// Juan Matias de la Camara Beovide
// TJF - Tiger JavaScrip Framework
// Abril 2008

// Este script incluye el objeto para manejar ventanas

// Modo de uso 
//	win1 = new TJF_Window( { title: 'Ventana número 1',
//				 close: true,
//				 onclose : closing_win,
//				 icon: 'favicon.ico'
//			       }
//	);
//
//	var html_window_element = win1.get_element();
//	dst.appendChild( html_window_element );
//
//	var region_for_draw = win1.get_free_region();
//
//	region_for_draw.innerHTML = 'hola';
//
//
//
//	function closing_win() {
//	  alert("cerrando la ventana " + this.options.title);
//	}


var TJF_Window = Class.create();

TJF_Window.Scroll = {
  Disable : 1,
  Enable  : 2,
  Auto	  : 3
};

TJF_Window.DEFAULTS = {
  title:  null,
  titlebar: true,
  width: 400,
  height: 300,
  border: '1px solid black',
  backgroundColor: 'white',
  titlebar_backgroundColor: 'orange',
  titlebar_color: 'black',
  titlebar_height: '20px',
  font_size: '11px',
  font_family: 'Verdana,Times',
  font_weight: 'bold',
  icon:	false,
  icon_width: 11,
  icon_height: 11,
  close: false,
  onclose: null,
  scroll: TJF_Window.Scroll.Auto,
  draggeable: true,
  pos_auto: false, // para que se autoposicione con el scroll del navegador
  centered: false
};


TJF_Window.prototype = {

  initialize: function( options ) {

    this.options = Extend(options, TJF_Window.DEFAULTS );

    // events
    this.events	= {
      onclose:	    [],
      onmousedown:  []
    };

    if ( this.options.close && this.options.onclose ) {
      this.register_onclose_handler( this.options.onclose.bindAsEventListener(this) );
    }

    this._element = this._create_window();
    this._helper  = this._create_helper();

    this.element = CE('div');
    this.element.style.position = 'absolute';
    this.element.style.border = '0px dashed blue';
    this.element.style.width = parseInt( this.options.width + 5 ) + 'px';
    this.element.style.height= parseInt( this.options.height + 5 ) +  'px';
    this.element.appendChild( this._helper );
    this.element.appendChild( this._element );

    if ( this.options.draggeable )
      this.element.draggeable_move = this.move.bind(this);

  },

  show: function() {
    this.element.style.display = '';
  },

  hide: function() {
    this.element.style.display = 'none';
  },

  get_element: function() {
    return this.element;
  },

  get_free_region: function() {
    return ( this.options.titlebar ) ? this._element.childNodes[1] : this._element.childNodes[0];
  },

  move: function(x,y) {
    abs_pos(this.element,x,y);
  },

  move_relative: function(deltaX,deltaY) {
    var offset = get_abs_offset(this.get_element());
    this.move( offset.left + deltaX, offset.top + deltaY );
  },

  opacity: function(opacity) {
    set_opacity(this.get_element(), opacity);

  },

  precedence: function(zIndex) {
    this.element.style.zIndex = zIndex;
  },

  


  _create_helper: function() {
    var helper = CE('iframe');
    helper.style.width = parseInt( this.options.width ) + 'px';
    helper.style.height= parseInt( this.options.height) + 'px';
    //helper.style.position = 'relative';
    //helper.style.top= '-' + this.options.height + 'px';
    helper.style.zIndex= 100;
    helper.style.border= '0px solid blue';
    return helper;
  },

  // Cuando creamos una ventana tenemos que tener en cuenta que si la ventana se posiciona sobre un
  // SELECT, en Internet Explorer, se mostrará siempre como primer elemento el SELECT sin importar el
  // valor de z-index que estemos usando. Para eliminar este problema se utiliza un iframe con el mismo
  // tamaño que el div ppal pero con un z-index menor
  _create_window: function() {

    // creamos el container general
    var container = CE('div');
    container.style.width = parseInt( this.options.width ) + 'px';
    container.style.height= parseInt( this.options.height) + 'px';
    container.style.border = this.options.border;
    container.style.overflow = 'hidden';
    container.style.zIndex= 101;
    container.style.position = 'relative';
    container.style.top= '-' +  this.options.height + 'px';


    if ( this.options.titlebar ) {

      // la titlebar
      var titlebar = CE('div');

      this._titlebar = titlebar;

      titlebar.onmousedown = this.onmousedown.bindAsEventListener(this);

      if ( this.options.draggeable ) {
        //titlebar.onmousedown = this.onmousedown.bindAsEventListener(this);
	this.register_onmousedown_handler( this.start_dragging.bindAsEventListener(this) );
      }
      
      with (titlebar.style) {
        backgroundColor = this.options.titlebar_backgroundColor;
        width	      = '100%';
        height	      = this.options.titlebar_height;
        color	      = this.options.titlebar_color;
      }
  
      // la tabla asociada
      var table = CE('table');
      table.style.color = this.options.titlebar_color;
  
      var tbody = CE('tbody');
      var tr = CE('tr');
  
      // icono
      if ( this.options.icon ) {
        var td_icon = CE('td');
        td_icon.appendChild( this._createIcon(this.options.icon) );
        tr.appendChild( td_icon );
      }
  
      // titulo
      var title = CE('td')
      var title_text = ( this.options.title ) ? this.options.title : '';
      title.appendChild( CT(title_text) );
      title.style.width = '100%';
      title.style.fontFamily = this.options.font_family;
      title.style.fontSize= this.options.font_size;
      title.style.fontWeight= this.options.font_weight;
      tr.appendChild( title );
  
      // opcion de cierre
      if ( this.options.close ) {
  
        var close = CE('td');
        close.style.cursor = 'pointer';
        close.style.fontSize = '10px';
        close.appendChild( CT('cerrar') );
        close.onclick = this.close.bind(this);
        tr.appendChild(close);
  
      }
  
      tbody.appendChild(tr);
      table.appendChild(tbody);
      titlebar.appendChild(table);
  
      container.appendChild(titlebar); 
    }

    // el resto de la venta
    var free_region = CE('div');

    free_region.style.backgroundColor = this.options.backgroundColor;

/*
    with ( free_region.style ) {
      width = '100%';
      height = '100%';
    }
*/
    var effective_width = this.options.width;
    var effective_height= this.options.height;

    if ( title )
      effective_height -= parseInt(this.options.titlebar_height);

    with ( free_region.style ) {
      width = effective_width + 'px';
      height= effective_height + 'px';
    }


    switch (this.options.scroll) {
      case TJF_Window.Scroll.Enable:    free_region.style.overflow = 'scroll';
				    break;

      case TJF_Window.Scroll.Auto:	    free_region.style.overflow = 'auto';
				    break;

      case TJF_Window.Scroll.Disable:
      default:
				    free_region.style.overflow = 'hidden';
				    break;

    };


    // unimos la región de usuario
    container.appendChild(free_region); 

    return container;
  },


  ///// NO FUNCIONA EN WINDOWS... SE VE EL IFRAME
  hide_titlebar : function() {
    if  ( this._titlebar ) {
      var height = parseInt(this._titlebar.style.height);
      this.move_relative(0, +height);
      this._titlebar.style.display = 'none';
      var cont = this._element;
      var helper  = this._helper;
      cont.style.height = parseInt(cont.style.height) - height + 'px';
      helper.style.height = parseInt(helper.style.height) - height + 'px';
    }
  },

  
  ///// NO FUNCIONA EN WINDOWS... SE VE EL IFRAME
  show_titlebar : function() {
    if  ( this._titlebar ) {
      var height = parseInt(this._titlebar.style.height);
      this.move_relative(0, -height);
      this._titlebar.style.display = '';
      var cont	  = this._element;
      var helper  = this._helper;
      cont.style.height = parseInt(cont.style.height) + height + 'px';
      helper.style.height = parseInt(helper.style.height) + height + 'px';
      //console.log("SHOW: " + cont.style.height);
    }
  },

  hide_border:	function() {
    if ( this.options.border ) {
      // y debemos tener en cuenta el borde..
      var border_size = (this.options.border) ? parseInt(this.options.border) : 0;
      this.move_relative(+border_size, +border_size);

      this._element.style.border = '0px solid blue';
    }
  },

  show_border:	function() {
    if ( this.options.border ) {

      // y debemos tener en cuenta el borde..
      var border_size = (this.options.border) ? parseInt(this.options.border) : 0;
      this.move_relative(-border_size, -border_size);

      this._element.style.border = this.options.border;
    }
  },

  start_dragging: function(e) {	
    TJF_Drag.start(this.element,e);
  },

  
  onmousedown: function(e) {

    // llamamos al handler del usuario si está seteado
    if ( this.events.onmousedown.length > 0 ) {
      for(var iter=0; iter < this.events.onmousedown.length; iter++) {
	// Ejecutamos la funcion solicitada, pasando como argumento
	// el handler de la ventana 
	this.events.onmousedown[iter](e);
      }
    }

  },

  close: function(e) {

    // llamamos al handler del usuario si está seteado
    if ( this.events.onclose.length > 0 ) {
      for(var iter=0; iter < this.events.onclose.length; iter++) {
	// Ejecutamos la funcion solicitada, pasando como argumento
	// el handler de la ventana 
	this.events.onclose[iter](this);
      }
    }

  },

  _createIcon: function( image_name ) {
    var img = CE('img');
    img.src = image_name;

    with ( img.style ) {
      width = parseInt( this.options.icon_width ) + 'px'; 
      height= parseInt( this.options.icon_width ) + 'px'; 
    }
    
    return img;
  },

  // la función de callback seteada recibe como argumento el objeto window donde se ha producido el evento
  register_onclose_handler: function(func) {
    this.events.onclose[ this.events.onclose.length ] = func.bindAsEventListener(this);
  },

  // la función de callback seteada recibe como argumento el objeto window donde se ha producido el evento
  register_onmousedown_handler: function(func) {
    this.events.onmousedown[ this.events.onmousedown.length ] = func.bindAsEventListener(this);
    //this._titlebar.onclick = func.bindAsEventListener(this);
  }

  	
};
