var map;
var image;
var infoWindow;
var dummyLayer;

var PALLET_HEIGHT;
var ANI_TIME = 250;
var palletMaxTop = -365;

var nowBoxId;				// 現在の絞り込みBOXのID
var detailLayer;			// 詳細表示のレイヤー

var CUSTOM_SCROLL_BAR = {
	scrollbarWidth		: 17,
	scrollbarMargin		: 0,
	animateTo			: true,
	animateInterval		: 20,
	animateStep			: 3,
	topCapHeight		: 39
};

var TABS = [ 'pics', 'times', 'places' ];

var MARKER_SHADOW_IMG;
var MARKER_DAT_URL		= './json/markers.json';

cacheObj				= function () {};
cacheObj.cache			= '';

var markerImgs			= new Array();
var markersArray;

var openTimer;
var closeTimer;

window.onload = init;

OverlayView.prototype = new google.maps.OverlayView();

//==================================================
// Init
//==================================================
function init()
{
	onResize();
	
	//--------------------------------------------------
	// GoogleMap関連
	//--------------------------------------------------
	var tmpLatlng = new google.maps.LatLng( 34.59718875381572, 133.76649501055908 );

	var tmpOptions = {
		zoom			: 13,
		center			: tmpLatlng,
		mapTypeId		: google.maps.MapTypeId.ROADMAP,
		mapTypeControl	: false
	};
	
    map = new google.maps.Map( document.getElementById( "map" ), tmpOptions );
	
	//
	// マーカー
	//
	for ( var i = 0, l = 47; i < l; i++ )
	{
		markerImgs[ i ] = new google.maps.MarkerImage(
			'./img/marker_' + digit( i + 1 ) + '.png',
			new google.maps.Size( 20, 32 ),
			new google.maps.Point( 0, 0 ), 
			new google.maps.Point( 10, 32 )
		);
	}
	
	//
	// マーカーの影
	//
	MARKER_SHADOW = new google.maps.MarkerImage(
		'./img/marker_shadow.png',
		new google.maps.Size( 24, 18 ),
		new google.maps.Point( 0, 0 ), 
		new google.maps.Point( 4, 18 )
	);
	
	//================================================== TEST ▲
	
	//--------------------------------------------------
	// マーカーの読み込み
	//--------------------------------------------------
	var data = cacheObj.cache;
	
	if ( data )
	{
		return putMarkers( data );
	}
	
	var onLoadedJSON = function ( data )
	{
        if ( !data )
        {
			return;
		}
		
		cacheObj.cache = data;
		putMarkers( data );
    }
    
    jQuery.getJSON( MARKER_DAT_URL, onLoadedJSON );
	
	//--------------------------------------------------
	// ダミーレイヤー（中心座標を計算するだめだけにある）
	//--------------------------------------------------
	dummyLayer = new OverlayView( map );
	
	//--------------------------------------------------
	// 詳細窓
	//--------------------------------------------------
//	var winOpt						= new google.maps.InfoWindowOptions();
//	winOpt.maxWidth					= 200;

	infoWindow = new google.maps.InfoWindow();
	
	//--------------------------------------------------
	// マップをクリックした時
	//--------------------------------------------------
	google.maps.event.addListener(
		map,
		'click',
		function( event )
		{
			cancelAll(); 
		}
	);
	
	//--------------------------------------------------
	PALLET_HEIGHT		= $('#picsbox').attr('offsetHeight');

	
	//--------------------------------------------------
	// アンカーの枠を消す
	//--------------------------------------------------
	var anchors = document.getElementsByTagName( 'a' );
	
	for ( var i = 0, l = anchors.length; i < l; i++ )
	{
		anchors[ i ].onfocus = function()
		{
			this.blur();
		}
	}
}

//--------------------------------------------------
// Resize時
//--------------------------------------------------
function onResize()
{
	//
	// GoogleMapが入る領域を調整
	//
	var mapHeight = $("#wrap").attr('offsetHeight') - 130;	// 130 = 110(header) + 20(footer)
	$('#map').height( mapHeight );
	
	palletMaxTop = - parseInt( mapHeight / 2 ); //-365;
	palletMaxTop = palletMaxTop < -365 ? -365 : palletMaxTop;
	palletMaxTop = palletMaxTop > -200 ? -200 : palletMaxTop;
	
	var newHeight = - palletMaxTop - 30;
	
	$('.selector').jScrollPaneRemove();
	
	$('.selector').height( newHeight );
	$('.selector').css( 'height', newHeight + "px" );	// IEはこっちでないと反映されない??
	
	$('.selector').jScrollPane( CUSTOM_SCROLL_BAR );
	
	openPallet( nowBoxId, 0 );
}

//--------------------------------------------------
// マーカーの配置 <- JSONファイルのロードが完了されたら呼ばれる
//--------------------------------------------------
function putMarkers( data )
{
	markersArray = data.markers;
	var tmpMarker;
	var l = markersArray.length;
	
	for( var i = 0; i < l; i++ )
	{
		tmpMarker = markersArray[i];
		
		markersArray[ i ].marker = new google.maps.Marker(
			{ 
				position	: new google.maps.LatLng( tmpMarker.lat, tmpMarker.lng ),
				map			: map,
				shadow		: MARKER_SHADOW,
				icon		: markerImgs[ i ],
				title		: tmpMarker.title
			}
		);
		
		google.maps.event.addListener(
			markersArray[ i ].marker,
			'click',
			( function( id )
			{
				return function()
				{
					showDetailLayer( id );
				}
			}
			).call( this, i )
		);
	}
	
	openTimer = setTimeout( function(){ openPallet( 'pics', ANI_TIME ); }, 1000 );
	closeTimer = setTimeout( function(){ closePallet(); }, 1800 );
}

//--------------------------------------------------
// 全閉じ
//--------------------------------------------------
function cancelAll()
{
	
//	alert( ">" + map.getCenter() + " / " + map.getZoom() );

	if( infoWindow )
	{
		infoWindow.close();
	}
	
	closePallet();
}

//--------------------------------------------------
// 作品リンクがクリックされた
//--------------------------------------------------
function showWork( id )
{
	id --;
	showDetailLayer( id );
	
	//
	// パレットを除いた領域でのセンタリング
	//
	var centerLatLnt = dummyLayer.getCentre( markersArray[ id ].marker.position );
	map.setCenter( centerLatLnt );
}

//--------------------------------------------------
// ダミーレイヤー関連
//--------------------------------------------------
function showDetailLayer( id )
{
	var contentString	= "<div class='detail'>"
						+ "<p><a href='./works/works_" + digit( id + 1 ) + ".html'><img src='./img/thumb_" + digit( id + 1 ) + ".jpg' width='100' height='65' alt='" + markersArray[ id ].title + "' /></a></p>"
						+ "<ul><li>" + markersArray[ id ].title + "</li><li><span>" + markersArray[ id ].artist + "</span></li><li><a href='./works/works_" + digit(id+1) + ".html'>詳細</a></li></ul>"
						+ "</div>";
	
	infoWindow.setContent( contentString );
	infoWindow.open( map, markersArray[ id ].marker ); 
}

function OverlayView( tmpMap )
{
	this.div_ = null;
	this.setMap( tmpMap );
}

OverlayView.prototype.onAdd = function()
{
}

OverlayView.prototype.draw = function()
{
	this.hide();
}

OverlayView.prototype.onRemove = function()
{
	this.div_.parentNode.removeChild( this.div_ );
	this.div_ = null;
}

//
// @param	latLng : 中心になるべき座標
//
OverlayView.prototype.getCentre = function( latLng )
{
	var overlayProjection = this.getProjection();
	
	var tmpPoint = overlayProjection.fromLatLngToDivPixel( latLng );
	
	var tmpY = tmpPoint.y + ( ( PALLET_HEIGHT ) / 2 ) - 40; // InfoWindowの分ちょっと下にする
	
	return this.getProjection().fromDivPixelToLatLng( new google.maps.Point( tmpPoint.x, tmpY ) );
}

OverlayView.prototype.hide = function()
{ 
	if (this.div_)
	{ 
		this.div_.style.visibility = "hidden";
	} 
} 
 
OverlayView.prototype.show = function()
{ 
	if (this.div_)
	{
		this.div_.style.visibility = "visible";
	}
} 

//--------------------------------------------------
// jQuery関連
//--------------------------------------------------
$(function()
{
	//--------------------------------------------------
	// リサイズ時
	//--------------------------------------------------
	$(window).resize(function()
	{
		onResize();
	});
	
	//--------------------------------------------------
	// スクロールバーのカスタマイズ
	//--------------------------------------------------
	$('.selector').jScrollPane( CUSTOM_SCROLL_BAR );
	
	//--------------------------------------------------
	// 別窓で開く
	//--------------------------------------------------
	$('.ext').attr("target","_blank");
	
	//--------------------------------------------------
	// 絞り込みの表示
	//--------------------------------------------------
	$('a.openSearch').bind
	(
		'click',
		function()
		{
			clearTimeout( openTimer );
			clearTimeout( closeTimer );
			
			var relId = $( this ).attr( 'rel' );
			var relBox = $( '#' + relId + 'box' );
			
			//
			// 開いているものと同じボタンなら閉じる
			//
			if( nowBoxId == relId )
			{
				closePallet();
			}
			//
			// 開いているものがあればまず閉じる
			//
			else if( nowBoxId )
			{
				changePallet( relId );
			}
			else
			{
				openPallet( relId, ANI_TIME );
			}
			
			return false;
		}
	);
	
	//--------------------------------------------------
	// 絞り込みを閉じる
	//--------------------------------------------------
	$('a.closeSearch').bind
	(
		'click',
		function()
		{
			closePallet();
			return false;
		}
	);
	
	//--------------------------------------------------
	// 作品のリンクがクリックされた時
	//--------------------------------------------------
	$('a.showWork').bind
	(
		'click',
		function()
		{
			showWork( $( this ).attr( 'rel' ) );
			return false;
		}
	);
});

function closePallet()
{
	var targetId;
	
	changeTab();
	
	$( '#innerbox' ).animate( { top: "-21px" }, ANI_TIME, "easeOutQuad" );
}

function openPallet( targetId, time )
{
	if ( targetId )
	{
		changeTab( targetId );
		
		$( '#innerbox' ).animate( { top: palletMaxTop + "px" }, time, "easeOutQuad" );
	}
}

function changePallet( targetId )
{
	if ( targetId )
	{
		changeTab( targetId );
	}
}

function changeTab( targetId )
{
	nowBoxId = targetId;
	
	var tmpTarget;
	
	for ( var i = 0, l = TABS.length; i < l; i++ )
	{
		tmpTarget = $('#mpnav' + TABS[i] + ' a');
		
		if ( targetId == TABS[i] )
		{
			$( '#' + TABS[i] + 'box' ).css( 'visibility', "visible" );
			
			tmpTarget.hover(
				function()
				{
					$( this ).css( 'backgroundPosition', '-240px 0' );
				},
				function()
				{
					$( this ).css( 'backgroundPosition', '-240px 0' );
				}
			);
			
			tmpTarget.css( 'backgroundPosition', '-240px 0' );
		}
		else
		{
			if ( targetId )
			{
				$( '#' + TABS[i] + 'box' ).css( 'visibility', "hidden" );
			}
			
			tmpTarget.hover(
				function()
				{
					$( this ).css( 'backgroundPosition', '-120px 0' );
				},
				function()
				{
					$( this ).css( 'backgroundPosition', '0' );
				}
			);
			tmpTarget.css( 'backgroundPosition', '0' );
		}
	}
}

function digit( num, keta )
{
	if ( keta == undefined )
	{
		keta = 2;
	}
	
	num = num + "";
	
	while( num.length <= keta - 1 )
	{
		num = "0" + num;
	}
	
	return num;
}

