//
// different utility methods
//

var printMap;

function e(divId){
	return document.getElementById(divId);
}

function getCampus(){
	return e("campusSelect").value;
}

function getCampusParent(){
	return window.opener.document.getElementById("campusSelect").value;
}

function fullScreen(url){
	var params = 'width='+screen.width;
	params += ', height='+screen.height;
	params += ', top=0, left=0';
	params += ', scrollbars=yes';
	params += ', fullscreen=yes';
	newwin=window.open(url,'fs', params);
	if (window.focus) {
		newwin.focus()
	}
	return false;
}

function openPrintPage(){
	newwin = window.open('index_print.html','print');
	if (window.focus) {
		newwin.focus()
	}
	return false;
}

function initializeMap() {
	if (!GBrowserIsCompatible()) {
		// display a warning if the browser was not compatible
		alert("Sorry, the Google Maps API is not compatible with this browser");
		return;
	}
	
	//e("uo_map").innerHTML = window.opener.document.getElementById("uo_map").innerHTML;
	
	printMap = new GMap2(e("uo_map_print"));

    var mt = printMap.getMapTypes();
    for (var i=0; i<mt.length; i++) {
      mt[i].getMaximumResolution = function() {return 18;}
    }

    printMap.addControl(new GSmallZoomControl());
    printMap.enableScrollWheelZoom();

    // set the centre point - grap the center from the opener...
	printMap.setCenter(window.opener.UOM._map.gmap.getCenter(), window.opener.UOM._map.gmap.getZoom(), G_NORMAL_MAP);
	
	printMap.addOverlay(createTileOverlay(getCampusParent()));
	
	setTimeout("addAllVisibleMarkers()",500);
	setTimeout("addDirections()",1000);
}

function addAllVisibleMarkers() {
	var newMarkers = window.opener.UOM._map.allMarkers;
	var count = 0;
	for (var i in newMarkers) {
		if (i != "buildingCodes" && i != "buildingNames" && i != "parkingLot") {
			for (var j = 0; j < newMarkers[i].length; j++) {
				var printArray = newMarkers[i][j];
				var printMarker = new cloneObject(printArray[1]);
				if (!printMarker.isHidden()) {
					var marker = new GMarker(printMarker.getPoint(), {icon:printMarker.getIcon()})
					printMap.addOverlay(marker);
				}
			}
		} else {
			//alert('codes or names');
			for (var j = 0; j < newMarkers[i].length; j++) {
				var printArray = newMarkers[i][j];
				//var printMarker = new cloneObject(printArray[1]);
				var printMarker = printArray[1];
				if (!printMarker.isHidden()) {
					var icon = new GIcon();
					icon.iconSize = new GSize(0,0);
					icon.iconAnchor = new GPoint(20,20);
					icon.image = "";
					var labelText = "";
//					if (window.opener.UOM.isIE()) {
//						var bgcolor = "#ffffff";
//						var color = "#000000";
//					} else {
//						var bgcolor = "#8c404f";
//						var color = "#ffffff";
//					}
					if (i == "buildingCodes") {
						var labelText = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td bgcolor=\"#ffffff\" nowrap><font size=\"1\" color=\"#000000\"><b>"+window.opener.BUILDINGS[printArray[0]].code+"</b></font></td></tr></table>";
						var markerOpts = {"icon": printMarker.getIcon(),
								  		  "title": window.opener.BUILDINGS[printArray[0]].name,
								  		  "labelText": labelText
					   			 	     };
					} else if (i == "buildingNames") {
						var labelText = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td bgcolor=\"#ffffff\" nowrap><font size=\"1\" color=\"#000000\"><b>"+window.opener.BUILDINGS[printArray[0]].name+"</b></font></td></tr></table>";
						var markerOpts = {"icon": icon,
								  		  "title": window.opener.BUILDINGS[printArray[0]].name,
								  		  "labelText": labelText
					   			 		 };
					} else {
						var icon = new GIcon();
						icon.iconSize = new GSize(20,20);
						icon.iconAnchor = new GPoint(20,20);
						//alert('parking');
						icon.image = "images/icons/icon_Parking_lot_32.png";
						if (window.opener.PARKING["parkingLot"][printArray[0]].label.length > 1) {
							var labelText = "<font color=\"#ffffff\" size=\"0.5px\"><b>"+window.opener.PARKING["parkingLot"][printArray[0]].label+"</b></font>";
							var labelOffset = new GSize(-18, -17);
						} else {
							var labelText = "<font color=\"#ffffff\"><b>"+window.opener.PARKING["parkingLot"][printArray[0]].label+"</b></font>";
							var labelOffset = new GSize(-14, -18);
						}
						//alert('parking');
						var markerOpts = {"icon": icon,"labelText": labelText,"labelOffset": labelOffset};
					}
					var marker = new LabeledMarker(printMarker.getPoint(),markerOpts);
					//alert('marker created');
					printMap.addOverlay(marker);
					//alert('added');
				}
			}
		}
	}
}

function cloneObject(what) {
    for (i in what) {
        this[i] = what[i];
    }
}

function addDirections() {
	if (window.opener.UOM._map.shortestPolyArray.length > 0) {

		printMap.addOverlay(new GPolyline(window.opener.UOM._map.shortestPolyArray, window.opener.UOM._shortestPathColor, window.opener.UOM._shortestPathThickness, 1, null));
	
		for (var i = 0; i < window.opener.UOM._map.insidePolyArray.length; i++) {
			printMap.addOverlay(new GPolyline(window.opener.UOM._map.insidePolyArray[i], window.opener.UOM._insidePathColor, window.opener.UOM._shortestPathThickness, 1, null));
		}

		var dirMarkers = window.opener.UOM._directionsMarkers;
		for (var i = 0; i < dirMarkers.length; i++) {
			var icon = new GIcon();
			icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			icon.image = i==0?"images/icons/icon_starting.gif":"images/icons/icon_destination.png";
			icon.iconSize = new GSize(20, 34);
			icon.shadowSize = new GSize(37, 34);
			icon.iconAnchor = new GPoint(9, 34);
			icon.infoWindowAnchor = new GPoint(9, 2);
			icon.infoShadowAnchor = new GPoint(18, 25);
			var newDirMarker = new cloneObject(dirMarkers[i]);
			//var icon = new GIcon(G_DEFAULT_ICON, "images/icons/icon_starting.gif");
			var marker = new GMarker(newDirMarker.getPoint(), {icon:icon});
			printMap.addOverlay(marker);
		}
		
		var dby = window.opener.document.getElementById("routingValue").value=="shortest"?"Shortest":"Warmest";
		var dtext = window.opener.document.getElementById("uo_path_distance").innerHTML;
	
		var html = "<div style='padding-top:5px;padding-bottom:5px;'><span style='color:#6f1223;font-weight:bold;'>Directions by:</span> "+dby+"</div>" +
				   "<div style='padding-bottom:5px;'><span style='color:#6f1223;font-weight:bold;'>Starting Point:</span> "+window.opener.document.getElementById("uo_end_location").options[window.opener.document.getElementById("uo_end_location").selectedIndex].text+"</div>" +
				   "<div style='padding-bottom:5px;'><span style='color:#6f1223;font-weight:bold;'>Destination:</span> "+window.opener.document.getElementById("uo_start_location").options[window.opener.document.getElementById("uo_start_location").selectedIndex].text+"</div>" +
				   "<div style='padding-bottom:5px;color:#ff8a00;font-weight:bold;'>"+dtext+"</div>";				   
		e("uo_directions").style.display = "";
		e("uo_directions").innerHTML = html;
	}
}

function doClose() {
	this.focus();
	window.top.opener = this;
	window.top.close(); 
}

function doPrint() {
	this.focus();
	window.top.opener = this;
	window.top.print(); 
}

function updatePrint() {
	if (e("tools-print")) {
		e("tools-print").href = "javascript:void(0);";
		e("tools-print").onclick = function() { var temp = new Function("openPrintPage()"); temp(); };
	}
}

function createTileOverlay(campus) {
	// ============================================================
	// ====== Create a copyright entry =====
	var copyright = new GCopyright(1,
			new GLatLngBounds(new GLatLng(45.4,-75.7),new GLatLng(45.5,-75.6) ),
			14, "Development");

	// ============================================================
	// ====== Create a copyright collection =====
	// ====== and add the copyright to it   =====
	var copyrightCollection = new GCopyrightCollection('Layouts (c) 2008');
	copyrightCollection.addCopyright(copyright);     

	// ============================================================
	// == Write our own getTileUrl functions ========
	var customGetTileUrl=function(pt,zm){
		if (zm < 12) return "http://maps.google.com/intl/en_ALL/mapfiles/transparent.png";
		// convert the point to latlng and determine if we have this tiles

		// Define our tile boundaries--should do this outside of this function
		//	or store it once calculated for future use
		// Note: origin in google maps is top-left
		if (campus.toString() == "mba") {
			var topLeft = new GLatLng(45.421739,-75.699180);
			var bottomRight = new GLatLng(45.420918,-75.695736);
		} else if (campus.toString() == "lees") {
			var topLeft = new GLatLng(45.416573,-75.669966);
			var bottomRight = new GLatLng(45.414871,-75.665331);
		} else if (campus.toString() == "altaVista") {
			var topLeft = new GLatLng(45.404476, -75.654516);
			var bottomRight = new GLatLng(45.398571, -75.637608);
		} else { //Default to main
			var topLeft = new GLatLng(45.426573,-75.689707);
			var bottomRight = new GLatLng(45.4188,-75.67);
		}
		
		// convert our lat/long values to world pixel coordinates
		var currentProjection = G_NORMAL_MAP.getProjection();
		var minPixelPt = currentProjection.fromLatLngToPixel(topLeft, zm);
		var maxPixelPt = currentProjection.fromLatLngToPixel(bottomRight, zm);

		// convert our world pixel coordinates to tile coordinates

		var minTileCoord = new GPoint();
		minTileCoord.x = Math.floor(minPixelPt.x / 256);
		minTileCoord.y = Math.floor(minPixelPt.y / 256);

		var maxTileCoord = new GPoint();
		maxTileCoord.x = Math.floor(maxPixelPt.x / 256);
		maxTileCoord.y = Math.floor(maxPixelPt.y / 256);

		// filter out any tile requests outside of our bounds
		if (pt.x < minTileCoord.x ||
				pt.x > maxTileCoord.x ||
				pt.y < minTileCoord.y ||
				pt.y > maxTileCoord.y)
		{
			return 'http://maps.google.com/intl/en_ALL/mapfiles/transparent.png';
		}

		// use this formula for tiles cut with Map Cruncher
		if (campus.toString() == "mba") {
			var tileurl = "tiles/mba/"+tileToQuadKey(pt.x,pt.y,zm) + ".png";
		} else if (campus.toString() == "lees") {
			var tileurl = "tiles/lees/"+tileToQuadKey(pt.x,pt.y,zm) + ".png";
		} else if (campus.toString() == "altaVista") {
			var tileurl = "tiles/altaVista/"+tileToQuadKey(pt.x,pt.y,zm) + ".png";
		} else { //Default to main
			var tileurl = "tiles/"+tileToQuadKey(pt.x,pt.y,zm) + ".png";
		}
		
		//GLog.write ("Requesting tile " + tileurl);
		return tileurl;
	}
	// ============================================================
	// ===== Create the GTileLayer =====
	// ===== and apply the CustomGetTileUrl to it
	var layer = new GTileLayer(copyrightCollection,14,18);
	layer.getTileUrl = customGetTileUrl;
	layer.isPng = function() {return true;};
	layer.getOpacity = function() {return 1.0;};
	// ============================================================
	// ===== Return the GTileLayerOverlay =====
	var overlay = new GTileLayerOverlay(layer);
	return overlay;

	// This Javascript is based on code provided by the
	// Blackpool Community Church Javascript Team
	// http://www.commchurch.freeserve.co.uk/   
	// http://econym.googlepages.com/index.htm
	// --------------------------------------------------------------------------------------
}

//the following function taken from Bill Chadwick at http://www.bdcc.co.uk/GoogleCrunch/Crunch.htm
function tileToQuadKey(x, y, zoom) {
	var quad = "";
	for (var i = zoom; i > 0; i--){
		var mask = 1 << (i - 1);
		var cell = 0;
		if ((x & mask) != 0)
			cell++;
		if ((y & mask) != 0)
			cell += 2;
		quad += cell;
		quad=zoom+"_"+(x)+"_"+y;
	}
	return quad;
}

