var Gallery = {
  initialize: function(options) {
    this.gallery      = $('gallery');
    this.image        = $('gallery_image');
    this.closeButton  = $('gallery_close');
    this.isOpen       = false;
    
    this.options = {
      width: 816,
      height: 566
    }; // Default options
    Object.extend(this.options, options || {});
    
    var actuators = $$('.enlargeable');
    actuators.each(function(link) {
      link.observe('click', function(event) {
        event.stop();
        this.open(link);
      }.bind(this));
    }.bind(this));
	
  	this.closeEvent = this.close.bindAsEventListener(this);
    this.closeButton.observe('click', this.closeEvent);
	
  	this.spinner = new Spinner('gallery_spinner_wrapper');
  },

  open: function(linkEl) {
    if (!this.isOpen) {
      this.spinner.show();
      Loader.load(linkEl.href, {
        onComplete: function() {
          this.spinner.hide();
          if (Prototype.Browser.IE) {
            this.image.src = '/images/blank.gif';
            this.image.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + linkEl.href + "', sizingMethod='scale');";
          }
          else {
            this.image.src = linkEl.href;
          }
          //Position.prepare(); // current middle of viewport
          //var top = Position.getPageSize().window.height/2 + Position.deltaY;
          
          var viewport = document.viewport.getDimensions();
          var scrollOffsets = document.viewport.getScrollOffsets();
          var coords = linkEl.cumulativeOffset();
          var dims = linkEl.getDimensions();
          
          this.initialState = {
            top: coords.top + 'px',
            left: coords.left + 'px',
            width: dims.width + 'px',
            height: dims.height + 'px',
            opacity: '0'
          };

          this.gallery.setStyle(this.initialState);

          this.gallery.show();
          //this.closeButton.show();
          
          //this.gallery.morph('margin:-283px 0 0 -408px; width:816px; height:566px;', {
          this.gallery.morph({
            top: viewport.height/2 + scrollOffsets.top - this.options.height/2 + 'px',
            left: viewport.width/2 + scrollOffsets.left - this.options.width/2 + 'px',
            width: this.options.width + 'px',
            height: this.options.height + 'px',
            opacity: '1'
          }, {
            duration: .5,
            transition: Effect.Transitions.sinoidal,
            afterFinish: (Object.isFunction(this.options.afterFinish)) ? this.options.afterFinish.bind(this) : function() { 
              this.closeButton.appear();
              this.image.observe('click', this.closeEvent);
              document.observe('click', this.closeEvent);
            }.bind(this)
          });

          this.isOpen = true;  
        }.bind(this)
      });
    }
  },
  
  close: function() {
    if (this.isOpen) {
      this.closeButton.hide();
      
      if(Object.isFunction(this.options.onClose))
        this.options.onClose.apply(this);
      
      this.gallery.morph(this.initialState, {
        duration:0.4,
        afterFinish: function() { this.gallery.hide(); }.bind(this)
      });
      
	  this.image.stopObserving('click', this.closeEvent);
      document.stopObserving('click', this.closeEvent);
      this.isOpen = false;
    }
  }
  
};

var RocketColumns = {
	initialize: function() {
	  if($$('.rocket_col').length == 0)
	    return;
	  
	  $$('.rocket_col').each(function(col) {
	    var colWidth = (Prototype.Browser.IE) ? '260px' : '240px';
	    col.makeClipping().setStyle({width:colWidth, height:'900px'});	      
	  });
	  (3).times(function(i){
      i++;
      $('organize_'+i,'deliver_'+i).invoke('setStyle', { visibility:'visible' });
      $('organize_'+i+'_content','deliver_'+i+'_content').invoke('setStyle', {top:'2000px', position:'relative'});
      $('overview_'+i).setStyle({ zIndex:1000 });
    });
    $('page_header_organize','page_header_deliver').invoke('setStyle', {marginLeft:'-450px', display:'block', opacity:0});
    this.currentSection = 'overview';
	},
  showSection: function(event, section) {
    if(section == this.currentSection) return;
    $$('ul#choose_os li a').invoke('removeClassName','active');
    $('tablink_'+section).addClassName('active');
    this.hideCurrentSection();
    if(section == 'overview') {
      $('container').morph('height:1800px', { duration:0.7 });
    } else {
      $('container').morph('height:1450px', { duration:0.7 });
    }
    this.flyIn(section+'_1_content', 0.5);
    this.flyIn(section+'_2_content', 0.2);
    this.flyIn(section+'_3_content', 0.6);
    if(section == 'overview') $('mini_features', 'footnotes_overview').invoke('appear', {delay:1.0});
    if(section == 'deliver') $('get_started_box', 'footnotes_deliver').invoke('appear', {delay:1.0});
    this.changeHeader(section);
    this.changeKicker(section);
    this.currentSection = section;
  },
  flyOut: function(element) {
    element = $(element);
    var delay = (arguments[1] || 0);
    element.setStyle({
      position:'relative'
    }).morph('top:-1000px', {
      duration:1.2, 
      delay:delay
    });
    $$('.rocket_col').invoke('setStyle', { zIndex:1 });
  },
  flyIn: function(element) {
    element = $(element);
    element.setStyle({
      top:'900px'
    });
    var delay = (arguments[1] || 0);
    element.morph('top:0px', {
      duration:1.2, 
      delay:delay
    });
    element.up().setStyle({ zIndex:1000 });
  },
  hideCurrentSection: function() {
    if(this.currentSection == 'overview') $('mini_features', 'footnotes_overview').invoke('fade');
    if(this.currentSection == 'deliver') $('get_started_box', 'footnotes_deliver').invoke('fade');
    this.flyOut(this.currentSection+'_1_content', 0.2);
    this.flyOut(this.currentSection+'_2_content');
    this.flyOut(this.currentSection+'_3_content', 0.3);
  },
  changeHeader: function(section) {
    $('page_header_'+section).appear({ delay: .5, duration: 1.0 });
    $('page_header_'+this.currentSection).fade({ delay: .5, duration: 0.7 });
  },
  changeKicker: function(section) {
    $$('div#kicker_left a').invoke('removeClassName', 'active');
    $('kickerlink_'+section).addClassName('active');
  }
};

var Spinner = Class.create({
	initialize: function(id, options){
		this.spinner = $(id);
		this.spinnerImg = this.spinner.down();
		this.animation = null;
		this._frame = 0;
		this.frames = 12;
	},
	show: function(){
	  this.spinner.setStyle({top: document.viewport.getHeight()/2 + document.viewport.getScrollOffsets()[1] - 20 + 'px'});
		this.fx = new Effect.Appear(this.spinner, {duration: .5, from: 0, to: 1});
		
		window.setTimeout(function(){
		  this.animation = setInterval(function(){ this.animate(); }.bind(this), 100);
		}.bind(this), 500); // We need a timeout for IE6 to apply filters on PNG image
		
	},
	animate: function(){
		if(this._frame == this.frames - 1)
			this._frame = 0;
		else
			this._frame++;
		
		this.spinnerImg.setStyle({left: -this._frame*50 + 'px'});
	},
	hide: function(){
		clearInterval(this.animation);
		if(this.fx.state != 'finished') this.fx.cancel();
		new Effect.Fade(this.spinner, {duration: .5});
	}
});

Position.getPageSize = function() {
  var xScroll, yScroll;

  if (window.scrollMaxX) {  
    xScroll = window.innerWidth  + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else {
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } 
  
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  pageHeight = Math.max(windowHeight, yScroll);

  // for small pages with total width less then width of the viewport
  pageWidth = Math.max(windowWidth, xScroll);

  return { page: { width: pageWidth, height: pageHeight }, window: { width: windowWidth, height: windowHeight } };
};


Event.observe(window, 'load', function() {
  if(!$('home') && !$('thedeck') && !$('picocool') && !$('ad')) {
    RocketColumns.initialize();
  	Gallery.initialize();
  } else {
    Gallery.initialize({
      afterFinish: function(){ // afterFinish callback for home page to inject video
        
        this.closeButton.appear();
        //  Thomas König 2008-12-01: google-analytics tracking 
        if(typeof(firstTracker) !=  'undefined') firstTracker._trackPageview('/introduction-video/start');
        //document.observe('click', this.closeEvent);
        
        this.image.insert({after: new Element('div', {id: 'video_wrapper'}).update('<p>To view the video please<br/> <a href="http://www.adobe.com/go/getflashplayer">get the latest Adobe Flash Player</a>')});

        // Init SWFObject
        var params = {
          menu: 'false',
          quality: 'high',
          allowfullscreen: 'false',
          wmode: 'transparent'
        };
        var flashvars = {
          screencolor: "#111111",
          skin: "/javascripts/skin.swf",

          lightcolor: "#717171",
          backcolor: "#000",
          frontcolor: "#555555",
//          tracecall: "arthropod",
          file: '/video/introducing-fluxiom-h264.mov',
          autostart: true
          
        };
        var attributes = {};
        swfobject.embedSWF("/javascripts/player.swf", 'video_wrapper', "640", "500", "9.0.115", false, flashvars, params, attributes);
      }, 
      onClose: function(){
        $('video_wrapper').remove();
      },
      width: 710,
      height: 570
    });
  }
  
  // Video auto start on home page feature
  if($('home') && window.location.href.indexOf('#video') > 0) {
    Gallery.open($('video-link'));
  }
});

/* FLW Player stuff */
var player;
function playerReady(obj) {
  player = $('video_wrapper');
	player.addModelListener('STATE', 'playerObservers');
};
function playerObservers(player){
  if(player.newstate == 'COMPLETED') {
    Gallery.close();
    if(firstTracker !=  'undefined') firstTracker._trackPageview('/introduction-video/completed');    
  }
};