$(function() {
function check_filetype()
	{
		value = $('#ulfile').val();
		file_parts = value.split('.');
		
		extension = file_parts[file_parts.length - 1].toLowerCase();
		
		vals = "jpg|png|jpeg|pjepg|gif|tiff|bmp|zip|rar|txt|swf|fla|7z|tar|gz|mp3|wav|m4a|aac|doc|docx|xls|rtf|ppt|bsd";
		allowed_parts = vals.split('|');
		
		for (i = 0; i < allowed_parts.length; i++)
		{
			if ( extension == allowed_parts[i] )
			{
				return true;
			}
		}
		
		return false;
	}
function readablizeBytes(bytes) {
    var s = [' Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes)/Math.log(1024));
    return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+""+s[e];
}

	$('#uploadform').submit(function(){
		if ( check_filetype() )
		{
			$(".error").hide();
			beginUpload();
			return true;
		}
		else
		{
			$("#errorC").slideDown('fast').animate({opacity:"1.0"}, 3000).slideUp('fast');
			$(".error").fadeIn(1000).animate({opacity:"1.0"}, 1500).fadeOut(1000);
			if(extension){
				$(".error").html("<em><strong>." + extension + "</strong></em> is an incorrect file type");
			} else {
				$(".error").html("Please choose a file to upload");
			}
			return false;
		}
	});


	$('#ulfile').change(function(){
		if (check_filetype() )
		{
			$(".error").hide();
			return true;
		} else {
			$("#errorC").slideDown('fast').animate({opacity:"1.0"}, 3000).slideUp('fast');
			$(".error").fadeIn(1000).animate({opacity:"1.0"}, 1500).fadeOut(1000);
			$(".error").html("<em><strong>." + extension + "</strong></em> is an incorrect file type");
			return false;
		}
	});


 
var progress_key = $('#progress_key').val();
function beginUpload() {
				$("#uploadprogress").show();
				$(".hide").hide();
				var i = setInterval(function() { 
					$.getJSON("../uploadprogress.php?id=" + progress_key, function(data) {

						var percentage = Math.floor(100 * parseInt(data.bytes_uploaded) / parseInt(data.bytes_total));
						$("#percent").text(percentage + "%");
						$("#upSize").html("<strong>" + readablizeBytes(data.bytes_uploaded) + "</strong>/<strong>" + readablizeBytes(data.bytes_total) + "</strong> at <strong>" + readablizeBytes(data.speed_average) +"/s</strong>");
						$("#upEst").html("<strong>" + data.est_sec + "</strong> seconds left");
						$("#cancel").html("<a href=\"/\">Cancel</a>");

					});
				}, 650);

				return true;
			}
		   });
