var map;
var geocoder;
var gmarkers = [];
var dir = "left";
var sidebar_width;
var fromAddress;
var toAddress;
var parkingKML;
var gmanager;
var fo;
var acomplete;
var firstImage;
var markerList = new Array();
var myLocalSearch;
var openSidbar = true;
var sidarbarLoaded = false;
var DDSPEED = 10;
var DDTIMER = 15;
var secs
var timerID = null
var timerRunning = false
var delay = 1000
var markerAddress = querySt("address");
var markerCity = querySt("city");
var markerState = querySt("state");
var markerZip = querySt("zip");
var local = querySt("e");

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 0
    StopTheClock()
    StartTheTimer()
}

function StopTheClock()
{	
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}

function StartTheTimer()
{
    if (secs==0)
    {
        StopTheClock()
		initialize()
	
    }
    else
    {
        self.status = secs
        secs = secs - 1
        timerRunning = true
        timerID = self.setTimeout("StartTheTimer()", delay)
    }
}
function stripHTML(html){
	var re = /(<([^>]+)>)/gi;
	for (i=0; i<arguments.length; i++)
		html=html.replace(re, "")
	return html
}

function initialize() { 
	
	if(markerAddress != undefined){
		html = decodeURIComponent(markerAddress) + "<br>" + markerCity + ", " +  markerState + " " + markerZip
		html = stripHTML(html)
		html2 = decodeURIComponent(markerAddress) + " " + markerCity + ", " +  markerState + " " + markerZip
		html2 = stripHTML(html2)
		showAddress(html2, html)
	}
	listAllMarkers();
} 

function showAddress(address, html) {  
	geocoder.getLatLng(address, 
	   function(point) {
		   if (!point) {
			   alert(address + " not found");
		   } else {
			   map.setCenter(point, 16);
			   var marker = new GMarker(point);
			   html = "<strong>Address:</strong><br>"  + html
			   html += "<div style='margin-bottom:10px;'><a href='javascript:showSearch(\"otherDirections\")'>Get Directions to here.</a></div>"
			   html += "<div style='height:40px'><div id=\"otherdirectionsbar\">"
			   html += "Start Address: <br><input type=\"text\" size=\"20\" id=\"otherFromAddress\" name=\"address\" onKeyPress=\"javascript:submitOnEnter(event, 'od'); \" />"
			   html += "<input type=\"button\" value=\"Go\" id=\"getDirections\" onclick=\"setDirections(document.getElementById('otherFromAddress').value, 'NONE');\">"
			   html += "</div></div>"
			   marker.mycontent = html;
			   marker.point = point;
			   map.addOverlay(marker);
			   marker.openInfoWindowHtml(html);
			   GEvent.addListener(marker, 'click', function() {
					//marker.openInfoWindowTabsHtml(tabs);
					marker.openInfoWindowHtml(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];
		}
	}
}

//This opens the photo gallery.
function openGallery(id) {
	document.getElementById("flashcontent").style.display = "block";
	document.getElementById("flashBackground").style.display = "block";
	document.getElementById("closeGallery").style.display = "block";
	fo.addVariable('xmlURL', 'images.php?id=' + id);
	fo.write('flashcontent');
}

//This closes the photo gallery.
function closeGallery() {
	document.getElementById("flashcontent").innerHTML = "";
	document.getElementById("flashBackground").style.display = "none";
	document.getElementById("flashcontent").style.display = "none";
	document.getElementById("closeGallery").style.display = "none";
}

//find a location and show that marker
function addLocation() {
	var title = document.getElementById('autocomplete_field').value;
	for(i in gmarkers) {
		if(gmarkers[i].myname == title) {
			gmarkers[i].show();
			gmarkers[i].openInfoWindowHtml(gmarkers[i].mycontent);
			break;
		}
	}
}

//This is used to run the search.
function findLocation() {
	myLocalSearch.execute(document.getElementById('autocomplete_field').value);
	document.getElementById('mapMarkersTitle').style.display = "none"
}

//This is used to clear the text.
function firstClear(obj) {
	if(obj.clearThis == undefined) {
		obj.value = '';
		obj.clearThis = true;
		obj.style.color = "#000000";
	}
}

/*****************************************
 GOOGLE.SEARCH
 ****************************************/

function initiateSearch() {
	myLocalSearch = new google.search.LocalSearch();
	myLocalSearch.setCenterPoint(map.getCenter());

	var searchControl = new google.search.SearchControl(null);
	searchControl.addSearcher(myLocalSearch);
	searchControl.setSearchCompleteCallback(this, googleSearchCallback);
	searchControl.draw(document.getElementById("searchcontrol"));
}

function removeSearchMarkers() {
	for(var i = 0; i < markerList.length; i++) {
		map.removeOverlay(markerList[i].gmarker);
	}
	markerList = new Array();
}

function clearSearch() {
	document.getElementById("content").innerHTML = "";
	if(dir == "right")
		slideLeft();
}

function clearDirections() {
	removeSearchMarkers();
	document.getElementById("content").innerHTML = "";
	if(dir == "right")
		slideLeft();
	
	map.setCenter(new GLatLng(41.15530,-87.8720), 16);
	reapplyTileLayerOverlay();
	gdir.clear() 
}

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();
				var number = ""
				markerObject.result = result;
				markerObject.latLng = new GLatLng(parseFloat(result.lat), parseFloat(result.lng));
				markerObject.gmarker = new GMarker(markerObject.latLng);
				
				if(typeof(result.phoneNumbers) !== 'undefined') {
					number = "<br>" + result.phoneNumbers[0].number
				}
				markerObject.content = "<a href='" + result.url + "'>" + result.title + "</a><br>" + result.streetAddress + "<br>" + result.city + ", " + result.region + 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>");
	if(dir == "left")
		slideRight();
}

//This handles the click action of the marker.
function onMarkerClick(markerObject) {
	map.closeInfoWindow();
	var htmlNode = markerObject.result.html.cloneNode(true);
	markerObject.gmarker.openInfoWindow(htmlNode);
}

//This closes the marker.
function method_closure(object, method, opt_argArray) {
	return function() {
	    return method.apply(object, opt_argArray);
    }
}

/*****************************************
 END GOOGLE.SEARCH
 ****************************************/

function showMe(){
	if(local == 1 ){
		map.setCenter(new GLatLng(41.192536,-87.966802), 19);
	}else if(local == 2){
		map.setCenter(new GLatLng(55.34529,-131.658547), 16);
	}else if(local == 3){
		map.setCenter(new GLatLng(41.949411,-87.654234), 19);
	}else if (local == 4){
		map.setCenter(new GLatLng(41.827705,-87.632318), 19);
	}else if(local == 5){
		map.setCenter(new GLatLng(41.894599,-87.623804), 19);
	}
}

function load() {
	fo = new SWFObject('autoviewer/autoviewer.swf', 'autoviewer', '100%', '100%', '8', '#181818');
	fo.addParam('wmode', 'transparent');
	parkingKML= new GGeoXml("http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=108842306921406306194.0004545a27fbebc829cc3&z=16&output=kml");
	//auto complete for text field
	acomplete = actb(document.getElementById("autocomplete_field"), keywords);

	resize();
	window.onresize = function() { resize() };

	//Create map
	
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(41.15530,-87.8720), 16);
	map.addControl(new GLargeMapControl());
	gmanager = new GMarkerManager(map);
	geocoder = new GClientGeocoder();
	//local search
	initiateSearch();
	showMe();

	// 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);
		    var markers = xml.documentElement.getElementsByTagName("marker");
			var titles  = xml.getElementsByTagName("title")
			var contents  = xml.getElementsByTagName("content")
		    for (var i = 0; i < markers.length; i++) {
				
		    	var title = titles[i].childNodes[0].nodeValue; //markers[i].getAttribute("title");
				title = title.replace(/"/gi, "&quot;");
			    var content = contents[i].childNodes[0].nodeValue; //markers[i].getAttribute("content");
			    var firstImage = markers[i].getAttribute("firstImage");
				var photos = markers[i].getAttribute("images");
				var tiger_dollars = markers[i].getAttribute("tiger_dollars");
			    var markertype = markers[i].getAttribute("markertype");
			    var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
				var id = markers[i].getAttribute("id");
			    var marker = createMarker(id, point, title, content, photos, markertype, tiger_dollars, firstImage);
			    map.addOverlay(marker);
				gmarkers.push(marker);
			}
        
			//sort the gmarkers array
			gmarkers.sort(customsort);
			listAllMarkers();
		
		
			//show or hide the markertypes initially
			for (var i = 0; i < marker_type.length; i++) {
				if(show_marker[i] == 1){
					show(marker_type[i]);
				}else{
					hide(marker_type[i]);
				}
			}
	})
    
    //Add the ONU map overlay tile set
		//tile overlay
	var tileLayerOverlay = new GTileLayerOverlay(
		new GTileLayer(null, null, null, {
			tileUrlTemplate: '../images/myTiles/onu_{Z}_{X}_{Y}.png',
			isPng:true,
			opacity:1.0
		})
	);
    map.addOverlay(tileLayerOverlay);

	//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"]
	}
	bothSettings = {
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 5 },
		br: { radius: 5 },
		antiAlias: true,
		autoPad: true,
		validTags: ["div"]
	}
	var topBox = new curvyCorners(topSettings, "top");
	var btmBox = new curvyCorners(bottomSettings, "btm");
	var closeBox = new curvyCorners(bothSettings, "close");
	topBox.applyCornersToAll();
	btmBox.applyCornersToAll();
	
	//Load check box data.
    var checkBoxsDiv = "";
	checkBoxsDiv += '<div class="dropdown">\n';
    checkBoxsDiv += '<div id="titleText" class="ddheader" onmouseover="ddMenu(\'titleText\',\'mapDetailsContent\',1)" onmouseout="ddMenu(\'titleText\',\'mapDetailsContent\',-1)">Map Details</div>\n';
    checkBoxsDiv += '<div id="mapDetailsContent" class="ddcontent" onmouseover="cancelHide(\'titleText\',\'mapDetailsContent\')" onmouseout="ddMenu(\'mapDetailsContent\',\'mapDetailsContent\',-1)">\n';
    checkBoxsDiv += '<ul>\n';
	for (var i = 0; i < marker_type.length; i++) {
		if(marker_type[i] == 'parking'){
			checkBoxsDiv += '<li class="underline" onmouseup="toggleMarker(\'' + marker_type[i] + '\')"><input type="checkbox" id="' + marker_type[i] + 'box" onclick="toggleMarker(\'' + marker_type[i] + '\')"">  ' + display_name[i] + '</li>\n';
		}else{
			checkBoxsDiv += '<li class="underline" onmouseup="toggleMarker(\'' + marker_type[i] + '\')"><input type="checkbox" id="' + marker_type[i] + 'box" onclick="toggleMarker(\'' + marker_type[i] + '\')"">  ' + display_name[i] + '</li>\n';
		}
		
	}
	checkBoxsDiv +=  '<li class="underline" onmouseup="displayTigerDollars(document.getElementById(\'TigerDollars\'))"><input type="checkbox" name="TigerDollars" id="TigerDollars" onClick="displayTigerDollars(this)"> Tiger Dollars' + '</li>\n'
	checkBoxsDiv += '</ul>\n'
    checkBoxsDiv += '</div>\n'
	checkBoxsDiv += '</div>\n'
	document.getElementById('checkboxes').innerHTML = checkBoxsDiv;
	map.enableScrollWheelZoom();
	InitializeTimer();
	
	
}

//Reapply the tiles if something has changed.
function reapplyTileLayerOverlay(){
	var tileLayerOverlay = new GTileLayerOverlay(
		new GTileLayer(null, null, null, {
			tileUrlTemplate: '/images/myTiles/onu_{Z}_{X}_{Y}.png',
			isPng:true,
			opacity:1.0
		})
	);
    map.addOverlay(tileLayerOverlay);	
}

function extendMarker(marker, html, result) {
	var pnt = marker.getLatLng().lat() + " " + marker.getLatLng().lng();
	var myStuff = document.createElement("div");
	myStuff.innerHTML = "<br /><br />Directions from <a style='text-decoration:underline; color:#0000FF;' onclick=\"setDirections('" + pnt + "','toONU');\">ONU</a>.";
	marker.closeInfoWindow();
	html.appendChild(myStuff);
	return html;
}

//This submits the form when the user pushes the enter key.
function submitOnEnter(e, type, point) {
	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) {
		if(type == 'd'){
			setDirections(document.getElementById('fromAddress').value, document.getElementById('fromorto').value);
		}else if(type == 'od'){
			setDirections(document.getElementById('otherFromAddress').value, 'NONE');
		}else if(type == 'Waypoints'){
			setDirections(document.getElementById('otherFromAddress').value, 'Waypoints', point)
		}else if(type == 's'){
			findLocation();	
		}
	}
}

//This loads the requested directions.
function onGDirectionsLoad() {
		// clear the local search results (if any)
		if(dir == "left")
    		slideRight();

		//add the print link
		document.getElementById('content').innerHTML = "<a href='" + printMap() + "' target='_blank'>Print Directions</a> <a href='javascript:clearDirections()'>Clear Directions</a>";
		document.getElementById('mapMarkersTitle').style.display = "none"
		sidarbarLoaded = false;
		openSidbar = true;
}
	
// add parking overlay
function addParking() {
	
	map.addOverlay(parkingKML);
}

// remove parking overlay
function removeParking() {
	map.removeOverlay(parkingKML);
}

// return the url for the print map
function printMap() {
	return "http://maps.google.com/maps?f=q&hl=en&geocode=&q=" + fromAddress + "+to+" + toAddress + "&z=6&pw=2";
}

//This is used to sort an array.
function customsort(a,b){
    if (a.myname>b.myname)
        return 1;
    else if (a.myname<b.myname)
        return -1;
    else
    return 0;
}

//This displays the search results.
function showSearch(inType) {
	if(inType == "search") {
		document.getElementById("searchbar").style.display = "block";
		document.getElementById("directionsbar").style.display = "none";
	} else if(inType == "directions") {
		document.getElementById("searchbar").style.display = "none";
		document.getElementById("directionsbar").style.display = "block";
	} else if(inType == "otherDirections"){
		document.getElementById("searchbar").style.display = "none";
		document.getElementById("directionsbar").style.display = "none";
		document.getElementById("otherdirectionsbar").style.display = "block";
		document.getElementById("otherFromAddress").focus();
	}
	
}

//resize the map.
function resize() {
    if(dir == "left") {
        document.getElementById("map").style.width = "100%"; //document.documentElement.clientWidth;
        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");
    }
}

//Move the side bar to the left.
function slideLeft() {
    document.getElementById("map").style.height = document.documentElement.clientHeight - 75 + "px";
    document.getElementById("map").style.width = "100%";
	document.getElementById("map").style.margin = "0";
	document.getElementById("map").style.left = "0";
    
	sidebar_width = 300;
	slideLeft_do();
    dir = "left";
	map.checkResize()
	openSidbar = true;
}

//Move the side bar to the right.
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";
	}
}

//This moves the side bar to the left.
function slideLeft_do() {
    var obj = document.getElementById('sidebar');
    var obj2 = document.getElementById('map');
	if (sidebar_width > -10) {
		sidebar_width -= 20;
        obj.style.left = sidebar_width + 'px';

        setTimeout('slideLeft_do();', 2);
    } else if (sidebar_width <= -20) {
		obj2.style.left = "0px";
		obj.style.display = "none";
	}
}

//This restes the map to the default settings.
function resetMap() {
	gdir.clear();
	map.setCenter(new GLatLng(41.15530,-87.8720), 16);
	slideLeft();
}

//Set the direction to move the side bar. I.E. right or left.
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(address, direction, point) {
	if(direction == "toONU") {
		fromAddress = "" + address;
		toAddress = "1 University Ave Bourbonnais IL 60914";
	} else if(direction == "NONE"){
		fromAddress = "" + address;
		toAddress = decodeURIComponent(markerAddress) + " " + markerCity + ", " +  markerState + " " + markerZip	
	} else if(direction == "Waypoints"){
		fromAddress = "" + address;
		toAddress = point	
	} else {
		fromAddress = "1 University Ave Bourbonnais IL 60914";
		toAddress = "" + address;
	}
	var points = []
	
	points[0] = fromAddress
	points[1] = toAddress
	gdir.loadFromWaypoints(points);
}


function mapit(){
	document.getElementById('mapMarkersTitle').style.display = "inline"
	document.getElementById("mapMarkersTitle").innerHTML = "Map It";
	
	var html = "";
	html += '<div><div style="width:60px; float:left;">Address:</div> <input type="text" size="25" id="mapitAddress" name="mapitAddress"  /></div>'
	html += '<div><div style="width:60px; float:left;">City:</div> <input type="text" size="25" id="mapitCity" name="mapitCity"  /></div>'
	html += '<div><div style="width:60px; float:left;">State:</div> <input type="text" size="2" id="mapitState" name="mapitState"  /></div>'
	html += '<div><div style="width:60px; float:left;">Zip:</div> <input type="text" size="10" id="mapitZip" name="mapitZip"  /></div>'
	html += '<div><input type="button" id="mapitSubmit" value="Get The URL" onclick="showURL()"> <a href="javascript:viewIT()">View it</a></div>'
	html += '<div style="display:none; margin-top:25px;" id="mapitURLDiv"><div>URL:</div> <input type="text" size="30" id="mapitURL" name="mapitURL"  onclick="document.getElementById(\'mapitURL\').focus();	document.getElementById(\'mapitURL\').select()"/>'
	html += ' <input type="button" id="mapitCopyURL" value="Copy URL" onclick="copy(document.getElementById(\'mapitURL\').value)">'
	html += '</div>'
	document.getElementById("content").innerHTML = html;
	 if (!window.clipboardData) {
		 document.getElementById('mapitCopyURL').style.display = "none"	
	 }
	if(dir == "left")
		slideRight();
}

function viewIT(){
	markerAddress = document.getElementById('mapitAddress').value
	markerCity = document.getElementById('mapitCity').value
	markerState = document.getElementById('mapitState').value
	markerZip = document.getElementById('mapitZip').value
	html = decodeURIComponent(markerAddress) + "<br>" + markerCity + ", " +  markerState + " " + markerZip
	html = stripHTML(html)
	html2 = decodeURIComponent(markerAddress) + " " + markerCity + ", " +  markerState + " " + markerZip
	html2 = stripHTML(html2)
	showAddress(html2, html)
}

function showURL(){
	markerAddress = document.getElementById('mapitAddress').value
	markerCity = document.getElementById('mapitCity').value
	markerState = document.getElementById('mapitState').value
	markerZip = document.getElementById('mapitZip').value
	document.getElementById('mapitURL').value = "http://map.olivet.edu/?address=" + markerAddress + "&city=" + markerCity + "&state=" + markerState + "&zip=" + markerZip
	
	document.getElementById('mapitURLDiv').style.display = "block"	
	document.getElementById('mapitURL').focus();
	document.getElementById('mapitURL').select()
}

function copy(text2copy) {
    if (window.clipboardData) {
        window.clipboardData.setData("Text",text2copy);
	}
    alert('The text is copied to your clipboard...');   
    return false;  
}

//Hanle any errors given by the directions.
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.");
}

//Show tiger dollars markers depend if the check box is checked or not.
function displayTigerDollars(checkbox){
	if(!checkbox.checked){
			checkbox.checked = true;
		}else{
			checkbox.checked = false;
		}
	for(var i = 0; i < gmarkers.length; i++) {
		if(gmarkers[i].tiger_dollars == 1 && checkbox.checked){
			gmarkers[i].show()
		}else if(gmarkers[i].tiger_dollars == 1 && !checkbox.checked){
			if(document.getElementById(gmarkers[i].markertype + "box").checked){
			}else{
				gmarkers[i].hide();
			}
		}
	}
}

//show all markers of a particular markertype, and ensure that the checkbox is checked
function show(category) {
	for(var i = 0; i < gmarkers.length; i++) {
		
		if(gmarkers[i].markertype == category) {
			gmarkers[i].show();
		}	
	}
	// check the checkbox
	document.getElementById(category + "box").checked = true;
}

// hide all markers of a particular markertype, and ensure the checkbox is cleared
function hide(category) {
	for(var i = 0; i < gmarkers.length; i++) {
		if(document.getElementById('TigerDollars').checked && gmarkers[i].tiger_dollars == 1){
		}else{
			if(gmarkers[i].markertype == category) {
				gmarkers[i].hide();
			}
		}
	}
	// clear the checkbox
	document.getElementById(category + "box").checked = false;

	//close the infor window, in case it is open on a marker that we just hid
	map.closeInfoWindow();
}

// on a click from the event list
function myclick(i) {
    GEvent.trigger(gmarkers[i],"click");
	reapplyTileLayerOverlay();
}

// a checkbox has been clicked
function boxclick(box, marker) {
	if(box.checked) {
		show(marker);
	} else {
		hide(marker);
	}
}

// the parking checkbox was clicked
function parkingclick(pkbox) {
	if(pkbox.checked) {
		addParking();
		document.getElementById("parkingKey").style.display = "block";
		map.setCenter(new GLatLng(41.15530,-87.8720), 16);
		reapplyTileLayerOverlay();
	}
	else {
		removeParking();
		document.getElementById("parkingKey").style.display = "none";
	}
}

// Create a marker given the following attributes
function createMarker(id, point, title, content, images, markerType, tiger_dollars, firstImage) {
	var addStarOnMarker = false;
	if(tiger_dollars == 1){
		addStarOnMarker = true;
	}
	for(i = 0; i < marker_height.length; i++){
		if(marker_type[i] == markerType){
			var mk = MapIconMaker.createLabeledMarkerIcon({addStar: addStarOnMarker, width:marker_width[i], height:marker_height[i], label: marker_lable[i], primaryColor: marker_color[i]});
		}
	}
		
	var marker = new GMarker(point, mk); 
	marker.markertype = markerType;
	marker.myname = title;
	marker.tiger_dollars = tiger_dollars;
	marker.point = point;

	var html = ""
	if(images == "") {
		html += "<h2 style='margin:0px; padding-bottom:10px;'>" + title + "&nbsp;&nbsp;<span style='color:gray; font:8pt Verdana'>" + markerType + "</span></h2>"; 
		html += "<div style='text-align:justify; padding-right:10px; overflow:auto;  max-width:400px; max-height:350px; float:'>" + convertToHtml(content) + "</div>";
		html += "</div>";
		if(addStarOnMarker){
			html += "<div><img src=\"" + mk.image + "\" width=\"20\" align=\"absmiddle\" border=\"0\"/> Tiger Dollars are accepted at this location.</div>";
		}
	} else {
		var imgSrc = "";
		html += "<div id='markerContnet' style='z-index:0; height:410px; width:460px'>"
		if(firstImage != ""){
			firstImage = "<div style='float:left; margin:0 5px 5px 0; padding:10px 5px 5px 0; width:260px'>" +
						   "<a href='javascript:openGallery(" + id + ")'><img style='border:0; width:250px; margin:0 10px 10px 0; padding:3px;' src='/images/mapimages/" + firstImage + "'>" +
						   "<br><center><a href='javascript:openGallery(" + id + ")'>Click for more images from " + title + "</a></center><br clear='both'>" +
					   "</div>" 
		}
		html += "<h2 style='margin:0px; padding-bottom:10px;'>" + title + "&nbsp;&nbsp;<span style='color:gray; font:8pt Verdana'>" + markerType + "</span></h2>" +
				   "<div style='text-align:justify; padding-right:10px; overflow:auto; height:350px'>" + firstImage +
				   "" + convertToHtml(content) + "";
		html += "</div></div>";
		if(addStarOnMarker){
			html += "<div><img src=\"" + mk.image + "\" width=\"20\" align=\"absmiddle\" border=\"0\"/> Tiger Dollars are accepted at this location.</div>";
		}
	}
	html += "<div style='margin-bottom:10px;'><a href='javascript:showSearch(\"otherDirections\")'>Get Directions to here.</a></div>"
	html += "<div style='height:40px'><div id=\"otherdirectionsbar\">"
			   html += "Start Address: <br><input type=\"text\" size=\"20\" id=\"otherFromAddress\" name=\"address\" onKeyPress=\"javascript:submitOnEnter(event, 'Waypoints', '" + point + "'); \" />"
			   html += "<input type=\"button\" value=\"Go\" id=\"getDirections\" onclick=\"setDirections(document.getElementById('otherFromAddress').value, 'Waypoints', '" + point + "');\">"
			   html += "</div></div>"
	marker.mycontent = html;

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

//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 += '<option onclick="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '</option>';
        }
    }
    document.getElementById("selectMarkers").innerHTML = html;
}

// List al the markers in the content div
function listAllMarkers() {
		document.getElementById('mapMarkersTitle').style.display = "inline"
			gmarkers.sort(customsort);
			var html = "";
			for(var j = 0; j < marker_type.length; j++){
				if(getMarkers(marker_type[j]) != ""){
					var mkIcon = MapIconMaker.createLabeledMarkerIcon({width:15, height:15, label: marker_lable[j], primaryColor: marker_color[j]});
					html += "<a href=\"javascript:displayMarker('" + marker_type[j] + "')\">";
					html += "<img src=\"" + mkIcon.image + "\" width=\"20\" align=\"absmiddle\" border=\"0\"/></a> ";
					html += "<a href=\"javascript:displayMarker('" + marker_type[j] + "')\" class=\"markerTypeTitle\">" + display_name[j] + "</a>";
					html += "<ul class=\"markersListUL\">"; 
					for(var i = 0; i < gmarkers.length; i++) {
						if(gmarkers[i].markertype ==  marker_type[j]){
							html += '<li><a href="javascript:myclick(' + i + '); displayMarker(\'' + marker_type[j] + '\')">' + gmarkers[i].myname+ '</a><br /></li>';
						}
					}
					html += "</ul>";
				}
			}
			document.getElementById("content").innerHTML = html;
		if(dir == "left")
			slideRight();
}

// Search gmarkers for a marker, returning the marker reference.
function searchMarkers(inMarker) {
	for(var i = 0; i < gmarkers.length; i++) {
		if(gmarkers[i].point == inMarker.point) {
			return i;
		}
	}
}

// Get all markers of a certain markertype, returning them in an array
function getMarkers(inType) {
	var typeArray = new Array();
	for(var i = 0; i < gmarkers.length; i++) {
		if(gmarkers[i].markertype == inType) {
			typeArray.push(gmarkers[i]);
		}
	}
	
	return typeArray;
}

// This shows the marker that the user clicked on in the side bar.
function displayMarker(markerType) {
	var markerTypeField = document.getElementById(markerType + "box")
	if(markerType == "parking"){
		if(!markerTypeField.checked){
			markerTypeField.checked = true;
			parkingclick(markerTypeField)
		}
	}else{
		if(!markerTypeField.checked){
			markerTypeField.checked = true;
			boxclick(markerTypeField, markerType)	
		}
	}
}

//This is used to display markers. If the user clicks on the marker check box.
function toggleMarker(markerType) {
	var markerTypeField = document.getElementById(markerType + "box")
	if(markerType == "parking"){
		if(!markerTypeField.checked){
			markerTypeField.checked = true;
			parkingclick(markerTypeField)
		}else{
			markerTypeField.checked = false;
			parkingclick(markerTypeField)
		}
	}else{
		if(!markerTypeField.checked){
			markerTypeField.checked = true;
			boxclick(markerTypeField, markerType)	
		}else{
			markerTypeField.checked = false;
			boxclick(markerTypeField, markerType)
		}
	}
}

function nToBR(myString){
	return myString.replace(/\n/g, "<br />");
}

function BRtoN(myString){
      myString=myString.replace(/<br.*?>/ig, "\n");
      return myString;
}
// Convert string to html
function convertToHtml(inString) {
    var tempString = inString;
	tempString = nToBR(tempString)
	tempString = tempString.replace(/%u200E/gi, "");
	tempString = tempString.replace(/%u2019/gi, "'");
    tempString = tempString.replace(/&lt;/gi, "<");
    tempString = tempString.replace(/&gt;/gi, ">");
    tempString = tempString.replace(/&quot;/gi, "\"");
	
    return tempString;
}


// main function to handle the mouse events //
function ddMenu(id,cid,d){
  var h = document.getElementById(id);
  var c = document.getElementById(cid);
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id,cid){
  var h = document.getElementById(id);
  var c = document.getElementById(cid);
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}
