﻿jQuery(function($) {
    $('a.addgift-buy').click(function() {
        $(this).parent()
           .find('a.add-gift')
           .click();

    });


    $('a.add-gift').click(function() {

        var selectvalue = "";
        var quantity = $(this).parent()
                              .find('input.gift-quantity')
                              .val();
        var c = $(this).parent()
                       .find('select.SubTypeSelector :selected');

        if (c.length > 0) {
            if (c.index() == 0) {
                alert("נא לבחור סוג המתנה");
                return false;
            }
            selectvalue = $(this).parent().find('select.SubTypeSelector :selected').val();
        }

        gift.addToCart($(this).attr("GiftID"), quantity, selectvalue, $(this).parent().hasClass('GiftCard'));
        //        if(typeof(cart) != 'undefined') {
        //            cart.GetCartList();
        //        }


        return false;
    });

    $('a.add-gift-special-addition').click(function() {

        var selectvalue = "";
        var quantity = $(this).parent()
                              .find('input.gift-quantity')
                              .val();
        var giftDetailsContainer = $(".giftmagnifier");
        var c = $('select.SubTypeSelector :selected', giftDetailsContainer);

        if (c.length > 0 && c != undefined) {
            if (c.index() == 0) {
                alert("נא לבחור סוג המתנה");
                return false;
            }
            selectvalue = $(this).parent().find('select.SubTypeSelector :selected').val();
        }

        gift.addToCart($(this).attr("GiftID"), quantity, selectvalue, $(this).parent().hasClass('GiftCard'));
        //        if(typeof(cart) != 'undefined') {
        //            cart.GetCartList();
        //        }


        return false;
    });
    
    $('a.popup-add-gift').click(function() {

        //debugger;
        //gift.addToCart($(this));
        //LinkAddToCart($(this), true);
        $(this).parent().find('div.GiftTypesControlBox').show();

        return false;
    });

    $('a.AddInnerGift').click(function() {
        //debugger;
        $(this).parent().hide();

        var selectvalue = "";
        var quantity = $(this).parent().parent().find('input.gift-quantity').val();
        var c = $(this).parent().find('select.SubTypeSelector :selected');

        if (c.length > 0) {
            if (c.index() == 0) {
                alert("נא לבחור סוג המתנה");
                return false;
            }
            selectvalue = $(this).parent().find('select.SubTypeSelector :selected').val();
        }

        gift.addToCart($(this).attr("GiftID"), quantity, selectvalue, $(this).parent().hasClass('GiftCard'));

        return false;
    });

    $('a.ClosePop').click(function() {
        $(this).parent().hide();
        return false;
    });

    var gift = {
        withLoader: false,
        ajaxLoader: null,
        triggerControl: null,
        getPrefixPhoneList: function() {
            //EliteGifts.AjaxMethods.GetPrefixPhoneList(this.onGetPrefixPhoneList, this.onAjaxError);
            //debugger;
            $.ajax({

                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/getPrefixPhoneList",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    //debugger;
                    var res = response.d;
                    gift.onGetPrefixPhoneList(res);
                }
            });
        },
        onGetPrefixPhoneList: function(value) {
            var JsonAjaxMethods = eval('(' + value + ')');

            if (JsonAjaxMethods.Action == true) {
                try {
                    var prefix = JsonAjaxMethods.Data;
                    var options = '';

                    for (var item in prefix) {
                        options += "<option value=\"" + prefix[item].AreaCodeID + "\">" + prefix[item].AreaCodeNumber + "</option>";
                    }

                    $('.prefixphone').html(options);
                }
                catch (ex) { alert("לא ניתן לטעון את רשימת איזורי חיוג"); }
            }
            else {
                alert(JsonAjaxMethods.Message);
            }
        },

        addToCart: function(giftid, quantity, type, cardtype) {
            try {

                $.ajax({
                    type: "POST",
                    async: false,
                    url: "/elitegifts/ajax/EliteGiftsHandler.asmx/AddToCart",
                    data: "{giftID: '" + giftid + "', quantity: '" + quantity + "', type: '" + type + "', cardtype: '" + cardtype + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(response) {
                        var res = eval('(' + response.d + ')');

                        if (res.IsSuccess) {
                            $('a.cartCount > span ').text("(" + res.Message + ")");

                            if (cart)
                                cart.GetCartList();
                        }
                        else
                            alert(res.Message);
                    }
                });

                return false;
                //EliteGifts.AjaxMethods.AddToCart(giftID, quantity, this.onAddToCartSuccess, this.onAjaxError);
            }
            catch (ex) {
                alert("לא ניתן כעת להוסיף פריט זה לסל, נא נסה שנית במועד מאוחר יותר");
                gift.hideLoader();
            }
        },




        showLoader: function() {
            if (!gift.withLoader) return;

            gift.ajaxLoader.css('display', 'inline');
            gift.triggerControl.css('display', 'none');
            $('#CartState').css('display', 'block');
        },

        hideLoader: function() {
            if (!gift.withLoader) return;

            gift.ajaxLoader.css('display', 'none');
            gift.triggerControl.css('display', 'inline');
        },
        onAjaxError: function(value) {
            alert("לא ניתן לבצע פעולה זאת כעת. ניתן לנסות שנית מאוחר יותר או לפנות לנציג תמיכה טכנית");
            location.reload(true);
        },
        getCartData: function() {

            $.ajax({
                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/GetCartData",
                //data: "{giftID: '" + giftID + "', quantity: '" + quantity + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    // debugger;
                    var res = response.d;
                    gift.onGetCartData(res);
                }
            });

            //EliteGifts.AjaxMethods.GetCartData(gift.onGetCartData, gift.onAjaxError);
        },
        onGetCartData: function(value) {
            //debugger;
            var JsonAjaxMethods = eval('(' + value + ')');

            if (JsonAjaxMethods.Action == true) {
                $("div[id$='pnlCartState']").html(JsonAjaxMethods.Data);
                $('#CartState').css('display', 'block');
            }
            else {
                alert(JsonAjaxMethods.Message);
            }
        },
        sendMail: function() {
            this.withLoader = false;

            var name = $("#txtName").val();
            var phone = $("#txtPhone").val();
            var number = $("#txtNumber").val();

            $.ajax({
                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/SendMail",
                data: "{name: '" + name + "', phone: '" + phone + "', number: '" + number + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    // debugger;
                    var res = response.d;
                    gift.onSendMail(res);
                }
            });

            //EliteGifts.AjaxMethods.SendMail(name, phone, number, this.onSendMail, this.onAjaxError);
        },
        onSendMail: function(value) {
            var JsonAjaxMethods = eval('(' + value + ')');

            if (JsonAjaxMethods.Action == true) {
                window.frames["QuoteRequestIFrame"].location = "/elitegifts/seo/SendSuccess.htm";
                $('.contactus-content').html(JsonAjaxMethods.Message);
            }
            else {
                alert(JsonAjaxMethods.Message);
                gift.hideLoader();
            }
        },
        clear: function() {
            this.withLoader = false;

            $.ajax({
                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/Clear",
                //data: "{name: '" + name + "', phone: '" + phone + "', number: '" + number + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    // debugger;
                    var res = response.d;
                    gift.onClear(res);
                }
            });

            //EliteGifts.AjaxMethods.Clear(gift.onClear, gift.onAjaxError);
        },
        onClear: function(value) {
            var JsonAjaxMethods = eval('(' + value + ')');

            if (JsonAjaxMethods.Action == true) {
                location.reload(true);
            }
            else {
                alert(JsonAjaxMethods.Message);
                gift.hideLoader();
            }
        },
        onAddToCartSuccess: function(value) {
            try {
                //debugger;
                var jsonMessage = eval('(' + value + ')');

                if (jsonMessage) {
                    alert(jsonMessage);
                    //todo: hide the loader...
                }

                //                gift.showLoader();

                $.ajax({
                    type: "POST",
                    async: false,
                    url: "/elitegifts/ajax/AjaxMethods.asmx/GetProductCount",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(response) {
                        //debugger;
                        var res = response.d;
                        $(".cartCount")[0].innerHTML = "הסל שלי (" + res + ")";

                        //gift.onGetCartData(res);
                    }
                });
                //return false;

                //                gift.showLoader();

                //                $.ajax({
                //                    type: "POST",
                //                    async: false,
                //                    url: "/elitegifts/ajax/AjaxMethods.asmx/GetCartData",
                //                    //data: "{giftID: '" + giftID + "', quantity: '" + quantity + "'}",
                //                    contentType: "application/json; charset=utf-8",
                //                    dataType: "json",
                //                    success: function(response) {
                //                        debugger;
                //                        var res = response.d;
                //                        gift.onGetCartData(res);
                //                    }
                //                });

                //  EliteGifts.AjaxMethods.GetCartData(gift.onGetCartData, gift.onAjaxError);
            }
            catch (ex) {
                location.reload(true);
                //gift.hideLoader();
            }
        },
        onGetCartData: function(value) {
            //debugger;
            var JsonAjaxMethods = eval('(' + value + ')');
            if (JsonAjaxMethods.Action == true) {
                $("div[id$='pnlCartState']").html(JsonAjaxMethods.Data);

                if ($('#cartlist').length > 0) {
                    cart.getCartList();

                }
                if ($(".CartStateItem").length > 0) {
                    $('#CartState').css('display', 'block');
                }
                gift.setMode();
            }
            else {
                alert(JsonAjaxMethods.Message);
                gift.hideLoader();
            }
        },
        setMode: function() {
            if ($(".visibleStatus").length > 0) {
                $('#CartState').css('display', 'block');
            }
            if ($('#contactus').length == 0) {
                gift.hideLoader();

                return;
            }

            gift.showLoader();

            $.ajax({
                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/GetCartCount",
                //data: "{giftID: '" + giftID + "', quantity: '" + quantity + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    // debugger;
                    var res = response.d;
                    gift.onCartCount(res);
                }
            });

            //EliteGifts.AjaxMethods.GetCartCount(gift.onCartCount, gift.onAjaxError);
        },

        onCartCount: function(value) {
            try {
                var contactus = $('#contactus');
                var CartState = $('#CartState');
                var cartIsEmpty = eval('(' + value + ')');
                if (cartIsEmpty) {
                    CartState.hide();
                    contactus.show();
                }
                else {
                    contactus.hide();
                    CartState.show();
                }
            }
            catch (ex) { }

            gift.hideLoader();
        },
        getCartData: function() {
            $.ajax({
                type: "POST",
                async: false,
                url: "/elitegifts/ajax/AjaxMethods.asmx/GetCartData",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    var res = response.d;
                    gift.onGetCartData(res);
                }
            });

            //EliteGifts.AjaxMethods.GetCartData(gift.onGetCartData, gift.onAjaxError);
        },
        getTotalCartPrice: function() {
            EliteGifts.AjaxMethods.GetTotalCartPrice(
                function(value) { var totalPrice = eval('(' + value + ')'); $('#totalPrice').html(totalPrice + " ₪"); },
                function(value) { alert(value); });
        }

    };

    var filter = {
        animationDelay: 3500,
        filterGifts: function() {

            $oChecks = $('#filterBox').find("input").filter(function(iIndex) {
                return $(this).attr('checked') != '';
            });

            $oChecksAll = $('#filterBox').find("input");
            if ($oChecksAll.length == $oChecks.length) {
                $("div[id$='product']").show('clip', { direction: 'horizontal', opacity: '1' }, this.animationDelay, function() { });
            }
            else {
                if ($oChecks.length != 0) {
                    $("div[id$='product']").each(function(index) {

                        var fadeOutProduct = true;
                        //get the product categories
                        var oCategs = $(this).attr("categories");
                        if (oCategs != '' && oCategs != null) {
                            oCategs = oCategs.split("#");

                            $oChecks.each(function() {
                                for (var i = 0; i < oCategs.length; i++) {
                                    if ($(this).attr("categ") == oCategs[i]) {
                                        //the product is not filtered out
                                        fadeOutProduct = false;
                                    }
                                }
                            });
                        }
                        else {
                            fadeOutProduct = false;
                        }

                        if (fadeOutProduct) {
                            if ($(this).css("display") != "none") {
                                $(this).hide('clip', { direction: 'horizontal', opacity: '0' }, this.animationDelay, function() { });
                            }
                        }
                        else {
                            if ($(this).css("display") == "none") {
                                $(this).show('clip', { direction: 'horizontal', opacity: '1' }, this.animationDelay, function() { });
                            }
                        }
                    });
                }
                else {
                    $("div[id$='product']").hide('clip', { direction: 'horizontal', opacity: '0' }, this.animationDelay, function() { });
                }
            }
        },
        applyFilter: function() {
            this.filterGifts();
        }

    };

});
//jQuery(function($) {
//    gift.getPrefixPhoneList();
//});
