// Common Javascript functions for RaceRaiser
// Jeff Rowberg <jeff@rowberg.net>

function smartEval(content) {
    clearMCEInstances();
    if (content == "_USERX") {
        if (!document.sessionExpireAlert) {
            document.sessionExpireAlert = true;
            alert("Your session has expired.  Please log in again.");
        }
        return true;
    }
    try {
        eval(content);
    } catch (e) {
        if (confirm("AJAX Javascript evaluation failed!\n\nError name: " + e.name + "\nError message: " + e.message + "\n\nClick OK to view failed script content, or Cancel to dismiss.")) {
            jPopup(content, "Javascript content");
        }
        /*var lines = content.split("\n");
        for (i = 0; i < lines.length; i++) {
            try {
                eval(lines[i]);
            } catch (e) {
                if (confirm("AJAX Javascript evaluation failed!\n\nError name: " + e.name + "\nError message: " + e.message + "\nContent line: #" + (i + 1) + "\nSource code: " + lines[i] + "\n\nClick OK to view entire content, or Cancel to dismiss."))
                    alert(content);
                return false;
            }
        }*/
        return false;
    }
    smartScriptUpdate();
    return true;
}

function smartScriptUpdate(selector) {
    if (!selector) selector = document;
    jQuery(selector).find(".autoDateField").dateField();
    jQuery(selector).find(".autoCurrencyField").currencyField();
    jQuery(selector).find(".autoTimeField").timeField();
    jQuery(selector).find(".autoDecimalField").decimalField();
    jQuery(selector).find("input[type=button], input[type=submit]").addClass("fbutton").hover(function() { jQuery(this).addClass("fbutton_hover"); }, function() { jQuery(this).removeClass("fbutton_hover"); });
    jQuery(selector).find("input[type=text]:not(.ftext), input[type=password]:not(.ftext), textarea:not(.ftext)").addClass("ftext").focus(function() { jQuery(this).addClass("ftext_focus"); }).blur(function() { jQuery(this).removeClass("ftext_focus"); });
    jQuery(selector).find(".autoMCEEditor").each(function(i) { if (!tinyMCE.get(this.id)) tinyMCE.execCommand('mceAddControl', false, this.id); });
    //if (!document.dropShadowsDisabled) { jQuery(selector).find(".autoDropShadow").jDropShadow({ thickness: 5, opacity: 0.1, color: "#333333" }); }
    //jQuery(selector).find(".autoDropShadow").wrap('<div class="wrap1"><div class="wrap2"><div class="wrap3"></div></div></div>');
    jQuery(selector).find("input[type=text][prmGhost!=]").each(function(i) {
        var t = jQuery(this);
        if (t.val() == "") t.addClass("ftext_ghost").val(t.attr("prmGhost"));
        t.focus(function() { var z = jQuery(this); if (z.val() == z.attr("prmGhost") && t.hasClass("ftext_ghost")) z.removeClass("ftext_ghost").val(""); });
        t.blur(function() { var z = jQuery(this); if (z.val() == "") z.addClass("ftext_ghost").val(z.attr("prmGhost")); });
    });
}

function clearMCEInstances(selector) {
    if (!selector) {
        jQuery(".autoMCEEditor").each(function(i) { if (tinyMCE.get(this.id)) tinyMCE.execCommand('mceRemoveControl', false, this.id); });
    } else {
        jQuery(selector).find(".autoMCEEditor").each(function(i) { if (tinyMCE.get(this.id)) tinyMCE.execCommand('mceRemoveControl', false, this.id); });
    }
}

// *****************************************************************************************
// *****************************************************************************************
// COMMON JQUERY EXTENSION OR RELATED FUNCTIONS
// *****************************************************************************************
// *****************************************************************************************

jQuery.formatDate = function(str) {
    if (str != "") {
        str = str.toString();
        var parts = str.split(/[-\/]/);
        if (parts.length == 3) {
            // month/day/year
            var m = parseInt(parts[0], 10);
            var d = parseInt(parts[1], 10);
            var y = parseInt(parts[2], 10);
            if (m > 12 || m < 1) {
                // alternate form YYYY-mm-dd
                y = parseInt(parts[0], 10);
                m = parseInt(parts[1], 10);
                d = parseInt(parts[2], 10);
            }
            if (!isNaN(m) && !isNaN(d) && !isNaN(y) && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
                if (y < 100 && y >= 70) {
                    y += 1900;
                } else if (y < 70) {
                    y += 2000;
                } else if (y < 1800) {
                    y = (y % 100) + 2000;
                }
                return (m + "/" + d + "/" + y);
            } else {
                return "";
            }
        } else if (parts.length == 2) {
            // only month/day
            var m = parseInt(parts[0], 10);
            var d = parseInt(parts[1], 10);
            if (!isNaN(m) && !isNaN(d) && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
                var y = new Date().getYear();
                if (y < 1900) y += 1900; // firefox fix?
                return (m + "/" + d + "/" + y);
            } else {
                return "";
            }
        } else {
            // unknown...reset
            return "";
        }
    } else return "";
};

jQuery.fn.dateField = function() {
    return this.each(function() {
        if (jQuery(this).attr("autoDateFieldEnabled")) return; // already enabled
        jQuery(this).attr("autoDateFieldEnabled", true);
        /*
        jQuery(this).after("<img src=\"images/cal.gif\" id=\"datetrigger" + this.id + "\" align=\"absmiddle\" style=\"cursor: pointer; border: 1px solid black; margin-right: 8px;\" title=\"Date selector\" />");
        Calendar.setup({inputField: this.id, ifFormat: "%m/%d/%Y", button: "datetrigger" + this.id, align:"bR", singleClick:true});
        jQuery("#datetrigger" + this.id).mouseover(function() { this.style.borderColor="#FF0000"; }).mouseout(function() { this.style.borderColor="#000000"; });
        */
        jQuery(this).datePicker({startDate: '01/01/1970'});
        jQuery(this).change(function() {
            if (jQuery(this).attr("prmFormat")) {
                var tD = new Date(jQuery.formatDate(jQuery(this).val()));
                jQuery(this).val(tD.formatDate(jQuery(this).attr("prmFormat")));
            } else {
                jQuery(this).val(jQuery.formatDate(jQuery(this).val()));
            }
        });
    });
};

jQuery.fn.jDropShadow = function(args) {
    if (!args) args = new Object();
    if (!args.opacity) args.opacity = 0.1;
    if (!args.thickness) args.thickness = 5;
    if (!args.color) args.color = "#000000";
    return this.each(function(i) {
        var d = jQuery(this);
        var x = d.offset().left, y = d.offset().top, w = d.outerWidth(), h = d.outerHeight();
        var tx, ty, tw, th, id;
        var thick = 4;
        for (var j = 0; j < args.thickness; j++) {
            id = "ddshadowx_" + new Date().getTime() + "_" + j + "_" + i;
            jQuery("body").append('<div id="' + id + 'b" class="appliedDropShadowX"></div>');
            tx = x + j + 3; ty = y + h; tw = w - 2; th = j;
            //if (jQuery.browser.msie) tx--;
            tx--;
            jQuery("#" + id + "b").css("left", tx + "px").css("top", ty + "px").width(tw).height(th);
            jQuery("body").append('<div id="' + id + 'r" class="appliedDropShadowX"></div>');
            tx = x + w + 1; ty = y + j + 2; tw = j; th = h - j - 2;
            //if (jQuery.browser.msie) tx--;
            tx--;
            jQuery("#" + id + "r").css("left", tx + "px").css("top", ty + "px").width(tw).height(th);
        }
        jQuery(".appliedDropShadowX").css("position", "absolute").css("background-color", args.color).css("opacity", args.opacity);
    });
};

/*var jDropShadowTimeout = false;
var jDropShadowsHidden = false;
jQuery(window).resize(function() {
    if (!document.dropShadowsDisabled) {
        if (!jDropShadowsHidden) { jQuery(".appliedDropShadowX").remove(); jDropShadowsHidden = true; }
        if (jDropShadowTimeout) clearTimeout(jDropShadowTimeout);
        jDropShadowTimeout = setTimeout('jDropShadowsHidden = false; jQuery(".autoDropShadow").jDropShadow({ thickness: 5, opacity: 0.1, color: "#333333" });', 25);
    }
});*/

jQuery.formatDecimal = function(str, places, zerofill) {
    if (typeof str != 'string' || str.length > 0) {
        str = str.toString();
        var number = parseFloat(str.replace(/[^0-9\.\-]/g, ''));
        var dec = 0;
        if (isNaN(number)) number = 0;
        if (!places || isNaN(places) || places < 0) places = 2;
        var sign = (Math.abs(number) == number);
        number = Math.abs(number);
        dec = Math.round(number * Math.pow(10, places)) - (Math.floor(number) * Math.pow(10, places));
        if (dec >= Math.pow(10, places)) { number++; dec -= Math.pow(10, places); }
        if (!zerofill) while (dec != 0 && dec / 10 == Math.floor(dec / 10)) dec /= 10;
        if (zerofill && dec == 0) {
            dec = "";
            for (var z = 0; z < places; z++) dec += "" + "0";
        }
        while (dec.toString().length < places) dec = "0" + "" + dec;
        number = Math.floor(number).toString();
        for (var i = 0; i < Math.floor((number.length - (1 + i)) / 3); i++)
            number = number.substring(0, number.length - (4 * i + 3)) + ',' + number.substring(number.length - (4 * i + 3));
        return ((sign ? "" : "-") + (number + ((dec != 0 || zerofill) ? ("." + dec) : "")));
    } else return "";
};

jQuery.fn.decimalField = function() {
    return this.each(function() {
        if (jQuery(this).attr("autoDecimalFieldEnabled")) return; // already enabled
        jQuery(this).attr("autoDecimalFieldEnabled", true);
        jQuery(this).change(function() {
            jQuery(this).val(jQuery.formatDecimal(jQuery(this).val(), parseInt(jQuery(this).attr("tag"))));
        }).css("text-align", "right");
    });
};

jQuery.formatCurrency = function(str) {
    if (typeof str != 'string' || str.length > 0) {
        str = str.toString();
        var amount = parseFloat(str.replace(/[^0-9\.\-]/g, ''));
        if (isNaN(amount)) amount = 0;
        var sign = (amount == Math.abs(amount));
        return (((sign) ? '' : '-') + '$' + jQuery.formatDecimal(Math.abs(amount), 2, true));
    } else return "";
};

jQuery.fn.currencyField = function() {
    return this.each(function() {
        if (jQuery(this).attr("autoCurrencyFieldEnabled")) return; // already enabled
        jQuery(this).attr("autoCurrencyFieldEnabled", true);
        jQuery(this).change(function() {
            jQuery(this).val(jQuery.formatCurrency(jQuery(this).val()));
        }).css("text-align", "right");
    });
};

jQuery.formatTime = function(str) {
    if (str != "") {
        var parts = jQuery.trim(str.replace(/\s+/, " ")).split(/[: ]/);
        var num, h = 0, m = 0, s = 0, assumePM = false, detail = 0, timeStr = "", pmStr = "";
        for (var i = 0; i < parts.length; i++) {
            num = parseInt(parts[i]);
            if (i == 0) {           // hours first
                if (isNaN(num) || num < 0 || num > 23) { timeStr = ""; break; }
                else if (num > 12) { h = num - 12; pmStr = " PM"; }
                else if (num == 0) { h = 12; pmStr = " AM"; }
                else h = num;
                timeStr += (h + 0);
                if (h < 8 || h == 12) assumePM = true;
                detail++;
            } else if (i == 1) {    // then minutes, if supplied
                if (isNaN(num) || num < 0 || num > 59) break;
                else m = num;
                timeStr += ":" + ((m < 10) ? "0" : "") + m;
                detail++;
            } else if (i == 2) {    // then seconds, if supplied
                if (isNaN(num) || num < 0 || num > 59) break;
                else s = num;
                timeStr += ":" + ((s < 10) ? "0" : "") + s;
                detail++;
            }
        }
        if (timeStr != "") {
            if (detail < 2) timeStr += ":00";   // add minutes
            //if (detail < 3) timeStr += ":00";   // add seconds
            if (pmStr != "") timeStr += pmStr;
            else timeStr += (str.match(/(pm|p)/i) || (assumePM && !str.match(/(am|a)/i))) ? " PM" : " AM";
        }
        return timeStr;
    } else return "";
};

jQuery.fn.timeField = function() {
    return this.each(function() {
        if (jQuery(this).attr("autoTimeFieldEnabled")) return; // already enabled
        jQuery(this).attr("autoTimeFieldEnabled", true);
        jQuery(this).change(function() {
            jQuery(this).val(jQuery.formatTime(jQuery(this).val()));
        });
    });
};

jQuery.combineMap = function(map1, map2) {
    var newMap = map1;
    for (i in map2) newMap[i] = map2[i];
    return newMap;
};

jQuery.buildSmartInputMap = function(selector, ignoreParams) {
    var map = { };
    var ed = false;
    var obj = jQuery(selector).find("input[type!=button], select, textarea");
    for (var i = 0; i < obj.length; i++) {
        with (obj[i]) {
            if (type == "select-multiple") {
                var sel = Array();
                for (j = 0; j < options.length; j++) {
                    if (options[j].selected) sel.push(options[j]);
                }
                map[id] = sel;
            } else if (type == "textarea") {
                if (!((ed = tinyMCE.get(id)) && (map[id] = ed.getContent()))) map[id] = jQuery(obj[i]).val();
            } else if (type == "checkbox") {
                if (checked) map[id] = value;
                else map[id] = "";
            } else if (type == "radio") {
                if (!map[name] && checked) map[name] = value;
            } else {
                map[id] = value;
            }
        }
        if (!ignoreParams && !jQuery(obj[i]).attr("disabled") && jQuery(obj[i]).attr("visibility") != "hidden") {
            if (jQuery(obj[i]).attr("prmRequired") == "yes" && map[obj[i].id] == "") {
                obj[i].focus();
                var label = jQuery("label[for=" + obj[i].id + "]");
                var title = jQuery(obj[i]).attr("prmTitle");
                if (!title) title = label.length > 0 ? label.text() : "current";
                if (obj[i].type == "checkbox") {
                    alert("Please check the '" + title + "' box.");
                } else {
                    alert("Please enter a value for the '" + title + "' field.");
                }
                return false;
            }
            if (jQuery(obj[i]).attr("prmMinimum") && parseFloat(map[obj[i].id]) < jQuery(obj[i]).attr("prmMinimum")) {
            }
            if (jQuery(obj[i]).attr("prmMaximum") && parseFloat(map[obj[i].id]) > jQuery(obj[i]).attr("prmMaximum")) {
            }
        }
    }
    return map;
};

var jScrollFollowLastPosition = false;
var jScrollFollowList = new Array();
var jScrollFollowSpeed = new Array();
var jScrollFollowTimeout = false;
var jScrollFollowUpdate = function() {
    for (var i = 0; i < jScrollFollowList.length; i++) {
        if (!jQuery("#" + jScrollFollowList[i].id).attr("fixedPos"))
            jScrollFollowList[i].func(jQuery("#" + jScrollFollowList[i].id), jScrollFollowList[i].left, jScrollFollowList[i].top, jScrollFollowSpeed[i]);
    }
};
jQuery.fn.jScrollFollow = function(left, top, speed) {
    if (speed == null) speed = "fast";
    if (!jScrollFollowLastPosition) {
        jScrollFollowLastPosition = 0;
        jQuery(window).scroll(function() {
            if (jScrollFollowTimeout) clearTimeout(jScrollFollowTimeout);
            jScrollFollowTimeout = setTimeout('jScrollFollowUpdate();', 150);
        });
        jQuery(window).resize(function() {
            if (jScrollFollowTimeout) clearTimeout(jScrollFollowTimeout);
            jScrollFollowTimeout = setTimeout('jScrollFollowUpdate();', 150);
        });
    }
    return this.each(function() {
        if (jQuery(this).attr("scrollFollowEnabled")) { jScrollFollowUpdate(); return; } // already enabled
        jQuery(this).attr("scrollFollowEnabled", true);
        jQuery(this).scrollFollowEnabled = true;
        var pos;
        if (left >= 0 && top >= 0) { pos = jPosition.windowTopLeft; }
        else if (left >= 0 && top < 0) { pos = jPosition.windowBottomLeft; top = -top; }
        else if (left < 0 && top >= 0) { pos = jPosition.windowTopRight; left = -left; }
        else { pos = jPosition.windowBottomRight; left = -left; top = -top; }
        jScrollFollowList.push({ id: this.id, func: pos, left: left, top: top });
        jScrollFollowSpeed.push(speed);
        jScrollFollowUpdate();
    });
};

var jHoverFadeList = new Array();
var jHoverFadeOn = new Array();
var jHoverFadeOff = new Array();
jQuery.fn.jHoverFade = function(level, speedOut, speedIn, off, on) {
    if (level == null) level = 0.2;
    if (speedOut == null) speedOut = 100;
    if (speedIn == null) speedIn = 200;
    return this.each(function() {
        if (jQuery(this).attr("hoverFadeEnabled")) return; // already enabled
        jQuery(this).attr("hoverFadeEnabled", true);
        jQuery(this).attr("hoverFadeLevel", level);
        jQuery(this).attr("hoverFadeSpeedIn", speedIn);
        jQuery(this).attr("hoverFadeSpeedOut", speedOut);
        jQuery(this).attr("hoverFadeLevelOriginal", jQuery(this).css("opacity"));
        jHoverFadeList.push(this.id);
        jHoverFadeOff.push(off);
        jHoverFadeOn.push(on);
        jQuery(this).hover(function() {
            var l = jQuery(this).attr("hoverFadeLevelOriginal");
            var s = jQuery(this).attr("hoverFadeSpeedOut");
            var n = jHoverFadeOn[jHoverFadeList.inArray(this.id)];
            if (s == 0) {
                jQuery(this).css("opacity", l); if (n) n();
            } else {
                jQuery(this).fadeTo(s, l, n ? n : null);
            }
        }, function() {
            var l = jQuery(this).attr("hoverFadeLevel");
            var s = jQuery(this).attr("hoverFadeSpeedIn");
            var n = jHoverFadeOff[jHoverFadeList.inArray(this.id)];
            if (n) n();
            if (s == 0) jQuery(this).css("opacity", l); else jQuery(this).fadeTo(s, l);
        });
    });
};

var jQueryNegativeCoverTimeout = null;
var jQueryNegativeCoverDisabledList = null;
jQuery(window).resize(function() {
    if (jQueryNegativeCoverTimeout) clearTimeout(jQueryNegativeCoverTimeout);
    jQueryNegativeCoverTimeout = setTimeout('jQuery("[negativeCoverEnabled]").negativeCover();', 250);
});
jQuery.fn.negativeCover = function(color, frame, opacity) {
    return this.each(function() {
        if (!jQuery(this).attr("negativeCoverEnabled")) {
            if (!color) color = "#000066";
            if (!frame) frame = "#FFFF00";
            if (!opacity) opacity = 0.5;
            var d = new Date();
            var id = "jNegativeCover" + Math.floor(Math.random(10000)) + "" + d.getTime();
            jQuery("body").append("<div id=\"" + id + "_1\"></div><div id=\"" + id + "_2\"></div><div id=\"" + id + "_3\"></div><div id=\"" + id + "_4\"></div>");
            jQuery(this).attr("negativeCoverId", id);
            jQuery(this).attr("negativeCoverColor", color);
            jQuery(this).attr("negativeCoverFrame", frame);
            jQuery(this).attr("negativeCoverOpacity", opacity);
        } else {
            var id = jQuery(this).attr("negativeCoverId");
            if (!color) color = jQuery(this).attr("negativeCoverColor");
            if (!frame) frame = jQuery(this).attr("negativeCoverFrame");
            if (!opacity) opacity = jQuery(this).attr("negativeCoverOpacity");
        }
        jQuery(this).attr("negativeCoverEnabled", true);

        var z = parseInt(jQuery(this).css("z-index"));
        if (isNaN(z)) z = 1; else z++;
        var z2 = z - 2;
        var s = jQuery("div[id^=" + id + "]").css("position", "absolute").css("opacity", opacity).css("background-color", color).css("z-index", z).hide();
        var fullWidth = jQuery(document).innerWidth();
        var fullHeight = jQuery(document).innerHeight();
        if (jQuery(window).outerWidth() > fullWidth) fullWidth = jQuery(window).outerWidth();
        if (jQuery(window).outerHeight() > fullHeight) fullHeight = jQuery(window).outerHeight();

        // this part shouldn't happen more than once, we hope...would this ever be called more than once at a time?
        if (!resizeOnly) {
            if (!jQueryNegativeCoverDisabledList) jQueryNegativeCoverDisabledList = jQuery(":disabled");
            jQuery("a, input, textarea, select, iframe").attr("disabled", true);
            jQuery(this).find("*").attr("disabled", false);
            jQueryNegativeCoverDisabledList.attr("disabled", true);
        }

        s.show();
        jQuery(s[0]).width(jQuery(this).offset().left).height(fullHeight).css("left", "0").css("top", "0");
        jQuery(s[1]).width(fullWidth - (jQuery(this).offset().left + jQuery(this).outerWidth())).height(fullHeight).css("left", (jQuery(this).offset().left + jQuery(this).outerWidth())).css("top", "0");
        jQuery(s[2]).width(jQuery(this).outerWidth()).height(jQuery(this).offset().top).css("left", jQuery(this).offset().left).css("top", "0");
        jQuery(s[3]).width(jQuery(this).outerWidth()).height(fullHeight - (jQuery(this).offset().top + jQuery(this).outerHeight())).css("left", jQuery(this).offset().left).css("top", (jQuery(this).offset().top + jQuery(this).outerHeight()));
    });
};

jQuery.fn.negativeUncover = function() {
    if (jQueryNegativeCoverDisabledList) {
        jQuery(":disabled").attr("disabled", false);
        jQueryNegativeCoverDisabledList.attr("disabled", true);
        jQueryNegativeCoverDisabledList = null;
    }
    return this.each(function() {
        if (jQuery(this).attr("negativeCoverEnabled")) {
            var id = jQuery(this).attr("negativeCoverId");
            jQuery("div[id^=" + id + "]").remove();
            jQuery(this).attr("negativeCoverId", false);
            jQuery(this).attr("negativeCoverEnabled", false);
        }
    });
};

var jQueryDocumentCoverTimeout = null;
var jQueryDocumentCoverDisabledList = null;
jQuery(window).resize(function() {
    if (jQuery("#jDocumentCoverDiv:visible").length > 0) {
        if (jQueryDocumentCoverTimeout) clearTimeout(jQueryDocumentCoverTimeout);
        jQueryDocumentCoverTimeout = setTimeout('if (jQuery("#jDocumentCoverDiv:visible").length > 0) jQuery.documentCover();', 250);
    }
});
jQuery.documentCover = function(message, color, opacity, z) {
    var d = jQuery("#jDocumentCoverDiv");
    var m = jQuery("#jDocumentCoverMessageDiv");
    if (d.length < 1) {
        if (!color) color = "#000066";
        if (!opacity && opacity !== 0) opacity = 0.5;
        if (!z) z = 900;
        jQuery("body").append("<div id=\"jDocumentCoverDiv\"></div>");
        if (message) {
            jQuery("body").append("<div id=\"jDocumentCoverMessageDiv\"></div>");
            m = jQuery("#jDocumentCoverMessageDiv");
        }
        d = jQuery("#jDocumentCoverDiv");
        d.attr("documentCoverColor", color);
        d.attr("documentCoverOpacity", opacity);
    } else {
        if (!color) color = d.attr("documentCoverColor");
        if (!opacity && opacity !== 0) opacity = d.attr("documentCoverOpacity");
        if (!z) z = d.css("z-index");
        if (!message && m.length > 0) message = m.html();
    }
    d.css("position", "absolute").css("left", "0").css("top", "0").css("opacity", opacity).css("background-color", color).css("z-index", z).hide();
    var fullWidth = jQuery(document).width();
    var fullHeight = jQuery(document).height();
    if (jQuery(window).width() > fullWidth) fullWidth = jQuery(window).width();
    if (jQuery(window).height() > fullHeight) fullHeight = jQuery(window).height();
    if (m.length > 0 && message) {
        //alert(m.length + "\n" + message + "\n" + z);
        m.css("position", "absolute").css("background-color", "#FFFFFF").css("color", "#000000").css("text-align", "center").css("padding", "16px").css("z-index", z + 1).css("border", "1px solid #000");
        m.width(180).html(message).show();
        jPosition.windowCenter(m, 0, 0);
    }

    if (!jQueryDocumentCoverDisabledList) jQueryDocumentCoverDisabledList = jQuery(":disabled");
    jQuery("a, input, textarea, select, iframe").attr("disabled", true);
    d.show().width(fullWidth).height(fullHeight);
};

jQuery.documentUncover = function() {
    jQuery("#jDocumentCoverDiv").hide();
    jQuery("#jDocumentCoverMessageDiv").hide();
    if (jQueryDocumentCoverDisabledList) {
        jQuery(":disabled").attr("disabled", false);
        jQueryDocumentCoverDisabledList.attr("disabled", true);
        jQueryDocumentCoverDisabledList = null;
    }
};

jQuery.fn.clickToggle = function(toggle, showText, hideText) {
    return this.each(function() {
        jQuery(this).attr("clickToggleSelector", toggle);
        jQuery(this).attr("clickToggleShowText", showText);
        jQuery(this).attr("clickToggleHideText", hideText);
        jQuery(this).click(function() {
            jQuery(jQuery(this).attr("clickToggleSelector")).toggle();
            jQuery(this).html(jQuery(this).attr(jQuery(jQuery(this).attr("clickToggleSelector")).css("display") == "none" ? "clickToggleShowText" : "clickToggleHideText"));
        });
    });
};

// *****************************************************************************************
// *****************************************************************************************
// JPOPUP FUNCTIONS
// *****************************************************************************************
// *****************************************************************************************

// jPopup and jMessage, v1.0
// Pretty ways to alert the user to stuff that's going on
// Jeff Rowberg <jeff@rowberg.net> - April 6, 2008
// http://www.sectorfej.net/jpopup

// Use it, have fun with it, modify it...just don't say you
// wrote it unless you actually totally do rewrite it.

// NOTE: Requires jQuery >= 1.2 (built around 1.2.1)
// http://www.jquery.com/

// ********************************************************

// Behavioral settings located at bottom of file

// ============-------------------
// CONSTANTS - DON'T CHANGE THESE!
// ============-------------------
var JPOPUP_BTN_OK = 0, JPOPUP_BTN_OKCANCEL = 1, JPOPUP_BTN_YESNO = 2, JPOPUP_BTN_YESNOCANCEL = 3, JPOPUP_BTN_CUSTOM = 10;
var JPOPUP_ICON_QUESTION = 0, JPOPUP_ICON_ALERT = 1, JPOPUP_ICON_ERROR = 2, JPOPUP_ICON_INFO = 3;
var JPOPUP_RESPONSE_OK = 0, JPOPUP_RESPONSE_CANCEL = 1, JPOPUP_RESPONSE_YES = 2, JPOPUP_RESPONSE_NO = 3;
var JMESSAGE_UPDATE = 0, JMESSAGE_ERROR = 1, JMESSAGE_SUCCESS = 2, JMESSAGE_NOTICE = 3;
var JMESSAGE_POS_TOPLEFT = 0, JMESSAGE_POS_TOPRIGHT = 1, JMESSAGE_POS_BOTTOMLEFT = 2, JMESSAGE_POS_BOTTOMRIGHT = 3;

// ====================
// ON TO THE GOOD STUFF
// ====================
var jPopupZIndex = 1500;
var jPopupRef = new Array();
var jMessageOffset = 0;
var jMessageRef = new Array();
var jMessageScrollTimeout = false;
var jMessageResizeTimeout = false;

jQuery(window).scroll(function() {
    if (jMessageScrollTimeout) clearTimeout(jMessageScrollTimeout);
    jMessageScrollTimeout = setTimeout("jPopupScrollAssist();", 180);
});

jQuery(window).resize(function() {
    if (jMessageResizeTimeout) clearTimeout(jMessageResizeTimeout);
    jMessageResizeTimeout = setTimeout("jPopupResizeAssist();", 180);
});

function jPopupScrollAssist() {
    if (jPopupRef.length > 0)
        for (var i = 0; i < jPopupRef.length; i++)
            if (!jQuery("#" + jPopupRef[i].id).attr("fixedPos") && !jPopupRef[i].left && !jPopupRef[i].top) jPosition.windowCenter(jQuery("#" + jPopupRef[i].id), 0, -32, jPopupScrollSpeed);
    if (jMessageRef.length > 0)
        for (var i = 0; i < jMessageRef.length; i++)
            jMessagePositionFunction(jQuery("#" + jMessageRef[i].id), jMessagePadHoriz, jMessageRef[i].top, jMessageScrollSpeed);
    jMessageScrollTimeout = null;
}

function jPopupResizeAssist() {
    if (jPopupRef.length > 0)
        for (var i = 0; i < jPopupRef.length; i++) {
            if (!jPopupRef[i].left && !jPopupRef[i].top)
                jPosition.windowCenter(jQuery("#" + jPopupRef[i].id), 0, -32, jPopupScrollSpeed);
            var fullWidth = jQuery(document).width();
            var fullHeight = jQuery(document).height();
            if (jQuery(window).width() > fullWidth) fullWidth = jQuery(window).width();
            if (jQuery(window).height() > fullHeight) fullHeight = jQuery(window).height();
            jQuery("#" + jPopupRef[i].id + "_fade").width(fullWidth).height(fullHeight);
        }
    if (jMessageRef.length > 0)
        for (var i = 0; i < jMessageRef.length; i++)
            jMessagePositionFunction(jQuery("#" + jMessageRef[i].id), jMessagePadHoriz, jMessageRef[i].top, jMessageScrollSpeed);
    jMessageResizeTimeout = null;
}

function jPopup(body, title, type, callback, width, left, top) {
    d = new Date();
    var id = "jpopup" + Math.floor(Math.random(10000)) + "" + d.getTime();

    if (!title) title = jPopupDefaultTitle;
    if (!type) type = jPopupDefaultType;
    if (!callback) callback = jPopupDefaultCallback;
    if (!width) width = jPopupDefaultWidth;

    jQuery("body").append("<div id=\"" + id + "\" class=\"jPopupDiv\" style=\"display: none;\"></div>");
    jQuery("body").append("<div id=\"" + id + "_fade\" class=\"jPopupFade\" style=\"display: none;\"></div>");

    var p = jQuery("#" + id).css("z-index", jPopupZIndex + 2).css("opacity", 0).show(); // show required for auto-width

    p.append("<div id=\"" + id + "_title\" class=\"jPopupTitle\">" + title + "</div>");
    p.append("<div id=\"" + id + "_body\" class=\"jPopupBody\"><span id=\"" + id + "_bodyspan\">" + body + "</span></div>");

    var b = jQuery("#" + id + "_body");
    var s = jQuery("#" + id + "_bodyspan");

    // use 75% of window if 0 passed
    if (width == 0) width = -Math.floor(parseInt(jPosition.o().innerWidth) * .75);

    if (width < 0) { // autosize up to maximum -width
        if (s.paddedWidth() + 40 < -width) width = s.paddedWidth() + 40;
        else width = -width;
    }
    p.width(width);

    if (!left && !top) {
        jPosition.windowCenter(p, 0, -32);
    } else {
        if (!top) top = 30;
        if (!left) left = 40;
        p.css("left", left).css("top", top);
    }

    jPopupRef.push({ id: id, left: left, top: top });

    var btnDiv = '<div class="jPopupButtonContainer">';
    var focus = "";
    switch (type) {
        case JPOPUP_BTN_OK:
            btnDiv += '<input id="' + id + '_btnOK" type="button" class="jPopupButton" value="OK" />';
            focus = "_btnOK";
            break;
        case JPOPUP_BTN_OKCANCEL:
            btnDiv += '<input id="' + id + '_btnOK" type="button" class="jPopupButton" value="OK" />';
            btnDiv += '<input id="' + id + '_btnCancel" type="button" class="jPopupButton" value="Cancel" />';
            focus = "_btnOK";
            break;
        case JPOPUP_BTN_YESNO:
            btnDiv += '<input id="' + id + '_btnYes" type="button" class="jPopupButton" value="Yes" />';
            btnDiv += '<input id="' + id + '_btnNo" type="button" class="jPopupButton" value="No" />';
            focus = "_btnYes";
            break;
        case JPOPUP_BTN_YESNOCANCEL:
            btnDiv += '<input id="' + id + '_btnYes" type="button" class="jPopupButton" value="Yes" />';
            btnDiv += '<input id="' + id + '_btnNo" type="button" class="jPopupButton" value="No" />';
            btnDiv += '<input id="' + id + '_btnCancel" type="button" class="jPopupButton" value="Cancel" />';
            focus = "_btnYes";
            break;
        case JPOPUP_BTN_CUSTOM:
            if (options.customButtons) {
                for (var item in options.customButtons) {
                    alert(item + "=" + fieldData[item]);
                }
            } else {
                // failsafe
                btnDiv += '<input id="' + id + '_btnOK" type="button" class="jPopupButton" value="OK" />';
                focus = "_btnOK";
            }
            break;
    }
    btnDiv += '</div>';
    b.append(btnDiv);

    jQuery(".appliedDropShadowX").hide();

    if (jPopupEnableSmooth) {
        jQuery("#" +  id + "_btnOK").click(function() { if (callback(JPOPUP_RESPONSE_OK)) jQuery("#" + id + ", #" + id + "_fade").fadeOut(jPopupFadeOutSpeed, function() { jQuery(this).remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }); }).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnCancel").click(function() { if (callback(JPOPUP_RESPONSE_CANCEL)) jQuery("#" + id + ", #" + id + "_fade").fadeOut(jPopupFadeOutSpeed, function() { jQuery(this).remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }); }).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnYes").click(function() { if (callback(JPOPUP_RESPONSE_YES)) jQuery("#" + id + ", #" + id + "_fade").fadeOut(jPopupFadeOutSpeed, function() { jQuery(this).remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }); }).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnNo").click(function() { if (callback(JPOPUP_RESPONSE_NO)) jQuery("#" + id + ", #" + id + "_fade").fadeOut(jPopupFadeOutSpeed, function() { jQuery(this).remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }); }).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
    } else {
        jQuery("#" +  id + "_btnOK").click(function() { if (callback(JPOPUP_RESPONSE_OK)) { jQuery("#" + id + ", #" + id + "_fade").remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }}).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnCancel").click(function() { if (callback(JPOPUP_RESPONSE_CANCEL)) { jQuery("#" + id + ", #" + id + "_fade").remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }}).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnYes").click(function() { if (callback(JPOPUP_RESPONSE_YES)) { jQuery("#" + id + ", #" + id + "_fade").remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }}).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
        jQuery("#" +  id + "_btnNo").click(function() { if (callback(JPOPUP_RESPONSE_NO)) { jQuery("#" + id + ", #" + id + "_fade").remove(); jQuery(".appliedDropShadowX").show(); jPopupZIndex -= 10; jQuery(window).resize(); }}).hover(function() { jQuery(this).addClass("jPopupButtonHover"); }, function() { jQuery(this).removeClass("jPopupButtonHover"); }).attr("disabled", false);
    }

    if (jPopupEnableModal) {
        var fullWidth = jQuery(document).width();
        var fullHeight = jQuery(document).height();
        if (jQuery(window).width() > fullWidth) fullWidth = jQuery(window).width();
        if (jQuery(window).height() > fullHeight) fullHeight = jQuery(window).height();
        var c = jQuery("#" + id + "_fade").width(fullWidth).height(fullHeight).css("z-index", jPopupZIndex + 1).css("opacity", 0).show();
    }

    jPopupZIndex += 10;
    if (jPopupEnableSmooth) {
        if (jPopupEnableModal) c.fadeTo(jPopupFadeInSpeed, 0.5);
        p.fadeTo(jPopupFadeInSpeed, 1);
    } else {
        if (jPopupEnableModal) c.css("opacity", 0.5);
        p.css("opacity", 1);
    }

    jQuery("#" + id + "_title").mousedown(function(e) {
        document.dragRefMouseX = e.pageX;
        document.dragRefMouseY = e.pageY;
        document.dragRefObjectX = jQuery(this).parent().offset().left;
        document.dragRefObjectY = jQuery(this).parent().offset().top;
        document.dragRefObject = jQuery(this).parent();
        document.dragRefOn = true;
        jQuery(this).parent().attr("fixedPos", "yes");
    });

    jQuery("#" + id + focus).focus();
    return p;
}

jQuery(document).mousemove(function(e) {
    if (document.dragRefOn) {
        var mx = e.pageX + (document.dragRefObjectX - document.dragRefMouseX);
        var my = e.pageY + (document.dragRefObjectY - document.dragRefMouseY);
        document.dragRefObject.css("left", mx + "px").css("top", my + "px");
    }
});

jQuery(document).mouseup(function() { document.dragRefOn = false; });

function jMessage(message, type, duration, width) {
    d = new Date();
    var id = "jmessage" + Math.floor(Math.random(10000)) + "" + d.getTime();
    if (!type) type = jMessageDefaultType;
    if (!duration && duration !== 0) duration = jMessageDefaultDuration;
    if (!width) width = jMessageDefaultWidth;
    var cssClass = "";
    switch (type) {
        case JMESSAGE_UPDATE:  cssClass = "jMessageUpdate"; break;
        case JMESSAGE_ERROR:   cssClass = "jMessageError"; break;
        case JMESSAGE_SUCCESS: cssClass = "jMessageSuccess"; break;
        case JMESSAGE_NOTICE:  cssClass = "jMessageNotice"; break;
    }
    jQuery("body").append("<div id=\"" + id + "\" class=\"jMessageDiv " + cssClass + "\" style=\"display: none;\"></div>");
    var m = jQuery("#" + id).css("opacity", 0).show(); // to make auto-width work correctly
    m.append('<span id="' + id + '_closespan" class="jMessageCloseSpan"><a class="jMessageCloseLink" href="javascript:void();" onClick="jMessageOffset -= jQuery(\'#' + id + '\').paddedHeight(); jQuery(\'#' + id + '\').remove(); jMessageShiftUp(\'' + id + '\'); return false;">[X]</a></span>');
    m.append('<span id="' + id + '_span" class="jMessageSpan">' + message + '</span>');
    var cs = jQuery("#" + id + "_closespan");
    var s = jQuery("#" + id + "_span");
    if (width < 0) { // autosize up to maximum -width
        if (s.width() + cs.width() + 16 < -width) width = s.width() + cs.width() + 16;
        else width = -width;
    }
    m.width(width);
    jMessagePositionFunction(m, jMessagePadHoriz, jMessagePadVert + jMessageOffset);
    jMessageRef.push({ id: id, top: jMessagePadVert + jMessageOffset });
    jMessageOffset += m.paddedHeight();
    if (duration == 0) {
        if (jMessageEnableSmooth)
            m.fadeTo(jMessageFadeSpeed, jMessageOpacity);
        else
            m.css("opacity", jMessageOpacity);
    } else {
        if (jMessageEnableSmooth)
            m.fadeTo(jMessageFadeSpeed, jMessageOpacity, function() { setTimeout('jQuery("#' + id + '").fadeOut(jMessageFadeSpeed, function() { jMessageOffset -= jQuery(this).paddedHeight(); jQuery(this).remove(); jMessageShiftUp("' + id + '"); });', duration); });
        else {
            m.css("opacity", jMessageOpacity);
            setTimeout('jMessageOffset -= jQuery("#' + id + '").paddedHeight(); jQuery("#' + id + '").remove(); jMessageShiftUp("' + id + '");', duration);
        }
    }
    return m;
}

// removes a given message (or the top one if not specified) and slides the rest to fit
function jMessageShiftUp(id) {
    if (jMessageRef.length > 1) {
        var old = false, num;
        if (id) {
            for (var i = 0; i < jMessageRef.length; i++) if (jMessageRef[i].id == id) { old = jMessageRef.splice(i, 1); old = old[0]; num = i; break; }
        } else {
            old = jMessageRef.shift(); // take the top one
            num = 0;
        }
        if (num >= jMessageRef.length) return; // no shifting necessary
        var dist = jMessageRef[num].top - old.top;
        for (var i = num; i < jMessageRef.length; i++) {
            jMessageRef[i].top -= dist;
            jMessagePositionFunction(jQuery("#" + jMessageRef[i].id), jMessagePadHoriz, jMessageRef[i].top, jMessageSlideSpeed);
        }
    } else if (jMessageRef.length == 1) {
        jMessageRef.shift(); // just disappear, since it's the last one
    }
}

// returns full width, including padding
jQuery.fn.paddedWidth = function() {
    return jQuery(this).width() + parseInt(jQuery(this).css("padding-left")) + parseInt(jQuery(this).css("padding-right"));
};

// returns full height, including padding
jQuery.fn.paddedHeight = function() {
    return jQuery(this).height() + parseInt(jQuery(this).css("padding-top")) + parseInt(jQuery(this).css("padding-bottom"));
};

// modified and extended from "viewport" object of unknown origin--email me for credit
var jPosition = {
    o: function() {
        if (self.innerHeight) {
            this.pageYOffset = self.pageYOffset;
            this.pageXOffset = self.pageXOffset;
            this.innerHeight = self.innerHeight;
            this.innerWidth = self.innerWidth;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            this.pageYOffset = document.documentElement.scrollTop;
            this.pageXOffset = document.documentElement.scrollLeft;
            this.innerHeight = document.documentElement.clientHeight;
            this.innerWidth = document.documentElement.clientWidth;
        } else if (document.body) {
            this.pageYOffset = document.body.scrollTop;
            this.pageXOffset = document.body.scrollLeft;
            this.innerHeight = document.body.clientHeight;
            this.innerWidth = document.body.clientWidth;
        }
        this.leftEdge = this.pageXOffset;
        this.rightEdge = this.innerWidth + this.pageXOffset;
        this.topEdge = this.pageYOffset;
        this.bottomEdge = this.innerHeight + this.pageYOffset;
        return this;
    },
    windowCenter: function(el, padHoriz, padVert, speed) {
        if (speed && speed !== 0) jQuery(el).animate({
            left: Math.round(jPosition.o().innerWidth / 2) + jPosition.o().pageXOffset - Math.round(jQuery(el).paddedWidth() / 2) + padHoriz,
            top: Math.round(jPosition.o().innerHeight / 2) + jPosition.o().pageYOffset - Math.round(jQuery(el).paddedHeight() / 2) + padVert
            }, speed, "swing");
        else {
            jQuery(el).css("left", Math.round(jPosition.o().innerWidth / 2) + jPosition.o().pageXOffset - Math.round(jQuery(el).paddedWidth() / 2) + padHoriz);
            jQuery(el).css("top", Math.round(jPosition.o().innerHeight / 2) + jPosition.o().pageYOffset - Math.round(jQuery(el).paddedHeight() / 2) + padVert);
        }
    },
    windowTopLeft: function(el, padHoriz, padVert, speed) {
        if (!padHoriz || isNaN(padHoriz)) padHoriz = 0; if (!padVert || isNaN(padVert)) padVert = 0;
        if (speed && speed !== 0) jQuery(el).animate({
            left: jPosition.o().pageXOffset + padHoriz,
            top: jPosition.o().pageYOffset + padVert
            }, speed, "swing");
        else {
            jQuery(el).css("left", jPosition.o().pageXOffset + padHoriz);
            jQuery(el).css("top", jPosition.o().pageYOffset + padVert);
        }
    },
    windowTopRight: function(el, padHoriz, padVert, speed) {
        if (!padHoriz || isNaN(padHoriz)) padHoriz = 0; if (!padVert || isNaN(padVert)) padVert = 0;
        //alert("padHoriz: " + padHoriz + "\npadVert: " + padVert + "\noldTop: " + jQuery(el).css("top") + "\noldLeft: " + jQuery(el).css("left") + "\nXOffset: " + jPosition.o().pageXOffset + "\nYOffset: " + jPosition.o().pageYOffset);
        if (speed && speed !== 0) jQuery(el).animate({
            left: jPosition.o().innerWidth + jPosition.o().pageXOffset - (jQuery(el).paddedWidth() + padHoriz),
            top: jPosition.o().pageYOffset + padVert
            }, speed, "swing");
        else {
            jQuery(el).css("left", jPosition.o().innerWidth + jPosition.o().pageXOffset - (jQuery(el).paddedWidth() + padHoriz));
            jQuery(el).css("top", jPosition.o().pageYOffset + padVert);
        }
    },
    windowBottomLeft: function(el, padHoriz, padVert, speed) {
        if (!padHoriz || isNaN(padHoriz)) padHoriz = 0; if (!padVert || isNaN(padVert)) padVert = 0;
        if (speed && speed !== 0) jQuery(el).animate({
            left: jPosition.o().pageXOffset + padHoriz,
            top: jPosition.o().innerHeight + jPosition.o().pageYOffset - (jQuery(el).paddedHeight() + padVert)
            }, speed, "swing");
        else {
            jQuery(el).css("left", jPosition.o().pageXOffset + padHoriz);
            jQuery(el).css("top", jPosition.o().innerHeight + jPosition.o().pageYOffset - (jQuery(el).paddedHeight() + padVert));
        }
    },
    windowBottomRight: function(el, padHoriz, padVert, speed) {
        if (!padHoriz || isNaN(padHoriz)) padHoriz = 0; if (!padVert || isNaN(padVert)) padVert = 0;
        if (speed && speed !== 0) jQuery(el).animate({
            left: jPosition.o().innerWidth + jPosition.o().pageXOffset - (jQuery(el).paddedWidth() + padHoriz),
            top: jPosition.o().innerHeight + jPosition.o().pageYOffset - (jQuery(el).paddedHeight() + padVert)
            }, speed, "swing");
        else {
            jQuery(el).css("left", jPosition.o().innerWidth + jPosition.o().pageXOffset - (jQuery(el).paddedWidth() + padHoriz));
            jQuery(el).css("top", jPosition.o().innerHeight + jPosition.o().pageYOffset - (jQuery(el).paddedHeight() + padVert));
        }
    }
};

// =================
// BEHAVIOR SETTINGS
// =================
var jPopupEnableSmooth = false;      // whether to animate or just show (disable for slower clients)
var jPopupFadeInSpeed = 150;        // ignored if jPopupEnableSmooth = false
var jPopupFadeOutSpeed = 300;       // ignored if jPopupEnableSmooth = false
var jPopupScrollSpeed = 300;        // ignored if jPopupEnableSmooth = false
var jPopupDefaultTitle = "Alert";
var jPopupDefaultType = JPOPUP_BTN_OK;
var jPopupDefaultCallback = function() { return true; };
var jPopupDefaultWidth = 0;
var jPopupEnableModal = true;

var jMessageEnableSmooth = true;    // whether to animate or just show (disable for slower clients)
var jMessageOpacity = 0.9;          // between 0 and 1
var jMessagePadHoriz = 28;          // safe for vertical scrollbars
var jMessagePadVert = 8;
var jMessagePosition = JMESSAGE_POS_TOPRIGHT;
var jMessageFadeSpeed = 600;        // ignored if jMessageEnableSmooth = false
var jMessageSlideSpeed = 600;       // ignored if jMessageEnableSmooth = false
var jMessageScrollSpeed = 100;      // ignored if jMessageEnableSmooth = false
var jMessageDefaultType = JMESSAGE_UPDATE;
var jMessageDefaultDuration = 10000; // time to show, in milliseconds (set 0 for indefinite)
var jMessageDefaultWidth = -320;

// ==================
// LAST MODIFICATIONS
// ==================

if (!jPopupEnableSmooth) {
    jPopupScrollSpeed = false;
}

if (!jMessageEnableSmooth) {
    jMessageFadeSpeed = false;
    jMessageSlideSpeed = false;
    jMessageScrollSpeed = false;
}

switch (jMessagePosition) {
    case JMESSAGE_POS_TOPLEFT: jMessagePositionFunction = jPosition.windowTopLeft; break;
    case JMESSAGE_POS_TOPRIGHT: jMessagePositionFunction = jPosition.windowTopRight; break;
    case JMESSAGE_POS_BOTTOMLEFT: jMessagePositionFunction = jPosition.windowBottomLeft; break;
    case JMESSAGE_POS_BOTTOMRIGHT: jMessagePositionFunction = jPosition.windowBottomRight; break;
}


/* DATEPICKER PLUGIN */
/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 *
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 *
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 *
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 *
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 0;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
//Date.format = 'dd/mm/yyyy';
Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

    /**
     * Adds a given method under the given name
     * to the Date prototype if it doesn't
     * currently exist.
     *
     * @private
     */
    function add(name, method) {
        if( !Date.prototype[name] ) {
            Date.prototype[name] = method;
        }
    };

    /**
     * Checks if the year is a leap year.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.isLeapYear();
     * @result true
     *
     * @name isLeapYear
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isLeapYear", function() {
        var y = this.getFullYear();
        return (y%4==0 && y%100!=0) || y%400==0;
    });

    /**
     * Checks if the day is a weekend day (Sat or Sun).
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.isWeekend();
     * @result false
     *
     * @name isWeekend
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isWeekend", function() {
        return this.getDay()==0 || this.getDay()==6;
    });

    /**
     * Check if the day is a day of the week (Mon-Fri)
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.isWeekDay();
     * @result false
     *
     * @name isWeekDay
     * @type Boolean
     * @cat Plugins/Methods/Date
     */
    add("isWeekDay", function() {
        return !this.isWeekend();
    });

    /**
     * Gets the number of days in the month.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDaysInMonth();
     * @result 31
     *
     * @name getDaysInMonth
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getDaysInMonth", function() {
        return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
    });

    /**
     * Gets the name of the day.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayName();
     * @result 'Saturday'
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayName(true);
     * @result 'Sat'
     *
     * @param abbreviated Boolean When set to true the name will be abbreviated.
     * @name getDayName
     * @type String
     * @cat Plugins/Methods/Date
     */
    add("getDayName", function(abbreviated) {
        return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
    });

    /**
     * Gets the name of the month.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getMonthName();
     * @result 'Janurary'
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getMonthName(true);
     * @result 'Jan'
     *
     * @param abbreviated Boolean When set to true the name will be abbreviated.
     * @name getDayName
     * @type String
     * @cat Plugins/Methods/Date
     */
    add("getMonthName", function(abbreviated) {
        return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
    });

    /**
     * Get the number of the day of the year.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getDayOfYear();
     * @result 11
     *
     * @name getDayOfYear
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getDayOfYear", function() {
        var tmpdtm = new Date("1/1/" + this.getFullYear());
        return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
    });

    /**
     * Get the number of the week of the year.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.getWeekOfYear();
     * @result 2
     *
     * @name getWeekOfYear
     * @type Number
     * @cat Plugins/Methods/Date
     */
    add("getWeekOfYear", function() {
        return Math.ceil(this.getDayOfYear() / 7);
    });

    /**
     * Set the day of the year.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.setDayOfYear(1);
     * dtm.toString();
     * @result 'Tue Jan 01 2008 00:00:00'
     *
     * @name setDayOfYear
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("setDayOfYear", function(day) {
        this.setMonth(0);
        this.setDate(day);
        return this;
    });

    /**
     * Add a number of years to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addYears(1);
     * dtm.toString();
     * @result 'Mon Jan 12 2009 00:00:00'
     *
     * @name addYears
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addYears", function(num) {
        this.setFullYear(this.getFullYear() + num);
        return this;
    });

    /**
     * Add a number of months to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addMonths(1);
     * dtm.toString();
     * @result 'Tue Feb 12 2008 00:00:00'
     *
     * @name addMonths
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addMonths", function(num) {
        var tmpdtm = this.getDate();

        this.setMonth(this.getMonth() + num);

        if (tmpdtm > this.getDate())
            this.addDays(-this.getDate());

        return this;
    });

    /**
     * Add a number of days to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addDays(1);
     * dtm.toString();
     * @result 'Sun Jan 13 2008 00:00:00'
     *
     * @name addDays
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addDays", function(num) {
        this.setDate(this.getDate() + num);
        return this;
    });

    /**
     * Add a number of hours to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addHours(24);
     * dtm.toString();
     * @result 'Sun Jan 13 2008 00:00:00'
     *
     * @name addHours
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addHours", function(num) {
        this.setHours(this.getHours() + num);
        return this;
    });

    /**
     * Add a number of minutes to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addMinutes(60);
     * dtm.toString();
     * @result 'Sat Jan 12 2008 01:00:00'
     *
     * @name addMinutes
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addMinutes", function(num) {
        this.setMinutes(this.getMinutes() + num);
        return this;
    });

    /**
     * Add a number of seconds to the date object.
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.addSeconds(60);
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:01:00'
     *
     * @name addSeconds
     * @type Date
     * @cat Plugins/Methods/Date
     */
    add("addSeconds", function(num) {
        this.setSeconds(this.getSeconds() + num);
        return this;
    });

    /**
     * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
     *
     * @example var dtm = new Date();
     * dtm.zeroTime();
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:01:00'
     *
     * @name zeroTime
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    add("zeroTime", function() {
        this.setMilliseconds(0);
        this.setSeconds(0);
        this.setMinutes(0);
        this.setHours(0);
        return this;
    });

    /**
     * Returns a string representation of the date object according to Date.format.
     * (Date.toString may be used in other places so I purposefully didn't overwrite it)
     *
     * @example var dtm = new Date("01/12/2008");
     * dtm.asString();
     * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
     *
     * @name asString
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    add("asString", function() {
        var r = Date.format;
        return r
            .split('yyyy').join(this.getFullYear())
            .split('yy').join((this.getFullYear() + '').substring(2))
            .split('mmm').join(this.getMonthName(true))
            .split('mm').join(_zeroPad(this.getMonth()+1))
            .split('dd').join(_zeroPad(this.getDate()));
    });

    /**
     * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
     * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
     *
     * @example var dtm = Date.fromString("12/01/2008");
     * dtm.toString();
     * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
     *
     * @name fromString
     * @type Date
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    Date.fromString = function(s)
    {
        var f = Date.format;
        var d = new Date('01/01/1977');
        var iY = f.indexOf('yyyy');
        if (iY > -1) {
            d.setFullYear(Number(s.substr(iY, 4)));
        } else {
            // TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
            d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
        }
        var iM = f.indexOf('mmm');
        if (iM > -1) {
            var mStr = s.substr(iM, 3);
            for (var i=0; i<Date.abbrMonthNames.length; i++) {
                if (Date.abbrMonthNames[i] == mStr) break;
            }
            d.setMonth(i);
        } else {
            d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
        }
        d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
        if (isNaN(d.getTime())) {
            return false;
        }
        return d;
    };

    // utility method
    var _zeroPad = function(num) {
        var s = '0'+num;
        return s.substring(s.length-2)
        //return ('0'+num).substring(-2); // doesn't work on IE :(
    };

})();

/* JQ DATEPICKER PLUGIN */
/**
 * Copyright (c) 2007 Kelvin Luck (http://www.kelvinluck.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $Id: jquery.datePicker.js 3739 2007-10-25 13:55:30Z kelvin.luck $
 **/

(function($){

    $.fn.extend({
/**
 * Render a calendar table into any matched elements.
 *
 * @param Object s (optional) Customize your calendars.
 * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render. Default is today's year.
 * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
 * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name renderCalendar
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#calendar-me').renderCalendar({month:0, year:2007});
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
 *
 * @example
 * var testCallback = function($td, thisDate, month, year)
 * {
 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
 *        var d = thisDate.getDate();
 *        $td.bind(
 *            'click',
 *            function()
 *            {
 *                alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
 *            }
 *        ).addClass('thursday');
 *    } else if (thisDate.getDay() == 5) {
 *        $td.html('Friday the ' + $td.html() + 'th');
 *    }
 * }
 * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
 *
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
 **/
        renderCalendar  :   function(s)
        {
            var dc = function(a)
            {
                return document.createElement(a);
            };

            s = $.extend(
                {
                    month            : null,
                    year            : null,
                    renderCallback    : null,
                    showHeader        : $.dpConst.SHOW_HEADER_SHORT,
                    dpController    : null,
                    hoverClass        : 'dp-hover'
                }
                , s
            );

            if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
                var headRow = $(dc('tr'));
                for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
                    var weekday = i%7;
                    var day = Date.dayNames[weekday];
                    headRow.append(
                        jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
                    );
                }
            };

            var calendarTable = $(dc('table'))
                                    .attr(
                                        {
                                            'cellspacing':2,
                                            'className':'jCalendar'
                                        }
                                    )
                                    .append(
                                        (s.showHeader != $.dpConst.SHOW_HEADER_NONE ?
                                            $(dc('thead'))
                                                .append(headRow)
                                            :
                                            dc('thead')
                                        )
                                    );
            var tbody = $(dc('tbody'));

            var today = (new Date()).zeroTime();

            var month = s.month == undefined ? today.getMonth() : s.month;
            var year = s.year || today.getFullYear();

            var currentDate = new Date(year, month, 1);


            var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
            if (firstDayOffset > 1) firstDayOffset -= 7;
            var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
            currentDate.addDays(firstDayOffset-1);

            var doHover = function()
            {
                if (s.hoverClass) {
                    $(this).addClass(s.hoverClass);
                }
            };
            var unHover = function()
            {
                if (s.hoverClass) {
                    $(this).removeClass(s.hoverClass);
                }
            };

            var w = 0;
            while (w++<weeksToDraw) {
                var r = jQuery(dc('tr'));
                for (var i=0; i<7; i++) {
                    var thisMonth = currentDate.getMonth() == month;
                    var d = $(dc('td'))
                                .text(currentDate.getDate() + '')
                                .attr('className', (thisMonth ? 'current-month ' : 'other-month ') +
                                                    (currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
                                                    (thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
                                )
                                .hover(doHover, unHover)
                            ;
                    if (s.renderCallback) {
                        s.renderCallback(d, currentDate, month, year);
                    }
                    r.append(d);
                    currentDate.addDays(1);
                }
                tbody.append(r);
            }
            calendarTable.append(tbody);

            return this.each(
                function()
                {
                    $(this).empty().append(calendarTable);
                }
            );
        },
/**
 * Create a datePicker associated with each of the matched elements.
 *
 * The matched element will receive a few custom events with the following signatures:
 *
 * dateSelected(event, date, $td, status)
 * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
 *
 * dpClosed(event, selected)
 * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
 *
 * dpMonthChanged(event, displayedMonth, displayedYear)
 * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
 *
 * dpDisplayed(event, $datePickerDiv)
 * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
 *
 * @param Object s (optional) Customize your date pickers.
 * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render when the date picker is opened. Default is today's year.
 * @option String startDate The first date date can be selected.
 * @option String endDate The last date that can be selected.
 * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
 * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
 * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
 * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
 * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
 * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
 * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
 * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
 * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
 * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
 * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
 * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name datePicker
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('input.date-picker').datePicker();
 * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
 *
 * @example demo/index.html
 * @desc See the projects homepage for many more complex examples...
 **/
        datePicker : function(s)
        {
            if (!$.event._dpCache) $.event._dpCache = [];

            // initialise the date picker controller with the relevant settings...
            s = $.extend(
                {
                    month                : undefined,
                    year                : undefined,
                    startDate            : undefined,
                    endDate                : undefined,
                    inline                : false,
                    renderCallback        : [],
                    createButton        : true,
                    showYearNavigation    : true,
                    closeOnSelect        : true,
                    displayClose        : false,
                    selectMultiple        : false,
                    clickInput            : false,
                    verticalPosition    : $.dpConst.POS_TOP,
                    horizontalPosition    : $.dpConst.POS_LEFT,
                    verticalOffset        : 0,
                    horizontalOffset    : 0,
                    hoverClass            : 'dp-hover'
                }
                , s
            );

            return this.each(
                function()
                {
                    var $this = $(this);
                    var alreadyExists = true;

                    if (!this._dpId) {
                        this._dpId = $.event.guid++;
                        $.event._dpCache[this._dpId] = new DatePicker(this);
                        alreadyExists = false;
                    }

                    if (s.inline) {
                        s.createButton = false;
                        s.displayClose = false;
                        s.closeOnSelect = false;
                        $this.empty();
                    }

                    var controller = $.event._dpCache[this._dpId];

                    controller.init(s);

                    if (!alreadyExists && s.createButton) {
                        // create it!
                        controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
                                .bind(
                                    'click',
                                    function()
                                    {
                                        $this.dpDisplay(this);
                                        this.blur();
                                        return false;
                                    }
                                );
                        $this.after(controller.button);
                    }

                    if (!alreadyExists && $this.is(':text')) {
                        $this
                            .bind(
                                'dateSelected',
                                function(e, selectedDate, $td)
                                {
                                    this.value = selectedDate.asString();
                                }
                            ).bind(
                                'change',
                                function()
                                {
                                    var d = Date.fromString(this.value);
                                    if (d) {
                                        controller.setSelected(d, true, true);
                                    }
                                }
                            );
                        if (s.clickInput) {
                            $this.bind(
                                'click',
                                function()
                                {
                                    $this.dpDisplay();
                                }
                            );
                        }
                        var d = Date.fromString(this.value);
                        if (this.value != '' && d) {
                            controller.setSelected(d, true, true);
                        }
                    }

                    $this.addClass('dp-applied');

                }
            )
        },
/**
 * Disables or enables this date picker
 *
 * @param Boolean s Whether to disable (true) or enable (false) this datePicker
 * @type jQuery
 * @name dpSetDisabled
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisabled(true);
 * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
 **/
        dpSetDisabled : function(s)
        {
            return _w.call(this, 'setDisabled', s);
        },
/**
 * Updates the first selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the first selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetStartDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetStartDate('01/01/2000');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
 **/
        dpSetStartDate : function(d)
        {
            return _w.call(this, 'setStartDate', d);
        },
/**
 * Updates the last selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the last selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetEndDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetEndDate('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
 **/
        dpSetEndDate : function(d)
        {
            return _w.call(this, 'setEndDate', d);
        },
/**
 * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
 *
 * @type Array
 * @name dpGetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * alert($('.date-picker').dpGetSelected());
 * @desc Will alert an empty array (as nothing is selected yet)
 **/
        dpGetSelected : function()
        {
            var c = _getController(this[0]);
            if (c) {
                return c.getSelected();
            }
            return null;
        },
/**
 * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
 *
 * @param String d A string representing the date you want to select (formatted according to Date.format).
 * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
 * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
 * @type jQuery
 * @name dpSetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetSelected('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
        dpSetSelected : function(d, v, m)
        {
            if (v == undefined) v=true;
            if (m == undefined) m=true;
            return _w.call(this, 'setSelected', Date.fromString(d), v, m);
        },
/**
 * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
 *
 * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
 * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
 * @type jQuery
 * @name dpSetDisplayedMonth
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisplayedMonth(10, 2008);
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
        dpSetDisplayedMonth : function(m, y)
        {
            return _w.call(this, 'setDisplayedMonth', Number(m), Number(y));
        },
/**
 * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
 *
 * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
 * @type jQuery
 * @name dpDisplay
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpDisplay();
 * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
 **/
        dpDisplay : function(e)
        {
            return _w.call(this, 'display', e);
        },
/**
 * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
 *
 * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
 * @type jQuery
 * @name dpSetRenderCallback
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
 * {
 *     // do stuff as each td is rendered dependant on the date in the td and the displayed month and year
 * });
 * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
 **/
        dpSetRenderCallback : function(a)
        {
            return _w.call(this, 'setRenderCallback', a);
        },
/**
 * Sets the position that the datePicker will pop up (relative to it's associated element)
 *
 * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
 * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
 * @type jQuery
 * @name dpSetPosition
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
 **/
        dpSetPosition : function(v, h)
        {
            return _w.call(this, 'setPosition', v, h);
        },
/**
 * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
 *
 * @param Number v The vertical offset of the created date picker.
 * @param Number h The horizontal offset of the created date picker.
 * @type jQuery
 * @name dpSetOffset
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetOffset(-20, 200);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
 **/
        dpSetOffset : function(v, h)
        {
            return _w.call(this, 'setOffset', v, h);
        },
/**
 * Closes the open date picker associated with this element.
 *
 * @type jQuery
 * @name dpClose
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-pick')
 *        .datePicker()
 *        .bind(
 *            'focus',
 *            function()
 *            {
 *                $(this).dpDisplay();
 *            }
 *        ).bind(
 *            'blur',
 *            function()
 *            {
 *                $(this).dpClose();
 *            }
 *        );
 * @desc Creates a date picker and makes it appear when the relevant element is focused and disappear when it is blurred.
 **/
        dpClose : function()
        {
            return _w.call(this, '_closeCalendar', false, this[0]);
        },
        // private function called on unload to clean up any expandos etc and prevent memory links...
        _dpDestroy : function()
        {
            // TODO - implement this?
        }
    });

    // private internal function to cut down on the amount of code needed where we forward
    // dp* methods on the jQuery object on to the relevant DatePicker controllers...
    var _w = function(f, a1, a2, a3)
    {
        return this.each(
            function()
            {
                var c = _getController(this);
                if (c) {
                    c[f](a1, a2, a3);
                }
            }
        );
    };

    function DatePicker(ele)
    {
        this.ele = ele;

        // initial values...
        this.displayedMonth        =    null;
        this.displayedYear        =    null;
        this.startDate            =    null;
        this.endDate            =    null;
        this.showYearNavigation    =    null;
        this.closeOnSelect        =    null;
        this.displayClose        =    null;
        this.selectMultiple        =    null;
        this.verticalPosition    =    null;
        this.horizontalPosition    =    null;
        this.verticalOffset        =    null;
        this.horizontalOffset    =    null;
        this.button                =    null;
        this.renderCallback        =    [];
        this.selectedDates        =    {};
        this.inline                =    null;
        this.context            =    '#dp-popup';
    };
    $.extend(
        DatePicker.prototype,
        {
            init : function(s)
            {
                this.setStartDate(s.startDate);
                this.setEndDate(s.endDate);
                this.setDisplayedMonth(Number(s.month), Number(s.year));
                this.setRenderCallback(s.renderCallback);
                this.showYearNavigation = s.showYearNavigation;
                this.closeOnSelect = s.closeOnSelect;
                this.displayClose = s.displayClose;
                this.selectMultiple = s.selectMultiple;
                this.verticalPosition = s.verticalPosition;
                this.horizontalPosition = s.horizontalPosition;
                this.hoverClass = s.hoverClass;
                this.setOffset(s.verticalOffset, s.horizontalOffset);
                this.inline = s.inline;
                if (this.inline) {
                    this.context = this.ele;
                    this.display();
                }
            },
            setStartDate : function(d)
            {
                if (d) {
                    this.startDate = Date.fromString(d);
                }
                if (!this.startDate) {
                    this.startDate = (new Date()).zeroTime();
                }
                this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
            },
            setEndDate : function(d)
            {
                if (d) {
                    this.endDate = Date.fromString(d);
                }
                if (!this.endDate) {
                    this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
                }
                if (this.endDate.getTime() < this.startDate.getTime()) {
                    this.endDate = this.startDate;
                }
                this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
            },
            setPosition : function(v, h)
            {
                this.verticalPosition = v;
                this.horizontalPosition = h;
            },
            setOffset : function(v, h)
            {
                this.verticalOffset = parseInt(v) || 0;
                this.horizontalOffset = parseInt(h) || 0;
            },
            setDisabled : function(s)
            {
                $e = $(this.ele);
                $e[s ? 'addClass' : 'removeClass']('dp-disabled');
                if (this.button) {
                    $but = $(this.button);
                    $but[s ? 'addClass' : 'removeClass']('dp-disabled');
                    $but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
                }
                if ($e.is(':text')) {
                    $e.attr('disabled', s ? 'disabled' : '');
                }
            },
            setDisplayedMonth : function(m, y)
            {
                if (this.startDate == undefined || this.endDate == undefined) {
                    return;
                }
                var s = new Date(this.startDate.getTime());
                s.setDate(1);
                var e = new Date(this.endDate.getTime());
                e.setDate(1);

                var t;
                if ((!m && !y) || (isNaN(m) && isNaN(y))) {
                    // no month or year passed - default to current month
                    t = new Date().zeroTime();
                    t.setDate(1);
                } else if (isNaN(m)) {
                    // just year passed in - presume we want the displayedMonth
                    t = new Date(y, this.displayedMonth, 1);
                } else if (isNaN(y)) {
                    // just month passed in - presume we want the displayedYear
                    t = new Date(this.displayedYear, m, 1);
                } else {
                    // year and month passed in - that's the date we want!
                    t = new Date(y, m, 1)
                }

                // check if the desired date is within the range of our defined startDate and endDate
                if (t.getTime() < s.getTime()) {
                    t = s;
                } else if (t.getTime() > e.getTime()) {
                    t = e;
                }
                this.displayedMonth = t.getMonth();
                this.displayedYear = t.getFullYear();
            },
            setSelected : function(d, v, moveToMonth)
            {
                if (this.selectMultiple == false) {
                    this.selectedDates = {};
                    $('td.selected', this.context).removeClass('selected');
                }
                if (moveToMonth) {
                    this.setDisplayedMonth(d.getMonth(), d.getFullYear());
                }
                this.selectedDates[d.toString()] = v;
            },
            isSelected : function(d)
            {
                return this.selectedDates[d.toString()];
            },
            getSelected : function()
            {
                var r = [];
                for(s in this.selectedDates) {
                    if (this.selectedDates[s] == true) {
                        r.push(Date.parse(s));
                    }
                }
                return r;
            },
            display : function(eleAlignTo)
            {
                if ($(this.ele).is('.dp-disabled')) return;

                eleAlignTo = eleAlignTo || this.ele;
                var c = this;
                var $ele = $(eleAlignTo);
                var eleOffset = $ele.offset();

                var $createIn;
                var attrs;
                var attrsCalendarHolder;
                var cssRules;

                if (c.inline) {
                    $createIn = $(this.ele);
                    attrs = {
                        'id'        :    'calendar-' + this.ele._dpId,
                        'className'    :    'dp-popup dp-popup-inline'
                    };
                    cssRules = {
                    };
                } else {
                    $createIn = $('body');
                    attrs = {
                        'id'        :    'dp-popup',
                        'className'    :    'dp-popup'
                    };
                    cssRules = {
                        'top'    :    eleOffset.top + c.verticalOffset,
                        'left'    :    eleOffset.left + c.horizontalOffset
                    };

                    var _checkMouse = function(e)
                    {
                        var el = e.target;
                        var cal = $('#dp-popup')[0];

                        while (true){
                            if (el == cal) {
                                return true;
                            } else if (el == document) {
                                c._closeCalendar();
                                return false;
                            } else {
                                el = $(el).parent()[0];
                            }
                        }
                    };
                    this._checkMouse = _checkMouse;

                    this._closeCalendar(true);
                }


                $createIn
                    .append(
                        $('<div></div>')
                            .attr(attrs)
                            .css(cssRules)
                            .append(
                                $('<h2></h2>'),
                                $('<div class="dp-nav-prev"></div>')
                                    .append(
                                        $('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>')
                                            .bind(
                                                'click',
                                                function()
                                                {
                                                    return c._displayNewMonth.call(c, this, 0, -1);
                                                }
                                            ),
                                        $('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
                                            .bind(
                                                'click',
                                                function()
                                                {
                                                    return c._displayNewMonth.call(c, this, -1, 0);
                                                }
                                            )
                                    ),
                                $('<div class="dp-nav-next"></div>')
                                    .append(
                                        $('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>')
                                            .bind(
                                                'click',
                                                function()
                                                {
                                                    return c._displayNewMonth.call(c, this, 0, 1);
                                                }
                                            ),
                                        $('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
                                            .bind(
                                                'click',
                                                function()
                                                {
                                                    return c._displayNewMonth.call(c, this, 1, 0);
                                                }
                                            )
                                    ),
                                $('<div></div>')
                                    .attr('className', 'dp-calendar')
                            )
                            .bgIframe()
                        );

                var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');

                if (this.showYearNavigation == false) {
                    $('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
                }
                if (this.displayClose) {
                    $pop.append(
                        $('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
                            .bind(
                                'click',
                                function()
                                {
                                    c._closeCalendar();
                                    return false;
                                }
                            )
                    );
                }
                c._renderCalendar();

                $(this.ele).trigger('dpDisplayed', $pop);

                if (!c.inline) {
                    if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
                        $pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
                    }
                    if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
                        $pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
                    }
                    $(document).bind('mousedown', this._checkMouse);
                }
            },
            setRenderCallback : function(a)
            {
                if (a && typeof(a) == 'function') {
                    a = [a];
                }
                this.renderCallback = this.renderCallback.concat(a);
            },
            cellRender : function ($td, thisDate, month, year) {
                var c = this.dpController;
                var d = new Date(thisDate.getTime());

                // add our click handlers to deal with it when the days are clicked...

                $td.bind(
                    'click',
                    function()
                    {
                        var $this = $(this);
                        if (!$this.is('.disabled')) {
                            c.setSelected(d, !$this.is('.selected') || !c.selectMultiple);
                            var s = c.isSelected(d);
                            $(c.ele).trigger('dateSelected', [d, $td, s]);
                            $(c.ele).trigger('change');
                            if (c.closeOnSelect) {
                                c._closeCalendar();
                            } else {
                                $this[s ? 'addClass' : 'removeClass']('selected');
                            }
                        }
                    }
                );

                if (c.isSelected(d)) {
                    $td.addClass('selected');
                }

                // call any extra renderCallbacks that were passed in
                for (var i=0; i<c.renderCallback.length; i++) {
                    c.renderCallback[i].apply(this, arguments);
                }


            },
            // ele is the clicked button - only proceed if it doesn't have the class disabled...
            // m and y are -1, 0 or 1 depending which direction we want to go in...
            _displayNewMonth : function(ele, m, y)
            {
                if (!$(ele).is('.disabled')) {
                    this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y);
                    this._clearCalendar();
                    this._renderCalendar();
                    $(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
                }
                ele.blur();
                return false;
            },
            _renderCalendar : function()
            {
                // set the title...
                $('h2', this.context).html(Date.monthNames[this.displayedMonth] + ' ' + this.displayedYear);

                // render the calendar...
                $('.dp-calendar', this.context).renderCalendar(
                    {
                        month            : this.displayedMonth,
                        year            : this.displayedYear,
                        renderCallback    : this.cellRender,
                        dpController    : this,
                        hoverClass        : this.hoverClass
                    }
                );

                // update the status of the control buttons and disable dates before startDate or after endDate...
                // TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
                if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
                    $('.dp-nav-prev-year', this.context).addClass('disabled');
                    $('.dp-nav-prev-month', this.context).addClass('disabled');
                    $('.dp-calendar td.other-month', this.context).each(
                        function()
                        {
                            var $this = $(this);
                            if (Number($this.text()) > 20) {
                                $this.addClass('disabled');
                            }
                        }
                    );
                    var d = this.startDate.getDate();
                    $('.dp-calendar td.current-month', this.context).each(
                        function()
                        {
                            var $this = $(this);
                            if (Number($this.text()) < d) {
                                $this.addClass('disabled');
                            }
                        }
                    );
                } else {
                    $('.dp-nav-prev-year', this.context).removeClass('disabled');
                    $('.dp-nav-prev-month', this.context).removeClass('disabled');
                    var d = this.startDate.getDate();
                    if (d > 20) {
                        // check if the startDate is last month as we might need to add some disabled classes...
                        var sd = new Date(this.startDate.getTime());
                        sd.addMonths(1);
                        if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
                            $('dp-calendar td.other-month', this.context).each(
                                function()
                                {
                                    var $this = $(this);
                                    if (Number($this.text()) < d) {
                                        $this.addClass('disabled');
                                    }
                                }
                            );
                        }
                    }
                }
                if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
                    $('.dp-nav-next-year', this.context).addClass('disabled');
                    $('.dp-nav-next-month', this.context).addClass('disabled');
                    $('.dp-calendar td.other-month', this.context).each(
                        function()
                        {
                            var $this = $(this);
                            if (Number($this.text()) < 14) {
                                $this.addClass('disabled');
                            }
                        }
                    );
                    var d = this.endDate.getDate();
                    $('.dp-calendar td.current-month', this.context).each(
                        function()
                        {
                            var $this = $(this);
                            if (Number($this.text()) > d) {
                                $this.addClass('disabled');
                            }
                        }
                    );
                } else {
                    $('.dp-nav-next-year', this.context).removeClass('disabled');
                    $('.dp-nav-next-month', this.context).removeClass('disabled');
                    var d = this.endDate.getDate();
                    if (d < 13) {
                        // check if the endDate is next month as we might need to add some disabled classes...
                        var ed = new Date(this.endDate.getTime());
                        ed.addMonths(-1);
                        if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
                            $('.dp-calendar td.other-month', this.context).each(
                                function()
                                {
                                    var $this = $(this);
                                    if (Number($this.text()) > d) {
                                        $this.addClass('disabled');
                                    }
                                }
                            );
                        }
                    }
                }
            },
            _closeCalendar : function(programatic, ele)
            {
                if (!ele || ele == this.ele)
                {
                    $(document).unbind('mousedown', this._checkMouse);
                    this._clearCalendar();
                    $('#dp-popup a').unbind();
                    $('#dp-popup').empty().remove();
                    if (!programatic) {
                        $(this.ele).trigger('dpClosed', [this.getSelected()]);
                    }
                }
            },
            // empties the current dp-calendar div and makes sure that all events are unbound
            // and expandos removed to avoid memory leaks...
            _clearCalendar : function()
            {
                // TODO.
                $('.dp-calendar td', this.context).unbind();
                $('.dp-calendar', this.context).empty();
            }
        }
    );

    // static constants
    $.dpConst = {
        SHOW_HEADER_NONE    :    0,
        SHOW_HEADER_SHORT    :    1,
        SHOW_HEADER_LONG    :    2,
        POS_TOP                :    0,
        POS_BOTTOM            :    1,
        POS_LEFT            :    0,
        POS_RIGHT            :    1
    };
    // localisable text
    $.dpText = {
        TEXT_PREV_YEAR        :    'Previous year',
        TEXT_PREV_MONTH        :    'Previous month',
        TEXT_NEXT_YEAR        :    'Next year',
        TEXT_NEXT_MONTH        :    'Next month',
        TEXT_CLOSE            :    'Close',
        TEXT_CHOOSE_DATE    :    'Choose date'
    };
    // version
    $.dpVersion = '$Id: jquery.datePicker.js 3739 2007-10-25 13:55:30Z kelvin.luck $';

    function _getController(ele)
    {
        if (ele._dpId) return $.event._dpCache[ele._dpId];
        return false;
    };

    // make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
    // comments to only include bgIframe where it is needed in IE without breaking this plugin).
    if ($.fn.bgIframe == undefined) {
        $.fn.bgIframe = function() {return this; };
    };


    // clean-up
    $(window)
        .bind('unload', function() {
            var els = $.event._dpCache || [];
            for (var i in els) {
                $(els[i].ele)._dpDestroy();
            }
        });


})(jQuery);
