/**
 * Flash Upload plugin
 *
 * Copyright (c) 2010 boygiandi! (upanh.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

(function($){
	$.fn.FUpload = function(options) {
	   
		var defaults = {
			maxFile: 	10,
			fileType: 		"*.mp3; *.MP3;",
			fileDesc: 		"Music ( *.MP3 )",
			maxSize: 		{ 'jpg': 5242880 },
			flashName:		"myFlashMovie",
			flashUrl:		"flash/upload.swf",
			Uploadto:		"/flashupload/upload.php",
			width:			100,
			height:			30,
			debug :			false,
			btUpload: 		null,
			btDelFile:		null,
			InsertFile:		null,
			RevResponse:	null,
			updateProgress:	null,
			UploadComplete: null,
			delFile:		null,
			preUpload:		null,
			error:			null,
			InsertFileComplete : null,
			variable:		""
		};
		
		var _WAITING = 0;
		var _UPLOADED = 1;
		var _DELETED = 2;
		var _UPLOADING = 3;
		var _UPLOAD_ERR = 4;

		var uploading=false;
		var ttLoaded=0;
		var current_file=-1;
		var ttSize = 0;
		
		var options = $.extend(defaults, options);
		var fupload = this;
		var flashObj;
		
		/* listfile = Array ( name, size ) */
		var listfile = new Array();
		
		this.insertfile = function(data) {
			var overweight=0;
			file = data.split("<!>");
			if ( data.length>3 )
				for ( i=0; i<file.length; i++ ) {
					if ( listfile.length>=options.maxFile ) {
						options.error('MANY_FILES');
						break;
					}
					f = file[i].split('<;>');

					var ext = fupload.fileExt(f[0]);
					var x = listfile.length;
					listfile[x] = new Array();
					listfile[x]['name'] = f[0];
					listfile[x]['size'] = f[1];
					
					if ( listfile[x]['size'] > options.maxSize[ext] ) {
						listfile[x]['status'] = _DELETED;
						overweight++;
						//return false;
					}
					else {
						listfile[x]['status'] = _WAITING;
						ttSize += parseInt(f[1]);
					}
					options.InsertFile(x, listfile[x]);
				}
			if ( overweight>0 ) options.error('TOO_BIG', overweight);
			//fupload.hideupbutton(1);
			options.InsertFileComplete( fupload.getTotal() );
		}
		
		this.attach = function(array) {
			var val = "";
			for (idx in array) {
				val += idx+"="+array[idx]+"&";
			}
			options.variable = val;
			return val;
		}
		
		this.upload = function()
		{
			uploading=true;
			options.btUpload.unbind('click');
			current_file = -1;
			for ( i=0; i<listfile.length; i++ ) {
				// Disable del button
				
				if (listfile[i]['status'] == _WAITING) {
					current_file = i;
					break;
				}
			}
			//console.log(current_file);
			if ( current_file>=0 ) {
				if ( typeof flashObj.hideupbutton=='function' )
					flashObj.upload(current_file, options.Uploadto+'&'+options.variable);
				else {
					shell = "<invoke name=\"upload\" returntype=\"javascript\"><arguments><number>"+current_file+"</number><string>"+options.Uploadto+'&'+options.variable+"</string></arguments></invoke>";
					this.callFlashFunction(shell);
				}
				listfile[current_file]['status'] = _UPLOADING;
			} else options.UploadComplete(-1);
		}
		
		this.getFlashMovieObject = function(movieName)
		{
		  if (window.document[movieName]) 
		  {
			return window.document[movieName];
		  }
		  if (navigator.appName.indexOf("Microsoft Internet")==-1)
		  {
			if (document.embeds && document.embeds[movieName])
			  return document.embeds[movieName]; 
		  }
		  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
		  {
			return document.getElementById(movieName);
		  }
		}
		
		this.callFlashFunction = function(shell) {
			var flashMovie = this.getFlashMovieObject(options.flashName);
			flashMovie.CallFunction(shell);
		}

		this.updateprogress = function(bytesLoaded)
		{
			// Set progress
			var filepercent = Math.floor(bytesLoaded*100/listfile[current_file]['size']);
			var ttpercent = Math.floor((ttLoaded+bytesLoaded)*100/ttSize);
			options.updateProgress(current_file, filepercent, ttpercent);
		}
		
		this.changetext = function(str) {
			if ( typeof flashObj.changetext=='function' )
				flashObj.changetext(str);
			else {
				shell = "<invoke name=\"changetext\" returntype=\"javascript\"><arguments><string>"+str+"</string></arguments></invoke>";
				this.callFlashFunction(shell);
			}
		}
		
		this.UploadComplete = function(m)
		{
			options.UploadComplete(current_file);
			uploading = false;
			if ( current_file>=0 )
				fupload.upload();
		}
		
		this.RevResponse = function( data ) {
			options.RevResponse(data);
		}
		
		this.delfile = function(id)
		{
			if ( !uploading ) {
				listfile[id]['status'] = _DELETED;
				options.delFile(id);
			}
		}

		this.delallfile = function()
		{
			for ( var i=0; i<listfile.length; i++ )
				this.delfile(i);
		}

		this.error = function(type, error)
		{
			if (parseInt(error) != 505) {
				this.UploadComplete(1);
			}
			else {
				
			}
			alert(type+': '+error);
		}

		this.browsefile = function()
		{
			flashObj.browsefile();
		}
		
		this.getTotal = function() {
			var i, c=0;
			for ( i=0; i<listfile.length; i++ )
				if ( listfile[i]['status'] == _WAITING ) c++;
			
			return { totalFile:c, totalSize:ttSize };
		}
		
		this.hideupbutton = function(i)
		{
			flashObj.width = "1px";
			flashObj.height = "1px";
			if ( typeof flashObj.hideupbutton=='function' )
				flashObj.hideupbutton(i);
			else {
				shell = "<invoke name=\"hideupbutton\" returntype=\"javascript\"><arguments><number>"+i+"</number></arguments></invoke>";
				this.callFlashFunction(shell);
			}
		}
		
		this.status = function() {
			if ( current_file+1==listfile.length ) return _UPLOADED;
			if ( uploading ) return _UPLOADING;
			else return _WAITING;
		}
		
		this.log = function(str) {
			$("#log").append(str+"<br>");
		}
		
		this.fileExt = function(file) {
			if ( file.indexOf(".")==-1 ) return "";
			t = file.split(".");
			return t[t.length-1].toLowerCase();
		}
		
		this.reload = function() {
			$obj = $(this);
			flashObj = $obj.find("#"+options.flashName).get(0);
		}
		
		this.moveTo = function(el) {
			$obj.appendTo(el);
			fupload.reload();
		}
		
		return this.each(function() {
			$obj = $(this);
			$obj.flash(
				{ 	src: 	options.flashUrl,
					id: 	options.flashName,
					width: 	options.width,
					height: options.height,
					wmode: 	"transparent",
					flashvars: { 
								debug: options.debug,
								fileDesc: options.fileDesc, 
								fileType: options.fileType
					}
				},
				{ wmode: "transparent", version: 6 }
			);
			
			flashObj = $obj.find("#"+options.flashName).get(0);
			options.btDelFile.livequery('click', function() {
				fupload.delfile( $(this).attr("rel") ); 
				return false;
			});
			
			options.btUpload.click(function() {
				fupload.reload();
				if ( options.preUpload($obj) ) {
					fupload.hideupbutton(1);
					fupload.upload();
				}
			});
			
			window.onunload = function() {
				$obj.empty();
			}
			
			return fupload;
		});
	};
})(jQuery);
