var map;
var gmarkers = [];
var markerTitleArray = [];
var markerAddressArray = [];
var dir ="right";
var gmanager;
var sidebar_width;
var fromAddress = "";
var toAddress = "";
var markersLength = 0;
var markerList = new Array();
//var markerOptions = { icon:onuIcon };

function showNewMarker(point, html){
	map.openInfoWindowHtml(point,html);	
}

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function googleSearchCallback(sc, searcher) {
	document.getElementById("content").innerHTML = "<h3>Search Results:</h3>";
	removeSearchMarkers();
	if(searcher.results && searcher.results.length > 0) {
		for(var i = 0; i < searcher.results.length; i++) {
			// Add search results markers to map
			var result = searcher.results[i];
			if(result.GsearchResultClass == GlocalSearch.RESULT_CLASS) {
				var markerObject = new Object();
				markerObject.result = result;
				markerObject.latLng = new GLatLng(parseFloat(result.lat), parseFloat(result.lng));
				markerObject.gmarker = new GMarker(markerObject.latLng);
				markerObject.content = "<a href='" + result.url + "'>" + result.title + "</a><br>" + result.streetAddress + "<br>" + result.city + ", " + result.region + "<br>" + result.phoneNumbers[0].number + "<br><a href='" + result.ddUrlToHere + "'>directions</a>";
				var clickHandler = method_closure(this, onMarkerClick, [markerObject]);
				GEvent.bind(markerObject.gmarker, "click", this, clickHandler);
				this.markerList.push(markerObject);
				map.addOverlay(markerObject.gmarker);
			}
			
			// Add description and links to content bar
			document.getElementById("content").innerHTML += "<a href='javascript:markerList[" + i + "].gmarker.openInfoWindowHtml(markerList[" + i + "].content)'>" + result.title + "</a><br>" + result.streetAddress+ "<br><br>";
		}
		this.onMarkerClick(this.markerList[0]);
	}
	document.getElementById("content").innerHTML += ("<a href='javascript:clearSearch();'>Clear search</a>");
}

//This loads the requested directions.
function onGDirectionsLoad() {
	// clear the local search results (if any)
	//add the print link
	document.getElementById('content').innerHTML = "<a href='" + printMap() + "' target='_blank'>Print Directions</a> <a href='javascript:clearDirections()'>Clear Directions</a> ";
}

function removeSearchMarkers() {
	for(var i = 0; i < markerList.length; i++) {
		map.removeOverlay(markerList[i].gmarker);
	}
	markerList = new Array();
}

function listAllMarkers() {
	var html = ""
	for (var i = 0; i < markerAddressArray.length; i++) {
		html += "<p><img src=\"http://map.olivet.edu/images/markerPurple.png\" align=\"absmiddle\" border=\"0\"/> ";
		html += "<a href=\"javascript:myclick('" + i + "');\"  class=\"markerTypeTitle\">" + markerTitleArray[i] + "<div style='margin-left:15px; margin-top:-15px; color:#000000; font-weight:normal;  text-decoration:none'>" + "<br>" + markerAddressArray[i] + "</div></a></p>";
		document.getElementById("content").innerHTML = html;
	}
}

function clearDirections() {
	removeSearchMarkers();
	gdir.clear() 
	listAllMarkers()
}

function load() {
	resize();
	window.onresize = function() { resize() };

	//Create map
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	//map.setCenter(new GLatLng(35,-96), 4);
	map.setCenter(new GLatLng(40.633125,-89.398529), 7);
	gmanager = new GMarkerManager(map);

	// Directions variable
	gdir = new GDirections(map, document.getElementById("content"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);

	// Markers
	GDownloadUrl("markers.php", function(data) {
		var xml = GXml.parse(data);
		markers = xml.documentElement.getElementsByTagName("marker");
		var html = "";
		var markerToShow = querySt("show");
		var markerContent = "";
		for (var i = 0; i < markers.length; i++) {
			var id = markers[i].getAttribute("id");
			var title = markers[i].getAttribute("title");
			markerTitleArray[i] = title
			var content = markers[i].getAttribute("content");
			var address = markers[i].getAttribute("address") + "<br>" + markers[i].getAttribute("city") + ", " + markers[i].getAttribute("state") + " " + markers[i].getAttribute("zip")
			markerAddressArray[i] = address
			var address2 = markers[i].getAttribute("address") + " " + markers[i].getAttribute("city") + ", " + markers[i].getAttribute("state") + " " + markers[i].getAttribute("zip")
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			var marker = createMarker(point, title, content, address, address2);
			html += "<p><img src=\"http://map.olivet.edu/images/markerPurple.png\" align=\"absmiddle\" border=\"0\"/> ";
			html += "<a href=\"javascript:myclick('" + i + "');\"  class=\"markerTypeTitle\">" + title + "<div style='margin-left:15px; margin-top:-15px; color:#000000; font-weight:normal;  text-decoration:none'>" + "<br>" + address + "</div></a></p>"; 
			
			document.getElementById("content").innerHTML = html;
			gmanager.addMarker(marker,3,17);
			//map.addOverlay(marker);
			gmarkers.push(marker)
			if(id == markerToShow){
				var html2 = "<div style='height:100px;'><strong>" + title + "</strong><br>" + address + "<br>" +  content
				html2 += "<div style='margin-bottom:10px;'><a href='javascript:showSearch(\"otherDirections\")'>Get Directions to here.</a></div>"
				html2 += "<div id=\"otherdirectionsbar\">"
				html2 += "Start Address: <br><input type=\"text\" size=\"20\" id=\"otherFromAddress\" name=\"address\" onKeyPress=\"javascript:submitOnEnter(event, '" + address2 + "'); \" />"
				html2 += "<input type=\"button\" value=\"Go\" id=\"getDirections\" onclick=\"setDirections(document.getElementById('otherFromAddress').value, '" + address2 + "');\">"
				html2 += "</div></div>"
				showNewMarker(point, html2)	
			}
		}
			
	});

			
	//CurvyCorners
	topSettings = {
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 0 },
		br: { radius: 0 },
		antiAlias: true,
		autoPad: true,
		validTags: ["div"]
	}
	bottomSettings = {
		tl: { radius: 0 },
		tr: { radius: 0 },
		bl: { radius: 5 },
		br: { radius: 5 },
		antiAlias: true,
		autoPad: true,
		validTags: ["div"]
	}
	var topBox = new curvyCorners(topSettings, "top");
	var btmBox = new curvyCorners(bottomSettings, "btm");
	topBox.applyCornersToAll();
	btmBox.applyCornersToAll();
	
	map.enableScrollWheelZoom();
	
}

function slideRight() {
    document.getElementById("map").style.height = document.documentElement.clientHeight - 75 + "px";
    document.getElementById("sidebar").style.height = document.documentElement.clientHeight - 85 + "px";
    document.getElementById("sidebar").style.display = "inline";
    document.getElementById("sidebar").style.width = "310px";
	document.getElementById("sidebar").style.margin = "0 0 0 -300px";
	
	sidebar_width = 0;
    slideRight_do();

    dir = "right";
	resize();
	map.checkResize()
}
//This moves the side bar to the right.
function slideRight_do() {
    var obj = document.getElementById('sidebar');
    var obj2 = document.getElementById('map');
	if (sidebar_width < 300) {
		sidebar_width += 20;
        obj.style.left = sidebar_width + 'px';

        setTimeout('slideRight_do();', 2);
    } else if (sidebar_width == 300) {
		obj2.style.left = "320px";
        obj2.style.width = document.documentElement.clientWidth - 320 + "px";
	}
}


// return the url for the print map
function printMap() {
	// http://maps.google.com/maps?f=q&hl=en&geocode=&q=60914+to+14609&sll=41.167637,-87.881538&sspn=0.009918,0.016351&ie=UTF8&ll=41.195707,-87.82711&spn=0.07931,0.130806&z=13&pw=2

	return "http://maps.google.com/maps?f=q&hl=en&geocode=&q=" + fromAddress + "+to+" + toAddress + "&z=6&pw=2";
}

function customsort(a,b){
    if (a.myname>b.myname)
        return 1;
    else if (a.myname<b.myname)
        return -1;
    else
    return 0;
}

function resize() {
    if(dir == "left") {
        document.getElementById("map").style.width = "100%";
        document.getElementById("map").style.height = document.documentElement.clientHeight - 75 + "px";
        document.getElementById("map").style.margin = "0";
        document.getElementById("sidebar").style.display = "none";
    } else if(dir == "right") {
        document.getElementById("map").style.height = document.documentElement.clientHeight - 75 + "px";
        document.getElementById("sidebar").style.height = document.documentElement.clientHeight - 75 + "px";
        document.getElementById("map").style.width = document.documentElement.clientWidth - 320  + "px";
        document.getElementById("sidebar").style.width = "310px";
    } else {
        alert("Wrong direction");
    }
}

function resetMap() {
	map.setCenter(new GLatLng(35,-96), 4);
}

function moveSidebar(dir) {
	var sb = document.getElementById("sidebar");
	var mp = document.getElementById("map");

	if (dir == "left") {
	} else if (dir == "right" ) {
		sb.style.display = "block";
		sb.style.width = "30%";
		mp.style.width = "70%";
	} else {
		alert("Direction not correct");
	}
}

//DIRECTIONS:
function setDirections(fAddress, tAddress) {
	fromAddress = fAddress
	toAddress = tAddress
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "en_US" });
}

function handleErrors() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
   		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
 	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
   		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
  	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    	alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
   	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    	alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
   	else alert("An unknown error occurred.");
}

// on a click from the event list
function myclick(i) {
    GEvent.trigger(gmarkers[i],"click");
}

//This submits the form when the user pushes the enter key.
function submitOnEnter(e, address) {
	var ENTER_KEY = 13;
	var code = "";

	if (window.event) // IE
	{
		code = e.keyCode;
	}
	else if (e.which) // Netscape/Firefox/Opera
	{
		code = e.which;
	}
	
	if (code == ENTER_KEY) {
		setDirections(document.getElementById('otherFromAddress').value, address);
	}
}

//This displays the search results.
function showSearch(inType) {
	if(inType == "otherDirections"){
		document.getElementById("otherdirectionsbar").style.display = "block";
	}
	
}


// Create a marker given the following attributes
function createMarker(point, title, content, address, address2) {
	var mk = eval("onuIcon");
	var html = "<div style='height:100px;'><strong>" + title + "</strong><br>" + address + "<br>" +  content
	html += "<div style='margin-bottom:10px;'><a href='javascript:showSearch(\"otherDirections\")'>Get Directions to here.</a></div>"
	html += "<div id=\"otherdirectionsbar\">"
	html += "Start Address: <br><input type=\"text\" size=\"20\" id=\"otherFromAddress\" name=\"address\" onKeyPress=\"javascript:submitOnEnter(event, '" + address2 + "'); \" />"
	html += "<input type=\"button\" value=\"Go\" id=\"getDirections\" onclick=\"setDirections(document.getElementById('otherFromAddress').value, '" + address2 + "');\">"
	html += "</div></div>"
	var marker = new GMarker(point, mk);
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	
	return marker;
}

function getGallery(string) {
	//parse string into array
}

//rebuilds the sidebar to match the markers currently displayed
function makeSidebar() {
	var html = "<option disabled='true' selected='true'>Select a marker</option>";
    for(var i = 0; i < gmarkers.length; i++) {
        if(!gmarkers[i].isHidden()) {
            //html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname+ '</a><br />';
            html += '<option onclick="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '</option>';
        }
    }
    document.getElementById("selectMarkers").innerHTML = html;
}

// Convert string to html
function convertToHtml(inString) {
    var tempString = inString;
    tempString = tempString.replace(/&lt;/gi, "<");
    tempString = tempString.replace(/&gt;/gi, ">");
    tempString = tempString.replace(/&quot;/gi, "\"");
    return tempString;
}
