roostr.widgets.master = {
    "max_requests" : 2,
    "render_queue" : [],
    "render_queue_interval" : undefined,
    "queue_render_widget" : function(widget_id, args) {
        if(!roostr.widgets_rendering) {
            roostr.widgets_rendering = 0;
        }
        if(this.render_queue_interval == undefined) {
            this.render_queue_interval = setInterval(roostr.widgets.master.check_render_queue, 500);
        }
        if(roostr.widgets_rendering >= this.max_requests) {
            var f = function() {roostr.widgets.master.render_widget(widget_id, args)};
            this.render_queue.push(f);
        }
        else {
            this.render_widget(widget_id, args);
            roostr.widgets_rendering++;
        }
    },
    "check_render_queue" : function() {
        if(!roostr.widgets_rendering || roostr.widgets_rendering < roostr.widgets.master.max_requests) {
            for(var i = roostr.widgets_rendering; i < roostr.widgets.master.max_requests; i++) {
                var f = roostr.widgets.master.render_queue.shift();
                if(f) {
                    roostr.widgets_rendering++;
                    f();
                }
            }
        }
        if(roostr.widgets.master.render_queue.length == 0) {
            clearInterval(roostr.widgets.master.render_queue_interval);
        }
    },
	"render_widget": function(widget_id, args){
        roostr.widgets.master.show_throbber(widget_id);
		var type = roostr.widget_list[widget_id].type;
		var url = this.build_widget_url(widget_id, args);
        if(!url) {
            return; //avoid bad, hard to debug firefox error
        }

        var content_id = $("#" + widget_id).find(".widget_content");
        if(content_id.length == 0) {
            content_id = $("#"+widget_id);
        }
		
        content_id.load(url, function() {
            roostr.widget_resources[type] = {};
            roostr.widget_resources[type].css = roostr.widgets.master.get_css_array(widget_id);
            roostr.widget_resources[type].js = roostr.widgets.master.get_js_array(widget_id);
            var load_complete_f = function() {
                if(roostr.widgets[type] && typeof(roostr.widgets[type].init) == "function") {

                // multi init removal - check & see if this works for a permanent fix
                    /*this is kinda hacky */
                    //for (var w in roostr.widget_list) {
                        //if (roostr.widget_list[w].type == type) {
                            roostr.widgets[type].init(widget_id);
                        //}
                   // }                   
                }
                roostr.widgets.master.hide_throbber(widget_id);
                if(roostr.widgets_rendering) {
                    roostr.widgets_rendering--;
                }
            }
            if($.browser.safari) {
                roostr.widgets.master.load_css_files(type, function() {
                    roostr.widgets.master.load_js_files(type, load_complete_f);
                });
            }
            else {
                roostr.widgets.master.load_js_files(type, load_complete_f);
            }
        });
	},

    "reload_widget": function(widget_id, args) {
        roostr.widgets.master.show_throbber(widget_id);
        var type = roostr.widget_list[widget_id].type;
		var url = this.build_widget_url(widget_id, {});
        if(!url) {
            return; //avoid bad, hard to debug firefox error
        }
        
        var content_id = $("#" + widget_id).find(".widget_content");
        if(content_id.length == 0) {
            content_id = $("#"+widget_id);
        }
        $.post(url, args, function(data, textStatus) {
            content_id.html(data);            
            roostr.widget_resources[type] = {};
            roostr.widget_resources[type].css = roostr.widgets.master.get_css_array(widget_id);
            roostr.widget_resources[type].js = roostr.widgets.master.get_js_array(widget_id);
            /*roostr.widgets.master.load_css_files(type, function() {*/
                roostr.widgets.master.load_js_files(type, function() {
                    if(roostr.widgets[type] && typeof(roostr.widgets[type].init) == "function") {
                        roostr.widgets[type].init(widget_id);
                    }
                    roostr.widgets.master.hide_throbber(widget_id);
                });
            });
        /*});*/

    },

	"render_all": function(){
		//loop through the widget_list
        var list = [];
		$.each(roostr.widget_list,function(i){
			list.push({id:i, obj:this});
		});
        list.sort(function(a,b) {var i = a.obj.load_priority; var j = b.obj.load_priority; return j - i;});
        $.each(list, function() {
            roostr.widgets.master.queue_render_widget(this.id);
        });
        /* old version, totally asynchronous, maxes out http pipeline. blocks js/css loading
        $.each(roostr.widget_list,function(i){
			roostr.widgets.master.render_widget(i);
		});*/
        //todo move this out of here
	},

    "build_widget_url":function(id, args) {
        var url = roostr.widget_list[id].url;
        var defaultArgs = roostr.widget_list[id].args
        if(args || defaultArgs) {
            u = roostr.URL.parse_query(url);
            for(var i in defaultArgs) {
                u.params[i] = defaultArgs[i];
            }
            for(var i in args) {
                u.params[i] = args[i];
            }
            for(var i in roostr.page_args) {
                u.params[i] = roostr.page_args[i];
            }
            url = roostr.URL.build_query(u);
        }
        return url;
    },

    "hide_throbber" : function(id) {
        $('#' + id).find(".widget_loading_show").hide();
        $('#' + id).find(".widget_content").show();
        $('#' + id).find('.widget_titletext').text($('#' + id).find('.widget_titletext').text().replace(/ - Loading/, ""));

        //$('#' + id).find(".widget_config_link").show();
    },

    "show_throbber" : function(id) {
        $('#' + id).find(".widget_content").hide();
        $('#' + id).find(".widget_loading_show").show();
    },

    "get_js_array" : function(id) {
        var a = [];
        $('#' + id + ' .js_includes input').each(function() {
           a.push(this.value); 
        });
        return a;
    },

    "get_css_array" : function(id) {
        var a = [];
        $('#' + id + ' .css_includes input').each(function() {
           a.push(this.value); 
        });
        return a;
    },

    "load_css_files" : function(type, callback) {
        var css_array = [];
        if(roostr.widget_resources[type]) {
            css_array = roostr.widget_resources[type].css;
        }
		var file = css_array.shift();

        if(!file) {
			callback();
        }
		else if(roostr.resources.css[file]){
            roostr.widgets.master.load_css_files(type, callback);
		}
        else {
            var include = document.createElement('link');

            include.type  = 'text/css';
            include.rel   = 'stylesheet';
            include.href  = file;
            include.media = 'screen';

            /*
             * Firefox doesn't fire any event handlers on css
            // Callback for real browsers
            include.onLoad = function() {
                roostr.resources.css[file] = 1;
                roostr.widgets.master.load_css_files(css_array, callback);
            }

            // Callback for Exploder
            include.onreadystatechange = function()
            {
                if (this.readyState == 'complete')
                {
                    roostr.resources.css[file] = 1;
                    roostr.widgets.master.load_css_files(css_array, callback);
                }
            };
            */
            $("head")[0].appendChild(include);

            roostr.resources.css[file] = 1;
            roostr.widgets.master.load_css_files(type, callback);
        }
    },

    "load_js_files" : function(type, callback) {
		var js_array = [];
        if(roostr.widget_resources[type]) {
            js_array = roostr.widget_resources[type].js;
        }
        var file = js_array.shift();
		if(!file){
			callback();
		}
        else if(roostr.resources.js[file]){
            roostr.widgets.master.load_js_files(type, callback);
		}
        else {
            var include = document.createElement('script');

            include.type  = 'text/javascript';
            include.src  = file;


            // Callback for real browsers
            include.onload = function() {
                roostr.resources.js[file] = 1;
                roostr.widgets.master.load_js_files(type, callback);
            }

            // Callback for Exploder
            include.onreadystatechange = function() {
                if (this.readyState == 'complete')
                {
                    roostr.resources.js[file] = 1;
                    roostr.widgets.master.load_js_files(type, callback);
                }
            };

            $("head")[0].appendChild(include);
        }
    },
    getElementPosition : function(id) {
            var w = $('#' + id).get(0);
            return {
                top : w.offsetTop,
                left : w.offsetLeft,
                bottom : w.offsetTop + w.offsetHeight,
                right : w.offsetLeft + w.offsetWidth,
                center : [w.offsetTop + (w.offsetHeight / 2), w.offsetLeft + (w.offsetWidth / 2)],
            };

    }
};

// global search function to search from within a container
$.sub_search = function(id,search){
    return $("#"+id+" "+search);
};

// global get function for widgets
// DEPRECATED - USE $.sub_search INSTEAD
function get(id,search){
    alert('this get method is deprecated. it will be removed very shortly');
	return $("#"+id).find(search);
}

