///////////////   To trim the string ////////////////////
function trim(str){
	return str.replace(/^\s*|\s*$/g,"");
}

var remail=/^([_&a-zA-Z0-9-]+(\.[_&a-zA-Z0-9-]+)*@[&a-zA-Z0-9-]+\.+[&a-zA-Z0-9-]+)/;

//////////// Validate email ///////////////////////

function checkEmail(fieldvalue){
	if(remail.test(fieldvalue))
		return false;
	else
		return true;
}

// Funtion to round the number //

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber; // Output the result to the form field (change for your purposes)
}

// Function to block alphabets //

function blockNumbers(e){
	var key;
	var keychar;
	var reg;			 
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode;
	}else if(e.which) {
		// netscape
		key = e.which;
	}else {
		// no event, so pass through
		return true;
	}
	keychar = String.fromCharCode(key);
	
	if ( (key>=48 &&  key<=57) || (key==46) || (key==44)|| (key==45) || (key==34) || (key==39) || (key==32) || (key == 8) || (key == 43) || (key == 41) || (key == 40)){
		return true;
	}else{
		return false;
	}
}

// Functions for the checkout pages //

function addtocart(formid)
{
	var ran_unrounded	=	Math.random()*100000;
	var ran_number		=	Math.floor(ran_unrounded); 
	params	=	$('#'+formid).serialize();
	params	=	params+"&action=addtocart&s="+ran_number;
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 		
			var OParr	=	msg.split("^");
			if(trim(OParr[1])	==	"S"){
				window.location.href='/shop/cart-items.html';				
			}
		}
	});	
}

// Function delete product in cart ------------------------------------
function deletefromcart(cartid,sessid)
{
	if ((sessid == null) || (sessid == "")) return;    
    var ran_unrounded	=	Math.random()*100000;
	var ran_number		=	Math.floor(ran_unrounded); 	
	var url_params	=	"cartid=" + escape(cartid)+"&sessid=" +escape(sessid)+"&action=deletefromcart&s="+ran_number;
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	url_params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 		
			var OParr	=	msg.split("^");
			if(OParr[1]	==	"S"){			
				$('.copy').filter(".wide").html(OParr[0]);													
			}else if(OParr[1]	==	"F"){			
				$('.copy').filter(".wide").html(OParr[0]);
				$('#frmBilling').hide();
			}
		}
	});
} 

// Function Update product in cart ------------------------------------

function updatetocart(formid,sessid)
{  
  if ((sessid == null) || (sessid == "")) return;    
    var ran_unrounded=	Math.random()*100000;
	var ran_number	=	Math.floor(ran_unrounded); 	
	if($('#alter_delivery').attr('checked')==true && $('#dcountry').val()!='0'){
		var bcontry	=	$('#dcountry').val();
	}else
		var	bcontry	=	$('#bcountry').val();
	params			=	$('#'+formid).serialize();
	params			=	params+"&action=updatetocart&country_id="+bcontry+"&sessid=" +escape(sessid)+"&s="+ran_number;	
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 		
			var OParr	=	msg.split("^");
			if(OParr[1]	==	"S"){				
				$('.copy').filter(".wide").html(OParr[0]);	
				$('.cart_action_buttons').append(OParr[2]);										
			}else if(OParr[1]	==	"F"){			
				$('.copy').filter(".wide").html(OParr[0]);
				$('#frmBilling').hide();
			}
		}
	});
}

function toggleDelivery(){
	$('.shipping').toggle(400);	
}

function validate_billing(frm){
	var flag		= true;
	var del_params	= '';
	var message		= '';
	var delmsg		= '';
	if($('#bfirst').val()==''){		
		message += '<li>Please insert first name</li>';
		$('#biname').addClass('error');
		flag = false;
	}else
		$('#biname').removeClass('error');
	if($('#blast').val()==''){
		message += '<li>Please insert last name</li>';
		$('#biname').addClass('error');
		flag = false;
	}else
		$('#biname').removeClass('error');

	if($('#bemail').val()=='' || ( $('#bemail').val()!='' && checkEmail($('#bemail').val()))){
		message += '<li>Please insert valid email</li>';
		$('#biemail').addClass('error');
		flag = false;
	}else
		$('#biemail').removeClass('error');

	if($('#baddress1').val()==''){
		message += '<li>Please insert address</li>';
		$('#biaddr').addClass('error');
		flag = false;
	}else
		$('#biaddr').removeClass('error');

	if($('#bcity').val()==''){
		message += '<li>Please insert city</li>';
		$('#biaddr').addClass('error');
		flag = false;
	}else
		$('#biaddr').removeClass('error');

	if($('#bzipcode').val()==''){
		message += '<li>Please insert zipcode</li>';
		$('#biaddr').addClass('error');
		flag = false;
	}else
		$('#biaddr').removeClass('error');	

	if($('#bphone').val()==''){
		message += '<li>Please enter contact number</li>';
		$('#bitel').addClass('error');
		flag = false;
	}else
		$('#bitel').removeClass('error');
	
	if($('#alter_delivery').attr('checked')==true){
		if($('#dfirst').val()==''){		
			delmsg += '<li>Please insert first name</li>';
			$('#shname').addClass('error');
			flag = false;
		}else
			$('#shname').removeClass('error');

		if($('#dlast').val()==''){
			delmsg += '<li>Please insert last name</li>';
			$('#shname').addClass('error');
			flag = false;
		}else
			$('#shname').removeClass('error');

		if($('#daddress1').val()==''){
			delmsg += '<li>Please insert address</li>';
			$('#shaddr').addClass('error');
			flag = false;
		}else
			$('#shaddr').removeClass('error');

		if($('#dcity').val()==''){
			delmsg += '<li>Please insert city</li>';
			$('#shaddr').addClass('error');
			flag = false;
		}else
			$('#shaddr').removeClass('error');

		if($('#dzipcode').val()==''){
			delmsg += '<li>Please insert zipcode</li>';
			$('#shaddr').addClass('error');
			flag = false;
		}else
			$('#shaddr').removeClass('error');
		
		if($('#dphone').val()==''){
			delmsg += '<li>Please enter contact number</li>';
			$('#shtel').addClass('error');
			flag = false;
		}else
			$('#shtel').removeClass('error');	
	}

	var params	 =	$('#frmBilling').serialize();		
	if(flag==true){				
		$('#billing').find('.error').html('');
		$('#shipping').find('.error').html('');
		register_customer(params,$('#check_sessid').val());
	}else{
		if(message != ''){
			$('#billing').find('p.error').html('<strong>There were problem(s) with your submission</strong><ul>'+message+'</ul>');
		}else
			$('#billing').find('.error').html('');
		if(delmsg != ''){
			$('#shipping').find('p.error').html('<strong>There were problem(s) with your submission</strong><ul>'+delmsg+'</ul>');
		}else
			$('#shipping').find('.error').html('');
		return flag;
	}
}


// Function to register customers with billing and shipping details//

function register_customer(params,sessid){
	if ((sessid == null) || (sessid == "")) return;    
    var ran_unrounded	=	Math.random()*100000;
	var ran_number		=	Math.floor(ran_unrounded); 
	var action			=	'register_customer';
	var url_params		=	params+"&action=" +escape(action)+"&sessid=" +escape(sessid)+"&s="+ran_number;
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	url_params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 	
			if(msg=="S"){
				if($('#cart_id')){
					document.frmBilling.action='/shop/summary.html';
					document.frmBilling.submit();
				}else{
					alert('Your cart is empty!');
				}
			}
		}
	});
}

function get_cartitems(country_id,sessid){
	if ((sessid == null) || (sessid == "")) return;    
    var ran_unrounded	=	Math.random()*100000;
	var ran_number		=	Math.floor(ran_unrounded); 
	var action			=	'country_cart';
	var url_params	=	"country_id=" + escape(country_id)+"&action=" +escape(action)+"&sessid=" +escape(sessid)+"&s="+ran_number;
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	url_params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 
			var OPArr	=	msg.split("^");
			if(OPArr[1]=='S'){
				$('.copy').filter('.wide').html(OPArr[0]);			
			}else if(OParr[1]	==	"F"){			
				$('.copy').filter(".wide").html(OParr[0]);
				$('#frmBilling').hide();
			}
		}
	});
}

// Function to validate shipping details highslide//

function validate_shipping(inv){	
	flag = true;	
	var msg	='';
	if($(inv).find('#btitle').val()==""){	
		msg += '<li>Please choose title</li>';		
		flag=false;
		$('#invname').addClass('error');
	}else
		$('#invname').removeClass('error');

	if($(inv).find('#firstname').val()==""){
		msg += '<li>Please enter your first name</li>';		
		flag=false;
		$('#invname').addClass('error');
	}else
		$('#invname').removeClass('error');

	if($(inv).find('#lastname').val()==""){
		msg += '<li>Please enter your last name</li>';			
		flag=false;
		$('#invname').addClass('error');
	}else
		$('#invname').removeClass('error');

	if($(inv).find('#address1').val()==""){
		msg += '<li>Please enter address1</li>';			
		flag=false;	
		$('#invadd').addClass('error');
	}else
		$('#invadd').removeClass('error');

	if($(inv).find('#icountry').val()=="0"){
		msg += '<li>Please select country</li>';	
		flag=false;
		$('#invadd').addClass('error');
	}else
		$('#invadd').removeClass('error');

	if($(inv).find('#phone').val()==""){
		msg += '<li>Please enter phone number</li>';		
		flag=false;
		$('#invtel').addClass('error');
	}else
		$('#invtel').removeClass('error');
	
	if(flag == true){
		$(inv).find('.error').html('');
		$(inv).find('.error').hide();
		var params	=$(inv).serialize();				
		update_shipping(params);
	}else{
		if(msg != ''){					
			$(inv).find('p.error').show();
			$(inv).find('p.error').html('<strong>There were problem(s) with your submission</strong><ul>'+msg+'</ul>');
			$(inv).find('p').removeClass('highlight').addClass('error').html('<strong>There were problem(s) with your submission</strong><ul>'+msg+'</ul>');
		}else{
			$(inv).find('p.error').hide();			
			$(inv).find('p.error').html('');
		}
		return false;
	}
	
}

// Function to update customers with billing and shipping details//

function update_shipping(params){
	if ((params == null) || (params == "")) return;    
    var ran_unrounded	=	Math.random()*100000;
	var ran_number		=	Math.floor(ran_unrounded); 
	var action			=	'update_shipping';
	var url_params		=	params+"&action=" +escape(action)+"&s="+ran_number;
	$.ajax({
		type	:	'POST',
		url		:	'/includes/cartajax.php',
		data	:	url_params,
		error	:	function(){alert('Error loading document!');},
		success	:	function(msg){ 	
			var OPArr	=	msg.split("^");
			if(OPArr[2]=="S"){
				$('#invadd').html(OPArr[0]);
				$('#deladd').html(OPArr[1]);
				if(OPArr[3]!=''){						
					$('.cart_table').html(OPArr[3]);					
					$('.button').filter('.payment-cart').click(function(){
						if($('#terms').attr('checked')==true){
							$(this).parent().parent().find(".highlight").filter('.warning').hide();
							document.frmSummary.action='/shop/checkout.html';
							document.frmSummary.submit();
						}else{
							$(this).parent().parent().find(".highlight").filter('.warning').show();
						}
					});
				}
				$('p').removeClass('error').addClass('highlight').html('Your details have been successfully updated!').show();
				$('.shoppingcart').find(".highlight").filter('.warning').hide();
			}else if(OPArr[2]=="F"){
				$('p').removeClass('error').addClass('highlight').html('Please try again!').show();
			}
		}
	});

}


$(document).ready(function () {
	// For shop related functions ===================================================

	if($('#editship').val()=='' || $('#editship').val()=='0'){
		$('#alter_delivery').attr('checked', false);
		$('.shipping').filter('.hidden').hide();
	}

	$('.button').filter('.checkout-cart').click(function(){
			validate_billing(document.frmBilling);
	});

	$(".highlight").filter('.warning').hide();

	$('.button').filter('.payment-cart').click(function(){
	  if($('#terms').attr('checked')==true){
		$(this).parent().parent().find(".highlight").filter('.warning').hide();
		document.frmSummary.action='checkout.html';
		document.frmSummary.submit();
	  }else{
		$(this).parent().parent().find(".highlight").filter('.warning').show();
	  }
	});

	// While changing the billing country //
	$('#bcountry').change(function(){			
		var country_id	=	$(this).val();
		if($('#alter_delivery').attr('checked')==true && $('#dcountry').val()!='0'){
			country_id	=	$('#dcountry').val();
		}
		if(country_id != '0')
			get_cartitems(country_id,$('#check_sessid').val());
	});

	// While changing the delivery country//
	$('#dcountry').change(function(){			
		var country_id	=	$(this).val();
		if(country_id != '0')
			get_cartitems(country_id,$('#check_sessid').val());
	});

	$('.button').filter('.pay-cart').click(function(){
		validate_payment('#frmCheckout');
	});

});

