var map;
var markers = new Array();
var marker_manager;
markers[0] = new Array();
markers[1] = new Array();
markers[2] = new Array();
markers[3] = new Array();
markers[4] = new Array();
markers[5] = new Array();

var point1;
var point2;
var polylines = new Array();
var onepoint = false;
var point_marker;

var milesFactor = 1609.344

$(document).ready(function () {
  if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
//marker_manager = new MarkerManager(map);
map.setCenter(new GLatLng(44.9441, -93.0852), 12);

var scalePos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(100,3)); 
map.addControl(new GScaleControl(), scalePos);
map.addControl(new GLargeMapControl3D());
map.addMapType(G_PHYSICAL_MAP);
map.addControl(new GMapTypeControl());
map.addControl(new GOverviewMapControl());
map.enableGoogleBar();

initialize();

GEvent.addListener(map,"click", function(overlay,latlng){
if (latlng)
{
}
if (overlay) 
{
if (overlay instanceof GMarker)
{
var church_id = overlay.getTitle();
pop_up_church(church_id);

}
}
});

  }
  else
alert('Your browser is not supported!');

$(window).unload( function () { GUnload(); });

$("#early_date").datepick({dateFormat: 'mm/dd/yy', duration: 1});
$("#late_date").datepick({dateFormat: 'mm/dd/yy', duration: 1});

$(".asc, .desc").live('click', function () {
var order_by = $(this).parent().attr('class');
var direction;

if ($(this).hasClass('asc'))
direction = 'asc';
else
direction = 'desc';


if ($(this).hasClass('report'))
load_reports(order_by, direction);
else if ($(this).hasClass('church'))
load_church_list(order_by, direction);
});
/*
$(".list_row").live('click', function () {
var report_id = $(this).attr('id');
report_id = report_id.substring(1);
//alert(report_id);
load_report_detail(report_id);
});*/

$(".change_view").live('change', function() {
change_view();
});


$("#match").focus(function () {
if ($(this).val() == 'Search for...')
$(this).val('');

});


$(".toggle_on, .toggle_off").live('click', function() {

var off;

var marker_id = $(this).attr('title');
var instances = $("span[title='"+marker_id+"']");

if ($(this).attr('class') == 'toggle_on')
{
off = true;
instances.each(function (i) {
$(this).html('&#9744;');
$(this).attr('class', 'toggle_off');
});
}
else
{
off = false;
instances.each(function (i) {
$(this).html('&#9745;');
$(this).attr('class', 'toggle_on');
});
}

toggle_marker(marker_id, off);
});




$("#toggle_picker").click(function () {
if ($(this).html() == "Hide")
{
$(this).html('Show');
$("#inner_date").slideUp();

}
else
{
$(this).html('Hide');
$("#inner_date").slideDown();
}
});

$(".all_on, .all_off").live('click', function() {

var off;

if ($(this).attr('class') == 'all_on')
{
off = true;
var instances = $("span[class='all_on']");

instances.each(function (i) {
$(this).html('&#9744;');
$(this).attr('class', 'all_off');
});


}
else
{
off = false;
var instances = $("span[class='all_off']");

instances.each(function (i) {
$(this).html('&#9745;');
$(this).attr('class', 'all_on');
});
}

toggle_all(off);
});

$("#tab-pane td").live('click', function () {

var tab = $(this)
show_tab(tab);

});


$("#church_list .list_row td.click").live('click', function() {
var id = $(this).attr('title');
pop_up_church(id);


});

$("#search_results .list_row td.click").live('click', function () {
var id = $(this).parent().attr('id');
id = id.substring(1);
show_report_detail(id);
show_tab($("#detail_tab"));
});

$("#report_list .list_row td.click").live('click', function () {
var id = $(this).parent().attr('id');
id = id.substring(1);
show_report_detail(id);
show_tab($("#detail_tab"));
});



$("#search_button").live('click', function () {

search();

});

$("#match").keypress(function (e) {
if (e.which == 13)
search();
});

});


function undo_set_point(marker_id)
{
onepoint = false;
point_marker = -1;
$("#infowindow").html('<a href="javascript:set_point(\''+marker_id+'\')">Set Point A</a>');
}

function set_point(marker_id)
{
var marker;

if (marker_id.length > 3 && marker_id.substring(0, 3) == "syn")
{
marker = markers[3][marker_id];
}
else if (marker_id.length > 3 && marker_id.substring(0, 3) == "sch")
{
marker = markers[4][marker_id];
}
else if (marker_id.length > 3 && marker_id.substring(0, 3) == "h24")
{
marker = markers[5][marker_id];
}
else
{
if (markers[0][marker_id] != undefined)
marker = markers[0][marker_id];
else if (markers[1][marker_id] != undefined)
marker = markers[1][marker_id];
else
marker = markers[2][marker_id];
}


$("#infowindow").html("Set");

if (!onepoint)
{
point1 = marker.getLatLng();
onepoint = true;
point_marker = marker_id;

$("#infowindow").html('Point A set | <a href="javascript:undo_set_point(\''+marker_id+'\')">Unset</a>');

}
else
{
point2 = marker.getLatLng();
onepoint = false;
point_marker = -1;

$("#infowindow").html("Point B Set, Loading Data...");

wayPoints = new Array();
wayPoints[0]=point1;
wayPoints[1]=point2;


var polyOptions = {geodesic:true};
polylines[0]=new GPolyline([
point1,
point2
], "#00ffff", 5,null,polyOptions);
var cfmeters=polylines[0].getLength();
cfmeters = cfmeters * 100;
cfmeters = Math.floor(Math.round(cfmeters));
cfmeters = cfmeters / 100;
cfmiles = cfmeters / milesFactor * 100;
cfmiles = Math.floor(Math.round(cfmiles));
cfmiles = cfmiles/100;

var directions = new GDirections(map, null);
polylines[1] = directions;
GEvent.addListener(directions,"load", 
function() 
{
var meters = directions.getDistance().meters;
meters = meters * 100;
meters = Math.floor(Math.round(meters));
meters = meters / 100;
miles = meters / milesFactor * 100;
miles = Math.floor(Math.round(miles));
miles = miles/100;
var duration = directions.getDuration().seconds / 60;
duration = duration * 10;
duration = Math.floor(Math.round(duration));
duration = duration / 10;
html = "\"As the Crow Flies\" Distance: " + cfmeters + " meters. ("+cfmiles+" miles) <br />";
html += "Driving Distance: "+meters + " meters. ("+miles+ " miles) &nbsp;Approx "+duration+" minutes &nbsp;&nbsp; <a href=\"javascript:remove_polyline()\">Remove line<\/a>";
$("#infowindow").html("");
$("#distance_results").html(html);
$("#distance_results").show();
});
directions.loadFromWaypoints(wayPoints, { preserveViewport: true });
}
}

function remove_polyline()
{
if (polylines[0] instanceof GDirections)
polylines[0].clear();
if (polylines[1] instanceof GDirections)
polylines[1].clear();

$("#distance_results").html('');
$("#distance_results").hide('');
}

function search() 
{
var user_query = $("#match").val();
var query = escape(user_query);
query = query.replace(/\+/g,"%2B");

reset_colors();
$("#search_count").html('(0)');

var timeframe = "";

if ($("#timeframe").val() == 'custom')
{
var start_date = "&start_date="+escape($("#early_date").val());
var end_date = "&end_date="+escape($("#late_date").val());

var days = "&days=";
days += ($("#sun").is(":checked")) ? "1" : "0";
days += ($("#mon").is(":checked")) ? "1" : "0";
days += ($("#tue").is(":checked")) ? "1" : "0";
days += ($("#wed").is(":checked")) ? "1" : "0";
days += ($("#thu").is(":checked")) ? "1" : "0";
days += ($("#fri").is(":checked")) ? "1" : "0";
days += ($("#sat").is(":checked")) ? "1" : "0";

timeframe = start_date + end_date + days;
}

$.getJSON("./gen/search?query="+query+timeframe, function(data){
var results = $("#search_results");
results.empty();
if (data.error.code == 0)
{
reset_colors();
$("#search_count").html('(' + data.count + ') | <a href="javascript:reset_colors()" style="color:#eef; text-decoration: none;">Reset</a>');

var results_info = '<tr class="report_list_header">';
results_info += '<td colspan="9" style="padding-left: 3px; text-align: left;">'+data.count+ ' results for "'+user_query+'" | Date Range: ' + data.min_date +' - ' + data.max_date+'</td>';
results_info += '</tr>';

results.append(results_info);

var header = '<tr class="report_list_header">';
header += '<td>ID</td>';
header += '<td>Church</td>';
header += '<td>Date</td>';
header += '<td>Time</td>';
header += '<td>Day</td>';
header += '<td>Method</td>';
header += '<td>Modus Operandi</td>';
header += '<td>Suspect Description</td>';
header += '<td>Stolen Items</td>';
results.append(header);

var oddeven = 'odd';
var counter = 0;
$.each(data.reports, function(i, report){
row = '';
row += '<tr class="list_row ' + oddeven + '" id="r'+report.id+'">';
row += '<td class="center click" title="'+report.id+'">'+report.id+'</td>';
row += '<td class="pad click" title="'+report.id+'">' + report.church+ '</td>';
row += '<td class="pad center click" title="'+report.id+'">' + report.date + '</td>';
row += '<td class="pad center">' + report.time + '</td>';
row += '<td class="pad center">' + report.day + '</td>';
row += '<td class="center">' + report.method + '</td>';
row += '<td class="center">' + report.MO + '</td>';
row += '<td class="center">' + report.suspect_desc + '</td>';
row += '<td class="center">' + report.stolen_items + '</td>';
row += '</tr>';

markers[1][report.church_id].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png");

results.append(row);

if (oddeven == 'odd')
oddeven = 'even';
else
oddeven = 'odd';

counter++;

if (counter % 9 == 0)
results.append(header);
});




}
else
{
results.append('<tr class="report_list_header"><td class="huge">No Results Found for "'+query+'"</td></tr>');
}

show_tab($("#search_tab"));
});
}

function show_report_detail(report_id)
{
var details = $("#report_details");
var header = '<tr class="report_list_header">';
header += '<td class="id">ID</td>';
header += '<td class="name">Church</td>';
header += '<td class="address">Address</td>';
header += '<td class="date">Date</td>';
header += '<td class="time">Time</td>';
header += '<td class="day">Day</td>';
header += '<td class="meet">AA Meeting</td>';
header += '<td class="cn">CN</td>';
header += '</tr>';

details.empty();
details.append(header);


$.getJSON("./gen/report_details?id="+escape(report_id), function(record){
if (record.error.code == 0)
{
pop_up_church(record.church_id);
var row = '<tr class="list_row">';
row += '<td class="center">' + record.id + '</td>';
row += '<td class="pad">' + record.church + '</td>';
row += '<td class="center">' + record.address + '</td>';
row += '<td class="center">' + record.date + '</td>';
row += '<td class="center">' + record.time + '</td>';
row += '<td class="center">' + record.day + '</td>';
row += '<td class="center">' + record.aa_meeting + '</td>';
row += '<td class="center">' + record.CN + '</td>';
row += '</tr>';
details.append(row);

var row2 = '<tr class="report_list_header">';
row2 += '<td colspan="2">Method</td>';
row2 += '<td colspan="2">Modus Operandi</td>';
row2 += '<td colspan="2">Suspect Description</td>';
row2 += '<td colspan="2">Stolen Items</td>';
row2 += '</tr>';

details.append(row2);

var row3 = '<tr class="list_row">';
row3 += '<td class="center" colspan="2">&nbsp;' + record.method + '&nbsp;</td>';
row3 += '<td class="center" colspan="2">&nbsp;' + record.MO + '&nbsp;</td>';
row3 += '<td class="center" colspan="2">&nbsp;' + record.suspect_desc + '&nbsp;</td>';
row3 += '<td class="center" colspan="2">&nbsp;' + record.stolen_items + '&nbsp;</td>';

details.append(row3);

}

});

}

function show_tab(tab)
{
reset_all_tabs();
tab.addClass('tab_highlight');
var selector = "#" + tab.attr('title');
$(selector).show();

}


function reset_all_tabs()
{
$("#report_list").hide();
$("#church_list").hide();
$("#report_details").hide();
$("#search_results").hide();
$("#tab-pane td").removeClass('tab_highlight');
}


function load_report_detail(report_id)
{

}

function change_view() 
{
if ($("#burglarized").is(':checked') == false)
hide_burglarized();
else
show_burglarized();

if ($("#unburglarized").is(':checked') == false)
hide_unburglarized();
else
show_unburglarized();
}


function hide_unburglarized()
{
for (var i in markers[0])
markers[0][i].setImage("http://camodeca.net/gd/transparent.png");
}

function hide_burglarized()
{
for (var i in markers[1])
markers[1][i].setImage("http://camodeca.net/gd/transparent.png");
}

function show_unburglarized()
{
for (var i in markers[0])
markers[0][i].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");

}

function show_burglarized()
{
for (var i in markers[1])
markers[1][i].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");

}

function clear_map()
{
map.clearOverlays();
}

function initialize()
{
load_reports('id','asc');
load_church_list('name','asc');
load_burglarized_churches();
load_unburglarized_churches();
}


function pop_up_church(marker_id)
{
$.getJSON("./gen/church_details?id="+escape(marker_id), function (data) {
if (data.error.code == 0)
{
var index = data.burglarized;
var name = data.name;
var address = data.address;
var marker = markers[index][marker_id];
if (!onepoint)
letter = 'A';
else
letter = 'B';

if (marker_id == point_marker)
{
marker.openInfoWindowHtml('<div>'+name+'<br />'+address+'<br /><span id="infowindow">Point A set | <a href="javascript:undo_set_point('+marker_id+')">Unset</a></span>');
}
else
{
marker.openInfoWindowHtml('<div>'+name+'<br />'+address+'<br /><span id="infowindow"><a href="javascript:set_point('+marker_id+')">Set Point '+letter+'</a></span>');
}
}

});
}

function load_church_list(order_by, direction)
{

$.getJSON("./gen/church_list.php?order_by="+escape(order_by)+"&dir="+escape(direction), function(data){
if (data.error.code == 0)
{
var counter = 0;
var oddeven = 'odd';
var church_list = $("#church_list");
church_list.empty();
var sort = ' &nbsp;<span class="asc church">&uarr;</span>&nbsp;<span class="desc church">&darr;</span>';
var header = '<tr class="report_list_header">';
header += '<td class="id">ID '+sort+'</td>';
header += '<td class="name">Name '+sort+'</td>';
header += '<td class="address">Address '+sort+'</td>';
header += '<td class="aa">A.A. Meetings '+sort+'</td>';
header += '<td class="burglarized">Burglarized? '+sort+'</td>';
header += '</tr>';
church_list.append(header);
$.each(data.churches, function(i, record){

row = '';
row += '<tr class="list_row ' + oddeven + '" id="r'+record.id+'">';
row += '<td class="center click" title="'+record.id+'">'+record.id+'</td>';
row += '<td class="pad click" title="'+record.id+'">' + record.name+ '</td>';
row += '<td class="center click" title="'+record.id+'">' + record.address + '</td>';
row += '<td class="center">' + record.aa_meetings + '</td>';
row += '<td class="center">' + record.burglarized + '</td>';
row += '</tr>';

church_list.append(row);

if (oddeven == 'odd')
oddeven = 'even';
else
oddeven = 'odd';

counter++;

if (counter % 9 == 0)
church_list.append(header);
});
}
});


}


function reset_colors()
{
for (var i in markers[1])
{
markers[1][i].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");
}

for (var i in markers[0])
{
markers[0][i].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
}

}

function load_burglarized_churches()
{
var redIcon = new GIcon(G_DEFAULT_ICON);
redIcon.shadow = ""; 
redIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png"; 
redIcon.iconSize = new GSize(32, 32);

$.getJSON("./gen/churches.php", function(data) {
if (data.error.code == 0)
{
$.each(data.churches, function(i, church){
if (church.burglarized == 't')
{
var id = church.id;
markerOptions = { title: id, icon:redIcon};
markers[1][id] = new GMarker(new GLatLng(church.lat, church.lng), markerOptions);
map.addOverlay(markers[1][id]);
}
});


}

});
}

function load_unburglarized_churches()
{
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.shadow = ""; 
blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; 
blueIcon.iconSize = new GSize(32, 32);

$.getJSON("./gen/churches.php", function(data) {
if (data.error.code == 0)
{
$.each(data.churches, function(i, church){
if (church.burglarized == 'f')
{
var id = church.id;
markerOptions = { title: id, icon:blueIcon};
markers[0][id] = new GMarker(new GLatLng(church.lat, church.lng), markerOptions);
map.addOverlay(markers[0][id]);
}
});


}

});
}


function toggle_all(off)
{
if (off)
{
for (var marker_id in markers[1])
{
markers[1][marker_id].setImage("http://camodeca.net/gd/transparent.png");
var instances = $("span[title='"+marker_id+"']");

instances.each(function (i) {
$(this).html('&#9744;');
$(this).attr('class', 'toggle_off');
});
}
}
else
{
for (var marker_id in markers[1])
{
markers[1][marker_id].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");
var instances = $("span[title='"+marker_id+"']");

instances.each(function (i) {
$(this).html('&#9745;');
$(this).attr('class', 'toggle_on');
});
}
}
}


function timeframe_change(value)
{
if (value == 'all')
$("#date_picker").slideUp();
else 
{
var position = $("#search").position();
var width = $("#search").width();
$("#date_picker").css('position','absolute');
$("#date_picker").css('top','0px');
$("#date_picker").css('left', position.left);
$("#date_picker").css('width', width);
$("#date_picker").slideDown();
}
}


function toggle_marker(marker_id, off)
{
if (off)
markers[1][marker_id].setImage("http://camodeca.net/gd/transparent.png");
else
markers[1][marker_id].setImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png");

}


function load_reports(order_by, direction)
{
$.getJSON("./gen/reports.php?order_by="+escape(order_by)+"&dir="+escape(direction), 
function(data){
if (data.error.code == 0)
{
var counter = 0;
var oddeven = 'odd';
var report_list = $("#report_list");
report_list.empty();
var sort = ' &nbsp;<span class="asc report">&uarr;</span>&nbsp;<span class="desc report">&darr;</span>';
var header = '<tr class="report_list_header">';
header += '<td class="center"><span class="all_on" style="font-size: 1.4em !important;">&#9745;</span></td>';
header += '<td class="id">ID'+sort+'</td>';
header += '<td class="name">Church'+sort+'</td>';
header += '<td class="address">Address'+sort+'</td>';
header += '<td class="date">Date'+sort+'</td>';
header += '<td class="time">Time'+sort+'</td>';
header += '<td class="day">Day'+sort+'</td>';
header += '<td class="meet">Stolen Items'+sort+'</td>';
header += '<td class="cn click">CN'+sort+'</td>';
header += '</tr>';
report_list.append(header);

$("#count").html(data.count);
$("#date_range").html(data.min_date + " - " + data.max_date + " (" +data.range+" days)");

$("#early_date").val(data.min_date);
$("#late_date").val(data.max_date);

$.each(data.records, function(i, record){

row = '';
row += '<tr class="list_row ' + oddeven + '" id="r'+record.id+'">';
row += '<td class="center"><span style="font-size: 80%;" class="toggle_on" title="'+record.church_id+'">&#9745;</span></td>';
row += '<td class="center click">' + record.id + '</td>';
row += '<td class="pad click">' + record.church + '</td>';
row += '<td class="center click">' + record.address + '</td>';
row += '<td class="center click">' + record.date + '</td>';
row += '<td class="center click">' + record.time + '</td>';
row += '<td class="center click">' + record.day + '</td>';
row += '<td class="center click">' + record.aa_meeting + '</td>';
row += '<td class="center click">' + record.CN + '</td>';
row += '</tr>';

report_list.append(row);

if (oddeven == 'odd')
oddeven = 'even';
else
oddeven = 'odd';

counter++;

if (counter % 9 == 0)
report_list.append(header);
});
}
});
}