
function resetEmailValues(){
	// set variables
    var emailToFriend = document.getElementById('emailToFriend');
    
    var senderName = document.getElementById('senderName');
    var senderEmail = document.getElementById('senderEmail');
    var recipientName = document.getElementById('recipientName');
    var recipientEmail = document.getElementById('recipientEmail');
    var senderMessage = document.getElementById('senderMessage');
    
    senderName.value = '';
    senderEmail.value = '';
    recipientName.value = '';
    recipientEmail.value = '';
    senderMessage.value = '';
    
	emailToFriend.style.display = 'none';
	emailToFriend.innerHTML = document.getElementById('tableTmp').innerHTML;
}

function emailFriend(company, product, url, action){
	var emailToFriend = document.getElementById('emailToFriend');
    
    // set variables
    var senderName = document.getElementById('senderName').value;
    var senderEmail = document.getElementById('senderEmail').value;
    var recipientName = document.getElementById('recipientName').value;
    var recipientEmail = document.getElementById('recipientEmail').value;
    var senderMessage = document.getElementById('senderMessage').value;
    	
    if( action == 'send' ){
    	var urlString  = 'senderName='+senderName+'&senderEmail='+senderEmail;
        	urlString += '&recipientName='+recipientName+'&recipientEmail='+recipientEmail+'&senderMessage='+senderMessage;
            urlString += '&companyName='+company+'&productName='+product+'&productURL='+url;
    
    	var myConn = new XHConn();
        if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
                        
		var fnWhenDone = function (oXML) {
            var xml = oXML.responseXML;
            	xmlSenderName = xml.selectSingleNode("emailFriend/sender/name/text()").nodeValue;
                xmlSenderEmail = xml.selectSingleNode("emailFriend/sender/email/text()").nodeValue;
                
                xmlRecipientName = xml.selectSingleNode("emailFriend/recipient/name/text()").nodeValue;
                xmlRecipientEmail = xml.selectSingleNode("emailFriend/recipient/email/text()").nodeValue;
                xmlRecipientMessage = xml.selectSingleNode("emailFriend/message/text()").nodeValue;
            
            
             if( xmlSenderName == 'valid' && xmlSenderEmail == 'valid' && 
             	 xmlRecipientName == 'valid' && xmlRecipientEmail == 'valid' ){            		
                    
                    var defaultHolder = document.createElement('DIV');
                    defaultHolder.id = 'tableTmp';
                    defaultHolder.style.cssText = 'position:absolute;display:none;';
	                defaultHolder.innerHTML = emailToFriend.innerHTML;
                    document.body.appendChild(defaultHolder);
                    
                    emailToFriend.innerHTML = 'Your message was successfully sent.';
                    
                    window.setTimeout("resetEmailValues()", 3000);
             }else{
             	if( xmlSenderName != 'valid' ){
                    document.getElementById('sName').innerHTML = '<br />'+xmlSenderName;
                    document.getElementById('sName').style.display = '';
                }else{
                	document.getElementById('sName').innerHTML = '';
                    document.getElementById('sName').style.display = 'none';
                }
				
             	if( xmlSenderEmail != 'valid' ){
                    document.getElementById('sEmail').innerHTML = '<br />'+xmlSenderEmail;
                    document.getElementById('sEmail').style.display = '';
                }else{
                	document.getElementById('sEmail').innerHTML = '';
                    document.getElementById('sEmail').style.display = 'none';
                }

             	if( xmlRecipientName != 'valid' ){
                    document.getElementById('rName').innerHTML = '<br />'+xmlRecipientName;
                     document.getElementById('rName').style.display = '';
                }else{
                	document.getElementById('rName').innerHTML = '';
                    document.getElementById('rName').style.display = 'none';
                }
                
             	if( xmlRecipientEmail != 'valid' ){
                    document.getElementById('rEmail').innerHTML = '<br />'+xmlRecipientEmail;
                     document.getElementById('rEmail').style.display = '';
                }else{
                	document.getElementById('rEmail').innerHTML = '';
                    document.getElementById('rEmail').style.display = 'none';
                }                                                   
             }
		};
        
        myConn.connect("inc.php?page=www/shopping_cart/inc.email_friend.php", "POST", urlString, fnWhenDone);
    }else{
        if( emailToFriend.style.display == 'none' ){
    		emailToFriend.style.display = '';
        }else{
        	emailToFriend.style.display = 'none';
        }
    }
}

//Customer Account Functions
var forgot_password = 0;

function set_forgot_password(status){
	forgot_password = status;
}

function check_forgot_email(){	
	if(forgot_password){
		var forgot_email = document.getElementById('email');
		
		if(forgot_email.value == ''){
			alert('Please type in your account email address!');
			return false;
		}
	}
	
	return true;
}


//Category Functions
function clear_text(strID,strText){
	var strNewText = document.getElementById(strID);
	
	if(strText == strNewText.value){
		strNewText.value = '';
	}else if(strNewText.value == ''){
		strNewText.value = strText;
	}
}

function check_category(id,text){
	var new_text = document.getElementById(id);
	var submit_type = document.getElementById('frmSubmitType');
	
	if(new_text.value == text && submit_type.value != 'Update'){ 
		alert('You must enter a category to add.');
		new_text.focus();
		return false; 
	}
	
	return true;
}

function check_promo(id,text){
	var new_text = document.getElementById(id);
	var submit_type = document.getElementById('frmSubmitType');
	
	if(new_text.value == text && submit_type.value != 'Update'){ 
		alert('You must enter a promo code to add.');
		new_text.focus();
		return false; 
	}
	
	return true;
}

//Product Functions
var sortAttribute;
var selectWidth;
	
function addOption(from,to){
	var foo = document.getElementById(from);
	var foo2 = document.getElementById(to);
	
	for( var i = 0; i < foo.options.length; i++ ){
		if( foo.options[i].selected == true ){
			var opt = foo2.appendChild(document.createElement('option'));
			opt.text = foo.options[i].text;
			opt.value = foo.options[i].value;

			foo.removeChild(foo.options[i]);

			--i;
			SortSelect(foo2);
		}
	}
}

function removeOption(to,from){
	var foo = document.getElementById(to);
	var foo2 = document.getElementById(from);
	
	for( var i = 0; i < foo.options.length; i++ ){
		if( foo.options[i].selected == true ){
			var opt = foo2.appendChild(document.createElement('option'));
			opt.text = foo.options[i].text;
			opt.value = foo.options[i].value;

			foo.removeChild(foo.options[i]);

			--i;
			SortSelect(foo2);
		}
	}
}	

function SortSelect(sel){
	if (!sel) return;
	sortAttribute = 'text';

	var numOpts=sel.options.length;
	var opts=[];
	for (var i=0;i<numOpts;i++) opts[i]=sel.options[i];
	opts.sort(SortBySortOrder);
	for (var i=0;i<numOpts;i++) sel.options[i].swapNode(opts[i]);
}

function SortBySortOrder(a,b){
	if (!sortAttribute) return 0;
	var aOrder = a.getAttribute(sortAttribute);
	var bOrder = b.getAttribute(sortAttribute);
	return (aOrder<bOrder?-1:aOrder>bOrder?1:0);
}
	
function set_dropdowns(){
	// SET CATEGORY LIST
        var category_select = document.getElementById('category_select');
    
        //set new array name
        var arrCategory = [];	
    
        //set the saved drop down into their own array
        for(var i = 0; i < category_select.options.length; i++)
            arrCategory[i] = category_select.options[i].value;	
            
        //set the array to a comma delimited string
        if(arrCategory.length > 0){
            document.getElementById('category_saved').value = arrCategory.join(",");
        }else{
            document.getElementById('category_saved').value = "";
        }
        
	//SET RELATED LIST
   		var related_products = document.getElementById('related_product_select');
    
        //set new array name
        var arrRelated = [];	
    
        //set the saved drop down into their own array
        for(var i = 0; i < related_products.options.length; i++)
            arrRelated.push(related_products.options[i].value);	
            
        //set the array to a comma delimited string
        if(arrRelated.length > 0){
            document.getElementById('related_saved').value = arrRelated.join(",");
        }else{
            document.getElementById('related_saved').value = "";
        }
}

function getCharCount( id, max_count )
{	
	var field = document.getElementById(id);
	var len = 0;
	var max_chars_msg = 'The maximum number of characters that can be entered is ';
	var current_chars_msg = 'Current number of characters: ';
	
	len = field.value.length;
	
	if (len > max_count){
		alert(max_chars_msg + max_count + ".\n" + current_chars_msg + len);

		field.value = field.value.substr(0, field.value.length + max_count - len);

		if ( field.value.charCodeAt(field.value.length - 2) == 13){
			field.value = field.value.substr(0, field.value.length - 2);
		}		
			
		document.getElementById(id + '_count').innerHTML = len - (len - max_count);
	}else{
		document.getElementById(id + '_count').innerHTML = len;
	}
}	
	
function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}	

//All Functions	
function check_passwords(){
	var frmSubmitType = document.getElementById('frmSubmitType');
	var strPassword = document.getElementById('txtPassword');
	var strConfirmPassword = document.getElementById('txtConfirmPassword');
	
	if(strPassword.value != strConfirmPassword.value){ return false; }
	
	return true;
}

function check_req_fields(frm){	
	var frmSubmitType = document.getElementById('frmSubmitType');
	if(frmSubmitType.value == 'new_option'){
		return true;
	}

	var val;
	var _req = frm.elements["_req"].value;
	var _reqArr = _req.split(',');
	var passExists = false;
	
	for(var i = 0; i < _reqArr.length; i++){
		for(var x = 0; x < frm.elements.length; x++){
			val = frm.elements[x];
			
			if(val.id.indexOf(_reqArr[i]) >= 0){
			//alert(_reqArr[i] + ' - ' + val.id.indexOf(_reqArr[i]));
			//alert(frm.elements[x].name.indexOf('Email'));
				if(frm.elements[x].name.indexOf('Email') > 0 && frm.elements[x].name.indexOf('Confirm') <= 0){
					//alert(document.getElementById(frm.elements[x].name).value + ' != ' + document.getElementById(frm.elements[x].name + 'Confirm').value);
					if(document.getElementById(frm.elements[x].name).value != document.getElementById(frm.elements[x].name + 'Confirm').value){
						alert('Email Address & Confirm Email Address must match.');
						return false;
					}
				}
				
				if(frm.elements[x].value == ''){
					alert('Please fill in all (*) required fields.');
					return false;
				}
			}
		}
	}
	
	for(var i = 0; i < frm.elements.length; i++){
		if(frm.elements[i].name == 'txtPassword'){
			passExists = true;
		}
	}
	
	if(passExists){
		if(!check_passwords()){
			alert('Password and Confirm Password do not match.');
			return false;
		}
	}
	
	return true;
}

function confirm_delete(strTitle,strURLQuery,str_frmSubmit){
	var msg = "Are you sure you want to delete '" + strTitle + "'";
	var ok = confirm(msg);
	
	if(ok){	
		if(str_frmSubmit){
			document.forms[0].action = strURLQuery;
			document.forms[0].submit();		
		}else{
			window.location.href = strURLQuery;	
		}
	}else{ return false; }
	
	//if(ok){	document.location.href = 'index.php?' + strURLQuery; }
}

function redirect(url){
	document.location.href = url;
}

function verify_shippingZipCode(){
	var strZipCode = document.getElementById('zipCode');
	var strShippingMethod = document.getElementById('shippingMethod');
	
	if(strZipCode.value == ''){
		alert('Shipping Zipcode is required to calculate shipping cost.');
		strShippingMethod.value = '';
		strZipCode.focus();
		
		return false;
	}else{
		if(strZipCode.value.length < 5){
			alert('Shipping Zipcode must be at least 5 digits long.');
			strShippingMethod.value = '';
			strZipCode.focus();
			
			return false;
		}else{
			if(strShippingMethod.value == ''){
				alert('Shipping Method is required to calculate shipping cost.');
			}else{
				return true;
			}
		}
	}
}

function set_shipping_price_bak(){
	var strZipCode = document.getElementById('zipCode');
	var strShippingMethod = document.getElementById('shippingMethod');
	
	var strTempShippingTotal = (document.getElementById('shippingTotal').value * 1);
	var strShippingTotal = document.getElementById('shippingTotal');
	
	var strShippingCost = document.getElementById('shippingCost');
	
	var strGrandTotal = document.getElementById('grandTotal');
	var strTempGrandTotal = (document.getElementById('tempCartTotal').value * 1);
	
	var arrShipping = strShippingMethod.value.split('-');
	var temp;
	
	if(strZipCode.value == ''){
		alert('Shipping Zipcode is required to calculate shipping cost.');
		strShippingMethod.value = '';
		strZipCode.focus();
		
		return false;
	}else{
		if(strZipCode.value.length < 5){
			alert('Shipping Zipcode must be at least 5 digits long.');
			strShippingMethod.value = '';
			strZipCode.focus();
			
			return false;
		}else{
			if(strShippingMethod.value == ''){
				strShippingCost.innerHTML = '0.00';
                //strGrandTotal.innerHTML = strTempGrandTotal;
                
				alert('Shipping Method is required to calculate shipping cost.');
			}else{
				strShippingCost.innerHTML = arrShipping[1];

				temp = strTempGrandTotal + (arrShipping[1] * 1);
				temp = (temp == Math.floor(temp)) ? temp + '.00' : Math.round(temp*100)/100;
				
				if(temp == Math.floor(temp)){
					strGrandTotal.innerHTML = temp;
				}else{
					strGrandTotal.innerHTML = temp.toFixed(2);
				}
				
				return true;
			}
		}
	}
}

function set_shipping_price(){
	var cartGrandTotal = document.getElementById('cartGrandTotal');
	var strShippingMethod = document.getElementById('shippingMethod');
	
	var strTempShippingTotal = (document.getElementById('shippingTotal').value * 1);
	var strShippingTotal = document.getElementById('shippingTotal');
	
	var strShippingCost = document.getElementById('shippingCost');
	
	var strGrandTotal = document.getElementById('grandTotal');
	var strTempGrandTotal = (document.getElementById('tempCartTotal').value * 1);
	
	var arrShipping = strShippingMethod.value.split('-');
	var temp = 0;

    if(strShippingMethod.value == ''){
        strShippingCost.innerHTML = '0.00';
        
        temp = strTempGrandTotal;
        temp = (temp == Math.floor(temp)) ? temp + '.00' : Math.round(temp*100)/100;
        
        if( document.getElementById('salesTax') )
			temp += +document.getElementById('salesTax').innerHTML;
        
        temp = parseFloat(temp);
        
        if(temp == Math.floor(temp)){
            strGrandTotal.innerHTML = temp;
            cartGrandTotal.value = temp;
        }else{
            strGrandTotal.innerHTML = temp.toFixed(2);
            cartGrandTotal.value = temp.toFixed(2);
        }
        
        //alert('Shipping Method is required to calculate shipping cost.');
    }else{
        strShippingCost.innerHTML = arrShipping[1];

        temp = strTempGrandTotal + (arrShipping[1] * 1);
        temp = (temp == Math.floor(temp)) ? temp + '.00' : Math.round(temp*100)/100;
        
        if( document.getElementById('salesTax') ){
        	var salesTax = document.getElementById('salesTax').innerHTML;	
	        temp = parseFloat(temp) + parseFloat(salesTax);            
        }
        
        if(temp == Math.floor(temp)){
            strGrandTotal.innerHTML = temp;
            cartGrandTotal.value = temp;
        }else{
            strGrandTotal.innerHTML = temp.toFixed(2);
            cartGrandTotal.value = temp.toFixed(2);
        }
        
        return true;
    }
}

function check_zip_length(frmSubmit){
	var strZipCode = document.getElementById('zipCode');
    var strShipping = document.getElementById('selShipping');

	if(strZipCode.value.length == 5){
		//alert(strZipCode.value);
		//if(frmSubmit){
			//document.frmShoppingCart.submit();
		//}
        
        strShipping.innerHTML = '<img src="/inc.php?page=www/image.php?img=www/shopping_images/getting_rates.gif" border="0" name="checkingRates" id="checkingRates">';
        //strShipping.innerHTML = '<img src="/inc.php?page=www/image.php?img=www/shopping_images/loading.gif" border="0" name="checkingRates" id="checkingRates"><span style="font-size:10px; color:#FF0000;">Checking Rates...</span>';
        strShipping.innerHTML = '<img src="/inc.php?page=www/image.php?img=www/shopping_images/loading2.gif" border="0" width="14" height="14" name="checkingRates" id="checkingRates">&nbsp;&nbsp;<span style="font-weight:bold;">Checking Rates...</span>';

        var myConn = new XHConn();
        if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
                        
		var fnWhenDone = function (oXML) {  
            strShipping.innerHTML = oXML.responseText;
            //document.getElementById('test').innerHTML = oXML.responseText;
		};
        
        myConn.connect("inc.php?page=www/shopping_cart/inc.shipping_rates.php", "GET", 'zipCode=' + strZipCode.value, fnWhenDone);
        
		return true;
	}else{
		return false;
	}	
}

function set_page(page){
	var page_num = page;
	var go_to = document.getElementById('Page');
	
	go_to.value = page_num;
	document.forms.frmSearch.submit();
}

function set_shipping(){
	var frm = document.forms.frmCheckout;
	
	var bill_element;
	var bill_element_value;
	
	var ship_element;
	
	if(document.getElementById('txtDuplicate').checked == true){
		for(var x = 0; x < frm.elements.length; x++){
			bill_element = frm.elements[x];
			bill_element_value = bill_element.value;
	
			if(bill_element.name.indexOf("Bill") > 0){
				ship_element = document.getElementById(bill_element.name.replace("Bill","Ship"));
	
				if(ship_element != null){
					ship_element.value = bill_element_value;
				}
			}
		}
	}else{
		for(var x = 0; x < frm.elements.length; x++){
			bill_element = frm.elements[x];
			bill_element_value = bill_element.value;
	
			if(bill_element.name.indexOf("Bill") > 0){
				ship_element = document.getElementById(bill_element.name.replace("Bill","Ship"));
	
				if(ship_element != null){
					ship_element.value = '';
				}
			}
		}
	}
	
	return(true);
}

function checkInventoryItem( opt ){
	var inventoried = document.getElementById('inventoried');
    
    if( opt )
    	inventoried.style.display = 'none';
    else
    	inventoried.style.display = '';
}

function clear_field(strFieldName,strDefaultValue){
	var strCurrentValue = document.getElementById(strFieldName);
	if(strCurrentValue.value == strDefaultValue){ 
		strCurrentValue.value = '';
	}else{
		if(strCurrentValue.value == ''){
			strCurrentValue.value = strDefaultValue;
		}
	}
	return true;
}

function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

// mozXPath [http://km0ti0n.blunted.co.uk/mozxpath/] km0ti0n@gmail.com
// Code licensed under Creative Commons Attribution-ShareAlike License 
// http://creativecommons.org/licenses/by-sa/2.5/
if( document.implementation.hasFeature("XPath", "3.0") ){
	if( typeof XMLDocument == "undefined" ){ XMLDocument = Document; }
  XMLDocument.prototype.selectNodes = function(cXPathString, xNode){
    if( !xNode ) { xNode = this; } 
		var oNSResolver = this.createNSResolver(this.documentElement)
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++){aResult[i] =  aItems.snapshotItem(i);	}
		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode){
		if( !xNode ) { xNode = this; } 
		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 ){return xItems[0];	}
		else{return null;	}
	}
	Element.prototype.selectNodes = function(cXPathString){
		if(this.ownerDocument.selectNodes){	return this.ownerDocument.selectNodes(cXPathString, this);}
		else{throw "For XML Elements Only";}
	}
	Element.prototype.selectSingleNode = function(cXPathString){	
		if(this.ownerDocument.selectSingleNode){return this.ownerDocument.selectSingleNode(cXPathString, this);	}
		else{throw "For XML Elements Only";}
	}
}