var indice;
//var ruta_url = "http://www.lavand.es/";
var ruta_url = "http://192.168.1.250:8000/lavand/www/";

function crearFile(obj,num){
	num++;
	if(indice){
		do{
			num++;
		}while(indice>=num)
	}

	var fi = document.getElementById(obj);
	var contenedor = document.createElement('div');
	contenedor.id = 'div'+num;
	fi.appendChild(contenedor);
	num2=num + 1;
	element = document.createElement('label');
	if(!document.getElementById('Color0')){
		text = document.createTextNode('Color 1');
		element.appendChild(text);
		contenedor.appendChild(element);
		
		element = document.createElement('input');
		element.id = 'Color0';
		element.name = 'data[Color][0]';
		contenedor.appendChild(element);
		
		element = document.createElement('label');
		text = document.createTextNode('Foto 1');
		element.appendChild(text);
		contenedor.appendChild(element);	
		
		element = document.createElement('input');
		element.type = 'file';
		element.name = 'data[Image][0]';
		element.id = 'Foto0';
		contenedor.appendChild(element);
	}else{
		text = document.createTextNode('Color '+num2);
		element.appendChild(text);
		contenedor.appendChild(element);
		
		element = document.createElement('input');
		element.id = 'Color'+num;
		element.name = 'data[Color]['+num+']';
		contenedor.appendChild(element);
		
		element = document.createElement('label');
		text = document.createTextNode('Foto '+num2);
		element.appendChild(text);
		contenedor.appendChild(element);	
		
		element = document.createElement('input');
		element.type = 'file';
		element.name = 'data[Image]['+num+']';
		element.id = 'Foto'+num;
		contenedor.appendChild(element);
	}
	element = document.createElement('input');
	element.name = 'div'+num;
	element.type = 'button';
	element.value = 'Eliminar';
	element.onclick = function() {eliminarElement(this.name,obj)}
	contenedor.appendChild(element);
	indice = num;
}

function eliminarElement(nom,obj){
	indice--;
	fi = document.getElementById(obj);
	fi.removeChild(document.getElementById(nom));
}

function controlTalles(camp){
	if(document.getElementById(camp).checked==1){
		for (i = 0; i <= 8; i++) {
			if(document.getElementById('Talla'+i) != document.getElementById(camp)){
				document.getElementById('Talla'+i).checked = 0;
				document.getElementById('Talla'+i).disabled = true;
			}
		}
	}else{
		for (i = 0; i <= 8; i++) {
			if(document.getElementById('Talla'+i) != document.getElementById(camp)){
				document.getElementById('Talla'+i).disabled = false;
			}
		}
	}
}

function noUnica(camp){
	if(document.getElementById(camp).checked==1){
		document.getElementById('Talla5').checked = 0;
		document.getElementById('Talla6').checked = 0;
		document.getElementById('Talla7').checked = 0;
		document.getElementById('Talla8').checked = 0;

	}
	/*
	if(
	(document.getElementById('Talla0').checked == 0) && 
	(document.getElementById('Talla1').checked == 0) && 
	(document.getElementById('Talla2').checked == 0) && 
	(document.getElementById('Talla3').checked == 0) && 
	(document.getElementById('Talla4').checked == 0)){
		document.getElementById('Talla5').disabled = false;
		document.getElementById('Talla6').disabled = false;
	}
	*/
}

function tractaColor(camp){
	var valor = camp.value;
	var posicio_final = valor.length-1;
	while (''+valor.charAt(0)==' ') valor=valor.substring(1,valor.length);
	while (''+valor.charAt(0)==',') valor=valor.substring(1,valor.length);
  while (''+valor.charAt(posicio_final)==' ') valor=valor.substring(0,valor.length-1);
	while (''+valor.charAt(posicio_final)==',') valor=valor.substring(0,valor.length-1);
	
	out = ",,"
	add = ",";
	while (valor.indexOf(out)>-1)
	{
		pos=valor.indexOf(out);
		valor = "" + (valor.substring(0, pos) + add + valor.substring((pos + out.length), valor.length));
	}
	camp.value = valor;
}


function guardaCombos(idioma){
	document.getElementById('talla').value = document.getElementById('talles').value;
	if(document.getElementById('unidades').value != ''){
		document.getElementById('unitats').value = document.getElementById('unidades').value;
	}else{
		if(idioma == 'en') alert('No unit has been selected.');
		else alert('No ha seleccionado ninguna unidad.');
		return true;
	}
	if (!noColors()) {
		return true;
	}
	/*
	if(document.getElementById('color').value == ''){
		if(idioma == 'en') alert('No style has been selected.');
		else alert('No ha seleccionado ningun modelo.');
		return true;		
	}
	tractaColor(document.getElementById('color'));
	*/
	tractaColor(document.getElementById('imatge'));
	tractaColor(document.getElementById('id_imatge'));
}

function carregaColor(label,imatge,id_imatge,idioma){
	if (!noColors()) {
		if(idioma == 'en') alert('No style has been selected.');
		else alert('No ha seleccionado ningun modelo.');
		return true;
	}
	
	if (!colorsMinims()) {
		if(idioma == 'en') alert('The maximum of styles for this order is 2.');
		else alert('El n\u00famero m\u00e1ximo de modelos para este pedido es de 2.');
		document.getElementById(label).checked = false;
		return false;
	}
	
	
	if(document.getElementById(label).checked == 1){
		if(document.getElementById('imatge').value =='') document.getElementById('imatge').value = imatge;
		else document.getElementById('imatge').value += ','+imatge;
		if(document.getElementById('id_imatge').value =='') document.getElementById('id_imatge').value = id_imatge;
		else document.getElementById('id_imatge').value += ','+id_imatge;
	}	else {
		if(document.getElementById('imatge').value == imatge) document.getElementById('imatge').value = '';
		else {
			/* Treiem el nom de la imatge que s'ha desseleccionat al catalogo */
			out = imatge;
			add = "";
			temp = document.getElementById('imatge').value;
			while (temp.indexOf(out)>-1)
			{
				pos=temp.indexOf(out);
				temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
			}
			document.getElementById('imatge').value = temp;
		}	
		if(document.getElementById('id_imatge').value ==id_imatge) document.getElementById('id_imatge').value = '';
		else {/* Treiem el id de la imatge que s'ha desseleccionat al catalogo */
			out = id_imatge;
			add = "";
			temp = document.getElementById('id_imatge').value;
			while (temp.indexOf(out)>-1)
			{
				pos=temp.indexOf(out);
				temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
			}
			document.getElementById('id_imatge').value = temp;
		}
	}
	tractaColor(document.getElementById('imatge'));
	tractaColor(document.getElementById('id_imatge'));
}

/*   backup funcio carregaColor  */
/*
function carregaColor(label,imatge,id_imatge){
	text = '';
	if(document.getElementById(label).checked == 1){
		text = document.getElementById(label).value;
		i = 1;
		while(document.getElementById('Color.'+i)){
			if((document.getElementById('Color.'+i))!=(document.getElementById(label))){
				document.getElementById('Color.'+i).checked = 0;
			}
			i++;
		}
	}
	if(document.getElementById(label).checked == 0){
		text = '';
		i = 1;
		while(document.getElementById('Color.'+i)){
			if((document.getElementById('Color.'+i))!=(document.getElementById(label))){
				document.getElementById('Color.'+i).checked = 0;
			}
			i++;
		}
	}
	document.getElementById('color').value = text;
	if(text != ''){
		document.getElementById('imatge').value = imatge;
		document.getElementById('id_imatge').value = id_imatge;
	}else{
		document.getElementById('imatge').value = '';
		document.getElementById('id_imatge').value = '';
	}
}
*/


function canviarUnitats(id,idioma,minim){
	var error = false;
	
	if(document.getElementById('unidades.' + id).value < minim){
		document.getElementById('unidades.' + id).value = minim;
		if(idioma == 'en') alert("Minimum order for this category is "+minim+" units \n\r");
		else alert("El n\u00famero m\u00ednimo de prendas para esta categoria es de "+minim+" unidades. \n\r");
		return true;
	}
	
	var valor = document.getElementById('unidades.' + id).value;
	var v = MyTrim(valor);
	if (v == ''){
		if(idioma == 'en') msgError = "No value has been introduced. ";
		else msgError = "No se ha introducido ning\u00fan valor ";
		error = 1;
	}

	
	if (!/^([0-9])*$/.test(document.getElementById('unidades.' + id).value)) {
		if(idioma == 'en') msgError = "El valor " + document.getElementById('unidades.' + id).value + " no es un n\u00famero v\u00e1lido (Angles)";
		else msgError = "El valor " + document.getElementById('unidades.' + id).value + " no es un n\u00famero v\u00e1lido";
  	
		error = 1;
  }
	if ( parseInt(document.getElementById('unidades.' + id).value, 10) == 0 ){
		if(idioma == 'en') msgError = "El valor " + document.getElementById('unidades.' + id).value + " no es un n\u00famero v\u00e1lido (Angles)";
		else msgError = "El valor " + document.getElementById('unidades.' + id).value + " no es un n\u00famero v\u00e1lido";
		error = 1;
	}
	if (error) 
  	alert(msgError);
  else {
  	if (document.getElementById('unitats_enviar').value == '') {
  		document.getElementById('unitats_enviar').value = document.getElementById('unidades.' + id).value;
  	}
  	else {
  		document.getElementById('unitats_enviar').value += ', ' + document.getElementById('unidades.' + id).value;
  	}
  	if (document.getElementById('id_edit').value == '') {
  		document.getElementById('id_edit').value = id;
  	}
  	else {
  		document.getElementById('id_edit').value += ', ' + id;
  	}
		avisa();
  }
}

var i = 0;
function estatIva(){
	i = 1;
	if(document.getElementById('iva16').checked == 0){
		document.getElementById('iva16_actiu').value = 0;
	}else{
		document.getElementById('iva16_actiu').value = 1;
	}
	if(document.getElementById('iva4').checked == 0){
		document.getElementById('iva4_actiu').value = 0;
	}else{
		document.getElementById('iva4_actiu').value = 1;
	}
}

function validarRealizar(total,idioma){
	if(total == 0){
		if(idioma == 'en') alert('Your basket is empty.');
		else alert('El carrito est\u00e1 vacio.');
		return true;
	}
}

function MyTrim(camp) {
  var valor = camp;
	while (''+valor.charAt(0)==' ') valor=valor.substring(1,valor.length);
  while (''+valor.charAt(valor.length)==' ') valor=valor.substring(0,valor.length-1);
	return valor;
}

function verificarText(id) {
 if(document.getElementById(id)){
	 var valor = document.getElementById(id).value;
	 var v = MyTrim(valor);
	 document.getElementById(id).value = v;
	 if(v == '') return false;
	 else return true;
	}else{
		return true;
	}
}

function acceptNum(evt,catalogo){
// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, '.' = 46
	var navegador = navigator.appName
	if (navegador == "Microsoft Internet Explorer") {
		var key=(document.all) ? evt.keyCode : e.which;
	}else{
		var key = nav4 ? evt.which : evt.keyCode;
	}
	if(catalogo == 1) return (key <= 13 || (key >= 48 && key <= 57));
	else return (key <= 13 || (key >= 48 && key <= 57) || key == 46);
}

function verificarPrenda(){
	ruta = document.forms[0];
	var hayFile = false;
	
	if (document.getElementById('Color0')) hayFile = true;
	
	if (!hayFile) {
		alert("Introduce un color");
		return true;
	}	
	
	if(!indice) indice = 0;
	var error = false;
	var msgError = '';
	var i = 0;
	for(i;i<=indice;i++){
		var num_color = i+1;
		if (!verificarText('Color'+i)){
			error = true;
			msgError += "Introduce un color en el color "+num_color+".\n\r";
		}
		if(document.getElementById('Foto'+i)){
			if(document.getElementById('Foto'+i).value == ''){
				error = true;
				msgError += "No se ha introducido ninguna imagen para el color "+num_color+".\n\r";
			}
		}
	}
	if (error) alert(msgError);
	return error;
}

function validarUnitatsCarrito(){
	estatIva();
}

function marcarOpcionMenu(opcion){
	
	document.getElementById("home").className = "home";
	//document.getElementById("about").className = "about";
  document.getElementById("brand").className = "brand";
  document.getElementById("company").className = "company";
 // document.getElementById("collections").className = "collections";
	document.getElementById("fw").className = "fw";
	document.getElementById("ss").className = "ss";
	document.getElementById("shop").className = "shop";
	document.getElementById("tradeshows").className = "tradeshows";
	//document.getElementById("contact").className = "contact";
	document.getElementById("showrooms").className = "showrooms";
	document.getElementById("headquarters").className = "headquarters";
  
  if (opcion == "home"){
    document.getElementById("home").className = "homeSelect";
  }
  if (opcion == "brand"){
    document.getElementById("brand").className = "brandSelect";
  }
  if (opcion == "company"){
    document.getElementById("company").className = "companySelect";
  }
  
  if (opcion == "fw"){
    document.getElementById("fw").className = "fwSelect";
  }
  
  if (opcion == "ss"){
    document.getElementById("ss").className = "ssSelect";
  }
  if (opcion == "shop"){
    document.getElementById("shop").className = "shopSelect";
  }
	if (opcion == "tradeshows"){
    document.getElementById("tradeshows").className = "tradeshowsSelect";
  }
/*  if (opcion == "contact"){
    document.getElementById("contact").className = "contactSelect";
  }*/
   if (opcion == "showrooms"){
    document.getElementById("showrooms").className = "showroomsSelect";
  }
   if (opcion == "headquarters"){
    document.getElementById("headquarters").className = "headquartersSelect";
  }

	}


function validarRegistre(idioma,emails){
	var emailsExistents = emails.split(",");
	var error = false;
	var msgError = '';
	var i = 0;
	while(emailsExistents[i]){
		if(document.getElementById('email').value == emailsExistents[i]){
			if(idioma == 'en') msgError += "Sorry, it's not possible to register because this user is already in our data base. \n\r";
			else msgError += "Lo sentimos, no es posible registrarse porque este usuario ya existe en nuestra base de datos. \n\r";
			error = 1;
			if (error) alert(msgError);
			return error;
		}
		i++;
	}
	
	if (MyTrim(document.getElementById('nomContacte').value) == '') {
		if(idioma == 'en') msgError += "Contact person name incorrect. \n\r";
		else msgError += "Nombre persona contacto incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('nomFiscal').value) == '') {
		if(idioma == 'en') msgError += "Tax name incorrect. \n\r";
		else msgError += "Nombre fiscal incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('nif').value) == '') {
		if(idioma == 'en') msgError += "Tax ID incorrect. \n\r";
		else msgError += "NIF/CIF incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('email').value) == '') {
		if(idioma == 'en') msgError += "E-mail incorrect. \n\r";
		else msgError += "E-mail incorrecto. \n\r";
  	error = 1;
  }else{
		var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		if (!filter.test(document.getElementById('email').value)){
			if(idioma == 'en') msgError += "E-mail incorrect. \n\r";
			else msgError += "E-mail incorrecto. \n\r";
			error = 1;
		}
	}
	
	if (MyTrim(document.getElementById('telefon').value) == '') {
		if(idioma == 'en') msgError += "Phone number incorrect. \n\r";
		else msgError += "Tel\u00e9fono incorrecto. \n\r";
  	error = 1;
  }else {
  	if (!/^([0-9])*$/.test(document.getElementById('telefon').value)) {
  		if(idioma == 'en') msgError += "Phone number incorrect. \n\r";
			else msgError += "Tel\u00e9fono incorrecto. \n\r";
  		error = 1;
  	}
  }
	
	if (MyTrim(document.getElementById('direccio').value) == '') {
		if(idioma == 'en') msgError += "Adress incorrect. \n\r";
		else msgError += "Direcci\u00f3n incorrecta. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('cp').value) == '') {
		if(idioma == 'en') msgError += "Zip Code incorrect. \n\r";
		else msgError += "C\u00f3digo postal incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('poblacio').value) == '') {
  	if(idioma == 'en') msgError += "City incorrect. \n\r";
		else msgError += "Poblaci\u00f3n incorrecta. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('provincia').value) == '') {
  	if(idioma == 'en') msgError += "Country Area incorrect. \n\r";
		else msgError += "Provincia incorrecta. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('pais').value) == '') {
		if(idioma == 'en') msgError += "Country incorrect. \n\r";
		else msgError += "Pa\u00eds incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('existent').value) == '') {
		if(idioma == 'en') msgError += "Are you already an existing Lavand client incorrect. \n\r";
		else msgError += "Cliente existente de Lavand incorrecto. \n\r";
  	error = 1;
  }

	if (MyTrim(document.getElementById('estiloTienda').value) == '') {
		if(idioma == 'en') msgError += "Style of your shop incorrect. \n\r";
		else msgError += "Estilo de la tienda incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('marcas').value) == '') {
		if(idioma == 'en') msgError += "Brands are you working with incorrect. \n\r";
		else msgError += "Principales marcas vendidas en la tienda incorrecto. \n\r";
  	error = 1;
  }
	
	if (MyTrim(document.getElementById('fechaTienda').value) == '') {
		if(idioma == 'en') msgError += "Your business is running since incorrect. \n\r";
		else msgError += "La tienda existe desde incorrecto. \n\r";
  	error = 1;
  }

	if (error) alert(msgError);
	return error;
}

function loadFoto(idFoto) {
	var result = function(obj) {
		document.getElementById('fotoColor').value = obj.responseText;
	}
	var url  = ruta_url+'images/loadFoto/'+idFoto;
	new Ajax.Updater( 'foto_p', url, { method: 'get' , parameters: '', onComplete: result }); 
}

function avisa(idioma){
	if(idioma == 'es') alert('Por favor haga click en el bot\u00f3n Actualizar del Importe Total para aplicar los cambios.');
	else alert('Please click on Refresh Total Amount in order to save the changes.');
}

//crear i eliminar opció d'adjuntar fotos al crear un projecte
var numero = 0;
function crearFotoClient(obj,idioma){
numero++;
	var fi = document.getElementById(obj);
	var contenedor = document.createElement('div');
	contenedor.id = 'div'+numero;
	fi.appendChild(contenedor);
	
	element = document.createElement('label');
	var label = '';
	text = document.createTextNode(label);
	element.appendChild(text);
	contenedor.appendChild(element);	
	
	element = document.createElement('input');
	element.type = 'file';
	element.name = 'data[ImagesClient]['+numero+']';
	contenedor.appendChild(element);
	
	element = document.createElement('input');
	element.name = 'div'+numero;
	element.type = 'button';
	if(idioma == 'en'){
		element.value = 'Delete';
	} else {
		element.value = 'Eliminar';
	}
	
	element.onclick = function() {eliminarFotoClient(this.name,obj)}
	contenedor.appendChild(element);
}

function eliminarFotoClient(nom,obj){
	numero--;
	fi = document.getElementById(obj);
	fi.removeChild(document.getElementById(nom));
}

function unitatsMinimes(minim,idioma){
	if(document.getElementById('unidades').value < minim){
		document.getElementById('unidades').value = minim;
		if(idioma == 'en') alert("Minimum order for this category is "+minim+" units \n\r");
		else alert("El n\u00famero m\u00ednimo de prendas para esta categoria es de "+minim+" unidades. \n\r");
	}
}

function colorsMinims() {
	var cont = 0;
	for (i=0;i<document.forms[1].elements.length;i++) {
		if (document.forms[1].elements[i].type == 'checkbox') {
			if (document.forms[1].elements[i].checked == true) cont++;
		}	
	}
	if (cont>2) return false; else return true;
}

function noColors(){
	var cont = 0;
	for (i=0;i<document.forms[1].elements.length;i++) {
		if (document.forms[1].elements[i].type == 'checkbox') {
			if (document.forms[1].elements[i].checked == true) cont++;
		}	
	}
	if (cont==0) return false; else return true;
}

function cambiaFoto(capa) {
	var valor = 0;
	if(capa.substring(capa.length-1,capa.length) == '1') valor = 11;
	if(capa.substring(capa.length-1,capa.length) == '2') valor = 11;
	if(capa.substring(capa.length-1,capa.length) == '3') valor = 3;
	var randomnumber=Math.floor(Math.random()*valor);
	//document.getElementById("fondo").myActionscriptFunction(capa+'/'+randomnumber+'.jpg');
	document.getElementById("fondo").myActionscriptFunction(capa,valor);
}
/*
function sendToJavaScript() {
	//alert("holaaaa AS! ");
}*/