var imageState = "site/images/inicio_down.jpg";
var idImageState = "home_img";
var lastOpenMenuId = new Object();
var urlrelocate = '/dtelmex/';

function changeTableMenu (tableId, level) {
	if (lastOpenMenuId[level]) {
		if (document.getElementById ("TABLE" + lastOpenMenuId[level]).style.display == '')
			document.getElementById ("TABLE" + lastOpenMenuId[level]).style.display = "none";
	}
	
	document.getElementById ("TABLE" + tableId).style.display = (document.getElementById ("TABLE" + tableId).style.display == '')? "none" : "";
	lastOpenMenuId[level] = tableId;
}

function changeImageMenu (id, newImage, oldImage) {
	if (idImageState) {
		document.getElementById (idImageState).src = imageState;
	}
	
	document.getElementById (id).src = newImage;
	idImageState = id;
	imageState = oldImage;
}

function showPage (pageName, conteiner) {
	var objLayer = document.getElementById (conteiner);
	objLayer.innerHTML = '<img src="site/images/busy.gif" width="14" height="14" hspace="5"><span class="verdanabasica">Cargando .... <br />Por favor espera</span>';
	var url = "servlet/FollowLink?page_name=" + pageName + "&adminMode=false";
	var ht = HTTPRequest.get (
		{
			'url' : url,
			'cache' : true,
			'onSuccess' : function ( request )	{
				objLayer.innerHTML = request.responseText;
			},
			'onError' : function ( obj )	{
				objLayer.innerHTML = '<span class="verdanabasicarojo"><b>En este momento el servicio requerido no est&aacute; disponible.</b></span><br /><span class="verdanabasica"><b>Puedes recargar esta p&aacute;gina para intentarlo otra vez.</b></span>';
			}
		}
	);
}

function showContent (idContent, displayType, conteiner) {
	var objLayer = document.getElementById (conteiner);
	objLayer.innerHTML = '<img src="site/images/busy.gif" width="14" height="14" hspace="5"><span class="verdanabasica">Cargando .... <br />Por favor espera</span>';
	var url = "servlet/FollowLink?adminMode=false&idFile=" + idContent + "&displayType=" + displayType;
	var ht = HTTPRequest.get (
		{
			'url' : url,
			'cache' : true,
			'onSuccess' : function ( request )	{
				objLayer.innerHTML = request.responseText;
			},
			'onError' : function ( obj )	{
				objLayer.innerHTML = '<span class="verdanabasicarojo"><b>En este momento el servicio requerido no est&aacute; disponible.</b></span><br /><span class="verdanabasica"><b>Puedes recargar esta p&aacute;gina para intentarlo otra vez.</b></span>';
			}
		}
	);
}
/* FUNCIONES PARA ENVIAR FORMULARIO */

	function validateOptions ( validateparam ){
		for (key in validateparam){
			var  keys = key.split("-");  			
			var valelem = document.getElementById( keys[0] );
			var valelem2;
			if (valelem != undefined){
				if( keys[1] != undefined ){
					valelem2 = document.getElementById( keys[1] );					
				}
				if (validateparam[key]=='isnotempty'){
					if ( !isNotEmpty(valelem) ){							
						alert ("El campo '" + ( (valelem.alt != undefined && valelem.alt != "" ) ? valelem.alt : valelem.name ) + "' no debe estar vacio");
						valelem.focus();
						return false;
					}
				} else if (validateparam[key]=='isselected'){
					if ( !isNotEmpty(valelem) ){
						alert ("Debe Seleccionar un valor valido");
						valelem.focus();
						return false;
					}
				} else if (validateparam[key]=='ismail'){
					if ( !isEmail(valelem) ){
						alert ("La direccion de correo no es valida");
						valelem.focus();
						return false;
					}
				} else if (validateparam[key]=='isdate'){
					if ( !isDate(valelem) ){
						alert ("La Fecha es Invalida");
						valelem.focus();
						return false;
					}
				} else if (validateparam[key]=='ispasswd'){
					if ( !isPasswd(valelem) ){
						alert ("La contrase?a esta incorrecta");
						valelem.focus();
						return false;
					}
				} else if (validateparam[key]=='isdateinterval'){
					if ( !isValidInterval(valelem,valelem2) ){
						alert("Advertencia: La fecha inicial no puede ser posterior a la fecha final.");
						valelem.focus();
						return false;
					}
				}
			}
		}
		return true;
	}
	
	function isValidInterval( startDateField, endDateField ){
		var parts = startDateField.value.split ("-");
		var startDateObj = new Date(parts[0], parts[1], parts[2]);
		
		parts = endDateField.value.split ("-");
		var endDateObj = new Date(parts[0], parts[1], parts[2]);
		return ( startDateObj <=  endDateObj );
	}

	function isNotEmpty( field ){
		if (field.value != undefined){
			return (field.value.trim() != "");
		}
		return true;
	}
	
	function isSelected( field ){
		if (field.options != undefined)
			return (field.options[field.selectedIndex].value.trim() != "");
		return true
	}
	
	function isEmail( field ){
		//var str=document.validation.emailcheck.value
		if (field.value != undefined){
			var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			return (filter.test(field.value));
		}
		return true
	}

	function isDate( field ){
		if (field.value != undefined){
			return (field.value.trim() != "");
		}
		return true;
	}
	
	function isPasswd( field ){		
		if (field.value != undefined){
		}
		return true;
	}
	function sendForm3 (form, content)	{
		var layer = document.getElementById (content);
		
		var ht = HTTPRequest.submit ( form, 
			{
				'url' : form.action,
				'cache' : true,
				'onSuccess' : function ( request )	{
					layer.innerHTML = request.responseText;
					execScript (request.responseText);
				},
				'onError' : function ( obj )	{
					layer.innerHTML = '<span class="textos"><b>En este momento el servicio requerido no est&aacute; disponible.</b></span><br /><span class="textos"><b>Puedes recargar esta p&aacute;gina para intentarlo otra vez.</b></span>';
				}
			}
		);
		layer.innerHTML = '<img src="site/images/busy.gif" width="14" height="14" hspace="5"><span class="textos">Verificando datos .... <br />Por favor espera</span>';
	}

function sendForm ( formsave, idContent, validate ){
		if (validate == undefined){
			validate = new Array();
		}
		if (idContent == undefined){
			alert ("no existe el id del contenido");
			return false;
		}
		if (!validateOptions(validate))
			return;
			
		var contentID = document.getElementById(idContent);
		if (contentID){
			var result = dojo.io.bind( 
				{
					url: urlrelocate + formsave.action,
					content:	{ inline: "yes" },
					formNode : formsave,
					handler: function (type, data, evt) {				
						if(type == 'load'){
							if ( typeof( data ) == "object" ){
								contentID.innerHTML="";
								contentID.appendChild(data.firstChild);
							} else {
								contentID.innerHTML = data;
							}							
							executeScript( data );
							configCalendars( data );
							dirtyForm = false;
						} else if (type == 'error'){
							contentID.innerHTML = "Problemas Cargando El contenido";
							alert(data);
						} else {
							contentID.innerHTML = "Problemas Cargando El contenido";
							alert(data);
						}
					},
					method: formsave.method,
					multipart: false,
					mimetype: "text/html"
				} 
			)
			contentID.innerHTML = loadingHTML();			
		} else {
			alert ("Problema de la Aplicaci&oacute;n");
		}	
	}


function loadHtml ( url, addcontent, idContent ){
	
	if (idContent == undefined){
		alert ("No existe el id del contenedor!");
		return false;
	}
	
	var contentID = document.getElementById(idContent);
	if (contentID){
		contentID.innerHTML = loadingHTML();
		var params = "";
		for (key in addcontent){
			var param = key + "=" +addcontent[key];
			if( params != "" )
				params += "&"; 		
			params += param; 
		} 
		
		var ht = HTTPRequest.get (
			{
				'url' : url + "?" + params,
				'cache' : false,
				'onSuccess' : function ( request )	{
						contentID.innerHTML = request.responseText;
						executeScript(request.responseText);	
 				},
				'onError' : function ( obj ) {
					contentID.innerHTML = "Problemas Cargando El contenido";
				}
			}
		);		
		
	} else {
		alert ("Problema de la Aplicaci&oacute;n");
	}
}
window.executeScript = function( text )	{
		var startPos = text.indexOf( '<script' );
		if( startPos >= 0 )
			startPos = text.indexOf( '>', startPos ) + 1;
		while( startPos >= 0 )	{
			var endPos = text.indexOf( '<\/script>', startPos );
			var script = text.substring( startPos, endPos );
			if( window.execScript )
				window.execScript( script );
			else
				window.eval( script );
			if( endPos > startPos )	{
				startPos = text.indexOf( '<script', endPos );
				if( startPos >= 0 )
					startPos = text.indexOf( '>', startPos ) + 1;
			}
		}
	}
function loadingHTML(){
		//return "<img src='"+ INTRA_BASE_URL + "site/images/loading.gif' border='0'>";
		return "<span class='textos'>Cargando...</span>";
}

function rateFile (idFile, fileName) {
	window.open('pages/file_rate.jsp?fileName='+fileName+'&idFile='+idFile,'','width=420, height=210, scrollbars=no, resizable=no');
}

function setNodeFontSize( node, size )	{
	if( node.nodeType == 3 )	{
		if( node.parentNode.style )
			node.parentNode.style.fontSize = size;
		return;
	}

	var childNodesInt = node.childNodes;
	if( childNodesInt )	{
		for( var c = 0; c < childNodesInt.length; c ++ )	{
			setNodeFontSize( childNodesInt.item( c ), size )
		}
	}	
}

function setFontSize( size )	{
	var childNodes = document.body.childNodes;
	for( var c = 0; c < childNodes.length; c ++ )	{
		setNodeFontSize( childNodes.item( c ), size );
	}
	
	if( window.frame_content ){
		window.frame_content.setFontSize( size );
	}
}

function imprimir() {
	window.open( urlrelocate + "print.html", "", "width=563, height=500, resizable=false, scrollbars=yes");
}

function enviar(idFile) {
	window.open( urlrelocate + "pages/amigo.jsp?send=" + escape(document.location.search), "", "width=500, height=370, scrollbars=no, resizable=false");
}

/*
 FUNCIONES DE AUTENTICACION PARA CARGAR EL SITIO DEPENDIENDO DEL GRUPO DEL USUARIO
*/

	
	function validateAuthForm(){
		var login = document.getElementById('auth_login');
		var password = document.getElementById('auth_passwd');
		if (login && login.value != "");
		else { 
			alert ("Digite un valor en el login");
			login.focus();
			return false;
		}
		if (password && password.value != "");
		else{
			alert ("Digite un valor en el Password");
			password.focus();
			return false;
		}			
		sendLogin (login.value, password.value);
	}
	
	function removeOverlay(){
		thediv=document.getElementById('overlay');
		if (thediv)
			document.body.removeChild(thediv);
	}
	
	function sendLogin (login , password) {
		
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
	
		
		var thediv=document.createElement("div");
		thediv.setAttribute('id','overlay');
		thediv.style.position = 'absolute';
		thediv.style.width= '100%';
		thediv.style.height='100%';
		thediv.style.top = '0px';
		thediv.style.left = '0px';
		thediv.style.zIndex = '300';
		thediv.onclick = function () { removeOverlay(); }
		document.body.appendChild(thediv);
	
		var thediv2=document.createElement("div");
		thediv2.innerHTML = "<img src='imagenes/cargando.gif' width='100' height='100' border='0'>";	  
		thediv2.style.position = 'absolute';
		thediv2.style.width= '100px';
		thediv2.style.height = '100px';
		thediv2.style.top = (myHeight/2 - 50) + 'px';
		thediv2.style.left = (myWidth/2 -50) + 'px';
		thediv2.style.zIndex = '320';

		thediv.appendChild(thediv2);

		var url = "servlet/AuthRedirect?login=" + login + "&password=" + password;		
		var ht = HTTPRequest.get (
			{

				'url' : url,
				'cache' : false,
				'onSuccess' : function ( request )	{
					var arrtext = request.responseText.split(';');
					
					if ( arrtext.length == undefined || arrtext.length < 2){
						var newhtml = "<table width='120' cellpading='5' cellspacing='0' border='0' style='background:#FFFFFF' class='textos'><tr><td style='height:80px' valign='middle' align='center'>";
						//newhtml += request.responseText;
						newhtml += " Nombre de usuario o contrase?a inv&aacute;lidos. ";
						newhtml += "</td></tr><tr><td style='height:20px' align='center'><div style='cursor:pointer;height:15px;width:50px;border:1px solid #000000' onclick='removeOverlay()'>Cerrar</div></td></tr>";
						thediv2.innerHTML = newhtml;
					} else {
						var newhtml = "<table width='120' cellpading='5' cellspacing='0' border='0' style='background:#FFFFFF' class='textos'><tr><td style='height:80px' valign='middle' align='center'>";
						var redir="";
						for (i=1;i<arrtext.length;i++){
							if ( arrtext[i].split(":")[0] != "1"){
								newhtml += arrtext[i].split(":")[1];
								redir = arrtext[i].split(":")[0];
								i=arrtext.length;
							}
						}
						newhtml += "</td></tr><tr><td style='height:20px' align='center'></td></tr>";
						//thediv2.innerHTML = newhtml;
						document.location.href='index.jsp?site=' + redir;
					}
 				},
				'onError' : function ( obj )	{
					var newhtml = "<table width='100' cellpading='0' cellspacing='0' border='0' style='background:#FFFFFF' class='textos'><tr><td style='height:80px' valign='top'>";
					newhtml += "Problemas en la Comunicaci&oacute;n";
					newhtml += "</td></tr><tr><td style='height:20px' align='center'><div style='cursor:pointer;height:15px;width:50px;border:1px solid #000000' onclick='removeOverlay()'>Cerrar</div></td></tr>";
					thediv2.innerHTML = newhtml;
				}
			}
		);		
	}

	function closeSession(){
		var url = "servlet/AuthRedirect?destroy=true";
		var ht = HTTPRequest.get (
			{
				'url' : url,
				'cache' : false,
				'onSuccess' : function ( request )	{
					document.location.href='index.jsp';
 				},
				'onError' : function ( obj ) {
					document.location.href='index.jsp';
				}
			}
		);			
	}
	/**
	 *	This Script needs function.js
	**/

	function initTips ( )	{
		var layer = document.getElementById( 'tipsLayer' );
		if ( !layer )	{
			layer = document.createElement( 'span' );
			layer.setAttribute( 'id', 'tipsLayer' );
			document.body.appendChild( layer );
		}
		
		hideElement( layer );
		layer.innerHTML = '';
	}
	
	// Use like this: showTip ( 'see this text', '#000000', '#FFFFFF' )
	function showTip ( msg, color, bgcolor, className )	{
		var layer = null;
		var style = null;

		initTips ( );
		layer = document.getElementById ( 'tipsLayer' );
		if ( !layer )
			return;
		style = layer.style;
		layer.setAttribute( 'class', ( typeof ( className ) != 'undefined' ? 'textos' : className ) );
				
		if ( typeof ( msg ) != 'undefined' && msg != '' )	{
			document.oldMousemove = document.onmousemove;

			//if ( document.releaseEvents )
				//document.releaseEvents( Event.MOUSEMOVE );
			document.onmousemove = null;

			if ( typeof ( color ) == 'undefined' )
				color = "#555555";
			if ( typeof ( bgcolor ) == 'undefined' )
				bgcolor = "#FFFFFF";
				
			while ( layer.hasChildNodes( ) )
				layer.removeChild( layer.firstChild );
			
			var opacity = ( document.all ? 'filter:Alpha(Opacity=40);' : '-moz-opacity:0.4;' );
				
			layer.innerHTML = '' + 
				'<div style="width:400px;position:absolute;">' + 
					'<div class="textos" style="background:#000000;position:absolute;top:4px;left:4px;max-width:300px;border:2px solid #000000;padding:2px;' + opacity + '">' + msg + '</div>' + 
					'<div class="textos" style="background:#FFF9E9;position:absolute;top:0px;left:0px;max-width:300px;border:2px solid #CDCDCD;padding:2px;">' + msg + '</div>' + 
				'</div>'
			//if ( document.captureEvents )
				//document.captureEvents( Event.MOUSEMOVE );
			document.onmousemove = tipToMouse;
			
			showElement ( layer );
		}
	}

	function hideTip ( )	{
		//if ( document.releaseEvents )
			//document.releaseEvents( Event.MOUSEMOVE );
		document.onmousemove = null;

		//if ( document.captureEvents )
			//document.captureEvents( Event.MOUSEMOVE );
		document.onmousemove = document.oldMousemove;
		
		hideElement ( 'tipsLayer' );
	}
	
	function tipToMouse ( e ) {
		var currentX = 0;
		var currentY = 0;

		if ( !e )
			e = window.event;
		if ( e.pageX || e.pageY )	{
			currentX = e.pageX
			currentY = e.pageY
		}
		else if ( e.clientX || e.clientY )	{
			currentX = e.clientX + document.body.scrollLeft;
			currentY = e.clientY + document.body.scrollTop;
		}

		setElementPosition( 'tipsLayer', currentX + 15 , currentY - 30 );
		return true;
	}
	function hideElement ( something )	{
		something = toObject ( something );
		if ( something )	{
			something.style.visibility = 'hidden';
			something.style.display = 'none';
		}
	}
	
	function showElement ( something )	{
		something = toObject ( something );
		if ( something )	{
			something.style.visibility = 'visible';
			something.style.display = 'block';
		}
	}
	function toObject ( something )	{
		if ( something.toString().toLowerCase().indexOf ( "[object" ) == -1 && something.toString().toLowerCase().indexOf ( "http://" ) == -1  )
			something = document.getElementById ( something );
		return something;
	}
	function setElementPosition( something, posx, posy )	{
		something = toObject( something );
		something.style.position = 'absolute';
		something.style.left = (posx - 150) + 'px';
		something.style.top = posy + 'px';
		something.style.zIndex = '500';
	}	
	/* END ToolTips Script */
	
	function getParameterValue( name ){  
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
		var regexS = "[\\?&]"+name+"=([^&#]*)";  
		var regex = new RegExp( regexS );  
		var results = regex.exec( window.location.href );  
		if( results == null )    
		return "";  else    
		return results[1];
	}