/* handle the functions for the XPRIZE teams section */

if (typeof(XPRIZE) == "undefined") {
    XPRIZE = {};
}
XPRIZE.teams = function() {
    // private variables
    var teams_map = null;
    var mapcount = 0;
    var currentTeam = null;
    var currentVehicleId = null;	// format is TEAM_n
    var currentVehicleNum = 0;		// index in array of vehicles for a team
    var currentUnits = "standard"; 
    var currentStage = null;   // get this from where? in what format?
    var currentEvent = null;   // get this from where? in what format?
    // ever-expanding cache of team data
    var teams_data = {};
    var currentTab = null;
	var MEDIA_BASE_URL = 'teams/media/';
    var TAB_NAMES = {
        "search" : "Team Search",
        "profile" : "Team Profile",
        "media" : "Team Media",
        "telemetry" : "Telemetry Data",
        "archive" : "Archive Data"
    }
    var GADGETS_ROW1 = [
        "MPGeGadget",
        "FuelConsumptionGadget",
        "FuelCostGadget"
    ];
    var GADGETS_ROW2 = [
        "CarbonFootprintGadget",
        "GasEmissionsGadget"
    ];
    var GADGETS_ROW3 = [
        "VehicleSpeedGadget",
        "TotalDistanceGadget",
        "TimeGadget"
    ];
    var MAP_GADGET = "MapGadget";
	var ARCHIVE_GADGET_URL = "swf/GraphGadget.swf";
    var currentGadgets = ["MPGeGadget", "FuelConsumptionGadget", "FuelCostGadget", "CarbonFootprintGadget", "GasEmissionsGadget", "VehicleSpeedGadget", "TotalDistanceGadget", "TimeGadget", "MapGadget"];
    var archiveGadgets = ["MPGe", "FuelConsumption", "FuelCost", "CarbonFootprint", "GasEmissions", "VehicleSpeed", "TotalDistance"];  // start with all? or get from cookie?
    var ARCHIVE_GADGET_WIDTH = 905;
    var ARCHIVE_GADGET_HEIGHT = 230;

    var VEHICLE_MNEMONICS = {
        "primaryEnergy" : {
            "BIOD" : "Biodiesel",
            "ELEC" : "Electric",
            "HYDR" : "Hydrogen",
            "GAS" : "Gasoline",
            "DIES" : "Diesel",
            "E85" : "E85",
            "STM" : "Steam",
			"HUMN": "Human"
        },
        "design" : {
            "NEW" : "New",
            "MOD" : "Modified"
        },
        "vehicleClass" : {
            "MNSTRM" : "Mainstream",
            "ALT" : "Alternative",
			"ALTTNDM" : "Alternative Tandem"
        },
		"drivetrain" : {
			"HSV" : "Hybrid Steam Vehicle",
			"HEV" : "Hybrid Electric Vehicle",
			"BEV" : "Battery Electric Vehicle",
			"ICE" : "Internal Combustion Engine",
			"PHV" : "Parallel Hybrid Vehicle",
			"PHEV" : "Parallel Hybrid Electric Vehicle"
		}
    };
	var MAX_PHOTOS_PROFILE = 3;
	var VEHICLE_CLASS_IDS = {"MNSTRM":0, "ALT":1};
	
    var cookie_expires = new Date();
    // set the cookie expiration date to 6 months in the future
    cookie_expires.setDate(cookie_expires.getDate() + 180);

    function showWelcome() {
        // create welcome content
        var html = [];
        html.push('<div id="welcome_content">');
        html.push('<h2>Welcome!</h2>');
        html.push('<p>Registered Teams have been officially accepted into the Progressive Insurance Automotive X PRIZE competition. These competitors come from a variety of backgrounds that range from large auto manufacturers to independent backyard inventors. These are the people who have heard the call to action, and decided that they can make a difference.</p>');
        html.push('<h2>Helpful Instructions</h2>');
        html.push('<p>The main navigation bar has 3 tabs. You can see information about the competing teams and their vehicles including live telemetry data when it is available from the <b>Teams</b> tab. The <b>Social Media</b> tab provides access to the teams\' posts on their blogs, YouTube, Facebook, Flickr and Twitter. The cumulative performance statistics for the vehicles in the completed events can be found on the <b>Dashboard</b> tab. Go Explore!</p>');
        html.push('</div>');
        XPRIZE.main.showLightbox(html.join(''));
        
//        alert("document.body.clientWidth: " + document.body.clientWidth + "\ndocument.body.clientHeight: " + document.body.clientHeight + "\nwindow.innerWidth:" + window.innerWidth + "\nwindow.innerHeight:" + window.innerHeight + "\ndocument.documentElement.clientWidth:" + document.documentElement.clientWidth + "\ndocument.documentElement.clientHeight:" + document.documentElement.clientHeight);

    }
    function initTabs() {
        $("#search_tab_open select").change(function() {
            var selected = this.options[this.selectedIndex].value;
            if (selected != "all") {
                var select = this.id;
                // reset others
                $(".select_onlyone").each(function() {
                    if (this.id == select) {
                        $(".select_any").each(function() {
                            this.selectedIndex = 0;
                        });
                    }
                    else {
                        this.selectedIndex = 0;
                    }
                });
            }
            updateSearchMap(this);            
        });
        $(".tab_submit").click(function(e) {
                // close tab
                $(this).next(".clickable_open_tab").click();
                // extract the tab name
                var id = $(this).attr("id");
                var type = id.substring(0, id.indexOf("_submit"));
                // do stuff
                switch (type) {
                case "telemetry":
                    // get telemetry input
                    updateTelemetryGadgets();
                    break;
                case "archive":
                    // get archive input
                    updateArchiveGadgets();
                    break;
                }
            });
        $("input[name='media_types']").click(function() {	// note: have to use click not change event for ie
            // close tab
            $("#media_tab_open .clickable_open_tab").click();
        	// use timeout to let tabs complete their business first
        	setTimeout(displayTeamMedia, 300);
        });
        XPRIZE.tabs.init(XPRIZE.teams);
    }
    function initContent(tab_init) {
		// init the stage/event info
		XPRIZE.stages.init();
		// initialize the tab
		if (tab_init)
			$("#" + tab_init).trigger("click");
	}

    function initSearchMap() {
		$("#profile_tab").hide();
        // get script if necessary
        if (typeof XPRIZE.XMap == "undefined") {
            $.getScript("js/map.js", function() {
                createMap();
            });
        }
        else
            createMap();
    }
    function createMap() {
        if (!teams_map) {
            $("#team-search-wrapper").html('<div id="team_search_map" class="team-search-map"></div>');
		 	teams_map = new XPRIZE.XMap();
            teams_map.init("team_search_map");
            requestData();
        }
        else {
            teams_map.closeInfoWin();
            // should I open the currentTeam's info win here?
        }
    }
    function requestData() {
		// we have loaded the teamlist json file already
        receivedTeams(XPRIZE.teamlist);
    }
    function receivedTeams(teams) {
		if (!teams) return;
        for (var teamkey in teams) {
			if (teamkey == "PAXP") continue;
            // verify that mneumonics match
            for (var type in VEHICLE_MNEMONICS) {
                for (var veh=0; veh<teams[teamkey].vehicles.length; veh++) {
                    if (!VEHICLE_MNEMONICS[type].hasOwnProperty(teams[teamkey].vehicles[veh][type])) {
//                        alert (teamkey + " field " + type + " has unexpected value: " + teams[teamkey].vehicles[veh][type]);
                    }
                }
            }
            // get logo img url (and dimensions if available)
			if (!teamkey) continue;
            var logo = "";
            var logo_dims = null;
            if (teams[teamkey].logo == true)
                logo = MEDIA_BASE_URL + teamkey + "/" + teamkey + "_logo.jpg";
            else if (typeof teams[teamkey].logo == "object") {
                logo_dims = teams[teamkey].logo;
                logo = MEDIA_BASE_URL + teamkey + "/" + teamkey + "_logo.jpg";
            }
            else if (teams[teamkey].logo != false)
                logo = teams[teamkey].logo;
            // get url for photo
            var img = "";
            if (teams[teamkey].image == true)
                img = MEDIA_BASE_URL + teamkey + "/" + teamkey + "_1.jpg";
            else if (teams[teamkey].image != false)
                img = teams[teamkey].image;
            teams_map.addTeamMarker(teamkey, teams[teamkey].lat, teams[teamkey].lon, teams[teamkey].teamName, logo, logo_dims, img);
        }
        if (currentTeam)
            showTeam(currentTeam);
    }
    function showTeam(team) {
        teams_map.openInfoWindow(team);
    }
    function updateSearchMap(select) {
        // get the search selections
        var search = {};
        var getAll = true;
        $(".team_search_select").each(function() {            
            if (this.selectedIndex != 0) {
                var idx = this.id.indexOf("_select");
                var name = this.id.substring(0, idx);
                search[name] = this.options[this.selectedIndex].value;
                getAll = false;
            }
        });
        // close any info window
        teams_map.closeInfoWin();
		// remove current team
		resetTeam();
        // filter results based on selections 
        var showTeamMarkers = [];   // array of team indexes to display
        var done = false;           // flag to indicate
        for (var teamkey in XPRIZE.teamlist) {
            var team = XPRIZE.teamlist[teamkey];
            // add the key to the team object for lookup
            team["teamKey"] = teamkey;
            if (getAll) {
                showTeamMarkers.push(teamkey);
                continue;
            }
            var matched = false;
            // check each search condition for a match
            for (var name in search) {
                if (name == "teamKey" || name == "teamLocation" || name == "vehicleKey") {
                    if (teamkey == search[name])
                        matched = true;
                }
                else {
                    // check if any vehicles match this search criteria
                    var matched = false;    // reset for vehicles
                    for (var j=0; j<team.vehicles.length; j++) {
                        if (name == "energy") { // have to check primary and secondary energy sources
                            if (team.vehicles[j].primaryEnergy == search[name]) {
                                matched = true;
                            }
                            else if (team.vehicles[j].secondaryEnergy) {
                                for (var k=0; k<team.vehicles[j].secondaryEnergy.length; k++) {
                                    if (team.vehicles[j].secondaryEnergy[k] == search[name]) {
                                        matched = true;
                                        break;  
                                    }
                                }
                            }
                            if (matched) break; 
                        }
                        else if (team.vehicles[j].hasOwnProperty(name) && team.vehicles[j][name] == search[name]) {
                            matched = true;
                            break;
                        }
                    }
                    // don't bother looking at any more search criteria if this one didn't match
                    if (!matched) break;
                }
            }
            if (matched) {
                // save this team if it is a match
                showTeamMarkers.push(teamkey);
                // stop searching if this is one of the exclusive searches
                if ($(select).hasClass("select_onlyone")) {
					currentTeam = teamkey;
					break;
				}
            }
        }

        teams_map.clearMarkers();
        // show marker(s) on the map
        for (var team_i=0; team_i<showTeamMarkers.length; team_i++) {
            var teamkey = showTeamMarkers[team_i];
            teams_map.showTeamMarker(teamkey, (showTeamMarkers.length == 1));
        }
		updateBreadcrumbs();
    }
    function unloadMap() {
        teams_map.destroy();
        teams_map = null;
        $("#team-search-wrapper").html("");
    }
    function initTelemetryData() {
		$("#profile_tab").show();
        // first clear the gadgets
        $("#telemetry_gadgets").html("");
        // use pace car if no team selected
        if (!currentTeam) {
            currentTeam = getRandomTeam();
        }
		// make sure we have the teams_events json file before 
		if (!XPRIZE.teams_events) {
			$.getJSON("json/teams_events.json", function(json_data) {
				XPRIZE.teams_events = json_data;
        		updateTelemetryGadgets();
			});
		}
		else {
        	updateTelemetryGadgets();
		}
    }
    function updateTelemetryGadgets() {
        // get the selected checkboxes
        var gadgets = [];
        $(".team_telemetry_check:checked").each(function() {
            gadgets.push(this.value);
        });
        currentGadgets = gadgets;
		if (!XPRIZE.stages.ready()) {
			XPRIZE.stages.init(function() {
        		displayTelemetryData(XPRIZE.teamlist[currentTeam]);
			});
		}
		else {
        	displayTelemetryData(XPRIZE.teamlist[currentTeam]);
		}        
    }
    function displayTelemetryData(data) {
		var noVehicle = false;	// flag when vehicle is not specifically chosen
		if (!currentVehicleId) {
			// if a currentVehicle is not defined, use the first one
			currentVehicleId = currentTeam + "_1";
			currentVehicleNum = 0;
			noVehicle = true;
		}
		// create gadgets display
		var html = ['<div id="megagadget_wrapper"><div id="megagadget"></div></div>'];
        $("#telemetry_gadgets").html(html.join(''));
		// create header
		var now = new Date();
		currentStage = XPRIZE.stages.getCurrentStage(now);
		// check if we need to display a message and get event display for header
		var displayEvent = processVehicleStatus(noVehicle);
        buildTelemetryHeader("telemetry_header", currentTeam, data.teamName, data.vehicles, displayEvent);
        // add the gadgets (use timeout because adding gadgets interrupts opening tab)
        setTimeout(addGadgets, 300);
    }
	function processVehicleStatus(tryAllVehicles) {
		var now = new Date();
		var displayEventStr = "";
		// need to check current or most recent stage for success or failure
		var stage = currentStage || XPRIZE.stages.lastCompletedStage(now);
		//console.log("team = " + currentTeam + ", vehicle index = " + vehicleIndex + ", stage = " + stage);
		// check all vehicles for this team if the flag is set to see if there are any still in competition
		var team_out = false;
		if (currentTeam != "PAXP" && XPRIZE.teams_events.teamsStatus[currentTeam].vehicles[currentVehicleNum][stage] == "FL") {
			team_out = true;
			if (tryAllVehicles && XPRIZE.teams_events.teamsStatus[currentTeam].vehicles.length > 1) {
				for (i=0; i<XPRIZE.teams_events.teamsStatus[currentTeam].vehicles.length; i++) {
					if  (XPRIZE.teams_events.teamsStatus[currentTeam].vehicles[i][stage] != "FL") {
						team_out = false;
						currentVehicleNum = i;
						currentVehicleId = currentTeam + "_" + (i+1);
						break;
					}
				}
			}
		}
/*
		if (team_out) {
			// team is out
			displayEventStr = "Out of Competition";
			var html = "<h1>NOTICE</h1>This vehicle is no longer in the competition, so there should not be any telemetry data being transmitted at this time. You may view this team's archived telemetry data from previous events on the <b>Archive Data</b> tab.";
			XPRIZE.main.showLightbox(html, 300, 225);
		}
		else {
			// make web service query to see if there is a current event for this vehicle
			try {
				var telemetryId = XPRIZE.teamlist[currentTeam].vehicles[currentVehicleNum].telemetryID;
				var url = "vts?v=" + telemetryId;
				var onSuccess = function(data) {
					// get event name
					currentEvent = data.length >= 1 ? data[0] : "Unknown";
					// update the status message
					$("#telemetry_event").html("Active Event: <b>" + currentEvent + "</b>");
				};
				var onFailure = function(data) {
					// no data flowing
					currentEvent = null;
					if (telemetryId == "99") return;
					// get next event
					var nextEvent = XPRIZE.stages.getEventName(XPRIZE.stages.getNextEvent(now));
					if (nextEvent)
						displayEventStr = "Pending Event: <b>" + nextEvent + "</b>";
					else
						displayEventStr = "No Pending Event";
					// update the status message
					$("#telemetry_event").html(displayEventStr);
					showNoDataMessage();
				};
				XPRIZE.main.doQuery(url, onSuccess, onFailure);
			}
			catch (err) {
				showNoDataMessage();
			}
		}
*/
		return displayEventStr;
	}
	function showNoDataMessage() {
		// check web-service for special message
			// use datetime for unique url so IE doesn't cache response?
			var url = "qam?t=T&z=" + (new Date()).getTime();
			var onSuccess = function(data) {
				var html = "<h1>NOTICE</h1>" + (data.length >=1  && data[0] != "" ? data[0] : "Data not available, reason unknown");
				XPRIZE.main.showLightbox(html, 300, 225);
			}
			var onFailure = function(data) {
				XPRIZE.main.showLightbox("<h1>NOTICE</h1>Data not available, reason unknown", 300, 225);
			}
			XPRIZE.main.doQuery(url, onSuccess, onFailure);
	}
    function addGadgets() {
		var vehicle_data = XPRIZE.teamlist[currentTeam].vehicles[currentVehicleNum];
		// get the flashvars values for the current vehicle
		var telemetryId = vehicle_data.telemetryID;
		var vehicleClassId = VEHICLE_CLASS_IDS[vehicle_data.vehicleClass];
        var flashvars = {VehicleId: telemetryId, GadgetSystem: currentUnits, VehicleType: vehicleClassId};
        var cnt3 = 0;
        var hasMap = false;
		// figure out size of megagadget
		var row1, row2, row3 = false;
		for (var i=0; i<currentGadgets.length; i++) {
			if (GADGETS_ROW1.indexOf(currentGadgets[i]) != -1)
				row1 = true;
			else if (GADGETS_ROW2.indexOf(currentGadgets[i]) != -1)
				row2 = true;
			else if (GADGETS_ROW3.indexOf(currentGadgets[i]) != -1)
				row3 = true;
			else if (currentGadgets[i] == "MapGadget")
				hasMap = true;
		}
		var height = (row1 ? 220 : 0) + (row2 ? 290 : 0) + (hasMap ? 575 : (row3 ? 550 : 0));


		flashvars.IncludedGadgets = currentGadgets.join(',');
		addSWF("megagadget", "swf/MegaGadget.swf", 974, 928, flashvars, true);
    }
    function addSWF(id, src, width, height, flashvars, transparent_flag) {
        var gid = id + "_gadget";
        // make the gadget visible at the same time
        $("#" + id).css("display", "block");
        var attr = {
            name:gid,
            id:gid
        };
        var params = {
            allowscriptaccess:"always",
            bgcolor:"#3b3b3b"
        };
        if (transparent_flag)
            params.wmode = "transparent";

        swfobject.embedSWF(src, id, width, height, "9", "swf/expressInstall.swf", flashvars, params, attr);
    }
	function buildTelemetryHeader(headerid, teamkey, teamname, vehicles, eventStatus) {
        var html = [];
        html.push('<span class="telemetry_title telemetry_header_item">');
        html.push(      teamname);
        html.push(  '</span>');
        if (vehicles.length > 1) {
            html.push(      '<select class="telemetry_vehicle telemetry_header_item">');
            for (var i=0; i<vehicles.length; i++) {
                var vid = teamkey + "_" + (i+1);
       	        html.push(          '<option value="' + vid + '" ');
                if (currentVehicleId == vid)
                    html.push(          'selected ');
                html.push(              '>' + vehicles[i].vehicleName + '</option>');
            }
            html.push(      '</select>');
        }
        else {
            html.push('<span class="telemetry_title telemetry_header_item">');
            html.push(      vehicles[0].vehicleName);
            html.push(  '</span>');
        }
        if (eventStatus != null) {   // event info for telemetry data
            html.push(    '<span id="telemetry_event" class="telemetry_header_item" alt="Alert">');
            html.push(      eventStatus);
            html.push(    '</span>');
        }
        else {  // select list of events for archive data
            html.push(      '<select id="choose_event" class="telemetry_header_item">');
            html.push(      '</select>');            
        }
        html.push(  '<div class="telemetry_header_item" style="margin-right:0px"><a href="" class="measure_buttons standard_button " id="standard"></a><a href="" class="measure_buttons metric_button " id="metric"></a></div>');
        $("#" + headerid).html(html.join(''));

		// set the dynamic contents of the stage and event drop-downs for archive data
		if (eventStatus == null) {
			$("#choose_event").html(getArchiveEvents());
		}
        // add function to vehicle select options
        $(".telemetry_vehicle").change(function() {
            currentVehicleId = currentTeam + "_" + (this.selectedIndex + 1);
			currentVehicleNum = this.selectedIndex;
            //console.log(currentVehicle);
            // reload the gadgets
            reloadTab();
        });
		// add function to stage select dropdown
		$("#choose_event").change(function() {
			var selected = this.options[this.selectedIndex].value;
			if (selected != 0) {
				currentEvent = selected;
				reloadTab();
			}
		});
        // get the measurement units from cookie
        if (!currentUnits) {
            currentUnits = $.cookies.get("xprize_telemetry_units");
            if (!currentUnits) currentUnits = "standard";
        }
        // use class to highlight selected button because telemetry and archive use the same buttons and the right one might not be active
        $("." + currentUnits + "_button").addClass("selected");
        // add function to change measurement units
        $(".measure_buttons").click(function() {
            var clicked = this.id;
            if (clicked != currentUnits) {
                $(this).addClass("selected");
                $("." + currentUnits + "_button").removeClass("selected");
                currentUnits = clicked;
                // save to cookie
                var opts = {
                    expiresAt: cookie_expires
                };
                $.cookies.set("xprize_telemetry_units", clicked, opts);
                // tell the gadgets
                var gadgets = [];
                if ($(this).parents("#telemetry_header").length >= 1)
                    gadgets = ["megagadget"];
                else
                    gadgets = archiveGadgets;
                for (var i=0; i<gadgets.length; i++) {
                    var id = gadgets[i] + "_gadget";
                    //var gadget = getFlashMovie(id);
                    var gadget = document.getElementById(id);
                    if (gadget) {
                        if (gadget.switchGadgetSystem) {
                        try {
                            gadget.switchGadgetSystem();
                        }
                        catch (e) {
                            alert("Error communicating with gadget(s): " +e.description)
                        }
                    }}
                }
            }
            return false;
        });
    }
    function getFlashMovie(movieName) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? window[movieName] : document[movieName];
    }
    function getArchiveEvents() {
		var html = [];
		current_event_ok = false;
		var telemID = XPRIZE.teamlist[currentTeam].vehicles[currentVehicleNum].telemetryID;
		if (!XPRIZE.eventData.hasOwnProperty(telemID)) return "";
		// create the option html code for each event this vehicle has data for
		for (var i=0; i<XPRIZE.eventData[telemID].length; i++) {
				var eventID = XPRIZE.eventData[telemID][i];
				// identify if the currentEvent is in the list
				if (eventID == currentEvent) 
					current_event_ok = true;
				// use unshift to add to the head of the array to get the later events at the top
				html.unshift('<option value="' + eventID + '"' + (eventID == currentEvent ? ' selected' : '') +	'>' + XPRIZE.stages.getEventName(eventID) + '</option>');
		}
		if (html.length == 0) 
			html.push('<option value=0>No Events Completed</option>');
		else if (!current_event_ok) {
			// if the currentEvent was not in the list of events for this vehicle, set the currentEvent to the most recently completed one for this vehicle
			if (XPRIZE.eventData[telemID].length > 0)
				currentEvent = XPRIZE.eventData[telemID][XPRIZE.eventData[telemID].length-1];
			// if we want to see nothing instead of empty graph gadgets when vehicle has no event data, add "else currentEvent = null"
		}
		return html.join('');
    }
    function initArchiveData() {
		$("#profile_tab").show();
        // first clear the gadgets
        $("#archive_gadgets").html("");
        // use random team if no team selected
        currentTeam = currentTeam || getRandomTeam();

		// load the teams_events data so we can see what events are available
		if (!XPRIZE.teams_events) {
			$.getJSON("json/teams_events.json", function(json_data) {
				XPRIZE.teams_events = json_data;
        		initArchiveEvent();
			});
		}
		else {
        	initArchiveEvent();
		}
	}
	function initArchiveEvent() {
		var now = new Date();
		currentStage = XPRIZE.stages.getCurrentStage(now) || XPRIZE.stages.lastCompletedStage(now);
		// use first vehicle still in comp if none selected
        if (!currentVehicleId) {
			if (currentTeam == "PAXP") {
				currentVehicleId = "PAXP_1";
				currentVehicleNum = 0;
			}
			else {
        	currentVehicleNum = 0;			
			for (var i=0; i<XPRIZE.teams_events.teamsStatus[currentTeam].vehicles.length; i++) {
				if (XPRIZE.teams_events.teamsStatus[currentTeam].vehicles[i][currentStage] != "FL") {
        			currentVehicleNum = i;
					break;
				}
			}
			currentVehicleId = currentTeam + "_" + (i+1);
			}
		}
/* I don't seem to need this anymore: taken care of in getArchiveEvents
		// if there is no current event selected or this team has not completed the current event, set the current event to the most recently completed one
//		var vehicle_events = XPRIZE.teams_events.teamsStatus[currentTeam].vehicles[currentVehicleNum].eventsCompleted;
		var vehicle_events = XPRIZE.eventData[XPRIZE.teamlist[currentTeam].vehicles[currentVehicleNum].telemetryID];
		if (!currentEvent || vehicle_events.indexOf(currentEvent) == -1) {
			if (vehicle_events.length > 0 ) {
				currentEvent = vehicle_events[vehicle_events.length-1];
				// check if this is a display event, if not can return null because only Shakedown events are not displayable?
				if (XPRIZE.teams_events.stages[XPRIZE.stages.getStageName(currentEvent)].display_events.indexOf(currentEvent) == -1)
					currentEvent = null;
			}
			else
				currentEvent = null;
		}
*/
		// create the header
		if (!XPRIZE.stages.ready()) {
			XPRIZE.stages.init(function() {
        		buildTelemetryHeader("archive_header", currentTeam, XPRIZE.teamlist[currentTeam].teamName, XPRIZE.teamlist[currentTeam].vehicles, null);
       	updateArchiveGadgets();
			});
		}
		else {
        	buildTelemetryHeader("archive_header", currentTeam, XPRIZE.teamlist[currentTeam].teamName, XPRIZE.teamlist[currentTeam].vehicles, null);
       	updateArchiveGadgets();
		}        
        
		// create the gadgets
    }
    function updateArchiveGadgets() {
        // get the selected checkboxes
        var a_gadgets = [];
        $(".team_archive_check:checked").each(function() {
            a_gadgets.push(this.value);
        });
        archiveGadgets = a_gadgets;
        displayArchiveData();
    }
    function displayArchiveData() {
		// if there is no event available, can't show anything
		if (currentEvent == null) return;
        var html = [];
//        for (var gadget in ARCHIVE_GADGETS) {
        for (var i=0; i<archiveGadgets.length; i++) {
            var gadget = archiveGadgets[i];
            html.push('<div class="archive_gadget_wrapper"><div id="' + gadget + '" class="archive_gadget"></div></div>');
        }
//        html.push('<div style="clear:both;"></div></div>');
        $("#archive_gadgets").html(html.join(''));
        // add the gadgets (use timeout because adding gadgets competes with opening tab)
        setTimeout(addArchiveGadgets, 300);
    }
    function addArchiveGadgets() {
		var vehicle_data = XPRIZE.teamlist[currentTeam].vehicles[currentVehicleNum];
		// get the flashvars values for the current vehicle
		var telemetryId = vehicle_data.telemetryID;
		var vehicleClassId = VEHICLE_CLASS_IDS[vehicle_data.vehicleClass];
        var flashvars = {VehicleId: telemetryId, GadgetSystem: currentUnits, VehicleType:vehicleClassId, StageId:currentEvent};
        for (var i=0; i<archiveGadgets.length; i++) {
            var gadget = archiveGadgets[i];
//			flashvars.GraphType = ARCHIVE_GADGET_TYPES[gadget];
			flashvars.GraphType = gadget;
            addSWF(gadget, ARCHIVE_GADGET_URL, ARCHIVE_GADGET_WIDTH, ARCHIVE_GADGET_HEIGHT, flashvars, (i==0));
            $(".archive_gadget_wrapper:nth-child("+(i+1)+")").show();
        }
    }
	function unloadSWFs() {
		var mega_gadget = document.getElementById("megagadget_gadget");
		if (mega_gadget) {
			swfobject.removeSWF("megagadget_gadget");
		}
        for (var i=0; i<archiveGadgets.length; i++) {
            var gadget = document.getElementById(archiveGadgets[i] + "_gadget");
			if (gadget) {
				swfobject.removeSWF(archiveGadgets[i] + "_gadget");
			}
		}
	}
	function linkToTeamProfile() {
		window.open(XPRIZE.teamlist[currentTeam].profileUrl);
	}
    function reloadTab() {
		unloadSWFs();
        switch (currentTab) {
        case "search":
            initSearchMap();
            break;
        case "profile":
            getTeamProfile();
            break;
//        case "media":
//            initTeamMedia();
//            break;
        case "telemetry":
            initTelemetryData();
            break;
        case "archive":
            initArchiveData();
            break;
        }
    }
    function updateBreadcrumbs() {
        var crumbs = [];
        if (currentTab == "search") {
            crumbs.push(TAB_NAMES[currentTab]);
            if (currentTeam)
                crumbs.push(XPRIZE.teamlist[currentTeam].teamName);
        }
        else {
            if (currentTeam) 
                crumbs.push(XPRIZE.teamlist[currentTeam].teamName);
            crumbs.push(TAB_NAMES[currentTab]);
        }
        XPRIZE.breadcrumbs.displayCrumbs(crumbs);
    }
    function getCurrentContextUrl() {
		if (!currentTab) return null;
        var url = window.location.href;
        url = url.substring(0, url.indexOf(".html")+5);
        url += "?p=" + currentTab;
        if (currentTeam) {
            url += "&tk=" + currentTeam;
            if (currentVehicleId) 
                url += "&v=" + currentVehicleId;
        }
        return url;
    }
	function getRandomTeam() {
    	// constant
		var NUM_TEAMS = 26;
		
		var rnd = Math.floor(Math.random() * NUM_TEAMS);
		var count = 0;
		for (var id in XPRIZE.teamlist) {
			if (count >= rnd && id != "APTR") break;
			count++;
		}
		return id;
	}
	function resetTeam() {
		currentTeam = null;
		currentVehicleId = null;
		currentVehicleNum = 0;
	}
	function getTeamFromTelemetryID(telem_id) {
		for (var teamkey in XPRIZE.teamlist) {
			for (var i=0; i<XPRIZE.teamlist[teamkey].vehicles.length; i++) {
				if (telem_id == XPRIZE.teamlist[teamkey].vehicles[i].telemetryID) {
					currentTeam = teamkey;
					currentVehicleId = teamkey + "_" + (i+1);
					currentVehicleNum = i;
					return;
				}
			}
		}
		// didn't find a match, assume it is the pace car
		currentTeam = "PAXP";
		currentVehicleId = "PAXP_1";
		currentVehicleNum = 0;
		// set the vehicle's telemetry id to match
		XPRIZE.teamlist["PAXP"].vehicles[0].telemetryID = telem_id;
	}
    return {
        init: function(params) {
            
            // check visited cookie
            // if first time show Welcome
            if (!$.cookies.get("xprize_welcome")) {
                showWelcome();
                var opts = {
                    expiresAt: cookie_expires
                };
                $.cookies.set("xprize_welcome", "true", opts);
            }

            teams_map = null;
            initTabs();
			var telem_id = null;
            // default to team search?
            var tab = "search";
			var go_tab = true;
            // check for url parameters to set page and contents
            if (params) {
                if (params["tk"]) {
                    currentTeam = params["tk"].toUpperCase();
                }
                if (params["v"]) {
                    currentVehicleId = params["v"];
					// extract the vehicle index from the current vehicle key
					var idx = currentVehicleId.indexOf('_');
					if (idx != -1) {
						currentTeam = currentVehicleId.substring(0, idx);
						currentVehicleNum = parseInt(currentVehicleId.substring(idx+1)) - 1;
					}
				}
				if (params["tid"]) {
					telem_id = params["tid"];
				}
                if (params["p"]) {
					go_tab = false;
					if (params["p"] == "trm")
						$("#terms_conds").click();
					else if (params["p"] == "prv")
						$("#privacy_policy").click();
					else if (params["p"] == "cnt")
						$("#contact_us").click();
					else {
	                    tab = params["p"];
						go_tab = true;
					}
				}
            }
            tab += "_tab";
			// load the teamlist json file first if necessary because breadcrumbs needs it
			if (!XPRIZE.teamlist) {
				$.getJSON("json/teamlist.json", function(data) {
					// launch the selected tab when data returns							 
					if (data && typeof data == "object") {
						XPRIZE.teamlist = data;
						if (telem_id) getTeamFromTelemetryID(telem_id)
						initContent(go_tab ? tab : null);
					}
					else alert ("Sorry, no team data is available. Could not open teamlist file.");
				});
			}
			else {
				if (telem_id) getTeamFromTelemetryID(telem_id)
				// launch the selected tab
				initContent(go_tab ? tab : null);
			}
        },
        setContent: function(type) {
            if (!TAB_NAMES.hasOwnProperty(type)) {
                alert("Whoops, " + type + " doesn't exist!");
                return;
            }
			// profile tab is just a link to xprize site now
			if (type == "profile") {
				// reset the previous tab
				XPRIZE.tabs.setSelected("#" + currentTab + "_tab");
                linkToTeamProfile();
				return;
			}
            // if the tab is already selected, do nothing
            if (type == currentTab) return;
            // otherwise hide the current tab contents and get the new one
			unloadSWFs();
            $(".content-wrapper").hide();
            currentTab = type;

			// hide telemetry dropdown tab for aptera
			if (currentTeam == "APTR")
				$('#telemetry_tab_open').addClass('tab_no_open');
			else 
				$('#telemetry_tab_open').removeClass('tab_no_open');

			switch (type) {
            case "search":
                initSearchMap();
                $("#team-search-wrapper").show();
                break;
            case "telemetry":
                initTelemetryData();
                $("#team-telemetry-wrapper").show();
                break;
            case "archive":
                initArchiveData();
                $("#team-archive-wrapper").show();
                break;
            }
            updateBreadcrumbs();
        },
        loadTeamData: function(team_data) {
            //console.log("loadTeamData function");
            teams_data[currentTeam] = team_data;
        },
        goToTeamProfile: function(team_key) {
			if (team_key)
            	currentTeam = team_key;
            $("#telemetry_tab").click();
        },
        goToTeam: function(team_key) {
            currentTeam = team_key;
            currentVehicleId = null;
            currentVehicleNum = 0;
            // unload the map if it exists
//            if (teams_map) unloadMap();
            if (!currentTab || currentTab == "search")
                $("#telemetry_tab").click();
            else
                reloadTab();
            updateBreadcrumbs();
        },
        goToView: function(breadcrumb) {
            //console.log("Go to " + breadcrumb);
            var teamname = currentTeam ? XPRIZE.teamlist[currentTeam].teamName : "";
            if (breadcrumb == teamname) {
                $("#search_tab").click();
                // open the info window for this team
                teams_map.openInfoWindow(currentTeam);
            }
            else {
                switch(breadcrumb) {
                    case "Teams":
					case "Team Search":
                        resetTeam();
                        $("#search_tab").click();
                        break;
                    case "Team Profile":
                        $("#profile_tab").click();
                        break;
//                    case "Team Media":
//                        $("#media_tab").click();
//                        break;
                    case "Telemetry Data":
                        $("#telemetry_tab").click();
                        break;
                    case "Archive Data":
                        $("#archive_tab").click();
                        break;
                }
            }
        },
        setCurrentTeam: function(newTeam) {
			if (currentTeam == newTeam) return;
			resetTeam();
            currentTeam = newTeam;
            updateBreadcrumbs();
        },
        getCurrentTeam: function() {
			return currentTeam;
		},
        closeAll: function() {
            $(".clickable_open_tab").click();
            XPRIZE.tabs.reset();
            currentTab = null;
        },
        siteHelp: function() {
            var content = "<h4>Team Page</h4><p>The Team page contains information about the competing teams and vehicles.</p><p>The Team Tracking bar provides quick links to the Telemetry Data of up to 5 of your favorite teams. Select the teams you want to track by clicking on their markers on the map and selecting the 'Track This Team' from the info bubble.</p><p>In the content section there are 3 pulldown tabs you can click for access to the following sections:<ol><li>Team Search - See all the teams home locations on the map. Click a marker for a window to identify the team and provide links to go to the team's profile page or add that team to the Teams you are Tracking for quick access later. You can also filter the map contents using the Team Search dropdown tab.</li><li>Telemetry Data - When the vehicle is competing in an event you can watch gadgets display live telemetry data. The dropdown tab allows you to choose which gadgets you want to monitor.</li><li>Archive Data - Once an event is complete, see the aggregate data to evaluate the performance of each vehicle.</li><li>Team Profile - This tab is only available when you are viewing a particular team\'s data. It links to www.progressiveautoxprize.org where you can read the team's biography and information about their vehicle(s)</li></ol></p><p>Terms you will see on this page:</p><b>Telemetry</b> - a technology that allows remote measurement and reporting of information, in this case vehicle movement and consumption statistics.<br />";
            XPRIZE.main.showLightbox(content, 600,420);
        },
        unload: function() {
            if (teams_map) unloadMap();
        },
        linkToThis: function() {
            return getCurrentContextUrl();
        }
    }
}();

