var Gallery = new Class({
	Implements: [Options,Events],
	options: {
		content: "content",
		overlay: {
			opacity: 0.8,
			bg: "#000000"
		},
		lang: 0, // lang uid from typo3
		autoplay: true,
		autoplayDelay: 3000
	},
	initialize: function(options) {
		this.setOptions(options);
		SqueezeBox.initialize({
			onOpen: function() {
				if(!this.stop && this.playButton) {
                	this.currentScrollPos = this.thumbCol.getScroll().y;
					if(this.playButton.hasClass("act")) {
		            	this.stopButton.fireEvent("click");
					}
				}
			}.bind(this)
		});
		this.lang = this.options.lang;
		this.content = $(this.options.content);
		this.loaded = false; // auf true wenn die Gallerie mit HTML schon existiert
		this.isLoading = false; // auf true wenn eine Galerie gerade vorgeladen wird
        this.curImgIndex = 0;
		this.isFading = false;
		this.stop = false;
		this.timer = null;
		this.createOverlay();
	},
	setLanguage: function(lang) {
		this.lang = lang;
	},
	showGallery: function(pageUid) {
		if(!this.isLoading) {
			if(!this.loaded) {
				// load gallery from scratch
				this.loadGallery(pageUid,function() {
					this.emptyContent(function() {
						this.scrollSteps = ((this.normalImgs.length - 1) / 4).toInt();
						this.currentScrollStep = 0;
						this.createHtmlStructure();
						this.hideLoading(function() {
							this.tweenMinis();
							this.content.tween("opacity",1).get("tween").chain(function() {
								this.isLoading = false;
								this.loaded = true;
								if(this.options.autoplay) {
									this.timer = this.autoplay.delay(this.options.autoplayDelay,this);
								}
							}.bind(this));
						}.bind(this));
					}.bind(this));
				}.bind(this));
			}
			else {
				// Galerie existiert schon, nur Dinge updaten die es auch benötigt
                $clear(this.timer);
				this.isFading = false;
				this.stop = false;
				this.curImgIndex = 0;
				delete (this.thumbImgs);
				delete (this.normalImgs);
				delete (this.description);
                this.loadGallery(pageUid,function() {
                    this.content.tween("opacity",0).get("tween").chain(function () {
                        this.scrollSteps = ((this.normalImgs.length - 1) / 4).toInt();
                        this.currentScrollStep = 0;
                        this.updateHtmlStructure();
                        this.hideLoading(function() {
                            this.content.tween("opacity",1).get("tween").chain(function() {
                                this.isLoading = false;
                                if(this.options.autoplay) {
                                    this.timer = this.autoplay.delay(this.options.autoplayDelay,this);
                                }
                            }.bind(this));
                        }.bind(this));
                    }.bind(this));
                }.bind(this));
				
			}
			return (true);
		}
		else {
			return (false);
		}
	},
	loadGallery: function(pageUid,fnAfter) {
		this.isLoading = true;
		this.showLoading();
		new Request.JSON({ "url": "index.php?id="+pageUid+"&eID=tx_snigallery_pi1&L="+this.lang,
			onSuccess: function(respJson) {
				var normal = Array();
				var thumbs = Array();
				this.description = Array();
				var bigImgs = Array();
				respJson.images.each(function(item) {
					thumbs.include(item.thumb);
					normal.include(item.normal);
					this.description.push(item.description);
					bigImgs.include(item.big);
				}.bind(this));
				$("controls").getElement("h1").set("text",respJson.slogan);
				this.thumbImgs = new Asset.images(thumbs, {
					"properties": {
						"events": {
							"mouseenter": function() {
								this.addClass("hover");
							},
							"mouseleave": function() {
								this.removeClass("hover");
							}
						}
					},
					"onProgress": function(counter,index) {
						this.thumbImgs[index].addEvent("click",function() {
							this.show(index);
						}.bind(this));
					}.bind(this),
					"onComplete": function() {
						this.normalImgs = new Asset.images(normal, {
							"properties": {
								"tween": {
									"duration": "normal",
									"transition": "sine:in:out"
								}
							},
							"onProgress": function(counter,index) {
								this.normalImgs[index].set("title",bigImgs[index]);
								SqueezeBox.assign(this.normalImgs[index]);
							}.bind(this),
							"onComplete": function() {
								if(fnAfter) {
									fnAfter.attempt(this)
								}
							}.bind(this)
						});
					}.bind(this)
				});
			}.bind(this)
		}).send();	
	},
	autoplay: function() {
		if(!this.stop) {
			$clear(this.timer);
			if(this.curImgIndex < this.normalImgs.length - 1) {
				var toIndex = this.curImgIndex + 1;
			}
			else {
				var toIndex = 0;
			}
			this.show(toIndex,this.autoplay.bind(this),this.options.autoplayDelay);
		}
	},
	show: function(index,fnAfter,timeout) {
		if(!fnAfter && !this.stop && this.playButton.hasClass("act")) {
			// show wird nicht von autoplay ausgeführt, stoppe das Autoplaying
			this.stopButton.fireEvent("click");
		}
		// neues Bild hinter aktuellem einfügen
		// aktuelles Bild hat immer z-index = 8, das zu dem gefadet werden soll hat z-index = 7, die control-arrows haben 9
		if(this.curImgIndex != index && !this.isFading && this.normalImgs[index]) {
			this.normalImgs[index].setStyle("z-index",7);
			this.rightCol.adopt(this.normalImgs[index]);
			this.isFading = true;
			this.normalImgs[this.curImgIndex].tween("opacity",0).get("tween").chain(function() {
				this.normalImgs[this.curImgIndex] = this.normalImgs[this.curImgIndex].dispose().clone().cloneEvents(this.normalImgs[this.curImgIndex]).setStyle("opacity",1);
				this.normalImgs[index].setStyle("z-index",8);
				this.curImgIndex = index;
				this.descr.set("html",this.description[this.curImgIndex]);
				this.isFading = false;
				if(fnAfter) {
					this.timer = fnAfter.delay(timeout,this);
				}
			}.bind(this));
			var curTop = index * 74;
			this.actBorder.tween("top",curTop);
			// check if we must scroll
			if(index > ((this.currentScrollStep + 1) * 4) - 1 || index < (this.currentScrollStep) * 4) {
				var toStep = (index / 4).toInt();
				this.scrollToStep(toStep);
			}
		}	
	},
	tweenMinis: function(fnAfter) {
		var to = {};
		[0,1,2,3].each(function(item) {
			var toTop = 42 + (item * 74); 
			to[item] = {
				"width": 68,
				"height": 68,
				"top": ["0", toTop],
				"margin-left": 23,
				"opacity": 0
			};
			if(item==0) {
				to[item]["opacity"] = 1;
				to[item]["border-color"] = "#ec7f0c";
			}
		});
		new Fx.Elements($("gal_thumbs").getElements("div"), {
			duration: "normal",
			transition: "sine:in:out"
		}).start(to).chain(function() {
			$("gal_thumbs").empty();
			this.actBorder.setStyle("visibility","visible");
			if(fnAfter) {
				fnAfter.attempt(this)
			}
		}.bind(this));
	},
	scrollToStep: function(step,noAni) {
		this.currentScrollStep = step;
		if(!noAni) {
			this.scrollFx.start(0,this.currentScrollStep * 296);
		}
		else {
			this.thumbCol.scrollTo(0,this.currentScrollStep * 296);
		}
		if(step > 0) {
			this.scrollTop.setStyle("display","block");
		}
		else {
			this.scrollTop.setStyle("display","none");
		}
		if(step < this.scrollSteps) {
			this.scrollBottom.setStyle("display","block");
		}
		else {
			this.scrollBottom.setStyle("display","none");
		}
	},
	createHtmlStructure: function() {
		var topWrap = new Element("div", {
			"class": "topWrap",
            "events": {
                "mouseenter": function() {
                    nextArrow.setStyle("opacity",1);
                    prevArrow.setStyle("opacity",1);
                }.bind(this),
                "mouseleave": function() {
                    nextArrow.setStyle("opacity",0);
                    prevArrow.setStyle("opacity",0);
                }.bind(this)
            }
		});
		var bottomWrap = new Element("div", {
			"class": "bottomWrap"
		});
		this.thumbCol = new Element("div", {
			"class": "thumbCol"
		});
		this.scrollFx = new Fx.Scroll(this.thumbCol, {
			"link": "cancel",
			"duration": "normal",
			"transition": "sine:in:out"
		});
		this.actBorder = new Element("div", {
			"class": "actBorder",
			"styles": {
				"visibility": "hidden"
			},
			"tween": {
				"duration": "normal",
				"transition": "sine:in:out",
				"link": "cancel"
			}
		});
		this.thumbCol.adopt(this.actBorder,this.thumbImgs);
		this.rightCol = new Element("div", {
			"class": "rightCol"
		});
		this.scrollBottom = new Element("span", {
			"class": "scrollDown scroll",
			"events": {
				"click": function() {
                    if(this.currentScrollStep < this.scrollSteps) {
                        this.scrollToStep(this.currentScrollStep + 1);
					}
				}.bind(this)
			}
		});
		if(!this.scrollSteps) {
			this.scrollBottom.setStyle("display","none");
		}
		this.scrollTop = new Element("span", {
			"class": "scrollTop scroll",
			"styles": {"display": "none"},
			"events": {
				"click": function(e) {
                    if(this.currentScrollStep > 0) {
						this.scrollToStep(this.currentScrollStep - 1);
					}
				}.bind(this)
			}
		});
		var nextArrow = new Element("span", {
			"class": "nextArrow arrow",
			"styles": { "opacity": 0 },
			"events": {
				"click": function(e) {
					if(this.curImgIndex==this.normalImgs.length-1) {
						this.show(0);
					}
					else {
						this.show(this.curImgIndex + 1);
					}
				}.bind(this)
			}
		});
        var prevArrow = new Element("span", {
            "class": "prevArrow arrow",
            "styles": { "opacity": 0 },
            "events": {
                "click": function(e) {
                    if(this.curImgIndex==0) {
                        this.show(this.normalImgs.length-1);
                    }
                    else {
                        this.show(this.curImgIndex - 1);
                    }
                }.bind(this)
            }
        });
		this.normalImgs[0].setStyle("z-index",8);
		this.rightCol.adopt(this.normalImgs[0]);
		this.descr = new Element("p", {
			"html": this.description[0],
			"class": "descr"
		});
		var controlsWrap = new Element("div", {
			"class": "controlsWrap"
		});
		this.playButton = new Element("span", {
			"text": "Play",
			"events": {
				"click": function(e) {
					if(this.stop || !this.options.autoplay) {
						this.stop = false;
						$clear(this.timer);
                        this.timer = this.autoplay.delay(this.options.autoplayDelay,this);
						this.playButton.addClass("act");
						this.stopButton.removeClass("act");
					}
				}.bind(this)
			}
		});
		if(this.options.autoplay) {
			this.playButton.addClass("act");
		}
		this.stopButton = new Element("span", {
			"text": "Stop",
			"events": {
				"click": function() {
					this.stop = true;
					$clear(this.timer);
					this.playButton.removeClass("act");
					this.stopButton.addClass("act");
				}.bind(this)
			}
		});
		if(!this.options.autoplay) {
			this.stopButton.addClass("act");
		}
		var next = new Element("a", {
			"text": "Next"
		});
		next.cloneEvents(nextArrow,"click");
		var prev = new Element("a", {
			"text": "Previous"
		});
		prev.cloneEvents(prevArrow,"click");
		controlsWrap.adopt(this.playButton,this.stopButton,prev,next);
		bottomWrap.adopt(this.descr,controlsWrap);
		topWrap.adopt(this.thumbCol,this.scrollTop,this.scrollBottom,prevArrow,nextArrow,this.rightCol);
		this.content.adopt(topWrap,bottomWrap);
	},
	updateHtmlStructure: function() {
		this.thumbCol.empty();
		this.actBorder.setStyle("top",0);
        this.thumbCol.adopt(this.actBorder,this.thumbImgs);
		this.scrollToStep(0);
        this.normalImgs[0].setStyle("z-index",8);
		this.rightCol.empty();
        this.rightCol.adopt(this.normalImgs[0]);
		this.descr.set("html",this.description[0]);
        if(!this.scrollSteps) {
            this.scrollBottom.setStyle("display","none");
        }
        if(this.options.autoplay) {
            this.playButton.addClass("act");
        }
		else {
			this.playButton.removeClass("act");
		}
        if(!this.options.autoplay) {
            this.stopButton.addClass("act");
        }
		else {
			this.stopButton.removeClass("act");
		}
	},
	createOverlay: function() {
		var size = this.content.getSize();
		this.overlay = new Element("div", {
			"class": "gal_overlay",
			"styles": {
				"width": size.x,
				"height": size.y,
				"opacity": 0,
				"position": "absolute",
				"z-index": "10",
				"background-color": this.options.overlay.bg,
				"display": "none"
			},
			"tween": {
				"duration": "normal",
				"link": "cancel"
			}
		});
		this.overlay.inject(this.content,"before");
	},
	showLoading: function(fnAfter) {
		this.overlay.setStyle("display","block");
		return (this.overlay.tween("opacity",this.options.overlay.opacity).get("tween"));
	},
	hideLoading: function(fnAfter) {
		this.overlay.tween("opacity",0).get("tween").chain(function() { 
			this.overlay.setStyle("display","none") 
			if(fnAfter) {
				fnAfter.attempt(this);
			}
		}.bind(this));
	},
	emptyContent: function(fnAfter) {
        this.content.set("tween", { "duration": "long" });
        // erster Overlay mit Loading - Bilder vorloden, donn content austweenen, donn kastelen ormorphen - gallery HTML aufbauen
        this.content.tween("opacity",0).get("tween").chain(function() {
            this.content.empty();
			if(fnAfter) {
				fnAfter.attempt(this);
			}	
        }.bind(this));
	}
});

