/*////////////////////////////////////////////////////////////

- tokyoblue.js

 -- Author: Kenji Morisaki
 -- Url: http://decremented.net
 
 *Require jQuery
	
////////////////////////////////////////////////////////////*/

/*############################################################

[common]

############################################################*/

window.onunload=function(){};


/*--------------------------------------------------

Avoid errors in the browser without the console

--------------------------------------------------*/
if ( typeof window.console != 'object' )
{
	window.console = {log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},assert:function(){},dir:function(){},dirxml:function(){},trace:function(){},group:function(){},groupEnd:function(){},time:function(){},timeEnd:function(){},profile:function(){},profileEnd:function(){},count:function(){}};
}


/*--------------------------------------------------

set cover css

--------------------------------------------------*/
$( 'head' ).append('<style type="text/css">#cover { display: block; height: ' + window.innerHeight + 'px; }</style>');

/*--------------------------------------------------

check browser

--------------------------------------------------*/
// check browser
var isIE = $.browser.msie && !$.support.opacity;
var isIE6 = isIE && $.browser.version < 7;

// check smart phone
var ua = navigator.userAgent;
var isAndroid = ua.indexOf('Linux; U; Android ') != -1;
var isIpod = ua.indexOf('iPod; U') != -1;
var isIphone = ua.indexOf('iPhone; U') != -1;
var isIpad = ua.indexOf('iPad; U') != -1;


/*############################################################

[tokyoblue]

############################################################*/

/*--------------------------------------------------

on load

--------------------------------------------------*/
$( function()
{
	// tokyoblue
	$( '#container' ).tokyoblue();
});



/*--------------------------------------------------

tokyoblue

--------------------------------------------------*/
( function( $ )
{
	
	$.tokyoblue = function( element, options )
	{
		/* property
		==============================*/
		var w = 0;
		var h = 0;
		var minW = parseInt( $( '#container' ).css( 'min-width' ) );
		var minH = parseInt( $( '#container' ).css( 'min-height' ) );
		var right = 0;
		var ypt = 0;
		
		var topTitle = $( '#top > .title' );
		var topIntro = $( '#top > .intro' );
		var side = $( '#side', element );
		var sideWidth = side.outerWidth();
		var main = $( '#main', element );
		var mapCont = $( '#map_s', element );
		var pagetop = $( '.pagetop', side );
		var contents = $( '.content', main );
		var photoContents = $( '.photo', main );
		var navi = $( 'ul > li:has( a )', side );
		var btn = $( '.btn > dd:has( a )', side );
		var listNavi = $( '#list li', main );
		
		var imgSizeList = [];
		var currentNavi;
		
		var cnt = 0;
		var current = 0;
		var intervalID = 0;
		var enterframeID = 0;
		var delay = ( 1000 / options.fps ) | 0;
		
		var mapCanvas;
		var markerList = [
			　{ lat: 35.64972, lng: 139.691666, zoom: 14 },
			　{ lat: 35.664741, lng: 139.722305, zoom: 14 },
			　{ lat: 35.669593, lng: 139.702878, zoom: 15 },
			　{ lat: 35.674034, lng: 139.744429, zoom: 15 },
			　{ lat: 35.675531, lng: 139.719164, zoom: 16 },
			　{ lat: 35.659665, lng: 139.700432, zoom: 16 },
			　{ lat: 35.659665, lng: 139.700432, zoom: 16 }
		];
		var defaultZoom = 12;
		
		var isMapVisible = false;
		var isPageTopVisible = false;
		
		
		
		
		/* extends
		==============================*/
		$.fn.extend({
			clickable: function()
			{
				// default cancel
				$( 'a', this )
					.focus( function(){ this.blur(); } )
					.click( function( e ){ e.preventDefault(); } );
				
				$( this )
					.css({
						cursor	: 'pointer'
					})
					.hover(
						function( e ){ $( this ).addClass( 'over' ); },
						function( e ){ $( this ).removeClass( 'over' ); }
					);
					
				return $( this );
			},
			
			unclickable: function()
			{
				if ( $( this ).is( '.over' ) ) $( this ).removeClass( 'over' ); 
				
				$( this )
					.css( 'cursor', 'default' )
					.hover( null );
					
				return $( this );
			},
			
			switchBtImg: function( area, suffix )
			{
				suffix = suffix || '_on';
				return this.not( '[ src *= "' + suffix + '." ]' ).each( function()
				{
					var img = $( this );
					var target = ( !img.attr( 'vml' ) ) ? img : $( img.attr( 'vml' ).image.fill );
					var src = img.attr( 'src' );
					var _on = [
						src.substr( 0, src.lastIndexOf( '.' ) ),
						src.substring( src.lastIndexOf( '.' ) )
					].join( suffix );
					
					$( '<img>' ).attr( 'src', _on );
					
					area.hover(
						function(){ target.attr( 'src', _on ); },
						function(){ target.attr( 'src', src ); }
					);
				});
			},
			
			clickLink: function()
			{
				var url = $( this ).attr( 'href' );
				var target = $( this ).attr( 'target' );
				
				if ( target == "_top" ) top.location.href = url;
				else if( target == "_blank" || target == "blank" ) window.open( url, "" );
				else if ( target != "" ) eval( "parent.location.href = url" );
				else location.href = url;
				
				return $( this );
			},
			
			
			
			onLargeMapClick: function( value )
			{
				$( navi[ value ] ).trigger( 'click' );
			}
		})
		
		
		/* method
		==============================*/
		/* init */
		function init()
		{
			photoContents.each( function()
			{
				var img = $( 'img', this );
				imgSizeList.push( { width: img.attr( 'width' ), height: img.attr( 'height' ) } );
			});
			
			// navigation
			$( '.en_title', side )
				.clickable()
				.bind( 'click', onNaviClick );
			
			navi.each( function()
			{
				$( this )
					.clickable()
					.bind( 'click', onNaviClick );
			});
			
			btn.each( function()
			{
				$( this )
					.clickable()
					.bind( 'click', onBtnClick );
			});
			
			listNavi.each( function()
			{
				$( this )
					.clickable()
					.bind( 'click', onNaviClick )
					.bind( 'click', onListClick );
			});
			
			
			// page top
			pagetop
				.clickable()
				.bind( 'click', onNaviClick )
				.find( 'img' )
					.switchBtImg( pagetop );
			
			
			// hide top title
			topTitle.css( 'opacity', 0 );
			
			
			// init gppgle maps api
			initMap();
			
						
			// ipod / iphone / ipad
			if ( isIpod || isIphone || isIpad )
			{
				element.css({
					height		: $( window ).height(),
					overflow	: 'hidden'
				});
				main.css( 'position', 'absolute' );
				side.css( 'position', 'absolute' );
			}
			else
			{
				$( window ).bind( 'scroll', onScroll );
				if ( window.attachEvent )
				{
					/** IE/Opera. */
					window.onmousewheel = document.onmousewheel = onMouseWheel;
				}
				else $( window ).bind( 'mousewheel', onMouseWheel );
			}
			

			// add event listener
			$( window ).one( 'load', show );
			$( window ).bind( 'resize orientationchange', onResize );
			
			// resize
			onResize();
		}
		
		
		/* initialize google maps api */
		function initMap()
		{
			var latlng = new google.maps.LatLng( 35.649725, 139.691658 );
			var options = {
				zoom										: defaultZoom,
				center									: latlng,
				mapTypeId								: google.maps.MapTypeId.ROADMAP,
				disableDefaultUI				: true,
				disableDoubleClickZoom	:	false,
				draggable								: false,
				scrollwheel							: false,
				mapTypeControl					: false,
				navigationControl				: false,
				scaleControl						: false
			};
			
			mapCanvas = new google.maps.Map( $( '#map_s > #map_s_canvas' )[0], options );
			
			
			// markers
			var markerOptions;
			var marker;
			
			// icon
			var iconImg = './images/maps_icon_web.png';
			var iconSize = new google.maps.Size( 32, 32 );
			var iconOrigin = new google.maps.Point( 0, 0 );
			var iconAnchor = new google.maps.Point( 16, 32 );
			var icon = new google.maps.MarkerImage( iconImg, iconSize, iconOrigin, iconAnchor );
			
			var shadowImg = './images/maps_icon_shadow.png';
			var shadowSize = new google.maps.Size( 29, 22 );
			var shadowOrigin = new google.maps.Point( 0, 0 );
			var shadowAnchor = new google.maps.Point( 5, 22 );
			var shadow = new google.maps.MarkerImage( shadowImg, shadowSize, shadowOrigin, shadowAnchor );
			
			for ( var i = 0; i < markerList.length; i++ )
			{
				markerOptions = {
					position	: new google.maps.LatLng( markerList[i].lat, markerList[i].lng ),
					map				: mapCanvas,
					icon			: icon,
					shadow		: shadow
				}
				
				marker = new google.maps.Marker( markerOptions );
			}
		}
		
		
		
		/* show
		------------------------------*/
		function show()
		{
			setTimeout( function()
			{
				$( '#cover' ).animate( { opacity: 0 }, 1000, 'easeInOutQuad', function()
				{
					// hide cover
					$( '#cover' ).css( 'display', 'none' );
					
					// intro
					intro();
				});
			}, 200 );
		}
		
		
		
		/* intro
		------------------------------*/
		function intro()
		{
			if ( $( window ).scrollTop() < h )
			{
				// show intro
				topIntro.animate( { opacity: 1 }, 1200, 'easeOutQuad', function()
				{
					setTimeout( function()
					{
						topIntro.animate( { opacity: 0 }, 1200, 'easeOutQuad', function()
						{
							topIntro.css( 'display', 'none' );
							setTimeout( function()
							{
								topTitle.animate( { opacity: 1 }, 1600, 'easeInQuad', function()
								{
									if ( $( window ).scrollTop() == 0 ) setTimeout( function(){ $( navi[0] ).trigger( 'click' ); }, 3000 );
								});
							}, 1000 )
						});
					}, 1400 )
				});
			}
			else
			{
				topIntro.css( 'display', 'none' );
				topTitle.css( 'opacity', 1 );
			}
		}
		
		
		/* resize
		------------------------------*/
		function onResize( e )
		{
			// width / height
			w = Math.max( minW, /*Math.max( $( '#container' ).width(), */$( window ).width()/* )*/ );
			h = Math.max( minH, $( window ).height() );
			
			
			// cover
			$( '#cover' ).height( $( document ).height() );
			
			// container
			if ( isIE6 ) element.width( w ).height( h );
			
			// position before resize
			var scrollPos = $( window ).scrollTop() / $( document ).height();
			
			
			// side
			if ( !isIE6 && $( window ).width() < minW ) right = $( window ).width() - minW;
			else right = 0;
			
			side.css({
				right		: right,
				height	: h
			});
			
			// .content
			contents.each( function(i)
			{
				$( this ).css({
					width		: w - sideWidth,
					height	: h
				});
			});
			
			
			// .photo
			photoContents.each( function(i)
			{
				var img = $( 'img', this );
				var obj = imgSizeList[i];
				var scale = Math.max( ( w - sideWidth ) / obj.width, h / obj.height );
				var targetW = obj.width * scale;
				var targetH = obj.height * scale;
				
				img
					.attr({
						width		: targetW,
						height	: targetH
					})
					.css({
						top		: ( h - targetH ) >> 1,
						left	: ( ( w - sideWidth ) - targetW ) >> 1
					});
			});
			
			
			
			
			if ( isIpod || isIphone || isIpad )
			{
				// ipod / iphone / ipad
				element.height( h );
				main.css( 'top', 0 );
			}
			else
			{
				// position
				$( window ).scrollTop( $( document ).height() * scrollPos );
				
				// scroll
				onScroll();
			}
		}
		
		
		/* enter frame handler
		------------------------------*/
		function enterFrameHandler()
		{
			var currentY;
			if ( isIpod || isIphone || isIpad )
			{
				// ipod / iphone / ipad
				currentY = main.position().top;
				main.css( 'top', currentY + Math.round( ( ypt - currentY ) * 0.2 ) );
			}
			else
			{
				currentY = $( window ).scrollTop();
				$( window ).scrollTop( currentY + Math.round( ( ypt - currentY ) * 0.2 ) );
			}
			
			enterframeID = setTimeout( enterFrameHandler, delay );
			
			if ( Math.abs( ypt - currentY ) <= 2 )
			{
				//console.log( 'complete enter frame' );
				
				// clear time out
				clearTimeout( enterframeID );
				
				if ( isIpod || isIphone || isIpad ) main.css( 'top', ypt );
				else $( window ).scrollTop( ypt );
				
				
				// change map zoom
				if ( cnt > 0 && cnt - 1 < markerList.length ) mapCanvas.setZoom( markerList[cnt - 1].zoom );
				
				
				// large map
				if ( $( '#map' )[0].contentWindow.$ && $( '#map' )[0].contentWindow.$.largeMap )
				{
					if ( ypt != $( '#map', main ).offset().top )
					{
						if ( $( '#map' )[0].contentWindow.$.largeMap.property.isZoom )
						{
							$( '#map' )[0].contentWindow.$.largeMap.zoomDefault();
						}
					}
					else if ( $( '#map' )[0].contentWindow.$.largeMap.property.currentMarker ) $( '#map' )[0].contentWindow.$.largeMap.zoomMap();
				}
			}
		}
		
		
		/* scroll
		------------------------------*/
		function onScroll( e )
		{
			// clear time out
			if ( intervalID ) clearTimeout( intervalID );
			
			// set time out
			intervalID = setTimeout( scrollComplete, 400 );
			
			
			// cnt
			cnt = Math.round( $( window ).scrollTop() / h );
			if ( cnt > contents.length - 1 ) cnt = contents.length - 1;
			
			// move map
			if ( cnt != current && cnt > 0 && cnt - 1 < markerList.length ) mapCanvas.panTo( new google.maps.LatLng( markerList[cnt - 1].lat, markerList[cnt - 1].lng ) );
			
			// change map zoom
			if ( mapCanvas.getZoom() > defaultZoom + 1 ) mapCanvas.setZoom( defaultZoom );
			
			// map
			if ( $( window ).scrollTop() >= h && $( window ).scrollTop() < h * markerList.length + 1 )
			{
				if ( !isMapVisible  )
				{
					isMapVisible = true;
					mapCont.stop().animate( { left: 20 }, 400, 'easeOutExpo' );
				}
			}
			else
			{
				if ( isMapVisible )
				{
					isMapVisible = false;
					mapCont.stop().animate( { left: -140 }, 400, 'easeOutExpo' );
				}
			}
			
			// page top
			if ( $( window ).scrollTop() >= $( document ).height() - h - ( h >> 1 ) )
			{
				if ( !isPageTopVisible )
				{
					isPageTopVisible = true;
					pagetop.css( 'display', 'block' ).stop().animate( { bottom: 25 }, 400, 'easeOutExpo' );
				}
			}
			else
			{
				if ( isPageTopVisible )
				{
					isPageTopVisible = false;
					pagetop.stop().animate( { bottom: -55 }, 400, 'easeOutExpo', function(){ pagetop.css( 'display', 'none' ) } );
				}
			}
			
			
			if ( isIE6 )
			{
				// side
				side.css( 'top', Math.max( $( window ).scrollTop(), h ) );
				
				// map
				mapCont.css( 'top', $( window ).scrollTop() + 20 );
				
				// date
				photoContents.each( function()
				{
					$( 'h4', this ).css( 'top', h - 280 );
				})
			}
			else
			{
				side.css( 'top', Math.max( 0, h - $( window ).scrollTop() ) );
				if ( $( window ).width() < minW )
				{
					side.css( 'right', right + $( window ).scrollLeft() );
				}
			}
			
			
			// current
			if ( current != cnt )
			{
				// current cnt
				current = cnt;
				
				
				// set prev navi
				if ( currentNavi )
				{
					var span = $( 'span', currentNavi );
					span.replaceWith( '<a href="' + span.attr( 'class' ) + '">' + span.text() + '</a>' );
					currentNavi
						.clickable()
						.bind( 'click', onNaviClick );
				}
				
				
				// set current navi
				if ( navi[cnt - 1] )
				{
					currentNavi = $( navi[cnt - 1] );
					currentNavi.addClass( 'current' );
					var a = $( 'a', currentNavi );
					a.replaceWith( '<span class="' + a.attr( 'href' ) + '">' + a.text() + '</span>' );
					currentNavi
						.unclickable()
						.unbind( 'click', onNaviClick );
				}
				else currentNavi = null;
			}
		}
		
		function scrollComplete()
		{
			ypt = h * cnt;
			enterFrameHandler();
			
			// ipod / iphone / ipad
			if ( isIpod || isIphone || isIpad )
			{
				side.stop().animate({ top: h * cnt }, 400, 'easeOutExpo' );
			}
		}
		
		
		/* mouse wheel
		------------------------------*/
		function onMouseWheel( e )
		{
			// clear enter frame
			if ( enterframeID ) clearTimeout( enterframeID );
		}
		
		
		/* click
		------------------------------*/
		function onNaviClick( e )
		{
			// clear enter frame
			if ( enterframeID ) clearTimeout( enterframeID );
			
			// ypt
			var arr = $( 'a', e.currentTarget ).attr( 'href' ).split( '/' );
			var target = $( arr[arr.length - 1] );
			
			ypt = ( isIpod || isIphone || isIpad ) ? -target.position().top : target.offset().top;
			
			
			// enterframe
			enterFrameHandler();
		}
		
		function onBtnClick( e )
		{
			$( 'a', e.currentTarget ).clickLink();
		}
		
		function onListClick( e )
		{
			//console.log( $( '#map' )[0].contentWindow.$.largeMap );
			//console.log( document.getElementById("map").contentWindow );
			
			// add class
			if ( !$( this ).is( '.visited' ) )
			{
				$( this ).addClass( 'visited' );
			}
			
			
			// select marker on large map
			$( '#map' )[0].contentWindow.$.largeMap.selectMarker( listNavi.index( this ) );
		}
		
		
		/* initialize
		==============================*/
		init();
	};
	
	
	
	$.fn.tokyoblue = function( options )
	{
		var defaults = {
			fps : 30
		};
				
		var options = $.extend( {}, defaults, options );
		
		return this.each( function()
		{
			new $.tokyoblue( $( this ), options );
		});
	};
	
})( jQuery );
