var grayboxint = 0;
var grayboxint2 = 0;
var cctimeout = 0;
var globalm = '';
var iferror = 0;
var cartCCObj = new Object();
	
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,'/ajax/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('/ajax/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, data, qty) {
		if (!qty) {
			qty = 1;
		}
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request(this.addToCartURL + item_id + "/" + data, {
			asynchronous: false, 
			method: 'post',
			parameters: {qty: qty},
			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) {
		request = new Ajax.Request(this.updateCartURL + item_id + "/" + quantity, {
			asynchronous: false, 
			method: 'post'
		});
	},
	_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,
			method: 		'post',
			parameters:  {echo: 'true'},
			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;
			//this.target;
		}
		request = new Ajax.Request("/cart/getPromoInfo/", {
			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() {
	},
	_UpdateShipTo: function(zip_code) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Request("/shipping/getCityAndState/" + zip_code, {
			asynchronous: false, 
			method: 'get',
			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_elements) {
		collector_array = new Array();
		form_elements.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;
		});
		
		if (collector_array.length > 0) {
			// Put AJAX for save here.
			 new Ajax.Request('/cart/saveCustomerInfo', {
				asynchronous: false, 
				method: 'post', 
				parameters: {bundle: 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 ) {
			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}/)){
		 			passed_validation = false;
				}else{
				}
			 }
		}
		
		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, data) {
	$('loading_box').style.display = 'block';
	var qty = 1;
	if($("product_item_qty") && $("product_item_min_qty")){
		if ($("product_item_qty").value > $("product_item_min_qty").value) {
			qty = $("product_item_qty").value;
		} else {
			qty = $("product_item_min_qty").value;
		}
	}
	
	var cart = new Cart;
	cart._AddToCart(item_id, data, qty);
	
	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();	
		if($('view-cart-items') != null){
			$('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._UpdateCart(item_id,quantity);
}
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) {
	fillCartCCObj();
	$('loading_box').style.display = 'block';
	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;
		}

		if (quantity <= 0) {
			if (confirm("Are you sure you want to remove this item?")) {
				xUpdateCartItem(item_id, quantity, target);
				window.location.reload();
			}else{
				$('loading_box').style.display = 'none';
			}
		} else {
			xUpdateCartItem(item_id, quantity, target);
			if(target == "reviewAndPay"){
				ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
				window.location = "//www.softwaremedia.com/cart/reviewAndPay";
			}else{
				ajaxUpdateMyCart('/ajax/refreshCart');
			}
			
			$('loading_box').style.display = 'none';
		}
}

function changeShippingOption(value){
	$('loading_box').style.display = 'block';
	SetCookieData('ship_method',value);
	ajaxUpdateMyCart('/ajax/refreshCart');
	$('loading_box').style.display = 'none';
}
function SetCookieData(id, value) {
	request = new Ajax.Request('/ajax/updateCookie', {
		asynchronous: false, 
		method: "post", 
		parameters: {id: id, value: value} 
	});
}
function ajaxUpdateMyCart(refreshCall) {

	new Ajax.Updater('main', refreshCall, {
		asynchronous: false,
		parameters: {ccobj:Object.toJSON(cartCCObj)},
		onSuccess: function(trans){
			$('loading_box').style.display = 'none';
		}
	});

	/**
	var csslink = document.createElement("link");
	csslink.setAttribute("rel", "stylesheet");
	csslink.setAttribute("type", "text/css");
	csslink.setAttribute("href", "/application/views/sm/skins/default/css/cart.css");
	document.getElementsByTagName("head")[0].appendChild(csslink);
	**/
}
/* 
 * The shipping option changed, update the price.
 */
function fillCartCCObj(){
	if($('card_name') != null){
		cartCCObj.name = $F('card_name');
		cartCCObj.num = $F('card_number');
		cartCCObj.type = $F('card_type');
		cartCCObj.cvv = $F('card_cvv');
		cartCCObj.exp_mo = $F('card_exp_mo');
		cartCCObj.exp_yr = $F('card_exp_yr');
		if($F('special_comments') != "Optional: Enter special shipping instructions or additional comments"){
			cartCCObj.comments = $F('special_comments');
		}else{
			cartCCObj.comments = "";
		}
	}
}
function xChangedShippingOption(selected_option){
	fillCartCCObj();
	$('loading_box').style.display = 'block';
	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";
		}
	}

	total_price = option_object.total_price;
	var ship_method = option_object.internal_name;
	var session = new Session;
	session._SetCookieData('ship_method',ship_method);
	ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
}

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('/ajax/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){
	$('loading_box').style.display = 'block';
	
	//Validate zip code before setting it. This is just a band-aid. I couldn't figure out another way to fix this within a reasonable amount of time.
	//The whole cart needs to be rewritten... badly...
	new Ajax.Request('/ajax/testZipCode', {
		asynchronous: false,
		method: 'post',
		parameters: {zip_code: zip_code},
		onComplete: function (transport) {
			var r = transport.responseText.evalJSON();
			if (r.error) {
				alert("Please enter a valid zip code");
				SetCookieData("zip_code","");
			} else {
				SetCookieData("zip_code",zip_code);
			}
		}
	});

	new Ajax.Request('/ajax/setDefaultMethod', {
		asynchronous: false, 
		method: 'post', 
		parameters: {zip_code: zip_code}
	});
	ajaxUpdateMyCart('/ajax/refreshCart');
	$('loading_box').style.display = 'none';
}

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 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)) {
			forgotPassword(message,$F('email'));
	}
}

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

/* check the validity of the code first */
	cart._GetPromoInfo({promo_code: code});
	response = cart._responseText.evalJSON();
	if (!response.error_text) {
		cart._SetPromoCode({promo_code: code});
		if(!cart._responseText.empty()){
			if (validatePromoItemExists(cart._responseText.evalJSON())) {
				showGraybox('chooseitem',{decode_promo_data: cart._responseText});
			} 
		}
		session = new Session;
		session._GetSessionData("_promotion");
		if (session._responseText != "") {
			session._GetSessionData("promo_info");
			var promotion = session._responseText.evalJSON();
			$("promotion_info").innerHTML = promotion.description;
			$('loading_box').style.display = 'block';
			ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
		} else {
			cart._UnsetPromoCode();
			$('loading_box').style.display = 'block';
			ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
			$("promotion_info").innerHTML = "Invalid Promotion Code";
		}
	} else {
		cart._UnsetPromoCode();
		$('loading_box').style.display = 'block';
		ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
		$("promotion_info").innerHTML = response.error_text;
	}
}
function validatePromoItemExists(obj){
	var r = false;
	obj.each(function(i){
		if(!i.id.empty()){
			r = true;
		}
	});
	return r;
}
function toggleShippingInfo(e){
	if(e.checked){
		populateShippingWithBilling();
	}else{
		clearShippingInfo();
	}
}

function toggleEndUserInfo(e,type){
	if(e.checked){
		if(type == 'billing'){
			if($('eu_sasa').checked){
				clearEndUserInfo();
				$('eu_sasa').checked = false;
			}
			populateEndUserWithBilling();
		}else if(type == 'shipping'){
			if($('eu_saba').checked){
				clearEndUserInfo();
				$('eu_saba').checked = false;
			}
			populateEndUserWithShipping();
		}
	}else{
		clearEndUserInfo();
	}
}

function clearEndUserInfo(){
	$("eu_company").enable(); 	
	$("eu_email").enable();		
	$("eu_name").enable();		
	$("eu_phone").enable();
	
	$("eu_address").enable(); 	
	$("eu_city").enable(); 		
	$("eu_state").enable(); 	
	$("eu_zip").enable(); 				
	
	removeAttributeSafe($("customer_company"),'onKeyUp',"changeTargetEndUser(this,'customer')",";");
	removeAttributeSafe($("customer_email"),'onKeyUp',"changeTargetEndUser(this,'customer')",";");
	removeAttributeSafe($("customer_name"),'onKeyUp',"changeTargetEndUser(this,'customer')",";");
	removeAttributeSafe($("customer_phone"),'onKeyUp',"changeTargetEndUser(this,'customer')",";");
	
	removeAttributeSafe($("billing_name"),'onKeyUp',"changeTargetEndUser(this,'billing')",";");
	removeAttributeSafe($("billing_address1"),'onKeyUp',"changeTargetEndUser(this,'billing')",";");
	removeAttributeSafe($("billing_address2"),'onKeyUp',"changeTargetEndUser(this,'billing')",";");
	removeAttributeSafe($("billing_city"),'onKeyUp',"changeTargetEndUser(this,'billing')",";");
	removeAttributeSafe($("billing_state"),'onchange',"changeTargetEndUser(this,'billing')",";");
	removeAttributeSafe($("billing_zip"),'onKeyUp',"changeTargetEndUser(this,'billing')",";");
	
	removeAttributeSafe($("shipping_name"),'onKeyUp',"changeTargetEndUser(this,'shipping')",";");
	removeAttributeSafe($("shipping_address1"),'onKeyUp',"changeTargetEndUser(this,'shipping')",";");
	removeAttributeSafe($("shipping_address2"),'onKeyUp',"changeTargetEndUser(this,'shipping')",";");
	removeAttributeSafe($("shipping_city"),'onKeyUp',"changeTargetEndUser(this,'shipping')",";");
	removeAttributeSafe($("shipping_state"),'onchange',"changeTargetEndUser(this,'shipping')",";");
	removeAttributeSafe($("shipping_zip"),'onKeyUp',"changeTargetEndUser(this,'shipping')",";");
}

function saveEndUserInfo(){
	if($('eu_company') != null){
		new Ajax.Request('/cart/saveEndUserInfo', {
			asynchronous: false, 
			method: 'POST', 
			parameters: {company:$F('eu_company'),address:$F('eu_address'),city:$F('eu_city'),state:$F('eu_state'),zip:$F('eu_zip'),email:$F('eu_email'),contact:$F('eu_name'),phone:$F('eu_phone'),plauth:$F('eu_plauth'),plagree:$F('eu_plagree')}
		});
	}
}

function validateEndUserInfo(){
	if($('eu_company') != null){
		var return_str = '';
		var delim = '';
		jQuery('#eu_block .required input').each(function(){
			if(this.value == ''){
				if(return_str != '')
					delim = ', ';
				return_str += delim+jQuery(this).attr('alt_text');
				jQuery(this).css({border: '2px solid #D15C1E'});
			}else{
				jQuery(this).css({border: '1px solid #CCCCCC'});
			}
		});
		return return_str;
	}
	return '';
}
function removeAttributeSafe(e,a,v,d){
	var a_data = e.getAttribute(a);
	if(a_data != '' && a_data != null){
		if(v == a_data){
			e.removeAttribute(a);
		}else{
			var newAttrib = a_data.replace(v,"");
			e.removeAttribute(a);
			if(newAttrib.substr(0,1) == d)
				newAttrib = newAttrib.substr(1);
			if(newAttrib != '')
				e.setAttribute(a,newAttrib);
		}
	}
}

function setAttributeSafe(e,a,v,d){
	var a_data = e.getAttribute(a);
	if(a_data != '' && a_data != null){
		if(v != a_data){
			var newAttrib = a_data+d+v;
			if(newAttrib.substr(0,1) == d)
				newAttrib = newAttrib.substr(1);
			e.removeAttribute(a);
			e.setAttribute(a,newAttrib);
		}
	}else{
		e.setAttribute(a,v);
	}
}

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

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();
	setAttributeSafe($("billing_name"),'onKeyUp',"changeTarget(this)",";");
	setAttributeSafe($("billing_address1"),'onKeyUp',"changeTarget(this)",";");
	setAttributeSafe($("billing_address2"),'onKeyUp',"changeTarget(this)",";");
	setAttributeSafe($("billing_city"),'onKeyUp',"changeTarget(this)",";");
	setAttributeSafe($("billing_state"),'onchange',"changeTarget(this)",";");
	setAttributeSafe($("billing_zip"),'onKeyUp',"changeTarget(this)",";");
	setAttributeSafe($("billing_country"),'onchange',"changeTarget(this)",";");
}

function populateEndUserWithBilling() {
	$("eu_company").value 	= $("customer_company").value;
	$("eu_email").value		= $("customer_email").value;
	$("eu_name").value		= $("customer_name").value;
	$("eu_phone").value		= $("customer_phone").value;
	
	$("eu_address").value 	= $("billing_address1").value +" "+ $("billing_address2").value;
	$("eu_city").value 		= $("billing_city").value;
	$("eu_state").value 	= $("billing_state").value;
	$("eu_zip").value 		= $("billing_zip").value;
	
	$("eu_email").disable();		
	$("eu_name").disable();		
	$("eu_phone").disable();
	
	$("eu_address").disable(); 	
	$("eu_city").disable(); 		
	$("eu_state").disable(); 	
	$("eu_zip").disable(); 				
	
	setAttributeSafe($("customer_company"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_email"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_name"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_phone"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	
	setAttributeSafe($("billing_name"),"onKeyUp","changeTargetEndUser(this,'billing')",";");
	setAttributeSafe($("billing_address1"),"onKeyUp","changeTargetEndUser(this,'billing')",";");
	setAttributeSafe($("billing_address2"),"onKeyUp","changeTargetEndUser(this,'billing')",";");
	setAttributeSafe($("billing_city"),"onKeyUp","changeTargetEndUser(this,'billing')",";");
	setAttributeSafe($("billing_state"),"onchange","changeTargetEndUser(this,'billing')",";");
	setAttributeSafe($("billing_zip"),"onKeyUp","changeTargetEndUser(this,'billing')",";");
}

function populateEndUserWithShipping() {
	$("eu_company").value 	= $("customer_company").value;
	$("eu_email").value		= $("customer_email").value;
	$("eu_name").value		= $("customer_name").value;
	$("eu_phone").value		= $("customer_phone").value;
	
	$("eu_address").value 	= $("shipping_address1").value +" "+ $("shipping_address2").value;
	$("eu_city").value 		= $("shipping_city").value;
	$("eu_state").value 	= $("shipping_state").value;
	$("eu_zip").value 		= $("shipping_zip").value;
	
	$("eu_email").disable();		
	$("eu_name").disable();		
	$("eu_phone").disable();
	
	$("eu_address").disable(); 	
	$("eu_city").disable(); 		
	$("eu_state").disable(); 	
	$("eu_zip").disable(); 				
	
	setAttributeSafe($("customer_company"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_email"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_name"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	setAttributeSafe($("customer_phone"),"onKeyUp","changeTargetEndUser(this,'customer')",";");
	
	setAttributeSafe($("shipping_name"),"onKeyUp","changeTargetEndUser(this,'shipping')",";");
	setAttributeSafe($("shipping_address1"),"onKeyUp","changeTargetEndUser(this,'shipping')",";");
	setAttributeSafe($("shipping_address2"),"onKeyUp","changeTargetEndUser(this,'shipping')",";");
	setAttributeSafe($("shipping_city"),"onKeyUp","changeTargetEndUser(this,'shipping')",";");
	setAttributeSafe($("shipping_state"),"onchange","changeTargetEndUser(this,'shipping')",";");
	setAttributeSafe($("shipping_zip"),"onKeyUp","changeTargetEndUser(this,'shipping')",";");
}

function changeTarget(e){
	var name = e.id;
	var newname = name.replace("billing","shipping");
	$(newname).value = e.value;
}

function changeTargetEndUser(e,r){
	var name = e.id;
	var newname = name.replace(r,"eu");
	if(newname != 'eu_address1' && newname != 'eu_address2'){
		$(newname).value = e.value;
	}else if(newname == 'eu_address1'){
		$('eu_address').value = e.value+" "+$F(r+'_address2');
	}else if(newname == 'eu_address2'){
		$('eu_address').value = $F(r+'_address1')+" "+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('/ajax/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);
	
	h = document.body.parentNode.scrollHeight; 
	w = document.body.parentNode.scrollWidth; 
	$('graybox-window').style.top = (document.body.parentNode.scrollTop+200)+"px";
	$('graybox-window').style.left = ((document.body.clientWidth/2) - ($('graybox-window').getWidth()/2))+"px";
	$('graybox').style.width = w+"px";
	$('graybox').style.height = h+"px";
	changeOpac(0,'graybox');
	changeOpac(0,'graybox-window');
	
	var speed1 = 750;
	var speed2 = 1000;
	if (navigator.userAgent.indexOf("MSIE") != -1) {
		speed1 = 75;
		speed2 = 100;
	}
	
	opacity('graybox', 0, 75, speed1);
	opacity('graybox-window', 0, 100, speed2);

	if (navigator.userAgent.indexOf("MSIE 6") != -1) {
		var element_to_shim = $("graybox");
		iframeShim(element_to_shim, "popup");
	}
}

function closeGraybox() {
	var speed1 = 750;
	var speed2 = 1000;
	if (navigator.userAgent.indexOf("MSIE") != -1) {
		speed1 = 75;
		speed2 = 100;
	}
	
	opacity('graybox', 75, 0, speed1);
	opacity('graybox-window', 100, 0, speed2);
	if ($("iframeshimpopup").style.display == "block") {
		$("iframeshimpopup").style.display = "none";
	}

}
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	if(opacity == 0){
		$(id).style.display = "none";
	}
	if(opacity > 0){
		$(id).style.display = "block";
	}
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

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 validate_reviewed_cart()
{
	if(iferror == 0 && !processing)
	{
		processing = true;
		$('loading_box').style.display = 'block';
		
		/* Check for/process promo code if it is set */
		/*if ($F('promo_code') != '') {
			xGetPromoCodeSubmit($F('promo_code'));
		}*/
		
		var missing_text = "";
		valid_data = true;
		form_data = new CustomForm;
		var infobox_form = $('body').getElementsBySelector('form.process');
		
		if($("zipcode-error") != null){
			$("zipcode-error").innerHTML = "";
			$("zipcode-error").hide();	
		}
		
		var savedata = new Array();
		var cc_choice = $('cc_choice');
		//alert(cc_choice.value);
		
		if($('cart-total-pre') == null || (parseFloat($('cart-total-pre').innerHTML.replace(/[^0-9]/,"")) != 0 && $('cart-total-pre').innerHTML != 0)){
			
			if(cc_choice != null && cc_choice.value == 'new')
			{
				savedata.push($('card_name'));
				savedata.push($('card_number'));
				savedata.push($('card_cvv'));
				savedata.push($('card_exp_mo'));
				savedata.push($('card_exp_yr'));
				savedata.push($('card_type'));
			}
			else if(cc_choice != null && cc_choice.value != 'new')
			{		 
				var checked = $("card_choice");
						    
			    if(!checked)
			    {
			    	missing_text = "Credit Card";
			    	valid_data = false;
			    }
			    else
			    {
			    	savedata.push(checked);
			    	savedata.push(cc_choice);
			    }
			}
		}
		
		if($('password') != null){
			if($F('password') != ""){
				if($F('password') != $F('confirm_password')){
					$("zipcode-error").innerHTML = $("zipcode-error").innerHTML+"  Passwords Must Match";
					$("zipcode-error").show();
					$('password').setStyle({border:'solid 2px #d15c1e'});
					$('confirm_password').setStyle({border:'solid 2px #d15c1e'});
					valid_data = false;
				} else if($("zipcode-error").innerHTML == ""){
					$("zipcode-error").hide();					
				}
			}
		}
		if (valid_data) {
			if($('special_comments') != null){
				savedata.push($('special_comments'));
			}
			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();checkGiftCard();proStatus()" );
				valid_data = false;
			}else{
				form_data._SaveFormData(savedata);
			}
		}
		
		$("missing_field_text").innerHTML = '';
		
		if(!missing_text.empty()){
			$("missing_field_text").innerHTML = "The following fields are missing or invalid: " + missing_text;
			$("missing_fields").show();
		}else{
			$("missing_fields").hide();
		}
		
		var eu_missing_text = validateEndUserInfo();
		if(eu_missing_text != ''){
			valid_data = false;
			if($("missing_field_text").innerHTML == ''){
				$("missing_field_text").innerHTML = "The following fields are missing or invalid: " + eu_missing_text;
			}else{
				$("missing_field_text").innerHTML += ", " + eu_missing_text;
			}
			$("missing_fields").show();
			processing = false;
			$('loading_box').style.display = 'none';
		}else{
			saveEndUserInfo();
		}
		
		if (valid_data) {
			window.location = "//www.softwaremedia.com/cart/thankYou";
		}else{
				processing = false;
				$('loading_box').style.display = 'none';
		}
	}
}

function startCCAuth(m,e){
	if(e.keyCode >= 48 && e.keyCode <= 57){
		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++;

		});

		errors['len'] = 0
		errors['display_type'] = '';
		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(iferror !=  0){
			$('error_text').innerHTML += "Please Check the Card and Try Again.";
			$('error_fields').style.display = "block";
		}else{
			$('error_fields').style.display = "none";
		}
	}else{
		iferror = 0;
		$('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) {
		processing = true;
		$('loading_box').style.display = 'block';
	if(source_id == "submit-button"){
		/* Check for/process promo code if it is set */
		if ($F('promo_code') != '') {
			xGetPromoCodeSubmit($F('promo_code'));
		}
	}
	var missing_text = "";
	valid_data = true;
	form_data = new CustomForm;
	var infobox_form = $('body').getElementsBySelector('form.process');
	if($("zipcode-error") != null){
		$("zipcode-error").innerHTML = "";
		$("zipcode-error").hide();	
	}
	var savedata = new Array();
	if($('cart-total-pre') == null || (parseFloat($('cart-total-pre').innerHTML.replace(/[^0-9]/,"")) != 0 && $('cart-total-pre').innerHTML != 0)){
		cc_choice = $('cc_choice');
		$('customer_info').getElements().each(function (input_element) {
				input_element.setStyle({border:'solid 1px #CCC'});
				/* 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 = $("zipcode-error").innerHTML+" Billing Information :  "+details.error_text;
							$("zipcode-error").show();
					
							if (missing_text != "") {
								missing_text = missing_text + ", ";
							}
							missing_text = missing_text + $("billing_zip").readAttribute('alt_text');
							input_element.setStyle({border:'solid 2px #d15c1e'});
							valid_data = false;
						} else if($("zipcode-error").innerHTML == ""){
							$("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 = $("zipcode-error").innerHTML+" Shipping Information :  "+details.error_text;
							$("zipcode-error").show();
					
							if (missing_text != "") {
								missing_text = missing_text + ", ";
							}
							missing_text = missing_text + $("shipping_zip").readAttribute('alt_text');
							input_element.setStyle({border:'solid 2px #d15c1e'});
							valid_data = false;
						} else if($("zipcode-error").innerHTML == ""){
							$("zipcode-error").hide();					
						}
					}
					if(cc_choice != null && cc_choice.value == 'new')
					{
						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;
									showGraybox('cart/password',{email: input_element.value});
								}
							}
						}
					}
				}
				savedata.push(input_element);
			});
	}
	
	if(cc_choice != null && cc_choice.value != 'new')
	{
		if($('selected_cc').type && $('selected_cc').type.toLowerCase() == 'radio') {
	        var radioGroup = $('selected_cc').name;
	    } else if ($('selected_cc').tagName.toLowerCase() != 'form') {
	        //return false;
	    }
	 
	    var checked = $('selected_cc').getInputs('radio', 'cc_info').find(
	        function(re) {return re.checked;}
	    );
	    
	    if(!checked)
	    {
	    	missing_text = "Credit Card";
	    	valid_data = false;
	    }
	    else
	    {
	    	savedata.push(checked);
	    }
	}
	
	if($('password') != null){
		if($F('password') != ""){
			if($F('password') != $F('confirm_password')){
				$("zipcode-error").innerHTML = $("zipcode-error").innerHTML+"  Passwords Must Match";
				$("zipcode-error").show();
				$('password').setStyle({border:'solid 2px #d15c1e'});
				$('confirm_password').setStyle({border:'solid 2px #d15c1e'});
				valid_data = false;
			} else if($("zipcode-error").innerHTML == ""){
				$("zipcode-error").hide();					
			}
		}
	}
	if (valid_data) {
		if(source_id == "submit-button"){
			if($('special_comments') != null){
				savedata.push($('special_comments'));
			}
			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();checkGiftCard();proStatus()" );
				valid_data = false;
			}else{
				form_data._SaveFormData(savedata);
			}
		}else{
			form_data._SaveFormData(savedata);
		}
	}
	
	$("missing_field_text").innerHTML = '';
	
	if(!missing_text.empty()){
		$("missing_field_text").innerHTML = "The following fields are missing or invalid: " + missing_text;
		$("missing_fields").show();
	}else{
		$("missing_fields").hide();
	}
	
	var eu_missing_text = validateEndUserInfo();
	if(eu_missing_text != ''){
		valid_data = false;
		if($("missing_field_text").innerHTML == ''){
			$("missing_field_text").innerHTML = "The following fields are missing or invalid: " + eu_missing_text;
		}else{
			$("missing_field_text").innerHTML += ", " + eu_missing_text;
		}
		$("missing_fields").show();
		processing = false;
		$('loading_box').style.display = 'none';
	}else{
		saveEndUserInfo();
	}
	
	if (valid_data) {
		window.location = $(source_id).readAttribute('destination');
	}else{
			processing = false;
			$('loading_box').style.display = 'none';
	}
}
function informationValidation2(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();checkGiftCard();proStatus()" );
						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(){
	$('loading_box').style.display = 'block';
	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); 
		}
	});

}

/**
 * Check Gift Card Values
 */
function checkGiftCard() {
	fillCartCCObj();
	if(iferror == 0){
		$('loading_box').style.display = 'block';
		cart = new Cart
		cart._GetCartInfo2();
		var k =cart_totals.total0+""+cart_totals.total1;
		var j =cart_totals.subtotal0+""+cart_totals.subtotal1;
		var l =cart_totals.shipping0+""+cart_totals.shipping1;

		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, cart_subtotal: j, cart_shipping: l},
			onComplete: function (transport) {
				if(transport.responseText == 'Invalid Campagin') {
					alert('You cannot use promotional gift cards to purchase a gift card');
				}
				else if(transport.responseText == 'Duplicate') {
					alert('You cannot use more than one gift card on a purchase');
				}
				else if(transport.responseText == 'Not Users')
				{
					alert('Gift Card is not assigned to your account');
				}
				else if(transport.responseText == 'Invalid'){
					alert('Gift Card is either Invalid or has a $0 balance. If you have any questions please call customer service at: 1-800-474-1045');
				}else if(transport.responseText == 'Zero'){
					alert('May not use another gift card, order total is zero.');
				}else{
					ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
					$('gift_card_number').value = "";
					$('gift_card_cvv').value = "";
				}
			}
		});
		
		$('loading_box').style.display = 'none';
	}
}

function removeGiftCard(id){
	$('loading_box').style.display = 'block';
	new Ajax.Request("/cart/removeGiftCard", {
		asynchronous: false,
		method: "post",
		parameters: {gift_card_id: id},
		onComplete: function (transport) {
			ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
		}
	});
}

function proStatus(){
	closeGraybox();
}
function setButtonPro(e,n){
	if(n){
		e.removeClassName('submit-button-gray');
	}else{
		e.addClassName('submit-button-gray');
	}
}
function processPromoSelection(form,group_name) {
	item_data = $RF(form,group_name).evalJSON();
	var cart = new Cart;
	cart._GetPromoInfo();
	cart_data = cart._responseText.evalJSON();
	var process = true;
	if (!cart_data.promotion_info.empty) {
		if (cart_data.cart_items.length > 0) {
			cart_data.cart_items.each(
			function(item) {
				cart_data.promotion_info.option_list.each(
				function (promo_item) {
					if (item.item_id == promo_item && item.quantity >= cart_data.promotion_info.limit_customer && cart_data.promotion_info.limit_customer > 0) {
						xRemoveFromCart(item.item_id, 'review_and_pay');
					}
				}
				);
			});
		}
	}
	cart._AddToCart(item_data.id, item_data.data);
//	alert(cart._responseText);
	ajaxUpdateMyCart('/ajax/refreshReviewAndPay');
}
function addToCartWhenEnterIsPressedInQtyInputBoxOnProductPages(event, item_id, data) {
	var keypressed;
	if (window.event) {
		keypressed = event.keyCode;
	} else if (event.which) {
		keypressed = event.which;		
	} else {
		keypressed = "unknown";
	}

	if (keypressed == 13) {
		xAddToCart(item_id, data);
	} else {
		return false;
	}
}

function create_credit_card(element)
{
	var choice = jQuery('#card_choice option:selected').val();
	createCookiePro('creditCardChoice', choice, 7);

	if(choice == 'new')
	{
		jQuery('#add-new-payment').show();
		jQuery('#cc_choice').val('new');
	}
	else
	{
		jQuery('#add-new-payment').hide();
		jQuery('#cc_choice').val('old');
	}
}

function createCookiePro(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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