function load_js(name) {
    var script = document.createElement('script');
    script.src = name;
    script.type = 'text/javascript';
    script.defer = true;
    script.id = name;
    // Insert the created object to the html head element
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(script);
}

function load_deps() {
    // will do something when CSS deps can be factored in as well (for jqPlot)
}

/*
 * submitGetForm(it = ID of form container tag [, url]);
 *  if URL is not provided, uses current URL
 *   and preserves query string params where available
 */
function submitGetForm(it, url) {
    var siblings = $('#'+it+' *');
    var q = url ? $.query.empty() : $.query;
    for(i=0; i<siblings.length; ++i) {
        node = siblings[i];
        if (node.name) {
            q = q.set(node.name, node.value);
        }
    }
    if (!url) {
        url = document.location.href;
    }
    i = url.indexOf('?');
    if(i != -1) {
        url = url.substr(0,i);
    }
    document.location.href = url + q.toString();
}

var dd_colours = ["#003258", "#FF4500", "#0094D2", "#35DE00", "#026A65", "#211412", "#D3CABA"];

function makeBarChart(src_id, dest_id, title) {

    var items = $("#" + src_id + " tbody tr td");

    var data = [], series = [];

//    uribase = document.location.href;

    for(i=0, j=0; i<items.length; i+=3, j = (j+1)%dd_colours.length) {
        data.push( [parseInt($(items[i+2]).text(), 10)] );
        series.push( { color: dd_colours[j] } );
        $(items[i]).attr('style', 'background-color: '+dd_colours[j]);
//        $(items[i+1]).wrapInner('<a href="'+uribase+'&swid='+$(items[i+1]).text()+'></a>');
    }

    $.jqplot( dest_id, data, {
                title: title,
                seriesDefaults: {
                    renderer: $.jqplot.BarRenderer
//                    rendererOptions: {
//                        barWidth: null,
//                        barPadding: null
//                    }
                },
                series: series,
                highlighter: {
                    sizeAdjust: 5
                },
                axes: {
                    xaxis:{
                        renderer:$.jqplot.CategoryAxisRenderer,
                        showTicks: false,
                        tickOptions: {
                            showGridline: false
                        }
                    },
                    yaxis:{
                        min:0,
                        tickOptions: {
                            formatString: '%.0f'
                        }
                    }
                }
            });
    // $("#" + src_id + "table").text('');
    return false;
}

function makePieChart(src_id, dest_id, title) {

    var items = $("#" + src_id + " tbody tr td");

    var data = [];

    for(i=0; i<items.length; i+=2) {
        data.push( [$(items[i]).text(), parseInt($(items[i+1]).text(), 10)] );
    }

    $.jqplot( dest_id, [data], {
                title: title,
                seriesColors: dd_colours,
                seriesDefaults: {
                    renderer: $.jqplot.PieRenderer,
                    rendererOptions: {
                        sliceMargin: 4,
                        diameter: 150
                    }
                },
                legend: { show: true, location:'s', rowSpacing: "0.1" }
            });
    $("#" + src_id + "table").text('');
    return false;
}


/*
 * Load any common (global) dependencies
 */
load_deps();


/*
 * abstracted out ready handles for documents
 * perhaps this should go in an event handler on the page in a predictable location?
 */
dd_events = {
    FleetOverview: {
        ready: function() {
//                   makePieChart("tabledata", "chartdiv");
                   makeBarChart("tabledata", "chartdiv");
               }
    },
    FleetbySoftware: {
        ready: function() {
                   makeBarChart("tabledata2", "chartdiv2");
               }
    },
    'DeviceDirector.aspx': {
        ready: function() {
                   $('a.load_content').click(function(){return load_content(this.href);});
               }
    }

};


function on_load_content(url) {
    if(!url) {
        url = document.location.href;
    }
    url = url.toString();

    for(var pattern in dd_events) {
        if(url.indexOf(pattern)>=0) {
            dd_events[pattern].ready();
            break;
        }
    }
}

function is_internal_link(href) {
    if ( (href && href.indexOf('#') != -1)
      && ( href.startsWith('#')
          || href.startsWith(location.pathname+location.search+'#')
          || href.startsWith(location+'#')
         ) ) {
        return true;
    }
    return false;
}


function load_content(url) {
    url = url.toString();
    if(url.indexOf('dnnprintmodule') < 0) {
        url += '&dnnprintmodule=true&SkinSrc=[G]Skins/_default/No+Skin';
    }
    url += '&random='+Math.random();

    url += ' #Table1';
//    $('#contentpanel').html('<img src="http://i18.tinypic.com/630xenc.gif');
    $('#contentpanel').append('<img src="/images/throbber.gif" style="position: absolute; top: 10em; left: 40%" />');
//    $('#contentpanel').loading(true, {img:'/images/throbber.gif', align: 'center'});
    $('#contentpanel').load(url,[],function(x,y,z) {
      $('#Table1').attr("width","100%");
      // FIXme: not sure why the below was present?
      // $('#Table1 a[onclick]').attr('onclick','');
      $('#Table1 a[href]').map(function(i, el) {
        elj = $(el);
        href = elj.attr('href');
        if ( (!is_internal_link(el.href))
          && (href.indexOf('LinkClick.aspx')==-1)
          && (elj.attr('rel') != 'page') ) {
          elj.click(function(){return load_content(this.href);});
        }
      } );
      on_load_content(url);
    } );

    return false;
}



