$('document').ready(function(){

	// Navigation items that you want to be "anchors" with subpages, but not active as links.

	var anchors = new Array("Books", "Speaking", "For Readers", "About Tricia");
	
	$(anchors).each(function(){
		$('a:contains('+this+')').attr('href', '#').click(function(e){
			e.preventDefault();
		});
	});


	// Extra layer of coercion to force the "Blog" link to go to the blog url

	$('a:contains("Blog")').attr('href', 'http://triciagoyer.blogspot.com/');


	// Bookslider

	$('#bookslider').css('overflow','hidden');	// Overflow is hidden instead of showing a scroll bar
	
	var duration = 10000;	// Auto-advance delay in milliseconds
	var speed = 800;		// Animated movement duration in milliseconds
	var position = 0;		// Starting position of the slider
	var slide1 = 0;			// Slide 1 position
	var slide2 = -854;		// Slide 2 position
	var slide3 = -1708;		// Slide 3 position

	$('#sliderleft').animate({ opacity: '0.5' }, 200, 'swing');	// Left button starts out "disabled"
	$('#sliderright').animate({ opacity: '1' }, 200, 'swing');	// Right button starts out "enabled"

	// Checks the current position and enables or disables the left and right button as needed
	function buttonStatus(){
		// Check status of left button
		if ( position >= slide1 ){
			$('#sliderleft').animate({ opacity: '0.5' }, 200, 'swing');
		} else {
			$('#sliderleft').animate({ opacity: '1' }, 200, 'swing');
		}

		// Check status of right button
		if ( position <= slide3 ){
			$('#sliderright').animate({ opacity: '0.5' }, 200, 'swing');
		} else {
			$('#sliderright').animate({ opacity: '1' }, 200, 'swing');
		}
	}

	// Click event for the left button
	$('#sliderleft').click(function(e){

		// If in the Slide 1 position
		if ( position >= slide1 ){
			position = slide1;				// Keep position at Slide 1
			$('#bookholder').animate(		// Move slider (shouldn't be necessary, but just in case something got out of whack)
				{ left: position },
				speed,
				'swing'
			);
		}
		
		// Else if in the Slide 2 position
		else if ( position < slide1 && position >= slide2 ) {
			position = slide1;				// Set position to Slide 1
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		// Else if in the Slide 3 position
		else if ( position < slide2 ) {
			position = slide2;				// Set position to Slide 2
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		buttonStatus();		// Check position and set status of buttons

		e.preventDefault();	// Prevent hyperlink action of the button
	});

	// Click event for the right button
	$('#sliderright').click(function(e){

		// If in the Slide 1 position
		if ( position >= slide1 ){
			position = slide2;				// Set position to Slide 2
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		// Else if in the Slide 2 position
		else if ( position < slide1 && position >= slide2 ) {
			position = slide3;				// Set position to Slide 3
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		// Else if in the Slide 3 position
		else if ( position < slide2 ) {
			position = slide3;				// Keep position at Slide 3 
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		buttonStatus();		// Check position and set status of buttons

		e.preventDefault();	// Prevent hyperlink action of the button
	});

	function advance(){

		// If in the Slide 1 position
		if ( position >= slide1 ){
			position = slide2;				// Set position to Slide 2
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		// Else if in the Slide 2 position
		else if ( position < slide1 && position >= slide2 ) {
			position = slide3;				// Set position to Slide 3
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		// Else if in the Slide 3 position
		else if ( position < slide2 ) {
			position = slide1;				// Set position to Slide 1
			$('#bookholder').animate(		// Move slider
				{ left: position },
				speed,
				'swing'
			);
		}

		buttonStatus();		// Check position and set status of buttons
	}
	

	var interval = setInterval(advance, duration);	// Call slideShow() at the interval set in duration

	$('#bookslider').mouseenter(function(){
		clearInterval(interval);					// Stop auto-advance when the mouse enters the slider
	});

	$('#bookslider').mouseleave(function(){
		interval = setInterval(advance, duration);	// Restart auto-advance when the mouse leaves the slider
	});

	// End Bookslider


	// Set current year in copyright.
	var now=new Date();
	var year=now.getFullYear();
	$('#currentYear').html(year);

	// Print when a link with the class "print" is clicked.
	$('.print').click(function(){
		window.print();
		return false;
	});

	// Buy This Book tooltip.
	var buyBook = new BookList("buythisbook/xml/data.xml", "bookPane");
	buyBook.GetBookList();
	$('a.buythisbook').click(function(e){
		var bookID = $(this).attr('id');
		buyBook.PopValues(this,bookID);
		e.preventDefault();

		// Add event listener to the close button.
		$('a#closebutton').click(function(e){
			buyBook.Close();
			e.preventDefault();
		});
	});

});

// XML parsing function needed for the Buy This Book tooltip.
function Xml()
{
     this.SendRequest = function(url, callback, postData)
     {
          var req = createXMLHTTPObject();
          if (!req) return;
          
          var method = (postData) ? "POST" : "GET";
          req.open(method, url, true);
          req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
          
          if (postData)
          {
               req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
          }
          
          req.onreadystatechange = function()
          {
               if (req.readyState != 4) return;
               if (req.status != 200 && req.status != 304)
               {
                    //alert('HTTP error ' + req.status);
                    return;
               }
               callback(req);
          }
          if (req.readyState == 4) return;
          req.send(postData);
     }

     var XMLHttpFactories = [
          function() { return new XMLHttpRequest() },
          function() { return new ActiveXObject("Msxml2.XMLHTTP") },
          function() { return new ActiveXObject("Msxml3.XMLHTTP") },
          function() { return new ActiveXObject("Microsoft.XMLHTTP") }
     ];

     function createXMLHTTPObject()
     {
          var xmlhttp = false;
          for (var i = 0; i < XMLHttpFactories.length; i++)
          {
               try
               {
                    xmlhttp = XMLHttpFactories[i]();
               }
               catch (e)
               {
                    continue;
               }
               break;
          }
          return xmlhttp;
     }

}

// Functions for the Buy This Book tooltip.
function BookList(url)
{
     var imagepath = "buythisbook/images";
     var xml = null;
     var isReady = false;
     var requestTimer = null;
     var books = new Array();
     var pane;
     var tmpAnchor;
     var tmpId;
     var lightboxback;

     this.GetBookList = function()
     {
          var xmlLoader = new Xml();
          xmlLoader.SendRequest(url, handleRequest);
          requestTimer = window.setTimeout(processXml, 1000);
     }

     function handleRequest(req)
     {
          xml = req.responseXML;
     }

     function processXml()
     {
          if (xml == undefined)
          {
               requestTimer = window.setTimeout(processXml, 100);
          }
          
          var bookNodes = xml.getElementsByTagName("book");
          for (x = 0; x < bookNodes.length; x++)
          {
               var book = new Book();
               var id = bookNodes[x].getAttribute("id");
               book.Id = id;
               book.Title = bookNodes[x].getAttribute("title");
               book.ThumbNail = bookNodes[x].getAttribute("thumbnail");
               books[id] = book;
               
               var linkNodes = bookNodes[x].getElementsByTagName("booklink");
               for (y = 0; y < linkNodes.length; y++)
               {
                    var link = new Link();
                    var linktxt = "";
                    link.Vendor = linkNodes[y].getAttribute("vendor");
                    link.Link = linkNodes[y].childNodes[0].nodeValue;

                    if (window.ActiveXObject)
                    {
                         linktxt = linkNodes[y].childNodes[0].nodeValue.Trim();
                    }
                    else
                    {
                         linktxt = linkNodes[y].childNodes[1].data.Trim();
                    }

                    link.Link = linktxt;
                    book.Links[link.Vendor] = link;
               }
          }
          isReady = true;
     }

     this.SubmitSearch = function(action)
     {
          var city = document.getElementById("city");
          var state = document.getElementById("state");
          var zip = document.getElementById("zip");

          if (city.value == "City") city.value = "";
          if (state.value == "State") state.value = "";
          if (zip.value == "Zip") zip.value = "";

          var url = action + "?q=bookstore&near=" + city.value + "+" + state.value + "+" + zip.value;

          window.open(url, "", "");

          return false;
     }

     this.Blur = function(input)
     {
          if (input.value == "")
          {
               switch (input.id)
               {
                    case "city":
                         input.value = "City";
                         break;
                    case "state":
                         input.value = "State";
                         break;
                    case "zip":
                         input.value = "Zip";
                         break;
               }
          }
     }

     this.Focus = function(input)
     {
          switch (input.id)
          {
               case "city":
                    if (input.value == "City") input.value = "";
                    break;
               case "state":
                    if (input.value == "State") input.value = "";
                    break;
               case "zip":
                    if (input.value == "Zip") input.value = "";
                    break;
          }
     }

     this.PopValues = function(anchor, id)
     {
          if (!isReady || id != undefined)
          {
               if (pane == undefined)
               {
                    pane = document.getElementById("bookPaneContainer");
               }

               var bookTitle = "";
               var bookThumb = "";
               var bookAnchor_amazon_href = "";
               var bookAnchor_barnes_href = "";
               var bookPane_booksamillion_href = "";
               var bookPane_indiebound_href = "";
               var bookPane_christianbook_href = "";

               var book = books[id];
               if (book != undefined)
               {
                    bookTitle = book.Title;
                    bookThumb = book.ThumbNail;

                    var link_amazon = book.Links["amazon"];
                    var link_barnes = book.Links["barnes"];
                    var link_booksamillion = book.Links["booksamillion"];
                    var link_indiebound = book.Links["indiebound"];
                    var link_christianbook = book.Links["christianbook"];

                    if (link_amazon != undefined) bookAnchor_amazon_href = link_amazon.Link;
                    if (link_barnes != undefined) bookAnchor_barnes_href = link_barnes.Link;
                    if (link_booksamillion != undefined) bookPane_booksamillion_href = link_booksamillion.Link;
                    if (link_indiebound != undefined) bookPane_indiebound_href = link_indiebound.Link;
                    if (link_christianbook != undefined) bookPane_christianbook_href = link_christianbook.Link;

                    _getLightboxBack();
                    lightboxback.style.display = "block";
                    pane.style.display = "block";
               }
               else
               {
                    //alert("Book not found.");
               }
          }

          var htmlSource = '<b class="bookPane">' +
                    '<b class="bookPane1"><b></b></b>' +
                    '<b class="bookPane2"><b></b></b>' +
                    '<b class="bookPane3"></b>' +
                    '<b class="bookPane4"></b>' +
                    '<b class="bookPane5"></b></b>' +
                    '<div id="bookPaneBackground">' +
                         '<div id="bookPane">' +
                              '<div id="bookPane_header"><p>Buy This Book:</p><a href="" id="closebutton">X</a></div>' + // Javascript taken out of href because we're using jQuery now.
                              '<div id="bookPane_imgbox">' +
                                   '<div id="bookPane_thumbnail" style="float: left;">' +
                                        '<img src="' + bookThumb + '" id="bookPane_thumbnail_image" alt="' + bookTitle + '" />' +
                                   '</div>' +
                                   '<div id="bookPane_logos" style="float: left;">' +
                                        '<a href="' + bookAnchor_amazon_href + '" id="bookPane_amazon" target="_blank"><img src="' + imagepath + '/buythisbook_logo_amazon.gif" /></a>' +
                                        '<a href="' + bookAnchor_barnes_href + '" id="bookPane_barnes" target="_blank"><img src="' + imagepath + '/buythisbook_logo_barnsnoble.gif" /></a>' +
                                        '<br />' +
                                        '<a href="' + bookPane_booksamillion_href + '" id="bookPane_booksamillion" target="_blank"><img src="' + imagepath + '/buythisbook_logo_booksamillion.gif" /></a>' +
                                        '<a href="' + bookPane_indiebound_href + '" id="bookPane_indiebound" target="_blank"><img src="' + imagepath + '/indieboundlogo.jpg" /></a>' +
                                        '<br />' +
                                        '<a href="' + bookPane_christianbook_href + '" id="bookPane_christianbook" target="_blank"><img src="' + imagepath + '/buythisbook_logo_christianbook.gif" /></a>' +
                                   '</div>' +
                                   '<div style="clear: all;"></div>' +
                              '</div>' +
                              '<div id="bookPane_searchheader"><p>Find a Local Bookstore:</p></div>' +
                              '<form action="http://maps.google.com/maps" onsubmit="return buyBook.SubmitSearch(this.action);">' +
                                   '<div style="text-align: center;">' +
                                        '<input type="hidden" name="q" value="christian bookstore" />' +
                                        '<input type="text" id="city" value="City" name="city" size="20" onfocus="buyBook.Focus(this)" onblur="buyBook.Blur(this)" />,' +
                                        '<input type="text" id="state" value="State" name="state" size="2" onfocus="buyBook.Focus(this)" onblur="buyBook.Blur(this)" maxlength="2" />' +
                                        '<input type="text" id="zip" value="Zip" name="zip" size="5" onfocus="buyBook.Focus(this)" onblur="buyBook.Blur(this)" maxlength="5" /><br />' +
                                        '<input type="image" src="' + imagepath + '/buythisbook_button_findstore.gif" />&nbsp;&nbsp;<img src="' + imagepath + '/buythisbook_logo_google.gif" />' +
                                   '</div>' +
                              '</form>' +
                         '</div>' +
                    '</div>' +
                    '<b class="bookPane">' +
                    '<b class="bookPane5"></b>' +
                    '<b class="bookPane4"></b>' +
                    '<b class="bookPane3"></b>' +
                    '<b class="bookPane2"><b></b></b>' +
                    '<b class="bookPane1"><b></b></b></b>';

          pane.innerHTML = htmlSource;

          _setPaneLocation(anchor);
          return false;
     }
     
     this.Close = function()
     {
          if (pane == undefined)
          {
               pane = document.getElementById("bookPaneContainer");
          }
          _getLightboxBack();
          lightboxback.style.display = "none";
          pane.style.display = "none";
     }
     
     function _setPaneLocation(obj)
     {
          if (pane == undefined)
          {
               pane = document.getElementById("bookPaneContainer");
          }
          var coords = _getObjectPosition(obj);
          
          pane.style.left = coords.x + "px";
          pane.style.top = (coords.y + 20) + "px";
     }

     function _getObjectPosition(obj)
     {
          var useWindow = false;
          var coordinates = new Object();
          var x = 0;
          var y = 0;

          x = _getPageOffsetLeft(obj);
          y = _getPageOffsetTop(obj);
          
          coordinates.x = x;
          coordinates.y = y; 
          return coordinates;
     }

     function _getObjectWindowPosition(obj)
     {
          var coordinates = _getObjectPosition(obj);
          var x = 0;
          var y = 0;
          if (document.getElementById)
          {
               if (isNaN(window.screenX))
               {
                    x = coordinates.x - document.body.scrollLeft + window.screenLeft;
                    y = coordinates.y - document.body.scrollTop + window.screenTop;
               }
               else
               {
                    x = coordinates.x + window.screenX + (window.outerWidth - window.innerWidth) - window.pageXOffset;
                    y = coordinates.y + window.screenY + (window.outerHeight - 24 - window.innerHeight) - window.pageYOffset;
               }
          }
          else if (document.all)
          {
               x = coordinates.x - document.body.scrollLeft + window.screenLeft;
               y = coordinates.y - document.body.scrollTop + window.screenTop;
          }
          coordinates.x = x;
          coordinates.y = y;
          return coordinates; 
     }

     function _getLightboxBack()
     {
          if (lightboxback == undefined)
          {
               lightboxback = document.createElement("div");
               lightboxback.setAttribute("id", "bookPaneLightboxBack");
               document.body.appendChild(lightboxback);
          }
          else
          {
               lightboxback = document.getElementById("bookPaneLightboxBack");
          }
     }
     
     function _getPageOffsetLeft(el)
     {
          var ol = el.offsetLeft;
          while ((el = el.offsetParent) != null)
          {
               ol += el.offsetLeft;
          }
          return ol;
     }

     function _getWindowOffsetLeft(el)
     {
          return _getPageOffsetLeft(el) - document.body.scrollLeft;
     }

     function _getPageOffsetTop(el)
     {
          var ot = el.offsetTop;
          while ((el = el.offsetParent) != null)
          {
               ot += el.offsetTop;
          }
          return ot;
     }

     function _getWindowOffsetTop(el)
     {
          return _getPageOffsetTop(el) - document.body.scrollTop;
     }
}

function Book()
{
     this.Id = 0;
     this.Title = "";
     this.ThumbNail = "";
     this.Links = new Array();
}

function Link()
{
     this.Vendor = "";
     this.Link = "";
}

String.prototype.Trim = function()
{
     return this.replace(/^\s+|\s+$/g, "");
}
