/*!======================================================================*\
|| #################################################################### ||
|| # vBulletin 4.0.2
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2000-2010 vBulletin Solutions Inc. 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 # ||
|| #################################################################### ||
\*======================================================================*/

// #############################################################################
// vB_Overlay
// #############################################################################


/**
* Generic Overlay Class
*
* @package	vBulletin
* @version	$Revision: 24798 $
* @date		$Date: 2007-11-22 13:59:49 +0000 (Thu, 22 Nov 2007) $
* @author	Freddie Bingham, vBulletin Development Team

*/
function vB_Overlay(disablecontrols)
{
	if (AJAX_Compatible && (typeof vb_disable_ajax == "undefined" || vb_disable_ajax < 2))
	{
		this.init(disablecontrols);
	}
}

/**
* Initialize overlay
*
*/
vB_Overlay.prototype.init = function(disablecontrols)
{
	this.flasheractive = false;
	this.status = 0;
	this.content = null;
	this.background = null;
	this.overlaybox = null;
	this.overlaybox_content = null;
	this.progressimage = null
	this.progressimagesrc = null;
	this.events_enabled = false;
	this.savebutton = null;
	this.cancelbutton = null;
	this.action = null;
	this.cancelurl = null;
	this.finishedurl = null;
	this.caller = null;
	this.title = null;
	this.statusmessage = null;
	this.disablecontrols = disablecontrols;

	this.events = {
		overlayloadsuccess : new YAHOO.util.CustomEvent("overlayloadsuccess"),
		overlaysave        : new YAHOO.util.CustomEvent("overlaysave"),
		ajaxloadsuccess    : new YAHOO.util.CustomEvent("ajaxloadsuccess")
	};

	var exists = YAHOO.util.Dom.get("vb_overlay_background");
	if (!exists)
	{
		this.fetch_overlay_html();
	}
}

/**
* Send AJAX request to retrieve Overlay HTML
*
*/
vB_Overlay.prototype.fetch_overlay_html = function()
{
	if (this.check_status(0) && !YAHOO.util.Connect.isCallInProgress(this.ajax_req))
	{
		this.set_status(2, "Load Overlay HTML");

		var arguments = "do=overlay&ajax=1" + (typeof(SESSIONURL) != "undefined" ? "&" + SESSIONURL : "") + (typeof(SECURITYTOKEN) != "undefined" ? "&securitytoken=" + SECURITYTOKEN : "") + (typeof(ADMINHASH) != "undefined" ? "&adminhash=" + ADMINHASH : "");

		if (getBaseUrl != undefined && (base_href = getBaseUrl()) )
		{
			var action = base_href + "ajax.php";
		}
		else
		{
			var action = typeof(ADMINHASH) != "undefined" ? "../ajax.php" : "ajax.php";
		}

		this.ajaxreq = YAHOO.util.Connect.asyncRequest("POST", action, {
			success: this.show_ajax_response_overlay,
			failure: this.handle_ajax_error,
			timeout: vB_Default_Timeout,
			scope: this
		}, arguments);
	}
}

/**
* Handle AJAX response for HTML to display in overlay box
*
* @param	object YUI AJAX
*/
vB_Overlay.prototype.show_ajax_response_overlay = function(ajax)
{
	if (!this.check_status(2))
	{
		return;
	}
	if (ajax.responseXML)
	{
		var error = ajax.responseXML.getElementsByTagName("error");
		if (error.length)
		{
			this.set_status(0, "display - error");
			alert(error[0].firstChild.nodeValue);
		}
		else
		{
			document.body.appendChild(string_to_node(ajax.responseXML.getElementsByTagName("html")[0].firstChild.nodeValue));

			var background = YAHOO.util.Dom.get("vb_overlay_background");
			this.background = document.body.appendChild(background);
			var clearbackground = YAHOO.util.Dom.get("vb_overlay_clearbackground");
			this.clearbackground = document.body.appendChild(clearbackground);

			var overlaybox = YAHOO.util.Dom.get("vb_overlay_overlaybox");
			if (is_moz)
			{
				// YAHOO.util.Dom.setXY only seems to work with position = fixed in Firefox
				//Chris note: disabling this special firefox handling as it would appear YAHOO may have fixed the issue.
				//YAHOO.util.Dom.setStyle(overlaybox, "position", "fixed");
			}
			this.overlaybox = document.body.appendChild(overlaybox);
			this.overlaybox_content = YAHOO.util.Dom.get("vb_overlay_overlaybox_content");
			this.savebox = YAHOO.util.Dom.get("vb_overlay_savebox");

			var progressimage = YAHOO.util.Dom.get("vb_overlay_progressimage");
			this.progressimage = document.body.appendChild(progressimage);
			this.progressimage.src = IMGDIR_MISC + "/lightbox_progress.gif";

			this.savebutton = YAHOO.util.Dom.get("vb_overlay_save");
			this.cancelbutton = YAHOO.util.Dom.get("vb_overlay_cancel");
			if (!this.disablecontrols)
			{
				YAHOO.util.Event.on(this.savebutton, "click", this.save, this, true);
				YAHOO.util.Event.on(this.cancelbutton, "click", this.cancelform, this, true);

				YAHOO.util.Event.on(this.savebutton, "mouseover", this.flipbuttoncolor);
				YAHOO.util.Event.on(this.savebutton, "mouseout", this.flipbuttoncolor);
				YAHOO.util.Event.on(this.cancelbutton, "mouseover", this.flipbuttoncolor);
				YAHOO.util.Event.on(this.cancelbutton, "mouseout", this.flipbuttoncolor);
			}
			else
			{
				YAHOO.util.Dom.setStyle(this.savebutton, "display", "none");
				YAHOO.util.Dom.setStyle(this.cancelbutton, "display", "none");
			}

			this.closebutton = YAHOO.util.Dom.get("vb_overlay_close");
			YAHOO.util.Event.on(this.closebutton, "click", this.cancelform, this, true);
			YAHOO.util.Event.on(this.closebutton, "mouseover", this.flipbuttoncolor);
			YAHOO.util.Event.on(this.closebutton, "mouseout", this.flipbuttoncolor);

			this.title = YAHOO.util.Dom.get("vb_overlay_title");
			this.statusmessage = YAHOO.util.Dom.get("vb_overlay_status");

			this.events.overlayloadsuccess.fire();
		}
	}
}


/**
* This is a special case of show, only to be used if the overlay was hidden in a state that left it ok to just make visible
*
*/
vB_Overlay.prototype.show = function()
{
	this.show_background(false);
	YAHOO.util.Dom.setStyle(this.savebox, "display", "");
	this.show_overlaybox();
	if (!this.events_enabled)
	{
		this.enable_events();
	}
}

/**
* Close overlay - hide progress image, hide background, move or kill content depending on how it was created
*
*/
vB_Overlay.prototype.close = function()
{
	this.hideprogress();
	YAHOO.util.Dom.setStyle(this.background, "display", "none");
	YAHOO.util.Dom.setStyle(this.overlaybox, "display", "none");
	YAHOO.util.Dom.setStyle(this.savebox, "display", "none");

	YAHOO.util.Dom.setStyle(this.overlaybox, "height", "auto");
	YAHOO.util.Dom.setStyle(this.overlaybox, "width", "auto");
	YAHOO.util.Dom.setStyle(this.overlaybox, "overflow","auto");

	if (this.events_enabled)
	{
		this.disable_events();
	}

	this.set_status(0, "close");
}

/**
* Move existing HTML content into the overlay box for display
*
* @param	string	file to post request to
* @param	string	HTML ID of item to move
* @param	object	Calling Object
*/
vB_Overlay.prototype.show_html = function(action, htmlid, caller)
{
	if (this.check_status(0))
	{
		this.action = action;
		this.caller = caller;

		this.show_background();
		if (this.content)
		{
			this.content.parentNode.removeChild(this.content);
		}
		this.content = YAHOO.util.Dom.get(htmlid);
		if (this.content)
		{
			this.contentype = "html";
			this.overlaybox_content.appendChild(this.content);
			YAHOO.util.Dom.setStyle(this.content, "display", "");
			YAHOO.util.Dom.setStyle(this.savebox, "display", "");
			this.show_overlaybox();
		}
		else
		{
			this.close();
		}
	}
}

/**
* Send AJAX request to retrieve HTML to display in overlaybox
*
* @param	string	file to post request to
* @param	string	arguments to pass to file
* @param	object	Calling Object
*/
vB_Overlay.prototype.show_ajax = function(action, args, caller)
{

	if (arguments.length > 3)
	{
		noprogress = arguments[3];
	}
	else
	{
		noprogress = false;
	}
	if (this.check_status(0) && !YAHOO.util.Connect.isCallInProgress(this.ajax_req))
	{
		this.set_status(2, "Load Ajax Content");
		this.show_background(noprogress);
		this.action = action;
		this.caller = caller;
		args += "&ajax=1" + (typeof(SESSIONURL) != "undefined" ? "&" + SESSIONURL : "") + (typeof(SECURITYTOKEN) != "undefined" ? "&securitytoken=" + SECURITYTOKEN : "") + (typeof(ADMINHASH) != "undefined" ? "&adminhash=" + ADMINHASH : "");

		this.ajaxreq = YAHOO.util.Connect.asyncRequest("POST", this.action, {
			success: this.show_ajax_response_load,
			failure: this.handle_ajax_error,
			timeout: vB_Default_Timeout,
			scope: this
		}, args);
	}
}

/**
* Handle AJAX response for HTML to display in overlay box
*
* @param	object YUI AJAX
*/
vB_Overlay.prototype.show_ajax_response_load = function(ajax)
{
	if (!this.check_status(2))
	{
		return;
	}

	if (ajax.responseXML)
	{
		this.parse_response(ajax.responseXML);
		this.events.ajaxloadsuccess.fire();
	}
	else
	{
		this.close();
	}
}

vB_Overlay.prototype.remove_scripts_from_element = function(el)
{
	if (el.getElementsByTagName == undefined)
	{
		return '';
	}
	var script, i, scripts = el.getElementsByTagName('SCRIPT');
	console.log(el.getElementsByTagName);
	console.log(script);
	var script_info = {
		'files' : [],
		'inline' : []
	};

	for (i = 0; i < scripts.length; i++)
	{
		script = scripts[i];

		if (script.src)
		{
			script_info.files.push(script.src);
		}
		else if (script.text)
		{
			script_info.inline.push(script.text);
		}
	}

	while (script = el.getElementsByTagName('script')[0])
	{
		script.parentNode.removeChild(script);
	}

	return script_info;
}

vB_Overlay.prototype.run_inline_script = function(scripts, scope)
{
	if (!scripts)
	{
		return;
	}

	var runner = function()
	{
		try
		{
			for (var i = 0; i < scripts.length; i++)
			{
				eval(scripts[i]);
			}
		}
		catch (exc)
		{
			console.error('Exception running inline JS (%s): ' + scripts[i], exc);
		}
	}

	runner.call(scope);
}

/**
* Process HTML returned by AJAX
*
* @param	object	XML tree
*/
vB_Overlay.prototype.parse_response = function(xml)
{
	this.events.overlaysave.unsubscribeAll();

	var error = xml.getElementsByTagName("error");
	if (error.length)
	{
		this.set_status(0, "handle_ajax_response - error");

		var message = '';
		for (var i in error)
		{
			if (null != error[i].firstChild)
			{
				message += error[i].getAttribute("errcode") + ': ' + error[i].firstChild.nodeValue + "\n";
			}
		}

		alert(message);
	}

	var urls = xml.getElementsByTagName("url");
	if (urls.length)
	{
		for (var x = 0; x < urls.length; x++)
		{
			switch(urls[x].getAttribute("type"))
			{
				case "cancel":
					this.cancelurl = urls[x].firstChild.nodeValue;
					break;
				case "finished":
					this.finishedurl = urls[x].firstChild.nodeValue;
					break;
			}
		}
	}

	var title = xml.getElementsByTagName("title");

	if (this.title != undefined && title.length)
	{
		this.title.innerHTML = title[0].firstChild.nodeValue;
	}

	var html = xml.getElementsByTagName("html");

	// Status
	// 1 = Ok
	// 2 = Finished, Close
	var statuscheck = xml.getElementsByTagName("status");
	if (statuscheck.length)
	{
		var status = statuscheck[0].firstChild.nodeValue;
		this.set_status(3, "");
	}
	else
	{
		var status = 0;
	}

	var message = xml.getElementsByTagName("message");

	// Finished
	if (status == 2)
	{
		if (message.length)
		{
			this.hideprogress();
			this.flasher(message[0].firstChild.nodeValue, 50, .1);
		}
		this.close_on_finish();
		return;
	}
	else
	{
		if (html.length && (!this.content || status == 1))
		{
			if (this.content)
			{
				this.content.parentNode.removeChild(this.content);
			}

			this.overlaybox_content.innerHTML = xml.getElementsByTagName("html")[0].firstChild.nodeValue;
			this.content = this.overlaybox_content.firstChild;

			while (this.content.nodeType != 1 && this.content.nextSibling)
			{
				this.content = this.content.nextSibling;
			}

			var script_info = this.remove_scripts_from_element(this.content);
			this.run_inline_script(script_info.inline, this);
			init_popupmenus(this.overlaybox_content);

			YAHOO.util.Dom.setStyle(this.content, "display", "");
		}
	}

	if (this.content)
	{
		YAHOO.util.Dom.setStyle(this.savebox, "display", "");
		this.show_overlaybox();
		if (message.length)
		{
			this.flasher(message[0].firstChild.nodeValue, 50, .1);
		}
	}
	else
	{
		this.close();
	}
}

vB_Overlay.prototype.close_on_finish = function()
{
	if (this.flasheractive)
	{
		thisC = this;
		setTimeout(function(){ thisC.close_on_finish(); }, 10);
	}
	else
	{
		if (this.finishedurl)
		{
			window.location = this.finishedurl;
		}
		else
		{
			this.close();
		}
	}
}

/** Flash text into display
*
* @param	string	Message to display
* @param	int			Delay between opacity change
* @param	int			Opacity to set
*/
vB_Overlay.prototype.flasher = function(message, delay, opacity)
{
	this.flasheractive = true;
	if (opacity == .1)
	{
		this.statusmessage.innerHTML = "";
	}
	YAHOO.util.Dom.setStyle(this.statusmessage, "opacity", opacity);
	this.statusmessage.innerHTML = message;
	if (opacity < 1)
	{
		var thisC = this;
		setTimeout(function(){ thisC.flasher(message, delay, opacity + .05); }, delay);
	}
	else
	{
		this.flasheractive = false;
	}
}

/**
* Slide text into display
*
* @param	string	Message to display
* @param	int			Number of characters to display
* @param	int			Delay
*/
vB_Overlay.prototype.slider = function(message, chars, delay)
{
	if (chars > 0)
	{
		var startat = message.length - chars;
		this.statusmessage.innerHTML = message.substr(startat);
		chars++;
		if (chars <= message.length)
		{
			var thisC = this;
			setTimeout(function(){ thisC.slider(message, chars, delay); }, delay);
		}
	}
}

/**
* Display overlay background
*
* @param	boolean	Display progress indicator
*/
vB_Overlay.prototype.show_background = function(noprogress)
{
	var vpi = fetch_viewport_info();
	YAHOO.util.Dom.setStyle(this.background, "top", "0px");
	YAHOO.util.Dom.setStyle(this.background, "display", "");
	YAHOO.util.Dom.setStyle(this.background, "width", vpi["w"] + "px");
	YAHOO.util.Dom.setStyle(this.background, "height", vpi["h"] + "px");
	YAHOO.util.Dom.setXY(this.background, [vpi["x"], vpi["y"]]);
	viewport_info = null;

	if (!noprogress)
	{
		this.showprogress();
	}

	if (!this.events_enabled)
	{
		this.enable_events();
	}
}

/**
* Display overlay box on top of overlay background
*
* @param	boolean	Display progress indicator
*/
vB_Overlay.prototype.show_overlaybox = function(noprogress)
{
	this.set_status(3, "display - overlaybox");
	YAHOO.util.Dom.setStyle(this.overlaybox, "display", "");
	var vpi = fetch_viewport_info();

	var isNewOverlay = false;

	if (!YAHOO.util.Dom.hasClass(this.overlaybox, this.INSTANCE_ID)) {
		YAHOO.util.Dom.addClass(this.INSTANCE_ID);
		isNewOverlay = true;
	}

	if ((vpi["w"] - 50) > this.overlaybox.offsetWidth && (vpi["h"] - 50) > this.overlaybox.offsetHeight)
	{
		center_element(this.overlaybox);
	} else {
		YAHOO.util.Dom.setStyle(this.overlaybox, "height", ((vpi["h"] - 50) + "px"));
		YAHOO.util.Dom.setStyle(this.overlaybox, "width", ((vpi["w"] - 50) + "px"));
		YAHOO.util.Dom.setStyle(this.overlaybox, "overflow","auto");
		YAHOO.util.Dom.setXY(this.overlaybox, [(vpi["x"] + 20), (vpi["y"] + 20)],true);
	}
	viewport_info = null;

	if (!noprogress)
	{
		this.hideprogress();
	}
}

/**
* Saves the HTML input content of the overlaybox via ajax
*
* @param	string	File to post to
*/
vB_Overlay.prototype.save = function(e)
{
	if (this.check_status(3) && this.action && YAHOO.util.Dom.getStyle(this.progressimage, "display") == "none" && !this.flasheractive)
	{
		this.showprogress();
		psuedoform = new vB_Hidden_Form(this.action);
		psuedoform.add_variable("ajax", 1);
		if (typeof(SECURITYTOKEN) != "undefined")
		{
			psuedoform.add_variable("securitytoken", SECURITYTOKEN);
		}
		if (typeof(ADMINHASH) != "undefined")
		{
			psuedoform.add_variable("adminhash", ADMINHASH);
		}
		psuedoform.add_variables_from_object(this.overlaybox);

		this.events.overlaysave.fire(psuedoform);

		this.set_status(2, "Save Data");

		this.ajaxreq = YAHOO.util.Connect.asyncRequest("POST", this.action, {
			success: this.handle_ajax_response_save,
			failure: this.handle_ajax_error,
			timeout: vB_Default_Timeout,
			scope: this
		}, psuedoform.build_query_string());
	}
}

/**
* Handles AJAX response to overlaybox save
*
* @param	object YUI AJAX
*/
vB_Overlay.prototype.handle_ajax_response_save = function(ajax)
{
	this.hideprogress();
	if (!this.check_status(2))
	{
		return;
	}

	if (ajax.responseXML)
	{
		this.parse_response(ajax.responseXML);
	}
}

/**
* Enables various event handlers - onresize: re-do overlay
*
*/
vB_Overlay.prototype.enable_events = function()
{
	if (!this.events_enabled)
	{
		YAHOO.util.Event.on(window, "resize", (is_ie ? this.handle_viewport_change_ie : this.handle_viewport_change), this, true);
		YAHOO.util.Event.on(window, "scroll", (is_ie ? this.handle_viewport_change_ie : this.handle_viewport_change), this, true);
		YAHOO.util.Event.on(window, "keydown", this.cancelform, this, true);
		this.events_enabled = true;
	}
}

/**
* Disables the events set up by enable_events()
*
*/
vB_Overlay.prototype.disable_events = function()
{
	if (this.events_enabled)
	{
		YAHOO.util.Event.removeListener(window, "resize", (is_ie ? this.handle_viewport_change_ie : this.handle_viewport_change));
		YAHOO.util.Event.removeListener(window, "scroll", (is_ie ? this.handle_viewport_change_ie : this.handle_viewport_change));
		this.events_enabled = false;
	}
}

/**
* Resizes and repositions the overlaybox and the window overlay after the browser viewport has altered
*
*/
vB_Overlay.prototype.handle_viewport_change = function()
{
	this.show_background(1);
	this.show_overlaybox(1);
}
/**
* Special case for IE - starts handle_viewport_change after a short delay
*
*/
vB_Overlay.prototype.handle_viewport_change_ie = function()
{
	var thisC = this;
	setTimeout(function(){ thisC.handle_viewport_change(); }, 100);
}

/**
* Checks the internal status of the object
*
* @param	integer	Status (checks for >= status)
*
* @return	boolean
*/
vB_Overlay.prototype.check_status = function(status)
{
	if (this.status >= status)
	{
		return true;
	}
	else
	{
		console.warn("Checked status for %d, found %d", status, this.status);
		return false;
	}
}

/**
* Sets the internal status of the object
*
* @param	integer	Status
*/
vB_Overlay.prototype.set_status = function(status, caller)
{
	console.log("vB_Overlay :: Set status = %d (%s)", status, caller);
	this.status = status;
}

/**
* Display the progress image
*
* @param	integer	Alternate progress image to display
*/
vB_Overlay.prototype.showprogress = function(alt)
{
	YAHOO.util.Dom.setStyle(this.clearbackground, "display", "");
	if (typeof(alt) == "undefined")
	{
		alt = "";
	}
	var imagestring = "this.progressimage" + alt;
	var imagetype = eval(imagestring);
	YAHOO.util.Dom.setStyle(imagetype, "display", "");
	if (!alt)
	{
		center_element(imagetype);
	}
}

/**
* Hides the progress image
*
*/
vB_Overlay.prototype.hideprogress = function()
{
	YAHOO.util.Dom.setStyle(this.progressimage, "display", "none");
	YAHOO.util.Dom.setStyle(this.clearbackground, "display", "none");
}

/**
* Flip button color
*
* @param	object	Event
*/
vB_Overlay.prototype.flipbuttoncolor = function(e)
{
	var is_highlighted = YAHOO.util.Dom.hasClass(this, 'vb_overlay_highlight');

	if (is_highlighted)
	{
		YAHOO.util.Dom.removeClass(this, 'vb_overlay_highlight');
	}
	else
	{
		YAHOO.util.Dom.addClass(this, 'vb_overlay_highlight');
	}
}

/**
* Cancels the edit
*
*/
vB_Overlay.prototype.cancelform = function(e)
{
	if ((e && e.type == "keydown" && e.keyCode != 27) || YAHOO.util.Dom.getStyle(this.progressimage, "display") == "" || this.flasheractive)
	{
		return;
	}
	if (this.cancelurl)
	{
		window.location = this.cancelurl;
	}
	else
	{
		this.close();
	}
}

/**
* Handle AJAX failure
*
* @param	object	YUI AJAX
*/
vB_Overlay.prototype.handle_ajax_error = function(ajax)
{
	this.close();
	vBulletin_AJAX_Error_Handler(ajax);
}
/*======================================================================*\
|| ####################################################################
|| # NulleD By - FintMax
|| # CVS: $RCSfile$ - $Revision: 25662 $
|| ####################################################################
\*======================================================================*/