/*
	Eval scripts after UpdatePanel updates
	Copyright (C) 2006 Slavik Tretyak

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

	some ideas taken from:
	* protorype library
	* http://cain.supersized.org/archives/2-Dynamic-loading-of-external-JavaScript-.js-files.html
	* http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/
*/

if (typeof(js_eval_scripts_included) != 'undefined')
{
	alert('Secondary include.');
}

var js_eval_scripts_included = true;

var js_ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
var js_ScriptSrcFragment = '<script.+(src[ ]*=[ ]*\'(.*?)\'|src[ ]*=[ ]*"(.*?)").+';
var js_FunctionNameFragment ='[\\s;\n]*function[\\s\n]*([a-zA-Z_\\$]+[0-9a-zA-A_\\$]*)[\\s\n]*\\(';

function js_extractScripts(str)
{
	var matchAll = new RegExp(js_ScriptFragment, 'img');
	var matchOne = new RegExp(js_ScriptFragment, 'im');
	var matchSrc = new RegExp(js_ScriptSrcFragment, 'im');

	var arr = str.match(matchAll) || [];
	var res = [];

	for (var i = 0; i < arr.length; i++)
	{
		var srcMt = arr[i].match(matchSrc);
		if (srcMt)
		{
			if (srcMt.length > 3) res.push(['src', srcMt[3]]);
			else res.push(['src', srcMt[2]]);
		}

		var mtCode = arr[i].match(matchOne) || ['', ''];
		if (mtCode[1] != '') res.push(['code', mtCode[1]]);
	}

	return res;
}

/*
	Eval string and register functions in global namespace
*/
function js_EvalString(str)
{
	/*
		in "http://cain.supersized.org/archives/2-Dynamic-loading-of-external-JavaScript-.js-files.html"
		written that window.eval(str) will be eval string in global namespace, but for IE this is incorrect,
		and you must register all functions in global namespace manually
	*/

	eval(str);

	var matchAll = new RegExp(js_FunctionNameFragment, 'img');
	var matchOne = new RegExp(js_FunctionNameFragment, 'im');

	var arr = str.match(matchAll) || [];

	for (var i = 0; i < arr.length; i++)
	{
		var fname = (arr[i].match(matchOne))[1];
		if (eval('typeof(' + fname + ')') == 'function') window[fname] = eval(fname);
	}
}

/*
	Load script and wait until it loads.
	(if appent script element to DOM, Firefox does not wait until loading was completed)
*/
function js_loadScript(src)
{
	var ex;
	var req = null;

	if (window.XMLHttpRequest)
	{
		req = new XMLHttpRequest();
	}
	else
	if (window.ActiveXObject)
	{
		var msxmls = ['Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
		for (var i = 0; i < msxmls.length; i++)
		{
			try
			{
				req = new ActiveXObject(msxmls[i]);
				break;
			}
			catch (ex) {}
		}
	}

	if (req===null || req===false)
	{
		alert('Unable find XMLHttpRequest or it ActiveX alalog.');
		return;
	}

	req.open("GET", src, false);	// not asynchronous
	req.send(null);

	if (req.status == 200) js_EvalString(req.responseText);
	else alert('Unable to load ' + src + ' (' + req.status + ')');
}

function js_evalScripts(str)
{
	var ex;
	var arr = js_extractScripts(str);

	for (var i = 0; i < arr.length; i++)
	{
		switch (arr[i][0])
		{
			case 'src':
				js_loadScript(arr[i][1]);
				break;

			case 'code':
				var cnt = arr[i][1];

				// hack for RadTabStrip
				// but the best way is set HttpContext.Current.Request["httprequest"] to true in code behind
				cnt = cnt.replace(/AppendStyleSheet\(false,/g, 'AppendStyleSheet(true,');

				js_EvalString(cnt);
				break;
		}
	}
}

function js_updateElement(element)
{
	var content = element.innerHTML;
	setTimeout(function() {js_evalScripts(content)}, 1);
}

var js_postbackElement;

function js_beginRequestHandler(sender, args)
{
	js_postbackElement = args.get_postBackElement();

//	var updatedPanels = args.get_panelsUpdated();
//	alert(updatedPanels.length);
}

function js_pageLoadedHandler(sender, args)
{
	if (typeof(js_postbackElement) === "undefined") return;

	var updatedPanels = args.get_panelsUpdated();
	for (var i = 0; i < updatedPanels.length; i++) js_updateElement(updatedPanels[i]);
}

function js_registerJsEval()
{
	var ex;

	// don't display error if EnablePartialRendering is false
	try
	{
		Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(js_beginRequestHandler);
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(js_pageLoadedHandler);
	}
	catch (ex) {}
}
