
var RFTWresults = new RFTWdekiInit();

var teamsInfo = new Array();
var teamsData = new Array();
var teamsLT = "";
//--------------------------------
//  Helper functions
//--------------------------------

function getPathHref(pathLink) {
	return Deki.BaseHref + "/" + pathLink;
}
function getLeagueHref(leagueLink) {
	return Deki.BaseHref + "/" + leagueLink;
}
function getTeamHref(leagueLink, teamLink) {
	return getLeagueHref(leagueLink) + "/" + teamLink;
}
function getSwimmerHref(swimmerId) {
	return Deki.BaseHref + "/Results_Statistics/Swimmer_Results?swimmerId=" + swimmerId;
}
function bxTeamsSort(a,b) {
	return a.team_id - b.team_id;
}
function bxPointsSort(a,b) {
	return parseFloat(b.points_raw) - parseFloat(a.points_raw);
}

$wpjQ(document).ready(function(){
	var getData = {};
	getData.result = "meet";
	getData.meetId = RFTWresults.getQS("meetId");	
	$wpjQ.getJSON("http://"+ RFTWresults.jsonurl + "/wp-content/themes/rftw/json.php?" + getData.result + "&callback=?",getData,function(data){ processMeet(data); });
});

//--------------------------------
// Main function: Process Meet
//--------------------------------
function processMeet(data) {
	var output = "";

	output += printMeetHeader(data);
	output += printBoxScore(data);
	if (data.indswims[0].swimmers.length > 0){
       	output += printIndResults(data.indswims);
    }
	output += printRelayResults(data.relays);
	output += printDivesResults(data.dives);
	$wpjQ("#meet").html(output);
}

//--------------------------------
// Header
//--------------------------------
function printMeetHeader(data) {
	var output = "";
	
	$wpjQ.each(data.teams, function() {
		
		teamsInfo[this.team_abbrev] =  this.league_name_link + "/" + this.team_name_link;
		teamsData.push(this);
		
	});

	teamsLT = RFTWresults.pagelinks[data.team_type];

//	teamsData.sort(bxTeamsSort);
	
	var teamStr = "";
	var teamNames = "";
	var leagueNames = "";
	var leagueNamesAr = [];
	var count = 1;
	for (var i in teamsData) {
		teamStr += teamsData[i].team_abbrev;
		teamNames += "<li><a href='" + getTeamHref(teamsLT + "/" + teamsData[i].league_name_link, teamsData[i].team_name_link) + "'>"+teamsData[i].team_name+"</a></li>";
		
		var leagueNameHref = "<a href='" + getLeagueHref(teamsLT + "/" + teamsData[i].league_name_link) + "'>"+teamsData[i].league_name+"</a>";
		if ( !in_array(leagueNameHref,leagueNamesAr) ){
			leagueNamesAr.push(leagueNameHref);
		}
		if (count < teamsData.length) {
			teamStr += " : ";
			count++;
		}
	}
	var count = 1;
	for (var i in leagueNamesAr) {
		leagueNames += leagueNamesAr[i];
		if (count < leagueNamesAr.length) {
			leagueNames += " <br/> ";
			count++;
		}
	}
	
    output += "<div id='meet-header'>";
    if (data.boxscoretype == "short") {
	if (data.meet_title){
		output +="<center><h2>" + data.meet_title + "</h2></center>";
	}
	else{
	    	output += "<center><h2>" + data.meet_type + "</h2></center>";
	}
    } else {
		output += "<center><h2>" + teamStr + "</h2></center>";
	}
	output += "<strong>Date:</strong> " + data.meet_date + "<br>";
	output += "<strong>League:</strong> " + leagueNames + "<br>";
	output += "<strong>Location:</strong> " + data.pool + "<br>";
	output += "<strong>Course:</strong> " + data.course + "<br>";
	if (data.division) {
		output += "<strong>Division:</strong> " + data.division + "<br>";
	}
	if (data.meet_type.toLowerCase() != 'all star'){
		output += "<strong>Opponents:</strong><ul>" + teamNames + "</ul><br>";
	}
	else{
		output += "<strong>NOTE: </strong> Points aren't usually reported in All-Star meets.<br>";
	}
    output += "</div>";
	return output;
}

//--------------------------------
// Box Score
//--------------------------------
function printBoxScore(data) {
	var output = "";
	if (data.boxscoretype == "short" ) {
		// for all stars, no points are kept, etc.
		if (data.meet_type.toLowerCase() != 'all star'){
			output += printDivisionalBoxScore(data);
		}
	} else {
		output += printFullBoxScore(data);
	}
	return output;
}

//--------------------------------
// Divisional Box Score
//--------------------------------
function printDivisionalBoxScore(data) {
	var output = "";
	output += "<table class='api-data box-score' width='440'>";
    output += "<caption class='w440'>Box Score</caption>";    
    output += "<thead class='box-score'>";
    
    var bxTeams = new Array();
    $wpjQ.each(data.teams, function() {    	
		bxTeams.push(this);
    });
    // Header    
   	output += "<th class='scoring-breakdown'>Scoring Breakdown</th>";
    $wpjQ.each(data.boxscore, function() {
		output += "<th class='eventname'>" + this.eventname + "</th>";
    });
    output += "</tr>";
    output += "<tr></thead>";

	var maxPts = [0,0,0];
	// totals are teams[0],girls are [1] and boys [2]
	// let's find and remember the top pts in each category
	// so we can bold them later ... 
	for (var g=0;g<data.boxscore.length;g++){
		for (var j in data.boxscore[g].teams){
		    if (!parseFloat(data.boxscore[g].teams[j].points)){
		        data.boxscore[g].teams[j].points = 0.0;
		    }
			if (parseFloat(data.boxscore[g].teams[j].points) > parseFloat(maxPts[g])){
				maxPts[g] = data.boxscore[g].teams[j].points;
			}
		}
	}
    output += "<tbody class='box-score'>";
    for (var i in bxTeams) {
		output += "<tr>";
		output += "<td class='scoring-breakdown'>" + bxTeams[i].team_abbrev + "</td>";
		var j = 0;
		$wpjQ.each(data.boxscore, function() {
			if (this.teams[i].points == parseFloat(maxPts[j])){
				output += "<td class='box-team'><strong>" + this.teams[i].points + "</strong></td>";
			}
			else{
				output += "<td class='box-team'>" + this.teams[i].points + "</td>";
			}
			j++;
		});
		output += "</tr>";
    }
    output += "</tbody>";
	output += "</table>";
	
	return output;
}

//--------------------------------
// Full Box Score
//--------------------------------
function printFullBoxScore(data) {
	var output = "";
	output += "<table class='api-data box-score' width='440'>";
    output += "<caption class='w440'>Box Score</caption>";    
    output += "<thead class='box-score'>";
    output += "<tr>";
   	output += "<th class='scoring-breakdown'>Scoring Breakdown</th>";
   	
   	var bxTeams = new Array();
    $wpjQ.each(data.teams, function() {    	
		bxTeams.push(this);
    });
    bxTeams.sort(bxTeamsSort);
    for (var i in bxTeams) {
		output += "<th class='box-team'>" + bxTeams[i].team_abbrev + "</th>";
	}

    output += "</tr></thead><tbody class='box-score'>";

    $wpjQ.each(data.boxscore, function() {
		output += "<tr>";
		if ($wpjQ.trim(this.eventname) == "Totals" || $wpjQ.trim(this.eventname) == "Boys All" || $wpjQ.trim(this.eventname) == "Girls All") {
			output += "<td class='eventname'>" + this.eventname + "</td>";
		} else {
			output += "<td class='eventname eventname-link'>" + "<a href='#" + this.eventname + "'>" + this.eventname + "</a></td>";
		}
		var maxPoints = 0;
		var bxScores = new Array();
		$wpjQ.each(this.teams, function() {
			if (parseFloat(this.points) > maxPoints) { maxPoints = parseFloat(this.points); }
			bxScores.push(this);
		});
		bxScores.sort(bxTeamsSort);

		var totalTeams = teamsData.length;
		for (var i in bxScores) {
			var teamClass = i==(totalTeams-1) ? ' box-team-final' : ' box-team';
			if (parseFloat(bxScores[i].points) == maxPoints) {
				output += "<td class='win" + teamClass + "'>";
			} else {
				output += "<td class='" + teamClass + "'>";
			}
			output += bxScores[i].points + "</td>";
		}
		output += "</tr>";
    });
 
    output += "</tbody>";
	output += "</table>";
	
	return output;
}

//--------------------------------
// Individual Results
//--------------------------------
function printIndResults(ind) {
	var output = "";
	$wpjQ.each(ind, function() {
		output += "<table  class='api-data individual-results' width='440'>";
		output += "<caption class='w440'><a name='" + this.eventname + "'>" + this.eventname + "</a>" + " - " + this.eventnum + "</caption>";
        output += "<thead class='individual-results'>";
		output += "<tr>";
        output += "<th class='finish'>&#35;</th>";
        output += "<th class='swimmer'>Swimmer</th>";
        output += "<th class='age'>Age</th>";
        output += "<th class='team'>Team</th>";
        output += "<th class='seedtime'>Seed Time</th>";
        output += "<th class='swimresult'>Swim Time</th>";
        output += "<th class='points'>Points</th>";
        output += "</tr>";
        output += "</thead>";
		output += "<tbody class='individual-results'>";        
		output += printEachEvent(this);
		output += "</tbody>";
		output += "</table>";
	});	
	return output;
}

//--------------------------------
// Each Event
//--------------------------------
function printEachEvent(event) {
	output = "";
	var count = 0;
	var swimage = '';
	if (!event.swimmers) { return output; }
	$wpjQ.each(event.swimmers, function() {
		var teamwww = getPathHref(teamsLT + "/" + teamsInfo[this.team_abbrev]);
		var swimmerwww = getSwimmerHref(this.swimmer_id);
		if (count % 2 != 0) {
			output += "<tr class='even'>";
		} else { 
			output += "<tr class='odd'>";
		}
		output += "<td class='finish'>" + this.finish + "</td>";
		if (!this.swimmer_name) {
			output += "<td class='swimmer'>&mdash;</td>";
		} else {
			output += "<td class='swimmer'>" + "<a href='"+swimmerwww+"'>"+this.swimmer_name + "</a></td>";
		}
		if (this.swimmer_age.length > 0){
		    swimage=this.swimmer_age;
    	}
    	else if (this.hsclass.length > 0){
    	    swimage=this.hsclass;
    	}
    	else{
    	    swimage='';
    	}
   		output += "<td class='age'>" + swimage + "</td>";
		output += "<td class='team'>" + "<a href='"+ teamwww +"'>"+ this.team_abbrev + "</a></td>";
		output += "<td class='seedtime'>" + this.seedtime + "</td>";
		output += "<td class='swimresult'>" + this.swimresult + "</td>";
		if ((!this.points || this.points == 0) && this.status) {
			output += "<td class='points'>" + this.status + "</td>";
		} else {
			output += "<td class='points'>" + Math.round(this.points*10)/10;
		}
		output += "</tr>";
		count++;
	});
	return output;
}


//--------------------------------
// Relay Results
//--------------------------------
function printRelayResults(relay) {
	var output = "";
	$wpjQ.each(relay, function() {
	output += "<table class='api-data relay-results' width='440'>";
		output += "<caption class='w440'><a name='" + this.eventname + "'>" + this.eventname + "</a>" + " - " + this.eventnum + "</caption>";
        output += "<thead>";
		output += "<tr>";
        output += "<th class='swimmer'>Swimmer</th>";
        output += "<th class='age'>Age</th>";
        output += "<th class='team'>Team</th>";
        output += "<th class='seedtime'>Seed Time</th>";
        output += "<th class='swimresult'>Swim Time</th>";
        output += "<th class='points'>Points</th>";
        output += "</tr></thead><tbody>";

		output += printEachRelay(this);

		output += "</tbody>";
		output += "</table>";
	});
	return output;
}

function printEachRelay(relay) {
	var output = "";
	var count = 0;
	if (!relay.teams) { return output; }
	$wpjQ.each(relay.teams, function() {
		var teamwww = getPathHref(teamsInfo[this.team_abbrev]);
		if (count % 2 == 0) {
			output += "<tr class='even'>";
		} else { 
			output += "<tr class='odd'>";
		}
		output += printRelaySwimmers(this.swimmers);
		output += printRelayAges(this.swimmers);
		output += "<td class='team'>" + "<a href='"+teamwww+"'>"+ this.team_abbrev + "</a></td>";
		output += "<td class='seedtime'>" + this.seedtime + "</td>";
		if (!this.swimresult) {
			output += "<td class='swimresult'>&mdash;</td>";
		} else {
			output += "<td class='swimresult'>" + this.swimresult + "</td>";
		}
		output += "<td class='points'>" + Math.round(this.points*10)/10 + "</td>";
		output += "</tr>";
		count++;
	});
	return output;
}

function printRelaySwimmers(swimmersData) {
	var output = "";
	output += "<td class='relay swimmer-data swimmer'>";	
	$wpjQ.each(swimmersData, function() {
		if (!this.swimmer_name) {
			output += "&mdash;";
		} else {
			var swimmerwww = getSwimmerHref(this.swimmer_id);
			output += "<a href='" + swimmerwww + "'>" +this.swimmer_name + "</a>";
		}
		output += "<br>";
	});
	output += "</td>";
	return output;
}

function printRelayAges(swimmersData) {
	var output = "";
	var swimage ="";
	output += "<td class='relay swimmer-data age'>";
	$wpjQ.each(swimmersData, function() {
		if (this.swimmer_age.length > 0 && this.swimmer_age != "0"){
		    swimage=this.swimmer_age;
    	}
    	else if (this.hsclass.length > 0){
    	    swimage=this.hsclass;
    	}
    	else{
    	    swimage='';
    	}

		output += swimage + "<br>";
	});
	output += "</td>";
	return output;
}

//--------------------------------
// Dive Results
//--------------------------------
function printDivesResults(dive) {
	var output = "";
	if (dive[0].divers == null) { return output; }
	$wpjQ.each(dive, function() {
		output += "<table class='api-data' width='440'>";
		output += "<caption class='w440'><a name='" + this.eventname + "'>"+ this.eventname + " - " + this.eventnum + "</a></caption>";
		output += "<thead>";
		output += "<tr>";
        output += "<th class='swimmer'>Swimmer</th>";
        output += "<th class='age'>Age</th>";
        output += "<th class='team'>Team</th>";
        output += "<th class='score dive-score'>Dive Score</th>";
        output += "<th class='points'>Points</th>";
        output += "</tr></thead><tbody>";

		output += printEachDive(this);

		output += "</tbody>";
		output += "</table>";
	});	
	
	return output;
}

//--------------------------------
// Each Dive
//--------------------------------
function printEachDive(dive) {
	output = "";
	var count = 0;
	if (!dive.divers) { return output; }
	$wpjQ.each(dive.divers, function() {
    	var swimage="";
		var teamwww = getPathHref(teamsInfo[this.team_abbrev]);
		var diverwww = getSwimmerHref(this.diver_id);
		if (count % 2 != 0) {
			output += "<tr class='even'>";
		} else { 
			output += "<tr class='odd'>";
		}
		output += "<td class='swimmer'>" + "<a href='"+diverwww+"'>"+this.diver_name + "</a></td>";
		if (this.diver_age.length > 0 && this.diver_age != "0"){
		    swimage=this.diver_age;
    	}
    	else if (this.hsclass.length > 0){
    	    swimage=this.hsclass;
    	}
    	else{
    	    swimage='';
    	}
		output += "<td class='age'>" + swimage  + "</td>";
		output += "<td class='team'>" + "<a href='"+teamwww+"'>"+ this.team_abbrev + "</a></td>";
		output += "<td class='score dive-score'>" + this.dive_score + "</td>";
		output += "<td class='points'>" + Math.round(this.points*10)/10 + "</td>";
		output += "</tr>";
		count++;
	});
	return output;
}
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
function in_array(needle,haystack){
// copy of the php function same name
// no error check to see if haystack is actually an array. 

	for (var i = 0;i<haystack.length;i++){
		if (haystack[i] == needle){
			return true;
			}
		}
	return false;

}


