var error='';

function validateEmail(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(address) == false) {
      return false;
   }
}

function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function swapship(div1,div2){
	$('#'+div1).css("display","none");
	$('#'+div2).css("display","block");
	recalc();
}

function validateForm(){
	recalc();
	arrow='<img src="http://www.timelessjazz.com/img/arrow-left-red.png">';
	frm=document.forms['orderform'];
	
	error='';
	tocheck = new Array("name","street","zip","city","state","country");
	for(var i=0; i<tocheck.length; i++) {
		name=tocheck[i];
		if(frm['pr_'+name].value==''){
			error += "Your "+name+"\n";
			$('#a_pr_'+name).html(arrow);
		} else {
			$('#a_pr_'+name).html('');
		}
	}

	if(validateEmail(frm.pr_email.value)==false){
		error += "Your email address is not valid \n";
		$('#a_pr_email').html(arrow);
	} else {
		$('#a_pr_email').html('');
	}

	if($('#ship_diff').css("display") != 'none'){
		//also check all shp
		for(var i=0; i<tocheck.length; i++) {
			name=tocheck[i];
			if(name!='email'){
				if(frm['sh_'+name].value==''){
					error += 'Shipping '+name+"\n";
					$('#a_sh_'+name).html(arrow);
				} else {
					$('#a_sh_'+name).html('');
				}
			}
		}
	}
	

	
}

function sendForm(){
	validateForm();
	
	if(error==''){
		$('#missingfields').html('');
		alert('You will now be redirected to the payment page. Please finish your order by returning to this page after the transaction.');
		frm.submit();
	} else {
		/* alert("Please fill out the following fields:\n"+error); */
		$('#missingfields').html('<span color="#a92121">Please fill out the missing fields</span>');
	}
}


function recalc(){
	frm=document.forms['orderform'];

	subtotal	 = parseFloat(frm.subtotal.value);
	
	if($('#ship_diff').css("display")=='none'){
		countryvalue = frm.pr_country.value;
	} else {
		countryvalue = frm.sh_country.value;
	}
	ineu = countryvalue.substr(0,1);
	country = countryvalue.substr(2,countryvalue.length-2);

	if(ineu!=1){
		shipping=5;
	} else {
		shipping=3;
	}
	if(country=="Netherlands"){
	
		shipping=0;
	
	}
	
	total = parseFloat(subtotal) + parseFloat(shipping);
	frm.total.value = parseFloat(total);
	
	if(countryvalue==''){
		$('#newtotal').html('Please fill in your details to calculate the shipping');
	} else {
		$('#newtotal').html('<table cellpadding=8><tr><td>Subtotal:</td><td>&euro;'+formatAsMoney(subtotal)+'</td></tr><tr><td>Shipping to '+country+':&nbsp;</td><td>&euro;'+formatAsMoney(shipping)+'</td></tr><tr><td colspan=2><hr></td></tr><tr><td><b>Total</b>:</td><td>&euro;'+formatAsMoney(total)+'</td></tr></table>');
	}
}
