/// <reference path="jquery-1.4.4-vsdoc.js" />
// JavaScript Document

var isLoginG = "False";
$(document).ready(function () {
    $('.slide_certs .prev_btn').hide();
    $("#searchText").keypress(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            goToSearch();
        }

    });
    $(document).keyup(function (event) {
        if (event.which == 27) {
            $('.popup').fadeOut();
            hidePop();
        }
    });
    isLoginG = $('#isLogin').val();
    $("#frmSignIn #Password").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btn_key_signin").click();
        }
    });
    $("#frmSignIn #UserName").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btn_key_signin").click();
        }
    });
    if ($("body").attr("id") == "home")
        setInterval("slideSwitch()", 5000);
});
function showHide(elt) {
    if ($(elt).is(':checked')) {
        $(elt).parent().parent().find('.validate_code').show(100);  
    }
    else {
        $(elt).parent().parent().find('.validate_code').removeClass("error");
        $(elt).parent().parent().find('.validate_code').hide(100);
    }
}
var LogginDet = false;
var userComm = "";
  function showLogin() {
    //Hide all messages and input text
    $('#fill_form').show();
    $('#notHere').hide();
    $('#forg_pass').val("");
    if ($('#frmSignIn').length != 0)
     document.getElementById("frmSignIn").reset();
    $("#isnotuser").hide();
    $('#frmSignIn').find('input').each(function () {
        $(this).parent().removeClass('missing');
    });
    //Close PopUP
	 $('#login_pop').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
    });
    $(document).scrollTop(0); 
}
function showForgPass() {
    $('#forg_pass').val("");
	 $('#fill_form').fadeOut();
	 $('#forgot_password').fadeIn();
}
function returnLog() {
    $('#forg_pass').val("");
    $('#forgot_password').fadeOut();
    $('#fill_form').fadeIn();
    $('#notHere').hide();
}
function showThankYou()
{
	 $('#forgot_password').fadeOut();
	 $('#thank_you').fadeIn();
}

function showSearch() {
    
    $('#search_pop .input_search #searchText').val("");
    $('#search_pop').fadeIn('normal', function () {
        document.getElementById('searchText').focus();
        $('body').click(function (event) { popupHide(event) });
    });
}
var openLogin1 = 0;
function openLogin() {
    
    $('#giftVoucher_popup').hide();
    showLogin();
    openLogin1 = 1;
}
var productToDeleteID = -1;
var parentCatName = "";
var BagID = -1;
function showQuestionConf(productID, parentCategoryName, BaggID) {
    productToDeleteID = productID;
    parentCatName = parentCategoryName;
    BagID = BaggID;
    window.scrollTo(0, 0);
    if ($('#mproduct').length == 0) {
        $('#ques_popup').fadeIn('normal', function () {
            $('body').click(function (event) { popupHide1(event) });
        });
    }
    else
    removeProductFromBas();
}
function showRegLogPop() {    
      
    $('#giftVoucher_popup').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide1(event) });
    });
}

function comingSoon() {
    window.scrollTo(0, 0);
    $('#ComingSoon').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide1(event) });
    });
}
function showNutritonsFact() {
    $('#nutritionFacts').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide1(event) });
    });
}
function closeRegLog() {
    $('.popup').fadeOut();
    $('body').unbind('click');
    hidePop(); //$('#giftVoucher_popup').hide();
}
function showAccList(elt)
{
    $('#my_account_pop').fadeIn('normal', function () {
    });
    $('#my_account_pop').mouseleave(function (event) {
        hideHandlerAcc(event);
    });
}

 function hideHandlerAcc(event) {
    var target = $(event.relatedTarget);
    if (!$(target).is("#my_account_pop")) {
        hidePop();
    }
}

function showAddShip(actionUrl) {

    $('.all_shippings_adr').css('min-height', '555px');
    document.getElementById('frmAddShipping').reset();
    $('#frmAddShipping').find('#address').val("") ;
    $('#frmAddShipping').attr("action", actionUrl);
	$('#add_edit_shipping').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
    });
}
function showEditShip(elt,actionUrl) {
    $('.all_shippings_adr').css('min-height', '555px');
    document.getElementById('frmAddShipping').reset();
    window.scrollTo(0, 0);
    $('#frmAddShipping').find('#address').val("") ;
    $('#frmAddShipping').attr("action", actionUrl);
    $('#add_edit_shipping').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
        FillValues(elt);
    });
}

function FillValues(elt) {
    var row = $(elt).parent().parent();
    $('#frmAddShipping #firstName').val($($(row).find('.fname')).text());
    $('#lastName').val($($(row).find('.lname')).text());
    $('#telephone').val($($(row).find('.tel')).text());
    $('#email').val($($(row).find('.mail_ship')).text());
    $("#zipCode").val($($(row).find('#hiddenzipcode')).val());
    $('#frmAddShipping #address').val($($(row).find('.street_floor')).text());
    $('#frmAddShipping #cityState').val($($(row).find('.region')).text()); 
    $("#countryId").find("option").each(function () {
        if ($(this).text() == $($(row).find('.country')).text())
            $(this).attr('selected', 'selected');
        else
            $(this).removeAttr('selected');

    });

}
function showTestimonialForm() {

    $('.testimonials').css('min-height', '633px');
    document.getElementById('frmAddTestimonial').reset();
    $('#frmAddTestimonial').find('input,textarea,select').each(function () {
        $(this).removeClass('missed');
    });
    $('.member').hide();
    $('.fill_req').hide();
	$('.add_testimonial').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
    });
}
function showFeed() {
    document.getElementById('frmFeedback').reset();
    $('#frmFeedback').find('input,textarea,select').each(function () {
        $(this).removeClass('missed');
    });
    $('.member').hide();
    $('.fill_req').hide();
	$('#feedback_pop').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
    });	
}
function popupHide(event) {
if(openLogin1 == 0){
    if ($('.popup').length != 0 && !$(event.target).closest('.popup').length && !$(event.target).closest('.login').length && !$(event.target).closest('.search').length && !$(event.target).closest('.tab_orders').length && !$(event.target).closest('#contact_form').length) {
        $('.popup').fadeOut();
        $('body').unbind('click');
        hidePop();
    }
    else {
        setTimeout(function () {
            openLogin1 = 0;

        },2000);
    }
    }
}
function popupHide1(event) {
    if (openLogin1 == 0) {
        if (!$(event.target).closest('.popQuest').length && $('.popup').length != 0) {
            $('.popup').fadeOut();
            $('body').unbind('click');
            hidePop();
        }
    }
    else {
        setTimeout(function () {
            openLogin1 = 0;

        }, 2000);
    }
}
function hidePop()
{
	$('#fill_form').hide();
	$('#forgot_password').hide();
	$('#thank_you').hide();
	$('#search_pop').hide();
	 $('#my_account_pop').hide();
	 $('#add_edit_shipping').hide();
	 $('#feedback_pop').hide();
	 $('.add_testimonial').hide();
	 $('#ques_popup').hide();
	 if ($('.testimonials').length != 0) {
	     $('.testimonials').css('min-height', '0px');
	 }
	 if ($('#my_orders_popup').length != 0) {
	     $('body').unbind('click');
	     $('#my_orders_popup').hide();
	 }
	 if ($('.all_shippings_adr').length !=0)
     {
       $('.all_shippings_adr').css('min-height','0px');
   }
   $('#login_pop').hide();

}
function closeQuest() {
    $('.popup').fadeOut();
    $('body').unbind('click');
    $('#ques_popup').hide();
}
function showReg()
{
	$('.member').show();
}
function hideRow(elt)
{
	$(elt).parent().fadeOut();
}
function hideShip(elt)
{
	$(elt).parent().parent().fadeOut();
}
function selectYear(elt) {
    var currentIndex = $('.ruler > .selected').index();
    var lastIndex = currentIndex;
    currentIndex = $(elt).index();
    $($('.year')[lastIndex]).removeClass("selected");
    $($('.year')[currentIndex]).addClass("selected");
	$($('.all_txt_pics > .text_pic')[lastIndex]).hide();
	$($('.all_txt_pics > .text_pic')[currentIndex]).fadeIn();

}

function showDesc(elt)
{
	$(elt).parent().find('.desc_country_bg').show();
}
function hideDesc(elt)
{
	$(elt).hide();
}

              
function validate(elt) {
    if ($(elt).parent().find('input').val() == 'Enter your code here' || $(elt).parent().find('input').val() == '') {
        $(elt).parent().addClass('error');
        $('#chk_promotion').attr('checked', 'checked');
//        $(elt).parent().find('input').click(function () {
//            $(elt).parent().removeClass('error');
//        });
    }
    else {
        var currenturl = window.location.toString();
        var from = 0;
        if (currenturl.indexOf("/basket") != -1) {
            from = 1;
        }
        var routeURL = document.getElementById("routeURL").value;
        var couponCode = $(elt).parent().find('input').val(); 
        var BasketID = $("#BasketID").val();
        var poststr = "ekomBasketId=" + BasketID + "&couponCode=" + couponCode + "&from=" + from;
        $(".validate_code").append("<div class='ValidateLoader'></div>")
        $.ajax({
            url: routeURL + 'yourBasket/AssignCoup',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                $(".validate_code").find(".ValidateLoader").remove();
                document.getElementById("promCode_id").innerHTML = ''
                document.getElementById("promCode_id").innerHTML = data;
                $('#chk_promotion').attr('checked', 'checked');
            }
        });
       
        }

}
function assignVoucherCredit(BasketID) {
    var routeURL = document.getElementById("routeURL").value;
    var poststr = "ekomBasketId=" + BasketID;
    $.ajax({
        url: routeURL + 'yourBasket/AssignVoucherC',
        type: 'POST',
        data: '' + poststr,
        success: function (data) {           
            document.getElementById("promCode_id").innerHTML = ''
            document.getElementById("promCode_id").innerHTML = data;
        }
    });
}

function deleteVoucherCredit(BasketID) {
    var routeURL = document.getElementById("routeURL").value;
    var poststr = "ekomBasketId=" + BasketID;
    $.ajax({
        url: routeURL + 'yourBasket/deleteVoucherC',
        type: 'POST',
        data: '' + poststr,
        success: function (data) {            
            document.getElementById("promCode_id").innerHTML = ''
            document.getElementById("promCode_id").innerHTML = data;
        }
    });
}
function showValidation(elt) {
    var currenturl = window.location.toString();
var from = 0;
if(currenturl.indexOf("/basket") != -1){
    from = 1;
}
    var routeURL = document.getElementById("routeURL").value;
    var couponCode = $(elt).parent().find('input').val();
    var BasketID = $("#BasketID").val();
    var poststr = "ekomBasketId=" + BasketID + "&from=" + from;
    $.ajax({
        url: routeURL + 'yourBasket/removeCoup',
        type: 'POST',
        data: '' + poststr,
        success: function (data) {

            document.getElementById("promCode_id").innerHTML = ''
            document.getElementById("promCode_id").innerHTML = data;
            
           
        }
    });
//    $(elt).parent().parent().hide();
//    $(elt).parent().parent().parent().find('.validate_code').fadeIn();
}
function showStar() {
    $('.star_s').show();
    $('.star_s').mouseleave(function (event) {
        hideHandlerStar(event);
    });
}
function hideHandlerStar(event) {
    var target = $(event.relatedTarget);
    if (!$(target).is(".fav_s")) {
        hideStar();
    }
}
function hideStar() {
    $('.star_s').hide();
}
function showQuestion() {
    $('.question_mixing').fadeIn();
}

function showPreNuts(elt, catID) {

    /// CHCK if the NUTS ID DIFFERENT THEN CATID /////////////////////////// 
     var currentcatId = document.getElementById("currentcatId").value;
     if (currentcatId != catID) {
         $('.' + catID).stop().animate({
             top: "0"
         }, 300, function () {
         });
         $('.' + catID).css('z-index', '11');
         $('.nuts_container').css('z-index', '9');
         $('#' + elt).mouseleave(function (event) {
             hideHandler(event, catID);
         });
     }
        /////////////////////// /////////////////////// /////////////////////// 

}

function hideHandler(event, catID) {   
  var target = $(event.relatedTarget);
  if( !$(target).is("#nuts")) {
      showNormal(catID);
  }
}

function showMixNuts(elt, catID) {
 /// CHCK if the NUTS ID DIFFERENT THEN CATID ///////////////////////////
    var currentcatId = document.getElementById("currentcatId").value;
    if (currentcatId != catID) {
        $('.' + catID).stop().animate({
            top: "0"
        }, 300, function () {
        });
        $('.' + catID).css('zIndex', '12');
        $('.nuts_container').css('zIndex', '9');
        $('#' + elt).mouseleave(function (event) {
            hideHandler(event, catID);
        });
    }
        /////////////////////// /////////////////////// /////////////////////// 
}
function showNormal(nutID) {
    var currentcatId = document.getElementById("currentcatId").value;    
    $('.' + currentcatId).css('top', '0px!important');
    $('.' + currentcatId).css('zIndex', '11!important');
    $('.' + currentcatId).css('background-color', '#FFF!important');
    $('.nuts_container').css('zIndex', '9');
    var indexOFCurrentID = $('.' + currentcatId).index();
    var btnofIndex = $($($('.main_menu').find('.btn'))[indexOFCurrentID]);
     $(btnofIndex).mouseleave(function (event) {
        
    });
    $('.nuts_container').find('#nuts').each(function () {
        if ($(this).attr('class').split(' ')[1] != currentcatId) {
            if ($(this).position().top == 0) {
                $(this).stop().animate({
                    top: "-104"
                }, 300, function () {
                });
                $(this).css('zIndex', '10!important');
                $(this).css('background-color', 'transparent!important');
            }
        }
    });  
    $('.nuts_container').css('zIndex', 'auto');
}
function setProducts(catID) {
    $('#nuts').removeClass('specialClass');
    $('.nuts_container .' + catID).addClass('specialClass');
    $('.nuts_container').css('zIndex', '9');
}
function is_child_of(parent, child) {
    if (child != null) {
        while (child.parentNode) {
            if ((child = child.parentNode) == parent) {
                return true;
            }
        }
    }
    return false;
}
function fixOnMouseOut(element, event, catID) {
 var current_mouse_target = null;
   if (event.toElement) {
       current_mouse_target = event.toElement;
  } else if (event.relatedTarget) {
      current_mouse_target = event.relatedTarget;
   }
  if (!is_child_of(element, current_mouse_target) && element != current_mouse_target) {
  var currentcatId = document.getElementById("currentcatId").value;
  if (currentcatId != catID) {
      showNormal(catID);
  }
    }
}

function showTrack() {
    $('#my_orders_popup').fadeIn('normal', function () {
        $('body').click(function (event) { popupHide(event) });
    });	
}

function slideSwitch() {
    if ($("#slide_show").find(".show").length > 1) {
        var $active = $('#slide_show DIV.active');

        if ($active.length == 0) $active = $('#slide_show DIV:last');

        var $next = $active.next().length ? $active.next()
        : $('#slide_show DIV:first');
        $active.addClass('last-active').animate({ opacity: 0.0 }, 1000);
        $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 1000, function () {
            $active.removeClass('active last-active');
        });
    }
    }

    function validateForm(frmId) {        
        hideMessages();
        test = false;
        var routeURL = document.getElementById("routeURL").value;
        $('#' + frmId).find('input,textarea,select').each(function () {
            var isError = false;
            //var test = false;

            var elem;
            if (($(this).attr('required') == '1' && $(this).attr('value').length == 0) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value'))) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value')))) {
                if (frmId == "frmSignIn")
                    $(this).parent().addClass('missing');
                else
                    $(this).addClass('missed');
                isError = true;
                test = true;
                if (!elem) elem = $(this);
            } else {
                if (frmId == "frmSignIn")
                    $(this).parent().removeClass('missing');
                else
                    $(this).removeClass('missed'); 
            }
        });

        if (frmId == "frmDistributor") {
            if ($($('#frmDistributor').find('#countryId')).val() == "0") {
                $('#frmDistributor #countryId').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#frmDistributor #countryId').removeClass('missed');
            }
        }

        if (frmId == "frmRegister") {
            if ($($('#frmRegister').find('#Password')).val() != $('#ConfirmPassword').val()) {
                $('#ConfirmPassword').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#ConfirmPassword').removeClass('missed');
            }
        }
        if (frmId == "frmPayment") {
            if ($($('#frmPayment').find('#country')).val() == "0") {
                $('#frmPayment #country').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#frmPayment #country').removeClass('missed');
            }
        }
        if ($('#calendargoeshere').length != 0 && $('#dob').length != 0 && frmId != "frmSignIn") {
              var Dob_val = $('#dob').val();
              var newDob_val = Dob_val.replace(" ", "");
              if (frmId == "frmDeliveryDetails") {
                  if (newDob_val == "" && $('#deliveryDate').val() =="") {
                      $('#dob').addClass('missed');
                      isError = true;
                      test = true;
                  }
                  else {
                      $('#dob').removeClass('missed');
                  }
              }
              else {
                  if (newDob_val == "") {
                      $('#dob').addClass('missed');
                      isError = true;
                      test = true;
                  }
                  else {
                      $('#dob').removeClass('missed');
                  }
              }
        }
        if (frmId == "frmDeliveryDetails") {
            if ($('#giftMessage').val() == "Write your message" || $('#giftMessage').val() == "") {
                $('#giftMessage').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#giftMessage').removeClass('missed');
            }
        }
        if (frmId == "frmNewsLetter") {
            if ($('#frmNewsLetter #countryId').val() == "0") {
                $('#frmNewsLetter #countryId').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#frmNewsLetter #countryId').removeClass('missed');
            }        
        }
        if (test == false) {
            if (frmId=="frmSignIn")
                $('#loading_sgnin').show();
            else if (frmId == "frmRegister")
                $('#reg_loading').show();
            else
                $('.loading').show();
            $.post($('#' + frmId).attr('action'),
            $('#' + frmId).serialize() /*  { firstName: $('#firstName').val(), lastName: $('#lastName').val(), telephone: $('#telephone').val(), mobile: $('#mobile').val(), email: $('#email').val(), countryId: $('#countryId').val(), comment: $('#comment').val() }*/,
                function (data) {
                    if (data.split("*/*")[0] == "success") {
                        if ($('#typeReg').length != 0) {
                            if ($('#typeReg').val() == "2")
                                window.location.reload();
                        }

                        if (frmId == "frmSignIn") {
                            if (!LogginDet)
                                window.location.reload();
                                //window.location = routeURL;
                            else {
                                if ($('#frmSignIn').length != 0) {
                                    document.getElementById("frmSignIn").reset();
                                    $('#frmSignIn').find('input').each(function () {
                                        $($(this).parent()).removeClass("missing");
                                    });
                                }
                                $('.popup').fadeOut();
                                $('#login_pop').fadeOut();
                                hidePop();
                                var heightDec = ($(document).height()) - ($('.bgfooter').height() + 300);
                                if (heightDec < 0)
                                    heightDec = 0;
                                $('html, body').animate({ scrollTop: heightDec }, 1500);
                                isLoginG = "True";
                                LogginDet = false;
                                addCommentToProduct('True');
                            }
                        }
                        else if (frmId == "frmDeliveryDetails")
                            window.location = $('#paymentURL').val();
                        else if (frmId == "frmRegister") {
                            if ($("#messup").length != 0) {
                                window.location = $('#shippingURL').val();
                            } else {
                                //window.location.reload();
                                window.location = routeURL;
                            }
                        }
                        if (frmId == "frmAddShipping" && $("#frmAddShipping").attr("action").indexOf("EditShippingInfo") == -1 && window.location.toString().indexOf("myAccount") == -1) {
                            var id = data.split("*/*")[1];
                            window.location = routeURL + "yourBasket/Deliverydetails?ekomShippingInfoId=" + id;
                        }
                        else {
                            $('.fill_req').hide();
                            $('.loading').hide();
                            $('.member').show();
                            setTimeout("hideSuccess()", 5000);
                        }

                    }
                    else {
                        if (frmId == "frmSignIn") {
                            $('#frmSignIn').fadeOut();
                            $('#loading_sgnin').fadeIn();
                            setTimeout("showSignin()", 5000);
                        }
                        if (frmId == "frmRegister") {
                            $(".registration_part").append("<span style='top: 10px; margin-left: 16px; color: red;'>Your Email already exists in our DataBase.</span>");
                            $("#reg_loading").hide();
                        }   

                    }
                });
        }
            else {
                if (frmId == "frmDeliveryDetails") {
                    $(".next_skip").append("<span style='top: 10px; margin-left: 16px; color: red;'>Please fill in the required fields or skip this step.</span>")
                }
                if ($('#typeReg').length != 0) {
                    if ($('#typeReg').val() == "2")
                        $('#fq_2').show();
                    $('.fill_req').show();
                }
                else {
                    $('.fill_req').show();
                    $('.member').hide();
                }
                 
        }
     }
   
    function showSignin() {
        $('#loading_sgnin').fadeOut();
        $('#isnotuser').show();
        $('#frmSignIn').fadeIn();
    }

    function SignIn(frmId) {
       
        test = false;
        $('#fq1').hide();
        $('#isnotuser1').hide();   
        $('#' + frmId).find('input,textarea,select').each(function () {
            var isError = false;
            //var test = false;

            var elem;
            if (($(this).attr('required') == '1' && $(this).attr('value').length == 0) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value'))) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value')))) {
                $(this).addClass('missed');
                isError = true;
                test = true;
                if (!elem) elem = $(this);
            } else {
                $(this).removeClass('missed');

            }
        });

        if (test == false) {
            $('#l1').show();
            $.post($('#' + frmId).attr('action'),
          $('#' + frmId).serialize(),
                function (data) {
                    if (data == "success") {
                        $('#l1').hide();
                        if (frmId == "frmSignINU") {
                            window.location.reload();
                        }
                    }
                    else {
                        $('#l1').hide();
                        //$('#isnotuser1').show();
                        $('#fq2').show();
                    }
                });
        }
        else {
             $('#fq1').show();
        }
       
    }
    function showForgetting() {
        $('#forg_pass1').val("");
        $('#inputs_Sign').find('input').each(function () {
            $(this).removeClass('missed');
            $(this).val("");             
        });
        $('#inputs_Sign').hide();
        $('#forgot_password1').show();
        $("#Password").removeAttr("required");
    }
    function hideForgetting() {
        $('#forg_pass1').val("");
        $('#inputs_Sign').find('input').each(function () {
            $(this).removeClass('missed');
            $(this).val("");
        });

        $('#inputs_Sign').show();
        $('#forgot_password1').hide();
    }
    function hideMessages(){
       $('.member').hide();
       $('.fill_req').hide();
    }
    function hideLoad() {
        $('.loading').hide();
        $('.member').show();
        setTimeout("hideSuccess()", 5000);
    }
    function hideSuccess() {
        if ($('#frmRegister').length == 0)
         $('.member').hide();
        if ($('#frmAddTestimonial').length != 0)
            document.getElementById('frmAddTestimonial').reset();
        if ($('#frmContactUs').length != 0)
            document.getElementById('frmContactUs').reset();
        if($('#frmDistributor').length!=0)
            document.getElementById('frmDistributor').reset();
        if ($('#frmFeedback').length != 0)
            document.getElementById('frmFeedback').reset();
        if ($('#frmAddShipping').length != 0) {
            document.getElementById('frmAddShipping').reset();
            $('#frmAddShipping').find('#address').val("");
        }
        if ($('#frmsendGift').length != 0)
            document.getElementById('frmsendGift').reset();
        if ($('#frmNewsLetter').length != 0)
            document.getElementById('frmNewsLetter').reset();
            window.location.reload();       
    }    

    function IsValidEmail(email) {
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return filter.test(email);
    }

    /validate number/
    function IsValidNumber(number) {
        var filter = /[0-9]+/;
        return filter.test(number);
    }



    // click once on checkbox
    function cleanInput(objc) {
        $("#jobs_opennings").find("input").each(function () {
            $(this).removeAttr('checked')
            $(objc).attr('checked', 'checked')
        });
        $(".row_job").removeClass('selected');        
        $($(objc).parent()).addClass('selected');
        var titleJob = $(objc).parent().find('.title_job').text();
        changeSelection(titleJob);
    }

    function changeDisable(elt) {
        if ($(elt).is(':checked')) {           
            $('#frmDeliveryDetails #senderName').attr('disabled', 'disabled');
            $('#frmDeliveryDetails #senderName').attr("required", "0");
            $('#frmDeliveryDetails #senderName').val("");
            $($('#frmDeliveryDetails #senderName').parent()).addClass("gray");
        }
        else {
            $('#frmDeliveryDetails #senderName').removeAttr('disabled');
            $('#frmDeliveryDetails #senderName').attr("required", "1");
            $($('#frmDeliveryDetails #senderName').parent()).removeClass("gray");
        }
    }
    function changeSelection(titleJob) {
        $("#Position").find("option").each(function () {
            if ($(this).text() == titleJob)
                $(this).attr('selected', 'selected');
            else
                $(this).removeAttr('selected');

        });

    }
 
    function changeCurrency(pIndex) {
        var part_number = 0;
        var isOrderValue = -1;
        if ($('#sortddl').length != 0)
            isOrderValue = document.getElementById("sortddl").value; 
        var currencyId_dropy = document.getElementById("currency_ddl").value; 
        var routeURL = document.getElementById("routeURL").value;
        var currentUrl = document.getElementById("currentUrl").value;
        var newcurrentUrl = currentUrl.split("?");
        var array = newcurrentUrl[0].split("/");
        if (array[2] == "shift") {            
                part_number = 4;
        } else {
                part_number = 3;
                routeURL = "http://"+ array[2];
        }
        var myUrl = "";
        while (part_number < array.length) {
            myUrl = myUrl + "/" + array[part_number];
            part_number += 1;
        }
        var poststr = "currencyId_dropy=" + encodeURI(currencyId_dropy);
        if ($("body").attr("id") == "nDetails")
            window.location = routeURL + myUrl + "?currencyId=" + currencyId_dropy;
        else
            if ($("body").attr("class") == "searchPage")
                window.location = routeURL + myUrl + "?PageIndex=" + pIndex + "&isorder=" + isOrderValue + "&currencyId=" + currencyId_dropy + "&criteria=" + $('#criteria_s').text();
            else
                window.location = routeURL + myUrl + "?PageIndex=" + pIndex + "&isorder=" + isOrderValue + "&currencyId=" + currencyId_dropy;
    }

    function showDiv(elt, idDIV, idSiblingDiv) {
        $(elt).removeClass('selected');
        $(elt).siblings().removeClass('selected');
        $(elt).addClass('selected');
        $('#' + idDIV).fadeIn();
        $('#' + idSiblingDiv).fadeOut();
    }

    function roll_over(img_name, img_src, idItem) {
        document[img_name].src = img_src;
        $('.your_desc_1').removeClass('selected');
        $('#' + idItem).addClass('selected');
    }

    function submitSelect(uRL, isOrdered, pgIndex, viewall) {
        var currencyId_dropy = document.getElementById("currency_ddl").value;      
            if (viewall == 0)
                window.location = uRL + "?PageIndex=" + pgIndex + "&isorder=" + isOrdered + "&currencyId=" + currencyId_dropy;
            else
                window.location = uRL + "?PageIndex=" + pgIndex + "&isorder=" + isOrdered + "&viewall=" + viewall + "&currencyId=" + currencyId_dropy;
        }
        function submitSelectSearch(uRL, isOrdered, pgIndex, viewall) {
            var currencyId_dropy = document.getElementById("currency_ddl").value;
            if (viewall == 0)
                window.location = uRL + "&PageIndex=" + pgIndex + "&isorder=" + isOrdered + "&currencyId=" + currencyId_dropy;
            else
                window.location = uRL + "&PageIndex=" + pgIndex + "&isorder=" + isOrdered + "&viewall=" + viewall + "&currencyId=" + currencyId_dropy;
        }

    function IncNb(elt) {
        var parentElt = $(elt).parent().parent();
        $($(parentElt).find('.num')).text(parseInt($($(parentElt).find('.num')).text()) + 1);        
    }

    function DecNb(elt) {
        var parentElt = $(elt).parent().parent();
        if (parseInt($($(parentElt).find('.num')).text()) > 1)
            $($(parentElt).find('.num')).text(parseInt($($(parentElt).find('.num')).text()) - 1);
    }
   
    function IncNbM(elt) {
        var parentElt = $(elt).parent().parent();
        if (parseInt($($(parentElt).find('.num')).text()) == 500) {
            $($(parentElt).find('.num')).text("1");
            $('.add_to_basket .ddl_gramme #dl_grame').text("kg");
            ChangePrice("inc");
        }
        else {
            $($(parentElt).find('.num')).text(parseFloat($($(parentElt).find('.num')).text()) + 0.5);
            $('.add_to_basket .ddl_gramme #dl_grame').text("kg");
            ChangePrice("inc");
        }
    }

    function DecNbM(elt) {
        var parentElt = $(elt).parent().parent();
        if (parseFloat($($(parentElt).find('.num')).text()) == 1) {
            $($(parentElt).find('.num')).text("500");
            $('.add_to_basket .ddl_gramme #dl_grame').text("g");
            ChangePrice("dec");
        }
        else {
            if (parseFloat($($(parentElt).find('.num')).text()) != 500 && parseFloat($($(parentElt).find('.num')).text()) != 1) {
                $($(parentElt).find('.num')).text(parseFloat($($(parentElt).find('.num')).text()) - 0.5);
                //$('.add_to_basket .ddl_gramme #dl_grame').text("g");
                ChangePrice("dec");
            }
        }
        
    }
    function ChangePrice(inc) {
        var QteBYPrice = Number($('#priceDefault').val());
        var initialWeight = $('#initialWeight').val();
//        var newPrice = Number((QteBYPrice * 1000) / initialWeight).toFixed(2);    
//        if(inc=="dec")
//            newPrice = Number((QteBYPrice * 500) / initialWeight).toFixed(2);
//        $('.price .det_price').text(newPrice);
    }
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    function IncNbB(elt, productID, BasketID , UserID, Qty) {

        UpdateProdBask(elt,productID, BasketID, UserID, Qty, "inc");       
    }

    function DecNbB(elt, productID, BasketID, UserID, Qty) {
        UpdateProdBask(elt,productID, BasketID, UserID, Qty, "dec");
    }
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    function IncNbBM(elt, productID, BagID, Qty) {

        UpdateProdBag(elt, productID, BagID, Qty, "inc");
    }

    function DecNbBM(elt, productID, BagID, Qty) {
        UpdateProdBag(elt, productID, BagID, Qty, "dec");
    }
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    var working = false;
    function UpdateProdBag(elt, productID, BagID, Qty, inc) {
        var parentElt = $(elt).parent().parent();
        var InitialQty = parseFloat($($(parentElt).find('.num .w_mix')).text()); //get the initial value from the display

        if (InitialQty < 500) {  //Check if the value is in KG or G
            InitialQty = InitialQty * 1000;   //if the value is in KG convert to G
        }

       

        if (!(inc == "dec" && InitialQty <= 500)) {
            if (!working) {
                working = true;
                if (inc == "inc") {
                    InitialQty = parseFloat($($(parentElt).find('.num .w_mix')).text());
                    if (InitialQty < 500) {
                        InitialQty = InitialQty * 1000; //if the value is in KG convert to G
                    }
                    Qty = InitialQty + 500; //Increment The value By 500G
                }
                else {
                    InitialQty = parseFloat($($(parentElt).find('.num .w_mix')).text());
                    if (InitialQty < 500) {
                        InitialQty = InitialQty * 1000; //if the value is in KG convert to G
                    }
                    Qty = InitialQty - 500; //Decrement The value By 500G
                }

                $($(elt).parent().parent().parent().find('.speciaLoader')).show(); //Show the Loader

                var routeURL = document.getElementById("routeURL").value; //Route URL.

                var poststr = "ekomProductId=" + productID + "&EKomBagId=" + BagID + "&quantity=" + Qty; //Post Arguments

                $.ajax({
                    url: routeURL + 'KMS/EKomBag/UpdateProductInBag',
                    type: 'POST',
                    data: '' + poststr,
                    success: function (data) {

                        if (data == "success") {
                            //Hide Loader
                            $($(elt).parent().parent().parent().find('.speciaLoader')).hide();
                            //Modify Prices value
                            if (inc == "inc")
                                IncNbMix(elt);
                            else
                                DecNbMix(elt);

                            var newQty = parseFloat($($(parentElt).find('.num .w_mix')).text()); // Qty choosed
                            if (newQty < 500) {
                                newQty = newQty * 1000;
                            }
                            var hello = $('#row_pre_' + productID).attr('class');
                            var hello1 = $('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0];
                            var hello2 = Number($('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0]);
                            var QteinKms = (Number($('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0])); // GEt the initialweight/2 (prices showed for the mainPrice/2)
                            var oldPrice = Number($('#main_price_' + productID).text()).toFixed(2); // main Price 
                            var newPrice = Number((newQty * oldPrice) / 1000).toFixed(2); // New Price related to the Qty Choosed 
                            var oldItemPrice = Number($('#totPrix_' + productID).text()).toFixed(2);

                            $('#totPrix_' + productID).text(newPrice); // Set totPrix with the new Price for 1 Product                       
                            if (inc == "inc") {
                                $('.totPrixB').text(Number(Number(Number($('.totPrixB').text()).toFixed(2)) + Number(newPrice - oldItemPrice)).toFixed(2));
                                //$('.promotional_code .total_shi_price .price .tPrice').text($('.totPrixB').text());
                                if ($('.nb_dollars').find('.nbdollars').length != 0)
                                    $($('.nb_dollars').find('.nbdollars')).text(Number(Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) + Number(Number(oldPrice).toFixed(2))).toFixed(2));


                            }
                            else if (inc == "dec") {
                                $('.totPrixB').text(Number(Number(Number($('.totPrixB').text()).toFixed(2)) - Number(oldItemPrice - newPrice)).toFixed(2));
                                // $('.promotional_code .total_shi_price .price .tPrice').text($('.totPrixB').text());
                                if ($('.nb_dollars').find('.nbdollars').length != 0)
                                    $($('.nb_dollars').find('.nbdollars')).text(Number(Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) - Number(Number(oldPrice).toFixed(2))).toFixed(2));

                            }
                            $.ajax({
                                url: routeURL + 'yourBasket/reviewTotal',
                                type: 'POST',
                                data: '',
                                success: function (data) {
                                    document.getElementById("promCode_id").innerHTML = ''
                                    document.getElementById("promCode_id").innerHTML = data;
                                }
                            });

                            working = false;
                        }
                        else {
                            working = false;
                        }

                    }
                });
            }
        }
    }

    function IncNbMix(elt) {
        var parentElt = $(elt).parent().parent();
        if (parseFloat($($(parentElt).find('.num .w_mix')).text()) == 500) {
            $($(parentElt).find('.num .w_mix')).text("1");
            $($(parentElt).find('.num .unitImp')).text("Kg");
        } else {
            $($(parentElt).find('.num .w_mix')).text(parseFloat($($(parentElt).find('.num .w_mix')).text()) + 0.5);
            $($(parentElt).find('.num .unitImp')).text("Kg");
        }
    }
    function DecNbMix(elt) {
        var parentElt = $(elt).parent().parent();
        if (parseFloat($($(parentElt).find('.num .w_mix')).text()) != 1) {
            $($(parentElt).find('.num .w_mix')).text(parseFloat($($(parentElt).find('.num .w_mix')).text()) - 0.5);
        }
        else {
            $($(parentElt).find('.num .w_mix')).text("500");
            $($(parentElt).find('.num .unitImp')).text("g");

        }
    }



    function UpdateProdBask(elt, productID, BasketID, UserID, Qty, inc) {
        var breakingAndEntering;
        var isItLogin = $("#isLogin").val();
        var parentElt = $(elt).parent().parent();
        var oldQty = parseFloat($($(parentElt).find('.priceImp')).text());
        

        var mixorNaugat = false;
        if ($('#row_pre_' + productID).hasClass('malban')) {
            mixorNaugat = true;
        }
        if (oldQty < 500 && mixorNaugat) {
            breakingAndEntering = oldQty * 1000;
        }
        //if(mixorNaugat == true && ) 
        if (!(inc == "dec" && parseInt($($(parentElt).find('.priceImp')).text()) <= 1 && !mixorNaugat) && !(inc == "dec" && breakingAndEntering <= 500 && mixorNaugat)) {
            if (!working) {
                working = true;
                if (inc == "inc") {
                    Qty = parseInt($($(parentElt).find('.num')).text()) + 1;
                    if (mixorNaugat) {
                        Qty = parseFloat($($(parentElt).find('.priceImp')).text());
                        if (Qty == 500) {
                            Qty = Qty + 500;
                        }
                        else {
                            Qty = Qty * 1000 + 500;
                        }
                    }
                }
                else {
                    Qty = parseInt($($(parentElt).find('.num')).text()) - 1;
                    if (mixorNaugat) {
                        Qty = parseFloat($($(parentElt).find('.priceImp')).text());
                        if (Qty == 500) {
                            Qty = Qty - 500;
                        }
                        else {
                            Qty = Qty * 1000 - 500;
                        }
                    }
                }
                $($(elt).parent().parent().parent().find('.speciaLoader')).show();

                var routeURL = document.getElementById("routeURL").value;
                if (isItLogin == "True")
                    var poststr = "ekomProductId=" + productID + "&ekomBasketId=" + BasketID + "&userId=" + UserID + "&quantity=" + Qty;
                else
                    var poststr = "ekomProductId=" + productID + "&ekomBasketId=" + BasketID + "&quantity=" + Qty;
                $.ajax({
                    url: routeURL + 'KMS/EKomBasket/UpdateProductInBasket',
                    type: 'POST',
                    data: '' + poststr,
                    success: function (data) {

                        if (data == "success") {
                            //Hide Loader
                            $($(elt).parent().parent().parent().find('.speciaLoader')).hide();
                            //Modify Prices value
                            if (!mixorNaugat) {
                                if (inc == "inc")
                                    IncNb(elt);
                                else
                                    DecNb(elt);
                            }
                            else {
                                var parentElt = $(elt).parent().parent();
                                if (inc == "inc") {
                                    if (parseFloat($($(parentElt).find('.priceImp')).text()) == 500) {
                                        $($(parentElt).find('.priceImp')).text("1");
                                        $($(parentElt).find('.unitImp')).html("Kg");
                                    }
                                    else {
                                        $($(parentElt).find('.priceImp')).text(parseFloat($($(parentElt).find('.priceImp')).text()) + 0.5);
                                        $($(parentElt).find('.unitImp')).html("Kg");
                                    }
                                }
                                else {
                                    if (parseFloat($($(parentElt).find('.priceImp')).text() == 1)) {
                                        $($(parentElt).find('.priceImp')).text(500);
                                        $($(parentElt).find('.unitImp')).html("g");

                                    }
                                    else {
                                        $($(parentElt).find('.priceImp')).text(parseFloat($($(parentElt).find('.num')).text()) - 0.5);
                                        $($(parentElt).find('.unitImp')).html("Kg");
                                    }


                                }

                            }

                            var newQty = parseFloat($('#row_pre_' + productID).find('.num').text()); // Qty choosed 
                            if (mixorNaugat) {
                                newQty = parseFloat($('#row_pre_' + productID).find('.priceImp').text()); // Qty choosed 
                            }
                            var oldPrice = Number($('#main_price_' + productID).text()); // main Price

                            var newPrice = newQty * oldPrice; // New Price related to the Qty Choosed 

                            var oldTotPrix = Number($('#totPrix_' + productID).text()); // Old Total Price for 1 Product 

//                            if (mixorNaugat) {
//                                var initweight = $('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0];
//                                newPrice = Number(Number((newQty * oldTotPrix) / oldQty).toFixed(2));
//                            }
                            $('#totPrix_' + productID).text(newPrice.toFixed(2)); // Set totPrix with the new Price for 1 Product   

                            if (inc == "inc") {

                                $('.totPrixB').text((Number($('.totPrixB').text()) + (newPrice - oldTotPrix)).toFixed(2));
                                if ($('.nb_dollars').find('.nbdollars').length != 0)
                                    $($('.nb_dollars').find('.nbdollars')).text((Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) + oldPrice).toFixed(2));

                            }
                            else if (inc == "dec") {
                                $('.totPrixB').text((Number($('.totPrixB').text()) - (oldTotPrix - newPrice)).toFixed(2));
                                if ($('.nb_dollars').find('.nbdollars').length != 0)
                                    $($('.nb_dollars').find('.nbdollars')).text((Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) - oldPrice).toFixed(2));

                            }
                            $.ajax({
                                url: routeURL + 'yourBasket/reviewTotal',
                                type: 'POST',
                                data: '',
                                success: function (data) {
                                    document.getElementById("promCode_id").innerHTML = ''
                                    document.getElementById("promCode_id").innerHTML = data;
                                }
                            });
                            working = false;
                        }
                        else {
                            working = false;
                        }

                    }
                });
            }
        }
    }



    /////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////Backup//////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
//    function UpdateProdBask(elt, productID, BasketID, UserID, Qty, inc) {
//        var isItLogin = $("#isLogin").val();
//        var parentElt = $(elt).parent().parent();
//        var oldQty = parseInt($($(parentElt).find('.num')).text());
//        var mixorNaugat = false;
//        if ($('#row_pre_' + productID).hasClass('malban'))
//            mixorNaugat = true;       
//        if (!(inc == "dec" && parseInt($($(parentElt).find('.num')).text()) <= 1 && !mixorNaugat) && !(inc == "dec" && parseInt($($(parentElt).find('.num')).text()) <= 500 && mixorNaugat)) {
//         if (!working) {
//             working = true;
//             if (inc == "inc") {
//                 Qty = parseInt($($(parentElt).find('.num')).text()) + 1;
//                 if (mixorNaugat)
//                     Qty = parseInt($($(parentElt).find('.num')).text()) + 500;
//             }
//             else {
//                 Qty = parseInt($($(parentElt).find('.num')).text()) - 1;
//                 if (mixorNaugat)
//                     Qty = parseInt($($(parentElt).find('.num')).text()) - 500;
//             }
//             $($(elt).parent().parent().parent().find('.speciaLoader')).show();
//             var routeURL = document.getElementById("routeURL").value;
//             if (isItLogin == "True")
//                 var poststr = "ekomProductId=" + productID + "&ekomBasketId=" + BasketID + "&userId=" + UserID + "&quantity=" + Qty;
//             else
//                 var poststr = "ekomProductId=" + productID + "&ekomBasketId=" + BasketID + "&quantity=" + Qty;
//             $.ajax({
//                 url: routeURL + 'KMS/EKomBasket/UpdateProductInBasket',
//                 type: 'POST',
//                 data: '' + poststr,
//                 success: function (data) {

//                     if (data == "success") {
//                         //Hide Loader
//                         $($(elt).parent().parent().parent().find('.speciaLoader')).hide();
//                         //Modify Prices value
//                         if (!mixorNaugat) {
//                             if (inc == "inc")
//                                 IncNb(elt);
//                             else
//                                 DecNb(elt);
//                         }
//                         else {
//                             var parentElt = $(elt).parent().parent();
//                             if (inc == "inc")
//                                 $($(parentElt).find('.num')).text(parseInt($($(parentElt).find('.num')).text()) + 500);
//                             else
//                                 $($(parentElt).find('.num')).text(parseInt($($(parentElt).find('.num')).text()) - 500);

//                         }

//                         var newQty = parseInt($('#row_pre_' + productID).find('.num').text()); // Qty choosed 
//                         var oldPrice = Number($('#main_price_' + productID).text()); // main Price
//                         var newPrice = newQty * oldPrice; // New Price related to the Qty Choosed  
//                         var oldTotPrix = Number($('#totPrix_' + productID).text()); // Old Total Price for 1 Product 
//                         if (mixorNaugat) {
//                             var initweight = $('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0];
//                             newPrice = Number(Number((newQty * oldTotPrix) / oldQty).toFixed(2));
//                         }                                  
//                         $('#totPrix_' + productID).text(newPrice.toFixed(2)); // Set totPrix with the new Price for 1 Product   

//                         if (inc == "inc") {

//                             $('.totPrixB').text((Number($('.totPrixB').text()) + (newPrice - oldTotPrix)).toFixed(2));
//                             if ($('.nb_dollars').find('.nbdollars').length != 0)
//                                 $($('.nb_dollars').find('.nbdollars')).text((Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) + oldPrice).toFixed(2));

//                         }
//                         else if (inc == "dec") {
//                             $('.totPrixB').text((Number($('.totPrixB').text()) - (oldTotPrix - newPrice)).toFixed(2));
//                             if ($('.nb_dollars').find('.nbdollars').length != 0)
//                                 $($('.nb_dollars').find('.nbdollars')).text((Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) - oldPrice).toFixed(2));

//                         }
//                         $.ajax({
//                             url: routeURL + 'yourBasket/reviewTotal',
//                             type: 'POST',
//                             data: '',
//                             success: function (data) {
//                                 document.getElementById("promCode_id").innerHTML = ''
//                                 document.getElementById("promCode_id").innerHTML = data;
//                             }
//                         });
//                         working = false;
//                     }
//                     else {
//                         working = false;
//                     }

//                 }
//             });
//         }
//     }
// }
// function IncNbMix(elt) {
//     var parentElt = $(elt).parent().parent();
//     $($(parentElt).find('.num .w_mix')).text(parseInt($($(parentElt).find('.num .w_mix')).text()) + 500);
// }
// function DecNbMix(elt) {
//     var parentElt = $(elt).parent().parent();
//     if (parseInt($($(parentElt).find('.num .w_mix')).text())>200)
//     $($(parentElt).find('.num .w_mix')).text(parseInt($($(parentElt).find('.num .w_mix')).text()) - 500);
// }
 
// function UpdateProdBag(elt, productID, BagID, Qty, inc) {

//     var parentElt = $(elt).parent().parent();
//     if (!(inc == "dec" && parseInt($($(parentElt).find('.num .w_mix')).text()) <= 500)) {
//         if (!working) {
//             working = true;
//             if (inc == "inc")
//                 Qty = parseInt($($(parentElt).find('.num .w_mix')).text()) + 500;
//             else
//                 Qty = parseInt($($(parentElt).find('.num .w_mix')).text()) - 500;

//             $($(elt).parent().parent().parent().find('.speciaLoader')).show();
//             var routeURL = document.getElementById("routeURL").value;
//             var poststr = "ekomProductId=" + productID + "&EKomBagId=" + BagID + "&quantity=" + Qty;
//             $.ajax({
//                 url: routeURL + 'KMS/EKomBag/UpdateProductInBag',
//                 type: 'POST',
//                 data: '' + poststr,
//                 success: function (data) {

//                     if (data == "success") {
//                         //Hide Loader
//                         $($(elt).parent().parent().parent().find('.speciaLoader')).hide();
//                         //Modify Prices value
//                         if (inc == "inc")
//                             IncNbMix(elt);
//                         else
//                             DecNbMix(elt);

//                         var newQty = parseInt($($(parentElt).find('.num .w_mix')).text()); // Qty choosed    
//                         var hello = $('#row_pre_' + productID).attr('class');
//                         var hello1 = $('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0];
//                         var hello2 = Number($('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0]);
//                         var QteinKms = (Number($('#row_pre_' + productID).attr('class').split('initweight_')[1].split(' ')[0])); // GEt the initialweight/2 (prices showed for the mainPrice/2)
//                         var oldPrice = Number($('#main_price_' + productID).text()).toFixed(2); // main Price 
//                         var newPrice = Number((newQty * oldPrice) / 1000).toFixed(2); // New Price related to the Qty Choosed 
//                         var oldItemPrice = Number($('#totPrix_' + productID).text()).toFixed(2);
//                         $('#totPrix_' + productID).text(newPrice); // Set totPrix with the new Price for 1 Product                       
//                         if (inc == "inc") {
//                             $('.totPrixB').text(Number(Number(Number($('.totPrixB').text()).toFixed(2)) + Number(newPrice - oldItemPrice)).toFixed(2));
//                             //$('.promotional_code .total_shi_price .price .tPrice').text($('.totPrixB').text());
//                             if ($('.nb_dollars').find('.nbdollars').length != 0)
//                                 $($('.nb_dollars').find('.nbdollars')).text(Number(Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) + Number(Number(oldPrice).toFixed(2))).toFixed(2));


//                         }
//                         else if (inc == "dec") {
//                             $('.totPrixB').text(Number(Number(Number($('.totPrixB').text()).toFixed(2)) - Number(oldItemPrice - newPrice)).toFixed(2));
//                             // $('.promotional_code .total_shi_price .price .tPrice').text($('.totPrixB').text());
//                             if ($('.nb_dollars').find('.nbdollars').length != 0)
//                                 $($('.nb_dollars').find('.nbdollars')).text(Number(Number($($('.my_bas_m').find('.nb_dollars .nbdollars')).text()) - Number(Number(oldPrice).toFixed(2))).toFixed(2));

//                         }
//                         $.ajax({
//                             url: routeURL + 'yourBasket/reviewTotal',
//                             type: 'POST',
//                             data: '',
//                             success: function (data) {
//                                 document.getElementById("promCode_id").innerHTML = ''
//                                 document.getElementById("promCode_id").innerHTML = data;
//                             }
//                         });
//                         working = false;
//                     }
//                     else {
//                         working = false;
//                     }

//                 }
//             });
//         }
//     }
// }
    /////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////Backup//////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////
 function removeProductFromBasLeft(ID, parentCategoryName) {
     productToDeleteID = ID;
     parentCatName = parentCategoryName;
     removeProductFromBas();
 }

 function removeProductFromBas() {

        if (parentCatName != "mix your own")
            remProdFromB();       
        else 
            removeProductFromBag(productToDeleteID, BagID);
        
    }
    function remProdFromB() {
        var routeURL = document.getElementById("routeURL").value;
        var BasketID = $('#BasketID').val();
        var poststr = "ekomProductId=" + productToDeleteID + "&ekomBasketId=" + BasketID;
        $.ajax({
            url: routeURL + 'KMS/EKomBasket/RemoveFromBasket',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {

                if (data == "success") {
                    window.location.reload();
                }
                else {
                }

            }
        });
    }
    var toFirst = -1;
    function removeProductFromBagToFirst(ID, BasketID, BagID) {
        productToDeleteID = ID;
        toFirst = 1;
        AddToFirstBag(productToDeleteID, BasketID, BagID);
    }

    function removeProductFromBag(ID, BagID) {
        productToDeleteID = ID;
        removeProductFromB(BagID);
    }
    function removeProductFromB(BagID) {
        var x = true;
        if ($('#mproduct').length != 0)
         x = window.confirm("Are you sure you want to delete this product From Basket?");
        if (x) {
            var routeURL = document.getElementById("routeURL").value;
            var poststr = "ekomProductId=" + productToDeleteID + "&EKomBagId=" + BagID;
            $.ajax({
                url: routeURL + 'KMS/EKomBag/RemoveFromBag',
                type: 'POST',
                data: '' + poststr,
                success: function (data) {

                    if (data == "success") {

                        window.location.reload();
                    }
                    else {
                    }

                }
            });
        }

    }
    function AddToFirstBag(productsID, BasketID, BagID) {
        var x = true;
        if ($('#mproduct').length != 0)
         x = window.confirm("Are you sure you want to remove product From this Bag?");
        if (x) {
            var routeURL = document.getElementById("routeURL").value;
            var poststr = "myBasketId=" + BasketID + "&ProductsId=" + productsID + "&bagId=" + BagID;
            $.ajax({
                url: routeURL + 'yourBasket/MoveProdTofirstBag',
                type: 'POST',
                data: '' + poststr,
                success: function (data) {
                    var newDiv = document.createElement("div");
                    newDiv.innerHTML = data;
                    newDiv.style.display = "none";
                    document.getElementById("rows_pre_pro2").appendChild(newDiv);
                    $(newDiv).fadeIn();
                    window.location.reload();
                }
            });
        }
    }
    function addToBasket(BasketID, ProductID) {
        var routeURL = document.getElementById("routeURL").value;
       
        var Qte = $('.nb_add_basket .num').text(); 
        var initialWeight = $('#initialWeight').val(); // From KMS (placed in hidden input)
        if (Qte != 500 && $('#dl_grame').length != 0)
            Qte =Qte*1000;
        var poststr = "myBasketId=" + BasketID + "&myProductId=" + ProductID + "&quantity=" + Qte;
        $('#addB_loading').show();
        var Items = $('#bas_it .your_item');
        var Exists = false;
        var i = 0;
        for (i = 0; i < Items.length; i++) {
            if ((Items[i].id.split('_'))[1] == ProductID) {
                Exists = true;
                break;
            }
        }

        $.ajax({
            url: routeURL + 'yourBasket/AddProductsToBasket',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                var nbItems = 0;
                var OldQte = 0;
                var Qte = 0;
                var QteChoosed = 0;
                if (Exists == false) {
                    var newDiv = document.createElement("div");
                    newDiv.innerHTML = data;
                    newDiv.style.display = "none";
                    document.getElementById("bas_it").appendChild(newDiv);
                    $(newDiv).fadeIn();
                    nbItems = parseInt($('.items_price .nbi').text()) + 1;
                    Qte = parseFloat($('.nb_add_basket .num').text());
                    var oldQteNmChoosed = Qte;
                    if ($('#dl_grame').length != 0)// Naugat and Malban
                    {
                        Qte = 1;
                        var QteItem = parseFloat($('.nb_add_basket .num').text());
                        if (QteItem != 500)
                            QteItem = QteItem * 1000;
                        oldQteNmChoosed = QteItem;
                        if (QteItem > 500) {
                            $($('#itbas_' + ProductID).find('.qte .nmab')).text(QteItem / 1000);
                            $($('#itbas_' + ProductID).find('#ununit')).text("kg");
                        }
                        else {
                            $($('#itbas_' + ProductID).find('.qte .nmab')).text(QteItem);
                        }
                    }
                }
                else {
                    OldQte = parseInt($($('#itbas_' + ProductID).find('.qte_i')).text());
                    QteChoosed = parseFloat($('.nb_add_basket .num').text());
                    Qte = parseFloat(OldQte) + parseFloat(QteChoosed);
                    if ($('#dl_grame').length != 0)// Naugat and Malban                    
                    {
                        Qte = parseInt(OldQte) + 1;
                        if (QteChoosed != 500)
                            QteChoosed = QteChoosed * 1000;
                        oldQteNmChoosed = parseFloat(($('#itbas_' + ProductID).find('.qte .nmab')).text());
                        if (oldQteNmChoosed < 500) {
                            oldQteNmChoosed = oldQteNmChoosed * 1000;
                        }
                        var QteItem = QteChoosed + oldQteNmChoosed;

                        if (QteItem > 500) {
                            $($('#itbas_' + ProductID).find('.qte .nmab')).text(QteItem / 1000);
                            $($('#itbas_' + ProductID).find('#ununit')).text("kg");
                        }
                        else {
                            $($('#itbas_' + ProductID).find('.qte .nmab')).text(QteItem);
                        }
                    }
                    if ($('#dl_grame').length != 0) {
                        nbItems = $('.items_price .nbi').text();
                    }
                    else {
                        nbItems = parseInt($('.items_price .nbi').text()) + 1;
                    }
                }
                // Change Price

                if (Exists) {
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);

                    if ($('#dl_grame').length != 0)// Naugat and Malban
                    {
                        // Change Price
                        var newW = Number(($('#itbas_' + ProductID).find('.nmab')).text());
                        if (newW < 500) {
                            newW = newW * 1000;
                        }
                        var oldW = oldQteNmChoosed;
                        var oldP = Number(($('#itbas_' + ProductID).find('.price_' + ProductID)).text());
                        var newP = Number((newW * oldP) / oldW).toFixed(2);
                        $('#itbas_' + ProductID).find('.price_' + ProductID).text(newP);
                    }
                    else {
                        // Change Price
                        var newW = Qte;
                        var oldW = OldQte;
                        var oldP = Number(($('#itbas_' + ProductID).find('.price_' + ProductID)).text());
                        var newP = Number((newW * oldP) / oldW).toFixed(2);
                        $('#itbas_' + ProductID).find('.price_' + ProductID).text(newP);
                    }

                }
                else {
                    //   $('#itbas_' + ProductID).find('.price_' + ProductID).text(Number($('.price .det_price').text()).toFixed(2));
                    if ($('#dl_grame').length != 0)// Naugat and Malban
                    {
                        // $('#itbas_' + ProductID).find('.price_' + ProductID).text(Number($('.price .det_price').text()).toFixed(2));
                        var newW = parseFloat($('.nb_add_basket .num').text()); //QteCHoosed;

                        if (newW != 500)
                            newW = newW * 1000;
                        var unitPrice = $('.ingredients').find('.det_price').text(); // for 1000

                        var newP = Number(parseFloat(newW) * Number(unitPrice) * 0.001).toFixed(2);

                        $('#itbas_' + ProductID).find('.price_' + ProductID).text(newP);
                    }
                    else {
                        var unitPrix = $('.ingredients').find('.det_price').text(); // Price for the Qty in kms
                        var qteChsd = parseFloat($('.nb_add_basket .num').text()); //QteCHoosed;
                        var newPrix = Number(parseFloat(qteChsd) * Number(unitPrix)).toFixed(2);
                        $('#itbas_' + ProductID).find('.price_' + ProductID).text(newPrix);
                    }


                }

                // End Changing Price


                if ($('#dl_grame').length == 0)// Not Naugat and Malban
                    $($('#itbas_' + ProductID).find('.qte_i')).text(Qte);


                var OldPrice = Number($('.items_price .nb_p').text()).toFixed(2);
                var NewPrice = (Number($('.price .det_price').text()) * parseInt($('.nb_add_basket .num').text())).toFixed(2); // Price * Qte



                if ($('#dl_grame').length != 0) {// Naugat and Malban               
                    var newWeight = parseFloat($('.nb_add_basket .num').text());
                    if (newWeight != 500) {
                        newWeight = newWeight * 1000;
                    }

                    NewPrice = Number($('.price .det_price').text()).toFixed(2) * newWeight / 1000;
                }

                var Price = (Number(OldPrice) + Number(NewPrice)).toFixed(2);

                $('.items_price .nb_p').text(Price);
                if ($('.nb_dollars').find('.nbdollars').length != 0)
                    $($('.nb_dollars').find('.nbdollars')).text(Price);
                $('.items_price .nbi').text(nbItems);
                if ($('.my_bas_m').find('.nbitems').length != 0)
                    $($('.my_bas_m').find('.nbitems')).text(nbItems);

                hideLoader();
            }
        });
    }
    function addToBag(BasketID, ProductID) {
        var routeURL = document.getElementById("routeURL").value;
        var Qte = $('.nb_add_basket .num').text();
        var initialWeight = $('#initialWeight').val(); // From KMS (placed in hidden input)
        if (Qte != 500)
            Qte = Qte*1000;
        var poststr = "myBasketId=" + BasketID + "&myProductId=" + ProductID + "&quantity=" + Qte;
        $('#addB_loading').show();
        var Items = "";
        if($('#bag_items').length!=0)
         Items = $('#bag_items .your_item');
        var Exists = false;
        var i = 0;
        for (i = 0; i < Items.length; i++) {
            if ((Items[i].id.split('_'))[1] == ProductID) {
                Exists = true;
                break;
            }
        }
        $.ajax({
            url: routeURL + 'yourBasket/AddProductsToBag',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                var nbItems = 0;
                var OldQte = 0;
                var Qte = 0;
                var QteChoosed = 0;
                var QteInKg = 0;
                if (Exists == false) {
                    var newDiv = document.createElement("div");
                    if ($('#t_bag').length == 0) {
                        $('#bag_cont').prepend('<div class=your_bas_pre_nuts id=t_bag>Mix Your Own</div>');
                    }
                    newDiv.innerHTML = data;
                    newDiv.style.display = "none";
                    document.getElementById("bag_items").appendChild(newDiv);
                    $(newDiv).fadeIn();
                    nbItems = parseInt($('.items_price .nbi').text()) + 1;
                    Qte = parseFloat($('.nb_add_basket .num').text());
                    if (Qte != 500)
                        Qte = Qte * 1000;
                }
                else {
                    OldQte = Number($($('#itbas_' + ProductID).find('.qte_i')).text());
                    if (OldQte < 500)
                        OldQte = OldQte * 1000;
                    QteChoosed = parseFloat($('.nb_add_basket .num').text());
                    if (QteChoosed != 500)
                        QteChoosed = QteChoosed * 1000;
                    Qte = Number(OldQte) + Number(QteChoosed);

                    nbItems = $('.items_price .nbi').text();
                }
                if (Qte >= 1000) {
                    QteInKg = Qte / 1000;
                    $($('#itbas_' + ProductID).find('.qte_i')).text(QteInKg);
                    $($('#itbas_' + ProductID).find('#mixunit')).text("kg");
                } else {
                    $($('#itbas_' + ProductID).find('.qte_i')).text(Qte);
                }

                if (Exists) {
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    $('#itbas_' + ProductID).fadeOut(90);
                    $('#itbas_' + ProductID).fadeIn(90);
                    // Change Price
                    var newW = Number(($('#itbas_' + ProductID).find('.qte_i')).text());
                    if (newW < 500) {
                        newW = newW * 1000;
                    }
                    var oldW = OldQte;
                    var oldP = Number(($('#itbas_' + ProductID).find('.price_' + ProductID)).text());
                    var newP = Number((newW * oldP) / oldW).toFixed(2);
                    $('#itbas_' + ProductID).find('.price_' + ProductID).text(newP);
                }
                else {
                    // $('#itbas_' + ProductID).find('.price_' + ProductID).text(Number($('.price .det_price').text()).toFixed(2));
                    var newWm = parseFloat($('.nb_add_basket .num').text()); //QteCHoosed;

                    if (newWm != 500)
                        newWm = newWm * 1000;

                    var unitPricem = $('.ingredients').find('.det_price').text(); // for 1000

                    var newPm = Number(parseFloat(newWm) * Number(unitPricem) * 0.001).toFixed(2);

                    $('#itbas_' + ProductID).find('.price_' + ProductID).text(newPm);


                    //$('#itbas_' + ProductID).find('.price_' + ProductID).text(Number($('.price .det_price').text()).toFixed(2));
                }
                var OldPrice = Number($('.items_price .nb_p').text()).toFixed(2);
                var NewW = parseFloat($('.nb_add_basket .num').text());
                if (NewW != 500) {
                    NewW = NewW * 1000;
                }
                var NewPrice = Number($('.price .det_price').text()).toFixed(2) * NewW / 1000; ;
                var Price = (Number(OldPrice) + Number(NewPrice)).toFixed(2);
                $('.items_price .nb_p').text(Price);
                if ($('.nb_dollars').find('.nbdollars').length != 0)
                    $($('.nb_dollars').find('.nbdollars')).text(Price);
                $('.items_price .nbi').text(nbItems);
                if ($('.my_bas_m').find('.nbitems').length != 0)
                    $($('.my_bas_m').find('.nbitems')).text(nbItems);
                hideLoader();
            }
        });
    }
    var destBagID = -1;
    function collectProducts(productsID, BasketID, BagID) {
        var routeURL = document.getElementById("routeURL").value;
        var finalProducts = "";
        var Exists = false; // No Elements selected
        var EltsparentTodelete = "";
        var nbProdTodelete = 0;
        if ($('#rows_pre_pro2 .row_pre_pro').length != 0) {
            $(".row_pre_pro").find("input").each(function () {
                if ($(this).is(':checked')) {
                    Exists = true;
                    nbProdTodelete++;
                    var ID = (($(this).attr("id")).split("_"))[1];
                    if (finalProducts == "")
                        finalProducts = ID;
                    else
                        finalProducts = ID + "," + finalProducts;

                    if (EltsparentTodelete == "")
                        EltsparentTodelete = ($(this).parent().attr("id"));
                    else
                        EltsparentTodelete = ($(this).parent().attr("id")) + "," + EltsparentTodelete;
                }

            });
            if (Exists) {
                CheckBags();
                var poststr = "myBasketId=" + BasketID + "&ProductsId=" + finalProducts + "&bagId=" + BagID + "&destbagId=" + destBagID;
                $('#mixprodloading').show();
                var eltsToDelete = EltsparentTodelete.split(",");
                $.ajax({
                    url: routeURL + 'yourBasket/MoveProductsToBag',
                    type: 'POST',
                    data: '' + poststr,
                    success: function (data) {
                        if (destBagID == -1) {
                            var newDiv = document.createElement("div");
                            newDiv.innerHTML = data;
                            newDiv.style.display = "none";
                            document.getElementById("bags_products").appendChild(newDiv);
                            $(newDiv).fadeIn();
                            newDiv.style.display = "inline-block";
                        }
                        $('#mixprodloading').hide();
                        var i = 0;
                        var priceToMini = 0;
                        var priceid = -1;
                        for (i = 0; i < eltsToDelete.length; i++) {
                            priceid = $('#' + eltsToDelete[i]).attr("id").split("row_pre_")[1];
                            priceToMini = Number(Number(Number(Number(priceToMini).toFixed(2)) + Number(Number($($('#' + eltsToDelete[i]).find('#totPrix_' + priceid)).text()).toFixed(2))).toFixed(2));
                            $('#' + eltsToDelete[i]).fadeOut();
                        }
                        $('.nbitems_v').text(parseInt($('.nbitems_v').text()) - nbProdTodelete);
                        var newPriceBag = Number(Number(Number(Number(Number($('.totPrixBMix').text()).toFixed(2)) - Number(Number(priceToMini).toFixed(2))).toFixed(2))).toFixed(2);
                        if (newPriceBag < 0)
                            newPriceBag = 0;
                        $('.totPrixBMix').text(newPriceBag);
                        var nbBagsD = $('#bags_products .bag_2').length;
                        $('.nbitems .nbBags').text(nbBagsD);
                        var newpricemixedProd = Number(Number(Number(Number($('.totBagPrices').text()).toFixed(2)) + Number(Number(priceToMini).toFixed(2))).toFixed(2)).toFixed(2);
                        $('.totBagPrices').text(newpricemixedProd);
                        uncheckAll();
                        if (destBagID != -1)
                            window.location.reload();

                    }
                });
            }
            else
                alert("You must select products to mix");
        }

    }
    function EnableElt(elt) {
        if ($(elt).is(':checked')) {
            $("#bags_products").find("input").each(function () {
                $(this).attr('disabled', true);
                $(elt).attr('disabled', false);
            });
        }
        else {
            $("#bags_products").find("input").each(function () {
                $(this).attr('disabled', false);               
            });
        }
    }
    function uncheckAll() {
        $("#bags_products").find("input").each(function () {
            $(this).attr('disabled', false);
            $(this).attr('checked', false);
        });
        $("#rows_pre_pro2").find("input").each(function () {           
            $(this).attr('checked', false);
        });
    }
    function CheckBags() {
        $("#bags_products").find("input").each(function () {
            if ($(this).is(':checked')) {
                var parentBag = $(this).parent().parent();               
                var idBag = $(parentBag).attr('id');               
                destBagID = idBag.split("bag_")[1];
                             
            }
        });
    }
    function MoveProductsBag(productsID, BasketID, BagID) {
        var routeURL = document.getElementById("routeURL").value;
        var poststr = "myBasketId=" + BasketID + "&ProductsId=" + productsID + "&bagId=" + BagID;       
       
        $.ajax({
            url: routeURL + 'yourBasket/MoveToBag',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                var newDiv = document.createElement("div");
                newDiv.innerHTML = data;
                newDiv.style.display = "none";
                document.getElementById("rows_pre_pro2").appendChild(newDiv);
                $(newDiv).fadeIn();               
                var i = 0;
                for (i = 0; i < eltsToDelete.length; i++) {
                    $('#' + eltsToDelete[i]).fadeOut();
                }
            }
        });

    }

    function sendGift(frmId, UserID) {
        var routeURL = document.getElementById("routeURL").value;
        hideMessages();
        test = false;
       
            $('#gift_voucher').find('input,textarea,select').each(function () {
                var isError = false;
                var elem;
                if (($(this).attr('required') == '1' && $(this).attr('value').length == 0) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value'))) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value')))) {
                    $(this).addClass('missed');
                    isError = true;
                    test = true;
                    if (!elem) elem = $(this);
                } else {
                    $(this).removeClass('missed');
                }
            });
            if ($($('#gift_voucher').find('textarea')).val() == "Write your message" || $($('#gift_voucher').find('textarea')).val() == "") {
                $($('#gift_voucher').find('textarea')).addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $($('#gift_voucher').find('textarea')).removeClass('missed');
            }
            var voucherID = $('select#voucherddl option:selected').val();
            if (voucherID == -1) {
                $('#voucherddl').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#voucherddl').removeClass('missed');
            }
            if (!test) {
                var poststr = "userId=" + UserID + "&voucherId=" + voucherID + "&email=" + $('#email').val() + "&fullNameVoucher=" + $('#fullNameVoucher').val() + "&telephone=" + $('#telephone').val() + "&message=" + $('#message').val();
                $('#voucher_loader').show();
                var URL = $('#' + frmId).attr('action');
                $.ajax({
                    url: URL,
                    type: 'POST',
                    data: '' + poststr,
                    success: function (data) {
                        $.ajax({
                            url: routeURL + 'giftVoucher/getFormPayment',
                            type: 'POST',
                            data: "voucherid=" + data,
                            success: function (data) {
                                document.getElementById("payment_voucher").innerHTML = '';
                                document.getElementById("payment_voucher").innerHTML = data;
                                document.submitOrderForm.submit();
                            }
                        });
                    }
                });
            }
            else {
                $('.fill_req').show();
                $('.member').hide();
            }
        }

    function LogOut() {
        var routeURL = document.getElementById("routeURL").value;
        $.ajax({
            url: routeURL + 'myAccount/LogOff',
            type: 'POST',
            data: '',
            success: function (data) {

                if (data == "success") {                    
                    window.location = routeURL;
                }

            }
        });
    }

    function sendPassword() {
        $('#notHere').hide();        
        var routeURL = document.getElementById("routeURL").value;
        var userName = $('#forg_pass').val();
        if ($('#forg_pass').val() == '') {
            return;

        }
        else {
            if ($('#forg_pass').val() != 0 && !(($('#forg_pass').val().indexOf(".") > 0) && ($('#forg_pass').val().indexOf("@") > 0))) {

                return;
            }
            else {
               
            }
        }
        var poststr = "userName=" + userName;
        $('#forgot_password').fadeOut();
        $('#loading_srch').fadeIn();
        $.ajax({
            url: routeURL + 'KMS/Account/ForgetPassword',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                $('#loading_srch').fadeOut();                
                if (data) {
                    showThankYou();
                    setTimeout("reLogin()", 5000);
                }
                else {
                    $('#forgot_password').fadeIn();
                    $('#notHere').show();
                }
            }
        });
    }
    function sendPassword1() {
        $('#notHere1').hide();
        $('#fq1').hide();
        $('#inputs_Sign').find('input').each(function () {    
                $(this).removeClass('missed');
                $(this).val("");
        });
        var routeURL = document.getElementById("routeURL").value;
        var userName = $('#forg_pass1').val();
        var poststr = "userName=" + userName;               
        $.ajax({
            url: routeURL + 'KMS/Account/ForgetPassword',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                if (data == "True") {
                    $('#forgot_password1').fadeIn();
                    $('#thank_you1').fadeIn();
                    setTimeout("reLogin1()", 5000);
                }
                else {
                    $('#forgot_password1').fadeIn();
                    $('#notHere1').show();
                }
            }
        });
    }
    function deleteCookie(CookieName) {

        var d = $('#dateExpire').val();
        alert(d)
         document.cookie = CookieName + '=; expires=' + d + ";";
         alert(document.cookie);
    }

    function addToFav(ProductId, UserID, flag) {
        var routeURL = document.getElementById("routeURL").value;
        var currentUrl = document.getElementById("currentUrl").value;
        var poststr = "ekomProductId=" + ProductId + "&userId=" + UserID;
        $('#fav_load').show();
        $.ajax({
            url: routeURL + 'KMS/EKomProduct/AddToFavorite',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {

                if (data == "success") {
                    $($('.ingredients').find('.favorites')).addClass('selected');
                    //window.location = currentUrl;  
                    reloadProd(ProductId, flag); // ajaxCall
                   
                }
                else {
                    $($('.ingredients').find('.favorites')).removeClass('selected');
                }

                $('#fav_load').hide();

            }
        });
    }
    function remFromFav(ProductId, UserID, flag) {
        var routeURL = document.getElementById("routeURL").value;
        var currentUrl = document.getElementById("currentUrl").value;
        var poststr = "ekomProductId=" + ProductId + "&userId=" + UserID;
        $('#fav_load').show();
        $.ajax({
            url: routeURL + 'KMS/EKomProduct/DeleteFromFavorite',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {

                if (data == "Success") {
                    //window.location = currentUrl;  
                    reloadProd(ProductId, flag); // ajaxCall
                    if ($("#favhere").val() == "true") {
                        window.location.reload();
                    }
                }
                else {

                }
                $('#fav_load').hide();
            }
        });
    }

    function reloadProd(ProductId, flag) {
        var routeURL = document.getElementById("routeURL").value;
        var poststr = "ekomProductId=" + ProductId + "&flag=" + flag;
        $.ajax({
            url: routeURL + 'Home/reloadFavProd',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                if (flag == "list") {                   
                    $("#it_" + ProductId).replaceWith(data);
                }
                if (flag == "gift") {
                    $("#gf_" + ProductId).replaceWith(data);
                }
                else if (flag == "details")
                    $(".fav_like").replaceWith(data);
            }
        });
    }

    function DeleteShipInfo(id) {
        var answer = confirm("Are you sure you want to delete this shipping address?");
        if (answer) {
            var routeURL = document.getElementById("routeURL").value;
            $.ajax({
                url: routeURL + 'myAccount/DeleteShippingInfo/' + id,
                type: 'POST',
                data: '',
                success: function (data) {

                    if (data == "success") {
                        window.location.reload();
                    }
                    else {

                    }

                }
            });
        }
        else{}
    }
    var canLike = true;
    function LikeProd(ProductId, UserID) {
        if (canLike == true) {
            canLike = false;
            var routeURL = document.getElementById("routeURL").value;
            var poststr = "ekomProductId=" + ProductId + "&userId=" + UserID;
            $.ajax({
                url: routeURL + 'KMS/EKomProduct/LikeProduct',
                type: 'POST',
                data: '' + poststr,
                success: function (data) {

                    if (data == "success") {
                        $('.likeCount' + ProductId).text(parseInt($('.likeCount' + ProductId).text()) + 1);
                        $('#like_' + ProductId).removeAttr("onclick");
                        $('#like_' + ProductId).css("cursor", "default");
                        setTimeout(function () {

                            canLike = true;
                        }, 3000)
                    }
                    else {

                    }

                }
            });
        } 
    }
    
    function addCommentToProduct(isLogin) {
        isLogin = isLoginG;        
        var routeURL = document.getElementById("routeURL").value;
        var ProductId = document.getElementById("ProductId_details").value;
        userComm = $('#user_comment').val();
        if (isLogin == "True") {
            if (userComm != "type your comment")
          {
            var poststr = "ekomProductId=" + ProductId + "&userComment=" + $('#user_comment').val();
            $('.commenting_part .loading').show();
            $.ajax({
                url: routeURL + 'nutsDetails/CommentOnProduct',
                type: 'POST',
                data: '' + poststr,
                success: function (data) {

                    if (data == "success" || data == "Success") {
                        $('.commenting_part .loading').hide();
                        GetCommentUserInfo(ProductId);
                    }
                    else {

                    }

                }
            });
          }
        }
        else {
            LogginDet = true;  
            showLogin();
            window.scrollTo(0, 0);
        }
    }    
    function GetCommentUserInfo(ekomProductId) {
        var routeURL = document.getElementById("routeURL").value;
        var poststr = "&ekomProductId=" + ekomProductId ;
        $.ajax({
            url: routeURL + 'nutsDetails/GetCommentUserInfo',
            type: 'POST',
            data: '' + poststr,
            success: function (data) {
                var fName = (data.split('_'))[0];
                var lName = (data.split('_'))[1];
                var cdate = (data.split('_'))[2];
                addComment(fName, lName, cdate);
            }
        });
    }
    function addComment(fName, lName, cdate) {
        var routeURL = document.getElementById("routeURL").value;
        var newDiv = document.createElement("div");
        var comment = $('textarea#user_comment').val();
        var data = "<div class='com_div'><div class='top_com_div'></div><div class='content_com_div'><div class='desc_user'><div class='user'>" + fName + ' ' + lName + "</div><div class='date'>" + cdate + "</div></div><div class='com_txt'>" + comment + "</div></div><div class='bottom_com_div'></div></div>"
        newDiv.innerHTML = data;
        newDiv.style.display = "none";      
        document.getElementById("product_comments").appendChild(newDiv);
        $(newDiv).fadeIn();
        $('#user_comment').val("type your comment");
        $.ajax({
            url: routeURL + 'nutsDetails/ReloadHead',
            type: 'POST',
            data: '',
            success: function (data) {
                document.getElementById("cont_head_ajax").innerHTML = '';
                document.getElementById("cont_head_ajax").innerHTML = data;
            }
        });
    }

    function updateProfile(id) {        
        hideMessages();
        test = false;

        $('#frmRegister').find('input,textarea,select').each(function () {
            var isError = false;
            //var test = false;

            var elem;
            if (($(this).attr('required') == '1' && $(this).attr('value').length == 0) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value'))) || ($(this).attr('email') == '1' && !IsValidEmail($(this).attr('value')))) {
                $(this).addClass('missed');
                isError = true;
                test = true;
                if (!elem) elem = $(this);
            } else {
                $(this).removeClass('missed');

            }
        });
        if ($('#calendargoeshere').length != 0) {
            var Dob_val = $('#dob').val();
            var newDob_val = Dob_val.replace(" ", "");
            if (newDob_val == "") {
                $('#dob').addClass('missed');
                isError = true;
                test = true;
            }
            else {
                $('#dob').removeClass('missed');
            }
        }
        var routeURL = document.getElementById("routeURL").value;
        var poststr = "id=" + id;
        if (test == false) {
            $('.loading').show();
            $.post($('#frmRegister').attr('action'),
             $('#frmRegister').serialize() /*  { firstName: $('#firstName').val(), lastName: $('#lastName').val(), telephone: $('#telephone').val(), mobile: $('#mobile').val(), email: $('#email').val(), countryId: $('#countryId').val(), comment: $('#comment').val() }*/,
                function (data) {               
                    if (data == "success") {                        
                        $('.fill_req').hide();
                        $('.loading').hide();
                        $('.member').show();
                        setTimeout("hideSuccess()", 5000);                       
                    }
                    else {
                        $('.loading').hide();
                    }
            });
        }
        else {
            $('.fill_req').show();
            $('.member').hide();
        
        }
     }   

    function reLogin() {
        $('#thank_you').fadeOut();
        $('#fill_form').fadeIn();
    }
    function reLogin1() {        
    $('#forgot_password1').fadeOut();
    $('#thank_you1').fadeOut();
    $('#inputs_Sign').fadeIn();
    } 
    function hideLoader() {
        $('.loading').hide();
    }

    function setDate(datethis) {
        if ($('#frmDeliveryDetails #deliveryDate').length != 0)
         $('#frmDeliveryDetails #deliveryDate').val(datethis);
    }
    function setBirthDate(dateB) {
        $('#frmRegister #dob').val(dateB);
    }
    function setValueVoucher(elt) {
        var currentVal = $(elt).val();       
        if (currentVal != -1)
            $('.voucher_value').text(currentVal + " $");
        else
            $('.voucher_value').text("");
    }
    function GoToSendGift() {
        if ($('#isLogin').val() == "True")
            window.location = $('#lnkGiftVoucher').val();
        else {
            showRegLogPop();
            window.scrollTo(0,0);
        }
    }
    function goToSearch() {       
        window.location = $('#lnksearch').val() + "?criteria=" + $('#searchText').val();
    }
    function printDiv() {
        var divToPrint = document.getElementById('div_to_print');
        var routeURL = document.getElementById("routeURL").value;
        var newWin = window.open('', '', 'width=735,height=788');
        newWin.document.open();
        newWin.document.write('<html><head><link href=' + routeURL + 'Content/css/styles.css rel=stylesheet type=text/css /></head><body><div id=invoice><div id=div_to_print class=invoice_form>' + divToPrint.innerHTML + '</div></div></body></html>');
        newWin.print();
      //  newWin.document.close();
     //   setTimeout(function () { newWin.close(); }, 10);
    }
    function printDivBack(id) {
        var divToPrint = document.getElementById('div_to_print');
        var routeURL = document.getElementById("routeURL").value;
        var newWin = window.open('', 'Print-Window', 'width=735,height=788');
        newWin.location = routeURL + "printinvoice?orderid="+id;
        newWin.document.open();
        newWin.document.write('<html><head><link href=' + routeURL + 'Content/css/styles.css rel=stylesheet type=text/css /></head><body><div id=invoice><div id=div_to_print class=invoice_form>' + divToPrint.innerHTML + '</div></div></body></html>');
        newWin.print();
        //  newWin.document.close();
        //   setTimeout(function () { newWin.close(); }, 10);
    }
    function GoToNewsLetter() {
        var email = $('.join_e_news input').val();
        if (email == "join our e-news")
            window.location = $('#newsletterUrl').val();
        else
            window.location = $('#newsletterUrl').val()+"?username="+email;
    }
    /* -------------------------------------Slide show animation :-------------------------------------------*/
    var index = 0;
    var disable = 0;
    var padding = 0;
    function showPreviousSlide() {
        x = $('.slides_c > .slide_c');
        width = x.width();
        if (disable == 0) {
            disable = 1;
            //left = $('.slideshow').position().left;
            left = $('.slide_certs > .slides_c').position().left;
            if (index == 0) {
                disable = 0;

            }
            else {
                $('.slide_certs > .slides_c').animate({
                    left: left + (width + padding) + "px"
                }, 1000, 'easeInOutCubic', sub_index);
            }
        }
    }

    function add() {
        index = index + 1;
        disable = 0;
        end_next();
        reset_previous();
    }

    function sub_index() {
        index = index - 1;
        disable = 0;
        reset_next();
        end_previous();
    }
    function end_next() {
        if (index == x.length - 1) {
            $('.next_btn').hide();
        }
    }
    function reset_next() {
        if (index != x.length - 1)
            $('.next_btn').show();
    }
    function end_previous() {
        if (index == 0)
            $('.prev_btn').hide()
    }
    function reset_previous() {
        if (index != 0)
            $('.prev_btn').show();
    }


    function updateButtons() {
        if (index == 0)
            $('.prev_btn').hide();        
    }

    function showNextSlide() {
        $('.slide_certs .prev_btn').show()
        x = $('.slides_c > .slide_c');
        width = x.width();
        if (disable == 0) {
            disable = 1;
            //left = $('.slideshow').position().left;
            left = $('.slide_certs > .slides_c').position().left;
            if (index == 0) {
                $('.slide_certs > .slides_c').animate({
                    left: left - (width + padding) + "px"
                }, 1000, 'easeInOutCubic', add);
            }
            else {

                if (index == x.length - 1) {
                    disable = 0;
                }

                else {
                    $('.slide_certs > .slides_c').animate({
                        left: left - (width + padding) + "px"
                    }, 1000, 'easeInOutCubic', add);
                }
            }
        }
    }
    /* -------------------------------------End Slide show animation -------------------------------------------*/

    function GWT_entryPoint() {
        if (document.getElementById("calendargoeshere") != null) {
            var Editndate = "";

//            if (document.getElementById("frmDeliveryDetails") != null)
//            {
//              $('#deliveryDate').val($('#dob').val());
//              $('#dob').val("");
//            }
            if (document.getElementById("Editndate") != null) {
                Editndate = document.getElementById("Editndate").value;               
            }
            else {
                Editndate = "";                
            }
            calendarPath = document.getElementById('CalendarPath').value;
            if (document.getElementById("frmDeliveryDetails") == null)
                showAge('calendargoeshere', 'dob', true, '', Editndate, 'MM/dd/yyyy');
                //showCalendar('' + calendarPath + '', 'calendargoeshere', 'deliveryDate', true, false, '', 'MM/dd/yyyy', Editndate);
            else {
                showCalendar('' + calendarPath + '', 'calendargoeshere', 'deliveryDate', true, false, '', 'MM/dd/yyyy', Editndate);
               // showAge('calendargoeshere', 'dob', true, '', Editndate, 'MM/dd/yyyy');
               }
        }

    }


    function showcalc() {
        $("#calculator").show(200);
        $(document).scrollTop(0);
    }
    function IsNumeric(val) {

    if (isNaN(parseFloat(val))) {

          return false;

     }

     return true

}
function calculate() {
        var routeURL = document.getElementById("routeURL").value;
        var gram = $("#qty").val();
        var country = $("#country").val();
        if (isNaN(gram)) {
            alert("please enter numbers only.");
            return;
        }
        $.ajax({
            url: routeURL + 'home/shipping?country_id=' + country + "&weight=" + gram,
            type: 'POST',
            data: '',
            success: function (data) {
                if (data != null) {
                    $("#results").val(data+"$");
                }
                else {
                    alert("Something went wrong please try again later.");
                }
            }
        });
    }

    $(document).ready(function () {
        $(".headercontentHeader").find("div").click(function () {
            $(".allcontainers").slideUp(800);
            $("#" + $(this).attr("class")).slideDown(800);
            $(".content").attr("id", $(this).attr("class"));
        });




    });
    function goUp(id) {
        if (id == "1") {
            $(window).scrollTop(392);
        }
        else {
            $(window).scrollTop(663);
        
        }

    }
    function autofill(id) {
        if (id != null) {
        var routeURL = document.getElementById("routeURL").value;
        $.ajax({
            url: routeURL + 'home/getshipping?id=' + id,
            type: 'GET',
            data: '',
            success: function (data) {
                if (data != null) {
                    var x = data.split("*/*");
                    $("#firstName").val(x[0]);
                    $("#lastName").val(x[1]);
                    $("#telephone").val(x[2]);
                    $("#email").val(x[3]);
                    $("#address").val(x[4]);
                    var countryId = x[5];
                    var country = x[6];
                    $("#cityState").val(x[7]);
                    $("#zipCode").val(x[8]);

                    //$("#countryId").prepend("<option selected class='option' value='" + countryId + "'>" + country + "</option>");
                    var countryNb = $("#countryId").find("option").length;
                    for (i = 0; i < countryNb - 2; i++) {
                        if (($($("#countryId").find("option")[i])).html().toString().toLowerCase() == country.toLowerCase()) {
                            ($($("#countryId").find("option")[i])).attr("selected", "selected");
                            break;
                        }
                    }
                }
                else {
                    alert("Something went wrong please try again later.");
                }
            }
        });
        }

}
function closeit() {
    $(".packed").hide(200);
}
function askif(url) {
    var yes = confirm("To ship for free to Lebanon your minimum order value should be 35$.add more products?");
    if (yes) {
        var routeURL = document.getElementById("routeURL").value;
        window.location = routeURL;
    }
    else {
        //window.location = url;
    }
}
function wofting(elem) {
    $(elem).parent().find('.Package').hide();
    var class1 = $(elem).attr("class");
    class1 = class1.split(" ");

    $(elem).parent().find("."+class1[1]).show(200);
}
