$(document).ready(function() {
	// Al hacer click en un menú
	$('body').on('click', '.menu', function(e) {
		$this = $(this);
		if ($this.hasClass('selected'))
			return false;
			
		//var url = $this.attr('rel');
		//console.log('url:' + url);
		
		//loadUrl(url, $('#content'));
		$('.selected').removeClass('selected');
		$this.addClass('selected');

		var $clone = $('#' + $('.selected:last').attr('rel')).clone().removeClass('hidden');
		//$('#content').html($clone);
		$('#content').html('');
		$('#content').append($clone);
		
		return false;
	});
	
	// Se empieza con el Inicio seleccionado
	$('.menu:first').click();
	//$('.menu[rel="contacto"]').click();
	
	// Al hacer click en el <li> de un submenu
	$('body').on('click', 'li', function(e) {
		var $this = $(this);
		$this.find('span').click();
		return false;
	});
	
	// Al hacer click en un submenú
	$('body').on('click', '.submenu', function(e) {
		$this = $(this);
		if ($this.hasClass('selected'))
			return false;
			
		//var url = $this.attr('rel');
		//console.log('url:' + url);
		
		//loadUrl(url, $('#content'));
		$('.selected').removeClass('selected');
		$this.addClass('selected');

		var $clone = $('#' + $('.selected').attr('rel')).clone().removeClass('hidden');
		$('#content').html($clone);
		
		$this.parent().parent().parent().find('span:first').addClass('selected');
		
		return false;
	});
	
	// Al hacer click en ver más info para el Agroshow
	$('body').on('click', '#promoagroshow', function(e) {
		$('.menu[rel="insumos"]').click();
	});
	
	// Al hacer click en insumos
	$('body').on('click', '.menu[rel="insumos"], .submenu[rel="insumos"]', function(e) {
		$('#insumos .contenido').hide();
		$('#insumos .producto:first').click();
	});
	
	// Al hacer click en algún producto
	$('body').on('click', '.producto', function(e) {
		var $this = $(this);
		var top = $this.offset().top + 5;
		$('#flecha').css('margin-top', top - 199);
		$('#insumos .contenido').hide();
		$('#' + $this.attr('id')).show();
		$('#insumos #contenidowrap').css('background-color', $('#' + $this.attr('id')).css('background-color'));
	});
	
	// Al hacer click en enviar el formulario de contacto
	$('body').on('click', '#contacto #enviar', function(e) {
		var nombre = $('#contacto #nombre').val();
		var email = $('#contacto #email').val();
		var mensaje = $('#contacto #mensaje').val();

		console.log('hola?');
		
		if (!errorAlValidar(nombre, email, mensaje)) {
			// el post
			var data = 'nombre=' + nombre + '&email=' + email + '&mensaje=' + mensaje;
			//$("#contacto #status").css('display', 'block');
			$("#contacto #status").html('Enviando mensaje...');
			$("#contacto #status").fadeIn('slow');
			
			setTimeout(function(){enviarcorreo(data)}, 2000);
			
			//setTimeout('enviarcorreo(nombre=' + nombre + '&email=' + email + '&mensaje=' + mensaje + ')', 2000);
		}
	});

});

errorAlValidar = function(nombre, email, mensaje) {
	var error = false;
	var nameError = false;
	// Si no se introdujo un nombre
	if (nombre == '') {
		$('#frmcontacto_nombre_error').html('Por favor introduzca su nombre.');
		nameError = true;
		error = true;
	}
	
	var mailError = false;
	// Si no se introdujo una dirección de correo
	if (email == '') {
		$('#frmcontacto_email_error').html('Por favor introduzca su correo electr&oacute;nico.');
		mailError = true;
		error = true;
	}
	
	// Si no se introdujo una dirección de correo válida
	if (!mailError) {
		if (!isValidEmail(email)) {
			$('#frmcontacto_email_error').html('Por favor introduzca una direcci&oacute;n de correo v&aacute;lida.');
			mailError = true;
			error = true;
		}
	}
	
	if (!nameError)
		$('#frmcontacto_nombre_error').html('');
		
	if (!mailError)
		$('#frmcontacto_email_error').html('');
	
	return error;
}

isValidEmail = function(email) {
	var splitted = email.match("^(.+)@(.+)$");
	if(splitted == null)
		return false;
	if (splitted[1] != null) {
		var regexp_user = /^\"?[\w-_\.]*\"?$/;
		if (splitted[1].match(regexp_user) == null)
			return false;
	}
	
	if (splitted[2] != null) {
		var regexp_domain = /^[\w-\.]*\.[A-Za-z]{2,4}$/;
		if (splitted[2].match(regexp_domain) == null) {
			var regexp_ip = /^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
			if(splitted[2].match(regexp_ip) == null)
				return false;
		}
		return true;
	}
	return false;
}

enviarcorreo = function(data) {
	$.ajax({
		type: 'POST',
		url: 'contact.php',
		data: data,
		cache: false,
		success: function(html) {
			$('#contacto #status').hide();
			$('#contacto #status').fadeIn('slow');
			if (html == 'ok') {
				$('#contacto #status').css('color', 'green');
				$('#contacto #status').html('Mensaje enviado. Gracias por contactarnos.');
				$('#contacto #nombre').val('');
				$('#contacto #email').val('');
				$('#contacto #mensaje').val('');
			}
			else {
				$('#contacto #status').css('color', 'red');
				$('#contacto #status').html('Hubo alg&uacute;n problema. Mensaje no enviado.');
			}
			setTimeout(function(){$("#contacto #status").fadeOut("slow")}, 4000);
			//$('#contacto #status').fadeOut('slow', 2000);
		}
	});
}

// La url que se quiere y el target donde se quiere mostrar el contenido cargado
loadUrl = function(url, $target) {
	$target.html('<div class="vcenter-container" style="height: 100%"><div class="vcenter"><img src="images/loading.gif" style="height: 100px" /></div></div>');
	$target.load(url + '#categorias');
};

