/* 
 *Updated for mic
 */
var currentCartItemID;
 var currentQuantity;
 var currentTextboxID;
 var currentProductOptionID;

 function handleSubmit()
{
/******************/
var chkDisable = "Yes";
$('.shippingmethodchk :selected').each(function(i, selectedChk){
    //console.log($(selectedChk).val());
    if($(selectedChk).val() == "")
        {chkDisable = "No";}
});
if(chkDisable == "Yes"){
$('#promo').attr('disabled','disabled');
$('#submitCoupon').attr('disabled','disabled');
$("#complete").hide();
$("#completeLoader").show();
}

/*********************/
	return true;
}
 $(document).ready(function(){
	var shippingcountryID = $('#shippingCountry').val();	
	var shippingCity = $('#shippingcityhidValue').val();
	listshippingCities(shippingcountryID, shippingCity);
	
	


function getshippingCityHiddenValue(val) {
    $('#shippingcityhidValue').val(val);
}
	
	
 	$('#common_message').show();
	//$("#stateProvinceInput").hide();
	//$("#shippingStateProvinceInput").hide();
	showPaymentForm();
        //$('.firatradiopay :radio').prop("checked", true); 
	//$(".radiopaymentcls").trigger('click'); 
	$(".checkout_billing").hide();
        $(".checkout_billing .content").hide();
				
	if($('#address').val()>0)
	{
		$('#shipping_save_to_list').hide();
	}
        if($("#paymentSettingsGroupKey").val()=='') { 
            //$("#paymentSettingsGroupKey").val($("#paymentSettingsGroupKey option:eq(1)").val());
            $("#paymentSettingsGroupKey").val('CashOnDeliveryRedemption');
                       
        }
	$(document).on("change",'#shippingCountry,#shippingCity',function(){
		showShippingMethodUpdated();
        });
	/*$(document).on('change',"#billingCountry", function(){
		listStates($(this).val(), '');
	});
	$(document).on('change',"#shippingCountry", function(){
		listStatesShipping($(this).val(), '');
	});
        $(document).on('change',"#billingState", function(){ //13-03-15
		listCity($("#billingCountry").val(),$(this).val(), '');
	}); 
	$(document).on('change',"#shippingState", function(){ //13-03-15
		listCityShipping($("#shippingCountry").val(), $(this).val(),'');
	});*/
	$(document).on("click",".chkout-fr-pw,#forgot-password-link",function(){
		$("#forgot-password-block").show();
                $('.password').hide();
		$('.userLoginEmail').hide();
		$('.loginButton').hide();
		$('.login-div').hide();
               
	});
	$(document).on("click",".chkout-bk-login",function(){
                $('.login-div').show();                
		$("#forgot-password-block").hide();
                $('.password').show();
		$('.userLoginEmail').show();
		$('.loginButton').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){
                        //09-03-15 Start
                        try {
				var x = $.parseJSON(msg);
			} catch (e) {				
				return false;
			}			
			if(x.error=='Yes')
			{				
				jNotify(x.errorMessage,'common_message','message_error');
			} else if(x.error=='No')	{		
				 $('#check-email-div').attr('style','display:block');
                                 $('#reset-password-div').attr('style','display:none'); 			 
				 $('#messageStatus').text(x.errorMessage);
			}
                        //09-03-15 ENDs
			/*$('#check-email-div').attr('style','display:block');
			$('#reset-password-div').attr('style','display:none');
			$('#messageStatus').text(msg);*/
			//jNotifyShowWithClose(msg,"promo_message", "message_success");
		}
	});
	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').show();
		$('.checkoutNav .chk-login').addClass('current');
		// $('.checkout_login .heading').addClass('active');
		//$(".checkout_billing .content").show();
		//$(".checkout_billing, .checkout_shipping,.checkout_payment,.checkout_shipping_method").hide();
		//$(".checkout_login .heading span, .checkout_shipping .heading span,.checkout_billing .heading span,.checkout_shipping_method .heading span").hide();
	}else{
		userConfirmTabs = 1;
		$(".checkout_billing").show();
		$('.checkoutNav .chk-billing').addClass('active');
		//$('.checkout_billing .heading').addClass('active');
		//$(".checkout_shipping ,.checkout_payment,.checkout_shipping_method").hide();
		//$(".checkout_login .heading span, .checkout_shipping .heading span,.checkout_billing .heading span,.checkout_shipping_method .heading span").hide();

	}
	/*.checkout_login .heading, */
	$(".checkoutNav .chk-login").click(function() {
			userConfirmBillingTab 	= 0 ;
			userConfirmShippingTab 	= 0 ;
			userConfirmShippingMethodTab 	= 0 ;
		if($('.checkout_login').is(":hidden"))
  		{
			$('.checkout_login').slideToggle(500);
			// $(".checkout_login .heading span").hide();
			// $(".checkout_billing .heading span").hide();
			// $(".checkout_shipping_method .heading span").hide();
			// $(".checkout_shipping .heading span").hide();
			// $(".checkout_login .heading span").show();
			$('.checkoutOption:checked').trigger('click');
			$(".checkout_billing , .checkout_shipping , .checkout_payment , .checkout_shipping_method ").slideUp();
		}
  	});
	
	/*.checkout_billing .heading, */
	$(".checkoutNav .chk-billing , .show-billing").click(function() {
		if($(".checkout_billing").is(":hidden") && userConfirmTabs == 1)
  		{
			$(".checkout_billing").slideToggle(500);
			// $(".checkout_billing .heading span").hide();
			// $(".checkout_shipping_method .heading span").hide();
			// $(".checkout_shipping .heading span,.checkout_shipping_method .heading span").show();
			
			//$(".checkout_login,.checkout_shipping,.checkout_payment,.checkout_shipping_method").slideUp();
		}
  	});
	
	/*.checkout_shipping .heading*/	        
	$(".checkoutNav .chk-shipping").click(function() {
		if($(".checkout_shipping").is(":hidden") && userConfirmBillingTab == 1)
  		{
			$(".checkout_shipping").slideToggle(500);
			//$(".checkout_shipping .heading span").hide();
			//$(".checkout_billing .heading span,.checkout_shipping_method .heading span").show();
			
			$(".checkout_billing ,.checkout_shipping_method ,.checkout_payment").slideUp();
		}
  	});
	
	$(document).on("click",".checkout_shipping_method .heading",function(){
		if($(this).next(".content").is(":hidden") && userConfirmShippingTab == 1)
  		{
			$(this).next(".content").slideToggle(500);
			$(".checkout_shipping_method .heading span").hide();
			$(".checkout_billing .heading span").show();
			$(".checkout_shipping .heading span").show();
			$(".checkout_billing .content,.checkout_payment .content,.checkout_shipping .content").slideUp();
		}
  	});
	
	/*.checkout_payment .heading, */
	$(".checkoutNav .chk-payment").click(function() {
		if($(".checkout_payment").is(":hidden") && userConfirmShippingMethodTab == 1)
  		{
			$(".checkout_payment").slideToggle(500);
			//$(".checkout_billing .heading span,.checkout_shipping .heading span,.checkout_shipping_method .heading span").show();
			
			$(".checkout_billing ,.checkout_shipping ,.checkout_shipping_method").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);
                                        
                                        if($("#shipping_AmountDiv").length) { //23-04-15
                                            $("#shipping_AmountDiv").html(x.htmlShipp);
                                        }
					
					$(".checkout_billing").slideUp();
					//$(".checkout_billing .heading span").show();
					$(".checkout_shipping").slideToggle(500);
					//$(".checkout_shipping .heading").addClass('active');
					$('.checkoutNav .chk-shipping').addClass('active');
					$('.checkoutNav .chk-billing').addClass('completed');
					//$(".checkout_shipping .heading span").hide();
					$('html,body').animate({
							scrollTop:20},
						'slow');
				}
			},
			complete:function()
			{ 
				$('#submitCheckoutBillingLoader').hide();
				$('#submitCheckoutBilling').show();
			}
			
		});

	});
	
	
	$(document).on("change",".delivery_select .shippingmethodchk",function(){
            var id = $(this).attr('id');
            if( $('#'+id).val()!=''){
               $('#hid_err_formCheckoutShippingMethod_'+id).val("0");
            }else{
               $('#hid_err_formCheckoutShippingMethod_'+id).val("1"); 
            }
        });
	   $(document).on("click",".shippingMethodSelect",function(){
            if($('#shippingCountry').val()=='' || $('#shippingCountry').val()<=0 || $('#shippingCountryID').val()=='' || $('#shippingCountryID').val()<=0){
                $('#shippingCountry').val(selCountryID);
                $('#shippingCountryID').val(selCountryID);
            }
            var postData='';
            $('.ajaxCartItems').each(function()
		{
                   
			/*name = $('.'+$(this).attr("id")+':first').attr('name');
			postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val();*/
                    $('#'+$(this).attr("id")+' :radio').each(function() 
			{ 
				name = $(this).attr('name');
			});
                        var reserr = name;
                        reserr     = reserr.replace("_", "_val_");
                               
                        if($('input[name='+name+']:radio:checked').length>0) {                           
                           
                            $("#div_err_formCheckoutShippingMethod_"+reserr).addClass('hide');
                            $("#hid_err_formCheckoutShippingMethod_"+reserr).val(0);
                        }
//                        var multiBusiness =  $(this).find('h5').length;
//                        if(multiBusiness>0){
//                            var incr =0;
//                            var inputName = '';
//                            $('h5.ship-product-name').each(function(){
//                                if(incr==0){
//                                    inputName = 'shippingMethod_'+$(this).attr('rel');
//                                }
//                                var newName = 'shippingMethod_'+$(this).attr('rel');
//                                var postValue	 = '-'+newName+'~'+$('input[name='+inputName+']:radio:checked').val();
//                                postData  += postValue;
//                                incr++;
//                            })
//                        }else{
//			    postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val(); 
//                        }
                        postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val(); 
                       
		});
                $.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateShippingMethod/",
	   		/*data: {postData:postData},*/
                        data: $("form#formCheckoutShipping").serialize()+"&postData="+postData+"&shippingCountryID="+$("#shippingCountryID").val(),
			/*beforeSend:function()
			{
				//$('#submitCheckoutShippingMethod').hide();
				//$('#submitCheckoutShippingMethodLoader').show();
			},*/
	   		success: function(data)
			{
				var x = jQuery.parseJSON(data);
                                
				//$(".checkout_block .orderSumry").html(x.html);
				$("#order_summary .totSummary").html(x.summary); 
                                if($("#shipping_AmountDiv").length) { //23-04-15
                                    $("#shipping_AmountDiv").html(x.htmlShipp);
                                }
                                
                                //if(x.totordamt<=0) {                                    
                                   //window.location.href = GLOBAL_BASE_PATH+"/cart/checkoutprocess/";
                                //} else {
                                    //$(".checkout_payment .content").html($(".pop_loader").html());
                                    //$(".checkout_payment .content").slideToggle(500);
                                   // $(".checkout_shipping_method .content").slideUp();
                                   // $(".checkout_shipping_method .heading span").show();
                                   // $('.checkout_shipping_method .heading').addClass('active');
                                    //showPaymentInfoUpdated();
                                    //$('.checkoutpay h3').addClass('active');
                                //}
			}
                        /*,
			complete:function(data)
			{
                                var x = jQuery.parseJSON(data);                               
				 
                                if(x.totordamt<=0) {
                                    $('#submitCheckoutShippingMethod').hide();
                                    $('#submitCheckoutShippingMethodLoader').show();
                                } else {                                
                                    $('#submitCheckoutShippingMethodLoader').hide();
                                    $('#submitCheckoutShippingMethod').show();
                                }
				userConfirmShippingMethodTab = 1;
			}*/
		});
            
        });
	$(document).on("click","#submitCheckoutShippingMethod",function(){
		$('.delivery_select .shippingmethodchk').each(function(){
                    var id = $(this).attr('id');
                    if( $('#'+id).val()==''){
                      $('#hid_err_formCheckoutShippingMethod_'+id).val("1");
                    }
                  });
                  
		$('.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;
				}
                                 //28-05-15
                                if(x.isError=='Yes')
                                {
                                    jNotify(x.isErrorMsg,'common_message','message_error');
                                }else {
                                    $(".checkout_block").html(x.html);
                                    $("#order_summary").html(x.summary);
                                    if($("#shipping_AmountDiv").length) { //23-04-15
                                        $("#shipping_AmountDiv").html(x.htmlShipp);
                                    }
                                    $(".checkout_payment").html($(".pop_loader").html());
                    $(".checkout_shipping").hide();
                                    $(".checkout_shipping_method").hide();
                                    $(".checkout_payment").slideToggle(500);
                                   // $('html,body').animate({scrollTop:20},'slow');
                                    $('.checkoutNav .chk-shipping').addClass('completed');
                                    showPaymentInfoUpdated();
                                }
			},
			complete:function()
			{ 
				$('#submitCheckoutShippingMethodLoader').hide();
				$('#submitCheckoutShippingMethod').show();
				userConfirmShippingMethodTab = 1;
			}
		});
		
		
	});
	if(cartShipAdrs) {                
            showShippingMethodUpdated();
        } 
	
	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/onestepcheckout/';  
				  }
				  else
				  {
					  if(x.cartEmpty=='Yes')
					  {
						  	window.location=GLOBAL_BASE_PATH+'/';
					  }
					  else
					  {
							window.location=GLOBAL_BASE_PATH+'/cart/onestepcheckout/'; 
					  }
				  }
			  }
			  });
        } 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);
		}
                 if(paymentKey=='PayFort') {
                     $("#siteHosted").val(2);
                 }
	}
	$(document).on('click',"#applypromo", function(){
		applyPromoCodeCheckout();		
	})
	$('#promoCode').bind("keyup", function(e) {
	  var code = e.keyCode || e.which; 
	  if (code  == 13) { 
		applyPromoCodeCheckout();
		return false;
	  }
	});
	$(document).on('click',"#removepromo", function(){
		removePromoCode();		
	})
	$(document).on('submit','#formPaymentGateway',function() 
	{

		if($(".message_validation :visible").length>0)
		{
		}
		else
		{
			$("#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($("#paymentSettingsGroupKey").val()=='') {
            
            $("#paymentSettingsGroupKey").val(defaultGateway);
            paymentSelected();
        }*/
        $(document).on('change',"#paymentSettingsGroupKey", function(){
                paymentSelected();
	})
	
	$(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/onestepcheckout');
			
		}
                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){
                                        if($.trim(msg)=='success'){
						if(reUrl!="" && !(typeof reUrl === "undefined")){
							window.location = GLOBAL_BASE_PATH+'/'+reUrl+'/';
						}else{
							location.reload();
						}
					}else{
                                                try {
                                                        var x = $.parseJSON(msg);
                                                        jNotify(x.errorMessage,'common_message','message_error');
                                                        if (typeof(FB) != 'undefined'&& FB != null )
                                                        {
                                                                FB.XFBML.parse();
                                                        }
                                                        if(typeof __errValidEmail!="undefined" && __errValidEmail!='')
                                                        {
                                                                jNotify(__errValidEmail,'common_login_message','message_error');
                                                        }
                                                        return false;
                                                } catch (e) {
                                                        $(".checkoutSignup").html("");
                                                        $(".checkoutSignup").html(msg);
                                                        //$(".cstm_slct").selectpicker('refresh');
                                                        //customCheck() 
                                                        return false;
                                                }
						
					}
                                        
				}				
			});
		}
		else{
			$('#userLoginEmail').trigger('blur');
			if($(".message_validation :visible").length>0)
			{
				return false;
			}else{
				var userEmail = $("#userLoginEmail").val();//userLoginguestEmail
				$.ajax({
					type:"POST",
					url:GLOBAL_BASE_PATH+'/cart/ajaxupdateuseremail/',
					data:'userLoginEmail='+userEmail,
					success:function(msg){                                    
                                                 
						var x = $.parseJSON(msg);
						if(x.code == 'error'){
                                                        if(x.message!='') {
                                                            jNotify(x.message,"common_message", "message_error");
                                                        }
							$("#checkUserExistGuest").val('');
							$("#div_err_formLoginGuest_checkUserExistGuest").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{
							$("#checkUserExistGuest").val('1');
							$("#checkUserExistGuest").trigger('blur');
							$("#shipping_save_to_list").hide();
							$("#divPayAddressList").hide();
							$("#shipping_save_to_list").prop('checked',false);
							if($("#billingEmail").val() == ''){
								$("#billingEmail").val(userEmail);
							}
							/*$('.checkout_login').slideUp();
							$('.checkout_billing').slideDown();
							//$('.checkout_billing .heading').addClass('active');
							$('.checkoutNav .chk-billing').addClass('active');
							$('.checkout_login .heading #loginText').html(lblLogedAsGuest);
							//$('.checkout_login .heading span').show();
							*/
                                                        $(".selectAddressArea").addClass('hide');
                                                        //$("#divPayAddressList .guest-listbox").removeClass('hide').addClass('show');  
                                                        window.location.href = GLOBAL_BASE_PATH+'/cart/onestepcheckout/'; 
						}
					}
				});
			}
		}
		
			
	});
	//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;
				}
                      
				setPromoCharityBlockCheckout(x);
				//showPaymentInfoUpdated();
				//showShippingMethodUpdated();
 
			  }
		});
                
                
	});
	//one page checkout ends

});

function applyPromoCodeCheckout()
{
	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;
			}
			setPromoCharityBlockCheckout(x);
			
		}
	});
	//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;
		}
		setPromoCharityBlockCheckout(x);
		
	}
	});
	  //return false;

} 
function paymentSelected() {
     checkPaymentSelected();
     displayPaymentDetails();
}
function checkPaymentSelected() {
   // if($("#paymentSettingsGroupKey").val()=='') {
        
        $("#div_err_formPaymentGateway_validatePayment").addClass('hide');
        $("#hid_err_formPaymentGateway_validatePayment").val(0);
       
   // }
}
function setPaymentparams(param) {
           var rel = param.attr('rel');
            
           param.addClass("active");
            param.siblings().removeClass("active");
           //$("#Payment_"+rel).addClass("active");
            $('.PaymentTxt').html(param.text());
             $('.PaymentAgreeTxt').hide();
            $('#paymentSettingsGroupKey').val(rel);
            
            displayPaymentDetails();
}
function displayPaymentDetails() {

        
	var appendCardImages	=	'';
	var paymentKey = $("#paymentSettingsGroupKey").val();
        if(paymentKey=='') {
                $(".paymentDesc").hide();         
		$(".AjaxOfflinePaymentDesc").html('');
		$("#siteHosted").val(0);
		$(".payment-div").hide();
                $(".payment-div1").hide(); 
                $(".payment-div2").hide(); 
        } else {
             $(".paymentDesc").show();     
        }
        /*$('.paymentNew').each(function() 
        {
                
                var paymentKeySel = $(this).attr('rel');
                $(".paymentDesc_"+paymentKeySel).hide();
                $("#Payment_"+paymentKeySel).removeClass('active');
                $(".paymentDesc_"+paymentKeySel).removeClass('active');
                
        });*/
        /*if(paymentKey!='') {
            
          $("#Payment_"+paymentKey).addClass('active');
          $(".paymentDesc_"+paymentKey).addClass('active');  
        }*/
	$("#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();           
                //$(".paymentDesc_"+paymentKey).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(); 
                $(".payment-div1").hide(); 
                $(".payment-div2").hide(); 
                //$(".paymentDesc_"+paymentKey).show();
		$(".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();
                                                        //var myVar = $("ul.CheckOutPay li.active").text();
                                                        //$('.PaymentTxt').html(myVar);
                                                        // $('.PaymentAgreeTxt').hide();
                                                         
						 }
					   });
	}
	else
	{
                /*$("#submitPayment").val(lblPayNow);
		$(".AjaxOfflinePaymentDesc").html('');
		$("#siteHosted").val(0);
		$(".payment-div").hide();
                
                var myVar = $("ul.CheckOutPay li.active").text();
                $('.PaymentAgreeTxt').show();
               $('.PaymentAgreeTxt').html(myVar);
                $('#paymentSettingsGroupKey').val(paymentKey);*/
                //$(".paymentDesc_"+paymentKey).show();         
		$(".AjaxOfflinePaymentDesc").html('');
		$("#siteHosted").val(0);
		$(".payment-div").hide();
                $(".payment-div1").hide(); 
                $(".payment-div2").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);
					$("#billingState").selectpicker('refresh');
					$("#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();
			}
		});
	}
}
//ajax City populating 13-03-15
function listCity(countryID,stateID,cityID){
	
	if(countryID!=''){
		var data=new Object();
		data.countryID=countryID;
		data.stateID=stateID;
                data.cityID=cityID;
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH+"/ajax/ajaxCity/",
			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);
////                                        $('#billingState').selectpicker('refresh');
////                                        $('#billingCountry').selectpicker('refresh');
//					$("#stateSelectedType").val("state");	
//					$("#billingProvince").val('');

                                        $('#billingCity').empty();
                                        $("#billingCity").append('<option value="">' + selecttext + '</option>' + msg);
                                        
				} else {
//					$("#stateInput").hide();
//					$("#stateProvinceInput").show();
//					if(stateID==0) { 
//						stateID	=	'';
//					}
//					if(!(stateID>=0 || stateID==''))
//					$("#billingProvince").val(stateID);
//					$("#stateSelectedType").val("province");
//						$("#billingState").empty()
//						$("#billingStateID").val('');
    
                                        $('#billingCity').empty();
                                        $('#billingState option:selected').each(function(){
                                            var cloned = $(this).clone();
                                           // cloned.attr('value',cloned.text());
                                            $('#billingCity').append(cloned);
                                        });
                                            
                                        //$('#billingCity').val('');
//                                        $('#billingCity').find("option").filter(function(){
//                                            return ( ($(this).val() == txt) || ($(this).text() == txt) )
//                                          }).prop('selected', true);
                                       // $('#billingCity option[value="' + txt + '"]').prop('selected', true);
				}
				$("#loadProcessImage").empty();
			}
		});
	}
}
//For Shipping 13-03-15
function listCityShipping(countryID, stateID,cityID) {
    $("#loadProcessImageShipping").append(progressImg);
		var data=new Object();
		data.countryID=countryID;
		data.stateID=stateID;
                data.cityID=cityID;
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH + "/ajax/ajaxCity/",
			data: data,
			success: function (msg) {
				if (msg != '') {
					
					$('#shippingCity').empty();					
					$("#shippingCity").append('<option value="">' + selecttext + '</option>' + msg);
                                        $("#shippingCity").selectpicker('refresh');
										$("#shipAddressEdit .message_validation").addClass('hide');
										$("#shipAddressEdit .field_wrp ").removeClass('error_active');
										showShippingMethod(); 
				} else {

					$('#shippingCity').empty();
                                        //$('#shippingCity').val('');
                                        $('#shippingState option:selected').each(function(){
                                            var cloned = $(this).clone();
                                            //cloned.attr('value',cloned.text());
                                            $('#shippingCity').append(cloned);
                                        });
                                        $("#shippingCity").selectpicker('refresh');
				}
				$("#loadProcessImageShipping").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);
					$("#shippingState").selectpicker('refresh');
					$("#shippingStateSelectedType").val("state");
					$("#shippingProvince").val('');
                                        //$("#shippingCountry").selectpicker('refresh');
                                        $("#div_err_formCheckoutShipping_shippingCountry").addClass("hide");
										$("#shipAddressEdit .message_validation").addClass('hide');
										$("#shipAddressEdit .field_wrp ").removeClass('error_active');
				} 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 = '';
	$("#shippingCountry").val($('#shippingCountryID').val());
	
	if(cartShipAdrs) {
            
	//listStatesShipping($("#shippingCountryID").val(), $('#shippingStateID').val());
       // listCityShipping($('#shippingCountryID').val(), $('#shippingStateID').val(),$('#hidshippingCityVal').val()); //13-03-15
	showShippingMethod(1); 
	}
			
}


//Same Information for Billing and Shipping
/*function billingShippingSame(chkStatus){
	if(chkStatus){
		//$("#divPayAddressBlk").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());
		var stateType = $("#stateSelectedType").val();
		var stateID = (stateType=='state') ? $("#billingState").val() : $("#billingProvince").val();
		listStatesShipping($("#billingCountry").val(),stateID);
                listCityShipping($("#billingCountry").val(),$("#billingState").val(),$("#billingCity").val());
//                $(this).validateForm({form: "formCheckoutShipping"})
                $("#shipAddressEdit .message_validation").addClass('hide');
                $("#shipAddressEdit .field_wrp ").removeClass('error_active');
                $("#divPayAddressBlk").slideUp();
	}else{
		if($('.checkoutOption:checked').val() != 'guest'){
		$("#divPayAddressBlk").slideDown();
			$("#shipAddressEdit").slideUp();
		}
	}
	$("#address").val('');
} */
//Same Information for Billing and Shipping
function billingShippingSame(chkStatus){
	if(chkStatus){
                $(".checkout_billing").show();
                $(".checkout_billing .content").show();
                $("#billingshippingSamehid").val(1);
                $("#billingFirstName") .val('');
                $("#billingLastName") .val('');
                $("#billingAddress") .val('');
                $("#billingAddress1") .val('');                
                $("#billingCity") .val('');
                $("#billingZip") .val('');
                $("#billingPhone") .val('');
                $("#shippingStateSelectedType").val("state");
                $("#billingState").val('');

	}else{
                $("#billingshippingSamehid").val(0);
                $(".checkout_billing").hide();
                $(".checkout_billing .content").hide();
	}
        $("ul.billingContent li span.message_validation").addClass('hide');
	$("#address").val('');
}


function formFillShippingAddress(selAdrs,editType){
        if(editType!='') {
            $('#editShipAdd').val(selAdrs);
            $("#address").val(selAdrs);
        }
	if(selAdrs >0){
		$('.addressBox').removeClass('active');
		$('#addressBox_'+selAdrs).addClass('active');               
                
                
		$.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']);				
				$("#shippingCountry").val(address['shippingCountryID']);
				//$("#shippingCountry").selectpicker('refresh');
                                
				$("#shippingCountryID").val(address['shippingCountryID']);
				//listStatesShipping(address['shippingCountryID'],address['shippingStateID']);   
                                /*if($("#shippingCountryID").val()!=selCountryID) {
                                    $("#shippingCountryID").val(selCountryID);
                                }*/
                                listshippingCities(address['shippingCountryID'], address['shippingCity']);
                                $("#shippingCity").val(address['shippingCity']);
                                //listCityShipping(address['shippingCountryID'], address['shippingStateID'],address['shippingCity']);
				//$("#shippingProvince").val(address['shippingProvince']);
				$("#shippingZip").val('');
                                $("#shippingPhone").val(address['shippingPhone']);
                                showShippingMethod(1);
                                showShippingMethodUpdated();
				$("#shipAddressEdit .message_validation").addClass('hide');
                $("#shipAddressEdit .field_wrp ").removeClass('error_active');		
                $("#shippingCity").trigger("liszt:updated");
			}
		});
		
		//$("#shipping_save_to_list").slideUp();
	}else if(selAdrs == -1){
		//document.formCheckoutShipping.reset();
		$("#shippingFname").val('');
		$("#shippingLname").val('');
		$("#shippingAddress").val('');
		$("#shippingAddress1").val('');
		$("#shippingCity").val('');
		$("#shippingCountry").val(selCountryID);
                $("#shippingCountryID").val($("#shippingCountry").val());
		//$("#shippingState").empty().append('<option value="">'+selecttext+'</option>');
        //$("#shippingCity").empty().append('<option value="">'+selecttext+'</option>');
		//$("#shippingState,#shippingCountry,#shippingCity").selectpicker('refresh');
		//$("#shippingProvince").val('');
		$("#shippingZip").val('');
                $("#shippingPhone").val('');
        $("#billingshippingSame").prop("checked",false)
		$("#billingshippingSame").parent().removeClass('checked')
		$("#address").val(selAdrs);
		$("#shipping_save_to_list").slideDown();
		$('#shipAddressEdit').slideDown();
		$('#formCheckoutShippingMethod').remove();
                
        $('html,body').animate({ scrollTop: $("#shipAddressEdit").offset().top - 100 },'slow'); //22-04-15
	}
	/*$('#shipAddressEdit').slideDown();*/
       // $('#submitCheckoutShipping').trigger('click');
//	$('html,body').animate({
//		scrollTop: $("#shipAddressEdit").offset().top - 50},
//	'slow');	
}

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');
				}
				displayPaymentDetails();
				//customCheck();  
			}
		},
		complete:function()
		{ 
			if(!$("#paymentSettingsGroupKey").val() > 0) {
				$('.radiopaymentcls :radio').prop('checked',false);
				$('.firatradiopay :radio').prop("checked", true); 
				$(".firatradiopay").trigger('click'); 
			} 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
		}
	});
}
function showShippingMethodUpdated(){
    if(showShipping>0) {       
	var currentPaymentTabStatus = $(".checkout_shipping_method .content").css('display');	
        if($('#shippingCountryID').val()=='') {
            $('#shippingCountryID').val($('#shippingCountry').val());
        }
	$.ajax({
   		type: "POST",
   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
   		data: $("form#formCheckoutShipping").serialize()+"&adrsType=ShippingMethod"+"&sectionType=checkout&shippingCountryID="+$("#shippingCountryID").val(),
   		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);
                                
                                //17-03-15 SHipping Methods Updation and calculations                                
                                var postData='';
                                var postValue = 0;
                                $('.ajaxCartItems').each(function() 
                                {
                                        
                                        $('#'+$(this).attr("id")+' :radio').each(function() 
                                        { 
                                                postValue = 1;
                                                name = $(this).attr('name');
                                                
                                        });
                                        var reserr = name;
                                        reserr     = reserr.replace("_", "_val_");
                                        
                                        if($('input[name='+name+']:radio:checked').length>0) {                           
                                          
                                            $("#div_err_formCheckoutShippingMethod_"+reserr).addClass('hide');
                                            $("#hid_err_formCheckoutShippingMethod_"+reserr).val(0);
                                        } else {
                                            
                                            $("#div_err_formCheckoutShippingMethod_"+reserr).removeClass('hide');
                                        }
                                        postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val();
                                });
                                
                                //postValue = 0;
                                if(postValue>0) {
								
                                    $.ajax({
                                            type: "POST",
                                            url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateShippingMethod/",
                                            data: $("form#formCheckoutShipping").serialize()+"&postData="+postData+"&shippingCountryID="+$("#shippingCountryID").val(),
                                            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);
                                                    $("#order_summary .totSummary").html(x.summary); 
                                                    if($("#shipping_AmountDiv").length) { //23-04-15
                                                        $("#shipping_AmountDiv").html(x.htmlShipp);
														
                                                    }
													//showPaymentInfoUpdated();
                                            },
                                            complete:function()
                                            { 
                                                    $('#submitCheckoutShippingMethodLoader').hide();
                                                    $('#submitCheckoutShippingMethod').show();
                                                    userConfirmShippingMethodTab = 1;
                                            }
                                    });
                                }
                                //17-03-+15 Shipping Rate Clculation Reproduce End
                                
				if(currentPaymentTabStatus=='none')
				{
					 $(".checkout_shipping_method .content").hide();
				}
			}
		},
		complete:function()
		{ 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
			if(currentPaymentTabStatus!='none' && $(".checkout_shipping_method").next(".content").not(":hidden"))
			{
				$('.checkout_shipping_method .heading').addClass('active');
				$('.checkoutNav .chk-shipping').addClass('active');
				$('.checkout_shipping_method .heading span').hide();
			}
			else
			{
				$('.checkout_shipping_method .heading span').hide();
			}
			//$(".cstm_slct").selectpicker('refresh');
		}
	});
    }
}
function setPromoCharityBlockCheckout(x){ 
       
	if(x.promoData.promoError=='Yes')
	{
		//jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_error"); 
                jNotifyShowWithClose(x.promoData.promoErrMsg,"common_message", "message_error");                 
		$("#promoCode").val('');
		$("#couponCode").val('');
	}
	else if(x.promoData.promoError=='No')
	{ 
		//$(".checkout_block").html(x.html);
		$("#order_summary .totSummary").html(x.summary); 
                if($("#shipping_AmountDiv").length) { //23-04-15
                    $("#shipping_AmountDiv").html(x.htmlShipp);
                }
			
    if($("#orderTotalAmount").val()<=0) {    
        $("#checkPG").val(1);        
        $(".paymentSelFld").hide();        
        $(".paymentLabel").hide();
    } else {
        $(".paymentSelFld").show();
        $(".paymentLabel").show();
    }				
		//jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_success");
                jNotifyShowWithClose(x.promoData.promoErrMsg,"common_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',function(){
		//validate($(this));
    });
	
		
	$('#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone,#shippingFname,#shippingLname,#shippingAddress,#shippingAddress1,#shippingProvince,#shippingCity').each(function(){
		//validate($(this));
    });
    
    $('.use_btn').click(function(){
        //$("#shipAddressEdit").slideUp();
    })
    
    $('.edit_btn').click(function(){
        $("#shipAddressEdit").slideDown();
        $('html,body').animate({ scrollTop: $("#shipAddressEdit").offset().top - 100 },'slow'); //22-04-15
    })
	
});
//your fb login function
function fblogin() { 
	FB.login(function(response) {
	window.location = GLOBAL_BASE_PATH+'/login/facebook/';
	}, {scope:'email,user_birthday,publish_actions'});
}

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

function CallDeleteCart(cartItemID)
{
	jConfirm(msgConfirmDelete, AlertText,function (r) {
	if (r == true) {
		$.ajax({
			  type: "POST",
			  url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCart/",
			  data: { cartItemID: cartItemID,mode: 'delete_item',sectionType: 'checkout'},
			  success: function (data) {
					try 
					{
						var x = $.parseJSON(data);
					}catch (e) 
					{
						window.location = location.href;
						return false;
					}
				  if(x.isError=='Yes')
				  {
					 jNotifyShowWithClose(x.error,"common_message", "message_error"); 
				  }
				  else
				  {
					  if(x.cartEmpty=='Yes')
					  {
							window.location=GLOBAL_BASE_PATH+'/';
					  }
					  else
					  {
							$('#cart_ajax_section').html('');
							$('#cart_ajax_section').append(x.cartHtml);
							assignJsonDataToCartJS(x.cartData);
							updateCartNotification();
							setPromoCharityBlockCheckout(x);
							jNotifyShowWithClose(x.error,"common_message", "message_info"); 
                                                         var carcount=$("#hidcartitemcount").val();
                                                        $("#hidcartitemcount").val(carcount-1);
                                                        $("#cartitemcount").html($("#hidcartitemcount").val()+"  item(s) ");
					  }
				  }
			  }
			  });
	}
	else
	{
		return false;
	}
	},okText,cancelText);
}

function CallDeleteCartinCheckout(cartItemID){
    jConfirm(msgConfirmDelete, AlertText,function (r) {
	if (r == true) {
		$.ajax({
			  type: "POST",
			  url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCart/",
			  data: { cartItemID: cartItemID,mode: 'delete_item',sectionType: 'checkout'},
			  success: function (data) {
                              
					try 
					{
						var x = $.parseJSON(data);
					}catch (e) 
					{
                                            console.log(x.cartHtml);
                                                console.log(e);
						//window.location = location.href;
						return false;
					}
                                        //
				  if(x.isError=='Yes')
				  {
					 jNotifyShowWithClose(x.error,"common_message", "message_error"); 
				  }
				  else
				  {
					  if(x.cartEmpty=='Yes')
					  {
							window.location=GLOBAL_BASE_PATH+'/';
					  }
					  else
					  {
							$('#cart_ajax_section').html('');
							$('#cart_ajax_section').append(x.cartHtml);
							assignJsonDataToCartJS(x.cartData);
							updateCartNotification();
							setPromoCharityBlockCheckout(x);
							jNotifyShowWithClose(x.error,"common_message", "message_info"); 
                                                         var carcount=$("#hidcartitemcount").val();
                                                        $("#hidcartitemcount").val(carcount-1);
                                                        $("#cartitemcount").html($("#hidcartitemcount").val()+"  item(s) ");
                                                        $("#order_summary").html(x.summary);
                                                        if($("#shipping_AmountDiv").length) { //23-04-15
                                                            $("#shipping_AmountDiv").html(x.htmlShipp);
                                                        }
					  }
				  }
			  }
			  });
	}
	else
	{
		return false;
	}
	},okText,cancelText);
}
function listshippingCities(shippingcountryID, shippingCity) {
    $('#shippingcityhidValue').val(shippingCity);
    if (shippingcountryID != '') {
        var data = {
            "shippingcountryID": shippingcountryID,
            "shippingCity": shippingCity
        };
        $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH + "/index/shippingcitiesAjax/",
            data: data,
            beforeSend: function () {
                $("#loadProcessImage1").append('<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
            },
            success: function (msg) {
                $("#loadProcessImage1").empty();
				$(".choosen").chosen();
                var data = $.trim(msg);
                if (data != '') {
                    $("#cityInput").show();
                    $('#shippingCity').empty();
                    $("#cityProvinceInput").hide();
                    $("#shippingCity").append('<option value="">Select</option>' + msg);
					$('#shippingCity').trigger("liszt:updated");
                    $("#citySelectedType").val("city");
                    $('#shippingProvince').val('');
                    $("#div_err_frmBusiness_provincehidden").css("display", "none");
                } else if (data == '') {
                    $("#cityInput").hide();
                    $("#cityProvinceInput").show();
                    $('#shippingCity').val(shippingCity);
                    $('#userProvince').val(shippingCity);
                    $("#citySelectedType").val("province");
                    $("#div_err_frmBusiness_provincehidden").css("display", "none");
                }
            }
        });
    }
}
function showShippingMethod(arg){
            //alert(showShipping);
         if(showShipping>0) {
                   
		if(arg==2) {
                    $('#shippingFname,#shippingLname,#shippingAddress,#shippingCity,#shippingCountry,#shippingPhone').trigger('blur');
		
                    if(!$(this).validateForm({
                            form: "formCheckoutShipping"
                    })) {                        
                            //$("#shipAddressEdit").show();
                            $("#shipAddressEdit").slideDown();
                            $('html,body').animate({ scrollTop: $("#shipAddressEdit").offset().top - 100 },'slow'); //22-04-15
                            return false;
                    }
                } else {
                    $("#shipAddressEdit").show();   
                }
                if(arg==4) {
                //$("#shipAddressEdit").slideUp();
                    var save2list = ($("#shippingSaveToList").prop('checked'))?1:0;
                    $('#hidshippingCityVal').val($('#shippingCity').find(':selected').data('city-id')); //13-03-15
                    $.ajax({
                            type: "POST",
                            url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
                            data: $("form#formCheckoutShipping").serialize()+"&shippingSaveToList="+save2list+"&adrsType=Shipping"+"&sectionType=checkout&shippingCountryID="+$("#shippingCountryID").val(),
                            beforeSend:function()
                            {
                                    //$('#submitCheckoutShipping').hide();
                                    $(".pop_loader").removeClass('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);
                                           // $("#order_summary .totSummary").html(x.summary); 
                                           // if($("#shipping_AmountDiv").length) { //23-04-15
                                                //$("#shipping_AmountDiv").html(x.htmlShipp);
                                            //}
                                            //$(".checkout_shipping_method .payment-first").html($(".pop_loader").html());
                                            //$(".checkout_shipping").slideUp();
                                            //$(".checkout_shipping_method").slideDown(500,function(){
                                                    // $('html,body').animate({
                                                            // scrollTop: $(".checkout_shipping_method").offset().top - 120},
                                                    // 'slow');		
                                            //});
                                           
                                            //$(".checkout_shipping .heading span").show();
                                            //showShippingMethodUpdated();

                                    }
                            },
                            complete:function()
                            { 
                                    //$(".pop_loader").addClass('hide');
                                    //$('#submitCheckoutShippingLoader').hide();
                                    //$('#submitCheckoutShipping').show();
                            }
                    });
                        }
                    }
                    
		}
$(document).on("change","#billingCountry,#billingState,#billingCity,#billingZip,#billingEmail",function(){            
           saveBillling();
        });
	function saveBillling(){
		
	$('#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()
			{
				$(".pop_loader").removeClass('hide'); 
			},
	   		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);
                                        
                                        // if($("#shipping_AmountDiv").length) { //23-04-15
                                            // $("#shipping_AmountDiv").html(x.htmlShipp);
                                        // }
					
					//$(".checkout_billing").slideUp();
					//$(".checkout_billing .heading span").show();
					//$(".checkout_shipping").slideToggle(500);
					//$(".checkout_shipping .heading").addClass('active');
					//$('.checkoutNav .chk-shipping').addClass('active');
					//$('.checkoutNav .chk-billing').addClass('completed');
					//$(".checkout_shipping .heading span").hide();
					// $('html,body').animate({
							// scrollTop:20},
						// 'slow');
				}
			},
			complete:function()
			{ 
				$(".pop_loader").addClass('hide');
			}
			
		});
	}
$('#submitPayment').on("click", function(e) {
        
        showShippingMethod(2); 
        
        if($("#citySelectedType").val()=='province') {
            $("#shippingcityhidValue").val( $("#userProvince").val());
        } else {
            $("#shippingcityhidValue").val( $("#shippingCity").val());
        }
        var save2list = ($("#shippingSaveToList").prop('checked'))?1:0;
        $("#cartShipDetails").val($("#formCheckoutShipping").serialize()+"&shippingSaveToList="+save2list+"&shippingCountryID="+$("#shippingCountryID").val());
        var postData;
        postData = '';
        $('.ajaxCartItems').each(function()
	{
          $('#'+$(this).attr("id")+' :radio').each(function() 
            { 
                    name = $(this).attr('name');
            });
            var reserr = name;
            reserr     = reserr.replace("_", "_val_");
            postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val(); 
                       
	});
        $("#cartShipMethodDetails").val(postData);	
	if($('.processCheckout').find(".message_validation :visible").length>0){  
		return false;	
	}
	
});
// $(document).on("click","#userGender",function(){ 
// $("#div_err_formUserSignup_gender").addClass('hide');
// });   
// $(document).on("change","#dobDay",function(){ 
// $("#div_err_formUserSignup_dobDay").addClass('hide');
// }); 
// $(document).on("change","#dobMonth",function(){ 
// $("#div_err_formUserSignup_dobMonth").addClass('hide');
// }); 
// $(document).on("change","#dobYear",function(){ 
// $("#div_err_formUserSignup_dobYear").addClass('hide');
// }); 
// $(document).on("change","#countryID",function(){ 
// $("#div_err_formUserSignup_countryID").addClass('hide');
// }); 
