var map;
var gmarkers = [];
var dir = "left";
var gmanager;
var sidebar_width;
var fromAddress;
var toAddress;
//var markerOptions = { icon:onuIcon };

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);
	gmanager = new GMarkerManager(map);

	// Markers
	GDownloadUrl("markers2.php", function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {
			var pop = markers[i].getAttribute("pop");
			var city = markers[i].getAttribute("city");
			var state = markers[i].getAttribute("state");
			var address = state + " , US";
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			var marker = createMarker(point, null, state, pop);
			gmanager.addMarker(marker,3,9);
		}
	});

	GDownloadUrl("markers1.php", function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {
			var pop = markers[i].getAttribute("pop");
			var city = markers[i].getAttribute("city");
			var state = markers[i].getAttribute("state");
			var address = state + " , US";
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			var marker = createMarker(point, city, state, pop);
			gmanager.addMarker(marker,10,13);
		}
	});

	//tile overlay
	/*
	var tileLayerOverlay = new GTileLayerOverlay(
		new GTileLayer(null, null, null, {
			tileUrlTemplate: '../images/myTiles/onu_{Z}_{X}_{Y}.png',
			isPng:true,
			opacity:1.0
		})
	);
    
    //Add the ONU map overlay tile set
    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"]
	}
	var topBox = new curvyCorners(topSettings, "top");
	var btmBox = new curvyCorners(bottomSettings, "btm");
	topBox.applyCornersToAll();
	btmBox.applyCornersToAll();
	
	map.enableScrollWheelZoom();
}

// 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(address, direction) {
	if(direction == "toONU") {
		fromAddress = "" + address;
		toAddress = "1 University Ave Bourbonnais IL 60914";
	} else {
		fromAddress = "1 University Ave Bourbonnais IL 60914";
		toAddress = "" + address;
	}
	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");
}

// Create a marker given the following attributes
function createMarker(point, city, state, pop) {
	var mk = eval("onuIcon");
	if(city == null) {
		if(pop <=1) {
			var html = "<b>" + state + "</b><br />There is " + pop + " city in " + state + " with alumni<br /><br /><a href='javascript:map.setZoom(10);'>Click here</a> to view city population specifics";
		} else {
			var html = "<b>" + state + "</b><br />There are " + pop + " cities in " + state + " with alumni<br /><br /><a href='javascript:map.setZoom(10);'>Click here</a> to view city population specifics";
		}
	} else {
		if(pop <= 1) {
			var html = "<b>" + city + ", " + state + "</b><br/>There is " + pop + " ONU alumn here";
		} else {
			var html = "<b>" + city + ", " + state + "</b><br/>There are " + pop + " ONU alumni here";
		}
	}
	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;
}
