/*

Copyright (c) 2009 Stefano J. Attardi, http://attardi.org/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
(function($) {
    function toggleLabel() {
        var input = $(this);
        setTimeout(function() {
            var def = input.attr('title');
            if (!input.val() || (input.val() == def)) {
                input.prev('span').css('visibility', '');
                if (def) {
                    var dummy = $('<label></label>').text(def).css('visibility','hidden').appendTo('body');
                    input.prev('span').css('margin-left', dummy.width() + 3 + 'px');
                    dummy.remove();
                }
            } else {
                input.prev('span').css('visibility', 'hidden');
            }
        }, 0);
    };

    function resetField() {
        var def = $(this).attr('title');
        if (!$(this).val() || ($(this).val() == def)) {
            $(this).val(def);
            $(this).prev('span').css('visibility', '');
        }
    };

    $('input, textarea').live('keydown', toggleLabel);
    $('input, textarea').live('paste', toggleLabel);
    $('select').live('change', toggleLabel);

    $('input, textarea').live('focusin', function() {
        $(this).prev('span').css('color', '#999');
    });
    $('input, textarea').live('focusout', function() {
        $(this).prev('span').css('color', '#555');
    });

    $(function() {
        $('input, textarea').each(function() { toggleLabel.call(this); });
    });

})(jQuery);






//==============================================================================
// XXX hack:
//==============================================================================
// msie won't let us change the type of an existing input element, so to get this 
// functionality, we need to create the desired element type in an HTML string.
//==============================================================================
function label_setInputType(el, type) {
	if (navigator.appName == "Microsoft Internet Explorer") {
		var newEl = document.createElement("SPAN");
		newEl.innerHTML = '<input type="' + type + '" />';
		newEl = newEl.firstChild;
		var s = '';
		for (prop in el) {
			// some properties are read-only
			try {
				// the craziest browser bug ever: "height" and "width" (which 
				// should not even exist) return totally garbage numbers, like 
				// 458231 for instance, so we need to ignore those.
				if (prop != "type"
				&& prop != "height"
				&& prop != "width") newEl[prop] = el[prop];
			} 
			catch(e) { }
		}
		addEvent(newEl, "focus", label_focused);
		addEvent(newEl, "blur", label_blurred);
		el.parentNode.replaceChild(newEl, el);
		return newEl;
	} else {
		el.setAttribute("type", type);
		return el;
	}
}



//==============================================================================
// utility functions below...
//==============================================================================

// scott andrew (www.scottandrew.com) wrote this function. thanks, scott!
// adds an eventListener for browsers which support it.
function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
  } else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
	return false;
  }
}

// add a style rule in ie or dom
function addStyleRule(stylesheet, selector, rule) {
	if (stylesheet.addRule) stylesheet.addRule(selector, rule);
	else {
		var index = stylesheet.cssRules.length;
		stylesheet.insertRule(selector + "{" + rule + "}", index);
	}
}

// makes ie behave like a sc browser with regard to events
function fix_e(e) {
	if (!e && window.event) e = window.event;
	if (!e.currentTarget && e.srcElement) e.currentTarget = e.srcElement;
	if (!e.originalTarget && e.srcElement) e.originalTarget = e.srcElement;
	// paul:
	// we can put more things in here as we go along, 
	// whenever we come across differences that need to
	// be fixed.
	return e;
}
