//"CONSTANTS"
//Shopping Cart
var CART_TITLE='Shopping Cart';
//Misc
var ERROR_BACKGROUND_COLOR='faf5b0';

window.onload = initialize;
//stop enter from submitting form
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"){
		//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==="home"){
		blendImages('slideshow', 30, 3000);
	}

	createCartPanel();
	createMenus();
	enableEffects();
}

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':'#0295fd' }) },
			'mouseleave' : function() { morph.start({ 'color':'#004c80' }) }
		});
	});
	$each($$('.pagelink'), function(el) {
		var morph = new Fx.Morph(el,{ 'duration':'500', 'link':'cancel' });
		el.addEvents({
			'mouseenter' : function() { morph.start({ 'color':'#0295fd' }) },
			'mouseleave' : function() { morph.start({ 'color':'#004c80' }) }
		});
	});

}
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 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) {
	//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 
	//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);
	//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) {  
    // 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);  
				}
				else {
					document.getElementById(divId).innerHTML = req.responseText;
					enableEffects();
				}
            }
			else {
				document.getElementById("AJAXError").innerHTML = "HTTP error: "+req.status;  
			}
        }  
    }  
}

//specific response functions for AJAX requests
function responseAddToCart (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 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 title=getNodeValue(data,"title");
		var contents=getNodeValue(data,"contents");
		var viewLinkText=getNodeValue(data,"viewlinktext");
		var checkoutLink=getNodeValue(data,"checkoutlink");
		var checkoutLinkText=getNodeValue(data,"checkoutlinktext");
		var cartIsEmpty=getNodeValue(data,"cartisempty");
		//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');
		hlink.setAttribute('onclick','DisplayCartPanel();');
		hlink.appendChild(document.createTextNode(viewLinkText));
		hlink.className="fade";
		addMssg.appendChild(hlink);
		//update card in masthead
		displayCartMasthead(title, contents, viewLinkText, checkoutLinkText, cartIsEmpty);
		enableEffects();
	}
}

//response handler for displaying shopping cart
function responseDisplayCart (req, divId) {
	document.getElementById(divId).innerHTML = req.responseText;
	//transfer totals from cart to masthead.
	document.getElementById("cart").innerHTML = document.getElementById("cartmasthead").innerHTML;
	enableEffects();
}

//update cart display in masthead
function displayCartMasthead (title, contents, viewLinkText, checkoutLinkText, cartIsEmpty) {
	var cartDiv = document.getElementById("cart");
	//this is complicated, so it's easier to build a big string and replace the innerHTML, plus this will match the PHP code in layout.php
	var html='<p class="message"><strong>'+title+'</strong><br />'+contents+'</p>';
	if (cartIsEmpty!=1){
		html+='<a class="fade" onclick="DisplayCartPanel();">'+viewLinkText+'</a><a class="fade" href="'+gRoot+'">'+checkoutLinkText+'</a><div class="clear"></div>';
	}
	cartDiv.innerHTML=html;
}

//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:"none",effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.50}
		} );
	});
}

//create the menu
function createMenus() {
	YAHOO.util.Event.onContentReady("mainmenu", function () {
		var oMainMenuBar = new YAHOO.widget.MenuBar("mainmenu", { 
											autosubmenudisplay: true,
											lazyload: true,
											hidedelay: 750
											});
		oMainMenuBar.render();
		oMainMenuBar.subscribe("beforeShow", onMenuBarBeforeShow);
	});
	
	YAHOO.util.Event.onContentReady("rightmenu", function () {
		var oRightMenuBar = new YAHOO.widget.MenuBar("rightmenu", { 
											autosubmenudisplay: true,
											lazyload: true,
											hidedelay: 750});
		oRightMenuBar.render();
		oRightMenuBar.subscribe("beforeShow", onMenuBarBeforeShow);
	}); 
}

function onMenuBarBeforeShow() {
 
	// Create a reference to the submenu's parent object
 	var oParent = this.parent;
	// If the submenu's parent is an instance of MenuBarItem, then it is a first-tier submenu
	if (oParent && oParent instanceof YAHOO.widget.MenuBarItem) {
 		this.cfg.setProperty("display", "dynamic");
		this.cfg.setProperty("zindex", 22001);
	}
}

//display shiopping cart
function DisplayCartPanel(mainFrm,action,extra) {
	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'></div><div class='right'></div>");
	YAHOO.c9.container.CartPanel.render("cartpanel");

	if (action == null){
   		action = 'display';
 	}
	if (mainFrm == null) {
		mainFrm = '';
	}
	if (extra == null) {
		extra = '';
	}
	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");
	cartbodyDiv.innerHTML='<img src="'+gRoot+'images/shoppingcart/loading.gif" class="loading" />';
	if (action == "delete") {
		additional="&itemID="+extra;
	}
	sendAJAXRequest(mainFrm, gRoot+'displayShoppingCart.php', action, additional, responseDisplayCart, 'cartbody');
} 


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

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
/* 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 <  13 )) { 
			 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 checkNumber(field) {
	var check = true;
	var value = field.value; //get characters
	//check that all characters are digits, ., -, or ""
	for(var i=0;i < field.value.length; ++i)
	{
	   var new_key = value.charAt(i); //cycle through characters
	   if(((new_key < "0") || (new_key > "9")) && 
			!(new_key == ""))
	   {
			check = false;
			break;
	   }
	}
}

function copyBillingAddress(frm) {
	frm.ShipToName.value = frm.BillToName.value;	
	frm.ShipToAddressLine1.value = frm.BillToAddressLine1.value;
	frm.ShipToAddressLine2.value = frm.BillToAddressLine2.value;
	frm.ShipToAddressLine3.value = frm.BillToAddressLine3.value;
	frm.ShipToCity.value = frm.BillToCity.value;
	frm.ShipToStateProvince.value = frm.BillToStateProvince.value;
	frm.ShipToZipPostal.value = frm.BillToZipPostal.value;
	frm.ShipToCountryCode.value = frm.BillToCountryCode.value;
}

function enableUserInfo(frm, checked){
	if (checked){
		style = "txt";
	}
	else {
		style = "txtdisabled";
	}
	
	frm.Password.disabled=!checked;
	frm.Password2.disabled=!checked;
	frm.FirstName.disabled=!checked;
	frm.LastName.disabled=!checked;	
	frm.Password.className=style;
	frm.Password2.className=style;
	frm.FirstName.className=style;
	frm.LastName.className=style;	

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