﻿(function () {
    Array.prototype.indexOf || (Array.prototype.indexOf = function (value) {
        for (var i in this) {
            if (this[i] == value) {
                return i;
            }
        }

        return -1;
    });

    Array.prototype.remove = function (b) {
        var a = this.indexOf(b);
        if (a >= 0) {
            this.splice(a, 1);
            return true;
        }
        return false;
    };

    window.jlUtil = {
        getJSON: function (obj, skip_arr) {
            if (typeof obj == "number"
		    || typeof obj == "boolean") {
                return obj;
            } else if (typeof obj == "string") {
                return "'" + obj.replace(/'/g, "\\'") + "'";
            } else if (!obj) {
                return "''";
            }

            var json = [];
            skip_arr = skip_arr ? skip_arr : [];
            for (var key in obj) {
                //skip function and the keys in skip arr
                if (typeof obj[key] == "function"
			     || skip_arr.indexOf(key) != -1) {
                    continue;
                }

                //in Array loop
                if (!isNaN(key) || key.constructor != String) {
                    json.push(jlUtil.getJSON(obj[key], skip_arr));
                    continue;
                }
                //else recurrency
                json.push("'" + key + "':" + jlUtil.getJSON(obj[key], skip_arr));
            }
            if (Object.prototype.toString.apply(obj) === '[object Array]') {
                return "[" + json.join(",") + "]";
            } else {
                return "{" + json.join(",") + "}";
            }
        },
        extend: function (obj) {
            if (arguments.length == 1) {
                this.extend(this, obj);
                return this;
            } else if (arguments.length >= 2) {
                var dst = arguments[0];
                //extend the rest args to args[0]
                for (var i = 1; i < arguments.length; ++i) {
                    for (var item in arguments[i]) {
                        var tmp = arguments[i][item];
                        if (typeof arguments[i][item] == "object") {
                            //make a copy while is a object, needs jQuery here
                            var tmp = $.extend({}, arguments[i][item]);
                        }
                        //if is object try recurrency
                        if (dst[item] && typeof dst[item] == "object") {
                            try {
                                this.extend(dst[item], tmp);
                            } catch (e) {
                                dst[item] = tmp;
                            }
                        } else {
                            dst[item] = tmp;
                        }
                    }
                }
                return dst;
            }
        }
    };

    jQuery.cookie = function (name, value, options) {
        if (typeof value != 'undefined') {
            options = options || { "expires": 30, "path": "/" };
            if (value === null) {
                value = '';
                options = $.extend({}, options);
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString();
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookieValue = null;
            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;
        }
    };

    window.Wish = function (Answer, OptionLast, Comment) {
        this.Answer = Answer;
        this.OptionLastInput = OptionLast;
        this.AdditionalComment = Comment;
    }

    window.Wishes = {};
    window.PushWish = function (wishId, wish, callback) {
        var wishStr = jlUtil.getJSON(wish);
        $.get("/c-rootsite/Builtin_WishSave",
            {
                "wishId": wishId,
                "wishAnswer": wishStr
            },
            function (data) {
                if (data != "0") {
                    wish.UUID = data;
                }
                Wishes = GetWishs();
                Wishes[wishId] = wish;
                wishStr = jlUtil.getJSON(Wishes);
                $.cookie("wishes", wishStr);
                callback && callback();
            }
        );
    }

    window.GetWish = function (wishId) {
        Wishes = GetWishs();
        return Wishes[wishId];
    }

    window.GetWishs = function () {
        var wishes = $.cookie("wishes");
        if (wishes) {
            var obj = (new Function("return " + wishes + ";"))();
            return obj;
        } else {
            return {};
        }
    }

    window.RemoveWish = function (wishId, callback) {
        Wishes = GetWishs();
        $.get("/c-rootsite/Builtin_WishSave",
        {
            "delete": "true",
            "wishId": wishId
        },
        function (data) {
            delete Wishes[wishId];
            $.cookie("wishes", jlUtil.getJSON(Wishes));
            callback && callback();
            return;
        });
    }

    window.CustProducts = {};
    window.PushCustProduct = function (groupId, text, callback) {
        $.get("/c-rootsite/Builtin_WishSave",
            {
                "groupId": groupId,
                "text": text
            },
            function (data) {
                var custProducts = GetCustProducts();
                custProducts[groupId] = text;
                var str = jlUtil.getJSON(custProducts);
                $.cookie("custProducts", str);
                callback && callback();
            }
        );
    }
    window.GetCustProducts = function () {
        var str = $.cookie("custProducts");
        if (str)
            return (new Function("return " + str + ";"))();
        else
            return {};
    }
    window.RemoveCustProduct = function (groupId, callback) {
        var custProducts = GetCustProducts();
        $.get("/c-rootsite/Builtin_WishSave",
        {
            "delete": "true",
            "groupId": groupId
        },
        function (data) {
            delete custProducts[groupId];
            $.cookie("custProducts", jlUtil.getJSON(custProducts));
            callback && callback();
        });
    }


    window.StaticQuestions = {};
    window.PushStaticQuestion = function (staticQuestionId, staticQuestion, callback) {
        var staticQuestionStr = jlUtil.getJSON(staticQuestion);
        $.get("/c-rootsite/Builtin_WishSave",
            {
                "staticQuestionId": staticQuestionId,
                "staticQuestionAnswer": staticQuestionStr
            },
            function (data) {
                if (data != "0") {
                    staticQuestion.UUID = data;
                }
                StaticQuestions = GetStaticQuestions();
                StaticQuestions[staticQuestionId] = staticQuestion;
                staticQuestionStr = jlUtil.getJSON(StaticQuestions);
                $.cookie("staticQuestions", staticQuestionStr);
                callback && callback();
            }
        );
    }
    window.GetStaticQuestion = function (staticQuestionId) {
        StaticQuestions = GetStaticQuestions();
        return StaticQuestions[staticQuestionId];
    }
    window.GetStaticQuestions = function () {
        var StaticQuestions = $.cookie("staticQuestions");
        if (StaticQuestions) {
            return (new Function("return " + StaticQuestions + ";"))();
        } else {
            return {};
        }
    }
    window.RemoveStaticQuestion = function (staticQuestionId, callback) {
        StaticQuestions = GetStaticQuestions();
        $.get("/c-rootsite/Builtin_WishSave",
        {
            "delete": "true",
            "staticQuestionId": staticQuestionId
        },
        function (data) {
            delete StaticQuestions[staticQuestionId];
            $.cookie("staticQuestions", jlUtil.getJSON(StaticQuestions));
            callback && callback();
            return;
        });
    }

    window.SelectedProducts = [];
    window.MemberProducts = {};
    window.PushProduct = function (productId, callback) {
        $.get("/c-rootsite/Builtin_WishSave",
            { "productId": productId },
            function (data) {
                if (data != "0") {
                    MemberProducts[productId] = data;
                }
                SelectedProducts = GetProducts();
                if (SelectedProducts.indexOf(productId) < 0) {
                    SelectedProducts.push(productId);
                    $.cookie("products", SelectedProducts.join(","));
                    callback && callback();
                }
            }
        );
    }

    window.GetProducts = function () {
        var products = $.cookie("products");
        if (products) {
            return products.split(",");
        } else {
            return [];
        }
    }

    window.RemoveProduct = function (productId, callback) {
        $.get("/c-rootsite/Builtin_WishSave",
        {
            "delete": "true",
            "memberProductId": productId
        },
        function (data) {
            SelectedProducts = GetProducts();
            SelectedProducts.remove(productId);
            $.cookie("products", SelectedProducts.join(","));
            callback && callback();
        });
    }

    window.GetWishType = function () {
        var wishType = $.cookie('wishType');
        return wishType;
    }

    window.GetLocation = function () {
        var location = $.cookie('location');
        return location;
    }
})();


