/*
 * Dialog.js
 * An easy to use dialog factory that uses jQuery UI
 * By Ryan Sandor Richards
 * Copyright 2009 FreeCause, Inc.
 */

var Dialog = {
  /**
   * Fetches, initializes, and displays a dialog.
   *
   * TODO Fix me to work with the new base url system.
   *
   * @param param This is a multi-type parameter. It can be an associative array
   *  containing the keys "controller", "dialog", and "params", or it can be
   *  a string representing the name of a dialog to fetch if a default controller
   *  has been set and no parameters need to be passed.
   */
  show: function(param) {
    var controller;
    var dialog;
    var params = {};

    // Determine the controller to use pull the dialog information
    if (typeof(param) == "string" || typeof(param['controller']) == "undefined") 
      controller = window.location.toString().match(/index\.php\/([^\/]*)\//)[1];
    else 
      controller = param['controller'];

    // Ensure that a dialog name was provided
    if (typeof(param) == "string") {
      dialog = param;
    }
    else if (typeof(param['dialog']) != 'undefined') {
      dialog = param['dialog'];
    }
    else {
      throw('Dialog.show(): A dialog name must be supplied to show a dialog.');
    }
  
    // Handle parameters
    if (typeof(param) != 'string' && typeof(param['params']) != 'undefined') {
      params = param['params'];
    }
    
    // Add the site_id parameter
    params['site_id'] = Site.id;

    // Make the call to the dialog service for the given controller
    var url = Site.baseurl + controller + '/dialog/' + dialog;

    // Dialog load success function
    function success(response, status) {
      if (status == "success") {
        var dialog_html = '<div class="dialog dialog_' + dialog + '">' + response + '</div>';

        var dialog_var = jQuery.extend({}, eval('dialog_' + dialog));
        var close_func = function() {return;};

        if (typeof(dialog_var['close']) != "undefined") {
          close_func = dialog_var['close'];
        }
        // Handle parameters        
        if (typeof(param) != 'string' && typeof(param['complete']) == 'function') {
          onComplete = param['complete'];
        }else
          onComplete = function(){};

        dialog_var['close'] = function() {
          close_func();
          onComplete();
          $(this).dialog('destroy');
          $('body > .dialog_' + dialog).remove();
        }
         
        try {
          var dialog_buttons = dialog_var['buttons'];            
        } catch (e) {
          // fall back to something for IE
          var dialog_buttons;
        }

        dialog_buttons.Cancel = function(){           
          onComplete();          
          $(this).dialog('close');
        }
        
        dialog_var['buttons'] = dialog_buttons;      
        
        $('body').append(dialog_html);
        $('body > .dialog:last').dialog(dialog_var);
      } else {
        Dialog.alert("Unable to load dialog, please try again!");
      }
    }
  
    // Dialog load error function
    function error(XMLHttpRequest, textStatus, errorThrown) {
      Dialog.alert("Unable to load dialog, please try again!");
    }

    // Make the request to load the dialog
    jQuery.ajax({
      cache: false,
      dataType: 'html',
      data: params,
      success: success,
      error: error,
      url: url,
      type: 'POST'
    });
  },

  /**
   * Standard modal alert dialog using jQuery UI.
   * @param title Title for the dialog box.
   * @param msg Message to be displayed in the dialog.
   * @param callback Function to call when the OK button is clicked.
   */
  alert: function(title, msg, callback) {
    $('body').append('<div class="dialog alert">' + msg + '</div>');
    $('body > .alert').dialog({
      modal: true,
      title: title,
      buttons: {
        'Ok': function() { $(this).dialog("close"); }
      },
      close: function() {
        if (callback != undefined){
          if (typeof(callback) == 'string')
          eval(callback);
          else if (typeof(callback) == 'function')
            callback();
          else
            throw "Dialog.alert: Invalid callback type please use a string or function.";
        }
        $(this).dialog('destroy');
        $('body > .alert').remove();
      }
    });
  },

  /** 
   * Standard modal yes/no dialog.
   * @param title Title for the dialog.
   * @param msg Message for the dialog.
   * @param yes Function to execute when the user presses the yes button.
   * @param no Function to execute when the user presses the no button.
   */
  confirm: function(title, msg, yes, no) {
    $('body').append('<div class="confirm">' + msg + '</div>');
    $('body > .confirm').dialog({
      modal: true,
      title: title,
      buttons: {
        "Yes": function() { yes(); $(this).dialog("close"); },
        "No": function() { no(); $(this).dialog("close"); }
      },
      close: function() {
        $(this).dialog('destroy');
        $('body > .confirm').remove();
      }
    });
  }
};
