/**
 * Copyright (c) 2009 Argentum IT Lab (http://argentum.ua/)
 * Release date: june 2009
 */


/**
* CommentFormClass class
*/
function CommentFormClass() {
  // id of container
  this.containerId = 'containerComment0';

  // isAjaxRequest
  this.isAjaxRequest = false;

  // attributes
  this.commentPage    = 1;
  this.commentObject  = '';
  this.commentId      = 0;
  this.commentPid     = 0;
  this.commentSort    = 'desc';
  this.commentPerPage = 20;


  // update object
  this.updateObject = function(object, id)
  {
    this.commentObject = object;
    this.commentId = id;
  }


  // showForm function
  this.showForm = function() {
    this.answer(0);

    var el = jQuery('#commentOperator')[0];

    if(el.innerHTML == '+')
    {
      el.innerHTML = '-';
    }
    else
    {
      el.innerHTML = '+';
    }
  }


  // processForm function
  this.processForm = function() {
    var jsonData = {};

    this.hideError();
    this.prepareData();

    var inputs = $('#formComment input');

    for(var i = 0; i < inputs.length; i++)
    {
      var el = inputs[i];

      if(el.type != 'submit' && el.type != 'button')
      {
        jsonData[el.name] = el.value;
      }
    }

    var el = $('#formComment textarea')[0];
    jsonData[el.name] = el.value;

    this.isAjaxRequest = true;

    jQuery.post("/comment_post", jsonData,
      function(data){
        commentFormObject.isAjaxRequest = false;

        if(data.status)
        {
          commentFormObject.addComment(data);
          commentFormObject.formClear();
          wcReloadCaptcha();
        }
        else{
          commentFormObject.renderError(data);
          wcReloadCaptcha();
        }
      }, "json");


    return false;
  }


  // prepareData
  this.prepareData = function()
  {
    $('#comment_object')[0].value = this.commentObject;
    $('#comment_id')[0].value     = this.commentId;
    $('#comment_pid')[0].value    = this.commentPid;
  }


  // formCancel function
  this.formCancel = function() {
    document.getElementById(this.containerId).style.display = 'none';
    document.getElementById('commentOperator').innerHTML    = '+';
    return false;
  }


  // formClear
  this.formClear = function() {
    var inputs = $('#formComment input');

    for(var i = 0; i < inputs.length; i++)
    {
      var el = inputs[i];

      if(el.type != 'submit' && el.type != 'button')
      {
        if(el.name == 'comment[code]' || el.name == 'comment[name]' || el.name == 'comment[text]')
        {
          el.value = '';
        }
      }
    }

    $('#formComment textarea')[0].value = '';
  }


  // moveForm
  this.moveForm = function(pid)
  {
    var containerId = 'containerComment' + pid;
    var oldContainerId = this.containerId;

    document.getElementById(this.containerId).style.display = 'none';
    var container = document.getElementById(this.containerId).cloneNode(true);
    this.containerId = containerId;

    $('#' + oldContainerId).remove();

    container.id = containerId;
    this.commentPid = pid;

    if(pid == 0)
    {
      $('#b-comments-header').after(container);
    }
    else
    {
      $('#comment-' + pid).next().after(container);
    }
  }


  // answer function
  this.answer = function(pid) {
    if(this.isAjaxRequest === true)
    {
      return false;
    }

    var containerId = 'containerComment' + pid;
    var oldContainerId = this.containerId;

    if(containerId == oldContainerId)
    {
      $('#' + this.containerId).toggle();

      return false;
    }

    this.moveForm(pid);
    $('#' + this.containerId).toggle();

    return false;
  }


  // addComment function
  this.addComment = function(data) {
    this.formCancel();

    var cid = data.cid;
    var class_tree = '';
    var sex = data.sex;

    if(data.pid > 0)
    {
      // get level for parent
      var level = 1;

      var match = $('#comment-' + data.pid).next()[0].className.match(/b-comments-tree-(\d)+/);
      if(match)
      {
        var level = parseInt(match[1], 10) + 1;
      }

      if(level > 5)
      {
        level = 5;
      }

      class_tree = 'b-comments-tree-' + level;
    }

    var profileUrl = 'javascript:;';
    if(data.uid > 0)
    {
      profileUrl = '/users/' + data.uid;
    }

    var html = '' +
    '<a name="comment-' + cid + '" id="comment-' + cid + '"/>' +
    '<div class="b-comments-item ' + class_tree + '">' +
      '<div class="b-comments-info">' +
        '<div class="b-comments-pic"><a href="' + profileUrl + '"><img src="/images/user_' + data.sex + '.gif" alt="" /></a></div>' +
          '<div class="b-comments-author">' +
            '<a href="' + profileUrl + '" class="' + data.sex + '">' + data.name + '</a>' +
            '<div class="b-comments-date">' + data.date + ' <a href="javascript:;" onclick="commentFormObject.answer(\'' + cid + '\')">ответить</a></div>' +
        '</div>' +
      '</div>' +
      '<div class="b-comments-entry">' +
        '<p>' + data.text + '</p>' +
      '</div>' +
     '</div>';


    if(data.pid == 0)
    {
      var children = $('#commentList').children();

      if(children.length > 0)
      {
        $(children[0]).before(html);
      }
      else
      {
        $('#commentList').append(html);
      }
    }
    else
    {
      $('#comment-' + data.pid).next().after(html);
    }

    this.scrollTo(data.cid);
  }

  // scroll to comment
  this.scrollTo = function(cid){
    var href = document.location.href;
    var ref = '#comment-' + cid;

    if(cid === '')
    {
      ref = '#comment';
    }

    document.location.href = href.substring(0, href.lastIndexOf('#')) + ref;
  }


  // renderError function
  this.renderError = function(data) {
    for(var field in data.error)
    {
      $('#comment_error_msg_' + field)[0].style.display = 'block';
    }
  }


  // hideError
  this.hideError = function() {
    var el = $('#' + this.containerId + ' span.comment_error_msg');

    for(var i = 0; i < el.length; i++)
    {
      el[i].style.display = 'none';
    }
  }


  // showCommentForPage
  this.showCommentForPage = function(page) {
    this.commentPage = page;

    this.updateComment(2);
  }


  // switchCommentPerPage
  this.switchCommentPerPage = function(number) {
    this.commentPerPage = number;
    this.commentPage = 1;

    this.updateComment();
  }


  // showCommentPerPage
  this.switchSortMode = function() {
    if(this.commentSort == 'asc')
    {
      this.commentSort = 'desc';
    }
    else
    {
      this.commentSort = 'asc';
    }

    this.commentPage = 1;

    this.updateComment();
  }


  // update comment block
  this.updateComment = function(img_ajax_number) {
    var jsonData = {};

    this.moveForm(0);

    if(undefined == img_ajax_number)
    {
      img_ajax_number = 1;
    }

    var el = $('#formComment textarea')[0];

    jsonData['page']    = this.commentPage;
    jsonData['object']  = this.commentObject ;
    jsonData['id']      = this.commentId;
    jsonData['sort']    = this.commentSort;
    jsonData['cpp']     = this.commentPerPage;

    jQuery('#img_ajax_loading_' + img_ajax_number).css('display', 'block');

    this.isAjaxRequest = true;

    jQuery.post("/comment_get", jsonData,
      function(data){
        commentFormObject.isAjaxRequest = false;

        jQuery('#img_ajax_loading_1').css('display', 'none');
        jQuery('#img_ajax_loading_2').css('display', 'none');

        if(data.length > 0)
        {
          var div = document.getElementById('blockComments');
          div.removeChild(document.getElementById('commentList'));

          if(commentFormObject.commentSort == 'asc')
          {
            $('#commentSortMode').removeClass('top');
            $('#commentSortMode').addClass('down');
          }
          else
          {
            $('#commentSortMode').removeClass('down');
            $('#commentSortMode').addClass('top');
          }

          $(div).append(data);
          commentFormObject.formCancel();
          commentFormObject.scrollTo('');
        }
      }, "html");
  }

}

var commentFormObject = new CommentFormClass();


/* End Comment */


/**
* VotingClass class
*/
function VotingClass() {
  // isAjaxRequest
  this.isAjaxRequest = false;

  // attributes
  this.votingId      = 0;

  this.doVote = function(id) {
    var num = $('#b_voting_' + id + ' input[@name="vote_' + id + '"]:checked').val();
    if(num < 1)
      return false;
    return this.postRequest('vote', id, num);
  }

  this.showResults = function(id) {
    return this.postRequest('results', id);
  }

  this.showAnswers = function(id) {
    return this.postRequest('answers', id);
  }

  this.postRequest = function(action, votingId, votingNum) {
    if(this.isAjaxRequest) {
      return false;
    }
    this.isAjaxRequest = true;
    this.votingId = votingId;
    votingNum = votingNum ? votingNum : 0;
    $('#b_voting_' + votingId).append('<div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; opacity: 0.5; background: #f0f0f3; z-index: 10">&nbsp;</div>');
    jQuery.ajax({
      type: "GET",
      url: "/voting_ajax/" + action + "/"  + votingId + "/" + votingNum,
      cache: false,
      success: this.renderResult,
      error: this.ajaxError
    });
    return false;
  }

  this.renderResult = function(html) {
    votingObject.isAjaxRequest = false;
    if(html) {
      $('#b_voting_' + votingObject.votingId).html(html);
    }
  }

  this.ajaxError = function() {
    votingObject.isAjaxRequest = false;
  }

}

var votingObject = new VotingClass();

/* End Voting */


/**
* Conference class
*/
function ConferenceClass() {
  // isAjaxRequest
  this.isAjaxRequest = false;

  // attributes
  this.questionId    = 0;

  this.doVoteQuestion = function(questionId) {
    if(this.isAjaxRequest) {
      return false;
    }
    this.isAjaxRequest = true;
    this.questionId = questionId;
    $('#b_question_' + questionId).append('<div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; opacity: 0.5; background: #f0f0f3; z-index: 10">&nbsp;</div>');
    jQuery.ajax({
      type: "GET",
      url: "/conference_ajax/" + questionId,
      cache: false,
      success: this.renderResult,
      error: this.renderResult
    });
    return false;
  }

  this.renderResult = function(html) {
    if(html) {
      $('#question_rating_' + conferenceObject.questionId).html(html);
      $('#question_rating_link_' + conferenceObject.questionId).fadeOut();
    }
    conferenceObject.isAjaxRequest = false;
  }

}

var conferenceObject = new ConferenceClass();

/* End Conference */
