// Homepage slideshow system
var
	currentImage, 
	currentIndex = -1,
	myTimer, 
	totalScreens = 1,
	currentScreen = 1,
	images = [];

$(document).ready(function () {

	setupSlideshow();
});


// Hide unused slider navigation buttons
function hideUnusedButtons() {
	
	currentScreen == 1 ? $('div#navigation .buttons a.back').hide() : $('div#navigation .buttons a.back').show();
	currentScreen == totalScreens ? $('div#navigation .buttons a.forward').hide() : $('div#navigation .buttons a.forward').show();
	
}

/*
get and parse XML, 
apply the data to the html, 
adapt css accordingly:
 - set container size based on image size,
 - create margins.
call subsequent functions when images are loaded
*/

function setupSlideshow() {

	$('#slideshow').append('<div class="loading-box"><span>loading</span></div>');

	$.ajax({
		type: "GET",
		url: "media/adrianalanmedia/slideshow/slideshow.xml",
		dataType: "xml",
		success: function (xml) {
			$(xml).find('slide').each(function (index, domEle) {

				// Get object data
				var
					title = $(this).find('title').text(),
					description = $(this).find('description').text(),
					mainImage = $(this).find('main-image').text(),
					thumb = $(this).find('thumb-image').text(),
					url = $(this).find('url').text();

				// Create container for slide
				$('div#slideshow').append('<div class="container" />');

				// Create invisible container for title and description
				$('body').append('<div style="display:none" id="data-container"></div>');
				
				// Insert values into invisible container
				$('div#data-container').html(title + ' - ' + description);
				
				// Find tags and alt attribute and store them on variables
				var
					altAttr = $('div#data-container').text(),
					imgTag = '<img' + ' src="media/adrianalanmedia/slideshow/' + mainImage + '" alt="' + altAttr + '" />',
					titleTag = '<div class="title">' + title + '</div>',
					descriptionTag = '<div class="body">' + description + '</div>',
					thumbImgTag = '<img' + ' src="media/adrianalanmedia/slideshow/' + thumb + '" alt="' + altAttr + '" />';

				// Append elements to slide container and define the target location on click
				$('div#slideshow div.container:last').append(imgTag).append(titleTag).append(descriptionTag).click(function () {

					window.location = url;

				});

				// Insert thumb image tag into its container
				$('div#navigation div.thumbs-container div.thumbs-inner').append(thumbImgTag);

			});

			// Create a variable to store the number of the total loaded thumbnails
			var loadedThumbs = 0;

			// On image load
			$('div#navigation div.thumbs-container div.thumbs-inner img').load(function () {
				
				// increment loaded thumbs counter
				loadedThumbs++;

				// *** if all images are loaded *** , calculate the margins of the thumbnails and set up navigation button events
				if (loadedThumbs == $('div#navigation div.thumbs-container div.thumbs-inner img').length) {

					// Create a variable for the width of the current serie of thumbs
					var
						serieWidth = 0;
						
					// Loop through all thumbnails
					for (var i = 0; i < $('div#navigation div.thumbs-container div.thumbs-inner img').length; i++) {

						// Increment the serie width with the current image widh
						serieWidth += $($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).width()

						// Plus the margins
						+ parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-right').replace('px', ''))
						+ parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-left').replace('px', ''));


						// If the width is bigger than the container, go to next serie
						if (serieWidth >= 835) {

							// Increment screen (serie) counter
							totalScreens++;

							// Fill the rest of the current serie by setting the margin-right of the last thumb to
							$($('div#navigation div.thumbs-container div.thumbs-inner img')[i - 1]).css('margin-right',

							// The size of the last image of the current serie plus the right margin (that will be substituted)
							parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i - 1]).css('margin-right').replace('px', '')) +

							// The size of the container (835) minus the width of the images in this serie
							835 - (serieWidth -
							
							// Substract the width of the first image of the next serie (incremented on the last occurence of the loop)
							$($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).width() 
							
							// Substract also the margins of the reffered image
							- parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-right').replace('px', ''))
							- parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-left').replace('px', ''))
							
							)

							)
							
							// Set the serie width to the size of the current thumb imqge
							serieWidth = $($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).width()

							// Add the margins
							+ parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-right').replace('px', ''))
							+ parseInt($($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).css('margin-left').replace('px', ''));
						}
						
						// Add a variable to the current thumbnail image element with the value of its serie (page) number
						$($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).data('serie', totalScreens);
						
						// Add a class to the current thumbnail image element with the value of its serie (page) number
						$($('div#navigation div.thumbs-container div.thumbs-inner img')[i]).addClass('serie' + totalScreens);


					}
					// set container width to total screens times container total width
					$('div#navigation div.thumbs-container div.thumbs-inner').width(totalScreens * 835);
					
					//remove loading
					$('#slideshow div.loading-box').remove();
					
					//load first image
					showNext(true); 
					
					// setup navigation via clicking on thumbs					
					$('div#navigation img').each(function (index, domEle) {

						$(domEle).bind('click', function () {
							$('div#navigation img').removeClass('active');
							$(domEle).addClass('active');

							showImage($(domEle).index(), false, 1500);

						})
					})

					hideUnusedButtons();

					// setup navigation button events
					if (totalScreens > 1) {

						$('div#navigation .buttons a.back').click(function () {
						
							if (currentScreen > 1) {
								$('div#navigation div.thumbs-container div.thumbs-inner').animate({
									marginLeft: "+=835"
								}, 1500);
								
								currentScreen--;
								
								
								hideUnusedButtons();
								
								//Show first image of this serie
								$('div#navigation img').removeClass('active');
								$('div#navigation div.thumbs-container div.thumbs-inner img.serie' + currentScreen + ':first').addClass('active');
								

								showImage($('div#navigation div.thumbs-container div.thumbs-inner img.active').index(), false, 1500);
								
							}
							return false;
						});
						$('div#navigation .buttons a.forward').click(function () {
							if (currentScreen < totalScreens) {
								$('div#navigation div.thumbs-container div.thumbs-inner').animate({

									marginLeft: '-=835'

								}, 1500);
								currentScreen++;
							
								hideUnusedButtons();
							
								//Show first image of this serie
								$('div#navigation img').removeClass('active');
								$('div#navigation div.thumbs-container div.thumbs-inner img.serie' + currentScreen + ':first').addClass('active');
								

								showImage($('div#navigation div.thumbs-container div.thumbs-inner img.active').index(), false, 1500);
							
							}
							return false;
						});

					} else {

						$('div#navigation .buttons a.back').click(function () {
							$('.wishListItemQuantity').html(currentIndex);
							var len = $('div#navigation img').length;
							var next = currentIndex > 0 ? currentIndex - 1 : len - 1;
							showImage(next, 300);
							return false;
						});
						$('div#navigation .buttons a.forward').click(function () {
							$('.wishListItemQuantity').html(currentIndex);
							var len = $('div#navigation img').length;
							var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

							showImage(next, false, 300);
							return false;
						});
						/*
						
						Pause and play buttons disabled
						
						$('div#navigation .buttons a.pause').click(function () {
							$('div#navigation .buttons a.play').toggleClass('active');
							$('div#navigation .buttons a.pause').toggleClass('active');
							clearTimeout(myTimer);
							return false;
						});
						$('div#navigation .buttons a.play').click(function () {
							$('div#navigation .buttons a.play').toggleClass('active');
							$('div#navigation .buttons a.pause').toggleClass('active');
							clearTimeout(myTimer);
							myTimer = setTimeout("showNext(false)", 5000);
							return false;
						});*/
					}
				}

			})


		}
	});

}



// Show main image

function showImage(index, firstTime, speed) {
	var indexImage = $('.imageNav li')[index]

	currentImage = indexImage;
	currentIndex = index;

	$('div#navigation div.thumbs-container div.thumbs-inner img.last-active').removeClass('last-active');
	if (!firstTime) $('div#navigation img.active').addClass('last-active');
	$('div#navigation div.thumbs-container div.thumbs-inner img').removeClass('active');
	$($('div#navigation div.thumbs-container div.thumbs-inner img')[index]).addClass('active');

	//alert($('div#navigation div.thumbs-container div.thumbs-inner img.active').data('serie'));

	if ($('div#navigation div.thumbs-container div.thumbs-inner img.active').data('serie') != currentScreen) {
		//alert($('div#navigation div.thumbs-container div.thumbs-inner img.active').data('serie') + ' - ' + currentScreen);
		$('div#navigation div.thumbs-container div.thumbs-inner').animate({
			marginLeft: -($('div#navigation div.thumbs-container div.thumbs-inner img.active').data('serie') - 1) * 835
		}, 1500);
		currentScreen = $('div#navigation div.thumbs-container div.thumbs-inner img.active').data('serie');
		hideUnusedButtons();
	}
	
	$('div#slideshow > div').stop();
	$($('div#slideshow > div')[index]).css({
		'z-index': 8,
		'opacity': 0
	}).fadeTo(speed, 1, function () {

		$('div#slideshow > div').css({
			'z-index': 6,
			'display': 'none'
		})
		$($('div#slideshow > div')[index]).css({
			'z-index': 7,
			'display': 'block'
		})

	});




	clearTimeout(myTimer);
	myTimer = setTimeout("showNext(false)", 5000);


}

// Change slide

function showNext(firstTime) {

	var len = $('div#navigation img').length;
	var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;

	showImage(next, firstTime, 1500);

}




