const FLASHON_ICON = "http://tb4.fr/labs/jetpack/clicktoflash/on.png";
const FLASHOFF_ICON = "http://tb4.fr/labs/jetpack/clicktoflash/off.png";

var state = false;

function findFlashObjects(doc){
 return $(doc).find('object, embed');
}
function createPlaceHolder(name, height, width, doc) {
  var placeHolder = $("<div />", doc);
  placeHolder.css({'display' : 'table-cell', 'z-index' : '999', 'border' : '1px solid gray', 'min-width' : '40px', 'min-height' : '40px', 'background' : '-moz-linear-gradient(top, bottom, from(white), to(#d9d9d9));', 'cursor' : 'pointer', 'vertical-align' : 'middle', 'text-align' : 'center', 'height' : height, 'width' : width});
  var label = $("<span />", doc);
  label.html(name);
  label.css({'font-family' : '"Lucida Sans Unicode","Lucida Grande",Garuda,sans-serif', 'color' : '#a5a5a5', 'font-size' : '20px', 'border' : '2px solid #a5a5a5', 'text-shadow' : '1px 1px 0 #fff', '-moz-border-radius' : '5px', 'font-weight' : 'bold', 'padding' : '0 5px', '-moz-box-shadow' : '1px 1px 0 #fff'});
  placeHolder.append(label);
  return placeHolder;
}
function removeFlashObjects(doc){
  findFlashObjects(doc).each(function() {
    var placeHolder = createPlaceHolder("Flash", this.clientHeight, this.clientWidth, doc);
    placeHolder.click(function(eventObject){
      $(this).replaceWith(jQuery.data( placeHolder, "myEmbed") );
    });
    jQuery.data(placeHolder, "myEmbed" ,this);
    $(this).replaceWith(placeHolder);
  });
}

jetpack.statusBar.append({
    html: '<img />',
    width: 16,
    onReady: function(widget){
        $(widget).find("img").attr("src", FLASHON_ICON);
        $(widget).find("img").click(function(){
            if(state) {
                $(widget).find("img").attr("src", FLASHON_ICON);
                jetpack.tabs.onReady.unbind( removeFlashObjects );
                state = false;
            } else {
                $(widget).find("img").attr("src", FLASHOFF_ICON);
                jetpack.tabs.onReady( removeFlashObjects );
                removeFlashObjects(jetpack.tabs.focused.contentDocument);
                state = true;
            }
          });
      }
});