/*global jQuery, window, console, document */
/*jslint unparam: true, white: true, browser: true, type: true, unparam: true */

(function ($) {
    "use strict";
    var csn = window.CSN || (window.CSN = {});

    csn.queryString = function (param) {
        var result, re = new RegExp("^" + param + "=", "i"), decode = window.decodeURIComponent || unescape;
        result = $.grep(window.location.search.substring(1).split("&"), function (item) {
            return re.test(item);
        });

        switch (result.length) {
            case 1:
                return decode(result[0].split("=")[1].split(","));
            case 0:
                return "";
            default:
                return $.map(result, function (nameValue) {
                    return decode(nameValue.split("=")[1].split(","));
                });
        }
    };

    csn.formatNumber = function (format, value) {
        var result = "", i, j, c, isFloat, decimalPlaces;

        if (format && value) {
            decimalPlaces = /\.([#0]+)/.exec(format) ? RegExp.$1.length : 0;
            value = String(Number(value).toFixed(decimalPlaces));
            j = value.length - 1;
            i = format.length - 1;

            while (i >= 0) {
                c = format.charAt(i);
                switch (c) {
                    case "#":
                        if (j >= 0) {
                            result = value.charAt(j) + result;
                            j -= 1;
                        }
                        break;
                    case "0":
                        if (j >= 0) {
                            result = value.charAt(j) + result;
                            j -= 1;
                        } else {
                            result = "0" + result;
                        }

                        break;
                    case ",":
                        if (j >= 0) {
                            result = c + result;
                        }
                        if (j > 0 && i >= 1) {
                            i += 4;
                        }
                        break;
                    case ".":
                        result = c + result;
                        break;
                    default:
                        result = c + result;
                        break;
                }

                if (value.charAt(j) === ".") {
                    j -= 1;
                }
                i -= 1;
            }
        }

        if (j > 0) {
            result = value.substring(0, j + 1) + result;
        }

        return result || String(value);
    };

    csn.subCookie = function (cookieName, key, value) {
        var cookie = $.cookie(cookieName, { raw: true }) || "", subKeys = [], keyMatch, i;

        if (cookie.indexOf("=") > 0) {
            subKeys = cookie.indexOf("&") > 0 ? cookie.split("&") : [cookie];
        }

        if (typeof value === "string") {
            if (cookie.indexOf(key) !== -1) {
                for (i = subKeys.length - 1; i >= 0; i--) {
                    if (subKeys[i].indexOf(key) === 0) {
                        subKeys[i] = subKeys[i].split("=")[0] + "=" + value;
                        break;
                    }
                }
            } else {
                subKeys.push(key + "=" + value);
            }
            $.cookie(cookieName, subKeys.join("&"), { domain: window.location.hostname, path: "/", raw: true });
        } else {
            while (subKeys.length > 0) {
                keyMatch = subKeys.shift();
                if (keyMatch.indexOf(key) === 0) {
                    return keyMatch.split("=")[1];
                }
            }
            return null;
        }
    };

    csn.getTextCss = function (source) {
        var css = {};
        $.each(["padding-left", "padding-right", "margin-left", "margin-right", "font-weight", "font-style", "font-size", "font-family"], function (i, prop) {
            css[prop] = source.css(prop);
        });
        return css;
    };

    csn.addEllipsis = function (target, maxWidth) {
        var text = target.text(),
            textWidth = maxWidth || target.width(),
            clone = target.clone(true).css({ "display": "none", "word-wrap": "normal", "white-space": "pre", "visibility": "visible", "position": "absolute", "overflow": "visible", "width": "auto", "height": "auto" }),
            testWidth = function () {
                return clone.width() > textWidth;
            },
            textCss = target.data("text-css");

        if (!textCss) {
            textCss = csn.getTextCss(target);
            target.data("text-css", textCss);
        }

        clone.css(textCss).appendTo("body");
        while (text.length && testWidth()) {
            text = text.slice(0, -1);
            clone.text(text + "...");
        }
        target.text(clone.text());
        clone.remove();
    };

    (function () {
        var scriptsLoaded = {},
        loadCounter = {},
        loadCompleted = function (src, loadId) {
            scriptsLoaded[src] = true;
            loadCounter[loadId].count += 1;
            if ($.isFunction(loadCounter[loadId].callback) && loadCounter[loadId].count === loadCounter[loadId].max) {
                loadCounter[loadId].callback();
            }
        },
        loadScript = function (src, loadId) {
            var script = document.createElement("script"), timer;

            script.src = src;
            script.type = "text/javascript";
            $("head")[0].appendChild(script);

            if (($.browser.webkit && !navigator.userAgent.match(/Version\/3/)) || $.browser.opera) {
                timer = setInterval(function () {
                    if (/loaded|complete/.test(document.readyState)) {
                        clearInterval(timer);
                        loadCompleted(src, loadId);
                    }
                }, 10);
            } else {
                script.onreadystatechange = function () {
                    if (/loaded|complete/.test(script.readyState)) {
                        loadCompleted(src, loadId);
                    }
                };
                script.onload = function () {
                    loadCompleted(src, loadId);
                };
            }
        },
        adjustFileUrlCurry = function () {
            var re = /^(\$lib)?(\$jq)?(\$ui)?\/?(?:.+?)(\.js)?$/,
            paths = ["/lib", "/lib/jquery/plugins", "/lib/jquery/plugins/ui"];

            return function (jsFile) {
                var match = re.exec(jsFile);
                if (jsFile.indexOf("$") === -1) {
                    jsFile = paths[1] + "/" + jsFile;
                } else {
                    for (var i = 1; i <= 3; i++) {
                        if (match[i]) {
                            jsFile = jsFile.replace(match[i], paths[i - 1]);
                        }
                    }
                }
                if (!match[4]) {
                    jsFile += ".js";
                }
                return jsFile;
            };
        };

        // Load a JavaScript file
        csn.loadScript = function (scripts, callback) {
            var src, loadId = "S" + (+new Date()), i, count, adjustFileUrl = adjustFileUrlCurry();

            if ($.isArray(scripts) && scripts.length) {
                loadCounter[loadId] = {
                    count: 0,
                    max: scripts.length,
                    callback: callback
                };

                for (i = 0; i < loadCounter[loadId].max; i += 1) {
                    src = adjustFileUrl(scripts[i]);
                    if (!scriptsLoaded[src]) {
                        scriptsLoaded[src] = $("script[src$='" + src + "']").length === 1;
                    }

                    if (!scriptsLoaded[src]) {
                        loadScript(src, loadId);
                    } else {
                        loadCompleted(src, loadId);
                    }
                }
            } else if ($.isFunction(callback)) {
                callback();
            }
        }
    } ());

} (jQuery));



