var directoryconfig = {
  numberOfResultsPerPage: 20
};

var directoryResults = [];

(function ($) {
  
  $directory = $(".directory");
  
  var $selectores = $directory.find("input[name=filter_by]");
  var $unblockers = $(".unblocker");
  var $filters = $directory.find(".filter");  
  var $tbody = $directory.find(".results .content");
  var $inplacefilters = $directory.find(".inplace-filters");
  var $searchbutton = $directory.find("button");
  
  var $inplacefilter_direcciones = $(".inplace-filter.direcciones");
  var $inplacefilter_oficinasasesoras = $(".inplace-filter.oficinasasesoras");
  var $inplacefilter_metropolitanas = $(".inplace-filter.metropolitanas");
  var $inplacefilter_escuelas = $(".inplace-filter.escuelas");
  
  $unblockers.click(function(ev) {
    var $element = $(this);
    $element.closest(".filter").find("input[name=filter_by]").attr("checked", "checked").click();
  });
  
  
  $selectores.click(function(ev) {
    $filters.addClass("disabled");
    $filters.find("select").attr("DISABLED","DISABLED");
    $filters.find("input[type=text]").attr("DISABLED","DISABLED");
    
    $selector = $(this);
    var $filter = $selector.closest(".filter");
    $filter.removeClass("disabled");
    $filter.find("select").removeAttr("DISABLED");
    $filter.find("input[type=text]").removeAttr("DISABLED");
    
    policia_evaluar_visibilidad_inplace_filters();
    
  });
  
  $selectores.closest(".filter").find("select").change(function() {
    policia_evaluar_visibilidad_inplace_filters();
  });
  
  $(".directory input[name=filter_by]:checked").click(); 
  //$directory.find("input[name=filter_by]:checked").show();
  
  $("input[name=custom_search]").keypress(function(e) {
    if(e.which == 13) {
      $searchbutton.click();
    }
  });
  
  
  $searchbutton.click(function(ev) {
    $(".message_box.start").hide();
    ev.preventDefault();
    
    $inputbox = $directory.find("input[name=filter_by]:checked");
    
    if($inputbox.val() == "unity_type" || $inputbox.val() == "place") {
      
      var $select = $inputbox.closest(".filter").find("select");
      var $option = $select.find(":selected");
      var valor = $option.attr("value").split("_");
      
    } else if ($inputbox.val() == "custom_search") {
      
      var $text = $inputbox.closest(".filter").find("input[type=text]");
      var valor = $text.val();
      
    }
      
    var path = "";
    var searchterm = "";
    var typeofsearch = $inputbox.val();
    if(typeofsearch == "unity_type") {
      path = "/directorio/tipo_unidad/"+valor[0]+"/"+valor[1];
      if(valor[0] == 'elemento-tipounidad') {
        if(valor[1] == 6) {
          var select = $(".inplace-filter.direcciones select");
          path = path + "/" + select.val();
          searchterm = "Direcciones / " + select.find("option:checked").text();
        }
        if(valor[1] == 54) {
          var select = $(".inplace-filter.oficinasasesoras select");
          path = path + "/" + select.val();
          searchterm = "Oficinas asesoras / " + select.find("option:checked").text();
        } 
        if(valor[1] == 56) {
          var select = $(".inplace-filter.escuelas select");
          path = path + "/" + select.val();
          searchterm = "Escuelas de policía / " + select.find("option:checked").text();
        }  
      }
      if(valor[0]=='elemento-otraunidad') {
        var $select = $inputbox.closest(".filter").find("select");
        var $option = $select.find(":selected");
        searchterm = $option.text();
      }
      if(valor[0]=='elemento-directorio') {
        if(valor[1]=='128796') {
          var $option = $(".city-filter-128796 select option:selected");
          path = path + "/" + $option.text();
        }
      }
      
    } else if(typeofsearch == "place") {
      var $subfilter = $("input[name=inplace-filter]:checked");
      path = "/directorio/lugar/"+valor[0]+"/"+$subfilter.val();
      var subfilter_text = $subfilter.parent().find("label").text();
      searchterm = $("select[name=place] option:selected").text() + " / " + subfilter_text;
    } else if(typeofsearch == "custom_search") {
      path = "/directorio/busqueda_personalizada/"+valor;
      searchterm = valor;
    }
    
    $(".message_box.loading").show();
    $(".directory .results").hide();
    
    $.get(path , function( data ) {
      
      
      directoryResults = data;
      showResults(directoryResults, 1);
      
      $(".message_box.loading").hide();
      $(".directory .results").show();
      
      $(".search_term .value").html(searchterm);


    },"json"
    );
      
  });
  
  $(".pager a").live("click", function() {
    var $a = $(this);
    var page = parseInt($a.attr("href").replace("#",""));
    
    document.getElementById("results-start").scrollIntoView();
    
    showResults(directoryResults, page);
    
  });
  
  
  if(typeof document['preload_directory'] != "undefined" && document.preload_directory) {
    $searchbutton.click();
    document.getElementById("filters-start").scrollIntoView();
  }
  $(".directory input[name=filter_by]:checked").click();
  
}(jQuery));

function policia_directory_getValues() {
  
  var $ = jQuery;
  var $topfilter = $("input[name=filter_by]:checked");
  var topvalue = $topfilter.val();
  var bottomvalue = $topfilter.closest(".filter").find("select, input[type=text]").val();
  
  var answer = {
    topvalue: topvalue,
    bottomvalue: bottomvalue
  };
  
  return answer;
  
}

function showResults(results, page) {
  
  var $tbody = $directory.find(".results .content"); 
  var $ = jQuery;
  
  $tbody.html("");
  var totalhtml = "";
  var maps = [];

  var min = ( (page-1) * directoryconfig.numberOfResultsPerPage ) + 1;
  var max = min + (directoryconfig.numberOfResultsPerPage - 1);
  var totalPaginadores = Math.ceil(results.length / directoryconfig.numberOfResultsPerPage);
  
  var result_counter = 0;
  for(var result_id in results) {   
    result_counter++;
    
    if( result_counter >= min && result_counter <= max ) {
      var result = results[result_id];
      var localhtml = "";
      localhtml += '<div class="row" type="'+result['tipo']+'">';            
        localhtml += '<div class="cell basic-information">';
          for(var data_id in result['basico']) {
            var dato = result['basico'][data_id];
            localhtml += '<div class="item">';    
              localhtml += '<div class="label">'+dato['label']+'</div>';    
              localhtml += '<div class="value">'+dato['value']+'</div>';    
            localhtml += '</div>';
          }
        localhtml += '</div>';
        localhtml += '<div class="cell contact-information">';

          var hasMap = false;
          var mapvars = {};      

          for(var data_id in result['contacto']) {
            var dato = result['contacto'][data_id];
            var isMapData = false;
            if(

              dato['label'].toUpperCase() == 'LAT. GRADO' || dato['label'].toUpperCase() == 'LAT. MIN'
               || dato['label'].toUpperCase() == 'LAT. SEG' || dato['label'].toUpperCase() == 'LONG. GRADO'
               || dato['label'].toUpperCase() == 'LONG. MIN' || dato['label'].toUpperCase() == 'LONG. SEG'


              || dato['label'].toUpperCase() == 'LAT' || dato['label'].toUpperCase() == 'LONG' 


              || dato['label'].toUpperCase() == 'LATLONG'                
            ) {

              mapvars[dato['label'].toUpperCase()] = dato['value'];
              hasMap = true;
              isMapData = true;

            }

            if(!isMapData) {
              localhtml += '<div class="item">';    
                localhtml += '<div class="label">'+dato['label']+'</div>';    
                localhtml += '<div class="value">'+dato['value']+'</div>';    
              localhtml += '</div>';  
            }


          }

          if(hasMap) {
            var map_id = 'map-'+result_counter;
            maps.push({
              id: map_id,
              coords: mapvars
            });
            localhtml += '<div class="item">';    
              //localhtml += '<div class="label">'+JSON.stringify(mapvars)+'</div>';    
              localhtml += '<div class="label"></div>';    
              localhtml += '<div id="'+map_id+'" style="width:400px;height:300px"></div>';    
            localhtml += '</div>';

          }

        localhtml += '</div>';
      localhtml += '</div>';
      if(result['contacto'].length > 0) {
        totalhtml += localhtml;
      }
      
    }
  }
  
  $tbody.html(totalhtml);
  
  
  // Paginador
  var pager_html = "";
  if(totalPaginadores > 1) {
    for(var i = 1; i <= totalPaginadores; i++) {
      var classes = [];
      if(i == 1 && page == 1) {
        classes.push('first');
      }
      if(i == totalPaginadores && page == totalPaginadores) {
        classes.push('last');
      }
      if(page == i) {
        classes.push('pager-current');
        pager_html += '<li class="'+classes.join(' ')+'">'+i+'</li>';
      } else {
        classes.push('pager-item');
        pager_html += '<li class="'+classes.join(' ')+'"><a title="Ir a la página '+i+'" href="#'+i+'">'+i+'</a></li>';
      }
    }
    if(page > 1) {
      pager_html = '<li class="pager-previous first"><a title="Ir a la página anterior" href="#'+(page-1)+'">< anterior</a></li>'
        + pager_html;
    }
    if(page < totalPaginadores) {
      pager_html = pager_html + 
        '<li class="pager-next last"><a title="Ir a la página siguiente" href="#'+(page+1)+'">siguiente ></a></li>';
    }    
  }
  $(".results .pager").html(pager_html);
  
  

      
  for(var ind in maps) {
    var map = maps[ind];

    if(typeof map.coords['LAT. GRADO'] != "undefined") {
      var lat = parseInt(map.coords['LAT. GRADO']) +
        (parseInt(map.coords['LAT. MIN']) / 60) + (parseInt(map.coords['LAT. SEG']) / 3600);
      var lon = parseInt(map.coords['LONG. GRADO']) + 
          (parseInt(map.coords['LONG. MIN']) / 60) + (parseInt(map.coords['LONG. SEG']) / 3600);  
    } else if(typeof map.coords['LAT'] != "undefined") {
      var parsed = parse_gps(map.coords['LAT'].replace(/,/g,".").replace(/N/g,"") + "N," + map.coords['LONG'].replace(/,/g,".").replace(/W/g,"")+"W");
      var lat = parsed[0];
      var lon = parsed[1];
    } else if(typeof map.coords['LATLONG'] != "undefined") {
      var parsed = parse_gps(map.coords['LATLONG']);
      var lat = parsed[0];
      var lon = parsed[1];
    }

    var mapCanvas = document.getElementById(map.id);
    var myLatLng = {lat: lat, lng: -1 * Math.abs(lon) };
    $("#"+map.id).attr("data-lat", Math.abs(lat));
    $("#"+map.id).attr("data-long", Math.abs(lon));
    var mapOptions = {
      center: myLatLng,
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(mapCanvas, mapOptions);
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: ''
    });

  }
  
}

function parse_gps( input ) {
  
  input = input.toUpperCase();  
  
  input = input.replace(/ /g,"").replace(/LATITUD/g,"");
  input = input.replace(/,/g," ").replace(/LONGITUD/g,"").replace(/LOGITUD/g,"");

  if( input.indexOf( 'N' ) == -1 && input.indexOf( 'S' ) == -1 &&
    input.indexOf( 'W' ) == -1 && input.indexOf( 'E' ) == -1 ) {
    return input.split(',');
  }

  var parts = input.split(/[º°´'"]+/).join(' ').split(/[^\w\S]+/);

  var directions = [];
  var coords = [];
  var dd = 0;
  var pow = 0;
  
  var signs = [1, 1];
  if(parseFloat(parts[0]) < 0) {
    signs[0] = -1;
    parts[0] = Math.abs(parts[0]);
  }
  if(parseFloat(parts[4]) < 0) {
    signs[1] = -1;
    parts[4] = Math.abs(parts[4]);
  }
    

  for( i in parts ) {

    // we end on a direction
    if( isNaN( parts[i] ) ) {

      var _float = parseFloat( parts[i] );

      var direction = parts[i];

      if( !isNaN(_float ) ) {
        dd += ( _float / Math.pow( 60, pow++ ) );
        direction = parts[i].replace( _float, '' );
      }

      direction = direction[0];

      if( direction == 'S' || direction == 'W' )
        dd *= -1;

      directions[ directions.length ] = direction;

      coords[ coords.length ] = dd;
      dd = pow = 0;

    } else {

      dd += ( parseFloat(parts[i]) / Math.pow( 60, pow++ ) );

    }

  }

  if( directions[0] == 'W' || directions[0] == 'E' ) {
    var tmp = coords[0];
    coords[0] = coords[1] * signs[0];
    coords[1] = tmp * signs[1];
  }
  
  return coords;
  
}

function showInplaceFilters() {
  
  var $ = jQuery;
  
  $(".filters").addClass("showing-inplacefilters");
  $(".inplace-filters").show();  
  
}

function hideInplaceFilters() {
  
  var $ = jQuery;
  
  $(".filters").removeClass("showing-inplacefilters");
  $(".inplace-filters").hide();  
  
}

function policia_evaluar_visibilidad_inplace_filters() {
  
  var $ = jQuery;
  var values = policia_directory_getValues();  
  
  var $inplacefilters = $(".inplace-filters");
  
  
  $inplacefilters.find(".inplace-filter").hide();
  hideInplaceFilters();
  
  if(values.topvalue == 'place') {
    showInplaceFilters();
    $inplacefilters.find(".inplace-filter.radio").show();
  } else if (values.topvalue == 'unity_type') {
    if(values.bottomvalue == 'elemento-tipounidad_6' ) {
      showInplaceFilters();
      $(".inplace-filter.direcciones").show();
    } else if(values.bottomvalue == 'elemento-tipounidad_54' ) {
      showInplaceFilters();
      $(".inplace-filter.oficinasasesoras").show();
    } else if(values.bottomvalue == 'elemento-tipounidad_55' ) {
      showInplaceFilters();
      $(".inplace-filter.metropolitanas").show();
    } else if(values.bottomvalue == 'elemento-tipounidad_56' ) {
      showInplaceFilters();
      $(".inplace-filter.escuelas").show();
    } else if(values.bottomvalue == 'elemento-directorio_128793' ) {
      showInplaceFilters();
      $(".inplace-filter.establecimientossanidad").show();
    } 
    
  } else if (values.topvalue == 'custom_search') {
    
  }
  
  var $selectores = $directory.find("input[name=filter_by]");
  var $unblockers = $(".unblocker");
  var $filters = $directory.find(".filter");  
  var $tbody = $directory.find(".results .content");
  var $inplacefilters = $directory.find(".inplace-filters");
  var $searchbutton = $directory.find("button");
  
  var $inplacefilter_direcciones = $(".inplace-filter.direcciones");
  var $inplacefilter_oficinasasesoras = $(".inplace-filter.oficinasasesoras");
  var $inplacefilter_metropolitanas = $(".inplace-filter.metropolitanas");
  var $inplacefilter_escuelas = $(".inplace-filter.escuelas");  
  
}


