// Licencia: http://creativecommons.org/licenses/by-sa/3.0/
// Basado en "Content Syndication with Case-Hardened JavaScript" (http://kentbrewster.com/case-hardened-javascript/) [http://kentbrewster.com/rights-and-permissions]

( function() {

	var idPoder =document.getElementById('poder').value;
	
	var idEntidad =document.getElementById('entidad').value;
	/** cambiar a url de produccion para entrega**/
	//var urlPagina ='http://www.contratacion.euskadi.ejiedes.eus/w32-1084/'
	var urlPagina ='http://www.contratacion.euskadi.eus/w32-1084/'
	/** cambiar a url de produccion para entrega**/
	var urlAplicacion = '/v79aWar/comunJSP/v79aWidgetAnuncios.do?';
	var idioma = document.getElementById('idioma').value;
	
	var nombreOfuscado = '';
	for (var i = 0; i < 16; i++) {
		nombreOfuscado += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
	}
	window[nombreOfuscado] = {};
	var $ = window[nombreOfuscado];
	
	$.f = function() {
		
		return {	
			/**
				URLs de acceso a las licitaciones
				la parte _at / _ul .... de la URL es al que indica que tipo de información se va a mostrar
				Extensión at:	devuelve alertas tempranas
				Extensión ul:	devuelve últimas licitaciones
				Extensión tl:	devuelve todas las licitaciones
				Extensión ap:	devuelve anuncios previos
				Extensión aa:	devuelve anuncios abiertos
				Extensión ae: 	devuelve anuncios en estudio
				Extensión sr:	devuelve suspensiones por recurso
				Extensión aj:	devuelve adjudicaciones
				Extensión de:	devuelve desistimientos
				Extensión ds:	devuelve desiertos
				Extensión bp:	devuelve búsqueda personalizada por entidad, en este caso con p04=81 (entidad URA)
				Extensión fc:	devueve formalizaciones del contrato
				Extensión ba:	devuelve los anuncios por entidad, en este caso con p04=81 (entidad URA)
				Extensión hi:	devuelve históricos
			**/
			
			
			URL_datos_at :  'p01=AT&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_ul :  'p01=&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=novedades&R01HNoPortal=true',
			URL_datos_tl :  'p01=AL&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=licitaciones&p23='+idPoder+'&R01HNoPortal=true',
			URL_datos_ap :  'p01=AP&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_aa :  'p01=AL&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_ae :  'p01=AC&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_aj :  'p01=AD&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_de :  'p01=DE&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_ds :  'p01=DS&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_bp :  'p01=&p02=1&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=novedades&p23='+idPoder+'&R01HNoPortal=true',
			URL_datos_ba :  'p01=&p02=1&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=busquedaPersonalizada&p23=&R01HNoPortal=true',
			URL_datos_fc :  'p01=FO&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_hi :  'p01=HI&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=18%2F05%2F2011&p14=&p15=17%2F06%2F2011&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			URL_datos_sr :  'p01=SR&p02=&p03='+idPoder+'&p04='+idEntidad+'&p05=&p06=&p07=&p08=&p09=&p10=&p11=&p12=&p13=&p14=&p15=&p16=&p17=AMPLIADO&p18=false&p19=false&p20=false&p21='+idioma+'&p22=ultimos30dias&p23=&R01HNoPortal=true',
			
			runFunction : [],
			init : function(target) {
				var theScripts = document.getElementsByTagName('SCRIPT');
				for (var i = 0; i < theScripts.length; i++) {
					
					if (theScripts[i].src.indexOf("v79aPerfilContratante.js") != -1) {
						$.a = {};
						if (theScripts[i].innerHTML) {
							
							$.a = $.f.parseJson(theScripts[i].innerHTML);
						}
						if ($.a.err) {
							alert($.f.traducir('param_mal'));//bad json!
						}
						
						$.f.cargarVariables();
						$.f.crearEstructuraGeneral();
						
						break;
					}
				}
				
			},
			parseJson : function(json) {
					
				this.parseJson.data = json;
				if ( typeof json !== 'string') {
					return {"err":"Parametrización del widget mal formada."};//trying to parse a non-string JSON object
				}
				try {
					var f = Function(['var document,top,self,window,parent,Number,Date,Object,Function,',
						'Array,String,Math,RegExp,Image,ActiveXObject;',
						'return (' , json.replace(/<\!--.+-->/gim,'').replace(/\bfunction\b/g,'function&shy;') , ');'].join(''));
					return f();
				} catch (e) {
					return {"err":"ERROR parametrizando"};//trouble parsing JSON object
				}
			},
			crearPresentacion : function () {
				
				var ns = document.createElement('style');
				document.getElementsByTagName('head')[0].appendChild(ns);
				if (!window.createPopup) {
					ns.appendChild(document.createTextNode(''));
					ns.setAttribute("type", "text/css");
				}
				var s = document.styleSheets[document.styleSheets.length - 1];
				var ieRules = "";
				for (r in $.css) {
					var selector = '.' + nombreOfuscado + ' ' + r;
					if (!window.createPopup) {
						var theRule = document.createTextNode(selector + $.css[r]);
						ns.appendChild(theRule);
					} else {
						ieRules += selector + $.css[r];
					}
				}
				if (window.createPopup) { s.cssText = ieRules; }
				
			},
			cargarJSON : function() {
				
				var inf = $.a.tipoInformacion;
				
	
				eval ('var urlXML = $.f.URL_datos_'+inf);	
				
				if (inf == "ul")	
				{
					urlXML = urlXML + '&p23=' +$.a.poder;
				}
				
				
				if (!$.f.runFunction) { 			
					$.f.runFunction = [];
				}
					
		
				var url = urlPagina + $.a.idioma+ urlAplicacion +urlXML+'&callback=?';
				
				cargarAnuncios(url, "jswidget",$.w,$.a);
				//var capaResultado = document.getElementById("jswidget");
				//capaResultado.appendChild(capaResultado);

			},
			borrarElemento : function(id) {
				
				if (document.getElementById(id)) {
					var s = document.getElementById(id);
					s.parentNode.removeChild(s);
				}
			},
			cargarVariables : function() {
				$.d = {
					"idioma" : document.getElementById('idioma').value,
					"titulo" : document.getElementById('titulo').value,
					"poder" : document.getElementById('poder').value,
					"tipoInformacion" : document.getElementById('tipoInformacion').value,
					"entidad" : document.getElementById('entidad').value
					};
				for (var k in $.d) { if ($.a[k] === undefined) { $.a[k] = $.d[k]; } }
			},

			crearEstructuraGeneral : function() {
				$.f.borrarElemento("perfil");
				$.w = document.createElement('div');
				$.w.id = "perfil";
				$.f.cargarJSON();									
			},
			
			
			cortar_cadena: function (txt,numLetras) {
				palabras = txt.split(' ');
				texto_acortado = '';
				i=0;
				tot=0;
				while (tot + palabras[i].length <= numLetras) {
					texto_acortado += palabras[i] + ' ';
					tot += palabras[i].length;
					i++;
					if (i > palabras.length-1) break;
				}
				if (txt.length > numLetras) return texto_acortado+'[...]';
				else return texto_acortado;
			},
			traducir: function (cadena) {
				if ($.a.idioma=='eu') {
					return $.traducciones_eu[cadena];
				} else {
					return $.traducciones_es[cadena];
				}
			}
			
		};
	}();
	var thisScript = /^v79aPerfilContratante.js$/;
	
	
	if ((document.getElementById('probar')) && (document.getElementById('actualizar'))) {
		h1 = function() { $.f.init(thisScript); };
		if(typeof window.addEventListener !== 'undefined') {
			document.getElementById('probar').addEventListener('click', h1, false);
			document.getElementById('actualizar').click();
			document.getElementById('probar').removeEventListener('click', h1 ,false);
		} else if(typeof window.attachEvent !== 'undefined') {
			document.getElementById('probar').attachEvent('onclick', h1);
			document.getElementById('actualizar').click();
			document.getElementById('probar').onclick=null;
			document.getElementById('probar').detachEvent('onclick', h1);
		}
	}
	
	
 })();

	function cargarAnuncios(url, id, window,literales){
		$.ajax({ 
			url: url,
			type: "GET",
			dataType: "jsonp",
			async: false,
			jsonpCallback: 'processResponse',
			contentType: "application/json;charset=utf-8",
			success: function( html, status, xhr ) {
				pintarTabla(html,window, literales);			
			},
			error: function (xhr, ajaxOptions, thrownError) {
				alert("error " + thrownError);
			}
		});
	}

	function pintarTabla (r,window, literales) {
					
		var tit = document.createElement('h4');
		tit.innerHTML = literales.titulo;
		window.appendChild(tit);
					
		var tabla1 = document.createElement('table');
		tabla1.id = "tablaWidget";
		var cuerpo = document.createElement('tbody');
		var filaCabecera    = document.createElement('tr');
		var columnaCabecera2 = document.createElement('th');
		var columnaCabecera3 = document.createElement('th');
					
		var idioma = literales.idioma;
										
		if (idioma == "es")
		{
			columnaCabecera2.innerHTML = 'T\u00EDtulo';
			columnaCabecera3.innerHTML = 'Fecha Publicaci\u00F3n';
		}
		else
		{
			columnaCabecera2.innerHTML = 'Izenburua';
			columnaCabecera3.innerHTML = 'Argitalpenaren Data';					
		}
		filaCabecera.appendChild(columnaCabecera2);
		filaCabecera.appendChild(columnaCabecera3);
		cuerpo.appendChild(filaCabecera);
																
		if (r.length==0 ){
													
			var m = document.createElement('dl');
			window.appendChild(m);
			h = document.createElement('dt');												
			sub = document.createElement('dd');
											
			if (idioma == "es")
			{							
				sub.innerHTML = "No se ha encontrado nada que mostrar";
			}else
			{
				sub.innerHTML = "Ez da aurkitu ezer erakusteko";
			}
												
			h.appendChild(sub);
			m.appendChild(h);
						
		}else{
			for (var i = 0; i < r.length; i++) {												
				var fila1 = document.createElement('tr');					
				var columna2 = document.createElement('td');
				var a2 = document.createElement('A');
				var link = r[i].link;
				var link_final = link.replace("//contenidos","/"+idioma+"/contenidos");
				a2.href = link_final;
				a2.target = '_blank';
				a2.innerHTML = r[i].titulo + "  ";						
				columna2.appendChild(a2);
							
				var columna3 = document.createElement('td');
				var fechadato = "";						
							
				if (idioma == "es")
				{
					fechadato = formatearFecha_es(r[i].pubDate.substring(0,r[i].pubDate.indexOf("00")));
				} else {
					fechadato = formatearFecha_eu(r[i].pubDate.substring(0,r[i].pubDate.indexOf("00")));
				}
							
				columna3.innerHTML = fechadato;
				
				if (i % 2 != 0) {
					fila1.className = "impar"
				} else {
					fila1.className = "par"
				}
				
				fila1.appendChild(columna2);
				fila1.appendChild(columna3);
				cuerpo.appendChild(fila1);											
			}
					
			tabla1.appendChild(cuerpo);
			window.appendChild(tabla1);
		}
							
		var tabla = document.createElement('table');
		tabla.id = "tablaImagen";
		var cuerpo2 = document.createElement('tbody');
		var fila = document.createElement('tr');
		var columna1 = document.createElement('td');
		// var columna2 = document.createElement('td');
		var imagen = document.createElement('img');
		
		var a1 = document.createElement('A');
					
		a1.href = "http://www.contratacion.euskadi.eus/w32-home/"+literales.idioma;
		a1.target = '_blank';
					
		imagen.src = '/documents/70490/105625/w32-logo_contratacion.jpg/0c325ae4-1cea-4896-8d1e-080bda6d9404?t=1440416473000';
		a1.appendChild(imagen);
		columna1.innerHTML = '';
        columna1.style.align = 'right';
		// columna1.style.width = '82%';
		// columna1.style.border='none';
		// columna1.style.background= '#ffffff';
		// columna2.style.width = '18%';
		// columna2.style.border='none';
		// columna2.style.align = 'right';
		// columna2.style.background= '#ffffff';
									
					
		columna1.appendChild(a1);
		fila.appendChild(columna1);
		// fila.appendChild(columna2);
		cuerpo2.appendChild(fila);
		tabla.appendChild(cuerpo2);
		window.appendChild(tabla);
		elemento2 = document.getElementById('jswidget');
		elemento2.appendChild(window);												
	}
