String.prototype.trim = function() { return this.replace(/(?:^\s+|\s+$)/g, ""); }

window.onresize = moveLoadingScreen;
window.onscroll = moveLoadingScreen;

var IsUserLoggedIn = false;

function fetchLowestPrice(bookID) {
// Remove string token from the beginning of the variable
  bookID = bookID.substr(1, bookID.length - 1);

  if(bookID != undefined) {
    var divToUpdate = document.getElementById('results-' + bookID);
	var comparisonType = 1;
	if(arguments.length > 2 && arguments[2]) comparisonType = 2;

    if(divToUpdate.innerHTML == '' || divToUpdate.innerHTML == '<img src="images/ajax-loading.gif">') ajax_loadContent('results-' + bookID, 'compare.php?id=' + bookID + '&t=' + comparisonType, '<img src="images/ajax-loading.gif">');
    else {
	  if(divToUpdate.style.display == 'block' || divToUpdate.style.display == '') divToUpdate.style.display = 'none';
      else divToUpdate.style.display = 'block';
    }
  }
}

function fetchPriceForSale(bookID) {
// Remove string token from the beginning of the variable
  bookID = bookID.substr(1, bookID.length - 1);

  if(bookID != undefined) {
    var divToUpdate = document.getElementById('results-' + bookID);
	var comparisonType = 1;
	if(arguments.length > 2 && arguments[2]) comparisonType = 2;

    if(divToUpdate.innerHTML == '' || divToUpdate.innerHTML == '<img src="images/ajax-loading.gif">') ajax_loadContent('results-' + bookID, 'compare_sell.php?id=' + bookID + '&t=' + comparisonType, '<img src="images/ajax-loading.gif">');
    else {
	  if(divToUpdate.style.display == 'block' || divToUpdate.style.display == '') divToUpdate.style.display = 'none';
      else divToUpdate.style.display = 'block';
    }
  }
}


function showLoadingScreen(textToShow) {
// Replace the text so that it shows the proper text
  if(textToShow == undefined) textToShow = 'Search';

  var textToSearch = document.getElementById('loading').innerHTML;
  textToSearch = textToSearch.replace(/SEARCH_WORD/g, textToShow);
  textToSearch = textToSearch.replace(/Search/g, textToShow);
  textToSearch = textToSearch.replace(/Comparison/g, textToShow);
  document.getElementById('loading').innerHTML = textToSearch;

  var loadingScreen = document.getElementById('loading');
  var sizeArray = getPageSize();
  var scrollArray = getPageScroll();
  
// The default size of the loading screen is 200 x 100 pixels
  var top = (scrollArray[1] + ((sizeArray[3] - 35 - 80) / 2) + 'px');;
  var left = (((sizeArray[0] - 20 - 200) / 2) + 'px');
  
  if(left < 0) left = 0;
  if(top < 0) top = 0;
  
// Position the loading screen at the center of the screen
  loadingScreen.style.top = top;
  loadingScreen.style.left = left;

// Show the loading screen
  loadingScreen.style.display = 'block';
  loadingScreen.style.visibility = 'visible';
}

function hideLoadingScreen()
{
  var loadingScreen = document.getElementById('loading');
  loadingScreen.style.visibility = 'hidden';
  loadingScreen.style.display = 'none';
}

function moveLoadingScreen()
{
	var loadingScreen = document.getElementById('loading');
	if(loadingScreen != undefined && loadingScreen.style.visibility == 'visible')
	{
	  var sizeArray = getPageSize();
	  var scrollArray = getPageScroll();
	  
	// The default size of the loading screen is 200 x 100 pixels
	  var top = (scrollArray[1] + ((sizeArray[3] - 35 - 80) / 2) + 'px');;
	  var left = (((sizeArray[0] - 20 - 200) / 2) + 'px');
	  
	  if(left < 0) left = 0;
	  if(top < 0) top = 0;
	  
	// Position the loading screen at the center of the screen
	  loadingScreen.style.top = top;
	  loadingScreen.style.left = left;
	}
}

function clearPreloadPage()
{
  if(document.getElementById) // DOM
  {
    document.getElementById('loading').style.visibility = 'hidden';
  }

  else
  {
    if(document.layers) //NS4
    {
      document.loading.visibility = 'hidden';
    }

    else //IE4
    {
      document.all.loading.style.visibility = 'hidden';
    }
  }
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Taken from Lokesh Dhakar - http://www.huddletogether.com (Lightbox project)
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Taken from Lokesh Dhakar - http://www.huddletogether.com (Lightbox project)
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function checkAdvancedSearchForm()
{
// If checking an ID is impossible, return true and validate server side.
	if(!document.getElementById('page')) return true;
	if(document.getElementById('BookTitle').value.trim() != '') return true;
	if(document.getElementById('BookAuthor').value.trim() != '') return true;
	if(document.getElementById('BookSubject').value.trim() != '') return true;
	if(document.getElementById('BookKeyword').value.trim() != '') return true;
	
	return false;
}

// Preload images
tempimg = new Image(220, 19);
tempimg.src = "images/ajax-loading.gif";

// jQuery ready
// When DOM is ready
$(document).ready(function() {
	if(!IsUserLoggedIn) {
		$("a.login_link").attr("href", "login_box.php");
		
		$("a.login_link").fancybox({
			centerOnScroll : true,
			overlayOpacity : 0.8,
			onComplete : show_recaptcha
		});
	} else {
		$("a.login_link").each(function(index, element) {
			// Change the login to logout to reflect the logged in status
			if("Login" == $(this).text()) {
				$(this).text("Logout");
				$(this).click(process_logout);
			// Bind the thumbs up/down processing
			} else $(this).click(process_thumb_action);
		});
	}
});

start_login = function() {
	var username = $("#login_email").val();
	var password = $("#login_password").val();
	
	// Check that the username and password exist
	if("" == username.trim()) $("#login_error_message").html("You must enter your email.");
	else if("" == password.trim()) $("#login_error_message").html("You must enter your password.");
	else {
		$("#login_submit_button").attr("enabled", "false");
		$("#login_loading").css("display", "block");
		// Check if the Captcha field is empty
		if("" == Recaptcha.get_response().trim()) $("#login_error_message").html("You must enter the words for the Captcha test.");
		else {
			password = $.sha1(password);

			$.post('login.php', {
					username : username,
					password : password,
					recaptcha_challenge_field : Recaptcha.get_challenge(),
					recaptcha_response_field : Recaptcha.get_response()
				}, function(data) {
					if('OK' == data) {
						$("#login_loading").css("display", "none");
						process_login();
						$("#login_error_message").text("Thanks for logging in!");
						window.setTimeout($.fancybox.close, 1200);
					} else {
						// Hide the progress bar
						$("#login_loading").css("display", "none");
						// Display error message
						$("#login_error_message").html(data);
						Recaptcha.reload();
					}
				}
			);
		}
	}
};

start_registration = function() {
	var email = $("#email").val();
	var email_repeat = $("#email_repeat").val();
	var password = $("#password").val();
	var password_repeat = $("#password_repeat").val();
	
	// Check that the username and password exist
	if("" == email.trim()) $("#login_error_message").html("You must enter your email.");
	else if("" == password.trim()) $("#login_error_message").html("You must enter your password.");
	else if(email != email_repeat) $("#login_error_message").html("The email and repeat email fields do not match.");
	else if(password != password_repeat) $("#login_error_message").html("The password and repeat password fields do not match.");
	else {
		// Check if the Captcha field is empty
		if("" == Recaptcha.get_response().trim()) $("#login_error_message").html("You must enter the words for the Captcha test.");
		else {
			$("#login_submit_button").attr("enabled", "false");
			$("#login_loading").css("display", "block");
			
			password = $.sha1(password);
			password_repeat = $.sha1(password_repeat);
	
			$.post('register.php', {
					email : email,
					email_repeat : email_repeat,
					password : password,
					password_repeat : password_repeat,
					recaptcha_challenge_field : Recaptcha.get_challenge(),
					recaptcha_response_field : Recaptcha.get_response()
				}, function(data) {
					if('OK' == data) {
						$("#login_loading").css("display", "none");
						process_registration();
						$("#login_error_message").text("Thanks for registering!");
						window.setTimeout($.fancybox.close, 1200);
					} else {
						// Hide the progress bar
						$("#login_loading").css("display", "none");
						// Display error message
						$("#login_error_message").html(data);
					}
				}
			);
		}
	}
};


process_login = function() {
	$("a.login_link").each(function(index, element) {
		$("a.login_link").attr("href", "");
		$(this).unbind('click');
		// Change the login to logout to reflect the logged in status
		if("Login" == $(this).text()) {
			$(this).text("Logout");
			$(this).click(process_logout);
		// Bind the thumbs up/down processing
		} else $(this).click(process_thumb_action);
	});
	
	IsUserLoggedIn = true;
}

process_registration = function () {
	$("a.login_link").each(function(index, element) {
		$("a.login_link").attr("href", "");
		$(this).unbind('click');
		// Change the login to logout to reflect the logged in status
		if("Login" == $(this).text()) {
			$(this).text("Logout");
			$(this).click(process_logout);
		// Bind the thumbs up/down processing
		} else $(this).click(process_thumb_action);
	});
	
	IsUserLoggedIn = true;
}

process_logout = function() {
	$.ajax('logout.php', {
		success : function(data) {
			// Logout was successful
			if('OK' == data) {
				// Change the text of links to "Login" and remove the logout event
				$("a.login_link").each(function(index, element) {
					$(this).unbind('click');
					if("Logout" == $(this).text()) $(this).text("Login");
				});

				// Put the fancybox link back in place so that the user can log in again
				$("a.login_link").attr("href", "login_box.php");

				$("a.login_link").fancybox({
					centerOnScroll : true,
					overlayOpacity : 0.8,
					onComplete : show_recaptcha
				});		

				// And finish with
				IsUserLoggedIn = false;
			}
		}
	});
	
	return false;
}

process_thumb_action = function() {
	var BookId = $(this).parent().attr("id").replace("thumbs-", "");
	var Action = 0;
	
	if(BookId.length > 0) {
		// Thumbs up was pressed
		if($(this).children("img.up").size() > 0) Action = 1;
		// Thumbs down was pressed
		else Action = -1;
		
		$.post('action.php', {
				a : 'evaluation',
				v : Action,
				id : BookId
			}, function(data) {
			// Remove the thumbs and display if the user likes the book or not
			if('OK' == data) {
				// The user likes the book
				if(Action > 0) {
					$("#thumbs-" + BookId).html("I <b>like</b> this book");
				// The user dislikes the book
				} else {
					$("#thumbs-" + BookId).html("I <b>don't like</b> this book");
				}
			} else if ('NO' == data) {
				alert('Your account needs to be validated.');
			}
		});
	}
	
	return false;
}

show_recaptcha = function() {
	Recaptcha.create('6LeZGMUSAAAAAOTRXKE1qWDRGSAYyE9pNS-SNm7H', 'login_captcha', {
		theme : 'clean',
		tabindex : 60
	});
}
