var OpenWidgetsHost = {
  lastHashCommand: null,
  
  load: function(options) {
    var stylesheets = '';

    /* Load host stylesheets into widget */
    jQuery('link').each(function(x){
      stylesheet = jQuery(jQuery('link')[x]).attr('href');

      /* Only pass stylesheets that are jquery-ui or custom theme related */
      if(stylesheet.match(/jquery-ui|theme/)) {
        stylesheets += escape(stylesheet) + '___';
      }
    });
      
    /* Build final widget URL */
    delimiter = options.widget_url.match(/\?/) ? '&' : '?'
    var url = options.widget_url + delimiter + 'theme_stylesheets=' + stylesheets + 
          '&host_url=' + escape(options.host_url.split('#')[0]) + '&target=' + options.target;
    var prm = '';
    if(options.forward_params != undefined) {
      jQuery.each(options.forward_params, function(i,v) {
        prm += i+"="+escape(v)+'&';
      });
      url += '&'+prm;
    }

    /* Load widget into iFrame */
    var iframe = '<iframe class="openwidget" style="padding: 0; border: 0; margin: 0; overflow-x: hidden; overflow-y: auto;" frameborder=0' + 
             ' width=100% height=100% scrollbar="no" src="' + url + '" onload="document.OpenWidgets.pollHash();">';
    jQuery('#' + options.target).append(iframe);
  },
  
  pollHash: function() {
    if(location.hash && location.hash != this.lastHashCommand) {
      this.doHashCommands();
      this.lastHashCommand = location.hash;
    }
    setTimeout("document.OpenWidgets.pollHash();", 500);
  },
  
  doHashCommands: function() {
    var commands = location.hash.substring(1).replace(/^\+/, '').replace(/\+$/, '').split('+');
    var stripped_hash = location.hash;
    jQuery.each(commands, function(key, value) {
      var command = value.split('___');
      switch(command[0]) {
        case 'sizeWidget':
          /* Looking for format sizewidget_widgetdiv_x200_y800 */
          x = (command[2].substring(0, 1) == 'x' ? command[2].substring(1) : (command[3] && command[3].substring(0, 1) == 'x' ? command[3].substring(1) : 0));
          y = (command[2].substring(0, 1) == 'y' ? command[2].substring(1) : (command[3] && command[3].substring(0, 1) == 'y' ? command[3].substring(1) : 0));
          if(x > 15) { jQuery('#' + command[1]).width(x + 'px'); jQuery('#' + command[1] + ' iframe').width(x + 'px'); }
          if(y > 15) { jQuery('#' + command[1]).height(y + 'px'); jQuery('#' + command[1] + ' iframe').height(y + 'px'); }
          break;
      }
      stripped_hash = stripped_hash.replace(value, '').replace(/^\+/, '').replace(/\+$/, '');
    });
    
    location.hash = (stripped_hash.length > 1 ? stripped_hash : 'openwidgets')
  }
}

if(document.OpenWidgets != undefined) {
  jQuery.extend(document.OpenWidgets, OpenWidgetsHost);
} else {
  document.OpenWidgets = OpenWidgetsHost;
}
