var debug = true;
//myMap.map.getBounds().contains(events[4].marker.getPoint())
//myMap.map.setCenter(events[4].marker.getPoint())
//myMap.map.setZoom(6)

dojo.require("dojo.widget.GoogleMap");
dojo.require("dojo.io.*");
dojo.require("dojo.event.*");
dojo.require("dojo.widget.*");
dojo.hostenv.writeIncludes();

var centerOnZIP = function() {
};

var addCounselorDialog;
var editEventDialog;
var editLocationDialog;
var eventsByType = {};
var events = [];
var myMap;
var currentType = "";
var geocoder;

function showEvents(type) {
	if (type) {
		var target = type + "Events";
		dojo.debug("showing events " + type);
		dojo.byId(target).innerHTML = "";
		if (currentType != type) {
			dojo.debug("got new type");
			for (var i = 0; i < events.length; i++) {
				events[i].marker.hide();
				events[i].marker.closeInfoWindow();
			}
		}
		if (eventsByType[type]) {
			for (i = 0; i < eventsByType[type].length; i++) {
				eventsByType[type][i].marker.show();
				if (myMap.map.getBounds().contains(eventsByType[type][i].marker.getPoint())) {
					//dojo.byId(target).appendChild(eventsByType[type][i].link());

					var link = eventsByType[type][i].link();
					dojo.event.connect(link, "onclick", eventsByType[type][i].openInfo);
					dojo.byId(target).appendChild(link);
				}
			}
		}
	} else {
		dojo.debug("showing all events");
		dojo.byId("allEvents").innerHTML = "";
		for (var i = 0; i < events.length; i++) {
			events[i].marker.show();
			if (myMap.map.getBounds().contains(events[i].marker.getPoint())) {
				var link = events[i].link();
				dojo.event.connect(link, "onclick", events[i].openInfo);
				dojo.byId("allEvents").appendChild(link);
			}
		}
	}
}

function mapInit(e) {
	myMap = dojo.widget.createWidget("GoogleMap", { controls: ["smallmap"]}, dojo.byId("eventGoogleMapContainer"));
	GEvent.addListener(myMap.map, "moveend", function() { showEvents(currentType) });
	geocoder = new GClientGeocoder();

	var myIcon = new GIcon();
	myIcon.image = "markers/HSvisitmarker.png";
	myIcon.shadow = "markers/mm_20_shadow.png";
	myIcon.iconSize = new GSize(12, 20);
	myIcon.shadowSize = new GSize(22, 20);
	myIcon.iconAnchor = new GPoint(6, 20);
	myIcon.infoWindowAnchor = new GPoint(5, 1);

	var fairIcon = new GIcon(myIcon);
	fairIcon.image = "markers/collegefair.png";

	var receptionIcon = new GIcon(myIcon);
	receptionIcon.image = "markers/preview.png";

	function addCounselorEvent(e) {
		var k = {};
		k.id = e.getAttribute("id");
		k.type = e.getAttribute("type");
		k.name = e.getAttribute("name");
		k.start = new Date(parseInt(e.getAttribute("start"), 0));
		k.end = new Date(parseInt(e.getAttribute("end"), 0));
		k.notes = e.getAttribute("notes");
		k.counselor = e.getAttribute("who");
		k.counselorEmail = e.getAttribute("email");
		k.link = function() { 
			var p = document.createElement("p");
			p.className = "eventLink";
			var a = document.createElement("a");
			a.appendChild(document.createTextNode(k.start.toLocaleDateString()));
			a.appendChild(document.createElement("br"));
			a.appendChild(document.createTextNode(k.name));
			p.appendChild(a);
			return p;
		}
		k.infoTab = function() {
			var i = document.createElement("div");
			i.appendChild(document.createTextNode("Date: " + k.start.toLocaleDateString()));
			i.appendChild(document.createElement("br"));
			i.appendChild(document.createTextNode("Location: " + k.name));
			i.appendChild(document.createElement("br"));
			i.appendChild(document.createTextNode("Event Type: " + k.type));
			i.appendChild(document.createElement("br"));
			i.appendChild(document.createTextNode("Counselor: "));
			if (k.counselorEmail) {
				var e = document.createElement("a");
				e.href = "mailto:" + k.counselorEmail + "?subject=" + k.name + " " + k.type + " " + k.start.toLocaleDateString();
				e.appendChild(document.createTextNode(k.counselor));
				i.appendChild(e);
			} else {
				i.appendChild(document.createTextNode(k.counselor));
			}
			i.appendChild(document.createElement("br"));

			return (new GInfoWindowTab(k.type, i));
		}
		k.notesTab = function() {
			var i = document.createElement("div");
			var n = document.createElement("textarea");
			n.style.width = "256px";
			n.style.height = "64px";
			n.value = k.notes;
			i.appendChild(n);
			i.appendChild(document.createElement("br"));

			return (new GInfoWindowTab("Notes", i));
		}
		k.directionsTab = function() {
			var i = document.createElement("div");
			return (new GInfoWindowTab("Directions", i));
		}
		
		var address = e.getAttribute("city") + ", " + e.getAttribute("state") + " " + e.getAttribute("zip");
		var point = new GLatLng(e.getAttribute("lat"), e.getAttribute("lng"));
				if (point) {
					events.push(k);
					if (eventsByType[k.type]) {
						eventsByType[k.type].push(k);
					} else {
						eventsByType[k.type] = [];
						eventsByType[k.type].push(k);
					}
					if (k.type == "Fair") {
						k.marker = new GMarker(point, {icon: fairIcon});
					} else if (k.type == "Reception") {
						k.marker = new GMarker(point, {icon: receptionIcon});
					} else {
						k.marker = new GMarker(point, {icon: myIcon});
					}
					myMap.map.addOverlay(k.marker);
					GEvent.addListener(k.marker, "click", function() {
						dojo.debug("got marker click " + k.name);
						myMap.map.panTo(point);
						k.marker.openInfoWindowTabsHtml([k.infoTab(), k.notesTab()]);
						//k.marker.openInfoWindowTabsHtml([k.infoTab(), k.notesTab(), k.directionsTab()]);
						});
					k.openInfo = function() {
						dojo.debug("got link click " + k.name);
						myMap.map.panTo(point);
						k.marker.openInfoWindowTabsHtml([k.infoTab(), k.notesTab()]);
						//k.marker.openInfoWindowTabsHtml([k.infoTab(), k.notesTab(), k.directionsTab()]);
					}
				}
	}

	centerOnZIP = function() {
		if (dojo.widget.byId("zipCode").getValue()) {
			address = dojo.widget.byId("zipCode").getValue();
			geocoder.getLatLng(address, function(point) {
				if (point) {
					myMap.map.setCenter(point, 8);
					showEvents(currentType);
				} else {
					alert("I can't find ZIP code " + address);
				}
			});
		} else {
			dojo.debug("no zip");
		}
	}

	var loadEvents = function() { 
		GDownloadUrl("eventmap.pl", function(data, responseCode) {
			var xml = GXml.parse(data);
			var e = xml.documentElement.getElementsByTagName("event");
			for (var i = 0; i < e.length; i++) {
				addCounselorEvent(e[i]);
			}

			myMap.map.panTo( new GLatLng( 39.30029918615029, -99.84375 ));
			dojo.addOnLoad(centerOnZIP);
		});
	}

	dojo.addOnLoad(loadEvents);

}

function newEvent(f) {
	if(document.editLocationForm.locationName.value) {
	} else {
		alert("Please select a school or location");
		return false;
	}

	if(! document.newEventForm.counselorId.value) {
		alert("Please select a counselor");
		return false;
	}
	
	if(! document.newEventForm.eventType.value) {
		alert("Please select an event type");
		return false;
	}

	if(! dojo.widget.byId("eventStart").getValue()) {
		alert("Please select a start date");
		return false;
	}

	if(! dojo.widget.byId("eventEnd").getValue()) {
		alert("Please select an end date");
		return false;
	}

	//if (document.newEventForm.eventEnd.value < document.newEventForm.eventStart.value) {
	//	alert("The event end date is before the start date");
	//	return false;
	//}

	return true;
}

function adminInit(e) {
	myMap = dojo.widget.createWidget("GoogleMap", null, document.createElement("div"));
	geocoder = new GClientGeocoder();

	editLocationDialog = dojo.widget.byId("editLocationFormContainer");
	editLocationDialog.setCloseControl(document.getElementById("editLocationFormOk"));
	editLocationDialog.setCloseControl(document.getElementById("editLocationFormCancel"));

	editEventDialog = dojo.widget.byId("editEventFormContainer");
	editEventDialog.setCloseControl(document.getElementById("editEventFormOk"));
	editEventDialog.setCloseControl(document.getElementById("editEventFormCancel"));
	editEventDialog.setCloseControl(document.getElementById("editEventFormDelete"));
	editEventDialog.setCloseControl(document.getElementById("editEventFormClone"));

	addCounselorDialog = dojo.widget.byId("addCounselorFormContainer");
	addCounselorDialog.setCloseControl(document.getElementById("addCounselorFormOk"));
	addCounselorDialog.setCloseControl(document.getElementById("addCounselorFormCancel"));

	var w = dojo.widget.byId("eventsTable");
	dojo.event.connect(w, "onSelect", function() { 
			editEventDialog.show();
			var curEvent = w.getSelectedData();
			document.editEventForm.editEventId.value = curEvent.id;
			document.editEventForm.editEventLocation.value = curEvent.school;
			document.editEventForm.editEventAddress.value = curEvent.address;
			document.editEventForm.editEventAddress1.value = curEvent.address1;
			document.editEventForm.editEventCity.value = curEvent.city;
			document.editEventForm.editEventState.value = curEvent.state;
			document.editEventForm.editEventZip.value = curEvent.zip;
			document.editEventForm.editEventNotes.value = curEvent.notes;
			document.editEventForm.editEventLat.value = curEvent.lat;
			document.editEventForm.editEventLng.value = curEvent.lng;
			for (var i = 0; i < document.editEventForm.counselorId.options.length; i++) {
				if (document.editEventForm.counselorId.options[i].text == curEvent.counselor) {
					document.editEventForm.counselorId.options[i].selected = true;
					break;
				}
			}
			for (i = 0; i < document.editEventForm.editEventType.options.length; i++) {
				if (document.editEventForm.editEventType.options[i].value == curEvent.type) {
					document.editEventForm.editEventType.options[i].selected = true;
					break;
				}
			}
			var oldStart = dojo.widget.byId("editEventStart");
			var oldEnd = dojo.widget.byId("editEventEnd");
			var target = oldStart.domNode.parentNode;
			oldStart.destroy();
			oldEnd.destroy();
			var newStart = dojo.widget.createWidget("DropDownDatePicker", {id: "editEventStart", name: "editEventStart", saveFormat: "unix", value: new Date(curEvent.start)});
			var newEnd = dojo.widget.createWidget("DropDownDatePicker", {id: "editEventEnd", name: "editEventEnd", saveFormat: "unix", value: new Date(curEvent.end)});
			target.insertBefore(newStart.domNode, target.childNodes[1]);
			target.appendChild(newEnd.domNode);
			});
	updateEventsTable();
}

function updateLocationForm() {
	if (document.schoolForm.locationName && document.schoolForm.locationName.value) {
		document.editLocationForm.locationName.value = document.schoolForm.locationName.value;
		document.editLocationForm.locationAddress.value = document.schoolForm.locationAddress.value;
		document.editLocationForm.locationAddress1.value = document.schoolForm.locationAddress1.value;
		document.editLocationForm.locationCity.value = document.schoolForm.locationCity.value;
		document.editLocationForm.locationState.value = document.schoolForm.locationState.value;
		document.editLocationForm.locationZip.value = document.schoolForm.locationZip.value;
	}
}

function setLocationFormDefaults() {
	document.editLocationForm.locationName.defaultValue = document.editLocationForm.locationName.value;
	document.editLocationForm.locationAddress.defaultValue = document.editLocationForm.locationAddress.value;
	document.editLocationForm.locationAddress1.defaultValue = document.editLocationForm.locationAddress1.value;
	document.editLocationForm.locationCity.defaultValue = document.editLocationForm.locationCity.value;
	document.editLocationForm.locationState.defaultValue = document.editLocationForm.locationState.value;
	document.editLocationForm.locationZip.defaultValue= document.editLocationForm.locationZip.value;
}

function updateNewEventLocation() {
	document.newEventForm.locationName.value = document.editLocationForm.locationName.value;
	document.newEventForm.locationAddress.value = document.editLocationForm.locationAddress.value;
	document.newEventForm.locationAddress1.value = document.editLocationForm.locationAddress1.value;
	document.newEventForm.locationCity.value = document.editLocationForm.locationCity.value;
	document.newEventForm.locationState.value = document.editLocationForm.locationState.value;
	document.newEventForm.locationZip.value = document.editLocationForm.locationZip.value;
}

function processor(target, data, action) {
	document.newEventForm.addEventButton.disabled = true;
	document.newEventForm.addEventButton.value = "Processing ...";
	if (! action) { 
		action = { action: "save" };
	}
	var kw = {
		mimetype: "text/html",
		formNode: data,
		content: action,
		transport: "XMLHTTPTransport",
		load: function(type, result) {
			target.innerHTML = result;
			document.newEventForm.addEventButton.value = "Add Event";
			document.newEventForm.addEventButton.disabled = false;
			switch (action.action) {
				case "locationAdmin":
					updateLocationForm();
					updateNewEventLocation();
					setLocationFormDefaults();
					break;
				case "newEvent":
				case "cloneEvent":
				case "deleteEvent":
				case "saveEvent":
					updateEventsTable();
					break;
				default:
					break;
			}
		},
		error: function(type, data, evt){
		       dojo.debug("processor " + action.action);
		       dojo.debugDeep(data);
	       }
	}
	dojo.io.bind(kw);
}

function updateEventsTable() {
	var w=dojo.widget.byId("eventsTable");
	var kw = {
		url: "eventdump.pl",
		mimetype: "application/json",
		transport: "XMLHTTPTransport",
		load: function(type, result) {
			w.store.setData(result);
			filterEventsTable();
		},
		error: function(type, data, evt){
		       dojo.debugDeep(data);
	       }
	}
	dojo.io.bind(kw);
}

function filterEventsTable() {
	var byDate = document.getElementById("filterDate");
	var byCounselor = document.getElementById("filterCounselorId");
	var byState = document.getElementById("filterState");
	var today = new Date();
	var w=dojo.widget.byId("eventsTable");
	w.clearFilters();
	if (byDate.value == "upcoming") {
		w.setFilter("start", function(name) { 
				return (name >= today);
				});
	}

	if (byDate.value == "past") {
		w.setFilter("start", function(name) { 
				return (name <= today);
				});
	}

	if (byCounselor.value) {
		w.setFilter("counselor", function(name) { 
				return (name == byCounselor.value);
				});
	}

	if (byState.value) {
		w.setFilter("state", function(state) { 
				return (state == byState.value);
				});
	}
}

function checkLocations() {
	var w=dojo.widget.byId("eventsTable");
	w.store.forEach(function(data) { 
			var address = data.src.address + " " + data.src.address1 + " " + data.src.city + " " + data.src.state + " " + data.src.zip;
			geocoder.getLatLng(address, function(point) {
				if (point) {
					data.src.lat = point.lat();
					data.src.lng = point.lng();
				} else {
					dojo.debug('I can not find coords for ' + address); 
				}
				});
			});
	dojo.debug("done");
}
