/*
@Javascript for buy now functionalities
@Usage product details page/product quick view page
@Created 01-06-213 
*/

var combinationHash;
var combinationHashFree;
var ajaxResponse = new Object();
var ajaxBusDetResponse = new Object();
var basePrice;
var cashbackPrice;
var userUploadedImageArray;
var buyNowButtonElm;
var buybox;
var basePriceFree;
var encodedCombinationsFree;
var encodedCustomOptionsFree;
function setTabPosition (){
    var windowWidth =$(window).width();
    var navItemPositionCurrent = $(".nav-link.active").offset().left;
    if(languageDir == 'rtl'){
        if(navItemPositionCurrent<0){
            navItemPositionCurrent = Math.abs(navItemPositionCurrent);
            navItemPositionCurrent = parseFloat(navItemPositionCurrent) + parseFloat(windowWidth)  ;
        }
    }
    if(languageDir == 'ltr'){
    var navItemWidth = $(".nav-link.active").outerWidth();
    var navItemPosition = navItemPositionCurrent + navItemWidth;
    }
    else{
        var navItemPosition = navItemPositionCurrent;
    }
    var containerUl     = $("#productdetailTab");
    if(languageDir == 'ltr'){
        var containerUlposition = $("#productdetailTab").css("left");
        containerUlposition = containerUlposition.replace("-", "");
        containerUlposition = containerUlposition.replace("px", '');
    }
    else{
        var containerUlposition = $("#productdetailTab").css("right");
        containerUlposition = containerUlposition.replace("-", "");
        containerUlposition = containerUlposition.replace("px", '');
    }
    if (windowWidth < navItemPosition){
        var navPosition = navItemPosition - windowWidth;
        var navPositionNew = parseFloat(navPosition) + parseFloat(containerUlposition);
        if(languageDir == 'ltr'){
          $("#productdetailTab").attr('style','left : -'+navPositionNew+'px');
        }
        else{
          $("#productdetailTab").attr('style','right : -'+navPositionNew+'px');
        }
    }
}  

$(document).ready(function (){
	if (typeof productDefaultCurrency != 'undefined') 
	{
		resetCurrency(productDefaultCurrency);
	}
    //Event triger while click on bundle  product detail page buy now button
    $(document).on('click', '.buynow_Bundle_link', function (event) {
		var msgDivID = typeof isQuickView == 'undefined' ? 'common_message' : 'poppup_common_message';
		 var post_data = new Object();
		 handleBuySubmit();
		  post_data = $( ":input" ).serializeArray();
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxAddItemCart/",
                data: post_data,
				async: false,
                success: function (data) {
					
					if(data){
                    var x = jQuery.parseJSON(data);
					if (typeof x.isError != 'undefined' && x.isError == 'Yes') 
					{
                        jNotifyShow(x.error, msgDivID, "message_error");
						return false;
                        //closeBuynowPopUp();
                    } 
				}
					
						window.location = GLOBAL_BASE_PATH + "/cart/";
                    
                }
            });		
  });
  //Event triger while click on product detail page buy now button
    $(document).on('click', '.buynow_link', function (event) {
		
        var freeProduct = $(this).attr('free');
        freeProduct = (typeof freeProduct == 'undefined' || freeProduct=='') ? '' : freeProduct;
        
        //Product custom options validation
        if(freeProduct=='') {
            var frmname = 'formProductOptions';
        }
        else {
             var buyParams = $(this).attr('rel').split("-");
             var frmname   = 'formProductOptionsFree_'+buyParams[2]+'_'+buyParams[0];
             
        }
        if (!$(this).validateForm({
            form: frmname
        })){
		
			//closeBuynowPopUp(this);
			/*if($(this).hasClass('buynowCart')){
				jAlert(msgAddtoCartValidation);
			}   */  
            //alert("bbbbbb");
//return false;
                        var scrollTopnew=$('.hid_err_'+frmname+'_validations'+"[value=1]:first").closest('div:visible').position().top;
                        scrollTopnew = scrollTopnew;
                        var elementOffset = $('.hid_err_'+frmname+'_validations'+"[value=1]:first").closest('div:visible').offset().top;                        
			$('html,body').animate({scrollTop:elementOffset},'slow');                        
                        return false;
		}else{

		}
        //Product custom options validation ends here

        var hasImageUpload = $('#hasImageUpload').val();
        buyNowButtonElm = $(this);
        if (hasImageUpload == 1) { //If product have file upload type custom option
            $.when(asyncCall()).then(function () {});
			if($(this).hasClass('buynowCart')){
				jAlert(errImage);
			}			
            return false;
        } else {
            /*if($(this).hasClass('buynowCart')){ 
                    redirect_to_cart_page_on_add_to_cart_click = 'Yes';
            }
            else
            {
                    redirect_to_cart_page_on_add_to_cart_click = 'No';
            }  */                      
            buynow_link(buyNowButtonElm); //If product dn't have file upload type custom option
        }
    });
    $(".close-icon").on('click',function(){
            
           if($(this).attr('rel')!='') {
               window.location = GLOBAL_BASE_PATH + "/cart/";
           } else {
            var totQty =0 ;
            for (var i = 0; i < cart["items"].length; i++) {
                 totQty = parseFloat(totQty) + parseFloat(Number(cart["items"][i]["orderItemQuantity"]));
            }
            var showmsg = lblThere+" "+totQty+" ";
                                                 if(parseFloat(totQty)>1) {
                                                     showmsg = showmsg+lblItemsInShopping;
                                                 } else {
                                                     showmsg = showmsg+lblItemInShopping;
                                                 }
            jAlertCustom(showmsg);
            $("#popup_container").addClass('addcartpopup');
           }
    });                                                      

    $(document).on('change', '.fileUpload', function () {
        $(this).nextAll(".hiddenField").first().val($(this).val());
    });
    $(document).on('click', '.productOptionsChangeLink', function () {
        var productOptionId = this.id;
         var optBusinessID   = this.rel;
        $(".option_title").empty().html(this.title);
        changeProductOption(productOptionId,optBusinessID);
    });
    $(document).on('click', '.productOptionsChangeLinkFree', function () {
        var productOptionId = $(this).val();        
        //changeProductOptionFree(productOptionId);
    });
//    $(document).on('change', '.custom_option', function () {
//        changeCombinationImage(combinationHash, $("#selectedProductOption").val(), selectedProductID);
//    });

    if (typeof selectedProductID != 'undefined') {
        productOptionID = $("#selectedProductOption").val();
        if (typeof encodedCartItemDetails != 'undefined') {
            if (typeof encodedCartItemDetails.combinationValues != 'undefined' && encodedCartItemDetails.combinationValues != null) {
                if (typeof encodedCartItemDetails.combinationValues.customOption != 'undefined') {
                    $.each(encodedCartItemDetails.combinationValues.customOption, function () {
                        customOptionID = Number(this.customOptionID);
                        customOptionVariantID = Number(this.customOptionVariantID);
                        $("#option_" + selectedProductID + "_" + customOptionID + " [value=" + customOptionVariantID + "]").attr("selected", "selected");
                    });
                }
            }
        }
        if (typeof encodedCartItemDetails != 'undefined') {
            if (typeof encodedCartItemDetails.customOptionValues != 'undefined' && encodedCartItemDetails.customOptionValues != null) {
                $.each(encodedCartItemDetails.customOptionValues, function () {
                    $.each(this, function () {
                        customOptionID = Number(this.customOptionID);
                        customOptionVariantID = Number(this.customOptionVariantID);
                        var tempElement = $("#option_" + selectedProductID + "_" + customOptionID);
                        if (tempElement.is(':checkbox')) {
                            $(".option_" + selectedProductID + "_" + customOptionID + "[value=" + customOptionVariantID + "]").attr("checked", "checked");
                        } else if (tempElement.is("select")) {
                            $("#option_" + selectedProductID + "_" + customOptionID + " [value=" + customOptionVariantID + "]").attr("selected", "selected");
                        } else if (tempElement.is(':file')) {
                            //$("#option_"+selectedProductID+"_"+customOptionID).val('');
                            $("#option_" + selectedProductID + "_" + customOptionID).css("opacity", "2");
                            $("#option_" + selectedProductID + "_" + customOptionID).text(this.variantValueText)
                            $("#file_name_option_" + selectedProductID + "_" + customOptionID).text(this.variantValueText)
                            tempElement.nextAll(".hiddenField").first().val(1);
                            $("#uploadedImage_" + selectedProductID + "_" + customOptionID).val(this.variantValueText)
                            //console.log(tempElement)
                        } else {
                            $("#option_" + selectedProductID + "_" + customOptionID).val(this.variantValueText);
                        }
                    });
                });
            }
        }
       // fn_change_options('', selectedProductID);      
        if (combinationHash != '') {
            //changeCombinationImage(combinationHash, productOptionID, selectedProductID);
        }
    }

    $('.QuantityBox').keypress(function (e) {
        var a = [];
        var k = e.which;
        for (i = 48; i < 58; i++)
            a.push(i);
        if (!(a.indexOf(k) >= 0))
            e.preventDefault();
    });
	 $('.icon-close').click(function(){
        $('#Summary-tab').trigger('click');
    });
    $('#Summary-tab').click(function(){
        buynow_link($(this));
		update_payment_loan_summary();
    });
	$('.saveConfig').click(function(){
		$(".pop_loader").removeClass('hide');
		buynow_link($(this));
		$.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/saveProductConfig/",
                async: true,
                success: function (data) {                   
                    $(".pop_loader").addClass('hide');
                    if(data == 'success'){
                        $('#configThx').modal('show');
						return false;
                    }
                }
            })
    });
    $('#Payment-tab-new').click(function(){ 
         
        update_payment();
         $('#payUserName, #payUserPhone, #payUserEmail').val('');    
        //$('#paysubtitle').val('Mr.'); 
		$("#paysubtitle").val($("#paysubtitle option:first").val());
        $('#payment-screen-1').removeClass('d-none');
        $('#payment-screen-2').addClass('d-none');
        $('#payment-screen-3').addClass('d-none');
        $('.payotpfield').val('');
    })
    $('#Payment-tab').click(function(){
        
        /*if(typeof cart.cartID != 'undefined')
            update_payment();
        else{*/
        //if(fromCheckout!='payment') {
            buynow_link($(this));
        //}
            update_payment(); 
        /*}*/
        $('#payUserName, #payUserPhone, #payUserEmail').val('');    
        //$('#paysubtitle').val('Mr.'); 
		$("#paysubtitle").val($("#paysubtitle option:first").val());
        $('#payment-screen-1').removeClass('d-none');
        $('#payment-screen-2').addClass('d-none');
        $('#payment-screen-3').addClass('d-none');
        $('.payotpfield').val('');
    })
    $('.continue-btn').click(function(){
        if($('.nav-link.active').parent().next().children('a').attr('aria-controls')!='Summary' && $('.nav-link.active').parent().next().children('a').attr('aria-controls')!='Payment')
	{
            $('.nav-link.active').parent().next().children('a').trigger('click');
        setTabPosition();
        }else{
            if($('.nav-link.active').parent().next().children('a').attr('aria-controls')=='Summary')
            {
                $('.nav-link.active').parent().next().children('a').trigger('click');setTabPosition();
            }
            else if($('.nav-link.active').parent().next().children('a').attr('aria-controls')=='Payment')
            {
                $('.nav-link.active').parent().next().children('a').trigger('click');setTabPosition();
            }
        }
    });
	$('.continue-btn-calculator').click(function(){
        $('.nav-link.active').trigger('click');
    });
    
    $('#summaryDownloadBtn').click(function(){
        $('#userFirstName,#userLastName,#userEmail,#userPhone').blur();
        checkAgree(1);
        if($('.message_validation:visible').length>0){
            return false;
        }else{
            sendOTPData();
        }
    });
	$('#broucherDownloadBtn').click(function(){
        $('#userFirstName,#userLastName,#userEmail,#userPhone').blur();
        checkAgree(1);
        if($('.message_validation:visible').length>0){
            return false;
        }else{
			sendBroucherOTPData();
        }
    });
    $(document).on('click','#agree',function() {
        if($(this).prop('checked')) {
            $("#hid_err_formDownloadProductInfo_validateAgree").val(0);           
        } else {
            $("#hid_err_formDownloadProductInfo_validateAgree").val(1);   
        } 
        checkAgree(1);
    });
    $(document).on('click','#cbagree',function() {
        if($(this).prop('checked')) {
            $("#hid_err_formReqCallBack_cbvalidateAgree").val(0);           
        } else {
            $("#hid_err_formReqCallBack_cbvalidateAgree").val(1);   
        } 
        checkAgree(2);
    });
    $(document).on('click','#payagree',function() {
        if($(this).prop('checked')) {
            $("#hid_err_formPaymentContactInfo_payvalidateAgree").val(0);           
        } else {
            $("#hid_err_formPaymentContactInfo_payvalidateAgree").val(1);   
        } 
        checkAgree(3);
    });
    
    $('#download-product-info-otp-submit').click(function(){
        if($('#userotp1').val()=='' || $('#userotp2').val()=='' || $('#userotp3').val()==''|| $('#userotp4').val()==''){
            $('.otp_validateion_error').removeClass('hide');
            return false;
        }else{
            checkSubmittedOTP()
        }
        
    });
	$('#download-broucher-otp-submit').click(function(){
        if($('#userotp1').val()=='' || $('#userotp2').val()=='' || $('#userotp3').val()==''|| $('#userotp4').val()==''){
            $('.otp_validateion_error').removeClass('hide');
            return false;
        }else{
            checkSubmittedBroucherOTP()
        }
        
    });
    $('#userotp1,#userotp2,#userotp3,#userotp4').blur(function(){
        $('.otp_validateion_error').addClass('hide');
    })
    $('#callbackotp1,#callbackotp2,#callbackotp3,#callbackotp4').blur(function(){
        $('.cb_validateion_error').addClass('hide');
    })
    $('.close-download-info').click(function(){
        refreshdownloadinfo()
    });
    
    $('.otpfield').keyup(function(){
        $('.otpfield').eq($('.otpfield').index(this)).focus()
    });
    
    $('#summaryReqCallBack').click(function(){ 
        $("#summaryReqCallBack").addClass('disabled');
        $('#cbUserFirstName,#cbUserLastName,#cbUserEmail,#cbUserPhone').blur();
        checkAgree(2);
        if($('.message_validation:visible').length>0){
            $("#summaryReqCallBack").removeClass('disabled');
            return false;
        }else{
            sendCBOTPData();
        }
    });
    
    $('#callback-otp-submit').click(function(){
	checkSubmittedCBOTP()
	});
    $('.cb-close').click(function(){
        refreshcallbackinfo()
    });
    
$('.cbotpfield').keyup(function(){
        $('.cbotpfield').eq($('.cbotpfield').index(this)).focus()
    });    
    
$('#proceedcheckout').click(function(){
    $("#proceedcheckout").addClass('disabled');
//    $("#proceedcheckout").addClass('hide');
//    $("#proceedcheckoutdisabled").removeClass('hide');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxcheckout/",
                data: { subtitle:$('#paysubtitle').val(), username:$('#payUserName').val(),useremail: $('#payUserEmail').val(),userphone: $('#payCountrycode').val()+' '+$('#payUserPhone').val(),paymentSettingsGroupKey:'CashOnDeliveryRedemption'},
                async: true,
                success: function (data) {
                    var result = JSON.parse(data);
                    if(result.result == 'success'){
                        window.location.href = siteUrl+'/payment/index/type/'+result.type+'/id/'+result.orderid+'/';
                    }else{
//                        $("#proceedcheckoutdisabled").addClass('hide');
//                        $("#proceedcheckout").removeClass('hide');
                        $("#proceedcheckout").removeClass('disabled');
                        return false; 
                    }
                }
        })
});

$('#Summary-tab, #Showroom-tab, .custopts, #Packages-tab').click(function(){
	resetpaymenttab();
})
//getCombination(colorCustID,'Color');

$("#requestacallback").on('show.bs.modal', function(){
        $('#cbUserFirstName, #cbUserLastName, #cbUserEmail, #cbUserPhone, #cbUserComment').val('');
        //$('#cbsubtitle').val('Mr.');
		$("#cbsubtitle").val($("#cbsubtitle option:first").val());
        $('.cbotpfield').val('');
	$('#cbCountrycode').val('971');
	$('.request-callback-form-blk').removeClass('hide');
	$('.request-callback-otp-blk').addClass('hide');
	$('.callback-thankyou-blk').addClass('hide');
        $('#summaryReqCallBack').removeClass('disabled');
  });
  $(document).on("submit","#formSummaryContactInfo",function(){
	  $("#submitSummaryForm").addClass('disabled');
	 var fullname = $("#firstname").val()+' '+ $("#lastname").val();
	 var subtitle = $("#subtitle").val();
	 var fname = $("#firstname").val();
	 var lname = $("#lastname").val();
	 var payCountrycode = $("#payCountrycode").val();
	 var email  = $("#emailID").val();
	 var phone= $("#phone").val();
	 
     $.ajax({
		type: "POST",
		async:true, 
		url: GLOBAL_BASE_PATH + "/product/ajaxLoanSummary/",
		data:$(this).serialize(),
		success: function (data) 
		{  
		 if(data){
				  var x = jQuery.parseJSON(data);
				  if(x > 0){
					$('#loanThx').modal('show');
					 $("#submitSummaryForm").removeClass('disabled');
					$('#contactName').html(fname+' '+lname);
					 $("#hiddensubtitle").val(subtitle);
					  $("#hiddenfname").val(fname);
					  $("#hiddenlname").val(lname);
					  $("#hiddenphonecode").val(payCountrycode);
					  $("#hiddenemail").val(email);
					  $("#hiddenphone").val(phone);
					  $("#firstname").val('');
					  $("#lastname").val('');
					  $("#phone").val('');
					  $("#emailID").val('');
					  $("#location").val('');
					  $("#monthlyincome").val('');
					  $("#totalcreditcardlimit").val('');
					  $("#loanmonthlyPayment").val('');
					  $("#payagreeloan").val(0);
					  $('input[type=checkbox]').prop('checked', false);
					return false;
				  }
			} 
		
		}
		
		});
		return false;
   
   });
   $('#loan-continue').click(function(){ 
	$('#loanThx').modal('hide');
	$("#Payment-tab").show();
	var hiddensubtitle=$("#hiddensubtitle").val();
	var hiddenfname=$("#hiddenfname").val();
	var hiddenlname=$("#hiddenlname").val();
	$("#paysubtitle option[value='" + hiddensubtitle + "']").attr("selected","selected");
	$("#payUserName").val(hiddenfname+' '+hiddenlname);
	$("#payCountrycode").val($("#hiddenphonecode").val());
	$("#payUserPhone").val($("#hiddenphone").val());
	$("#payUserEmail").val($("#hiddenemail").val());
	});
	$(document).on('click', '#summary-form', function(e){ 
        e.preventDefault();
        $("#summury-main-blk").addClass("d-none");
		$("#finance-calculator-blk").addClass("d-none");
		$("#lease-calculator-blk").addClass("d-none");
        $("#summary-form-blk").removeClass("d-none");
      });
});
function checkAgree(arg) {
    if(arg==1) {
        if($("#hid_err_formDownloadProductInfo_validateAgree").val()!='0') {
            $("#div_err_formDownloadProductInfo_validateAgree").removeClass('hide');
        } else {
            $("#div_err_formDownloadProductInfo_validateAgree").addClass('hide');
        }
    } else
    {
        if(arg==2) {
           if($("#hid_err_formReqCallBack_cbvalidateAgree").val()!='0') {
               $("#div_err_formReqCallBack_cbvalidateAgree").removeClass('hide');
           } else {
               $("#div_err_formReqCallBack_cbvalidateAgree").addClass('hide');
           }
       } else {
            if($("#hid_err_formPaymentContactInfo_payvalidateAgree").val()!='0') {
               $("#div_err_formPaymentContactInfo_payvalidateAgree").removeClass('hide');
           } else {
               $("#div_err_formPaymentContactInfo_payvalidateAgree").addClass('hide');
           }
       }
    }
}
function checkSubmittedCBOTP(){
    if($('#callbackotp1').val() == '' || $('#callbackotp2').val() == '' || $('#callbackotp3').val() == '' || $('#callbackotp4').val() == ''){
        $('.cb_validateion_error').removeClass('hide');
        return false;
    }
    $("#callback-otp-submit").addClass('disabled');
    var otp =   $('#callbackotp1').val()+''+$('#callbackotp2').val()+''+$('#callbackotp3').val()+''+$('#callbackotp4').val();
    
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/checkSentCBSms/",
                data: { otp: otp},
                async: true,
                success: function (data) {
                    if(data == 'success'){
                        $("#callback-otp-submit").removeClass('disabled');
                        submitCallbackData()
                        $('.request-callback-otp-blk').addClass('hide');
                        $('.callback-thankyou-blk').removeClass('hide');
                        $('.cb_validateion_error').addClass('hide');
						 refreshcallbackinfo()
                        return false;
                    }else{
                        $("#callback-otp-submit").removeClass('disabled');
                        $('.cb_validateion_error').removeClass('hide');
                        return false;
                    }
                }
        })
}
	
function sendCBOTPData(){
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUserCallback/",
                cache: false, 
                async:true, 
                data: { userPhone: $('#cbCountrycode').val()+''+$('#cbUserPhone').val(),userEmail: $('#cbUserEmail').val(),userName: $('#cbUserFirstName').val(),subtitle: $('#cbsubtitle').val()},
                beforeSend: function(){
                    $("#summaryReqCallBack").addClass('disabled');
                   },
                success: function (data) {                   
                    if(data == 'success'){
                        $("#summaryReqCallBack").removeClass('disabled');
                         $('.phoneassign').html($('#cbUserPhone').val());
						 $('.emailassign').html($('#cbUserEmail').val());
                         $('.request-callback-form-blk').addClass('hide');
                         $('.request-callback-otp-blk').removeClass('hide');
                        return false;
                    }else{
                        $("#summaryReqCallBack").removeClass('disabled');
                    }
                }
            })
}

function resendCBOTPData(){
    $(".resend").addClass('hide');
    $(".resending").removeClass('hide');
    $('#callback-otp-submit').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUserCallback/",
                cache: false, 
                async:true, 
                data: { userPhone: $('#cbCountrycode').val()+''+$('#cbUserPhone').val(),userEmail: $('#cbUserEmail').val(),userName: $('#cbUserFirstName').val(),subtitle: $('#cbsubtitle').val()},
                beforeSend: function(){
                    $(".resend").addClass('hide');
                    $(".resending").removeClass('hide');
                   },
                success: function (data) {                   
                    $(".resend").removeClass('hide');
					$(".resending").addClass('hide');
					$('#callback-otp-submit').removeClass('disabled');
                    if(data == 'success'){
                        $(".resend").removeClass('hide');
						$(".resending").addClass('hide');
						$('#callback-otp-submit').removeClass('disabled');
                        $('.phoneassign').html($('#cbUserPhone').val());
						$('.emailassign').html($('#cbUserEmail').val());
                        $('.request-callback-form-blk').addClass('hide');
                        $('.request-callback-otp-blk').removeClass('hide');
                        return false;
                    }else{
                        $(".resend").removeClass('hide');
						$(".resending").addClass('hide');
						$('#callback-otp-submit').removeClass('disabled');
                    }
                }
            })
    $(".pop_loader").addClass('hide');
}

function checkSubmittedOTP(){
    var otp =   $('#userotp1').val()+''+$('#userotp2').val()+''+$('#userotp3').val()+''+$('#userotp4').val();
    $('#download-product-info-otp-submit').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/checkSentSms/",
                data: { otp: otp},
                async: true,
                success: function (data) {
                    $('#download-product-info-otp-submit').removeClass('disabled');
                    if(data == 'success'){
                        $('.download-product-info-otp-blk').addClass('hide');
                        $('.download-product-info-thankyou-blk').removeClass('hide');
                        $('.otp_validateion_error').addClass('hide');
                        submitDownloadData()
                        return false;
                    }else{
                        $('.otp_validateion_error').removeClass('hide');
                        return false;
                    }
                }
        })
}
function checkSubmittedBroucherOTP(){
    var otp =   $('#userotp1').val()+''+$('#userotp2').val()+''+$('#userotp3').val()+''+$('#userotp4').val();
    $('#download-broucher-otp-submit').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/checkSentBroucherSms/",
                data: { otp: otp},
                async: true,
                success: function (data) {
                    $('#download-broucher-otp-submit').removeClass('disabled');
                    if(data == 'success'){
                        $('.download-product-info-otp-blk').addClass('hide');
                        $('.download-product-info-thankyou-blk').removeClass('hide');
                        $('.otp_validateion_error').addClass('hide');
                        submitDownloadBroucherData()
                        return false;
                    }else{
                        $('.otp_validateion_error').removeClass('hide');
                        return false;
                    }
                }
        })
}

function sendOTPData(){
	$('#summaryDownloadBtn').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUser/",
                data: { userPhone: $('#countrycode').val()+' '+$('#userPhone').val(),userEmail: $('#userEmail').val(),userName: $('#userFirstName').val(),subtitle: $('#subtitle').val()},
                async: true,
                success: function (data) {
				$('#summaryDownloadBtn').removeClass('disabled');
                    if(data == 'success'){
                         $('.phoneassign').html($('#userPhone').val());
						 $('.emailassign').html($('#userEmail').val());
                         $('.download-product-info-form-blk').addClass('hide');
                         $('.download-product-info-otp-blk').removeClass('hide');
                        return false;
                    }
                }
            })
}
function sendBroucherOTPData(){
	$('#broucherDownloadBtn').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToBroucher/",
                data: { userPhone: $('#countrycode').val()+' '+$('#userPhone').val(),userEmail: $('#userEmail').val(),userName: $('#userFirstName').val(),subtitle: $('#subtitle').val()},
                async: true,
                success: function (data) {
				$('#broucherDownloadBtn').removeClass('disabled');
                    if(data == 'success'){
                         $('.phoneassign').html($('#userPhone').val());
						 $('.emailassign').html($('#userEmail').val());
                         $('.download-product-info-form-blk').addClass('hide');
                         $('.download-product-info-otp-blk').removeClass('hide');
                        return false;
                    }
                }
            })
}
function resendOTPData(){
    $('.otp_validateion_error').addClass('hide');
	$('#download-product-info-otp-submit').addClass('disabled');
	$('.resenddownloadotp').addClass('hide');
	$('.resendingdownloadotp').removeClass('hide');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUser/",
                data: { userPhone: $('#countrycode').val()+' '+$('#userPhone').val(),userEmail: $('#userEmail').val(),userName: $('#userFirstName').val(),subtitle: $('#subtitle').val()},
                async: true,
                success: function (data) {
                    $('#download-product-info-otp-submit').removeClass('disabled');
					$('.resenddownloadotp').removeClass('hide');
					$('.resendingdownloadotp').addClass('hide');
                    if(data == 'success'){
                         $('.phoneassign').html($('#userPhone').val());
						 $('.emailassign').html($('#userEmail').val());
                        return false;
                    }
                }
            })
}

function resendBroucherOTPData(){
    $('.broucher_otp_validateion_error').addClass('hide');
	$('#download-broucher-otp-submit').addClass('disabled');
	$('.resenddownloadbroucherotp').addClass('hide');
	$('.resendingdownloadbroucherotp').removeClass('hide');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToBroucher/",
                data: { userPhone: $('#countrycode').val()+' '+$('#userPhone').val(),userEmail: $('#userEmail').val(),userName: $('#userFirstName').val(),subtitle: $('#subtitle').val()},
                async: true,
                success: function (data) {
                    $('#download-broucher-otp-submit').removeClass('disabled');
					$('.resenddownloadotp').removeClass('hide');
					$('.resendingdownloadotp').addClass('hide');
                    if(data == 'success'){
                         $('.phoneassign').html($('#userPhone').val());
						 $('.emailassign').html($('#userEmail').val());
                        return false;
                    }
                }
            })
}
function sendPayOTPData(){
    $("#to-payment-screen-2").addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUserPay/",
                data: { userPhone: $('#payCountrycode').val()+' '+$('#payUserPhone').val(),userEmail: $('#payUserEmail').val(),userName: $('#payUserName').val(),subtitle: $('#paysubtitle').val()},
                async: true,
                success: function (data) {
                    $("#to-payment-screen-2").removeClass('disabled');
                    if(data == 'success'){
						$("#to-payment-screen-2").removeClass('disabled');
                            $('.payotp').html($('#payUserPhone').val());
							$('.payotpemail').html($('#payUserEmail').val()); 
                            $("#payment-screen-1").addClass("d-none");
                            $("#payment-screen-2").removeClass("d-none");
                            $('#hidUserEmail').val($('#payUserEmail').val());
                            $('#hidUserName').val($('#payUserName').val());
                            $('#hidSubTitle').val($('#paysubtitle').val());
                            $('#hidUserPhone').val($('#payCountrycode').val()+' '+$('#payUserPhone').val());
                        return false;
                    }
                }
            })
}

function resendPayOTPData(){
    $('.otp_pay_validateion_error').addClass('hide');
	$('.sendingpayotp').addClass('hide');
	$('.resendingpayotp').removeClass('hide');
	$('#to-payment-screen-3').addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/sendsmsToUserPay/",
                data: { userPhone: $('#payCountrycode').val()+''+$('#payUserPhone').val(),userEmail: $('#payUserEmail').val(),userName: $('#payUserName').val(),subtitle: $('#paysubtitle').val()},
                async: true,
                success: function (data) {  
					$('.sendingpayotp').removeClass('hide');
					$('.resendingpayotp').addClass('hide');
					$('#to-payment-screen-3').removeClass('disabled');
                    if(data == 'success'){
                         $('.payotp').html($('#payUserPhone').val());
						 $('.payotpemail').html($('#payUserEmail').val());
                        return false;
                    }
                }
            })
}

function checkSubmittedOTPPay(){
    var otp =   $('#payuserotp1').val()+''+$('#payuserotp2').val()+''+$('#payuserotp3').val()+''+$('#payuserotp4').val();
    $("#to-payment-screen-3").addClass('disabled');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/checkSentSmsPay/",
                data: { otp: otp},
                async: true,
                success: function (data) {
                    $("#to-payment-screen-3").removeClass('disabled');
                    if(data == 'success'){
                        //submitPayDownloadData()
                        $("#payment-screen-2").addClass("d-none");
                        $("#payment-screen-3").removeClass("d-none");
                        $('.otp_pay_validateion_error').addClass('hide');
                        return false;
                    }else{
                        $('.otp_pay_validateion_error').removeClass('hide');
                        return false;
                    }
                }
        })
}

function submitDownloadData(){
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/downloadProductInfo/",
                data: {subtitle: $('#subtitleid').val(),userFirstName: $('#userFirstName').val(),userLastName: $('#userLastName').val(),userEmail: $('#userEmail').val(),userPhone: $('#countrycode').val()+' '+$('#userPhone').val()},
                async: true,
                success: function (data) {   
                    $(".pop_loader").addClass('hide');
                    if(data != ''){
                        $('.download-product-info-form-blk').addClass('hide');
                        $('.download-product-info-otp-blk').addClass('hide');
                        //document.write(data);
                        window.open(siteUrl+'/product/productinfo/id/'+data, '_blank');
                        window.open(siteUrl+'/product/productinfodetail/id/'+data, '_blank');
                        return false;
                    }
                }
            })
}
function submitDownloadBroucherData(){
	
	$.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/downloadBroucher/",
                data: {subtitle: $('#subtitleid').val(),userFirstName: $('#userFirstName').val(),userLastName: $('#userLastName').val(),userEmail: $('#userEmail').val(),userPhone: $('#countrycode').val()+' '+$('#userPhone').val(),productCategoryID: $('#productCategoryID').val(),bodyStyle: $('#bodyStyle').val(),productCategoryName: $('#productCategoryName').val()},
                async: true,
                success: function (data) {   
                    $(".pop_loader").addClass('hide');
                    if(data != ''){
                        $('.download-product-info-form-blk').addClass('hide');
                        $('.download-product-info-otp-blk').addClass('hide');
                        //document.write(data);
                        window.open(siteUrl+'/product/broucherinfo/id/'+data, '_blank');
                       // window.open(siteUrl+'/product/productinfodetail/id/'+data, '_blank');
                        return false;
                    }
                }
            })
}

function submitCallbackData(){
    $(".pop_loader").removeClass('hide');
    $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/product/callbackProductInfo/",
                data: { userFirstName: $('#cbUserFirstName').val(),userLastName: $('#cbUserLastName').val(),userEmail: $('#cbUserEmail').val(),userPhone: $('#cbCountrycode').val()+' '+$('#cbUserPhone').val(),comment: $('#cbUserComment').val(),subtitle: $('#cbsubtitle').val()},
                async: true,
                success: function (data) {                   
                    $(".pop_loader").addClass('hide');
                    if(data == 'success'){
//                        $('.request-callback-form-blk').addClass('hide');
//                        $('.request-callback-otp-blk').removeClass('hide');
                        return false;
                    }
                }
            })
}
function changeProductOptionFree(productOptionId) 
{
    var data = new Object();
    data.productOptionID = productOptionId;
    data.productCurrency = productCurrency;
    data.productID = selectedProductID;
    data.categoryID = selectedProductCategoryID;
    $(".selectedOptionFree").removeClass('selectedOptionFree');    
    $(this).addClass('selectedOptionFree');
    $(".productOptionsFree[id=" + productOptionId + "]").addClass('selectedOptionFree');

    /*var key = 'ajaxGetProductOptionDetails_' + productOptionId;
    if (typeof ajaxResponse[key] == 'undefined') {
        $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH + "/product/ajaxGetProductOptionDetails/",
            data: data,
            success: function (data) 
			{
                ajaxResponse[key] = data;
                response = data;
                $(".buynow_contents").empty();
                $(".buynow_contents").html(response);
            }
        });
    } else
	{
        var response = ajaxResponse[key];
        $(".buynow_contents").empty();
        $(".buynow_contents").html(response);
    }

    //fn_change_options('', selectedProductID);
    //changeCombinationImage(combinationHash, productOptionId, selectedProductID);

    $.when(fn_change_options('', selectedProductID)).then(function () 
	{
        changeCombinationImage(combinationHash, productOptionId, selectedProductID)
    });*/

}
function changeProductOption(productOptionId,optBusinessID) 
{
    var data = new Object();
    data.productOptionID = productOptionId;
    data.productCurrency = productCurrency;
    data.productID = selectedProductID;
    data.categoryID = selectedProductCategoryID;
    data.currBusinessID = optBusinessID;
    $(".selectedOption").removeClass('selectedOption');
    $("#selectedProductOption").val(productOptionId);
    $(this).addClass('selectedOption');
    $(".productOptions[id=" + productOptionId + "]").addClass('selectedOption');

    var key = 'ajaxGetProductOptionDetails_' + productOptionId;
    var busDetKey = 'business_details_' + productOptionId;
    if (typeof ajaxResponse[key] == 'undefined' || typeof ajaxBusDetResponse[busDetKey] == 'undefined') {
        $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH + "/product/ajaxGetProductOptionDetails/",
            data: data,
            success: function (data){
                var dataSplit = data.split("seperate~*");
                ajaxResponse[key]       = dataSplit[0];
                ajaxBusDetResponse[busDetKey] = dataSplit[1];
                response = dataSplit[0];
                $(".buynow_contents").empty();
                $(".buynow_contents").html(response);
                
                $("#business_info_details").empty();
                $("#business_info_details").html(dataSplit[1]);
            }
        });
    } else
	{
        var response = ajaxResponse[key];
        var busDetResponse = ajaxBusDetResponse[busDetKey];
        $(".buynow_contents").empty();
        $(".buynow_contents").html(response);
        
        $("#business_info_details").empty();
        $("#business_info_details").html(busDetResponse);
    }

    $('#moreSellers').addClass('hide');
    $('.moreSellerOptionList').addClass('hide');

    //fn_change_options('', selectedProductID);
    //changeCombinationImage(combinationHash, productOptionId, selectedProductID);

    $.when(fn_change_options('', selectedProductID,'',optBusinessID,'',productOptionId)).then(function () 
	{
        //changeCombinationImage(combinationHash, productOptionId, selectedProductID)
    });

}
function handleBuySubmit()
{
	$("#buynowcheckout,.buynowCart,.buynow_Bundle_link").hide();
	$("#completeLoader").show();
	return true;
	

}
function buynow_link(obj) {
    $('.nav-link').addClass('disabled');
    var parts = obj.attr('rel').split("-");
    var tempProductId = parts[0];
	 addItemtoCart(obj.attr('rel'), false,'',obj);
	 createSummaryFromCart();
    $('.nav-link').removeClass('disabled');     
}

/*function addItemtoCart(relData, redirect,thisVal,giveAsGift) {
    var buybox = thisVal.attr('buybox');
    addItemtoCart(obj.attr('rel'), false,'',obj);
}*/


function addItemtoCart(relData, redirect, giveAsGift,obj) {
    var buybox      = obj.attr('buybox');
    var freeProduct = obj.attr('free');
    var selbusinessKey = obj.attr("selbusinessKey");
   
    giveAsGift = (typeof giveAsGift !== 'undefined' && giveAsGift!=='') ? giveAsGift : 'No';
    freeProduct = (typeof freeProduct == 'undefined' || freeProduct=='') ? '' : freeProduct;
   
    var msgDivID = typeof isQuickView == 'undefined' ? 'common_message' : 'poppup_common_message';
    var parts = relData.split("-");
    var productID = parts[0];
    var fgCount   = 0;
    if(freeProduct!='') {        
        var productOptionID = $("#freeOption_"+productID+"_"+parts[3]).val();
        fgCount             = obj.attr('fgc');
    } else {
        var productOptionID = parts[1];
    }
    
    var basepar = 0;
    $("#selectedProductOption").val(productOptionID);
    var currbusinessid = parts[2];
    
    if(freeProduct=='') {
        if(buybox=='yes'){
            products = $.merge( products , eval('products_'+productID) );
            //products = eval('products_'+dealID);
            basepar = obj.attr('basepar');
        }
         $("#selectedProductOption").val(productOptionID);
        fn_change_options('', productID, '',currbusinessid,'itemadded',productOptionID);
    } else {
        fn_change_options_free('', productID, '',parts[3],productOptionID);
    }
    
    
    var selectedVarientArray = new Array(0);
    var selectedVarientString;
    if (typeof userUploadedImageArray != 'undefined') {
        var userUploadedImageObj = JSON.parse(userUploadedImageArray);
    }
    if(freeProduct=='') {
        $(".hid_custom_option").each(function () {
            attributeID = $(this).attr('rel');
            element = this;
            switch (element.type) {
                case 'hidden':
                selectedVarient = element.value;
                break;
            case 'select-one':
                if (element.value > 0)
                    selectedVarientArray.push(element.value);
                break;
            case 'checkbox':
                if (element.checked == true) {
                    selectedVarientArray.push(element.value);
                }
                break;
            }
        });
    } else {
        $(".custom_option_free_"+parts[2]+"_"+productID).each(function () {           
            attributeID = $(this).attr('rel');
            element = this;
            switch (element.type) {
                case 'hidden':
                selectedVarient = element.value;
                break;
            case 'select-one':
                if (element.value > 0)
                    selectedVarientArray.push(element.value);
                break;
            case 'checkbox':
                if (element.checked == true) {
                    selectedVarientArray.push(element.value);
                }
                break;
            }
        });
    }
    
    selectedVarientArray.sort(function (a, b) {
        return a - b
    });
    selectedVarientString = implode('_', selectedVarientArray);
    var freecnt   = 0;
    if(obj.attr('freecnt')>0) {
        freecnt = obj.attr('freecnt');
    }    
    //var encodedCustomOption = '';
    //var encodedCombinations = '';
    var customCount = '';
    var optionCount = '';
    var cartFreeProduct = 'No';
    
    if(freeProduct=='') {
      
        //console.log(selectedVarientString);
        for (var i = 0; i < products.length; i++) 
            {
                
            if (products[i]['productID'] == productID) 
                    {
            var currBusKey = products[i].businessKey
            if(selbusinessKey!=""){
                currBusKey = selbusinessKey;
            }
                if (giveAsGift == 'No') {
                    var maxBuyLimit = Number(products[i]['productMaxBuyLimit']);
                } else {
                    var maxBuyLimit = Number(products[i]['productMaxGiftBuy']);
                }

                var mainMaxBuyLimit = Number(products[i]['productMaxBuyLimit']);
                var minBuyLimit = Number(products[i]['productMinBuyLimit']);
            var businessKey = currBusKey;
                var productImage = products[i]['productImage'];
                var productServiceFee = Number(products[i]['productServiceFee']);
                var giftUnlimited = products[i]['giftUnlimited'];
                var productDefaultCurrency = Number(products[i]['productDefaultCurrency']);
                var productTitle = products[i]['productTitle'];
                var optionQuantity;
            var optionQuantityUnlimited;
                for (var j = 0; j < products[i]['options'].length; j++) {
                    if (products[i]['options'][j]['productOptionID'] == productOptionID) {
                        if (products[i]['InventoryTrackLevel'] == 'Options') {
                            $.each(encodedCombinations, function () {
                                if (this.combinationHash == combinationHash) {
                                var busCombinations = this.busCombinations;
                                if(busCombinations.length>0){
                                    $.each(busCombinations, function (key,value) {
                                        if(currbusinessid==value.businessID){
                                            optionQuantity            =   Number(value.businessCombQuantity);
                                            optionQuantityUnlimited   =   Number(value.businessCombQtyUnlimited);
                                        }
                                    });
                                }else{
                                    optionQuantity = Number(this.combinationQty);
                                    optionQuantityUnlimited = Number(this.combinationQtyUnlimited);
                                }
                            }
                            });
                        } else {
                        var busOptLen   =   0;
                        if(products[i]['options'][j]['busOptions']){
                            busOptLen   =   products[i]['options'][j]['busOptions'].length;
                        }
                        if(busOptLen>0){
                            for (var m = 0; m < products[i]['options'][j]['busOptions'].length; m++) {
                                if(products[i]['options'][j]['busOptions'][m]['businessID']==currbusinessid){
                                    optionQuantity          = Number(products[i]['options'][j]['busOptions'][m]['productOptionQuantity']);
                                    optionQuantityUnlimited = Number(products[i]['options'][j]['busOptions'][m]['productQuantityUnlimited']);
                                }
                            }
                        }else{
                            optionQuantity = Number(products[i]['options'][j]['productOptionQuantity']);
                            optionQuantityUnlimited = Number(products[i]['options'][j]['productQuantityUnlimited']);
                        }
                    }
                        //var productPrice = Number(products[i]['options'][j]['offerPrice']).toFixed(2);

                        if(products[i]['options'][j]['isProductDeal']=='Yes')
                            {var productPrice = Number(products[i]['options'][j]['dealPrice']).toFixed(2);}
                        else
                            {var productPrice = Number(products[i]['options'][j]['offerPrice']).toFixed(2);}
                        var productOptionName = products[i]['options'][j]['productOptionName'];
                        break;
                    }
                }
                break;
            }
        }
    } else {        
        var productValues       = obj.attr('attrs').split("~");
        var minBuyLimit         = '1';//productValues[0];
        var mainMaxBuyLimit     = productValues[1];
        if (giveAsGift == 'No') {
            var maxBuyLimit     = Number(mainMaxBuyLimit);
        } else {
            var maxBuyLimit     = Number(productValues[2]);
        }        
        var productDefaultCurrency         = productValues[3];
        var InventoryTrackLevel            = productValues[4]; 
        customCount                        = productValues[5]; 
        optionCount                        = productValues[6];
        cartFreeProduct         = 'Yes';
        
    }
    
    var userExistingSelfPurchase = 0;
    var userExistingGiftPurchase = 0;
    var currentCartSelfPurchase = 0;
    var currentCartGiftPurchase = 0;
    var itemExist = false;
    var sameItem = false;
    var existingItemQuantity = 0;
    if($(obj).attr("id")=='addtocartlink') {
       
        if(edit_cart_item_id>0) {
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCart/",
                data: { mode: 'update_cartdata'},
                async: true,
                success: function (data) {                   
                    assignJsonDataToCartJS(data);                    
                }
            })
        }
    }
   
    for (var i = 0; i < cart["purchasedDetails"].length; i++) {
        if (cart["purchasedDetails"][i]["productID"] == productID) {
            userExistingSelfPurchase = Number(cart["purchasedDetails"][i]["self"]);
            userExistingGiftPurchase = Number(cart["purchasedDetails"][i]["gift"]);
            break;
        }
    }
    var totQty =1 ;
   // alert(cart["items"].length);
    for (var i = 0; i < cart["items"].length; i++) {
        totQty = parseFloat(totQty) + parseFloat(Number(cart["items"][i]["orderItemQuantity"]));
        //alert(cart["items"][i]["productOptionID"]+ " "+productOptionID);
        //alert(selectedVarientString+ " "+cart["items"][i]["optionsHash"]);
        //alert(cart["items"][i]["orderGiveAsGift"]+ " "+ giveAsGift +" "+ cart["items"][i]["freeProduct"]+" "+cartFreeProduct);
        if (selectedVarientString != '') {
            if (cart["items"][i]["productOptionID"] == productOptionID && cart["items"][i]["optionsHash"] == selectedVarientString && cart["items"][i]["orderGiveAsGift"] == 'No' && giveAsGift == 'No' && cart["items"][i]["freeProduct"]==cartFreeProduct && cart["items"][i]["businessID"] == currbusinessid) {
                //if(freeProduct=='') {
                    itemExist = true;   
                //}
                existingItemQuantity = Number(cart["items"][i]["orderItemQuantity"]);
            }
        } else {
            if (cart["items"][i]["productOptionID"] == productOptionID && cart["items"][i]["optionsHash"] == selectedVarientString && cart["items"][i]["orderGiveAsGift"] == 'No' && giveAsGift == 'No' && cart["items"][i]["freeProduct"]==cartFreeProduct && cart["items"][i]["businessID"] == currbusinessid) {
                //if(freeProduct=='') {
                    itemExist = true;   
                //}
                existingItemQuantity = Number(cart["items"][i]["orderItemQuantity"]);
            }
        }
        if (cart["items"][i]["productID"] == productID) {
            sameItem = true;           
            if (cart["items"][i]["orderGiveAsGift"] == 'No') {
                userExistingSelfPurchase = userExistingSelfPurchase + Number(cart["items"][i]
                    ["orderItemQuantity"]);
            }
        }
        if (combinationHash != '' && InventoryTrackLevel == 'Options') {
            if (cart["items"][i]["combinationHash"] == combinationHash && cart["items"][i]["businessID"] == currbusinessid && cart["items"][i]["orderGiveAsGift"] == 'No') {
                currentCartSelfPurchase = currentCartSelfPurchase + Number(cart["items"][i]["orderItemQuantity"]);
            }
        } else {
            if (cart["items"][i]["productOptionID"] == productOptionID && cart["items"][i]["businessID"] == currbusinessid && cart["items"][i]["orderGiveAsGift"] == 'No') {
                currentCartSelfPurchase = currentCartSelfPurchase + Number(cart["items"][i]["orderItemQuantity"]);
            }
        }
    }
    var selectedQuantity   =   1;
    if(obj.attr('id')=='addtocartlink'){
        selectedQuantity   =   $('#quantityBox').val();
    }else if($('#busOptQuantity_'+productOptionID+'_'+currbusinessid).length>0){
        selectedQuantity   =   $('#busOptQuantity_'+productOptionID+'_'+currbusinessid).val();
    }else{
        selectedQuantity   =   $('#quantityBox').val();
    }
    
    if (giveAsGift == 'No') {
        if (currentCartSelfPurchase + Number(selectedQuantity) >= minBuyLimit) {
            if (selectedQuantity > 0) {
                var purchasingQuantity = Number(selectedQuantity);
            } else {
                var purchasingQuantity = 1;
            }
        } else {
            var purchasingQuantity = minBuyLimit;
        }
    } else {
        if (minBuyLimit <= Number(selectedQuantity) && Number(selectedQuantity) > 0) {

            var purchasingQuantity = Number(selectedQuantity);
        } else {
            var purchasingQuantity = minBuyLimit;
        }
    }
   
    if (optionQuantityUnlimited < 1 && optionQuantity < purchasingQuantity + existingItemQuantity) {
        closeBuynowPopUp(obj);
        jNotifyShow(lblCartStockNotAvailable, msgDivID, "message_error");
        return true;
    } else {
        if (optionQuantityUnlimited < 1 && optionQuantity - (currentCartSelfPurchase) < purchasingQuantity) {
            closeBuynowPopUp(obj);
            jNotifyShow(lblCartStockNotAvailable, msgDivID, "message_error");
            return true;
        }
        if ((purchasingQuantity) > mainMaxBuyLimit && maxBuyLimit > 0 && mainMaxBuyLimit > 0) {
            closeBuynowPopUp(obj);
            jNotifyShow(lblCartYouHaveExceededLimit, msgDivID, "message_error");
            return true;
        }
        if ((userExistingSelfPurchase + purchasingQuantity) > maxBuyLimit && maxBuyLimit > 0 && giveAsGift == 'No') {
            closeBuynowPopUp(obj);
            jNotifyShow(lblCartYouHaveExceededLimit, msgDivID, "message_error");
            return true;
        }
        if (productDefaultCurrency < 1) {
            closeBuynowPopUp(obj);
            jNotifyShow(lblCartInvalidCurrencyConfig, msgDivID, "message_error");
            return true;
        }        
       
        if (productDefaultCurrency != Number(cart["currencyID"]) && cart["items"].length > 0) {
            closeBuynowPopUp(obj);
            jNotifyShow(lblCartCurrencyNotMatching, msgDivID, "message_error");
            return true;
        }
        var data = new Object();

        data.productID = productID;
        data.productOptionID = productOptionID;
        if(freeProduct=='') {
            data.businessKey = businessKey;
            data.productImage = productImage;
            data.productOptionName = productOptionName;
            data.productTitle = productTitle;
            data.productServiceFee = productServiceFee;
            data.freeProduct = '';
            data.freeBaseProductID ='';
        } else {
            data.freeProduct = 'Yes';
            data.freeBaseProductID =freeProduct;
        }
        data.giveAsGift = giveAsGift;
        data.productDefaultCurrency = productDefaultCurrency;
        data.basepar = basepar;
        data.currbusinessid = currbusinessid;
        var attributeID;
        var elementType;
        var priceDiff;
        var priceDiffType;
        var strcustomOptionValues = '';
        var strcombinationValues = '';
        var existingUploadedImage;
        if(freeProduct=='') {
            $(".hid_custom_option").each(function () {
            attributeID = $(this).attr('rel');
            element = this;
            switch (element.type) {
            case 'hidden':
                selectedVarient = element.value;
                break;
            case 'select-one':
                selectedVarient = element.value;
                break;
            case 'checkbox':
                if (element.checked == true) {
                    selectedVarient = element.value;
                } else {
                    selectedVarient = 0;
                }
                break;
            case 'text':
                selectedVarient = attributeID;
                break;
            case 'textarea':
                selectedVarient = attributeID;
                break;
            }
            if ($(this).hasClass("inv_yes"))
                var combinationAvilable = checkCombinationAvilabe(element, combinationHash);
            else
                var combinationAvilable = false;
            if (!combinationAvilable) {
                
                jQuery.each(encodedCustomOption, function () {
                    if (this.customOptionID == attributeID) {
                        if (element.type == 'file') {
                            existingUploadedImage = $('#uploadedImage_' + productID + '_' + attributeID).val();
                        }
                        if ((element.type == 'text' || element.type == 'textarea') && $.trim(element.value) != '') {
                            priceDiff = this.priceDiff;
                            priceDiffType = this.priceDiffType;
                            if (priceDiffType == 'I' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else if (priceDiffType == 'D' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + '~:inputType~*' + this.inputType;
                            }
                        } else if (element.type == 'file' && (element.value != '' || existingUploadedImage != '')) {
                            priceDiff = this.priceDiff;
                            priceDiffType = this.priceDiffType;
                            if (element.value != '') {
                                var imgNameKey = 'option_' + productID + '_' + attributeID + '--' + $("#currentTime").val();
                                //console.log(imgNameKey);
                                var imgName = userUploadedImageObj[imgNameKey];
                                //console.log(imgName);
                                //console.log(userUploadedImageObj);
                            } else {
                                imgName = existingUploadedImage;
                            }
                            if (priceDiffType == 'I' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else if (priceDiffType == 'D' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + '~:inputType~*' + this.inputType;
                            }
                        } else {
                            for (var j = 0; j < this.variants.length; j++) {
                                
                                if (this.variants[j]['customOptionVariantID'] == selectedVarient) {
                                   
                                    priceDiff = this.variants[j].priceDiff;
                                    priceDiffType = this.variants[j].priceDiffType;
                                    if (priceDiffType == 'I' && priceDiff > 0) {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + priceDiff + '~:priceDiffType~*' + priceDiffType + '~:inputType~*' + this.inputType;
                                    } else if (priceDiffType == 'D' && priceDiff > 0) {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + priceDiff + '~:priceDiffType~*' + priceDiffType + '~:inputType~*' + this.inputType;
                                    } else {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + '~:inputType~*' + this.inputType;
                                    }
                                    continue;
                                }
                            }
                        }
                    }
                });
            }
        });
        if (combinationHash != '') {
            $.each(encodedCombinations, function () {
                checkedCount = 0;
                if (this.combinationHash == combinationHash) {
                    var busCombinations = this.busCombinations;
                    if(busCombinations.length>0){
                        $.each(busCombinations, function (key,value) {
                            if(currbusinessid==value.businessID){
                                this.combinationPrice       =   value.businessCombPrice;
                                this.combinationPriceDiffType   =   value.businessCombDiff;
                            }
                        });
                    }
                    
                    combinationArray = explode('_', this.combination);
                    combinationCount = combinationArray.length - 1;
                    if (this.combinationPriceDiffType == 'I' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( + ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else if (this.combinationPriceDiffType == 'D' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( - ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else if (this.combinationPriceDiffType == 'O' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + '->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    }
                    for (var i = 1; i < combinationArray.length; i++) {
                        $(".hid_custom_option").each(function () {
                            if (this.type == 'select-one') {
                                if (this.value == combinationArray[i]) {
                                    attributeID = $(this).attr('rel');
                                    selectedVarient = this.value;
                                    jQuery.each(encodedCustomOption, function () {
                                        if (this.customOptionID == attributeID) {
                                            for (var j = 0; j < this.variants.length; j++) {
                                                if (this.variants[j]['customOptionVariantID'] == selectedVarient) {
                                                    strcombinationValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                                    strcombinationValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + '~:inputType~*' + this.inputType;
                                                    continue;
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        } else {
            $(".custom_option_free_"+parts[2]+"_"+productID).each(function () {
            attributeID = $(this).attr('rel');
            element = this;
            switch (element.type) {
            case 'select-one':
                selectedVarient = element.value;
                break;
            case 'checkbox':
                if (element.checked == true) {
                    selectedVarient = element.value;
                } else {
                    selectedVarient = 0;
                }
                break;
            case 'text':
                selectedVarient = attributeID;
                break;
            case 'textarea':
                selectedVarient = attributeID;
                break;
            case 'hidden':
                selectedVarient = element.value;
                break;
            }
            if ($(this).hasClass("inv_yes"))
                var combinationAvilable = checkCombinationAvilabeFree(element, combinationHashFree,productOptionID,productID);
            else
                var combinationAvilable = false;
            if (!combinationAvilable) {
                
                jQuery.each(encodedCustomOptionsFree, function () {
                    if (this.customOptionID == attributeID) {
                        if (element.type == 'file') {
                            existingUploadedImage = $('#uploadedImage_' +parts[2]+ productID + '_' + attributeID).val();
                        }
                        if ((element.type == 'text' || element.type == 'textarea') && $.trim(element.value) != '') {
                            priceDiff = this.priceDiff;
                            priceDiffType = this.priceDiffType;
                            if (priceDiffType == 'I' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else if (priceDiffType == 'D' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + $.trim(element.value) + '~:variantValue~*' + $.trim(element.value) + '~:inputType~*' + this.inputType;
                            }
                        } else if (element.type == 'file' && (element.value != '' || existingUploadedImage != '')) {
                            priceDiff = this.priceDiff;
                            priceDiffType = this.priceDiffType;
                            if (element.value != '') {
                                var imgNameKey = 'option_' +parts[2]+ productID + '_' + attributeID + '--' + $("#currentTime").val();
                                //console.log(imgNameKey);
                                var imgName = userUploadedImageObj[imgNameKey];
                                //console.log(imgName);
                                //console.log(userUploadedImageObj);
                            } else {
                                imgName = existingUploadedImage;
                            }
                            if (priceDiffType == 'I' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else if (priceDiffType == 'D' && priceDiff > 0) {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + this.priceDiff + '~:priceDiffType~*' + this.priceDiffType + '~:inputType~*' + this.inputType;
                            } else {
                                strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                strcustomOptionValues += '~:customOptionVariantID~*0~:variantValueText~*' + imgName + '~:variantValue~*' + imgName + '~:inputType~*' + this.inputType;
                            }
                        } else {
                            for (var j = 0; j < this.variants.length; j++) {
                                if (this.variants[j]['customOptionVariantID'] == selectedVarient) {
                                    priceDiff = this.variants[j].priceDiff;
                                    priceDiffType = this.variants[j].priceDiffType;
                                    if (priceDiffType == 'I' && priceDiff > 0) {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + ' ( + ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + priceDiff + '~:priceDiffType~*' + priceDiffType + '~:inputType~*' + this.inputType;
                                    } else if (priceDiffType == 'D' && priceDiff > 0) {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + ' ( - ' + formatCurrency(priceDiff, 'Full') + ' )~:priceDiff~*' + priceDiff + '~:priceDiffType~*' + priceDiffType + '~:inputType~*' + this.inputType;
                                    } else {
                                        strcustomOptionValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                        strcustomOptionValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + '~:inputType~*' + this.inputType;
                                    }
                                    continue;
                                }
                            }
                        }
                    }
                });
            }
        });
        if (combinationHashFree != '') {
            $.each(encodedCombinationsFree, function () {
                checkedCount = 0;
                if (this.combinationHash == combinationHashFree) {
                    combinationArray = explode('_', this.combination);
                    combinationCount = combinationArray.length - 1;
                    if (this.combinationPriceDiffType == 'I' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( + ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else if (this.combinationPriceDiffType == 'D' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( - ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else if (this.combinationPriceDiffType == 'O' && this.combinationPrice > 0) {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + ' ( ' + formatCurrency(this.combinationPrice, 'Full') + ' )->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    } else {
                        strcombinationValues += '->combinationSKU~*' + this.combinationSKU + '->combinationPrice~*' + this.combinationPrice + '->combinationPriceDiffType~*' + this.combinationPriceDiffType;
                    }
                    for (var i = 1; i < combinationArray.length; i++) {
                        $(".hid_custom_option").each(function () {
                            if (this.type == 'select-one') {
                                if (this.value == combinationArray[i]) {
                                    attributeID = $(this).attr('rel');
                                    selectedVarient = this.value;
                                    jQuery.each(encodedCustomOptionsFree, function () {
                                        if (this.customOptionID == attributeID) {
                                            for (var j = 0; j < this.variants.length; j++) {
                                                if (this.variants[j]['customOptionVariantID'] == selectedVarient) {
                                                    strcombinationValues += '->customOptionID~*' + this.customOptionID + '~:customOptionName~*' + this.customOptionName;
                                                    strcombinationValues += '~:customOptionVariantID~*' + selectedVarient + '~:variantValue~*' + this.variants[j].value + '~:inputType~*' + this.inputType;
                                                    continue;
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        }
        
        data.showroom   =   $('#showroom').val();
        data.customOptionValues = strcustomOptionValues;
        data.strcombinationValues = strcombinationValues;
        if(freeProduct!='') {
            data.combinationHash = combinationHashFree;
        } else {
            data.combinationHash = combinationHash;
        }
        data.optionsHash = selectedVarientString;
        if (!sameItem && cart["items"].length > 0) {
            data.sameItem = 'No';
        } else {
            data.sameItem = 'Yes';
        } 
		/*if($(obj).attr("id")!='addtocartlink'){
			handleBuySubmit();
		}*/
   // alert(itemExist);return false;
        $(".pop_loader").removeClass('hide'); 
        if (itemExist) {
            /*if(freeProduct!='') {                
                data.quantity = Number(purchasingQuantity);
            } else {
                data.quantity = Number(purchasingQuantity) + Number(existingItemQuantity);
            }*/
            data.showroom   =   $('#showroom').val();
            data.quantity = Number(purchasingQuantity) + Number(existingItemQuantity);
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateQuantity/",
                data: data,
				async: false,
                success: function (data) {
                    $(".pop_loader").addClass('hide');
                    assignJsonDataToCartJS(data);
                    resetCurrency(productDefaultCurrency);
                    //updateCartNotification();
                    //closeOptionPopUp();
                    //jNotifyShow(lblCartItemAddedSuccessfully, msgDivID, "message_info");
					if(redirect_to_cart_page_on_add_to_cart_click=='Yes' || ($(obj).attr("id")=='addtocartlink' && freecnt<=0))
					{
						window.location = GLOBAL_BASE_PATH + "/cart/";
						
					}else if($(obj).attr("id")=='buynowcheckout'){
						 window.location = GLOBAL_BASE_PATH + "/cart/checkout/";
					}
					else
					{
						updateCartPopUp();
                                                if(freeProduct=='') {
                                                    var showmsg = productTitle;
                                                } else {
                                                    var x = jQuery.parseJSON(data);
                                                    if (x!=null && typeof x.isError != 'undefined' && x.isError == 'Yes') 
                                                    {
                                                        jNotifyShow(x.error, msgDivID, "message_error");
                                                        //closeBuynowPopUp();
                                                    } 
                                                    var showmsg = x.selectedProduct;
                                                }
                                                showmsg = showmsg+" "+lblCartItemNameAddedSuccessfully+"<br><br>"+lblThere+" "+totQty+" ";
                                                if(parseFloat(totQty)>1) {
                                                    showmsg = showmsg+lblItemsInShopping;
                                                } else {
                                                    showmsg = showmsg+lblItemInShopping;
                                                }
                                                if(freeProduct!='') {
                                                    var dec = parseFloat($("#totAddedFreeGifts_"+freeProduct).val())+parseFloat(1);                                                            
                                                    $("#totAddedFreeGifts_"+freeProduct).val(dec);
                                                    $(".freeadded_"+productID+"_"+parts[2]).removeClass('prdadded_'+freeProduct);
                                                    $(".freeadded_"+productID+"_"+parts[2]).addClass('prdadded_'+freeProduct);
                                                    $(".freeprodcls_"+productID+"_"+parts[2]).html("<span class='icon-shopping-cart'></span>"+lblUpdate);
                                                    if(fgCount==dec) {
                                                        $(".add_btn_free_"+freeProduct).hide();
                                                        $(".update_btn_free_"+freeProduct).hide();
                                                        $(".prdadded_"+freeProduct).removeClass('hide');
                                                        $(".prdadded_"+freeProduct).show();                                                       
                                                    }
                                                    else 
                                                    {
                                                        $(".freeprodcls_"+productID+"_"+parts[2]).show();
                                                    }
                                                    
                                                    
                                                } 
                                               
                                                
                                                
					}	
                }
            });
        } else {
            data.showroom   =   $('#showroom').val();
            data.quantity = purchasingQuantity;
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxAddItem/",
                data: data,
				async: false,
                success: function (data) {
                    $(".pop_loader").addClass('hide');                   
                    var x = jQuery.parseJSON(data);
                    if (x!=null && typeof x.isError != 'undefined' && x.isError == 'Yes') 
					{
                        jNotifyShow(x.error, msgDivID, "message_error");
                        //closeBuynowPopUp();
                    } 
					else 
					{
                        assignJsonDataToCartJS(data);
                        resetCurrency(productDefaultCurrency);
                        //updateCartNotification();
                       // closeBuynowPopUp();	  	
                        //jNotifyShow(lblCartItemAddedSuccessfully, msgDivID, "message_info");
                       
						if(redirect_to_cart_page_on_add_to_cart_click=='Yes' || ($(obj).attr("id")=='addtocartlink' && freecnt<=0))
						{
                                                    
							//window.location.href = GLOBAL_BASE_PATH + "/cart/";
							
						}else if(obj.attr("id")=='buynowcheckout'){
                                                   
						 //window.location = GLOBAL_BASE_PATH + "/cart/checkout/";
					   }
						else
						{
							 //$("#addtocartlink").attr("href","/cart/popup/");
							//updateCartPopUp();
                                                       
                                                        if(freeProduct=='') {
                                                            var showmsg = productTitle;
                                                        } else {
                                                            var showmsg = x.selectedProduct;
                                                        }
                                                        showmsg     = showmsg+" "+lblCartItemNameAddedSuccessfully+"<br><br>"+lblThere+" "+totQty+" ";
                                                        if(parseFloat(totQty)>1) {
                                                            showmsg = showmsg+lblItemsInShopping;
                                                        } else {
                                                            showmsg = showmsg+lblItemInShopping;
                                                        }
                                                        
						}
                    }
                }
            });
        }
	
		
    }
}
function getRedirectURL(businessKey) 
{
    var producttypeURL = 'product';
    var returnURL = GLOBAL_BASE_PATH + "/" + producttypeURL + "/" + businessKey + "/";
    return returnURL;
}
function getCombination(tempID,custname) {
    if(tempID!='') {
        var data = new Object();
        //data.productOptionID = productOptionID;
        //data.combinationID   = combinationID;
        var spid = tempID.split("|");
       
        data.varID           = spid[0];
        data.custID          = spid[1];
        data.intCustID       = intCustID;
        data.productID       = selectedProductID;
        var productID        = selectedProductID;
        var attributeID      = data.custID;
        var selectedVarient  = data.varID;
        if(custname=='Color') {
            $.ajax({
                    type: "POST",
                    url: GLOBAL_BASE_PATH + "/product/ajaxsetcombination/",
                    data: data,
                    success: function (data) {
                           if(data){
                                var x = jQuery.parseJSON(data);
                                $(".custopt_"+intCustID).empty();
                                $(".custopt_"+intCustID).html(x);   
                                $(".rowcust_Upholstery").removeClass("hide");
                                var custattr = $(".rowcust_Upholstery").attr("custattr");
                                $('.variants_'+attributeID).removeClass('active');
                                //console.log('#variant_thumb_image_'+selectedVarient)
                                $('#variant_thumb_image_'+selectedVarient).addClass('active');
                                $("#option_" + productID + "_" + attributeID + " [value=" + $("#hidoption_"+ productID + "_" + attributeID).val() + "]").removeAttr("selected");
                                $("#option_" + productID + "_" + attributeID + " [value=" + selectedVarient + "]").attr("selected", "selected");
                                $("#option_" + productID + "_" + attributeID).val(selectedVarient);
                                $("#hidoption_"+ productID + "_" + attributeID).val(selectedVarient);
                                var element = document.getElementById("option_" + productID + "_" + attributeID)
                                fn_change_options(element, productID, attributeID,0,'');
                                //changeCombinationImage(combinationHash, $("#selectedProductOption").val(), selectedProductID);
                                var variantid	=	$('#option_'+productID+'_'+attributeID).val()
                                var varimage	=	$('.var_image_'+selectedVarient).attr('src');
                                $('.sel_variant_'+attributeID).attr('src',varimage);
                                $('.sel_variant_'+attributeID).attr('rel',selectedVarient);
                                if($('.custopts[rel='+attributeID+']').attr('aria-controls') != 'Upholstery' && $('.custopts[rel='+attributeID+']').attr('aria-controls') != 'Trim'){
                                    var imageType   =   'extr';
                                }else{
                                    if($('.custopts[rel='+attributeID+']').attr('aria-controls') == "Trim")
                                        var imageType   =   'trim';
                                    else
                                        var imageType   =   'intr';
                                }
                                updatecarimages(imageType,$('.custopts[rel='+attributeID+']').attr('aria-controls'));
                                
                                var variantidsel	=	$('#option_'+productID+'_'+intCustID).val();
                                var varimage            =	$('.var_image_'+variantidsel).attr('src');
                                $('.sel_variant_'+intCustID).attr('src',varimage);
                                $('.sel_variant_'+intCustID).attr('rel',variantidsel);                                
                                var imageType   =   'intr';                                
                                updatecarimages(imageType,$('.custopts[rel='+intCustID+']').attr('aria-controls'));                               
                                if(custattr=='Yes') {                                    
                                    addItemtoCart(productID+"-"+$("#selectedProductOption").val(), false,'',$('.variants_'+attributeID));
                                    $(".Summary").removeClass("hide");
                                    update_payment();
                                    $(".continue-btn-cart").removeClass("disabled");
                                    $(".continue-btn-cart").removeClass("hide");
                                }
                            }
                    }
            });
        } 
     }
}
function fn_set_options(thisElm, productID, attributeID, selectedVarient,custname) 
{
    if(custname=='Color') {       
        getCombination(selectedVarient+"|"+attributeID,custname);
    } else {
       
         $('.variants_'+attributeID).removeClass('active');
            //console.log('#variant_thumb_image_'+selectedVarient)
            $('#variant_thumb_image_'+selectedVarient).addClass('active');
            $("#option_" + productID + "_" + attributeID + " [value=" + selectedVarient + "]").attr("selected", "selected");
            $("#option_" + productID + "_" + attributeID).val(selectedVarient);
            $("#hidoption_"+ productID + "_" + attributeID).val(selectedVarient);
            var element = document.getElementById("option_" + productID + "_" + attributeID)
            fn_change_options(element, productID, attributeID,0,'');
            //changeCombinationImage(combinationHash, $("#selectedProductOption").val(), selectedProductID);
            var variantid	=	$('#option_'+productID+'_'+attributeID).val()
            var varimage	=	$('.var_image_'+selectedVarient).attr('src');
            $('.sel_variant_'+attributeID).attr('src',varimage);
            $('.sel_variant_'+attributeID).attr('rel',selectedVarient);
            if($('.custopts[rel='+attributeID+']').attr('aria-controls') != 'Upholstery' && $('.custopts[rel='+attributeID+']').attr('aria-controls') != 'Trim'){
                var imageType   =   'extr';
            }else{
                if($('.custopts[rel='+attributeID+']').attr('aria-controls') == "Trim")
                    var imageType   =   'trim';
                else
                    var imageType   =   'intr';
            }
            updatecarimages(imageType,$('.custopts[rel='+attributeID+']').attr('aria-controls'));
    }
}


			
function fn_change_options(thisElm1, productID, attributeID,optBusinessID,callfrom,selProductOptionID) 
{
    combinationHash = '';
    var selectedVarient;
    var priceDiff;
    var priceDiffType;
    var tempBasePrice;
    var productOptionID = $("#selectedProductOption").val();    
    if(typeof productOptionID=="undefined" || productOptionID<=0){
        var productOptionID = selProductOptionID;    
    }
    var combinationAvilable = false;
    var all_combi_attr_selected	= true;;
    var thisElm;
    if(callfrom!="itemadded"){
        busOptionsPriceChange(0,'none');
    }
    
    for (var i = 0; i < products.length; i++) {
        if (products[i]['productID'] == productID) {
            for (var j = 0; j < products[i]['options'].length; j++) {
                if (products[i]['options'][j]['productOptionID'] == productOptionID) {
                    if(products[i]['options'][j]['isProductDeal']=='Yes'){
                        basePrice = Number(products[i]['options'][j]['dealPrice']);
                    }
                    else{
                        basePrice = Number(products[i]['options'][j]['offerPrice']);
                    }
                    cashbackPrice = Number(products[i]['options'][j]['productOptionCashBack']);
                    productOptionRegularPrice = Number(products[i]['options'][j]['productOptionRegularPrice']);
                    tempBasePrice = basePrice;
                    break;
                }
            }
            break;
        }
    }
    $('.product-variant-image-selected').removeClass('product-variant-image-selected');
	
	$(".hid_custom_option").each(function () 
	{
            
		thisElm = this;
		if (thisElm.type == 'select-one' && $(this).hasClass("inv_yes") && $.trim(this.value)<1) 
		{
           all_combi_attr_selected	= false;
        }
        switch (thisElm.type) {
        case 'select-one': 
            if(thisElm.value=='') {
                //$("#option_"+productID+"_"+$(this).attr('rel')).prop("selectedIndex", 1);
            }
            break;
        }
	});
	
	if(!all_combi_attr_selected)
	{
		$("#stock-not-avilable").hide();
		$("#combination-not-avilable").hide();
		$("#buynow-btn").show();
		return false;
	}

    var priceDiffIncr = 0;
    var priceDiffDecr = 0;
    $(".hid_custom_option").each(function () 
	{
        combinationAvilable = false;
        thisElm = this;
           
        if (thisElm.type == 'select-one' && $(this).hasClass("inv_yes") && $.trim(this.value)>0){
            combinationAvilable = updateCombination(thisElm, tempBasePrice,optBusinessID,callfrom);
        }
		
        attributeID = $(thisElm).attr('rel');       
        switch (thisElm.type) {
        case 'select-one':
            selectedVarient = thisElm.value;
         $('#variant_thumb_image_' + thisElm.value).addClass('product-variant-image-selected');
            break;
        case 'checkbox':
            if (thisElm.checked == true) {
                selectedVarient = thisElm.value;
                $('#variant_thumb_image_' + thisElm.value).addClass('product-variant-image-selected');
            } else {
                selectedVarient = 0;
            }
            break;
        case 'text':
            selectedVarient = attributeID;
            break;
        case 'textarea':
            selectedVarient = attributeID;
            break;
        }
        jQuery.each(encodedCustomOption, function () 
		{
            if (this.customOptionID == attributeID) {
                if ((thisElm.type == 'text' || thisElm.type == 'textarea') && $.trim(thisElm.value) != '') {
//                    priceDiff = this.priceDiff;
//                    priceDiffType = this.priceDiffType;
//                    if (priceDiffType == 'I' && priceDiff > 0) {
//                        basePrice     = basePrice + Number(priceDiff);
//                        tempBasePrice = basePrice;
//                        priceDiffIncr = priceDiffIncr+Number(priceDiff);
//                    } else if (priceDiffType == 'D' && priceDiff > 0) {
//                        basePrice     = basePrice - Number(priceDiff);
//                        tempBasePrice = basePrice;
//                        priceDiffDecr = priceDiffDecr+Number(priceDiff);
//                    }
                } else {
                    if (thisElm.type == 'select-one' && $(this).hasClass("inv_yes")) {
                        combinationAvilable = checkCombinationAvilabe(thisElm, '', productOptionID);
                    }
                    if (!combinationAvilable) {
//                        for (var j = 0; j < this.variants.length; j++){
//                            if (this.variants[j]['customOptionVariantID'] == selectedVarient) {
//                                priceDiff = this.variants[j].priceDiff;
//                                priceDiffType = this.variants[j].priceDiffType;
//                                if (priceDiffType == 'I' && priceDiff > 0) {
//                                    basePrice = basePrice + Number(priceDiff);
//                                    tempBasePrice = basePrice;
//                                    priceDiffIncr = priceDiffIncr+Number(priceDiff);
//                                } else if (priceDiffType == 'D' && priceDiff > 0) {
//                                    basePrice = basePrice - Number(priceDiff);
//                                    tempBasePrice = basePrice;
//                                    priceDiffDecr = priceDiffDecr+Number(priceDiff);
//                                }
//                                continue;
//                            }
//                        }
                    }
                }
//                if (!combinationAvilable) {
//                    var priceDiffVal    =   0;
//                    if(priceDiffIncr>priceDiffDecr){
//                        priceDiffVal    =   Number(priceDiffIncr)-Number(priceDiffDecr);
//                        busOptionsPriceChange(Number(priceDiffVal),'incr');
//                    }else if(priceDiffDecr>priceDiffIncr){
//                        priceDiffVal    =   Number(priceDiffDecr)-Number(priceDiffIncr);
//                        busOptionsPriceChange(Number(priceDiff),'decr');
//                    }else if(priceDiffDecr==0 && priceDiffIncr==0){
//                        busOptionsPriceChange(0,'none');
//            }
//                }
            }
        });
    });
//    $("#product-price").empty();
//    resetCurrency(productCurrency);
//	var product_discount = ((productOptionRegularPrice-basePrice)/productOptionRegularPrice)*100;
//	$("#product_discount").html($.getFormattedDiscount(product_discount));
//    $("#product-price").append(formatCurrency(basePrice, 'Round'));
//    $('.cashback span#productcashBack').empty();
//    $('.cashback span#productcashBack').append(formatCurrency(cashbackPrice, 'Round'));
//    if (combinationHash != '')
//    return basePrice;
}

function busOptionsPriceChange(priceDiff,action){
    $('#moreSellers ul.moreSellerOptionList ul').each(function(){
        var currBusOptPrice   =   $(this).find('.hiddenBusOptProdPrice').val();
        var newBusOptPrice    =   0;
        if(action=="incr"){
            newBusOptPrice    =   parseInt(currBusOptPrice)+parseInt(priceDiff);
        }else if(action=="decr"){
            newBusOptPrice    =   parseInt(currBusOptPrice)-parseInt(priceDiff);
        }else if(action=="none"){
            newBusOptPrice    =   currBusOptPrice
        }
        $(this).find('span.busOptProdPrice').empty();
        $(this).find('span.busOptProdPrice').append(formatCurrency(newBusOptPrice, 'Round'));
    });
}

function updateCombination(element, tempBasePrice,optBusinessID,callfrom) 
{
    var productOptionID = $("#selectedProductOption").val();
    var tempCombinationHash;
    var tempCombinationPrice = 0;
    var tempCombinationPriceDiffType = '';
    var tempCombinationQty = 0;
    var tempCombinationQtyUnlimited = 0;
    if (element.type == 'select-one') {
        var currentVarientID = element.value;
    }

    var checkedCount = 0;
    var combinationFound = false;
    var combinationCount = 0;
    var n = -1;
    var combinationAvilable = false;
    var option_have_combi = false;

    $.each(encodedCombinations, function () {
        combinationArray = explode('_', this.combination);
        var combinationStr = this.combination;
        tempCombinationCount = combinationArray.length - 1;
        if (tempCombinationCount > combinationCount) {
            combinationCount = tempCombinationCount;
        }

        $("#" + element.id + " > option").each(function () {
            if (this.value > 0) 
			{
                var temp = combinationStr.search("_" + this.value);
                if (temp >= 0) {
                    option_have_combi = true;
                }
            }
        })

    });
    $.each(encodedCombinations, function () {
        checkedCount = 0;
        if (this.productID == selectedProductID && currentVarientID > 0) {
            n = this.combination.search("_" + currentVarientID);
            if (n >= 0) {
                combinationAvilable = true;
                if($("#moreSellerOptions_"+productOptionID+" li#business-no-sellers").length<=0 && callfrom!='itemadded'){
                    $('ul.businessListSec').addClass('hide');
                    $("#moreSellerOptions_"+productOptionID).append("<li id='business-no-sellers'>Combination Doesnot Exists</li>");
                    $("#moresellerlinkSec").addClass("hide");
                    $("#buyBoxDetails").html("");
                }
                combinationArray = explode('_', this.combination);

                for (var i = 1; i < combinationArray.length; i++) {
                    $(".hid_custom_option").each(function () {
                        if (this.type == 'select-one') {
                            if (this.value == combinationArray[i]) {
                                checkedCount++;
                            }
                        }
                    });
                    if (checkedCount == combinationCount) {
                        var combPriceDiff       =   "";
                        var combPrice           =   0;
                        var combQuantity        =   "";
                        var combQuantityUnlim   =   "";
                        var busCombinations     =   this.busCombinations;
                        //var addCartRel          =   $('.addToCartMain').attr("rel");
                        //var partsRel            =   addCartRel.split("-");
                        //var currbusinessid      =   partsRel[2];
                        var currbusinessid      =   optBusinessID;
                        if(currbusinessid<=0 || currbusinessid==""){
                            if($('.addToCartMain').length>0){
                                var addCartRel          =   $('.addToCartMain').attr("rel");
                                var partsRel            =   addCartRel.split("-");
                                currbusinessid      =   partsRel[2];
                            }
                        }
                        
                        if(busCombinations.length>0){
                            var businessExists  =   0;
                            $.each(busCombinations, function (key,value) {
                                if(currbusinessid==value.businessID){
                                    combPrice           =   Math.round(value.businessCombPrice);
                                    combPriceDiff       =   value.businessCombDiff;
                                    combQuantity        =   value.businessCombQuantity;
                                    combQuantityUnlim   =   value.businessCombQtyUnlimited;
                                    businessExists      =   businessExists+1;
                                }
                                var currBusCombPrice    =   $("#busOptProdPrice_"+productOptionID+"_"+value.businessID).val();
                                var newBusCompPrice     =   0;
                                if(value.businessCombDiff=="I"){
                                    newBusCompPrice     =   parseInt(currBusCombPrice)+parseInt(Math.round(value.businessCombPrice));
                                }else{
                                    newBusCompPrice     =   currBusCombPrice
                                }
                                if($("#moreSellerOptions_"+productOptionID+" li#business-no-sellers").length>=0){
                                    $("#moreSellerOptions_"+productOptionID+" li#business-no-sellers").remove();
                                }
                                $("#businessUl_"+productOptionID+"_"+value.businessID).removeClass("hide");
                                $("#businessOptionPrice_"+productOptionID+"_"+value.businessID).empty();
                                $("#businessOptionPrice_"+productOptionID+"_"+value.businessID).append(formatCurrency(newBusCompPrice, 'Round'));
                            });
                            if(businessExists==0){
                                $('.quantity-price-sec').addClass("hide");
                                $('.combination-not-avail').removeClass("hide");
                                $("#stock-not-avilable").addClass("hide");
                            }else{
                                $('.quantity-price-sec').removeClass("hide");
                                $('.combination-not-avail').addClass("hide");
                            }
                        }
                        combinationFound = true;
                        tempCombinationHash = this.combinationHash;
                        tempCombinationPrice = Number(combPrice);
                        tempCombinationPriceDiffType = combPriceDiff;
                        tempCombinationQty = combQuantity;
                        tempCombinationQtyUnlimited = combQuantityUnlim;
                        break;
                    }
                }
            }
        }
    });
	
    if (combinationAvilable) 
	{
        if (combinationFound) 
		{
            if (InventoryTrackLevel != 'Options') 
			{
                $("#stock-not-avilable").hide();
				$("#combination-not-avilable").hide();
                $("#buynow-btn").show();
            } 
			else 
			{
                if (Number(tempCombinationQty) > 0 || tempCombinationQtyUnlimited > 0) 
				{
                    $("#stock-not-avilable").hide();
					$("#combination-not-avilable").hide();
                    $("#buynow-btn").show();
                } 
				else 
				{
                    $("#stock-not-avilable").show();
					$("#combination-not-avilable").hide();
                    $("#buynow-btn").hide();
                }
				
                if (showQuantityAvailable > tempCombinationQty) 
				{
                    $("#quantity_available").html(tempCombinationQty + " Available");
                } 
				else 
				{
                    $("#quantity_available").html("");
                }
            }
            combinationHash = tempCombinationHash;
            if (tempCombinationPrice > 0 && tempCombinationPriceDiffType == 'I') 
			{
                tempBasePrice = tempBasePrice + tempCombinationPrice;
            }
            if (tempCombinationPrice > 0 && tempCombinationPriceDiffType == 'D') {
                tempBasePrice = tempBasePrice - tempCombinationPrice;
            }
            if (tempCombinationPrice > 0 && tempCombinationPriceDiffType == 'O') {
                tempBasePrice = tempCombinationPrice;
            }
            basePrice = tempBasePrice;
        } 
		else 
		{
            $("#stock-not-avilable").hide();
            $("#buynow-btn").hide();
			$("#combination-not-avilable").show();
                        
            $("#quantity_available").html("");
            combinationHash = '';
            $('.quantity-price-sec').addClass("hide");
            $('.combination-not-avail').removeClass("hide");
            $("#stock-not-avilable").addClass("hide");
        }
    } 
	else if (option_have_combi) 
	{
        $("#stock-not-avilable").hide();
        $("#buynow-btn").hide();
		$("#combination-not-avilable").show();
        $("#quantity_available").html("");
        combinationHash = ""
        $('.quantity-price-sec').addClass("hide");
        $('.combination-not-avail').removeClass("hide");
        $("#stock-not-avilable").addClass("hide");
    }
    return combinationAvilable;
}

function checkCombinationAvilabe(element, tempcombinationHash, productOptionID) {
    if (element.type == 'select-one') {
        var currentVarientID = element.value;
    } else if (element.type == 'checkbox') {
        if (element.checked == true) {
            currentVarientID = element.value;
        } else {
            currentVarientID = 0;
        }
    }
    var n = -1;
    var combinationAvilable = false;
    $.each(encodedCombinations, function () {
        checkedCount = 0;
        if (typeof tempcombinationHash != 'undefined') {
            if (this.combinationHash == tempcombinationHash) {
                n = this.combination.search("_" + currentVarientID);
                if (n >= 0) {
                    combinationAvilable = true;
                }
            }
        }
        if (typeof selectedProductID != 'undefined') {
            if (this.productID == selectedProductID) {
                n = this.combination.search("_" + currentVarientID);
                if (n >= 0) {
                    combinationAvilable = true;
                }
            }
        }
    });
    return combinationAvilable;
}

function changeCombinationImage(combinationID, productOptionID, selectedProductID) {
    var data = new Object();
    data.productOptionID = productOptionID;
    data.combinationID = combinationID;
    data.categoryID = selectedProductCategoryID;
    data.productID = selectedProductID;
	$.ajax({
		type: "POST",
		url: GLOBAL_BASE_PATH + "/product/ajaxGetCombinationImages/",
		data: data,
		success: function (data) {
			
			response = data;
			$("#img_slider").empty();
			$("#img_slider").html(response);
//                        if(InventoryTrackLevel=="Options"){
//                            getMoreSellersSec(selectedProductID,combinationID);
//                        }
                                            //alert(response);
		}
	});
}

function getMoreSellersSec(productID,combinationHash){
    var selectedOption  =  $('#selectedProductOption').val();
    if(combinationHash!=""){
        $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH + "/product/ajaxGetMoreSellers/",
            data: "productID="+productID+"&combinationHash="+combinationHash+"&productOptionID="+selectedOption,
            success: function (data){
                var sellCount  =  $(data).filter("#buyboxSellerCnt").attr("rel");
                $(data).filter("#buyboxSellerCnt").remove();
                $("#buyBoxDetails").html(data);
                
                if(sellCount>0){
                    $("#moresellerlinkSec").removeClass("hide");
                }else{
                    $("#moresellerlinkSec").addClass("hide");
                }
//                if($(data).find("ul.businessListSec").length>0){
//                    $("#moresellerlinkSec").removeClass("hide");
//                }
//                if($("#moresellerlink").hasClass("hidesellerlink")==true){
//                    $("#moreSellers").removeClass("hide");
//                    $('#moreSellerOptions_'+selectedOption).removeClass('hide');
//                }else{
//                    $("#moreSellers").addClass("hide");
//                    $('#moreSellerOptions_'+selectedOption).addClass('hide');
//                }
                  $("#moresellerlink").removeClass("hidesellerlink").addClass("moresellerlink");
                  $("#moreSellers").addClass("hide");
                  $('#moreSellerOptions_'+selectedOption).addClass('hide');
            }
        });
    }
}

function createSummaryFromCart(){
	$.ajax({
		url: GLOBAL_BASE_PATH + "/product/loadingCartSummary/",
		type: "POST",
		cache: false,
		async: true,
		global: false,
		success: function (list) {
			x = JSON.parse(list);
                        $('.summary-img').attr('src',x.summaryImage);
                        $('.summaryfinancelease').attr('src',x.summarythumbImage);
			$('.specification-summary').html(x.specificationsummary);
                        $('.summaryfinanceleaseprice').html($(".financeText").html()+formatCurrency(x.calulatorproduct.monthlyInstallment, 'Full'));
                        $('.summaryfinanceleasetitle').html(x.calulatorproduct.productTitle);
		}
	});
}


function update_payment(){
	$.ajax({
		url: GLOBAL_BASE_PATH + "/product/loadingCartPaymentSummary/",
		type: "POST",
		cache: false,
		async: false,
		global: false,
		success: function (list) {
			x = JSON.parse(list);
			$('.payment-summary').html(x.paymentsummary);
                        $('.showroomname').html(x.showroomdetails.name);
                        $('.showroomaddress').html(x.showroomdetails.address);
                        //$('.showroomphone').html(x.showroomdetails.phone);
                        $('.showroomemail').html(x.showroomdetails.email);
                        //$('.showroommap').attr('href','http://www.google.com/maps/place/'+x.showroomdetails.latitude+','+x.showroomdetails.longitude);
						$('.showroomphone').html('<a href="tel:'+x.showroomdetails.codedPhone+'">'+x.showroomdetails.phone+'</a>');
						$('.showroommap').attr('href',x.showroomdetails.mapLink);
                        
		}
	});
}
function update_payment_loan_summary(){
	var loan = 'Yes';
	$.ajax({
		url: GLOBAL_BASE_PATH + "/product/loadingCartPaymentSummary/",
		type: "POST",
		cache: false,
		async: false,
		global: false,
		data: "loan="+loan,
		success: function (list) {
			x = JSON.parse(list);
			$('.loan-summary').html(x.paymentsummary);
                        $('.showroomname').html(x.showroomdetails.name);
                        $('.showroomaddress').html(x.showroomdetails.address);
                        //$('.showroomphone').html(x.showroomdetails.phone);
                        $('.showroomemail').html(x.showroomdetails.email);
                        //$('.showroommap').attr('href','http://www.google.com/maps/place/'+x.showroomdetails.latitude+','+x.showroomdetails.longitude);
						$('.showroomphone').html('<a href="tel:'+x.showroomdetails.codedPhone+'">'+x.showroomdetails.phone+'</a>');
						$('.showroommap').attr('href',x.showroomdetails.mapLink);
                        
		}
	});
}
function seKey() {
    var d = new Date();
    $("#currentTime").val(d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + '-' + d.getHours() + '-' + d.getMinutes() + '-' + d.getSeconds());
}

function asyncCall() {
    $.when(seKey()).then(function () {
        $("#productOptionsSubmit").trigger('click');
    });
}
function closeBuynowPopUp(obj){
			if($(obj).attr("id")=='addtocartlink'){
			   if($('.iframe', window.parent.document).is(":visible")){
					setTimeout(function(){
						parent.$.fancybox.close();
					}, 2000	);			

			   }	
			
			}
	
			return true;
}

function refreshdownloadinfo(){
         $('#userFirstName,#userLastName,#userEmail,#userPhone').val('');
         //$('#subtitle').val('Mr.');
		 $("#subtitle").val($("#subtitle option:first").val());
         $('#agree').prop('checked',false);
         $("#hid_err_formDownloadProductInfo_validateAgree").val(1);  
         $("#div_err_formDownloadProductInfo_validateAgree").addClass('hide'); 
         $('.otpfield').val('');
        $('.download-product-info-form-blk').removeClass('hide');
        $('.download-product-info-otp-blk').addClass('hide');
        $('.download-product-info-thankyou-blk').addClass('hide');
    }
    
function refreshcallbackinfo(){
        $('#cbUserFirstName,#cbUserLastName,#cbUserEmail,#cbUserPhone').val('');
        //$('#cbsubtitle').val('Mr.');  
		$("#cbsubtitle").val($("#cbsubtitle option:first").val());
        $('#cbagree').prop('checked',false);
        $("#hid_err_formReqCallBack_cbvalidateAgree").val(1);  
        $("#div_err_formReqCallBack_cbvalidateAgree").addClass('hide'); 
       /* $('.request-callback-form-blk').removeClass('hide');
        $('.request-callback-otp-blk').addClass('hide');
        $('.callback-thankyou-blk').addClass('hide');*/    
    }
function resetpaymenttab(){
	$('#payUserName, #payUserPhone, #payUserEmail, .payotpfield').val('');
        //$('#paysubtitle').val('Mr.'); 
		$("#paysubtitle").val($("#paysubtitle option:first").val());
		cbsubtitle
        $('#payagree').prop('checked',false);
        $("#hid_err_formPaymentContactInfo_payvalidateAgree").val(1);  
        $("#div_err_formPaymentContactInfo_payvalidateAgree").addClass('hide'); 
$('#payment-screen-1').removeClass('d-none');
$('#payment-screen-2').addClass('d-none');
$('#payment-screen-3').addClass('d-none');
}
    
/* jquery.form.js */

(function (e) {
    "use strict";

    function r(t) {
        var n = t.data;
        if (!t.isDefaultPrevented()) {
            t.preventDefault();
            e(this).ajaxSubmit(n)
        }
    }

    function i(t) {
        var n = t.target;
        var r = e(n);
        if (!r.is("[type=submit],[type=image]")) {
            var i = r.closest("[type=submit]");
            if (i.length === 0) {
                return
            }
            n = i[0]
        }
        var s = this;
        s.clk = n;
        if (n.type == "image") {
            if (t.offsetX !== undefined) {
                s.clk_x = t.offsetX;
                s.clk_y = t.offsetY
            } else if (typeof e.fn.offset == "function") {
                var o = r.offset();
                s.clk_x = t.pageX - o.left;
                s.clk_y = t.pageY - o.top
            } else {
                s.clk_x = t.pageX - n.offsetLeft;
                s.clk_y = t.pageY - n.offsetTop
            }
        }
        setTimeout(function () {
            s.clk = s.clk_x = s.clk_y = null
        }, 100)
    }

    function s() {
        if (!e.fn.ajaxSubmit.debug) return;
        var t = "[jquery.form] " + Array.prototype.join.call(arguments, "");
        if (window.console && window.console.log) {
            window.console.log(t)
        } else if (window.opera && window.opera.postError) {
            window.opera.postError(t)
        }
    }
    var t = {};
    t.fileapi = e("<input type='file'/>").get(0).files !== undefined;
    t.formdata = window.FormData !== undefined;
    var n = !! e.fn.prop;
    e.fn.attr2 = function () {
        if (!n) return this.attr.apply(this, arguments);
        var e = this.prop.apply(this, arguments);
        if (e && e.jquery || typeof e === "string") return e;
        return this.attr.apply(this, arguments)
    };
    e.fn.ajaxSubmit = function (r) {
        function k(t) {
            var n = e.param(t).split("&");
            var r = n.length;
            var i = [];
            var s, o;
            for (s = 0; s < r; s++) {
                n[s] = n[s].replace(/\+/g, " ");
                o = n[s].split("=");
                i.push([decodeURIComponent(o[0]), decodeURIComponent(o[1])])
            }
            return i
        }

        function L(t) {
            var n = new FormData;
            for (var s = 0; s < t.length; s++) {
                n.append(t[s].name, t[s].value)
            }
            if (r.extraData) {
                var o = k(r.extraData);
                for (s = 0; s < o.length; s++)
                    if (o[s]) n.append(o[s][0], o[s][1])
            }
            r.data = null;
            var u = e.extend(true, {}, e.ajaxSettings, r, {
                contentType: false,
                processData: false,
                cache: false,
                type: i || "POST"
            });
            if (r.uploadProgress) {
                u.xhr = function () {
                    var e = jQuery.ajaxSettings.xhr();
                    if (e.upload) {
                        e.upload.addEventListener("progress", function (e) {
                            var t = 0;
                            var n = e.loaded || e.position;
                            var i = e.total;
                            if (e.lengthComputable) {
                                t = Math.ceil(n / i * 100)
                            }
                            r.uploadProgress(e, n, i, t)
                        }, false)
                    }
                    return e
                }
            }
            u.data = null;
            var a = u.beforeSend;
            u.beforeSend = function (e, t) {
                t.data = n;
                if (a) a.call(this, e, t)
            };
            return e.ajax(u)
        }

        function A(t) {
            function T(e) {
                var t = null;
                try {
                    if (e.contentWindow) {
                        t = e.contentWindow.document
                    }
                } catch (n) {
                    s("cannot get iframe.contentWindow document: " + n)
                }
                if (t) {
                    return t
                }
                try {
                    t = e.contentDocument ? e.contentDocument : e.document
                } catch (n) {
                    s("cannot get iframe.contentDocument: " + n);
                    t = e.document
                }
                return t
            }

            function k() {
                function r() {
                    try {
                        var e = T(v).readyState;
                        s("state = " + e);
                        if (e && e.toLowerCase() == "uninitialized") setTimeout(r, 50)
                    } catch (t) {
                        s("Server abort: ", t, " (", t.name, ")");
                        _(x);
                        if (w) clearTimeout(w);
                        w = undefined
                    }
                }
                var t = a.attr2("target"),
                    n = a.attr2("action");
                o.setAttribute("target", p);
                if (!i) {
                    o.setAttribute("method", "POST")
                }
                if (n != l.url) {
                    o.setAttribute("action", l.url)
                }
                if (!l.skipEncodingOverride && (!i || /post/i.test(i))) {
                    a.attr({
                        encoding: "multipart/form-data",
                        enctype: "multipart/form-data"
                    })
                }
                if (l.timeout) {
                    w = setTimeout(function () {
                        b = true;
                        _(S)
                    }, l.timeout)
                }
                var u = [];
                try {
                    if (l.extraData) {
                        for (var f in l.extraData) {
                            if (l.extraData.hasOwnProperty(f)) {
                                if (e.isPlainObject(l.extraData[f]) && l.extraData[f].hasOwnProperty("name") && l.extraData[f].hasOwnProperty("value")) {
                                    u.push(e('<input type="hidden" name="' + l.extraData[f].name + '">').val(l.extraData[f].value).appendTo(o)[0])
                                } else {
                                    u.push(e('<input type="hidden" name="' + f + '">').val(l.extraData[f]).appendTo(o)[0])
                                }
                            }
                        }
                    }
                    if (!l.iframeTarget) {
                        d.appendTo("body");
                        if (v.attachEvent) v.attachEvent("onload", _);
                        else v.addEventListener("load", _, false)
                    }
                    setTimeout(r, 15);
                    try {
                        o.submit()
                    } catch (c) {
                        var h = document.createElement("form").submit;
                        h.apply(o)
                    }
                } finally {
                    o.setAttribute("action", n);
                    if (t) {
                        o.setAttribute("target", t)
                    } else {
                        a.removeAttr("target")
                    }
                    e(u).remove()
                }
            }

            function _(t) {
                if (m.aborted || M) {
                    return
                }
                A = T(v);
                if (!A) {
                    s("cannot access response document");
                    t = x
                }
                if (t === S && m) {
                    m.abort("timeout");
                    E.reject(m, "timeout");
                    return
                } else if (t == x && m) {
                    m.abort("server abort");
                    E.reject(m, "error", "server abort");
                    return
                }
                if (!A || A.location.href == l.iframeSrc) {
                    if (!b) return
                }
                if (v.detachEvent) v.detachEvent("onload", _);
                else v.removeEventListener("load", _, false);
                var n = "success",
                    r;
                try {
                    if (b) {
                        throw "timeout"
                    }
                    var i = l.dataType == "xml" || A.XMLDocument || e.isXMLDoc(A);
                    s("isXml=" + i);
                    if (!i && window.opera && (A.body === null || !A.body.innerHTML)) {
                        if (--O) {
                            s("requeing onLoad callback, DOM not available");
                            setTimeout(_, 250);
                            return
                        }
                    }
                    var o = A.body ? A.body : A.documentElement;
                    m.responseText = o ? o.innerHTML : null;
                    m.responseXML = A.XMLDocument ? A.XMLDocument : A;
                    if (i) l.dataType = "xml";
                    m.getResponseHeader = function (e) {
                        var t = {
                            "content-type": l.dataType
                        };
                        return t[e]
                    };
                    if (o) {
                        m.status = Number(o.getAttribute("status")) || m.status;
                        m.statusText = o.getAttribute("statusText") || m.statusText
                    }
                    var u = (l.dataType || "").toLowerCase();
                    var a = /(json|script|text)/.test(u);
                    if (a || l.textarea) {
                        var f = A.getElementsByTagName("textarea")[0];
                        if (f) {
                            m.responseText = f.value;
                            m.status = Number(f.getAttribute("status")) || m.status;
                            m.statusText = f.getAttribute("statusText") || m.statusText
                        } else if (a) {
                            var c = A.getElementsByTagName("pre")[0];
                            var p = A.getElementsByTagName("body")[0];
                            if (c) {
                                m.responseText = c.textContent ? c.textContent : c.innerText
                            } else if (p) {
                                m.responseText = p.textContent ? p.textContent : p.innerText
                            }
                        }
                    } else if (u == "xml" && !m.responseXML && m.responseText) {
                        m.responseXML = D(m.responseText)
                    }
                    try {
                        L = H(m, u, l)
                    } catch (g) {
                        n = "parsererror";
                        m.error = r = g || n
                    }
                } catch (g) {
                    s("error caught: ", g);
                    n = "error";
                    m.error = r = g || n
                }
                if (m.aborted) {
                    s("upload aborted");
                    n = null
                }
                if (m.status) {
                    n = m.status >= 200 && m.status < 300 || m.status === 304 ? "success" : "error"
                }
                if (n === "success") {
                    if (l.success) l.success.call(l.context, L, "success", m);
                    E.resolve(m.responseText, "success", m);
                    if (h) e.event.trigger("ajaxSuccess", [m, l])
                } else if (n) {
                    if (r === undefined) r = m.statusText;
                    if (l.error) l.error.call(l.context, m, n, r);
                    E.reject(m, "error", r);
                    if (h) e.event.trigger("ajaxError", [m, l, r])
                }
                if (h) e.event.trigger("ajaxComplete", [m, l]);
                if (h && !--e.active) {
                    e.event.trigger("ajaxStop")
                }
                if (l.complete) l.complete.call(l.context, m, n);
                M = true;
                if (l.timeout) clearTimeout(w);
                setTimeout(function () {
                    if (!l.iframeTarget) d.remove();
                    m.responseXML = null
                }, 100)
            }
            var o = a[0],
                u, f, l, h, p, d, v, m, g, y, b, w;
            var E = e.Deferred();
            if (t) {
                for (f = 0; f < c.length; f++) {
                    u = e(c[f]);
                    if (n) u.prop("disabled", false);
                    else u.removeAttr("disabled")
                }
            }
            l = e.extend(true, {}, e.ajaxSettings, r);
            l.context = l.context || l;
            p = "jqFormIO" + (new Date).getTime();
            if (l.iframeTarget) {
                d = e(l.iframeTarget);
                y = d.attr2("name");
                if (!y) d.attr2("name", p);
                else p = y
            } else {
                d = e('<iframe name="' + p + '" src="' + l.iframeSrc + '" />');
                d.css({
                    position: "absolute",
                    top: "-1000px",
                    left: "-1000px"
                })
            }
            v = d[0];
            m = {
                aborted: 0,
                responseText: null,
                responseXML: null,
                status: 0,
                statusText: "n/a",
                getAllResponseHeaders: function () {},
                getResponseHeader: function () {},
                setRequestHeader: function () {},
                abort: function (t) {
                    var n = t === "timeout" ? "timeout" : "aborted";
                    s("aborting upload... " + n);
                    this.aborted = 1;
                    try {
                        if (v.contentWindow.document.execCommand) {
                            v.contentWindow.document.execCommand("Stop")
                        }
                    } catch (r) {}
                    d.attr("src", l.iframeSrc);
                    m.error = n;
                    if (l.error) l.error.call(l.context, m, n, t);
                    if (h) e.event.trigger("ajaxError", [m, l, n]);
                    if (l.complete) l.complete.call(l.context, m, n)
                }
            };
            h = l.global;
            if (h && 0 === e.active++) {
                e.event.trigger("ajaxStart")
            }
            if (h) {
                e.event.trigger("ajaxSend", [m, l])
            }
            if (l.beforeSend && l.beforeSend.call(l.context, m, l) === false) {
                if (l.global) {
                    e.active--
                }
                E.reject();
                return E
            }
            if (m.aborted) {
                E.reject();
                return E
            }
            g = o.clk;
            if (g) {
                y = g.name;
                if (y && !g.disabled) {
                    l.extraData = l.extraData || {};
                    l.extraData[y] = g.value;
                    if (g.type == "image") {
                        l.extraData[y + ".x"] = o.clk_x;
                        l.extraData[y + ".y"] = o.clk_y
                    }
                }
            }
            var S = 1;
            var x = 2;
            var N = e("meta[name=csrf-token]").attr("content");
            var C = e("meta[name=csrf-param]").attr("content");
            if (C && N) {
                l.extraData = l.extraData || {};
                l.extraData[C] = N
            }
            if (l.forceSync) {
                k()
            } else {
                setTimeout(k, 10)
            }
            var L, A, O = 50,
                M;
            var D = e.parseXML || function (e, t) {
                    if (window.ActiveXObject) {
                        t = new ActiveXObject("Microsoft.XMLDOM");
                        t.async = "false";
                        t.loadXML(e)
                    } else {
                        t = (new DOMParser).parseFromString(e, "text/xml")
                    }
                    return t && t.documentElement && t.documentElement.nodeName != "parsererror" ? t : null
                };
            var P = e.parseJSON || function (e) {
                    return window["eval"]("(" + e + ")")
                };
            var H = function (t, n, r) {
                var i = t.getResponseHeader("content-type") || "",
                    s = n === "xml" || !n && i.indexOf("xml") >= 0,
                    o = s ? t.responseXML : t.responseText;
                if (s && o.documentElement.nodeName === "parsererror") {
                    if (e.error) e.error("parsererror")
                }
                if (r && r.dataFilter) {
                    o = r.dataFilter(o, n)
                }
                if (typeof o === "string") {
                    if (n === "json" || !n && i.indexOf("json") >= 0) {
                        o = P(o)
                    } else if (n === "script" || !n && i.indexOf("javascript") >= 0) {
                        e.globalEval(o)
                    }
                }
                return o
            };
            return E
        }
        if (!this.length) {
            s("ajaxSubmit: skipping submit process - no element selected");
            return this
        }
        var i, o, u, a = this;
        if (typeof r == "function") {
            r = {
                success: r
            }
        }
        i = r.type || this.attr2("method");
        o = r.url || this.attr2("action");
        u = typeof o === "string" ? e.trim(o) : "";
        u = u || window.location.href || "";
        if (u) {
            u = (u.match(/^([^#]+)/) || [])[1]
        }
        r = e.extend(true, {
            url: u,
            success: e.ajaxSettings.success,
            type: i || "GET",
            iframeSrc: /^https/i.test(window.location.href || "") ? "javascript:false" : "about:blank"
        }, r);
        var f = {};
        this.trigger("form-pre-serialize", [this, r, f]);
        if (f.veto) {
            s("ajaxSubmit: submit vetoed via form-pre-serialize trigger");
            return this
        }
        if (r.beforeSerialize && r.beforeSerialize(this, r) === false) {
            s("ajaxSubmit: submit aborted via beforeSerialize callback");
            return this
        }
        var l = r.traditional;
        if (l === undefined) {
            l = e.ajaxSettings.traditional
        }
        var c = [];
        var h, p = this.formToArray(r.semantic, c);
        if (r.data) {
            r.extraData = r.data;
            h = e.param(r.data, l)
        }
        if (r.beforeSubmit && r.beforeSubmit(p, this, r) === false) {
            s("ajaxSubmit: submit aborted via beforeSubmit callback");
            return this
        }
        this.trigger("form-submit-validate", [p, this, r, f]);
        if (f.veto) {
            s("ajaxSubmit: submit vetoed via form-submit-validate trigger");
            return this
        }
        var d = e.param(p, l);
        if (h) {
            d = d ? d + "&" + h : h
        }
        if (r.type.toUpperCase() == "GET") {
            r.url += (r.url.indexOf("?") >= 0 ? "&" : "?") + d;
            r.data = null
        } else {
            r.data = d
        }
        var v = [];
        if (r.resetForm) {
            v.push(function () {
                a.resetForm()
            })
        }
        if (r.clearForm) {
            v.push(function () {
                a.clearForm(r.includeHidden)
            })
        }
        if (!r.dataType && r.target) {
            var m = r.success || function () {};
            v.push(function (t) {
                var n = r.replaceTarget ? "replaceWith" : "html";
                e(r.target)[n](t).each(m, arguments)
            })
        } else if (r.success) {
            v.push(r.success)
        }
        r.success = function (e, t, n) {
            var i = r.context || this;
            for (var s = 0, o = v.length; s < o; s++) {
                v[s].apply(i, [e, t, n || a, a])
            }
        };
        if (r.error) {
            var g = r.error;
            r.error = function (e, t, n) {
                var i = r.context || this;
                g.apply(i, [e, t, n, a])
            }
        }
        if (r.complete) {
            var y = r.complete;
            r.complete = function (e, t) {
                var n = r.context || this;
                y.apply(n, [e, t, a])
            }
        }
        var b = e('input[type=file]:enabled[value!=""]', this);
        var w = b.length > 0;
        var E = "multipart/form-data";
        var S = a.attr("enctype") == E || a.attr("encoding") == E;
        var x = t.fileapi && t.formdata;
        s("fileAPI :" + x);
        var T = (w || S) && !x;
        var N;
        if (r.iframe !== false && (r.iframe || T)) {
            if (r.closeKeepAlive) {
                e.get(r.closeKeepAlive, function () {
                    N = A(p)
                })
            } else {
                N = A(p)
            }
        } else if ((w || S) && x) {
            N = L(p)
        } else {
            N = e.ajax(r)
        }
        a.removeData("jqxhr").data("jqxhr", N);
        for (var C = 0; C < c.length; C++) c[C] = null;
        this.trigger("form-submit-notify", [this, r]);
        return this
    };
    e.fn.ajaxForm = function (t) {
        t = t || {};
        t.delegation = t.delegation && e.isFunction(e.fn.on);
        if (!t.delegation && this.length === 0) {
            var n = {
                s: this.selector,
                c: this.context
            };
            if (!e.isReady && n.s) {
                s("DOM not ready, queuing ajaxForm");
                e(function () {
                    e(n.s, n.c).ajaxForm(t)
                });
                return this
            }
            s("terminating; zero elements found by selector" + (e.isReady ? "" : " (DOM not ready)"));
            return this
        }
        if (t.delegation) {
            e(document).off("submit.form-plugin", this.selector, r).off("click.form-plugin", this.selector, i).on("submit.form-plugin", this.selector, t, r).on("click.form-plugin", this.selector, t, i);
            return this
        }
        return this.ajaxFormUnbind().bind("submit.form-plugin", t, r).bind("click.form-plugin", t, i)
    };
    e.fn.ajaxFormUnbind = function () {
        return this.unbind("submit.form-plugin click.form-plugin")
    };
    e.fn.formToArray = function (n, r) {
        var i = [];
        if (this.length === 0) {
            return i
        }
        var s = this[0];
        var o = n ? s.getElementsByTagName("*") : s.elements;
        if (!o) {
            return i
        }
        var u, a, f, l, c, h, p;
        for (u = 0, h = o.length; u < h; u++) {
            c = o[u];
            f = c.name;
            if (!f || c.disabled) {
                continue
            }
            if (n && s.clk && c.type == "image") {
                if (s.clk == c) {
                    i.push({
                        name: f,
                        value: e(c).val(),
                        type: c.type
                    });
                    i.push({
                        name: f + ".x",
                        value: s.clk_x
                    }, {
                        name: f + ".y",
                        value: s.clk_y
                    })
                }
                continue
            }
            l = e.fieldValue(c, true);
            if (l && l.constructor == Array) {
                if (r) r.push(c);
                for (a = 0, p = l.length; a < p; a++) {
                    i.push({
                        name: f,
                        value: l[a]
                    })
                }
            } else if (t.fileapi && c.type == "file") {
                if (r) r.push(c);
                var d = c.files;
                if (d.length) {
                    for (a = 0; a < d.length; a++) {
                        i.push({
                            name: f,
                            value: d[a],
                            type: c.type
                        })
                    }
                } else {
                    i.push({
                        name: f,
                        value: "",
                        type: c.type
                    })
                }
            } else if (l !== null && typeof l != "undefined") {
                if (r) r.push(c);
                i.push({
                    name: f,
                    value: l,
                    type: c.type,
                    required: c.required
                })
            }
        }
        if (!n && s.clk) {
            var v = e(s.clk),
                m = v[0];
            f = m.name;
            if (f && !m.disabled && m.type == "image") {
                i.push({
                    name: f,
                    value: v.val()
                });
                i.push({
                    name: f + ".x",
                    value: s.clk_x
                }, {
                    name: f + ".y",
                    value: s.clk_y
                })
            }
        }
        return i
    };
    e.fn.formSerialize = function (t) {
        return e.param(this.formToArray(t))
    };
    e.fn.fieldSerialize = function (t) {
        var n = [];
        this.each(function () {
            var r = this.name;
            if (!r) {
                return
            }
            var i = e.fieldValue(this, t);
            if (i && i.constructor == Array) {
                for (var s = 0, o = i.length; s < o; s++) {
                    n.push({
                        name: r,
                        value: i[s]
                    })
                }
            } else if (i !== null && typeof i != "undefined") {
                n.push({
                    name: this.name,
                    value: i
                })
            }
        });
        return e.param(n)
    };
    e.fn.fieldValue = function (t) {
        for (var n = [], r = 0, i = this.length; r < i; r++) {
            var s = this[r];
            var o = e.fieldValue(s, t);
            if (o === null || typeof o == "undefined" || o.constructor == Array && !o.length) {
                continue
            }
            if (o.constructor == Array) e.merge(n, o);
            else n.push(o)
        }
        return n
    };
    e.fieldValue = function (t, n) {
        var r = t.name,
            i = t.type,
            s = t.tagName.toLowerCase();
        if (n === undefined) {
            n = true
        }
        if (n && (!r || t.disabled || i == "reset" || i == "button" || (i == "checkbox" || i == "radio") && !t.checked || (i == "submit" || i == "image") && t.form && t.form.clk != t || s == "select" && t.selectedIndex == -1)) {
            return null
        }
        if (s == "select") {
            var o = t.selectedIndex;
            if (o < 0) {
                return null
            }
            var u = [],
                a = t.options;
            var f = i == "select-one";
            var l = f ? o + 1 : a.length;
            for (var c = f ? o : 0; c < l; c++) {
                var h = a[c];
                if (h.selected) {
                    var p = h.value;
                    if (!p) {
                        p = h.attributes && h.attributes["value"] && !h.attributes["value"].specified ? h.text : h.value
                    }
                    if (f) {
                        return p
                    }
                    u.push(p)
                }
            }
            return u
        }
        return e(t).val()
    };
    e.fn.clearForm = function (t) {
        return this.each(function () {
            e("input,select,textarea", this).clearFields(t)
        })
    };
    e.fn.clearFields = e.fn.clearInputs = function (t) {
        var n = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;
        return this.each(function () {
            var r = this.type,
                i = this.tagName.toLowerCase();
            if (n.test(r) || i == "textarea") {
                this.value = ""
            } else if (r == "checkbox" || r == "radio") {
                this.checked = false
            } else if (i == "select") {
                this.selectedIndex = -1
            } else if (r == "file") {
                if (/MSIE/.test(navigator.userAgent)) {
                    e(this).replaceWith(e(this).clone(true))
                } else {
                    e(this).val("")
                }
            } else if (t) {
                if (t === true && /hidden/.test(r) || typeof t == "string" && e(this).is(t)) this.value = ""
            }
        })
    };
    e.fn.resetForm = function () {
        return this.each(function () {
            if (typeof this.reset == "function" || typeof this.reset == "object" && !this.reset.nodeType) {
                this.reset()
            }
        })
    };
    e.fn.enable = function (e) {
        if (e === undefined) {
            e = true
        }
        return this.each(function () {
            this.disabled = !e
        })
    };
    e.fn.selected = function (t) {
        if (t === undefined) {
            t = true
        }
        return this.each(function () {
            var n = this.type;
            if (n == "checkbox" || n == "radio") {
                this.checked = t
            } else if (this.tagName.toLowerCase() == "option") {
                var r = e(this).parent("select");
                if (t && r[0] && r[0].type == "select-one") {
                    r.find("option").selected(false)
                }
                this.selected = t
            }
        })
    };
    e.fn.ajaxSubmit.debug = false
})(jQuery);
