jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "application/json") }
});

$(document).ready(function() {
  var searchbox = $('#search');
  if ($('#search')) {
    searchbox.focus(function() {
      if ($(this).val() === 'Search by title, author, or ISBN.') {
        $(this).css('color', '#000');
        $(this).val('');
      }
    });
    searchbox.blur(function() {
      readIt.setDefaultSearch();
    });
    readIt.setDefaultSearch();
  }

  // on readlog user pg.
  $('.form-post').click(function(){
    var status = $(this).attr('rel');
    $(this).parents('form').find('.readlog-status').attr('name', 'readlog[' + status + ']');
    $(this).parents('form').submit();
    return false;
  });

  // BOOK SEARCH RESULTS
  $('.book-result .post-readlog').click(function() {
    // TODO: show user something is happening
    var rel = $(this).attr('rel');
    var asin = rel.substr(rel.indexOf('-')+1);
    var status = rel.substr(0, rel.indexOf('-'));
    $('#readlog_status_' + asin).attr('name', 'readlog[' + status + ']').val('true');
    if ($(this).hasClass('active')) {
      $.post(
        '/readlogs/cancel/'+status+'/'+asin,
        {
          _method: 'put',
          authenticity_token: AUTH_TOKEN
        },
        function (data) {
          $('#readlog_' + status + '_' + asin).removeClass('active');
        },
        'json' 
      );
    } else {
      $.post( 
        '/readlogs',
        $('form#book_' + asin).serialize(),
        function (data) {
          $('#readlog_' + status + '_' + asin).addClass('active');
          $('#result-' + asin + ' div.status p.' + status).html(data.msg);
          // Also publish to stream, if user has asked.
          if (data.fb_publish) {
            readIt.publishToFacebook(data);
          }
        },
        'json'
      );
    }
    return false;
  });

  $('.book-result .cancel').live('click', function() {
    if (confirm('Are you sure?')) {
      var e = $(this);
    }
  });

  // leaving comments.
  $('.book-result .comment').live('click', function() {
    if ($(this).val() == 'Leave a comment?') {
      $(this).val('');
    }
  });

  $('.save-comment').live('click', function() {
    var id = $(this).attr('rel');
    var new_comment = $('#comment-' + id).val();
    $.post(
      '/readlogs/update/' + id,
      {
          _method: 'put',
          authenticity_token: AUTH_TOKEN,
          comment: new_comment
      },
      function (data) {
        if (data.msg == 'Success.') {
          $('#save-comment-' + id).val('Saved');
          $('div#comment-form-' + id).html('<q>' + new_comment + '</q>');
        }
      },
      'json'
    );
  });

  // Profile comment editing
  $('.edit-comment').live('click', function() {
    var id = $(this).attr('rel');
    var commentDiv = $('#comment-form-' + id);
    // If it's already showing field, ignore.
    if (commentDiv.html().indexOf('input') == -1) {
      var html = '<q><input type="text" class="comment" id="comment-' + id + '" name="comment" value="' + commentDiv.find('q').text() + '" size="50" maxlength="150" /></q><input type="button" value="Save" class="save-comment" id="save-comment-' + id + '" rel="' + id + '" />';
      commentDiv.html(html);
    }
  });

  $('.post-readlog-to-facebook').click(function() {
    var id = $(this).attr('rel');
    $.getJSON(
      '/readlogs/' + id + '.json',
      readIt.publishToFacebook
    );
    return false;
  });

  // FB USER PROFILE
  $('input#user_fb_publish_started').click(function() {
    if ($(this).is(':checked')) {
      FB.Connect.showPermissionDialog("publish_stream");
    }
  });

  $('input#user_fb_publish_finished').click(function() {
    if ($(this).is(':checked')) {
      FB.Connect.showPermissionDialog("publish_stream");
    }
  });

  $('.book-result').mouseover(function(){
    $(this).addClass('hover');
  });
  $('.book-result').mouseout(function(){
    $(this).removeClass('hover');
  });

});

var readIt = {
  publishToFacebook: function(data) {
    var attachment = {
      'name': data.book_info.book.title,
      'href': 'http://amazon.com/dp/' + data.book_info.book.asin + '/?tag=rea036-20',
      'caption': 'By ' + data.book_info.book.author,
      'description': data.book_info.book.description
    };

    if (data.book_info.book.image != '') {
      attachment['media'] = [ {
        'type': 'image',
        'src': data.book_info.book.image.replace(/%2b/ig, '+'),
        'href': 'http://amazon.com/dp/' + data.book_info.book.asin + '/?tag=rea036-20'
      } ]
    }

    FB.Connect.streamPublish(
      data.fb_publish_msg,
      attachment,
      data.action_links
    );

  },
  setDefaultSearch: function() {
    if ($('#search') && $('#search').val() === '') {
      $(this).css('color', '#ccc');
      $(this).val('Search by title, author, or ISBN.');
    }
  }
};
