/**
 * Wraps general functions for input control. E.g. methods for defaultizing text inputs 
 * and textarea are included as well as methode to resticts amount of characters that can be
 * entered int textares. 
 */
var Toolkit = Class.create();
Object.extend(Toolkit.prototype, {

	/**
	 * Initialize
	 */
	initialize : function(){
	},

	/**
	 * Adds default texts to textareas and textinputs
	 *
	 * @param obj HtmlElement Input[type=text] or Teaxtarea
	 */
	defaultize : function (obj){
		obj = $(obj);
	
		// get default text from title attribute
		var defaultText = obj.getAttribute('title');
		if( defaultText.length <= 0 || obj.value.length > 0){
			return false;
		}

		var originalType = obj.getAttribute('type');
		
		try {
			// if this is a password input change type
			// note: this might throw an exception in IE
			if( obj.tagName == 'INPUT' ){
				obj.type = originalType=='password' ? 'text' : originalType;
			}
			
			obj.defaultValue = defaultText;
			obj.value = defaultText;
			obj.addClassName('defaulttext');
		
			// register event oberserver to clear default text
			Event.observe(obj, 'focus', function(evt){
				if( obj.value == defaultText ){
					obj.value = '';
					obj.removeClassName('defaulttext');
					if( obj.tagName == 'INPUT' ){
						obj.type = originalType;
					}
				}
			});
			Event.observe(obj, 'blur', function(evt){
				if( obj.value == '' ){
					obj.value = defaultText;
					obj.addClassName('defaulttext');
					if( obj.tagName == 'INPUT' ){
						obj.type = originalType=='password' ? 'text' : originalType;
					}
				}
			});
			// Get the form containing this thing and tell it to check on submit.
			// This works not for ajax forms, since they are not submitted (but the data
			// is serialized and sent afterwards.
			var f = obj.up('form');
			try{
				Event.observe(f, 'submit', function(evt){
					if( obj.value == defaultText ){
						obj.value = '';
						if( obj.tagName == 'INPUT' ){
							obj.type = originalType;
						}
					}
				});
			} catch( ex ){}
			
		} catch( x ){}
		
		return true;
	},
	
	/**
	 * Undefaultize input elements in form f.
	 *
	 * @param f HtmlFormElement form which contains elements that are supposed to be undefaultized
	 */
	undefaultizeElements : function (f){
		f = $(f);
		var objs = f.getElementsBySelector('input[title]');
		objs.each(function(obj){
			if( obj.value == obj.getAttribute('title') ){
				obj.value = '';
			}
		});
	}
	
});
var toolkit = new Toolkit();

/**
 * Basic stuff that happen after page load
 *
 */
Event.observe(window, 'load', function(evt){
    
	// default texts
	$$('textarea[title], input[type=text][title], input[type=password][title]').each(function(obj){
		toolkit.defaultize(obj);
	});
	
});