/*													
* javascript to make useful The iframe frameAuthEvolved inserted at default.asp file.
* Author:				fcabezas@riskamerica.com
* Last change´s Date:	Nov, 12th 2009
* Obs:					modified to work with old look and feel of www.riskamerica.com
*/

/*
* Init process to make a useful interface with jQuery
* using top.window (not document) to be consistent with the default.asp file.
*
*/
$(top.window).ready( function() {
	var sesionState=checkSession()
	var htmlStr="";
	if (sesionState=="Si"){
		htmlStr=htmlNoLogueado();
		$("#contentDiv").html(htmlStr);			
		setEventsLogueado();
		setElementsLogueado();
	} else {
		htmlStr=htmlNoLogueado();
		$("#contentDiv").html(htmlStr);
		setElementsNoLogueado();
		setEventsNoLogueado();	
	}
});

/*
* Author:				fcabezas@riskamerica.com
* Args:					no argument
* return:				the value got using AJAX, {SI, NO}, result from check session at server side.
*/
function checkSession(){
	var result="";
	$.ajax({
			url: 		"engine/auth.asp",
			type: 		"POST",
			data: 		"engineAuthAction=getSessionState",
			cache: 		false,
			async:		false,
			success:	function (html) {	result=html;	},
			error:	function(xhr) {
						errorMessage="No se puede establecer conexi&oacute;n con el servidor para chequear sesi&oacute;n."; 
						// error de conexion o no se pudo realizar la llamada AJAX al sitio
						if (top.window.docDialog){	
								top.window.docDialog
									.html("<div style='font-size:14px;paddig:0;margin:0;color:#FF1111;'><center>"+errorMessage+"</center></div>")
									.dialog('option', 'title', '').dialog('open');	
						}
				}
	});
	return result;
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments
* action:				rebuild menu async.
*/
function getBuildMenuList() {
	var result="";
	var dataString = 'engineMenuAction=buildMenuList';
	var dataArray = {engineMenuAction:"buildMenuList"};
	$.ajax({
		url: 		"engine/menu.asp",
		type: 		"POST",
		data: 		dataArray,
		cache: 		false,
		async:		true,
		success:	function (html) {	$('#menu', top.document).html(html);	reloadMenuEvents();},
		error:		function(xhr) {
						errorMessage="No fue posible recargar el men&uacute;."; 
						// error de conexion o no se pudo realizar la llamada AJAX al sitio
						if (top.window.docDialog){	
								top.window.docDialog
									.html("<div style='font-size:14px;paddig:0;margin:0;color:#FF1111;'><center>"+errorMessage+"</center></div>")
									.dialog('option', 'title', '').dialog('open');	
						}
					}	
	});
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments
* action:				reload menu js events.
*/
function reloadMenuEvents() {
	$.ajax({
		  type:		"GET",
		  url:		"/jquery/menuRA/menu.js",
		  dataType: "script",
		  async:	true
		});
	} 

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments
* action:				send login to system
*/
function sendLoginToSystem(){
	var timeGap=100;
	var errorMessage=null;
	if ($("#Email").val()=="")		{	errorMessage=strW[1];}
	if ($("#Password").val()=="")	{	errorMessage=strW[1];}
	if ($("#Email").val()!="" && $("#Password").val()!=""){
		var dataString = 'engineAuthAction=loginToSystem&email='+ $("#Email").val() + '&password=' + $("#Password").val() ; 		
		$.ajax({
			url: 	"engine/auth.asp",
			type: 	"POST",
			data: 	dataString,
			cache: 	false,
			async:	false,
			success:	function (html) {
							if (html=="OK") {
								//Trigger from here before to change the #contentDiv
								var stat=sendLoginToSites();
								(EmailVal=="") ? (EmailVal=$("#Email").val() ) : 1;
								//var stat=reloadMenu();
								setTimeout("changeContent()",SitesToAuth.length*timeGap);			
							} else	{
								errorMessage=strW[2]; // Usuario o password incorrectos
								$("#identFrameAuth").text(strW[2]);
							}
							return false;
						},
			error:	function(xhr) {	errorMessage="Error al intentar ingresar al sitio.";	}/*frameAuthEvolvedMess[5];// error de conexion o no se pudo realizar la llamada AJAX al sitio */
		});
	}	
	if (errorMessage){	
			top.window.docDialog
					.html("<div style='font-size:14px;paddig:0;margin:0;color:#FF1111;'><center>"+errorMessage+"</center></div>")
					.dialog('option', 'title', '').dialog('open');	
	}
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments
* action:				change elements to show a login successful.
*/
function changeContent(){
	//var htmlStr=htmlLogueado();
	//$("#contentDiv").html(htmlStr);
	setEventsLogueado();
	setElementsLogueado();
	reloadContenido();
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments but use SitesToAuth stablished on default.asp. 
* action:				create a session for each site.
*/
function sendLoginToSites(){
	var sites=SitesToAuth;	
	var Stat=true;
	var email=$("#Email").val();
	var password=$("#Password").val();

	for(var i = 0; i<sites.length;i++){
		/*
		if (email == 'fcabezas@riskamerica.com')
		{
			alert(sites[i])
		}
		*/
		var dataArray = {'engineAuthAction':'loginToSites',	'email': email, 'password' : password }; 
		var dataString = 'engineAuthAction=loginToSites&email='+ email + '&password=' + password ;
		var urlStr="http://"+sites[i]+"/engine/auth.asp?"+dataString+"&jsoncallback=?";
		$.getJSON(urlStr,   function(data){  Stat=Stat*data; },Stat);
	}
	return Stat;
}


/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* return:				the first and second name to the session's user.
*/
function getSessionUser() {
	var response='';
	$.ajax({
		url:		"engine/auth.asp", 
		data:		"engineAuthAction=getUserName", 
		cache:		false,
		type: 		"POST",
		async:		false,
		success:	function(html){ response=html;},
		error:		function(xhr) {
						errorMessage="No fue posible definir el nombre de usuario."; 
						// error de conexion o no se pudo realizar la llamada AJAX al sitio
						if (top.window.docDialog){	
								top.window.docDialog
									.html("<div style='font-size:14px;paddig:0;margin:0;color:#FF1111;'><center>"+errorMessage+"</center></div>")
									.dialog('option', 'title', '').dialog('open');	
						}
					}
		});
	return response;
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				Set html elements inside noLogged html document.
*/
function setElementsNoLogueado(){
	$("#identFrameAuth").text(strW[1]);
	$("#changePasswdTr").hide("fast");
	var c = new $.cookie();
	c.cookieID="RiskAmerica";
	c.get();
	(EmailVal=="") && (EmailVal=c.usr);
	$("#Email").val(EmailVal);
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				Set events with noLogged html.
*/
function setEventsNoLogueado()	{
	$("#btnLogin").click(		function(){	sendLoginToSystem(); return false; });
	$("#submitButton").click(	function(){	sendLoginToSystem(); return false; });
	$("#btnExit").click(		function(){	sendLogoutFromSystem(); return false; });
	$("#identFrameAuth").text(strW[1]);
	$("#Email, #Password").focus(function(){
			$(this).addClass("inputAuthFocus");
    }).blur(function(){
            $(this).removeClass("inputAuthFocus");
    });
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				Set html elements inside logged html document.
*/
function setElementsLogueado(){
	$("#identFrameAuth").html(strW[0]+getSessionUser());
	var c = new $.cookie();
	c.cookieID="RiskAmerica";
	c.get();
	EmailVal=c.usr;
	$("#Email").val(EmailVal);
	$("#Password").val("");
	$("#changePasswdTr").show("fast");
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				Set events with logged html.
*/
function setEventsLogueado()	{
	// Begin Patch
	//Bug hortega 2009: if you are logged, sometimes the login button failed in action do it.
	$("#btnLogin").click(		function(){	sendLoginToSystem(); return false; });
	$("#submitButton").click(	function(){	sendLoginToSystem(); return false; });
	// End Patch
	$("#btnExit").click(		function(){	sendLogoutFromSystem(); return false; });
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				Destroy principal session at server.
*/
function sendLogoutFromSystem()	{
	var logoutResponse="";
	var errorMessage;
	$.ajax({
						url: 		"engine/auth.asp",
						type: 		"POST",
						data: 		"engineAuthAction=logoutFromSystem",
						cache: 		false,
						async:		false,
						success:	function(html)	{	logoutResponse=html;	},
						error:		function(xhr)	{	errorMessage="Error al intentar salir del sitio.";	}
					});
	if (logoutResponse=="OK") {
		var htmlStr=htmlNoLogueado();
		$("#contentDiv").html(htmlStr);
		//var stat=reloadMenu();
		setEventsNoLogueado();
		setElementsNoLogueado();
		sendLogoutFromSites();
		reloadContenido();
	}
	if (errorMessage){	
			top.window.docDialog
					.html("<div style='font-size:14px;paddig:0;margin:0;color:#FF1111;'><center>"+errorMessage+"</center></div>")
					.dialog('option', 'title', '').dialog('open');	
	}
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments but use SitesToAuth stablished on default.asp. 
* action:				destroy session for each site.
*/
function sendLogoutFromSites(){
	var sites=SitesToAuth;
	for(var i = 0; i<sites.length;i++){
		var dataString = 'engineAuthAction=logoutFromSites&email='+ $("#Email").val() + '&password=' + $("#Password").val() ;
		var urlStr="http://"+sites[i]+"/engine/auth.asp?"+dataString+"&jsoncallback=?";
		$.getJSON(urlStr,function(data){ 1;});
	}
}

/*
* Author:				fcabezas@riskamerica.com
* Args:					no arguments. 
* action:				reload contenido frame.
*/
function reloadContenido() {
	// comentado mientras no se separe el menu como div.
	parent.contenido.location.reload();
	//alert("Pause")
	//$("#contenido", top.document).document.location.reload(); //importante descomentar para funcionalidad completa hasta aislar el menu. (lograr reload selectivo)
}

function htmlLogueado(){
	var html="";
	html+="<input type='hidden' class='aIpt' name='Email' id='Email' value='' >";
	html+="<input type='hidden' class='aIpt' name='Password'  id='Password' value=''>";
	html+="<div class='logueado tablaAuth'>";
	html+="		<div class='loginLineElementRight' style='height:16px; padding-right:4px; padding-top:8px; padding-bottom:0;border:0px solid #FFFFFF'>";
	html+=" 		<img name='btnExit' id='btnExit' src='/Images/salir.gif' border='0' title='"+frameAuthEvolvedMess[0]+"' ";
	html+=          "style='cursor:hand;width:16px; height: 16px' onMouseOver=\"btnExit.src='/Images/salir_on.gif';\" "; 
	html+=          "onMouseOut=\"btnExit.src='/Images/salir.gif';\">";
	html+=" 	</div>";
	html+="		<div class='loginLineElementRight' id='identFrameAuth' style='font-weight: bold; height:16px; padding-right:8px;padding-top:8px;border:0px solid #FFFFFF'>&nbsp;</div>";
	html+="		<div class='clearBoth' style='width:0; height:0; padding:0; margin:0; font-size:0px;'></div>"
	html+="		<div class='loginLineElementRight cp' style='padding-right:28px;padding-bottom:8px;border:0px solid #FFFFFF'>";
	html+="			<a class='cp' href='' onClick='javascript:openChangePassword(); return false;'>"+frameAuthEvolvedMess[2]+"</a>";
	html+="		</div>";					
	html+="</div>";
	html=supportOldLookAndFeel();
	return html;
}

function htmlNoLogueado() {
	var html="";
	html+="<div class='nologueado tablaAuth'>";
	html+="		<div class='loginLineElementRight' style='width:30px; padding-top:4px'>&nbsp;</div>";
	html+="		<div class='loginLineElementRight'  style='width:146px; padding-top:4px'>";
	html+="	         <input class=inputAuth  name=Email id=Email size=28 style='width:140px;' tabindex=1>";
	html+="	    </div>";
	html+="		<div class='loginLineElementRight' style='padding-top:4px'>"+frameAuthEvolvedMess[4]+":</div>";
	html+="		<div class='clearBoth' style='width:0; height: 2px; padding:0; margin:0; border:0px solid #FFFFFF;font-size:0px; '></div>";
	html+="		<div id='progressbar' class='loginLineElementRight' style='padding-top:1px;padding-bottom:1px;width:142px;height:4px; border:0px solid; padding-right:30px; font-size:0px;'>";
	html+="			<div id='progressbarStat' class='loginLineElementRight' style='width:100%; height:1px; padding-top:1px;padding-bottom:1px; padding-right:0; padding-left:0;background-color:#11F011; border: none;display:none; font-size:0px;'></div>";
	html+="			<div class='clearBoth' style='width:0; height:0; padding:0; margin:0; font-size:0px;	'></div>";
	html+="		</div>";
	html+="		<div class='clearBoth' style='width:0; height:0; padding:0; margin:0; font-size:0px;'></div>";
	html+="		<div class='loginLineElementRight' style='width:30px;border: 0px #FFFFFF solid; padding-bottom:2px;'>";
	html+="			<img name='btnLogin' id='btnLogin' src='/Images/entrar.gif' border='0' title='"+frameAuthEvolvedMess[1]+"' style='width:16px;height:16px;cursor:hand; margin:0px; padding-right:7px;' onMouseOver='btnLogin.src=\"/Images/entrar_on.gif\";' onMouseOut='btnLogin.src=\"/Images/entrar.gif\";'> ";
	html+="			<input id='submitButton' type=submit  style='width:1px;height:1px;position:absolute;top:-100px;left:-100px;' tabindex=-1>";
	html+="		</div>";
	html+="		<div class='loginLineElementRight' style='width:146px; padding-bottom:2px;'>";
	html+="			<input class=inputAuth name='Password' id='Password' type=password style='width:140px;' tabindex=2>";
	html+="		</div>";
	html+="		<div class='loginLineElementRight' style='padding-bottom:2px;'>"+frameAuthEvolvedMess[3]+":</div>";
	html+="		<div class='clearBoth' style='width:0; height:0; padding:0; margin:0; font-size:0px;'></div>";
	html+="	</div>";
	html=supportOldLookAndFeel();
	return html;
}

function supportOldLookAndFeel() { 
var html="";
html="<table cellpadding='0' cellspacing='0' width='163px' border=0 class='encabezadoAntiguo' style='border:0px solid #FFFFFF'>";
html+="		<tr>";
html+="			<td colspan='3' nowrap height=18 style='font: bold 10px Arial; color:#FFFFFF;' id='identFrameAuth'>"+strW[1]+"</td>";
html+="		</tr>";
html+="		<tr>";
html+="			<td class=IcnWng style='font-size:15px;'>*</td>";
html+="			<td colspan=2><input class=aIpt name=Email id='Email' value='' size=24 style='font-size:10px; height: 15px; color:#000000'></td>";
html+="		</tr>";
html+="		<tr>";
html+="			<td class=IcnWeb style='font-size:18px;'>Ñ</td>";
html+="			<td><input class=aIpt name=Password id='Password' type=password size=16 style='font-size:10px; height: 15px; color:#000000'></td>";
html+="			<td nowrap style='valign:bottom;'>";
html+="			 	<img id='btnLogin' name='btnLogin' src='/Icono/btnLogin2.gif' border='0' title='"+frameAuthEvolvedMess[1]+"'   style='cursor:hand;' onmouseover="+'"'+"btnLogin.src='/Icono/btnLoginHover2.gif';"+'"'+" onmouseout="+'"'+"btnLogin.src='/Icono/btnLogin2.gif';"+'"'+" >";
html+="				<img id='btnExit' name='btnExit' src='/Icono/btnExit2.gif' border='0' title='"+frameAuthEvolvedMess[0]+"'  style='cursor:hand;' onmouseover="+'"'+"btnExit.src='/Icono/btnExitHover2.gif';"+'"'+" onmouseout="+'"'+"btnExit.src='/Icono/btnExit2.gif';"+'"'+" >";
html+="				<input id=submitButton type=submit style='width:1px;height:1px;position:absolute;top:-100px;left:-100px;'>";
html+="			</td>";
html+="		</tr>";
html+="		<tr valign=top height='8px' >";
html+="			<td></td><td colspan='2' style='text-align:rigth;' valign='top' class='encabezadoAntiguo cp' >";
html+="				<div id='changePasswdTr' style='display: none'><a   class='cp' style='text-align:top;' href='' onClick="+'"'+"javascript:window.open('changePasswd.asp','passwdChange','width=400,height=320,toolbars=no,scrollbars=no,location=no,statusbars=no,menubars=no,resizable=no');return false;"+'"'+">Cambiar Clave</a></div>";
html+="			</td>";
html+="		</tr>";

html+="	</table>";
return html;
}
/*		<%
			if Session("IDUser") <> "" then
		%>
		<tr valign="top" height="8px">
			<td></td>
			<td style='text-align:left;' valign='top' class='encabezadoAntiguo cp' height=10>
				<a class='cp' style='text-align:top;' href="" onClick="javascript:window.open('changePasswd.asp','passwdChange','width=400,height=320,toolbars=no,scrollbars=no,location=no,statusbars=no,menubars=no,resizable=no');return false;">Cambiar Clave</a>
			</td>
			<td></td>
		</tr>
		<%
			end if 
		%>
*/		


function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};


//alert("Fin")
