SocialEngineAPI.CompetitionObject = new Class({
  
  // Class
  Implements: [Options],
  
  // Properties
  Base: {},
  
  changed: false,
  
  options: {
    'ajaxURL' : 'competitionobject_ajax.php'
  },


  
  // Methods
  initialize: function(options)
  {
    this.setOptions(options);

    var bind = this;
    window.addEvent('domready', function()
    {
      bind.initControl();
      bind.initEnabler();
	 
	  //if (!$('competition_voting_button'))
	  {
      	bind.getVotes();
      }
    });
  },



  initControl: function()
  {
  	//if not exists submit block
  	if (!$('comment_body')) return;
	
    // Add events
    var bind = this;
	var commentArea = $('comment_body');
	
    commentArea.addEvent('focus', function()     { bind.removeText(this);  });
    commentArea.addEvent('blur', function()      { bind.addText(this);     });
	commentArea.value = this.options.defaultText;
	
	bind.options.originalHeight = textarea_autogrow('comment_body');
	
	$('competition_voting_block').addEvent('submit', function(event)
	{
	  if(!bind.changed)
	  {
      	$('comment_body').value='';
      }
	  
	  bind.doVotePost();
      event.stop();
	  return false;
    });
    
    var b = $('competition_voting_button');
    b.disabled = false;
  },



  initEnabler: function()
  {
    var bind = this;
    
    if ($('voter_enabler_link') && bind.options.userLevel == 4)
    {
      if (bind.options.objectEnabled == 1)
      {
        $('voter_enabler_link').set('text', 'Снять с конкурса');
      }
      else
      {
        $('voter_enabler_link').set('text', 'Вернуть на конкурс');
        $('voter_enabler_link').addClass('light-grey');
      }
      
      $('voter_enabler_link').addEvent('click', function() {
        bind.edit();
      });

      $('voter_enabler_link').style.display = 'block';
    }
  },



  edit: function()
  {
    if($('voter_enabler_link').get('text') == 'Обработка') return;
    
    var bind = this;
    var enabled = (bind.options.objectEnabled == 1) ? 0 : 1;
    
    $('voter_enabler_link').set('text','Обработка');

    var request = new Request.JSON({
      'method' : 'post',
      'url' : bind.options.ajaxURL,
      'data' : {
        'task' : 'set_enabled',
        'object_id' : bind.options.objectId,
        'object_type' : bind.options.objectType,
        'enabled' : enabled
      },
      
      'onComplete' : function(responseObject) {
        if( $type(responseObject) != "object" || !responseObject.result )
        {
          alert("Ошибка обработки данных. Обновите страницу и попробуйте снова.");
        }
        else
        {
          if (responseObject.result == 'failure')
          {
            alert('Ошибка обработки данных. Обновите страницу и попробуйте снова.');
          }
          else
          { 
            bind.setViewEnabled(enabled);
          }
        }
      }
    });
    
    request.send();
  },



  getRate: function ()
  {    
    var rateObject = document.competition_voting.competition_object_rate;
    if (rateObject.length)
    {
      for (var i=0; i < rateObject.length; i++)
      {
        if (rateObject[i].checked)
        {
          return rateObject[i].value;
        }
      }
    }
    else if (rateObject.value)
    {
      return rateObject.value;
    }
    
    return null;
  },
  
  
  
  setViewEnabled: function(objectEnabled)
  {
    var bind = this;
    
    if (typeof objectEnabled != 'number') objectEnabled = !parseInt(bind.options.objectEnabled);
    
    if(objectEnabled)
    {
      bind.options.objectEnabled = 1;
      
      $('voter_enabler_link').removeClass('light-grey');
      
      $('voter_enabler_link').set('text','Снять с конкурса');
      
      if ($('voter_div'))
      {
        $('voter_div').style.display = 'block';
      }
      
      $('item_header').removeClass('light-blue');
      $('item_header').addClass('orange');
      
      if ($('item_object'))
      {
        $('item_object').addClass('orange');
      }
      
      if($('voter_enabled_text'))
      {
        $('voter_enabled_text').style.display = 'none';
      }
    }
    else
    {
      bind.options.objectEnabled = 0;
      
      $('voter_enabler_link').addClass('light-grey');
      
      $('voter_enabler_link').set('text','Вернуть на конкурс');
      
      if ($('voter_div'))
      {
        $('voter_div').style.display = 'none';
      }
      
      $('item_header').removeClass('orange');
      $('item_header').addClass('light-blue');
      
      if ($('item_object'))
      {
        $('item_object').removeClass('orange');
      }
      
      if($('voter_enabled_text'))
      {
        $('voter_enabled_text').style.display = 'block';
      }
    }
  },
  
  

  toggleVotesList: function()
  {
    if ($('voter_votes').style.display == 'none')
    {
      $('voter_votes').style.display = 'block';
      $('voter_votes_link').innerHTML = 'Скрыть оценки';
    }
    else if ($('voter_votes').style.display == 'block')
    {
      $('voter_votes').style.display = 'none';
      $('voter_votes_link').innerHTML = 'Показать оценки';
    }
  },  
  


  setViewVoteEnabled: function(id, r)
  {
    var n = $('vote_' + id);
    if (typeof r != 'number') r = !parseInt(n.get('voteEnabled'));
    
    if(r)
    {
      n.set('voteEnabled', 1);
      
      n.getElements('a').removeClass('light-grey');
      n.getElements('div').removeClass('light-grey');
      n.getElements('b').removeClass('light-grey');
      
      $('vote_edit_link_' + id).set('text','Деактивировать');
    }
    else
    {
      n.set('voteEnabled', 0);
      
      n.getElements('a').addClass('light-grey');
      n.getElements('div').addClass('light-grey');
      n.getElements('b').addClass('light-grey');
        
      $('vote_edit_link_' + id).set('text','Активировать');
    }
  },
  
  
  
  doVotePost: function()
  {
    var bind = this;
    var rate = bind.getRate();
    var voteBlock = $('competition_voting_block');
    var b = $('competition_voting_button');
    
    b.value = bind.options.submit.waitText;
    b.disabled = true;

    var request = new Request.JSON({
      'method' : 'post',
      'url' : this.options.ajaxURL,
      'data' : {
        'task' : 'vote',
        'object_id' : this.options.objectId,
        'object_type' : this.options.objectType,
        'object_rate' : rate,
        'object_body' : $('comment_body').value
      },
      'onComplete' : function(responseObject) {
        if( $type(responseObject)!="object" || !responseObject.result )
        {
          alert(bind.options.vote.error);
        }
        else
        {
          if (responseObject.result == 'failure1')
          {
            alert(bind.options.vote.failure1);
          }
          else if (responseObject.result == 'failure2')
          {
            alert(bind.options.vote.failure2);
          }
          else if (responseObject.result == 'failure3')
          {
            alert(bind.options.vote.failure3);
          }
          else
          {
            voteBlock.innerHTML = '<span class="light-blue"><b>'+bind.options.vote.textString+':</b></span> <span class="orange"><b>'+rate+'</b></span>.';
            alert(bind.options.vote.success);
            
            bind.getVotes();
          }
        }
        
        b.value = bind.options.submit.defaultText;
        b.disabled = false;        
        
      }
    });
    
    request.send();    
  },
  
  
  
  getVotes: function()
  { 
    // AJAX
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : 'post',
      'data' : {
        'task'  : 'votes_list',
        'object_id' : this.options.objectId,
        'object_type' : this.options.objectType
      },
      'onComplete' : function(responseObject, responseText)
      { 
        bind.updateVotes(responseObject);
      }
    });
    
    request.send();
  },
  
  
  
  // THIS FUNCTION UPDATES THE COMMENTS
  updateVotes: function(responseObject)
  {
    var bind = this;
    
    if( $type(responseObject) != "object" )
    {
      return false;
    }
    
    //if not exists votes block
    if (!$('voter_votes')) return;
    
    //add click event to #voter_votes_link 
    if (responseObject.total_votes > 0)
    {
      if ($('voter_votes_link_container').getStyle('display') == 'none')
      {
        $('voter_votes_link').addEvent('click', function(event)
        {
          bind.toggleVotesList();
          event.stop();
          return false;
        });
        
        $('voter_votes_link_container').setStyle('display', 'block');
      }
    }
    else
    {
      return;
    }
    
    // Prepare

    var votesContainerElement = $('voter_votes');

    var votes = $H(responseObject.votes);
    

    // CREATE DIV TO HOLD COMMENT BODY FOR CLEANING
    var voteBodyDiv = document.createElement('div');
    
    // EMPTY CONTAINER 
    votesContainerElement.empty();
    
    // LOOP OVER COMMENTS
    var bind = this;


    var t = bind.Base.Viewer.user_info;
    
    votes.each(function(voteObject, voteId)
    {
      var newVote = new Element('div',
      {
        'id' : 'vote_' + voteId,
        'voteEnabled': voteObject.vote_enabled ? 1 : 0
      });
      
      // BUILD COMMENT
      var newVoteInnerHTML = "<div class='comment1'>";
      
      // AUTHOR PHOTO
      if( voteObject.vote_authoruser_id && voteObject.vote_authoruser_exists )
      {
        newVoteInnerHTML += "<div style='float: left; width: 70px;' ><a href='" + voteObject.vote_authoruser_url + "'><img src='" + voteObject.vote_authoruser_photo + "' class='photo' width='60' border='0'></a></div>";
      }
      else
      {
        newVoteInnerHTML += "<div style='float: left; width: 70px;'><img src='./images/nophoto.gif' class='photo' width='60' border='0'></div>";
      }
      
      newVoteInnerHTML += "<div style='overflow: hidden;'>";
      
      // AUTHOR NAME/LINK
      newVoteInnerHTML += "<div class='profile_comment_author'><a href='" + voteObject.vote_authoruser_url + "'><b "+(!voteObject.vote_enabled ? "class='light-grey'" : '')+">" + voteObject.vote_authoruser_displayname + "</b></a></div>";
      
      // COMMENT DATE
      newVoteInnerHTML += "<div class='profile_comment_date "+(!voteObject.vote_enabled ? "light-grey" : '')+"' >" + voteObject.vote_date + "</div>";
      
      if (bind.options.userLevel == 4)
      {
      	var phone = voteObject.vote_authoruser_phone.split('#');
      	phone = (phone[2]?'+' + phone[2] + ' ':'') + (phone[1]?phone[1] + ' ':'') + phone[0];
        newVoteInnerHTML += "<a class=\"voteEditLink orange "+(!voteObject.vote_enabled ? "light-grey" : '')+"\" href=\"javascript:void(0);\" id='vote_edit_link_" + voteId + "' style='float: right;'>" + (!voteObject.vote_enabled ? "Активировать" : "Деактивировать") + "</a>";
        newVoteInnerHTML += "<div "+(!voteObject.vote_enabled ? "class='light-grey'" : "")+" style='float: right; margin-right: 10px;' >Телефон: <a title='" + phone + "'>" + phone + "</a>; IP: <a title='" + voteObject.vote_ip + "'>" + voteObject.vote_ip + "</a><br/>";         
        newVoteInnerHTML += "User-Agent: <a title='" + voteObject.vote_user_agent + "'>" + voteObject.vote_user_agent.substring(0,50) + "</a></div>";
      }
      
      newVoteInnerHTML += "<br /><br class='voter-br'/>";
      
      newVoteInnerHTML += "<div "+(!voteObject.vote_enabled ? "class='light-grey'" : "")+">Оценка: <b class='orange "+(!voteObject.vote_enabled ? "light-grey" : "")+"'>"+voteObject.vote_rate+"</b></div>";
      
      // COMMENT BODY
      newVote.setProperty('html', voteObject.vote_body);
      
      newVoteInnerHTML += "<div class='profile_comment_body "+(!voteObject.vote_enabled ? "light-grey" : "")+"' id='profile_comment_body_" + voteId + "'>" + voteObject.vote_body + "&nbsp;</div>";
      
      newVoteInnerHTML += "</div></div>";
      

      // ADD NEW INNERHTML
      newVote.setProperty('html', newVoteInnerHTML);
      newVote.inject(votesContainerElement);
      
      if (bind.options.userLevel == 4)
      {
        if (newVote.getElement('.voteEditLink'))
        { 
          newVote.getElement('.voteEditLink').addEvent('click', function() {
            bind.editVote(voteId);
          });
        }
      }          
    
    });
  },

  
  
  editVote: function(id)
  {
    var bind = this;
    var n = $('vote_' + id);
    var enabled = (parseInt(n.get('voteEnabled')) == 1) ? 0 : 1;
    
    $('vote_edit_link_' + id).set('text','Обработка');

    var request = new Request.JSON({
      'method' : 'post',
      'url' : bind.options.ajaxURL,
      'data' : {
        'task' : 'vote_set_enabled',
        'vote_id': id,
        'vote_set_enabled' : enabled 
      },
      
      'onComplete' : function(responseObject) {
        if( $type(responseObject)!="object" || !(responseObject.result) )
        {
          alert("Произошла ошибка. Пожалуйста, сообщите Администратору.");
        }
        else
        {
          if (responseObject.result == 'failure')
          {
            alert('Ошибка обработки данных. Обновите страницу  и попробуйте снова.');
          }
          else if (!responseObject.result)
          {
            alert('Ошибка обработки данных. Обновите страницу  и попробуйте снова.');
          }
          else
          { 
            bind.setViewVoteEnabled(id, enabled);
          }
        }
      }
    });
    
    request.send();    
  },
  
  
  
  // UI Methods
  removeText: function(commentBody)
  {
    if( !this.changed )
    {
      commentBody.value = '';
      this.changed = true;
    }
  },
  
  
  
  addText: function(commentBody)
  {
    if( !commentBody.value.trim() )
    {
      commentBody.value = this.options.defaultText;
      this.changed = false;
    }
  }
    
});