var ven, lightboxPopUp
function Browser(){		
  this.dom = document.getElementById?1:0;
  this.ie4 = (document.all && !this.dom)?1:0;
  this.ns4 = (document.layers && !this.dom)?1:0;
  this.ns6 = (this.dom && !document.all)?1:0;
  this.ie5 = (this.dom && document.all)?1:0;
  this.ok = this.dom || this.ie4 || this.ie5;
  this.platform = navigator.platform;
}
var browser = new Browser();

function popup(pag, nombre, parametros){
	ven = window.open(pag,nombre,parametros)
	ven.focus();
	if(browser.ie5)event.returnValue=false;
}

function ventana(url,targe,ancho,alto) {

	switch(targe){			
		case "lightbox":
		case "borrar":					
			ventanaLightbox(url,"lightboxPopUp",ancho,alto)
			break;
		default:
			posh=(Math.round(screen.height-(alto))/2)//centra la ventana a lo alto
			posv=(Math.round(screen.width-(ancho))/2)//centra a lo ancho				

			if (ven && !ven.closed){ven.close();}
			ven = window.open(url,targe,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,width=" + ancho + "px,height=" + alto + "px,left=" + posv + ",top=" + posh + ",resizable=no");	

			ven.focus()
	}
	if(browser.ie5)event.returnValue=false;
}

function ventanaScroll(url,targe,ancho,alto) {		
	posh=(Math.round(screen.height-(alto))/2)//centra la ventana a lo alto
	posv=(Math.round(screen.width-(ancho))/2)//centra a lo ancho				

	if (ven && !ven.closed){ven.close();}
	ven = window.open(url,targe,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,width=" + ancho + "px,height=" + alto + "px,left=" + posv + ",top=" + posh + ",resizable=no");

	ven.focus()
	if(browser.ie5)event.returnValue=false;
}

function ventanaLightbox(url,targe,ancho,alto) {		
	posh=(Math.round(screen.height-(alto))/2)//centra la ventana a lo alto
	posv=(Math.round(screen.width-(ancho))/2)//centra a lo ancho				
	
	if (lightboxPopUp && !lightboxPopUp.closed){		
		lightboxPopUp.close();
	}
	lightboxPopUp = window.open(url,targe,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,width=" + ancho + "px,height=" + alto + "px,left=" + posv + ",top=" + posh + ",resizable=no");	

	lightboxPopUp.focus()
	if(browser.ie5)event.returnValue=false;
}

function LTrim(str){
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
	  var j=0, i = s.length;
	  while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
		 j++;
	  s = s.substring(j, i);
   }
   return s;
}


function RTrim(str){
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
	  var i = s.length - 1;
	  while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
		 i--;
	  s = s.substring(0, i+1);
   }

   return s;
}

function Trim(str){
   return RTrim(LTrim(str));
}

function isArray(obj){
	return(typeof(obj.length)=="undefined")?false:true;
}

function txtBlanco(elemento, msg){
   valor = Trim(elemento.value);
   if(valor==""){
	  /*if(elemento.type!="hidden")
		elemento.focus();*/
	  alert(msg);
	  return false;
   }
   elemento = valor;
   return true;
}

function validacbo (elemento, msg){
	valor = elemento.selectedIndex;
	if(valor==-1){
		alert(msg);
	elemento.focus();
	return false;
	}
   return true;
}

function validacboBlanco (elemento, msg){
	valor = elemento.options[elemento.selectedIndex].value;
	if(valor==""){
		alert(msg);
	elemento.focus();
	return false;
	}
   return true;
}

function replaceStr(str, strBuscar, strSustituir){
	var regExpresion = new RegExp(strBuscar, 'gi');
	return str.replace(regExpresion,strSustituir)
}

function validaMoneda(elemento, msg){
	elemento.value = replaceStr(elemento.value, ",", ".")
	valor = Trim(elemento.value);
	if(valor != "" && isNaN(valor)){
		alert(msg);
		elemento.focus();
		return false;
	}
   return true;
}

function validaNumero(elemento, msg){
	valor = Trim(elemento.value);
	if(valor != "" && isNaN(valor)){
		alert(msg);
	elemento.focus();
	return false;
	}
	return true;
}

function posimgY(obj){	
	if(browser.ie4 || browser.ie5 || browser.dom) return wipeGetOffset(obj,"Top");
	//if(browser.dom) return obj.y;
	if(browser.ns4) return obj.y;
}

function posimgX(obj){
	if(browser.ie4 || browser.ie5 || browser.dom) return wipeGetOffset(obj,"Left");
	//if(browser.dom) return obj.x;
  	if(browser.ns4) return obj.x;
}

function wipeGetOffset(obj, coord) {
	var val = obj["offset"+coord] ;
	while ((obj = obj.offsetParent )!=null) {
		val += obj["offset"+coord];
		if (obj.border && obj.border != 0) val++;
	}
	return val;
}

function div(nombre, imgRef){
	if (browser.ns4){
		var tmpLayer = new Layer(127);
	}
	if (browser.dom || browser.ie4){
		var tmpLayer = browser.dom?document.getElementById(nombre):document.all(nombre);
  	}	
  	if(imgRef != ""){
		objRef = document.images[imgRef];
		this.xRef = posimgX(objRef);
		this.yRef = posimgY(objRef);
	}else{
		this.xRef = 0
		this.yRef = 0
	}
	this.containerLayer = tmpLayer;
	this.desplazaX = desplazaX;
	this.desplazaY = desplazaY;
	this.escribeDiv = escribeDiv;
	this.visible = visible;
	this.display = display;
	this.muestraContenido = contenido;
}

function contenido(){
	if (browser.ie4 || browser.dom)
		return this.containerLayer.innerHTML
}

function visible(valor){
	if (browser.ie4 || browser.dom){
		divmenu = this.containerLayer.style
		switch(valor){
			case 0:
				nuevo_estado = "hidden";
				break;
			case 1:
				nuevo_estado = "visible";
		}
	}else{
		if (browser.ns4){
			divmenu = this.containerLayer;
			switch(valor){
				case 0:
					nuevo_estado = "hide";
					break;
				case 1:
					nuevo_estado = "show";
			}
		}
	}

	divmenu.visibility = nuevo_estado
}

function display(valor){
	if (browser.ie4 || browser.dom){
		divmenu = this.containerLayer.style
		switch(valor){
			case 0:
				nuevo_estado = "none";
				break;
			case 1:
				nuevo_estado = "block";
		}
		divmenu.display = nuevo_estado
	}
}

function escribeDiv(str){
	if (browser.ie4)
		this.containerLayer.innerHTML = str;
	else
		if (browser.dom)
			this.containerLayer.innerHTML = str;
		else
			if(browser.ns4){
				this.containerLayer.document.open();
				this.containerLayer.document.write(str);
				this.containerLayer.document.close();
			}
}

function desplazaX(x){
	if (browser.dom || browser.ie4)
		this.containerLayer.style.left = x;
	if(browser.ns4)
		this.containerLayer.left = x;
}

function desplazaY(y){
	if (browser.dom || browser.ie4)
		this.containerLayer.style.top = y;
	if(browser.ns4)
		this.containerLayer.top = y;
}			

function isObject(a){
	 return (typeof a == 'object' && !!a) || isFunction(a);
}

function isFunction(a) {
	return typeof a == 'function';
}

 	
function cargaCanal(){	
	var formu = document.forms["buscador"]	
	var valor = formu["cboCanales"].options[formu["cboCanales"].selectedIndex].value		
	switch(valor){
		default:
			document.location = "canal.aspx?canal=" + valor
	}
	//formu.submit()
}

function valFecha(formName){
	var formu = document.forms[formName]	
	if(formu["rdFecha1"].checked){
		formu["txtDesde"].value = ""		
		formu["txtHasta"].value = ""
		var divCalendario = new div("divCalendario", "")
		divCalendario.display(0)
	}
}

function valRegion(formName){
	var formu = document.forms[formName]	
	if(formu["rdRegion1"].checked){
		for(i=0;i<formu.length;i++){				
			switch(formu[i].type){
				case "checkbox":
					if(formu.elements[i].id.indexOf('chkRegion') != -1){
						formu.elements[i].checked = false
						formu.elements[i].disabled = true
					}
					break;
			}
		}
	}else{
		for(i=0;i<formu.length;i++){				
			switch(formu[i].type){
				case "checkbox":	
					if(formu.elements[i].id.indexOf('chkRegion') != -1){
						formu.elements[i].disabled = false
					}
					break;
			}
		}
	}
}

var xmlObj, calCargado = false

function cargaFecha(formName, txt, img){
	var formu = document.forms[formName]	
	xmlObj = new objXML("xmlObj", false)
	xmlObj.gDomXML()	
	formu["rdFecha2"].checked = true	
	formu["txtDesde"].disabled = false	
	formu["txtHasta"].disabled = false		
	if(!xmlObj.creado || browser.platform == 'MacPPC'){			
		ventana('calendario.aspx?formName=' + formName + '&txt=' + txt,'calendario',200,165)
	}else{					
		if(calCargado){
			var divCalendario = new div("divCalendario", img)
			divCalendario.desplazaX(divCalendario.xRef)
			divCalendario.desplazaY(divCalendario.yRef+10)
			divCalendario.display(1)			
		}else{
			xmlObj.cargaUrlXML("../aspx/calendarioXML.aspx?formName=" + formName + "&txt=" + txt)
			xmlObj.gestionaContenido = function(){							
				var divCalendario = new div("divCalendario", img)								
				divCalendario.escribeDiv(xmlObj.resultado)			
				divCalendario.display(1)		
				divCalendario.desplazaX(divCalendario.xRef - 160)				
				divCalendario.desplazaY(divCalendario.yRef+20)
			}
		}
	}
}

function cargaFechaForm(formName, txt, fechaCal){		
	document.forms[formName][txt].value = fechaCal
	var divCalendario = new div("divCalendario", "")
	divCalendario.display(0)
}	


function cargarFechaDada(mes, anyo){
	var formu = document.forms["frmCalendario"] 
	xmlObj = new objXML("xmlObj", false)
	xmlObj.gDomXML()
	if(xmlObj.creado && browser.platform != 'MacPPC'){			
		var mes = formu[formu["mes"].value].options[formu[formu["mes"].value].options.selectedIndex].value	
		var anyo = formu[formu["anyo"].value].options[formu[formu["anyo"].value].options.selectedIndex].value	
		var fecha = "1/" + mes + "/" + anyo		
		xmlObj.cargaUrlXML("../aspx/calendarioXML.aspx?formName=" + formu[formu["txtFormName"].value].value + "&txt=" + formu["txtForm"].value + "&fecha=" + fecha)
		xmlObj.gestionaContenido = function(){						
			var divCalendario = new div("divCalendario", "")
			divCalendario.escribeDiv(xmlObj.resultado)						
		}
	}else{		
		formu.submit()
	}
}

function cerrarCalendario(popup){
	if(popup=='1'){
		window.close()
	}else{
		var divCalendario = new div("divCalendario", "")
		divCalendario.display(0)
	}
}


function checkClick(){
	var formu = document.forms["frmResultadoBus"]
	formu["txtFiltrarBus"].value = ""
	formu.submit()
}	

function enviaLightBox(formName, idLightBox){
	var formu = document.forms[formName]
	var y =  formu["cboLightBoxUsuarioEmail"].options[formu["cboLightBoxUsuarioEmail"].selectedIndex].value
	var nombre =  formu["cboLightBoxUsuarioEmail"].options[formu["cboLightBoxUsuarioEmail"].selectedIndex].text
	if(formu["cboLightBox"].options.length > 0){
		var idLightBox = formu["cboLightBox"].options[formu["cboLightBox"].selectedIndex].value	
		if(y!="")
			ventana('../aspx/lightBox-enviar.aspx?y=' +  y + '&idLightBox=' + idLightBox + '&nombre=' + nombre,'lightBox','400','406');
	}else
		alert("Debe seleccionar el lightbox a enviar.")	
	return false;
}

function recargarReportaje(params){
	top.window.opener.location.href = "reportaje.aspx?idReportaje=" + params + "&hdActBus=1"
}

function lanzaDescarga(url){
	var posh = (Math.round(screen.height-(200))/2)//centra la ventana a lo alto
	var posv = (Math.round(screen.width-(200))/2)//centra a lo ancho
	var descarga = window.open(url, null, "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,width=200px,height=200px,left=" + posv + ",top=" + posh + ",resizable=no")
	if(descarga == null)
		alert("No se ha podido lanzar la ventana para realizar la descarga, compruebe que no tiene activado el bloqueador de popups.")
	return false;
}

function cargaPreferencias(){
	var formu = document.forms["buscador"]
	var checked = formu["usarPrefe"].checked
	var parametro = ""
	if(checked)
		parametro = "?activar=1"
	
	ventana('activarPreferencia.aspx' + parametro,'preferencias',400,406)		
	
}

function anadeEleAsocLightbox(objForm, objCbo, id, label){			
	var formu = document.forms[objForm]
	var combo
	if(isObject(formu[objCbo]))
		combo = formu[objCbo]
	else{
		for(i=0;i<formu.length;i++){				
			if(formu.elements[i].name.indexOf(objCbo) != -1){
				combo = formu[formu.elements[i].name]
				break;
			}
		}
	}	
	var existe = false	
	for(var i=0;i<combo.options.length;i++){
		if(combo.options[i].value == id){
			existe = true
			break;
		}
	}
	if(!existe){		
		combo.options[combo.options.length] = new Option(label, id);		
		combo.options.selectedIndex = combo.options.length - 1
		formu.submit()
	}
}

function validaBusqueda(){
	var formu = document.forms["buscador"]
	if(txtBlanco(formu["txtBus"], 'Debe indicar el texto de búsqueda.'))
		return true
	return false
}

function validaLogin(){
	var formu = document.forms["frmLogin"]
	if(txtBlanco(formu["txtUsuario"], 'Debe indicar el usuario.'))
		if(txtBlanco(formu["txtPwd"], 'Debe indicar la contraseña.'))
			return true
	return false
}

function validaAltaUsuario(){
	var formu = document.forms["frmAltaUsuario"]
	if(txtBlanco(formu["txtNombre"], 'El nombre es un dato obligatorio.'))
		if(txtBlanco(formu["txtPwd"], 'La contraseña es un dato obligatorio.'))
			if(txtBlanco(formu["txtEmail"], 'El Email es un dato obligatorio.'))
				if(formu["txtPwd"].value == formu["txtRepPwd"].value){
					return true
				}else{
					alert("No coinciden las contraseñas.")
				}
	return false
}

function validaPerfil(){
	var formu = document.forms["frmRegistro"]
	if(txtBlanco(formu["txtNombre"], 'El nombre del usuario administrador es un dato obligatorio.'))
		if(txtBlanco(formu["txtApellidos"], 'Los apellidos del usuario administrador son un dato obligatorio.'))
			if(txtBlanco(formu["txtEmail"], 'El email de contacto es un dato obligatorio.'))		
				if(txtBlanco(formu["txtEmpresa"], 'El nombre de la empresa es un dato obligatorio.'))					
					if(txtBlanco(formu["txtTelefono"], 'El teléfono de contacto es un dato obligatorio.'))									
						if(txtBlanco(formu["txtRsocialFac"], 'El nombre o razón social de la empresa es un dato obligatorio.'))														
							if(txtBlanco(formu["txtDireccionFac"], 'La dirección de la empresa es un dato obligatorio.'))																				
								if(validacboBlanco(formu["cboCiudadFac"], 'La ciudad de la empresa es un dato obligatorio.'))	
									if(validacboBlanco(formu["cboEstProFac"], 'La provicina o estado de la empresa es un dato obligatorio.'))	
										if(txtBlanco(formu["txtCPFac"], 'El código postal de la empresa es un dato obligatorio.'))
											return true
	return false
}


function validaLightBox(frm){
	var formu = document.forms[frm]
	if(txtBlanco(formu["nombreLightBox"], 'El nombre del lightbox es un dato obligatorio.'))
		if(txtBlanco(formu["txtNombreProyecto"], 'El nombre del proyecto es un dato obligatorio.')){			
			if(formu["txtNotas"].value.length > 200)
				alert("El texto introducido en el campo 'Notas' es excesivo")
			else
				return true
		}
	return false
}

function validaEncargo(){
	var formu = document.forms["frmEncargo"]
	if(txtBlanco(formu["txtNombre"], 'El nombre es un dato obligatorio.'))
		if(txtBlanco(formu["txtApellidos"], 'Los apellidos son un dato obligatorio.'))
			if(txtBlanco(formu["txtEmpresa"], 'El nombre de la empresa es un dato obligatorio'))
				if(txtBlanco(formu["txtTelefono"], 'El teléfono de contacto es un dato obligatorio'))
					if(txtBlanco(formu["txtEmailAdmin"], 'El email de contacto es un dato obligatorio'))
						if(formu["chkCondiciones"].checked){
							if(formu["chkEmail"].checked || formu["chkTlf"].checked){
								return true
							}else{
								alert('Es necesario indicar el medio mediante el cual nos pondremos en contacto con usted')
								return false
							}
						}else{
							alert('Es necesario aceptar los términos de las condiciones legales para continuar con el proceso de registro')
							return false
						}						
	return false
}

var arrayForm = new Array()
var arrayElemnoDis = new Array()	
var tiempoRes = 500;
var idOptMarcado = '', idOptMarcadoSub = ''

function deshabilitar(){
	var formu;				
	for(i=0;i<arrayForm.length;i++){
		formu = document.forms[arrayForm[i]]						
		if(arrayElemnoDis.length>0){
			for(j=0;j<formu.length;j++){											
				for(x=0;x<arrayElemnoDis.length;x++){													
					if(arrayElemnoDis[x][0] == arrayForm[i] && arrayElemnoDis[x][1] == formu.elements[j].id){														
						formu.elements[j].disabled = false;									
						break;
					}else{																				
						formu.elements[j].disabled = true;
					}
				}
			}
		}else{
			for(j=0;j<formu.length;j++){									
				formu.elements[j].disabled = true;					
			}
		}
	}
}

startMenu = function() {	
	if (document.getElementById) {
		arrayElemInicial = new Array('optMenu11','optMenu21','optMenu31')
		arrayElemAsociado = new Array('optMenu12','optMenu22','optMenu32')
		var arrayNodo = new Array()
		var arrayNodoAsoc = new Array()
		//var elementoSel = ""
		var optSel = ""
		idOptMarcadoSub = ""		
		for (i=0;i<arrayElemInicial.length;i++) {						
			
			nodo = document.getElementById(arrayElemInicial[i])			
			if(arrayElemAsociado[i]!='')
				arrayNodo[nodo.id] = document.getElementById(arrayElemAsociado[i])
			else
				arrayNodo[nodo.id] = ""
			arrayNodoAsoc[arrayElemAsociado[i]] = document.getElementById(arrayElemInicial[i])

			nodo.idTimeOut = null;
			nodo.onmouseover=function() {				
				clearInterval(this.idTimeOut)
				if(optSel != this.id && optSel != ""){					
					if(optSel != idOptMarcado){
						arrayNodo[optSel].className="optMenuOut";						
						arrayNodoAsoc[arrayNodo[optSel].id].className="optMenuNoSel";											
					}
				}else
					if(optSel != "")
						clearInterval(arrayNodo[optSel].idTimeOut)
				if(arrayNodo[this.id]!=""){
					arrayNodo[this.id].className="optMenuOver";																		
					optSel = this.id
					this.className="optMenuSel";																
				}															
			}				
			
			nodo.onmouseout=function() {					
				var id = ""
				if(arrayNodo[this.id] != "" && this.id != idOptMarcado){					
					id = arrayNodo[this.id].id
					this.idTimeOut = setTimeout("oculCapa('" + id + "','" + this.id + "')", tiempoRes)	
				}
			}	
			
			if(arrayNodo[this.id]!=""){
				arrayNodo[nodo.id].idTimeOut = null;
				arrayNodo[nodo.id].onmouseover=function() {							
					if(optSel != ""){				
						if(optSel != arrayNodoAsoc[this.id].id)
							arrayNodo[optSel].className="optMenuOut";	
						clearInterval(arrayNodoAsoc[arrayNodo[optSel].id].idTimeOut)											
						if(optSel == arrayNodoAsoc[arrayNodo[optSel].id].id){							
							clearInterval(arrayNodo[optSel].idTimeOut)
						}				
					}
				}
				arrayNodo[nodo.id].onmouseout=function() {	
					if(this.id != idOptMarcadoSub)
						this.idTimeOut = setTimeout("oculCapa('" + this.id + "','" + arrayNodoAsoc[this.id].id + "')", tiempoRes)											
				}
			}
			
			if(idOptMarcadoSub!=''){
				document.getElementById(idOptMarcadoSub).className="optMenuOver";	
			}
		}
	}
	deshabilitar();
}

function oculCapa(id1, id2){							
	if(id1!=""){
		obj1 = document.getElementById(id1)
		obj1.className="optMenuOut";		
	}
	obj2 = document.getElementById(id2)
	obj2.className="optMenuNoSel";		
	optSel = ""
}

function cargaLighBoxXML(pagina){	

	xmlObj = new objXML("xmlObj", false)
	var formu = document.forms["frmResultadoBus"]		 
	var hash = ''
	var idLightBox = ''
	var urlParametros = ''
	xmlObj.gDomXML()				
	
	if(pagina == -1){			
		pagina = formu["numPaginaLightbox"].value
	}else
		formu["numPaginaLightbox"].value = pagina	
		
		
	for(i=0;i<formu.length;i++){				
		if(formu.elements[i].id.indexOf('cboLightBoxUsuario') != -1){
			hash = (formu.elements[i].options.selectedIndex!=-1)?formu.elements[i].options[formu.elements[i].options.selectedIndex].value:"";
		}else		
			if(formu.elements[i].id.indexOf('cboLightBoxX') != -1){
				idLightBox = (formu.elements[i].options.selectedIndex!=-1)?formu.elements[i].options[formu.elements[i].options.selectedIndex].value:"";
			}else		
				if(formu.elements[i].id.indexOf('urlParametros') != -1){
					urlParametros = formu.elements[i].value
				}
	}	
	
	if(idLightBox!=""){	
		if(!xmlObj.creado || browser.platform == 'MacPPC'){					
			var url = document.location.href;						
			url = anadeParam(url, "despliega", "1");		
			url = anadeParam(url, "paginaLightBox", pagina);
			url = anadeParam(url, "hash", hash);
			url = anadeParam(url, "idLightBox", idLightBox);
			if(url.indexOf(urlParametros) == -1){
				url += "&" + urlParametros
			}
			document.location.href = url
		}else{					
			xmlObj.cargaUrlXML("../aspx/miniLightBoxXML.aspx?paginaLightBox=" + pagina + "&hash=" + hash + "&idLightBox=" + idLightBox)									
			xmlObj.gestionaContenido = function(){				
				var divCalendario = new div("miniLightBoxResultado", "")	
				if(isObject(xmlObj.xmlhXML))		
					divCalendario.escribeDiv(xmlObj.resultado)								
				if(isObject(lightboxPopUp) && !lightboxPopUp.closed){													
					lightboxPopUp.close()						
				}			
			}				
		}
	}
}

function anadeParam(url, parametro, valor){
	if(url.indexOf(parametro) != -1){
		url = url.substring(0, url.indexOf(parametro) + parametro.length + 1) +  valor + url.substring(url.indexOf(parametro) + parametro.length + 2)			
	}else
			if(url.indexOf("?") != -1)		
				url += "&" + parametro + "=" + valor
			else
				url += "?" + parametro + "=" + valor
	if(url.indexOf("#") != -1){					
		url = url.substring(0, url.indexOf("#")) + url.substring(url.indexOf("#") + 1, url.length)
	}
	return url
}