﻿var activeMenu = -1;
var activeMenuClass = '';
$(document).ready(function (n) {

});
function validateEmail(email) {
    var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return emailReg.test(email);
}


function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function ShoppingCartDeliveryDate()
{

    $(".jqDatePickerDeliveryDate").val("");
    var dateToday = new Date();
    $(".jqDatePickerDeliveryDate").datepicker({
        dateFormat: "dd/mm/yy",
        changeMonth: true,
        changeYear: true,
        minDate: dateToday,
        beforeShowDay: function (date) {
            var day = date.getDay();

            //check if today should be disabled
            var dt = new Date();
            if (dt.getDate() == date.getDate() && dt.getMonth() == date.getMonth() && dt.getFullYear() == date.getFullYear()) {
                //  var currentHour = dt.getHours();
                //if (currentHour >= 17) day = 0;
                day = 0;
            }

           //if area outsidwe beirut then disable next two days
                var str = "";
                $("#ddlArea option:selected").each(function () {
                    str = $(this).text();
                });
                if (str == 'Outside Beirut') {
                    if ((dt.getDate()+1 == date.getDate()  || dt.getDate()+2 == date.getDate()  ) && dt.getMonth() == date.getMonth() && dt.getFullYear() == date.getFullYear()) {
                        day = 0;
                    }

                }
                
           




            return [(day != 0), ''];

        },
        onSelect: function (dateText, inst) {
            var time = $('#ddlDeliveryTime').val();
            var dt = new Date();
            var nowDate = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear()
            var choosenStringDate = $(this).val().split("/")
            var choosenDate = new Date(choosenStringDate[2], choosenStringDate[1] - 1, choosenStringDate[0])
            $('#ddlDeliveryTime').val('-1');
            if (dt.getDate() == choosenDate.getDate() && dt.getMonth() == choosenDate.getMonth() && dt.getFullYear() == choosenDate.getFullYear()) {
                var currentHour = dt.getHours();
                if (currentHour < 8) {

                    $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);
                } else
                    if (currentHour < 17) {
                        $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);

                    }
                    else {
                        $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', true);

                    }


            }
            else {

                $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);

            }

            var str = "";
            $("#ddlArea option:selected").each(function () {
                str = $(this).text();
            });
            if (str == 'Outside Beirut') {
                DisplayNotificationMessageNew('divNotificationMessage', 'Please note that deliveries outside Beirut will take up to 48 hours', 2000);
            }
        },
        yearRange: "-100:+0"
    });
}
function InitializeData() {
    HighlightActiveMenu();
    AnimateMenu();
    SetWaterMarks();
    $('[data-toggle="tooltip"]').tooltip();
    DisplayShoppingCartItemCount();

    $(".jqDatePicker").datepicker({
        dateFormat: "dd/mm/yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+0"
    });
    ShoppingCartDeliveryDate();
    var dateToday = new Date();
    $(".jqDatePickerDeliveryDateTemp").datepicker({
        dateFormat: "dd/mm/yy",
        changeMonth: true,
        changeYear: true,
        minDate: dateToday,
        beforeShowDay: function (date) {
            var day = date.getDay();

            //check if today should be disabled
            var dt = new Date();
            if (dt.getDate() == date.getDate() && dt.getMonth() == date.getMonth() && dt.getFullYear() == date.getFullYear()) {
              //  var currentHour = dt.getHours();
                //if (currentHour >= 17) day = 0;
                day = 0;
            }

            return [(day != 0), ''];

        },
        onSelect: function (dateText, inst) {
            var time = $('#ddlDeliveryTime').val();
            var dt = new Date();
            var nowDate = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear()
            var choosenStringDate = $(this).val().split("/")
            var choosenDate = new Date(choosenStringDate[2], choosenStringDate[1] - 1, choosenStringDate[0])
            $('#ddlDeliveryTime').val('-1');
            if (dt.getDate() == choosenDate.getDate() && dt.getMonth() == choosenDate.getMonth() && dt.getFullYear() == choosenDate.getFullYear()) {
                var currentHour = dt.getHours();
                if (currentHour < 8) {

                    $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);
                } else
                    if (currentHour < 17) {
                        $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);

                    }
                    else {
                        $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', true);

                    }


            }
            else {

                $("#ddlDeliveryTime option[value*='8:00am to 5:00pm']").prop('disabled', false);

            }

            var str = "";
            $("#ddlArea option:selected").each(function () {
                str = $(this).text();
            });
            if (str == 'Outside Beirut') {
                DisplayNotificationMessageNew('divNotificationMessage', 'Please note that deliveries outside Beirut will take up to 48 hours', 2000);
            }
        },
        yearRange: "-100:+0"
    });

    $('.searchProductTextBox').keyup(function (e) {
        if (e.keyCode == 13) {
            //var n = $('.searchProductTextBox').val();
            //var searchpage = 'searchproducts.aspx?n=' + n + '';
            //window.location.assign(searchpage)
            SearchProducts($('.searchProductTextBox').val());
        }
    });
    $('.searchProductButton').click(function (e) {
        //var n = $('.searchProductTextBox').val();
        //var searchpage = 'searchproducts.aspx?n=' + n + '';
        //window.location.assign(searchpage)

        SearchProducts($('.searchProductTextBox').val());
    });

    $('.searchProductTextBoxM').keyup(function (e) {
        if (e.keyCode == 13) {
            //var n = $('.searchProductTextBoxM').val();
            //var searchpage = 'searchproducts.aspx?n=' + n + '';
            //window.location.assign(searchpage)

            SearchProducts($('.searchProductTextBoxM').val());
        }
    });
    $('.searchProductButtonM').click(function (e) {
        //var n = $('.searchProductTextBoxM').val();
        //var searchpage = 'searchproducts.aspx?n=' + n + '';
        //window.location.assign(searchpage)

        SearchProducts($('.searchProductTextBoxM').val());
    });

    $('#divNotificationMessageClose').click(function (e) {
        $('#divAddingItemToCartMessage').fadeOut('slow');
    });


    if ($('.divOrderConfirmationOrder').length > 0) {
        var str = $('.divOrderConfirmationOrder').html();
        res = str.replace(/"/g, "'");
        OrderContent = res;
        $.ajax({
            type: "GET",
            async: false,
            url: "SiteWebService.asmx/OrderConfirmationOrderEmailContent",
            type: "POST",
            dataType: "json",
            data: '{OrderContent:"' + OrderContent + '"}',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
            },
            error: function (e) {
                alert("Error! " + e.status + " - " + e.statusText);
            }
        });
    }
    //to be cpmmented only in case of fixed scroll header
    //if ($('#divShoppingCartContainer').length > 0) {
    //    $('html, body').animate({
    //        scrollTop: $("#divShoppingCartContainer").offset().top
    //    }, 250);
    //}

    if ($('#ddlArea').length > 0) {
        var str = "";

        $("#ddlArea option:selected").each(function () {
            str = $(this).text();
        });

        if (str == 'Outside Beirut') {

            //$("#divDeliveryDate").hide();
            $("#divDeliveryTime").hide();
        }
        else {
            //$("#divDeliveryDate").show();
            $("#divDeliveryTime").show();
        }
    }


    $("#ddlArea")
        .change(function () {
            var str = "";
            $("#ddlArea option:selected").each(function () {
                str = $(this).text();
            });
            if (str == 'Outside Beirut') {
                //alert($("#divDeliveryDate").text());
                //if ($("#divDeliveryDate").text() != '')
                //DisplayNotificationMessageNew('divNotificationMessage', 'Please not that your order will be delivered within a minimum period of up to 48h', 2000);



                $("#divDeliveryTime").hide();
            }
            else {
                //$("#divDeliveryDate").show();
                $("#divDeliveryTime").show();
            }
            ShoppingCartDeliveryDate();
        });


    EqualizeSubCategoriesHeightForCategories();


    $('.SupplierSlider').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        dots: true,
        infinite: true,
        arrows: false,
        prevArrow: '<button type="button" class="slick-prev"></button>',
        nextArrow: '<button type="button" class="slick-next"></button>',
        slidesToShow: 6,
        slidesToScroll: 6
    });

    $('.SupplierMobileSlider').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        dots: false,
        infinite: true,
        arrows: false,
        prevArrow: '<button type="button" class="slick-prev"></button>',
        nextArrow: '<button type="button" class="slick-next"></button>',
        centerMode: true,
        slidesToShow: 4,
        slidesToScroll: 4
    });

    $('.BrandsSlider').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        dots: true,
        infinite: true,
        arrows: false,
        prevArrow: '<button type="button" class="slick-prev"></button>',
        nextArrow: '<button type="button" class="slick-next"></button>',
        slidesToShow: 6,
        slidesToScroll: 6
    });

    $('.BrandsMobileSlider').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        dots: false,
        infinite: true,
        arrows: false,
        prevArrow: '<button type="button" class="slick-prev"></button>',
        nextArrow: '<button type="button" class="slick-next"></button>',
        centerMode: true,
        slidesToShow: 4,
        slidesToScroll: 4
    });

    $('.ProductCategoriesProductSlider').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        dots: false,
        infinite: true,
        arrows: true,
        prevArrow: '<button type="button" class="slick-prev"></button>',
        nextArrow: '<button type="button" class="slick-next"></button>',
        slidesToShow: 3,
        slidesToScroll: 3,
        responsive: [

            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
        ]
    });



    if ($(".divPromoNotificationContainerWrapper").length > 0) {
        $(".divPromoNotificationContainerWrapper").click(function () {
            $('#divPromoNotification').hide();

        })
    }


    if ($('#hdfShowPromoNotification').val() == '1') {

        setTimeout(function () {
            $('#divPromoNotification').show();
            $.ajax({
                type: "GET",
                async: false,
                url: "SiteWebService.asmx/SetShowPromoNotification",
                type: "POST",
                dataType: "json",
                data: "",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                },
                error: function (e) {
                }
            });

        }, 2000);
    }



}


function SearchProducts(keyword) {
   
    //var searchpage = '/searchproducts.aspx?n=' + keyword.toLowerCase() + '';
    //window.location.assign(searchpage)
    keyword = URLRewriteQueryString(keyword);
    //alert(keyword);
    $.ajax({
        type: "GET",
        async: false,
        url: "/SiteWebService.asmx/StringUrlEncoding",
        type: "POST",
        dataType: "json",
        data: '{Word:"' + keyword + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var searchpage = '/searchproducts.aspx?n=' + data.d + '';
            window.location.assign(searchpage)
        },
        error: function (e) {
          //alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
        }
    });




}
function URLRewriteQueryString(Querystring) {

    return Querystring.replaceAll('"', "");
}

function EqualizeSubCategoriesHeightForCategories() {
    var maxLength = 0;
    $(".ProductCategoriesItemPadding .item .subContainer").each(function (index) {
        if (maxLength < $(this).height())
            maxLength = $(this).height();
    });
    $(".ProductCategoriesItemPadding .item .subContainer").each(function (index) {
        if (maxLength > $(this).height()) {
            $(this).height(maxLength);
            //  alert($(this).text());
        }
    });
}



function ApplyToCareer(JobTitle) {
    $('#txtJobTitle').val(JobTitle);
    $('#txtTitle').focus();
}

function SetWaterMarks() {
    //  $('#txtSubscribeEmail').watermark('your e-mail');

    // $('.txtSearchSite').watermark('Search...');
    // $('.txtSearchSite2').watermark('Search...');



    $('#txtLoginUser2').watermark('Username');
    $('#txtLoginPassword2').watermark('Password');
    $('#txtUsernameForgetPassword').watermark('Username');
}

function AnimateMenu() {
    $("#topMenu li.Desktop.links").each(function (index) {
        if (index != activeMenu) {
            $(this).hover(
                function () {

                    $(this).stop(true, false).animate({
                        height: "90px"
                    });
                }, function () {
                    $(this).stop(true, false).animate({
                        height: "70px"
                    });
                });
        }
        else {
            $(this).stop(true, false).animate({
                height: "90px"
            });
        }
    });

}

function HighlightActiveMenu() {
    var activeClass = '';
    var pageName = $(location).attr('pathname').toLowerCase();
    if (pageName == '/')
        pageName = "/default.aspx";
    //alert(pageName);
    switch (true) {
        case (pageName.match(/default/g) || []).length > 0:
            activeClass = ".home";
            break;
        case (pageName.match(/profile/g) || []).length > 0:
            activeClass = ".profile";
            break;
        case (pageName.match(/services/g) || []).length > 0:
            activeClass = ".services";
            break;
        case (pageName.match(/products/g) || []).length > 0:
            activeClass = ".products";
            break;
        case (pageName.match(/specialoffers/g) || []).length > 0:
            activeClass = ".specialoffers";
            break;
        case (pageName.match(/newsandevents/g) || []).length > 0:
            activeClass = ".newsandevents";
            break;
        case (pageName.match(/careers/g) || []).length > 0:
            activeClass = ".careers";
            break;
        case (pageName.match(/contactus/g) || []).length > 0:
            activeClass = ".contactus";
            HighlightQuickViewIcon("location");
            break;
        case (pageName.match(/offerdetails/g) || []).length > 0:
            activeClass = ".specialoffers";
            break;
        case (pageName.match(/shoppingcart/g) || []).length > 0:
            HighlightQuickViewIcon("shoppingcart");
            break;
    }
    activeMenu = $("#topMenu li.Desktop.links").index($(".navbar-nav " + activeClass));
    $(".navbar-nav " + activeClass).addClass('active');
    activeMenuClass = activeClass;
}


function AddItemToCart(ProductID, CID, SID) {
    location.href = 'productsdetails.aspx?pid=' + ProductID + '&cid=' + CID + '&scid=' + SID;
    //$.ajax({
    //    type: "GET",
    //    async: false,
    //    url: "SiteWebService.asmx/AddProductToShoppingCart",
    //    type: "POST",
    //    dataType: "json",
    //    data: '{ProductID:' + ProductID + '}',
    //    contentType: "application/json; charset=utf-8",
    //    success: function (data) {
    //        if (data.d) {
    //            $("#divShopcartadd").show();
    //            $("#divShopcartexclude").hide();
    //        }
    //        else {
    //            $("#divShopcartadd").hide();
    //            $("#divShopcartexclude").show();
    //        }
    //        $("#divAddingItemToCartMessage").show();
    //    },
    //    error: function (e) {
    //        //  alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
    //        $("#divShopcartadd").hide();
    //        $("#divShopcartexclude").show();
    //        $("#divAddingItemToCartMessage").show();

    //    }
    //});
    //DisplayShoppingCartItemCount();
    //setTimeout(function () {
    //    $('#divAddingItemToCartMessage').fadeOut('slow');
    //}, 15000);

}


function HideNotificationMessage() {
    $('#divAddingItemToCartMessage').fadeOut('slow');
}


function DisplayNotificationMessage(control, Message, Duration) {
    $("#" + control).text(Message);
    $("#" + control).show();
    $("#divAddingItemToCartMessage").show();
    setTimeout(function () {
        $('#divAddingItemToCartMessage').fadeOut('slow');
        $("#" + control).hide();

    }, 3000);
}


function DisplayNotificationMessageNew(control, Message, Duration) {
    $("#" + control).text(Message);
    $("#" + control).show();
    $("#divAddingItemToCartMessage").show();
    setTimeout(function () {
        $('#divAddingItemToCartMessage').fadeOut('slow');
        $("#" + control).hide();

    }, Duration);
}

function AddItemToCartWithDetails(ProductID) {
    var Quantity = $(".txtQuantity").val();
    var DeliveryDate = $(".txtDeliveryDate").val();
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/AddProductToShoppingCartWithDetails",
        type: "POST",
        dataType: "json",
        data: '{ProductID:' + ProductID + ',Quantity:' + Quantity + ',DeliveryDate:"' + DeliveryDate + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                $("#divShopcartadd").show();
                $("#divShopcartexclude").hide();
            }
            else {
                $("#divShopcartadd").hide();
                $("#divShopcartexclude").show();
            }
            $("#divAddingItemToCartMessage").show();
        },
        error: function (e) {
            //  alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
            // $("#errorDiv").text("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText)
            $("#divShopcartadd").hide();
            $("#divShopcartexclude").show();
            $("#divAddingItemToCartMessage").show();

        }
    });

    DisplayShoppingCartItemCount();
    setTimeout(function () {
        $('#divAddingItemToCartMessage').fadeOut('slow');
    }, 15000);

}


var selectedQuickViewIcon = '';
function ShowQuickView(name) {
    if (selectedQuickViewIcon == name) {
        HideQuickView(name);
        return;
    }
    if (selectedQuickViewIcon != '')
        HideQuickView(selectedQuickViewIcon);

    HighlightQuickViewIcon(name);
    $('.' + name + '-quickview').toggle("slide", { direction: "right" }, 1000);
    selectedQuickViewIcon = name;
}

function HighlightQuickViewIcon(name) {
    switch (name) {
        case 'shoppingcart':
            $('.menu-shoppingcart-icon').attr('src', 'images/shoppingCart-selected-icon.jpg');
            SetShoppingCartQuickView();
            break;
        case 'search':
            $('.menu-search-icon').attr('src', 'images/search-selected-icon.jpg');

            break;
        case 'location':
            $('.menu-location-icon').attr('src', 'images/location-selected-icon.jpg');
            break;
        case 'user':
            $('.menu-user-icon').attr('src', 'images/user-selected-icon.jpg');
            SetUserQuickView();
            break;

    }
}


function ClearHighlightQuickViewIcon(name) {
    switch (name) {
        case 'shoppingcart':
            $('.menu-shoppingcart-icon').attr('src', 'images/shoppingCart-icon.png');
            break;
        case 'search':
            $('.menu-search-icon').attr('src', 'images/search-icon.jpg');
            break;
        case 'location':
            $('.menu-location-icon').attr('src', 'images/location-icon.jpg');
            break;
        case 'user':
            $('.menu-user-icon').attr('src', 'images/user-icon.jpg');
            break;

    }
}

function HideQuickView(name) {
    if (selectedQuickViewIcon != '')
        switch (selectedQuickViewIcon) {
            case 'shoppingcart':
                $('.menu-shoppingcart-icon').attr('src', 'images/shoppingCart-icon.jpg');
                break;
            case 'search':
                $('.menu-search-icon').attr('src', 'images/search-icon.jpg');
                break;
            case 'location':
                $('.menu-location-icon').attr('src', 'images/location-icon.jpg');
                break;
            case 'user':
                $('.menu-user-icon').attr('src', 'images/user-icon.jpg');
                break;

        }
    $('.' + selectedQuickViewIcon + '-quickview').toggle("slide", { direction: "right" }, 1000);
    selectedQuickViewIcon = '';
}

function GoToSearch() {
    var p = $('.searchProductPriceTextBox').val();
    var n = $('.searchProductNameTextBox').val();
    var c = $('.searchProductCategoryTextBox').val();
    var b = $('.searchProductBrandTextBox').val();
    var searchpage = 'searchproducts.aspx?n=' + n + '&c=' + c + '&p=' + p + '&b=' + b + '';
    window.location.assign(searchpage)
}




function GetShoppingCartItemCount() {
    var ShoppingCartItemCount = 0;
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/GetShoppingCartItemCount",
        type: "POST",
        dataType: "json",
        data: '',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            ShoppingCartItemCount = data.d
        },
        error: function (e) {
        }
    });
    return ShoppingCartItemCount
}


function DisplayShoppingCartItemCount() {
    var ShoppingCartItemCount = GetShoppingCartItemCount();
    if (ShoppingCartItemCount > 0) {
        $('.ShoppingCartItemsCount').html('' + ShoppingCartItemCount + '');
        HighlightQuickViewIcon('shoppingcart');
    }
    else {
        $('.ShoppingCartItemsCount').html('0');
        ClearHighlightQuickViewIcon('shoppingcart');
    }
}

function SetShoppingCartQuickView() {
    var ShoppingCartItemCount = GetShoppingCartItemCount();

    if (ShoppingCartItemCount > 0) {
        $('.divShoppingCartEmpty').hide();
        $('.divShoppingCart').show();
        $('.divShoppingCartItemsQuickView').html('');
        var c = GetShoppingCartItems();
        $('.divShoppingCartItemsQuickView').html(c);
    }
    else {
        $('.divShoppingCart').hide();
        $('.divShoppingCartItemsQuickView').html('');
        $('.divShoppingCartEmpty').show();
    }

}
function SetUserQuickView() {
    ShowSignup();
}


function GetShoppingCartItems() {
    var currency = $("#hdfCurrency").val();
    var shoppingCartItems = '';
    var shoppingCartItemsQuickViewTotalPrice = 0;
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/GetShoppingCartItems",
        type: "POST",
        dataType: "json",
        data: '',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var shoppingCartList = jQuery.parseJSON(data.d);

            for (var i = 0; i < shoppingCartList.length; i++) {
                var itemFormat = "";
                itemFormat = itemFormat + '<tr class="ui-widget-content">';
                itemFormat = itemFormat + '<td style="border-right: 0px;"><img width="60px" src="../imagesdb/Products/Thumbnail/' + shoppingCartList[i].ThumbnailPhoto + '" /></td>';
                itemFormat = itemFormat + '<td  >' + shoppingCartList[i].ProductTitle + '</td>';
                itemFormat = itemFormat + '<td >' + shoppingCartList[i].Price.toLocaleString("en", { minimumFractionDigits: 2 }) + ' ' + currency + '</td>';
                itemFormat = itemFormat + '<td >' + shoppingCartList[i].ShoppingCartQuantity + '</td>';
                itemFormat = itemFormat + '</tr>';
                shoppingCartItems = shoppingCartItems + itemFormat;
                shoppingCartItemsQuickViewTotalPrice += shoppingCartList[i].Price * shoppingCartList[i].ShoppingCartQuantity
            }
            shoppingCartItems = '<table class="gridview" style="border-style: None; width: 100%;"><tr class="ui-widget-header"><th colspan=2>Product Name</th><th>Quantity</th><th style="border-right: 0px;">Price</th></tr>' + shoppingCartItems + '</table>';

        },
        error: function (e) {
            alert("Error! " + e.status + " - " + e.statusText);
        }
    });

    $("#spanShoppingCartItemsQuickViewTotal").html(shoppingCartItemsQuickViewTotalPrice.toLocaleString("en", { minimumFractionDigits: 2 }) + ' ' + currency);

    return shoppingCartItems
}



function Login() {
    $("#lblLoginMessage").hide();
    if ($("#txtLoginUser2").val() == '') $("#spLoginUser").show();
    if ($("#txtLoginPassword2").val() == '') $("#spLoginPassword").show();
    if ($("#txtLoginUser2").val() == '' || $("#txtLoginPassword2").val() == '') return;
    $("#spLoginUser").hide();
    $("#spLoginPassword").hide();


    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/Login",
        type: "POST",
        dataType: "json",
        data: '{username:"' + $("#txtLoginUser2").val() + '",password:"' + $("#txtLoginPassword2").val() + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                window.location.reload();
            }
            else {

                $("#lblLoginMessage").show();
            }
        },
        error: function (e) {
            //alert("Error! " + e.status + " - " + e.statusText);
            $("#lblLoginMessage").show();
        }
    });

}



function ShowForgetPassword() {
    $(".divSignin").hide();
    $(".divForgetPassword").show();
    $("#spForgetPasswordNotification").hide();
    $("#spForgetPasswordNotification").hide();
    $("#txtUsernameForgetPassword").val('');
}
function ShowSignup() {
    $(".divSignin").show();
    $(".divForgetPassword").hide();

    $("#lblLoginMessage").hide();
    $("#txtLoginUser2").val('');
    $("#txtLoginPassword2").val('');
    $("#spLoginUser").hide();
    $("#spLoginPassword").hide();


}



function ResetPassword() {
    $("#spForgetPasswordNotification").hide();
    if ($("#txtUsernameForgetPassword").val() == '') { $("#spUsernameForgetPassword").show(); return; }
    $("#spUsernameForgetPassword").hide();


    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/ResetPassword",
        type: "POST",
        dataType: "json",
        data: '{username:"' + $("#txtUsernameForgetPassword").val() + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                $("#spForgetPasswordNotification").html('please check your email address');
                $("#spForgetPasswordNotification").show();
            }
            else {
                $("#spForgetPasswordNotification").html('please enter a valid username');
                $("#spForgetPasswordNotification").show();
            }
        },
        error: function (e) {
            //alert("Error! " + e.status + " - " + e.statusText);
            $("#spForgetPasswordNotification").html('please enter a valid username');
            $("#spForgetPasswordNotification").show();
        }
    });

}



function AddProductWithQuantityToShoppingCart(ProductID, Quantity) {
    var shoppingcartProductPrice = 0;
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/AddProductWithQuantityToShoppingCart",
        type: "POST",
        dataType: "json",
        data: '{ProductID:' + ProductID + ',Quantity:' + Quantity + '}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                shoppingcartProductPrice = data.d;
            }

        },
        error: function (e) {
            //  alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
            return -1;
        }
    });
    return shoppingcartProductPrice;
}


function ModifyShoppingcartQuantities(ProductID, Operation, txtQuantity, imgOutOfStock) {
    var qty = parseInt($("#" + txtQuantity).val());
    switch (Operation) {
        case '+':
            qty = qty + 1;
            break;
        case '-':
            qty = qty - 1;
            break;
        default:
    }
    if (qty > 0) {

        $("#" + txtQuantity).val(qty);

        var x1 = txtQuantity.lastIndexOf("_");
        var x2 = txtQuantity.substring(x1 + 1);
        if (txtQuantity.indexOf("Mobile") > 0) {
            $("#ContentPlaceHolder1_gvShoppingCart_txtQuantity_" + x2).val(qty);
        }
        else {
            $("#ContentPlaceHolder1_gvShoppingCartMobile_txtQuantity_" + x2).val(qty);
        }

        var currency = $("#hdfCurrency").val();
        //var total = AddProductWithQuantityToShoppingCart(ProductID, qty);

        var shoppingcartProductPrice = 0.00;
        var Availability = false;
        $.ajax({
            type: "GET",
            async: false,
            url: "SiteWebService.asmx/AddProductWithQuantityToShoppingCart",
            type: "POST",
            dataType: "json",
            data: '{ProductID:' + ProductID + ',Quantity:' + qty + '}',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data.d) {
                    shoppingcartProductPrice = data.d.ShoppingCartProductSum;
                    Availability = data.d.Availability;
                }
            },
            error: function (e) {
                //alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
            }
        });
        var total = shoppingcartProductPrice;
        $("#lblSubTotal").html(total.toLocaleString("en", { minimumFractionDigits: 2 }) + ' ' + currency);
        $("#lblAllTotal").html(total.toLocaleString("en", { minimumFractionDigits: 2 }) + ' ' + currency);

        if (Availability) {
            $("#ContentPlaceHolder1_gvShoppingCart_imgOutOfStock_" + x2).hide();
            $("#ContentPlaceHolder1_gvShoppingCart_imgOutOfStocky_" + x2).hide();
        }
        else {

            $("#ContentPlaceHolder1_gvShoppingCart_imgOutOfStock_" + x2).show();
            $("#ContentPlaceHolder1_gvShoppingCart_imgOutOfStocky_" + x2).show();
            DisplayNotificationMessage('divNotificationMessage', 'Some items are out of stock. Please review your order');
        }
    }
}


function ModifyShoppingcartDeliveryDate(ProductID, txtDeliveryDate) {
    var qty = $("#" + txtDeliveryDate).val();
    //$("#" + txtQuantity).val(qty);
    var x1 = txtDeliveryDate.lastIndexOf("_");
    var x2 = txtDeliveryDate.substring(x1 + 1);
    //if (txtDeliveryDate.indexOf("Mobile") > 0) {
    //        $("#ContentPlaceHolder1_gvShoppingCart_txtDeliveryDate_" + x2).val(qty);
    //    }
    //    else {
    //        $("#ContentPlaceHolder1_gvShoppingCartMobile_txtDeliveryDate_" + x2).val(qty);
    //    }
    updateProductShoppingCartWithDeliveryDate(ProductID, qty);
}


function updateProductShoppingCartWithDeliveryDate(ProductID, DeliveryDate) {
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/UpdateProductShoppingCartWithDeliveryDate",
        type: "POST",
        dataType: "json",
        data: '{ProductID:' + ProductID + ',DeliveryDate:' + DeliveryDate + '}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                return true
            }
        },
        error: function (e) {
            alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);

        }
    });
    return false;
}





function GetProductFeatureDetails(ProductFeatureID) {
    var ProductID = 0;
    var showFirstImage = false;
    $('#galleryImage >li').hide();
    $('#galleryImage >li').filter(function (index) {
        if (parseInt($(this).attr('data-feature')) == ProductFeatureID) {
            if (showFirstImage) return false;
            else {
                showFirstImage = true;
                return true

            }
        }
        else
            return false;
        //return (parseInt($(this).attr('data-feature')) == ProductFeatureID ) 
    }).show();

    if (showFirstImage == false) {

        $('#galleryImage >li').filter(function (index) {
            if (parseInt($(this).attr('data-feature')) == 0) {
                if (showFirstImage) return false;
                else {
                    showFirstImage = true;
                    return true

                }
            }
            else
                return false;
            //return (parseInt($(this).attr('data-feature')) == ProductFeatureID ) 
        }).show();

    }

    $('#ulThumbnail >li').hide();

    $('#ulThumbnail >li').filter(function (index) {
        return (parseInt($(this).attr('data-feature')) == ProductFeatureID)
    }).show();

    if ($('#ulThumbnail >li').filter(function (index) {
        return (parseInt($(this).attr('data-feature')) == ProductFeatureID)
    }).length == 0)
        $('#ulThumbnail >li').filter(function (index) {
            return (parseInt($(this).attr('data-feature')) == 0)
        }).show();

    $(".divProductColors > div").removeClass('selected');
    $(".divProductColors > div").addClass('unselected');
    $(".divColor" + ProductFeatureID).removeClass('unselected');
    $(".divColor" + ProductFeatureID).addClass('selected');

    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/GetProductFeatureDetails",
        type: "POST",
        dataType: "json",
        data: '{ProductID:' + ProductID + ',ProductFeatureID:' + ProductFeatureID + '}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {

                var qty = data.d.QuantityInStock;
                var price = data.d.Price;
                if (qty > 0)
                    //$(".lblAvailableQuantity").html(qty + ' item(s)');
                    $(".lblAvailableQuantity").html('Available');

                else
                    $(".lblAvailableQuantity").html('Out of Stock');
              //  var priceValue = 'LBP ' + price.toLocaleString("en", { minimumFractionDigits: 2 })  ;
                var priceValue =  price.toLocaleString("en", { minimumFractionDigits: 2 }) + ' $';
              //  $(".lblPrice").html(priceValue);
                $(".lblPrice").html(priceValue);

                $("#hdfAvailableQuantity").val(data.d.QuantityInStock);
                $("#hdfSelectedFeature").val(ProductFeatureID);
                $(".lblProductCode").html(data.d.ItemCode);


            }
        },
        error: function (e) {
            //alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
        }
    });


}




function AddItemToCartWithFeatureDetails(ProductID) {

    if ($("#hdfHasFeatures").val() == '1' && $("#hdfSelectedFeature").val() == '') {
        var featureTitle = $(".ProductFeaturesCategpryTitle").html();
        var title = featureTitle.replace(':', '')
        DisplayNotificationMessageNew('divNotificationMessage', 'Please select a ' + title + '.', 2000);

        return;
    };

    var Quantity = parseInt($(".txtQuantity").val());


    var AvailableQuantity = parseInt($("#hdfAvailableQuantity").val());

    if (Quantity > AvailableQuantity) {
        DisplayNotificationMessageNew('divNotificationMessage', 'Quantity is not available in stock. Please review your order.', 2000);
        return;
    };





    var MinimumQuantityToOrder = parseInt($("#hdfMinimumQuantityToOrder").val());

    if (MinimumQuantityToOrder > 1 && Quantity < MinimumQuantityToOrder) {
        DisplayNotificationMessageNew('divNotificationMessage', 'Minimum quantity to order is ' + MinimumQuantityToOrder + ' items.', 2000);

        return;
    };



    var selectedProductFeatureID = 0;
    if ($("#hdfSelectedFeature").val() != '') selectedProductFeatureID = $("#hdfSelectedFeature").val();
    var DeliveryDate = $(".txtDeliveryDate").val();
    $.ajax({
        type: "GET",
        async: false,
        url: "SiteWebService.asmx/AddProductToShoppingCartWithFeauterDetails",
        type: "POST",
        dataType: "json",
        data: '{ProductID:' + ProductID + ',ProductFeatureID:' + selectedProductFeatureID + ',Quantity:' + Quantity + ',DeliveryDate:"' + DeliveryDate + '"}',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.d) {
                $("#divShopcartadd").show();
                $("#divShopcartexclude").hide();
            }
            else {
                $("#divShopcartadd").hide();
                $("#divShopcartexclude").show();
            }
            $("#divAddingItemToCartMessage").show();
        },
        error: function (e) {
            //  alert("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText);
            // $("#errorDiv").text("function execution has failed: " + e.status + ": " + e.statusText + "." + e.responseText)
            $("#divShopcartadd").hide();
            $("#divShopcartexclude").show();
            $("#divAddingItemToCartMessage").show();

        }
    });

    DisplayShoppingCartItemCount();
    setTimeout(function () {
        $('#divAddingItemToCartMessage').fadeOut('slow');
    }, 15000);

}

