
// select objects

$(document).ready(function(){
    $('.selectTag').mousedown(
			   function(){
			     $(this).addClass('hovering');
			   })
      .mouseup(function(){
	  $(this).selectMe();
	  $(this).removeClass('hovering');});
  });

// select-all button
$(document).ready(function(){
    $('#selectAll').click(function(){
	$('.selectTag').selectMe();
      });});

// select-none button
$(document).ready(function(){
    $('#selectNone').click(function(){
	$('.selectTag').unselectMe();});});

// select object

jQuery.fn.selectMe = function(){
  $(this).addClass('selected').unbind().mousedown(
			   function(){
			     $(this).addClass('selectedhovering');
			   })
      .mouseup(function(){
	  $(this).removeClass('selectedhovering');
	  $(this).unselectMe();
});
};

// un-select object

jQuery.fn.unselectMe = function (){
  $(this).removeClass('selected').unbind().mousedown(
			   function(){
			     $(this).addClass('hovering');
			   })
      .mouseup(function(){
	  $(this).selectMe();
	  $(this).removeClass('hovering');});
};

// make link with selected objects

jQuery.fn.appendId = function( link, key ){
  var i=0;

  $(this).each(function(){
       link += '&' + key + i + '=' + $(this).attr('objectId');
       i++;
    });
    return link;
}

// new trail with selected books

function new_trail_with_books(  ){
  var baseLink = "trail_edit.php?";
  var link = $('.selected').appendId(baseLink, 'b');

  if(link == baseLink )
    {
      popup('<p>Please select at least one book.</p>');
    }
  else
    {
      window.location = link;
    }
}


//////////// FRIENDS //////////////////


function add_friend(id1, id2){
  var httpObject = getHTTPObject();
  if(httpObject != null)
    {
      var link =  "save_friend_status.php?id1="+id1+"&id2="+id2;
      httpObject.open("GET", link, true);
      httpObject.send(null);
      httpObject.onreadystatechange =  function(){
	if(httpObject.readyState == 4)
	  {
	    var id2 = httpObject.responseText;

	    var div = document.getElementById('friend'+id2);
	    if(div)
	      {
		var p = getElementsByClass('friendFunction', div, 'p');
		div.innerHTML = "Request pending. <a href='write_message.php?rid=" + id2 + "'>Send message.</a>";
	      }
	  }
      }
    }
}
 

function confirm_friend(id1, id2){
  var httpObject = getHTTPObject();
  if(httpObject != null)
    {
      var link =  "save_friend_status.php?id1="+id1+"&id2="+id2;
      httpObject.open("GET", link, true);
      httpObject.send(null);
      httpObject.onreadystatechange = function(){
	if(httpObject.readyState == 4)
	  {
	    var id2 = httpObject.responseText;
	    var div = document.getElementById('friend'+id2);
	    var p = getElementsByClass('friendFunction', div, 'p');
	    div.innerHTML = "You are now friends.";
	  }
      }
    }  
}


function remove_friend(id1, id2){
  var httpObject = getHTTPObject();
  if(httpObject != null)
    {
      var link =  "remove_friend_status.php?id1="+id1+"&id2="+id2;
      httpObject.open("GET", link, true);
      httpObject.send(null);
      httpObject.onreadystatechange = function(){
	if(httpObject.readyState == 4)
	  {
	    var id2 = httpObject.responseText;
	    var div = document.getElementById('friend'+id2);
	    var p = getElementsByClass('friendFunction', div, 'p');
	    div.innerHTML = "Friendship removed.";
	  }
      }
    }
}



function deny_friend(id1, id2){

  httpObject = getHTTPObject();
  if(httpObject != null)
    {
      var link =  "remove_friend_status.php?id1="+id1+"&id2="+id2;
      httpObject.open("GET", link, true);
      httpObject.send(null);
      httpObject.onreadystatechange = function(){
	if(httpObject.readyState == 4)
	  {
	    var id2 = httpObject.responseText;
	    var div = document.getElementById('friend'+id2);
	    var p = getElementsByClass('friendFunction', div, 'p');
	    div.innerHTML = "Friendship declined.";
	  }
      }
    }
}

 
 
function add_selected_friends(id){
  $('.selected').each(function(){
      if($(this).attr('friendStatus') == 0)
	add_friend( id, $(this).attr('objectId'));
    });
}

function confirm_selected_friends(id){
  $('.selected').each(function(){
      if($(this).attr('friendStatus') == 1)
	confirm_friend( id, $(this).attr('objectId'));
    });
}

function remove_selected_friends(id){
  $('.selected').each(function(){
      if($(this).attr('friendStatus') == 2)
	remove_friend( id, $(this).attr('objectId'));
    });
}


function message_selected_people( target ){
  var baseLink =  "write_message.php?";
  var link = $('.selected').appendId(baseLink, 'rid');

  if( link == baseLink )
    popup("<p>Please select at least one person.</p>");
  else
    {
      if(target == 'new')
	window.open(link);
      else
	window.location = link;
    }
}



function trail_status( userID, trailID ){
  var select = document.getElementById('trailStatus' + trailID );
  var index = select.selectedIndex;
  var newStatus;
  if(index == 0)
    newStatus = 'not saved';
  if(index == 1)
    newStatus = 'saved';
  if(index == 2)
    newStatus = 'traveling';
  if(index == 3)
    newStatus = 'completed';
  change_trail_status(trailID, userID, newStatus);

}

function change_trail_status( trailID, userID, newStatus){

  var link = "save_trail_status.php?trailID=" + trailID + "&userID=" + userID + "&newStatus=" + newStatus;

  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')
	    //	      alert(response);
	  }
      }
    }
}

function select_status_trails( status ){
      var selects = document.getElementById('searchResults').getElementsByTagName('select');
    var rows = document.getElementById('searchResults').getElementsByTagName('tr');
  var IDs = new Array();
  var j = 0;
  for( var i=0; i<selects.length; i++)
    {
      if(selects[i].selectedIndex == status)
	{
	  IDs[j] = selects[i].getAttribute('trailID');
	  j++;
	}
    }

  for( var i=0; i<rows.length; i++)
    {
      if(IDs.indexOf(rows[i].id) >= 0)
	{

	  buttonP = rows[i].getElementsByTagName('input');
	  if(buttonP.length > 0)
	    {
	      button = buttonP[0];
	      button.checked = true;
	      rows[i].style.backgroundColor = '#eeeeff';
	    }
	}
    }  
}


function mark_selected_trails_as( userID ){
  var selectedRows = get_selected_rows();
  var newStatus = document.getElementById('trailStatusChange').selectedIndex;
  if(newStatus != 0)
    {
      var selectField;
      for( var i=0; i<selectedRows.length; i++)
	{
	  selectField = selectedRows[i].getElementsByTagName('select')[0];
	  selectField.selectedIndex = (newStatus - 1);
	  var trailID = selectedRows[i].id;
	  change_trail_status(trailID, userID, newStatus-1);
	}
    }
}

// SEND SELECTED TRAILS

$(document).ready(function(){
    $('#sendSelectedTrails').click(function(){
	oldLink = 'email_trail.php?';
	var link = $('.selected').appendId(oldLink, 't');
	if( link == oldLink )
	  popup("<p>Please select at least one trail to share.</p>");
	else
	    popupAjax(link);
      });});




function resize_book_images(){
  var bookImages = getElementsByClass('bookImage', document);
  var image;
  for( var i=0; i<bookImages.length; i++)
    {
      image = bookImages[i].getElementsByTagName('img')[0];
    }
}


/********************** TAGS **********************/

function search_results_by_tag(type){
  var select = document.getElementById('resultsTags');
  var index = select.selectedIndex;
  if(index == 0)
    {
      var inputs = document.getElementsByTagName('input');
      var hiddens = new Array();
      var j=0;
      for( var i=0; i<inputs.length; i++)
	if(inputs[i].getAttribute('type') == 'hidden')
	  {
	    hiddens[j] = inputs[i];
	    j++;
	  }
      var link = "search.php?";
      for( var i=0; i<hiddens.length; i++)
	{
	  if(hiddens[i].value != '' && hiddens[i].name.substr(1) != 'Spttag' && hiddens[i].name.substr(1) != 'Sbptag')
	    link += hiddens[i].name.substr(1) + "=" + hiddens[i].value + "&";
	}

      window.location = link;
    }
  else
    {
      var tag = select.options[index].value;
      var inputs = document.getElementsByTagName('input');
      var hiddens = new Array();
      var j=0;
      for( var i=0; i<inputs.length; i++)
	if(inputs[i].getAttribute('type') == 'hidden')
	  {
	    hiddens[j] = inputs[i];
	    j++;
	  }

      var link = "search.php?";
      for( var i=0; i<hiddens.length; i++)
	{
	  if(hiddens[i].value != '' && hiddens[i].name != 'Spttag' && hiddens[i].name != 'Sbptag')
	    link += hiddens[i].name.substr(1) + "=" + hiddens[i].value + "&";
	}
      if(type == 'trail')
	link += "Spttag=";
      else if(type == 'book')
	link += "Sbptag=";
      link += tag;
      window.location = link;
    }
}



function remove_from_saved_books( bookID, remove ){
  var message = "<p>Are you sure you want to remove this book from all categories? </p><p>(If so, it will not appear in Your Books any more.)</p><p class='options'><a onclick=\"remove_from_saved_books_go('" + bookID + "', " + remove + "); close_box();\" class='option'>Yes</a> <a class='option' onclick='close_box();'>No</a></p>";
  popup(message);
}

function remove_from_saved_books_go( bookID, remove ){
  var link = "remove_from_saved_books.php?bookID=" + bookID;
  
  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')
		//		  alert(response);
		//else 
		if(remove)
		  {
		    var book = document.getElementById('book'+bookID);
		    book.parentNode.removeChild(book);
		  }
	      }
	  }
	}
}


function add_in_amazon_search_results( j, count ){
  var results;

  if( results = document.getElementById('amazonResults'))
    {
      results.innerHTML = "<p>Searching for more results...</p>";
      var authorN = document.getElementById('amazonAuthor');

      if(authorN)
	{
	  var author = authorN.getAttribute('value') ;
	  var title = document.getElementById('amazonTitle').getAttribute('value');
	  var query = document.getElementById('amazonQuery').getAttribute('value');
	  var link = "search_page_results_amazon.php?search=books&author="+author+"&title="+title+"&query="+query + "&j=" + j + "&count=" + count;

	  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 == '0')
		      {
			if($('.resultsCounter').eq(0).attr('count') == '0')
			  results.innerHTML = '<p>There were no matching books.</p>';
		      }
		    else
		      {
			var rcount = $('.resultsCounter');
			if(rcount.eq(0).attr('count') == '0')
			  rcount.eq(0).html('More results');
			else
			  rcount.html(rcount.html() + ' + more');
			results.innerHTML = response;
			$('.selectTag').mousedown(
						  function(){
						    $(this).addClass('hovering');
						  })
			.mouseup(function(){
			    $(this).selectMe();
			    $(this).removeClass('hovering');});
		      }
		  }
	      }
	    }
	}
    }
}

function show_tags(){
  $('.tags').show();
  $('.showTags').hide();
  $('.hideTags').show();
}

function hide_tags(){
  $('.tags').hide();
  $('.hideTags').hide();
  $('.showTags').show();
}
