// Global Class for UML

var UML = {
    version: '1.1.0',
    TopPositionsRows: 50,
    MyAthletesRows: 20,
    ReturnNavigationID: 0,
    ReturnNavigationShow: false,
    BibNo: -1,
    PersonID: -1,
    MaxHour: 30,
    StartStationID: 0,
    FinishStationID: 0,
    NAV_OVERALL_LEADERS: 1,
    NAV_MEN_LEADERS: 2,
    NAV_WOMEN_LEADERS: 3,
    NAV_STATION: 4,
    DROPS: 6,
    NAV_STATIONDETAIL: 7,
    NAV_MYFAVORITES: 8,
    NAV_100K: 10,
    STATUS_FINISHED: 'Finished',
    STATUS_DROPPED: 'Dropped',
    STATUS_ONTRAIL: 'On Course',
    STATUS_DNS: 'DNS',
    STATUS_ENTERED: 'Entered',
    STATUS_100K: '100K',
    UpdateRaceClock: function(t)
    {
	// Shows elapsed time in HH:MM
	// Assumes time as a string in HH:MM:SS format
	var h = parseFloat(t.substring(0,t.indexOf(':')));
	var img_src0 = "0";
	var img_src1 = "0";
	var img_src3 = "0";
	var img_src4 = "0";
	var img_src5 = "0";
	var img_src6 = "0";
	if (h >= this.MaxHour)
	{
		var max_hour_str = this.MaxHour + "";
	    img_src0 = max_hour_str.substr(0,1);
	    img_src1 = max_hour_str.substr(1,1);
	}
	else if ((h >=0) && (h < UML.MaxHour))
	{
	    img_src0 = t.substring(0,1);
	    img_src1 = t.substring(1,2);
	    img_src3 = t.substring(3,4);
	    img_src4 = t.substring(4,5);
	    img_src5 = t.substring(6,7);
	    img_src6 = t.substring(7,8);
	}
	$('raceclock0').src = UMLStaticImgURL + "/images/dg" + img_src0 + ".gif";
	$('raceclock1').src = UMLStaticImgURL + "/images/dg" + img_src1 + ".gif";
	$('raceclock3').src = UMLStaticImgURL + "/images/dg" + img_src3 + ".gif";
	$('raceclock4').src = UMLStaticImgURL + "/images/dg" + img_src4 + ".gif";
	$('raceclock5').src = UMLStaticImgURL + "/images/dg" + img_src5 + ".gif";
	$('raceclock6').src = UMLStaticImgURL + "/images/dg" + img_src6 + ".gif";


    },

    CheckBibNo: function(bibno)
    {
	// returns non null string of athlete name if found.
	var s = AL[bibno];

	if (s == undefined)
	    return null;
	else
	    return s;
    },

	ShowAtheleteFromSearch: function(s)
	{
		UML.ShowRaceGroup(0);
		UML.findAthlete(s);
	},

    GetAthleteDisplayInfo: function(bibno)
    {
	var DisplayInfo = this.CheckBibNo(bibno);
	// Get athele name from lookup array
	if (DisplayInfo != null)
	    return bibno + ' ' + AL[bibno];
	else
	    return null;
    },

    GetBibNoFromString: function(s)
    {
	if (s.indexOf(' ') != -1)
	{
	    return s.substring(0, s.indexOf(" ", 1));
	}
	return s;
    },

    GetAthleteNameFromString: function(s)
    {
	if (s.indexOf(' ') != -1)
	{
	    return s.substring(s.indexOf(' ',1));
	}
	return 'UNKNOWN';
    },

    OnSelectAthlete: function(txt, li)
    {
	UML.ShowRaceGroup(0);
	UML.findAthlete(txt.value);
    },
    
    findAthlete: function(s)
    {
	var bibno = this.GetBibNoFromString(s);
	if (bibno == '')
	{
	    alert('Athlete bib number or name must be entered.');
	    return;
	}
	this.BibNo = bibno;
	this.showAthleteSplits();
	this.showAthleteByBibNo(bibno);
    },

    findMyAthlete: function(rowid)
    {
	this.ReturnNavigationID = 0;
	this.ReturnNavigationShow = false;
	var rowname = "myathlete_bib_" + rowid;
	this.findAthlete($(rowname).innerHTML);
    },

    populateSearchName: function(bibno)
    {
	var DisplayInfo =  this.GetAthleteDisplayInfo(bibno);
	if (DisplayInfo != null)
	{
	    $('runners').value = DisplayInfo;
	    return true;
	}
	else
	{
	    alert('The bib number is not valid for this event.');
	    return false;
	}
    },

    getPersonID: function(bibno)
    {
    	return PID[bibno];
    },

    showAthleteByBibNo: function(bibno)
    {
	
		if (this.ReturnNavigationID == this.NAV_STATION) this.ReturnNavigationID = this.NAV_STATIONDETAIL;
		this.ReturnNavigationShow = true;
		this.BibNo = bibno;
		this.PersonID = this.getPersonID(bibno);
		// Check if in cache, then show while checking updates
		//if (UMLCache.exists(UML.CacheObjID(reqtype, params1)) this.Show		
		this.showAthleteSplits();
		UMLAjax.ajaxRequest(UMLAjax.ATHLETE_DATA, [this.PersonID]);

    },

    showAthlete: function(rowno)
    {
		var bibid = 'bibno_' + rowno;
		var bibno = $(bibid).innerHTML;
		if (bibno != '')
		{
			this.ReturnNavigationShow = true;
			this.showAthleteByBibNo(bibno);
		}
    },

    showDrops: function(content)
    {
		this.ShowDropsTab();
		$('dropcontent').innerHTML = content;
    },

    showStationInfoDetail: function(content)
    {
		// put in breadcrumb for return
		// change title text?
		this.ShowStationDetailTab();
		$('stationdetail_content').innerHTML = content;
		$('stationdetail_tab').show();
    },

    clearAthleteInfo: function()
    {
		//$('athletephoto').src="images/photomissing.jpg";
		//$('athlete_bib_no').innerHTML="--";
		$('athlete_full_name').innerHTML="--";
		$('athlete_starttime').innerHTML="--";
		$('athlete_gender').innerHTML="--";
		$('athlete_age').innerHTML="--";
		$('athlete_hometown').innerHTML="--";
		$('athlete_status_current').innerHTML="--";
		$('athlete_status_place').innerHTML="--";
		$('athlete_status_station').innerHTML="--";
		$('athlete_status_distance').innerHTML="--";
		$('athlete_status_timein').innerHTML="--";
		$('athlete_status_est_timein').innerHTML="--:-- to --:--";
		$('athlete_status_next_station').innerHTML="N/A";
    },

	showAthleteSplits: function()
	{
		$('runner_splits').show();
		if (UMLShowHistory)	$('runner_history').hide();
		$('runner_videos').hide();
	},

	showAthleteHistory: function(id)
	{
		if (UMLShowHistory)
		{
			$('runner_splits').hide();
			$('runner_videos').hide();
			$('runner_history').show();
		}
	},
	
	showAthleteVideoClips: function(id)
	{
		$('runner_splits').hide();
		$('runner_history').hide();		
		$('runner_videos').show();
	},

    showAthleteInfo: function(athlete, racestatus)
    {

		this.clearAthleteInfo();
		this.ShowAthleteTab();
		
		this.ContentTitleDescription(athlete.name + ' - ' + athlete.bibno + ' (' + athlete.status + ')');

		// Clear search criteria
		//$('runners').value='';

		// Athlete Info update
		if (UMLUseAthleteImg) 
		{
			if ((athlete.img.substr(0,6) != 'images') && (athlete.img.substr(0,4) != 'http'))
			{
				athlete.img = 'http://ultrasignup.com/images/ImgHandler.ashx?id=' + athlete.img; 
			}
			$('athletephoto').src=athlete.img;
		}
		//$('athlete_bib_no').innerHTML=athlete.bibno;
		$('athlete_full_name').innerHTML=(athlete.name + ' - ' + athlete.bibno);
		$('athlete_starttime').innerHTML=athlete.starttime;
		$('athlete_gender').innerHTML=athlete.gender;
		$('athlete_age').innerHTML=athlete.age;
		if (athlete.country == null) athlete.country = '';
		$('athlete_hometown').innerHTML=athlete.city + ', ' + athlete.state + ' ' + athlete.country;
		$('athlete_finishes').innerHTML=athlete.finishes;
	    $('athlete_status_current').innerHTML=athlete.status;
	    //this.updateStatusImg(athlete.status);
	    $('athlete_status_place').innerHTML=athlete.position;
	    $('athlete_status_station').innerHTML=athlete.station;
	    $('athlete_status_distance').innerHTML=athlete.distance;
	    $('athlete_status_elapsedtime').innerHTML=athlete.elapsedtime;
	    $('athlete_status_timein').innerHTML=athlete.timein;
	    $('athlete_status_timeout').innerHTML=athlete.timeout;
	    $('athlete_status_next_station').innerHTML=athlete.nextstation;
		$('athlete_status_est_timein').innerHTML=athlete.timeinest1 + ' to ' + athlete.timeinest2;
		
		// Splits update
		for (var i =0; i < athlete.splits.length; i++)
		{
		    id = "timein_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].TimeIn;      
		    id = "timeout_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].TimeOut;      
		    id = "elapsed_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].Elapsed;
		    id = "position_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].Position;      
		    id = "pace_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].Pace;      
		    id = "pace_section_" + athlete.splits[i].StationID;
		    $(id).innerHTML=athlete.splits[i].PaceLastSection;      

		}
	
		// History
		if (UMLShowHistory)
		{
			var history_tab_html = "<table class='History'\><thead><tr class='Corner'><th>Year</th><th>Time</th><th>Pace</th><th>Place</th><th>Age</th></tr></thead><tbody>";
			for (var i =0; i < athlete.history.length; i++)
			{
				//alert(athlete.finishes.Year);
				var class_odd = "";
				if ((i % 2) == 0) class_odd = " class='Odd'";
				var finish_time = athlete.history[i].finishtime;
				if (finish_time == "DNF") finish_time = finish_time + " (" + athlete.history[i].station + ")";
				history_tab_html = history_tab_html + "<tr" + class_odd + "><td>" + athlete.history[i].year + "</td>"
									+ "<td>" + finish_time + "</td>"
									+ "<td>" + athlete.history[i].pace + "</td>"
									+ "<td>" + athlete.history[i].place + "</td>"
									+ "<td>" + athlete.history[i].age + "</td></tr>";
			}
			history_tab_html = history_tab_html + "</tbody></table>";
			$('runner_history').innerHTML = history_tab_html;
		}
		
		// Video Clips
		var video_tab_html = "<table width='265' cellpadding='0' cellspacing='0' class='VideoList'><tbody>";
		if (athlete.videos.length > 0)
		{
			for (var i=0; i < athlete.videos.length; i++)
			{
				video_tab_html = video_tab_html + "<tr><td valign='top' style='cursor: pointer;' onClick='UML.playVideo(\"" + athlete.videos[i].vid + "\");'>" + athlete.videos[i].description + "</td></tr>";	
			}
		}
		else
		{
			video_tab_html = video_tab_html + "<tr><td valign='top'>No videos for runner at this time</td></tr>";
		}
		video_tab_html = video_tab_html + "</tbody></table>";
		$('runner_videos_tab').innerHTML = video_tab_html;
		
		if (UMLShowMaps) { this.updateCourseMap(athlete, racestatus); }
    },
    
    playVideo: function(vid)
    {
    	var youtube = "<iframe width='425' height='349' src='http://www.youtube.com/embed/" + vid + "?rel=0' frameborder='0' allowfullscreen></iframe>";
    	$('runner_video_player').innerHTML = youtube;
    },

	updateStatusImg: function(status)
	{
		var img = 'images/status_entered.gif';
		if (status == this.STATUS_ENTERED) img = 'images/status_entered.gif';
		if (status == this.STATUS_DNS) img = 'images/status_dns.gif';
		if (status == this.STATUS_DROPPED) img = 'images/status_dropped.gif';
		if (status == this.STATUS_ONTRAIL) img = 'images/status_ontrail.gif';
		if (status == this.STATUS_FINISHED) img = 'images/status_finished.gif';
		alert(img);
		$('athlete_status_img').src = img;
	},

	updateCourseMap: function(athlete, racestatus)
	{
		// Load correct map image
		$('coursemap').src=athlete.mapimg;
		var paces = this.getPacesForElapsedTime(parseFloat(racestatus.ElapsedTime));
		var ElapsedTime = Math.floor(racestatus.ElapsedTime);
		var PaceLeadMale = Math.floor(racestatus.PaceLeadMale);
		var PaceLeadFemale = Math.floor(racestatus.PaceLeadFemale);
		var CurrentPace = 0;
		if (athlete.distance > 0) CurrentPace = athlete.timeinticks/athlete.distance;
		var EstimatedMile = 1;
		var EstimatedMile24 = parseFloat(paces[0]);
		var EstimatedMile30 = parseFloat(paces[1]);
		var EstimatedLeadMaleMile = Math.floor(racestatus.ElapsedTime/PaceLeadMale);
		var EstimatedLeadFemaleMile = Math.floor(racestatus.ElapsedTime/PaceLeadFemale);
		if ((athlete.status != '') && (CurrentPace > 0))
		{
			EstimatedMile = Math.floor(racestatus.ElapsedTime/CurrentPace);
		}
		if (EstimatedMile > 100) EstimatedMile = 100;
		if (EstimatedMile24 > 100) EstimatedMile24 = 100;
		if (EstimatedMile30 > 100) EstimatedMile30 = 100;
		if (EstimatedLeadMaleMile > 100) EstimatedLeadMaleMile = 100;
		if (EstimatedLeadFemaleMile > 100) EstimatedLeadFemaleMile = 100;
		//alert(EstimatedMile24 + ' ' + EstimatedMile30);	
		if (EstimatedMile24 > 0) this.mapPosition($('24hr'), EstimatedMile24, 12);
		if (EstimatedMile30 > 0) this.mapPosition($('30hr'), EstimatedMile30, 12);
		//alert(EstimatedMile);
		if (ElapsedTime < 0) 
		{
			$('curpos').hide();
		}
		else
		{
			this.mapPosition($('curpos'), EstimatedMile, 0);
		}
	//$('map_debug').innerHTML = "Pace:" + racestatus.ElapsedTime + "Elapsed:" + racestatus.ElapsedTime +  " mile:" + EstimatedMile + " map_x:" + map_x + " map_y:" + map_y;	

	// Logic for displaying/hiding the various icons
		if ((ElapsedTime < 0) || (ElapsedTime > 86400) || (EstimatedMile24 >= 100)) { $('24hr').hide();}
		else { $('24hr').show(); }

		if ((ElapsedTime < 0) || (EstimatedMile30 >= 100)) { $('30hr').hide();}
		else { $('30hr').show(); }
	
		// Status Checks
		var showCutOff = true;
		if (athlete.status == this.STATUS_DNS)
		{
	    	$('curpos').hide();
	    	$('drop').hide();
	    	$('dns').show();
	    	showCutOff = false;
	    	this.mapPosition($('dns'), 0, 0);
		}
		else if (athlete.status == this.STATUS_ENTERED)
		{
	    	$('curpos').show();
	    	showCutOff = false;
	    	this.mapPosition($('curpos'), 0, 0);
		}
		else if (athlete.status == this.STATUS_DROPPED)
		{
	    	$('dns').hide(); 
	    	$('curpos').hide();
	    	var DropMile = Math.floor(athlete.distance);
	    	this.mapPosition($('drop'), DropMile, 0);
	    	$('drop').show();
	    	showCutOff = false;
		}
		else
		{ 
	    	$('dns').hide(); 
	    	$('drop').hide(); 
	    	$('curpos').show(); 
		}

		// CheckPoint Cutoff
		$('cutoff').hide();
		if ((EstimatedMile < 100) && (showCutOff))
		{
	    	var CutoffMile = 0;
	    	for (var i = 0; i < cutoff_array.length; i++)
	    	{
				if (ElapsedTime >= cutoff_array[i].CutoffTime) CutoffMile = cutoff_array[i].Mile;
	    	}
	    	if (CutoffMile > 0)
	    	{
				this.mapPosition($('cutoff'), CutoffMile, 0);   
				$('cutoff').show();
	    	}
		}

		// Male/Female Leader
		if ((ElapsedTime > 0) && (EstimatedLeadMaleMile < 100))
		{
		    this.mapPosition($('leadmale'), EstimatedLeadMaleMile, -12);   
		    $('leadmale').show();
		}
		else
		{
		    $('leadmale').hide();
		}
		// Lead Female
		if ((ElapsedTime > 0) && (EstimatedLeadFemaleMile < 100))
		{
		    this.mapPosition($('leadfemale'), EstimatedLeadFemaleMile, -12);   
		    $('leadfemale').show();
		}
		else
		{
		    $('leadfemale').hide();
		}
		element = $('map');
	  	element.makePositioned();
	},

    getPacesForElapsedTime: function(t)
    {
		var paces = new Array(2);
		if (t >= 0)
		{
			for (var i = 0; i < map_array.length; i++)
	    	{
				if (map_array[i].Pace1 < t) paces[0] = map_array[i].Mile;
				if (map_array[i].Pace2 < t) paces[1] = map_array[i].Mile;
	    	}
	    }
	    else
	    {
	    	paces[0] = 0;
	    	paces[1] = 0;
	    }
		return paces;
    },

    mapPosition: function(element, mile, y_offset)
    {
	// map_x offset formula: ([row width] - 640)/2
	// (800-640)/2 = 80
	var map_x = parseFloat(map_array[mile].MapX) + 0; //80;
	var map_y = parseFloat(map_array[mile].MapY) + parseFloat(y_offset);
	var x_px = map_x + "px";
	var y_px = map_y + "px";
	element.setStyle({top: y_px, left: x_px});
    },

    showStationsInfo: function(tableHTML)
    {
    	$('stations_detail').innerHTML = tableHTML;
    	return;
    },

    showSelectedStationInfo: function(stationselect)
    {
	var stationid = stationselect.options[stationselect.selectedIndex].value
	UMLAjax.ajaxRequest(UMLAjax.TOP_POSITION_DATA, [5, stationid]);
    },

    showTopPositionInfo: function(positions)
    {

    	var showNoData = false;
    	var noDataMsg = '';
    	if (positions.length == 0) showNoData = true;
    	if (positions.length ==1)
    	{
    		if (positions[0].pid == '-1') 
    		{
    			showNoData  = true;
    			noDataMsg = '<center><h1>Choose a runner and click on the \"Add Favorite\" button to add to My Favorites.</h1></center>';	
    		}
    	}
    	if (showNoData)
    	{
    		this.ShowNoDataTab(noDataMsg);
    		return;
    	}
		this.ShowGroupTab();
		for (var i = 0; i < positions.length; i++)
		{
			if (positions[i].pid != "-1")
			{
				$('groupinforow_'+i).className = "";
			    id = "place_" + i;
			    $(id).innerHTML=positions[i].position;      
			    id = "bibno_" + i;
			    $(id).innerHTML=positions[i].bibno;      
			    $(id).setStyle({textDecoration: 'underline', cursor: 'pointer'});
			    id = "athletename_" + i;
			    $(id).innerHTML=(positions[i].firstname + ' ' + positions[i].lastname);
			    id = "athletegender_" + i;
			    $(id).innerHTML=positions[i].gender;
			    id = "athleteage_" + i;
			    $(id).innerHTML=positions[i].age;
			    id = "stationname_" + i;
			    $(id).innerHTML=positions[i].station;
			    id = "distance_" + i;
			    $(id).innerHTML=positions[i].distance;
			    id = "timein_" + i;
			    $(id).innerHTML=positions[i].timein;      
			    id = "elapsed_" + i;
			    $(id).innerHTML=positions[i].elapsedtime;      
			    id = "status_" + i;
			    $(id).innerHTML=positions[i].status;
		    }
		}
		for (var i = positions.length; i < this.TopPositionsRows; i++)
		{
		    this.clearRow(i);
		    $('groupinforow_'+i).className = "NoData";
		}
		return;
    },

    clearRow: function(row)
    {
	id = "place_" + row;
	$(id).innerHTML="";
	id = "bibno_" + row;
	$(id).innerHTML="";
	id = "athletename_" + row;
	$(id).innerHTML="";
	id = "athletegender_" + row;
	$(id).innerHTML="";
	id = "athleteage_" + row;
	$(id).innerHTML="";
	id = "stationname_" + row;
	$(id).innerHTML="";
	id = "distance_" + row;
	$(id).innerHTML="";
	id = "timein_" + row;
	$(id).innerHTML="";
	id = "elapsed_" + row;
	$(id).innerHTML="";
	id = "status_" + row;
	$(id).innerHTML="";
	return;
    },

    LeftNavItemSelect: function(nav_id)
    {
	if (leftnav_item_id != null)
	{
	    $(leftnav_item_id).setStyle({fontWeight: 'normal'});      
	}
	$(nav_id).setStyle({fontWeight: 'bold' });
	leftnav_item_id = nav_id;
	return;
    },

    UpdateBreadCrumb: function(nav_id)
    {
	var bc = '';
	if (nav_id == 'leftnav_leaders_row')
	{
	    bc = 'Race Leaders';
	}

	
	$('breadcrumb').innerHTML = bc;
    },

	ShowFinishersDetail: function()
	{
		this.LeftNavItemSelect('leftnav_finishers_row');
		this.ShowStationDetail(this.FinishStationID);
	},
	
	Show100KDetail: function()
	{
		this.LeftNavItemSelect('leftnav_100K_row');
		this.ShowStationDetail(this.Station100KID);
	},
	
	ShowStartersDetail: function()
	{
		this.LeftNavItemSelect('leftnav_starters_row');
		this.ShowStationDetail(this.StartStationID);
	},

	ShowOverallLeaders: function()
	{
		this.ShowRaceGroup(1);
	},

    ShowStationDetail: function(id)
    {
		this.ReturnNavigationShow = true;
		this.ReturnNavigationID = this.NAV_STATION;
		this.ShowTab(7);
		UMLAjax.ajaxRequest(UMLAjax.STATIONDETAIL, [id, 0]);
		return;
    },

    ShowRaceGroup: function(group)
    {
		var params = '';
		var reqtype = UMLAjax.TOP_POSITION_DATA;
		this.ReturnNavigationShow = false;
		UMLCookie.setNavGroup(group);
		if (group == 0)
		{
		    return;
		}
		// Leaders
		if (group == 1)
		{
		    this.LeftNavItemSelect('leftnav_leaders_row');
		    this.ReturnNavigationID = this.NAV_OVERALL_LEADERS;
		}
		// Top Men
		if (group == 2)
		{
		    this.LeftNavItemSelect('leftnav_topmen_row');
		    this.ReturnNavigationID = this.NAV_MEN_LEADERS;
		}
		// Top Women
		if (group == 3)
		{
		    this.LeftNavItemSelect('leftnav_topwomen_row');
		    this.ReturnNavigationID = this.NAV_WOMEN_LEADERS;
		}
		// My Favorites
		if (group == 4)
		{
			this.LeftNavItemSelect('leftnav_myfavorites_row');
			this.ReturnNavigationID = this.NAV_MYFAVORITES;
			var ids = UMLCookie.getPID();
		    params = ids.join(',');
		    reqtype = UMLAjax.MY_ATHLETE_DATA;
		}
		// Stations
		if (group == 5)
		{
		    this.LeftNavItemSelect('leftnav_stations_row');
		    var stationid = $('aid_station_id');
		   	this.ShowTab(5);
		   	return;
		}
		// Drops
		if (group == 6)
		{
		    this.LeftNavItemSelect('leftnav_drops_row');
		    this.ReturnNavigationID = this.DROPS;
		    reqtype = UMLAjax.DROPS;
		    params = '0';
		}
		
		// Finishers
		if (group == 7)
		{
			this.ShowFinishersDetail();
			return;
		}
		
		// Live Blog
		if (group == 8)
		{
			this.ShowCoverItLiveTab()
			return;
		}
		
		// Starters
		if (group == 9)
		{
			this.ShowStartersDetail();
			return;
		}
		
		// 100K
		if (group == 10)
		{
			this.LeftNavItemSelect('leftnav_100K_row');
		    this.ReturnNavigationID = this.NAV_100K;
		    reqtype = UMLAjax.FINISH_100K;
		    params = UMLAjax.FINISH_100K;
		}
		
		
		if (group == 42)
		{
			this.ShowUstreamTab();
			return;
		}
		UMLAjax.ajaxRequest(reqtype, [group, params]);
		this.ShowTab(group);
		return;
    },

    getSelectedIndexValue: function(c)
    {
	return c.options[c.selectedIndex].value;
    },

    ReturnNavigationLink: function()
    {
	var tabid = 1;
	var resetID = true;
	if (this.ReturnNavigationID == this.NAV_OVERALL_LEADERS) 
	{
	    this.ShowGroupTab(); 
	    tabid = 1;
	}
	if (this.ReturnNavigationID == this.NAV_MEN_LEADERS) 
	{
	    this.ShowGroupTab();
	    tabid = 2;
	}
	if (this.ReturnNavigationID == this.NAV_WOMEN_LEADERS) 
	{
	    this.ShowGroupTab();
	    tabid = 3;
	}
	if (this.ReturnNavigationID == this.NAV_STATION) 
	{
	    this.ShowStationsTab();
	    tabid = 5;
	}
	if (this.ReturnNavigationID == this.DROPS) 
	{
	    this.ShowDropsTab();
	    tabid = 6;
	}
	if (this.ReturnNavigationID == this.NAV_STATIONDETAIL) 
	{
	    tabid = 7;
	    resetID = false;
	    this.ReturnNavigationID = this.NAV_STATION;
	    this.ReturnNavigationShow = true;
	    this.ShowStationDetailTab();
	}

	if (this.ReturnNavigationID == this.NAV_MYFAVORITES) 
	{
	    this.ShowGroupTab();
	    tabid = 4;
	}

	if (resetID) 
	{
	    //this.ReturnNavigationID = 0;
	    this.ReturnNavigationShow = false;
	}
	this.ShowTab(tabid);

    },

    ContentTitleDescription: function(desc)
    {
	$('content_title_navigation').innerHTML = "";
	if ((this.ReturnNavigationID != 0) && this.ReturnNavigationShow)
	{
	    $('content_title_navigation').innerHTML = "<< Return";
	    desc = "&nbsp;&nbsp;" + desc;
	}
	$('content_title_description').innerHTML = desc;
    },

    ShowTab: function(group)
    {
	if (group == 1)
	{
	    this.ContentTitleDescription('Overall Leaders');
	    //this.ShowGroupTab();
	}
	if (group == 2)
	{
	    this.ContentTitleDescription('Top Men Leaders');
	    //this.ShowGroupTab();
	}
	if (group == 3)
	{
	    this.ContentTitleDescription('Top Women Leaders');
	    //this.ShowGroupTab();
	}
	if (group == 4)
	{
	    this.ContentTitleDescription('My Favorites');
	    //this.ShowGroupTab();
	}
	if (group == 5)
	{
	    // Static content on original page
	    this.ContentTitleDescription('Checkpoints');
	    this.ShowStationsTab();
	}
	if (group == 6)
	{
	    this.ContentTitleDescription('Drops');
	    //this.ShowDropsTab();
	}
	if ((group == 7) || (group == 10))
	{
	    this.ContentTitleDescription('Station Detail');
	    //this.ShowStationDetailTab();
	}
	return;
    },

    ShowProcessingTab: function()
    {
		this.HideAllTabs();
		$('processing_tab').show();
    },

    HideProcessingTab: function()
    {
		$('processing_tab').hide();
    },

	ShowCheckingUpdate: function()
	{
		$('content_update_check').show();
	},
	
	HideCheckingUpdate: function()
	{
		$('content_update_check').hide()
	},

    ShowAthleteTab: function()
    {
    	this.HideAllTabs();
		$('athlete_tab').show();
    },

    HideAthleteTab: function()
    {
		$('athlete_tab').hide();
    },

    HideAllTabs: function()
    {
	    $('processing_tab').hide();
	    $('content_update_check').hide()
		$('athlete_tab').hide();
		$('stations_tab').hide();
		$('drop_tab').hide();
		$('stationdetail_tab').hide();
		$('error_tab').hide();
		$('group_tab').hide();
		$('coveritlive_tab').hide();
		$('nodata_tab').hide();
		$('ustream_tab').hide();
    },

	ShowCoverItLiveTab: function()
	{
		this.HideAllTabs();
		this.LeftNavItemSelect('leftnav_coveritlive_row');
		this.ContentTitleDescription('Live Blog');
		$('coveritlive_tab').show();
	},
	
	ShowUstreamTab: function()
	{
		this.HideAllTabs();
		this.LeftNavItemSelect('leftnav_ustream_row');
		this.ContentTitleDescription('Live Video');
		$('ustream_tab').show();
	},

    ShowGroupTab: function()
    {
    	this.HideAllTabs();
		$('group_tab').show();
    },

    ShowStationsTab: function()
    {
    	this.HideAllTabs();
    	this.LeftNavItemSelect('leftnav_stations_row');
		$('stations_tab').show();
    },

    ShowStationDetailTab: function()
    {
    	this.HideAllTabs();
		$('stationdetail_tab').show();
    },

    ShowDropsTab: function()
    {
    	this.HideAllTabs();
		$('drop_tab').show();
    },

    ShowErrorTab: function()
    {
    	this.HideAllTabs();
		$('error_tab').show();
    },

    ShowNoDataTab: function(msg)
    {
    	this.HideAllTabs();
    	if (msg.length == 0)
    	{
    		$('nodatacontent').innerHTML = '<center><h1>No data available.  The data entry is currently delayed due to weather conditions.  Check back later.</h1><br/></center>';
    	}
    	else
    	{
    		$('nodatacontent').innerHTML = msg;
    	}
		$('nodata_tab').show();
    },


    // Track Athlete
    GetMyAthleteListFromCookie: function()
    {
		var ids = UMLCookie.getPID();
		if (ids == null)
		{
	    $('myathletelist_note').show();
		}
		else
		{
	    $('myathletelist_note').hide();
	    // Get PersonID from BibNo
	    pids = [];
	    for (var i = 0; i < ids.length; i++)
	    {
	    	if (ids[i] != '') pids.push(ids[i]);
	    }
	    if (pids.length > 0) 
	    {
	    	UMLAjax.ajaxRequest(UMLAjax.MY_FAVORITES_DATA, ['', pids.join(',')]);
	    }
	}
    },
    
    ShowMyAthleteListInfo: function(athletes)
    {
		var id = "";
		for (var i = 0; i < athletes.length; i++)
		{
			if (athletes[i].pid != "-1")
			{
	    		this.PopulateMyAthleteListInfo((i + 1), athletes[i].bibno, athletes[i].name);
	    	}
		}
    },

    PopulateMyAthleteListInfo: function(rowid, bibno, athletename)
    {
	var id = "myathlete_bib_" + rowid;
	$(id).innerHTML = bibno + '';
	id = "myathlete_name_" + rowid;
	$(id).innerHTML = athletename + " - ";
    },

    AddBibToCookie: function()
    {
		var pids = this.GetMyAthleteBibsFromTable(true);
		UMLCookie.setPID(pids);
    },

    RemoveAthleteForTracking: function(athlete)
    {
	var bibno =  this.GetBibNoFromString(athlete);
	this.RemoveBibFromCookie(bibno);
	this.ClearTrackedAthletes();
	this.GetMyAthleteListFromCookie();
    },

    RemoveBibFromCookie: function(bibno)
    {
		// Get cookie value
		var pid = this.getPersonID(bibno);
		var bibarray = UMLCookie.getPID();
		var newbibs = [];
		for (var i = 0; i < bibarray.length; i++)
    	{
	    	if (bibarray[i] != pid)
	    	{
	    		newbibs.push(bibarray[i]);
	    	}
        }
        UMLCookie.setPID(newbibs);
    },

    GetMyAthleteBibsFromTable: function(convertToPID)
    {
		var lastbib = '';
		var bib = '';
		var bibs = [];
		for (var i = 1; i <= this.MyAthletesRows; i++)
		{
	    	rowid = "myathlete_bib_" + i;
		    bib = $(rowid).innerHTML;
		    if (convertToPID) bib = this.getPersonID(bib);
		    
		    if (bib != null) bibs.push(bib);
		}
		return bibs;
    },

    FindFirstEmptyRow: function()
    {
      var rowid = '';
      for (var i = 1; i <= this.MyAthletesRows; i++)
      {
	  rowid = "myathlete_bib_" + i;
	  if ($(rowid).innerHTML == '') return i;
	  
      }
      return -1;
    },

    ClearTrackedAthletes: function()
    {
	for (var i = 1; i <= this.MyAthletesRows; i++)
	{
	    var id = "myathlete_bib_" + i;
	    $(id).innerHTML = '';
	    id = "myathlete_name_" + i;
	    $(id).innerHTML = '';
	}
    },

    IsAthleteTracked: function(bibno)
    {
	for (var i = 1; i <= this.MyAthletesRows; i++)
	{
	    rowid = "myathlete_bib_" + i;
	    if ($(rowid).innerHTML == bibno) return true;
	}
	return false;
    },

    AddAthleteForTracking: function(athlete)
    {
	var rowid = this.FindFirstEmptyRow();
	//var AthleteID = this.GetBibNoFromString(athlete);
	var AthleteID = athlete;
	if (AthleteID == '')
	{
            alert('Please choose an athlete from the list before adding to the watch list.');
            return;
	}

	if (!this.IsAthleteTracked(AthleteID))
	{
	    var AthleteName = AL[AthleteID];
	    if (rowid != -1)
	    {
		this.PopulateMyAthleteListInfo(rowid, AthleteID, AthleteName);
		//this.findAthlete(AthleteID);
		this.AddBibToCookie();
	    }
	    else
	    {
		alert("Unable to track athelete.  Table is full.");
	    }
	}
	else
	{
	    alert('Athelete already in tracking list.');
	}
    },

    RowHighLight: function(obj, className)
    {
    	if (obj.cells[0].innerHTML != '') obj.className = className;
    },
    
    CacheObjID: function(reqtype, id)
    {
    	var cache_id = id;
    	if (reqtype == UMLAjax.ATHLETE_DATA) cache_id = 'A'+id; 
    	if (reqtype == UMLAjax.TOP_POSITION_DATA) cache_id = 'P'+id;
    	if (reqtype == UMLAjax.DROPS) cache_id = 'D'+id;
    	if (reqtype == UMLAjax.STATIONDETAIL) cache_id = 'S'+id;
    	if (reqtype == UMLAjax.MY_ATHLETE_DATA) cache_id = 'MYA';
    	return cache_id;
    }

};


var UMLAjax = {
  NetworkErrorRetry: 0,
  ATHLETE_DATA: 1,
  TOP_POSITION_DATA: 2,
  MY_FAVORITES_DATA: 3,
  MY_ATHLETE_DATA: 4,
  DROPS: 5,
  STATIONDETAIL: 6,
  FINISH_100K: 10,
  
  ajaxRequest: function(reqtype, params)
  {
    // Show processing image
    var url = 'ajaxapi.php';
    var qs = 'json=true';
    var pageName = '/ajaxapi.php';
    var epoch  = 0;
    var checkingForUpdate = false;
    //$('ajax-message-area').hide();
    var cacheid = '';
    
    
    if (reqtype == this.ATHLETE_DATA)
      {
        qs += '&rtype='+reqtype+'&id='+params[0];
        pageName = '/webcast/ajax/Athlete_Data';
        cacheid = UML.CacheObjID(reqtype, params[0]);
        epoch = UMLCache.getItemEpoch(cacheid);
        if (epoch > 0) checkingForUpdate = true;
      }
    if (reqtype == this.TOP_POSITION_DATA)
      {
        qs += '&rtype='+reqtype+'&rowtype='+params[0]+'&params='+params[1];
        pageName = '/webcast/ajax/Top_Positions';
        cacheid = UML.CacheObjID(reqtype, params[0]);
        epoch = UMLCache.getItemEpoch(cacheid);
        if (epoch > 0) checkingForUpdate = true;
        
      }
    if (reqtype == this.MY_FAVORITES_DATA)
      {
        qs += '&rtype='+reqtype+'&rowtype=1&params='+params[1];
        pageName = '/webcast/ajax/My_Favorites';
      }
    if (reqtype == this.MY_ATHLETE_DATA)
      {
        qs += '&rtype='+reqtype+'&rowtype=2&params='+params[1];
        pageName = '/webcast/ajax/My_Athletes';
        cacheid = UML.CacheObjID(reqtype, 0);
        epoch = UMLCache.getItemEpoch(cacheid);
        if (epoch > 0) checkingForUpdate = true;
        
      }
    if (reqtype == this.DROPS)
      {
        qs += '&rtype='+reqtype;
        pageName = '/webcast/ajax/Drops';
        cacheid = UML.CacheObjID(reqtype, params[0]);
        epoch = UMLCache.getItemEpoch(cacheid);
        if (epoch > 0) checkingForUpdate = true;
      }
    if ((reqtype == this.STATIONDETAIL) || (reqtype == this.FINISH_100K))
      {
        qs += '&rtype='+reqtype+'&id='+params[0];
        pageName = '/webcast/ajax/Station_Detail';
        cacheid = UML.CacheObjID(reqtype, params[0]);
        epoch = UMLCache.getItemEpoch(cacheid);
        if (epoch > 0) checkingForUpdate = true;
      }

      qs += '&epoch=' + epoch;

	if (checkingForUpdate)
	{
		// Show cached data before doing AJAX call
		this.ajaxShowData(reqtype, UMLCache.getItem(cacheid), UMLStatusCache, params);
		UML.ShowCheckingUpdate();
	}
	else
	{
    	UML.ShowProcessingTab();
    }

    //alert(qs);
    //this.ajaxErrorMessage(qs);    
    new Ajax.Request(url, {
      parameters: qs,
      method:'get',
      onSuccess: function(transport, json){
        UMLAjax.ajaxSuccess(url, qs, transport, json, reqtype, params);
      },
      onFailure: function(){ 
        msg = 'Ajax request failed (onFailure)';
        UMLAjax.ajaxFailure(url, qs, msg, true) 
      }
    });
    Analytics.TrackPage(pageName);
  },

	ajaxSuccess: function(url, qs, transport, json, reqtype, params)
    {
    	var VALID_UML_JSON = '{"AjaxMessage":{"MessageType":"JSON"}';
		UML.HideProcessingTab();
		if (transport.responseText.substring(0,37) != VALID_UML_JSON)
		{
		    this.NetworkErrorRetry++;
			var networkError = false;
			if (transport.responseText.length == 0) networkError = true; 
			// This is a strange response from the Network solutions server.  Seems to be related to when a browser is inactive for a while.
			if (transport.responseText.substring(0,21) == "<!DOCTYPE html PUBLIC") networkError = true; 
			
		    if (this.NetworkErrorRetry == 1)
			{
			    this.ajaxRequest(reqtype, params);
			    return;
			}
			this.ajaxFailure(url, qs, transport.responseText, networkError);
			return;
		}
		this.NetworkErrorRetry = 0;
		//alert(transport.substring(0,10));
		var data = transport.responseText.evalJSON();
		var header = data.AjaxHeader;
		var content = data.AjaxContent;
		var athletestatus = data.AjaxAthleteStatus;
		//var athletestatus = null;
		var racestatus = data.AjaxRaceStatus;

		var updatedData = true;
		var epoch = 0;
		var cacheid = '';
		// Check cache for object and compare epoch
		if ((reqtype==this.ATHLETE_DATA) || (reqtype==this.STATIONDETAIL) || (reqtype==this.TOP_POSITION_DATA) || (reqtype==this.MY_ATHLETE_DATA) || (reqtype==this.DROPS))
		{
			cacheid = UML.CacheObjID(reqtype, params[0]);
			epoch = UMLCache.getItemEpoch(cacheid);
			if ((header.Epoch > epoch) && (header.Epoch != 0))
			{
				UMLCache.setItem(cacheid, content, header.Epoch);
			}
			else if (header.Epoch != 0)
			{
				content = UMLCache.getItem(cacheid);
				updatedData = false;
			}	
		}
		
		UMLStatusCache = racestatus;
		//$('ajax-message-area').show();
		//this.ajaxSetInfo(header);
		
		// Update with new data if available
		if (updatedData)
		{ 
			this.ajaxShowData(reqtype, content, racestatus, params);
		}
		else
		{
			// Just update the race clock
			UML.UpdateRaceClock(racestatus.RaceClockTime);
			UML.HideCheckingUpdate();			
		}
	
		return;
    },
    
    ajaxShowData: function(reqtype, content, racestatus, params)
    {
		if (reqtype==this.ATHLETE_DATA)
		{
            UML.showAthleteInfo(content, racestatus);
		}
	
		if (reqtype==this.TOP_POSITION_DATA)
		{
	    	if (params[0] == 5)
	        {
				UML.showStationsInfo(content);
	        }
	        else
	        {
				UML.showTopPositionInfo(content);
	        }
		}
		
		// Populates side bar
		if (reqtype==this.MY_FAVORITES_DATA)
		{
	        UML.ShowMyAthleteListInfo(content);
		}
		
		if (reqtype==this.MY_ATHLETE_DATA)
		{
			UML.showTopPositionInfo(content);
		}
		
		if (reqtype==this.DROPS)
		{
	            UML.showDrops(content);
		}
	
		if (reqtype==this.STATIONDETAIL || reqtype == this.FINISH_100K)
		{
	            UML.showStationInfoDetail(content);
		}
	
		// Update Race Clock
		UML.UpdateRaceClock(racestatus.RaceClockTime);
    },
    
    ajaxFailure: function(url, qs, msg, networkError)
    {
		UML.HideProcessingTab();
		UML.ShowErrorTab();
		var errmsg = msg;
		if (networkError)
		{
			errmsg = "<center><H1>A network error occurred.</H1><br/>Please check your connection and try again.</center>";
		}
		else
		{
			errmsg = "<center><H1>Sorry, an error has occurred.  Please refresh the page to clear the error.</H1></center>" +
					"<b>URL: " + url + "?" + qs + "</b><br/><br/>Message:<br/>" + msg;
		}
		$('errorcontent').innerHTML = errmsg;
    },

    ajaxErrorMessage: function(reqtype, msg)
    {
		UML.HideProcessingTab();
		$('ajax-message-area').show();
		var ajaxmsg = 'AJAX Error - Message:' + msg;
		$('ajax-message').innerHTML=ajaxmsg;
    },

    ajaxSetInfo: function(info)
    {
		$('ajax-rc').innerHTML=info.ReturnCode;
		$('ajax-msg').innerHTML=info.Message;
		$('ajax-sqlhits').innerHTML=info.SQLHits;
		$('ajax-sqltime').innerHTML=info.SQLTime;
		$('ajax-cache').innerHTML=info.CachedItem;
		$('ajax-pagetime').innerHTML=info.GenerationTime;
    }

}

var Analytics = {
    TrackPage: function(pagename)
    {
    	if (typeof(pageTracker) != 'undefined')
    	{
    		if (pageTracker != null) pageTracker._trackPageview(pagename);
    	}
    }
};

// Cache constructor
function Cache(maxSize) {
    this.items = {};
    this.count = 0;
}

// Cache Item exits
// Returns true
Cache.prototype.exists = function(key) {
	return ((this.getItem(key) == null) ? false : true);
}

// Cache.getItem
// retrieves an item from the cache, returns null if the item doesn't exist
Cache.prototype.getItem = function(key) {

    // retrieve the item from the cache
    var item = this.items[key];
    
    // return the item value (if it exists), or null
    var returnVal = null;
    if (item != null) {
        returnVal = item.value;
    }
    return returnVal;
}

// Cache.getItemEpoch
// Gets time from item of last know update from ajax data
Cache.prototype.getItemEpoch = function(key) {
    var item = this.items[key];
    if (item != null) return item.epoch;
    return 0;
}


// Cache.setItem
// sets an item in the cache
// parameters: key - the key to refer to the object
//             value - the object to cache
//             epoch - time value for object (0 if null)
Cache.prototype.setItem = function(key, value, epoch) {

    function CacheItem(k, v, e) {
        if ((k == null) || (k == ''))
            throw new Error("key cannot be null or empty");
        this.key = k;
        this.value = v;
		this.epoch = e;
    }

    // add a new cache item to the cache
    if (this.items[key] != null)
        this._removeItem(key);
    this._addItem(new CacheItem(key, value, epoch));
    
}

// Cache.clear
// Remove all items from the cache
Cache.prototype.clear = function() {

    // loop through each item in the cache and remove it
    for (var key in this.items) {
      this._removeItem(key);
    }  
}

// Cache._addItem
// add an item to the cache
Cache.prototype._addItem = function(item) {
    this.items[item.key] = item;
    this.count++;
}

// Cache._removeItem 
Cache.prototype._removeItem = function(key) {
    var item = this.items[key];
    delete this.items[key];
    this.count--;
}

function popup(PAGE) {
file = PAGE + ".htm";
newWindow = window.open(file,"help","width=400,height=400,scrollbars=yes,location=no,left=10,top=10,menubar=no,resizable=yes,toolbar=no,status=no");
newWindow.focus();
}


function sendto(TO,ADDR,DOM,SUBJ) {
     if (!DOM) DOM = "ws100.com";
     if (ADDR == "webmaster") {
    		ADDR = "webmaster";
    		DOM = "ws100.com";}
     file = "mailto:" + ADDR;
     subject = "Website Feedback";
     if (SUBJ) subject = SUBJ;
     subject = "[WSER] " + subject + "  (Attn: " + TO + ")";
     message = "&body=Page Title = " + document.title + 
               "&body=URL = " + document.URL +
               "&body=_______________________________________" +
               "&body= " +
               "&body=Please add your message below..." +
               "&body=  &body=  ";
     file = file + "@" + DOM + "?Subject=" + subject;
     if (TO == "Webmaster") file = file + message;
     window.location = file;
}
