
var glitter, gold = 1.618;
function alive( v ) {return v.length > 0;}

/*

- linking .be to .com

- new front, rotation, no pagination - top featured row
- per category ( ? )

*/



(function($)
{
	var
		wrap = $( '#wrap' ), home = $( '.home' ), touch = $( '#touch' ),
		badorientation = $( '#bad-orientation' ), badsize = $( '#bad-size' ), about = $( '#about' ),
		cycleTime, initphase = true, overlay = [];

	if( !alive( home ) ) home = false;
	$( '#pagenumber .total' ).html( $( '.slide' ).length );
	$( '#aboutblock' ).click( function() { setOverlay( 'about', true ); });
	$( '#closeabout' ).click( function() { setOverlay( 'about', false ); });
	
	
	
	// !SetOverlay
	function setOverlay( t, b )
	{
		if( b )
		{
			var check = false;
			for( var i = 0; i < overlay.length; i++ )
			{
				if( overlay[ i ] == t ) check = true;
			}
			
			if( !check )
			{
				var i = overlay.push( t );
				showOverlay();
			}
		}
		
		else
		{
			for( var i = 0; i < overlay.length; i++ )
			{
				if( overlay[ i ] == t ) overlay.splice( i, 1 );
			}
			
			( overlay.length > 0 ) ? showOverlay() : hideOverlay();
		}	
	}
	
	function showOverlay()
	{
		var t;
		
		switch( overlay[ 0 ] )
		{
			case 'orient' 	: t = badorientation; break;
			case 'size'		: t = badsize; break;
			case 'about'	: t = about; break;		
		}
		
		badorientation.fadeOut( 300 );
		badsize.fadeOut( 300 );
		about.fadeOut( 300 );
		
		wrap.fadeOut( 300 );
		
		t.delay( 500 ).fadeIn( 500 );
	}
	
	function hideOverlay()
	{
			badorientation.fadeOut( 300 );
			badsize.fadeOut( 300 );
			about.fadeOut( 300 );
			
			wrap.delay( 500 ).fadeIn( 500 );
	}
	
	

	// !Orientation
	function orientation()
	{
		var o = Math.abs( window.orientation );

		if( !isNaN( o ) )
		{
			var l = ( o == 90 ) ? false : true;
			setOverlay( 'orient', l );
		}
	}

	window.onorientationchange = orientation;
	orientation();



	// !Home & suggestion init
	if( home )
	{
		var leg = 220;

		var
			wi = Math.floor( $( window ).width() / leg ),
			hi = Math.floor( ( $( window ).height() - 113 ) / leg );

		if( wi > 0 && hi > 0 )
		{
			var
				tc = $( '.tile-container' ),
				l = wi * hi,
				s = 1;

			var p = Math.ceil( tc.length / l );
			$( '#pagenumber .total' ).html( p );

			//	Add the missing slides
			var i = 0;
			while( i < p )
			{
				if( ++i > 1) $( '#touch' ).append( '<div id="slide-' + i + '" class="slide"><div class="page"></div></div>' );
			}

			$( '.tile-container' ).each(function( i, v )
			{
				i += 1;
				i = i - ( l * ( s - 1 ) );

				if( s > 1 )
				{
					v = $( v );
					v.appendTo( $( '#slide-' + s + ' .page' ) );
				}

				if( i == l ) s++;
			});

			if( l > tc.length ) hi = Math.ceil( tc.length / wi );
			csswi = ( wi > tc.length ) ? tc.length : wi;

			// Set the size
			$( '.page' ).css(
			{
				'width'  : csswi * leg,
				'margin-top' : ( ( $( window ).height() - 113 ) - ( hi * leg ) ) / 2

			});
		}
	}

	var sslide = $( '.suggestion-slide' );
	if( alive( sslide ) )
	{


		var leg = 220;

		var
			wi = Math.floor( $( window ).width() / leg ),
			hi = Math.floor( ( $( window ).height() - 113 - 105 ) / leg ); // 105 = if you liked this text

		if( wi > 0 && hi > 0 )
		{
						var
				tc = sslide.children( '.page' ).children( '.tile-container' ),
				l = wi * hi,
				s = 1;

			if( l > tc.length ) hi = Math.ceil( tc.length / wi );
			csswi = ( wi > tc.length ) ? tc.length : wi;

			// Set the size
			sslide.children( '.page' ).css(
			{
				'width'  : csswi * leg,
				'margin-top' : ( ( $( window ).height() - 113 - 105 ) - ( hi * leg ) ) / 2 // again, -105

			});
		}
	}



	// !Resizing
	function resizeListener( w, h )
	{
		

		if( $( window ).width() < 700 || $( window ).height() < 500 )
		{
			setOverlay( 'size', true );
		}
		
		else
		{
			setOverlay( 'size', false );
			
			//	Interface
			touch.css({ 'height':  h - 108 });

			//	Home
			if( home ) { if( !initphase ) document.location = 'http://thelistmag.com/'; }

			//	Resizing pages
			else
			{
				$( '.show, .prev, .next' ).children( '.page' ).each(function( i, v )
				{
					var page = $( v );

					//	I do declare
					var body 	= page  .children( '.body' );
					var canvas 	= body  .children( '.canvas' );
					var slides 	= canvas.children( '.canvas-slide' );

					//	If there are any slides at all
					if( slides.length > 0 )
					{
						var
							th = page.children( '.title' ).height(),
							mw = parseFloat( canvas.children( '.canvas-width' ) .text() ),
							mh = parseFloat( canvas.children( '.canvas-height' ).text() );

						var
							w = $( window ).width()  - 345,
							h = $( window ).height() - ( 158 + th );

						w = ( mw < w ) ? mw : w;
						h = ( mh < h ) ? mh : h;

						//	adapt
						if( ( ( w / mw ) * mh ) > h ) w = ( h / mh ) * mw;
						if( ( ( h / mh ) * mw ) > w ) h = ( w / mw ) * mh;
						//	@end adapt

						if( w != canvas.width() || h != canvas.height() )
						{
							var newSize = { 'width'	 : w, 'height' : h };

							canvas.css( newSize );
							slides.css( newSize );

							page.width( w + 345 );

							body.children( '.subtext' ).css(
							{
								'width' : w,
								'top' : h + 4
							});

							setSize( slides, w, h );
							
							slides.each( function( i, v ) 
							{
								v = $( v );
								
								v.children( '.bigwordshellyeah' ).css
								( 
									'top', 
									( parseFloat( v.height() ) - 45 ) / 2 
								);			
							});
						}
					}
				});
			}

			//	after init
			if( initphase )
			{
				touch.delay( 500 ).fadeIn( 1000 );
				initphase = false;
			}
		}
		
		//	Overlays
		$( '.jscenter' ).each( function( i, v )
		{
			v = $( v );
			var i = ( $( window ).height() - v.height() - 30 ) / 2;
			
			v.css( 'margin-top', i );
		});
	}

	//	make a plugin will you
	function setSize( q, w, h )
	{
		q.each(function( i, v )
		{
			var
				t = $( v ).children('img'),

				sw = t.attr( 'width' ),
				sh = t.attr( 'height' ),

				r = w/sw*sh>h?true:false,

				tw = Math.ceil( r?w:h/sh*sw ),
				th = Math.ceil( r?w/sw*sh:h ),

				tx = setPosition( 'x', r, w, tw ),
				ty = setPosition( 'y', r, h, th );

			t.css({ width: tw, height: th, left: tx, top: ty });
		});
	}

	function setPosition( t, r, fs, ts )
	{
		if(
			( ( t == 'x' ) && r ) ||
			( ( t == 'y' ) && !r )
		)
		{t = 0;}

		else
		{
			switch( 'center' )
			{
				case 'top'  : 		t = 0;			break;
				case 'left' : 		t = 0;			break;

				case 'bottom' : 	t = fs - ts;	break;
				case 'right'  : 	t = fs - ts;	break;

				default :			t = ( fs - ts ) / 2;
			}
		}

		return t;
	}

	var facesize = 0, facetimes = 0;

	function fontfaceCheck()
	{
		var size = $( '.slide:first' ).children( '.page' ).children( '.title' ).height();

		if( ( size > 0 ) && ( size == facesize ) ) facetimes++;
		facesize = size;

		( facetimes == 3 ) ? resizeListener() : setTimeout( fontfaceCheck, 100 );
	}
	fontfaceCheck();



	// !Cycling the canvas
	function cycleSlides( w, h )
	{
		var
			newCycle = ( w ) ? true : false,
			init = ( !cycleTime ) ? true : false,

			c = 'canvas-show',
			p = $('.show').children( '.page' ).children( '.body' ).children( '.canvas' ),
			l = p.children( '.canvas-slide' ),
			t = p.parent().children( '.subtext' ),
			s, n;

		if( !newCycle )
		{
			s = p.children( '.' + c ).removeClass( c ).css( 'z-index', '0' );
			n = getNext( s ).addClass( c ).css( 'z-index', '-1' );

			n.show();
			s.fadeOut( 2000 );

			t.fadeOut( 1000, function()
			{
				t.html( n.children( '.slide-title' ).html() );
				t.fadeIn( 1000 )
			});
		}

		else
		{
			//	Page numbering
			$( '#pagenumber .current' ).text( $( '.show' ).attr('id').substr( 6 ) );
		}

		if( alive( $( '#player' ) ) ) removeVideo( $( '#player' ).parent().parent().parent().parent().parent() );

		clearTimeout( cycleTime );
		cycleTime = ( l.length > 1 ) ? setTimeout( cycleSlides, 4000 ) : null;
	}

	function getNext( div )
	{
		var t = div.next();
		if( t.hasClass( 'canvas-width' ) ) t = div.parent().children().first();
		return t;
	}

	// !Clicking the canvas
	$( '.canvas' ).click(function()
	{

		var
			n = $( this ).children( '.canvas-show' ),
			c = n.children( '.link-context' ),
			l = n.children( '.slide-link' );

		if( alive( c ) )
		{
			c = c.text();
			l = l.text();

			switch( c )
			{
				case 'youtube' 	: insertYoutube( n, l ); 	break;
				case 'vimeo' 	: insertVimeo  ( n, l ); 	break;
				case 'home' 	: window.location = l;		break;
				case 'external' : window.open( l );			break;
			}

			return false;
		}
	});

	function insertYoutube( n, l )
	{
		insertVideo( n, 'http://www.youtube.com/embed/' + l + '?autohide=1&autoplay=1&fs=1&hd=1&modestbranding=1&rel=0&showinfo=0&showsearch=0' );
	}

	function insertVimeo( n, l )
	{
		insertVideo( n, 'http://player.vimeo.com/video/' + l + '?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1' );
	}

	function insertVideo( r, e )
	{
		clearTimeout( cycleTime );
		var w = r.width(), h = r.height();

		var p = '<div id="player" class="hide"><iframe id="youtube" src="' + e + '" width="' + w + '" height="' + h + '" frameborder="0"></iframe></div>';
			r.append( p );
			r.append( '<div id="close" class="hide">click to close</div>' );

			$( '#close' )
				.delay( 2000 ).fadeIn( 300 )
				.click( removeVideo );

			p = $( '#player' );

		r.children( '.bigwordshellyeah' ).fadeOut( 300, function() { p.fadeIn( 1000 ); });
	}

	function removeVideo( r )
	{
		if( !r.originalEvent )
		{
			$( '#player' ).remove();
			$( '#close' ) .remove();
			r.children( '.page' ).children( '.body' ).children( '.canvas' ).children( '.canvas-show' ).children( '.bigwordshellyeah' ).show();
		}

		else
		{
			$( '#close' ).fadeOut( 300 );

			$( '#player' ).fadeOut( 300, function()
			{
				$( '#player' ).remove();
				$( '#close' ) .remove();

				$( '.show .page .body .canvas .canvas-show .bigwordshellyeah' ).fadeIn( 300 );
			});
		}
	}



	// !Cycling the front
	var cycleTilesFun, cTilePage = home, cTileQuery, cl = 'busytile', cycleTilesCycle = 0;

	function cycleTiles( w, h )
	{

		cTilePage = $('.show');
		cTileQuery = cTilePage.children( '.page' ).children( '.tile-container' ).not( '.draft' ).not( '.overstate' );

		if( alive( cTileQuery ) )
		{
			var b = ( alive( cTileQuery.parent().children( '.' + cl ) ) ) ? cTileQuery.parent().children( '.' + cl ).removeClass( cl ) : cTileQuery.first();
			var n = getNextTile( b ).addClass( cl );


			//	img-frame

			var c = $( n ).children( '.count' );
			var i = parseFloat( c.children( '.totitle' ).text() );

			if( !n.hasClass( 'overstate') )
			{
				if( i != 0 )
				{
					swapThumb( n );
					c.children( '.totitle' ).text( --i );
				}

				else
				{
					var j = parseFloat( c.children( '.totile' ).text() );
					var tf = n.children( 'a' ).children( '.tile' ).children( '.title-frame' );

					if( j != 0 )
					{
						if( j == 2 ) tf.fadeIn( 300 );
						c.children( '.totile' ).text( --j );
					}

					else
					{
						c.children( '.totitle' ).text( '2' );
						c.children( '.totile' ).text( '2' );

						tf.fadeOut( 200 );

					}
				}
			}
		}

		clearTimeout( cycleTilesFun )
		cycleTilesFun = setTimeout( cycleTiles, 600 );
	}

	$( '.tile-container' ).hover(
	function()
	{
		$( this ).addClass( 'overstate' );
		$( this ).children( 'a' ).children( '.tile' ).children( '.title-frame' ).fadeIn( 400 );

	},

	function()
	{
		$( this ).removeClass( 'overstate' );
		$( this ).children( 'a' ).children( '.tile' ).children( '.title-frame' ).fadeOut( 300 );

	});

	//	$( '.title-frame' ).show();

	var tmbstr = 'tile-show';
	function swapThumb( t )
	{
		t = t.children( 'a' ).children( '.tile' ).children( '.img-frame' );

		var c = t.children( '.' + tmbstr ).removeClass( tmbstr ).css( 'z-index', '-1' );
		var n = getNextTile( c ).addClass( tmbstr ).hide().css( 'z-index', '0' );

		n.fadeIn( 300, function() { c.hide(); } );
	}

	function getNextTile( div )
	{
		var t = div.next();
		while( t.hasClass( 'draft' ) ) t = t.next();
		if( !alive( t ) ) t = div.parent().children().first();

		return t;
	}


	
	// !MouseWheel
	wrap.mousewheel(function( e, d )
	{
		e.preventDefault();
		vel = Math.abs( d );
	
		d = ( d > 0 ) ? 'next' : 'prev';
		touch.flickDragClick( d );
	});


	// !Init flickDragClick
	touch.flickDragClick( 'addListener', 'init', 	resizeListener );
	touch.flickDragClick( 'addListener', 'resize', 	resizeListener );
	if( !home ) touch.flickDragClick( 'addListener', 'newView',	resizeListener );

	if( !home )
	{
		touch.flickDragClick( 'addListener', 'init', 	cycleSlides );
		touch.flickDragClick( 'addListener', 'newView',	cycleSlides );
	}

	touch.flickDragClick( 'addListener', 'init', 	cycleTiles );
	touch.flickDragClick( 'addListener', 'newView',	cycleTiles );
	
	touch.flickDragClick({ swipeDistance : .2 });

	$( '#rightarrow' ).click(function() { touch.flickDragClick( 'next' ) });
    $( '#leftarrow' ) .click(function() { touch.flickDragClick( 'prev' ) });

	// !Prevent anchor slides
	$( 'a' ).click(function()
	{
		document.location = $( this ).attr( 'href' );
		return false;
	});

	// !youmightlike
	$( '#youmightlike' ).click( function()
	{
		var t = $( '.suggestion-slide' );

		if( alive( t ) )
		{
			t = t.attr( 'id' ).substr( 6 );
			touch.flickDragClick( 'goto', parseFloat ( t ) );
		}
	});

	$( '#twitter' ).click( function()
	{
		window.open( 'http://twitter.com/share' );

	});

	$( '#facebook' ).click( function()
	{
		window.open( 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent( document.location.href ) );
	});




})(jQuery);

