var SWF_VIEWER = Class.create({
  Version: '0.1',

  initialize: function(swf_object, cpage) {
    this.viewer = swf_object;
    this.current_page_input = cpage;
    this.current_page = 1;
  },

  next_page: function () {
    this.go_to_page(this.current_page +1);
  },
  
  previews_page: function () {
    this.go_to_page(this.current_page -1);
  },
  
  go_to_page: function (p) {
    p = parseInt(p, 10);
    if (p !== NaN) {
      if (p < 1) {
        p = 1;
      }
      else if (p > this.num_of_pages()) {
        p = this.num_of_pages();
      }
      this.current_page = p;
      this.viewer.GotoFrame(p-1);
      this.current_page_input.value = this.current_page;
    }
  },
  
  zoom_in: function () {
    this.viewer.Zoom(71);
  },
  
  zoom_out: function () {
    this.viewer.Zoom(141);
  },
  
  reset_zoom: function () {
    this.viewer.Zoom(0);
  },
  
  num_of_pages: function () {
    if (this.num_of_pages_mem === undefined) {
      /* TotalFrames workaround as seen on https://bugs.launchpad.net/ubuntu/+source/firefox/+bug/220575 */
      if (typeof this.viewer.TotalFrames == "number")
        this.num_of_pages_mem = this.viewer.TotalFrames; /* IE */
      else if (typeof this.viewer.TotalFrames == "function")
        this.num_of_pages_mem = this.viewer.TotalFrames(); /* WebKit, Mozilla */
      else
        this.num_of_pages_mem = 1; /* Partially loaded Flash in IE? */
    }
    return this.num_of_pages_mem;
  }

});

var Swfbox = Class.create({
  initialize  : function(extra_set) {
    this.settings = {
      loading_image  : '/facebox/loading.gif',
      close_image    : '/facebox/closelabel.gif',
      image_types    : new RegExp('\.' + ['png', 'jpg', 'jpeg', 'gif'].join('|') + '$', 'i'),
      inited        : true,
      clickOutsideCloses: false,
      swfbox_html  : '\
	  <div id="swfbox" style="display:none;"> \
	    <div class="popup"> \
	      <table id="swfbox_table"> \
	        <tbody> \
	          <tr> \
	            <td class="tl"/><td id="swfbox_top" class="b"/><td class="tr"/> \
	          </tr> \
	          <tr> \
	            <td class="b"/> \
	            <td class="body"> \
	              <div class="header"> \
	                <a href="#" class="close"> \
	                  <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
	                </a> \
	                <h3 class="swf_viewer_title">halli hallo &nbsp;</h3> \
                   <div style="clear:both;height:0px;">&nbsp;</div> \
	              </div> \
	              <div class="content"> \
	              </div> \
	            </td> \
	            <td class="b"/> \
	          </tr> \
	          <tr> \
	            <td class="bl"/><td class="b"/><td class="br"/> \
	          </tr> \
	        </tbody> \
	      </table> \
	    </div> \
	  </div>'
    };
    if (extra_set) Object.extend(this.settings, extra_set);
    $(document.body).insert({bottom: this.settings.swfbox_html});

    this.preload = [ new Image(), new Image() ];
    this.preload[0].src = this.settings.close_image;
    this.preload[1].src = this.settings.loading_image;

    var f = this;
    $$('#swfbox .b:first, #swfbox .bl, #swfbox .br, #swfbox .tl, #swfbox .tr').each(function(elem) {
      f.preload.push(new Image());
      f.preload.slice(-1).src = elem.getStyle('background-image').replace(/url\((.+)\)/, '$1');
    });

    this.swfbox = $('swfbox');
    this.keyPressListener = this.watchKeyPress.bindAsEventListener(this);

    // this.watchClickEvents();
    var fb = this;
    Event.observe($$('#swfbox .close').first(), 'click', function(e) {
      Event.stop(e);
      fb.close()
    });
    Event.observe($$('#swfbox .close_image').first(), 'click', function(e) {
      Event.stop(e);
      fb.close()
    });
  },

  watchKeyPress : function(e) {
    // Close if espace is pressed or if there's a click outside of the swfbox
    if (e.keyCode == 27 || (this.settings.clickOutsideCloses && !Event.element(e).descendantOf(this.swfbox))) this.close();
  },

  watchClickEvents  : function(e) {
    var f = this;
    $$('a[rel=swfbox]').each(function(elem, i) {
      Event.observe(elem, 'click', function(e) {
        Event.stop(e);
        f.click_handler(elem, e);
      });
    });
  },

  loading  : function() {
    if ($$('#swfbox .loading').length == 1) return true;

    contentWrapper = $$('#swfbox .content').first();
    contentWrapper.childElements().each(function(elem, i) {
      elem.remove();
    });
    contentWrapper.insert({bottom: '<div class="loading"><img src="' + this.settings.loading_image + '"/></div>'});

    var pageScroll = document.viewport.getScrollOffsets();
    this.swfbox.setStyle({
      'top': pageScroll.top + (document.viewport.getHeight() / 10) + 'px',
      'left': document.viewport.getWidth() / 2 - (this.swfbox.getWidth() / 2) + 'px'
    });

    Event.observe(document, 'keypress', this.keyPressListener);
    Event.observe(document, 'click', this.keyPressListener);
  },

  reveal  : function(data, title, klass) {
    this.loading();
    load = $$('#swfbox .loading').first();
    if (load) load.remove();

    contentWrapper = $$('#swfbox .content').first();
    if (klass) contentWrapper.addClassName(klass);
    contentWrapper.insert({bottom: data});

    $$('#swfbox .body').first().childElements().each(function(elem, i) {
      elem.show();
    });

    if (!this.swfbox.visible()) new Effect.Appear(this.swfbox, {duration: .3});
    this.swfbox.setStyle({
      'left': document.viewport.getWidth() / 2 - (this.swfbox.getWidth() / 2) + 'px'
    });

    Event.observe(document, 'keypress', this.keyPressListener);
    Event.observe(document, 'click', this.keyPressListener);
    
    this.updateTitle(title);
    this.hideScrollbars();
    this.resize();
    Event.observe(document.onresize ? document : window, "resize", this.resize );
  },
  
  updateTitle: function(title){
    $$('#swfbox .body .header .swf_viewer_title').first().update(title);
  },

  hideScrollbars: function(){
    document.body.style.overflow="hidden";
  },
  showScrollbars: function(){
    document.body.style.overflow="visible";
  },
  
  resize: function() {
    var pageScroll = document.viewport.getScrollOffsets();
    $('swfbox').setStyle({
      'top': pageScroll.top + 5 +'px',
      'left': pageScroll.left + 5 + 'px'
    });
    contentWrapper = $$('#swfbox .content').first();
    contentWrapper.setStyle('height:' + (document.viewport.getHeight() - 90) +'px; width:' + (document.viewport.getWidth() - 50) + 'px;' )
    swf_obj = $$('#swfbox .content .viewer').first();
    swf_obj.height = contentWrapper.getHeight();
  },

  close    : function() {
    new Effect.Fade('swfbox', {duration: .3});
    this.showScrollbars();
  },
  
  open: function() {
    new Effect.Appear(this.swfbox, {duration: .3});
  },
  
  click_handler  : function(elem, e) {
    this.loading();
    Event.stop(e);

    // support for rel="swfbox[.inline_popup]" syntax, to add a class
    var klass = elem.rel.match(/swfbox\[\.(\w+)\]/);
    if (klass) klass = klass[1];

    this.open();
    this.loadUrl(elem.href, klass);
  },

  loadUrl : function(href, klass) {
    if (href.match(/#/)) {
      var url = window.location.href.split('#')[0];
      var target = href.replace(url + '#', '');
      // var data			= $$(target).first();
      var d = $(target);
      // create a new element so as to not delete the original on close()
      var data = new Element(d.tagName);
      data.innerHTML = d.innerHTML;
      this.reveal(data, klass);
    }
    else if (href.match(this.settings.image_types)) {
      var image = new Image();
      fb = this;
      image.onload = function() {
        fb.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
      }
      image.src = href;
    }
    else {
      var fb = this;
      var url = href;
      new Ajax.Request(url, {
        method    : 'get',
        onFailure  : function(transport) {
          fb.reveal(transport.responseText, klass);
        },
        onSuccess  : function(transport) {
          fb.reveal(transport.responseText, klass);
        }
      });

    }
  },

  load : function(href) {
    this.loading();
    this.loadUrl(href);
  }
});


// var swffacebox;
// document.observe('dom:loaded', function() {
//   swffacebox = new Swfbox();  
// });

