//////////////////////////////////////////////////////////////////////////////////////////////
//
// Execute
//
//////////////////////////////////////////////////////////////////////////////////////////////

/*************************************************************
** ONLOAD SCRIPT - adapted from the window.onload script
**    written by Dean Edwards - http://dean.edwards.name
**************************************************************/
function init()
{
	if (arguments.callee.done) return;
	arguments.callee.done = true;
	if(document.onload)
	{
		if(typeof(document.onload) == 'object')
		{
			for(var i in document.onload)
			{
				if(typeof(document.onload[i]) == 'function')
				{
					document.onload[i]();
				}
			}
		}
		else if(document.onload && typeof(document.onload[i]) == 'function')
		{
			document.onload();
		}
	}
}

/* for Mozilla */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        init(); // call the onload handler
    }
};
/*@end @*/


/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) {  // sniff
  var _timer = setInterval(function() {
      if (/loaded|complete/.test(document.readyState)) {
          clearInterval(_timer);
          init();  // call the onload handler
      }
  }, 10);
}

/* for other browsers */
window.onload = init;
/************************************************************
** END ONLOAD SCRIPT
*************************************************************/


//////////////////////////////////////////////////////////////////////////////////////////////
//
// Debug
//
//////////////////////////////////////////////////////////////////////////////////////////////

function getProperties(obj, html)
{
	var space = html ? '&nbsp;&nbsp;&nbsp;&nbsp;' : '    ';
	var nl = html ? '<br>' : '\n';
	var props = [];
	var indent = arguments[2] ? arguments[2] : 0;
	for(var i in obj)
	{
		switch(typeof(obj[i]))
		{
			case 'object':
				props.push(repeat(space, indent + 1) + i + ': ' + nl + getProperties(obj[i], html, indent + 1));
				break;
			case 'string':
				props.push(repeat(space, indent + 1) + i + ': \'' + obj[i] + '\'');
				break;
			default:
				props.push(repeat(space, indent + 1) + i + ': ' + obj[i]);
				break;
		}
	}
	return (html && !indent ? '<pre>' : '') + repeat(space, indent) + (obj.length ? '[' : '{') + nl + props.join(', ' + nl) + nl + repeat(space, indent) + (obj.length ? ']' : '}') + (html && !indent ? '</pre>' : '');
}

function debug()
{
	var output = [];
	for(var i = 0; i < arguments.length; i++)
		if(typeof(arguments[i]) == 'object')
			output[i] = '[' + typeof(arguments[i]) + '] = ' + getProperties(arguments[i], true);
		else
			output[i] = '[' + typeof(arguments[i]) + '] = ' + arguments[i];
	if(navigator.userAgent.indexOf('MSIE') != -1) 
		alert(output.join('\n\n')); 
	else 
		return wnd('Debug Information', '<pre>' + output.join('\n\n') + '</pre>');
}

//////////////////////////////////////////////////////////////////////////////////////////////
//
// Window
//
//////////////////////////////////////////////////////////////////////////////////////////////

function wnd(title, html, x, y, width, height, opacity, padding, container, isIframe)
{
	if(!container) container = document.body;
	if(!container.wnds) container.wnds = [];
	container.onmouseup = function(e) 
	{ 
		var evt = e ? e : event; 
		this.drag = null; 
		this.resize = null; 
	};
	container.onmousemove = function(e) 
	{ 
		var evt = e ? e : event; 
		if(this.resize) 
		{ 
			if(this.resize.resize.side.indexOf('E') != -1) 
			{ 
				this.resize.style.width = (this.resize.resize.width + evt.clientX - this.resize.resize.mouseX) + 'px'; 
			} 
			else if(this.resize.resize.side.indexOf('W') != -1) 
			{ 
				this.resize.style.left = evt.clientX + 'px'; 
				this.resize.style.width = (this.resize.resize.width - evt.clientX + this.resize.resize.left) + 'px'; 
			} 
			if(this.resize.resize.side.indexOf('S') != -1) 
			{ 
				this.resize.style.height = (this.resize.resize.height + evt.clientY - this.resize.resize.mouseY) + 'px';
			} 
			else if(this.resize.resize.side.indexOf('N') != -1) 
			{ 
				this.resize.style.top = evt.clientY + 'px'; 
				this.resize.style.height = (this.resize.resize.height - evt.clientY + this.resize.resize.top) + 'px';
			} 
			this.resize.onresize(); 
		} 
		else if(this.drag) 
		{ 
			this.drag.style.left = (this.drag.drag.startX + evt.clientX - this.drag.drag.mouseX) + 'px'; 
			this.drag.style.top = (this.drag.drag.startY + evt.clientY - this.drag.drag.mouseY) + 'px'; 
		}
	};

		var div = container.wnds[container.wnds.length] = document.createElement('DIV');
		div.container = container;
		div.style.position = 'absolute';
		div.style.color = 'black';
		div.style.fontFamily = 'Verdana, Helvetica, Arial, sans-serif';
		div.resizemargin = 7;
		div.isIframe = isIframe;
		if(opacity)
		{
			div.style.filter = 'alpha(opacity=' + opacity + ')';
			div.style['-moz-opacity'] = '0.' + opacity;
			div.style.opacity = '0.' + opacity;
		}
		if(container.wnds.length == 1)
		{
			div.style.top = (x ? x : 50) + 'px';
			div.style.left = (y ? y : 50) + 'px';
			div.style.zIndex = container.maxZ = 10000;
		}
		else
		{
			div.style.top = (x ? x : container.wnds[container.wnds.length - 2].offsetTop + 30) + 'px';
			div.style.left = (y ? y : container.wnds[container.wnds.length - 2].offsetLeft + 30) + 'px';
			div.style.zIndex = container.maxZ++;
		}
		div.onmousemove = function(e) 
		{ 
			var evt = e ? e : event; 
			var side = ''; 
			if(evt.clientY - this.offsetTop < this.resizemargin) 
				side = 'N'; 
			if(evt.clientY - this.offsetTop - this.offsetHeight > -this.resizemargin) 
				side = 'S'; 
			if(evt.clientX - this.offsetLeft < this.resizemargin) 
				side += 'W'; 
			if(evt.clientX - this.offsetLeft - this.offsetWidth > -this.resizemargin) 
				side += 'E'; 
			if(side) 
			{ 
				this.style.cursor = side + '-resize'; 
				this.resize = { width: this.offsetWidth, height: this.offsetHeight, top: this.offsetTop, left: this.offsetLeft, mouseX: evt.clientX, mouseY: evt.clientY, side: side }; 
			} 
			else 
			{ 
				this.style.cursor = 'auto'; 
				if(this.parentNode.resize != this)
					this.resize = null; 
			}
		};
		div.onmousedown = function(e) 
		{ 
			var evt = e ? e : event; 
			this.style.zIndex = this.parentNode.maxZ++; 
			if(this.resize)
				this.parentNode.resize = this; 
			if(evt.stopPropagation) 
				evt.stopPropagation(); 
			evt.cancelBubble = true; 
			return false; 
		};
		div.set = function(html) 
		{ 
			if(this.isIframe) 
				this.cnt.src = html; 
			else 
				this.cnt.innerHTML = html; 
		};
		div.onresize = function(e) 
		{ 
			this.tdm.style.width = (this.clientWidth - this.lft.clientWidth - this.rgt.clientWidth) + 'px'; 
			this.wnd.style.width = (this.tab.clientWidth - 6) + 'px'; 
			this.wnd.style.height = (this.clientHeight - this.rgt.clientHeight) + 'px'; 
		};
		
		
			var wnd = div.wnd = document.createElement('DIV');
			wnd.style.position = 'static';
			wnd.style.overflow = 'auto';
			wnd.style.borderLeft = wnd.style.borderRight = wnd.style.borderBottom = '3px solid blue';
			wnd.style.backgroundColor = 'white';
		
				var cnt = div.cnt = document.createElement(isIframe ? 'IFRAME' : 'DIV');
				if(isIframe) cnt.src = html; else cnt.innerHTML = html;
				cnt.style.padding = (padding === undefined || padding === null ? 10 : padding) + 'px';
				if(width) cnt.style.width = width + 'px';
				if(height) cnt.style.height = height + 'px';
				div.set(html);
	
			var bar = document.createElement('DIV');
			bar.onmousedown = function(e) 
			{ 
				var evt = e ? e : event; 
				this.parentNode.style.zIndex = this.parentNode.container.maxZ++; 
				this.parentNode.container.drag = this.parentNode; 
				this.parentNode.drag = { startX: this.parentNode.offsetLeft, startY: this.parentNode.offsetTop, mouseX: evt.clientX, mouseY: evt.clientY }; 
			};
			
			
				var tab = div.tab = document.createElement('TABLE');
				tab.border = '0';
				tab.cellPadding = '0';
				tab.cellSpacing = '0';
				tab.height = '30';
				
					var tbd = document.createElement('TBODY');
					
						var trw = document.createElement('TR');
						trw.valign = 'bottom';
					
							var tdl = document.createElement('TD');
			
								var lft = div.lft = document.createElement('IMG');
								lft.src = '/images/wnd_header_left.gif';
								lft.style.cursor = 'default';
			
							var tdm = div.tdm = document.createElement('TD');
							tdm.style.backgroundImage = 'url("/images/wnd_header_bg.gif")';
							tdm.style.backgroundRepeat = 'repeat-x';
							tdm.style.backgroundPosition = 'top';
							tdm.nowrap = 'nowrap';
	
								var tit = document.createElement('DIV');
								tit.innerHTML = title;
								tit.overflow = 'hidden';
								tit.style.maxHeight = '29px';
								tit.style.color = 'white';
								tit.style.fontFamily = 'Verdana, Helvetica, Arial, sans-serif';
								tit.style.paddingLeft = '2px';
								tit.style.paddingRight = '4px';
								tit.style.paddingTop = '1px';
								tit.style.fontWeight = 'bold';
								tit.style.fontSize = '10pt';
								tit.style.cursor = 'default';
	
							var tdr = document.createElement('TD');
							
								var rgt = div.rgt = document.createElement('IMG');
								rgt.src = '/images/wnd_header_right.gif';
								rgt.style.cursor = 'pointer';
								rgt.onclick = function() 
								{ 
									this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode); 
									return false; 
								};
			
							tdl.appendChild(lft);
							tdm.appendChild(tit);
							tdr.appendChild(rgt);
						trw.appendChild(tdl);
						trw.appendChild(tdm);
						trw.appendChild(tdr);
					tbd.appendChild(trw);
				tab.appendChild(tbd);
			bar.appendChild(tab);
			wnd.appendChild(cnt);
		div.appendChild(bar);
		div.appendChild(wnd);
	container.appendChild(div);
	div.onresize();
	return div;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//
// Document Object Model (DOM)
//
//////////////////////////////////////////////////////////////////////////////////////////////

function getSibling(node)
{
	var sib = arguments[1] ? arguments[1] + 'Sibling' : 'nextSibling';
	while(node[sib])
		if(node[sib].tagName)
			return node[sib];
		else
			node = node[sib];
}

function getChildren(node)
{
	var result = [];
	for(var i = 0; i < node.childNodes.length; i++)
		if(node.childNodes[i].tagName)
			result[result.length] = node.childNodes[i];
	return result;
}

function setEvent(obj, evt, func)
{
	if(evt == 'load')
		if(!document.onload)
			document.onload = [func];
		else
			document.onload[document.onload.length] = func;
	else if(obj.addEventListener)
		obj.addEventListener(evt, func, false);
	else if (obj.attachEvent)
		obj.attachEvent('on' + evt, func);
	else if (document.getElementById)
		obj['on' + evt] = func;
}

function getNodeText(node)
{
	return coalesce(node.textContent, node.innerText, node.text);
}


//////////////////////////////////////////////////////////////////////////////////////////////
//
// Asyncronous JavaSctipt and XML (AJAX)
//
//////////////////////////////////////////////////////////////////////////////////////////////

function loadAjax(url, func, data)
{
	var obj;
	if (window.XMLHttpRequest) 
	{
		obj = new XMLHttpRequest();
	}
	else
	{
		if (window.ActiveXObject) 
		{
			obj = new ActiveXObject('MSXML2.XMLHTTP.3.0');
			if(!obj)
			{
				obj = new ActiveXObject('Microsoft.XMLHTTP');
			}
		}
	}
	if(obj)
	{
		if(!window.ajax)
			window.ajax = [obj];
		else
			window.ajax[window.ajax.length] = obj;
		obj.onsuccess = func;
		obj.data = data;
		obj.onreadystatechange = function()
		{
			if(obj.readyState == 4)
			{
				if(obj.status == 200)
				{
					if(obj.onsuccess)
					{
						obj.onsuccess(obj.responseXML.documentElement, obj.data);
					}
				}
				else
				{
					debug("Problem retrieving data from the server, status code: "  + obj.status);
				}
			}
		};
		obj.open('GET', url, true);
		obj.send(null);		
	}
}


function populateForm(doc, frm)
{
	var field;
	var children;
	var value;
	var nodes = getChildren(doc);
	for(var i = 0; i < nodes.length; i++)
	{
		for(var j in frm.elements)
		{
			if(frm.elements[j] && frm.elements[j].tagName && frm.elements[j].name == nodes[i].getAttribute('name'))
			{
				field = frm.elements[j];
				children = getChildren(nodes[i]);
				value = getNodeText(nodes[i]);
				switch(field.tagName.toUpperCase())
				{
					case 'INPUT':
						field.value = value;
						break;
					case 'SELECT':
						if(field.multiple)
						{
							if(children.length)
							{
								value = [];
								for(var k = 0; k < children.length; k++)
								{
									value[k] = getNodeText(children[k]);
								}
							}
							else if(nodes[i].getAttribute('delimiter'))
							{
								value = value.split(nodes[i].getAttribute('name'));
							}
						}
						selectOption(field, value);
						break;
				}
			}
		}
	}
}

function populateSelect(doc, sel)
{
	var node = null;
	var opt = null;
	var index = 0;
	var old = typeof(sel) == 'object' ? sel : document.getElementById(sel);
	if(old.tagName.toUpperCase() == 'SELECT')
	{
		sel = old.cloneNode(false);
	}
	else
	{
		sel = document.createElement('SELECT');
		sel.id = old.id;
		sel.name = old.name;
		sel.className = old.className;
	}
	for(var i = 0; i < doc.childNodes.length; i++)
	{
		node = doc.childNodes[i];
		if(node.tagName)
		{
			opt = document.createElement('OPTION');
			opt.value = coalesce(node.getAttribute('value'), node.getAttribute('id'), node.getAttribute('ID'));
			opt.text = getNodeText(node);
			sel.options.add(opt);
			if(node.getAttribute('selected') || doc.getAttribute('selectedValue') == opt.value || doc.getAttribute('selectedIndex') == i)
			{
				sel.selectedIndex = index;
			}
			index++;
		}
	}
	old.parentNode.replaceChild(sel, old);
	return sel;
}

function populateSelectElseText(doc, sel)
{
	var old = typeof(sel) == 'object' ? sel : document.getElementById(sel);
	if(doc.childNodes.length == 0 || (doc.childNodes.length == 1 && !doc.childNodes[0].tagName))
	{
		sel = document.createElement('INPUT');
		sel.type = 'text';
		sel.id = old.id;
		sel.name = old.name;
		sel.className = old.className;
		if(old.tagName.toUpperCase() == 'INPUT')
		{
			sel.value = old.value;
		}
		old.parentNode.replaceChild(sel, old);
	}
	else
	{
		populateSelect(doc, sel);
	}
	return sel;
}


//////////////////////////////////////////////////////////////////////////////////////////////
//
// DHTML Interaction
//
//////////////////////////////////////////////////////////////////////////////////////////////

function selectOption(sel, val)
{
	if(sel.multiple)
	{
		if(typeof(val) == 'string')
			if(arguments[2])
				val = val.split(arguments[2]);
			else if(value.indexOf('|') != -1)
				val = val.split('|');
			else if(value.indexOf(';') != -1)
				val = val.split(';');
			else if(value.indexOf(',') != -1)
				val = val.split(',');
		for(var i = 0; i < sel.options.length; i++)
			for(var j = 0; j < val.length; j++)
				if(sel.options[i].value == val[j])
					sel.options[i];
	}
	else
	{
		for(var i = 0; i < sel.options.length; i++)
		{
			if(sel.options[i].value == val)
			{
				sel.selectedIndex = i;
				break;
			}
		}
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////
//
// Element Rotator
//
//////////////////////////////////////////////////////////////////////////////////////////////

var Rotator = function(container, frameRate, fadeFactor, duration)
{
	
	this.setProperties = function(page)
	{
		page.index = this.pages.length;
		page.style.display = 'none';
		page.rotator = this;
		page.style.position = 'absolute';
		page.style.top = '0px';
		page.style.left = '0px';
		
		page.setOpacity = function(value)
		{
			page.current = value;
			page.style.MozOpacity = value;
			page.style.opacity = value;
			page.style.filter = 'alpha(opacity=' + (value * 100) + ')';
		};
		
		page.show = function()
		{
			page.style.display = 'block';
			if(page.intervalID)
			{
				clearInterval(page.intervalID);
			}
			this.intervalID = setInterval(function()
			{
				page.setOpacity(page.current + (1 - page.current) / page.rotator.fadeFactor);
				if(page.current > 0.99)
				{
					clearInterval(page.intervalID);
					page.setOpacity(1);
					page.intervalID = null;
					if(page.rotator.duration > 0)
					{
						page.timeoutID = setTimeout(function() { page.rotator.next(); }, page.rotator.duration * 1000);
					}
				}
			}, 1000 / page.rotator.frameRate);
		};
		
		page.hide = function()
		{
			if(page.timeoutID)
			{
				clearTimeout(page.timeoutID);
				page.timeoutID = null;
			}
			if(page.intervalID)
			{
				clearInterval(page.intervalID);
			}
			page.intervalID = setInterval(function()
			{
				page.setOpacity(page.current - page.current / page.rotator.fadeFactor);
				if(page.current < 0.01)
				{
					page.setOpacity(0);
					page.style.display = 'none';
					clearInterval(page.intervalID);
					page.intervalID = null;
				}
			}, 1000 / page.rotator.frameRate);
		};
		
		page.setOpacity(0);
	}
	
	this.find = function(obj, id)
	{
		if(obj.id == id)
		{
			return obj;
		}
		if(obj.children)
		{
			for(var i = 0; i < obj.childNodes.length; i++)
			{
				var child = this.find(obj.childNodes[i], id);
				if(child)
				{
					return child;
				}			
			}
		}
		return null;
	}
	
	this.next = function()
	{
		if(arguments[0] === undefined || arguments[0] != this.current)
		{
			if(this.pages[this.current])
			{
				this.pages[this.current].hide();
			}
			this.current = (arguments[0] === undefined ? ++this.current : arguments[0]) % this.pages.length;
			this.pages[this.current].show();
		}
	}

	this.pages = [];
	this.current = -1;
	this.container = container;
	this.container.rotator = this;
	this.frameRate = frameRate ? frameRate : 24;
	this.fadeFactor = fadeFactor ? fadeFactor : 20;
	this.duration = duration;
	for(var i = 0; i < this.container.childNodes.length; i++)
	{
		if(this.container.childNodes[i].tagName)
		{
			this.setProperties(this.container.childNodes[i]);
			this.pages.push(this.container.childNodes[i]);
		}
	}
	
};


//////////////////////////////////////////////////////////////////////////////////////////////
//
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////

function walk(callback)
{
	var obj = arguments[1] ? arguments[1] : document;
	callback(obj);
	for(var i in obj.childNodes)
	{
		walk(callback, obj.childNodes[i]);
	}
}

function coalesce()
{
	for(var i = 0; i < arguments.length; i++)
		if(arguments[i] != null)
			return arguments[i];
}

function captcha(width, height, background, noise, text, foreground, font, nonumbers)
{	
	id = code(10);
	document.write('<img id="' + id + '" />');
	obj = document.getElementById(id);
	func = function() { obj.src = '/common/captcha.php?Width=' + (width ? width : '') + '&Height=' + (height ? height : '') + '&Background=' + (background ? background : '') + '&Noise=' + (noise ? noise : '') + '&Text=' + (text ? text : '') + '&Foreground=' + (foreground ? foreground : '') + '&Font=' + (font ? font : '') + '&NoNumbers=' + (nonumbers ? nonumbers : '') + '&u=' + code(20); };
	setEvent(document, 'load', func);
	setEvent(obj, 'click', func);
}

function code()
{
	var output = '';
	var length = arguments[0] ? arguments[0] : 5;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwhyx1234567890';
	for(var i = 0; i < length; i++)
	{
		output += chars.substr(Math.round(Math.random() * chars.length), 1);
	}
	return output;
}

function repeat(string, times)
{
	var result = '';
	for(var i = 0; i < times; i++)
	{
		result += string;
	}
	return result;
}

