function preloadPhotoGalleryImages()
{
	var slides = $('#PhotoGallery').find('li[src]');
	if(slides.size() > 0)
	{
		slides.addClass('loading');
		preloadSlideImage(slides.filter(':first'));
	}
}

function preloadSlideImage(slide)
{
	var slideImg = jQuery('<img style="display:none">');
	
	slideImg
		.appendTo(slide)
		.load(function()
					{
						var img = jQuery(this);
						img.css('display', 'block')
						
						var slide = img.parent();
						slide.removeClass('loading');
						
						var nextSlide = slide.next('li[src]');
						if(nextSlide.size() > 0)
							preloadSlideImage(nextSlide);
					});
	slideImg.attr('src', slide.attr('src'));
}

function initPhotoGallery()
{	
	if($('#PhotoGallery').size() > 0)
	{
		preloadPhotoGalleryImages();
		
		$('#PhotoGallery')
			.after('<div id="PhotoGalleryNav">' +
						'<a href="#" id="prev">&lt;&lt; prev</a>' +
						'<h3 id="title"></h3>' +
						'<a href="#" id="next">next &gt;&gt;</a>' +
					'</div>')
			.find('ul')
			.cycle({
						timeout: 0,
						next:   '#next', 
						prev:   '#prev',
						after: function()
								{ 
									$('#title').html($(this).attr('title'));
								}
					})
	}
}

function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  
function initAnimatedScroll()
{
 var locationPath = filterPath(location.pathname);
  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') )
	{
      var $target = $(this.hash), target = this.hash;
      if (target)
	  {
        var targetOffset = $target.offset().top;
        $(this)
			.click(function(event)
					{
			          event.preventDefault();
					$('html, body')
						.animate({
								 	scrollTop: targetOffset
								}, 
								'slow', 
								function()
								{
						            location.hash = target;
						         }
								);
			        });
      }
    }
  });
}

// global array var for storing information about the right gallery slides
var SideSlides = new Array();

// builds the initial HTML display, containing the loaders indicators, loads the XML containing the gallery info and updates the SideSlides array, then calls rotateSideGallery()
function initSideGallery()
{
	if(jQuery('.TwoColContent .col2').size() == 0)
		return;
	initSideGalleryDisplay();
	// read and parse XML data
	 jQuery
		.ajax({
				 type: "GET",
				 url: 'assets/common/xml/side_gallery.xml',
				 dataType: "xml",
				 success: function(xml)
							{
								var xmlData = jQuery(xml).find('gallery');
								var xmlSlidesLocation = xmlData.find('>slidesLocation').text();
								xmlSlides = xmlData.find('>slides>slide');
								
								xmlSlides
									.each(function(index)
											{
												var slideInfo = jQuery(this);			
												SideSlides.push({
																	thumbnail: xmlSlidesLocation + slideInfo.find('thumbnail').text(), 
																	title: slideInfo.find('title').text()
																});
											});
								rotateSideGallery();
				 },
				 error: function(err)
						{
							alert('Invalid XML file');
						}
			  });
}

// periodically updates the slides displayed
function rotateSideGallery()
{
	updateDisplaySlides();
	setInterval(updateDisplaySlides, 10000);
}

//builds the initial HTML display, containing the loaders indicators
function initSideGalleryDisplay()
{
	var lis = '';
	for (var i=0; i<3; i++)
		lis += '<li><img src="assets/common/img/side_gallery/loading.gif" title="loading" /></li>';
	jQuery('.TwoColContent .col2')
		.html(
				'<ul id="SideGallery">' +
					lis + 
				'</ul>'
			);
}

// updates the displayed slides
function updateDisplaySlides()
{
	// filter slides other than the ones currently displayed
	var slidesNotDisplayed = filterDisplaySlides(SideSlides);
	
	// get new random slides
	var SlidesToDisplay = new Array();
	for (var j=0; j<3; j++)
	{
		var idx = getRandomInt(slidesNotDisplayed.length - 1);
		SlidesToDisplay[j] = slidesNotDisplayed[idx];
		slidesNotDisplayed = extractArrayItem(slidesNotDisplayed, idx);
	}
	
	// update slide images with animation
	jQuery('#SideGallery img')
		.each(function(i)
				{
					var img = jQuery(this);
					 img.attr({
								newSrc: SlidesToDisplay[i].thumbnail,
								newTitle: SlidesToDisplay[i].title
							  })
						.fadeTo(300, 0.01, function()
												{
													var nm = jQuery(this);
													nm
														.unbind('load')
														.load(function()
															{
																var inm = jQuery(this);
																inm.fadeTo(300, 1)
															})
														.attr({
																src: nm.attr('newSrc'),
																title: nm.attr('newTitle')
															});
												});
				});
		
	slidesNotDisplayed = null;
}

// filter slides other than the ones currently displayed
function filterDisplaySlides(Slides)
{
	var SlidesDisplayed = jQuery('#SideGallery img');
	if(SlidesDisplayed.size() != 0)
	{
		var slideFilter = new Array();
		SlidesDisplayed
			.each(function()
					{
						var it = jQuery(this);
						slideFilter.push(it.attr('title')); // the filter array contains the image titles
					});
		return extractSlides(Slides, slideFilter);
	}
}

// extracts the slides from a given slides array, based on a slide filter containing image titles
function extractSlides(Slides, SlidesFilter)
{
	var arrRes = Slides.slice();
	for (var j=0; j<SlidesFilter.length; j++)
	{
		for (var i=0; i<arrRes.length; i++)
		{
			if(arrRes[i].title == SlidesFilter[j])
				{
					arrRes = extractArrayItem(arrRes, i);
					break;
				}
		}
	}
	
	return arrRes.slice();
}

// returns a random int from 0 to Max
function getRandomInt(Max)
{
	return Math.floor(Math.random()*(Max+1));
}

// extract an element from an array and returns the new array
function extractArrayItem(array, itemIndex)
{
	var arrRes = array.slice();
	for (var i=itemIndex; i<arrRes.length-1; i++)
		arrRes[i] = arrRes[i+1]
		
	arrRes.pop();
	return arrRes.slice();
}

function initHomeGallery()
{
	if($('#HomeGallery').size() > 0)
	{
		
		$('#HomeGallery ul')
			.cycle({
					timeout: 4000
				})
	}
}

function initPressGallery()
{
	var pressGallery = jQuery("#PressReviewsGallery");
	if(pressGallery.size() > 0)
	{
		jQuery("#PressReviewsGallery")
			.scrollable({
					items: "ul",
					prev: "#PressReviewsGalleryPrevious",
					next: "#PressReviewsGalleryNext",
					size: 4,
					loop: true,
					clickable: false
				    });
			
		  $('#PressReviewsGallery li')
			.each(function()
				{
					jQuery(this).find('a.lightbox')
						.lightBox({
								imageLoading:			'assets/common/img/jquery.lightbox/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
								imageBtnPrev:			'assets/common/img/jquery.lightbox/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
								imageBtnNext:			'assets/common/img/jquery.lightbox/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
								imageBtnClose:			'assets/common/img/jquery.lightbox/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
								imageBlank:			'assets/common/img/jquery.lightbox/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel),
								txtImage:			'',
								fixedNavigation:		true
							  });
				})
	}
}

jQuery(function(){
	initHomeGallery();
	initSideGallery();
	initPhotoGallery();
	initPressGallery();
	initAnimatedScroll();
})
