/*----------------------------------------------
* JS of Ruby Ranch
* Author: Jordan Burnett
* Created: November 30th, 2008
-----------------------------------------------*/
var maxAnimalsPerPage = 4;	//The maximum number of animals to be displayed per page. Should be a final variable

//Draws each animal from the animalList.xml file
function drawAnimals(pageNumber){
	$.ajax({ 
		type: "GET",
		url: "../xml/animalList.xml", //Needs to be changed to ../xml/animalList.xml when uploaded
		datatype: "xml", 
		success: function(xml){
				var animalPane = $("#animalImages");	//The pane in which to display the animals.
				var animalXML = $(xml).find("animal");	//The root of the animalList.xml file
				var pageMaxNumber = 0;					//The number of animals to be displayed on the paneNumber
				var isMoreAnimals = true;				//True if there are more pages after this one
				var isLessAnimals = true;				//True if there are more pages before this one

				//Clear the current animalPane
				$("#animalImages > *").remove();

				//Find how many animals should be drawn for the current page
				if ((pageNumber + 1) * maxAnimalsPerPage > animalXML.length)
				{
					isMoreAnimals = false; //There are no more animals to be drawn after this page
					pageMaxNumber = animalXML.length - (pageNumber * maxAnimalsPerPage);
				}
				else
				{
					pageMaxNumber = maxAnimalsPerPage;
				}

				//If the last animal is already going to be drawn on the page, do not make a link for 'more' animals to be drawn
				if (pageNumber * maxAnimalsPerPage + pageMaxNumber == animalXML.length)
				{
					isMoreAnimals = false;
				}
				
				//Find if there are any less animals to draw
				if (pageNumber == 0)
				{
					isLessAnimals = false;
				}
				
				//Find lower and upper range of display
				var lowerRange = pageNumber * maxAnimalsPerPage;
				var upperRange = (pageNumber * maxAnimalsPerPage) + pageMaxNumber;

				//Draw out the anchors if there are more/less animals at the bottom of the pane. Give the anchors appropriate function calls
			$(animalPane).append("<div class='dispMorePigs'>");  //Begin dispMorePigs DIV
			if (isLessAnimals)
			{
				var lessPageNumber = pageNumber - 1;
				$(".dispMorePigs").append(
					"<a onClick='drawAnimals(" + lessPageNumber + ")' class='lessAnimals'><< Click to see More Animals</a>"	
				);
			}

			if (isMoreAnimals)
			{
				var morePageNumber = pageNumber + 1;
				$(".dispMorePigs").append(
					"<a onClick='drawAnimals(" + morePageNumber + ")' class='moreAnimals'>Click to see More Animals >></a>"	
				);
			}
			$(animalPane).append("</div>");  //end dispMorePigs DIV

				//Prints a certain number of animals on the "animal" pane
				for (var i = lowerRange ; i < upperRange ; i++ )
				{
					//Get all the information about the animal
					var animal = animalXML[i];
					var animalName = $(animal).find("animalName").text();
					var pictureURL = $(animal).find("picture").text();
					var smallPicURL = $(animal).find("smallPic").text();
					if (smallPicURL.valueOf() == "")
					{
						smallPicURL = pictureURL;
					}
					var animalDescription = $(animal).find("animalDescription");

					//Post that information into the document
					var toAppend = "";
					toAppend += "<div class='animalInfo'>" +
						"<span class='animalName'>" + animalName + "</span><br />";
					
					for (var x = 0 ; x < animalDescription.length ; x++ )
					{
						var descToPrint = animalDescription[x];
						toAppend += "<span class='animalDescription'>" + $(descToPrint).text() + "</span><br />";
					}
					toAppend += "</div>" +
						"<div class='animalPic'>" + //Note that href='' must be change to /img/animals before uploading
						"<span class='picture'><a href='/img/animals/" + pictureURL + "' rel='lightbox' title='" + animalName + "'><img src='img/animals/" + smallPicURL + "' height='160px' width='120px' /></a></span><br />" + 
						"</div>";

					$(animalPane).append(
						"<div class='animalDiv'>" + toAppend
					);
					
					$(animalPane).append("</div>");

					var pictureSpan = $(".picture");
					var pictureSpanImgs = $(".picture > a");

					$(pictureSpanImgs).lightBox();

				} //End for loop

			//Draw out the anchors if there are more/less animals at the bottom of the pane. Give the anchors appropriate function calls
			$(animalPane).append("<div class='dispMorePigs'>");  //Begin dispMorePigs DIV
			if (isLessAnimals)
			{
				var lessPageNumber = pageNumber - 1;
				$(".dispMorePigs:last").append(
					"<a onClick='drawAnimals(" + lessPageNumber + ")' class='lessAnimals'><< Click to see More Animals</a>"	
				);
			}

			if (isMoreAnimals)
			{
				var morePageNumber = pageNumber + 1;
				$(".dispMorePigs:last").append(
					"<a onClick='drawAnimals(" + morePageNumber + ")' class='moreAnimals'>Click to see More Animals >></a>"	
				);
			}
			$(animalPane).append("</div>");  //end dispMorePigs DIV
			},//End of success: function
		error: function (XMLHttpRequest, textStatus, errorThrown){
				alert("There has been an error loading the piglets. This will be fixed soon!" );
			}//End of error: function
	});//End of $.ajax();
};

$(document).ready(function(){
	drawAnimals(0);

	var popupCookie = get_cookie( "PopupAgain" );
	
	//Function for checking a cookie and displaying a popup
	/*
	$(function(){
		if (popupCookie != "false")
		{
			var arrPageSizes = getPageSizeJB();

			$('body').append('<div id="jquery-overlay"></div>');
			$('body').append('<div id="popup"><a id="popupClose"></a></div>');
			$('#jquery-overlay').css({
					backgroundColor:	'#000000',
					opacity:			0.8,
					width:				arrPageSizes[0],
					height:				arrPageSizes[1]
			}).fadeIn();

			
			$("#popup").fadeIn("slow",function() {

				$("#popup").click(function(){
					$("#popup").hide();
					$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); } , function() { $('#jquery-overlay').remove(); });	
				});
				$("#popupClose").click(function() {
					var d = new Date();
					d.setDate(d.getDate() + 3);
					var cookieString = "PopupAgain=" + escape("false") + "; expires=" + d.toUTCString() + ";"; 
					document.cookie = cookieString;
				});
			});	//End FadeIn callback
		}	//End IF statement
	});
	*/

	//Applying lightbox to images
	$(function(){
		$("#animalImages > a").lightBox();
	});

	//OnClick event for expanding panes
	$(".paneTitle").click(function () {
		var paneClicked = $(this);
		var paneContentArray = $(".paneContent");  //This is the small blurb seen on each pane.
		var paneTitleArray = $(".paneTitle");  //This is where the user clicks
		var paneHiddenContent = $(".hiddenContent"); //The hidden elements that need to be shown
		var paneNumClicked = null;
		
		//Figure out which paneTitle the user clicked.
		for (var i = 0 ; i < paneTitleArray.length ; i++ )
		{
			var testElement = $(paneTitleArray[i]);
			if (testElement.text() == paneClicked.text())
			{
				paneNumClicked = i;
			}
		}

		//Toggle the display of the hidden content
		var showPane = $(paneHiddenContent[paneNumClicked]);
		var titleToChange = $(paneTitleArray[paneNumClicked]);
		var anchorTitleArray = $(".paneTitle > a");
		var anchorToChange = $(anchorTitleArray[paneNumClicked]);  //Click for more/less anchor
		if (showPane.is(":hidden"))
		{
			showPane.slideDown(1000, function(){
				var textToShowArray = $(".hiddenContent");
				var textToShow = textToShowArray[paneNumClicked];
				$(textToShow).show(1000);	
			});
		}
		else{
			var textToShowArray = $(".hiddenContent");
			var textToShow = textToShowArray[paneNumClicked];
			$(textToShow).hide(1000, function(){
				showPane.slideUp(1000);		
			});
		}
	
		//Toggles the 'click for more' anchor per each pane
		if (anchorToChange.text().search("Click for more") >= 0)
		{
			$(anchorToChange).html("Click for less");
		}
		else
		{
			anchorToChange.html("Click for more");
		}	
	});
});

// ================================== 
// Cleartype fade fix by Mike Alsup

jQuery.fn.fadeIn = function(speed, callback) { 
     return this.animate({
          opacity: 'show' }, speed, function() { 
               if (jQuery.browser.msie) 
                    this.style.removeAttribute('filter'); 
               if (typeof callback == 'function') 
                    callback();
     }); 
};

jQuery.fn.fadeOut = function(speed, callback) { 
     return this.animate({
           opacity: 'hide' }, speed, function() { 
               if (jQuery.browser.msie) 
                    this.style.removeAttribute('filter'); 
               if (typeof callback == 'function') callback();
     }); 
}; 

jQuery.fn.fadeTo = function(speed,to,callback) { 
     return this.animate({opacity: to }, speed, function() { 
          if (to == 1 && jQuery.browser.msie) 
               this.style.removeAttribute('filter'); 
          if (typeof callback == 'function') callback(); 
     }); 
};

function getPageSizeJB() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		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
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			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 = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

function get_cookie ( cookie_name )
{
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results )
		return ( unescape ( results[2] ) );
	else
		return null;
}
