//********************************************
//
//	Copyright Mobifriends S.L. 2007
//	
//	programador: Javier Velasco Gonzalez	
//
//********************************************


//********************************************
// devuelve la version de explorer o 0.
//--------------------------------------------
function isExplorer() {
	if (navigator.appName=="Microsoft Internet Explorer") {
		var iversion = navigator.appVersion.indexOf("MSIE ");
		if (iversion>0) {
			iversion+=5;
			var eversion = navigator.appVersion.indexOf(";",iversion);
			var version = navigator.appVersion.substring(iversion,eversion);
			return parseInt(version);
		}
	} else return 0;
}

//********************************************
// devuelve la version de firefox o 0.
//--------------------------------------------
function isFirefox() {
	if (navigator.appName.indexOf("Netscape")!=-1 && parseInt(navigator.appVersion)>=5) {
		var iversion = navigator.userAgent.indexOf("Firefox/");
		if (iversion>0) {
			iversion+=8;
			var eversion = navigator.userAgent.indexOf(" ",iversion);
			if (eversion<navigator.userAgent.length) eversion = navigator.userAgent.length;
			var version = navigator.userAgent.substring(iversion,iversion + 1000);
			return parseInt(version);
		} else return 0;
	} 
	else return 0;
}


function getWindowWidth() {
  var width = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    if( document.body && document.body.clientWidth) width = document.body.clientWidth;
    else width = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth) {
    //IE 6+ in 'standards compliant mode'
    width = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth) {
    //IE 4 compatible
    width = document.body.clientWidth;
  }
  return width;
}

function getWindowHeight() {
  var height = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    if( document.body && document.body.clientHeighth) height = document.body.clientHeight;
    else height = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    height = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    height = document.body.clientHeight;
  }
  return height;
}


function getDocumentHeight() {
	var height = document.height;
	//if (!height) height = document.docubody.clientHeight;
	if (!height) height = document.documentElement.scrollHeight;

	if (height<getWindowHeight()) height = getWindowHeight();

	return height;
}


function getDocumentWidth() {
	var width = document.width;
//	if (!width) width = document.body.clientWidth;
	if (!width) width = document.documentElement.scrollWidth;
	if (width<getWindowWidth()) width = getWindowWidth();
	return width;
}

function getHScrollPos() {
	var vExplorer = isExplorer();
	var pos;
	if (vExplorer) {
		pos = document.documentElement.scrollLeft;
		if (!pos) pos = document.body.scrollLeft;
	} else {
		pos=window.pageXOffset;		
	}
	return pos;	
}

function getVScrollPos() {
	var vExplorer = isExplorer();
	var pos;
	if (vExplorer) {
		pos = document.documentElement.scrollTop;
		if (!pos) pos = document.body.scrollTop;
	} else {
		pos=window.pageYOffset;		
	}
	return pos;	
}

function getVScrollAdjustments() {
	var screenHeight = getWindowHeight();
	var vScrollPos =  getVScrollPos();
	return screenHeight +"," +vScrollPos;
}


//********************************************
// envia el formulario con el id = formid.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//
// @return: 
//
//********************************************
function submitFormById(formid) {
	f = document.getElementById(formid)
	f.submit();
}

//********************************************
// devuelve el valor de un campo.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//	devuelve el valor de un campo en funcion de el id.
//
//********************************************
function getValue(id) {
	f = document.getElementById(id);
	return f.value;
}

//********************************************
// establece el valor de un campo.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//
//********************************************
function setValue(id,value) {
	f = document.getElementById(id);
	if (f==null) return;
	switch (f.tagName.toLowerCase()) {
		case "select":
			f.value = value;
		break;
		case "input":
			f.value = value;
			if (f.type=="checkbox") {
				if (value==0) f.checked = null;
				else f.checked= true;
			}
		break;
		case "div":
			otype = document.getElementById(id+"__type");
			olenght = document.getElementById(id+"__length");
			if (otype==null) return;
			switch (otype.value) {
				case "mcheckbox":
					for (i=0;i<olenght.value;i++) {
						o = document.getElementById(id+String(i));
						if (o.value==value) {
							o.checked = true;
							return;
						}
					}
				break;				
			}
		break;
	}
}


//********************************************
// limpia los checkboxes 
//--------------------------------------------
//
// @params:
//	id: id del multiple checkbox.
//
// @return: 
//
//********************************************
function clearMCheckbox(id) {
	f = document.getElementById(id);
	if (f==null) return;
	otype = document.getElementById(id+"__type");
	olenght = document.getElementById(id+"__length");
	if (otype==null || otype.value!="mcheckbox") return;
	for (i=0;i<olenght.value;i++) {
		o = document.getElementById(id+String(i));
		o.checked=null;
	}
}

//********************************************
// borra todas las referencias dentro de un objeto
// de forma recursiva.
// Se usa para prevenir el memory leak de explorer,
// tiene que ser llamada antes de un setInnerHTML
// y antes de un removeChild.
//--------------------------------------------
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
        	try{
            	n = a[i].name;
            }catch(e){
            	return;
            }
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
//********************************************
// establece el html dentro de una etiqueta.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//
//********************************************
function setInnerHTML(id,text) {
	f = document.getElementById(id);
	if (f==null) return;//alert("No encuentra" + id);
	else {
		if (isExplorer()) purge(f);
		f.innerHTML = text;
	}
}


function urldecode( str ) {
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    ret = decodeURIComponent(ret);
    return ret;
}

function striptags(str) {
	var flip = false;
	var result="";
	for (c in str) {
		if (str[c]=='<') flip=true;
		else if (str[c]=='>') flip=false;
		else if (!flip) result+=str[c];
	}
	return result;
}


function setInnerEHTML(id,text) {
	f = document.getElementById(id);
	if (f==null) return; //alert("No encuentra" + id);
	else {
		purge(f);
		f.innerHTML = urldecode(text);
	}
}


//Rellena un campo select con valores numericos.
function fillNumbersCombo(id,nini,nfin,value,rellenarconceros) {
	options = "";
	snfin = nfin.toString();
	snini = nini.toString();
	maxlen = snfin.length;
	if (snini.length>maxlen) maxlen = snini.length ;
	/*
	for (i=nini;;) {
		stri = i.toString();
		if (rellenarconceros) {
			len = stri.length;
			for (j=0;j<maxlen-len;j++) stri = "0"+stri;
		}
		if (value!=i) options += "<option value='" + i.toString()+"'>" + stri + "</option>";
		else options += "<option selected='true' value='" + i.toString()+"'>" + stri + "</option>";
		//test del loop.		
		if (nini<nfin) {
			if (i>=nfin) break;
			i++
		} else {
			if (i<=nfin) break;
			i--;
		}
	}*/
	setInnerHTML(id,options);
}

//********************************************
// devuelve el valor de un elemento del tipo INPUT.
//--------------------------------------------
//
// @params:
//	fieldid: id del elemento INPUT.
//
// @return: 
//	devuelve una cadena con el valor del INPUT
//
//********************************************
function getInputValueById(fieldid) {
	f = document.getElementById(fieldid)
	return f.value;
}

//********************************************
// cambia el elemento seleccionado en un SELECT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	comboname: nombre del campo SELECT.
//	value: attributo value del OPTION a seleccionar.
//
// @return: 
//	devuelve una cadena con el valor del INPUT
//
//********************************************
function setComboByValue(formid,comboname,value) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[comboname];
	} else {
		element = f.all[comboname];
	}
	var attrs="";
	for (i=0;i<element.length;i++) {
		var option = element[i];
		if (option.tagName=="OPTION" && 
			option.value==value) {
			element.selectedIndex=i;
		} 
	}
}

//********************************************
// cambia el elemento seleccionado en un SELECT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	comboname: nombre del campo SELECT.
//	text: texto de la opcion a seleccionar.
//
// @return: 
//
//********************************************
function setComboByText(formid,comboname,text) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[comboname];
	} else {
		element = f.all[comboname];
	}
	var attrs="";
	for (i=0;i<element.length;i++) {
		var option = element[i];
		if (option.tagName=="OPTION" && 
			option.innerText==text) {
			element.selectedIndex=i;
		} 
	}
}

//********************************************
// establece el valor de un campo INPUT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	fieldname: nombre del campo INPUT.
//	value: valor para el campo INPUT.
//
// @return: 
//
//********************************************
function setInput(formid,fieldname,value) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[fieldname];
	} else {
		element = f.all[fieldname];
	}
	element.value = value;
}

//********************************************
// devuelve el estilo de un elemento.
//--------------------------------------------
//
// @params:
//	id: attributo id del elemento.
//
// @return: 
//
//********************************************
function getStyleById(id) {
	element = document.getElementById(id)
	return element.style;
}


//Funciones de validacion

//********************************************
// valida que sea una direccion de correo valida.
//--------------------------------------------
//
// @params:
//	email: cadena de texto que contiene el email.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateEmail(email) {
	var parts = email.split('@');
	if (parts.length!=2) return false;
	var user = parts[0];
	var server = parts[1];
	parts = server.split('.');
	if (parts.length<1) return false;
	else return true;
}

//********************************************
// valida que sea un numero.
//--------------------------------------------
//
// @params:
//	number: cadena de texto que contiene el numero.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateIsNumber(number) {
	for (i=0;i<number.length;i++) {
		var ch = number.charAt(i);
		if (ch!='0' && ch!='1' && ch!='2' && ch!='3' && ch!='4' && ch!='5' && ch!='6' && ch!='7' && ch!='8' && ch!='9')
		return false;
	}
	return true;
}

//********************************************
// valida que sea un numero de telefono valido.
//--------------------------------------------
//
// @params:
//	number: cadena de texto que contiene el numero.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateIsPhoneNumber(number) {
	for (i=0;i<number.length;i++) {
		var ch = number.charAt(i);
		if (ch!='0' && ch!='1' && ch!='2' && ch!='3' && ch!='4' && ch!='5' && ch!='6' && ch!='7' && ch!='8' && ch!='9')
		return false;
	}
	return true;
}


var WINDOW_TYPE_MODAL 	= 1;
var WINDOW_HCENTERED 	= 2;
var WINDOW_VCENTERED 	= 4;

var __windows = new Array();
var __zIndex = 1000;

function CreateIFrame(id,x,y,width,height,color,opac) {
        var windowdiv = document.createElement('iframe');
        windowdiv.setAttribute('id',id);
        windowdiv.setAttribute('class',"windowiframe");
        windowdiv.src='javascript:false;';
        zi = __zIndex++;
        var div = document.getElementsByTagName("body")[0];
        if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
        windowdiv.style.position="absolute";
        windowdiv.style.zIndex=zi;
        windowdiv.style.top=y;
        windowdiv.style.left=x;
        if (width!=null)  windowdiv.style.width=width;
        if (height!=null) windowdiv.style.height=height;
        if (color!=null) windowdiv.style.background = color;
        div.appendChild(windowdiv);
        __windows.push(windowdiv);
}


var allSelects = new Array(); //fix Explorer 6, array con los selects.
var activeWindows = 0; // for fix window mode on flash objects in IE
//********************************************
// Crea una div dinamicamente
//--------------------------------------------
//
// @params:
//	id: atributo id de la div.
//	x: posicion x dentro de la ventana, debe ser expresada como cadena indicando la unidad %,px etc.
//	y: posicion y dentro de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	width: ancho de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	height: alto de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	html: contenido xhtml de la div.
//	color: color de fondo si lo tuviera sino el atributo es omitido (transparente).
//	opac: opacidad de la capa indicado en %.
//
// @return: 
//
//********************************************
function CreateWindow(id,x,y,width,height,html,color,opac) {
	
	var windowdiv = document.createElement('div');
	var vExplorer = isExplorer();
	
	windowdiv.setAttribute('id',id);
	windowdiv.setAttribute('class',"window");
	__zIndex+=500;
	zi = __zIndex;
	var div = document.getElementsByTagName("body")[0];
	if (isFirefox()) {
	    if (opac!=null) {
	    	fopac = opac/100;
	    	windowdiv.style.MozOpacity=fopac;
	    }
	} 
	if (vExplorer>6) {
		if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
		windowdiv.style.position="absolute";
	} else if (vExplorer<=6 && vExplorer>3) {
		if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
		windowdiv.style.position="absolute";
	} else {
		windowdiv.style.position="fixed";
	}
	//a�adidos para cambiar la opacity de Opera y Safari
	//como no hay funcion para detectar estos navegadores y no afecta a los otros lo he puesto directamente aqui.
	if (opac!=null) {
	  	fopac = opac/100;
	   	windowdiv.style.opacity=fopac;
	}
	
	windowdiv.innerHTML = html;
	windowdiv.style.display="block";
	windowdiv.style.top=y;
	windowdiv.style.left=x;

	if (vExplorer>=8) {
		div.style.zIndex=10;
		windowdiv.style.zIndex=zi;
	} else {
		windowdiv.style.zIndex=zi;
	}
	if (width!=null)  windowdiv.style.width=width;
	if (height!=null) windowdiv.style.height=height;
	if (color!=null) windowdiv.style.background = color;
	div.appendChild(windowdiv);
}

function updateFlashHeaderWindowMode(wmode){
	var vExplorer = isExplorer();
	if(vExplorer === 0) return;
	var flashObj = document.getElementById('FlashHead');
	if(flashObj === null) return;

	var container = document.getElementById('header_wrapper');
	
	if(container === null){
		// Create the div and append to header div
		container = document.createElement('div');
		container.id = 'header_wrapper';
		container.style.position = 'relative';
		container.style.margin = '0';
		container.style.padding = '0';
		container.style.backgroundColor = '#ffffff';
		
		var menu = document.getElementById('cabmenu');
		if(menu !== null){
			document.getElementById('cabecera').removeChild(menu);
		}
		document.getElementById('cabecera').appendChild(container);
		document.getElementById('cabecera').appendChild(menu);
	}
	
	// Remove the old flash
	var parentNode = flashObj.parentNode;
	purge(flashObj);
	parentNode.removeChild(flashObj);
	
	for(var i=0;i<flashObj.childNodes.length;i++){
		flashObj[i] = null;
	}
	
	flashObj = null;
	
	// Load wrapper with new flash
	AC_FL_RunContent2('header_wrapper','codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,19,0',
               'width','780px',
               'height','128px',
               'src','flash/head',
               'quality','high',
               'bgcolor','#ffffff',
               'name','head',
               'allowscriptaccess','sameDomain',
               'pluginspage','http://www.macromedia.com/go/getflashplayer',
               'scale','noborder',
               'wmode', wmode,
               'flashvars', '',
               'id', 'FlashHead',   
               'movie','flash/head' );
}

function CreateIEWindow(id,x,y,width,height,html,color,opac) {
	var windowdiv = document.createElement('div');
	var vExplorer = isExplorer();
	windowdiv.setAttribute('id',id + "_parent");
	//windowdiv.setAttribute('class',"window");
	
	var div = document.getElementsByTagName("body")[0];
	if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
	windowdiv.style.position="absolute";
	//a�adidos para cambiar la opacity de Opera y Safari
	//como no hay funcion para detectar estos navegadores y no afecta a los otros lo he puesto directamente aqui.
	if (opac!=null) {
	  	fopac = opac/100;
	   	windowdiv.style.opacity=fopac;
	}
	divzi = __zIndex++;
	zi = __zIndex++;
	html = "<iframe style='position:absolute; "+
			" src='javascript:false;'" + 
			" top:0px;" + 
			" left:0px;" + 
			" width: 1px;" + 
			" height: 1px;" +
			" z-index: " + zi + ";'" + 
			" id='" + id + "_iframe' >'</iframe>";
	zi = __zIndex++;
	html = html + "<div style='position:absolute; top:0px; left:0px; " + 
			"z-index:" + zi +";' id='" + id + "' ></div>";	
	windowdiv.innerHTML = html;
	windowdiv.style.display="block";
	windowdiv.style.zIndex=divzi;
	windowdiv.style.top=y;
	windowdiv.style.left=x;
	if (width!=null)  windowdiv.style.width=width;
	if (height!=null) windowdiv.style.height=height;
	if (color!=null) windowdiv.style.background = color;
	div.appendChild(windowdiv);
	__windows.push(windowdiv);
	iframe = document.getElementById(id+"_iframe");
	newdiv = document.getElementById(id);
	iframe.style.width = newdiv.clientWidth;
	iframe.style.height = newdiv.clientHeight;
}


var __window_selected=null;


// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xStartPos = null; // Horizontal position of the mouse on the screen
yStartPos = null; // Vertical position of the mouse on the screen

function captureMousePosition(e) {
	var vExplorer = isExplorer();
	if (!e) e = window.event;
	if (!e.pageX) {
    	xMousePos = e.clientX;
    	yMousePos = e.clientY;
    	
	} else {
    	xMousePos = e.pageX;
    	yMousePos = e.pageY;
	}
	window.status="x:" + xMousePos + " y:" + yMousePos;
	//setInnerHTML('debug',xMousePos + "," + yMousePos)
}

function MoveWindow(e) {
	captureMousePosition(e);	
	if (!xStartPos) {
		xStartPos = xMousePos;
		yStartPos = yMousePos;
	}
    if (__window_selected!=null) {
    	x = parseInt(__window_selected.style.left) + xMousePos - xStartPos;
    	y = parseInt(__window_selected.style.top) + yMousePos - yStartPos;
   		__window_selected.style.left = x + "px";
		__window_selected.style.top = y + "px";
    }
	xStartPos = xMousePos;
	yStartPos = yMousePos;
}


function StartMoveWindow(id) {
	var vExplorer = isExplorer();
	if (vExplorer==6) id=id+"_parent";
	
	//RaiseWindow(id);
	xStartPos = null;
	__window_selected = document.getElementById(id);
	if (document.layers) { // Netscape
	    document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	} else if (document.all) { // Internet Explorer
	    document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	} else if (document.getElementById) { // Netcsape 6
    	document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	}
}

var ic=0;
function testScroll(e) {
	setInnerHTML('debug',ic + ":=" + getHScrollPos() + "," + getVScrollPos() + "  " + getDocumentWidth() + "x" + getDocumentHeight());
	ic++;
}

function StopMoveWindow(id) {
    document.onmousemove = null;
    document.onmouseup = null;
	__window_selected = null;
}



function CreateURLWindow(id,x,y,url) {
	activeWindow=1;
	updateFlashHeaderWindowMode('transparent');

	if(isExplorer()>0){
		y += getVScrollPos();
	}
	
	var wwidth = getDocumentWidth();
	var wheight = getDocumentHeight();
	
	var vExplorer = isExplorer();
	var cx = 0;
	var cy = 0;
	// This window will never be destroyed so decrement activeWindows
	CreateWindow(id + "bg","0px","0px",wwidth + "px",wheight + "px","","#000000","30");
	//if (vExplorer==6) CreateIFrame(id + "bg","0px","0px",wwidth + "px",wheight + "px","#000000","30");
	//else CreateWindow(id + "bg","0px","0px",wwidth + "px",wheight + "px","","#000000","30");
	if (vExplorer==6) {
		//CreateIEWindow(id,x + 'px',y + 'px',null,null,"",null,null);
		CreateWindow(id,x + 'px',y + 'px',null,null,"",null,null);
		//Vamos a ocultar todos los select visibles y ponerlos en un array.
		allSelects[id] = new Array();
		selects = document.getElementsByTagName('select');
		for (i=0;i<selects.length;i++) {
			if (selects[i].style.visibility!='hidden') {
				allSelects[id].push(selects[i]);
				selects[i].style.visibility='hidden';
			}
		}
	}
	else {
		CreateWindow(id,x + 'px',y + 'px',null,null,"",null,null);
	}
	ajax_call(id,url,null);
}


//********************************************
// pone una ventana en primer plano.
//--------------------------------------------
//
// @params:
//	id: id del elemento.
//
// @return: 
//
//********************************************
function RaiseWindow(id) {
	var windowdiv = document.getElementById(id);
	zi = __zIndex++;
	windowdiv.style.zIndex=zi;
}



//********************************************
// destruye una ventana creada con CreateWindow.
//--------------------------------------------
//
// @params:
//	id: id de la div contenedora de la ventana.
//
// @return: 
//
//********************************************
function DestroyWindow(id) {
	var abody = document.getElementsByTagName("body");
	var vExplorer = isExplorer();
	
	var div = null;
	if (abody.length>=1) div = abody[0];
	if (div!=null) {
		var windowdiv;
		
		windowdiv = document.getElementById(id+"_parent");
		
		if (windowdiv!=null) {
			purge(windowdiv);
			div.removeChild(windowdiv);
		}
		
		windowdiv = document.getElementById(id);
		if (windowdiv!=null) {
			purge(windowdiv);
			div.removeChild(windowdiv);
		}
		
		var windowbg = document.getElementById(id + "bg");
		if (windowbg!=null) {
			if(activeWindows==1){
				updateFlashHeaderWindowMode('window');
				activeWindows=0;
			}
			purge(windowbg);
			div.removeChild(windowbg);
		}
		
		var windowiframe = document.getElementById(id + "_parent");
		if (windowiframe!=null) {
			purge(windowiframe);
			div.removeChild(windowiframe);
		}
		
	}
	//Manda el foco al ultimo foco conocido.
	setFocusOn(lastFocus);
	//Vuelve a mostrar los select que ocultamos en CreateWindow.
	if (vExplorer<=6 && vExplorer>3) {
		if (allSelects[id]) {
			len = allSelects[id].length;
			for (i=0;i<len;i++) {
				select = allSelects[id].pop();
				select.style.visibility='visible';
			}
			allSelects[id] = null;
		}
	}
}


//********************************************
// establece el estado de visibilidad de un elemento
// usando el id.
//--------------------------------------------
//
// @params:
//	id: id del elemento.
//	visible: true | false.
//
// @return: 
//
//********************************************
function Show(id,visible) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (visible) {
		obj.style.visibility = "visible";
	} else {
		obj.style.visibility = "hidden";
	}
	//Les pone la misma visibilidad que la capa que los contiene.
	vExplorer = isExplorer();
	if (vExplorer<=6 && vExplorer>3) {
		selects = obj.getElementsByTagName('select');
		for (i=0;i<selects.length;i++) selects[i].style.visibility =obj.style.visibility;
	}
}

function Resize(id,w,h) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (w>0) obj.style.width=w+ "px";
	if (h>0) obj.style.height=h+ "px";
}

function ShowAndResize(id,visible,w,h) {
	Show(id,visible);
	Resize(id,w,h);
}

function SwapShow(id) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (obj.style.visibility=="visible") {
		Show(id,false);
	} else {
		Show(id,true);
	}
}

//Pequeño workaround para devolver el foco despues de un popup 
//al ultimo objeto sobre el que hicimos un setFocus.
var lastFocus;

function setFocusOn(id) {
	obj = document.getElementById(id);
	if (obj==null) return;
	obj.focus();
	lastFocus = id;
}





//********************************************
// limpia espacios al principio y al final
// de una cadena.
//--------------------------------------------
//
// @params:
//	str: la cadena a limpiar.
//
// @return: 
//	la cadena modificada.
//
//********************************************
function cleanSpaces(str) {
	//pendiente
}


function setFlashVar(flashid,varname,varvalue) {
	fl = document.getElementById("mz" + flashid);
	if (!fl) fl = document.getElementById(flashid);
 	if (fl!=null) fl.SetVariable(varname,varvalue);
}



var chatWindowStatus = 0;
function setChatWindowStatus(status) {
	chatWindowStatus = status;
}

var chatWindow = null;

function openChat(para,roomid,solicitud) {
	if (chatWindowStatus==0) {
		var chatparams = '';
		if(para != '' ){
			chatparams = '?para=' + para + '&roomid=' + roomid + '&solicitud=' + solicitud; 
		}
		var url = "wmiscomchat.php" + chatparams;
		//var url = "testresize.php" + chatparams;
		chatWindow = window.open(url, 'chat', 'height=562,width=552,scrollbars=0,resizable=1');
		if(!chatWindow.opener) chatWindow.opener=self;
		if(window.focus){
			chatWindow.focus();
		}
	} else {
		ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
        //if (isFirefox()) {
        //    fh = document.getElementById('mzFlashHead');
        //} else fh = document.getElementById('FlashHead');
		//fh.openPrivateChat(para,roomid,solicitud);
		//url = "php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid;
		//alert(url);
		//ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
	}
}
/*
function openChat(para,roomid,solicitud) {
	if (chatWindowStatus==0) {
		var chatparams = '';
		if(para != '' ){
			chatparams = '?para=' + para + '&roomid=' + roomid + '&solicitud=' + solicitud; 
		}
		var url = "wmiscomchat.php" + chatparams;
		if (isExplorer()) {
			chatWindow = window.open(url, 'chat', 'left='+((window.screenX||window.screenLeft)+10)+',top='+((window.screenY||window.screenTop)+10)+',height=769,width=765,scrollbars=1');
		} else {
			chatWindow = window.open(url, 'chat', 'left='+((window.screenX||window.screenLeft)+10)+',top='+((window.screenY||window.screenTop)+10)+',height=769,width=749,scrollbars=1');
		}
		if(!chatWindow.opener) chatWindow.opener=self;
		if(window.focus){
			chatWindow.focus();
		}
	} else {
		ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
        //if (isFirefox()) {
        //    fh = document.getElementById('mzFlashHead');
        //} else fh = document.getElementById('FlashHead');
		//fh.openPrivateChat(para,roomid,solicitud);
		//url = "php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid;
		//alert(url);
		//ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
	}
}
*/

function openChatFromFlash(para,roomid,solicitud) {
	window.opener.ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
}


function reloadChat() {
	window.location.reload();
}

function showPopUp(windowname,url) {
	CreateURLWindow(windowname,
					0,
					0,
					url);
}

function setWindowToFullScreen(windowname) {
	wn = document.getElementById(windowname);
	wn.style.position='absolute';
	wn.style.left='0px';
	wn.style.top='0px';
	wn.style.width = getDocumentWidth() + "px";
	wn.style.height = getDocumentHeight() + "px";
	wn.style.width="100%";
	wn.style.height="100%";
}

function showInfoPopUp(title,msg) {
	CreateURLWindow("infowindow",
					getWindowWidth()/2-100,
					getWindowHeight()/2-100,
					"php/mostrarpopupinfo.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg));
}

function showConfirmationPopUp(title,msg,yeslink,nolink) {
	CreateURLWindow("confirmationwindow",
					getWindowWidth()/2-100,
					getWindowHeight()/2-100,
					"php/mostrarpopupconfirmation.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg) + "&ylink="+yeslink+"&nlink=" + nolink);
}

function showWarningPopUp(title,msg,onclose){
	CreateURLWindow("warningwindow",
					getWindowWidth()/2-175,
					getWindowHeight()/2-150,
					"php/mostrarpopupaviso.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg) + "&onclose=" + onclose);
}

//********************************************
// Funcion para en los submenus verticales.
// Resalta el fondo del submenu donde este el cursor.
//--------------------------------------------
//
// @params:
//	H: elemento donde se ha situado el cursor.
//
//********************************************
function fhover(H){
if(H.className.indexOf("HoverBGColor")>=0)
H.className=H.className.replace("HoverBGColor ","");
else H.className="HoverBGColor "+H.className;
}

//********************************************
// Funciones de la primera version del portal.
// Funciones utilizadas para mostrar y ocultar textos con los links de "comprimir todo" y "expandir todo".
function activa(tipo)
{
	if (activado!="") document.getElementById(activado).style.display="none";
	if (activado!=tipo)
	{
		document.getElementById(tipo).style.display="";
		activado=tipo;
	}
	else activado="";
}

function activa_sub(tipo,enlace)
{
	if (document.getElementById(tipo).style.display=='none')
	{ 
		document.getElementById(tipo).style.display="";
		// muestra en la subseccion el link comprimir todo
		
		var splittedId = tipo.split("_");
		subid = splittedId[0] + "_" + splittedId[1] + "_" + splittedId[2];
		
		document.getElementById(subid).style.display="";
	}
	else 
	{
		document.getElementById(tipo).style.display="none";
		
		var splittedId = tipo.split("_");
		subid = splittedId[0] + "_" + splittedId[1] + "_" + splittedId[2];
		
		document.getElementById(subid).style.display="";
		subspans=document.getElementsByName(subid);
		subdisplay="none";
		for(i=0;i<subspans.length;i++)
		{
			if (subspans[i].style.display=="") subdisplay="";
		}
		document.getElementById(subid).style.display=subdisplay;
	}
	if (document.getElementById(enlace).className=='expandirbw') document.getElementById(enlace).className="comprimirbw";
		else document.getElementById(enlace).className="expandirbw";
}

function comprimir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="none";
		if (valor2==enlace) v_doc[i].className="expandirbw";
	}
}

function expandir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="";
		if (valor2==enlace) v_doc[i].className="comprimirbw";
	}
}

function ocultar(tipo)
{
	document.getElementById(tipo).style.display="none";
	activado="";
}

//Comprueba el formato del correo
function verifica_mail(t_mail)
{
	if ((t_mail.lastIndexOf(" ")!=-1) || (t_mail.lastIndexOf("@")==-1) || (t_mail.lastIndexOf(".")<=(t_mail.lastIndexOf("@")+1)) || (t_mail.lastIndexOf(".")==(t_mail.length-1))) return false;
		else return true;
}

var javascriptNewMessage = "";
function OnNewMessage() {
	eval(javascriptNewMessage);
}

var javascriptNewMobi = "";
function OnNewMobi() {
	eval(javascriptNewMobi);
}

function show_div(tipo)
{	
	if(document.getElementById(tipo)) document.getElementById(tipo).style.display="block";
}

function hide_div(tipo)
{
	if(document.getElementById(tipo)) document.getElementById(tipo).style.display="none";
}

function ifsetdisplay(divtipo,divboton)
{
	if (document.getElementById(divtipo).style.display=='none')
	{ 
		document.getElementById(divboton).style.display="block";
	}
	else 
	{	
		document.getElementById(divboton).style.display="none";
	}
}


function compareOptionText(a,b) {

	// textual comparison
	return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;

}

function sortOptions(list) {

	var items = list.options.length;

	// create array and make copies of options in list
	var tmpArray = new Array(items);

	for ( i=0; i<items; i++ )
		tmpArray[i] = new Option(list.options[i].text,list.options[i].value);

	// sort options using given function
	tmpArray.sort(compareOptionText);
	
	// make copies of sorted options back to list
	for ( i=0; i<items; i++ )
		list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);

}


function onCloseSession() {
	document.location='login.php';	
}

function sendVerificationEmail(email, alias, signupDate, lang){
	var response_container = document.getElementById('verification-email-sent');
	response_container.innerHTML = "<img src='images/common/popups/h-ajax-loading.gif' border='0' />";
	
	//ajax_eval_response("php/usuariodatos_form.php?cmd=verification-email&email="+email, "email=" + email + "&alias=" + alias + "&signupDate=" + signupDate + "&lang=" + lang);
	
	new Ajax.Request("php/email_verify_email_address.php",{
			method: 'get',
			parameters: {'email':email, 'alias':alias, 'signupDate':signupDate, 'lang':lang},
			onSuccess: function(transport){
				response_container.innerHTML = transport.responseText; 
			}
		});
}

function externalLinks() {
	if (!document.getElementsByTagName) {
		return;
	}
	var anchors = document.getElementsByTagName("a");
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("rel")) {
			var rel = anchor.getAttribute("rel");
			var external = false;
			if (rel.indexOf(" ") > 0) {
				while (rel.indexOf(" ") > 0 && external == false) {
					if (rel.substr(0, rel.indexOf(" ")) == "external") {
						external = true;
					}
					rel = rel.substr(rel.indexOf(" ") + 1, rel.length - rel.indexOf(" ") + 1);
				}
			}
			if (rel == "external") {
				external = true;
			}
			if (anchor.getAttribute("href") && external == true) {
				anchor.target = "_blank";
			}
		}
	}
	return;
}
