$(function(){

    //// Swap Input Value on Focus :: See Searchform.php
	swapValues = [];
	$(".swap_value").each(function(i){
		swapValues[i] = $(this).val();
		$(this).focus(function(){
			if ($(this).val() == swapValues[i]) {
				$(this).val("");
			}
		}).blur(function(){
			if ($.trim($(this).val()) == "") {
				$(this).val(swapValues[i]);
			}
		});
	});
   
   
	
	//// Establish Sucker Fish Jquery Menu
	$("ul.sf-menu").supersubs({ 
		minWidth:    15,   // minimum width of sub-menus in em units 
		maxWidth:    19,   // maximum width of sub-menus in em units 
		extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
						   // due to slight rounding differences and font-family 
	}).superfish();  // call supersubs first, then superfish, so that subs are 
					 // not display:none when measuring. Call before initialising 
					 // containing tabs for same reason.	

					 
					 				 
	// Following Jquery works with a custom wordpress posttype:portfolio
	//
	$('#page_gallery_template #childrenmenu').show();						// Portfolio item Preview
	$('#page_gallery_template #parent_content').show();						// post content from posttype:page with template set to 'portfolio'
	$('#page_gallery_template #slidetoggle a').hide();						// "view all portfolio items"
	$('#page_gallery_template .children_content_item').hide();				// get_portfolio_content(), see page_portfolio.php
	//
	//
	//
	$("#page_gallery_template ul#children_thumbslist li").each(function() {			// Set's Portfolio item Preview span to match image widths
				var imgwidth = $("img", this).width();
				$("SPAN",this).css("width", imgwidth+"px"); 	
	});
	//
	//
	$('#page_gallery_template #slidetoggle a').click(function() {			// Actions that occure when user exits Porfolio item Detail back to Preview Mode
		$('#primary .children_content_item').hide();
		$('ul#children_thumbslist').slideToggle();
		$('#slidetoggle a').hide();
		
		$('#parent_content').show();										// Show post content from posttype:page with template set to 'portfolio'
		$("#children_thumbs_controls").show();								// Show the filterable controls
		$("#children_thumbs").show();										// Show Portfolio Item Preview;
		
	});	
	//
	//
	$('#page_gallery_template ul#children_thumbslist li SPAN').hide();				// Intial display settings for hover effects on Portfolio item preview thumbs		
	$("#page_gallery_template ul#children_thumbslist li").hoverIntent(
			function() { 
				//$(this).animate({ backgroundColor: "#f0f0f0" }, 200);
				$("img",this).removeAttr('title');
				$("SPAN",this).fadeIn("fast");
			},
			function() { 
				//$(this).animate({ backgroundColor: "#272727" }, 200); 
				$("SPAN",this).fadeOut("fast"); 
			}
	);
	//
	//
	//
	//
	// Intiate Jquery Cycle when the a children's thumblist link is clicked 
	$('#page_gallery_template ul#children_thumbslist li a').click(function() {
		// $("body").css("overflow", "hidden");
		// $('ul#children_thumbslist li SPAN').hide();
		
		// Actions that occure after clicking on Preview Portfolio Item
		$("SPAN",this).fadeOut("fast"); 									//	Fade Out on the Span (Project Title)		
		$("#children_thumbs_controls").hide();								//  Hide the Filterable Controls
		$("#children_thumbs").hide();										//  Hide all Preview Images		

		// Execute State Changes when Thumbnail was clicked
		$('#parent_content').hide();											// Content associated with Wordpress page
		$('#parent_content .children_content_item .media_controls').hide();		// Prev/Next Controls for each of the Projects
		$('#parent_content .children_content_item').show();						

		// Things to do when we click on a non_current link
		// Which indicates that we are clicking on a different Thumbnail
		//if(!$(this).parent().hasClass('current')) {
			//Figure out the class for the Thumbnail that was clicked
			$(this).css('outline','none');


			// Remove li current class, since we will change lasted targeted click	
			$('ul#children_thumbslist li').each(function() {
					$(this).fadeIn('slow').removeClass('current').animate({ backgroundColor: "#272727" }, 250);
			});				


			// Grab the targeted
			var targetclass = $(this).parent().attr('rel');




			// And then bring up our targeted content item...the selected project
			$('#primary .'+targetclass).show();


			// Highlight Current Selection for Childern Thumblist
			$(this).parent().fadeIn('slow').addClass('current').animate({ backgroundColor: "#d0d0d0" }, 250);		


			// Active Jcycle for current set of images
			////// JCycle Plulgin Stuff
			// Hide all the controls
			$('.'+targetclass+' .media_controls').hide();
			$('.pause').click(function() { $('.'+targetclass+' .media_assets').cycle('pause'); return false; });
			$('.play').click(function() { $('.'+targetclass+' .media_assets').cycle('resume'); return false; });

			// Check for hover over media elemetns
			$('.media_grouping').hoverIntent(
				function() { $('.media_controls').fadeIn(); },
				function() { $('.media_controls').fadeOut(); }
			);

			// Initiate JCycle
			$('.'+targetclass+' .media_assets').cycle({
				fx:     'fade',
				speed:   400,
				next:   '.next',
				prev:   '.prev',
				timeout: 700,
				nowrap: 0,
				after: adjustHeight  		
			});

			// Make sure it starts off paused
			$('.'+targetclass+' .media_assets').cycle('pause');
		//}


			// Hide Pause/Play
			$('.'+targetclass+' .pause').hide();
			$('.'+targetclass+' .play').click(function(){
				$('.'+targetclass+' .media_assets').cycle('resume'); 
				$('.'+targetclass+' .media_controls').fadeOut(); 
				$(this).hide();
				$('.'+targetclass+' .pause').show(); 			
			});		
			$('.'+targetclass+' .pause').click(function(){  
				$('.'+targetclass+' .media_assets').cycle('pause'); 
				$('.'+targetclass+' .media_controls').fadeOut(); 
				$(this).hide();
				$('.'+targetclass+' .play').show();			
			});



		// FInish executing State Changes when Thumbnail was clicked
		$(this).parent().parent().slideToggle();
		$('#slidetoggle a').show();
		//$('#slidetoggle a span').show();


		return false;
	});
	/////////////////////////////////////////////////////////////////////////////////






	// JCycle Plugin, used with grab_post_media_content() in functions.php
	// Creates the autogenerated SlideShows
	$('#index_template .children_content, #single_template .children_content, #page_template_default .children_content, #single_portfolio_default .children_content').each(function(i) {
		//$(this).append(i.toString());

		var targetclass = $(this).children().attr('id');
		//$(this).append(targetclass);

		$('#'+targetclass+' .media_grouping').hoverIntent(
			function() { $('#'+targetclass+' .media_controls').fadeIn(); },
			function() { $('#'+targetclass+' .media_controls').fadeOut(); }  
		);



		////// JCycle Plulgin Stuff
		// Hide all the controls
		$('#'+targetclass+' .media_controls').hide();
		$('#'+targetclass+' .pause').click(function() { $('.'+targetclass+' .media_assets').cycle('pause'); return false; });
		$('#'+targetclass+' .play').click(function() { $('.'+targetclass+' .media_assets').cycle('resume'); return false; });

		// Check for hover over media elemetns


		// Initiate JCycle
		$('#'+targetclass+' .media_assets').cycle({
			fx:     'fade', 
			speed:   2400,
			next:   '#'+targetclass+' .next',
			prev:   '#'+targetclass+' .prev',
			timeout: 700,
			nowrap: 0,
			containerResize: 0,
			before: adjustHeight,
			pager:  '#'+targetclass+' .thumbnav',
		    pagerEvent:     'click.cycle', // name of event which drives the pager navigation 


			// callback fn that creates a thumbnail to use as pager anchor 
			//var img = $(slide).find("img").eq(0).attr("src");
			pagerAnchorBuilder: function(idx, slide) { 
				// return selector string for existing anchor 
				return '#'+targetclass+' .thumbnav li:eq(' + idx + ') a'; 
			}			

		});

			// Hide Pause/Play
			$('#'+targetclass+' .pause').hide();
			$('#'+targetclass+' .play').click(function(){
				$('#'+targetclass+' .media_assets').cycle('resume'); 
				$('#'+targetclass+' .media_controls').fadeOut(); 
				$(this).hide();
				$('#'+targetclass+' .pause').show(); 			
			});		
			$('#'+targetclass+' .pause').click(function(){  
				$('#'+targetclass+' .media_assets').cycle('pause'); 
				$('#'+targetclass+' .media_controls').fadeOut(); 
				$(this).hide();
				$('#'+targetclass+' .play').show();			
			});

		// Make sure it starts off paused
		$('#'+targetclass+' .media_assets').cycle('pause');		
	});


	
	// Jquery serialScroll Plugin Used with Wordpress Custom Function
	// See function sidescroller_bytags() inside function.php
	// Mastheadslide settings
	$('#mastheadslide .serialscroller').each(function(i) {

		var targetid = $(this).attr('id');

		$('#'+targetid+' .scrollcontent').serialScroll({
			items:'div.slide_item',
			prev:'#'+targetid+' .scrollboxnav a.previtem',
			next:'#'+targetid+' .scrollboxnav a.nextitem',
			offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
			start:0, //as we are centering it, start at the 2nd
			duration:1200,
			force:true,
			stop:true,
			lock:false,
			cycle:true, //don't pull back once you reach the end
			easing:'easeOutQuart', //use this easing equation for a funny effect
			jump: false //click on the images to scroll to them
		});

	});

	// Jquery serialScroll Plugin Used with Wordpress Custom Function
	// See function sidescroller_bytags() inside function.php
	$('#content .serialscroller').each(function(i) {

		var targetid = $(this).attr('id');

		$('#'+targetid+' .scrollcontent').serialScroll({
			items:'div.slide_item',
			prev:'#'+targetid+' .scrollboxnav a.previtem',
			next:'#'+targetid+' .scrollboxnav a.nextitem',
			offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
			start:0, //as we are centering it, start at the 2nd
			duration:1200,
			force:true,
			stop:true,
			lock:false,
			cycle:true, //don't pull back once you reach the end
			easing:'easeOutQuart', //use this easing equation for a funny effect
			jump: true //click on the images to scroll to them
		});

	});		
	

	$("div#makeMeScrollable").smoothDivScroll({
		scrollingHotSpotLeft:	"div.scrollingHotSpotLeft",		// The identifier for the hotspot that triggers scrolling left.
		scrollingHotSpotRight:	"div.scrollingHotSpotRight",	// The identifier for the hotspot that triggers scrolling right.
		scrollWrapper:	"div.scrollWrapper",					// The identifier of the wrapper element that surrounds the scrollable area.
		scrollableArea:	"div.scrollableArea",					// The identifier of the actual element that is scrolled left or right.	
		scrollingSpeed: 12, 
		mouseDownSpeedBooster: 3, 
		autoScroll: "onstart", 
		autoScrollDirection: "endlessloop", 
		autoScrollSpeed: 2, 
		visibleHotSpots: "always", 
		hotSpotsVisibleTime: 9, 
		}
	);	

	$("div#thumbnavscrollerable").smoothDivScroll({
		scrollingHotSpotLeft:	"div.scrollingHotSpotLeft",		// The identifier for the hotspot that triggers scrolling left.
		scrollingHotSpotRight:	"div.scrollingHotSpotRight",	// The identifier for the hotspot that triggers scrolling right.
		scrollWrapper:	"div.media_thumbs",						// The identifier of the wrapper element that surrounds the scrollable area.
		scrollableArea:	"ul.thumbnav",							// The identifier of the actual element that is scrolled left or right.	
		scrollingSpeed: 12, 
		mouseDownSpeedBooster: 3, 
		// autoScroll: "onstart", 
		autoScrollDirection: "endlessloop", 
		autoScrollSpeed: 2, 
		visibleHotSpots: "always", 
		hotSpotsVisibleTime: 9, 
		}
	);	

	
	$('.anythingSlider').anythingSlider({
		easing: "easeInOutExpo",        // Anything other than "linear" or "swing" requires the easing plugin
		autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
		delay: 3000,                    // How long between slide transitions in AutoPlay mode
		startStopped: false,            // If autoPlay is on, this can force it to start stopped
		animationTime: 600,             // How long the slide transition takes
		hashTags: true,                 // Should links change the hashtag in the URL?
		buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
		pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
		startText: "Go",             // Start text
		stopText: "Stop",               // Stop text
		navigationFormatter: formatText       // Details at the top of the file on this use (advanced use)
	});
	
	$("#slide-jump").click(function(){
		$('.anythingSlider').anythingSlider(6);
	});

	$('#children_thumbslist').filterable({
		tagSelector: '#portfolio-filter a',
		selectedTagClass: 'currentfilter',
		useTags: true,
	});
	
	$("#children_thumbs_xx a").fancybox({
		'autoScale'			: false,
		'autoDimensions'	: false,
		'width'				: 880,
		'height'			: 525,
		'overlayOpacity'	: .7,
		'titleShow'			: false,
		'padding'			: 5,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'showCloseButton'	: false,		
		'overlayColor'  	:'#000',
		'scrolling'			: 'no',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
		
	});
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////////

	// OVERRIDE OUR CSS WIDTH FOR THESE TWO, ITS SET IN CSS FOR THE CLIP WINDOW
//	 $("#children_thumbs").css("width", "auto");	
//	 $("#children_thumbs UL").css("width", "auto");	
 
	 
	 
	 
	
	// Some Variables we will need
	var $paneTarget = $('#children_thumbs');						// This is the Layout Plane, All thumbs must fit on here
	$("#children_thumbs").calcThumbSize();							// Run Our Custom Thumb Resize Function
	

	
	
	// When the Window Resizes We need to recalculate the Thumbns and Clipping window
	$(window).resize(function() {
				$("#children_thumbs").calcThumbSize();
				$paneTarget.scrollTo( 0 );				
	});
	// When the Filter is Applied Resizes We need to Recalculate the Thumbs and Clipping window	
	$("#portfolio-filter a").click(function(){
				$("#children_thumbs").calcThumbSize();
				$paneTarget.scrollTo( 0 );
	});	

	

	// Our Most Postion Along X Axis Determines the Position of the Clipping Window
	// We use scrollTo Handle the movement interms of percentage
   $("#content").mousemove(function(e){

	if ( $("#children_thumbs").is(":visible") ) {
  
	  var offset = $("#children_thumbs").offset();
  
	  var x = e.pageX - offset.left - 100;				// Half the Shaved part
	  var y = e.pageY - offset.top - 100;	
   
	  var viewport = $("#children_thumbs").width() - 200;		// We shave off a little, so that our mouse doesn't have to right up the edge to get the clipping window full left or full right
	  var percentage = x /  viewport  * 100;

	  // figure out mouse Y move
	  var viewporty = $("#children_thumbs").height() - 200;
	  var percentagey = y /  viewporty  * 100;	  
	  
	  // Debug Code	
	  //$('#masthead').html(x +', '+ y + ', ' + percentage);
	  

	  
	  var tstring = "{top:'25%',left:'25%'}";
	  $paneTarget.stop().scrollTo( {
			top: percentagey+'%',
			left: percentage+'%'
			} 
		
		);
		
		
		
	}		
		
		
   }); 

		
	

	$(".nextslide").hoverIntent(
			// On hover
			function() {
				$("#children_thumbs").calcThumbSize(); 	
				$paneTarget.stop().scrollTo( '100%', 800 );
			},
			// Off Hover
			function() {}
	);
	
	$(".prevslide").hoverIntent(
			function() {
				$("#children_thumbs").calcThumbSize();
				$paneTarget.stop().scrollTo( '0%', 800 );	
			},
			function() {}
	);	



	
});






jQuery.fn.calcThumbSize = function () {

	// SOME CSS Settings we'll need
	$("#children_thumbs").css("overflow", "hidden");	
	$("#children_thumbs").css("clear", "both");	 

	// Some Variables we will need
	var viewportWidth = $("#content").width();
	var viewportHeight = $(window).height();	
	

	var offset = $("#children_thumbs").offset();
	var ctheight = viewportHeight - offset.top - 100;	
    $("#children_thumbs").css( "height", ctheight+"px");										// Adjust height to fit everythin in view, otherwise css auto 	  
	$("#children_thumbs").css("width", viewportWidth+"px");										// Match the div to the viewport size, Acts like a clipping mask for our technique
	  
	//
	var numofthumbs = 4;																		// Numbers of Thumbs in Visible in the Row, inside the viewport
	var numofthumbsclipped = 2;																	// Additional number of thumbs outside the Vieport per row
	var thumbmargin = parseInt($("#children_thumbs LI").css("marginRight"));					// Grab the desired thumb margin from css
	$("#children_thumbs UL").css("paddingLeft", thumbmargin+"px");		

	// Calculcate amount of Rows We'll have
	var totalthumbs = $("#children_thumbs LI").size();											// Determine Total number of Thumbs in the List
	var rowCalc = Math.ceil(totalthumbs / ( numofthumbs + numofthumbsclipped ) );   			// Number of Rows needed

	var setthumbwidth = ( viewportWidth - (thumbmargin * numofthumbs) - thumbmargin ) / numofthumbs;	// Width based on number of visible items in viewport
	
	// var thumbnailHeight = ( (viewportHeight - 260 ) - ( rowCalc * thumbmargin) ) / rowCalc;			// Calculate to fit evenly in viewport
	var thumbnailHeight = setthumbwidth	* 240 / 360;													// Height will scale according to width, based on image ratio
	
	$("#children_thumbs LI").css("width", setthumbwidth+"px");				
	$("#children_thumbs LI").css("height", thumbnailHeight+"px");
	$("#children_thumbs LI IMG").css("width", setthumbwidth+"px");				
	$("#children_thumbs LI IMG").css("height", thumbnailHeight+"px");

	var adjustedSPANpos = thumbnailHeight + 5;
	$("#page_gallery_template ul#children_thumbslist li SPAN").css("top", "-"+adjustedSPANpos+"px");


	// Determine size of the div that is being masked by #children_thumbs
	var panewidth = ( setthumbwidth * numofthumbs + ( setthumbwidth * numofthumbsclipped) ) + ( (thumbmargin * numofthumbs ) + ( thumbmargin * numofthumbsclipped) );				
	$("#children_thumbs UL").css("width", panewidth+"px");

}




















function formatText(index, panel) {
	  return index + "";
}


// Works with JCycle, Detects Container item height and adjust entire Container
// accordingly
function adjustHeight(curr, next, opts, fwd) {
	//var index = opts.currSlide;
	//$('#prev')[index == 0 ? 'hide' : 'show']();
	//$('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
	
	//get the height of the current slide
	var $ht = $(this).height();
	var $wt = $(this).width();
	
	//set the container's height to that of the current slide
	$(this).parent().css("width", $wt+"px" );	
	$(this).parent().animate({ height: $ht}, 250);



}



// Works with JCycle, Detects Container item height and adjust entire Container
// accordingly
jQuery.fn.fadeToggle = function(speed, easing, callback) {
	   return this.animate({opacity: 'toggle'}, speed, easing, callback);
	}; 

