/*
    This file is part of JonDesign's SmoothGallery v2.1beta1.

    JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    JonDesign's SmoothGallery is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JonDesign's SmoothGallery; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
*/

function enlargeSlideshowToggle()
{
	var built=0;
	if (!myGallery2)
	{
		myGallery2 = new gallery($('myGallery2'), {
			timed: true,
			showPlay: true,
			playState: myGallery.options.playState,
			delay: myGallery.options.delay,
			startPos: myGallery.currentIter
		});
		built = 1;
//		Rounded('div#myGallery2','top', 'transparent', '#000', 'transparent');
	}

	elEnlarged = getEl("myGallery2");
	if (built || elEnlarged.style.display == 'none')
	{
		elEnlarged.style.display = 'block';
		showWindowShade('block');
		if (myGallery.options.playState)
			myGallery2.play();
		else
			myGallery2.pause();
		myGallery.pause();
		if (!built)
			myGallery2.goTo(myGallery.currentIter);
	}
	else
	{
		showWindowShade('none');
		myGallery2.pause();
		elEnlarged.style.display = 'none';
		var shouldPlay = getPrefInCookie('playSlideshow', 1);
		if (shouldPlay != 0)
			myGallery.play();
		myGallery.goTo(myGallery2.currentIter);
 	}
}

/* some quirks to circumvent broken stuff in mt1.2 */
function isBody(element){
	return (/^(?:body|html)$/i).test(element.tagName);
};
Element.implement({
	getPosition: function(relative){
		if (isBody(this)) return {x: 0, y: 0};
		var el = this, position = {x: 0, y: 0};
		while (el){
			position.x += el.offsetLeft;
			position.y += el.offsetTop;
			el = el.offsetParent;
		}
		var rpos = (relative) ? $(relative).getPosition() : {x: 0, y: 0};
		return {x: position.x - rpos.x, y: position.y - rpos.y};
	}
});

// declaring the class
var gallery = {
	Implements: [Events, Options],
	options: {
		startPos: 0,
		randomStart: 0,
		savePlayState: 0,
		showArrows: true,
		showInfopane: true,
		showPlay: false,
		playState: true,
		fadeDuration: 500,
		timed: false,
		delay: 9000,
		preloader: true,
		/* Data retrieval */
		manualData: [],
		populateFrom: false,
		populateData: true,
		destroyAfterPopulate: false,
		elementSelector: "div.imageElement",
		titleSelector: "h2",
		subtitleSelector: "p",
		fontSize: "100%",
		imageSelector: "h1",
		defaultTransition: "fade",
		/* InfoPane options */
		slideInfoZoneOpacity: 1,
		slideInfoZoneSlide: true,
		/* CSS Classes */
		baseClass: 'jdGallery',
		withArrowsClass: 'withArrows',
		/* Plugins: ReMooz */
		useReMooz: false
	},
	initialize: function(element, options) {
		this.setOptions(options);
		var shouldPlay = getPrefInCookie('playSlideshow', 1);
		if (shouldPlay == 0 && this.options.savePlayState)
			this.options.playState = false;
		this.fireEvent('onInit');
		this.showControlId = 'showControl'+element.id
		this.leftId = 'left'+element.id
		this.rightId = 'right'+element.id
		this.currentIter = 0;
		this.lastIter = 0;
		this.maxIter = 0;
		this.galleryElement = element;
		this.maxImgHeight = element.style.height.toInt()-42; // slideInfoZone
		this.maxImgWidth = element.style.width.toInt();
		this.galleryData = this.options.manualData;
		this.galleryInit = 1;
		this.galleryElements = Array();
		this.thumbnailElements = Array();
		this.galleryElement.addClass(this.options.baseClass);

		if (this.options.useReMooz&&(this.options.defaultTransition=="fade"))
			this.options.defaultTransition="crossfade";

		this.populateFrom = element;
		if (this.options.populateFrom)
			this.populateFrom = this.options.populateFrom;
		if (this.options.populateData)
			this.populateData();

		this.constructElements();
		if ((this.galleryData.length>1)&&(this.options.showArrows))
		{
			var leftArrow = new Element('a').addClass('left').setProperties({id: this.leftId}).addEvent(
				'click', this.prevItem.bind(this)).addEvent(
				'mousemove', this.mouseMoveLeft.bind(this)).injectInside(element);
			var rightArrow = new Element('a').addClass('right').setProperties({id: this.rightId}).addEvent(
				'click', this.nextItem.bind(this)).addEvent(
				'mousemove', this.mouseMoveRight.bind(this)).injectInside(element);
		}

		if (this.options.showPlay)
		{
			var classname = 'play';
			if (this.options.playState)
				classname = 'pause';
			var playBtn = new Element('a').addClass(classname).setProperties({id: this.showControlId}).addEvent(
				'click', this.playPauseShow.bind(this)).addEvent(
				'mousemove', this.mouseMovePlayPause.bind(this)).injectInside(element);
		}

		if (this.options.randomStart)
			this.options.startPos = Math.floor(Math.random() * this.maxIter);

		this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
		if (this.options.showInfopane)
			this.initInfoSlideshow();
		this.doSlideShow();
	},
	clearPlayPause: function ()
	{
		elControl = getEl(this.showControlId);
		elControl.removeClass('pauseOver');
		elControl.removeClass('playOver');
	},
	clearLeft: function ()
	{
		el = getEl(this.leftId);
		el.removeClass('leftOver');
	},
	clearRight: function ()
	{
		el = getEl(this.rightId);
		el.removeClass('rightOver');
	},
	mouseMovePlayPause: function ()
	{
		this.clearRight();
		this.clearLeft();
		elControl = getEl(this.showControlId);
		if(elControl.hasClass('pause'))
			elControl.addClass('pauseOver');
		else if(elControl.hasClass('play'))
			elControl.addClass('playOver');
		$clear(this.clearPlayPauseTimerId);
		this.clearPlayPauseTimerId = this.clearPlayPause.delay(1400, this);
	},
	mouseMoveRight: function ()
	{
		el = getEl(this.rightId);
		el.addClass('rightOver');
		this.clearPlayPause();
		this.clearLeft();
		$clear(this.rightTimerId);
		this.rightTimerId = this.clearRight.delay(1400, this);
	},
	mouseMoveLeft: function ()
	{
		el = getEl(this.leftId);
		el.addClass('leftOver');
		this.clearPlayPause();
		this.clearRight();
		$clear(this.leftTimerId);
		this.leftTimerId = this.clearLeft.delay(1400, this);
	},

	populateData: function() {
		currentArrayPlace = this.galleryData.length;
		options = this.options;
		var data = $A(this.galleryData);
		data.extend(this.populateGallery(this.populateFrom, currentArrayPlace));
		this.galleryData = data;
		this.fireEvent('onPopulated');
	},
	populateGallery: function(element, startNumber) {
		var data = [];
		options = this.options;
		currentArrayPlace = startNumber;
		document.getElements(options.elementSelector).each(function(el) {
			elementDict = $H({
				image: el.getElement(options.imageSelector).innerHTML,
				number: currentArrayPlace,
				transition: this.options.defaultTransition
			});
			if (options.showInfopane)
				elementDict.extend({
					title: el.getElement(options.titleSelector).innerHTML,
					link: el.getElement('a.open').href,
					description: el.getElement(options.subtitleSelector).innerHTML
				});

			data.extend([elementDict]);
			currentArrayPlace++;
			if (this.options.destroyAfterPopulate)
				el.dispose();
		});
		return data;
	},
	constructElements: function() {
		el = this.galleryElement;
		this.maxIter = this.galleryData.length;
		var currentImg;
		for(i=0;i<this.galleryData.length;i++)
		{
			var currentImg = new Fx.Morph(
				new Element('div').addClass('slideElement').setStyles({
					'position':'absolute',
					'left':'0px',
					'right':'0px',
					'margin':'0px',
					'padding':'0px',
					'backgroundPosition':"center center",
					'opacity':'0'
				}).injectInside(el),
				{duration: this.options.fadeDuration}
			);
			if (this.options.preloader)
			{
				currentImg.source = this.galleryData[i].image;
				currentImg.loaded = false;
				currentImg.load = function(imageStyle, i) {
					if (!imageStyle.loaded)	{
						this.galleryData[i].imgloader = new Asset.image(imageStyle.source, {
		                            'onload'  : function(img, i){
													img.element.setStyle(
													'backgroundImage',
													"url('')")
													img.loaded = true;
													img.width = this.galleryData[i].imgloader.width;
													img.height = this.galleryData[i].imgloader.height;
													var new_height = img.height;
													var new_width = img.width;
													var margin_top = 1;
													if(this.maxImgHeight < img.height){
														new_height = this.maxImgHeight;
														new_width = Math.round(this.maxImgHeight*img.width/img.height);
													}
													if(this.maxImgWidth < new_width) {
														new_width = this.maxImgWidth;
														new_height = Math.round(this.maxImgWidth*img.height/img.width);
													}
													if (new_height < this.maxImgHeight)
														margin_top = Math.round((this.maxImgHeight - new_height)/2)+1;
													new_height -= 0;
													new_width -= 0;
//alert(this.galleryElement.id+' '+this.maxImgHeight+' '+new_height);
													img.element.appendChild(new Element('img').set('src',img.source).setStyles({
														'margin':'0 auto',
														'display':'block',
														'width':new_width+'px',
														'height':new_height+'px',
														'margin-top':margin_top+'px'
													}));
												}.pass([imageStyle, i], this)
						});
					}
				}.pass([currentImg, i], this);
			} else {
					currentImg.element.appendChild(new Element('img').set('src',this.galleryData[i].image).setStyles({
						'margin':'0 auto',
						'display':'block',
						'width':top_width+'px',
						'height':top_height+'px'
					}));
			}
			this.galleryElements[parseInt(i)] = currentImg;
		}
	},
	destroySlideShow: function(element) {
		var myClassName = element.className;
		var newElement = new Element('div').addClass('myClassName');
		element.parentNode.replaceChild(newElement, element);
	},
	startSlideShow: function() {
		this.fireEvent('onStart');
		this.loadingElement.style.display = "none";
		this.lastIter = this.maxIter - 1;
		this.galleryInit = 0;
		this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
		if (this.options.showInfopane)
			this.showInfoSlideShow.delay(800, this);
		if (this.options.playState)
			this.prepareTimer();
	},

	pause: function() {
		this.clearTimer();
		elControl = getEl(this.showControlId);
		if(elControl.hasClass('pause'))
		{
			//pause
			this.options.playState = false;
			elControl.removeClass('pause');
			elControl.addClass('play');
		}
	},

	play: function() {
		elControl = getEl(this.showControlId);
		if(elControl.hasClass('play'))
		{
			//start
			this.clearTimer();
			this.options.playState = true;
			this.prepareTimer();
			elControl.removeClass('play');
			elControl.addClass('pause');
		}
	},
	playPauseShow: function() {
		this.clearTimer();
		this.clearPlayPause();
		elControl = getEl(this.showControlId);
		if(elControl.hasClass('pause')) {
			//pause
			this.options.playState = false;
			elControl.removeClass('pause');
			elControl.addClass('play');

		} else if(elControl.hasClass('play')) {
			//start
			this.options.playState = true;
			this.nextItem();
			elControl.removeClass('play');
			elControl.addClass('pause');
		}
		this.savePlayState();
	},
	savePlayState: function()
	{
		if (!this.options.savePlayState)
			return;

		var shouldPlay = 0;
		elControl = getEl(this.showControlId);
		if(elControl.hasClass('pause'))
			shouldPlay = 1;

		setPrefInCookie('playSlideshow', shouldPlay);
	},

	nextItem: function() {
		this.fireEvent('onNextCalled');
		this.nextIter = this.currentIter+1;
		if (this.nextIter >= this.maxIter)
			this.nextIter = 0;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	prevItem: function() {
		this.fireEvent('onPreviousCalled');
		this.nextIter = this.currentIter-1;
		if (this.nextIter <= -1)
			this.nextIter = this.maxIter - 1;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	goTo: function(num) {
		this.galleryInit = 0;
		this.clearTimer();
		if(this.options.preloader)
		{
			this.galleryElements[num].load();
			if (num==0)
				this.galleryElements[this.maxIter - 1].load();
			else
				this.galleryElements[num - 1].load();
			if (num==(this.maxIter - 1))
				this.galleryElements[0].load();
			else
				this.galleryElements[num + 1].load();

		}
		if (this.options.showInfopane)
		{
			this.slideInfoZone.clearChain();
			this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
		} else
			this.currentChangeDelay = this.changeItem.delay(500, this, num);
		if (this.options.playState)
			this.prepareTimer();
	},
	changeItem: function(num) {
		this.fireEvent('onStartChanging');
		this.galleryInit = 0;
		if (this.currentIter != num)
		{
			for(i=0;i<this.maxIter;i++)
			{
				if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
			}
			gallery.Transitions[this.galleryData[num].transition].pass([
				this.galleryElements[this.currentIter],
				this.galleryElements[num],
				this.currentIter,
				num], this)();
			this.currentIter = num;
		}
		this.doSlideShow.bind(this)();
		this.fireEvent('onChanged');
	},
	clearTimer: function() {
		if (this.options.timed)
			$clear(this.timer);
	},
	prepareTimer: function() {
		if (this.options.timed)
			this.timer = this.nextItem.delay(this.options.delay, this);
	},
	doSlideShow: function() {
		if (this.galleryInit == 1)
		{
			this.currentIter = this.options.startPos;
			this.nextIter = this.options.startPos;

			this.galleryElement.style.visibility = 'visible';
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startSlideShow.delay(10, this);
			}.bind(this);
			imgPreloader.src = this.galleryData[this.currentIter].image;
			if(this.options.preloader)
				this.galleryElements[this.currentIter].load();
		} else {
			if (this.options.showInfopane)
			{
				if (this.options.showInfopane)
				{
					this.showInfoSlideShow.delay((500 + this.options.fadeDuration), this);
				}
			}
		}
	},

	log: function(value) {
		if(console.log)
			console.log(value);
	},

	initInfoSlideshow: function() {
		/*if (this.slideInfoZone.element)
			this.slideInfoZone.element.remove();*/
		this.slideInfoZone = new Fx.Morph(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
		var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
		var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
		this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
		this.slideInfoZone.element.setStyle('opacity',0);
	},
	changeInfoSlideShow: function()
	{
		this.hideInfoSlideShow.delay(10, this);
		this.showInfoSlideShow.delay(500, this);
	},
	showInfoSlideShow: function() {
		this.fireEvent('onShowInfopane');
		this.slideInfoZone.cancel();
		element = this.slideInfoZone.element;
		var href = "<a target=\"_blank\" title=\"Open in New Window\" href=\""+this.galleryData[this.currentIter].link+"\">";
		element.getElement('h2').set('html', href+ this.galleryData[this.currentIter].title +"</a>");
		element.getElement('h2').setStyle('font-size',this.options.fontSize);
		element.getElement('p').set('html', href+ this.galleryData[this.currentIter].description +"</a>");
		element.getElement('p').setStyle('font-size',this.options.fontSize);

		if(this.options.slideInfoZoneSlide)
			this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
		else
			this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity]});
		return this.slideInfoZone;
	},
	hideInfoSlideShow: function() {
		this.fireEvent('onHideInfopane');
		this.slideInfoZone.cancel();
		if(this.options.slideInfoZoneSlide)
			this.slideInfoZone.start({'opacity': 0, 'height': 0});
		else
			this.slideInfoZone.start({'opacity': 0});
		return this.slideInfoZone;
	},

	/* To change the gallery data, those two functions : */
	flushGallery: function() {
		this.galleryElements.each(function(myFx) {
			myFx.element.dispose();
			myFx = myFx.element = null;
		});
		this.galleryElements = [];
	},
	changeData: function(data) {
		this.galleryData = data;
		this.clearTimer();
		this.flushGallery();
		this.constructElements();
		if (this.options.showInfopane) this.hideInfoSlideShow();
		this.galleryInit=1;
		this.lastIter=0;
		this.currentIter=0;
		this.doSlideShow(1);
	}
};
gallery = new Class(gallery);

gallery.Transitions = new Hash ({
	fade: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		if (newPos > oldPos) newFx.start({opacity: 1});
		else
		{
			newFx.set({opacity: 1});
			oldFx.start({opacity: 0});
		}
	},
	crossfade: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		newFx.start({opacity: 1});
		oldFx.start({opacity: 0});
	},
	fadebg: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration / 2;
		oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
	}
});

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: formatString (function)
 * Original name: Yahoo.Tools.printf
 * Copyright Yahoo.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function formatString() {
	var num = arguments.length;
	var oStr = arguments[0];
	for (var i = 1; i < num; i++) {
		var pattern = "\\{" + (i-1) + "\\}";
		var re = new RegExp(pattern, "g");
		oStr = oStr.replace(re, arguments[i]);
	}
	return oStr;
}