$(document).ready(function(){
  	var mozL10n = document.mozL10n || document.webL10n;
  	var empty_msg = mozL10n.get('empty_msg', null, 'Field is empty.');
  	var nav_page = mozL10n.get('nav_page', null, 'Page');
    var connect_msg = mozL10n.get('connect_msg', null, 'Network connection unavailable.');
    var find_msg = mozL10n.get('find_msg', null, 'Searching results…');
    var no_result = mozL10n.get('no_result', null, 'No results were found, try another search.');
    var error_inesp = mozL10n.get('error_inesp', null, 'An unexpected error occurred, will try again.');
    var result_cero = mozL10n.get('result_cero', null, 'No results were found...');
	  
    var total_page = 1;
    var show_page = 1;
    function mostrar_error(texto,search){
      	if (typeof search != "undefined")
      	{
	        if (search != ""){
	          	$('.ui.error.message').hide();
	          	return true;
	        }else{
	          	$('.ui.error.message ul li font font').html(texto)
	          	$('.ui.error.message').show();
	          	$('.close.icon.error.message').click(function(){
	            	$('.ui.error.message').hide();
	          	});
	          	return false;
	        }
	      }else{
	          	$('.ui.error.message ul li font font').html(texto)
	          	$('.ui.error.message').show();
	          	$('.close.icon.error.message').click(function(){
	            	$('.ui.error.message').hide();
	          	});
	          	return false;
      	}
    }
    function search_data(uri_encode){
      	var data = {
        	'search': uri_encode,
        	'show_page': show_page
      	};
      	var valid = mostrar_error(empty_msg, data.search);
      	if (valid == true)
        	pdf_buscador(data);  
    }
    $('.search.link.icon').click(function(){
      	var uri_encode = encodeURIComponent($('#search').val());
      	search_data(uri_encode);
    });

    $('#search').keypress(function(event){  
        var keycode = (event.keyCode ? event.keyCode : event.which);  
        if(keycode == '13'){  
          	var uri_encode = encodeURIComponent($('#search').val());
      		search_data(uri_encode);
        }
    });  
    function obt_data(){
      var data = {
        'search': $('#search').val(),
        'show_page': parseInt($('.page.pagination.online b').html())
      };
      return data
    }
    var data = obt_data();
    $('.ui.icon.button.refresh').click(function(){
      if ($('.ui.inbox.list.active').attr("data-tab") == "saved")
        pdf_buscador(data);
    });
    $('.ui.pagination.online .item.page_prev').click(function(){  
        if(!$('.ui.pagination.online .item.page_prev').hasClass('disabled')){
          var data = obt_data();
          data.show_page -= 1;
          $('.page.pagination.online b').html(''+data.show_page+'');
          if(data.show_page == 1)        
            $('.ui.pagination.online .item.page_prev').addClass("disabled");
          pdf_buscador(data);
          $('.ui.pagination.online .item.page_next').removeClass("disabled");
        }    
      });
      $('.ui.pagination.online .item.page_next').click(function(){
        if(!$('.ui.pagination.online .item.page_next').hasClass('disabled')){
          var data = obt_data();
          data.show_page += 1;
          $('.page.pagination.online b').html(''+data.show_page+'');
          if (data.show_page == 10)
            $('.ui.pagination.online .item.page_next').addClass("disabled");
          pdf_buscador(data);
          $('.ui.pagination.online .item.page_prev').removeClass("disabled");
        }
      });
    function pdf_buscador(busqueda) {
        if (navigator.onLine === false) {
          mostrar_error(connect_msg);
        } else {
          $('.ui.inbox.list.active').html('<a id="Message" class="active item">'+find_msg+'</a>');
          $('.ui.segment.loader_pdf').show();
          $.getJSON(
          "http://pdfviewer2.appspot.com/buscador/generar/",
          busqueda,
          function (data) {
              if (data != undefined && data.success == true) {
                  for (link in data.link){
                    $('.ui.inbox.list.active').attr("data-tab","saved").append(''+
                      '<a id="'+data.link[link]+'" class="item online">'+
                        '<div class="right floated date"> - Tipo: Online</div>'+
                        '<div class="left floated ui star rating"><img src="./images/pdf.png" style=" width: 45px;"></i></div>'+
                        '<div class="description">' + link + '</div>'+
                      '</a>'
                    ); 
                  }
                  $('#Message').remove();
                  $('.ui.segment.loader_pdf').hide();
                  $('.ui.inbox.list a.online').click(function(){
                      var openURL = new MozActivity({
                          name: "view",
                          data: {
                              type: "application/pdf",
                              url: $(this).attr('id')
                          }
                      });
                  });
                  $('.page.pagination.online').html(''+nav_page+' <b>'+data.show_page+'</b> / 10')
                  $('.ui.pagination.online .item.page_next').removeClass("disabled");
              }else{
                  
                  if(data.error == "no_result"){
                      mostrar_error(no_result);
                  }
                  else{
                      mostrar_error(error_inesp);
                  }        	
                  $('.ui.inbox.list.active').html('<a id="Message" class="active item">'+result_cero+'</a>');
                  $('.ui.segment.loader_pdf').hide(); 
              }
          }
      )
          .error(function () {
              mostrar_error(error_inesp);
              $('.ui.inbox.list.active').html('<a id="Message" class="active item">'+result_cero+'</a>');
              $('.ui.segment.loader_pdf').hide(); 
          })
        }
    }
});