var initialProductSku = ''; //needed for quick look pages
var quicklookIsOpen = false;
var docReadyFlag = false;
var windowReadyFlag = false;	
//Prevents IE from breaking on console entries.
if (!window.console) { console = {log: function() {}}; }

$.waypoints.settings.scrollThrottle = 10;

//Onload function in shell, loads on every page load.
$(document).ready(function(){
	FS.dom = {
		body: $('body'),
		page: $('#page'),
		content: $('#content'),
		footer: $('#footerContainer'),
		footerResponder: $('#footer'),
		columnContainer : $('#columnContainer'),
		primaryContent : $('#primaryContent'),
		secondaryContent: $('#secondaryContent'),
		menuToggle: $("#menuToggle"),
		leftNavContainer: $("#leftNavContainer"),
		contentPadding: $('#contentPadding')
	};

	//! this width should be sniffed according to platform/bowser
	FS.scrollbarWidth = 14;
  FS.slideDuration = 250;

  var cookieVal,
  		parentQ = new FS.queryString(),
  		parentCat = parentQ.params.departmentCategoryId,
  		footerContents;

	if ($('#footer').length > 0) {
	    footerContents = document.getElementById('footer').innerHTML;
	    document.getElementById('footer').innerHTML = "<div id='footerFix'>" + footerContents + "</div>";
	}

  if (typeof parentCat != 'undefined') {
    if($.cookie('FSGrid_' + parentCat)) {
      cookieVal = $.cookie('FSGrid_' + parentCat);
    } else {
      FS.cookieMonster('FSGrid_' + parentCat, '0');
      cookieVal = 0;
    }
  } else {
    cookieVal = '0';
  }

	FS.layoutSettings(cookieVal);

	$(window).FSresponder();

  $('html').removeClass('nojs');

	FS.dom.content.waypoint(function(event, direction) {
		var $this = $(this);
		var secondaryContent = FS.dom.secondaryContent;
		var secondaryHeight = FS.dom.secondaryContent.height();
		var viewPortHeight = window.innerHeight;
		var menuToggle = FS.dom.menuToggle;
		FS.respond.pageOffset = $this.offset().left;

        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
            //Use this area for special mobile handling.

        } else {
            if(typeof contentPageID == 'undefined') {
                if(!FS.dom.body.hasClass('account') && !FS.dom.body.hasClass('giftFinder') && FS.dom.secondaryContent.length) {
		            $this.parents('body').toggleClass('navPinned', direction === "down");
		            FS.respond.navPinned = (direction === "down") ? true : false;

		            if (FS.respond.menuShown === 1) {
			            if (direction === "down") {
			                FS.dom.secondaryContent.css({backgroundPosition: '0px 0px'});
			            }
			            else {
			              var leftSide = FS.dom.secondaryContent.length ? FS.dom.secondaryContent.offset().left : 0;
                    FS.dom.secondaryContent.css({backgroundPosition: -leftSide + 'px 0px'});
                    if($.browser.msie) {
                      $('#leftNav').css({zoom: '1'});
                    }
			            }

			            if ($(window).data("responder").hasSecondaryContent) {
				            $(window).FSresponder('footerCollision');
			            }
		            }
		            event.stopPropagation();
		        }
		    }
		}
	});

	FS.activatePlaceholders();

	if (FS.respond.menuToggleEnabled) {
		FS.dom.menuToggle.click(function(e) {
			e.stopPropagation();

			FS.respond.menuShown = FS.respond.menuShown === 1 ? 0 : 1;
			return false;
		});
	}


	// For Mantis #5034. Script removes alt text on mouseover so that it is present for SEO
	// but invisible to the user. Text is replaced on mouseout to avoid edge-case breaking.
	var titleHolder = '';
	$('a').live("mouseover", function(){
		titleHolder = $(this).attr('title');
		$(this).attr('title','');
	});
	$('a').live("mouseout", function(){
		$(this).attr('title', titleHolder);
	});
	
	//holiday handbag view all link redirect
	viewAllLeftNav(['FSSCWomensHandbags','FSSCMensBags', 'FSSCWomensWatchesCollections', 'FSSCWomensWatches', 'FSSCWomensHandbagsCollections', 'FSSCMensWatchesCollections', 'FSSCMensWatches', 'FSSCMensBagsCollections','FSSCWomensShopNewArrivals','FSSCMensShopNewArrivals','FSSCWomensApparel','FSSCWomensWallets','FSSCWomensFootwear','FSSCWomensJewelry','FSSCWomensAccessories','FSSCMensApparel','FSSCMensWallets','FSSCMensJewelry','FSSCMensFootwear','FSSCMensAccessories']);

	viewAllBreadCrumb(['Bag Styles', 'Taschenmodelle', 'Handbag Silhouettes','Bags' ,'Handbags','Watches', 'Watch Styles', 'Watch Collections', 'Bag Collections', 'Handbag Collections', 'Uhrenkollektionen', 'Uhren', 'Taschenkollektionen', 'New Arrivals', 'Neuheiten', 'Clothing', 'Wallets', 'Shoes', 'Jewellery', 'Accessories','Bekleidung','Geldbörsen','Schuhe','Schmuck','Accessoires','Nuovi Arrivi','Orologi','Borse','Piccola pelletteria','Portafogli','Calzature Donna','Gioielli','Accessori','Calzature Uomo','Nouveautés','Montres Par Collection','Montres Par Modèle','Sacs Par Collection','Sacs Par Silhouette','Petite Maroquinerie','Chaussures','Bijoux','Accessoires Autres','Vêtements','ウォッチ','ハンドバッグ','財布','ジュエリー','アクセサリー','メンズバッグ']);

	function viewAllBreadCrumb(title){
		for(var i =0; i<title.length; i++){
			$('#breadCrumb > li:eq(1) > a').each(function(){
				if($(this).find('span').size() > 0){
					crumbText = $.trim($(this).find('span').eq(0).html());
				}else{
					crumbText = $.trim($(this).html());
				}
				if( crumbText == title[i]){
					var breadCrumbLink = $(this);
					var oldURL = breadCrumbLink.attr('href');
					breadCrumbLink.attr('href', oldURL+'&page=viewall');
				}
			});
		}
	}
	function viewAllLeftNav(FSSC){
		for(var i =0; i<FSSC.length; i++){
			var leftNavLink = $('#'+FSSC[i]+' > a');
			var oldURL = leftNavLink.attr('href');
			leftNavLink.attr('href', oldURL+'&page=viewall');
		}
	}
//end holiday handbag view all link redirect
	
	//checks for deferred window load function, runs when appropriate flag set
	if(windowReadyFlag){
		windowReady();
	}else{
		docReadyFlag = true;
	}
	
});//end document ready function

//window.load function checks to make sure document ready has run. if not, sets flag and defers
//this is a workaround to support legacy until full modular implementation
$(window).load(function() {
	if(docReadyFlag){
		windowReady();
	}else{
		windowReadyFlag = true;
	}
});
function windowReady(){
	if (FS.dom.secondaryContent && FS.dom.secondaryContent.length) {
		$(window).FSresponder('updateNav');
	}

	$(".eSpotDetailsGlobal").live("click", function(e) {
		e.preventDefault();
		$.colorbox({href: $(this).attr("href"), opacity: 0, photo: true, innerWidth: 387, innerHeight: 182}, function() {
			$("#cboxLoadedContent .cboxPhoto").click(function(e) {
				$.colorbox.close();
			});
		});
	});

	/* $("#storelocator a").colorbox({iframe:true, width:"880px", scrolling:false, innerHeight:"600px", title:'<p>'+FS.local_lang.labels.storeLocator+'</p>' + FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})}); */

	// Shopping Cart
	var shoppingCart = $("#shoppingCart");
	if (shoppingCart.length > 0 && !FS.isNonCommerce ) {
		var shoppingBag_URL = FS.isLocal ? '/AssetStore/Fossil/en_US/shoppingBagContents.php' : '/webapp/wcs/stores/servlet/FSAJAXService?'+FS.params({service: 'getMiniCart', URL: 'MiniCartView'});

		$.ajax({
			url: shoppingBag_URL,
			cache: false,
			success: function(html) {
				if (html.indexOf('<!--  FSMiniCart.jsp  -->') != -1) {
					shoppingCart[0].innerHTML = html;
					$('#cartButton .sbag0').attr('title', FS.local_lang.labels.shoppingBagTitle);
					FS.miniCart.bagEmpty = false;
					FS.dom.cartDropdown = $("#cartDropdown");

					// cart dropdown
					$("div.espot img").each(function() {
						if ($(this).complete) {
							FS.miniCart.imagesLoaded++;
						}

						if (FS.miniCart.numCartImages <= FS.miniCart.imagesLoaded) {
							FS.miniCart.cartHeight(FS.dom.cartDropdown.height());
						}
					});

					var cartTall;
					shoppingCart.each(function() {
						FS.dom.cartDropdown.show();
						cartTall = FS.dom.cartDropdown.height();
						FS.dom.cartDropdown.hide();
					});

					var slideConfig = {
						over: function() {
							cartChangeHeight = FS.miniCart.cartHeight() > 0 ? FS.miniCart.cartHeight() : null;
							if (!FS.miniCart.isDropdownAnimated) {
								FS.miniCart.isDropdownAnimated = true;
								$(this).children("#cartDropdown").height(0).show().animate({
										height: cartChangeHeight ? cartChangeHeight: cartTall
									},
									200
								);
							}
						},
						timeout: 200,
						out: function() {
							$(this).children("#cartDropdown").height(cartTall).animate({
									height: 0
								},
								200,
								function() {
									FS.miniCart.isDropdownAnimated = false;
									$(this).hide();
								}
							);
						}
					};

					shoppingCart.hoverIntent(slideConfig);
				}

				$('body').trigger('cartLoaded');
			}
		});
	}

	// Locale dropdown
	var currentLocale = $('.currentLocale').html();
	$('#locale > h4').append('<span> : ' + currentLocale + '</span>');

	// Header Search Box
	$('#headerSearchInput, #bannerSearch').val(FS.local_lang.labels.searchKeywordItem).focus(function() {
		if (this.value==FS.local_lang.labels.searchKeywordItem) {
			this.value='';
		}
	}).bind('blur',function() {
		if (this.value=='') {
			this.value=FS.local_lang.labels.searchKeywordItem;
		}
	});

	$('input.headerSearchButt').bind('click', function() {
		if($('#headerSearchInput').val() == FS.local_lang.labels.searchKeywordItem) {
			$('#headerSearchInput').val('');
		}
	});

	$("#headerSearchForm").FSvalidate();
	$("#headerSearchInput").FSvalidate().addRule({'name':'minLength', 'message': FS.local_lang.errors.searchMinimumChars, 'options' : {'minLength' : 3}});

	// Setup default validation
	$('.validate').FSvalidate();

	//Footer Email Signup
	$("#emailListSignupForm").FSvalidate({
		validateOnBlur: true,
		validateOnKeyup: false,
		validateOnChange: false,
		showValidation: function(obj, settings){},
		errorStyle: {},
		errorHandler: function(obj, settings) {
			//set error message
			$(obj).data('email', $(obj).val())
				.val($(obj).data('errorMessage'))
				.unbind('focus')
				.focus( function() {
					var currentValue = $(this).data('email');
					if( currentValue && (currentValue!=FS.local_lang.errors.enterEmail) && (currentValue!=FS.local_lang.errors.validEmail) ) {
						$(this).val($(this).data('email'));
					}
					else {
						$(this).val('');
					}
				});
		}
	});

	$('#signupListEmail').val(FS.local_lang.errors.enterEmail)
		.addRule({'name':'required', 'message':FS.local_lang.errors.enterEmail})
		.addRule({'name':'email', 'message':FS.local_lang.errors.validEmail})
		.focus( function(){
			if(this.value==FS.local_lang.errors.enterEmail || this.value==FS.local_lang.errors.validEmail) {
				this.value='';
			}
		})
		.blur( function(){
			if(this.value=='')
				this.value=FS.local_lang.errors.enterEmail;
		});

	// email signup footer
	$("#signupSubmit").bind('click', function(e) {
		if ($('#emailListSignupForm').valid()) {
			registerEmailAddress();
		}
		return false;
	});

	/* opens external links in a new window if they have class="external" defined */
	$("a.external").click(function() {
		$(this).attr('target', '_blank');
	});

	//Global fix for colorbox close buttons
	$('#cboxTitle button').live('click', function() {
		$.colorbox.close();
	});

	$('#closeButton a').live('click', function() {
		$.colorbox.close();
	});
	// Make our flyovers usable
	var config = {
		over: function() {
			var $this = $(this);
			if ($this.attr('id') == 'search' && $('.threshold0').length || $('.threshold1').length) {
				$this.children('form').fadeIn(200);
			}

			if ($this.attr('id') == 'menuCatalog' || $this.attr('class') == 'navChildren') {
				$this.children('ul').fadeIn(200);
			}
			if($this.attr('id') == 'locale'){
				$this.children('#localePicker').fadeIn(200);
			}

		},
		timeout: 500,
		out: function() {
			var $this = $(this);
			if ($this.attr('id') == 'search' && $('.threshold0').length || $('.threshold1').length) {
				$this.children('form').animate({opacity: '.1'}, 200, function() {
				    $this.children('form').attr('style', '');
				});
			}

			if ($this.attr('id') == 'menuCatalog' || $this.attr('class') == 'navChildren') {
				$this.children('ul').fadeOut(200);
			}
			if($this.attr('id') == 'locale'){
				$this.children('#localePicker').fadeOut(200);
			}
		}
	};

	$("#search, #menuCatalog, #locale, .navChildren").hoverIntent( config );

	//reskin rollover image swap
	var reskinRollover,imageDomInsert,imageDomInsertSrc
	$('.reskinRollover').each(function(){
		imageDomInsertSrc = $(this).attr('src');
		imageDomInsertSrc = imageDomInsertSrc.replace('Off','On');
		imageDomInsert = $('<img />').attr('src', imageDomInsertSrc);
	});
	$('body').delegate('.reskinRollover','mouseover',function(){
		reskinRollover = $(this).attr('src');
		reskinRollover = reskinRollover.replace('Off','On');
		$(this).attr('src',reskinRollover);
	});
	$('body').delegate('.reskinRollover','mouseout',function(){
		reskinRollover = $(this).attr('src');
		reskinRollover = reskinRollover.replace('On','Off');
		$(this).attr('src',reskinRollover);
		reskinRollover,imageDomInsert = "";
	});
//end reskin rollover image swap

	//img map resizer
	FS.dom.content.map_resizer();

	if(FS.dom.secondaryContent.length) {
	    FS.backgroundNavFix();
	};

} // End WindowReady

function registerEmailAddress() {
	$.ajax({
		url:'/webapp/wcs/stores/servlet/EmailLookup',
		type: 'post',
		data: $('#emailListSignupForm').serialize(),
		dataType: 'text',
		cache:false,
		success: function(html){
			registerEmailResponse();
			return false;
		},
		error: function() {
			registerEmailResponse();
			return false;
		}
	});
	return false;
}

function registerEmailResponse() {
	if($('#footerSec2 .email_input').length) {
		$('#footerSec2 .email_input').html("<strong>"+FS.local_lang.labels.signupThankYou+"</strong>");
	} else {
		$('#emailListSignupForm').empty().append('<strong>'+FS.local_lang.labels.signupThankYou+'</strong>')
	}
}

//Giving placeholder support to non-safari browsers
FS.activatePlaceholders = function() {
	var detect = navigator.userAgent.toLowerCase();
	if (detect.indexOf("safari") > 0) return false;
	var inputs = document.getElementsByTagName("input");
	for (var i=0;i<inputs.length;i++) {
		if (inputs[i].getAttribute("type") == "text" || inputs[i].getAttribute("type") == "email" || inputs[i].getAttribute("type") == "password") {
			if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) {
				inputs[i].value = inputs[i].getAttribute("placeholder");
				inputs[i].onclick = function() {
					if (this.value == this.getAttribute("placeholder")) {
						this.value = "";
					}
					return false;
				}

				inputs[i].onblur = function() {
					if (this.value.length < 1) {
						this.value = this.getAttribute("placeholder");
					}
				}
			}
		}
	}
};

FS.cookieMonster = function(cookieName,gridSize,removeCookie) {
	var cookieItems;

	if (cookieName) {
		var cookie = $.cookie(cookieName);

		if (removeCookie) {
			$.cookie(cookieName, null);
		}
		else {
			if ($.cookie(cookieName)) {
				cookieItems = cookie.split(/,/);

				if (gridSize == '0' || gridSize == '1' || gridSize == '2') {
					cookieItems[0] = gridSize;
				}

				$.cookie(cookieName, cookieItems.join(','), {path: '/'});
			}
			else {
				cookieItems = new Array();

				if (gridSize == '0' || gridSize == '1' || gridSize == '2') {
					cookieItems.push(gridSize);
				}

				$.cookie(cookieName, cookieItems.join(','), {path: '/'});
			}
		}
	}
	else {
		if(console) {
			console.log('No Cookie Name Defined - Function Skipped');
		}
	}
};

FS.layoutSettings = function(gridSize) {
  gridSize = typeof gridSize == "undefined" ? '0' : parseInt(gridSize);
  if (FS.dom.body.hasClass('searchResults')) {
    var curSizeActive = new FS.queryString();
    if(typeof curSizeActive.params['template'] != 'undefined') {
      if(curSizeActive.params['template'] == 'default') {
        gridSize = '0';
      } else {
        gridSize = '1';
      }
    }
  }
	if(FS.defaultSize != undefined && !FS.dom.body.hasClass('subCat')){
		gridSize = FS.defaultSize;
	}
	var menuState = FS.dom.secondaryContent.length ? 1 : 0; // 0 = closed | 1 = open
	FS.respond.menuShown = menuState;

  if(menuState == 1) {
    var menuWidth = FS.respond.leftNavWidth();

    FS.dom.primaryContent.css({marginLeft : FS.respond.leftNavWidth()});
		FS.dom.secondaryContent.css({width : FS.respond.leftNavWidth()});
  } else {
    FS.dom.primaryContent.css({marginLeft : 0, width: '100%'});

  }

	if (gridSize >= 0) {
    $('#imgResize a').eq(gridSize).addClass("active").siblings().removeClass('active');
		FS.dom.body.addClass('gridSize'+gridSize);
		FS.currentSizeIndex = gridSize;
	}
};

FS.backgroundNavFix = function() {
    var leftSide = FS.dom.secondaryContent.offset().left;
    FS.dom.secondaryContent.css({backgroundPosition: -leftSide + 'px 0px'});
}

function addScript(source){
	var s = document.createElement("script");
	s.type = "text/javascript";
	s.src = source;
	$("head").append(s);
};

function getParameterByName(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (results == null) {
  	return "";
  }
  else {
  	return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}

String.prototype.substringBefore = function(matchString) {
	var matchIndex = this.indexOf(matchString);
	var returnString = '';
	if (matchIndex != -1) {
		returnString = this.substr(0, matchIndex);
	}
	return returnString;
};

String.prototype.substringAfter = function(matchString) {
	var matchIndex = this.indexOf(matchString);
	var returnString = '';
	if (matchIndex != -1) {
		returnString = this.substr(matchIndex + matchString.length, this.length);
	}

	return returnString; //changed to nothing since no match found - for searchResults build param
};

String.prototype.substringBeforeLast = function(matchString) {
	var matchIndex = this.lastIndexOf(matchString);
	var returnString = '';
	if (matchIndex != -1) {
		returnString = this.substr(0, matchIndex);
	}
	return returnString;
};

String.prototype.substringAfterLast = function(matchString) {
	var matchIndex = this.lastIndexOf(matchString);
	var returnString = '';
	if (matchIndex != -1) {
		returnString = this.substr(matchIndex + matchString.length, this.length);
	}
	return returnString;
};

String.prototype.replaceAll = function(replace, with_this) {
	return this.replace(new RegExp(replace, 'g'),with_this);
}

