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

// Este archivo contiene al objeto TJF_Desktop


// suscriptor de desktops. en teoria deberia haber uno solo, pero esto permitiria
// manejar n en la funcion de reposicionamiento de ventanas
var TJF_DesktopsCollection = new Array();
var TJF_DesktopReposActive = false;

  function TJF_Desktop_reposWindows(interval) {
  	// Seteo la variable para saber si existen ventanas reubicables
  	var existenVentanas = false;
  	// Averiguo el tamaño de la ventana
    var sw = parseInt(document.body.clientWidth);
    var sh = parseInt(document.body.clientHeight);
  	// Para cada desktop suscripto
  	for(i=0;i<this.TJF_DesktopsCollection.length;i++){
  		// busco las ventanas suscritas
		for(f=0;f<TJF_DesktopsCollection[i].windowsPosAuto.length;f++){
		    var e = TJF_DesktopsCollection[i].windowsPosAuto[f].oWin.get_element();
			var nx = TJF_DesktopsCollection[i].windowsPosAuto[f].x;
			var ny = TJF_DesktopsCollection[i].windowsPosAuto[f].y;

		    if ( window.scrollY ) {
			  nx += window.scrollX;
			  ny += window.scrollY;
		    }
		    else if ( document.body.scrollTop ) {
			  nx += document.body.scrollLeft;
			  ny += document.body.scrollTop;
		    }  	
			TJF_DesktopsCollection[i].windowsPosAuto[f].oWin.move(nx,ny);
			existenVentanas = true;
		}
	}

	if(existenVentanas ==  true){
		setTimeout("TJF_Desktop_reposWindows("+interval+")",interval);
		TJF_DesktopReposActive = true;
	} else { 
		TJF_DesktopReposActive = false;
	}
  }
  
  
// Ahora el desktop en si mismo
var TJF_Desktop = Class.create();

TJF_Desktop.Position = {
  Auto	  : 1,
  Manual  : 2
};

TJF_Desktop.DEFAULTS = {
  position  : TJF_Desktop.Position.Auto,
  container : null,
  INITIAL_X_POSITION: 10, 
  INITIAL_Y_POSITION: 10,
  DELTA_X_POSITION  : 20,
  DELTA_Y_POSITION  : 20,
  MAX_WINDOWS_PER_DELTA_POSITION: 5,
  reposInterval : 1000
};


TJF_Desktop.prototype = {


  initialize: function(options) {
    this.options = Extend(options, TJF_Desktop.DEFAULTS);
    this.windows    = new Array();
    this.windowsPosAuto    = new Array(); // Para las ventanas sensibles a los scrolls
    this.actual_windows_position_counter = 0;
    
    // el container no puede setearse a document.body por default si no se
    // especifica debido a que en este punto, todavía no existe document.body
    this.container  = this.options.container;
    
    // suscribo este desktop
    TJF_DesktopsCollection.push(this);
  },


  // en options puede especificarse particularmente si esta ventana debe autoposicionarse (TJF_Desktop.Position.Auto)
  add:	function(win, options) {

    if ( this.container == null ) {
      this.container = document.body;
    }

    // verificamos si ya está en el TJF_Desktop, si es asi no la agregamos
    if ( this.find(win) != -1 ) {
      alert("ya existe!");
      return;
    }
  
    // agregamos la ventana
    this.windows.push(win);

    // 
    var desktop = this;

    // registramos los handlers para el cierre de las ventanas
    
    win.register_onclose_handler( function() { desktop.remove(win); } );

    // y para llevar la ventana al frente cuando se clickea sobre la misma
    win.register_onmousedown_handler( function() { desktop.to_front(win); } );

    // agregamos al container
    this.container.appendChild(win.get_element());

    // ajustamos la precedencia visual
    this._adjust_precedences();

	var pos;
	
    if ( this.options.position == TJF_Desktop.Position.Auto ) {
      	if ( win.options.centered ) {
      		pos = this._find_centered_position(win);
      		win.move(pos.x,pos.y);
      	} else {
	      	pos = this._find_next_position();
			win.move(pos.x,pos.y);
      	}
//      if ( !( options && options.position==TJF_Desktop.Position.Manual) ) {
//      }
    }
    
    // Para ver si tengo que reubicar automaticamente la ventana cada n segundos
    // Sirve para reubicar luego de un scroll
    if(win.options.pos_auto == true){
    	this.windowsPosAuto.push({ oWin : win , x : pos.x , y : pos.y});
    	// Activo el scrip para reposicionar
    	TJF_Desktop_reposWindows(this.options.reposInterval);
    }
    
  },


  _find_centered_position: function(win){

    var bwidth = parseInt(document.body.clientWidth);
    var bheight = parseInt(document.body.clientHeight);
	var wwidth = parseInt(win.element.style.width);
	var wheight = parseInt(win.element.style.height);

	var x_pos = parseInt(( bwidth / 2 ) - ( wwidth / 2));
	var y_pos = parseInt(( bheight / 2 ) - ( wheight / 2));

	x_pos = (x_pos<0)?0:x_pos;
	y_pos = (y_pos<0)?0:y_pos;

    return { x: x_pos, y: y_pos };
  },
  
  _find_next_position: function(){

    var x_pos = this.options.INITIAL_X_POSITION + this.actual_windows_position_counter * this.options.DELTA_X_POSITION;
    var y_pos = this.options.INITIAL_Y_POSITION + this.actual_windows_position_counter * this.options.DELTA_Y_POSITION;


    // si superamos el máximo de ventanas abiertas PARA POSICIONAMIENTO volvemos a empezar
    if ( this.actual_windows_position_counter++ >= this.options.MAX_WINDOWS_PER_DELTA_POSITION )
      this.actual_windows_position_counter = 0;

  
    return { x: x_pos, y: y_pos };
  },

  _adjust_precedences: function() {
    var a = this.windows;
    var l = a.length;

    var initial_precedence = 100+l;

    for(var iter=l-1,precedence = initial_precedence; iter>=0; iter--, precedence--) {
      var win = a[iter];
      win.precedence(precedence);
    }

  },

  find: function(search_win) {
    var a = this.windows;
    var l = a.length;

    for(var iter=l-1; iter>=0; iter--) {
      var win = a[iter];

      //console.log("Comparando " + win + " con " + search_win );

      if ( win == search_win )
	return iter;

    }

    return -1;
  },

  to_front: function(win) {

    var index = this.find(win);

    if ( index == -1 )
      return false;

    var a = this.windows;
    a.splice(index,1);
    a.push(win);

    this._adjust_precedences();
  },

  to_back: function(win) {
  
    var index = this.find(win);

    if ( index == -1 )
      return false;

   
    var a = this.windows;
    a.splice(index,1);
    a.unshift(win);

    this._adjust_precedences();

  },

  remove: function(win) {

    var index = this.find(win);

    //console.log("Eliminando ventana " + index + " ("+win+")");
    if ( index == -1 )
      return false;


    var a = this.windows;
    a.splice(index,1);

    this.container.removeChild(win.get_element());

  }


  

};

