var w_request;
var w_obj;

function widgetrequest(url, params, func, type)
{
	w_request = false;
	if(window.XMLHttpRequest)
	{
		w_request = new XMLHttpRequest();
		if(w_request.overrideMimeType) w_request.overrideMimeType('text/xml');
	}
	else if(window.ActiveXObject)
	{
		try
		{
			w_request = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(error)
		{
			try
			{
				w_request = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch(error) {}
		}
	}
	
	if(!w_request) return false;
	
	w_request.onreadystatechange = func;
	if(type.toLowerCase() == 'post')
	{
		w_request.open('POST', url, true);
		w_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		w_request.setRequestHeader('Content-length', params.length);
		w_request.setRequestHeader('Connection', 'close');
		w_request.send(params);
	}
	else //get
	{
		w_request.open('GET', url, true);
		w_request.send(null);
	}
	
	return true;
}

function widgetresponse()
{
	if(w_request.readyState == 4)
	{
		if(w_request.status == 200)
		{
			w_obj.innerHTML = w_request.responseText;
			
			_initwidget(w_obj);
		}
	}
}

function encodeparam(text)
{
	return (encodeURIComponent) ? encodeURIComponent(text) : 
			escape(text.replace(/\+/g, '%2B'));
}

function getformfields(form)
{
	str = '';
	usedfields = {};
	
	for(i = 0; i < form.childNodes.length; i++)
	{
		obj = form.childNodes[i];
		
		if(obj.nodeName.toLowerCase() == 'input' || obj.nodeName.toLowerCase() == 'textarea')
		{
			if(!obj.name) continue;
			if(str.length) str += '&';
			
			if(obj.type.toLowerCase() == 'checkbox')
			{
				if(obj.checked) str += obj.name+'=on';
			}
			else if(obj.type.toLowerCase() == 'radio')
			{
				if(obj.checked && !usedfields[obj.name])
				{
					str += obj.name+'='+encodeparam(obj.value);
					usedfields[obj.name] = 1;
				}
			}
			else //we're not gonna give a damn about files and other special fields
				str += obj.name+'='+encodeparam(obj.value);
		}
	}
	
	return str;
}

function _widgetform(widget, form)
{
	//first get all the parameters
	params = getformfields(form);
	
	//then check and set the global widget object
	if( (w_obj = document.getElementById(widget)) == false) return true;
	
	//and finally submit the form
	if(form.method.toLowerCase() == 'get')
	{
		url = form.action+'?'+params;
		if(!widgetrequest(url, 0, widgetresponse, 'get')) 
			alert('Error in setting up get request');
	}
	else if(form.method.toLowerCase() == 'post')
	{
		if(!widgetrequest(form.action, params, widgetresponse, 'post')) 
			alert('Error in setting up post request');
	}
	else return true; //we can't handle it...
	
	return false;
}

function _widgetlink(widget, url)
{
	if( (w_obj = document.getElementById(widget)) == false)
	{
		window.location = url; //error
		return;
	}
	
	if(!widgetrequest(url, 0, widgetresponse, 'get')) 
		alert('Error in setting up get request');
	
	return;
}

//this is meant to be called by widgets explicitly (ie. in js code)
//the object is simply any object within the widget (or the widget itself)
function widgetlink(obj, url)
{
	//first find the widget
	while(obj.parent && obj.className != 'Widget') obj = obj.parent;
	if(obj.className != 'Widget') return; //not found
	
	//then call internal function
	_widgetlink(obj.id, url);
}

//as is this
function widgetform(obj)
{
	form = obj;
	
	//first find the widget
	while(obj.parent && obj.className != 'Widget') obj = obj.parent;
	if(obj.className != 'Widget') return; //not found
	
	//then call internal function
	_widgetform(obj.id, form);
}

function _initwidget(widget)
{
	//first convert regular links
	wlinks = widget.getElementsByTagName('a');
	for(j = 0; j < wlinks.length; j++)
	{
		if(wlinks[j].className.indexOf('InternalLink') == -1) continue;
		
		//just in case someone was really sloppy...
		if( (t = wlinks[j].href.indexOf(':')) != -1)
			if(wlinks[j].href.substr(0, t) == 'javascript') continue;
		
		if(wlinks[j].className.indexOf('ToWidget') != -1)
		{
			wobj = widget.id.split('_');
			wobj = wobj[1];
			
			wlinks[j].href = 'extensions/Widgets/widget.php?w_obj='+wobj+'&'+wlinks[j].href;
		}
		
		wlinks[j].href = 'javascript:_widgetlink(\''+widget.id+'\', \''+wlinks[j].href+'\');';
	}
	
	//and now do forms
	wforms = widget.getElementsByTagName('form');
	for(j = 0; j < wforms.length; j++)
	{
		if(wforms[j].className.indexOf('InternalForm') == -1) continue;
		
		wforms[j].onsubmit = new Function('return _widgetform(\''+widget.id+'\', this);');
		
		if(!wforms[j].action.length || wforms[j].className.indexOf('ToWidget') != -1)
		{
			wobj = widget.id.split('_');
			wobj = wobj[1];
			
			if(wforms[j].action) str = wforms[j].action;
			else str = '';
			
			wforms[j].action = 'extensions/Widgets/widget.php';
			if(wforms[j].method.toLowerCase() == 'get')
			{
				inpt = document.createElement('input');
				
				inpt.type = 'hidden';
				inpt.name = 'w_obj';
				inpt.value = wobj;
				
				wforms[j].appendChild(inpt);
			}
			else 
				wforms[j].action += '?w_obj='+wobj+(str.length ? ('&' + str) : '');
		}
	}
	
	return;
}

function initwidgets()
{
	container = document.getElementById('Content');
	if(!container) return;
	
	for(i = 0; i < container.childNodes.length; i++)
		_initwidget(container.childNodes[i]);
	
	return;
}

window.onload = initwidgets;

/*
some notes for widgets developers:

to make a link open in your widget, have a class value of (but not limited to) InternalLink
for forms, it is InternalForm
please note that this will only work if the target of the form or link is at the same address as the current server

to send info to a single widget via a:
 - link, add a class value of ToWidget; the current href value will be appended to the widget url and hence passed on to it
   in this case the href value would be used for extra parameters, eg. 
   <a href="disp=1&value=testing" class="InternalLink ToWidget">Click Me!!!</a>
 - form, leave the action value blank, or add a class value of ToWidget and the current action value will be appended to 
   the correct url.  Sample usage:
   <form action="disp=1" class="InternalForm ToWidget">
    <input name="value" value="testing">
    <input type="submit">
   </form>

when a widget is 'accessed' via such a method, it can retrieve these values via the superglobals $_GET and $_POST

*/