// Author Kevin Dibble
// EXAMPLE /////////////////////////////////////////////////////////////////////////////////////////////
/*

<link href="../lib/styles/validate.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../lib/jsv2/scripts.php"></script>
<script type="text/javascript" src="../lib/jsv2/swfupload.js"></script>
<script type="text/javascript" src="../lib/jsv2/uploader.js"></script>
<? include("metaHead.inc.php"); ?></head>
<body>
<form action="../lib/showDetails.php" method="post" enctype="multipart/form-data" name="userForm" id="userForm">
	<input name="thumbnail" type="file" title="uploadfiles:upload.php:<?php echo session_id(); ?>"/>
</form>

<form action="../lib/showDetails.php" method="post" enctype="multipart/form-data" name="fileForm" id="fileForm">
 <input name="filename" type="file" title="uploadfiles/swfupload.swf;uploadfiles/upload.php:<?php echo session_id(); ?>;idtoupdate" />
</form>
</body>
</html>
*/

// NOTES:
// Use the Title field to point to the location of the PHP processing file (it must be relative from the flash file location)
var uploader = new Class({
	ani 	: null,					// Used to keep track of the progress animations
	initialize: function(obj){
		this.name = obj.name;
		this.wrapper = new Element('div',{
				'class' : 'uploaderWrapper'
		});
		this.FileBtn = new Element('div',{
				'id'	 : obj.name +'select',
				'styles' : {
							'width'  : '20px',
							'height' : '20px'
				}
			});
		this.myTmp  = new Element('div', {
				'id'	: obj.name+ "FileUploadSection",
				'class'	: "FileUploadSection",
				'html' 	: '<div class="FileUploadName" id="'+ obj.name +'FileUploadName">[Click Folder to Select File]</div>'+
						  '<div class="FileUploadProgress" id="'+ obj.name +'FileUploadProgress"></div>'
		});
		$(this.wrapper).injectBefore(obj);
		$(this.myTmp).injectInside(this.wrapper);
		$(this.FileBtn).injectInside(this.wrapper);
		this.paths			= obj.title.split(';');
		//added by Manjinder to allow to pass base url in title tag
		if(this.paths[5]){
			var swfURL = this.paths[5];
		} else{
			var swfURL = window.location.toString();
			swfURL = swfURL.substring(0,swfURL.lastIndexOf('/'));
		}
		
		var fileString = "*.jpg;*.gif;*.png;*.pdf;*.doc;*.ppt;*.flv;*.swf;*.mp3;*.wav;*.vcf;*.docx";
		if(this.paths[4]){
			fileString = this.paths[4].replace(/\|/g,';');
		}
		
		this.settings 		= {
			flash_url 		: swfURL + "/" + this.paths[0],
			upload_url		: swfURL + "/" + this.paths[1],				// Relative to the SWF file	
			post_params		: {"PHPSESSID" : this.paths[2],"filename" : this.name},
			file_post_name	: this.name,
			file_size_limit : "100 MB",
			file_types 		: fileString,
			file_types_description : "All Files",
			file_upload_limit : 100,									// Allow lots of file attempts
			file_queue_limit : 1,										// Only allow one file in the que
			debug: false,
			
			// Custom Settings
			custom_settings : {
				animation		: obj.name,
				showImage		: this.paths[3] || false,
				path_thumb		: swfURL
			},
			// Button settings
			button_image_url: swfURL + "/uploadfiles/folder.png",	
			button_width: "20",
			button_height: "20",
			button_placeholder_id: obj.name + 'select',
				
			// The event Functions
			file_queued_handler 	: this.fileQueued,
			file_queue_error_handler: this.queueError,
			file_dialog_start_handler: this.fileDialogStart,
			file_dialog_complete_handler : this.fileDialogComplete,
			upload_start_handler 	: this.uploadStart,
			upload_progress_handler : this.uploadProgress,
			upload_error_handler 	: this.uploadError,
			upload_success_handler  : this.success,
			upload_complete_handler : this.uploadFinished
			//queue_complete_handler : queueComplete					// Queue plugin event
		}
		this.swfu = new SWFUpload(this.settings);						// Create SWF Uploader object
		var uploadFunction = this.startUpload.bind(this);
		this.UploadBtn = new Element('div',{
			'id'     : obj.name + 'FileUploadBtn',
			'class'	 : 'upload',
			'events' : {
					'click' 	: uploadFunction,
					'mouseenter': function(){this.className="uploadOvr";},
					'mouseleave': function(){this.className="upload";}
			}
		});
		$(this.UploadBtn).setOpacity(0);
		$(this.UploadBtn).injectBefore($(this.myTmp));
		$(obj).destroy();												// Remove the file feild from the form
	},
	queueError: function(){
		$(this.customSettings.animation+'FileUploadName').set("html","");					// Remove the last file text 
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFinished');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadSuccess');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFailed');
		$(this.customSettings.animation+'FileUploadName').addClass('Uploading');
		this.cancelUpload();
	},
	fileDialogStart: function(){
		new Fx.Tween($(this.customSettings.animation + 'FileUploadBtn')).start('opacity',0); // Hide the upload button
		$(this.customSettings.animation+'FileUploadName').set("html","");					 // Remove the last file text 
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFinished');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadSuccess');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFailed');
		$(this.customSettings.animation+'FileUploadName').addClass('Uploading');
		this.cancelUpload();																 // Cancel the current file going up
	},
	fileDialogComplete: function(){
		var btn = this.customSettings.animation;
		new Fx.Tween($(btn + 'FileUploadBtn'),{onComplete: function(){
			if($(btn+'FileUploadName').get('html')==""){
				$(btn+'FileUploadName').set("html","<div class='error' style='border:none; padding:0px; margin:0px'>Please select only one file</div>");
				$(btn+'FileUploadBtn').fade('hide');
			}
		}}).start('opacity',1);  // Show the upload button
	},
	success: function(file,response){
		var tempAmount="";
		var amount= "" + (file.size / 1024 / 1024);					// Get the file size in MB
		if(amount.indexOf('.')!=-1){
			amount=amount.substring(0,amount.indexOf('.')+1+parseInt(3));
		}
		for(var i=0;i<amount.length;i++){
			if(!isNaN(amount.charAt(i))||amount.charAt(i)=="."){
				tempAmount+=""+amount.charAt(i);
			}
		}
		if(this.customSettings.showImage){
			var location = this.customSettings.showImage;
			//var swfURL = window.location.toString();
			var swfURL = this.customSettings.path_thumb;
			//swfURL = swfURL.substring(0,swfURL.lastIndexOf('/'));
			//alert(swfURL);
			var simpleAjax= new Request.HTML({
				url: swfURL+'/uploadfiles/showThumb.php',
				onSuccess: function(response,elements,html,scripts){
					if($(location)){
						$(location).set("html",html);
					}
				}
			}).send('filename=' + this.customSettings.animation);
		}
		$(this.customSettings.animation+'FileUploadName').removeClass('Uploading');
		$(this.customSettings.animation+'FileUploadName').addClass('UploadSuccess');
		$(this.customSettings.animation+'FileUploadName').set("html",file.name + " : " + tempAmount + "MB : 100%");
		new Fx.Morph($(this.customSettings.animation+'FileUploadProgress')).start({
				'width' : $(this.customSettings.animation+'FileUploadName').getSize().x + "px",
				'background-color': '#009900'
		});
		$(this.customSettings.animation + 'FileUploadBtn').setOpacity(0);
		$$('input[type=submit]').each(function(item,index){
			$(item).disabled=false;
		});
	},
	fileQueued: function(file){											// Queue and Show the file
		$(this.customSettings.animation+'FileUploadProgress').style.width=0+"px";
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadSuccess');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFailed');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFinished');
		$(this.customSettings.animation+'FileUploadName').set("html","");
		var tempAmount="";
		var amount= "" + (file.size / 1024 / 1024);					// Get the file size in MB
		if(amount.indexOf('.')!=-1){
			amount=amount.substring(0,amount.indexOf('.')+1+parseInt(3));
		}
		for(var i=0;i<amount.length;i++){
			if(!isNaN(amount.charAt(i))||amount.charAt(i)=="."){
				tempAmount+=""+amount.charAt(i);
			}
		}
		$(this.customSettings.animation+'FileUploadName').set("html",file.name + ": " + tempAmount + "MB");
		this.startUpload();											// modified for fletcher
	},
	startUpload: function(){
		this.swfu.startUpload();
		new Fx.Tween($(this.swfu.customSettings.animation + 'FileUploadBtn')).start('opacity',0);
	},
	uploadProgress: function(file,loaded,total){
		if (this.ani) {
			this.ani.cancel();
		}
		var percentage = (loaded / total) * 100;
		var size = $(this.customSettings.animation + 'FileUploadName').getSize();
		percentage = parseInt(((size.x - 2) / 100) * percentage);
		var tempAmount = "";
		var offset = 3;
		var amount = "" + (file.size / 1024 / 1024); // Get the file size in MB
		if (amount.indexOf('.') != -1) {
			amount = amount.substring(0, amount.indexOf('.') + 1 + parseInt(3));
		}
		for (var i = 0; i < amount.length; i++) {
			if (!isNaN(amount.charAt(i)) || amount.charAt(i) == ".") {
				tempAmount += "" + amount.charAt(i);
			}
		}
		if (parseInt(percentage) <= 3) {
			offset = 0;
		}
		$(this.customSettings.animation + 'FileUploadName').set("html", file.name + " : " + tempAmount + "MB : " + parseInt(((loaded / total) * 100) - offset) + "%");
		this.ani = new Fx.Morph($(this.customSettings.animation + 'FileUploadProgress')).start({
			'width': parseInt(percentage - offset) + "px",
			'background-color': '#009900'
		});
	},
	uploadStart: function(){
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFinished');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadSuccess');
		$(this.customSettings.animation+'FileUploadName').removeClass('UploadFailed');
		$(this.customSettings.animation+'FileUploadName').addClass('Uploading');
		$(this.customSettings.animation+'FileUploadProgress').setOpacity(1);
		$(this.customSettings.animation+'FileUploadProgress').style.visibility='visible';
		$(this.customSettings.animation+'FileUploadProgress').style.display='block';
		$(this.customSettings.animation+'FileUploadProgress').style.width="1px";
		$$('input[type=submit]').each(function(item,index){
			$(item).disabled=true;
		});
		return true;
	},
	uploadFinished: function(file){
		var animation = this.customSettings.animation;
		new Fx.Tween($(animation+'FileUploadProgress'),{
			onComplete: function(){
				$(animation+'FileUploadName').removeClass('Uploading');
				$(animation+'FileUploadName').addClass('UploadFinished');
			}
		}).start('opacity',0);
		$$('input[type=submit]').each(function(item,index){
			$(item).disabled=false;
		});
	},
	uploadError : function(file, errorCode, message) {
		switch (errorCode) {
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				alert("HTTP Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				alert("Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				alert("IO Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				alert("Security Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				alert("Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
				alert("File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				break;
			default:
				alert("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
		}
	}
});
var uploaders = Array();								// Global uploaders object array
window.addEvent('domready',function(){
	$$('input[type=file]').each(function(item,index){ 	// Get all file feilds on the form
		uploaders[index] = new uploader(item);
	});
});