var grayboxint = 0;
var grayboxint2 = 0;
var cctimeout = 0;
var globalm = '';
var iferror = 0;
var KeyDelay = Class.create({
	interval: 300,
	initialize: function () {},
	execute: function (target_function) {
		this.timeout = setTimeout(target_function, this.interval);
	},
	clear: function () {
		clearTimeout(this.timeout);
	}
});
var	key_delay = new KeyDelay;
	
var pulse_cart;
var CustomTemplate = Class.create( {
	initialize: function () {},
	_loadTemplate: function (target, template_name, template_parameters) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Updater(target,'/home/fetchTemplate', {
			asynchronous: false, 
			method: 'post',  
			parameters: {'template': template_name, 'template_parameters': Object.toJSON(template_parameters)},
			onComplete: result.bind(this)
		});
	},
	_getTemplate: function (template_name, template_parameters) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/home/fetchTemplate', {
			asynchronous: false, 
			method: 'post',  
			parameters: {'template': template_name, 'template_parameters': Object.toJSON(template_parameters)},
			onComplete: result.bind(this)
		});
	}
});
	
var Cart = Class.create( {
	initialize: function() {
		this.addToCartURL = "/cart/addToCart/";
		this.removeFromCartURL = "/cart/removeFromCart/";
		this.updateCartURL = "/cart/updateCart/";
		this.updateCartURL2 = "/cart/updateCart/";
		this.target = "";
		this.responseText = "";
	},
	processResponse: function(transport) {
		this.responseText = transport.responseText;
	},
	_AddToCart: function (item_id, price, quantity) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request(this.addToCartURL + item_id + "/" + price + "/" + quantity, {
			asynchronous: false, 
			method: 'post',  
			onComplete: result.bind(this)
		});
	},
	_RemoveFromCart: function (item_id) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Updater(this.target, this.removeFromCartURL + item_id + "/" + this.target, {
			asynchronous: false, 
			method: 'post',  
			evalScripts:true,
			onComplete: result.bind(this)
		});
	},
	_UpdateCart: function (item_id,quantity) {
		result = function(transport) {
			this._responseText = transport.responseText;
			updateCartTotals();
		}
		request = new Ajax.Updater(this.target, this.updateCartURL + item_id + "/" + quantity + "/" + this.target, {
			asynchronous: false, 
			method: 'post', 
			evalScripts:true,
			onComplete: result.bind(this)
		});
	},
	_UpdateCart2: function (item_id,quantity) {
		result = function(transport) {
			this._responseText = transport.responseText;
			var row_val = this._responseText.evalJSON();
			var pre_element = "row-total-" + item_id + "-pre";
			var super_element = "row-total-" + item_id + "-super";
			$(pre_element).innerHTML = "$" + row_val.row_total0 + ".";
			$(super_element).innerHTML =  row_val.row_total1;

			var qty_element = "quantity_" + item_id;
			$(qty_element).value = quantity;


			//updateCartTotals();
		}
		request = new Ajax.Updater(this.target, this.updateCartURL2 + item_id + "/" + quantity + "/" + this.target, {
			asynchronous: false, 
			method: 'post', 
			evalScripts:true,
			onComplete: result.bind(this)
		});
	},
	_GetCartInfo: function(target) {
		result = function(transport) {
			price_format = new CustomTemplate;
			price_format._loadTemplate($(target), 'cart/cart_price_format', {price: transport.responseText});
		}
		request = new Ajax.Request("/cart/getCartInfo", {
			asynchronous:	false,
			method: 		'post',
			evalScripts:true,
			parameters: 	{'target':target},
			onComplete:		result.bind(this)
		});
	},
	_GetCartInfo2: function() {
		result = function(transport) {
			cart_totals = transport.responseText.evalJSON();
		}
		request = new Ajax.Request("/cart/getCartInfo2", {
			asynchronous:	false,
			evalScripts:true,
			method: 		'post',
			onComplete:		result.bind(this)
		});
	},
	_SaveCart: function(parameters) {
		result = function(transport) {
			//alert(transport.responseText);
			//$('dev').innerHTML = transport.responseText;
		}
		request = new Ajax.Request("/cart/saveForLater", {
			asynchronous:	false,
			method: 		'post',
			parameters: 	parameters,
			onComplete:		result.bind(this)
		});
	},
	_GetPromoInfo: function(parameters) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Updater(this.target, "/cart/updatePromotion/" + this.target, {
			asynchronous:	false,
			method: 		'post',
			parameters: 	parameters, //promo_code
			onComplete:		result.bind(this)
		});
	},
	_SetPromoCode: function(parameters) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request("/cart/updatePromotion", {
			asynchronous:	false,
			method: 		'post',
			parameters: 	parameters,
			onComplete:		result.bind(this)
		});
	},
	_UnsetPromoCode: function() {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request("/cart/unsetPromotion", {
			asynchronous:	false,
			method: 		'post',
			onComplete:		result.bind(this)
		});
	},
	
	_UpdateView: function(parameters) {
		result = function(transport) {
			//this._responseText = transport.responseText;
		}
		request = new Ajax.Updater(this.target, "/cart/viewCart/" + this.target, {
			asynchronous:	false,
			method: 		'post',
			evalScripts:true,
			parameters: 	parameters, //promo_code
			onComplete:		result.bind(this)
		});
	},
	_GetCartNumItems: function() {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request("/cart/getCartNumItems", {
			asynchronous:	false,
			method: 		'post',
			onComplete:		result.bind(this)
		});
	}
	
});

var Shipping = new Class.create( {
	initialize: function() {
	},
	_GetShippingOptions: function(zip_code, prod_weight, prod_price) {
		result = function(transport) {
			if(zip_code == 'new'){
				prod_price_object = new Object();
				prod_price_object.total_price = prod_price;
				xChangedShippingOption(Object.toJSON(prod_price_object));	
			}else{
				this._UpdateShipTo(zip_code);
				var details =  this._responseText.evalJSON();
				if (details.city == undefined) {
					$("product-details-ship-to-destination").innerHTML = "Zip code not recognized";
					$("product-details-change").innerHTML = "(Try again)";
				} else {
					$("product-details-ship-to-destination").innerHTML = details.city + ", " + details.state + " " + details.zip_code;
				}
				xChangedShippingOption($F('ship_method'));
			}
		}
		request = new Ajax.Updater("shipping-options","/shipping/getShippingDropDown/" + zip_code + "/" + prod_weight + "/" + prod_price, {
				asynchronous: false, 
				method: 'post',
				onComplete: result.bind(this)
			});
	},
	_ChangeShippingOption: function() {
	},
	_GetShippingBubble: function(zip_code) {
		result = function(transport) {
			this._UpdateShipTo(zip_code);
			var details =  this._responseText.evalJSON();
			if (details.city == undefined) {
				$("shipping-bubble-ship-to-destination").innerHTML = "Zip code not recognized";
			} else {
				$("shipping-bubble-ship-to-destination").innerHTML = details.city + ", " + details.state + " " + details.zip_code;			
			}
			xChangedShippingOption($F('shipMethod'));
			this._responseText = transport.responseText;
		}
		request = new Ajax.Updater("shipping-bubble","/shipping/getShippingBubble/" + zip_code, {
			asynchronous: false, 
			method: 'post',
			onComplete: result.bind(this)
		});
	},
	_UpdateShipTo: function(zip_code) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request("/shipping/getCityAndState/" + zip_code, {
			asynchronous: false, 
			method: 'post',
			onComplete: result.bind(this)
		});
	}
});


var Session = Class.create( {
	initialize:  function () {
		this._responseText = "ERROR";
	},
	_GetSessionData: function(target) {
		result = function(transport) {			
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/getSessionData', {
			asynchronous: false,
			method: 'post',
			parameters: {'key':target},
			onComplete: result.bind(this)
		});
	},
	_GetCookieData: function(target) {
		result = function(transport) {			
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/getCookieData', {
			asynchronous: false,
			method: 'post',
			parameters: {'key':target},
			onComplete: result.bind(this)
		});
	},
	_SetSessionData: function(id, value) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/updateSession', {
			asynchronous: false, 
			method: 'post', 
			parameters: {id: id, value: value}, 
			onComplete: result.bind(this)
		});
	},
	_SetCookieData: function(id, value) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/updateCookie', {
			asynchronous: false, 
			method: 'post', 
			parameters: {id: id, value: value}, 
			onComplete: result.bind(this)
		});
	},
	_ShowSessionData: function() {
		var url = "/cart/showSession/";
		var target = "dev-session";
		request = new Ajax.Updater(target,url, {asynchronous: false, method: 'get'});
		
	},
	_UnsetSessionData: function() {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/unsetSessionData', {
			asynchronous: false, 
			method: 'post', 
			parameters: {}, 
			onComplete: result.bind(this)
		});
	},
	_UnsetSessionVar: function(sess_var) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/unsetSessionVar/' + sess_var, {
			asynchronous: false,
			method: 'post',
			parameters: {sess_var: sess_var},
			onComplete: result.bind(this)
		});
	},
	_copyVar: function(from,to) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/copySessionVar/', {
			asynchronous: false,
			method: 'post',
			parameters: {from: from, to: to},
			onComplete: result.bind(this)
		});
	}
});

var CustomForm = new Class.create ({
	initialize: function () {},
	_GetFormData: function(form_object) {
		session = new Session;
		session._GetSessionData(form_object.id);
		this.form_data = session._responseText;
		this.data_object = (!session._responseText.blank())?session._responseText.evalJSON():[];
		
	},

	_SaveFormData: function (form_object) {
		collector_array = new Array();
		form_object.getElements().each(function (form_element) {
			var element_info_array = new Object();
			element_info_array['id'] = form_element.id;		
			if (form_element.type == 'checkbox' || form_element.type == 'radio') {
				element_info_array['value'] = form_element.checked;
			} else {
				element_info_array['value'] = form_element.value;
			}
			collector_array[collector_array.length] = element_info_array;
		});
		
		session = new Session;
		if (collector_array.length > 0) {
		
			session._SetSessionData(form_object.id, collector_array.toJSON());
		}
	},
	_ValidateEmailDomain: function(email){
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/cart/validateEmailDomain', {
			asynchronous: false, 
			method: 'post', 
			parameters: {email: email}, 
			onComplete: result.bind(this)
		});		
	},
	verifyCustomerEmailExists: function(email) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/account/getCustomerExists', {
			asynchronous: false, 
			method: 'post', 
			parameters: {email: email}, 
			onComplete: result.bind(this)
		});	
	},
	validateCustomerEmail: function(email) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/account/validateCustomerEmail', {
			asynchronous: false, 
			method: 'post', 
			parameters: {email: email}, 
			onComplete: result.bind(this)
		});	
	},
	validateFormElement: function(element) {
		passed_validation =  true;
		if (element.up().className == "required" && !element.value ) {

			//element.style.background = '#faa';
			passed_validation = false;
		} else {
			if (element.id.match(/email/)){
				if(element.value.match(/^[\d\w.-]+?[@]{1}?([\d\w-]+?[.]{1}[\w\d]+?)+?$/)){
					passed_validation = true;
				}else{
					passed_validation = false;
				}
			} else if (element.id.match(/phone/)){
			 	if(!element.value.match(/^[(][0-9]{3}[)][0-9]{3}[-][0-9]{4}/)){
		 			//element.style.background = '#faa';
		 			passed_validation = false;
				}else{
					element.style.background = '#fff';
				}
			 } else if (element.id.match(/card_cvv/)) {
			 	passed_validation = checkCreditCardFormat("card_cvv");
			 } else if (element.id.match(/card_number/)) {
			 	passed_validation = checkCreditCardFormat("card_number");
			 } else if (element.id.match(/card_type/)) {
			 	passed_validation = checkCreditCardFormat("card_type");
			 } else if (element.id.match(/card_exp_mo/)) {
			 	passed_validation = checkCreditCardFormat("card_exp_mo");
			 }  else if (element.id.match(/card_exp_yr/)) {
			 	passed_validation = checkCreditCardFormat("card_exp_yr");
			 } else {
				element.style.background = '#fff';
			 }
		}
		
		return passed_validation;
	},
	updateFormValidation: function(input_element, validated) {
		session = new Session;
		session._GetSessionData("_validation");
		validation_hash = session._responseText.evalJSON();
		new_hash = new Hash; 
		for (var key in validation_hash) {
			form_element_hash = new Hash();
			for (var subkey in validation_hash[key]) {
				if (input_element.id == subkey)
					form_element_hash.set(subkey,validated)
				else
					form_element_hash.set(subkey,validation_hash[key][subkey]);
			}
			new_hash.set(key, form_element_hash);
		}
		
		if (!new_hash.empty) {
			session._SetSessionData("_validation",new_hash.toJSON());
		}
	},
	validateForm: function() {
		var validated = true;
		session = new Session;
		session._GetSessionData("_validation");
		validation_hash = new Hash;
		validation_json = session._responseText;
		validation_hash = validation_json.evalJSON();
		for (var key in validation_hash) {
			for (var subkey in validation_hash[key]) {
				if(validation_hash[key][subkey] == false) {
					validated = false;
				}
			}
		}
		return validated;
		
	},
	_PopulateFormData: function (form_object, data_object) {
		form_object.getElements().each(function (element) {
			data_object.each(function(element_data) {
				if (element.id == element_data.id) {
					if (element.type == 'checkbox' || element.type == 'radio') {
						if (element_data.value == true) {
							form_object[element.id].checked = element_data.value; 
							if (form_object[element.id].onclick) { form_object[element.id].onclick();}
						} else {
							form_object[element.id].checked = null;
						}							
					} else {
						if (form_object[element.name].value != element_data.value) {
							form_object[element.name].value = element_data.value;
						}
					}
				}
			});
		});
		
		this._PopulateCityState(form_object);
	},
	_PopulateCityState: function(form_object) {
		if (form_object.id == "billing_info") { 
			this._GetCityState('billing_zip', 'billing_city', 'billing_state','billing_country');
			
		} else if (form_object.id == "shipping_info") {
			this._GetCityState('shipping_zip', 'shipping_city', 'shipping_state', 'shipping_country');
		}
		
	},
	_GetCityState: function(zip_element, city_element, state_element, country_element) {		
		zip_code = "";
		session = new Session;
		if (!$F(zip_element).blank()) {				
			if (validateZipCode($F(zip_element))) {
				zip_code = $F(zip_element)
			}
		}
		
		if (!zip_code.blank()) {
			var shipping = new Shipping;
			shipping._UpdateShipTo(zip_code);
			details =  shipping._responseText.evalJSON();
			
			if (!details.error_code) {
				$(state_element).value = details.state;					
				if ($F(city_element).blank() || $F(city_element) == 'undefined') {
					$(city_element).value = details.city;
				}
				if ($F(zip_element).blank() || $F(zip_element) == 'undefined') {
					$(zip_element).value = zip_code;
				}
				$(country_element).value = this.GetCountryFromZip(zip_code);
				if ($("zipcode-error").style.display != "none") {
					$("zipcode-error").hide();
				}
			} else {
				$("zipcode-error").innerHTML = details.error_text;
				$("zipcode-error").show();
			}
			//var CityStateForm = new CustomForm;
			/*
			 * Determine Form 
			 */
			this.updateFormValidation($(city_element), this.validateFormElement($(city_element)));
			this.updateFormValidation($(state_element), this.validateFormElement($(state_element)));
			this.updateFormValidation($(country_element), this.validateFormElement($(country_element)));
		}
	},
	GetCountryFromZip: function(zip_code) {
		if(zip_code.match(/^[a-z][0-9][a-z][\-]?[0-9][a-z][0-9]$/i)){
			return 'CA';
		}else if(zip_code.match(/^[0-9]{5}$|^[0-9]{9}$/)){
			return 'US';
		}else{
			return 'US';
		}
	},
	ShowWorkingMessage: function(after) {
		showGraybox('working_message', {message_title: 'Working...', message: "Please wait while we check validate your information."}, after);
	},
	HideWorkingMessage: function() {
		closeGraybox();
	}
});
	
var CustomerInformation = new Class.create ( {
	initialize: function() {},
	_validatePassword: function(action, email, password, signinfrom) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request(action, {
			asynchronous: false, 
			method: 'post', 
			parameters: {email: email, password: password, signinfrom : signinfrom}, 
			onComplete: result.bind(this)
		});
	},
	_updateAccountPassword: function(account_data) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/account/updateAccountPassword', {
			asynchronous: false, 
			method: 'post', 
			parameters: account_data, 
			onComplete: result.bind(this)
		});		
	}, 
	_sendForgotPassword: function(email, cart) {
		cart = typeof(cart) != 'undefined' ? cart : false;
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request('/account/forgotPasswordEmail/' + email, {
			asynchronous: false, 
			method: 'post', 
			parameters: {email: email, sentfromcart: cart}, 
			onComplete: result.bind(this)
		});		
	}	
});
/*
 * Cart Functions
 */
 
function checkCreditCardFormat(submitting_element) {

	var card_number_valid = true;
	var card_type_valid = true;
	var card_cvv_valid = true;	
	var card_exp_mo_valid = true;
	var card_exp_yr_valid = true;	
	
	var todays_date = new Date();
	var todays_month = todays_date.getMonth();
	var todays_year = todays_date.getFullYear();
	
	var cardNumbersOnly = $("card_number").value;
	var cardNumbersOnly = cardNumbersOnly.replace(/\D/g,"");
	var cardNumberLength = cardNumbersOnly.length;

	// Check expiration date
	if ($("card_exp_mo").value == "") {
		card_exp_mo_valid = false;
	}

	if ($("card_exp_yr").value == "") {
		card_exp_yr_valid = false;
	}

	if (todays_year > $("card_exp_yr").value) {
		card_exp_yr_valid = false;
	} 
	
	if (todays_year == $("card_exp_yr").value) {
		if (todays_month > $("card_exp_mo").value) {
			card_exp_yr_valid = false;
		}
	}
	
	if ($("card_type").value != "") {
		var ct = $("card_type").value;
	} else {
		card_type_valid = false;
	}
	
	// Check Visa cards
	if ($("card_type").value == "visa") {
		if ((cardNumberLength != 16) && ((cardNumberLength != 14))){
			card_number_valid = false;
		}
		
		if ($("card_cvv").value.length != 3) {
			card_cvv_valid = false;
		}
	}
	
	// Check Mastercard cards
	if ($("card_type").value == "mastercard") {
		if (cardNumberLength != 16) {
			card_number_valid = false;
		}
	
		if ($("card_cvv").value.length != 3) {
			card_cvv_valid = false;
		}
	}
		
	// Check American Express cards
	if ($("card_type").value == "amex") {
		if ((cardNumberLength != 16) && ((cardNumberLength != 15))){
			card_number_valid = false;
		}
		
		if ($("card_cvv").value.length != 4) {
			card_cvv_valid = false;
		}
	}
	
	// Check Discover cards
	if ($("card_type").value == "discover") {
		if ((cardNumberLength != 14) && ((cardNumberLength != 15)) && ((cardNumberLength != 16))){
			card_number_valid = false;
		}
	
		if ($("card_cvv").value.length != 3) {
			card_cvv_valid = false;
		}
	}
	
	// send the appropriate validation status back according to which element called this function
	if (submitting_element == "card_number") {
		ret_var = card_number_valid;
	} else if (submitting_element == "card_type") {
		ret_var = card_type_valid;
	} else if (submitting_element == "card_cvv") {
		ret_var = card_cvv_valid;
	} else if (submitting_element == "card_exp_mo") {
		ret_var = card_exp_mo_valid;
	} else if (submitting_element == "card_exp_yr") {
		ret_var = card_exp_yr_valid;
	} else {
		ret_var = false;
	}
	return ret_var;
}
 
function xAddToCart(item_id, price, quantity) {
	var cart = new Cart;
	cart._AddToCart(item_id, price, quantity);
	
	if ($('view-cart-items').style.display == 'none') {
		 var count = 2;
	} else {
		var count = 3;
	}
	if (pulse_cart) { pulse_cart.cancel(); }
	pulse_cart = new Effect.Parallel([
		new Effect.Appear('view-cart-items', {duration: 2, sync: true}),
		new Effect.Pulsate('view-cart-items', {pulses: count, duration: 2, sync: true})
	],{
		duration: 2
	});

	window.location = "/cart";
}

function xRemoveFromCart(item_id, target) {
	var cart = new Cart;
	cart.target = target;
	cart._RemoveFromCart(item_id);
	
	cart._GetCartNumItems();
	if (cart._responseText <= 0) {
		$('added-to-cart').hide();	
		$('view-cart-items').hide();
	}
}

function confirmDelete(item_id, target) {
	if (confirm("Are you sure you want to remove this item?")) {
		xRemoveFromCart(item_id, target);
	}
}
function xUpdateCartItem(item_id,quantity,target) {
	var cart = new Cart;
	cart.target = target;
	cart._UpdateCart2(item_id,quantity,target);
}
function updateMe(item_id,quantity,target,min_quantity,allow_zero,e){
	var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		keycode = "undetermined";
	}
	if(keycode == 13){
		xUpdateCartItemMinQty(item_id,quantity,target,min_quantity,allow_zero,e);
	}
}
function xUpdateCartItemMinQty(item_id,quantity,target,min_quantity,allow_zero,e) {
	quantity = Math.ceil(quantity);
		if (allow_zero == 0) {
			if (quantity < 1) { quantity = 1;}
		} else {
			if (quantity < 1) { quantity = 0;}
		}
	
		if ((quantity < min_quantity) && (quantity > 0)) {
			quantity = min_quantity;
		}
		key_delay.clear();
		
		if (quantity <= 0) {
			if (confirm("Are you sure you want to remove this item?")) {
				//key_delay.execute("xUpdateCartItem('" + item_id + "','" + quantity + "','" + target + "')");
				xUpdateCartItem(item_id, quantity, target);
			} else {
				window.location.reload();
			}
		} else {
			//key_delay.execute("xUpdateCartItem('" + item_id + "','" + quantity + "','" + target + "')");
			xUpdateCartItem(item_id, quantity, target);
		}
	//}
}

/* 
 * The shipping option changed, update the price.
 */
function xChangedShippingOption(selected_option){
	option_object = selected_option.evalJSON();
	if($('est_arrival')){
		if(option_object.est_arrival != ""){
			$('est_arrival').innerHTML = option_object.est_arrival;
			$('ea_row').style.display = "block";
		}else{
			$('ea_row').style.display = "none";
		}
	}
	if($('get_faster_text')){
		if(option_object.get_faster_text != ""){
			$('get_faster_text').innerHTML = option_object.get_faster_text;
			$('gft_row').style.display = "block";
		}else{
			$('gft_row').style.display = "none";
		}
	}
//
//	if ($("shipping-options-table")) {
//		$("shipping-options-table").down().childElements().each(function (element) {
//			if (element.identify() == "shipMethod-" + option_object.internal_name) {
//				element.style.color = '#d15c1e';
//			} else {
//				element.style.color = '#000';
//			}
//		});
//	}
	total_price = option_object.total_price;
	var ship_method = option_object.internal_name;
	var session = new Session;
	session._SetCookieData('ship_method',ship_method);
	
	updateCartTotals();
	
	xGetProductPriceInfo();
}

function xGetProductPriceInfo() {
	session = new Session;
	
	session._GetSessionData('prod_data');
	prod_data = session._responseText.evalJSON();

	session._GetCookieData('zip_code');
	zip_code = session._responseText;

	session._GetCookieData('ship_method');
	sm_ship_method = session._responseText;
	
	new Ajax.Request('/product/getProductPriceInfo/' + prod_data.price + '/' + zip_code + '/' + sm_ship_method + '/' + prod_data.weight + '/' + prod_data.id,{
		method: 'post',
		onComplete: function(transport) {
			var prod_price_info = transport.responseText.evalJSON();
			if ($('product-tax')) {$('product-tax').show(); }
			if(prod_price_info.pst != '$0.00'){
				if ($('product-pst')) {$('product-pst').show(); }
				if ($('prod-price-pst')) {$('prod-price-pst').innerHTML = prod_price_info.pst;}
			}
			if ($('product-shipping')) {$('product-shipping').show(); }
			if ($('product-total-price')) {$('product-total-price').show(); }			

			if ($('prod-price-tax')) {$('prod-price-tax').innerHTML = prod_price_info.tax;}
			if ($('prod-price-shipping')) {$('prod-price-shipping').innerHTML = prod_price_info.shipping;}
			if ($('prod-price-total')) {$('prod-price-total').innerHTML = prod_price_info.total;}
		}
	});
}

function hideProductPriceInfo() {
	if ($('product-tax')) {$('product-tax').hide();}
	if ($('product-pst')) {$('product-pst').hide();}
	if ($('product-shipping')) {$('product-shipping').hide(); }
	if ($('product-total-price')) {$('product-total-price').hide(); }
}

/* product page:
 * Get our shipping options based on zip_code,prod_weight,prod_price.
 */
function xGetShippingOptions(prod_weight,prod_price){
	
	if (!$('zipcode')) { 
		zip_code = validateZipCode('new'); 
	} else { 
		zip_code = validateZipCode($F('zipcode')); 
	}
	
	if (!zip_code) { 
		$('zipcode').style.backgroundColor = '#f99'; 
		return false; 
	} else if ($('zipcode')) { 
		$('zipcode').style.borderColor = '#fff';
	}
	
	shipping = new Shipping;
	shipping._GetShippingOptions(zip_code,prod_weight,prod_price);
	
	xGetProductPriceInfo();
}

function changedZipCode(prod_weight, prod_price) {
	session = new Session;
	session._UnsetSessionVar('is_canadian');
	session._UnsetSessionVar('zip_code');
 	hideProductPriceInfo(); 
 	xGetShippingOptions(prod_weight, prod_price); 
}

function xGetShippingBubble(zip_code){
	zip_code = validateZipCode(zip_code);
	if(!zip_code){
		$('zip_code').style.backgroundColor = '#f99';
		return false;
	}else if($('zip_code')){
		$('zip_code').style.borderColor = '#fff';
	}
	shipping = new Shipping;
	shipping._GetShippingBubble(zip_code);

}

function xCreateAccount() {
	account_info = new CustomerInformation;
	account_info._updateAccountPassword({password: $F('password')});
	if (!account_info._responseText.empty()) {
		$('infobox').down().innerHTML = "THANK YOU";
		$('infobox').down('div#infobox-data').innerHTML = "Your password has been saved. Sign in during your next visit to speed up the checkout process.";
		$('infobox').down('div#infobox-data').next().hide();
	}
}

function updateCartTotals(){
	cart = new Cart
//	if ($('cart-tax')){cart._GetCartInfo('cart-tax'); }
//	if ($('cart-shipping-rate')){cart._GetCartInfo('cart-shipping-rate');}
//	if ($('cart-total')){cart._GetCartInfo('cart-total');}
	cart._GetCartInfo2();
	if ($('cart-tax-pre')) {
		$("cart-tax-pre").innerHTML = cart_totals.tax0;
		$("cart-tax-super").innerHTML = cart_totals.tax1;
	}
	
	if ($('cart-pst-pre')) {
		if(cart_totals.pstrate == 0){
			$('pst_block').hide();
		}else{
			$('pst_block').show();
		}
		$("cart-pst-pre").innerHTML = cart_totals.psttax0;
		$("cart-pst-super").innerHTML = cart_totals.psttax1;
	}
	
	if ($('cart-shipping-pre')) {
		$("cart-shipping-pre").innerHTML = cart_totals.shipping0;
		$("cart-shipping-super").innerHTML = cart_totals.shipping1;
	}

	if ($('cart-total-pre')) {
		$("cart-total-pre").innerHTML = cart_totals.total0;
		$("cart-total-super").innerHTML = cart_totals.total1;
	}

	if ($('review-items-promotion')) {
		session = new Session;
		session._GetSessionData("_promotion");

//		if (session._responseText != "") {
//			$("review-items-promotion").show();		
//		} else {
//			$("review-items-promotion").hide();
//		}	
	}
}

function validateZipCode(zip_code){
	session = new Session;
	zip_code = zip_code.replace(/[^[a-z0-9]/gi,'');
	
	if(zip_code.match(/^[a-z][0-9][a-z][\-]?[0-9][a-z][0-9]$/i)){
		zip_code = zip_code.replace(/^([a-z][0-9][a-z])([0-9][a-z][0-9])$/gi,"$1 $2");
		zip_code = zip_code.toUpperCase();
		session._SetSessionData('is_canadian',1);
	}else if(zip_code.match(/^[0-9]{5}$|^[0-9]{9}$/)){
		zip_code = zip_code.replace(/^([0-9]{5})([0-9]{4})$/,"$1-$2");
		session._UnsetSessionVar('is_canadian');
	}else if(zip_code == 'new'){
		session._UnsetSessionVar('is_canadian');
		return zip_code;
	}else{
		session._UnsetSessionVar('is_canadian');
		return false;
	}
	return zip_code;
}

function xFormatPhoneNumber(){
	if(!$F('customer_phone')){
		return false;
	}else{
		phone_number = $F('customer_phone');
	}
	phone_number = phone_number.replace(/[^0-9+]/g,"");
	if(phone_number.match(/^[0-9]{0,3}$/)){
		phone_number = phone_number.replace(/^([0-9]{0,3})$/,"($1");
	}
	else if(phone_number.match(/^[0-9]{3}[0-9]{0,3}$/)){
		phone_number = phone_number.replace(/^([0-9]{3})([0-9]{0,3})$/,"($1)$2");
	}
	else if(phone_number.match(/^[0-9]{3}[0-9]{0,3}[0-9]{0,4}$/)){
		phone_number = phone_number.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})$/,"($1)$2-$3");
	}
	else if(phone_number.match(/^[0-9]{3}[0-9]{0,3}[0-9]{0,4}[0-9a-z ]*$/i)){
		phone_number = phone_number.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})([0-9 ]*)$/i,"($1)$2-$3 ext-$4");
	}
	$('customer_phone').value = phone_number;

	return true;
}

function xCheckPassword(action, email, password, signinfrom) {
	customer_information = new CustomerInformation;
	customer_information._validatePassword(action, email, password, signinfrom);
	if(!customer_information._responseText.empty()) {
		window.location = customer_information._responseText;
	} else {
		$('error-box').innerHTML = "Invalid Password";
		$('error-box').show();
	}
}
/*
function xGetPromoCode(code, e) {
	if (e && (e.keyCode == Event.KEY_RETURN)) {
		xGetPromoCodeSubmit(code);
	}
}
*/
function xSubmitForgotPassword(message, event) {
	if (event && (event.keyCode == Event.KEY_RETURN)) {
		key_delay = new KeyDelay;
		key_delay.execute('forgotPassword(\''+message+'\',$F(\'email\'))');
	}
}

function xGetPromoCodeSubmit(code) {
	code = code.strip();
	var cart = new Cart;

	cart.target ='review-items-body';
	cart._SetPromoCode({promo_code: code});
	cart._UpdateView({});
	xRefreshCartView();
	session = new Session;
	session._GetSessionData("_promotion");
	if (session._responseText != "") {
		session._GetSessionData("promo_info");
		var promotion = session._responseText.evalJSON();
		$("promotion_info").innerHTML = promotion.description;
	} else {
		cart._UnsetPromoCode();
		$("promotion_info").innerHTML = "Invalid Promotion Code";
	}
	
	//updateCartTotals();
}

function xRefreshCartView(){
	request = new Ajax.Updater('review-items-body', "/cart/reloadOrderSummary", {
		asynchronous:	false,
		method: 		'post',
		onComplete:		function(transport) {
		}
	});
}

function toggleShippingInfo(e){
	if(e.checked){
		populateShippingWithBilling();
	}else{
		clearShippingInfo();
	}
}

function clearShippingInfo() {
	$("shipping_name").enable();
	$("shipping_address1").enable();
	$("shipping_address2").enable();
	$("shipping_city").enable();
	$("shipping_state").enable();
	$("shipping_zip").enable();
	$("shipping_country").enable();
	$("billing_name").removeAttribute("onKeyUp");
	$("billing_address1").removeAttribute("onKeyUp");
	$("billing_address2").removeAttribute("onKeyUp");
	$("billing_city").removeAttribute("onKeyUp");
	$("billing_state").removeAttribute("onchange");
	$("billing_zip").removeAttribute("onKeyUp");
	$("billing_country").removeAttribute("onchange");
}

function populateShippingWithBilling() {
	$("shipping_name").value 		= $("billing_name").value;
	$("shipping_address1").value 	= $("billing_address1").value;
	$("shipping_address2").value 	= $("billing_address2").value;
	$("shipping_city").value 		= $("billing_city").value;
	$("shipping_state").value 		= $("billing_state").value;
	$("shipping_zip").value 		= $("billing_zip").value;
	$("shipping_country").value		= $("billing_country").value;
	$("shipping_name").disable();
	$("shipping_address1").disable();
	$("shipping_address2").disable();
	$("shipping_city").disable();
	$("shipping_state").disable();
	$("shipping_zip").disable();
	$("shipping_country").disable();
	$("billing_name").setAttribute("onKeyUp","changeTarget(this)");
	$("billing_address1").setAttribute("onKeyUp","changeTarget(this)");
	$("billing_address2").setAttribute("onKeyUp","changeTarget(this)");
	$("billing_city").setAttribute("onKeyUp","changeTarget(this)");
	$("billing_state").setAttribute("onchange","changeTarget(this)");
	$("billing_zip").setAttribute("onKeyUp","changeTarget(this)");
	$("billing_country").setAttribute("onchange","changeTarget(this)");
}
function changeTarget(e){
	var name = e.identify();
	var newname = name.replace("billing","shipping");
	$(newname).value = e.value;
}
function submitForm(form_id, e) {
	var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		return true;
	}
	
	if (keycode == 13) {
	   form_id.submit();
	   return false;
	} else {
	   return true;
	}
}

function enterButtonPressed(e) {
	var keycode;
	
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		return false;
	}
	
	if (keycode == 13) {
	   return true;
	}
}

function matchPasswords(password_one, password_two) {
	if (password_one == password_two) {
		xCreateAccount();
	} else {
		alert("Passwords do not match");
	}
}

function logComment(message) {
	request = new Ajax.Request('/home/logComment', {
		asynchronous: true, 
		method: 'post', 
		parameters: {message: message}
	});
	closeGraybox();
}

function showGraybox(template, parameters,after) {

	new_template = new CustomTemplate;
	new_template._loadTemplate($('graybox-window'),template,parameters);

	if (Prototype.Browser.IE) {
		h = document.body.parentNode.scrollHeight; 
		w = document.body.parentNode.scrollWidth; 
		$('graybox').style.width = w+"px";
		$('graybox').style.height = h+"px";
		$('graybox-window').style.top = (document.body.parentNode.scrollTop+200)+"px";
		$('graybox-window').style.left = ((document.body.clientWidth/2) - 152)+"px";
		$('graybox').show();
		$('graybox-window').show();
		grayboxint = setInterval('optMe()', 10);
	} else {
		if ($('graybox').style.display == "none") {
			new Effect.Appear($('graybox'),{
				asynchronous: false, 
				to: .4, 
				from: .1, 
				duration: .5, 
				afterFinish: function(o) {
					new Effect.Appear($('graybox-window'),{asynchronous: false, to: 1, duration: .5, queue: {position: 'end', scope: 'queue1'}, after: after});
//					new Effect.MoveBy($('graybox-window'),( ( $('graybox').getDimensions().height / 2 ) - ( $('graybox-window').getDimensions().height / 2 ) ) , ( ( $('graybox').getDimensions().width / 2 ) - ( $('graybox-window').getDimensions().width / 2) ),{asynchronous: false, duration: 0,queue: {position: 'front', scope: 'queue1'}});
				}
			});
		}	
		h = document.body.parentNode.scrollHeight; 
		w = document.body.parentNode.scrollWidth; 
		$('graybox').style.width = w+"px";
		$('graybox').style.height = h+"px";
		$('graybox-window').style.top = (document.body.parentNode.scrollTop+150)+"px";
		$('graybox-window').style.left = ((document.body.clientWidth/2) - 152)+"px";
	}						
}
function optMe(){
	if($('graybox').filters[0].opacity > 49){
		clearInterval(grayboxint);
	}
	$('graybox').filters[0].opacity = $('graybox').filters[0].opacity + 2;
}
function unoptMe(){
	if($('graybox').filters[0].opacity < 2){
		clearInterval(grayboxint2);
		$('graybox').style.width = "0px";
		$('graybox').style.height = "0px";
		$('graybox').hide();
	}
	$('graybox').filters[0].opacity = $('graybox').filters[0].opacity - 2;
}

function closeGraybox(custom_event) {
	if (!is_object(custom_event)) {
		custom_event = {event: "default"};
	}

	if (Prototype.Browser.IE) {
		$('graybox-window').hide();
		grayboxint2 = setInterval('unoptMe()', 10);
	} else {
		new Effect.Fade($('graybox-window'),{from: 1, to: 0, duration: .5, afterFinish: function (o) {
		new Effect.MoveBy($('graybox-window'), -1 * (($('graybox').getDimensions().height / 2) - ($('graybox-window').getDimensions().height / 2 )), -1 * (($('graybox').getDimensions().width / 2) - ($('graybox-window').getDimensions().width / 2)),{duration: 0});
			
		}});
		new Effect.Fade($('graybox'),{from: .4, to: 0, duration: .5});
		document.fire('cart:' +custom_event.event,custom_event.parameters);
	}
}

function checkoutStep(which_step, highest_step, current_step) {

	if (which_step != current_step) {
		if ((which_step == 1) && (highest_step >= 1)) {
			window.location = "/cart/customerInformation"; 
		} else if ((which_step == 2) && (highest_step >= 2)) {
			window.location = "/cart/shippingOptions"; 
		} else if ((which_step == 3) && (highest_step >= 3)) {
			window.location = "/cart/reviewAndPay"; 
		} else {
			return false;
		}
	} else {
		return false;
	}

}
processing = false;
function clickNextStepButton(source_id, bypass_gc) {
	if(typeof bypass_gc == 'undefined'){
		bypass_gc = false;
	}
	if(iferror == 0 && !processing){
		informationValidation(source_id, bypass_gc);
	}
}
function startCCAuth(m){
	clearTimeout(cctimeout);
	if(m.value == ""){
		$('error_fields').style.display = "none";
		cardReset();
		iferror = 0;
	}
	cctimeout = setTimeout("cardChecker()", 100);	
	m.value = m.value.replace(/\D/g,'');
	globalm = m;
}
function mod10valid(m){
	if(m.value != ""){
		var ccnum = m.value;
		ccnum = ccnum.replace(/\D/g,'');
		var cctype = ccnum.substr(0,4);
		errors = new Array();
		cardarray = ccnum.split("");
		cardarray = cardarray.reverse();
		j = cardarray.length;
		var cardsum = 0;
		var count = 0;
		cardarray.each(function(i){
			if(count%2 != 0){
				var n = parseInt(i)*2;
				if(n > 9){
					n = n+"";
					k = n.split("");
					k.each(function(s){
						cardsum = parseInt(s)+cardsum;
					});
				}else{
					cardsum = n+cardsum;
				}
			}else{
				cardsum = parseInt(i)+cardsum;
			}
			count++;
		});
		if(cardsum%10 == 0){
			errors['mod10'] = 0;
		}else{
			errors['mod10'] = 1;
		}
		errors['display_type'] = '';
		switch(parseInt(cctype.substr(0,1))){
			case 4:
					errors['len'] = lengthTest(new Array(13,16),ccnum);
					errors['slen'] = "13 or 16";
					errors['type'] = 'visa';
					errors['display_type'] = 'Visa';
					break;
		}
		switch(parseInt(cctype.substr(0,2))){
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
					 errors['len'] = lengthTest(16,ccnum);
					 errors['slen'] = 16;
					 errors['type'] = 'mastercard';
					 errors['display_type'] = 'Mastercard';
					break;
			case 34:
			case 37:
					 errors['len'] = lengthTest(15,ccnum);
					 errors['slen'] = 15;
					 errors['type'] = 'amex';
					 errors['display_type'] = 'American Express';
					break;
		}
		switch(parseInt(cctype)){
			case 6011:
					errors['len'] = lengthTest(16,ccnum);
					errors['slen'] = 16;
					errors['type'] = 'discover';
					errors['display_type'] = 'Discover';
					break;
		}
		iferror = 0;
		$('error_text').innerHTML = '';
		if(errors['type'] == undefined){
			cardReset();
			// Invalid Card Type
			$('error_text').innerHTML += "Credit Card Number Entered is Not a Valid Visa, Mastercard, American Express or Discover card number.<br>";
			iferror++;
		}else{
			cardFader(errors['type']);
			if(errors['len'] != 0){
				// Invalid Length
				$('error_text').innerHTML += "Improper number of digits for the card type you are using.<br>";
				iferror++;
			}
			if(errors['mod10'] != 0){
				// Invalid Card Sequence
				$('error_text').innerHTML += "Credit Card Number Entered is Not a Valid "+errors['display_type']+" Credit Card Number.<br>";
				iferror++;
			}
		}
		if(iferror !=  0){
			$('error_text').innerHTML += "Please Check the Card and Try Again.";
			$('error_fields').style.display = "block";
		}else{
			$('error_fields').style.display = "none";
		}
	}
}
function mod7valid(m){
	if(m.value != ""){
		var ccnum = m.value;
		ccnum = ccnum.replace(/\D/g,'');
		var cctype = ccnum.substr(0,4);
		errors = new Array();
		cardarray = ccnum.split("");
		cardarray = cardarray.reverse();
		j = cardarray.length;
		var cardsum = 0;
		var count = 0;
		cardarray.each(function(i){
			if(count%2 != 0){
				var n = parseInt(i)*2;
				if(n > 9){
					n = n+"";
					k = n.split("");
					k.each(function(s){
						cardsum = parseInt(s)+cardsum;
					});
				}else{
					cardsum = n+cardsum;
				}
			}else{
				cardsum = parseInt(i)+cardsum;
			}
			count++;
		});
		if(cardsum%7 == 0){
			errors['mod7'] = 0;
		}else{
			errors['mod7'] = 1;
		}
		errors['display_type'] = '';
		switch(parseInt(cctype.substr(0,2))){
			case 67:
					 errors['len'] = lengthTest(16,ccnum);
					 errors['slen'] = 16;
					 errors['display_type'] = 'SM Gift Card';
					break;
		}
		iferror = 0;
		$('error_text').innerHTML = '';
			if(errors['len'] != 0){
				// Invalid Length
				$('error_text').innerHTML += "Improper number of digits for the gift card you are using.<br>";
				iferror++;
			}
			if(errors['mod7'] != 0){
				// Invalid Card Sequence
				$('error_text').innerHTML += "Gift Card Number Entered is Not a Valid "+errors['display_type']+" Number.<br>";
				iferror++;
			}
		if(iferror !=  0){
			$('error_text').innerHTML += "Please Check the Card and Try Again.";
			$('error_fields').style.display = "block";
		}else{
			$('error_fields').style.display = "none";
		}
	}
}
function cardChecker(){
	var ccnum = globalm.value;
	var cctype = ccnum.substr(0,4);
	errors = new Array();
	errors['display_type'] = '';
	switch(parseInt(cctype.substr(0,1))){
		case 4:
				errors['type'] = 'visa';
				errors['display_type'] = 'Visa';
				break;
	}
	switch(parseInt(cctype.substr(0,2))){
		case 51:
		case 52:
		case 53:
		case 54:
		case 55:
				 errors['type'] = 'mastercard';
				 errors['display_type'] = 'Mastercard';
				break;
		case 34:
		case 37:
				 errors['type'] = 'amex';
				 errors['display_type'] = 'American Express';
				break;
	}
	switch(parseInt(cctype)){
		case 6011:
				errors['type'] = 'discover';
				errors['display_type'] = 'Discover';
				break;
	}
	if(errors['type'] == undefined){
		cardReset();
	}else{
		cardFader(errors['type']);
	}
}
function cardFader(type){
	$('card_type').value = type;
	$('visa').src = $('visa').getAttribute('graypic');
	$('mastercard').src = $('mastercard').getAttribute('graypic');
	$('amex').src = $('amex').getAttribute('graypic');
	$('discover').src = $('discover').getAttribute('graypic');
	$(type).src = $(type).getAttribute('bpic');
}
function cardReset(){
	$('card_type').value = '';
	$('visa').src = $('visa').getAttribute('bpic');
	$('mastercard').src = $('mastercard').getAttribute('bpic');
	$('amex').src = $('amex').getAttribute('bpic');
	$('discover').src = $('discover').getAttribute('bpic');
}
function lengthTest(n, ccnum){
	var k = ccnum.length;
	var arrreturn = 1;
	if(n.constructor.toString().indexOf("Array") != -1){
		n.each(function(i){
			if(i == k){
				arrreturn = 0;
			}
		});
		if(arrreturn == 1){
			arrreturn = k;
		}
		return arrreturn;
	}else{
		if(n == k){
			return 0;
		}else{
			return k;
		}
	}
}
function informationValidation(source_id, bypass_gc) {
	if(source_id == "submit-button"){
		processing = true;
		$(source_id).removeClassName('submit-button');
		$(source_id).addClassName('submit-button-gray');
		/* Check for/process promo code if it is set */
		if ($F('promo_code') != '') {
			xGetPromoCodeSubmit($F('promo_code'));
		}
	}
	var missing_text = "";
	valid_data = true;
	if($('cart-total-pre') == null || (parseFloat($('cart-total-pre').innerHTML.replace(/[^0-9]/,"")) != 0 && $('cart-total-pre').innerHTML != 0)){
		form_data = new CustomForm;
		var infobox_form = $('body').getElementsBySelector('form.process');
		infobox_form.each(function (value) {
			var form_inputs = value.getElements();
			form_inputs.each(function (input_element) {
				/* check to see if it's a required element */
				if (input_element.up().hasClassName("required")) {
				
					if ((input_element.id == "billing_zip") && (input_element.value.strip() != "")) {
						var shipping = new Shipping;
						shipping._UpdateShipTo(input_element.value);
						details =  shipping._responseText.evalJSON();
						if (details.error_code) {
							$("zipcode-error").innerHTML = details.error_text;
							$("zipcode-error").show();
					
							if (missing_text != "") {
								missing_text = missing_text + ", ";
							}
							missing_text = missing_text + $("billing_zip").readAttribute('alt_text');		
							valid_data = false;
						} else {
							$("zipcode-error").hide();					
						}
					}
	
					if ((input_element.id == "shipping_zip") && (input_element.value.strip() != "")) {
						var shipping = new Shipping;
						shipping._UpdateShipTo(input_element.value);
						details =  shipping._responseText.evalJSON();
						if (details.error_code) {
							$("zipcode-error").innerHTML = details.error_text;
							$("zipcode-error").show();
					
							if (missing_text != "") {
								missing_text = missing_text + ", ";
							}
							missing_text = missing_text + $("shipping_zip").readAttribute('alt_text');		
							valid_data = false;
						} else {
							$("zipcode-error").hide();					
						}
					}
				
					if (!form_data.validateFormElement(input_element) || (input_element.value.strip() == "")) {
						/* not populated, add it to the list of missing bits */
						if (missing_text != "") {
							missing_text = missing_text + ", ";
						}
						missing_text = missing_text + input_element.readAttribute('alt_text');
						input_element.setStyle({border:'solid 2px #d15c1e'});
						valid_data = false;
					}else{
						if (input_element.id.match(/email/)){
							test = new CustomForm;
							test.validateCustomerEmail(input_element.value);
							if(test._responseText.empty()){
								valid_data = false;
								//element.style.background = '#faa';
								showGraybox('cart/password',{email: input_element.value});
							}else{
								input_element.style.background = '#fff';
							}	
						}
					}					
				}
			});
			if (valid_data) {
				if(source_id == "submit-button"){
					if($F('gift_card_cvv') != '' && $F('gift_card_number') != '' && !bypass_gc){
						yesNoConfirm('Process Gift Card?','Gift card has not yet been applied. Would you like to use the gift card?',"clickNextStepButton('submit-button',true)","proStatus(1);checkGiftCard();proStatus(2)" );
						valid_data = false;
					}else{
						form_data._SaveFormData(value);
					}
				}else{
					form_data._SaveFormData(value);
				}
			}
		});
	}
	if($('cart-total-pre') != null){
		if(parseFloat($('cart-total-pre').innerHTML.replace(/[^0-9]/,"")) == 0 && $('cart-total-super').innerHTML == 0){
			missing_text = "";
			valid_data = true;
		}
	}
	if(!missing_text.empty()){
		$("missing_field_text").innerHTML = "The following fields are missing or invalid: " + missing_text;
		$("missing_fields").show();
	}else{
		$("missing_fields").hide();
	}
	if (valid_data) {
		window.location = $(source_id).readAttribute('destination');
	}else{
		if(source_id == "submit-button"){
			processing = false;
			$(source_id).removeClassName('submit-button-gray');
			$(source_id).addClassName('submit-button');
		}
	}
}

document.observe('cart:clear_form_element',function(event) { 
	$(event.memo.element).value = "";
	form_data = new CustomForm;
	form_data.updateFormValidation($(event.memo.element), form_data.validateFormElement($(event.memo.element)));
}); 
document.observe('cart:save_cart',function(event) {
	var cart = new Cart;
	cart._SaveCart(event.memo);
}); 
document.observe('cart:default',function(event) { 
	
}); 

/*
 *  OnLoad Functions
 */
function initializeElement () {
form_data = new CustomForm;
var infobox_form = $('body').getElementsBySelector('form.process');

if ($('customer_phone')) {
	xFormatPhoneNumber();
}

session = new Session
updatePageElements();

}

function updateForm(input_element, value) {
	
	form_data = new CustomForm;
	input_element = $(input_element);
	value = $(value);
	form_data.updateFormValidation(input_element, form_data.validateFormElement(input_element)); 
//	form_data._GatherFormData(value, input_element);
}

function buildValidation() {
	elements_array = new Hash();
	var infobox_form = $('body').getElementsBySelector('form.process');
	infobox_form.each(function (value) {
		form_element_hash = new Hash();
		value.getElementsBySelector('div.required').each( function(element) {
			
			element.childElements().each( function(form_element) {
				if (form_element.hasClassName('popup')) {
					return;
				}
				form_element_hash.set(form_element.id, false);
				if (!form_element.value.empty()) {
					form_element_hash.set(form_element.id, true);
				} else {
					form_element_hash.set(form_element.id, false);
					
				}
			});
			
			
		});
		elements_array.set(value.name, form_element_hash);
		
	});
	return(elements_array.toJSON());
}

function updatePageElements() {
	/*
	 * Update Shopping Cart Elements
	 */
	if ($('cart-box')) {
		if ($('ship-method')) { 
			$('ship-method').getInputs().each( function(input) {
				if(input.checked) {xChangedShippingOption(input.value);}
				//; 
			});
			updateCartTotals();
		}
	}
	
	if ($("review-items-promotion")) {
		session = new Session;
		session._GetSessionData("_promotion");
//		if (session._responseText != "") {
//			$("review-items-promotion").show();
//		} else {
//			$("review-items-promotion").hide();	
//		}
	}
}

function runThankYouAgain(){
	window.location = "/cart/thankYou/1";
}

function homePageClearSession(){
	session = new Session;
	session._UnsetSessionData();
	window.location = "/";
}
         
function trackButtonClicks(product_id, button_pressed) {
	request = new Ajax.Request("/cart/trackButtonClicks", {
		asynchronous: false,
		method: "post",
		parameters: {product_id: product_id, button_pressed: button_pressed},
		onComplete: function (transport) {
//			alert(transport.responseText); 
		}
	});

}

function checkGiftCard(){
	if(iferror == 0){
		cart = new Cart
		cart._GetCartInfo2();
		var k =cart_totals.total0+""+cart_totals.total1;
		new Ajax.Request("/cart/checkGiftCard", {
			asynchronous: false,
			method: "post",
			parameters: {gift_card_id: $F('gift_card_number'), gift_card_cvv: $F('gift_card_cvv'), cart_total: k},
			onComplete: function (transport) {
				if(transport.responseText == 'Invalid'){
					$('error_text').innerHTML = "Gift Card is either Invalid or has a $0 balance. If you have any questions please call customer service at: 1-800-474-1045";
					$('error_fields').style.display = "block";
				}else if(transport.responseText == 'Zero'){
					$('error_text').innerHTML = "May not use another gift card, order total is zero.";
					$('error_fields').style.display = "block";
				}else{
					xRefreshCartView();
					$('gift_card_number').value = "";
					$('gift_card_cvv').value = "";
				}
			}
		});
	}
}

function removeGiftCard(id){
	new Ajax.Request("/cart/removeGiftCard", {
		asynchronous: false,
		method: "post",
		parameters: {gift_card_id: id},
		onComplete: function (transport) {
				xRefreshCartView();
		}
	});
}

function proStatus(n){
	switch(n){
	case 1:
		$('forgot-password-tile').down().innerHTML = "Processsing Gift card...";
		$('ynbuttons').innerHTML = "";
		break;
	case 2:
		$('forgot-password-tile').down().innerHTML = "Gift Card processed. Hit 'Submit Order' to finalize order.";
		break;
	}
}

//Event.observe(window,'dom:loaded',initializeElement,false);
Event.observe(window,'load',initializeElement,false);
//Event.observe(window,'load',xShowSession,false);
