// Variables/
var map;
var geo;
var rg;
var lastpoint;
var lastplace;
var seen = [];
var checksToMarkers = [];
var boundaryPolygons = [];
var iconG;
var iconR;
var iconA;
var checks;
var endcheck;
var inputcnt = 0;
var currmarker;
var gSearchForm;
var gLocalSearch;


function loadGoogleMap(container, latitude, longitude, zoom, map_type)
{
  if (GBrowserIsCompatible())
  {
     map = new GMap2(container);
     geo = new GClientGeocoder();
     map.enableScrollWheelZoom();

     rg = new GReverseGeocoder(map);

     map.addControl(new GLargeMapControl());
     map.addControl(new GMapTypeControl());

     map.setCenter(new GLatLng(latitude, longitude), zoom);

     map.setMapType(map_type);

     return map;
  }

  return false;
}

function loadExchangeMap(container, searchform, latitude, longitude, zoom, map_type, hidepanel)
{
   map = loadGoogleMap(container, latitude, longitude, zoom, map_type);

   if(map)
   {
      checks = document.getElementById("checks");
      endcheck = document.getElementById("endcheck");

      iconG = new GIcon();
      iconG.image = PUBLIC_PATH + '/images/house.gif';
      iconG.shadow = '';
      iconG.iconSize = new GSize(25,21);
      iconG.iconAnchor = new GPoint(0,0);
      iconG.infoWindowAnchor = new GPoint(16,0);
      
      gSearchForm = new GSearchForm(false, searchform);
      gSearchForm.setOnSubmitCallback(null, CaptureForm);
  
      if (!hidepanel) {
         gSearchForm.input.focus();
      }

      gLocalSearch = new GlocalSearch();
      gLocalSearch.setCenterPoint("United Kingdom");
      gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);

      GEvent.addListener(rg, "load", goodresult);
      GEvent.addListener(rg, "error", badresult);
      GEvent.addListener(map, "click", function(marker, point) 
      {
         if (point) {
            lastpoint = point;
            rg.reverseGeocode(point);
         }
      });

      GEvent.addListener(map, "moveend", function() 
      {
         if (map.getZoom() >= 10) {
            updateMap(map.getBounds());
	 }
      });
 
      GEvent.trigger(map, 'moveend');     
   }
}

function getWindowHeight() 
{
   if (window.self && self.innerHeight) {
      return self.innerHeight;
   }

   if (document.documentElement && document.documentElement.clientHeight) {
      return document.documentElement.clientHeight;
   }

   if (document.body && document.body.clientHeight) {
      return document.body.clientHeight;
   }

   return 0;
}

function getWindowWidth() 
{
   if (window.self && self.innerWidth) {
      return self.innerWidth;
   }
   if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientWidth;
   }
   if (document.body && document.body.clientWidth) {
      return document.body.clientWidth;
   }
   return 0;
}

process_point_info = function(jsonData)
{
   var marker = new GMarker(lastpoint);
   marker.value = jsonData;

   inputcnt = inputcnt + 1;
   checksToMarkers[inputcnt] = marker;
   marker.value.id = inputcnt;


   if (seen[marker.value.olo] == null)
   {
      var url = EXCHANGE_COORDINATES_URL + '?yl='
              + (marker.value.elng-0.02) + '&yh=' + (marker.value.elng+0.02) + '&xl='
              + (marker.value.elat-0.02) + '&xh=' + (marker.value.elat+0.02);


      jQuery.getJSON(url, function(data) {
         process_json_coords(data);
      });
   }

   GEvent.addListener(marker, 'click', function()
   {
      var html = '';
      if(marker.value.thr != '' || marker.value.town != '' || marker.value.pc != '') 
      {
	 var address = '';
	 if(marker.value.thr != '')  address += (address != '' ? ', ' : '') + marker.value.thr;
	 if(marker.value.town != '') address += (address != '' ? ', ' : '') + marker.value.town;
	 if(marker.value.pc != '')   address += (address != '' ? ', ' : '') + marker.value.pc;

         html += '<div style="font-weight:bold; margin-bottom:4px">'+address+'</div>';
      }
	
      html += 'Exchange: <a href="javascript:pan_to_exchange(\'' + marker.value.olo + '\')">' + marker.value.exchange + '</a>'
           +  ' (' + marker.value.dist + 'm away)'
           +  '<div style="margin:4px 0px 4px 0px;">';

      currmarker = marker;
      if (document.getElementById("check" + marker.value.id) == null) 
      {
         html += '<table border="0" cellspacing="0" cellpadding="1" width="210">'
              +  '<tr><td width="60">House:&nbsp;</td>'
              +  '<td align="right" width="125">'
              +  '<input class="field" type="text" id="house' + inputcnt + '" onKeyPress="if(event.keyCode==13) { do_check(inputcnt); return false; }"></td>'
              +  '<td width="25">&nbsp;</td></tr>'
              +  '<tr><td>Postcode:&nbsp;</td>'
              +  '<td align="right">'
              +  '<input class="field" type="text" value="' + marker.value.pc + '" id="postcode' + inputcnt + '" onKeyPress="if(event.keyCode==13) { do_check(inputcnt); return false; }">'
              +  '<td width="25">&nbsp;</td></tr>'
              +  '</table>';
      } else {
         html += "See results to the left";
      }

      html += '<table border="0" width="185" cellspacing="0" cellpadding="0" style="margin-top:1px;">'
           +  '<tr><td valign="bottom"><a href="javascript:removeMarker(' + marker.value.id + ')">Remove</a></td>';

      if (document.getElementById("check" + marker.value.id) == null) {
         html += '<td align="righ"><input style="font-size: 9pt; margin: 0; padding: 0 2px" type="submit" value="Check" onclick="do_check(inputcnt)"></td>';
      }

      html += '</tr></table>'
      html +  '</div>';

      marker.openInfoWindowHtml(html);
   });

   GEvent.addListener(marker, "infowindowclose", function()
   {
      var el = document.getElementById("check" + marker.value.id);
      if (el != null) 
      {
	 el.style.border = '1px solid #FFFFFF';
      }
   });

   GEvent.addListener(marker, "infowindowopen", function()
   {
      var el = document.getElementById("check" + marker.value.id);
      if (el != null) 
      {
	 el.style.border = '1px solid #F26907';
      }
  });

  map.addOverlay(marker);
  GEvent.trigger(marker, 'click');
}

function pan_to_exchange(olo)
{
  if (seen[olo] != null)
  {
     GEvent.trigger(seen[olo],'click');
  }
}

function removeMarker(id)
{
  if (checksToMarkers[id] != null) {
     map.removeOverlay(checksToMarkers[id]);
  }

  var chkNode = document.getElementById("check" + id);

  if (chkNode != null) 
  {
     chkNode.style.display = 'none';
     document.getElementById("checks").removeChild(chkNode);
  }

  var children = document.getElementById("checks").childNodes;
  if (children.length <= 5) {
     document.getElementById("firstcheck").style.display = 'block';
  }
}

function do_check(cnt, hou_in, thr_in, town_in, pc_in,bts_in)
{
   var el = document.getElementById('house'+cnt);
   var pcel = document.getElementById('postcode'+cnt);

   var pc; 
   var thr; 
   var hou; 
   var town; 
   var bts = "";

   if (pc_in != null) 
   {
      pc = pc_in; 
      thr = thr_in; 
      hou = hou_in; 
      town = town_in;
   }
   else
   {
      if (pcel.value != "" && pcel.value != currmarker.value.pc) {
         pc = pcel.value;
      } else {
         pc = currmarker.value.pc;
      }

      thr = currmarker.value.thr;
      town = currmarker.value.town;
      hou = el.value;
   }

   if (bts_in != null) {
      bts = bts_in;
   }

   if (checksToMarkers[inputcnt] != null) {
      checksToMarkers[inputcnt].closeInfoWindow();
   }

   var chk = document.getElementById("check"+cnt);
   if (chk == null)
   {
      document.getElementById("firstcheck").style.display = 'none';
      chk = document.createElement("div");
      chk.setAttribute("id", "check" + cnt);
      chk.className = "check";
      checks.insertBefore(chk,endcheck);
   }


   var content = '<div class="check_head">' + (hou=='' ? '' : hou + ', ') + thr + ', ' + pc + '</div>'
               + '<div class="check_content">'
               + '<img src="/images/ajax-loader.gif" alt="Checking..." style="padding-right: 4px" /> Checking, please wait...'
               + '</div>';

   chk.innerHTML = content;


   var url = CHECK_ADDRESS_URL 
	   + "?id="   + cnt 
	   + "&hou="  + hou 
           + "&thr="  + thr 
	   + "&town=" + town 
	   + "&pc="   + pc 
	   + "&bts="  + bts;
   
   GDownloadUrl(url, process_check_result);
}

process_check_result = function(doc)
{
   try 
   {
      var data = eval('(' + doc + ')');
      var checkEl = document.getElementById("check"+data.id);
      var foot = "";

      foot = '<div class="check_foot">'
      foot + '<a href="javascript:GEvent.trigger(checksToMarkers[' + data.id + '],"click")">Jump to</a> | '
      foot + '<a href="javascript:removeMarker(' + data.id + ')">Remove</a>'
      foot + '</div>';

      checkEl.innerHTML = data.html + foot;
   }
   catch (ex)
   {
     alert("Sorry, an unknown error occurred whilst checking availability. If this persists, please contact sam@samknows.com");
   }
}

function goodresult(placemark)
{
   var location = null;
   var town = '';

   if (placemark != null &&
      placemark.AddressDetails.Country != null &&
      placemark.AddressDetails.Country.AdministrativeArea != null &&
      placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null &&
      placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
   {
      location = placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality;
      town = location.LocalityName;
   }
   else if (placemark != null &&
      placemark.AddressDetails.Country != null &&
      placemark.AddressDetails.Country.AdministrativeArea != null &&
      placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null)
   {
      if(placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality != null)
      {
         location = placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality;
      }
      else
      {
         location = placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea;
      }

      town = location.SubAdministrativeAreaName;
   }
   else if (placemark != null &&
      placemark.AddressDetails.Country != null &&
      placemark.AddressDetails.Country.SubAdministrativeArea != null)
   {
      if(placemark.AddressDetails.Country.SubAdministrativeArea.DependentLocality != null)
      {
         location = placemark.AddressDetails.Country.SubAdministrativeArea.DependentLocality;
	 town = placemark.AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName;
      }
      else if(placemark.AddressDetails.Country.SubAdministrativeArea.Locality != null)
      {
         location = placemark.AddressDetails.Country.SubAdministrativeArea.Locality;
         town = placemark.AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName;
      }
      else
      {
         location = placemark.AddressDetails.Country.SubAdministrativeArea;
	 town = placemark.AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName;
      }
   }
   else if (placemark != null &&
      placemark.AddressDetails.Country != null &&
      placemark.AddressDetails.Country.AdministrativeArea != null)
   {
      location = placemark.AddressDetails.Country.AdministrativeArea;
      town = location.AdministrativeAreaName;
   }
   else if(placemark != null &&
      placemark.AddressDetails.Country != null &&
      placemark.AddressDetails.Country.Locality != null)
   {
      if(placemark.AddressDetails.Country.Locality.DependentLocality != null)
      {
         location = placemark.AddressDetails.Country.Locality.DependentLocality;
         town = placemark.AddressDetails.Country.Locality.DependentLocality.DependentLocalityName;
      }
      else
      {
         location = placemark.AddressDetails.Country.Locality;
         town = placemark.AddressDetails.Country.Locality.LocalityName;
      }
   }   
   else if(placemark != null && placemark.AddressDetails.Country != null)
   {
      location = placemark.AddressDetails.Country;
      town = '';
   }
   else if(placemark != null && placemark.AddressDetails != null)
   {
      location = placemark.AddressDetails;
      town = '';
   }

   if (location != null)
   {
      var lng = lastpoint.lng();
      var lat = lastpoint.lat();

      var url = POINT_INFO_URL + "?"
              +  "lat="   + lat
              +  "&lng="  + lng
              +  "&pc="   + (location.PostalCode != null ? location.PostalCode.PostalCodeNumber : '')
              +  "&thr="  + (location.Thoroughfare != null ? location.Thoroughfare.ThoroughfareName : '')
              +  "&town=" + town;

      jQuery.getJSON(url, function(data) {
         process_point_info(data);
      });
   }
}

function badresult(placemark)
{
  alert("Unable to find an address at this location");
}

process_json_bounds = function(data)
{
   var poly = [];

   for(var i = 0; i < data.points.length; i++) {
      if (data.points[i] == null) continue;
      poly.push(new GLatLng(data.points[i].lat, data.points[i].lng));
   }

   if (data.points.length > 0) {
      poly.push(new GLatLng(data.points[0].lat, data.points[0].lng));
   }

   var line = new GPolygon(poly,'#0000AF', 1, 0.8,'#0000FF', 0.2, {clickable: false} );
   boundaryPolygons[data.olo] = line;
   map.addOverlay(line);
}

function showExchangeBounds(olo)
{
   if (boundaryPolygons[olo] != null)
   {
      map.removeOverlay(boundaryPolygons[olo]);
      boundaryPolygons[olo] = null;
   }
   else
   {
      var url = EXCHANGE_BOUNDS_URL + '?olo=' + olo;
      jQuery.getJSON(url, function(data) {
         process_json_bounds(data);
      });
   }
}

// Get exchange info as we roam around the page
process_json_coords = function(data)
{
  for (var i = 0; i < data.length; i++)
  {
    if (data[i] == null) continue;
    if (seen[data[i].olo] != null) continue;

    var point = new GLatLng(data[i].lat, data[i].lng);
    var marker = createMarker(point, data[i].olo, data[i].olo, 'g');
    seen[data[i].olo] = marker;
    map.addOverlay(marker);
  }
}

function createMarker(point,html,value,iconcolour)
{
   var icon = iconG;
   var marker = new GMarker(point, { icon: icon });
   marker.value = value;

   GEvent.addListener(marker, "click", function()
   {
      var url = EXCHANGE_DETAILS_URL + '?olo=' + marker.value;
      jQuery.getJSON(url, function(data) {
         process_exchange_detail(data);
      });
   });

   return marker;
}

function toggle_display(id)
{
   var el = document.getElementById(id);
   if (el != null && el.style.display == 'none')
   {
     el.style.display = 'block';
   }
   else if (el != null && el.style.display == 'block')
   {
     el.style.display = 'none';
   }
}

// Get exchange detail
process_exchange_detail = function(data)
{
   if (seen[data.olo] != null)
   {
      var marker = seen[data.olo];

      var html = '<b>' + data.name + '</b> (<a href="' + PUBLIC_PATH + 'exchange/' + data.olo + '">' + data.olo + '</a>)<br />'
               + '<div style="margin: 4px 0px 4px 0px">'
               + 'BT Wholesale: ' + data.BTW + '<br />'
               + 'LLU Services: ' + data.LLU + '<br />'
               + 'Cable services: ' + data.Cable + '</div>'
               + '<a href="javascript:showExchangeBounds(\'' + data.olo + '\');">Show/hide exchange coverage</a>';

      marker.openInfoWindowHtml(html);
   }
}

// A function to read the data
function updateMap(bounds)
{
   var url = EXCHANGE_COORDINATES_URL + '?'
	   + 'yl='  + bounds.getSouthWest().lng()
	   + '&yh=' + bounds.getNorthEast().lng()
	   + '&xl=' + bounds.getSouthWest().lat()
	   + '&xh=' + bounds.getNorthEast().lat();

   jQuery.getJSON(url, function(data) {
      process_json_coords(data);
   });
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch()
{
   if (!gLocalSearch.results) return;

   // move the map to the first result
   var first = gLocalSearch.results[0];
   if (first == null) 
   {
      alert("Sorry, could not find your location");
      return;
   }

   map.setCenter(new GLatLng(parseFloat(first.lat), parseFloat(first.lng)),15);
}

// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) {
   gLocalSearch.execute(searchForm.input.value);
   return false;
}

