(function ($) {
  
  var $glosario = $("#glosario");
  
  if($glosario.size()) {
    
    
    // <patch # busqueda de tildes>
      // La idea de este parche es reescribir los ids a los que se les omitió tilde o ñ para facilitar la busqueda
      var dts = $(".lexicon-list").find("dt");
      dts.each(function(ev1, ev2) {
        var dt = $(this);
        var term = $.trim(dt.clone().children().remove().end().text());
        var term_clean = term.replace(/Á/g,"A").replace(/É/g,"E").replace(/Í/g,"I").replace(/Ó/g,"O").replace(/Ú/g,"U").replace(/Ñ/g,"N").replace(/ /g,"_");
        var $anchor = dt.find("a");
        $anchor.attr("id", term_clean);        
      });    
    // </patch # busqueda de tildes>
    
    // <patch # reubicación elementos con tilde>
      // Este parche reubica los elementos que inician con tilde
      var especial_anchors = $("#letter_á,#letter_é,#letter_í,#letter_ó,#letter_ú");
      especial_anchors.each(function(ev1, ev2) {
        var $anchor = $(this);
        var letter = $anchor.attr("id").replace("letter_","");
        letter = letter.replace(/á/g,"a").replace(/é/g,"e").replace(/í/g,"i").replace(/ó/g,"o").replace(/ú/g,"u");
        var $anchor_target = $("#letter_"+letter);
        var $h2 = $anchor.next();
        var $dl = $h2.next();        
        $anchor_target.next().next().append($dl.html());
        $anchor.remove();
        $h2.remove();
        $dl.remove();        
      });
      $("[href$=letter_á],[href$=letter_é],[href$=letter_í],[href$=letter_ó],[href$=letter_ú]").remove();
    // </patch # reubicación elementos con tilde>
    
    
    // <patch # reordenar elementos con tilde>
      // Por defecto los elementos no tienen en cuenta las tildes para ordenar.
      var $dls = $("dl");
      $dls.each(function(ev1, ev2) {
        var $dl = $(this);
        $dts = $(this).find("dt");
        var definitions = [];
        $dts.each(function(ev1, ev2) {
          var $dt = $(this);
          var definition = {
            def: $dt.find("a").attr("id").replace(/_/g," "),
            dt: $dt,
            dd: $dt.next()            
          };
          definitions.push(definition);
        });
        
        definitions.sort(function(x, y) {
          
          return x.def.localeCompare(y.def);
          
        });
        
        var definitions_html = "";
        for(var ind in definitions) {
          var definition = definitions[ind];
          definitions_html += "<dt>"+definition.dt.html()+"</dt><dd>"+definition.dd.html()+"</dd>"
        }
        $dl.html(definitions_html);
        
      });
    // </patch # reordenar elementos con tilde>
    
    
    
    // <patch # reordenar los enlaces>
      // Por defecto los elementos no tienen en cuenta las tildes para ordenar.
      var $links = $(".lexicon-links a");
      var links_html = $links.sort(function(x, y) {
        var x_text = $(x).attr("href");
        x_text = x_text.split("#");
        x_text = x_text[1].replace("letter_","");
        var y_text = $(y).attr("href");
        y_text = y_text.split("#");
        y_text = y_text[1].replace("letter_","");
        return x_text.localeCompare(y_text);
      });
      $(".lexicon-links").html(links_html);
    // </patch # reordenar los enlaces>
    
    
    var $links = $(".lexicon-links a");
    var $result_list = $(".lexicon-list");
    var $result_titles = $result_list.find(".lexicon-letter");
    var $result_words = $result_list.find("dl");
    var $result_everyword = $result_list.find("dd");
    var $result_everymeaning = $result_list.find("dt");
    
    var search_box = '<div class="search-box"><label for="glosary-search">Busqueda por palabra</label><input name="glosary-search" id="glosary-search"></input><button id="glosary-search-button">Buscar</button></div>';
    $result_list.before(search_box);
    var $searchbox = $("#glosary-search");
    var $searchbutton = $("#glosary-search-button");
    
    $searchbox.keypress(function(e) {
      if(e.which == 13) {
        $searchbutton.click();
      }
    });
    
    $searchbutton.click(function(ev) {
      ev.preventDefault();
      
      var search = $.trim($searchbox.val().toUpperCase());
      search = search.replace(/Á/g,"A").replace(/É/g,"E").replace(/Í/g,"I").replace(/Ó/g,"O").replace(/Ú/g,"U").replace(/Ñ/g,"N");
      search = search.replace(/ /g,"_");
      
      if(search == "") {
        $($(".lexicon-links a").eq(0)).click();            
      } else {
        $links.removeClass("active");
        policia_ocultar($result_titles);
        policia_mostrar($result_words);
        policia_ocultar($result_everyword);
        policia_ocultar($result_everymeaning);
        var $found = $('dt a[id*="'+search+'"]');
        var $foundword = $found.parent();
        var $foundmeaning = $foundword.next();
        policia_mostrar($foundword);
        policia_mostrar($foundmeaning);
      }
    });
    
    
    $links.click(function(ev) {
      ev.preventDefault();
      
      // Iniciamos busqueda por letra
      policia_mostrar($result_everyword);
      policia_mostrar($result_everymeaning);
      
      var $link = $(this);
      var $anchor = $("a#"+$link.attr("href").split("#")[1]);
      var $current_title = $anchor.next();
      var $current_words = $current_title.next();
      
      $links.removeClass("active");
      policia_ocultar($result_titles);
      policia_ocultar($result_words);      
      
      $link.addClass("active");
      policia_mostrar($current_title);
      policia_mostrar($current_words);
      
    });
    
    $($(".lexicon-links a").eq(0)).click();
    
  }
  
}(jQuery));

function policia_ocultar($elements) {
  
  $elements.hide();
  
}

function policia_mostrar($elements) {
  
  $elements.show();
  
}