// JavaScript Document
// prepare the form when the DOM is ready 
var dominio = '.frc.utn.edu.ar';
var initSesion = "/funciones/sesion/iniciarSesion.frc";
var shutSesion = "/funciones/sesion/cerrarSesion.frc";
var eCookie = "/logon.frc?e=000";
var urlLoginSeguro = 'http://www.frc.utn.edu.ar/logon.frc';

function initPage() {
	accesosPrincipales();
	setServicio();
	initSugerencias();
	$('#tips').cycle({ fx:'scrollRight',  delay: -700});
	$('#banner0').cycle({ fx:'scrollRight', random:1 ,  delay: -2500});	
	$('#banner1').cycle({ fx:'scrollLeft', random:1 ,  delay: -1000});	
}
function accesosPrincipales(){
jQuery(document).bind('keydown', 'f1',function (evt){location.href = '/ayuda/default.frc?i=8&t=1'; return false;});
jQuery(document).bind('keydown', 'Alt+Shift+i',function (evt){location.href = urlLoginSeguro; return false;});
jQuery(document).bind('keydown', 'Alt+Shift+p',function (evt){location.href = '/'; });
jQuery(document).bind('keydown', 'Alt+Shift+a',function (evt){location.href = '/academico3/'; return false; });
jQuery(document).bind('keydown', 'Alt+Shift+m',function (evt){rMa(document.forms.login); return false; });
jQuery(document).bind('keydown', 'Alt+Shift+f',function (evt){aFd(document.forms.frmFLog); return false;});
jQuery(document).bind('keydown', 'Alt+Shift+v',function (evt){aUv(document.forms.form); return false;});
jQuery(document).bind('keydown', 'Alt+Shift+b',function (evt){location.href = '/BibliotecaCentral/Busqueda.asp'; return false; });
}
function setServicioLogon(id) { setPaginaCookieCompleto(id); location.href = urlLoginSeguro; }
function setServicio() { $("#servicioElegido").html(getServicio(getPaginaCookie())); }
function getServicio(id) {
	var r = "Web Principal";
	switch(id) {
		case '1': 	
		r = r;	break;
		case '2': 
		r = "Autogestión"; break;
		case '3': 
		r = "Prensa y Protocolo"; break;
		case '4': 
		r = "Foros de Discusión"; break;				
		case '5': 
		r = "Correo"; break;
		case '6': 
		r = "Educación Virtual"; break;
		case '7': 
		r = "SAP"; break;				
		case '8': 
		r = "Portal"; break;					
	}
	return r;
}
function setPaginaCookie(pagina) {	$.cookie("pag",pagina,{expires:14}); }
function setPaginaCookieCompleto(pagina) {	$.cookie("pag", pagina, {expires:14, path: '/', domain: dominio}); }
function getPaginaCookie() {	return $.cookie('pag'); }			
function cambiarUsuario() {
		$('#txtUsuario').show();
		$('#lblUsuarioCompleto').text('');

		$('#elArroba').text('@');
		$('#txtDominios').show();

		$('#tblRecordar').show();
		$('#tblCambiarUsuario').hide();
		//por defecto la web
		var n = "chk1";
		var i = "#"+n;
		setCheck(n,i);
		
		delUsuarioCookie();
		setRecordarCookie(0);
		$('#txtUsuario').attr('value','');		
		$('#pwdClave').attr('value','');				
		$('#txtUsuario').focus();
}
function setCheck(n,i) {
	$('#frmPagina input:checkbox').attr("checked", "");
	$('#frmPagina '+i).attr("checked", "checked");
	var elId = n.replace('chk','');
	if (elId==6) { mostrarLogonUVInvitado(); } 
	else { ocultarLogonUVInvitado();}
	setPaginaCookieCompleto(elId);
	setServicio();
}
function setRecordarCookie(v) { $.cookie('rec',v,{expires:14}); }
function delRecordarCookie() { $.cookie('rec',null); }
function getRecordarCookie() { return $.cookie('rec'); }
function setRecordar() {
var s = '';
if ($("#rec").attr('checked')) s = 1;
else s = 0;
setRecordarCookie(s);
setUsuarioCookie();
}
function delUsuarioCookie() { $.cookie('usr',null); }
function setUsuarioCookie() {
var u = getUsuario() + getDominio();
$.cookie("usr",u,{expires:14});
}
function getUsuarioCookie() { 
var v =$.cookie("usr");
var r ='';
if (v) r = v;
else r = '';
return r; }
function getUsuarioNombreCookie() { var v = getUsuarioCookie();  return  v.split('@')[0]; }
function getUsuarioDominioCookie() { var v = getUsuarioCookie();  return  v.split('@')[1]; }
function getUsuarioDominioSimpleCookie() { 
	var v = getUsuarioCookie();  
	var dominioCompuesto = v.split('@')[1];
	var dominioSimple = '';
	if (dominioCompuesto) 
		dominioSimple = dominioCompuesto.replace(dominio,'');
	return dominioSimple;	
 }
function getUsuario() { return $('#txtUsuario').fieldValue(); }
function setUsuario(usr) { $('#txtUsuario').val(usr); }
function getDominio() {
var str = '';
          $("#txtDominios option:selected").each(function () {
                str += $(this).text();
              });
			  str = '@' + str + dominio;
			  return str;
}

function setDominio(dom) {
var str = "#txtDominios option:contains("+dom+")";
$(str).attr("selected", true);
}
function getClave()  { return $('#pwdClave').fieldValue(); }
function validar(formData, jqForm, options) { 
    var usernameValue = getUsuario();
    var passwordValue = getClave();
 
    if (!usernameValue[0]) { 
        alert("Debe ingresar el Usuario para continuar.\n - El usuario no debe contener espacios en blanco.");
        return false; 
    }
	var p = passwordValue[0];
	var pt = p.length;
    if ((!p) || (pt==0) || (pt < 4)) { 
        alert("Debe ingresar la Contraseña para continuar.");
        return false; 
    } 
	setRecordar();
	document.frmLogon.action = initSesion;	
	document.frmLogon.submit();
}
function logout() {
	document.frmLogOut.action = shutSesion;
	document.frmLogOut.submit();
}
$("#txtDominios").change(function () {
          var str = "";
          $("#txtDominios option:selected").each(function () {
                str += $(this).text();
              });
			  str = "@" + str + ".frc.utn.edu.ar";
          $("#dominioAMostrar").text(str);
        })
        .change();

  $("#txtUsuario").keypress(function (e) {
  $("#teclado").text(e.which);
  if (e.which==0)  {$("#usuarioAMostrar").text(this.value); }
      if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                        || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("#usuarioAMostrar").append($("<span/>")).children(":last").append(document.createTextNode(c));
      } else if (e.which == 8) {
        // backspace in IE only be on keydown
        $("#usuarioAMostrar").children(":last").remove();
      }
    });
	
	  $("#pwdClave").keypress(function (e) {
	  	$("#usuarioAMostrar").text(getUsuario());
		  $("#dominioAMostrar").text(getDominio());
      });
	
	$("#rec").click(setRecordar);


function psl(pwd){
	var	length = pwd.length, level = 0;
	if(length > 4) {
		level = 1;
		if(length > 5) {
			if(/[a-z]/.test(pwd) && /[A-Z]/.test(pwd) && /[0-9]/.test(pwd))
				level = 3;
			else if(
				(/[a-z]/.test(pwd) && (/[A-Z]/.test(pwd) || /[0-9]/.test(pwd))) ||
				(/[0-9]/.test(pwd) && (/[A-Z]/.test(pwd) || /[a-z]/.test(pwd))) ||
				(/[A-Z]/.test(pwd) && (/[a-z]/.test(pwd) || /[0-9]/.test(pwd)))
			)
				level = /[\x20-\x2F]|[\x3A-\x40]|[\x5b-\x60]|[\x7B-\uFFFF]/.test(pwd) ? 3 : 2;
		};
	};
	return level;
};
function checkSecurity(inputId, securityId, submitId){
		if ( $('#tblMostrarNivel').is(':visible') ) { 
		var security_levels = ["No Segura","Seguridad Baja","Seguridad Media","Seguridad Alta"];
		var v = $('#'+inputId).val(); 
		var level = psl(v);
		var security_informations = document.createElement("P");
		security_informations.id = securityId;
		security_informations.className = "pwdlevel".concat(level);
		security_informations.appendChild(document.createTextNode(security_levels[level]));
		
		var	oldinformations = document.getElementById(securityId);
		oldinformations.parentNode.replaceChild(security_informations, oldinformations);
	}
};
function mostrarLogonUVInvitado() { $('#logonInvitadoUV').show(); }
function ocultarLogonUVInvitado() { $('#logonInvitadoUV').hide(); }
function iniciarSesionUVInvitado() { document.guestlogin.submit(); } 
function oBw(theURL,winName,features) { window.name='WebPrincipal';  window.open(theURL,winName,features);}
function pRt(psBarra) { 
var rEs; 
if (psBarra) rEs = location.protocol + "//";
else rEs = location.protocol; 
return rEs; }

/* ---- SCRIPT PARA EL ACCESO AL MAIL ---- */
function rMa(frm) {
//$('#enlaceMail').attr('href','#');
var clav = dCr(frm.passwd.value); //var aCt = frm.action;
var aCt = 'correo.frc.utn.edu.ar/login.cgi';
frm.action =  'http://' + aCt; //pRt(true) 
frm.passwd.value = clav;	
frm.submit();
}
/* ---- SCRIPT PARA LOS FOROS DE DISCUSION ---- */
function aFd(frm) {
var clav = dCr(frm.pword.value); //var aCt = frm.action;
var aCt = 'www.foros.frc.utn.edu.ar/login.asp?$sid=&mode=login';
frm.action =  'http://' + aCt;//pRt(true)
frm.pword.value = clav;
frm.submit();
}
/* ---- SCRIPT PARA UV ---- */
function aUv(frm) {
var clav = dCr(frm.password.value); //var aCt = frm.action;
frm.password.value = clav;
frm.submit();
}

function dCr(cadena) {
var encrip="";
for(i=0;i<cadena.length;i += 2) {	var entrada = parseInt(cadena.substr(i,2)) + 23;
entrada = unescape('%' + entrada.toString(16));
encrip += entrada;	  }
return unescape(encrip);
}

$("#pwdNueva").blur(function() {
	$("#pwdConfirmar").valid();
});
function IsSpace(s) {
  var flag= false;
  for (i = 0; i < s.length; i++) {
     if (s.substring(i, i+1) == ' ') {
        flag = true;
        break;
     }
  }
  return(flag);
}
/*inicio sugerencias*/
function crearUISugerencia() { 
if ($('#tblSugerencia').length==0) { 
	$('#frmSugerencias').append($( [
			'<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center" id="tblSugerencia">',
			  '<tr><td colspan="3" bgcolor="#E4F1F9" style="font-size:11px;" onclick="javascript:$(\'#tblSugerenciaMain\').show(\'slow\');">&nbsp;',
			  '<img src="/imagenes/o.gif"  width="22" height="19" border="0" style="margin:8px;" align="absmiddle"/><img src="/imagenes/sep0.jpg" alt="|" width="1" height="27" border="0" style="margin:4px;margin-left:10px; margin-right:10px;" align="absmiddle" /> ',
				'<span style="margin-left:0px; font-weight:bold;">Nos interesa tu opini&oacute;n.</span><br />',			
					'<table width="87%" border="0" cellspacing="4" cellpadding="0" align="right" id="tblSugerenciaMain"><tr>',
					'<td><textarea id="txtMs" name="txtMs" rows="2" cols="40" style="font-size:11px;"></textarea></td>',
					 '</tr><tr><td>',
					'<input type="submit" id="btn" name="btn" value="Enviar" class="boton" />',
					'<input type="button" name="btnCerrar" value="Cerrar" class="boton" onclick="javascript:$(\'#msjSugerencia\').hide(\'slow\');" />',
					'</td></tr></table>',
'</td></tr><tr>',
			  '</tr></table>'
	].join('') )); 
	}
$('#tblSugerenciaMain').hide();
//$('#msjSugerencia').slideToggle();
}

function crearUIRespuesta() { 
if ($('#tblRespuesta').length==0) { 
	$('#respuesta').empty();
	$('#resSugerencia').append($( [
		'<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center" style="margin:0px;margin-left:0px;border:1px solid #66CC66" id="tblRespuesta">',
		  '<tr><td colspan="3" bgcolor="#99CC99"><br />',
			'<div id="respuesta" style="color:#006633; font-weight:bold; font-size:14px"><img id="ok" src="../imagenes/ok.gif" style="display:inline; margin-left:10px; margin-right:10px;" />&nbsp;',
			'<a href="#" onclick="javascript:$(\'#resSugerencia\').hide(\'slow\');" style="font-size:10px;color:#006600">Cerrar</a>',
			'</div><br /></td></tr><tr>',
			'<td width="1" height="1%" align="right" valign="top"><img src="imagenes/bdr00.gif" width="10" height="10" /></td>',
			'<td width="100%" height="1%" bgcolor="#99CC99"></td>',
			'<td width="1" height="1%" align="left" valign="top"><img src="imagenes/bdr11.gif" width="10" height="10" /></td>',
			'</tr></table>'	
	].join('') )); 
	}
}

function initSugerencias() { 
	var options = { 
        success:       respuestaSugerencia,  // post-submit callback 
 
        url:       '/scripts/app/sugerencias.frc',         
        type:      'post',        
        dataType:  'xml',    
		beforeSubmit: validate
    }; 

	crearUISugerencia();	
    $('#frmSugerencias').ajaxForm(options); 
	
} 
function req(formData, jqForm, options) { return false; } 
 
function respuestaSugerencia(responseText, statusText)  { 
    var mensaje = $('mensaje', responseText).text(); 
    var estado = $('estado', responseText).text();
	if (estado == 1) {	
		$('#msjSugerencia').hide('fast');
		crearUIRespuesta();
		$('#resSugerencia').show();
		$('#respuesta > #ok').after(mensaje);
	} else {
		$('#msjSugerencia').hide();
		$('#resSugerencia').show();
		$('#respuesta').text('Ha occurrido un error');
	}	
	
} 

function validate(formData, jqForm, options) { 
	var mensaje = $('#frmSugerencias #txtMs').fieldValue(); 
	if ((!mensaje) || (mensaje[0].length==0)) { 
		alert("Ingresa tu comentario, Por favor...");
		return false;
	}	
}
/*fin sugerencias*/
/*jquery.hotkeys*/
(function(jQuery){jQuery.fn.__bind__=jQuery.fn.bind;jQuery.fn.__unbind__=jQuery.fn.unbind;jQuery.fn.__find__=jQuery.fn.find;var hotkeys={version:'0.7.9',override:/keypress|keydown|keyup/g,triggersMap:{},specialKeys:{27:'esc',9:'tab',32:'space',13:'return',8:'backspace',145:'scroll',20:'capslock',144:'numlock',19:'pause',45:'insert',36:'home',46:'del',35:'end',33:'pageup',34:'pagedown',37:'left',38:'up',39:'right',40:'down',109:'-',112:'f1',113:'f2',114:'f3',115:'f4',116:'f5',117:'f6',118:'f7',119:'f8',120:'f9',121:'f10',122:'f11',123:'f12',191:'/'},shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"},newTrigger:function(type,combi,callback){var result={};result[type]={};result[type][combi]={cb:callback,disableInInput:false};return result;}};hotkeys.specialKeys=jQuery.extend(hotkeys.specialKeys,{96:'0',97:'1',98:'2',99:'3',100:'4',101:'5',102:'6',103:'7',104:'8',105:'9',106:'*',107:'+',109:'-',110:'.',111:'/'});jQuery.fn.find=function(selector){this.query=selector;return jQuery.fn.__find__.apply(this,arguments);};jQuery.fn.unbind=function(type,combi,fn){if(jQuery.isFunction(combi)){fn=combi;combi=null;}
if(combi&&typeof combi==='string'){var selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();var hkTypes=type.split(' ');for(var x=0;x<hkTypes.length;x++){delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];}}
return this.__unbind__(type,fn);};jQuery.fn.bind=function(type,data,fn){var handle=type.match(hotkeys.override);if(jQuery.isFunction(data)||!handle){return this.__bind__(type,data,fn);}
else{var result=null,pass2jq=jQuery.trim(type.replace(hotkeys.override,''));if(pass2jq){result=this.__bind__(pass2jq,data,fn);}
if(typeof data==="string"){data={'combi':data};}
if(data.combi){for(var x=0;x<handle.length;x++){var eventType=handle[x];var combi=data.combi.toLowerCase(),trigger=hotkeys.newTrigger(eventType,combi,fn),selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();trigger[eventType][combi].disableInInput=data.disableInInput;if(!hotkeys.triggersMap[selectorId]){hotkeys.triggersMap[selectorId]=trigger;}
else if(!hotkeys.triggersMap[selectorId][eventType]){hotkeys.triggersMap[selectorId][eventType]=trigger[eventType];}
var mapPoint=hotkeys.triggersMap[selectorId][eventType][combi];if(!mapPoint){hotkeys.triggersMap[selectorId][eventType][combi]=[trigger[eventType][combi]];}
else if(mapPoint.constructor!==Array){hotkeys.triggersMap[selectorId][eventType][combi]=[mapPoint];}
else{hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length]=trigger[eventType][combi];}
this.each(function(){var jqElem=jQuery(this);if(jqElem.attr('hkId')&&jqElem.attr('hkId')!==selectorId){selectorId=jqElem.attr('hkId')+";"+selectorId;}
jqElem.attr('hkId',selectorId);});result=this.__bind__(handle.join(' '),data,hotkeys.handler)}}
return result;}};hotkeys.findElement=function(elem){if(!jQuery(elem).attr('hkId')){if(jQuery.browser.opera||jQuery.browser.safari){while(!jQuery(elem).attr('hkId')&&elem.parentNode){elem=elem.parentNode;}}}
return elem;};hotkeys.handler=function(event){var target=hotkeys.findElement(event.currentTarget),jTarget=jQuery(target),ids=jTarget.attr('hkId');if(ids){ids=ids.split(';');var code=event.which,type=event.type,special=hotkeys.specialKeys[code],character=!special&&String.fromCharCode(code).toLowerCase(),shift=event.shiftKey,ctrl=event.ctrlKey,alt=event.altKey||event.originalEvent.altKey,mapPoint=null;for(var x=0;x<ids.length;x++){if(hotkeys.triggersMap[ids[x]][type]){mapPoint=hotkeys.triggersMap[ids[x]][type];break;}}
if(mapPoint){var trigger;if(!shift&&!ctrl&&!alt){trigger=mapPoint[special]||(character&&mapPoint[character]);}
else{var modif='';if(alt)modif+='alt+';if(ctrl)modif+='ctrl+';if(shift)modif+='shift+';trigger=mapPoint[modif+special];if(!trigger){if(character){trigger=mapPoint[modif+character]||mapPoint[modif+hotkeys.shiftNums[character]]||(modif==='shift+'&&mapPoint[hotkeys.shiftNums[character]]);}}}
if(trigger){var result=false;for(var x=0;x<trigger.length;x++){if(trigger[x].disableInInput){var elem=jQuery(event.target);if(jTarget.is("input")||jTarget.is("textarea")||jTarget.is("select")||elem.is("input")||elem.is("textarea")||elem.is("select")){return true;}}
result=result||trigger[x].cb.apply(this,[event]);}
return result;}}}};window.hotkeys=hotkeys;return jQuery;})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('r.5=w(k,d,a){4(m d!=\'H\'){a=a||{};4(d===p){d=\'\';a.3=-1}2 g=\'\';4(a.3&&(m a.3==\'n\'||a.3.u)){2 f;4(m a.3==\'n\'){f=G E();f.C(f.B()+(a.3*z*s*s*v))}o{f=a.3}g=\'; 3=\'+f.u()}2 b=a.7?\'; 7=\'+(a.7):\'\';2 e=a.9?\'; 9=\'+(a.9):\'\';2 l=a.t?\'; t\':\'\';6.5=[k,\'=\',K(d),g,b,e,l].I(\'\')}o{2 h=p;4(6.5&&6.5!=\'\'){2 c=6.5.F(\';\');D(2 i=0;i<c.8;i++){2 j=r.A(c[i]);4(j.q(0,k.8+1)==(k+\'=\')){h=y(j.q(k.8+1));x}}}J h}};',47,47,'||var|expires|if|cookie|document|path|length|domain|||||||||||||typeof|number|else|null|substring|jQuery|60|secure|toUTCString|1000|function|break|decodeURIComponent|24|trim|getTime|setTime|for|Date|split|new|undefined|join|return|encodeURIComponent'.split('|'),0,{}))
