/*
*  ajxContent.js
*  Fitxer d'scripts AJAX per a la web
*
*  Creat per Esteve Blanch Sanmartí a 26 de gener de 2009
*  Copyright (C) 2009. Esteve Blanch Sanmartí.
*  Cleopatra Network Solutions.
*
*/

// ************************ Annex per les pàgines dinamiques ************************ //
var tagScript = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
/**
* Eval script fragment
* @return String
*/
String.prototype.evalScript = function()
{
	return (this.match(new RegExp(tagScript, 'img')) || []).evalScript();
};
/**
* strip script fragment
* @return String
*/
String.prototype.stripScript = function()
{
    return this.replace(new RegExp(tagScript, 'img'), '');
};
/**
* extract script fragment
* @return String
*/
String.prototype.extractScript = function()
{
    var matchAll = new RegExp(tagScript, 'img');
    return (this.match(matchAll) || []);
};
/**
* Eval scripts
* @return String
*/
Array.prototype.evalScript = function(extracted)
{
	var s=this.map(function(sr){
    	var sc=(sr.match(new RegExp(tagScript, 'im')) || ['', ''])[1];
        if(window.execScript){
			window.execScript(tagScript);
        }
        else
        {
			window.setTimeout(sc,0);
        }
	});
	
    return true;
 };
/**
* Map array elements
* @param {Function} fun
* @return Function
*/
Array.prototype.map = function(fun)
{
    if(typeof fun!=="function"){return false;}
     var i = 0, l = this.length;
     for(i=0;i<l;i++)
     {
		 fun(this[i]);
     }
	 
     return true;
};


// ************************ Codi de la web ************************ //


function createXMLcon()
{
	var obj;
	
	try {
		obj = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			obj = new ActiveXObject("Microsoft.XMLHTTP")
		} catch(e) { obj = null; }
	}
	
	if ( obj == null )
	{
		try {
			obj = new XMLHttpRequest();
		} catch (e) {}
	}
	
	if ( obj == null && window.createRequest )
	{
		try {
			obj = window.createRequest();
		} catch (e){
			throwError( 001000, "El navegador sembla que no accepta les transmisions XML-HTTP. Utilitza un navegador compatible.<br />"+ e );
		}
	}
	
	return obj; 
}

function mostrarLoading()
{
	var mnDiv = document.createElement('div');
	mnDiv.id = "mainCharger";
	mnDiv.width = document.getElementById('efectMain').width;
	mnDiv.height = document.getElementById('efectMain').height;
	mnDiv.innerHTML = "<p><img src=\"imatges/charger.gif\" /> carregant ...</p><p>&nbsp;</p><p style=\"font-size: 12px\">Algunes versions del navegador internet explorer no son del tot compatibles amb la web de l'espai. Estem treballant per corregir-ho, disculpeu les molesties.</p>";
	
	document.getElementById('mainContainer').appendChild(mnDiv);
}

function amagarLoading()
{
	var mnDiv = document.getElementById("mainCharger");
	document.getElementById('mainContainer').removeChild(mnDiv);
}

function throwError( codi, missatge )
{
	desti = document.getElementById("AJAXcontingut");
	amagarLoading();
	
	desti.innerHTML = "<br /><p class=\"ERm\"><img src=\"imatges/error.gif\" align=\"left\" />ERROR</p><p>Codi: 0x" + codi +"</p><p>"+ missatge +"</p>";
}

function tabClick( idTab )
{
	var url = "dades/tabs.xml";
	
	mostrarLoading();
	
	var xmlReq = createXMLcon();
	xmlReq.open("GET", url + "?" + Math.floor(Math.random()*1024), true);
	xmlReq.setRequestHeader("Content-type", "aplication/x-www-form-urlencodes");
	xmlReq.setRequestHeader("X-AJAX-APP", "Cleopatra Asyncrous web plataform");
	xmlReq.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
	xmlReq.send(null);
	xmlReq.onreadystatechange = function()
		{
			if(xmlReq.readyState == 4)
			{
				var resposta = xmlReq.responseText;
				parseXMLtab(resposta, idTab);
			}
		};
}

function parseXMLtab( dades, idTab )
{
	var xmlData;
	
	try {
		XmlData = new ActiveXObject("Microsoft.XMLDOM");
		XmlData.async = false;
		XmlData.loadXML(dades);
	}
	catch (e)
	{
		parser = new DOMParser();
		XmlData = parser.parseFromString(dades, "text/xml");
	}
	
	reqTipus = XmlData.getElementsByTagName("response")[0].attributes[0].nodeValue;
	
	if( reqTipus == "relTabs" )
	{
		rDades = XmlData.getElementsByTagName("relTabs")[0];
		i = 0;
		trobat = false;
		
		while( i < rDades.childNodes.length && !trobat )
		{
			t = rDades.childNodes[i];
			if( t.nodeType == 1 )
			{
				if( t.attributes[0].nodeValue == idTab ) trobat = true;
			}
			i++;
		}
		
		if( trobat )
		{
			creaPagina(t.attributes[1].nodeValue, t.attributes[2].nodeValue);
			
		} else {
			// ERROR: El id de la pestanya no ha estat trobada
			throwError( 010002, "L'identificador de pestanya sol&middot;licitat no est&agrave; registrat al sistema." );
		}
		
	} else {
		// ERROR: Sembla que el fitxer XML no és el correcte.
		throwError( 010001, "Les dades de configuraci&oacute; de pestanyes semblen estar corruptes." );
	}
}

function creaPagina(url, tipus)
{
	desti = document.getElementById("AJAXcontingut");
	
	var xmlReq = createXMLcon();
	xmlReq.open("GET", url + "?" + Math.floor(Math.random()*1024), true);
	xmlReq.setRequestHeader("Content-type", "aplication/x-www-form-urlencodes");
	xmlReq.setRequestHeader("X-AJAX-APP", "Cleopatra Asyncrous web plataform");
	xmlReq.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
	xmlReq.send(null);
	xmlReq.onreadystatechange = function()
		{
			if(xmlReq.readyState == 4 && xmlReq.status == 200)
			{
				var resposta = xmlReq.responseText;
				if( tipus == "dinamic" )
				{
					scp = resposta.extractScript();
					desti.innerHTML = resposta.stripScript();
					scp.evalScript();
				} else {
					desti.innerHTML = resposta;
					amagarLoading();
				}
			}
			if(xmlReq.readyState == 4 && xmlReq.status == 404)
			{
				// ERROR: Sembla que la pàgina asociada no s'ha trobat
				throwError( 010003, "Les dades associades a la pestanya sol&middot;licitada no es troben disponibles." );
			}
		};
}

