/*
 * $RCSfile$
 * $Revision: 14166 $
 * $Date: 2005-02-07 15:57:29 -0800 (Mon, 07 Feb 2005) $
 *
 * Copyright (C) 1999-2006 Jive Software. All rights reserved.
 *
 * This software is the proprietary information of Jive Software. Use is subject to license terms.
 */

var JiveAutoSave = Class.create();
JiveAutoSave.prototype = {

 /*
  * Initialize the JiveAutoSave object.
  * @enabled Whether or not the autosave invocations should begin automatically
  * @interval The number (in seconds) between autosave invocations.
  * @draftType The object type of the document being saved.
  * @objectType The object type of the container (MESSAGE,THREAD,FORUM,CATEGORY,SYSTEM)
  * @objectID The ID of the container
  * @subject The name of the document element containing the subject field.
  * @body The name of the document element containing the body field.
  * @properties An array of document element properties that need to be saved.
  * @confirmationMessage A message to show the user if the draft has not been saved.
  * @saveMessage The 'save now' button text.
  * @savedMessage The 'saved' button text.
  */
  initialize: function(enabled,interval,draftType,objectType,objectID, subject, body, properties,
                       confirmationMessage, saveMessage, savedMessage) {
    enabled = enabled;
    interval = interval;
	needSave = false;
	draftType = draftType;
	objectType = objectType;
	objectID = objectID;
    subject = subject;
    body = body;
    properties = properties;
    confirmation = true;
    confirmationMessage = confirmationMessage;
    saveMessage = saveMessage;
    savedMessage = savedMessage;
    if (enabled) {
		this.autoSaveInit(interval);
    }
    window.onbeforeunload = this.navigateAway;
	// window.onbeforeunload = null;
  },

  /*
  * Schedule the JiveAutoSave object with PeriodicalExecutor to be fired every
  * n seconds where n = interval.
  * @interval The number (in seconds) between autosave invocations.
  */
  autoSaveInit: function(interval) {
    var pe = new PeriodicalExecuter(this.saveDraft, interval);
  },

  /*
  * Save the draft to the server.  Fired every n seconds by the
  * PeriodicalExecuter only if the content has changed in some
  * way. Can also be used as a callback as part of a DWR operation.
  *
  * @data Data from a DWR operation. Only applicable when the editor
  * body name is 'textEditor' and the tinyMCE mode is 'advanced'.
  */
  saveDraft: function(data) {
    if (needSave) {
        // prototype 1.5.0 final changed now PeriodicalExecuter functions and now passes in an
        // instance of itself as a parameter to any called function
        if (body == 'textEditor' && (data == undefined || data.__proto__ == PeriodicalExecuter.prototype) 
                && getEditorMode() == 'advanced') 
        {
            getEditorContent(autoSave.saveDraft);
            return;
        }

        var draft = new Object();
		draft.draftID = $F('draftid');
        draft.draftType = draftType
        draft.objectType= objectType;
        draft.objectID = objectID;
		draft.subject = $F(subject);
        if (body == 'textEditor') {
            if (getEditorMode() == 'advanced') {
                draft.body = data;
            } else {
                draft.body = getEditorContent();
            }
        } else {
            draft.body = $F(body);
        }
		draft.properties = {};
        for (var i = 0; i < properties.length; i++) {
			var prop = document.getElementById(properties[i]);
            if (prop.type == 'checkbox' || prop.type == 'radio') {
				if (prop.checked) {
					draft.properties[properties[i]] = 'checked';
				}
			} else if (prop.type == 'text' || prop.type == 'textarea' || prop.type == 'hidden') {
				if (prop.value.length > 0) {
					draft.properties[properties[i]] = prop.value;
				}
            }
        }

        Draft.saveDraft(draft, autoSave.postSave);
	}
  },

  /*
  * Handle the results of a draft save to the server.
  *
  * @data The data returned from DWR, should be a draft in JSON.
  */
  postSave: function(data) {
    needSave = false;
    confirmation = false;
    $('doDraft').disabled = true;
    $('doDraft').value = savedMessage;
    $('draftid').value = data.draftID;
    message = data.modificationDateFormatted;
    DWRUtil.setValue("autosave", message);
    // window.onbeforeunload = null;
  },


  /*
  * Handle changes to the form fields
  */
  messageChangeHandler: function() {
	needSave = true;
    confirmation = true;
    if (enabled && $('doDraft')) {
    	$('doDraft').disabled = false;
        $('doDraft').value = saveMessage;
        // window.onbeforeunload = this.navigateAway;
    }
  },


 /*
  * Fired when the user decides they want to 'use a draft' when one
  * is available on the server.  Starts up the draft autosave engine,
  * retrieves the draft from the server and sends the result to the
  * displayDraft() method.
  *
  */
  useDraft: function(callbackFunction) {
	enabled = true;
    this.autoSaveInit(interval);
    var self = this;
    if (!callbackFunction) {
        Draft.getDraft(draftType, objectType, objectID, this.displayDraft);
    }
    else {
        Draft.getDraft(draftType, objectType, objectID,
            {
                callback:function(dataFromServer) {
                    self.displayDraft(dataFromServer);
                    eval(callbackFunction + "()");
                }
            }
        );
    }
  },

 /*
  * Displays data retrieved from the server on the client, turns on
  * 'save draft' button, fades out the 'draft exists' message and puts
  * the cursor in the body text field.
  *
  * @data: The JSON draft object returned from the server.
  */
  displayDraft: function(data) {
    var props = data.properties;
	// special case for polls: we have to create form elements that may not exist
	if (data.draftType == 18) {
		for (var prop in props) {
			if (prop.indexOf('jive-option-table-option-') > -1 &&
				prop != 'jive-option-table-option-1' &&
				prop != 'jive-option-table-option-2') {
					addOption('jive-option-table', true);
			}
		}
	}

    if (body == 'textEditor' && getEditorMode() == 'advanced') {
        retrieveHTML = true;
        setEditorContentFromDraft(data.body);
    } else {
        $(body).value = data.body;
    }

    $(subject).value = data.subject;

    for (var i = 0; i < properties.length; i++) {
        var prop = document.getElementById(properties[i]);
        if (prop.type == 'checkbox' || prop.type == 'radio') {
			if (props[properties[i]] == 'checked') {
				prop.checked = true;
			}
		} else if (prop.type == 'text' || prop.type == 'textarea' || prop.type == 'hidden') {
            if (props[properties[i]] != undefined && props[properties[i]] != '' ) {
				prop.value = props[properties[i]];
			} else {
                prop.value = '';
            }
		}
	}

    Effect.Fade('jive-info-message');
    // IE / TinyMCE doesn't like it when you try to focus a GUI enabled textarea
    // $(body).focus();
  },

  /*
  * Deletes the draft from the server.
  */
  deleteDraft: function() {
    Draft.deleteDraft(draftType, objectType, objectID, function() {});
    enabled = true;
    this.autoSaveInit(interval);
    Effect.Fade('jive-info-message');
  },

  /*
  * Called by window.onbeforeunload. Checks to see if the draft is in an
  * unsaved state AND if we haven't turned off confirmations. So for instance,
  * a draft could be in an unsaved state and the user could be clicking the
  * 'post' button: we wouldn't want to show a 'draft unsaved' message.
  */
  navigateAway: function() {
  	if (!$('doDraft').disabled) {
  	// if (needSave && confirmation) {
		return confirmationMessage + "\n";
	}
    else {
        try {
            event.cancelBubble = true;
        } catch (err) {
            // ignore, cancelBubble is IE only
        }
    }
  },

  /*
  * Called by the 'discard draft' button, asks the user to confirm that they
  * want to discard the draft they are currently working with.
  */
  confirmDiscard: function(message) {
    if (confirm(message)) {
        cancelPost = true;
        window.onbeforeunload = null;
        return true;
    }
    else {
        return false;
    }
  },

  getProperties: function() {
      return properties;
  },

  addProperty: function(prop) {
      properties[properties.length] = prop;
      this.messageChangeHandler();
  },

  deleteProperty: function(prop) {
      temp = [];
      k = 0;
      for (var i = 0; i < properties.length; i++) {
        if (properties[i] != prop) {
            temp[k++] = properties[i];
        }
      }
      properties = temp;
      this.messageChangeHandler();
  }
}


var DummyAutoSave = Class.create();
DummyAutoSave.prototype = {

  initialize: function() {
  },

  autoSaveInit: function(interval) {
  },

  saveDraft: function(data) {
  },

  postSave: function(data) {
  },

  messageChangeHandler: function() {
  },

  useDraft: function(callbackFunction) {
  },

  displayDraft: function(data) {
  },

  deleteDraft: function() {
  },

  navigateAway: function() {
  },

  confirmDiscard: function(message) {
    return false;
  },

  getProperties: function() {
  },

  addProperty: function(prop) {
  },

  deleteProperty: function(prop) {
  }
}