$(document).ready(function(){
    $('#searchTitle').keydown(function(event){
      switch (event.keyCode) {
      case 13:
	search_local_books_quick($('#fb').attr('fb'));
      }
    });

    $('#searchAuthor').keydown(function(event){
      switch (event.keyCode) {
      case 13:
	search_local_books_quick($('#fb').attr('fb'));
      }
    });

  });

function save_all_captions( trailID ){
  var captions = new Array();
  var i = 0, nextCaption, nextBookId;
  var n = getElementsByClass('bookCaption').length;

  
  var n = $('.bookCaption').length;
  $('.bookCaption').each(function(){
      var i = $(this).attr('n');
      var bookId = $(this).attr('bookID');

      save_caption(i, bookId, trailID, n);

    });

  if( n == 0 )
    {
	     save_basic_info( 'title', trailID);
	     update_title();
    }

}

function save_caption( j, bookID, trailID, n ){
  var bookDiv = document.getElementById('captionDiv'+j);
  var caption = encodeURIComponent(bookDiv.getElementsByTagName('textarea')[0].value);

   var httpObject = getHTTPObject();
   if(httpObject != null)
     {
       var link =  "save_book_caption.php?trailID=" + trailID + "&bookID=" + bookID + "&caption=" + caption;

       httpObject.open("GET", link, true);
        httpObject.onreadystatechange = function(){
	 if(httpObject.readyState == 4)
	   {
	     var response = httpObject.responseText;
	     //	     if(response != 'true')
	     //	       {
	     //	     		 alert(response);
	     //	       }

	     if( (n-1) == j )
	       {
		 save_book_order(trailID, 2);
	       }
	   }
	}

	httpObject.send(null);
     }
}

function save_book_order( trailID, radius){
  var allBooks = getElementsByClass('bookIconTrail');
  var s = '';
  var j = 0;
  for( var i=radius; i<allBooks.length - radius; i++)
    {
      s += 'id' + j + '=' + allBooks[i].getAttribute('bookID') + '&';
      j++;
    }

 var httpObject = getHTTPObject();
   if(httpObject != null)
     {
       var link =  "save_book_order.php?trailID=" + trailID + "&" + s;
       httpObject.open("GET", link, true);

       httpObject.onreadystatechange = function(){
	 if(httpObject.readyState == 4)
	   {
	     var response = httpObject.responseText;
	     //	     if(response != 'true')
	     //	       {
	     //		 alert(response);
	     //	       }
	     save_basic_info( 'title', trailID);

	     update_title();
	   }
       }

       httpObject.send(null);
     }
}


function move_book( trailID, bookID, direction, userID, radius ){
  save_message_save(trailID);
  var allBooks = getElementsByClass('bookIconTrail');
  if(direction=='left')
    inc = -1;
  else
    inc = 1;
  for( var i=0; i < allBooks.length; i++ )
    {
      if( allBooks[i].firstChild.className == 'focusIcon' && allBooks[i+inc].getAttribute('type') != 'spacer')
	{
	  if(direction == 'right')
	    var previousBook = allBooks[i+2];
	  else
	    var previousBook = allBooks[i-1];
	  var thisBook = allBooks[i];
	  thisBook.parentNode.removeChild(thisBook);
	  previousBook.parentNode.insertBefore(thisBook, previousBook);
	  if(direction == 'right')
	    advance_trail_back(trailID, userID, radius);
	  advance_trail_forward(trailID, userID, radius);
	  if(direction == 'left')
	    advance_trail_back(trailID, userID, radius);
	}
    }  
}

function remove_book( trailID, bookID, userID, radius  ){
  var link = "change_trail(" + trailID + ", \"" +  bookID + "\", \"remove_book_from_trail.php?trailID=" + trailID + "&bookID=" + bookID + "\", " + userID + ", " + radius + ", \"false\" )";
  popup("<p>Are you sure you want to remove this book?</p><p><a class='confirm jqmClose' onclick='" + link + "'>Yes</a> <a class='confirm jqmClose'>No</a></p>");
}

function change_trail( trailID, bookID, link, userID, radius, focus){
  var httpObject = getHTTPObject();
   if(httpObject != null)
     {
       httpObject.open("GET", link, true);
       httpObject.send(null);
       httpObject.onreadystatechange = function(){
	 if(httpObject.readyState == 4)
	   {
	     var response = httpObject.responseText;
	     if(response == 'true')
	       get_trail_body(trailID, userID, radius, focus, 'true', 'false', 'false');
	     //	     else
	     //	       alert(response);
	   }
       }
     }
}


function save_basic_info( infoName, trailID ){
  var infoField = document.getElementById(infoName);
  if(infoField)
    {
      var newValue = infoField.value;
      
      if(infoName=='anonymous' && infoField)
	if(infoField.checked)
	  newValue = 'on';
	else
	  newValue = '';
      var httpObject = getHTTPObject();
      
      if(httpObject != null)
	{
	  var link =  "save_trail_basic_info.php?trailID="+trailID+"&infoName=" + infoName + "&newValue=" + newValue;
	  
	  httpObject.open("GET", link, true);
	  httpObject.send(null);
	  httpObject.onreadystatechange = function(){
	    if(httpObject.readyState == 4)
	      {
		//	    if(httpObject.responseText != 'true')
		//	      alert(httpObject.responseText);
		
		if(infoName == 'title')
		  save_basic_info( 'description', trailID);
		
		if(infoName == 'description')
		  save_basic_info( 'anonymous', trailID);
		
		if(infoName == 'anonymous')
		  save_message_reset();
		
	      }
	  }
	}
    }
  else if(infoName == 'anonymous')
    save_message_reset();
}

function update_title(){
  var infoField = document.getElementById('title');
  var title = document.getElementById('trailTitleHeader');
  var newValue = infoField.value;
  title.innerHTML = newValue;
}


function save_all_basic_info( trailID ){
  save_message_saving();
  save_all_captions( trailID);
}

function save_message_reset(){
  $('#saveMessage').val('Saved').attr('disabled', true);
  window.onbeforeunload = null;
}

function save_message_saving(){
  $('#saveMessage').val('saving changes...').attr('disabled', true);
  window.onbeforeunload = function () { return 'There are unsaved changes to this trail.';};
}

function set_leave_delete(trailID){
    $(window).unload(function(){
	var link = 'delete_new_trail.php?id='+trailID;
	var httpObject = getHTTPObject();
	httpObject.open("GET", link, true);
	httpObject.send(null);
  });
}

    
function save_message_save(trailID){
  $('#saveMessage').val('Save now').attr('disabled', false).click(function(){
      save_all_basic_info(trailID);
    });
  window.onbeforeunload = function () { return 'You have made unsaved changes to this trail.' } 
}


function add_book_manually(trailID, fb){
  popupAjax("add_book_manually.php?trailID=" + trailID + "&width=420&height=360&fb="+fb);
}

function return_manual_book( fb ){
  var title = encodeURIComponent(document.getElementById('manualBookTitle').value);
  var author = encodeURIComponent(document.getElementById('manualBookAuthor').value);
  var publisher = encodeURIComponent(document.getElementById('manualBookPublisher').value);
  var isbn = encodeURIComponent(document.getElementById('manualBookIsbn').value);
  var trailID = encodeURIComponent(document.getElementById('manualBookTrailID').value);
  var userID = encodeURIComponent(document.getElementById('manualBookUserID').value);

  if(isbn == 'n/a'  || isbn == 'N/A')
    isbn='';
  create_book_manually(title, author, isbn, publisher, trailID, userID, 2, fb);
}

function create_book_manually(title, author, isbn, publisher, trailID, userID, radius, fb){ // 
  var link = "add_book_manually_create.php?title=" + title + "&author=" + author + "&isbn=" + isbn + '&publisher=' + publisher;

  var httpObject = getHTTPObject();
   if(httpObject != null)
     {
       httpObject.open("GET", link, true);
       httpObject.send(null);
       httpObject.onreadystatechange = function(){
	 if(httpObject.readyState == 4)
	   {
	     var newID = httpObject.responseText;

	     if(newID == 'failed')
	       {
		 var msg = document.getElementById('bookAddMsg');
		 msg.innerHTML = '<p><b>Error</b> Another book exists with that ISBN number.  If you believe this is an error, please email the site administrator.</p>';
	       }
	     else
	       {
		 $('#popup').jqmHide();
		 if(fb)
		   radius = 1;
		 return_book_id(trailID, newID, userID, radius, 'end', fb);
	       }
	   }
       }
     }
}

function cancel_changes(){
  window.reload;
}

function open_trail( checkbox ){
  if(checkbox.checked)
    $('#openMessage').slideDown('slow');
  else
    $('#openMessage').slideUp('slow');
}

function fb_feed( fb ){
  var user_message_prompt = "You created a new trail"; 
  var title = $('#title').val();
  var id = $('#trailID').val();
  var description = $('#description').val();
  var template_data = {"trail":title, "id":id, "description": description};
  var body_general = '';
  if(fb)
    var bundle = 64154503122;
  else
    var bundle = 80759991896;

  FB.Connect.showFeedDialog(bundle, template_data);
}
