// Funciones Ajax
jQuery.noConflict();
jQuery(document).ready(function() {
	// LISTA SELECT SUBCATEGORIAS
	jQuery('.select_subcategorias_form').change(function() {
		document.location.href = document.location.href + jQuery(this).val();
	});
	
	// FUNCIÓN EMPLEADA EN LA SELECCION DE CATEGORIA/ESPECIALIDAD DE LA HOME
	jQuery('#select_categoria_form').change(function() {													 
		cargarContenido('/_libs/operaciones/home/lista_subcategorias.php?categoria=' + jQuery(this).val() + '&subcategoria=-1', 'lista_select_subcategorias', true);
	});
	
	// FUNCIÓN PARA MOSTRAR/OCULTAR EL TEXTO action_home
	jQuery('#mostrar_action_home').click(function() {
		if(jQuery('#action_home').css("display") == "none")	{									  
			jQuery('#mostrar_action_home').text("Ocultar más información");
			jQuery('#action_home').fadeIn('slow');
		} else {
			jQuery('#mostrar_action_home').text("Mostrar más información");
			jQuery('#action_home').fadeOut('slow');
		}
	});
	
	// VALIDACIÓN DE FORMULARIOS
	// Campos específicos creados dinámicamente
	jQuery('.option_radio_obligatorio').click(function() {
		var id_option = this.id;
		var campo = id_option.substr(0, id_option.lastIndexOf("_"));
		var campo_obligatorio_id = "#" + campo + "_obligatorio";
		jQuery(campo_obligatorio_id).val(jQuery("#" + id_option).val());
		
		// Si es el radiobutton 'otro' --> focus en campo texto
		var campo_texto_otro = "#" + campo + "_text";			
		if(jQuery("#" + id_option).val() == "otro") {
			jQuery(campo_texto_otro).focus();
		} else
			jQuery(campo_texto_otro).val("");		
			
	});	
	
	jQuery('.option_radio').click(function() {
		var id_option = this.id;
		var campo = id_option.substr(0, id_option.lastIndexOf("_"));
		var campo_obligatorio_id = "#" + campo + "_valor";
		jQuery(campo_obligatorio_id).val(jQuery("#" + id_option).val());
	});	
	
	jQuery('.option_checkbox_obligatorio').click(function() {
		var id_option = this.id;
		var campo = id_option.substr(0, id_option.lastIndexOf("_"));
		var campo_obligatorio_id = "#" + campo + "_obligatorio";
		
		// Compruebo si todos los campos checkbox estan activados (comparten una clase llamada como el contenido de 'campo')
		var clase_campos_checked = "." + campo;
		var activos = false;
		jQuery(clase_campos_checked).each(function() {
			activos = (jQuery("#" + this.id).val() == 1 || activos == true) ? true : false;
		});
		
		jQuery(campo_obligatorio_id).val(activos);
		
		// Si es el checkbox 'otro' --> focus en campo texto
		if(id_option.lastIndexOf("_otro") != -1) {
			var campo_texto_otro = "#" + campo + "_text";
			if(jQuery("#" + this.id).val() == 1)
				jQuery(campo_texto_otro).focus();
			else
				jQuery(campo_texto_otro).val("");
		}
	});
	
	/* LISTADO SUBCATEGORIAS REGISTRO */
	jQuery('.categoria_usuario').click(function() {
		var id_categoria = (this.id).substr((this.id).lastIndexOf("_")+1, (this.id).length);
		var id_lista_subcategoria = "subcategorias_" + id_categoria;
		
		if( ( jQuery("#li_" + this.id).css("list-style-image") ).lastIndexOf("menos") == -1) {
			jQuery("#li_" + this.id).css("list-style-image", "url(/css/images/menos.gif)");
			jQuery("#" + id_lista_subcategoria).show();
		} else {
			jQuery("#li_" + this.id).css("list-style-image", "url(/css/images/mas.gif)");
			jQuery("#" + id_lista_subcategoria).hide();
		}
		// jQuery("#" + id_lista_subcategoria).slideToggle("slow");
	});
	
	// AYUDA
	jQuery(".titulo_faq_pagina").click(function () {
		var respuesta = "#respuesta_" + this.id;
		jQuery(respuesta).toggle();
	});	
	
	// IMAGE TICKER
	if(jQuery('.imageTicker').length > 0) {
		jQuery('.imageTicker').easyticker({
			speed: 'slow',
			dureeAffichage: 10000
		});	
	}
	
	// FILTRO PROVEEDORES DESTACADOS CATEGORIA POR SUBCATEGORIA
	if(jQuery('#filtro_subcategorias').length > 0) {
		jQuery('#filtro_subcategorias').change(function() {
			jQuery('#filtro_subcategorias_proveedores').submit();
		});
	}
	
	// REPUTACION ONLINE PROVEEDORES
	var $caption, $cap = jQuery("<span/>").addClass("caption");

	// Hide all elements (it's possible to create Stars from hidden elements too)
	jQuery(".multiField").children().not("select, .messages_rating").hide();
	
	if(jQuery(".avg").length > 0)
		jQuery(".avg").stars();
	
	jQuery(".star_rating").each(function() {
		var id_star_rating = this.id;
		// Star Ratings
		$caption = $cap.clone();
		jQuery("#"+id_star_rating)
			.stars({
				inputType: "select",
				cancelValue: 999,
				cancelShow: false,
				captionEl: $caption,
				callback: function() {
					var valor_select = jQuery(this).val();
					var rate = valor_select.substring(0,1);
					var id_proveedor = valor_select.substring(valor_select.indexOf("_")+1,valor_select.lastIndexOf("_"));
					var id_categoria = valor_select.substr(valor_select.lastIndexOf("_")+1, valor_select.length);
					
					// Display message to the user at the begining of request
					jQuery("#messages_rating-" + id_proveedor + "-" + id_categoria).text("Guardando...").stop().css("opacity", 1).fadeIn(30);
			
					jQuery.post("/_libs/operaciones/star_rating/star_rating.php", {rate: rate, id_proveedor: id_proveedor, id_categoria: id_categoria}, function(db)
					{
							if(db == false)
								jQuery("#messages_rating-" + id_proveedor + "-" + id_categoria).text("Sólo se permite un voto por proveedor. Gracias.").stop().css("opacity", 1).fadeIn(30);
							else {
								// Select stars from "Average rating" control to match the returned average rating value
								jQuery("#avg_" + id_proveedor + "-" + id_categoria).stars("select", Math.round(db.avg));
								
								// Actualizar valoración media para todos los proveedores
								jQuery(".avg").each(function() {
									var id_star_avg = this.id;
									var id_proveedor_avg = id_star_avg.substring(id_star_avg.indexOf("_")+1,id_star_avg.indexOf("-"));
									var id_categoria_avg = id_star_avg.substr(id_star_avg.indexOf("-")+1, id_star_avg.length);
									jQuery("#" + id_star_avg).append("&nbsp;<img id='spinner_" + id_star_avg + "' src='/images/spinner.gif' />");
									jQuery.post("/_libs/operaciones/star_rating/avg_rating.php", {id_proveedor: id_proveedor_avg, id_categoria: id_categoria_avg}, function(db_avg) {
										jQuery("#" + id_star_avg).stars("select", db_avg.valoracion_proveedor);
										jQuery("#spinner_" + id_star_avg).remove();
									}, "json");
								});
								
								// Display confirmation message to the user
								jQuery("#messages_rating-" + id_proveedor + "-" + id_categoria).text("Valoración guardada (" + rate + "). Gracias.").stop().css("opacity", 1).fadeIn(30);
							}
							// Hide confirmation message and enable stars for "Rate this" control, after 2 sec...
							setTimeout(function(){
								jQuery("#messages_rating-" + id_proveedor + "-" + id_categoria).text('')
							}, 4000);
					}, "json");
				}
			})
			.append($caption);
	});	
	
});
