//--------------------------------------------------------------------------------------
function uploadFinish() {

	//modify Feb 10 2008
	//if this is uploaded through flash, we will estimate the time to finish upload
	if(!noFlash)
	{
		var now=new Date();
		var totalSeconds=TimeToSeconds(now)-TimeToSeconds(startUploadSubmit);
		document.sendIt.UploadTime.value=totalSeconds;


	}

	doSubmit();

}
//--------------------------------------------------------------------------------------

// Initialize upload form
// create SWFupload object
function fInitUploadForm(){
	if (!$("sendIt") || !$("SWFUploadTarget"))
	{
	    fDisplayForm();
	}

	if ($("SWFUploadTarget")) {

	    swfUploadTimeout = setTimeout(fSwfUploadTimeout, swfLoadTimeout);

	    if(flashDetected = fDetectRequiredFlashVersion())
	    {
		    // init SWF upload object ONLY if there is an element on the page that can host it.
		     swfu = new SWFUpload({
			    // Backend Settings, relative to flash, must better to put it in absolute path http://...
			    //upload_url : "{StorageServer}/swfUpload.php?tmp_sid={tmp_sid}",
			    upload_url : upload_url,

			    // Flash Settings, relative to template file
			    flash_url : flash_url,

			    // File Upload Settings
			    file_size_limit : 1024*18000,
			    file_types : "*.*",
			    file_types_description : "All Files",
			    file_upload_limit : "0",
			    file_queue_limit : "100",

			    // Event Handler Settings (all my handlers are in the Handler.js file)
			    file_dialog_start_handler : fileDialogStart,
			    file_queued_handler : fileQueued,
			    file_queue_error_handler : fileQueueError,
			    file_dialog_complete_handler : fileDialogComplete,
			    upload_start_handler : uploadStart,
			    upload_progress_handler : uploadProgress,
			    upload_error_handler : uploadError,
			    upload_success_handler : uploadSuccess,
			    upload_complete_handler : uploadComplete,
			    swfupload_loaded_handler : swfUploadLoaded,
                assume_success_timeout : 30,

			    // Debug Settings
			    debug: true
		    });
		}
		else // Flash 9.0 or higher was not detected
		{
		    fIncorrectFlashVersionDetected();
		}
	}
	// submit form button
	if ($("send6") && $("sendIt"))
	{
		$("send6").addEvent("click", function(e){
			new Event(e).stop();
			//---------------------------------------------
			//thao
			if( !validateUpload()){
				return false;
			}
			//---------------------------------------------
			if(!noFlash) {

				startUploadSubmit=new Date();
				swfu.startUpload();

			} else {
				doSubmit();
			}
			//this.form.submit();
		});
	}
	//
	//
	function swfUploadLoaded() {
		noFlash=false;

        clearTimeout(swfUploadTimeout);
        clearTimeout(swfShowInitProgressTimeout);	// don't have to show the progress bar now... we are loaded.

		//------------------------------------------------------------------
		if($('fileBrowseList'))
			$('fileBrowseList').style.display='none';
		if($('flashBrowse'))
			$('flashBrowse').style.display='block';

		fDisplayForm();

		//--------------------------------------------------------------------
		action=document.sendIt.action.toString();
		action=action.replace("uploader.pl","uploadFinished.php");
		document.sendIt.action=action;
		//--------------------------------------------------------------------
		// create button
		$("SWFUploadTarget").empty();
		var uploadBtn = new Element("input").setProperties({
			type: "image",
			src: "images/btn_browse_n.gif"
		}).injectInside("SWFUploadTarget");
		uploadBtn.addEvents({
			"mouseover" : function(e) {
				new Event(e).stop();
				$(this).src = "images/btn_browse_o.gif";
			},
			"mouseout" : function(e) {
				new Event(e).stop();
				$(this).src = "images/btn_browse_n.gif";
			},
			"click" : function(e){
				new Event(e).stop();
				swfu.selectFiles();
			}
		});
	}
}

function uploadProgressStatus(status,totalSize,totalFilesUploaded,uploadedSize,Speed)
{
    var oBar = $("fileProgressBar1");

	if(status=="Finished")
	{
		oBar.setStyle("width", 100*4+"px");
		$('percentComleted').setHTML("Upload Completed");

		$('estimateTimeRemaining').setHTML("Waiting for confirmation.");
	}else{
		percent=Math.ceil((uploadedSize / totalSize) * 100)

		/*html="Uploading " +  totalFilesUploaded +" of files"
		html= html+ "<br>"+ formatFilesize(uploadedSize) +" of "+ formatFilesize(totalSize) +" ("+percent+"%) uploaded with speed " + Speed + "KB/s";*/

		$('percentComleted').setText(percent+"% completed("+ formatFilesize(uploadedSize)+" of "+ formatFilesize(totalSize) +") ");

		oBar.setStyle("width", percent*4+"px");
		if(Speed>0)
		{
			timeRemaining=Math.floor((totalSize-uploadedSize)/(Speed*1024));
			timeRemaining="<br>Estimated Time Remaining: "+formatTimeFromSeconds(timeRemaining);
		}else
		{
			timeRemaining="Calculation Time Remaining";
		}
		var filesUpload="Uploading file "+ totalFilesUploaded+" file(s) of " + getTotalFilesUploaded();

		$('estimateTimeRemaining').setHTML(filesUpload+"<br>Speed: "+ Speed + "KB/s"+timeRemaining);

		setTimeout(requestUploadStatus,2000);
	}
	//$('uploadStatusBar').setHTML(html);

}
//--------------------------------------------------------------------------------------
function formatTimeFromSeconds(nSeconds)
{
	hours = Math.floor(nSeconds / ( 60 * 60));
	nSeconds -= hours * ( 60 * 60);

	mins = Math.floor(nSeconds / ( 60));
	nSeconds -= mins * (  60);
	if(hours<10)
		hours="0"+hours;
	if(mins<10)
		mins="0"+mins;
	if(nSeconds<10)
		nSeconds="0"+nSeconds;
	return hours+":"+mins+":"+nSeconds;
}
//--------------------------------------------------------------------------------------
function requestUploadStatus()
{
	url="/getUploadStatusIframe.php?server="+StorageServerUploader+"&tmp_sid="+tmp_sid;
	if(fromEmail!=undefined && fromEmail!="")
	{
		url=url+"&from="+fromEmail;
	}
	if(toEmail!=undefined && toEmail!="")
	{
		url=url+"&to="+toEmail;
	}
	//url=StorageServerUploader+"/getUploadStatus.php?tmp_sid={tmp_sid}";
	top.iframe_upload_status.location.href=url;
	/*var ajax = new Ajax(url, {
		method: 'get',
		evalResponse:true,
		onComplete: function(transport)
		{



		},
		onCancel: function() {

		}
		});
	ajax.request();*/

}
//--------------------------------------------------------------------------------------
function getTotalFilesUploaded()
{
	var frm=document.sendIt;
	total=0;
	for(i=1;i<=6;i++)
	{

		if (eval("frm.file"+i+".value")!="")
		{
			total=total+1;
		}
	}
	return total;
}
//--------------------------------------------------------------------------------------