﻿// On body load.
$(document).ready(function() {
  $("#txtCity").blur(function() {
    hideSelectResults();
  });
  $("#txtCity").dblclick(function() {
    getTopHits('#plaatsResults', this);
  });

  disableTab();

  $("#bibliobusResults").append('<tr><td class="noResults">Er zijn geen zoekresultaten beschikbaar, voor een nieuwe zoekopdracht vul het bovenstaande "<i>Halteplaats</i>" invoerveld in.</td></tr>')

  $("#btnSearch").click(function(){
    showOnMap($("#txtCity").val());
  });

  var e = $('#txtCity');
  if (e.length != 0) {
    e.autocomplete = 'off';
    e.focus();

    if (e.val().length > 0)
      showOnMap(e.val());
  }
});

var xmldoc;

// Zorgt voor foo.stripHTML - Verwijdert alle HTML, .text() ook
String.prototype.stripHTML = function() {
  return this.replace(/<.*?>/g, "");
}
// Zorgt voor een reverse array binnen jQuery.
jQuery.fn.reverse = function() {
  return this.pushStack(this.get().reverse(), arguments);
};
// Zorgt voor een replace binnen Javascript case INsensitive
RegExp.escape = function(str) {
  var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  return str.replace(specials, "\\$&");
}

// Functie: replace case insenstive.
function highlightSearch(line, word) {
  var regex = new RegExp("(" + RegExp.escape(word) + ")", "gi");
  return line.replace(regex, "<b>$1</b>");
}


// Herstelt alles naar originele state.
function restoreResults() {
  $(".selected_dropdown_td").removeClass('selected_dropdown_td');
  // Extra.
  //$("#mobielFiliaal").html("");
}

// Selecteer indien mogelijk huidige locatie en verberg
function hideSelectResults() {
  var selected = $("#plaatsResults .selected_dropdown_td");
  if (selected.length) $("#txtCity").val($(selected).text());
  setTimeout(function() {hideResults()}, 200);
  //getResults(null, '#plaatsResults', $('#txtCity'));
}

// Zet de zoekresultaten op niet zichtbaar.
function hideResults() {
  $(".dropdown_table").css("visibility", "hidden");
}

// Vang ook de "tab" af.
function captureTab() {
  if ($(".selected_dropdown_td")[0]) {
    var temp = $(".selected_dropdown_td")[0];
    $("#txtCity").val($(temp).text());
    hideResults();
    return false;
  } else {
    hideResults();
  }
}

// disable TAB
function disableTab() {
  $("#txtCity").keypress(function(e) {
  var e = e ? e : window.event;
  var KeyCode = e.which ? e.which : e.keyCode;
  if (KeyCode == 9) return false;
  })
}

// Selecteer 't eerste resultaat

// Zoekt de plaatsnamen op.
function getResults(e, resultTable, txt) {
  $(txt).focus();
  // Controleer voor arrow en enter keys (tab werkt niet :/) -- TAB werkt met onkeypress
  if (!$(txt).val().length) {
    hideResults();
    return;
  }
  var e = e ? e : window.event;
  var KeyCode = e.which ? e.which : e.keyCode;
  var objTable = $(resultTable);
  var next = false;

  // Arrow down.
  if (KeyCode == 40) {
    if (!$(resultTable + ' tr .selected_dropdown_td')[0]) {
      $(resultTable + " tr td:first").addClass("selected_dropdown_td");
      return;
    }
    $('td', objTable).each(function() {
      if (next == true) {
        restoreResults();
        next = false;
        $(this).addClass("selected_dropdown_td");
      }
      else if ($(this).is(".selected_dropdown_td")) {
        next = true;
      }
    });
    next = false;
    return;
  }
  // Arrow up.
  else if (KeyCode == 38) {
    $('td', objTable).reverse().each(function() {
      if (next == true) {
        restoreResults();
        next = false;
        $(this).addClass("selected_dropdown_td");
      }
      else if ($(this).is(".selected_dropdown_td")) {
        next = true;
      }
    });
    return;
  }
  // Return.
  else if (KeyCode == 13) {
    if ($(resultTable + ' tr .selected_dropdown_td')[0]) {
      var temp = $(resultTable + ' tr .selected_dropdown_td')[0];
      $(txt).val($(temp).text());

      // Extra.
      $("#mobielFiliaal").html('Het mobiele filiaal van ' + $(txt).val() + ' is een voorziening van <b>' + $(temp).attr("alt") + '</b>.<br /><br />Voor meer informatie van deze bibliotheek: <a href="' + $(temp).attr("url") + '">' + $(temp).attr("url") + '</a>.');
      //$("#urlFiliaal").html($(temp).attr("url"));
      showOnMap($(txt).val())
      hideResults();
      return;
    }
  }

  // Remove all records.
  $(objTable).find("tr").remove();
  //$("#mobielFiliaal").html("");
  $("#urlFiliaal").html("");

  if ($(txt).val().length > 0) {
    var optie = $("#optie").val();
    $.ajax({
      type: "GET",
      url: "/includes/ajaxsearch.asp?p=" + $(txt).val() + "&t=" + optie,
      success: function(returnValue) {
        xmldoc = $(returnValue);
        // Remove all records.
        $(objTable).find("tr").remove();
        $(objTable).css("visibility", "hidden");

        // Loop door de XML output heen.
        $(xmldoc).find("plaats").each(function() {
          $(objTable).append("<tr><td class=\"dropdown_td\">" + highlightSearch($(this).attr("naam"), $("#txtCity").val()) + "</td></tr>");
          $(objTable).css("visibility", "visible");
        });


        // Hang een mouse -over, -out en -click aan de resultaten.
        $(".dropdown_td").mouseover(function() {
          restoreResults();
          $(this).addClass('selected_dropdown_td');
        }).mouseout(function() {
          $(this).removeClass('selected_dropdown_td');
        }).click(function() {
          setBus(txt, $(this).attr("naam"), false);
        });
      }
    });
  }
}

function getTopHits(resultTable, txt) {
  var objTable = $(resultTable);
  // Remove all records.
  $(objTable).find("tr").remove();
  //$("#mobielFiliaal").html("");
  $("#urlFiliaal").html("");

  $.ajax({
    type: "GET",
    url: "/includes/ajaxsearch.asp?top=true&t=" + $("#optie").val(),
    success: function(returnValue) {
      xmldoc = $(returnValue);
      // Remove all records.
      $(objTable).find("tr").remove();
      $(objTable).css("visibility", "hidden");

      // Loop door de XML output heen.
      $(xmldoc).find("plaats").each(function() {
        $(objTable).append("<tr><td class=\"dropdown_td\">" + highlightSearch($(this).attr("naam"), $("#txtCity").val()) + "</td></tr>");
        $(objTable).css("visibility", "visible");
      });

      // Hang een mouse -over en -out en -click aan de resultaten.
      $(".dropdown_td").mouseover(function() {
        restoreResults();
        $(this).addClass('selected_dropdown_td');
      }).mouseout(function() {
        $(this).removeClass('selected_dropdown_td');
      }).click(function() {
        setBus(txt, $(this).attr("naam"), false);
      });
    }
  });
}
function setBus(txt, val, show) {
  $(txt).val(val);
  $(txt).focus();
  if (show) showOnMap($(txt).val());
}
function setContactLink(plaats) {
  if (plaats != "")
    $("#contactlink").attr("href", "contact.asp?plaats=" + plaats);
  else
    $("#contactlink").attr("href", "contact.asp");
}
function resetContactLink() {
  setContactLink("");
}
var w = "", w2 = "";
function showOnMap(plaats) {
  var optie = $("#optie").val();
  var l = "";
  if ((optie != "gemeente") && (optie != "busnummer"))
    setContactLink(plaats);
  else
    resetContactLink();
  $.ajax({
    type: "GET",
    url: "/includes/ajaxsearch.asp?b=" + plaats + "&t=" + optie,
    success: function(returnValue) {
      parseResult(returnValue, plaats, optie);
    }
  });
  hideResults();
}

function parseResult(xml, plaats, optie) {
  if (map) map.clearOverlays();
  xmldoc = $(xml);
  $("#bibliobusResults").find("tr").remove();
  $("#bibliobusResults").append('<tr><td>Locatie</td><td>dag</td><td>aankomst</td><td>vertrek</td><td>adres</td><td>postcode</td><td>gegevens</td></tr>');
  $(xmldoc).find("artikel").each(function(i) {
    changeNews($(this).find("id").text(), $(this).find("titel").text(), $(this).find("datum").text(), $(this).find("intro").text());
  });
  $(xmldoc).find("bibliobus").each(function(i) {
    if (optie == "halteplaats")
      $("#content_city").text($(this).find("plaats").text());
    else
      $("#content_city").text("");
    w = $(this).find("url").text();
    if (!w.length)
      w2 = "geen website";
    else
      w2 = "<a href=\"" + w + "\" target=\"_blank\">klik hier</a>"; // voor resultaten
    w = "<a onclick=\"changeMapType()\">klik hier om de weergave te wijzigen</a>"; // voor icoontje op map
    l = $(this).find("lokatie").text();
    if (!l.length)
      l = plaats;
    $("#bibliobusResults").append('<tr><td><b>' + l + '</b></td><td>' + $(this).attr("dag") + '</td><td>' + $(this).attr("van") + '</td><td>' + $(this).attr("tot") + '</td><td nowrap="nowrap">' + $(this).find("adres").text() + '</td><td>' + $(this).find("postcode").text() + '</td><td><a href="/contact.asp?plaats=' + plaats + '&hid=' + $(this).find("hid").text() + '">contact</td></tr>');
    pinMarker($(this).find("adres").text() + ", " + plaats + ", Netherlands", "Bibliobus", "Bibliobus " + plaats, w);
    setMobielFiliaal($(this).find("relatie").text(), $(this).find("url").text());

    // Creeer specifieke link.
    $("#subPage").html('<a href="/bus-details.asp?plaats=' + plaats + '">Bekijk de pagina van <b>bibliobus ' + $(this).find("busnummer").text() + '</b></a>');
    $("#subPage").css("display", "block");
  });

  $("#bibliobusResults tr:even").css("background-color", "#d7eba6");
  $("#bibliobusResults tr:odd").css("background-color", "#c7e180");
  $("#bibliobusResults tr:first").css("background-color", "#a6cd34");
  $("#bibliobusResults tr:first td").css("font-weight", "bold");

  setTimeout(function(){setWarningMaps()}, 2000);
}

var gNewsTitle = "", gNewsDate = "", gNewsText = "", gNewsId = "";
function setDefaultNews(id, title, date, text) {
  gNewsTitle = title;
  gNewsDate = date;
  gNewsText = text;
  gNewsId = id;
}
function resetDefaultNews() {
  changeNews(gNewsId, gNewsTitle, gNewsDate, gNewsText);
}

function changeNews(id, title, date, text) {
  if (!(id && title && date && text)) {
    id    = gNewsId;
    title = gNewsTitle;
    date  = gNewsDate;
    text  = gNewsText;
  }
  $("#bottom_left .kop a").html(title);
  $("#bottom_left .date").html(date);
  $("#bottom_left div#tekst").html(text);
  $("#bottom_left .kop a").attr("href", "nieuws.asp?id=" + id);
}

function resetResults() {
  $.ajax({
    type: "GET",
    url: "/includes/ajaxsearch.asp?remsession=true",
    success: function(returnValue) {
      resetPage();
    }
  });
  resetDefaultNews();
  $("#txtCity").focus();
}
function resetPage() {
  $("#txtCity").val("");
  $("#content_city").html("");
  $("#mobielFiliaal").html("");
  $("#subPage").hide();
  $("#bibliobusResults").find("tr").remove();
  $("#bibliobusResults").append('<tr><td class="noResults">Er zijn geen zoekresultaten beschikbaar, voor een nieuwe zoekopdracht vul het bovenstaande "<i>Halteplaats</i>" invoerveld in.</td></tr>');
  resetContactLink();
}

// Google Maps.
function changeMapType() {
  if (!map) return;
  if (map.getCurrentMapType() == G_NORMAL_MAP)
    map.setMapType(G_SATELLITE_MAP);
  else if (map.getCurrentMapType() == G_SATELLITE_MAP)
    map.setMapType(G_HYBRID_MAP);
  else
    map.setMapType(G_NORMAL_MAP);
}

//var gSet = false;
function setMobielFiliaal(titel, url) {
  //if (!gSet) {
    if (titel.length > 0)
      $("#mobielFiliaal").html('Het mobiele filiaal van ' + $("#txtCity").val() + ' is een voorziening van <a href="' + url + '">' + titel + '</a>.');
    //if (url.length > 0)
    //  $("#mobielFiliaal").html($("#mobielFiliaal").html() + '<br /><br />Voor meer informatie van deze bibliotheek: <a href="' + url + '">' + url + '</a>.')
    //gSet = true;
  //}
}

var gLast = "", gNrWarnings = 0;
function setWarningMaps() {
  if (gNrWarnings > 0) {
    if (gLast != $("#txtCity").val())
      $("#mobielFiliaal").html($("#mobielFiliaal").html() + "<br /><span class=\"warning\">E&eacute;n of meerdere locaties kunnen niet op de kaart getoond worden.</span>");
    else
      gLast = $("#txtCity").val();
  }
  gNrWarnings = 0;
}

var geocoder = null;
var map = null;
var icon = null;

// Creates a story marker at the given point with the given label
function pinMarker(address, title, name, website) {
  if (geocoder) {
    geocoder.getLatLng(address, function(point) {
      if (point) {
        // Map.
        map.setCenter(point, 12);

        // Icon.
        icon = new GIcon();
        icon.image = "images/marker.png";
        icon.iconSize = new GSize(67, 25);
        icon.iconAnchor = new GPoint(13, 25);
        icon.infoWindowAnchor = new GPoint(10, 4);

        // Zet de marker
        var marker = new GMarker(point, icon);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml("'<i>" + address.replace(", Netherlands", "") + "</i>'<br /><br />[ " + website + " ]");
        });
        map.addOverlay(marker);
      } else {
        gNrWarnings++;
      }
    });
  }
}

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(address, function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        map.setCenter(point, 15);
        map.addOverlay(pinMarker(point, address.replace(", Netherlands", ""), 'Bibliobus'));
      }
    });
  }
}

function initialize() {
try {
  if (GBrowserIsCompatible()) {

    map = new GMap2(document.getElementById("google_maps"));
    geocoder = new GClientGeocoder();

    if (geocoder) {
      geocoder.getLatLng("Gelderland, Netherlands", function(point) {
        map.setCenter(point, 8)
      });
    }
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
  }
  } catch (e) {}
}
