(function() {

    var PLACEHOLDER_CLASS = 'empty';

    function init() {
        $('#login input[name=username]').each(function(i) {text_init(this)});
        $('#login input[name=password]').each(function(i) {password_init(this)});
    };

    function text_init(element) {
        // the second part of the OR eludes Firefox, which saves the value on page refresh
        if (!element.value || element.value == element.title) {
            element.value = element.title;
            $(element).addClass(PLACEHOLDER_CLASS);
        }
        $(element).bind('focus', text_focus);
        $(element).bind('blur', text_blur);
    };

    function text_focus(event) {
        if ($(event.target).hasClass(PLACEHOLDER_CLASS)) {
            event.target.value = "";
            $(event.target).removeClass(PLACEHOLDER_CLASS);
        }
    };

    function text_blur(event) {
        if (!event.target.value) {
            if (!$(event.target).hasClass(PLACEHOLDER_CLASS)) {
                $(event.target).addClass(PLACEHOLDER_CLASS)
            }
            event.target.value = event.target.title;
        }
    };

    function password_init(element) {
        // this initialization is needed by Explorer,
        // which doesn't support changing the type of input elements
        var clone;
        clone = document.createElement('input');
        if (element.id) {
            clone.id = element.id + '-clone';
        }
        clone.type = 'text';
        clone.className = element.className;
        clone.name = element.name;
        clone.value = element.title;
        clone.title = element.title;
        $(clone).addClass(PLACEHOLDER_CLASS);

        if (!element.value) {
            element.parentNode.replaceChild(clone, element);
        };

        $(clone).bind('focus', {element: element}, password_focus);
        $(element).bind('blur', {clone: clone}, password_blur);
    };

    function password_focus(event) {
        event.target.parentNode.replaceChild(event.data.element, event.target);
        // calling focus() immediately doesn't work in Explorer
        setTimeout(function() {event.data.element.focus();}, 0);
    };

    function password_blur(event) {
        if (!event.target.value) {
            event.target.parentNode.replaceChild(event.data.clone, event.target);
        }
    };

    $(document).ready(init); 

})();
