//<![CDATA[

var sxsw_map_points = {};
var sxsw_map_settings = {
	"Map Name" : "sxsw_map",
	"Map Width" : "100%",
	"Map Height" : "100%",
	"Popup Width" : 225,
	"Zoom Level" : 12,
	"Zoom Controls" : "small",
	"Show Zoom" : true,
	"Show Scale" : false,
	"Show Reset" : true,
	"Show Map Types" : false,
	"Key" : "ABQIAAAAKkU33N_8p_XIkUjS83zp7xSJemsAnBA3E2_CNHQePzO1c9bDJhQ1dpOAWMl5t2tEVhn8zlVsXaEJvw"
};

var sxsw_map_obj = null;

includeScript("http://maps.google.com/maps?file=api&v=2&key=" + sxsw_map_settings["Key"]);

function loadSXSWMap() {
	if (GBrowserIsCompatible()) {
	    window.onunload = GUnload;
		sxsw_map_obj = new SXSWMap(sxsw_map_points, sxsw_map_settings);
		//sxsw_map_obj.display();
	} else {
		var error_msg = "Your browser is incompatible with Google Maps."
		alert(error_msg);
	}
}

function SXSWMap(points, settings) {
	var n = 0;
	for (var i in points) {
	    n++;
	}
	this.total_points = n;
	this.address_points = new Array();
	this.map_div = document.getElementById(settings["Map Name"]);
	this.width = settings["Map Width"];
	this.height = settings["Map Height"];
	this.zoom_action = true;
	this.zoom_init = settings["Zoom Level"];
	this.current_zoom = this.zoom_init;
	this.zoom_type = settings["Zoom Controls"];
	this.show_zoom = settings["Show Zoom"];
	this.show_scale = settings["Show Scale"];
	this.show_reset = settings["Show Reset"];
	this.show_map_types = settings["Show Map Types"];
	this.information = points;
	//this.setSize(this.width, this.height);
	this.map = new GMap2(this.map_div);
	this.geocoder = new GClientGeocoder();
}

SXSWMap.prototype.reset = function () {
	var points = sxsw_map_points;
	var n = 0;
	for (var i in points) {
	    n++;
	}
	this.total_points = n;
	this.information = points;
	this.address_points = new Array();
	this.map.clearOverlays();
}

SXSWMap.prototype.update = function(points) {
	var new_points = points;
	for (var i in sxsw_map_points) {
		if (!new_points[i]) {
			this.map.removeOverlay(sxsw_map_points[i].marker);
			//delete sxsw_map_points[i].marker;
		}
		else {
			alert(new_points[i].icon +" "+ sxsw_map_points[i].icon);
			if (new_points[i].icon != sxsw_map_points[i].icon) {
            	this.map.removeOverlay(sxsw_map_points[i].marker);
            }
		}
	}
	var points_to_add = {};
	for (var i in new_points) {
		if (!sxsw_map_points[i]) {
		    sxsw_map_points[i] = new_points[i];
			points_to_add[i] = new_points[i];
		}
	}
	this.information = sxsw_map_points;
	this.zoom_action = false;
	this.showAddresses(points_to_add);
}

SXSWMap.prototype.display = function () {
	this.reset();
	var map = this.map;
	var geocoder = this.geocoder;
	if (this.show_zoom) {
		if (this.zoom_type == "small") {
			map.addControl(new GSmallMapControl(false), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(6, 65)));
		}
		else {
		    map.addControl(new GLargeMapControl(false), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5, 65)));
		}
	}
	if (this.show_map_types) {
		map.addControl(new GMapTypeControl(false));
	}
	if (this.show_scale) {
		map.addControl(new GScaleControl(false), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5, 20)));
	}
	map.setCenter(new GLatLng(30.266944, -97.742778), 13);
	this.showAddresses(this.information);
}

SXSWMap.prototype.showAddresses = function(information) {
	var geocoder = this.geocoder;
	for (var i in information) {
		geocoder.getLocations(i, this.addAddressPoint);
	}
}

SXSWMap.prototype.addAddressPoint = function(response) {
	var map_obj = sxsw_map_obj;
	if (!response || response.Status.code != 200) {
		//alert("Address not found: " + response.name);
	} else {
		var place = response.Placemark[0];
		var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map_obj.address_points.push(point);
		if (map_obj.total_points == map_obj.address_points.length && map_obj.zoom_action) {
            map_obj.averagePoints(map_obj.address_points);
		}
		var sxsw_point = new SXSWMapPoint(point, place, map_obj.information[response.name], response.name, map_obj);
	}
}

SXSWMap.prototype.averagePoints = function(points) {
	var bounds = new GLatLngBounds();
	// extend the bounds to include all the points.
	for (var i=0; i < points.length; i++) {
		bounds.extend(points[i]);
	}
	this.centerAndZoomOnBounds(bounds);
}

SXSWMap.prototype.centerAndZoomOnBounds = function(bounds) {
	var center = bounds.getCenter();
	var newZoom = this.map.getBoundsZoomLevel(bounds);// - 1;
    this.map.setCenter(center, newZoom); //this.map.setCenter(center, this.zoom_init);
    this.current_zoom = newZoom;
	if (this.show_reset) {
    	this.createResetButton(center, this.current_zoom);
    }
}

SXSWMap.prototype.setSize = function(w, h) {
	var div = this.map_div;
	div.style.width = w+"px";
	div.style.height = h+"px";
}

SXSWMap.prototype.createResetButton = function(center, zoom) {
	var map = this.map;
	var reset_button = document.createElement("div");
	reset_button.style.textDecoration = "underline";
	reset_button.style.color = "#0000cc";
	reset_button.style.backgroundColor = "white";
	reset_button.style.fontSize = "12px";
	reset_button.style.fontFamily = "Arial, Tahoma, sans-serif";
	reset_button.style.border = "1px solid black";
	reset_button.style.padding = "2px";
	reset_button.style.marginBottom = "3px";
	reset_button.style.textAlign = "center";
	reset_button.style.cursor = "pointer";
	reset_button.appendChild(document.createTextNode("Reset"));
	reset_button.style.position = "absolute";
	reset_button.style.bottom = "35px";
	if (this.zoom_type == "small") {
	    reset_button.style.left = "5px";
	}
	else {
        reset_button.style.left = "13px";
	}
	map.getContainer().appendChild(reset_button);
	GEvent.addDomListener(reset_button, "click", function() {
    	map.setCenter(center, zoom);
	});
}

SXSWMap.prototype.showDirectionsOption = function(dir) {
	var map = this.map;
	var infoindex = map.getInfoWindow().current_address; //var information = this.information;
	var marker = map.getInfoWindow().current_marker;
	var info_div = map.getInfoWindow().getContentContainers()[0].childNodes[0].childNodes[0];
	if (info_div.lastChild.className == "directions") {
		var dir_div = info_div.lastChild;
		dir_div.innerHTML = '<strong>Get directions:</strong> ';
		if (dir == "to") {
			dir_div.innerHTML += 'To here - <a href="javascript:void(0)" onclick="javascript:sxsw_map_obj.showDirectionsOption(\'from\')">From here</a><br />';
            dir_div.innerHTML += '<span class="gray small">Start address:</span>';
		}
		else if (dir == "from") {
			dir_div.innerHTML += '<a href="javascript:void(0)" onclick="javascript:sxsw_map_obj.showDirectionsOption(\'to\')">To here</a> - From here<br />';
			dir_div.innerHTML += '<span class="gray small">End address:</span>';
		}
		dir_div.innerHTML += '<br />';
		dir_div.innerHTML += '<input type="text" id="input_address" size="25" /> ';
		dir_div.innerHTML += '<input type="submit" value="Go" onclick="javascript:sxsw_map_obj.getDirections(\''+infoindex+'\', \''+dir+'\', getElementById(\'input_address\').value)" />';
	}
	this.map.closeInfoWindow();
	marker.openInfoWindowHtml('<div class="infowindow">'+info_div.innerHTML+'</div>', {maxWidth: sxsw_map_settings["Popup Width"]});
}

SXSWMap.prototype.getDirections = function(infoindex, dir, input) {
	var start_addr;
	var end_addr;
	if (dir == "to") {
		start_addr = input;
		end_addr = infoindex;
	}
	else if (dir == "from") {
		start_addr = infoindex;
		end_addr = input;
	}
	window.open("http://maps.google.com/maps?saddr="+start_addr+"&daddr="+end_addr);
}

function SXSWMapPoint(point, place_obj, info_obj, address_str, map) {
	this.map_obj = map;
	this.map = this.map_obj.map;
	this.point = point;
	this.id = info_obj.id;
	this.title = info_obj.name;
	//this.description = info_obj.description;
	this.events = info_obj.events;
	//this.phone = info_obj.phone;
	this.show_address = info_obj.showAddress;
	this.show_directions = info_obj.showDirections;
	this.icon = info_obj.icon;
	// address properties
	this.address = address_str;
	this.street = place_obj.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
	this.city = place_obj.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
	this.state = place_obj.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
	this.zip = place_obj.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
	this.addMarker();
}

SXSWMapPoint.prototype.addMarker = function() {
	this.marker = new GMarker(this.point, {icon: this.setupIcon(this.icon), title: this.title});
	GEvent.bind(this.marker, "click", this, this.setupClick);
	//GEvent.bind(this.marker, "click", this, this.setupInfoWindowOpen);
	//GEvent.bind(this.marker, "infowindowclose", this, this.setupInfoWindowClose);
	this.map_obj.information[this.address].marker = this.marker;
	this.map.addOverlay(this.marker); //return marker;
}

SXSWMapPoint.prototype.setupClick = function() {
	var address_obj = {};
	address_obj.address = this.address;
	address_obj.street = this.street;
	address_obj.city = this.city;
	address_obj.state = this.state;
	address_obj.zip = this.zip;
	showSXSWEventInfo(this.title, address_obj);
	//showSXSWEventInfo(this.id, address_obj);
}

SXSWMapPoint.prototype.setupInfoWindowOpen = function() {
	//alert(this.events[0].type);
	showMapPointInfo(this.title);
    if (this.map.getInfoWindow().current_marker != this.marker) {
        this.map.closeInfoWindow();
		var display = '<div class="infowindow">';
		for (var i=0; i < this.events.length; i++) {
		    display += '<div class="event">';
			display += this.events[i].name;
			display += '</div>';
		}
		display += '<div class="venue">';
		if (this.title != "" && this.title != null && this.title != undefined) {
			display += '<strong>' + this.title + '</strong><br />';
		}
		/*if (this.description != "" && this.description != null && this.description != "undefined") {
			display += this.description + '<br />';
		}*/
		if (this.show_address) {
        	display += '<br />';
			display += this.street + '<br />';
			display += this.city + ', ';
			display += this.state + ' ';
			display += this.zip;
			display += '<br />';
			if (this.phone != "" && this.phone != null && this.phone != "undefined") {
				display += this.phone + '<br />';
			}
		}
		display += '</div>';
		if (this.show_directions) {
		    //display += '<br />';
		    display += '<div class="directions">';
		    display += 'Get directions: <a href="javascript:void(0)" onclick="javascript:sxsw_map_obj.showDirectionsOption(\'to\')">To here</a> - <a href="javascript:void(0)" onclick="javascript:sxsw_map_obj.showDirectionsOption(\'from\')">From here</a>';
            display += '</div>';
		}
		display += '</div>';
		this.marker.openInfoWindowHtml(display, {maxWidth: sxsw_map_settings["Popup Width"]});
		this.map.getInfoWindow().current_marker = this.marker;
		this.map.getInfoWindow().current_address = this.address;
	}
	else {
	    this.map.closeInfoWindow();
		//delete map.getInfoWindow().current_marker;
		//delete map.getInfoWindow().current_address;
	}
}

SXSWMapPoint.prototype.setupInfoWindowClose = function() {
	delete this.map.getInfoWindow().current_marker;
	delete this.map.getInfoWindow().current_address;
}

SXSWMapPoint.prototype.setupIcon = function(png) {
	if (png == "default") {
		return new GIcon(G_DEFAULT_ICON);
	} else {
		return new GIcon(G_DEFAULT_ICON, png);
	}
}

// write script

function includeScript(script_filename) {
    document.write('<' + 'script');
    document.write(' id="google_map_script"');
    document.write(' language="javascript"');
    document.write(' type="text/javascript"');
    document.write(' src="' + script_filename + '">');
    document.write('</' + 'script' + '>');
    //window.onload = loadSXSWMap;
}

// UNUSED

function panTo(address) {
	geocoder.getLocations(address, panToAddress);
}

function panToAddress(response) {
	if (!response || response.Status.code != 200) {
		alert(address + " not found");
	} else {
		var place = response.Placemark[0];
		var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map.panTo(point);
		GEvent.trigger(sxsw_map_points[response.name].marker, "click");
	}
}

SXSWMap.prototype.createAd = function() {
	var mapdiv = this.map_div;
	var ad_div = document.createElement("div");//document.getElementById("ad");
	ad_div.style.width = "75px";
	ad_div.style.height = "50px";
	ad_div.style.border = "1px solid black";
	ad_div.style.backgroundColor = "red";
	ad_div.style.position = "absolute";
	ad_div.style.top = parseInt(mapdiv.style.height) - parseInt(ad_div.style.height) + "px";
	ad_div.style.left = parseInt(mapdiv.style.width) - parseInt(ad_div.style.width) + "px";
	this.map.getContainer().appendChild(ad_div);
}

//]]>

