var map;
var data = [];
var centerLatitude = 51.89435;
centerLongitude = -126.0318;
startZoom = 6;

function initializePoint(pointData, iconURL, iconSizeX, iconSizeY) {
	var icon = new GIcon();
 	 icon.image = iconURL;
 	 icon.iconSize = new GSize(iconSizeX, iconSizeY);
	 icon.iconAnchor = new GPoint(6, 6);
	 icon.infoWindowAnchor = new GPoint(5, 1);
	var marker = new GMarker(new GLatLng(pointData.latitude, pointData.longitude), icon);
	  marker.feature = pointData.feature;
	  marker.alias = pointData.alias;
	  marker.name = pointData.name;
	  marker.bco_number = pointData.bco_number;
	  marker.source = pointData.source;
	  marker.band = pointData.band;
	var infoTable = '';
	infoTable = '<div id=\'IWTable\'><table><tr><th colspan="2">' + pointData.feature.toUpperCase() + '</th></tr>';
	 if(pointData.name){
		infoTable = infoTable + '<tr><td>NAME: </td><td>' + pointData.name + '</td></tr>';
	 };
	 if(pointData.location){
		infoTable = infoTable + '<tr><td>LOCATION: </td><td>' + pointData.location + '</td></tr>';
	 };
	 if(pointData.city){
		infoTable = infoTable + '<tr><td>CITY: </td><td>' + pointData.city + '</td></tr>';
	 };
	 if(pointData.address){
		infoTable = infoTable + '<tr><td>ADDRESS: </td><td>' + pointData.address + '</td></tr>';
	 };
	 if(pointData.source){
		infoTable = infoTable+ '<tr><td>SOURCE: </td><td>' + pointData.source + '</td></tr>';
	 };
	 if(pointData.band){
		infoTable = infoTable+ '<tr><td>BAND: </td><td>' + pointData.band + '</td></tr>';
	 };
	 infoTable = infoTable + '</table></div>';
	GEvent.addListener(marker, 'click',
		function() {
		    marker.openInfoWindowHtml(infoTable);
		});
	data.push(marker);	
	return marker;
}
	
	
// == shows all markers of a particular feature type, and ensures the checkbox is checked ==
function show(alias) {
	for(id in data){
  	  if (data[id].alias == alias) {
  	    data[id].show();
 	  }
	}
	// == check the checkbox ==
	document.getElementById(alias+"box").checked = true;
}



// == hides all markers of a particular feature, and ensures the checkbox is cleared ==
function hide(alias) {
	for (id in data){
	  if (data[id].alias == alias) {
	    data[id].hide();
	  }
	}
	// == clear the checkbox ==
	document.getElementById(alias+"box").checked = false;
	// == close the info window, in case it is open on a marker that we just hid
	map.closeInfoWindow();
}	

	
function legend(keyValues) {
	var listItem = document.createElement('li');
	// IE dynamic form input type assignment doesn't work nicely.
	// so, this method taken from http://cf-bill.blogspot.com/ :
	// try/catch: try works in IE 6 (maybe 7) catch works in ff/ns browsers 
	// not tested in Opera - may not work.
	try{
		var listItemCheckBox = listItem.appendChild(document.createElement('<input type="checkbox"/>'));
	}
	catch(err){
		var listItemCheckBox = listItem.appendChild(document.createElement('input'));
	}
	listItemCheckBox.type = 'checkbox';
	listItemCheckBox.id = keyValues.alias+'box';
	listItemCheckBox.onclick = function(){
	        if (this.checked) {
	          show(keyValues.alias);
	        } 
	        else {
	          hide(keyValues.alias);
	        }
	}
	var legKey = listItem.appendChild(document.createElement('img'));
	 legKey.src =  keyValues.image
	 legKey.width = keyValues.sizex
	 legKey.height = keyValues.sizey
	var listItemLink = listItem.appendChild(document.createElement('a'));
	 listItemLink.href = "metadata.html";
	 listItemLink.innerHTML = keyValues.feature; 
	document.getElementById('legend').appendChild(listItem);
}


function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	var height = windowHeight() - document.getElementById('title').offsetHeight - 30;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height + 'px';
}


function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}


/**
 * Stuff the JSON feed data into local objects
 */
function loadJSON(json) {
  alert(json.feed.entry.length + ' records');
  for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = json.feed.entry[i];
    //if(entry["gsx$latitude"]) {
      alert(entry["content"].$t);
      var lat = parseFloat(entry["gsx$LATITUDE"].$t);
      var lng = parseFloat(entry["gsx$LONGITUDE"].$t);
      alert(lat);
   //   }
      /*var point = new GLatLng(lat,lng);
      var html = "<div style='font-size:12px'>";
      html += "<strong>" + entry["gsx$"+param_titleColumn].$t 
              + "</strong>";
      var label = entry["gsx$"+param_titleColumn].$t;
      var rank = 0;
      if(usingRank && entry["gsx$" + param_rankColumn]) {
        rank = parseInt(entry["gsx$"+param_rankColumn].$t);
      }
      if(entry["gsx$" + param_descriptionColumn]) {
        html += "<br/>" + entry["gsx$"+param_descriptionColumn].$t;
      }
      html += "</div>"; */
   }
}

/**
 * Creates a script tag in the page that loads in the 
 * JSON feed for the specified key/ID. 
 * Once loaded, it calls loadJSON.
 */
function getJSON() {
  // Retrieve the JSON feed.
  var script = document.createElement('script');
  script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list/o00147266091684130284.5725758285326351958/od6/public/basic?alt=json-in-script&callback=loadJSON');
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}



function init() {
	document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	handleResize();
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	//map.addControl(new GScaleControl());
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	map.addControl(new GOverviewMapControl(new GSize(150,150)));
	map.addControl(gv_maptypecontrol = new GV_MapTypeControl()); // add custom map type switcher
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();
	map.enableGoogleBar()
	// get the data - problems referencing it for now....
	// getJSON();
	/*for(id in bco_data) {
		marker = initializePoint(bco_data[id]);
		map.addOverlay(marker);
	}	
	for(id in bco_key) {
		legend(bco_key[id]);
		show(bco_key[id].alias)
	}*/
	for(key_id in bco_key) {
		for(record_id in bco_data) {
			if(bco_data[record_id].alias == bco_key[key_id].alias){
				marker = initializePoint(bco_data[record_id], bco_key[key_id].image, bco_key[key_id].sizex, bco_key[key_id].sizey);
				map.addOverlay(marker)
			}
		}
		legend(bco_key[key_id]);
		hide(bco_key[key_id].alias)
	}
}
window.onresize = handleResize;
window.onload = init;
