﻿/**
* jQuery is required
*/

var offers = [
//added for test
{
"id": "free-overnight-shipping",
"from": "2011-12-16T00:00-05:00",
"to": "2011-12-21T23:59-05:00",
"priority": 0,
"type": "free-overnight-shipping",
"code": "holiday",
"successText": "You qualify for FREE guaranteed shipping.",
"offerText": "You qualify for FREE guaranteed shipping",
"minPurchase": 0
}

];


//Get active offer for Today EST

//on Document load replace assets images as neded

var offerApi = function (_offers) {
    // 
    if (!_offers) return {};
    //private stuff
    var offers = _offers;

    function get_active_offers() {
        var offerList = [];
        for (var i in offers) {
            var o = offers[i];
            var from = parseDate(o.from);
            var to = parseDate(o.to);
            var now = new Date();
            if (from.getTime() < now.getTime() && now.getTime() < to.getTime()) {
                //Offer is active
                offerList.push(o);
            }
        }
        return offerList;
    }

    function parseDate(s) {
        if (navigator.userAgent.indexOf("MSIE") > -1) {

        }

        var a = s.split("T");
        var y = a[0].replace(/-/g, "/");
        //only for  - gmt
        var b = a[1].split("-");
        var h = b[0];
        var tz = b[1].replace(":", "");
        var s = y + " " + h + " GMT-" + tz;

        var t = Date.parse(s);
        return new Date(t);

    }

    function is_gwp(sku) {
        var activeOffers = get_active_offers();
        var b = false;
        for (var i in activeOffers) {
            var o = activeOffers[i];
            if (o.type == "gwp" && o.sku == sku) {
                b = true;
                break;
            }
            else if (o.type == "gwp-select" && o.sku == sku) {
                b = true;
                break;
            }
        }
        return b;
    }

    function get_applied_offers(_st) {
        var subtotal = _st;
        var activeOffers = get_active_offers();
        var temp_offer_list = [];
        var offerList = [];
        //get Discount if
        var d = 1;
        var min_p = 0;
        for (var i in activeOffers) {
            var o = activeOffers[i];
            if (o.type == "discount") {
                if (o.code) {
                    var cc = url_decode(get_cookie("couponCodes"));
                    if (cc) {
                        var c = cc.couponCodes.split(",");
                        var b = false;
                        for (var j in c) {
                            var enteredCode = c[j];
                            if (o.code == enteredCode) {
                                d = 1 - o.amount;
                                break;
                            }
                        }
                    }
                }
                else if (!o.minPurchase || o.minPurchase <= subtotal) {
                    d = 1 - o.amount;
                }
                break;
            }
        }
        for (var i in activeOffers) {
            var o = activeOffers[i];

            if (!o.code && (!o.minPurchase || o.minPurchase <= (subtotal * d))) {
                temp_offer_list.push(o);
            }
            else if (o.code && (!o.minPurchase || o.minPurchase <= (subtotal * d))) {
                //check for code cookies
                var cc = url_decode(get_cookie("couponCodes"));
                if (cc) {
                    var c = cc.couponCodes.split(",");
                    var b = false;
                    for (var j in c) {
                        var enteredCode = c[j];
                        if (o.code == enteredCode) {
                            temp_offer_list.push(o);
                        }
                    }
                }
            }
        }

        //offerList
        var pp = url_decode(get_cookie("priority"));
        if (pp && o.hasOwnProperty("priority") && typeof pp.priority == "string") {
            pp.priority = parseInt(pp.priority);
        }
        if (pp && o.hasOwnProperty("priority") && pp.priority != 0) {
            for (var i in temp_offer_list) {
                var o = temp_offer_list[i];
                if (o.hasOwnProperty("priority") && (o.priority == 0 || o.priority == pp.priority)) {
                    offerList.push(o);
                }
            }
        }
        else {
            offerList = temp_offer_list;
        }
        return offerList;
    }


    function get_offer_by_code(_code, _st) {
        var offerList = get_active_offers(_st);
        for (var i in offerList) {
            var o = offerList[i];
            if (o.code == _code) {
                return o;
            }
        }
        return null;
    }


    /**
    * 
    * @param {string} c_name
    */
    function delete_cookie(c_name) {
        set_cookie(c_name, "", -(1000 * 60 * 60 * 24));
    }

    /**
    * 
    * @param {string} c_name
    * @param {string} update
    * @param {?number=} [alive]
    */
    function update_cookie(c_name, update, alive) {

        var i;
        var s;

        var value = get_cookie(c_name);
        var ps = value.split("&");
        var o = {};
        for (i in ps) {
            var ta = ps[i].split("=");
            if (!ta || ta.length < 2)
                continue;

            var p = ta[0];
            var v = ta[1];
            o[p] = v;
        }


        if (update && update != "") {
            ps = update.split("&");
            for (i in ps) {
                ta = ps[i].split("=");
                if (!ta || ta.length < 2)
                    continue;
                p = ta[0];
                v = ta[1];
                o[p] = v;
            }
        }
        value = "";
        for (s in o) {
            if (o[s] == "" || o[s] == null || o[s] == undefined) {
                continue;
            }
            value += "&" + s + "=" + o[s];
        }
        set_cookie(c_name, value, alive);
    }


    /**
    * 
    * @param {string} c_name
    * @return {string}
    */
    function get_cookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }

    /**
    * 
    * @param {string} c_name
    * @param {string} value
    * @param {?number=} [alive]
    */
    function set_cookie(c_name, value, alive) {
        var exdate;
        if (alive) {
            exdate = new Date();
            var st = exdate.getTime();
            exdate.setTime(st + alive);
        }
        document.cookie = c_name + "=" + escape(value) + (exdate ? (";expires=" + exdate.toGMTString()) : "") + "; path=/";
    }

    /**
    * @private
    * @param {Object} h
    * @return Url encoded representation of a hash table
    */
    function url_encode(h) {
        var s = "";
        for (var i in h) {
            if (typeof h[i] === "number" || typeof h[i] === "string" || typeof h[i] === "boolean")
                s += "&" + i + "=" + h[i];
            else if (typeOf(h[i]) == "array")
                s += "&" + i + "=" + h[i].join(",");
        }
        return s;
    }

    /**
    * 
    * @param {?string} s
    * @return {?Object}
    */
    function url_decode(s) {
        if (!s || typeof s != "string" || s.length == 0) return null;
        var o = null;
        var a = s.split("&");
        for (var i = 0; i < a.length; i++) {
            var p = a[i]
            if (p && p.indexOf("=") > -1) {
                var b = p.split("=");
                if (b.length == 2) {
                    if (!o) o = {};
                    o[b[0]] = b[1];
                }
            }
        }
        return o;
    }

    return {
        //expose public api here
        "getActiveOffers": get_active_offers,
        "getAppliedOffers": get_applied_offers,
        "getOfferByCode": get_offer_by_code,
        "isGwp": is_gwp,
        "setCookie": set_cookie,
        "getCookie": get_cookie,
        "urlDecode": url_decode
    }
} (offers);





$(function (e) {
    var os = offerApi.getActiveOffers();
    $("gwp-select").empty();
    var ss = offerApi.urlDecode(offerApi.getCookie("selectedGwp"));
    for (var i in os) {
        var o = os[i];
        if (o.asset1) {
            $(".special-offers-asset1").html("<a href=\"special-offers\"><img src=\"" + o.asset1 + "\" width=\"244\" height=\"84\" alt=\"special offers\" /></a>");
        }
        if (o.asset2) {
            $(".special-offers-asset2").html("<a href=\"special-offers\"><img src=\"" + o.asset2 + "\" width=\"310px\" height=\"285px\" alt=\"special offers\" /></a>");
        }

        if (o.type == "gwp-select") {
            var cx = ""
            if (ss && ss.sku && ss.sku == o.sku) {
                cx = "checked='checked'"
            }

            var ghtml = "<div class='gwp-select-item'  data-sku='" + o.sku + "' data-uid='" + o.uid + "' data-priority='" + (o.priority ? o.priority : 0) + "' style='width:241px;'><img width='240' height='240' src='/api/products/" + o.uid + ".jpg?key=" + MLC.key + "'/><div class='gwp-select-item-title'>" + o.title + "</div><div class='gwp-select-item-descr'>" + o.descr + "</div><input name='gwp-select' type='radio' " + cx + "/></div>";
            $(".gwp-select").append(ghtml);
        }

        if (o.type == "free-overnight-shipping") {
            $("#overnight").val(0);
            $("label[for=overnight]").html("<b>FREE Overnight Shipping</b>- $0.00");
            $("#overnight").attr("checked", "checked");
        }
    }
    $(".gwp-select").append("<div style='clear:both;'></div>");
    $(".gwp-select-item").click(function (e) {
        var $this = $(this);
        $("input", $this).attr("checked", true);
        offerApi.setCookie("selectedGwp", "sku=" + $this.data("sku"));
        offerApi.setCookie("priority", "priority=" + $this.data("priority"));
        getCart();
    });
});


