var timeYYYYNode;
var timeMONode;
var timeDDNode;
var timeHHNode;
var timeMMNode;
var timeSSNode;
var timeWWNode;

var timeLag;
var timeTimer;

var nowYear;
var nowMonth;
var nowDate;
var nowHour;
var nowMinute;
var nowSecond;
var nowDay;

var sideDiv;
var sideDivIniY;
var footerY;
var FIX_MARGIN_TOP		= 10;					// サイドトップのマージン
var FIX_MARGIN_BOTTOM	= 80;					// フッタから何px上に上げるか ※FIX_MARGIN_TOPを先に決めて調整

var sendWindow = { 
					loader:0, 
					width:416,
					height:267,
					borderSize:0,
					borderColor:null,
					windowBGColor:null,
					windowPadding:0
				};

function initMain()
{
	replaceAnchor();
	
	timeExe();
	
	readyML();
	
	replaceSunsteAnchor();
	
	replaceSunsteFooter();
	
	//
	// for GOOGLE ANALYTICS
	//
	if ( URL.indexOf ( 'okayama' ) != -1)
	{
		setGoogleAnalytics( 'UA-20824217-4' );
	}
	else if ( URL.indexOf ( 'fukuyama' ) != -1)
	{
		setGoogleAnalytics( 'UA-20824217-3' );
	}
	else
	{
		setGoogleAnalytics( 'UA-20824217-5' );
	}
}

/**************************************************
 *
 *	時計関連 ※要jquery.js
 *
**************************************************/
function timeExe()
{
	timeYYYYNode	= document.getElementById( 'yyyy' );
	timeMONode		= document.getElementById( 'mo' );
	timeDDNode		= document.getElementById( 'dd' );
	timeHHNode		= document.getElementById( 'hh' );
	timeMMNode		= document.getElementById( 'mm' );
	timeSSNode		= document.getElementById( 'ss' );
	timeWWNode		= document.getElementById( 'ww' );
	
	if ( timeYYYYNode )
	{
		var jsonUrl;
		
		jsonUrl		= ROOT_PATH + '/cgi/nowDate.cgi';
    	
		if ( window.jQuery )
		{
			var loadTime = function ( data )
			{
	            if ( !data )
	            {
					return;
				}
				
				onLoadedTime( data );
	        }
	        
	        jQuery.getJSON( jsonUrl, loadTime );
		}
	}
}

function onLoadedTime( data )
{
	var today		= new Date();
	var timeA		= today.getTime();
	var timeB;
	
	var year		= data[ 'year' ];
	var month		= data[ 'month' ];
	var date		= data[ 'date' ];
	var hour		= data[ 'hour' ];
	var minute		= data[ 'minute' ];
	var second		= data[ 'second' ];
	
	today.setFullYear( year );
	today.setMonth( month );
	today.setDate( date );
	today.setHours( hour );
	today.setMinutes( minute );
	today.setSeconds( second );
	
	timeB			= today.getTime();
	
	timeLag			= timeA - timeB;		// サーバとの時間差を計算
	
	timeHandler();
}

function timeHandler()
{
	var tmpDate		= new Date();
	tmpDate.setTime( tmpDate.getTime() - timeLag );
	
	nowYear			= tmpDate.getYear();
	nowMonth		= tmpDate.getMonth();
	nowDate			= tmpDate.getDate();
	nowHour			= tmpDate.getHours();
	nowMinute		= tmpDate.getMinutes();
	nowSecond		= tmpDate.getSeconds();
	nowDay			= tmpDate.getDay();
	
	nowYear -= ( nowYear > 1900 ? 2000 : 100 );
	
	nowMonth++;
	
	timeYYYYNode.style.backgroundPosition	= "0 " + ( -11 * nowYear ) + "px";
	timeMONode.style.backgroundPosition		= "0 " + ( -22 * nowMonth ) + "px";
	timeDDNode.style.backgroundPosition		= "0 " + ( -22 * nowDate ) + "px";
	timeHHNode.style.backgroundPosition		= "0 " + ( -13 * nowHour ) + "px";
	timeMMNode.style.backgroundPosition		= "0 " + ( -13 * nowMinute ) + "px";
	timeSSNode.style.backgroundPosition		= "0 " + ( -13 * nowSecond ) + "px";
	timeWWNode.style.backgroundPosition		= "0 " + ( -11 * nowDay ) + "px";
	
	timeTimer		= setTimeout( "timeHandler()", 500 );
}

/**************************************************
 *
 *	サイドDIVの固定
 *
**************************************************/
function fixSideDiv()
{
	sideDiv		= document.getElementById( 'searchBar' );
	sideDivIniY	= getAbsolutePos( document.getElementById( 'searchBar' ) ).y;
	
	//
	// for IE6
	//
	if( IE && document.compatMode == "BackCompat" )
	{
	//	document.body.onscroll = onScrollEvent;
	}
	//
	// for Other Browser
	//
	else
	{
		document.onscroll = onScrollEvent;
		document.documentElement.onscroll = onScrollEvent;
	}
	
	onScrollEvent();
}

function onScrollEvent()
{
	viewPort	= getViewportArea();
	footerY		= getAbsolutePos( document.getElementById( 'footer' ) ).y;		// JSでページの一部を表示している時に高さが変わるから毎回取得する
	
	if ( sideDiv )
	{
		//
		// i) Topが枠外の場合
		//
		if ( viewPort.y < ( sideDivIniY - FIX_MARGIN_TOP ))
		{
			sideDiv.style.position = "relative";
			sideDiv.style.top = null;
		}
		//
		// ii) Bottomが枠外の場合
		//
		else if (( viewPort.y + sideDiv.offsetHeight ) > footerY - FIX_MARGIN_BOTTOM )
		{
			sideDiv.style.position = "relative";
			sideDiv.style.top = ( footerY - sideDiv.offsetHeight - sideDivIniY - FIX_MARGIN_BOTTOM + FIX_MARGIN_TOP ) + "px";
		}
		//
		// iii) 
		//
		else
		{
			sideDiv.style.position = "fixed";
			sideDiv.style.top = FIX_MARGIN_TOP + "px";
		}
	}
}

/**************************************************
 *
 *	メールマガジンの登録 ※要jquery.js
 *
**************************************************/
function readyML()
{
	var iniText			= 'メールアドレス';
	var mlEmailNode		= document.getElementById( 'registerEmail' );
	var mlButtonNode	= document.getElementById( 'registerBtn' );
	
	if ( document.forms['ml'] )
	{
		document.forms['ml'].elements['mlEmail'].value = iniText;
		
		mlEmailNode.onfocus = function()
		{
			if ( document.forms['ml'].elements['mlEmail'].value == iniText )
			{
				document.forms['ml'].elements['mlEmail'].value = '';
			}
		}
		
		mlEmailNode.onblur = function()
		{
			if ( document.forms['ml'].elements['mlEmail'].value == '' )
			{
				document.forms['ml'].elements['mlEmail'].value = iniText;
			}
		}
		
		mlButtonNode.onclick = function()
		{
			var email		= document.forms['ml'].elements['mlEmail'].value;
			subscribeML( email );
			return false;
		}
	}
	
	//
	// 送信中ウィンドウの作成
	//
	$('body').append('<div id="sendingWindowOk" style="display:none;"><div id="sendingOK"><div class="btm"><div class="bg"><h3>登録用URLを送信いたしました</h3><p class="sendingMsg">ご記入のメールアドレスにさんすてメールマガジンの登録用URLを送信しました。送信されたURLのページを表示して、登録用ページにおすすみください。また、メールマガジンの詳細については<a href="./magazine/">こちら</a>のページよりご覧いただけます。</p><p class="sendingClose"><a href="#footer" class="closeDOMWindow">閉じる</a></p></div></div></div></div>');
	
	$('body').append('<div id="sendingWindowNG" style="display:none;"><div id="sendingNG"><div class="btm"><div class="bg"><h3>メールの送信に失敗しました</h3><p class="sendingMsg">ご記入のメールアドレスへのメール送信に失敗しました。もう一度ご記入いただいたメールアドレスをお確かめの上、再度送信ボタンをクリックしてください。</p><p class="sendingClose"><a href="#footer" class="closeDOMWindow">閉じる</a></p></div></div></div></div>');
}

function subscribeML( email )
{
	var jsonUrl;
	
	jsonUrl		= ROOT_PATH + '/cgi/subscribeML.cgi?email=' + email;

	if ( window.jQuery )
	{
		var onSubscribedML = function ( data )
		{
            if ( !data )
            {
				return;
			}
			
			onFinishedSubscribeML( data );
        }
        
        jQuery.getJSON( jsonUrl, onSubscribedML );
	}
}

function onFinishedSubscribeML( data )
{
	var success	= data[ 'success' ];
	
	if ( success == 1 )
	{
		sendWindow['windowSourceID']	= '#sendingWindowOk';
	}
	else
	{
		sendWindow['windowSourceID']	= '#sendingWindowNG';
	}
	
	$.openDOMWindow( sendWindow ); 
}


/**************************************************
 *
 *	アンカーの処理
 *
**************************************************/
function replaceSunsteAnchor()
{
	var aNodes = document.getElementsByTagName( 'a' );
	var node;
	
	for( var i=0, l=aNodes.length; i<l; i++ )
	{
		node = aNodes[i];
		
		if ( node )
		{
			//
			// 一覧へ戻る
			//
			if( node.id == "prev" )
			{
				var anchor = URL.replace( /[^\/]*$/, '' );
				
				//
				// i) 直URL
				// ii) 別ドメインから飛んできたか、別ウィンドウ表示の場合はアンカーを消す
				//
				if(
					( !REFERRER && !window.name ) ||
					(( REFERRER.match( HOST_REG ) && RegExp.$1 != HOST_NAME ) || window.name )
				)
				{
				//	node.href = anchor;
				}
				//
				// iii) 一覧画面、検索画面、別ページに戻る
				//
				else
				{
					node.href = REFERRER;
				}
			}
			//
			// History.back()
			//
			else if ( node.className == 'bach' )
			{
				node.href = "#";
				node.onclick = function()
				{
					history.back();
					return false;
				}
			}
			
		}
	}
}

/**************************************************
 *
 *	フッターの処理
 *
**************************************************/
function replaceSunsteFooter()
{
	var jsonUrl = ROOT_PATH + '/cgi/replaceFooterCategory.cgi';

	if ( window.jQuery )
	{
		var loadCategory = function ( data )
		{
            if ( !data )
            {
				return;
			}
			
			onLoadedCategory( data );
        }
        
        jQuery.getJSON( jsonUrl, loadCategory );
	}
}


function onLoadedCategory( data )
{
	var html	= data[ 'html' ];
	
	var categoryNode = document.getElementById( 'footerCategory' );
	
	if ( categoryNode )
	{
		html = html.replace( /ROOT_PATH/g, ROOT_PATH );	// <-- ROOT_PATH を挿入
		categoryNode.innerHTML	= html;
	}
	
	//
	// さんすて福山の場合
	//
	if ( URL.indexOf( '/fukuyama/' ) != -1 )
	{
		addEventSpaceLink();
	}
}

function addEventSpaceLink()
{
	var eventSpaceLinkTag = '<li><a href="' + ROOT_PATH + '/eventspace/" title="イベントスペースのご案内">イベントスペースのご案内</a></li>';
	
	$( '#footerTVCM' ).parent().parent().append( eventSpaceLinkTag );
}

//--------------------------------------------------
addOnloadEvent( initMain );

