//<!--
$(document).ready(function(){

	// ------------------ GENERICO ------------------
	
	// Muestra el contenido que se esconde a los usuarios sin javascript
	$('.hasjs').show();
	
	// ------------------ BIENVENIDA ------------------
	
	// Rota el fondo del texto de bienvenida
	$('#slideshow').cycle({timeout:  6000});
	
	// ------------------ FOTOS ------------------
	
	// Cerrar Lightbox: al hacer click sobre el fondo negro
	$(".lightbox_bg").click(function() {
		reset_form_values($(this).prev("div.lightbox"));
		$(this).fadeOut();
		$(this).prev("div.lightbox").fadeOut();
	});
	
	// Cerrar Lightbox: al hacer click sobre la cruceta
	$("p.close a").click(function() {
		reset_form_values($(this).parent().parent("div.lightbox"));
		$(this).parent().parent("div.lightbox").fadeOut();
		$(this).parent().parent("div.lightbox").next("div.lightbox_bg").fadeOut();
	});
	
	// ponemos todos los campos a null para no dejar valores residuales de formulario
	function reset_form_values(element) {
	
		element.find("input").each(function() {
			switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
				break;
			}
		});
	};
	
	(function($){

		// Obtener info sobre los divs anterior y posterior al actual
		get_div_info = function(current_div,last_div) {
			var divs = new Array(3);
			var id_current_div = current_div.split("_");
			
			// Previous div
			divs[0] = (id_current_div[1] == 1) ? last_div : id_current_div[0]+"_"+(parseInt(id_current_div[1])-1);
			// Current div
			divs[1] = current_div;
			// Next div
			divs[2] = (current_div == last_div) ? id_current_div[0]+"_1" : id_current_div[0]+"_"+(parseInt(id_current_div[1])+1);
			
			return divs;
		};
		
		// Navegar adelante o atrás en los thumbnails
		browse_gallery = function(current_div,last_div,direction) {
			
			var divs = get_div_info(current_div,last_div);
			
			//alert(divs[0]+"-"+divs[1]+"-"+divs[2]);
			
			$('#'+divs[1]).hide();
			
			switch(direction)
			{
				case 'fwd':
					$('#'+divs[2]).show();
					break;
				case 'bwd':
					$('#'+divs[0]).show();
					break;
			}
			
		};
		
		// Abrir la imagen a pantalla completa
		open_lightbox = function(current_div,last_div) {
			//IE patch
			$('#lb_bg_'+current_div).css('filter','alpha(opacity=80)');
			$('#lb_'+current_div+',#lb_bg_'+current_div).fadeIn('fast');			
			navigation_info(current_div,last_div);
			resize_image('#lb_'+current_div);
		};
		
		// Cerrar la imagen a pantalla completa
		close_lightbox = function(current_div) {
			$('#lb_'+current_div+',#lb_bg_'+current_div).fadeOut('fast');
			$('body').removeAttr('onkeydown');
		};
		
		// Navegar adelante o atrás en la imagen a pantalla completa
		browse_lightbox = function(current_div,last_div,direction) {
		
			var divs = get_div_info(current_div,last_div);
			
			$('#lb_'+divs[1]+',#lb_bg_'+divs[1]).hide();
			
			switch(direction)
			{
				case 'fwd':
					$('#lb_'+divs[2]+',#lb_bg_'+divs[2]).show();
					navigation_info(divs[2],last_div);
					resize_image('#lb_'+divs[2]);
					break;
				case 'bwd':
					$('#lb_'+divs[0]+',#lb_bg_'+divs[0]).show();
					navigation_info(divs[0],last_div);
					resize_image('#lb_'+divs[0]);
					break;
			}		
		};
		
		// Añadir evento al body para poder usar teclado para navegar en determinadas situaciones
		navigation_info = function(current_div,last_div) {
			$('body').attr('onkeydown', 'key_navigation(event,\''+current_div+'\',\''+last_div+'\');');
		};
		
		// Usar teclado para navegar en la imagen a pantalla completa
		key_navigation = function(event,current_div,last_div) {
			var key = ('which' in event) ? event.which : event.keyCode;
			switch(key)
			{
				// Izquierda, retroceder página
				case 37:
				case 33:
					browse_lightbox(current_div,last_div,'bwd');
					break;
				// Derecha, avanzar página
				case 39:
				case 34:
					browse_lightbox(current_div,last_div,'fwd');
					break;
				// Escape
				case 27:
					close_lightbox(current_div);
					break;
			}
			
			if(event.preventDefault) {
				event.preventDefault();
			} else {
				event.returnValue = false;
			}

		};
		
		//Adaptar tamaño de la imagen al tamaño de la pantalla
		resize_image = function(div) {
			
			image = $(div+' img');
			
			$(image).removeAttr("width",width);
			$(image).removeAttr("height",height);
			
			var width = $(image).width();
			var max_width = $(window).width()-200;
			var height = $(image).height();	
			var max_height = $(window).height()-200;
				
			if(height > max_height && width > max_width)
			{
				if(height > width) {
					width = Math.ceil(width / height * max_height);
					height = max_height;
				} else {
					height = Math.ceil(height / width * max_width);
					width = max_width;
				}
			} else if(height > max_height) {
				width = Math.ceil(width / height * max_height);
				height = max_height;
			} else if(width > max_width) {
				height = Math.ceil(height / width * max_width);
				width = max_width;
			}
			
			$(image).attr("width",width);
			$(image).attr("height",height);
			$(div).css("marginLeft",-((width/2)+44));
			$(div).css("marginTop",-((height/2)+68));
			
		};

	// ------------------ FORMULARIOS ------------------
		
		// Cambiar de tipo de formulario
		display_form = function(form) {
			switch(form) {
				case "order":
					$('#contact_form_order').show();
					$('#contact_form_query').hide();
					break;
				case "query":
					$('#contact_form_query').show();
					$('#contact_form_order').hide();
					break;
			}
			
		};
		
	})(jQuery);
	
	// Comprobar campos requeridos
	function required_field(field) {
		if($(field).val().length == 0)
		{
			$(field).addClass("error");
			$("#"+$(field).attr('id')+"_error_req").show();
			return false;
		} else {
			$(field).removeClass("error");
			$("#"+$(field).attr('id')+"_error_req").hide();
		}
		
		return true;
	};
	
	// Comprobar campos requeridos al perder foco
	$("div#edition input.required, div#edition textarea.required, #contact_form_order_name,#contact_form_order_phone,#contact_form_order_address,#contact_form_order_content,#contact_form_query_email,#contact_form_query_content")
		.bind("blur keyup",function() {
			required_field(this);
	});
	
	//Comprobar formato del teléfono
	function check_phone(field) {
		
		var regExp = /^[0-9]{9,9}/;
		
		if($(field).val().length != 0)
		{
			if(regExp.test($(field).val()) != true)
			{
				$(field).addClass("error");
				$("#"+$(field).attr('id')+"_error_phone").show();
				return false;
			} else {
				$(field).removeClass("error");
				$("#"+$(field).attr('id')+"_error_phone").hide();
			}
		}
		
		return true;
	};
	
	// Comprobar formato del teléfono al perder el foco
	$("div#edition .phone, #contact_form_order_phone,#contact_form_query_phone").blur(function(){
		check_phone(this);		
	});
	
	//Comprobar formato del email
	function check_email(field) {
		
		var regExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		
		if($(field).val().length != 0)
		{
			if(regExp.test($(field).val()) != true)
			{
				$(field).addClass("error");
				$("#"+$(field).attr('id')+"_error_email").show();
				return false;
			} else {
				$(field).removeClass("error");
				$("#"+$(field).attr('id')+"_error_email").hide();
			}
		}
		
		return true;
	};
	
	//Comprobar formato número con decimales
	function check_float(field) {
		
		var regExp = /^([0-9])*[,.]?[0-9]*$/;
		
		if($(field).val().length != 0)
		{
			if(regExp.test($(field).val()) != true)
			{
				$(field).addClass("error");
				$("#"+$(field).attr('id')+"_error_float").show();
				return false;
			} else {
				$(field).removeClass("error");
				$("#"+$(field).attr('id')+"_error_float").hide();
			}
		}
		
		return true;
	};
	
	//Comprobar formato número sin decumales
	function check_integer(field) {
		
		var regExp = /^[0-9]*$/;
		
		if($(field).val().length != 0)
		{
			if(regExp.test($(field).val()) != true)
			{
				$(field).addClass("error");
				$("#"+$(field).attr('id')+"_error_integer").show();
				return false;
			} else {
				$(field).removeClass("error");
				$("#"+$(field).attr('id')+"_error_integer").hide();
			}
		}
		
		return true;
	};
	
	// Comprobar formato del email al perder el foco
	$("div#edition .email, #contact_form_order_email,#contact_form_query_email").blur(function(){
		check_email(this);		
	});
	
	// Comprobar formato del un número con decimales al perder el foco
	$("div#edition input.float").blur(function(){
		check_float(this);		
	});
	
	// Comprobar formato del un número con decimales al perder el foco
	$("div#edition input.integer").blur(function(){
		check_float(this);		
	});
	
	// Validar formulario entero al hacer submit (Formulario de contacto)
	$("#contact_form_order,#contact_form_query").submit(function(){
		
		var check_result = true;
		
		switch($(this).attr('id'))
		{
			case "contact_form_order":
				$("#contact_form_order_name,#contact_form_order_phone,#contact_form_order_address,#contact_form_order_content").each(function() {
					check_result = (required_field(this) == true) ? check_result : false;
				});
				$("#contact_form_order_phone").each(function(){
					check_result = (check_phone(this) == true) ? check_result : false;
				});
				$("#contact_form_order_email").each(function(){
					check_result = (check_email(this) == true) ? check_result : false;
				});
				break;
			case "contact_form_query":
				$("#contact_form_query_email,#contact_form_query_content").each(function() {
					check_result = (required_field(this) == true) ? check_result : false;
				});
				$("#contact_form_query_phone").each(function(){
					check_result = (check_phone(this) == true) ? check_result : false;
				});
				$("#contact_form_query_email").each(function(){
					check_result = (check_email(this) == true) ? check_result : false;
				});
				break;
		}
		
		return check_result;
	});
	
	// Validar formulario entero al hacer submit (Panel de administración)
	$("div#edition form").submit(function(){
		
		var check_result = true;
		
		$(this).find("input.required, textarea.required").each(function() {
			check_result = (required_field(this) == true) ? check_result : false;
		});
		$(this).find("input.phone").each(function(){
			check_result = (check_phone(this) == true) ? check_result : false;
		});
		$(this).find("input.email").each(function(){
			check_result = (check_email(this) == true) ? check_result : false;
		});
		$(this).find("input.float").each(function(){
			check_result = (check_float(this) == true) ? check_result : false;
		});
		$(this).find("input.integer").each(function(){
			check_result = (check_integer(this) == true) ? check_result : false;
		});
		
		return check_result;
	});
	
	// Al seleccionar un tipo de static page
	$("select[name='edit_page_type'], select[name='add_page_type']").change(function(){
		switch($(this).find("option:selected").val()) {
			case "text":
				$(".static_page_text").show();
				$(".static_page_include").hide();
			break;
			case "include":
				$(".static_page_text").hide();
				$(".static_page_include").show();
			break;
		}
	});
	
	// Al seleccionar un tipo de precio (precio único o Pricechart)
	$("input.price_type").change(function(){
		$("input.price_type:checked").closest("span").addClass("prices");
		$("input.price_type:not(:checked)").closest("span").removeClass("prices");
	});
	
});

//--> 
