/*  */
/* Author: Jeffrey Day */
/* Date  : August 2008 */
/*  */
/* Purpose: Tools for use with the alfa.com website built using Websmart */
/*  */

/* 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;


// KAB 20091103 - added isIE6 flag
var isIE6 = false;
if (jQuery.browser.msie === true && jQuery.browser.version.substr(0, 1) <= 6) { isIE6 = true; }


//only if object jQuery exists, call loadtools on document ready
if (typeof jQuery !== "undefined") {
	jQuery(document).ready(loadtools);
}

function loadtools() {
	
	//get's the language from the URL
	getlanguage();
	
	//DK moved this into the function, otherwise we'll have errors
	checkLogon(); /* pull in login info */
	
	//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();
	});		
	
	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
			var path = "/" + ulang + "/gp140w.pgm";
			jQuery.ajax({
				url: path,
				cache: false,
				data: "task=getpdfmsg",
				success: function (htmldata) {
					loadPopup(htmldata, '450px');
				}
			});
		});
	}*/
	
}


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);
}

// 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) {
		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("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;
		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 (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";
    aPath = "/" + ulang + "/gs140w.pgm";
	
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "POST",
		data: "uname=" + unameVal + "&upass=" + 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");
			}
		}
		//	}, "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();
	//aPath = path + 'gs140w.pgm';
	aPath = "/" + ulang + "/gs140w.pgm";
	
	//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
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "POST",
		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 (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
	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';
	var aPath = "/" + ulang + "/gs140w.pgm";
	
	//aPath = "https://" + location.hostname + "/" + ulang + "/gs140w.pgm?task=new";
	jQuery.ajax({
		url: aPath,
		cache: false,
		dataType: "json",
		type: "POST",
		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 (
	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 !== 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();
		
		jQuery.ajax({
			url: pgm,
			type: "post",
			cache: false,
			data: 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('');
}

//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;
}