$(document).ready(function() {
	
	
	var $objHomepage = $('.homepage');
	var $objGallery = $('.gallery');
	var $objSearch = $('.search-results');
	var $objVideos = $('object');
	var $objArchive = $('.archive');
	var $objH2 = $('#content h2');
	var $objCountry = $('.country');
	var $objState = $('.state');
	
	var badBrowser = (/MSIE ((5\.5)|6|7|8)/.test(navigator.userAgent) && navigator.platform == "Win32");
	
	/**
	 * Clear Search (header)
	 */
	if ( $('#s').val() == "" )
	{
		$('#s').val('Search Website');	
	}
	$('#s').focus(function() {
		if ( $('#s').val() == "Search Website" )
		{
			$('#s').val('');
		}
		else if ( $('#s').val() == "" )
		{
			$('#s').val('Search Website');	
		}
	});
	
	
	/**
	 * Share Link (all pages)
	 */
	$('.share-link').html('Share, Bookmark, Email, or Print This');
	
	
	/**
	 * Create Table Of Content on article pages
	 */
	if ($objH2.length > 0 && $objHomepage.length == 0 && $objSearch.length == 0)
	{
		var aTags = "";
		var i = 0;
		$objH2.each(function() {
			var linkName = $(this).html().replace(/ /g, '-');
			$(this).attr('id', linkName);
			aTags += '<li><a href="#'+ linkName +'">'+ $(this).html() +'</a></li>';
			i++;
			
			// Add top link
			if ( i > 1)
			{
				$(this).prepend('<a href="#top" class="top">Top</a>');
			}
		});
		
		// Add to content
		if ( i > 1 )
		{
			$('.post').prepend('<div class="toc"><h3>In this article...</h3><ul>'+ aTags +'</div></ul>');
			$('.post p:last').append('<a href="#top" class="top">Top</a>');
		}
	}
	
	/**
	 * Homepage
	 */
	if ( $objHomepage.length > 0 )
	{
		// close welcome, start banners
		$('.welcome-close').bind('click', function() {
			
			// set the cookie
			if ( $.cookie('homepage_banner')  == null )
			{
				$.cookie('homepage_banner', 'hide', { expires: 7, path: '/' });
			}
			
			$('.welcome').html('&nbsp;').css('background', 'url(wp-content/themes/nj/images/loader.gif) no-repeat center center');
			$.get(
				'wp-content/themes/nj/homepage-slideshow.php',
				{ },
				function(data)
				{
					$('.welcome').before(data).remove();
					
					// Cycle (fade) banner images...
					var iImg = $('#banner-img img').length;
					if (iImg < 1) return false;
					$('#banner-img').cycle({ fx: 'fade', speed: 2000, timeout: 9000 });
					
				}
			);
		});	
		
		// cookie is set, load banners
		if ($.cookie('homepage_banner') == "hide")
		{
			$('.welcome-close').trigger('click');
		}
	}
	
	/**
	 * Blog Categories (archive template)
	 */
	if ( $objArchive.length > 0 )
	{
		$('.post:first', $objArchive).css('border-top', 'none');
	}
	
	/**
	 * Single Post Page 
	 */
	$('a.post-tags-toggle').click(function() {
		
		$('.post-tags').toggle();
		if ($('.post-tags').is(':visible'))
		{
			$('a.post-tags-toggle').html('&#9660; Post Tags')
		}
		else 
		{
			$('a.post-tags-toggle').html('&#9658; Show Post Tags');
		}
	});
	
	/**
	 * Directory, Country, State, etc.
	 */
	if ($objCountry.length > 0 || $objState.length > 0)
	{
		// Replace the breadcrumb 
		$('.breadcrumb a:first').attr('href', '/directory/').html('Browse'); 
	}
	
	
	/**
	 * Common Questions ( remove top links )
	 */
	if ( $('#Common-Questions').length > 0 )
	{
		$i = 1;
		$('.top').each(function() {
			if ($i == 4)
				return false;
				
			$(this).remove();
			$i++;
		});
	}
	
	/**
	 * Replace Video Content
	 */
	if ($objVideos.length > 0)
	{
		$objVideos.each(function() {
			$(this).wrap('<div class="video">'); // Nicely format videos
		});
	}
	
	/**
	 * Create Image Gallery
	 */
	var skip = false;
	if ($objGallery.length > 0)
	{	
		$objGallery.addClass('clearfix');
		$('br', $objGallery).remove();
		var eventNumber = 1; //so we can track the ordering of the events in the example 
		$('a', $objGallery).bind('click', function(event, target){ 
			skip = false;
			if (target != undefined)
			{
				eventImg  = ($('img', $(event.currentTarget)).attr('src'));
				targetImg = ($('img', target).attr('src'));
				if (eventImg == targetImg)
				{
					//alert('made it');
					//$(this) = target;
					skip = false;
				}
				else
				{
					skip = true;
				}
			}
			if (!skip)
			{
				//prepare the dynamic content to be added to the DOM. this content could easily come from an $.ajax request 
	            var newContent = '<div"><div class="imageSection">';  
				origUrl = $('img', $(this)).attr('src');
	            imgUrl = origUrl.replace('-150x150', '').replace('-230x230', '');
				newContent  += '<img src="'+ imgUrl +'" alt="image">';
				imageDesc = $(this).parent().parent().find('.gallery-caption').html();
	            newContent  += '<span class="imageDesc">'+ imageDesc +'</span></div></div>'; 
				// preloader image...
 				$('#content h2:first').css('background', 'url(../wp-content/themes/nj/images/loader.gif) no-repeat right center'); 
	            var $newContent = $(newContent); //create a new jquery element out of the dynamic html 
 
	            $newContent.onImagesLoad({ //attach onImagesLoad to the new content 
	                selectorCallback: contentSectionLoaded
	            }).insertAfter($objGallery); //insert the new content to the DOM 
			}
			if (!badBrowser) // gallery doesnt work in IE
            	return false; 
        }); 
 
        function contentSectionLoaded($selector){ 
            //note: this == $selector. $selector will be the new content section here 
            //$selector.find('.imageSection').html('<div class="loaded">Event #'+(eventNumber++)+': All images have loaded within this item</div>'); 
        	var objImg = $('img', $selector);
			var imgW = objImg.width();
			var imgH = objImg.height();
			objImg.attr( { 'rel' : imgW +'x'+ imgH });
			loadFullScreenImage(objImg);
			$selector.find('.imageSection').remove();
			initFullScreenNext();
			
			$('#content h2:first').css('background', 'none'); // remove loader image
		}	 
	
	}
	
	/**
	 * Full Screen Content
	 */
		var objImagesParent = ""; //Parent div holding images (prev / next)
		function loadFullScreen(html)
		{
			//Check if loaded already...
			if ($('#fullscreen-bg').is(':visible'))
			{
				$('#fullscreen-content').html(html);
				initFullScreenEvents();
			}
			//Load'r in...
			else {
				$('#fullscreen-bg').height($(document).height());
				$('#fullscreen-bg').css('display','block').fadeTo(300, .75, function() {
					$('#fullscreen-content').css('display', 'block').html(html).fadeTo(500, 1, function() {
						$('#fullscreen-close').css('display', 'block');
						initFullScreenEvents();
					});
				});
			}
		}
		function initFullScreenEvents()
		{
			initFullScreenNext();

			//Remove fullscreen
			$('#fullscreen-close, #fullscreen-bg').click(function() {
				removeFullScreen();
			});
			//Escape, or backspace key is press
			$(document).keypress(function (e) {
				if (e.which == 0 || e.which == 8)
				{
					removeFullScreen();
				}
			});
		}
		function removeFullScreen()
		{
			//Remove previously added classes...
			$('#fullscreen-content').removeClass('fullscreen-video');
			$('#fullscreen-close').removeClass('fullscreen-video-close');

			//Remove inline styles...
			$('#fullscreen-content').attr('style', 'display: none');
			$('#fullscreen-close').attr('style', '');

			$('#fullscreen-bg, #fullscreen-close, #fullscreen-content').css('display', 'none');
			$('#fullscreen-content').html('');
			
			skip = true;
		}
		function loadFullScreenImage(objImg)
		{
			var imgSrc  = objImg.attr('src');
			var imgDesc = $('.imageDesc').html();
			var imgDim  = $(objImg).attr('rel').split('x');
			var imgW    = Number(imgDim[0]);
			var imgH    = Number(imgDim[1]);

			html  = '<img src="'+ imgSrc +'" />'; 
			html += '<div class="fullscreen-video-desc" style="margin-top: 6px">'+ imgDesc +'</div>';
			html += '<div class="fullscreen-next-link">Click for Next Image</div>';
			$('#fullscreen-content')
			.animate({
				'width'  	 : imgW +'px',
				'height' 	 : (imgH+40) +'px',
				'left' 		 : (imgW/2)*-1,
				'marginTop'  : ((imgH+40)/2)*-1
			},200); 
			$('#fullscreen-close')
			.animate( {
				'left' 		 : (imgW/2)-100,
				'marginTop'  : ((imgH-40)/2)+13
			},200);
			
			loadFullScreen(html);
			$('.fullscreen-next-link').click(function() {
				$('#fullscreen-content img').trigger('click');
			});
		}
		function initFullScreenNext()
		{
			$('#fullscreen-content img').click(function() {	
				thisImageSrc = $(this).attr('src'); 		 //Get the current fullscreen image
				objChildImages  = $('img', $('.gallery')); //Get children images (thumbnails)
								
				//Loop thumbnails...
				objChildImages.each(function() {

					//Check if the current image is the loop item
					var strChildSrc = $(this).attr('src').replace('-150x150', '').replace('-230x230', '');
					if (strChildSrc == thisImageSrc)
					{
						//Replace current image with the next image
						var objNext = $(this).parent().parent().parent().next('dl');
				
						var refA = $('a', objNext);
						if ($(refA).length == 0) {
							//removeFullScreen();
							//return false;
							refA = $('a:first', $('.gallery'));													
						}
						
						$('a', $objGallery).trigger('click', [refA]);
						return false;
						
					}
				})
			});
		}
	
});
