/*
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 Your Name.",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 validatePay(form) {
	return (
				validateBillingAddress(form) &&
				 //checkSelect(form.elements["billing_id"],"V","","You must select a Credit Card",false) &&
				 checkSelect(form.elements["billing[fullname]"],"V","","Please enter the Name exactly as it appears on the Credit Card.",false) &&
				 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));
}

function validateBillingAddress(form) {	
	return (
		checkSelect(form.elements["billing[first_name]"],"V","","Please enter the billing first name.",false) &&
		checkSelect(form.elements["billing[last_name]"],"V","","Please enter the billing last 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)
	);
}


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

}

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(form.elements["fullname"]) {
        if(! checkSelect(form.elements["fullname"],"V","","Please enter your full name.",false)) {
            return false;
        }
    }
    if(form.elements["firstname"]) {
        if(! checkSelect(form.elements["firstname"],"V","","Please enter your first name.",false)) {
            return false;
        }
    }
    if(form.elements["lastname"]) {
        if(! checkSelect(form.elements["lastname"],"V","","Please enter your last name.",false)) {
            return false;
        }
    }
	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 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)
	) {
	
		if(form.elements["account[password1]"].value != form.elements["account[password2]"].value) {
			alert("Please verify that your password and confirmation password match.");
			return false;
		}
		
		if(form.elements["account[password1]"].value.length < 6) {
			alert("Your password must be at least 6 characters.");
			return false;
		}
		
		return validateShipping(form);
	}

	return false;
}

function validateShipping(form) {	
	return (
		checkSelect(form.elements["shipping[first_name]"],"V","","Please enter the shipping first name.",false) &&
		checkSelect(form.elements["shipping[last_name]"],"V","","Please enter the shipping last 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[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 validateSearch(form) {
	return (
		checkString(form.elements['keyword'], 'A keyword is required to search', false)
	);	
}

function validateStockNotification(form) {
	return (
		checkSelect(form.elements["fullname"],"V","","Please enter your Full 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 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 LoginOptionCheck(myself, hasCookie) {

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

	if ( myself.value == "new" ) {
		elem_pass_old.disabled = true;
		hideElements(elem_pass_old);
		elem_pass_new.disabled = true;
		showElements(elem_pass_new);
	} else {

		elem_pass_old.disabled = false;
		showElements(elem_pass_old);
		elem_pass_new.disabled = true;
		hideElements(elem_pass_new);
		frm.elements['loginemail'].focus();

	}

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

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

function loadPreview() {

	try {
		var body_obj = opener.did("wysiPlainTextarea1");
		var headline_obj = opener.did("headline");
		var child_head = did("headline");
		var child_body = did("body");
		var caption_value = window.opener.did("caption").value;
		var child_caption = did("img_caption");
	} catch (e) {
		try {
			console.debug(e);
		} catch (e2) {
			
		}
	}
		
	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 ) {
  return /(^-?\d\d*$)/.test(strValue);
}

/**
  * pops up a window a fraction of the size of the current one
  */
function popup(url) {
	var ratio = 0.75, def_x = 800, 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;
}

//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 = did('frmCart');
	var pid = frm.elements['product_id'];
	var act = frm.elements['action'];
	if (pid){
		pid.value = product_id; 
	}
	if (act) {
		act.value = action;
	}
	frm.submit();
	return false;
}

function submitComment(product_id) {
	var frm = did('frmComment');

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

var options_prices1=new Array();
function updatePrices() {
	for(var i=0; i<options_prices1.length; i++) {
		var subtotal = '';
		var count = parseInt(did('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 != '') {
			did('subtotal'+i).innerHTML = "$"+moneyFormat(subtotal);
		} else {
			did('subtotal'+i).innerHTML = '';
		}
	}
}

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

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 favoritesAction(product_id, option_id, action) {
	var frm = did('frmFavorites');
	var pid = frm.elements['product_id'];
	var oid = frm.elements['option_id'];
	var act = frm.elements['action'];
	
	if (pid) {
		pid.value = product_id;
	}
	if (oid) {
		oid.value = option_id;
	}
	if (act) {
		act.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/products.xsl');
	} else if ( window.ActiveXObject ) {
		xslDoc = new ActiveXObject("Microsoft.XMLDOM");
		xslDoc.async = false;
		xslDoc.validateOnParse = false;
		xslDoc.load('listview/products.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 = did('list');
		if ( list ) {
			list.parentNode.replaceChild(doc, 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);
			did('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 ignoreEnterKeyPress(event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	// Enter = 13
	return keyCode != 13;
}

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;
	did('now_loading').innerHTML = str;

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

function lv_hist_change() {
	if ( lvhistinitted ) {
		lvhistinitted = false;
		return;
	}
	var params = unFocus.History.getCurrent();
	if ( params == '' ) {
		params = 'viewtype='+ListviewType;
		for( x in lv_tracking) {
			params += "&tracking["+x+"]="+lv_tracking[x];
		}
		if(sort_value) {
			params += "&srt="+sort_value;
		}
	}
	refreshView('listview.php?'+params);
}

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

var express = false;
var storeCC = false;

function doProfileChange(type) {
	var type_id = did(type+'_id');
	var id = type_id ? type_id.value : '';

	if ( id != '' ) {
		if ( type == 'billingAddr' ) {
			if ( !express ) {
				if ( id == '0' ) {
					type_id.value = 'new';
					did('shipping_action').value = 'true';
					did('address_name').value = '';
					showID('add_addr_profile');
				} else if ( id == 'new' ) {
					did('shipping_action').value = 'true';
					showID('add_addr_profile');
				} else {
					did('shipping_action').value = 'true';
					showID('update_addr_profile');
				}
			}
		} else if ( (type == 'billing' && storeCC) || type != 'billing' ) {
			showID('update_profile');
		}
		did(type+'_action').value = 'true';
	} else {
		if ( type == 'billingAddr' ) {
			if ( !express ) {
				hideID('update_addr_profile');
			}
		} else if ( (type == 'billing' && storeCC) || type != 'billing' ) {
			hideID('update_profile');
		}
	}
}

function changeBilling(id) {
	var elms = ['update_profile','name_profile'];	
	if (!id) {
		showID('add_profile');
		did('billing_action').value = 'true';
	} else {
		elms.push('add_profile');
		did('billing_action').value = 'false';
	}
	hideElements(elms);
	
	did('add_billing_profile').checked = false;
	did('update_billing_profile').checked = false;

	var data = "";

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

	ActivaUpdater("ActivaUpdater.php", data);
}

function changeBillingAddr(id) {
	var elms = ['update_addr_profile','name_billing_addr'];

	if ( id == 'new' && !express ) {
		showID('add_addr_profile');
		did('shipping_action').value = 'true';
	} else {
		elms.push('add_addr_profile');
		did('shipping_action').value = 'false';
	}
	hideElements(elms);
	
	did('add_shipping_profile').checked = false;
	did('update_shipping_profile').checked = false;

	var data = "";

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

	ActivaUpdater("ActivaUpdater.php", data);
}

function changeShipping(id) {
	var elms = ['update_profile','name_profile'];
	if (!id) {
		showID('add_profile');
		did('shipping_action').value = 'true';
	} else {
		elms.push('add_profile');
		did('shipping_action').value = 'false';
	}
	hideElements(elms);
	
	did('add_shipping_profile').checked = false;
	did('update_shipping_profile').checked = false;

	var data = "";

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

	ActivaUpdater("ActivaUpdater.php", 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':
			did('name_profile_label').innerHTML = 'Name this '+label;
			break;
		case 'update':
			did('name_profile_label').innerHTML = 'Name of '+label;
			break;
	}
	did('name_profile').style.display = (checked) ? '' : 'none';
}

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

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 handleKeyPress(event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

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

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

function switchPaymentType(type) {
	paymentTypes.forEach(function(ptype){
		var frm = did(ptype+'_form');
		if (type == ptype && frm) {
			showElements(frm); 
		} else if(frm) {
			hideElements(frm);
		}
	});
}

function multi_quantity_check(frm, popup) {
	if ( did('action') ) {
		if ( did('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 data = "";

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

	ActivaUpdater("ActivaUpdater.php", data);
}

function getShipPrice(service, carrier) {
	var elms = ['shiptotalvalue','gnd_total','grp_total','pmo_total','gft_total'];
	elms.forEach(function(id){
		var el = did(id);
		if (el) {
			el.innerHTML = 'loading';
		}
	});

	var data = "";

	data = nh.compressData("action", "getShipPrice");
	data += nh.compressData("service", service);
	data += nh.compressData("carrier", carrier);

	ActivaUpdater("ActivaUpdater.php", data);
}

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

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

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

function updateCountry() {
	var country = did('country');
	if (!country || country.value == '' ) {
		return;
	}

	hideElements('state','province','other');
	if ( country.value == 'US' || country.value == '213' ) {
		showID('state');
	} else if ( country.value == 'CA' || country.value == '38' ) {
		showID('province');
	} else {
		showID('other');
	}
}

function changeProductOption(id) {
	var uri="ActivaUpdater.php";
    var data="";
    
    data += nh.compressData("action", "changeProductOption");
    data += nh.compressData("id", id);
    
    ActivaUpdater(uri, data);
}

/**
 * DOM Utilities
 */

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

/**
 * dbn - Shorcut for getElementsByName
 * @param	name	The element name you are looking for
 * @param	parent	optional;The parent item to search within
 * @return			Collection of elements
 */
function dbn(name, parent) {
	return (parent || document).getElementsByName(name);
}

/**
 * dbt - Shorcut for getElementsByTagName
 * @param	tag		The element tagName you are looking for
 * @param	parent	optional;The parent item to search within
 * @return 			Collection of elements
 */
function dbt(tag, parent) {
	return (parent || document).getElementsByTagName(tag);
	}

/**
 * dbc - Shortcut for getElementsByClass
 * @param	className	The className you are looking for
 * @param	parent		optional;The parent item to search within
 * @return				Array of elements
 */
function dbc(className, parent) {
	return getElementsByClass((parent || document), className);
}

//Find elements with a given className and returns them in an array
function getElementsByClass( boundingBox, className ) {
	var children = dbt('*', boundingBox);
	var classElements = new Array();

	for ( var i=0; i < children.length; i++ ) {
		if ( children[i].className == className ) {
			classElements.push(children[i]);
    }
}
	return classElements;
}

/**
 * next - Returns the next non-whitespace node in the DOM
 * @param	el	object		Element node from which to start
 * @return		object		Next non-whitespace element in the DOM
 */
function next(el){ elm=elm.nextSibling; return (elm.nodeType==1) ? elm : next(elm); }
/**
 * prev - Returns the previous non-whitespace node in the DOM
 * @param	el	object		Element node from which to start
 * @return		object		Previous non-whitespace element in the DOM
 */
function prev(el){ elm=elm.previousSibling; return (elm.nodeType==1) ? elm : prev(elm); }

/**
 * createElement - Shortcut for document.createElement
 * @param	tag		Tag of the element to create
 * @return			Element or null if no tag specified
 */
function createElement(tag) {
	if (!tag) { return null; }
	return document.createElement(tag);
}

/**
 * createTextNode - Shortcut for document.createTextNode
 * @param	text	Text to place inside the new node
 * @return			New text node
 */
function createTextNode(text) {
	return document.createTextNode(String(text));
	}

//Displays an element
function showID(id) {
	showElements(id);
}
//Hides an element
function hideID(id) {
	hideElements(id);
}
//Toggles the display on an element
function toggleID(id) {
	toggleElements(id);
}
//Use toggleID instead (new name for consistency)
//but this is provided as legacy function
function toggleDisplayID(id) {
	toggleElements(id);
}

function domcheck(elem) {
	if ( typeof(elem) == 'object' ) {
		return elem;
	}
	return did(elem);
}

/**
 * showElements - Shows all of the elements passed in
 * 		Note: Takes any number of element objects or ids
 */
function showElements(){
	var args = slice(arguments);
	if (args.length == 0 && (this instanceof Array)) {
		args = args.concat(this);
	}
	args.flatten();
	args.forEach(function(el){
		el = (typeof el == 'object' && el.nodeType == 1) ? el : did(el);
		if (!el) { return; }
		el.style.display = '';
	});
}
/**
 * hideElements - Hides all of the elements passed in
 * 		Note: Takes any number of element objects or ids
 */
function hideElements() {
	var args = slice(arguments);
	if (args.length == 0 && (this instanceof Array)) {
		args = args.concat(this);
	}
	args.flatten();
	args.forEach(function(el){
		el = (typeof el == 'object' && el.nodeType == 1) ? el : did(el);
		if (!el) { return; }
		el.style.display = 'none';
	});
}
/**
 * toggleElements - Toggles the display of all elements passed in
 * 		Note: Takes any number of element objects or ids
 */
function toggleElements() {
	var args = slice(arguments);
	if (args.length == 0 && (this instanceof Array)) {
		args = this;
	}
	var toHide=[], toShow=[];
	args.flatten();
	args.forEach(function(el){
		el = (typeof el == 'object' && el.nodeType == 1) ? el : did(el);
		if (!el) { return; }
		if (el.style.display == 'none') {
			toShow.push(el);
		} else {
			toHide.push(el);
		}
	});
	hideElements(toHide);
	showElements(toShow);
	}

/**
 * getDocSize - Get the size of the document
 * @return	object		The width, height of the document in a keyed object ( obj.width obj.height )
 */
function getDocSize() {
  var w = 0, h = 0;
  if(typeof(window.innerWidth) == 'number'){
    //Non-IE
    w = window.innerWidth;
    h = window.innerHeight;
  }else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
    //IE 6+ in 'standards mode'
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
  }else if(document.body && (document.body.clientWidth || document.body.clientHeight)){
    //IE 4 compatible
    w = document.body.clientWidth;
    h = document.body.clientHeight;
}
  return {'width':w,'height':h};
}

/**
 * getScrollXY - Gets the distance the page has been scrolled vertically and horizontally
 * @return	object		The x,y distance in a keyed object ( obj.x obj.y )
 */
function getScrollXY() {
	var sX = 0, sY = 0;
	if(typeof(window.pageYOffset)=='number'){
		//Non-IE
		sY = window.pageYOffset;
		sX = window.pageXOffset;
	}else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)){
		//IE 6+ in 'standards mode'
		sY = document.documentElement.scrollTop;
		sX = document.documentElement.scrollLeft;
	}else if(document.body && (document.body.scrollLeft || document.body.scrollTop)){
		//IE 6 in 'strict mode' & some other browsers
		sY = document.body.scrollTop;
		sX = document.body.scrollLeft;
	}
	return {'x':sX,'y':sY};
}

/**
 * DOM Event Functions & Objects
 */

/* domLoader - detects when the DOM is ready in the browser (typically before onload would fire).
 * Also allows registration of functions to execute once ready.
 * 
 * Example using the optional object and args parameters:
 *		-keyword 'this' will be the person object
 * 		-arg1 and arg2 become 'name' and 'job'
 * 		-function will log:
 * 				name: bob job: plummer
 * 		
 * 		var person = {'name':'bob','job':'plummer'};
 * 		domLoader.register(function(arg1, arg2){
 * 			console.log(arg1+': '+this[arg1]+' arg2: '+this[arg2]);
 * 		}, person, ['name','job']); 
 */
var domLoader = {
	'isReady': false,
	'isBound': false,
	'queue': [],
	'binds': [],
	'args': [],
	/**
	 * register - Register a function to be executed when the dom is ready
	 * @param	fn		function	Function to execute
	 * @param	obj		object		optional;Object that will be the scope for fn(keyword 'this' inside function, default is window)
	 * @param	args	array		optional;Array of parameters to be passed to the function upon execution
	 */
	'register': function(fn, obj, args) {
		this.checkReady();
		this.queue = (this.queue instanceof Array) ? this.queue : [];
		if(!fn || typeof fn != 'function') {
			return;
		}
		
		var offset = this.queue.push(fn) - 1;
		
		obj = obj || null;
		this.binds = (this.binds instanceof Array) ? this.binds : [];
		this.binds[offset] = obj;
		
		args = args ? ((args instanceof Array) ? args :  slice(args)) : [];
		this.args = (this.args instanceof Array) ? this.args : [];
		this.args[offset] = args;
		return this;
	},
	/**
	 * checkReady - Starts checking the for the dom to be ready (internal use)
	 */
	'checkReady': function() {
		if(this.isBound) {
			return;
		}
		this.isBound = true;
		var self = this;
		var events = {'load': window};
		// Mozilla, Opera and Safari
		if(document.addEventListener) {
			events['DOMContentLoaded'] = document;
		// IE
		} else if(document.attachEvent) {
			events['onreadystatechange'] = document;
			// If IE and not an iframe -- continually check to see if the document is ready
			if(document.documentElement.doScroll && window == window.top) {
				(function(){
					if(self.isReady) {
						return;
					}
					try {
						// If IE is used, use the trick by Diego Perini -- http://javascript.nwbox.com/IEContentLoaded/
						document.documentElement.doScroll("left");
					} catch(error) {
						setTimeout(arguments.callee, 0);
						return;
					}
					// and execute any waiting functions
					self.isReady = true;
					self.ready();
				})();
			}
		}
		
		//Faster Safari detection
		if(typeof navigator.taintEnabled === 'undefined') {
			var timer = window.setInterval(function() {
				if(/loaded|complete/.test(document.readyState)){
					window.clearInterval(timer);
					if(self.isReady) {
						return;
					}
					self.isReady = true;
					self.ready();
				}
			}, 10);
		}
		
		for(var name in events) {
			(function(name, obj) {
				registerEvent(obj, name, function() {
					unregisterEvent(obj, name, arguments.callee);
					if(!self.isReady) {
						self.isReady = true;
						self.ready();
					}
				});
			})(name, events[name]);
		}
	},
	/**
	 * ready - Executes all registered functions with any bound scope & args (internal use)
	 */
	'ready': function(){
		if(!this.isReady || !(this.queue instanceof Array)) {
			return;
		}
		
		var fn, obj, args;
		while(fn = this.queue.shift()) {
			obj = this.binds.shift() || window;
			args = this.args.shift();
			fn.apply(obj, args);
		}
		
		this.queue = [];
		this.binds = [];
		this.args = [];
	}
};

/**
 * fixEvent - Returns an event object with common properties/methods normalized for easier cross browser usage.
 * @param e		object	optional;Event object to normalize
 * @return		object	Event object after normalization
 */
function fixEvent(e){
	var evnt = e || window.event;
	if (!evnt) { return null; }
	if(!evnt.target){ evnt.target = evnt.srcElement; }
	evnt.preventDefault = (evnt.preventDefault)? evnt.preventDefault : function(){ this.returnValue = false; };
	evnt.stopPropagation = (evnt.stopPropagation)? evnt.stopPropagation : function(){ this.cancelBubble = true; }
	return evnt;
}

/**
 * registerEvent - registers a function to execute when the specified event occurs
 */
function registerEvent(elem, type, callback, capture){
	if (type == 'allchange') {
		['change','click','keyup'].forEach(function(chg_type){
			registerEvent(elem, chg_type, callback, capture);
		});
		return;
	}
	
	elem = typeof elem == 'object' ? elem : did(elem);
	if (elem.addEventListener) {
		elem.addEventListener(type, callback, (capture || true));
	} else {
		elem.attachEvent('on'+type, callback);
	}
}
/**
 * unregisterEvent - unregisters a function for execution when the specified event occurs
 */
function unregisterEvent(elem, event, callback, capture) {
	if ( typeof(capture) != 'undefined' ) {
		capture = true;
	}
	if ( event == 'allchange' ) {
		['change','click','keyup'].forEach(function(chg_type){
			unregisterEvent(elem, chg_type, callback, capture);
		});
		return;
	}
	elem = domcheck(elem);

	if ( elem.removeEventListener ) {
		elem.removeEventListener(event, callback, capture);
	} else {
		elem.detachEvent('on'+event, callback); 
	}
}
    
/**
 * String Utility Functions
 */
    
function ltrim(string) {
	return string.replace(/^\s*/, '');
}

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

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

String.prototype.ltrim = function(){ return ltrim(this); }
String.prototype.rtrim = function(){ return rtrim(this); }
String.prototype.trim = function(){ return trim(this); }

/**
 * Array and object functions
 */

/**
 * Array methods indexOf, forEach, map, filter
 * 		Added for browsers without native support
 */
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj,start){
		var len = this.length;
		start = Number(start) || 0;
		start = (start < 0) ? Math.ceil(start) : Math.floor(start);
		if(start < 0){ start+= len; }
		for(;start < len;start++){
			if(start in this && this[start]===obj){ return start; }
		}
		return -1;
	}
}
if(!Array.forEach){
	Array.prototype.forEach = function(fn /*, bind*/){
		var len = this.length;
		if(typeof(fn) != 'function'){ throw new TypeError(); }
		var bind = arguments[1];
		for(var i=0;i < len;i++){
			if(i in this){ fn.call(bind, this[i], i, this); }
		}
	};
}
if(!Array.map){
	Array.prototype.map = function(fn /*, bind*/){
		var len = this.length;
		if(typeof(fn) != 'function'){ throw new TypeError(); }
		var ret = [], bind = arguments[1];
		for (var i=0;i < len;i++){
			if(i in this){ ret[i] = fn.call(bind, this[i], i, this); }
		}
		return ret;
	};
}
if(!Array.filter){
	Array.prototype.filter = function(fn /*, bind*/){
		var len = this.length;
		if(typeof(fn) != 'function'){ throw new TypeError(); }
		var ret = [], bind = arguments[1], val=null;
		for(var i=0;i < len;i++){
			if(i in this){
				val=this[i];
				if(fn.call(bind,val,i,this)){ ret.push(val); }
			}
		}
		return ret;
	};
}

/**
 * Array.flatten - Modifys the array instance such that any arrays(or array-like) items
 * within the array are replaced with all the items within that array item.
 * Example: [1,2,[3,4,[5,6,7]]] will become [1,2,3,4,5,6,7]
 */
Array.prototype.flatten = function(){
	var args = [];
	for(var i=0;i < this.length;i++){
		if (this[i] instanceof Array) {
			args = [i,1].concat(this[i]);
			this.splice.apply(this,args);
		} else if(typeof this[i] != 'string' && typeof this[i].length == 'number'){
			args = [i,1].concat(slice(this[i]));
			this.splice.apply(this,args)
		}
	}
}

/**
 * slice - Shortcut for Array.prototype.slice.call(obj, idx)
 * @param obj	mixed		Object to call array.slice on
 * @param idx	integer		Index at which to begin slicing
 * @return		array		New array containing values from the idx to the end of the obj
 *		Note: Useful for transforming arguments object and collections into regular arrays
 *		ex.	function(){ var args = slice(arguments); alert(args instanceof Array); }
 */
function slice(obj,idx){
	var ret = obj;
	if(/internet\sexplorer/i.test(navigator.appName)){
		if(typeof obj.length=='undefined'){ obj.length = getLength(obj); }
		ret = Array.prototype.map.call(obj,function(item){return item;});
	}
	return Array.prototype.slice.call(ret,idx || 0);
}

/**
 * getLength - Finds the total number of all non-function properties owned by the object (see hasOwnProperty)
 * @param obj    object    The object whose properties to count.
 * @return       int       The length of the object or 0 if obj was invalid
 */
function getLength(obj){
    if(!obj){ return 0; }
    var i=0;
    for(var key in obj){
        if(obj.hasOwnProperty(key) && typeof obj[key] !='function'){i++;}
    }
    return i;
}