// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
};

// Preloading images
jQuery.preloadImages = function(images)
{
  for(var i = 0; i<images.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(document).ready(function(){
  // Adding a new book asset or item
  $('.add_nested_item').click(function(){
    var item_type = $(this).attr("href");
    var template = eval(item_type.replace(/.*#/, ''));
    $(item_type + "_list").append(replace_ids(template));
    return false;
  });

  // Removing a new book asset
  $('.remove_book_asset, .remove_book_related_item, .remove_book_related_experience, .remove_book_creator').click(function() {
    var target = $(this).attr("href").replace(/.*#/, '.');
    var parent =  $(this).parents("." + target);
    parent.hide();
    var hidden_input = $(this).prev("input[type=hidden]");
    hidden_input.val('1');
    return false;
  });

  // Hide more than 5 items in rollover
  $("#relatedcontent .item:gt(4), #relatedexperiencescontent .item:gt(4)").hide();
  $("#relatedcontent, #relatedexperiencescontent").addClass("aa");
  $("#relatedcontent a.sectionmore, #relatedexperiencescontent a.sectionmore").click(function() {
    var contentDiv = $(this).parent(".section");

    if (contentDiv.hasClass("aa")) {
      contentDiv.removeClass("aa")
      $("a.sectionmore", contentDiv).text("Less");
      $(".item:gt(4)", contentDiv).show();
    }
    else {
      contentDiv.addClass("aa")
      $("a.sectionmore", contentDiv).text("More");
      $(".item:gt(4)", contentDiv).hide();
    }
    return false;
  });


  // rollover on books
  var ctp = $(".cluetip");
  if (ctp.length > 0) {
    ctp.cluetip({ positionBy: 'mouse' });
  }

  // rollover on experiences
  // slightly different settings because rel attribute is taken up by
  // shadowbox settings

  var ctp = $(".cluetipexp");
  if (ctp.length > 0) {
    ctp.cluetip({ positionBy: 'mouse', attribute: "crel" });
  }

  //Adding hooks for Ajax-fied Add/Remove from library
  $('.library_action').click(function() {
    // Limitations
    // * Script does not change other book elements if there
    //   are multiple copies of book on page
    // * Script does not move the element to library section (on homepage)
    //   automatically (needs page refresh)
    var self = $(this);
    if (self.hasClass("add")){
      $.post($(this).attr('href'), { _test : "testing"},
      function(data) {
        if (data.error) {
           location.href = data.url;
          return;
        }
       self.removeClass("add");
       self.addClass("remove");
       self.attr("href", data.url)
       self.text("Remove From Library");
      },
      "json");
    }
    else if (self.hasClass("remove")) {
      $.post($(this).attr('href'), { _method : "DELETE"},
      function(data) {
       // TODO extract book id and make changes to
       // all matching book elements
       self.removeClass("remove");
       self.addClass("add");
       self.attr("href", data.url)
       self.text("Add To Library");
      },
      "json");
    }
    return false;
  });


});


function addRatings(readOnly) {
    $(document).ready(function() {
        $("input.rating").rating({
            readOnly: readOnly,
            required: true,
            "callback": function(value, link) {
                var actionUrl = $(this).parent("form").attr("action");
                var rating = value;
                $.ajax({
                    type: "POST",
                    url: actionUrl,
                    data: "rating[rating]=" + value,
                    success: function() {
                        $.jGrowl("Thanks for rating!", { header: "Memetales" });
                    },
                    error : function() {
                      window.location = LOGIN_URL;
                    }
                });
            }
        });
    });
}

function fb_connect_invite_friends(options) {

  if ( typeof options != 'object' ) { options = {} }
  if ( options.title == undefined ) { options.title = "Invite your friends" }
  if ( options.type == undefined ) { options.type = window.location.hostname }
  if ( options.all_friends_invited == undefined ) { options.all_friends_invited = "<div style='padding: 10px; font-size: 1.2em;'>You've already invited all of your friends and they've accepted.</div>" }
  if ( options.invitation_copy == undefined ) { options.invitation_copy = "" }
  if ( options.invitation_choice_url == undefined ) { options.invitation_choice_url = window.location.protocol + '//' + window.location.host + '/' }
  if ( options.invitation_choice_label == undefined ) { options.invitation_choice_label = 'Accept' }
  if ( options.request_action_url == undefined ) { options.request_action_url = window.location.href }
  if ( options.request_action_text == undefined ) { options.request_action_text = options.title }
  if ( options.friend_selector_rows == undefined ) { options.friend_selector_rows = 3 }
  if ( options.friend_selector_email_invite == undefined ) { options.friend_selector_email_invite = 'true' }
  if ( options.friend_selector_bypass == undefined ) { options.friend_selector_bypass = 'cancel' }
  if ( isNaN(options.width) ) { options.width = 760 }
  if ( isNaN(options.height) ) { options.height = 600 }

  var api = FB.Facebook.apiClient
   // added here
  FB.Connect.requireSession();
  var sequencer = new FB.BatchSequencer()
  var friends = api.friends_get(null, sequencer)
  var friends_app_users = api.friends_getAppUsers(sequencer)

  sequencer.execute(function() {

    var friend_ids = ''
    try {
      friend_ids = friends.result.sort().join(',')
    }catch(e) {;}

    var exclude_ids = ''
    try {
      exclude_ids = friends_app_users.result.sort().join(',')
    }catch(e) {;}

    var dialog = new FB.UI.FBMLPopupDialog(options.title, '')

    if ( friend_ids.length > 0 && exclude_ids.length > 0 && friend_ids == exclude_ids ) {
      var fbml = ''
      fbml += '<fb:fbml>'
      fbml += options.all_friends_invited
      fbml += '</fb:fbml>'

      dialog.setFBMLContent(fbml)
      dialog.setContentWidth(300)
      dialog.setContentHeight(70)
    }else {
      var content = ''
      content += options.invitation_copy
      content += "<fb:req-choice url='" + options.invitation_choice_url + "' label='" + options.invitation_choice_label + "' />"

      var fbml = ''
      fbml += '<fb:fbml>'
      fbml += '<fb:request-form type="' + options.type + '" content="' + content + '" invite="true" action="' + options.request_action_url + '" method="get">'
      fbml += '<fb:multi-friend-selector'
      fbml += ' actiontext="' + options.request_action_text + '" '
      fbml += ' showborder="true" '
      fbml += ' rows="' + options.friend_selector_rows + '" '
      fbml += ' exclude_ids="' + exclude_ids + '" '
      fbml += ' bypass="' + options.friend_selector_bypass + '" '
      fbml += ' email_invite="' + options.friend_selector_email_invite + '" '
      fbml += '/>'
      fbml += '</fb:request-form>'
      fbml += '</fb:fbml>'

      dialog.setFBMLContent(fbml)
      dialog.setContentWidth(options.width)
      dialog.setContentHeight(options.height)
    }
    dialog.show()
  })


}

function fb_connect_invite_friends_facebook(options) {

  if ( typeof options != 'object' ) { options = {} }
  if ( options.title == undefined ) { options.title = "Invite your friends" }
  if ( options.type == undefined ) { options.type = window.location.hostname }
  if ( options.all_friends_invited == undefined ) { options.all_friends_invited = "<div style='padding: 10px; font-size: 1.2em;'>You've already invited all of your friends and they've accepted.</div>" }
  if ( options.invitation_copy == undefined ) { options.invitation_copy = "" }
  if ( options.invitation_choice_url == undefined ) { options.invitation_choice_url = window.location.protocol + '//' + window.location.host + '/' }
  if ( options.invitation_choice_label == undefined ) { options.invitation_choice_label = 'Accept' }
  if ( options.request_action_url == undefined ) { options.request_action_url = window.location.href }
  if ( options.request_action_text == undefined ) { options.request_action_text = options.title }
  if ( options.friend_selector_rows == undefined ) { options.friend_selector_rows = 3 }
  if ( options.friend_selector_email_invite == undefined ) { options.friend_selector_email_invite = 'true' }
  if ( options.friend_selector_bypass == undefined ) { options.friend_selector_bypass = 'cancel' }
  if ( isNaN(options.width) ) { options.width = 760 }
  if ( isNaN(options.height) ) { options.height = 600 }

  var api = FB.Facebook.apiClient
  var sequencer = new FB.BatchSequencer()
  var friends = api.friends_get(null, sequencer)
  var friends_app_users = api.friends_getAppUsers(sequencer)

  sequencer.execute(function() {

    var friend_ids = ''
    try {
      friend_ids = friends.result.sort().join(',')
    }catch(e) {;}

    var exclude_ids = ''
    try {
      exclude_ids = friends_app_users.result.sort().join(',')
    }catch(e) {;}

    var dialog = new FB.UI.FBMLPopupDialog(options.title, '')

    if ( friend_ids.length > 0 && exclude_ids.length > 0 && friend_ids == exclude_ids ) {
      var fbml = ''
      fbml += '<fb:fbml>'
      fbml += options.all_friends_invited
      fbml += '</fb:fbml>'

      dialog.setFBMLContent(fbml)
      dialog.setContentWidth(300)
      dialog.setContentHeight(70)
    }else {
      var content = ''
      content += options.invitation_copy
      content += "<fb:req-choice url='" + options.invitation_choice_url + "' label='" + options.invitation_choice_label + "' />"

      var fbml = ''
      fbml += '<fb:fbml>'
      fbml += '<fb:request-form type="' + options.type + '" content="' + content + '" invite="true" action="' + options.request_action_url + '" method="get">'
      fbml += '<fb:multi-friend-selector'
      fbml += ' actiontext="' + options.request_action_text + '" '
      fbml += ' showborder="true" '
      fbml += ' rows="' + options.friend_selector_rows + '" '
      fbml += ' exclude_ids="' + exclude_ids + '" '
      fbml += ' bypass="' + options.friend_selector_bypass + '" '
      fbml += ' email_invite="' + options.friend_selector_email_invite + '" '
      fbml += '/>'
      fbml += '</fb:request-form>'
      fbml += '</fb:fbml>'

      dialog.setFBMLContent(fbml)
      dialog.setContentWidth(options.width)
      dialog.setContentHeight(options.height)
    }
    dialog.show()
  })


}

