// hGallery hGallery.js v1.0, Fri May 05 2007

// Copyright (c) 2005-2007 Makerweb (http://www.makerweb.it)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see http://www.makerweb.it

var Banner = Class.create();

Banner.prototype = {

	initialize: function(divId,xmlUrl,idBanner) {
		this.inprogress = false;
		this.paramList = [];
		this.imageList = [];
		this.idBanner = idBanner;
		this.bannerDiv = document.getElementById(divId);
		this.xmlUrl = xmlUrl;
		this.params = {};
		this.intervalid;
		this.playing = false;
		this.render = false;
		
		this.Engine = {
			detect: function() {
				var UA = navigator.userAgent;
				this.isKHTML = /Konqueror|Safari|KHTML/.test(UA);
				this.isGecko = (/Gecko/.test(UA) && !this.isKHTML);
				this.isOpera = /Opera/.test(UA);
				this.isMSIE  = (/MSIE/.test(UA) && !this.isOpera);
				this.isMSIE7 = this.isMSIE && !(/MSIE 6\./.test(UA) && !this.isOpera);
			}
		};
		this.Engine.detect();
		
	},
	
	load: function() {
		var idBanner = this.idBanner;
		this.getXml();
	},
	
	getXml: function() {
		var idBanner = this.idBanner;
		
		if (window.XMLHttpRequest) {
			var xmlData = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			var xmlData = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (xmlData) {
			xmlData.onreadystatechange = function() {
				if (xmlData.readyState == 4) {
					if (xmlData.status == 200) {
						myBanner[idBanner].parseXml(xmlData)
					}
				}
			};
			xmlData.open("GET", this.xmlUrl, true);
			xmlData.send("");
		}
	},
	
	trimString: function(sInString) {
		sInString = sInString.replace( /^\s+/g, "" );
		return sInString.replace( /\s+$/g, "" );
	},
	
	parseXml: function(xmlData) {

		var items = xmlData.responseText.split(/<banner>/g);
		var parameters = items[1].split(/<parameters>/g);
		var images = items[1].split(/<image>/g);

		xmlData = false;
		var lines;
		var no2;
		var key;
		var pattern;
		var value;
		for(var no=1;no<parameters.length;no++){
			lines = parameters[no].split(/\n/g);
			this.paramList[no-1] = [];
			for(no2=0;no2<lines.length;no2++){
				key = lines[no2].replace(/<([^>]+)>.*/g,'$1');
				if (key) { key = this.trimString(key); }
				pattern = new RegExp("<\/?" + key + ">","g");
				value = lines[no2].replace(pattern,'');
				value = this.trimString(value);
				if (key=='/parameters') { break; }
				if (key!=='' && value!=='') {
					this.paramList[no-1][key] = value;
				}
			}
		}

		for(no=1;no<images.length;no++){
			lines = images[no].split(/\n/g);
			this.imageList[no-1] = [];
			for(no2=0;no2<lines.length;no2++) {
				key = lines[no2].replace(/<([^>]+)>.*/g,'$1');
				if (key) { key = this.trimString(key); }
				pattern = new RegExp("<\/?" + key + ">","g");
				value = lines[no2].replace(pattern,'');
				value = this.trimString(value);
				if (key=='/images') { break; }
				if (key!=='' && value!=='') {
					this.imageList[no-1][key] = value;
				}
			}
		}
		this.initializeParams();
		this.createBanner();
		this.play();
	},

	initializeParams: function() {
		
		this.params.width = 0;
		this.params.height = 0;
		var i;
		for (i=0;i<this.imageList.length;i++) {
			if (parseInt(this.imageList[i]["width"])>this.params.width) this.params.width = parseInt(this.imageList[i]["width"]);
			if (parseInt(this.imageList[i]["height"])>this.params.height) this.params.height = parseInt(this.imageList[i]["height"]);
		}
		this.params.transition = (this.paramList[0]["effetto"]!==undefined)?this.paramList[0]["effetto"]:'dissolve';
		this.params.orientation = (this.paramList[0]["verso"]!==undefined)?this.paramList[0]["verso"]:'down';
		this.params.duration = (this.paramList[0]["durata"]!==undefined)?parseInt(this.paramList[0]["durata"]):5;
	},
	
	createBanner: function() {
		var idBanner = this.idBanner;

		var divSlideShow = document.createElement('div');
		divSlideShow.id = 'B_slideshow_'+idBanner;
		divSlideShow.style.width = this.params.width+'px';
		divSlideShow.style.height = this.params.height+'px';
		divSlideShow.style.position = 'relative';
		divSlideShow.style.left = '0px';
		
		var divShow = document.createElement('div');
		divShow.id = 'B_show_'+idBanner;
		divShow.style.width = this.params.width+'px';
		divShow.style.height = this.params.height+'px';
		divShow.style.position = 'relative';
		divShow.style.overflow = 'hidden';

		var viewImage = document.createElement('img');
		viewImage.id = 'B_viewImage_'+idBanner;
		viewImage.style.display = 'none';
		viewImage.style.zIndex = '100';
		divShow.appendChild(viewImage);

		divSlideShow.appendChild(divShow);

		this.bannerDiv.appendChild(divSlideShow);
	},
	
	viewImage: function() {
		var idBanner = this.idBanner;
		var id = this.showing;

		if (this.playing) {
			window.clearInterval(this.intervalid);
		}
		if (document.getElementById('B_viewImage_'+idBanner)) {
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				myBanner[idBanner].renderTransition(id,this);
			}
			imgPreloader.src = this.imageList[id]["url"];
		}
	},
	
	renderTransition: function(id,newimg) {
		var idBanner = this.idBanner;
		this.render = true;
		var img = document.getElementById('B_viewImage_'+idBanner);
		if (this.Engine.isKHTML) {
			newimg = document.createElement('img');	
			newimg.src = this.imageList[id]["url"];
		}
		newimg.id = 'B_viewImage_'+idBanner;
		newimg.style.position = 'absolute';
		newimg.style.left = '0px';

		var top = Math.floor((this.params.height-parseInt(this.imageList[id]["height"]))/2);
		newimg.style.top = top+'px';

		switch(this.params.transition) {
			case 'dissolve':
				newimg.style.display = 'none';
				if (img.src=='') {
					img.parentNode.replaceChild(newimg,img);
					new Effect.Appear(newimg,{duration:0.5,afterFinish:function(){myBanner[idBanner].render=false}})
					this.setImageEvents(id);
				} else {

					if (this.Engine.isKHTML) {
						left = left+8;
						top = top+8;
					}
					newimg.style.position = 'absolute';
					var left = Math.floor((this.params.width-parseInt(this.imageList[id]["width"]))/2);
					var divShow = document.getElementById('B_show_'+idBanner);
					left = left+parseInt(findPosX(divShow));
					newimg.style.left = '0px';
					newimg.style.zIndex = '2000';

					//document.getElementsByTagName('body')[0].appendChild(newimg);
					divShow.appendChild(newimg);
					new Effect.Appear(newimg,{
						duration: 0.5,
						afterFinish: function() {
							img.parentNode.removeChild(img);
							myBanner[idBanner].setImageEvents(id);
							myBanner[idBanner].resumePlaying();
						}
					});
					myBanner[idBanner].render=false;
				}
			break;
			case 'hslide':
				var offset;
				var divShow;
				var left;
				var top = Math.floor(this.params.height-parseInt(this.imageList[id]["height"]));
				newimg.style.top = top+'px';
				if (img.src=='') {
					newimg.style.display = 'none';
					img.parentNode.replaceChild(newimg,img);
					new Effect.Appear(newimg,{duration:0.5,afterFinish:function(){myBanner[idBanner].render=false}})
					this.setImageEvents(id);
					this.lastid = id;
				} else {
					
					divShow = document.getElementById('B_show_'+idBanner);
					
					var tempimage1 = document.createElement('img');
					tempimage1.style.marginRight = '5px';
					tempimage1.cssFloat = 'left';

					var tempimage2 = document.createElement('img');
					tempimage2.cssFloat = 'left';
					
					var imageSize = Element.getDimensions(img);
					
					if (this.params.orientation=='left') {
						tempimage1.src = img.src;
						tempimage2.src = newimg.src;
						offset = -(parseInt(imageSize.width)+5);
						left = '0px';
					} else if (this.params.orientation=='right') {
						tempimage1.src = newimg.src;
						tempimage2.src = img.src;
						offset = parseInt(this.imageList[id]["width"])+5;
						left = '-'+offset+'px';
					}
					topPos = this.params.height - Math.max(parseInt(imageSize.height),parseInt(this.imageList[id]["height"]));
					var slidingDiv = document.createElement('div');
					slidingDiv.style.position = 'absolute';
					slidingDiv.style.top = topPos+'px';
					slidingDiv.style.left = left;
					slidingDiv.style.width = (parseInt(this.imageList[id]["width"])+5+parseInt(imageSize.width))+'px';
					slidingDiv.appendChild(tempimage1);
					slidingDiv.appendChild(tempimage2);
					slidingDiv.style.display = 'none';
					
					divShow.appendChild(slidingDiv);
					new Effect.Appear(slidingDiv,{
						duration:0.3,
						afterFinish: function() {
							new Effect.MoveBy(slidingDiv, 0, offset,{
								duration:0.8,
								fps: 25,
								//transition: Effect.Transitions.exponential,
								beforeStart: function() {
									img.style.display = 'none';
									newimg.style.display = 'none';
									img.parentNode.replaceChild(newimg,img);
								},
								afterUpdate: function(effect) {
									if (effect.currentFrame==17) newimg.style.display = 'block';
								},
								afterFinish:function(){
									newimg.style.display = 'block';
									myBanner[idBanner].render = false;
									slidingDiv.parentNode.removeChild(slidingDiv);
									myBanner[idBanner].setImageEvents(id);
									myBanner[idBanner].resumePlaying();
								}
							});
						}
					});
					
					
					this.lastid = id;
				}
			break;
			case 'vslide':
				var offset;
				var divShow;
				var left;
				if (img.src=='') {
					newimg.style.display = 'none';
					img.parentNode.replaceChild(newimg,img);
					new Effect.Appear(newimg,{duration:0.5,afterFinish:function(){myBanner[idBanner].render=false}})
					this.setImageEvents(id);
					this.lastid = id;
				} else {
					
					divShow = document.getElementById('B_show_'+idBanner);
					
					var tempimage1 = document.createElement('img');
					tempimage1.style.marginBottom = '15px';
					
					var tempimage2 = document.createElement('img');
					
					var imageSize = Element.getDimensions(img);
					
					topPos = Math.floor((this.params.height - parseInt(imageSize.height))/2);
					var topPosNext = Math.floor((this.params.height - parseInt(this.imageList[id]['height']))/2);
					
					if (this.params.orientation=='up') {
						tempimage1.src = img.src;
						tempimage2.src = newimg.src;
						offset = -(this.params.height+15);
						tempimage1.style.marginTop = topPos+'px';
						tempimage2.style.marginTop = (topPosNext+topPos)+'px';
						top = '0px';
					} else if (this.params.orientation=='down') {
						tempimage1.src = newimg.src;
						tempimage2.src = img.src;
						offset = this.params.height+15;
						top = '-'+offset+'px';
						tempimage1.style.marginTop = topPosNext+'px';
						tempimage2.style.marginTop = (topPos+topPosNext)+'px';
					}
					
					var slidingDiv = document.createElement('div');
					slidingDiv.style.position = 'absolute';
					slidingDiv.style.top = top;
					slidingDiv.style.left = '0px';
					slidingDiv.style.width = this.params.width+'px';
					slidingDiv.style.height = (parseInt(this.imageList[id]["height"])+15+this.params.height)+'px';
					slidingDiv.appendChild(tempimage1);
					slidingDiv.appendChild(tempimage2);
					slidingDiv.style.display = 'none';
					
					divShow.appendChild(slidingDiv);

					new Effect.Appear(slidingDiv,{
						duration:0.3,
						afterFinish: function() {
							new Effect.MoveBy(slidingDiv, offset, 0,{
								duration:0.8,
								fps: 25,
								//transition: Effect.Transitions.slowstop,
								beforeStart: function() {
									img.style.display = 'none';
									newimg.style.display = 'none';
									img.parentNode.replaceChild(newimg,img);
								},
								afterUpdate: function(effect) {
									if (effect.currentFrame==17) newimg.style.display = 'block';
								},
								afterFinish:function(){
									newimg.style.display = 'block';
									myBanner[idBanner].render = false;
									slidingDiv.parentNode.removeChild(slidingDiv);
									myBanner[idBanner].setImageEvents(id);
									myBanner[idBanner].resumePlaying();
							}})
						}
					});
					this.lastid = id;
				}
			break;
		}
	},
	
	resumePlaying: function() {
		if (this.playing) {
			var idBanner = this.idBanner;
			this.intervalid = window.setInterval('myBanner['+idBanner+'].setNext()',this.params.duration*1000)
		}
	},
	
	setImageEvents: function(id) {
		var idBanner = this.idBanner;
		if (this.imageList[id]["link"]!==undefined) {
			document.getElementById('B_viewImage_'+idBanner).onclick = function() {
				document.location.href = myBanner[idBanner].imageList[id]["link"];
			}
			document.getElementById('B_viewImage_'+idBanner).style.cursor = 'pointer';
		}
	},
	
	play: function() {
		var idBanner = this.idBanner;
		this.playing = true;
		this.getNextImg();
		this.viewImage();
		this.intervalid = window.setInterval('myBanner['+idBanner+'].setNext()',this.params.duration*1000)
	},
	
	pause: function() {
		this.playing = false;
		window.clearInterval(this.intervalid);
	},
	
	getNextImg: function() {
		if ((this.showing==undefined) || (this.showing==(this.imageList.length-1))) {
			this.showing = 0;
		} else {
			this.showing += 1;
		}
	},
	
	setNext: function() {
		var idBanner = this.idBanner;
		this.getNextImg();
		this.viewImage();
	}
}

var myBanner = [];
