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? \nPerderá su pedido activo.');
	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(idioma){
	var campos = new Array("nif_cif","facturacion_nombre","facturacion_apellidos","facturacion_empresa","facturacion_direccion","facturacion_ciudad","facturacion_cod_postal");
	var nom_campos_esp = new Array("NIF / CIF","Nombre","Apellidos","Empresa","Dirección","Ciudad","Código Postal");	
	var nom_campos_cat = new Array("NIF / CIF","Nom","Cognoms","Empresa","Adresa","Ciutat","Codi Postal");	
	var nom_campos_eng = new Array("ID Number","Name","Last Name","Company","Address","City","Postal Code");
	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.\r\n\r\nAccept the Purchase Policy to\r\n continue with your order.\r\n\r\nThank you.');
		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;
			} else if(idioma=="eng"){
				alert('Error in data validation. Check: '+nom_campos_eng[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(idioma){
	var elemento = "forma_pago";
	var fpago = document.getElementById(elemento);
	valid = valida_form_ralizar_pago(idioma);
	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 nom_campos_eng = new Array("User","Password","Name","Last Name","Address","Postal Code","City","Phone","ID number");
	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;
		} else if(idioma=="eng"){
		alert('To complete your application\r\naccepts the terms of purchase\r\n by ticking the check box.\r\n\r\nThank you.');
		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;
			} else if(idioma=="eng"){
				alert('Error in data validation. Check: '+nom_campos_eng[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 login(lloc){
	elemento = "form_login_"+lloc;
	document.getElementById(elemento).submit();
}

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","Dirección","Ciudad","Código postal","Teléfono");	
	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 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;
}
