var giftFinder = false;
var de=document.documentElement;if(de){de.className+=" js";}

if (FS.hostName.match(/relicbrand.com/)) {
	document.domain = 'relicbrand.com';
}
else if (FS.hostName.match(/fossil.com/)) {
	document.domain = 'fossil.com';
}

//Onload function in shell, loads on every page load.
$(document).ready(function(){
	$('#breadCrumb img').remove();

	$("#cartDropdown .eSpotDetailsGlobal").live("click", function(e) {
		e.preventDefault();
		$.colorbox({href: $(this).attr("href"), width:"867px", height:"622px", opacity: 0.3, iframe: true, title:'<p>'+FS.local_lang.labels.specialOffers+'</p>'+FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})});
	});

	var cartButtonWrapperEl = document.getElementById("cartButtonWrapper");
	if (cartButtonWrapperEl != null) {
		var shoppingBag_URL = FS.hostName.match(/(local|172\.30|127\.|assetstore-stage\.fossil\.com)/) ? '/AssetStore/Relic/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 (document.getElementById('cartButtonWrapper') != null && html.indexOf('<span id="global_bag_qty">0</span>') == -1 && html.indexOf('<!--  FSMiniCart.jsp  -->') != -1) {
					document.getElementById("cartButtonWrapper").innerHTML = html;

					FS.miniCart.bagEmpty = false;
					// cart dropdown
					$(".espotWrapper img").each( function() {
						if ($(this).complete) {
							FS.miniCart.imagesLoaded++;
						}

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

					$("#cartWrapper").hover(function () {
						FS.slideDown();
					}, function () {
						FS.slideUp();
					});
					
					
				}
				
				giftFinder = true;
			}
		});
	}

	// account dropdown
	$("#accountWrapper").hover(function () {
		FS.accountSlideDown();
	}, function () {
		FS.accountSlideUp();
	});

	//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;
		}
	}).bind('keyup', function(e) {
		if (e.keyCode === 13) {
			$(".headerSearchButt").click();
		}
	});

	$("#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())
				.css('background', '#DDBEBB')
				.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;
	});

	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() {
		$('#emailListSignupForm').html("<strong>"+FS.local_lang.labels.signupThankYou+"</strong>");
	}
	//End Footer Email Signup


	/* add this back in after launch? */
	/*
	$("a[href^='http://']").not("a[href^='http://www.relicbrand.com/']").click(function(){
	window.open(this.href,'external','location=yes,scrollbars=yes,menubar=yes,resizable=yes,toolbar=yes,status=yes,width=700,height=500,left='+(screen.availWidth/2-350)+',top='+(screen.availHeight/2-250)+'' );
	return false;
	});
	*/

	/* opens external links in a new window if they have class="external" defined */
	$("a.external").click(function(e) {
		e.preventDefault();
		window.open(this.href,'external','location=yes,scrollbars=yes,menubar=yes,resizable=yes,toolbar=yes,status=yes,width=700,height=500,left='+(screen.availWidth/2-350)+',top='+(screen.availHeight/2-250)+'' );
	});

	/*adds tooltips to image map <a> tags with alt attribute */
	$("area").each(function(){
		var mytip =	 $(this).attr("alt");
		if(mytip != '' && mytip != undefined){
			$(this).wTooltip({content: mytip});
		}
	});

	/* kill all menu /# links be default */
	$(".nav .sub").click(function() {
		return false;
	});

	var dropdownOffset = 28;
	var accountWidth=$('#accountButtonWrapper').width() + $('#headerAccWrap').width() + $('#cartWrapper').width();

	$('#accountDropdown').width(accountWidth + dropdownOffset);

	enableEspotModals();
});//end document ready function

//Global Functions
var enableEspotModals = function(){
	$('.freeGiftEspot').colorbox({width:"678px", height:"622px", opacity: 0.3, iframe: true, title:'<p>'+FS.local_lang.labels.giftWithPurchase+'</p>'+FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})});
	$('.eSpotDetailsGlobal').colorbox({width:"867px", height:"622px", opacity: 0.3, iframe: true, title:'<p>'+FS.local_lang.labels.specialOffers+'</p>'+FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})});
	$('.shipModal').colorbox({width:"620px", height:"622px", opacity: 0.3, iframe: true, title:'<p>'+FS.local_lang.labels.shippingMethod+'</p>'+FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})});
	$('.sizeGuideModal').colorbox({width:"721px", height:"712px", opacity: 0.3, iframe: true, title:'<p>'+FS.local_lang.labels.sizeChartFitGuide+'</p>'+FS.button({buttonName: "closeButton", buttonClass: "closeButton", buttonId: "closeButton", buttonLabel: FS.local_lang.labels.close})});
};

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( original, matchString ) {
	var matchIndex = original.indexOf( matchString );
	var returnString = original;
	if( matchIndex != -1 ) {
		returnString = returnString.substr(0, matchIndex);
	}
	return returnString;
};


//open modal if url parameter is present
loc = document.URL;
openCatalog = loc.substr(loc.indexOf("catModal") + 9, 1);
if(openCatalog == 't'){
	$('#modalOpen').trigger('click');
	console.log('test');
}


$(document).ready(function() {
	//hide breadcrumb if url parameter is present
	loc = document.URL;
	bcMenu = loc.substr(loc.indexOf("subCatBC") + 9, 1);
	if(bcMenu == 'n'){
		document.getElementById('breadCrumb').style.visibility="hidden";
		console.log('test');
	}
});
