(function ($) {
    $.sc_version = "2.0";
    $.config = function (x) {
        var config = {
            defaultCurrency: "$"
        };
        return config[x]
    };
    $.debug = function (message) {
        if (this.customFunc != null) {
            customDebugFunc(message);
            return
        }
        alert(message)
    };
    $.debug.customFunc = null;
    $.sprintf = function (format) {
        var argv = Array.apply(null, arguments).slice(1);
        return format.replace(reStringFormat, dispatchStringFormat(argv))
    };
    $.vsprintf = function (format, data) {
        return format.replace(re, dispatchStringFormat(data))
    };
    $.toCamelCase = function (data) {
        if (data != null && data.indexOf("-") > 0) {
            var parts = data.split("-"),
                x = parts[0];
            for (i = 1; i < parts.length; i++) x += parts[i].substr(0, 1).toUpperCase() + parts[i].substr(1).toLowerCase();
            return x
        }
        return data
    };
    $.startWith = function (str, x) {
        if (str == null) return false;
        return str.match("^" + x) == x
    };
    $.endWith = function (str, x) {
        if (str == null) return false;
        return str.match(x + "$") == x
    };
    $.toPrice = function (x, currency) {
        if (x) {
            x = $.forceFloat(x).toFixed(2).toString();
            for (var intEnd = x.indexOf(".") - 3, i = intEnd, j = 0; i > j; i -= 3) x = x.substring(0, i) + "," + x.substring(i, x.length);
            x = x
        } else x = "0.00";
        if (!currency || $.typeOf(currency) !== "string") currency = $.config("defaultCurrency");
        return currency + x
    };
    $.stripHtml = function (x) {
        var tmp = "";
        if (x && $.typeOf(x) === "string") tmp = x.replace(/\<\/?[^\>]+\>/g, "");
        return tmp
    };
    $.cleanHtml = function (x) {
        var tmp = "";
        if (x && $.typeOf(x) === "string") tmp = x.replace(/\<(?!br|\/?ul|\/?ol|\/?li|\/?dl|\/?dd|\/?dt|\/?p|\/?b|\/?i|\/?em|\/?strong)(?:\s.*?)?\>/ig, " ");
        return tmp
    };
    $.isEmail = function (x) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(x)) return true;
        return false
    };
    $.isPositiveInt = function (x) {
        var regex = /^[0-9]+$/;
        if (x.match(regex)) return true;
        else return false
    };
    $.isFloat = function (x) {
        return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(x)
    };
    $.isPrice = function (x) {
        var s = x.replace(/\$/gi, "");
        return $.isFloat(s)
    };
    $.isEmptyString = function (str) {
        if (str == null || str == "") return true;
        return false
    };
    $.dimScreen = function (speed, opacity, callback) {
        if ($("#__dimScreen").size() > 0) return;
        if (typeof speed == "function") {
            callback = speed;
            speed = null
        }
        if (typeof opacity == "function") {
            callback = opacity;
            opacity = null
        }
        if (speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder
        }
        if (opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder
        }
        speed = speed > 0 ? speed : 500;
        opacity = opacity > 0 ? opacity : .5;
        return $("<div></div>").attr({
            id: "__dimScreen",
            fade_opacity: opacity,
            speed: speed
        }).css({
            background: "#000",
            height: "100%",
            left: $(window).scrollLeft() + "px",
            opacity: 0,
            position: "absolute",
            top: $(window).scrollTop() + "px",
            width: "100%",
            zIndex: 999
        }).appendTo(document.body).fadeTo(speed, opacity, callback)
    };
    $.dimScreenStop = function (callback) {
        var x = $("#__dimScreen"),
            opacity = x.attr("fade_opacity"),
            speed = x.attr("speed");
        x.fadeOut(speed, function () {
            x.remove();
            typeof callback == "function" && callback()
        })
    };
    $.buildUrl = function (domain, page, params, path, protocol) {
        if (domain == null) return null;
        var ps = "",
            addQ = page.indexOf("?") == -1;
        if (params != null) {
            for (var x in params) {
                if (ps != "") ps = ps + "&";
                ps = ps + escape(x) + "=" + escape(params[x])
            }
            if (addQ) ps = "?" + ps
        }
        return (protocol != null ? protocol : window.location.protocol) + "//" + domain + "/" + (path != null ? path + "/" : "") + page + ps
    };
    $.urlParam = function (name, url) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)",
            regex = new RegExp(regexS),
            results = regex.exec(url == undefined || url == null ? window.location.href : url);
        if (results == null) return null;
        else return results[1]
    };
    $.cookie = function (name, value, options) {
        if (typeof value != "undefined") {
            options = options || {};
            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 * 1e3)
                } else date = options.expires;
                expires = "; expires=" + date.toUTCString()
            }
            var path = options.path ? "; path=" + options.path : "",
                domain = options.domain ? "; domain=" + options.domain : "",
                secure = options.secure ? "; secure" : "";
            document.cookie = [name, "=", encodeURIComponent(value), expires, path, domain, secure].join("")
        } else {
            var cookieValue = null;
            if (document.cookie && document.cookie != "") for (var cookies = document.cookie.split(";"), i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == name + "=") {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break
                }
            }
            return cookieValue
        }
    };
	
	$.trim = function(x) {
		if (x==null || x==undefined) return null;
		return x.replace(/^\s+|\s+$/, ''); 
	}
	
    $.inFrame = function () {
        if (window.parent !== window.self) return true;
        return false
    };
    $.forceFloat = function (x) {
        return isNaN(x = parseFloat($.typeOf(x) === "string" ? x.replace(/\,/g, "").replace(/^.*?([\+\-]?[\d\.]+).*?$/, "$1") : x)) ? 0 : x
    };
    $.forceInt = function (x) {
        return isNaN(x = parseInt($.typeOf(x) === "string" ? x.replace(/\,/g, "").replace(/^.*?([\+\-]?[\d\.]+).*?$/, "$1") : x)) ? 0 : x
    };
    $.typeOf = function (x) {
        var str = typeof x;
        if (str === "object") if (x) {
            if (x.nodeType === 1) str = "html";
            else if (x instanceof Array) str = "array";
            else if (x instanceof Date) str = "date"
        } else str = "null";
        return str
    };
    $.toJSON = function (v) {
        var f = isNaN(v) ? sJSON[typeof v] : sJSON["number"];
        if (f) return f(v)
    };
    $.parseJSON = function (v, safe) {
        if (safe === undefined) safe = $.parseJSON.safe;
        if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v)) return undefined;
        return eval("(" + v + ")")
    };
    $.parseJSON.safe = false;
    var fStringFormat = {
        "%": function (val) {
            return "%"
        },
        b: function (val) {
            return parseInt(val, 10).toString(2)
        },
        c: function (val) {
            return String.fromCharCode(parseInt(val, 10))
        },
        d: function (val) {
            return parseInt(val, 10) ? parseInt(val, 10) : 0
        },
        u: function (val) {
            return Math.abs(val)
        },
        f: function (val, p) {
            return p > -1 ? Math.round(parseFloat(val) * Math.pow(10, p)) / Math.pow(10, p) : parseFloat(val)
        },
        o: function (val) {
            return parseInt(val, 10).toString(8)
        },
        s: function (val) {
            return val
        },
        x: function (val) {
            return ("" + parseInt(val, 10).toString(16)).toLowerCase()
        },
        X: function (val) {
            return ("" + parseInt(val, 10).toString(16)).toUpperCase()
        }
    },
        reStringFormat = /%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g,
        dispatchStringFormat = function (data) {
            if (data.length == 1 && typeof data[0] == "object") {
                data = data[0];
                return function (match, w, p, lbl, fmt, off, str) {
                    return fStringFormat[fmt](data[lbl])
                }
            } else {
                var idx = 0;
                return function (match, w, p, lbl, fmt, off, str) {
                    return fStringFormat[fmt](data[idx++], p)
                }
            }
        },
        mJSON = {
            "\b": "\\b",
            "\t": "\\t",
            "\n": "\\n",
            "\f": "\\f",
            "\r": "\\r",
            '"': '\\"',
            "\\": "\\\\"
        },
        sJSON = {
            array: function (x) {
                for (var a = ["["], b, f, l = x.length, v, i = 0; i < l; i += 1) {
                    v = x[i];
                    f = sJSON[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == "string") {
                            if (b) a[a.length] = ",";
                            a[a.length] = v;
                            b = true
                        }
                    }
                }
                a[a.length] = "]";
                return a.join("")
            },
            "boolean": function (x) {
                return String(x)
            },
            "null": function (x) {
                return "null"
            },
            number: function (x) {
                return isFinite(x) ? String(x) : "null"
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) return sJSON.array(x);
                    var a = ["{"],
                        b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = sJSON[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == "string") {
                                if (b) a[a.length] = ",";
                                a.push(sJSON.string(i), ":", v);
                                b = true
                            }
                        }
                    }
                    a[a.length] = "}";
                    return a.join("")
                }
                return "null"
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) x = x.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                    var c = mJSON[b];
                    if (c) return c;
                    c = b.charCodeAt();
                    return "\\u00" + Math.floor(c / 16).toString(16) + (c % 16).toString(16)
                });
                return '"' + x + '"'
            }
        };
    $.template = function (html, options) {
        return new $.template.instance(html, options)
    };
    $.template.instance = function (html, options) {
        if (options && options["regx"]) options.regx = this.regx[options.regx];
        this.options = $.extend({
            compile: false,
            regx: this.regx.standard
        }, options || {});
        this.html = html;
        this.options.compile && this.compile();
        this.isTemplate = true
    };
    $.template.regx = $.template.instance.prototype.regx = {
        jsp: /\$\{([\w\.-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        ext: /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        jtemplates: /\{\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}\}/g
    };
    $.template.regx.standard = $.template.regx.jsp;
    $.template.helpers = $.template.instance.prototype.helpers = {
        substr: function (value, start, length) {
            return String(value).substr(start, length)
        },
        toPrice: function (value) {
            return $.toPrice(value)
        }
    };
    $.extend($.template.instance.prototype, {
        apply: function (values) {
            if (this.options.compile) return this.compiled(values);
            else {
                var tpl = this,
                    fm = this.helpers,
                    fn = function (m, name, format, args) {
                        if (format) if (format.substr(0, 5) == "this.") return tpl.call(format.substr(5), values[name], values);
                        else {
                            if (args) {
                                var re = /^\s*['"](.*)["']\s*$/;
                                args = args.split(",");
                                for (var i = 0, len = args.length; i < len; i++) if (args[i] == "this") args[i] = values;
                                else if (args[i].substr(0, 5) == "this.") {
                                    for (var v = args[i].substr(5), vs = v.split("."), ob = values, b = true, j = 0; j < vs.length; j++) {
                                        ob = ob[vs[j]];
                                        if (ob == undefined) {
                                            args[i] = null;
                                            b = false;
                                            break
                                        }
                                    }
                                    if (b) args[i] = ob
                                } else args[i] = args[i].replace(re, "$1");
                                args = [values[name]].concat(args)
                            } else args = [values[name]];
                            return fm[format].apply(fm, args)
                        } else {
                            if (values == undefined) return "";
                            for (var vs = name.split("."), ob = values, i = 0; i < vs.length; i++) {
                                ob = ob[vs[i]];
                                if (ob == undefined) return ""
                            }
                            return ob
                        }
                    };
                return this.html.replace(this.options.regx, fn)
            }
        },
        compile: function () {
            var sep = $.browser.mozilla ? "+" : ",",
                fm = this.helpers,
                fn = function (m, name, format, args) {
                    if (format) {
                        args = args ? "," + args : "";
                        if (format.substr(0, 5) != "this.") format = "fm." + format + "(";
                        else {
                            format = 'this.call("' + format.substr(5) + '", ';
                            args = ", values"
                        }
                    } else {
                        args = "";
                        format = "(values['" + name + "'] == undefined ? '' : "
                    }
                    return "'" + sep + format + "values['" + name + "']" + args + ")" + sep + "'"
                },
                body;
            if ($.browser.mozilla) body = "this.compiled = function(values){ return '" + this.html.replace(/\\/g, "\\\\").replace(/(\r\n|\n)/g, "\\n").replace(/'/g, "\\'").replace(this.options.regx, fn) + "';};";
            else {
                body = ["this.compiled = function(values){ return ['"];
                body.push(this.html.replace(/\\/g, "\\\\").replace(/(\r\n|\n)/g, "\\n").replace(/'/g, "\\'").replace(this.options.regx, fn));
                body.push("'].join('');};");
                body = body.join("")
            }
            eval(body);
            return this
        }
    });
    var $_old_functions = {
        domManip: $.fn.domManip,
        text: $.fn.text,
        html: $.fn.html
    };
    $.fn.domManip = function (args, table, reverse, callback) {
        if (args[0] != null && args[0].isTemplate) {
            args[0] = args[0].apply(args[1]);
            delete args[1]
        }
        var r = $_old_functions.domManip.apply(this, arguments);
        return r
    };
    $.fn.html = function (value, o) {
        if (value && value.isTemplate) var value = value.apply(o);
        var r = $_old_functions.html.apply(this, [value]);
        return r
    };
    $.fn.text = function (value, o) {
        if (value && value.isTemplate) var value = value.apply(o);
        var r = $_old_functions.text.apply(this, [value]);
        return r
    };
    $.fn.domElement = function () {
        if (this.length > 0) return this[0];
        return null
    };
    $.sc = function () {};
    $.sc.modules = [];
    $.sc.registerModule = function (name, version) {
        $.sc.modules[name] = version
    };
    $.sc.hasModule = function (name) {
        for (x in $.sc.modules) if (x == name) return $.sc.modules[x];
        return false
    };
    $.sc.callbacks = [];
    $.sc.runCallback = function (callback, data) {
        var name = null;
        if (callback.indexOf(":") > 0) {
            var a = callback.split(":", 2);
            callback = a[0];
            name = a[1]
        }
        var fs = $.sc.callbacks[callback];
        if (fs != null) for (var x in fs)(name == null || x == name) && fs[x](data)
    };
    $.sc.addCallback = function (callback, name, func) {
        if ($.sc.callbacks[callback] == null) $.sc.callbacks[callback] = [];
        $.sc.callbacks[callback][name] = func
    };
    $.yahoo = function () {
        this.version = "1.0";
        $.sc && $.sc.registerModule("yahoo", "1.0");
        this.pageId = null;
        this.storeId = null;
        this.storeParams = null;
        this.personalization = null
    };
    $.yahoo.setStoreId = function (storeId) {
        $.yahoo.storeId = storeId
    };
    $.yahoo.setPageId = function (pageId) {
        $.yahoo.pageId = pageId
    };
    $.yahoo.setPersonalization = function (value) {
        $.yahoo.personalization = $.toPrice(value)
    };
    $.yahoo.setStoreParams = function (storeParams) {
        $.yahoo.storeParams = storeParams;
        if (this.storeId) {
            function scdecrypt(arr, base) {
                var tmpStr = "";
                for (x = 0, j = 3, k = 2, fib = 1; x < arr.length; x++, fib = j + k, k = j, j = fib) tmpStr += String.fromCharCode(arr[x] - fib - base);
                return tmpStr
            }
            var caresParam1, caresParam2;
            for (i in storeParams) if (typeof storeParams[i] != "function") {
                caresParam1 = i;
                caresParam2 = storeParams[i]
            }
            var str = this.storeId,
                flag = str.length % 2 == 0 ? false : true,
                chkStr1 = scdecrypt(caresParam1.split("|"), 20),
                chkStr2 = scdecrypt(caresParam2.split("|"), 8),
                chkStr = flag ? chkStr1.substring(0, chkStr1.length - 1) + chkStr2 : chkStr1 + chkStr2;
            $.yahoo.stCk = chkStr == str ? true : false
        }
    };
    $.yahoo.stCk = false;
    $.yahoo.getCartUrl = function () {
        $.yahoo.storeId = "https://order.store.yahoo.net/cgi-bin/wg-order?" + this.storeId
    };
    $.yahoo.getAddToCartFormAction = function () {
        return "http://order.store.yahoo.net/" + this.storeId + "/cgi-bin/wg-order?" + this.storeId
    };
    $.yahoo.hexEncode = function (str) {
        var tmp = "";
        if ($.typeOf(str) === "string") {
            for (var hxMp = "0123456789ABCDEF", i = 0, j = str.length; i < j; i++) {
                tmp += hxMp.charAt(str.charCodeAt(i) / 16);
                tmp += hxMp.charAt(str.charCodeAt(i) % 16)
            }
            hxMp = null
        }
        return tmp
    };
    $.yahoo.inEditor = function () {
        var u = window.document.location.url;
        if (u.indexOf("edit.store.yahoo.net/RT/") > 0 || u.indexOf("edit.store.yahoo.com/P/COMGR/") > 0) return true;
        return false
    };
    $.yahoo.getItem = function (site, options) {
        if (options.id == null) return null;
        try {
            $.get(site.domain ? $.buildUrl(site.domain, options.id + ".html") : options.id + ".html", options, function (data) {
                var captionMatch = null,
                    info = null;
                if (data != null) {
                    var infoMatch = data.match(/\<\!\-\-sc\-tag\-start ((?:.|\n|\r)*?) sc\-tag\-end\-\-\>/);
                    if (infoMatch) {
                        info = $.parseJSON(infoMatch[1]);
                        info.name = $.cleanHtml(info.name);
                        captionMatch = data.match(/\<\!\-\-sc\-caption\-start\-\-\>((?:.|\n|\r)*?)\<\!\-\-sc\-caption\-end\-\-\>/);
                        if (captionMatch) info.caption = $.cleanHtml(captionMatch[1])
                    }
                }
                var callback = $.urlParam("callback", this.url);
                if (callback != null) try {
                    eval("var callback_func=" + callback);
                    callback_func(info, data)
                } catch (e1) {}
                $.sc.runCallback("parsedItem", info)
            }, options.type)
        } catch (e) {}
    };
    $.yahoo.getCart = function (site, options) {
        $("body").createAppend("iframe", {
            src: site.cartUrl,
            style: "display:block;width:300px;height:300px;border:0px;"
        })
    };
    $.yahoo.parseCart = function (parseHtml) {
        var cart = {};
        $("#ys_cart table.ys_basket tr").each(function (pos) {
            if (this.className == "ys_evenRow" || this.className == "ys_oddRow") {
                if (cart.items == null) cart.items = [];
                var cartItem = {};
                cartItem.number = cart.items.length;
                cart.items.push(cartItem);
                $("td.ys_items span.ys_itemInfo a:first", this).each(function () {
                    cartItem.name = this.innerHtml;
                    cartItem.url = this.href;
                    if (cartItem.url != null) cartItem.id = cartItem.url.substring(cartItem.url.lastIndexOf("/") + 1).replace(/\.html/gi, "")
                });
                cartItem.qty = $.forceInt($("td.ys_quantity input:text:first", this).val());
                cartItem.image = $("td.ys_items span.ys_itemImg img:first", this).attr("src");
                $("td.ys_options ul li", this).each(function () {
                    if (cartItem.options == null) cartItem.options = [];
                    var html = this.innerHTML.split(":", 2);
                    cartItem.options[html[0]] = html.length == 2 ? html[1] : ""
                });
                cartItem.price = $.forceFloat($("td.ys_unitPrice", this).html());
                cartItem.inStock = $("td.ys_inStock:first", this).html().toLowerCase() === "yes"
            } else if ($(this).hasClass("ys_orderLine")) {
                var vx = $.forceFloat($("td.ys_last:first", this).html());
                if ($(this).html().indexOf("Shipping:") >= 0) cart.shipRate = vx;
                if ($(this).html().indexOf("Tax:") >= 0) cart.taxRate = vx;
                if ($(this).html().indexOf("Total:") >= 0) cart.total = vx;
                if ($(this).html().indexOf("Subtotal:") >= 0) cart.subtotal = vx;
                if ($(this).html().indexOf("Discount:") >= 0) cart.discount = vx
            }
        });
        cart.shipZip = $("#shipping-zip").val();
        cart.shipState = $("#shipping-state-for-shipping-calculator").val();
        cart.shipCountry = $("#shipping-country option:selected").val();
        cart.shipMethod = $("#merchant-selected-shipping-methods option:selected").val();
        return cart
    }
})(jQuery)
