$(document).ready(function() {
	var g_thumbCarousel;
	var g_currentSlideId;
	var g_thumbRangeScroll = (window.slideshow_thumbScroll && !isNaN(parseInt(window.slideshow_thumbScroll))) ? parseInt(window.slideshow_thumbScroll) : 6;
	var g_thumbRangeFirst = 1;
	var g_thumbRangeLast = g_thumbRangeScroll;
	
	//the default value for the load and fetch
	var g_slideShowLoadImageCount = 5;

	//global variable assigned if it exists
	if (JS_SLIDESHOW_LOADIMAGECOUNT != 0 && isNaN(JS_SLIDESHOW_LOADIMAGECOUNT)== false) 
	{
		
		g_slideShowLoadImageCount = JS_SLIDESHOW_LOADIMAGECOUNT;
		
	}
	
	//if the slide fetch is less than the minimum value 2, then assign the minimum value;
	if (g_slideShowLoadImageCount < 3) 
	{

		g_slideShowLoadImageCount = 3;

	}
	//Assigns the length of the allSlideshowImages array if the images to fetch is greater  
	//than the number of actual images in the container
	if (g_slideShowLoadImageCount > allSlideshowImages.length) 
	{
		g_slideShowLoadImageCount = allSlideshowImages.length;
	}

	//position of the slide ahead from the current slide where it checks onload property 
	var g_checkSlidePosition = 2;
	
	function _onInit(carousel, state)
	{
		if(state == "init")
		{
			$('#thumbnails ul li a').bind('click', function() {
				var pos = $.jcarousel.intval($(this).attr("slideId")) + 1;
				carousel.scroll(pos);
				
				return false;
			});

			//the slideShowLoadImageCount is the number of times the loop iterates
			for (var i = 0; i < g_slideShowLoadImageCount; i++) 
			{
				if (i == 0)
					continue;

				var slideItem = allSlideshowImages[i];
				carousel.add(i + 1, createLIImg(slideItem, i));
				slideItem.isLoaded = true;
			}
			
			//Add final slideshow element
			carousel.add(allSlideshowImages.length + 1, createFinalSlide());
			$('#slideshowAjax .slideshowEnd .viewAgain a').bind('click', function() {
				//Move back to start
				carousel.scroll(1);
				return false;
			});

			carousel.size(allSlideshowImages.length + 1);
			
			//Display the total number of slideshow elements
			var totalCount = document.getElementById("currentItemTotalCount");
			if(totalCount)
			{
				totalCount.innerHTML = allSlideshowImages.length;
			}
		}
	}
	
	function createLIImg(slideItem, slideId)
	{
		return "<img slideId='" + slideId + "' src='" + slideItem.img + "' alt='" + slideItem.title + "' />"
	}
	
	function createFinalSlide()
	{
		var html = "";
		html += "<div slideId='last' class='slideshowEnd'>";
			html += "<div class='endMessage'>You've reached the end of this slideshow</div>";
			html += "<div class='viewAgain'><a href='javascript:void(0);'>View it again</a></div>";
			var backLink = document.getElementById("slideshowBackToArticleLink");
			if(backLink)
			{
				html += "<div class='relatedLink'><a href='" + backLink.href + "'>Read related article</a></div>";
			}
			if(slideshow_moreSlideshowFeed)
			{
				html += "<div id='endMoreGalleries'>";
					html += "Loading...";
				html += "</div>";
				
				//Fetch more galleries from configured feed
				Ninemsn.Global.ContentManager.GetContent(slideshow_moreSlideshowFeed, _renderMoreGalleries);
			}
		html += "</div>";
		return html;
	}
	
	function _renderMoreGalleries(data)
	{
		var items = null;
		if(data && data.HttpTransferResult && data.HttpTransferResult.rss && data.HttpTransferResult.rss.channel && data.HttpTransferResult.rss.channel.item)
		{
			var items = data.HttpTransferResult.rss.channel.item;
			if(!items.length)
			{
				items = [data.HttpTransferResult.rss.channel.item];
			}
		}
		else
		{
			return;
		}

		var endMoreGalleries = document.getElementById("endMoreGalleries");
		if(endMoreGalleries)
		{
			var html = "";
			html += "<div class='title'>More galleries</div>";
			html += "<div class='moreThumbs'>";
			$.each(items, function(i,item){
				if(i >= 3)
				{
					return;
				}

				if(item.enclosure && item.enclosure.url && item.title)
				{
					if(item.enclosure.url.substring(0, 1) == "/")
					{
						item.enclosure.url = "http://" + document.location.host + item.enclosure.url;
					}
					
					var imgSrc = "http://images.ninemsn.com.au/resizer.aspx?height=96&url=" + escape(item.enclosure.url);
					html += "<div class='moreItem'>";
						html += "<div class='itemImg'><a href='" + item.link + "'><img src='" + imgSrc + "' /></a></div>";
						html += "<div class='itemTitle'><a href='" + item.link + "'>" + item.title + "</a></div>";
					html += "</div>";
				}
			});

			html += "</div>";

			endMoreGalleries.innerHTML = html;
		}
	}

	function updateCurrentThumb()
	{
		var pos = parseInt(g_currentSlideId) + 1;
		if(!pos && g_currentSlideId == "last")
		{
			pos = g_thumbCarousel.size();
		}

		//Set border
		$('#thumbnails ul li a').removeClass('selectedborder');
		$('#thumbnails .jcarousel-item-' + pos + ' a').addClass('selectedborder');
		
		var thumbnailIsOpen = $("#thumbnails").attr("isShowing");

		//if the thumbnail is open and is outside of the visible range, scroll it to show the current image
		if(thumbnailIsOpen == "true")
		{
			if(pos > g_thumbRangeLast)
			{//move forwards
				g_thumbCarousel.scroll(pos);

				//recalculate the positions of the currently showing first and last element
				recalculateThumbnailRange(pos, true);
			}
			else if(pos < g_thumbRangeFirst)
			{//move backwards
				g_thumbCarousel.scroll(pos - g_thumbRangeScroll + 1);

				//recalculate the positions of the currently showing first and last element
				recalculateThumbnailRange(pos, false);
			}
		}
	}
	
	function recalculateThumbnailRange(currentFirstPos, movedForward)
	{
		if(movedForward)
		{
			//recalculate the positions of the currently showing first and last element
			g_thumbRangeLast = (currentFirstPos + g_thumbRangeScroll - 1) <= g_thumbCarousel.size() ? (currentFirstPos + g_thumbRangeScroll - 1) : g_thumbCarousel.size();
			g_thumbRangeFirst = (g_thumbRangeLast - g_thumbRangeScroll + 1) > 0 ? (g_thumbRangeLast - g_thumbRangeScroll + 1) : 1;
		}
		else //moved backwards
		{
			//recalculate the positions of the currently showing first and last element
			g_thumbRangeFirst = (currentFirstPos - g_thumbRangeScroll + 1) > 0 ? (currentFirstPos - g_thumbRangeScroll + 1) : 1;
			g_thumbRangeLast = (g_thumbRangeFirst + g_thumbRangeScroll - 1) <= g_thumbCarousel.size() ? (g_thumbRangeFirst + g_thumbRangeScroll - 1) : g_thumbCarousel.size();
		}
	}

	function _onItemLoad(carousel, state)
	{
		try
	    {
		    var current = carousel.get(carousel.first).find(":first");
		    g_currentSlideId = current.attr("slideId");
		    var slideItem = allSlideshowImages[g_currentSlideId];
			
			updateCurrentThumb();
    									
		    if(state == "init")
		    {
			    if(slideItem && g_currentSlideId != 0)
			    {
				    refreshSlideDetails(slideItem);
			    }
		    }

		    if(state != "init")
		    {
		    
		    	//Create a variable and adds the slide Id of the next slide
				var currentSlideIdNext = parseInt(g_currentSlideId) + g_checkSlidePosition;

				//Create a variable and assign the object that corresponds to the slide Id 
				var slideItemNext = allSlideshowImages[currentSlideIdNext];

				//Assign global variable slideshow count to the local variable 
				//Also adjusting the loop by decreasing 1
				var defaultFetchEndCounter = g_slideShowLoadImageCount - 1;

				//Append to the default fetch count to get the end position to be fetched
				defaultFetchEndCounter += currentSlideIdNext;

				//Checks if the remaining fetch count is less than or equal to the default fetch
				//count then assign the remaining value to it
				if ((allSlideshowImages.length - currentSlideIdNext) <= (g_slideShowLoadImageCount - 1)) {
					//recalculating the end position for the last fetch
					defaultFetchEndCounter = (allSlideshowImages.length - currentSlideIdNext) + (currentSlideIdNext - 1);
				}

				//check if the values are not empty
				if (slideItemNext && currentSlideIdNext != 0) {

					//Checks if isloaded value in the next slideItem is "false" then, it fetches the default number
					//of images and assigning isloaded value to "true"
					if (slideItemNext.isLoaded == false) {

						for (var i = currentSlideIdNext; i <= defaultFetchEndCounter; i++) {
							var slideItemNext = allSlideshowImages[i];
							carousel.add(i + 1, createLIImg(slideItemNext, i));
							slideItemNext.isLoaded = true;


						}

					}
				}
		    
			    if(slideItem)
			    {
				    refreshSlideDetails(slideItem);
				    //Currently commented out until decision is made Regarding back button functionality
				    //document.location.hash = parseInt(g_currentSlideId) + 1;
			    }

			    registerNewPageRefresh();
			    
		    }

		    if(slideItem)
		    {
			    /*
			     *  Load Rating
			     */
			    var currentPhotoRating = document.getElementById("currentPhotoRating");
			    if(currentPhotoRating && !window.slideshow_turnOffRatings)
			    {
				    currentPhotoRating.innerHTML = "";
				    renderAjaxUGCControl("rating",slideItem.hlLinkID,10,"currentPhotoRating");
			    }
    			
			    /*
			     *  Render Comments
			     *  If suppression flag exists then clear out the comments.
			     */
			    var currentPhotoReview = document.getElementById("currentPhotoReview");
			    if(currentPhotoReview)
			    {
			        if(window.slideshow_turnOffReviews || slideItem.suppressComments)
			        {
				        currentPhotoReview.innerHTML = "";
			        }
			        else
			        {
			            renderAjaxUGCControl("review",slideItem.hlLinkID,10,"currentPhotoReview");
			        }
			    }    
		    }

		    setCurrentPosition(parseInt(g_currentSlideId) + 1);
		}
		catch (ex)
		{
		    // Suppress from client, render in debugger window if available
	        if (window.debout) 
	            debout(ex.description);
		}
	}
	
	function setCurrentPosition(num)
	{
		var currentPosCounter = document.getElementById("currentItemPosition");
		if(currentPosCounter)
		{
			if(isNaN(num))//Reached end
			{
				//disable back button on main image
				$("#mainCarouselPhoto .jcarousel-container .jcarousel-prev").hide();
                $("#mainCarouselPhoto .jcarousel-container .jcarousel-next").hide();
                
				//Hide ratings, photo credit, slideDetails, next button on bottom
				$("#slideshowAjax .photoFunctions .photoNavigation .next, #slideshowAjax .photoFunctions .photoNavigation .next a").css("cursor","default");
				disableElement("#slideshowAjax .photoFunctions .photoNavigation .next");
				enableElement("#slideshowAjax .photoFunctions .photoNavigation .back");
				
				$("#slideshowAjax .photoBottom div").css("visibility","hidden");
				$("#currentPhotoTitle").css("visibility","hidden");
				$("#currentPhotoDescription").css("visibility","hidden");
				$("#slideshowAjax .sl_right .relatedLinks").css("visibility","hidden");
				$("#slideshowAjax .currentPosition").css("visibility","hidden");
				
			}
			else
			{
				currentPosCounter.innerHTML = num;

				$("#mainCarouselPhoto .jcarousel-container .jcarousel-prev").show();
				$("#mainCarouselPhoto .jcarousel-container .jcarousel-next").show();

				if(num == 1)
				{//first picture
					disableElement("#slideshowAjax .photoFunctions .photoNavigation .back");
					$("#slideshowAjax .photoFunctions .photoNavigation .next, #slideshowAjax .photoFunctions .photoNavigation .back a").css("cursor","default");
				}
				else
				{
					enableElement("#slideshowAjax .photoFunctions .photoNavigation .back");
					$("#slideshowAjax .photoFunctions .photoNavigation .next, #slideshowAjax .photoFunctions .photoNavigation .back a").css("cursor","pointer");
				}
				
				/*
				 *  change the cursor
				 */
				enableElement("#slideshowAjax .photoFunctions .photoNavigation .next");				
				$("#slideshowAjax .photoFunctions .photoNavigation .next, #slideshowAjax .photoFunctions .photoNavigation .next a").css("cursor","pointer");
				
				$("#slideshowAjax .photoBottom div").css("visibility","visible");
				
				$("#currentPhotoTitle").css("visibility","visible");
				$("#currentPhotoDescription").css("visibility","visible");
				$("#slideshowAjax .sl_right .relatedLinks").css("visibility","visible");
				
				$("#slideshowAjax .currentPosition").css("visibility","visible");
			}
		}
	}
	
	function disableElement(jQPath)
	{
		$(jQPath).css("opacity", 0.2);
	}
	
	function enableElement(jQPath)
	{
		$(jQPath).css("opacity", 1);
	}
	
	function refreshSlideDetails(slideItem)
	{
		var currentPhotoTitle = document.getElementById("currentPhotoTitle");
		if(currentPhotoTitle)
		{
			currentPhotoTitle.innerHTML = slideItem.title;
		}

		var currentPhotoDescription = document.getElementById("currentPhotoDescription");
		if(currentPhotoDescription)
		{
			currentPhotoDescription.innerHTML = slideItem.description;
		}

		var relatedLinks = slideItem.relatedLinks;
		if(relatedLinks)
		{
			var innerHTML = "";
			for(var i = 0; i < relatedLinks.length; i++)
			{
				var rl = relatedLinks[i];
				innerHTML += "<a href='" + rl.url + "'>" + rl.title + "</a>"
			}
			
			var currentPhotoRL = document.getElementById("currentPhotoRL");
			if(currentPhotoRL)
			{
				currentPhotoRL.innerHTML = innerHTML;
			}
			$("#slideshowAjax .relatedLinks").show();
		}
		else
		{
			$("#slideshowAjax .relatedLinks").hide();
		}

		var currentPhotoCredit = document.getElementById("currentPhotoCredit");
		if(currentPhotoCredit)
		{
			currentPhotoCredit.innerHTML = slideItem.photoCredit;
		}
	}
	
	function registerNewPageRefresh()
	{	    
	    try
	    {
	        //Refresh the Island ad
	        var adIframe = document.getElementById("slideshowBannerAdIframe");
	        if(adIframe)
	        {
		        adIframe.src = slideshow_adIframeSrc;
	        }
		else
		{
			dapMgr.trackEvent(eventType.click);
		}
        	
	        //Track page refresh OMNI
	        OMNTRPageTracking(JS_OMNTR_COMPANY, JS_OMNTR_CATEGORY, JS_SITE, JS_SECTION, JS_SUB_SECTION, null, null, null, JS_OMNTR_SUITEID);
        	
	        //Track page refresh NIELSEN
	        _rsSlideShowEvent(JS_SITE);
	    }
	    catch (ex)
	    {
	        // Suppress Ad / Tracking errors from client, render in debugger window if available     
	        if (window.debout) 
	            debout(ex.description);
	    }
	}

	function _onThumbnailVisible(carousel, el, index, state)
	{
		switch (index)
	    {
	        case carousel.size():
	            /* hide next button */           
	            $("#thumbnails .jcarousel-next-horizontal").hide();
	            break;
	            
	        case 1:
	            /* hide back button */           
	            $("#thumbnails .jcarousel-prev-horizontal").hide();
	            break;
	            
	        default:
	            break;
	    
	    }
	}
	
	function _onThumbnailHidden(carousel, el, index, state)
	{
		switch (index)
	    {
	        case carousel.size():
	            /* display next button */  	                 
	            $("#thumbnails .jcarousel-next-horizontal").show();
	            break;
	            
	        case 1:
	            /* display back button */ 
	            $("#thumbnails .jcarousel-prev-horizontal").show();
	            break;
	            
	        default:
	            break;
	    }
	}
	
	function _onThumbnailInit(carousel, state)
	{
		if(state == "init")
		{
			g_thumbCarousel = carousel;
			$("#thumbnails .jcarousel-next-horizontal").click(function(){
				recalculateThumbnailRange(parseInt(carousel.first) + g_thumbRangeScroll, true);
			});
			$("#thumbnails .jcarousel-prev-horizontal").click(function(){
				recalculateThumbnailRange(parseInt(carousel.first - 1), false);
			});
		}
	}
	
	$("#thumbnails").css("visibility", "visible");

	//Init thumbnails carousel
	$("#thumbCarousel").jcarousel({
	    scroll: g_thumbRangeScroll,
		animation: "fast",
		initCallback: _onThumbnailInit,
		itemVisibleInCallback: _onThumbnailVisible,
		itemVisibleOutCallback: _onThumbnailHidden
	});
	
	var hash = document.location.hash;
	if (hash.indexOf('#') >= 0)
	{
		var startLocation = parseInt(hash.substring(1, hash.length));
		if(isNaN(startLocation) || startLocation < 1)
		{
			startLocation = 1;
		}
		else if(startLocation > allSlideshowImages.length)
		{
			startLocation = allSlideshowImages.length;
		}
	}

	//Init main image slideshow
	$("#mainImgCarousel").jcarousel({
		scroll: 1,
		start: startLocation,
		animation: ((window.slideshow_mainSlideAnimationLen || window.slideshow_mainSlideAnimationLen == "0") ? isNaN(parseInt(window.slideshow_mainSlideAnimationLen)) ? window.slideshow_mainSlideAnimationLen : parseInt(window.slideshow_mainSlideAnimationLen) : "fast"),
		initCallback: _onInit,
		itemLoadCallback: _onItemLoad
	});

	//Adding hover classes to next/prev divs for IE6
	$('.jcarousel-skin-main .jcarousel-next-horizontal').hover(function() {
		$(this).addClass('jcarousel-next-hover');
	}, function() {
		$(this).removeClass('jcarousel-next-hover');
	});

	$('.jcarousel-skin-main .jcarousel-prev-horizontal').hover(function() {
		$(this).addClass('jcarousel-prev-hover');
	}, function() {
		$(this).removeClass('jcarousel-prev-hover');
	});

	//Synchronising next/prev to move the slideshow to the next/prev image
	$("#slideshowAjax .photoFunctions .photoNavigation .next a").click(function() {
		$("#photoContainer .jcarousel-skin-main .jcarousel-container .jcarousel-next").click();
	});
	$("#slideshowAjax .photoFunctions .photoNavigation .back a").click(function() {
		$("#photoContainer .jcarousel-skin-main .jcarousel-container .jcarousel-prev").click();
	});
	
	//Attaching tooltip to all thumbnail images
	$("#thumbCarousel li a").tooltip({ 
		track: true,
		delay: 0,
		showURL: false,
		top: -35,
		left: -5
	});
	
	//Remove the alt text so the browser defualt tooltip does not appear
	$("#thumbCarousel li a img").removeAttr("alt");

	//Setting 80% opacity to thumbnails and next/prev buttons
	$("#thumbnails, .jcarousel-skin-main .jcarousel-prev-horizontal, .jcarousel-skin-main .jcarousel-next-horizontal").css("opacity", 0.8);	
	$("#thumbnails").hide();

	//Show/hide thumbnails and change text of button
	$("#showThumbsBtn").click(function() {
		var isLoaded = $("#thumbnails").attr("isLoaded");
		if(!isLoaded)
		{//Load all thumbnails through resizer when the thumbnails are first requested
			for(var i = 0; i < allSlideshowImages.length; i++)
			{
				var slideItem = allSlideshowImages[i];
				var thumbnails = $("#thumbnails li a img");
				var thumbImg = thumbnails[i];
				if(thumbImg)
				{
					var resizeUrl = slideItem.img;
					if(resizeUrl.substring(0, 1) == "/")
					{
						resizeUrl = "http://" + document.location.host + resizeUrl;
					}
					thumbImg.src = "http://images.ninemsn.com.au/resizer.aspx?url=" + resizeUrl + "&height=48";
				}
			}

			$("#thumbnails").attr("isLoaded", "true");
		}
		
		$("#thumbnails").slideToggle(200);
		var BTN_SHOW_TEXT = "Show thumbnails";
		var BTN_HIDE_TEXT = "Hide thumbnails";
		var showHideBtn = document.getElementById("showThumbsBtn")
		if(showHideBtn && showHideBtn.innerHTML == BTN_SHOW_TEXT)
		{
			$("#thumbnails").attr("isShowing", "true");
			//Move thumbnails to current position
			updateCurrentThumb();
			showHideBtn.innerHTML = BTN_HIDE_TEXT;
		}
		else if(showHideBtn)
		{
			$("#thumbnails").attr("isShowing", "false");
			showHideBtn.innerHTML = BTN_SHOW_TEXT;
		}
	});

	/**
	 * JCarousel does something perculiar by binding to the window.onresize event.  When the event fires, JCarousel exectues
	 * its "Prev" function to make the carousel move back.  This functionality makes no sense and also causes problems with
	 * our implementation.  We unbind from the event here to avoid this.
	 */
	$(window).unbind('resize');
	
	//Turn off loading sign and show slideshow content
	$("#slideshowLoadingPlaceholder").hide();
	$("#photoContainer, .photoTop .photoFunctions, .sl_right .infoBlock, #currentPhotoCredit").css("visibility", "visible");
});