/* Example when 125,163 and 245 are not available */
//var kbrNotAvailable = ['0','125','163','245','0'];
/* Everything is availbale */
var kbrNotAvailable = ['0','0'];

var fromLeft = 0;  
var fromTop =  0;
var borderwidth= 5;
var lang = "nl";
var lastMapNumber;
var lastSearch;

function clickSection(number, place, community, refKbr) {
  // Hide autcompletion
  cleanup();
  
  // Show result
  if ( community != null ) {
    document.getElementById('inputAC').value = community;
    fetchCommunities(community, number);
  }
  else {
    refKbr = getRefKbr(number);
    showResults(number, place, place, refKbr);
    calculateMapPosition();
    highlightSection(number);
  }
  lastMapNumber = number;
}

function cleanup(resetResults) {
  document.getElementById('autocomplete').style.display = "none";
  if ( resetResults != 0 )
    document.getElementById('results').innerHTML = "";
}

function fetchCommunities(place, number) {
    /* Set up the request */
    var xmlhttp =  myRequestObject(); 
    xmlhttp.open('POST', '/FerrarisKBR/post.jsp', true);
  
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                var count = xmlhttp.responseXML.getElementsByTagName('village').length;
                for ( var i = 0; i < count; i++ ) {
                  var village = xmlhttp.responseXML.getElementsByTagName('village')[i].firstChild.data;
                  var section = xmlhttp.responseXML.getElementsByTagName('section')[i].firstChild.data;
                  var refKbr = xmlhttp.responseXML.getElementsByTagName('refKbr')[i].firstChild.data;
                  
                  showResults(section, village, escapeString(place), refKbr);
                }
                calculateMapPosition();
                highlightSection(number);
            }
        }
    }
    
    /* Send the POST request */
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.send("place=" + escapeString(place));
}

function getRefKbr(number) {
  var kbr = new Array(1589210, 1616094, 1616100, 1616103, 1616111, 1616114, 1616124, 1616145, 1616153, 1616158, 1616159, 1616235, 1616238, 1616241, 1616244, 1616246, 1616248, 1616287, 1616258, 1616266, 1616270, 1616274, 1616279, 1616281, 1616282, 1616289, 1616304, 1616309, 1616311, 1616315, 1616322, 1616326, 1616332, 1616334, 1616335, 1616408, 1616409, 1616411, 1616413, 1616432, 1616421, 1616424, 1616438, 1616441, 1616461, 1616465, 1616468, 1616474, 1616476, 1616479, 1616484, 1616487, 1616493, 1616495, 1616498, 1616500, 1616512, 1616513, 1616514, 1616515, 1616517, 1616518, 1616520, 1616521, 1616522, 1616524, 1616525, 1616526, 1616630, 1616653, 1616656, 1616657, 1616659, 1616661, 1616663, 1616664, 1616665, 1616667, 1616669, 1616719, 1616720, 1616722, 1616725, 1616734, 1616736, 1616739, 1616742, 1616744, 1616745, 1616746, 1616747, 1616750, 1616751, 1616752, 1616753, 1616856, 1616863, 1616869, 1616874, 1616879, 1616883, 1616888, 1616893, 1616899, 1616919, 1616924, 1616927, 1616930, 1616936, 1616945, 1616947, 1616968, 1616971, 1616975, 1616979, 1616983, 1616988, 1616990, 1616996, 1617001, 1617003, 1617004, 1617005, 1617007, 1617010, 1617014, 1617017, 1617021, 1617023, 1617026, 1617029, 1617031, 1617035, 1617039, 1617040, 1617043, 1617046, 1617080, 1617078, 1617076, 1617075, 1617073, 1617068, 1617066, 1617064, 1617062, 1617060, 1617058, 1617056, 1617055, 1617052, 1617051, 1617050, 1617049, 1617048, 1617045, 1617042, 1617041, 1617037, 1617036, 1617033, 1617030, 1617028, 1617025, 1617024, 1617022, 1617018, 1617016, 1617013, 1617011, 1616836, 1616838, 1616842, 1616843, 1616868, 1616870, 1616872, 1616875, 1616877, 1616881, 1616884, 1616885, 1616890, 1616895, 1616898, 1616900, 1616904, 1616905, 1616911, 1616917, 1616921, 1616922, 1616926, 1616928, 1616931, 1616934, 1616937, 1616938, 1616952, 1616372, 1616373, 1616374, 1616376, 1616377, 1616380, 1616382, 1616383, 1616385, 1616386, 1616387, 1616389, 1616392, 1616393, 1616433, 1616434, 1616436, 1616437, 1616440, 1616442, 1616443, 1616447, 1616449, 1616450, 1616452, 1616453, 1616457, 1616459, 1616464, 1616466, 1616469, 1616472, 1616473, 1616475, 1616477, 1616480, 1616481, 1616483, 1616485, 1616488, 1616492, 1616494, 1616496, 1616497, 1616499, 1616501, 1616503, 1616504, 1616505, 1616506, 1616507, 1616509, 1616511, 1616347, 1616345, 1616344, 1616343, 1616341, 1616340, 1616339, 1616333, 1616331, 1616328, 1616323, 1616321, 1616317, 1616316, 1616312, 1616310, 1616308, 1616306, 1616302, 1616301, 1616299, 1616152, 1616149);
  return kbr[--number];
}

function calculateMapPosition() {
  var x = 0;
  var y = 0;

  var mapx = document.getElementById("ferrarisMap");
  while( mapx != null ) {
    x += mapx.offsetLeft;
    mapx = mapx.offsetParent;
  }
  
  var mapy = document.getElementById("ferrarisMap");
  while( mapy != null ) {
    y += mapy.offsetTop;
    mapy = mapy.offsetParent;
  }
  
  fromLeft = x - 2;
  fromTop = y - 24;
}

function highlightSection(mapnumber) {
  var coords = document.getElementById(mapnumber).coords;
  var coordsArray = coords.split(",");
  var xMin= Number( coordsArray[0] ); 
  var yMin= Number( coordsArray[1] );	
  var xMax= Number( coordsArray[2] );	
  var yMax= Number( coordsArray[3] );
  
  var left   = xMin + Number(fromLeft);
  var top    = yMax + Number(fromTop);
  var width  = xMax - xMin;
  var height = yMax - yMin;
  
  createLayer("highlightTop",(left-borderwidth),(top-borderwidth),(width+(3*borderwidth)),borderwidth, "visible");
  createLayer("highlightLeft",(left-borderwidth),(top-borderwidth),borderwidth,(height+(2*borderwidth)), "visible");
  createLayer("highlightRight",(left+width+borderwidth),top,borderwidth,(height+(2*borderwidth)), "visible");
  createLayer("highlightBottom",(left-borderwidth),(top+height+borderwidth),(width+(2*borderwidth)),borderwidth, "visible")
}

function createLayer(name, inleft, intop, width, height, visible) {	
  document.getElementById(name).style.left = inleft +"px";	
  document.getElementById(name).style.top = intop +"px";
  document.getElementById(name).style.width = width +"px";
  document.getElementById(name).style.height = height +"px";
  document.getElementById(name).style.visibility = visible;	
}

function showResults(number, place, community, refKbr) {
  var results = document.getElementById("results");
  var show = "<li>";
  if ( refKbr == null )
    show += number + ", " + place + "</li>";
  else {
    if ( lang == "fr" ) {
      show += "<span id='linkResults'>";
      show += "<a href=\"javascript: clickSection("+number+",'"+escapeString(place)+"','"+community+"')\">D&eacute;coupe</a>";
      show += "</span>";
      if ( kbrNotAvailable.toString().search("," + number + ",") == -1 )
	show += number + ", <a href='javascript: showMap(" + refKbr + ");'>" + place + "</a></li>";
      else
      	show += number + ", " + place + " (Visualisation de la carte temporairement indisponible)";
      	    
    }
    else {
      show += "<span id='linkResults'>";
        show += "<a href=\"javascript: clickSection("+number+",'"+escapeString(place)+"','"+community+"')\">Overzichtskaart</a>";
      show += "</span>";
      if ( kbrNotAvailable.toString().search("," + number + ",") == -1 ) 
      	show += number + ", <a href='javascript: showMap(" + refKbr + ");'>" + place + "</a></li>";
      else
      	show += number + ", " + place + " (Kaartvisualisatie tijdelijk niet beschikbaar)";
    }

  }
  results.innerHTML += show;
}

function submitRating(target) {
    if ( target.value != "" && target.value != lastSearch ) {
      /* Set up the request */
      var xmlhttp =  myRequestObject(); 
      xmlhttp.open('POST', '/FerrarisKBR/post.jsp', true);

      /* The callback function */
      xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4) {
              if (xmlhttp.status == 200) {
                  addRatingFeedback(xmlhttp.responseXML, target);
              }
          }
      }

      /* Send the POST request */
      xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
      xmlhttp.send('search=' + escapeString(target.value));
      lastSearch = target.value;
    }
    else
      cleanup(0);
}

function myRequestObject() {
  var ro = null;
  if ( window.XMLHttpRequest )
    ro = new XMLHttpRequest();
  else if (window.ActiveXObject)
    ro = new ActiveXObject("Microsoft.XMLHTTP");

  if ( ro == null )
    alert("Your browser does not support XMLHTTP.");
  return ro;
}

function addRatingFeedback(xml, target) {
  var count = xml.getElementsByTagName('community').length;
  var autocompletion = document.getElementById('autocomplete');
  autocompletion.style.display = "block";
  
  if ( count > 0 ) {
		/*
    if ( count == 1 ) {
      var community = xml.getElementsByTagName('community')[0].firstChild.data;
      var section = xml.getElementsByTagName('section')[0].firstChild.data;
      
      document.getElementById('inputAC').value = community;
      clickSection(section, community, community);
      autocompletion.style.display = "none";  
    }
    else {*/
      var content = "<ul id='listAutocomplete'>";
      for ( var i = 0; i < count; i++ ) {
        var icommunity = xml.getElementsByTagName('community')[i].firstChild.data;
        var isection = xml.getElementsByTagName('section')[i].firstChild.data;
        content += "<li class='community'>";
          content += "<a href=\"javascript:clickSection("+isection+",'"+escapeString(icommunity)+"','"+escapeString(icommunity)+"')\">";
            content += icommunity;
          content += "</a>";
        content += "</li>";
      }
      content += "</ul>";
      
      autocompletion.innerHTML = content;
//    }
  }
  else {
    autocompletion.style.display = "none";  
  }
  
}

function escapeString(word){
  word = word.replace("'", "\\'");
  word = word.replace("\"", "\\\"");
  //word = word.replace("(", "\\(");
  //word = word.replace(")", "\\)");
  return word;
}

function showMap(refKbr) {
  var divKbr = document.getElementById('kbr');
  var link = "http://mara.kbr.be/kbrImage/ferraris/";
	link = "http://lucia.kbr.be/mapview/index.php?image=/ferraris/";
  var content = "<div id='closeKbrMap'><a href='javascript: hideMap();'>Close</a></div>";
  content += "<iframe scrolling='no' frameborder='0' width='100%' height='95%' src='" + link + refKbr + ".imgf'></iframe>";
  divKbr.innerHTML = content;
  divKbr.style.display = "block";
}

function hideMap() {
  var divKbr = document.getElementById('kbr');
  divKbr.innerHTML = "";
  divKbr.style.display = "none";
}

function init() {
  calculateMapPosition();
  setLanguage();
}

function setLanguage() {
  lang = document.getElementById('lang').innerHTML;
}

window.onload=init;
window.onresize= function() {
  calculateMapPosition();
  highlightSection(lastMapNumber);
}

