
var errorsValidacio = new Array();
$(document).ready(function() {
	$('#registro a.recordar-password').click(function() {
		$('#registro div.recordar-password').toggle();
		return false;
	});

	$('#registro button.recordar-password').click(function() {
		var $emailInput = $('#emailPassword');
		var email = $('#emailPassword').val();
		errorsValidacio = new Array();
		if (!email.testEmail()) {
			addError($emailInput.get(0), 'El email introducido no es correcto');
		} else {
			var urlAjax = siteRoot + "ajax/recordarPassword.php?email=" + email;
			var respuesta = ajaxAsincrono(urlAjax);
			if (respuesta == 'ok') {
				alert(txt_passwordEnviado + ' ' + email);
			} else {
				addError($emailInput.get(0), respuesta);
			}
		}
		if (errorsValidacio.length > 0) {
			presentarErrores();
		}
		return false;
	});

// Antes del submit del buscador de tiendas, si se ha indicado código postal, borrar provincia (si no, no aparecería nada)
	$('#tiendas').submit(function() {
		errorsValidacio = new Array();
		if ($('[name=cp]').val() == '') {
			if ($('[name=provincia]').val() == '') {
				addError($('[name=provincia]').get(0), txt_seleccionarProvincia);
				presentarErrores();
				return false;
			}
		} else {
			$('[name=provincia]').val('');
		}
		return true;
	});

// Si cambia la provincia, borrar el código postal (si no, no aparecería nada)
	$('#tiendas').find('[name=provincia]').change(function() {
		$('[name=cp]').val('');
		$('#tiendas').submit();
	});

// Utilizado en la página atletas para el div con los productos relacionados
// Puede utilizarse en otras, utilizando la clase "desplazable" en el div y desplazar-anterior/desplazar-siguiente en los links o buttons para desplazamiento
	var desplazables = new Desplazables();
	desplazables.init();

// Para la galeria de la home
	var galeriaImagenesHome = new Galeria();
	galeriaImagenesHome.init();

// Para el video de la home (es fancybox con width/height específicas)
	FancyboxWH.init();

// Para el resto de las fancybox
// OJO! Esto no me parece correcto: es para que no salga la scroll horizontal en los fancybox de productos
// En realidad sería mejor solucionarlo revisando el html de #contenidos (infoProducto.php y comprar.inc.php
	$('a.fancy').fancybox({
		'onComplete': function() {
			$('#fancybox-inner').css('overflow-x', 'hidden');
		}
	});

	$('#email').submit(onSubmitFormularioConAviso);
	
	$('#btn_contacto').live('click', function() {
			errorsValidacio = new Array();
			if (validarFormulario($('#contacte'))) {
				$('#contacte').submit();
			}
	});
	

	//$('form[name=form_distribuidores]').submit(onSubmitFormularioConAviso);
	
	$('#btn_distribuidores').live('click', function() {
			errorsValidacio = new Array();
			if (validarFormulario($('#contact'))) {
				if (confirm('En cumplimiento de lo establecido en la Ley 34/2002 de Servicio de la Sociedad de la Información y de Comercio Electrónico, mediante el presente envío Ud. Manifiesta expresamente su deseo de recibir comunicaciones comerciales mediante correo electrónico de las ofertas, promociones y nuevos productos de Original Buff, SA.'))
				$('#contact').submit();
			}
	});
	
	

	$('form[name=form_customized]').submit(onSubmitFormulario);

// Para las fotos de la sección empresa
	if ($('#fotos-empresa').length > 0) {
		var sliderManager = new SliderManager($('#fotos-empresa'), 'timeout'); // se puede poner click en lugar de timeout para activar la transición con click
		sliderManager.init();
	}

});


function ajaxAsincrono(urlAjax) {
	if (urlAjax.indexOf('/') != 0) {
		urlAjax = siteRoot + urlAjax;
	}
	var respuesta = '';
	$.ajax({
		async: false,
		url: urlAjax,
		success: function(data) {
			respuesta = data;
		}
	});
//	alert('url: ' + urlAjax + "\n" + respuesta);
	return respuesta;
}

function ajaxNoAsincrono(urlAjax) {
	if (urlAjax.indexOf('/') != 0) {
		urlAjax = siteRoot + urlAjax;
	}
	var respuesta = '';
	$.ajax({
		url: urlAjax,
		success: function(data) {
			respuesta = data;
		}
	});
//	alert('url: ' + urlAjax + "\n" + respuesta);
	return respuesta;
}

function onSubmitFormulario() {
	errorsValidacio = new Array();
	if (!validarFormulario($(this))) {
		return false;
	}
	return true;
}
function onSubmitFormularioConAviso() {
	errorsValidacio = new Array();
	if (!validarFormulario($(this))) {
		return false;
	}
	return confirm('En cumplimiento de lo establecido en la Ley 34/2002 de Servicio de la Sociedad de la Información y de Comercio Electrónico, mediante el presente envío Ud. Manifiesta expresamente su deseo de recibir comunicaciones comerciales mediante correo electrónico de las ofertas, promociones y nuevos productos de Original Buff, SA.');
}
function presentarError(txt) {
	errorsValidacio = new Array();
	errorsValidacio.push(txt);
	presentarErrores();
}
function presentarErrores() {
	var divErrores = $('#errores');
	if (errorsValidacio.length == 0) {
		divErrores.html('');
		divErrores.hide();
		return;
	}
	var txtErrors = obtenerErroresValidacion();
	var txtError = '';
	var i;
	if (divErrores.length > 0) {
		txtError = '<ul>';
		for (i = 0; i < txtErrors.length; i++) {
			txtError += ('<li>' + txtErrors[i] + '</li>');
		}
		txtError += '</ul>';
		divErrores.html(txtError);
	} else {
		txtError = '';
		for (i = 0; i < txtErrors.length; i++) {
			txtError += (txtErrors[i] + "\n");
		}
		alert(txtError);
	}
}
function validarFormulario(elForm) {
	var $e = elForm.find('.email');
	$e.each(comprobarEmail);
	var $obl = elForm.find('.obl');
	$obl.each(comprobarObligatorio);
	var $oblc = elForm.find('.oblc');
	$oblc.each(comprobarObligatorioCheck);
	if (errorsValidacio.length > 0) {
		presentarErrores();
		return false;
	}
	return true;
}
function trim(text) {
	var ultimoCaracter = -1;
	for (var i = text.length - 1; i >= 0; i--) {
		if (text.substring(i, i + 1) != "" && text.substring(i, i + 1) != "\n" && text.substring(i, i + 1) != "\t") {
			ultimoCaracter = i;
			return text.substring(0, ultimoCaracter + 1);
		}
	}
	return text;
}
function obtenerErroresValidacion() {
	var txtErrors = new Array();
	txtErrors.push(txt_seHanProducidoErrores);
	for (var i = 0; i < errorsValidacio.length; i++) {
		var t = errorsValidacio[i].split('|');
		var txt = '<span>' + trim(t[0]) + ":</span> ";
		if (t.length > 1) {
			txt += t[1];
		}
		txtErrors.push(txt);
	}
	txtErrors.push(txt_corrijaErrores);
	return txtErrors;
}
function comprobarEmail() {
	var $e = $(this);
	if (!$e.val().testEmail()) {
		addError(this, txt_emailIncorrecto);
	}
}
function comprobarObligatorio() {
	var $e = $(this);
	if (!$e.val()) {
		addError(this, txt_campoObligatorio);
	}
	
}

function comprobarObligatorioCheck() {
	var $e = $(this);
	if (!$e.attr('checked')) {
		addErrorCheck(this, txt_campoObligatorio);
	}
	
}

function addError(elem, txt) {
	errorsValidacio.push(buscarLabel(elem) + '|' + txt);
}

function addErrorCheck(elem, txt) {
	errorsValidacio.push(buscarLabelCheck(elem) + '|' + txt);
}

function buscarLabel(campoBuscado) {
	var labelEncontrada = '';
	$('label').each(function() {
						 
		if (this.htmlFor == campoBuscado.id) {
			labelEncontrada = this.innerHTML;
			var pos = labelEncontrada.indexOf('<');
			if (pos >= 0) {
				labelEncontrada = labelEncontrada.substring(0, pos);
			}
		}
	});
	return labelEncontrada;
}

function buscarLabelCheck(campoBuscado) {
	var labelEncontrada = '';
	labelEncontrada = document.getElementById("che").innerHTML;
	return labelEncontrada;
}

/////////////////////////////////////// Exclusivo de mongolGallery.php ///////////////////////////////////////
var galeria = 0;
function cargar (id_contenedor, flecha) {
	if (flecha=="right") {
			galeria++;
	} else {
			galeria--;
	}
	if (galeria!=0) {
		$("#left").show();
	} else {
		$("#left").hide();
	}

	if (galeria == paginasMongol.length - 1) {
		$("#right").hide();
	} else {
		$("#right").show();
	}
	var nuevasFotos = new Array();
	for (var imagen in paginasMongol[galeria]) {
		nuevasFotos.push(imagen);
	}
	$('#gallery_img').find('div').each(function(index) {
		var $this = $(this);
		var $linkCargar = $this.find('a');
		$linkCargar.click(function() {
			if (index < nuevasFotos.length) {
				return carga_imagen(nuevasFotos[index], paginasMongol[galeria][nuevasFotos[index]]);
			} else {
				return false;
			}
		});
		var $imgCargar = $this.find('img');
		if (index < nuevasFotos.length) {
			$imgCargar.attr('src', siteRoot + 'img/mongol_rally/small/' + nuevasFotos[index]);
			$imgCargar.show();
		} else {
			$imgCargar.hide();
			$imgCargar.attr('src', '');
		}
	});

}


function carga_imagen (imagen, nombre) {
	$("#big_photo").html('<img src="' + siteRoot + 'img/mongol_rally/big/'+imagen+'"/>');
	$("#autor").html('<div style="float:right" id="autor"><strong></strong></div>').delay(50);
	$("#autor").html('<strong>'+nombre+'</strong>');
	return false;
}
/////////////////////////////////////// FINAL Exclusivo de mongolGallery.php ///////////////////////////////////////


