/*!======================================================================*\
|| #################################################################### ||
|| # vBulletin 2.0.2
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2000-2009 Jelsoft Enterprises Ltd. All Rights Reserved. ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/

vBulletin.events.systemInit.subscribe(function()
{
	if (AJAX_Compatible)
	{
		vB_QuickEditor_Factory = new vB_QuickEditor_Factory();
	}
});

// #############################################################################
// vB_AJAX_QuickEditor
// #############################################################################

/**
* Class to allow quick editing of posts within postbit via AJAX
*
* @package	vBulletin
* @version	$Revision: 25662 $
* @date		$Date: 2008-02-04 14:33:20 -0800 (Mon, 04 Feb 2008) $
* @author	Kier Darby, vBulletin Development Team
*/
function vB_QuickEditor_Factory()
{
	this.editorcounter = 0;
	this.controls = new Array();
	this.open_objectid = null;

	this.init();
}

// =============================================================================
// vB_AJAX_QuickEditor methods

vB_QuickEditor_Factory.prototype.init = function()
{

	/*
	this.target = "editpost.php";
	this.objecttype = "p";
	this.getaction = "editpost";
	this.postaction = "updatepost";
	this.ajaxtarget = "ajax.php";
	this.ajaxaction = "quickedit";
	this.deleteaction = "deletepost";
	*/


	this.target = "blog_post.php";
	this.postaction = "postcomment";

	this.objecttype = "bt";
	this.getaction = "editcomment";

	this.ajaxtarget = "blog_ajax.php";
	this.ajaxaction = "quickeditcomment";
	this.deleteaction = "deleteblog";

	this.messagetype = "comment_text_";
	this.containertype = "comment";
	this.responsecontainer = "commentbits";

	if (vBulletin.elements["vB_QuickEdit"])
	{
		for (var i = 0; i < vBulletin.elements["vB_QuickEdit"].length; i++)
		{
			var objectid = vBulletin.elements["vB_QuickEdit"][i];
			var editbutton = YAHOO.util.Dom.get(this.containertype + "_edit_" + objectid);
			if (editbutton)
			{
				this.controls[objectid] = new vB_QuickEditor(objectid, this);
			}
		}
		vBulletin.elements["vB_QuickEdit"] = null;
	}
}

vB_QuickEditor_Factory.prototype.obj_init = function(objectid)
{
	// this comes from Quick_Comment and needs to be dealt with if Quick Comment is disabled.
	Comment_Init(YAHOO.util.Dom.get(this.containertype + objectid));
}

vB_QuickEditor_Factory.prototype.close_all = function()
{
	if (this.open_objectid)
	{
		// hide open edit
		this.controls[this.open_objectid].abort();
	}
}

// #############################################################################

/**
* Creates a single editable post object
*
* @package	vBulletin
* @version	$Revision: 24798 $
* @date		$Date: 2007-11-22 13:59:49 +0000 (Thu, 22 Nov 2007) $
* @author	Freddie Bingham, Kier Darby, vBulletin Development Team
*
* @param	string	Objectid of the message to be edited
* @param	vB_QuickEditor_Factory	Controlling factory class
*/
function vB_QuickEditor(objectid, factory)
{
	this.init(objectid, factory);
}

/**
* Initialize the onclick action
*
* @return	boolean
*/
vB_QuickEditor.prototype.init = function(objectid, factory)
{
	this.originalhtml = null;
	this.ajax_req = null;
	this.show_advanced = true;
	if (objectid)
	{
		this.objectid = objectid;
	}
	if (factory)
	{
		this.factory = factory;
	}
	this.messageobj = YAHOO.util.Dom.get(this.factory.messagetype + this.objectid);

	this.node = YAHOO.util.Dom.get(this.factory.containertype + this.objectid);
	this.progress_indicator = YAHOO.util.Dom.get(this.factory.containertype + "_progress_" + this.objectid);

	var editbutton = YAHOO.util.Dom.get(this.factory.containertype + "_edit_" + this.objectid);
	YAHOO.util.Event.on(editbutton, "click", this.edit, this, true);
}

/**
* Check if the AJAX system is ready for us to proceed
*
* @return	boolean
*/
vB_QuickEditor.prototype.ready = function()
{
	if (this.factory.open_objectid != null || YAHOO.util.Connect.isCallInProgress(this.ajax_req))
	{
		return false;
	}
	else
	{
		return true;
	}
};

/**
* Prepare to edit a single post
*
* @return	boolean	false
*/
vB_QuickEditor.prototype.edit = function(e)
{
	if (e)
	{
		YAHOO.util.Event.stopEvent(e);
	}

	// Don't believe this is needed
	if (typeof vb_disable_ajax != 'undefined' && vb_disable_ajax > 0)
	{
		// couldn't initialize, return true to allow click to go through
		return true;
	}

	if (YAHOO.util.Connect.isCallInProgress(this.ajax_req))
	{
		// something is waiting to complete
		return false;
	}
	else if (!this.ready())
	{
		if (this.objectid == this.factory.open_objectid)
		{
			this.full_edit();
			return false;
		}
		this.factory.close_all();
	}

	this.factory.open_objectid = this.objectid;
	this.factory.editorcounter++;
	this.editorid = 'vB_Editor_QE_' + this.factory.containertype + this.factory.editorcounter;

	this.originalhtml = this.messageobj.innerHTML;
	this.unchanged = null;
	this.unchanged_reason = null;

	this.fetch_editor();

	return false;
};

/**
* Send an AJAX request to fetch the editor HTML
*/
vB_QuickEditor.prototype.fetch_editor = function()
{
	if (this.progress_indicator)
	{
		this.progress_indicator.style.display = '';
	}
	document.body.style.cursor = 'wait';

	YAHOO.util.Connect.asyncRequest("POST", this.factory.ajaxtarget + "?do=" + this.factory.ajaxaction + "&" + this.factory.objecttype + "=" + this.objectid, {
		success: this.display_editor,
		failure: this.error_opening_editor,
		timeout: vB_Default_Timeout,
		scope: this
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=" + this.factory.ajaxaction + "&" + this.factory.objecttype + "=" + this.objectid + '&editorid=' + PHP.urlencode(this.editorid));
};

/**
* Handle unspecified AJAX server error when opening editor - opens full editor
*
* @param	object	YUI AJAX
*/
vB_QuickEditor.prototype.error_opening_editor = function(ajax)
{
	vBulletin_AJAX_Error_Handler(ajax);

	window.location = this.target + "?" + SESSIONURL + "do=" + this.getaction + "&" + this.objecttype + "=" + this.objectid;
}

/**
* Handle unspecified AJAX server error when saving
*
* @param	object	YUI AJAX
*/
vB_QuickEditor.prototype.handle_save_error = function(ajax)
{
	vBulletin_AJAX_Error_Handler(ajax);

	this.show_advanced = false;
	this.full_edit();
}

/**
* Display the editor HTML when AJAX says fetch_editor() is ready
*
* @param	object	YUI AJAX
*/
vB_QuickEditor.prototype.display_editor = function(ajax)
{
	if (ajax.responseXML)
	{
		if (this.progress_indicator)
		{
			this.progress_indicator.style.display = 'none';
		}

		document.body.style.cursor = 'auto';

		if (fetch_tag_count(ajax.responseXML, 'disabled'))
		{
			// this will fire if quick edit has been disabled after the showthread page is loaded
			window.location = this.failed_location + this.objectid;
		}
		else if (fetch_tag_count(ajax.responseXML, 'error'))
		{
			// do nothing
		}
		else
		{
			var editor = fetch_tags(ajax.responseXML, 'editor')[0];
			var reason = editor.getAttribute('reason');

			// display the editor
			this.messageobj.innerHTML = editor.firstChild.nodeValue;

			// display the reason
			var editreason = YAHOO.util.Dom.get(this.editorid + '_edit_reason')
			if (editreason)
			{
				this.unchanged_reason = PHP.unhtmlspecialchars(reason);
				editreason.value = this.unchanged_reason;
				editreason.onkeypress = vB_QuickEditor_Delete_Events.prototype.reason_key_trap;
			}

			// initialize the editor
			vB_Editor[this.editorid] = new vB_Text_Editor(
				this.editorid,
				editor.getAttribute('mode'),
				editor.getAttribute('parsetype'),
				editor.getAttribute('parsesmilies')
			);

			if (YAHOO.util.Dom.get(this.editorid + '_editor') && YAHOO.util.Dom.get(this.editorid + '_editor').scrollIntoView)
			{
				YAHOO.util.Dom.get(this.editorid + '_editor').scrollIntoView(true);
			}

			vB_Editor[this.editorid].set_editor_width('100%', true);
			vB_Editor[this.editorid].check_focus();

			this.unchanged = vB_Editor[this.editorid].get_editor_contents();

			YAHOO.util.Event.on(YAHOO.util.Dom.get(this.editorid + '_save'), "click", this.save, this, true);
			YAHOO.util.Event.on(YAHOO.util.Dom.get(this.editorid + '_abort'), "click", this.abort, this, true);
			YAHOO.util.Event.on(YAHOO.util.Dom.get(this.editorid + '_adv'), "click", this.full_edit, this, true);
			YAHOO.util.Event.on("quick_edit_errors_hide", "click", this.hide_errors, this, true);
			YAHOO.util.Event.on("quick_edit_errors_cancel", "click", this.abort, this, true);

			var delbutton = YAHOO.util.Dom.get(this.editorid + '_delete');
			if (delbutton)
			{
				YAHOO.util.Event.on(this.editorid + '_delete', "click", this.show_delete, this, true);
			}
		}
	}
};

/**
* Destroy the editor, and use the specified text as the post contents
*
* @param	string	Text of post
*/
vB_QuickEditor.prototype.restore = function(post_html, type)
{
	this.hide_errors(true);
	if (this.editorid && vB_Editor[this.editorid] && vB_Editor[this.editorid].initialized)
	{
		vB_Editor[this.editorid].destroy();
	}
	if (type == 'node')
	{
		// usually called when message is saved
		var newnode = string_to_node(post_html);
		this.node.parentNode.replaceChild(newnode, this.node);
	}
	else
	{
		// usually called when message edit is cancelled
		this.messageobj.innerHTML = post_html;
	}

	this.factory.open_objectid = null;
};

/**
* Cancel the post edit and restore everything to how it started
*
* @param	event	Event object
*/
vB_QuickEditor.prototype.abort = function(e)
{
	if (e)
	{
		YAHOO.util.Event.stopEvent(e);
	}

	if (this.progress_indicator)
	{
		this.progress_indicator.style.display = 'none';
	}
	document.body.style.cursor = 'auto';
	this.restore(this.originalhtml, 'messageobj');
};

/**
* Pass the edits along to the full editpost.php interface
*
* @param	event	Event object
*/
vB_QuickEditor.prototype.full_edit = function(e)
{
	if (e)
	{
		YAHOO.util.Event.stopEvent(e);
	}

	var form = new vB_Hidden_Form(this.factory.target + "?do=" + this.factory.postaction + "&" + this.factory.objecttype + "=" + this.objectid);

	form.add_variable('do', this.factory.postaction);
	form.add_variable('s', fetch_sessionhash());
	form.add_variable('securitytoken', SECURITYTOKEN);
	if (this.show_advanced)
	{
		// Don't preview - see blog_post.php if you want to know why
		form.add_variable('advanced', 1);
	}
	form.add_variable(this.factory.objecttype, this.objectid);
	form.add_variable('wysiwyg', vB_Editor[this.editorid].wysiwyg_mode);
	form.add_variable('message', vB_Editor[this.editorid].get_editor_contents());
	form.add_variable('reason', YAHOO.util.Dom.get(this.editorid + '_edit_reason').value);

	form.submit_form();
}

/**
* Save the edited post via AJAX
*
* @param	event	Event object
*/
vB_QuickEditor.prototype.save = function(e)
{
	YAHOO.util.Event.stopEvent(e);

	var newtext = vB_Editor[this.editorid].get_editor_contents();
	var newreason = YAHOO.util.Dom.get(this.editorid + '_edit_reason');

	if (newtext == this.unchanged && newreason && newreason.value == this.unchanged_reason)
	{	// this doesn't get fired
		this.abort(e);
	}
	else
	{
		YAHOO.util.Dom.get(this.editorid + '_posting_msg').style.display = '';
		document.body.style.cursor = 'wait';

		var pc_obj = YAHOO.util.Dom.get('postcount' + this.objectid);
		var linkobj = YAHOO.util.Dom.get('blog_entry_list');

		this.ajax_req = YAHOO.util.Connect.asyncRequest("POST", this.factory.target + "?do=" + this.factory.postaction + "&" + this.factory.objecttype + "=" + this.objectid, {
			success: this.update,
			failure: this.handle_save_error,
			timeout: vB_Default_Timeout,
			scope: this
		}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&do=" + this.factory.postaction + "&ajax=1&" + this.factory.objecttype + "="
			+ this.objectid
			+ '&wysiwyg=' + vB_Editor[this.editorid].wysiwyg_mode
			+ '&message=' + PHP.urlencode(newtext)
			+ '&reason=' + PHP.urlencode(YAHOO.util.Dom.get(this.editorid + '_edit_reason').value)
			+ (pc_obj != null ? '&postcount=' + PHP.urlencode(pc_obj.name) : '')
			+ (linkobj != null ? '&linkblog=1' : '')
		);

		this.pending = true;
	}
};

/**
* Show the delete dialog
*/
vB_QuickEditor.prototype.show_delete = function()
{
	this.deletedialog = YAHOO.util.Dom.get('quickedit_delete');
	if (this.deletedialog && this.deletedialog.style.display != '')
	{
		this.deletedialog.style.display = '';

		this.deletebutton = YAHOO.util.Dom.get('quickedit_dodelete')
		YAHOO.util.Event.on(this.deletebutton, "click", this.delete_post, this, true);

		var del_reason = YAHOO.util.Dom.get("del_reason")
		if (del_reason)
		{
			del_reason.onkeypress = vB_QuickEditor_Delete_Events.prototype.delete_items_key_trap;
		}

		// don't do this stuff for browsers that don't have any defined events
		// to detect changed radio buttons with keyboard navigation
		if (!is_opera && !is_saf)
		{
			this.deletebutton.disabled = true;
			this.deleteoptions = new Array();

			this.deleteoptions['leave'] = YAHOO.util.Dom.get('rb_del_leave');
			this.deleteoptions['soft'] = YAHOO.util.Dom.get('rb_del_soft');
			this.deleteoptions['hard'] = YAHOO.util.Dom.get('rb_del_hard');

			for (var i in this.deleteoptions)
			{
				if (YAHOO.lang.hasOwnProperty(this.deleteoptions, i) && this.deleteoptions[i])
				{
					this.deleteoptions[i].onclick = this.deleteoptions[i].onchange = vB_QuickEditor_Delete_Events.prototype.delete_button_handler;
					this.deleteoptions[i].onkeypress = vB_QuickEditor_Delete_Events.prototype.delete_items_key_trap;
				}
			}
		}
	}
};

/**
* Run the delete system
*/
vB_QuickEditor.prototype.delete_post = function()
{
	var dontdelete = YAHOO.util.Dom.get('rb_del_leave');
	if (dontdelete && dontdelete.checked)
	{
		this.abort();
		return;
	}

	var form = new vB_Hidden_Form(this.factory.target);

	form.add_variable('do', this.factory.deleteaction);
	form.add_variable('s', fetch_sessionhash());
	form.add_variable('securitytoken', SECURITYTOKEN);
	form.add_variable(this.factory.objecttype, this.objectid);
	form.add_variables_from_object(this.deletedialog);

	form.submit_form();
};

/**
* Check for errors etc. and initialize restore when AJAX says save() is complete
*
* @param	object	YUI AJAX
*
* @return	boolean	false
*/
vB_QuickEditor.prototype.update = function(ajax)
{
	if (ajax.responseXML)
	{
		this.pending = false;
		document.body.style.cursor = 'auto';
		YAHOO.util.Dom.get(this.editorid + '_posting_msg').style.display = 'none';

		// this is the nice error handler, of which Safari makes a mess
		if (fetch_tag_count(ajax.responseXML, 'error'))
		{
			var errors = fetch_tags(ajax.responseXML, 'error');

			var error_html = '<ol>';
			for (var i = 0; i < errors.length; i++)
			{
				error_html += '<li>' + errors[i].firstChild.nodeValue + '</li>';
			}
			error_html += '</ol>';

			this.show_errors('<ol>' + error_html + '</ol>');
		}
		else
		{
			var message = ajax.responseXML.getElementsByTagName("message");
			this.restore(message[0].firstChild.nodeValue, 'node');
			this.factory.obj_init(this.objectid);
		}
	}

	return false;
};

/**
* Pop up a window showing errors
*
* @param	string	Error HTML
*/
vB_QuickEditor.prototype.show_errors = function(errortext)
{
	set_unselectable("quick_edit_errors_hide");

	YAHOO.util.Dom.get('ajax_post_errors_message').innerHTML = errortext;
	var errortable = YAHOO.util.Dom.get('ajax_post_errors');
	errortable.style.width = '400px';
	errortable.style.zIndex = 500;
	var measurer = (is_saf ? 'body' : 'documentElement');
	errortable.style.left = (is_ie ? document.documentElement.clientWidth : self.innerWidth) / 2 - 200 + document[measurer].scrollLeft + 'px';
	errortable.style.top = (is_ie ? document.documentElement.clientHeight : self.innerHeight) / 2 - 150 + document[measurer].scrollTop + 'px';
	errortable.style.display = '';
};

/**
* Hide the error window
*/
vB_QuickEditor.prototype.hide_errors = function(skip_focus_check)
{
	this.errors = false;
	var errors = YAHOO.util.Dom.get("ajax_post_errors")
	if (errors)
	{
		errors.style.display = 'none';
	}
	if (skip_focus_check != true)
	{
		vB_Editor[this.editorid].check_focus();
	}
};

// =============================================================================
// vB_AJAX_QuickEditor Event Handlers

/**
* Class to handle quick editor events
*/
function vB_QuickEditor_Delete_Events()
{
}

/**
* Handles manipulation of form elements in the delete section
*/
vB_QuickEditor_Delete_Events.prototype.delete_button_handler = function(e)
{
	var open_objectid = vB_QuickEditor_Factory.open_objectid;
	var openobj = vB_QuickEditor_Factory.controls[open_objectid];

	if (this.id == 'rb_del_leave' && this.checked)
	{
		openobj.deletebutton.disabled = true;
	}
	else
	{
		openobj.deletebutton.disabled = false;
	}
}

/**
* Key trapper for reason box
*/
vB_QuickEditor_Delete_Events.prototype.reason_key_trap = function(e)
{
	var open_objectid = vB_QuickEditor_Factory.open_objectid;
	var openobj = vB_QuickEditor_Factory.controls[open_objectid];
	e = e ? e : window.event;

	switch (e.keyCode)
	{
		case 9: // tab
		{
			YAHOO.util.Dom.get(openobj.editorid + '_save').focus();
			return false;
		}
		break;

		case 13: // enter
		{
			openobj.save();
			return false;
		}
		break;

		default:
		{
			return true;
		}
	}
}

/**
* Key trapper for reason box
*/
vB_QuickEditor_Delete_Events.prototype.delete_items_key_trap = function(e)
{
	var open_objectid = vB_QuickEditor_Factory.open_objectid;
	var openobj = vB_QuickEditor_Factory.controls[open_objectid];
	e = e ? e : window.event;

	if (e.keyCode == 13) // enter
	{
		if (open_obj.deletebutton.disabled == false)
		{
			open_obj.delete_post();
		}
		return false;
	}

	return true;
}

/*======================================================================*\
|| ####################################################################
|| # Downloaded: 18:40, Mon Jun 15th 2009
|| # CVS: $RCSfile$ - $Revision: 25662 $
|| ####################################################################
\*======================================================================*/