﻿// Nmma.Dialog

//if (Object.isUndefined(Nmma)) { var Nmma = { }; }

Nmma.Dialog = Class.create({
  initialize: function(parameters) {
	  /// Constructor
    /// This only creates the dialog, hooks up events, and registers it with the Manager but does not show it.
    this.id = '_dialog' + new Date().getTime();	
    if ($(this.id)) {
	    alert("Dialog " + this.id + " already exists.");
	  }

    this.parameters = {};
    this.url = '';
    this.requestOptions = {};
    this.modal = true;
    this.width = 0;
    this.height = 0;
    this.dragging = false;
    this.draggable = false;
    this.float = false;
    this.resizable = false;   
    this.resizing = false;
    this.collapsed = false;
    this.submitting = null;

    this.useScriptaculous = typeof Effect != 'undefined';
    this.isIE = (navigator.appVersion.indexOf('MSIE') > 0) && (navigator.userAgent.indexOf('Opera') < 0); 
	
	  this.resetParameters();	
	  this.setParameters(parameters);
	
    this.eventClick = this.click.bindAsEventListener(this);
    this.eventMouseDown = this.mouseDown.bindAsEventListener(this);
    this.eventMouseUp = this.mouseUp.bindAsEventListener(this);
    this.eventMouseMove = this.mouseMove.bindAsEventListener(this);
    
    this.eventMouseDownContent = this.focus.bindAsEventListener(this);
    this.eventwindowScrollOrResize = this.windowScrollOrResize.bindAsEventListener(this);
	
    this.build();	
	
    DialogManager.register(this);	
  },

  addButton: function(label, method, index) {
    /// Add a button to the button area of the popup.
	  /// label: Label of the button
	  /// method: Method that will be triggered on the click event.
	  /// index: Specifies the position of the button (zero-based). 0 means before the buttons. Default is after the buttons.
    var label = label ? label : 'button';
    var index = index != null ? index : -1;	
	  index = /^\d+$/.test(index) ? index : -1;
	  var buttons = this.buttonarea.select('input');	
	  var button = new Element('input', { 'type' : 'button', 'class' : this.parameters.cssClass + '_button', 'value' : label, 'id' : this.id + '_button_' + buttons.length });
    if (Object.isUndefined(buttons[index])) {
  	  this.buttonarea.appendChild(button);
  	}
  	else {
	    Element.insert(buttons[index], {'before' : button});
  	}
	  if (method) {
	    this.addMethod(button, method);
  	}
	  else {
	    this.addMethod(button, function() { alert('No method.'); });
	  }
	  return button;
  },
  addMethod: function(element, method) {
    /// Add a method to an element of the popup. This method will be called when the element is clicked.
    if (element) {     
      if (Object.isElement(element)) { 
	      if (element.descendantOf(this.dialog)) {
	  	    if (method && !Object.isUndefined(method) && Object.isFunction(method)) {
            element.method = method;
            element.observe('click', this.eventClick);
	        }            
	      }
      }
	  }
  },
  applyParameters: function() {
    /// Apply the user parameters to the dialog before showing it
    if (this.parameters.width <= 0) {
      this.parameters.width = 400;
    }
    if (this.parameters.height <= 0) {
      this.parameters.width = 400;
    }
    if (this.parameters.minWidth <= 0) {
      this.parameters.minWidth = 300;
    }
    if (this.parameters.minHeight < this.titlebar.getDimensions().height) {
      this.parameters.minHeight = this.titlebar.getDimensions().height;
    }
    if (this.parameters.minHeight <= 0) {
      this.parameters.minHeight = 30;
    }
    this.height = this.parameters.height;
    this.width = this.parameters.width;    
    if (this.parameters.zIndex > 0) {
      this.setZIndex(this.parameters.zIndex);
    }
    this.dialog.setStyle({ 'min-height' : this.height + 'px', 'min-width' : this.width + 'px' });
    this.dialog.setStyle({ 'width' : this.width + 'px' });
	
    this.setClass(this.parameters.cssClass);
    if (this.isIE) { // Rounded corner doesn't work in IE anyway
      this.parameters.roundedCorners = false;
    }
    if (this.parameters.roundedCorners) {
      this.dialog.addClassName('roundedcorners');        
      this.titlebar.addClassName('roundedcorners');    
    }
    if (this.parameters.draggable) {
      this.titlebar.addClassName('draggable');
    }
    if (this.parameters.showButtons) {
      this.buttonarea.show();
    }
    else {
      this.buttonarea.hide();    
    }
    if (this.parameters.showSubmitButton) {
      this.submitbutton.show();
    }
    else {
      this.submitbutton.hide();    
    }
    if (this.parameters.showResetButton) {
      this.resetbutton.show();
    }
    else {
      this.resetbutton.hide();    
    }
    if (this.parameters.showCloseButton) {
      this.closebutton.show();
    }
    else {
      this.closebutton.hide();    
    }
    this.setTitle(this.parameters.title);
    this.setHeader(this.parameters.header);
    this.setMessage(this.parameters.message);
    this.setFooter(this.parameters.footer);
    this.resetbutton.value = this.parameters.resetButtonLabel;    
    this.submitbutton.value = this.parameters.submitButtonLabel;
    this.closebutton.value = this.parameters.closeButtonLabel;
    this.height = this.dialog.getHeight();
    this.width = this.dialog.getWidth();
	  if (this.parameters.centered) {
      this.center();	
	  }
	  else {
      this.centered = false;
      if (!this.parameters.top || isNaN(this.parameters.top) || this.parameters.top < 0) {
	      this.parameters.top = this.centerY();
	    }
      if (!this.parameters.left || isNaN(this.parameters.left) || this.parameters.left < 0) {
	      this.parameters.left = this.centerX();
	    }
      this.setPosition(this.parameters.top, this.parameters.left);	  
	  }
	  if (this.parameters.effects && this.useScriptaculous) {
      this.parameters.showEffect = Effect.Appear;
      this.parameters.hideEffect = Effect.Fade;
      this.showEffectOptions = this.parameters.effectOptions;
      this.hideEffectOptions = this.parameters.effectOptions;	  
    } else {
      this.parameters.showEffect = Element.show;
      this.parameters.hideEffect = Element.hide;
      this.showEffectOptions = {};	  
      this.hideEffectOptions = {};      
      this.parameters.hideEffect = function() { Element.hide(this.dialog); if (this.parameters.fullDestroy) { this.destroy(); } }.bind(this)
    }
  	if (this.parameters.delay > 0) {
  	  this.delay(this.parameters.delay);
  	}	
  },
  build: function() {
    /// Creates the dialog but does not show it.
    //this.dialog = new Element('div', { 'class' : this.parameters.cssClass, 'style' : 'display:none', 'id': this.id });
  	var id = this.id;
	  // Dialog
    this.dialog = new Element('div', { 'class' : this.parameters.cssClass, 'id': this.id });	
	  // Titlebar	
    this.titlebar = new Element('div', { 'class' : this.parameters.cssClass + '_titlebar', 'id': this.id + '_titlebar' });
    this.titlebarclose = null;
	  // Close
    if (this.parameters.closable) {
      this.titlebarclose = new Element('div', { 'class' : this.parameters.cssClass + '_close', 'id': this.id + '_close', 'title': 'Close'});	  
      this.titlebarclose.observe('click', function(event){ DialogManager.close(id); Event.stop(event); return false; });
      this.titlebar.appendChild(this.titlebarclose);
    }
	  // Collapse/Expand
    this.titlebarcollapse = null;		
    this.titlebarexpand = null;
    if (this.parameters.collapsable) {
      this.titlebarcollapse = new Element('div', { 'class' : this.parameters.cssClass + '_collapse', 'id': this.id + '_collapse', 'title': 'Collapse'});
      this.titlebarcollapse.observe('click', function(e){ DialogManager.collapse(id); Event.stop(e); return false; });
      this.titlebar.appendChild(this.titlebarcollapse);
      this.titlebarexpand = new Element('div', { 'class' : this.parameters.cssClass + '_expand', 'id': this.id + '_expand', 'title': 'Expand'});
      this.titlebarexpand.observe('click', function(e){ DialogManager.expand(id); return false; });
      this.titlebarexpand.hide();
      this.titlebar.appendChild(this.titlebarexpand);
    }
    this.title = new Element('h3', { 'class' : this.parameters.cssClass + '_title', 'id': this.id + '_title' });
    this.titlebar.appendChild(this.title);
    this.dialog.appendChild(this.titlebar);
    // Content area
    this.contentarea = new Element('div', { 'class' : this.parameters.cssClass + '_contentarea', 'id': this.id + '_contentarea' });
    // Header	    
    this.header = new Element('div', { 'class' : this.parameters.cssClass + '_header', 'id': this.id + '_header' });
    this.contentarea.appendChild(this.header);
    this.header.hide();
    // Message
    this.message = new Element('div', { 'class' : this.parameters.cssClass + '_message', 'id': this.id + '_message' });
    this.contentarea.appendChild(this.message);
    this.header.hide();
    // Error Messages
    this.errormessage = new Element('div', { 'class' : this.parameters.cssClass + '_errormessage', 'id': this.id + '_messages' });
    this.contentarea.appendChild(this.errormessage);
    this.errormessage.hide();
    // Form    
    this.form = new Element('form', { 'id': this.id + '_form' });
    this.form.setStyle({ 'padding' : '0px', 'margin' : '0px' });
    this.contentarea.appendChild(this.form);    
    // Content
    this.content = new Element('div', { 'class' : this.parameters.cssClass + '_content', 'id': this.id + '_content' });
    this.form.appendChild(this.content);
    //this.contentarea.appendChild(this.content);    
    // Button area    
    this.buttonarea = new Element('div', { 'class' : this.parameters.cssClass + '_buttonarea', 'id': this.id + '_buttonarea' });
    this.contentarea.appendChild(this.buttonarea);
    this.submitbutton = new Element('input', { 'type' : 'button', 'class' : this.parameters.cssClass + '_button', 'value' : 'Save', 'id' : this.id + '_submitButton' });
    this.resetbutton = new Element('input', { 'type' : 'button', 'class' : this.parameters.cssClass + '_button', 'value' : 'Reset', 'id' : this.id + '_resetButton' });
    this.closebutton = new Element('input', { 'type' : 'button', 'class' : this.parameters.cssClass + '_button', 'value' : 'Close', 'id' : this.id + '_closeButton' });
	  this.buttonarea.appendChild(this.submitbutton);
	  this.buttonarea.appendChild(this.resetbutton);
    this.resetbutton.hide();    	  
	  this.buttonarea.appendChild(this.closebutton);	  
    // Processing
    this.processingarea = new Element('div', { 'class' : this.parameters.cssClass + '_processingarea', 'id': this.id + '_processingarea' });
    this.contentarea.appendChild(this.processingarea);
    this.processingarea.hide();
    // Footer
    this.footer = new Element('div', { 'class' : this.parameters.cssClass + '_footer', 'id': this.id + '_footer' });
    this.contentarea.appendChild(this.footer);
    this.footer.hide();    
    this.dialog.appendChild(this.contentarea);
    // Resizing grips: Diagonal, horizontal, and vertical	
	  this.diagonalgrip = null;
    this.horizontalgrip	= null;
    this.verticalgrip = null;	
    if (this.parameters.resizable ) {
      this.diagonalgrip = new Element('div', { 'class' : this.parameters.cssClass + '_diagonalgrip', 'id': this.id + '_diagonalgrip' });
	    this.dialog.appendChild(this.diagonalgrip);	    
      this.verticalgrip = new Element('div', { 'class' : this.parameters.cssClass + '_verticalgrip', 'id': this.id + '_verticalgrip' });	
	    this.dialog.appendChild(this.verticalgrip);
	    this.verticalgrip.appendChild(new Element('span'));
      this.horizontalgrip = new Element('div', { 'class' : this.parameters.cssClass + '_horizontalgrip', 'id': this.id + '_horizontalgrip' });	
	    this.dialog.appendChild(this.horizontalgrip);
	    this.horizontalgrip.appendChild(new Element('span'));
    }
	  this.dialog.hide();  // Why display:none doesn't work?????
    this.parameters.parent.insertBefore(this.dialog, this.parameters.parent.firstChild);
    // Default methods for submit and close buttons
    this.addMethod(this.submitbutton, this.defaultSubmitMethod.bind(this));
    this.addMethod(this.resetbutton, this.defaultResetMethod.bind(this));    
	  this.addMethod(this.closebutton, this.defaultCloseMethod.bind(this));
  },
  center: function() {
    this.parameters.top = this.centerY();
    this.parameters.left = this.centerX();	
    this.setPosition(this.parameters.top, this.parameters.left);
    this.focus();
    this.centered = true;
  },
  centerX: function() {  
    var pageSize = DialogManager.getPageSize(this.parameters.parent); 
    var scroll = DialogManager.getScroll(this.parameters.parent);
	  var x = ((pageSize.windowWidth - this.width) / 2) + scroll.left;
    if (isNaN(x)) {
	    x = 100;
	  }
    if (x <= 0) {
	    x = 100;
	  }
	  return x;
  },
  centerY: function() {  
    var pageSize = DialogManager.getPageSize(this.parameters.parent); 
    var scroll = DialogManager.getScroll(this.parameters.parent);
	  var y = ((pageSize.windowHeight - this.height) / 2) + scroll.top;
    if (isNaN(y)) {
	    y = 100;
	  }
    if (y <= 0) {
	    y = 100;
	  }
	  return y;
  },
  changeClass: function(element, oldClassName, newClassName) { 
    if (element) {
      element.removeClassName(oldClassName);
      element.addClassName(newClassName);
    }
  },
  click: function(e) {
    /// Execute the method associated with the element on the click event.
    e.stopPropagation();
    e.preventDefault();
    this.setMessage();
    this.setErrorMessage();
    var target = e.target;
	  if (!Object.isUndefined(target.method)) {
      if (Object.isFunction(target.method)) {
        if (target.type == 'button' && !target.id.endsWith('_resetButton')) {
          this.onStartSubmitting(target);
        }        
        target.method(e);        
	    }
	    else {
	      alert('onClick: Not a function.');
	    }
    }
	  else {
	    alert('onClick: Not defined.');
	  }
  },
  close: function() {
/// DMA review this closing thing??????????????  
    if (this.visible) {
      if ((!this.submitting) || ((this.submitting) && (this.submitting.id == this.closebutton.id))) {
        if (this.parameters.closeCallback && !this.parameters.closeCallback(this)) {
	        return;
	      }
        if (this.parameters.fullDestroy) {
          var tempDestroy = this.destroy.bind(this);
          if (this.hideEffectOptions.afterFinish) {
            var func = this.hideEffectOptions.afterFinish;
            this.hideEffectOptions.afterFinish = function() { func(); tempDestroy() };
          }
          else {
            this.hideEffectOptions.afterFinish = function() { tempDestroy() };
          }
        }
        this.closing = true;
        this.hide();
        this.closing = false;
        DialogManager.updateActive();      
        this.raiseEvent("onClose");
      }
    }
  },  
  collapse: function() {
    /// Collapse the popup, leaving only the titlebar showing
    /// DO NOT use setHeight method as the it will also change the current height (this.height)
    if (this.parameters.collapsable) {
      if (!this.collapsed) {
        this.collapsed = true;
        this.titlebarcollapse.hide();
        this.titlebarexpand.show();
        this.hideGrips();
        if (this.parameters.effects && this.useScriptaculous) {
          new Effect.Morph(this.dialog, { style: 'height:' + this.titlebar.getDimensions().height + 'px;', duration: 0.2 });
        } 
	      else {
		      this.dialog.style.height = this.titlebar.getDimensions().height + 'px';
        }
        this.raiseEvent("onCollapse");
      }
	  }    
  },
  defaultCloseMethod: function() {
    /// Default close method. This method will just close the popup.
    //var THIS = this;
	  //return function(e) { DialogManager.close(THIS.id); Event.stop(e); return false; };
	  //return function(e) { THIS.close(e); Event.stop(e); return false; };	  
    //return function() { THIS.close(); };
    DialogManager.close(this.id);
    return false;
  },
  defaultResetMethod: function(e) {
    /// Default reset method. Clear form inputs.
    //var THIS = this;
    //return function(e) { THIS.reset(e); Event.stop(e); return false; };
    this.reset(e);
    return false;
  },
  defaultSubmitMethod: function() {
    /// Default submit method. This method will call an Ajax request with the url passed during the load and the serialized form.
    //var THIS = this;
    //return function(e) { THIS.submit(e); Event.stop(e); return false; };
    this.submit();
    return false;
  },
  delay: function(seconds, fn) {
    /// Close the popup after a specified number of seconds.
    /// fn: Optional function that is executed before the popup closes.
    if (seconds) {  
  	  if (/^\d+$/.test(seconds)) {
        try {
	      var milliseconds = seconds * 1000;
	      var THIS = this;
          window.setTimeout(function() { if (fn && !Object.isUndefined(fn) && Object.isFunction(fn)) { fn(); } THIS.close(); }, milliseconds); 	  
        }
        catch(e) {}
      }
    }
  }, 
  destroy: function() {
    this.raiseEvent("onDestroy");
    Event.stopObserving(this.content, "mousedown", this.eventMouseDownContent);    
    if (this.float) {
      Event.stopObserving(window, "resize", this.eventwindowScrollOrResize);
      Event.stopObserving(window, "scroll", this.eventwindowScrollOrResize);    
      Event.stopObserving(this.parameters.parent, "scroll", this.eventwindowScrollOrResize);
    }
  	if (this.draggable) {
      Event.stopObserving(this.titlebar, "mousedown", this.eventMouseDown);
    }
    if (this.resizable) {
	    Event.stopObserving(this.diagonalgrip, "mousedown", this.eventMouseDown);
	    Event.stopObserving(this.horizontalgrip, "mousedown", this.eventMouseDown);
	    Event.stopObserving(this.verticalgrip, "mousedown", this.eventMouseDown);
  	}
    if (this.oldParent && this.oldParent != document.body) {
      this.oldParent.innerHTML = this.content.innerHTML;
      this.oldParent = null;
    }
    if(this.iFrame) { 
	    if (this.iFrame.parentNode) {
	      Element.remove(this.iFrame);
      }
	    else {
	      delete this.iFrame; 
	    }
  	}
    if (this.dialog.parentNode) {
	    Element.remove(this.dialog);
    }
	  else {
	    delete this.dialog;
  	}
    if (this.modal) {
      DialogManager.unregisterModal(this);
      DialogManager.resetOverflow();
    } 
	  else {
      DialogManager.unregister(this);
    }
  },  
  draggingOverButtons: function() {
    /// Don't know what is this use for???
    if (this.titlebarclose && Position.within(this.titlebarclose, this.pointer[0], this.pointer[1])) {
	    return true;
	  }
    if (this.titlebarcollapse && Position.within(this.titlebarcollapse, this.pointer[0], this.pointer[1])) {
	    return true;
	  }
    if (this.titlebarexpand && Position.within(this.titlebarexpand, this.pointer[0], this.pointer[1])) {
	    return true;
	  }
    return false;
  },
  expand: function() {
    /// Expand the popup to the lastest known height was before it was collapsed.
    if (this.parameters.collapsable) {
      if (this.collapsed) {
        this.collapsed = false;
        this.titlebarcollapse.show();
        this.titlebarexpand.hide();
        this.showGrips();
        if (this.parameters.effects && this.useScriptaculous) {
          new Effect.Morph(this.dialog, { style: 'height:' + this.height + 'px;', duration: 0.2 });
        } 
  	    else {
		      this.dialog.style.height = this.height + 'px';
        }
        this.raiseEvent('onExpand');
        this.focus();
      }    
	  }    
  },
  fixOverlap: function() {
    if (!this.iFrame && this.isIE) {
  	  this.iFrame = new Element('iframe', { 'id': this.id
  	   + '_iframe', 'src': 'javascript:false', 'frameborder': 0, 'scrolling': 'no'});
  	  this.parameters.parent.appendChild(this.iFrame);
    }
    if (this.iFrame) {
	    setTimeout(this.fixOverlapping.bind(this), 50);
	  }
  },
  fixOverlapping: function() {
    if (this.dialog && this.dialog.style && this.iFrame && this.iFrame.style) {
      var dm = this.dialog.getDimensions();
  	  this.iFrame.setStyle({
        'top' : this.dialog.getStyle('top'),
      	'left' : this.dialog.getStyle('left'),
      	'width' : dm.width,
      	'height' : dm.height,
        'filter' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)',
        'display' : 'none',
        'position' : 'absolute'
      });
      this.iFrame.setOpacity(0);
      this.iFrame.show();
    }
  }, 
  focus: function() {
    if (this.dialog.style.zIndex < DialogManager.topIndex) {
	    this.setZIndex(DialogManager.topIndex + 1);
	  }
    if (this.iFrame) {
	    this.fixOverlapping();
	  }
  },
  getButtonArea : function () { 
    return this.buttonarea; 
  },
  getCloseButton: function () { 
    return this.closebutton; 
  },
  getContent: function () { 
    return this.content; 
  },
  getDialog: function() {
    return this.dialog;
  },
  getFooter: function() {
    return this.footer;
  },
  getHeader: function() {
    return this.header;
  },
  getHeight: function() {
    return this.dialog.getHeight();
  },
  getMessage: function() {
    return this.message;
  },
  getSize: function() { 
    return {width: this.width, height: this.height}; 
  },
  getSubmitButton: function () { 
    return this.submitbutton; 
  },
  getTitle: function() {
    return this.title;
  },
  getTitlebar: function() {
    return this.titlebar;
  },
  getWidth: function() {
    return this.dialog.getWidth();
  },
  hide: function() {
    this.visible = false;
    // If untagged => PB with overlay with multiple popups
    //if (this.modal) {
    //  DialogManager.unregisterModal(this);
    //  DialogManager.resetOverflow();
    //}
    this.oldStyle = this.getContent().getStyle('overflow') || 'auto';
    this.getContent().setStyle({'overflow' : 'hidden'});
    this.parameters.hideEffect(this.dialog, this.hideEffectOptions);  
    if(this.iFrame) {
	    this.iFrame.hide();
	  }
    if (!this.closing) {
	    this.raiseEvent('onHide');
	  }
  },  
  hideGrips: function() {
	  if (this.diagonalgrip) { this.diagonalgrip.hide(); }
    if (this.horizontalgrip) { this.horizontalgrip.hide(); }
    if (this.verticalgrip) { this.verticalgrip.hide(); }
  },
  load: function(url, requestOptions, parameters) {
    this.url = url ? url : '';
    this.requestOptions = requestOptions ? requestOptions : {};
	  this.setParameters(parameters);
    this.loadRequest(this.url, this.requestOptions);
  },
  loadJSONResponse: function(response) {
  	if (response.isSuccess()) {
      this.setContent(response.responseText);
    }
    else {
      this.parameters.showButtons = false;
      this.showErrors(response);
    }
    this.show();
  },
  loadRequest: function(url, parameters) {
    var THIS = this; 
    new Ajax.Request(url ? url : '', {
    parameters: parameters ? parameters : {},
	  onSuccess: function(response) { THIS.loadRequestSuccess(response); },
	  onFailure: function(response) { THIS.loadRequestFailure(response); }
    });
  },
  loadRequestFailure: function(response) {
    var contentType = response.getResponseHeader('Content-Type') ? response.getResponseHeader('Content-Type').toLowerCase() : '';
    this.parameters.showButtons = false;
    if (contentType.include('application/json')) {
      var o = new Nmma.JSONResponse(response);
      this.setContent(o.getErrorsList());      
    }
    else if (contentType.include('nmma/json')) {
      this.setContent(response.getErrorsList());      
	  }
    else { // 'text/html'
      this.setContent(response.responseText);	  
    }
    this.show();
    alert('Error.');				
  },  
  loadRequestSuccess: function(response) {
    var contentType = response.getResponseHeader('Content-Type') ? response.getResponseHeader('Content-Type').toLowerCase() : '';
    if (contentType.include('text/javascript')) {
      return;
    }
    else if (contentType.include('application/json')) {
      this.loadJSONResponse(new Nmma.JSONResponse(response));	  
    }
    else if (contentType.include('nmma/json')) {
      this.loadJSONResponse(response);
    }
    else { // 'text/html'
      this.setContent(response.responseText);	  
      this.show();
    }
  },
  mouseDown: function(event) {
    this.pointer = [Event.pointerX(event), Event.pointerY(event)];
    this.draggedDialog = this.dialog;
    this.dragging = false;
    this.resizing = false;
    if (this.diagonalgrip && Event.element(event) == this.diagonalgrip) {
      this.resizing = {H: this.height, W: this.width, X: event.pageX, Y: event.pageY, direction: 'both'};			
      document.body.style.cursor = 'se-resize';
    }
    else if (this.horizontalgrip && Event.element(event) == this.horizontalgrip) {
	    this.resizing = {H: this.height, W: this.width, X: event.pageX, Y: event.pageY, direction: 'horizontal'};
      document.body.style.cursor = 'col-resize';	    
    }
    else if (this.verticalgrip && Event.element(event) == this.verticalgrip) {
      this.resizing = {H: this.height, W: this.width, X: event.pageX, Y: event.pageY, direction: 'vertical'};
      document.body.style.cursor = 'row-resize';
	  }
	  else {
      if (this.draggingOverButtons()) { 
	      this.draggedDialog = null; 
		    return; 
	    }
      this.focus();
      if (!this.parameters.draggable) {
	      return;
	    }
      this.dragging = true;
      this.raiseEvent("onStartDragging");
      document.body.style.cursor = 'move';          
    }
    Event.observe(document, "mouseup", this.eventMouseUp, false);
    Event.observe(document, "mousemove", this.eventMouseMove, false);    
    DialogManager.lockScreen(this.id, 'lockoverlay', 0);
    document.body.ondrag = function () { return false; };
    document.body.onselectstart = function () { return false; };
    this.draggedDialog.show();
    Event.stop(event);
  },
  mouseMove: function(event) {
    if (this.resizing) {
      var v = this.resizing;
      if (v.direction == 'horizontal' || v.direction == 'both')
      {
		    var width = v.W + event.pageX - v.X;
		    if ((width > this.parameters.minWidth || this.width < this.parameters.minWidth) && (width < this.parameters.maxWidth || this.width > this.parameters.maxWidth))
		    {
		      this.dialog.style.width = width + 'px';
		      this.width = width;
		    }			
	    }
	    if (v.direction == 'vertical' || v.direction == 'both')
	    {
		    var height = v.H + event.pageY - v.Y;
		    if ((height > this.parameters.minHeight || this.height < this.parameters.minHeight) && (height < this.parameters.maxHeight || this.height > this.parameters.maxHeight))
		    {
		      this.dialog.style.height = height + 'px';
		      this.height = height;
		      this.horizontalgrip.setStyle({ 'height' : this.dialog.getHeight() + 'px' });
		    }
	    }
      this.raiseEvent("onResize");
    } 
    else if (this.dragging) {
      var pointer =  [Event.pointerX(event), Event.pointerY(event)];
      var dx = pointer[0] - this.pointer[0];
      var dy = pointer[1] - this.pointer[1];
      this.pointer = pointer;
      var left =  parseFloat(this.draggedDialog.getStyle('left')) + dx;
      var newLeft = left;
      this.pointer[0] += newLeft-left;
      this.draggedDialog.setStyle({ 'left' : newLeft + 'px' });
      var top =  parseFloat(this.draggedDialog.getStyle('top')) + dy;
      var newTop = top;
      this.pointer[1] += newTop - top;
      this.draggedDialog.setStyle({ 'top' : newTop + 'px' });
      this.raiseEvent("onMove");
    }
    if (this.iFrame) {
	    this.fixOverlapping();
	  }
    Event.stop(event);
  },
  mouseUp: function(event) {
    document.body.style.cursor = 'default';  
    DialogManager.unlockScreen('lockoverlay', 0);
    if (this.resizing) {
      if (this.centered) {
	      this.center();
	    }
      this.raiseEvent("onEndResize");
    } else {
      this.centered = false;
      this.raiseEvent("onEndMove");
    }
    Event.stopObserving(document, "mouseup", this.eventMouseUp, false);
    Event.stopObserving(document, "mousemove", this.eventMouseMove, false);
    Event.stop(event);
    document.body.ondrag = null;
    document.body.onselectstart = null;
    this.dragging = false;
    this.resizing = false;
  }, 
  onStartSubmitting: function(button) {
    if (button) {
      this.submitting = button;
      button.disabled = true;    
      if (this.isIE) {
        this.processingarea.show();      
      }
      else {
        button.addClassName('submitting');
      }
    }
  }, 
  onEndSubmitting: function() {
    if (this.submitting != null) {
      this.submitting.disabled = false;        
      if (this.isIE) {
        this.processingarea.hide();
      }
      else {
        this.submitting.removeClassName('submitting');      
      }
      this.submitting = null;      
    }
  },
  pushContent: function(id) {
    /// DMA doesn't work anymore ?????  Review this later
    var element = $(id);
    if (null == element) {
	    throw "Unable to find element '" + id + "' in DOM";
	  }
    element.show();
    this.oldParent = element.parentNode;
    this.setContent("");
    this.content.appendChild(element);
  },
  raiseEvent: function(eventName) {
    if (this.parameters[eventName]) {
	    this.parameters[eventName](this);
    }
	  else {
      DialogManager.notify(eventName, this);
	  }
  },
  registerCloseCallback: function(callback) { 
    this.parameters.closeCallback = callback; 
  },
  registerSubmitCallback: function(callback) {
    this.parameters.submitCallback = callback; 
  },
  reset: function(e) {
    if (this.visible) {
      if (this.submitting != null) {
        this.onStartSubmitting(e.target);
        this.form.reset();
        this.onEndSubmitting();        
      }
    }  
  },
  resetDimensions: function() {
    this.resetHeight;
    this.resetWidth();
  },
  resetHeight: function() {
    //if (this.dialog.getHeight() < this.parameters.minHeight + 4 ) {
      this.height = this.dialog.getHeight();
    //}
  },
  resetParameters: function() {
    /// Reset the dialog parameters default values
    this.parameters.centered = true;    
    this.parameters.closable = true;
    this.parameters.closeButtonLabel = 'Close';
    this.parameters.closeCallback = null;
    this.parameters.collapsable = false;
    this.parameters.cssClass = 'dialog';
    this.parameters.delay = 0;
    this.parameters.displayErrors = 'popup';
    this.parameters.draggable = false;
    this.parameters.effectOptions = { duration: 0.2 };
    this.parameters.effects = false;
    this.parameters.float = false;
    this.parameters.footer = '';        
    this.parameters.fullDestroy = true; //??    
    this.parameters.header = '';    
    this.parameters.height = 300;  
    this.parameters.left = -1;
    this.parameters.maxWidth = 800;
    this.parameters.maxHeight = 1000;
    this.parameters.message = '';
    this.parameters.minHeight = 30;
    this.parameters.minWidth = 300;
    this.parameters.modal = true;	
    this.parameters.parent = document.body;
    this.parameters.resetButtonLabel = 'Reset';    
    this.parameters.resizable = false;    
    this.parameters.roundedCorners = false;
    this.parameters.showButtons = true;
    this.parameters.showCloseButton = true;    
    this.parameters.showResetButton = false;    
    this.parameters.showSubmitButton = true;
    this.parameters.submitButtonLabel = 'Submit';
    this.parameters.submitCallback = null;
    this.parameters.title = '';
    this.parameters.top = 40;
    this.parameters.width = 400;
    this.parameters.zIndex = 0;
  },
  resetWidth: function() {
    this.width = this.dialog.getWidth();
  },
  setClass: function(cssClass) {
    /// DMA TO REVIEW DOES NOT SEEM TO WORK
    if (cssClass != this.parameters.cssClass) {
      var currentCssClass = this.parameters.cssClass;
      $A(["", "_titlebar", "_close", "_collapse", "_expand", "_contentarea", "_messages", "_content", "_buttonarea", "_footer", "_diagonalgrip", "_horizontalgrip", "_verticalgrip"]).each( function(value) {
        if ($(this.id + value)) this.changeClass($(this.id + value), currentCssClass + value, cssClass + value)
      }.bind(this));
      this.parameters.cssClass = cssClass;
	  }
  },
  setContent: function(content) {
    /// Update the content are of the popup
    this.content.update(content);
    this.resetHeight();
  },
  setErrorMessage: function(text) {
    if (text && text.strip().length > 0) {
      this.errormessage.update(text);
      this.errormessage.show();
    }
    else {
      this.errormessage.update('');    
      this.message.hide();    
    }
  },  
  setFooter: function(text) {
    if (text && text.strip().length > 0) {
      this.footer.update(text);
      this.footer.show();
    }
    else {
      this.footer.update('');    
      this.footer.hide();    
    }
  },
  setHeader: function(text) {
    if (text && text.strip().length > 0) {
      this.header.update(text);
      this.header.show();
    }
    else {
      this.header.update('');    
      this.header.hide();    
    }
  },
  setHeight: function(height) {
    height = parseFloat(height);
    if (!this.collapsed && height < this.parameters.minHeight) {
	    height = this.parameters.minHeight;
	  }
    if (this.parameters.maxHeight && height > this.parameters.maxHeight) {
	    height = this.parameters.maxHeight;
	  }
    var e = this.draggedDialog ? this.draggedDialog : this.dialog;
    e.setStyle({ 'height' : height + 'px' });
    this.height = height;
  },
  setMessage: function(text) {
    if (text && text.strip().length > 0) {
      this.message.update(text);
      this.message.show();
    }
    else {
      this.message.update('');    
      this.message.hide();    
    }
  },  
  setOpacity: function(opacity) {
    if (Element.setOpacity) {
	    Element.setOpacity(this.dialog, opacity);
	  }
  },
  setParameters: function(parameters) {
    /// Set the dialog parameters with a user defined parameters
    if (parameters && !Object.isUndefined(parameters)) {
      if (!Object.isUndefined(parameters.centered)) { this.parameters.centered = parameters.centered; }    
      if (!Object.isUndefined(parameters.closable)) { this.parameters.closable = parameters.closable; }	  
      if (!Object.isUndefined(parameters.closeButtonLabel)) { this.parameters.closeButtonLabel = parameters.closeButtonLabel; }	  
      if (!Object.isUndefined(parameters.collapsable)) { this.parameters.collapsable = parameters.collapsable; }
      if (!Object.isUndefined(parameters.cssClass)) { this.parameters.cssClass = parameters.cssClass; }	  
      if (!Object.isUndefined(parameters.delay)) { this.parameters.delay = parameters.delay; }
      if (!Object.isUndefined(parameters.displayErrors)) { this.parameters.displayErrors = parameters.displayErrors; }
      if (!Object.isUndefined(parameters.draggable)) { this.parameters.draggable = parameters.draggable; }
      if (!Object.isUndefined(parameters.effects)) { this.parameters.effects = parameters.effects; }
      if (!Object.isUndefined(parameters.float)) { this.parameters.float = parameters.float; }
      if (!Object.isUndefined(parameters.footer)) { this.parameters.footer = parameters.footer; }      
      if (!Object.isUndefined(parameters.header)) { this.parameters.header = parameters.header; }
      if (!Object.isUndefined(parameters.height)) { this.parameters.height = parameters.height; }
      if (!Object.isUndefined(parameters.left)) { this.parameters.left = parameters.left; }
      if (!Object.isUndefined(parameters.maxHeight)) { this.parameters.maxHeight = parameters.maxHeight; }
      if (!Object.isUndefined(parameters.maxWidth)) { this.parameters.maxWidth = parameters.maxWidth; }
      if (!Object.isUndefined(parameters.message)) { this.parameters.message = parameters.message; }      
      if (!Object.isUndefined(parameters.minHeight)) { this.parameters.minHeight = parameters.minHeight; }
      if (!Object.isUndefined(parameters.minWidth)) { this.parameters.minWidth = parameters.minWidth; }
      if (!Object.isUndefined(parameters.modal)) { this.parameters.modal = parameters.modal; }      
      if (!Object.isUndefined(parameters.parent)) { this.parameters.parent = parameters.parent; }
      if (!Object.isUndefined(parameters.resetButtonLabel)) { this.parameters.resetButtonLabel = parameters.resetButtonLabel; }      
      if (!Object.isUndefined(parameters.resizable )) { this.parameters.resizable  = parameters.resizable ; }
      if (!Object.isUndefined(parameters.roundedCorners)) { this.parameters.roundedCorners = parameters.roundedCorners; }
      if (!Object.isUndefined(parameters.showButtons)) { this.parameters.showButtons = parameters.showButtons; }
      if (!Object.isUndefined(parameters.showCloseButton)) { this.parameters.showCloseButton = parameters.showCloseButton; }
      if (!Object.isUndefined(parameters.showResetButton)) { this.parameters.showResetButton = parameters.showResetButton; }	  
      if (!Object.isUndefined(parameters.showSubmitButton)) { this.parameters.showSubmitButton = parameters.showSubmitButton; }	        
      if (!Object.isUndefined(parameters.submitButtonLabel)) { this.parameters.submitButtonLabel = parameters.submitButtonLabel; }
      if (!Object.isUndefined(parameters.title)) { this.parameters.title = parameters.title; }	  	  
      if (!Object.isUndefined(parameters.top)) { this.parameters.top = parameters.top; }	
      if (!Object.isUndefined(parameters.width)) { this.parameters.width = parameters.width; }
      if (!Object.isUndefined(parameters.zIndex )) { this.parameters.zIndex  = parameters.zIndex ; }
	  }
  },  
  setPosition: function(top, left) {
    var e = this.draggedDialog || this.dialog;
    e.setStyle({ 'top' : parseFloat(top) + 'px' });
    e.setStyle({ 'left' : parseFloat(left) + 'px' });
  },
  setSize: function(width, height) {
    this.setWidth(width);
    this.setHeight(height);
  },
  setTitle: function(text) {
    if (text && text.strip().length > 0) {
      this.title.update(text);
      this.titlebar.removeClassName('notitle');
    }
    else {
      this.title.update('');
      this.titlebar.addClassName('notitle');      
    }
  },
  setWidth: function(width) {
    width = parseFloat(width);
    if (!this.collapsed && width < this.parameters.minWidth) {
	    width = this.parameters.minWidth;
	  }
    if (this.parameters.maxWidth && width > this.parameters.maxWidth) {
	    width = this.parameters.maxWidth;
	  }
    var e = this.draggedDialog ? this.draggedDialog : this.dialog;
    e.setStyle({ 'width' : width + 'px' });
    this.width = width;    
  },
  setX: function(left) {
    var e = this.draggedDialog || this.dialog;
    e.setStyle({ 'left' : parseFloat(left) + 'px' });
  },
  setY: function(top) {
    var e = this.draggedDialog || this.dialog;
    e.setStyle({ 'top' : parseFloat(top) + 'px' });
  },
  setZIndex: function(zindex) {
    this.dialog.setStyle({ 'zIndex' : zindex });
    DialogManager.updateZindex(zindex, this);
  },
  show: function(parameters) {
    if (!this.visible) {
      this.submitting = null;  
      this.setParameters(parameters);
      this.applyParameters();
      this.height = this.dialog.getHeight();
      this.width = this.dialog.getWidth();
      Event.observe(this.content, "mousedown", this.eventMouseDownContent);
      if (this.parameters.draggable)  {
        var THIS = this;
        this.titlebar.observe("mousedown", THIS.eventMouseDown);
        this.titlebar.addClassName("titlebar_dragging");
        this.draggable = true;
      }
	    if (this.parameters.float) {
        Event.observe(window, "resize", this.eventwindowScrollOrResize);
        Event.observe(window, "scroll", this.eventwindowScrollOrResize);
        Event.observe(this.parameters.parent, "scroll", this.eventwindowScrollOrResize);
        this.float = true;
      }
      if (this.parameters.resizable ) {
        if (this.diagonalgrip) { Event.observe(this.diagonalgrip, "mousedown", this.eventMouseDown); }
  	    if (this.verticalgrip) { Event.observe(this.verticalgrip, "mousedown", this.eventMouseDown); }
  	    if (this.horizontalgrip) { Event.observe(this.horizontalgrip, "mousedown", this.eventMouseDown); }
  	    this.resizable = true;
  	  }
	    if (this.parameters.modal) {
        DialogManager.registerModal(this);	
	    }
      if (this.dialog.style && !this.dialog.style.zIndex) {
	      this.setZIndex(DialogManager.topIndex + 1);
	    }
      if (this.oldStyle) {
	      this.getContent().setStyle({ 'overflow' : this.oldStyle });
	    }
      this.raiseEvent("onBeforeShow");   
      if (this.parameters.showEffect != Element.show && this.showEffectOptions) {
        this.parameters.showEffect(this.dialog, this.showEffectOptions);  
	    }
      else { 
	      this.parameters.showEffect(this.dialog);
	    }
  	  
      this.fixOverlap();
      DialogManager.activeDialog = this;
      if (this.horizontalgrip) {
	      this.horizontalgrip.setStyle({ 'height' : this.dialog.getHeight() + 'px' });
	    }
      this.visible = true;
      this.raiseEvent("onShow");
    }
  },  
  showErrors: function(response) {
    if (this.parameters.displayErrors == 'summary') {
      this.setErrorMessage(response.getErrorsList());
    }
    else {
      alert(response.getErrorsText());
    }  
  },  
  showGrips: function() {
	  if (this.diagonalgrip) { this.diagonalgrip.show(); }
    if (this.horizontalgrip) { this.horizontalgrip.show(); }
    if (this.verticalgrip) { this.verticalgrip.show(); }
  },
  submit: function(e) {
    if (this.submitting != null) {
      this.raiseEvent("onSubmit");
      var THIS = this;
      //this.onStartSubmitting(e.target);      
      if (THIS.parameters.submitCallback && !THIS.parameters.submitCallback(THIS)) {
        this.onEndSubmitting();    
        return;      
      }
      new Ajax.Request(this.url ? this.url : '', {
        parameters: Form.serialize(this.content.id, true),
	      onSuccess: function(response) { THIS.submitRequestSuccess(response); },
	      onFailure: function(response) { THIS.submitRequestFailure(response); }
      });
    }    
  },
  submitJSONResponse: function(response) {
    if (response.isSuccess()) {
      this.onEndSubmitting();
      this.close();
    }
    else {
      this.showErrors(response);
      this.onEndSubmitting();
    }
  },   
  submitRequestFailure: function(response) {
    alert('Error on submit');
    this.onEndSubmitting();      
  },
  submitRequestSuccess: function(response) {
    var contentType = response.getResponseHeader('Content-Type') ? response.getResponseHeader('Content-Type').toLowerCase() : '';
    if (contentType.include('application/json')) {
      this.submitJSONResponse(new Nmma.JSONResponse(response));
    }
    else if (contentType.include('nmma/json')) {
      this.submitJSONResponse(response);
    }
	  else {
      this.onEndSubmitting();  
      this.close();
    }
  },  
  windowScrollOrResize: function(event) {
    var ov = $('overlay');
    var d = document.viewport.getDimensions();
    if (ov) {
	    ov.setStyle({ 'height' : parseFloat(d.height + 'px'), 'width' : parseFloat(d.width + 'px') });
	  }
    if (this.centered) {
	    this.center();
	  }
  }
});



// DMA later rename to Nmma.DialogManager => add DialogManager to Nmma object
var DialogManager = {
  activeDialog: null,
  dialogs: [],
  modalDialogs: [],
  observers: [],
  overlayOpacity: 0.10,
  overlayHideEffectOptions: {duration: 0.3},
  overlayShowEffectOptions: {duration: 0.3},  
  topIndex: 90000,
  addObserver: function(observer) { 
    this.removeObserver(observer); 
	  this.observers.push(observer); 
  },
  afterDisableScreen: function(elem, dialogId, opacity) {
    if (dialogId && Prototype.Browser.IE) { 
	    this.disableSelectBoxes(); 
	    this.enableSelectBoxes(dialogId); 
  	}
    elem.style.display = 'none'; 
    if (this.useScriptaculous && DialogManager.overlayShowEffectOptions && opacity > 0) {
      new Effect.Appear(elem, Object.extend({from: 0, to: opacity}, DialogManager.overlayShowEffectOptions));
    } 
	  else {
      elem.style.display = "block";
      elem.setOpacity(opacity);
    }
  },
  blur: function(id) {
    var d = this.find(id);  
    if (!d) {
	    return;
	  }
    d.changeClass(d.dialog, d.parameters.cssClass, d.parameters.cssClass + ' inactive');
    if (this.activeDialog == d) {
	    this.activeDialog = null;
	  }
    d.raiseEvent("onBlur");
  },
  close: function(id) { 
    var d = this.find(id); if (d) d.close(); 
  },
  closeAll: function() { 
    this.dialogs.each( function(d) { DialogManager.close(d.id) } ); 
  },
  closeAllModalWindows: function() {
    DialogManager.unlockScreen('overlay', DialogManager.overlayOpacity);     
    this.modalDialogs.each( function(win) { if (win) { win.close(); } });    
  },
  collapse: function(id) {
    var d = this.find(id);
    if (d && d.visible) {
	    d.collapse();
	  }
  },
  disableSelectBoxes: function(id) {
    if (Prototype.Browser.IE) {
      id = (id ==  null) ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (!DialogManager.isDefined(element.oldVisibility)) {
          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
          element.style.visibility = "hidden";
        }
      });
    }
  },
  enableSelectBoxes: function(id) {
    if (Prototype.Browser.IE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (DialogManager.isDefined(element.oldVisibility)) {
          //IE Fix
          try {
            element.style.visibility = element.oldVisibility;
          } 
		      catch(e) {
            element.style.visibility = "visible";
          }
          element.oldVisibility = null;
        }
        else {
          if (element.style.visibility) element.style.visibility = "visible";
        }
      });
    }
  },
  expand: function(id) {
    var d = this.find(id)
    if (d && d.visible) {
	    d.expand();
    }
  },
  find: function(id) { 
    return this.dialogs.detect(function(d) { return d.id == id }); 
  },  
  fixOverflow: function(except) {    
    this.dialogs.without(except).each(function(d) { d.getContent().setStyle({ 'overflow' : "hidden" }) });
    // DMA: ????? This creates a scrollbar on the content ????
    //  except.getContent().setStyle( {overflow: "auto"} );
  },
  focus: function(id) {
    var d = this.find(id);  
    if (!d) {
	    return;       
	  }
    if (this.activeDialog) {
	    this.blur(this.activeDialog.id);
	  }
    d.changeClass(d.dialog, d.parameters.cssClass + ' inactive', d.parameters.cssClass);  
    this.activeDialog = d;
    d.raiseEvent("onFocus");
  },  
  getActive: function() { 
    return this.activeDialog; 
  },
  getPageSize: function(parent) {
    parent = parent || document.body;              
    var windowWidth, windowHeight;
    var pageHeight, pageWidth;
    if (parent != document.body) {
      windowWidth = parent.getWidth();
      windowHeight = parent.getHeight();                                
      pageWidth = parent.scrollWidth;
      pageHeight = parent.scrollHeight;                                
    } 
    else {
      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;
      }
      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;
      }
    }             
    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },
  getSize: function(content, id, width, height, margin, className) {
    var objBody = document.body;
    var tmpObj = document.createElement("div");
    tmpObj.setAttribute('id', id);
    tmpObj.className = className + "_content";
    if (height) {
      tmpObj.style.height = height + "px"
	  }
    else {
      tmpObj.style.width = width + "px"
    } 
    tmpObj.style.position = 'absolute';
    tmpObj.style.top = '0';
    tmpObj.style.left = '0';
    tmpObj.style.display = 'none';
    tmpObj.innerHTML = content;
    objBody.insertBefore(tmpObj, objBody.firstChild);
    var size;
    if (height) {
      size = $(tmpObj).getDimensions().width + margin;
	  }
    else {
      size = $(tmpObj).getDimensions().height + margin;
	  }
    objBody.removeChild(tmpObj);
    return size;
  },
  getScroll: function(parent) {
    var T, L, W, H;
    parent = parent || document.body;              
    if (parent != document.body) {
      T = parent.scrollTop;
      L = parent.scrollLeft;
      W = parent.scrollWidth;
      H = parent.scrollHeight;
    } 
    else {
      var w = window;
      with (w.document) {
        if (w.document.documentElement && documentElement.scrollTop) {
          T = documentElement.scrollTop;
          L = documentElement.scrollLeft;
        } 
		else if (w.document.body) {
          T = body.scrollTop;
          L = body.scrollLeft;
        }
        if (w.innerWidth) {
          W = w.innerWidth;
          H = w.innerHeight;
        } 
		else if (w.document.documentElement && documentElement.clientWidth) {
          W = documentElement.clientWidth;
          H = documentElement.clientHeight;
        } 
		else {
          W = body.offsetWidth;
          H = body.offsetHeight
        }
      }
    }
    return { top: T, left: L, width: W, height: H };
  },
  lockScreen: function(dialogId, overlayId, opacity) {
    var ov = $(overlayId);
    if (ov) {
      ov.setStyle({ 'zIndex' : DialogManager.topIndex + 1 });
      DialogManager.topIndex++;
      this.afterDisableScreen(ov, dialogId, opacity);
    } 
	  else {
      ov = new Element('div', { 'id': overlayId, 'class': overlayId} );
      ov.setStyle({ 'display': 'none', 'position': 'fixed', 'top': '0', 'left': '0', 'right':'0', 'bottom':'0', 'zIndex': DialogManager.topIndex + 1, 'width': '100%' });
      document.body.insertBefore(ov, document.body.firstChild);
      DialogManager.topIndex++;
      if (Prototype.Browser.WebKit) {
        setTimeout( function() { this.afterDisableScreen(ov, dialogId, opacity) }, 10);
      } 
	    else {
        this.afterDisableScreen(ov, dialogId, opacity);
      }
    }
  },
  isDefined: function(object) {
    return typeof(object) != "undefined" && object != null;
  },
  notify: function(eventName, d) {
    this.observers.each( function(o) { if (o[eventName]) { o[eventName](eventName, d); } });
  },
  register: function(d) { 
    this.dialogs.push(d); 
  },
  registerModal: function(d) {
    if (this.modalDialogs.length == 0) {
      DialogManager.lockScreen(d.id, 'overlay', DialogManager.overlayOpacity);
    } 
	  else {
      $('overlay').style.zIndex = DialogManager.topIndex + 1;
      DialogManager.topIndex += 1;
      this.disableSelectBoxes(this.modalDialogs.last().id);
      this.enableSelectBoxes(d.id);
    }
    d.modal = true;
    d.setZIndex(DialogManager.topIndex + 1);
    DialogManager.fixOverflow(d);
    this.modalDialogs.push(d);
  },
  removeObserver: function(observer) { 
    this.observers = this.observers.reject( function(o) { return o == observer } ); 
  },
  resetOverflow: function() {
    this.dialogs.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({ 'overflow': d.oldOverflow }) });
  },
  submit: function(id) { 
    var d = this.find(id); if (d) d.submit(); 
  },
  unlockScreen: function(overlayId, opacity) {
    var ov =  $(overlayId);
    if (ov) {
      if (this.useScriptaculous && DialogManager.overlayHideEffectOptions && opacity > 0) {
        new Effect.Fade(ov, Object.extend({from: opacity, to:0}, DialogManager.overlayHideEffectOptions));
	    }
      else {
        ov.style.display = 'none';
        ov.parentNode.removeChild(ov);
      }
      this.enableSelectBoxes();
    }
  },
  unregister: function(d) {
    this.dialogs = this.dialogs.reject( function(dd){ return dd==d } ); 
  },
  unregisterModal: function(d) {
    this.modalDialogs.pop();
    if (this.modalDialogs.length == 0) {
	    this.unlockScreen('overlay', DialogManager.overlayOpacity);
	  }
    else {
      this.modalDialogs.last().focus();
      this.enableSelectBoxes(this.modalDialogs.last().id);        
    }
  },
  updateActive: function() { 
    this.activeDialog = this.dialogs.length >=2 ? this.dialogs[this.dialogs.length-2] : null; 
  },
  updateZindex: function(zindex, dialog) {
    if (zindex > this.topIndex) {   
      this.topIndex = zindex;    
      if (this.activeDialog) {
	      this.blur(this.activeDialog.id)
	    }
    }
    this.activeDialog = dialog;
    if (this.activeDialog) {
	    this.focus(this.activeDialog.id);
	  }
  }
}; 

if (Object.isUndefined(Nmma.Login)) { Nmma.Login = { } };

Nmma.Login = {
  
  initialize: function() {
    this.popup = null;
  },

  getUrl: function() {
		return '/shared/pages/ajaxhandlers/login.aspx';
  },

  show: function(args) {
    if (this.popup != null) this.popup.close();
    this.popup = new Nmma.Dialog({ 'title' :'Sign in', submitButtonLabel:'Sign in' }); 
    var content = new Element('div', {'class':'dialog_login'});
    content.appendChild(new Element('h2').update(args.message));
    content.appendChild(new Element('span').update('Username'));
    content.appendChild(new Element('input', { 'id': 'username', 'name': 'username', 'type':'text' }));
    content.appendChild(new Element('br'));
    content.appendChild(new Element('span').update('Password'));
    content.appendChild(new Element('input', { 'id': 'password', 'name' : 'password', 'type':'password' }));
    this.popup.setContent(content);
    this.popup.registerSubmitCallback(this.signIn.bind(this));
    this.popup.show();
  },

  signIn: function(args){
    Nmma.Ajax.request(this.getUrl(), {
      parameters: { 'form' : this.popup.getContent().id, 'arguments' : { 'ActionType' : 'signin', 'User' : Nmma.User!=null?Nmma.User.username:''  } },
	    onSuccess: function (response) {
	      if (response.isSuccess()){
	        this.popup.setContent(response.responseText);
	        this.popup.getSubmitButton().hide();
	        if (response.getMessage() == 'Reload') this.popup.registerCloseCallback(Nmma.Forms.Reload);
	      }
	      else {
	        this.popup.setMessage(response.getErrorsList());
	      }
	      this.popup.onEndSubmitting(); 
	    }.bind(this),
		  onFailure: function(response) { $(target).update('Request failed'); }
    });
  }
}

if (Prototype.Browser.WebKit) {
  var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));
  Prototype.Browser.WebKitVersion = parseFloat(array[1]);
}
