/*  */
/* Author: Jeffrey Day */
/* Date  : August 2008 */
/*  */
/* Purpose: Tools for use with the alfa.com website built using Websmart */
/*  

CHANGE LOG:

KAB 20110308 - added code to hide portions of the site when viewing in a punchout session.
KAB 20110321 - fixed language dropdown to work within the punchout iframe session.
KAB 20110323 - add Punchout greeting popup functionality
JRD 20110517 - add country display to header
DK  20110602 - added redirect handling to mobile site
KAB 20110805 - removed hardcoded MIT logo from Punchout greeting, to be replaced with client-specific image later.

*/

/* start parms */
var path = location.pathname.substr(0, 4);
var isIE5 = navigator.userAgent.toUpperCase().indexOf("MSIE 5") !== -1;
var targetElementID = "container";
var targetElementStyleOffset = 30; // 58 76 85 wrap container
var ulang = "en", curLang;
var topie6 = 0;
var uShipTo = "";   // populated in loadtools();

// KAB 20091103 - added isIE6 flag
var isIE6 = false;
if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) <= 6) { isIE6 = true; }

// KAB 20110308 - isPunchout and punchoutChecked are set and checked in punchoutDisplay()
var isPunchout = false;
var punchoutChecked = false;

// KAB 20110323 - added for Punchout
var punchoutGreeting = false;

//only if object jQuery exists, call loadtools on document ready
if (typeof jQuery !== "undefined") {
	jQuery(document).ready(loadtools);
	// JRD 20100617 - solve IE7 issue not displaying logon in header by turning cache off for ajax calls
	jQuery.ajaxSetup({
		cache: false
	});
}

/**
 * DK 20110602
 * Added anonymous function downloaded from www.detectmobilebrowser.com to automatically redirect to 
 * the mobile site, when the regular expression is true (user is using a mobile defice). The downloaded 
 * function has been slightly changed, so it doesn't always redirect but instead calls a function, i.e. 
 * mobileRedirect() below. This is to allow users to chose which site to visit.
 */
(function(a,b){if(/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))b()})(navigator.userAgent||navigator.vendor||window.opera, mobileRedirect);

/**
 * DK 20110602
 * The function checks the cookie "AlfaMobile" for it's value. It can be either yes or no. If it's empty it will
 * be set to yes. And if the cookie is yes, the user is redirected to the mobile product search page.
 */
function mobileRedirect()
{
	var siteCookie = getCookie("AlfaMobile");
	
	if(siteCookie == "")
	{
		setCookie("AlfaMobile", "yes", 7);
		siteCookie = "yes";
	}
	
	if(siteCookie == "yes")
	{
		var url = window.location.href;
		var redirectUrl = "";
		redirectUrl = url.match(/^(http|https):\/\/([a-zA-Z:0-9\.]*)\/([a-zA-Z]{2})\//);
		/*
			[0] => http://www.alfa.com:81/en/
			[1] => http
			[2] => www.alfa.com:81
			[3] => en
		*/
		if(redirectUrl == null)
		{
			window.location = url + "en/mo160w.pgm";
		}
		window.location = redirectUrl[0] + 'mo160w.pgm';
	}
}

function loadtools() {

	// KAB 20110323 - check whether to display Punchout Greeting popup
	if (punchoutGreeting) 
	{
		// KAB 20110805 - removed hardcoded MIT logo
		//var greetingdata = '<div id="greetingImage"><img src="http://web.mit.edu/newsoffice/templates/mit/images/footer-logo.gif" /></div>'
		//+ '<div id="greetingText"><span lang="Y" key="">'
		var greetingdata = '<div id="greetingText"><span lang="Y" key="">'
		+ 'Welcome, you have successfully "punched out" to the Supplier WebSite Alfa Aesar - <a href="http://www.alfa.com">http://www.alfa.com</a>.'
		+ '</span></div><div id="greetingButton">';
		greetingdata += '<a href="javascript: disablePopup();"><img src="/' + curLang + '/images/OK.gif" /></a></div>';
		
		// modify look/feel of popup
		jQuery('#popupBox').addClass('punchoutGreeting');
		
		loadPopup(greetingdata);
	}

	// make any changes needed for display in a Punchout session
	punchoutDisplay();

	//retrieves the language from the URL
	getlanguage();

        // SJ retrieve searchtype from cookie
	getsearchtype();

	//DK moved this into the function, otherwise we'll have errors
	checkLogon(); /* pull in login info */

	checkCtry(); /* pull in country selected */
        
	//window.onresize=adjustHeight; /* buggy - bad browser compatibility */
	jQuery(window).resize(function () {
		adjustHeight();
		contentheight();
	}); /* assign adjustHeight to window.resize event */

	//window.onload=adjustHeight;   /* buggy - bad browser compatibility */
	//DK changed from jQuery(window).load()
	jQuery(window).load(function ()  {
		adjustHeight();
	}); /* assign adjustHeight to window.onload event */

	contentheight();
	
	// JEL 20090831  - call before IE6 code, or it will disable part of the menu
	//jQuery('ul.jd_menu').jdMenu();
	
	// JEL 20090831  - check the menu for links with a ref attr starting with "tab",
	// prevent the default action and call a function based on the ref attribute, then navigate the location in the href attribute
	jQuery("div.menu9 a[ref^=tab]").click(function (event) {
		var that = this;
		event.preventDefault();
		setActiveTab(jQuery(that).attr("ref")) ? (window.location = that.href) : false;
	});
	
	makeTabActive();
	
	setFooterYear();
	
	//DK moved up here, to keep it all in one function
	//CLOSING POPUP
	//Click the x event!
	jQuery("#popupBoxClose").click(function () {			
		disablePopup();
		//DK added to hide iframe
		backgroundoverlayhide();
	});		

	// KAB 20110323 - added
	jQuery("#punchoutPopupBoxClose").click(function () {			
		disablePopupPunchout();
		//DK added to hide iframe
		backgroundoverlayhide();
	});		
	

	if (jQuery("#titletag").html() !== null) {
		document.title = jQuery("#titletag").html() + " - Alfa Aesar - A Johnson Matthey Company";
	}

	// JEL 20090824 changed .menu1 to .menu9
	jQuery(".menu9 > ul > li").hover(function () {
		var that = this;
		var id;
		
		// fix the width of the menu items in IE 7 and below
		if ((jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) === "7") || jQuery.browser.opera === true) {
			id = "#" + jQuery(that).attr("id");
			var widest = 0;
			
			// display the hidden list so the widths of the children <li> elements are populated
			jQuery(id + " > ul").css({
				display: "block",
				"vertical-align": "bottom",
				"white-space": "nowrap",
				width: "auto",
				position: "absolute"
			});
			
			// check the <a> elements for the widest one
			jQuery(id + " > ul > li > a").each(function () {
				var thisWidth = jQuery(this).width();
				widest = (thisWidth > widest ? thisWidth : widest);
			});
			//widest += 16;	// padding
			
			// assign all <a> elements the width of the widest one, so they are even
			jQuery(id + " > ul > li  > a").each(function () {
				jQuery(this).width(widest + "px").css("padding-right", "16px");				
			});
			
		}
		
		if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) <= 6) {
			id = "#" + jQuery(that).attr("id");
			jQuery(id + " > ul > li  > a").each(function () {
				jQuery(this).width("205px").css("padding-right", "16px");
			});
			jQuery(id + " > ul").width("205px");
		}
		
		
		/*	JEL - not needed with jdMenu, which does it's own iFrame
		var li_id = jQuery(that).attr("id");
		var ul_elem = "#" + li_id + " ul";
		var position = findPos(document.getElementById(li_id));
		position.top += 44;		
		var options = {
			element: ul_elem,
			top: position.top,
			left: position.left,
			width: 174,
			zindex: 2
		}		
		backgroundoverlay(options);
        */
	},
	function () {
		var that = this;		
		var id = "#" + jQuery(that).attr("id");
		jQuery(id + " > ul").css({
			display: "none"
		});
		
		/*	JEL - not needed with jdMenu, which does it's own iFrame
		var li_id = jQuery(that).attr("id");
		var ul_elem = "#" + li_id + " ul";
		var options = {
			element: ul_elem
		};
		backgroundoverlayhide(options);
*/
	});
	
	// KAB 20100104 - added validation function for header bar search form - there is already click behaviour on
	//	the arrow button and "Advanced Search" link, but not on the form itself when the user simply hits the
	//	enter key
	jQuery('#productSearchForm').submit(function ()
	{
		return headerBarSearch();
	});


	/* KAB 20090929 - moved <select> translation code to its own function, translateDropdowns(), 
		since it was being called here before any spans had been translated, and therefore 
		translating everything into English. */
	/*
	jQuery(".dropdown").each(function (){

		var dropname = jQuery(this).attr("name");
		var dropval = jQuery(this).attr("value");
		var droptxt = jQuery(this).html();
		
		jQuery('select[name="' + dropname + '"] option[value="' + dropval + '"]').text(droptxt);
	});
	*/
	
	// KAB 20091105 - show IE6 MSDS pdf message if we're in IE6, and attach onclick event
	// KAB 20091105 - TEMP - hide IE6 link for all browsers until functionality is done
	/*if (isIE6)
	{
		// show message
		jQuery('#msds_ie6_message').show();
	
		// attach click event
		jQuery('#msds_ie6_message').click(function ()
		{
			// get popup text from include ie6_msds_instr.txt
			if(ulang == '') ulang = 'en';
			var path = "/" + ulang + "/gp140w.pgm";
			jQuery.ajax({
				url: path,
				cache: false,
				data: "task=getpdfmsg",
				success: function (htmldata) {
					loadPopup(htmldata, '450px');
				}
			});
		});
	}*/
	
    
    // JEL 20100114 - added script to check for Chinese users
    // select CAS search if user is Chinese
    // JRD 20101006 - fix page error on country selection page - do not run this ajax when on this page
    //var strLoc = window.location.href

    //document.write("win loc href:"  + "<br/>" + strLoc + "<br/>");
    //document.write(str.substr(strLoc.lastIndexOf("/") + 1) + "<br /><br />");

    if(ulang == '') ulang = 'en';

    jQuery.get("/" + ulang + "/gs140w.pgm", {task: "getShipTo"}, function (rtnDta) {
        uShipTo = rtnDta.toString();
        if (uShipTo === "CN" || uShipTo === "ZH") {
            jQuery("#searchtype [value=CAS]").attr("selected", "selected");
        }
    }, "text");
}


function getlanguage()
{
	ulang = window.location.href;
	ulang = ulang.replace("http://", "");
	ulang = ulang.replace("https://", "");
	var pos = ulang.indexOf("/");
	ulang = ulang.substr(pos + 1, ulang.length - pos);
	pos = ulang.indexOf("/");
	ulang = ulang.substr(0, pos);
	if(ulang == '') ulang = 'en';
}

// set alt title attributes on images and inputs with type=image
// KAB 20091008 - added optional div ID parameter to limit the processing to a 
//	particular container
function setAltTitleAttr(containerID)
{
	//if (containerID === null)
	if(typeof containerID === "undefined")
	{
		//DK added for alt text on images and input type=image
		jQuery("img").each(function () {
			btnimgalttxt("img", jQuery(this).attr("alttxt"));
		});
		
		//get all inputs of type image to set alt and title attribute
		jQuery("input").each(function () {
			if (jQuery(this).attr("type") === "image") {
				btnimgalttxt("input", jQuery(this).attr("alttxt"));
			}
		});
	}
	else
	{
		//DK added for alt text on images and input type=image
		jQuery(containerID + " img").each(function () {
			btnimgalttxt("img", jQuery(this).attr("alttxt"), containerID);
		});
		
		//get all inputs of type image to set alt and title attribute
		jQuery(containerID + " input").each(function () {
			if (jQuery(this).attr("type") === "image") {
				btnimgalttxt("input", jQuery(this).attr("alttxt"), containerID);
			}
		});
	}
}

// set the year in the footer to this year
function setFooterYear()
{
	var mydate = new Date();
	var year = mydate.getFullYear();
	jQuery('#copyyear').html(year);	
}

// used in go160w to enforce a minimum of three characters to search on product search term
function min3Chars() {
	
	jQuery("span.MSDSmsg, span.msg").css('display', 'none');
	
	// don't show the message if nothing is entered
	if (jQuery("#PSvalue").val().length === 0 && jQuery("table#prodsearch input[name=chinesechars]").attr("checked") === true) {
		jQuery("span[key=at_least_one_character]").css("display", "");
		return false;
		
	} else if (jQuery("#PSvalue").val().length === 0 && jQuery("table#prodsearch input[name=chinesechars]").attr("checked") === false 
	           && jQuery("#PSvalue_mlt").val().length === 0) {
		return false;
		
		// JEL 20091111 - if the chinese chars checkbox is checked only at least one character must be input
	} else if (jQuery("#PSvalue").val().length < 3 && jQuery("table#prodsearch input[name=chinesechars]").attr("checked") === false
		   && jQuery("#PSvalue_mlt").val().length === 0) {	
		jQuery("span[key=at_least_three_characters]").css("display", "");
		return false;
	}

	return true;
}

function min6Chars() {
	if (jQuery("#product").val().length < 6 && jQuery("#docsrchtyp option:selected").val() === "MSDS") {
		// JEL 20090903 - min length handled in advancedsearch.js
		return false;
	}

	return true;
}

function productSearch()
{
	// JEL 20091111 - if the chinese chars checkbox is checked only at least one character must be input
	if (jQuery('#value').val().length >= 3 ||
	(jQuery('#value').val().length >= 1 && jQuery("form#productSearchForm input[name=chinesechars]").attr("checked") === true)) {
        if (jQuery("#searchtype").val() === "CAS") {
            // change the value of #srchHow to "EXACT"
        }
		jQuery('#productSearchForm').submit();
		
	} else if (jQuery('#value').val().length === 0 &&
    
	jQuery("form#productSearchForm input[name=chinesechars]").attr("checked") === true) {
    
		var language = jQuery('#languageBox select').val();
		window.location = "/" + language + "/GO160W.pgm?errmsg=min1chars";

	} else {
    
		var language = jQuery('#languageBox select').val();
		window.location = "/" + language + "/GO160W.pgm?errmsg=min3chars";
	}
}

function advancedSearch() {	
	var language = jQuery('#languageBox select').val();
	
	if (jQuery('#value').val().length >= 3) {
		jQuery('#productSearchForm').submit();
		
	} else if (jQuery('#value').val().length === 0) {
		window.location = "/" + language + "/GO160W.pgm";
	} else {
		window.location = "/" + language + "/GO160W.pgm?errmsg=min3chars";
	}
}

// KAB 20100104 - function to handle header bar search form submission, when user presses enter to submit form instead of
//	clicking on arrow button (calls productSearch() function) or "Advanced Search" link (calls advancedSearch() function)
//	- this function is adapted from productSearch()
function headerBarSearch()
{
	// init valid flag
	var headerBarValid = true;

	// if the chinese chars checkbox is checked only at least one character must be input
	if (jQuery('#value').val().length >= 3 ||
	(jQuery('#value').val().length >= 1 && jQuery("form#productSearchForm input[name=chinesechars]").attr("checked") === true)) {
        if (jQuery("#searchtype").val() === "CAS") {
            // change the value of #srchHow to "EXACT"
        }
		headerBarValid = true;
		
	} else if (jQuery('#value').val().length === 0 && jQuery("form#productSearchForm input[name=chinesechars]").attr("checked") === true) {
    
		var language = jQuery('#languageBox select').val();
		window.location = "/" + language + "/GO160W.pgm?errmsg=min1chars";

		headerBarValid = false;

	} else {
    
		var language = jQuery('#languageBox select').val();
		window.location = "/" + language + "/GO160W.pgm?errmsg=min3chars";

		headerBarValid = false;
	}

	return headerBarValid;
}


/* functions */
function switchLanguage(newLang) /* change language */ {
	/*var lang = new String(newLang.options[newLang.selectedIndex].value);
	var page = location.pathname;
	var parm = location.search;
	var redir;
	//DK 2009-10-06: commented out, program not needed to set smurfs for new programs
	//var aPath = path + 'gs120w.pgm?wklang=' + lang;
	//jQuery.get(aPath);
	if((page.substr(0,1) === '/') && (page.substr(3,1) === '/'))
	{
		redir = '/' + lang + '/' + page.substr(4) + parm;

		// KAB 20110321 - changed from parent.location to window.location, so that this works
		//	within the punchout iframe session
		window.location = redir; 
	}*/

	var lang = new String(newLang.options[newLang.selectedIndex].value);
	var page = location.pathname;
	var parm = location.search;
	var pgmName = page.substr(4);
	var redir;

	if(pgmName == '') { pgmName = 'gh100w.pgm'; }
	if(lang == '') { lang = 'en'; }

	redir = '/' + lang + '/' + pgmName + parm;
	parent.location = redir; 
}

function adjustHeight() /* adjust height to fill screen vertically */
{
	if (document.getElementById) {
		var targetElement=document.getElementById(targetElementID),
			documentHeight, totalOffset;
		
		if (targetElement && document.documentElement.offsetHeight &&
		targetElement.offsetHeight && targetElement.offsetTop) {
			documentHeight=document.documentElement.offsetHeight;
			if (targetElement.offsetHeight<documentHeight-targetElement.offsetTop) {
				if (isIE5) {
					totalOffset = targetElement.offsetTop;
				} else {
					totalOffset = targetElement.offsetTop + targetElementStyleOffset;
				}
				targetElement.style.height = String(documentHeight - totalOffset) + 'px';
			}
		}
	}
}

function makeTabActive(defaultTabName) /* make a specific tab active */
{
	var tabName = getActiveTab();
	if ((tabName === '') || (tabName === ' ')) {
		tabName = (defaultTabName) ? defaultTabName : "tab1";
	}
	if (tabName !== "tab0") {
		jQuery("#" + tabName).attr('id', 'nav1');
		
		if (tabName === "tab8")  // change color of titlebar
		{
			//jQuery("#titleBar").css("background-color", "#7ABC3A");
			jQuery("#titleBar").css("background-color", "#599610");
		}
	}
}

function setActiveTab(tabName) /* set the Active tab value in a cookie */
{
	var menu = "menu";
	var days = 365;
	return setCookie(menu, tabName, days) ? false : true;
}

function getActiveTab() /* retrieve the active tab */
{
	var menu = "menu";
	var tabName;
	tabName = getCookie(menu);
	return tabName;
}

function getCookie(c_name) /* read from a cookie */
{
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		
		if (c_start !== -1) { 
			c_start=c_start + c_name.length + 1; 
			c_end = document.cookie.indexOf(";", c_start);
			
			if (c_end === -1) {
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		} 
	}
	return "";
}

function setCookie(NameOfCookie, value, expiredays) /* populate/create cookie path='/'  */
{
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	document.cookie = NameOfCookie + "=" + escape(value) +
		((expiredays === null) ? "" : "; expires=" + ExpireDate.toGMTString()) + "; path=/";
}

function formHandler(form) /* contact page select box to drop to correct section */
{
	var URL = document.form.site.options[document.form.site.selectedIndex].value;
	window.location.href = URL;
}

/*jQuery(document).ready(function () {  jQuery.get(aPath,  function(data) { jQuery("#addressTable").replaceWith(data); }, "html");  }); prepend*/
// KAB 20091018 - added optional ID field for translation after ajax success
function getAddressFields(ID) { /* add address fields to screen */
	var aPath = path + 'gs150w.pgm';
	jQuery.get(aPath, function (data) {
		jQuery("#addressTable").replaceWith(data);
		adjustHeight();
		contentheight();
		
		// KAB 20091018 - added div-specific translation if ID parm is specified
		if(ulang == '') ulang = 'en';
		if (typeof ID !== "undefined") {
			tran_SwitchLang(ulang, '#' + ID);
		}
		
	}, "html");
}

function checkLogon() { /* determine if user is signed in, display name or diplay prompt fields */
	/* CDF commented out temporarily (cookie error)*/    
	var unameVal = jQuery("#uname").val();
	var upassVal = jQuery("#upass").val();
	//aPath = path + 'gs140w.pgm';
	
	//aPath = "https://" + location.hostname + "/" + ulang + "/gs140w.pgm";
	//aPath = "https://" + location.hostname + ":4433/" + location.pathname.substr(1,2) + "/gs140w.pgm";
	//aPath = "http://" + location.hostname + ":81/" + location.pathname.substr(1,2) + "/gs140w.pgm";
	if(ulang == '') ulang = 'en';
  	aPath = "/" + ulang + "/gs140w.pgm";
  	//aPath = "/en/gs140w.pgm";
	
	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "GET",
		data: "uname=" + encodeURI(unameVal) + "&upass=" + encodeURI(upassVal),
		success: function (data){
			var responseObj = data;
			/*jQuery(document).ready(function () {  
		jQuery.post(aPath,  { uname: unameVal, upass:  upassVal }, function(data) { 
			
			try{
				// Create the JSON response as a javascript object
				var responseObj = eval('(' + data + ')');    	    	    	    	
			}
			catch(err)
			{
				return;
			}
		*/
			jQuery("#userLogin").html(responseObj.html); 
			
			if (typeof tran_SwitchLang === "function") { 
                tran_SwitchLang(curLang , "#userLogin");
                
			}

			// KAB 20110308 - check to see if any of this content should be hidden in a Punchout session
			if (typeof punchoutDisplay === "function") { 
                punchoutDisplay();
                
			}
		}
		//	}, "html" );  
	});      
}

function newLogon() { /* determine if user is signed in, display name or diplay prompt fields */
	/* CDF commented out temporarily (cookie error)*/
	var unameVal = jQuery("#uname").val();
	var upassVal = jQuery("#upass").val();
	var unameVal = encodeURIComponent(unameVal);
	var upassVal = encodeURIComponent(upassVal);

	//aPath = path + 'gs140w.pgm';
	if(ulang == '') ulang = 'en';
	aPath = "/" + ulang + "/gs140w.pgm";
	//aPath = "/en/gs140w.pgm";  // JRD 20100716 - fix js error on country selection page
	
	//aPath = "https://" + location.hostname + "/" + ulang + "/gs140w.pgm";
	
	// aPath = 'https://' + location.hostname + path + 'gs140w.pgm';  needs https - will be sending user / pwd 
	
	//DK rewritten to use ajax to get json response using a post request, so the eval function is not being needed
	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "GET",
		data: "uname=" + unameVal + "&upass=" + upassVal,
		success: function (data) {
			// Create the JSON response as a javascript object
			var responseObj = data;
			var loc = window.location.href.toLowerCase();
			/*try{
				responseObj = eval('(' + data + ')');    	    	    	    	    	
			}
			catch(err)
			{			
				return;			
			}*/

			if (responseObj.gotoURL == 'undefined' || responseObj.gotoURL == 'UNDEFINED') {
				responseObj.gotoURL = "";
			}

			if (responseObj.success == true && responseObj.gotoURL != '') {
				window.location.href = responseObj.gotoURL.substr(responseObj.gotoURL.indexOf('/', 10));
				return;
			}

			if (typeof responseObj.success !== "undefined" && responseObj.success === "cemcat") {
				// registration help page
				window.location = "/" + ulang + "/gr110w.pgm?task=cemcat&email=" + responseObj.email;
				
			} else {
				if (responseObj.success === false) {
					window.location.href = "/" + ulang + "/gr100w.pgm?e=y";

				} else {
					// replace login inputs with user's name
					jQuery("#userLogin").html(responseObj.html);
					
					// check the user's language, used to reload the page if different from current language (ulang)
					if (typeof responseObj.lang !== "undefined" && responseObj.lang != "") {
						curLang = responseObj.lang;
					} else {
						curLang = "en";
					}

					tran_SwitchLang(curLang , "#userLogin");
						
					if (loc.match("gr100w.pgm") !== null) {
						window.location.href = "/" + curLang + "/gh100w.pgm";
					} else {
						reloadAfterLogin(curLang);
					}
					
					/* LR 20091124 - replaced with the code above.  Changed the call to reloadAfterLogin, 
					                 which will rebuild URL with user profile(smurf) language.
					tran_SwitchLang(curLang , "#userLogin");
					if (loc.match("gr100w.pgm") !== null) {
						window.location.href = "/" + ulang + "/gh100w.pgm";
					} else {

						reloadpage();
					}
					*/
				}
				//getAddressFields();
			}
		}   // end ajax success
	});
/*  // old login process //
    jQuery.post(aPath, { uname: unameVal, upass:  upassVal }, 
        function(data) {
            // Create the JSON response as a javascript object
            var responseObj;
            try {
                responseObj = eval('(' + data + ')');
                
            } catch(err) {
                return;
            }
            
            if (responseObj.success && responseObj.success === 'cemcat') {
                // registration help page
                window.location = "gr110w.pgm?task=cemcat&email=" + responseObj.email;
            } else {
                jQuery("#userLogin").html(responseObj.html);
                tran_SwitchLang(curLang , "#userLogin");
                
                //getAddressFields();
                
                reloadpage();
            }
        }, "html" );
*/
}

function newSession() /* signoff */
{
	
	// KAB 20091015 - if user has items in cart, give popup message that items in cart will
	//	be lost unless it's saved
	if(ulang == '') ulang = 'en';
	var path = "/" + ulang + "/go180w.pgm";
	jQuery.ajax({
		url: path,
		cache: false,
		data: "task=getcartitems",
		success: function (items) {
			if (items === "0")
			{
				logoff();
			}
			else 
			{
				var htmldata = '<span lang="Y" key="logout_cart_message">'
				+ 'Your shopping cart will be cleared when you log out. Would you like to continue logging out? Click Cancel to go back and save your cart.</span>'
				+ '<br /><br /><center>';
				htmldata += '<a href="javascript: logoff(); disablePopup();"><img src="/' + curLang + '/images/Yes.gif" /></a>';
				htmldata += '&nbsp;<a href="javascript: disablePopup();"><img src="/' + curLang + '/images/Cancel.gif" /></a></center>';
				loadPopup(htmldata);
				tran_SwitchLang(curLang , "#popupBox");
			}
		}
	});
	
	
}

/* KAB 20091015 - logout of the cart - to be called from newSession(), above. This function 
	used to be newSession() until the popup check was implemented. */
function logoff() {
	/* CDF commented out temporarily (cookie error)*/
	//var aPath = path + 'gs140w.pgm?task=new';
	if(ulang == '') ulang = 'en';
	var aPath = "/" + ulang + "/gs140w.pgm";
	
	//aPath = "https://" + location.hostname + "/" + ulang + "/gs140w.pgm?task=new";
	// KAB 20100217 - changed type from POST to GET for performance improvement
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "GET",
		data: "task=new",
		success: function(data){
			var responseObj = data;
			/*jQuery.get(aPath,  
	function(data) { 
		// Create the JSON response as a javascript object
		try{
            var responseObj = eval('(' + data + ')');    	    	    	    	    	
		}
		catch(err)
		{
			return;			
		}	*/	
			
			jQuery("#userLogin").html(responseObj.html);    
			tran_SwitchLang(curLang , "#userLogin");
			getAddressFields();
			
			reloadpage();
		}
	});
	//}, "html");
	
}


function reloadpage() {	
	
	// KAB 20091021 - removed GR150W from first list, covered in third condition
	
	var url = window.location.href.toLowerCase();
	if(ulang == '') ulang = 'en';
	
	if (
	url.indexOf("gl160w") > 0 || 
	url.indexOf("go180w") > 0 || 
	url.indexOf("go170w") > 0 ||
	url.indexOf("go200w") > 0 ||
	url.indexOf("gp100w") > 0 ||
	url.indexOf("gp120w") > 0 ||
	url.indexOf("go190w") > 0 ||
	url.indexOf("gb120w") > 0 ||
	url.indexOf("gb100w") > 0 || 
	url.indexOf("gd150w") > 0 ||
	url.indexOf("gn120aj") > 0 ||
	url.indexOf("gp110w") > 0 ||
	url.indexOf("gl110ah") > 0 
	) {
		window.location.reload();
	}
	// if reloading the search listings page, just hit the URL again, so form does not request
	//	to be resent
	else if ( url.indexOf("gp140w") > 0 )
	{
		window.location.href = url;
	}
	// if reloading a registration page (except first registration page), go to login help (GR100W)
	else if ( url.indexOf("gr") > 0 && url.indexOf("gr110w")<= 0 )
	{
		window.location.href = "/" + ulang + "/GR100W.pgm";
	}
	else
	{
		getcartitems();
		getbulkitems();
	}
}

// this function reloads the page if the language has changed
function reloadAfterLogin(lang) {
	//LR 20091124 - simplified as language must now change to preference on login	
	if(ulang == '') ulang = 'en';

	if (ulang !== lang)
	{
		var url = window.location.href.toLowerCase();
		var langLoc = url.indexOf("/" + ulang + "/");
		
		if (langLoc > 0) {
			url = url.replace("/" + ulang + "/", "/" + lang + "/");	
		}
		window.location.href = url;
		
	} else {
		// KAB 20091211 - added else condition to reload page in certain conditions,
		//	even if language did not switch - Original change by Josh.
		reloadpage();
	}
}

function buildSelectList() /* build work field of checkbox id's that are selected, this field is then read in, in Websmart */
{
	jQuery("#wkCheckList").val("");
	for (var i = 0, ii = document.getElementsByTagName('input').length; i < ii; i++) {
		if (document.getElementsByTagName('input')[i].type === 'checkbox')
			if (document.getElementsByTagName('input')[i].checked === true)
			//if(jQuery("#wkCheckList").val() === '' )
		//jQuery("#wkCheckList").val(document.getElementsByTagName('input')[i].id);
		//else
		jQuery("#wkCheckList").val(jQuery("#wkCheckList").val() + document.getElementsByTagName('input')[i].id + ",");
	}
	//alert(jQuery("#wkCheckList").val());
}

function checkForm(pgm) {

    // prevent the function from continuing if the button is disabled
    if (jQuery("#submit").attr("disabled") === true) {
        return;
    }
    
    jQuery("#submit").attr("disabled", "disabled");
    jQuery("body").css("cursor", "wait");
	
	if (typeof pgm === "undefined") {
		pgm = "";
	}
	
	jQuery(".submitmsg").html("");
	
	formIsValid=true;
	
	if(jQuery("#vfirst").val() === ''){
		formIsValid=false;
		jQuery("#vfirst").addClass("error");
	}
	else jQuery("#vfirst").removeClass("error");
	
	if(jQuery("#vlast").val()===''){
		formIsValid=false;
		jQuery("#vlast").addClass("error");
	}
	else jQuery("#vlast").removeClass("error");
	
	if(jQuery("#vcomp").val()===''){
		formIsValid=false;
		jQuery("#vcomp").addClass("error");
	}
	else jQuery("#vcomp").removeClass("error");
	
	if(jQuery("#vaddr1").val()===''){
		formIsValid=false;
		jQuery("#vaddr1").addClass("error");
	}
	else jQuery("#vaddr1").removeClass("error");
	
	if(jQuery("#vcity").val() === ''){
		formIsValid=false;
		jQuery("#vcity").addClass("error");
	}
	else jQuery("#vcity").removeClass("error");
	
	if(jQuery("#vzip").val() === ''){
		formIsValid=false;
		jQuery("#vzip").addClass("error");
	}
	else jQuery("#vzip").removeClass("error");
	
	if(jQuery("#vcountry").val() === ''){
		formIsValid=false;
		jQuery("#vcountry").addClass("error");
	}
	else jQuery("#vcountry").removeClass("error");
	
	if(jQuery("#vphone").val() === ''){
		formIsValid=false;
		jQuery("#vphone").addClass("error");
	}
	else jQuery("#vphone").removeClass("error");
	
	if(jQuery("#vemail").val() === ''){
		formIsValid=false;
		jQuery("#vemail").addClass("error");
	}
	else jQuery("#vemail").removeClass("error");
	
	if(jQuery("#plsfl").val() == undefined) {
		jQuery("#plsfl").val('');
	}
	
	if(jQuery("#plsrc").val() == undefined) {
		jQuery("#plsrc").val('');
	}
	
	if(formIsValid)
	{
		// KAB 20091210 - added () to .val - was .val, needs to be .val() - was breaking 
		//	landing page emails
		var d = "task=send" +
            "&vfirst=" + jQuery("#vfirst").val() +
            "&vlast=" + jQuery("#vlast").val() +
            "&vtitle=" + jQuery("#vtitle").val() +
		    "&vcomp=" + jQuery("#vcomp").val() +
		    "&vaddr1=" + jQuery("#vaddr1").val() +
		    "&vaddr2=" + jQuery("#vaddr2").val() +
		    "&vcity=" + jQuery("#vcity").val() +
		    "&vcounty=" + jQuery("#vcounty").val() +
		    "&vstate=" + jQuery("#vstate").val() +
		    "&vzip=" + jQuery("#vzip").val() +
		    "&vcountry=" + jQuery("#vcountry").val() +
		    "&vphone=" + jQuery("#vphone").val() +
		    "&vfax=" + jQuery("#vfax").val() +
		    "&vemail=" + jQuery("#vemail").val() +
		    "&vcomments=" + jQuery("#vcomments").val() +
		    "&wkCheckList=" + jQuery("#wkCheckList").val() +
		    "&plsfl=" + jQuery("#plsfl").val() +
		    "&plsrc=" + jQuery("#plsrc").val();

		// KAB 20100217 - changed type from POST to GET for performance improvement
		// JRD 20101005 - urlencode d - retain multi-lingual values
		jQuery.ajax({
			url: pgm,
			type: "GET",
			cache: false,
			data: encodeURI(d),
			success: function (msg) {
				jQuery(".submitmsg").html(msg);
				tran_SwitchLang(curLang, ".submitmsg");

                // re-enable the button            
                jQuery("#submit").attr("disabled", "")
                jQuery("body").css("cursor", "auto");
            },
            error: function () {
                // re-enable the button, even on error
                jQuery("#submit").attr("disabled", "");
                jQuery("body").css("cursor", "auto");
            }
		});
		formIsValid = false;
	}
	// KAB 20091210 - if form is invalid, set cursor back to normal
	else
	{
		jQuery("body").css("cursor", "auto");
	}

	
	return formIsValid;
}

/*function togView()
{
 jQuery(".artlink").toggleClass("hideit");
 adjustHeight();
 
 jQuery(document).ready(function () {  jQuery(".artlink").toggleClass("hideit"); adjustHeight();  });
}*/

/****************** Functions for popup boxes  ***************************************************/

//disabling popup with jQuery magic!
function disablePopup(){			
	jQuery("#popupBox").fadeOut("slow");			
	//jQuery('#popupcontent').html('');

	// KAB 20110323 - remove Punchout Greeting css class (if it was attached) to reset styles
	jQuery("popupBox").removeClass("punchoutGreeting");
}

//loading popup with jQuery magic!
// width, height, timeout values optional
function loadPopup(htmldata, width, height, timeout){
	
	if (typeof width !== "undefined") {
		if(width > 0){
			jQuery("#popupBox").css("width", width);
		}
	} else {
		jQuery("#popupBox").css("width", "");
	}
	
	if (typeof height !== "undefined") {
		if(height > 0){
			jQuery("#popupBox").css("height", height);
		}
	} else {
		jQuery("#popupBox").css("height", "");
	}
	
	jQuery('#minipopupcontent').html(htmldata);
	
	tran_SwitchLang(curLang , "#minipopupcontent");
	
	//DK added fix for IE6
	if (jQuery.browser.msie === true && jQuery.browser.version.substr(0,1) == 6) {
		jQuery("#popupBoxClose, #popheader").css({
			"display":"inline"
		});
		jQuery("#popupBox").css({
			position: "absolute"
		});		
	}
	
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = jQuery("#popupBox").height();
	var popupWidth = jQuery("#popupBox").width();
	
	//DK setting header width and display (fix for IE)
	jQuery("#popheader").css({
		"width": popupWidth + "px",
		"display": "block"
	});
	
	//centering
	jQuery("#popupBox").css({
		"top": windowHeight/2 - popupHeight/2,
		"left": windowWidth/2 - popupWidth/2
	});			
	
	//DK position:fixed not available in IE6, added scrolling event to keep popup in place
	if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) == 6) {
		var topnew = 0;
		topie6 = jQuery("#popupBox").css("top");
		topie6 = topie6.replace(/px/, "");
		topie6 = topie6 - 1 + 1;
		jQuery(window).scroll(function () {
			topnew = document.documentElement.scrollTop + topie6;
			jQuery("#popupBox").css({
				"top": topnew + "px"
			});
		});
	}
	
	jQuery("#popupBox").fadeIn("slow");
	
	if (timeout !== undefined){
		timer = window.setTimeout("disablePopup();", timeout);					
	}
}




function capitalizeDrop(id, cls)
{
	//DK added option to select drop down using a class instead of an id
	var selector = "";
	if(typeof cls === "undefined")
	{
		selector = "#" + id;
	}
	else
	{
		selector = "." + cls;
	}
	jQuery(selector+' option').each(function()
	{
		value = jQuery(this).html();				
		jQuery(this).html(capitalizeMe(value));
	});
}

function capitalizeMe(val) {
	//val = obj.value;
	newVal = '';
	val = val.toLowerCase();
	val = val.split(' ');
	for(var c = 0, cc = val.length; c < cc; c++) {
		newVal += val[c].substring(0,1).toUpperCase() +
		val[c].substring(1,val[c].length) + ' ';
	}
	//obj.value = newVal;
	return newVal;
}

//DK sets alt and title attribute
// KAB 20091008 - added container ID as optional third parm
function btnimgalttxt(btnimgtype, classname, containerID){
	
	var selector = "";
	//if (containerID === null)
	if(typeof containerID === "undefined")
	{
		selector = btnimgtype + '[alttxt="' + classname + '"]';
	}
	else
	{
		selector = containerID + ' ' + btnimgtype + '[alttxt="' + classname + '"]';
	}
	
	var spansel = "span." + classname;
	jQuery(selector).attr("alt", jQuery(spansel).html()).attr("title", jQuery(spansel).html());
}


//DK added to reset the content height
function contentheight()
{
	if(document.getElementById("content") !== null)
	{
		var contenth = document.getElementById("content").offsetHeight + 5;
		var containerh = document.getElementById("container").offsetHeight;
		
		//viewport height
		var height = jQuery(window).height();
		
		var containertop = document.getElementById("container").offsetTop;
		
		if((containerh + containertop) < height)
		{
			if(contenth > containerh)
			{
				document.getElementById("container").style.height = contenth + "px";
			}
		}
		else
		{
			document.getElementById("container").style.height = "";
		}
	}
}

function backgroundoverlay (options) {
	var f_opacity;
	var f_contentwidth;
	var f_contentheight;
	
	if (typeof options.element !== "string") {
		options.element = "body";
	}
	
	if (typeof options.opacity !== "number") {
		options.opacity = 0;
	}
	
	if (typeof options.background !== "boolean") {
		options.background = false;
	}
	
	if (typeof options.left !== "number") {
		options.left = 0;
	}
	
	if (typeof options.top !== "number") {
		options.top = 0;
	}
	
	if (typeof options.width !== "number") {
		options.width = 0;
	}
	
	if (typeof options.size !== "string") {
		options.size = options.element;
	}
	
	if (typeof options.zindex !== "number") {
		options.zindex = 100;
	}
	
	f_opacity = 0;
	if (options.opacity > 0) {
		f_opacity = options.opacity / 100;
	}
	
	f_contentwidth = jQuery(options.size).width() + "px";
	f_contentheight = jQuery(options.size).height() + "px";
	
	if (options.width > 0) {
		f_contentwidth = options.width + "px";
	}
	
	if (options.element === "body" || options.size === "body") {
		f_contentheight = (jQuery("#wrap").height() + 35) + "px";
	}
	
	if (options.background === true) {
		jQuery("body").append("<div id=\"iframebackground\"></div>");
		
		jQuery("#iframebackground").css({
			position: "absolute",
			top: "0px",
			left: "0px",
			"background-color":"#000000",
			"z-index": "101",
			display: "block",
			width: f_contentwidth,
			height: f_contentheight,
			opacity: f_opacity,
			filter:"alpha(opacity=" + options.opacity + ")"
		});
	}
	
	if (options.element !== "body") {
		jQuery(options.element).css({"z-index":"105"});
	}
	
	//DK added filter:mask() to iframeoverlay, no need for empty.html page for IE
	//if (jQuery.browser.msie === true) {// && jQuery.browser.version.substr(0,1)>7) {
	//	jQuery("body").append("<iframe id=\"iframeoverlay\" src=\"/en/html/empty.html\" frameborder=\"0\" scrolling=\"no\" allowtransparency=\"true\"></iframe>");
	//} else {
	jQuery("body").append("<iframe id=\"iframeoverlay\" src=\"javascript:void(0);\" frameborder=\"0\" scrolling=\"no\"></iframe>");
	//}
	
	jQuery("#iframeoverlay").css({
		position: "absolute",
		top: options.top,
		left: options.left,
		"z-index": options.zindex,
		display: "block",
		width: f_contentwidth,
		height: f_contentheight,
		filter:"mask()"
	});
	
	if (jQuery.browser.msie === true) {// && jQuery.browser.version.substr(0,1)>7) {
		//jQuery("#iframeoverlay").css({ filter: "mask" });
	}
}

function findPos(obj)
{
	var curleft = 0, curtop = 0;
	if(obj.offsetParent)
	{
		do{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj == obj.offsetParent);
		return {left:curleft, top:curtop};
	}
}

function backgroundoverlayhide(options)
{
	if(typeof options !== "undefined")
	{
		if(typeof options.element === "string")
		{
			jQuery(options.element).css({"z-index":""});
		}
	}
	jQuery("#iframeoverlay, #iframebackground").remove();
}

/* translate <select> elements that are in this form, using span translation:
<select name="myselect">
  <option value="all">all orders</option>
  <option value="web">web orders only</option>
  <option value="nweb">non-web orders only</option>
</select>
<span lang="Y" key="all_orders" class="hideit dropdown" name="myselect" value="all">all orders</span>
<span lang="Y" key="web_orders" class="hideit dropdown" name="myselect" value="web">web orders only</span>
<span lang="Y" key="nonweb_orders" class="hideit dropdown" name="myselect" value="nweb">non-web orders only</span> 
*/
function translateDropdowns()
{
	jQuery(".dropdown").each(function (){
		
		var dropname = jQuery(this).attr("name");
		var dropval = jQuery(this).attr("value");
		var droptxt = jQuery(this).html();
		
		// replace English option text with translated text
		jQuery('select[name="' + dropname + '"] option[value="' + dropval + '"]').text(droptxt);
	});
	
}

/* dayjr 2010.02.11 - this is a handy tool to limit the text entered into a textarea */
function limitText(field, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// else 
		// otherwise, update 'characters left' counter
		// countfield.value = maxlimit - field.value.length;
}

function stripTags(thisValue) {
	var regexHTML = /<\S[^>]*>/g;	// regex to find HTML Tags
	var regexEnt  = /&[^\s]*;/;		// &[^\s]*;
   	thisValue = thisValue.replace(regexHTML, "");
   	thisValue = thisValue.replace(regexEnt, "");
   	return thisValue;
}


// KAB 20110308 - Change the appearance of the site for Punchout sessions. This function is called when the page is loaded
//	and is also called for ajax content (passed in the "container" parm).
function punchoutDisplay()
{
	if(ulang == '') ulang = 'en';
	// check whether we are in a punchout session - only do this once, even though this function is called several times
	if (punchoutChecked == false)
	{
		jQuery.ajax({
			url: "/en/go247w.pgm",
			cache: false,
			success: function (response) {
				
				if (response == "Y") isPunchout = true;

				punchoutChecked = true;
			}
		});

	}

	// if we have determined, at some point, that we are in a Punchout session, make the following manipulations
	if (isPunchout)
	{
				// hide My Account tab
				jQuery('.tabMA').css('visibility', 'hidden');

				// hide logout link
				jQuery('#loggedIn a').css('visibility', 'hidden');

				// hide Add to Favourites links
				jQuery('[id^="fav"], .add_to_favourites').hide();

				// hide the Save Cart section of the cart page
				jQuery('#savecart').closest('td').css('visibility', 'hidden');

				// hide the Save Bulk Quote section of the bulk quote requst page
				jQuery('#savediv').css('visibility', 'hidden');
	}
}


function checkCtry() {
	if(ulang == '') ulang = 'en';
	aPath = "/" + ulang + "/gs342w.pgm";
  	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "html",
		type: "GET",
		success: function (html){
			jQuery("#countryBox").html(html);
			//window.location.reload();
		}
	});
}

function switchCtry() {
	var ctryCode = jQuery("#selectCtry :selected").val();
	if(ulang == '') ulang = 'en';
	aPath = "/" + ulang + "/gs342w.pgm";
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "html",
		type: "GET",
		data: "task=switchctry&ctryCode=" + ctryCode,
		success: function (html){
			window.location.reload();
		}
	});
}

//Reload Page function for Premier site
// renamed it as reloadppage
function reloadppage() {	
	
	var url = window.location.href.toLowerCase();	
	
	if (
	url.indexOf("pl160w") > 0 || 
	url.indexOf("po180w") > 0 || 
	url.indexOf("po170w") > 0 ||
	url.indexOf("po200w") > 0 ||
	url.indexOf("pp100w") > 0 ||
	url.indexOf("pp120w") > 0 ||
	url.indexOf("po190w") > 0 ||
	url.indexOf("pb120w") > 0 ||
	url.indexOf("pb100w") > 0 || 
	url.indexOf("pd150w") > 0 ||
	url.indexOf("pp110w") > 0 
	
	) {
		window.location.reload();
	}
	// if reloading the search listings page, just hit the URL again, so form does not request
	//	to be resent
	else if ( url.indexOf("pp140w") > 0 )
	{
		window.location.href = url;
	}
	
	else
	{
		getcartitems();
		getbulkitems();
	}
}


function seoTrackNonPage(thisObj) {
	var url = window.location.pathname.toLowerCase() + window.location.search.toLowerCase();
	//var litCatName = 'Literature ' + jQuery("#litCatName").val();
	var objPath = jQuery(thisObj).attr("href");

	if ( url.indexOf("gl110ah") > 0 ) { // track literature pdf
		_gaq.push(['_trackEvent', 'PDF', 'Download', objPath]);

	}
}

// SJ The following functions are added to save the search type selection  
function savesrchtyp(seltyp) /* change language */ {
	var typ = new String(seltyp.options[seltyp.selectedIndex].value);
	setCookie("searchtype", typ, 1);
	
}

function getsearchtype()
{
	var typ = getCookie("searchtype");	
	jQuery("#searchtype option[value="+typ+"]").attr("selected", "selected");
}

