/**
 * 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");
  },
  
  relocate: function(event){
    if (JCMS.window.Modal.current){
      JCMS.window.Modal.current.position();
    }
  },
  
  /**
   * 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){
    
    // Case 0: I am in a Modal ?
    var inModal = tag.fastUp(['DIV'],'modal',false,10);
    if (inModal){
      JcmsLogger.warn('Modal','Cannont open a Modal in a Modal');
      return false;
    }
    
    // Case 1 : IFRAME requested through "rel" attribute
    if (tag.rel && tag.rel == 'iframe'){
      var window_header  = new Element('div', { className: 'iframe-modal-header'  });
      var window_title   = new Element('div', { className: 'iframe-modal-title'   });
      var window_close   = new Element('div', { className: 'iframe-modal-close'   });
      var window_content = new Element('div', { className: 'iframe-modal-content' });

      var options = JCMS.window.Modal._buildModalOption('iframe-modal', null, {
          iframe: true,
          closeOnClick: window_close,
          insertRemoteContentAt: window_content,
          width: function(){ return document.viewport.getWidth()-100; },
          height: function(){ return document.viewport.getHeight()-100; }
      });
      var modal = new Control.Modal(tag, options);

      modal.container.insert(window_header);
      modal.container.insert(window_content);
      window_header.insert(window_title);
      window_header.insert(window_close);
      window_title.update(tag.readAttribute('title') || tag.href);
      
      return modal;
    } 

    // Case 2 : IMAGES
    if (tag.hasClassName('close-modal') || (tag.href && tag.href.match(new RegExp('(jpg|jpeg|gif|png|bmp)$','img')))) {
      // If we are in a iframe, do not open the modal as the iframe might
      // be too small for the modal to be visible, instead use a popup 
      if (Util.isInIFrame()) {
        Popup.popupWindow(tag.href, tag.readAttribute('title') || tag.href, 640, 480);
        return null; // correctly handled later by _openModal
      }
      var options = JCMS.window.Modal._buildModalOption('image-modal', null, {
        closeOnClick: true
      });
      var modal = new Control.Modal(tag, options);
      return modal;
    }
    
    // Default : simple modal creation with default options
    var options = JCMS.window.Modal._buildModalOption('def-modal');
    var modal = new Control.Modal(tag, options);
    return 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, callback, { parameters:parameters })
    );
    return modal;
  },
  
  _buildModalOption: function(classes, callback, options) {
    var defaultOptions = {
      fade: true,
      fadeDuration:   JCMS.window.Modal.FADE_DURATION,
      overlayOpacity: JCMS.window.Modal.OVERLAY_OPACITY,
      className: 'modal '+ (classes || ''),
      height: null,
      position: 'center',
      closeOnClick: 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.
      }
    };
    
    var finalOptions = Object.extend(defaultOptions, options || {});
    return finalOptions;
  },
  
  _initFocus: function(){
    if (!this.container){ return; }
    
    // Force refresh
    document.fire('refresh:before' ,{ wrapper: this.container.identify() });
    document.fire('refresh:after' ,{ wrapper: this.container.identify() });
    
    // Focus first .focus
    var focusElm = this.container.down('.focus');
    if (focusElm && focusElm.focus){
      InputUtil.focus(focusElm);
      return; 
    }
    
    // Focus first element
    var form = this.container.down('FORM');
    if (!form){ return; }
    var first = form.findFirstElement();
    if (!first){ return; }
    InputUtil.focus(first);
    
  }
});

// ---------------------------------------
//  EVENTS 
// ---------------------------------------

Event.observe(window,   'load'  ,        JCMS.window.Modal.init);
Event.observe(document, 'refresh:after', JCMS.window.Modal.relocate);
Event.observe(document, 'refresh:lazy',  JCMS.window.Modal.relocate);




