﻿var NG = function () {
    var webServiceUrl = "http://" + location.host + "/Handlers/NGAjaxWebService.asmx/"
    var namespace = {};

    namespace.Cookie = function () {
        var pub = {};
        pub.SetCookie = function (name, value, expiredays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
        }
        pub.GetCookie = function (name) {
            var cookieValue = "";
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        return pub;
    };
    namespace.Basket = function () {
        var pub = {};
        pub.AddItem = function (id, size, quantity, callBack) {
            $.ajax({
                url: webServiceUrl + "AddToBasket",
                type: 'POST',
                data: "{ 'productId': " + id + ", 'size': '" + size + "', 'quantity': " + quantity + "}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        };
        pub.RemoveItem = function (id, callBack) {
            $.ajax({
                url: webServiceUrl + "RemoveFromBasket",
                type: 'POST',
                data: "{ 'productId': " + id + " }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });

        };
        pub.GetCurrent = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetBasket",
                type: 'POST',
                data: "{ 'dummy': " + 0 + " }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        };
        pub.AddDiscountCode = function (discountCode, callBack) {
            $.ajax({
                url: webServiceUrl + "AddDiscountCode",
                type: 'POST',
                data: "{ 'discountCode': '" + discountCode + "' }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        return pub;
    };
    namespace.User = function () {
        var pub = {};
        pub.Login = function (username, password, callBack) {
            $.ajax({
                url: webServiceUrl + "Login",
                type: 'POST',
                data: "{ 'username': '" + username + "', 'password': '" + password + "' }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.Logout = function (callBack) {
            $.ajax({
                url: webServiceUrl + "Logout",
                type: 'POST',
                data: "{ 'logout': 'true' }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.GetInfo = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetUserInfo",
                type: 'POST',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.SendNewPassword = function (email, callBack) {
            $.ajax({
                url: webServiceUrl + "SendCustomerNewPassword",
                type: 'POST',
                data: "{ 'email': '" + email + "' }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.CheckLojalBonus = function (customerID, callBack) {
            $.ajax({
                url: webServiceUrl + "CheckLojalBonus",
                type: 'POST',
                data: "{ 'customerID': '" + customerID + "' }",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        return pub;
    }

    namespace.Store = function () {
        var pub = {};
        pub.GetAll = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetStores",
                type: 'POST',
                data: "{ 'id':'0'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.GetFromCountryCode = function (countryCode, callBack) {
            $.ajax({
                url: webServiceUrl + "GetStoresFromCountryCode",
                type: 'POST',
                data: "{ 'countryCode':'" + countryCode + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.GetFromProductId = function (productId, callBack) {
            $.ajax({
                url: webServiceUrl + "GetStoresByProduct",
                type: 'POST',
                data: "{ 'productId':'" + productId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        };

        return pub;
    }
    namespace.Product = function () {
        var pub = {};
        pub.filters = [];

        pub.GetOtherPopularProducts = function (productId, callBack) {
            $.ajax({
                url: webServiceUrl + "GetOtherPopularProducts",
                type: 'POST',
                data: "{ 'productId':'" + productId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.ApplyFilter = function (filter, value) {
            pub.filters.push({ "filter": filter, "value": value });
        }

        pub.ClearFilter = function () {
            pub.filters = [];
        }

        pub.SearchWithFilter = function (callBack) {
            $.ajax({
                url: webServiceUrl + "ApplySearchFilter",
                type: 'POST',
                data: "{'searchFiltersJson':'" + JSON.stringify(pub.filters) + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        /*
        pub.ApplyFilter = function (filter, value, callBack) {
        $.ajax({
        url: webServiceUrl + "ApplySearchFilter",
        type: 'POST',
        data: "{ 'filter':'" + filter + "', 'value':'" + value + "'}",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: callBack
        });
        }
        */
        pub.Filter = function (pageId, callBack) {
            $.ajax({
                url: webServiceUrl + "FilterProducts",
                type: 'POST',
                data: "{ 'pageId':'" + pageId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.SendToMobile = function (number, productId, callBack) {
            $.ajax({
                url: webServiceUrl + "SendToMobile",
                type: 'POST',
                data: "{ 'number':'" + number + "', 'productId':'" + productId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.RegisterReminder = function (email, productId, callBack) {
            $.ajax({
                url: webServiceUrl + "RegisterReminder",
                type: 'POST',
                data: "{ 'email':'" + email + "', 'productId':'" + productId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.GetStock = function (productId, storeId, callBack) {
            $.ajax({
                url: webServiceUrl + "GetStockFromStoreAndProduct",
                type: 'POST',
                data: "{ 'productId':'" + productId + "', 'storeId':'" + storeId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });

        }
        pub.ApplySort = function (filter, elem) {
            if ($(elem).attr("class") == "sortasc") {
                pub.filters.push({ "filter": filter, "value": "asc" });
            }
            else {
                pub.filters.push({ "filter": filter, "value": "desc" });
            }
        }

        pub.SendTipsToFriend = function (nameFrom, emailFrom, nameTo, emailTo, message, productId, callBack) {
            var postObj = { nameFrom: nameFrom, emailFrom: emailFrom, nameTo: nameTo, emailTo: emailTo, message: message, productId: productId };
            var postJson = JSON.stringify(postObj);
            $.ajax({
                url: webServiceUrl + "SendTipsToFriend",
                type: 'POST',
                data: postJson, //"{ 'productId':'" + productId + "', 'storeId':'" + storeId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }

        pub.GetFavoritesFromCookie = function () {
            var cookieObj = NG.Cookie();
            var currentFavString = cookieObj.GetCookie("DSFavorites");
            var favorites = [];
            if (currentFavString != null && currentFavString != "") {
                favorites = currentFavString.split(',');
            }
            return favorites;
        };

        pub.ToggleFavorite = function (productId, callBack, context) {

            $.ajax({
                url: webServiceUrl + "ToggleFavoriteProduct",
                type: 'POST',
                data: "{ 'productId':'" + productId + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });

        }
        pub.GetFavoriteProducts = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetFavoriteProducts",
                type: 'POST',
                data: "",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        return pub;
    }
    namespace.Group = function () {
        var pub = {};
        pub.GetGroupByHeadGroup = function (headGroup, callBack) {
            $.ajax({
                url: webServiceUrl + "GetGroupByHeadGroup",
                type: 'POST',
                data: "{ 'headGroup':'" + headGroup + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.GetSizeByHeadGroup = function (headGroup, callBack) {
            $.ajax({
                url: webServiceUrl + "GetSizeByHeadGroup",
                type: 'POST',
                data: "{ 'headGroup':'" + headGroup + "'}",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        pub.GetColors = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetColors",
                type: 'POST',
                data: "",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        return pub;
    }
    namespace.Magazine = function () {
        var pub = {};
        pub.Get = function (callBack) {
            $.ajax({
                url: webServiceUrl + "GetMagazineCovers",
                type: 'POST',
                data: "",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: callBack
            });
        }
        return pub;
    }
    return namespace;
} ();

var _tmplCache = {}
this.parseTemplate = function (str, data) {
    /// <summary>
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            //                        str
            //                  .replace(/[\r\t\n]/g, " ")
            //                  .split("<#").join("\t")
            //                  .replace(/((^|#>)[^\t]*)'/g, "$1\r")
            //                  .replace(/\t=(.*?)#>/g, "',$1,'")
            //                  .split("\t").join("');")
            //                  .split("#>").join("p.push('")
            //                  .split("\r").join("\\'") + "');}return p.join('');";

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
}
