var vat_rate	= 0.2;

$(document).ready(function(){
	// Colorbox Help
	$(".help").colorbox({innerWidth:"600", innerHeight:"400", iframe:true});

	// Toggle Register/Login
	$('.login-toggle').each(function(){
		$('.login-method:first').slideUp().find(':input').attr({disabled:'disabled'});
	}).click(function(){
		if (!$(this).next('.login-method').is(':visible')) {
			$('.login-method:visible').slideUp().find(':input').attr({disabled:'disabled'});
			$(this).next('.login-method').slideDown().find(':input').removeAttr('disabled');
		}
	});
	
	// Change up/down arrow on toggle Register/Login
	$('#existing_customer').click(function() {
		$(this).css("background-image","url(images/arrow_down.gif)");
		$('#new_customer').css("background-image","url(images/arrow_up.gif)");
	});
	$('#new_customer').click(function() {
		$(this).css("background-image","url(images/arrow_down.gif)");
		$('#existing_customer').css("background-image","url(images/arrow_up.gif)");
	});
	
	// Toggle payment method
	$('#paybypaypal').click(function() {
		$('#card_form:visible').slideUp();
	});
	$('#paybybt').click(function() {
		$('#card_form:visible').slideUp();
	});
	$('#paybycard').click(function() {
		$('#card_form:hidden').slideDown();
	});
	
    // Form validation
	$("#validate_form,#checkout").validate();
	
	// stripe lists
	$(".list tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
   	$(".list tr:odd").addClass('alt');
   	// show issue number/date if card suits
   	//if($("#card_select").val()=="Maestro"||$("#card_select").val()=="Solo") {
   	//	$('#issue_fields:hidden').slideDown();
   	//}
   	// Slide up card form if PayPal is selected from post vars
   	if($("#paybypaypal:checked").val()=="paypal") {
   		$('#card_form:visible').slideUp();
   	}
	
	$('#card_type').change( function() {
		if($(this).val()=="Maestro"||$(this).val()=="Solo"){
			$('#issue_fields:hidden').slideDown();
		} else {
			$('#issue_fields:visible').slideUp(); 
		}
	});
	
	/*
	* Even if you mess about with this, we'll still charge you the correct price.
	* The javascript is purely for display purposes, all the logic is done serverside
	* nice try, but no free software for you!
	*/
	
	var subtotal	= 0*0;
	var taxtotal	= 0*0;
	
	var discount	= false;
	var valid_vat	= false;
		
	$('#vat_no').blur(function(){
		/* Check for a valid VAT number */
		valid_vat	= false;
		var value	= $(this).val();
		var string	= value.replace(/[^A-Z0-9\+\*\.]+/gi, '');
		if (string != '') {
			var country_code = string.substr(0,2);
			var vat_number = string.substr(2);
			var selected_country_code = $('#country').val();
			
			// exceptions!
			if(selected_country_code == 'GR') {
				selected_country_code = 'EL';
			}
			
			if (country_code == selected_country_code) {
				$.get(site_url+'order/checkvat/'+country_code+'/'+vat_number, {}, function(data){
					if (data == 1) {
						valid_vat = true;
						$('.calc:first').change();
						alert('Thank you, your VAT number \'' + vat_number + '\' is valid and no tax will be charged.');
					} else if(country_code=='GB') {
						valid_vat = false;
						$('#vat_no').val('');
						alert('Sorry but under HMRC rules we are obliged to charge tax to British VAT registered companies.');
					} else {
						valid_vat = false;
						$('#vat_no').val('');
						alert('Sorry but that VAT number is not recognised.');
					}
				}, 'text');
			} else {
				valid_vat = false;
				$('#vat_no').val('');
				alert('The VAT number entered does not match your invoice country.');
			}
		} else {
			calculatecost();
		}
	});
	
	$('#code').blur(function(){
		discount	= false;
		var code	= $(this).val();
		if (code != '') {
			$.get(site_url+'order/discount/'+code+'/'+subtotal, {}, function(data){
				if (data == '0') {
					$('#code').val('');
					alert('Invalid discount code');
				} else {
					discount	= data;
					$('.calc:first').change();
					alert('Discount code \'' + code + '\' has been accepted.');
				}
			}, 'json');
		} else {
			calculatecost();
		}
	});
	
	$('.upgrade_checkbox').click(function() {
		if($(this).val()=='1') {
			$(this).val('0');
		} else {
			$(this).val('1');
		}
		calculatecost();
	});
	
	$('.calc').change(function(){
		calculatecost();
	});
	
	var calculatecost = function() {
		subtotal	= 0;
		$('.calc.quantity').each(function(){
			var value	= $(this).val();
			value	= value.replace(/\D/ig, '');
			if (value == '') value = 0;
			if ($(this).attr('maxlength') > 0) {
				var max	= $(this).attr('maxlength');
				if (value > max) {
					value	= max;
				}
			}
			var rel		= $(this).attr('rel');
			var price	= product_json[rel];
			subtotal += (price*value);
			$(this).val(value);
		});
		if (typeof(discount) == 'object') {
			var remove = 0*0;
			if (discount.percent > 0) {
				percent	= discount.percent/100;
				remove	= subtotal*(percent);
			} else if (discount.fixed > 0) {
				remove = discount.fixed;
			}
			subtotal -= remove;
		}
		
		if (valid_vat == false && $('#vat_no').val() != '') $('#vat_no').blur();
		if (discount == false && $('#code').val() != '') $('#code').blur();
				
		var country	= $('#country').val();
		if (country == 'GB') {	/* Always add VAT to UK orders */
			taxtotal = subtotal*vat_rate;
		} else {
			taxtotal = 0;
			for (key in europe_json) {
				if (europe_json[key] != country) continue;
				/* If European state, only add VAT if they've given us a valid VAT number */
				if (!valid_vat) taxtotal	= subtotal*vat_rate;
				break;
			}
		}
		var total	= taxtotal+subtotal;
		if (total == 0) {
			$('#payment_options').slideUp();
		} else {
			$('#payment_options').slideDown();
		}
		
		$('#vat').text(taxtotal.toFixed(2));
		$('#total').text(total.toFixed(2));
	};
	$('.calc:first').change();
	
	$('a.delete,.confirm').click(function(){
		var message	= $(this).attr('title');
		if (message != '') {
			return confirm(message.replace(/\\n/ig, "\n"));
		}
	});

});

