document.oncontextmenu = function() { return false; };

Window._windows = [];
Window._onClosedWindow = function(window) {
    for (var i=0;i<Window._windows.length;i++) {
	if (Window._windows[i]==window) {
	    Window._windows.splice(i, 1);
	    break;
	}
    }

    // Diminuer de 1 les zIndex de chaque fenêtre
    if (!window._optionsWindow['modal']) {
	for (var i=0;i<Window._windows.length;i++) Window._windows[i]._nodeWidget.style.zIndex--;
	
    } else {
	Window._divCaptureEvents.style.display = "none";
	Window._windowModalOpened = null;
    }
};
Window._onToolbarRightClicked = function(window) {
    if (window._optionsWindow['modal']) return;

    var zIndexOfWindow = window._nodeWidget.style.zIndex;

    // le zIndex de id devient 10 (première fenêtre)
    for (var i=0;i<Window._windows.length;i++) {
	var zIndex = Window._windows[i]._nodeWidget.style.zIndex;
	if (zIndex<zIndexOfWindow) Window._windows[i]._nodeWidget.style.zIndex++;
    }
    window._nodeWidget.style.zIndex = 10;
};
Window._onToolbarLeftClicked = function(window) {
    if (window._optionsWindow['modal']) return;

    var zIndexOfWindow = window._nodeWidget.style.zIndex;

    // le zIndex de id devient 10 (première fenêtre)
    for (var i=0;i<Window._windows.length;i++) {
	var zIndex = Window._windows[i]._nodeWidget.style.zIndex;
	if (zIndex>zIndexOfWindow) Window._windows[i]._nodeWidget.style.zIndex--;
    }
    window._nodeWidget.style.zIndex = Window._windows.length + 10;
};
Window._divCaptureEvents = null; // Pour créer les fenêtres modales
Window._windowModalOpened = null;

Window._stylesModel = {
    'toolbar':{'backgroundColor':"#3b83cb", 'color':"#FFF"},
    'barBottom':{'backgroundColor':"#a9a9a9"},
    'window':{'borderColor':'black', 'borderWidth':1}
};
Window.setToolbarStyles = function(styles) { 
    Window._stylesModel['toolbar'] = styles;
    HEvent.trigger(Window, 'dataChanged', 'toolbar');
};
Window.setBarBottomStyles = function(styles) { 
    Window._stylesModel['barBottom'] = styles;
    HEvent.trigger(Window, 'dataChanged', 'barBottom');
};
Window.setWindowStyles = function(styles) { 
    Window._stylesModel['window'] = styles;
    HEvent.trigger(Window, 'dataChanged', 'window');
};

function Window(parent, titre, width, height, options) {
    if (arguments.length==0) return;
    Window._windows.push(this);

    var div = document.createElement('div');
    div.style.position = "absolute";
    div.style.backgroundColor = "#FFF";    
    div.style.border = Window._stylesModel['window']['borderWidth']+"px solid "+Window._stylesModel['window']['borderColor'];

    this.superClass = Widget;
    this.superClass(parent, div);
    delete this.superclass;

    this._layoutWidget = 1;

    this._titreWindow = titre;
    this._widthWindow = width;
    this._heightWindow = height;

    if (this._widthWindow==null) this._widthWindow = 500;
    if (this._heightWindow==null) this._heightWindow = 300;

    this.setWidth(this._widthWindow);
    this.setHeight(this._heightWindow);

    this._widgetToolBar = null;
    this._widgetContent = null;
    this._widgetBarBottom = null;

    this._optionsWindow = {
	'draggabled':true, 
	'padding':'5px', 
	'toolbar':true, 
	'resizabled':true, 

	'modal':false,
	'modalBackgroundColor':"#CCC",
	'modalOpacity':0.2
    };
    if (options) { for (var key in options) this._optionsWindow[key] = options[key]; }

    this._preferedPosWindow = null; // Si est null, alors sera centré, sinon est un objet Point
    
    this._isDraggingWindow = false;
    this._posMouseDragStartWindow = null;
    this._posWindowDragStartWindow = null;

    this._isResizingWindow = false;
    this._posMouseStartResizeWindow = null;
    this._widthWindowStartResizeWindow = null;
    this._heightWindowStartResizeWindow = null;    

    this._listenerEventMouseMoved = null;
    this._listenerEventScreenResized = null;

    this._isOpenedWindow = false;

    HEvent.addListener(Window, "dataChanged", this, this._onStylesChanged);

    /**
     * Créer les enfants (Toolbar, contenu et barre du bas)
     */
    this._createWindow();
};
Window.prototype = new Widget();

Window.prototype._onStylesChanged = function(index) { 
    if (index=='window') {
	this._nodeWidget.style.border = Window._stylesModel['window']['borderWidth']+"px solid "+Window._stylesModel['window']['borderColor'];

    } else if (index=="toolbar" && this._widgetToolBar!=null) {
	this._widgetToolBar._nodeWidget.style.color = Window._stylesModel['toolbar']['color'];
	this._widgetToolBar._nodeWidget.style.backgroundColor = Window._stylesModel['toolbar']['backgroundColor'];

    } else if (index=="barBottom" && this._widgetBarBottom!=null) {
	this._widgetToolBar._nodeWidget.style.backgroundColor = Window._stylesModel['barBottom']['backgroundColor'];
    }
};

Window.prototype.contentWidgetWindow = function() { return this._widgetContent; };

Window.prototype.setContentHTML = function(html) {
    this._widgetContent._nodeWidget.innerHTML = html;
};

Window.prototype.appendContentNode = function(node) {
    this._widgetContent._nodeWidget.appendChild(node);
};

Window.prototype.prependContentNode = function(node) {
    var parent = this._widgetContent._nodeWidget;
    var firstChild = parent.firstChild;

    if (firstChild==null) parent.appendChild(node);
    else parent.insertBefore(node, firstChild);
};

Window.prototype._createWindow = function() {
    var s = this;

    if (this._optionsWindow['modal']) {
	if (Window._divCaptureEvents==null) {
	    var node = document.createElement('div');
	    node.style.position = "absolute";
	    node.style.left = 0;
	    node.style.top = 0;
	    node.style.width = "100%";
	    node.style.height = "100%";
	    node.style.zIndex = 4000;
	    node.style.backgroundColor = this._optionsWindow['modalBackgroundColor'];
	    node.style.display = "none";

	    node.style.opacity = this._optionsWindow['modalOpacity'];
	    node.style.filter = 'alpha(opacity='+(this._optionsWindow['modalOpacity']*10)+')';
	    
	    document.body.appendChild(node);
	    Window._divCaptureEvents = node;
	}
	var node = Window._divCaptureEvents;
	node.style.display = "block";	
	node.style.backgroundColor = this._optionsWindow['modalBackgroundColor'];
	node.style.opacity = this._optionsWindow['modalOpacity'];
	node.style.filter = 'alpha(opacity='+(this._optionsWindow['modalOpacity']*10)+')';
	
	Window._divCaptureEvents.onmousedown = function() {
	    s.trigger("clickedOut");
	    return false;
	};
    }
    
    if (this._optionsWindow['modal']) this._nodeWidget.style.zIndex = 5001;
    else this._nodeWidget.style.zIndex = Window._windows.length + 10;

    var toolBar = null;
    if (this._optionsWindow['toolbar']) {
	toolBar = document.createElement('div');
	toolBar.style.zIndex = Window._windows.length + 10;
	toolBar.style.paddingLeft = "3px";
	toolBar.style.paddingRight = "1px";
	toolBar.style.paddingTop = "1px";
	toolBar.style.paddingBottom = "1px";
	toolBar.style.fontWeight = "bold";
	toolBar.style.color = Window._stylesModel['toolbar']['color'];
	toolBar.style.backgroundColor = Window._stylesModel['toolbar']['backgroundColor'];

	this._widgetToolBar = new Widget(this, toolBar);
	this._widgetToolBar.setSizes({'height':21});
	this._widgetToolBar.show();

	toolBar.appendChild( document.createTextNode(this._titreWindow) );

	var close = document.createElement('a');
	close.href = "#";
	close.style.border = 0;
	close.style.display = "block";
	close.style.position = "absolute";
	close.style.right = "2px";
	close.style.top = 0;
	close.style.width = "21px";
	close.style.height = "21px";
	close.innerHTML = '<img src="/css/images/closeWindow.jpg" />';
	
	close.onclick = function() { s.close(); return false; };
	toolBar.appendChild(close);
    }

    var divContent = document.createElement('div');
    divContent.style.marginLeft = "auto";
    divContent.style.marginRight = "auto";
    divContent.style.overflow = "auto";
    divContent.style.backgroundColor = "white";
    divContent.style.padding = this._optionsWindow['padding'];

    this._widgetContent = new Widget(this, divContent);
    this._widgetContent.setSizes({'height':'*'});
    this._widgetContent.setVerticalLayout();
    this._widgetContent.show();

    var bottomBar = null;
    if (this._optionsWindow['resizabled']) {
	bottomBar = document.createElement('div');
	bottomBar.style.fontWeight = "bold";
	bottomBar.style.backgroundColor = Window._stylesModel['barBottom']['backgroundColor'];
	bottomBar.style.paddingLeft = "3px";
	bottomBar.style.paddingRight = "1px";

	bottomBar.style.backgroundImage = 'url(/css/images/icone-resize.jpg)';
	bottomBar.style.backgroundRepeat = "no-repeat";
	bottomBar.style.backgroundPosition = "right 0px";

	this._widgetBarBottom = new Widget(this, bottomBar);
	this._widgetBarBottom.setSizes({'height':15});
	this._widgetBarBottom.show();

	var resize = document.createElement('div');
	resize.style.border = 0;
	resize.style.display = "block";
	resize.style.position = "absolute";
	resize.style.right = 0;
	resize.style.top = 0;
	resize.style.width = "14px";
	resize.style.height = "15px";

	bottomBar.appendChild(resize);
	resize.onmouseover = function() {
	    resize.style.cursor = "move"; 
	};

	bottomBar.onmousedown = function(evt) {
	    var event = new HEventHandler(evt);

	    s._isResizingWindow = true;
	    
	    s._posMouseStartResizeWindow = Mouse.pos(evt);
	    s._widthWindowStartResizeWindow = s.width();
	    s._heightWindowStartResizeWindow = s.height();

	    event.stopPropagation();

	    return false;
	};

	bottomBar.onmouseup = function(evt) { 
	    s._widthWindow = s.width();
	    s._heightWindow = s.height();

	    s._isResizingWindow = false; 
	    return false; 
	};
	
    }	

    if (toolBar!=null) {
	if (!this._optionsWindow['draggabled']) { // Si on ne peut pas déplacer la fenêtre
	    
	    toolBar.onmousedown = function(evt) {
		var event = new HEventHandler(evt);
		if (event.mouseButton()==3) Window._onToolbarRightClicked(s);
		else Window._onToolbarLeftClicked(s);
		
		event.stopPropagation();
		
		return false;
	    };	

	} else {
	    toolBar.onmouseover = function(evt) { 
		this.style.cursor = "move"; 
		
		var event = new HEventHandler(evt);
		event.stopPropagation();
		
		return false; 
	    };	
	    
	    toolBar.onmousedown = function(evt) {
		var event = new HEventHandler(evt);
		if (event.mouseButton()==3) {
		    Window._onToolbarRightClicked(s);
		    event.stopPropagation();
		    return false;		
		    
		} else Window._onToolbarLeftClicked(s);
		
		s._isDraggingWindow = true;
		
		s._posMouseDragStartWindow = Mouse.pos(evt);
		s._posWindowDragStartWindow = CustomNode.posAbsolute(s._nodeWidget);
		
		event.stopPropagation();
		
		return false;
	    };
	    
	    toolBar.onmouseup = function(evt) { s._isDraggingWindow = false; return false; };		
	}
    }
	
    if (bottomBar!=null || (toolBar!=null && this._optionsWindow['draggabled']))
	this._listenerEventMouseMoved = HEvent.addListener(document, "mousemove", s, s._onMouseMoved);

};

Window.prototype.open = function(preferedPos) {
    if (this._isOpenedWindow) return;

    if (this._optionsWindow['modal']) {
	if (Window._windowModalOpened!=null) {
	    Debug.warning("Vous essayez d'ouvrir une fenêtre modal alors qu'une est déjà ouverte !");
	    return;
	}
	Window._windowModalOpened = this;
    }

    this._isOpenedWindow = true;

    if (preferedPos!=null) this._preferedPosWindow = preferedPos;

    this.show();
    
    var s = this;
    this._listenerEventScreenResized = HEvent.addListener(window, "resized", s, s._onScreenResized);

    this.trigger("opened"); // Permet par exemple, une fois une fenêtre ouverte, de donner le focus à un élément
};

Window.prototype.close = function() {
    this._isOpenedWindow = false;
    
    Window._onClosedWindow(this);

    if (this._listenerEventScreenResized!=null) HEvent.removeListenerFromId(this._listenerEventScreenResized);
    if (this._listenerEventMouseMoved!=null) HEvent.removeListenerFromId(this._handlerEventMouseMove);
    
    this._listenerEventScreenResized = null;
    this._listenerEventMouseMoved = null;

    this.closeWidget();
};
    
/**
 * Appelé chaque fois que la souris se déplace
 */
Window.prototype._onMouseMoved = function(evt) {
    if (this._isDraggingWindow) {
    
	var point = Mouse.pos(evt);
	var dx = point.x() - this._posMouseDragStartWindow.x();
	var dy = point.y() - this._posMouseDragStartWindow.y();
	
	var x = this._posWindowDragStartWindow.x() + dx;
	var y = this._posWindowDragStartWindow.y() + dy;
	
	this._nodeWidget.style.left = x+"px";
	this._nodeWidget.style.top = y+"px";

    } else if (this._isResizingWindow) {
	var point = Mouse.pos(evt);
	var dx = point.x() - this._posMouseStartResizeWindow.x();
	var dy = point.y() - this._posMouseStartResizeWindow.y();
	
	this.setWidth(this._widthWindowStartResizeWindow + dx);
	this.setHeight(this._heightWindowStartResizeWindow + dy);
	this.widgetResized();
    }

};

Window.prototype.becomeReallyVisible = function() {
    this._onScreenResized();
};

Window.prototype._onScreenResized = function() {
  var widthBrowser = browser.width();
  var heightBrowser = browser.height();

  var widthDialog = this._nodeWidget.offsetWidth;
  var heightDialog = this._nodeWidget.offsetHeight;

  if (this._preferedPosWindow==null) {
      var x = Math.ceil( (widthBrowser - this.width())/2 );
      var y = Math.ceil( (heightBrowser - this.height())/2 );
      
  } else {
      var x = this._preferedPosWindow.x();// - document.documentElement.scrollLeft;	
      var y = this._preferedPosWindow.y();// - document.documentElement.scrollTop;	
      
      if (x+this.width()>widthBrowser) x = widthBrowser - this.width();
      if (y+this.height()>heightBrowser) y = heightBrowser - this.height();
  }

  this._nodeWidget.style.left = Math.max(x, 0) + 'px';
  this._nodeWidget.style.top = Math.max(y, 0) + 'px';
};

Window.openContextMenu = function(actions, event) {
    if (actions.length==0) return;
    if (Window._windowModalOpened!=null) Window._windowModalOpened.close();
   
    var ul = document.createElement('ul');
    ul.style.position = "absolute";
    ul.style.left = "-2000px";
    ul.style.top = "-2000px";
    ul.style.width = "1000px";
    
    ul.style.backgroundColor = "#EEE";
    ul.style.paddingTop = "10px";
    ul.style.paddingRight = "10px";
    ul.style.paddingBottom = "10px";
    ul.style.paddingLeft = "10px";

    // Nécessaire pour pouvoir calculer les dimensions
    document.body.appendChild(ul);

    var width = 0;
    var height = 0;
    for (var i=0;i<actions.length;i++) {
	var li = document.createElement('li');
	li.style.margin = 0;
	li.style.padding = 0;
	li.style.border = "1px solid #EEE"; // Obligé, sinon calcule mal la hauteur ???
	ul.appendChild(li);
	var span = document.createElement('span');
	li.appendChild(span);

	if (actions[i]['func']==null) {
	    span.innerHTML = actions[i]['text'];
	    if (actions[i]['color']==null) span.style.color = "black";
	    else span.style.color = actions[i]['color'];

	} else {
	    var a = document.createElement('a');
	    a.innerHTML = actions[i]['text'];
	    if (actions[i]['color']==null) a.style.color = "black";
	    else a.style.color = actions[i]['color'];
	    
	    a.href = "#";
	    a.onclick = (function(func) { 
		    return function() { 
			if (func()) {
			    // L'utilisateur demande à ce que le ContextMenu soit fermé
			    if (Window._windowModalOpened!=null) Window._windowModalOpened.close();
			}
			return false; 
		    }
		})(actions[i]['func']);

	    span.appendChild(a);
	}	

	if (span.offsetWidth>width) width = span.offsetWidth;

	if (i!=actions.length-1) {
	    var hr = document.createElement('hr');
	    hr.style.border = "1px solid black";	    
	    li.appendChild(hr);
	}
	height += li.offsetHeight;
    }

    width += 20;
    height += 20;

    ul.style.width = width + "px";
    ul.style.height = height + "px";

    document.body.removeChild(ul);
    ul.style.position = "relative";
    ul.style.left = 0;
    ul.style.top = 0;

    var context = new Window(null, "", width+2, height+2, {'toolbar':false, 'resizabled':false, 'modal':true, 'padding':0});    
    context._nodeWidget.style.border = "1px solid #CCC";

    context.setHandler("clickedOut", function() { context.close(); });

    context.appendContentNode(ul);
    
    context.open(event.pos());    
    context._widgetContent._nodeWidget.scrollTop = 0;
    context._widgetContent._nodeWidget.style.overflow = "hidden";
};

Window.closeContextMenu = function() { if (Window._windowModalOpened!=null) Window._windowModalOpened.close(); };

