var Lightbox = new Class ({
	Implements: [Options, Events],
	
	options: {
		stylesheet: "/javascripts/libs/classes/Lightbox.css",
		targetSelector: ".lightbox",
		
		lightboxID: "ts-lightbox",
		lightboxClass: "ts-lightbox",
		
		// Display Options
		showModal: true,
		showTitleBar: false,
		showCloseButton: true,
		dismissOnModalClick: true,
		dismissOnEscape: true,
		
		// callback functions
		closeClick: function() {  },
		escapePress: function() {  },
		beforeShow: function() {  },
		afterShow: function() {  },
		beforeHide: function() {  },
		afterHide: function() {  }
		
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.css = new Element("link", { rel: "stylesheet", href: this.options.stylesheet, type: "text/css" }).inject(document.head);
		
		this.elements = document.getElements(this.options.targetSelector);
		
		this._dom();
		this._addKeyboardEvents();
		
		return this.lightbox;
		
	},
	
	_dom: function() {
		
		var self = this;
		
		// Lightbox
		self.lightbox = new Element("div", {
			"id": self.options.lightboxID,
			"class": self.options.lightboxClass
		}).inject(document.body, "bottom").fade("hide");
		
		self.lightbox.targets = self.elements;
		self.lightbox.isShowing = false;

		// add the hover image - RN - 2011-05-03
		self.lightbox.targets.addClass(self.options.lightboxClass + '-target')
		self.lightbox.targets.englarge = new Element('div', {
			"id": self.options.lightboxID + "-enlarge-button",
			"class": self.options.lightboxClass + "-enlarge-button",
			html: '&nbsp;'}).inject(self.lightbox.targets[0],"bottom");

		
		// Canvas
		self.lightbox.canvas = new Element("div", {
			"id": self.options.lightboxID + "-canvas",
			"class": self.options.lightboxClass + "-canvas"
		}).inject(self.lightbox);
		
		// Modal (Optional)
		self.lightbox.modal = false;
		if (self.options.showModal) {
			self.lightbox.modal = new Element("div", {
				"id": self.options.lightboxID + "-modal",
				"class": self.options.lightboxClass + "-modal"
			}).inject(document.body, "bottom").fade('hide');
			
			if (self.options.dismissOnModalClick) {
				
				self.lightbox.modal.addEvent("click", function() {
					
					self.options.closeClick();
					self.lightbox.hide();
					
				});
				
			}
		}
		
		// Titlebar (Optional)
		self.lightbox.titleBar = false;
		if (self.options.showTitleBar) {
			
			self.lightbox.titleBar = new Element("div", {
				"id": self.options.lightboxID + "-titlebar",
				"class": self.options.lightboxClass + "-titlebar"
			}).inject(self.lightbox, "top");
		
		}
		
		// Close Button (Optional, only with TitleBar)
		self.lightbox.titleBar.closeButton = false;
		if (self.options.showCloseButton) {
			
			var parentElement = (self.lightbox.titleBar) ? self.lightbox.titleBar : self.lightbox;
			
			self.lightbox.titleBar.closeButton = new Element("a", {
				"href": "#close-the-lightbox",
				"text": "Close",
				"id": self.options.lightboxID + "-close-button",
				"class": self.options.lightboxClass + "-close-button",
				events: {
					click: function(evt) {
						
						evt.stop();
						self.options.closeClick();
						self.lightbox.hide();
						
					}
				}
			}).inject(parentElement);
		}
		
		// Some Methods
		var tween = self.lightbox.get("tween");
		self.lightbox.show = function() {
			
			// reset the scrollheight.
			var newheight = document.getScrollHeight();
			var currentheight = self.lightbox.modal.getSize().y;
			
			if (newheight != currentheight) self.lightbox.modal.setStyle("height", newheight);
			
			self.options.beforeShow();
			
			tween.start("opacity", 1).chain(function() {
				self.options.afterShow();
				tween.callChain();
			});
			
			if (self.lightbox.modal) self.lightbox.modal.get("tween").start("opacity", 0.8);
			
			self.lightbox.isShowing = true;
			
		};
		
		self.lightbox.hide = function() {
			
			self.options.beforeHide();
			
			tween.start("opacity", 0).chain(function() {
				self.options.afterHide();
				tween.callChain();
				self.lightbox.canvas.empty();
			});
			
			if (self.lightbox.modal) self.lightbox.modal.get("tween").start("opacity", 0);
			
			self.lightbox.isShowing = false;
			
		};
		
		self.lightbox.loadContent = function(mixed) {
			
			var element = null;
			
			if (typeOf(mixed) == "string") {
				
				if (mixed.test("/")) {
					
					var uri = new URI(mixed);
					var data = uri.get("data");
					
					var filename = uri.get("file");
					var fileparts = filename.split(".");
					var extension = fileparts[fileparts.length - 1];
					
					if (extension == "jpeg" || extension == "jpg" || extension == "png" || extension == "gif") {
						
						// Image
						var title = (data.title) ? data.title : null;
						var alt = (data.alt) ? data.alt : null;
						
						element = new Element("img", { src: mixed, title: title, alt: alt, "class": self.options.lightboxClass + "-image" });
						self.insertContent(element);
						
					} else if (extension == "swf") {
						
						if (data.width && data.height) {
							
							var params = (data.params) ? data.params : null;
							var properties = (data.properties) ? data.properties : null;
							var vars = (data.vars) ? data.vars : null;
							var flashLoaded = function() {
								self.insertContent(element);
							};
							
							// Flash
							element = new Element("div", { id: self.options.lightboxID + "-flashcontainer" });
							element.flashobject = new Swiff(mixed, { id: self.options.lightboxID + "-flashobject", container: element, width: data.width, height: data.height, callbacks: { onLoad: flashLoaded } });
							self.insertContent(element);
							
						}
						
					} else {
						
						element = new Element("div", { id: self.options.lightboxID + "-ajaxcontainer" });
						
						// URL?
						var responseObject = null;
						var request = new Request({
							url: mixed, 
							method: "get",
						
							onRequest: function() {},
							onSuccess: function(response) {
								
								responseObject = response;
								
							},
							onFailure: function(xhr) {},
							onComplete: function() {
								
								if (responseObject) {
									element.set("html", responseObject);
									self.insertContent(element);
								}
								
							}
							
						}).send();
					
					}
				} else {
					
					// Selector?
					if (document.getElement(mixed)) {
						
						element = document.getElement(mixed);
						self.insertContent(element);
					}
					
				}
				
			} else if (typeOf(mixed) == "element") {
				
				// Element.
				element = mixed;
				self.insertContent(element);
				
			}
			
		};
		
	},
	
	insertContent: function(element) {
		
		var self = this;
		
		if (element) {
			
			// clear the old stuff if it exists
			if (self.lightbox.canvas.get("html")) self.lightbox.canvas.empty();
			
			// add the new stuff
			element.inject(self.lightbox.canvas);
			
			// runit.
			if (self.lightbox.isShowing == false) self.lightbox.show();
			return;
		}
		
	},
	
	_addKeyboardEvents: function() {
		
		var self = this;
		
		// Dismiss on Escape.
		if (self.options.dismissOnEscape) {
			
			document.addEvent("keyup", function(evt) {

				if (evt.key == "esc") { 
					
					self.options.escapePress();
					self.lightbox.hide();
					
				}
			
			});
			
		}
		
	}

});

Lightbox.Extra = new Class({
	
	/*	TODO:
		- Gallery Counter: x of y
		- Arrow Key Controls (left and right = next and previous).
	*/
	
	Implements: [Options, Events],
	Extends: Lightbox,
	
	options: {
		useGalleryObject: false,
		
		// new callbacks
		onButtonClick: function(target, index) {},
		onArrowKeyPress: function() {}
	},
	
	initialize: function(options) {
		this.setOptions(options);
		this.parent(options);
		
		if (this.options.useGalleryObject) {
			
			if (this.options.useGalleryObject.thumbnailImages && this.options.useGalleryObject.thumbnailImages.length > 1) {
				this._buildGalleryControls();
				//this._registerMoreKeyboardEvents();
			}
		}
		
		return this.lightbox;
		
	},
	
	_buildGalleryControls: function() {
		
		var self = this;
		var gallery = self.options.useGalleryObject;
		self.lightbox.thumbnailImages = gallery.thumbnailImages;
	
	// Previous Button
		self.lightbox.previousButton = new Element("a", { 
			id: self.options.lightboxID + "-previous-button",
			href: "#previous-image",
			title: "See Previous Image",
			text: "Previous",
			events: {
				click: function(evt) {
					
					if (evt) evt.stop();
					
					// get previous index.
					var current = self.lightbox.thumbnailImages.activeItemIndex;
					var previous = current - 1;
					if (previous <= -1) previous = (self.lightbox.thumbnailImages.length - 1);
					
					self.lightbox.changeActiveImage(previous);
					
					self.options.buttonClick(this, previous);
					
				}
			}
		}).inject(self.lightbox);
	
	// Next Button
		self.lightbox.nextButton = new Element("a", {
			id: self.options.lightboxID + "-next-button",
			href: "#next-image",
			title: "See Next Image",
			text: "Next",
			events: {
				click: function(evt) {
					
					if (evt) evt.stop();
					
					// get previous index.
					var current = self.lightbox.thumbnailImages.activeItemIndex;
					var next = current + 1;
					if (next >= self.lightbox.thumbnailImages.length) next = 0;
					
					self.lightbox.changeActiveImage(next);
					
					self.options.buttonClick(this, next);
										
				}
			}
		}).inject(self.lightbox);
		
		
		self.lightbox.changeActiveImage = function(index) {
			
			// set the active item.
			self.lightbox.thumbnailImages.setActiveItem(index);
			if (gallery.thumbnailSlider) gallery.thumbnailSlider.slideToIndex(index);
			
			// replace the large image.
			var largeImage = null;
			var activeImage = self.lightbox.thumbnailImages[index];
			if (typeOf(gallery.imagesCache) == "array" && gallery.imagesCache > 0) {
				
				largeImage = gallery.imagesCache[index];
				
			} else {
				
				largeImage = new Element("img", {
					src: activeImage.get("href"),
					alt: activeImage.get("alt"),
					title: activeImage.get('title')
				});
				
			}
			
			largeImage.replaces(gallery.mainImageContainer.getElement("img"));
			
			// replace the large image container href
			var uri = new URI(activeImage.get("href"));
			var extraLargeImage = uri.get("data").large;
			self.lightbox.loadContent(extraLargeImage);
			
		};
		
	}
	
});
