/* -----------------------------------------------------------------------------
		Functions lifted from http://www.hesido.com/web.php?page=javascriptanimation
	//Generic Animation Step Value Generator By www.hesido.com
* ------------------------------------------------------------------------------- */
function easeInOut(minValue,maxValue,totalSteps,actualStep,powr){
	var delta = maxValue - minValue;
	var stepp = minValue+(Math.pow(((1 / totalSteps)*actualStep),powr)*delta);
	return Math.ceil(stepp);
}

function doPosChangeMem(elem,startPos,endPos,steps,delay,powr) {
	//Position changer with Memory by www.hesido.com
	if (elem.intervalID) window.clearInterval(elem.intervalID);
	var actStep = 0;
	elem.intervalID = window.setInterval(
		function() {
			elem.currentPos = [
				easeInOut(startPos[0],endPos[0],steps,actStep,powr),
				easeInOut(startPos[1],endPos[1],steps,actStep,powr)
				];
			elem.style.left = elem.currentPos[0]+"px";
			elem.style.top = elem.currentPos[1]+"px";
			actStep++;
			if (actStep > steps) window.clearInterval(elem.intervalID);
		}
		,delay);

}

/* -----------------------------------------------------------------------------
		Theme switcher (aka "slider")
* ------------------------------------------------------------------------------- */
ThemeSlider = function(){
}

ThemeSlider.prototype = {
	_sliderContent: null, // handle to cell-level element holding all the thumbs, it's the element that we're going to animate
	// animation parameters:
	steps: 21, // total steps of animation (default: 12)
	delay: 40, // intervals the animation will be done in miliseconds (default: 30)
	powr: 0.7, // value used for determining ease-in and out. (default: 0.6)
	// info about the strip being moved:
	_cellWidth: 115, /* width (pixels) for each sample thumbnail div */
	_scrollByStep: 3, // number of cells to show (total move is StepSize * CellWidth)
	_totalCells: 0,
	_startCell: 1,// a one-based pointer to first cell currently being displayed...

	setCount: function(value) { this._totalCells = value; },

	init: function(){
		this._sliderContent = document.getElementById("sliderContent");
		this._sliderContent.style.width = (this._totalCells * this._cellWidth) + "px";
		this._sliderContent.currentPos = [0, 0]; // starting position is 0,0, this attribute holds current x, y coordinates
		this._sliderContent.intervalID = null; // handle to the window interval  

		this.attachEvents();
		this.goTo(1);

	}, // init

	goTo: function(cell){
		this._startCell= cell;
		var endPos = new Array(-((this._startCell-1) * this._cellWidth),0);
		doPosChangeMem(this._sliderContent,this._sliderContent.currentPos,endPos,this.steps,this.delay,this.powr);
	}, // goto

	moveBy: function(cellsToMove){
		// one-based index
		var cell = this._startCell + cellsToMove;
		if (cellsToMove>0){
			if (this._startCell == this._totalCells)
				cell = 1;
			else if (cell > this._totalCells)
				cell = this._totalCells;
		} else {
			if (this._startCell == 1)
				cell = this._totalCells;
			else if (cell < 1)
				cell = 1;
		}

		this.goTo(cell);
	},

	left: function(){
		this.moveBy(-this._scrollByStep);
	},
	
	right: function(){
		this.moveBy(this._scrollByStep);
	},

	attachEvents: function(){
		var x = this;
		
		var h= document.getElementById("scrollRightBtn");
		h.href="javascript:void(0);";
		h.onclick = function(){
			x.right();
		}
	
		var h= document.getElementById("scrollLeftBtn");
		h.href="javascript:void(0);";
		h.onclick = function(){
			x.left();
		}

	}
	
} // themeSlider (object)


/* -----------------------------------------------------------------------------
//	Instant Gallery reads HTML and loads the PBTS Photo Gallery
//	It then wipes out the original HTML and loads the Gallery.
//	Format your HTML like this:

<ul id="photoList">
	<li><blockquote>{description}</blockquote>
		<a href="{ignored, for SEO}" title="{ignored, for SEO}">
			<img src="{grabs filename, following last '/'}" 
				alt="{title}" 
				xwidth="{width in pixels}" 
				xheight="{height in pixels}" />
		</a>
		<h6>{extra1}</h6>
	</li>
</ul>
*/

InstantGallery = function(){
}

InstantGallery.prototype = {
	_listId: "",
	_gallery: null,
	_enableSlider: false,
	
	get_gallery: function(){ return this._gallery; },

	scrapeHTML: function(){
		var h = document.getElementById(this._listId);
		h.style.display = "none";
		var l = h.getElementsByTagName( "li" );
		var img, file, width, height, title;
		var maxHeight=-1;
		for (var i=0; i < l.length; i++){
			img = l[i].getElementsByTagName( "img" );
			if (img.length > 0){
				// image
				file = new String(img[0].src);
				file = file.substr(file.lastIndexOf("/")+1);
				title = img[0].alt;
				if (img[0].style && img[0].style.height){
					height = img[0].style.height;
					height = height.substr(0,height.length-2);
					width = img[0].style.width;
					width = width.substr(0,width.length-2);
				} 
				if (height > maxHeight) maxHeight = height;
				var e = l[i].getElementsByTagName( "*" );
				this._gallery.addImg( file, title, this.getMeta( e, 'descr'), width, height, this.getMeta( e, 'extra1') );
			}
		}
		h.innerHTML = "";
	},
	
	getMeta: function( e, prop ){
		for (var i=0; i < e.length; i++){
			if (e.className == prop){
				return e.innerHTML;
			}
		}
		return '';
	},
	/*
				// other meta
				//["file","title","description","width","height","extra1","extra2","extra3","extra4","date"],
				//descr = this.getMeta( l[i], 'descr');
				//extra1 = this.getMeta( l[i], 'extra1');
				else 
				{
					height = img[0].getAttribute('xheight');
					width = img[0].getAttribute('xwidth');
				}
	scrapeHTML: function(){
		var h = document.getElementById(this._listId);
		h.style.display = "none";
		var l = h.getElementsByTagName( "li" );
		var img, file, descr, extra1;
		for (var i=0; i < l.length; i++){
			img = l[i].getElementsByTagName( "img" );
			if (img.length > 0){
				descr = l[i].getElementsByTagName( "blockquote" );
				extra1 = l[i].getElementsByTagName( "h6" );
				file = new String(img[0].src);
				file = file.substr(file.lastIndexOf("/")+1);
				this._gallery.addImg( 
					file,
					img[0].alt,
					(descr.length > 0)?descr[0].innerHTML:"",
					img[0].getAttribute('xwidth'),
					img[0].getAttribute('xheight'),
					(extra1.length > 0)?extra1[0].innerHTML:"" );
			}
		}
		h.innerHTML = "";
	},
	*/

	next: function(){ this._gallery.gotoNextPic();},
	previous: function(){ this._gallery.gotoPrevPic();},
	help: function(){ this._gallery.showHelp()},

	// ---------------------------------------------------------------------
	// Function: mySlideshow
	// Descr:    a local function wraps the photo gallery's slideshow function
	//           so visual cue (the anchor) can be displayed
	// ---------------------------------------------------------------------
	toggleSlideshow: function(){
		var s= document.getElementById("myslides");
		if (this._gallery.toggleSlideshow()) {
			s.innerHTML="Stop Slideshow";
			s.className="stop";
		} else {
			s.innerHTML="Start Slideshow";
			s.className="start";
		}
	},

	scrollToSelectedThumb: function(idx){
		// todo: scroll
		return;
	},
	
	initialize: function(config){
		this._listId = config.listId;
		this._enableSlider = config.enableSlider;
		
		// start by loading the pbts Gallery Manager, first shared photo
		this._gallery = new PBTSGallery;
		
		this._gallery.initialize({
			ThumbDir: config.thumbDir,
			ImgDir: config.imgDir,
			LoadingImg: config.loadingImg,
			Spacer: config.loadingImg,
			Rows: config.rows,
			Cols: config.cols,
			enableKeys: true,
			PropOrder: ["file","title","description","width","height","extra1","extra2","extra3","extra4","date"],
			ThumbWidth: config.thumbWidth,
			ThumbSpacing: 2,
			ThumbClass: "thumb",
			ThumbSelectedClass: "selected",
			ThumbAll: false,
			ThumbTitles: true,
			defaults: {
				width: 500,
				height: 333
				},
			ids: { 
				pages: config.ids.pages,
				thumbs: config.ids.thumbs,
				image: config.ids.image,
				info: config.ids.info,
				description: config.ids.description,
				title: config.ids.title,
				Link: config.ids.link
				}
			}
		);

		var x = this;
		this._gallery.set_Callback(
			function(idx){
				x.scrollToSelectedThumb(idx);
			}
		);
		
		// now let's read picture info from Static HTML
		this.scrapeHTML();
		if (this._enableSlider){
			this._gallery.set_Cols(this._gallery.getCount());
		}

		// now blast in the pizza gallery
		this._gallery.writeGallery();	

		if (this._enableSlider){
			var mySlider = new ThemeSlider;
		
			mySlider.setCount(this._gallery.getCount());
			mySlider.init();
		}

	}

}