/* Demo Note:  This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
The FileProgress class is not part of SWFUpload.
*/


/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */

//trigger when the SWFUploader is initiated
swfReady = function () {
  //forces the swfuploader object to have the file_upload_limits already set
  if (this.customSettings.successful_uploads) {
    var stats = this.getStats();
    stats.successful_uploads = this.customSettings.successful_uploads;
    this.setStats(stats);
    this.customSettings.successful_uploads = 0;
  }
}

fileQueued = function (file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setStatus("Pending...");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

fileQueueError = function (file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("Dit bestand is te groot. De limiet staat ingesteld op " + this.settings.file_size_limit +".");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

fileDialogComplete = function (numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			//document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}

		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

uploadStart = function (file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		 */

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setStatus("Bezig met uploaden...");
		//document.getElementById(this.customSettings.cancelButtonId).style.display = 'inline';

		$('progressbar-container-'+this.customSettings.marker).style.display = 'block';

		//document.getElementById('progressbar-container-'+this.customSettings.marker).style.display = 'block';
		//document.getElementById('progressbar-total-container-'+this.customSettings.marker).style.display = 'block';

		progress.toggleCancel(true, this);
	}
	catch (ex) {}

	return true;
}

uploadProgress = function (file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		var width = xWidth(document.getElementById('progressbar-container-'+this.customSettings.marker));

		var ratio = (width - 4) / 100;

		try {
		  document.getElementById('progressbar-'+this.customSettings.marker).style.width = Math.ceil(percent * ratio)+'px';
		}
		catch(e) {}

		try {
		  document.getElementById('progressbar-total-'+this.customSettings.marker).style.width = Math.ceil(percent * ratio)+'px';
		}
		catch(e) {}

		//progress.setStatus('');
	} catch (ex) {
		this.debug(ex);
	}
}

uploadSuccess = function (file, serverData) {
	try {
	  var settings = this.customSettings;
	  var progress = new FileProgress(file, settings.progressTarget);
		progress.setComplete();
		//progress.setStatus("Gereed.");

		//progress.setStatus('Bestand '+file.name+' is succesvol verzonden.');
		if (settings.customCallback != undefined) {
		  eval(settings.customCallback);
		}
		else {
      var env = window.location.href.match("/(?:backend|frontend)?(_dev|_prod)?.php");
      env = env!=null && (typeof env=='object') && env.length ? env[0] : '';
		  var link = env + '/swfuploader/reload/';
		  if(settings.panel != undefined) {
		    link += 'panel/'+ settings.panel;
		  }
		  else {
		    link += 'swfupload/' + settings.marker;
		  }
		  link += '/rmodule/'+settings.module;

		  if(settings.template != undefined) {
		    link += '/template/'+settings.template;
		  }

		  if(parseInt(this.settings.file_upload_limit) > 1) {
		    link += '/multiple/' + this.settings.file_upload_limit;
		  }

		  var options = { 'parameters': { 'object_type': this.settings.object_type }};
      if(settings.onUploadCompleteCallback != undefined ) {
        options.onComplete = function() {
            eval(settings.onUploadCompleteCallback);
        }
      }
/*
      if(typeof(settings.multiple) != 'undefined' && typeof(this.settings.updateUpload) == 'undefined') {
        new Ajax.Request(link, options );
      }
      else {
        new Ajax.Updater(settings.marker+'-container', link, options );
      }
*/		  
      //we always make an ajax request since the user has to know visually that his content was uploaded
      new Ajax.Updater(settings.marker+'-container', link, options );
	  }
		//document.getElementById(settings.cancelButtonId).style.display = 'none';

		try {
  		document.getElementById('progressbar-'+settings.marker).style.width = '0px';
  		document.getElementById('progressbar-container-'+settings.marker).style.display = 'none';

		} catch(e) {}

		progress.toggleCancel(false);
	} catch (ex) {
		this.debug(ex);
	}
}

removeAttachment = function ()
{
  document.getElementById('file-status-'+this.customSettings.marker).style.display = 'none';
  document.getElementById('file-upload-'+this.customSettings.marker).style.display = 'block';
  document.getElementById('progress-'+this.customSettings.marker).innerHTML = '';
  new Ajax.Request('swfuploader/clear/file/'+this.customSettings.marker);
}

uploadError = function (file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Geannuleerd");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Onverwachte fout: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }

	//document.getElementById(this.customSettings.cancelButtonId).style.display = 'none';

	try {
	document.getElementById('progressbar-'+this.customSettings.marker).style.width = '0px';
	document.getElementById('progressbar-container-'+this.customSettings.marker).style.display = 'none';

	}
	catch(e) {}
}

uploadComplete = function (file) {
	if (this.getStats().files_queued === 0) {
		//document.getElementById(this.customSettings.cancelButtonId).disabled = true;
		$('progressbar-container-'+this.customSettings.marker).style.display = 'none';
	}
}

// This event comes from the Queue Plugin
queueComplete = function (numFilesUploaded) {
	var status = document.getElementById("divStatus");
	if(status!=null) status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}

