var obj_xml_noticia, obj_xml_imatge;

function ltrim(cadena)
{
	while (cadena.charAt(0) == ' ') cadena = cadena.substr(1, cadena.length - 1);
  return cadena;
}

function rtrim(cadena)
{
	while (cadena.charAt(cadena.length - 1) == ' ') cadena = cadena.substr(0, cadena.length - 1);
	return cadena;
}

function trim(cadena)
{
	return rtrim(ltrim(cadena));
}

function obtenir_element(id)
{
	if(document.all)
  {
  	return document.all[id];
  }
  else if(document.layers)
  {
  	return document.layers[id];
  }
  else if(document.getElementById)
  {
  	return	document.getElementById(id);
  }
}

function obtenir_obj_xml()
{ 
  var obj_xml = null;
  try
  {
  	obj_xml = new XMLHttpRequest();
  }
  catch (e)
  {
  	try
  	{
  		obj_xml = new ActiveXObject("Msxml2.XMLHTTP");
  	}
    catch (e)
    {
    	obj_xml = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  
  return obj_xml;
}

function comprovar_data(data)
{
	if(data.length > 10) return false;

	// Obtenim parts de la data.
	var reg = new RegExp("/");
	var vect = data.split(reg);
	//var avui = new Date();
	//var any_actual = avui.getYear();
	//var mes_actual = avui.getMonth();
	//var dia_actual = avui.getDay();

	var any, dia, mes;

	// Dia +  Mes + Any
	if(vect.length == 3) {
		
		// Dia 2 digits, Mes 2 digits i any 4 digits
		if(vect[0].length != 2) return false;
		if(vect[1].length != 2) return false;
		if(vect[2].length != 4) return false;

		// Comprovem que siguin numerics
		dia = vect[0] * 1;
		mes = vect[1] * 1;
		any = vect[2] * 1;

		if(isNaN(dia) || isNaN(mes) || isNaN(any)) return false;

		// Mes i any dins els rangs permesos
		if(any < 1900 || any > 9999) return false;
		if(mes < 1 || mes > 12) return false;

		// Si no es febrer considerem 31 dies
		if(mes != 2)
		{
			if(dia < 1 || dia > 31) return false;
		}
		// Si no 29
		else
		{
			if(dia < 1 || dia > 29) return false;
		}

		//if(any > any_actual) return true;
		//else if(any == any_actual && mes > mes_actual) return true;
		//else if(any == any_actual && mes == mes_actual && dia >= dia_actual) return true;
		return true;
	}
	
	return false;
}

function comprovar_mail(text)
{
	var mailres = true;
	var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
	var arroba = text.indexOf("@",0);
  var punto = text.lastIndexOf(".");
	
  if ((text.lastIndexOf("@")) != arroba) arroba = -1;

	for (var contador = 0 ; contador < text.length ; contador++)
	{
		if (cadena.indexOf(text.substr(contador, 1),0) == -1)
		{
			mailres = false;
			break; 
   	} 
  }

  if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (text.length)) && (mailres == true) && (text.indexOf("..",0) == -1)) mailres = true;
  else mailres = false;
  
  return mailres;
}

function posicionar_contingut_centre()
{
	var objecte = obtenir_element('capa_centrat');
	
	if(objecte)
	{	
		var amplada_objecte = objecte.offsetWidth ? objecte.offsetWidth : objecte.style.width ? parseInt(objecte.style.width) : 0;
		var alcada_objecte = objecte.offsetHeight ? objecte.offsetHeight :  objecte.style.height ? parseInt(objecte.style.height) : 0;
			
		var coordenada_x = (amplada_visualitzacio() - amplada_objecte) / 2;
		var coordenada_y = (alcada_visualitzacio() - alcada_objecte) / 2;
			
		if(coordenada_x < 0) coordenada_x = 0;
		if(coordenada_y < 0) coordenada_y = 0;
			
		objecte.style.left = coordenada_x + 'px';
		objecte.style.top = coordenada_y + 'px';		
	}
}

function amplada_visualitzacio()
{
	var amplada = 0;
	
	if(document.documentElement && document.documentElement.clientWidth) amplada = document.documentElement.clientWidth;
	else if(document.body && document.body.clientWidth)	amplada = document.body.clientWidth;
	else if(window.innerWidth) amplada = window.innerWidth - 18;

	return amplada;
}

function alcada_visualitzacio()
{
	var alcada = 0;
	
	if(document.documentElement && document.documentElement.clientHeight) alcada = document.documentElement.clientHeight;
	else if(document.body && document.body.clientHeight) alcada = document.body.clientHeight;
	else if(window.innerHeight) alcada = window.innerHeight - 18;
		
	return alcada;
}

function posicio_scroll()
{
  var posicio = 0;

  if(document.documentElement && document.documentElement.scrollTop) posicio = document.documentElement.scrollTop;
  else if(document.body && esta_definit(document.body.scrollTop)) posicio = document.body.scrollTop;
  else
  {
  	if(es_numeric(obtenir_element(capa_actual).scrollTop)) posicio = 0;
  }
  	
  return posicio;
}

function es_numeric(n)
{
  for(var i = 0; i < arguments.length; i++)
  {
  	if(typeof(arguments[i]) != 'number') return false;
  }
  return true;
}

function esta_definit()
{
  for(var i = 0; i < arguments.length; i++)
  {
  	if(typeof(arguments[i]) == 'undefined') return false;
  }
  return true;
}

function posicionar_centre_pantalla(nom_objecte, desviacio_horitzontal, desviacio_vertical)
{
	var objecte = obtenir_element(nom_objecte);
	var capa_centrat = obtenir_element('capa_centrat');
	
	if(objecte)
	{	
		var amplada_objecte = objecte.offsetWidth ? objecte.offsetWidth : objecte.style.width ? parseInt(objecte.style.width) : 0;
		var alcada_objecte = objecte.offsetHeight ? objecte.offsetHeight :  objecte.style.height ? parseInt(objecte.style.height) : 0;
		var amplada_capa_centrat = capa_centrat.offsetWidth ? capa_centrat.offsetWidth : capa_centrat.style.width ? parseInt(capa_centrat.style.width) : 0;
		var alcada_capa_centrat = capa_centrat.offsetHeight ? capa_centrat.offsetHeight :  capa_centrat.style.height ? parseInt(capa_centrat.style.height) : 0;
		
		var coordenada_x = (amplada_capa_centrat - amplada_objecte) / 2 - desviacio_horitzontal;
		var coordenada_y = (alcada_capa_centrat - alcada_objecte) / 2 - desviacio_vertical + posicio_scroll();
			
		if(coordenada_x < 0) coordenada_x = 0;
		if(coordenada_y < 0) coordenada_y = 15;
			
		objecte.style.left = coordenada_x + 'px';
		objecte.style.top = coordenada_y + 'px';
	}
}

function mida(opcio)
{
	if(opcio == 'petit')
	{
		obtenir_element('capa_centrat').style.fontSize = '85%';
		obtenir_element('enllac_mida_petit').style.fontWeight = 'bold';
		obtenir_element('enllac_mida_normal').style.fontWeight = 'normal';
		obtenir_element('enllac_mida_gran').style.fontWeight = 'normal';
	}
	else if(opcio == 'normal')
	{
		obtenir_element('capa_centrat').style.fontSize = '100%';
		obtenir_element('enllac_mida_petit').style.fontWeight = 'normal';
		obtenir_element('enllac_mida_normal').style.fontWeight = 'bold';
		obtenir_element('enllac_mida_gran').style.fontWeight = 'normal';
	}
	else if(opcio == 'gran')
	{
		obtenir_element('capa_centrat').style.fontSize = '115%';
		obtenir_element('enllac_mida_petit').style.fontWeight = 'normal';
		obtenir_element('enllac_mida_normal').style.fontWeight = 'normal';
		obtenir_element('enllac_mida_gran').style.fontWeight = 'bold';
	}
}

function seleccionar(fila, color)
{
	obtenir_element('taula_menu_principal').rows[fila].cells[0].style.backgroundColor = color;
}

function deseleccionar(fila, color)
{
	obtenir_element('taula_menu_principal').rows[fila].cells[0].style.backgroundColor = color;
}

function imatge_cercador()
{ 
	var f = obtenir_element('Cercador');
	if (f && f.Text_cerca)
	{ 
		var q = f.Text_cerca;
		var n = navigator;
		var l = location;
		if (n.platform == 'Win32') q.style.cssText = 'border: 1px solid #545454; color: #000000;';
		var b = function() 
		{ 
			if (q.value == '') q.style.background = '#FFFFFF url(http:\x2F\x2Fwww.google.com\x2Fcoop\x2Fintl\x2Fen\x2Fimages\x2Fgoogle_custom_search_watermark.gif) left no-repeat'; 
		}; 
		var f = function() 
		{ 
			q.style.background = '#FFFFFF'; 
		}; 
		q.onfocus = f; 
		q.onblur = b; 
		if(q.value == '') b();
	}
}

function obrir_finestra_tamany(enllac, amplada, alcada)
{
	var res = window.open(enllac, '', 'scrollbars=yes,resizable=yes,width=' + amplada + ',height=' + alcada);
}

function canviar_imatge_noticies(imatge, titol_imatge)
{
	var cella;
	var sortida = '';
	
	cella = obtenir_element('cella_imatge_noticies');
	sortida = '<img src="../../arxius/noticies/' + imatge + '" alt="' + titol_imatge + '" title="' + titol_imatge + '" border="0"><br>';
	sortida = sortida + '<img src="../../imatges/pixel_transparent.gif" alt="" border="0" width="1" height="3"><br>';
	sortida = sortida + titol_imatge;
	cella.innerHTML = sortida;
}

function mostrar_carregant(idioma)
{
	if(idioma == "Català") obtenir_element('capa_visualitzacio').innerHTML = '<img src="../../imatges/carregant.gif" alt="Carregant" title="Carregant" border="0">';
	else if(idioma == "Castellà") obtenir_element('capa_visualitzacio').innerHTML = '<img src="../../imatges/carregant.gif" alt="Cargando" title="Cargando" border="0">';
	else obtenir_element('capa_visualitzacio').innerHTML = '<img src="../../imatges/carregant.gif" alt="Loading" title="Loading" border="0">';
	obtenir_element('capa_visualitzacio').style.padding = '20px';
	obtenir_element('capa_fons_visualitzacio').style.display = 'block';
	obtenir_element('capa_visualitzacio').style.display = 'block';
	posicionar_centre_pantalla('capa_visualitzacio', 0, 0);
}

function tancar_carregant()
{
	obtenir_element('capa_visualitzacio').style.display = 'none';
	obtenir_element('capa_visualitzacio').innerHTML = '';
	obtenir_element('capa_visualitzacio').style.padding = '10px';
}

function mostrar_noticia(id, idioma)
{	
	obj_xml_noticia = obtenir_obj_xml();
	if(obj_xml_noticia == null)
	{
		alert('El teu navegador no suporta AJAX.');
		return;
	}
	
	mostrar_carregant(idioma);
	
	obj_xml_noticia.onreadystatechange = canvi_estat_mostrar_noticia;
	obj_xml_noticia.open('POST', '../../comuns/obtenir_noticia.php', true);
	obj_xml_noticia.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	obj_xml_noticia.setRequestHeader('Charset', 'ISO-8859-1');
	obj_xml_noticia.send('Id=' + id + '&Idioma=' + escape(idioma));
}

function canvi_estat_mostrar_noticia()
{ 
	var doc_xml;
	var titol, text, enllac, titol_imatge, imatge, idioma;
	var sortida;
	
	if(obj_xml_noticia.readyState == 4 || obj_xml_noticia.readyState == 'complete')
	{
		var doc_xml = obj_xml_noticia.responseXML.documentElement;
		titol = doc_xml.getElementsByTagName('titol')[0].childNodes[0].nodeValue;
		text = doc_xml.getElementsByTagName('text')[0].childNodes[0].nodeValue;
		enllac = doc_xml.getElementsByTagName('enllac')[0].childNodes[0].nodeValue;
		titol_imatge = doc_xml.getElementsByTagName('titol_imatge')[0].childNodes[0].nodeValue;
		imatge = doc_xml.getElementsByTagName('imatge')[0].childNodes[0].nodeValue;
		idioma = doc_xml.getElementsByTagName('idioma')[0].childNodes[0].nodeValue;

		tancar_carregant();
		
		sortida =	'<table cellpadding="0" cellspacing="0" border="0" width="500">\n';
		sortida = sortida + '<tr>\n';
		sortida = sortida + '<td align="left" valign="top">\n';
		if(imatge != '-')
		{
			sortida = sortida + '<div id="imatge">\n';
			sortida = sortida + '<img src="../../arxius/noticies/' + imatge + '" alt="' + titol_imatge + '" title="' + titol_imatge + '" border="0" class="contorn_negre"><br>';
			sortida = sortida + titol_imatge;
			sortida = sortida + '<\/div>';
		}
		if(enllac == '-') sortida = sortida + '<b>' + titol + '</b><br>' + text + '\n';
		else sortida = sortida + '<a href="' + enllac + '" target="_blank"><b>' + titol + '</b></a><br>' + text + '\n';
		sortida = sortida + '<\/td>\n';
		sortida = sortida + '<\/tr>\n';
		sortida = sortida + '<tr>\n';
		if(idioma == 'Català') sortida = sortida + '<td align="right"><a href="javascript: tancar();"><img src="../../imatges/tancar.png" alt="Tancar" title="Tancar" border="0"><\/a><\/td>\n';
		else if(idioma == 'Castellà') sortida = sortida + '<td align="right"><a href="javascript: tancar();"><img src="../../imatges/tancar.png" alt="Cerrar" title="Cerrar" border="0"><\/a><\/td>\n';
		else sortida = sortida + '<td align="center"><a href="javascript: tancar();"><img src="../../imatges/tancar.png" alt="Close" title="Close" border="0"><\/a><\/td>\n';
		sortida = sortida + '<\/tr>\n';
		sortida = sortida + '<\/table>';
		
		obtenir_element('capa_visualitzacio').innerHTML = sortida;
		obtenir_element('capa_visualitzacio').style.display = 'block';		
		posicionar_centre_pantalla('capa_visualitzacio', 0, 0);
	}
}

function tancar()
{
	obtenir_element('capa_fons_visualitzacio').style.display = 'none';
	obtenir_element('capa_visualitzacio').style.display = 'none';
	obtenir_element('capa_visualitzacio').innerHTML = '';
}

function afegir_producte(str_opcions_select)
{
	var ultima_final, nova_fila, columna, num_productes, classe;
	
	num_productes = document.Comanda.Num_productes.value * 1;
	num_productes++;
	classe = (num_productes - 1) % 2;
	
  nova_fila = document.createElement('TR');
  nova_fila.id = 'Fila_producte_' + num_productes;
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'left';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<select name="Id_producte_format_' + num_productes + '" size="1" onchange="javascript: seleccionar_producte(' + num_productes + ');" onblur="javascript: seleccionar_producte(' + num_productes + ');">\n<option value="" selected>-- Selecciona un producte --</option>\n' + str_opcions_select + '</select>';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<img src="../../imatges/pixel_transparent.gif" alt="" border="0" width="1" height="1">';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.id = 'Cella_preu_producte_' + num_productes;
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '0.00 €';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<img src="../../imatges/pixel_transparent.gif" alt="" border="0" width="1" height="1">';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<input type="text" name="Quantitat_' + num_productes + '" value="0" size="4" onkeyup="javascript: comprovar_calcular(this);" onblur="javascript: comprovar_calcular(this);">';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<img src="../../imatges/pixel_transparent.gif" alt="" border="0" width="1" height="1">';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'right';
  columna.id = 'Cella_import_producte_' + num_productes;
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '0.00 €';
  columna = document.createElement('TD');
  nova_fila.appendChild(columna);
  columna.align = 'center';
  columna.className = 'cella_dades_' + classe;
  columna.innerHTML = '<img src="../../imatges/pixel_transparent.gif" alt="" border="0" width="1" height="1">';
  
	ultima_fila = obtenir_element('Fila_producte_' + (num_productes - 1));
  ultima_fila.parentNode.insertBefore(nova_fila, ultima_fila.nextSibling);
  
  document.Comanda.Num_productes.value = num_productes;
}

function treure_producte(id_format_producte)
{
	var taula, fila, num_productes;
	
	if(id_format_producte != '')
	{
		var obj_xml_aux = obtenir_obj_xml();
		if(obj_xml_aux == null)
		{
			alert('El teu navegador no suporta AJAX.');
			return;
		}
		
		obj_xml_aux.open('POST', '../../comuns/eliminar_producte.php', true);
		obj_xml_aux.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		obj_xml_aux.setRequestHeader('Charset', 'ISO-8859-1');
		obj_xml_aux.send('Id=' + id_format_producte);		
	}
	
	num_productes = document.Comanda.Num_productes.value * 1;
	
	if(num_productes > 1)
	{
		taula = obtenir_element('Taula_productes').lastChild;
		fila = obtenir_element('Fila_producte_' + num_productes);
		taula.removeChild(fila);
		num_productes--;
		
		document.Comanda.Num_productes.value = num_productes;
	}
	else alert('No és possible eliminar més productes.');
}

function comprovar_productes()
{
	var num_productes, trobat = false;
	var i, str_aux;
	
	num_productes = document.Comanda.Num_productes.value * 1;
	i = 1;
	while(i <= num_productes && !trobat)
	{
		str_aux = 'document.Comanda.Id_producte_format_' + i + '.options[document.Comanda.Id_producte_format_' + i + '.selectedIndex].value != \'\' && trim(document.Comanda.Quantitat_' + i + '.value) != \'\' && trim(document.Comanda.Quantitat_' + i + '.value) != \'0\'';
		if(eval(str_aux)) trobat = true;
		else i++;
	}
	
	return trobat;
}

function seleccionar_producte(index)
{
	var id, preu;
	
	id = eval('document.Comanda.Id_producte_format_' + index + '.options[document.Comanda.Id_producte_format_' + index + '.selectedIndex].value');
	if(id != '')
	{
		preu = array_preus[id] * 1;
		obtenir_element('Cella_preu_producte_' + index).innerHTML = preu + " €";
		calcular_imports_total();
	}
	else
	{
		obtenir_element('Cella_preu_producte_' + index).innerHTML = "0.00 €";
		eval('document.Comanda.Quantitat_' + index).value = "0";
		calcular_imports_total();		
	}
}

function calcular_imports_total()
{
	var num_productes, total, valor_import;
	var i, str_aux;
	
	num_productes = document.Comanda.Num_productes.value * 1;
	total = 0.00;
	for(i = 1; i <= num_productes; i++)
	{
		if(eval('document.Comanda.Id_producte_format_' + i + '.options[document.Comanda.Id_producte_format_' + i + '.selectedIndex].value') != '')
		{
			valor_import = trim(obtenir_element('Cella_preu_producte_' + i).innerHTML.replace('€', ''));
			str_aux = 'trim(document.Comanda.Quantitat_' + i + '.value)';
			if(eval(str_aux) != '')	valor_import = valor_import * (eval(str_aux) * 1);
			else
			{
				eval('document.Comanda.Quantitat_' + i + '.value = \'0\'');
				valor_import = 0.00;
			}
			obtenir_element('Cella_import_producte_' + i).innerHTML = valor_import.toFixed(2) + ' €';
			total = total + valor_import;
		}
		else obtenir_element('Cella_import_producte_' + i).innerHTML = '0.00 €';
	}
	obtenir_element('Cella_total').innerHTML = total.toFixed(2) + ' €';
}

function comprovar_calcular(num_fila)
{
	var obj_aux = eval('document.Comanda.Quantitat_' + num_fila);
	obj_aux.value = obj_aux.value.replace(',', '.');
	calcular_imports_total();
}

function mostrar_fitxa(id)
{
	obtenir_element('Fitxa_' + id).className = 'caracteristiques_vi_visible';
	obtenir_element('Enllac_fitxa_' + id).href = 'javascript: tancar_fitxa(' + id + ');';
}

function tancar_fitxa(id)
{
	obtenir_element('Fitxa_' + id).className = 'caracteristiques_vi_oculta';
	obtenir_element('Enllac_fitxa_' + id).href = 'javascript: mostrar_fitxa(' + id + ');';
}
