/* 
 *Updated for mic
 */
 $(document).ready(function(){
 
 	$('#common_message').show();
	$("#stateProvinceInput").hide();
	$("#shippingStateProvinceInput").hide();
	showPaymentForm();
	
	if($('#address').val()>0)
	{
		$('#shipping_save_to_list').hide();
	}
	
	$(document).on('change',"#billingCountry", function(){
		listStates($(this).val(), '');
	});
	$(document).on('change',"#shippingCountry", function(){
		listStatesShipping($(this).val(), '');
	});
	
	$(document).on("click",".chkout-fr-pw",function(){
		$('.password').hide();
		$('.userLoginEmail').hide();
		$('.loginButton').hide();
		$("#forgot-password-block").show();
		$(".login-div").hide();	
	});
	$(document).on("click",".chkout-bk-login",function(){
		$('.password').show();
		$('.userLoginEmail').show();
		$('.loginButton').show();
		$("#forgot-password-block").hide();
		$(".login-div").show();	
	});
$('#sendPassword').on("click", function(e) {
    e.preventDefault();
	$('#reqemailID').trigger('blur');
	if($('#forgot-password-block').find(".message_validation :visible").length>0){  
		return false;	
	}
	var emailID = $('#reqemailID').attr('value');
	$.ajax({
		type:"POST",
		url:GLOBAL_BASE_PATH+'/forgotpassword/ajaxForgotPassword/',
		data:"emailID="+emailID,
		success:function(msg){
			$('#check-email-div').attr('style','display:block');
			$('#reset-password-div').attr('style','display:none');
			//$('#messageStatus').text(msg);
			try 
			{
				var x = $.parseJSON(msg);
			}catch (e) 
			{
				window.location = location.href;
				return false;
			}
			//jNotifyShowWithClose(msg,"promo_message", "message_success");
			if(x.error=='Yes')
			{				
				jNotify(x.errorMessage,'common_login_message','message_error');
			} 
			else if(x.error=='No')	
			{					 
				$('#messageStatus').text(x.errorMessage);
			}
		}
	});
	return false;
});
	if(!cartShipAdrs)
		formFillShippingAddress($("#address").val());
		
	var userConfirmTabs 		= 0;
	var userConfirmBillingTab 	= 0 ;
	var userConfirmShippingTab 	= 0 ;
	var userConfirmShippingMethodTab 	= 0 ;
	if($('.checkout_login').length){
		$('.checkout_login .content').show();
		$('.checkoutNav .chk-login').addClass('current');
		$(".checkout_billing .content, .checkout_shipping .content,.checkout_payment .content,.checkout_shipping_method .content").hide();
	}else{
		userConfirmTabs = 1;
		$(".checkout_billing .content").show();
		$('.checkoutNav .chk-billing').addClass('active');
        if ($( ".line-to" ).length) {
            $(".line-to").css("width","50%")
        }
		$(".checkout_shipping .content,.checkout_payment .content,.checkout_shipping_method .content").hide();
	}
	$(".checkoutNav .chk-login").click(function() {
			userConfirmBillingTab 	= 0 ;
			userConfirmShippingTab 	= 0 ;
			userConfirmShippingMethodTab 	= 0 ;
		if($(".checkout_login .content").is(":hidden"))
  		{
			$(".checkout_login .content").slideToggle(500);
			$(".checkout_login .heading span").hide();
			$(".checkout_billing .heading span").hide();
			$(".checkout_shipping_method .heading span").hide();
			$(".checkout_shipping .heading span").hide();
			$('.checkoutOption:checked').trigger('click');
			$(".checkout_billing .content,.checkout_shipping .content,.checkout_payment .content,.checkout_shipping_method .content").slideUp();
		}
  	});
	$(".checkoutNav .chk-billing , .show-billing").click(function() {
		if($(".checkout_billing .content").is(":hidden") && userConfirmTabs == 1)
  		{
			$(".checkout_billing .content").slideToggle(500);
			
			$(".checkout_login .content,.checkout_shipping .content,.checkout_payment .content,.checkout_shipping_method .content").slideUp();
		}
  	});
		
	$(".checkoutNav .chk-shipping").click(function() {
		if($(".checkout_shipping .content").is(":hidden") )
  		{
			$(".checkout_shipping .content").slideToggle(500);
			$(".checkout_billing .content,.checkout_shipping_method .content,.checkout_payment .content").slideUp();
		}
  	});
	
	$(document).on("click",".checkout_shipping_method .heading",function(){
		if($(".checkout_shipping_method .content").is(":hidden") && userConfirmShippingTab == 1) 
  		{
			$(".checkout_shipping_method .content").slideToggle(500);
			$(".checkout_billing .content,.checkout_payment .content,.checkout_shipping .content").slideUp();
		}
  	});
	
	$(".checkoutNav .chk-payment").click(function() {
		if($(".checkout_payment .content").is(":hidden") && userConfirmShippingMethodTab == 1)
  		{
			$(".checkout_payment .content").slideToggle(500);
			$(".checkout_billing .content,.checkout_shipping .content,.checkout_shipping_method .content").slideUp();
		}
  	});
	
	$(document).on("click","#submitCheckoutBilling",function(){
		
		$('#billingFirstName,#billingLastName,#billingAddress,#billingCity,#billingCountry,#billingState,#billingProvince,#billingZip,#billingEmail').trigger('blur');
		
		if(!$(this).validateForm({
			form: "formCheckoutBilling"
		}))
			return false;
		
		$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
	   		data: $("form#formCheckoutBilling").serialize()+"&adrsType=Billing",
			beforeSend:function()
			{
				$('#submitCheckoutBilling').hide();
				$('#submitCheckoutBillingLoader').show();	
			},
	   		success: function(data)
			{ 
				try 
				{
					var x = $.parseJSON(data);
				}catch (e) 
				{
                                        window.location = location.href;
					return false;
				}
				if(x.userError =='no_user'){
					location.reload();
					return false;
				}
				if(x.validationError=='No'){
					userConfirmBillingTab = 1;
					$(".checkout_block").html(x.html);
					$("#order_summary").html(x.summary);
					
					$(".checkout_billing .content").slideUp();
					$(".checkout_shipping .content").slideToggle(500);
					$('.checkoutNav .chk-shipping').addClass('active');
					$('.checkoutNav .chk-billing').addClass('completed');
				}
			},
			complete:function()
			{ 
				$('#submitCheckoutBillingLoader').hide();
				$('#submitCheckoutBilling').show();
			}
			
		});

	});
	
	$(document).on("click","#submitCheckoutShipping",function(){
		$('#shippingFname,#shippingLname,#shippingAddress,#shippingCity,#shippingCountry,#shippingZip,#shippingState,#shippingProvince,#shippingPhone').trigger('blur');
		
		if(!$(this).validateForm({
			form: "formCheckoutShipping"
		}))
			return false;
		
		var save2list = ($("#shippingSaveToList").prop('checked'))?1:0;
		$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
	   		data: $("form#formCheckoutShipping").serialize()+"&shippingSaveToList="+save2list+"&adrsType=Shipping",
	   		beforeSend:function()
			{
				$('#submitCheckoutShipping').hide();
				$('#submitCheckoutShippingLoader').show();	
			},
			success: function(data){ 
				try 
				{
					var x = $.parseJSON(data);
				}catch (e) 
				{
					//window.location = location.href;
					return false;
				}
				if(x.userError =='no_user')
				{
					location.reload();
					return false;
				}
				if(x.validationError=='No')
				{
					userConfirmShippingTab = 1;
					$(".checkout_block").html(x.html);
					$("#order_summary").html(x.summary);
					$(".checkout_shipping_method .content").html($(".pop_loader").html());
					$(".checkout_shipping_method .content").slideToggle(500);
					$(".checkout_shipping .content").slideUp();
					showShippingMethodUpdated();
				}
			},
			complete:function()
			{ 
				$('#submitCheckoutShippingLoader').hide();
				$('#submitCheckoutShipping').show();
			}
		});

	});
	
	
	$(document).on("click","#submitCheckoutShippingMethod",function(){
		
		$('.shippingMethodSelect').trigger('blur');
		if(!$(this).validateForm({
			form: "formCheckoutShippingMethod"
		}))
		return false;
		var postData='';
		$('.ajaxCartItems').each(function() 
		{
			$('#'+$(this).attr("id")+' :radio').each(function() 
			{ 
				name = $(this).attr('name');
			});
			postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val();
		});
		$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateShippingMethod/",
	   		data: {postData:postData},
			beforeSend:function()
			{
				$('#submitCheckoutShippingMethod').hide();
				$('#submitCheckoutShippingMethodLoader').show();	
			},
	   		success: function(data)
			{ 
				try 
				{
					var x = $.parseJSON(data);
				}catch (e) 
				{
					//window.location = location.href;
					return false;
				}
				$(".checkout_block").html(x.html);
				$("#order_summary").html(x.summary);
				$(".checkout_payment .content").html($(".pop_loader").html());
				$(".checkout_payment .content").slideToggle(500);
				$(".checkout_shipping_method .content").slideUp();
				$('.checkoutNav .chk-shipping').addClass('completed');
				showPaymentInfoUpdated();
			},
			complete:function()
			{ 
				$('#submitCheckoutShippingMethodLoader').hide();
				$('#submitCheckoutShippingMethod').show();
				userConfirmShippingMethodTab = 1;
			}
		});
		
		
	});
	
	
	displayPaymentDetails();	
	$(document).on('change',"#paymentSettingsGroupKey", function(){
		displayPaymentDetails();
	})
	$(document).on('click',".remove-link", function(){
	var cartItemID = Number($(this).attr('rel'));	
	jConfirm(msgConfirmDelete, AlertText,function (r) {
        if (r == true) {
            $.ajax({
			  type: "POST",
			  url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCart/",
			  data: { cartItemID: cartItemID,mode: 'delete_item'},
			  success: function (data) {
				  var x = JSON.parse(data);
				  if(x.isError=='Yes')
				  {
					window.location=GLOBAL_BASE_PATH+'/cart/checkout/';  
				  }
				  else
				  {
					  if(x.cartEmpty=='Yes')
					  {
						  	window.location=GLOBAL_BASE_PATH+'/';
					  }
					  else
					  {
							window.location=GLOBAL_BASE_PATH+'/cart/checkout/'; 
					  }
				  }
			  }
			  });
        } else {
            return false;
        }
    },okText,cancelText);
		
	})
	$(document).on('mouseover',"#divSecurityText", function(){
		DisplayTip("TipBox2");		
	})
	$(document).on('mouseout',"#divSecurityText", function(){
		HideTip("TipBox2");		
	})
	$(document).on('mouseover',"#TipBox2", function(){
		DisplayTip("TipBox2");		
	})
	$(document).on('mouseout',"#TipBox2", function(){
		HideTip("TipBox2");		
	})
	if($("#paymentGatewaysCount").val()==1)
	{
		var paymentKey = $("#paymentSettingsGroupKey").val();
		if(paymentKey=='Authorize' || paymentKey=='Beanstream' || paymentKey=='EWay' || paymentKey=='Moneris' || 
		paymentKey=='payment_express_post' || paymentKey=='Paypalpro' || paymentKey=='Psigate' || 
		paymentKey=='Pxfusion'|| paymentKey=='Securepay')
		{
			$("#siteHosted").val(1);
		}	
	}
	$(document).on('click',"#applypromo", function(){
		applyPromoCode();		
	})
	$('#promoCode').bind("keyup", function(e) {
	  var code = e.keyCode || e.which; 
	  if (code  == 13) { 
		applyPromoCode();
		return false;
	  }
	});
	$(document).on('click',"#removepromo", function(){
		removePromoCode();		
	})
	$(document).on('submit','#formPaymentGateway',function() 
	{

		if($(".message_validation :visible").length>0)
		{
		}
		else
		{
                        var paymentGateway = $('#paymentSettingsGroupKey').val();
                        var paymentSubmit = $('#paymentSubmit').val();
                        if(paymentGateway=='Payfort' && paymentSubmit!='Yes'){
                            var totAmount = $('#totOrderAmount').val();
                            var payFortCurrency = $('#payFortCurrency').val();
                            StartCheckout.open({
                                    amount:   totAmount*100,  // = AED 100.00
                                    currency: payFortCurrency,
                                    email:$('#loggedInUserEmail').val()
                                });
                                $('#paymentSubmit').val('Yes');
                            return false;
                        }
			$("#submitPayment").hide();
			$("#submitPaymentLoader").show();
			$(".overlay_checkout").show();
			$('.checkoutNav .chk-payment').addClass('completed');
		}
	}
	);
	// One page checkout
	$(document).on('click',".checkoutOption",function(){
		userConfirmTabs = 0;               
                $('.login-div').attr('style','display:block');
		if($('.checkoutOption:checked').val() == 'signin'){
			$('.password').show();
			$('.userLoginEmail').show();
			$('.loginButton').show();
			$('.signup').hide();
			$('.guestButton').hide();
			$('#forgot-password-block, #back-login-link').attr('style','display:none');
			$('#forgot-password-link').attr('style','display:block');
			$("#div_err_formLogin_checkUserExist").addClass("hide");
		}else if ($('.checkoutOption:checked').val() == 'signup'){
			$('.signup').show();
			$('.password').hide();
			$('.userLoginEmail').hide();
			$('.loginButton').hide();
			$('#forgot-password-block, #back-login-link').attr('style','display:none');

		}
		else{
			$('.userLoginEmail').show();
			$('.password').hide();
			$('.signup').hide();
			$('.loginButton').hide();
			$('.guestButton').show();
			$('#forgot-password-block, #back-login-link').attr('style','display:none');
		}
	});
	$(document).on("keyup",
		"#userLoginEmail,#userLoginPassword,#userFirstName,#userLastName,#userEmail,#userPassword,#userConfirmPassword",
	function(e){
		if(e.which==13){
			$("#submitLogin").trigger('click');
		}
	});
	$(document).on('click',"#loginProceed",function(){
	
		var userEmail = $("#userLoginEmail").val();
		$.ajax({
			type:"POST",
			url:GLOBAL_BASE_PATH+'/cart/ajaxupdateuseremail/',
			data:'userLoginEmail='+userEmail,
			success:function(msg){
				$('.checkout_login .content').slideUp();
				$('.checkout_billing .content').slideDown();
                if ($( ".line-to" ).length) {
                    $(".line-to").css("width","50%")
                }
			}
		});
	});
	
	$(document).on("click","#submitLogin",function(){
		$("#shipping_save_to_list").show();
		$("#divPayAddressList").show();
		$("#checkUserExist").val('1');
		$("#div_err_formLogin_checkUserExist").addClass('hide');
		if($('.checkoutOption:checked').val() == 'signin'){
			$('#userLoginEmail, #userLoginPassword').trigger('blur');
			if(!$(this).validateForm({
			form: "formLogin"
			}))
			return false;
			var formData= $("#formLogin").serializeArray();
				formData.push({ name: "submitLogin", value: loginSubmit });
			__loginAjax(formData,'common_message','cart/checkout');
		}else if ($('.checkoutOption:checked').val() == 'signup'){
			$('#userFirstName, #userLastName,#userEmail, #userPassword,#userConfirmPassword').trigger('blur');
			if(!$(this).validateForm({
			form: "formUserSignup"
			}))
			return false;

			var reUrl	=	$("#redirectLoginUrl").val();
		 	var formData= $("#formUserSignup").serializeArray();
			formData.push({ name: "submit", value: 1 });
			$.ajax({
				type:"POST",
				url:GLOBAL_BASE_PATH+'/login/ajaxCheckoutSignup/',
				data:formData,
				success:function(msg){
					try {
						var x = $.parseJSON(msg);
					} catch (e) {
						$(".checkoutSignup").html("");
						// $(".checkoutSignup").append(msg);
						$(".checkoutSignup").append('<div class="warning">'+ msg +'<span class="notifyClose"></span></div>');
						$(".notifyClose").click(function () {
		                    $(this).parent('.warning').fadeOut('fast');
		                });

						return false;
					}
					if(x.error=='Yes')
					{
						jNotify(x.errorMessage,'common_message','message_error');
						if (typeof(FB) != 'undefined'&& FB != null ) 
						{
							FB.XFBML.parse();	
						}
						return false;
					}
					else
					{
						window.location = GLOBAL_BASE_PATH+'/cart/checkout/';
					}
				}				
			});
		}
		else{
			$('#userLoginEmail').trigger('blur');
			if($(".message_validation :visible").length>0)
			{
				return false;
			}else{
				var userEmail = $("#userLoginEmail").val();
				$.ajax({
					type:"POST",
					url:GLOBAL_BASE_PATH+'/cart/ajaxupdateuseremail/',
					data:'userLoginEmail='+userEmail,
					success:function(msg){
						try 
						{
							var x = $.parseJSON(msg);
						}catch (e) 
						{
							window.location = location.href;
							return false;
						}
						if(x.code == 'error'){
							$("#checkUserExist").val('');
							$("#div_err_formLogin_checkUserExist").removeClass('hide');
							return false;
						}else if (x.code == 'cart_validation_error'){
							var i;
							for (i = 0; i < x.message.length; ++i)
							{
								jNotifyShowWithClose(x.message[i],"message_cart", "message_error"); 
							}
							return false;
						}else if (x.code == 'promo_error'){
							jNotifyShowWithClose(x.message,"message_cart", "message_error");
							removePromoCode();
							return false;
						}else{
							$("#checkUserExist").val('1');
							$("#checkUserExist").trigger('blur');
							$("#shipping_save_to_list").hide();
							$("#divPayAddressList").hide();
							$("#shipping_save_to_list").prop('checked',false);
							if($("#billingEmail").val() == ''){
								$("#billingEmail").val(userEmail);
							}
							$('.checkout_login .content').slideUp();
							$('.checkout_billing .content').slideDown();
							$('.checkoutNav .chk-billing').addClass('active');
                            if ($( ".line-to" ).length) {
                                $(".line-to").css("width","50%")
                            }
							$('.checkout_login .heading #loginText').html(lblLogedAsGuest);
							userConfirmTabs = 1;
						}
					}
				});
			}
		}
		
			
	});
	//Redeem gift Coupon
	$(document).on("click",'#submitCoupon', function () 
	{
		if(!$("#cartUser").val()>0){
			return false;
		}
		var couponCodeValue = $('#couponCode').val();
		$.ajax({
		  type: "POST",
		  url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCoupon/",
		  data: { couponCode: couponCodeValue},
		  success: function (data) {
				try 
				{
					var x = $.parseJSON(data);
				}catch (e) 
				{
					window.location = location.href;
					return false;
				}
				setPromoCharityBlock(x);
				showPaymentInfoUpdated();
				showShippingMethodUpdated();
 
			  }
		});
	});
	//one page checkout ends
        
        StartCheckout.config({
            key: $('#open_key').val(),
            complete: function(params) {
              submitFormWithToken(params);
            }
        });
});

function submitFormWithToken(params) {
    $('#startToken').val(params.token.id);
    $('#startEmail').val(params.email);
    $('#creditCardNumber').val(params.token.card.last4);
    $('#expMonth').val(params.token.card.exp_month);
    $('#expYear').val(params.token.card.exp_year);
    //$('#securityCode').val($('#cvc').val());
  // Append the params to the form
//  frm = $("<form action='/cart/checkout/' method='POST'></form>");
//  frm.append("<input type='hidden' name='startToken' value='" + params.token.id + "'>");
//  frm.append("<input type='hidden' name='startEmail' value='" + params.email + "'>");
//  // Finally, submit the form
  //frm.submit();
  $('#formPaymentGateway').submit();
}
function applyPromoCode()
{
	var promoCode 	= $("#promoCode").val();
	$.ajax({
		type: "POST",
		url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateAddress/",
		data: {applyPromo: 'Yes',promoCode:promoCode},
		success: function (data) {
			try 
			{
				var x = $.parseJSON(data);
			}catch (e) 
			{
				window.location = location.href;
				return false;
			}
			setPromoCharityBlock(x);
			showPaymentInfoUpdated();
			showShippingMethodUpdated();
		}
	});
	return false;
}  
function removePromoCode()
{
	$.ajax({
	type: "POST",
	url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateAddress/",
	data: {removePromo: 'Yes',promoCode:''},
	success: function (data) {
		try 
		{
			var x = $.parseJSON(data);
		}catch (e) 
		{
			window.location = location.href;
			return false;
		}
		setPromoCharityBlock(x);
		showShippingMethodUpdated();
		showPaymentInfoUpdated();
	}
	});
	  return false;

} 

function displayPaymentDetails() {
	
	var appendCardImages	=	'';
	var paymentKey = $("#paymentSettingsGroupKey").val();
	$("#AjaxdivPaymentCardTypes").show();
	if(paymentKey=='Authorize' || paymentKey=='Beanstream' || paymentKey=='EWay' || paymentKey=='Moneris' || 
	paymentKey=='payment_express_post' || paymentKey=='Paypalpro' || paymentKey=='Psigate' || paymentKey=='Pxfusion'|| 
	paymentKey=='Securepay')
	{
		$("#siteHosted").val(1);
		$(".payment-div").show();
		$(".AjaxOfflinePaymentDesc").html('');
		$("#AjaxloadProcessImagePay").append('<img src="'+GLOBAL_ROOT_PATH+'/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2" width="16" height="16" border="0" alt="Loading"/>');
		$.ajax({
					 type: "POST",
					 url: GLOBAL_BASE_PATH+"/cart/ajaxCardType/",
					 data: 'paymentKey='+paymentKey,
					 success: function(data) {	
						$("#AjaxloadProcessImagePay").empty();
						$('#creditCardType').empty(); 
						if(data!='') { 
							$('#creditCardType').show(); 
							$("#creditCardType").append(data);
							if($('#userCardType').val()!='')
							{
								$("#creditCardType [value=" + $('#userCardType').val() + "]").
								attr("selected", true);
							}
							$("#creditCardType option").each(function()
							{ 
								if($(this).text()!= selecttext) {
									var cardImage		=	$("#imgFullPath").val()+'/'+$(this).val()+'.png';
										appendCardImages=appendCardImages + '<li> <img src="'+cardImage+'" alt="'+$(this).text()+'" title="'+$(this).text()+'" /> </li>';
								}
							});
						} else {
							
							$('#creditCardType').hide(); 
						}
						$("#AjaxdivPaymentCardTypeImages").empty();
						$("#AjaxdivPaymentCardTypeImages").append(appendCardImages);
						
					 }
			
				});
		
	}
	else if(paymentKey=='CashOnDeliveryRedemption' || paymentKey=='ChequeMoneyOrder')
	{
		$("#siteHosted").val(0);
		$(".payment-div").hide();
		$(".AjaxOfflinePaymentDesc").html('');
		$(".AjaxOfflinePaymentDesc").html('<img src="'+GLOBAL_ROOT_PATH+'/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
		$.ajax({
						 type: "POST",
						 url: GLOBAL_BASE_PATH+"/cart/ajaxOfflinePayments/",
						 data: 'paymentKey='+paymentKey,
						 success: function(data) 
						 {	
						 	$(".AjaxOfflinePaymentDesc").html(data);
							
							$("#divPaymentButton").hide();
							$("#divCompleteOrdertButton").show();
							
						 }
					   });
	}
	else
	{
		$(".AjaxOfflinePaymentDesc").html('');
		$("#siteHosted").val(0);
		$(".payment-div").hide();
	}
}

function DisplayTip(TipBoxID) { 
   tip_box_id = document.getElementById(TipBoxID);  
   tip_box_id.style.display = "block";  
} // function DisplayTip()

function HideTip(TipBoxID) { 
	tip_box_id = document.getElementById(TipBoxID);
	tip_box_id.style.display = "none";
}




var progressImg = '<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"/>';

//ajax state populating
function listStates(countryID,stateID){
	
	if(countryID!=''){
		var data=new Object();
		data.countryID=countryID;
		data.stateID=stateID;
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH+"/ajax/ajaxState/",
			data: data,
			beforeSend:function(){
				$("#loadProcessImage").append(progressImg);
			},
			success: function(msg){  
				if(msg!=''){
					$("#stateInput").show();
					$('#billingState').empty();
					$("#stateProvinceInput").hide();
					$("#billingState").append('<option value="">'+selecttext+'</option>'+msg);
					$("#stateSelectedType").val("state");	
					$("#billingProvince").val('');
				} else {
					$("#stateInput").hide();
					$("#stateProvinceInput").show();
					if(stateID==0) { 
						stateID	=	'';
					}
					if(!(stateID>=0 || stateID==''))
					$("#billingProvince").val(stateID);
					$("#stateSelectedType").val("province");
						$("#billingState").empty()
						$("#billingStateID").val('');
				}
				$("#loadProcessImage").empty();
			}
		});
	}
}

//For Shipping
function listStatesShipping(countryID, stateID) {
    $("#loadProcessImageShipping").append(progressImg);
		var data=new Object();
		data.countryID=countryID;
		data.stateID=stateID;
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH + "/ajax/ajaxState/",
			data: data,
			success: function (msg) {
				if (msg != '') {
					$("#shippingStateInput").show();
					$('#shippingState').empty();
					$("#shippingStateProvinceInput").hide();
					$("#shippingState").append('<option value="">' + selecttext + '</option>' + msg);
					$("#shippingStateSelectedType").val("state");
					$("#shippingProvince").val('');
				} else {
					$("#shippingStateInput").hide();
					$("#shippingStateProvinceInput").show();
					
					if(!(stateID>=0 || stateID==''))
						$("#shippingProvince").val(stateID);
					$("#shippingStateSelectedType").val("province");
						$("#shippingState").empty()
						$("#shippingStateID").val('');
				}
				$("#loadProcessImageShipping").empty();
			}
		});
	}

function showPaymentForm(){
	var countryID = '';
	$("#billingCountry").val($('#billingCountryID').val());
	$("#shippingCountry").val($('#shippingCountryID').val());
	
	listStates($('#billingCountryID').val(), $('#billingStateID').val());
	if(cartShipAdrs)
	listStatesShipping($("#shippingCountryID").val(), $('#shippingStateID').val());
}


//Same Information for Billing and Shipping
function billingShippingSame(chkStatus){
	if(chkStatus){
		$("#divPayAddressList").slideUp();
		$("#shippingFname").val($("#billingFirstName").val());
		$("#shippingLname").val($("#billingLastName").val());
		$("#shippingAddress").val($("#billingAddress").val());
		$("#shippingAddress1").val($("#billingAddress1").val());
		$("#shippingCity").val($("#billingCity").val());
		$("#shippingCountry").val($("#billingCountry").val());
		$("#shippingCountryID").val($("#billingCountry").val());
		$("#shippingZip").val($("#billingZip").val());
                $("#shippingPhone").val($("#billingPhone").val());
		var stateType = $("#stateSelectedType").val();
		var stateID = (stateType=='state') ? $("#billingState").val() : $("#billingProvince").val();
		listStatesShipping($("#billingCountry").val(),stateID);
	}else{
		if($('.checkoutOption:checked').val() != 'guest'){
			$("#divPayAddressList").slideDown();
		}
	}
	$("#address").val('');
}


function formFillShippingAddress(selAdrs){

	if(selAdrs >0){
		$.each(userAddressList, function (i, address) {
			if(address['userShippingID'] == selAdrs){
                                //console.log(address);
				$("#shippingFname").val(address['shippingFname']);
				$("#shippingLname").val(address['shippingLname']);
				$("#shippingAddress").val(address['shippingAddress1']);
				$("#shippingAddress1").val(address['shippingAddress2']);
				$("#shippingCity").val(address['shippingCity']);
				$("#shippingCountry").val(address['shippingCountryID']);
				$("#shippingCountryID").val(address['shippingCountryID']);
				listStatesShipping(address['shippingCountryID'],address['shippingStateID']);
				$("#shippingProvince").val(address['shippingProvince']);
				$("#shippingZip").val(address['shippingZip']);
                                $("#shippingPhone").val(address['shippingPhone']);
			}
		});
		
		$("#shipping_save_to_list").slideUp();
	}else if(selAdrs == -1){
		//document.formCheckoutShipping.reset();
		$("#shippingFname").val('');
		$("#shippingLname").val('');
		$("#shippingAddress").val('');
		$("#shippingAddress1").val('');
		$("#shippingCity").val('');
		$("#shippingCountry").val('');
		$("#shippingState").empty().append('<option value="">'+selecttext+'</option>');
		$("#shippingProvince").val('');
		$("#shippingZip").val('');
                $("#shippingPhone").val('');
		
		$("#address").val(selAdrs);
		$("#shipping_save_to_list").slideDown();
	}
}

function showPaymentInfoUpdated(){
	var currentPaymentTabStatus = $(".checkout_payment .content").css('display');	
	$.ajax({
   		type: "POST",
   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
   		data: "adrsType=Payment",
   		beforeSend:function()
		{
			$('#submitCheckoutShipping').hide();
			$('#submitCheckoutShippingLoader').show();	
		},
		success: function(data){ 
			try 
			{
				var x = $.parseJSON(data);
			}catch (e) 
			{
				window.location = location.href;
				return false;
			}
			if(x.userError =='no_user')
			{
				location.reload();
				return false;
			}
			if(x.validationError=='No'){
				$(".checkout_payment").html(x.html);
				if(currentPaymentTabStatus=='none')
				{
					$(".checkout_payment .content").hide();
				}else{
					$('.checkoutNav .chk-payment').addClass('active');
                    if ( $( ".line-to" ).length ) {
                    $(".line-to").css("width","100%")
                    }
				}
				displayPaymentDetails();
			}
		},
		complete:function()
		{ 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
		}
	});
}
function showShippingMethodUpdated(){
	var currentPaymentTabStatus = $(".checkout_shipping_method .content").css('display');	
	$.ajax({
   		type: "POST",
   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
   		data: $("form#formCheckoutShipping").serialize()+"&adrsType=ShippingMethod",
   		beforeSend:function()
		{
			$('#submitCheckoutShipping').hide();
			$('#submitCheckoutShippingLoader').show();	
		},
		success: function(data){ 
			try 
			{
				var x = $.parseJSON(data);
			}catch (e) 
			{
				//window.location = location.href;
				return false;
			}
			if(x.userError =='no_user')
			{
				location.reload();
				return false;
			}
			if(x.validationError=='No'){
				$(".checkout_shipping_method").html(x.html);
				if(currentPaymentTabStatus=='none')
				{
					$(".checkout_shipping_method .content").hide();
				}
			}
		},
		complete:function()
		{ 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
			if(currentPaymentTabStatus!='none' && $(".checkout_shipping_method").next(".content").not(":hidden"))
			{
				$('.checkoutNav .chk-shipping').addClass('active');
			}
			
		}
	});
}
function setPromoCharityBlock(x)
{
	if(x.promoData.promoError=='Yes')
	{
		jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_error"); 
		$("#promoCode").val('');
		$("#couponCode").val('');
	}
	else if(x.promoData.promoError=='No')
	{ 
		$(".checkout_block").html(x.html);
		$("#order_summary").html(x.summary);
		jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_success");
	}
}

function validate(item){
	var StrippedString = item.val().replace(/(<([^>]+)>)/ig,"");
	if(item.val() != StrippedString){
		jAlert(lblHtmltags);	
	}
	item.val(StrippedString);
	return true;
}
/* $(document).ready(function($){ 
	if($("#billingFirstName").val()!=''){
		$("#submitCheckoutBilling").trigger('click');
	}
}); */
$(document).ready(function($){ 
	$(document).on("blur",'#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone,#shippingFname,#shippingLname,#shippingAddress,#shippingAddress1,#shippingProvince,#shippingCity,#shippingZip,#shippingPhone',function(){
		validate($(this));
    });
	
		
	$('#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone,#shippingFname,#shippingLname,#shippingAddress,#shippingAddress1,#shippingProvince,#shippingCity,#shippingZip,#shippingPhone').each(function(){
		validate($(this));
    });
	
});
//your fb login function
function fblogin() {
	FB.login(function(response) {
	window.location = GLOBAL_BASE_PATH+'/login/facebook/';
	}, {scope:'email,user_birthday,publish_stream,read_stream,offline_access'});
}

function handleSubmit()
{
	$('#promo').attr('disabled','disabled');
	$('#submitCoupon').attr('disabled','disabled');
	$("#complete").hide();
	$("#completeLoader").show();
	return true;
}

var loginSubmit	=	"{$language.lblLogin}";
$(document).on("click","#forgot-password-link",function(){
    $("#forgot-password-block").show();
    $(".login-div").hide();	
});
$(document).on("click","#back-login-link",function(){
    $("#forgot-password-block").hide();
    $(".login-div").show();	
});
