/* conf */
var config = {
   time_update_interval : 60000,
   get_new_interval : 15000,
   post_delay : 1000,
   ajax: '/ajax.php',
   /* cookie names */
   lang : 'lang',
   nick : 'nick',
   post_class : ['odd', 'even'],
   post_self : 'author'
}

$(document).ready(function() {
   // setup init stuff
   speeka.init();
   setInterval(get_new, config.get_new_interval);
   setInterval(update_time, config.time_update_interval);
    
   // get japtcha
   $.getJSON(config.ajax + '?cmd=japtcha', function(data) {
      $('<input type="hidden" name="japtcha_key" value="'+ data.key +
         '" />').insertAfter('#topic-post div');
      $('<input type="hidden" name="japtcha_response" value="' +
         eval(data.chal) + '" />').insertAfter('#topic-post div');
   });
    
   // bind votes
   $('ol#posts li span.vote a').click(function() {
      var post = $(this).parents('li').attr('id').split('-')[0].substring(4);
      var a = this;
        
      // check if we already clicked
      if($('a',$(this).parent()).is('.voted-good,.voted-bad'))
         return false;
                  
      if($(this).hasClass('good'))
         vote(a, post, 1);
      else
         vote(a, post, -1);
            
      return false;
   });
   
   // bind submit
   $('form#topic-post').submit(function() {
      var textEl = $('#post-text', this);
      
      if($.trim(textEl.val()) == '') 
         return false;
        
      if(speeka.posting) return false;
        
      speeka.posting = true;
      show_loading();
      
      // add nick if set
      speeka.setPost(textEl.val());
      textEl.val(speeka.postWithNick());
              
      var last = $('ol#posts li:first').attr('id');
      $.ajax({
         url : this.action,
         type : 'POST',
         dataType : 'json',
         data : $(this).serialize() + '&ajax=true' +
               ((typeof last != 'undefined') ? '&last=' + last.split('-')[0].substring(4) : ''),
         success : on_success,
         error: on_error
      });
        
      return false;
   });
    
   $('#set-nick').hide();
    
   $('#nickname').click(function() {
      if($('#set-nick:hidden').length) {;
         $('#nick').val(speeka.nick ? speeka.nick : '');
         $('#set-nick').fadeIn('slow');
      } else {
         $('#set-nick').fadeOut('slow');
      }
         
      return false;
   });
   
   $('#set-nick form').submit(function() {
      $('#set-nick').hide('slow');
      
      if($.trim($('#nick',this).val()) == '') {
         speeka.clearNick();
      } else {
         speeka.setNick($('#nick', this).val());
      }
      
      $('#post-text')[0].focus();
      return false;
   });
    
    // ie fix
   $('#menu li').mouseover(function() {
      if($('ul', this).length)
         $('ul', this).css('display', 'block');
   });
    
   $('#menu li').mouseout(function() {
      if($('ul', this).length)
         $('ul', this).css('display', 'none'); 
   });
    
    // lang choosing
   $('#menu li ul a').click(function() {
      util.setCookie(config.lang, $('img', this).attr('alt'));
      window.location.reload();
       
      return false;
   }); 
    
   // focus input
   $('#post-text')[0].focus();
});

/* posting & nick */
var speeka = {
   posting : false,
   post : null,
   nick: null,
   
   /* init some stuff */ 
   init: function() {
      this.nick = util.getCookie(config.nick)
   },
   
   setPost : function(value) {
      this.post = value;
   },
   
   clearPost : function() {
      this.post = null;
   },
   
   setNick : function(value) {
      this.nick = value;
      util.setCookie(config.nick, value);
   },
   
   clearNick : function() {
      this.nick = null;
      util.deleteCookie(config.nick);  
   },
   
   postWithNick : function() {
      var post = this.post ? this.post : '';
      return this.nick ? post + ' (' + this.nick + ')' : post;
   },
   
   checkPost: function(text) {
      return util.htmlSpecialChars(this.postWithNick()) == text;
   }
   
}

/* utility functions */
var util = {
   setCookie : function (name, value) {
      var expire = new Date();
      expire.setDate(expire.getDate() + 30);
      document.cookie = name  + '=' + escape(value) + '; expires='
         + expire.toUTCString() + '; path=/';
   },
   
   getCookie : function(name) {
      var index = -1;
   
      if(document.cookie.length > 0)
      {
         index = document.cookie.indexOf(name + '=');
         if(index != -1)
         {
            index = index + name.length + 1
            var end = document.cookie.indexOf(';', index);
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(index, end));
         }
      }
   
      return null;
   },
   
   deleteCookie : function(name) {
      var date = new Date(1);
      document.cookie = name + '=; expires=' + date.toUTCString() +
      '; path=/';
   },
   
   htmlSpecialChars : function(text) {
      text = text.replace(/&/g, '&amp;');
      text = text.replace(/</g, '&lt;');
      text = text.replace(/>/g, '&gt;');
      text = text.replace(/"/g, '&quot;');
      return text.replace(/(http:\/\/([-a-zA-Z0-9@:%_\+.;~#?&\/=]+))/,
         '<a href="$1" rel="nofollow">$1</a>');
   }
}

function get_new()
{
   var options = {
      cmd : 'get_new',
      topic : $('form#topic-post input[name=topic]').val()
   };
   var last = $('ol#posts li:first').attr('id');
   if((typeof last != 'undefined'))
      options.last = last.split('-')[0].substring(4);
        
   $.getJSON(config.ajax, options, function(data) {
      if(data.status)
         update_page(data);
   });
}

function show_loading()
{
   $('#siteinfo').remove();
   $('.important').hide();
   $('#write').hide();
   $($('.important').length ? '.important' : 'div#set-nick').after('<div id="write-loading"><p>' + 
      lang.message_posting + '</p></div>');
}

function on_success(data)
{
   // update japtcha
   $('input[name=japtcha_key]').val(data.japtcha_key);
   $('input[name=japtcha_response]').val(eval(data.japtcha_chal));
    
   if(data.status) {     
      $('#write-loading p').text(lang.message_post_success);
      setTimeout(function() {
         if($('ol#posts li span.vote:not(:hidden)').length == 0)
               $('ol#posts li span.vote').show();

	 update_page(data);
         $('#mod_pass').hide();
         $('#write-loading').remove();
         $('#write').show();
         $('#post-text').val('').focus();
         speeka.clearPost();
      }, config.post_delay);
   } else {
      $('#post-text').val(speeka.post);
      speeka.clearPost();
      set_info(lang.error_post + ' : ' + data.error);
      setTimeout(function() {
         $('#write-loading').remove();
         $('#write').show();
      }, config.post_delay);
   }
   
   speeka.posting = false;
}

function on_error(XMLHttpRequest, textStatus, errorThrown)
{
   $('#post-text').val(speeka.post);
   speeka.clearPost();
   set_info(lang.error_req);
   setTimeout(function() {
      $('#write-loading').remove();
      $('#write').show();
   }, config.post_delay);
   
   speeka.posting = false;   
}

function update_page(data)
{
   var ol = $('ol#posts');
   var elements = $(ol).length;
   var post_class;
   for(key in data.new_posts)
   {
      if(post_id_exists(data.new_posts[key]))
         continue;

      if ($('li', ol).length == 0) {
         post_class = config.post_class[0];
      } else {
         post_class = ($('li:first', ol).hasClass(config.post_class[0]) ?
            config.post_class[1] : config.post_class[0]);
      }
        
      $(create_post_markup(data.new_posts[key], post_class)).prependTo(ol);
      bind_vote($('li:first', ol));
      
      // add 'author' class if we wrote post
      if(speeka.checkPost(data.new_posts[key].message))
         $('li:first', ol).addClass(config.post_self);
      
      if($('li span.vote:not(:hidden)', ol).length)
         $('li:first span.vote', ol).show();
   }
    
   if($(ol).length > elements)
      update_time();
}

function update_time()
{
   $('ol#posts li').each(function() {
      var me = this;
      $('em',this).text('(' + format_time($(this).attr('id').split('-')[1]) + ')');
   });
}

function post_id_exists(post)
{
   if($('li#post' + post.id + '-' + post.time).length)
      return true;
   else
      return false;
}

function create_post_markup(post, post_class)
{
   return '<li id="post' + post.id + '-' + post.time + '" class="' + post_class +
      '"><span class="vote" style="display:none;"><a href="#"' +
      'title="' + lang.vote_up + '" class="good"></a><a href="#"' +
      'title="' +  lang.vote_down + '" class="bad"></a></span><span ' +
      'class="message">' + post.message + '<em class="time">(' +
      format_time(post.time) + ')</em></span></li>';      
}

function bind_vote(element)
{   
   $('span.vote a', element).click(function() {
      var post = $(element).attr('id').split('-')[0].substring(4);
      var a = this;
        
      if($('span.vote a', element).is('.voted-good, .voted-bad'))
         return false;
        
      if($(this).hasClass('good'))
         vote(a, post, 1);
      else
         vote(a, post, -1);
            
      return false;
   });
}

function vote(a, post, param)
{
   $.get(config.ajax, {cmd:'vote', 'post':post, 'param':param},
      function(data) {
         if(parseInt(data)) {
               if(param == 1) {
                  $('a.bad', $(a).parent()).hide();
                  $(a).addClass('voted-good');
               } else {
                  $('a.good', $(a).parent()).hide();
                  $(a).addClass('voted-bad');
               }
         }
   });
}

function set_info(info)
{
   if($('.important').length)
      $('.important').show();
   else
      $('<div><p></p></div>').insertAfter('div#set-nick').addClass('important');
    
   $('.important p').text(info);
}
