//## Jack Mullen 2009 
//## based entirely on Adam Royle's swfupload-jquery-plug-in 
//## using swfupload.org flash object 

//### Global Variables ####
var debug=false;
var obj_swfu=Object();
var stor="data";
var uploadCounter=1;
var cref=new Array();
var upload_code="";
//1- images, 0-all others
var upload_type='0';
//#####################

//##### OnLoad Functions/Bindings ######
 
$(function(){
	$('#swfupload-control').swfupload({
		upload_url: "./img/cgi-bin/fmxup.cgi",
		file_size_limit : "200 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : "1",
		flash_url : "./swf/vendor/swfupload/swfupload.swf",
		//## note bug in version 2 requires fix in swfuploader.js to test for no button url
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_disabled:false,
		button_width : 61,
		button_height : 22,
		button_placeholder : $('#spanButtonPlaceholder')[0],
		debug: false,
		custom_settings : {fileCount: 0}
	})
		.bind('swfuploadLoaded', function(event){
		
		Objswfu=$.swfupload.getInstance('#swfupload-control');
 		Objswfu.customSettings["fileCount"]=1;	
		Objswfu.debug("loaded");
		////$('#log').append('<li>Loaded</li>');
		
		})
		.bind('fileQueued', function(event, file){
			//$('#log').append('<li>File queued - '+file.name+'</li>');
			try {
	
		//turn off file-input display
	$("#file-input-upload").hide();
	$("#btnUpload").hide();
	//deal with file types
	if ( file.name.indexOf('.')>0 ) {
		var fileType=file.name;
		var i=fileType.length-1;
		var revname="";
		for (var x = i; x >=0; x--) {revname+=fileType.charAt(x);}
		var dot=revname.indexOf('.');
		var fext="";
		if (!(dot==-1) ) {
		var revext=revname.substring(0,dot);
		for (var x=revext.length-1; x>=0;x--){ fext+=revext.charAt(x); } }
	    var s=/jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF|BMP|bmp|tif|tiff|TIF|TIFF/.test(fext); 
		if (s==true) {
			upload_type="1"; } 
			else upload_type="0"; 
		}
		
		var locator=file.id;
		var id='file_'+locator;
		var file_object=$("#FileObjCont").html();
		$(file_object).appendTo("#upload-list-table");
		
		$("#filename").attr('id',id);
		$("#table_obj").attr('id','table_'+locator);
		//$("#tpWrapper").attr('id','tpWrapper_'+Objswfu.customSettings["fileCount"]);
		var pid='tpProgress_'+locator;
		var upt='tbUploadText_'+ locator;
		var fid=file.id;
		$("#cancel").click(function() {
		delupl(fid,locator);  });
		$("#cancel").attr('id','cancel_'+fid);		
		$("#tpProgress").attr('id',pid);
		$("#tbUploadText").attr('id',upt);
		$('#'+upt).html(' Queued for upload: '+ Math.round(file.size/1000)+'kb '); 
		//$("#upload-list").append('<br>');
		$('#'+id).append('&nbsp;&nbsp;'+file.name.substring(0,45));
		Objswfu.customSettings["fileCount"]++;
		} catch (ex) {
			
		Objswfu.debug(ex);
	}
			
			
		})
		.bind('fileQueueError', function(event, file, errorCode, message){
			//$('#log').append('<li>File queue error - '+message+'</li>');
		})
		.bind('fileDialogStart', function(event){
			//$('#log').append('<li>File dialog start</li>');
		})
		.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
			$("#selectedfiles").show();
			//$('#log').append('<li>File dialog complete</li>');
		})
		.bind('uploadStart', function(event, file){
			 try {
					$('#swfupload-control').swfupload('addPostParam','i',cref[uploadCounter-1]);	
					Objswfu.customSettings["progressCount"] =0;
					$('#tpProgress_'+uploadCounter).show();					
					} catch (ex) {Objswfu.debug(ex); }
				 							
			//$('#log').append('<li>Upload start - '+file.name+'</li>');
		})
		.bind('uploadProgress', function(event, file, bytesLoaded){
		
		var v=(bytesLoaded/file.size)*100;
		var vp=v+'%';
		var progress_pointer='#tpProgress_'+file.id;
				
try {
		$(progress_pointer).width(vp);
		Objswfu.customSettings["progressCount"]++;
		var upt='tbUploadText_'+file.id;
		updateDisplay.call(this, file, upt);
	    } catch (ex) { Objswfu.debug(ex); }
										 
			//$('#log').append('<li>Upload progress - '+bytesLoaded+'</li>');
		})
		.bind('uploadSuccess', function(event, file, serverData){
										
	try {
	if (serverData.indexOf('<img') >-1) {
	var imgtag=serverData.slice(serverData.indexOf('<img'),serverData.indexOf("width='75' />")+13);
	if (!! ("#image-list") ) { $("#image-list").append(imgtag+"&nbsp;"); } 	 }
	
	if(serverData.indexOf( "<File Too Large>") >-1) {
	var sizeerror=serverData.slice(serverData.indexOf( "<File Too Large>")+16,serverData.indexOf('</File Too Large>'));
	alert("Upload Failed -  File Size Too Large :"+sizeerror); }
	} catch (ex) { Objswfu.debug(ex); }							
										
			//$('#log').append('<li>Upload success - '+file.name+'</li>');
		})
		.bind('uploadComplete', function(event, file){
	
	var progress_pointer='#tpProgress_'+file.id;
	var upt='tbUploadText_'+ uploadCounter;
try {
	$(progress_pointer).width('100%');
	$('#'+upt).html('<center> Successfully Uploaded: '+ Math.round(file.size/1024)+'kbytes <\/center>'); 
	uploadCounter++;
	if (Objswfu.getStats().files_queued==0) {
	if (upload_type=="1") { document.location.href="http://picsmojo.com/uploaded/"+upload_code;  	}
	else {document.location.href="http://filemojo.com/uploaded/"+upload_code; }
	}	}
	catch(ex)  { Objswfu.debug(ex); }		
		
		//$('#log').append('<li>Upload complete - '+file.name+'</li>');
			
		})
		.bind('uploadError', function(event, file, errorCode, message){
		alert ( "Error Uploading: "+message);
		//$('#log').append('<li>Upload error - '+message+'</li>');
		});
	
});	

//######## Begin Connection Functions ###########

var updateDisplay= function(file,upt) {
//time remaining :: +' time remaining:'+SWFUpload.speed.formatTime(file.timeRemaining)
$('#'+upt).html(' &nbsp;&nbsp;&nbsp;&nbsp;'+SWFUpload.speed.formatPercent(file.percentUploaded)+'&nbsp;&nbsp;&nbsp;&nbsp; upload Speed ' + SWFUpload.speed.formatBPS(file.currentSpeed) ); }


var  prepareUpload = function() {
	if ( upload_type=='1') 								  
	getCollectionId( Objswfu.getStats().files_queued );
	else getFilemojoId(Objswfu.getStats().files_queued) ;
}

var delupl=function(fid,locator) {
	var fo=Objswfu.getFile(fid);
	if (fo!=null) {
	$('#swfupload-control').swfupload('cancelUpload',fid);
	 $('#table_'+locator).remove();
	 $("#file-input-upload").show();
	 $("#btnUpload").show();
	 } }
	 
//## Filemojo Specific
var getFilemojoId=function(c) { 
	var cnt=0;
	$.post("http://filemojo.com/newmojo2/iufm.php", { a1:c,sid:ssid }, 
	function (data) {
		
	if (data.status==0) { 
	if (data.chkcookies) 
		alert ( 'Error Storing Cookies : Please be sure cookies are enabled THEN RELOAD PAGE and try again  ');
		else
	alert ( "Unable to reach server "); 
	return;}
	$.each(data, function(i,val) {
	if(i=='collection') return;
	if(i=='upload_code') return;
	if(i=='status') return;
	cref[cnt]=val; cnt++; })
	upload_code=data.upload_code;
	
	$('#swfupload-control').swfupload('addPostParam','r',data.collection);
	$('#swfupload-control').swfupload('addPostParam','upload_code',data.upload_code);
	$('#swfupload-control').swfupload('addPostParam','stor',stor);
	$('#swfupload-control').swfupload('addPostParam','ssid',ssid);
	$('#swfupload-control').swfupload('addPostParam','c',c);
	$('#swfupload-control').swfupload('addPostParam','op1','Family');
	//#######for filemojo thumb == -1 (no thumb ) 
	$('#swfupload-control').swfupload('addPostParam','op2','-1');
	$('#swfupload-control').swfupload('addPostParam','op3','0');
	 $('#swfupload-control').swfupload('setUseQueryString','use_query_string');
	 //## start the process
	 $('#swfupload-control').swfupload('startUpload');
 	}, "json" );  }
	
//####PicsMojo
var	getCollectionId=function(c) {
	var cnt=0;
	$.post("http://filemojo.com/img/iu.php", { f:2,a1:c,sid:ssid }, 
	function (data) {
		if (data.status==0) { 
	if (data.chkcookies) 
		alert ( 'Error Storing Cookies : Please be sure cookies are enabled THEN RELOAD PAGE and try again  ');
		else
		alert ( "Unable to reach server "); 
	return; }
	$.each(data, function(i,val) {
	if(i=='collection') return;
	if(i=='upload_code') return;
	if(i=='status') return;
	cref[cnt]=val; cnt++; })
	upload_code=data.upload_code;
	
	$('#swfupload-control').swfupload('addPostParam','r',data.collection);
	$('#swfupload-control').swfupload('addPostParam','upload_code',data.upload_code);
	$('#swfupload-control').swfupload('addPostParam','stor',stor);
	$('#swfupload-control').swfupload('addPostParam','ssid',ssid);
	$('#swfupload-control').swfupload('addPostParam','c',c);
	$('#swfupload-control').swfupload('addPostParam','op1','Family');
	$('#swfupload-control').swfupload('addPostParam','op2','0');
	$('#swfupload-control').swfupload('addPostParam','op3','0');
	 $('#swfupload-control').swfupload('setUseQueryString','use_query_string');
	 
	 //## start the process
	 $('#swfupload-control').swfupload('startUpload');
	
 	}, "json" );  }
