function modifica_quantitat(producte,tipus){
	elemento = "quantitat_"+producte;
	var nova_quantitat = 0;
	if(tipus=="mes"){
		nova_quantitat = parseInt(document.getElementById(elemento).value) + 1;
	}
	if(tipus=="menys"){
		nova_quantitat = parseInt(document.getElementById(elemento).value) - 1;
	}
	if(tipus=="res"){
		nova_quantitat = parseInt(document.getElementById(elemento).value);
	}
	if(isNaN(nova_quantitat)){
		document.getElementById(elemento).value = 1;
	} else if(nova_quantitat<1){
		document.getElementById(elemento).value = 1;
	} else if(nova_quantitat>99){
		document.getElementById(elemento).value = 99;
	} else {
		document.getElementById(elemento).value = nova_quantitat;
	}
}

//// AJAX FUNCTIONS 
var estat_ajax = 'OK';

function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function updateProvincies(tipo_anuncio){
	var valor_actiu = tipo_anuncio;
	var element = "contenedor_provincia";
	contenedor = document.getElementById(element);
	ajax=nuevoAjax();
	//contenedor.innerHTML = '<img src="../icons/icon_orange.gif" alt="Guardant" width="10" height="10">';
	ajax.open("POST", "../ajax/update_provincies.php",true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==0) {
			contenedor.innerHTML = "Inicializando";
		} //el 0 vol dir que el retorn es estat INICIALIZAR 
		if (ajax.readyState==1) {
			contenedor.innerHTML = "Cargando";
		} //el 1 vol dir que el retorn es estat CARGANDO 
		if (ajax.readyState==2) {
			contenedor.innerHTML = "Cargado";
		} //el 2 vol dir que el retorn es estat CARGADO 
		if (ajax.readyState==3) {
			contenedor.innerHTML = "Interactuando";
		} //el 3 vol dir que el retorn es estat INTERACTUANDO 

		if (ajax.readyState==4) { //el 4 vol dir que el retorn es estat COMPLETADO 
			contenedor.innerHTML = ajax.responseText;
			campo2 = document.getElementById('donde_buscas');
			campo2.focus();
		}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("tipo_anuncio_actiu="+valor_actiu);
}
function compra(producte){
	modifica_quantitat(producte,'res');
	elemento = "form_producte_"+producte;
	document.getElementById(elemento).submit();
}

function update(producte){
	modifica_quantitat(producte,'res');
	elemento = "form_update_producte_"+producte;
	document.getElementById(elemento).funcio_update.value = 'actualitza';
	document.getElementById(elemento).submit();
}

function elimina(producte){
	elemento = "form_update_producte_"+producte;
	agree = confirm('¿Seguro que desea eliminar el producto?');
	if (agree) {
		document.getElementById(elemento).funcio_update.value = 'elimina';
		document.getElementById(elemento).submit();
	}
}

function anular(){
	elemento = "form_anular";
	agree = confirm('¿Seguro que desea anular el pedido?');
	if (agree) {
		document.getElementById(elemento).submit();
	}
}

function finalizar(){
	elemento = "form_finalizar";
//	agree = confirm('¿Segur que vol finalitzar aquesta comanda?');
//	if (agree) {
		document.getElementById(elemento).submit();
//	}
}

function login(lloc){
	elemento = "form_login_"+lloc;
	document.getElementById(elemento).submit();
}

function logout(){
	elemento = "form_logout";
	agree = confirm('¿Desea salir de la sesion activa / cambiar de usuario?');
	if (agree) {
		document.getElementById(elemento).submit();
	}
}

function confirmar_pedido(){
	elemento = "form_confirmar_pedido";
	document.getElementById(elemento).submit();
}

function valida_null(campo){
	var elemento = campo;
	elementID = document.getElementById(elemento);
	if ((elementID.value==null)||(elementID.value=="")){
		return false;
	}
	return true;
}

function valida_form_ralizar_pago(){
	var campos = new Array("nif_cif","facturacion_nombre","facturacion_apellidos","facturacion_direccion","facturacion_cod_postal","facturacion_ciudad");
	var nom_campos = new Array("Nif/Cif","Nombre","Apellidos","Dirección","Código postal","Ciudad");
	var elemento = "form_realizar_pago";
	var aceptoID = document.getElementById(elemento).acepto_condiciones_compra;
	if(aceptoID.checked == false){
		alert('Para poder finalizar su pedido\r\nacepte las condiciones de compra\r\nmarcando la casilla de verificación.\r\n\r\nGracias.');
		return false;
	}
	
	// comprobem nulls als camps
	for (i=0; i<campos.length; i++){
		var validat = valida_null(campos[i]);
		if(validat==false){
			alert('Error en validación de datos. Compruebe:'+nom_campos[i]);
			return false;
		}
	}
	return true;
}

function pagar_tarjeta() { 
	vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
	document.compra.submit();
	// enviem l'update de la comanda
	//elemento = "form_realizar_pago";
	//document.getElementById(elemento).submit();
	document.form_realizar_pago.submit();
}

function pagar_transf() { 
	// enviem l'update de la comanda
	//elemento = "form_realizar_pago";
	//document.getElementById(elemento).submit();
	document.form_realizar_pago.submit();
}

function realizar_pago(){
	var elemento = "forma_pago";
	var fpago = document.getElementById(elemento);
	valid = valida_form_ralizar_pago();
	if(valid==true){
		if(fpago[fpago.selectedIndex].value == 'transferencia'){
			pagar_transf();
		} else {
			pagar_tarjeta();
		}
	} else {
		//alert('Error en validación de datos. Compruébelos y vuleva a confirmar.');
	}
}

/*
function calc() { 
	vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
	document.compra.submit();
}
*/

/*
function valida_form_registro(idioma){
	var campos = new Array("usr_registro","pwd_registro","nombre","apellidos","direccion","cod_postal","ciudad","telefonos","nif_cif");
	var nom_campos_esp = new Array("Usuario","Password","Nombre","Apellidos","Dirección","Código postal","Ciudad","Teléfono","Nif/Cif");	
	var nom_campos_cat = new Array("Usuari","Password","Nom","Cognoms","Direcció","Codi postal","Ciutat","Telèfon","Nif/Cif");	
	var elemento = "form1";
	var aceptoID = document.getElementById(elemento).acepto_terminos_tpsport;
	if(aceptoID.checked == false){
		if(idioma=="esp"){
		alert('Para poder finalizar su solicitud\r\nacepte las condiciones de compra\r\nmarcando la casilla de verificación.\r\n\r\nGracias.');
		return false;
		} else if(idioma=="cat"){
		alert('Per poder finalitzar la seva solicitut\r\naccepti les condicions de compra\r\nmarcant la casella de verificació.\r\n\r\nGràcies.');
		return false;
		}
	}
	// comprobem nulls als camps
	for (i=0; i<campos.length; i++){
		var validat = valida_null(campos[i])
		if(validat==false){
			if(idioma=="esp"){
				alert('Error en validación de datos. Compruebe:'+nom_campos_esp[i]);
			return false;
			} else if(idioma=="cat"){
				alert('Error en la validació de dades. Comprovi:'+nom_campos_cat[i]);
			return false;
			}
		}
	}
	document.getElementById(elemento).submit();
}
*/

function copiar_datos(){
	document.form_realizar_pago.envio_nombre.value				= document.form_realizar_pago.facturacion_nombre.value;
	document.form_realizar_pago.envio_apellidos.value 			= document.form_realizar_pago.facturacion_apellidos.value;
	document.form_realizar_pago.envio_empresa.value 			= document.form_realizar_pago.facturacion_empresa.value;
	document.form_realizar_pago.envio_direccion.value 			= document.form_realizar_pago.facturacion_direccion.value;
	document.form_realizar_pago.envio_cod_postal.value			= document.form_realizar_pago.facturacion_cod_postal.value;
	document.form_realizar_pago.envio_ciudad.value 				= document.form_realizar_pago.facturacion_ciudad.value;
	document.form_realizar_pago.envio_provincia.selectedIndex	= document.form_realizar_pago.facturacion_provincia.selectedIndex ;
	document.form_realizar_pago.envio_pais.selectedIndex		= document.form_realizar_pago.facturacion_pais.selectedIndex;
}

function obre_carret(numero_carret){
	var elemento = "form_obre_carret_"+numero_carret;
	document.getElementById(elemento).submit();	
}

function obre_pago(numero_carret){
	var elemento = "form_obre_pago_"+numero_carret;
	document.getElementById(elemento).submit();	
}

function clubs(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto');
}


function posa_usr_pwd(usuari,contrasenya){
	document.form_registro.usr_registro.value=usuari;
	document.form_registro.pwd_registro.value=contrasenya;
}

function valida_null(campo){
	var elemento = campo;
	elementID = document.getElementById(elemento);
	if ((elementID.value==null)||(elementID.value=="")){
		return false;
	}
	return true;
}
					
function valida_form_registro(idioma){
	//comprovar_edat();
	var campos = new Array("usr_registro","pwd_registro","nombre","apellidos","direccion","ciudad","cod_postal","telefonos");
	var nom_campos_esp = new Array("Usuario","Password","Nombre","Apellidos","Ciudad","Código postal");	
	var nom_campos_cat = new Array("Usuari","Password","Nom","Cognoms","Direcció","Ciutat","Codi postal","Telèfon");	
	var elemento = "form_registro";
	var aceptoID = document.getElementById(elemento).acepto_terminos;
	if(aceptoID.checked == false){
		if(idioma=="esp"){
		alert('Para poder finalizar su solicitud\r\nacepte las condiciones\r\nmarcando la casilla de verificación.\r\n\r\nGracias.');
		return false;
		} else if(idioma=="cat"){
		alert('Per poder finalitzar la seva solicitut\r\naccepti les condicions\r\nmarcant la casella de verificació.\r\n\r\nGràcies.');
		return false;
		}
	}
	// comprobem nulls als camps
	for (i=0; i<campos.length; i++){
		var validat = valida_null(campos[i])
		if(validat==false){
			if(idioma=="esp"){
				alert('Error en validación de datos. Compruebe: '+nom_campos_esp[i]);
			return false;
			} else if(idioma=="cat"){
				alert('Error en la validació de dades. Comprovi: '+nom_campos_cat[i]);
			return false;
			}
		}
	}
	document.getElementById(elemento).submit();
}

function comprovar_edat(){
	var data=document.form_registro.any.value+"-"+document.form_registro.mes.value+"-"+document.form_registro.dia.value;
	document.form_registro.data_naixement.value=data;
}
function posar_data(){
	var data=document.form_consulta.anno.value+"-"+document.form_consulta.mes.value+"-"+document.form_consulta.dia.value;
	document.form_consulta.fecha_compra.value=data;
//	alert(data);
}
function poner_tipo(){
	var form_consulta = document.getElementById('form_consulta');
	var campo = document.getElementById('productes');
	var selcampo = document.getElementById('familia');
	var selind = selcampo.selectedIndex;
	if(selind>0){
		updateProductes(selcampo.value);
	} else {
		campo.selectedIndex=0;
		campo.disabled=true;
	}
}
function updateProductes(id_familia){
	var valor_actiu = id_familia;
	var element = "contenedor_productos";
	contenedor = document.getElementById(element);
	ajax=nuevoAjax();
	ajax.open("POST", "../ajax/update_productes.php",true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==0) {
			contenedor.innerHTML = "Inicializando";
		} //el 0 vol dir que el retorn es estat INICIALIZAR 
		if (ajax.readyState==1) {
			contenedor.innerHTML = "Cargando";
		} //el 1 vol dir que el retorn es estat CARGANDO 
		if (ajax.readyState==2) {
			contenedor.innerHTML = "Cargado";
		} //el 2 vol dir que el retorn es estat CARGADO 
		if (ajax.readyState==3) {
			contenedor.innerHTML = "Interactuando";
		} //el 3 vol dir que el retorn es estat INTERACTUANDO 

		if (ajax.readyState==4) { //el 4 vol dir que el retorn es estat COMPLETADO 
			contenedor.innerHTML = ajax.responseText;
			campo = document.getElementById('productes');
			campo.focus();
		}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("id_familia="+valor_actiu);
}
function posarProductes(elemento){
	var selec_producte = elemento.options[elemento.selectedIndex].value;
	var selec_producte_txt = elemento.options[elemento.selectedIndex].lang;
	document.form_consulta.id_producte.value=selec_producte;
	document.form_consulta.txt_producte.value=selec_producte_txt;
}

function comporbar_aficiones(){
	// comprobem checkboxs
	var camp_num_aficiones = document.getElementById('num_aficiones');
	if(camp_num_aficiones!=null){
		var num_aficiones = parseInt(document.getElementById('num_aficiones').value)+1;
/*	
		var error_check2 = true;
		for (i=1; i<num_aficiones; i++){
			var nom_campo_activo = "aficiones_"+i;
			var campo_activo = document.getElementById(nom_campo_activo);
			if(campo_activo.checked == true){
				error_check2 = false;
			}
		}
		
		if(error_check2==true){
			alert("Debe seleccionar almenos una forma de pago.\r\nGracias.");
			return false;
		}
	}
	*/
	document.getElementById('form_aficiones');
	}
}

function registrar_producto(){
	var form_arctiu = document.getElementById('form_consulta');
	var fecha_compra = document.getElementById('fecha_compra');
	var id_producte = document.getElementById('id_producte');
	var ref = document.getElementById('ref');
	var sn = document.getElementById('sn');
	var lugar_compra = document.getElementById('lugar_compra');
	var val_dis = document.getElementById('val_dis');
	var val_fun = document.getElementById('val_fun');
	var observaciones = document.getElementById('observaciones');
	
	var dia = document.getElementById('dia');
	var mes = document.getElementById('mes');
	var anno  = document.getElementById('anno');
	
	if(id_producte.value=='-1'){ alert('Debe seleccionar una familia y un producto'); return false; }
	if(ref.value==''){ alert('Debe introducir la referencia exacta de su producto'); return false; }
	if(sn.value==''){ alert('Debe introducir el número de série de su producto'); return false; }
	if((fecha_compra.value=='-1')||(fecha_compra.value=='0000-00-00')){ 
		alert('Compruebe la fecha de compra'); return false; 
	} else {
		if(dia.selectedIndex=='0'){ alert('Compruebe la fecha de compra'); return false; }
		if(mes.selectedIndex=='0'){ alert('Compruebe la fecha de compra'); return false; }
		if(anno.selectedIndex=='0'){ alert('Compruebe la fecha de compra'); return false; }
	}
	if(lugar_compra.value==''){ alert('Debe indicarnos el lugar de compra'); return false; }
	if(val_dis.selectedIndex=='0'){ alert('Debe seleccionar una valoración para el diseño del producto'); return false; }
	if(val_fun.selectedIndex=='0'){ alert('Debe seleccionar una valoración para la funcionalidad del producto'); return false; }
//	if(observaciones.value==''){ alert('Introduzca sus observaciones'); return false; }
	form_arctiu.submit();
}
function denunciar_foto(id_foto,id_usuari,idioma){
	if(idioma=="esp"){
		var frase = '¿Desea enviar aviso de que la foto no corresponde con su usuario?';
	}
	if(idioma=="por"){
		var frase = 'Deseja enviar aviso de que as fotos não correspondem ao seu nome de usuário?';
	}
	if(idioma=="eng"){
		var frase = 'Want to send notice that the photo does not match your username?';
	}
	agree = confirm(frase);
	if (agree) {
		document.envio_error.usuari.value=id_usuari;
		document.envio_error.foto.value=id_foto;
		document.envio_error.submit();
	}	
}
function update_select(sel){
	var elemento ='filtre_'+sel;
		document.getElementById(elemento).submit();
}
function menu() {
	var elem = 'acordeon';
	document.getElementById(elem).style.visibility = 'visible';
}

