var current_image = 0,
	total_images = 0,
	browser_width,
	browser_height,
	lightboxScroll,
	touch_enabled = false;

load_images = function()
{
    for (var i = 0; i <= arguments.length - 1; i++) {
    	$("#lightbox-images li:nth-child(" + arguments[i] + ") img").attr("src", $("#lightbox-images li:nth-child(" + arguments[i] + ") img").attr("data-src"));
    }
}

resize_gallery = function() {
	browser_width = $(window).width();
	browser_height = $(window).height();
	var thumbs_per_row = Math.floor(((browser_width - 88)/312));
	var flickr_per_row = Math.floor(((browser_width - 88)/252));
	
	/*if($("body").hasClass("home"))
	{
		var available_height = browser_height - $("header").outerHeight() - $("footer").outerHeight();
		$("body.home article").css("height", available_height + "px");
		$("body.home article img").css("padding-top", (available_height - $("body.home article img").height()) / 2 + "px");
	}*/
	
	if($(".gallery"))
	{
		if($("#overlay").hasClass("visible"))
		{
			$("#overlay").width(browser_width).height($(document.body).height());
		}
		
		if(($("#lightbox").length > 0) && $("#lightbox").hasClass("visible"))
		{
			$("#lightbox-images").width(browser_width * $("#lightbox-images").children("li").length).height(browser_height).addClass("no_transition");
			$("html.touch #lightbox-images").css("opacity", 0);
			
			if(!touch_enabled)
			{
				$("#lightbox-images").css("margin-left", "-" + (current_image-1)*browser_width + "px");
			}
			
			$("#lightbox, #lightbox-images li").width(browser_width).height(browser_height);
				
			waitForResize = setTimeout(function() {
				$("#lightbox-images").removeAttr("class");
				
				//buggy when lightbox is triggered by a hash
				$("#lightbox").css("top", $(document).scrollTop() + "px");
				
				clearTimeout(waitForResize);
			}, 0);
			
			//IMAGE RESIZING
			
			$("#lightbox-images img").each(function(){
			
				var newWidth = browser_width - 100;
				var newHeight = browser_height - 120;
				
				if((newWidth != $(this).width()) || (newWidth == 1224) || (newHeight != $(this).height()))
				{
					if(newWidth > 1224) newWidth = 1224;
					var ratio = newWidth / parseInt($(this).attr("data-width"));
					$(this).css("width", newWidth + "px").css("height", parseInt($(this).attr("data-height"))*ratio + "px");
					
					if($(this).height() > newHeight)
					{
						if(newHeight > 816) newHeight = 816;
						var ratio = newHeight / parseInt($(this).attr("data-height"));
						$(this).css("height", newHeight + "px").css("width", parseInt($(this).attr("data-width"))*ratio + "px");
					}
					
					$(this).css("margin-left", -$(this).width()/2 + "px").css("margin-top", -$(this).height()/2 - 30 + "px");
				}
			});
			
			if(touch_enabled && lightboxScroll)
			{
				refreshScroll = setTimeout(function() {
					lightboxScroll.refresh();
					lightboxScroll.scrollToPage(lightboxScroll.currPageX, 0, 0);
					clearTimeout(refreshScroll);
				}, 0);
			}

			waitForScroll = setTimeout(function() {
				$("#lightbox-images").css("opacity", 1);
				clearTimeout(waitForScroll);
			}, 500);
			
		}
				
		$(".gallery").each(function(){
			
			if($(this).length > 0 && (thumbs_per_row>=2) && (browser_width>=768))
			{
				$(this).css("width", thumbs_per_row*312 + "px");
			}
			else
			{
				$(this).css("width", "auto");
			}
			
			if($("ul", this))
			{
				$("ul", this).width(browser_width * $("ul", this).children("li").length).queue(function(next) {
				    $("li", this).each(function(){
						$(this).width(browser_width);
					});
					
					/*if($("body").hasClass("portrait"))
					{
						$("img", this).each(function(){
							var ratio = 612 / parseInt($(this).attr("width"));
							$(this).css("width", 612 + "px").css("height", parseInt($(this).attr("height"))*ratio + "px");							
						});
					}
					else
					{
						$("img", this).each(function(){
							$(this).removeAttr("style");							
						});
					}*/
					
					//$(this).css("height", $("img", this).eq(0).height() + "px");
										
				    next();
				});
				
				var id = $(this).attr("id").replace("gallery-","");
				var current_item = parseInt($("#index-"+ id).text());
								
				if(current_item && (current_item !== 1)){ 
					temp_ul = $("ul", this);
					$("ul", this).addClass("no_transition").css("margin-left", -browser_width*(current_item-1) + "px");
					waitForGalleryResize = setTimeout(function() {
						temp_ul.removeAttr("class");
						clearTimeout(waitForGalleryResize);
					}, 0);
				}
				
			}		
		});
		
	}
	
	if(($(".flickrpress-container").length > 0) && (flickr_per_row >= 2))
	{
		$(".flickrpress-container").eq(0).width(flickr_per_row*252);
	}
	
	if($(".thumbs").length > 0 && (thumbs_per_row>=2) && (browser_width>=768))
	{
		$(".thumbs").css("width", thumbs_per_row*312 + "px");
	}
	else
	{
		$(".thumbs").css("width", "auto");
	}
		
};


// Ready to go

$(document).ready(function() {
	
	// ADD SELECTED TO ACTIVE MENU LINK
	$(".current-menu-item a, .current_page_parent a").addClass("selected");
	
	$("body.home p img, body.single p img").each(function(){
		if($(this).width() > 624) $(this).addClass("float_right");
	});
	
	// MOVE WORK GALLERIES OUT OF CONTAINER
	if(($(".work .content .full-gallery, .work .content .gallery, .work .content object").length !== 0) && !$("body").hasClass("wrktp"))
	{
		var gallery_html = $(".work .content .full-gallery, .work .content .gallery, .work .content object").clone();
		$(".work .full-gallery, .work .gallery, .work object").detach();
		$(".content").after(gallery_html);
		if($(".work .content .gallery_nav"))
		{
			var gallery_nav = $(".work .content .gallery_nav").clone();
			$(".work .content .gallery_nav").detach();
			$(".content").after(gallery_nav);
		}
	}
		
	// KEEP WORK INFO AT TOP WHILE SCROLLING
	if($("body").hasClass("single-work") && !$("body").hasClass("wrktp"))
	{
		var original_offset = $(".content").offset().top-50;
		$(window).scroll(function() {
		  if($(window).scrollTop() > original_offset)
		  {
		  	$("#page").addClass("sticky");
		  }
		  else
		  {
		  	$("#page").removeClass("sticky");
		  }
		});
	}
	
	// ADD SELECTED TO WORK TAGS IN TAXONOMY
	if($("body").hasClass("tax-worktags"))
	{
		var classes = $("body").attr("class").split(" ");
		$(".filter-nav a:contains("+ classes[2].replace("term-", "").replace(/^\w/, function($0) { return $0.toUpperCase(); })  +")").addClass("selected");
	}
	
	// FIX FOR OLD DTAILED GALLERIES
	if($("#sliderone, #slidertwo"))
	{
		var fake_id = 0;
		$("#sliderone, #slidertwo").each(function(){
			fake_id++;
			$(this).attr("id", "gallery-" + fake_id);
			$(this).addClass("slider");
			$(this).before('<nav id="gallery-nav-' + fake_id + '" class="gallery_nav"><ul><li id="prev-' + fake_id + '" class="prev"><a href="#prev" class="circle">Prev</a></li><li id="next-' + fake_id + '" class="next"><a href="#next" class="circle">Next</a></li><li id="count-' + fake_id + '" class="count circle">Image <span id="index-' + fake_id + '" class=\"index\">1</span> of <span id="total-' + fake_id + '" class=\"total\">1</span></li><li id="show-overlay-' + fake_id + '" class="show-overlay"><a href="#show-overlay" class="circle"></a></li><li id="clear-overlay-' + fake_id + '" class="clear-overlay"><a href="#clear-overlay" class="circle"></a></li></ul></nav>');
		});
	}
	
	//resize_gallery();
		
	if($("html").hasClass("touch"))
	{
		touch_enabled = true;
	}
	
	if(!touch_enabled)
  	{	
		$(window).resize(function() {
	  		resize_gallery();
		});
  	}
  	else
  	{
  		$('html.touch body').bind('orientationchange',function(event){
	        resize_gallery();
	    })	
	}
	
	//var loader = $("<img />").attr("src", "http://www.dtailed.com/wp-content/themes/_wrk_wordpress/loader.gif");
	
	if($(".gallery"))
	{
	
		$("body").append('<div id="overlay" class="overlay"></div>');
		resize_gallery();
		
		if($(".slider"))
		{
			$(".slider").each(function(){
			
				var current_item  = 0;
				var id = $(this).attr("id").replace("gallery-","");
				
				//$("#gallery-"+ id + " ul").css("height", $("#gallery-"+ id +" li img").eq(0).height() + "px");
				
				if($("#gallery-"+ id +" li").length == 1)
				{
					$("#next-"+ id +", #prev-"+ id +", #count-"+ id +"").hide();
				}
				
				else
				{		
					$("#gallery-"+ id +" li").eq(0).addClass("selected");
					
					$("#total-"+ id).text($("#gallery-"+ id +" ul").children("li").length);
										
					$("#prev-"+ id + " a").live("click", function(){
						current_item = $("#gallery-"+ id +" li").index($("#gallery-"+ id +" li.selected"))+1;

						if(current_item >= 2)
						{
							$("#gallery-"+ id +" ul").css("margin-left", -$(window).width()*(current_item-2) + "px");
							$("#index-"+ id +"").text(current_item-1);
							$("#gallery-"+ id +" li.selected").removeClass("selected");
							$("#gallery-"+ id +" li").eq(current_item-2).addClass("selected");
						}
						
						return false;
					});
					
					$("#next-"+ id + " a").live("click", function(){
						current_item = $("#gallery-"+ id +" li").index($("#gallery-"+ id +" li.selected"))+1;
						
						if(current_item == $("#gallery-"+ id +" ul").children("li").length)
						{
							current_item = 0;
							$("#gallery-"+ id +" ul").css("margin-left", 0);
							$("#index-"+ id +"").text(1);
							$("#gallery-"+ id +" li").eq(0).addClass("selected");
						}
						else
						{
							$("#gallery-"+ id +" ul").css("margin-left", -$(window).width()*current_item + "px");
							$("#index-"+ id +"").text(current_item+1);
							$("#gallery-"+ id +" li.selected").removeClass("selected");
							$("#gallery-"+ id +" li").eq(current_item).addClass("selected");
						}
						
						return false;
					});
					
					$("#gallery-"+ id + " img").live("click", function(){
						current_item = $("#gallery-"+ id +" li").index($("#gallery-"+ id +" li.selected"))+1;
						
						if(current_item == $("#gallery-"+ id +" ul").children("li").length)
						{
							current_item = 0;
							$("#gallery-"+ id +" ul").css("margin-left", 0);
							$("#index-"+ id +"").text(1);
							$("#gallery-"+ id +" li").eq(0).addClass("selected");
						}
						else
						{
							$("#gallery-"+ id +" ul").css("margin-left", -$(window).width()*current_item + "px");
							$("#index-"+ id +"").text(current_item+1);
							$("#gallery-"+ id +" li.selected").removeClass("selected");
							$("#gallery-"+ id +" li").eq(current_item).addClass("selected");
						}
						
						return false;
					});				}
			});
		}
		
		// LIGHTBOX
				
		if($(".thumbs-gallery"))
		{
			
			$('.thumbs-gallery a[rel="lightbox"]').click(function(){
				
				if($("#lightbox").length == 0)
				{
					$("body").append('<div id="lightbox"></div>');
				}
				
				var lightbox_nav = "<nav id='lightbox-nav' class='gallery_nav'><p class='text'></p><ul><li id='lightbox-count' class='count circle'><span class='index'>1</span> / <span class='total'>1</span></li><li id='lightbox-prev' class='prev'><a href='#prev' class='circle'>Prev</a></li><li id='lightbox-next' class='next'><a href='#next' class='circle'>Next</a></li><li id='lightbox-close' class='close'><a href='#close' class='circle'>Close</a></li></ul></nav>";
				
				var lightbox_html = "";
						
				$(this).parent().children("a").each(function(){
					lightbox_html += "<li><img data-src=\"" + $(this).attr('href') + "\" src=\""+ wrkFolder +"/images/img-placeholder.png\" width=\"" + $(this).attr('data-width') + "\" height=\"" + $(this).attr('data-height') + "\" data-width=\"" + $(this).attr('data-width') + "\" data-height=\"" + $(this).attr('data-height') + "\" alt=\"" + $(this).attr('data-text') + "\" data-text=\"" + $(this).attr('data-text') + "\" style=\"margin-left: -" + $(this).attr('data-width')/2 + "px; margin-top: -" + (parseInt($(this).attr('data-height'))/2 - 30) + "px;\" /></li>";
				});
				
				$("#lightbox").addClass("visible").append("<ul id=\"lightbox-images\">" + lightbox_html + "</ul>" + lightbox_nav);			
						
				current_image = $('a[rel="lightbox"]', $(this).parent()).index($(this)) + 1;
				total_images = $('a[rel="lightbox"]', $(this).parent()).length;
				if(current_image == 1)
				{
					load_images(current_image, current_image+1, total_images);
				}
				else
				{
					load_images(current_image, current_image+1, current_image-1);
				}
				
				resize_gallery();
				show_overlay();
				
				//window.location.hash = current_image;
				
				if(touch_enabled)
				{
					$(document).bind("touchmove", function(e) { e.preventDefault(); });
					lightboxScroll = new iScroll('lightbox', {snap: 'li', momentum: false, hScrollbar: false, vScrollbar: false, useTransition: true });
					lightboxScroll.scrollToPage(current_image-1, 0, 0);
					
					/* Lightbox touch event */
					
					lightboxObject = document.getElementById("lightbox");
					lightboxObject.ontouchstart = function (e) {
						
						lightboxObject.ontouchmove = moveDrag;			
						var originPage = lightboxScroll.currPageX;
						
						lightboxObject.ontouchend = function () {
							var endPage = lightboxScroll.currPageX;
									
							if(originPage != endPage)
							{
								current_image = lightboxScroll.currPageX + 1;
								$("#lightbox-nav .text").text($("#lightbox-images li:nth-child(" + current_image + ") img").attr("data-text"));
								$("#lightbox-nav .index").text(current_image);
								
								var image_to_load = current_image;
								
								if(current_image  == 1)
									image_to_load = total_images + 1;
								else if (current_image == total_images)
									image_to_load = 0;
								
								if(originPage < endPage)
								{
									load_images(image_to_load+1);
								}
								else
								{
									load_images(image_to_load-1);
								}
								
								//window.location.hash = current_image;
							}
							
							lightboxObject.ontouchmove = lightboxObject.ontouchend = null;
						}
						
						function moveDrag() {
							var currentPos = getCoors();
						}
					
						function getCoors() {
							var coors;
							if (e.touches) { 			// iPhone
								coors = e.touches[0].clientX;
							} else { 				// all others
								coors = e.clientX;
							}
							return coors;
						}
					
					}
				}
				else
				{
					$("#lightbox-images").addClass("no_transition").css("margin-left", "-" + (current_image-1)*browser_width + "px");
				}
				
				//$("#lightbox-images li:nth-child(" + current_image + ")").css("opacity", 1);
				$("#lightbox-nav .text").append($("#lightbox-images li:nth-child(" + current_image + ") img").attr("data-text"));
				$("#lightbox-nav .index").text(current_image);
				$("#lightbox-nav .total").text($("#lightbox-images").children("li").length);
				
				waitForTransition = setTimeout(function() {
					$("#lightbox-images").removeAttr("class");
					$("#lightbox").css("visibility", "visible").css("opacity", 1);
					clearTimeout(waitForTransition);
				}, 500);
				
				return false;
			});
			
			$('#lightbox-images li img, #lightbox-nav .next').live('click', function() {					
				if(current_image == $("#lightbox-images").children("li").length)
				{
					current_image = 1;
					$("#lightbox-images").addClass("no_transition")
				}
				else
				{
					current_image++;
				}
								
				if(touch_enabled)
				{
					lightboxScroll.scrollToPage(current_image-1, 0, 600);
				}
				else
				{
					$("#lightbox-images").css("margin-left", "-" + (current_image-1)*browser_width + "px");
					if($("#lightbox-images").hasClass("no_transition"))
						waitForTransition = setTimeout(function() {
							$("#lightbox-images").removeAttr("class");
							clearTimeout(waitForTransition);
						}, 500);
				}
				
				var image_to_load = current_image;
				
				if (current_image == total_images)
					image_to_load = 0;
				
				load_images(image_to_load+1);
				
				$("#lightbox-nav .text").text($("#lightbox-images li:nth-child(" + current_image + ") img").attr("data-text"));
				$("#lightbox-nav .index").text(current_image);
				//window.location.hash = current_image;
				
				return false;
			});
			
			$('#lightbox-nav .prev').live('click', function() {					
				if(current_image > 1)
				{
					current_image--;
				}
				else
				{
					current_image = $("#lightbox-images").children("li").length;
					$("#lightbox-images").addClass("no_transition")
				}
								
				if(touch_enabled)
				{
					lightboxScroll.scrollToPage(current_image-1, 0, 600);
				}
				else
				{
					$("#lightbox-images").css("margin-left", "-" + (current_image-1)*browser_width + "px");
					if($("#lightbox-images").hasClass("no_transition"))
						waitForTransition = setTimeout(function() {
							$("#lightbox-images").removeAttr("class");
							clearTimeout(waitForTransition);
						}, 500);
				}
				
				var image_to_load = current_image;
				
				if (current_image == 1)
					image_to_load = total_images + 1;
				
				load_images(image_to_load-1);
				
				$("#lightbox-nav .text").text($("#lightbox-images li:nth-child(" + current_image + ") img").attr("data-text"));
				$("#lightbox-nav .index").text(current_image);
				//window.location.hash = current_image;
			
				return false;
			});
			
			$(document).keyup(function(e) {
		      if($("#lightbox").hasClass("visible"))
		      {
			      switch(e.keyCode) { 
			         case 39:
			            $('#lightbox-nav .next').trigger("click");
			            return false;
			         break;
			         case 37:
			            $('#lightbox-nav .prev').trigger("click");
			            return false;
			         break;
			         case 27:
			            hide_overlay();
			            return false;
			         break;
			      }
			      switch(e.charCode) { 
			         case 39:
			            $('#lightbox-nav .next').trigger("click");
			            return false;
			         break;
			         case 37:
			            $('#lightbox-nav .prev').trigger("click");
			            return false;
			         break;
			         case 27:
			            hide_overlay();
			            return false;
			         break;
			      }
		      }
		   	});
		   	
		}
		
		// GALLERY OVERLAY
		
		show_overlay = function(){
			if($("#lightbox").hasClass("visible"))
	      	{
				$("html,body").addClass("hide_scroll");
			}
			$("#overlay").height($(document.body).height()).css("visibility", "visible").css("opacity", 1).addClass("visible");
		}
		
		hide_overlay = function(){
			$("#lightbox").css("opacity", 0);
			waitForTransition = setTimeout(function() {
				$("html,body").removeClass("hide_scroll");
				$("#overlay").css("opacity", 0).removeAttr("class");
				
				/*if(window.location.hash)
				{
					window.location.hash = "";
				}*/
				
				if($("#lightbox").hasClass("visible") && touch_enabled)
				{
					$(document).unbind("touchmove");
					$("#lightbox").removeAttr("class");
					current_image = 0;
					/*lightboxScroll.destroy();
					lightboxScroll = null;*/
				}

				clearTimeout(waitForTransition);
				
				waitForTransition = setTimeout(function() {
					$("#overlay").css("visibility", "hidden").css("height", "auto");
					$("#lightbox").detach();//$("#lightbox").css("visibility", "hidden").empty();
					clearTimeout(waitForTransition);
				}, 1000);
			}, 500);
		}
		
		$(".show-overlay").click(function(){
			$("#overlay").css("background-color", "#222");
			show_overlay();
			return false;
		});
		
		$(".clear-overlay, #overlay, #lightbox-nav .close").live('click', function(){
			hide_overlay();
			return false;
		});
		
		/*waitabit = setTimeout(function() {
			var hash_hash = window.location.hash.slice(1);
			if(hash_hash !== "")
			{
				var potential_image	= $('.thumbs-gallery a:nth-child(' + hash_hash + ')[rel=lightbox]');	
				if(potential_image)
				{				
					potential_image.trigger("click");
				}
			}
		}, 200);*/
	}
	
	$("html:not(.touch) a.backtotop").live('click', function() {
		$('html,body').animate({scrollTop: $("html, body").offset().top},'fast');
		return false; 
	});
	
	$("a[rel=external]").each(function(){
		$(this).attr("target", "_blank");
	});
	
});

// Shuffle thumbnails load

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);

show_thumbs = function(){
	
	var totalImg = $(".thumbs img, .thumbs-gallery img").length;
	var randomIndexes = [];
	
	for(var i=0;i<=totalImg-1;i++)
		randomIndexes.push(i);
	
	$.shuffle(randomIndexes);
	
	$(".thumbs img, .thumbs-gallery img").each(function(index){
		var currImg = $(this);
		setTimeout(function(){
			currImg.css("opacity", 1);
		}, randomIndexes[index]*50);
	});
	
}

$(window).load(function(){
	show_thumbs();
});
