
var ProgressUploader = Class.create();
//Uploader static variables: Edit these as necessary
ProgressUploader.INSTALL_PATH = "progressUploader/";
ProgressUploader.FILENAME_FILTER = new RegExp(".+");
ProgressUploader.REFRESH_RATE = 3000;
ProgressUploader.prototype = {
  initialize: function(container){
    //Ensure the container has the progressUploader className for styles
    if(!container.className.match(/progressUploader/)) container.className += " progressUploader";
    
    //Get the id attribute from the container if it exists: Otherwise, create one
    this.fileId = container.id;
    if(!this.fileId){
      this.fileId = container.id = Math.floor(Math.random() * 10000000);
    }
    
    //If the user has provided an onSuccess redirect file, use that
    this.onSuccessFile = container.getAttribute("onSuccessFile");
    
    //If the user has specified whether or not to start a session
    this.startSession = container.getAttribute("startSession");
    
    //If the user has provided a filename filter, override the default
    var filter = container.getAttribute("filter");
    if(filter) ProgressUploader.FILENAME_FILTER = new RegExp(filter);
    
    //Create and add the upload iframe to the container
    this.uploadFrame = document.createElement("iframe");
    var frameSrc = ProgressUploader.INSTALL_PATH+"upload_iframe.php?fileId="+this.fileId+"&ensureRefresh="+Math.random();
    if(this.onSuccessFile) frameSrc += "&onSuccessFile="+this.onSuccessFile;
    if(this.startSession) frameSrc += "&startSession="+this.startSession;
    
    //All hidden inputs inside of this cointainer will be added to the request as key value pairs
    $A(container.getElementsByTagName("input")).each(
      function(input){
        frameSrc += "&"+input.getAttribute("name")+"="+encodeURIComponent(input.getAttribute("value"));
      }
    );
    this.frameSrc = frameSrc;
    this.uploadFrame.src = this.frameSrc;
    this.uploadFrame.frameBorder = 0;
    this.uploadFrame.name = this.uploadFrame.id = "uploadFrame_"+this.fileId;
    container.appendChild(this.uploadFrame);

    //Create and add the progress div to the container
    this.progressPanel = document.createElement("div");
    container.appendChild(this.progressPanel);

    //Provide the container a reference to 'this' object: This is required for the global setInterval calls
    var progressUploader = this;//Make a copy of this for the function implementation
    container.getProgressUploader = function(){
      return progressUploader;
    }
    
    //If the provided container defines an onComplete function, use it!
    if(container.onComplete) this.onComplete = container.onComplete;
    if(container.onStart) this.onStart = container.onStart;
  },
  startUpload: function(){
    var fileInput = window.frames['uploadFrame_'+this.fileId].document.getElementById("userfile");
    if(fileInput){
      if(!fileInput.value.match(ProgressUploader.FILENAME_FILTER)){//Bogus filename
        window.frames['uploadFrame_'+this.fileId].document.getElementById("invalidFileMessage").style.display = "inline";
        return false;
      }
    }
    if(this.onStart) this.onStart();
    this.progressPanel.innerHTML = "Starting...";
    this.progressPanel.style.display = "block";
    this.submitUploadForm();
    this.startUpdater();
  },
  stopUpload: function(){
    //window.frames['uploadFrame_'+this.fileId].location.reload(true);
    //this.uploadFrame.src = this.frameSrc;
    this.uploadFrame.src = ProgressUploader.INSTALL_PATH+"cancel.cgi?fileId="+this.fileId;
    this.progressPanel.innerHTML = "Cancelling...";
    this.stopUpdater();
    //Give the iframe a chance to load up, and ensure the upload cancels okay
    window.setTimeout("$('"+this.fileId+"').getProgressUploader().getUploadForm();", ProgressUploader.REFRESH_RATE);
  },
  submitUploadForm: function(){
    window.frames['uploadFrame_'+this.fileId].document.forms[0].submit();
    this.uploadFrame.style.display = "none";
  },
  startUpdater: function(){
    this.updateOn = true;
    this.getUploadProgress();
    this.progressInterval = window.setInterval("$('"+this.fileId+"').getProgressUploader().getUploadProgress();", ProgressUploader.REFRESH_RATE);
  },
  stopUpdater: function(){
    this.updateOn = false;
    window.clearInterval(this.progressInterval);
  },
  getUploadProgress: function(){
    var url = ProgressUploader.INSTALL_PATH+"progress.php";
    var pars = "fileId="+this.fileId+"&ensureRefresh="+Math.random();
    
    var uploadProgress = this;//Make a copy of this for the impl
    new Ajax.Request(
      url,
      {
        method: "get",
        parameters: pars,
        onComplete: function(originalRequest){
          if(!uploadProgress.updateOn) return;
          var response = originalRequest.responseText;
          var tmpDiv = document.createElement("div");
          tmpDiv.innerHTML = response;
          if(tmpDiv.firstChild && tmpDiv.firstChild.tagName.toLowerCase()=="label") var uploadStatus = tmpDiv.firstChild.getAttribute("uploadStatus");
          
          //If there is an image in the response, lets preload it so it's in cache, and it will display much faster
          var responseImage = tmpDiv.getElementsByTagName("img")[0];
          if(responseImage){
            var preloadImage = new Image();
            preloadImage.src = responseImage.src;
            //alert(preloadImage.src);
          }
          if(uploadStatus && uploadStatus.toLowerCase()=="aborted"){
            uploadProgress.progressPanel.innerHTML = response;
            uploadProgress.stopUpdater();
            if(uploadProgress.onComplete) uploadProgress.onComplete();
          }
          if(uploadStatus && uploadStatus.toLowerCase()=="completed"){
            uploadProgress.progressPanel.innerHTML = response;
            uploadProgress.stopUpdater();
            if(uploadProgress.onComplete) uploadProgress.onComplete();
          }
          //uploadProgress.progressPanel.innerHTML = response;
          if(tmpDiv.firstChild){
            uploadProgress.progressPanel.innerHTML = "";
            uploadProgress.progressPanel.appendChild(tmpDiv.firstChild);
          }
        }
      }
    );
  },
  getUploadForm: function(){
    this.uploadFrame.style.display = "block";
    this.progressPanel.style.display = "none";
  }
}//ProgressUploader

//Create Behaviour rules to automatically generate upload forms
ProgressUploader.Rules = {
  ".progressUploader": function(element){
    if(element.loaded) return true;
    element.loaded = true;

    new ProgressUploader(element);
  },
  "#submitAllUploadsButton": function(element){
    if(element.loaded) return true;
    element.loaded = true;
    
    Event.observe(element, "click",
      function(event){
        document.getElementsByClassName("progressUploader").each(
          function(progressUploaderContainer){
            progressUploaderContainer.getProgressUploader().startUpload();
          }
        );
      }
    );
  }
}
//Be sure to comment the following line out if you don't want to use behaviour
//Behaviour.register(ProgressUploader.Rules);
