/*
 * Edit In Place
 * http://josephscott.org/code/js/eip/
 * Version 0.3.3
 * License http://josephscott.org/code/js/eip/license.txt
 */

/*  Code has been customized for this extension  */

var CommentID;

// Fake a EdintInPlace.* name space.
var EditInPlace = function() { };

// Default settings for editable ids.
EditInPlace.defaults = {
	// Default options that you can over write.
	id:						false,
	save_url:				false,
	type:					'text',
	select_text:			false,
	size:					false,  // will be calculated at run time
	max_size:				100,
	rows:					false,  // will be calculated at run time
	cols:					50,
	options:				false,
	mouseover_class:		'eip_mouseover',
	editfield_class:		'eip_mouseover',
	savebutton_text:		'SAVE',
	savebutton_class:		'eip_savebutton',
	cancelbutton_text:		'CANCEL',
	cancelbutton_class:		'eip_cancelbutton',
	saving_text:			'Saving...',
	saving_class:			'eip_saving',
	empty_text:				'Click To Edit',
	empty_class:			'eip_empty',
	click:					'click',  // or dblclick
									// (which doesn't work on Safari)
	savefailed_text:		'Failed to save changes.',

	// Private options that are managed for you.
	// PLEASE DO NOT TOUCH THESE.
	is_empty:				false,
	orig_text:				'',
	mouseover_observer:		false,
	mouseout_observer:		false,
	mouseclick_observer:	false
};

// Place to keep individual option sets.
EditInPlace.options = { };

// Make an id editable.
EditInPlace.makeEditable = function(args) {
	var id = args['id'];
	var id_opt = EditInPlace._getOptionsReference(id);

	// Start the option set with the defaults.
	for(var i in EditInPlace.defaults) {
		id_opt[i] = EditInPlace.defaults[i];
	}

	// Over write defaults with provided arguments.
	for(var i in args) {
		id_opt[i] = args[i];
	}

	// Store the current (original) value of the editable id.
	id_opt['orig_text'] = $(id).innerHTML;

	// Check for empty values.
	if($(id).innerHTML == '') {
		id_opt['is_empty'] = true;
		$(id).innerHTML = id_opt['empty_text'];
		Element.addClassName(id, id_opt['empty_class']);
	}

	// Build event observers.
	id_opt['mouseover_observer'] = EditInPlace._mouseOver.bindAsEventListener();
	id_opt['mouseout_observer'] = EditInPlace._mouseOut.bindAsEventListener();
	id_opt['mouseclick_observer'] = EditInPlace._mouseClick.bindAsEventListener();

	// Watch for events.
	Event.observe(id, 'mouseover', id_opt['mouseover_observer']);
	Event.observe(id, 'mouseout', id_opt['mouseout_observer']);
	Event.observe(id, id_opt['click'], id_opt['mouseclick_observer']);

	// Return a reference the option set
	// just in case someone is interested.
	return(id_opt);
};

// **************  Private Functions ***************** 

// Get a reference to the option set for a specific editable id.
EditInPlace._getOptionsReference = function(id) {
	// If an option set doesn't exist for the id
	// then create an empty one.
	if(!EditInPlace.options[id]) {
		EditInPlace.options[id] = { };
	}

	return(EditInPlace.options[id]);
};

// Process mouseover events.
EditInPlace._mouseOver = function(event) {
	var id = Event.element(event).id;
	var id_opt = EditInPlace._getOptionsReference(id);

	// If we can't get the id then don't process the event.
	if(!id) {
		return(false);
	}

	Element.addClassName(id, id_opt['mouseover_class']);
};

// Process mouseout events.
EditInPlace._mouseOut = function(event) {
	var id = Event.element(event).id;
	var id_opt = EditInPlace._getOptionsReference(id);

	// If we can't get the id then don't process the event.
	if(!id) {
		return(false);
	}

	Element.removeClassName(id, id_opt['mouseover_class']);
};

// Process mouseclick events.
EditInPlace._mouseClick = function(event) {
	var id = Event.element(event).id;
	var id_opt = EditInPlace._getOptionsReference(id);
//	var form = EditInPlace._formField(id) + EditInPlace._formButtons(id);

	// If we can't get the id then don't process the event.
	if(!id) {
		return(false);
	}

    CommentID = id.slice(12);

// TODO:  change this to show Mark's loading pinwheel
    document.getElementById('CommentBody_'+CommentID).innerHTML = '<strong>Loading...</strong>';

    	if(!http_get('extensions/EditInPlace/eip.php?CommentID='+CommentID, _ReplaceDiv))
		alert('An error occured while attempting to set up request');

};

//TODO: Process save button clicks.
EditInPlace._saveClick = function(event) {
	var id = Event.element(event).id.replace(/_save$/, '');
	var id_opt = EditInPlace._getOptionsReference(id);

	// Package data for the AJAX request.
	var new_text = escape($F(id + '_edit'));
	var params = 'id=' + id + '&content=' + new_text;
	if(id_opt['type'] == 'select') {
		params += '&option_name=' + $(id + '_option_' + new_text).innerHTML;
	}

	// Build saving message.
	var saving = '<span class="'
		+ id_opt['saving_class'] + '">' + id_opt['saving_text'] + '</span>\n';

	// Turn off event watching while saving changes.
	Event.stopObserving(id, 'mouseover', id_opt['mouseover_observer']);
	Event.stopObserving(id, 'mouseout', id_opt['mouseout_observer']);
	Event.stopObserving(id, id_opt['click'], id_opt['mouseclick_observer']);

	// Remove the form editor and display the saving message.
	Element.remove(id + '_editor');
	$(id).innerHTML = saving;
	Element.show(id);

	// Send the changes via AJAX.
	var ajax_req = new Ajax.Request(
		id_opt['save_url'],
		{
			method: 'post',
			postBody: params,
			onSuccess: function(t) { EditInPlace._saveComplete(id, t); },
			onFailure: function(t) { EditInPlace._saveFailed(id, t); }
		}
	);
};

// Complete the successful AJAX request.
EditInPlace._saveComplete = function(id, t) {
	var id_opt = EditInPlace._getOptionsReference(id);

	// Check to see if the user deleted all of the text.
	if(t.responseText == '') {
		id_opt['is_empty'] = true;
		$(id).innerHTML = id_opt['empty_text'];
		Element.addClassName(id, id_opt['empty_class']);
	}
	else {
		id_opt['is_empty'] = false;
		Element.removeClassName(id, id_opt['empty_class']);
		$(id).innerHTML = t.responseText;
	}

	// Save the new text as the original text.
	id_opt['orig_text'] = t.responseText;

	// Turn on event watching again.
	Event.observe(id, 'mouseover', id_opt['mouseover_observer']);
	Event.observe(id, 'mouseout', id_opt['mouseout_observer']);
	Event.observe(id, id_opt['click'], id_opt['mouseclick_observer']);
};

// Complete the failed AJAX request.
EditInPlace._saveFailed = function(id, t) {
	var id_opt = EditInPlace.getOptionsReference(id);

	// Restore the original text, remove the editfield class
	// and alert the user that the save failed.
	$(id).innerHTML = id_opt['orig_text'];
	Element.removeClassName(id, id_opt['editfield_class']);
	alert(id_opt['savefailed_text']);

	// Turn on event watching again.
	Event.observe(id, 'mouseover', id_opt['mouseover_observer']);
	Event.observe(id, 'mouseout', id_opt['mouseout_observer']);
	Event.observe(id, id_opt['click'], id_opt['mouseclick_observer']);
};


var req;

function http_get(url, func) {
   req = false;
   if(window.XMLHttpRequest) {
      req = new XMLHttpRequest();
      if(req.overrideMimeType) req.overrideMimeType('text/xml');
   }
   else if(window.ActiveXObject) {
      try {
         req = new ActiveXObject('Msxml2.XMLHTTP');
      }
      catch(error) {
         try {
            req = new ActiveXObject('Microsoft.XMLHTTP');
         }
         catch(error) {}
      }
   }

   if(!req) return false;

   req.onreadystatechange = func;
   req.open('GET', url, true);
//   req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  // these are used for POSTs
//   req.setRequestHeader('Content-length', params.length);
   //req.setRequestHeader('Connection', 'close');
   req.send(null);

   return true;
}

function _ReplaceDiv() {

    if (req.readyState == 4) {
       if (req.status == 200) {
          document.getElementById('CommentBody_'+CommentID).innerHTML = req.responseText;
       }
    }


}
