// JavaScript Document

//var INIT_IMPORT=-1;
var zAct=50;	//valor del zIndex maxim actual
//TRADUCCIO:  trad.NomDia1 = "Dilluns";
var trad = {CCT: "Cristian"};
var idDivNotSel='-1';
var nCargant=0;	//numero de cargues (>0 es mostra el div ajaxLoader; <= 0 s'oculta el div ajaxLoader>

function _$(x){return document.getElementById(x);} 
//function _$GA(e,a){return e.getAttribute(a);}
//function _$SA(x,a,v){document.getElementById(x).setAttribute(a,v);}
function _SA(x,a,v){x.setAttribute(a,v);}

function prnt(text){document.write(text);}

function trd(x){document.write(trad[x]);}


//CLK GENERALS
function clkLogoutCommon(){
	include(PATH_WEB+'/codi/js/login/login.js#logoutUser();');
}
function clkLoginCommon(){
	showGetLoginUsu('loginOkCommon();');
}
function loginOkCommon(){
	document.location.reload();
}


//FUNCIONS URL

//var defAnch=''; 	//valor de l'ancora per defecte. Indica quins elements carregar dins la web
var actAnch='-1';
function initChekAnchor(){
	//Si volem començar rebent les noticies per ajax
	//checkAnchorInicial();

	//periodicament anirem comprovant si canvia l'ancora de la url i en tal cas executant-la
	 setInterval("checkAnchor()", 400);
}

function checkAnchorDiferent(){
	//Evaluem nomes aquells elements que difereixen del anchor inicial
	//document.location.hash='#oooooo';
	
	var anchor = actAnch;
	var listDef = defAnch.split('/');
	var listDif=new Array('');
	
	if (anchor.length > 0) {
		var listAct = anchor.split('/');
		for (k = 0; k < listAct.length; k++) {
			var matched=false;
			var paramA = listAct[k].split(';');
			for (j = 0; j < listDef.length && !matched; j++) {
				var paramB = listDef[j].split(';');
				if (paramA[0] == paramB[0]) {
					listDif.unshift(listDef[j]);
					listDef[j] = listAct[k];
					matched=true;
				}
			}
//			if(!matched){	//Si el contenidor indicat no existeix en la llista per defete, l'afegeix
//				listDef.unshift(listAct[k]);
//				k++;
//				matched=false;
//			}
		}
	}
	actAnch='';
	//Executa el anchor actual
	evalAnchor(listDif);
}
///**Canvia la llengua per defecte d'una sessio
// * 
// * @param {Object} lang
// */
//function clkChgLang(lang){
//	var sendReq = new sendRequestAjax();
//	sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=chgLang&lang='+lang, respChgLang);
//}
//function respChgLang(xmlHttp){
//	if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//		document.location.reload();
//	}
//}
/**
 * 
 * @param {Object} id
 * @param {Object} typ	Not, LliNot
 */
function genURLElem(id,typ){
	var url = document.location.href.split('#')[0];
	url = url.split('?')[0];
	
	url = url.split('!=')[0];
	//url= url.substring(url.indexOf(PATH_WEB));
	url=url.substring(url.lastIndexOf('/')+1);
	if(id!=''){
		url+='?!=1;'+typ+';'+id;
	}
	//	url=chgLangParamUrl(url,_$('langEditNot').value);
	return url;

	
}
function chgLangParamUrl(url,lang){
	//http://localhost/amic/index.php?lang=ca&pp=0#1;Not;79
	//var url = document.location.href;
	var indxA=url.indexOf('?');
	var linkLang = url;
	if(indxA<0){
		//url sense parametres
		indxA=url.indexOf('#');
		if(indxA<0){
			//http://localhost/amic/index.php
			linkLang=linkLang+ "?lang=" + lang;
		}else{
			//http://localhost/amic/index.php#1;Not;79
			linkLang=url.substr(0, indxA)+ "?lang=" + lang+url.substr(indxA,url.length);
		}
	}else{
		//url amb parametres
		indxA=url.indexOf('lang=');
		var indxB=url.indexOf('&',indxA);
		if(indxB<0){
			//http://localhost/amic/index.php?lang=ca#1;Not;79
			indxB=url.indexOf('#',indxA);
		}
		linkLang = url.substr(0, indxA) + "lang=" + lang;
		if(indxB>0){
				linkLang+=url.substr(indxB,url.length);	
		}
	}
	return linkLang;
}

/**Parseja la url i busca com omplir la web
 * format parametres:
 * #nomElement+nom del contenidor contCon+param1+param2+param3...
 */
function checkAnchor(){  
	var anchor = document.location.hash.substring(1);
	
	if (actAnch != anchor) {
		if (anchor == '') {
			checkAnchorDiferent();
		}
		else {
			actAnch = anchor;
			var listAnch = actAnch.split('/');
			
			evalAnchor(listAnch);
		}
	}
}  


function evalAnchor(listDef){
	//Evalua les funcions indicades
	for (var k = 0; k < listDef.length; k++) {
		var def = listDef[k].split(';');
		var titl=def[0].split(':');
//		_$('banner').innerHTML+=' -  falg1:'+listDef[k];
		if(titl.length>1){
			//titol que li pasem per url
			def[0]=titl[1];//obtenim el idCont
			//titl=unescape(titl[0]);
			titl=titl[0];
			document.title=trad['nomCapsula']+' : '+titl;
			//type,titol,id,idCont
//			genTitolRuta(def[1],titl,def[2],def[0]);
			genTitolRuta(titl,listDef[k],def[1]);
		}
		
		var fun = 'showGet' + def[1] + '("contenidor' + def[0] + '"';
		for (var i = 2; i < def.length; i++) {
			fun += ',"' + def[i] + '"';
		}
		fun += ');';
		
		try {
			eval(fun);
		} 
		catch (e) {
		}
	}
}

/**Inserta un parametre en una URL. Si existeix el substitueix
 * No funciona molt bé que diguem
 * @param {Object} url	->var url = location.search;
 * @param {Object} param
 * @param {Object} val
 */
/**
function insertParamURL(url, param, val){
    param = escape(param); val = escape(val);
    var kvp = url.substr(0).split('&');
    var i=kvp.length; 
	var x; 
	while(i--){
        x = kvp[i].split('=');
        if (x[0]==param){
                x[1] = val;
                kvp[i] = x.join('=');
                break;
        }
    }
    if(i<0) {kvp[kvp.length] = [param,val].join('=');}
    url = kvp.join('&');
	return url; 
}

*/

//FUNCIONS TRADUCCIO
/*Tradueix l'atribut trd dels tags span i inserta el resultat dins el tag span
 * 
 */
function trdDocument(){
	 trdListElem(document.getElementsByTagName('span'));
}
function trdContenidor(idCont){
	 trdListElem(document.getElementById(idCont).getElementsByTagName('span'));
}
function trdListElem(list){
	for(k=0; k < list.length; k++){
		var tmp = list[k].getAttribute('trd');
		if (tmp) {
			list[k].removeAttribute(tmp);	
			list[k].innerHTML = trad[tmp];	
			list[k].removeAttribute('trd');
		}
	}
}


//FUNCIONS EVENTS 

/**Fer servir aixó en comptes de AddEventListener, que IE6 no ho accepta
 * addEvent(div,'click', function(e){	funcio(param);	}, false);
 * @param {Object} obj objecte al que afegir l'event
 * @param {Object} evType quan salta l'event? ("mouseover")
 * @param {Object} fn funcio que es llença0 (function(e){resetMouseVal();})
 * @param {Object} useCapture  false normalment
 */
function addEvent(obj, evType, fn, useCapture){
	useCapture = useCapture || false;//PER DEFECTE, FALSE
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
	return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
}
/**
 * 
 * @param {Object} obj
 * @param {Object} evType
 * @param {Object} fn
 * @param {Object} useCapture
 */
function removeEvent(obj,evType,fn,useCapture){ 
	useCapture = useCapture || false;//PER DEFECTE, FALSE
    if(obj.removeEventListener){ 
        obj.removeEventListener(evType,fn,false); 
    }else if(obj.detachEvent){ 
        obj.detachEvent('on'+evType,obj[fn.toString()+evType]); 
        obj[fn.toString()+evType]=null; 
    }else{ 
        obj['on'+evType]=function(){} 
    } 
} 

/**Cancels the event if it is cancelable,
 * 
 * @param {Object} e
 */
function cancelEv(e){ 
    e=e || window.event; 
    if(e.preventDefault) 
        e.preventDefault(); 
    else 
        e.returnValue=false; 
} 
/**stop further propagation of the event through the DOM
 * 
 * @param {Object} e
 */
function stopEv(e){ 
    e=e || window.event; 
    if(e.stopPropagation) 
        e.stopPropagation(); 
    else 
        e.cancelBubble=true; 
} 

//

/**
El siguiente fragmento de código proporciona la posición absoluta de cualquier elemento HTML del árbol DOM. Es bastante útil para situar capas emergentes encima de un elemento concreto - ya sea en forma de ayudas o para menús.
La esencia de la función son las propiedades offsetLeft y offsetTop, que devuelven la posición relativa de un elemento respecto a su contenedor, que a su vez está almacenado en offsetParent.
*/
function getAbsoluteElementPosition(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}


//
/**conmuta entre l'estat de show i hide d'un element
 * retorna l'estat en el que acava
*/
function showHide(id){	
	if( _$(id).style.visibility!= 'hidden'){
		_$(id).style.visibility='hidden';
		return 'hidden';
	}else{
		_$(id).style.visibility='visible';
		return 'visible';
	}	
}
function show(id){
	var elm = _$(id);
	if(elm){elm.style.visibility='visible';}
	
}
function hide(id){
	var elm = _$(id);
	if(elm){elm.style.visibility='hidden';}
}
/**Per defecte display = none
 * 
 * @param {Object} id
 */
 function switchDisplay(id,typ){
 	if (!typ) {
		typ = 'block';
	}
 	if (_$(id).style.display != 'none') {return notDisplay(id);	}
	else {		
	_$(id).style.display = typ; 
	return typ;
	}
 }
 function notDisplay(id){
 	try {
		_$(id).style.display = 'none';
	}catch(e){}
	return 'none';
}
 function display(id){//_$(id).style.display = 'inline';}
 try {
 	_$(id).style.display = 'block';
 }catch(e){} 
 	return 'block';
}

//FUNCIONS DE DATES
//Substituir per dateSqlToJava(data)
//extreu el dia d'un text del tipus dd-mm-aaaa
function extractDiaData(idDia){
	var sepD = idDia.indexOf('-',0);
	var dia = idDia.substring(0,sepD);
	return dia;
}
//extreu el dia d'una text del tipus dd-mm-aaaa  TODO:Millorar
function extractMesData(idDia){
	var sepD = idDia.indexOf('-',0);
	var sepM = idDia.indexOf('-',sepD+1);
	var mes = idDia.substring(sepD+1,sepM);
	return mes;
}
//extreu el dia d'una text del tipus dd-mm-aaaa   TODO:Millorar
function extractAnyData(idDia){
	var sepD = idDia.indexOf('-',0);
	var sepM = idDia.indexOf('-',sepD+1);
	var any = idDia.substring(sepM+1,idDia.length);
	return any;
}
function getMesAnterior(data){
		var mes = extractMesData(data)-1;
		var any = extractAnyData(data);
		if(mes <=0){
			mes =12;
			any = any -1;
		}
		return extractDiaData(data)+"-"+mes+"-"+any;
}
function getMesPosterior(data){
		var mes = extractMesData(data)-1+2;
		var any = extractAnyData(data);
		
		if(mes > 12){
			mes =1;
			any = any -1+2;
		}
		
		return extractDiaData(data)+"-"+mes+"-"+any;
		//return '2009-08-31 00:00:00';
}

/*miFecha = new Date()	Data actual
miFecha = new Date(año,mes,dia,hora,minutos,segundos) 
miFecha = new Date(año,mes,dia)
	getDate() 		Devuelve el día del mes. 
	getDay() 		Devuelve el día de la semana. 
	getHours() 		Retorna la hora. 
	getMinutes() 	Devuelve los minutos. 
	getMonth() 		Devuelve el mes (atención al mes que empieza por 0). 
	getSeconds()  	Devuelve los segundos. 
	getTime() 		Devuelve los milisegundos transcurridos entre el día 1 de enero de 1970 y la fecha correspondiente al objeto 	al que se le pasa el mensaje. 
	getYear() 		Retorna el año, al que se le ha restado 1900. Por ejemplo, para el 1995 retorna 95, para el 2005 retorna 105. Este método está obsoleto en Netscape a partir de la versión 1.3 de Javascript y ahora se utiliza getFullYear(). 
	getFullYear() 	Retorna el año con todos los dígitos. Usar este método para estar seguros de que funcionará todo bien en fechas posteriores al año 2000. 
	setDate() 		Actualiza el día del mes. 
	setHours() 		Actualiza la hora. 
	setMinutes() 	Cambia los minutos. 
	setMonth() 		Cambia el mes (atención al mes que empieza por 0). 
	setSeconds() 	Cambia los segundos. 
	setTime() 		Actualiza la fecha completa. Recibe un número de milisegundos desde el 1 de enero de 1970. 
	setYear() 		Cambia el año recibe un número, al que le suma 1900 antes de colocarlo como año de la fecha. Por ejemplo, si recibe 95 colocará el año 1995. Este método está obsoleto a partir de Javascript 1.3 en Netscape. Ahora se utiliza setFullYear(), indicando el año con todos los dígitos. 
	setFullYear() 	Cambia el año de la fecha al número que recibe por parámetro. El número se indica completo ej: 2005 o 1995. Utilizar este método para estar seguros que todo funciona para fechas posteriores a 2000.
*/
function dateSqlToJava(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    var r = new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
	return r;
}
//	miFecha = new Date(anyIni,mesIni,diaIni,horIni,minIni,'0');
function dateJavaToSql(time){
	return ''+time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDay()+' '+time.getHours()+':'+time.getMinutes()+':'+time.getSeconds();
}

function htmlToTextArea(text){
	text = text.split('<br/>').join('\n');
	text = text.split('<br>').join('\n');
	text = text.split('&nbsp;').join(' ');

	text = text.split(/&lt;/).join('<');
	text = text.split(/&gt;/).join('>');	
	text = text.split(/&amp;/).join('&');	
	
	return text;
}
function textAreaToHtml(text){	
	text = text.split('&').join('&amp;');	
	text = text.split(/</).join('&lt;');
	text = text.split(/>/).join('&gt;');	
	
	text = text.split(/\n/).join('<br/>');
	text = text.split(/\s/).join('&nbsp;');

	return text;
}

/**Retorna el frame que se li pasa com a identificador
 * pe:getFrameWindow('textEditor').document.body.innerHTML='aaaa';
 * 
 * @param {Object} frameId
 */
function getFrameWindow(frameId) {
  var frame = document.getElementById(frameId);
  var result = null;
  if (frame.contentDocument) {
    // For NS6
    result = frame.contentDocument.window || frame.contentDocument.defaultView; 
  } else if (frame.contentWindow) {
    // For IE5.5 and IE6
    result = frame.contentWindow;
  } else if (frame.document) {
    // For IE5
    result = frame.document.window;
  }
  return result;
}
/**Deselecciona tots els elements seleccionats
 * 
 */
function clearSelection () {
	if (window.getSelection) window.getSelection().removeAllRanges();
else if (document.selection && document.selection.empty) document.selection.empty();
}


function escapeReally(text){
	text=escape(text);
	text=text.replace(new RegExp( "\\+", "g" ),"%2B");
	
	return text;
}
function unescapeReally(text){
	text = unescape(text);
	return text;
}



/**
 * 
 * @param {Object} text	text a chequejar
 * @param {Object} numDig	minim digits que te que tenir
 * @param {Object} errCont	id del element al que situar el possible error
 */
function chkMinDigits(text,numDig, errCont){
	var textResp='';
	var resp=0;
	if(text.length < numDig){
		textResp=trad.errNumDigits+numDig;		
		resp=-1;	
	}
	if (_$(errCont)) {
		_$(errCont).innerHTML=textResp;
		return resp;
	}else{
		if (textResp != '') {
			window.alert(textResp);
		}
	}
}


var llistaIncludes = new Array(0);	//pila FIFO a on s'hi van possant els includes a afegir 
var carregant=false;	//Indica si s'está dins el bucle de carrega d'includes

/*Exemple codi que es parseja per insertar dins bucle d'includes
 * <include><path><![CDATA['.PATH_WEB.'/css/gestorFitxers/gestorFitxers.css]]></path></include>'
 * Exemple codi que es parseja per insertar com codi html en el bodi o idCont especificat
 * <code>
 * <idCont>gestFitxCont</idCont>
 * <id>gestFitxWin</id>
 * <html><![CDATA[
 * <div id="gestFitxWin"  style="top:18px;	left:110px;">
 */
/**Parseja el XML per insertar el codi html.
 * <br> Primer inserta els codis html que tenen que anar en el body dins la capa especificada per el tag id
 * <br> Si existeix el contenidor especificat (idCont) ,inserta el codi dins, sinó crea un div amb id = idCont
 * <br> Si ja existeix el id, no fa res
 * <br> Segon inserta els includes necessaris
 * <br> si se li indica un idCont, inserta el codi al contenidor indicat, sinó crea el un contenidor per defecte i inserta el codi allí
 * @param {Object} xmlHttp
 */
function parseXMLAppendCode(xmlHttp){
	if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		
		var resposta = xmlHttp.responseXML;
		//Carreguem variable INIT_IMPORT
		var listResp = resposta.getElementsByTagName("info");
		var add=0;
		for (var k = 0; k < listResp.length; k++) {
			try{
				add=listResp[k].getElementsByTagName("add")[0].childNodes[0].nodeValue;
			}catch(e){}
		}
		//Primer Carreguem el HTML
		listResp = resposta.getElementsByTagName("code");
		
		for (var k = 0; k < listResp.length; k++) {
			var id = listResp[k].getElementsByTagName("id")[0].childNodes[0].nodeValue;
			var divTmp = _$(id);
			if (divTmp) {
				divTmp.parentNode.removeChild(divTmp);
			}
//			if (!_$(id)) {
				//EL DIV no existeix
				var idCont = listResp[k].getElementsByTagName("idCont")[0].childNodes[0].nodeValue;
				if (!_$(idCont)) {
					var div = document.createElement('div');
					div.id = idCont;
					try {
						document.body.appendChild(div);
					}catch(e){}
				}
				else {
					//El cont existeix
					var div = _$(idCont);
				}
				var codi = listResp[k].getElementsByTagName("html")[0].childNodes[0].nodeValue;
				if (add == 1) {
					div.innerHTML += codi;
				}
				else {
					div.innerHTML = codi;
				}
//			}
		}
		listResp = resposta.getElementsByTagName("include");
		
		for (var k = 0; k < listResp.length; k++) {
			var path = listResp[k].getElementsByTagName("path")[0].childNodes[0].nodeValue;
			//include(path);
			llistaIncludes.push(path);
		}
		iniciaCarregaIncludes();
	}
}
/**Afegeix un path a la llista de paths per incloure
 * 
 * @param {Object} path
 * /css/editorNoticia/showNoticia.css
 * /codi/js/common.js#funcions inici
 * idScript#script#text/javascript#initShowLliNot(1);
 * idCss#1#style#text/css#codiCSS
 */
function include(path){
//	try {_$('flag1').innerHTML+="<br>encua: -"+llistaIncludes.length+"["+path+"]";}catch(e){}
	llistaIncludes.push(path);
	iniciaCarregaIncludes();
}
/**Indica que comenci el bucle de cárrega. No té efecte si el bucle encara está carregant
 */
function iniciaCarregaIncludes(){
	if (!carregant) {
		carregant = true;
		carregaNextInclude();
	}
}
/**Carrega el seguent include dins el bucle de cárrega
 * NO HAURIA DE SER CRIDAT EXCEPTE DINS ADDINCLUDE o LOADSCRIPT
 * Per carrega un include hem de cridar a include(path) i iniciaCarregaIncludes()
 */
function carregaNextInclude(){
		//	try {_$('pop').innerHTML+=" 1 "}catch(e){}
		if (llistaIncludes.length > 0) {
			addInclude(llistaIncludes.shift());
		}else{
			carregant=false;
		}
}
/**Carga Asincrona d'arxius javascript i css
 * NO HAURA DE SER CRIDAT EXCEPTE PER carregaNextInclude
 * Per carrega un include hem de cridar a include(path) i iniciaCarregaIncludes()
 * @param {Object} path
 */
function addInclude(path){
//	try {_$('pop').innerHTML+="addInclude:"+path;}catch(e){}
	//fr = path.split('#');
	var fr= Array(0);
	var tmpF=path.indexOf('#',0);
	var tmpI=0;
	if (tmpF == -1) {
		fr[0] = path;
	}
	else {
		for (k = 0; k < 3 && tmpF != -1; k++) {
			fr[k] = path.substring(tmpI, tmpF);
			tmpI = tmpF + 1;
			tmpF = path.indexOf('#', tmpI);
		}
		fr[k] = path.substring(tmpI, path.length);
	}
	
	if (document.getElementById(fr[0]) == null) {
		if (fr[0].match(/\.(css)$/)) {
			loadCss(fr[0]);
//try {_$('pop').innerHTML+="add CSS: "+fr[0];}catch(e){}
		}
		else {
//			try {_$('pop').innerHTML+="add JAVASCRIPT: "+fr[0];}catch(e){}
			//LINKS JAVASCRIPT
			if (fr[0].match(/\.(js)$/)) {
				if (fr[1]) {
					loadScript(fr[0], fr[1]);
				}
				else {
					loadScript(fr[0], '');
				}
			//FUNCIO JAVASCRIPT
			}else{
//			try {_$('pop').innerHTML+=" WTF! "+fr[0];}catch(e){}
			}

		}
	}else{
		if (fr[1]) {
//			try {_$('pop').innerHTML+=" evaluant else: "+fr[1];}catch(e){}
					eval(fr[1]);
				}
//		try {_$('pop').innerHTML+=" url existent"+fr[0];}catch(e){}
		carregaNextInclude();
	}
	//try {_$('pop').innerHTML+=" carregat"+path;}catch(e){}
}
/**Carrega un codi javascript de la url especificada. Si se li indica una funcio extra, l'evalua despres de carregar l'escript
 * Crida a carregaNextInclude() un cop carregat el codi.
 * 
 * NO HAURA DE SER CRIDAT EXCEPTE PER carregaNextInclude
 * Per carrega un include hem de cridar a include(path) i iniciaCarregaIncludes()
 * @param {Object} url
 * @param {Object} nextFun
 */
function loadScript(url,nextFun){
//try {_$('pop').innerHTML+="loadScript: "+url;}catch(e){}
	var script = document.createElement("script")
	script.type = "text/javascript";

	
	if (script.readyState) { //IE 
		script.onreadystatechange = function(){
			if (script.readyState == "loaded" || script.readyState == "complete") {
				script.onreadystatechange = null;
					if(nextFun!=''){
						eval(nextFun);
					}
				carregaNextInclude();
			}
		};
	}
	else { //Others
		script.addEventListener('load', function(){ 
				if(nextFun!=''){
						eval(nextFun);
					}
					carregaNextInclude();
        }, false); 
	}
	script.id=url;
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}

function loadCss(url){
	var css = document.createElement("link")
	css.type = "text/css";
	css.rel = "stylesheet";
	css.id=url;
	css.href = url;
	document.getElementsByTagName("head")[0].appendChild(css);
//	try {_$('flag1').innerHTML+="<br>loadCSS: "+url;}catch(e){}
	if (css.readyState) {
		css.onreadystatechange = function(){//IE
			if (css.readyState == 'complete') {
				carregaNextInclude();
			}
		};
	}else{
		carregaNextInclude();
	}	
}

/**Crea un menu popup superior a les altres finestres, en les coordenades indicades i amb el contingut indicat
 * S'hi poden afegir opcions amb: addOpcMenuPopUp
 * @param {Object} top
 * @param {Object} left
 * @param {Object} html	codi que s'inserta dins	 -1 per res
 * @param {Object} elem	element que si adjunta	-1 per res
 */
function showGetMenuPopUp(top,left,html){
	var div =_$('menuPopUp');
	if (!div) {
		div = document.createElement('div');
		div.id = "menuPopUp";
		document.body.appendChild(div);
	}
	div.style.zIndex=zAct+3;
	div.style.top=top;
	div.style.left=left;
	div.innerHTML = '';
	try{
		div.appendChild(html);
	}catch(e){
		div.innerHTML = html;
	}
//	if(!html.tagName || html.tagName="undefined"){}else
//	if (html != '-1') {
//		div.innerHTML = html;
//	}if (elem != '-1') {
//		div.appendChild(elem);
//	}
	div.style.visibility='visible';
}
/**Afegeix una opcio al menu dels fitxers
 * 
 * @param {Object} param  farametres de la funcio
 * @param {Object} table
 * @param {Object} funcio
 * @param {Object} titol
 */
function addOpcMenuPopUp(table,funcio,param,titol){
	var row=table.insertRow(-1);
	var cel=row.insertCell(0);
	cel.className="opcMenuPopUp";
	cel.innerHTML=titol;
	if (funcio != -1) {
		addEvent(cel, 'click', function(e){funcio(param);},true);
	}
	return cel;
}

/**Carrega l'editor d'usuari, o si ja existeix el mostra
 * 
 * @param {Object} idU
 */
function showGetEditUsu(idU){
	if(_$('editUsuWin')){	
	showEditUsu(idU);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiEditUsu&idUsu='+idU, parseXMLAppendCode);
	}
}

function showGetEditGrup(idG){
	if(_$('editGrupWin')){	
	showEditGrup(idG);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiEditGrup&idGrup='+idG, parseXMLAppendCode);
	}
}
function showGetGestorAdmin(){
	if(_$('gestorAdminWin')){	
	showGestorAdmin();	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getGestorAdmin', parseXMLAppendCode);
	}
}
function showGetGestorUsus(){
	if(_$('gestorUsusWin')){	
	showGestorUsus();	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiGestorUsus', parseXMLAppendCode);
	}
}

function showGetGestorGrups(){
	if(_$('gestorGrupsWin')){	
	showGestorGrups();	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiGestorGrups', parseXMLAppendCode);
	}
}
/**
 * 
 * @param {Object} fun funcio que es cridará un cop ens haguem autentificat correctament
 */
function showGetLoginUsu(fun){
	if(_$('loginWin')){	
	showLogin(fun);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiLogin&fun='+fun, parseXMLAppendCode);
	}
}
function showGetOpcLogin(){
	var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiLogin&fun='+fun, parseXMLAppendCode);
}
function showGetGestorCarp(idC){
	if(_$('gestorCarpWin')){	
	showGestorCarp(idC);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getCodiGestorCarp&idC='+idC, parseXMLAppendCode);
	}
}
/**	id de la carpeta inicial desde les que mostrar el gestor
 * @param {Object} idC id carpeta desde la que mostrar el gestor	
 * <p>Els seguents parametres poden tenir 3 valors:
 * <br>1 Mostra (arxius, carpetes, noticies)
 * <br>0 No el mostra
 * <br>-1 No els mostra ni es pot seleccionar el checkBox perque els mostri	
 * @param {Object} vA	veu arxius
 * @param {Object} vC	veu carpetes
 * @param {Object} vN	veu noticies
 * @param {Object} vLN	veu llista noticies
 */
function showGetGestorFitx(idCont,idC, vA, vC, vN, vLN){
	if(_$('gestorFitxWin')){	
	showGestorFitx(idC);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php',parseXMLAppendCode,'action=getGestorFitxers&idC='+idC+'&idCont='+idCont+'&vA='+vA+'&vC='+vC+'&vN='+vN+'&vLN='+vLN);
	}
}
/**
 * @param {Object} idCont
 * @param {Object} idDadIni	id de l'element del que agafar les dades inicials del editor
 */

function showGetEditCont(idCont, idDadIni){
	if(_$('editContWin')){	
		showEditCont(idDadIni);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getEditorContingut&idCont=' + idCont + '&idDadIni=' + idDadIni, parseXMLAppendCode);
	}
}

/**Mostra una noticia dins el contenidor indicat
 * @param {Object} idCont	contenidor en el que es vol insertar la noticia inicialment
 * @param {Object} idN	identificador de la noticia
 * @param {Object} idL
 * @param {Object} shTit
 * @param {Object} shDes
 * @param {Object} shRes
 * @param {Object} shIni
 * @param {Object} shFi
 * @param {Object} shLloc
 * @param {Object} shForm
 * @param {Object} lang
 */
function showGetNot(idCont,idN,idL,shTit,shDes,shRes, shIni, shFi, shLloc, shForm,shLink,lang){
//	if(_$('showNotWin'+idN+'F'+shForm)){
//		if(_$('showNotWin'+idN+'F'+shForm).parentNode.id == idCont){
//			showShowNot(idN);		
//		}else{
//			if (!_$(idCont)) {
//				var div = document.createElement('div');
//				div.id = idCont;
//				try {
//					document.body.appendChild(div);
//				}catch(e){}
//			}
//		}
//	}else{
		showGetNotI(idCont,idN,idL,shTit,shDes,shRes, shIni, shFi, shLloc, shForm,shLink,lang);
//	}
}
function showGetNotI(idCont,idN,idL,shTit,shDes,shRes, shIni, shFi, shLloc, shForm,shLink,lang){
	var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php',parseXMLAppendCode,'action=getShowNoticia&idN='+idN
		+'&idCont='+idCont
		+'&idL='+idL
		+'&tit='+shTit
		+'&des='+shDes
		+'&res='+shRes
		+'&ini='+shIni
		+'&fi='+shFi
		+'&lloc='+shLloc
		+'&form='+shForm
		+'&idioma='+lang
		+'&link='+shLink);
}



/**Mostra una llista de noticies
 * 
 * @param {Object} idCont
 * @param {Object} idLN
 */
function showGetLliNot(idCont, idL,nIni){
	var sendReq = new sendRequestAjax();
	sendReq.connect (PATH_WEB + '/codi/php/passarela.php' , parseXMLAppendCode,'action=getShowLliNot&idL='+idL+'&idCont='+idCont +'&nIni='+nIni);
}

function showGetEditLliNot(idCont,idLN,idCarp,dIni){
	if(_$('editLliNotWin')){	
		showEditLliNot(idLN,idCarp,dIni);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getEditLliNot&idLN='+idLN+'&idCarp='+idCarp+'&idCont'+idCont+'&dIni'+dIni, parseXMLAppendCode);
	}
}
///**
// * 
// * @param {Object} idA
// * @param {Object} idCont Només serveig per les imatges, no per als documents
// */
//function showArxiu(idA,idCont){
//	if (idCont) {//Mostrem una imatge dins un contenidor
//		_$(idCont).innerHTML ='<img src="'+PATH_WEB + '/codi/gf.php?idA='+idA+'"/>';
//		}
//	else {//mostrem un contingut en un popup
//		myRef = window.open(PATH_WEB + '/codi/gf.php?idA=' + idA, 'ShowFile', 'width=600,height=600,toolbar=no,resizable=yes,location=yes,directories=no,copyhistory=no,scrollbars=yes');
//	}
//} 

function showGetImg(idCont,idA){
	if (idCont) {//Mostrem una imatge dins un contenidor
		_$(idCont).innerHTML ='<img src="codi/gf.php?id='+idA+'"/>';
		}
//	else {//mostrem un contingut en un popup
//		myRef = window.open(PATH_WEB + '/codi/gf.php?idA=' + idA, 'ShowFile', 'width=600,height=600,toolbar=no,resizable=yes,location=yes,directories=no,copyhistory=no,scrollbars=yes');
//	}
} 

/**
 * 
 * @param {Object} type: Not(Noticia) LliNot(llistaNoticies) Arx(Arxiu)
 * @param {Object} id	identificador del element
 * @param {Object} tit ATENCIO: En IE alguns titols poden donar error (amb ; o -1)
 * @param {Object} idCon
 * @param {Object} width
 * @param {Object} height
 */
function showElemNewWin(type, id,tit,idCon,width,height){
	if (!idCon) {idCon=1;}
	if (!width) {width=850;}	
	if (!height) {height=700;}
	if(!tit){tit="ShowWindow"+type+id}
	tit= escape(tit);
	switch(type){
		case 'Arx':
			myRef = window.open(PATH_WEB + '/codi/gf.php?id=' + id+'&tit=' + tit,
			 tit="ShowWindow"+type+id,
			  'width=' + width + ',height=' + height + ',toolbar=yes,resizable=yes,location=yes,scrollbars=yes,directories=no,copyhistory=no');
		break;
		case 'FlashUpload':
			myRef = window.open(PATH_WEB + '/blank.php#'+tit+':' + idCon + ';' + type + ';' + id, 
			"ShowWindow"+type+id,
			'width=' + width + ',height=' + height + ',toolbar=yes,resizable=yes,location=yes,scrollbars=yes,directories=no,copyhistory=no');
		break;
		case 'EditNot':
			myRef = window.open(PATH_WEB + '/blank.php#'+tit+':' + idCon + ';' + type + ';' + id, 
			"Edit Not id:"+id,
			'width=' + width + ',height=' + height + ',toolbar=yes,resizable=yes,location=yes,scrollbars=yes,directories=no,copyhistory=no');
			break;
		default:
			myRef = window.open(PATH_WEB + '/blank.php?!=' + idCon + ';' + type + ';' + id
			+'&tit=' + tit + '', 
			"ShowWindow"+type+id,
			'width=' + width + ',height=' + height + ',toolbar=yes,resizable=yes,location=yes,scrollbars=yes,directories=no,copyhistory=no');
		break;
		
	}
	//myRef = window.open(PATH_WEB + '/blank.php?tit=' + tit + '#' + idCon + ';' + type + ';' + id, tit, 'width=' + width + ',height=' + height + ',toolbar=yes,resizable=yes,location=yes,scrollbars=yes,directories=no,copyhistory=no');
}
/**
 * 
 * @param {Object} idN	id de la noticia que es vol mostrar o -1	Si s'especifica, es busca aquesta noticia
 * @param {Object} idCarp	id de la carpeta en la que guardar la nova noticia o -1	.Si no s'ha especifica idN, es mostra un editor per una nova noticia dins aquesta carpeta
 * @param {Object} idCont	id del contenidor en el que insertar l'editor de noticia o -1( Si s'especifica la primera vegada que es crea, no es recoloca)
 */
function showGetEditNot(idCont,idN,idCarp,idDivNot,shRes){
	if (_$(idDivNotSel)) {
		display(idDivNotSel);
	}
	idDivNotSel = idDivNot || -1;

	if (_$('editNotWin')) {
		//		clkCloseEditNot();
				//Si ja existeix el codi, resituem l'editor
	
		showEditNot(idN, idCarp, '', idCont, shRes);

	}
	else {
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getEditorNoticia&idN=' + idN + '&idC=' + idCarp + '&idCont=' + idCont + '&shRes=' + shRes, parseXMLAppendCode);
	}
	
}

function showGetEditCss(idE,idCont,tab){
	if(_$('editCssWin')){
		showEditCss(idE,tab);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getEditCss&idE='+idE+'&idCont='+idCont+'&tab='+tab, parseXMLAppendCode);
	}
}

function showGetEditImage(idA, idCont){
	if(_$('editImageWin')){
		showEditImage(idA);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getEditImage&idA='+idA+'&idCont='+idCont, parseXMLAppendCode);
	}
}

function showGetFlashUpload(idCont,idC){
	if(_$('flashUploadWin')){
		showFlashUpload(idC);	
	}else{
		var sendReq = new sendRequestAjax();
		sendReq.connect(PATH_WEB + '/codi/php/passarela.php?action=getFlashUpload&idC='+idC+'&idCont='+idCont, parseXMLAppendCode);
	}
}



function addCarga(){
	if(nCargant==0){
		display('ajaxLoader');
		document.body.style.cursor="progress";
	}
	nCargant++;
}
function remCarga(){
	nCargant--;
	 setTimeout(function(){if(nCargant<=0){
		nCargant=0;
		notDisplay('ajaxLoader');
		document.body.style.cursor="";
	}}, 500); 
	
}
function genUrlRec(idR,tip,nom,target){
	var url= new Array();
	nom=escape(nom);
	url[0]='';
	target=target||'_self';
	url[1]=target;
	if (tip.match(/^(image)/)) {
		url[0]='?!='+nom+':1;Img;'+idR;
	}else{
		if (tip == 'not') {
			url[0]='?!='+nom+':1;Not;'+idR;
		}else{
			if(tip=='lliNot'){
				url[0]='?!='+nom+':1;LliNot;'+idR;
			}else{
				url[0]='codi/gf.php?id='+idR+' &tit='+nom;
			}
		}
	}
	return url;
}
//function genTitolRuta(type,titol,id,idCont,rec){
function genTitolRuta(titol,ruta,type,rec){
	try{
		var parent= _$('titolRutaNot').parentNode;
		if (type == 'LliNot') {
			_$('titolRutaNot').innerHTML = '';
			_$('titolRutaArx').innerHTML = '';
		}
		else {//> &#62;
			if (type == 'Not') {
				_$('titolRutaArx').innerHTML = '';
			}else{
				type='Arx';
			}
		}
	}catch(e){}
	try{
//		_$('titolRuta'+type).innerHTML='<span style="font-size:10px;"> &#222; </span><a href="?!='+titol+':'+idCont+';'+type+';'+id+'">'+titol+'</a>';
	_$('titolRuta'+type).innerHTML='<span style="font-size:10px;"> &#222; </span><a href="?!='+ruta+'">'+titol+'</a>';
	}catch(e){
		if (rec != 1) {
			//segurament titolRutaArx no existeix.
			try {
				parent.innerHTML += '<span id="titolRutaArx"></span>';
//				genTitolRuta(type, titol, id, idCont, 1);
				genTitolRuta(titol,ruta,type, 1);
			} 
			catch (e1) {
				
			}
		}
		
	}	
		
}

//EVENT PER CAPTURAR ELS CLIKS ALS LINKS I TRANSFORMARLOS EN CRIDES AJAX
addEvent(window.document,'click', function(e){
 	var ie='0';
 	//cross browser EVENT TARGET
 	 var evt=window.event || e;
	 if (!evt.target) {
	 	ie=1;//IE
		evt.target = evt.srcElement //extend obj with custom e.target prop
	}else{
		var tmpList= evt.currentTarget.childNodes;
		for(k=0; k < tmpList.length; k++){
		}
		
	}
	//obtengo el elemento seleccionado
	var elem = evt.target;
	//busco si tiene algun padre con href (miro un maximo de 5 padres)
	try {
		for (var k = 0; k < 5 && !elem.href; k++) {
			elem = elem.parentNode;
			
		}
	}catch(e){
		return;
	}
	
	//var anch = unescape(elem.href).split('!=');
	var anch = unescape(elem.href).split('!=');


	
	if(anch){
		if(elem.target=='_blank'){
			return;
		}
		//afegim un ? a la url de la pag si no en tenia
		//urlPag=nomPagAct.split('!=')[0].split('?')[0];
		urlPag=nomPagAct.split('?')[0];
		urlPag=urlPag+'?';
		
		
//		_$('colesqsup').innerHTML += " <br>-----<br>flag:"+urlPag.split('!=')[0];
//		_$('colesqsup').innerHTML += " <br>flag: "+anch[0];
		
		if(urlPag.split('!=')[0].indexOf(anch[0], 0)>-1){
			//link dins la mateixa pagina
			if(anch[1]){
				//LINK AJAX
				//var params=anch[1].split(';');
				//comprovem si li hem especificat un titol al link. Sino agafem el text que hem clicat
				var titl=anch[1].split(':');
				if(titl.length>1){
					//li hem passat un titol per url
					titl[0]=titl[0];
					anch[1]=titl.join(':');
				}else{
//					var linkTitol=evt.target.innerHTML;
//					//afegim el titol en l'arrray del link
//					titl.unshift(escape(linkTitol));
//					anch[1]=titl.join(':');
				}
				
				//genTitolRuta(params[1],linkTitol,params[2],params[0]);
				//Evitem que vagin al link
				if(ie==1){	event.returnValue = false;	}	//IE
				else{ evt.preventDefault();}	// Firefox, Safari, Opera



				window.location=nomPagAct.split('#')[0]+"#"+anch[1];
				return(false);	
			}
		}
	}else{
		
	}
}, false);

