/*
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();}



	///////////////////////////////////////
	// Product Listview Pop-up
	///////////////////////////////////////

var product_options_lookup = [];

function load_product_options(id, options, color_id, option_id){
	product_options_lookup = options;
	build_product_color_menu(did('swatches'), did('option_id'), did('product_image'));
	select_product_color(color_id, option_id, did('option_id'), did('product_image'));
}

function load_product_popup(event,id, cid, url, description, image_src, image_width, image_height, title, price, options){
	event = event || window.event;
	var target = event.target || event.srcElement;
	var pop = did('product_popup');
	var ppod = getParentPod(target);
	ppod.appendChild(pop);
	
	did('product_id').value=id;
	did('popup_title').innerHTML=title;
	did('popup_title').href=url;
	did('popup_image_link').href=url;
	did('popup_description').innerHTML=description;
	did('popup_price').innerHTML=price;
	
	did('popup_fav_link').href="cart_action.php?action=save&product_id="+id;
	did('popup_cart_link').href="cart_action.php?action=add&product_id="+id;
	
	did('popup_image').width=image_width;
	did('popup_image').height=image_height;
	did('popup_image').src=image_src;
	
	product_options_lookup = options;
	build_product_color_menu(did('popup_colors'), did('popup_options'), did('popup_image'));
	
	var color = /.*colors\/(\d+)\/.*/i;
	if(image_src.indexOf("defaults")==-1) {
		var color_id = color.exec(image_src)[1];
	} else {
		var color_id = 0;
	}
	
	did('popup_image_link').href+='?color='+color_id;
	
	select_product_color(color_id, 0, did('popup_options'), did('popup_image'));
	
	showID('product_popup');
}

function build_product_color_menu(color_menu, option_menu, preview_image){
	// This method requires that the product_options_lookup array is populated with the currently viewed product's color and option information
	// Populate the unique colors array (all colors, not just those for a particular option)
	js_colors = [];
	color_menu.innerHTML="";
	html = '';
	for(i=0;product_options_lookup.length>i;i++) {
		if(!js_colors.in_array(product_options_lookup[i][0])) {
			html += '<a id="select_product_color_'+product_options_lookup[i][0]+'" onclick="select_product_color('+product_options_lookup[i][0]+',0,did(\''+option_menu.id+'\'),did(\''+preview_image.id+'\')); return false;" title="'+product_options_lookup[i][2]+'"><img src="'+product_options_lookup[i][3]+'" height="30" alt="'+product_options_lookup[i][2]+'" /></a>';
			js_colors[js_colors.length] = product_options_lookup[i][0];
		}
	}
	if ( js_colors.length > 1 ) {
		color_menu.innerHTML = html;
	}
}

function select_product_color(color_id, option_id, option_menu, preview_image){
	// This method requires that the product_options_lookup array is populated with the currently viewed product's color and option information
	// Populate the unique options array (for the currently selected color)
	//	- product_options_lookup[colors][0=color_id, 1=option_array](...[options][0=label, 1=option_id, 2=color_id, 3=preview_image, 4=zoom_image]... option_array)
	if(option_menu.options){ option_menu.options.length=0; }
	var color_index=null;
	for(var x=0;x < product_options_lookup.length;x++){
		if(!color_id || product_options_lookup[x][0]==color_id){
			for(var i=0;i < product_options_lookup[x][1].length;i++){
				if(option_menu.options){
					option_menu.options[i] = new Option(product_options_lookup[x][1][i][0],product_options_lookup[x][1][i][1]);
					if(product_options_lookup[x][1][i][1]==option_id){
						option_menu.options[i].selected = true;
					}
				}else{
					option_menu.value=product_options_lookup[x][1][i][1];
				}
			}
			color_index=x;
			break;
		}
	}
	if(option_menu.options){
		var pop_price = did('popup_price');
		var option_viz = (option_menu.length > 1) ? true : false;
		option_menu.style.display = option_viz ? 'block' : 'none';
		if(pop_price){	pop_price.style.display = option_viz ? 'none' : 'block'; }
		
		if (option_viz) {	
			did('option_id').value = option_menu.value;
			showID('option_id_label'); 
		} else { 
			pop_price.innerHTML = option_menu.options[0].innerHTML.replace(/[\(\)]/g,'');
			hideID('option_id_label');
			did('option_id').value = option_menu.options[0].value; 
		}
	}
	
	// Change the product preview image as nescessary
	preview_image.src = product_options_lookup[color_index][1][0][3];
	
	// And any enlarge links if found
	if(did('product_image_link')) {
		url="pop_zoom.php?img="+product_options_lookup[color_index][1][0][4]+"&dir=colors&id="+product_options_lookup[color_index][1][0][2];
		did('product_image_link').href=url;
		did('product_image_enlarge_link').href=url;
	}
	//Fix the pop-in image link to direct to the correct color version of details page
	var pop_image_link = did('popup_image_link');
	if(pop_image_link){
		var linkhref=pop_image_link.href.toString(); 
		pop_image_link.href = linkhref.replace(/(color=)(\d+)/i,'$1'+color_id);
	}
	
	for(var i=0;i<js_colors.length;i++) {
		if(did('select_product_color_'+js_colors[i])) {
			did('select_product_color_'+js_colors[i]).className = '';
		}
	}
	if(did('select_product_color_'+color_id)) {
		did('select_product_color_'+color_id).className = 'selected_color';
	}
	
	if(did('option_id')) {
		changeProductOption(did('option_id').value);
	}
}

function close_product_popup(){
	hideID('product_popup');
}

function getParentPod(el){
	return (/^product_pod[^_]*$/.test(el.className) ? el : getParentPod(el.parentNode));
}

function podover(event){
	event = event || window.event;
	target = event.target || event.srcElement;
	var pod = getParentPod(target);
	if(/\s*hover\s*/.test(pod.className)){ return; }
	pod.className+=' hover';
}
function podout(event){
	event = event || window.event;
	target = event.target || event.srcElement;
	var pod = getParentPod(target);
	pod.className=pod.className.replace(/\s?hover\s?/,'');
}

	///////////////////////////////////////
	// 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 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 validateCatalogRequest(form){
	var stateField = "state";
	if ( form.elements["country"].value == 38 || form.elements["country"].value == 'CA' ) {
		stateField = "province";
	} else if ( form.elements["country"].value != 213 && form.elements["country"].value != 'US' ) {
		stateField = "other";
	}
	
	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["country"],"V","","Please enter the shipping country.",false) &&
		checkSelect(form.elements["address"],"V","","Please enter the shipping Address.",false) &&
		checkSelect(form.elements["city"],"V","","Please enter the shipping City.",false) &&
		checkSelect(form.elements[stateField],"V","","Please enter the shipping State/Prov.",false) &&
		checkSelect(form.elements["zip"],"V","","Please enter the shipping ZIP.",false) &&
		checkSelect(form.elements["howfound"],"V","","Please indicate how you heard about us.",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 checkEmails(elms,emptyOK){
	var retval = true;
	for(var i=0,z=elms.length; i < z; i++){
		if(elms[i].disabled){ continue; }
		retval=checkEmail(elms[i],emptyOK);
	}
	return retval;
}

function validateTellAFriend(form){
	var result = (
		checkSelect(form.elements["from_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));
				 
	for(var i=0; i<=friends; i++) {
		if(!result) {
			return false;
		}
		//alert("checking friend #"+i);
		// if they entered either a name or email address, then check the info, otherwise allow them to continue
		if(i==0 || form.elements["to_email["+i+"]"].value || form.elements["to_name["+i+"]"].value) {
			result = (
				 result &&
				 checkSelect(form.elements["to_name["+i+"]"],"V","","Please enter your Friend's Name.",false) &&
				 checkSelect(form.elements["to_email["+i+"]"],"V","","Please enter your Friend's E-mail.",false) &&
				 checkEmail(form.elements["to_email["+i+"]"],false) &&
				 checkSelect(form.elements["to_email["+i+"]"],"V","joe@example.com","Please supply a valid E-mail Address.",false));
		}
	}
				 
	return result;
}

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 validateEmailSignupExtended(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["age"],"V","","Please select Your Age.",false) &&
		checkSelect(form.elements["howfound"],"V","","Please select How You Heard About Us.",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){
	cc_type_full = '';
	switch(form.elements['billing[cc_type]'].value) {
		case 'v': cc_type_full = 'VISA'; break;
		case 'd': cc_type_full = 'DISCOVER'; break;
		case 'm': cc_type_full = 'MASTERCARD'; break;
		case 'a': cc_type_full = 'AMEX'; break;
	}
	out = (
		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) 
	);
	
	if (!out) {
		return false;
	}
	
	if (!isCardMatch(cc_type_full,form.elements["billing[cc_num]"].value.replace(/[- ]/g,''))) {
		warnInvalid(form.elements["billing[cc_num]"], 'Your credit card number does not match your credit card type. Please double check your credit card number and type before resubmitting.');
		return false;
	} 
	
	return true;
}

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

}//end validatePO

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["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)
	) {
		return validateShipping(form);
	}

	return false;
}

function validateShipping(form){
	var stateField = "shipping[state]";
	if ( form.elements["shipping[country]"].value == 38 || form.elements["shipping[country]"].value == 'CA' ) {
		stateField = "shipping[province]";
	} else if ( form.elements["shipping[country]"].value != 213 && form.elements["shipping[country]"].value != 'US' ) {
		stateField = "shipping[other]";
	}
	
	return (
		checkSelect(form.elements["shipping[country]"],"V","","Please enter the shipping country.",false) &&
		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[stateField],"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) &&
		checkSelect(form.elements["hear_about_us"],"V","","Please indicate how you heard about us.",false)
	);
}

function validateBillingAddress(form){
	var stateField = "billing[state]";
	if ( form.elements["billing[country]"].value == 38 || form.elements["billing[country]"].value == 'CA' ) {
		stateField = "billing[province]";
	} else if ( form.elements["billing[country]"].value != 213 && form.elements["billing[country]"].value != 'US' ) {
		stateField = "billing[other]";
	}
	
	return (
		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.",false) &&
		checkSelect(form.elements["billing[phone]"],"V","","Please enter the billing Phone.",false) &&
		checkSelect(form.elements["billing[fullname]"],"V","","Please enter the billing full name.",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 = 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 = "";
	} 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['loginemail'].focus();
}

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

function loadPreview(){

	try {
		var body_obj = opener.document.getElementById("wysiPlainTextarea1");
		var headline_obj = opener.document.getElementById("headline");
		var child_head = document.getElementById("headline");
		var child_body = document.getElementById("body");

		var caption_value = window.opener.document.getElementById("caption").value;
		var child_caption = document.getElementById("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 ){

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

//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 ( did('popup_options') && frm.elements['option_id'] ) {
		frm.elements['option_id'].value = did('popup_options').value;
	}

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

	if ( multi_quantity_check(frm, false) ) {
		frm.submit();
	}
	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( file ){
	if ( file == null ) {
		file = 'listview/products.xsl';
	}

	if ( document.implementation.createDocument ) {
		xslDoc = document.implementation.createDocument("", "", null);
		xslDoc.addEventListener("load", onXSLLoad, false);
		xslDoc.load(file);
	} else if ( window.ActiveXObject ) {
		xslDoc = new ActiveXObject("Microsoft.XMLDOM");
		xslDoc.async = false;
		xslDoc.validateOnParse = false;
		xslDoc.load(file);
		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') ) {
			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){
	/*var waiting = document.createElement("div");
	waiting.id = 'list';
	waiting.innerHTML = "Loading...";
	document.getElementById('list').parentNode.replaceChild(waiting, document.getElementById('list'));*/

	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) {
				if (x == 'in_array') continue;
				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);
			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 refreshView2(xslfile, page, sort, dir, perpage){
	/*var waiting = document.createElement("div");
	waiting.id = 'list';
	waiting.innerHTML = "Loading...";
	document.getElementById('list').parentNode.replaceChild(waiting, document.getElementById('list'));*/

	try {
		if ( !xslLoaded ) {
			loadXSL(xslfile);
		}
		if ( sort != undefined ) {
			var url = 'listview.php?ret&pg='+page+'&srt='+sort+'&dir='+dir+'&perpage='+perpage+'&viewtype='+ListviewType;
			for( x in lv_tracking) {
				if (x == 'in_array') continue;
				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);
			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 += '.';
	}
	curr = (curr == 3) ? 1 : curr+1; 
	
	var str = 'Loading'+dots;
	$('now_loading').innerHTML = str;
	timer = setTimeout("dotDot("+timer+")", 300);
}

function lv_hist_change( xslfile ){
	if ( lvhistinitted ) {
		lvhistinitted = false;
		return;
	}
	
	if ( xslfile == null ) {
		xslfile = 'listview/products.xsl';
	}
	
	var params = unFocus.History.getCurrent();
	if ( params == '' ) {
		params = 'viewtype='+ListviewType;
		for( x in lv_tracking) {
			if ( x == 'in_array') continue;
			params += "&tracking["+x+"]="+lv_tracking[x];
		}
		if(sort_value) {
			params += "&srt="+sort_value;
		}
	}
	
	refreshView2(xslfile, 'listview.php?'+params);
}

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';
					showID('add_addr_profile');
					$('shipping_action').value = 'true';
					$('address_name').value = '';
				} else if ( id == 'new' ) {
					showID('add_addr_profile');
					$('shipping_action').value = 'true';
				} else {
					showID('update_addr_profile');
					$('shipping_action').value = 'true';
				}
			}
		} else if ( (type == 'billing' && storeCC) || type != 'billing' ) {
			showID('update_profile');
		}
		$(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){
	hideID('update_profile');
	hideID('name_profile');
	
	if ( id == '' ) {
		showID('add_profile');
		$('billing_action').value = 'true';
	} else {
		hideID('add_profile');
		$('billing_action').value = 'false';
	}
	
	$('add_billing_profile').checked = false;
	$('update_billing_profile').checked = false;

	var data = "";
	data += nh.compressData("action", "changeBilling");
	data += nh.compressData("id", id);
	ActivaUpdater('ActivaUpdater.php', data);
}

function changeBillingAddr(id){
	hideID('update_addr_profile');
	hideID('name_billing_addr');
	
	if ( id == 'new' && !express ) {
		showID('add_addr_profile');
		$('shipping_action').value = 'true';
	} else {
		hideID('add_addr_profile');
		$('shipping_action').value = 'false';
	}
	
	$('add_shipping_profile').checked = false;
	$('update_shipping_profile').checked = false;

	var data = "";
	data += nh.compressData("action", "changeBillingAddr");
	data += nh.compressData("id", id);
	ActivaUpdater('ActivaUpdater.php', data);
}

function changeShipping(id){
	hideID('update_profile')
	hideID('name_profile');
	
	if ( id == '' ){
		showID('add_profile');
		$('shipping_action').value = 'true';
	} else {
		hideID('add_profile');
		$('shipping_action').value = 'false';
	}
	$('add_shipping_profile').checked = false;
	$('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':
			$('name_profile_label').innerHTML = 'Name this '+label;
			break;
		case 'update':
			$('name_profile_label').innerHTML = 'Name of '+label;
			break;
	}
	
	$('name_profile').style.display = (checked ? '' : 'none');
}

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

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){
	for ( var x=0; x<paymentTypes.length; x++ ) {
		if ( type == paymentTypes[x] ) {
			if ( $(paymentTypes[x]+'_form') ) {
				showID(paymentTypes[x]+'_form');
			}
		} else {
			if ( $((paymentTypes[x]+'_form')) ) {
				hideID(paymentTypes[x]+'_form');
			}
		}
	}
}

function multi_quantity_check(frm, popup){
	var action = $('action');
	if ( action ) {
		if ( 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 getZoneServices(state){
	var data ='';
	data += nh.compressData('action', 'getZoneServices');
	data += nh.compressData('state', state);
	ActivaUpdater('ActivaUpdater.php',data); 
}

function calcShipping(silent){
	var values = {'shiptype':'','shipcarrier':'','zipcode':'','country':'','state':'','province':''}, elm=null, empty=/^\s*$/i;
	silent = silent || false;
	for(var key in values){
		elm = $(key);
		if(elm){
			if(key=='shiptype' || key=='shipcarrier'){ values[key]=elm.value; continue; }
			if(key=='state' && values['country'] != 'US'){ continue; }
			if(key=='province' && values['country'] != 'CA'){ continue; }
			if(empty.test(elm.value)){
				var iszip = (key=='zipcode' ? true : false);
				elm.focus();
				if(!silent){
					alert('Please '+(iszip ?'enter':'select')+' your '+(iszip ? 'zip code': key)+' to estimate the shipping costs');
				}
				return;
			}
			values[key]=elm.value;
		}else{ values[key]=''; }
	}
	getShipPrice(values['shiptype'], values['shipcarrier'], values['zipcode'], values['country'], (values['country']=='US' ? values['state']: values['province']));
}

function getShipPrice(service, carrier, zipcode, country, state){
	var elms = ['shipping','shiptotalvalue','gnd_total','grp_total','pmo_total','gft_total'], elm=null;
	for(var i=0;i < elms.length;i++){
		elm = $(elms[i]);
		if(elm){ elm.innerHTML = 'loading'; } 
	}

	var data='';
	data = nh.compressData("action", "getShipPrice");
	data += nh.compressData("service", service);
	data += nh.compressData("carrier", carrier);
	data += nh.compressData("zip", zipcode);
	data += nh.compressData("country", country);
	data += nh.compressData("state", state);
	
	ActivaUpdater('ActivaUpdater.php', data);
}

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 updateGoogle(comments){
    var uri="ActivaUpdater.php";
    var data="";
    data += nh.compressData("action", "update_google");
    data += nh.compressData("comments", comments);
    ActivaUpdater(uri, data);
}

Array.prototype.in_array = function(datum, strict){
	strict = strict || false;
	for(var i in this){
		if( (strict ? this[i]===datum : this[i]==datum) ){
			return true;
		}
	}
	return false;
}

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

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


function hideID(id){
	var elm = $(id);
	if(elm){ elm.style.display = 'none'; }
}

function showID(id){
	var elm = $(id);
	if(elm){ elm.style.display = ''; }
}

function toggleDisplayID(id){
	var elm = $(id);
	if(elm){ elm.style.display = (elm.style.display=='none' ? '' : 'none'); }
}

function setSelect(select, value){
	var sel = (typeof select == 'object') ? select : $(select);
	if(!sel){ return false; }
	if(!value){ sel.options[0].selected = true; sel.selectedIndex=0; }
	var opts = sel.options, optVal='', optText='';
	value = trim(value.toString().toLowerCase());
	for(var i=0;i < opts.length;i++){
		optVal = opts[i].value.toString().toLowerCase();
		optText = opts[i].text.toString().toLowerCase();
		if((optVal == value) || (optText == value)){
			opts[i].selected = true;
			sel.selectedIndex = i;
			return true;
		}
	}
	return false;
}

function setValues(obj){
	var elm = null, name='';
	for(var key in obj){
		elm = $(key);
		if(elm && elm.nodeName){
			name = elm.nodeName.toLowerCase();
			switch(name){
				case 'input':
					elm.value = (obj[key]) ? obj[key]:''; break;
				case 'select':
					setSelect(elm, obj[key]); break;
				default:
					elm.innerHTML = (obj[key]) ? obj[key]:''; break;
			}
		}
	}
}

function updateCountry(){
	var country=$('country'), areas=['state','province','other'], elm=null;
	var oldvalues = [];
	if ( country.value == '' ) { return; }
	for(var i=0;i < areas.length;i++){
		elm = $(areas[i]);
		if(elm && areas[i]!='other'){
			oldvalues[i] = elm.value;
			elm.selectedIndex = 0;
		}else if(elm){
			oldvalues[i] = elm.value;
			elm.value='';
		}
		hideID(areas[i]);
	}
	if ( country.value == 'US' || country.value == '213' ) {
		showID('state'); setSelect('state',oldvalues[0]);
	} else if ( country.value == 'CA' || country.value == '38' ) {
		showID('province'); setSelect('province',oldvalues[1]);
	} else {
		showID('other');
		$('other').value = oldvalues[2];
	}
}

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

function toggleStockRows(show){
	show = (show!=null ? show: true);
	quick = (quick != null ? quick: true);
	var fn = show ? showID: hideID;
	var sfn = !show ? showID: hideID;
	var rows = ['qty','add'];
	for(var i=0;i < rows.length;i++){
		fn(rows[i]+'_row');
	}
	sfn('stock_row');
}

function shopping_drop(show){
	$('shopping_dropdown').style.display = (show ? '' : 'none');
}

function registerEvent(elem, event, callback){
	if ( event == 'allchange' ) {
		registerEvent(elem, 'change', callback);
		registerEvent(elem, 'click', callback);
		registerEvent(elem, 'keyup', callback);
		return;
	}
	elem = domcheck(elem);
	
	if ( elem.addEventListener ) {
		elem.addEventListener(event, callback, true);
	} else {
		elem.attachEvent('on'+event, callback, true); 
	}
}
function domcheck(elem){
	return (typeof(elem)=='object') ? elem : $(elem);
}

/**
 * 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){
	evnt = e || window.event;
	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;
}