/*----------------------FILEPROGRESS------------------------*/
function FileProgress(file, targetID) {
	this.fileProgressID = file.id;

	this.opacity = 100;
	this.height = 0;

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
        
        if(file.name.length>7)
        {
            var nachalo = file.name.substr(0,8);
            var konec = file.name.substr(file.name.length-10,file.name.length);
            file.name = nachalo+'...'+konec;
        }
		progressText.appendChild(document.createTextNode(file.name));

		var progressSize = document.createElement("span");
		progressSize.className = "progressSize";
		progressSize.innerHTML = "<span id=\"filesize"+this.fileProgressID+"\"></span>";

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);
		this.fileProgressElement.appendChild(progressSize);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.reset();
	}

	this.height = this.fileProgressWrapper.offsetHeight;
	this.setTimer(null);


}

FileProgress.prototype.setTimer = function (timer) {
	this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
	return this.fileProgressElement["FP_TIMER"] || null;
};

FileProgress.prototype.reset = function () {
	this.fileProgressElement.className = "progressContainer";

	this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;";
	this.fileProgressElement.childNodes[2].className = "progressBarStatus";
	
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = "0%";
	
	this.appear();	
};

FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";

	this.appear();	
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 10000));
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 5000));
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 0));
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

FileProgress.prototype.appear = function () {
	if (this.getTimer() !== null) {
		clearTimeout(this.getTimer());
		this.setTimer(null);
	}
	
	if (this.fileProgressWrapper.filters) {
		try {
			this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
		}
	} else {
		this.fileProgressWrapper.style.opacity = 1;
	}
		
	this.fileProgressWrapper.style.height = "";
	
	this.height = this.fileProgressWrapper.offsetHeight;
	this.opacity = 100;
	this.fileProgressWrapper.style.display = "";
	
};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		this.setTimer(setTimeout(function () {
			oSelf.disappear();
		}, rate));
	} else {
		this.fileProgressWrapper.style.display = "none";
		this.setTimer(null);
	}
};
/*----------------------FILEPROGRESS------------------------*/


















/*------------------------HANDERS JS-------------------------*/
function cancelQueue(instance) {
	document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	
}

function fileDialogStart() {
	/* I don't need to do anything here */
}
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

function fileQueueError(file, errorCode, message) {
	try {
	    if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            window.parent.QueLimitIT();            
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
            window.parent.SizeLimitIT();            
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

var totalFiles = 0;
var totalSize = 0;
var urlFiles = '';
var urlFilesTotal = 0;
var scrollHeight = 0;
function fileDialogComplete(numFilesSelected, numFilesQueued) 
{
	try 
	{
        var qFiles = parseInt(this.getStats().files_queued);
        scrollHeight = 0; 
        scrollHeight = qFiles * 23;
        if(scrollHeight > (4*23)) scrollHeight = 4*23;
        $('.scroll-pane').jScrollPane();                
        $('#SWFUpload_0').css({'top':(scrollHeight+swfTop)+'px'});
        $('#totalfilesize').val(0);
        if(qFiles > 0)
        {
             totalFiles+=numFilesSelected;
             for(var i = 0; i < totalFiles; i++)
             {
                    var fileSearch = this.getFile(i);
                    if(fileSearch.filestatus == SWFUpload.FILE_STATUS.QUEUED)
                    {                        
                        if(parseInt(this.getSetting('file_size_limit')) > (fileSearch.size / 1024))
                        {
                            totalSize = parseInt($('#totalfilesize').val());
                            totalSize+= fileSearch.size;
                            var itemSize = Math.round(fileSearch.size / 1024);
                            if(itemSize <= 999) $('#filesize'+fileSearch.id).html(itemSize + "Kb") ;
                            if(itemSize >  999 && itemSize < 999999) $('#filesize'+fileSearch.id).html((Math.round(itemSize / 1024 * 100) / 100) + "Mb") ;
                            if(itemSize >  999999) $('#filesize'+fileSearch.id).html((Math.round(itemSize / 1024 / 1024 * 100) / 100) + "Gb") ;
                            var buttonTextVal = ((this.getSetting('file_size_limit') / 1024) - (totalSize / 1024 / 1024)).toFixed(2);
                            if((buttonTextVal / 1024) > this.getSetting('file_size_limit')) buttonTextVal = (this.getSetting('file_size_limit') / 1024);
                            this.setButtonText("<p align=\"right\" class=\"righttext\">(Free: " + buttonTextVal + " Mb)</p>");
                            $('#totalfilesize').val(totalSize);
                        }
                        else
                        {
                            this.fileQueueError(this.getFile(i),-110,'File is too big');
                            this.cancelUpload(fileSearch.id);
                        }

                        for(var k = 0; k < totalFiles; k++)
                        {
                            var fileCompare = this.getFile(k);
                            if(fileSearch.name === fileCompare.name && fileSearch.id !== fileCompare.id && fileCompare.filestatus === SWFUpload.FILE_STATUS.QUEUED)
                            {
                                this.cancelUpload(fileSearch.id);
                                
                                urlFiles = '';
                                urlFilesTotal = 0;
                                for(var k = 0; k < totalFiles; k++)
                                {
                                    var fileUrl = this.getFile(k);
                                    if(fileUrl.filestatus == SWFUpload.FILE_STATUS.QUEUED)
                                    {
                                        urlFiles+='&file'+urlFilesTotal+'='+encodeURIComponent(fileUrl.name);
                                        urlFilesTotal++;
                                    }
                                }
                                
                                break;
                            }
                        }
                    }
              }
              
              urlFiles = '';
              urlFilesTotal = 0;
              for(var k = 0; k < totalFiles; k++)
              {
                    var fileUrl = this.getFile(k);
                    if(fileUrl.filestatus == SWFUpload.FILE_STATUS.QUEUED)
                    {
                        urlFiles+='&file'+urlFilesTotal+'='+encodeURIComponent(fileUrl.name);
                        urlFilesTotal++;
                    }
              }

         }
   	}
	catch (ex)  
	{        
		this.debug(ex);
	}
}

function uploadStart(file) {
	try {
          var progress = new FileProgress(file, this.customSettings.progressTarget);
		  progress.setStatus("Uploading...");
		  progress.toggleCancel(true, this);
	}
	catch (ex) {
	}
	
	return true;
}

var totalLoaded = 0, totalFilesLoaded = 0, totalSpeed = 1, leftTime = 0, mailSend = 0;
function uploadProgress(file, bytesLoaded, bytesTotal) 
{
    try 
    {
        var percentLoaded = Math.ceil(((totalLoaded + bytesLoaded) / totalSize) * 100);
        $('.loaderMiddleend').css({'background-position':'0px '+( (92 - percentLoaded * 1.08) * -1 )+'px'});
        $('.loaderText').html(percentLoaded+'%');

        if(bytesLoaded == bytesTotal) { totalLoaded+= bytesTotal; totalFilesLoaded++ }

		if(file.averageSpeed > 0)
        {
            totalSpeed = parseInt(file.averageSpeed);
            leftTime = Math.ceil((((totalSize - (totalLoaded + bytesLoaded)) / totalSpeed) * 30));
            if(leftTime < 0) leftTime = 0;
            if(leftTime < 60) $('.loaderTime').html('Осталось примерно <br/>' + leftTime + ' сек.');
            if(leftTime > 60 && leftTime < 3600) { leftTime = Math.ceil(leftTime / 60); $('.loaderTime').html('Осталось примерно <br/>' + leftTime + ' мин.'); }
            if(leftTime > 3600) { leftTime = Math.ceil(leftTime / 3600); $('.loaderTime').html('Осталось примерно <br/>' + leftTime + ' час.'); }
        }

        if(percentLoaded == 100 && mailSend == 0)
        {
            mailSend = 1;
            $('#major_cancel').html('Загрузить еще');
            $('.loaderMiddleend').css({'background-position':'0px 20px'});
            $('.loading-text').html('Идет создание архива...');
            var url = 'template/mail.php?totalFiles='+urlFilesTotal+urlFiles;
            var tomail   = encodeURIComponent($('.receiveEmail').val());
            var frommail = encodeURIComponent($('.authorEmail').val());
            var comment  = encodeURIComponent($('.fileComments').val());
            if(comment == 'Комментарий (не обязательно)')comment = '';
            var password = encodeURIComponent($('.passw1').val());
            url+='&tomail='+tomail+'&frommail='+frommail+'&comment='+comment+'&password='+password+'&key='+global_key;
            setTimeout(function(){
                SendGetAjax(url,function(response){
                    if(parseInt(response)==0)
                        $('.loading-text').html('Все готово!<br/>Ссылка на скачивание отправлена Вам и получателю.<br/>Файлы хранятся 3 дня.');
                    else
                        $('.loading-text').html('Неудачно!<br/>Произошла внутреняя ошибка сервиса!<br/>Попробуйте еще раз.');
                });                            
            },1000);
        }

        var progress = new FileProgress(file, this.customSettings.progressTarget);
	} 
    catch (ex) 
    {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try 
    {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try 
    {
		if (this.getStats().files_queued === 0) 
        {
			//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
		} 
        else 
        {
            this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

function uploadError(file, errorCode, message) {
	try 
    {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) 
        {
		  case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
    			progress.setStatus("Upload Error: " + message);
    			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
    			progress.setStatus("Configuration Error");
    			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
    			progress.setStatus("Upload Failed.");
    			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
    			progress.setStatus("Server (IO) Error");
    			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
    			progress.setStatus("Security Error");
    			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
    			progress.setStatus("Upload limit exceeded.");
    			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
    			progress.setStatus("File not found.");
    			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
    			progress.setStatus("Failed Validation.  Upload skipped.");
    			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
    			break;
    		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
    			if(this.getStats().files_queued === 0) 
                {
    				//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
    			}
    			progress.setStatus("Cancelled");
    			progress.setCancelled();
    			break;
    		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
    			progress.setStatus("Stopped");
    			break;
    		default:
    			progress.setStatus("Unhandled Error: " + error_code);
    			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
    			break;
  		}
	} catch (ex) {
        this.debug(ex);
    }
}
/*------------------------HANDERS JS-------------------------*/
