// Recordamos los valores por si falla la llamada poder repetirla
var doAjax_url;
var doAjax_f;
var doAjax_loading;
var doAjax_error = false;
var doAjax_intentoserror = 0;

function doAjax(url,f,loading){
// FUNCIÓN GENÉRICA: se le pasa en url la dirección del XML a cargar (incluidos parámetros) 
//                   en f el nombre de la función a ejecutar cuando el XML esté cargado
//					 y en loading la función a ejecutar mientras el XML está cargando.					 
	doAjax_url = url;
	doAjax_f = f;
	doAjax_loading = loading;

	if (document.implementation && document.implementation.createDocument)
	{			
		// Mozilla			
		Document.prototype.__defineGetter__("xml", function () 
		{
		   return (new XMLSerializer()).serializeToString(this);
		}
		);
			
		//add the loadXML() method to the Document class
		Document.prototype.loadXML = function(strXML) 
		{
			
			//create a DOMParser
			var objDOMParser = new DOMParser();
					
			//create new document from string
			var objDoc = objDOMParser.parseFromString(strXML, "text/xml");
					
			//make sure to remove all nodes from the document
			while (this.hasChildNodes())
				this.removeChild(this.lastChild);
	
			//add the nodes from the new document
			for (var i=0; i < objDoc.childNodes.length; i++) {
							
			  //import the node
			  var objImportedNode = this.importNode(objDoc.childNodes[i], true);
							
			  //append the child to the current document
			  this.appendChild(objImportedNode);
						
			} //End: for
	
		  } //End: function
	
		xmlDoc = document.implementation.createDocument('', '', null);

		xmlDoc.onload = ajaxcheck;

		// Como en FF no hay onreadystatechange, ejecutamos siempre el loading
		if (loading != null)
		eval(loading);

	}
	else if (window.ActiveXObject)
	{			
		// Explorer
		xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
		xmlDoc.async = true;

		xmlDoc.onreadystatechange = function () { 
			if(loading!=null){
				if (xmlDoc.readyState == 1) eval(loading);
			}
			if (xmlDoc.readyState == 4) ajaxcheck();			
		};
	}
	else
	{
		alert('Tu navegador no puede soportar el script');
		return;
	}
		
	xmlDoc.load(url);	
}

function ajaxcheck(){
	try{
		var auxnode = xmlDoc.firstChild.data;
		doAjax_error = false;
	}
	catch(e) {
		doAjax_error = true;
		if(doAjax_intentoserror < 3)
			if(confirm('Ha ocurrido un error de comunicación con el servidor. ¿Desea reintentar?')){
				doAjax_intentoserror ++;
				doAjax(doAjax_url,doAjax_f,doAjax_loading);
			}
			else{
				doAjax_intentoserror = 0;
				hideerror('ERROR: No se ha podido establecer comunicaci&oacute;n con el servidor.');
			}
		else{
			alert('Error de comunicación con el servidor.\nPor favor, vuelva a intentarlo pasados unos minutos.');
			doAjax_intentoserror = 0;
			hideerror('ERROR');
		}
	}

	if(!doAjax_error){
		doAjax_intentoserror = 0;
		eval(doAjax_f);
	}
}



// EFECTOS Y MENSAJES ////////////////////////////////////////////////


	// VARIABLES LOCALES /////////////////////

	var label;
	var indicemodal=0;
	var modal2Html = '';
	var hideTimeout = 2;
	var errorTimeout = 5;
	
	
	// MÉTODOS ///////////////////////////////
	
	// Mostrar mensaje en etiqueta arriba a la derecha, tipo Google
	function show(msg){
		crearEtiqueta();
		label.style.color = '#000';
		label.style.background = '#FD6';
		label.innerHTML = msg;
		label.style.display = '';
	}


	// Ocultar etiqueta (si se pasa un texto como parámetro se muestra con fondo verde durante 2 segundos)
	function hide(msg){
		if(msg){
			crearEtiqueta();
			label.style.color = '#FFF';
			label.style.background = '#093';
			label.innerHTML = msg;
			setTimeout('if(document.getElementById("_ajax_label")) document.body.removeChild(document.getElementById("_ajax_label"));',hideTimeout*1000);
		}
		else 
			if(document.getElementById("_ajax_label")) 
				document.body.removeChild(document.getElementById("_ajax_label"));
	}


	// Ocultar etiqueta mostrando un mensaje con fondo rojo durante 5 segundos
	function hideerror(msg){
		crearEtiqueta();
		label.style.color = '#FFF';
		label.style.background = '#C30';
		label.innerHTML = msg;
		setTimeout('if(document.getElementById("_ajax_label")) document.body.removeChild(document.getElementById("_ajax_label"));',errorTimeout*1000);
	}


	// Ventana modal centrada
	function showmodal(html){
		indicemodal++;
		bgTrans();
		var idventana = '_ajax_modalcontent_'+indicemodal;
		
		if(!document.getElementById(idventana)){
			var modalcontent = document.createElement('DIV');
	
			modalcontent.style.cssText = 'position:absolute; left: 0px; top: 0px; width: 100%; height: 100%; z-index:'+((1000*indicemodal)+1)+';';
			modalcontent.id = idventana;
			visionCombos('hidden');

			document.body.appendChild(modalcontent);
		}
		
		document.getElementById(idventana).innerHTML = '<table border="0" width="100%" height="100%" align="center"><tr><td align="center"><div id="_ajaxmodal" class="ajaxmodal">'+html+'</div></td></tr></table>';

		document.getElementById(idventana).style.top = getScrollY();

	/*	if(document.all)
			document.body.style.overflow = 'hidden';
		else
			window.onscroll = function(){
				if(document.getElementById(idventana)){
					document.getElementById(idventana).style.top = getScrollY();
				}
			}*/
	}
	
	
	// Ventana modal centrada que carga un iframe con el contenido url con ancho y alto
	function showmodalurl(url,ancho,alto){
		showmodal('<iframe name="frame_ajax" width="'+ancho+'" height="'+alto+'" scrolling="no" src="'+url+'" frameborder="no"></iframe>');
	}	
	

	function showmodal2(html){
		modal2Html = html;

//		hideModal();
		
		indicemodal++;
		bgTrans();

		if(!document.getElementById('_ajax_modal2_'+indicemodal)){
			var modal = document.createElement('DIV');
			modal.style.cssText = 'position: absolute; z-index:'+((1000*indicemodal)+1)+'; left: -45px; width: 15px; height: 15px; border: 1px solid #469dbe;';
			modal.style.top= getScrollY() + 15 + 'px'; 			
			modal.id = '_ajax_modal2_'+indicemodal;
			document.body.appendChild(modal);
		}

		/*if(document.all)
			document.body.style.overflow = 'hidden';
		else
			window.onscroll = function(){
				if(document.getElementById('_ajax_modal2_'+indicemodal)){
					document.getElementById('_ajax_modal2_'+indicemodal).style.top = getScrollY()+15;
				}
			}*/		

		modal2mover();
	}
		

	// Ocultar ventanas modales
	function hidemodal(){
		if(document.getElementById('_ajax_modal2_'+indicemodal)){
			document.body.removeChild(document.getElementById('_ajax_modal2_'+indicemodal));
			document.body.removeChild(document.getElementById('_ajax_trans_'+indicemodal));
			indicemodal--;
		}else if(document.getElementById('_ajax_modalcontent_'+indicemodal)){
			document.body.removeChild(document.getElementById('_ajax_modalcontent_'+indicemodal));
			document.body.removeChild(document.getElementById('_ajax_trans_'+indicemodal));
			indicemodal--;
		}

		if(indicemodal==0){
			//document.body.style.overflow = 'auto';
			visionCombos('visible');
		}
		else{
			if(document.getElementById('_ajax_modalcontent_'+indicemodal)){
				document.getElementById('_ajax_modalcontent_'+indicemodal).style.top = getScrollY();
			}
			
			/*window.onscroll = function(){
				if(document.getElementById('_ajax_modalcontent_'+indicemodal)){
					document.getElementById('_ajax_modalcontent_'+indicemodal).style.top = getScrollY();
				}
			}*/			
		}
	}



	function crearEtiqueta(){
		if(document.getElementById('_ajax_label'))
			label = document.getElementById('_ajax_label');
		else{
			label = document.createElement('SPAN');
			label.style.cssText = 'position: absolute; right:0px; padding: 2px 20px 2px 20px; font-family: arial; font-size: 13px; font-weight: bold; z-index: 99';
			
			label.id = '_ajax_label';
			document.body.appendChild(label);
		}

		label.style.top = getScrollY();
	}


	function modal2mover(){	
		var modal = document.getElementById('_ajax_modal2_'+indicemodal);
		
		if (modal.style.left!='30px'){
			modal.style.left = parseInt(modal.style.left.replace('px','')) + 5 + 'px';
			setTimeout(function(){modal2mover();},1);
		} 
		else {
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FF850D"',100);
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FFF"',200);
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FF850D"',300);
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FFF"',400);
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FF850D"',500);
			setTimeout('document.getElementById(\'_ajax_modal2_'+indicemodal+'\').style.background="#FFF"',600);
			setTimeout(function(){modal2resize();},700);
		}
	}
		
	function modal2resize(){
		var modal = document.getElementById('_ajax_modal2_'+indicemodal);
	
		if (modal.style.width!=415+'px'){
			modal.style.width = parseInt(modal.style.width.replace('px','')) + 40 + 'px';
			modal.style.height = parseInt(modal.style.height.replace('px','')) + 10 + 'px';
			setTimeout(function(){modal2resize();},20);
		}
		else{
			modal.style.background= 'url(http://www.facilisimo.com/mensajes/expocasa/images/logo.gif) no-repeat top center #FFF';
			modal.style.height = 'auto';
			modal.innerHTML = '<div style="margin: 50px 0 15px 0; text-align: center;">'+modal2Html+'</p>';
		}
	}	
	
	
	function bgTrans(){
		if(!document.getElementById('_ajax_trans_'+indicemodal)){
			var modal = document.createElement('DIV');
			if(document.all){
				modal.style.backgroundColor = 'transparent'; 
				modal.style.backgroundImage = 'url(/images/px.gif)';
				modal.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader (src="/images/px.png", sizingMethod="scale")';
			}
			else			
				modal.style.backgroundImage = 'url(/images/px.png)';
			
			modal.style.position = 'absolute';
			modal.style.height = document.body.scrollHeight+'px';
			modal.style.top = '0px';
			modal.style.left = '0px';
			modal.style.zIndex = 1000*indicemodal;
			modal.style.width = '100%';
			modal.id = '_ajax_trans_'+indicemodal;
	
			visionCombos('hidden');
			
			document.body.appendChild(modal);
		}
	}
	
	
	function visionCombos(opcion){
		if(document.all){
			var arr = document.getElementsByTagName('select');
			for(i = 0; i < arr.length; i++) {
				arr[i].style.visibility = opcion;
			}
		}
	}
	
	
	function getScrollY(){
		var scrollY = 0;
		
		if ( document.documentElement && document.documentElement.scrollTop ){
			scrollY = document.documentElement.scrollTop;
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop;
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset;
		}else if ( window.scrollY ){
			scrollY = window.scrollY;
		}
		
		return scrollY;
	}
