function update_shipping_method(button,shipping_method_id,shipping_method_price) {
	var xhr_callback = { 
		success:update_shipping_method_success,
		failure:update_shipping_method_failure,
		argument:button
	}   

	YAHOO.util.Connect.asyncRequest('POST', 'ajax_targets/update_shipping_method.php', xhr_callback,'shipping_method_id='+shipping_method_id+'&shipping_method_price='+shipping_method_price);
}

function update_shipping_method_success(button){
	var shipping_error = document.getElementById('shipping_method_error');
	if(shipping_error){
		shipping_error.style.display = 'none';
	}
	$(button.argument).attr("checked","checked");

}

function update_shipping_method_failure(button){
	var shipping_error = document.getElementById('shipping_error');
	if(shipping_error){
		shipping_error.style.display = 'block';
	}   
}

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

	var 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 tnt_returned(obj) {
	tnt_graphic = document.getElementById('tnt_loading_graphic');
	options = eval('('+obj.responseText+')');
	mydiv = obj.argument;
	mydiv.innerHTML= options.html;
	mydiv.style.display='block';
	tnt_graphic.style.display='none';
} 

function tnt_failure(obj) {
	document.write('Failed');
}

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

	if (e && e.preventDefault) {
		e.preventDefault();
	}
	var tnt_target_form_element = document.getElementById('service_types');
	
	var spinner_graphic = document.getElementById('tnt_loading_graphic');
	var my_location = {
		'city': document.getElementById('tnt_destination_city').value,
		'state': document.getElementById('tnt_destination_state').value,
		'zip': document.getElementById('tnt_destination_zip').value,
		'service_type_header': document.getElementById('service_type_header').value,
		'service_type_footer': document.getElementById('service_type_footer').value,
		'service_type_row': document.getElementById('service_type_row').value,
		'no_guarantee_text': document.getElementById('no_guarantee').value
	};
	var xhr_callback = {
		success:tnt_returned,
		failure:tnt_failure,
		argument:tnt_target_form_element
	}
	
	spinner_graphic.style.display='block';
	tnt_target_form_element.style.display='none';
	YAHOO.util.Connect.asyncRequest('POST', 'ajax_targets/time_in_transit.php', xhr_callback, 'city='+my_location['city']+'&state='+my_location['state']+'&zip='+my_location['zip']+'&country=US&ajax_response=true&product_id='+arg+'&service_type_header='+my_location['service_type_header']+'&service_type_footer='+my_location['service_type_footer']+'&service_type_row='+my_location['service_type_row']+'&no_guarantee_text='+my_location['no_guarantee_text']);

	return false;
		
}





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

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

	var config_string = '';
	var error = false;
	$('.product_configuration_popup_menu').each ( function(index)  { 
		var config_name = $(this).attr('name')
		if ($(this).val() == 'none') { 
			var test = config_name.replace(/.*\[(.*)\]/, "$1")
			alert("Please choose a "+test);
			error = true;
		}
		config_string += "&"
		config_string +=  $(this).attr('name')
		config_string += "="
		config_string += $(this).val()
	})
	if (error) return false;




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

	var tag_name = '';
	if (typeof shipping_options_tag_name != 'undefined') { 
		tag_name = shipping_options_tag_name;
	}


	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, 'shipping_calculator=true&tagname='+tag_name+'&city='+my_location['city']+'&state='+my_location['state']+'&zip='+my_location['zip']+'&country='+my_location['country']);

	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);
	YAHOO.util.Event.addListener("tnt_search", "click", calculate_tnt, product_id);
}


function register_tnt_event(){
	var product_id = 0;
	if (document.getElementById('hidden_product_id')) { 
		product_id = document.getElementById('hidden_product_id').value;
	}
	YAHOO.util.Event.addListener("tnt_search", "click", calculate_tnt, product_id);
}

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;
	if (this_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);
YAHOO.util.Event.onContentReady("tnt_search", register_tnt_event);

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();
				billing_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_", ""); 
 	// 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.message != undefined) { 
 					alert(prod.message);
 				}
 				if (prod.retvalue!=0) {
 					$('.checkout_button').unbind('click');
 					$(handle).val(prod.retvalue);
 					$('#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');
 					}
 				}
 				if (prod.retvalue == 0) { 
 					$('.checkout_button').click(function(e) { 
 						alert(prod.message);
 						return false;
 					});
 				}
 			}
 		},
 		failure: function(o){
 			alert("Action failed. Please Try again.");
 		}
 	}
 	var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback_shoppingcart, args);
 	return true;		
}

