var passwordImage = 'url(' + baseUrl +  '/images/resources/password-bg.png)';
var confirmationPasswordImage = 'url(' + baseUrl +  '/images/resources/password-confirmation-bg.png)';

//add focus event for registration form & contact form
window.addEvent('domready', function() {
	var forms = document.forms;

	for(var i = 0;i<forms.length;i++){
		var form = forms[i];
		//only for registation form & contact form
		if(!(form.id == 'registration_form' || form.id == 'contact_form')){
			continue;
		}
		var elements = form.elements;
		for(var j=0;j<elements.length;j++){

			var doLabelEvent = isDoLabelEvent(elements[j]);
		
			if(doLabelEvent){
				//set default value (label)
				if(elements[j].value == '' && getLabel(elements[j].id))
				{
					elements[j].value = getLabel(elements[j].id); 
		
				}
				
				//default value for password and confirm_password
				if(elements[j].id == 'password' && elements[j].value == ''){
					elements[j].style.backgroundImage = passwordImage;
				}
				
				if(elements[j].id == 'password_confirmation' && elements[j].value == ''){
					elements[j].style.backgroundImage = confirmationPasswordImage;
				}
				
				//set default hasFocus Flag
				elements[j].hasFocus = false;
				//add on focus event to element
				elements[j].onfocus = elementFocus;
			}
		}
	}
	
});

//this function called when certain element get focus
function elementFocus(){
	//set hasFocus flag
	this.hasFocus = true;
	
	//set the value = '' if current value = label
	if(this.value == getLabel(this.id) &&  getLabel(this.id))
	{
		this.value = ''; 
	}
	
	//default value for password and confirm_password
	if(this.id == 'password' && this.value == ''){
		this.style.backgroundImage = 'none';
	}
	
	if(this.id == 'password_confirmation' && this.value == ''){
		this.style.backgroundImage = 'none';
	}
}

//get the element label
//the label id is "fieldId + -label" (default zend framework)
function getLabel(id){
	//get first word in id (before -)
	try{
		id = id.split("-",1);
		var dt = $(id + '-label');
		if(dt){
			var label = dt.getElement('label');
			return label.innerHTML;
		}
		else{
			return null;
		}
	}catch(e){
		return null;
	}
}

//only input and text area need label event
function isDoLabelEvent(element){
	var doLabelEvent = false;
	var tagName = element.tagName;

	//check tagName ang type, need to add additional 
	if(tagName.toLowerCase() == "input"){
		type = element.type; 
		if(type == "text" ||type == "password" ){
			doLabelEvent = true;
		}
	}
	else if(tagName.toLowerCase() == "textarea" ){
		doLabelEvent = true;
	}
	
	return doLabelEvent;
}


function initFormValidation(formName)
{
	//init form validation on submit
	initFormSubmitValidation(formName);
	
	//init form validation on field lost focus
	initFieldBlurValidation(formName);
	
}

/**
 * Initialize onsubmit ajax validation
 * Will validate form when the form is submited,
 * the form will be validated using ajax
 * @param formName
 * @return
 */
function initFormSubmitValidation(formName){
	//run the function when the form submited
	$(formName).addEvent('submit', function(e) {

		var result = false;
		//if baseUrl not found stop the process
		if(!baseUrl){
			//Prevents the default submit event from loading a new page.
			e.stop();
			alert("baseUrl not found");
			return;
		}
		
		//reset the values if the value = label
		if(formName == 'registration_form' || 
				formName == 'contact_form'){
			var elements = $(formName).elements;
			for(var i=0;i<elements.length;i++){
				//check if the element need label event
				var doLabelEvent = isDoLabelEvent(elements[i]);
	
				if(doLabelEvent){
//					set the element value to '' if the element value = element label and element label is not empty
					if(elements[i].value == getLabel(elements[i].id) && getLabel(elements[i].id) )
					{
						elements[i].value = ''; 
					}
				}
			}
		}

		//set the url of ajax request
		//the ajax request will be synchronous
		this.set('send', {url:baseUrl + '/ajax-form-validation?formClassName=' + formName,method:'post',async:false,onComplete: function(response) { 
			//decode the JSON response
			result = JSON.decode(response);

			if(result == null){
				//message for developer only
				alert("Configuration problem check your form name in js and AjaxController");
			}
			
			//if there are validation error, display it
			if(result != true && result != null){
				appendErrorMessage(result);
			}
		}});
		
		//Send the form.
		this.send();

		//set back the label if the value is empty
		if(result != true && result != null ){
			//only registration form
			if(formName == 'registration_form' ||
					formName == 'contact_form'){
				//put back the label if the value = ''
				var elements = $(formName).elements;
				for(var i=0;i<elements.length;i++){
					var doLabelEvent = isDoLabelEvent(elements[i]);
	
					if(doLabelEvent){
						if(elements[i].value == '' && getLabel(elements[i].id))
						{
							elements[i].value = getLabel(elements[i].id); 
						}
					}
				}
			}
			//Prevents the default submit event from loading a new page.
			e.stop();
		}
	});
}
/**
 * Initialize onblur field ajax validation
 * 
 * will validate the field when blur (lost focus) event triggered
 * @param formName
 * @return
 */
var formName;
function initFieldBlurValidation(formNameInput){
	var elements = $(formNameInput).elements;
	formName = formNameInput;
	//define elements that need validation
	for(var i=0;i<elements.length;i++){
		var doValidate = false;
		var tagName = elements[i].tagName;
		
		//check tagName ang type, need to be validated 
		if(tagName.toLowerCase() == "input"){
			type = elements[i].type; 
			if(type == "text" || type == "checkbox" || type == "radio" || type == "password"){
				doValidate = true;
			}
			

		}
		else if(tagName.toLowerCase() == "select"){
			doValidate = true;
		}
		else if(tagName.toLowerCase() == "textarea" ){
			doValidate = true;
		}

		if(doValidate == true){
			//add blur event to element
			elements[i].onblur = validateBlur;
		}
	}
}

function validateBlur(){
	//set hasFocus false
	this.hasFocus = false;

	//if baseUrl not found stop the process
	if(!baseUrl){
		alert("baseUrl not found");
		return;
	}
	var form = $(formName);
	
	var fieldName = this.id;
	
	//only registration_form and contact form have label inside the field
	if(formName == 'registration_form' ||
			formName == 'contact_form'){
		//if value == label name the value is empty
		if(this.value == getLabel(this.id) && getLabel(this.id)){
			this.value = '';
		}
							
//		//handle email and confimation email
		if(this.id == 'email' && $('email_confirmation') != null){
			if($('email_confirmation').value == getLabel('email_confirmation')){
				$('email_confirmation').value = '';
			}
		}
		
		if(this.id == 'email_confirmation' && $('email')){
			if($('email').value == getLabel('email')){
				$('email').value = '';
			}
		}
	}
	
	
	form.set('send', {url:baseUrl + '/ajax-field-validation?formClassName=' + formName + '&fieldName='+fieldName,method:'post',async:true,onComplete: function(response) { 
		result = JSON.decode(response);
		
		//apppend the error message and remove the old error message
		//ignore the response if the fieldName == captcha-input
		if(fieldName != 'captcha-input'){
			appendErrorMessage(result , fieldName);
		}
		
		
		//only registration_form and contact form have label inside the field
		if(formName == 'registration_form' || 
				formName == 'contact_form'){
			//set back the label if the value is empty
			if($(fieldName).value == '' && getLabel(fieldName))
			{
				$(fieldName).value = getLabel(fieldName); 
				
				
			}

			//default value for password and confirm_password
			if(fieldName == 'password' && document.forms['registration_form'].password.value == ''){
				document.forms['registration_form'].password.style.backgroundImage= passwordImage;
			}
			
			if(fieldName == 'password_confirmation' && $(fieldName).value == ''){
				$(fieldName).style.backgroundImage = confirmationPasswordImage;
			}
			
//			//handle email and confimation email
			if(fieldName == 'email' && $('email_confirmation')){
				if($('email_confirmation').value == '' && $('email_confirmation').hasFocus == false){
					$('email_confirmation').value = getLabel('email_confirmation');
				}
			}
			
			if(fieldName == 'email_confirmation' && $('email')){
				if($('email').value == '' && $('email').hasFocus == false){
					$('email').value = getLabel('email');
				}
			}
		}
		
	}});
	
	//Send the form.
	form.send();
}

//Display the error message beside the field
function appendErrorMessage(errorMsgs,fieldName){

	if(fieldName == null){
		//the validation is on form submit
		//get all error message containers, to be removed
		var errors = $$('ul');
	}else{
		
		//get error message container that exist in the error message
		var errors = new Array(); 	
		for(var i in errorMsgs){
			if(i != fieldName){
				var element = $( i + '-element');
				var tempErrors = element.getElement('ul');
				if(tempErrors){
					errors.push(tempErrors);
				}
			}
		}
		
		//get the error message container from current field name
		var element = $(fieldName + '-element');
		var tempErrors = element.getElement('ul');
		if(tempErrors){
			errors.push(tempErrors);
		}
	}
	
	//remove all displayed error mesage
	errors.each(function(item, index){
	    if(item.className == 'errors'){
			item.dispose();
		}
	});
	
	//iterate the error message and display
	for(var i in errorMsgs){

		//create an ul element
		var errorUL = new Element('ul', {
			'class' : 'errors'
		});

		//add each error message to the ul
		//the error message inside li tag
		for(var j in errorMsgs[i]){
			var errorLI = new Element('li');
			errorLI.innerHTML = errorMsgs[i][j];
			errorUL.grab(errorLI);
		} 

		//display the error message beside the field
		try{
		$(i + '-element').grab(errorUL);		
		}catch(e){
			
		}
	}
}