var key = 'o18179269431215094585.6628314605817990628'
var worksheet = 'od6'

var map = null;
var club_map = null;
var geocoder = null;
var global_point = null;
var debug = 0;
//var clubs = new Array();
var map_loaded = false;
var data_loaded = false;
var current = "home";
//var jazzy = null;
var jazzy = clubs [ gig.Club ];

var gig_map_finished = false;

function load() {
	loadClubsMap();
	loadGigMap();
}

function loadClubsMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		//map.setCenter(new GLatLng(37.4419, -122.1419), 8);

		//add controls
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
		// map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		
		//map.setZoom(5);
		if (!geocoder) {
        	geocoder = new GClientGeocoder();
		}
	} else {
		alert ("Browser doesn't seem to support Google Maps. That makes this site way less cool.");
	}	
}

function loadGigMap() {
	if (GBrowserIsCompatible()) {
		club_map = new GMap2(document.getElementById("club_map"));
		club_map.addControl(new GLargeMapControl());
        club_map.addControl(new GMapTypeControl());
		//club_map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		if (!geocoder) {
        	geocoder = new GClientGeocoder();
		}
	} else {
		alert ("Browser doesn't seem to support Google Maps. That makes this site way less cool.");
	}	
}

function plotPoint (club, point, source, map) {
	map.setCenter(point, 10);
	var marker = new GMarker(point);
	map.addOverlay(marker);
	var clubName = club.name;
	
	if (club.url != '') {
		var cluburl = "<a href = \"" + club.url + "\">" + clubName + "</a>";
	} else {
		var cluburl = clubName;
	}
	
	//var back_str = "<a href=\"http://www.isaacezer.com\">Isaac's Website</a>";
	var back_str = "";	
	back_str += "<p>X: " + point.x + "</p>";
	back_str += "<p>Y: " + point.y + "</p>";
	
	if (debug) {
		var el;
		el = document.getElementById("xy-table");
		if (!el) {
			var el_xy = document.getElementById('xy');
			el = document.createElement("table");
			el.id = "xy-table";
			el_xy.appendChild (el);
		}

		//var xy_str = "" + point.lat() +"\t" + point.y;
		//el.appendChild (document.createTextNode( xy_str ) );
		//el.appendChild (document.createElement ("br"));
		var row = document.createElement ("tr");
		var row_name = document.createElement ("td");		
		var row_x = document.createElement ("td");
		var row_y = document.createElement ("td");
		var row_source = document.createElement ("td");
		row_name.appendChild (document.createTextNode (clubName));
		row_x.appendChild (document.createTextNode (point.lat()));
		row_y.appendChild (document.createTextNode (point.lng()));
		row_source.appendChild (document.createTextNode (source));
		row.appendChild(row_name);		
		row.appendChild(row_x);
		row.appendChild(row_y);
		row.appendChild(row_source);
		el.appendChild (row);
	}

/* Forget tabs
	var infoTabs = [
	      new GInfoWindowTab(club.Name, cluburl),

		  new GInfoWindowTab("Isaac", back_str)
	];
	
	if (map == club_map) {
		marker.openInfoWindowTabsHtml(infoTabs);
	}
	
	GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml(infoTabs);
	});
*/
	if (debug) {
		cluburl += back_str;
	}

	if (map == club_map) {
		marker.openInfoWindowHtml(cluburl)
	}
	GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(cluburl);
	});
}

/* try to use geopoint, ow use geocoder */
function showAddress(club) {
	
	if (debug) {
		//alert ("About to plot " + club.Name);
	}

	if ( (club.geox && club.geoy) ) {
		point = new GLatLng (club.geox, club.geoy); 
		plotPoint (club, point, "Coords", map);
	
	} else if (club.mapsquery && geocoder) {
		geocoder.getLatLng(
		club.mapsquery,
		function(point) {
			if (!point) {
				if (debug)
					alert("Can't find " + club.name + " " + club.mapsquery);
			} else {
				plotPoint(club, point, "Address", map);
			}
		}
		);
	}
}  

function strcmp(a, b) {
	if (a.length != b.length) {
		document.writeln("different lengths" + a.length + " "+ b.length);
	}
	
	var len = a.length;
	for (var i = 0; i < len; i++) {
		if (a.charAt(i) != b.charAt(i)) {
			document.writeln ("difference: " + i + " " + a.charAt(i) + " " + b.charAt(i));
		}
	}
}

function plotClubs() {
	if (map_loaded) {
		return;
	}
	map_loaded = true;

	for (var i = 0; i < clubs.length; i++) {
		var club = clubs[i];
		if (club.MapsQuery != '') {
			showAddress(club);
		}
	}
}

function plotGigMap() {
	var point = new GLatLng (jazzy.GeoX, jazzy.GeoY); 
	plotPoint (jazzy, point, "Coords", club_map);
	gig_map_finished = true;
}

function setVisible (window) {
	if (window == "map_area") {
		plotClubs();
	}

	if (window == "gigs" && jazzy && !gig_map_finished) {
		plotGigMap();
	}
	
	document.getElementById (current).className = "hidden";
	document.getElementById (window).className = "map_area";

	current = window;
}

function listEntries(json) {

	removeOldResults();
	
	// Delete stored club values
	clubs = new Array();
	
	var dl = document.createElement('dl');
	dl.setAttribute('id', 'output');
	var i = 0;
	for (var i = 0; i < json.feed.entry.length; i++) {
	
		var entry = json.feed.entry[i];
	
		var s = "{" + entry.content.$t + "}";
	
		var club = eval ( "(" + s + ")");

		clubs.push(club);

		if (debug) {
			var dt = document.createElement('dt');
			
                        //show the index of each entry. comment this out to make copy and paste in JSON easier
                        var title = document.createTextNode(entry.title.$t);
			dt.appendChild(title);
	
			var dd = document.createElement('dd');

			//var content = document.createTextNode(entry.content.$t);
			var content = document.createTextNode(s + ",");	
	
			dd.appendChild(content);
	
			dl.appendChild(dt);
			dl.appendChild(dd);
		}
		
		if (club.Name == "Bar Jazzy") {
			jazzy = club;
		}
	}

	if (debug) {	
		document.getElementById('data').appendChild(dl);
	}
	// plot the points on the map;
	plotClubs();
	data_loaded = true;
}


/**
 * Called when the user clicks the 'OK' button to
 * retrieve a spreadsheet's JSON feed.  Creates a new
 * script element in the DOM whose source is the JSON feed,
 * and specifies that the callback function is
 * 'listEntries' for a list feed and 'cellEntries' for a
 * cells feed (above).
 */
function displayResults() {
	removeOldJSONScriptNodes();
	removeOldResults();
	
	// Show a "Loading..." indicator.
	var div = document.getElementById('data');
	var p = document.createElement('p');
	p.appendChild(document.createTextNode('Loading...'));
	div.appendChild(p);
	
	// Retrieve the JSON feed.
	var script = document.createElement('script');
	
	script.setAttribute('src', 'http://spreadsheets.google.com/feeds/'
			 + 'list'
			 + '/' + key
			 + '/' + worksheet + '/public/values' +
			'?alt=json-in-script&callback=listEntries');
	
	script.setAttribute('id', 'jsonScript');
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);;
}

/**
 * Removes the script element from the previous result.
 */
function removeOldJSONScriptNodes() {
	var jsonScript = document.getElementById('jsonScript');
	if (jsonScript) {
		jsonScript.parentNode.removeChild(jsonScript);
	}
}

/**
 * Removes the output generated from the previous result.
 */
function removeOldResults() {
	var div = document.getElementById('data');
	if (div.firstChild) {
		div.removeChild(div.firstChild);
	}
}



var SUBSCRIBED = 1;
var UNSUBSCRIBED = 2;
var CONFIRMATION = 3;
var ALREADY = -1;
var NOT_IN = -2;
var INVALID_ADDRESS = -3;
var MISSING_REQ_FIELDS = -4;
var MISMATCH_EMAILS = -5;

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return "";
} 

function getStatus (code) {

	switch (code) {
		case SUBSCRIBED:
			return "Thank you for subscribing.";
		case UNSUBSCRIBED:
			return "Your e-mail has been taken off the list. I'm so sorry it's come this :-(";
		case CONFIRMATION:
			return "Just to make sure you don't get spam, a confirmation e-mail has been sent you. Please click on the link in the e-mail to subscribe."
		case ALREADY:
			return "You're already on the list. No need to subscribe.";
		case NOT_IN:
			return "Actually you aren't on the list. No need to unsubscribe.";
		case INVALID_ADDRESS:
			return "That's not a valid e-mail address. Please check it below.";
		case MISSING_REQ_FIELDS:
			return "Please fill in both fields below.";
		case MISMATCH_EMAILS:
			return "mismatched emails";
		default:
			"Confused"
	}
}

function mail_list_output() {
	var code = getQueryVariable("code");
	var name = getQueryVariable("name");
	var address = getQueryVariable("address");
	var missing = getQueryVariable("missing");
	//alert (code + name + address + missing);
	
	if ( ! ( (code) && ( address || missing ) ) ) {
		return;
	}
	
	var el;
	
	el = document.getElementById("mail-list-info");
	el.className = "mail-list-info";	

	var h2 = document.createElement("h2");
	h2.appendChild (document.createTextNode("Mailing List"));
	el.appendChild (h2);

	var status = getStatus( parseInt(code) );
	//document.getElementById("mail-list").className = "mail-list-big";
	el.appendChild (document.createTextNode ( status ) );
	document.MailListForm.name.value = unescape(name);
	document.MailListForm.email.value = unescape(address);
}

//if debug = 1, print debug output
// if debug = 2, print debug output AND actually get data from google spreadsheet
function checkDebug() {
	if (getQueryVariable("debug") == "1") {
		debug = 1;
	}
	if (getQueryVariable("debug") == "2") {
		debug = 2;
	}
}

function linkHover (element) {
	element.className = "link-hover";
}

function linkOut (element) {
	element.className = "link";
}


