var PopupBox = Class.create();
PopupBox.create = function ( content ) {
  var box = new PopupBox( content, arguments[1] || {});
  return box.popupbox;
}

PopupBox.prototype = {
  popupbox: null,
  initialize: function(url) {
    this.setOptions(arguments[1] || {});
    var clonedBox = this.setup();
    clonedBox.update(url);
    clonedBox.position();
    clonedBox.display();
    this.popupbox = clonedBox;
  },
  setOptions: function(options) {
    this.options = {
      type: 'text',
      template: 'popup-box-template',
      height: false,
      width:'250',
      top: null,
      left: null,
      title: '&nbsp;',
      draggable: false,
      closeable: true,
      zindex: '1005',
      closeButton: false,
      id: '',
      modal: true,
      timeout: 0,
      classNames: ['template-box-1','box-layout-1','popup-box']
    }
    Object.extend(this.options, options || {});
  },
  setup: function () {
    this.event('beforeSetup');
    
    if (this.options.id.length > 0 && $(this.options.id)) {
      $(this.options.id).parentNode.removeChild($(this.options.id));
    }
    var clonedBox = this.cloneTemplate();
    clonedBox.cleanWhitespace();
    Object.extend( clonedBox, this );
    if( this.options.draggable ) {
      new Draggable(clonedBox,{handle: 'move_handle'});
    }
    else {
      $(clonedBox.firstChild).removeClassName('move_handle');
    }
    clonedBox.firstChild.cleanWhitespace();
    //clonedBox.firstChild.firstChild.cleanWhitespace();
    //var closeButton = clonedBox.firstChild.firstChild;
    //closeButton.onclick = function(){this.parentNode.parentNode.close();};
    //closeButton.onclick.bindAsEventListener(clonedBox);

    // title
    clonedBox.firstChild.cleanWhitespace();
    clonedBox.myTitle = $(clonedBox.firstChild.lastChild);

    // box-body:
    clonedBox.contentBox = $(clonedBox.lastChild);
    clonedBox.contentBox.addClassName('infos-border');

    this.event('afterSetup');
    return clonedBox;
  },
  cloneTemplate: function() {
    var clonedBox = $(this.options.template).cloneNode(true);
    clonedBox.hide();
    clonedBox.setAttribute('id',this.options.id);
    clonedBox.setStyle({zIndex: this.options.zindex});
    clonedBox.className = $A(this.options.classNames).join(' ');
    document.body.appendChild(clonedBox);
    return clonedBox;
  },
  position: function( ) {
    //Position.absolutize( this );
    var arrayPageSize = this.getPageSize();
    var arrayPageScroll = this.getPageScroll();
    var position = {};
    var boxHeight = this.getDimensions().height;

    if(this.options.height) {
      this.contentBox.setStyle({height: this.options.height});
    }

    position.left = (this.options.left ? this.options.left : (arrayPageSize[2] / 2 - this.options.width / 2)) + 'px';
    position.top = (this.options.top ? this.options.top : arrayPageScroll[1] + (arrayPageSize[3] / 2 - boxHeight / 2)) + 'px';
    position.width = this.options.width + 'px';

    this.setStyle({position:'absolute', top: position.top, left: position.left, width: position.width, height: 'auto'});
  },
  event: function(eventName) {
    //if(this.options['_'+eventName]) this.options['_'+eventName]();
    if(this.options[eventName]) {
      this.options[eventName].bind( this );
      this.options[eventName]();
    }
  },
  update: function( content ) {
    this.event('beforeUpdate');

    if(this.options.title.length == 0) {
      $(this.myTitle.parentNode).hide();
    } else {
      $(this.myTitle).update(this.options.title);
    }

    switch(this.options.type) {
      case 'ajax':
      this.loader = $(document.createElement('DIV'));
      this.loader.setStyle({backgroundImage: 'url(/pics/globaluniversal/progress/ajax-loader.gif)',backgroundPosition: 'center', backgroundRepeat: 'no-repeat', height: '250px', width: 'auto' });
      this.contentBox.appendChild(this.loader);

      var onComplete = this.options.onComplete || Prototype.emptyFunction;
      this.options.onComplete = (function(transport, param) {
        this.appendCloseButton(this.newContentBox);
        this.setTimeout();
        this.ajaxUpdate();
        onComplete(transport, param);
      }).bind(this);
      this.newContentBox = $(document.createElement('DIV'));
      this.newContentBox.hide();
      this.contentBox.appendChild(this.newContentBox);
      new Ajax.Updater(this.newContentBox,content,this.options);
      break;
      case 'element':
      this.contentBox.update($(content).innerHTML);
      this.appendCloseButton(this.contentBox);
      this.setTimeout();
      break;
      default:
      this.contentBox.update(content);
      this.appendCloseButton(this.contentBox);
      this.setTimeout();
    }
    this.event('afterUpdate');
  },
  ajaxUpdate: function() {
    var newContent = this.newContentBox.getDimensions();
    var curContent = this.contentBox.getDimensions();
    var wholeBox = this.getDimensions();
    var loader = this.loader.getDimensions();
    var xScale = ((newContent.width + wholeBox.width - loader.width)  / wholeBox.width) * 100;
    var yScale = ((newContent.height + wholeBox.height - curContent.height) / curContent.height) * 100;
    new Effect.Scale(this.contentBox, yScale, {scaleX: false, duration: 0.5,scaleFromCenter: true, scaleContent: false });
    new Effect.Scale(this, xScale, {scaleY: false, delay: 0.5, duration: 0.5, scaleFromCenter: true, scaleContent: false, afterFinish: (function() {
      $(this.loader).remove();
      this.newContentBox.show();
    }).bind(this)});
  },
  display: function() {
    this.event('beforeShow');
    var clonedBox = this;
    new Effect.Appear( clonedBox, {
      duration: this.options.duration || 0.5,
      from: this.options.from || 0.0,
      to: this.options.to || 1.0,
      afterFinish: clonedBox.options['afterShow'] || Prototype.emptyFunction
    });
    if(this.options.modal == true && $('popupbox-overlay')) {
      var arrayPageSize = Lightbox.prototype.getPageSize();
//      Element.setHeight('popupbox-overlay', arrayPageSize[1]);
      $('popupbox-overlay').setStyle({height:arrayPageSize[1]+"px"});
      $('popupbox-overlay').show();
    }
  },
  close: function() {
    this.event('beforeClose');
    //this.contentBox.hide();
    new Effect.SwitchOff( this ,{
      afterFinish: (function() { if (this.parentNode) this.parentNode.removeChild(this); }).bind(this)
    });

    if(this.options.modal == true && $('popupbox-overlay')) {
      $('popupbox-overlay').hide();
    }
  },
  setTimeout: function () {
    if(this.options.timeout == 0) {
      return;
    }
    this._timeout = setTimeout((function(){this.close()}).bind(this),this.options.timeout * 1000);
  },
  appendCloseButton: function( whereToAppend ) {
    if(!this.options.closeButton) {
      return;
    }
    var closeButtonBox = $(document.createElement('P'));
    closeButtonBox.setStyle({textAlign: 'center'});

    var closeButton = $(document.createElement('BUTTON'));
    closeButton.addClassName('button');
    closeButton.setStyle({marginTop: '15px', fontSize: '11px'});
    closeButton.onclick = (function() {this.close();}).bind(this);
    closeButton.appendChild(document.createTextNode(this.options.closeButton.length > 0 ? this.options.closeButton : 'Close'));
    closeButtonBox.appendChild(closeButton);
    whereToAppend.appendChild(closeButtonBox);
  },

  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(){
  
  	var xScroll, yScroll;
  
  	if (window.innerHeight && window.scrollMaxY) {
  		xScroll = document.body.scrollWidth;
  		yScroll = window.innerHeight + window.scrollMaxY;
  	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
  		xScroll = document.body.scrollWidth;
  		yScroll = document.body.scrollHeight;
  	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
  		xScroll = document.body.offsetWidth;
  		yScroll = document.body.offsetHeight;
  	}
  
  	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
  	if(yScroll < windowHeight){
  		pageHeight = windowHeight;
  	} else {
  		pageHeight = yScroll;
  	}
  
  	// for small pages with total width less then width of the viewport
  	if(xScroll < windowWidth){
  		pageWidth = windowWidth;
  	} else {
  		pageWidth = xScroll;
  	}
  
  
  	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
  	return arrayPageSize;
  },
  //
  // getPageScroll()
  // Returns array with x,y page scroll values.
  // Core code from - quirksmode.org
  //
  getPageScroll: function() {
    
    var yScroll;
    
    if (self.pageYOffset) {
    	yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
    	yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
    	yScroll = document.body.scrollTop;
    }
    
    arrayPageScroll = new Array('',yScroll)
    return arrayPageScroll;
  }
};
