var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
var applicationPages = ['engine.html', 'engine.php', 'other.html'];
var applicationURL = 'qcc.icomsystem.net';
var confirmExit = true; // doe we ask if leaving a page in the application?
var application = false;
var launched = false;

var JSdocs = [
	
];
var CSSdocs = [];

var req = null; // new JSHttpRequest();
var config = false;
var cfgClasses = false;
var noticeFadedOpacity = 45;
var currentCoursePath = false;
var currentCourseTitle = false;
var topicsXML = false;
var includedScripts = new Array();
var topicsObj = false;
var currentTopicIndex = false;
var currentProblems = false;
var systemInit = false;
var conceptList = false;
var basepath = false;
var currentProblemIndex = false;

var debug= false;

var explain = false;

function init(){
	if(systemInit){
		
		
	}else{
	
		window.onbeforeunload = function(e){
			if(confirmExit){
				
				var thisPage = getPageFile();
				var confirmNav = true;
				for(var n=0; n<=applicationPages.length; n++){
					if(thisPage==applicationPages[n]) confirmNav = false;
		
					if(!confirmNav){
						//alert('we are navigating to another page in teh system.');
						if(isIE) event.returnValue = 'Leaving this page will exit the system.';
						else e.returnValue = 'Leaving this page will exit the system.';
						quit();
						window.onfocus = function(){
							
							closeNotice();	
						}
						return false;
					}
				}
			}
		}
		if(inApplication()) loadConfig()
		//checkBrowserWidth();
	}
}
var classes = false;

function loadConfig(data){
	
	
			
	
	if(data){
		//alert(data);
		config = parseDOM(data);
		basepath = getNodeText(config, 'basePath');
		dataObj['classes'] = classes = config.getElementsByTagName('class');
		
		loadClasses(classes);
		loadConcepts('global/concepts.xml');
		//alert('basePath=' + getText(basepath[0]) + '\n-----------------------\n' + classes.length + ' classes:\n');
		//loadClasses();
		return;
	}

	var req = new getXMXHTTPRequest();
	req.open("GET", "global/config.php?" + Math.random(), true);
	req.onreadystatechange = function(){
		if(req.readyState ==4){
			
			if(req.status == 200){
				loadConfig(req.responseText);
				
			}
		} else {
			//alert('Problem: XMP HTTPRequest status: ' + req.status);
		}
	};
	// send the request for the xml file
	try {
		req.send(null);
	} catch(e){
		
		alert(e);	
	}
}



function reloadProblemsXML(data){
	
	config = parseDOM(data.responseText);
	//basepath = getNodeText(config, 'basePath');
	dataObj['problems-list'] = config.getElementsByTagName('problem');


	alert('reloading problems' + dataObj['problems-list'].length);
	//loadColumn(dataObj['problems-list']);
	
}
function loadTopicsXML(data){
	
	config = parseDOM(data.responseText);
	dataObj['topics-list'] = config.getElementsByTagName('topic');
	
	alert('reloading tiopics' + dataObj['topics-list'].length);
	
	
	
	//loadClasses(dataObj['classes']);
}
function loadClassesXML(data){
	//alert(data + ' loading Classes');
	config = parseDOM(data.responseText);
	basepath = getNodeText(config, 'basePath');
	dataObj['classes'] = config.getElementsByTagName('class');
	loadClasses(dataObj['classes']);
}
function editDialog(args){
	
	var onSuccess = function(o) {
		alert("Your data was successfully submitted. The response was: " + o.responseText);
	}
	var onFailure = function(o) {
		alert("Your submission failed. Status: " + o.status);
	}
	var onCancel = function(o){
	
		this.hide();
	
	}
	var onSubmit = function(o){
	
		var afterAdd = function(obj){
			args.api.reload(obj);			
		}
		
		apiCall(args.api.add, 'name=' + escape(this.getData().name), false, afterAdd);
		
		switch(args.module){
			case("problems"):
			
			break;
			default:	//mainClickNode.onclick();
		}
		
		//args.api.reload();
		this.hide();
	}
	Feedback.edit= new YAHOO.widget.Dialog("editDialog", { 
		modal: true,
		width:"300px", 
		visible:false, 
		draggable:true, 
		fixedcenter: true,
		close:true,
		constraintoviewport: true,
		effect: [ {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25} ],
		buttons: [
				  { text: 'Save', handler: onSubmit, isDefault: true },
				  { text: 'Cancel', handler: onCancel, isDefault: false }
				  ]
	} ); 
	
	
	
	// add a subscribe to teh form submit to do the onsubmit handler
	
	Feedback.edit.submitEvent.subscribe(onSubmit);
	
	Feedback.edit.callback.success = onSuccess;
	Feedback.edit.callback.failure = onFailure;
	//selectListItem(this.parentNode);
	Feedback.edit.cfg.queueProperty("postmethod", "none");
	Feedback.edit.setHeader('Adding...');
	Feedback.edit.render();
	
	
	
	Feedback.edit.form.id.value = '';		
	Feedback.edit.form.name.value = '';			
	
	Feedback.edit.hideMacGeckoScrollbars();
	
	
	Feedback.edit.show();
			
			
}
function loadClasses(classes){
	

	//Feedback.trace('loadClasses()');


	var cb = {
		addHandler: function(obj){
			
			
			//alert('adding problem to topic' + id);
			editDialog(cb);
			return;
			
			
			
			var name = prompt('name?', '');
			
			if(name!=false){
				
				// 
				var cc = function(req){
					
					apiCall('loadClasses', '', false, loadClassesXML);
				}
				
				apiCall('addClass', 'name=' + name, false, cc);	
			}
			//alert('custom add handler');
			
		},
		deleteHandler: function(obj){
			
			alert('custom delete handler');
			
		},
		onclick: function(obj){
			
			//alert('Clicked Class' + obj.parentNode.getAttribute('itemid'));
			selectClass(0, obj.parentNode.getAttribute('itemid'));
			
			//loadTopic(obj.parentNode.getAttribute('itemid'));
		},
		titleAttribute: { 
			path: "getText(items[n].getElementsByTagName('title')[0])" 
		},
		module: 'classes',
		moduleId: 1,
		api: {
			'add':	'addClass',
			'edit': 'editClass',
			'delete': 'deleteClass',
			'reload': loadClassesXML
			
		}
	}

	loadColumn(classes, 'class-list', cb);

}


function _loadClasses(classes){
	
	cfgClasses = classes;
	
	var classlist = document.getElementById('class-list');
	clearList(classlist);
	
// -- START MANAGEMENT
	var li = document.createElement('li');
	li.index = -1;
	var a = document.createElement('a');
	a.onclick = function(){
		
		selectListItem(this.parentNode);
		addClass({
				 list: this.parentNode.parentNode
				 });
	}
	
	a.innerHTML = "Add new...";
	li.appendChild(a);
	classlist.appendChild(li);
// --END MANAGEMENT
	
	
	for(var n=0; n<classes.length; n++){
		
		//alert(classes[n].childNodes);
		var li = document.createElement('li');
		li.index = n;
		li.id = classes[n].getAttribute('id');
		var a = document.createElement('a');
		
		a.onclick = function(){
			//alert(this.parentNode.tagName);
			
			//alert('selected class' + this.parentNode.id);
			
			currentModule = this.parentNode.id;
		
			selectListItem(this.parentNode);
			selectClass(this.parentNode.index, this.parentNode.id);
		}
		a.innerHTML = getNodeText(classes[n], 'title');
		
		/*
		li.innerHTML = getText(classes[n].getElementsByTagName('title')[0]) + '\n' 
						+ " path: " + getText(classes[n].getElementsByTagName('path')[0]);
		
		*/
		li.appendChild(a);
		classlist.appendChild(li);
	}
}


function loadTopics(topics){
	
	topicsObj = topics;
								
	//alert('loading ' + topics.length + 'topics for class: ' + currentCourseTitle);
	var topicsList = document.getElementById('topics-list');
	
	clearList(topicsList);
	
	for(var n=0; n<topics.length; n++){

		//alert(classes[n].childNodes);
		var li = document.createElement('li');
		li.index = n;
		
		var a = document.createElement('a');
		a.index = n;
		
		if(topics[n].getAttribute('onclick')){
			a.onclick= function(){
				//eval(topics[n].getAttribute('onclick'));
			}
		} else {
			
			if(topics[n].getAttribute('subdatafile')){
			
				a.datafile = topics[n].getAttribute('subdatafile');
				a.onclick = function(){
					
					alert('load the last column data with a file:' + this.datafile);
				};
			} else {
				a.onclick = function(){
					
					selectListItem(this.parentNode);
					selectTopic(this.index);
				}
			}
		}
		
		if(topics[n].getAttribute('checkbox')=="yes"){
			var c = document.createElement('input');
			c.type = 'checkbox';
			c.style.display = 'inline';
			a.appendChild(c);
		}

		if(topics[n].getAttribute('img')){
			var c = document.createElement('img');
			c.src = topics[n].getAttribute('img');
			c.style.display = 'inline';
			c.height = '30';
			a.appendChild(c);
		}

		var s = document.createElement('span');
		s.style.display = 'inline';
		s.innerHTML = topics[n].getAttribute('title');
		a.appendChild(s);
		li.appendChild(a);
		topicsList.appendChild(li);
	}
}




function loadConcepts(path){

	var req2 = new getXMXHTTPRequest();
	req2.open("GET", path + "?" + Math.random(), true);
	req2.onreadystatechange = function(){
		if(req2.readyState ==4){
			if(req2.status == 200){
				//alert(req2.responseText);
				conceptList = Array();
				var concepts = parseDOM(req2.responseText).getElementsByTagName('concept');
				
				for(var n=0; n<concepts.length; n++){
					conceptList[concepts[n].getAttribute('id')] = {
						title: 	getNodeText(concepts[n], 'title'),
						text:	getNodeText(concepts[n], 'text')
					};
					
				}
				//loadConcepts(req2.passAlong, req2.responseText);
			}
		} else {
			//alert('Problem: XMP HTTPRequest status: ' + req.status);
		}
	};
	// send the request for the xml file
	try {
		req2.send(null);
	} catch(e){
		
		alert(e);	
	}
}

if(debug) alert("loaded lib.js");



function loadHints(){
	
	//if(visibleHints>totalHints) var num = totalHints;
	//else var num = visibleHints;
	
	 var num = totalHints;
	
	var hintsList = document.getElementById('hints-list');
	
	clearList(hintsList);
	// add the hints to teh display
	for(var n=0; n<num; n++){
	
		var li = document.createElement('li');
		li.index = n;
		if(n<visibleHints) {
			li.className = 'enabled';
		
			var a = document.createElement('a');
			a.index = n;
			
			li.onclick = function(){
				
				showHint( (this.index + 1) );
				//selectListItem(this.parentNode);
				//selectQuestion(this.index);
			}
		}
		//a.innerHTML = "<div>" + (n+1) + "</div>";
		//li.appendChild(a);
		
		li.innerHTML = "<div>" + (n+1) + "</div>";
		hintsList.appendChild(li);
	}
}


function loadQuestions(questions){
	
	
	document.getElementById('questions-list').parentNode.parentNode.scrollTop = 0;
	
	if(questions) currentProblems = questions;
	
	//alert('loading ' + questions.length + ' questions');	
	var list = document.getElementById('questions-list');
	var problemsList = document.getElementById('problem-list');
	
	
		  
	 clearList(list);
	
	clearList(problemsList);
	
	
	
	
	for(var n=0; n<currentProblems.length; n++){
		
		//alert(classes[n].childNodes);
		var li = document.createElement('li');
		li.index = n;
		var a = document.createElement('a');
		a.index = n;
		a.innerHTML = getNodeText(currentProblems[n], 'title');
		li.appendChild(a);

		a.onclick = function(){
			
			//alert(document.getElementById('problem-list'));
			selectQuestion(this.index);
		}
		list.appendChild(li);

		var li = document.createElement('li');
		li.index = n;
		var a = document.createElement('a');
		a.index = n;
		a.innerHTML = getNodeText(currentProblems[n], 'title');
		li.appendChild(a);

		a.onclick = function(){
			
			selectQuestion(this.index);
			
		}
		problemsList.appendChild(li);
	}
}



var dataObj = {};


function selectClass(index, id){
	
	//alert('selected class#' + id);
	//alert('selected index#' + index);
	index = 0;
	
	currentModule = id;
	//alert(dataObj['classes'][index]);
	
	// clear questions
	var list = document.getElementById('questions-list');
	clearList(list);
	
	currentCourseTitle = getNodeText(dataObj['classes'][index], 'title')
	currentCoursePath = getNodeText(dataObj['classes'][index], 'path');


	var currentClass = document.getElementById('current-class')
	currentClass.innerHTML = currentCourseTitle;
	

	var filename = dataObj['classes'][index].getElementsByTagName('path')[0].getAttribute('file');
	if(!filename){
		var filename = "/data.xml";	
	} else {
		//alert('cutom file name:' + filename);	
	}
	
	
	var xmlPath = basepath + currentCoursePath + filename +'?id=' + id;
	//alert('loading course: ' + currentCourseTitle + ' data.xml from: ' + xmlPath);
	//notice(xmlPath);
	
	var reqs = new getXMXHTTPRequest();
	reqs.open("GET", xmlPath, true);
	
	reqs.onreadystatechange = function(){
	
		if(reqs.readyState ==4){
			switch(reqs.status){
				case(404):	notice(xmlPath +'<hr/>does not exist');
							//alert(xmlPath +'\ndoes not exist: \n\n' + xmlPath);
				break;
				case(200):	if(explain) alert('simulated loading delay...\n\nYou should see a timed loading pop-up');
							//alert(req.responseText);
							Feedback.loaded();
							Feedback.trace("XML<br /><textarea wrap='off' style='background: black;color: lime;width: 100%;height: 300px;'>" + reqs.responseText + '</textarea>', 'Class Selected id:' + id);
							
							topicsXML = parseDOM(reqs.responseText);
							//loadTopics(topicsXML.getElementsByTagName('topic'));;
							
							//alert(obj.parentNode.getElementsByTagName('input')[0].value);
							dataObj['topics-list'] = topicsXML;
							
							
							
							var callback = {
								onclick: function(obj) { 
									
									var id = obj.parentNode.getElementsByTagName('input')[0].value;
									
									//alert('getting the problems for topic:' + id);
									var cb = function(req){
										
										//alert(req.responseText);
										var problems = parseDOM(req.responseText);
										
										var cb = {
											addHandler: function(obj){
												
												//alert('adding problem to topic' + id);
													
												var name = prompt('name?', '');
												
												if(name!=false){
													
													var cc = function(req){
															
														//loadColumn(problems.getElementsByTagName('problem'), 'questions-list', cb);
														var problems = parseDOM(req.responseText);
														loadColumn(problems.getElementsByTagName('problem'), 'questions-list', cb);
														
														//alert(req.responseText);
														
														//alert('ok, added new item, reload the column' + id);
														//loadColumn(problems.getElementsByTagName('problem'), 'questions-list', cb);
														//selectTopic(id);
													}
													
													apiCall('addQuestion', 'topic=' + id + '&name=' + name, false, cc);	
												}
												//alert('custom add handler');
												
											},
											deleteHandler: function(obj){
												
												alert('custom delete handler');
												
											},
											onclick: function(obj){
												
												selectQuestion(obj.index);
											},
											apiEditCommand: 'editQuestion',
											titleAttribute: { 
												path: "getText(items[n].getElementsByTagName('title')[0])" 
											
											},
											module: 'problems',
											moduleId: id,
											api: {
												'edit': 'editProblem',
												'delete': 'deleteProblem',
												'reload': reloadProblemsXML
											}

										};
										loadColumn(problems.getElementsByTagName('problem'), 'questions-list', cb);
									
									}
									apiCall('loadQuestions', 'topic=' + id, false, cb);
									//var d = dataObj['topics-list'].getElementsByTagName('problem');
									//loadColumn(d, 'questions-list', {});
								},
								titleAttribute: 'title',
								apiEditCommand: 'editTopic',
								module: 'topics',
								moduleId: id,
								api: {
									'edit': 'editTopic',
									'delete': 'deleteTopic',
									'reload': loadTopicsXML
								}

							}
							
							loadColumn(topicsXML.getElementsByTagName('topic'), 'topics-list', callback);
				
				default:
			}
		} else {
			//alert('Problem: XMP HTTPRequest status: ' + req.status);
		}

	}
	reqs.send(null);
	Feedback.loading();
}










function switchTo(panel){
	
	//alert('switcig to:' + panel);	
	
	switch(panel){
		case("problem-view"):	selectQuestion(currentProblemIndex);
		break;
		case("menu-view"):		mainMenu();
		break;
		default:				notice('unknown panel:' + panel);
	}
}

function selectTopic(index){
	
	Feedback.trace(index, 'new topic selected');
	
	

	
	if(index==currentTopicIndex){
		
		//alert('already loaded!');
		return;
	}
	
	
	var callback = function(reqs){
		
		var xml = parseDOM(reqs.responseText);
		
		
		Feedback.trace("XML<br /><textarea wrap='off' style='background: black;color: lime;width: 100%;height: 300px;'>" + reqs.responseText + '</textarea>', 'Topic Selected id:' + index);
		dataObj['topics-list'] = XML;
		var topicsList = document.getElementById('topics-list');
		//loadQuestions(xml.getElementsByTagName('problem'));
	
		loadColumn(xml.getElementsByTagName('problem'), 'questions-list', {onclick: function(){ alert('sd'); } });
	
	}
	apiCall('loadQuestions', 'topic=' + index, false, callback);
	return;
	
	
	//alert(dataObj['topics-list']);
	//alert(dataObj['topics-list'].getElementsByTagName('problem').length + ' problems');
	
	currentTopicIndex = index;
	//alert('chose topic#: ' + index);
	//alert(topicsObj[index]);
	var topicsList = document.getElementById('topics-list');
	loadQuestions(dataObj['topics-list'].getElementsByTagName('problem'));
	
	
	
	
	
	//document.getElementById('current-topic').innerHTML = topicsList.childNodes[index].childNodes[0].innerHTML;
	
	//var rpt = document.getElementById('related-problems-topic');
	//rpt.innerHTML  =dataObj['topics-list'].getAttribute('title');
	
	return true;
}

function changeClass(){
	
	var problemsList = document.getElementById('questions-list');
	var topicsList = document.getElementById('topics-list');
	
	clearList(problemsList);
	clearList(topicsList);
	selectListItem(document.getElementById('class-list'), -1);
	
	mainMenu();
}

function changeTopic(){

	//currentProblemIndex =0;
	//resetScrollPosition();
	

	var problemsList = document.getElementById('questions-list');
	
	currentProblemIndex =0;
	clearList(problemsList);
	//selectListItem(document.getElementById('class-list'), -1);
	
	currentTopicIndex =0;
	selectListItem(document.getElementById('topics-list'), -1);
	mainMenu(true);
}


function nextTopic() {

	Feedback.dismiss();
	//alert('next topic');

	//notice('there are currently ' + topicsObj.length + ' topics');
	
	if(currentTopicIndex+1<topicsObj.length) {
		
		// if we sucessfully select the topic
		if(selectTopic(currentTopicIndex+1)){
			selectQuestion(0);
		}
	} else {
		Feedback.timedNotice('You are on the last topic', 1000);
		//mainMenu();
		
	}
}


function resetMainMenu(){
	
	//clearList(document.getElementById('class-list');
	clearList(document.getElementById('questions-list'));
	clearList(document.getElementById('topics-list'));
	
	selectListItem(document.getElementById('class-list'), -1);
	//selectListItem(document.getElementById('questions-list'), -1);
	//selectListItem(document.getElementById('topics-list'), -1);
}

function mainMenu(resetMenu){
	
	document.getElementById('switchto-menu-button').style.display = 'none';
	document.getElementById('switchto-problem-button').style.display = 'block';
	//if(!resetMenu) resetMainMenu();
	
	var problemView = document.getElementById('problem-view');
	problemView.style.display = 'none';
	
	var mainMenu = document.getElementById('main-menu');
	mainMenu.style.display = 'block';
}




function previousQuestion() {

	//alert('next Question');
	//alert(currentProblems.length + ' ' + currentProblemIndex);
	if((currentProblemIndex-1)<0){
		
		mainMenu();
		//alert('all done!');
	} else {
		
		currentProblemIndex--;
		selectQuestion(currentProblemIndex);
	}
	closeNotice();
}



function nextQuestion() {

	//alert('next Question');
	//alert(currentProblems.length + ' ' + currentProblemIndex);
	if((currentProblemIndex+1)>=dataObj['questions-list'].length){
		
		mainMenu();
		//alert('all done!');
	} else {
		
		currentProblemIndex++;
		selectQuestion(currentProblemIndex);
	}
	closeNotice();
}

var visibleHints = 0;
var totalHints = 0;

function selectQuestion(index){
	
	
	Feedback.trace(index, 'problem selected');
	
	
	if(index>dataObj['questions-list'].length) Feedback.display('no more quesinos');
	var problem = dataObj['questions-list'][index];
	
	
	var msg = "seleced question, <br />adjusting the question listing scroll position <br />Question index =['" + index + ']';
	
	//document.getElementById('switchto-problem-button').style.display = 'block';
	document.getElementById('switchto-menu-button').style.display = 'block';
	document.getElementById('switchto-problem-button').style.display = 'none';
	document.getElementById('problem-tab-block').style.display = 'none';
								
	msg += "<br />The problems pane position: " + document.getElementById('questions-list').parentNode.style.position;
	
	msg += "<br />The problems pane top: " + document.getElementById('questions-list').style.top;
	msg += "<br />height: " + document.getElementById('questions-list').style.height;

	//notice(msg, "blue");

	currentProblemIndex	= index;
	
	selectListItem(document.getElementById('problem-list'), index);
	
	
	
	
	
	var mainMenu = document.getElementById('main-menu');
	mainMenu.style.display = 'none';
	
	var problemView = document.getElementById('problem-view');
	problemView.style.display = 'block';
	
	
	
	updateScrollPosition();
	
	selectListItem(document.getElementById('questions-list'), index);
	

	document.getElementById('problem-text').innerHTML = getNodeText(problem, 'problemText');
	document.getElementById('current-problem').innerHTML = getNodeText(problem, 'title');


	

	totalHints = problem.getAttribute('totalhints');
	visibleHints=1;
	if(visibleHints>totalHints) var limit = totalHints;
	else var limit = visibleHints;

	loadHints(limit);
	
	var relatedConcepts = problem.getElementsByTagName('concept');
	var list = document.getElementById('concept-list');
	
	clearList(list);
	
	for(var x=0; x<relatedConcepts.length; x++){

		var li = document.createElement('li');
		//li.index = conceptsList[relatedConcepts.getAttribute('id')];
		var a = document.createElement('a');
		a.index = relatedConcepts[x].getAttribute('id');
		
		//alert('related to concept: ' + conceptList[relatedConcepts[x].getAttribute('id')].title);
		//alert('id: ' + a.index);
		
		a.alt = relatedConcepts[x].getAttribute('id');
		a.onclick = function(){
			
			//alert(this.alt);
			showConcept(this.alt);
			//showHint( (this.index + 1) );
			//selectListItem(this.parentNode);
			//selectQuestion(this.index);
		}
		
		
		try{
			a.innerHTML = conceptList[relatedConcepts[x].getAttribute('id')].title;
		
			li.appendChild(a);
			list.appendChild(li);
		} catch(e){
			
			//Feedback.display('relatedConcepts[ ' + x + '] does not exist' + relatedConcepts.length);	
		}
	
	}
	
	
	answers =  problem.getElementsByTagName('answer');
	solutions = problem.getElementsByTagName('solution');
	
	
	//alert('we have ' +  answers.length + ' answers');
	var answerObj = document.getElementById('answer-text');
	clearList(answerObj);
	
	for(var x=0; x<answers.length; x++){

		var p = document.createElement('p');
		var type = answers[x].getAttribute('type');
		var label = answers[x].getAttribute('label');
		var instructions = getText(answers[x].getElementsByTagName('instructions')[0]);
		
		
		
		var l = document.createElement('span');

		l.innerHTML = label;
		l.className = 'answer-instructions';
		answerObj.appendChild(l);
		var txt = document.createElement('span');
		
		txt.id = 'answer' + x +'_feedback';
		//txt.className = 'answer-feedback';
		//txt.innerHTML = '<div class="answer-feedback" style="" id="answer' + x +'_feedback"></div>';
		answerObj.appendChild(txt);

		answerObj.appendChild(document.createElement('br'));

		var obj= document.createElement('span');
		//obj.innerHTML = "(" + type + ")| " + instructions +"";
		obj.innerHTML = instructions;
		answerObj.appendChild(obj);
		

		
		var entry = document.createElement('div');
		entry.className = 'answer-entry';
		
		var input = document.createElement('input');
		input.type = 'text';
		input.className = 'input-field';
		input.id = 'response' + x;
		
		entry.appendChild(input);
		
		switch(type){
			case("string"):
			
				//alert('STRING TYPE');
			
			break;
			default:
			case("numeric/formula"):
		
				// what are we working with for units?
				var units = answers[x].getElementsByTagName('unit');
				
				if(units.length==1){
					
					//only add teh label, not a selector	
					var s = document.createElement('span');
					s.innerHTML = units[0].getAttribute('title');
					entry.appendChild(s);
				
				} else {
					
					var s = document.createElement('select');
					s.id = 'response' + x + '_units';
					for(var t=0; t<units.length; t++){
						
						var opt = new Option();
						opt.innerHTML = units[t].getAttribute('title');
						opt.value = units[t].getAttribute('id');
						
						
						s.appendChild(opt);
					}
					entry.appendChild(s);
				}
		} // END TYPE SWITCH
		
		
		var an = document.createElement('div');
		an.className = 'answer-entry-container';
		
		an.appendChild(entry);
		answerObj.appendChild(an);
		
		
		
		
		// if this is the last part of the answer
		if(x+1==answers.length) {
			var butt = document.createElement('div');
			butt.align = 'right';
			butt.style.marginRight= '10px';
			butt.innerHTML = '<div class=""><img onmouseover="this.className=\'over\'" onmouseout="this.className=\'\'" id="ssubmit-answer-button" onclick="checkAnswers();" src="images/submit.jpg" /></div>';
			answerObj.appendChild(butt);
		}
	}
}

var answers = false;
var solutions = false;

function checkAnswers(){
	
	var trace = false;
	// what type of answwer are we looking for ?
	
	if(trace) alert('checking ' + answers.length + ' answers against ' + solutions.length);
	
	var response_correct = true;
	
	for(var n=0; n<answers.length; n++){
		
		var correct = true;
		// what type of response are we looking for ?
		var type = answers[n].getAttribute('type');
		if(trace) alert('answer type: ' + type + '');
		//unitID="1" min="2.0" max="2.1"
		
		var response = document.getElementById('response' +n);
		
		var min_value = solutions[n].getAttribute('min');
		// do we have a max value ?
		var max_value = solutions[n].getAttribute('max');
		if(max_value==null){
			
			var max_value = min_value;
			/*
			//alert('min value=' + min_value + ', there is no max value, response=' + response.value);	
			if(min_value==response.value){
				response.className = 'correct';
			} else {
				response.className = 'incorrect';
				correct = false;
			}
			*/
		} else {
		
			//alert('A range answer');
			//alert('min value=' + min_value + ', max value=' + max_value + ', response=' + response.value);	
		}
		
		switch(type){
			case("string"):
			
				//alert('STRING TYPE');
				//alert(response.value + '' +  min_value);
				if(response.value != min_value) {
					document.getElementById('answer' + n + '_feedback').className = 'incorrect';
					document.getElementById('answer' + n + '_feedback').innerHTML = getText(answers[n].getElementsByTagName('incorrect')[0]);
					correct= false;
				}
			break;
			default:
			case("numeric/formula"):
			
				// do we have units to match ?
				var units = answers[n].getElementsByTagName('unit');
				if(units.length>1){
					
					var correct_units_id = solutions[n].getAttribute('unitID')
					
					if(trace) 	alert('we have units to process');
					
					var un_s = document.getElementById('response' + n + '_units');
					
					if(trace) alert(un_s.options[un_s.selectedIndex].value +'='+ correct_units_id);
					
					if(un_s.options[un_s.selectedIndex].value == correct_units_id){
						//un_s.className = 'correct';
					} else {
						//un_s.className = 'incorrect';
						correct = false;
					}
					// does teh selected value of the units match with the solution value ?
				}
		
				
				if(isScienticNotation(response.value)){
					//alert('response id sci notation');
					
					if(!scientificEval(response.value, min_value, max_value)) {
					var units = answers[n].getElementsByTagName('unit');
						document.getElementById('answer' + n + '_feedback').className = 'incorrect';
						document.getElementById('answer' + n + '_feedback').innerHTML = getText(answers[n].getElementsByTagName('incorrect')[0]);
						correct= false;
				
					}
				} else if(isNumeric(response.value)){
						
					//alert('response is numeric');
					if(!floatEval(response.value, min_value, max_value)) {
						
						document.getElementById('answer' + n + '_feedback').className = 'incorrect';
						document.getElementById('answer' + n + '_feedback').innerHTML = getText(answers[n].getElementsByTagName('incorrect')[0]);
						correct= false;
					}
						
				} else {
					document.getElementById('answer' + n + '_feedback').className = 'incorrect';
					document.getElementById('answer' + n + '_feedback').innerHTML = getText(answers[n].getElementsByTagName('incorrect')[0]);
					correct= false;
					//alert('Response id neither scientific notation or numeric');	
				}
				//alert('isNumeric = ' + isNumeric(response.value));
				//alert('isScienticNotation = ' + isScienticNotation(response.value));
				//if(response.value>10) correct = false;
				
				
		}	// END SWITCH TYPE
		
		
		if(correct){
			document.getElementById('answer' + n + '_feedback').className = 'correct';
			document.getElementById('answer' + n + '_feedback').innerHTML = getText(answers[n].getElementsByTagName('correct')[0]);
					
			//response.className = 'correct';
		
		} else {
			
			//response.className = 'incorrect';
		}
		if(response_correct) response_correct = correct;

	} // END ITERATE RESPONSES / ANSWERS
	
	if(response_correct) correctAnswer();
	else incorrectAnswer();
}


function floatEval(val, mi, mx){
	
	//alert(val +','+ mi +','+ mx );
	
	if(!isNumeric(val) || !isNumeric(mi) || !isNumeric(mx) ){
		
		if(!isNumeric(val)){
			//alert('val not numeric');
			val = makeSciNumerical(val);	
		}
		if(!isNumeric(mi)){
			//alert('min not numeric');
			mi = makeSciNumerical(mi);	
		}
		if(!isNumeric(mx)){
			//alert('max not numeric');
			mx = makeSciNumerical(mx);	
		}
		//alert('one of the arguments to the float evaluator is not numerical');	
		
	} else {
		//alert('all good');	
	}
	
	//alert(eval(val) +','+ eval(mi) +','+ eval(mx) );
	
	if( eval(val)>=eval(mi) && eval(val)<=eval(mx) ){
		
		return true;
	} else {
		
		return false;	
	}
	
}


function makeSciNumerical(value){
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+[e](?:[-+]?[0-9]+)?$/;
	var result = value.match(RegExp);
	if(result){
		var let = 'e';
	} else {
		var let = 'E';
	}
	
	var nums = value.split(let);
	//alert(parseFloat(nums[0]) * Math.pow(10, nums[1]));
	return (parseFloat(nums[0]) * Math.pow(10, nums[1]));
}

function makeSciNotataion(value, base, precision){

	if(!base) base = 10;
	if(!precision) precision = 3;
	
	//var new_val = value / (base*precision);

	var c_val = value;
	var p = 1;
	while( c_val<1) {
		
		c_val = c_val*10;
		p++;
	}
	return c_val + 'E' + p;
	//alert(c_val + 'E' + p);
	//alert('turning ' + value  + ' into sci notation precision:' + precision + ' = ' + new_val);
}

function scientificEval(val, mi, mx){
	
	
	
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+[e](?:[-+]?[0-9]+)?$/;
	var result = val.match(RegExp);
	if(result){
		var let = 'e';
	} else {
		var let = 'E';
	}
	
	
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+[e](?:[-+]?[0-9]+)?$/;
	var result = mi.match(RegExp);
	if(result){
		var let_mi = 'e';
	} else {
		var let_mi = 'E';
	}
	
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+[e](?:[-+]?[0-9]+)?$/;
	var result = mx.match(RegExp);
	if(result){
		var let_mx = 'e';
	} else {
		var let_mx = 'E';
	}
	
	
	if(!isScienticNotation(val) || !isScienticNotation(mi) || !isScienticNotation(mx) ){
		
		//alert('one of the arguments to the scientific notation evaluator is not in scientific notation format');	
		
		if(!isScienticNotation(val)){
			
			val = makeSciNotataion(val);	
		}
		if(!isScienticNotation(mi)){
			
			mi = makeSciNotataion(mi);	
		}
		if(!isScienticNotation(mx)){
			
			mx = makeSciNotataion(mx);	
		}
	}
	
	var nums = val.split(let);
	var mi_nums = mi.split(let_mi);
	var mx_nums = mx.split(let_mx);
	
	//alert('base:' + nums[0] +', minbase=' + mi_nums[0] +', maxbase=' + mx_nums[0] +'=' + (nums[0]>=mi_nums[0] && nums[0]<=mx_nums[0]) );
	//alert(:' + nums[1] +', minbase=' + mi_nums[1] +', maxbase=' + mx_nums[1] +'=' + (nums[1]>=mi_nums[1] && nums[1]<=mx_nums[1]) );
	
	if( (nums[0]>=mi_nums[0] && nums[0]<=mx_nums[0]) && (nums[1]>=mi_nums[1] && nums[1]<=mx_nums[1]) ){
		
		return true;
	} else {
		
		return false;	
	}
}

function checkAnswer(){
	
	
	
}

function isScienticNotation(x){
	
	var RegExp = /^[-+]?[0-9]*\.?[0-9]+[Ee](?:[-+]?[0-9]+)?$/; // Note: this WILL allow a number that ends in a decimal: -452.
	// compare the argument to the RegEx
	// the 'match' function returns 0 if the value didn't match
	var result = x.match(RegExp);

	//new
	if (result==null) result=false;
	else result = true;
	
	return result;
	
}

function isNumeric(x) {
	
	// I use this function like this: if (isNumeric(myVar)) { }
	// regular expression that validates a value is numeric
	var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
	// compare the argument to the RegEx
	// the 'match' function returns 0 if the value didn't match
	var result = x.match(RegExp);

	//new
	if (result==null) result=false;
	else result = true;
	
	return result;
}







function updateScrollPosition(){
	try{
		var list = document.getElementById('questions-list');
		var move = list.firstChild.offsetHeight * (currentProblemIndex);
		var current = list.parentNode.parentNode.scrollTop;
		//alert('moving from: ' + list.parentNode.parentNode.scrollTop + ' to: ' + move);
		list.parentNode.parentNode.scrollTop = move;
	
		var list = document.getElementById('problem-list');
		var move = list.firstChild.offsetHeight * (currentProblemIndex);
		var current = list.parentNode.scrollTop;
		//alert('moving problem-list from: ' + list.parentNode.scrollTop + ' to: ' + move);
		list.parentNode.scrollTop = move;
	} catch(error){
		
		//notice('Error in updateScrollPosition()', 'red');	
	}

}

function resetScrollPosition(){
	
	alert('resetting the questions scroll p[ositions');
	
	var list = document.getElementById('questions-list');
	var move = 0;
	list.parentNode.parentNode.scrollTop = move;


	var list = document.getElementById('problem-list');
	alert(list.parentNode.scrollTop);
	
	list.parentNode.scrollTop = 0;
	alert(list.parentNode.scrollTop);

}




function inApplication(){
	var thisPage = getPageFile();
	for(var n=0; n<=applicationPages.length; n++){
		if(thisPage==applicationPages[n]) return true;
	}	

}
function getPageFile(){
	
	var url = String(window.location);
	var chunks = url.split('/');
	return chunks[chunks.length-1];
	
}

function isExitingApplication(url){
	
	return false;
}






function quit(){
	Feedback.darkenScreen();
	//notice('<div style="padding-top: 70px;margin: auto;text-align: bottom;"><h3>Are you sure you want to quit?</h3><div class=buttons> <input class="button" type="button" onclick="finalize();" value="YES EXIT" /><input class="button" type=button onclick="closeNotice();" value="CANCEL" /></div>');
	/*
	
	confirmExit = false;
	//window.onbeforeunload = false;
	window.opener.application = false;
	
	window.opener.focus();
	window.close();
	*/
}

function finalize(){
	
	window.onbeforeunload = null;
	confirmExit = false;
	
	//window.opener.application = false;
	
	try {
		window.opener.focus();
	} catch(e){
		
	}
	window.close();
}







function dialog(text, title, options){
	Feedback.dialog(text, title, options);
}

function notice(msg, title, color, opacity){
		Feedback.display(msg, title, color, opacity);

}

function closeNotice(){
	Feedback.dismiss();
}

function killNotice(){
	
	alert('killNotice() -- depreciated');
	document.getElementById('notice').style.top = 0;
	document.getElementById('notice').style.left = 0;
	document.getElementById('notice').style.zIndex = -900;
	//document.getElementById('notice').style = null;
}

function navigate(url){
	
	alert('navigating to: ' + url);
	if(!isExitingApplication(url)){
		alert('not exiting application');
		window.location = url;
	} else {
		alert('is exiting application');	
	}
}























function correctAnswer(){
	
	
	var correctText = '';
	
	var feedback = currentProblems[currentProblemIndex].getElementsByTagName('correct');
	for(n=0; n<feedback.length; n++){
			
			
			
			correctText = '<p>' + getText(feedback[n]) + '</p>';
	}
	
	var nextText = 
	
	'<div style="padding-top: 70px;margin: auto;text-align: bottom;">'
	+ correctText + 
	'<div class=buttons> <input class="button" type=button onclick="closeNotice();" value="Close" /> <input  id="focused" class="button" type=button onclick="nextQuestion();" value="Go to Next Problem &gt;" /></div>';

	var doneText = '<div style="padding-top: 70px;margin: auto;text-align: bottom;"><h3>Completed this Topic. <br />Continue to next ?</h3><div class=buttons> <input class="button" type=button onclick="closeNotice();" value="CLOSE" /><input class="button" type=button onclick="mainMenu();closeNotice();" value="MENU" /> <input id="focused" class="button" type=button onclick="nextTopic();"" value="NEXT TOPIC" /></div>';
	
	
	
	
	if((currentProblemIndex+1)>=currentProblems.length){
		
		notice(doneText, 'Correct Answer', '#003300');
		document.getElementById('focused').focus();
		
	} else {
		
		notice(nextText, 'Correct Answer', '#003300');
		document.getElementById('focused').focus();
	}
}

function incorrectAnswer(){
	//var text = '';
	//notice(text, 'Inorrect Answer', '#330000');
}





function stopVideo(){
	
	alert('stopping video');	
}
function __showHint(index){
	
	
	// IF THE VIDEO PLAYER LAYER DOES NOT EXIST... CREATE IT.
	if(!document.getElementById('video-player')){
				
		/*var vpt = document.createElement('div');
		vpt.id="video-player-title" ;
		
		vpt.style.zIndex = 600;
		
		var vc = document.createElement('a');
		vc.className="close-button"
		vc.onclick = function(){
			
			Feedback.dismiss();
		};
		vpt.appendChild(vc);
		
		var vt = document.createElement('span');
		vt.id="video-title";
		vt.className = "title";
		vpt.appendChild(vt);
		*/
		var vp = document.createElement('div');
		vp.id = "video-player";
		
		//document.getElementById('problem-view').appendChild(vpt);
		document.getElementById('problem-view').appendChild(vp);
	}

	var file = '../../FLVs/t' + topicsObj[currentTopicIndex].getAttribute('id')+ 'p' 
					+currentProblems[currentProblemIndex].getAttribute('id')+ 'h' +index+ '.flv';
	var FO = {	
		movie:"js/flv_player/flvplayer.swf",
		width:"640",height:"500",majorversion:"7",
		build:"0",bgcolor:"#FFFFFF",
		flashvars:"file=" + file + "&showdigits=true&autostart=true&showfsbutton=false"
	};
	UFO.create(	FO, "video-player");

	Feedback.videoPlaying = true;
	Feedback.darkenScreen(60);
	
	//document.getElementById('video-player').style.zIndex = 900;
	//document.getElementById('video-player-title').style.zIndex = 901;
	
	
	document.getElementById('noticer-title').innerHTML = "Video Hint#" + index;
	document.getElementById('noticer-text').style.display = 'block';
	
	

	
	Feedback.onclose = function(){
		
		document.getElementById('noticer-text').style.display = 'none';
	
		if(visibleHints<=totalHints) visibleHints++;
		loadHints();
	}
}

function relaunch(){
	
	
	//alert('relaunch.');
	setTimeout("launch()", 500);
	
	
}

function reboot(){
	
	confirmExit=false;	
	window.opener.location = window.opener.location;
	window.opener.relaunch();
	window.opener.setTimeout("launch()", 200);
	window.close();
}
function hideSelects(){
	
	var sel = document.getElementsByTagName('select');
	for(var x=0; x<sel.length; x++){
		
		sel[x].style.display = 'none';	
	}
}
function unHideSelects(){
	
	var sel = document.getElementsByTagName('select');
	for(var x=0; x<sel.length; x++){
		
		sel[x].style.display = 'inline';	
	}
}


function showHint(index){
	
	

	/*
	var file = '../../FLVs/t' + topicsObj[currentTopicIndex].getAttribute('id')+ 'p' 
					+currentProblems[currentProblemIndex].getAttribute('id')+ 'h' +index+ '.flv';
	*/
	
	var file = '../../js/flv_player/video.flv';
	var FO = {	
		movie:"js/flv_player/flvplayer.swf",
		width:"100%",height:"100%",majorversion:"7",
		build:"0",bgcolor:"#FFFFFF",
		flashvars:"file=" + file + "&showdigits=true&autostart=true&showfsbutton=false"
	};
	
	
	
	YAHOO.example.container.videoDialog.setHeader("Video Hint#" + index);
	//YAHOO.example.container.videoDialog.setBody("<div id='video-player'>ssss</div>");
	
	var beforeHide = function(type, args){
		
		
		//alert('before hide');	
		document.getElementById('video-player').innnerHTML = '';
		
		document.getElementById('video-player').style.display = 'none';
		
		loadHints();
	
	}
	
	var show = function(){
		
			
	}
	
	//alert(YAHOO.example.container.videoDialog.showEvent);
	
	
	YAHOO.example.container.videoDialog.showEvent.subscribe(show);
	YAHOO.example.container.videoDialog.beforeHideEvent.subscribe(beforeHide);


var render = function(){
	
	console.log('sdfsdf');	
}

	YAHOO.example.container.videoDialog.renderEvent.subscribe(render);

	
	YAHOO.example.container.videoDialog.show();
	document.getElementById('video-player').style.display = 'block';
		
	var show = function(){
		UFO.create(	FO, "video-player");
	}
	setTimeout(show, 500);
	//Feedback.videoPlaying = true;
	//Feedback.darkenScreen(60);
	
	
	

		
	/*
	Feedback.onclose = function(){
		
		document.getElementById('noticer-text').style.display = 'none';
	
		if(visibleHints<=totalHints) visibleHints++;
		loadHints();
	}
	*/
}


function showConcept(index){
	
	var s = {};
	s.position = 'absolute';
	s.top = '118px';
	s.left = '200px';
	s.width = '410px';
	
	//alert('shoeing concept: ' + index);
	//var obj = document.getElementById('concept-list').getElementsByTagName('li')[(index-1)];
	
	
	var concepts = document.getElementById('concept-list').getElementsByTagName('li');
	//alert(concepts);
	
	for(var n=0; n<concepts.length; n++){
		
		if(concepts[n].firstChild.alt==index){
			
			var obj = concepts[n];
			break;
		}
	}
	//return;
	
	YAHOO.example.container.conceptDialog.setHeader(conceptList[index].title);
	YAHOO.example.container.conceptDialog.setBody(conceptList[index].text);
	YAHOO.example.container.conceptDialog.show();
	
	/*
	
	
	obj.className = 'active';
	hideSelects();
	Feedback.customDisplay('<div class="concept-body">' + conceptList[index].text + '</div>', conceptList[index].title, 'black', 1, s);
	
	Feedback.onclose = function(){
		
		obj.className = '';
		unHideSelects();
	};
	
	*/
	
}





