/***********************************DOCUMENT READY****************************************/ 
	$(function() {
	
/****************HOVER EFFECT ON CONTACT PAGE ***********************/	

		//Looks for the #formTop id with a class of .input-bg (which exsists in the contact.php file).  When this area is hovered over, a new class is added
		//in this case, the class "active" is added.  When the mouse is no longer hovering over the area, then the "active" class is removed.  
		var contactInput = $('#formTop input');
		var contactInputBg = $('#formTop .input-bg');
		var contactTextarea = $('#formBottom textarea');
		var contactTextareaBg = $('#formBottom .message-bg');
		
		contactInputBg.hover(function() {
			$(this).addClass('active');
		}, function() {
			$(this).removeClass('active');
		});

		contactInput.focus(function() {
			$(this).parent().addClass('active');
		});
		contactInput.blur(function() {
			contactInputBg.removeClass('active');
		});

		contactTextareaBg.hover(function() {
			$(this).addClass('active');
		}, function() {
			$(this).removeClass('active');
		});

		contactTextarea.focus(function() {
			$(this).parent().addClass('active');
		});
		contactTextarea.blur(function() {
			contactTextareaBg.removeClass('active');
		});

		//This initializes the jQuery validater plugin
		$('#commentForm').validate();
	

/*******************SUBMISSION OF CONTACT FORM**************************/
		$contactName = $('input#name');
		$contactCity = $('input#city');
		$contactEmail = $('input#email');
		$contactMessage = $('textarea#message');

		//Replaces the instructional text that I've placed in each form by default, after the user clicks inside said field
		replaceDefaultValue($contactName, "Type your name here.");
		replaceDefaultValue($contactCity, "Type your city here.");
		replaceDefaultValue($contactEmail, "Type your email here.");
		replaceDefaultValue($contactMessage, "Type your message here.");
		//The function takes two parameters:  the id name of the field to replace and the text of the default value that we'll be replacing
		function replaceDefaultValue(fieldName, defaultValue){
			fieldName.focus(function(){ //Deletes the default value once the user clicks (or tabs into) the field
				if ($(this).val() == defaultValue) { $(this).val(''); }
			});
			fieldName.blur(function(){ //Replaces the form field with the default value if it is empty when the user clicks away from it
				if ($(this).val() == '') { $(this).val(defaultValue); }
			});
		}
		
		$(".button").click(function() {
			//Sets a few variables equal to the values that were entered in the contact form on the contact.php page
			var name = $("input#name").val();
			var city = $("input#city").val();
			var email = $("input#email").val(); 
			var message = $("textarea#message").val();
			//Looks for the ".button" class and once clicked, does the following...
			 //This sets up a data sring containing all the information submitted through the contact form
			 var dataString = 'name=' + name + '&city=' + city + '&email=' + email + '&message=' + message;
			 //alert (dataString);return false; (This line can be uncommented and used for testing purposes)
			 //This sets up the jQuery ajax
			 $.ajax({  
			   type: "POST", 
			   //The values in the dataString get sent to this file and then processed... this file actually handles the mail.  The rest of the jQuery below; however, 
			   //deals with how the page loads using ajax...
			   url: "http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/contactengine.php",  
			   //This is the data to be sent, the variable "dataString" that we prepared earlier....
			   data: dataString,  
			   //If successful, this function is run.  It refreshes the area to give a message letting the user know their info was submitted successfully.
			   success: function() {  
				 //Places the following new html inside of the element with an id of #submit_button
				 $('#submit_button').html("<img src='/wp-content/themes/nightfrightevents/images/RIP.png' />")
				 //Hides the new html to begin with...
				 .hide() 
				 //Then fades it in... 
				 .fadeIn(1500, function() {  

				 });  
			   }  
			 });
			 //This return false is important.  Without it, the page would attempt to reload.
			 return false; 	
		});


//**********************************IMAGE THUMBNAIL CAROUSEL***********************************//

		$.fn.infiniteCarousel = function() {
			//This function accepts two parameters.  The string that needs to be repeated is passed in, as well as the number of times to repeat it, which is signified by "n".  This creates an array and plugs the string into it as many times as it needs to.  
			function repeat(str, n) {
				return new Array( n + 1 ).join(str);
			}

			return this.each(function() {
				//Set up variables
				// Grab the wrapper
				var $wrapper = $('> div', this).css('overflow', 'hidden'),
					//Now the ul and no futher
					$slider = $wrapper.find('> ul'),
					//Now the li and no futher
					$items = $slider.find('> li'),
					//Just pick one li to use for the $single variable
					$single = $items.filter(':first')
					//full width of one li thumbnail.  The +10 allows for the width of my margins on each li because outerWidth only calculates the width and padding, but not the margins
					singleWidth = $single.outerWidth() + 10, 
					//Width of the whole wrapper divided by the width of one list item, then round up.
					visible = Math.ceil($wrapper.innerWidth() / singleWidth),
					//This will track the current page we're on.  We'll start by setting it equal to the first page.
					currentPage = 1,
					//Pages = the number of list items divided by that which is visible. For example, we have 25 items, 8 of which are visible, then we have four pages we can scroll through using the buttons.  ($items.length equals the number of thumbnails I have) 
					pages = Math.ceil($items.length / visible);

				//TASKS
				// 1. pad the pages with empty elements if required
				// If there is a remainder when the length of a single item is divided by the width of the page... (in my situation, there's a remainder of 1), then do the following...
				if ($items.length % visible != 0) {
					// padding (if needed) to fill out the last page
					// "n" is equal to 7 in this case.  It is the number of times I need to create an empty li to act as padding.  "n" is passed into the repeat function (above).
					var n = visible - ($items.length % visible);
					//This li element is appended to the slider ul element as many times as necessary.  Both these are passed into the "repeat" function (written above), which will return an array containing the full number of times that this needs to be appended.
					$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
					//When the li elements get appended, it goofs up the slider, so this is necessary to reset it to the beginning. It's also important because $items need to be reset to take into account all of the newly appeneded li elements. 
					$items = $slider.find('> li');
				}

				// 2. create the carousel padding on the left and right (cloned items).  All of the items are filtered to grab just the first, and then we want to put stuff before it...
				$items.filter(':first').before(
					//We're going to slice off all 8 items and then clone them.  We'll give them the class of "cloned" so we can target the styling for them specifically if we want.  These new cloned list items will go before the ones that were already there.
					$items.slice(-visible).clone().addClass('cloned'));
				//Now we need to do the same thing, but this time after the exsisting list items instead of before.
				$items.filter(':last').after(
					$items.slice(0, visible).clone().addClass('cloned'));
				//Reset $items once again to take into account all of the new cloned items.
				$items = $slider.find('> li')

				// 3. reset scroll.  This sets the scrollbar back to the beginning position.
				$wrapper.scrollLeft(singleWidth * visible); 

				// 4. paging function
				function gotoPage(page) {
					//Page starts out as 1 by default at the begginning.  If page is less then currentPage (which is also 1 to start), then the direction is negetive, otherwise it's positive. 
					var dir = page < currentPage ? -1 : 1,
						//n is the number of pages we're going to flip through.  Math.abs ensures that the number is always positive.  We take the current page (for example, 2) and subtract it by the page we want to go to (for exmple, 3), which equals -1.  Math.abs changes that to just "1" and so then "n" is equal to 1.  
						n = Math.abs(currentPage - page),
						//"left" is how many pixels we want to scroll left when the user clicks the left button.  The amount that is scrolled is equal to the width of one list item, times positive or negative (the direction), times the amount of visible items on the page, times the number of pages we want to leap over to (signified by "n").
						left = singleWidth * dir * visible * n;

					//Check to make sure nothing is already being animated, and if not, then animate...	
					$wrapper.filter(':not(:animated)').animate({
						//Now we're actually going to scroll left, by the amount we specified earlier.
						scrollLeft : '+=' + left
					//Take a half a second to run the animation.  Once the animation is finished, run this function.
					}, 500, function() {
						// if the page that the user wants to scroll to (signified by the "page" variable) is larger then the number of pages that there actually are, then reset the position back to the beginning of the carousel.
						if (page > pages) {
							//This instantaneously sets the scrollbar back the beginning.  Because the scrollbar is hidden, the user doesn't even know this action has taken place.  To them, the scrolling seem "infinite."  That's that magic!
							$wrapper.scrollLeft(singleWidth * visible);
							page = 1;
						//If the user tries to go backwards and there are no more pages to scroll backwards through, then direct them to the last page (page = the number of pages... ie. "the last" page)...
						} else if (page == 0) {
							page = pages;
							//We're going to scrollLeft like before, but this time we're going to multiple by "pages" in order to scroll to the position of the last page.
							$wrapper.scrollLeft(singleWidth * visible * pages);
						}
						//This updates the page we're on, so we know what page to go to relative to that
						currentPage = page;
					});
				}

				var scrollPos = singleWidth * visible;	

				// 5. insert the back and forward link
				//$wrapper.after('<a href="#" class="arrow back"></a><a href="#" class="arrow forward"></a>');

				// 6. bind the back and forward links
				$('a.back', this).click(function() {
					//run the gotoPage function.  "currentPage" is passed into the gotoFunction and becomes "page".  We're going to add or subtract from that depending on which link is clicked.  In this case, we're going to subtract.
					gotoPage(currentPage - 1);		
					return false;
				});

				//If the forward button is clicked, then we're going to add to the current page.
				$('a.forward', this).click(function() {
					gotoPage(currentPage + 1);
					return false;
				});

				$(this).bind('goto', function(event, page) {
					gotoPage(page);
				});	

/**************************LOAD LARGER IMAGE WHEN THUMBNAIL CLICKED***************************/
				//Replaces the div below the carousel with the large version of the image. It does this by grabbing out the href attribute from the "a" tag link. The link only works if Javascript is disabled, otherwise it's simply used so the href can be grabed and then displayed in the div below
				$('#carousel_wrapper ul li span.regular').click(function() {
					//Grabs the href string and stores it in a variable called href
					var href = $(this).attr('href');
					//The large version of the photo is then loaded into the photos div
					//The order that this all happens is important and each element needs to be targeted correctly.  If not, then weird things happen during the loading of the image such as page jumps and whatnot...
					//Fade out the img (not the DIV!).  Once faded out, run this function...
					var loader = $('#loader');
					$('#photos img').fadeOut(250, function() {
						//Stops and current animation of the loader GIF, then fades it in.  This fires every time no matter wether the image is already loaded into the cache or not.  However, since it fades in over 1 seconds, if the image has already been loaded prevoiusly, then it will display before the loading GIF has a chance to show it's face.
						loader.stop().fadeIn(1000);
						//load in the new html
						$('#photos').html('<img src="' + href + '" />');
						//Hide the new image.  Once the image is loaded, fade it in.  It is important that the newImage variable is created here and not earlier, otherwise the program will break.  This is because the image selector has changed, and so jquery needs to search through the DOM again. 
						var newImage = $('#photos img'); 
						newImage.hide().load(function() {
						    //Hides the loader GIF so that it won't blend in with the image that's about to load in over the top of it.
							loader.hide();
							//Fades in the new image.
							newImage.fadeIn(500);
							
						});
					});
				});

/**************************THUMBNAIL HOVER AND CLICK EFFECTS***************************/
//These thumbnail effects need to stay inside of the infiniteCarousel function (as they are now).  The reason for this is because these effects need to be reapplied to any new batches of thumbnails that are loaded in via ajax.     
				//This is the hover effect for when the mouse moves over the thumbnail
				$('#carousel_wrapper ul li').hover(
					// mouse in
					function() {
						$(this).stop().toggleClass('red_border')
									  .animate({"opacity" : 1}, 300);
					}, 
					// mouse out
					function() {
						$(this).stop().toggleClass('red_border')
									  .animate({"opacity" : .6}, 300);
					}
				);
				
				//This function grabs the attribute id tag for the thumbnail that was clicked on (suchs as "thumb1" or "thumb2") and saves it to a variable.  That variable is used to target the thumbnail that was clicked on and make it unique from the others.  The purposes of this is so that the thumbnail that is currently being viewed has something special about it - such as a red border - to let the website visitor know which thumbnail they're currently viewing at each moment.	
				$('.thumb').click(function() { 
				//First we remove the red border from any thumbnails which might have had it added to them previously.
					$(this).removeClass('red_border')
					//Now we grab the id value
					thumbIdName = $(this).attr('id');
					//Now we apply the new class to the specific thumbnail that was clicked.
					$(thumbIdName).addClass('red_border');
				});
				
			}); // Ends return this.each(function() {

		}; // Ends $.fn.infiniteCarousel = function() {
/*
		$('#arrow_left').hover(
				function() {
				$(this).html('<img src="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/images/arrow-left-glow.png" />');   
			},  function() {
				$(this).html('<img src="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/images/arrow-left.png" />');
			}
		);

		$('#arrow_right').hover(
			   function() {
				$(this).html('<img src="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/images/arrow-right-glow.png" />');	   
			}, function() {
				$(this).html('<img src="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/images/arrow-right.png" />');
			}
		);
*/
/**************************CALL THE CAROUSEL FUNCTION***************************/
		$('div#carousel').infiniteCarousel();

/**************************GALLERY THUMBNAIL LOADER************************/		
		//Spites for when the user hovers over a date.  
		$('#gallery_box_links .each').hover(function(){
			$(this).css({'background-position' : '0px -41px'})
			}, function() {
			$(this).css({'background-position' : '0px 0px'})
		});
		$('#gallery_box_links .eachbig').hover(function(){
			$(this).css({'background-position' : '1px -53px'})
			}, function() {
			$(this).css({'background-position' : '1px 0px'})
		});
		
		
		//Loads in the respective thumbnails depending on which image is clicked.  The only difference in each of these lines is that the gallery variable is set to a different name (such as "haunt2008").  This name is then passed into the function below, which handles the execution of the code and picks out the images from the correct folder depending on the value of the gallery variable that was passed into it. 
		$('.haunt2009', '#gallery_box_links').click(function() {var gallery = "haunt2009";loadGallery(gallery);});
		$('.haunt2008', '#gallery_box_links').click(function() {var gallery = "haunt2008";loadGallery(gallery);});
		$('.haunt2007', '#gallery_box_links').click(function() {var gallery = "haunt2007";loadGallery(gallery);});	
		$('.haunt2006', '#gallery_box_links').click(function() {var gallery = "haunt2006";loadGallery(gallery);});
		$('.tothall2009', '#gallery_box_links').click(function() {var gallery = "tothall2009";loadGallery(gallery);});
		$('.tothall2008', '#gallery_box_links').click(function() {var gallery = "tothall2008";loadGallery(gallery);});
		$('.tothall2007', '#gallery_box_links').click(function() {var gallery = "tothall2007";loadGallery(gallery);});
		$('.tothall2006', '#gallery_box_links').click(function() {var gallery = "tothall2006";loadGallery(gallery);});
		$('.pumpkinchunkin2009', '#gallery_box_links').click(function() {var gallery = "pumpkinchunkin2009";loadGallery(gallery);});
		$('.pumpkinchunkin2008', '#gallery_box_links').click(function() {var gallery = "pumpkinchunkin2008";loadGallery(gallery);});
		$('.pumpkinchunkin2007', '#gallery_box_links').click(function() {var gallery = "pumpkinchunkin2007";loadGallery(gallery);});
		$('.pumpkinchunkin2006', '#gallery_box_links').click(function() {var gallery = "pumpkinchunkin2006";loadGallery(gallery);});
		$('.costumeball2009', '#gallery_box_links').click(function() {var gallery = "costumeball2009";loadGallery(gallery);});
		$('.costumeball2008', '#gallery_box_links').click(function() {var gallery = "costumeball2008";loadGallery(gallery);});
		$('.costumeball2007', '#gallery_box_links').click(function() {var gallery = "costumeball2007";loadGallery(gallery);});
		$('.costumeball2006', '#gallery_box_links').click(function() {var gallery = "costumeball2006";loadGallery(gallery);});
		$('.harvestfestival2009', '#gallery_box_links').click(function() {var gallery = "harvestfestival2009";loadGallery(gallery);});
		$('.harvestfestival2008', '#gallery_box_links').click(function() {var gallery = "harvestfestival2008";loadGallery(gallery);});
		$('.harvestfestival2007', '#gallery_box_links').click(function() {var gallery = "harvestfestival2007";loadGallery(gallery);});
		$('.harvestfestival2006', '#gallery_box_links').click(function() {var gallery = "harvestfestival2006";loadGallery(gallery);});

		//When the user clicks on a new catagory or year, load in the respective thumbnails associated with what they clicked on. This function pulls it's values from an XML file that contains the name of each of the images.  The name of each image's thumbnail is the same as the name of the regular sized image, but resides in a different thumbnail ("tn") folder.  
		function loadGallery(gallery) {
			scrollDown();//Before loading the gallery, first scroll the page to the right position
			function scrollDown() {
				var windowHeight = $(window).height();      //Get the height of the window frame (what can be seen)
				var documentHeight = $(document).height();  //Get the height of the document (what can be scrolled)
				var scrollableHeight = documentHeight - windowHeight;  
				var i = $(window).scrollTop();				//Get the current scroll position from the top
				scrollPageDown = setInterval(function(){ 
					i = i + 30;								//Scroll this many pixels for every interval
					if(i >= scrollableHeight || i >= 580) { //Scroll no futher than 580px down
						clearInterval(scrollPageDown);  		//Stops scrolling
						return continueLoadGallery();  		//Callback - Ensures that the ajax doesn't start loading until the scrolling is complete
					}
					else { $(window).scrollTop(i); }		//Continue scrolling
				}, 1);										//Run the interval every 5 milliseconds
			}
			
			function continueLoadGallery(){
			//First task is the grab the current ul list and fade it out.  After fade out, the rest of the function is run...	
				$('#carousel_wrapper ul').fadeOut(500, function() {
					//Remove each list item
					$('#carousel_wrapper ul li').remove();
					//Get the gallery.xml file, store it in the variable "d" and run the following...
					$.get('http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/gallery.xml', function(d){
						//First time the thumbnail ID starts at 0
						thumbID = 0;
						//Find the gallery name in the XML file that we're currenly targeting.  Its name was passed into this function depending on which gallery was clicked on by the user.  Now that we have the name of the gallery tag in the XML file targeted (such as "haunt2008"), do the following to each of the nested items...
						var carouselUl = $('#carousel_wrapper ul');
						$(d).find(gallery).each(function(){
							var $galleryname = $(this);
							//Grab the text inside of each "imagename" XML tag.
							var imagename = $galleryname.find('imagename').text();
	   						//Increment the thumbnail ID number.  This is necessary because we will be adding this to the outputted html string so that each thumbnail can be target individually later on in other functions.
							thumbID++;
							//This is the html for each thumbnail.  It is created dynamically, with the specific gallery name, imagename, and thumbID for each item plugged into it.
							var html = '<li><span href="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/photos/' + gallery + '/reg/';
							html += imagename + '.JPG" class="regular">';
							html += '<img src="http://www.nightfrightproductions.com/wp-content/themes/nightfrightevents/photos/' + gallery + '/tn/';
							html += imagename + '.JPG" id="thumb' + thumbID + '" class="thumb" />';
							html += '</span></li>';
	   						//Each list item's html gets appended inside of the <ul></ul> tags
							carouselUl.append($(html));
						 });
						//Finally, we want to fade in the new thumbnail list we just created, creating a nice, smooth transition...
						carouselUl.fadeIn(700);
						 //The infiniteCarousel function is re-run every time a new batch of thumbnails is passed in.  This is necessary in order to re-apply the carousel code to the current batch.  
						$('div#carousel').infiniteCarousel();
					 });//End of .find()
				});//End of .get()
			}//Ends continueLoadGallery()
		};//End of loadGallery()


	}); // Ends $(function() {