//var activeImageLink;
var currentShoot;
var myLightbox;
var currentShootScrollPage = 	1;
var shootCount;
var shootScrollerPages;

function initGallery()
{
	// quit if this function has already been called
	if (arguments.callee.done) return;

	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;

	// kill the timer
	if (_timer) clearInterval(_timer);

	myLightbox = new Lightbox();
	myLightbox.initContainer($('galleryWrapper'));
	
	if ($('shoots')) initShootSelector();
	
	if ($('otherGalleriesHeading')) 
	{
		Element.insert('otherGalleriesHeading', 
		{ 
			before: '<a id="picLensLink" class="pngImage" href="#"><strong>NEW!</strong> View on 3D wall with PicLens</a>' 
		});
	
		Element.observe('picLensLink', 'click', function(e) 
		{ 
			launchPicLens(picLensFeed); 
			Event.stop(e);
		});
	}
}

function initShootSelector()
{
	var shootLinks 				= $$('#shootsList a');
	var galleryWrapper			= $('galleryWrapper');
	var galleryWrapperInner		= $('galleryWrapperInner');
	var shootsContainer			= $('shoots');
	var shootsListWrapper 		= $('shootsListWrapper');
	currentShoot				= $$('.aShoot')[0];
	var currentShootDimensions 	= Element.getDimensions(currentShoot);
	
	shootCount = shootUrls.length - 1;
	shootScrollerPages = Math.ceil(shootCount/9);
	
	// Insert extra controls
	Element.insert(galleryWrapper, 		{ top: '<img id="gallerySpinner" src="/images/signin_spinner.gif"/>'} );
	Element.insert(shootsContainer, 	{ top: '<a href="#" class="shootScroller inactive" id="prevShoot">Previous Shoots</a>'} );
	Element.insert(shootsContainer, 	{ bottom: '<a href="#" class="shootScroller inactive" id="nextShoot">Next Shoots</a>'} );
	Element.insert('shootsListWrapper', { top: '<div id="frame"></div>'} );
	
	// Set initial styles
	galleryWrapper.setStyle({ height: (currentShootDimensions.height+40)+'px'});
	galleryWrapperInner.setStyle({ height: '5000px'});
	shootsContainer.setStyle({ marginLeft: '0px'});
	shootsListWrapper.setStyle({ overflow: 'hidden' });
	$('shootsList').setStyle({ width: (shootCount * 99) + 'px' });
	$('frame').setStyle({ left: (currentShootIndex * 99 + 1) + 'px' });
	$('shootsListWrapper').scrollLeft = 0;
	
	// Add behavior to each shoot link 
	shootLinks.each(function(link)
	{
		Element.observe(link, 'click', function(e)
		{			
			$('gallerySpinner').style.display = 'block';

			new Effect.Morph($('frame'),
			{				
				style: 		'left: ' + (link.rel * 99 + 1) + 'px',
				duration: 	0.3  
			});

			var gallery = $('shoot-' + link.name);
			if (gallery)
			{
				showGallery(gallery);
			}
			else
			{
				new Ajax.Request(baseUrl + 'gallery/name/' + modelFolder + '/shoot/' + link.name, 
				{ 
					asynchronous: 	false,
					insertion: 		Insertion.Top,
					onSuccess: 		function(transport)
					{
						//galleryWrapper.insert( { top: transport.responseText } );
						galleryWrapperInner.insert( { top: transport.responseText } );
						var newShoot = galleryWrapperInner.firstChild;
						
						newShoot.style.display = 'none';
						showGallery(newShoot);
						myLightbox.initContainer(newShoot); 	
					}
				});		
			}

			Event.stop(e);
		});
	});

	// Add behavior to scrolling buttons
	var shootScrollerLinks 		= $$('a.shootScroller');
	
	shootScrollerLinks.each(function(link)
	{
		Element.observe(link, 'click', function(e)
		{
			if (!Element.hasClassName(link, 'inactive'))
			{
				if (link.id == 'prevShoot') 
				{
					scrollAmount = -891;
					currentShootScrollPage--;
				}
				else 
				{
					scrollAmount = 891;
					currentShootScrollPage++;
				}
			
				var currentScrollLeft = shootsListWrapper.scrollLeft;
			
				new Effect.Tween
				(
					$('shootsListWrapper'), 
					currentScrollLeft, 
					currentScrollLeft + scrollAmount, 
					{ duration: 0.8 },
					function(s) 
					{
						this.scrollLeft = s;
					}
				);
			
				checkScrollerPosition();
			}
			Event.stop(e);

		});
	});
	
	checkScrollerPosition();
}

function checkScrollerPosition()
{
	if (currentShootScrollPage < shootScrollerPages) $('nextShoot').removeClassName('inactive');
	else $('nextShoot').addClassName('inactive');
	
	if (currentShootScrollPage > 1) $('prevShoot').removeClassName('inactive');
	else $('prevShoot').addClassName('inactive');
}

function showGallery(shoot)
{
	var effectDuration 			= 1;
	var newShootDimensions 		= Element.getDimensions(shoot);
	var galleryWrapper			= $('galleryWrapper');

	var wrapperDimensions		= Element.getDimensions(galleryWrapper);

	new Effect.Fade(currentShoot,
	{
		duration: 		0.2,
		afterFinish: 	function()
		{
			new Effect.Morph(galleryWrapper, 
			{
				style: 			'height: '+(newShootDimensions.height)+'px',
				duration: 		0.4
			});
			
			new Effect.Appear(shoot, 
			{
				duration: 		0.2,
				afterFinish: 	function()
				{
					$('gallerySpinner').style.display = 'none';
				}
			});
			currentShoot = shoot;
		}
	});	
}

function launchPicLens(url) 
{
	if (hasPicLensClient())
	{
		window.piclens.launch(url,'','');
	}
	else 
	{
		location.href = "/cooliris";
	}
}

function hasPicLensClient()
{
	// check if the bridge has already been defined
	var clientExists = false;

	if (window.piclens) 
	{
		clientExists = true;
	} 
	else 
	{
		// if not, try to define it here...
		var context = null;
		if (typeof PicLensContext != 'undefined') 
		{	// Firefox ONLY
			context = new PicLensContext();
		} 
		else 
		{	// IE ONLY
			try 
			{
				context = new ActiveXObject("PicLens.Context");
			} 
			catch (e) 
			{
				context = null;
			}
		}
		
	   	window.piclens = context;
		
		if (window.piclens) 
		{
			clientExists = true;
		}
	}
	
	if (clientExists) 
	{ 	// check the version number
		var version;
		try { version = window.piclens.version; } catch (e) { return false; }
					
		var parts = version.split('.'); // minimum version is: 1.6.0.824
		if (parts[0] > 1) {			    // a version 2.X product
			return true;
		} else if (parts[0] == 1) {	    // a 1.X product
			if (parts[1] > 6) {		    // a version 1.7.X product
				return true;
			} else if (parts[1] == 6) { // a 1.6 product
				if (parts[2] > 0) {	    // a version 1.6.1.X product
					return true;
				} else if (parts[2] == 0) {
					if (parts[3] >= 824) { // 1.6.0.824 or newer...
						return true;
					}
				}
			}
		}
		return false; // e.g., a 0.X product
	} else {
		return false;
	}
}

/* for Mozilla/Opera9 */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", initGallery, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			initGallery(); // call the onload handler
		}
	};
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
	var _timer = setInterval(function() {
		if (/loaded|complete/.test(document.readyState)) {
			initGallery(); // call the onload handler
		}
	}, 10);
}

/* for other browsers */
window.onload = initGallery;