
/* - autopopulate.js - */

/**
 * Init on window load.
 * Replace this with a call to your own addEvent/DOMReady function if you use one.
 */
jq(window).load(function() {
	// Check for DOM support
	if (!document.getElementById || !document.createTextNode) {return;}
	// Find all input elements with the given className
	
	var sInputClass = 'populate'; // Class name for input elements to autopopulate
	var sHiddenClass = 'hide'; // Class name that gets assigned to hidden label elements
	var sInputHelpClass ='input_help_shown'; // Class name that is set when the help text is shown

	
	var arrInputs = jq('input');
	var iInputs = arrInputs.length;
	var oInput;
	for (var i=0; i<iInputs; i++) {
		oInput = arrInputs[i];

		if (oInput.type == 'submit') {
			jq(oInput).click(function(){
				jq('input.' + sInputClass).each(function(i){
					// clear all inputs that have the same value as title on submit.
					// To make sure no rubbish data is entered.
					if (this.value == this.title){
						this.value = '';
					}
				});
			});
			
		}else if((oInput.type == 'text') && 
				(jq(oInput).hasClass(sInputClass))){
			
			// If value is empty and title is not, assign title to value
			if ((oInput.value == '') && (oInput.title != '') ||
					(oInput.value == oInput.title)) { 
				jq(oInput).addClass( sInputHelpClass);
				oInput.value = oInput.title;
			}
			// Add event handlers for focus and blur
			jq(oInput).focus(function() {
				
				// If value and title are equal on focus, clear value
				if (this.value == this.title) {
					jq(this).removeClass( sInputHelpClass);
					this.value = '';
					this.select(); // Make input caret visible in IE
				}
			});
			
			jq(oInput).blur(function() {
				
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { 
					// if the field was a password make it back to a text so that we can see the text
					jq(this).addClass( sInputHelpClass);
					this.value = this.title; 
				}
			});
		}
	}
});

