//window.onload = initialize;
var gMobile=false;
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i))) {
	gMobile=true;
}
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;
ajaxDebug=false;
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();
		document.getElementById('loading').style.visibility = 'visible';
		//Subcategories
		sendAJAXRequest("", gRoot+"categoryDetail.php", "subcategories", "&categoryID="+encodeURIComponent(gCategoryID)+"&parentID="+encodeURIComponent(gParentID)+"&currentpage="+gCategoryPage, '', "subcategories");
		//Items
		sendAJAXRequest("", gRoot+"categoryDetail.php", "items", "&categoryID="+encodeURIComponent(gCategoryID)+"&parentID="+encodeURIComponent(gParentID)+"&currentpage="+gItemPage, '', "items");
	}

	if (gPageID==="categoryalt"){
		//Test for cookie support
		testForCookies();
		document.getElementById('loading').style.visibility = 'visible';
		//Items
		sendAJAXRequest("", gRoot+"categoryAltDetail.php", "items", "&groupcode="+encodeURIComponent(gGroupCode)+"&currentpage="+gItemPage, '', "items");
	}

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

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

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

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

	if (gPageID==="home"){
		//Test for cookie support
		testForCookies();
		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
	//responseParams: parameters to pass through to the response handler
	if (responseParams==null || responseParams=='') responseParams = {};
	if (ajaxDebug) {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)) { //yes, this is =, not ==
			params += '&'+str;
		}
	}
	if (ajaxDebug) {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 {
					if (ajaxDebug) {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
	if (ajaxDebug) {alert (req.responseText);}
	//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(divId);
		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
	if (ajaxDebug) {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();
}
//deleting saved cart
function responseDeleteSavedCart (req, divId, responseParams) {
	var errorText = '';
	var xmlDoc = req.responseXML;
	document.getElementById(divId).innerHTML=''; // get rid of current message
	if (ajaxDebug) {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;
		var myArray = c9.scDataTable.getSelectedRows();
		recordSet = c9.scDataTable.getRecordSet();
		for(i=0; i<myArray.length; i++) {
			var rec = recordSet.getRecord(myArray[i]);
			var index = recordSet.getRecordIndex(rec);
			c9.scDataTable.deleteRow(index);
		}
		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
	if (ajaxDebug) {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;
	}
	if (ajaxDebug) {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() {
	//because the onscreen keyboard on touch screen devices may reconfigure the viewport we want to turn off auto centering for touchscreen devices.
	if (gMobile) {
		var configOptions={
			width:"764px",
			visible:false,
			modal:true,
			close:true,
			fixedcenter: false,
			constraintoviewport:true,
			draggable:false,
			underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		}
	}
	else {
		var configOptions={
			width:"764px",
			visible:false,
			modal:true,
			close:true,
			fixedcenter: true,
			constraintoviewport:true,
			draggable:false,
			underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		}
	}
	YAHOO.namespace("c9.container");
	YAHOO.util.Event.onDOMReady(function () {
		YAHOO.c9.container.CartPanel = new YAHOO.widget.Panel("CartPanel", configOptions);
		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></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.c9.container.CartPanel.center();
		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) {
	if (gMobile) {
		var configOptions={
			width:panelWidth,
			visible:false,
			modal:true,
			close:true,
			fixedcenter: false,
			constraintoviewport:false,
			draggable:false,
			underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		}
	}
	else {
		var configOptions={
			width:panelWidth,
			visible:false,
			modal:true,
			close:true,
			fixedcenter: true,
			constraintoviewport:true,
			draggable:false,
			underlay:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		}
	}
	YAHOO.namespace("c9.container");
	YAHOO.util.Event.onDOMReady(function () {
		YAHOO.c9.container.PopupPanel = new YAHOO.widget.Panel("PopupPanel", configOptions);
	});
}

//response handler for displaying popup
function responseDisplayPopup (req, divId, responseParams) {
	document.getElementById(divId).innerHTML = req.responseText;
	//what document are we displaying?
	var type="";
	switch (responseParams.action){
		case "order":
			type="orderdetail";
			var detailheight="140px";
			break;
		case "invoice":
			type="invoicedetail";
			var detailheight="140px";
			break;
		case "savedcart":
			type="cartdetail"
			var detailheight="200px";
			break;
	}
	YAHOO.namespace("c9");
	YAHOO.c9.DetailTable = function() {
		switch (type){
			case "orderdetail":
			case "invoicedetail":
			case "cartdetail":
				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"}
							]
				};
				break;
		}
        var oConfigs = {
            initialRequest: "dir=asc&results=250&custID="+encodeURIComponent(responseParams.custID)+"&key1="+encodeURIComponent(responseParams.key1)+"&key2="+encodeURIComponent(responseParams.key2)+"&type="+type+"&siteRoot="+encodeURIComponent(gRoot),
            sortedBy:{key:"ItemCode",dir:"asc"},
            height:detailheight
        };
	    var detailDataTable = new YAHOO.widget.ScrollingDataTable("linedetail", detailColumnDefs, detailDataSource, oConfigs);
		detailDataTable.subscribe("rowMouseoverEvent", detailDataTable.onEventHighlightRow);
		detailDataTable.subscribe("rowMouseoutEvent", detailDataTable.onEventUnhighlightRow);
	} ();

	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;
			height="520px";
			break;
		case 'order':
			title='Sales Order '+key1;
			additional='&custID='+custID+'&key1='+key1;
			height="520px";
			break;
		case 'savedcart':
			title='Saved Cart '+key2;
			additional='&custID='+custID+'&key1='+key1+'&key2='+key2;
			height="360px";
			break;
	}
	YAHOO.c9.container.PopupPanel.setHeader('<div class="left"><h2>'+title+'</h2></div>');
	YAHOO.c9.container.PopupPanel.setBody('<div id="popupbody"><div style="height:'+height+';"><img src="'+gRoot+'images/loading.gif" class="loading"/></div></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.center();
	YAHOO.c9.container.PopupPanel.show();
	sendAJAXRequest('', gRoot+'displayPopup.php', action, additional, responseDisplayPopup, 'popupbody', responseParams);

}
//select customer for salesperson login
function selectSalespersonCustomer(custID, salespersonID, redirect){
	if (ajaxDebug) {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;
	if (ajaxDebug) {alert (responseParams.redirect);}
}

//Look up for express entry
function lookupItem(itemid, quantity, row){
	if (ajaxDebug) {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;
	if (ajaxDebug) {alert (req.responseText);}
	try {
		var errors = xmlDoc.getElementsByTagName('error')[0];
		errorText = getNodeValue(errors,"errormssg");
	}
	catch (err){}
	if (errorText != '' ){
		hasErrors=true;
		if (ajaxDebug) {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();
}

function resortTable(dt,key,sortdir){
		sortState = dt.getState().sortedBy
		var sort = sortState ? sortState.key : key;
		var dir = sortState ? sortState.dir : sortdir;
		dt.sortColumn(dt.getColumn(sort),dir);
}

function selectAltItemGroup(selectBox, path){
	altCode=selectBox.options[selectBox.selectedIndex].value;
	if (altCode!='') {
		window.location=path+altCode+'/';
	}
}

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;
}

function setLoadingImage(div,size){
	//alert(div);
	if (size == null) {
		size = "small";
	}
	if (size=="large"){
		imagefile='loading.gif';
	}
	else {
		imagefile='loading_small.gif';
	}
	try{
		document.getElementById(div).innerHTML='<img src="'+gRoot+'images/'+imagefile+'" />';
	}
	catch (err){}
}

function setFieldColor(obj){
	obj.style.backgroundColor=ACTIVE_BACKGR_COLOR;
}

function resetFieldColor(obj){
	obj.style.backgroundColor=gFieldColor;
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

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;
	}
}
// 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

