
function goto(url) {
    location.href=url;
}

sfHover = function() {
	var sfEls = document.getElementById("primaryTopNav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

if (window.attachEvent) window.attachEvent("onload", sfHover);
	//turn off primary when slide from primary to secondary NOT WORKING
	sfHoverOut = function() {
}

//secondary nav
function divSecondaryMenu() {
	this.ShowMenu = function ShowDiv(_id, _top, _left) {
		this.HideAll();
		this.ShowGuts(_id);
		document.getElementById(_id).style.display = 'inline';
	}

	this.ShowCart = function ShowCart(_id, _top, _right) {
		this.HideAll();
		this.ShowGuts(_id);
		document.getElementById(_id).style.display = 'inline';
	}

	this.HideAll = function HideSecondarySubNav() {
		var divs = document.getElementById("secondaryTopNav").getElementsByTagName("DIV");
		for (var i=0; i<divs.length; i++) {
			divs[i].style.display = 'none';
		}
	}

	this.ShowGuts = function ShowChildDivs(_id) {
		var divs = document.getElementById(_id).getElementsByTagName("DIV");
		for (var i=0; i<divs.length; i++) {
			divs[i].style.display = 'block';
		}
	}
}

divBrandNav = new divSecondaryMenu();
//end secondary

// Change Background Position on Search Div for rollover
function changePosition() {
document.getElementById('searchGO').style.backgroundPosition="0px -34px";
}
function changePositionBack() {
document.getElementById('searchGO').style.backgroundPosition="0px 0px";
}

// begin new jquery specific scripts
// this $(function() piece needs to surround any basic jquery scripts
// most scripts would go inside of this doc.ready piece anyway
// using this method allows us to use multiple script libraries
$(function() {

	$(document).ready(function(){
	    $(document).pngFix();

	    $(".genericToggleArea").each(function() {
	    	$(this).css("width","590px");
	    	$(this).css("display","none");
	    });

	    //set scripts for accordian style toggles
	    $(".genericToggleBtn").each(function() {
			$(this).click(function()	{
				$(this).next().slideToggle('slow');
			});
		});

	    $("#v_toggle").click(function()	{
			$("#vertical_slide").slideToggle('slow');
			return false;
		});

	    $(".catToggleBtn").click(function()	{
	    	$(".catToggleArea").slideToggle('slow');
			return false;
		});

	    $(".newsToggleArea").hide();

	    $(".newsToggleBtn").click(function()	{
			$(".newsToggleArea").slideToggle('slow');
			return false;
		});

	    $("#stateCSName").change( function() {
	    	/*alert("Entered the function");
	    	var state = $(this).attr('value');
	    	alert(state);
	    	var response = $.ajax({type:"GET",url:"/customerService/getCityData.jsp?st="+state,async:true,
	    							success : function()
	    							{
	    								alert(this);
	    							}
	    							});*/
            if (checkAllParameters()) {

                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                var jsComments = replaceCarriageReturns($("#comments").attr('value'), '%250d');
                var jsMiddleName = $("#middleName").attr('value') == 'undefined' ? '' : $("#middleName").attr('value');
                goto('/contactUs/index.jsp?f=CS&st=' + $(this).attr('value') + "&fn=" + $("#firstName").attr('value') + "&mn=" + jsMiddleName
                                                    + "&ln=" + $("#lastName").attr('value') + "&e=" + $("#email").attr('value') + "&ta=" + $("#phoneArea").attr('value')
                                                    + "&tp=" + $("#phonePrefix").attr('value') + "&ts=" + $("#phoneSuffix").attr('value') + "&addr=" + $("#address").attr('value')
                                                    + "&city=" + $("#city").attr('value') + "&state=" + $("#stateId").attr('value') + "&zip=" + $("#zip").attr('value')
                                                    + "&cnt=" + contactMethod + "&dt=" + $("#datepicker").attr('value') + "&inv=" + $("#invoiceNum").attr('value') + "&sp=" + $("#salesPerson").attr('value') + "&cmt=" + jsComments + "#jsstate");
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#stateCSName").val("Select State...");
            }
		});
		$("#cityCSName").change( function() {

            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                var jsComments = replaceCarriageReturns($("#comments").attr('value'), '%250d');
                var jsMiddleName = $("#middleName").attr('value') == 'undefined' ? '' : $("#middleName").attr('value');
                goto('/contactUs/index.jsp?f=CS&st=' + $("#stateCSName").attr('value') + '&selCity=' + $(this).attr('value') + "&fn=" + $("#firstName").attr('value') + "&mn=" + jsMiddleName
                                                    + "&ln=" + $("#lastName").attr('value') + "&e=" + $("#email").attr('value') + "&ta=" + $("#phoneArea").attr('value')
                                                    + "&tp=" + $("#phonePrefix").attr('value') + "&ts=" + $("#phoneSuffix").attr('value') + "&addr=" + $("#address").attr('value')
                                                    + "&city=" + $("#city").attr('value') + "&state=" + $("#stateId").attr('value') + "&zip=" + $("#zip").attr('value')
                                                    + "&cnt=" + contactMethod + "&dt=" + $("#datepicker").attr('value') + "&inv=" + $("#invoiceNum").attr('value') + "&sp=" + $("#salesPerson").attr('value') + "&cmt=" + jsComments + "#jscity");
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#cityCSName").val("Select City...");
            }
		});
		$("#stateEmpName").change( function() {
            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'relocate')) {
                    relocateChoice = $('form input:radio:checked').val();
                }
                goto('/contactUs/index.jsp?f=Employment&st='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                    + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneAreaCode").attr('value')
                                                    + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                    + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&rlc=" +relocateChoice
                                                    + "cmnts=" +$("#comments").attr('value') + "rsme=" + $("#resume").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#stateEmpName").val("Select State...");
            }
		});
		$("#cityEmpName").change( function() {

            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'relocate')) {
                    relocateChoice = $('form input:radio:checked').val();
                }
                goto('/contactUs/index.jsp?f=Employment&st='+$("#stateEmpName").attr('value') + '&selCity='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                    + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneAreaCode").attr('value')
                                                    + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                    + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&rlc=" +relocateChoice
                                                    + "cmnts=" +$("#comments").attr('value') + "rsme=" + $("#resume").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#cityEmpName").val("Select City...");
            }
		});

		$("#stateFinName").change( function() {
            if (checkAllParameters()) {
			    var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                //var rating = -1;
                //if($('form radio:checked').attr('name', 'rating')) {
                //	rating = $('form input:radio:checked').val();
                //}
                goto('/contactUs/index.jsp?f=FinQuestions&st='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                              + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneArea").attr('value')
                                                              + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                              + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&zip=" +$("#zip").attr('value')
                                                              + "&cnt=" +contactMethod+ "&dt=" +$("#datepicker").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#stateFinName").val("Select State...");
            }
		});
		$("#cityFinName").change( function() {

            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                goto('/contactUs/index.jsp?f=FinQuestions&st='+$("#stateFinName").attr('value') + '&selCity='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                              + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneArea").attr('value')
                                                              + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                              + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&zip=" +$("#zip").attr('value')
                                                              + "&cnt=" +contactMethod+ "&dt=" +$("#datepicker").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#cityFinName").val("Select City...");
            }
		});
		$("#stateWarName").change( function() {
            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                goto('/contactUs/index.jsp?f=WarQuestions&st='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                              + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneArea").attr('value')
                                                              + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                              + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&zip=" +$("#zip").attr('value')
                                                              + "&cnt=" +contactMethod+ "&dt=" +$("#datepicker").attr('value')+ "&inv=" +$("#invoiceNum").attr('value')+ "&sp=" +$("#salesPerson").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#stateWarName").val("Select State...");
            }
		});
		$("#cityWarName").change( function() {

            if (checkAllParameters()) {
                var contactMethod = 1;
                if($('form radio:checked').attr('name', 'contactMethod')) {
                    contactMethod = $('form input:radio:checked').val();
                }
                goto('/contactUs/index.jsp?f=WarQuestions&st='+$("#stateWarName").attr('value') + '&selCity='+$(this).attr('value')+ "&fn=" +$("#firstName").attr('value')+ "&mn=" +$("#middleName").attr('value')
                                                              + "&ln=" +$("#lastName").attr('value')+ "&e=" +$("#email").attr('value')+ "&ta=" +$("#phoneArea").attr('value')
                                                              + "&tp=" +$("#phonePrefix").attr('value')+ "&ts=" +$("#phoneSuffix").attr('value')+ "&addr=" +$("#address").attr('value')
                                                              + "&city=" +$("#city").attr('value')+ "&state=" +$("#stateId").attr('value')+ "&zip=" +$("#zip").attr('value')
                                                              + "&cnt=" +contactMethod+ "&dt=" +$("#datepicker").attr('value')+ "&inv=" +$("#invoiceNum").attr('value')+ "&sp=" +$("#salesPerson").attr('value'));
                //alert($(this).attr('value'));
            } else {
                alert("\"%\" character is not allowed in any of the fields.");
                $("#cityWarName").val("Select City...");
            }
		});

		$(".sliderButton").each( function() {
			$(this).click(function() {
				$(".sliderButton").each( function() {
					$(this).removeClass('selectedSlider');
				});
				$(this).addClass('selectedSlider');

				$(".slide").each(function (){
					$(this).hide();
				});
				$("."+this.id).show();

			});

		});
		//hide all slides onload except for first slide
		$(".slide").not("#slide1").each(function (){
			$(this).hide();
		});
		$("#slider1").addClass('selectedSlider');


		//image rotator script for multiple large product images

		$('.largeImageRotator').each( function(i, val) {
			var j= i+1;
			if(j < 10){j = "0"+j;}
			//alert("i = " + i);
			//alert("val = "+ val);
			$(this).click(function(){
				$('.imgPaginationActive').addClass("imgPagination");
				$('.imgPaginationActive').removeClass("imgPaginationActive");
				$(this).addClass("imgPaginationActive");
				$(this).removeClass("imgPagination");
				$("#largeImage").attr("src", this.id);
				//alert($("#largeImage").attr("src"));
			});
		});

		//alert($('#threeColumnContentCenterColumn').height());
		$('#threeColumnContentLeftColumn').css('padding-bottom', '30px');
		$('#threeColumnContentLeftColumn').css('margin-bottom', '-40px');
		//this was set to height()+250 , but changed it to +0 to remove extra space below pagination
		leftColHeight = $('#threeColumnContentCenterColumn').height()+0;
		if(leftColHeight < 840){
			leftColHeight = 840;
		}
		$('#threeColumnContentLeftColumn').css('height', leftColHeight);

		$('#twoColumnContentSmallColumnRight').css('padding-bottom', '30px');
		$('#twoColumnContentSmallColumnRight').css('margin-bottom', '-40px');
		//this was set to height()+250 , but changed it to +0 to remove extra space below pagination
		rightColHeight = $('#twoColumnContentSmallColumnRight').height()+0;
		if(rightColHeight < 840){
			rightColHeight = 840;
		}
		$('#twoColumnContentSmallColumnRight').css('height', rightColHeight);
		$('#twoColumnContentSmallColumnRight').css('border-bottom', '1px solid #E0E0E0');



		$("#productList").change( function() {
			//goto($("#goto").val()+$(this).attr('value'));
			goto($("#goto").val()+'?id=' + $("#productId").val() + '&skuId=' + $(this).attr('value') + '&type=' + $("#groupType").val());
		});

		$("#productTypeList").change( function() {
			goto($("#gotoProductType").val()+'&type='+$(this).attr('value'));
			//alert($("#goto").val()+'&skuId='+$(this).attr('value'));
		});

		$(".singleOption").parent().hide();

		//begin AJAX CART CODE FOR DOCUMENT READY
			//call this here because cartArea functions have been moved
			//to the initBinding function
			//this is because of the ajaxcallback on the addToCart functionality
			//we need to re-bind the hover functions because ajax replaced
			//the areas
			initBinding();
			$(".addToCartLink").each( function(){
				$(this).click(function() {
					addToCartAjax($(this).attr('href'));
					return false;
				});
			});

			//on prod pages with dropdowns, check the url params to see if we need to show the cart onload
			var showCart = getUrlVars()["showCart"];
			if(showCart == "1") {
				divBrandNav.ShowCart('CartWatcher', 0, 0);
			}
		//end AJAX CART CODE FOR DOCUMENT READY

		// begin checkoutstep1 scripts to fill addresses
		$("#shippingAddress").change( function(){
			if ($("#shippingAddress").attr("selectedIndex") > 0)
				selectedAddress = "ship" + $("#shippingAddress").attr("selectedIndex");
			else
				selectedAddress = "";

			if(selectedAddress != "") {
				//set values on all the input boxes
				$("#shippingAddress_firstName").val($("#"+selectedAddress+"-firstName").val());
				$("#shippingAddress_lastName").val($("#"+selectedAddress+"-lastName").val());
				$("#shippingAddress_companyName").val($("#"+selectedAddress+"-companyName").val());
				$("#shippingAddress_phoneNumber").val($("#"+selectedAddress+"-phoneNumber").val());
				$("#shippingAddress_address1").val($("#"+selectedAddress+"-address1").val());
				$("#shippingAddress_address2").val($("#"+selectedAddress+"-address2").val());
				$("#shippingAddress_city").val($("#"+selectedAddress+"-city").val());
				$("#shippingAddress_state").val($("#"+selectedAddress+"-state").val());
				$("#shippingAddress_postalCode").val($("#"+selectedAddress+"-postalCode").val());
			} else {
				//if it doesnt have anthing selected, clear the fields..
				$("input[id^='shippingAddress']").val("");
				$("select[id^='shippingAddress']").val("");
			}
		});

		$("#billingAddress").change( function(){
			if ($("#billingAddress").attr("selectedIndex") > 0)
				selectedAddress = "bill" + $("#billingAddress").attr("selectedIndex");
			else
				selectedAddress = "";

			if(selectedAddress != "") {
				//set values on all the input boxes
				$("#billingAddress_firstName").val($("#"+selectedAddress+"-firstName").val());
				$("#billingAddress_lastName").val($("#"+selectedAddress+"-lastName").val());
				$("#billingAddress_companyName").val($("#"+selectedAddress+"-companyName").val());
				$("#billingAddress_phoneNumber").val($("#"+selectedAddress+"-phoneNumber").val());
				$("#billingAddress_address1").val($("#"+selectedAddress+"-address1").val());
				$("#billingAddress_address2").val($("#"+selectedAddress+"-address2").val());
				$("#billingAddress_city").val($("#"+selectedAddress+"-city").val());
				$("#billingAddress_state").val($("#"+selectedAddress+"-state").val());
				$("#billingAddress_postalCode").val($("#"+selectedAddress+"-postalCode").val());
			} else {
				//if it doesnt have anthing selected, clear the fields..
				$("input[id^='billingAddress']").val("");
				$("select[id^='billingAddress']").val("");
			}
		});
		//end checkoutstep1 address updaters

		//checkoutStep3 update
		$("#savedCreditCard").change( function(){

			if ($("#savedCreditCard").attr("selectedIndex") > 0)
				selectedCard = "cc" + $("#savedCreditCard").attr("selectedIndex");
			else
				selectedCard = "";

			if(selectedCard != "") {
				//set values on all the input boxes
				$("#creditCard_creditCardType").val($("#"+selectedCard+"-creditCardType").val());
				$("#creditCard_cardholderName").val($("#"+selectedCard+"-cardholderName").val());
				$("#creditCard_creditCardNumber").val($("#"+selectedCard+"-creditCardNumber").val());
				$("#creditCard_cardVerificationNumber").val($("#"+selectedCard+"-cardVerificationNumber").val());
				$("#creditCard_expirationMonth").val($("#"+selectedCard+"-expirationMonth").val());
				$("#creditCard_expirationYear").val($("#"+selectedCard+"-expirationYear").val());

                $("input[id^='creditCard_']").attr('disabled', 'disabled');
                $("select[id^='creditCard_']").attr('disabled', 'disabled');
			} else {
				//if it doesn't have anything selected, clear the fields..
				$("input[id^='creditCard_']").val("");
				$("select[id^='creditCard_']").val("");
                $("input[id^='creditCard_']").removeAttr("disabled");
                $("select[id^='creditCard_']").removeAttr("disabled");
			}
		});
		//end checkoutStep3 update



		//begin search box autocomplete
		$("#mainSearchBox").autocomplete('/search/typeAhead.jsp', {
			width: 217,
			minChars: 1,
			matchContains: true
		});

	});
	//end document ready section


    /**
     * Checks for any possible "%" character in a given string.
     * @param element
     */
    function containsPercentChar(element) {
        if (element === undefined)
            return false;
        else
            return element.indexOf('%') != -1;
    }

    /**
     * Checks first name, middle name, last name, email, phone, address, city, zip, invoice no and sales person
     * fields of the cutomser service forms for any possible "%" character.
     */
    function checkAllParameters() {

        return (!containsPercentChar($("#firstName").attr('value')) && !containsPercentChar($("#lastName").attr('value')) &&
                !containsPercentChar($("#email").attr('value')) && !containsPercentChar($("#phoneArea").attr('value')) &&
                !containsPercentChar($("#phonePrefix").attr('value')) && !containsPercentChar($("#phoneSuffix").attr('value')) &&
                !containsPercentChar($("#address").attr('value')) && !containsPercentChar($("#city").attr('value')) &&
                !containsPercentChar($("#zip").attr('value')) && !containsPercentChar($("#invoiceNum").attr('value')) &&
                !containsPercentChar($("#salesPerson").attr('value')) && !containsPercentChar($("#middleName").attr('value')));
    }


	//begin AJAX CART FUNCTIONS
		//this gets called on document.ready and after an ajax callback
		//because after ajax, we need to rebind the hover
		function initBinding() {
			$("#cartArea").hover( function () {
				divBrandNav.ShowCart('CartWatcher', 0, 0);
			});
			$("#cartArea").mouseout( function () {
				divBrandNav.HideAll();
			});
		}
		//this function supports addToCart buttons that are not forms or cannot
		//be initialized during pageLoad
		function addToCartAjax(url) {
			$.get(url,
				function(data){
					$.ajax( {
			        	url: '/common/widgets/dynamicMiniCart.jsp',
			            success: function(html) {
			                $('#CartWatcher').empty().append(html);
			                initBinding();
			                divBrandNav.ShowCart('CartWatcher', 0, 0);
			            }
			        });
				}
			);
		}
	//end AJAX CART FUNCTIONS



	function getUrlVars(){
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	        hash = hashes[i].split('=');
	        vars.push(hash[0]);
	        vars[hash[0]] = hash[1];
	    }
	    return vars;
	}

	function replaceCarriageReturns(replaceFrom, replaceWith) {
		replaceFrom = escape(replaceFrom);
		//encode all characters in text area
		//to find carriage return character
		for(i=0; i < replaceFrom.length; i++) {
			//loop through string, replacing carriage return
			//encoding with HTML break tag
			if(replaceFrom.indexOf("%0D%0A") > -1) {
				//Windows encodes returns as \r\n hex
				replaceFrom = replaceFrom.replace("%0D%0A",replaceWith);
			}
			else if(replaceFrom.indexOf("%0A") > -1) {
				//Unix encodes returns as \n hex
				replaceFrom = replaceFrom.replace("%0A",replaceWith);
			}
			else if(replaceFrom.indexOf("%0D") > -1) {
				//Macintosh encodes returns as \r hex
				replaceFrom = replaceFrom.replace("%0D",replaceWith);
			}
		}
		return unescape(replaceFrom);
		//decode all characters in text area back
	}


	//check for images that are missing
	/*
	$(window).bind('load', function() {
		$('img').each(function() {
			if((typeof this.naturalWidth != "undefined" &&
				this.naturalWidth == 0 )
				|| this.readyState == 'uninitialized' ) {
				lastSlash = $(this).attr("src").lastIndexOf("/");
				prefix = $(this).attr("src").substr(0,lastSlash);
				$(this).attr("src", prefix+"/tn_noImage.jpg");
			}
		});
	})
	*/

});

