// Initiate our global variables...
var map;
var myPano;
var directionsPanel;
var directions;
var mapTypeControl;
var mapZoomControl;
var uwsLocation;
var uwsChosenLocation;
var uwsOverview; uwsOverview = new Array(2);
var customzoom;
var controlsVisible = false;
var myAccordion;
var marker;
var uwsIcon;
var noHide;
var directionsLoaded;
var startLocID;
var endLocID;
var directionsMode = 'custom';
var myTravelMode;

// Number of potential locations...
uwsLocation = new Array(8);
// Set our multidimensional array
for (i = 0; i < uwsLocation.length; i++) {
	uwsLocation[i] = new Array(2);
}

marker = new Array(uwsLocation.length);
// Set multidimensional object...erm..yeah
for (i = 0; i < uwsLocation.length; i++) {
	marker[i] = new Object();
}
    
function handleNoFlash(errorCode) {
	if (errorCode == 603) {
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	}
}

window.addEvent('domready', function() {
	// Show toggles
	$('options').setStyle('display', 'block');

	if (GBrowserIsCompatible()) {
	
		// Load map
		map = new GMap2(document.getElementById("map"));
		
		map.setCenter(
			new GLatLng(
				uwsDefaultLocation['lat'], 
				uwsDefaultLocation['lng']
			), customzoom
		);
		
		// Street View
		myPano = new GStreetviewPanorama(document.getElementById("streetView"));  
		GEvent.addListener(myPano, "error", handleNoFlash);

		
		
		// Load startup vars.
		map.setMapType(G_HYBRID_MAP);
		toggleControls();
		
		// Load directions (even though we havent got anything out of it yet!)
		directionsPanel = document.getElementById("directionsarea");
		directions = new GDirections(map, directionsPanel);
		
		
		// And one to remove all the markers... Note this also means it was successful
		// in generating the directions...
		GEvent.addListener(directions, "load", function(){
			map.clearOverlays();
			statusConversion('good');
			directionsLoaded = true;
			$('startLocation_link').set('html', '');
			$('endLocation_link').set('html', '');
		});
		
		// Add event to remove the loading icon once its found the directions from 
		// google. This is triggered AFTER "load" once all overlays are done loading
		GEvent.addListener(directions, "addoverlay", function(){
			$('loadingButton').setStyle('display', 'none');
			directionsLoaded = true;
			// Insert the start location link back to the campus...
			if (startLocID)
				$('startLocation_link').set('html', '<a href="'+uwsLocation[startLocID]['moreurl']+'">Get start campus map and information</a>');
			
			// Insert the end location link back to the campus...
			if (destLocID)
				$('endLocation_link').set('html', '<a href="'+uwsLocation[destLocID]['moreurl']+'">Get destination campus map and information</a>');
		});
		
		GEvent.addListener(directions, "error", function(){
			$('loadingButton').setStyle('display', 'none');
			statusConversion('error', this.getStatus().code);
		});
		
		// Marker options
		uwsIcon = new GIcon();
		uwsIcon.image = "http://prom.uws.edu.au/pubapps/data/maps/images/uwsicon.png";
		uwsIcon.shadow = "http://prom.uws.edu.au/pubapps/data/maps/images/uwsicon.png";
		uwsIcon.iconSize = new GSize(25, 20);
		uwsIcon.shadowSize = new GSize(25, 20);
		uwsIcon.iconAnchor = new GPoint(17, 14);
		uwsIcon.infoWindowAnchor = new GPoint(5, 1);
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:uwsIcon };
		
		addAllMarkers()
		
		// Add in the left nav toggle bar
		var toggleNav = new Element('a', {
		    'href': '',
		    'class': 'toggleNav',
		    'styles': {
		        'height': $('maparea').getStyle('height').toInt() + 2
		    },
		    'events': {
		        'click': function(){
		            alert('clicked');
		        }
		    }
		});
		
		//toggleNav.inject('maparea', 'after');
		
		
	}
	
});

window.addEvent('domready', function() {

	// Function for the directions input
	$('userlocation').addEvent('submit', function(ee) {
		
		// Transport mode detection
		if ($('transportMode').get('value') == 'walking') {
			myTravelMode = G_TRAVEL_MODE_WALKING;
		} else if ($('transportMode').get('value') == 'driving') {
			myTravelMode = G_TRAVEL_MODE_DRIVING;
		}
		
		
		// Flash to show that its done something...
		// $('directionsbox').highlight('#FFF1AF');
		
		// Add the little loading icon...
		$('loadingButton').setStyle('display', 'block');
		
		startLocID = $('campusSelectbox').get('value');
		destLocID = $('campusDestSelectbox').get('value');
		
		if (directionsMode == 'custom') {
			startLocID = '';
			// Make sure that a value exists first...
			if ($('directionsbox').get('value').clean() == '') {
				statusConversion('error', 700);
			// And make sure the destination value exists (it always should...)
			} else if (destLocID.clean() == '') {
				statusConversion('error', 800);
			} else {
				locationInput = "from " + $('directionsbox').get('value') + " " + $('state_select').get('value') + " to " + uwsLocation[destLocID]['lat'] + ", " + uwsLocation[destLocID]['lng'];
				directions.load(locationInput, {travelMode: myTravelMode});
			}
		} else if (directionsMode == 'campus') {
			if (startLocID.clean() == '') {
				statusConversion('error', 701);
			} else if (destLocID.clean() == '') {
				statusConversion('error', 800);
			} else if (destLocID == startLocID) {
				statusConversion('error', 702);
			} else {
				locationInput = "from " + uwsLocation[startLocID]['lat'] + ", " + uwsLocation[startLocID]['lng'] + " to " + uwsLocation[destLocID]['lat'] + ", " + uwsLocation[destLocID]['lng'];
				directions.load(locationInput, {travelMode: myTravelMode});
			}
		}
		
		
		ee.stop();
		
	});
	
	// Toggle directions type button
	$$('.toggle_directions_type').addEvent('click', function(ee) {
	
		// Show left form (custom directions) and hide campus input
		if ($('custom_start_location').getStyle('display') == 'none') {
			
			$('custom_start_location').setStyle('display', 'block');
			$('campus_to_campus').setStyle('display', 'none');
			
			// Set var
			directionsMode = 'custom';
			
		} else {
			
			$('custom_start_location').setStyle('display', 'none');
			$('campus_to_campus').setStyle('display', 'block');
			// Set var
			directionsMode = 'campus';
		}
		
		
		ee.stop();
	});
	
	
	// Has to be mouseup because IE has timing issues...
	$$('#leftnav ul#navitems li a.navchoice').each(function(e, num){
		$(e).addEvent('mouseup', function(ee){
	    	
	    	// Essentially, this just checks to see if any of the accordion
	    	// menus are open... if not, then it will reset the map.
			var foundlink;
			if ($('#navitems li a.on')){
				foundlink = true;
			}
			if (foundlink != true) {
	    		// The user has closed the current campus. Zoom out.
				customzoom = 8;
				newcenter = map.setCenter(
				new GLatLng(
						uwsOverview['lat'], 
					uwsOverview['lng']
					), customzoom
				);
			}
			
			if (ee) {
				ee.stop();
			}
		});
		$(e).addEvent('click', function(ee){
			if (ee) {
				ee.stop();
			}
		});
	});

	// Hide the directions from its default spot.
	$('directions_global_holder').setStyle('display', 'none');
	
	// Show the directions tab
	$('tabdirections_toggle').setStyle('display', 'block');
	
	myAccordion = new Accordion($$('#leftnav ul li a.navchoice'), $$('#leftnav ul li ul'), {
	    display: defaulted,
	    alwaysHide: true,
	    onActive: function(toggler, element){
	    	
	    	// This is the campus ID.
			num = ($(toggler).id).substr(7, 8);
			
			if (!$(toggler).hasClass('on')) {
	    		$(toggler).addClass('on');
	    	}
	    	$(element).addClass('on');
	    	
			resetUWSMap(true, true, num);
			
			
	    	
			customzoom = 15;
			newcenter = map.setCenter(
				new GLatLng(
					uwsLocation[num]['lat'], 
					uwsLocation[num]['lng']
				), customzoom
			);
			uwsChosenLocation = num;
	    },
	    onBackground: function(toggler, element){
			
	    	$(toggler).removeClass('on');
	    	$(element).removeClass('on');
	    }
	});
	
	$('controlToggle').addEvent('click', function(ee){
		toggleControls();
		$('controlToggle').highlight('#FFF1AF');
		ee.stop();
	});
	
	$('removeDirections').addEvent('click', function(ee){
		resetUWSMap();
		$('removeDirections').highlight('#FFF1AF');
		ee.stop();
	});
	
	//$('showStreetView').addEvent('click', function(ee){
	//	streetViewSwitch('toggle');
	//	ee.stop();
	//});
	
	// Switching tabs.
	$$('#mapTabs ul li a').each(function(mapTabButton){
		$(mapTabButton).addEvent('click', function(evnt) {
		
			resetUWSMap();

			// Remove the start/end location links (reset)
			$('startLocation_link').set('html', '');
			$('endLocation_link').set('html', '');
			
			if (!$(mapTabButton).getParent().hasClass('tabon')) {
			
				$$('#mapTabs ul li.tabon').getLast().removeClass('tabon');
				$(mapTabButton).getParent().addClass('tabon');
				
				switch($(mapTabButton).id) {
				
					// Load the standard maps tab
					case 'tab_campusmaps':
						$('directions_global_holder').setStyle('display', 'none');
						$('leftnav').setStyle('display', 'inline');
						$('maparea').setStyle('width', '490px');
						//$('showStreetView').setStyle('display', 'block');
					break;
					
					// Load the directions tab
					case 'tab_directions':
						$('directions_global_holder').setStyle('display', 'block');
						$('leftnav').setStyle('display', 'none');
						$('maparea').setStyle('width', '100%');
						// Street view not available in directions view
						//$('showStreetView').setStyle('display', 'none');
						//streetViewSwitch(false);
					break;
					
				}
			}
			
			evnt.stop();
			
		});
	});
	
});

// Street view functionality not ready. Has been disabled.
function streetViewShow() {
	$('streetView').setStyle('display', 'block');
	$('showStreetView').set('text', 'Hide Street View');
	
	$('map').setStyle('height', '250px');
	map.checkResize();
	resetUWSMap(true, true);
	toggleControls('showsmall');
	
	svOverlay = new GStreetviewOverlay();
	map.addOverlay(svOverlay);        
	GEvent.addListener(map, "click", function(overlay,latlng) {
		myPano.setLocationAndPOV(latlng);
	});
	
}

function streetViewHide() {
	myPano.hide();
	
	$('map').setStyle('height', '350px');
	map.checkResize();
	resetUWSMap(true, true);
	toggleControls('hidesmall');
	
	$('streetView').setStyle('display', 'none');
	$('showStreetView').set('text', 'Show Street View');
	map.removeOverlay(svOverlay);
}


function streetViewSwitch(on) {
	switch(on) {
		case true:
			streetViewShow();
		break;
		case false:
			streetViewHide();
		break;
		case 'toggle':
			if ($('streetView').getStyle('display') == 'none') {
				streetViewShow();
			} else {
				streetViewHide();
			}
		break;
	}
}

function statusConversion(errorOrGood, errorCode) {

	$('resultsbox').setStyle('display', 'block');
	// Done loading... hide the loading image.
	$('loadingButton').setStyle('display', 'none');

	
	if (errorOrGood == 'error') {
		
		switch(errorCode) {
			case 601:
				errorText = '<div id="results_error"><span>Unable to create directions.</span> <a href="http://www.uws.edu.au/campuses_structure/cas/campuses/interactive_maps_help" class="help">Help</a></div>';
				break;
			case 602:
				errorText = '<div id="results_error"><span>Unable to create directions.</span> <a href="http://www.uws.edu.au/campuses_structure/cas/campuses/interactive_maps_help" class="help">Help</a></div>';
				break;
			case 603:
				errorText = '<div id="results_error"><span>Unable to create directions.</span> <a href="http://www.uws.edu.au/campuses_structure/cas/campuses/interactive_maps_help" class="help">Help</a></div>';
				break;
			case 604:
				errorText = '<div id="results_error"><span>Unable to create directions.</span> <a href="http://www.uws.edu.au/campuses_structure/cas/campuses/interactive_maps_help" class="help">Help</a></div>';
				break;
			case 620:
				errorText = '<div id="results_error"><span>Unable to create directions.</span> <a href="http://www.uws.edu.au/campuses_structure/cas/campuses/interactive_maps_help" class="help">Help</a></div>';
				break;
			case 700:
				errorText = 'No directions entered';
				break;
			case 701:
				errorText = 'No start campus selected';
				break;
			case 702:
				errorText = 'Destination same as start location';
				break;
			case 800:
				errorText = 'No destination chosen';
				break;
		}
		
		$('resultsbox').set('html', errorText);
		$('resultsbox').addClass('error');
		$('resultsbox').removeClass('success');
		
		// Reset the map
		resetUWSMap(true, true);
		
	} else if (errorOrGood == 'good') {
		if ($('resultsbox').getStyle('display') == 'block') {
			$('resultsbox').setStyle('display', 'none');
		}
	}
	
}

// Add campus markers
function addAllMarkers() {
	for (i = 0; i < uwsLocation.length; i++) {
		center = new GLatLng(uwsLocation[i]['lat'], uwsLocation[i]['lng']);
		
		marker[i] = new GMarker(center, markerOptions);
		map.addOverlay(marker[i]);
		marker[i].myID = i;
		GEvent.addListener(marker[i], "click", function(){
		
			myID = this.ID;
			newcenter = map.setCenter(this.getLatLng(), 15);
			noHide = true;
			uwsChosenLocation = this.myID;
			
			// This stops is opening/closing an already open campus.
			
			// This is the accordion menu item.
			var isOpen = $('campus_'+this.myID).getNext();
			if ($(isOpen)) {
				// Check if its visible...
				if ($(isOpen).getStyle('visibility') == 'visible') {
					num = this.myID;
					customzoom = 15;
					newcenter = map.setCenter(
						new GLatLng(
							uwsLocation[num]['lat'], 
							uwsLocation[num]['lng']
						), customzoom
					);
					uwsChosenLocation = num;
				// Not visible... open the accordion menu.
				} else {
					myAccordion.display(this.myID);
				}
			}
			
		});
	}
}

// Reset the map
function resetUWSMap(dontzoomout, keepresultbar, campusID, forceRemark) {

	// Remove the start/end location links (reset)
	$('startLocation_link').set('html', '');
	$('endLocation_link').set('html', '');
	
	// Check if the directions have been loaded (we dont want to do the cpu-intensive task of reloading markers
	// unless necessary)
	if ((directionsLoaded == true) || (forceRemark == true)) {
		map.clearOverlays();
		addAllMarkers();
		directionsLoaded = false;
	}
	
	if (keepresultbar != true) {
		// Reset results status bar
		$('resultsbox').setStyle('display', 'none');
		// Clear text
		$('directionsbox').set('value', '');
	}
	
	
	$('directionsarea').set('html', '');
		
	// Proper reset if not set to true
	if (dontzoomout != true) {
		// Hides the accordion menu
		$$('#leftnav ul li a.on').each(function(ele){
			$(ele).fireEvent('click');
		});
		// Zoom out.
		customzoom = 8;
		newcenter = map.setCenter(
			new GLatLng(
				uwsOverview['lat'], 
				uwsOverview['lng']
			), customzoom
		);
	}
}

// The "Hide/Show" Controls button
function toggleControls(showsmall) {
	if (!showsmall) {
		if (controlsVisible == true) {
			// Remove controls
			map.removeControl(mapTypeControl);
			map.removeControl(mapZoomControl);
			
			$('controlToggle').set('text', 'Show controls');
			controlsVisible = false;
		} else {
			// Add them to vars
			mapTypeControl = new GMapTypeControl();
			mapZoomControl = new GLargeMapControl();
			// Add them properly...
			map.addControl(mapTypeControl);
			map.addControl(mapZoomControl);
			
			controlsVisible = true;
			$('controlToggle').set('text', 'Hide controls');
		}
	} else {
		if ((showsmall == 'showsmall') && (controlsVisible == true)) {
			// Remove controls first
			map.removeControl(mapTypeControl);
			map.removeControl(mapZoomControl);
			// Add small controls
			mapTypeControl = new GMapTypeControl();
			mapZoomControl = new GSmallMapControl();
			map.addControl(mapTypeControl);
			map.addControl(mapZoomControl);
		} else if ((showsmall == 'hidesmall') && (controlsVisible == true)) {
			// Remove existing controls
			map.removeControl(mapTypeControl);
			map.removeControl(mapZoomControl);
			// Add normal controls
			mapTypeControl = new GMapTypeControl();
			mapZoomControl = new GLargeMapControl();
			map.addControl(mapTypeControl);
			map.addControl(mapZoomControl);
		}
	}
}

// Now IE builds up a whole lot of memory leaks if we dont do this... (it doesnt unload correctly)

function fixUnload() {
	// Is there things still loading, then fake the unload event
	if (document.readyState == 'interactive') {
		function stop() {
			// Prevent memory leak
			document.detachEvent('onstop', stop);

			// Call unload handler
			unload();
		};

		// Fire unload when the currently loading page is stopped
		document.attachEvent('onstop', stop);

		// Remove onstop listener after a while to prevent the unload function
		// to execute if the user presses cancel in an onbeforeunload
		// confirm dialog and then presses the stop button in the browser
		window.setTimeout(function() {
			document.detachEvent('onstop', stop);
		}, 0);
	}
};

function fixUnload() {GUnload();};
function unload() {GUnload();};

if (window.attachEvent) {
	window.attachEvent('onunload', unload);
	window.attachEvent('onbeforeunload', fixUnload);
}