/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
		var host = "www.madrid.org";
		
		var pathname = "/cs/Satellite";
		
		var url_readspeaker = "http://" + host + pathname + this._utf8_encode(string).substring(this._utf8_encode(string).indexOf("?"), this._utf8_encode(string).length);
		
        return escape(url_readspeaker);
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

/* pariasfe: encargo seco */
var vWindow = {
	/*
		url:direccion de la pagina
		target:donde queremos abrir la pagina
		w: ancho
		h: alto
		l: posiccion respecto a la izquierda de la ventana
		t: posiccion respecto al top de la ventana
		s: scroll
		tb: toolbar
		mb: menu bar
	*/
	abrir:function(url,target,w,h,l,t,s,tb,mb)
	{
		ventana = window.open (url,target,"width="+w+",height="+h+",left="+l+",top="+t+",scrollbars="+s+",toolbar="+tb+",menubar="+mb);
		ventana.focus();
	}
}

var generar = {
	url:function(qObj,language)
	{
		/*
		//No se visualiza el lector para el idioma rumano
		if (language != "ro")
		{
			//Si existe la clase la visualizamos
			classSpeaker = document.getElementsByClassName("lspeaker");
			for (var i=0;i<classSpeaker.length;i++)
			{
				var objContenedora = classSpeaker[i];
				if (objContenedora != null) { objContenedora.style.display = "block";}
			}
		}
		*/
		url = "http://app.readspeaker.com/cgi-bin/rsent?customerid=4888&lang=es_es&output=template&readid=contenido&url=";
		
		qObj.onclick = function()
		{
			urlPage = Url.encode(document.location.href);
			vWindow.abrir(url+urlPage,'winSpeak',610,425,100,100,'auto','no','no');
			return false;
		}
	}
}

function doPopups() {
		var properties = "left=100,top=100,width=610,height=614,scrollbars=yes,resizable=yes";
		if (!document.getElementsByTagName) {
			  return false;
		}
		var links = document.getElementsByTagName("a");

		for (var i=0; i < links.length; i++) {
		    if(links[i].className.match("popup")) {
			    var enlace = links[i].href;
			    links[i].onclick = function() {
			        window.open(this.href,"Ficha",properties);
			        return false;
           		}
			}
		}
	}

	function doBuscador() {

		if(document.getElementById("buscador1")){
		document.getElementById("buscador1").value = "Buscador";
    		document.getElementById("buscador1").onclick = function() {VaciarBuscador(this);}
		}
		if(document.getElementById("busquedaGoogle")){
    		document.getElementById("busquedaGoogle").onclick = function() {
		 		return validarBuscador(this);
    		}
		}
	}

	// Metodo para contabilizar las estadisticas de los documentos
    function doEstadisticasDocumento() {
      if (!document.getElementsByTagName) return false;
      var links = document.getElementsByTagName("a"); //se comprueba en los enlaces a href
      for (var i=0; i < links.length; i++) {
        if (links[i].className.match("estadisticasDocumento")) { // a aquellos que tengan el estilo estadisticasDocumento
            links[i].onclick = function(){ rs_click(this, document.title); } // que en su onclick ejecuten el metodo rs_click
        }
      }
    }// doEstadisticasDocumento


    window.onload = function() {
       

    		if(document.getElementById("caja_roja")) {
    			ICajaRoja.src = aCajaRoja[cont_rojo][2];
    			intervaloEspera= aCajaRoja[cont_inicial][4];
    			setTimeout("cambio_caja_roja()",intervaloEspera);
    		}

    		if(document.getElementById("caja_roja")) {
    			ICajaOro.src = aCajaOro[cont_oro][2];
    			intervaloEsperaOro= aCajaOro[cont_inicial2][4];
    			setTimeout("cambio_caja_oro()",intervaloEsperaOro);	    			
    		}


			//Declaracion de los iconos de impresion
			//objIconos = document.getElementById("iconos");
			objIconos = document.getElementById("contenedor_iconos");
			if (objIconos != null) { objIconos.style.display = "block";}
			//Objeto de impresion
			objPrint = document.getElementById("print");
			if (objPrint != null)
			{
				objPrint.onclick = function() { 
					window.print(); return false;
				}
				objPrint.onkeypress = objPrint.onclick;
			}

			//Objeto speaker
			aux_objSpeak = null;
			objSpeakES = document.getElementById("speaker_es"); if (objSpeakES != null) { aux_objSpeak = objSpeakES;}
			objSpeakEN = document.getElementById("speaker_en"); if (objSpeakEN != null) { aux_objSpeak = objSpeakEN;}
			objSpeakFR = document.getElementById("speaker_fr"); if (objSpeakFR != null) { aux_objSpeak = objSpeakFR;}
			objSpeakRO = document.getElementById("speaker_ro"); if (objSpeakRO != null) { aux_objSpeak = objSpeakRO;}
			if (aux_objSpeak != null)
				{
				language = aux_objSpeak.id.split("speaker_");
				generar.url(aux_objSpeak,language[1]);
				}
    	
		doBuscador();
		doPopups();
	    // Metodo para la gestion de las estadisticas de documento
        doEstadisticasDocumento();


	//Encargo 73642 (esotoari): Div desplegable en listado
	var listado = document.getElementById("listadoContratos0");
	if (listado != null) {
		
		//oculta todos los listados al cargar la p©na
		document.getElementsByClassName=function(className) {
			var data = [];
			var node=(document.getElementById("listado"))? document.getElementById("listado"):document;
			var tags = (!document.all) ? node.getElementsByTagName("*") : document.all
			for(var i=0;i<tags.length;i++) { if(tags[i].className == className) data[data.length]=tags[i];}
				return data;
		}
		var myObject = document.getElementsByClassName("listadoContratos");
		
		for (var i=0;i<myObject.length;i++){
			var listados = myObject[i];
			if (listados != null) { 
				listados.style.display = 'none';
			}
		}

// = 'url(images/mas.gif)';
		enlace = document.createElement("a");//creamos el enlace de la imagen + para desplegar
		enlace.setAttribute ("href", "#");
		enlace.setAttribute ("id", "idListado0");
		hermano = document.getElementById("enlaceContratos");
		document.getElementById("conListadoContratos").insertBefore(enlace, hermano);//lo colocamos antes del otro enlace
		imagen = document.createElement("img");
		imagen.setAttribute ("src", "StaticFiles/PortalContratacion/img/mas.gif");
		imagen.setAttribute ("alt", "Pinche para expandir");
		enlace.appendChild(imagen);
		document.getElementById("conListadoContratos").style.listStyleImage = 'none';
		document.getElementById("conListadoContratos").style.listStylePosition = 'outside';
		document.getElementById("conListadoContratos").style.listStyleType = 'none';
		imagen.style.marginLeft = '-18px';
		imagen.style.verticalAlign = 'middle';
		if (navigator.userAgent.toLowerCase().indexOf("msie")>-1){ //colocar el + y el - alineado al texto segı'0px';		
		}
		else{
			imagen.style.marginBottom = '2px';		
		}
		
		
		document.getElementById("idListado0").onclick = function() { //Despliega u oculta el div, y cambia el + por el -
			if (document.getElementById("listadoContratos0").style.display == "none") {
				document.getElementById("listadoContratos0").style.display = "block";
				imagen.setAttribute ("src", "StaticFiles/PortalContratacion/img/menos.gif");
				imagen.setAttribute ("alt", "Pinche para contraer");
				document.getElementById("listadoContratos0").innerHTML = '<span class="txt07azu">Cargando...</span>';				
				// LLAMADA AJAX
				depliegaCentrosSMAS(urlpage,cid,tipoServicio,definicion,idOrganismo,idConsejeria,op2,idPagina);
				return false;			
			}
			else {
				document.getElementById("listadoContratos0").style.display = "none";
				imagen.setAttribute ("src", "StaticFiles/PortalContratacion/img/mas.gif");
				imagen.setAttribute ("alt", "Pinche para expandir");				
				return false
			}
		}
		
	}	
	
}
function depliegaCentrosSMAS(urlpage,cid,tipoServicio,definicion,idOrganismo,idConsejeria,op2,idPagina){ 
	var url = "http://"+document.location.host +document.location.pathname+"?pagename=ComunidadMadrid/Comunes/Logica/getCentrosSMAS&urlpage="+urlpage+"&cid="+cid+"&tipoServicio="+tipoServicio+"&definicion="+definicion+"&idOrganismo="+idOrganismo+"&idConsejeria="+idConsejeria+"&segmento=1";
	// LLAMADA AJAX
	httpRequest("POST",url,true);
	return false;
}

// INICIALIZACION DE OBJETO AJAX

/* Funcion para construir un objeto de peticion.
		Parametros: 
			reqType: El tipo de peticion HTTP, como GET o POST
			url: La direccion URL del programa servidor
			asynch: Indica si deseamos enviar una peticion asincrona o no.
*/	
function httpRequest(reqType,url,asynch){
	//Navegadores basados en Mozilla
	if(window.XMLHttpRequest){
		request = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		request = new ActiveXObject("Msxml2.XMLHTTP");
		if(! request){
			request = new ActiveXObject("Microsof.XMLHTTP");
		}
	}
	// la peticion deberia seguir siendo nula si ninguna inicializacion de ActiveXObject
	if(request){
		initReq(reqType,url,asynch);
	} 
	else{
		alert ("El navegador no soporta AJAX");
	}
}
/*
	Inicializa un objeto de peticion que ya se ha construido
	Parametros: 
		reqType: El tipo de peticion HTTP, como GET o POST
		url: La direccion URL del programa servidor
		asynch: Indica si deseamos enviar una peticion asincrona o no.
*/
function initReq(reqType,url,asynch){		
	request.onreadystatechange = handleResponse;
	request.open(reqType,url,asynch);
	request.send(null);
}

// Manejador de evento para XMLHttpRequest
function handleResponse(){	
	try{		
		if(request.readyState == 4){			
			if(request.status == 200){												
				if(request.responseText != null){
					document.getElementById("listadoContratos0").innerHTML = request.responseText;
				}	
			}
		}
	
	}catch(err){
		alert("Error en la funcion handleResponse");
	}

}