$(document).ready(function() {
	//Manejar Enter del formulario de entrada
	$("form[name='acceso']").keypress(function(e){
	      if(e.which == 13){
	    	loginExternal();
	    	return false;	
	      }
	});
});

// Generic clear/restore form field on focus
function clearField(t) {
	if (t.defaultValue == t.value) t.value='';
}
function restoreField(t){
	if (t.value == '') t.value = t.defaultValue;
}
function onPasswordFocus(inputText){
	/*inputText.style.display = 'none';
	
	var inputPwd = (document.getElementById) ? document.getElementById('PASSWORD') : document.all['PASSWORD'];
	inputPwd.style.display = 'inline';
	inputPwd.focus();
	
	return true;*/
}


function onPasswordBlur(inputPwd){
	if(inputPwd.value === ''){
		inputPwd.style.display = 'none';
		
		var inputText = (document.getElementById) ? document.getElementById('PASSWORDTXT') : document.all['PASSWORDTXT'];
		inputText.style.display = 'inline';
		inputText.style.border = '1px solid #809DB9';
	}
	return true;
}


function openForgotPsw(){
	var btnAcceptText = $("#forgotPswDialog").attr("btn_accept_txt").toString();
	var btnCancelText = $("#forgotPswDialog").attr("btn_cancel_txt").toString();
		
	$("#forgotPswDialog").dialog({modal: false, resizable: false, autoOpen: false, width: 350, dialogClass: "forgotPsw-Dialog", closeOnEscape: true});	
	var buttons = {};
	buttons[btnAcceptText] = function() { submitAndCloseForgotPsw(); };
	buttons[btnCancelText] = function() { $(this).dialog("close"); };
	$("#forgotPswDialog").dialog("option", "buttons", buttons);
	
	//Deshabilitar el boton de envio
	var firstButton=$('#forgotPswDialog + .ui-dialog-buttonpane button:first');
	firstButton.attr("disabled", true);
	firstButton.addClass('ui-state-disabled');
	$("input[name='USERNAME']").val('');
	
	//Manejar los cambios en el input
	$("input[name='USERNAME']").keyup(function(){	
		if ($(this).val()!=''){
			firstButton.attr("disabled", false);	
			firstButton.removeClass('ui-state-disabled');		
		}else{
			firstButton.attr("disabled", true);	
			firstButton.addClass('ui-state-disabled');		
		}		
	});	
	
	//Manejar Enter
	$("#forgotPswDialog").keypress(function(e){
	      if(e.which == 13){
	    	if(!firstButton.hasClass('ui-state-disabled')){	
	    		firstButton.click();
	    	}
	    	return false;	
	      }
	});

	//Mostrar el dialogo
	$("#forgotPswDialog").dialog('open');
}


function submitAndCloseForgotPsw(){
				
	$("#forgotPswDialog").dialog('close');
	$.ajax({
		async:true,
		type: "POST",
		dataType: "html",
		url: $("#forgotPswForm").attr("postUrl"),	       
		data: $("#forgotPswForm").serialize(),
		success: function (data,status,XHRobj) {
			var code = processStandardResponse(data);		    		   
	    },				
    	error: function (XHRobj,errtype,errObj) {}
	});
		
}

function loginExternal(){
	$.ajax({
		async:true,
		type: "POST",
		dataType: "html",
		url: $("form[name='acceso']").attr("postUrl"),	       
		data: $("form[name='acceso']").serialize(),
		success: function (data,status,XHRobj) {
			var code = processStandardResponse(data);
			if (code == "success") window.location.replace($("form[name='acceso']").attr("afterUrl"));
	    },				
    	error: function (XHRobj,errtype,errObj) {}
	});
}

function processStandardResponse(data){

	var returnCode = "success";
	var response = "";
    
    var index = data.indexOf("\"errors\"");	
    if (index==-1) index = data.indexOf("id=errors");
    if (index != -1) {	
    	returnCode = "error";
    	
    	$('#errorDialog').dialog({modal: false, resizable: false, autoOpen: false, width: 350, 
    		                      dialogClass: "error-Dialog", closeOnEscape: true});
    	
	    //Recuperar la lista devuelta por el servidor
		response = "<ul>\n";
	    $(data).find("li").each(function(){
	    	        response = response + "<li>"+$(this).html()+"</li>\n";
	      });
	    response = response + "</ul>\n";
	    $('#errorDialog').html(response);
	    
	    var btnAcceptText = $("#errorDialog").attr("btn_accept_txt").toString();
	    var buttons = {};
		buttons[btnAcceptText] = function() { $(this).dialog("close"); };
		$("#errorDialog").dialog("option", "buttons", buttons);
		$("#errorDialog").dialog('open');
	    			    		    	
    }
    
    index = data.indexOf("\"warning\"");
    if (index != -1) {
    	returnCode = "warning";
    	
    	$('#warningDialog').dialog({modal: false, resizable: false, autoOpen: false, width: 350, 
    		                        dialogClass: "warning-Dialog", closeOnEscape: true});		    	
    			    	
    	$(data).find("span").each(function(){
	        response = response + "<span>"+$(this).html()+"</span>\n";	    	       
    	});
    	$('#warningDialog').html(response);
    	
	    var btnAcceptText = $("#warningDialog").attr("btn_accept_txt").toString();
	    var buttons = {};
		buttons[btnAcceptText] = function() { $(this).dialog("close"); };
		$("#warningDialog").dialog("option", "buttons", buttons);
		$("#warningDialog").dialog('open');				
    	
    }
    
    return returnCode;
}

function handleLoading(data,status,XHRobj) {
	if (XHRobj.readyState == 4) {
		alert("readyState:"+XHRobj.readyState
			+"\nresponseText:"+XHRobj.responseText
			+"\nstatus:"+XHRobj.status
			+"\nstatusText:"+XHRobj.statusText
			+"\nSource Object Id: "+XHRobj.instanceId
		);
	}
}

function handleError(XHRobj,errtype,errObj) {
	alert("Error: "+errObj.number
		+"\nType: "+errObj.name
		+"\nDescription: "+errObj.description
		+"\nSource Object Id: "+errObj.srcElement.instanceId
	);
}

