/***************************************************************
Javascript Library for Search API
    
Library Dependencies:
- jQuery Core v1.3.2
***************************************************************/

(function ($) {

    /* 
    * Evaluate is given object is undefined or null or empty
    */
    $.isEmpty = function (object) {
        return (object === undefined || object === null || object.length === 0);
    };

    $.getButton = function (container) {
        var button = container.find(":button");

        if ($.isEmpty(button)) {
            button = container.find(".link-button");
        }

        return button;
    };

})(jQuery);


/* 
* URL Parser
*/
$.url = (function () {

    var queryHash = null;

    function buildQueryHash(currentUrl) {
        var control;

        queryHash = { "eapi": "2" };

        if (currentUrl == undefined || currentUrl == null) {
            currentUrl = window.location.search;
        }

        currentUrl = currentUrl.replace("?", "&");

        $.each(currentUrl.substring(1).split("&"), function () {
            var q = this.split("=");
            if (q.length === 2) {
                queryHash[q[0]] = q[1];
            }
        });

        if (!(queryHash["vertical"] || queryHash["silo"])) {
            // TODO: this is expensive
            // need to find a way to contextualize the selector
            control = $("div[data-vertical]:first");
            queryHash.vertical = control.attr("data-vertical");
            queryHash.silo = control.attr("data-silo");
        }

        delete queryHash.Page;
    }


    function buildQueryString(currentUrl) {
        if (queryHash == null)
            return currentUrl != undefined ? currentUrl : location.search

        var search = "?";
        $.each(queryHash, function (key, value) {

            if (search.length > 1)
                search += "&";

            search += key + "=" + value;
        });

        return search;
    }

    function getBaseUrl(url) {
        return url.substring(0, url.indexOf("?"));
    }



    return {

        /* 
        * Get the query given key, or perform update if value is provided
        * Example of usage:
        * - get: $.url.query('key');
        * - update: $.url.query('key', 'new-value');
        */
        query: function (key, value, currentUrl) {

            if (currentUrl != undefined && currentUrl.length > 0) {
                buildQueryHash(currentUrl);
            }
            else if (queryHash == null && currentUrl == undefined) {
                buildQueryHash();
            }



            // do get
            if (typeof value !== "string") {
                var val = queryHash[key];
                if (val === undefined)
                    return "";
                return unescape(val);
            }
            else { // do update  
                queryHash[key] = value;
            }

        },



        removeParameter: function (url, parameter) {
            var urlparts = url.split('?');

            if (urlparts.length >= 2) {
                var urlBase = urlparts.shift(); //get first part, and remove from array
                var queryString = urlparts.join("?"); //join it back up

                var prefix = encodeURIComponent(parameter) + '=';
                var pars = queryString.split(/[&;]/g);
                for (var i = pars.length; i-- > 0; )               //reverse iteration as may be destructive
                    if (pars[i].lastIndexOf(prefix, 0) !== -1)   //idiom for string.startsWith
                        pars.splice(i, 1);
                url = urlBase + '?' + pars.join('&');
            }
            return url;
        },

        joinBaseWithQueryString: function (url) {
            return getBaseUrl(url) + buildQueryString(url);
        },

        redirect: function (currentUrl) {
            if (currentUrl != undefined && currentUrl.length > 0) {
                window.location.href = $.url.joinBaseWithQueryString(currentUrl);
            }
            else {
                window.location.search = buildQueryString();
            }
        }
    };

})();

/*
jQuery utility functions
*/

(function ($) {
    var scriptsLoaded = {};
    // Load a JavaScript file
    $.loadScript = function (src, callback) {
        var timer,
            script = document.createElement("script");

        if (!scriptsLoaded[src]) {
            scriptsLoaded[src] = $("script[src$='" + src + "']").length === 1;
        }

        if (!scriptsLoaded[src]) {
            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);
                        scriptsLoaded[src] = true;
                        if ($.isFunction(callback)) {
                            callback();
                        }
                    }
                }, 10);
            } else if ($.isFunction(callback)) {
                script.onreadystatechange = function () {
                    if (/loaded|complete/.test(script.readyState)) {
                        scriptsLoaded[src] = true;
                        callback();
                    }
                };

                script.onload = callback;
            }
        } else if ($.isFunction(callback)) {
            callback();
        }
    }

    // Manipulate cookie sub-keys
    $.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;
        }
    };

} (jQuery));
