RIGHTWIDTH = 350;

var g = new Object();
var tab = '';

function clearRegion() {
  g.region.value = '';
}

function clearZip() {
  g.zip.value = '';
}

function cookieDelete(key) {
  var time = new Date('January 1, 1970');
  document.cookie = key + '=null; expires=' + time.toGMTString();
}

function cookieGet(key) {
  var pair;
  var pairs = unescape(document.cookie).split('; ');
  for (var i = 0; i < pairs.length; i++) {
    pair = pairs[i].split('=');
    if (pair[0] == key)
      return pair[1];
  }
  return '';
}

function cookieSet(key, value) {
  var time = new Date('July 4, 2030');
  document.cookie = key + '=' + escape(value) + '; expires=' + time.toGMTString();
}

function createMarker(point, i) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(showIncidentHTML(i));
  });
  return marker;
}

function execSearch() {
  var statusText;
  var url;
  
  if (g.zip.value != '') {
    if (g.zip.value.match(/^\d{5}([\-]\d{4})?$/)) {
      parent.window.location = '/zip/' + g.zip.value + '/';
      return;
    }
    else {
      showError('"' + g.zip.value + '" is not a valid zip code.');
      resetSearchForm(0);
      return;
    }
  }
  else
    if (g.region.value != '') {
      parent.window.location = g.region.value;
      return;
    }
    else {
      showError('Please select a zip code or region.');
      return;
    }
}

function loadIncidents(url) {

  g.map.disableDragging();
  g.zip.disabled = 'true';
  g.region.disabled = 'true';

  g.http.open('GET', url, true);
  g.http.onreadystatechange = processResponse;
  g.http.send(null);

}

function initializeMap() {

  g.center = new GLatLng(0, 0);
  g.control = false;
  g.http = GXmlHttp.create();
  g.IE = document.all ? true : false;
  g.map = null;
  g.incidentCount = 0;
  g.incidents = new Array();
  g.tab = 0;

  var form = document.getElementById('searchForm');
  g.zip = form.zip;
  g.zipparam = form.zp.value;
  g.region = form.region;
  g.regionparam = form.rp.value;
  g.initLatitude = form.la.value;
  g.initLongitude = form.lo.value;
  g.initZoom = parseInt(form.zm.value);

  var firefox = navigator.userAgent.indexOf('Firefox') != -1;
  
  var map = document.getElementById('map');
  map.style.width = RIGHTWIDTH;
  map.style.left = 0;
  map.style.display = 'block';

  var right = document.getElementById('right');
  right.style.width = RIGHTWIDTH;
  right.style.display = 'none';
  
  var info = document.getElementById('info');
  info.style.width = RIGHTWIDTH;
  info.style.display = 'block';
  
  resizeMap();
  
  g.map = new GMap(document.getElementById("map"));
  g.large_map_control = new GLargeMapControl();
  g.map_type_control = new GMapTypeControl();
  //g.map.centerAndZoom(new GLatLng(40, -95), 13);
  g.map.centerAndZoom(new GLatLng(g.initLatitude, g.initLongitude), g.initZoom);
  g.map.disableDragging();

  if (window.attachEvent)
    window.attachEvent('onresize', resizeMap);
  else
    window.addEventListener('resize', resizeMap, false);

  resetSearchForm(1);

  if (g.zipparam != '') {
    loadIncidents('incident.asp?z=' + g.zipparam);
  }
  else {
    if (g.regionparam != '') {
      loadIncidents('incident.asp?r=' + g.regionparam);
    }
    else  {
      loadIncidents('incident.asp?a=1');
    }
  }

}

function processFeedbackResponse() {

  if (g.http.readyState != 4)
    return;

  var txt = g.http.responseText;

  if (txt == '')
    showStatus('Feedback sent successfully');
  else
    showError(txt);
}

function processResponse() {

  if (g.http.readyState != 4)
    return;
  var xml = g.http.responseXML;

  resetSearchForm(0);
  
  var data = xml.getElementsByTagName('incidents').item(0);
  g.name = data.getAttribute('name');
  g.lat = parseFloat(data.getAttribute('latitude'));
  g.lng = parseFloat(data.getAttribute('longitude'));

  //if (g.zip.value != '') {
  //  cookieSet('zip', g.zip.value);
  //  cookieDelete('region');
  //}
  //else
  //  if (g.region.value != '') {
  //    cookieSet('region', g.region.value);
  //    cookieDelete('zip');
  //  }

  document.getElementById('incidentPanel').scrollTop = 0;
  document.getElementById('filterPanel').scrollTop = 0;
  document.getElementById('incidents').innerHTML = '';
  document.getElementById('tab0').style.display = 'inline';
  document.getElementById('tab1').style.display = 'inline';

  var incidents = xml.getElementsByTagName('incidents').item(0).getElementsByTagName('incident');
  g.incidentCount = incidents.length;

  if (g.incidentCount) {

    showStatus('Adding ' + g.incidentCount + ' incidents to the map for ' + g.name);

    document.getElementById('tab0').innerHTML = 'Incidents (' + g.incidentCount + ')';

    g.incidents.length = 0;

    g.map.clearOverlays();

    for (var i = 0; i < g.incidentCount; i++) {
      g.incidents[i] = {source: incidents[i].getAttribute('source'),
                        type: incidents[i].getAttribute('type'),
                        identifier: incidents[i].getAttribute('identifier'),
                        date: incidents[i].getAttribute('date'),
                        description: incidents[i].getAttribute('description'),
                        disposition: incidents[i].getAttribute('disposition'),
                        address: incidents[i].getAttribute('address'),
                        city: incidents[i].getAttribute('city'),
                        state: incidents[i].getAttribute('state'),
                        zip: incidents[i].getAttribute('zip'),
                        latitude: parseFloat(incidents[i].getAttribute('latitude')),
                        longitude: parseFloat(incidents[i].getAttribute('longitude'))}
      var point = new GLatLng(g.incidents[i].latitude, g.incidents[i].longitude);
      var marker = createMarker(point, i);
      g.map.addOverlay(marker);
      g.incidents[i].marker = marker;
    }

    if (!g.control) {
      g.control = true;
      g.map.addControl(g.large_map_control);
      g.map.addControl(g.map_type_control);
    }

    var html = '';
    for (var i = 0; i < g.incidentCount; i++)
      html += '<div id="' + g.incidents[i].identifier + '" class="listtitle"><a href="javascript:showIncident(' + i + ')">' + g.incidents[i].type + '</a> <span class="listdate">(' + g.incidents[i].date + ')</span></div>';
    document.getElementById('incidents').innerHTML = html;

    g.map.closeInfoWindow();

    if (g.tab == 1) {
      document.getElementById('filterPanel').style.display = 'block';
      document.getElementById('filter').style.display = 'block';
      document.getElementById('incidentPanel').style.display = 'none';
      document.getElementById('incidents').style.display = 'none';
    }
    else {
      document.getElementById('filterPanel').style.display = 'none';
      document.getElementById('filter').style.display = 'none';
      document.getElementById('incidentPanel').style.display = 'block';
      document.getElementById('incidents').style.display = 'block';
    }

    if (g.name == 'All')
      showStatus('Most recent incidents');
    else
      showStatus('Incidents for ' + g.name);

  }
  else {
    if (g.zip.value != '')
      showError('No incidents found near zip code ' + g.zip.value + '.');
    else
      if (g.name == 'All')
        showError('No recent incidents found.');
      else
        showError('No incidents found near ' + g.name + '.');
  }

  g.center = g.map.getCenterLatLng();
  g.map.enableDragging();

  if (g.name != 'All') {
    document.getElementById('right').style.display = 'block';
    document.getElementById('info').style.display = 'none';
  }

  if (g.map)
    g.map.checkResize();

  resetMinMax();
  g.marker_count = 0;
  for (var i = 0; i < g.incidentCount; i++)
    if (g.incidents[i].marker) {
      g.min_x = Math.min(g.min_x, g.incidents[i].longitude);
      g.max_x = Math.max(g.max_x, g.incidents[i].longitude);
      g.min_y = Math.min(g.min_y, g.incidents[i].latitude);
      g.max_y = Math.max(g.max_y, g.incidents[i].latitude);
      g.marker_count++;
    }
  if (g.marker_count) {
    var bounds;
    var zoom;
    g.map.zoomTo(0);
    do {
      g.map.recenterOrPanToLatLng(new GLatLng((g.min_y + g.max_y) / 2, (g.min_x + g.max_x) / 2));
      bounds = g.map.getBoundsLatLng();
      zoom = g.min_x < bounds.minX || g.max_x > bounds.maxX ||
             g.min_y < bounds.minY || g.max_y > bounds.maxY;
      if (zoom)
        g.map.zoomTo(g.map.getZoomLevel() + 1);
    } while (zoom);
  }
  else
    g.map.recenterOrPanToLatLng(new GLatLng(g.lat, g.lng));
}

function resetMinMax() {
  g.max_x = -180;
  g.max_y = -90;
  g.min_x = 180;
  g.min_y = 90;
}

function resetSearchForm(init) {

  g.zip.disabled = '';
  g.region.disabled = '';
  
  //if (init && g.zip.value == '') {
  //  g.zip.value = cookieGet('zip');
  //  if (g.zip.value == '') {
  //    g.region.value = cookieGet('region');
  //  }
  //}
  g.zip.blur();
  g.zip.focus();
}

function resizeMap() {
  var firefox = navigator.userAgent.indexOf('Firefox') != -1;
  var frame = parent.document.getElementById('frame');
  if (frame)
    var h = frame.clientHeight;
  else
    var h = document.body.clientHeight;
  h -= 50;
  if (h < 0)
    h = 0;
    
  var wdth = document.getElementById('header').clientWidth - RIGHTWIDTH;
  if (wdth < 100)
    wdth = 100;
  var map = document.getElementById('map');
  map.style.width = wdth;
  map.style.height = h;
  
  var info = document.getElementById('info');
  if (info) {
    info.style.left = wdth;
    info.style.height = h;
  }
  if (firefox) {
    document.getElementById('info_panel').style.height = h - 20;
  }
  
  var right = document.getElementById('right');
  if (right) {
    right.style.left = wdth;
    right.style.height = h;
  }

  if (g.map)
    g.map.checkResize();
}

function sendFeedback() {
  
  var form = document.getElementById('feedbackForm');
  var name = form.Name.value;
  var email = form.Email.value;
  var message = form.Message.value;

  showStatus('Sending Feedback...');
  
  g.http.open('GET', 'feedback.asp?n=' + name + '&e=' + email + '&m=' + message, true);
  g.http.onreadystatechange = processFeedbackResponse;
  g.http.send(null);

}

function showError(errorText) {

  var error = document.getElementById('error');
  error.innerHTML = errorText;
  error.style.display = 'block';
  
  document.getElementById('status').style.display = 'none';

}

function showAdvancedSearch() {
  document.getElementById('tab0').className = '';
  document.getElementById('tab1').className = 'selected';
  document.getElementById('info').style.display = 'none';
  document.getElementById('right').style.display = 'block';
  document.getElementById('incidentPanel').style.display = 'none';
  document.getElementById('incidents').style.display = 'none';
  document.getElementById('filterPanel').style.display = 'block';
  document.getElementById('filter').style.display = 'block';
}

function showIncident(i) {
  g.incidents[i].marker.openInfoWindowHtml(showIncidentHTML(i));
}

function showIncidentHTML(i) {
  var html = '<table id="panel_table" class="panel_table" cellspacing="5"><tr><td><div style="width:300px">';
  
  html += '<div class="intitle">' + g.incidents[i].type + '</div>';
  html += '<div class="indate">' + g.incidents[i].date + '</div>';
  if (g.incidents[i].description != '')
    html += '<div class="indescription">' + g.incidents[i].description + '</div>';
  if (g.incidents[i].disposition != '')
    html += '<div class="indisposition">Disposition: ' + g.incidents[i].disposition + '</div>';
  html += '<br /><div class="inaddress">' + g.incidents[i].address + '<br />' + g.incidents[i].city + ', ' + g.incidents[i].state + '  ' + g.incidents[i].zip + '</div><br />';
  html += '<div class="inidentifier">Identifier: ' + g.incidents[i].identifier + '</div>';
  html += '<div class="insource">Source: <i>' + g.incidents[i].source + '</i></div>';
  html += '</div></td></tr></table>';
  return html;
}

function showIncidentList() {
  document.getElementById('tab0').className = 'selected';
  document.getElementById('tab1').className = '';
  document.getElementById('info').style.display = 'none';
  document.getElementById('right').style.display = 'block';
  document.getElementById('filterPanel').style.display = 'none';
  document.getElementById('filter').style.display = 'none';
  document.getElementById('incidentPanel').style.display = 'block';
  document.getElementById('incidents').style.display = 'block';
}

function showStatus(statusText) {

  var status = document.getElementById('status');
  status.innerHTML = statusText;
  status.style.display = 'block';
  
  document.getElementById('error').style.display = 'none';

}

