/*                                                                                                                                                                                                           
 *  Copyright (c) 2008 Snapvine, LLC. All rights reserved.
 *                                                                                                  
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Snapvine, LLC 
 *    The copyright notice above does not evidence any            
 *    actual or intended publication of such source code.       
*/

if (typeof(snapvine) == "undefined") { snapvine = new function() {}; }
if (typeof(snapvine.common) == "undefined") { snapvine.common = new function() {}; }
snapvine.common.PhotoUpload = function() {};

/* Class for PhotoUpload.
 *
 * Correct usage:
 * Use photo_upload_tag in html_helper.rb. This class is not designed for isolated usage.
 *
 */
snapvine.common.PhotoUpload.prototype = {
  
  m_fileFieldParent: false,     // Container for the photo_upload_tag to control scope.
  m_fileField: null,            // DOM element for file upload.
  m_guidField: null,            // Hidden DOM element for storing uploaded photo guid.
  m_onComplete: null,           // That which happens after upload is complete.
  m_photoForm: null,            // Explicitly defined form for uploading.
  m_iframe: null,               // Explicitly defined iframe for upload target.
  m_progressImage: null,        // Image used as a progress icon.
  m_pollInterval: 1000,         // Defined in milliseconds.
  
  /* Initialize variables.
   * @public
   *
   * @param {Element}       fileField,      Input[type=file] for uploading photo.
   * @param {String}        guidFieldID,    ID of Input[type=hidden] for determining the photo GUID in later processing.
   * @param {String}        onComplete,     Optional Javascript to execute after photo is uploaded.
   *
   */
  init: function(fileField, guidFieldID, onComplete) {
    this.m_fileFieldParent = fileField.parentNode;
    
    this.m_fileField = fileField;
    this.m_guidField = document.getElementById(guidFieldID);
    this.m_onComplete = onComplete;
    
    this.m_photoForm = document.getElementById('photo_form');
    this.m_iframe = document.getElementById('photo_upload');
    
    this.m_progressImage = document.createElement('img');
    this.m_progressImage.src = "/images/progress.gif";
  },
  
  run: function() {
    try
    {
        this.cloneFileField();          // Not actually cloning; we borrow the file field and drop it into a different form.
        this.m_photoForm.submit();      // And then we submit it.
        this.unclone();                 // This puts the original file field back in its original location.
    }
    catch (e)
    {
        this.unclone();
        if (e.message.indexOf("Access is denied.") != -1)
          alert("The file you entered could not be found. Please try another.");
        return;
    }
    this.m_fileFieldParent.appendChild(this.m_progressImage);
    this.poll();                    // Wait for the upload to complete.
  },
  
  cloneFileField: function() {
    this.m_fileField.name = "photo[file]";
    this.m_photoForm.appendChild(this.m_fileField);
  },
  
  unclone: function() {
    this.m_fileFieldParent.appendChild(this.m_fileField);
  },
  
  poll: function() {
    var _this = this;
    setTimeout(function() {
           _this.checkProgress();
        }, this.m_pollInterval);
  },
  
  checkProgress: function() {
    // Go into the IFRAME and pull its contents out.
    // The contents are expected to be a line of text: GUID or error message.
    this.m_newGuid = this.m_iframe.contentWindow.document.body.innerHTML;
                          
    if (this.m_newGuid == "") { // This means it's not done. So we wait another interval and poll again.
      this.poll();
    } else if (this.m_newGuid.substr(0, 7) == "failed ") { // This means we got an error, so we deal with it.
      this.m_fileFieldParent.removeChild(this.m_fileFieldParent.getElementsByTagName('img')[0]);
      this.m_fileField.value="";
      alert("Error: "+this.m_newGuid.substr(7));
    } else { // This means it was successful. Now we wrap things up.
      this.onComplete();
    }
  },
  
  onComplete: function() {
    // Get rid of the progress icon.
    this.m_fileFieldParent.removeChild(this.m_fileFieldParent.getElementsByTagName('img')[0]);
    
    // Inject the new GUID into the expected field.
    // (This makes it possible to upload multiple photos with the same IFRAME.)
    this.m_guidField.value = this.m_newGuid;
    
    // Clear out the IFRAME so it can be used again.
    this.m_iframe.contentWindow.document.body.innerHTML = "";
    
    // If we have a preview, then fetch the URL and push it in.
    // This is not generalized for multiple uploads. Maybe some other day.
    if (this.m_previewImage != null)
    {
      var _this = this;
      $.getJSON("/phpto/get_url?photo="+ this.newGuid, null,
      function(data) {
        _this.src = data.thumb_url_full;
      });
    }
    
    // I can't think of a better way to run Javascript to be processed later.
    eval(this.m_onComplete);
  }
};