/*
Copyright 2006 Active Media Architects, Inc. - www.activema.com
Usage of these scripts is limited to their original intent as developed and deployed for Activa Commerce Website by Active Media Architects, Inc. Copying, selling or distributing of these scripts, in whole or in part, is strictly prohibited.
*/


	///////////////////////////////////////
	// Frame Buster
	///////////////////////////////////////

if (window != window.top)
  top.location.href = location.href;


	///////////////////////////////////////
	// On-Click-Pop-Center
	///////////////////////////////////////
	// Requires "onClick="NewWindow(this.href,'title','400','300','no');return false;"" in the A HREF tag
	// Example: <a href="doc.html" onClick="NewWindow(this.href,'title','400','300','no');return false;">LINK</a>

function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes,,toolbar=no,menubar=no'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}




	///////////////////////////////////////
	// Auto-Select Field
	///////////////////////////////////////
	// Requires "onLoad=ready()" in the BODY tag
	// Example: <body onLoad=ready()>
	// Requires form name to match where it reads "form" in script
	// Example: <form name="form">
	// Requires form field name to match where it reads "field" in script
	// Example: <input name="field">

function ready(){document.form.field.focus();}



	///////////////////////////////////////
	// Form Validation
	///////////////////////////////////////

function validateGiftCertificate ( form ) {
	return (
				 checkSelect(form.elements["amount"],"V","","Please enter an amount.",false) &&
				 checkSelect(form.elements["recipient_name"],"V","Please enter recipient's name",false) &&
				 checkSelect(form.elements["recipient_email"],"V","","Please enter your recipient's E-mail Address.",false) &&
				 checkEmail(form.elements["recipient_email"],false) &&
				 checkSelect(form.elements["recipient_email"],"V","joe@example.com","Please supply valid E-mail Address.",false));
}

function validateTell(form) {
	return (
				 checkSelect(form.elements["to_email"],"V","","Please enter your Friend's E-mail Address.",false) &&
				 checkEmail(form.elements["to_email"],false) &&
				 checkSelect(form.elements["to_email"],"V","joe@example.com","Please supply valid E-mail Address.",false) &&
				 checkSelect(form.elements["from_email"],"V","","Please enter Your E-mail Address.",false) &&
				 checkEmail(form.elements["from_email"],false) &&
				 checkSelect(form.elements["from_email"],"V","joe@example.com","Please supply valid E-mail Address.",false) &&
				 checkSelect(form.elements["from_name"],"V","","Please enter Your Name.",false));
}

function validateContact(form) {
	return (
				 checkSelect(form.elements["firstname"],"V","","Please enter your First Name.",false) &&
				 checkSelect(form.elements["lastname"],"V","","Please enter your Last Name.",false) &&
				 checkSelect(form.elements["email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["email"],false) &&
				 checkSelect(form.elements["email"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["message"],"V","","Please provide us with your Message.",false));
}

function validateSubmitQuestion(form) {
	return (
				 checkSelect(form.elements["submitquestion[fullname]"],"V","","Please enter your Fullname.",false) &&
				 checkSelect(form.elements["submitquestion[email]"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["submitquestion[email]"],false) &&
				 checkSelect(form.elements["submitquestion[email]"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["submitquestion[question]"],"V","","Please provide us with your Question.",false));
}

function validateSendToFriend(form) {
	return (
				 checkSelect(form.elements["to_name"],"V","","Please enter your Friend's Name.",false) &&
				 checkSelect(form.elements["to_email"],"V","","Please enter your Friend's E-mail.",false) &&
				 checkEmail(form.elements["to_email"],false) &&
				 checkSelect(form.elements["to_email"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["to_name"],"V","","Please enter your Name.",false) &&
				 checkSelect(form.elements["from_email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["from_email"],false) &&
				 checkSelect(form.elements["from_email"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["message"],"V","","Please provide us with your Message.",false));
}

function validateEmailSignup(form) {
	return (
				 /*checkSelect(form.elements["fullname"],"V","","Please enter Your Name.",false) &&
				 checkSelect(form.elements["fullname"],"V","Your Name","Please enter your real Name.",false) &&
				 checkSelect(form.elements["fullname"],"V","your name","Please enter your real Name.",false) &&
				 checkSelect(form.elements["fullname"],"V","my name","Please enter your real Name.",false) &&
				 checkSelect(form.elements["fullname"],"V","name","Please enter your real Name.",false) &&
				 checkSelect(form.elements["fullname"],"V","asdf","Please enter your real Name.",false) &&*/
				 checkSelect(form.elements["email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["email"],false) &&
				 checkSelect(form.elements["email"],"V","joe@example.com","Please supply a valid E-mail Address.",false));
}

function validateUnsub(form) {
	return (
				 checkSelect(form.elements["email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["email"],false) &&
				 checkSelect(form.elements["email"],"V","joe@example.com","Please supply a valid E-mail Address.",false));
}

function validateLogin(form) {
	return (
				 checkSelect(form.elements["email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["email"],false) &&
				 checkSelect(form.elements["email"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["password"],"V","","Please enter your Password.",false));
}

function validateNewLogin(form) {
	return (

				 checkSelect(form.elements["firstname"],"V","","Please enter your first name.",false) &&
				 checkSelect(form.elements["lastname"],"V","","Please enter your last name.",false) &&
				 checkSelect(form.elements["email"],"V","","Please enter your E-mail.",false) &&
				 checkEmail(form.elements["email"],false) &&
				 checkSelect(form.elements["email"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
				 checkSelect(form.elements["password1"],"V","","Please create a Password.",false) &&
				 checkSelect(form.elements["password2"],"V","","Please confirm your Password.",false));
}

function validatePay(form) {
	return (
				validateBillingAddress(form) &&
				 checkSelect(form.elements["billing[cc_num]"],"V","","You have chosen to pay by Credit Card. Please enter your Credit Card Number before continuing.",false) &&
				 checkSelect(form.elements["billing[exp_month]"],"V","00","Please select the Month this credit card expires.",false) &&
				 checkSelect(form.elements["billing[exp_year]"],"V","00","Please select the Year this credit card expires.",false) &&
				 checkSelect(form.elements["billing[ccv]"],"V","","Please enter your credit card's 3-digit Identification Number.",false) &&
				 checkCCNum(form)
				 );
}

function validateSignin(form) {
	return (
				 checkSelect(form.elements["loginemail"],"V","","Please enter your E-mail Address.",false) &&
				// checkEmail(form.elements["loginemail"],false) &&
				 checkSelect(form.elements["loginemail"],"V","joe@example.com","Please supply valid E-mail Address.",false) &&
				 checkSelect(form.elements["password"],"V","","Please enter your Password.",false));
}

function validatePO(form)
{
	//return checkSelect(form.elements["po_number"],"V","","Please enter the PO Number.",false);
	return true;

}//end validatePO

function validateBillingAddress(form)
{
	// This fixes the state / province box nature of the country form
	// 213 == United States
	// 28 == Canada
	var stateField = "billing[state]";
	if ( form.elements["billing[country]"].value != 213 && form.elements["billing[country]"].value != 'US' ) {
		stateField = "billing[province]";
	}

	return (
		checkSelect(form.elements["billing[fullname]"],"V","","Please enter the Billing Full Name.",false) &&
		checkSelect(form.elements["billing[country]"],"V","","Please enter the Billing Country.",false) &&
		checkSelect(form.elements["billing[address]"],"V","","Please enter the Billing Address.",false) &&
		checkSelect(form.elements["billing[city]"],"V","","Please enter the Billing City.",false) &&
		checkSelect(form.elements[stateField],"V","","Please enter the Billing State/Prov.",false) &&
		checkSelect(form.elements["billing[zip]"],"V","","Please enter the Billing Zip/Postal Code.",false) &&
		checkSelect(form.elements["billing[phone]"],"V","","Please enter the Billing Phone.",false)
	);


}//end validateBillingAddress

function checkPasswords(form) {

	if ( form.elements["password1"].value != form.elements["password1"].value ) {
		alert("Your passwords does not match.  Please enter re-enter your passwords");
		return false;
	} else {
		return true;
	}

}

function validateExpressPurchase(form)
{
	if (

		checkSelect(form.elements["email_address"],"V","","Please enter your E-mail.",false) &&
		checkEmail(form.elements["email_address"],false) &&
		checkSelect(form.elements["email_address"],"V","joe@example.com","Please supply valid E-mail Address.",false) &&
		checkSelect(form.elements["billing_fullname"],"V","","Please enter the billing Full Name.",false) &&
		checkSelect(form.elements["billing_address"],"V","","Please enter the billing Address.",false) &&
		checkSelect(form.elements["billing_address"],"V","","Please enter the billing Address.",false) &&
		checkSelect(form.elements["billing_city"],"V","","Please enter the billing City.",false) &&
		checkSelect(form.elements["billing_state"],"V","","Please enter the billing State/Prov.",false) &&
		checkSelect(form.elements["billing_zip"],"V","","Please enter the billing ZIP.",false) &&
		checkSelect(form.elements["billing_phone"],"V","","Please enter the billing Phone.",false))

	{
		//All billing was ok - check shipping and return it
		return validateShippingAddress(form);

	} else {
		//something was false
		return false;
	}

}//end validateBillingAddress

function validateBillingAddress1(form)
{
	if (
		//checkSelect(form.elements["billing_fullname"],"V","","Please enter the billing First Name.",false) &&
		//checkSelect(form.elements["billing_lastname"],"V","","Please enter the billing Last Name.",false) &&
		checkSelect(form.elements["billing_fullname"],"V","","Please enter the billing Full Name.",false) &&
		checkSelect(form.elements["billing_address"],"V","","Please enter the billing Address.",false) &&
		checkSelect(form.elements["billing_city"],"V","","Please enter the billing City.",false) &&
		checkSelect(form.elements["billing_state"],"V","","Please enter the billing State/Prov.",false) &&
		checkSelect(form.elements["billing_zip"],"V","","Please enter the billing ZIP.",false) &&
		checkSelect(form.elements["billing_phone"],"V","","Please enter the billing Phone.",false)
		//checkSelect(form.elements["billing_country"],"V","","Please enter the billing Country.",false)
	) {
		//All billing was ok - check shipping and return it
		return validateShippingAddress(form);

	} else {
		//something was false
		return false;
	}

}//end validateBillingAddress

function validateBillingAddress2(form)
{
	if (
		//checkSelect(form.elements["billing_fullname"],"V","","Please enter the billing First Name.",false) &&
		//checkSelect(form.elements["billing_lastname"],"V","","Please enter the billing Last Name.",false) &&
		checkSelect(form.elements["billing_fullname"],"V","","Please enter the billing Full Name.",false) &&
		checkSelect(form.elements["billing_address"],"V","","Please enter the billing Address.",false) &&
		checkSelect(form.elements["billing_city"],"V","","Please enter the billing City.",false) &&
		checkSelect(form.elements["billing_state"],"V","","Please enter the billing State/Prov.",false) &&
		checkSelect(form.elements["billing_zip"],"V","","Please enter the billing ZIP.",false) &&
		checkSelect(form.elements["billing_phone"],"V","","Please enter the billing Phone.",false)
		//checkSelect(form.elements["billing_country"],"V","","Please enter the billing Country.",false)
	) {
		//All billing was ok - check shipping and return it
		return true;

	} else {
		//something was false
		return false;
	}

}//end validateBillingAddress

function validateShippingAddress(form)
{
	// This fixes the state / province box nature of the country form
	// 213 == United States
	// 28 == Canada
	var stateField = "ship_state";
	if ( form.elements["ship_country"].value != 213 && form.elements["ship_country"].value != 38 ) {
		stateField = "ship_province";
	}

	return (
		checkSelect(form.elements["ship_fullname"],"V","","Please enter the shipping full name.",false) &&
		checkSelect(form.elements["ship_country"],"V","","Please enter the shipping country.",false) &&
		checkSelect(form.elements["ship_phone"],"V","","Please enter the shipping Phone.",false) &&
		checkSelect(form.elements["ship_address"],"V","","Please enter the shipping Address.",false) &&
		checkSelect(form.elements["ship_city"],"V","","Please enter the shipping City.",false) &&
		checkSelect(form.elements[stateField],"V","","Please enter the shipping State/Prov.",false) &&
		checkSelect(form.elements["ship_zip"],"V","","Please enter the shipping ZIP.",false)
	);
}//end validateShippingAddress

function validateExpressPurchase(form)
{
	return (
		checkSelect(form.elements["email_address"],"V","","Please enter your email address.",false) &&
		checkSelect(form.elements["ship_fullname"],"V","","Please enter the shipping full name.",false) &&
		checkSelect(form.elements["ship_phone"],"V","","Please enter the shipping Phone.",false) &&
		checkSelect(form.elements["ship_address"],"V","","Please enter the shipping Address.",false) &&
		checkSelect(form.elements["ship_city"],"V","","Please enter the shipping City.",false) &&
		checkSelect(form.elements["ship_state"],"V","","Please enter the shipping State/Prov.",false) &&
		checkSelect(form.elements["ship_zip"],"V","","Please enter the shipping ZIP.",false)
	);
}//end validateShippingAddress

function validatePaypalForm()
{
	if (document.getElementById('billing_state').value.length == 0) {
		alert ("Please enter the billing state.");
		return false;
	} else {
		return true;
	}
}//end validateShippingAddress

function validateExpress(form)
{
	if (
		checkSelect(form.elements["email_address"],"V","","Please enter your email address.",false)
	) {
		return validateShipping(form);
	}

	return false;
}

function validateNewAccount(form)
{
	if (
		checkSelect(form.elements["account[email]"],"V","","Please enter your E-mail.",false) &&
		checkEmail(form.elements["account[email]"],false) &&
		checkSelect(form.elements["account[email]"],"V","joe@example.com","Please supply a valid E-mail Address.",false) &&
		checkSelect(form.elements["account[password1]"],"V","","Please create a Password.",false) &&
		checkSelect(form.elements["account[password2]"],"V","","Please confirm your Password.",false) &&
		checkSelect(form.elements["firstname"],"V","","Please enter your first name.",false) &&
		checkSelect(form.elements["lastname"],"V","","Please enter your last name.",false)
	) {
		return validateShipping(form);
	}

	return false;
}

function validateShipping(form)
{
	return (
		checkSelect(form.elements["shipping[fullname]"],"V","","Please enter the shipping full name.",false) &&
		checkSelect(form.elements["shipping[address]"],"V","","Please enter the shipping Address.",false) &&
		checkSelect(form.elements["shipping[city]"],"V","","Please enter the shipping City.",false) &&
		checkSelect(form.elements["shipping[country]"],"V","","Please enter the shipping Country.",false) &&
		//checkSelect(form.elements["ship_state"],"V","","Please enter the shipping State/Prov.",false) &&
		checkSelect(form.elements["shipping[zip]"],"V","","Please enter the shipping ZIP.",false) &&
		checkSelect(form.elements["shipping[phone]"],"V","","Please enter the shipping Phone.",false)
	);
}

function checkCCNum(form) {
	
	if (document.getElementById('billing_id').value > 0) { return true; }

	// meh, while I'm here, I'll check the date too
	// well, at least I could
//	if (new Date(form.elements['billing[exp_year]'],form.elements['billing[exp_month]']-1,1) < new Date()) {
//		return warnInvalid(form.elements['billing[cc_num]'],"Your Credit Card has expired");
//	}
	
	ccnum = form.elements['billing[cc_num]'].value.replace(/[ -]/g,'');
	cctype = form.elements['billing[cc_type]'].value;
	
	switch (cctype) {
		case 'a': pattern = /^(?:34|37)[0-9]{13}$/; break;
		case 'd': pattern = /^6011[0-9]{12}$/; break;
		case 'm': pattern = /^5[1-5][0-9]{14}$/; break;
		case 'v': pattern = /^4[0-9]{12}(?:[0-9]{3})?$/; break;
		default: return warnInvalid(form.elements['billing[cc_num]'],"Invalid Credit Card Number");
	}
	
	if ( ccnum.match(pattern) ) { return true; }

	return warnInvalid(form.elements['billing[cc_num]'],"Invalid Credit Card Number");
}

function checkProfile(form)
{
	var arrElements = new Array("firstname","lastname","address", "city", "state", "zip");
	var len = arrElements.length;
	var i = 0;

	for ( i=0; i<len; i++ ) {
		if ( form.elements['billing_'+arrElements[i]].value != form.elements['hidden_billing_'+arrElements[i]].value ) {
			form.elements['profilecontrol'].value = 'change';
		}

	}//for

	//alert(form.elements['profilecontrol'].value);

	//and one by hand
	if ( form.elements['cc_type'].value != form.elements['hidden_cc_type'].value ) {
		form.elements['profilecontrol'].value = 'change';
	}

	return validateBillingAddress(form);

}//end checkProfile


function validateProductComment(form){
	
	if (
		checkSelect(form.elements["customer"],"V","","Please enter your name.",false) &&
		checkSelect(form.elements["rating"],"V","","Please include a product rating.",false) &&
		checkSelect(form.elements["headline"],"V","","Please enter a headline.",false) &&
		checkSelect(form.elements["comment_text"],"V","","Please enter a comment.",false)
		
		
	){
		var x = form.elements['rating'].value;
		if(x >= 0 && x <= 10){
			return true;
		}
		alert('Your rating must be a number between 0 and 10.');
		
	}
	return false;

}


function validateCatalogRequest(form) {
	return (
			checkSelect(form.elements["fullname"],"V","","Please enter your Full Name.",false) &&
			checkSelect(form.elements["address1"],"V","","Please enter your Address.",false) &&
			checkSelect(form.elements["city"],"V","","Please enter your City.",false) &&
			checkSelect(form.elements["state"],"V","","Please enter your State.",false) &&
			checkSelect(form.elements["zip_code"],"V","","Please enter your Zip Code.",false)
		);
				 
}


function validateAddress(form) {
	
	if(! checkSelect(form.elements["address[country]"],"V","","Please enter your Country.",false)) {
		return false;
	}
	
	var stateField = "address[state]";
	if ( form.elements["address[country]"].value != 213 && form.elements["address[country]"].value != 'US' ) {
		stateField = "address[province]";
	}
	
	return ( 
			checkSelect(form.elements["address[fullname]"],"V","","Please enter your Full Name.",false) &&
			checkSelect(form.elements["address[address]"],"V","","Please enter your Address.",false) &&
			checkSelect(form.elements["address[city]"],"V","","Please enter your City.",false) &&
			checkSelect(form.elements[stateField],"V","","Please enter your State/Province.",false) &&
			checkSelect(form.elements["address[zip_code]"],"V","","Please enter your Zip Code.",false) &&
			checkSelect(form.elements["address[country]"],"V","","Please enter your Country.",false)
		);
				 
}

function validateCreditAccount(form) {
	fields = { 
		"company" : "Company Name",
		"email" : "Email Address",
		"password" : "your Password",
		"applicant" : "Applicant Name",
		"address1" : "your Address",
		"city" : "your City",
		"state" : "your State",
		"zip_code" : "your Zip Code",
		"phone" : "your Phone Number",
		"business_start_date" : "Starting Business Date",
		"incorporation_date" : "Date of Incorporation",
		"estimated_account_req" : "Estimated Open Account Requirement"
	};
		
	fields = add_bank_fields(fields);
	fields = add_trade_fields(fields);
	
	function check_fields(fields) {
		phone_fields = [
			"phone",
			"bank_reference[phone]",
			"bank_reference[fax]",
			"trade_reference[0][phone]",
			"trade_reference[0][fax]",
			"trade_reference[1][phone]",
			"trade_reference[1][fax]",
			"trade_reference[2][phone]",
			"trade_reference[2][fax]"
		];
		
		email_fields = ["email"]; 
		
		for ( i in fields ) {
			if (!has_value(i,fields[i])) { return false; }
		}
		
		for ( i in  phone_fields ) {
			if (!valid_phone(phone_fields[i])) { return false; }
		}
		
		for ( i in  email_fields ) {
			if (!valid_email(email_fields[i])) { return false; }
		}
		
		return true;
	}

	function has_value(field_name, nice_name) {
		try {
			return checkSelect(form.elements[field_name],"V","","Please enter "+nice_name+".",false);
		} catch(e) {
			try { console.warn(e); } catch (e2) { }
			return true;
		}
	}
	
	function valid_phone(field_name) {
		try {
			return checkUSPhone(form.elements[field_name],false);
		} catch(e) {
			try { console.warn(e); } catch (e2) { }
		}
		return true;
	}

	function valid_email(field_name) {
		try {
			return checkEmail(form.elements[field_name],false);
		} catch(e) {
			try { console.warn(e); } catch (e2) { }
		}
		return true;
	}
	
	function add_bank_fields(fields) {
		fields = add_address_fields(fields, 'bank_reference', 'Bank Reference > ');
		fields["bank_reference[account_num]"] = "Bank Reference > Account No.";
		return fields;
	}

	function add_trade_fields(fields) {
		for (j = 0; j < 3; ++j) {
			fields = add_address_fields(fields, 'trade_reference['+j+']', 'Trade '+(j+1)+' Reference > ');
			fields["trade_reference["+j+"][account_num]"] = "Trade "+(j+1)+" Reference > Account No.";
		}
		return fields;
	}
	
	function add_address_fields(fields, field_prefix, name_prefix) {
		address = {
			"name" : "Name",
			"address1" : "Address",
			"city" : "City",
			"state" : "State",
			"zip_code" : "Zip Code",
			"phone" : "Phone Number",
			"fax" : "Fax Number"
		};
		
		for(i in address) {
			fields[field_prefix+"["+i+"]"] = name_prefix+address[i];
		}
		
		return fields;
	}
	
	return check_fields(fields);
}

////////////////////////////////////////////////
// disabling and enabling shipping info fields
////////////////////////////////////////////////

function toggleFields(form)
{
	var toggle = form.elements['same_as_billing'];

	var arrShipFields = new Array('ship_fullname', 'ship_address', 'ship_city', 'ship_state', 'ship_zip', 'ship_phone');
	var fieldShipCount = arrShipFields.length;

	var arrBillFields = new Array('billing_fullname', 'billing_address', 'billing_city', 'billing_state', 'billing_zip', 'billing_phone');
	var fieldBillCount = arrBillFields.length;

	var i = 0;

	if (toggle.checked == false) {
		//Already checked, unset everything
		for ( i=0; i<fieldShipCount; i++) {
			form.elements[arrShipFields[i]].value = "";
		}//for

	} else {
		//Not yet checked, copy the values from billing
		for ( i=0; i<fieldShipCount; i++) {
			form.elements[arrShipFields[i]].value = form.elements[arrBillFields[i]].value;
		}//for
	}

}//end toggleFields

function toggleSaveProfile(elem) {
	var form = elem.form;

	//valid values are insert, donotupdate, and update
	if (elem.checked == true) {
		form.elements['profilecontrol'].value = 'insert';

	} else {
		form.elements['profilecontrol'].value = 'donotupdate';

	}

	//alert(form.elements['profilecontrol'].value);

}//end toggleSaveProfile

function checkField() {
	var frm = document.search_store;

	if ( (frm.p_keyword.value == "" ) || (frm.p_keyword.value == " " ) ) {

		alert("A Keyword is required to search");
		return false;
	}

}

function validateSearch()
{
	var frm = document.getElementById('search');

	if ( trim(frm.keyword.value) == "" && did('manufacturer_search_select').value != 'searchAll' ) {
		alert("A keyword is required to search");
		return false;
	}
	return true;
}


function checkEmailSignup() {

	var frm = document.emailSignup;

	if ( (frm.firstname.value == "" ) || (frm.firstname.value == " " ) ) {

		alert("First name is required");
		return false;
	}

	if ( (frm.lastname.value == "" ) || (frm.lastname.value == " " ) ) {
		alert("Last name is required");
		return false;
	}

	if ( (frm.email.value == "") || (frm.email.value == " ") ) {

		alert("E-mail is required");
		return false;
	}

	return true;

}
function LoginOptionCheck(myself, hasCookie) {

	frm = document.forms['new_login'];
	// if the new Customer item is checked
	var elem_pass_new = document.getElementById('newcustomerpassword');
	var elem_pass_old = document.getElementById('returningcustomerpassword');

	if ( myself.value == "new" ) {
		elem_pass_old.disabled = true;
		elem_pass_old.style.display = "none";
		elem_pass_new.disabled = true;
		elem_pass_new.style.display = "";
		frm.elements['action'].value = "account_new";
		//document.getElementById("remember").style.display="";
		//document.getElementById("forget").style.display="none";
	} else {

		elem_pass_old.disabled = false;
		elem_pass_old.style.display = "";
		elem_pass_new.disabled = true;
		elem_pass_new.style.display = "none";
                        frm.elements['loginemail'].focus();
		frm.elements['action'].value = "account";
		//document.getElementById("remember").style.display=!hasCookie;
		//document.getElementById("forget").style.display=hasCookie;

	}

	frm.elements['loginemail'].focus();
}

function LoginOptionCheck2(myself, hasCookie) {

	frm = document.forms['new_login'];
	// if the new Customer item is checked
	var elem_pass_new = document.getElementById('newcustomerpassword');
	var elem_pass_old = document.getElementById('returningcustomerpassword');

	if ( myself.value == "new" ) {
		elem_pass_old.disabled = true;
		elem_pass_old.style.display = "none";
		elem_pass_new.disabled = true;
		elem_pass_new.style.display = "none";
		frm.elements['action'].value = "account_new";

		document.getElementById('new_cust').style.display = "none";
	} else {

		elem_pass_old.disabled = false;
		elem_pass_old.style.display = "";
		elem_pass_new.disabled = true;
		elem_pass_new.style.display = "none";
                        frm.elements['loginemail'].focus();
		frm.elements['action'].value = "account";
		
		document.getElementById('new_cust').style.display = "";
	}

	frm.elements['loginemail'].focus();
}

function focusLoginField() {
	if ( typeof(document.new_login) != "undefined" ) {
		document.new_login.loginemail.focus();
	}
}

function loadPreview() {

	var caption_value = (window.opener.document.getElementById("caption") ? window.opener.document.getElementById("caption").value : null);
	var headline_obj = window.opener.document.getElementById("headline");
	var body_obj = window.opener.document.getElementById("body") || window.opener.document.getElementById('wysiPlainTextarea1');
	var child_head = document.getElementById("headline");
	var child_body = document.getElementById("body") || document.getElementById('wysiPlainTextarea1');
	var child_caption = document.getElementById("img_caption");

	if ( caption_value != '' && child_caption != null ) {

		child_caption.innerHTML = caption_value;
	}
	child_head.innerHTML = headline_obj.value;
	child_body.innerHTML = body_obj.value;

}

function fadeout() {
	for (var iterator = 0; iterator < arguments.length; iterator++) {
		arguments[iterator].value = '';
		arguments[iterator].disabled = true;
	}
}

function fadein() {
	for (var iterator = 0; iterator < arguments.length; iterator++) {
		arguments[iterator].disabled = false;
	}
	arguments[1].focus();
	arguments[1].select();
}

function quantity_check(frm)
{
	if ( frm.elements['qty'].value < 1 || !validateInteger(frm.elements['qty'].value) ) {
		alert("Quantity must be an integer greater than 0");
		return false;
	}
}

function multiple_quantity_check(frm)
{
	for ( var i=0; i<arr_content_index.length; i++ ) {
		if ( !validateInteger(frm.elements['update[' + arr_content_index[i] + ']'].value) ) {
 			alert("Quantity must be an integer greater than 0");
			return false;
		}
	}
}

function validateInteger( strValue ) {

  var objRegExp  = /(^-?\d\d*$)/;

  return objRegExp.test(strValue);
}

/**
  * pops up a window a fraction of the size of the current one
  */
function popup(url) {
	var ratio = 0.75;
	var def_x = 800;
	var	def_y = 600;
	//get current window's dimensions
	parent_x = document.documentElement.clientWidth;
	if (!parent_x) parent_x = document.body.clientWidth;
	if (!parent_x) parent_x = window.innerWidth;
	if (!parent_x) parent_x = def_x;
	parent_y = document.documentElement.clientHeight;
	if (!parent_y) parent_y = document.body.clientHeight;
	if (!parent_y) parent_y = window.innerHeight;
	if (!parent_y) parent_y = def_y;
	//end get current window's dimensions
	//calculate child dimensions
	var child_x = ratio * parent_x;
	var child_y = ratio * parent_y;
	//end calculate child dimensions
	//popup the window
	window.open(url, "pop_window", "status=1, scrollbars=1, width="+child_x+", height="+child_y);
	//end popup the window
	return false;
}

// fill_span(_name, _html) fills object id _name with contents of _html after lu_unescaping
function fill_span(_name, _html) {
	var span = document.getElementById(_name);
	span.innerHTML = lu_unescape(_html);
}

//lu_unescape(_input) unescapes code which has been escaped for the live updater
function lu_unescape( _input) {
	output = _input;
	output = output.replace(/#lt#/g, "<");
	output = output.replace(/#rt#/g, ">");
	return output;
}

function cartAction(product_id, action)
{
	var frm = document.getElementById('frmCart');

	if ( frm.elements['product_id'] ) {
		frm.elements['product_id'].value = product_id;
	}

	if ( frm.elements['action'] ) {
		frm.elements['action'].value = action;
	}

	if ( multi_quantity_check(frm, false) ) {
		//frm.submit();
		return true;
	}

	return false;
}

function submitComment(product_id)
{
	var frm = document.getElementById('frmComment');

	if ( frm.elements['product_id'] ) {
		frm.elements['product_id'].value = product_id;
	}
	
	if(validateProductComment(frm)){
		frm.submit();
	}
	//return false;
	
}

function favoritesAction(product_id, option_id, action)
{
	var frm = document.getElementById('frmFavorites');

	if ( frm.elements['product_id'] ) {
		frm.elements['product_id'].value = product_id;
	}

	if ( frm.elements['option_id'] ) {
		frm.elements['option_id'].value = option_id;
	}

	if ( frm.elements['action'] ) {
		frm.elements['action'].value = action;
	}

	frm.submit();

	return false;
}

var xmlLoaded = false;
var xslLoaded = false;

function loadXSL()
{
	if ( document.implementation.createDocument ) {
		xslDoc = document.implementation.createDocument("", "", null);
		xslDoc.addEventListener("load", onXSLLoad, false);
		xslDoc.load('listview/categories.xsl');
	} else if ( window.ActiveXObject ) {
		xslDoc = new ActiveXObject("Microsoft.XMLDOM");
		xslDoc.async = false;
		xslDoc.validateOnParse = false;
		xslDoc.load('listview/categories.xsl');
		xslLoaded = true;
	}
}

function onXMLLoad()
{
	xmlLoaded = true;
	styleLoad();
}

function onXSLLoad()
{
	xslLoaded = true;
	styleLoad();
}
var timer;
var curr = 1;
function styleLoad()
{
	if ( xmlLoaded && xslLoaded ) {
		var processor = new XSLTProcessor();

		processor.importStylesheet(xslDoc);
		var doc = processor.transformToFragment(xmlDoc, document);

		var list = document.getElementById('list');

		if ( document.getElementById('list') ) {
			//console.log('replacing list parent node?');
			document.getElementById('list').parentNode.replaceChild(doc, document.getElementById('list'));
		}
		xmlLoaded = false;
		document.body.style.cursor = 'auto';
		clearTimeout(timer);
		curr = 1;
		//xslLoaded = false;
	}
}

var resorting_selected = false;
var lvhistinitted = false;

function refreshView(page, sort, dir, perpage)
{
	try {
		if ( !xslLoaded ) {
			loadXSL();
		}
		if ( sort != undefined ) {
			var url = 'listview.php?ret&pg='+page+'&srt='+sort+'&dir='+dir+'&perpage='+perpage+'&viewtype='+ListviewType;
			for( x in lv_tracking) {
				url += "&tracking["+x+"]="+lv_tracking[x];
			}
			hist_set(url.substring(13));
		} else {
			var url = page;
		}

		if ( document.implementation.createDocument ) {
			timer = setTimeout("dotDot()", 0);
			document.body.style.cursor = 'progress';
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.addEventListener("load", onXMLLoad, false);
			xmlDoc.load(url);

		} else if ( window.ActiveXObject ) {
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = false;
			xmlDoc.validateOnParse = false;
			xmlDoc.load(url);
			//console.log('adding html to list');
			document.getElementById('list').innerHTML = xmlDoc.transformNode(xslDoc);
		} else {
			return true;
		}
		return false;
	 } catch (e) {
		if ( resorting_selected ) {
			resorting_selected = false;
			throw "Resort";
		} else {
			if (window.location.toString().indexOf('product_search') > -1) {
				to_url = window.location.pathname+'?ret&pg='+page+'&srt='+sort+'&dir='+dir+'&perpage='+perpage+'&viewtype='+ListviewType;
				for( x in lv_tracking) {
					to_url += "&tracking["+x+"]="+lv_tracking[x];
				}

				window.location = to_url;
				return false;
			} else {
				return true;
			}
		}
	}
}

function refreshSort(page, sort, dir, perpage)
{
	resorting_selected = true;
	try {
		refreshView(page, sort, dir, perpage);
	} catch (e) {
		window.location = window.location.pathname+"?pg="+page+"&srt="+sort+"&dir="+dir+"&perpage="+perpage;
	}
}

function dotDot()
{
	if ( timer ) {
		clearTimeout(timer);
	}

	var dots = '';
	for ( var i=0; i < curr; i++ ) {
		dots = dots + '.';
	}

	curr += 1;
	if ( curr > 3 ) {
		curr = 1;
	}

	var str = 'Loading'+dots;
	document.getElementById('now_loading').innerHTML = str;

	timer = setTimeout("dotDot()", 300);
}

function lv_hist_change() {
	if ( lvhistinitted ) {
		lvhistinitted = false;
		return;
	}
	//console.log(unFocus.History.getCurrent());
	var params = unFocus.History.getCurrent();
	if ( params == '' ) {
		params = 'viewtype='+ListviewType;
		for( x in lv_tracking) {
			params += "&tracking["+x+"]="+lv_tracking[x];
		}
	}
	//refreshView('listview.php?'+params);
	//console.log(hist.body.innerHTML);
	//console.log("Hit");
}

function hist_set(str)
{
	lvhistinitted = true;
	unFocus.History.addHistory(str);
}

var express = false;
var storeCC = false;

function doProfileChange(type) {
	var id = '';

	if ( $(type+'_id') ) {
		id = $(type+'_id').value;
	}

	if ( id != '' ) {
		if ( type == 'billingAddr' ) {
			if ( !express ) {
				if ( id == '0' ) {
					$(type+'_id').value = 'new';
					
					$('add_addr_profile').style.display = '';
					$('shipping_action').value = 'true';
					
					$('address_name').value = '';
				} else if ( id == 'new' ) {
					$('add_addr_profile').style.display = '';
					$('shipping_action').value = 'true';
				} else {
					$('update_addr_profile').style.display = '';
					$('shipping_action').value = 'true';
				}
			}
		} else if ( (type == 'billing' && storeCC) || type != 'billing' ) {
			try {
				$('update_profile').style.display = '';
			} catch(e) {}
		}
		
		$(type+'_action').value = 'true';
	} else {
		if ( type == 'billingAddr' ) {
			if ( !express ) {
				$('update_addr_profile').style.display = 'none';
			}
		} else if ( (type == 'billing' && storeCC) || type != 'billing' ) {
			$('update_profile').style.display = 'none';
		}
	}
}

function changeBilling(id)
{
	$('update_profile').style.display = 'none';
	
	if ( id == '' ) {
		$('add_profile').style.display = '';
		$('billing_action').value = 'true';
	} else {
		$('add_profile').style.display = 'none';
		$('billing_action').value = 'false';
	}
	
	$('add_billing_profile').checked = false;
	$('update_billing_profile').checked = false;
	
	$('name_profile').style.display = 'none';

	var uri = "ActivaUpdater.php";
	var data = "";

	data += nh.compressData("action", "changeBilling");
	data += nh.compressData("id", id);

	ActivaUpdater(uri, data);
}

function changeBillingAddr(id)
{
	$('update_addr_profile').style.display = 'none';

	if ( id == 'new' && !express ) {
		$('add_addr_profile').style.display = '';
		$('shipping_action').value = 'true';
	} else {
		$('add_addr_profile').style.display = 'none';
		$('shipping_action').value = 'false';
	}
	
	$('add_shipping_profile').checked = false;
	$('update_shipping_profile').checked = false;
	
	$('name_billing_addr').style.display = 'none';

	var uri = "ActivaUpdater.php";
	var data = "";

	data += nh.compressData("action", "changeBillingAddr");
	data += nh.compressData("id", id);

	ActivaUpdater(uri, data);
}

function changeShipping(id)
{
	$('update_profile').style.display = 'none';

	if ( id == '' ) {
		$('add_profile').style.display = '';
		$('shipping_action').value = 'true';
	} else {
		$('add_profile').style.display = 'none';
		$('shipping_action').value = 'false';
	}
	
	$('add_shipping_profile').checked = false;
	$('update_shipping_profile').checked = false;
	
	$('name_profile').style.display = 'none';

	var uri = "ActivaUpdater.php";
	var data = "";

	data += nh.compressData("action", "changeShipping");
	data += nh.compressData("id", id);

	ActivaUpdater(uri, data);
}

function showProfileName(type, checked, action) {
	var label = '';
	
	switch ( type ) {
		case 'shipping':
			label = 'Address';
			break;
		case 'billing':
			label = 'Saved Card';
			break;
	}
	
	switch ( action ) {
		case 'add':
			$('name_profile_label').innerHTML = 'Name this '+label;
			break;
		case 'update':
			$('name_profile_label').innerHTML = 'Name of '+label;
			break;
	}
	
	if ( checked ) {
		$('name_profile').style.display = '';
	} else {
		$('name_profile').style.display = 'none';
	}
}

function showBillingAddrName(checked, action) {
	switch ( action ) {
		case 'add':
//			$('name_billing_addr_label').innerHTML = 'Name this Address';
			$('name_profile_label').innerHTML = 'Name this Address';
			break;
		case 'update':
//			$('name_billing_addr_label').innerHTML = 'Name of Address';
			$('name_profile_label').innerHTML = 'Name of Address';
			break;
	}
	
	if ( checked ) {
		$('name_billing_addr').style.display = '';
	} else {
		$('name_billing_addr').style.display = 'none';
	}
}

function changeCountry(country)
{
	if ( country == '213' || country == '38' || country == '' ) {
		document.getElementById('province_box').style.display='none';
		document.getElementById('state_box').style.display='';
	} else {
		document.getElementById('province_box').style.display='';
		document.getElementById('state_box').style.display='none';
	}
}

function handleKeyPress(event)
{
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	// Enter
	if ( keyCode == 13 ) {
		cartAction('', 'quantity_update');
	}
}

function handleKeyPressCartZip(event)
{
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	// Enter
	if ( keyCode == 13 ) {
		getShipPrice();
		return false;
	}
}

function ignoreEnterKeyPress(event)
{
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	// Enter = 13
	return keyCode != 13;
}

var paymentTypes = new Array('cc', 'pp', 'po', 'gg');

function switchPaymentType(type)
{
	for ( var x=0; x<paymentTypes.length; x++ ) {
		if ( type == paymentTypes[x] ) {
			if ( $(paymentTypes[x]+'_form') ) {
				$(paymentTypes[x]+'_form').style.display = '';
			}
		} else {
			if ( $((paymentTypes[x]+'_form')) ) {
				$(paymentTypes[x]+'_form').style.display = 'none';
			}
		}
	}
}

function multi_quantity_check(frm, popup)
{
	if ( document.getElementById('action') ) {
		if ( document.getElementById('action').value != 'remove_item' ) {
			for ( var i=0; i<frm.length; i++ ) {
				var element = frm.elements[i];
				if ( element.name.search(/qty/) >= 0 ) {
					if ( element.value < 1 || !validateInteger(element.value) ) {
						if ( popup ) {
							alert("Quantity must be an integer greater than 0");
						}
						return false;
					}
				}
			}
		}
	} else {
		for ( var i=0; i<frm.length; i++ ) {
			var element = frm.elements[i];
			if ( element.name.search(/qty/) >= 0 ) {
				if ( element.value < 1 || !validateInteger(element.value) ) {
					if ( popup ) {
						alert("Quantity must be an integer greater than 0");
					}
					return false;
				}
			}
		}
	}

	return true;
}

function getShipServices(carrier)
{
	var uri = "ActivaUpdater.php";

	var data = "";

	data += nh.compressData('action', "getShipServices");
	data += nh.compressData('target', "shiptype");
	data += nh.compressData('carrier', carrier);

	ActivaUpdater(uri, data);
}

function getShipPrice(service, carrier)
{
	$('shiptotalvalue').innerHTML = 'loading';
	$('gnd_total').innerHTML = 'loading';

	if ( $('grp_total') ) {
		$('grp_total').innerHTML = 'loading';
	}
	
	if ( $('pmo_total') ) {
		$('pmo_total').innerHTML = 'loading';
	}

	if ( $('gft_total') ) {
		$('gft_total').innerHTML = 'loading';
	}
	
	
	var destcity = '';
	var deststate = '';
	var destzip = '';
		
	if ( document.getElementById('destcity')) {
		destcity = document.getElementById('destcity').value;
	}
	if ( document.getElementById('deststate')) {
		deststate = document.getElementById('deststate').value;
	}
	if ( document.getElementById('destzip')) {
		destzip = document.getElementById('destzip').value;
	}
	
	if(destzip != '' && service != '-none-') { //destcity != '' && deststate != '' && 
		showID('shipping_estimate_row');
	} else {
		hideID('shipping_estimate_row');
	}
	
	if(! carrier)
		carrier = document.getElementById('shipcarrier').value;
	if(! service)
		service = document.getElementById('shiptype').value;

	var uri = "ActivaUpdater.php";

	var data = "";

	data = nh.compressData("action", "getShipPrice");
	data += nh.compressData("service", service);
	data += nh.compressData("carrier", carrier);
	if(destcity != '') {
		data += nh.compressData("destcity", destcity);
	}
	if(deststate != '') {
		data += nh.compressData("deststate", deststate);
	}
	if(destzip != '') {
		data += nh.compressData("destzip", destzip);
	}

	ActivaUpdater(uri, data);
}

function $(id) {
	return document.getElementById(id);
}

function ltrim(string)
{
	return string.replace(/^\s*/, '');
}

function rtrim(string)
{
	return string.replace(/\s*$/, '');
}

function trim(string)
{
	return rtrim(ltrim(string));
}

var cleared = false;
function clearCCNum(input)
{
	if ( !cleared ) {
		input.value = '';
		cleared = true;
	}
}

function clearCart()
{
        var uri="ActivaUpdater.php";
        var data="";
        data = nh.compressData("action", "clear_cart");
        ActivaUpdater(uri, data);
}

function clearCart()
{
        var uri="ActivaUpdater.php";
        var data="";
        data = nh.compressData("action", "clear_cart");
        ActivaUpdater(uri, data);
}

function updateGoogle(comments)
{
        var uri="ActivaUpdater.php";
        var data="";
        data += nh.compressData("action", "update_google");
        data += nh.compressData("comments", comments);
        ActivaUpdater(uri, data);
}

function number_format(num) {
  var num = String(num);
  var re0 = /(\d+)(\d{3})($|\..*)/;
  if (re0.test(num))
    return num.replace(
      re0,
      function(str,p1,p2,p3) { return number_format(p1) + "," + p2 + p3; }
    );
  else
    return num;
}


function moneyFormat(n) {
	return number_format(n.toFixed(2));
}

function did(name) {
	return document.getElementById(name);
}

function hideID(name) {
     if(did(name)) {
        did(name).style.display = "none";
     }

    if (name.indexOf('categoryNav') > -1) {
        did(name).style.top = '';
    }
 }

function showID(name) {
	if(did(name)) {
		did(name).style.display = "";
	}
}

function toggleDisplay(name) {
	if(did(name)) {
		if(did(name).style.display == "none") {
			showID(name);
		} else {
			hideID(name);
		}
	}
}


function displayProductTab(region) {
	var regions=new Array("shipping","specifications");
	
	for(var i=0;i<regions.length;i++) {
		if(region != regions[i]) {
			hideID(regions[i]);
			did(regions[i]+"_link").className = '';
		} else {
			showID(regions[i]);
			did(regions[i]+"_link").className = 'on';
		}
	}
}


var options_prices1=new Array();
function updatePrices() {
	for(var i=0; i<options_prices1.length; i++) {
		
		var subtotal = '';
		var count = parseInt(document.getElementById('qty'+i).value);
		
		if(count > 0 && options_prices2_end[i] > 0 && options_prices2_end[i] < count ) {
			subtotal = count*options_prices3[i];
		} else if(count > 0 && options_prices1_end[i] > 0 && options_prices1_end[i] < count ) { 
			subtotal = count*options_prices2[i];
		} else if(count > 0) { 
			subtotal = count*options_prices1[i];
		}
		
		if(subtotal != '') {
			document.getElementById('subtotal'+i).innerHTML = "$"+moneyFormat(subtotal);
		} else {
			document.getElementById('subtotal'+i).innerHTML = '';
		}
	}
}

function showSubMenu( span, menu) {
		
	showID(menu);
	elem = document.getElementById(menu);
	
    if ((elem.offsetTop + elem.clientHeight) > (document.body.scrollTop + document.body.clientHeight)) {
	
		if (elem.parentNode.childNodes[1].clientHeight) {
			offset = (elem.offsetTop - elem.clientHeight) + elem.parentNode.childNodes[1].clientHeight;
			if (offset >= document.body.scrollTop) {
				elem.style.top = (offset) + 'px';
			}
			return ;
		}
		
		next_node = elem.parentNode;
		
		attempts = 0;
		
		while (next_node.nextSibling && ++attempts < 5) {
			sib = next_node.nextSibling;
			if (sib.nodeType == 1 && sib.offsetTop) {
				offset = (elem.offsetTop - elem.clientHeight) + (sib.offsetTop - elem.parentNode.offsetTop);	
				if (offset >= document.body.scrollTop) {
					elem.style.top = (offset) + 'px';
				}
				return ;
			} else {
				next_node = sib;
			}
		}

		offset = (elem.offsetTop - elem.clientHeight);
		elem.style.top = (offset) + 'px';
		return ;
    }
}


function updateCountry() {
	if ( did('country').value == '' ) {
		return;
	}
	did('state').style.display = 'none';
	did('province').style.display = 'none';
	did('other').style.display = 'none';
	if ( did('country').value == 'US' || did('country').value == '213' ) {
		did('state').style.display = '';
	} else if ( did('country').value == 'CA' || did('country').value == '38' ) {
		did('province').style.display = '';
	} else {
		did('other').style.display = '';
	}
}

function checkShippingSelect() {
	if(did('shiptype')) {
		if(did('shiptype').value == '-none-') {
			alert('Please select a shipping method');
			did('shiptype').focus();
			return false;
		} else {
			return true;
		}
	}	
}

function changeFreeGift(checked) {
	var uri = 'ActivaUpdater.php';
	var data = '';
	
	data += nh.compressData('action','changeFreeGift');
	data += nh.compressData('checked',(checked?'yes':'no'));
	
	ActivaUpdater(uri,data);
}
