$(document).ready(function() {
    $.ajaxSetup ({
        // Disable caching of AJAX responses */
        cache: false
    });
	try{
		var imageUrl=$('#CheckoutTable #btnContinue').attr('src').replace('Continue','continue_yellow');
		$('#CheckoutTable #btnContinue').removeAttr('src');
		$('#CheckoutTable #btnContinue1').removeAttr('src');
		$('#CheckoutTable #btnContinue').attr('src',imageUrl);
		$('#CheckoutTable #btnContinue1').attr('src',imageUrl);
		$('#CheckoutTable #btnContinue').removeClass('spartanNoShow');
		$('#CheckoutTable #btnContinue1').removeClass('spartanNoShow');
	}catch(e){}

	$('#navcolumn div.HomepageBlock div.CategoryList h4 span').html('Hydrion &reg; Products');

	setQuickOrderMinimumQty();
	makeAddressCaptionDynamic();
	CategotyPageDynamicPull();
	FixImagePath();
	LoadMenu();
	changeLoginButton();
	customFAQ();
	$('#ProductProperties').attr("id",'productTabs');

	$('#footerNav2 li a').not(':first').addClass('navBorder');
	//set height of the subnav box equal to that of the main content area

	
	/*check to see if the <select> element with id="industry" exists.  $('#industry') will return an array of all the elements matching that selector.  If the length is greater than 0, this means that it exists*/
	if ( $("#industry").length > 0 ) {
	 	//if it exists, run the addField function
	 	$('#specifyInd').hide();
	 	addField();
	}
	

	if($("#ItemCount span").html()!='0 Products'){
		$(".itemCount").removeClass('spartanNoShow');
	}

	try{
		if($(".enlarge")){
			var popurl=$("#ProductImage").html();
			popurl=popurl.substring(popurl.indexOf('(\'')+2,popurl.indexOf('\','));
			if(popurl.length>1){
				$(".enlarge").click(function(){
					//$(".enlarge").attr('href','JavaScript:window.open('+ popurl +')');
					var newwin=window.open(popurl,'Images','width=700, height=600, menubar=no, scrollbars=yes, resizable=yes, status=no, toolbar=no');
					newwin.focus();
					return false;
				});
			}else{
				$(".enlarge").addClass('spartanNoShow');
				$(".enlarge").removeClass('enlarge');
			}
		}
	}catch(e){
		$(".enlarge").addClass('spartanNoShow');
		$(".enlarge").removeClass('enlarge');
	}

	changeVolumePricingOrder();
	minQuantityNotification();

	$('#EmailThisPage').attr('id','emailPrint');
	$('#EmailThisPage1_RemoteWindow1').html('E-mail This Page');



	$('#MyAccountMenu1_lstMyAccountMenu li:nth-child(4)').remove();
	$('#MyAccountMenu1_lstMyAccountMenu li:nth-child(2)').remove();

	$('tr.VolumePricingHeader td:nth-child(1)').addClass('spartanNoShow');
	$('tr.VolumePricingText td:nth-child(1)').addClass('spartanNoShow');

	var strIndustry='';
	var strPopular='';
	var strHydrion='';
	var industryStart=$('.CategoryListContent').children('span').children('ul').children('li').length-5

	$('.CategoryListContent').children('span').children('ul').children('li').each(function(i){
		if(i<=5){
			strPopular+='<li>'+$(this).html()+'</li>';
			$(this).html('');
			$(this).remove();
		}
		else if (i>=industryStart)
		{
			strIndustry+='<li>'+$(this).html()+'</li>';
			$(this).remove();
		}else{
			strHydrion+='<li>'+$(this).html()+'</li>';
		}
	})

	$("#navcolumn .HomepageBlock").html('');

	$("#navcolumn .HomepageBlock").append('<div class="CategoryList"><h4><span>Popular Searches</span></h4><div class="CategoryListContent"><ul>'+strPopular+'</ul></div>');

	$("#navcolumn .HomepageBlock").append('<div class="CategoryList"><h4><span>Additional Products</span></h4><div class="CategoryListContent"><ul>'+strHydrion+'</ul></div>');
	if (strIndustry!='')
	{
		$("#navcolumn .HomepageBlock").append('<div class="CategoryList"><h4><span>Industry Solutions</span></h4><div class="CategoryListContent"><ul>'+strIndustry+'</ul></div>');
	}


	strElement='';

	$("#lstProperties li span.ProductPropertyLabel").each(function(i){
		$(this).wrapInner('<a href="#'+i+'"></a>');
	});

	$(".ProductProperty").each(function(i){
		strElement+='<div id="'+i+'">'+$(this).html()+'</div>';
	});

	$(".ProductProperty").remove();

	$('#productTabs').append(strElement);

	$('#productTabs > ul').tabs();

	var selectedCategory=$('span.CurrentCategory').text()
	if($('#products h1').text()==''){
		$('#products h1').html(selectedCategory);
	}





	if($(".serviceCenter")){

		var toLoad = 'custom.aspx?id=19 .csaddress';
		var contentArea=$(".serviceCenter");
		contentArea.load(toLoad, function(){
			$(this).fadeTo("slow", 5.0);
		});
	}

	$("#btnContinueShopping").click(function(){
		var referer=document.referrer;
		if(referer.indexOf('Category')<0){
			referer='Category/53_1/BEST SELLERS.aspx';
		}
		location.href=referer;
		return false;
	});
	

	$('#NewUserControl1_lblUsername').html('Email Address');
	$('#LoginControl1_lblUsername').html('Username <a href="javascript:;" title="Usernames created after June 10th, 2009 are email addresses."><img src="./images/question.png" align="right"/></a>');
	$('#lblSKUTitle').html('Catalog#:');
	$('#lblSKUTitle').removeClass('spartanNoShow');
	$('#lblSitePriceName').html('Price');
	$('#lblSitePriceName').addClass('spartanNoShow');
	$('#lblSitePrice').addClass('spartanNoShow');
	fixPager();

	setUpContactUs();

	customToolTip();

	//resizeImage();
	//add extra space between Address Header and Address in the Checkout_Address.aspx page
	$('#AddressBookPanel #AddressList span b').append('<p></p>');
	$('#CheckoutTable #AddressBookPanel #AddressList span b').append('<hr>');
	$('.productinfopage').css({'width' : '710px'});
	$('#ContentColumnAcct #AddressList span b').css({'color' : 'red'});
	
	//remove wishlist and mailing lists links
	cleanupAccountLinks();
/*
	try{
	var totalprice=$('#CheckoutTable span#lblTotalOrder').html();
		var discountPrice=totalprice.substring(totalprice.indexOf('</span>')+7).trim()
			if(discountPrice!=''){
			totalprice=totalprice.replace(discountPrice,' <span class="discount">('+discountPrice.trim()+')</span>')
			$('#CheckoutTable span#lblTotalOrder').html(totalprice);
		}
	}catch(e){}
	
*/
});
/*left and right columns should be equal height all the time so that the borders extend downward even when there is no content to fill the container*/


/*add a field for specifying your industry if you select "other" from the dropdown*/
function addField(){
	//set the extra field to visible if the value of #industry is "other"
	if($('#industry').val().indexOf("Other") != -1) {
		$('#specifyInd').show();
	} else {
	//otherwise, make it invisible
		$('#specifyInd').hide();
	}
	
	//when the #industry select changes, check to see what value it has
	$('#industry').change(function(){
		/*--if the value of the select#industry element is "Other" (meaning indexOf() returns something other than -1), show the extra field--*/
		if($(this).val().indexOf("Other") != -1) {
			$('#specifyInd').show();	
		} else {
			$('#specifyInd').hide();
		}
	})
	
};



/*
addPrintLink function by Roger Johansson, www.456bereastreet.com
*/
var addPrintLink = {
	init:function(sTargetEl,sLinkText) {
		if (!document.getElementById || !document.createTextNode) {return;} // Check for DOM support
		if (!document.getElementById(sTargetEl)) {return;} // Check that the target element actually exists
		if (!window.print) {return;} // Check that the browser supports window.print
		var oTarget = document.getElementById(sTargetEl);
		var oLink = document.createElement('a');
		oLink.id = 'print-link'; // Give the link an id to allow styling
		oLink.href = '#'; // Make the link focusable for keyboard users
		oLink.appendChild(document.createTextNode(sLinkText));
		oLink.onclick = function() {window.print(); return false;} // Return false prevents the browser from following the link and jumping to the top of the page after printing
		oTarget.appendChild(oLink);
	},
/*
addEvent function included here for portability. Replace with your own addEvent function if you use one.
*/
/* addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html */
	addEvent:function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};
addPrintLink.addEvent(window, 'load', function(){addPrintLink.init('emailPrint','Print This Page');});

$(window).load(
			   
	function equalCols(){

	var subNavHeight = $('#navcolumn #HomepageBlock').innerHeight();
	var contentHeight = $('#contentAreaWrap').innerHeight();
	var productHeight = $('#products').innerHeight();
	var detailHeight = $('#maincontent').innerHeight();
	/*subtract 303 because the "Product Directions" tab with a fixed height is hidden and should not contribute to the total container height */
	var newDetail = detailHeight - 303;
	
	if(subNavHeight < productHeight){
		$('#subNav').height(productHeight);	
	} else {
		$('#products').height(subNavHeight);	
	}
	if(subNavHeight < contentHeight){
		$('#subNav').height(contentHeight);		
	} else {
		$('#contentAreaWrap').height(subNavHeight);
	}
	if(subNavHeight < detailHeight){
		$('#navcolumn #HomepageBlock').height(detailHeight);	
	} else if(subNavHeight > detailHeight) {
		$('#maincontent').height(subNavHeight);	
	}

	})

function changeVolumePricingOrder() {
	try{
	var VolumePricingText1=$('tr.VolumePricingText').not(':last').html();
	var VolumePricingText2=$('tr.VolumePricingText').not(':first').html();

	$('tr.VolumePricingText').not(':last').html(VolumePricingText2);
	$('tr.VolumePricingText').not(':first').html(VolumePricingText1);
	}catch(e){alert(e.message)};
}



function setCookie(id, value) {
	document.cookie = id+'='+value+';path=/;';
}
	
function getCookie( id, defaultValue ) {
	var re = new RegExp(id+'=(.*)');
	var value = re.exec(document.cookie);
	return (value) ? value[1].split(';')[0] : defaultValue;
}
function cookieTime(days){
	var now = new Date();
	var exp = new Date();
	var x = Date.parse(now);
	exp.setTime(x);
	str = exp.toUTCString();
	re = '/(\d\d)\s(\w\w\w)\s\d\d(\d\d))/';
	return str.replace(re,"$1-$2-$3");
}

function setUpContactUs(){
	$('#submitMsg').click(function(){
		var compName=document.getElementById("compName").value;
		var firstName=document.getElementById("firstName").value;
		var lastName=document.getElementById("lastName").value;
		var email=document.getElementById("email").value;
		var inquiryType=$('#inquiryType').attr("value");
		var message=document.getElementById("message").value;
		var contentArea=$("#result");
		contentArea.html('');
		if(compName=='' || firstName=='' || lastName=='' || email==''){
			alert("Company Name, First Name, Last Name and Email cannot be left blank.");
			return false;
		}
		if(!checkEmail(email)){
			alert("Please enter a valid Email Address.");
			return false;
		}
		var qString='compName='+escape(compName)+'&firstName='+escape(firstName)+'&lastName='+escape(lastName)+'&email='+email+'&inquiryType='+escape(inquiryType)+'&message='+escape(message)

		var toLoad = parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/SendMail.aspx?'+qString+' .result';
		contentArea.load(toLoad, function(){
			document.getElementById("compName").value='';
			document.getElementById("firstName").value='';
			document.getElementById("lastName").value='';
			document.getElementById("email").value='';
			$('#inquiryType').attr("value","Question");
			document.getElementById("message").value='';
			$(this).fadeTo("slow", 5.0);
		});
		return false;
	});
	$('#clearForm').click(function(){
		document.getElementById("compName").value='';
		document.getElementById("firstName").value='';
		document.getElementById("lastName").value='';
		document.getElementById("email").value='';
		$('#inquiryType').attr("value","Question");
		document.getElementById("message").value='';
		return false;
	});
}


function checkEmail(email)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(filter.test(email))
		return true;
	else
		return false;
}


function fixPager(){
	/*try{
		var objPrevButton=$('#lblPager a:nth-child(1)');
		if(objPrevButton){
			if(objPrevButton.html().indexOf('images')>0)
			objPrevButton.html('<img alt="previous page" src="../../images/images/buttons/products_previouspage.gif"/>');
		}
		var objPrevButton=$('#lblPager2 a:nth-child(1)');
		alert(objPrevButton.html())
		if(objPrevButton){
			if(objPrevButton.html().indexOf('images')>0)
			objPrevButton.html('<img alt="previous page" src="../../images/images/buttons/products_previouspage.gif"/>');
		}

	}catch(e){alert("here"+e.message)}
*/

		$('.SearchPage span#lblPager img,.SearchPage span#lblPage2 img').each(function(i){
			var src=$(this).attr('src')
			src=src.replace('../../','')
			if($('.SearchPage span#lblPager img').length>1){
				if(i==0 || i==2)
				src=src.replace('products_nextpage.gif','products_previouspage.gif')
			}

			$(this).attr('src',src);

		});
	

	$('.CategoryPage span#lblPager img').each(function(i){
		var src=$(this).attr('src')

		if($('.CategoryPage span#lblPager img').length>1){
			if(i==0)
			src=src.replace('products_nextpage.gif','products_previouspage.gif')
		}

		$(this).attr('src',src);

	});
}


function resizeImage()
{
	var obj = document.getElementById('MainImage');
	if(obj){
		try{
			var objJQ = $('#MainImage');
			zoom('150px','112px','250px','212px',obj);
			objJQ.removeClass('spartanNoShow');
		}catch(e){}
	}

}


function zoom(iWideSmall,iHighSmall,iWideLarge,iHighLarge,whichImage)
{
oW=whichImage.style.width;oH=whichImage.style.height;
if((oW==iWideLarge)||(oH==iHighLarge))
{
nW=iWideSmall;nH=iHighSmall;
}
else
{
nW=iWideLarge;nH=iHighLarge;
}
whichImage.style.width=nW;whichImage.style.height=nH;
}

function minQuantityNotification(){
	try{
	var errorMessage=$('div.WebPageMessageWarning div.Message').html();
	var intMinQty=$('#inQty').attr('value');
	if(errorMessage!=null){
		if(errorMessage.indexOf('Minimum quantity is')>=0){
			$('#minQtyLabel').removeClass('spartanNoShow');
			intMinQty=errorMessage.replace('Minimum quantity is','');
			$('#minQty').text(intMinQty);
		}
	}
		else if(intMinQty>1){
			var minQtyLabel=$('#minQtyLabel').html();
			$('#minQtyLabel').html(minQtyLabel.replace('each',$('#lstUofM').attr("value")));
			$('#minQtyLabel').removeClass('spartanNoShow');
			$('#minQty').text(intMinQty);
		}

		//$('.facilitySubType').hide();
		$('#lstUofM').change( function(){
			var selectedVal=$(this).attr("value");
			if(selectedVal=='Carton10'){
				$('#inQty').attr('value','1');
				$('#minQtyLabel').addClass('spartanNoShow');
			}else if(intMinQty>1){
				$('#inQty').attr('value',intMinQty);
				$('#minQtyLabel').removeClass('spartanNoShow');
			}
		});

	}catch(e){/*alert(e.message)*/};

}

function changeLoginButton(){
	if($('#Header1_LoginStatusControl1_lnkStatus').html()=='Sign Out'){
		$('#LoginControl1_btnDoLogin').attr('src','images/images/buttons/logout.gif');
		$('#LoginControl1_inPassword').attr('value','');
		$('#LoginControl1_btnDoLogin').click(function(){
			location.href="logout.aspx";
			return false;
		});
	}
	$('#LoginControl1_btnDoLogin').removeClass('spartanNoShow');
}

function LoadMenu(){
	var toLoad = parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/TopMenu.aspx #parentMenu';
	var contentArea=$("#nav");
	contentArea.load(toLoad, function(){

			// removing empty <ul> tag created from the dynamic pulled file
			$("#nav ul#parentMenu li ul").each(function(i){
					if($(this).children('li').length==0) $(this).remove();
			});

			var selectedMenu=getCookie('tmenu',1)
			if (selectedMenu=='')
			{
				selectedMenu=1
			}
			$("#nav ul#parentMenu li:nth-child(" + selectedMenu + ")").addClass('current')

			for(z=1;z<=6;z++){
				$("#nav ul#parentMenu li:nth-child(" + z +") ul li").removeClass('current');
			}


			/* setting link for Shop Our Catlog to the Default Product menu page*/

			var productLandingPage=$("#nav ul li:nth-child(2) a").attr('href');
			var objCatalog=$('#homeleft h2 span')
			objCatalog.html('<a href="'+productLandingPage+'" id="btnCatalog">'+objCatalog.html()+'</a>')

			$(".fleft a").click(function(){
				setCookie('tmenu',2)
			});

			
			$(".CategoryListContent a").click(function(){
				setCookie('tmenu',2)
			});
			$("#nav ul li:nth-child(2) ul li a").click(function(){
				setCookie('tmenu',2)
			});
			
			$("#nav ul li:nth-child(3) ul li a").click(function(){
				setCookie('tmenu',3)
			});

			$("#nav ul li:nth-child(4) ul li a").click(function(){
				setCookie('tmenu',4)
			});

			$("#nav ul li:nth-child(5) ul li a").not(':last').click(function(){
				setCookie('tmenu',5)
			});

			$("#nav ul li:nth-child(6) ul li a").click(function(){
				setCookie('tmenu',6)
			});

			// If IE then calling hoverfix function
			if("\v"=="v"){
				try{
					hoverFix();
				}catch(e){}
			}

			if($("#subNav") && selectedMenu>1){
				LoadSubMenu(selectedMenu);
			}
			
			LoadFooterMenu();

	});
}

function LoadSubMenu(parentMenu){
	var toLoad =parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/LeftMenu.aspx?ID='+parentMenu+' #dynSubMenu';
	var contentArea=$("#subNav");
	contentArea.load(toLoad, function(){
		var selectedMenu=getCookie('smenu',1)
		$("#subNav ul#dynSubMenu li").each(function(i){
			if(selectedMenu==1){
					$(this).addClass('current');
					return;
			}else{
				if($(this).attr('id')==selectedMenu){
					$(this).addClass('current');
					return;
				}
			}
		});
	});
}


function LoadFooterMenu(){
	var toLoad = parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/FooterMenu.aspx .footer1Items';
	var contentArea=$("#footerNav1");
	contentArea.load(toLoad, function(){
		$('#footerNav1 li a').not(':first').addClass('navBorder');
		$('#footerNav1 li').removeClass('footer1Items');
		$("#footer").removeClass('spartanNoShow');
	});
}



function CategotyPageDynamicPull(){
	$(".CategoryPage div.SingleProductDisplay,.SearchPage div.SingleProductDisplay").each(function(i){
		var ListPrice=null
		$(this).children('.SingleProductDisplayPrice').children('a').children('br').remove();
		$(this).children('.SingleProductDisplayPrice').children('a').children('.SitePriceDiscounted').wrapInner('<span class="priceValue"></span>');
		$(this).children('.SingleProductDisplayPrice').children('a').children('.SitePriceDiscounted').append(' <span class="priceUnit">Your Price</span>');
		try{
			ListPrice=$(this).children('.SingleProductDisplayPrice').children('a').children('.ListPrice');
			if(ListPrice.text()==""){
			ListPrice=$(this).children('.SingleProductDisplayPrice').children('a');
			}
		}catch(e){}
		var productid=$(this).children('.SingleProductDisplayAddToCartButton').children('a').attr('href');

		productid=productid.substring(productid.lastIndexOf('/')+1);
		productid=productid.substring(0,productid.lastIndexOf('.'));
		$(this).append('<div id="productExtra" class="loading"></div>');
		var toLoad = parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/ProductInfo.aspx?ID='+productid+' #dynInfo';
		var contentArea=$(this).children("#productExtra");
		contentArea.load(toLoad, function(){
			$(this).removeClass('loading');
			try{
				ListPrice.wrapInner('<span class="priceValue"></span>');
				ListPrice.append(' <span class="priceUnit">' + $(this).children('#dynInfo').children('span#hdSpanUoM').children('span#lblHdUoM').text().capitalize()+'</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
			}catch(e){}
		});
	});
}

function FixImagePath(){
	var page=window.location.toString().toLowerCase();
	if(page.indexOf('custom.aspx')>=0){
		$("img").each(function(i){
			var src=$(this).attr('src')
			if(src.indexOf('../uploads/media')>=0){
				$(this).attr('src',src.replace('../uploads/media','uploads/media'));
			}
		});
	}
}

function customFAQ(){
	var strQ='';
	var strA='';
	var objQ=null
	try{
		$("#dlPolicy div").each(function(i){

			objQ=$('#dlPolicy tr:nth-child('+(i+1)+') td a');
			if(objQ.length>1){
				objQ=$('#dlPolicy tr:nth-child('+(i+1)+') td a:first-child');
			}
			strQ=objQ.html();
			objQ.attr('href','#fa'+$(this).attr("id"));
			objQ.wrapInner('<li></li>');
			strA+='<tr><td><h3><a name="fa'+$(this).attr("id")+'"/>'+strQ+'</h3><div id="'+$(this).attr("id")+'" class="text">'+$(this).html()+'</div></td></tr>\n';
			
			$(this).remove();
			$('#dlPolicy tr:nth-child('+(i+1)+') td br').remove();
		});
	}catch(e){}
	if(strA!==''){
		$("#dlPolicy").append('<tbody><tr><td height="10px"></td></tr></tbody><tbody>'+strA+'</tbody>');

	}
}

function customToolTip(){
		$("#txtPONumber").after('<a href="javascript:;" title="This field can be used as a reference for customers who require a Purchase Order number on their invoice."> What is this?</a>');

}

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
function cleanupAccountLinks(){
	$("#Myaccountmenu2_lstMyAccountMenu li a[href=myaccount_WishList.aspx]").hide();
	$("#Myaccountmenu2_lstMyAccountMenu li a[href=myaccount_MailingLists.aspx]").hide();
}

function makeAddressCaptionDynamic(){
	try{
		if($('#ContentColumnAcct span#lblItems').length<=0) return;
		var content=$('#ContentColumnAcct span#lblItems').html();
		var count=content.indexOf('1 ');
		if(count==0) {
			content=content.replace('addresses','address');
			$('#ContentColumnAcct span#lblItems').html(content);
		}
	}catch(e){}

}

function setQuickOrderMinimumQty(){
		$("#tblquickOrder input.FormInput").each(function(i){
			var obj=$(this);
			if(obj.val()==''){
			var productid=$(this).parent().parent().children('td:first').children('span').text();
			$.ajax({
			beforeSend: function(){
			},
			type: 'GET',
			url: parent.location.protocol +'//'+location.hostname+'/SpartanNodusPatch/ProductInfo.aspx',
			data: 'ID='+productid,
			success: function(result){
				//$("#contents").html(result);
				var search='<span id="lblMinimumQty">';
				var fetchStart=result.indexOf(search);
				if(fetchStart>-1){
					fetchStart+=search.length;
					var fetchEndStart=result.indexOf('</span>',fetchStart)
					var minqty=result.substring(fetchStart,fetchEndStart);
					obj.attr('value',minqty);
				}else{
					//obj.attr('value',1);
				}

			},complete: function(){
			//reloadWall('../ajax_get.php','op=wall&start=0&force_relative=1');
				return false;
			}
		});
		}
	});
}
