$(document).ready(function() {
  // url = 'http://localhost/bvmcttt/';
  //url = 'http://localhost/cervantesvirtual.com/';
  // url = 'http://bvmcttt.dev.cervantesvirtual.com/';
  url = 'http://'+document.domain+'/';

  if (top.location.href != self.location.href) {
    top.location.href = self.location.href; 
  }
	
	//tabs
				$("#inicio .tabs").tabs(".panel",{
					effect: "default"
				});
    // links externos
    $('a[rel=external]').live('click', function() {
      $(this).attr('target', '_blank');
    });

    // scrollable 
    if ($(".bloqueCovers .scrollable").length > 0) {

        $(".bloqueCovers .scrollable").scrollable({
            speed: 1000,
            size: 3,
			clickable:false
        });

		$(".bloqueCovers .nextPage").unbind('click');
		$(".bloqueCovers .nextPage").click(function(e){
			var api = $(".bloqueCovers .scrollable").data("scrollable");
				var clase='z-'+(api.getPageIndex()+1);
				if( $("."+clase).length >0 || $(".z-fin").length >0){
					api.nextPage();
					if( $(".z-fin").length <= 0){
							$(".bloqueCovers .nextPage").removeClass("disabled");
					}
				}else {
					$(".bloqueCovers .prevPage").css("visibility","visible");
					$.get(url+'controladores/destacados-ajax.php',{p: api.getPageIndex()+1}, function(data) {
						api.getItemWrap().append(data);
						api.reload().end();
						if( $(".z-fin").length >0){
							$(".bloqueCovers .nextPage").addClass("disabled");
						}
						else{
							$(".bloqueCovers .nextPage").removeClass("disabled");
						}
					});
				}
		});
    }
	 if ($(".videos .scrollable").length > 0) {
        $(".videos .scrollable").scrollable({
            speed: 1000,
            size: 3,
            clickable:false
        });
        $(".videos .nextPage").unbind('click');
		$(".videos .nextPage").click(function(e){
			var api = $(".videos .scrollable").data("scrollable");
				var clase='z-'+(api.getPageIndex()+1);
				if( $("."+clase).length >0 || $(".z-fin").length >0){
					api.nextPage();
					if( $(".z-fin").length <= 0){
							$(".videos .nextPage").removeClass("disabled");
					}
				}else {
					$(".videos .prevPage").css("visibility","visible");
					$.get(url+'controladores/videos-ajax.php',{p: api.getPageIndex()+1}, function(data) {
						api.getItemWrap().append(data);
						api.reload().end();
						if( $(".z-fin").length >0){
							$(".videos .nextPage").addClass("disabled");
						}
						else{
							$(".videos .nextPage").removeClass("disabled");
						}
					});
					
				}
		});
     }	
	//scrollable obra
	if ($(".fichaLibro .scrollable").length > 0) {
	
        $(".scrollable").scrollable({
            speed: 1000,
            size: 1,
			clickable:false
			
        });

		$(".prevPage").click(function(){	
		  var api = $(".fichaLibro .scrollable").data("scrollable");
    });

	$(".nextPage").unbind('click');
		$(".nextPage").click(function(e){

			var api = $(".fichaLibro .scrollable").data("scrollable");
				if(api.getIndex()+1 == api.getSize()){
					$.get(url+'controladores/paginas-ajax.php',{slug: $('.fichaLibro').attr('rel'),p: api.getSize()}, function(data) {
						api.getItemWrap().append(data);
						api.reload().end();
					});
				}
				else{
					api.next();
				}
		});
    }
    //ventana modal
    if ($("a.modal").length > 0) {
      $("a.modal").fancybox({
		'width'			: 640,
		'height'          	: 360,
		'autoDimensions' 	: true,
       'autoScale'     	: true,
        	'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'			: 'iframe',
		'onCleanup' : function() {
                               			 $("#fancybox-inner").empty();
                           		 }
	});

    }
    if ($("a.modal2").length > 0) {

      	$("a.modal2").fancybox({
	      	'width'			: 450,
	      	'height'		: 370,
	    	   'autoDimensions'	: true,
		      'autoScale'     	: true,
		      'transitionIn'	    	: 'none',
	    	   'transitionOut'		: 'none',
	    	   'type'			: 'iframe',
	    	   'onCleanup' : function() {
                                  	 	$("#fancybox-inner").empty();
                               	 	 }
	});

    }
    //tooltips
    $('.checks_columna .tip').each(function() {

        $(this).qtip({
            style: {
                name: 'dark',
                tip: true,
                'color': '#ffffff',
                'text-align': 'center',
                'font-family': 'Arial'
            },
            content: $(this).text(),
            position: {
                adjust: {
                    screen: true
                }
            }
        });
    });
    $('a[title].tip').qtip({
        style: {
            name: 'dark',
            tip: true
        },
        position: {
            adjust: {
                screen: true
            }
        }
    })
	 $('img.tip').qtip({
		content: {text: $(this).attr("alt")},
        style: {
            name: 'dark',
            tip: true
        },
        position: {
            adjust: {
                screen: true
            }
        }
    })

    //facetado
    // formulario superior
    var bg = $('#buscarGeneral');
		var bp = $('#buscarPortales');
		var ba = $('#buscarArchivo');
    var otros = $('#buscarBiblioteca, #buscarHemeroteca, #buscarMultimedia');
    bg.click(function() {
        if (otros.is(':ckecked')) {
            otros.attr('checked', false);
        }
				if (bp.is(':checked')) {
						bp.attr('checked', false);
				}
				if (ba.is(':checked')) {
						ba.attr('checked', false);
				}
      //  colorear_buscador(bg, '0 0', url+"images/buscar-azul.jpg", "#36578C");
        comprobar_checks();
    });
    bp.click(function() {
        if (otros.is(':ckecked')) {
            otros.attr('checked', false);
        }
				if (bg.is(':checked')) {
						bg.attr('checked', false);
				}
				if (ba.is(':checked')) {
						ba.attr('checked', false);
				}
      //  colorear_buscador(bp, '0 -25px', url+"images/buscar-naranja.jpg", "#E77D0D");
        comprobar_checks();
    });
    ba.click(function() {
        if (otros.is(':ckecked')) {
            otros.attr('checked', false);
        }
				if (bp.is(':checked')) {
						bp.attr('checked', false);
				}
				if (bg.is(':checked')) {
						bg.attr('checked', false);
				}
     //   colorear_buscador(ba, '0 -50px', url+"images/buscar-verde.jpg", "#7D8E28");
        comprobar_checks();
    });
    otros.click(function() {
        if (bg.is(':ckecked')) {
            bg.attr('checked', false);
        }
				if (bp.is(':checked')) {
						bp.attr('checked', false);
				}
				if (ba.is(':checked')) {
						ba.attr('checked', false);
				}
        comprobar_checks();
    });

    function comprobar_checks() {
        if (!bg.is(':checked') && !otros.is(':checked') && !bp.is(':checked') && !ba.is(':checked')) {
            // no hay ninguno activado. Activamos bg.
            bg.attr('checked', true);
            colorear_buscador(bg, '0 0', url+"images/buscar2.png", "#0154e2");
          //  colorear_buscador(bg, '0 0px');
        } else {
          if (bg.is(':checked')) {colorear_buscador(bg, '0 0', url+"images/buscar2.png", "#0154e2");}
          if (bp.is(':checked')) {colorear_buscador(bp, '0 -25px', url+"images/buscar2.png", "#9746BF");}
          if (ba.is(':checked')) {colorear_buscador(ba, '0 -50px', url+"images/buscar2.png", "#da3926");}
        }
    }

    function colorear_buscador(el, offset, imgboton, colorback) {
        $('.checks label').removeClass('actual');
        el.parent().addClass('actual');
        //$('.inputs').css('background-color', el.parent().css('background-color'));
        $('.inputs #cadena').css('background-position', offset);
        $(".inputs .boton").attr("src", imgboton);
    	$(".inputs div").css("background-color", colorback);
    }

    // formulario columna derecha
    var bg_col = $('#buscarGeneral_col');
    var otros_col = $('#buscarBiblioteca_col, #buscarHemeroteca_col, #buscarMultimedia_col');
		var bp_col = $('#buscarPortales_col');
		var ba_col = $('#buscarArchivo_col');
    comprobar_checks_col();
    //activamos bg por defecto.
    bg_col.click(function() {
        if (otros_col.is(':ckecked')) {
            otros_col.attr('checked', false);
        }
				if (bp_col.is(':checked')) {
						bp_col.attr('checked', false);
				}
				if (ba_col.is(':checked')) {
						ba_col.attr('checked', false);
				}
        comprobar_checks_col();
    });
    bp_col.click(function() {
        if (otros_col.is(':ckecked')) {
            otros_col.attr('checked', false);
        }
				if (bg_col.is(':checked')) {
						bg_col.attr('checked', false);
				}
				if (ba_col.is(':checked')) {
						ba_col.attr('checked', false);
				}
        comprobar_checks_col();
    });
    ba_col.click(function() {
        if (otros_col.is(':ckecked')) {
            otros_col.attr('checked', false);
        }
				if (bp_col.is(':checked')) {
						bp_col.attr('checked', false);
				}
				if (bg_col.is(':checked')) {
						bg_col.attr('checked', false);
				}
        comprobar_checks_col();
    });
    otros_col.click(function() {
        if (bg_col.is(':ckecked')) {
            bg_col.attr('checked', false);
        }
				if (bp_col.is(':checked')) {
						bp_col.attr('checked', false);
				}
				if (ba_col.is(':checked')) {
						ba_col.attr('checked', false);
				}
        comprobar_checks_col();
    });

    function comprobar_checks_col() {
        if (!bg_col.is(':checked') && !otros_col.is(':checked') && !bp_col.is(':checked') && !ba_col.is(':checked')) {
            // no hay ninguno activado. Activamos bg.
            bg_col.attr('checked', true);
        }
    }

    //inicio
    comprobar_checks();
    //activamos bg por defecto.
    comprobar_checks_col();
    //activamos bg_col por defecto.
		

		
		// Contenidos AJAX coincidencias del texto y paginación
		$('.enlace_contenidos').click(function() {
		  id = $(this).attr('id');
		  q = $('#cadena').val();
		  $('#resultados-contenidos').hide('fast');
		  $('#ajax-loader'+id).show();
		  $('#resultados-contenidos').load(url+'contenidos/', {'id': id, 'q': q}, function() {
		    $('.listaItems, #paginacion1').hide('slow');
				$('#resultados-contenidos').show('slow');
  		  $('#ajax-loader'+id).hide();
        $('#boton-volver').click(function () {
  		    $('.listaItems, #paginacion1').show('slow');
  				$('#resultados-contenidos').hide('slow');
  				return false;         
        });
        // nuevos triggers para nuevos elementos.
        $('#paginacion2 a.paginacion_num, #paginacion2 a.paginacion_anterior, #paginacion2 a.paginacion_siguiente').live('click', function(){
    		  p = $(this).html();
    		  actual = parseInt($('#paginacion2 .paginacion_numActual').html());
    		  tipo = $(this).attr('class');
    		  $('#resultados_textos p.texto-coincidencia').hide('slow');
    		  $('#paginacion2 img').show();
    		  if (tipo == 'paginacion_num') {
      		  $('#resultados_textos').load(url+'contenidos/ #resultados_textos', {'id': id, 'q': q, 'p': p}, function() {
      		    $('#resultados_textos p.texto-coincidencia').show('slow');
      		  });
    		  } else if (tipo == 'paginacion_anterior') {
      		  $('#resultados_textos').load(url+'contenidos/ #resultados_textos', {'id': id, 'q': q, 'p': actual-1}, function() {
      		    $('#resultados_textos p.texto-coincidencia').show('slow');
      		  });
    		  } else {
      		  $('#resultados_textos').load(url+'contenidos/ #resultados_textos', {'id': id, 'q': q, 'p': actual+1}, function() {
      		    $('#resultados_textos p.texto-coincidencia').show('slow');
      		  });
    		  }
    		});
        // callback para scrollable
        //scrollable obra
      	if ($(".fichaLibro .scrollable").length > 0) {

              $(".scrollable").scrollable({
                  speed: 1000,
                  size: 1,
      			clickable:false

              });
      		$(".nextPage").click(function(){
      			var api = $(".fichaLibro .scrollable").data("scrollable");
      				if(api.getIndex() == api.getSize()-1){
      					$.get(url+'controladores/paginas-ajax.php',{slug: $('.fichaLibro').attr('rel'),p: api.getSize()}, function(data) {
      						api.getItemWrap().append(data);
      						api.reload().end();
      					});
      					return false;
      				}
      		});

          }
      	
			});
			return false;
		});

		//ÁREAS
		//árbol
    $('li img').live('click', function(){
      
      idExpand = new String($(this).attr('class'));
      idE = idExpand.split(' ');
      idRama = idE[1];

      bullet = idE[0];
      if (bullet == 'mas') {
        if ($('ul.'+idRama).html()) {
          $('.mas.'+idRama).hide();
          $('.menos.'+idRama).show();
          $('ul.'+idRama).show('slow');
        } else {
          $('#carga'+idRama).show();
          $('ul.'+idRama).load(url+'areas-ajax-desplegar/', {'mas': idRama}, function(){
            $('.mas.'+idRama).hide();
            $('.menos.'+idRama).show();
            $('#carga'+idRama).hide();
            $('ul.'+idRama).show('slow');
          });          
        }
      } else { //bullet == 'menos'
        $('.mas.'+idRama).show();
        $('.menos.'+idRama).hide();
        $('ul.'+idRama).hide('slow');        
      }
    });
		//zona de carga junto al árbol
    $('.arbol a').live('click', function(){

      id = $(this).attr('id');

      $('#datos-portal').hide('fast');
      $('#content-ajax-loader').show();
      $.ajax({
        url: url+'areas-ajax/',
        data: {'portal': id},
        type: 'post',
        success: function(data){
          $('#datos-portal').html(data);
          $('#content-ajax-loader').hide();
          $('#datos-portal').show('fast');
          pagina = $('#localizador').attr('rel');
          $('#localizador').load(pagina, function(response, status, xhr){
            if (status == "error") {
              $('.itemLocalizacion').hide('fast');
            }
          });
        }
      });
    });
		//localizador
    localizadores = $('.localizador');
    $.each(localizadores, function(){
      pagina = $(this).attr('rel');
      $(this).load(pagina);
    });
    
    //iframe auto height
    jQuery('iframe').iframeAutoHeight();
    
});

//Cross-site Ajax :P
jQuery.ajax = (function(_ajax){
    
    var protocol = location.protocol,
        hostname = location.hostname,
        exRegex = RegExp(protocol + '//' + hostname),
        YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
        query = 'select * from html where url="{URL}" and xpath="*"';
    
    function isExternal(url) {
        return !exRegex.test(url) && /:\/\//.test(url);
    }
    
    return function(o) {
        
        var url = o.url;
        
        if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
            
            // Manipular opciones para que las peticiones JSONP-x se hagan a YQL

            o.url = YQL;
            o.dataType = 'json';
            
            o.data = {
                q: query.replace(
                    '{URL}',
                    url + (o.data ?
                        (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
                    : '')
                ),
                format: 'xml'
            };
            
            // Como es una petición JSONP
            // complete === success
            if (!o.success && o.complete) {
                o.success = o.complete;
                delete o.complete;
            }
            
            o.success = (function(_success){
                return function(data) {
                    
                    if (_success) {
                        // Fingimos llamada a XHR
                        _success.call(this, {
                            responseText: data.results[0]
                                // YQL la jode con <script>s
                                // Tomamos medidas
                                .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
                        }, 'success');
                    }
                    
                };
            })(o.success);
            
        }
        
        return _ajax.apply(this, arguments);
        
    };
    
})(jQuery.ajax);

