// single global object

var BusCms = new Object();

BusCms.widgets = new Array();

BusCms.widgetTypes = new Array();

BusCms.addWidget = function (widgetObject)
{
	// set the querystring arguments member variable
	widgetObject.querystringAruments = qsToJson();
	if (widgetObject.isInstance)
	{
		BusCms.widgets[widgetObject.domid] = widgetObject;
	}
	else
	{
		BusCms.widgetTypes[widgetObject.widgetType] = widgetObject;
	}
}


BusCms.instantiateWidget = function(domid, widgetType)
{
	if (domid instanceof jQuery)
	{
		domid.each(function(index,obj){BusCms.instantiateWidget($(obj).attr('id'),widgetType);});	
	}
	else
	{
		if (typeof domid == "string")
		{
			var newWidgetInstance = jQuery.extend(true, {}, BusCms.widgetTypes[widgetType]);
			newWidgetInstance.domid=domid;
			newWidgetInstance.isInstance=true;
			
			$.each( $('#' + domid).data(),function(i, e) {
			   if (typeof newWidgetInstance.arguments == "undefined")
			   {
			   	newWidgetInstance.arguments = {};
			   }
			   newWidgetInstance.arguments[i] = e;
			});
			
			/*
			var elem = $('#' + domid)[0];
			for (var i = 0; i < elem.attributes.length; i++) {
			  var attrib = elem.attributes[i];
			  if (attrib.specified == true) 
			  {
			  	if (attrib.name.indexOf("data-")==0)
			  	{
			    		console.log(attrib.name + " = " + attrib.value);
			    		newWidgetInstance.arguments[attrib.name.substring(5)] = attrib.value;
			    	}
			  }
			}
			*/
			
			BusCms.widgets[newWidgetInstance.domid] = newWidgetInstance;
			newWidgetInstance.onLoad();
		}
	}
}




// Function that executes when the page has loaded and JQuery is ready
$(document).ready(function(){
	// loop through all elements in BusCms.widgets and call thier onLoad methods
	for (var widget in BusCms.widgets) {
	    BusCms.widgets[widget].onLoad();
  	}
});


function qsToJson()
{
	var scripts = document.getElementsByTagName('script');
	var currentScript = scripts[scripts.length - 1];
	var qs = currentScript.src.substring(currentScript.src.lastIndexOf("?")+1);

	var b = qs.split('&');
	var final ={};
	$.each(b, function(x,y){
	    var temp = y.split('=');
	    final[temp[0]] = temp[1];
	});
	return final;
}





/* language patch to add support for 'bind' to any function */
if (!Function.prototype.bind) {
    Function.prototype.bind = function () {
        var fn = this,
            args = Array.prototype.slice.call(arguments),
            object = args.shift();

        return function () {
            return fn.apply(
                object, args.concat(Array.prototype.slice.call(arguments))
            );
        };
    };
}
