/**
 * 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, {

	/**
	 * Stores the base path for ajax calls
	 */
	_basePath : '',

	initialize : function(){
		// set the base path
        var p = $A(document.getElementsByTagName('script')).findAll( function(s) {
          return (s.src && s.src.match(/main\.js$/i))
        }).first();
        p = p.src;
        p = p.replace(/js\/main\.js$/i,'');
        p = p.replace(document.location.protocol + '//' + document.location.host, '');
        this._basePath = p;
	},

	/**
	 * 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 = '';
			}
		});
	},
	
	/**
	 * Restricts input of characters to a maximum length.
	 *
	 * @param obj HtmlTextareaElement Textarea of class 'cr' to restrict. Reads from classname max amount, e.g. 'rc300' will restrict to 300 characters
	 */
	charRestrict : function (obj){
		obj = $(obj);
		
		var maxChars = obj.className;
		maxChars = maxChars.match(/cr\d{1,5}/g);
		if( maxChars.length <= 0 ){
			return false;
		}
	
		// get number of maximum allowed characters
		maxChars = parseInt(maxChars.first().substring(2));
		
		// build info div to display remaining characters
		var info = Builder.node('div', {'class':'crinfo'}, maxChars-obj.value.length);
		Element.insert(obj, {after:info});
		
		// position info div
		info.style.marginTop = obj.offsetHeight - info.offsetHeight + 'px';
		info.style.marginLeft = obj.offsetWidth - info.offsetWidth + 'px';
		Position.clone(obj, info, {setLeft:true, setTop:true, setWidth:false, setHeight:false});
		
		// register event observers for key events
		Event.observe(obj, 'keydown', function(evt){
			var numChars = obj.value.length;
			var diff = maxChars - numChars;
			if( diff > 0 ){
				info.innerHTML = diff;
			} else {
				info.innerHTML = '0';
				obj.value = obj.value.substring(0, maxChars-1);
			}
		});
		
		return true;
	},
	
	/**
	 * Gets the base path
	 *
	 */
	basePath : function(){
		return this._basePath;
	}
	
});
var toolkit = new Toolkit();

/**
 * Basic stuff that happen after page load
 *
 */
Event.observe(window, 'load', function(evt){
    
    // Hide flash messages after a while
    try {
        new Effect.Fade('flash', {duration:2, delay:2.5});
    } catch(x) {
    }
    
    // let links blur after a click
    $$('a').each(function(elm){
        Event.observe(elm, 'click', function(evt){
            elm.blur();
        });
    });
	
	// char restriction
	$$('textarea.cr').each(function(obj){
		toolkit.charRestrict(obj);
	});
	
	// default texts
	$$('textarea[title], input[type=text][title], input[type=password][title]').each(function(obj){
		toolkit.defaultize(obj);
	});
	
	// show info screen when clicked on group realm protected elements
    if( document.body.className.match(/inrealm/) ){
	    $$('.realm').each(function(elm){
	        Event.observe(elm, 'click', function(evt){
	        	Event.stop(evt);
	            Popup.ajax(Popup.getBasePath() + 'users/leaveRealm/');
	        });
	    });
    }
});

/**
 * Trims strings
 */
String.prototype.trim = function() {
	return this.replace(/^[\ ]{1,}/,"").replace(/[\ ]{1,}$/,"");
}