var infoSections = new Array();
var dateFields = new Array();
var crimeTypes = new Array();
var crimeList = new Array();
var currentPeriod = '';
var currentType = 'A';
var countDisplay = 0;
var countTotal = 0;
var countLimit = 30;
var countOffset = 0;
var map = '';

infoSections['crime-types'] = 1;
infoSections['crime-periods'] = 0;
dateFields['date-from'] = '';
dateFields['date-to'] = '';

crimeTypes = {  'A'   : [ 'crime', 'crimes', 'Crimes' ],
                '710' : [ 'vehicle theft', 'vehicle thefts', 'Vehicle thefts'],
                '640' : [ 'theft from a vehicle', 'thefts from a vehicle', 'Thefts from a vehicle' ],
                '300' : [ 'robbery', 'robberies', 'Robberies' ],
                '510' : [ 'home break-in', 'home break-ins', 'Home break-ins' ],
                '511' : [ 'business break-in', 'business break-ins', 'Business break-ins' ],
                '410' : [ 'aggravated assault', 'aggravated assaults', 'Agravated assaults' ],
                '830' : [ 'sexual assault', 'sexual assaults', 'Sexual assaults' ],
                '2620' : [ 'kidnapping', 'kidnappings', 'Kidnappings' ],
                '1610' : [ 'report of prostitution', 'reports of prostitution', 'Reports of prostitution' ],
                '120' : [ 'report of manslaughter', 'reports of manslaughter', 'Reports of manslaughter' ],
                '110' : [ 'murder', 'murders', 'Murders' ]  };

function load()
{
  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(35.05417, -78.877201), 11);
  }
  $('date-to').value='';
  $('date-from').value='';
  $('count').selectedIndex=2;
  displayCrimes();
}

function toggleInfoSection(section)
{
  if (infoSections[section])
  {
    $(section + '-list').style.display='none';
    $(section + '-bottom').style.display='none';
    $(section + '-indicator').src = '/images/icon-unfold.png';
    infoSections[section] = 0;
  }
  else
  {
    $(section + '-list').style.display='block';
    $(section + '-bottom').style.display='block';
    $(section + '-indicator').src = '/images/icon-fold.png';
    infoSections[section] = 1;
  }
}

function toggleTabs(tab)
{
  if (tab == 'map')
  {
    $('tab-map').className='tab-on';
    $('tab-data').className='tab-off';
    $('data-container').style.display='none';
    $('map-container').style.display='block';
  }
  else
  {
    $('tab-data').className='tab-on';
    $('tab-map').className='tab-off';
    $('map-container').style.display='none';
    $('data-container').style.display='block';
  }  
}

function toggleDatabase()
{
  if ($('database-framework').style.display == 'block')
  {
    $('database-framework').style.display = 'none';
    $('database-indicator').src = '/images/icon-unfold.png';
  }
  else
  {
    $('database-framework').style.display = 'block';
    $('database-indicator').src = '/images/icon-fold.png';
  }
}

function toggleRange()
{
  if ($('controls-range').style.display == 'block')
  {
    $('controls-range').style.display = 'none';
    $('controls-range-button').value = 'Set a Range';
  }
  else
  {
    $('controls-range').style.display = 'block';
    $('controls-range-button').value = 'Hide Range Controls';
  }
}

function toggleInfoOption(section,option)
{
  var s = section + '-list-element';
  for (var x=0; x < $(s).childNodes.length; x++)
  {
    if ($(s).childNodes[x].nodeType == 1) { $(s).childNodes[x].className=''; }
  }
  if (option) { $(option).className='info-box-section-list-selected'; }
}

function datePickerClosed(obj)
{
  if ($(obj.name).value != dateFields[obj.name])
  {
    dateFields[obj.name] = $(obj.name).value;
    currentPeriod = '';
    displayCrimes();
  }
}

function addMarker(latlng,html)
{
  var marker = new GMarker(latlng);
  GEvent.addListener(marker, 'click', function() { var markerHTML = html; marker.openInfoWindowHtml(markerHTML); });
  //GEvent.addListener(marker, 'mouseover', function() { var markerHTML = html; marker.openInfoWindowHtml(markerHTML); });
  //GEvent.addListener(marker, 'mouseout', function() { marker.closeInfoWindow(); });
  return marker;
}
function setPeriod(p)
{
  var d = new Date();
  d.setDate(d.getDate()-p);
  $('date-to').value = '';
  $('date-from').value = d.getFullYear() + '-' + leadingZeros(d.getMonth()+1) + '-' + leadingZeros(d.getDate());

  if (p == 30)
  {
    currentPeriod = ' in the last month'
  }
  if (p == 60)
  {
    currentPeriod = ' in the last two months'
  }
  if (p == 90)
  {
    currentPeriod = ' in the last three months'
  }
  if (p == 180)
  {
    currentPeriod = ' in the last six months'
  }
  displayCrimes();
}

function leadingZeros(s)
{
  if (s < 10) { return '0' + s; }
  else { return s; }
}

function setMessage()
{
  var ct = '';
  var cp = '';
  
  // --- Determine the type portion of the message
  if (currentType == 'A')
  {
    if (countDisplay != 1)
    {
      if (countTotal > countDisplay) { ct = 'Crimes'; }
      else { ct = 'crimes'; }
    }
    else { ct = 'crime'; }
  }
  else
  {
    if (countDisplay != 1)
    {
      if (countTotal > countDisplay)
      {
        ct = crimeTypes[currentType][2];
      }
      else
      {
        ct = crimeTypes[currentType][1];
      }
    }
    else { ct = crimeTypes[currentType][0]; }
  }

  // --- Determine the time portion of the message
  if (currentPeriod)
  {
    cp = currentPeriod;
  }
  else
  {
    if (($('date-from').value) && ($('date-to').value)) { cp = ' between ' + $('date-from').value + ' and ' + $('date-to').value; }
    else if ($('date-from').value) { cp = ' after ' + $('date-from').value; }
    else if ($('date-to').value) { cp = ' until ' + $('date-to').value; }
    else
    {
      cp = '';
    }
  }

  var cs = countOffset+1;
  var ce = countOffset+countDisplay;
  if (ce > countTotal) { ce = countTotal; }

  if (countDisplay)
  {
    if (countTotal > countDisplay) { return ct + ' ' + cs + ' thru ' + ce + ' (of ' + countTotal + ') reported' + cp + '.'; }
    else { return 'The ' + countDisplay + ' ' + ct + ' reported' + cp + '.'; }
  }
  else
  {
    return 'There are no ' + ct + ' listed ' + cp + '.';
  }
}

function setPages()
{
  var sp = 0;
  var np = 0;
  var ep = 0;
  var ap = 0;
  var b = 6;
  var html = '<table><tr>';

  if (countTotal > countLimit)
  {
    ap = parseInt(countOffset/countLimit);
    np = parseInt(countTotal/countLimit)-1;
    if (countTotal%countLimit) { np++; }
    
    if (np <= 4)
    {
      sp = 0;
      ep = np;
    }
    else
    {
      if (ap > (b/2)) { sp = ap - (b/2); }
      else { sp = 0; }
      if ((np-ap) > (b/2))
      {
        ep = ap + (b/2);
        if ((ep - sp) < b) { ep = sp + b; }
      }
      else { ep = np; }
    }

    if (sp > 0) { html += '<td class="message-pages-edge" onclick="javascript:countOffset=0;displayCrimes();">1...</td>'; }

    for (var p = sp; p <= ep; p++)
    {
      if (p == ap) { html += '<td class="message-pages-active">' + (p+1) + '</td>'; }
      else { html += '<td onclick="javascript:countOffset=' + (p*countLimit) + ';displayCrimes();">' + (p+1) + '</td>'; }
    }

    if (ep < np) { html += '<td class="message-pages-edge" onclick="javascript:countOffset=' + (np*countLimit) + ';displayCrimes();">...' + (np+1) + '</td>'; }
  
    html += '</tr></table>';
    $('message-pages').innerHTML = html;
  }
  else
  {
    $('message-pages').innerHTML = '';
  }
}

function displayCrimes()
{
  start = $('date-from').value;
  end = $('date-to').value;

  map.clearOverlays();

  new Ajax.Request("/910crime.com/tools/crimes.pl",
  {
    onSuccess: function (resp)
    {
      var data = resp.responseText.evalJSON();

      if (data['Status'] == 'OK')
      {
        crimeList = [];
        var table = '<table id="data-table">';

        for (x = 0; x < data['Crimes'].length; x++)
        {
          var address = data['Crimes'][x]['Address'];
          var re = /^(\d+)\s+(.*)$/;
          var a = data['Crimes'][x]['Address'];
          var n = '';
          var s = '';
          if (a.match(re))
          {
            a = a.match(re);
            if (a.length)
            {
              if (a[1] >= 100) { n = Math.floor(a[1]/100)*100; }
              else { n = Math.ceil(a[1]/100)*100; }
              s = a[2]
              address = n + ' block of ' + s;
            }
          }

          // --- Build the tabular data view for this item
          table += '<tr>\n';
          table += '<td>' + (x+1+countOffset) + '</td>\n';
          table += '<td><a href="' + data['Crimes'][x]['IncidentLink'] + '">' + data['Crimes'][x]['Incident'] + '</a></td>';
          table += '<td  width="100">' + data['Crimes'][x]['TDate'] + '</td>\n';
          table += '<td>';
          if (data['Crimes'][x]['Business'])
          {
            table += data['Crimes'][x]['Business'] + ' at ';
          }
          table += address + '</td>\n';
          // table += '<td>' + data['Crimes'][x]['UCR'] + '</td>\n';
          table += '<td>' + data['Crimes'][x]['Description'] + '</td>\n';
          table += '</tr>\n';

          // --- Map the point for this item (but don't map more than 100)
          if (x <= 100)
          {
            var html = '<div class="popup-container"><div class="popup-title">' + data['Crimes'][x]['Description'] + '</div>';
            html += '<p><b>Where:</b> ';
            if (data['Crimes'][x]['Business']) { html += data['Crimes'][x]['Business'] + ' at '; }
            html += address;
            html += '<br /><b>When:</b> ' + data['Crimes'][x]['Date'];
            html += '<br/><b>Case Number:</b> <a href="' + data['Crimes'][x]['IncidentLink'] + '">' + data['Crimes'][x]['Incident'] + '</a></p></div>';
            var latlng = new GLatLng(data['Crimes'][x]['Latitude'],data['Crimes'][x]['Longitude']);
            crimeList[x]= { 'latlng' : latlng, 'html' : html };

            map.addOverlay(addMarker(latlng,html));
          }
        }

        table += '</table>\n';
        $('data-container').innerHTML = table;

        countTotal = data['Total'];
        countDisplay = data['Crimes'].length;
        $('message-text').innerHTML = '<b>Currently Displaying:</b> ' + setMessage();
      }
      else
      {
        countDisplay = 0;
        countTotal = 0;
        $('message-text').innerHTML = '<b>Currently Displaying:</b> ' + setMessage();
      }
      setPages();
    },
    onFailure: function() { alert('Something went horribly awry...'); },
    parameters: 'UCR=' + currentType + '&count=' + countLimit + "&start=" + start + "&end=" + end + "&offset=" + countOffset
  });
  $('message-text').innerHTML = '<b>Currently Loading:</b> ' + setMessage();
}
function changeCount()
{
  var i = $('count').selectedIndex;
  var v = $('count').options[i].value;
  alert('Index is: ' + v);
  
}
