
/* PARA jQuery
----------------------------------------------------------------------------- */

(function(jQuery) {
    
    jQuery.extend({
        
        // devuelve los elementos de una clase CSS
        getElementsByClassName : function(classname, node) {
            if(!node) node = document.getElementsByTagName("body")[0];
            var a = [];
            var re = new RegExp('\\b' + classname + '\\b');
            var els = node.getElementsByTagName("*");
            for(var i=0,j=els.length; i<j; i++)
                if(re.test(els[i].className)) a.push(els[i]);
            return a;
        }
        
    });
        
})(jQuery);
        

jQuery(document).ready(function(){
    
    /* foto-noticia */
    if(jQuery.getElementsByClassName('anythingSlider').length > 0){
        
	jQuery('.anythingSlider').anythingSlider({
		easing: "swing",        // Anything other than "linear" or "swing" requires the easing plugin
		autoPlay: false,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
		delay: 3000,                    // How long between slide transitions in AutoPlay mode
		startStopped: false,            // If autoPlay is on, this can force it to start stopped
		animationTime: 600,             // How long the slide transition takes
		hashTags: true,                 // Should links change the hashtag in the URL?
		buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
		pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
		startText: "Go",             // Start text
		stopText: "Stop"               // Stop text
		//navigationFormatter: formatText       // Details at the top of the file on this use (advanced use)
	});
    }
    
	/* paginación */
	jQuery('#thumbNav a').click(function(){
		actualizaVisitaOJD('');
	});
		
/*	jQuery(".lstBloqueCarousel-rollover .jcarousel-item").hover(
		function(){
			// Mostramos el rollover
			jQuery('#mosaico-'+this.id).stop().show().animate({
			opacity: 1
			}, 300);
		},
	    function(){
	        // Ocultamos el rollover
	        jQuery('#mosaico-'+this.id).stop().animate({
	          opacity: 0
	        }, 300, function() { jQuery(this).hide(); });
		}
	);*/
	
	jQuery(".lstBloqueCarousel-rollover .rollover-mosaico").hover(
		function(){
			jQuery("#"+this.id).stop().show().animate({ opacity: 1 }, 300);
		},
		function(){
			jQuery("#"+this.id).stop().show().animate({ opacity: 0 }, 300);
		}
	);

    /* paginación en bloques de galería (de 1 imagen) */
    jQuery('.cntBloqueGaleria .paginacionBloque a').click(function(){
        pagBloqueGaleria(jQuery(this));
        return false;
    });

});

/**
 * -----------------------------------------------------------------------------
 * Cambiar el botón de anterior del carousel, para que está activo o no
 **/
function pagBloqueGaleria(boton){

    // id del bloque
    var bloque = boton.closest('.cntBloqueGaleria').attr('id');
    var idBloque = bloque.split('_')[1];
    var tabla = bloque.split('_')[2];
    var id = bloque.split('_')[3];

    var img     = jQuery('#'+ bloque +' .cntImg img');
    var numImg  = jQuery('#'+ bloque +' .numImg').html();
    numImg      = parseInt(numImg) - 1;

    // indice de la imagen actual
    var cont = jQuery('#'+ bloque +' .cont').text();
    cont = parseInt(cont) - 1;
    
    // indice de la imagen que cargaremos
    if(boton.hasClass('sig')){ cont++; }else{ cont--; }
    
    // control según el nº de fotos
    if(cont >= 0 && cont <= numImg){

        img.fadeOut();
        jQuery('#'+ bloque +' .paginacionBloque a').addClass('btnInactivo');
        
        // ajax
        var dataString = 'cual=recargaBloqueMultimediaImg&idBloque='+ idBloque +'&cont='+ cont +'&tabla='+ tabla +'&id='+ id;
        jQuery.ajax({
            url: 'consultaAjax.php',
            data: dataString,
            dataType: 'json',
            success: function(data){
                if(data != ''){
                    // img
                    jQuery(img).attr('src', data['src']);
                    // título de la galería
                    jQuery('#'+ bloque +' h1 a').text(data['galeria']);
                    // link galeria
                    jQuery('#'+ bloque +' a').attr('href', data['ruta']);
                    // firma
                    jQuery('#'+ bloque +' .txtFirma').html(data['firma']);
                    // contador
                    jQuery('#'+ bloque +' .cont').html((cont + 1));
                    // fecha
                    jQuery('#'+ bloque +' .txtHora').html(data['fecha']);
                    // botones
                    if(cont > 0){
                        jQuery('#'+ bloque +' .ant').removeClass('btnInactivo');
                    }
                    if(cont < numImg){
                        jQuery('#'+ bloque +' .sig').removeClass('btnInactivo');
                    }
                    // actualizamos la visita
                    actualizaVisitaOJD('');
                }
            }
        });
        
        img.fadeIn();
    }
}


/* Cambiar el botón de anterior del carousel, para que está activo o no
----------------------------------------------------------------------------- */
function cambia_btn_ant(carousel, item, i, state, tipo){
	if(i == 1){
		jQuery('#mosaico-ant-'+tipo).stop().animate({ opacity: 0.3 }, 600);
	}else{
		jQuery('#mosaico-ant-'+tipo).stop().animate({ opacity: 1}, 300);
	}
}

/* Cambiar el botón de siguiente del carousel, para que está activo o no
----------------------------------------------------------------------------- */
function cambia_btn_sig(carousel, item, i, state, tipo){
	if(i == carousel.options.size){
		jQuery('#mosaico-sig-'+tipo).stop().animate({ opacity: 0.3 }, 600);
	}else{
		jQuery('#mosaico-sig-'+tipo).stop().animate({ opacity: 1}, 300);
	}
}

/* usamos initCallback callback para asignar controles de siguiente y anterior al carousel
----------------------------------------------------------------------------- */
function funciones_carousel(carousel, tipo) {
	jQuery('#mosaico-ant-'+tipo).bind('click', function() {
		carousel.prev();
		actualizaVisitaOJD('');
		return false;
	});
   jQuery('#mosaico-sig-'+tipo).bind('click', function() {
		carousel.next();
		actualizaVisitaOJD('');
		return false;
	});
}

function muestraComentario(id){
	jQuery('#comentario-'+ id).show().animate({ opacity: 1 }, 600);
	jQuery('#comentarioOculto-'+ id).hide().animate({ opacity: 0 }, 600);
	actualizaVisitaOJD('');
}


/* abre una ventana modal - jquery.simplemodal-1.3.5.min.js
----------------------------------------------------------------------------- */
function abrePopModal(ruta, alto, ancho, scroll){
	
	if(ruta.indexOf("#") == -1){
		jQuery.modal('<iframe src="'+ ruta +'" height="'+ alto +'" width="'+ ancho +'" scrolling="'+ scroll +'" style="border:0">', {
			closeHTML: '',
			closeClass: "modalClose",
			overlayClose: true,
			onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.data.hide();
				dialog.container.fadeIn('fast', function () {
					dialog.data.slideDown('fast');
					});
				});
			},
			onClose: function (dialog) {
				dialog.data.fadeOut('fast', function () {
					dialog.container.hide('fast', function () {
						dialog.overlay.slideUp('fast', function () {
							jQuery.modal.close();
						});
					});
				});
			}
		});
	}else{
		jQuery(ruta).modal( {
			minHeight: alto,
			minWidth: ancho,
			closeHTML: '',
			closeClass: "modalClose",
			overlayClose: true,
			onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.data.hide();
				dialog.container.fadeIn('fast', function () {
					dialog.data.slideDown('fast');
					});
				});
			},
			onClose: function (dialog) {
				dialog.data.fadeOut('fast', function () {
					dialog.container.hide('fast', function () {
						dialog.overlay.slideUp('fast', function () {
							jQuery.modal.close();
						});
					});
				});
			}
		});
	}
}

/* graba el voto del comentario
----------------------------------------------------------------------------- */
function grabaComentarioVoto(idPulgar, voto){	
	var idComentario = idPulgar.split("-")[1];
	dataStringComentariosVoto = "cual=comentarioVota&voto="+ voto +"&idComentario=" + idComentario;
	jQuery.ajax({
		type: "GET",
		url: "consultaAjax.php",
		data: dataStringComentariosVoto,
		success: function(cadena){
            
			if(cadena == 0){
				jQuery("#pulgar_1-"+ idComentario).animate({className: ''}, 500);
				jQuery("#pulgar_0-"+ idComentario).animate({className: ''}, 500);
				if(voto == 1){
					txt = "#txtVotosPos-"+idComentario;
				}else{
					txt = "#txtVotosNeg-"+idComentario;
				}
				jQuery(txt).html(parseInt(jQuery(txt).html()) + 1);
			}else{
				var aCadena = cadena.split("|||");
				if(aCadena[0] == 1){
					alert(aCadena[1]);
				}else{
					if(confirm(aCadena[1])){
						window.location.href  = aCadena[2];
					}
				}
			}
		}
	});
}


/* contador de caracteres #count_char
----------------------------------------------------------------------------- */		
function muestraCaracteresDisponibles(totales, nCharWrite, contador){
	var nChar = totales;
	if(nCharWrite > 0){
		nChar = (totales - nCharWrite) - 1;
	}
	if(nChar < 0){ nChar = 0; }
	jQuery('#'+ contador).html(nChar);
}


// AJAX para cada blog del bloque de WP de portada
//------------------------------------------------------------------------------
function lstBloqueCarousel_WP_itemLoadCallback(carousel, state){

    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    jQuery.get(
        "consultaAjax.php",
            {
            cual: "devuelveInfoBlogWP",
            first: carousel.first,
            last: carousel.last
            },
        function(xml) {
            lstBloqueCarousel_WP_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
}
function lstBloqueCarousel_WP_itemAddCallback(carousel, first, last, xml){
    // Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));

    jQuery('blog', xml).each(function(i) {
        carousel.add(first + i, jQuery(this).text());
    });
}

// AJUSTA el tamaño de un elemento
//------------------------------------------------------------------------------
function ajustaTamanoBloque(cual, alto, ancho){
    if(alto != ""){
        jQuery(cual).height(alto);
    }
    if(ancho != ""){
        jQuery(cual).width(ancho);
    }
}

// PARSEA una respuesta JSON
// The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
// -----------------------------------------------------------------------------
function ecg_parseJson(data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : 'Unspecified error' };
  }
  return eval('(' + data + ');');
}

// RECARGA el contenido de un bloque (p.ej. publicidad)
//------------------------------------------------------------------------------
function recargaElemento(idElemento){
    if(document.getElementById(idElemento)){
        var contenido = jQuery('#'+ idElemento).html();
        document.getElementById(idElemento).innerHTML = '';
        document.getElementById(idElemento).innerHTML = contenido;
    }
}

// RECARGA el contenido de una posición de banners
//------------------------------------------------------------------------------
function recargaBannerPosicion(idZona){
    var idPosicion = idZona.replace('bannerPos', '');
    
    jQuery.ajax({
        url: "consultaAjax.php",
        data: 'cual=recargaBanner&idMenu='+ idMenu +'&idPosicion='+ idPosicion,
        success: function(data){
            var result = ecg_parseJson(data);
            result = ecg_parseJson(result['data']);
            jQuery.each(result, function() {
                //alert(this['banners']);
                if(this['banners']){
                    //alert(this['idZona']);
                    //document.getElementById(idZona).parentNode.innerHTML = '';
                    jQuery('#'+ this['idZona']).html(this['banners']);
                }
            });
        }
    });
}
        
    /* FIN jQuery
----------------------------------------------------------------------------- */

