/// <reference path="jquery-1.3.1.min-vsdoc.js" />
/// <reference path="jquery.manglar-vsdoc.js" />

$(document).ready(function() {
    $(document).click(function(event) {
        var calendarHandler = $(document).data(Calendar.GlobalCalendarHandlerId);
        if (calendarHandler) {
            for (var i = 0; i < calendarHandler.length; i++) {
                if (calendarHandler[i]) $(calendarHandler[i]).hide();
            }
        }
    });
});

function Calendar(start, action, options) {
    var self = this;
    var defaults = {}
    defaults.ShortWeekDays = ["do", "lu", "ma", "mi", "ju", "vi", "sa"];
    defaults.Months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    defaults.StartYear = start.getFullYear() - 10;
    defaults.EndYear = start.getFullYear() + 10;
    defaults["class"] = "calendar";
    options = $.extend(defaults, options);
    var table = new Table(options);
    var days = new Table({ "class": "days" });
    var months = new Element("select", { "class": "months" });
    var years = new Element("select", { "class": "years" });
    var headers = [];
    for (var i = 0; i < options.Months.length; i++) {
        $(months).append(new Element("option", { text: options.Months[i], value: i }));
    }
    $(months).val(start.getMonth());
    $(months).change(function() {
        self.draw(self.getDate());
    });
    for (var i = options.StartYear; i <= options.EndYear; i++) {
        $(years).append(new Element("option", { text: i, value: i }));
    }
    $(years).val(start.getFullYear());
    $(years).change(function() {
        self.draw(self.getDate());
    });
    for (var i = 0; i < 7; i++) {
        headers.push({ value: options.ShortWeekDays[i] });
    }
    days.setHeaders(headers);
    table.addRow([{ value: months }, { value: years}]);
    table.addRow([{ value: days.getElement(), options: { colspan: 2, align: "center"}}]);

    this.getDate = function(day, month) {
        var year = parseInt($(years).val());
        var month = parseInt($(months).val());
        if (!day) day = start.getDate();
        return new Date(year, month, day);
    }

    this.draw = function(start) {
        days.clearRows();
        var date = new Date(start.getFullYear(), start.getMonth(), 01);
        var end = new Date(start.getFullYear(), start.getMonth() + 1, 01);
        date.setDate(1 - date.getDay());
        while (date.getTime() < end.getTime()) {
            var row = [];
            for (var i = 0; i < 7; i++) {
                var style = "day";
                if (date.getDay() == 0 || date.getDay() == 6) style += " weekend";
                if (date.getFullYear() == start.getFullYear() && date.getMonth() == start.getMonth() && date.getDate() == start.getDate())
                    style += " today";
                var month = date.getMonth();
                var year = date.getFullYear();
                var day = date.getDate();
                if (date.getMonth() != start.getMonth()) style += " off-month";
                row.push({ value: date.getDate(), options: { "class": style, year: year, month: month, day: day, click: function() {
                    //action(self.getDate(parseInt($(this).text())));
                    var y = parseInt($(this).attr("year"));
                    var m = parseInt($(this).attr("month"));
                    var d = parseInt($(this).attr("day"));
                    $(months).val(m);
                    $(years).val(y);
                    action(new Date(y, m, d));
                }
                }
                });
                date.setDate(date.getDate() + 1);
            }
            days.addRow(row);
        }
    }
    this.getElement = function() { return table.getElement(); }
    this.draw(start);
}

Calendar.GlobalCalendarHandlerId = "GlobalCalendarHandlerId";

jQuery.fn.dateBox = function(fn) {
    var self = this;
    var div = new Element("div");
    var calendar = new Calendar(new Date(), function(date) {
        $(self).val(toISODateString(date));
        if (fn)fn(self);
        $(div).hide();
    });
    $(div).append(calendar.getElement());
    $(div).hide();
    $(div).css("position", "absolute");
    $(div).data("box", self);
    var calendarHandler = $(document).data(Calendar.GlobalCalendarHandlerId);
    if (!calendarHandler) {
        $(document).data(Calendar.GlobalCalendarHandlerId, []);
        calendarHandler = $(document).data(Calendar.GlobalCalendarHandlerId);
    }
    calendarHandler.push(div);
    $(this).attr("readonly", "readonly");
    $(this).click(function(event) {
        var date = new Date();
        if ($(this).val() != "") date = toDate($(this).val());
        calendar.draw(date);
        if (jQuery.browser.msie) {
            $(div).css("top", ($(this).position().top + $(this).outerHeight()) + "px");
            $(div).css("left", $(this).position().left + "px");
        }
        else {
            $(div).css("top", ($(this).offset().top + $(this).outerHeight()) + "px");
            $(div).css("left", $(this).offset().left + "px");
        }
        $(div).css("z-index", getNextZIndex());
        $(this).parent().append(div);
        $(div).show();
    });
    $(div).children().click(function(e) { e.stopPropagation(); });
    $(this).click(function(e) { e.stopPropagation(); });
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

var format_options = {
    dec: /,/,
    tho: /\./g,
    cur: /\$/,
    tho_replace: "$1.$2",
    cur_regexp: /^-?\$?\s?[0-9\.]+(\,\d*)?$/,
    num_regexp: /^-?[0-9\.]+(\,\d*)?$/,
    per_regexp: /^-?[0-9\.]+(\,\d*)?%?$/,
    cur_dec_format: "$ {0},{1}", 
    cur_format: "$ {0}",
    dec_format: "{0},{1}",
    num_format: "{0}",
    per_dec_format: "{0},{1}%",
    per_format: "{0}%"
};

jQuery.fn.free = function() {
    var colllectorId = "OptimizedGarbageCollector";
    var collector = $("#" + colllectorId);
    if (!collector) {
        collector = document.createElement("div");
        $(collector).attr("id", colllectorId);
        $(collector).attr("display", "none");
        $(document.body).append(collector);
    }
    $(this).remove();
    $(collector).append(this);
    $(collector).html("");
}

function getNextZIndex() {
    var max = 0;
    $("*").each(function() {
        var current = parseInt($(this).css("z-index"));
        if (current < 100000) max = current > max ? current : max;
    });
    return max + 1;
}

function toISODateString(date) {
    if (date != null) {
        var y = date.getFullYear().toString();
        var m = (date.getMonth() + 1).toString();
        var d = date.getDate().toString();
        if (m.length < 2) m = "0" + m;
        if (d.length < 2) d = "0" + d;
        return y + "-" + m + "-" + d;
    }
}

function toISODateTimeString(date) {
    if (date != null) {
        var dateString = toISODateString(date);
        var h = date.getHours().toString();
        var m = date.getMinutes().toString();
        var s = date.getSeconds().toString();
        if (h.length < 2) h = "0" + h;
        if (m.length < 2) m = "0" + m;
        if (s.length < 2) s = "0" + s;
        return dateString + " " + h + ":" + m + ":" + s;
    }
}

function toDate(date) {
    var values = date.split("-");
    return new Date(parseInt(values[0], 10), parseInt(values[1], 10) - 1, parseInt(values[2], 10));
}

function parseNumber(value, options) {
    options = $.extend(format_options, options);
    value = value.toString();
    var parts = value.split(options.dec);
    var integer = parts[0].replace(options.tho, "");
    integer = integer.replace(/\s/g, "");
    integer = integer.replace(options.cur, "");
    if (parts[1]) value = integer + "." + parts[1];
    else value = integer;
    return parseFloat(value);
}

function toNumber(value, options) {
    options = $.extend(format_options, options);
    var re = /(-?[0-9]+)([0-9]{3})/;
    value = value.toString();
    var parts = value.split(".");
    var integer = parts[0];
    var deci = parts[1];
    while (re.test(integer)) {
        integer = integer.replace(re, options.tho_replace);
    }
    if (deci) return $.format(options.dec_format, integer, deci);
    else return $.format(options.num_format, integer);
}

function isCurrency(value, options) {
    options = $.extend(format_options, options);
    var re = options.cur_regexp;
    return re.test(value);
}

function isNumber(value, options) {
    options = $.extend(format_options, options);
    var re = options.num_regexp;
    return re.test(value);
}

function toCurrency(value, options) {
    options = $.extend(format_options, options);
    var re = /(-?[0-9]+)([0-9]{3})/;
    value = value.toString();
    var parts = value.split(".");
    var integer = parts[0];
    var deci = parts[1];
    while (re.test(integer)) {
        integer = integer.replace(re, options.tho_replace);
    }
    if (deci) return $.format(options.cur_dec_format, integer, deci);
    else return $.format(options.cur_format, integer);
}

function isPercentage(value, options) {
    options = $.extend(format_options, options);
    var re = options.per_regexp;
    return re.test(value);
}

function toPercentage(value, options) {
    options = $.extend(format_options, options);
    var re = /(-?[0-9]+)([0-9]{3})/;
    value = value.toString();
    var parts = value.split(".");
    var integer = parts[0];
    var deci = parts[1];
    while (re.test(integer)) {
        integer = integer.replace(re, options.tho_replace);
    }
    if (deci) return $.format(options.per_dec_format, integer, deci);
    else return $.format(options.per_format, integer);
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Dialog(titleText, element, options) {
    options = $.extend({ modal: true, drag: true, "class": "dialog" }, options)
    var self = this;
    var table = new Table(options);
    var title = new Element("div", { "class": "title" });
    var button = new Element("div", { "class": "close" });
    if (titleText) $(title).text(titleText);
    var overlay = null;
    var header = table.addRow([{ value: title, options: { "class": "left"} }, { value: button, options: { "class": "right"}}], { "class": "header" });
    table.addRow([{ value: element, options: { "class": "content", colspan: 2}}], { "class": "content" });
    this.close = function() {
        $(table.getElement()).free();
        if (overlay) $(overlay).free();
        $(this).free();
    }

    $(button).click(this.close);

    this.show = function() {
        $(document.body).prepend(table.getElement());
        $(table.getElement()).css("position", "absolute");
        var windowHeight = $(window).height();
        var tableHeight = $(table.getElement()).height();
        $(table.getElement()).css("top", ((windowHeight - tableHeight) / 2));
        var windowWidth = $(window).width();
        var tableWidth = $(table.getElement()).width();
        $(table.getElement()).css("left", ((windowWidth - tableWidth) / 2));
        if (options.drag) {
            $(header).addClass("drag-element");
            $(table.getElement()).drag();
        }
        if (options.modal) {
            overlay = new Element("div", { "class": "dialog-overlay" });
            $(overlay).css("width", $(window).width());
            $(overlay).css("height", $(window).height());
            $(overlay).css("z-index", getNextZIndex());
            $(document.body).prepend(overlay);
        }
        $(table.getElement()).css("z-index", getNextZIndex());
    }

    this.size = function() {
        return { height: $(table.getElement()).height(), width: $(table.getElement()).width() };
    }

    this.move = function(x, y) {
        $(table.getElement()).css("top", y);
        $(table.getElement()).css("left", x);
    }

    this.getElement = function() { return table.getElement(); }
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

jQuery.fn.drag = function(box) {
    var isDown = false;
    var pos = { top: 0, left: 0 };
    var dragElement;
    if ($(this).hasClass("drag-element")) dragElement = this;
    else dragElement = $(this).find(".drag-element");
    var element = $(this);
    $(element).addClass("drag");
    $(dragElement).mousedown(function(event) {
        isDown = true;
        pos.left = event.pageX;
        pos.top = event.pageY;
        $(element).addClass("dragging");
    });
    $(document).mouseup(function(event) {
        isDown = false;
        $(element).removeClass("dragging");
    });

    $(document).mousemove(function(event) {
        if (isDown) {
            var deltaX = event.pageX - pos.left;
            var deltaY = event.pageY - pos.top;
            pos.left = event.pageX;
            pos.top = event.pageY;
            var elementPos = $(element).position();
            var left = elementPos.left + deltaX;
            var top = elementPos.top + deltaY;
            $(element).css("left", left);
            $(element).css("top", top);
            if (box) {
                var l = 0;
                var t = 0;
                var b = t + $(box).outerHeight();
                var r = l + $(box).outerWidth();
                var el = $(element).position().left;
                var et = $(element).position().top;
                var eh = $(element).outerHeight();
                var ew = $(element).outerWidth();
                if (el < l) $(element).css("left", left + (l - el));
                else if (el + ew > r) $(element).css("left", left - (el + ew - r));
                if (et < t) $(element).css("top", top + (t - et));
                else if (et + eh > b) $(element).css("top", top - (et + eh - b));
            }
        }
    });

    return this;
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Element(type, options) {
    var element = document.createElement(type);
    for (k in options) {
        if (k == "text") {
            $(element).text(options[k]);
        }
        else if (k == "val") {
            $(element).val(options[k]);
        }
        else if (k == "class") {
            $(element).addClass(options[k]);
        }
        else if (k == "click") {
            $(element).click(options[k]);
        }
        else if (k == "title") {
            tootTip = new Tooltip(element, options[k]);
        }
        else if (k.toString().toLowerCase() == "colspan") {
            $(element).attr("colSpan", options[k]);
        }
        else if (k.toString().toLowerCase() == "rowspan") {
            $(element).attr("rowSpan", options[k]);
        }
        else $(element).attr(k, options[k]);
    }
    return element;
}

function Label(text, options) {
    options = $.extend({ text: text }, options);
    var element = new Element("label", options);
    return element;
}

function Text(options) {
    options = $.extend({ type: "text" }, options);
    var element = new Element("input", options);
    return element;
}

function Password(options) {
    options = $.extend({ type: "password" }, options);
    var element = new Element("input", options);
    return element;
}

function Select(options) {
    var element = new Element("select", options);
    return element;
}

function Div(options) {
    var element = new Element("div", options);
    return element;
}

function Button(text, options) {
    var button = new Element("div", options);
    var left = new Element("div", { "class": "button-left" });
    var center = new Element("div", { "class": "button-center" });
    var right = new Element("div", { "class": "button-right" });

    $(button).append(left);
    $(button).append(center);
    $(button).append(right);
    $(center).text(text);

    this.setText = function(t) { $(center).text(t); };
    this.getText = function() { return $(center).text(); }
    this.getElement = function() { return button; }
}
/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function(string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }

    function AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x, y, z) { return (x & y) | ((~x) & z); }
    function G(x, y, z) { return (x & z) | (y & (~z)); }
    function H(x, y, z) { return (x ^ y ^ z); }
    function I(x, y, z) { return (y ^ (x | (~z))); }

    function FF(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var x = Array();
    var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
    var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
    var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
    var S41 = 6, S42 = 10, S43 = 15, S44 = 21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k = 0; k < x.length; k += 16) {
        AA = a; BB = b; CC = c; DD = d;
        a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
        a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = AddUnsigned(a, AA);
        b = AddUnsigned(b, BB);
        c = AddUnsigned(c, CC);
        d = AddUnsigned(d, DD);
    }

    var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);

    return temp.toLowerCase();
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

$(document).ready(function() {
    $(document).keypress(function(event) {
        if (event.keyCode == 27) {
            var menuHandler = $(document).data(Menu.GlobalMenuHandlerId);
            if (menuHandler) {
                for (var i = 0; i < menuHandler.length; i++) {
                    if (menuHandler[i]) {
                        if (event.timeStamp - menuHandler[i].getTimeStamp() > 500)
                            menuHandler[i].close();
                    }
                }
            }
        };
    });
    $(document).click(function(event) {
        var menuHandler = $(document).data(Menu.GlobalMenuHandlerId);
        if (menuHandler) {
            for (var i = 0; i < menuHandler.length; i++) {
                if (menuHandler[i]) {
                    if (event.timeStamp - menuHandler[i].getTimeStamp() > 500)
                        menuHandler[i].close();
                }
            }
        }
    });
});

function Menu(items, options) {
    options = $.extend({ "class": "menu", fade: "def" }, options)
    var self = this;
    var timeStamp = null;
    var menu = new Element("div", options);
    var ul = new Element("ul");
    $(menu).append(ul);
    var menuHandler = $(document).data(Menu.GlobalMenuHandlerId);
    if (!menuHandler) {
        $(document).data(Menu.GlobalMenuHandlerId, []);
        menuHandler = $(document).data(Menu.GlobalMenuHandlerId);
    }
    menuHandler.push(self);
    
    this.getElement = function() { return menu; }

    this.setItems = function(is) {
        $(ul).empty();
        items = [];
        for (var i = 0; i < is.length; i++) {
            var li = new MenuItem(is[i].value, is[i].action, is[i].id, is[i].options);
            items.push(li);
            $(li.getElement()).click(function() { self.close() });
            $(ul).append(li.getElement());
        }
    }

    this.setItems(items);

    this.showOnPosition = function(x, y, event, parent) {
        if (items.length > 0) {
            var id = $(event.currentTarget).data("id");
            if (id) {
                for (var i = 0; i < items.length; i++) {
                    items[i].setId(id);
                }
            }
            $(menu).css("top", y - 5);
            $(menu).css("left", x - 5);
            $(menu).css("display", "none");
            $(menu).css("z-index", getNextZIndex());
            $(menu).mouseleave(self.close);
            if (parent) $(parent).append(menu);
            else $(document.body).append(menu);
            if (options.fade) $(menu).fadeIn(options.fade);
            else $(menu).show();
            timeStamp = event.timeStamp;
        }

    }

    this.show = function(event, parent) {
        self.showOnPosition(event.pageX, event.pageY, event, parent);
    }

    this.close = function() {
        if (options.fade) $(menu).fadeOut();
        else $(menu).hide();
    }

    this.getTimeStamp = function() { return timeStamp; }
}

Menu.GlobalMenuHandlerId = "GlobalMenuHandler";

function MenuItem(value, action, id, options) {
    var self = this;
    var li = new Element("li", options);
    $(li).append(value);
    $(li).hover(function() {
        $(this).addClass("over");
        $(this).siblings().removeClass("over")
    }, function() { $(this).removeClass("over") });
    if (action) {
        $(li).click(function() {
            if (id != null && id != undefined) action(id);
            else action();
        });
    }
    this.getElement = function() { return li; }
    this.setId = function(i) {
        id = i;
    }
}

/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Panel(rows, columns, id, options) {
    options = $.extend({ "class": "panel", width: "100%" }, options)
    var menu = null;
    var toolTip = null;
    var pager = null;
    var panel = new Table(options);
    var headerDiv = new Element("div");
    var elements = new Table({ "class": "elements table", width: "100%", cellspacing: 0, cellpadding: 0 });
    var pagerDiv = new Element("div");
    elements.setInterLined(true);
    var headers = []
    for (var j = 0; j < columns.length; j++) {
        headers.push({ value: "&nbsp;" });
    }
    elements.setHeaders(headers);
    for (var i = 0; i < rows; i++) {
        var row = []
        for (var j = 0; j < columns.length; j++) {
            row.push({ value: "&nbsp;" });
        }
        elements.addRow(row);
    }
    panel.addRow([{ value: headerDiv }]);
    panel.addRow([{ value: elements.getElement()}]);
    panel.addRow([{ value: pagerDiv, options: { align: "center"}}]);

    this.getElements = function() { return elements; }
    this.getElement = function() { return panel.getElement(); }

    this.setTitles = function(headers, options) { elements.setHeaders(headers, options); };
    
    this.setPager = function(size, total, action, max, options) {
        $(pagerDiv).empty();
        pager = new Pager(size, total, action, max, options);
        $(pagerDiv).append(pager.getElement());
    };

    this.setTotal = function(total) { pager.setTotal(total); }
    
    this.setHeader = function(element) {
        $(headerDiv).empty();
        $(headerDiv).append(element);
    }

    this.setMenu = function(m) {
        menu = m;
    }
    this.getMenu = function() {
        return menu;
    }

    this.setToolTip = function(t) { toolTip = t; }

    this.hidePager = function() { $(pager.getElement()).hide(); }

    this.setElements = function(items) {
        elements.clearRows();
        for (var i = 0; i < rows; i++) {
            var row = [];
            var item = items[i];
            var itemOptions = null;
            if (menu && item && item.value) itemOptions = $.extend({ "click": menu.show }, item.options);
            else if (menu) itemOptions = { "click": menu.show };
            else if (item && (item.value || item.options)) itemOptions = item.options;
            if (toolTip) itemOptions = $.extend({ title: toolTip }, itemOptions);
            for (var j = 0; j < columns.length; j++) {
                var column = columns[j];
                if (items.length > i) {
                    var cell = null;
                    if (item.value) cell = item.value[column];
                    else cell = item[column];
                    if (cell && cell.value) row.push({ value: cell.value, options: cell.options });
                    else row.push({ value: cell });
                }
                else row.push({ value: "&nbsp;" });
            }
            if (!id || !item) elements.addRow(row);
            else if (item.value && item.value[id].value) elements.appendRow(item.value[id].value, row, itemOptions);
            else if (item.value) elements.appendRow(item.value[id], row, itemOptions);
            else elements.appendRow(item[id], row, itemOptions);
        }
    }
}

function Pager(size, total, action, max, options) {
    options = $.extend({ "class": "pager" }, options)
    var self = this;
    var pager = new Table(options);
    max = max ? max : 10;
    var pages = 0;
    var back = 0;
    var front = 0;
    if ((max - 1) % 2 == 0) {
        back = (max - 1) / 2;
        front = back;
    }
    else {
        back = (max - 2) / 2;
        front = back + 1;
    }
    var page = 1;
   
    this.getElement = function() { return pager.getElement(); }

    this.setPage = function(p) {
        if (p) page = p;
        pager.clearRows();
        var items = [];
        var start = 0;
        var end = 0;
        if (page - back <= 0) start = 1;
        else start = page - back;
        if (start + max > pages) {
            end = pages + 1;
            start = pages + 1 - max;
            if (start <= 1) start = 1;
        }
        else end = start + max;
        if (start != 1) items.push({ options: { "class": "left", click: function() { self.changePage(self.page - 1); } } })
        for (var i = start; i < end; i++) {
            var style = "page";
            if (i == page) style = "page selected";
            items.push({ value: i, options: { "class": style, click: function() { self.changePage(parseInt($(this).text())); } } });
        }
        if (end != pages + 1) items.push({ options: { "class": "right", click: function() { self.changePage(self.page + 1); } } });
        pager.addRow(items);

    }

    this.changePage = function(p) {
        this.setPage(p);
        if (action) action(page);
    }

    this.setTotal = function(t) {
        total = t;
        if (total % size > 0) pages = parseInt(total / size) + 1;
        else pages = total / size;
        this.setPage();
    }

    this.setTotal(total);
    this.setPage();
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Preloader() {
    var overlay = new Element("div");
    var preloader = new Element("div")
    $(overlay).addClass("preloader-overlay");
    $(preloader).addClass("preloader-image");
    
    this.show = function() {
        $(document.body).prepend(overlay);
        $(document.body).prepend(preloader);
        $(overlay).css("width", $(window).width());
        $(overlay).css("height", $(window).height());
        //$(overlay).css("z-index", getNextZIndex());
        $(preloader).css("position", "absolute");
        $(preloader).css("top", (($(window).height() - $(preloader).height()) / 2));
        $(preloader).css("left", (($(window).width() - $(preloader).width()) / 2));
        //$(preloader).css("z-index", getNextZIndex());
    }

    this.hide = function() {
        $(overlay).remove();
        $(preloader).remove();
    }
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

Date.prototype.toJSON = function() {
    var time = this.getTime() - (this.getTimezoneOffset() * 60 * 1000);
    return "\/Date(" + time + ")\/";
}

function ServiceProxy(service, onError) {
    var self = this;
    this.onError = onError;
    function convertToDate(data) {
        var testRe = /\/Date(.*)\//;
        var replaceRe = /\//g;
        if (typeof data === 'string') {
            if (testRe.test(data)) {
                data = eval("new " + data.replace(replaceRe, ""));
            }
        }
        else if ($.isArray(data)) {
            for(var i = 0; i < data.length; i++) data[i] = convertToDate(data[i]);
        }
        else if(typeof data === 'object') {
            for (k in data) data[k] = convertToDate(data[k]);
        }
        return data;
    }
    this.success = function(data, status, fn) {
        data = convertToDate(data);
        fn(data);
    };

    this.error = function(xhr, status, error, fn) {
        if (xhr.responseText && xhr.responseText != "")
            data = eval("(" + xhr.responseText + ")");
        else data = xhr.responseText;
        fn(data);
    }

    this.invoke = function(method, url, data, successFn, errorFn, noCache, sync) {
        if (!data) data = {};
        if (!errorFn) errorFn = this.onError;
        method = method.toUpperCase();
        var type = method;
        var onBefore;
        if (type != "GET" && type != "POST") {
            onBefore = function(xhr) {
                xhr.setRequestHeader("X-HTTP-Method-Override", type);
            }
            method = "POST";
        }
        if (method == "POST") data = JSON.stringify(data);
        $.ajax({
            type: method,
            url: service + url,
            data: data,
            contentType: "application/json",
            dataType: "json",
            success: function(data, textStatus) { self.success(data, textStatus, successFn); },
            error: function(xhr, status, error) { self.error(xhr, status, error, errorFn); },
            beforeSend: onBefore,
            processData: true,
            cache: !noCache,
            async: !sync
        });
    }

    this.get = function(url, sucess, error, noCache, sync) {
        this.invoke("GET", url, null, sucess, error, noCache, sync);
    }
}




/// <reference path="scripts/jquery-1.3.1.min-vsdoc.js" />

function Style(options) {
    options = $.extend({ "class": "style", colorImage: "images/colors.png", colorWidth: 217, colorHeight: 145 }, options);
    var element = new Element("div", options);
    this.colors = new Colors("#ffffff", options.colorImage, options.colorWidth, options.colorHeight);
    this.fonts = new Fonts();
    this.bold = new Bold();
    this.italic = new Italic();
    this.underline = new Underline();
    this.size = new Size();
    this.target = null;
    $(element).append(this.colors.getElement());
    $(element).append(this.size.getElement());
    $(element).append(this.bold.getElement());
    $(element).append(this.italic.getElement());
    $(element).append(this.underline.getElement());
    $(element).append(this.fonts.getElement());
    this.getElement = function() { return element; }
    this.setTarget = function(t) { 
        this.target = t;
        this.colors.setTarget(t); 
        this.fonts.setTarget(t);
        this.bold.setTarget(t);
        this.italic.setTarget(t);
        this.underline.setTarget(t);
        this.size.setTarget(t);
    }
}

function Size(selected, target, options) {
    var self = this;
    options = $.extend({ "class": "size" }, options);
    var control = new Element("select", options);
    var options = [8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72];
    for (var i = 0; i < options.length; i++) {
        $(control).append(new Element("option", {text: options[i], val: options[i]}));
    }
    if (selected) $(control).val(selected);
    this.getElement = function() { return control; }
    $(control).change(function() { self.select($(control).val()); });

    this.change = function(value) { $(control).val(value.toString().replace(/px/,"")); }
    this.select = function(value) {
        self.change(value);
        if (target) $(target).css("font-size", value);
    }
    this.getSelected = function() { return $(control).val(); }
    this.setTarget = function(t){ target = t; }
}

function Option(style, selected, target, options) {
    var self = this;
    options = $.extend({ "class": style }, options);
    var control = new Element("div", options);
    var button = new Element("div", { "class": "action" });
    $(control).append(button);
    if (selected) $(button).addClass("on");
    this.toggle = function() {
        if ($(button).hasClass("on")) {
            self.select(false);
        }
        else {
            self.select(true);
        }
    }
    $(button).click(this.toggle);
    this.getElement = function() { return control; }
    this.change = function(value) {
        if (value == "bold" || value == "700" || value == "italic" || value == "underline" || value == true) $(button).addClass("on");
        else $(button).removeClass("on");
    }
    this.select = function(value) {
        self.change(value);
        if (target) {
            if (style == "bold") {
                if (value) $(target).css("font-weight", "bold");
                else $(target).css("font-weight", "normal");
            }
            else if (style == "italic") {
                if (value) $(target).css("font-style", "italic");
                else $(target).css("font-style", "normal");
            }
            else if (style == "underline") {
                if (value) $(target).css("text-decoration", "underline");
                else $(target).css("text-decoration", "none");
            }
        }
    }
    this.getSelected = function() { return $(buttons).hasClass("on"); }
    this.setTarget = function(t){ target = t; }
}

function Bold(selected, target, options) {
    return new Option("bold", selected, options);    
}

function Italic(selected, target, options) {
    return new Option("italic", selected, options);
}

function Underline(selected, target, options) {
    return new Option("underline", selected, options);
}

function Fonts(selected, target, options) {
    var self = this;
    options = $.extend({ "class": "fonts" }, options);
    var control = new Element("div", options);
    var button = new Element("div", { "class": "action" });
    var actual = new Element("div", { "class": "actual" });
    $(control).append(actual);
    $(control).append(button);
    $(actual).click(showMenu);
    $(button).click(showMenu);

    this.change = function(value) {
        $(actual).text(value);
        $(actual).css("font-family", value);
    }
    this.select = function(value) {
        self.change(value);
        if (target) { $(target).css("font-family", value) }
    }

    this.getSelected = function() { return $(actual).val(); }
    
    var fonts = [];
    fonts.push({ value: "Arial", id: "Arial", options: { style: "font-family: Arial"}, action: self.select });
    fonts.push({ value: "Arial Black", id: "Arial Black", options: { style: "font-family: Arial Black" }, action: self.select });
    fonts.push({ value: "Comic Sans MS", id: "Comic Sans MS", options: { style: "font-family: Comic Sans MS" }, action: self.select });
    fonts.push({ value: "Courier New", id: "Courier New", options: { style: "font-family: Courier New" }, action: self.select });
    fonts.push({ value: "Georgia", id: "Georgia", options: { style: "font-family: Georgia" }, action: self.select });
    fonts.push({ value: "Impact", id: "Impact", options: { style: "font-family: Impact" }, action: self.select });
    fonts.push({ value: "Times New Roman", id: "Times New Roman", options: { style: "font-family: Times New Roman" }, action: self.select });
    fonts.push({ value: "Trebuchet MS", id: "Trebuchet MS", options: { style: "font-family: Trebuchet MS" }, action: self.select });
    fonts.push({ value: "Verdana", id: "Verdana", options: { style: "font-family: Verdana" }, action: self.select });
    fonts.push({ value: "Courier", id: "Courier", options: { style: "font-family: Courier" }, action: self.select });
    fonts.push({ value: "Helvetica", id: "Helvetica", options: { style: "font-family: Helvetica" }, action: self.select });
    fonts.push({ value: "Times", id: "Times", options: { style: "font-family: Times" }, action: self.select });
    fonts.push({ value: "Arial", id: "Arial", options: { style: "font-family: Arial" }, action: self.select });
    var menu = new Menu(fonts, {"class": "options"});
    
    function showMenu(event) {
        var x;
        var y;
        if (jQuery.browser.msie) {
            y = $(control).position().top + $(control).outerHeight();
            x = $(control).position().left;
        }
        else {
            y = $(control).offset().top + $(control).outerHeight();
            x = $(control).offset().left;
        }
        menu.showOnPosition(x + 5, y + 5, event, $(actual).parent());
    }

    this.getElement = function() { return control; }
    if (selected) this.select(selected);
    else this.select("Arial");
    this.setTarget = function(t){ target = t; }
}

function Colors(selected, src, width, height, target, options) {
    var self = this;
    options = $.extend({ "class": "colors", fade: "def" }, options);
    var control = new Element("div", options);
    var button = new Element("div", { "class": "action" });
    var actual = new Element("div", { "class": "actual" });
    var palette = new Element("div", { "class": "palette" });
    var image = new Element("img", { "class": "image", src: src, usemap: "#colormap", width: width, height: height });
    var size = width / 18;
    var map = new Element("map", { name: "colormap" });
    $(control).append(actual);
    $(control).append(button);
    $(button).click(show);
    $(actual).click(show);
    $(palette).append(image);
    $(palette).append(map);

    this.change = function(value) {
        $(actual).css("background-color", value);
    }
    this.select = function(value) {
        self.change(value);
        if (target) $(target).css("color", value);
    }

    this.getSelected = function(value) { return $(actual).css("background-color"); }

    if (selected) this.select(selected);
    
    for (var b = 0; b < 6; b++) {
        for (var r = 0; r < 3; r++) {
            for (var g = 0; g < 6; g++) {
                var x = (g + (r * 6)) * size;
                var y = b * size;
                var color = "#" + getColor(r) + getColor(g) + getColor(b);
                var area = new Element("area", { shape: "rect", coords: x + "," + y + "," + (x + size) + "," + (y + size), alt: color });
                $(area).data("color", color);
                $(map).append(area);
                $(area).click(function() {
                    self.select($(this).data("color"));
                    $(palette).hide();
                });
            }
        }
    }

    for (var b = 0; b < 6; b++) {
        for (var r = 0; r < 3; r++) {
            for (var g = 0; g < 6; g++) {
                var x = (g + (r * 6)) * size;
                var y = (b + 6) * size;
                var color = "#" + getColor(r + 3) + getColor(g) + getColor(b);
                var area = new Element("area", { shape: "rect", coords: x + "," + y + "," + (x + size) + "," + (y + size), alt: color });
                $(area).data("color", color);
                $(map).append(area);
                $(area).click(function() {
                    self.select($(this).data("color"));
                    $(palette).hide();
                });
            }
        }
    }
   
    function getColor(color) {
        switch (color) {
            case 0: return "00";
            case 1: return "33";
            case 2: return "66";
            case 3: return "99";
            case 4: return "CC";
            case 5: return "FF";
        }
    }

    function show() {
        var x;
        var y;
        if (jQuery.browser.msie) {
            y = $(control).position().top + $(control).outerHeight();
            x = $(control).position().left;
        }
        else {
            y = $(control).offset().top + $(control).outerHeight();
            x = $(control).offset().left;
        }
        $(palette).css("top", y);
        $(palette).css("left", x);
        $(palette).css("display", "none");
        $(palette).css("z-index", getNextZIndex());
        $(palette).mouseleave(self.close);
        $(control).append(palette);
        if (options.fade) $(palette).fadeIn(options.fade);
        else $(palette).show();
    }
    
    this.getElement = function() { return control; }
    this.setTarget = function(t) { target = t; }
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Table(options) {
    var table = new Element("table", options);
    var thead = new Element("thead");
    var tbody = new Element("tbody");
    var interLined = false;
    $(table).append(thead);
    $(table).append(tbody);

    this.getElement = function() { return table; }
    
    this.interLine = function() {
        var rows = $(tbody).children("tr");
        for (var i = 0; i < rows.length; i++) {
            if (i % 2 == 0) {
                $(rows[i]).removeClass("odd");
                $(rows[i]).addClass("even");
            }
            else {
                $(rows[i]).removeClass("even");
                $(rows[i]).addClass("odd");
            }
        }
    }
    
    this.setInterLined  = function(value){
        interLined = value;
    }
    
    this.setHeaders = function(headers, options) {
        $(thead).empty();
        $(thead).append(new Rx(null, headers, "th", options));
    }

    this.appendRow = function(id, values, options) {
        var tr = new Rx(id, values, "td", options);
        $(tbody).append(tr);
        if (interLined == true) this.interLine();
        return tr;
    }
    
    this.addRow = function(values, options) {
        var tr = this.appendRow(null, values, options);
        return tr;
    }

    this.clearRows = function() {
        var trs = $(tbody).children("tr");
        for (var i = 0; i < trs.length; i++) {
            $(trs[i]).free();
        }
    }

    this.findRow = function(id) {
        var rows = $(tbody).children("tr");
        for (var i = 0; i < rows.length; i++) {
            if ($(rows[i]).data("id") == id) return rows[i];
        }
    }

    this.updateCell = function(id, index, value) {
        var row = findRow(id);
        var cells = $(row).children("td");
        $(cells[index]).empty();
        $(cells[index]).append(value);
    }

    this.updateRow = function(id, values, options, type) {
        var row = new Row(values, options, type);
        $(row).data("id", id);
        $(this.findRow(id)).replaceWith(row);
    }

    this.getRow = function(index) {
        var rows = $(tbody).children("tr");
        return rows[i];
    }

    function Rx(id, values, type, options) {
        var tr = new Element("tr", options);
        $(tr).hover(function() { $(this).addClass("over") }, function() { $(this).removeClass("over") });
        $(tr).click(function() { $(this).siblings().removeClass("selected"); $(this).addClass("selected"); })
        $(tr).data("id", id);
        for (var i = 0; i < values.length; i++) {
            var td = new Tx(id, values[i].value, type, values[i].options);
            $(tr).append(td);
        }
        return tr;
    }

    function Tx(id, value, type, options) {
        var td = new Element(type, options);
        if (id) $(td).data("id", id);
        if (value) {
            if ($.isArray(value)) {
                for (var i = 0; i < value.length; i++) {
                    if (typeof (value) == "boolean") {
                        $(td).append(value[i].toString());
                    }
                    else if (value.getFullYear && value.getMonth && value.getDate) {
                        $(td).append(toISODateTimeString(value[i]));
                    }
                    else $(td).append(value[i]);
                }
            }
            else {
                if (typeof (value) == "boolean") {
                    $(td).append(value.toString());
                }
                else if (value.getFullYear && value.getMonth && value.getDate) {
                    $(td).append(toISODateTimeString(value));
                }
                else $(td).append(value);
            }
        }
        return td;
    }
}
/// <reference path="../scripts/jquery-1.3.1.min-vsdoc.js" />

function Tabs(items, options) {
    options = $.extend({ "class": "tabs" }, options)
    var tabs = new Element("div", options)
    var head = new Element("div", { "class": "head" });
    var tail = new Element("div", { "class": "tail" });
    var ul = new Element("ul");
    for (var i = 0; i < items.length; i++) {
        var li = new Tab(items[i].value, items[i].action, items[i].options);
        $(ul).append(li);
    }
    $(tabs).append(head);
    $(tabs).append(ul);
    $(tabs).append(tail);

    this.getElement = function() { return tabs; }
    this.getTab = function(index) {
        var li = $(ul).find("li")[index];
        return li;
    }
}

function Tab(value, action, options) {
    var li = new Element("li", options);
    $(li).hover(function() { $(this).addClass("over"); }, function() { $(this).removeClass("over") });
    $(li).click(function() {
        $(this).siblings().removeClass("selected");
        $(this).addClass("selected");
        if (action) action();
    });
    $(li).append(value);
    return li;
}
/// <reference path="scripts/jquery-1.3.1.min-vsdoc.js" />

$(document).ready(function() {
    $(document).click(function(event) {
        removeToolTips();
    });
});

function removeToolTips() {
    var tooltipHandler = $(document).data(Tooltip.GlobalToolTipHandlerId);
    if (tooltipHandler) {
        for (var i = 0; i < tooltipHandler.length; i++) {
            if (tooltipHandler[i]) $(tooltipHandler[i]).hide();
        }
    }
}

function Tooltip(element, text, options) {
    options = $.extend({ "class": "tooltip" }, options);
    var self = this;
    var span = new Element("span", options);
    $(span).html(text);
    $(span).css("position", "absolute");
    $(span).css("display", "none");
    $(document.body).prepend(span);
    $(element).hover(function() {
        removeToolTips();
        $(self.getElement()).css("z-index", getNextZIndex());
        $(self.getElement()).show();
    }, function() {
        $(self.getElement()).hide();
    });
    //$(element).mouseenter(function() { removeToolTips(); $(self.getElement()).css("z-index", getNextZIndex()); $(self.getElement()).show(); });
    //$(element).mouseleave(function() { $(self.getElement()).hide(); });
    $(element).mousemove(function(e) { $(self.getElement()).css({ "top": (e.pageY + 25) + "px", "left": (e.pageX) + "px" }) });
    var tooltipHandler = $(document).data(Tooltip.GlobalToolTipHandlerId);
    if (!tooltipHandler) {
        $(document).data(Tooltip.GlobalToolTipHandlerId, []);
        tooltipHandler = $(document).data(Tooltip.GlobalToolTipHandlerId);
    }
    tooltipHandler.push(span);
    this.getElement = function() { return span; }
}

Tooltip.GlobalToolTipHandlerId = "GlobalToolTipHandlerId";
/*
    http://www.JSON.org/json2.js
    2009-09-29

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());


