// JavaScript Document
function fileUploadExec(){
  upClass = new fileUpload();
  if(!upClass.supportChecks()) return false;
  upClass.prepareForms();
}
function fileUpload(){
  var fileForm = document.getElementById("fileForm");
  var uploadUl = document.createElement("ul");
  uploadUl.setAttribute("id","ajaxUploadList");
  insertAfter(uploadUl,fileForm);

  var uniqueIds = new Array(
  new Array(fileForm.UniqueId0.value,true,0),
  new Array(fileForm.UniqueId1.value,true,1),
  new Array(fileForm.UniqueId2.value,true,2),
  new Array(fileForm.UniqueId3.value,true,3),
  new Array(fileForm.UniqueId4.value,true,4),
  new Array(fileForm.UniqueId5.value,true,5),
  new Array(fileForm.UniqueId6.value,true,6),
  new Array(fileForm.UniqueId7.value,true,7),
  new Array(fileForm.UniqueId8.value,true,8),
  new Array(fileForm.UniqueId9.value,true,9)
  );
  var uniqueIdInForm = uniqueIds[0];

  var uploadCallback = { success:sendFileCallback, upload:sendFileCallback }
  var progressCallback = { success:sendProgressCallback }

  //set the timer to run the progress bar function
  var self = this;
  var interval = 3000;
  var progressInterval = setInterval(function () { self.progressListener() }, interval)

  this.clearFileForm = clearFileForm;
  this.supportChecks = supportChecks;
  this.prepareForms = prepareForms;
  this.checkForm = checkForm;
  this.sendFile = sendFile;
  this.sendFileCallback = sendFileCallback;
  this.createYourUploads = createYourUploads;
  this.getOpenId = getOpenId;
  this.openId = openId;
  this.closeId = closeId;
  this.progressListener = progressListener;
  this.sendProgressCallback = sendProgressCallback;

  function supportChecks(){
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById("fileForm")) return false;
    return true;
  }
  function prepareForms(){
    //intercept the upload button
    var inputs = fileForm.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
      if (inputs[i].type == "submit") {
        //Add the onclick event handler
        inputs[i].onclick = function(){
            sendFile();
          return false;
        }
      }
    }
  }
  function checkForm(){
    var errors = '';
    if(fileForm.file.value==""){errors += "No file selected.\n";}
    var newId = getOpenId();
    if (newId){
      uniqueIdInForm = newId;
      fileForm.UPLOAD_IDENTIFIER.value = newId[0];
    }else{
      errors += "Please wait for one of your uploads to finish.\n";
    }
    return errors;
  }
  function sendFile(){
    //check form before uploading
    var errors = checkForm();
    if (errors != '') {
      //errors found, display them and exit
      alert(errors);
    }else{
      // YUI set up the form
      YAHOO.util.Connect.setForm(fileForm,true);
      // Connect and do the dirty iframe/async/ajax/rails/soa/DHH/someother dumbbuzzword/MTV magic
      var cOBJ = YAHOO.util.Connect.asyncRequest('POST','ajaxProcessUpload.php',uploadCallback);
      //close this unique id (uploading)
      closeId(uniqueIdInForm[2]);
      clearFileForm();
      fileForm.action.disabled = true;
    }
    return false;
  }
  function sendFileCallback(o){
    var page = o.responseXML;
    var theForm = page.getElementById('returnValues');
    var uid = theForm.UPLOAD_IDENTIFIER.value;
    var imglink = theForm.link.value;
    var imgsrc = theForm.thumb.value;
    var upError = theForm.error.value;
    if(upError!=""){
      alert(upError);
      for (var x = 0; x<10; x++){
        if (uniqueIds[x][0] == uid){
          openId(uniqueIds[x][2]);
        }
      }
      fileForm.action.disabled = false;
    }else{
      var newLi = document.createElement("li");
      var newA = document.createElement("a");
      var newImg = document.createElement("img");
      newLi.appendChild(newA);
      newA.appendChild(newImg);
      newImg.setAttribute("src", imgsrc);
      newA.setAttribute("href", imglink);
  
      for (var x = 0; x<10; x++){
        if (uniqueIds[x][0] == uid){
          openId(uniqueIds[x][2]);
        }
      }
      fileForm.action.disabled = false;
      createYourUploads();
      var yourUploads = document.getElementById('yourUploads');
      var theLi = yourUploads.getElementsByTagName('li')[0]
      if(theLi){
        theLi.parentNode.insertBefore(newLi, theLi);
      }else{
        yourUploads.getElementsByTagName('ul')[0].appendChild(newLi);
      }
    }//end error if
  }
  function createYourUploads(){
    if(document.getElementById('yourUploads')){return true;}
    var upFormDiv = document.getElementById('uploadForm');

    var yourUploadsDiv = document.createElement("div");
    var yourUploadsH1 = document.createElement("h1");
    var H1Txt = document.createTextNode("Your Uploads");
    var yourUploadsUl = document.createElement("ul");
    yourUploadsDiv.appendChild(yourUploadsH1);
    yourUploadsH1.appendChild(H1Txt);
    yourUploadsDiv.appendChild(yourUploadsUl);
    yourUploadsDiv.appendChild(globalFooterDiv);
    yourUploadsDiv.setAttribute("id", "yourUploads");
    yourUploadsDiv.setAttribute("class", "contentDiv");

    insertAfter(yourUploadsDiv, upFormDiv);
    return true;
  }
  function progressListener(){
    //check array for closed Ids and send ajax request for the progress bars
    var uriVals = '';
    for (var x = 0; x<10; x++){
      if (uniqueIds[x][1] == false){
        uriVals += 'id=' + uniqueIds[x][0];
      }
    }
    //if uriVals has Ids, send the AJAX request
    if (uriVals != ''){
      YAHOO.util.Connect.asyncRequest('POST','ajaxGetUploadProgress.php',progressCallback,uriVals);
    }
  }
  function sendProgressCallback(o){
    uploadUl.innerHTML = o.responseText;
  }

  function getOpenId(){
    for (var x=0; x<10; x++){
      if (uniqueIds[x][1]) return uniqueIds[x];
    }
    //all IDs are closed(user cant upload until one finished and opens)
    return false;
  }
  function openId(id){
    uniqueIds[id][1] = true;
  }
  function closeId(id){
    uniqueIds[id][1] = false;
  }

  function clearFileForm(){
    fileForm.file.value = "";
    fileForm.title.value = "";
    fileForm.description.value = "";
  }
}

addLoadEvent(fileUploadExec);

