﻿/// <reference path="../jquery-1.3.2-vsdoc.js" />
/// <reference path="../MicrosoftAjax.js" />

(function($)
{
    var nmls = window.nmls = {}, templateCache = nmls.templateCache = {};

    nmls.alertAjaxError = function(xmlHttpReq, textStatus, errorThrown)
    {
        if (xmlHttpReq.statusText && xmlHttpReq.statusText !== "")
            alert(xmlHttpReq.statusText);
        else
        {
            var sb = new Sys.StringBuilder();
            if (textStatus)
                sb.append(textStatus);
            if (errorThrown)
            {
                sb.append(": ");
                sb.append(errorThrown.description);
            }

            alert(sb.toString());
        }
    }

    nmls.alertJsonError = function(jsonData)
    {
        var sb = new Sys.StringBuilder();
        for (var i = 0; i < jsonData.Errors.length; ++i)
            sb.appendLine(jsonData.Errors[i].ErrorMessage);

        alert(sb.toString());
    }

    // Taken from Rick Strahl's blog and is based on John Resig's micro-templating engine.
    nmls.parseTemplate = function(template, data)
    {
        /// <summary>
        /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
        /// and # # code blocks for template expansion.
        /// </summary>    
        /// <param name="template" type="string">The text of the template to expand</param>    
        /// <param name="data" type="var">
        /// Any data that is to be merged. Pass an object and
        /// that object's properties are visible as variables.
        /// </param>    
        /// <returns type="string" />  
        var error = "";
        try
        {
            var func = templateCache[template];
            if (!func)
            {
                var strFunc =
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                            "with(obj){p.push('" +
                //                        str
                //                  .replace(/[\r\t\n]/g, " ")
                //                  .split("<#").join("\t")
                //                  .replace(/((^|#>)[^\t]*)'/g, "$1\r")
                //                  .replace(/\t=(.*?)#>/g, "',$1,'")
                //                  .split("\t").join("');")
                //                  .split("#>").join("p.push('")
                //                  .split("\r").join("\\'") + "');}return p.join('');";

                template.replace(/[\r\t\n]/g, " ")
                   .replace(/'(?=[^#]*#>)/g, "\t")
                   .split("'").join("\\'")
                   .split("\t").join("'")
                   .replace(/<#=(.+?)#>/g, "',$1,'")
                   .split("<#").join("');")
                   .split("#>").join("p.push('")
                   + "');}return p.join('');";

                //alert(strFunc);
                func = new Function("obj", strFunc);
                templateCache[template] = func;
            }

            return func(data);
        }
        catch (e)
        {
            error = e.message;
        }

        return "< # ERROR: " + error + " # >";
    }

    nmls.toggleSlide = function(bindSelector, toggleSelector, speed)
    {
        speed = speed || "slow";

        $(bindSelector).toggle(function()
        {
            $(toggleSelector).slideDown(speed);
        },
        function()
        {
            $(toggleSelector).slideUp(speed);
        });
    }

    nmls.getQueryStringParam = function(param)
    {
        if (!param || $.trim(param) === "")
            return "";
    
        var query = window.location.search.substring(1),
            vars = query.split("&"),
            paramLower = param.toLowerCase();
        for (var i = 0; i < vars.length; i++)
        {
            var pair = vars[i].split("=");
            if (pair[0].toLowerCase() === paramLower)
            {
                var paramVal = decodeURIComponent(pair[1]);
                return paramLower === "searchtext" ? cleanSearchText(paramVal) : paramVal;
            }
        }
    }

    function cleanSearchText(searchText)
    {
        return searchText.split("+").join(" ");
    }

    nmls.spinner = function(options)
    {
        var _timeout,
            _$textElem,
            _$imageElem,
            _$spinner,
            _$elem = $("#" + options.elemId),
            _options =
            {
                animateText: "Processing...",
                interval: 30,
                spinnerClass: "nmls_spinner",
                animHeight: 16
            };

        $.extend(_options, options);

        _$imageElem = $("<div class='image'></div>");

        _$textElem = $("<span class='text'></span>"),
        _$textElem.html(_options.animateText);

        _$spinner = $("<div class='" + _options.spinnerClass + "'></div>");
        _$spinner.append(_$imageElem);
        _$spinner.append(_$textElem);

        _$elem.html(_$spinner);

        function _animate()
        {
            var $imageElem = $("." + _options.spinnerClass + " .image");
            var pos = $imageElem.css("backgroundPosition");
            var y = pos ? parseInt(pos.split(" ")[1]) - _options.animHeight : 0;
            $imageElem.css("backgroundPosition", "0px " + y + "px");
            _timeout = setTimeout(_animate, _options.interval);
        }

        this.start = function()
        {
            clearTimeout(_timeout);
            _$elem.show();
            _timeout = setTimeout(_animate, _options.interval);
        }

        this.stop = function()
        {
            clearTimeout(_timeout);
            _$elem.hide();
        }
    }

    nmls.modalDialog = function(elemId, options)
    {
        var _self = this,
            _$elem = $("#" + elemId),
            _options =
            {
                overlayOpacity: .6,
                overlayFilterOpacity: 60,
                overlayColor: "#000",
                closeHeaderClass: "nmls_modalDialogCloseHeader",
                closeImageClass: "nmls_modalDialogCloseImage",
                imageUrl: "",
                eventHandlers: document
            },
            _$overlay = $("<div></div>"),
            _$closeHeader,
            _$closeImage,
            _zindex = 1000;

        $.extend(_options, options);

        _$overlay.css(
        {
            "position": "fixed",
            "_position": "absolute",
            "z-index": _zindex,
            "left": 0,
            "top": 0,
            "width": "100%",
            "_width": document.body.offsetWidth + "px",
            "height": "100%",
            "_height": document.body.offsetHeight + "px",
            "background-color": _options.overlayColor,
            "opacity": _options.overlayOpacity,
            "filter": "alpha(opacity=" + _options.overlayFilterOpacity + ")",
            "display": "none"
        });

        $(document.body).append(_$overlay);

        _$closeHeader = $("<div class='" + _options.closeHeaderClass + "'></div>");
        _$closeImage = $("<input type='image' alt='Close' class='" + _options.closeImageClass + "' />");
        _$closeImage.attr("src", _options.imageUrl);
        _$closeHeader.html(_$closeImage);

        _$elem.prepend(_$closeHeader);
        _$elem.find("." + _options.closeImageClass).bind("click", function(e)
        {
            _self.close();
        });

        function _viewport()
        {
            var x = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft,
                y = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop,
                width = window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body.clientWidth,
                height = window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight
            return { x: x, y: y, width: width, height: height };
        };

        this.show = function()
        {
            var viewport = _viewport();
            _$overlay.show();
            _$elem.css(
            {
                "position": "fixed",
                "_position": "absolute",
                "z-index": _zindex + 1,
                "left": ((viewport.width - _$elem.width()) / 2) + "px",
                "top": ((viewport.height - _$elem.height()) / 2) + "px",
                "width": _$elem.width()
            });
            _$elem.show();
        }

        this.close = function()
        {
            _$overlay.hide();
            _$elem.hide();
            $(_options.eventHandlers).trigger("nmls_modalDialogClosed");
        }
    }

    $.fn.swapValues = function()
    {
        var swapValuesArr = [];
        var initialValue = [];

        this.each(function(i)
        {
            swapValuesArr[i] = $(this).val();
            initialValue[i] = $(this).attr("initialValue") ? $(this).attr("initialValue") : swapValuesArr[i];

            $(this).focus(function()
            {
                if ($(this).val() === initialValue[i])
                    $(this).val("");
            }).click(function()
            {
                if ($(this).val() === initialValue[i])
                    $(this).val("");
            }).blur(function()
            {
                if ($.trim($(this).val()) === "")
                    $(this).val(initialValue[i]);
            });
        });
    };

    $.fn.tooltip = function(options)
    {
        var _options =
            {
                cssClass: "nmls_tooltipClass",
                content: "",
                delay: 0,
                offsetToMouse: false,
                offsetX: 10,
                offsetY: 20,
                offsetPosition: ""
            },
            _timeout,
            _$tooltip;

        _options = $.extend(_options, options);
        _$tooltip = $("<div class='" + _options.cssClass + "'></div>")
            .html(_options.content)
            .css(
            {
                "position": "absolute",
                "display": "none"
            });

        this.each(function(i)
        {
            $(this).hover(function(e)
            {
                var $this = $(this),
                    position = { left: 0, top: 0 };

                clearTimeout(_timeout);
                $(document.body).append(_$tooltip);

                if (_options.offsetToMouse)
                    position = { left: e.pageX + _options.offsetX, top: e.pageY + _options.offsetY };
                else
                {
                    var offset = $this.offset();
                    if (typeof (_options.offsetPosition) === "string")
                    {
                        // Tooltip is positioned at the top and is horizontally centered.
                        if (_options.offsetPosition === "vt-hc")
                        {
                            position.left = offset.left + $this.width() / 2 - _$tooltip.width() / 2;
                            position.top = offset.top - _$tooltip.height() - _options.offsetY;
                        }
                        // Tooltip is positioned vertically centered and horizontally to the right.
                        else if (_options.offsetPosition === "vc-hr")
                        {
                            position.left = offset.left + $this.width() + _options.offsetX;
                            position.top = offset.top + $this.height() / 2 - _$tooltip.height() / 2;
                        }
                        if (position.left < 0)
                            position.left = 0;
                        if (position.top < 0)
                            position.top = 0;
                    }
                }

                _$tooltip.css(
                    {
                        "left": position.left + "px",
                        "top": position.top + "px",
                        "display": "none"
                    });
                _timeout = setTimeout(function() { _$tooltip.fadeIn(); }, _options.delay);
            }, function(e)
            {
                _$tooltip.remove();
            });
        });

        return this;
    };

    $.htmlEncode = function(content)
    {
        if (!content)
            return "";
        return $("<div/>").text(content).html();
    };

    $.htmlDecode = function(content)
    {
        if (!content)
            return "";
        return $("<div/>").html(content).text();
    };

    $.fn.showOrFadeIn = function()
    {
        if ($.browser.msie)
            this.show();
        else
            this.fadeIn();
    }

    $.fn.hideOrFadeOut = function()
    {
        if ($.browser.msie)
            this.hide();
        else
            this.fadeOut();
    }

})(jQuery);