var defaultaction;
var ev = YAHOO.util.Event;
var dom = YAHOO.util.Dom;
var isIE = YAHOO.env.ua.ie > 0;
ev.onDOMReady(initSearchFields);
ev.onDOMReady(initToggles);
ev.onDOMReady(initTextBoxes);
ev.onDOMReady(initForms);

var images = new Array('css/images/red-x.png','css/images/red-xhover.png', 'css/images/additemhover.png', 'css/images/right-arrow-hover.png', 'css/images/left-arrow-hover.png', 'css/images/between-arrow-hover.png', 'css/images/small-loader.gif', 'css/images/dialog-x-hover.png')
var monthnames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

for(var c = 0; c < images.length; c++)
{
	var i = new Image();
	i.src = images[c];
	
}

//fix IE's lack of indexOf() problem

if (Array.indexOf == null) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  }
}

function createRequest()
{
	var xmlHttp;
	try
	{
		 // Firefox, Opera 8.0+, Safari
		 xmlHttp=new XMLHttpRequest();
	}
		catch (e)
		{
		  // Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser is not supported. Please update to view this site properly.");
				return false;
			}
		}
	}
		 
	return xmlHttp;
}

function ordinal(num, superscript) 
{
	if(superscript)
	{
		return num + (
			(num % 10 == 1 && num % 100 != 11) ? '<sup>st</sup>' :
			(num % 10 == 2 && num % 100 != 12) ? '<sup>nd</sup>' :
			(num % 10 == 3 && num % 100 != 13) ? '<sup>rd</sup>' : '<sup>th</sup>'
		);
	}
	else
	{
		return num + (
			(num % 10 == 1 && num % 100 != 11) ? 'st' :
			(num % 10 == 2 && num % 100 != 12) ? 'nd' :
			(num % 10 == 3 && num % 100 != 13) ? 'rd' : 'th'
		);
	}
}

function ellipsis(str, length)
{
	if(str.length > length)
	{
		return str.substr(0, length-3) + "...";
	}
	else
	{
		return str;
	}
}

function getOptByValue(chooser, value)
{
	var options = chooser.options;
	var opt;
	var final = new Array();
	for(var c = 0; c < options.length; c++)
	{
		if(options[c].value == value)
		{
			final.push(options[c]);
		}
	}
	
	if(final.length == 1) //return element if theres only 1
	{
		return final[0];
	}
	else //more than one match - return array
	{
		return final;
	}
}

function button(text, func, args, classname, context)
{
	var a = document.createElement('a');
	dom.addClass(a, classname);
	a.href = 'javascript:void(0)';
	a.name = 'button';
	ev.addListener(a, 'click', func, args, context);
	a.innerHTML = text;
	return a;
}

function dialogBox(width, content, isajax, dontdestroy) //after isajax - altremove, boxgonefunc, e
														//if dontdestory is true, box will only go invisible when removed instead of being removed from DOM
{
	this.content;
	this.firsttime = true;
	this.visible;
	this.blackout;
	this.objects;
	this.embeds;
	this.isFading = false;
	this.loadShow = false;
	this.exists = false; //whether it is taking an already existing box and transforming it

	if(isajax == null)
	{
		isajax = false;
	}
	
	if(width == null)
	{
		this.width = null;
		this.content = null;
		this.isajax = null;
	}
	else
	{
		this.isactive = true;
		this.width = width;
		this.visible = false;
	
		if(!isajax)
			this.content = content;
	}
		
	this.loadFinished = new YAHOO.util.CustomEvent("boxloaded", this);
	this.loadFinished.subscribe(initTextBoxes);
	this.onGone = new YAHOO.util.CustomEvent("boxgone", this);
	this.onVisible = new YAHOO.util.CustomEvent("visible", this);
	
	this.show = function(type, args, func)
	{				
		if(func != null)
			func(this);
				
		var textboxes = dom.getElementsBy(function(el){return el.type != 'hidden' && el.style.display != 'none'}, 'input', this.dialogDiv);		
		
		if(!this.exists) //do fade up if appropriate
		{	
			if(textboxes[0] != null)
			{
				textboxes[0].focus();
			}
			else
			{
				//this.removeLink.focus();
			}
			this.hideFlash();
			var blackfade = new YAHOO.util.Anim(this.blackout,  {opacity: { from: 0, to: .7 } }, .3);
			var boxfade = new YAHOO.util.Anim(this.dialogDiv,  {opacity: { from: 0, to: 1 } }, .3);
			boxfade.onComplete.subscribe(this.showFlash, null, this);
			boxfade.animate(); 
			blackfade.animate();
		}
		else
		{
			if(textboxes[0] != null)
				textboxes[0].focus();
		}
		
		this.alignVertical();
	}
	
	this.hideFlash = function() //hide flash content
	{
		var foundone = false;
		
		for(var c = 0; c < this.objects.length; c++)
		{
			this.objects[c].style.visibility = 'hidden';
			foundone = true;
		}

		for(var c = 0; c < this.embeds.length; c++)
		{
			this.embeds[c].style.visibility = 'hidden';
			foundone = true;
		}
		
		return foundone;
	}
	
	this.showFlash = function() //show flash content
	{
		for(var c = 0; c < this.objects.length; c++)
		{
			this.objects[c].style.visibility = 'visible';
		}

		for(var c = 0; c < this.embeds.length; c++)
		{
			this.embeds[c].style.visibility = 'visible';
		}
	}

	this.setBorderColor = function(color)
	{
		this.dialogDiv.style.borderColor = color;
		this.boxbottom.style.background = color;
	}

	this.alignVertical = function() //calculate proper vertical alignment
	{
		var h = new YAHOO.util.Anim(this.dialogDiv, {}, 0);
		var height = h.getAttribute('height');

		var dh = new YAHOO.util.Anim(this.blackout, {}, 0);
		var docheight = dh.getAttribute('height');
		if(this.dialogDiv != null)
			this.dialogDiv.style.marginTop = (docheight-height)/2 + "px";
		this.visible = true;
	}
	
	this.remove = function(func)
	{
		if(!this.isFading)
		{
			removeChildren = function(type, args, e)
			{
				document.body.removeChild(document.getElementById('blackout'));
				document.body.removeChild(document.getElementById('dialogcenter'));
				e.onGone.fire();
			}

			var blackfade = new YAHOO.util.Anim(document.getElementById("blackout"),  {opacity: { from: .7, to: 0 } }, .3);
			var boxfade = new YAHOO.util.Anim(document.getElementById("dialogbox"),  {opacity: { from: 1, to: 0 } }, .3);

			boxfade.onComplete.subscribe(removeChildren, this, this);
			if(func != null){boxfade.onComplete.subscribe(func)};

			if(!YAHOO.lang.isUndefined(this.hideFlash) && this.hideFlash())
			{
				var delay = new YAHOO.util.Anim(this.boxbottom, {opacity:{from: 1, to:1 }}, .2);
				delay.onComplete.subscribe(function(type, args, e){e.boxfade.animate(); e.blackfade.animate();}, {boxfade:boxfade, blackfade: blackfade});
				delay.animate();
			}
			else
			{
				boxfade.animate(); 
				blackfade.animate();
			}
			
			this.isFading = true;
		}
	}
	
	this.setContent = function(content, width)//put new HTML or new element in
	{
		this.content = content;
		
		if(isIE)
		{
			if(width.search('ex') >= 0)
			{
				width = parseInt(width) + 12;
				width = width + "ex";
			}
			else if(width.search('em') >= 0)
			{
				width = parseInt(width) + 5;
				width = width + "em";
			}
			else if(width.search('px') >= 0)
			{
				width = parseInt(width) + 60;
				width = width + "px";
			}
		}
		
		this.width = width;
		
		if(YAHOO.lang.isString(content))
		{
			this.contentDiv.innerHTML = this.content;
			this.dialogDiv.style.width = this.width;
		}
		else if(YAHOO.lang.isObject(content))
		{
			this.contentDiv.innerHTML = "";
			this.contentDiv.appendChild(this.content);	
			this.dialogDiv.style.width = this.width;
		}
			
		var closers = dom.getElementsByClassName('closedialog', 'a', this.contentDiv, function(ref, args)
		{
			var rem = function(type, box)
			{
				box.remove();
			}
			
			ev.addListener(ref, 'click', rem, args);
		}, this);
	
	
		if(!this.exists)
		{
			this.onVisible.fire();
			this.blackout = document.createElement("div");
			this.blackout.id = 'blackout';
			this.blackout.style.opacity = 0;
			try
			{
				this.blackout.style.filter ="progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
			}
			catch(e)
			{}
			document.body.appendChild(this.blackout);
			document.body.appendChild(this.center);
		}
	
		this.objects = dom.getElementsBy(function(){return true;}, 'object', this.dialogDiv);
		this.embeds = dom.getElementsBy(function(){return true;}, 'embed', this.dialogDiv);
		this.alignVertical();
		this.loadFinished.fire();
	}
	
	this.ajax = function(query, width, ref)
	{
		this.width = width;
		var show = function(text, e)
		{
			e.obj.setContent(text, e.obj.width);
		}

		if(ref == null)
			ref = this;

		ajaxGet(query, show, {obj:ref, width:this.width})
	}
	
	this.onLoadFinishedShow = function(func)
	{
		if(func != null)
		{
			this.loadFinished.subscribe(this.show, func, this);
		}
		else
		{
			this.loadFinished.subscribe(this.show, null, this);
		}
		this.loadShow = true;
	}
	
	ev.addListener(window, 'resize', this.alignVertical, null, this);

	if(document.getElementById('dialogcenter') == null)
	{
		this.center = document.createElement("div");
		this.center.id = 'dialogcenter';
		this.dialogDiv = document.createElement('div');
		this.dialogDiv.id = 'dialogbox';
		this.dialogDiv.style.width = this.width;
		try
		{
			this.dialogDiv	.style.filter ="progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
		}
		catch(e)
		{}
		this.contentDiv = document.createElement('div');
		this.contentDiv.style['padding'] = '5px';
		this.contentDiv.id = 'boxcontent';
		this.boxbottom = document.createElement('div');
		this.boxbottom.id = 'boxbottom';
		this.removeLink = document.createElement('a');
		//this.removeLink.innerHTML = " ✕";
		if(this.dontdestroy)
		{
			ev.addListener(this.removeLink, 'click', this.toggleVisible, this, this);
		}
		else
		{
			ev.addListener(this.removeLink, 'click', this.remove, this, this);
		}
		
		this.removeLink.href = 'javascript:void(0)';
		this.boxbottom.appendChild(this.removeLink);
		this.dialogDiv.appendChild(this.contentDiv);
		this.dialogDiv.appendChild(this.boxbottom);
		this.center.appendChild(this.dialogDiv);
		document.body.appendChild(this.center);
	}
	else
	{
		this.center = document.getElementById('dialogcenter');
		this.dialogDiv = document.getElementById('dialogbox');
		this.contentDiv = document.getElementById('boxcontent');
		this.boxbottom = document.getElementById('boxbottom');
		this.blackout = document.getElementById('blackout');
		this.exists = true;
	}
	
	if(YAHOO.lang.isString(content))
	{
		if(isajax)	
		{
			this.ajax(content, this.width)
		}
		else
		{
			this.setContent(content, this.width);
		}
	}
	else if(YAHOO.lang.isObject(content))
	{
		this.setContent(content, this.width);
	}
}	


function ajax(id, query, func, e)//get content via ajax and put it in an element with id = id
{
	var request = createRequest();
	window.status = 'Loading...';
	
	request.onreadystatechange  = function()
	{
		if(request.readyState == 4)
		{
			window.status = '';
			if(id != "")
			{		
				if(YAHOO.lang.isObject(id))
				{
					var element = id;
				}
				else if(YAHOO.lang.isString(id) || YAHOO.lang.isNumber)
				{
					var element = document.getElementById(id);
					if(element === null)
						return;
				}
			
				element.innerHTML = request.responseText;
				if(func != null)
				{
					if(e==null)
					{
						func();
					}
					else
					{
						func(e);
					}
				}
			}
		}
		
	}
	
	request.open('GET', query, true);
	request.send(null);
}

function ajaxGet(query, success, e) //perform an ajax GET request and execute a function that takes the response text
{
	window.status = 'Loading...';
	var request = createRequest();
	var callback = function()
	{
		if(request.readyState == 4)
		{
			window.status = '';
			success(request.responseText, e);
		}
	}
	
	request.onreadystatechange = callback;
	request.open('GET', query, true);
	request.send(null);
}


function ajaxPost(query, params, success, givetext, e)//send a POST request via ajax  - query is the url, params is the parameter string - execute success() on completion with e passed as argument
{
	
	window.status = 'Loading...';
	
	var request = createRequest();
	
	if(givetext == null)
	{
		givetext = false;
	}
	
	callback = function()
	{
		if(request.readyState == 4)
		{
			if(request.responseText == "UNAUTHORIZED")
				window.location.href="index.php?page=home";
			if(success != null)
			{
				if(givetext)
				{
					if(e != null)
					{
						success(request.responseText, e);
					}
					else
					{
						success(request.responseText);
					}
				}
				else
				{
					window.status = '';
					if(e != null)
					{
						success(e);
					}
					else
					{
						success();	
					}
				}
			}
		}	
	}
	
	request.onreadystatechange = callback;
	
	request.open('POST', query, true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.send(params);
}

function myConfirm(message, func, obj, width, align, title)
{		
	
	if(width == null)
	{
		width = "200px";
	}
	
	if(align == null)
	{
		align = "center";
	}

	var outer = document.createElement('div');
	outer.style.paddingBottom = '5px';
	var h2 = document.createElement('h2');
	if(title == null)
	{
		h2.innerHTML = 'Confirm';
	}
	else
	{
		h2.innerHTML = title;
	}
	outer.appendChild(h2);
	outer.style.textAlign = 'center';
	var div = document.createElement('div');
	div.style.textAlign = align;
	div.style.marginBottom = '10px';
	div.style.marginTop = '5px';
	div.innerHTML = message;
	outer.appendChild(div);
	
	var dialog = new dialogBox(width, outer);
	
	var cancel = button('Cancel', dialog.remove);
	
	var confirmed = function(box, args)
	{
		args.box.onGone.subscribe(args.func, args.obj)
		args.box.remove();
	}
	
	var ok = button('OK', confirmed, {func:func, obj:obj, box:dialog});
	
	outer.appendChild(ok);
	outer.appendChild(cancel);
	
	dialog.show();
	ok.focus();

}

function myAlert(message, width)
{
	if(width == null)
		width = "200px";
	
	var outer = document.createElement('div');
	outer.style.paddingBottom = '5px';
	var h2 = document.createElement('h2');
	h2.innerHTML = 'Attention';
	outer.appendChild(h2);
	outer.style.textAlign = 'center';
	var div = document.createElement('div');
	div.style.textAlign = 'center';
	div.style.marginBottom = '10px';
	div.style.marginTop = '5px';
	div.innerHTML = message;
	outer.appendChild(div);

	var dialog = new dialogBox(width, outer, false);
	var ok = button('OK', dialog.remove);
	outer.appendChild(ok);
	
	dialog.show();
	ok.focus();
}

function initForms()
{
	var forms = document.getElementsByTagName('form');
	for(var curr in forms)
	{
		var key = new YAHOO.util.KeyListener(forms[curr], { keys:[13] }, function(e){ev.preventDefault(e);});
		key.enable();
	}
}


function initTextBoxes(startnode)
{
	var test = function(node)
	{
		return node.type == 'text' || node.type == 'password' || node.type == null && node.name != 'noinit';
	}
	
	var i = function(node)
	{
		var highlight = function(type, arg)
		{
			arg.style.background = '#D7DEFF';
		}
		
		var reset = function(type, arg)
		{
			arg.style.background = '#F0F0F0';
		}

		if(node.type == null || node.type != 'textarea')
		{
			var key = new YAHOO.util.KeyListener(node, { keys:[13] }, function(e){ev.preventDefault(e);});
			key.enable();
		}

		ev.addFocusListener(node, highlight, node);
		ev.addBlurListener(node, reset, node);
	}

	startnode = document.body;
	
	var boxes = dom.getElementsBy(test , "input" , startnode);
	var textareas = dom.getElementsBy(function(){return true;} , "textarea" , startnode);
	dom.batch(boxes, i);
	dom.batch(textareas, i);
}


function changeClassOnClick(el, newclass, newtext)
{	
	if(YAHOO.lang.isString(el))
		el = document.getElementById(el);
	
	var toggleclass = function(type, obj)
	{			
		if(this.className == obj.oldclass || this.className == null)
		{
			this.className = obj.newclass;
			if(newtext != null)
				this.innerHTML = obj.newtext;
		}
		else
		{
			this.className = obj.oldclass;
			this.innerHTML = obj.oldtext;
		}
	}
	
	ev.addListener(el , "click" , toggleclass, {oldclass:el.className, newclass:newclass, newtext:newtext, oldtext:el.innerHTML});
}

function initToggles()//initialize links that are to be mutually exclusive
{
	var groups = dom.getElementsByClassName("group");
	for(var c = 0; c < groups.length; c++)
	{
		var links = groups[c].childNodes; 
		for(var x = 0; x < links.length; x++)
		{
			ev.addListener(links[x] , "click" , doToggle, links[x]);
		}
	}
}

function doToggle(type, node)//method called to visually cue mutually exclusive links
{
	var parent = node.parentNode;
	for(var c = 0; c < parent.childNodes.length; c++)
	{
		dom.removeClass(parent.childNodes[c], 'selected');
	}
	
	dom.addClass(node, 'selected');
}

function initSearchFields()//init search boxes to say "Search..."
{
	var searches = dom.getElementsByClassName("searchfield");
	for(var c = 0; c < searches.length; c++)
	{
		if(searches[c].value == "")
			searches[c].value = "Search...";
		ev.addFocusListener(searches[c], clearVal, {obj:searches[c], value:searches[c].value});
		ev.addBlurListener(searches[c], clearVal, {obj:searches[c], value:searches[c].value});
	}
}

function clearVal(type, args) //toggle "Search" at appropriate times
{
	if(args.obj.value == args.value)
	{
		args.obj.value = "";
	}
	else if(args.obj.value == "")
	{
		args.obj.value = args.value;
	}
}

function formValues(formid) //returns a map - keys are ids of form elements, mappings are values
{
	var elements = document.getElementById(formid).elements;
	var result = new Array();
	for(var c = 0; c < elements.length; c++)
	{
		if((elements[c].type == 'radio') && !elements[c].checked)
		{
			continue;
		}

		var name;
		
		if(elements[c].id != null && elements[c].id != "")
		{
			name = elements[c].id;
		}
		else
		{
			name = elements[c].name;
		}
		
		if(elements[c].type == 'checkbox')
		{
			if(elements[c].checked)
			{
				result[name] = '1';
			}
			else
			{
				result[name] = '0';
			}
		}
		else
		{
			result[name] = elements[c].value;
		}
	}

	return result;
}


function sendForm(formid, query, success, arg1, arg2, arg3, callback2)
{
	var request = createRequest();
	var values = formValues(formid);
	var elements = document.getElementById(formid).elements;
	var params = "";
	var ids = dom.getElementsByClassName("status", "span", formid);
	var status = ids[0];
	if(status == null)
		status = document.getElementById('status');
	status.innerHTML = "&nbsp;";
	status.style.background = "url('css/images/small-loader.gif') no-repeat";
	
	for(key in values)
	{	
		if(key != 'indexOf')
			params += key + "=" + URL.encode(values[key]) + "&";
	}
	
	params = params.substring(0, params.length-1);	
	
	function react()
	{
		if(request.readyState == 4)
		{
			//alert(request.responseText);
			status.style.background = "";	
			var baditems = eval(request.responseText);
			var bad = false;
		
			for(var c = 0; c < elements.length; c++)
			{
				elements[c].style.background = "";
			}
		
		
			if(baditems != null && baditems.length != 0)
			{
				for(key in baditems) // baditems is an array created by the PHP page - encoded in JSON
				{
					bad = true;
					for(var c = 0; c < elements.length; c++)
					{
						if (elements[c].id == baditems[key] || elements[c].name == baditems[key])
							elements[c].style.background = "#F27364";
					}
						
				}
			}
			
			if(bad)
			{
				status.innerHTML = "<span style = 'font-size: 12px; color:red;'>Please complete the highlighted fields.</span>";
				if(callback2 != null)
				{
					callback2();
				}
			}
			else
			{
				status.innerHTML = "&nbsp;";
				if(YAHOO.lang.isString(success))
				{	
					eval(success);
				}
				else if(YAHOO.lang.isFunction(success))
				{		
					success(arg1, arg2, arg3);
				}
			}
		}
		
	}
	
	request.onreadystatechange = react;
	
	request.open('POST', query, true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.send(params);
}

function showLoginForm()
{
	function initBox()
	{
		
		function doLogin()
		{
			var elements = document.getElementById('loginform').elements;
			elements[0].blur();
			elements[1].blur();
			login();
		}
		
		var elements = document.getElementById('loginform').elements;
		var key1 = new YAHOO.util.KeyListener(elements[0], { keys:[13] }, doLogin);
		key1.enable();
		var key2 = new YAHOO.util.KeyListener(elements[1], { keys:[13] }, doLogin);
		key2.enable();
	}
	
	var dialogbox = new dialogBox('330px', "loginform.php", true);
	dialogbox.onLoadFinishedShow(initBox);
}

function login()
{
	var request = createRequest();
	var elements = document.getElementById('loginform').elements;
	var	params = elements[0].id + "=" + elements[0].value + "&" + elements[1].id + "=" + SHA1(elements[1].value);
	var status = document.getElementById("loginstatus");
	status.innerHTML = "<img src = 'css/images/small-loader.gif' alt = ''>";	

	request.onreadystatechange = function()
	{		
		if(request.readyState == 4)
		{	
			if(request.responseText == "true")
			{
				status.innerHTML = "<span style = 'font-size: 12px; color: green;'>Login successful!</span>"
				window.location.reload();
			}
			else
			{
				status.innerHTML = "<span style = 'font-size: 12px; color: red;'>Login failed.</span>";
			}
		}
	}

	request.open('POST', 'login.php', true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	
	request.send(params);
}

function confirmLogout(url)
{
	myConfirm('Are you sure you want to log out?', function(type, args, url){window.location = url;}, url, '220px');
}

function fileUploader(el, page, submitOnChoose)
{
	this.iframe = document.createElement('iframe');
	this.file;
	
	if(submitOnChoose)
	{	
		this.iframe.src = page + '.php?f=uploadform&submitonchoose=true';//page must define code for uploading
	}
	else
	{
		this.iframe.src = page + '.php?f=uploadform&submitonchoose=false';
	}

	this.iframe.width = '240px';
	this.iframe.height = '25px';
	this.iframe.scrolling = 'no';
	this.iframe.style.border = '0px transparent none';
	this.iframe.frameborder = '0';
	this.iframe.align = 'bottom';
	ev.generateId(this.iframe)
	var container = document.createElement('div');
	container.style.verticalAlign = 'middle';	
	this.hiddenel = document.createElement('input');
	this.hiddenel.name = 'filename';
	this.hiddenel.type = 'hidden';
	this.uploadStartedEvent = new YAHOO.util.CustomEvent('uploadStarted', this);
	this.uploadFinishedEvent = new YAHOO.util.CustomEvent('uploadFinished', this);
	this.uploadSuccessEvent = new YAHOO.util.CustomEvent('uploadSuccess', this);
	this.isFirstLoad = true;

	this.getiFrameDoc = function()
	{
		var doc = this.iframe.contentDocument;
		if(doc == null)
		{
			return document.frames[this.iframe.id].document; //ie fix
		}
		
		return doc;
	}

	this.reset = function()
	{
		this.getiFrameDoc().getElementById('fileupload').reset();
		this.setFile(null);
	}
	var element;
	
	if(YAHOO.lang.isString(el))
	{
		element = document.getElementById(el);
	}
	else if(YAHOO.lang.isObject(el))
	{
		element = el;
	}

	if(!submitOnChoose)
	{
		var reset = document.createElement('a');
		reset.style.display = 'inline-block';
		reset.style.marginBottom = '2px';
		reset.className = 'deletebutton';
		ev.addListener(reset, 'click', this.reset, null, this);
		container.appendChild(reset);
	}
	
	element.appendChild(container);
	container.appendChild(this.iframe);
	container.appendChild(this.hiddenel);

	if(this.isFirstLoad)
	{
		
		ev.addListener(this.iframe, 'load', function(type, args)
		{
			var f = args.getiFrameDoc().getElementById('file');
			ev.addListener(f, 'change', function()
			{ 
				args.setFile(f.value);
			});
		}, this);
		
		if(submitOnChoose)
		{
			ev.addListener(this.iframe, 'load', function(type, args)
			{
				var f = args.getiFrameDoc().getElementById('file');
				ev.addListener(f, 'change', function()
				{ 
					args.uploadStartedEvent.fire();
				});
			}, this);
		}
	}
	
	ev.addListener(this.iframe, 'load', function(type, args)
	{
		args.loadResponse(args.getiFrameDoc().getElementById('message').value);
	},  this);
	
	this.setFile = function(file)
	{
		if(file == null)
		{
			this.file = null;
		}
		else
		{
			this.file = basename(file); //keep file path off in IE
		}
		
		this.hiddenel.value = this.file;
	}
	
	this.loadResponse = function(message)
	{
		var m = eval(message);

		if(m != null)
		{
			if(m.status)
			{
				this.uploadSuccessEvent.fire();
			}
			else
			{
				if(m.message == 'FILEEXISTS')
				{
					var overwrite = function(type, args, e)
					{
						ajaxPost('filehandler.php?f=overwrite', 'filename='+e, function(){}, true);
					}

					m.message = "";
					myConfirm("\""+m.filename + "\" already exists. Overwrite?", overwrite, m.filename, '300px');
				}
			}
			this.uploadFinishedEvent.fire(m);
		}
			
		
	}
	
	this.submit = function()
	{
		this.uploadStartedEvent.fire();
		this.getiFrameDoc().getElementById('fileupload').submit();
	}
}

function isNumeric(sText)
{
	var ValidChars = "0123456789.";
	for (i = 0; i < sText.length; i++) 
	{ 
		if (ValidChars.indexOf(sText.charAt(i)) == -1)
			return false;
	}

	return true;
}

function SHA1 (msg) {
 
	function rotate_left(n,s) {
		var t4 = ( n<<s ) | (n>>>(32-s));
		return t4;
	};
 
	function lsb_hex(val) {
		var str="";
		var i;
		var vh;
		var vl;
 
		for( i=0; i<=6; i+=2 ) {
			vh = (val>>>(i*4+4))&0x0f;
			vl = (val>>>(i*4))&0x0f;
			str += vh.toString(16) + vl.toString(16);
		}
		return str;
	};
 
	function cvt_hex(val) {
		var str="";
		var i;
		var v;
 
		for( i=7; i>=0; i-- ) {
			v = (val>>>(i*4))&0x0f;
			str += v.toString(16);
		}
		return str;
	};
 
 
	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	};
 
	var blockstart;
	var i, j;
	var W = new Array(80);
	var H0 = 0x67452301;
	var H1 = 0xEFCDAB89;
	var H2 = 0x98BADCFE;
	var H3 = 0x10325476;
	var H4 = 0xC3D2E1F0;
	var A, B, C, D, E;
	var temp;
 
	msg = Utf8Encode(msg);
 
	var msg_len = msg.length;
 
	var word_array = new Array();
	for( i=0; i<msg_len-3; i+=4 ) {
		j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
		msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
		word_array.push( j );
	}
 
	switch( msg_len % 4 ) {
		case 0:
			i = 0x080000000;
		break;
		case 1:
			i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
		break;
 
		case 2:
			i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
		break;
 
		case 3:
			i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8	| 0x80;
		break;
	}
 
	word_array.push( i );
 
	while( (word_array.length % 16) != 14 ) word_array.push( 0 );
 
	word_array.push( msg_len>>>29 );
	word_array.push( (msg_len<<3)&0x0ffffffff );
 
 
	for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
 
		for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
		for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
 
		A = H0;
		B = H1;
		C = H2;
		D = H3;
		E = H4;
 
		for( i= 0; i<=19; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=20; i<=39; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=40; i<=59; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=60; i<=79; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		H0 = (H0 + A) & 0x0ffffffff;
		H1 = (H1 + B) & 0x0ffffffff;
		H2 = (H2 + C) & 0x0ffffffff;
		H3 = (H3 + D) & 0x0ffffffff;
		H4 = (H4 + E) & 0x0ffffffff;
 
	}
 
	var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
 
	return temp.toLowerCase();
 
}

var URL = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		
		try
		{
			string = string.replace(/\r\n/g,"\n");
		}
		catch(e)
		{
			string = "";
		}
			
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function basename(path) {
    return path.replace(/\\/g,'/').replace( /.*\//, '' );
}

function isUrl(s) {
	var http = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	var www = /(www.|ww3.)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return http.test(s) || www.test(s);	
}


