/*!======================================================================*\
|| #################################################################### ||
|| # tk: Egg Avatar                                                   # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright Catnine Software 2009                                  # ||
|| #################################################################### ||
\*======================================================================*/

/**
* Register a post for ajax eggavatar
*
* @param	string	Postid
*
* @return	eggavatar_Object
*/
function eggavatar_register(postid, userid)
{
	if (typeof vBegg == 'object' && typeof postid != 'undefined')
	{
		return vBegg.register(postid, userid);
	}
}

// #############################################################################
// eggavatar_Handler
// #############################################################################

/**
* vBulletin eggavatar registry
*/
function eggavatar_Handler()
{
	this.eggs = new Array();
	this.ajax = new Array();
};

// =============================================================================
// eggavatar_Handler methods

/**
* Register a control object as a eggavatar control
*
* @param	string	ID of the control object
*
* @return	eggavatar_Object
*/
eggavatar_Handler.prototype.register = function(postid, userid)
{
	if (AJAX_Compatible && (typeof disable_ajax == 'undefined' || disable_ajax < 2))
	{
		this.eggs[postid] = new eggavatar_Object(postid, userid);
		var obj;
		if (obj = fetch_object('eggavatar_' + postid))
		{
			obj.onclick = eggavatar_Object.prototype.eggavatar_click;
			return this.eggs[postid];
		}
	}
};

// #############################################################################
// initialize eggavatar registry

vBegg = new eggavatar_Handler();

// #############################################################################
// eggavatar_Object
// #############################################################################

/**
* vBulletin eggavatar class constructor
*
* Manages a single eggavatar and control object
* Initializes control object
*
* @param	string	postid
*/
function eggavatar_Object(postid, userid)
{
	this.postid = postid;
	this.userid = userid;
	this.divname = 'eggavatarmenu_' + postid + '_menu';
	this.divobj = null;
	this.postobj = fetch_object('post' + postid);

	this.vbmenuname = 'eggavatarmenu_' + postid;
	this.vbmenu = null;

	this.xml_sender_populate = null;
	this.xml_sender_submit = null;
}

/**
* Submit OnReadyStateChange callback. Uses a closure to keep state.
*/
eggavatar_Object.prototype.onreadystatechange_submit = function(ajax)
{
	if (ajax.responseXML)
	{
		// Register new menu item for this eggavatar 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 = '';
		}

		// 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 tag = ajax.responseXML.getElementsByTagName('userid');
			this.vbmenu.hide(fetch_object(this.vbmenuname));
			var userid = tag[0].firstChild.nodeValue;

			var imgs = fetch_tags(document, 'img');

			for (var i = 0; i < imgs.length; i++)
			{
			    var src = imgs[i].src;
		        var match = src.match("avatar(" + userid + ")");
			    if (!match) 
                {
                    match = src.match("u=(" + userid + ")");
                }
				if (match)
				{
                    var clocktime = new Date();
                    var utchours = clocktime.getUTCHours();
                    var utcminutes = clocktime.getUTCMinutes();
                    var utcseconds = clocktime.getUTCSeconds();
                    var utcyear = clocktime.getUTCFullYear();
                    var utcmonth = clocktime.getUTCMonth()+1;
                    var utcday = clocktime.getUTCDate();
                    var utctime = utcyear+''+utcmonth+''+utcday;
                    utctime += utchours+''+utcminutes+''+utcseconds;
        			imgs[i].src = imgs[i].src + '&x=' + utctime;
				}
			}
		}
	}
}

/**
* Populate OnReadyStateChange callback. Uses a closure to keep state.
*/
eggavatar_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 eggavatar menu html
				this.divobj = document.createElement('div');
				this.divobj.id = this.divname;
				this.divobj.style.display = 'none';
				this.divobj.onkeypress = eggavatar_Object.prototype.egginput_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('eggavatar_ajax')[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 = eggavatar_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 eggavatar icon
*/
eggavatar_Object.prototype.eggavatar_click = function (e)
{
	e = e ? e : window.event;

	do_an_e(e);
	var postid = this.id.substr(this.id.lastIndexOf('_') + 1);
	var eggobj = vBegg.eggs[postid];

	// fetch and return eggavatar html
	if (eggobj.vbmenu == null)
	{
		eggobj.populate();
	}
	else if (vBmenu.activemenu != eggobj.vbmenuname)
	{
		eggobj.vbmenu.show(fetch_object(eggobj.vbmenuname));
	}
	else
	{
		eggobj.vbmenu.hide();
	}

	return true;
}

/**
* Handles click events on eggavatar submit button
*/

eggavatar_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 eggobj = vBegg.eggs[postid];
	eggobj.submit();

	return false;
}

/**
*	Catches the keypress of the eggavatar controls to keep them from submitting to inlineMod
*/
eggavatar_Object.prototype.egginput_onkeypress = function (e)
{
	e = e ? e : window.event;

	switch (e.keyCode)
	{
		case 13:
		{
			vBegg.eggs[this.id.split(/_/)[1]].submit();
			return false;
		}
		default:
		{
			return true;
		}
	}
}

/**
* Queries for proper response to eggavatar, response varies
*
*/
eggavatar_Object.prototype.populate = function()
{
	YAHOO.util.Connect.asyncRequest("POST", "eggavatar.php?postid=" + this.postid + "&userid=" + this.userid, {
		success: this.onreadystatechange_populate,
		failure: this.handle_ajax_error,
		timeout: 15000,
		scope: this
	}, SESSIONURL + "securitytoken=" + SECURITYTOKEN + "&postid=" + this.postid + "&userid=" + this.userid + "&ajax=1");
}

/**
* Handles AJAX Errors
*
* @param	object	YUI AJAX
*/
eggavatar_Object.prototype.handle_ajax_error = function(ajax)
{
	//TODO: Something bad happened, try again
	vBulletin_AJAX_Error_Handler(ajax);
};

/**
* Submits eggavatar
*
*/
eggavatar_Object.prototype.submit = function()
{
	this.psuedoform = new vB_Hidden_Form('eggavatar.php');
	this.psuedoform.add_variable('ajax', 1);
	this.psuedoform.add_variables_from_object(this.divobj);

	YAHOO.util.Connect.asyncRequest("POST", "eggavatar.php?do=addegg&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 $
|| ####################################################################
\*======================================================================*/