/**
 * dctv_admin_login.js
 * JQuery code needed by the module for AJAX interaction.
 */

// $Id$

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Sets this module's JQuery behavior
$(document).ready(function(){

	$("#fms-form-login").ajaxForm({            
		target: "",
		beforeSubmit: validateLoginForm,
		success     : onLoginSuccess
	});
});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will do the basic validation of the form (required fields, confirmations, ...).
//
// formData:
// formData is an array of objects representing the name and value of each field 
// that will be sent to the server;  it takes the following form: 
// 
// [ 
//     { name:  username, value: valueOfUsernameInput }, 
//     { name:  password, value: valueOfPasswordInput } 
// ] 
//
// JqForm:
// jqForm is a jQuery object which wraps the form DOM element 
//
// options:
// this is the Options Object passed into ajaxForm/ajaxSubmit
function validateLoginForm(formData, jqForm, options) {

	//get the form object
	var form = jqForm[0];
	var valid = true;
	
	//email required
	if(!form.username.value){
		$("#fms-form-login-username").addClass("error");
		valid = false;
	}
	
	//pwd required
	if(!form.password.value){
		$("#fms-form-login-password").addClass("error");
		valid = false;
	}
	
	//everything is good, show the throbber and proceed to the core operation
	if(valid){
		$("#fms-form-login-wrapper").fadeOut('fast', function(){
			$("#fms-login-wrapper").addClass("loading"); 
		});
	}

	return valid;
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// This function will process the returning value of the submitions to see if the operation
// was successfull or not.
//
// result:
// the responseText or responseXML value (depending on the value of the dataType option).
function onLoginSuccess(result){
	
	//parse the result so that we know if there was an error or everything went fine
	var str = result.substr(0, 5);
	
	$("#fms-login-wrapper").removeClass("loading");
	
	if(str == "false"){
	
		//get the incorrect field
		var idx = result.indexOf("=");
		
		//check if the resulting error indicates a field. [example: false field_with_error=error_message]
		if(idx != -1){
			var field = result.substr(6, idx-6);
			alert(result.substr(idx+1, result.length));
			$("[name=" + field + "]").addClass("error");
		}else{
			alert(result.substr(6, result.length));
		}

		//graphical logic
		$("#fms-form-login-wrapper").fadeIn('fast');
	}
	else{
		window.location = result;
	}
}