//////////////////////////////////////////////////////////
// http://dwts.info
// Created by Raphael Pungin (raphael@raphaelpungin.com)
// Copyright 2006, All Rights Reserved
// Cannot be duplicated without author's permission
//////////////////////////////////////////////////////////
var bgcolor="#ededed";
var oddRowColor="#e7d6fe";
var evenRowColor="#eefeb8";
var highestScoreColor="#ff6372";
var lowestScoreColor="#84d9fe";
var averageScoreColor="#f6fa5e";
var scoreColor="#fb8e71";

var MENU_VIDEOS=0;
var MENU_LEADERBOARD=1;
var MENU_VOTE_RESULTS=2;
var MENU_RESULT_SHOW=3;
var MENU_WEEKLY_PROGRESS=4;
var MENU_PERFORMERS=5;
var MENU_DANCES=6;
var MENU_SONGS=7;
var MENU_STATS=8;
var MENU_FACEBOOK=9;

var CELEBRITY="Celebrity";
var PRODANCER="Professional Dancer";
var GUEST_PERFORMER="Guest Performer";
var HOST="Show Host";

var group = "Group Dance";

var PERSON_ID=0;
var PERFORMANCE=1;
var TOTAL_SCORE=2;
var SCORES=3;
var DANCE=4;
var SONG = 5;
var YOUTUBE_ID = 6;

var leftHalfWidth = 450;
var dwtsVideoWidth=320;
var dwtsVideoHeight=240;
var statsNameWidth = leftHalfWidth-100;
var mainDivWidth=dwtsVideoWidth+leftHalfWidth;
var mainDivHeight = dwtsVideoHeight+190;
var currentSelectionIndex = -1; // the currently selected couple in the list on the right
var currentMenuIndex=-1;

var statsShows = 0;
var statsPerformances = 0;
var statsCelebs = new Array();
var statsPros = new Array(); 
var statsDances = new Array();
var statsPerformers = new Array();
var statsScores = new Array();
var statsAvgScores = new Array();
var statsComputedAvgScores = new Array();
var statsMissingVideos = new Array();
var statsJudgesTotalScores = new Array();
var statsTotalScorePoints = 0;
var statsMissingJudgesScores = new Array();
var statsMissingSongs = new Array();

function getPersonId(fullName) {
	var spaceIndex = fullName.lastIndexOf(" ");
	var lastName = fullName.substr(spaceIndex+1);
	lastName = lastName.replace(/'/g,"");
	var id = fullName.substr(0,1)+lastName.substr(0,5);
	return id.toLowerCase();
}

function getBioUrl(season, fullName) {
	var s = fullName.replace(/ /g,"_");
	s = s.replace(/\./g,"");
	s = s.replace(/'/g,"");
	var url='http://abc.go.com/primetime/dancing/bios/'+season+'/'+s.toLowerCase()+'.html';
	return url;
}
	

function getPollFormName(season, week) {
  return "dwtspoll_"+season+"_"+week;
}

function setStyles() {
	var html = '<style>.dwtsmenu {position:relative;top:3px;display:inline;padding-left:7px;padding-right:7px;border-bottom-width:3px;border-left-width:3px;border-right-width:3px;}'
	+'.dwtsmenuSelected {font-weight:bold;position:relative;top:3px;display:inline;padding-left:7px;padding-right:7px;background-color:'+bgcolor+';'
	+'border-top-width:1px;border-left-width:1px;border-right-width:1px;'
	+'border-top-style:groove;border-left-style:groove;border-right-style:groove;}'
	+'.dwtsMain {background-color:'+bgcolor+';width:'+(mainDivWidth+10)+'px;height:'+(mainDivHeight+5)+'px;'
	+'border-top-width:1px;border-bottom-width:1px;border-left-width:1px;border-right-width:1px;'
	+'border-top-style:groove;border-bottom-style:groove;border-left-style:groove;border-right-style:groove;}'
	+'.dwtsmenulink {text-decoration:none;}'
	+'</style>';
	document.write(html);
}

function weekSelector(maxWeek) {
	var html = '<select id="weekSelector" onchange="selectWeek(this.options[this.selectedIndex].value)">';
	for (var w = 1; w<=maxWeek; w++) {
		var showName = "Week "+w;
		var url=document.location.href;
		if (url.indexOf("dwts") >= 0 && currentSeason == 1 && w == 7) showName = "Dance-Off"; 
		else if (url.indexOf("dwts") >= 0 && currentSeason == 2 && w == 9) showName = "Grand Finale";
		else if (url.indexOf("scd") >=0 && currentSeason == 5 && w == 13) showName = "Christmas Special";
		else if (url.indexOf("scd") >=0 && currentSeason == 4 && w == 13) showName = "Christmas Special";
		else if (url.indexOf("scd") >=0 && currentSeason == 3 && w == 11) showName = "Christmas Special";
		else if (url.indexOf("scd") >=0 && currentSeason == 2 && w == 9) showName="Christmas Special";
		else if (url.indexOf("tzg") >=0 && currentSeason == 3 && w == 11) showName="Final Of Finals";
		html += '<option value="'+w+'">'+showName+'</option>';
	}
	html += '<option value="eliminations">Eliminations</options>';
	html +='</select>';
	document.getElementById("weekSelectorDiv").innerHTML=html;
}

function dwtsInfo() {
	computeStats();
	document.write(getAllShows());
  var s=getParamValue(document.location.href,"s"); //season
  var w=getParamValue(document.location.href,"w"); //week
  var v=getParamValue(document.location.href,"v"); //video
  var p=getParamValue(document.location.href,"p"); //performance
	if (s=="" || w=="" || v=="" || p=="") {
		selectSeason(shows.length-1);
		selectWeek(shows[currentSeason].length-1);
		dwtsVideos();
	} else {
		selectSeason(s);
		selectWeek(w);
		//todo...
	}
  	
}
			
function getAllShows() {
	if (document.location.href.indexOf("pungin") == -1) return "";
	setStyles();
	var html = '<table border="3" ><tr><td>'//main table
	+'<table cellspacing="0" cellpadding="0" width="100%"><tr><td bgcolor="#89fde5" align="center">' // tabs
  +      '<div style="display:inline; padding:4px;">'
	+        '<select id="seasonSelector" onchange="selectSeason(this.options[this.selectedIndex].value)">';
	
	for (var i=1; i<shows.length; i++) {
		html += '<option value="'+i+'">Season '+i+'</option>';
	}
	html +='</select>'
	+      '</div>'
	+      '<div id="weekSelectorDiv" style="display:inline; padding:4px;"></div>'
	+      '<br>' 
	+      '<div id="dwtsmenu0" class="dwtsmenuSelected"><a class="dwtsmenulink" href="javascript:dwtsVideos()">Videos</a></div>'
	+      '<div id="dwtsmenu1" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsLeaderboard()">Leaderboard</a></div>'
	+      '<div id="dwtsmenu2" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsVoteResults()">Vote Results</a></div>'
	+      '<div id="dwtsmenu3" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsResultsShow()">Results Show</a></div>'
	+      '<div id="dwtsmenu4" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsWeeklyProgress()">Progress</a></div>'
	+  '</td><td valign="bottom" align="center" bgcolor="#e8a3fd">All Shows<br>'
	+'<div id="dwtsmenu5" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsPerformers()">Performers</a></div>'
	+'<div id="dwtsmenu6" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsDances()">Dances</a></div>'
	+'<div id="dwtsmenu7" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsSongs()">Songs</a></div>'
	+'<div id="dwtsmenu8" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsStats()">Stats</a></div>'
	+'<div id="dwtsmenu9" class="dwtsmenu"><a class="dwtsmenulink" href="javascript:dwtsFacebook()">Facebook</a></div>'
	+'</td></tr></table>' // tabs
	+'<div id="dwtsMain" class="dwtsMain"></div>'
	+'</td></tr></table>'; // main table
	return  html;
}

function selectSeason(season) {
	if (shows[season].length == 0) {
		alert("Season "+season+" is not available.");
		return;
	}
	currentSeason = season;
	document.getElementById("seasonSelector").selectedIndex = season -1;
	weekSelector(shows[season].length-1);
	selectWeek(1);
}

function selectWeek(week) {
	if (week == "eliminations") {
		eliminations(currentSeason);
		return;
	}
	currentWeek=week;
	document.getElementById("weekSelector").selectedIndex = week -1; 
	currentShow = shows[currentSeason][currentWeek];
	switch(currentMenuIndex) {
		case MENU_VIDEOS: dwtsVideos();break;
		case MENU_LEADERBOARD: dwtsLeaderboard(); break;
		case MENU_VOTE_RESULTS: dwtsVoteResults(); break;
		case MENU_RESULT_SHOW: dwtsResultsShow(); break;
		case MENU_WEEKLY_PROGRESS: dwtsWeeklyProgress(); break;
	}
	clearSelection();
}

function clearSelection() {
	currentSelectionIndex = -1;
}

function switchMenu(menuIndex) {
	if (currentMenuIndex != -1) document.getElementById("dwtsmenu"+currentMenuIndex).className="dwtsmenu";
	document.getElementById("dwtsmenu"+menuIndex).className="dwtsmenuSelected";
	currentMenuIndex=menuIndex;
}	

function scoreSortMethod(a, b) {
	return b[TOTAL_SCORE] - a[TOTAL_SCORE];
}

// Returns an array of [personId,totalScore,performanceCount] sorted by totalScore in descending order
function sortScores(season, week) {
	var show = shows[season][week];
	var combinedPerformances = new Array();
	var currentPersonId = show[0][PERSON_ID];
	var scoreForAllPerf = 0;
	var combinedPerformancesIndex = 0;
	var performanceCount = 0;
	for (var i = 0; i<show.length; i++) {
		var coupleData = show[i];
		var personId = coupleData[PERSON_ID];
		var score = coupleData[TOTAL_SCORE];
		if (currentPersonId == personId) {
			scoreForAllPerf += score;
			performanceCount++;
		} else {
			combinedPerformances[combinedPerformancesIndex++] = [currentPersonId, scoreForAllPerf, performanceCount];
			scoreForAllPerf = score;
			performanceCount = 1;
			currentPersonId = personId;
		}
	}
	combinedPerformances[combinedPerformancesIndex] = [currentPersonId, scoreForAllPerf, performanceCount];
	combinedPerformances.sort(sortTotalScoresMethod);
	return combinedPerformances;
}

function dwtsLeaderboard() {
	switchMenu(MENU_LEADERBOARD);
	var sortedShowData = sortScores(currentSeason, currentWeek);
	var highestScore = sortedShowData[0][1];
	var html = '<div align="center"><table>';
	for (var i=0; i<sortedShowData.length; i++) {
		var coupleData = sortedShowData[i];
		var personId = coupleData[0];
		if (personId == "group") continue;
		var score = coupleData[1];
		var performanceCount = coupleData[2];
		var coupleNames = getCoupleNamesWithLinks(currentSeason, currentWeek, personId);
		html += '<tr><td align="left">';
		html += getCoupleIcon(currentSeason, currentWeek, personId, 33, "")+'</a>&nbsp;'+coupleNames+'<br>&nbsp;&nbsp;';
		for (var p = 1; p<=performanceCount; p++) {
			html += '<a style="font-size:8pt" href="javascript:showVideo('+currentSeason+','+currentWeek+',\''+personId+'\','+p+')">(Video'+ (performanceCount > 1 ? " "+p : "")+')</a> ';
		}
		html += '</td><td align="left">'+getTotalScoreGraph(score, highestScore, "Total Score", 210);
		html += '</td></tr>';
	}
	html += '</table></div>';
	document.getElementById("dwtsMain").innerHTML=html;
}

function sortTotalScoresMethod(a, b) {
	return b[1] - a[1];
}

function getTotalScoresArray() {
	//Aggregate scores for all weeks so far
	var totalScoresByPersonId = new Array();
	for (var w = currentWeek; w >=1; w--) {
		var combinedScores = sortScores(currentSeason, w);	
		for (var i = 0; i<combinedScores.length; i++) {
			var scoreData = combinedScores[i];
			var personId = scoreData[0];
			var totalScore = scoreData[1];
			var existingScore = totalScoresByPersonId[personId];
			if (typeof existingScore == "undefined") {
				totalScoresByPersonId[personId] = [personId,totalScore];
			} else {
				totalScoresByPersonId[personId][1] = existingScore[1]+totalScore;
			}
		}
	}
	
	//Create total scores array for the current week.
	var distinctPersonIds = getDistinctPersonIds(currentSeason, currentWeek);
	var totalScoresArray = new Array();
	for (var i = 0; i<distinctPersonIds.length; i++) {
		totalScoresArray[i]=totalScoresByPersonId[distinctPersonIds[i]];
	}
	totalScoresArray.sort(sortTotalScoresMethod);
	return totalScoresArray;
}

function getDistinctPersonIds(season, week) {
	var showData = shows[season][week];
	var distinctPersonIds = new Array();
	var distinctPersonIdsIndex = 0;
	for (var i = 0; i<showData.length; i++) {
		var personId = showData[i][PERSON_ID];
		if (indexOf(distinctPersonIds, personId) == -1) {
			distinctPersonIds[distinctPersonIdsIndex++] = personId;
		}	
	}
	return distinctPersonIds;
}


		
function dwtsWeeklyProgress() {
	switchMenu(MENU_WEEKLY_PROGRESS);
	var totalScoresArray = getTotalScoresArray();
	
	var html='<table><tr height="20">'
	+'<td align="center"><b>Total Scores Up To Week '+currentWeek+'</b></td>'
	+'<td valign="top" align="center" width="'+dwtsVideoWidth+'">'
	+'<b>Progress Up To Week '+currentWeek+'</b></td>'
	+'</tr><tr>'
	+'<td valign="top"><div style="text-align:left; width:'+(leftHalfWidth-150)+'px;height:'+(mainDivHeight-23)+'px;overflow:auto;position:relative;">';
	var highestScore = totalScoresArray[0][1];
	for (var i=0; i<totalScoresArray.length; i++) {
		var personId = totalScoresArray[i][0];
		if (personId == "group") continue;
		var totalScore = totalScoresArray[i][1];		

		html +='<div style="border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'"><table><tr><td>'
		html +='<a href=\'javascript:coupleWeeklyProgress("'+personId+'",'+i+')\'>';
		html +=getCoupleIcon(currentSeason, currentWeek, personId, 50, "Click to to see weekly progress")+'</a></td><td>';
		html +='<span style="font-size:8pt">&nbsp;'+getCoupleNamesWithLinks(currentSeason, currentWeek, personId)+'<br><br>';
		html +=getTotalScoreGraph(totalScore, highestScore, "Total Score", 210);
		html +='</td></tr></table></div>';
	}
	html += '</td>';
	html += '<td><div id="selectedContent" style="text-align:left; overflow:auto; width:'+(dwtsVideoWidth+150)+'px;height:'+(mainDivHeight-23)+'px;"></div></td>';
	html += '</tr></table>';	
	document.getElementById("dwtsMain").innerHTML=html;
	coupleWeeklyProgress(totalScoresArray[0][0],0); //display  the first couple in the list
}

function coupleWeeklyProgress(personId, selectedIndex) {
	var scoreSum = 0, scoreCount = 0;
	var weeklyHtml = '<br clear="all"><table>';
	for (var w = 1; w<= currentWeek; w++) {
		var showData = shows[currentSeason][w];
		var couplePerformances = getCoupleData(showData, personId);
		for (var p = 0; p<couplePerformances.length; p++) {
			var coupleData = couplePerformances[p];
			var scores = coupleData[SCORES];
			var totalScore = coupleData[TOTAL_SCORE];
			if (totalScore > 0) {
				scoreSum+=totalScore;
				scoreCount++;
			}
			var dance = coupleData[DANCE];
			weeklyHtml += '<tr><td><span style="font-size:8pt">Wk. '+w+' ';
			weeklyHtml += '<a href="javascript:showVideo('+currentSeason+','+w+',\''+personId+'\','+(p+1)+')">'+getDanceLink(dance)+'</span></td><td>'+getScoreGraph(totalScore, scores)+'</td></tr>';			
		}
	}
	weeklyHtml += '</table>';
	var averageScore = scoreSum/scoreCount;
	var html = getCoupleIcon(currentSeason, currentWeek, personId, 50, "")
		+'<b>'+getCoupleNamesWithLinks(currentSeason, currentWeek, personId)+'</b>'
		+'<br>Average score so far: '+averageScore.toFixed(2)+'</span>'
	
	html += weeklyHtml;

	setSelectedContent(html, selectedIndex);
}

//returns an array of couple data for each performance in the given show
function getCoupleData(showData, personId) {
	var couplePerformances = new Array();
	var j = 0;
	for (var i = 0; i<showData.length; i++) {
		var coupleData = showData[i];
		if (coupleData[PERSON_ID] == personId) {
			couplePerformances[j++] = coupleData;
		}
	}
	return couplePerformances;
}

function showVideo(season, week, personId, performance) {
	selectSeason(season);
	selectWeek(week);
	var autoPlayIndex = getAlphaIndex(season, week, personId, performance);
	dwtsVideosPlay(autoPlayIndex);
}

function dwtsVideos() {
	dwtsVideosPlay(-1);
}
	
function dwtsVideosPlay(autoPlayIndex) {
	switchMenu(MENU_VIDEOS);
	document.getElementById("dwtsMain").innerHTML=showVideos();
	if (autoPlayIndex >=0) {
		coupleVideoPlayer(autoPlayIndex);
	}
}

function dwtsVoteResults() {
	var pollId = getPollId(currentSeason, currentWeek);
	if (pollId == null || pollId == "") {
		alert("No vote results available for season "+currentSeason+" week "+currentWeek+".");
		return;
	}
	switchMenu(MENU_VOTE_RESULTS);
	var height= 60 + (getNumberOfContestants(currentSeason, currentWeek)*27);
	
	var html='<br><br><br><iframe scrolling="no" width="'+mainDivWidth+'" height="'+height+'" frameborder="0" src="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollId+'"></iframe>';
	document.getElementById("dwtsMain").innerHTML=html;	
}	

function getNumberOfContestants(season, week) {
	var showData = shows[season][week];
	var contestants = new Array();
	for (var i = 0; i<showData.length; i++) {
		var personId = showData[i][PERSON_ID];
		if (personId != "group") {
			addToSet(contestants, personId);
		}
	}
	var numberOfContestants = contestants.length;
	return numberOfContestants;
}
	
function dwtsResultsShow() {
	if (resultShows[currentSeason].length <= currentWeek || resultShows[currentSeason][currentWeek] == null) {
		alert("Result show for season "+currentSeason+" week "+currentWeek+" is not available."); 
		if (currentMenuIndex == MENU_RESULT_SHOW) {
			dwtsVideos();
		}
		return;
	}
	switchMenu(MENU_RESULT_SHOW);
	document.getElementById("dwtsMain").innerHTML=resultShow();
}

function getPollId(season, week) {
	return dwtsPollIds[season][week-1];
}

function showVideos() {
	var html='<table><tr>'
	+'<td><div style="text-align:left; width:'+leftHalfWidth+'px; height:'+mainDivHeight+'px; overflow:auto; position:relative;">';
	for (var i=0; i<currentShow.length; i++) {
		var currentCoupleData = currentShow[i];
		var personId = currentCoupleData[PERSON_ID];
		var dance = currentCoupleData[DANCE];
		var totalScore = currentCoupleData[TOTAL_SCORE];
		var scores = currentCoupleData[SCORES];
		var song = currentCoupleData[SONG];
		var youTubeId = getYouTubeId(currentCoupleData);
		
		html +='<div style="border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'"><table><tr><td>'
		html +='<a href="javascript:coupleVideoPlayer('+i+')">';
		if (youTubeId != "missing") {
			html +=getCoupleIcon(currentSeason, currentWeek, personId, 50, "Click to play video")+'</a></td><td>';
		} else {
			html +='<img src="http://raphaelpungin.com/dance/dwts/novideo.gif" width="50" height="50" align="left" hspace="2" />';
		}
		html +='<span style="font-size:8pt">'+getCoupleNamesWithLinks(currentSeason, currentWeek, personId)+' - '+getDanceLink(dance)+'<br>';
		html +='Song: '+song+'<br>';
		html +=getScoreGraph(totalScore, scores);
		html +='</span></td></tr></table></div>';
	}
	html += '</div></td><td valign="top" width="'+dwtsVideoWidth+'">'
	+'<div id="selectedContent" style="width:'+dwtsVideoWidth+'px;height:'+mainDivHeight+'px;text-align:center">'
	+'<b><br><br><br>Click on the couple\'s photo to play the video</b>'
	+'<br><br><br><br><img src="'+rootUrl+'logo.jpg" /></div>'
	+'</td></tr></table>';	
	return html;
}


function resultShow() {
	var show = resultShows[currentSeason][currentWeek];
	var html='<table><tr>'
	+'<td><div style="width:'+leftHalfWidth+'px;height:'+mainDivHeight+'px;overflow:auto;position:relative;">';
	if (show.length > 1) {
		html +='<b>Videos:</b><br>';
	}
	for (var i=1; i<show.length; i++) {
		var videoData = show[i];
		var videoId = videoData[0];
		var videoTitle = concatNames(videoData[1], videoData[2]);
		var dance = videoData[3];
		if (videoId.indexOf("|") == -1) {
			var videoThumbnail = rootUrl+currentSeason+'/videos/'+videoId+'.jpg';
		} else {
			var videoThumbnail = videoId.split("|")[1];
		}
		html +='<div style="text-align:left; border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'"><table><tr><td>'
		html +='<a href="javascript:proVideoPlayer('+i+')">';
		html +='<img src="'+videoThumbnail+'" align="left" width="100" height="75"> '+videoTitle+'</a><br>'+dance ;
		html +='</td></tr></table></div>';
	}
	html += getEliminatedCouple();
	html += '</div></td><td valign="top" width="'+dwtsVideoWidth+'">'
	+'<div id="selectedContent" style="width:'+dwtsVideoWidth+'px;height:'+mainDivHeight+'px;text-align:center"></div>'
	+'</td></tr></table>';
	return html;	
}

function getEliminatedCouple() {
	var eliminatedPersonId = resultShows[currentSeason][currentWeek][0];
	if (typeof eliminatedPersonId == "undefined" || eliminatedPersonId == "") {
		return "";
	}
	
	var eliminatedCouple = getCoupleNamesWithLinks(currentSeason, currentWeek, eliminatedPersonId);
	
	var html = '<span style="color:red;font-weight:bold">Eliminated Couple:</span><br>'+getCoupleIcon(currentSeason, currentWeek, eliminatedPersonId, 75, "")+ eliminatedCouple+'<br clear="all">';
	return html;
}

function getCoupleIcon(season, week, personId, size, alt) {
	if (season == 3 && week == 11 && personId == "akwasn") personId = "akwasn2";
	return '<img alt="'+alt+'" width="'+size+'" height="'+size+'" align="left" bordercolor="black" border="1" vspace="2" hspace="2" src="'+rootUrl+season+'/images/c_'+personId+'.jpg">';
}

function getCoupleNamesWithLinks(season, week, personId, firstNameOnly) {
	if (personId == "group") return group;
	var couple = getCouple(season, week, personId);
	var html = getPerformerLink(couple[0], null, firstNameOnly)+' & '+getPerformerLink(couple[1], null, firstNameOnly);
	return html;
}	

function getCoupleNames(season, week, personId) {
	if (personId == "group") return group;
	
	var couple = getCouple(season, week, personId);
  return couple[0]+' & '+couple[1];
}

function concatNames(n1, n2) {
	if (n2 != "") {
		return n1+" & "+n2;
	} else {
		return n1;
	}
}

function concatNamesWithLinks(n1, n2) {
	if (n2 == "") {
		return n1;
	} else {
		return '<a href="javascript:dwtsPerformers(\''+ n1 + '\')">' + n1 + '</a>'
			+' & <a href="javascript:dwtsPerformers(\''+ n2 + '\')">' + n2 + '</a>';
	}	
}
	
function getScoreGraph(totalScore, scores) {
	if (totalScore == 0) return"";
	var width=9*totalScore;
	var html ='<table bgcolor="#fb8e71" border="2" border-color="black" style="border-collapse:collapse" width="'+width+'"><tr><td style="font-size:8pt" wrap="no">Score: '+scores+' ('+totalScore+')</td></tr></table>';
	return html;
}

function getTotalScoreGraph(totalScore, highestScore, label, totalWidth, color) {
	if (totalScore == 0) return "";
	var multiplier = totalWidth / highestScore;
	var width=multiplier*totalScore;
	if (color == null) color = scoreColor;
	var html ='<table bgcolor="'+color+'" border="2" border-color="black" style="border-collapse:collapse" width="'+width+'">'
	+'<tr><td style="font-size:8pt" wrap="no">'+label+': '+totalScore+'</td></tr></table>';
	return html;
}	
function getAlphaIndex(season, week, personId, performance) {
	var showData = shows[season][week];
	for (var i = 0; i<=showData.length; i++) {
		var coupleData = showData[i];
		if (coupleData[PERSON_ID] == personId && coupleData[PERFORMANCE]==performance) {
			return i;
		}
	}
	return -1;
}
	
function getCouple(season, week, personId) {
	if (personId == "group") {
		return [group];
	}
	
	//In tzg s3 w11 (final of finals) Aleksandra Kwasniewska danced with Michal Skawinski
	if (document.location.href.indexOf("tzg")>=0 && season == 3 && week == 11 && personId == "akwasn") {
		return ["Aleksandra Kwasniewska","Michal Skawinski"];
	}
	
	for (var s = season; s>=0; s--) {
		var seasonCouples = couples[s];
		for (var i = 0; i<seasonCouples.length; i++) {
			var couple = seasonCouples[i];
			if (getPersonId(couple[0]) == personId) {
				return couple;
			}
		}
	}
	alert("Invalid personId "+personId);
	return null;
}

function getCelebName(personId) {
	for (var s = 1; s<couples.length; s++) {
		var seasonCouples = couples[s];
		for (var i = 0; i<seasonCouples.length; i++) {
			var couple = seasonCouples[i];
			var celebName = couple[0];
			if (getPersonId(celebName) == personId) {
				return celebName;
			}
		}
	}
	alert("Invalid personId "+personId);
}
					
	

function getVideoHeader(season, week, personId, totalScore, scores, dance, song) {
	var coupleNames = getCoupleNamesWithLinks(season, week, personId);
	var html='<b>'+coupleNames+'</b><br><span style="font-size:8pt"><b>Dance:</b> '+getDanceLink(dance);
	if (song != "") html +='<br><b>Song:</b> '+song;
	if (totalScore > 0) html += '<br><b>Scores:</b> '+scores+' ('+totalScore+')';
	html += '</span>';
	return html;
}
	
function coupleVideoPlayer(coupleIndex) {
	var pollId = getPollId(currentSeason, currentWeek); 
	var currentCoupleData = currentShow[coupleIndex];
	var personId = currentCoupleData[PERSON_ID];
	var performance = currentCoupleData[PERFORMANCE];
	var totalScore = currentCoupleData[TOTAL_SCORE];
	var scores = currentCoupleData[SCORES];
	var dance = currentCoupleData[DANCE];
	var song = currentCoupleData[SONG];
	var youTubeId = getYouTubeId(currentCoupleData);
	var html = getVideoPlayerHtml(currentSeason, currentWeek, personId,performance, totalScore, scores, dance, song, pollId, youTubeId);
	setSelectedContent(html, coupleIndex);
}	

function getYouTubeId(data) {
	var youTubeId = "";
	if (data.length >= YOUTUBE_ID+1) {
		youTubeId = data[YOUTUBE_ID];
	}
	return youTubeId;
}

function isResultShow(id) {
	return id.indexOf("-") >=0 || id.indexOf("_") >= 0;
}

function showSongVideo(season, week, personId, performance, selectedIndex) {
	if (!isResultShow(personId)) {
		var show = shows[season][week];
		var coupleData = getCoupleData(show, personId);
		var performanceData = coupleData[performance-1];
		var totalScore = performanceData[TOTAL_SCORE];
		var scores = performanceData[SCORES];
		var dance = performanceData[DANCE];
		var song = performanceData[SONG];
		var youTubeId = getYouTubeId(performanceData);
		var html = getVideoPlayerHtml(season, week, personId, performance, totalScore, scores, dance, song, "", youTubeId);
	} else {
		var resultShow = resultShows[season][week];
		var coupleData = resultShow[performance];
		var videoFile = coupleData[0];
		var videoTitle = concatNamesWithLinks(coupleData[1], coupleData[2]);
		var dance = coupleData[3];
		var song = coupleData[4];
		var youTubeId = "";
		var html = getProVideoPlayerHtml(season, videoFile, videoTitle, dance, song, youTubeId);
	}	
	setSelectedContent(html, selectedIndex);
}	

function getVoteIndex(season, week, personId) {
	var showData = shows[season][week];
	var voteIndex = 0;
	var lastPersonId = "";
	for (var i = 0; i<=showData.length; i++) {
		var coupleData = showData[i];
		currentPersonId = coupleData[PERSON_ID];
		if (currentPersonId != lastPersonId) {
			voteIndex++;
			lastPersonId = currentPersonId;
			if (currentPersonId == personId) {
				return voteIndex;
			}
		}
	}
	return -1;
}
		
function getVideoPlayerHtml(season, week, personId, performance, totalScore, scores, dance, song, pollId, youTubeId){
	var pollFormName = getPollFormName(season, week);
	var coupleNames = getCoupleNames(season, week, personId);
	var alphaIndex = getAlphaIndex(season, week, personId, performance);
	var voteIndex = getVoteIndex(season, week, personId);
	var html = getVideoHeader(season, week, personId, totalScore, scores, dance, song)+'<br>';

	if (youTubeId == "missing") {
		html += getMissingVideoForm(season, week, coupleNames, dance);
	} else {
		if (youTubeId != "") {
			html += embedYouTubeVideo(youTubeId, dwtsVideoWidth, dwtsVideoHeight+24, true);
		} else {
			html += embedRealVideo(rootUrl+season+"/videos/", week+"-"+performance+"-"+personId, dwtsVideoWidth, dwtsVideoHeight, true, true);
		}
		if (typeof pollId != "undefined" && pollId != "" && totalScore > 0) {
			html += '<form name='+pollFormName+' action="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollId+'" method="post">';
			html += '<input type=hidden name="poll_answer">';
			html += '<input type="button" style="font-size:8pt" value="Vote for this couple..." onClick=\'setResult("'+pollFormName+'","'+voteIndex+'","'+coupleNames+'")\'></form>';
		} else {
			html += '<br>';
		}
		if (youTubeId == "") {
			html += realPlayerLink();
		}
	}

	if (personId != "group" && scores == "") {
		html += getMissingScoresForm(season, week, coupleNames, dance);
	}
	if (song == "" || song.toLowerCase() == "*unknown*") {
		html += getMissingSongForm(season, week, coupleNames, dance);
	}
	
	if (youTubeId != "") {
		html += getBrokenVideoForm(youTubeId);
	}
	return html;	
}

function getMissingVideoForm(season, week, couple, dance) {
	couple = couple.replace("&","and");
	var url = document.location.href;
	var type = url.indexOf("scd") != -1 ? "SCD"	: url.indexOf("tzg") != -1 ? "TZG" : "DWTS";
	var html ='<iframe src="http://raphaelpungin.com/dance/dwts/missing_video.shtml?t='+type
	+'&s='+season+'&w='+week+'&c='+couple+'&d='+dance+'" frameborder="0" scrolling="no" width="'+dwtsVideoWidth+'" height="'+(mainDivHeight-180)+'" />';
	return html;
}

function getMissingSongForm(season, week, couple, dance) {
	couple = couple.replace("&","and");
	var url = document.location.href;
	var type = url.indexOf("scd") != -1 ? "SCD"	: url.indexOf("tzg") != -1 ? "TZG" : "DWTS";
	var html ='<iframe marginwidth="0" marginheight="0" src="http://raphaelpungin.com/dance/dwts/missing_song.shtml?t='+type
	+'&s='+season+'&w='+week+'&c='+couple+'&d='+dance+'" frameborder="0" scrolling="no" width="'+dwtsVideoWidth+'" height="'+32+'" />';
	return html;
}

function getBrokenVideoForm(videoId) {
	var url = document.location.href;
	var type = url.indexOf("scd") != -1 ? "SCD"	: url.indexOf("tzg") != -1 ? "TZG" : "DWTS";
	var html ='<iframe marginwidth="0" marginheight="0" src="http://raphaelpungin.com/dance/dwts/broken_video.shtml?t='+type
	+'&v='+videoId+'" frameborder="0" scrolling="no" width="'+dwtsVideoWidth+'" height="32" />';
	return html;
}	
	
function getMissingScoresForm(season, week, couple, dance) {
	couple = couple.replace("&","and");
	var url = document.location.href;
	var type = url.indexOf("scd") != -1 ? "SCD"	: url.indexOf("tzg") != -1 ? "TZG" : "DWTS";
	var html ='<iframe marginwidth="0" marginheight="0" src="http://raphaelpungin.com/dance/dwts/missing_scores.shtml?t='+type
	+'&s='+season+'&w='+week+'&c='+couple+'&d='+dance+'" frameborder="0" scrolling="no" width="'+dwtsVideoWidth+'" height="'+64+'" />';
	return html;
}

function proVideoPlayer(proVideoIndex) {
	var show = resultShows[currentSeason][currentWeek];
	var videoData = show[proVideoIndex];
	var videoFile = videoData[0];
	var videoTitle = concatNamesWithLinks(videoData[1], videoData[2]);
	var dance = videoData[3];
	var song = videoData[4];
	var html = getProVideoPlayerHtml(currentSeason, videoFile, videoTitle, dance, song);
	setSelectedContent(html, proVideoIndex); 
}

function getProVideoPlayerHtml(season, videoFile, videoTitle, dance, song) {
	var html ='<b>'+videoTitle+'</b><br><span style="font-size:8pt">';
	if (dance != "") html += '<b>Dance:</b> '+getDanceLink(dance);
	if (song != "") html += '<br><b>Song:</b> '+song;
	html +='</span>';
	if (videoFile.indexOf("|") == -1) {
		html += embedRealVideo("http://raphaelpungin.com/dance/dwts/"+season+"/videos/",videoFile,dwtsVideoWidth, dwtsVideoHeight, true, true);
		html += '<br><br>'+realPlayerLink();
	} else {
		var youTubeId = videoFile.split("|")[0];
		html += embedYouTubeVideo(youTubeId, dwtsVideoWidth, dwtsVideoHeight+24, true);
	}
	return html;
}
	
function setSelectedContent(html, i) {
	document.getElementById("selectedContent").innerHTML=html;
	var element = document.getElementById("selectionList"+i);
	if (element != null) {
		element.style.background="#f8fb87";
	}
	if (currentSelectionIndex != -1) {
		element = document.getElementById("selectionList"+currentSelectionIndex);
		if (element != null) {
			element.style.background="";	
		}		
	}		
	currentSelectionIndex = i;
}

function realPlayerLink() {
	return 'Don\'t see the video? <a href="http://real.com/player" target="_blank"><img src="http://raphaelpungin.com/images/realplayer.jpg" border="0" align="top"></a>';
}

function getPerformersSelectorHtml() {
	var html ='<b>Performer:</b> <select id="performersSelector" onChange="selectPerformer(this.options[this.selectedIndex].value)">';
	var distinctPerformers = getDistinctPerformers();
	for (var i=0; i<distinctPerformers.length; i++) {
		var name = distinctPerformers[i];
		html += '<option value="'+name+'">'+name+'</option>';
	}
	html += '</select>';
	return html;
}

function dwtsPerformers(selectedPerformer) {
	switchMenu(MENU_PERFORMERS);
	var html = '<table><tr><td align="left" width='+leftHalfWidth+'><div align="center">'+getPerformersSelectorHtml()+'</div>';
	html += '<table><tr><td width="50" style="font-size:8pt;" align="left"><b>Show</b></td>'
	+'<td width="300" style="font-size:8pt;" align="left">'	+ '<b>Performers</b></td>'
	+'<td width="80" style="font-size:8pt;" align="left"><b>Dance</b></td>'
	+'<td style="font-size:8pt;" align="right"><b>Score</b></td>'
	+'</tr></table>'
	+ '<div id="performersList" style="width:'+leftHalfWidth+'px;height:'+(mainDivHeight-40)+'px;overflow:auto;"></div>'
	+ '</td><td valign="top" width="'+dwtsVideoWidth+'">'
	+ '<div id="selectedContent" style="width:'+dwtsVideoWidth+'px;height:'+mainDivHeight+'px;text-align:center;overflow:auto"></div>'
	+'</td></tr></table>';
	document.getElementById("dwtsMain").innerHTML=html;
	if (typeof selectedPerformer == "undefined") {
		selectedPerformer = getDistinctPerformers()[0];
	}
	selectPerformer(selectedPerformer);
}

function getDistinctPerformers() {
	var distinctNames = new Array();
	var distinctNameIndex = 0;

	for (var season = 1; season < shows.length; season++) {
		for (var week =1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (performance = 0; performance < showData.length; performance++) {
				var performanceData = showData[performance];
				var personId = performanceData[PERSON_ID];
				var couple = getCouple(season, week, personId);
				for (var c = 0; c < couple.length; c++) {
					var name = couple[c];
					if (indexOf(distinctNames, name) == -1) {
						distinctNames[distinctNameIndex++] = name;
					}
				}
			}
		}
	}		

	for (var season = 1; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week ++) {
			var showData = resultShows[season][week];
			if (typeof showData != "undefined" && showData != null) {
				for (var performance =1; performance < showData.length; performance++) {
					var performanceData = showData[performance];
					if (performanceData[3] != "") {//dance is not empty
						for (var n=1; n<=2; n++) {
							var name = performanceData[n];
							if (name != "" && indexOf(distinctNames, name) == -1) {
								distinctNames[distinctNameIndex++] = name;
							}
						}
					}
				}
			}
		}
	}

	return distinctNames = distinctNames.sort();
}
	

	
function selectPerformer(performer) {
	var performances = findPerformances(performer);
	var html = "";
	for (var i=0; i<performances.length; i++) {
		var performanceData = performances[i];
		var videoTitle = performanceData[0];
		var videoTitle1 = videoTitle.replace(/\'/g,"\\'");
		var season = performanceData[1];
		var week = performanceData[2];
		var performance = performanceData[3];
		var score = performanceData[4];
		if (score == 0) score = "&nbsp;";
		var dance = performanceData[5];
		var song = performanceData[6].replace(/\'/g,"\\'");
		var videoId = performanceData[7];
		html +='<div align="left" style="border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'">'
		+'<table><tr><td width="50" align="left" style="font-size:8pt;">s'+season+' w'+week+'</td>'
		+'<td width="300" align="left" style="font-size:8pt;">'
		+'<a style="font-size:8pt" href="javascript:showDanceVideo(\''+videoTitle1+'\',\''+dance+'\',\''+song+'\','+season+','+week+',\''+videoId+'\','+performance+','+i+')">'
		+videoTitle+'</a></td>'
		+'<td width="80" style="font-size:8pt" nowrap align="left">'+getDanceLink(dance)+'</td>'
		+'<td style="font-size:8pt" nowrap align="right">'+score+'</td>'
		+'</tr></table></div>';
	}
	document.getElementById("performersList").innerHTML = html;
	setSelection(document.getElementById("performersSelector"), performer);
	performerStats(performer);
}

function performerStats(performer) {
	var performerPersonId = getPersonId(performer);
	
	var participantType=GUEST_PERFORMER;
	var participatedInSeasons = new Array();
	var partners = new Array();
	var highestScore = 0, averageScore=0, lowestScore=999, totalScore = 0;
	var numCompPerf = 0;
	var numScoredPerformances = 0;
	var latinScores = new Array();
	var ballroomScores = new Array();
	for (var season = 1; season < shows.length; season++) {
		for (var week =1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (performance = 0; performance < showData.length; performance++) {
				var participated = false;
				var performanceData = showData[performance];
				var celebrityPersonId = performanceData[PERSON_ID];
				if (celebrityPersonId == "group") {
					continue;
				}
				var couple = getCouple(season, week, celebrityPersonId);
				var proPersonId = getPersonId(couple[1]);
				if (performerPersonId == celebrityPersonId) {
					participantType=CELEBRITY;
					addToSet(partners, couple[1]);
					participated = true;
				} else if (performerPersonId == proPersonId) {
					participantType=PRODANCER;
					addToSet(partners, couple[0]);
					participated = true;
				}
				if (participated) {
					numCompPerf++;
					addToSet(participatedInSeasons, season);
					var score = performanceData[TOTAL_SCORE];
					if (score > 0) {
						numScoredPerformances++;
						totalScore += score;
						if (score > highestScore) highestScore = score;
						if (score > 0 && score < lowestScore) lowestScore = score;
						var danceStyle = getDanceStyle(performanceData[DANCE]);
						if (danceStyle == "Latin") {
							addToArray(latinScores, score);
						} else if (danceStyle == "Ballroom") {
							addToArray(ballroomScores, score);
						}
					}
				}
			}
		}
	}
	var numProPerf = 0;
	for (var season = 1; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week++) {
			var showData = resultShows[season][week];
			if (typeof showData == "undefined") continue;
			for (var performance = 1; performance < showData.length; performance++) {
				var coupleData = showData[performance];
				var name1 = coupleData[1];
				var name2 = coupleData[2];
				if (performer == name1 || performer == name2) {
					numProPerf++;	
				}
			}
		}
	}
	var avgScore = totalScore/numScoredPerformances;
	var avgLatinScore = computeAverage(latinScores);
	var avgBallroomScore = computeAverage(ballroomScores);
	var html='<div align="left"><img src="'+rootUrl+'performers/'+performerPersonId+'.jpg" align="left" hspace="2">'
	html += '<b><a href="http://google.com/search?q='+performer+'" target="_blank">'+performer+'</a></b>';
	html += '<br>'+participantType;
	html += '<p>'+getParticipatedInSeasons(participatedInSeasons)+'</p>';
	if (participantType != GUEST_PERFORMER) {
		html += '<p>Partnered with '+getPartners(partners)+'.</p>';
	}
	var row = 0;
	html += '<br clear="all">'+getStatsTableStartHtml();
	if (participantType != CELEBRITY) {
		html += getStatsRow("Number Of Professional Performances", numProPerf, row++);
	}
	if (participantType != GUEST_PERFORMER) {			
		html+=getStatsRow("Number Of Competition Performances",numCompPerf, row++);
		html +='</table>';
		var maxScore = getMaxScore();
		html+='<br>'+getTotalScoreGraph(highestScore, maxScore, "Highest Score", 320, highestScoreColor);
		html+=getTotalScoreGraph(lowestScore, maxScore, "Lowest Score", 320, lowestScoreColor);
		html+=getTotalScoreGraph(avgScore.toFixed(2), maxScore, "Average Score", 320, averageScoreColor);
		html+='<br>'+getTotalScoreGraph(avgBallroomScore.toFixed(2), maxScore, "Avg. Ballroom Score", 320);
		html+=getTotalScoreGraph(avgLatinScore.toFixed(2), maxScore, "Avg. Latin Score", 320);
	
		html += '<br>'+getBallroomLatinGraph(avgBallroomScore,avgLatinScore); 
	}
	html += '</div>';
	document.getElementById("selectedContent").innerHTML = html;
}

function getMaxScore() {
	var maxScore = 0;
	for (var season = 1; season < judges.length; season++) {
		var seasonJudges = judges[season];
		var maxSeasonScore = seasonJudges.length * 10;
		if (maxSeasonScore > maxScore) {
			maxScore = maxSeasonScore;
		}
	}
	return maxScore;
}

function getBallroomLatinGraph(ballroomScore, latinScore) {
	var diff = Math.abs(ballroomScore - latinScore);
	var html='<table width="100%" border="1" bordercolor="black" style="border-collapse:collapse"><tr>';
	html += '<td align="center" width="50%"><b>Ballroom</b></td><td align="center" width="50%"><b>Latin</b></td></tr>';
	html += '<tr><td align="right">';
	if (ballroomScore > latinScore) {
		html += getGraph(diff*20) 
	} else {
		html += '&nbsp;';
	}
	html += '</td><td align="left">';	
	if (ballroomScore < latinScore) {
		html += getGraph(diff*20) 
	} else {
		html += '&nbsp;';
	}
	html +='</td></tr></table>';
	return html;
}

function getGraph(graphValue) {
	var html ='<table bgcolor="#fb8e71" border="2" border-color="black" style="border-collapse:collapse" width="'+graphValue+'"><tr><td style="font-size:8pt" wrap="no">&nbsp;</td></tr></table>';
	return  html;
}

function computeAverage(array) {
	var total = 0;
	for (var i = 0; i<array.length; i++) {
		total += array[i];
	}
	var avg = total/array.length;
	return avg;
}

function getPartners(partners) {
	var html = "";
	for (var i=0; i<partners.length; i++) {
		var partner = partners[i];
		html += getPerformerLink(partner);
		if (i < partners.length-1) {
			html += ', ';
		}
	}
	return html;
}

function getPerformerLink(personName, imgHtml, firstNameOnly) {
	var personName1=personName.replace(/\'/g,"\\'");
	if (firstNameOnly != null && firstNameOnly) {
		personName = personName.substring(0, personName.indexOf(" "));
	}		
	var linkHtml = imgHtml == null ? personName : imgHtml;
	var html = '<a href="javascript:dwtsPerformers(\''+personName1+'\')">'+linkHtml+'</a>';
	return html;
}


function getParticipatedInSeasons(a) {
	var html ="";
	if (a.length > 0) {
		html += "Participated in season"+ ((a.length > 1) ? "s":"")+" "+getElementsWithCommas(a)+".";
	}
	return html;
}

function getElementsWithCommas(a) {
	var s="";
	for (var i = 0; i<a.length; i++) {
		s += a[i];
		if (i < (a.length-1)) {
			s+=", ";
		}
	}
	return s;
}	
function getBioHtml(performer) {
	var personId = getPersonId(performer);
	var html = '<div align="left">';
	if (indexOf(bios, personId) == -1) {
		html += performer+'\'s biography is currently not available. Please check back later.'; 
	}
	else {
		html += '<iframe src="'+rootUrl+'performers/'+personId+'-bio.html" frameborder="0" width="'+dwtsVideoWidth+'" height="'+mainDivHeight+'"></iframe>';
	}
	html +='</div>';
	return html;
}
	
function getDanceLink(dance) {
	var html = '<a href="javascript:dwtsDances(\''+dance+'\')">'+dance+'</a>';
	return html;
}
	
function dwtsDances(selectedDance) {
	switchMenu(MENU_DANCES);
	var html = '<table><tr><td align="left" width='+leftHalfWidth+'><div align="center"><b>Dance:</b> <select id="danceSelector" onChange="selectDance(this.options[this.selectedIndex].value)">'
	if (document.location.href.indexOf("scd") >=0 ) {
		html +='<option value="American Smooth">American Smooth</option>';
	}
	html += '<option value="Argentine Tango">Argentine Tango</option>'
	+ '<option value="Breakdance">Breakdance</option>'
	+ '<option value="Cha Cha">Cha Cha</option>'
	+ '<option value="Foxtrot">Foxtrot</option>'
	+ '<option value="Freestyle">Freestyle</option>'
	+ '<option value="Jive">Jive</option>'
	+ '<option value="Lindy Hop">Lindy Hop</option>'
	+ '<option value="Mambo">Mambo</option>'
	+ '<option value="Pasodoble">Pasodoble</option>'
	+ '<option value="Quickstep">Quickstep</option>'
	+ '<option value="Rumba">Rumba</option>'
	+ '<option value="Salsa">Salsa</option>'
	+ '<option value="Samba">Samba</option>'
	+ '<option value="Tango">Tango</option>'
	+ '<option value="Viennese Waltz">Viennese Waltz</option>'
	+ '<option value="Waltz">Waltz</option>'
	+ '</select></div>'
	+ '<table><tr><td width="300" style="font-size:8pt" align="left"><b>Performed By</b></td><td style="font-size:8pt" align="left"><b>Show</b></td></tr></table>'
	+ '<div id="danceList" style="width:'+leftHalfWidth+'px;height:'+(mainDivHeight-45)+'px;overflow:auto;"></div>'
	+ '</td><td valign="top" width="'+dwtsVideoWidth+'">'
	+ '<div id="selectedContent" style="width:'+dwtsVideoWidth+'px;height:'+mainDivHeight+'px;text-align:center"></div>'
	+'</td></tr></table>';
	
	document.getElementById("dwtsMain").innerHTML=html;
	if (selectedDance == null) {
		selectedDance = document.location.href.indexOf("scd") >=0 ? "American Smooth":"Argentine Tango";
	}
	selectDance(selectedDance);
}

function selectDance(dance) {
	var performances = findDancePerformances(dance);
	var html = "";
	for (var i=0; i<performances.length; i++) {
		var performanceData = performances[i];
		var videoTitle = performanceData[0];
		var videoTitle1 = videoTitle.replace(/\'/g,"\\'");
		var season = performanceData[1];
		var week = performanceData[2];
		var videoId = performanceData[3];
		var song = performanceData[4].replace(/\'/g,"\\'");
		var performance = 0;
		if (performanceData.length == 6) {//competition show
			performance = performanceData[5];
		}
		html +='<div style="border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'">'
		+'<table><tr><td width="300" align="left">'
		+'<a style="font-size:8pt" href="javascript:showDanceVideo(\''+videoTitle1+'\',\''+dance+'\',\''+song+'\','+season+','+week+',\''+videoId+'\','+performance+','+i+')">'
		+videoTitle+'</a></td><td style="font-size:8pt" nowrap align="left">s'+season+ ' w'+week+'</td>'
		+'</tr></table></div>';
	}
	document.getElementById("danceList").innerHTML = html;
	setSelection(document.getElementById("danceSelector"), dance);
	showDanceDescription(dance);
}

function showDanceDescription(dance) {
	var filename = dance.replace(/ /g,"_").toLowerCase();
	var html = '<iframe src="http://raphaelpungin.com/dance/dwts/dances/'+filename+'.html" frameborder="0" width="'+dwtsVideoWidth+'" height="'+mainDivHeight+'"></iframe>';
	document.getElementById("selectedContent").innerHTML = html;
}

function showDanceVideo(videoTitle, dance, song, season, week, videoId, performance, selectedIndex) {
	var html = "";
	if (performance == 0) { // result show
		html += getProVideoPlayerHtml(season, videoId, videoTitle, dance, song);
	} else {
		var showData = shows[season][week];
		var coupleData = getCoupleData(showData, videoId);
		var performanceData = coupleData[performance-1];
		var totalScore = performanceData[TOTAL_SCORE];
		var scores = performanceData[SCORES];
		var song = performanceData[SONG];
		var youTubeId = getYouTubeId(performanceData);
		html += getVideoPlayerHtml(season, week, videoId, performance, totalScore, scores, dance, song, "", youTubeId);
	}
	setSelectedContent(html, selectedIndex);
}

function findDancePerformances(dance) {
	var dancePerformances = new Array();
	var dancePerformancesIndex = 0;
	for (var season = 1; season < shows.length; season++) {
		for (var week = 1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (var couple = 0; couple < showData.length; couple++) {
				var performanceData = showData[couple];
				if (performanceData[DANCE] == dance) {
					var personId = performanceData[PERSON_ID];
					var coupleNames = getCoupleNames(season, week, personId);
					var performance = performanceData[PERFORMANCE];
					var song = performanceData[SONG];
					dancePerformances[dancePerformancesIndex++]=[coupleNames, season, week, personId, song, performance];
				}
			}
		}
	}
	
	for (var season = 1; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week ++) {
			var showData = resultShows[season][week];
			if (typeof showData != "undefined" && showData != null) {
				for (var performance =0; performance < showData.length; performance++) {
					var performanceData = showData[performance];
					if (performanceData[3] == dance) {
						var coupleNames = concatNames(performanceData[1], performanceData[2]);
						var videoId = performanceData[0];
						var song = performanceData[4];
						dancePerformances[dancePerformancesIndex++]=[coupleNames, season, week, videoId, song]; 
					}
				}
			}
		}
	}
	
	dancePerformances = dancePerformances.sort();
	return dancePerformances;
}
	
function findPerformances(performer) {
	var dancerPerformances = new Array();
	var dancerPerformancesIndex = 0;
	for (var season = 1; season < shows.length; season++) {
		for (var week = 1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (var p = 0; p < showData.length; p++) {
				var performanceData = showData[p];
				var personId = performanceData[PERSON_ID];
				var coupleNames = getCoupleNames(season, week, personId);
				if (coupleNames.indexOf(performer) >=0) {
					var dance = performanceData[DANCE];
					var song = performanceData[SONG];
					var performance = performanceData[PERFORMANCE];
					var score = performanceData[TOTAL_SCORE];
  					var videoId = performanceData[0];
					dancerPerformances[dancerPerformancesIndex++]=[coupleNames, season, week, performance, score, dance, song, videoId];
				}
			}
		}
	}

	for (var season = 1; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week ++) {
			var showData = resultShows[season][week];
			if (typeof showData != "undefined" && showData != null) {
				for (var performance =0; performance < showData.length; performance++) {
					var performanceData = showData[performance];
					var coupleNames = concatNames(performanceData[1], performanceData[2]);
					if (coupleNames.indexOf(performer) >=0) {
						var videoId = performanceData[0];
						var dance = performanceData[3];
						var song = performanceData[4];
						dancerPerformances[dancerPerformancesIndex++]=[coupleNames, season, week, 0, 0, dance, song, videoId];
					}
				}
			}
		}
	}

	return dancerPerformances.sort(performersSortMethod);
}
	
function performersSortMethod(a, b) {
	var sw1 = a[1]*10+a[2];
	var sw2 = b[1]*10+b[2];
	return sw1-sw2;
	
}
		
function getAllSongs() {
		var allSongs = new Array();
	var allSongsIndex = 0;
	for (var season = 1; season < shows.length; season++) {
		for (var week = 1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (var couple = 0; couple < showData.length; couple++) {
				var coupleData = showData[couple];
				var song = coupleData[SONG];
				if (song != "") {
					var personId = coupleData[PERSON_ID];
					var dance = coupleData[DANCE];
					var performance = coupleData[PERFORMANCE];
					var songData = [song, personId, dance, season, week, performance];
					allSongs[allSongsIndex++]=songData;	
				}
			}
		}	
	}
	for (var season = 2; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week++) {
			var showData = resultShows[season][week];
			if (typeof showData == "undefined") continue;
			for (var couple = 1; couple < showData.length; couple++) {
				var coupleData = showData[couple];
				var song = coupleData[4];
				if (song != "") {
					var videoId = coupleData[0];
					var dance = coupleData[3];
					var songData = [song, videoId, dance, season, week, couple]; //-1 means result show
					allSongs[allSongsIndex++]=songData;
				}
			}
		}
	}
	allSongs = allSongs.sort();
	return allSongs;
}

function dwtsSongs() {
	switchMenu(MENU_SONGS);
	
	var html='<table><tr><td valign="top" align="left">'
	+'<form onsubmit="return applySongFilter()">'
	+'<span style="font-size:10pt">Filter: <input type="text" id="songFilter" style="font-size:10pt"/>'
	+'&nbsp;<input type="submit" value="Apply" onClick="applySongFilter()" style="font-size:10pt" />'
	+'&nbsp;<input type="button" value="Clear" onClick="clearSongFilter()" style="font-size:10pt"/>'
	+'&nbsp;<span id="songCount"></span>'
	+'</span></form>';
	
	//header table
	html+='<table><tr><td width=320 style="font-size:8pt" align="left"><b>Song</b></td><td width=55 style="font-size:8pt" align="left"><b>Dance</b></td>'
	+'<td style="font-size:8pt" align="left"><b>Show</b></td></tr></table>';
	
	html +='<div id="songList" style="width:'+leftHalfWidth+'px;height:'+(mainDivHeight-45)+'px;overflow:auto;position:relative;"></div>';
	html += '</td>';
	html += '<td><div id="selectedContent" style="text-align:center; width:'+dwtsVideoWidth+'px; height:'+mainDivHeight+'px;"></div></td>';
	html += '</tr></table>';	
	document.getElementById("dwtsMain").innerHTML=html;
	applySongFilter("");
}

function applySongFilter() {
	var filter = document.getElementById("songFilter").value;
	document.getElementById("songList").innerHTML=getSongList(filter);
	return false;
}

function clearSongFilter() {
	document.getElementById("songFilter").value = "";
	document.getElementById("songList").innerHTML=getSongList("");
}

function getSongList(filter) {
	filter = filter.toLowerCase();
	var allSongs = getAllSongs();
	var html="";
	var count = 0;
	for (var i=0; i<allSongs.length; i++) {
		var songData = allSongs[i];
		var song = songData[0];
		if (filter != "" && song.toLowerCase().indexOf(filter) == -1) {
			continue;
		}
		count++;
		var personId = songData[1];
		var dance = songData[2];
		var season = songData[3];
		var week = songData[4];
		var performance = songData[5];
		html +='<div style="border-bottom-width:1px; border-bottom-color:black; border-bottom-style:solid" id="selectionList'+i+'">'
		+'<table><tr><td width=320 align="left">'
		+'<a style="font-size:8pt" href="javascript:showSongVideo('+season+','+week+',\''+personId+'\','+performance+','+i+')">'
		+song+'</a></td><td width=55 style="font-size:8pt">'+getDanceLink(dance)+'</td><td style="font-size:8pt" nowrap>s'+season+ ' w'+week+'</td>'
		+'</tr></table></div>';
	}
	document.getElementById('songCount').innerHTML=count+ (count == 1 ? ' song':' songs')+ ' found.';
	return html;
}
function dwtsFacebook() {
	switchMenu(MENU_FACEBOOK);
	var html='<div align="center">'
	+'<input type="radio" name="facebook" value="celeb" checked onClick="showFacebook(\'celebs\')">Celebrities&nbsp;&nbsp;&nbsp'
	+'<input type="radio" name="facebook" value="pros" onClick="showFacebook(\'pros\')">Professional Dancers'
	+'<div id="facebookdiv" style="height:'+(mainDivHeight-23)+'px;overflow:auto"></div>';
	document.getElementById("dwtsMain").innerHTML=html;
	showFacebook("celebs");
}

function showFacebook(who) {
	var names = new Array();
	for (var season = 1; season < shows.length; season++) {
		for (var week =1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			for (performance = 0; performance < showData.length; performance++) {
				var performanceData = showData[performance];
				var celebrityPersonId = performanceData[PERSON_ID];
				if (celebrityPersonId == "group") {
					continue;
				}
				var couple = getCouple(season, week, celebrityPersonId);
				var name = (who == "celebs") ? couple[0] : couple[1];
				addToSet(names, name);
			}
		}
	}
	var html = '<table ><tr>'
	for (var i = 0; i<names.length; i++) {
		var name = names[i];
		var imgHtml='<img src="'+rootUrl+'performers/'+getPersonId(name)+'.jpg" border="0" alt="'+name+'" width="110" height="130">';
		html +='<td>'+getPerformerLink(name, imgHtml)+'</td>';
		if ((i+1) % 6 == 0) {
			html += '</tr><tr>';
		}
	}
	html += '</tr></table>';
	document.getElementById("facebookdiv").innerHTML=html;
}

function dwtsStats() {
	switchMenu(MENU_STATS);
	var html = '<table><tr><td align="left" width='+leftHalfWidth+'><div align="center"><b>Statistics:</b> <select onChange="selectStats(this.options[this.selectedIndex].value)">'
	+ '<option value="Cumulative">Overall Cumulative</option>'
	+ '<option value="Dances">Number Of Performances By Dance</option>'
	+ '<option value="Celebs">Number Of Performances By Celebrity</option>'
	+ '<option value="Pros">Number Of Performances By Pro Dancer</option>'
	+ '<option value="BestPerf">20 Best Performances</option>'
	+ '<option value="WorstPerf">20 Worst Performances</option>'
	+ '<option value="AvgScores">Celebrities\' Average Scores</option>'
	+ '<option value="Judges">Judges</option>'
	+'<option value="MissingData">Missing Data</option>'
	+'</select></div>'
	+ '<div id="statsList" align="center" style="width:'+leftHalfWidth+'px;height:'+(mainDivHeight-45)+'px;overflow:auto;"></div>'
	+ '</td><td valign="top" width="'+dwtsVideoWidth+'">'
	+ '<div id="selectedContent" style="width:'+dwtsVideoWidth+'px;height:'+mainDivHeight+'px;text-align:center"></div>'
	+'</td></tr></table>';
	
	document.getElementById("dwtsMain").innerHTML=html;
	selectStats("Cumulative");
}

function selectStats(stats) {
	document.getElementById("selectedContent").innerHTML='';	
	var html ;
	if (stats == "Cumulative") {
		html = getCumulativeStatsHtml();
	} else if (stats == "Dances") {
		html = getCountsHtml(statsDances, false);
	} else if (stats == "Celebs") {
		html = getCountsHtml(statsCelebs, true);
	} else if (stats == "Pros") {
		html = getCountsHtml(statsPros, true);
	} else if (stats == "WorstPerf") {
		html = getTop("Worst");
	} else if (stats == "BestPerf") {
		html = getTop("Best");
	} else if (stats == "AvgScores") {
		html = getAvgScores();
	} else if (stats == "Judges") {
		html = getJudgesStats();
	} else if (stats == "MissingData") {
		html = getMissingData();
	}
	document.getElementById("statsList").innerHTML = html;
	if (stats == "MissingData") {
		selectMissingData("videos");
	}
}

function getStatsTableStartHtml() {
	return '<table border="0" cellspacing="0" cellpadding="0" width="95%">';
}

function getCumulativeStatsHtml() {
		var row =0;	
		var html = getStatsTableStartHtml()
		+getStatsRow("Number of shows",statsShows, row++)
		+getStatsRow("Number of performances",statsPerformances, row++)
		+getStatsRow("Number of dances",getMapSize(statsDances), row++)
		+getStatsRow("Number of celebrities",getMapSize(statsCelebs), row++)
		+getStatsRow("Number of professional dancers",getMapSize(statsPros), row++)
		+getStatsRow("Total judges' points awarded",statsTotalScorePoints, row++)
		+'</table>';
		return html;
}

function getAvgScores() {
	var html = getStatsTableStartHtml();
	var row = 0;
	var count = 20;
	for (var i = 0; i<statsComputedAvgScores.length; i++) {
		var avgScoreData = statsComputedAvgScores[i];
		var personId = avgScoreData[0];
		var name = getCelebName(personId);
		var avgScore = avgScoreData[1];
		html += getStatsRow(getPerformerLink(name), avgScore.toFixed(2), row++);
	}
	html += '</table>';
	return html;
}

function getMissingData() {
	document.getElementById("selectedContent").innerHTML='';
	var html = '<select id="missingDataSelector" onchange="selectMissingData(this.options[this.selectedIndex].value)">'
	+'<option value="videos">Videos</option>'
	+'<option value="songs">Songs</option>'
	+'<option value="scores">Judges\' Scores</option></select>'
	+'<div id="missingDataDiv" style="width:'+leftHalfWidth+'px;height:'+(mainDivHeight-70)+'px;overflow:auto;"></div>';
	return html;
}

function selectMissingData(dataType) {
	var html='';
	if (dataType == "videos") {
		html = getMissingVideos();
	} else if (dataType == "songs") {
		html = getMissingSongs();
	} else if (dataType == "scores") {
		html = getMissingScores();
	}
	document.getElementById("missingDataDiv").innerHTML = html;
}
	
function getMissingVideos() {
	var html = getStatsTableStartHtml();
	var row = 0;
	for (var i=0; i<statsMissingVideos.length; i++) {
		var missingVideosData = statsMissingVideos[i];
		var season = missingVideosData[0];
		var week = missingVideosData[1];
		var coupleNames = missingVideosData[2];
		var dance = missingVideosData[3];
		var s = 's'+season+' w'+week+' '+coupleNames+' - '+dance;
		var linkHtml='<a href=\'javascript:submitMissingVideo('+season+','+week+',"'+coupleNames+'","'+dance+'")\'>Submit URL</a>';
		html += getStatsRow(s, linkHtml, row++);
	}
	html += '</table>';
	document.getElementById("selectedContent").innerHTML= "Number of missing videos: <b>"+statsMissingVideos.length+"</b><br>If you know of a URL to a missing video, please help me out by submitting it.";
	return html;
}

function getMissingSongs() {
	var html = getStatsTableStartHtml();
	var row = 0;
	for (var i=0; i<statsMissingSongs.length; i++) {
		var missingSongsData = statsMissingSongs[i];
		var season = missingSongsData[0];
		var week = missingSongsData[1];
		var personId = missingSongsData[2];
		var performance = missingSongsData[3];
		var dance = missingSongsData[4];
		var s = 's'+season+' w'+week+' '+getCoupleNamesWithLinks(season, week, personId)+' - '+getDanceLink(dance);
		var linkHtml='<a href=\'javascript:submitMissingData('+season+','+week+',"'+personId+'","'+performance+'")\'>Submit Song</a>';
		html += getStatsRow(s, linkHtml, row++);
	}
	html += '</table>';
	document.getElementById("selectedContent").innerHTML= "Number of missing songs: <b>"+statsMissingSongs.length+"</b><br>If you know the names of the songs (and artists), please help me out by submitting them.";
	return html;
}

function getMissingScores() {
	var html = getStatsTableStartHtml();
	var row = 0;
	for (var i=0; i<statsMissingJudgesScores.length; i++) {
		var missingScoresData = statsMissingJudgesScores[i];
		var season = missingScoresData[0];
		var week = missingScoresData[1];
		var personId = missingScoresData[2];
		var performance = missingScoresData[3];
		var dance = missingScoresData[4];
		var s = 's'+season+' w'+week+' '+getCoupleNamesWithLinks(season, week, personId)+' - '+getDanceLink(dance);
		var linkHtml='<a href=\'javascript:submitMissingData('+season+','+week+',"'+personId+'","'+performance+'")\'>Submit Scores</a>';
		html += getStatsRow(s, linkHtml, row++);
	}
	html += '</table>';
	document.getElementById("selectedContent").innerHTML= "Number of missing judges' scores: <b>"+statsMissingJudgesScores.length+"</b><br>If you know the judges scores, please help me out by submitting them.";
	return html;}

function submitMissingVideo(season, week, couple, dance) {
	var html = getMissingVideoForm(season, week, couple, dance);
	document.getElementById("selectedContent").innerHTML = html;
}

function getPerformanceData(season, week, personId, performance) {
	var showData = shows[season][week];
	var performanceData = null;
	for (var i=0; i<showData.length; i++) {
		if (showData[i][PERSON_ID] == personId && showData[i][PERFORMANCE]==performance) {
			performanceData = showData[i];
		}
	}
	if (performanceData == null) {
		alert("Could not find performance data for season "+season+" week "+week+ " person id "+personId+" performance "+performance);
	}
	return performanceData;
}
			
function submitMissingData(season, week, personId, performance) {
	var html = "";
	if (performance == 0) { // result show (todo: code not finished yet)
		html += getProVideoPlayerHtml(season, videoId, personId, dance, "");
	} else {
		var performanceData = getPerformanceData(season, week, personId, performance);
		var totalScore = performanceData[TOTAL_SCORE];
		var scores = performanceData[SCORES];
		var dance = performanceData[DANCE];
		var song = performanceData[SONG];
		var youTubeId = getYouTubeId(performanceData);
		html += getVideoPlayerHtml(season, week, personId, performance, totalScore, scores, dance, song, "", youTubeId);
	}
	document.getElementById("selectedContent").innerHTML = html;
}

		
function getTop(kind) {
	var html = getStatsTableStartHtml();
	var row = 0;
	var count = 20;
	if (kind == "Worst") { // the array is sorted in descending order by score
		for (var i = statsScores.length-count; i<=statsScores.length-1; i++) {
			html += getScoreStatsRowHtml(statsScores[i], row++);
		}
	} else if (kind = "Best") {
		for (var i = 0; i<=count-1; i++) {
			html += getScoreStatsRowHtml(statsScores[i], row++);
		}
	}		
	html += '</table>';
	return html;
}

function getScoreStatsRowHtml(scoreData, row) {
	var personId = scoreData[0];
	var score = scoreData[1];
	var season = scoreData[2];
	var week = scoreData[3];
	var performance = scoreData[4];
	var dance = scoreData[5];
	var song = scoreData[6].replace(/\'/g,"\\'");
	var name = getCouple(season, week, personId)[0];
	var firstCell = '<a href="javascript:showDanceVideo(\''+name+'\',\''+dance+'\',\''+song+'\','+season+','+week+',\''+personId+'\','+performance+','+row+')">'
		+name+' (s'+season+' w'+week+')</a> '+dance;
	var html = getStatsRow(firstCell,'Score: '+score, row);
	return html;
}

function getStatsRow(name, value, rowNum) {
	var html = '<tr bgcolor="'+(rowNum % 2 == 0 ? evenRowColor : oddRowColor)+'">'
		+'<td align="left" width="'+statsNameWidth+'">'+name+'</td><td align="right">'+value+'</td></tr>';
	return html;
}

	
function computeStats() {
	var statsScoresIndex = 0;
	for (var season = 1; season < shows.length; season++) {
		for (var week = 1; week < shows[season].length; week++) {
			var showData = shows[season][week];
			statsShows++;
			for (var performance = 0; performance < showData.length; performance++) {
				statsPerformances++;
				var coupleData = showData[performance];
				var song = coupleData[SONG];
				var personId = coupleData[PERSON_ID];
				var dance = coupleData[DANCE];
				var p = coupleData[PERFORMANCE];
				var coupleNames = getCouple(season, week, personId);
				if (song == "" || song.toLowerCase() == "*unknown*") {
					addToArray(statsMissingSongs,[season,week,personId,p,dance]);
				} 
				var score = coupleData[TOTAL_SCORE];
				statsTotalScorePoints += score;
				if (coupleNames[0] != group && score > 0) {
					incrementCount(statsCelebs, coupleNames[0]);
					incrementCount(statsPros, coupleNames[1]);
					var song = coupleData[SONG];
					statsScores[statsScoresIndex++]=[personId, score,season,week,p, dance, song];
					updateAverageScores(personId, score);
				}
				incrementCount(statsDances, dance);
				if (getYouTubeId(coupleData) == "missing") {
					addToArray(statsMissingVideos, [season,week,getCoupleNames(season, week, personId), dance]);
				}
				var scores = coupleData[SCORES];
				if (scores != "") {
					var scoresArray = scores.split(",");
					for (var j=0; j<scoresArray.length; j++) {
						var judge = judges[season][j];
						var score = parseInt(scoresArray[j]);
						incrementCount(statsJudgesTotalScores, judge, score);
					}
				} else if (score > 0) {
					addToArray(statsMissingJudgesScores, [season,week,personId,p,dance]);
				}
			}
		}	
	}
	for (var season = 1; season < resultShows.length; season++) {
		for (var week = 1; week < resultShows[season].length; week++) {
			var showData = resultShows[season][week];
			if (typeof showData == "undefined") continue;
			if (showData.length > 1) {
				statsShows++; // count the results show with at least one performance
			}
			for (var performance = 1; performance < showData.length; performance++) {
				var coupleData = showData[performance];
				var name1 = coupleData[1];
				var name2 = coupleData[2];
				var dance = coupleData[3];
				if (dance == "" || indexOf(hosts, name1)>=0 || indexOf(hosts, name2)>=0) continue;				
				statsPerformances++;
				var song = coupleData[4];
				var videoId = coupleData[0];
				incrementCount(statsDances, dance);
				incrementCount(statsPros, name1);
				if (name2 != "") incrementCount(statsPros, name2);
			}
		}
	}
	
	statsScores = statsScores.sort(sortTotalScoresMethod);
	
	var i = 0;
	for (var personId in statsAvgScores) {
		var scores = statsAvgScores[personId];
		var totalScore = 0;
		for (var s = 0; s<scores.length; s++) {
			totalScore += scores[s];
		}
		statsComputedAvgScores[i++] = [personId, totalScore / scores.length];
	}
	statsComputedAvgScores = statsComputedAvgScores.sort(sortTotalScoresMethod);
}

function updateAverageScores(personId, score) {
	if (typeof statsAvgScores[personId] == "undefined") {
		statsAvgScores[personId] = [score];
	} else {
		var len = statsAvgScores[personId].length;
		statsAvgScores[personId][len]=score;
	}
}
		
function getCountsHtml(array, isPerformer) {
	var html = getStatsTableStartHtml();
	var sortedArray = new Array();
	var i=0;
	for (var key in array) {
		sortedArray[i++] = [key, array[key]];
	}
	sortedArray = sortedArray.sort(sortTotalScoresMethod);
	for (var i = 0; i<sortedArray.length; i++) {
		var entry = sortedArray[i];
		var string = entry[0];
		var count = entry[1];
		if (isPerformer) {
			string = getPerformerLink(string);
		}
		html += getStatsRow(string, count, i);
	}
	html += '</table>';
	return html;
}

function incrementCount(array, key, increment) {
	if (key =="") return;
	
	if (increment == null) {
		increment = 1;
	}
	var count = array[key];
	if (typeof count == "undefined") {
		array[key]=increment;
	} else {
		array[key]=count+increment;
	}
}		

function getJudgesStats() {
	document.getElementById("selectedContent").innerHTML='The most generous judge is at the top and the toughest one is at the bottom.';
	var html='<div align="left"><table>';
	var sortedArray = new Array();
	var i = 0;
	for (var judge in statsJudgesTotalScores) {
		sortedArray[i++] = [judge, statsJudgesTotalScores[judge]];
	}
	sortedArray = sortedArray.sort(sortTotalScoresMethod);
	var maxScore = sortedArray[0][1];
	for (var i=0; i<sortedArray.length; i++) {
		var judge = sortedArray[i][0];
		var totalScore = sortedArray[i][1];
		var judgeId = getPersonId(judge);
		html += '<tr><td align="left"><img src="'+rootUrl+'performers/'+judgeId+'.jpg" width="66" height="78" align="left" hspace="2" border="0">'+judge+'<br>';
		html += getTotalScoreGraph(totalScore, maxScore, "Total points awarded", 350)+'</td></tr>';
	}
	html += '</table></div>';
	return html;
}

function getDanceStyle(dance) {
	var latinDances = ["Cha Cha","Samba","Rumba","Jive","Pasodoble","Mambo","Salsa"];
	var ballroomDances = ["Foxtrot","American Smooth","Quickstep","Waltz","Viennese Waltz","Tango","Argentine Tango"];
	var danceStyle;
	if (indexOf(latinDances, dance) >= 0) {
		danceStyle = "Latin";
	}else if (indexOf(ballroomDances, dance) >= 0) {
		danceStyle = "Ballroom";
	} else {
		danceStyle = dance;
	}
	return danceStyle;
}

function eliminations(season) {
	switchMenu(MENU_WEEKLY_PROGRESS);
	var seasonCouples = couples[season];
	var weeks = shows[season];
	var showFinal = finals[season];
	var lastWeek = showFinal[0];
	var html='<div align="left" style="width:'+mainDivWidth+'px;height:'+mainDivHeight+'px;overflow:auto"><table>';
	for (var week = 1; week < lastWeek && week < resultShows[season].length; week++) {
		html += '<tr><td>Week '+week+'</td>';
		var resultShow = resultShows[season][week];
		if (resultShow == null) continue;
		var eliminatedPersonId = resultShow[0];
		if (eliminatedPersonId == null || eliminatedPersonId == "") continue;
		html += '<td>'+getCoupleEliminationHtml(season, week, eliminatedPersonId)+'</td></tr>';
	}
	for (var place=showFinal.length-1; place>0; place--) {
		var personId = showFinal[place];
		if (personId != "") {//final week has not yet arrived
			html += '<tr><td';
			if (place == 1) {
				html += ' style="background-image:url(http://raphaelpungin.com/dance/dwts/trophy_bg.jpg);background-repeat:no-repeat;background-position:center"';
			}
			html +='>'+getNumberSuffix(place)+' place</td>';
			html += '<td>'+getCoupleEliminationHtml(season, lastWeek, personId)+'</td></tr>';
		}
	}
	html +='</tr></table></div>';
	document.getElementById("dwtsMain").innerHTML=html;
}

function getCoupleEliminationHtml(season, week, personId) {
var html = getCoupleIcon(season, week, personId, 75, "")+getCoupleNamesWithLinks(season, week, personId);
var scores = getScores(personId, season, week);
var maxScore = getMaxScore();
var graphWidth=500;
html += getTotalScoreGraph(scores[0],maxScore,"Highest Score", graphWidth, highestScoreColor);
html += getTotalScoreGraph(scores[1],maxScore,"Lowest Score", graphWidth, lowestScoreColor);
html += getTotalScoreGraph(scores[2],maxScore,"Average Score", graphWidth, averageScoreColor);
return html;
}


//Returns array of [highest score, lowest score, avg score]
function getScores(personId, season, lastWeek) {
var highestScore = 0, lowestScore=999, totalScore = 0, avgScore=0, numScores = 0;
for (var week =1; week <= lastWeek; week++) {
	var showData = shows[season][week];
	for (performance = 0; performance < showData.length; performance++) {
		var performanceData = showData[performance];
		var celebrityPersonId = performanceData[PERSON_ID];
		if (celebrityPersonId == "group" || celebrityPersonId != personId) {
			continue;
		}
		var score = performanceData[TOTAL_SCORE];
		if (score > 0) {
			numScores++;
			totalScore += score;
			if (score > highestScore) highestScore = score;
			if (score < lowestScore) lowestScore = score;
		}
	}
}

var scores = [highestScore, lowestScore, (totalScore/numScores).toFixed(2)];
return scores;
}


var viewerSurveyQuestions = [
"040","If you were a celebrity, which would you prefer to learn?",
["Ballroom Dancing","Ice Skating"],
"039","Who is your favorite judge?",
["Carrie Ann Inaba","Len Goodman","Bruno Tonioli"],
"030","*What is Ballroom Dancing to you?",
  ["Not my cup of tea.",
  "Like to watch it, but would not do it.",
  "Might try it sometime.",
  "It's my hobby/profession."],
"031","What is your gender?",["Male","Female"],
"032","What is your age group?",["Under 20","20's","30's","40's","50's","Over 60"]

];

function writeViewerSurvey() {
	document.write('<table><tr><td style="background:#000080;color:white" colspan="4" align="center"><b>Viewers\' Survey</b><br>');
	document.write('<small>Please click Submit button for each question.<br>');
	document.write('Once on the results page, click Back button on your browser<br>');
	document.write('to return back to the survey to answer the next question.</small></td></tr>');
	for (var i=0,r=0; i<viewerSurveyQuestions.length;r++) {
	  var pollID = viewerSurveyQuestions[i++];
	  var question = viewerSurveyQuestions[i++];
	  var answers =  viewerSurveyQuestions[i++];
	  var bgcolor = r % 2 == 0 ? "#cccccc":"#e8e8e8";
	  document.write('<tr bgcolor="'+bgcolor+'"><td>');
	  if (question.substring(0,1) == "*") {
	    document.write('<img src="http://raphaelpungin.com/images/new.gif" valign="middle" border="0">');
	    question = question.substring(1,question.length);
	  }
	  document.write(question+'</td>');
	  document.write('<form name="'+pollID+'" action="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollID+'" method="post" onsubmit="return validateSurvey(this)">');
	  document.write('<td><select name="poll_answer">');
	  document.write('<option value="0" selected">--Please make a selection--</option>');
	  for (var j=0; j<answers.length; j++) document.write('<option value="'+(j+1)+'">'+answers[j]+'</option>');
	  document.write('</select>');
	  document.write('<input type="submit" value="Submit"></td></form>');
	  document.write('<td><a href="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollID+'">Results</a></td></tr>');
	}
	document.write('<tr><td style="background:#000080;color:white" colspan="4" align="center">');
	document.write('<b><a style="color:white" href="http://raphaelpungin.com/dance/dwts2/suggest_question.html">Suggest a question</a></b><br>');
  document.write('</table>');
}

	
function setResult(formName, result, couple) {
	var week=getRightMostNumber(formName);
	var show="WEEK "+week;
  var msg=
     "=== YOU ARE VOTING FOR THE BEST COUPLE IN "+show+" ===\n\n"
    msg+="Note that this vote will not affect the ratings of contestants in the show.\n"
    +"The results of the votes are only available on this website for everyone to see and share.\n"
    +"Make sure you carefully watch the videos of all couples for this week before you vote.\n"
    +"You may only vote once and you cannot change your vote.\n"
    +"There is no deadline for voting, so take your time to think about your decision.\n\n"
    +"Click OK to vote for "+couple+", otherwise click Cancel.";
  if (!confirm(msg)) {
    return;
  }

  document.forms[formName].poll_answer.value=result;
  document.forms[formName].submit();
}

function validateSurvey(form) {
  var value = form.poll_answer.value;
  if (value == "0") {
    alert("Please make a selection.");
    return false;
  }
  return true;
}

function writeSurvey(pollNumber, jpgFile, name, rowColor) { 
switch (rowColor) {
  case 0: var color="#fffe8d"; break;
  case 1: var color="#f2f190"; break;
  case 2: var color="#99fdca"; break;
  case 3: var color="#79f3b5"; break;
}  
document.write('<tr bgcolor="'+color+'">');
document.write('<form name="'+jpgFile+'" action="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollNumber+'" method="post" onSubmit="return validateSurvey(this)">');
document.write('<input type="hidden" name="person" value="'+name+'">');
document.write('<td><img valign="middle" align="left" hspace="2" src="http://raphaelpungin.com/dance/dwts2/'+jpgFile+'.jpg" >'+name+'</td><td>');
document.write('<select name="poll_answer">');
  document.write('<option value="0">--Please make a selection--</option>');
  document.write('<option value="1">I\'ve never heard the name before DWTS.</option>');
	document.write('<option value="2">I\'ve heard the name, but I\'m not a fan.</option>');
	document.write('<option value="3">I\'m a fan!</option>');
document.write('</select>');
document.write('<input type="submit" value="Submit"></td></form>');
document.write('<td><a href="http://rpungin.freepolls.com/cgi-bin/pollresults/'+pollNumber+'">Results</a></td></tr>');
}
