var timer = null;
var timerOn = false;
var map = null, directions = null, directionsPanel = null;
var menuIdIncrement = 0, didIncrement = 0;
var requests = new Requests();
var statusMessage = new StatusMessage();

window.onload = init;

function init()
{
   var menu = document.getElementById('menu');
   
   for (var i = 0; i < menu.childNodes.length; i++)
      if (menu.childNodes[i].nodeName == 'UL')
         for (var j = 0; j < menu.childNodes[i].childNodes.length; j++)
            if (menu.childNodes[i].childNodes[j].nodeType == 1)
            {
               menu.childNodes[i].childNodes[j].onmouseover = showMenu;
               menu.childNodes[i].childNodes[j].onmouseout = hideMenu;
            }
            
   changeAddToSchoolBoxLinks(document.getElementById('map_results'), false);
   changeAddToSchoolBoxLinks(document.getElementById('school_info'), false);
   
   var links = document.getElementsByTagName('a');
   for (var i = 0; i < links.length; i++)
      if (links[i].rel == 'new window' || links[i].rel == 'external')
         links[i].setAttribute('target', '_blank');
}

function showMenu()
{
   var menu = document.getElementById('menu');

   for (var i = 0; i < menu.childNodes.length; i++)
      if (menu.childNodes[i].nodeName == 'UL')
         for (var j = 0; j < menu.childNodes[i].childNodes.length; j++)
            if (menu.childNodes[i].childNodes[j].nodeType == 1 && this != menu.childNodes[i].childNodes[j] && menu.childNodes[i].childNodes[j].childNodes[2])
               menu.childNodes[i].childNodes[j].childNodes[2].style.display = 'none';

   if (this.childNodes[2])
      this.childNodes[2].style.display = 'block';

   stopTime();
}

function hideMenu()
{
   if (!timerOn && this.childNodes[2])
   {
      this.childNodes[2].id = 'dmid' + menuIdIncrement++;
      timer = setInterval("document.getElementById('" + this.childNodes[2].id + "').style.display = 'none';", 600);
      timerOn = true;
   }
}

function stopTime()
{
   if (timer)
   {
      clearInterval(timer);
      timer = null;
      timerOn = false;
   }
}

function Requests()
{
   this.http = window.XMLHttpRequest ? new XMLHttpRequest() : null;
   this.requests = [];
   this.requestIndex = 0;
   this.requestInProgress = false;
}

Requests.prototype.request = function(id, url)
{
   if (this.http)
   {
      this.requests[this.requestIndex] = [id, url];

      if (!this.requestInProgress && this.requests.length > 0)
         this.send(this.requestIndex);

      this.requestIndex++;

      return true;
   }

   return false;
}

Requests.prototype.send = function(requestIndex)
{
   this.requestInProgress = true;
   this.http.open('GET', this.requests[requestIndex][1] + '&view=view_schools_url&view_type=json&url_id=' + parseInt(Math.random() * 99999999), true);
   this.http.setRequestHeader('Content-type', 'text/html');
   this.http.onreadystatechange = new Function ('requests.handleChange(' + requestIndex + ", '" + this.requests[requestIndex][0] + "');");
   this.http.send(null);
}

Requests.prototype.handleChange = function(requestIndex, id)
{
   if (this.http.readyState == 4)
   {
      this.requestInProgress = false;
      delete this.requests[requestIndex];

      if (this.http.status == 200)
      {
         eval('var addToSchoolBox = ' + this.http.responseText + ';');
         document.getElementById('school_box').innerHTML = addToSchoolBox;

         statusMessage.stopWaiting(id, 'Added to school box');
      }
      else
         statusMessage.stopWaiting(id, 'Unable to add to box');

      if (!this.requestInProgress && this.requests.length > 0)
         for (key in this.requests)
         {
            this.send(key);
            break;
         }
   }
}

function StatusMessage()
{
   this.intervals = [], this.lengths = [];
}

StatusMessage.prototype.startWaiting = function(id, html)
{
   document.getElementById(id).innerHTML = html;
   statusMessage.lengths[id] = document.getElementById(id).innerHTML.length;

   statusMessage.intervals[id] = setInterval("statusMessage.keepWaiting('" + id + "');", 500);
}

StatusMessage.prototype.keepWaiting = function(id)
{
   var object = document.getElementById(id);

   if (object)
   {
      if (object.innerHTML.length < statusMessage.lengths[id] + 3)
         object.innerHTML += '.';
      else
         object.innerHTML = object.innerHTML.substring(0, statusMessage.lengths[id]) + '.';
   }
}

StatusMessage.prototype.stopWaiting = function(id, html)
{
   clearInterval(statusMessage.intervals[id]);
   document.getElementById(id).innerHTML = html;
}

function changeAddToSchoolBoxLinks(object, fixURL)
{
   if (object)
   {
      var spans = object.getElementsByTagName('span');

      for (var i = 0; i < spans.length; i++)
         if (spans[i].className == 'smaller' || spans[i].className == 'school_box_link')
         {
            spans[i].id = 'did' + didIncrement++;

            if (spans[i].firstChild && spans[i].firstChild.nodeName == 'A')
               spans[i].firstChild.onclick = new Function("return clickAddToSchoolBox('" + spans[i].id + "', '" + (fixURL ? spans[i].firstChild.href.substring(6) : spans[i].firstChild.href) + "');");
         }
   }

   return object;
}

function clickAddToSchoolBox(id, url)
{
   if (requests.request(id, url))
   {
      statusMessage.startWaiting(id, 'Adding to school box');
      return false;
   }

   return true;
}

function submitCriteria(map)
{
   var url = '/', append = '', postsecondary = false;
   var object = document.getElementById('criteria_form');
   
   if (object.type.selectedIndex == 0)
   {
      url += 'public-';
      append = map ? '-map' : '';
   }
   else if (object.type.selectedIndex == 1)
   {
      url += 'private-';
      append = map ? '-map' : '';
   }
   else
   {
      url += object.type.options[object.type.selectedIndex].value;
      append = map ? '-map' : '';
      postsecondary = true;
   }
   
   if (!postsecondary)
   {
      if (object.grade_level)
      {
         if (object.grade_level.selectedIndex == 1)
            url += 'elementary-';
         else if (object.grade_level.selectedIndex == 2)
            url += 'middle-';
         else if (object.grade_level.selectedIndex == 3)
            url += 'high-';
      }
         
      url += 'schools';
   }

   url += append;

   object.action = url;
   object.submit();
   
   return false;
}

function checkAll()
{
   var allChecked = true;
   var object = document.getElementById('results_form');
   
   for (var i = 0; i < object.elements.length; i++)
      if (object.elements[i].name.substring(0, 13) == 'school_result' && object.elements[i].checked != true)
      {
         allChecked = false;
         break;
      }
   
   for (var i = 0; i < object.elements.length; i++)
      if (object.elements[i].name.substring(0, 13) == 'school_result')
         object.elements[i].checked = allChecked ? false : true;
   
   return false;
}

function showMap(id, coordinates)
{
   if (GBrowserIsCompatible())
   {
      map = new GMap2(document.getElementById(id));
      map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 8)));
      map.enableDoubleClickZoom();
      map.enableScrollWheelZoom();
      map.enableContinuousZoom();
      var bounds = new GLatLngBounds();
      var smallMarkers = [], largeMarkers = [];
      var markerIcon = null;
      for (var i = 0; i < coordinates.length; i++)
      {
         bounds.extend(coordinates[i][0]);
         var smallIcon = new GIcon();
         smallIcon.image = '/images/markers' + coordinates[i][2] + '/small-marker.png';
         smallIcon.shadow = '/images/markers/small-marker-shadow.png';
         smallIcon.iconSize = new GSize(12, 20);
         smallIcon.shadowSize = new GSize(22, 20);
         smallIcon.iconAnchor = new GPoint(6, 20);
         smallIcon.infoWindowAnchor = new GPoint(5, 1);
         smallIcon.imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0];
         smallIcon.transparent = '/images/markers/small-transparent-marker.png';
         markerIcon = (coordinates.length <= 30) ? new GIcon(G_DEFAULT_ICON, '/images/markers' + coordinates[i][2] + '/marker' + (id == 'map' ? i + 1 : '') + '.png') : smallIcon;
         smallMarkers.push(new GMarker(coordinates[i][0], {icon:markerIcon, title:coordinates[i][1]}));
         markerIcon = (i < 99) ? new GIcon(G_DEFAULT_ICON, '/images/markers' + coordinates[i][2] + '/marker' + (id == 'map' ? i + 1 : '') + '.png') : smallIcon;
         largeMarkers.push(new GMarker(coordinates[i][0], {icon:markerIcon, title:coordinates[i][1]}));
         if (id == 'map')
         {
            smallMarkers[i].bindInfoWindow(changeAddToSchoolBoxLinks(document.getElementById('map_result' + i).cloneNode(true), true));
            largeMarkers[i].bindInfoWindow(changeAddToSchoolBoxLinks(document.getElementById('map_result' + i).cloneNode(true), true));
         }
      }
      var boundsZoomLevel = map.getBoundsZoomLevel(bounds);
      map.setCenter(bounds.getCenter(), Math.min(boundsZoomLevel, 13), id == 'school_map' ? G_HYBRID_MAP : G_NORMAL_MAP);
      var mapProjection = map.getCurrentMapType().getProjection();
      var anchorPointSW = mapProjection.fromLatLngToPixel(bounds.getSouthWest(), boundsZoomLevel);
      var anchorPointNE = mapProjection.fromLatLngToPixel(bounds.getNorthEast(), boundsZoomLevel);
      bounds = new GLatLngBounds(mapProjection.fromPixelToLatLng(new GPoint(anchorPointSW.x - markerIcon.iconAnchor.x, anchorPointSW.y - markerIcon.iconAnchor.y + markerIcon.iconSize.height), boundsZoomLevel), mapProjection.fromPixelToLatLng(new GPoint(anchorPointNE.x - markerIcon.iconAnchor.x + markerIcon.iconSize.width, anchorPointNE.y - markerIcon.iconAnchor.y), boundsZoomLevel));
      map.setCenter(bounds.getCenter(), Math.min(map.getBoundsZoomLevel(bounds), id == 'school_map' ? 17 : 13));
      var markerManager = new GMarkerManager(map);
      markerManager.addMarkers(smallMarkers, 0, 10);
      markerManager.addMarkers(largeMarkers, 11, 17);
      markerManager.refresh();
   }
}

function showDirections(panelId, schoolAddressId, startingAddressId)
{
   directionsPanel = document.getElementById(panelId);
   directionsPanel.innerHTML = '';
   if (directions)
      directions.clear();
   directions = new GDirections(map, directionsPanel);
   GEvent.addListener(directions, 'error', handleDirectionsError);
   directions.load(document.getElementById(startingAddressId).value + ' to ' + document.getElementById(schoolAddressId).value);
   return false;
}

function handleDirectionsError(errorCode)
{
   if (directions.getStatus().code != G_GEO_SUCCESS)
   {
      directionsPanel.innerHTML = 'Driving directions could not be provided.&nbsp; Please make sure that you have entered your starting address correctly.';
      return;
   }
}
