/* Allows NSW government toolbar to be inserted into a page
 */
var NetworkToolbar = {
  
  /* insert toolbar
   * options: object-literal with the following optional properties:
   *      - domain: the domain to load the data from, defaults to www.nsw.gov.au
   *      - width: an integer to 
   */
  insert: function(options) {
    // handle missing console
    if (!('console' in window)) {
      window.console = {};
      console['log'] = function() {};
    }
    
    options = options || {};
    var domain = options['domain'] || 'www.nsw.gov.au';
    var width = options['width'];
    var url = ('https:' == document.location.protocol ? 'https://' : 'http://') + domain + '/widgets/network-toolbar.json?';
    
    // load toolbar html from json payload
    $.ajax({url: url, dataType: "jsonp", jsonp: "callback",
      success: function(json) {
        var content = json.content;
        if (content) {
          $('#nsw-network-toolbar').fadeIn().html(content);
          if (width) {
            $('#network-wrapper').width(width);
          }
          
          // This code is pulled from /themes/nswworks/js/functions.js
          // and is called here again after the menu is rebuilt.
          $('#nsw-network-toolbar a').each(function() {
        		if ($(this).attr('href')) {
        			var host = 'http://' + window.location.hostname;
        			var href = $(this).attr('href');
        			if (href.substr(0,1)!='/') {
        				if (href.substr(0,4)=='http') {
        					if (href.substr(0,host.length)!=host) {
        						$(this).attr('target','_blank').addClass('external');
        					}
        				}
        			}
        		}
        	})
        	
          $('.network-menu > ul.menu > li.expanded').hover(function() {  
            $(this).addClass('over');
          },function() {
            $(this).removeClass('over');
          })
        }
        else {
          console.log('Error getting data...');
        }
      },
      error: function(xhr, s, e) {
        if (window.console) {
          console.log(s, e);
        }
      }
    });
  }
}
