$(document).ready(function(){  
  initialize_export();
  initialize_email();
  initialize_print();

  $("#edit_link").click(function() {
    $("#bookbag_edit").fadeToggle();
  });

  $('.remove_from_bookbag').click(function() {
    remove_url = $(this).attr('href')
    $.getJSON(remove_url);
    $(this).closest('div.booksInfo').fadeOut();
    return false;
  }); 
});

function initialize_print() {
  $('.print_link').click(function() {
    window.print();
    return false;
  });
}

function initialize_export() {
  $("#export_options").dialog({title: "Export your reading list",
			       width: '550px',
			       autoOpen: false
				    });

  $(".export_link").click(function() {
      var bookbag_id = this.id;
      $.post("/reading_list/export/options/", {'bookbag_id': bookbag_id}, function(data) {
        $("#export_options").html(data);
	$("#export_options").dialog("open");      
      });	  
  });
   
}

function close_export_dialog()
{
       $("#export_options").dialog("close");
}

function initialize_email() {
  //Setup dialogs.  We have to do this because we want to be able to reopen them
  //which doesn't work well unless you create them with auto open false and then open
  //and close them.
  $("#email_bookbag").dialog({title: "Email your reading list",
				width: '550px',
				autoOpen: false
			      });

  $("#email_success").dialog({title:"Reading List Emailed",
			      buttons: {
			      OK: function() {
				  $(this).dialog('close');
			      }},
			      autoOpen:false});
  $("#email_fail").dialog({title:"Email Error",
			      buttons: {
			      OK: function() {
				  $(this).dialog('close');
			      }},
			      autoOpen:false});
			      
  $(".email_link").click(function() {
      var bookbag_id = this.id;
      $.post("/reading_list/email/", {'bookbag_id': bookbag_id}, function(data) {
        $("#email_bookbag").html(data);
	$("#email_form").ajaxForm({dataType:'json',
				       beforeSubmit:start_email_send,
				       success:email_sent				       
					});
	$("#email_bookbag").dialog('open');
      });
  });
  
 }

function start_email_send() {
  $("#email_bookbag").dialog("close");
}

function email_sent(data) {
  if (data.success) {
    $("#email_success").dialog('open');
  } else{
    $("#email_fail").dialog('open');
    }

}

