jQuery.ajaxSetup({
  dataType: "json",
  error: function(xhr, textStatus, errorThrown) {
    console.log(errorThrown);
  }
});

jQuery(document).ready(function($) {

  $("input[type=text][placeholder], textarea[placeholder]").focus(function() {
    if ($(this).val() == $(this).attr('placeholder'))
      $(this).val('');
    $(this).css('color', '');
  }).blur(function () {
    if ($(this).val() == '')
      $(this).css('color', '#999999').val( $(this).attr('placeholder') );
  }).val(function() {
    return $(this).attr('placeholder');
  }).css('color', '#999999');
  
  $("input[type=password][placeholder]").blur(function() {
    if ($(this).val() == '')
      $(this).hide().prev().show();
  }).hide().before(function() {
    if (this != document) {
      var passwd = $(this);
      return $("<input type='text' value='" + passwd.attr('placeholder') + "' />").focus(function() {
        $(this).hide();
        passwd.show().focus().css('color', 'black');
      }).css('color', '#999999');
    }
  });
  
  $("form").submit(function() {
    $(this).find("[placeholder]").val(function() {
      return $(this).attr('placeholder') == $(this).val() ? '' : $(this).val(); 
    });
  });
  
  $("a[rel=vote]").click(function() {
    var match = $(this).attr('href').match(/vote\/(\w+)\/(\d+)\/\d/)
    var id = match[2],
        block = $(this).parents("." + match[1]);
    
    $.ajax({
      url: $(this).attr('href'),
      success: function(answer) {
        if (answer) {
          $("div.num", block)
            .html(answer.rate)
            .addClass(answer.rate < 0 ? 'negative' : 'positive')
            .removeClass(answer.rate < 0 ? 'positive' : 'negative');
          
          $("div.voteProgress", block).hide();
          $("div.voteAnswer", block).show().html(answer.message);
          setTimeout(function() {
            $("div.voteAnswer", block).hide().html('');
          }, 3000);
        }
      }
    });
    
    $(this).parents("." + match[1]).find("div.voteProgress").show();
    return false;
  });
  
  $("a[rel=get50]").click(function() {
    var link = this;
    
    $.ajax({
      url: $(link).attr('href'),
      type: 'POST',
      data: {
        offset: $(".comments .comment").length
      },
      success: function(answer) {
        if (answer) {
          $(".comments").append(answer.html);
          
          $(".get50Progress").hide();
          if (answer.more)
            $(link).show();
        }
      }
    });
    
    $(link).hide();
    $(".get50Progress").show();
    
    return false;
  });
  
  $("a[rel=aremove]").click(function() {
    var link = $(this);
    
    $.ajax({
      url: link.attr('href'),
      success: function(answer) {
        if (answer == 1) {
          link.parents(".comment, .answer").fadeOut(1000, function() {
            $(this).add( $(this).next() ).remove();
          });
        }
        else {
          link.next().remove();
          link.after('Ошибка!');
        }
      }
    });
    
    link.hide().after('<img src="/images/loading.gif" height="12" />');
    
    return false;
  });
  
  $("form[name=addcomment], form[name=answer]").submit(function() {
    var form = this;
    
    $.ajax({
      url: $(form).attr('action'),
      type: 'POST',
      data: $(form).serialize(),
      success: function(answer) {
        if (answer) {
          if (answer.html) {
            $("#add_form").slideUp(500, function() {
              $(this).remove();
              $(".comments").prepend(answer.html);
            });
          }
          else if (answer.errors) {
            if ($("#errorlist").length)
              $("#errorlist").html('');
            else
              $("<div id='errorlist'></div>").prependTo(form);
            
            for (var i = 0; i < answer.errors.length; i++)
              $("#errorlist").append("<div class='errmsg'>" + answer.errors[i] +  "</div>");
          }
        }
      }
    });
    
    return false;
  });
  
  $("form[name=login]").submit(function() {
    var form = this;
    
    $.ajax({
      url: $(form).attr('action'),
      type: 'POST',
      data: $(form).serialize(),
      success: function(answer) {
        if (answer) {
          if (answer.success)
            window.location = window.location;
          else if (answer.errors) {
            if ($("#errorlist").length)
              $("#errorlist").html('');
            else
              $("<div id='errorlist'></div>").prependTo(form);
            
            for (var i = 0; i < answer.errors.length; i++)
              $("#errorlist").append("<div class='errmsg'>" + answer.errors[i] +  "</div>");
          }
        }
      }
    });
  
    return false;
  });
  
  $("img[rel=captcha]").click(function() {
    var sid = parseInt(Math.random() * 100000);
    
    $("input[name=captchaSid]").val(sid);
    $(this).attr('src', '/captcha/' + sid + '.html');
  });
  
  var popups = $();
  
  $("<div id='overlay'></div>").click(function() {
    $(this).hide();
    $(popups).hide();
  }).appendTo('body');
  
  $("a[rel=login]").click(function() {
    var dh = $(window).height(),
        dw = $(window).width();
    
    var form = $("#login_form").css({
      left: (dw - 275) / 2,
      top: (dh - 300) / 2
    }).show();
    
    popups = popups.add(form);
    $("#overlay").show();
    
    return false;
  });
  
  $("#vcategory").val('Выберите категорию');
  $(".subcategory").val('Выберите категорию');
  $("#qtext").tinymce({
    theme : "advanced",
    theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,cut,copy,paste,|,undo,redo,|,image",
    theme_advanced_buttons2: "",
    theme_advanced_buttons3: "",
    theme_advanced_toolbar_location: "top"
  });
  
  $("#category").change(function() {
    $(".subcategory:visible").slideUp('fast').val(0);
    $("#subcategory" + $(this).val()).slideDown('fast');
  });
  
  $("#addphoto").click(function() {
    var cls = $(".fakefile").parent().attr('class');
    
    $(this).parent().before(
      "<div class='" + cls + "'><input type='file' name='photo[]' class='fakefile'  />" +
        "<input type='text' placeholder='Фото' readonly='readonly' />" +
      "</div>" +
      "<div class='clear'></div>");
  
    $(this).parent().parent().find("." + cls + " input:text:last").val('Еще фото').css('color', '#999999');
    
    if ( $(".fakefile").length >= 5 )
      $(this).parent().remove();
    
    return false;
  });
  
  $(".fakefile").live('change', function() {
    $(this).next().val( $(this).val() ).css('color', '');
  });
  
});

