// Global Variables
var map = null;
var sideBarHtml = '<ul id="labul">';
var labMarkers = [];
var geoXml = null;
var labsVisible = true;
var labsWithStats = [];

function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function tableRow(label, text) {
	var html = '<tr><th>';
	html += label;
	html += '</th><td>';
	html += text;
	html += '</td></tr>';
	return html;
}

function processMarkers() {
	// Intermediately used objects
	var point;
	var marker;
	
	// XML based data
	var latitude;
	var longitude;
	var buildingname;
	var html;

	$.getJSON("/scripts/campusmaps/labs.cfm", 
			  {}, 
			  function(data, textStatus) {				
				// For each object in the labs array...
				$.each(data.labs,
					   function() {
						   
						    // Process single lab entry
							var regularInfo = "";
							var summaryInfo = "";
							var markerhtml  = "";
							var usagehtml   = "";							
							var laburl      = "";
							var lablinkid   = "";
							var labliid     = "";
							var labspanid   = "";
							var detailTab   = null;
							var usageTab    = null;
							var option      = null;							
							var tabs        = [];
							
							var point =  new GLatLng(this.LATITUDE, this.LONGITUDE);
							var marker = new GMarker(point);
							
							// Labels for minimized and maximized state of info window
							regularInfo = this.LOCATION + '<br /><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more information ... </a>'
                    		summaryInfo = '<a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().restore()">less information ... </a>';
							
							// HTML for general information tab
							markerhtml += "<table>";
							markerhtml += '<thead><tr><th colspan="2">' + this.LOCATION + '</th></tr></thead>';
							markerhtml += "<tbody>";
							if (this.CONTACTNAME != "") {
								markerhtml += tableRow("Contact", this.CONTACTNAME);
							}
							if (this.LABPHONE != "") {
								markerhtml += tableRow("Phone", this.LABPHONE);
							}
							if (this.HOURS != "") {
								markerhtml += tableRow("Hours", this.HOURS);
							}
							if (this.SPECIALNEEDS == "S") {
								markerhtml += '<tr><th>&nbsp;</th><td><img src="/campusmaps/images/International_Symbol_Of_Access_Icon.png" width="30" height="30" alt="International Symbol of Access" /> Accomodates Special Needs</td></tr>';
							}
							markerhtml += "</tbody></table>";

							detailTab = new MaxContentTab('Details', markerhtml);
							tabs.push(detailTab);
							
							// HTML for usage information tab; graphic from Labstats
							if (this.LABSTATSID != "") {
								labsWithStats.push(this.LABSTATSID);
								lablinkid = 'id="lablink' + this.LABSTATSID + '" ';
								labliid = ' id="labli' + this.LABSTATSID + '"';
								labspanid = ' id="labspan' + this.LABSTATSID + '"';
								usagehtml += '<p>' + this.LOCATION + '</p>';
								usagehtml += '<table><thead><th>Status</th><th>Seats</th><tbody>';
								usagehtml += '<tr><td class="count">Available</td><td class="count" id="available' + this.LABSTATSID + '"></td></tr>'
								usagehtml += '<tr><td class="count">In Use</td><td class="count" id="inuse' + this.LABSTATSID + '"></td></tr>'
								usagehtml += '</tbody></table>';
								usagehtml +='<div class="labstats" id="' + this.LABSTATSID + '"><img id="labstatsimage' +  this.LABSTATSID + '" width="300" height="150" alt="Graph of Current Lab Usage" /></div>';
								usageTab = new MaxContentTab('Availability', usagehtml);
								tabs.push(usageTab);
							}

							// Add a listener for the click event on the marker itself
							GEvent.addListener(marker, "click", function() {
								marker.openMaxContentTabsHtml(map, regularInfo, summaryInfo, tabs, { maxTitle: 'Detailed Information'} );																		
							});
							
							// Add our current marker to a list of all markers
							labMarkers.push(marker);
							
							// Add this lab to the sidebar along with a JavaScript action
							sideBarHtml += '<li' + labliid + '><a ' + lablinkid +  ' href="javascript:myclick(' + (labMarkers.length-1) + ')">' + this.BUILDINGROOM + '<\/a><span' + labspanid + '></span></li>';
							
							// Add this marker to the map itself
							map.addOverlay(marker);
						});
				sideBarHtml += '</ul>';
				sideBarHtml += '<p id="markerinfo"></p>';

				// Set the sidebar to contain our newly generated HTML
				$('#main-sidebar').html(sideBarHtml);
				
			  });

}

// This function creates the map, adds the building layer, invokes the addition of the markers, and 
// adds the event for a lab usage tab being viewed
function ECUMap(){	
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		
		// Shape data for ECU buildings
	    geoXml = new GGeoXml("http://www.ecu.edu/campusmaps/kml/buildingpolygons.kmz");
		map.addOverlay(geoXml);
        map.setCenter(new GLatLng(35.603789, -77.364693), 15);
		
		// Load the lab data
		processMarkers();
		
		// We want the freshest data for the pie chart, so set the src using jQuery
		GEvent.addListener(map.getTabbedMaxContent(), 'selecttab', function(tab) {
			switch (tab.getLabel()) {
				case 'Availability':
					$.getScript('/scripts/campusmaps/labstatsjs.cfm', function() {												
						var lab_id = $('div.labstats').attr('id');
						var lab_available = lookup(lab_id, 'lab_available');						
						var lab_inuse     = lookup(lab_id, 'lab_inuse');
						var lab_offline   = lookup(lab_id, 'lab_offline');
						var lab_free      = lab_available + lab_offline;
						chart_url = 'http://chart.apis.google.com/chart?cht=p&chs=300x150&chl=Available|In%20Use&chco=2CEC43,EB2A2A&chd=t:' + lab_free + ',' + lab_inuse;
						$('#available' + lab_id).html(lab_free);
						$('#inuse' + lab_id).html(lab_inuse);
						$('#labstatsimage' + lab_id).attr('src', chart_url);
					});
				break;
			}
		});
     }
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
	GEvent.trigger(labMarkers[i], "click");
}
