// These must be set for each site that is using this.
// TODO: Find a way to have this programmatically done
var baseWidgetUrl = '';
var domainParts = document.domain.split('.');
if (domainParts.length > 1)
{
	document.domain = domainParts[domainParts.length-2] + '.' + domainParts[domainParts.length-1];
}

function sendPublicHttpRequest(method, url, params, cookie, callback) {
	var result = sendHttpRequest(method, url, params, cookie, callback);
	return result;
}

function sendHttpRequest(method, url, params, cookie, callback) {
	if (top.frames["childframe"])
	{
		if (top.frames["childframe"].sendPublicHttpRequest)
		{
			return top.frames["childframe"].sendPublicHttpRequest(method, url, params, cookie, callback);
		}
	}
}

function WidgetManager()
{
	// Only create a single instance of this
	if(window.widgetManager)
	{
		return;
	}
	
	window.widgetManager = this;
	this.Widgets = new Object();
	this.element_count = 0;

	this.domComplete = false;	// flag to test if the DOM is ready
	if(document.addEventListener && document.readyState) // Safari and Opera
	{
		this.startPoll();	// start Polling
	}
	this.initialize();	// add listeners to window.document or window
}


function WidgetManager_StartPolling() 
{
	if(this.pollId) 
	{
		return;
	}
	var self = this;
	this.pollId = setInterval(function(){ self.loadWidgets(); }, 1000);
}


function WidgetManager_StopPolling() 
{
	if (!this.pollId) 
	{
		return;
	}
	clearInterval(this.pollId);
	this.pollId = null;
}


function WidgetManager_Initialize()
{
	var self = this;
	var callBack = function(){
		if(document.readyState) // IE and Opera 9
		{
			if(document.readyState == 'complete')
			{ 
				self.domComplete = true; 
				//self.loadWidgets();
			}
		}
		else // Firefox
		{
			self.domComplete = true; 
			//self.loadWidgets();
		}
	}
	
	if(document.addEventListener) // W3C Recommendation
	{
		if(document.readyState) // Opera and Safari
		{
			document.addEventListener("onreadystatechange", callBack, false);
		}
		else // Firefox
		{
			document.addEventListener("DOMContentLoaded", callBack, false);
		}
	}
	else if(document.attachEvent) // IE
	{
		document.attachEvent("onreadystatechange", callBack);
	}
	else
	{
		//window.onload = callBack;
	}
}
	

function WidgetManager_LoadWidgets()
{
	/* Scan for all widgets and kick off each */
	var elements = document.getElementsByTagName("rda:widget");
	var len = elements.length;
	
	// Need to do this from the bottom up because we are removing the
	//   widget from the page as it is loaded
	for(var elementIndex = len-1; elementIndex >= 0; elementIndex--)
	{
		var widget = new Widget(elements[elementIndex]);
		var widgetID = widget.WidgetID;
		this.Widgets[widgetID] = widget;
		widget.Load();
	}
	
	if(this.domComplete)
	{	
		this.stopPoll();
	}
}


function WidgetManager_UpdateContent(moduleId, uri)
{
	if(this.Widgets[moduleId])
	{
		this.Widgets[moduleId].Update(PT["host"] + uri);
	}
}


function WidgetManager_SetContent(moduleId,sContent)
{
	if(this.Widgets[moduleId])
	{
		this.Widgets[moduleId].SetContent(sContent);
	}
}


/**
 Determine if request is coming from:
	0. External Domain
	1. Same Domain
	2. Same Host
**/
function WidgetManager_GetEnvironment()
{
	// Test Same Host
	if(PT["host"] == window.location.host)
	{
		return 2;
	}
	// Test Same Domain
	else 
	{ 
		// This assumes that ajaxHost is a fully qualified domain name.
		// To Do: Probably should use a regular expression to tighten this up
		var ajaxHost = PT["host"].split('//');
		var ajaxDomain = ajaxHost[1].split('\.');
		var xhrDomain = window.location.host.split('\.');
		for(i = 0; i < xhrDomain.length - 1; i++)
		{
			for(j = 1; j < ajaxDomain.length - 1; i++)
			{
				if(xhrDomain[i] == ajaxDomain[j]);
				{
					return 1;
				}
			}
		}
		// Must be an External Domain
		return 0;
	}
}


WidgetManager.prototype = new Object();
WidgetManager.prototype.getEnvironment = WidgetManager_GetEnvironment;
WidgetManager.prototype.initialize= WidgetManager_Initialize;
WidgetManager.prototype.loadWidgets = WidgetManager_LoadWidgets;
WidgetManager.prototype.SetContent= WidgetManager_SetContent;
WidgetManager.prototype.startPoll = WidgetManager_StartPolling;
WidgetManager.prototype.stopPoll = WidgetManager_StopPolling
WidgetManager.prototype.UpdateContent = WidgetManager_UpdateContent;



function Widget(Element)
{
		/* Generate a unique ID for the widget */
		this.WidgetID = Widget.Prefix + widgetManager.element_count++;
		this.element = Element;
		
		/* The canvas will be the dynamically created div in which the widget operates */
		this.canvas = null;

		this.source = this.element.getAttribute("src");
		this.args = this.element.getAttribute("args");
		this.id = this.element.getAttribute("id");
		this.args["id"] = this.id;
}

function	Widget_SetContent(sContent)
{
		// modification to handle scripts
	if(this.element)
	{
		<!-- Needed to correct IE race condition -->
		var parentNode;
		if(this.element.parentNode)
		{
			parentNode = this.element.parentNode;
		}

		if(parentNode)
		{
			if(this.canvas == null)
			{
				this.loadingMessage = document.getElementById(this.id + "loading");
				if(this.loadingMessage)
				{
						this.loadingMessage.style.display = "none";
				}
				this.canvas = document.createElement("div");
				parentNode.replaceChild(this.canvas, this.element);						
				this.element= this.canvas;
			}
			this.canvas.innerHTML = sContent;
		}
	}
}


function Widget_Load()
{
	var html = '';
	var arg = null;
	var key = '';
	var val = '';
	
	var params = new Array();
	
	var aArgs = this.args.split("`");
	for (var i = 0; i < aArgs.length; ++i)
	{
		arg = aArgs[i].split("~");
		key = arg[0];
		val = arg[1];
		params[i] =  { name: key, value: val };
	}
	params[params.length] = { name: "id", value: this.id };
	
	var loadRequest = sendHttpRequest("GET", baseWidgetUrl + this.source, params, document.cookie);
	if (loadRequest)
	{
		html = loadRequest.responseText;
		delete loadRequest;
	}
	this.SetContent(html);
}

function checkform(notification, requiredFields)
{
	var field = null;
	var okay = true;
	
	return true;
	
	for (var i = 0; i < requiredFields.length; ++i)
	{
		field = requiredFields[i];
		if (document.getElementById(field).value.length == 0)
		{
			okay = false;
		}
	}
	
	if (!okay && notification != null)
	{
		document.getElementById(notification).innerHTML = 'Please Fill In All Required Items';
	}
	
	return okay;
}

function submitdata(widgetID, target, args)
{
	var html = '';
	var params = new Array();
	
	var aArgs = args.split("`");
	for (var i = 0; i < aArgs.length; ++i)
	{
		arg = aArgs[i].split("~");
		key = arg[0];
		val = arg[1];
		params[i] =  { name: key, value: val };
	}
	params[params.length] = { name: "id", value: widgetID };
	
	var saveRequest = sendHttpRequest("POST", baseWidgetUrl + target, params, document.cookie);
	if (saveRequest)
	{
		var response = saveRequest.responseText
		
		// Reload the page to get the comment to show up
		if (response == 'Success')
		{
			delete saveRequest;
			window.location.reload();
			return;
		}
		else if (response == 'Failure')
		{
			html = 'There was a problem with your request.  Please try again later.'
		}
		else
		{
			html = response;
		}
		
		//html = saveRequest.responseText;
		delete saveRequest;
	}
	
	var response = document.getElementById(widgetID + 'responsebox');
	
	if (response != null)
	{
		response.innerHTML = html;
	}
}


Widget.prototype = new Object();
Widget.prototype.Load = Widget_Load;
Widget.prototype.SetContent = Widget_SetContent;

Widget.Prefix = "Widget";

/** 
		Create the singleton global object window.widgetManager which does all the work of module creation registration and execution
**/
 
new WidgetManager();