/* 
 *Updated for mic
 */
 $('.tab a').click(function(){
		var indexVar =  $(".tab a").index(this);
		$('.tab-cnt').slideUp(300);
		$('.tab-cnt:eq('+indexVar+')').slideDown(500);
		$(".tab a").removeClass('active');
		$(this).addClass('active');
});
/*$('.step .main-tab').click(function(){
		var indexVar =  $(".step .main-tab").index(this);
		$('.main-tab-cnt').slideUp(300);
		$('.main-tab-cnt:eq('+indexVar+')').slideDown(500);
		$(".step .main-tab").removeClass('active');
		$(this).addClass('active');
});*/

 $(document).ready(function(){
	//for hide search box//
	$('.search').css('display','none');
 	$('#common_message').show();
	$("#stateProvinceInput").hide();
	$("#shippingStateProvinceInput").hide();
	$("#shippingStateProvinceInputEdit").hide();
	showPaymentForm();
	$(document).on('change',"#billingCountry", function(){
		listStates($(this).val(), '');
	});
	$(document).on('change',"#shippingCountry", function(){
		listStatesShipping($(this).val(), '');
	});
	$(document).on('change',"#shippingCountryEdit", function(){
		listStatesShippingEdit($(this).val(), '');
	});
	var userConfirmTabs 		= 0;
	var userConfirmBillingTab 	= 0 ;
	var userConfirmShippingTab 	= 0 ;
	var userConfirmShippingMethodTab 	= 0 ;
	if(!$('.checkout_login').length){
		userConfirmTabs = 1;
	}
	$('#billing div').removeClass('main-tab');
	$('.checkout_billing').removeClass('main-tab-cnt');
	$('#delivery div').removeClass('main-tab');
	$('.checkout_shipping').removeClass('main-tab-cnt');
	$('#payment div').removeClass('main-tab');
	$('.checkout_payment').removeClass('main-tab-cnt');

	
		
	
	//for login tab
	$(document).on('click','#login',function(){
		$('#login div span.number').css('background','');
		$('#login div span.number').html('1');
		$('#billing div span.number').html('2');
		$('#billing div span.number').css('background','');
		$('#billing div').removeClass('active');
		$('#delivery div').removeClass('active');
		$('#payment div').removeClass('active');
		$('#billing').removeClass('completed');
		$('#login').removeClass('completed');
		$('.checkout_billing').hide();
		$('#shipping_edit').hide();
		$('.checkout_shipping').hide();
		$('.checkout_payment').hide();
		$('#login div').addClass('active');
		$('.checkout_login').show();
		userConfirmTabs =0;
		userConfirmBillingTab=0;
		userConfirmShippingTab=0;
	});
	// for billing tab
	$(document).on('click','#billing',function(){
		if(userConfirmTabs == 1){
			$('#login div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
			$('#login div span.number').css('background','green');
			$('#login div').removeClass('active');
			$('#login ').addClass("completed");
			$('#billing ').removeClass("completed");
			$('#delivery ').removeClass("completed");
			$('.checkout_login').hide();
			$('#shipping_edit').hide();
			$('.checkout_shipping').hide();
			$('.checkout_payment').hide();
			$('#billing div').addClass('active');
			$('.checkout_billing').show();
		}
		userConfirmBillingTab=0;
		$('#delivery div').removeClass('active');
		$('#payment div').removeClass('active');
		$('#billing div span.number').css('background','');
		$('#billing div span.number').html('2');
	});
	// for delivery tab
	$(document).on('click','#delivery',function(){ 
		if(userConfirmBillingTab == 1){
			$('#billing div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
			$('#billing div span.number').css('background','green');
			$('#login div').removeClass('active');
			$('#billing div').removeClass('active');
			$('#payment div').removeClass('active');
			$('.checkout_login').hide();
			$('.checkout_billing').hide();
			$('.checkout_payment').hide();
				$('#login ').removeClass("completed");
			$('#billing ').addClass("completed");
			$('#delivery ').removeClass("completed");
			$('#delivery div').addClass('active');
			showShippingNormalPage();
			$('.checkout_shipping').show();
		}
		userConfirmShippingTab=0;
		$('#delivery div span.number').css('background','');
		$('#delivery div span.number').html('3');
	});
	//for payment tab
	$(document).on('click','#payment',function(){ 
		if(userConfirmShippingTab == 1){
			$('#billing div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
			$('#billing div span.number').css('background','green');
			$('#delivery div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
			$('#delivery div span.number').css('background','green');
			$('#billing ').removeClass("completed");
			$('#delivery ').addClass("completed");
			$('#login div').removeClass('active');
			$('#billing div').removeClass('active');
			$('#delivery div').removeClass('active');
			$('.checkout_login').hide();
			$('.checkout_billing').hide();
			$('.checkout_shipping').hide();
			$('#payment div').addClass('active');
			$('.checkout_payment').show();
		}
		$('#payment div span.number').css('background','');
		$('#payment div span.number').html('4');
	});
	$(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)
			{ 
				var x = jQuery.parseJSON(data);
				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);
					$('#billing div').removeClass('active');
					//showShippingMethodUpdated();
					showShippingNormalPage();
					$('#delivery div').addClass('main-tab');
					$('#delivery div').addClass('active');
					$('#billing div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
					$('#billing ').addClass("completed");
					$('#login ').addClass("success");
					$('#login ').removeClass("completed");
					$('.checkout_billing').hide();
					$('.checkout_shipping').addClass('main-tab-cnt');
					$('.checkout_shipping').show();
				}
			},
			complete:function()
			{ 
				$('#submitCheckoutBillingLoader').hide();
				$('#submitCheckoutBilling').show();
			}
			
		});

	});
	
	$(document).on("click","#submitCheckoutShipping",function(){
		$('#shippingFname,#shippingLname,#shippingAddress,#shippingCity,#shippingCountry,#shippingZip,#shippingState,#shippingProvince').trigger('blur');
		if(!$(this).validateForm({
			form: "formCheckoutShipping"
		}))
			return false;
		
		var save2list = 1;
		$.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){ 
			var x = jQuery.parseJSON(data);
				if(x.userError =='no_user')
				{
					location.reload();
					return false;
				}
				if(x.validationError=='No')
				{
					//selAddress	=	'';
					//$(".checkout_block").html(x.html);
					//$("#order_summary").html(x.summary);
					$('#shipping_update').hide();
					showShippingNormalPage()
					//$('.shipping_update').remove();
					//$('#checkout_shipping #normal_shipping_page').html(data).trigger('create');
					//$('#checkout_shipping #normal_shipping_page').show();
					
				}
			},
			complete:function()
			{ 
				$('#submitCheckoutShippingLoader').hide();
				$('#submitCheckoutShipping').show();
				$("form#formCheckoutShipping").reset();
			//	alert(selAddress.shippingZip)
				
			}
		});
	
	});
	
	
	$(document).on("click","#submitCheckoutShippingMethod",function(){  
		
		//$('.shippingMethodSelect').triggerHandler('click');

		var postData='';
		var postDataCount	=	0;
		var uncheckedData	=	'';
		var	checkedData		=	'';
		$('.ajaxCartItems').each(function() 
		{
			$('#'+$(this).attr("id")+' :radio').each(function() 
			{ 
				name = $(this).attr('name'); 
				ref		=	$(this).attr('ref');
			});
			if($('input[name='+name+']:radio:checked').length>0){
				postData	+= '-'+name+'~'+$('input[name='+name+']:radio:checked').val();
				postDataCount	=	postDataCount +1;
				if(checkedData!=''){
					checkedData	+= '-';
				}
				checkedData	+= ref;
			}
			else{
				if(uncheckedData!=''){
					uncheckedData	+= '-';
				}
				uncheckedData	+= ref;
			}
		});
			sucData	=	checkedData.split('-');
			sucData	=	jQuery.unique(sucData);
			jQuery.each(sucData,function(i,val){
				$('#hid_err_formCheckoutShippingMethod_shippingMethod_val_'+val).val('');	
				$('#div_err_formCheckoutShippingMethod_shippingMethod_val_'+val).hide();
			});
			
		if($('.ajaxCartItems').length != postDataCount){
			errorData	=	uncheckedData.split('-');
			errorData	=	jQuery.unique(errorData);
			jQuery.each(errorData,function(i,val){
				$('#hid_err_formCheckoutShippingMethod_shippingMethod_val_'+val).val('1');	
				$('#div_err_formCheckoutShippingMethod_shippingMethod_val_'+val).show();
			});
			return false;
		}
		if(!$(this).validateForm({form: "formCheckoutShippingMethod"})){
		return false;
		}
		$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateShippingMethod/",
	   		data: {postData:postData},
			beforeSend:function()
			{
				$('#submitCheckoutShippingMethod').hide();
				$('#submitCheckoutShippingMethodLoader').show();	
			},
	   		success: function(data)
			{ 
				//var x = jQuery.parseJSON(data);
				//$(".checkout_block").html(x.html);
				//$("#order_summary").html(x.summary);
				$('#login div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
				$('#login div span.number').css('background','green');
				$('#billing div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
				$('#billing div span.number').css('background','green');
				$('#delivery div span.number').html('<img src="'+viewPath+'/tick2.png" width="18" height="18" />');
				$('#delivery div span.number').css('background','green');
				$('#billing ').removeClass("completed");
				$('#delivery ').addClass("completed");
				$('#payment div').addClass('main-tab active');
				$('.checkout_payment').addClass('main-tab-cnt');
				userConfirmShippingTab = 1;
				showPaymentInfoUpdated();
			},
			complete:function()
			{ 
				$('#submitCheckoutShippingMethodLoader').hide();
				$('#submitCheckoutShippingMethod').show();
				
			}
		});
		
		
	});
	
	
	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
		{
			$("#submitPayment").hide();
			$("#submitPaymentLoader").show();
			$(".overlay_checkout").show();
		}
	}
	);
	// One page checkout
	$(document).on('click',".checkoutOption",function(){
		userConfirmTabs = 0;
		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",
	function(e){
		if(e.which==13){
			$("#submitLogin").trigger('click');
		}
	});
	$(document).on("click","#submitLogin",function(){  
		$("#shipping_save_to_list").show();
		$("#divPayAddressList").show();
		$("#checkUserExist").val('1');
		$("#div_err_formLogin_checkUserExist").addClass('hide'); 
		if($('.tab a.active').attr('value') == 'guest') 
		{
			$('#guestUserLoginEmail').trigger('blur');
			if($(".message_validation :visible").length>0)
			{ 
				return false; 
			}else{ 
				var userEmail = $("#guestUserLoginEmail").val();
				$.ajax({
					type:"POST",
					url:GLOBAL_BASE_PATH+'/cart/ajaxupdateuseremail/',
					data:'userLoginEmail='+userEmail,
					success:function(msg){
						var x = jQuery.parseJSON(msg);
						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);
							$("#billingEmail").val(userEmail);
							$('.checkout_login .heading').html(lblLogedAsGuest);
							$('#login div').removeClass('active');
							$('#login').addClass('completed');
							$('.checkout_login').slideUp();
							$('#billing div ').addClass('active');
							$('.checkout_billing').show();
							userConfirmTabs = 1;
						}
					}
				});
			}
		}
		else
		{ 
			$('#userLoginEmail, #userLoginPassword').trigger('blur');
			if(!$(this).validateForm({form: "formLogin"})) 
			{
				return false;
			}
			var formData= $("#formLogin").serializeArray();
			formData.push({ name: "submitLogin", value: loginSubmit });
			var isLogin = __loginAjax(formData,'common_message','cart/checkout');
			if(!isLogin){
				userConfirmTabs = 0;
			}
		}
			
	});
	//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) {
				var x = jQuery.parseJSON(data);
				setPromoCharityBlock(x);
				//showPaymentInfoUpdated();
				showShippingNormalPage();
 
			  }
		});
	});
	//one page checkout ends
});
function showShippingNormalPage(){

	$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/checkout/",
			async: false,
	   		data: "ajax="+1+"&pagename=ShippingNormal",
			success: function(data){ 
				$('#shipping_update').hide;
				$('#checkout_shipping #showShippingSelectedAddress').empty().html(data).trigger('create');
				$('#checkout_shipping #normal_shipping_page').show();
			},
			complete:function(){
				showShippingMethodUpdated(selAddress);
			}
		});
		$('#checkout_shipping #shipping_update').hide();
}
/*function showShippingAddPage(){
	
	$('#checkout_shipping #shipping_update').remove();
	$('#checkout_shipping #normal_shipping_page').after('<div id="shipping_update" class="shipping_update"></div>');
	$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/checkout/",
	   		data: "ajax="+1+"&pagename=ShippingAdd",
	   		success: function(data){ 
				$('#checkout_shipping #shipping_update').html(data);
			}
		});
}*/
function showShippingAddPage(){
	
	//$('#checkout_shipping #shipping_update').remove();
	//$('#checkout_shipping #normal_shipping_page').after('<div id="shipping_update" class="shipping_update"></div>');
	
	$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/checkout/",
	   		data: "ajax="+1+"&pagename=ShippingAdd",
	   		success: function(data){ 
				$('#shipping_update #shipping_change').html(data);
			}
		});
		
		$('#checkout_shipping #shipping_update').css('display','block');
	//	$('#formCheckoutShipping').reset();
}
function applyPromoCode()
{
	var promoCode 	= $("#promoCode").val();
	$.ajax({
		type: "POST",
		url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateAddress/",
		data: {applyPromo: 'Yes',promoCode:promoCode},
		success: function (data) {
			var x = jQuery.parseJSON(data);
			//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')
			{ 
				
				jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_success");
			}
			showShippingNormalPage();
		}
	});
	return false;
}  
function removePromoCode()
{
	$.ajax({
	type: "POST",
	url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateAddress/",
	data: {removePromo: 'Yes',promoCode:''},
	success: function (data) {
		var x = jQuery.parseJSON(data);
		if(x.promoData.promoError=='Yes')
			{
				jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_error"); 
				$("#promoCode").val('');
				$("#couponCode").val('');
			}
			else if(x.promoData.promoError=='No')
			{ 
				
				jNotifyShowWithClose(x.promoData.promoErrMsg,"promo_message", "message_success");
			}
			showShippingNormalPage();
	}
	});
	  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('');
					$("#billingState option").each(function(){
						if($(this).val() == data.stateID)
						$('#billingState-button span').text($(this).text());
					});
				} 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());
}
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){ 
		var x = jQuery.parseJSON(data);
			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{
				//	$('.checkout_payment .heading').addClass('active');
				//}
				displayPaymentDetails();
				$('#delivery div').removeClass('active');
				$('#payment div').addClass('active');
				$('.checkout_shipping ').hide();
				$('.checkout_payment').show();
			}
		},
		complete:function()
		{ 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
		}
	});
}
function showShippingMethodUpdated(shipAddress){
	if(shipAddress.shippingStateID>0){shipAddress.shippingStateSelectedType ="state"}else{shipAddress.shippingStateSelectedType ="provice"}
	var selectedShipAddressData = "shippingZip="+shipAddress.shippingZip+"&shippingState="+shipAddress.shippingStateID+"&shippingCountry="+shipAddress.shippingCountryID+"&shippingStateSelectedType="+shipAddress.shippingStateSelectedType
	$.ajax({
   		type: "POST",
   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateAddress/",
   		data: selectedShipAddressData+"&adrsType=ShippingMethod",
   		beforeSend:function()
		{
			$('#submitCheckoutShipping').hide();
			$('#submitCheckoutShippingLoader').show();	
		},
		success: function(data){ 
		var x = jQuery.parseJSON(data);
			if(x.userError =='no_user')
			{
				location.reload();
				return false;
			}
			if(x.validationError=='No'){
			//	alert(data);
				$("#order_summary").empty().html(x.html).trigger('create');
				$("#order_summary").show();
			}
		},
		complete:function()
		{ 
			$('#submitCheckoutShippingLoader').hide();
			$('#submitCheckoutShipping').show();
		}
	});
}
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($){ 
	$(document).on("blur",'#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone,#shippingFname,#shippingLname,#shippingAddress,#shippingAddress1,#shippingProvince,#shippingCity,#shippingZip',function(){
		validate($(this));
    });
	
		
	$('#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone,#shippingFname,#shippingLname,#shippingAddress,#shippingAddress1,#shippingProvince,#shippingCity,#shippingZip').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;
}
////////////////////////////////////////////// new script //////////////////////////

$(document).on("click",'#shippingedit',function(){
	$('#normal_shipping_page').hide();
	showShippingAddPage();
});
$(document).on("click","input[name='changeUserShippingAddress']",function(){ 
	var shipID			=	$(this).attr('rel');
	var selectedAddress	=	address[shipID];
	var addrressArr	= "shippingStateID="+selectedAddress.shippingStateID+"&userShippingID="+selectedAddress.userShippingID+"&shippingFname="+selectedAddress.shippingFname+"&shippingLname="+selectedAddress.shippingLname+"&shippingAddress1="+selectedAddress.shippingAddress1+"&shippingAddress2="+selectedAddress.shippingAddress2+"&shippingCity="+selectedAddress.shippingCity+"&shippingProvince="+selectedAddress.shippingProvince+"&shippingZip="+selectedAddress.shippingZip+"&shippingCountryID="+selectedAddress.shippingCountryID
	$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxUpdateSelectedAddress/",
			data: addrressArr+"&adrsType=Shipping",
	   		success: function(data){ 
			showShippingNormalPage();	
			}
			
		});
	
	});
//For Shipping Edit
function listStatesShippingEdit(countryID, stateID) {
		$("#loadProcessImageShippingEdit").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 != '') {
					$("#shippingStateInputEdit").show();
					$('#shippingStateEdit').empty();
					$("#shippingStateProvinceInputEdit").hide();
					$("#shippingStateEdit").append('<option value="">' + selecttext + '</option>' + msg);
					$("#shippingStateSelectedTypeEdit").val("state");
					$("#shippingProvinceEdit").val('');
					$("#shippingStateEdit option").each(function(){
						if($(this).val() == data.stateID){
							$('#shippingStateEdit-button span').text($(this).text());
						}
					});
				} else {
					$("#shippingStateInputEdit").hide();
					$("#shippingStateProvinceInputEdit").show();
					
					if(!(stateID>=0 || stateID==''))
						$("#shippingProvinceEdit").val(stateID);
					$("#shippingStateSelectedTypeEdit").val("province");
						$("#shippingStateEdit").empty()
						$("#shippingStateIDEdit").val('');
				}
				$("#loadProcessImageShippingEdit").empty();
			}
		});
	}
$(document).on("click",".edit",function(){ 
		var shipID	=	$(this).attr('rel');
		var data = address[$(this).attr('rel')];
		$("#userID").val(data.userID);
		$("#shippingstatehidValueEdit").val(data.shippingStateID);
        $("#userShippingIDEdit").val(data.userShippingID);
        $("#shippingFnameEdit").val(data.shippingFname);
        $("#shippingLnameEdit").val(data.shippingLname);
        $("#shippingAddressEdit").val(data.shippingAddress1);
        $("#shippingAddress1Edit").val(data.shippingAddress2);
        $("#shippingCityEdit").val(data.shippingCity);
        $("#shippingProvinceEdit").val(data.shippingProvince);
        $("#shippingZipEdit").val(data.shippingZip);
		$("#shippingCountryIDEdit").val(data.shippingCountryID);
		$("#shippingCountryEdit > option").each(function(){
				if($(this).val() == data.shippingCountryID){
					$('#shippingCountryEdit-button span').text($(this).text());
					$(this).attr('selected','selected');
				}
			});
        listStatesShippingEdit(data.shippingCountryID, data.shippingStateID);
		$('#shipping_update').hide();
		$('#shipping_edit').show();

});
$(document).on("click","#submitCheckoutShippingEdit",function(){
		$('#shippingFnameEdit,#shippingLnameEdit,#shippingAddressEdit,#shippingCityEdit,#shippingCountryEdit,#shippingZipEdit,#shippingStateEdit,#shippingProvinceEdit').trigger('blur');
		
		if(!$(this).validateForm({
			form: "formCheckoutShippingEdit"
		})){
			return false;}
		var save2list = 1;
		$.ajax({
	   		type: "POST",
	   		url: GLOBAL_BASE_PATH+"/cart/ajaxEditShippingAddress/",
	   		data: $("form#formCheckoutShippingEdit").serialize()+"&shippingSaveToList="+save2list+"&adrsType=Shipping",
	   		success: function(data){ 
			var x = jQuery.parseJSON(data);
				if(x.validationError=='No')
				{
				userConfirmShippingTab = 1;
				$(".checkout_block").html(x.html);
				$("#order_summary").html(x.summary);
				$('#shipping_edit').hide();
				showShippingNormalPage()
				}
			}
			
		});
	
});
$(document).on('click','.delete',function(){
	var shipID	=	$(this).attr('rel');
	$.ajax({
		type: "POST",
		url	: GLOBAL_BASE_PATH+"/cart/ajaxDeleteShippingAddress/",
		data: "shipID="+shipID,
		success:function(msg){
			if(msg){
				$('#shipping_update').hide();
				showShippingNormalPage()
			
			}
		}	
	});


});
