// #include "DrawGeneratorObjects.js";
// #include "Disciplines.js";

var m_oContentSpan = null;
var m_selClasses = null;
var m_selDisciplines = null;
var m_chkPictures = null;
var m_txtColumns = null;
var m_txtSpecificDraw = null;

function sImageTagFromFormation(oFormation, ix) {
	if (ix < oFormation.arsImage.length) {
		var ret = ['<img src="', oFormation.arsImage[ix], '"'];
		if (oFormation.sImageClass !== '') {
			ret.push('class="');
			ret.push(oFormation.sImageClass);
			ret.push('"');
		}
		ret.push(' />');
		return ret.join('');
	} else {
		return null;
	}
}

function sPictureDescriptionSpanFromText(s, bVisible) {
	return '<span class="' + (bVisible ? 'PictureDescriptionVisible' : 'PictureDescriptionHidden') + '">' + s + '</span>';
}

function sTDFromFormation(oFormation) {
	var ret = ['<td><h3>', oFormation.sShortName, '</h3>'];
	
	//if (m_chkPictures.checked) {
		for (var ix = 0; ix < oFormation.arsLongName.length; ix++) {
			ret.push(oFormation.arsLongName[ix]);
			ret.push('<br>');
			
			if (ix < oFormation.arsImage.length) {
				var sImg = sImageTagFromFormation(oFormation, ix);
				if (sImg !== null) {
					ret.push(sPictureDescriptionSpanFromText(sImg, m_chkPictures.checked));
				}
			}
			
			if (oFormation.sExtraInformation !== null && oFormation.sExtraInformation != '') {
				ret.push(sPictureDescriptionSpanFromText(oFormation.sExtraInformation, m_chkPictures.checked));
			}
		}
	//}
	//else {
	//	ret.push(oFormation.sName());
	//}
	
	//ret.push('<hr>');
	//ret.push(oFormation.toString());
	
	ret.push('</td>');
	
	return ret.join('');
}

/// sBuildDivePool
/// builds and returns an HTML table containing a dive pool for a class
/// <Parameters>
/// <Parameter Name="oDiscipline">The discipline</Parameter>
/// <Parameter Name="iClassLevel" Optional="True">The class level. If omitted then all formations are shown.</Parameter>
/// <Parameter Name="iColumns" Optional="True">The number of columns in the table. Default = 4</Parameter>
/// </Parameters>
function sBuildDivePool(oDiscipline, iClassLevel, iColumns) {
	iClassLevel = iClassLevel || 999999;
	iColumns = iColumns || 4;
	
	var ret = '<table border="1" cellpadding="1" cellspacing="3"><tr><th colspan="' + iColumns + '">' + oDiscipline.sName + '</th></tr>';
	
	var ixColumn = 0;
	var bCurrentPoints = oDiscipline.aroFormations[0].iPointValue;
	var bEndRow = false;
	for (var ix = 0; ix < oDiscipline.aroFormations.length; ix++) {
		if (oDiscipline.aroFormations[ix].iClassLevel <= iClassLevel) {
			ixColumn++;
			if (ixColumn > iColumns) {
				bEndRow = true;
			}
			if (bCurrentPoints != oDiscipline.aroFormations[ix].iPointValue) {
				bEndRow = true;
				bCurrentPoints = oDiscipline.aroFormations[ix].iPointValue;
			}
			
			if (bEndRow) {
				bEndRow = false;
				ret += '</tr>';
				ixColumn = 1;
			}
			
			if (ixColumn == 1) {
				ret += '<tr>';
			}
			ret += sTDFromFormation(oDiscipline.aroFormations[ix]);
		}
	}
	ret += '</table>';
	return ret;
}

function oSelectedDiscipline() {
	if (m_selDisciplines.selectedIndex == -1) { return null; }
	
	var sSelected = m_selDisciplines.options[m_selDisciplines.selectedIndex].text;

	for (var ix = 0; ix < Disciplines.length; ix++) {
		if (Disciplines[ix].sName == sSelected) {
			return Disciplines[ix];
		}
	}
	
	return null;
}

function selDisciplines_change() {
	m_selClasses.options.length = 0;
	
	var oDiscipline = oSelectedDiscipline();
	if (oDiscipline === null) { return; }

	for (var ix = 0; ix < oDiscipline.aroClassLevelNames.length; ix++) {
		m_selClasses.options.add(new Option(oDiscipline.aroClassLevelNames[ix].sClassName, oDiscipline.aroClassLevelNames[ix].iClassLevel));
	}
	
	if (m_selClasses.options.length > 0) {
		m_selClasses.selectedIndex = 0;
	}
}

function showContent(s) {
	showDebug(s);
	m_oContentSpan.innerHTML = s;
}

function btnShowDivePool_click() {
	var oDiscipline = oSelectedDiscipline();
	if (oDiscipline === null) { return; }
	
	var iLevel = parseInt(m_selClasses.options[m_selClasses.selectedIndex].value);
	
	var s = sBuildDivePool(oDiscipline, iLevel);
	showContent(s);
}

function iRandom(iMax) {
	ret = Math.floor(Math.random() * iMax) + 1;
	return ret;
}

function oGetRoundRules(oDrawRules, iRoundNumber) {
	if (oDrawRules.aroDrawRoundRules !== null) {
		for (var ix = 0; ix < oDrawRules.aroDrawRoundRules.length; ix++) {
			if (oDrawRules.aroDrawRoundRules[ix].iRoundNumber == iRoundNumber) {
				return oDrawRules.aroDrawRoundRules[ix];
			}
		}
	}
	return null;
}

function CopyArray(aroSrc, aroDest) {
	for (var ix = 0; ix < aroSrc.length; ix++) {
		aroDest.push(aroSrc[ix]);
	}
}

function aroDrawRound(aroAllFormations, aroCurrentFormations, oDrawRules, iRoundNumber) {
	var oRoundRules = oGetRoundRules(oDrawRules, iRoundNumber);
	if (oRoundRules !== null) {
		FilterFormationsArrayByRules(aroCurrentFormations, oRoundRules);
		if (aroCurrentFormations.length === 0) {
			CopyArray(aroAllFormations, aroCurrentFormations);
			FilterFormationsArrayByRules(aroCurrentFormations, oRoundRules);
		}
	}

	var iPoints = 0;
	var ret = [];
	while (iPoints < oDrawRules.iMinPointsPerRound) {
		if (aroCurrentFormations.length === 0) { return ret; }
		
		var oFormationToAdd = null;
		
		if (aroCurrentFormations.length == 1) {
			oFormationToAdd = aroCurrentFormations.pop();
			// now rebuild the array for the current formations
			CopyArray(aroAllFormations, aroCurrentFormations);
			if (oRoundRules !== null) {
				FilterFormationsArrayByRules(aroCurrentFormations, oRoundRules);
			}
		}
		else {
			var iRnd = iRandom(aroCurrentFormations.length - 1);
			oFormationToAdd = aroCurrentFormations[iRnd];
			// move the last formations to the draw one's place and remove the last element of the array
			aroCurrentFormations[iRnd] = aroCurrentFormations[aroCurrentFormations.length - 1];
			aroCurrentFormations.pop();
		}
		
		ret.push(oFormationToAdd);
		iPoints += oFormationToAdd.iPointValue;
	}
	
	return ret;
}

function bArrayContains(aro, o) {
	for (var ix = 0; ix < aro.length; ix++) {
		if (aro[ix] == o) {
			return true;
		}
	}
	return false;
}

function FilterFormationsArrayByRules(aroFormations, oDrawRoundRules) {
	var aroValid = [];
	for (var ix = 0; ix < aroFormations.length; ix++) {
		if (oDrawRoundRules.arsLimitToFormations !== null) {
			if (bArrayContains(oDrawRoundRules.arsLimitToFormations, aroFormations[ix].sShortName)) {
				aroValid.push(aroFormations[ix]);
			}
		}
	}
	
	if (aroFormations.length != aroValid.length) {
		aroFormations.splice(0, aroFormations.length);
		CopyArray(aroValid, aroFormations);
	}
}

function btnGenerateDraw_click() {
	var oDiscipline = oSelectedDiscipline();
	if (oDiscipline === null) { return; }
	
	var iLevel = parseInt(m_selClasses.options[m_selClasses.selectedIndex].value);
	
	var oDrawRules = null;
	for (var ix = 0; ix < oDiscipline.aroDrawRules.length; ix++) {
		if (oDiscipline.aroDrawRules[ix].iClassLevel == iLevel) {
			oDrawRules = oDiscipline.aroDrawRules[ix];
			break;
		}
	}
	if (oDrawRules === null) { return; }
	
	// the full set of formations from which to draw
	var aroCurrentFormations = [];
	var aroAllFormations = [];
	for (ix = 0; ix < oDiscipline.aroFormations.length; ix++) {
		if (oDiscipline.aroFormations[ix].iClassLevel <= iLevel) {
			aroCurrentFormations.push(oDiscipline.aroFormations[ix]);
			aroAllFormations.push(oDiscipline.aroFormations[ix]);
		}
	}
	
	var aroRounds = []; // array of arrays
	for (ix = 1; ix <= oDrawRules.iNumberOfRounds; ix++) {
		aroRounds.push(aroDrawRound(aroAllFormations, aroCurrentFormations, oDrawRules, ix));
	}
	
	var sTitle = oDiscipline.sName + ' (' + oDiscipline.sClassNameFromLevel(iLevel) + ')';
	
	var sHTML = sBuildDrawHTML(oDiscipline, sTitle, aroRounds, iGetColumns());
	showContent(sHTML);
	
	m_txtSpecificDraw.value = sTextDrawFromRounds(aroRounds);
}

function sTextDrawFromRounds(aroRounds) {
	var ret = [];
	for (var ixRound = 0; ixRound < aroRounds.length; ixRound++) {
		if (ixRound > 0) { ret.push('\n'); }
		for (var ixFormation = 0; ixFormation < aroRounds[ixRound].length; ixFormation++) {
			if (ixFormation > 0) { ret.push(','); }
			ret.push(aroRounds[ixRound][ixFormation].sShortName);
		}
	}
	
	return ret.join('');
}

function iGetColumns() {
	var s = m_txtColumns.value;
	try
	{
		var i = parseInt(s);
		return i;
	}
	catch (ex) { }
	return 5;
}

function sBuildDrawHTML(oDiscipline, sTitle, aroRounds, iColumns) {
	iColumns = iColumns || 6;
	
	var ret = '<table border="0" cellpadding="1" cellspacing="2">';
	if (sTitle !== null && Trim(sTitle) != '') {
		ret += '<tr><th colspan="' + iColumns + '">' + sTitle + '</th></tr>';
	}
	
	var bMultipleRow = false; // have we fully added one row
	var ixColumn = 0;
	for (var ix = 0; ix < aroRounds.length; ix++) {
		ixColumn++;
		if (ixColumn > iColumns) {
			ixColumn = 1;
			ret += '</tr>';
			bMultipleRow = true;
		}
		
		if (ixColumn == 1) {
			if (bMultipleRow) {
				ret += '<tr class="DrawRoundMultipleRow">';
			} else {
				ret += '<tr>';
			}
		}
		
		ret += '<td valign="top" align="center"><table class="DrawRoundTable" border="1" cellpadding="1" cellspacing="1"><tr><th>Round ' + (ix+1) + '</th></tr>';
		
		for (var ixFormation = 0; ixFormation < aroRounds[ix].length; ixFormation++) {
			ret += '<tr>';
			ret += sTDFromFormation(aroRounds[ix][ixFormation]);
			ret += '</tr>';
		}
		ret += '</table></td>';
	}
	
	return ret;
}

function btnGenerateRelatedDraw_click() {
}

function btnGenerateSpecificDraw_click() {
	var oDiscipline = oSelectedDiscipline();
	if (oDiscipline === null) { return; }
	
	var aroRounds = [];
	
	var sDraw = m_txtSpecificDraw.value;
	var arsLines = sDraw.split(/[\r\n]/);
	for (var ixLine = 0; ixLine < arsLines.length; ixLine++) {
		var sLine = Trim(arsLines[ixLine]);
		if (sLine != '') {
			var aroRound = aroRoundFromDrawLine(sLine, oDiscipline.aroFormations);
			if (aroRound !== null && aroRound.length > 0) {
				aroRounds.push(aroRound);
			}
		}
	}
	
	var sHTML = sBuildDrawHTML(oDiscipline, $('txtTitle').value, aroRounds, iGetColumns());
	showContent(sHTML);
}

// sDrawLine is in the format of
// A,B,1,2
// or
// A B 1 2
function aroRoundFromDrawLine(sDrawLine, aroFormations) {
	var aroRound = [];
	var arsFormations = sDrawLine.split(/[\s\,]/);
	for (var ixFormation = 0; ixFormation < arsFormations.length; ixFormation++) {
		var sFormation = Trim(arsFormations[ixFormation]);
		if (sFormation != '') {
			var oFormation = oFormationFromShortName(sFormation, aroFormations);
			if (oFormation !== null) {
				aroRound.push(oFormation);
			}
		}
	}
	return aroRound;
}

function oFormationFromShortName(sShortName, aroFormations) {
	var sLower = sShortName.toLowerCase();
	for (var ix = 0; ix < aroFormations.length; ix++) {
		if (aroFormations[ix].sShortName.toLowerCase() == sLower) {
			return aroFormations[ix];
		}
	}
	return null;
}

function Trim(s) {
	return s.replace(/^\s+|\s+$/g,"");
}

function InitializePage() {
	m_oContentSpan = $("content");
	m_selClasses = $('selClasses');
	m_chkPictures = $('chkPictures');
	m_txtColumns = $('txtColumns');
	m_txtSpecificDraw = $('txtSpecificDraw');
	
	m_selDisciplines = $('selDisciplines');
	for (var ix = 0; ix < Disciplines.length; ix++) {
		m_selDisciplines.options.add(new Option(Disciplines[ix].sName));
	}
	m_selDisciplines.onchange = selDisciplines_change;
	m_selDisciplines.onclick = selDisciplines_change;
	m_chkPictures.onclick = m_chkPictures_click;
	$('btnShowDivePool').onclick = btnShowDivePool_click;
	$('btnGenerateDraw').onclick = btnGenerateDraw_click;
	$('btnGenerateRelatedDraw').onclick = btnGenerateRelatedDraw_click;
	$('btnGenerateSpecificDraw').onclick = btnGenerateSpecificDraw_click;
	
	if (m_selDisciplines.options.length >= 0) {
		m_selDisciplines.selectedIndex = 0;
		selDisciplines_change();
	}
}

function m_chkPictures_click() {
	var arElements = document.getElementsByTagName('span');
	var bVisible = m_chkPictures.checked;
	for (var ix = 0; ix < arElements.length; ix++) {
		if (arElements[ix].className == 'PictureDescriptionVisible' || arElements[ix].className == 'PictureDescriptionHidden') {
			var sClassName = (bVisible ? 'PictureDescriptionVisible' : 'PictureDescriptionHidden');
			if (arElements[ix].className != sClassName) { arElements[ix].className = sClassName; }
		}
	}
}

function $(element) {
	return document.getElementById(element);
}

function showDebug(s) {
	$('txtDebug').value = s;
}