$(function()
{ // shortcut for: $(document).ready(function() {});
	
	// GLOBAL vars
	var categoryId = 1; 		// = Downloads category
	var selectedGallery = "cat-2";	// = Wallpapers
	var galleryNavigation = null;
	var galleryData = new Array();
	
	// load data
	$.get( 'includes/bi_downloads.xml', loadGalleryXml );
	
	function loadGalleryXml( xml )
	{
		$('category', xml).each(function()
		{
			var $category = $(this);
			
			if($category.attr('id') == categoryId)
			{ // Downloads
				$('gallery', $category).each(function()
				{
					$gallery = $(this);
					$ul = $('ul#gallery');
					// $ul.empty();
					
					$('item', $gallery).each(function()
					{
						$item = $(this);
						var captionArr = new Array();
						
						$('link', $item).each(function()
						{
							// build caption
							var captionObj = {
								title:	$(this).attr('title'),
								url:	$(this).attr('url')
							}
							captionArr.push(captionObj);
							
						}); // END $('link', $item).each(function()
						
						var galleryObj = {
							id:			$item.attr('id'),
							title:		$item.attr('title'),
							image:		$item.attr('image'),
							thumb:		$item.attr('thumb'),
							captions:	captionArr
						};
						
						$li = $('<li />')
								.data('captions', galleryObj.captions);
						$a = $('<a />')
								.attr('title', galleryObj.title)
								.attr('href', galleryObj.image);
						$img = $('<img />')
								.attr('alt', galleryObj.title)
								.attr('src', galleryObj.thumb)
								.attr('width', 100)
								.attr('height', 75);
						$ul.append($li.html($a.html($img)));
						
					}); // END $('item', $gallery).each(function()
					
					//alert($ul.html());
					
				}); // END $('gallery', $category).each(function()
				
			} // END if
			
		}); // END $('category', xml).each(function()
		
		// build gallery
		buildGallery();
	}
	
	// build gallery
	function buildGallery()
	{
		// assign unique index to each gallery list element
		$('#gallery li').each(function(idx)
		{
			$(this).data('index', (++idx));
		});
		
		// hide all thumbnails until loaded
		$('#gallery li img').css('opacity', 0).each(function()
		{
			// when img is loaded, animate opacity to 1
			if (this.complete || this.readyState == 'complete') { $(this).animate({'opacity': 1}, 300) }
			else { $(this).load(function() { $(this).animate({'opacity': 1}, 300) }); }
		});
		
		// set up links to each gallery
		/*
		$('#galleries li').each(function()
		{
			$(this).bind( 'click', selectGallery );
		});
		*/
		
		// START Galleria setup
		$('#gallery').galleria(
		{
			// #img is an empty div which holds the full size images
			insert: '#img',
			
			// enable history plugin
			history: true,
			
			// fired when the full sized image is displayed
			onImage: function(image, caption, thumb)
			{
				// fade in the image
				image.hide().fadeIn(500);
				
				// animate active thumbnail's opacity to 1, siblings to 0.6
				thumb.parent().fadeTo(200, 1).siblings().fadeTo(200, 0.6);
				
				var $li = thumb.parent();
				var captionsArr = $li.data('captions');
				var captionText = '<h2>Download '+caption.text()+'</h2>';
				for(var i=0; i<captionsArr.length; i++)
				{
					var captionObj = captionsArr[i];
					captionText += '<a href="'+captionObj.url+'">'+captionObj.title+'</a>';
				}
				
				// alert("caption : " + captionText);
				caption.html(captionText);
				//caption.html('<h2>Download '+caption.text()+'</h2><a href="#">1024x768</a> <a href="#">1280x1000</a>');
				
				// hide cation initially
				$('#img .caption').css('height', 25);
				
				// trigger image-loaded event so jCarousal can react
				// toggle show/hide caption on hover
				$('#img')
					.trigger('image-loaded')
					.hover(
						function(){ $('#img .caption').stop().animate({height:50}, 250) },
						function(){ $('#img .caption').stop().animate({height:20}, 250) }
					);
			},
			
			// similar to onImage, but fired when thumbnail is displayed
			onThumb: function(thumb)
			{
				// get thumbnail's parent li element
				var $li = thumb.parent();
				var opacity = $li.is('.active') ? 1 : 0.6;
				
				// hover effects for list elements
				$li.hover(
					function() { $li.fadeTo(200, 1); },
					function() {$li.not('.active').fadeTo(200, opacity); }
				);
			}
		}).find('li:first').addClass('active'); // displays first image when Galleria is loaded
		// END Galleria setup
		
		// START jCarousel setup
		$('#gallery').jcarousel(
		{
			scroll: 3,
			visible: 4,
			initCallback: initCallbackFunction
		});
		// END jCarousel setup
	}
	
	// callback function for jCarousel
	function initCallbackFunction(carousel, state)
	{
		if( state == 'init' )
		{
			galleryNavigation = carousel;
		}
		
		// bind "image-loaded" event to the #img container (we trigger it inside onImage function)
		$('#img').bind('image-loaded', function()
		{
			// find 'index' data of the active thumbnail 
			var idx = $('#gallery li.active').data('index');
			
			// scroll carousel and center the active list item
			carousel.scroll(idx);
			return false;
		});
		
		// next image
		$(document).bind('keydown', 'right', function (evt){ $.galleria.next(); });
		
		//prev image
		$(document).bind('keydown', 'left', function (evt){ $.galleria.prev(); });
		
		// scoll x items to the right
		$(document).bind('keydown', 'up', function (evt){ $('.jcarousel-next-horizontal').click();  return false; });
		
		// scoll x items to the left
		$(document).bind('keydown', 'down', function (evt){ $('.jcarousel-prev-horizontal').click();  return false; });
	}
	
	// callback function for jCarousel
	/*
	function loadGalleryData(carousel, state)
	{		
		if(state == 'init')
		{
			console.log("loadGalleryData(state="+state+")");
			// build gallery list for selected gallery
			console.log("loadGalleryData: galleryData["+selectedGallery+"]: " + galleryData[selectedGallery]);
			if(galleryData[selectedGallery] != undefined)
			{
				var galleryArr = galleryData[selectedGallery];
				var $ul = $('ul#gallery');
				
				if($ul.length > 0)
				{
					console.log("loadGalleryData: ul#gallery found");
				}
				else
				{
					console.log("loadGalleryData: ul#gallery NOT found!!!");
				}
				
				// $ul.empty();
				console.log("galleryArr.length: " + galleryArr.length);
				
				for( var i=0; i<galleryArr.length; i++)
				{
					var galleryItem = galleryArr[i];
					/*
					console.log("loadGalleryData: galleryItem["+i+"] = "+galleryItem);
					var $li = $('<li />');
					var $a = $('<a />')
						.attr('href', galleryItem.image)
						.attr('title', galleryItem.title);
					var $img = $('<img />')
						.attr('src', galleryItem.thumb)
						.attr('alt', galleryItem.title)
						.attr('width', 100)
						.attr('height', 75);
					
					$a.html($img);
					$li.html($a);
					$ul.append($li);
					*//*
					// galleryNavigation.add(i, galleryItem.thumb);
					galleryNavigation.add(i, '<a href="images/downloads/wallpaper/BI_heroTerracore.jpg" title="BI_heroTerracore"><img src="images/downloads/wallpaper/BI_heroTerracore_tn.jpg" width="100" height="75" alt="BI_heroTerracore" /></a>');
					
					if( i == 0 )
					{
						// $myGallery.activate('<img src="images/downloads/wallpaper/BI_heroTerracore.jpg />');
					}
				}
				
				console.log("gallery: " + $ul);
				
				// select first item
				// .find('li:first').addClass('active'); // displays first image when Galleria is loaded
				// $ul.find('li:first').addClass('active'); 
			}
			else
			{
				// TODO add error handling
				// $("li#"+selectedGallery).trigger('click');
				alert("Something went horribly horribly wrong...");
			}
		}
	}
	*/
	// click handler for gallery list
	/*
	function selectGallery( evt )
	{
		var galleryId = this.id;
		// var $li = $('li#'+this.id);
		console.log("selectGallery: " + galleryId);
		// load the selected gallery if not already cached
		if( !galleryData[galleryId] )
		{
			// move xml parsing to function...
			$.get( 'includes/bi_downloads.xml', function(xml)
			{
				// search category elements for 'Downloads'
				$('category', xml).each(function()
				{
						var $category = $(this);
						var title = $category.attr('title');
						var id = $category.attr('id');
						
						console.log("category: " + title);
						
						if($category.attr('id') == categoryId)
						{
							//$category.find('gallery').each(function()
							$("gallery", xml).each( function()
							{
								console.log("menu: " + $(this).attr('title') + ", id: " + $(this).attr('id'));
								if( ("cat-"+$(this).attr('id')) == galleryId )
								{
									selectedGallery = "cat-"+$(this).attr('id');
									
									$gallery = $(this);
									var galleryArr = new Array();
																		
									//$gallery.find('item').each(function()
									$("item", xml).each( function()
									{
										$item = $(this);
										console.log("new item found: " + $item.attr('title') + ", id: " + $item.attr('id'));
																				
										// build caption
										var captionArr = new Array();
										//$item.find('link').each(function()
										$("link", xml).each( function()
										{
											var captionObj = {
												title:	$(this).attr('title'),
												url:	$(this).attr('url')
											}
											
											captionArr.push(captionObj);
										});
										
										var galleryObj = {
											id:			$item.attr('id'),
											title:		$item.attr('title'),
											image:		$item.attr('image'),
											thumb:		$item.attr('thumb'),
											captions:	captionArr
										};
										galleryArr.push( galleryObj );
										console.log("galleryObj = " + galleryObj);
										console.log("added to galleryArr. length: " + galleryArr.length);
										
									});
									
									galleryData[galleryId] = galleryArr;
									console.log("selectGallery: galleryData["+galleryId+"]: " + galleryData[galleryId]);
									galleryNavigation.reset();
								}
							});
						}
					});				
			});
		}
		else
		{
			console.log("calling reset.");
			galleryNavigation.reset();
		}
		
	};
	*/
});