var total_pagines = 0;
var pag_actual = 1;

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function displayLoading(element) {
	while(element.hasChildNodes()) {
		element.removeChild(element.lastChild);
	}
	var image = document.createElement('img');
	image.setAttribute('src', '../imatges/vinyetes/loading.gif');
	image.setAttribute('alt', 'Loading...');
	image.setAttribute('id', 'img_loading');
	element.appendChild(image);
}

function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

function ultimesNoticies() {
	pillaNoticies(1); //obté les primeres notícies que es mostraran en la pŕgina
}

function pillaNoticies(pagina) {
  var request = getHTTPObject();
  if (request) {
	  displayLoading(document.getElementById('leftPan'));
    request.onreadystatechange = function() {
    	parseResponse(request);
  	};
	var query_str = 'lang='+lang+'&pagina='+pag_actual;
    request.open("POST", '../scripts/php/ajax/noticies_xml.php');
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(query_str);
  }
}

function parseResponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      var leftPan = document.getElementById('leftPan');
	  buidaNode(leftPan);
	  leftPan.appendChild(creaElement('div', 'horitzontal', ''));
      insertaNoticies(request.responseXML);
    }
  }
}

function buidaNode(node) {
	while(node.hasChildNodes()) {
		node.removeChild(node.lastChild);
	}
}

function creaElement(tag, classe, id) {
	var element = document.createElement(tag);
	if(classe!='') {
		element.className = classe;
	}
	if(id!='') {
		element.setAttribute('id', id);
	}
	return element;
}

function insertaNoticies(xml) {
	var leftPan = document.getElementById('leftPan');
	var root = xml.getElementsByTagName('resultats')[0];
	total_pagines = root.getAttribute('n_pagines');
	var noticies = root.getElementsByTagName('noticia');
	for(var i=0; i<noticies.length; i++) {
		var noticia = noticies[i];
		var html_noticia = generaHtmlNoticia(noticia);
		leftPan.appendChild(html_noticia);
	}
	var div_pag = paginacio();
	leftPan.appendChild(div_pag);
}

function generaHtmlNoticia(nodo_not) {
	var fecha = nodo_not.getAttribute('fecha');
	var imatge = nodo_not.getAttribute('imatge');
	var titol = nodo_not.firstChild.firstChild.nodeValue;
	var texto_not = nodo_not.lastChild.firstChild.nodeValue;
	var nodo = creaElement('div', 'noticia', '');
	var cont_foto = creaElement('div', 'foto', '');
	var foto = creaElement('img', '', '');
	foto.setAttribute('src', imatge);
	foto.setAttribute('alt', titol);
	cont_foto.appendChild(foto);
	nodo.appendChild(cont_foto);
	var h1 = creaElement('h1', '', '');
	var txt_h1 = document.createTextNode(titol);
	h1.appendChild(txt_h1);
	var span_fecha = creaElement('span', 'fecha', '');
	span_fecha.appendChild(document.createTextNode(fecha));
	h1.appendChild(span_fecha);
	nodo.appendChild(h1);
	var div_cos = creaElement('div', 'cont_cos');
	nodo.appendChild(div_cos);
	div_cos.innerHTML = texto_not;
	
	return nodo;
}

function paginacio() {
	var div = creaElement('div', '', 'paginacio');
	if(pag_actual!=1) {
		var a_anterior = creaElement('a', '', 'pag_anterior');
		a_anterior.setAttribute('href', '#');
		var txt_anterior = document.createTextNode('&lt;&lt;');
		a_anterior.appendChild(txt_anterior);
		a_anterior.onclick = function() {
			pag_actual -= 1;
			pillaNoticies(pag_actual);
			return false;
		}
		div.appendChild(a_anterior);
	}
	if(pag_actual!=total_pagines) {
		var a_siguiente = creaElement('a', '', 'pag_siguiente');
		a_siguiente.setAttribute('href', '#');
		var txt_siguiente = document.createTextNode('&gt;&gt;');
		a_siguiente.appendChild(txt_siguiente);
		a_siguiente.onclick = function() {
			pag_actual += 1;
			pillaNoticies(pag_actual);
			return false;
		}
		div.appendChild(a_siguiente);
	}
	var p = creaElement('p', '', '');
	var txt_p = document.createTextNode(pag_actual+' / '+total_pagines);
	p.appendChild(txt_p);
	div.appendChild(p);
	return div;
}

function inicialitza_formulari_subscripcio() {
	var boto_submit = document.getElementById('submit');
	boto_submit.onclick = function() {
		var ok = true;
		var nom = document.getElementById('nom');
		var empresa = document.getElementById('empresa');
		var telefono = document.getElementById('telefono');
		var poblacion = document.getElementById('poblacion');
		var email = document.getElementById('email');
		var imatge_proteccio = document.getElementById('imatge_proteccio');
		//var proteccio = document.getElementById('proteccio');
		if(nom.value=='') {
			nom.className = 'no_complet';
			ok = false;
		} else {
			nom.className = '';
		}
		if(empresa.value=='') {
			empresa.className = 'no_complet';
			ok = false;
		} else {
			empresa.className = '';
		}
		if(telefono.value=='') {
			telefono.className = 'no_complet';
			ok = false;
		} else {
			telefono.className = '';
		}
		if(poblacion.value=='') {
			poblacion.className = 'no_complet';
			ok = false;
		} else {
			poblacion.className = '';
		}
		if(email.value=='') {
			email.className = 'no_complet';
			ok = false;
		} else {
			email.className = '';
		}
		if(imatge_proteccio.value=='') {
			imatge_proteccio.className = 'no_complet';
			ok = false;
		} else {
			imatge_proteccio.className = '';
		}
		if(!ok) {
			var missatge = (lang=='es')?'Algunos de los campos requeridos están incompletos':'Some of the required fields are incomplete.';
			alert(missatge);
		} else {
			envia_formulari_subscripcio(document.forms[0]);
		}
		return false;
	}
}

function envia_formulari_subscripcio(form) {
	var request = getHTTPObject();
	if (request) {
		mostra_progres(document.getElementById('contenidos'));
    	request.onreadystatechange = function() {
			if (request.readyState == 4) {
    			if (request.status == 200 || request.status == 304) {
				document.getElementById('contenidos').removeChild(document.getElementById('capa_sending'));
      			informa_ok(request);
   			 }
  			}
    	};
		var query_str = conforma_query_string_subscripcio(form);
    	request.open("POST", 'http://www.etiquetasvinalopo.com/scripts/php/ajax/procesar_subscripcion.php', true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	request.send(query_str);
  	}
}

function informa_ok(req) {
	var missatge = req.responseText;
	var contenidor_missatge = document.getElementById('missatge_ok_error');
	contenidor_missatge.innerHTML = missatge;
}

function conforma_query_string_subscripcio(form) {
	var nom = document.getElementById('nom').value;
	var empresa = (document.getElementById('empresa').value=='')?'-':document.getElementById('empresa').value;
	var poblacion = (document.getElementById('poblacion').value=='')?'-':document.getElementById('poblacion').value;
	var telefono = (document.getElementById('telefono').value=='')?'-':document.getElementById('telefono').value;
	var email = document.getElementById('email').value;
	var imatge_proteccio = document.getElementById('imatge_proteccio').value;
	var id_llista = document.getElementById('id_llista').value;
	var query = 'nom='+nom+'&empresa='+empresa+'&poblacion='+poblacion+'&telefono='+telefono+'&email='+email+'&imatge_proteccio='+imatge_proteccio+'&id_llista='+id_llista;
	return query;
}

function mostra_progres(contenidor) {
	var div = document.createElement('div');
	div.setAttribute('id', 'capa_sending');
	var image = document.createElement('img');
	image.setAttribute('src', '../imatges/vinyetes/img_sending2.gif');
	image.setAttribute('alt', 'Sending...');
	image.setAttribute('id', 'img_sending');
	div.appendChild(image);
	contenidor.appendChild(div);
}