YAHOO.namespace("YAHOO.SWFUpload");

/** YAHOO.SWFUpload.Status
	* Class
	*/
YAHOO.SWFUpload.Status = function()
{
	this.bReady = false;
	this.bBusy = false;
	this.nProgress = 0;
	this.sMessage = "Ready...";
	this.aFileList = new Array();
	
	YUISWFstatus = YAHOO.util.Dom.getElementsByClassName("YUISWFstatus", "div", YAHOO.SWFUpload.YUISWFdiv);
	this.YUISWFstatus = YUISWFstatus[0];
	
	/** isFileQueued
		* Checks if file already queued or not. If not add the name to list.
		* @return bool
		*/
	this.isFileQueued = function(sFilename)
	{
		var bIsUnique = true;
		for (i = 0; i < this.aFileList.length; i++)
		{
			if (this.aFileList[i] == sFilename)
			{
				bIsUnique = false;
				break;
			}
		}
		
		if (bIsUnique == true)
		{
			this.aFileList.push(sFilename);
			return false;
		}
		else return true;
	}
	
	this.removeFileFromFilelist = function(sFilename)
	{
		for (i = 0; i < this.aFileList.length; i++)
		{
			if (this.aFileList[i] == sFilename)
				this.aFileList.splice(i, 1);
		}
	}
	
	this.setStatus = function(sMsg)	
	{
		this.sMessage = sMsg;
		if (this.YUISWFstatus != null)
			this.YUISWFstatus.innerHTML = sMsg;
	}
	
	this.addStatus = function(sMsg)	
	{
		this.sMessage = this.sMessage + " " + sMsg;
		if (this.YUISWFstatus != null)
			this.YUISWFstatus.innerHTML = this.sMessage;
	}

	/** updateProgress
		* updates overall progress (for all files)
		*/
	this.updateProgress = function()
	{
		var stats = YAHOO.SWFUpload.swfUploadObject.getStats();
		if (stats.files_queued == 0)
			this.nProgress = 100;
		else this.nProgress = (stats.successful_uploads * 100) / (stats.files_queued + stats.successful_uploads);
	}
	
	this.setFileStatus = function(file, nProgress)
	{
		var oYUISWFfilestatus_active = YAHOO.util.Dom.getElementsByClassName("YUISWFfilestatus", "div", "YUISWFfile" + file.index)[0];
		oYUISWFfilestatus_active.className = "YUISWFfilestatus";
		
		switch (file.filestatus) 
		{
			case SWFUpload.FILE_STATUS.QUEUED: 
				oYUISWFfilestatus_active.innerHTML = "na čakanju";
				YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "queue"); 
			break;
			case SWFUpload.FILE_STATUS.IN_PROGRESS: 
				oYUISWFfilestatus_active.innerHTML = "Prenos (" + Math.ceil(nProgress * 100) + "%)";
				YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "inprogress"); 
			break;
			case SWFUpload.FILE_STATUS.ERROR: 
				oYUISWFfilestatus_active.innerHTML = "Napaka";
				YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "error"); 
			break;
			case SWFUpload.FILE_STATUS.COMPLETE: 
				oYUISWFfilestatus_active.innerHTML = "Končano"; 
				YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "complete"); 
				YAHOO.util.Dom.addClass(YAHOO.util.Dom.getElementsByClassName("YUISWFcancel", "div", "YUISWFfile" + file.index)[0], "hide");
			break;
			case SWFUpload.FILE_STATUS.CANCELLED: 
				oYUISWFfilestatus_active.innerHTML = "Prekinjeno"; 
				YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "canceled");
			break;
		}
	}
	
	this.setFileStatusError = function(file)
	{
		var oYUISWFfilestatus_active = YAHOO.util.Dom.getElementsByClassName("YUISWFfilestatus", "div", "YUISWFfile" + file.index)[0];
		oYUISWFfilestatus_active.className = "YUISWFfilestatus";
		oYUISWFfilestatus_active.innerHTML = "Napaka";
		YAHOO.util.Dom.addClass(oYUISWFfilestatus_active, "error");
		this.setStatus("Prenos datoteke " + file.name + " ni bil uspešen!");
		this.removeFileFromFilelist(file.name);
	}
	
	this.removeFileFromQueue = function(file)
	{
		var oYUISWFqueue = YAHOO.util.Dom.getElementsByClassName("YUISWFqueue", "div", YAHOO.SWFUpload.YUISWFdiv)[0];
	  oYUISWFqueue.removeChild(YAHOO.util.Dom.get("YUISWFfile" + file.index));
	  
	  this.removeFileFromFilelist(file.name);
	}
}

/** YAHOO.SWFUpload.init
	* @var string sYUISWFdiv
	*/
YAHOO.SWFUpload.init = function(ev, args) 
{ 
	if (YAHOO.SWFUpload.swfUploadObject != null)
		return false;
		
	if (args.YUISWFdiv == null || args.sessid == null)
	{
		alert("mandatory arguments missing.");
		return false;
	}
	
	YAHOO.SWFUpload.YUISWFdiv = YAHOO.util.Dom.get(args.YUISWFdiv);
	if (YAHOO.SWFUpload.YUISWFdiv == null)
	{
		alert("DIV with name " + args.YUISWFdiv + " not found.");
		return false;
	}
	
	//crate wrapping container
	var oYUISWFuploader = document.createElement("div");
	oYUISWFuploader.setAttribute("class", "YUISWFuploader");
	
	//create and append the FLASH button holder span element
	var oYUISWFspanStartButton = document.createElement("div");
	oYUISWFspanStartButton.setAttribute("id", "uploadStartButton");
	oYUISWFuploader.appendChild(oYUISWFspanStartButton);
	
	//create and append YUISWFstatus container
	var oYUISWFstatus = document.createElement("div");
	oYUISWFstatus.setAttribute("class", "YUISWFstatus");
	oYUISWFuploader.appendChild(oYUISWFstatus);
	
	//create and append YUISWFqueue container
	var oYUISWFqueue = document.createElement("div");
	oYUISWFqueue.setAttribute("class", "YUISWFqueue hide");
	oYUISWFuploader.appendChild(oYUISWFqueue);
	
	//append the whole wrapping container to YUISWFdiv
	YAHOO.SWFUpload.YUISWFdiv.appendChild(oYUISWFuploader);
	
	
	
	var settings_object = { 
		upload_url : "upload.php", 
		post_params: {"PHPSESSID": args.sessid},
		flash_url : "SWFUpload/Flash/swfupload.swf", 
		file_size_limit : "5 MB", 
		file_types : "*.doc;*.pdf",
		file_types_description : "Word & Adobe Acrobat datoteke",
		file_upload_limit : 3,
		debug: false,
		
		button_placeholder_id : "uploadStartButton",
		button_width: "130",
		button_height: "29",
		button_text_left_padding: 12,
		button_text_top_padding: 4,
		button_text: '<span class="buttonFont">Dodaj datoteke...</span>',
		button_text_style: ".buttonFont { font-family: Corbel, \"Trebuchet MS\", Arial; color: #000 }",
		button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES, 
		button_cursor : SWFUpload.CURSOR.HAND,
		
		// The event handler functions are defined in handlers.js
		swfupload_loaded_handler: YAHOO.SWFUpload.Events.swfUploadLoaded,
		file_dialog_start_handler: YAHOO.SWFUpload.Events.fileDialogStart,
		file_dialog_complete_handler: YAHOO.SWFUpload.Events.fileDialogComplete,
		upload_start_handler: YAHOO.SWFUpload.Events.uploadStart,
		upload_progress_handler: YAHOO.SWFUpload.Events.uploadProgress,
		upload_success_handler: YAHOO.SWFUpload.Events.uploadSuccess,
		upload_complete_handler: YAHOO.SWFUpload.Events.uploadComplete,
		upload_error_handler: YAHOO.SWFUpload.Events.uploadError,
		file_queued_handler: YAHOO.SWFUpload.Events.fileQueued, 
		file_queue_error_handler: YAHOO.SWFUpload.Events.fileQueueError
	};
	
	
	YAHOO.SWFUpload.swfUploadObject = new SWFUpload(settings_object);
	YAHOO.SWFUpload.StatusInstance = new YAHOO.SWFUpload.Status();
};

YAHOO.SWFUpload.Events = 
{
	swfUploadLoaded: function()
	{
		//The swfUploadLoaded event is fired by flashReady. It is settable. 
		//swfUploadLoaded is called to let you know that it is safe to call SWFUpload methods.
		try	
		{
			YAHOO.SWFUpload.StatusInstance.bReady = true;
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	}, 
	
	fileDialogStart: function()
	{
		//fileDialogStart is fired after selectFile for selectFiles is called. 
		//This event is fired immediately before the File Selection Dialog window is displayed. 
		//However, the event may not execute until after the Dialog window is closed.
	}, 
	
	fileQueued: function(file)
	{
		//The fileQueued event is fired for each file that is queued after the File Selection Dialog window is closed.
		
		
		try 
		{
			if (YAHOO.SWFUpload.StatusInstance.isFileQueued(file.name))
			{
				YAHOO.SWFUpload.StatusInstance.setStatus("Datoteka " + file.name + " že obstaja v čakalni vrsti.");
				YAHOO.SWFUpload.swfUploadObject.cancelUpload(file.id);
				return false;
			}
			else
			{
				var YUISWFqueuediv = YAHOO.util.Dom.getElementsByClassName("YUISWFqueue", "div", YAHOO.SWFUpload.YUISWFdiv);
				YUISWFqueuediv = YUISWFqueuediv[0];
				YAHOO.util.Dom.removeClass(YUISWFqueuediv, "hide");
				
				//create file div
				var oYUISWFfile = document.createElement("div");
				oYUISWFfile.setAttribute("class", "YUISWFfile");
				oYUISWFfile.setAttribute("id", "YUISWFfile" + file.index);
				
				//create file cancel div
				var oYUISWFcancel = document.createElement("div");
				oYUISWFcancel.setAttribute("class", "YUISWFcancel");
				oYUISWFcancel.appendChild(document.createTextNode("prekini"));
				YAHOO.util.Event.addListener(oYUISWFcancel, "click", YAHOO.SWFUpload.Events.cancel, {fileid: file.id});
				//create filename div
				var oYUISWFfilename = document.createElement("div");
				oYUISWFfilename.setAttribute("class", "YUISWFfilename");
				oYUISWFfilename.appendChild(document.createTextNode(file.name));
				//create filesize div
				var oYUISWFfilesize = document.createElement("div");
				oYUISWFfilesize.setAttribute("class", "YUISWFfilesize");
				oYUISWFfilesize.appendChild(document.createTextNode("(" + Math.ceil(file.size / 1024) + "kb)"));
				//create filestatus div
				var oYUISWFfilestatus = document.createElement("div");
				oYUISWFfilestatus.setAttribute("class", "YUISWFfilestatus");
				
				//append description divs to file div
				oYUISWFfile.appendChild(oYUISWFcancel);	
				oYUISWFfile.appendChild(oYUISWFfilename);	
				oYUISWFfile.appendChild(oYUISWFfilesize);	
				oYUISWFfile.appendChild(oYUISWFfilestatus);
				
				YUISWFqueuediv.appendChild(oYUISWFfile);
				YAHOO.SWFUpload.StatusInstance.setFileStatus(file);
				
				return true;
			}
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	fileDialogComplete: function(numFilesSelected, numFilesQueued, numFilesQueuedTotal)
	{
		//The fileDialogComplete event fires after the File Selection Dialog window has been closed and all the selected files have been processed.
		//The 'number of files queued' argument indicates the number of files that were queued from the dialog selection 
		//(as opposed to the number of files in the queue).
		//If you want file uploading to begin automatically this is a good place to call 'this.startUpload()'
		
		try
		{
			if (numFilesSelected > 0)
				YAHOO.SWFUpload.swfUploadObject.startUpload();
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	uploadStart: function(file)
	{
		//uploadStart is called immediately before the file is uploaded. 
		//This event provides an opportunity to perform any last minute validation, 
		//add post params or do any other work before the file is uploaded.
		//The upload can be cancelled by returning 'false' from uploadStart. 
		//If you return 'true' or do not return any value then the upload proceeds. 
		//Returning 'false' will cause an uploadError event to fired.
		
		try
		{
			YAHOO.SWFUpload.StatusInstance.bBusy = true;
			YAHOO.SWFUpload.StatusInstance.setStatus("Prenos...");
			
			return true;
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	uploadProgress: function(file, bytesLoaded, bytesTotal)
	{
		//The uploadProgress event is fired periodically by the Flash Control. This event is useful for providing UI updates on the page.
		//Note: The Linux Flash Player fires a single uploadProgress event after the entire file has been uploaded. 
		//This is a bug in the Linux Flash Player that we cannot work around.
		try 
		{
			YAHOO.SWFUpload.StatusInstance.setStatus("Prenos datoteke: " + file.name);
			YAHOO.SWFUpload.StatusInstance.setFileStatus(file, bytesLoaded / bytesTotal);
		} 
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	uploadSuccess: function(file, serverData, receivedResponse)
	{
		//uploadSuccess is fired when the entire upload has been transmitted and the server returns a HTTP 200 status code. 
		//Any data outputted by the server is available in the server data parameter.
		//Due to some bugs in the Flash Player the server response may not be acknowledged and no uploadSuccess event is fired by Flash. 
		//In this case the assume_success_timeout setting is checked to see if enough time has passed to fire uploadSuccess anyway. 
		//In this case the received response parameter will be false.
		
		
	try
		{
			/* possible error codes (returned with HTML 200 status code)
			FILES_ERROR_MSG
			NOT_UPLOADED
			NO_NAME
			MAX_FILESIZE_EXCEEDED
			ZERO_BYTE_SIZE
			INVALID_EXTENSION
			UNABLE_TO_SAVE
			*/
			
			//What if the file upload is successful but you then still reject the file 
			//(e.g., uploadSuccess is fired but you use serverData it indicate an error? 
			//You'll also have to remove the file from fileInfo, 
			//or not if you don't want to allow the file again)	
		
			if (serverData.length < 3)
			{
				YAHOO.SWFUpload.StatusInstance.setStatus("Prenos datoteke " + file.name + " uspešno končan.");
				YAHOO.SWFUpload.StatusInstance.setFileStatus(file);
			}
			else
			{
				switch (serverData)
				{
					case 'FILES_ERROR_MSG':
					case 'NOT_UPLOADED':
					case 'NO_NAME':
					case 'MAX_FILESIZE_EXCEEDED':
					case 'ZERO_BYTE_SIZE':
					case 'INVALID_EXTENSION':
					case 'UNABLE_TO_SAVE':
					case 'FILE_EXISTS':
					default:
					{
						YAHOO.SWFUpload.StatusInstance.setFileStatusError(file);
						this.debug("Backend error - server responded with: "  + serverData);
					}
					break;
				}
			}
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	uploadComplete: function(file)
	{
		//uploadComplete is always fired at the end of an upload cycle (after uploadError or uploadSuccess). 
		//At this point the upload is complete and another upload can be started.
		//If you want the next upload to start automatically this is a good place to call this.uploadStart(). 
		//Use caution when calling uploadStart inside the uploadComplete event if you also have code that cancels all the uploads in a queue.
		
		try
		{
			YAHOO.SWFUpload.StatusInstance.updateProgress();
			YAHOO.SWFUpload.StatusInstance.bBusy = false;
			
			if (YAHOO.SWFUpload.swfUploadObject.getStats().files_queued > 0)
				YAHOO.SWFUpload.swfUploadObject.startUpload();
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	},
	
	uploadError: function(file, errorCode, message)
	{
		//The uploadError event is fired any time an upload is interrupted or does not complete successfully. 
		//The error code parameter indicates the type of error that occurred. 
		//The error code parameter specifies a constant in SWFUpload.UPLOAD_ERROR.
		//Stopping, Cancelling or returning 'false' from uploadStart will cause uploadError to fire. 
		//Upload error will not fire for files that are cancelled but still waiting in the queue.
		
		
		try
		{
			switch (errorCode) 
			{
				case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				{
					YAHOO.SWFUpload.StatusInstance.setFileStatus(file);
					YAHOO.SWFUpload.StatusInstance.setStatus(file.name + " je večja od " + YAHOO.SWFUpload.swfUploadObject.settings.file_size_limit + ".");
				}
				break;
				
				case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
				{
					YAHOO.SWFUpload.StatusInstance.setFileStatus(file);
					YAHOO.SWFUpload.StatusInstance.setStatus("Napaka pri prenosu datoteke " + file.name);
				}
				break;
				
				case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				{
					YAHOO.SWFUpload.StatusInstance.addStatus("Prenos datoteke " + file.name + " je bil prekinjen.");
				}
				break;
				
				default:
					YAHOO.SWFUpload.StatusInstance.setStatus("Unhandled Error: " + errorCode);
					break;
			}
			
			/*What if there is an error or a file is cancelled? You'll need to remove that file from the fileInfo list*/
			YAHOO.SWFUpload.StatusInstance.removeFileFromFilelist(file.name);
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	}, 
	
	fileQueueError: function(file, errorCode, message)
	{
		//The fileQueueError event is fired for each file that was not queued after the File Selection Dialog window is closed. 
		//A file may not be queued for several reasons such as, the file exceeds the file size, 
		//the file is empty or a file or queue limit has been exceeded.
		//The reason for the queue error is specified by the error code parameter. 
		//The error code corresponds to a SWFUpload.QUEUE_ERROR constant.
		try
		{
			switch (errorCode) 
			{
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					YAHOO.SWFUpload.StatusInstance.setStatus("Dovoljeno število datotek: " + YAHOO.SWFUpload.swfUploadObject.settings.file_upload_limit);
				break;
				
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					YAHOO.SWFUpload.StatusInstance.setStatus(file.name + " je večja od " + YAHOO.SWFUpload.swfUploadObject.settings.file_size_limit + ".");
				break;
				
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					YAHOO.SWFUpload.StatusInstance.setStatus(file.name + " je prazna.");
				break;
				
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					YAHOO.SWFUpload.StatusInstance.setStatus(file.name + " je neveljavna, dovoljene so samo datoteke tipa " + YAHOO.SWFUpload.swfUploadObject.settings.file_types_description + "(" + YAHOO.SWFUpload.swfUploadObject.settings.file_types + ").");
				break;
				
				default:
				{
					if (file !== null) 
					{
						YAHOO.SWFUpload.StatusInstance.setFileStatus(file);
						YAHOO.SWFUpload.StatusInstance.setStatus("Unhandled exception (" + file.name + ").");
					}
					else YAHOO.SWFUpload.StatusInstance.setStatus("Napaka!");
				}
				break;
			}
		}
		catch (ex) 
		{
			this.debug(ex);
		} 
	},
	
	cancel: function(ev, args)
	{
		//cancelUpload cancels the file specified by the file_id parameter. The file is then removed from the queue.
		//If the file_id parameter is omitted or undefined then the first file in the queue is cancelled.
		//The trigger_error_event is optional. If set to false the uploadError event is suppressed.
		
		try
		{
			var file = YAHOO.SWFUpload.swfUploadObject.getFile(args.fileid);
			if (file != null)
			{
				YAHOO.SWFUpload.swfUploadObject.cancelUpload(args.fileid);
				YAHOO.SWFUpload.StatusInstance.removeFileFromQueue(file);
			}
		}
		catch (ex) 
		{
			this.debug(ex);
		}
	}, 
}