//Constants
var uploadpath = 'http://u3.stagevu.com';
var webcgipath = uploadpath + "/uploader/cgi-bin/upload.pl";
var siteuploadpath = uploadpath + "/uploader/siteupload.php";
var userprogresspath = uploadpath + "/uploader/getsize.php";
var siteuploadprogpath = uploadpath + "/uploader/getsiteuploadsize.php";
var stoppath = uploadpath + "/uploader/cancel.php";
var checkevery = 2000; //ms between checks
var updateevery = 0.25; // seconds between bar updates

function reloaddone(data, status) {
	if (data.success === true) {
		window.notice(data.message, '#090');
		location.reload(true);
	} else window.notice(data.message, '#900');
	window.loading();
}

function logout() {
	window.loading();
	$.post(window.uploadpath + "/ajax/logout.php", {}, reloaddone, "json");
}

function changecolour(theme) {
	window.loading();
	$.get(window.uploadpath + "/ajax/changetheme.php", {colour: theme}, reloaddone, "json");
}

function changelayout(theme) {
	window.loading();
	$.get(window.uploadpath + "/ajax/changetheme.php", {layout: theme}, reloaddone, "json");
}

//Variables
function uploadinfo(type) {
	if (type == 'site') {
		this.type = 'site';
		this.prefix = 's';
	} else {
		this.type = 'user';
		this.prefix = 'u';
	}
	this.uploading = false;
	this.id = 0;
	this.donesize = 0, this.totalsize = 0, this.pixelsperinterval = 0, this.bps = 0;
	this.prevdone = 0;
	this.elapsed = 0, this.etr = -1, this.stoptimer = false;
	this.pixels = 0;
	this.fields = 1;
}

var user = new uploadinfo('user');
var site = new uploadinfo('site');

//Generic methods
function randstr(len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i = 0; i < len; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum, rnum + 1);
	}
	return randomstring;
}

function bytetokb(b) { //to KILOBYTE, not kilobit; rounded
	return Math.round(b / 1024);
}

function secstostr(secs) {
	var time = new Array(3);
	var i;
	time[0] = Math.floor(secs / 3600);
	time[1] = Math.floor((secs - (time[0] * 3600)) / 60);
	time[2] = Math.floor(secs - ((time[0] * 3600) + (time[1] * 60)));
	for (i = 0; i < 3; i++)
		if (time[i] < 10) time[i] = "0" + time[i];
	
	return (time[0] + ':' + time[1] + ':' + time[2]);
}

//Methods

//debug
function dump(arr,level) {
	var dumped_text = "";
	if (!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for (var j=0;j<level+1;j++) level_padding += "    ";

	if (typeof(arr) == 'object') { //Array/Hashes/Objects
		for (var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 

//Public:
function uploadsubmit(info) {
	if ($("#" + info.prefix + "uploadbutton").attr("disabled") != "disabled" && !info.uploading
) {
		$("#" + info.prefix + "uploaderrors").html('');
		if (info.type == 'site') {
			if (info.id == 0) {
				$("#suploaderrors").html("<span style='color: #f84;'>Code error! Please contact us with the problem</span>");
				return false;
			}
		}
		info.uploading = true;
		
		barsmoother(info);
		startuploadstatus(info);
		setTimeout('$(".' + info.prefix + 'upload").attr("disabled", "disabled")', 25); //Disables the form
		return true;
	} else return false;
}

//Private
function startuploadstatus(info) {
	$("#" + info.prefix + "uploadprogress").removeClass("nodisplay"); //Makes the upload progress section show
	$("#" + info.prefix + "uploadbar").width(0);
	displayprogress(info);
}

function displayprogress(info) {
	if (!info.uploading) return false;
	
	function update(data) {
		if (data.donesize != 0) info.donesize = data.donesize;
		else info.donesize = 0;
		if (data.totalsize != 0) info.totalsize = data.totalsize;
		else info.totalsize = 0;
	}
	
	function updateuser(data) {
		if (typeof data.received != 'undefined') info.donesize = data.received;
		else info.donesize = 0;
		if (typeof data.size != 'undefined') info.totalsize = data.size;
		else info.totalsize = 0;
	}
	
	if (info.type == 'site') $.getJSON(siteuploadprogpath + "?id=" + info.id, false, update);
	else {
		/*$.ajax({
			type: 'GET',
			url: userprogresspath,
			beforeSend: function(req) { req.setRequestHeader("X-Progress-Id", info.id); return true; },
			dataType: 'json',
			success: updateuser
		});*/
		$.getJSON(userprogresspath + "?id=" + info.id, false, update);
	}
	
	//Following calculates the number of info.pixels done
	var floatpercent = info.donesize / info.totalsize;
	if (info.totalsize == 0 || isNaN(floatpercent)) floatpercent = 0.00001;
	var intpercent = Math.round(floatpercent * 1000) / 10; //Percentage to one decimal
	info.bps = (info.donesize - info.prevdone) / (checkevery / 1000);
	
	info.prevdone = info.donesize;
	
	info.pixels = floatpercent * $("#" + info.prefix + "uploadwrap").width();
	info.etr = ((1 - floatpercent) / floatpercent) * info.elapsed;
	
	//Stats displays
	$("#" + info.prefix + "percent").text(intpercent + "%");
	$("#" + info.prefix + "current").text(bytetokb(info.donesize) + " KB");
	$("#" + info.prefix + "total").text(bytetokb(info.totalsize) + " KB");
	$("#" + info.prefix + "time").text(secstostr(info.elapsed));
	$("#" + info.prefix + "remain").text(secstostr(info.etr));
	$("#" + info.prefix + "speed").text(bytetokb(info.bps) + " KB/s");
	
	//Used for bar and stats smoothing
	info.pixelsperinterval = ((info.bps / info.totalsize) / (1 / updateevery)) * $("#" + info.prefix + "uploadwrap").width();
	//Reasoning: Bytes per second / info.totalsize = percent per second
	//Percent per second / interval = percents per interval
	//Percents per interval * info.pixels = info.pixels / interval
	
	$("#" + info.prefix + "uploadbar").width(info.pixels + "px");

	setTimeout(function() { displayprogress(info); }, checkevery);
}


function barsmoother(info) {
	if (!info.uploading) return false;

	//Simply increases the bar by "pixelsperinterval" px every interval, and calls itself again
	if (info.pixels < $("#" + info.prefix + "uploadwrap").width() - 10) info.pixels += info.pixelsperinterval;
	if (isNaN(info.pixels)) info.pixels = 0;
	$("#" + info.prefix + "uploadbar").width(info.pixels + "px");
	
	//Timer functions
	info.elapsed += updateevery;
	$("#" + info.prefix + "time").text(secstostr(info.elapsed));
	if (info.etr >= updateevery) info.etr -= updateevery;
	if (info.etr >= 0) $("#" + info.prefix + "remain").text(secstostr(info.etr));
	setTimeout(function() { barsmoother(info); }, (updateevery * 1000));
}

function terminate(info) {
	function done(data, status) {
		loading();
		if (data.success === true) {
			notice(data.message, '#090');
			stopupload(info, '', false);
			$('#suploadprogress').addClass('nodisplay');
		} else notice(data.message, '#900');
		loading();
	}

	if (info.type == 'site') {
		$.post(
			uploadpath + '/uploader/stopsiteupload.php',
			{ uploadid: info.id, killkey: killkey },
			done,
			'json'
		);
	} else stopupload(info, '', false);
}

function stopupload(info, done, success) {
	info.uploading = false;
	if (success) {
		$("#" + info.prefix + "uploadbar").width($("#" + info.prefix + "uploadwrap").width()); //Makes the upload section "Done"
		$("#" + info.prefix + "percent").text("100%");
		$("#" + info.prefix + "current").text(bytetokb(info.totalsize) + " KB");
		$("#" + info.prefix + "total").text(bytetokb(info.totalsize) + " KB");
		$("#" + info.prefix + "time").text(secstostr(info.elapsed));
		$("#" + info.prefix + "remain").text("00:00:00");
		$("#" + info.prefix + "speed").text(bytetokb(info.donesize / info.elapsed) + " KB/s");
		// Success or failure message
		$("#" + info.prefix + "uploaderrors").html(done);
		// Disables the add new file input
		$("#" + info.prefix + "addinput").click("return false;");
		$("#" + info.prefix + "addinput").css("display", "none");
	} else {
		$("#" + info.prefix + "uploadbar").width("0"); //Resets everything
		$("#" + info.prefix + "percent").text("0%");
		$("#" + info.prefix + "current").text("0 KB");
		$("#" + info.prefix + "total").text("0 KB");
		$("#" + info.prefix + "time").text("00:00:00");
		$("#" + info.prefix + "remain").text("Unknown");
		$("#" + info.prefix + "speed").text("Unknown KB/s");
		// Success or failure message
		$("#" + info.prefix + "uploaderrors").html(done);
		// Disables the add new file input
		$("." + info.prefix + "upload").removeAttr("disabled");
		info.uploading = false;
		info.donesize = 0, info.totalsize = 0, info.pixelsperds = 0, info.bps = 0;
		info.prevdone = 0;
		info.elapsed = 0, info.etr = -1, info.stoptimer = false;
		info.pixels = 0;
		info.fields = 1;
	}
}

function addinput(info) {
	if (info.uploading) return false;
	if (info.fields < 10) {
		info.fields++;
		
		if (info.type == 'site') var insertafter = '<tr id="supload' + info.fields + '" class="uploadrow"><td><label for="username" class="yellow floatright">URL #' + info.fields + '</label></td><td><input name="url' + info.fields + '" id="url' + info.fields + '" type="text" class="text supload" /></td><td></td></tr>';
		else var insertafter = '<tr id="uupload' + info.fields + '" class="uploadrow"><td><label for="file" for="upfile' + info.fields + '" class="yellow floatright">File #' + info.fields + '</label></td><td><input type="file" name="upfile' + info.fields + '" id="upfile1" class="uupload" value="" /></td><td></td></tr>';
		$("#" + info.prefix + "upload" + (info.fields - 1)).after(insertafter);
		return true;
	} else $("#" + info.prefix + "uploaderrors").html('<span style="color: #f84;"><strong>Try</strong> to keep the number of files below 10. (Tip: open a new window)</span>');
}

$(document).ready(function() {
	$("input").removeAttr("disabled");
	$('#suploadform').ajaxForm({
		beforeSubmit: function() { return uploadsubmit(site); },
		dataType: 'json',
		success: function(data) { return stopupload(site, data.text, data.success); }
	});
	$(window).unload(function () {
		if (site.uploading) terminate(site);
	});
});

