/*
	reflection.js for mootools v1.43
	(c) 2006-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
Element.implement({reflect:function(b){var a=this;if(a.get("tag")=="img"){b=$extend({height:1/3,opacity:0.5},b);a.unreflect();function c(){var f=a.width,d=a.height,k,h,l,g,j;h=Math.floor((b.height>1)?Math.min(d,b.height):d*b.height);if(Browser.Engine.trident){k=new Element("img",{src:a.src,styles:{width:f,height:d,marginBottom:h-d,filter:"flipv progid:DXImageTransform.Microsoft.Alpha(opacity="+(b.opacity*100)+", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy="+(h/d*100)+")"}})}else{k=new Element("canvas");if(!k.getContext){return}try{g=k.setProperties({width:f,height:h}).getContext("2d");g.save();g.translate(0,d-1);g.scale(1,-1);g.drawImage(a,0,0,f,d);g.restore();g.globalCompositeOperation="destination-out";j=g.createLinearGradient(0,0,0,h);j.addColorStop(0,"rgba(255, 255, 255, "+(1-b.opacity)+")");j.addColorStop(1,"rgba(255, 255, 255, 1.0)");g.fillStyle=j;g.rect(0,0,f,h);g.fill()}catch(i){return}}k.setStyles({display:"block",border:0});l=new Element(($(a.parentNode).get("tag")=="a")?"span":"div").injectAfter(a).adopt(a,k);l.className=a.className;a.store("reflected",l.style.cssText=a.style.cssText);l.setStyles({width:f,height:d+h,overflow:"hidden"});a.style.cssText="display: block; border: 0px";a.className="reflected"}if(a.complete){c()}else{a.onload=c}}return a},unreflect:function(){var b=this,a=this.retrieve("reflected"),c;b.onload=$empty;if(a!==null){c=b.parentNode;b.className=c.className;b.style.cssText=a;b.store("reflected",null);c.parentNode.replaceChild(b,c)}return b}});

window.addEvent('domready',function() {
									
	$$("img").filter(function(img) { return img.hasClass("reflect"); }).reflect({height:1/3, opacity: 0.4});
									
	new SmoothScroll({ duration:700 }, window);

	new Element('img', {
		'id': 'loader',
		'src': '/images/ajax-loader.gif'
	}).inject(document.body, "bottom");
	
	var slideshow = $$('.slideshow-carousel');
	
	slideshow.each(function(show, k) {
							
		var f1 = show.getElements('.floater')[0], f2 = show.getElements('.floater')[1], transition = 20000;
		
		function again() {

			var f1_top = f1.getStyle('right').toInt();
			var f2_top = f2.getStyle('right').toInt();
			
			if(parseFloat(f1_top) > parseFloat(f2_top)) {
				f1.setStyle('right', '-1115px');
				f2.setStyle('right', '-15px');
			} else {
				f1.setStyle('right', '-15px');
				f2.setStyle('right', '-1115px');
			}

			go();
			
		}
				
		var go = function() {
			
			var f1_top = f1.getStyle('right').toInt();
		  	var f2_top = f2.getStyle('right').toInt();
						
			var fx = {
				f1: new Fx.Morph(f1, {duration: transition, transition: Fx.Transitions.linear}),
				f2: new Fx.Morph(f2, {duration: transition, transition: Fx.Transitions.linear, onComplete: again})
			};
			
			fx.f1.start({'right': f1_top + 1100});
			fx.f2.start({'right': f2_top + 1100});
			
		};
		
		go();
	
	});	
	
	/*
	*	MEDIA Module // Based on the certain snippets from MediaBoxAdv.

		//	mediaboxAdvanced v1.2.4 - The ultimate extension of Slimbox and Mediabox; an all-media script
		//	updated 2010.06.15
		//	(c) 2007-2010 John Einselen <http://iaian7.com>
		//		based on
		//	based on Slimbox v1.64 - The ultimate lightweight Lightbox clone
		//	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
		//	MIT-style license.
	*
	----------------------------------------------------------------------------------------------*/
									
	var canvas_i = $$('.x-event');
	var media_list = $$('.x-list-2 li');
	
	var overlay = new Overlay(document.body,{
		duration: 500,
		opacity: 0.88,
		zIndex: 999,
		onShow: function(item) { 
			document.id("loader").setStyle('visibility', 'visible'); 
			document.id("logo").addClass("white");
			document.id("navBar").addClass("white");		
		},
		onClose: function() { 
			document.id("canvas_content").dispose();
			document.id("loader").setStyle('visibility', 'hidden'); 
			document.id("logo").removeClass("white");
			document.id("navBar").removeClass("white");
		},
		onClick: function() {
			this.close();
		}
	});
	
	function canvas_object(canvas_i,i) {
		
		options = {
			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.7,			// 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)
			initialHeight: 180,				// Initial height of the box (in pixels)
			defaultWidth: 777,				// Default width of the box (in pixels) for undefined media (MP4, FLV, etc.)
			defaultHeight: 497,				// Default height of the box (in pixels) for undefined media (MP4, FLV, etc.)
			showCaption: true,				// Display the title and caption, true / false
			showCounter: true,				// If true, a counter will only be shown if there is more than 1 image to display
			counterText: '({x} of {y})',	// Translate or change as you wish
//			Image options
			imgBackground: false,			// Embed images as CSS background (true) or <img> tag (false)
											// ...a CSS background is naturally non-clickable, preventing downloads
											// ...the IMG tag allows automatic scaling for smaller screens, minimal no-click code is included but does not work in Opera
			imgPadding: 70,					// Clearance necessary for images larger than the window size (only used when imgBackground is false)
											// Change this number only if the CSS style is significantly divergent from the original, and requires different sizes
//			Inline options
//				overflow: 'auto',				// Sets CSS overflow of the overflow to allow for
//			Global media options
			scriptaccess: 'true',		// Allow script access to flash files
			fullscreen: 'true',			// Use fullscreen
			fullscreenNum: '1',			// 1 = true
			autoplay: 'true',			// Plays the video as soon as it's opened
			autoplayNum: '1',			// 1 = true
			autoplayYes: 'yes',			// yes = true
			volume: '100',				// 0-100, used for NonverBlaster and Quicktime players
			medialoop: 'true',			// Loop video playback, true / false, used for NonverBlaster and Quicktime players
			bgcolor: '#000000',			// Background color, used for flash and QT media
			wmode: 'opaque',			// Background setting for Adobe Flash ('opaque' and 'transparent' are most common)
//			NonverBlaster
			useNB: true,				// use NonverBlaster (true) or JW Media Player (false) for .flv and .mp4 files
			playerpath: '/scripts/NonverBlaster.swf',	// Path to NonverBlaster.swf
			controlColor: '0xFFFFFF',	// set the controlbar color
			controlBackColor: '0x000000',	// set the controlbar color
			showTimecode: 'false',		// turn timecode display off or on
//			JW Media Player settings and options
			JWplayerpath: '/js/player.swf',	// Path to the mediaplayer.swf or flvplayer.swf file
			backcolor:	'000000',		// Base color for the controller, color name / hex value (0x000000)
			frontcolor: '999999',		// Text and button color for the controller, color name / hex value (0x000000)
			lightcolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
			screencolor: '000000',		// Rollover color for the controller, color name / hex value (0x000000)
			controlbar: 'over',			// bottom, over, none (this setting is ignored when playing audio files)
//			Quicktime options
			controller: 'true',			// Show controller, true / false
//			Flickr options
			flInfo: 'true',				// Show title and info at video start
//			Revver options
			revverID: '187866',			// Revver affiliate ID, required for ad revinue sharing
			revverFullscreen: 'true',	// Fullscreen option
			revverBack: '000000',		// Background color
			revverFront: 'ffffff',		// Foreground color
			revverGrad: '000000',		// Gradation color
//			Ustream options
			usViewers: 'true',				// Show online viewer count (true/false)
//			Youtube options
			ytBorder: '0',				// Outline				(1=true, 0=false)
			ytColor1: '000000',			// Outline color
			ytColor2: '333333',			// Base interface color (highlight colors stay consistent)
			ytQuality: '&ap=%2526fmt%3D18', // Leave empty for standard quality, use '&ap=%2526fmt%3D18' for high quality, and '&ap=%2526fmt%3D22' for HD (note that not all videos are availible in high quality, and very few in HD)
			ytRel: '0',					// Show related videos	(1=true, 0=false)
			ytInfo: '1',				// Show video info		(1=true, 0=false)
			ytSearch: '0',				// Show search field	(1=true, 0=false)
//			Viddyou options
			vuPlayer: 'basic',			// Use 'full' or 'basic' players
//			Vimeo options
			vmTitle: '1',				// Show video title
			vmByline: '1',				// Show byline
			vmPortrait: '1',			// Show author portrait
			vmColor: 'ffffff'			// Custom controller colors, hex value minus the # sign, defult is 5ca0b5
		}
		
		mediaWidth = options.defaultWidth;
		mediaHeight = options.defaultHeight;

		var imgSrc = canvas_i[i].getElement('img').get('src');
		imgSrc = imgSrc.substr(imgSrc.indexOf("/"), imgSrc.indexOf("&")-(imgSrc.indexOf("/")));
		
		var URL = canvas_i[i].getElement('img').get('alt') || null;
		
		var imgDsc = canvas_i[i].getElement('.rel-desc').get('html');
		var imgTtl = encodeURIComponent(canvas_i[i].getElement('.rel-title').get('html'));
/*		var imgpdf = encodeURIComponent(canvas_i[i].get('pdf'));*/
		var share = encodeURIComponent(canvas_i[i].get('share'));
		
		if ( document.id("media") != null ) {
			var imgDsc = canvas_i[i].getElement('.rel-media').get('html');
			
//			alert(imgDsc.getElement('x-list-2').get('html'));
		}

		var container = new Element('div', {
			'id': 'canvas_content'
		}).inject(document.body, "bottom");
				
//		if ( imgDsc != "" ) {
			var canvas_desc = new Element('div', {
				'id': 'canvas_desc',
				'html': imgDsc
			}).inject(container, "bottom");
//		}
		
		if ( document.id("media") != null ) {

			var ylist = canvas_i[i].getElements('.x-list-2 li');
			
			
			for(var y in ylist) {
				if ( ylist[y].nodeType == 1 ) {
				ylist[y].clone().cloneEvents(ylist[y]).inject(document.id('canvas_desc').getElement('.x-list-2'),'bottom');
				}
			}
		
//			var media_list = document.id('canvas_desc').getElement('.x-list-2 img');
			
//			document.id('canvas_desc').getElement('.x-list-2 img').each(function(j,u) {
//				alert('test');
//			});


		}
		
		var canvas_img = new Element('div', {
			'id': 'canvas_img'
		}).inject(container, "bottom"); 
		
		var canvas_nav = new Element('div', {
				'id': 'canvas_nav',
				'html': '<ul></ul>'
			}).inject(canvas_img, "top");
		
		var prev_btn = new Element('li', {
			'html': '<div>Previous</div>',
			'styles': {
				'cursor': 'pointer'
			},
			'events': {
				'click': function(){
					overlay.close();
					canvas_object(canvas_i,i-1);
					overlay.open();
				}
			},
			'id': 'prev_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
		
		var sep_btn = new Element('li', {
			'html': '<div>|</div>',
			'id': 'sep_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
				
		var next_btn = new Element('li', {
			'html': '<div>Next</div>',
			'styles': {
				'cursor': 'pointer'
			},
			'events': {
				'click': function(){
					overlay.close();
					canvas_object(canvas_i,i+1);
					overlay.open();
				}
			},
			'id': 'next_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
		
		var email_btn = new Element('li', {
			'html': '<span class="social email"></span> <a href="mailto:?subject=FW:%20'+imgTtl+'&body='+ share +'">Email</a>',
			'styles': {
				'cursor': 'pointer'
			},
			'id': 'email_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
		
		var facebook_btn = new Element('li', {
			'html': '<span class="social facebook"></span> Facebook',
			'styles': {
				'cursor': 'pointer'
			},
			'events': {
				'click': function() {
					popupform('http://www.facebook.com/share.php?u='+ share);
				}
			},
			'id': 'facebook_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
		
		var twitter_btn = new Element('li', {
			'html': '<span class="social twitter"></span> Twitter',
			'styles': {
				'cursor': 'pointer'
			},
			'events': {
				'click': function() {
					popupform('http://twitter.com/share?text='+imgTtl+'%20|%20'+window.location.hostname+'&url='+share);
				}
			},
			'id': 'twitter_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 
		
		var close_btn = new Element('li', {
			'text': 'Close',
			'styles': {
				'cursor': 'pointer'
			},
			'events': {
				'click': function(){
					overlay.close();
				}
			},
			'id': 'close_btn'
		}).inject(canvas_nav.getElement('ul'), "bottom"); 


		if ( URL.match(/youtube\.com\/watch/i) ) {
			
			mediaType = 'obj';
			mediaSplit = URL.split('v=');
			mediaId = mediaSplit[1];
			
			if (mediaId.match(/fmt=18/i)) {
				mediaFmt = '&ap=%2526fmt%3D18';
				mediaWidth = mediaWidth || "560px";
				mediaHeight = mediaHeight || "345px";
			} else if (mediaId.match(/fmt=22/i)) {
				mediaFmt = '&ap=%2526fmt%3D22';
				mediaWidth = mediaWidth || "640px";
				mediaHeight = mediaHeight || "385px";
			} else {
				mediaFmt = options.ytQuality;
				mediaWidth = mediaWidth || "480px";
				mediaHeight = mediaHeight || "295px";
			}
			preload = new Swiff('http://www.youtube.com/v/'+mediaId+'&autoplay='+options.autoplayNum+'&fs='+options.fullscreenNum+mediaFmt+'&border='+options.ytBorder+'&color1=0x'+options.ytColor1+'&color2=0x'+options.ytColor2+'&rel='+options.ytRel+'&showinfo='+options.ytInfo+'&showsearch='+options.ytSearch, {
				id: mediaId,
				width: mediaWidth,
				height: mediaHeight,
				params: {wmode: options.wmode, bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
				});
		} else if (URL.match(/youtube\.com\/view/i)) {
			mediaType = 'obj';
			mediaSplit = URL.split('p=');
			mediaId = mediaSplit[1];
			mediaWidth = mediaWidth || "480px";
			mediaHeight = mediaHeight || "385px";
			preload = new Swiff('http://www.youtube.com/p/'+mediaId+'&autoplay='+options.autoplayNum+'&fs='+options.fullscreenNum+mediaFmt+'&border='+options.ytBorder+'&color1=0x'+options.ytColor1+'&color2=0x'+options.ytColor2+'&rel='+options.ytRel+'&showinfo='+options.ytInfo+'&showsearch='+options.ytSearch, {
				id: mediaId,
				width: mediaWidth,
				height: mediaHeight,
				params: {wmode: options.wmode, bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
				});
		} else if (URL.match(/vimeo\.com/i)) {
			mediaType = 'obj';
			mediaWidth = mediaWidth || "640px";		// site defualt: 400px
			mediaHeight = mediaHeight || "360px";	// site defualt: 225px
			mediaSplit = URL.split('/');
			mediaId = mediaSplit[3];
			preload = new Swiff('http://www.vimeo.com/moogaloop.swf?clip_id='+mediaId+'&amp;server=www.vimeo.com&amp;fullscreen='+options.fullscreenNum+'&amp;autoplay='+options.autoplayNum+'&amp;show_title='+options.vmTitle+'&amp;show_byline='+options.vmByline+'&amp;show_portrait='+options.vmPortrait+'&amp;color='+options.vmColor, {
				id: mediaId,
				width: mediaWidth,
				height: mediaHeight,
				params: {wmode: options.wmode, bgcolor: options.bgcolor, allowscriptaccess: options.scriptaccess, allowfullscreen: options.fullscreen}
				});
		} else {
			preload = new Element('img', { 'id': 'main_image', 'src': imgSrc + ( ( imgDsc != "" ) ? '&width=777' : '') });
		}
		
		preload.inject(canvas_img, "bottom");
				
	};
	
	canvas_i.each(function(li,i) {
		
		if ( li.get("href") == "#top" ) {						   
		
			li.addEvent('click', function() {
				canvas_object(canvas_i,i);
				overlay.open();
				return false;
			});	
		}
		
	});
	
	media_list.each(function(j,u) {
		j.addEvent('click', function() {
									 
			var imgSrc = j.getElement('img').get('src');
			imgSrc = imgSrc.substr(imgSrc.indexOf("/"), imgSrc.indexOf("&")-(imgSrc.indexOf("/")));
			
			document.id('main_image').set('src', imgSrc +'&width=777' );
		});
	});
	
	var lnk = window.location.pathname;
	if( lnk.contains('/i/') ) {
		lnk = lnk.substring(lnk.indexOf('/i/')+3);		
		if ( lnk.contains('/') ) lnk = lnk.substring(0,lnk.indexOf('/'));
		canvas_object(canvas_i,document.id('hash_'+lnk).get('rel'));
		overlay.open();
	}
	
	function getUrlVars()
	{
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
	
		return vars;
	}
	
/*	var lnk = window.location.href;
	if( lnk.contains('/#!/') ) {
		lnk = lnk.substring(lnk.indexOf('/#!/')+4);		
		if ( lnk.contains('/') ) lnk = lnk.substring(0,lnk.indexOf('/'));
		
		$$('.x-event').each(function(li) {
									 
			if ( !li.hasClass('hash_'+lnk) ) {
				li.getParent().setStyle('display', 'none');
			}
									 
//			alert(li.get('rel-data').indexOf(' '));
									 
//			if ( li.get('reldata').indexOf(' ') == -1) {
				
//				alert(li.get('rel-data'));
				
//				$$('.x-event[reldata="'+li.get('reldata')+'"]').getParent().setStyle('display', 'none');
				
//			} else {
				
//				alert(li.get('rel-data'));
				
//				hashes = li.get('rel-data').split('m ');
//			}
			
		});
			
									 
/*			li.addEvent('click', function() {
										  alert(this.get('rel-data'));
				  });
			 });*/
		
/*		if ( lnk.contains('/') ) lnk = lnk.substring(0,lnk.indexOf('/'));
		canvas_object(canvas_i,document.id('hash_'+lnk).get('rel'));
		overlay.open();
	}
		*/
});

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;
}
