
// NOTE: this file depends on utils.js


// NOTE: those cursors calls can break opera's rendering
// document.body.style.cursor = 'wait'
// document.body.style.cursor = 'default'


	var _schoolsArray = new Array();


	function resetAllSchools()
	{
		setTimeout('resetAllAynch()', 25)
	}

	function resetAllAynch()
	{
		var sa = new Array();

		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null)
			{
				sc.setTalentsRanksFromEncoded("", true) // force to inactive
				sa[sa.length] = sc;
			}
		}

		for (var i=0; i<sa.length; i++)
			sa[i].validateTalents(true);
	}

	function resetSchool(schoolPosition)
	{

		var sc = getSchoolByPosition(schoolPosition);
		if (sc != null)
		{
			sc.setTalentsRanksFromEncoded("", true) // force to inactive
			sc.validateTalents(true);
		}
	}

	function getSchoolsEncodedUrl()
	{
		var parms = Utils.extractParamsFromUrl();

		var ar = new Array();

		for (var i=1; i<=3; i++)
		{
			var sc = getSchoolByPosition(i);
			if (sc != null)
			{
				var pa = sc.getSchoolUrlParam();

				var updtd = false;
				for (var j=0; j<parms.length ; j++)
				{
					if (parms[j][0] == pa[0])
					{
						parms[j][1] = pa[1];
						updtd = true;
						break;
					}
				}

				if (!updtd)
				{
					parms[parms.length] = new Array()
					parms[parms.length-1][0] = pa[0]
					parms[parms.length-1][1] = pa[1]
				}
			}
		}

		var urrl = Utils.extractRadicalFromUrl()

		if ( urrl.indexOf('?')<0  )
			urrl += "?"

		for (var i=0; i<parms.length ;i++)
		{
			if (i>0)
				urrl += '&'
			urrl += parms[i][0] + '='+ parms[i][1];
		}
		
		// Get the current tab to save it in the URL
		var currentTab;
		for(i=0; i<3; i++) { // 3 is hardwired number of schools/specs
			if(document.getElementById("tabcontent_"+i).className == "tabvisible") { currentTab = i; }
		}     
		
		// if tab parameter is already set in the URL, remove it
		// this should be better integrated into the paramter code since checks for other params are done there
		// but it works fine as-is
		var tabParamIndex = urrl.indexOf('&tab=');
		if ( tabParamIndex >= 0 ) { 
			urrl = urrl.slice(0,tabParamIndex) + urrl.slice(tabParamIndex+6);
		}
		
		// Add the tab parameter to the URL
		urrl += "&tab=";
		urrl += currentTab;

		return (urrl);
	}

	function getSchoolsEncodedStr()
	{
		var s = ''

		for (var i=1; i<=3; i++)
		{
			var sc = getSchoolByPosition(i);
			if (sc != null)
			{
				var pa = sc.getSchoolUrlParam();

				if (s.length>0)
					s+= '&'

				s += pa[0] + '='+ pa[1];
			}
		}
		return s;
	}

	function initSchoolObj(jsonSchool)
	{
		var school = new SchoolObj()
		school.init(jsonSchool);
		return school;
	}

	function getSchoolById(schoolId)
	{
		return _schoolsArray[schoolId]
	}

	function getSchoolByPosition(schoolPosition)
	{
		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null && schoolPosition == sc.id_ui)
					return sc;
		}
		return null;
	}

	function repaintAllSchools()
	{
		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null)
				sc.repaint()
		}
	}

	function validateAllSchools()
	{
		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null)
				sc.validateTalents()
		}
	}

	function setTalentsDependancies()
	{
		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null)
				sc.drawDependancies()
		}
	}

	
	// -- School obj def --
	// IMPORTANT: instanciate using initSchoolObj()
	function SchoolObj()
	{
		this.init = function(jsonSchool)
		{
			this.id = jsonSchool.school_id;
			this.id_ui = jsonSchool.position;
			this.name = jsonSchool.name;

			this.name_encd = Utils.strReplace( this.name.toLowerCase(), " ", "_")

			this.talentsArray = new Array();

			_schoolsArray[this.id] = this;

			this.createTable(); // will init this.table
		};


		this.toString = function()
		{
			var str = 'School[' + this.id + ', pos: ' + this.id_ui + ', ';
				str += 'name: ' + this.name + ']';

			return str;
		};


		// note: we need to force a repaint later, because in some case some talents
		//       require other talents to be inited before painting (tooltip, level req)
		this.addTalent = function(talentObj)
		{
			// check if it is in there already
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var t = this.talentsArray[i];
				if (t.id == talentObj.id)
				{
					this.talentsArray[i] = talentObj;
					return;
				}
			}

			// nope, add it
			this.talentsArray[this.talentsArray.length] = talentObj;
		};


		this.getTalentById = function(talentId)
		{
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null && tal.id == talentId)
					return this.talentsArray[i];
			}
			return null;
		};



		this.reset = function(doValidate)
		{
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null && tal.rank> 0)
				{
					tal.rank = 0;
					tal.active = false;
				}
			}

			if (doValidate)
				this.validateTalents(true); // force repaint
		}


				this.sortByschoolReq = function(ta, tb)
				{
					var a = parseInt(ta.school_prereq ,10)
					var b = parseInt(tb.school_prereq ,10)

					if (a == b)
						return 0;
					else
					if (a<b)
						return -1;
					else
						return 1;
				}
				this.talentsArrayBySchoolReq = false;


		this.validateTalents = function(forceRepaint)
		{
			if (!this.talentsArrayBySchoolReq)
			{
				this.talentsArrayBySchoolReq = new Array();
				for (var i=0; i<this.talentsArray.length; i++)
					this.talentsArrayBySchoolReq[this.talentsArrayBySchoolReq.length] = this.talentsArray[i]
				this.talentsArrayBySchoolReq.sort(this.sortByschoolReq);
			}


				var prereq = 0;
				var schPoints = 0;
				var points = 0;

					for (var i=0; i<this.talentsArrayBySchoolReq.length; i++)
					{

						var tal = this.talentsArrayBySchoolReq[i];

						if (tal.school_prereq > prereq) // commit the counts
						{
							schPoints += points;
							points = 0;
							prereq = tal.school_prereq;
						}

						tal.updateState(schPoints + points, forceRepaint);

						if (tal.active && tal.rank>0 )
							points += tal.rank;
					}


			this.updatePointsDisplay();
			this.updateSummary();
		}




		this.restoreTalentsRank = function(parms)
		{
			var str = parms['sc_' + this.id_ui]

			if (str!= null)
				this.setTalentsRanksFromEncoded(str)
		}

		this.getSchoolUrlParam = function()
		{
			var r = new Array()

			r[0] = 'sc_' + this.id_ui;
			r[1] = this.getSchoolEncodedStr()

			return r
		}




		this.getSchoolEncodedStr = function()
		{
			// first sort the ids
			var ar = new Array();
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null)
				{
					ar[ar.length] = tal.id;
				}
			}

			// we don't care if it's not in order as long as we are always in the same order
			ar.sort();

			var r = ''
			for (var i = 0; i< ar.length; i++)
			{
				var tal = this.getTalentById(ar[i]);
				if (tal != null)
					r += tal.rank;
			}

				// trim ending 0s
				while ( r.charAt(r.length-1) == '0' )
					r = r.substring(0, r.length-1)

			return r;
		}



		this.setTalentsRanksFromEncoded = function(encoded, forceToInactive)
		{
			// put the values in an array
			var ss = new Array();
			for (var i = 1; i <= encoded.length; i++)
				ss[i-1] = encoded.substring((i - 1), i);


			// first sort the ids
			var ar = new Array();
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null)
					ar[ar.length] = tal.id ;

				if (ss.length < ar.length)
					ss[ss.length] = "0";
			}
			ar.sort();




			for (var i = 0; i <= ar.length; i++)
			{
				var t = this.getTalentById(ar[i]);
				if (t!= null)
				{
					// console.log( t.id + " > " + ss[i] + "    " + t.name)

					var or = t.rank;
					var oa = t.active;

					t.rank = parseInt(ss[i],10);
					if (forceToInactive)
						t.active = false;

					if (or != t.rank || oa != t.active)
						t.repaint()
				}
			}
		}














		this.getSchoolPoints = function()
		{
			var cnt = 0;

			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null)
					cnt += tal.rank;
			}

			return cnt;
		}




		this.repaint = function()
		{
			for (var i=0; i<this.talentsArray.length; i++)
			{
				var tal = this.talentsArray[i];
				if (tal != null && tal.repaint != null)
					tal.repaint();
			}
		};

		this.updatePointsDisplay = function()
		{
			// ex: school_1_points
			var fld = document.getElementById('school_' + this.id_ui + '_points');
			if (fld != null)
			{

				var s  = '<SPAN class="txtTitle">' + this.name + ': </SPAN>'
					s += '<SPAN class="txtCountHdr">' + this.getSchoolPoints() + ' ' + str_points + ' </SPAN>'

				fld.innerHTML = s;
			}

			Utils.updatePointsTotalDisplay();
		}




		this.updateSummary = function()
		{

			// ex: school_2_summary

			var fld = document.getElementById('school_' + this.id_ui + '_summary');
			if (fld != null)
			{

				var s = '<TABLE class="summary_school_table">'

				for (var i=0; i<this.talentsArray.length; i++)
				{

					var t = this.talentsArray[i];

					if ( t!= null && t.rank >0 )
					{
						s += '<TR><TD>'
							s += t.name;
						s += '</TD><TD style="text-align:right">'
							s += t.rank + ' / ' + t.rank_max;
						s += '</TD></TR>'
					}
				}
				s += '</TABLE>'

				fld.innerHTML = s;
			}
		}



		this.getBgImgPath = function()
		{
			return Utils.computeImgPathRoot(CurrentClass.name_encd, this.name_encd)  +  '/background.jpg';
		}



		this.createTable = function()
		{


			// Note: I did try to render the objects with the createElement() and obj.setAttributes() calls,
			//		 but doinf so was ignoring the table attributes which I need to render cells without padding


				var dv = document.getElementById("school_" + this.id_ui);

				if (dv === null)
				{
					alert("Error: couldn't init the School ["+ this.id +"].\nThis <DIV> must be defined in your body tag:\n <DIV id=\"school_"+ this.id_ui +"\" class=\"school\"></DIV>");
					return;
				}

				Utils.setBackgroundImg(dv, this.getBgImgPath());

				var nb_rows = 9*2-1;
				var nb_cols = 6*2-1;


				var str = '<TABLE cellpadding="0" cellspacing="0" border="0" id="school_table_' + this.id + '" class="school_table">'

				var isRowTal = true;

				var talent_row_id = 1;
				var talent_alt_row_id = 1;
				var talent_cell_id = 1;
				var talent_alt_cell_id = 1;

				// creating all cells
				for (var r=0;r<nb_rows; r++)
				{
					str += '<TR>'

					var isColTal = true;


					for (var c=0; c<nb_cols; c++)
					{
						if (isRowTal)
						{
							if (isColTal)
							{
								str += '<TD id="'+Utils.getCellTalentId(this.id, talent_row_id, talent_cell_id)+'">'
								str += Utils.getCellMainTalentEmpty();
								str += '</TD>'

							} else {

								str += '<TD id="'+Utils.getCellTalentSepId(this.id, talent_row_id, talent_cell_id)+'">'
								str += Utils.getCellMainSepEmpty();
								str += '</TD>'

								talent_cell_id++;
							}

						} else {

							if (isColTal)
							{
								str += '<TD id="'+ Utils.getCellAltId(this.id, talent_alt_row_id, talent_alt_cell_id)+'">'
								str += Utils.getCellSepTalentEmpty();
								str += '</TD>'

							} else {
								str += '<TD id="'+Utils.getCellAltSepId(this.id, talent_alt_row_id, talent_alt_cell_id)+'">'
								str += Utils.getCellSepSepEmpty();
								str += '</TD>'

								talent_alt_cell_id ++;
							}
						}


						isColTal = ! isColTal;

					} // end for c


					str += '</TR>'

					if (isRowTal)
						talent_row_id++;
					 else
						talent_alt_row_id ++;

					talent_alt_cell_id = 1;
					talent_cell_id = 1;

					isRowTal = ! isRowTal;

				} // end for r

				str += '</TABLE>';


				dv.innerHTML = str;

				tooltip.init();


			};





	/////// Draw dependancies //////

			// Note: this assumes req relationship don't go *thru* talents and don't cross
			this.drawDependancies = function()
			{
				var ar = new Array()

				for (var i=0; i<this.talentsArray.length; i++)
				{
					var t = this.talentsArray[i];
					if (t != null && t.talent_prereq > 0)
					{
						ar[ar.length] = new Array();
						ar[ar.length-1][0] = t.talent_prereq; // from
						ar[ar.length-1][1] = t.id; // to
					}
				}

				for (var i=0; i<ar.length; i++)
				{
					var tf = this.getTalentById(ar[i][0]);
					var tt = this.getTalentById(ar[i][1]);

					if (tf != null && tt != null)
					{
						if (tf.row == tt.row)
							this.drawDepH(tf.school_id, tf.row, tf.col, tt.col)
						else
						if (tf.col == tt.col)
							this.drawDepV(tf.school_id, tf.col, tf.row, tt.row)
					}
				}
			}
				this.drawDepH = function(schoolId, row, fromCol, toCol)
				{
					if (fromCol < toCol)
					{
						for (var i = fromCol; i < toCol; i++)
						{
							// talent column cell
							if (i != fromCol)
								this.drawCellTalentHoriz(Utils.getCellTalentId(schoolId, row, i));

							// sep column cell
							var id = Utils.getCellTalentSepId(schoolId, row, i)

							if (i < toCol-1) // just a link
								this.drawCellSepHoriz(id);
							else // arrow
								this.drawCellSepRight(id);
						}

					} else {


						for (var i = toCol; i < fromCol; i++)
						{
							// talent column cell
							if (i != toCol)
								this.drawCellTalentHoriz(Utils.getCellTalentId(schoolId, row, i));

							var id = Utils.getCellTalentSepId(schoolId, row, i)

							// sep column cell
							if (i == toCol)// arrow
								this.drawCellSepLeft(id);
							else // just a link
								this.drawCellSepHoriz(id);
						}
					}
				}
								this.drawCellTalentHoriz = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellMainTalentHoriz();
								}
								this.drawCellSepHoriz = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellTalentSepHoriz(cellId);
								}
								this.drawCellSepLeft = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellSepTalentLeft();
								}
								this.drawCellSepRight = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellSepTalentRight();
								}


				this.drawDepV = function(schoolId, col, fromRow, toRow)
				{

					for (var i = fromRow; i < toRow; )
					{
						// start with the cell below the talent - td_alt_18_1_3 // getCellAltId
						if (i < toRow-1)
							this.drawCellSepVert(Utils.getCellAltId(schoolId, i, col));
						else
							this.drawCellSepDown(Utils.getCellAltId(schoolId, i, col))

						i++; // ok, next talent line

						// cell with a talent = td_talent_18_2_3 // getCellTalentId
						if (i<toRow)
							this.drawCellTalentVert(Utils.getCellTalentId(schoolId, i, col))
					}
				}
								this.drawCellTalentVert = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellMainTalentVert();
								}
								this.drawCellSepVert = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellTalentSepVert(cellId);
								}
								this.drawCellSepDown = function(cellId)
								{
									var c = document.getElementById(cellId);
									if (c == null)
										return;
									c.innerHTML = Utils.getCellSepTalentDown();
								}

	/////// END Draw dependancies //////


		}
	// -- School obj def --

	function onPresetChanged(selElt)
	{
		if (presetEvtHold)
			return;

		for (var i=0; i<selElt.options.length; i++)
		{
			var opt = selElt.options[i]
			if (opt.selected)
			{
				if (opt.value.length>0)
					setTimeout('presetSetAsynch("' + opt.value + '")', 25)

				return;
			}
		}
	}
	
	var presetEvtHold = false;

	function presetSetAsynch(prmStr)
	{
		var prmsAr = prmStr.split('&')
		var parms = Utils.splitSchoolsParams( prmsAr )

		restoreSchoolsTalentsRanks(parms);
	}

	function matchPresetsList()
	{
		var selElt = document.getElementById('schs_presets');

		if (selElt != null)
		{

			if (Utils.getPointsTotal() == 0)
			{
				presetEvtHold = true;
				selElt.selectedIndex = 0;
				presetEvtHold = false;
				return;
			}

			var cur = getSchoolsEncodedStr();

			for (var i=0; i<selElt.options.length; i++)
			{
				var opt = selElt.options[i]
				if (cur == opt.value)
				{
					presetEvtHold = true;
					selElt.selectedIndex = opt.index;
					presetEvtHold = false;
					return;
				}
			}

			// no match - unselect
			presetEvtHold = true;
			selElt.selectedIndex = 0;
			presetEvtHold = false;

		}
	}

	function checkSchoolsRestoreFromUrl()
	{
		var query = window.location.search;
			query = Utils.strReplace(query, '??', '?');
			query = query.substring(1);

		var parms = Utils.splitSchoolsParams( query.split('&') )
		restoreSchoolsTalentsRanks(parms);
	}

	function restoreSchoolsTalentsRanks(parms)
	{
		for (var i=0; i<_schoolsArray.length; i++)
		{
			var sc = _schoolsArray[i];
			if (sc != null)
				sc.restoreTalentsRank(parms);
		}
		validateAllSchools();
	}


