/**
 * Javascript library code
 *
 * Licenced for use with solagen-sentient
 * Changes to this file are unsupported
 *
 * @author Ian Guerit <ian@appee.com>
 * @version 1.0
 * @package appee-library
 * @copyright appee 2006
 */

function debug(type, component, message)
{
	var err = document.createElement('div');

	var err_typ = document.createElement('div');
	var err_com = document.createElement('div');
	var err_msg = document.createElement('div');

	err.setAttribute('class', 'debug');
	err_typ.setAttribute('class', 'type');
	err_com.setAttribute('class', 'component');
	err_msg.setAttribute('class', 'message');

	err_typ.innerHTML = type;
	err_com.innerHTML = component;
	err_msg.innerHTML = message;

	err.appendChild(err_typ);
	err.appendChild(err_com);
	err.appendChild(err_msg);

	document.getElementById('debug').appendChild(err);
}

function createElement(type, classname)
{
	var tmp = document.createElement(type);
	tmp.setAttribute('className',classname);
	tmp.setAttribute('class',classname);
	return tmp;
}

function formatDate(date)
{
	var months = new Array('', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	var ord = new Array('th','st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th');
	var datearray = date.split('-');

	for(number in datearray)
	{
		if(datearray[number].substr(0,1)==0)
		{
			datearray[number] = datearray[number].substr(1,1);
		}
	}
	var date = datearray[2];
	var month = datearray[1];
	var year = datearray[0];

	// Special cases that don't follow the regular pattern
	if (date == 11 || date == 12 || date == 13)
	{
		return date+'th '+months[month]+' '+year;
	}
	else
	{
		return date+ord[date.substring(date.length-1)]+' '+months[month]+' '+year;
	}
}

function formatDateWithDay (date)
{
	var days = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
	var dateString = formatDate (date);
	var tmpDate = new Date ();
	var datearray = date.split('-');
	
	tmpDate.setFullYear (datearray[0]);
	tmpDate.setMonth (datearray[1] - 1);
	tmpDate.setDate (datearray[2]);

	return days[tmpDate.getDay ()]+' '+dateString;
}

/**
 * Browser object
 *  - allows us to determin the current browser
 */
function Browser() {
	var ua, s, i;
	this.isIE    = false;
	this.isNS    = false;
	this.version = null;
	ua = navigator.userAgent;
	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	s = "Gecko"; // Treat any other "Gecko" browser as NS 6.1.
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = 6.1;
		return;
	}
}
/**
 * XMLHTTP Request object
 *  - returns a XMLHTTP request object
 * @component AJAX
 */
function RequestObject()
{
	if(browser.isIE)
		return new ActiveXObject("Microsoft.XMLHTTP");
	else
		return new XMLHttpRequest();
}
/**
 * HTTP Request processor
 * - processes requests
 * @component AJAX
 */
function RequestProcessor()
{
	this.queue = new Array();
	this.position = 0;
	this.busy = false;
	this.add = function(request)
	{
		this.queue[this.queue.length] = request;
		this.process();
		return this.queue.length-1;
	}
	this.abort = function(ticket)
	{
		if(this.position == ticket)
			http.abort();
		this.queue[ticket].abort = true;
	}
	this.process = function()
	{
		if(this.busy||http.readyState!=0&&http.readyState!=4)
		{
			if(this.queue[this.position+1])
			{
				setTimeout("requestProcess.process();",50);
			}
			return;
		}
		this.busy = true;
		if(!this.queue[this.position])
		{
			alert('Lost place in queue ('+this.position+')');
			this.position--;
		}
		var current = this.queue[this.position];
		this.position++;
		if(current.abort)
		{
			if(this.position < this.queue.length)
				this.process();
			return;
		}
		http.open(current.method, current.address);
		http.onreadystatechange = function()
		{
			try{}
			catch(e)
			{
				alert(e);
			}
			
			current.onStateChange();
			requestProcess.busy = false;
			if(requestProcess.position < requestProcess.queue.length)
				requestProcess.process();
		}
		http.send(current.data);
	}
}
/**
 * Request object
 * - holds all information for a request
 * @component AJAX
 */
function Request(method, address, data, onStateChange)
{
	this.method = method;
	this.address = address;
	this.data = data;
	this.onStateChange = onStateChange;
	this.abort = false;
}
/**
 * JSON encoder
 */
function toJSONString(x)
{
  return s.object(x);
};

var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        }
var s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

/**
 * Select box
 */
function SelectBox(label, options, selected, onupdate)
{
	this.root;
	this.select;
	this.options = options;
	this.value = selected;
	this.optionlist = new Array();
	this.label = label;
	this.onupdate = onupdate;

	this.draw = function()
	{
		this.root = createElement('div', 'selectinput');

		var label = createElement('label', 'selectlabel');
		label.innerHTML = this.label;
		this.root.appendChild(label);

		this.select = createElement('select', 'selectbox');
		var tmp = this;
		this.select.onchange = function()
		{
			tmp.update();
		}
		for(option in this.options)
		{
			var ele = createElement('option', 'selectoption');
			ele.setAttribute('value',this.options[option]);
			if(option == this.value)
			{
				ele.setAttribute('selected', 'selected');
			}
			ele.innerHTML = option;
			this.optionlist.push(ele);
			this.select.appendChild(ele);
		}
		this.root.appendChild(this.select);

		return this.root;
	}

	this.update = function()
	{
		this.value = this.select.value;
		this.onupdate();
	}
	
	this.setValue = function(value)
	{
		for(option in this.optionlist)
		{
			if(this.optionlist[option].value == value)
			{
				this.optionlist[option].selected = true;
			}
			else
			{
				this.optionlist[option].selected = false;
			}
		}
		this.update();
		this.onupdate();
	}
}
/**
 * Option buttons
 */

function ToggleButtons(title, options, selected, onupdate)
{
	this.root;
	this.onupdate = onupdate;
	this.options = options;
	this.buttons;
	this.selected = selected;
	this.title = title;

	this.draw = function()
	{
		this.root = createElement('div', 'toggleButtons');

		var title = createElement('div', 'title');
		title.innerHTML = this.title;
		this.root.appendChild(title);

		this.buttons = new Array();
		var tmp = this;
		for(option in this.options)
		{
			if(option == this.selected)
			{
				this.buttons[option] = createElement('a', 'toggleSelected');
			}
			else
			{
				this.buttons[option] = createElement('a', 'toggle');
			}
			this.buttons[option].onclick = function()
			{
				tmp.select(this.innerHTML); // messy!
			}
			this.buttons[option].innerHTML = option;
			this.root.appendChild(this.buttons[option]);
		}

		return this.root;
	}

	this.update = function()
	{
		this.onupdate();
	}
	this.select = function(selected)
	{
		for(option in this.options)
		{
			this.buttons[option].className='toggle';
			this.buttons[option].setAttribute('class','toggle');
		}
		this.buttons[selected].className='toggleSelected';
		this.buttons[selected].setAttribute('class','toggleSelected');
		this.selected = selected;
		this.update();
	}
}
function Button(label, style, onclick, state)
{
	this.enabled = state;
	this.onclick  = onclick;
	this.label = label;
	this.style = style;
	this.root;

	this.draw = function()
	{
		if(this.enabled)
		{
			var state = '';
		}
		else
		{
			var state = '_disabled';
		}
		this.root = createElement('div', this.style);
		var button = createElement('a', 'button');
		button.onclick = this.onclick;
		if(this.label=='Delete')
		{
			this.root.style.textAlign='center';
			button.style.backgroundImage='url(media/delete.gif)';
			button.style.display='block';
			button.style.width = '84px';
			button.style.height= '20px';
			button.style.padding='0px';
		}
		else if(this.label=='Save to desktop')
		{
			button.style.backgroundImage='url(media/savetopc.gif)';
			button.style.display='block';
			button.style.width = '84px';
			button.style.height= '20px';
			button.style.padding='0px';
		}
		else if(this.label=='Save as default')
		{
			button.style.backgroundImage='url(media/saveasdefault.gif)';
			button.style.display='block';
			button.style.width = '121px';
			button.style.height= '20px';
			button.style.padding='0px';
		}
		else
		{
			button.innerHTML = this.label;
		}
		this.root.appendChild(button);
		return this.root;
	}
}

function FancyButton(label, style, onclick, width, height)
{
	this.onclick  = onclick;
	this.label = label;
	this.style = style;
	this.root;
	this.height = height;
	this.width = width;

	this.draw = function()
	{
		this.root = createElement('img', 'fancybutton');
		this.root.setAttribute('src', 'media/'+style+'.gif');
		this.root.setAttribute('alt', this.label);
		this.root.setAttribute('width', this.width);
		this.root.setAttribute('height', this.height);
		return this.root;
	}
	this.enable = function()
	{
		style = this.style;
		this.root.onmouseover = function()
		{
			this.src = 'media/'+style+'_hover.gif';
		}
		this.root.onmouseout = function()
		{
			this.src = 'media/'+style+'.gif';
		}
		this.root.onmousedown = function()
		{
			this.src = 'media/'+style+'_down.gif';
		}
		this.root.onmouseup = function()
		{
			this.src = 'media/'+style+'.gif';
		}
		this.root.onclick = this.onclick;
		this.root.src = 'media/'+style+'.gif';
	}
	this.disable = function()
	{
		this.root.onclick = new Function();
		this.root.onmouseover = new Function();
		this.root.onmouseout = new Function();
		this.root.onmousedown = new Function();
		this.root.onmouseup = new Function();
		this.root.src = 'media/'+style+'_disabled.gif';
	}
}

/* Fix IE's problem with animated gifs (they stop after calling a js function!)*/
function fixforIE()
{
	if(status)
	{
		status.update();
	}
}

function calcDuration(str_start, str_end, type)
{
	// ensure that we're comparing on fair terms (could cause weird errors otherwise)
	var dt_start = new Date("1/1/70 "+str_start);
	var dt_end = new Date("1/1/70 "+str_end);

	// get number of milliseconds
	var ms_start = dt_start.getTime();
	var ms_end = dt_end.getTime();
	
	switch(type)
	{
		case 'minutes':
		{
			return (ms_end-ms_start)/60000;
		}
	}
}

function dateToMonth(date)
{
	return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
}