/*!======================================================================*\
|| #################################################################### ||
|| # tk: Post Notes                                                   # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright Catnine Software 2009                                  # ||
|| #################################################################### ||
\*======================================================================*/

/**
* Register a post for ajax postnote
*
* @param	string	Postid
*
* @return	postnote_Object
*/
function postnote_register(postid)
{
	if (typeof vBpostnote == 'object' && typeof postid != 'undefined')
	{
		return vBpostnote.register(postid);
	}
};

// #############################################################################
// postnote_Handler
// #############################################################################

/**
* vBulletin postnote registry
*/
function postnote_Handler()
{
	this.postnotes = new Array();
	this.ajax = new Array();
};

// =============================================================================
// postnote_Handler methods

/**
* Register a control object as a postnote control
*
* @param	string	ID of the control object
*
* @return	postnote_Object
*/
postnote_Handler.prototype.register = function(postid)
{
	if (AJAX_Compatible && (typeof disable_ajax == 'undefined' || disable_ajax < 2))
	{
		this.postnotes[postid] = new postnote_Object(postid);
		var obj;
		if (obj = fetch_object('reputation_' + postid))
		{
			obj.onclick = postnote_Object.prototype.postnote_click;
			return this.postnotes[postid];
		}
	}
};

// #############################################################################
// initialize postnote registry

vBpostnote = new postnote_Handler();

// #############################################################################
// postnote_Object
// #############################################################################

/**
* vBulletin postnote class constructor
*
* Manages a single postnote and control object
* Initializes control object
*
* @param	string	postid
*/
function postnote_Object(postid)
{
	this.postid = postid;
	this.divname = 'reputationmenu_' + postid + '_menu';
	this.divobj = null;
	this.postobj = fetch_object('post' + postid);

	this.vbmenuname = 'reputationmenu_' + postid;
	this.vbmenu = null;

	this.xml_sender_populate = null;
	this.xml_sender_submit = null;
}

/**
* Submit OnReadyStateChange callback. Uses a closure to keep state.
*/
postnote_Object.prototype.onreadystatechange_submit = function(ajax)
{
	if (ajax.responseXML)
	{
		// Register new menu item for this postnote icon
		if (!this.vbmenu)
		{
			this.vbmenu = vbmenu_register(this.vbmenuname, true);
			// Remove menu's mouseover event
			fetch_object(this.vbmenu.controlkey).onmouseover = '';
			fetch_object(this.vbmenu.controlkey).onclick = '';
		}
		else
		{
            this.vbmenu.hide(fetch_object(this.vbmenuname));
        }
        
		// check for error first
		var error = ajax.responseXML.getElementsByTagName('error');
		if (error.length)
		{
			this.vbmenu.hide(fetch_object(this.vbmenuname));
			alert(error[0].firstChild.nodeValue);
		}
		else
		{
    		var postid = ajax.responseXML.getElementsByTagName("postid")[0];
    		var rep = ajax.responseXML.getElementsByTagName("rep")[0];
    		var cell0 = ajax.responseXML.getElementsByTagName("cell0")[0];
    		var cell1 = ajax.responseXML.getElementsByTagName("cell1")[0];
    		var cell1 = ajax.responseXML.getElementsByTagName("cell1")[0];
    		var clr = ajax.responseXML.getElementsByTagName("clr")[0].firstChild.data;
    		var bclr = ajax.responseXML.getElementsByTagName("bclr")[0].firstChild.data;
    		var legend = ajax.responseXML.getElementsByTagName("legend")[0].firstChild.data;
    		if (ajax.responseXML.getElementsByTagName("cell2"))
    		{
    			var cell2 = ajax.responseXML.getElementsByTagName("cell2")[0];
    		}
    		var tableid = 'postnote_table_' + postid.firstChild.data;
    		var postdivid = 'post_message_' + postid.firstChild.data;
    		
            var oTable = document.getElementById(tableid);
            if (!oTable)
            {
                oDiv = document.getElementById(postdivid);
                oDiv.appendChild(document.createElement('br'));
                oDiv.appendChild(document.createElement('br'));
                oFS = document.createElement('fieldset');
                oFS.setAttribute("class", "fieldset");
                oFS.setAttribute("style", "border-color:#DDDDDD;");
                oLeg = document.createElement('legend');
                oLeg.innerHTML = legend;
                oFS.appendChild(oLeg);
                oTable = document.createElement('table');
                oTable.setAttribute("id", tableid);
                oTable.setAttribute("style", "width: 100%;");
                oTable.setAttribute("cellpadding", "0");
                oTable.setAttribute("cellspacing", "0");
                oFS.appendChild(oTable);
                oDiv.appendChild(oFS);
            }

            var newRow = oTable.insertRow(-1);
            if (cell2)
            {
                var oCell0 = newRow.insertCell(-1);
            	   oCell0.innerHTML = cell0.firstChild.data;
            	   var oCell1 = newRow.insertCell(-1);
            	   oCell1.setAttribute("style", "vertical-align: center; text-align: left;");
            	   oCell1.noWrap = true;
            	   oCell1.innerHTML = cell1.firstChild.data;
            	   var oCell2 = newRow.insertCell(-1);
            	   oCell2.className = 'alt1';
            	   oCell2.setAttribute("style", "text-align: left; width: 100%;");
            	   oCell2.innerHTML = cell2.firstChild.data;
            }
            else
            {
                var oCell0 = newRow.insertCell(-1);
                oCell0.setAttribute("style", "vertical-align: center; text-align: left; background-color: " + bclr + "; color: " + clr + ";");
                oCell0.style.backgroundColor = bclr;
                oCell0.style.color = clr;
                oCell0.noWrap = true;
                oCell0.innerHTML = cell0.firstChild.data;
                var oCell1 = newRow.insertCell(-1);
                oCell1.className = 'alt1';
                oCell1.setAttribute("style", "text-align: left; width: 100%;");
                oCell1.setAttribute("colspan", "2");
                oCell1.innerHTML = cell1.firstChild.data;
        	}
        }
	}
}

/**
* Populate OnReadyStateChange callback. Uses a closure to keep state.
*/
postnote_Object.prototype.onreadystatechange_populate = function(ajax)
{
	if (ajax.responseXML)
	{
		// check for error first
		var error = ajax.responseXML.getElementsByTagName('error');
		if (error.length)
		{
			alert(error[0].firstChild.nodeValue);
		}
		else
		{
			if (!this.divobj)
			{
				// Create new div to hold postnote menu html
				this.divobj = document.createElement('div');
				this.divobj.id = this.divname;
				this.divobj.style.display = 'none';
				this.divobj.onkeypress = postnote_Object.prototype.postnoteinput_onkeypress; //TODO
				this.postobj.parentNode.appendChild(this.divobj);

				this.vbmenu = vbmenu_register(this.vbmenuname, true);

				// Remove menu's mouseover event
				fetch_object(this.vbmenu.controlkey).onmouseover = '';
				fetch_object(this.vbmenu.controlkey).onclick = '';
			}

			this.divobj.innerHTML = ajax.responseXML.getElementsByTagName('reputationbit')[0].firstChild.nodeValue;

			var inputs = fetch_tags(this.divobj, 'input');
			for (var i = 0; i < inputs.length; i++)
			{
				if (inputs[i].type == 'submit')
				{
					var sbutton = inputs[i];
					var button = document.createElement('input');
					button.type = 'button';
					button.className = sbutton.className;
					button.value = sbutton.value;
					button.onclick = postnote_Object.prototype.submit_onclick;
					sbutton.parentNode.insertBefore(button, sbutton);
					sbutton.parentNode.removeChild(sbutton);
					button.name = sbutton.name;
					button.id = sbutton.name + '_' + this.postid
				}
			}

			this.vbmenu.show(fetch_object(this.vbmenuname));
		}
	}
}

/**
* Handles click events on postnote icon
*/
postnote_Object.prototype.postnote_click = function (e)
{
	e = e ? e : window.event;

	do_an_e(e);
	var postid = this.id.substr(this.id.lastIndexOf('_') + 1);
	var postnoteobj = vBpostnote.postnotes[postid];

	// fetch and return postnote html
	if (postnoteobj.vbmenu == null)
	{
		postnoteobj.populate();
	}
	else if (vBmenu.activemenu != postnoteobj.vbmenuname)
	{
		postnoteobj.vbmenu.show(fetch_object(postnoteobj.vbmenuname));
	}
	else
	{
		postnoteobj.vbmenu.hide();
	}

	return true;
}

/**
* Handles click events on postnote submit button
*/

postnote_Object.prototype.submit_onclick = function (e)
{
	e = e ? e : window.event;
	do_an_e(e);

	var postid = this.id.substr(this.id.lastIndexOf('_') + 1);
	var postnoteobj = vBpostnote.postnotes[postid];
	postnoteobj.submit();

	return false;
}

/**
*	Catches the keypress of the postnote controls to keep them from submitting to inlineMod
*/
postnote_Object.prototype.postnoteinput_onkeypress = function (e)
{
	e = e ? e : window.event;

	switch (e.keyCode)
	{
		case 13:
		{
			vBpostnote.postnotes[this.id.split(/_/)[1]].submit();
			return false;
		}
		default:
		{
			return true;
		}
	}
}

/**
* Queries for proper response to postnote, response varies
*
*/
postnote_Object.prototype.populate = function()
{
	YAHOO.util.Connect.asyncRequest("POST", "reputation.php?postid=" + this.postid, {
		success: this.onreadystatechange_populate,
		failure: this.handle_ajax_error,
		timeout: 15000,
		scope: this
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&postid=" + this.postid + "&ajax=1");
}

/**
* Handles AJAX Errors
*
* @param	object	YUI AJAX
*/
postnote_Object.prototype.handle_ajax_error = function(ajax)
{
	//TODO: Something bad happened, try again
	vBulletin_AJAX_Error_Handler(ajax);
};

/**
* Submits postnote
*
*/
postnote_Object.prototype.submit = function()
{
	this.psuedoform = new vB_Hidden_Form('reputation.php');
	this.psuedoform.add_variable('ajax', 1);
	this.psuedoform.add_variables_from_object(this.divobj);

	YAHOO.util.Connect.asyncRequest("POST", "reputation.php?do=addpostnote&p=" + this.psuedoform.fetch_variable('p'), {
		success: this.onreadystatechange_submit,
		failure: vBulletin_AJAX_Error_Handler,
		timeout: 15000,
		scope: this
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&" + this.psuedoform.build_query_string());
}

/*======================================================================*\
|| ####################################################################
|| # Downloaded: 04:08, Tue Mar 10th 2009
|| # CVS: $RCSfile$ - $Revision: 26385 $
|| ####################################################################
\*======================================================================*/