/* 
 * Author: Chris Vilchez
 * Contact: hello@chrisvilchez.com
 * Website: http://chrisvilchez.com
 */
 
/*
88                                        
88                                        
88                                        
88     ,adPPYba,   ,adPPYba,   ,adPPYba,  
88     I8[    ""  a8P_____88  a8P_____88  
88      `"Y8ba,   8PP"""""""  8PP"""""""  
88     aa    ]8I  "8b,   ,aa  "8b,   ,aa  
88     `"YbbdP"'   `"Ybbd8"'   `"Ybbd8"'  
                    88                         ,d                                               
                    88                         88                                               
8b      db      d8  88,dPPYba,   ,adPPYYba,  MM88MMM     8b       d8   ,adPPYba,   88       88  
`8b    d88b    d8'  88P'    "8a  ""     `Y8    88        `8b     d8'  a8"     "8a  88       88  
 `8b  d8'`8b  d8'   88       88  ,adPPPPP88    88         `8b   d8'   8b       d8  88       88  
  `8bd8'  `8bd8'    88       88  88,    ,88    88,         `8b,d8'    "8a,   ,a8"  "8a,   ,a88  
    YP      YP      88       88  `"8bbdP"Y8    "Y888         Y88'      `"YbbdP"'    `"YbbdP'Y8  
                                                             d8'                                
         88  88           88              88                d8'                               
         88  ""           88       ,d     88                                               
         88               88       88     88                                               
 ,adPPYb,88  88   ,adPPYb,88     MM88MMM  88,dPPYba,    ,adPPYba,  8b,dPPYba,   ,adPPYba,  
a8"    `Y88  88  a8"    `Y88       88     88P'    "8a  a8P_____88  88P'   "Y8  a8P_____88  
8b       88  88  8b       88       88     88       88  8PP"""""""  88          8PP"""""""  
"8a,   ,d88  88  "8a,   ,d88       88,    88       88  "8b,   ,aa  88          "8b,   ,aa  
 `"8bbdP"Y8  88   `"8bbdP"Y8       "Y888  88       88   `"Ybbd8"'  88           `"Ybbd8"'  
*/                                                                                           
                                                                                           


//Cufon.replace('nav ul');
QueryLoader.init();


$(document).ready(function() {

	var $window = $(window),
		$container = $('#container'),
		$nav = $('nav'),
		gallery_width = 0,
		check_scroll = true,
		next_counter = 0,
		next_page = "Nighthawks",
		on_handle = false,
		now_sliding = false;


	var setupSlider = {
		init: function(){
			var height = $window.height(),
				slider_height = "";
				
			if(height < 678 ){
				slider_height = ((height * 0.965) + 0 ) + "px";
			} else if(height < 760 ){
				slider_height = ((height * 0.95) + 0 ) + "px";
			} else {
				slider_height = ((height * 0.5) + 350 ) + "px";
			}
						
			var the_slider = $("<div/>", {
					id: "slider",
					css: {
						position: "fixed",
						top: slider_height,
						left: "75%",
						width: "230px",
						marginLeft: "-230px"
					}
				}
			);
	              
	               
			the_slider
				.appendTo($container)
				.slider(this.sliderOpts);
			
			$(".ui-slider-handle").hover(
				function(){
					on_handle = true;
					$(this).stop().animate({top: "-3px", height: "7px"}, 150);
				},
				function(){
					on_handle = false;
					if(!now_sliding){
						$(this).stop().animate({top: "-1px",height: "3px"}, 150);
					}
				}
			);
			
			$window.resize(function() {
				var height = $(this).height(),
					slider_height = "";
				
					
				if(height < 678 ){
					slider_height = ((height * 0.965) + 0 ) + "px";
				} else if(height < 760 ){
					slider_height = ((height * 0.95) + 0 ) + "px";
				} else {
					slider_height = ((height * 0.5) + 350 ) + "px";
				}
				
				the_slider.css({
					top: slider_height
				});

				gallerySetup.setNavigation();
			});	 
			
			$('.current_page_item').css("background", "none");
			
			
		}, // end of init
		
		sliderOpts: { 
			animate: true,
			slide: function(e, ui) {	
			
				var scrollLeft = percent(ui.value, gallery_width, 1, 10);
				
				$('#main').stop().animate({scrollLeft: scrollLeft}, 350, 'easeOutQuad');
				gallerySetup.setNavigation();
				gallerySetup.loadGallery(scrollLeft);
				
			},
			start: function(){
				now_sliding = true;
			},
			stop: function(e, ui){
				now_sliding = false;
				if(!on_handle){
						$(ui.handle).stop().animate({top: "-1px",height: "3px"}, 150);
				}
			}			 
		}	
	}
	

  
  

		
	if($nav.attr('gallery') === "yes"){
		var $gallery = $('.gallery'),
			current_page = $nav.attr("current"),
			gallery_pages = $nav.attr("galleries"),
			gallery_pages = gallery_pages.split(","),
			total_galleries = gallery_pages.length,
			middle_counter = gallery_pages.findIndex(current_page),
			been_loaded = [middle_counter],
			next_up_index = middle_counter + 1;

						
		var gallerySetup = {
		
			init: function(){
			
				$gallery
					.find('img').each(
						function(){
							gallerySetup.addToWidth($(this));
						}
					)
					.end()
					.css({'width' : gallery_width + 20});

				$(gallery_pages).each(
					function(){
						var gallery_title = this;
					
						$('.' + gallery_title).live('click', function(){
								var li = $(this),
									prev_ul = li.parent().prevAll();
									prev = li.prevAll(),
									new_scroll = 0;
					
								prev_ul.each(function(){
									this_width = $(this).width();
									new_scroll = new_scroll + this_width;			
								});
												
								prev.each(function(){
									var this_width = $(this).find('img').attr('width');
									this_width = this_width + 20;
									new_scroll = new_scroll + this_width;
									handle = percent(new_scroll, gallery_width, 0, 10);;
									
								});
												
								$('#main').animate({scrollLeft: new_scroll}, 600, 'easeInOutQuad');
						        $(".ui-slider-handle").animate({left: handle + "%"}, 600, 'easeInOutQuad');
					
						});
		
					}
				);
				
				
				$container.mousewheel(function (event, delta) {
					var current = $('#main').scrollLeft(),
						addition = (-delta * 30),
						handle = percent(current, gallery_width, 0, 10);

			        $('#main').stop().scrollLeft(current + addition);
//			        $(".ui-slider-handle").css({left: handle + "%"});
					$("#slider").slider( "option", "value", handle);
					gallerySetup.setNavigation();

			        					

					gallerySetup.loadGallery(current, addition);
			        

			
			
			    });
		    
				$marker = $("<img>", {
					id: "marker",
					src: "/wp-content/themes/zach_lewis/images/current.png",
					css: {
						position: "absolute",
						right: "0px"
						}
					}
				).appendTo($nav);	        
		        
		        gallerySetup.setNavigation();
//		        gallerySetup.loadGallery();
		        			
			}, // End of init
			
			loadGallery: function(current, mouse){
			
				var starting_page = gallery_pages.findIndex(current_page);
				
				if(starting_page === 0 ){
				
				
			        if(check_scroll && current > (gallery_width - 5000) && next_counter < (total_galleries - 1)){
			        	check_scroll = false;
			        
						$('<div/>').load(gallery_pages[next_counter+1]+'/ .gallery ul',function(){
							next_counter++;

							current_value = $( "#slider" ).slider( "option", "value" );
							current_width = gallery_width;
							
							handle_position = percent(current_value, current_width, 1, 10);
							
//							console.log(current_value);
//							console.log(current_width);
//							console.log(handle_position);
							
							
//							console.log()
							
							$this = $(this);
							
							$this.find('img').each(
								function(){
									gallerySetup.addToWidth($(this));
								}
							);
							
							new_handle_position = percent(handle_position, gallery_width, 0, 10);
//console.log(new_handle_position);

							
							$("#slider")
								.trigger("mouseup")
								.slider( "option", "value", new_handle_position);

							$gallery.css({'width' : gallery_width + 20}).append( $(this).html() );
							gallerySetup.setNavigation();
							
							check_scroll = true;
						});	
			        				        	
			        }		
				} else if (starting_page > 0 && starting_page + 1 < total_galleries){
										
					if( mouse > 0){

		
				        if( check_scroll && current > (gallery_width - 5000) && middle_counter < (total_galleries - 1) && !(next_up_index in oc(been_loaded)) ){
				        	check_scroll = false;
				        	next_up = gallery_pages[middle_counter+1];
				        	next_up_index = gallery_pages.findIndex(next_up);
				        	been_loaded.push(next_up_index);
				        	middle_counter++;
				        
							$('<div/>').load(next_up +'/ .gallery ul',function(){
								next_counter++;
								
								$this = $(this);
								
								$this.find('img').each(
									function(){
										gallerySetup.addToWidth($(this));
									}
								);
								

								$gallery.css({'width' : gallery_width + 20}).append( $(this).html() );
//								the_max gallery_width + 2
//								$("#slider").slider( "option", "value", handle);

//console.log(handle);

								gallerySetup.setNavigation();
								check_scroll = true;
				//    			$(this).appendTo('#content');    // once they're loaded, append them to our content area
							});	
				        				        	
				        }
					} else if (mouse < 0){
						var currently_on = this.getLocation();

			        	next_up_index = (gallery_pages.findIndex(currently_on) - 1);
						next_up = gallery_pages[next_up_index];

				    
						if( check_scroll && (gallery_width - current) > 5000 && middle_counter < (total_galleries) && !(next_up_index in oc(been_loaded)) ){
							middle_counter++;
				        	check_scroll = false;
//				        	next_up_index = gallery_pages.findIndex(next_up);
				        	been_loaded.push(next_up_index);
//				        
							$('<div/>').load(next_up +'/ .gallery ul',function(){
								next_counter++;
								
								$this = $(this);
								
								$this.find('img').each(
									function(){
										gallerySetup.addToWidth($(this));
									}
								);
								

								$gallery.css({'width' : gallery_width + 20}).prepend( $(this).html() );
								gallerySetup.setNavigation();
								
								check_scroll = true;
				//    			$(this).appendTo('#content');    // once they're loaded, append them to our content area
							});	
				        	
				        }
				    
				    }
			        			        	
				} else{
//			        	console.log("looks like the end to me!");
				}	
				
				
			
			},
			
			addToWidth: function($that){
				this_width = $that.attr('width');
				$that.attr({
					alt: "",
					title: ""
				});
				this_width = this_width + 20;
				gallery_width = gallery_width + this_width;
			},
			
			getLocation: function(return_li){
				var location = $("#main li:in-viewport");
					location = (location[1] ? location[1] : location[0]);
					
					
				return ( return_li ? location : $(location).attr('class'));
			}, 
			
			setNavigation: function(){
				var current_page = gallerySetup.getLocation(),
					in_the_menu = gallery_pages.findIndex(current_page) + 2,
					$li = $nav.find("li:nth-child("+in_the_menu+")"),
					item_height = $li.height(),
					item_offset = $li.offset(),
					li_pos = (item_offset.top + (item_height / 2) - 6);
					
//					console.log(total_galleries);
					
				$marker.stop().animate({top: li_pos}, 400, 'easeInOutQuad');

			
			}
		
		
		}
		
	
	
		gallerySetup.init();
	
		setupSlider.init();

		

	} // End of Gallery pages
	
//	setupSlider.init();
	$("nav ul li:first-child").lettering();
	
		
});

function oc(a) {
  var o = {};
  for(var i=0;i<a.length;i++) {
    o[a[i]]='';
  }
  return o;
}


function percent(number, whole, inverse, rounder){
	whole=parseFloat(whole);
	if(!whole){whole=100;};
	number=parseFloat(number);
	if(!number){number=0;};
	if(!whole || !number){return 0;};
	rounder=parseFloat(rounder);
	rounder=( rounder && (!(rounder%10) || rounder==1) )? rounder:100;
	return (!inverse)? Math.round( ((number*100)/whole) *rounder)/rounder:
	Math.round( ((whole*number)/100) *rounder)/rounder;

}


Array.prototype.findIndex = function(value){
	var ctr = "";
	for (var i=0; i < this.length; i++) {
		// use === to check for Matches. ie., identical (===), ;
		if (this[i] == value) {
			return i;
		}
	}
	
	return ctr;
};

