var activo = 1;

function marcarControl(carousel) {
	var index = carousel.first;
	
	$("#item-nav a").removeClass('activo');
	$("#item-nav a[rel=" + index + "]").addClass('activo');	
}

function carouselScroll(e) {
	e.preventDefault();
	
	var index = $(this).text(),
		index = parseFloat(index);
	$("#carousel").data('jcarousel').scroll(index);
}

function carouselInit(carousel) {
	var count = carousel.size(),
		i = 1;
		
	$("#carousel").parent().append('<div id="item-nav"></div>');
	
	for (i = 1; i <= count; i++) {
		$("#item-nav").append('<a href="#" rel="' + i + '">' + i + '</a>');
	}
	
	$("#item-nav a").click(carouselScroll);
	
	marcarControl(carousel);
}

function coleccionAnim() {
	
	var codigo = $("#coleccion li:nth-child(" + activo +") img").attr('alt');
	
	$("#coleccion img").animate({"width": 100, "height": 100, opacity: .5, top: 200}, 800);
	$("#coleccion li:nth-child(" + activo +") img").clearQueue().animate({"width": 500, "height": 500, opacity: 1, top: 0}, 800, "linear");
	
	$("#codigo").fadeOut(400, function() {
		$(this).text(codigo).fadeIn(400);
	});
}

function thumbsInit(carousel) {
	$("#thumbs-list li").click(function () {
		activo = $(this).index() + 1;
		
		carousel.scroll(activo);
		
		$("#coleccion").data('jcarousel').scroll(activo);
		coleccionAnim();
	});
}

function coleccionControl(carousel) {
	var current = carousel.first;
	
	//alert(current);
	$("#thumbs-list li").removeClass("activo");
	$("#thumbs-list li:nth-child(" + current + ")").addClass("activo");
}

function coleccionInit(carousel) {

	var codigo = $("#coleccion li:first img").attr('alt'),
		count = carousel.size();
	
	$("#codigo").text(codigo).fadeIn(400);
	
	$("#thumbs").append("<ul id='thumbs-list'></ul>");
	
	$("#coleccion").find('img').each(function () {
		var src = $(this).attr('src'),
			thumb = src.replace('imagen', 'thumb');
			
		$("#thumbs-list").append('<li><a><img src="' + thumb + '" alt="" /></a></li>');
	});
	
	$('#thumbs-list li:first-child').addClass('activo');

	$("#next").click(function (e) {
		if (activo < count) {
			activo = activo + 1;
			e.preventDefault();
			coleccionAnim();
			$("#thumbs-list").data('jcarousel').scroll(activo);
		}
	});
	
	$("#prev").click(function (e) {
		if (activo > 1) {
			activo = activo - 1;
			e.preventDefault();
			coleccionAnim();
			$("#thumbs-list").data('jcarousel').scroll(activo);
		}
	});
	
	$("#coleccion img").css({"width": 100, "height": 100, opacity: .5, top: 200});
	$("#coleccion li:nth-child(" + activo +") img").css({"width": 500, "height": 500, opacity: 1, top: 0});
	
	$("#thumbs-list").jcarousel({
		scroll: 4,
		animation: 300,
		setupCallback: thumbsInit,
		buttonNextHTML: '<a id="th-next">Siguiente</a>',
		buttonPrevHTML: '<a id="th-prev">Anterior</a>',
		itemFallbackDimension: 94
	});
}

function muestraError(msg) {
	$("#error").append(msg);
}

function evalForm(e) {
	e.preventDefault();
	
	var vacios = 0,
		errores = 0;
	
	$("#error").text('');
	
	$(this).find('input').each(function () {
		
		var name = $(this).attr('class');
		
		if (!$(this).val()) {
			vacios = vacios +1;
		}
		
		switch (name) {
			case "rut":
				var rut = $(this).val(),
					digito = $.Rut.getDigito(rut);
				
				if ($("#verificador").val() !== digito) { muestraError('Rut inválido. <br />'); errores = errores +1;}
				
				break;
			case "mail":
				var mail = $(this).val(),
					emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					
				if (!emailReg.test(mail)) { muestraError('Email inválido. <br />'); errores = errores +1 }
				break;
			case "fono":
				var numero = $(this).val(),
					numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
				
				if (!numberRegex.test(numero)) {
					if ($(this).attr('name') == 'fono') {
						muestraError('Teléfono inválido. <br />');
					} else {
						muestraError('RUT inválido. <br />');
					}
					errores = errores +1
				}
				break;
		}
	});
	
	if (vacios > 0) {
		$("#error").text('');
		muestraError("Complete todos los campos.");
	}
	
	if (vacios == 0 && errores == 0) {
		
		var method = $(this).attr('method'),
			action = $(this).attr('action'),
			info = $(this).serialize();
		
		$.ajax({
			url: action,
			type: "POST",
			data: $(this).serialize(),
			dataType: 'json',
			success: function (json) {
				if (json['exito']) {
					muestraError('Formulario enviado exitosamente');
					$('form input[type="text"]').val('');
					$('form textarea').text('');
				}
				if (json['error']) {
					muestraError('El formulario no se pudo enviar. Intente de nuevo.');
				}
			},
			error: function (jqXHR, textStatus, errorThrown) {
				muestraError('El formulario no se pudo enviar. Intente de nuevo.');
			}
		});
	}
}

$(document).ready(function () {
	$("#carousel").jcarousel({
		scroll: 1,
		animation: 800,
		setupCallback: carouselInit,
		itemFirstInCallback: marcarControl,
		itemFallbackDimension: 998
	});
	
	$("#coleccion").jcarousel({
		scroll: 1,
		animation: 800,
		setupCallback: coleccionInit,
		itemFirstOutCallback: coleccionControl,
		buttonNextHTML: '<a href="#" id="next">Siguiente</a>',
		buttonPrevHTML: '<a href="#" id="prev">Anterior</a>',
		itemFallbackDimension: 720
	});
	
	$("form").submit(evalForm);
});

