
/**
 * Open a modal/confirm box for the given link.
 * 
 * Usage:
 *
 * Iframe
 * <a href='http://www.google.com' class='modal' rel='iframe'>Google</a>
 *
 * Ajax
 * <a href='ajax/ajax.jsp' class='modal'>AJAX</a>
 *
 *
 * Confirm
 * <a href='do/action.jsp' class='modal confirm' title="Are you sure ?">Confirm Link</a>
 * <input value='Confirm Button' class='modal confirm' title="Are you sure ?" />
 */

// ---------------------------------------
//  MODAL
// ---------------------------------------

'JCMS.window.Modal'.namespace({

  OVERLAY_OPACITY: 0.60,
  FADE_DURATION: 0.20,

  init: function(){
    Util.observeClass('modal', JCMS.window.Modal._show);
    JcmsLogger.info("Modal", "Init Modal");
  },
  
  /**
   * Close the current Modal window
   * @return boolean to be used in onclick="" 
   * (eg true => The modal is not closed, false => The modal has been closed)
   */
  close: function(confirmValue){ 
    var modal = JCMS.window.Modal.current;
    if (modal){
      modal._confirm = confirmValue;
      return !modal.close();
    }
    return true;
  },
  
  /**
   * Create and Display a Modal Window for the alert message
   * @param msg the alert message
   */
  alert: function(msg){
    var modal = JCMS.window.Modal._showAlert(function(){}, 'alert', msg);
    JCMS.window.Modal._openModal(modal);
  },
  
  /**
   * Create and Display a Modal Window for the confirm message
   * @param msg the alert message
   * @param func the callback function
   * @param usage optional parameter that will define class/jsp used (default is confirm)
   */
  confirm: function(msg, func, usage){
    var modal = JCMS.window.Modal._showAlert(func, usage || 'confirm', msg);
    JCMS.window.Modal._openModal(modal);
  },
  
  /**
   * Create and Display a Modal Window for the prompt message
   * @param msg the alert message
   * @param func the callback function
   * @param defvalue the default value
   */
  prompt: function(msg, func, defvalue){
    var modal = JCMS.window.Modal._showAlert(function(value){ 
      if (value != undefined){ func(value); }
	  }, 'prompt', msg,  defvalue);
	  JCMS.window.Modal._openModal(modal);
  },
  
  showJSP: function(jsp, callback, parameters){
    var modal = JCMS.window.Modal._createModal(jsp, callback, parameters);
    JCMS.window.Modal._openModal(modal);
  },
  
  // ----------------------------------------
  //  Private
  // ----------------------------------------
  
    
  /**
   * Create and Display a Modal Window for the current event
   * @param event the document click event
   * @param elm the A/BUTTON/INPUT element being clicked
   * @param classname the matching classname
   */
  _show: function(event, elm, classname){
    Event.stop(event);
    var modal;
    if (elm.hasClassName('warning')) {
      modal = JCMS.window.Modal._showConfirm(elm,'warning');
    }
    else if (elm.hasClassName('confirm')) {
      modal = JCMS.window.Modal._showConfirm(elm);
    }
    else if (elm.hasClassName('prompt')) {
      modal = JCMS.window.Modal._showPrompt(elm);
    }
    else {
      modal = JCMS.window.Modal._showModal(elm);
    }
    
    // Display the modal
    JCMS.window.Modal._openModal(modal, event);
  },
  
  _openModal: function(modal, event){
    if(!modal){ return; }
    if (event){ Event.stop(event); }
    
    JCMS.window.Modal.current = modal;
    JCMS.window.Modal.current.open(event);
  },
  
  _showModal: function(tag){
    // Check rel
    if (tag.rel && tag.rel == 'iframe'){
      return new Control.Modal(
        tag,
        JCMS.window.Modal._buildModalOption('def-modal', this /* =>modal */, false, false, true, 
          function(){ return document.viewport.getWidth()-50 },
          function(){ return document.viewport.getHeight()-50 }
        )
      );
    } 
    else {
      return new Control.Modal( tag, JCMS.window.Modal._buildModalOption('def-modal', this /* =>modal */));
    }
  },
  
  _showConfirm: function(tag,usage){
    return JCMS.window.Modal._showAlert(function(confirm){
      if (!confirm)    { return; }
      
      // Handle onclick: do not work because of bubbling effect
      // if (tag.onclick) {
      //   if (!tag.onclick(confirm)){
      //     return;
      //   }
      // }
      
      // Hand Href also if onlick return true
      if (tag.href)  { document.location = tag.href; }
      
      // Handle button/input with actions
      if (tag.form){
        simpleSubmitForm(window,tag.form,tag.name); 
      }
      
    },usage || 'confirm', tag.title);
  },
  
  _showPrompt: function(tag){
    return JCMS.window.Modal._showAlert(function(value){
      if (!value){ return; }
      if (tag.href) {
        document.location = getUrlWithUpdatedParam(tag.href, 'value', value);
      }
    },'prompt', tag.title);
  },
  
  _showAlert: function(callback, usage, msg, defValue){
    var jsp = 'jcore/modal/'+usage+'.jsp';
    var parameters = { msg: msg, defValue: defValue };
    var classes = usage;
    return JCMS.window.Modal._createModal(jsp, callback, parameters, classes);
  },
  
  _createModal: function(jsp, callback, parameters, classes){
    // Always create a Window because there is no reference to tag
    // if (tag._confirm){ return; } tag._confirm = true;
    var modal = new Control.Modal(
      JcmsJsContext.getContextPath()+ "/" + jsp,
      JCMS.window.Modal._buildModalOption(classes, this/* => modal */, callback, parameters)
    );
    return modal;
  },
  
  _buildModalOption: function(classes, modal, callback, parameters, iframe, width, height){ // => FIXME: Why modal parameter never used ?
    var option = {
      fade: true,
      fadeDuration:   JCMS.window.Modal.FADE_DURATION,
      overlayOpacity: JCMS.window.Modal.OVERLAY_OPACITY,
      className: 'modal '+ (classes || ''),
      height: null,
      closeOnClick: iframe || false,
      afterOpen: JCMS.window.Modal._initFocus,
      afterClose: function(){
        var modal = JCMS.window.Modal.current;
        if(!modal){ return; } // Prevent timming/dual modal errors
        
        // Retrieve confirm value from modal params
        var confirmValue = modal._confirm;
        
        // Destroy, clean modal
        modal.destroy();
        if (modal.container.parentNode){ // make sure we remove the div container (livepipe only do this if the original link is not in the DOM)
          modal.container.remove(); 
        }
        JCMS.window.Modal.current = null;
        
        // Invoke callback
        if (callback) { callback.delay(0.1, confirmValue); };  // Fix IE6/IE7 Bug: delay code that are too slow in click event scope.
      }
    };
    
    if (parameters){ option.parameters = parameters;  }
    if (iframe)    { option.iframe = iframe;   }
    if (width)     { option.width  = width;    }
    if (height)    { option.height = height;   }
    
    return option;
  },
  
  _initFocus: function(){
    if (!this.container){ return; }
    
    // Focus first .focus
    var focusElm = this.container.down('.focus');
    if (focusElm && focusElm.focus){
      focusElm.focus();
      return; 
    }
    
    // Focus first element
    var form = this.container.down('FORM');
    if (!form){ return; }
    form.focusFirstElement();
  }
  
  
  
});

// ---------------------------------------
//  EVENTS 
// ---------------------------------------

Event.observe(window, 'load'  , function() { JCMS.window.Modal.init();   });

