

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

function create_ajax_object()
{
	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) {}
		}
	}

	if(!myRequest)
		alert('Error: could not create AJAX object.');

	return myRequest;
}


function goajax_fc(page)
{
	theRequest = create_ajax_object();
	if(theRequest)
	{
		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>/);
				printdebug('');

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

				for(i = 0; i < update.length; i++)
				{
					var vars = update[i].split('=');
					if(vars[0])
					{
						fcvar[vars[0]] = vars[1];
						printdebug('fcvar[' + vars[0] + ']=' + fcvar[vars[0]]);
					}
				}

				if(fcvar['total_size'] != 0)
					total_upload_size = fcvar['total_size'];

				if(fcvar['size_error'])
				{
					var go = "http://procopyonline.com/estimate.html?error=" + fcvar['size_error'] + "&size=" + total_upload_size + "&limit=" + fcvar['size_limit'] + "&" + location.search.replace(/^\?/, '');
					return enc_js_redirect(go);
				}

				var completed_upload_size	= fcvar['progress'];
				var elapsedtime			= fcvar['elapsed_time'];
				var numfinishedfiles		= fcvar['finished_file_count'];
				var numtotalfiles		= fcvar['total_file_count'];
				var postprocessingdone		= fcvar['ppd_status'];

				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))
				{
					hide_element('progBarPlaceholder');
					show_element('progBarContainer');

					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)) { 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))
					{
						if(document.getElementById('showprogtable'))
						{
							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)
					{
						hide_element('theMeter');
						show_element('uploadCompleteMsg');

						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.';

						if(document.getElementById('showprogtable'))
						{
							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';
						}

						
					}
				}

				schedule_progressbar_update(700);
			}
			else
			{
				if(document.getElementById('fcdebug'))
					alert('Error: got a not-OK status code...');
				// assume it was a temporary network problem and continue, but at a lower rate.
				schedule_progressbar_update(5000);
			}
		}
	}
}


function startupload()
{
	if(check_if_onload_happened() && check_for_required_fields() && filenames_are_legal() && verify_that_new_passwords_match())
	{
		

		if(document.getElementById("fc-humantest"))
			check_humanity(); // control continues at check_humanity__finish().

		do_upload(); // called unconditionally; all checks within this block must either return false or use num_upload_checks_still_pending if they want to halt the upload.
	}
	else { return false; }
}

function check_if_onload_happened()
{
	if(document.getElementById("onload_happened"))
	{
		if(document.getElementById("onload_happened").value == 1)
		{
			return true;
		}
		else
		{
			alert("Our onload actions did not run.  You must remove any 'onload' attribute from your page's <body> tag.");
			return false;
		}
	}
}

function update_onload_status()
{
	if(document.getElementById("onload_happened"))
		document.getElementById("onload_happened").value = 1;
}

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()
{
	if(num_upload_checks_still_pending > 0)
		return;

	var file_present = document.getElementById('uploadname1') && 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;

		show_element('progBarPlaceholder');

		if(document.getElementById('popupstatus'))
			document.getElementById('progBarPlaceholder').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.';

		printdebug('get_progress_and_size() AJAX return values:');

		if(document.getElementById('fcclearpage'))
		{
			hide_element('theuploadform');
		}

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

function schedule_progressbar_update(timeout)
{
	var now = new Date();
	window.setTimeout("goajax_fc('" + document.getElementById('theuploadform').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';
	}
	else
	{
		window.clearInterval(stopinc);
		stopinc = '';
		document.getElementById('progBarDone').style.width = newwidth + 'px';
	}
}

function hide_element(elname)
{
	var theel = document.getElementById(elname);
	theel.style.position = 'absolute';
	theel.style.left = '-8000';
	theel.style.overflow = 'hidden';
	theel.style.height = '0';
	//theel.style.display = 'none'; // display:none on the upload form will cause Safari to fail to upload the file(s).
}

function show_element(elname)
{
	var theel = document.getElementById(elname);
	theel.style.position = 'relative';
	theel.style.left = '0';
	theel.style.overflow = 'visible'; // or 'auto' ?
	theel.style.height = 'auto';
	//theel.style.display = 'block';
}

function printdebug(msg)
{
	if(document.getElementById('fcdebug'))
		document.getElementById('fcdebug').innerHTML += '<br />' + msg + '<br />';
}

function enc_js_redirect(gotoURL)
{
	if(document.getElementById('popupstatus'))
	{
		window.opener.location.href = gotoURL;
		window.close();
		return null;
	}
	else
	{
		location.href = gotoURL;
	}
}

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;
		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;

	for(i = 0; i < onlyinputs.length; i++)
		inputs[inputs.length] = onlyinputs[i];

	for(i = 0; i < selects.length; i++)
		inputs[inputs.length] = selects[i];

	for(i = 0; i < textareas.length; i++)
		inputs[inputs.length] = textareas[i];

	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].type == 'checkbox'   &&   !inputs[i].checked)
		{
			items_missing = 1;
		}
		else 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.length > 0   &&   !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 filenames_are_legal()
{
	var inputs = document.getElementById('theuploadform').getElementsByTagName('input');
	for(i = 0; i < inputs.length; i++)
	{
		if(inputs[i].type == 'file' && !(inputs[i].value == '' || inputs[i].value == undefined))
		{
			var filename__array = inputs[i].value.match(/([^\/\\]+)$/);
			var filename = filename__array[1];
			var this_files_extension__array = filename.match(/.*(\..+)$/);
			var this_files_extension = this_files_extension__array ? this_files_extension__array[1] : '';
			var illegal = 0;

			var only_allow_these_file_extensions = "";
			if(only_allow_these_file_extensions)
			{
				if(!this_files_extension)
					illegal = 1;

				var extension_is_in_allowed_list = 0;
				var allowed_extensions = only_allow_these_file_extensions.split(" ");
				for(j = 0; j < allowed_extensions.length; j++)
				{
					if(this_files_extension == allowed_extensions[j])
						extension_is_in_allowed_list = 1;
				}

				if(!extension_is_in_allowed_list)
					illegal = 1;
			}

			var disallow_these_file_extensions = ".exe .php .php3 .php4 .php5 .phtml .cgi .pl .sh .py .htaccess .htpasswd";
			if(disallow_these_file_extensions)
			{
				var extension_is_in_disallowed_list = 0;
				var disallowed_extensions = disallow_these_file_extensions.split(" ");
				for(j = 0; j < disallowed_extensions.length; j++)
				{
					if(this_files_extension == disallowed_extensions[j])
						extension_is_in_disallowed_list = 1;
				}

				if(extension_is_in_disallowed_list)
					illegal = 1;
			}

			var disallow_these_strings_within_filenames = "\.php \.asp \.cgi \.pl$ \.plx";
			if(disallow_these_strings_within_filenames)
			{
				var name_contains_disallowed_string = 0;
				var disallowed_strings = disallow_these_strings_within_filenames.split(" ");
				for(j = 0; j < disallowed_strings.length; j++)
				{
					var re = new RegExp(disallowed_strings[j], "i");
					if(filename.match(re))
						name_contains_disallowed_string = 1;
				}

				if(name_contains_disallowed_string)
					illegal = 1;
			}

			if(("yes" == "no")   &&   !this_files_extension)
			{
				illegal = 1;
			}

			if(!filename.match(/[0-9A-Za-z]/))
				illegal = 1;

			if(illegal)
			{
				var message = "Filename or file type not allowed: %%filename%%";
				message = message.replace(/%%filename%%/, filename);
				alert(message);
				return false;
			}
		}
	}
	return true;
}

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;
}

// 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 = "/estimate.html?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 = "/estimate.html?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 == 'cp')
				{
					div.innerHTML += '<a href="' + link.href + '">Copy</a>';
				}
				else if(cols[i].className == 'mv')
				{
					div.innerHTML += '<a href="' + link.href + '">Move/Rename</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 set_up_human_test()
{
	var htimg = document.getElementById("fcht0");
	var htfield1 = document.getElementById("fcht1");
	var htfield2 = document.getElementById("fcht2");
	if(htfield1 && htfield2)
	{
		htimg.src = htimg.src.replace(/\w+\.jpg/, '21fba522302cb745afceeeb76305b79d.jpg');

		htfield1.value = '21fba522302cb745afceeeb76305b79d';

		if(document.getElementById("ht_is_invisible"))
			htfield2.value = '992883';
	}
}

var uploadbutton_text_default = '';

function check_humanity()
{
	num_upload_checks_still_pending++;

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

	var url_to_get = '/cgi-bin/estimate.cgi?ajax_do_humantest&fcht1=' + document.getElementById("fcht1").value + '&fcht2=' + document.getElementById("fcht2").value;
	do_ajax_request(url_to_get, check_humanity__finish);
}

function check_humanity__finish(output_from_request)
{
	num_upload_checks_still_pending--;

	document.getElementById("uploadbutton").value = uploadbutton_text_default;
	document.getElementById("uploadbutton").disabled = false;

	if(output_from_request.match(/passed=true/))
		do_upload();
	else
		alert("Error: failed human test; please try again.");
}

function do_ajax_request(url_to_get, callback_function)
{
	var ajax_request = create_ajax_object();
	if(ajax_request)
	{
		ajax_request.onreadystatechange = function()
		{
			if(ajax_request)
			{
				if(ajax_request.readyState == 4)
				{
					if(ajax_request.status == 200)
					{
						var rawdata = ajax_request.responseText.match(/<data>(.+)<\/data>/);
						callback_function(rawdata[1]);
					}
				}
			}
		}
		ajax_request.open('GET', url_to_get, true);
		ajax_request.send(null);
	}
}

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 > 6)
	{
		alert("The owner of this site has set the limit to 6.");
		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' && !document.getElementById("only_one_subdir_dropdown"))
			kids[i].name = 'subdir' + newnum;
		else if(kids[i].name == 'subdir1' && document.getElementById("only_one_subdir_dropdown"))
		{
			// if only_one_subdir_dropdown is set, then delete the subdir nodes for the other files in the upload.
			var entire_subdir_section = kids[i].parentNode;
			var subdir_text = kids[i].parentNode.nextSibling;
			if(entire_subdir_section.parentNode)
				entire_subdir_section.parentNode.removeChild(entire_subdir_section);
			if(subdir_text)
				subdir_text.parentNode.removeChild(subdir_text);
		}
		else if(kids[i].name == 'newsubdir1' && !document.getElementById("only_one_new_subdir"))
		{
			kids[i].name = 'newsubdir' + newnum;
			kids[i].value = '';
		}
		else if(kids[i].name == 'newsubdir1' && document.getElementById("only_one_new_subdir"))
		{
			// if only_one_new_subdir is set, then delete the new-subdir nodes for the other files in the upload.
			var entire_newsubdir_section = kids[i].parentNode;
			var newsubdir_text = kids[i].parentNode.nextSibling;
			entire_newsubdir_section.parentNode.removeChild(entire_newsubdir_section);
			newsubdir_text.parentNode.removeChild(newsubdir_text);
		}
		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);
			kids[i].value = '';
			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;

	if(document.getElementById("subdir_dropdown_visible") || document.getElementById("new_subdir_field_visible"))
	{
		var subdirnote = document.createElement("p");
		if(document.getElementById("only_one_subdir_dropdown") && document.getElementById("only_one_new_subdir"))
			subdirnote.innerHTML = "(will use directory settings from first file)";
		else if(document.getElementById("only_one_subdir_dropdown"))
			subdirnote.innerHTML = "(will use directory from first file)";
		else if(document.getElementById("only_one_new_subdir"))
			subdirnote.innerHTML = "(will use new subdir name from first file)";
		newfile_div.appendChild(subdirnote);
	}

	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;
		schedule_progressbar_update(timeout);
	}
}


function verify_that_new_passwords_match()
{
	var pw1 = '';
	var pw2 = '';

	var inputs = document.getElementsByTagName("input");
	for(var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf('encnewpw') != -1)
		{
			if(pw1)
				pw2 = inputs[i].value;
			else
				pw1 = inputs[i].value;
		}
	}

	if(pw1 != pw2)
	{
		alert("Passwords do not match.");
		return false;
	}
	else
	{
		return true;
	}
}

function undisable_upload_button()
{
	// necessary so if a user browses back to the upload page,
	// they can actually click the upload button, which we had
	// disabled during the previous upload.
	var btn = document.getElementById('uploadbutton');
	if(btn)
		btn.disabled = false;
}

//////////////////////////////////////////////////////////// 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_up_human_test);
schedule_onload_action(set_row_mouseovers);
schedule_onload_action(set_itemaction_highlights);
schedule_onload_action(generate_new_serial_number);
schedule_onload_action(undisable_upload_button);
schedule_onload_action(start_juststatus);
schedule_onload_action(update_onload_status);




