/**
 * JavaScript comment.js
 * @version 1.0
 * @Created: 2011-01-10
 * @Author: Oscar Engström, http://www.engstream.se/
 *
 * Comment to this document:
 * No comment yet
 */

$(document).ready(function(){
  //Initialize
  performerComment.init();
});

var performerComment = {
  /**
   * Run this function once for initializing and binding
   */
  init: function(){
    $(".addComment").live('click', function(ev){
      ev.preventDefault();
      //Send event to function for adding comment (sending $(this) helps making several comment-fields for one page possible)
      performerComment.addComment($(this));
    });

    //For anonymous users that place a comment here, we ask for their name, this is the second submit sort of...
    $("#nameCommentSubmit").live('click', function(ev){
      ev.preventDefault();
      //Send event to function for adding comment (sending $(this) helps making several comment-fields for one page possible)
      performerComment.addComment($(this));
    });

    //Check if this page has box for comments
    if(typeof($("#commentBox").attr('id')) !== 'undefined'){
      //Load comments
     performerComment.getComments();
    }

    //When someone wants to report a comment (link to form)
    $(".reportComment").live('click', function(ev){
      ev.preventDefault();
      //Send event to function for reporting comment (sending $(this) helps making several comment-fields for one page possible)
      performerComment.reportComment($(this));
    });

    //When someone wants to report a comment (submit)
    $("#reportCommentSubmit").live('click', function(ev){
      ev.preventDefault();
      //Send event to function for reporting comment (do the actual reporting)
      performerComment.performReportComment($(this));
    });

    //When someone wants to answer a comment (link to form)
    $(".replyComment").live('click', function(ev){
      ev.preventDefault();
      //Send event to function for answering comment (sending $(this) helps making several comment-fields for one page possible)
      performerComment.answerComment($(this));
    });

    $("a.rulesForCommenting").live('click', function(ev){
      ev.preventDefault();
      //Get template for rules
      performerComment.getRulesTemplate();
    });
  },

  /**
   * Add a comment to item (most likely an article)
   * @param $this jQuery-object of trigger (most likely a button)
   */
  addComment: function($this){
    var commentHolder = new Object();
        commentHolder.trigger = $this;
        commentHolder.form = $("#makeComment");
    
    //Get parameters and values for comment
    commentHolder.sourceID = commentHolder.form.find('input[name="sourceID"]').val();
    commentHolder.commentType = commentHolder.form.find('input[name="commentType"]').val();
    commentHolder.commentatorType = commentHolder.form.find('input[type="radio"][name="makeCommentLoggedInAs"]:checked').val();
    commentHolder.comment = commentHolder.form.find('textarea[name="comment"]').val();
    commentHolder.parentCommentID = commentHolder.form.find('input[name="parentCommentID"]').val();

    switch(commentHolder.commentatorType){
      case 'site':
        //User wants to add comment as logged in on site
        if(performerFrontUser.isLoggedIn()){
          //User is logged in on site
          performerComment.performAddComment(commentHolder);
        } else {
          //User is not yet logged in on site
          performerFrontUser.sayLogin();
        }
        break;
      case 'facebook':
        //User wants to add comment as logged in through Facebook
        if(performerFacebook.isLoggedIn()){
          //User is logged in on Facebook and connected
          performerComment.performAddComment(commentHolder);
        } else {
          //User is not yet logged in on site
          performerFacebook.getConnectTemplate();
        }
        break;
      case 'anonymous':
        //User wants to add comment not logged in at all
        if(typeof($("#nameCommentName").attr('id')) === 'undefined'){
          performerComment.getNameTemplate();
        } else {
          if($("#nameCommentName").val().length == 0){
            performerComment.getNameTemplate();
          } else {
            commentHolder.commentatorName = $("#nameCommentName").val();
            performerComment.performAddComment(commentHolder);
          }
        }
        break;
      default:
        //Illegal case
        break;
    }
  },

  performAddComment: function(commentHolder){
    //Validate before sending comment
    if(performerComment.validate(commentHolder)){
      //Comment is validated
    } else {
      //Comment is not validating
      var data = new Object();
          data.action = 'getCommentNotValidatingInfoTemplate';

          var dataString = $.toJSON(data);

          $.post('ajax/comment.php', {data: dataString}, function(res){
              var obj = $.evalJSON(res);
              if(obj.success == 1){
                //Comment-template successfully loaded
                performerShadowbox.stdOpen(obj.tpl, 155, 555);
              } else {
                //Could not get the comments

              }
          });
      return false;
    }

    var data = new Object();
        data.action = 'addComment';
        data.sourceID = commentHolder.sourceID;
        data.commentType = commentHolder.commentType;
        data.commentatorType = commentHolder.commentatorType;
        data.comment = commentHolder.comment;
        if(commentHolder.commentatorName){
          data.commentatorName = commentHolder.commentatorName;
        }
        if(commentHolder.parentCommentID){
          data.parentCommentID = commentHolder.parentCommentID;
        }

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Comment added succesfully
              performerShadowbox.stdOpen(obj.tpl);
              performerComment.getComments();
              $("#makeComment").find('input[name="parentCommentID"]').val('');
            } else {
              //Error
              performerShadowbox.stdOpen(obj.tpl);
            }
        });
  },

  getComments: function(){
    var articleID = $('div[id^="articleID_"]').attr('id');
        articleID = filterString(articleID, 'articleID_');
    var data = new Object();
        data.action = 'getComments';
        data.articleID = articleID;

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Comment-template successfully loaded
              $("#commentItemHolder").html(obj.tpl);
              //Re-init wrShadow (performer gathers all necessary instances)
              performerWRShadow.init();
            } else {
              //Could not get the comments

            }
        });
  },

  getRulesTemplate: function(){
    var data = new Object();
        data.action = 'getRulesTemplate';

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Name-template succesfully loaded
              performerShadowbox.stdOpen(obj.tpl, 350, 555);
            } else {
              //Could not get template for name
            }
        });
  },

  getNameTemplate: function(){
    var data = new Object();
        data.action = 'getNameTemplate';

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Name-template succesfully loaded
              performerShadowbox.stdOpen(obj.tpl, 250, 555);
            } else {
              //Could not get template for name
            }
        });
  },

  /**
   * Report a comment
   * @param $this jQuery-object of trigger (most likely a link)
   */
  reportComment: function($this){
    var commentHolder = new Object();
        commentHolder.trigger = $this;
        commentHolder.layer = $this.parents('div.whiteField');

    //Get commentID for reporting comment
    var commentID = commentHolder.layer.attr('id');
        commentID = filterString(commentID, 'commentID_');

    var data = new Object();
        data.action = 'getReportTemplate';
        data.commentID = commentID;

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Comment-template successfully loaded
              performerShadowbox.stdOpen(obj.tpl, 575, 555);
            } else {
              //Could not get the comments

            }
        });
  },

  /**
   * Report a comment, do the actual reporting here
   * @param $this jQuery-object of trigger (most likely a link)
   */
  performReportComment: function($this){
    var commentHolder = new Object();
        commentHolder.form = $this.parents('form');

    //Get parameters and values for comment
    commentHolder.commentID = $("#reportCommentCommentID").val();
    commentHolder.name = $("#reportCommentName").val();
    commentHolder.phone = $("#reportCommentPhone").val();
    commentHolder.email = $("#reportCommentEmail").val();
    commentHolder.comment = $("#reportCommentComment").val();

    if(commentHolder.comment.length == 0){
      alert("Du har inte skrivit någon kommentar till din anmälan. Beskriv vad det är du misstycker om gällande kommentaren, det hjälper oss att behandla ärendet snabbare.");
      return false;
    }

    var data = new Object();
        data.action = 'reportComment';
        data.commentID = commentHolder.commentID;
        data.name = commentHolder.name;
        data.phone = commentHolder.phone;
        data.email = commentHolder.email;
        data.comment = commentHolder.comment;

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Comment-template successfully loaded
              performerShadowbox.stdOpen(obj.tpl, 155, 555);
            } else {
              //Could not get the comments

            }
        });
  },

  /**
   * Answer a comment
   * @param $this jQuery-object of trigger (most likely a link)
   */
  answerComment: function($this){
    var commentParentID = $this.parents('div.whiteField').attr('id');
        commentParentID = filterString(commentParentID, 'commentID_');
        $("#makeComment").find('input[name="parentCommentID"]').val(commentParentID);
        $("#makeComment").find('textarea[name="comment"]').focus();
    wrScroll.scrollTo(0,$("#commentBox").position().top);

    var data = new Object();
        data.action = 'getAnswerCommentTemplate';

        var dataString = $.toJSON(data);

        $.post('ajax/comment.php', {data: dataString}, function(res){
            var obj = $.evalJSON(res);
            if(obj.success == 1){
              //Comment-template successfully loaded
              performerShadowbox.stdOpen(obj.tpl, 155, 555);
            } else {
              //Could not get the comments

            }
        });
  },

  /**
   * Validate a comment
   * @param $this jQuery-object of trigger (most likely a link)
   */
  validate: function(commentHolder){
    var isPassed = true;
    if(commentHolder.comment.length == 0){
      isPassed = false;
    }
    if(commentHolder.sourceID.length == 0){
      isPassed = false;
    }

    return isPassed;
  }
}
