  
AjaxComments = {
};

AjaxComments = function(){
}

//array where some temporarly removed elements are stored
AjaxComments.content = new Array();
//AjaxComments.textarea = null;
AjaxComments.op = null;
AjaxComments.opid = null;
//AjaxComments.grippie = null;

/*
* Removes the form and restores saved content
*/
AjaxComments.deleteForm = function(form){
  $(form).parents('.content').eq(0).parent().append(AjaxComments.content['content']);
  $(form).parents('.content').eq(0).slideUp("slow", function(){
    $(form).parents('.content').siblings('.preview').remove();
    $(form).remove();
  }); 
  $("#comments ul.links li.comment_reply a").bind('click', AjaxComments.click);  
  $("#comments ul.links li.comment_edit a").bind('click', AjaxComments.click);
  AjaxComments.content = new Array(); 
  return false;
};

/*
* loads response data into the document
*/
AjaxComments.loadData = function(data, form){
  if (data != ''){
    var response = $("<div>"+data+"</div>");
    if ($(".messages", response).length > 0){
      $(form).parents('.content').eq(0).before($(response).css("display", "none"));
      $(response).fadeIn("slow");
    }
    else{
      if ($(".comment", response).length > 0){
        var response = $("<div class=\"preview\">"+data+"</div>");
        $(form).parents('.content').eq(0).before($(response).css("display", "none"));
        response.fadeIn("slow");
        $(".input-created", form).removeAttr("style");
      }
    }
  }
};

//disable submit button
AjaxComments.disableForm = function(form){
	$("form[id*='comment-form'] :submit").attr("disabled", "disabled");
};

/*
* Called whenever a submit button is called
*/
AjaxComments.submit = function(event){

//check type of operation
  if(AjaxComments.opid != "edit-discard"){
    var form = $(this);
    //set parent variable to the div containing the comment list
    
    if ($("#comments").length > 0){
      var parent = $("#comments").parent();
    }
    else{
      var parent = $(".node .content").eq(0);
    }
            //build url
    var nid = form.attr('action').split('comment/reply/');
              if(typeof(nid[1]) == 'undefined' && form.attr('action').search('edit') != (-1)){
            nid = $('form#comment-form').attr('action').split('comment/reply/');
          }
          var url = event.data.url+nid[1];
    if( AjaxComments.opid == "edit-submit"){

    //remove comment list
      $("#comments").fadeOut("slow", function(){
        $(this).remove();
      });
      parent.append("<div class=\"waitbig\" style=\"display:none\"></div>");
        $(".waitbig", parent).fadeIn("slow");    
    }

    
    //eventually retrieves comment id from the evnt object if exists( ie if the form is a reply or edit form)
    if(typeof(event.data) != 'undefined' && typeof(event.data.id) != 'undefined'){
      url += event.data.id;
    }
    //serializes form values
    var query  = $(this).formSerialize();  
    query += "&op="+AjaxComments.op;
    //properties object for ajax call
    var properties = {
      url: url,
      type: "POST",
      dataType: "html",
      data: query,
      beforeSubmit: AjaxComments.disableForm(form),
      success: function(data){

        var context = $("#block-axmedis-node_comments");
        //function called if the ajax call returns succesfully
        if($(".messages",context).length > 0){
        //if there is a .messages div in page content remove it and load data
          $(".messages",context).fadeOut("slow", function(){
            $(".messages",context).parent().remove();
            AjaxComments.loadData(data, form);
          });        
        }
        else{
         // alert($('.preview').length);
          if($('.preview').length > 0){
            $('.preview').fadeOut("slow", function(){
              $('.preview').remove();
              AjaxComments.loadData(data, form);
            });        
          }
          else{
            AjaxComments.loadData(data, form);
          }
        }
        $("form[id*='comment-form'] :submit").removeAttr("disabled");
        if(AjaxComments.opid != 'edit-preview'){
          //var form = $("#comment-form");
          var locale = "";
          if(Drupal.settings.allpages.locale != null){
            locale = Drupal.settings.allpages.locale+"/";
          }
          //ajax call to get the new comment list after a form submit operation
          $.get("?q="+locale+"ajax_comments_render/"+nid[1], function(data){
            var comments = $(data).css("display","none");
            $(".waitbig", parent).fadeOut("slow", function(){
              $(this).remove();
              
              parent.append(comments);
              AjaxComments.reloadForm();
              AjaxComments.load();
              $("#comments").fadeIn("slow"); 
            });
            $(".input-created", $(this)).attr("style", "display:none");
            AjaxComments.content = new Array();
            if(AjaxComments.opid == "edit-submit"){
              $("#comment-form").resetForm();
              $(".input-created").css("display","none");
            }                  
          });
        }    
      }
    };
    //ajax call
    $.ajax(properties);
  }
  else{
    AjaxComments.deleteForm($(this));
  }  
  return false;
}

AjaxComments.reloadForm = function(){
              Style.resizeContent();
                Drupal.behaviors.collapse();
  Drupal.behaviors.textarea();
              /*Drupal.textareaAttach();
              AjaxComments.loadFieldset();*/
}

AjaxComments.loadFieldset = function(){
    $('fieldset.collapsible > legend').each(function() {
      var fieldset = $(this.parentNode);
      // Expand if there are errors inside
      if ($('input.error, textarea.error, select.error', fieldset).size() > 0) {
        fieldset.removeClass('collapsed');
      }

      // Turn the legend into a clickable link and wrap the contents of the fieldset
      // in a div for easier animation
      var text = this.innerHTML;
      $(this).empty().append($('<a href="#">'+ text +'</a>').click(function() {
        var fieldset = $(this).parents('fieldset:first')[0];
        // Don't animate multiple times
        if (!fieldset.animating) {
          fieldset.animating = true;
          Drupal.toggleFieldset(fieldset);
        }
        return false;
      })).after($('<div class="fieldset-wrapper"></div>').append(fieldset.children(':not(legend)')));
      fieldset.filter('.collapsed').children('.fieldset-wrapper')
        .css({height: 'auto', display: 'inline'});
    });
    if(typeof(Syle) != "undefined"){
      Style.bindFieldset();
    }
    
};

/*
* Saves id and value of submit button clicked
*/    
AjaxComments.saveOp = function(event){

  AjaxComments.opid = $(this).attr("id");
  AjaxComments.op = $(this).val();
};

/*
* Handles click on a comment link
*/
AjaxComments.click = function(){
  //retrieves saved content and stores it in a local array
  var saved = new Array();
  if (typeof(AjaxComments.content['id']) != 'undefined'){
    saved['id'] = AjaxComments.content['id'].replace('/','');
    saved['content'] = AjaxComments.content['content'];
  }
  
  var comment = $(this).parents("div.links").eq(0).parent(); 
  //comment id
  var id = $(this).attr("href").slice($(this).attr("href").lastIndexOf('/'));
  AjaxComments.content['id'] = id;
  //saves content and builds url for ajax call
  if ($(this).attr("href").search("reply")!= (-1)){
    var links = $(this).parents("div.links").eq(0);
    AjaxComments.content['content'] = links;           
    var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
    var url = "?q="+locale+"ajax_comments_post/";
    var divid = "comment-form-reply";  
  }
  else{
    if($(this).attr("href").search("edit")!= (-1)){
      var submitted = comment.html();      
      AjaxComments.content['content'] = submitted;
      var parent = $(this).parents("div.links").parent();
      $(this).parents("div.links").remove();
      parent.append("<div class=\"waitsmall\"></div>");
      var locale = "";
      if(Drupal.settings.allpages.locale != null){
        locale = Drupal.settings.allpages.locale+"/";
      }
      var url = "?q="+locale+"ajax_comments_post_edit/";
      var divid = "comment-form-edit";     
    }
  }
  if($("#comment-form-reply").length <= 0 && $("#comment-form-edit").length <= 0){
    //if there isn't another reply or edit form, create one cloning the comment-form
    var form = $("#comment-form").parents().eq(0);
    $(".input-created", form).attr("style", "display:none");
    var newform = form.clone();
    $("form", newform).attr("id", divid);
    $("#edit-discard", newform).removeAttr("style");
    if(divid == "comment-form-edit"){
      //if it is an edit form change the action
      action = $("form", newform).attr("action");
      var params = action.split("?q=");
          var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
      $("form", newform).attr("action", params[0]+"?q="+locale+"comment/edit"+id);
    }
    
  }
  else{
    //if another form exists save its type and clear it
    if ($("#comment-form-edit").length > 0){
      var form = "comment-form-edit";
      $("#comment-form-edit").clearForm();
    }
    else{
      var form = "comment-form-reply";
    }
    
    $(".input-created", $("#"+form)).attr("style", "display:none");
    if (divid != form){
    //if the existing form is different from the form to be displayed change it
      var newform = $("#"+form).parents().eq(0);
      $("form", newform).attr("id", divid);
      if(divid == "comment-form-reply"){
        action = $("form", newform).attr("action");
        var params = action.split("?q=");
            var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
        $("form", newform).attr("action", params[0]+"?q="+locale+"comment/reply"+id);      
      }        
    }
    else{
      var newform = $("#"+divid).parent();
    }  
  }
  $('.preview').remove();
  if ( typeof(saved['id']) != 'undefined' ){
  //remove old form and restore saved content
    var oldform = $("#comment-"+saved['id']).next().find("form")[0];
    var dest =  $(oldform, document).parents('.content').eq(0).parent();
    dest.append(saved['content']);
    $("#comments ul.links li.comment_reply a").bind('click', AjaxComments.click);  
    $("#comments ul.links li.comment_edit a").bind('click', AjaxComments.click);
    
  }    
  if (divid == "comment-form-edit"){
  //properties object for ajax call
      var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
    var properties = {
      url: "?q="+locale+"ajax_comments_edit"+id,
      type: "GET",
      dataType: "html",
      async: false,
      success: function(data){
      //returns details about the form about to be edited and fill the form with thi details
        var results = Drupal.parseJson(data);
        for (var v in results){
          if($("#comment-form-edit [name="+v+"]", newform).length >0 && v!="format"){
            $("#comment-form-edit [name="+v+"]", newform).val(results[v]);
          }
          if ( v == "format" ){
            $("#comment-form-edit [name="+v+"]", newform).each(function(){
              if($(this).val() == results[v]){
                this.checked = true;
              }
            });
          }
        }
        $(newform).css("display", "none");
        comment.html($(newform));
        $(newform, comment).slideDown("slow");

        $("#"+divid+" :submit").bind('click', AjaxComments.saveOp);
        $("#"+divid).bind('submit', {id: id, url: url}, AjaxComments.submit);     
      }
    };
    //call to retrieve comment details
    $.ajax(properties);

  }
  else{
  //reply form
    links.remove();
    $(newform).css("display", "none");    
    comment.append($(newform));
    $(newform, comment).slideDown("slow");   
  //bind functions
    $("#"+divid+" :submit").bind('click', AjaxComments.saveOp);    
    $("#"+divid).bind('submit', {id: id, url: url}, AjaxComments.submit);
  }
  Drupal.behaviors.collapse();
  Drupal.behaviors.textarea();
  //animate fieldset
  /*$("#"+divid+" fieldset.collapsible").each(function(){
    $("legend a",this).bind('click', AjaxComments.fieldset);
  });
  //animate textarea
  $('textarea.resizable').each(function(){
    AjaxComments.textarea = $(this), staticOffset = null;
    AjaxComments.grippie = $('div.grippie', $(this).parent())[0];
    $(AjaxComments.grippie).bind('mousedown', startDrag);
  });*/

  return false;
};

/*
* Toggles fieldset animation
*/
/*AjaxComments.fieldset = function(){
  var fieldset = $(this).parents('fieldset:first')[0];
  if(!fieldset.animating){
    fieldset.animating = true;
    Drupal.toggleFieldset(fieldset);
  }
  return false;
};*/

/*
* Fires Ajax call to change page in the comment list
*/
AjaxComments.changePage = function(event){
  var parent = $("#comments").parent();
  //fades and removes comment list
  $("#comments").fadeOut("slow", function(){
    $(this).remove();
  });
  //shows wait gif
  parent.append("<div class=\"waitbig\" style=\"display:none\"></div>");
  $(".waitbig", parent).fadeIn("slow"); 
  var page = this.href.split("page=");
  

  var form = $("#comment-form");
  var nid = form.attr('action').split('comment/reply/');
      var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
  //builds url for Ajax call
  var url = "?q="+locale+"ajax_comments_render/"+nid[1];
  if(typeof(page[1]) != 'undefined'){
    url += "&page="+page[1];
  }
  // Ajax call
  $.get(url, {}, function(data){
    //call succeeded
    var comments = $(data).css("display","none");
    $(".waitbig", parent).fadeOut("slow", function(){
      //removes wait gif, shows comment list and binds function to links
      $(this).remove();
      parent.append(comments);
      //$("#comments ul.links li.comment_reply a").bind('click', AjaxComments.click); 
      //$("#comments ul.links li.comment_edit a").bind('click', AjaxComments.click);
      //$("#comments ul.pager a").bind('click', AjaxComments.changePage);
          AjaxComments.reloadForm();
    AjaxComments.load();
      $("#comments").fadeIn("slow");
    });
    AjaxComments.content = new Array(); 

  });
      

  return false;

};

/*
* Binds AjaxComments functions to comment links, and retrieves nid from global variable gnid if exists
*/
AjaxComments.load = function(){
    var locale = "";
    if(Drupal.settings.allpages.locale != null){
      locale = Drupal.settings.allpages.locale+"/";
    }
    $("#comments ul.links li.comment_reply a").bind('click', AjaxComments.click);
    $("#comments ul.links li.comment_edit a").bind('click', AjaxComments.click);
    $("#comment-form :submit").bind('click', AjaxComments.saveOp);
    $("#comment-form").bind('submit', {url: "?q="+locale+"ajax_comments_post/"}, AjaxComments.submit);
    $("#comments ul.pager a").bind('click', AjaxComments.changePage);   
};

//functions for textarea animation
    /*function startDrag(e) {
    
          staticOffset = AjaxComments.textarea.height() - Drupal.mousePosition(e).y;
          AjaxComments.textarea.css('opacity', 0.25);
          $(document).mousemove(performDrag).mouseup(endDrag);
          return false;
    }

    function performDrag(e) {
      AjaxComments.textarea.height(Math.max(32, staticOffset + Drupal.mousePosition(e).y) + 'px');
      return false;
    }

    function endDrag(e) {
      $(document).unmousemove(performDrag).unmouseup(endDrag);
      AjaxComments.textarea.css('opacity', 1);
    }*/


/*if(Drupal.jsEnabled){ 
  //when the document is ready AjaxComments.load is fired
  $(document).ready(AjaxComments.load);
}*/
Drupal.behaviors.ajaxComments = AjaxComments.load;

