interval = null;
allow_extensions = /(swf|flv|mpg|mpeg|mp4|mp2|avi|mov|wmv|ico|xml|css|psd|jpg|jpeg|gif|bmp|png|tiff|vob|wma|mp3|mid|midi|mp4|m4a|3g2|3gp|wav|ape|flac|ogg|rar|zip|tgz|gz|bz2|7z|exe|tar|ppt|pdf|rtf|doc|r[0-9]+|xls|txt)$/i;

function start_upload() {
	if(!CheckFile()) return false;
	else {
		uuid = "";
		time = 0;
		for (i = 0; i < 32; i++) {
			uuid += Math.floor(Math.random() * 16).toString(16);
		}       	
		var string = document.getElementById('upload').elements['fileupload'].value;
		var num_of_last_slash = string.lastIndexOf("\\");
		if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }
		var file_name = string.slice(num_of_last_slash + 1, string.length);

		document.getElementById('showAlertMessage').innerHTML = "Идет загрузка файла<br>" + file_name;
		document.getElementById("upload").action="/new_upload_file?X-Progress-ID=" + uuid;
		document.getElementById("progress_bar_container").style.display="block";
		document.getElementById("upload_stats_container").style.display="block";
		document.getElementById("upload_form_container").style.display="none";

		interval = window.setInterval(
			function () {
				time = time + 1;
				fetch(uuid, time);
			},
			1000
		);
	}
}

function fetch(uuid, time) {
	req = new XMLHttpRequest();
	req.open("GET", "/upload_process", 1);
	req.setRequestHeader("X-Progress-ID", uuid);
	req.onreadystatechange = function () {
		if (req.readyState == 4) {
			if (req.status == 200) {
				/* poor-man JSON parser */
				var upload = eval(req.responseText);

				//document.getElementById('tp').innerHTML = upload.state;
				document.getElementById('current_position').innerHTML = Math.round ( upload.received / 1024 );
				document.getElementById('total_kbytes').innerHTML = Math.round ( upload.size / 1024 );


				if(time > 0) { 
					var speed_kb = Math.round ( upload.received / time / 1024 ); 
					document.getElementById('est_speed').innerHTML = speed_kb; 
                        
					var el_sec = (time % 60);
					var el_min = (((time - el_sec) % 3600) / 60);
					var el_hours = ((((time - el_sec) - (el_min * 60)) % 86400) / 3600);
                        
					if(el_sec < 10){ el_sec = "0" + el_sec; }
					if(el_min < 10){ el_min = "0" + el_min; }
					if(el_hours < 10){ el_hours = "0" + el_hours; }
                        
					document.getElementById('elapsed_time').innerHTML = el_hours + ':' + el_min + ':' +el_sec; 
				}
				if(speed_kb > 0) {
					var est_time= Math.round (( upload.size - upload.received ) / speed_kb / 1024);
                        
					var est_sec = (est_time % 60);
					var est_min = (((est_time - est_sec) % 3600) / 60);
					var est_hours = ((((est_time - est_sec) - (est_min * 60)) % 86400) / 3600);
                        
					if(est_sec < 10){ est_sec = "0" + est_sec; }
					if(est_min < 10){ est_min = "0" + est_min; }
					if(est_hours < 10){ est_hours = "0" + est_hours; }
                        
					document.getElementById('est_time_left').innerHTML = est_hours + ':' + est_min + ':' +est_sec; 
				}
				/* change the width if the inner progress-bar */
				if (upload.state == 'done' || upload.state == 'uploading') {
					bar = document.getElementById('progressbar');
					w = 400 * upload.received / upload.size;
					bar.style.width = w + 'px';
				}
				/* we are done, stop the interval */
				if (upload.state == 'done') {
					window.clearTimeout(interval);
				}
			}
		}
	}
	req.send(null);
}
function CheckFile() {
	if(document.getElementById('upload').elements['fileupload'].value != "") {
		if(!document.getElementById('upload').elements['fileupload'].value.match(allow_extensions)){
			var string = document.getElementById('upload').elements['fileupload'].value;
			var num_of_last_slash = string.lastIndexOf("\\");

			if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }

			var file_name = string.slice(num_of_last_slash + 1, string.length);
			var file_extension = file_name.slice(file_name.indexOf(".")).toLowerCase();

			alert('Загрузка файлов данного формата "' + file_extension + '" не разрешена.');
			return false;
		}
	} else {
		alert("Выберите файл для загрузки");
		return false;
	}
	return true;
}
//	var file_extension = substring(file_name.value.lastIndexOf('.') + 1, file_name.value.length).toLowerCase();
//	alert(substring(file_name.value.lastIndexOf('.') + 1, file_name.value.length).toLowerCase());

/*
	var file_name = UberUpload.getFileName(JQ(this).val());

	if(!UberUpload.check_file_name_regex.test(file_name)){
		UberUpload.highlightFileLabel(JQ(this).attr('id')+"_label", UberUpload.file_label_highlight_on);
		alert(UberUpload.check_file_name_error_message);
		found_error = true;
	}

	if(!file_extension.match(allow_extensions)){
		UberUpload.highlightFileLabel(JQ(this).attr('id')+"_label", UberUpload.file_label_highlight_on);
		alert('Ошибка! Загрузка файлов с расширением "' + file_extension + '" не разрешена.');
		found_error = true;
	}
	if(file_extension.match(UberUpload.disallow_extensions)){
		UberUpload.highlightFileLabel(JQ(this).attr('id')+"_label", UberUpload.file_label_highlight_on);
		alert('Ошибка! Загрузка файлов с расширением "' + file_extension + '" не разрешена.');
		found_error = true;
	}

	return found_error;
*/

