var debugTable = null;
var openWindowDataShow = "";
var apiToolsIncluded = false;

function findFrame(name, frame)
{
	for (var i = 0; i < frame.length; i++) {
		if (frame[i].name == name) {
			return frame[i];
		} else {
			var result = findFrame(name, frame[i]);
			if (result) return(result);
		}
	}
	return(null);
};
function findUserVars(win)
{	
	try { //pg2-in case of https:// and a course in new window, there could be an exception- just intercept it, do nothing
		if (win.extContent) return null;
	} catch(e) {};
	try {
		if (win.me != null) return win.me;
	} catch(e) {};
	if (checkFrame(win.location)) return null;
	storeFrame(win.location);	
	
	if (win.length > 0) {
		for(var i = 0; i < win.length; i++) {
			var me = findUserVars(win.frames[i]);
			if (me != null) return me;
		}
		var winParent = null;
		try {
			winParent = win.parent;
			if (winParent.name == win.name) return null;
		} catch(e) {};
		
		if (winParent != null) {
			var me = findUserVars(winParent);
			if (me != null) return me;
		}
	}
	return null;
};

function getUserVars()
{
	try {
		var obj = window.parent;
		while (obj) {
			if (obj.me) return obj.me;
			if (obj == window.top) break;
			obj = obj.parent;
		}
	} catch(e) {};
	
	var me = findUserVars(parent);
	framesTable = new Array();
	return me;
};
function findPlayerInterface(win)
{	
	try {
		if (win.extContent) return null;
	} catch(e) {};
	try {
		if (win.PlayerInterface != null) return win.PlayerInterface;
	} catch(e) {};
	if (checkFrame(win.location)) return null;
	storeFrame(win.location);	
	
	if (win.length > 0) {
		for(var i = 0; i < win.length; i++) {
			var PlayerInterface = findPlayerInterface(win.frames[i]);
			if (PlayerInterface != null) return PlayerInterface;
		}
		var winParent = win.parent;
		
		if(winParent.name == win.name) return null;
		
		if (winParent != null) {
			var PlayerInterface = findPlayerInterface(winParent);
			if (PlayerInterface != null) return PlayerInterface;
		}
	}
	return null;
};

function getPlayerInterface()
{
	try {
		var obj = window.parent;
		while (obj) {
			if (obj.PlayerInterface) return obj.PlayerInterface;
			if (obj == window.top) break;
			obj = obj.parent;
		}
	} catch(e) {};
	var PlayerInterface = findPlayerInterface(parent);
	framesTable = new Array();
	return PlayerInterface;
};
function findPageInterface(win)
{	
	try {
		if (win.extContent) return null;
	} catch(e) {};
	try {
		if (win.PageInterface != null) return win.PageInterface;
	} catch(e) {};
	
	if (checkFrame(win.location)) return null;
	storeFrame(win.location);	
	
	if (win.length > 0) {
		for(var i = 0; i < win.length; i++) {
			var PageInterface = findPageInterface(win.frames[i]);
			if (PageInterface != null) return PageInterface;
		}
		var winParent = win.parent;
		
		if(winParent.name == win.name) return null;
		
		if (winParent != null) {
			var PageInterface = findPageInterface(winParent);
			if (PageInterface != null) return PageInterface;
		}
	}
	return null;
};

function getPageInterface()
{
	try {
		var obj = window.parent;
		while (obj) {
			if (obj.PageInterface) return obj.PageInterface;
			if (obj == window.top) break;
			obj = obj.parent;
		}
	} catch(e) {};
	var PageInterface = findPageInterface(parent);
	framesTable = new Array();
	return PageInterface;
};
function setOpenWindowDataShow(value)
{
	openWindowDataShow = value;
	
	getReportType();	
}
function getReportType() 
{
	removeDebugTable();

	switch (openWindowDataShow)
	{
		case "showCourseConfig" :
			showCourseConfig();
			break;
		case "showUELOData" :
			showUELOData();
			break;
		case "showUELOPagesStatus" :
			showUELOPagesStatus();
			break;	
		case "showUELOPageInteractions" :
			showUELOPageInteractions();
			break;	
		case "getLessonStatus" :
			getLessonStatus();
			break;	
		case "getTotalScore" :
			getTotalScore();
			break;	
		case "showUserVars" :
			showUserVars();
			break;	
		case "getExerciseTryMaxNumberTitle" :
			getExerciseTryMaxNumberTitle();
			break;
	}
}
function removeDebugTable() 
{	
	debugTable = null;
}
function setDebugTableColpan(colgroupWidthArr) 
{
	if (!debugTable) debugTable = document.createElement('table');
	var colGr = document.createElement("COLGROUP");	
	var col = null;
	
	for (var i=0; i < colgroupWidthArr.length; i++)
	{	
		col = document.createElement("COL");	
		col.setAttribute("width", colgroupWidthArr[i]);
		colGr.appendChild(col);
	}
	debugTable.appendChild(colGr);
}
function setDebugTableHeader(headerNamesArr) 
{
	if (!debugTable) debugTable = document.createElement('table');
	var newRow = debugTable.insertRow(0);
	var newCell = null;
	
	for (var i=0; i < headerNamesArr.length; i++)
	{	
		newCell = newRow.insertCell(i);
		newCell.className = 'header';
		newCell.innerHTML = headerNamesArr[i];
	}
}
function setDebugTableRowSeparator(colspan, separatorColor) 
{
	if (!debugTable) debugTable = document.createElement('table');
	
	var newRow = debugTable.insertRow(debugTable.rows.length);
	var newCell = newRow.insertCell(0);
	newCell.setAttribute("colspan", colspan);
	newCell.style.cssText += "background-color: "+separatorColor;
	newCell.innerHTML = '&nbsp;'
}
function createDebugTable() 
{
	if (!debugTable) debugTable = document.createElement('table');
	debugTable.setAttribute('id', 'debugTable');
	
	var newRow = debugTable.insertRow(debugTable.rows.length);
	var newCell = null;
	
	for (var i=0; i < arguments.length; i++)
	{
		newCell = newRow.insertCell(i);
		newCell.innerHTML = arguments[i];
	}
}
function writeContentToWindow(theElement) 
{
	var logsData = document.getElementById('logsData');
	logsData.removeChild(logsData.firstChild);
	logsData.appendChild(theElement);
}
function getDebugTable() 
{
	if (debugTable) 
	{
		return debugTable;
	} else {
		return "";		
	}
}
function showCourseConfig(obj) 
{
	try {
		var content = findFrame("page_frame", top);
		if (content && content.config)
		{
			var config = content.config;
			
			setDebugTableHeader(['Nazwa parametru', 'Wartosc parametru']);
			setDebugTableColpan(['50%', '50%']);
			
			for (var k in config)
			{
				createDebugTable(k, config[k])
			}
			writeContentToWindow(getDebugTable());
		}
	} catch(e) {};
}
function showCorrectAnswer() 
{
	var coursePage = getPage();
	if (coursePage)
	{
		coursePage.showCorrectAnswer();
	}
}
function prevStep() 
{
	var PInterface = getPageInterface();
	if (PInterface) PInterface.Execute("prevStep");		
}
function prevPage() 
{
	var PInterface = getPageInterface();
	if (PInterface) PInterface.Execute("prevPage");		
}
function resetPage() 
{
	var coursePage = getPage();
	if (coursePage)
	{
		coursePage.resetPage();
	}
}
function confirmAnswer() 
{
	var coursePage = getPage();
	if (coursePage)
	{
		coursePage.actionCheckAnswer();
	}
}
function nextStep() 
{
	var PInterface = getPageInterface();
	if (PInterface) PInterface.Execute("nextStep");		
}
function nextPage() 
{
	var PInterface = getPageInterface();
	if (PInterface) PInterface.Execute("nextPage");		
}
function setPageStatus(status) 
{
	var coursePage = getPage();
	if (coursePage)
	{
		coursePage.setPageStatus(status);
	}
}
function showUELOData() 
{
	if (!uelo) var uelo = getUELO();
	if (uelo)
	{
		var displayProp = ['courseName', 'courseDescription', 'percentCompleted', 'pagesCount', 'pointsMax', 'passThreshold', 'beginTime', 'endTime', 'sessionTime', 'userVars', 'lastVisitedPage', 'courseOryginalStatus', 'courseOryginalScore' ];	

		setDebugTableHeader(['Nazwa parametru', 'Wartosc parametru']);
		setDebugTableColpan(['50%', '50%']);
		
		for (var i=0; i < displayProp.length; i++)
		{
			createDebugTable(displayProp[i], uelo[displayProp[i]])
		}
		writeContentToWindow(getDebugTable());
	}	
}
function getParagraphColor(text, colour) 
{
	return '<p style="color:'+colour+'">'+text+'</p>';
}
function reformatPageName(pageGix, pageName) 
{
	return '<p style="text-decoration: underline; cursor: pointer;" onClick=\'getPlayerInterface().Execute("gotoPage", '+pageGix+');\'>'+pageName+'</p>';
}
function reformatStatus(text) 
{
	switch (text)
	{
		case 'N' :
			return getParagraphColor(text, '#ff0000');
			break;
		case 'I' :
			return getParagraphColor(text, '#ff0000');
			break;
		case 'C' :
			return getParagraphColor(text, '#00ff00');
			break;
		case 'P' :
			return getParagraphColor(text, '#00ff00');
			break;
		case 'F' :
			return getParagraphColor(text, '#ff0000');
			break;
	}
}
function showUELOPagesStatus() 
{
	if (!uelo) var uelo = getUELO();
	if (uelo)
	{
		setDebugTableHeader(['Nazwa strony', 'Status']);
		var pagesArr = uelo.getPagesArrWithStatus();
		
		for (var i=0; i < pagesArr.length; i++)
		{
			createDebugTable(reformatPageName(pagesArr[i][0], pagesArr[i][1]), reformatStatus(pagesArr[i][2]));
		}		
		
		writeContentToWindow(getDebugTable());
	}
}
function getUELOPageInteractions(pageGlobalIndex, displayValues) 
{
	var result = "";
	if (!uelo) var uelo = getUELO();
	if (uelo)
	{	
		var ueloPage = uelo.FindPage(pageGlobalIndex);
		if (ueloPage) {
			for (var i = 0; i < ueloPage.interactions.length; i++) 
			{
				if (i != 0) setDebugTableRowSeparator(2, '#d2d2d2');
				var inter = ueloPage.interactions[i];
				for (var j = 0; j < displayValues.length; j++) 
				{
					createDebugTable(displayValues[j], inter[displayValues[j]]);
				}
			}
		}
	}
}
function showUELOPageInteractions() 
{
	var coursePage = getPage();
	if (coursePage)
	{
		setDebugTableHeader(['Nazwa parametru', 'Wartosc parametru']);
		setDebugTableColpan(['50%', '50%']);
		
		var displayValues = [ 'gix', 'id', 'elementId', 'correctResponses', 'studentResponse', 'all_possible', 'answerValuesString', 'correctResponsesAsText', 'studentResponseAsText', 'time', 'timestamp', 'type', 'weighting', 'status', 'result', 'maxScore', 'score',  'question', 'latency', 'tryNumber', 'maxTryNumber' ];

		getUELOPageInteractions(coursePage.p_globalIndex, displayValues);
		
		writeContentToWindow(getDebugTable());
	}
}
function getLessonStatus() 
{
	if (!player) var player = getPlayer();
	if (player)
	{	
		setDebugTableHeader(['Status kursu']);
		createDebugTable(player.getLessonStatus())
		
		writeContentToWindow(getDebugTable());
	}
}
function getTotalScore() 
{
	if (!player) var player = getPlayer();
	if (player)
	{	
		setDebugTableHeader(['Poziom zaliczenia kursu (w %)']);
		createDebugTable(player.getTotalScore())
		
		writeContentToWindow(getDebugTable());
	}
}
function getExerciseTryMaxNumberFromUelo()
{
	if (!uelo) var uelo = getUELO();
	if (uelo)
	{	
		var uPage = null;
		for (var i = 0; i < uelo.pages.length; i++) {
			uPage = uelo.pages[i];
			if (uPage.visible == 1 && uPage.interactions.length < 1) continue;
			createDebugTable(uPage.title, uPage.interactions[0].tryNumber, uPage.interactions[0].maxTryNumber);
		}	
	}
};
function getExerciseTryMaxNumberTitle() 
{
	setDebugTableHeader(['Nazwa strony', 'Liczba prob wykorzystanych', 'Maksymalna liczba prob']);
	setDebugTableColpan(['60%', '20%', '20%']);		
	
	getExerciseTryMaxNumberFromUelo();
	
	writeContentToWindow(getDebugTable());
}
function showUserVars() 
{
	var userVars = getUserVars();
	if (userVars)
	{
		this.setDebugTableHeader(['Param Name', 'Value']);
		
		for (var k in userVars)
		{
			this.createDebugTable(k, userVars[k])
		}
		this.writeContentToWindow(this.getDebugTable());
	}
}
function gotoPage(obj)
{
	getPlayerInterface().Execute("gotoPage", obj.value);	
	//var p = getPage();
	//p.gotoPage(obj.value);
}
function gotoStep(obj)
{
	if (obj.value != 0)
	{
		getPageInterface().Execute("skipToChosenStep", obj.value);
//		PageInterface.Execute("nextStep");
	} else {
		getPageInterface().Execute("refreshPage");		
	}
}
function fillSelectPagesName() 
{
	var pagesList = document.getElementById('pagesList');
	var pageGix = getPageInterface().GetValue("pageGix");	
	
	var uelo = getUELO();
	var item = null;
	var option = null;
	var title = "";
	
	for (var i = 0; i < uelo.pages.length; i++) {
		item = uelo.pages[i];
		option = document.createElement("OPTION");
		title = item.title;
		
		if (item.realParent != "1"){
			//option.className = "move";
			title = "--" + title;
		}
		option.text = title +" ["+item.globalIndex+"]";
		option.value = item.globalIndex;
		if (pageGix == item.globalIndex) option.selected = true;
		pagesList.options.add(option);
	};
}
function removeSelectOptions() 
{
	var stepsList = document.getElementById('stepsList');
	var stepsListL = stepsList.options.length;
	
	for (var i = 0; i <= stepsListL; i++) {
		stepsList.options.remove(0);
	};
}
function fillSelectPageSteps() 
{
	removeSelectOptions();
	
	var stepsList = document.getElementById('stepsList');
	PageInterface = getPageInterface();
	if (PageInterface && stepsList) //pg2- && stepsList
	{
		var pageStepsCount = PageInterface.GetValue("pageStepsCount");
		var item = null;
		var option = null;

		option = document.createElement("OPTION");
		option.text = "Step 0";
		option.value = "0";
		stepsList.options.add(option);	
		
		for (var i = 1; i <= pageStepsCount; i++) {
			option = document.createElement("OPTION");
			option.text = "Step "+i;
			option.value = i;
			stepsList.options.add(option);
		};
	}
}
function includeApiTools() 
{
	var fr = null;
	var script_tag = null;
	try {
		fr = findFrame("content", top);
	} catch(e) {
		fr = null;
	}
	if (fr) {
		script_tag = fr.document.getElementsByTagName("script");
		
		for (i = 0; i < script_tag.length; i++ ) 
		{
			if (script_tag[i].src.indexOf("tools.js") != -1) 
			{
				var head_tag = document.getElementsByTagName("head");
				var script = document.createElement("script");
				script.setAttribute('type', 'text/javascript');
				script.setAttribute('src', script_tag[i].src);
				head_tag[0].appendChild(script);
				apiToolsIncluded = true;
			}
		}
	}
	return apiToolsIncluded;
}
function checkApiToolsIncluded() 
{
	if (apiToolsIncluded) 
	{
		return true;
	} else {
		return includeApiTools();
	}
}
var d = new Date();
var timer = d.getTime();
var timerObj = null;

function writeTimer() 
{
	var timer1st = document.getElementById("timer1st");
	if (timer1st) { //pg2
		var d = new Date();
		var nowMili = d.getTime();
		timer1st.innerHTML = nowMili - timer;
	}
}
function timerStop() 
{
	window.clearTimeout(timerObj);
	timerObj = null;
	writeTimer();
}
function startTimer() 
{
	writeTimer();
	timerObj = setTimeout("startTimer();", 900);
}
function fillTemplateInformations() 
{
	var d = new Date();
	timer = d.getTime();
	startTimer();
	if (checkApiToolsIncluded()) setTimeout("fillSelectPagesName();", 1000);
}
function updateDebugInformations() 
{
	if (checkApiToolsIncluded()) 
	{
		fillSelectPageSteps();	
		
		var coursePage = getPage();
		if (coursePage)
		{
			setInner('pageStatus', coursePage.pageStatus);
			setInner('pageType', coursePage.pageType);
			setInner('stepsCount', coursePage.steps.length-2);
			setInner('masteryScore', coursePage.masteryScore+"%");
			setInner('userScore', coursePage.userScore+"%");
		}
	}
}
function setValue(where, value) 
{
	var element = document.getElementById(where);
	if (element) element.value = value;
}
function setInner(where, inner) 
{
	var element = document.getElementById(where);
	if (element) element.innerHTML = inner;
}
function collapseExpandBox(e, subMenuId, icoId) {
	var subMenu = document.getElementById(subMenuId);
	
	var img = document.getElementById(icoId);
	
	var imgPathArr = new Array();
	if (img) imgPathArr = img.src.split('/');
	
	if (subMenu) {
		showHideDiv(img, subMenu, 'box_collapse.gif', 'box_expand.gif', imgPathArr);
	}
	e.cancelBubble = true;
}
function showHideDiv(imgObj, divObj, icoCollapse, icoExpand, imgPathArr) 
{
	if (divObj.style.display == "none"){
		divObj.style.display = "block";
		imgPathArr[imgPathArr.length-1] = icoCollapse;
	} else {
		divObj.style.display = "none";
		imgPathArr[imgPathArr.length-1] = icoExpand;
	}
	if (imgObj) imgObj.src = imgPathArr.join('/');
}
function removeWatch()
{
	var watchTable = document.getElementById('watchTable');
	var watchRow = document.getElementById('row_'+this.id);
	var rI = -1;
	if (watchRow && watchTable) { //pg2- && watchTable
		rI = watchRow.rowIndex;
		watchTable.deleteRow(rI);
	} else {
		return false;
	}
}
function replaceWatchData(value)
{
	var userWatchData = value.replace('page', 'getPage()');
	userWatchData = userWatchData.replace('struct', 'getStruct()');
	userWatchData = userWatchData.replace('player', 'getPlayer()');
	
	return userWatchData;
}
function gerateId()
{
	var d = new Date();
	
	return d.getTime();
}
function evalWatch(e, obj)
{
	if (obj.value != "")
	{
		var watchTable = document.getElementById('watchTable');
		if (watchTable) { //pg2
			var rowsL = watchTable.rows.length;
			var newRow = watchTable.insertRow(rowsL);
			var uniqeId = gerateId();
			
			newRow.setAttribute('id', 'row_close'+uniqeId);
			var newCell = null;		

			newCell = newRow.insertCell(0);
			newCell.innerHTML = obj.value;

			newCell = newRow.insertCell(1);
			newCell.innerHTML = "|";
			
			newCell = newRow.insertCell(2);
			try{
				var content = findFrame("content", top);
				if (content)
				{		
					var userWD = replaceWatchData(obj.value);
					newCell.innerHTML = eval('content.'+userWD);
				}
			}catch(e){
				newCell.innerHTML = 'watch error';
			}

			var img = document.createElement('img');
			img.setAttribute('id', 'close'+uniqeId);
			img.setAttribute('src', '../resources/close.gif');
			img.onclick = removeWatch;	
			newCell = newRow.insertCell(3);
			newCell.appendChild(img);
			
			obj.value = "";
		}
	}
}
var dragElement = null;
var dragElementOffsettop = 0;
function getDragElementOffsettop(obj)
{
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else
	if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
function getElement(elemId)
{	
	return document.getElementById(elemId);
}
function divMousedown(elemId)
{
	var obj = getElement(elemId);
	dragElement = obj;
	dragElementOffsettop = getDragElementOffsettop(obj);
}
function divMouseup()
{
	dragElement = null;
	dragElementOffsettop = 0;
}
function divMousemove(e)
{
	if (dragElement) {
		e = (e)?e:event;	
		var h = parseInt(e.clientY - dragElementOffsettop - 5);
		
		dragElement.style.height = ((h>0)?h:1) + 'px';
	};
}
