 /**
  * ajax/?action=votes
  * onclick="return votePhoto(this);" 
  * onmouseover="this.parentNode.className='votes votes_1'" 
  * onmouseout="this.parentNode.className='votes'"
  */

var PVotes = Class.create({
  photoId: 0,
  vote: 0,
  currentVote: undefined,
  aTitle: ['1 балл','2 балла','3 балла'],
  
  initialize: function () {
    this.prepare();
  },
  
  prepare: function () {
    var aPhotoItems = $$("div.votes");
    aPhotoItems.each(function(divPhotoVotes) {
      if(divPhotoVotes.getAttribute('info') == 'photo') {
        divPhotoVotes.getElementsBySelector('a').each(function(itemVotes, index) {
          itemVotes.title='Голосовать: '+PVotes.prototype.aTitle[index];
          itemVotes.observe('mouseout', function(event){this.parentNode.className='votes';window.status=''});
          itemVotes.observe('mouseover', function(event){this.parentNode.className='votes votes_'+(index+1);window.status='Голосовать: '+PVotes.prototype.aTitle[index];});
          itemVotes.observe('click', (PVotes.prototype.clickVote).bind(this));
        });
      }
    });
  },
  
  clickVote: function(event){
    var formVote = $('formVote');
    if(formVote) {
      formVote.hide();
      PVotes.prototype.createForm();
      var elementEvent = Event.element(event);
      this.currentVote = $(elementEvent.parentNode);
      PVotes.prototype.vote = elementEvent.getAttribute('value');
      PVotes.prototype.photoId = $(elementEvent.parentNode).getAttribute('value');
      var firstListItem = $(elementEvent.parentNode.firstChild);
      firstListItem.insert({before: formVote});
      new Effect.Appear(formVote, { duration: 0.5, from: 0.0, to: 1 });
    }
  },
  
  clickOk: function(event){
    if($F('uCaptcha').length < 4) {
      alert('Введите текст, указанный на картинке');
    }else {
      var url = base + 'ajax/?action=postVote';
      var pars = 'photoId=' + this.photoId + '&vote=' + this.vote + 
                 '&uCaptcha=' + $F('uCaptcha');// + '&uComment=' + $F('uComment');
      var photoId = this.photoId;
      var vote = this.vote;
      var myAjax = new Ajax.Request(url,
        {
          method: 'post',
          parameters: pars,
          onComplete: function(transport) {
            var hashResponse = transport.responseText.evalJSON();
            switch (hashResponse.result) {
              case 'failed' :
                  alert('Неверно введен текст, указанный на картинке.');
                break;
              case 'successfull' :
                  alert('Спасибо. Ваш голос учтен.');
                  $('rate'+photoId).innerHTML = parseInt(parseInt($('rate'+photoId).innerHTML) + parseInt(vote));
                  this.currentVote.remove();
                break;
              case 'error' :
                alert('Произошла ошибка. Попробуйте еще раз.');
              break;
              case 'already' :
                alert('Вы уже голосовали за эту фотографию.');
                this.currentVote.remove();
              break;
              case 'blocking' :
                alert('Слишком много голосов за данную фотографию.\nПопробуйте позже.');
                this.currentVote.remove();
              break;
              default :
                break;
            }
          }
        });
      $$('body')[0].firstChild.insert({before: $('formVote')});
      $('formVote').hide();
    }
  },
  
  createForm: function () {
    var formVote = $('formVote');
    if(formVote) {
      formVote.innerHTML = ''; 
      formVote.appendChild(
        Builder.node('div',{'class':currentClanName+' round'}, [
          Builder.node('div',{'class':'tl'}, [Builder.node('s'),Builder.node('u')]),
          Builder.node('div',{'class':'ml'}, [
            Builder.node('form',{'action':'#', onsubmit:'return false'}, [
              /*Builder.node('div', {'class':'message'}, 'Ваш комментарий'),
              Builder.node('div', {'class':'input'}, 
                Builder.node('textarea', {'id':'uComment','name':'uComment'})
              ),*/
              Builder.node('div', {'class':'message'}, 'Введите текст, указанный на картинке ниже'),
              Builder.node('div', {'id':'captcha'}, 
                Builder.node('img',{'src':base+'ajax/?action=getCaptchaImage&'+ Date().toLocaleString()})
              ),
              Builder.node('div', {'class':'input'}, 
                Builder.node('input', {'type':'text','id':'uCaptcha','name':'uCaptcha','maxlength':4})
              ),
              Builder.node('div', {'class':'buttons'}, [
                Builder.node('input', {'type':'button','id':'bOk','name':'bOk','value':'OK'}),
                Builder.node('input', {'type':'button','id':'bCancel','name':'bCancel','value':'Отмена'})
              ])
            ])
          ]),
          Builder.node('div',{'class':'bl'}, [Builder.node('s'),Builder.node('u')])
        ])
      );
      $('bCancel').observe('click', (function(event){formVote.hide()}).bind(this));
      $('bOk').observe('click', (PVotes.prototype.clickOk).bind(this));
    }else{
      return false;
    }
  }
});

document.observe('dom:loaded', function () { new PVotes(); });