/*
 * Version 0.2.1, 2009-07-14
 * 
 * @author  Are Nybakk, e-vita
 * 
 * See jdimlist-readme.txt for recent changes and known issues
 */

(function($){
  
  $.fn.jforum = function(options) {
    
    var opts = $.extend({}, $.fn.jforum.defaults, options);
          
    $(this).jdimlist(opts);
    
  };
  
  $.fn.jforum.reloadObjects = $.fn.jdimlist.reloadObjects;
  
  $.fn.jforum.setSelection = $.fn.jdimlist.setSelection;
  
  $.fn.jforum.setFirstSelection = $.fn.jdimlist.setFirstSelection;
  
})(jQuery);

$.fn.jforum.defaults = {
  data:{},
  columns:[],
  animation:{
    duration:"slow", 
    easing:"swing"
  },
  actions:[],
  maxFirstLevel:50,
  headers:true,
  objectText:true,
  objectSubmit:true,
  objectSubmitGenerator:function(e_obj_body, opts, level){
  
    function createInputFocusHandler(column) {
      return function(e) {
        if(this.value == column["defaultValue"] || this.value == column["name"]) {
          this.value = "";
        }
      }
    }
  
    function createInputBlurHandler(column) {
      return function(e) {
        if(this.value == "") {
          var thisDefaultValue = column["defaultValue"];
          if(thisDefaultValue == null || thisDefaultValue == undefined) {
            var thisDefaultValue = column["name"];
          }
          this.value = thisDefaultValue;
        }
      }
    }
    
    var e_reply = $('<div class="jforum-reply jforum-reply-collapsed"></div>').appendTo(e_obj_body);
    
    //Header
    var e_replyHeader = $('<div class="jforum-reply-header"></div>')
      .hover(
        function(e){
          this.style.cursor = "pointer";
          $(this).parent().addClass("jforum-reply-hover");},
        function(e){
          this.style.cursor = "default";
          $(this).parent().removeClass("jforum-reply-hover");})
      .click(function(e){
        var thisReply = $(this).parent();
        var thisBody = $(this).next();
        
        thisReply.toggleClass("jforum-reply-selected");
            
        thisBody.animate(
          {
            height : "toggle", 
            opacity : "toggle"
          }, 
          "slow", 
          "swing", 
          function(){
            if(thisReply.hasClass("jforum-reply-collapsed")) {
              thisReply.removeClass("jforum-reply-collapsed").addClass("jforum-reply-expanded");
            } else {
              thisReply.removeClass("jforum-reply-expanded").addClass("jforum-reply-collapsed");
            }
          }
        );
      });
    
    //Add spacers and icons
    if(++level != 0) { //Visually the depth is the same as the next level
      for(var j=level; j>1; j--) {
        $('<div class="jforum-reply-header-spacer"></div>').html("&nbsp;").appendTo(e_replyHeader);
      }
      $('<div class="jforum-reply-header-level-icon"></div>').html("&nbsp;").appendTo(e_replyHeader);
    }
    $('<div class="jforum-reply-header-icon"></div>').html("&nbsp;").appendTo(e_replyHeader);
    
    //Add label
    if(level == 0) {
      $('<div class="jforum-reply-header-label"></div>').html(opts.objectSubmitTopLabel).appendTo(e_replyHeader);
    } else {
      $('<div class="jforum-reply-header-label"></div>').html(opts.objectSubmitLabel).appendTo(e_replyHeader);
    }
    $('<div class="jdimlist-terminator"></div></div>').appendTo(e_replyHeader);
    
    e_replyHeader.appendTo(e_reply);
    
    //Body
    var e_body = $('<div class="jforum-reply-body"></div>');
    
    //Add spacers and icons
    if(level != 0) {
      for(var j=level; j>1; j--) {
        $('<div class="jforum-reply-body-spacer"></div>').html("&nbsp;").appendTo(e_body);
      }
      $('<div class="jforum-reply-body-level-icon"></div>').html("&nbsp;").appendTo(e_body);
    }
    $('<div class="jforum-reply-body-icon"></div>').html("&nbsp;").appendTo(e_body);
    
    //Body content
    var e_bodyContent = $('<div class="jforum-reply-body-content"></div>').html("&nbsp;");
    
    var submitFields = [];
    
    //Input fields
    var e_inputFields = $('<div class="jforum-reply-datainput"></div>');
    var columns = opts.columns;
    for(var i=0; i<columns.length; i++) {
      var column = columns[i];
      if(column.submitable) {
        var thisDefaultValue = column["defaultValue"];
        if(thisDefaultValue == null || thisDefaultValue == undefined) {
          thisDefaultValue = column["name"];
        }
        submitFields[submitFields.length] = 
          $('<input type="text" name="' + column.dataField + '" value="' + thisDefaultValue + '" />')
            .focus(createInputFocusHandler(column))
            .blur(createInputBlurHandler(column))
            .appendTo(e_inputFields);
      }
    }
    e_inputFields.appendTo(e_bodyContent);
    
    //Input text
    var e_inputText = $('<div class="jforum-reply-textinput"></div>');
    submitFields[submitFields.length] = 
      $('<textarea name="text"></textarea>')
        .appendTo(e_inputText);
    e_inputText.appendTo(e_bodyContent);
    
    //Submit button
    $('<button name="Send">Send</button>')
      .click(function(e){
        
          var e_context = $(this).parent().parent().parent().parent();
          var parentID = e_context.hasClass("jdimlist") ? 0 : e_context.parent().attr("id"); //Set parent ID to 0 if this is the top level submit
          var validData = true;
          
          var submitParams = {};
          for(var i=0; i<submitFields.length; i++) {
            
            var submitField = submitFields[i];
            var dataField = submitField.attr("name");
            
            //Find validator function and validate input
            var validator = null;
            if(dataField == "text") {
              validator = opts["textInputValidator"];
            } else {
              //Find column object to fetch any validator
              for(var j=0; j<opts.columns.length; j++) {
                if(opts.columns[j].dataField == dataField) {
                  validator = opts.columns[j]["validator"];
                }
              }
            }
            if(validator != null || validator != undefined) {
              validData = validData && validator(submitField.val());
            }
            
            submitParams[submitField.attr("name")] = submitField.val();
            
          }
          
          //Submit if validated
          if(validData) {
            opts.onSubmit(e, submitParams, parentID);
          }
          
        })
      .appendTo(e_bodyContent);
      
    e_bodyContent.appendTo(e_body);
    $('<div class="jdimlist-terminator"></div></div>').appendTo(e_body);
      
    e_body.appendTo(e_reply);
    $('<div class="jdimlist-terminator"></div>').appendTo(e_reply);
    
    e_reply.appendTo(e_obj_body);
    
    return true;
    
  },
  objectSubmitTopLabel:"",
  objectSubmitLabel:"",
  onSubmit:function(e, submitParams, parentID){}, //parentID = 0 if top level submit
  subObjects:true,
  navigation:true,
  sortable:false,
  reorganizable:false,
  textInputValidator:function(inputVal){return true;}   //Validator function for text input. Returns true if valid
};
