var name, surname, phone1, phone2, email, usedRC, address, zipCode, city, province, country;
var size, breed, pet, namePet, birthday, sex, breedDog, breedCat, sterilized, wetFood, dryFood, hair;
var homemadeFoodm, numberPets;
var aPet			= new Array();
var aBreed			= new Array();
var aSize			= new Array();
var aHair			= new Array();
var aNamePet		= new Array();
var aBirthday		= new Array();
var aSex			= new Array();
var aSterilized		= new Array();
var aWetFood		= new Array();
var aDryFood		= new Array();
var aHomemadeFood	= new Array();

function checkForm()
{
	valid = true;
	var message 	= "";
	name			= ($('#name').val()						== "Nombre")					? "" : $('#name').val();
	surname			= ($('#surname').val()					== "Apellidos")					? "" : $('#surname').val();
	phone1			= ($('#phone1').val()					== "Teléfono fijo")				? "" : $('#phone1').val();
	phone2			= ($('#phone2').val()					== "Teléfono movil")			? "" : $('#phone2').val();
	email			= ($('#email').val()					== "E-mail")					? "" : $('#email').val();
	usedRC			= ($('#usedRC').val()					== 0)							? 0  : $('#usedRC').val();
	address			= ($('#address').val()					== "Dirección")					? "" : $('#address').val();
	zipCode			= ($('#zipCode').val()					== "Código Postal")				? "" : $('#zipCode').val();
	city			= ($('#city').val()						== "Población")					? "" : $('#city').val();
	province		= ($('#province').val()					== 0)							? 0  : $('#province').val();
	country			= ($('#country').val()					== 0)							? 0  : $('#country').val();


	if(!name || !surname || !phone1 || !phone2 || !email || usedRC == 0 || !address || !zipCode || !city || province == 0 || country == 0)  {
		valid = false;
	}

	if (!valid) {
		alert('Debe rellenar los campos marcados con asterisco.');
	} else {
		var emailCheck = /^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.-]+[A-za-z]$/.test($('#email').val());
		var phoneCheck1 = /^\d{9}$/.test($('#phone1').val());
		var phoneCheck2 = /^\d{9}$/.test($('#phone2').val());
		var condition = $('#f_acepta').attr('checked');
		if(numberPets == 0 || !numberPets) {
			message+= "Debe indicarnos los datos de al menos una mascota.\n";
		} else {
			for (var i = 1; i<= numberPets; i++) {
				var allOk = true;
				var pet = ($('#pet_'+i).val() == 0) ? 0 : $('#pet_'+i).val();
				if(pet == 0) {
					message+= "Debe indicar el tipo de mascota. Número: "+i+".\n";
					allOk = false;
				} else {
					breedDog	= ($('#breedDog_'+i).val()				== 0)			 ? 0  : $('#breedDog_'+i).val();
					breedCat	= ($('#breedCat_'+i).val()				== 0)			 ? 0  : $('#breedCat_'+i).val();
					size		= ($('#size_'+i).val()					== 0)			 ? 0  : $('#size_'+i).val();
					hair		= ($('#hair_'+i).val()					== 0)			 ? 0  : $('#hair_'+i).val();
					namePet		= ($('#namePet_'+i).val()				== "Nombre")	 ? "" : $('#namePet_'+i).val();
					birthday	= ($('#birthday_'+i).val()				== "dd/mm/aaaa") ? "" : $('#birthday_'+i).val();
					sex			= ($('#sex_'+i).val()					== 0)			 ? 0  : $('#sex_'+i).val();
					sterilized	= ($('#sterilized_'+i).val()			== 0)			 ? 0  : $('#sterilized_'+i).val();
					wetFood		= ($('#wetFood_'+i).attr('checked')		== true)		 ? 1  : 2;
					dryFood		= ($('#dryFood_'+i).attr('checked')		== true)		 ? 1  : 2;
					homemadeFood= ($('#homemadeFood_'+i).attr('checked')== true)		 ? 1  : 2;

					if(breedDog == 0 && breedCat == 0) {
						message+= "Debe indicar la raza de su mascota. Mascota: "+i+".\n";
						allOk = false;
					}
					if(breedDog > 0 && size == 0) {
						message+= "Debe indicar la talla de su perro. Mascota: "+i+"\n";
						allOk = false;
					}
					if(breedCat > 0 && hair == 0) {
						message+= "Debe indicar el pelaje de su gato. Mascota: "+i+"\n";
						allOk = false;
					}
					if(!namePet) {
						message+= "Debe indicar el nombre de su mascota. Mascota: "+i+"\n";
						allOk = false;
					}
					if(birthday) {
						var inputDate = /^\d{2}\/\d{2}\/\d{4}$/.test(birthday);
					} else {
						var inputDate = '';
					}
					if (!inputDate) {
						message+= "Debe indicar una fecha de nacimiento de la mascota válida. ej. 16/04/2005. Mascota: "+i+"\n";
						allOk = false;
					}
					if(sex == 0) {
						message+= "Debe indicar el sexo de su mascota. Mascota: "+i+"\n";
						allOk = false;
					}
					if(sterilized == 0) {
						message+= "Debe indicar si su mascota está esterilizada o no. Mascota: "+i+"\n";
						allOk = false;
					}
					if(wetFood == 2 && dryFood == 2 && homemadeFood == 2) {
						message+= "Debe indicar al menos un tipo de alimento (Comida húmeda, Comida seca, Comida casera). Mascota: "+i+"\n";
						allOk = false;
					}
					if (allOk) {
						aPet.push(pet);
						breed = (breedDog != '') ? breedDog : breedCat;
						aBreed.push(breed);
						if(breedDog > 0 && size != 0){
							aSize.push(size);
							aHair.push(0);
						}
						if(breedCat > 0 && hair != 0){
							aHair.push(hair);
							aSize.push(0);
						}
						aNamePet.push(namePet);
						aBirthday.push(birthday);
						aSex.push(sex);
						aSterilized.push(sterilized);
						aWetFood.push(wetFood);
						aDryFood.push(dryFood);
						aHomemadeFood.push(homemadeFood);
					}
				}
			}
		}
		if (!emailCheck) message+= "Debe indicar un email válido.\n";
		if (!phoneCheck1) message+= "Debe indicar un numero de telefono fijo válido. Únicamente 9 dígitos.\n";
		if (!phoneCheck2) message+= "Debe indicar un numero de telefono movil válido. Únicamente 9 dígitos.\n";
		if (!condition) message+= "Debe aceptar las condiciones.";

		if (!message) {
			generateXml();
		} else {
			alert(message);
		}
	}
}

function generateXml() {
	$.post(BASE_PATH +'modules/_generatexml.php',{
			typeXml:			'5',
			nombre:				name,
			apellidos:			surname,
			telfijo:			phone1,
			telmovil:			phone2,
			email:				email,
			direccion:			address,
			cp:					zipCode,
			localidad:			city,
			provincia:			province,
			pais:				country,
			utilizarc:			usedRC,
			nperrosgatos:		numberPets,
			'tipoanimal[]':		aPet,
			'raza[]':			aBreed,
			'nombreanimal[]':	aNamePet,
			'fechanacimiento[]':aBirthday,
			'sexo[]':			aSex,
			'talla[]':			aSize,
			'pelo[]':			aHair,
			'esterilizado[]':	aSterilized,
			'alimentohumedo[]':	aWetFood,
			'alimentoseco[]':	aDryFood,
			'alimentocasero[]':	aHomemadeFood
		},
		function(request) {
			alert('Gracias por su consulta, en breve recibirá una respuesta.');
			window.location.reload();
		}
	);
}

function limitText(box, inputText) {
	var limitNum = 2000;
	if (($(box).val().length > limitNum && $(box).val() != inputText) || $(box).val() != '') {
		$(box).val($(box).val().substring(0,limitNum));
	} else {
		$(box).val(inputText);
	}
}

function generateFormPets() {
	var dataPet, dataPetHtml;
	numberPets = parseInt($('#numberPet').val());
	if(isNaN(numberPets)) {
		alert("El número de mascotas ha de ser entero y comprendido entre 1 y 10.");
	} else {
		if(numberPets > 10) {
			numberPets = 10;
		}
	}
	for (var i = 1; i<= 10; i++) {
		$('#dataPet_'+i).remove();
	}
	for (var i = 1; i<= numberPets; i++) {
		dataPet		= $('#divHidden').clone(false);
		dataPetHtml = $('#dataPet__ID_').html().replace(/_ID_/g, i);
		dataPet.attr('id','dataPet_'+i);
		dataPet.html(dataPetHtml);
		dataPet.insertBefore('#divHidden');
		dataPet.css('display','block');
		//namePet = $('#namePet').clone(false).insertAfter('#namePet');
		//$(namePet).attr('name','namePet['+i+']');
		//$('#dataPet').clone(true).insertAfter('#dataPet');
	}
	
}

function selectPet(listSelect, id) {
	$('#lrg_'+id).hide();
	$('#lrp_'+id).hide();
	$('#lrg_'+id+' select').attr('disabled','disabled');
	$('#lrp_'+id+' select').attr('disabled','disabled');
	if (listSelect.value=='1'){
		$('#lrp_'+id).show();
		$('#lrp_'+id+' select').attr('disabled','');
		$('#breedCat_'+id).val(0);
		$('#hair_'+id).val(0);
	} else if (listSelect.value=='2'){
		$('#lrg_'+id).show();
		$('#lrg_'+id+' select').attr('disabled','');
		$('#breedDog_'+id).val(0);
		$('#size_'+id).val(0);
	}
}
