//Various javascript functions for interacting with CSS and html


//Set readonly value on textbox field, expects id name
//
// the readonly background color can be changed via csslike...
// 	<style type="text/css">
// 		input[readonly] {background:orange;}
// 	</style>
//
function input_readonly_off(id) {
	document.getElementById(id).readOnly = false;
}

function input_readonly_on(id) {
	document.getElementById(id).readOnly = true;
}

function input_toggle_readonly(id) {
	var obj = document.getElementById(id);
	if(obj.readOnly == true)
		obj.readOnly = false;
	else
		obj.readOnly = true;
}


//-----


//Change text via innerHTML (allows updating of status message. etc
//
// for example, the given html text block can be changed...
//  <div id="statusmessage">
//		My Status message goes here
//  </div>
// then somewhere later, a javascript function changes it like..
//	onClick="change_text('statusmessage', 'New message');"
//
function change_text(id, newtext) {
	var element = document.getElementById(id);
	if(element != null) {
		element.innerHTML = newtext;
	}
}

//----


/*
* This function will not return until (at least)
* the specified number of milliseconds have passed.
* It does a busy-wait loop.
*/
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//----


//change image source
//
// expects id of img to be changed and the new image object
//
function change_image_source(id, newimgobj) {
	var element = document.getElementById(id);
	if(element != null) {
		element.src = newimgobj.src;
	}
}

//-----------

// trims strings
// 	from http://www.somacon.com/p355.php
//
// returns the trimmed string
//
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

//change onclick property of element
//
// expects id of element to change onlick
//
function change_onclick(id, newonclick) {
	var element = document.getElementById(id);
	if(element != null) {
		element.onclick = function(){eval(newonclick)};
	}
}


//---------------------


// focus_on(id)
//
// focus the window on this element
//
function focus_on(id) {
	var element = document.getElementById(id);
	//if(element != null) {
		element.focus();
	//}
	//eval("window." + id + ".focus()");
}



//---------

// DisplayElements(idtosee)
//
// dumps to 'debug' div tag all the sub elements of this element id
//
function DisplayElements(idtosee)
{
	var str = '';
	var elem = document.getElementById(idtosee).elements;
	for(var i = 0; i < elem.length; i++)
	{
		str += "<b>Type:</b>" + elem[i].type + "&nbsp&nbsp";
		str += "<b>Name:</b>" + elem[i].name + "&nbsp;&nbsp;";
		str += "<b>Value:</b><i>" + elem[i].value + "</i>&nbsp;&nbsp;";
		str += "<BR>";
	}
	document.getElementById('debug').innerHTML = str;
}


// DisplayChildNodes(idtosee)
//
// dumps to 'debug' div tag all the child nodes of this element id
//

function DisplayChildNodes(idtosee)
{
	alert('Does this element have child nodes? ' + document.getElementById(idtosee).hasChildNodes());
	var str = '';
	var elem = document.getElementById(idtosee).childNodes;
	for(var i = 0; i < elem.length; i++)
	{
		str += "<b>nodeName:</b>" + elem[i].nodeName + "&nbsp&nbsp";
		str += "<b>nodeType:</b>" + elem[i].nodeType + "&nbsp;&nbsp;";
		str += "<b>nodeValue:</b><i>" + elem[i].nodeValue + "</i>&nbsp;&nbsp;";
		str += "<BR>";
	}
	document.getElementById('debug').innerHTML = str;
}


//-------------


// ajaxFunction_loadpage(id, url)
// fetches given url and returns into element indentified by id
//
function ajaxFunction_loadpage(id, url){
	var ajaxRequest;  // The variable that makes Ajax possible!
 	var contentType = "application/x-www-form-urlencoded; charset=UTF-8";

	if(global_ajaxRequestType == 1) { 	
		ajaxRequest = new XMLHttpRequest();
	}
	else if(global_ajaxRequestType == 2){
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}
	else if(global_ajaxRequestType == 3) {
		ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else {
		alert("Your browser broke!");
		return false;
	}

	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		//readyState == 4 means complete
		if(ajaxRequest.readyState == 4){
			//return status
			var returnedhtml = trim(ajaxRequest.responseText);
			//split into two pieces if neccessary
			//alert("loading html");
			change_text(id, returnedhtml);
		}
		//else {
		//	//failure
		//	change_text('ajaxMessage_' + itemid, 'Unable to change, please try again. ');
		//}
		
	}
	
	//objImage = new Image();
	//objImage.src = "/ajax/ajax-loader.gif";
	//change_image_source(id, objImage);	
	ajaxRequest.open("GET", url, true);
	//ajaxRequest.setRequestHeader("Content-Type", contentType);
	
	//var postvalue = '';
	//alert(postvalue);
	//ajaxRequest.send(postvalue);
	ajaxRequest.send(null);
	
}

// ajaxFunction_loadpage_via_post(id, url)
// fetches given url and returns into element indentified by id (but uses post method) 
//
function ajaxFunction_loadpage_via_post(id, url){
	var ajaxRequest;  // The variable that makes Ajax possible!
 	var contentType = "application/x-www-form-urlencoded; charset=UTF-8";

	if(global_ajaxRequestType == 1) { 	
		ajaxRequest = new XMLHttpRequest();
	}
	else if(global_ajaxRequestType == 2){
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}
	else if(global_ajaxRequestType == 3) {
		ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else {
		alert("Your browser broke!");
		return false;
	}

	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		//readyState == 4 means complete
		if(ajaxRequest.readyState == 4){
			//return status
			var returnedhtml = trim(ajaxRequest.responseText);
			//split into two pieces if neccessary
			//alert("loading html");
			change_text(id, returnedhtml);
		}
		//else {
		//	//failure
		//	change_text('ajaxMessage_' + itemid, 'Unable to change, please try again. ');
		//}
		
	}
	
	//objImage = new Image();
	//objImage.src = "/ajax/ajax-loader.gif";
	//change_image_source(id, objImage);	
	
	//breakout the url
	var query = url.substring(url.indexOf('?')+1,url.length);
	var url_without_query = url.replace('?' + query, '');
	
	//console.log('query: ' + query);
	//console.log('url sans: ' + url_without_query);
	
	ajaxRequest.open("POST", url_without_query, true);
	ajaxRequest.setRequestHeader("Content-Type", contentType);
	
	ajaxRequest.send(query);
	//ajaxRequest.send(null);
	
}


//----



//---------------- Scheduler -----------------------
//
// From http://www.kevlindev.com/gui/utilities/scheduler/index.htm
//

/*****
*
*	Scheduler.js
*	copyright 2000, 2001, Kevin Lindsey
*
*****/

/*****
*
*	Globals and Constants
*
*****/
var scheduler = new Scheduler();
Scheduler.INTERVAL = 1000;


/*****
*
*	Scheduler constructor
*
*****/
function Scheduler() {
	this.timeoutID = null;
    this.running   = 0;
	this.tasks     = new Array();
}


/*****
*
*	process
*
*****/
Scheduler.process = function() {
	for (var i = 0; i < scheduler.tasks.length; i++) {
		scheduler.tasks[i].decrement();
	}

    if ( scheduler.running ) {
        scheduler.timeoutID = window.setTimeout("Scheduler.process()", Scheduler.INTERVAL);
    }
};


/*****
*
*	add_task
*
*****/
Scheduler.prototype.add_task = function(task, tick_count) {
	this.tasks[this.tasks.length] = new Task(task, tick_count);
};


/*****
*
*	delete_task
*
*****/
Scheduler.prototype.delete_task = function(task) {
	var last = this.tasks.length - 1;

	for (var i = 0; i <= last; i++) {
		if (this.tasks[i].task == task) {
			for (var j = i; j < last; j++) {
				this.tasks[j] = this.tasks[j+1];
			}
			this.tasks.length = last;
			break;
		}
	}
};


/*****
*
*	start
*
*****/
Scheduler.prototype.start = function() {
	if (this.timeoutID == null) {
		this.last_time = new Date();
        this.running   = true;
		this.timeoutID = window.setTimeout("Scheduler.process()", Scheduler.INTERVAL);
	}
};


/*****
*
*	stop
*
*****/
Scheduler.prototype.stop = function() {
	if (this.timeoutID != null) {
		this.timeoutID = null;
        this.running   = false;
		window.clearTimeout(this.timeoutID);
	}
};


/*****
*
*	pause_resume
*
*****/
Scheduler.prototype.pause_resume = function() {
	if (this.timeoutID) {
		this.stop();
	} else {
		this.start();
	}
};


/*****	Task Class	*****/

/*****
*
*	Task
*
*****/
function Task(task, tick_count) {
	this.task         = task;
	this.tick_count   = tick_count;
	this.current_tick = tick_count;
}


/*****
*
*	decrement
*
*****/
Task.prototype.decrement = function() {
	this.current_tick--;
	if (this.current_tick <= 0) {
		this.task();
		this.current_tick = this.tick_count;
	}
};

//---------------------------

//2008-05-04 Bozeman - frame functions

	function get_most_top_window() {
		me = self;
		while(me != me.top) {
			me = me.top;
		}
		return me;
	}

	function frame_fetch_object(nameofframe) {
		//go through all the top frames until we find the correct
		// one, then return the frame object

		//1. get number of frames in the top window
		numofframes = get_most_top_window().frames.length;

		frametoreturn = null;
		for(i = 0; i < numofframes; i = i+1) {
			if(get_most_top_window().frames[i].name == nameofframe) {
				frametoreturn = get_most_top_window().frames[i];
			}
		}

		return frametoreturn;

	}

	function frame_reload(nameofframe) {
		frametoreload = frame_fetch_object(nameofframe);
		if(frametoreload != null) {
			frametoreload.location.reload(true);
		}
	}

	function frame_href(nameofframe, newhref) {
		frametochange = frame_fetch_object(nameofframe);
		if(frametochange != null) {
			//console.log('Changing frame ' + nameofframe + ' to ' + newhref);
			frametochange.location.href = newhref;
		}
		else {
			console.log('Unable to fetch frame ' + nameofframe);
		}
		return false;
	}


	function frame_list() {
		//go through all the top frames and print names to console

		numofframes = get_most_top_window().frames.length;
		console.log('The number of frames in the top window is ' + numofframes);

		for(i = 0; i < numofframes; i = i+1) {
			console.log('Frame ' + i + ': ' + get_most_top_window().frames[i].name);
		}

	}
//---------