/**
 * Javscript file for the uploads page
 */
Ext.onReady(function(){

	// removing the original form button to make room for the Ext one
	Ext.get('btnContinue').first().remove();
	
	// specify some targets
	var uploadForm=new Ext.form.BasicForm('upload-form',{});

	var fldNotify = new Ext.form.ComboBox({
	   transform: 'fldNotify', 
	   emptyText: 'Select one...', 
	   typeAhead: true, 
	   allowBlank: false, 
	   cls: 'ext-combo',  
	   width: 268, 
	   forceSelection:true, 
	   triggerAction: 'all'
    });

 
    var fldName = new Ext.form.TextField({
        applyTo: 'fldName', 
        allowBlank: false
    });	
    
    var fldCompany=new Ext.form.TextField({
        applyTo: 'fldCompany', 
        allowBlank: false
    });
    
    var fldEmail = new Ext.form.TextField({
        applyTo: 'fldEmail', 
        allowBlank: false, 
        vtype:'email'
    });
    
    var fldPhone = new Ext.form.TextField({
        applyTo: 'fldPhone', 
        allowBlank: true
    });
		
    
	// patch the form for Ext handling
	uploadForm.add(
		fldName, 
		fldCompany,
		fldEmail,
		fldPhone,
		fldNotify
	);
	
   fldNotify.reset(); // Get rid of initial validation marker

   // Custom Form validation - don't enable button until everything is valid
//	Ext.TaskMgr.start({
//		run : validateForm,
//        interval : 200
//    });	
	
	function validateForm(){
		var valid=true;
        uploadForm.items.each(function(f){    
            valid = valid & f.validate();
        });
        return valid;
	//	continueBtn.setDisabled(!valid);
	//	continueBtn.setDisabled(false); /////////////////// REMOVE
	}

	// --------------------------------------------------------------------//
	var progressTemplate=new Ext.Template(
		'<div class="progressWrapper" id="{id}">',
			'<div class="progressQueued">',
				'<img class="progressFileIcon {extension}" src="/img/s.gif" alt=""/>', 
				'<a href="#" class="progressAction" title="Cancel / Remove"> </a>',
				'<div class="progressName">{name}</div>',
				'<div class="progressBar">',
					'<div class="progressBarInProgress"></div>',
				'</div>',
				'<div class="progressBarStatus"></div>',
			'</div>',
		'</div>'
	);

	// --------------------------------------------------------------------//
	
	var continueQueue=true;
	
	// --------------------------------------------------------------------//
	// Create the SWFUpload Instance
	var uploader= new SWFUpload({
		flash_url : "/js/swfupload/swfupload.swf",
//		upload_url: "http://uploads.sextonprinting.com/cgi-bin/uploader.pl",
		upload_url: '/uploads/upload',
		
		// Extra parameters for the upload CGI
		file_post_name  : 'upfile-0',
		post_params: {
			action 		: 'upload',
			overwrite 	: 'No',
			fieldorder	: 'name,company,return,phone,comments',
			category	: 'Uploads'
		},
		
		// SWFUpload UI controls
		file_size_limit : "1 GB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 1100,
		file_queue_limit : 0,
		
		// Storage that can be accessed by handlers
		custom_settings : {
			progressTarget : "fsUploadProgress"
		},
		
		// Button Settings
		button_image_url : '/img/uploads/uploadbtn.png',//"/img/ucbutton.png", //js/email_marketing/images/SmallSpyGlassWithTransperancy_17x18.png",	// Relative to the SWF file
		button_placeholder_id : "swfbutton",
		button_width: 66, //Ext.get(settings.post_params.field_name).getWidth(), //+40,
		button_height: 21,
		//button_text : '<span class="button">Change</span>',
		//button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',
		//button_text_top_padding: 0,
		//button_text_left_padding: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		
		// Debugging
		debug: false,

		// The event handler functions are defined in handlers.js
		swfupload_loaded_handler :		onSWFUploadLoaded,
		file_queued_handler : 			onFileQeued,
		file_queue_error_handler : 		onFileQeueError,
		file_dialog_start_handler : 	onFileDialogStart,
		file_dialog_complete_handler : 	onFileDialogComplete,
		upload_start_handler : 			onUploadStart,
		upload_progress_handler : 		onUploadProgress,
		upload_error_handler : 			onUploadError,
		upload_success_handler : 		onUploadSuccess,
		upload_complete_handler : 		onUploadComplete,
		//debug_handler:					onDebug,
		
		// SWFObject settings
		// minimum_flash_version : "9.0.28",
		swfupload_pre_load_handler : 	onSWFUploadPreload,
		swfupload_load_failed_handler : onSWFUploadLoadFailed
	});
	

	var continueBtn=new Ext.Button({applyTo:'btnContinue', text: 'Continue', type: 'button', handler: continueUpload , disabled: false}); 
	//var browseBtn=new Ext.Button({renderTo:'leftButtons', text: 'Add Files', type: 'button', id:'x-upload-browse-button', handler: uploader.selectFiles, scope: uploader});
	var backBtn=new Ext.Button({renderTo:'leftButtons', text: 'Back', type: 'button', id:'x-upload-back-button', handler: goBack});
	var startUploadBtn=new Ext.Button({renderTo:'rightButtons', text: 'Upload', type: 'button', id:'x-upload-start-button', disabled: true, handler: startStopUpload});
	var clearQueueBtn=new Ext.Button({renderTo:'middleButtons', style:"margin-right: 8px", id:'x-upload-clear-button', text: 'Clear', type: 'button', disabled: true, handler: clearQueue});

	// --------------------------------------------------------------------//
	
	// SWFUpload event handlers
	
	// --------------------------------------------------------------------//
	
	/**
	 * SWFUploadPreload Event
	 * 
	 * Only available with the SWFObject version of SWFUpload
	 * 
	 * Use this event to prepare some UI functionality with regards
	 * to loading messages, et
	 */
	function onSWFUploadPreload() {
		/*console.log('Getting ready to load SWFU');
		var self = this;
		var loading = function () {
			document.getElementById("divSWFUploadUI").style.display = "none";
			document.getElementById("divLoadingContent").style.display = "";

			var longLoad = function () {
				document.getElementById("divLoadingContent").style.display = "none";
				document.getElementById("divLongLoading").style.display = "";
			};
			this.customSettings.loadingTimeout = setTimeout(function () {
					longLoad.call(self)
				},
				15 * 1000
			);
		};
		
		this.customSettings.loadingTimeout = setTimeout(function () {
				loading.call(self);
			},
			2*1000
		);*/
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * SWFUploadLoadFailed Event
	 * 
	 * Only available with the SWFObject version of SWFUpload
	 * 
	 * Use this event to clean anything setup in the Preload Event
	 * and prepare the UI for failure condition
	 */
	function onSWFUploadLoadFailed() {
		/*console.log('Failed to Load SWFU');
		clearTimeout(this.customSettings.loadingTimeout);
		document.getElementById("divSWFUploadUI").style.display = "none";
		document.getElementById("divLoadingContent").style.display = "none";
		document.getElementById("divLongLoading").style.display = "none";
		document.getElementById("divAlternateContent").style.display = "";*/
	}

	// --------------------------------------------------------------------//
	
	/**
	 * SWFUploadLoadLoaded Event
	 * 
	 * Fires once the SWFUpload object is truly ready to go. This is the
	 * opposite of the SWFUploadLoadFailed event. When this event is called 
	 * it is safe to call SWFUpload methods.
	 * 
	 * Use this event to clean anything setup in the Preload Event
	 * and prepare the UI for success condition
	 */
	function onSWFUploadLoaded() {
		/*console.log('SWFU Loaded');
		var self = this;
		clearTimeout(this.customSettings.loadingTimeout);
		document.getElementById("divSWFUploadUI").style.visibility = "visible";
		document.getElementById("divSWFUploadUI").style.display = "block";
		document.getElementById("divLoadingContent").style.display = "none";
		document.getElementById("divLongLoading").style.display = "none";
		document.getElementById("divAlternateContent").style.display = "none";*/
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * FileQueued Event
	 * 
	 * The fileQueued event is fired for EACH file that is queued after the 
	 * File Selection Dialog window is closed.
	 * Fires BEFORE FileDialogCompleteEvent
	 * 
	 * Queued means that a file has been successfully added to the SWFU's
	 * internal queue. Use this event to add this file to the UI
	 */
	function onFileQeued(theFile) {
		//console.log('A file was queued');
		createProgress(theFile,this.customSettings.progressTarget);
		setProgressStatus(theFile,'Ready...');
		startUploadBtn.enable();
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * FileQueueError Event
	 * 
	 * Firesfor each file that was not queued after the File Selection 
	 * Dialog window is closed. A file may not 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.
	 * 
	 */
	function onFileQeueError(theFile, errorCode, errorMessage) {
		//console.log('The was an error in queueing the file');
		Ext.Msg.show({
			title:'File Queue Error',
			msg: 'The file <b>'+theFile.name+'</b> cannot be uploaded:<br/><br/>'+errorMessage,
			buttons: Ext.Msg.OK,
			icon: Ext.MessageBox.ERROR,
			minWidth: 480
		})
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * FileDialogStart Event
	 * 
	 * Fires 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.
	 * 
	 * NOTE: Not a very useful event...
	 */
	function onFileDialogStart() {
		//console.log('Showing the file dialog', arguments);
	}
	
	// --------------------------------------------------------------------//

	/**
	 * 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()'
	 */
	function onFileDialogComplete(numFilesSelected, numFilesQueued) {
		//console.log('User dimissed the file dialog', arguments);
		//console.log('queuedfiles: ', queuedFiles);
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * UploadStart Event
	 * 
	 * Fires immediately before the file is uploaded. This event provides 
	 * an oppurtunity 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.	 
	 */
	function onUploadStart(theFile) {
		//console.log('Upload is starting');
		setProgressStatus(theFile,'Uploading...');
		setProgressRunning(theFile);
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * UploadProgress Event
	 * 
	 * Fires 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.	 
     */
	function onUploadProgress(theFile, bytesLoaded, bytesTotal) {
		//console.log('uploading file in progress', bytesLoaded ,'of', bytesTotal)
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
		setProgress(theFile, percent);
		setProgressStatus(theFile, Ext.util.Format.fileSize(bytesLoaded) +' of '+Ext.util.Format.fileSize(bytesTotal)+' sent')
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * UploadError Event
	 * 
	 * Fires 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.	 
     */	
	function onUploadError(theFile, errorCode, errorMessage) {
		//console.log('there was an error in uploading', errorMessage);
		if(errorCode==SWFUpload.UPLOAD_ERROR.FILE_CANCELLED){
			// It's possible that the progressWrapping element had
			// already been removed in the UI Queue was cleared
			try {
				Ext.get(theFile.id).remove();
			} catch (e) {}
		}
		
		// Else handle other error conditions
		clearQueueBtn.setDisabled(Ext.select('.progressWrapper').getCount()==0);
		startUploadBtn.setDisabled(this.getStats().files_queued<=0);
		
		
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * UploadSuccess Event
	 * 
	 * Fires when an upload completes and the server returns a HTTP 200 status 
	 * code. Any data outputted by the server is available in the server 
	 * data parameter (Flash Player 9 version only).
	 *
	 * At this point the upload is not yet complete. Another upload cannot 
	 * be started from uploadSuccess.
     */	
	function onUploadSuccess(theFile, serverData) {
		//console.log('the upload was successful');
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * UploadComplete Event
	 * 
	 * Fires 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 calling uploadStart inside the
	 * uploadComplete event if you are trying to cancel all the uploads in a queue.
     */	
	function onUploadComplete(theFile) {
		// console.log('the upload is complete',theFile);
		if(theFile.filestatus==SWFUpload.FILE_STATUS.QUEUED) {
			//console.log('the file remains queued');
			setProgressStatus(theFile,'Ready...');
			setProgressQueued(theFile, this.customSettings.progressTarget);
			setProgress(theFile, '0');
		} else {
			// rather than removing the file set it to completed
			// and move it to the end of the queue and detache
			// the cancelled link event listener
			setProgressStatus(theFile,'Complete.');
			setProgressComplete(theFile, this.customSettings.progressTarget);
		}
		
		if (this.getStats().files_queued==0) {
			completeQueue(this.customSettings.progressTarget);
		}
		return continueQueue;
	}
	
	// --------------------------------------------------------------------//
	
	/**
	 * The debug event is called by the SWFUpload library and the Flash 
	 * Control when the debug setting is set to 'true'. If the debug event 
	 * is not overridden then SWFUpload writes debug messages to the 
	 * SWFUpload console (a text box dynamically added to the end of the 
	 * page body).
	 */
	function onDebug(message) {
		//console.log('SWFU::DEBUG',message);
	}
	
	// --------------------------------------------------------------------//
	
	
	
	// --------------------------------------------------------------------//
	
	// Queue Actions
	
	// --------------------------------------------------------------------//

	
	
	
	
	
	
	// --------------------------------------------------------------------//
	
	// UI Actions
	
	// --------------------------------------------------------------------//

	function createProgress(theFile, UiContainer) {
		if (!Ext.get(theFile.id)) {
			theFile.extension = theFile.name.substr(theFile.name.lastIndexOf('.')+1).toLowerCase();

			el=progressTemplate.append(UiContainer,theFile,true);
			el.child('.progressAction').on('click', function(e){
				e.stopEvent();
				uploader.cancelUpload(theFile.id);
			});
			
			clearQueueBtn.enable();
		}
	}
		
	
	
	
	
	function setProgressComplete(theFile, UiContainer) {
		try {
			var progressWrapper=Ext.get(theFile.id);
			progressWrapper.down('div').dom.className="progressComplete";
			progressWrapper.child('.progressAction').removeAllListeners();
		//	progressWrapper.remove();
		///	Ext.get(UiContainer).appendChild(progressWrapper);
		} catch (e) {
			//console.log(e)
		}
		
	}
	function setProgressRunning(theFile, UiContainer) {
		try {
			var progressWrapper=Ext.get(theFile.id);
			progressWrapper.down('div').dom.className="progressRunning";
		} catch (e) {
			//console.log(e)
		}
		
	}
	function setProgressQueued(theFile, UiContainer) {
		try {
			var progressWrapper=Ext.get(theFile.id);
			progressWrapper.down('div').dom.className="progressQueued";
		} catch (e) {
			//console.log(e)
		}
		
	}
	
	function setProgress(theFile, percentComplete) {
		var progressWrapper=Ext.get(theFile.id);
		progressWrapper.child('.progressBarInProgress').setWidth(percentComplete+'%');
	}
	
	function setProgressStatus(theFile, message) {
		Ext.get(theFile.id).child('.progressBarStatus').update(message);
	}
	
	
	/* When then entire queue went through it's upload cycle */
	function completeQueue(UIContainer) {
		startUploadBtn.disable();
		startUploadBtn.setText('Upload');
		clearQueueBtn.setDisabled(Ext.select('.progressWrapper').getCount()==0);
	}
	
	//swfu.customsettings.startButton=startUploadBtn;
	

		
	function continueUpload() {
	   if (!validateForm()) {
	       return;
	   }
	    var rawValues=uploadForm.getValues();
		Ext.get('upload-info').slideOut('t',{useDisplay: true});
		//console.log(rawValues);
		uploader.addPostParam('name',rawValues.name);
		uploader.addPostParam('company',rawValues.company);
		uploader.addPostParam('return',rawValues.email);
		uploader.addPostParam('phone',rawValues.phone);
		uploader.addPostParam('email',rawValues.notify.replace(/##TA##/g,'@').replace(/##DOT##/g,'.'));
		uploader.addPostParam('comments',rawValues.comments);
		//console.log(uploader);
		return;
	}
	
	function goBack() {
	   Ext.get('upload-info').slideIn('t',{useDisplay: true});
	}
	
	
	function startStopUpload(btn) {
		var stats=uploader.getStats();
		if (stats.in_progress==0) {
			btn.setText('Stop');
			continueQueue=true;
			uploader.startUpload();
			clearQueueBtn.disable();
		} else {
			continueQueue=false;
			uploader.stopUpload()
			btn.setText('Upload');
			clearQueueBtn.setDisabled(stats.files_queued==0 || Ext.select('.progressWrapper').getCount()==0); // this should be handled depending on what's displayed in the queue
/*			Ext.each(Ext.query('#fsUploadProgress .progressWrapper'),function(el){
				if(el.style.display!='none') {
					clearQueueBtn.enable();
				}
			});*/
		}
	}
	
	function clearQueue(btn) {
		//console.log('cancelling queue');
		uploader.cancelQueue();
		Ext.select('.progressWrapper').remove();
		btn.disable();
		startUploadBtn.disable();
	}
	
	
	
	


});




/**
 Upload cgi required fields:


<input type="hidden" value="category,upfile-0" name="required"/>
<input type="hidden" value="name,company,return,phone,comments" name="fieldorder"/>
<input type="hidden" value="upload" name="action"/>
<input type="hidden" value="Uploads" name="category"/>
<input type="hidden" value="No" name="overwrite"/>
<input type="hidden" value="adf" name="name"/>
<input type="hidden" value="asdf" name="company"/>
<input type="hidden" value="adsf" name="return"/>
<input type="hidden" value="afds" name="phone"/>
<input type="hidden" value="jeff@sextonprinting.com" name="email"/>

**/