
function shipping_methods_returned(obj) {
	shipping_graphic = document.getElementById('loading_graphic');
	
	options = eval('('+obj.responseText+')');
	mydiv = obj.argument;
	mydiv.innerHTML= options.html;

	search = options.html;
	if(search) {
		while( script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i)) {
			search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);

			if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break;

			block = search.substr(0, search.indexOf(RegExp.$1));
			search = search.substring(block.length + RegExp.$1.length);

			eval(block);
		}
	}

	mydiv.style.display='block';
	shipping_graphic.style.display='none';
}

function shipping_methods_failure(obj) {
	if (times_tried < 3) {
		var version = 0;
		if (navigator.appVersion.indexOf('MSIE') != -1) {
			var temp = navigator.appVersion.split('MSIE');
			version = parseFloat(temp[1]);
		}
		if (version == 6.0) {
			times_tried++;
			calculate_shipping(this);
		}
	}
   // error, no options returned
   error_message = document.createElement('div');
   error_message.id = 'shipping_error_message';
   error_message.innerHTML = "No shipping options found, please enter a valid shipping address.";
   mydiv = obj.argument;
   container = mydiv;
   container.innerHTML = '';
   container.appendChild(error_message);
   mydiv.style.display='none';
}

function calculate_shipping(e, arg) {
	if (e.type == 'keypress' && e.keyCode != 13) {
		return true;
	}

	if (e && e.preventDefault) {
		e.preventDefault();
	}

	var shipping_methods_target_form_element = document.getElementById('shipping_methods');
	var spinner_graphic = document.getElementById('loading_graphic');
	var my_location = {
		'city': document.getElementById('shipping_address_ship_city').value,
		'state': document.getElementById('shipping_address_ship_state').value,
		'zip': document.getElementById('shipping_address_ship_zip').value ,
		'country': document.getElementById('shipping_address_ship_country').value 
	};
	var xhr_callback = {
		success:shipping_methods_returned,
		failure:shipping_methods_failure,
		argument:shipping_methods_target_form_element
	}

	error = document.getElementById('shipping_error_message');
	if (error) {
		error.style.display='none';
	}
	spinner_graphic.style.display='block';
	shipping_methods_target_form_element.style.display='none';
	YAHOO.util.Connect.asyncRequest('POST', 'ajax_targets/get_shipping_methods.php', xhr_callback, 'city='+my_location['city']+'&state='+my_location['state']+'&zip='+my_location['zip']+'&country='+my_location['country']+'&shipping_calculator=true&product_id='+arg);

	return false;

}

function set_coupon_code(e, form) {
	if (e.type == 'keypress' && e.keyCode != 13) {
		return true;
	}
	if (e && e.preventDefault) {
		e.preventDefault();
	}

	form.hidden_action.value = 'enter_coupon';
	form.submit();
	return false;
}

function update_quantities(e, form) {
	if (e.type == 'keypress' && e.keyCode != 13) {
		return true;
	}
	if (e && e.preventDefault) {
		e.preventDefault();
	}

	document.getElementById('hidden_action').value = 'update_quantities';
	form.submit();
	return false;
}

function register_events() {
	/** send the product id, if it exists **/
	var product_id = 0;
	if (document.getElementById('hidden_product_id')) { 
		product_id = document.getElementById('hidden_product_id').value;
	}
	YAHOO.util.Event.addListener("calculate_link", "click", calculate_shipping, product_id);
	YAHOO.util.Event.addListener("shipping_address_ship_city", "keypress", calculate_shipping, product_id);
	YAHOO.util.Event.addListener("shipping_address_ship_zip", "keypress", calculate_shipping, product_id);
	YAHOO.util.Event.addListener("coupon_code", "keypress", set_coupon_code);
}

function expand_search_criteria(criteria) {
	if (document.getElementById(criteria + '_more_checkboxes')){
		document.getElementById(criteria + '_more_checkboxes').style.display = 'none';
		document.getElementById(criteria + '_hidden_checkboxes').style.display = 'block';
	}else
	if (document.getElementById(criteria + '_more_anchors')){
		document.getElementById(criteria + '_more_anchors').style.display = 'none';
		document.getElementById(criteria + '_hidden_anchors').style.display = 'block';
	}
	return false;
}

function update_hidden_action(obj, id, value) {
	var this_form = obj.form;
	for (var i = 0; i < this_form.elements.length; i++) {
		if (this_form.elements[i].id == id) {
			this_form.elements[i].value = value;
			break;
		}
	}
}

function update_order_item_fields() {
	var inputs = [];
	$('.order_item_update_field').each(function() {
		inputs.push(escape(this.name) + '=' + escape(this.value));
	});
	$.ajax({
		type: 'POST',
		data: inputs.join('&'),
		url: 'ajax_targets/update_order_items.php'
	});
}

function open_printer_window() {
	$(document).ready(function() {
		setTimeout("window.print()",1000);
	});
}

$(document).ready(function() {
	$('.order_item_update_field').change(function() {
		update_order_item_fields();
	});
});

// wait until everything is loaded in the page, before registering callbacks.
YAHOO.util.Event.onContentReady("calculate_link", register_events);

var times_tried = 0;

// #26593 Loyalty program - STARTS
var toggleDisplay = function(id){
	var status = $('#'+id).css("display");
	if(status == 'none'){
			$('#'+id).slideDown(400);
	}else{
			$('#'+id).slideUp(300);
	}
}

var apply_coupon_code = function () {
	var sUrl = "ajax_targets/apply_coupon_code.php";

	var args = "coupon_code="+$('[name=coupon_code]').val();
	var callback_coupon = {
		success: function(o) {
			var restxt = o.responseText;
			var prod = eval('('+restxt+')');

			if (prod.retvalue==1){
				$('#coupon_code_success_message').css('display', 'block');
				$('#coupon_code_error_message').css('display', 'none');
				shipping_target_change();
				update_order_summary();
			}
			else{
				$('#coupon_code_error_message').css('display', 'block');
				$('#coupon_code_success_message').css('display', 'none');
			}
		},
		failure: function(o){
			alert("Action failed. Please Try again.");
		}
	}
	var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback_coupon, args);	
	return false;	
}

var apply_rewards = function (form) {
	var sUrl = "ajax_targets/apply_rewards.php";

	var elem = form.elements;
	var flength = elem.length;
	var i;
	var buff = '';
	for (i=0; i < flength; i++)
	{
		if (elem[i].type == 'checkbox' && elem[i].name.indexOf('chkreward') != -1 && elem[i].checked == true) 
		{
			buff = buff + elem[i].value + '|';
		}
	}
	
	var args = "rewards="+buff;

	var callback_rewards = {
		success: function(o) {
			var restxt = o.responseText;
			if (restxt != '')
			{
				var prod = eval('('+restxt+')');
				if (prod.retvalue==1){
					update_order_summary();
				}
			}
		},
		failure: function(o){
			alert("Action failed. Please Try again.");
		}
	}
	var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback_rewards, args);
	return false;
}

var switch_billing_loyalty = function() {
	if (document.getElementById('create_account').checked) {
		if (document.getElementById('default_loyalty_signup').value == 'false') 	{
			document.getElementById('do_loyalty_signup').checked = false;
		}
		else {
			document.getElementById('do_loyalty_signup').checked = true;
		}
		document.getElementById('do_loyalty_signup').disabled = false;
	}
	else {
		document.getElementById('do_loyalty_signup').checked = false;
		document.getElementById('do_loyalty_signup').disabled = true;
	}
}

$("input[name=create_account]").click(function() {
	switch_billing_loyalty();
});
// #26593 Loyalty program - ENDS


function update_payment_plan(handle)
{
	var index = handle.id; 
	index = index.replace("payment_method_", ""); 
	
	if ( handle.value == 1 && ($("#pp_limit_"+index).val() < $("input[name='quantity["+index+"]']").attr('defaultValue')) )
	{
		alert($('#message').val());
		return false;
	}
	else {
		// Call update payment plan ajax
		var base = $('base').attr('href');
		var sUrl = base+"ajax_targets/update_payment_plan.php";
		var args = "index="+index;
		args += "&pp_option="+handle.value;

		var callback_shoppingcart = {
			success: function(o) {
				var restxt = o.responseText;
				if (restxt != '')
				{
					var prod = eval('('+restxt+')');
					if (prod.retvalue==1) {
						$('#order_subtotal').html(prod.sub_total);
						$('#order_item_price_'+index).html(prod.order_item_price);
						$('#order_item_total_price_'+index).html(prod.order_item_total_price);
						$('#payments_order_subtotal').html(prod.payments_sub_total);
						$('#order_item_payments_price_'+index).html(prod.order_item_payments_price);
						$('#order_item_payments_total_price_'+index).html(prod.order_item_payments_total_price);
						if (prod.you_saved != "$0.00") { 
							$('#order_item_promo_info_'+index).css('display', 'inline');
							$('#order_item_promo_info_'+index).html('<br/><span class="you_saved_text">(You saved:</span><span class="you_saved_price"> '+prod.you_saved+'</span><span class="you_saved_text">)</span>');
						}
						else { 
							$('#order_item_promo_info_'+index).css('display', 'none');
						}
					}
				}
			},
			failure: function(o){
				alert("Action failed. Please Try again.");
			}
		}
		var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback_shoppingcart, args);
		return true;		
	}
}
