/**
 *	Gallery and lightbox script for Entix modules.
 *		copyright 2008-2011 Entix, http://www.entix.nl/
 */

/*
 *	Global vars
 */
tableId = 'gallery';
embedId = 'image';
lightboxId = 'lightbox';
loadingImg = "content/images/loading.gif";
animated = true;
embed = false;
fixedWidth = false;
scroller = false;
scrollMode = 'center';
LightBoxOpen = false;
LightBoxGid = 0;
faderOpacity = 0;

// Slide duration will adjust for impatient user
slideDuration = 1000;
maxSlideDuration = 1000;
minSlideDuration = 300; // Don't go lower than this

pageChapter = 1; // Pagination vars
numChapters = 1;

nowViewing = new Array();
animationLock = false;
imageIsLoading = false;

lightBoxMin = {top:2, left: 5, right: 5, bottom: 4};

minWidth = 320;
minHeight = 260;

maxImageSize = {x: 800, y: 600};
maxOriginalSize = {x: 1024, y: 768};

imgList = new Array();
imgOrig = new Array();
imgNames = new Array();
imgDesc = new Array();
scrollList = new Array();

gallCount = new Array();
Ic1 = new Array();
Ic2 = new Array();

panning = false;
panTimer = null;
panEffect = new Array();

LbxEffect = null;
Ic1Effect = new Array();
Ic2Effect = new Array();
scrollFx = new Array();


/*
 *	Functions
 */

/*
 * Initialisation function
 *  (should be run on page load, after dependencies loaded)
 */
function entixGalleryInit() {
	var i=0;
	while ($(tableId+i)) {
		initGallery(i);
		i++;
	}
}

function initGallery(id) {
	var imgTable = $(tableId+id);
	var list = getImgList(imgTable);
	gallCount[id] = list[0].length;
	imgList = imgList.concat(list[0]);
	imgOrig = imgOrig.concat(list[1]);
	imgNames = imgNames.concat(list[2]);
	imgDesc = imgDesc.concat(list[3]);
	scrollList = scrollList.concat(getScrollList(id));
	
	if (embed) { // Image containers
		Ic1[id] = $$('#'+embedId+id+' .ic1')[0];
		if (animated)
			Ic2[id] = $$('#'+embedId+id+' .ic2')[0];
	} else {
		Ic1[id] = $$('#'+lightboxId+' .ic1')[0];
		if (animated)
			Ic2[id] = $$('#'+lightboxId+' .ic2')[0];
	}
	
	if (!embed && $(lightboxId)) // Lightbox effect
		LbxEffect = new Fx.Morph(lightboxId, {'link': 'cancel', duration: parseInt(.9*slideDuration), transition: Fx.Transitions.Sine.easeOut});
	else
		LbxEffect = new Fx();

	if (embed || id == 0) { // Lightbox only uses effects once, embed for each gallery present
		if (animated) {
			panEffect[id] = new Fx();
			Ic1Effect[id] = new Fx.Morph(Ic1[id], {'link': 'cancel', duration: parseInt(.8*slideDuration), transition: Fx.Transitions.Sine.easeOut});
			Ic2Effect[id] = new Fx.Morph(Ic2[id], {'link': 'cancel', duration: parseInt(slideDuration), transition: Fx.Transitions.Sine.easeOut, onComplete: function(){slideComplete(id)}});
		}
		scrollFx[id] = new Fx();
	}
	
	var myURI = new URI(window.location);
	checkForSpecifiedShot = parseInt(myURI.getData('s'));
	if (checkForSpecifiedShot == -1)
		checkForSpecifiedShot = imgList.length;
	//checkForSpecifiedShot = window.location.href.split("s=");
	var viewTo = (checkForSpecifiedShot) ? checkForSpecifiedShot - 1 : getNumFromGid(id);
	// Set nowViewing global
	nowViewing[id] = viewTo;
	
	if ($('iTotal'))
		$('iTotal').innerHTML = totalImgs; //imgList.length;
	if (scrollMode == 'circular') { // put first image in the center (moves half the images in front of the first)
		var scroll = imgTable.getElements('.scroll')[0];
		var scrollContain = imgTable.getElements('.scroll_contain')[0];
		var cur = Math.floor((imgList.length-1)/2);
		scrollMoveCircular(scroll, scrollContain, cur, 0);
	}
	if ( (checkForSpecifiedShot > 0 && viewTo <= imgList.length) || embed)
		openImage(id,viewTo,1);
	// events
	if ($('fade'))
		$('fade').addEvent('click', function(event){
			closeLightBox();
		});
	if ($('lb_prev'))
		$('lb_prev').addEvent('click', function(event){
			prevScreen();
		});
	if ($('lb_next'))
		$('lb_next').addEvent('click', function(event){
			nextScreen();
		});
	if ($('lb_close'))
		$('lb_close').addEvent('click', function(event){
			closeLightBox();
		});
	if ($('sc_prev'))
		$('sc_prev').addEvent('click', function(event){
			prevScreen();
		});
	if ($('sc_next'))
		$('sc_next').addEvent('click', function(event){
			nextScreen();
		});
	if (Ic1[id]) {
		if (embed && detailLbx)
			Ic1[id].addEvent('click', function(){
				openDetailLightBox();
			});
		else
			Ic1[id].addEvent('click', function(){
				nextScreen(id);
			});
	}
	if ($('lb_detail_img'))
		$('lb_detail_img').addEvent('click', function(event){
			nextDetail();
		});
	
	// add onclick events for image thumbnails
	imgTable.getElements('a > img').getParent().addEvent('click', function(event){
		event.stop(); //Prevents the browser from following the link.
		var imgnum = parseInt(this.id.substr(3));
		var gid = getGidFromNum(imgnum);
		openImage(gid,imgnum);
	});
	
	// window resize event
	window.addEvent('resize', function(){
		if (LightBoxOpen) {
			updateLightBoxSize();
		}
	});
	
	// extra functions
	if (typeof(galleryExtra) == 'function')
		galleryExtra(id);
}

function getImgList(oContain) {
	aList = new Array();
	aList[0] = new Array();
	aList[1] = new Array();
	aList[2] = new Array();
	aList[3] = new Array();
	var aAnchors = oContain.getElementsByTagName("a");
	for(var i=0; i<aAnchors.length; i++) {
		var oA = aAnchors[i];
		aList[0][i] = oA.href.split("'").join("%27"); // url
		aList[1][i] = $(oA).getParent().getElement('span').get('text'); // orig_url
		aList[2][i] = oA.getChildren('img').get('title'); // title
		if ($(oA).getParent().getElement('p'))
			aList[3][i] = $(oA).getParent().getElement('p').get('html'); // description
		else
			aList[3][i] = '';
	}
	return aList;
}

function getImgSrc(n) {
	// Choice in images?
	if (imgOrig[n] && imgList[n] != imgOrig[n]) { // Yes, image and original
		if (maxImageSize.x > maxOriginalSize.x && window.getSize().x - (lightBoxMin.right + lightBoxMin.left + 5) < maxImageSize.x) {
			//alert('image too wide, use original instead');
			return imgOrig[n];
		} else
		if (maxImageSize.y > maxOriginalSize.y && window.getSize().y - (lightBoxMin.top + lightBoxMin.bottom + 10) < maxImageSize.y) {
			//alert('image too high, use original instead');
			return imgOrig[n];
		}
	}
	return imgList[n];
}

function getScrollList(gid) {
	var list = new Array();
	if (embed) {
		var scroll = $(tableId+gid).getElements('.scroll')[0];
		if (scroll) {
			var j=0;
			var totalWidth = 0;
			for (var i=0; i<scroll.childNodes.length; i++) {
				if (scroll.childNodes[i].nodeType == 1) {
					list[j] = scroll.childNodes[i];
					totalWidth += scroll.childNodes[i].getSize().x;
					totalWidth += scroll.childNodes[i].getStyle('margin-left').toInt();
					totalWidth += scroll.childNodes[i].getStyle('margin-right').toInt();
					j++;
				}
			}
			scroll.setStyle('width', totalWidth);
			var containWidth = scroll.getParent().getSize().x;
			if (totalWidth < containWidth) { // Not enough to fill the scroll?
				scroll.parentNode.setStyle('width', totalWidth);
				var button = scroll.parentNode.parentNode.getElement('div.button.prev');
				if (button)
					button.setStyle('right', (button.getStyle('right').toInt() - (containWidth-totalWidth)));
			}
		}
	}
	return list;
}

function openImage(gid, num, instant) {
	// Set title and description
	setImgTitles(gid,num);
	// Open image
	if (!embed && $(lightboxId)) { // lightbox
		openLightBox(gid,num);
	} else if (embed && $(embedId+gid)) { // embed
		embedImage(gid,num,(instant ? 1 : 0));
	} else { // popup
		window.open(getImgSrc(num));
	}
}

function panImage() {
	// The times
	var scrolltime = 8000;
	var delaytime = 1000;
	// The vars
	var gid = getGidFromNum(NowViewing);
	var img = $(embedId+gid);
	var sx = screenImage.width - img.getSize().x;
	var sy = screenImage.height - img.getSize().y;
	// Reset pan effect
	if (panTimer)
		$clear(panTimer);
	panEffect[gid].cancel();
	// In animation, reset to next position fast
	if (animationLock) {
		panEffect[gid] = new Fx.Scroll(img, {
				'link': 'chain', 'duration': 750, 'transition': Fx.Transitions.Cubic.easeOut
		}).start(parseInt(sx/2),parseInt(sy/2));
	} else {
		// The effect
		panEffect[gid] = new Fx.Scroll(img, {'link': 'cancel', 'duration': scrolltime, 'transition': Fx.Transitions.Sine.easeInOut});
		// Set start position
		panEffect[gid].set(parseInt(sx/2),parseInt(sy/2));
		// The scroll function
		var scrollOut = function() {
			this.start(sx,sy).chain(function() {
				panTimer = (function(){
					this.start(0,0).chain(function() {
						panTimer = scrollOut.delay(delaytime, this);
					});
				}).delay(delaytime, this);
			});
		};
		// The start
		panTimer = scrollOut.delay(delaytime, panEffect[gid]);
	}
}

function openLightBox(gid,num) {
	inFade();
	$(lightboxId).style.display='block';
	LightBoxOpen = true;
	LightBoxGid = gid;
	nowViewing[gid] = num;
	
	// load image
	screenImage = new Image();
	screenImage.src = getImgSrc(num);
	slideTo(num,1);
	// preload
	nextShot = new Image();
	nextShot.src = (num+1 < imgList.length) ? getImgSrc(num+1) : getImgSrc(0);
	prevShot = new Image();
	prevShot.src = (num<1) ? getImgSrc(num-1) : getImgSrc(imgList.length-1);
}

function openSingleLightBox(img_url, name, x, y) {
	screenImage = new Image();
	screenImage.src = img_url;
	inFade();
	Ic1[0].setStyle('background-image', "url('"+loadingImg+"')");
	$(lightboxId).style.display='block';
	LightBoxOpen = true;
	window.setTimeout(function () { viewSingleLightBox( screenImage, Ic1[0] ); }, 150);
}
function viewSingleLightBox(loadImg, containImg) {
	if (!$(lightboxId) || !LightBoxOpen)
		return;
	if(loadImg.complete) { // Image is ready
		if ($('container'))
			$('container').style.cursor = '';
		var w = loadImg.width;
		var h = loadImg.height;
		containImg.setStyles({width: w, height: h, 'background-image': "url('"+loadImg.src+"')"});
		// Set desired dimensions
		$(lightboxId).setStyles({display: 'block', width: w});
		// Check positioning
		var lb_top = parseInt(getAvailHeight() / 2);
		var lb_left = parseInt(getAvailWidth() / 2);
		if (lb_top < lightBoxMin.top || lb_left < lightBoxMin.left) { // Lightbox too big
			if (lb_top < lightBoxMin.top) {
				h = (h + getAvailHeight()) - (lightBoxMin.top + lightBoxMin.bottom);
				lb_top = lightBoxMin.top;
			}
			if (lb_left < lightBoxMin.left) {
				w = (w + getAvailWidth()) - (lightBoxMin.left + lightBoxMin.right);
				lb_left = lightBoxMin.left;
			}
			containImg.setStyles({width: w, height: h});
		}
		$(lightboxId).setStyles({width: w, top: lb_top, left: lb_left});
	} else { // Image not ready (so presume it's downloading)
		if ($(lightboxId).getStyle('display') == 'none') { // lightbox still hidden
			if ($('container'))
				$('container').style.cursor = 'wait';
			var w = loadImg.width; var h = loadImg.height;
			if (w == 0 && h == 0) { w=minWidth; h=minHeight; }
			containImg.setStyles({width: w, height: h, 'background-image': "url('"+loadingImg+"')"});
			$(lightboxId).setStyles({display: 'block', width: w});
			var lb_top = parseInt(getAvailHeight() / 2);
			var lb_left = parseInt(getAvailWidth() / 2);
			$(lightboxId).setStyles({left: lb_left, top: lb_top});
		}
		window.setTimeout(function () { viewSingleLightBox(loadImg, containImg); }, 50);
	}
}

function openDetailLightBox(nofade) {
	if (!imgOrig[nowViewing[0]])
		return;
	var img = new Image();
	img.src = imgOrig[nowViewing[0]];
	if (!nofade)
		inFade();
	LightBoxOpen = true;
	var img_contain = $(lightboxId).getElement('div.img');
	window.setTimeout(function () { viewSingleLightBox(img, img_contain); }, 50);
}

function nextDetail() {
	closeLightBox(1);
	nextScreen();
	openDetailLightBox(1);
}

function embedImage(gid,num,instant) {
	// load image
	screenImage = new Image();
	screenImage.src = getImgSrc(num);
	slideTo(num,instant);
	// preload
	nextShot = new Image();
	nextShot.src = getImgSrc(getNextImgNum(gid,num));
	prevShot = new Image();
	prevShot.src = getImgSrc(getPrevImgNum(gid,num));
}

function closeLightBox(nofade) {
	LightBoxOpen = false;
	if ($(lightboxId))
		$(lightboxId).setStyle('display', 'none');
	if ($('container'))
		$('container').style.cursor = '';
	if (!nofade)
		unFade();
}

function inFade() {
	var fader = $('fade'); // get fader element
	if (!fader)
		return;
	
	if (faderOpacity == 0) // max opacity unknown, get from element
		faderOpacity = getOpacity(fader);
	else if (getOpacity(fader) > 0) // already fading/faded in
		return;
	fader.fade('hide'); // set opacity 0
	fader.setStyle('display', 'block'); // set display to block
	fader.fade(faderOpacity); // fade back to the max
}

function unFade() {
	var fader = $('fade'); // get fader element
	if (!fader)
		return;
	
	if (getOpacity(fader) < faderOpacity) {
		fader.get('tween').pause();
		fader.fade('hide');
	} else {
		fader.fade('out');
	}
}

function setImgTitles(gid, num) {
	if ($('iCurrent'))
		$('iCurrent').set('text', (pageChapter-1)*imgsPerPage+(parseInt(num)+1));//parseInt(num)+1);
	if ($('iUrl')) { // Title/URL
		$('iUrl').set('text', imgNames[num]);
		if ($('iUrl').get('tag') == 'a') {
			var url = (!imgOrig[num] ? imgList[num] : imgOrig[num]);
			$('iUrl').set('href', url);
			if ($('iUrl').get('text') == '') {
				var fname = url.replace(/^.*[\/\\]/g, '');
				$('iUrl').set('text', fname);
			}
		} else if ($('iUrl').get('tag') == 'p' && imgNames[num] == '') {
			$('iUrl').setStyle('display', 'none');
		} else {
			$('iUrl').setStyle('display', '');
		}
	}

	if ($('iUrl2')) { // Direct link
		var urlList = $('iUrl2').href.split("?");
		$('iUrl2').set('href', urlList[0]+'?s='+(parseInt(num)+1));
	}
	
	for (var i=0; i<2; i++) { // Title(s)
		var title = false;
		if (i==0 && $(embedId+gid)) {
			title = $(embedId+gid).getElement('.image_title');
		} else if (i==1 && $(lightboxId)) {
			title = $(lightboxId).getElement('.image_title');
		}
		if (title) {
			title.set('text', imgNames[num]);
			if (title.get('tag') == 'p' && imgNames[num] == '' || imgNames[num].indexOf(' ') == 0)
				title.setStyle('display', 'none');
			else
				title.setStyle('display', '');
		}
	}
	
	for (var i=0; i<2; i++) { // Description(s)
		var desc = false;
		if (i==0 && $(embedId+gid)) {
			desc = $(embedId+gid).getElement('.image_desc');
		} else if (i==1 && $(lightboxId)) {
			desc = $(lightboxId).getElement('.image_desc');
		}
		if (desc) {
			desc.set('html', imgDesc[num]);
			if (desc.get('tag') == 'p' && imgDesc[num] == '') {
				desc.setStyle('display', 'none');
			} else {
				desc.setStyle('display', '');
			}
		}
	}
	
	// extra functions
	if (typeof(galleryExtraTitles) == 'function')
		galleryExtraTitles();
}

function nextScreen(gid) {
	if (arguments.length == 0)
		gid = (embed ? 0 : LightBoxGid);
	var toNum = getNextImgNum(gid, nowViewing[gid]);
	var nextNum = getNextImgNum(gid, toNum);
	var prevNum = nowViewing[gid];
	// Check page switch
	if (toNum == 0 && numChapters > 1) {
		var nextChap = (numChapters >= pageChapter + 1) ? pageChapter + 1 : 1;
		var myURI = new URI(window.location);
		var toPage = myURI.get('file').split(':')[0]; // page name
		toPage += ':'+nextChap;
		myURI.set('file', toPage);
		myURI.set('query', 's=1');
		myURI.go();
		return;
	}
	
	// Preload
	nextShot = new Image();
	nextShot.src = getImgSrc(nextNum);
	slideTo(toNum,(animated ? 0 : 1));
}
function prevScreen(gid) {
	if (arguments.length == 0)
		gid = (embed ? 0 : LightBoxGid);
	var toNum = getPrevImgNum(gid, nowViewing[gid]);
	var prevNum = getPrevImgNum(gid, toNum);
	var nextNum = nowViewing[gid];
	// Check page switch
	if (toNum == imgList.length-1 && numChapters > 1) {
		var prevChap = (pageChapter > 1) ? pageChapter - 1 : numChapters;
		var myURI = new URI(window.location);
		var toPage = myURI.get('file').split(':')[0]; // page name
		toPage += ':'+prevChap;
		myURI.set('file', toPage);
		myURI.set('query', 's=-1');
		myURI.go();
		return;
	}
	
	// Preload
	prevShot = new Image();
	prevShot.src = getImgSrc(prevNum);
	slideTo(toNum,(animated ? 0 : 1));
}
function slideTo(num,instant) {
	// Get the image to slide to
	screenImage.src = getImgSrc(num);
	slideShowFader(num,(instant ? 1 : 0));
}

function slideShowFader(num,instant) {
	animationLock = true;
	var gid = getGidFromNum(num);
	// Wait for it to complete
	if(!screenImage.complete) {
		if (!imageIsLoading) { // First hit in loop whilst loading image
			// Set titles already (to avoid confusion)
			setImgTitles(gid,num);
			if (!embed) // Lightbox is on, set waiting cursor
				$(lightboxId).style.cursor = 'wait';
			imageIsLoading = true;
		}
		if (!embed) { // Lightbox is on, rescale window to next image size and put in loadingImg
			var w = screenImage.width; var h = screenImage.height;
			if (w == 0 && h == 0) { w=minWidth; h=minHeight; }
			Ic1[gid].setStyles({width: w, height: h, 'background-image': "url('"+loadingImg+"')"});
		}
		// Check again in some time
		window.setTimeout('slideShowFader('+num+','+instant+')',100);
	} else { // Loading done
		imageIsLoading = false;
		// Set titles to image that's being faded in now
		setImgTitles(gid,num);
		if (!embed) // Unset wait cursor
			$(lightboxId).style.cursor = 'default';
		// Set the nowViewing global var
		var wasViewing = nowViewing[gid];
		nowViewing[gid] = num;
		// Set the image in the background (invisible) to the current image
		if (animated)
			Ic2[gid].setStyle('background-image', "url('"+screenImage.src+"')");
		// Disable any scrollbars in the container and set dynamic height
		var img_contain = (embed ? $(embedId+gid) : $(embedId));
		img_contain.setStyles({'overflow':'hidden','height':''});
		if (panning) // If panning is enabled, resets current pan effect (when animationLock is on)
			panImage();
		// If image scroller is enabled, set active class and scroll animation
		if (scroller) {
			scrollList[wasViewing].removeClass('active');
			scrollList[num].addClass('active');
			var scroll = $('img'+num).parentNode.parentNode;
			var scrollContain = scroll.parentNode;

			if (scrollMode == 'circular') {
				scrollMoveCircular(scroll, scrollContain, wasViewing, num);
			}

			var x_pos = 0; var y_pos = 0;
			if (scrollPos == 'left') {
				if (scrollOrient == 'vertical')
					y_pos = $('img'+num).parentNode.getPosition(scroll).y;
				else
					x_pos = $('img'+num).parentNode.getPosition(scroll).x;
			} else if (scrollPos == 'right') {
				if (scrollOrient == 'vertical') {
					y_pos = scrollContain.getSize().y * -1 + 
						$('img'+num).parentNode.getPosition(scroll).y + 
						$('img'+num).parentNode.getSize().y;
				} else {
					x_pos = scrollContain.getSize().x * -1 + 
						$('img'+num).parentNode.getPosition(scroll).x + 
						$('img'+num).parentNode.getSize().x;
				}
			} else { // center
				if (scrollOrient == 'vertical') {
					y_pos = parseInt(scrollContain.getSize().y / 2) * -1 + 
						$('img'+num).parentNode.getPosition(scroll).y + 
						parseInt($('img'+num).parentNode.getSize().y / 2);
				} else {
					x_pos = parseInt(scrollContain.getSize().x / 2) * -1 + 
						$('img'+num).parentNode.getPosition(scroll).x + 
						parseInt($('img'+num).parentNode.getSize().x / 2);
				}
			}
			
			scrollFx[gid].cancel();
			scrollFx[gid] = new Fx.Scroll(scrollContain, {'link': 'chain', 'duration': (instant || !animated ? 250 : 600), 'transition': Fx.Transitions.Sine.easeOut});
			scrollFx[gid].start(x_pos,y_pos);
		}
 		if (instant || !animated) { // Set the styles
			if (!embed)
				resizeLightBoxWidth(screenImage.width);
			var h = screenImage.height;
			if (h == 0) { h=minHeight; }
 			Ic1[gid].setStyles({'height': h, 'background-position': '0% 0%'});
			slideComplete(gid,num);
 		} else { // Start the effects
 			var h = screenImage.height; var w = screenImage.width;
 			var w_lb = w; // Lightbox width
			if (!embed) {
				var lb_extra = parseInt($(lightboxId).getSize().y - $(lightboxId).getStyle('height').toInt());
				var diff = window.getSize().y - (h + lb_extra + lightBoxMin.top + lightBoxMin.bottom);
				if (diff < 0) // Screen will be too small
					w_lb = parseInt(w + 16); // Compensate for scrollbar
				var lb_xdiff = $(lightboxId).getStyle('width').toInt() - w_lb;
				var l_lb = parseInt((getAvailWidth()+lb_xdiff) / 2);
			}
			
			var newDuration = slideDuration;
			// Cancel effects, in case they're already running
			if (getOpacity(Ic2[gid]) > 0) {
				Ic1Effect[gid].cancel();
				Ic2Effect[gid].cancel();
				LbxEffect.cancel();
				slideComplete(gid,wasViewing);
				// Adjust slidetimer
				newDuration = parseInt(.9*newDuration);
				if (newDuration < minSlideDuration)
					newDuration = minSlideDuration;
			} else { // Was not running, increase slide timer
				newDuration = parseInt(1.05*newDuration);
				if (newDuration > maxSlideDuration)
					newDuration = maxSlideDuration;
			}
			
			if (newDuration != slideDuration) { // Re set options
				Ic1Effect[gid].setOptions({duration: parseInt(.8*newDuration)});
				if (!embed)
					LbxEffect.setOptions({duration: parseInt(.9*newDuration)});
				Ic2Effect[gid].setOptions({duration: parseInt(newDuration)});
				slideDuration = newDuration;
			}
			
 			if (Browser.Engine.gecko && !embed && $(lightboxId).getStyle('-moz-box-shadow')) // Disable box shadow for gecko browsers during effect
 				$(lightboxId).setStyle('-moz-box-shadow', 'none');
			if (fixedWidth) {
				Ic1Effect[gid].start({
					'height': h
				});
			} else {
				Ic1Effect[gid].start({
					'height': h,
					'width': w
				});
			}
 			if (LbxEffect) {
 				LbxEffect.start({
					'width': w_lb,
					'left': l_lb
				});
			}
			if (fixedWidth) {
				Ic2Effect[gid].start({
					'opacity': [0,1],
					'height': h
				});
			} else {
				Ic2Effect[gid].start({
					'opacity': [0,1],
					'height': h,
					'width': w
				});
			}
		}
	}
}

function scrollMoveCircular(scroll, contain, from, to) {
	/* calculate direction and number of steps */
	var side = 1; // forward (to the right)
	var diff = 1;
	var rd = (to - from);
	var ld = (from - to);
	if (rd < 0) rd += imgList.length;
	if (ld < 0) ld += imgList.length;
	if (ld < rd) { // backward (left)
		side = -1;
		diff = ld;
	} else {
		diff = rd;
	}

	for (var i=1; i<=diff; i++) {
		if (side == 1) {
			// moving forwards, move first element to back
			//if (scrollOrient == 'vertical' && contain.scrollTop == 0 || scrollOrient != 'vertical' && contain.scrollLeft == 0)
			//	continue;
			var move = scroll.getElements('div')[0];
			var moved = move.dispose();
			moved.inject(scroll);
			if (scrollOrient == 'vertical' && contain.scrollTop > 0)
				contain.scrollTop = contain.scrollTop - moved.getSize().y;
			else if (contain.scrollLeft > 0)
				contain.scrollLeft = contain.scrollLeft - moved.getSize().x;
		} else {
			// moving backwards, move last element to front
			var move = scroll.getElements('div').getLast();
			var moved = move.dispose();
			moved.inject(scroll, 'top');						
			if (scrollOrient == 'vertical')
				contain.scrollTop = contain.scrollTop + moved.getSize().y;
			else
				contain.scrollLeft = contain.scrollLeft + moved.getSize().x;
		}
	}
}

function slideComplete(gid,num) {
	if (num == undefined)
		num = nowViewing[gid];
	if (Browser.Engine.gecko && !embed)
		$(lightboxId).setStyle('-moz-box-shadow', '');
	Ic1[gid].setStyle('background-image', "url('"+getImgSrc(num)+"')");
	if (animated)
		setOpacity(Ic2[gid], 0);
	if (!embed)
		$(embedId).style.overflow = 'auto';
	setImgTitles(gid,num);
	/* this might be dangerous when multiple images are loading ... */
	window.setTimeout('setImgContainDimensions('+gid+')',100);
	animationLock = false;
	if (!embed)
		updateLightBoxPosition();
	if (panning)
		panImage();
}

function updateLightBoxPosition() {
	if ((getAvailHeight() - $(lightboxId).getPosition().y) < 0) {
		var topPos = parseInt(getAvailHeight() / 4 + 0.5);
		if (topPos < lightBoxMin.top)
			topPos = lightBoxMin.top;
		$(lightboxId).setStyle('top',topPos);
	}
}

function updateLightBoxSize() {
	// update height
	var availY = (getAvailHeight() - $(lightboxId).getPosition().y); // free height
	var imgy = $(embedId).getStyle('height').toInt(); // image container height
	if (availY >= (screenImage.height - imgy)) { // enough space for full height
		$(embedId).setStyle('height','');
		$(lightboxId).setStyle('width', parseInt(screenImage.width)); // reset width (no scrollbar)
	} else {
		$(embedId).setStyle('height', imgy + availY); // Set height to fit screen
		$(lightboxId).setStyle('width', parseInt(screenImage.width + 16)); // Compensate for scrollbar
	}
	
	centerLightboxHorizontal();
}

function setImgContainDimensions(gid) {
	/*Ic1[gid].setStyle('height', screenImage.height);*/
	if (animated)
		Ic2[gid].setStyle('height', screenImage.height);
	if (!fixedWidth) {
		Ic1[gid].style.width = screenImage.width + "px";
		if (animated)
			Ic2[gid].style.width = Ic1[gid].style.width;
	}
	if (!embed) {
		var diff = getAvailHeight() - (lightBoxMin.top + lightBoxMin.bottom);
		if (diff < 0) { // Screen too small
			var imgContain = Ic1[gid].getParent();
			var containHeight = imgContain.getStyle('height').toInt();
			imgContain.setStyle('height', parseInt(containHeight + diff)); // Set height to fit screen
			$(lightboxId).setStyle('width', parseInt(screenImage.width + 16)); // Compensate for scrollbar
		}
	}
}

function resizeLightBoxWidth(width) {
	if (width < minWidth)
		width = minWidth;
	$(lightboxId).setStyle('width', width);
	
	/*var availX = window.getSize().x - width;
	$(lightboxId).setStyle('left', parseInt(availX / 2));*/
	
	centerLightboxHorizontal();
}

function centerLightboxHorizontal() {
	var availX = getAvailWidth();
	if (availX > 2)
		$(lightboxId).setStyle('left', parseInt(availX / 2));
	else
		$(lightboxId).setStyle('left', 0);
}

function getAvailWidth() {
	return parseInt(window.getSize().x - $(lightboxId).getSize().x);
}
function getAvailHeight() {
	return parseInt(window.getSize().y - $(lightboxId).getSize().y);
}
function getNumFromGid(gid) {
	var num = 0;
	if ($(tableId+gid)) {
		var img = $(tableId+gid).getElements('.scroll a')[0];
		if (img)
			num = img.id.substr(3);
	}
	return num;
}
function getGidFromNum(num) {
	var gid = 0;
	if ($('img'+num)) {
		var gall = $('img'+num).getParent('.images');
		if (gall)
			gid = gall.id.substr(tableId.length);
	}
	return gid;
}

function getNextImgNum(gid, num) {
	var next = parseInt(num)+1;
	if (next >= imgList.length || next > lastImg(gid))
		next = firstImg(gid)
	return next;
}
function getPrevImgNum(gid, num) {
	var prev = parseInt(num)-1;
	if (prev < 0 || prev < firstImg(gid))
		prev = lastImg(gid);
	return prev;
}
function firstImg(gid) {
	return parseInt(getNumFromGid(gid));
}
function lastImg(gid) {
	return parseInt(getNumFromGid(gid)) + parseInt(gallCount[gid]) - 1;
}

function DeBug(html) {
	$('debug').set('html', $('debug').get('html') + html + '<br />');
}

