////////////////////////////////////////////////////////////////////////////////
/** 1. VENTANA
 * 2008-05-13 egonpin@gmail.com
 */
var _aVentana = new Array();
var Ventana = Class.create({
  initialize: function(id, titulo) {
    this.id  = trim(id);
    this.idr = "rVen" + this.id;
    this.idH = "tVen" + this.id;
    this.idB = "bVen" + this.id;

    this.idT = "ptVen" + this.id;
    this.idBot = "botVen" + this.id;

   this.oVen = new Element('div', { 'id':this.id, "class":"cVentana" });
	this.oVen.className = "cVentana";

   this.oHe = new Element('div', { 'id':this.idH, "class":"cVentanaH" });
   this.oBo = new Element('div', { 'id':this.idB, "class":"cVentanaB" });

	this.oTit = new Element('div', { 'id':this.idT, "class":"cVentanaT" });
	this.oBot1 = new Element('div', { 'id':this.idBot+"1", "class":"cVentanaBot" });
	this.oBot2 = new Element('div', { 'id':this.idBot+"1", "class":"cVentanaBot" });
	this.oBot3 = new Element('div', { 'id':this.idBot+"1", "class":"cVentanaBot" });

	this.oBot1.update("<img src='../img/window/minimize.gif' class='botVentanaMin' onmouseover=\"changeImagenes(this,'../img/window/minimize_over.gif')\" onmouseout=\"changeImagenes(this,'../img/window/minimize.gif')\" onclick=\"buscaVentana('"+this.id+"').minSize();\" />");
	this.oBot2.update("<img src='../img/window/maximize.gif' class='botVentanaMax' onmouseover=\"changeImagenes(this,'../img/window/maximize_over.gif')\" onmouseout=\"changeImagenes(this,'../img/window/maximize.gif')\" onclick=\"buscaVentana('"+this.id+"').maxSize();\" />");
	this.oBot3.update("<img src='../img/window/close.gif' class='botVentanaClo' onmouseover=\"changeImagenes(this,'../img/window/close_over.gif')\" onmouseout=\"changeImagenes(this,'../img/window/close.gif')\" onclick=\"buscaVentana('"+this.id+"').hide();\" />");

   $("divContenido").insert(this.oVen);
   this.oVen.insert(this.oHe);
   this.oVen.insert(this.oBo);
	this.oHe.insert(this.oTit);
	this.oHe.insert(this.oBot3);
	this.oHe.insert(this.oBot2);
	this.oHe.insert(this.oBot1);

	titulo = titulo?titulo:" Ventana... ";
	this.oTit.update(titulo);

   new Draggable(this.id, { 'handle': this.oTit, 'revert':false });
//   new Resizeable(this.id);
/*
   new Draggable("rVen" + this.id,
						{ 'revert':true,
						  'snap': function(x,y, obj) {
							var _obj = buscaVentana(obj.element.id);
							Anuncio(x + " - " + y + " - " + _obj.id );

						}
						});
*/

		this.estVen = 0; // 0 Cerrada, 1 Abierta, 2 Maximizada, 3 Minimizada
		this.oldW = 450;
		this.oldH = 350;
		this.size(this.oldW, this.oldH);
		this.pos();

     _aVentana.push(this);
  },
  titulo: function(titulo) {
		this.oTit.update(titulo);
  },
  size: function(w,h) {
		var dim = this.oVen.getDimensions();

		if(w != null && h != null)
		{
			var lT = new String(this.oTit.innerHTML);
			var minW = ((lT.length *10) + (18 * 1)); // cantidad de caracteres * tam fuente + (tam botones + numero de botones)
			w = minW>w?minW:w;
			h = 22>h?22:h;

			this.oldW = dim.width;
			this.oldH = dim.height;

			this.oVen.setStyle({
  					width: w,
  					height: (h)
						});

			this.oHe.setStyle({ width: w });

			this.oTit.setStyle({ width: w - (18*1) });  // * numero de botones

			this.oBo.setStyle({ height: (h-22) , width: w });  // Height total de la ventana - head height 22px
		}
		return [ dim.width, dim.height ];
	},
	pos: function(x,y)
	{
		if(!x && !y)
		{
			var dim = this.oVen.getDimensions();
			px = $('divContenido').getScrollDimensions().width;
			py = $('divContenido').getScrollDimensions().height;
			x = Math.abs(px - dim.width)/2;
			y = Math.abs(py - dim.height)/2;
		}
		this.oVen.setStyle({ left: x, top: y });
	},
	minSize: function(){
		if(this.estVen == 3)
		{
			this.estVen = 1;
			this.size(this.oldW, this.oldH);
			this.oBo.show();
		} else
		if(this.estVen == 1 || this.estVen == 2)
		{
			this.size(0,0);
			this.estVen = 3;
			this.oBo.hide();
		}
	},
	maxSize: function(){	},
	cont: function(txt) {
		this.oBo.update(txt);
	},
	autoSize: function() {
	   var dim = this.oBo.getScrollDimensions();
      this.size(dim.width, dim.height);
  },
  show: function() {
		this.estVen = 1;
		this.oVen.show();
	},
  hide: function() {
		this.estVen = 0;
		//alert('cierra');
	  	this.oVen.hide();
	}
});

////////////////////////////////////////////
function buscaVentana()
{
	var _sID = arguments[0];
	var _objx = null;
	var x=0;
//alert('before get ventana');
 	for(x=0; x<_aVentana.length; x++)
	{
		if(trim(_aVentana[x].id) == trim(_sID) || trim(_aVentana[x].idr) == trim(_sID) )
		{
			_objx = _aVentana[x];
      	x = _aVentana.length;
		}
	}
	//alert('get ventana');
	return _objx;
}

// Extendiendo Element
Element.addMethods({
  getScrollDimensions: function(element) {
    return {
      width:  element.scrollWidth,
      height: element.scrollHeight
    }
  },

  getScrollOffset: function(element) {
    return Element._returnOffset(element.scrollLeft, element.scrollTop);
  },

  setScrollOffset: function(element, offset) {
    element = $(element);
    if (arguments.length == 3)
      offset = { left: offset, top: arguments[2] };
    element.scrollLeft = offset.left;
    element.scrollTop  = offset.top;
    return element;
  },

  // returns "clean" numerical style (without "px") or null if style can not be resolved
  // or is not numeric
  getNumStyle: function(element, style) {
    var value = parseFloat($(element).getStyle(style));
    return isNaN(value) ? null : value;
  },

  // by Tobie Langel (http://tobielangel.com/2007/5/22/prototype-quick-tip)
  appendText: function(element, text) {
    element = $(element);
    text = String.interpret(text);
    element.appendChild(document.createTextNode(text));
    return element;
  }
});

// Extendiendo Object
Object.extend(document.viewport, {
  // Alias this method for consistency
  getScrollOffset: document.viewport.getScrollOffsets,

  setScrollOffset: function(offset) {
    Element.setScrollOffset(Prototype.Browser.WebKit ? document.body : document.documentElement, offset);
  },

  getScrollDimensions: function() {
    return Element.getScrollDimensions(Prototype.Browser.WebKit ? document.body : document.documentElement);
  }
});

// script.aculo.us Resizables.js

// Copyright(c) 2007 - Orr Siloni, Comet Information Systems http://www.comet.co.il/en/
//
// Resizable.js is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Resizables = {
	instances: [],
	observers: [],

	register: function(resizable) {
		if(this.instances.length == 0) {
			this.eventMouseUp   = this.endResize.bindAsEventListener(this);
			this.eventMouseMove = this.updateResize.bindAsEventListener(this);

			Event.observe(document, "mouseup", this.eventMouseUp);
			Event.observe(document, "mousemove", this.eventMouseMove);
		}
		this.instances.push(resizable);
	},

	unregister: function(resizable) {
		this.instances = this.instances.reject(function(d) { return d==resizable });
		if(this.instances.length == 0) {
			Event.stopObserving(document, "mouseup", this.eventMouseUp);
			Event.stopObserving(document, "mousemove", this.eventMouseMove);
		}
	},

	activate: function(resizable) {
		if(resizable.options.delay) {
			this._timeout = setTimeout(function() {
				Resizables._timeout = null;
				Resizables.activeResizable = resizable;
			}.bind(this), resizable.options.delay);
		} else {
			this.activeResizable = resizable;
		}
	},

	deactivate: function() {
		this.activeResizable = null;
	},

	updateResize: function(event) {
		if(!this.activeResizable) return;
		var pointer = [Event.pointerX(event), Event.pointerY(event)];
		// Mozilla-based browsers fire successive mousemove events with
		// the same coordinates, prevent needless redrawing (moz bug?)
		if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
		this._lastPointer = pointer;

		this.activeResizable.updateResize(event, pointer);
	},

	endResize: function(event) {
		if(this._timeout) {
		  clearTimeout(this._timeout);
		  this._timeout = null;
		}
		if(!this.activeResizable) return;
		this._lastPointer = null;
		this.activeResizable.endResize(event);
		this.activeResizable = null;
	},

	addObserver: function(observer) {
		this.observers.push(observer);
		this._cacheObserverCallbacks();
	},

	removeObserver: function(element) {  // element instead of observer fixes mem leaks
		this.observers = this.observers.reject( function(o) { return o.element==element });
		this._cacheObserverCallbacks();
	},

	notify: function(eventName, resizable, event) {  // 'onStart', 'onEnd', 'onResize'
		if(this[eventName+'Count'] > 0)
			this.observers.each( function(o) {
				if(o[eventName]) o[eventName](eventName, resizable, event);
			});
		if(resizable.options[eventName]) resizable.options[eventName](resizable, event);
	},

	_cacheObserverCallbacks: function() {
		['onStart','onEnd','onResize'].each( function(eventName) {
			Resizables[eventName+'Count'] = Resizables.observers.select(
				function(o) { return o[eventName]; }
			).length;
		});
	}
}

var Resizable = Class.create();
Resizable._resizing = {};

Resizable.prototype = {
	initialize: function(element){
		var defaults = {
			handle: false,
			snap: false,  // false, or xy or [x,y] or function(x,y){ return [x,y] }
			delay: 0,
			minHeight: false,
			minwidth: false,
			maxHeight: false,
			maxWidth: false
		}

		this.element = $(element);

		var options = Object.extend(defaults, arguments[1] || {});
		if(options.handle && typeof options.handle == 'string')
			this.handle = $(options.handle);
		if(!this.handle) this.handle = this.element;

		this.options  = options;
		this.dragging = false;

		this.eventMouseDown = this.initResize.bindAsEventListener(this);
		Event.observe(this.handle, "mousedown", this.eventMouseDown);

		Resizables.register(this);
	},

	destroy: function() {
		Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
	},

	currentDelta: function() {
		return([
			parseInt(Element.getStyle(this.element,'width') || '0'),
			parseInt(Element.getStyle(this.element,'height') || '0')]);
	},

	initResize: function(event) {
		if(typeof Resizable._resizing[this.element] != 'undefined' &&
			Resizable._resizing[this.element]) return;
		if(Event.isLeftClick(event)) {
			// abort on form elements, fixes a Firefox issue
			var src = Event.element(event);
			if((tag_name = src.tagName.toUpperCase()) && (
				tag_name=='INPUT' || tag_name=='SELECT' || tag_name=='OPTION' ||
				tag_name=='BUTTON' || tag_name=='TEXTAREA')) return;

			this.pointer = [Event.pointerX(event), Event.pointerY(event)];
			this.size = [parseInt(this.element.getStyle('width')) || 0, parseInt(this.element.getStyle('height')) || 0];

			Resizables.activate(this);
			Event.stop(event);
		}
	},

	startResize: function(event) {
		this.resizing = true;
		if(this.options.zindex) {
			this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
			this.element.style.zIndex = this.options.zindex;
		}
		Resizables.notify('onStart', this, event);
		Resizable._resizing[this.element] = true;
	},

	updateResize: function(event, pointer) {
		if(!this.resizing) this.startResize(event);

		Resizables.notify('onResize', this, event);

		this.draw(pointer);
		if(this.options.change) this.options.change(this);

		// fix AppleWebKit rendering
		if(Prototype.Browser.WebKit) window.scrollBy(0,0);
		Event.stop(event);
	},

	finishResize: function(event, success) {
		this.resizing = false;
		Resizables.notify('onEnd', this, event);
		if(this.options.zindex) this.element.style.zIndex = this.originalZ;
		Resizable._resizing[this.element] = false;
		Resizables.deactivate(this);
	},

	endResize: function(event) {
		if(!this.resizing) return;
		this.finishResize(event, true);
		Event.stop(event);
	},

	draw: function(point) {
		var p = [0,1].map(function(i){
			return (this.size[i] + point[i] - this.pointer[i]);
		}.bind(this));

		if(this.options.snap) {
			if(typeof this.options.snap == 'function') {
				p = this.options.snap(p[0],p[1],this);
			} else {
				if(this.options.snap instanceof Array) {
				p = p.map( function(v, i) {
				return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
			} else {
				p = p.map( function(v) {
				return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
			}
		}}

		if (this.options.minWidth && p[0] <= this.options.minWidth) p[0] = this.options.minWidth;
		if (this.options.maxWidth && p[0] >= this.options.maxWidth) p[0] = this.options.maxWidth;
		if (this.options.minHeight && p[1] <= this.options.minHeight) p[1] = this.options.minHeight;
		if (this.options.maxHeight && p[1] >= this.options.maxHeight) p[1] = this.options.maxHeight;

		var style = this.element.style;
		if((!this.options.constraint) || (this.options.constraint=='horizontal')){
			style.width = p[0] + "px";
		}
		if((!this.options.constraint) || (this.options.constraint=='vertical')){
			style.height = p[1] + "px";
		}

		if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
	}
};
