/*
	GalleryDisplay 
	(c) 2011 BlueSoap, updated 2011.03.29
	
	Based on mediaboxAdvanced v1.2.4 - The ultimate extension of Slimbox and Mediabox; an all-media script
	(c) 2007-2010 John Einselen <http://iaian7.com>

*/

/*
(function() {
	var ls = document.createElement('link');
	ls.rel = 'stylesheet';
	ls.href = '/shop/styles/mediabox.css';
	(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ls);
})(); */

var Asset={javascript:function(f,c){if(!c){c={};}var a=new Element("script",{src:f,type:"text/javascript"}),g=c.document||document,b=0,d=c.onload||c.onLoad;
var e=d?function(){if(++b==1){d.call(this);}}:function(){};delete c.onload;delete c.onLoad;delete c.document;return a.addEvents({load:e,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){e.call(this);
}}}).set(c).inject(g.head);},css:function(d,a){if(!a){a={};}var b=new Element("link",{rel:"stylesheet",media:"screen",type:"text/css",href:d});var c=a.onload||a.onLoad,e=a.document||document;
delete a.onload;delete a.onLoad;delete a.document;if(c){b.addEvent("load",c);}return b.set(a).inject(e.head);},image:function(c,b){if(!b){b={};}var d=new Image(),a=document.id(d)||new Element("img");
["load","abort","error"].each(function(e){var g="on"+e,f="on"+e.capitalize(),h=b[g]||b[f]||function(){};delete b[f];delete b[g];d[g]=function(){if(!d){return;
}if(!a.parentNode){a.width=d.width;a.height=d.height;}d=d.onload=d.onabort=d.onerror=null;h.delay(1,a,a);a.fireEvent(e,a,1);};});d.src=a.src=c;if(d&&d.complete){d.onload.delay(1);
}return a.set(b);},images:function(c,b){c=Array.from(c);var d=function(){},a=0;b=Object.merge({onComplete:d,onProgress:d,onError:d,properties:{}},b);return new Elements(c.map(function(f,e){return Asset.image(f,Object.append(b.properties,{onload:function(){a++;
b.onProgress.call(this,a,e,f);if(a==c.length){b.onComplete();}},onerror:function(){a++;b.onError.call(this,a,e,f);if(a==c.length){b.onComplete();}}}));
}));}};

var GalleryDisplay;

(function() {
	
	// Global variables, accessible to GalleryDisplay only
	var options, images, activeImage, prevImage, nextImage, top, mTop, left, mLeft, winWidth, winHeight, fx, preload, preloadPrev = new Image(), preloadNext = new Image(), foxfix = false, iefix = false,
	// DOM elements
	overlay, center, image, bottom, captionSplit, title, caption, prevLink, number, nextLink, list, _title, _url, social,
	// GalleryDisplay specific vars
	URL, WH, WHL, elrel, mediaWidth, mediaHeight, mediaType = "none", mediaSplit, mediaId = "GalleryDisplay", mediaFmt,
	
	displayImage, status;

	/*	Initialization  */

	window.addEvent("domready", function() {
		// Create and append the GalleryDisplay HTML code at the bottom of the document
		document.id(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "gdOverlay"}).addEvent("click", close),
				container = new Element("div", {id: "gdContainer"})
			]).setStyle("display", "none")
		);
		
		leftBar = new Element("div", {id: "gdLeftBar"}).injectInside(container).adopt(
			DisImage = new Element("div", {id: "gdDisImage"}),
			DisCaption = new Element("div", {id: "gdDisCaption"}),
			DisThumbnails = new Element("div", {id: "gdDisThumbnails"})
		);
		image = new Element("div", {id: "gdImage"}).injectInside(container);
		nav = new Element("div", {id: "gdNav"}).injectInside(container).adopt(	
			prevLink = new Element("a", {id: "gdPrev", href: "#", html: '<span></span> Previous'}).addEvent("click", previous),
			nextLink = new Element("a", {id: "gdNext", href: "#", html: 'Next <span></span>'}).addEvent("click", next),
			emailLink = new Element("a", {id: "gdEmail", 'class': 'social_icons', html: 'Email'}),
			facebookLink = new Element("a", {id: "gdFacebook", 'class': 'social_icons', html: 'Facebook'}).addEvent("click", poplink),
			twitterLink = new Element("a", {id: "gdTwitter", 'class': 'social_icons', html: 'Twitter'}).addEvent("click", poplink),
			new Element("a", {id: "gdClose", href: "#", html: 'Close'}).addEvent("click", close)
		);
		
		fx = {
			overlay: new Fx.Tween(overlay, {property: "opacity", duration: 360}).set(0),
			image: new Fx.Tween(image, {property: "opacity", duration: 360}).set(0),
			leftBar: new Fx.Tween(leftBar, {property: "opacity", duration: 240, onComplete: AnimateContent}).set(0),
			nav: new Fx.Tween(nav, {property: "opacity", duration: 240, onComplete: imageAnimate}).set(0)
		};
		
		social = {
			email: "mailto:?subject=FW:%20{TITLE}&body={SHARE_URL}",
			facebook : "http://www.facebook.com/share.php?u={SHARE_URL}",
			twitter : "http://twitter.com/share?text={TITLE} | "+window.location.hostname+"&url={SHARE_URL}"
		},
		
		status = {
			thumbs: false,
			large: false
		};
		
		displayImage = {
			src: null,
			title: null
		};
	});
	
	
	/*	API		*/

	GalleryDisplay = {
		close: function(){ 
			close();
		}, 

		open: function(_images, startImage, _options) {
			options = $extend({
						
				imageSRC: '/image.php?image=/images/{FOLDER}/{IMG}&width={WIDTH}',
				defaultFolder: 'gallery',
				defaultDisWidth: 200,
				defaultThumbWidth: 60,
				defaultImgWidth: 777,							
							  
				loop: false,					// Allows to navigate between first and last images
				keyboard: true,					// Enables keyboard control; escape key, left arrow, and right arrow
				alpha: true,					// Adds 'x', 'c', 'p', and 'n' when keyboard control is also set to true
				stopKey: false,					// Stops all default keyboard actions while overlay is open (such as up/down arrows)
													// Does not apply to iFrame content, does not affect mouse scrolling
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				resizeOpening: true,			// Determines if box opens small and grows (true) or starts at larger size (false)
				resizeDuration: 240,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// Mootools transition effect (false leaves it at the default)
				initialWidth: 320,				// Initial width of the box (in pixels)
				defaultWidth: 1041,				// Default width of the box (in pixels) for undefined media (MP4, FLV, etc.)

			}, _options || {});
			

			if (typeof _images == "string") {	// The function is called for a single image, with URL and Title as first two arguments
				_images = [[_images,startImage,_options]];
				startImage = 0;
			}
			
			options.imageSRC = options.imageSRC.replace('{FOLDER}', options.defaultFolder);

			images = _images;
			options.loop = options.loop && (images.length > 1);

			size();
			setup(true);
			top = window.getScrollTop() + (window.getHeight()/2);
			left = window.getScrollLeft() + (window.getWidth()/2);
			fx.resize = new Fx.Morph(container, $extend({duration: options.resizeDuration, onComplete: AnimateLayout}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			container.setStyle('display', '');
			fx.overlay.start(options.overlayOpacity);
			return changeImage(startImage);
		}
	}
	
	Element.implement({
		GalleryDisplay: function(_options, linkMapper) {
			$$(this).GalleryDisplay(_options, linkMapper);	// The processing of a single element is similar to the processing of a collection with a single element

			return this;
		}
	});
	
	Elements.implement({
		/*
			options:	Optional options object, see Mediabox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 3 elements:
						the image URL and the image caption (may contain HTML)
			linksFilter:Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
						the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
						This function must always return true when the DOM element argument is "this".
		*/
		GalleryDisplay: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				elrel = el.rel.split(/[\[\]]/);
				elrel = elrel[1];
				eljson = ( el.getAttribute("data") ) ? el.getAttribute("data") : "";
				elid = ( el.getAttribute("id") ) ? el.getAttribute("id") : "";
				return [el.href, el.title, elrel, eljson, elid];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.addEvent('contextmenu', function(e){
				if (this.toString().match(/\.gif|\.jpg|\.jpeg|\.png/i)) e.stop();
			});
			
			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredArray = links.filter(linksFilter, this);
				var filteredLinks = [];
				var filteredHrefs = [];

				filteredArray.each(function(item, index){
					if(filteredHrefs.indexOf(item.toString()) < 0) {
						filteredLinks.include(filteredArray[index]);
						filteredHrefs.include(filteredArray[index].toString());
					};
				});

				return GalleryDisplay.open(filteredLinks.map(linkMapper), filteredHrefs.indexOf(this.toString()), _options);
			});

			return links;
		}
	});
	
	function poplink() {
		popupform(this.href); 
		return false;
	}
	
	function position() {
		overlay.setStyles({top: window.getScrollTop(), left: window.getScrollLeft()});
	}

	function size() {
		winWidth = window.getWidth();
		winHeight = window.getHeight();
		overlay.setStyles({width: winWidth, height: winHeight});
	}
	
	function setup(open) {
		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		if (iefix) window[fn]("scroll", position);
		window[fn]("resize", size);
//		if (options.keyboard) document[fn]("keydown", keyDown);

	}
	
	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	
	function changeImage(imageIndex) {
		
		if (imageIndex >= 0) {
			image.set('html', '');
			activeImage = imageIndex;
			prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
			nextImage = activeImage + 1;
			if (nextImage == images.length) nextImage = options.loop ? 0 : -1;
			stop();
			
			if ( activeImage < ( images.length - 1 ) ) nextLink.setStyles({"cursor": "pointer", "opacity": 1});
			if ( activeImage > 0 ) prevLink.setStyles({"cursor": "pointer", "opacity": 1});
			
			container.className = "gdLoading";
		}

		// Lets do the cool loading
		container.className = "gdLoading";

		if ( images[imageIndex][3] != "" ) {
			
			var a = JSON.decode(images[imageIndex][3]);

			var subImages = {
				thumbs: new Array(),
				load: new Array()
			}
			
			a.previews.each(function(image, i) {
	
				if ( i ) {
					var thumbImage = options.imageSRC.replace('{IMG}', image.src).replace('{WIDTH}', options.defaultThumbWidth);
				} else {
					displayImage.src = options.imageSRC.replace('{IMG}', image.src).replace('{WIDTH}', options.defaultDisWidth);
					DisCaption.set('html', image.desc);
					
					_title = encodeURIComponent(image.title);
					_url = encodeURIComponent('http://' + window.location.host + window.location.pathname + '/#!/' + images[imageIndex][4]);
					
					emailLink.set('href', social.email.replace('{TITLE}', _title).replace('{SHARE_URL}', _url));
					facebookLink.set('href', social.facebook.replace('{TITLE}', _title).replace('{SHARE_URL}', _url));
					twitterLink.set('href', social.twitter.replace('{TITLE}', _title).replace('{SHARE_URL}', _url));
				}
							
				var largeImage = options.imageSRC.replace('{IMG}', image.src).replace('{WIDTH}', options.defaultImgWidth);
					
				subImages.thumbs.push(thumbImage);
				subImages.load.push(largeImage);
	
			});
						
			Asset.image(displayImage.src).inject(DisImage);
			Asset.image(subImages.load[0]).inject(image);
						
			var storedImages = Asset.images(subImages.load, {
				properties: {
					'class': 'myImage',
					title: 'myImage'
				},
				onComplete: function(){
					status.large = true;
				}
			});
			
			if ( subImages.thumbs.length > 1 ) {
				DisThumbnails.set('html', '<div class="click_enlarge">Click to open each page</div> <ul></ul>');
				list = DisThumbnails.getElement('ul');
			} 
			
			Asset.images(subImages.thumbs, {
				onProgress: function(counter,index) {
//					progressBar.set((counter + 1) * (100 / images.length));
				},
				onComplete: function(){
					
					subImages.thumbs.each(function(im, i) {
						if ( i ) {					   
							var li = new Element('li').inject(list);
							new Element('img',{ 
								src: im, 
								events: {
									'click' : function () {
										
										fx.image.cancel().start(0);
										image.empty();
										(function() {
											new Element('img',{ title: 'test', src: storedImages[i].src }).inject(image);
//											
											fx.image.start(1);
										}).delay(500);
									}
								}
							}).inject(li);
						}
						
					});
					status.thumbs = true;
				}
			});
			
		} else {
			status.thumbs = true;
			status.large = true;
		}
		
		// Lets call the sfx		
		
		(function() {		
			if ( status.thumbs && status.large ) {
				startEffect()
			}
		}).periodical(100);
		
		return false;
	}
	
	function imageAnimate() {
		fx.image.start(1);
	}
	
	function AnimateLayout() {
		
		container.className = "";
//		if (prevImage >= 0) prevLink.style.display = "";
//		if (nextImage >= 0) nextLink.style.display = "";
		fx.nav.start(1);
		fx.leftBar.start(1);
		
		
	}
	
	function AnimateContent() {
//		alert();	
//		fx.DisImage.start(1);
//		fx.DisCaption.start(1);
//		fx.DisThumbnails.start(1);
		
	}
	
	function startEffect() {
		
		// Lets add in all the fancy effects here
		fx.resize.start({width: mediaWidth, height: mediaHeight, marginTop: mTop, marginLeft: mLeft});
		
	}
	
	function emptyDis() {
		DisImage.empty();
		DisCaption.empty();
		DisThumbnails.empty();
		image.empty();
	}
	
	function stop() {
//		if (preload) preload.onload = $empty;

		fx.resize.cancel();
		fx.image.cancel().set(0);
		fx.leftBar.cancel().set(0);
		emptyDis();
		$$(prevLink, nextLink).setStyles({"cursor": "default", "opacity": 0.2});
	}
	
	function close() {

		// Lets close
		if (activeImage >= 0) {
//			preload.onload = $empty;
			image.set('html', '');
			for (var f in fx) fx[f].cancel();
			for (var f in status) status[f] = false;
			container.setStyle("display", "none");
			emptyDis();
			fx.overlay.chain(setup).start(0);
		}
		
		return false;
	}
	
	function popupform(c) {
		LeftPosition = (screen.width) ? (screen.width-550)/2 : 0;
		TopPosition = (screen.height) ? (screen.height-450)/2 : 0;
		if (!window.focus)return true;
			window.open(c, '', 'height=450,width=550,scrollbars=no,location=no,status=no,toolbars=no,top='+TopPosition+',left='+LeftPosition);
	
		return true;
	}
		  
})();


// AUTOLOAD CODE BLOCK
GalleryDisplay.scanPage = function() {
	var links = $$("a").filter(function(el) {
		el.rel.test(/^canvasbox/i);
		return el.rel && el.rel.test(/^canvasbox/i);
	});
	
	$$(links).GalleryDisplay({imageSRC: '/shop/mimage.php?img=/{IMG}&cat=gallery&width={WIDTH}', defaultFolder:'gallery'}, null, function(el) {
		var rel0 = this.rel.replace(/[[]|]/gi," ");
		var relsize = rel0.split(" ");
		return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
	});
};
window.addEvent("domready", GalleryDisplay.scanPage);

window.addEvent("domready", function() {

	if( window.location.hash.contains('!') ) {
		chars = "/";
		lnk = window.location.hash.replace(new RegExp("[" + chars + "]+$", "g"), "");
		
//		alert();
		if ( document.id(lnk.substring(3)) != null ) {
			document.id(lnk.substring(3)).fireEvent('click');
		}
		
//		lnk = lnk.substring(lnk.indexOf('//')+3);		
//		if ( lnk.contains('/') ) lnk = lnk.substring(0,lnk.indexOf('/'));
//		canvas_object(canvas_i,document.id('hash_'+lnk).get('rel'));
//		overlay.open();
	}
	
});
