﻿$(document).ready(function($){

	jQuery.webpurify.init('2a0beeff449081f83908bbc84e126c0a');

	var disableTheButton = false;

	/**************************************************
		handles the mini cart flyout
		stop prop to prevent the body click call below from firing
	**************************************************/
	initBindings();

	/**************************************************
		clears out the search box default text
		so form isnt submited with submit
		below section provides focus clearing
	**************************************************/

	$("#topSearchForm").submit(function() {
		schval = $("#topSearch").val();
		if(schval == "SEARCH") {
			$("#topSearch").val("");
		}
	});

	/**************************************************
	 	generic script to
		clear out the default value from form field
		when it is meant to be a label on focus
	**************************************************/
	$(".valueLabel").focus( function(){
		lblValue = $(this).val();
		ttlValue = $(this).attr("title");
		if(lblValue == ttlValue) {
			$(this).val("");
		}
	});

	$(".valueLabel").blur(function() {
		lblValue = $(this).val();
		ttlValue = $(this).attr("title");
		if(lblValue == "") {
			$(this).val(ttlValue);
		}
	});

	$("input, select").live("keyup change", function() {
		formSubmitDisabled();
	});

	$('#atg_store_checkoutLoginForm input#emailAddress, #atg_store_checkoutLoginForm input#password').live("keyup change", function() {
		signinSubmitDisabled();
	});

	$("#updateButtone").attr("disabled","true").css("opacity","0.4");

	/*
	if ($('div.regUsers:visible') != true) {
		$('.cc-selection').css('margin-bottom','270px');
	}

	$('#creditCard_creditCardType').change(function(){
		$('.cc-selection').css('margin-bottom','0');
	});
	*/



	/**************************************************
	 	generic script to
		loop through all href tags and for any that are
		marked rel=external, make those open in a new
		windows.  this allows us to be w3c compliant
		xhtml since you can no longer use the target attr
		-- added _blank to rel option
	**************************************************/
	$("a[rel$='external'], a[rel$='_blank']").click(function(){
		this.target = "_blank";
	});

	/**************************************************
		add to cart button ajax calls
		the actual ajax part has been moved to a function  to allow other buttons to support it without rewriting it
	**************************************************/
	$(".addToCartButton").live("click", function(e){
		addToCartAjax($(this));
		return false;
	});

	$(".addToCartLink").live("click", function(e){
		addToCartLinkAjax($(this).attr("href"));
		return false;
	});

	$(".addToWishListButton").live("click", function(e){
		addToWishListAjax($(this).attr("href"));
		$("#dialog").dialog("destroy");
		e.preventDefault();
		return false;
	});

	/**************************************************
		ajax add to cart - hidden inputs
	**************************************************/
	function addToCartAjax(obj) {
		url_catalog_ref_id = $("#catalogRefIds").val();
		url_product_id = $("#productId").val();
		url_quantity = $("#quantity").val();
		dcs_ci_catalogKey = $("#locale").val();

		$.ajax( {
        	url: '/store/common/includes/miniCartHolder.jsp',
        	data:"dcs_action=additemtocart&url_catalog_ref_id="+url_catalog_ref_id+"&url_product_id="+url_product_id+"&url_quantity="+url_quantity+"&dcs_ci_catalogKey="+dcs_ci_catalogKey,
            success: function(html) {
                $('#miniCartHolder').empty().append(html);
                //initBindings();
                miniCartDirection("down");
                $('html, body').animate({scrollTop:0}, 'slow');
            }
        });
	}

	
	/**************************************************
		ajax add to cart - passes the url as a get
	**************************************************/
	function addToCartLinkAjax(obj) {
		
		$.get(obj,
			function(data){
				$.ajax( {
		        	url: '/store/common/includes/miniCartHolder.jsp',
		            success: function(html) {
		                $('#miniCartHolder').empty().append(html);
		                //initBindings();
		                miniCartDirection("down");
		                $('html, body').animate({scrollTop:0}, 'slow');
		            }
		        });
			}
		);
	
	}
	
	
	/**************************************************
		ajax add to wishlist
	**************************************************/
	function addToWishListAjax(obj) {
		var arr = obj.split("&");

		for(i=0; i < arr.length; i++) {
			if(arr[i].indexOf("skuId") >= 0) {
				subArr = arr[i].split("=");
				skuId = subArr[1];
				if(window.console && window.console.firebug) {
					console.debug(subArr[1]);
				}
			}
			if(arr[i].indexOf("productId") >= 0) {
				subArr = arr[i].split("=");
				productId = subArr[1];
				if(window.console && window.console.firebug) {
					console.debug(subArr[1]);
				}
			}
			if(arr[i].indexOf("giftlistId") >= 0) {
				subArr = arr[i].split("=");
				giftlistId = subArr[1];
				if(window.console && window.console.firebug) {
					console.debug(subArr[1]);
				}
			}
			if(arr[i].indexOf("quantity") >= 0) {
				subArr = arr[i].split("=");
				quantity = subArr[1];
				if(window.console && window.console.firebug) {
					console.debug(subArr[1]);
				}
			}
		}

		dataString = 'skuId='+ skuId + '&productId=' + productId + '&giftlistId=' + giftlistId + '&quantity=' + quantity;

		$.ajax( {
        	url: '/store/common/wishlist.jsp',
        	data: dataString,
        	success: function(html) {
				$('#miniWishListHolder').empty().load("/store/account/wishlists/miniWishlist.jsp", function(){
					miniWishDirection("down");
				});
                //initBindings();
                $('html, body').animate({scrollTop:0}, 'slow');

                return false;
            }
        });

	}

	/**************************************************
		Changes Wallpaper from choices in footer
	**************************************************/

	/*
	$(".wallpaper").click( function(e) {
		bg = $(this).children("a").children("img").attr("src");
		$("body").css("background-image","url("+ bg +")");
		e.preventDefault();
	});
	*/

	/**************************************************
	 	generic script to
	 	Change the button image or any image on mouseover
	 	by adding "_over" suffix before the .png
		can be modified to work on any file type by adding
		to the split code
	**************************************************/
	$('.rolloverThis').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			src = $(this).attr("src");
			if($(this).attr("disabled") != true) {
				if(src.indexOf("_over") == -1) {
					var temp = new Array();
					temp = src.split('.png');
					var onState = temp[0] + "_over.png";
					$(this).attr("src", onState);
				}
			}
		} else {
			if($(this).attr("disabled") != true) {
				src = $(this).attr("src");
				var offState = src.replace("_over", "");
				$(this).attr("src", offState);
			}
		}
	});

	/**************************************************
		Modal windows
		-jquery ui dialog (styles handled in jquery ui styles)
		-colorbox plugin (styles handled in colorbox.css)
		both methods rely on the actual href of the link
		to determine the location of the modal window
		contents to load via ajax
	**************************************************/

	/*  colorbox code  */
	/*
	$("#locationText").click(function(e) {
		$(this).colorbox({
			href:this.href,
			transition:"none",
			opacity:0.35
		}, function(){
			$(this).colorbox.resize();
		});
		e.preventDefault();
	});
	*/

	$(".modalClose").live("click", function(e) {
		//console.debug('clicked modal closer');
		$.colorbox.close();
		parent.$.colorbox.close();
	});

	$(".modal").live("click", function(e) {
		$(this).colorbox({
			href:this.href,
			transition:"none",
			opacity:0.35
		}, function(){
			$(this).colorbox.resize();
		});
		e.preventDefault();
	});

	$(".modalIframe").live("click", function(e) {
		$(this).colorbox({
			iframe:true,
			transition:"none",
			width:"692px",
			height:"415px",
			opacity:0.35
		});
		e.preventDefault();
	});

	// jquery dialog code
	/*
	$( "#welcomeMessageText" ).click(function(e) {
		var url = this.href;
		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			open: function () {
				$(this).load(url, function() {
					$(this).dialog('option', 'position', 'center');
				});
			},
			closeOnEscape: true,
			width: "auto",
			modal: true
		});
		e.preventDefault();
	});
	*/

	$(".ui-widget-overlay, .dialogClose").live("click", function(e) {
		$("#dialog").dialog("destroy");
		e.preventDefault();
	});

	$(".dialog").live("click", function(e) {
		var url = this.href;
		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			closeOnEscape: true,
			width: "auto",
			modal: false
		});
		$("#dialog").load(url, function() {
			$(this).dialog('option', 'position', 'center');
			$(this).dialog("open");
		});
		e.preventDefault();
	});

	$(".dialogModal").live("click", function(e) {
		var url = this.href;
		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			closeOnEscape: true,
			autoOpen: false,
			width: "auto",
			height: "auto",
			modal: true
		});
		$("#dialog").load(url, function() {
			$(this).dialog('option', 'position', 'center');
			$(this).dialog("open");
			var script = 'https://s7.addthis.com/js/250/addthis_widget.js#pubid=claires&async=1';
			if (window.addthis){
			    window.addthis = null;
			}
			$.getScript( script, function(){
				initAddThis();
			} );

		});
		e.preventDefault();
	});

	/**************************************************
		browser detection modal
	**************************************************/

	// Requirement will be revisited post-launch
	/**
		var ua = $.browser;

		var userAgent = navigator.userAgent.toLowerCase();

		// Is this a version of Mozilla?
		if(ua.mozilla){
			//Is it Firefox?
			if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
				userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
				userAgent = userAgent.substring(0,userAgent.indexOf('.'));
				version = userAgent;
				//alert(version);
			}else{
				// If not then it must be another Mozilla
				version = ua.version;
			}
		}
		if (ua.msie && ua.version < "8" ||
		   ua.webkit && ua.version < "11" ||
		   ua.mozilla && version < "3.6")
		{
			$("#dialog").dialog({
				open: function () {
					$(this).load("/store/modals/browser-detect.jsp", function() {
						$(this).dialog('option', 'position', 'center');
					});
				},
				closeOnEscape: true,
				width: "auto",
				modal: false
			});
		}
	**/

	/**************************************************
		checkout scripts
		-shipping method selections
	**************************************************/
	$(".shippingBox").click( function(e) {
		$(".shippingBox").each( function() {
			$(this).removeClass("shippingBoxSelected");
		});
		$(this).addClass("shippingBoxSelected");
		var label = $(this).find("label").attr("for");
		$("#"+label).click();
		e.preventDefault();
	});
	/************************************************
	 * Onload shipping selector
	 */
	$("input.shippingMethodRadio").each(function(index) {
		var tfrad = $(this).attr('checked');
	    if(tfrad==true){
	    	var radVal = $(this).val();
	    	var selectedRad;
	    	switch (radVal)
	    	{
	    	case 'Standard':
	    	  selectedRad=0;
	    	  break;
	    	case 'Two Day':
	    	  selectedRad=1;
	    	  break;
	    	case 'Overnight':
	    	  selectedRad=2;
	    	  break;
	    	default:
	    		selectedRad=1;
	    	}
	    	//alert(selectedRad);
	    	$(".shippingBox").each( function(i) {
				if(i == selectedRad){
					$(this).addClass("shippingBoxSelected");
				}

			});
	    }
	  });

	/***************************************************
	 * Checkout GiftCart turn on update button
	 */
	if($('ul#giftOptions').length){
		$("#updateUserCartButton").attr('disabled','true');
		//$("#giftmessage").attr('disabled','true');


		$('#atg_store_addWrap').bind('click', function() {
				$("#updateUserCartButton").attr('disabled','false').attr("src","../images/buttons/update-cart-button.png");
		});
		$('#addGiftReceiptCB').bind('click', function() {
				$("#updateUserCartButton").attr('disabled','false').attr("src","../images/buttons/update-cart-button.png");
		});
		$('#atg_store_addNote').bind('click', function() {
				$("#updateUserCartButton").attr('disabled','false').attr("src","../images/buttons/update-cart-button.png");
		});
		$('#atg_store_promotionCodeInput').bind('click', function() {
				$("#updateUserCartButton").attr('disabled','false').attr("src","../images/buttons/update-cart-button.png");
		});

	}
	/*************************************************
	 	FAKE DROPDOWN USES LINKS INSTEAD
	 ************************************************/
	$("#productDetailWishList").live("click", function(e) {

		$("#productDetailWishListDropdownValues").toggle();
		$("#dialog").css("height", 500);

	});

	$("#productDetailWishListDropdownValues a").live("click", function(e){
		if(!$(this).hasClass("addToWishListButton")){
			location.href=$(this).attr("href");
		}
	});

	$(".productDetailWishList").each( function(e) {
		$(this).click( function(f){
			$(f.target).next(".productDetailWishListDropdownValues").toggle();
			//return false;
		});
	});


	$('body').not("#productDetailWishList").click( function(e) {
		//console.debug('hey');
		$("#productDetailWishListDropdownValues").hide();
		$("#dialog").css("height", "auto");
	});


	/*************************************************
	 	size dropdown submits a different form
	 ************************************************/
	$("#productDetailSize").change( function(e) {
		var action = $("#skuSelectionForm").attr("action");
		var color = $(document).getUrlParam("color");
		var quantity = $(document).getUrlParam("quantity");
		if (quantity==null) {
			quantity = 1;
		}
		var size = $("#productDetailSize").val();

		$("#skuSelectionForm").attr("action", action + "&color=" + color + "&quantity=" + quantity + "&size=" + size);
		$("#skuSelectionForm").submit();
	});

	$("#productDetailQuantity").change( function(e) {
		var action = $("#skuSelectionForm").attr("action");
		var color = $(document).getUrlParam("color");
		var quantity = $("#productDetailQuantity").val();
		var size = $(document).getUrlParam("size");

		$("#skuSelectionForm").attr("action", action + "&color=" + color + "&quantity=" + quantity + "&size=" + size);
		$("#skuSelectionForm").submit();
	})


	$('body').not("#productDetailWishList").click( function(e) {
		$("#productDetailWishListDropdownValues").hide();
	});

	$("#parentEmailSubmit").click(function(){

		var userDOB = $("#dobYear").val()+'-'+$("#dobMonth").val()+'-'+$("#dobDay").val();
		var d=new Date();
		var todaysDate = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();

		if((doAge(userDOB,todaysDate))< 13){

			if ($(".parentsEmail").is(":hidden")) {
				$(".parentsEmail").fadeIn('fast');
				return false;
			} else {
				return true;
			}
		}

	});

	$("#BrowseFormHandlerSearch_1").css("visibility", "hidden");

	$("#BrowseFormHandlerSearch_2").css("visibility", "hidden");

	$("#categorySortBy_1").change( function(e){
		$("#BrowseFormHandlerSearch_1").trigger("click");
	});

	$("#categoryRefineBy_1").change( function(){
		$("#BrowseFormHandlerSearch_1").trigger("click");
	});

	$("#categoryViewNumber_1").change( function(){
		$("#BrowseFormHandlerSearch_1").trigger("click");
	});

	$("#categorySortBy_2").change( function(){
		$("#BrowseFormHandlerSearch_2").trigger("click");
	});

	$("#categoryRefineBy_2").change( function(){
		$("#BrowseFormHandlerSearch_2").trigger("click");
	});

	$("#categoryViewNumber_2").change( function(){
		$("#BrowseFormHandlerSearch_2").trigger("click");
	});


	// Comment login popup
	$("#productCommentSignIn").css("display", "none");

	$("#productCommentSignInLink").hover(function(e) {
		$("#productCommentSignIn").show();
	});

	$("#productCommentSignIn").mouseup(function() {
		return false;
	});

	$(document).mouseup(function() {
		if($("#productCommentSignIn:visible")) {
			$("#productCommentSignIn").hide();
		}
	});

	/*************************************************
	 * quick view specific scripts
	 ************************************************/

	$(".quickViewColor").live("click", function(e) {
		url = encodeURI($(this).attr("href"));
		//console.debug("clickcing coolor link to " + url);

		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			open: function () {
				$(this).load(url, function() {
					$(this).dialog('option', 'position', 'center');
					$(this).dialog("open");
					var script = 'https://s7.addthis.com/js/250/addthis_widget.js#pubid=claires&async=1';
					if (window.addthis){
					    window.addthis = null;
					}
					$.getScript( script, function(){
						initAddThis();
					} );
				});
			},
			closeOnEscape: true,
			width: "auto",
			modal: true
		});

		e.preventDefault();
	});

	$('.quickViewQuantity, .quickViewSize').live("change", function(e) {

		form = $(this).closest("form");

		action = form.attr("action");

		url = action + "?" + form.serialize();

		//console.debug("clickcing form selects " + url);

		$("#dialog").dialog("destroy");
		$("#dialog").dialog({
			open: function () {
				$(this).load(url, function() {
					$(this).dialog('option', 'position', 'center');
					$(this).dialog("open");
					var script = 'https://s7.addthis.com/js/250/addthis_widget.js#pubid=claires&async=1';
					if (window.addthis){
					    window.addthis = null;
					}
					$.getScript( script, function(){
						initAddThis();
					} );
				});
			},
			closeOnEscape: true,
			width: "auto",
			modal: true
		});

		e.preventDefault();
	});

	/*************************************************
	 * 	General Privacy Page script
	 * 	toggles visibility of "more details" links
	 ************************************************/

	var $contentDivs = $('div.slideContent');
	var $toggleLinks = $('p.moreDetails');

	$('p.moreDetails').click(function() {

		var $toggleLink = $(this);
		var $content = $toggleLink.next();

		if($content.is(':hidden')) {
		    $contentDivs.hide();
		    $toggleLinks.html('More Details');
		    $content.slideDown('fast');
		    $toggleLink.html('Hide Details');
		}
		else {
		    $content.slideUp('fast');
		    $toggleLink.html('More Details');
		}
	});


	if($('div.prefsLeft').length){
		//populateCountry('${countryVal}');
		  //populateState(document.getElementById("country"))
		  //populateStateforCountry('${countryVal}','${stateVal}');
	}



	/*************************************************
	 * 	Carousel items
	 ************************************************/

	$("#productViewedItemsScroller").carouFredSel({
		auto: false,
		prev: ".leftArrow",
		next: ".rightArrow",
		padding: 0,
		width: 260
	});


	/*************************************************
	 * 	Category Quick View
	 ************************************************/

	$(".categoryItem").live("mouseover", function(e) {
		$(this).find(".catProdQuick").show();
	});
	$(".categoryItem").live("mouseout", function(e) {
		$(this).find(".catProdQuick").hide();
	});

	/*************************************************
	 * 	Category Sort and Refine
	 ************************************************/

	$("#categorySortBy, #categoryRefineBy, #categoryViewNumber").change( function() {
		$(this).closest('form').submit();
	});

	/****************************************************
	 * 	Populate Saved Address field in paymentInfo.jsp *
	 ****************************************************/
	$('#shippingAddress').change(function() {
		var selectIndex = $('#shippingAddress option:selected').attr("class");
		selectIndex = '#ship'+selectIndex+'-';
		$('#streetAddress').val($(selectIndex+'address1').val());
		//NO SECONDARY ADDRESS BEING COPIED TO INVISIBLE FIELDS
		/*$('#shippingAddress_address2').val(selectIndex+'address2');*/
		$('#shippingAddress_country').val($(selectIndex+'country').val());
		$('#shippingAddress_city').val($(selectIndex+'city').val());
		$('#shippingAddress_state').val($(selectIndex+'state').val());
		$('#shippingAddress_postalCode').val($(selectIndex+'postalCode').val());
		$('#shippingAddress_phoneNumber').val($(selectIndex+'phoneNumber').val());
	});

	/****************************************************
	 * 	Populate Saved Address field in shipping.jsp *
	 ****************************************************/

	$('#shippingAddressShipping').change(function() {
		doSaS();
	});

	/****************************************************
	 * 	Populate Saved CC & Address field in billing.jsp *
	 ****************************************************/
	$('#creditCard').change(function() {
		doBcC();
	});

	$('#billingAddress').change(function() {
		doBa();
	});


	$('.errorFieldMessage').each(function() {
		if($(this).html() != '') {

		    // fix some strange rendering issue with error text not clearing in some cases
			$(this).addClass('clearRight');
			// highlight error fields.
			$(this).siblings('.required').addClass('errorMessageField', 500);
			$(this).siblings('.gc-required').addClass('errorMessageField', 500);
			$('#errorMessageBox').removeClass('hidden').css({'margin-bottom' : '20px'});
		}
	});

	$(".addNewGiftCard").click(function() {
		$(".giftCardFields").show();
	});

	$("#creditCard_creditCardType").change(function() {
		$(".regUsers").show();
	});


	/****************************************************
	 * 	original scripts
	 ****************************************************/

	/******************************************
	 * INit accordian for earpiercing page
	 */
	if(jQuery("#lista").length!=0){
		  jQuery('#lista').accordion({
				    header: '.header',
					event: 'click',
					autoHeight: false,
					alwaysOpen:false,
					active:false
				});
		  $("div.accordian_item span.header a").click(function () {
			    $('span.ui-state-active a').html('More Details');
			    var $toggleLink = $(this);
				var $content = $toggleLink.next();

				if($content.is(':hidden')) {
				    $toggleLinks.html('More Details');
				}
				else {

				    $toggleLink.html('Hide Details');
				}
		    });

	}
	if(jQuery("#earPiercingVedio").length!=0){
		  jQuery("#earPiercingVedio").click(function(){
				//position with css
				positionPopup(100, 200,546,355);
				//load popup
				loadPopup();
				});
	}

	/******************************
	*   wall paper change
	******************************/


	var allwallpaper = jQuery(".wallpaper");
	jQuery.each(allwallpaper , function(i, val){
	        jQuery(this).mouseover( function(){
	                jQuery(this).css("cursor","pointer");

	        });

	        jQuery(this).click( function(e){
                var kidscookie = "kwp";
                var maincookie = "mwp";
                var options = { path: '/', expires: 365 };

                var newBgPath = jQuery(this).find('img').attr('src');
                if (jQuery('.kidsbody').length!=0) {
                        jQuery.cookie(kidscookie, "url("+ newBgPath +")", options );
                } else {
                        jQuery.cookie(maincookie, "url("+ newBgPath +")", options );
                }
                jQuery("body").css("background-image","url("+ newBgPath +")");
                e.preventDefault();

        })

	})




	/**************************************************
	sign in menu
	 **************************************************/
	jQuery(".signin").hover(function(e) {
		if(jQuery(e.target).parent("a.signin").length==0) {
			e.preventDefault();
			jQuery("fieldset#signin_menu").show();
		}
    });
	jQuery(".signin").click(function(e) {
		e.preventDefault();
		jQuery("fieldset#signin_menu").toggle();
	});
	jQuery("fieldset#signin_menu").mouseup(function() {
        return false
    });
	jQuery(document).mouseup(function(e) {
	        if(jQuery(e.target).parent("a.signin").length==0) {
	        	jQuery(".signin").removeClass("menu-open");
	        	jQuery("fieldset#signin_menu").hide();
	        }
	 });
	jQuery("#main").mouseenter(function() {
		jQuery(".signin").removeClass("menu-open");
		jQuery("fieldset#signin_menu").hide();
    });

	//SIGN IN FOR COMMENTS
	jQuery(".signinComments").hover(function(e) {
		if(jQuery(e.target).parent("a.signinComments").length==0) {
			e.preventDefault();
			jQuery("fieldset#signin_menu2").show();
		}
    });
	jQuery(".signinComments").click(function(e) {
		e.preventDefault();
		jQuery("fieldset#signin_menu2").toggle();

	});
	jQuery("fieldset#signin_menu2").mouseup(function() {
        return false
    });
	jQuery(document).mouseup(function(e) {
	        if(jQuery(e.target).parent("a.signinComments").length==0) {
	        	jQuery(".signinComments").removeClass("menu-open");
	        	jQuery("fieldset#signin_menu2").hide();
	        }
	 });


	/**************************************************
		init left nav tree views
	 **************************************************/
	if(jQuery("#productsAlbum").length!=0){
		jQuery("#productsAlbum").treeview({
		persist: "location",
		collapsed: true,
		unique: true}).css("cursor","pointer");
	}
	if(jQuery("#archivedFiles").length!=0){
	jQuery("#archivedFiles").treeview({
		persist: "location",
		collapsed: true,
		unique: true}).css("cursor","pointer");
	}
	if(jQuery("#archivedblogs").length!=0){
	jQuery("#archivedblogs").treeview({
		persist: "location",
		collapsed: true,
		unique: true}).css("cursor","pointer");
	}
	// sign in menu box
	/*
	$(".signin").hover(function(e) {
		if($(e.target).parent("a.signin").length==0) {
			e.preventDefault();
			$("fieldset#signin_menu").show();
		}
    });
	$(".signin").click(function(e) {
		e.preventDefault();
		$("fieldset#signin_menu").toggle();
	});
	$("fieldset#signin_menu").mouseup(function() {
        return false
    });
	$(document).mouseup(function(e) {
	        if($(e.target).parent("a.signin").length==0) {
	        	$(".signin").removeClass("menu-open");
	        	$("fieldset#signin_menu").hide();
	        }
	});
	*/

	$("input#registerLoginEmailAddress").Watermark(KEY_EMAIL);
	$("#loginEmailAddress").Watermark(KEY_EMAIL);
	$("#loginPassword").Watermark(KEY_PASSWORD);
	$("#fakeregisterLoginPassword").Watermark(KEY_PASSWORD);
    $("#fakeregisterLoginPassword2").Watermark(KEY_PASSWORD);
    $("#topSearch").Watermark(KEY_SEARCH);


    // location menu
	$("#location_selector").mouseover(function() {
		$("#location_menu").slideDown('fast');
	});

	$("#location_container").mouseleave(function() {
		$("#location_menu").slideUp('fast');
	});

	//Edit Addres validation - Item must be changed for update button to be active
	if($('form#eAddressGadg').length){
		$('form#eAddressGadg').children('input[type=image]').attr('disabled', true);
		$('input').change(function() {
			$('form#eAddressGadg').children('input[type=image]').attr('disabled', false);
		});
	}

	//CLOSING POPUP
	jQuery("#popupContactClose").click(function(){
		disablePopup();
	});

});
/**************************************************
	end of jquery document load scripts  begin
	standard functions below
**************************************************/



/**************************************************
handles minicart slide functionality
**************************************************/
function miniCartDirection(direction) {
	//console.debug(direction);
	if(direction == "down") {
		$('#miniWishFlyoutHolder, #signin_menu').hide();
		$('#miniCartFlyoutHolder').slideDown('fast', function() {
			$('.scroll-pane').jScrollPane(
				{
					showArrows: true,
					verticalDragMinHeight: 32,
					verticalDragMaxHeight: 32
				}
			);
		});
	} else {
		$('#miniCartFlyoutHolder').slideUp('slow', function() {
			//console.debug("slide up");
		});
	}
	}

function miniWishDirection(direction) {
	if(direction == "down") {
		$('#miniCartFlyoutHolder, #signin_menu').hide();
		$('#miniWishFlyoutHolder').slideDown('fast', function() {
			$('.scroll-paneWish').jScrollPane(
				{
					showArrows: true,
					verticalDragMinHeight: 32,
					verticalDragMaxHeight: 32
				}
			);
		});
	} else {
		$('#miniWishFlyoutHolder').slideUp('slow', function() {

		});
	}

}

function miniSignInDirection(direction) {
	if(direction == "down") {
		$('#miniWishFlyoutHolder, #miniCartFlyoutHolder').hide();
		$('#signin_menu').slideDown('fast', function() {

		});
	} else {
		$('#signin_menu').slideUp('slow', function() {

		});
	}

}



/**************************************************
initialize anything that needs to bind when the page loads
-minicart functionality
-wishlist functionality
**************************************************/
function toggleMenu(elem, menu) {
	elem.hover( function() {
		var timeout = $(this).data("timeout");
		if(timeout) clearTimeout(timeout);
		menu("down");
	}, function() {
		 $(this).data("timeout", setTimeout($.proxy(function() {
			 menu("up");
        }, this), 1000));
    });
    $(document).click(function() {
    	$('#miniWishFlyoutHolder:visible, #miniCartFlyoutHolder:visible').hide();
    });
}
function initBindings() {
	toggleMenu($('#miniCartHolder'),miniCartDirection);
	toggleMenu($('#miniWishListHolder'),miniWishDirection);
	toggleMenu($('#miniSignInHolder'),miniSignInDirection);

	formSubmitDisabled();
	signinSubmitDisabled();

}

/*************************************************
 * 	Age Verification script
 * 	uses YYYY-MM-DD format for both dates
 * 	calls doAge()
 ************************************************/

function doAge(originalDate, dateToCalculateAgeOn) {

	if(!(typeof dateToCalculateAgeOn != 'undefined' && dateToCalculateAgeOn)) {

		dateToday = new Date();

		dateToCalculateAgeOn = dateToday.getFullYear() + '-' + (dateToday.getMonth() + 1) + '-' + dateToday.getDate();

	}

	originalDate = originalDate.replace(/[^0-9\-]/g, '').split('-');

	dateToCalculateAgeOn = dateToCalculateAgeOn.replace(/[^0-9\-]/g, '').split('-');

	ageDetermined = (dateToCalculateAgeOn[0] - originalDate[0]) - 1;

	if(dateToCalculateAgeOn[1]>originalDate[1]||(dateToCalculateAgeOn[1]==originalDate[1]&&dateToCalculateAgeOn[2]>=originalDate[2]))

		ageDetermined++;

	return ageDetermined; // returns age in years

}

function quickViewAjax(obj)   {
	var url = this.attr("action");
	alert(url);
	$("#dialog").dialog("destroy");
	$("#dialog").dialog({
		open: function () {
			$(this).load(url, function() {
				$(this).dialog('option', 'position', 'center');
			});
		},
		closeOnEscape: true,
		width: "auto",
		modal: true
	});
	return false;
}

function doSaS(){
	var selectIndex = $('#shippingAddressShipping option:selected').attr("class");
	selectIndex = '#ship'+selectIndex+'-';
	$('#shippingAddress_address1').val($(selectIndex+'address1').val());
	$('#shippingAddress_address2').val($(selectIndex+'address2').val());
	$('#shippingAddress_country').val($(selectIndex+'country').val());
	$('#shippingAddress_city').val($(selectIndex+'city').val());
	$('#shippingAddress_state').val($(selectIndex+'state').val());
	$('#shippingAddress_postalCode').val($(selectIndex+'postalCode').val());
	$('#shippingAddress_phoneNumber').val($(selectIndex+'phoneNumber').val());
	$('#shippingAddress_firstName').val($(selectIndex+'firstName').val());
	$('#shippingAddress_lastName').val($(selectIndex+'lastName').val());
}

function doBcC(){
	var selectIndex = $('#creditCard option:selected').attr("class");
	selectIndex = '#card'+selectIndex+'-';

	$('#creditCard_creditCardType').val($(selectIndex+'creditCardType').val());
	$('#creditCard_creditCardNickname').val($(selectIndex+'nickName').val());
	$('#creditCard_expirationMonth').val($(selectIndex+'expirationMonth').val());
	$('#creditCard_expirationYear').val($(selectIndex+'expirationYear').val());
	$('#creditCard_creditCardNumber').val($(selectIndex+'creditCardNumber').val());
	//$('#creditCard_creditCardNumber').val($(selectIndex+'atg_store_verificationNumberInput').val());
	$('#creditCard_firstName').val($(selectIndex+'firstName').val());
	$('#creditCard_lastName').val($(selectIndex+'lastName').val());

	$('#billingAddress_address1').val($(selectIndex+'address1').val());



	ccVal = $("#creditCard").val();
	if(ccVal.indexOf("NEW") != -1) {
		$('#billingAddress').val("NEW");
	}
	else{
		$('#billingAddress').val($(selectIndex+'creditCardBillingAddress').val());
	}



	$('#billingAddress_address2').val($(selectIndex+'address2').val());
	$('#creditCard_country').val($(selectIndex+'country').val());
	$('#billingAddress_city').val($(selectIndex+'city').val());
	$('#billingAddress_state').val($(selectIndex+'state').val());
	$('#billingAddress_postalCode').val($(selectIndex+'postalCode').val());
	$('#billingAddress_phoneNumber').val($(selectIndex+'phoneNumber').val());
}

function doBa(){
	var selectIndex = $('#billingAddress option:selected').attr("class");
	selectIndex = '#bill'+selectIndex+'-';

	$('#creditCard_firstName').val($(selectIndex+'firstName').val());
	$('#creditCard_lastName').val($(selectIndex+'lastName').val());
	$('#billingAddress_address1').val($(selectIndex+'address1').val());
	$('#billingAddress_address2').val($(selectIndex+'address2').val());
	$('#billingAddress_city').val($(selectIndex+'city').val());
	$('#billingAddress_state').val($(selectIndex+'state').val());
	//$('#billingAddress_country').val($(selectIndex+'country').val());
	$('#billingAddress_postalCode').val($(selectIndex+'postalCode').val());
	$('#billingAddress_phoneNumber').val($(selectIndex+'phoneNumber').val());

}

function pwdFocus(fakeId,realId) {
	$('#'+fakeId).hide();
	$('#'+realId).show();
   	$('#'+realId).focus();
	$('#'+realId).attr('value','');
	return false;
}

function pwdBlur(fakeId,realId) {
    if ($('#'+realId).attr('value') == '') {
    	$('#'+realId).hide();
    	$('#'+fakeId).show();
    }
    return false;
}

// SMS Sign-up validation.  Needs to be client-side, since form submits off-site
function validateAlertSignup(formName) {

	if (formName == 'sms') {
		var phoneNumberField = $('#UPT_mobile_phone_number');
	    var phoneNumber = $('#UPT_mobile_phone_number').val();
	    var stripped = phoneNumber.replace(/[\(\)\.\-\ ]/g, '');
	    if (phoneNumber == '') {
	    	phoneNumberField.addClass('errorMessageField', 500);
	    	alert("Please enter a value for your mobile number");
	    	return false;
	    } else if (isNaN(parseInt(stripped))) {
	    	phoneNumberField.addClass('errorMessageField', 500);
	    	alert("Please only use digits for your mobile number");
	    	return false;
	    } else if (stripped.length != 10) {
	    	phoneNumberField.addClass('errorMessageField', 500);
	    	alert("Your mobile number must be 10 digits in length");
	    	return false;
	    }
	    return error;
	}
	return true;
}

function formSubmitDisabled() {
	$('form').each(function() {

		disableTheButton = false;

		$(this).find('input, select').each(function() {
			//("fieldreq = " + $(this).hasClass('required'));
			if(($(this).hasClass('required') == true) && ($(this).val()=="")) {
				disableTheButton = true;
			}
		});

		$(this).find(':image, :submit').not("#applyGiftCardButton").each(function() {
			//console.debug("image = " + $(this).attr("name"));
			if(disableTheButton == true) {
				$(this).attr("disabled", "true");
				$(this).css("opacity", "0.4");
			} else {
				$(this).attr("disabled", "");
				$(this).css("opacity", "1");
			}
		});
	});
}
function signinSubmitDisabled() {
	$('#atg_store_checkoutLoginForm').each(function() {

		disableTheButton = false;

		$(this).find('input').each(function() {
			if(($(this).hasClass('signin-r') == true) && ($(this).val()=="")) {
				disableTheButton = true;
			}
		});

		if(disableTheButton == true) {
			$('#checkout-signin-btn').attr("disabled", "true").css("opacity", "0.4");
		} else {
			$('#checkout-signin-btn').attr("disabled", "").css("opacity", "1");
		}
	});
}

function initAddThis() {
	if(window.console && window.console.firebug) {
		console.debug("called it");
	}
	addthis.init()
	//console.debug("afterwards");
}

/*******************************************
 * for PROFANITY CHECK WEBPURIFY API METHOD - copied from customValidate.js
*******************************************/
function validateComments(lang){

	// WebPurify's spanish lang code = 'sp', so need to catch 'es' and change
	if (lang == 'es') lang = 'sp';

	var commntFieldObj=document.getElementById('comment');
	var messageObj=document.getElementById('PST_MESSAGE');

	jQuery.webpurify.check( jQuery("#comment").val(), lang, function(isProfane){
		if(jQuery("#comment").val()!=""){
			if(!isProfane){
				document.forms['CommentsFrom'].submit();
				_gaq.push(['_trackPageview', '/virtual/comment']);
			}else{
				commntFieldObj.style.color="red";
				messageObj.style.display="block";
				return false;
			}
		}else{
			return false;
		}
	});
}

/*******************************************
	form validation
*******************************************/
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}


