//window.onload = initialize;
window.addEvent('domready', initialize);
//stop enter from submitting form
//un-remark to capture the enter key and stop form submissions from taking place on enter press
document.onkeypress = stopRKey;

function initialize(){
	//stuff that needs to run at page load time goes here
	//gPageID is used for page specific initializations
	//if category load subcategories and items...
	if (gPageID==="category"){
		//Test for cookie support
		testForCookies();
		//Subcategories)
		sendAJAXRequest("", gRoot+"categoryDetail.php", encodeURIComponent("subcategories"), "&categoryID="+encodeURIComponent(gCategoryID)+"&parentID="+encodeURIComponent(gParentID)+"&currentpage="+gCategoryPage, '', "subcategories");
		//Items
		sendAJAXRequest("", gRoot+"categoryDetail.php", encodeURIComponent("items"), "&categoryID="+encodeURIComponent(gCategoryID)+"&parentID="+encodeURIComponent(gParentID)+"&currentpage="+gItemPage, '', "items");
	}

	if (gPageID==="search"){
		//Test for cookie support
		testForCookies();
		//Subcategories)
		sendAJAXRequest("", gRoot+"searchDetail.php", encodeURIComponent("subcategories"), "&searchtext="+encodeURIComponent(gSearchText), '', "subcategories");
		//Items
		sendAJAXRequest("", gRoot+"searchDetail.php", encodeURIComponent("items"), "&searchtext="+encodeURIComponent(gSearchText), '', "items");
	}

	if (gPageID==="item"){
		//Test for cookie support
		testForCookies();
		if (gShowCategoryItems && gCategoryID!=''){
			//Items
			sendAJAXRequest("", gRoot+"categoryDetail.php", encodeURIComponent("items"), "&categoryID="+encodeURIComponent(gCategoryID)+"&currentpage="+gItemPage, '', "items");
		}
	}

	if (gPageID==="inquiry"){
		//Test for cookie support
		testForCookies();
		CreatePopupPanel("732px");
	}

	if (gPageID==="login"){
		//Test for cookie support
		testForCookies();
	}

	if (gPageID==="home"){
		if(HOME_SLIDESHOW){
			blendImages('slideshow', 30, 3000);
		}
	}
	customInit();
	//mootools link effects
	enableEffects();
	CreateCartPanel();
}
function testForCookies(){
	sendAJAXRequest("", gRoot+"cookieTest.php", "", "", "", "cookiemessage");
}

function setAutoLogout(destination, duration){
	var stmt="autoRedirect('"+destination+"')";
	return setTimeout(stmt, duration*1000);
}

function autoRedirect(destination) {
	window.location=destination;
}

function resetTimer(timer, destination, duration){
	clearTimeout(timer);
	timer=setAutoLogout(destination, duration);
	return timer;
}

function setCookie(name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=name + "=" + value;
}
function getCookie(name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==name)
		{
		return unescape(y);
		}
	}
}

function enableEffects() {
//mootools efects for newly loaded elements
//change color codes in accordance with CSS
$each($$('.fade'), function(el) {
			var morph = new Fx.Morph(el,{ 'duration':'500', 'link':'cancel' });
			el.addEvents({
				'mouseenter' : function() { morph.start({ 'color':FADE_COLOR })},
				'mouseleave' : function() { morph.start({ 'color':LINK_COLOR })}
			});
		});
$each($$('.pagelink'), function(el) {
			var morph = new Fx.Morph(el,{ 'duration':'500', 'link':'cancel' });
			el.addEvents({
				'mouseenter' : function() { morph.start({ 'color':FADE_COLOR,'background-color':MENU_FADE_COLOR,'border-color':FADE_COLOR }) },
				'mouseleave' : function() { morph.start({ 'color':LINK_COLOR,'background-color':PAGE_BACKGR,'border-color':PAGE_BORDER }) }
			});
		});
		$each($$('.fademenu'), function(el) {
			var morph = new Fx.Morph(el,{ 'duration':'500', 'link':'cancel' });
			el.addEvents({
				'mouseenter' : function() { morph.start({ 'color':MENU_FADE_COLOR }) },
				'mouseleave' : function() { morph.start({ 'color':MENU_LINK_COLOR }) }
			});
		});

		$each($$('.fadecat'), function(el) {
			var morph = new Fx.Morph(el,{ 'duration':'500', 'link':'cancel' });
			el.addEvents({
				'mouseenter' : function() { morph.start({ 'color':FADE_COLOR,'background-color':MENU_FADE_COLOR }) },
				'mouseleave' : function() { morph.start({ 'color':LINK_COLOR,'background-color':MENU_LINK_COLOR }) }
			});
		});
}
function NewWindow(mypage,myname,w,h,pos,infocus) {
	if(pos=="random"){myleft=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=="center"){myleft=(screen.width)?(screen.width-w)/2:100;mytop=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!='center' && pos!="random") || pos==null){myleft=0;mytop=20}
	settings="width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes";win=window.open(mypage,myname,settings);
	win.focus();
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/*
 * Original from: http://brainerror.net/scripts/javascript/blendtrans/demo.html
 *
 * Edits by ASC:
 *   - Removed unnecessary OO code that caused MSIE to choke
 *   - Added pause between setting bg image and setting opacity to zero to
 *     prevent MSIE image flash
 *   - Increased opacity check argument to 103 for completely smooth fade
 *
 */

//find next image
function nextImage(o) {
    do o = o.nextSibling;
    while(o && o.tagName != 'IMG');
    return o;
}

//find first image inside an element
function firstChildImage(o) {

    o = o.firstChild;

    while(o && o.tagName != 'IMG') {
        o = o.nextSibling;
    }

    return o;
}

//set the opacity of an element to a specified value
function setOpacity(obj, o) {

    obj.style.opacity = (o / 100);
    obj.style.MozOpacity = (o / 100);
    obj.style.KhtmlOpacity = (o / 100);
    obj.style.filter = 'alpha(opacity=' + o + ')';
}

//make image invisible and set next one as current image
function getNextImage(image) {

    if (next = nextImage(image)) {
	image.style.display = 'none';
	image.style.zIndex = 0;

	next.style.display = 'block';
	next.style.zIndex = 100;

    } else {
	//if there is not a next image, get the first image again
	next = firstChildImage(image.parentNode);
    }

    return next;
}

//set default values for parameters and starting image
function blendImages(id, speed, pause, caption) {

    if(speed == null) {
        speed = 30;
    }

    if(pause == null) {
        pause = 2500;
    }

    var blend = document.getElementById(id);

    var image = firstChildImage(blend);

    startBlending(image, speed, pause, caption);
}

//make image a block-element and set the caption
function startBlending(image, speed, pause, caption) {

    image.style.display = 'block';

    if(caption != null) {
	document.getElementById(caption).innerHTML = image.alt;
    }

    continueFadeImage(image, 0, speed, pause, caption);
}

// ASC: copied from http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm
function pausecomp(millis) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
}

//set an increased opacity and check if the image is done blending
function continueFadeImage(image, opacity, speed, pause, caption) {

    opacity = opacity + 3;

    if (opacity < 103) {

	setTimeout(function() {fadeImage(image, opacity, speed, pause, caption)}, speed);

    } else {
	//if the image is done, set it to the background and make it transparent
	image.parentNode.style.backgroundImage = "url("+image.src+")";

	// ASC: pause 1sec here to prevent MSIE image flash ...
	var paws=pause-1000;
	if (paws < 0 ) {
		paws = 0;
	}
	pausecomp(1000);

	setOpacity(image,0);
	//get the next image and start blending it again
	image = getNextImage(image);
	setTimeout(function() {startBlending(image, speed, pause, caption)}, paws);
    }
}
//set the opacity to a new value and continue the fading
function fadeImage(image, opacity, speed, pause, caption) {
    setOpacity(image,opacity);
    continueFadeImage(image, opacity, speed, pause, caption);
}
function initslideshow() {
       blendImages('slideshow', 100, 2000);
}
function strtolower_utf8($inputString) {
    $outputString    = utf8_decode($inputString);
    $outputString    = strtolower($outputString);
    $outputString    = utf8_encode($outputString);
    return $outputString;
}
//stop enter key from submitting form
function stopRKey(evt) {
	  var evt = (evt) ? evt : ((event) ? event : null);
	  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}
//create AJAX request object
function createXMLHttpRequest() {
	var ua;
	if(window.XMLHttpRequest) {
		try {
			ua = new XMLHttpRequest();
		}
		catch(e) {
			ua = false;
		}
	} else if(window.ActiveXObject) {
		try {
			ua = new ActiveXObject("MSXML2.XMLHTTP.6.0");
		}
		catch (e) {
			try {
			   ua = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			}
			catch (e) {
				try {
					ua = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e) {
					ua = false;
				}
			}
		}
	}
	return ua;
}

//Send AJAX Request
function sendAJAXRequest(frm, file, action, additional, handler, divId, responseParams) {
	//frm: form data to process
	//file: php script to call
	//action: typically used by the php script for control.  passed as a discrete value (&action=value) should be uri encoded
	//additional: additional parameters in "&name=value&name2=value2" format. Values should be uri encoded.
	//handler: function to handle the response. This is a function, not a string, may be null
	//divId: the ID ofthe div to update
	//alert(frm+"\n"+file+"\n"+action+"\n"+additional+"\n"+divId+"\n"+responseParams+"\n");
	//get new XML HTTP object
	AJAXReq=createXMLHttpRequest();
	//get handler function - handler must be an existing function that accepts the request as a parameter
	var handlerFunction = getReadyStateHandler(AJAXReq, handler, divId, responseParams);
	//we don't want the beowser to cache these requests
	var rnd982g = Math.random();
	var str = "";
	var params = "";
	//with form data
	params='action='+action+'&siteRoot='+gRoot+'&rnd982g='+rnd982g+additional;
	if (frm != '') {
		if (str = getForm(frm)) {
			params += '&'+str;
		}
	}
	//alert (params);
	AJAXReq.open('POST', file, true);
	AJAXReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // need a different type if no form data?
	//AJAXReq.setRequestHeader("Content-length", params.length);
	//AJAXReq.setRequestHeader("Connection", "close");
	AJAXReq.onreadystatechange = handlerFunction;
	AJAXReq.send(params);
	return false;
}

//returns a generic function to catch the response.
//responseXmlHandler needs to be an existing function
function getReadyStateHandler(req, responseXmlHandler, divId, responseParams) {
    // Return an anonymous function that listens to the
    // XMLHttpRequest instance
    return function () {
    // If the request's status is "complete"
        if (req.readyState == 4) {
            // Check that a successful server response was received
            if (req.status == 200) {
                // Pass the XML payload of the response to the
                // handler function if provided, else oput the response text directly
				if (typeof responseXmlHandler === 'function') {
                	responseXmlHandler(req, divId, responseParams);
				}
				else {
					//alert (req.responseText);
					document.getElementById(divId).innerHTML = req.responseText;
					postAJAX();
				}
            }
			else {
				document.getElementById("AJAXError").innerHTML = "HTTP error: "+req.status;
			}
        }
    }
}

//post AJAX apply effects once the new content is in the browser
function postAJAX(){
	enableEffects();
	customPostAJAX();
}

//specific response functions for AJAX requests
function responseAddToCart (req, divId, responseParams) {
	var errorText = '';
	var xmlDoc = req.responseXML;
	document.getElementById(divId).innerHTML=''; // get rid of current message
	//alert (req.responseText);
	//we validate the quantity when addingto the cart.
	var errors = xmlDoc.getElementsByTagName('error');
	if (errors.length>0) {
		errorText = getNodeValue(errors[0],"errormssg");
		//addmssg is the id of the element to hold the response
		qtyError = document.getElementById("addmssg");
		var err=document.createElement('p');
		err.className="error";
		err.appendChild(document.createTextNode(errorText));
		qtyError.appendChild(err);
	}
	else {
		//no errors
		var data = xmlDoc.getElementsByTagName('data')[0]; // get data
		//data we need
		var mssgText=getNodeValue(data,"addmssg");
		var itemId =getNodeValue(data,"itemid");
		var quantity=getNodeValue(data,"quantity");
		var viewLink=getNodeValue(data,"viewlink");
		var viewLinkText=getNodeValue(data,"viewlinktext");
		//update addmssg div
		var addMssg = document.getElementById(divId);
		var mssg=document.createElement('p');
		mssg.appendChild(document.createTextNode(mssgText));
		addMssg.appendChild(mssg);
		var hlink=document.createElement('a');
		if(window.addEventListener){
			hlink.addEventListener('click',DisplayCartPanelEvent,false);
		}
		else {
			hlink.attachEvent('onclick', DisplayCartPanelEvent); // this is for IE
		}
		hlink.appendChild(document.createTextNode(viewLinkText));
		hlink.className="fade";
		addMssg.appendChild(hlink);
		//update card in masthead
		displayMastheadInfo ("cart", "", "cart");
	}
	postAJAX();
}
//send document - writes to a queue for paperless office processing in MAS 90
function responseSendDocument (req, divId, responseParams) {
	var errorText = '';
	var xmlDoc = req.responseXML;
	document.getElementById(divId).innerHTML=''; // get rid of current message
	//alert (req.responseText);
	var errors = xmlDoc.getElementsByTagName('error');
	if (errors.length>0) {
		errorText = getNodeValue(errors[0],"errormssg");
		//addmssg is the id of the element to hold the response
		errorElement = document.getElementById(divId);
		errorElement.innerHTML=errorText;
		errorElement.className="error";
	}
	else {
		//no errors
		var data = xmlDoc.getElementsByTagName('data')[0]; // get data
		//data we need
		var mssgText=getNodeValue(data,"message");
		//update addmssg div
		var mssgElement = document.getElementById(divId);
		mssgElement.innerHTML=mssgText;
	}
	postAJAX();
}
//Add to maillist response - requires form field ids to match, etc...
function responseAddToMaillist (req, divId) {
	var errorText = '';
	var xmlDoc = req.responseXML;
	document.getElementById(divId).innerHTML=''; // get rid of current message
	//alert (req.responseText);
	//we validate the quantity when addingto the cart.
	var data = xmlDoc.getElementsByTagName("data")[0]; // get data
	var mssgText=getNodeValue(data,"addmssg");
	var errors = xmlDoc.getElementsByTagName("error")[0];
	var errorText = getNodeValue(errors,"errormssg");
	var emailError = getNodeValue(errors,"emailerror");
	var firstnameError = getNodeValue(errors,"firstnameerror");
	var lastnameError = getNodeValue(errors,"lastnameerror");
	if (emailError==1 || lastnameError==1 || firstnameError==1) {
		if (emailError==1){
			document.getElementById("EmailAddress").style.backgroundColor=ERROR_BACKGROUND_COLOR;
		}
		else {
			document.getElementById("EmailAddress").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		}
		if (firstnameError==1){
			document.getElementById("FirstName").style.backgroundColor=ERROR_BACKGROUND_COLOR;
		}
		else {
			document.getElementById("FirstName").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		}
		if (lastnameError==1){
			document.getElementById("LastName").style.backgroundColor=ERROR_BACKGROUND_COLOR;
		}
		else {
			document.getElementById("LastName").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		}
		document.getElementById(divId).className="error";
		document.getElementById(divId).innerHTML=errorText;
	}
	else {	//no errors
		document.getElementById(divId).className = "";
		document.getElementById(divId).innerHTML=mssgText;
		document.getElementById("EmailAddress").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		document.getElementById("EmailAddress").value='';
		document.getElementById("FirstName").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		document.getElementById("FirstName").value='';
		document.getElementById("LastName").style.backgroundColor=INPUT_BACKGROUND_COLOR;
		document.getElementById("LastName").value='';
	}
}

//response handler for displaying shopping cart
function responseDisplayCart (req, divId, responseParams) {
	var action=responseParams.action;
	var clickto=responseParams.clickto;
	//if going to checkout from shopping cart, we've updated the cart - go to the checkout page...
	if (action=='checkout') {
		window.location=clickto;
	}
	//alert (action+' '+clickto);
	document.getElementById(divId).innerHTML = req.responseText;
	//transfer totals from cart to masthead.
	displayMastheadInfo ("cart", "", "cart");
	postAJAX();
	document.getElementById('loadingmask').style.visibility = 'hidden';
}

function displayMastheadInfo (action, additional, divId) {
	sendAJAXRequest('', gRoot+'displayMastheadInfo.php', action, additional, '', divId, '');
}

//create the YUI dialog box to display the shopping cart
function CreateCartPanel() {
	YAHOO.namespace("c9.container");
	YAHOO.util.Event.onDOMReady(function () {
		YAHOO.c9.container.CartPanel = new YAHOO.widget.Panel("CartPanel", {
			width:"760px",
			visible:false,
			modal:true,
			close:true,
			fixedcenter: true,
			constraintoviewport:false,
			draggable:true,
			underlay:"shadow",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		} );
		YAHOO.c9.container.CartPanel.setHeader('<div class="left"><h2>'+CART_TITLE+'</h2></div><div class="right"></div>');
		YAHOO.c9.container.CartPanel.setBody('<div id="cartbody"><div style="height:500px;"></div></div>');
		YAHOO.c9.container.CartPanel.setFooter('<div class="left"><p>[<a class="fade" onclick="HideCartPanel();">Close Window</a>]</p></div><div class="right"></div>');
		YAHOO.c9.container.CartPanel.render("cartpanel");
		YAHOO.util.Event.addListener("closemessage", "click", YAHOO.c9.container.CartPanel.hide, YAHOO.c9.container.CartPanel, true);
	});
}

//display shopping cart
function DisplayCartPanelEvent(e){
	DisplayCartPanel();
}

function DisplayCartPanel(mainFrm,action,extra) {

	if (action == null){
   		action = 'display';
 	}
	if (mainFrm == null) {
		mainFrm = '';
	}
	if (extra == null) {
		extra = '';
	}

	var additional='';
	YAHOO.c9.container.CartPanel.show();
	//there might be stuff in here from a previus display, so replace the inner html with the loading graphic
	var cartbodyDiv = document.getElementById("cartbody");
	//if updating, don't replace the innerHTML, because it will wack the form in IE
	if (action == 'update') {document.getElementById('loadingmask').style.visibility = 'visible';}
	if (action == 'display') {cartbodyDiv.innerHTML='<img src="'+gRoot+'images/loading.gif" class="loading" />';}
	if (action == "delete") {
		additional="&itemID="+extra;
	}
	var responseParams = {action:action, clickto:extra};
	sendAJAXRequest(mainFrm, gRoot+'displayShoppingCart.php', action, additional, responseDisplayCart, 'cartbody', responseParams);
}

function HideCartPanel() {
	YAHOO.c9.container.CartPanel.hide();
}

function HidePopupPanel() {
	YAHOO.c9.container.PopupPanel.hide();
}

//create the YUI dialog box to display the popup inquiry box
function CreatePopupPanel(panelWidth) {
	YAHOO.namespace("c9.container");
	YAHOO.util.Event.onDOMReady(function () {
		YAHOO.c9.container.PopupPanel = new YAHOO.widget.Panel("PopupPanel", {
			width:panelWidth,
			visible:false,
			modal:true,
			close:true,
			fixedcenter: true,
			constraintoviewport:false,
			draggable:false,
			underlay:"shadow",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		} );
	});
}

//response handler for displaying popup
function responseDisplayPopup (req, divId, responseParams) {
	document.getElementById(divId).innerHTML = req.responseText;
	if (responseParams.action=="order"){
		type="orderdetail";
	}
	else {
		type="invoicedetail";
	}
	YAHOO.namespace("c9");
	YAHOO.c9.DetailTable = function() {
        var detailColumnDefs = [
            {key:"ItemCode", label:"Item",width:110,sortable:true},
            {key:"Description", label:"Description",width:220},
            {key:"QuantityOrdered", label:"Quantity",width:80,className:"align-right"},
            {key:"UnitPrice", label:"Price",width:80,className:"align-right"},
            {key:"ExtensionAmt", label:"Amount",width:85,className:"align-right"}
        ];

        var detailDataSource = new YAHOO.util.DataSource(gRoot+"json_proxy.php?");
        detailDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        detailDataSource.responseSchema = {
            resultsList: "records",
            fields: [{key:"ItemCode"},
                     {key:"Description"},
                     {key:"QuantityOrdered"},
                     {key:"UnitPrice"},
                     {key:"ExtensionAmt"}
                    ]
        };
        var oConfigs = {
                initialRequest: "dir=asc&results=250&custID="+responseParams.custID+"&key1="+responseParams.key1+"&key2="+responseParams.key2+"&type="+type+"&siteRoot="+gRoot,
                sortedBy:{key:"ItemCode",dir:"asc"},
                height:"140px"
        };

	    var detailDataTable = new YAHOO.widget.ScrollingDataTable("linedetail", detailColumnDefs, detailDataSource, oConfigs);
	} ();
	postAJAX();
}

//display popup panel
function DisplayPopupPanel(action,custID,key1,key2) {
	if (action == null) {
		action = 'order';
	}
	if (custID == null) {
		custID = '';
	}
	if (key1 == null) {
		key1 = '';
	}
	if (key2 == null) {
		key2 = '';
	}
	//set variables of global scope for data tables in popup panels
	//these variables must be defined in the root page to have proper scope...
	var responseParams = {action:action, custID:custID, key1:key1, key2:key2};

	switch (action) {
		case 'invoice':
			title='Invoice '+key1;
			additional='&custID='+custID+'&key1='+key1+'&key2='+key2;
			break;
		case 'order':
			title='Sales Order '+key1;
			additional='&custID='+custID+'&key1='+key1;
	}
	YAHOO.c9.container.PopupPanel.setHeader('<div class="left"><h2>'+title+'</h2></div>');
	YAHOO.c9.container.PopupPanel.setBody('<div id="popupbody"><img src="'+gRoot+'images/loading.gif" class="loading"/></div>');
	YAHOO.c9.container.PopupPanel.setFooter('<div class="left"><p>[<a class="fade" onclick="HidePopupPanel();">Close Window</a>]</p></div><div class="right"></div>');
	YAHOO.c9.container.PopupPanel.render("popuppanel");
	YAHOO.c9.container.PopupPanel.show();
	sendAJAXRequest('', gRoot+'displayPopup.php', action, additional, responseDisplayPopup, 'popupbody', responseParams);

}
//select customer for salesperson login
function selectSalespersonCustomer(custID, salespersonID, redirect){
	//alert (custID+salespersonID+redirect);
	additional="&customerID="+custID+"&salespersonID="+salespersonID;
	var responseParams = {redirect:redirect};
	sendAJAXRequest('', gRoot+'setSalespersonCustomer.php', '', additional, responseSetSalespersonCustomer, '', responseParams);
}

function responseSetSalespersonCustomer(req, divId, responseParams) {
	window.location=responseParams.redirect;
	//alert (responseParams.redirect);
}

//Look up for express entry
function lookupItem(itemid, quantity, row){
	//alert(itemid+" "+quantity+" "+row);
	action="item";
	additional="&key1="+itemid+"&key2="+quantity;
	var responseParams = {row:row};
	sendAJAXRequest('', gRoot+'lookup.php', action, additional, responseLookupItem, '', responseParams);
}

function responseLookupItem(req, divId, responseParams) {
	var row=responseParams.row;
	var errorText = '';
	var hasErrors = false;
	var xmlDoc = req.responseXML;
	//alert (req.responseText);
	var errors = xmlDoc.getElementsByTagName('error')[0];
	errorText = getNodeValue(errors,"errormssg");
	if (errorText != '' ){
		hasErrors=true;
		//alert(errorText);
	}
	var data = xmlDoc.getElementsByTagName('data')[0]; // get data
	if (hasErrors) {
		document.getElementById("d_"+row).className = 'error';
		document.getElementById("p_"+row).className = 'error';
		document.getElementById("e_"+row).className = 'error';
		document.getElementById("u_"+row).className = 'error';
	}
	else {
		document.getElementById("d_"+row).className = '';
		document.getElementById("p_"+row).className = '';
		document.getElementById("e_"+row).className = '';
		document.getElementById("u_"+row).className = '';
	}
	document.getElementById("d_"+row).innerHTML = getNodeValue(data,"description");
	document.getElementById("p_"+row).innerHTML = getNodeValue(data,"price");
	document.getElementById("e_"+row).innerHTML = getNodeValue(data,"extension");
	document.getElementById("u_"+row).innerHTML = getNodeValue(data,"unitofmeasure");
	postAJAX();
}

//Look up ship to code
function lookupShipto(custid, shiptocode, edit, phone, ext, fax, email) {
	responseParams={edit:edit, phoneRequired:phone, extRequired:ext, faxRequired:fax, emailRequired:email};
	action="shipto";
	additional="&key1="+custid+"&key2="+shiptocode;
	sendAJAXRequest('', gRoot+'lookup.php', action, additional, responseLookupShipto, '', responseParams);
}

function responseLookupShipto (req, divId, responseParams) {
	//requires ship to form fields on current page
	var errorText = '';
	var hasErrors = false;
	var xmlDoc = req.responseXML;
	//alert (req.responseText);
	var errors = xmlDoc.getElementsByTagName('error')[0];
	errorText = getNodeValue(errors,"errormssg");
	if (errorText != '' ){
		hasErrors=true;
		//alert(errorText);
	}
	if (!hasErrors) {
		var edit=responseParams.edit;
		var phoneRequired=responseParams.phoneRequired;
		var extRequired=responseParams.extRequired;
		var faxRequired=responseParams.faxRequired;
		var emailRequired=responseParams.emailRequired;
		//alert(edit);
		//no errors
		var data = xmlDoc.getElementsByTagName('data')[0]; // get data
		//update form with new data
		document.forms["checkout"].elements["ShipToName"].value=getNodeValue(data,"shiptoname");
		if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToName"],'ShipToNameError',true);
		document.forms["checkout"].elements["ShipToAddressLine1"].value=getNodeValue(data,"shiptoaddress1");
		if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToAddressLine1"],'ShipToAddressLine1Error',true);
		var address2=getNodeValue(data,"shiptoaddress2");
		document.forms["checkout"].elements["ShipToAddressLine2"].value=address2;
		// address 2 & 3 are optional.  Show or hide as needed.  Each field group is wrapped in a div with an id of ShipToAddress#
		if (address2 != '' || edit=='') {
			document.getElementById("ShipToAddress2").style.display = '';
		}
		else {
			document.getElementById("ShipToAddress2").style.display = 'none';
		}
		var address3=getNodeValue(data,"shiptoaddress3");
		document.forms["checkout"].elements["ShipToAddressLine3"].value=address3;
		if (address3 != '' || edit=='') {
			document.getElementById("ShipToAddress3").style.display = '';
		}
		else {
			document.getElementById("ShipToAddress3").style.display = 'none';
		}
		document.forms["checkout"].elements["ShipToCity"].value=getNodeValue(data,"shiptocity");
		if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToCity"],'ShipToCityError',true);
		var longState=getNodeValue(data,"shiptostatefull");
		if (document.forms["checkout"].elements["ShipToStateProvince"].type=="select-one" || longState=='') {
			document.forms["checkout"].elements["ShipToStateProvince"].value=getNodeValue(data,"shiptostate");
		}
		else {
			document.forms["checkout"].elements["ShipToStateProvince"].value=longState;
		}
		if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToStateProvince"],'ShipToStateProvinceError',true);
		document.forms["checkout"].elements["ShipToZipPostal"].value=getNodeValue(data,"shiptozipcode");
		if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToZipPostal"],'ShipToZipPostalError',true);
		try {
			document.forms["checkout"].elements["ShipToCountryCode"].value=getNodeValue(data,"shiptocountrycode");
		}
		catch (err){}
		try {
			document.forms["checkout"].elements["ShipToPhoneNo"].value=getNodeValue(data,"telephoneno");
			if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToPhoneNo"],'ShipToPhoneNoError',phoneRequired,14);
		}
		catch (err){}
		try {
			document.forms["checkout"].elements["ShipToPhoneExt"].value=getNodeValue(data,"telephoneext");
			if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToPhoneExt"],'ShipToPhoneExtError',extRequired);
		}
		catch (err){}
		try {
			document.forms["checkout"].elements["ShipToFaxNo"].value=getNodeValue(data,"faxno");
			if (edit=='') checkForValue(document.forms["checkout"].elements["ShipToFaxNo"],'ShipToFaxNoError',faxRequired,14);
		}
		catch (err){}
		try {
			document.forms["checkout"].elements["ShipToEmailAddress"].value=getNodeValue(data,"emailaddress");
			if (edit=='') checkForEmail(document.forms["checkout"].elements["ShipToEmailAddress"],'ShipToEmailAddressError',emailRequired);
		}
		catch (err){}
		postAJAX();
	}
}

function swapShipToName(cbox){
	if (cbox.checked) {
		//hide select
		if (document.getElementById('ShipToSelect') != null){
			document.getElementById("ShipToSelect").style.display = 'none';
		}
		document.getElementById("ShipToNameEntry").style.display = '';
	}
	else {
		//show select is exists
		if (document.getElementById('ShipToSelect') != null){
			document.getElementById("ShipToSelect").style.display = '';
			document.getElementById("ShipToNameEntry").style.display = 'none';
		}
	}
}

function getNodeValue(obj,tag)
{
	try {
		return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
	}
	catch(err) {
		return '';
	}
}

function getForm(fobj) {
	var str = "";
	var ft = "";
	var fv = "";
	var fn = "";
	var els = "";
	for(var i = 0;i < fobj.elements.length;i++) {
		els = fobj.elements[i];
		ft = els.title;
		fv = els.value;
		fn = els.name;
		switch(els.type) {
			case "text":
			case "hidden":
			case "password":
			case "textarea":
			// is it a required field?
			//if(encodeURI(ft) == "required" && encodeURI(fv).length < 1) {
				//alert('\''+fn+'\' is a required field, please complete.');
				//els.focus();
				//return false;
			//}
				str += fn + "=" + encodeURIComponent(fv) + "&";
				break;

			case "checkbox":
			case "radio":
				if(els.checked) str += fn + "=" + encodeURIComponent(fv) + "&";
				break;

			case "select-one":
				str += fn + "=" +
				els.options[els.selectedIndex].value + "&";
				break;
		} // switch
	} // for
	str = str.substr(0,(str.length - 1));
	return str;
}


//various formatting and validation routines for forms
/* FORMAT PHONE BEHAVIOR MASK */
function FormatPhone (e,input) {
	/* to prevent backspace, enter and other keys from
	 interfering w/ mask code apply by attribute
	 onkeydown=FormatPhone(control)
	*/
	evt = e || window.event; /* firefox uses reserved object e for event */
	var pressedkey = evt.which || evt.keyCode;
	var BlockedKeyCodes = new Array(8,27,13,9); //8 is backspace key
	var len = BlockedKeyCodes.length;
	var block = false;
	var str = '';
	for (i=0; i<len; i++){
	   str=BlockedKeyCodes[i].toString();
	   if (str.indexOf(pressedkey) >=0 ) block=true;
	}
	if (block) return true;

   s = input.value;
   if (s.charAt(0) =='+') return false;
   filteredValues = '"`!@#$%^&*()_+|~-=\QWERT YUIOP{}ASDFGHJKL:ZXCVBNM<>?qwertyuiop[]asdfghjkl;zxcvbnm,./\\\'';
   var i;
   var returnString = '';
   /* Search through string and append to unfiltered values
	  to returnString. */
   for (i = 0; i < s.length; i++) {
		 var c = s.charAt(i);
		 if ((filteredValues.indexOf(c) == -1) & (returnString.length <  14 )) {
			 if (returnString.length==0) returnString +='(';
			 if (returnString.length==4) returnString +=')';
			 if (returnString.length==5) returnString +=' ';
			 if (returnString.length==9) returnString +='-';
			 returnString += c;
		 }
	}
   input.value = returnString;
   return false;
}

function checkForValue(input,divId,required,minLen,errorMssg,validMssg){
	if (minLen==null || minLen==0) {
		minLen=1;
	}
	if (errorMssg==null || errorMssg==''){
		errorMssg='Required';
	}
	if (validMssg==null || validMssg==''){
		validMssg='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
	}
	var strLen=input.value.length;
	if(required || (!required && strLen>=1)){
		if (strLen<minLen){
			document.getElementById(divId).innerHTML=errorMssg;
		}
		else {
			document.getElementById(divId).innerHTML=validMssg;
		}
	}
	if (!required && strLen<1){
		document.getElementById(divId).innerHTML='';
	}
}
function checkForMatch(input,compare,divId,errorMssg,validMssg){
	if (compare==null) {
		return;
	}
	if (compare.value==''){
		return;
	}
	if (errorMssg==null || errorMssg==''){
		errorMssg='Fields do not match';
	}
	if (validMssg==null || validMssg==''){
		validMssg='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
	}
	if (input.value != compare.value){
		document.getElementById(divId).innerHTML=errorMssg;
	}
	else {
		document.getElementById(divId).innerHTML=validMssg;
	}
}

function checkPasswords(input,input2,divId,divId2){
	inputValid=false;
	input2Valid=false;
	invalidMssg='Password must be at least 5 characters'
	if (input.value.length < 5){
		document.getElementById(divId).innerHTML=invalidMssg;
	}
	else {
		inputValid=true;
		document.getElementById(divId).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
	}
	if (input2.value.length < 5){
		document.getElementById(divId2).innerHTML=invalidMssg;
	}
	else {
		input2Valid=true;
	}
	if (input.value != input2.value){
		document.getElementById(divId2).innerHTML='Passwords do not match';
	}
	else {
		if (inputValid && input2Valid){
			document.getElementById(divId2).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
		else {
			if (input2Valid){
				document.getElementById(divId2).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
			}
			else {
				document.getElementById(divId).innerHTML=invalidMssg;
			}
		}
	}
}

function checkForEmail(input,divId,required){
	errorMssg='Invalid e-mail address';
	validMssg='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
	if (required) {
		if (input.value.length < 1){
			document.getElementById(divId).innerHTML='Required';
			return false;
		}
	}
	if (input.value.length > 0){
		var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (!filter.test(input.value)){
			document.getElementById(divId).innerHTML=errorMssg;
			return false;
		}
		else {
			document.getElementById(divId).innerHTML=validMssg;
			return true;
		}
	}
	else {
		if(!required){
			document.getElementById(divId).innerHTML='';
			return true;
		}
	}
}
function numbersonly(e){
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode==0 || unicode==8 || unicode==9 || unicode==13 || unicode==27 || unicode==46) {
	   return true;
	}
	if (unicode<48||unicode>57){ //if not a number
		return false; //disable key press
	}
	else {
		return true;
	}
}
function checkCC(inputType, inputCc, divIdType, divIdCc, last4, required){
	//defined types musy match types defined in getCreditCards in Shopping.php
	//requires that global variables be set for determining what types are accepted
	var validCc=false;
	var validType=false;
	var re="";
	var cardLen=0;
	var type="";
	var ccnum=inputCc.value;
	var ccMask='************'+last4;

	if (ccnum==ccMask) {
		//if card is already validated, then we accept the entry
		//remember that we still have full server side validation to perform
		validCc=true;
		validType=true;
		type=inputType.value;
	}
	else {
		if (/^4\d{3}\d{4}\d{4}\d{4}$/.test(ccnum) && CC_VISA){
			type="VISA";
		}
		if (/^5[1-5]\d{2}\d{4}\d{4}\d{4}$/.test(ccnum) && CC_MC){
			type = "MC";
		}
		if (/^6011\d{4}\d{4}\d{4}$/.test(ccnum) && CC_DISC){
			type = "DISC";
		}
		if (/^3[4,7]\d{13}$/.test(ccnum) && CC_AMEX){
			type = "AMEX";
		}
		inputType.value=type;//set type control to selected type
		if (type!="") {
			validType=true;
		}
		if (validType) {
			// Checksum ("Mod 10")
			// Add even digits in even length strings or odd digits in odd length strings.
			var checksum = 0;
			for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
				checksum += parseInt(ccnum.charAt(i-1));
			}
			// Analyze odd digits in even length strings or even digits in odd length strings.
			for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
				var digit = parseInt(ccnum.charAt(i-1)) * 2;
				if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
			}
			if ((checksum % 10) == 0 && ccnum.length>0) {
				validCc=true;
			}
		}
		else {
			validCc=false;
		}
	}
	if (validCc){
		var icon="";
		var iconWidth=26;
		switch (type){
			case "VISA":
				icon="visa.png";
				break;
			case "MC":
				icon="mc.png";
				break;
			case "DISC":
				icon="disc.png";
				break;
			case "AMEX":
				icon="amex.png";
				break;
			default:
				icon="ok.gif";
				iconWidth="26";
		}
	}
	//we know if the type is valid and if the card is valid at this point
	if (!required){
		if (validType) {
			//document.getElementById(divIdType).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
		else {
			//document.getElementById(divIdType).innerHTML='';
		}
		if (validCc) {
			document.getElementById(divIdCc).innerHTML='<img src="'+gRoot+'images/'+icon+'" height=16 width='+iconWidth+' border=0 alt="OK" />';
		}
		else {
			if(ccnum.length>0) {
				document.getElementById(divIdCc).innerHTML='Invalid credit card number';
			}
			else {
				document.getElementById(divIdCc).innerHTML='';
			}
		}
	}
	else {
		if (validType) {
			//document.getElementById(divIdType).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
		else {
			//document.getElementById(divIdType).innerHTML='Invalid credit card type';
		}
		if (validCc) {
			document.getElementById(divIdCc).innerHTML='<img src="'+gRoot+'images/'+icon+'" height=16 width='+iconWidth+' border=0 alt="OK" />';
		}
		else {
			document.getElementById(divIdCc).innerHTML='Invalid credit card number';
		}
	}
}


function checkCreditCard(inputType, inputCc, divIdType, divIdCc, last4, required) {
	//defined types musy match types defined in getCreditCards in Shopping.php
	//requires that global variables be set for determining what types are accepted
	var validCc=false;
	var validType=false;
	var re='';
	var cardLen=0;
	var type=inputType.value;
	//if no type blank cc number
	if (type==''){
		inputCc.value='';
	}
	var ccnum=inputCc.value;
	var ccMask='************'+last4;
	if (type == "VISA" && CC_VISA) {
		// Visa: length 16, prefix 4, dashes optional.
		re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
	}
	else if (type == "MC" && CC_MC) {
		// Mastercard: length 16, prefix 51-55, dashes optional.
		re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
		cardLen=16;
	}
	else if (type == "DISC" && CC_DISC) {
		// Discover: length 16, prefix 6011, dashes optional.
		re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
		cardLen=16;
	}
	else if (type == "AMEX" && CC_AMEX) {
		// American Express: length 15, prefix 34 or 37.
		re = /^3[4,7]\d{13}$/;
		cardLen=15;
	}
	else if (type == "DINERS" && CC_DINERS) {
		// Diners: length 14, prefix 30, 36, or 38.
		re = /^3[0,6,8]\d{12}$/;
		cardLen=14;
	}
	if (re!='') { validType=true;}
	if (ccnum==ccMask) {
		validCc=true;
	}
	else if (re.test(ccnum)) {
		// Remove all dashes for the checksum checks to eliminate negative numbers
		ccnum = ccnum.split("-").join("");
		// Checksum ("Mod 10")
		// Add even digits in even length strings or odd digits in odd length strings.
		var checksum = 0;
		for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
			checksum += parseInt(ccnum.charAt(i-1));
		}
		// Analyze odd digits in even length strings or even digits in odd length strings.
		for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
			var digit = parseInt(ccnum.charAt(i-1)) * 2;
			if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
		}
		if ((checksum % 10) == 0 && ccnum.length>0) {
			validCc=true;
		}
	}
	//we know if the type is valid and if the card is valid at this point
	if (!required){
		if (!validType) {
			document.getElementById(divIdType).innerHTML='';
			document.getElementById(divIdCc).innerHTML='';
			inputCc.value='';
		}
		else {
			document.getElementById(divIdType).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
			if (validCc) {
				document.getElementById(divIdCc).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
			}
			else {
				document.getElementById(divIdCc).innerHTML='Invalid credit card format';
			}
		}
	}
	else {
		if (validType) {
			document.getElementById(divIdType).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
		else {
			document.getElementById(divIdType).innerHTML='Invalid credit card type';
		}
		if (validCc) {
			document.getElementById(divIdCc).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
		else {
			document.getElementById(divIdCc).innerHTML='Invalid credit card number';
		}
	}
}

function checkCcExpDate(inputExpYear, inputExpMonth, divId){
	var d = new Date();
	var currMonth = d.getMonth();
	var currYear = d.getFullYear();
	var hasDate=false;
	var expired=false;
	if(inputExpYear.value > 0 && inputExpMonth.value > 0) {
		hasDate=true;
	}
	if (hasDate){
		if (inputExpYear.value<currYear || (inputExpYear.value==currYear && inputExpMonth.value <= currMonth)){
			expired=true;
		}
	}
	if (!hasDate){
		document.getElementById(divId).innerHTML='Invalid expiration date';
	}
	else {
		if (expired){
			document.getElementById(divId).innerHTML='Card expired';
		}
		else {
			document.getElementById(divId).innerHTML='<img src="'+gRoot+'images/ok.gif" height=16 width=16 border=0 alt="OK" />';
		}
	}
}

function setDefaultCheckoutEmails(emailAddr, divId, required, updateBillToEmail, updateShipToEmail){
	if (checkForEmail(emailAddr,divId,required)){
		if (updateBillToEmail){
			document.getElementById('EmailAddress').value=emailAddr.value;
		}
		if (updateShipToEmail){
			document.getElementById('ShipToEmailAddress').value=emailAddr.value;
		}
	}
}
function setDefaultConfirmTo(firstName, lastName, confirmTo, update){
	if (update){
		confirmTo.value = firstName.value+' '+lastName.value;
	}
}
function copyBillingAddress(frm, phoneRequired, extRequired, faxRequired, emailRequired) {
	frm.ShipToName.value = frm.BillToName.value;
	checkForValue(frm.ShipToName,'ShipToNameError',true);
	frm.ShipToAddressLine1.value = frm.BillToAddressLine1.value;
	checkForValue(frm.ShipToAddressLine1,'ShipToAddressLine1Error',true);
	frm.ShipToAddressLine2.value = frm.BillToAddressLine2.value;
	frm.ShipToAddressLine3.value = frm.BillToAddressLine3.value;
	frm.ShipToCity.value = frm.BillToCity.value;
	checkForValue(frm.ShipToCity,'ShipToCityError',true);
	frm.ShipToStateProvince.value = frm.BillToStateProvince.value;
	checkForValue(frm.ShipToStateProvince,'ShipToStateProvinceError',true);
	frm.ShipToZipPostal.value = frm.BillToZipPostal.value;
	checkForValue(frm.ShipToZipPostal,'ShipToZipPostalError',true);
	if (document.getElementById("PhoneNumber")){
		frm.ShipToPhoneNo.value = frm.PhoneNumber.value;
		checkForValue(frm.ShipToPhoneNo,'ShipToPhoneNoError',phoneRequired, 14, 'Invalid phone number');
	}
	if (document.getElementById("PhoneExt")){
		frm.ShipToPhoneExt.value = frm.PhoneExt.value;
		if (extRequired){
			checkForValue(frm.ShipToPhoneExt,'ShipToPhoneExtError',true);
		}
	}
	if (document.getElementById("FaxNumber")){
		frm.ShipToFaxNo.value = frm.FaxNumber.value;
		checkForValue(frm.ShipToFaxNo,'ShipToFaxNoError',faxRequired, 14, 'Invalid fax number');
	}
	if (document.getElementById("EmailAddress")){
		frm.ShipToEmailAddress.value = frm.EmailAddress.value;
		checkForEmail(frm.ShipToEmailAddress,'ShipToEmailAddressError',emailRequired);
	}
	if (document.getElementById("BillToCountryCode")){
		frm.ShipToCountryCode.value = frm.BillToCountryCode.value;
	}
}
function setLoadingImage(divId){
	document.getElementById(divId).innerHTML='<img src="'+gRoot+'images/loading_small.gif" height=16 width=16 />';
}

// silent error handler - some of the scripts below will cause an exception if they don't have an object
// which is fine...
function silentError() {return true;}
//window.onerror=silentError; - enable for live

