
// __GLOBAL__
function setStyle(elem,newstyle)
{
	var oldstyle = elem.getAttribute("style");
	oldstyle = (oldstyle == null) ? '' : (oldstyle + '; ');

	if (elem.getAttribute("style") == '[object]')			// it's IE
	  { elem.style.setAttribute("cssText",newstyle); }		// use workaround
	else																	// else
	  {  elem.setAttribute("style", oldstyle + newstyle); }				// do it properly
	 
} 

function toggle(id) {
	var elem = document.getElementById(id);
	
	if (elem.className == "hide")  { elem.className = "show"; }
	else  { elem.className = "hide"; }

	return false;
}

function setMsgbox(id,text) {
	elem = document.getElementById(id);
	
	// empty box
	if (elem.hasChildNodes)
	{
		for (var i=0; i<elem.childNodes.length; i++)
		 { elem.removeChild(elem.lastChild); }
	}
	// fill box
	elem.appendChild(document.createTextNode(text));
}
function getKeypress(e)
{
	if (window.event) { return e.keyCode; } 
	else if (e.which) { return e.which; } 
}

function doKeypress(e,buttonName) 
{    
	var thebutton = document.getElementById(getId(buttonName));
   
	if(getKeypress(e) == 13) 
	 { thebutton.click(); return false; }

	return true;
}
	
function getId(name)  {	return name.replace('.',''); }

function popUp(name,URL,width,height,scrollval,resizeval) {
	var newwin = window.open(URL, name, 'toolbar=0,scrollbars='+scrollval+',location=0,statusbar=0,menubar=0,resizable='+resizeval+',width='+width+',height='+height+',left=100,top=100');
	if (window.focus)  { newwin.focus(); }
}


function onImgErrorSmall(source)
{
	if (((source.parentNode.href) && (source.parentNode.href == source.src)) || (source.name == "linkedImage"))
	 { source.parentNode.href = "/PDGCommTemplates/001/images/no-image-100px.gif"; }
	
	source.src = "/PDGCommTemplates/001/images/no-image-100px.gif";
	source.onerror = ""; // disable onerror to prevent endless loop
	return true;
}

function onImgErrorLarge(source)
{
	if ((source.parentNode.href) && (source.parentNode.href == source.src))
	 { source.parentNode.href = "/PDGCommTemplates/001/images/no-image-200px.gif"; }
	  
	source.src = "/PDGCommTemplates/001//images/no-image-200px.gif";
	source.onerror = ""; // disable onerror to prevent endless loop
	return true;
}


function validateForm(theform,formid,elem)
{
	theform = theform || document.getElementById(formid);
	elem = elem || theform.elements;
	var flag = theform.getElementsByTagName('span');	
	var isValid = true;
	var password = new Array();
	var pwc = 0; 	// password count
	var doesMatch = true;
	
	for (var i=0; i<elem.length; i++)
	{
		unmarkField(elem,i,flag);
		
		if (elem[i].getAttribute("class") == "requiredfield") 
		{
			if ((!elem[i].getAttribute("errortext")) || (elem[i].getAttribute("errortext") == ""))
			{
				switch(elem[i].type)
				{	
					case "password":	{ password[pwc] = i; pwc++; }			
					case "text": 
					{
						if ((elem[i].value == null) || (elem[i].value == ""))
							{ isValid = validationFailed(elem,i,flag,isValid); }
						break;
					}			
					case "select-one":
					{
						switch (elem[i].getAttribute("name")) 
						{
							case "billstate": case "shipstate": case "Constate": case "cardexpmonth": case "cardexpyear":
							{
								if  (elem[i].selectedIndex == 0) // "Non-US / Non-Canada" option
								  { isValid = validationFailed(elem,i,flag,isValid); }				
							}	// case
							default:
							{
								var elem2 = null;
								
								if (elem[i].getAttribute("name") == "billstate")  { elem2 = theform.billcountry; }
								if (elem[i].getAttribute("name") == "shipstate")  { elem2 = theform.shipcountry; }
									
								if ((elem2)) // if elem[i] refers to the shipstate or billstate select box, then verify state/province selected matches the country selected. (US/Canada)
								{	
									if  (elem[i].selectedIndex == 0) // "Non-US / Non-Canada" option
									  { isValid = validationFailed(elem,i,flag,isValid); }
									else if ((elem2.options[elem2.selectedIndex].text.search("United States of America") > -1) && (elem[i].options[elem[i].selectedIndex].text.search("US") == -1))
									  { isValid = validationFailed(elem,i,flag,isValid); }
									else if ((elem2.options[elem2.selectedIndex].text.search("Canada") > -1) && (elem[i].options[elem[i].selectedIndex].text.search("Canada") == -1))
									  { isValid = validationFailed(elem,i,flag,isValid); }
								}					
								break;
							}
						}	// switch (elem[i].getAttribute("name"))
						break;
					}	// select-one	
				}	// switch (elem[i].type)
			}
			else	// there is an errortext
			 { isValid = validationFailed(elem,i,flag,isValid); }																			
		}	// if "requiredfield"
	}	// for

	if (!isValid) 	// there are empty fields
	  { alert("One or more required fields have not been filled in."); }
	else if (pwc == 2)	// there are two password fields, so make sure they match.
	{		
		if(elem[password[0]].value != elem[password[1]].value)
		{ 														
			isValid = validationFailed(elem,password[0],flag,isValid,"Passwords must match");
					    validationFailed(elem,password[1],flag,isValid," "); 
			alert("The passwords entered do not match.");
		}
	}				  

	return isValid;	
}

// ^^validateForm()^^	Flag and place focus on fields that fail validation.
function validationFailed(elem,i,flag,isValid,errmsg) 
{
	errmsg = elem[i].getAttribute("errortext") || errmsg || "  * This is a required field";
	
	if (isValid) 			// if this is the first field to fail validation
	  { elem[i].focus(); }	// place the focus on it (this puts the cursor in the field and scrolls the screen to make the field visible to the user)
	
	markField(elem,i,flag,errmsg); 		// Flag the field as being required
	return false;			// on returning this will set isValid to false
}

// ^^validation Failed()^^	Add highlight and text alert to a field after failed field validation	
function markField(elem,i,flag,errmsg)
{ 
	//setStyle(elem[i],"border:1px solid red;"); 			// Highlight the field

	for(var j=0; j<flag.length; j++)
	{		
		if (flag[j].getAttribute("name") == elem[i].name)
		  { flag[j].childNodes[0].nodeValue = errmsg; }
	}
}

// ^^validateForm()^^	Remove highlight and text alerts from a field before validation
function unmarkField(elem,i,flag)
{ 
	//if (elem[i].style.display != 'none') 
	//{
	//	setStyle(elem[i],"border:1px solid #888;"); 			// Remove highlight from the field
		for(var j=0; j<flag.length; j++)
		{		
			if (flag[j].getAttribute("name") == elem[i].name)
			  { flag[j].childNodes[0].nodeValue = " "; }
		}								
	//}
}


// ^^updateLocation()^^
function adjustState(theState,theCountry)
{
	if ((theCountry.options[theCountry.selectedIndex].text.search("Canada") == -1) 						// if the new index is neither "Canada"
	&& (theCountry.options[theCountry.selectedIndex].text.search("United States of America") == -1))	// nor "United States of America"
	  { theState.selectedIndex = 0; }																	// set index to 0 ("Non-US / Non-Canada")
}

// ^^updateLocation()^^
function adjustCountry(theState,theCountry)
{
	if (theState.selectedIndex > 0) 															// abort if index is 0 ("Non-US / Non-Canada")
	{
		if (theState.options[theState.selectedIndex].text.search("Canada") > -1) 			// if Canadian province
		  { theCountry.selectedIndex = getOption("Canada",theCountry); }			  			// set country to "Canada"			
		else if (theState.options[theState.selectedIndex].text.search("US") > -1)			// if US state
		  { theCountry.selectedIndex = getOption("United States of America",theCountry); }	// set country to "United States of America"
	}
}

// ^^adjustCountry()^^
function getOption(str, sel)
{
	for (var i=0; i<sel.length; i++) 							// Cycle through the options;
  	  { if (sel.options[i].text == str)		{ return i; }	}   // if the option (str) is found, return the index of that option.
}

function linkToImage(thelink)
  { thelink.href = thelink.childNodes[0].src; } // makes an <a> tag link to the image nested inside it.

// Sample-Item.html // Replaces the larger image and link with the image/link currently moused over.
                    // reference to the calling <img>
function changeItemImage(hoverImage)
{
	if (hoverImage.src.search("no-image-100px.gif") == -1)
	{
		document.getElementById('item-image').setAttribute("myatt",document.getElementById('item-image').src);
		document.getElementById('item-image').src=hoverImage.parentNode.name;
		document.getElementById('item-link').href=hoverImage.parentNode.name;
		document.getElementById('item-desc').childNodes[0].nodeValue = hoverImage.alt;
	}
}


function changeItemImageBack(hoverImage)
{
	document.getElementById('item-image').src = document.getElementById('item-image').getAttribute("myatt");
	//document.getElementById('item-link').href = document.getElementById('item-image').getAttribute("myatt");
}


function highlightThumb(img)
{
	for (var i=0; i<document.images.length; i++)
	{
		if (document.images[i].className == "thumb")
		{
			if (img.src.search(document.images[i].parentNode.name) > -1)
			 { setStyle(document.images[i],"width:75px; border-width:2px; border-style:solid; border-color:#ff0 #dd0 #dd0 #ff0; margin:2px 0; padding:1px; background-color:#444;"); }
			else
			 { setStyle(document.images[i],"width:75px; border-width:2px; border-style:solid; border-color:#aaa #666 #666 #aaa; margin:2px 0; padding:1px; background-color:#444;"); }
		}
	}
}


function backorderText(invQty,buyQty)
{
	invQty = (parseInt(invQty,10)) ? parseInt(invQty,10) : 0; 
	buyQty = parseInt(buyQty,10);
	
	if ((!isNaN(buyQty)) && (buyQty > 0)) // customer's desired quantity was a positive integer
	{	
		if (buyQty <= invQty) // if the quantity is available then spread the good news!
		 { return ''; }
		else // else the quantity is not available and we must break it to them gently.
		{
			if ((buyQty-invQty) == 1)
			 { return ((buyQty-invQty) + " piece is on backorder."); } 
			else
			 { return ((buyQty-invQty) + " pieces are on backorder."); } 
		}
	}
	else // entered quantity was non-numeric.
	 { return 'Please enter a valid whole number as a quantity.'; }
	  
	return '';
}


function checkAvailability(inv,fieldname,leadtime)
{
	var addamount = parseInt(document.getElementById(fieldname).value,10); // addamount = customer's input (qty)
	inv = parseInt(inv);
	
	if (!isNaN(inv)) // there is a quantity in inventory
	{
		if ((!isNaN(addamount)) && (addamount > 0)) // customer's desired quantity was a positive integer
		{	
			if (addamount <= inv) // if the quantity is available then spread the good news!
			{
				if (addamount == 1)
				  { alert('Your ' + addamount + ' item is available and ready for shipping.'); } 
				else
				  { alert('Your ' + addamount + ' items are available and ready for shipping.'); } 
			}
			else // else the quantity is not available and we must break it to them gently.
			{
				if (inv == 1)
				  { alert(inv + " of your " + addamount + " items is available and ready for shipping.\n\n" + leadtime); } 
				else
				  { alert(inv + " of your " + addamount + " items are available and ready for shipping.\n\n" + leadtime); } 
			}
		}
		else // entered quantity was non-numeric.
		  { alert('Please enter a valid whole number as a quantity.'); }
	}
	else // inventory level is 0, so inv holds a text message about backordering availability with a <br> in the middle of the text (which we remove).
	  { alert("Out of stock.\n\n" + leadtime); } 
	  
	return false;	
}

function verifyAvailability(inv, fieldname, leadtime, sku)
{
	var field = document.getElementById(fieldname);
	var addamount = parseInt(field.value,10); // addamount = customer's input (qty)

	if ((!isNaN(addamount)) && (addamount > 0)) // entered quantity was a positive integer
	{	
		var canBackorder = (leadtime.search("cannot be backordered") > -1) ? false : true;
		inv = (parseInt(inv)) ? parseInt(inv) : 0;		// replace "out of stock" msg with quantity '0';
				
		if (canBackorder) 			// Quantity can be backordered
		 { return true; }
		else								// Quantity cannot be backordered
		{ 
			if (addamount <= inv) // quantity is available; no backordering necessary
			 { return true; }	
			else // Quantity not available; cannot backorder.
			{	
				field.focus();
				if (inv == 0)				// Out of stock
				 { alert("Product ["+sku+"]:\n\nWe're sorry. This item is out of stock.\n\n" + leadtime); }
				else if (inv == 1)		// single pc message
				  { alert("Product ["+sku+"]:\n\nWe're sorry. There is only 1 piece available in inventory.\n\n" + leadtime); } 
				else							// multi pc message
				  { alert("Product ["+sku+"]:\n\nWe're sorry. There are only " + inv + " pieces available in inventory.\n\n" + leadtime); } 
				  
				return false;
			}
		} 
	}
	else // entered quantity was non-numeric or negative.
	 { field.focus(); alert("Product ["+sku+"]:\n\nPlease enter a valid whole number as a quantity."); return false; }
}


function verifyAvailabilityMulti(root)
{
	var inputs = document.getElementsByTagName("input");
	var data = [];
	
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].name.search(root) == 0)
		 { data[inputs[i].name.replace(root,"")] = [inputs[i].name, inputs[++i].value, inputs[++i].value, inputs[++i].value]; } 
	}
	
	for(var i=0; (i<data.length) && verifyAvailability(data[i][1],data[i][0],data[i][2],data[i][3]); i++)
	 { if (i+1 == data.length) return true; }

	return false;	
}


function confirmreorder()
 { return confirm("This action will replace your current cart with the items on this invoice.\n\nAre you sure you want to do this?"); }

