var time_elapsed = 0;
var timer = null;
var pgtimer = null;
var uppgid = "";
var start_time = 0;
var fr = new friendly;

toggle_upload = function()
{
	$("#uploadbox").addClass("hide");
	$("#uploading").removeClass("hide");
//	counter_timer();
	start_time = (new Date()).getTime();
	poll();
	$("#uploadform").submit();
};

counter_timer = function()
{
	time_elapsed++;
	timer = setTimeout("counter_timer()", 1000);
};

stop_timer = function()
{
//	clearTimeout(timer);
//	timer = null;
	clearTimeout(pgtimer);
	pgtimer = null;
};

zidoupload_init = function()
{
	uppgid = $("#pgid").val();
	time_elapsed = 0;
	$("#submit_upload").click(submit_upload);
};

submit_upload = function()
{
	if (upload_valid())
	{
		toggle_upload();
		return true;
	}
	return false;
};

poll = function()
{
//	$.getJSON("json-pgrss.php", {pgid:uppgid}, function(js){progress_poll(js);});
	var data = $.ajax({url:"json-pgrss.php", data:"pgid=" + uppgid + "&r=" + (new Date()).getTime(), type:"GET", async:false}).responseText;
	eval("var d = " + data + ";");
	progress_poll(d);
};

update_stat = function(uploadinfo)
{
	$("#upload_file_name").text(uploadinfo[0]);
	$("#upload_file_size").text(fr.size(uploadinfo[1]));
	$("#upload_speed").text(uploadinfo[3].toFixed(2) + "Kbps (อัพโหลดแล้ว " + fr.size(uploadinfo[2]) + ")");
	$("#upload_time_left").text(fr.time(uploadinfo[4]) + " (โดยประมาณ)");

	v = (255 - parseInt(percent * 255 / 100)).toString(16);
	bgcolor = "#" + (v.length==1?"0":"") + v + "ff00";
	percent = uploadinfo[5];

	$("#progress_bar").css("width", 2 * parseInt(percent)).css("background-color", bgcolor);
};

progress_poll = function(js)
{
	var upstatus = "null";
	var done = false;
	if (js != null)
	{
		time_elapsed = parseInt(((new Date()).getTime() - start_time)/1000);
		total = js[0];
		current = js[1];
		filename = js[5];
		percent = parseFloat(current) * 100/ parseFloat(total);
		percentInt = parseInt(percent);
		bps = parseInt(current / time_elapsed);
		estimateTime = parseInt((total - current) / bps);
		kbps = bps / 1024;
		done = (total == current);
		update_stat([filename, total, current, kbps, estimateTime, percent]);
	}
	if (!done)
	{
		pgtimer = setTimeout("poll()", 1000);
	}
};

$(window).unload = function()
{
	stop_timer();
};

$(zidoupload_init);

