var _currentIndex= 0;
var t;
var speed = 1000;
var delay = 4000;
var _currentCarouselIndex = 0;

$(document).ready(function(){

    $(".clickable").each(function(){
        MakeClickable($(this), false);
    });

    $(".hoverable").each(function(){
	MakeHoverable($(this), "hover");
    });

    $(".jsenabled").each(function(){
	MakeJSEnabled($(this));
    });

    if($("#HomeSections").length > 0)
    {
    	StartContentFader("#HomeSections", "/Data/Images", 1000, 3000);
    }

    if($("#Gallery").length > 0)	
    {
	StartMainPageGallery("#MainPageImageInner", "#Gallery");
    }

    if($("#CaseStudyWindow").length > 0)
    {
	StartCarousel($("#CaseStudyWindow"),950);
    }
	
    if($("#BlogListWindow").length > 0)
    {
	StartCarousel($("#BlogListWindow"),450);
    }

    if($("#PageSummaries").length > 0)
    {
	//Hide and reposition page text
	$("#PageSummaries .page").each(function(){

		var pageText = $(this).find(".pageSummary");
		var pageLink = $(this).find("a");

		pageLink.hide();
        	pageText.fadeTo(0,0);
		pageText.show();
                
		$(this).bind("mouseenter",function(ev){
			pageText.fadeTo(500, 0.8);
		})

		$(this).bind("mouseleave",function(ev){
			pageText.fadeTo(500, 0.0);
		})
	})
    }

    $("a.fancybox").fancybox();
});

$(window).load(function(){
	if($("#CaseStudyWindow").length > 0)
    	{	
		$(window).bind("resize", function(){
			RepositionCarousel("#CaseStudyWindow", 950);
		});
		
		//position scroller to first item
		CarouselMove($("#CaseStudyWindow"), 0, 950, 1000);
		$("#CaseStudyWindow .caseStudyGallery a").fancybox();
	}

	if($("#BlogListWindow").length > 0)
	{
		$(window).bind("resize", function(){
			RepositionCarousel("#BlogListWindow", 450);
		});
		
		//position scroller to first item
		CarouselMove($("#BlogListWindow"), 0, 450, 1000);
		$("#BlogListWindow .gallery a").fancybox();
	}

	LoadMainPageGallery("#MainPageImageInner", "#Gallery");
});

//Gets an internal link and makes the whole item clickable
function MakeClickable(item, hideLink)
{
    var link = item.find("a").attr("href");
    item.bind("click", function(){window.location = link;});
    
    if(hideLink)
    {
        item.find("a").hide();
    }
}

//append/removes class on hover
function MakeHoverable(item, mouseOverClass)
{
    item.bind("mouseenter", function(){$(item).addClass(mouseOverClass)});
    item.bind("mouseleave", function(){$(item).removeClass(mouseOverClass)});
}

//adds the .loaded class to specific elements, this is added once the DOM is loaded
//hence only works for those browsers that have javascript enabled.
function MakeJSEnabled(item)
{
	$(item).addClass("loaded");
}

function StartContentFader(element, imagesDirectory, speed, delay)
{
        var viewPort = $(element);
	var elementsList = viewPort.find("ul");
	var elements= viewPort.find("li");
	var images = viewPort.find("li img");

	$(elements).each(function(){
		MakeClickable($(this));
	});
	
	//hide all contents to start
	viewPort.find("li").hide();
	viewPort.find("li a").hide();
	
	images.each(function(){
		$(this).attr("rel", $(this).attr("src"));
		$(this).attr("src","");
	});

	//wrap the ul with a loader the size of the viewport, allows background image
	//to be loading gif anim
	elementsList.wrap("<div class=\"loader\">","</div>");
	
	//make loaderInner the same size as viewport
	var loaderInner = $(element).find(".loader");
 	loaderInner.css("width", viewPort.width() + "px");
 	loaderInner.css("height", viewPort.height() + "px");
 	loaderInner.css("position", "absolute");
	loaderInner.css("background-image", "url(" + imagesDirectory + "/loading.gif)");
	loaderInner.css("background-repeat", "no-repeat");
	loaderInner.css("background-position", "center center");

	$(window).load(function(){
		ShowContent(viewPort, _currentIndex);	        
	});
}

function ShowNextContent(element)
{
	var elementToHide = $(element).find("li")[_currentIndex];
	var elementImageToHide = $(element).find("li")[_currentIndex];
	var elementSummary = $(elementToHide).find(".pageSummary");
	
	$(elementSummary).fadeTo("slow", 0, function(){

		$(elementToHide).fadeOut(speed, function(){

			$(elementToHide).find("img").attr("src","");
			
			if(_currentIndex+1 == $(element).find("li").size())
			{
				_currentIndex = 0;
				ShowContent(element, 0);	
			}
			else
			{
				ShowContent(element, _currentIndex+1);	
			}
	
		});
	});
}

function ShowContent(element, _indexToShow)
{
	var elementToShow = $(element).find("li")[_indexToShow];
	var elementImage = $(elementToShow).find("img");
	var elementSummary = $(elementToShow).find(".pageSummary");

	elementSummary.fadeTo(0, 0);	

		elementImage.load(function(){

			$(elementToShow).fadeIn("slow", function(){
				elementSummary.fadeTo("slow", 0.6);
				_currentIndex = _indexToShow;
				clearTimeout(t);
				t=setTimeout(function(){ShowNextContent(element);},delay);
			});	

		});

	if(elementImage.attr("src") == "")
	{
		elementImage.attr("src", elementImage.attr("rel"));
	}

}

function StartCarousel(carousel, widthOfViewer)
{
	var Carousel, CarouselScroller, CarouselScrollerWidth, ImageLeft, ImageRight, LeftOfWindow, RightOfWindow

	Carousel = $(carousel);
	Carousel.addClass("Carousel");
	CarouselItems = $(Carousel.find("li"));

	Carousel.find("ul").wrap("<div class=\"carouselScroller\">","</div>");
	CarouselScroller = $(Carousel.find(".carouselScroller"));

	CarouselScroller.css("position","absolute");
	CarouselScroller.css("left","0px");
	CarouselScrollerWidth = 0;
	//calculate width of scroller
	$(CarouselScroller.find("li")).each(function(i){
		var pageContent, pageImage;

		pageImage = $(this).find("img");
		pageImage.attr("rel", pageImage.attr("src"));
		pageImage.hide();

		CarouselScrollerWidth += $(this).width();

		//set pageContent
		pageContent = $(this).find(".pageContent");
		pageContent.css("top", $(this).outerHeight() - pageContent.find("h2").outerHeight() - 50);
		pageContent.fadeTo(0,0.9);

		$(this).bind("mouseenter", ShowPageContent);
		$(this).bind("mouseleave", HidePageContent);
	});

	CarouselScroller.css("width",CarouselScrollerWidth + "px");
	
	//get left and right of what should be the viewing window
	LeftOfWindow = GetLeftOfWindow(widthOfViewer);
	RightOfWindow = GetRightOfWindow(widthOfViewer);
	
	//sort left and right buttons
	ImageLeft = Carousel.find(".buttonLeft");
	ImageRight = Carousel.find(".buttonRight");

	ImageLeft.css("position","absolute");
	ImageRight.css("position","absolute");	
	
	ImageLeft.css("left",LeftOfWindow-ImageLeft.width()/2 + "px");
	ImageLeft.css("top",Carousel.height()/2-ImageRight.height()/2 + "px");	

	ImageRight.css("left",RightOfWindow-ImageRight.width()/2+ "px");
	ImageRight.css("top",Carousel.height()/2-ImageRight.height()/2 + "px");

	ImageLeft.fadeTo(0,0.6);
	ImageRight.fadeTo(0,0.6);

	ImageRight.click(function(){
		if(_currentCarouselIndex < CarouselItems.size()-1)
		{
			_currentCarouselIndex++;
			CarouselMove(Carousel, _currentCarouselIndex, widthOfViewer, 1000);
		}
	});

	ImageLeft.click(function(){
		if(_currentCarouselIndex > 0)
		{
			_currentCarouselIndex--;
			CarouselMove(Carousel, _currentCarouselIndex, widthOfViewer, 1000);
		}
	});

	ImageLeft.bind("mouseenter",function(){
		ImageLeft.fadeTo(300,1);
	});

	ImageRight.bind("mouseenter",function(){
		ImageRight.fadeTo(300,1);
	});
	
	ImageLeft.bind("mouseleave",function(){
		ImageLeft.fadeTo(300,0.6);
	});

	ImageRight.bind("mouseleave",function(){
		ImageRight.fadeTo(300,0.6);
	});

	CarouselItems.find("img").each(function(){
		
		$(this).attr("rel", $(this).attr("src"));
		$(this).attr("src", "/data/images/spacer.gif");
		$(this).parent().css("background-image","url(/data/images/loading.gif)");
		$(this).parent().css("background-repeat","no-repeat");
		$(this).parent().css("background-position","center center");
				
		$(this).load(function(){
			$(this).fadeTo(0,0);
			$(this).show();
			$(this).fadeTo(400,1);
		});
	});
}

function ShowPageContent()
{
	var pageContent = $(this).find(".pageContent");
	var pageContentInner = $(this).find(".pageContentInner ");
	pageContent.animate({
		top : $(this).outerHeight() - pageContentInner.outerHeight()
	}, 200);
}

function HidePageContent()
{
	var pageContent = $(this).find(".pageContent");
	pageContent.animate({
		top : "420px"
	}, 200);
}

function GetLeftOfWindow(widthOfViewer)
{
	return $(window).width()/2-widthOfViewer/2;
}

function GetRightOfWindow(widthOfViewer)
{
	return $(window).width()/2+widthOfViewer/2;
}

function GetCenterOfWindow()
{
	return $(window).width()/2;
}

function RepositionCarousel(carousel, viewerWidth)
{
	var Carousel, CarouselItems, CarouselScroller, LeftOfWindow, RightOfWindow, ImageLeft, ImageRight
	var MoveTo

	Carousel = $(carousel);
	CarouselItems = $(Carousel.find("li"));
	CarouselScroller = $(Carousel.find(".carouselScroller"));
	LeftOfWindow = GetLeftOfWindow(viewerWidth);
	RightOfWindow = GetRightOfWindow(viewerWidth);

	ImageLeft = $(Carousel.find(".buttonLeft"));
	ImageRight = $(Carousel.find(".buttonRight"));
	
	ImageLeft.css("left",LeftOfWindow-ImageLeft.width()/2 + "px");
	ImageLeft.css("top",Carousel.height()/2-ImageRight.height()/2 + "px");	

	ImageRight.css("left",RightOfWindow-ImageRight.width()/2+ "px");
	ImageRight.css("top",Carousel.height()/2-ImageRight.height()/2 + "px");

	MoveTo = 0 - ($(CarouselItems.eq(_currentCarouselIndex)).position().left-LeftOfWindow);
	CarouselScroller.css("left", MoveTo + "px");
}

function CarouselMove(carousel, itemIndex, viewerWidth, duration)
{
	var Carousel, CarouselItems, CarouselScroller, LeftOfWindow, RightOfWindow, MoveTo
	var ImageLeft, ImageRight

	Carousel = $(carousel);
	CarouselItems = $(Carousel.find("li"));
	CarouselScroller = $(Carousel.find(".carouselScroller"));
	ImageLeft = $(Carousel.find(".buttonLeft"));
	ImageRight = $(Carousel.find(".buttonRight"));

	Carousel.stop();	

	//get left and right of what should be the viewing window
	LeftOfWindow = GetLeftOfWindow(viewerWidth);
	RightOfWindow = GetRightOfWindow(viewerWidth);
	
	//if within bounds
	if(itemIndex <= CarouselItems.size()-1 && itemIndex >= 0)
	{
		MoveTo = 0 - ($(CarouselItems.eq(itemIndex)).position().left-LeftOfWindow);

		CarouselScroller.animate({
			left : MoveTo + "px"
		},duration);
		
		var carouselImage = $(CarouselItems.eq(itemIndex).find("img"));
		var nextCarouselImage = $(CarouselItems.eq(itemIndex+1).find("img"));
		
		if(carouselImage.attr("src") != carouselImage.attr("rel"))
		{
			carouselImage.attr("src",carouselImage.attr("rel"));
		}

		if(nextCarouselImage.attr("src") != nextCarouselImage.attr("rel"))
		{
			nextCarouselImage.attr("src",nextCarouselImage.attr("rel"));
		}
	}	
}

function StartMainPageGallery(pictureHolder, imageList)
{
	var pictureHolder = $(pictureHolder);	
	var imageList= $(imageList);	
	var images = imageList.find("img");
	var imageContainers = imageList.find("li");
	var bigimages = imageList.find("a");
	var pageText= pictureHolder.find(".pageText");
	
	pictureHolder.css("overflow","hidden");
	pictureHolder.append("<img id=\"BigImage\" src=\"" + $(bigimages[0]).attr("href") + "\" />");
	pageText.fadeTo(0,0);
	imageList.hide();
	imageList.css("bottom","-" + imageList.height() + "px");

	jQuery.each(imageContainers, function(){
		$(this).css("opacity","0.5");
	});
	
	$(pictureHolder.find("#BigImage")).fadeTo(0,0);
	
	$(imageContainers).each(function(){
		$(this).find("a").hide();
		$(this).find(".text").hide();		
	});
}

function LoadMainPageGallery(pictureHolder, imageList)
{
	var pictureHolder = $(pictureHolder);	
	var imageList= $(imageList);	
	var images = imageList.find("img");
	var imageContainers = imageList.find("li");
	var bigimages = imageList.find("a");
	var pageText= pictureHolder.find(".pageText");

	//Main Image Gallery
	$(imageContainers).each(function(){

		$(this).bind("click",function(ev){

			SwitchImage($("#BigImage"), $(ev.target).parent().find("a").attr("href"), $(ev.target).parent().find(".text").html(), imageList);
		});
	});

	pictureHolder.bind("mouseenter", function(){
		imageList.show();
		imageList.css("left", (pictureHolder.width()-imageList.width())/2 + "px");
		imageList.animate({
			top: "380px"
		},200);
		pageText.animate({
			opacity: 0.8
		},500);	
	});

	pictureHolder.bind("mouseleave", function(){
		imageList.animate({
			top: "550px"
		},200);
		pageText.animate({
			opacity: 0
		},500);		
	});

	imageContainers.bind("mouseenter", function(){
		var imageContainer = $(this);
		var imageText = imageContainer.find(".text");
		imageContainer.fadeTo(300,1);
	});

	imageContainers.bind("mouseleave", function(){
		$(this).fadeTo(300,0.5);
		$(this).find(".text").hide();
	});
	
	BindImageLoad($("#BigImage"), imageList);
	SwitchImage($("#BigImage"), imageContainers.eq(0).find("a").attr("href"), imageContainers.eq(0).find(".text").html(), imageList);		
}

function BindImageLoad(imageHolder, imageList)
{
	var imageHolder = $(imageHolder);
	var imageHolderParent = imageHolder.parent();
	var pageText = imageHolderParent.find(".pageText");

	imageHolder.load(function () {		

		if(imageHolder.height() > imageHolderParent.height())
		{
			var difference = (imageHolder.height() - imageHolderParent.height());
			var time = difference * 2;
			imageHolder.css("position","absolute");
			imageHolder.css("top", "-" + difference/2 + "px");
		}

		imageHolder.fadeTo(1000, 1, function(){
		if(imageList.css("opacity") != 1)
		{
			imageList.fadeTo(500, 0.5);
		}

		pageText.show();
		pageText.animate({
			opacity: 0.8
			},500);
			
		imageList.show();
		imageList.css("left", (imageHolder.width()-imageList.width())/2 + "px");
		imageList.animate({
			top: "380px"
			},200);
		});

	});
}

//Switch the image of the current collection        
function SwitchImage(imageHolder, imageToSwitchTo, text, imageList)
{   
	var newImage = imageToSwitchTo;
	var imageHolder = $(imageHolder);
	var imageHolderParent = imageHolder.parent();
	var pageText = imageHolderParent.find(".pageText");

	pageText.fadeTo(200, 0, function(){

		pageText.html(text);	
		//switch text
		imageHolder.fadeTo(200, 0, function(){
			imageHolder.attr("src", newImage);		
		});		
	});
 }