var base_icon_url = plugin_url+"/icons/";
var problem_icon = base_icon_url+"problem-icon.png";
var construction_icon = base_icon_url+"construction-icon.png";
var info_icon = base_icon_url+"info-icon.png";

var global_report_type = 'a';
var global_show_wards=0;
var global_mask=4095;

var firsttime=1;

var map;
var markers = [];
var infowindow = new google.maps.InfoWindow({content: "<h1>Foo</h1>", maxWidth: 500});
var boundary_layer = null;

var tshow_ward_boundaries=0;
var bikeLayer = new google.maps.BicyclingLayer();
var pano=null;

function bikemap_initialize() {
    map = new google.maps.Map(document.getElementById('bikemap'), {
    center: city_center,
    zoom: 15,
    streetViewControl: true,
    mapTypeId: 'roadmap'
  });
  google.maps.event.addListener(map, 'click', function(evt){
       if (infowindow) {infowindow.close();}
  });

  obp_button_div = document.createElement('DIV');
  obp_button = new obp_control(obp_button_div,map);
  obp_button_div.index = 1;
  map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(obp_button_div);
        
  bikeLayer.setMap(map);

  report_types_create("report_types_select",1,1);

  update_query(global_show_wards,global_report_type,global_mask);
}


function obp_control(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '1px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to set the map to Home';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.id="status_line";
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '8px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = '<b>'+site_name+'</b>';
  controlUI.appendChild(controlText);

  google.maps.event.addDomListener(controlUI, 'click', function() 
     { parent.location = base_url; });
}

function update_query(ward,report_type, mask)
{
  var first_query=1;
  var query_str;

  function add_and() { 
     if (first_query) { 
         first_query=0; query_str+=" WHERE "; 
     } else query_str+=" AND "; 
  }

  for (var i=0;i<markers.length;i++) {
    markers[i].setMap(null);
  }

  //create a viz query to send to Fusion Tables
  query_str = 
       "SELECT title, latitude, longitude, 'report type', "+
       "description, filenames, ward, mask, pano, number, revision, "+
       "url, url_title FROM " + table_number;

  add_and();
  query_str+=" state="+"'p'";

  if (ward!=0) {
    add_and();
    query_str+="ward="+ward.toString();
  }

  if (report_type!='a') {
    add_and();
    query_str+=" 'report type'='"+report_type+"'";
  }

  var query = new google.visualization.Query(
      'http://www.google.com/fusiontables/gvizdata?tq=' 
       + encodeURIComponent(query_str));

  status_update("Updating map...");

  //set the callback function that will be called when the query returns
  query.send(getData);
}

//define callback function, this is called when the results are returned
function getData(response) {

  if (response==null) {
      status_update("error querying server");
      return;
  }
  if (response.getDataTable()==null) {
      status_update("No results");
      return;
  }

  var gotone=0;
  var have_data_for_ward = [];
  for (var i=1;i<num_wards;i++) have_data_for_ward[i]=0;
  var bounds = new google.maps.LatLngBounds();
  //for more information on the response object, see the documentation
  //http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
  var numRows = response.getDataTable().getNumberOfRows();

  status_update("Displaying "+numRows+" items");

  //create an array of row values
  for (i = 0; i < numRows; i++) {
    var latitude = response.getDataTable().getValue(i,1);
    var longitude = response.getDataTable().getValue(i,2);
    var report_type = response.getDataTable().getValue(i,3);
    var mask = response.getDataTable().getValue(i,7);
    var ward = response.getDataTable().getValue(i,6);

    // FIXME: When we put automatic ward calculation back in, make sure ward is set
    if ((latitude=="") || (longitude=="") || (report_type=="")) {
      continue;
    }

    have_data_for_ward[ward]++;

    var marker = new google.maps.Marker({
        map: map, 
        position: new google.maps.LatLng(latitude,longitude),
        icon_url: get_icon_url(report_type),
        icon: icon_set_type(report_type),
        report_type: report_type
    });

    if ((mask & global_mask)==0) {
      marker.setVisible(false);
    } else {
      gotone++;
      bounds.extend(marker.position);
    }

    markers.push(marker);

    marker.mask=mask;
    marker.title = response.getDataTable().getValue(i,0);
    marker.description = response.getDataTable().getValue(i,4);
    var filenames= response.getDataTable().getValue(i,5);
    var pano = response.getDataTable().getValue(i,8);
    marker.number = response.getDataTable().getValue(i,9);
    marker.revision = response.getDataTable().getValue(i,10);
    var urls = response.getDataTable().getValue(i,11);
    var url_titles = response.getDataTable().getValue(i,12);

    if (filenames.length>0) 
       marker.files = filenames.split(',');
    else
       marker.files = [];

    if (urls.length>0) {
       marker.urls = urls.split(',');
       marker.url_titles = url_titles.split(',');
    } else {
       marker.urls = [];
       marker.url_titles = [];
    }

    marker.have_pano=0;
    if (pano.length>0) {
        var components = pano.split(',');
        marker.pano_latlng=new google.maps.LatLng(components[0],components[1]);
        marker.pano_heading=components[2];
        marker.pano_pitch=components[3];
        marker.pano_zoom=components[4];
        marker.have_pano=1;
    } else
        marker.have_pano=0;

    google.maps.event.addListener(marker,"click",show_info);
  }

  if (gotone==0) {
    map.fitBounds(city_bounds);
    return;
  }

  if (firsttime) {
    var num_options = 1;
    for (var i=1;i<num_wards;i++) {
       if (have_data_for_ward[i]>0) {
          document.filter.wards.options[num_options]=new Option(ward_names[i]);
          document.filter.wards.options[num_options].value=i;
          num_options++;
       }
    }
    firsttime=0;
  }

  map.fitBounds(bounds);
}

function show_info(marker)
{
   if (infowindow) { infowindow.close();}

   var marker=this;
   var num_files=marker.files.length;

   var html = [ 
      '<h2><img src="'+marker.icon_url+'" style=\"padding:1px;\">',
      marker.title+'</h2>',
      '<div style="height:260px" id="tabs">',
      '<ul>',
      '<li><a href="#tab-1"><span>Description</span></a></li>'
   ].join('');

   if (marker.have_pano)
      html+='<li><a href="#tab-2" id="SV"><span>Streetview</span></a></li>';

   if (num_files>0)
      html+='<li><a href="#tab-3"><span>Photos</span></a></li>';

   html+='</ul>'; // End the list

   html+='<div id="tab-1"><p>'+marker.description.replace(/XXX/g,"<br>")+'</p>';

   if (marker.urls.length>0) {
       html+="<p><b>Links</b><table>";
       for (var i=0;i<marker.urls.length;i++) {
           html+="<tr><td>"+marker.url_titles[i]+"</td>"+
               '<td><a href="'+marker.urls[i]+'">'+marker.urls[i]+
               "</a></td></tr>";
       }
       html+="</table>";
   }
   html+='<a href="'+edit_url+'&number='+marker.number+
         '&revision='+marker.revision+'">Click here to edit this entry</a>';
   html+='<p><small>v'+marker.number+'.'+marker.revision+'</small>';

   html+='</div>';

   if (num_files>0) {
      html+='<div id="tab-3">';
      for (var i=0;i<num_files;i++) {
         html+="<img width=300 src=\""+images_base+"/"+marker.files[i]+"\"><br>";
      }
      html+='</div>';
   }

   // For reasons I cannot explain, the SV tab needs to be last
   if (marker.have_pano) {
      html+='<div id="tab-2">';
      html+='<div style="width:500px; height:200px" id="panox">Loading Streetview</div>';
      html+='</div>';
   }

   html+='</div>';

   infowindow = new google.maps.InfoWindow({content: html,maxWidth: 550});
   infowindow.marker=this;
   infowindow.open(map,this);

   google.maps.event.addListenerOnce(infowindow, 'domready', function() { 
       $("#tabs").tabs();
   });

   if (marker.have_pano) {
      google.maps.event.addListenerOnce(infowindow, "domready", setup_pano);
   }
}

function setup_pano()
{
  var marker=this.marker;

  var panoramaOptions = {
    position: marker.pano_latlng,
    pov: {
       heading: Math.round(marker.pano_heading%360),
       pitch: Math.round(marker.pano_pitch),
       zoom: Math.round(marker.pano_zoom)
    }
  };
  $('#SV').click(function() {
     var panorama = new google.maps.StreetViewPanorama(document.getElementById("panox"),panoramaOptions);  
  });

}

function click_report_type(setting)
{
  global_report_type=setting;
  update_query(global_show_wards,global_report_type,global_mask);
}


function update_layers()
{
  try {boundary_layer.setMap(null);} catch (error) {};
  if (tshow_ward_boundaries==0) {
      return;
  }

  if (global_show_wards==0) {
    var url=base_url+'/wards/Wards4.kml';
    boundary_layer= new google.maps.KmlLayer(url);
    try {boundary_layer.setMap(map);} catch (error) {};
  } else {
    var url=base_url+'/wards/g/Ward'+global_show_wards+'.kml';
    boundary_layer= new google.maps.KmlLayer(url);
    try {boundary_layer.setMap(map);} catch (error) {};
  }
}

function status_update(status)
{
   var element=document.getElementById("status_line");
   if (element) {element.innerHTML=status}
}

function wardclick(dropdown)
{       
    global_show_wards=dropdown.value;
    update_query(global_show_wards,global_report_type,global_mask);
    update_layers();
}
  
function toggleWardBoundaries(checkbox)
{
  var orig=tshow_ward_boundaries;
  if (checkbox.checked)
    tshow_ward_boundaries=1;
  else
    tshow_ward_boundaries=0;

  if (tshow_ward_boundaries!=orig) {
    update_layers();
  }
}

function toggleGoogleBicycle(checkbox)
{
  if (checkbox.checked)
    bikeLayer.setMap(map);
  else
    bikeLayer.setMap(null);
}

function maskclick(box,category) 
{ 
  var value=1<<(category-1);
  if (box.checked)
     global_mask+=value;
  else
     global_mask-=value;

  updateMarkers();
}

var old_selected=0;
function report_type_click(select)
{  
   var shortname="";
   var i; 
   value=select[select.selectedIndex].value;
   // Remember the old one
   report_types[old_selected].mask=global_mask;
   if (value!='a') {
      for (i=0;i<report_types.length;i++) {
         if (report_types[i].acronym==value) {
            break;
         }
      }
      // Transfer in the new one
      global_mask=report_types[i].mask;
      old_selected=i;
      shortname=report_types[i].shortname;
       masks_create('subfilter',shortname,global_mask);
   } else
       document.getElementById('subfilter').innerHTML="";
       
   global_report_type=value;

   updateMarkers();
} 


function updateMarkers()
{

  for (var i=0;i<markers.length;i++) {
     marker=markers[i];
     if ((global_report_type=='a') || 
        ((marker.mask & global_mask) && 
         (marker.report_type==global_report_type)))
       marker.setVisible(true);
     else 
       marker.setVisible(false);
  }
}

setTimeout("bikemap_initialize()", 500);


