/*!
 * popup js
 * http://whypluseight.com/
 *
 * Copyright 2010, y8 (Ho-teng Chang)
 */

jQuery(function($){
  
  var ns  = "y8popup";
  var ns2 = "ppp";
  
  var ppp = window[ns] = window[ns2] = function(scene, control) {
    this.scene = scene;
    this.control = control;
    
    if (this.scene.length === 0 || this.control.length === 0) return;
    
    
    this.init();
  };
  ppp.prototype = {
    init: function() {
      
      this.width  = this.scene.width();
      this.height = this.scene.height();
      
      this.scene.hide()
                .css({  position:   'absolute',
                        top:        0,
                        left:       0
                      });

      this.reset();
      this.prepare();
      this.observe();
    },
    
    reset: function() {
      this.is_showing = 0;
    },
    
    prepare: function() {
      this.overlay  = $('<div>').css({  position:   'absolute',
                                        top:        0,
                                        left:       0,
                                        background: 'none',
                                        display:    'none'
                                        })
                                .appendTo('body');
      this.close = $('<a>').css({ position: 'absolute', 
                                  top: '10px', 
                                  right: '10px'})
                           .attr('href','#')
                           .html("CLOSE / X")
                           .click($.proxy(this.close, this))
                           .appendTo(this.scene);
    },
    
    close: function(event) {
      event.preventDefault();
      event.currentTarget.blur();
      this.scene.hide();
      this.reset();
      
    },
    
    observe: function() {
      // observe
      this.control.click($.proxy(this.start, this));
    },
    
    start: function(event) {
      event.preventDefault();
      if (this.is_showing) return;
      this.is_showing = 1;
      
      this.position();
      this.show();
    },
    
    position: function() {
      
      var l = ($(window).width() - this.width) / 2;
      if (l<0) l = 0;
      l += $(window).scrollLeft();
      
      var t = ($(window).height() - this.height) / 2;
      if (t<10) t = 10;
      t += $(window).scrollTop();
      
      this.scene.css({
        left: l + 'px',
        top:  t + 'px'
      });
    },
    
    show: function() {
      this.scene.show();
    }
    
  };
  
});
