var theRequest = false;
var total_upload_size = 1;
var force_KB_size = 0
var force_KB_rate = 1
var progressPercent = 0;

function new_ajax_request()
{
	var myRequest = false;

	if(window.XMLHttpRequest)
	{
		myRequest = new XMLHttpRequest();
		if(myRequest.overrideMimeType)
		{
			myRequest.overrideMimeType('text/xml');
		}
	}
	else if(window.ActiveXObject)
	{
		try
		{
			myRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try
			{
				myRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	return myRequest;
}


function goajax(page)
{
	theRequest = new_ajax_request();

	if(!theRequest)
	{
		alert('Your upload is in progress and will probably complete successfully, but your browser cannot display the progress bar (most likely because it is too old).  Please wait while your upload completes.');
		return false;
	}

	theRequest.onreadystatechange = updateProgress;
	theRequest.open('GET', page, true);
	theRequest.send(null);
}

function updateProgress()
{
	if(theRequest)
	{
		if(theRequest.readyState == 4)
		{
			if(theRequest.status == 200)
			{
				var rawdata = theRequest.responseText.match(/<data>(.+)<\/data>/);

				

				var update = new Array();
				update = rawdata[1].split('|');

				if(update[1] != 0)
				{
					total_upload_size = update[1];
				}

				if(update[5] == 'toobig' || update[5] == 'quotaglobal' || update[5] == 'quotauser')
				{
					location.href="http://encdemo.com/upload/?error=" + update[5] + "&size=" + total_upload_size + "&limit=" + update[6];
				}

				var completed_upload_size = update[0];
				var elapsedtime = update[2];
				var numfinishedfiles = update[3];
				var numtotalfiles = update[4];
				var postprocessingdone = update[5];

				if((postprocessingdone == 1)   &&   document.getElementById('popupstatus'))
					window.close();

				if(isNum(total_upload_size) && isNum(completed_upload_size) && isNum(elapsedtime) && isNum(numfinishedfiles) && isNum(numtotalfiles) && isNum(postprocessingdone) && (total_upload_size > 1))
				{
					document.getElementById('progStatus').innerHTML = 'Uploading; please wait.';

					var newProgressPercent = Math.ceil((completed_upload_size/total_upload_size)*100);
					if(isNum(newProgressPercent) && (newProgressPercent > progressPercent) && (newProgressPercent >= 0) && (newProgressPercent <= 100))
					{
						progressPercent = newProgressPercent;

						document.getElementById('progPercent').innerHTML = progressPercent + '%';
						document.title = progressPercent + '% Complete [Uploading]';

						var newbarwidth = parseInt(progressPercent*350/100);
						//if(isNum(newbarwidth)) { document.getElementById('progBarDone').style.width = newbarwidth + 'px'; }
						if(isNum(newbarwidth)) { increment_pb_width(newbarwidth); }
					}

					var totaltime = parseInt((elapsedtime * 100) / progressPercent);
					var totaltime_forprint = format_timespan_with_unit(totaltime, '&nbsp;');
					var remainingtime_forprint = format_timespan_with_unit(eval(totaltime - elapsedtime), '&nbsp;');
					var elapsedtime_forprint = format_timespan_with_unit(elapsedtime, '&nbsp;');

					var force_MB = total_upload_size > 999999 ? 1 : 0;
					var total_upload_size_forprint = format_filesize_with_unit(total_upload_size, '&nbsp;', force_MB, force_KB_size);
					var remaining_upload_size_forprint = format_filesize_with_unit(total_upload_size - completed_upload_size, '&nbsp;', force_MB, force_KB_size);
					var completed_upload_size_forprint = format_filesize_with_unit(completed_upload_size, '&nbsp;', force_MB, force_KB_size);

					var transfer_rate = format_filesize_with_unit(completed_upload_size/elapsedtime, '&nbsp;', force_MB, force_KB_rate);

					if((completed_upload_size != "")   &&   (completed_upload_size != 0))
					{
						
						document.getElementById('donet').innerHTML = elapsedtime_forprint;
						document.getElementById('dones').innerHTML = completed_upload_size_forprint;
						document.getElementById('donef').innerHTML = numfinishedfiles;

						document.getElementById('leftt').innerHTML = remainingtime_forprint;
						document.getElementById('lefts').innerHTML = remaining_upload_size_forprint;
						document.getElementById('leftf').innerHTML = numtotalfiles - numfinishedfiles;

						document.getElementById('totalt').innerHTML = totaltime_forprint;
						document.getElementById('totals').innerHTML = total_upload_size_forprint;
						document.getElementById('totalf').innerHTML = numtotalfiles;
						
						document.getElementById('progRate').innerHTML = transfer_rate + '/s';
					}

					if(progressPercent == 100)
					{
						document.getElementById('theMeter').style.position = 'absolute';
						document.getElementById('theMeter').style.left = '-10000px';
						document.getElementById('theMeter').style.overflow = 'hidden';
						document.getElementById('theMeter').style.height = '0';

						document.getElementById('uploadCompleteMsg').style.position = 'relative';
						document.getElementById('uploadCompleteMsg').style.left = '0';
						document.getElementById('uploadCompleteMsg').style.height = 'auto';
						document.getElementById('uploadCompleteMsg').innerHTML = 'Upload complete; the server is now processing your file(s).&nbsp; This could take a minute or two if your upload was very big.&nbsp; Please wait.';
						
						document.getElementById('donet').innerHTML = totaltime_forprint;
						document.getElementById('dones').innerHTML = total_upload_size_forprint;
						document.getElementById('donef').innerHTML = numtotalfiles;

						document.getElementById('leftt').innerHTML = '00:00:00';
						document.getElementById('lefts').innerHTML = '0.0 MB';
						document.getElementById('leftf').innerHTML = '0';
						

						

						//return null;
					}
				}

				var timeout = 700;
				var now = new Date();
				window.setTimeout("goajax('" + document.getElementById('theuploadform').action + "&action=get_progress_and_size&foo=" + now.getTime() + "')", timeout);
			}
			else
			{
				
				// assume it was a temporary network problem and continue, but at a lower rate.
				var now = new Date();
				window.setTimeout("goajax('" + document.getElementById('theuploadform').action + "&action=get_progress_and_size&foo=" + now.getTime() + "')", 5000);
			}
		}
	}
}


function startupload()
{
	if(check_for_required_fields())
	{
		

		if(document.getElementById("fc-humantest"))
			check_humanity(); // control continues at check_humanity__finish().
		else
			do_upload();
	}
	else { return false; }
}

function generate_new_serial_number()
{
	var theform = document.getElementById('theuploadform');
	var juststatus = document.getElementById('fcjuststatus');
	if(theform   &&   !juststatus)
	{
		var new_serial = hex_sha1(get_random_text());
		theform.action = theform.action.replace(/serial=\w+/, 'serial=' + new_serial);

		var juststatuslink = document.getElementById('juststatuslink');
		if(juststatuslink)
			juststatuslink.href = juststatuslink.href.replace(/serial=\w+/, 'serial=' + new_serial);
	}
}

function do_upload()
{
	var file_present = document.getElementById('uploadname1').type == 'file' ? 1 : 0;
	var uploadform = document.getElementById('theuploadform');

	if(file_present   &&   document.getElementById('popupstatus'))
	{
		window.open(document.getElementById('juststatuslink').href,'fcstatuswindow','width=400,height=270,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=yes');
	}

	update_numitems();
	uploadform.submit();

	if(file_present)
	{
		document.getElementById('uploadbutton').disabled = true;

		if(document.getElementById('popupstatus'))
			document.getElementById('progBarContainer').innerHTML = 'Upload in progress; please wait.<br />If progress bar does not appear,<br /><a href="#" onclick="this.href=document.getElementById(\'juststatuslink\').href; return true" target="_blank">click here</a> to display it.';

		document.getElementById('progBarContainer').style.position = 'relative';
		document.getElementById('progBarContainer').style.left = '0';
		document.getElementById('progBarContainer').style.height = 'auto';

		

					uploadform.style.position = 'absolute';
	uploadform.style.left = '-10000px';
	uploadform.style.overflow = 'hidden';
	uploadform.style.height = '0';
	uploadform.style.display = 'none'; /* IE doesn't properly hide everything under HTML 4.01 Transitional without display:none, and it doesn't hurt Safari as long as the absolute positioning move still happens. */

		if(!document.getElementById('popupstatus'))
		{
			var timeout = 1200;
			var now = new Date();
			window.setTimeout("goajax('" + uploadform.action + "&action=get_progress_and_size&foo=" + now.getTime() + "')", timeout);
		}
	}
}

var stopinc = '';
function increment_pb_width(newwidth)
{
	if(newwidth <= 350)
	{
		if(stopinc == '')
			stopinc = window.setInterval("inc_pb_width(" + newwidth + ")", 10);
		else
			window.setTimeout("increment_pb_width('" + newwidth + "')", 100);
	}
}

function inc_pb_width(newwidth)
{
	var oldwidth = document.getElementById('progBarDone').style.width;
	oldwidth = oldwidth.replace(/px/,'');
	if((oldwidth++) <= newwidth)
	{
		document.getElementById('progBarDone').style.width = (oldwidth++) + 'px';
		//document.getElementById('title').innerHTML = 'set it to ' + (oldwidth++);
	}
	else
	{
		window.clearInterval(stopinc);
		stopinc = '';
		document.getElementById('progBarDone').style.width = newwidth + 'px';
	}
}

function startorder()
{
	var inputs = document.getElementById('theorderform').getElementsByTagName('input');
	var missing = 0;
	var i = 0;
	for(i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf('required') != -1   &&   (inputs[i].value == '' || inputs[i].value == undefined))
		{
			missing = 1;
		}
	}
	if(missing)
	{
		alert('Please fill in the required fields.');
	}
	else
	{
		document.getElementById('theorderform').submit();
	}
}


function itemactions_verify()
{
	var action = document.getElementById("actiontodo").value;
	var counts = get_selected_item_counts();
	var confirmed = 0;

	if(action == 'unzip_files')
	{
		if(counts.files_selected)	{ confirmed = window.confirm("Selected: " + counts.files_selected + " files.  Unzip now?");		}
		else				{ alert("No files selected.");								}
	}
	else if(action.indexOf('rotate_images') != -1)
	{
		if(counts.files_selected)	{ confirmed = window.confirm("Selected: " + counts.files_selected + " images.  Rotate now?");		}
		else				{ alert("No files selected.");								}
	}
	else if(action == 'delete_items')
	{
		if(counts.files_selected || counts.dirs_selected)	{ confirmed = window.confirm("Selected: " + counts.files_selected + " files and " + counts.dirs_selected + " folders.  Delete now (including any folder contents)?");		}
		else							{ alert("No files or folders selected.");														}
	}
	else if(action == 'reprocess_items')
	{
		reprocess_items();
	}

	if(confirmed)
	{
		var action_attribute = document.getElementById("itemactions").action;
	        action_attribute = action_attribute.replace(/action=itemactions/, 'action='+action);
		document.getElementById("itemactions").action = action_attribute;
		//alert("action: " + document.getElementById("itemactions").action);
		document.getElementById('itemactions').submit();
	}
	else
	{
		return false;
	}
}


function get_selected_item_counts()
{
	var checkboxes = document.getElementById("itemactions").getElementsByTagName("input");
	var dirs_selected = 0;
	var files_selected = 0;
	var total_selected = 0;
	for(i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].checked)
		{
			total_selected++;

			if(checkboxes[i].name.match(/^dir-/))
			{
				dirs_selected++;
			}
			else if(checkboxes[i].name.match(/^file-/))
			{
				files_selected++;
			}
		}
	}

	return { dirs_selected : dirs_selected, files_selected : files_selected, total_selected : total_selected };
}


function check_for_required_fields()
{
	var onlyinputs = document.getElementById('theuploadform').getElementsByTagName('input');
	var selects = document.getElementById('theuploadform').getElementsByTagName('select');
	var textareas = document.getElementById('theuploadform').getElementsByTagName('textarea');
	var inputs = new Array;
	var i = 0;
	for(i = 0; i < onlyinputs.length; i++)
	{
		inputs[i] = onlyinputs[i];
	}
	var j = 0;
	for(j = 0; j < selects.length; j++)
	{
		inputs[i + j] = selects[j];
	}
	var k = 0;
	for(k = 0; k < textareas.length; k++)
	{
		inputs[i + j + k] = textareas[k];
	}

	var items_missing = 0;
	var email_format_incorrect = 0;
	var numeric_format_incorrect = 0;

	for(i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf('required') != -1   &&   (inputs[i].value == '' || inputs[i].value == undefined))
		{
			inputs[i].style.background	= '#ffdd00';
			inputs[i].style.color		= '#000';
			items_missing = 1;
		}
		else if(inputs[i].className.indexOf('emailformat') != -1   &&   !inputs[i].value.match( /.+@.+\..+/ ))
		{
			inputs[i].style.background	= '#ffdd00';
			inputs[i].style.color		= '#000';
			email_format_incorrect = 1;
		}
		else if(inputs[i].className.indexOf('numeric') != -1   &&   !inputs[i].value.match( /^\d+$/ ))
		{
			inputs[i].style.background	= '#ffdd00';
			inputs[i].style.color		= '#000';
			numeric_format_incorrect = 1;
		}
		else
		{
			inputs[i].style.background	= inputs[i].type == 'radio' || inputs[i].type == 'checkbox' || inputs[i].type == 'button' || inputs[i].type == 'submit' ? 'transparent' : '#ffffff';
			inputs[i].style.color		= '#000';
		}
	}

	if(items_missing)
	{
		alert("Please fill in the required item(s).");
	}
	else if(email_format_incorrect)
	{
		alert("Please enter a valid email address.");
	}
	else if(numeric_format_incorrect)
	{
		alert("Please enter a number.");
	}
	else
	{
		return 1;
	}

	return 0;
}




function format_filesize_with_unit(num,space,forceMB,forceKB)
{
	if(!isNum(num,1)) { return "?" + space + "KB"; }

	var unit;
	if(   ((num > 999999)  ||  forceMB)   &&   !forceKB)
	{
		num = num/(1024*1024);
		num = num.toString();

		var testnum = num.replace( /^(\d+\.\d).*/, '$1' ); // show 1 decimal place. // extra escaping b/c printing JS from Perl.

		if(testnum == '0.0')
		{
			testnum = num.replace( /^(\d+\.\d\d).*/, '$1' ); // show 2 decimal places.
		}
		if(testnum == '0.00')
		{
			testnum = num.replace( /^(\d+\.\d\d\d).*/, '$1' ); // show 3 decimal places.
		}
		num = testnum;

		unit = 'MB';
	}
	else
	{
		num = parseInt(num/(1024));
		unit = 'KB';
	}
	return num + space + unit;
}

function format_timespan_with_unit(num,space)
{
	if(!isNum(num)) { return "00:00:00"; }

	if(num >= (60*60))
	{
		var secs_left = num % (60*60);
		var mins_left = secs_left / 60;
		mins_left = mins_left.toString();
		mins_left = mins_left.replace( /^(\d+)\..*/, '$1' ); // show no decimal places.  // extra escaping b/c printing JS from Perl.
		mins_left = mins_left.replace( /^(\d)$/, '0$1' ); // for single-digits, prepend a zero.

		num = num/(60*60);
		num = num.toString();
		num = num.replace( /^(\d+)\..*/, '$1' ); // show no decimal places.

		num = num + ':' + mins_left + ':00';
	}
	else if(num >= 60)
	{
		var secs_left = num % 60;
		secs_left = secs_left.toString().replace( /^(\d)$/, '0$1' ); // for single-digits, prepend a zero.

		num = num/60;
		num = num.toString();
		num = num.replace( /^(\d+)\..*/, '$1' ); // show no decimal places.  // extra escaping b/c printing JS from Perl.
		num = num.replace( /^(\d)$/, '0$1' ); // for single-digits, prepend a zero.

		num = '00:' + num + ':' + secs_left;
	}
	else
	{
		num = num.toString();
		num = num.replace( /^(\d+)\..*/, '$1' ); // show no decimal places. // extra escaping b/c printing JS from Perl.
		num = num.replace( /^(\d)$/, '0$1' ); // for single-digits, prepend a zero.
		num = '00:00:' + num;
	}
	return num;
}

function isNum(testval,decimalsOK)
{
	if(typeof(testval) == 'undefined') return false;
	testval = testval.toString();
	if (!testval.length) return false;
	var numbers = decimalsOK ? '.0123456789' : '0123456789';
	for (i=0; i<testval.length; i++)
	{
		if (numbers.indexOf(testval.charAt(i),0) == -1) return false;
	}
	return true;
}

function update_form_fields()
{
	//location.href="http://encdemo.com/upload/?items=" + document.getElementById("itemcount").value;

        var qs = location.search;
        qs = qs.replace(/^\?/, '');
        qs = qs.replace(/(.*)items=\d+(.*)/, '$1$2');
        qs = qs.replace(/&+/g, '&');
        qs = qs.replace(/(^&|&$)/, '');
	if(qs != '')
	{
		qs = qs + '&';
	}
	location.href="/upload/?" + qs + "items=" + document.getElementById("itemcount").value;
}

// In case the user set the form to N files, but then didn't populate all of them.
function update_numitems()
{
	var theform = document.getElementById('theuploadform');
	var inputs = theform.getElementsByTagName('input');
	var populated_file_elements = 0;
	var i = 0;
	for(i = 0; i < inputs.length; i++)
	{
		if((inputs[i].type == 'file' || inputs[i].className.indexOf('reprocessingfile') != -1)   &&   inputs[i].value != ''   &&   inputs[i].value != undefined)
		{
			populated_file_elements++;
		}
	}

	document.getElementById('numitems').value = populated_file_elements;

	if(document.getElementById('totalf'))
		document.getElementById('totalf').innerHTML = populated_file_elements;
	if(document.getElementById('leftf'))
		document.getElementById('leftf').innerHTML = populated_file_elements;

	if(theform.action.match( /items=\d+/ ))
		theform.action = theform.action.toString().replace( /items=\d+/, 'items=' + populated_file_elements );
	else
		theform.action += '&items=' + populated_file_elements;
}

function set_cookie(name, value, hours_to_live, path, domain, secure)
{
	var expireDate = "";
	if(hours_to_live)
	{
		expireDate = (new Date((new Date()).getTime() + hours_to_live*3600000)).toGMTString();
	}

	var curCookie = name + "=" + escape(value) +
	((hours_to_live) ? "; expires=" + expireDate : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

	document.cookie = curCookie;
}


function get_cookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}


function delete_cookie(name, path, domain)
{
	if(get_cookie(name))
	{
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
	else
	{
		alert('Your cart is empty.');
	}
}


function toggle_file_counts()
{
	var incl = document.getElementById("counts-incl-subfolders");
	var excl = document.getElementById("counts-excl-subfolders");

	if(excl)
	{
		if(excl.style.display == 'none')	{ incl.style.display = 'none'; excl.style.display = 'inline'; }
		else					{ excl.style.display = 'none'; incl.style.display = 'inline'; }
	}
}


function select_item(newvalue)
{
	var set_it = 1;
	var oldvalue = get_cookie('selected_items');
	if(oldvalue)
	{
		if(oldvalue.indexOf(newvalue) != -1)
		{
			if(window.confirm('This item is already in your cart.  Add it again?'))
			{
				set_it = 1;
			}
			else
			{
				set_it = 0;
			}
		}

		newvalue = oldvalue + ':|:|:' + newvalue;
	}
	if(set_it)
	{
		set_cookie('selected_items', newvalue, 168, '/');
		alert('Item added to cart.');
	}
}


function clear_selections()
{
	if(get_cookie('selected_items'))
	{
		if(window.confirm('About to empty your cart.  Is that OK?'))
		{
			delete_cookie('selected_items', '/');
			location.reload();
		}
	}
	else
	{
		alert('Your cart is empty.');
	}
}


function select_all_items(newvalue)
{
	var checkboxes = document.getElementById("itemactions").getElementsByTagName("input");
	for(i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].type == 'checkbox' && checkboxes[i].className.indexOf('itemaction') != -1)
		{
			checkboxes[i].checked = newvalue;
			checkboxes[i].onchange();
		}
	}
}


function replace_items()
{
	var checkboxes = document.getElementById("itemactions").getElementsByTagName("input");
	var qsitems = '';
	var dirs_selected = 0;
	var j = 1;
	for(i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].checked)
		{
			if(checkboxes[i].name.match(/^dir-/))
			{
				dirs_selected = 1;
			}
			else
			{
				qsitems = qsitems + "rfn" + j + "=" + checkboxes[i].name + "&";
				j++;
			}
		}
	}

	if(j == 1)
	{
		alert("No files selected.");
	}
	else
	{
		if(dirs_selected)
		{
			alert("This operation only applies to files, so any folders that you have selected will be ignored.");
		}

		var qs = location.search;
		qs = qs.replace(/^\?/, '');
		qs = qs.replace(/action=\w+/, '');
		qs = qs.replace(/&+/g, '&');
		qs = qs.replace(/(^&|&$)/, '');
		if(qs != '')
		{
			qs = qs + '&';
		}

		location.href = "/upload/?action=upload&" + qs + qsitems;
	}
}


function reprocess_items()
{
	var checkboxes = document.getElementById("itemactions").getElementsByTagName("input");
	var qsitems = '';
	var dirs_selected = 0;
	var j = 1;
	for(i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].checked)
		{
			if(checkboxes[i].name.match(/^dir-/))
			{
				dirs_selected = 1;
			}
			else
			{
				qsitems = qsitems + "ffs" + j + "=" + checkboxes[i].name + "&";
				j++;
			}
		}
	}

	if(j == 1)
	{
		alert("No files selected.");
	}
	else
	{
		if(dirs_selected)
		{
			alert("This operation only applies to files, so any folders that you have selected will be ignored.");
		}

		var qs = location.search;
		qs = qs.replace(/^\?/, '');
		qs = qs.replace(/action=\w+/, '');
		qs = qs.replace(/&+/g, '&');
		qs = qs.replace(/(^&|&$)/, '');
		if(qs != '')
		{
			qs = qs + '&';
		}

		location.href = "/upload/?action=upload&" + qs + qsitems;
	}
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var old_document_body_onclick = '';
function showoptsmenu(el)
{
	if(document.getElementById("theoptsmenu"))
	{
		return;
	}

	var div = document.createElement("div");
	div.className = "optsmenu";
	div.id = "theoptsmenu";
	div.style.position = 'absolute';
	var pos = findPos(el);
	div.style.left = eval(pos[0] + 30) + 'px';
	div.style.top = eval(pos[1] + 15) + 'px';
	document.body.appendChild(div);

	var size = '';
	var date = '';

	var row = el.parentNode.parentNode;
	var cols = row.childNodes;
	var i = 0;
	for(i = 0; i < cols.length; i++)
	{
		var children = cols[i].childNodes;
		var j = 0;
		for(j = 0; j < children.length; j++)
		{
			var link = children[j];
			if(link.nodeName == 'a' || link.nodeName == 'A')
			{
				if(cols[i].className == 'del')
				{
					var old_onclick = link.title;
					div.innerHTML += '<a href="#" onclick="closeoptsmenu(); ' + old_onclick + '">Delete</a>';
				}
				else if(cols[i].className == 'mv')
				{
					div.innerHTML += '<a href="' + link.href + '">Move</a>';
				}
				else if(cols[i].className == 'info')
				{
					div.innerHTML += '<a href="' + link.href + '">Info</a>';
				}
				else if(cols[i].className == 'sel')
				{
					div.innerHTML += '<a href="' + link.href + '">Select</a>';
				}
				else if(cols[i].className == 'mopts')
				{
					div.innerHTML += '<a href="' + link.href + '">' + link.innerHTML + '</a>';
				}
				else if(cols[i].className == 'perms')
				{
					div.innerHTML += '<a href="' + link.href + '">Permissions</a>';
				}
			}
			else
			{
				if(cols[i].className == 'size')
				{
					size = '';
				}
				else if(cols[i].className == 'date')
				{
					date = '';
				}
			}
		}
	}

	div.innerHTML += size + date;

	if(!div.innerHTML)
	{
		div.innerHTML += '<a href="#" onclick="return false;">(none)</a>';
	}


	//div.innerHTML += "<a href=\"#\" onclick=\"closeoptsmenu(); return false\">[Close Menu]</a>";
	window.setTimeout("set_body_closeoptsmenu()", 500);
}

function set_body_closeoptsmenu()
{
	old_document_body_onclick = document.body.onclick;
	document.body.onclick = closeoptsmenu;
}

function closeoptsmenu()
{
	if(document.getElementById("theoptsmenu"))
	{
		document.body.removeChild(document.getElementById("theoptsmenu"));
		document.body.onclick = old_document_body_onclick;
		return true;
	}
}

function set_itemaction_highlights()
{
	var list = document.getElementById("filelist") ? document.getElementById("filelist") : document.getElementById("filegrid")
	if(list)
	{
		var filelist_inputs = list.getElementsByTagName("input");
		var i = 0;
		for(i = 0; i < filelist_inputs.length; i++)
		{
			if(filelist_inputs[i].className.indexOf('itemaction') != -1)
			{
				filelist_inputs[i].onchange = setbghighlight;
				filelist_inputs[i].onclick = setbghighlight; // IE is garbage.
			}
		}
	}
}

function setbghighlight()
{
	var p = this.parentNode.parentNode;
	if(this.checked)
	{
		p.style.background = '#5cae64';
		p.onmouseover = '';
		p.onmouseout = '';
	}
	else
	{
		if(document.getElementById("filelist"))
		{
			p.onmouseover = setbg;
			unsettext(p);
			if(p.className.indexOf('odd') != -1)
			{
				p.style.background = '#e6e6e6';
				p.onmouseout = unsetbgodd;
			}
			else
			{
				p.style.background = '#efefef';
				p.onmouseout = unsetbgeven;
			}
		}
		else // filegrid.
		{
			p.style.background = '';
		}
	}
}

function set_row_mouseovers()
{
	if(document.getElementById("filelist"))
	{
		var filelist_rows = document.getElementById("filelist").getElementsByTagName("tr");
		for(i = 0; i < filelist_rows.length; i++)
		{
			var r = filelist_rows[i];

			     if(r.className.indexOf('even') != -1)	{ r.onmouseover = setbg; r.onmouseout  = unsetbgeven;	}
			else if(r.className.indexOf('odd') != -1)	{ r.onmouseover = setbg; r.onmouseout  = unsetbgodd;	}
		}
	}
}

function setbg()
{
	this.style.background = '#507090';


	var tds = this.getElementsByTagName("td");
	var i = 0;
	for(i = 0; i < tds.length; i++)
	{
		tds[i].style.color = 'white';
		if(tds[i].getElementsByTagName("a"))
		{
			var links = tds[i].getElementsByTagName("a");
			var j = 0;
			for(j = 0; j < links.length; j++)
			{
				links[j].style.color = 'white';
			}
		}
	}

}

function unsetbgeven()
{
	this.style.background = '#efefef';
	unsettext(this);
}

function unsetbgodd()
{
	this.style.background = '#e6e6e6';
	unsettext(this);
}

function unsettext(myself)
{
	var tds = myself.getElementsByTagName("td");
	var i = 0;
	for(i = 0; i < tds.length; i++)
	{
		tds[i].style.color = 'black';
		if(tds[i].getElementsByTagName("a"))
		{
			var links = tds[i].getElementsByTagName("a");
			var j = 0;
			for(j = 0; j < links.length; j++)
			{
				links[j].style.color = 'black';
			}
		}
	}
}

function autofill_human_test()
{
	var htfield = document.getElementById("fcht2");
	if(htfield)
	{
		htfield.value = '';
	}
}

var serial_request = false;

function set_form_serial_number()
{
	var url_to_get = '/cgi-bin/filechucker.cgi?ajax_get_serial';
	if(document.getElementById('theuploadform'))
	{
		serial_request = new_ajax_request();
		if(!serial_request)
		{
			alert('Error: could not get serial number; please reload this page.');
			return false;
		}

		serial_request.onreadystatechange = set_form_serial_number__stage2;
		serial_request.open('GET', url_to_get, true);
		serial_request.send(null);
	}
}

function set_form_serial_number__stage2()
{
	if(serial_request)
	{
		if(serial_request.readyState == 4)
		{
			if(serial_request.status == 200)
			{
				var rawdata = serial_request.responseText.match(/<data>(.+)<\/data>/);
				var new_serial = rawdata[1];

				var theform = document.getElementById('theuploadform');
				theform.action = theform.action.replace(/serial=\w+/, 'serial=' + new_serial);
			}
		}
	}
}

var humantest_request = false;
var uploadbutton_text_default = '';

function check_humanity()
{
	var url_to_get = '/cgi-bin/filechucker.cgi?ajax_do_humantest&fcht1=' + document.getElementById("fcht1").value + '&fcht2=' + document.getElementById("fcht2").value;
	if(document.getElementById('theuploadform'))
	{
		humantest_request = new_ajax_request();
		if(!humantest_request)
		{
			alert('Error: could not run human test.');
			return false;
		}

		uploadbutton_text_default = document.getElementById("uploadbutton").value;
		document.getElementById("uploadbutton").value = "Please wait";
		document.getElementById("uploadbutton").disabled = true;

		humantest_request.onreadystatechange = check_humanity__stage2;
		humantest_request.open('GET', url_to_get, true);
		humantest_request.send(null);
	}
}

function check_humanity__stage2()
{
	if(humantest_request)
	{
		if(humantest_request.readyState == 4)
		{
			if(humantest_request.status == 200)
			{
				var rawdata = humantest_request.responseText.match(/<data>(.+)<\/data>/);

				if(rawdata[1].match(/passed=true/))
					check_humanity__finish(1);
				else
					check_humanity__finish(0);
			}
		}
	}
}

function check_humanity__finish(testsuccess)
{
	document.getElementById("uploadbutton").value = uploadbutton_text_default;
	document.getElementById("uploadbutton").disabled = false;

	if(testsuccess)
		do_upload();
	else
		alert("Error: failed human test; please try again.");
}

function add_file_element()
{
	var firstfile_div = document.getElementById("firstfile");
	var newfile_div = firstfile_div.cloneNode(true);

	newfile_div.id = '';

	var newnum = document.getElementById("numfileelements").value;
	newnum++;

	if(newnum > 5)
	{
		alert("The owner of this site has set the limit to 5.");
		return;
	}

	var i = 0;
	var kids = new Array();

	var new_divs = newfile_div.getElementsByTagName("div");
	for(i = 0; i < new_divs.length; i++)
		kids.push(new_divs[i]);

	var new_inputs = newfile_div.getElementsByTagName("input");
	for(i = 0; i < new_inputs.length; i++)
		kids.push(new_inputs[i]);

	var new_selects = newfile_div.getElementsByTagName("select");
	for(i = 0; i < new_selects.length; i++)
		kids.push(new_selects[i]);

	var new_textareas = newfile_div.getElementsByTagName("textarea");
	for(i = 0; i < new_textareas.length; i++)
		kids.push(new_textareas[i]);

	var new_labels = newfile_div.getElementsByTagName("label");
	for(i = 0; i < new_labels.length; i++)
		kids.push(new_labels[i]);

	var new_spans = newfile_div.getElementsByTagName("span");
	for(i = 0; i < new_spans.length; i++)
		kids.push(new_spans[i]);

	for(i = 0; i < kids.length; i++)
	{
		if(kids[i].name == 'uploadname1')
		{
			kids[i].id = 'uploadname' + newnum;
			kids[i].name = 'uploadname' + newnum;
			kids[i].value = '';
			kids[i].className = kids[i].className.replace(/required/, '');
		}
		else if(kids[i].name == 'subdir1')
			kids[i].name = 'subdir' + newnum;
		else if(kids[i].name == 'newsubdir1')
			kids[i].name = 'newsubdir' + newnum;
		else if(kids[i].className == 'filei')
			kids[i].innerHTML = newnum;
		else if(kids[i].name && kids[i].name.match(/\w+1$/)) // for perfile formfields.
		{
			kids[i].name = kids[i].name.replace(/1$/, newnum);
			if(kids[i].id && kids[i].id.match(/\w+1$/))
			{
				kids[i].id = kids[i].id.replace(/1$/, newnum);
			}
		}
	}

	if((newnum % 2)==0)
		newfile_div.className = newfile_div.className.replace(/odd/, 'even');

	newfile_div.className = newfile_div.className.replace(/first/, ''); // the new one isn't first...
	firstfile_div.className = firstfile_div.className.replace(/last/, ''); // ...and now the first one isn't last anymore.

	document.getElementById("numfileelements").value = newnum;
	document.getElementById("numitems").value = newnum;

	firstfile_div.parentNode.appendChild(newfile_div);

	var spans = document.getElementById("filefields").getElementsByTagName("span");
	for(i = 0; i < spans.length; i++)
	{
		if(spans[i].className == 'fileitotal')
			spans[i].innerHTML = newnum;
	}

}

var mouseX = 0;
var mouseY = 0;

function getMousePosition(event)
{
	var mouseX = window.event ? window.event.clientX : event.pageX;
	var mouseY = window.event ? window.event.clientY : event.pageY;
	//document.getElementById("title").innerHTML = mouseX + ' ' + mouseY;
}

function mouse_coords_init()
{
	document.onmousemove = getMousePosition;
}

function get_random_text()
{
	var now = new Date();
	var time = (now.getTime() - now.getMilliseconds()) / 1000;
	var ms = now.getMilliseconds();

	var ua = navigator.userAgent;
	var sw = screen.width;
	var sh = screen.height;
	var rand = Math.random();

	var mime = navigator.mimeTypes;
	var mimestring = '';
	for(var i=0; i<mime.length; i++)
	{
		mimestring += mime[i].type + mime[i].description;
	}

	var unique = 'time:' + time + ', ms:' + ms + ', rand:' + rand + ', sw:' + sw + ', sh:' + sh + ', ua:' + ua + ', mouseX:' + mouseX + ', mouseY:' + mouseY;
	//unique += mimestring;
	return unique;
}

function start_juststatus()
{
	if(document.getElementById("fcjuststatus"))
	{
		var timeout = navigator.userAgent.indexOf("Safari") == -1 ? 1200 : 1200;
		var now = new Date();
		window.setTimeout("goajax('" + document.getElementById('theuploadform').action + "&action=get_progress_and_size&foo=" + now.getTime() + "')", timeout);
	}
}


//////////////////////////////////////////////////////////// Start SHA-1 code.
// SHA-1 code from: http://pajhome.org.uk/crypt/md5
//
// Configurable variables. You may need to tweak these to be compatible with
// the server-side, but the defaults work in most cases.
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
  return bin;
}
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}
//////////////////////////////////////////////////////////// End SHA-1 code.


function schedule_onload_action(newfunc)
{
	var already_scheduled = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = newfunc;
	}
	else
	{
		window.onload = function()
		{
			already_scheduled();
			newfunc();
		}
	}
}



schedule_onload_action(mouse_coords_init);
//schedule_onload_action(set_form_serial_number);
schedule_onload_action(autofill_human_test);
schedule_onload_action(set_row_mouseovers);
schedule_onload_action(set_itemaction_highlights);
schedule_onload_action(generate_new_serial_number);
schedule_onload_action(start_juststatus);





