/** 
 *	Augmented WP-E-Commerce JS stuff
 *
*/
//full version and license can be found here: http://plugins.jquery.com/files/jquery.inlineFieldLabel.js.txt
(function($){$.fn.inlineFieldLabel=function(options){var opts=$.extend({},$.fn.inlineFieldLabel.defaults,options);this.each(function(){$this=$(this);var o=$.metadata?$.extend({},opts,$this.metadata({type:opts.metadataType,name:opts.metadataName})):opts;innerFunction($this,o.label);});return this;};$.fn.inlineFieldLabel.defaults={label:'some placeholder',metadataType:'class',metadataName:'metadata'};function innerFunction(jqElement,fieldLabel){var textInput=null;var clonedTextInput=null;var strBefore="";var strAfter="";var counter=0;textInput=jqElement;if(textInput.attr('type')=='password'){clonedTextInput=textInput.clone();strBefore=clonedTextInput.append(textInput.clone()).html();strAfter=strBefore.replace('type="password"','type="text"');;strAfter.replace('type="password"','type="text"');textInput.after(strAfter);clonedTextInput=textInput.next();clonedTextInput.addClass("intra-field-label").val(fieldLabel);textInput.hide();}else{textInput.addClass("intra-field-label").val(fieldLabel);}
if(clonedTextInput!=null){clonedTextInput.focus(function(){textInput.show();textInput.trigger('focus');clonedTextInput.hide();});}
textInput.focus(function()
{if(this.value==fieldLabel)
{textInput.removeClass("intra-field-label").val("");};});textInput.blur(function()
{if(this.value=="")
{if(clonedTextInput!=null){textInput.hide();clonedTextInput.show();}
else{textInput.addClass("intra-field-label").val(fieldLabel);}};});textInput.parents('form:first').find('input[type="submit"]').click(function(){if(clonedTextInput!=null){textInput.show();clonedTextInput.remove();}
if(textInput.val()==fieldLabel)
{textInput.removeClass("intra-field-label").val("");};});}})(jQuery);
function ajax_item(e){if(typeof e=='string')e=document.getElementById(e);return e};
function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};
/* ********************************************* */
/* See /w/wp-content/plugins/wp-e-commerce/wpsc-core/js/ajax.js for license */
ajax={};
ajax.x=function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}};
ajax.serialize=function(f){
  var g=function(n){return f.getElementsByTagName(n)};
  var nv=function(e){if(e.name){return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);}else{return '';}};
  var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');
};  
ajax.send=function(u,f,m,a){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText)};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a)};
ajax.get=function(url,func){ajax.send(url,func,'GET')};
ajax.gets=function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText};
ajax.post=function(url,func,args){ajax.send(url,func,'POST',args)};
ajax.update=function(url,elm){var e=ajax_item(elm);var f=function(r){e.innerHTML=r};ajax.get(url,f)};
ajax.submit=function(url,elm,frm){var e=ajax_item(elm);var f=function(r){e.innerHTML=r};ajax.post(url,f,ajax.serialize(frm))};
/* ********************************************* */
function wpsc_shipping_same_as_billing(){
	jQuery('#shippingsameasbillingmessage').slideDown('slow');
	jQuery("input[title='billingfirstname'], input[title='billinglastname'], textarea[title='billingaddress'], input[title='billingcity'], input[title='billingpostcode'], input[title='billingphone'], input[title='billingfirstname'], input[title='billingstate']").unbind('change', wpsc_shipping_same_as_billing).unbind('keyup', wpsc_shipping_same_as_billing).keyup(wpsc_shipping_same_as_billing).change(wpsc_shipping_same_as_billing);
	
	jQuery("select[title='billingregion'], select[title='billingstate'], select[title='billingcountry'], input[title='billingstate']").die( 'change', wpsc_shipping_same_as_billing ).live( 'change', wpsc_shipping_same_as_billing );
	
	var fields = new Array(
		Array("input[title='billingfirstname']","input[title='shippingfirstname']"),
		Array("input[title='billinglastname']","input[title='shippinglastname']"), 
		Array("textarea[title='billingaddress']","textarea[title='shippingaddress']"), 
		Array("input[title='billingcity']","input[title='shippingcity']"), 
		Array("input[title='billingpostcode']","input[title='shippingpostcode']"), 
		Array("input[title='billingphone']","input[title='shippingphone']"), 
		Array("input[title='billingemail']","input[title='shippingemail']")
	);
	
	for(var i in fields) {
		jQuery(fields[i][1]).val(jQuery(fields[i][0]).val());
		jQuery(fields[i][1]).parents('tr:first').hide();
		if(!jQuery(fields[i][0]).hasClass('intra-field-label'))
			jQuery(fields[i][1]).removeClass('intra-field-label');
		else
			jQuery(fields[i][1]).addClass('intra-field-label');
	}
	
	if( jQuery("input[title='billingstate']").length ){
		jQuery("input[title='shippingstate']").val(jQuery("input[title='billingstate']").val());
		jQuery("input[title='shippingstate']").parents('tr:first').hide();
		if(!jQuery("input[title='billingstate']").hasClass('intra-field-label'))
			jQuery("input[title='shippingstate']").removeClass('intra-field-label');
		else
			jQuery("input[title='shippingstate']").addClass('intra-field-label');
	} else {
		jQuery("input[title='shippingstate']").val(jQuery("select[title='billingstate']").val());
		jQuery(".shipping_region_name").text(jQuery("select[title='billingstate'] option[selected='selected']").text());
		jQuery("input[title='shippingstate']").parents('tr:first').hide();
	}
	
	
	jQuery("input.shipping_country").val(
		jQuery("select[title='billingcountry']").val()
	).removeClass('intra-field-label').parents('tr:first').hide();
	
	jQuery("span.shipping_country_name").html(
		jQuery("select[title='billingcountry'] :selected").text()
	).hide();
	
	jQuery('select[title="shippingcountry"] option').removeAttr('selected').parents('tr:first').hide();
	jQuery('select[title="shippingcountry"] option[value="' + jQuery('select[title="billingcountry"] option:selected').val() + '"]').attr('selected', 'selected');
			
	jQuery('select[title="shippingstate"] option').removeAttr('selected').parents('tr:first').hide();
	jQuery('select[title="shippingstate"] option[value="' + jQuery('select[title="billingstate"] option:selected').val() + '"]').attr('selected', 'selected');

	jQuery('select[title="shippingcountry"]').change();
	jQuery('select[title="shippingstate"]').change();
	
	//evil. If shipping is enabled checks if shipping country is the same and billing and if shipping state is the same as billing. If not - changes shipping country and (or) state to billing.
	if( 
		//if shipping is enabled this element will be present, so if it's not, then it will skip everything
		jQuery('#change_country #current_country').val() 
		&&
		//also we only need to do this when shipping country is different than billing country. following code does the check
		(
			//check if countries are different
			(
				//if billing country dropdown is present
				jQuery('select[title="billingcountry"]')
				&&
				//and if the value is different from shipping
				jQuery('#change_country #current_country').val() != jQuery('select[title="billingcountry"]').val()
			) 
			||
			//ceck if billing region is different
			(
				//if billing region is present
				jQuery('select[title="billingstate"]')
				&&
				//if its different from shipping
				jQuery('select[title="billingstate"]').val() != jQuery('#change_country #region').val()
			)
		) 
	){
		jQuery('#current_country option').removeAttr('selected');
		jQuery('#current_country option[value="'+jQuery('select[title="billingcountry"]').val()+'"]').attr('selected', 'selected');
		jQuery('#region').remove();
		if(jQuery('select[title="billingstate"]').html()){
			jQuery('#change_country #current_country').after('<select name="region" id="region" onchange="submit_change_country();">'+jQuery('select[title="billingstate"]').html()+'</select>')
			jQuery('#region option').removeAttr('selected');
			jQuery('#region option[value='+jQuery('select[title="billingstate"]').val()+']').attr('selected', 'selected');
		}
		var request_vars = {'country' : jQuery('#current_country').val(), 'wpsc_ajax_actions' : 'update_location', 'wpsc_update_location' : true, 'wpsc_submit_zipcode' : 'Calculate' };
		if(jQuery('#region'))
			request_vars.region = jQuery('#region').val();
		if(typeof(updated_shipping_quote_after)=='undefined')
			updated_shipping_quote_after = false;
		jQuery.post( 
			location.href,
			request_vars,
			function(){
				if(!updated_shipping_quote_after){
					jQuery('select[title="billingcountry"]').change();
					updated_shipping_quote_after = false;
				} else
					updated_shipping_quote_after = false;
			}
		);
	}
}
// this function is for binding actions to events and rebinding them after they are replaced by AJAX
// these functions are bound to events on elements when the page is fully loaded.
jQuery(document).ready(function () {
		
	//this bit of code runs on the checkout page. If the checkbox is selected it copies the valus in the billing country and puts it in the shipping country form fields. 23.07.09
	if(jQuery("#shippingSameBilling").is(":checked"))
		wpsc_shipping_same_as_billing();
		
	jQuery("#shippingSameBilling").change(function(){
		if(jQuery(this).is(":checked")){
			var data = {
				action: 'wpsc_shipping_same_as_billing',
				wpsc_shipping_same_as_billing: true
			};
		
			jQuery.post("/w/wp-admin/admin-ajax.php", data, function(response) {
			});
			wpsc_shipping_same_as_billing();
		} else {
			var data = {
				action: 'wpsc_shipping_same_as_billing',
				wpsc_shipping_same_as_billing: false
			};
			jQuery.post("/w/wp-admin/admin-ajax.php", data, function(response) {
			});
			jQuery(this).parents('table:first').find('tr').show();
			jQuery('.shipping_country_name').show();
			jQuery('#shippingsameasbillingmessage').hide();
			jQuery("select[title='billingregion'], select[title='billingstate'], select[title='billingcountry'], input[title='billingstate']").die( 'change', wpsc_shipping_same_as_billing );
			jQuery("input[title='billingfirstname'], input[title='billinglastname'], textarea[title='billingaddress'], input[title='billingcity'], input[title='billingpostcode'], input[title='billingphone'], input[title='billingfirstname'], input[title='billingstate']").unbind('change', wpsc_shipping_same_as_billing).unbind('keyup', wpsc_shipping_same_as_billing);
		}
	});

	//Shipping bug fix by James Collins
	var radios = jQuery(".productcart input:radio[name='shipping_method']");
	if (radios.length == 1) {
		// If there is only 1 shipping quote available during checkout, automatically select it
		jQuery(radios).click();
	} else if (radios.length > 1) {
		// There are multiple shipping quotes, simulate a click on the checked one
		jQuery(".productcart input:radio[name='shipping_method']:checked").click();
	}
});

// update the totals when shipping methods are changed.
function switchmethod(key,key1){
	// 	total=document.getElementById("shopping_cart_total_price").value;
	form_values = "ajax=true&";
	form_values += "wpsc_ajax_action=update_shipping_price&";
	form_values += "key1="+key1+"&";
	form_values += "key="+key;
	jQuery.post( 'index.php', form_values, function(returned_data) {
		eval(returned_data);
	});
}

// submit the country forms.
function submit_change_country(){
	document.forms.change_country.submit();
}

function set_billing_country(html_form_id, form_id){
	var billing_region = '';
	country = jQuery(("div#"+html_form_id+" select[class='current_country']")).val();
	region = jQuery(("div#"+html_form_id+" select[class='current_region']")).val();
	if(/[\d]{1,}/.test(region)) {
		billing_region = "&billing_region="+region;
	}

	form_values = "wpsc_ajax_action=change_tax&form_id="+form_id+"&billing_country="+country+billing_region;
	jQuery.post( 'index.php', form_values, function(returned_data) {
		eval(returned_data);
		if(jQuery("#shippingSameBilling").is(':checked')){
			jQuery('.shipping_region').parent().parent().hide();
			jQuery('.shipping_country_name').parent().parent().hide();
		}
	});
}
function set_shipping_country(html_form_id, form_id){
	var shipping_region = '';
	country = jQuery(("div#"+html_form_id+" select[class='current_country']")).val();
	if(country == 'undefined'){
		country =  jQuery("select[title='billingcountry']").val();
	}
	region = jQuery(("div#"+html_form_id+" select[class='current_region']")).val();
	if(/[\d]{1,}/.test(region)) {
		shipping_region = "&shipping_region="+region;
	}
	form_values = {
		wpsc_ajax_action: "change_tax",
		form_id: form_id,
		shipping_country: country,
		shipping_region: region
	}
	jQuery.post( 'index.php', form_values, function(returned_data) {
		eval(returned_data);
		if(jQuery("#shippingSameBilling").is(':checked')){
			jQuery('.shipping_region').parent().parent().hide();
			jQuery('.shipping_country_name').parent().parent().hide();
		}
	});
}
jQuery(document).ready(function(){
	jQuery('.wpsc_checkout_table input, .wpsc_checkout_table textarea').each(function(){
		var real_value = jQuery(this).val();
		value = jQuery('label[for="'+jQuery(this).attr('id')+'"]').html();
		if(null != value){
			value = value.replace(/<span class="?asterix"?>\*<\/span>/i,'');
		}
		jQuery(this).inlineFieldLabel({label:jQuery.trim(value)});
		if(real_value != '')
			jQuery(this).val(real_value).removeClass('intra-field-label');
	});
});
