
// 基本
var flashid = "yebizo";// flashムービーのID
var activeContentID = "top";//現在表示しているコンテンツID
var activeAnchorID = "";//現在アクティブなアンカーID

// スクロールボックス関連の変数
var scrlBox_initialized = false; //スクロールボックスが生成されているかどうか
var scrlBox_y; // スクロールボックスのY座標
var scrlBox_h; // スクロールボックスの高さ
var scrl_range; // スクロールの余地
var content_h; // スクロールするコンテンツの高さ
var scrlY = 0; // 現在のスクロール量
var flashIsActive = false; // Flashが表示されているかどうか
var preScrlY = 0;// ページ遷移する前のスクロールボックスのY座標

// 言語モードをクッキーから取得
var lang = getCookie("lang");
if( lang == "" ) lang = "jp";

// iPhone, iPadなどのタッチパネルデバイスかどうか
var agent = navigator.userAgent;
var isTouchDevice = ( agent.indexOf("iPhone") != -1 || agent.indexOf("iPad") != -1 );

// 基本となるmainArea内のdiv構造
var baseStructure = '<div class="main"><div class="content"></div></div><div class="barBox"></div><div class="shoulder">'+shoulderImage+'</div>';


/* ------------ for Contents -------------- */

// Initialize from hash key ( call when document.ready )
function initMain()
{
	// get id for content
	var hashKey = location.hash.slice(1);
	if( hashKey )
	{
		var hash_arr = hashKey.split("/");
		if( hash_arr[0] == "" ) hash_arr.shift();
		// read content
		if( hash_arr.length > 1 )
		{
			readContent(hash_arr[0], hash_arr[1] );
		}
		else
		{
			readContent(hash_arr[0], null );
		}
	}
	else
	{
		// in case hash is empty
		readContent(activeContentID, null);
	}
}

// Load contents
function readContent( contentID, anchorID )
{
	
	//refresh
	switch( activeContentID)
	{
		case "top":
			/*
			if( flashIsActive )
			{
				initWheel(false);
				$(".mainArea").empty();
				$(".mainArea").append( baseStructure );
			}
			*/
		break;
		case "contents":
			$(".main").empty();
			$(".main").append('<div class="content"></div>');
		break;
		default:
			if( activeContentID.slice(0,2) != "pg" && activeContentID.slice( 0,2 ) != "ar" )
			{
				preScrlY = scrlY;
			}
			$(".content").empty();
	}
	
	activeContentID = contentID;
	activeAnchorID = anchorID;
	
	if( activeContentID == "html" )
	{
		preScrlY = 0;
		
		var url = "xhtml_top.xml";
		$(".content").load("xml/" + url, onLoadContents);
		
		flashIsActive = false;
	}
	else
	{
		
		var url = "xhtml_"+contentID+".xml";
		$(".content").load("xml/" + url, onLoadContents);
		
		flashIsActive = false;
	}
}

// Resize flash height when window resized.
function resizeFlash()
{
	var flashHeight = $(window).height() - $(".mainArea").position().top;
	$("#flashcontent").css("height", flashHeight + "px" );
	$("#"+flashid).css("height", flashHeight + "px" );
	return flashHeight;
}

//Initialize Contents ( call when main.onload )
function onLoadContents()
{
	var self = this;
	
	//initialize page top
	$(".pagetop").css("cursor","pointer");
	$(".pagetop").click(function(){ pageTop(); });
	$(".pagetop").mouseover( function() { onover( $(this) ) } );
	$(".pagetop").mouseout( function() { onout( $(this) ) } );
	
	var initPlatformLink = function()
	{
		$(".platform").click( function(){ location.hash = $(this).attr("id");});
		$(".platform").mouseover( function(){ onover($(this)); });
		$(".platform").mouseout( function(){ onout($(this)); });
	}
	switch( activeContentID )
	{
		case "top":// for 2012
			preScrlY = 0;
			
			
			if( isTouchDevice )
			{
				$("#flashcontent").append('<video controls autoplay width="720" height="404"><source src="http://web-cache.stream.ne.jp/web/live/iphone-live/yebizo-live/meta.m3u8"></video>');
			}
			else
			{
				// init flash
				var flashvars ={};
				var params = { menu: "false", scale:"noscale", allowScriptAccess:"always", bgcolor:"#000000" };
				var atts ={id: flashid }
				swfobject.embedSWF("top12.swf", "flashcontent", "720", "404" , "9.0.115", 'js/expressinstall.swf', flashvars, params, atts);
			}
		break;
		case "contents":
			preScrlY = 0;
			$(".main").prepend(infomenu());
			$(".info_menuBtn").css("cursor","pointer");
			$(".info_menuBtn").click( function(){
				var id = $( this ).attr("id");
				var anchorID = id.split("_")[1];
				scrlByID( anchorID, true );
			});
			$(".info_menuBtn").mouseover( function() { onover( $(this) ) } );
			$(".info_menuBtn").mouseout( function() { onout( $(this) ) } );
		break;
		case "bySection":
		case "byDate":
			fadeInImage(".exBox > img");
			fadeInImage(".programBox > img");
			initLinkBtn(".exCont");
			initLinkBtn(".programLine");
		case "artists":
			fadeInImage(".artistBox > img");
			initLinkBtn(".artistBox");
			initPlatformLink();
		break;
		default:
			switch(activeContentID.slice(0,2))
			{
				case "ar":
					fadeInImage(".prof_thumb");
					initPlatformLink();
					initBackBtn(".btn_back");
				break;
				case "pg":
					fadeInImage(".pg_thumb");
					initLinkBtn(".artistLink");
					initLanguageBar();
					initBackBtn(".btn_back");
				break;
			}
	}
	
	initContents();
}

// Set LanguageBar
function initLanguageBar()
{
	var btn_jp = $(".btn_jp");
	var btn_en = $(".btn_en");
	switch( lang )
	{
		case "jp":
			btn_jp.die("click"); onout( btn_jp );
			btn_en.live("click", function(){ changelang("en");}); onover( btn_en );
		break;
		case "en":
			btn_en.die("click"); onout( btn_en );
			btn_jp.live("click", function(){ changelang("jp");}); onover( btn_jp );
		break;
	}
	$(".body_jp").css("display", lang == "jp" ? "block":"none" );
	$(".body_en").css("display", lang == "en" ? "block":"none" );
}

// Change language
function changelang( newLang )
{
	setCookie("lang", newLang);
	lang = newLang;
	initLanguageBar();
	content_h = $(".content").height() + 100;//plus 100 for bottom margin
	updateScrlHeight();
}

// Build information menu code ( Contents Menu )
function infomenu()
{
	var alts = ["開催によせて/WELCOME","第３回テーマについて/CONTENTS","実施概要/OUTLINE","チケット情報/TICKET INFORMATION","会場へのアクセス/ACCESS"];
	var code = '<div class="info_menuBox">';
	for( var i = 0; i < alts.length; i++) code += '<img class="info_menuBtn" id="btn_info'+i+'" src="images/info/btn_'+i+'.png" width="200" height="58" alt="'+alts[i]+'" />';
	code += '</div>';
	return code;
}


/* ------------ for ScrlBox -------------- */

// Initialize the contents and initialize scrlBox UI.
function initContents()
{
	content_h = $(".content").height() + 100;//plus 100 for bottom margin
	if( !isTouchDevice && !scrlBox_initialized)
	{
		initScrlBox();
	}
	else
	{
		scrl_range = content_h - scrlBox_h;
	}
	// check scrlBox able or disable
	scrlIsActive(( scrl_range > 0 ) );
	
	// scrl to...
	if( activeAnchorID )
	{
		scrlByID(activeAnchorID);
	}
	else if( preScrlY != 0 && activeContentID.slice(0,2) != "pg" && activeContentID.slice( 0,2 ) != "ar")
	{
		scrlByPix( preScrlY, true );
	}
	else
	{
		scrlByPix( 0, true );
	}
}

// Initialize ScrollBox Interface
function initScrlBox()
{
	scrlY = 0;
	scrlBox_y = $(".barBox").position().top;
	scrlBox_h = $(window).height() - scrlBox_y;
	scrl_range = content_h - scrlBox_h;
	
	// change div.main::height property
	$(".main").css("height",(scrlBox_h-40) + "px"); // minus 40 for main padding-Top
	
	// append to div.barBox
	var barBoxCode = '<img id="btn_scrlTop" src="/images/common/spacer.gif" width="40" height="50" border="0" alt="" />';
	barBoxCode += '<div id="slider" style="height:'+(scrlBox_h - 100)+'px;"></div>';
	barBoxCode += '<img id="btn_scrlBottom" src="/images/common/spacer.gif" width="40" height="50" border="0" alt="" />';
	$(".barBox").append( barBoxCode );
	
	// initialize slider UI
	$("#slider").slider({
		orientation: "vertical",
		range: "min",
		min: 0,
		max: 100,
		value: 100,
		animate: true,
		slide: function(event, ui) {
			scrlByPar( 100 - ui.value );
		}
	});
	$("#btn_scrlTop").click( function(){ scrlByPix(0, true); } );
	$("#btn_scrlBottom").click( function(){ scrlByPar(100, true); } );
	
	// window resize handler
	$(window).resize( updateScrlHeight );
	
	// initialize MouseWheel event handler
	$(".rightbox").mouseover( function(){	initWheel( true );});
	$(".rightbox").mouseout( function(){	initWheel( false );});
	
	// initialize animation
	$(".ui-slider-handle:first").css({ opacity:0, bottom:"0%" });
	$(".ui-slider-handle:first").animate( { opacity: 1, bottom:"100%" }, 1500, "easeOutExpo" );

	scrlBox_initialized = true;
}


function killScrlBox()
{
	initWheel(false);
	$(window).die("resize");
	$("#btn_scrlTop").die("click" );
	$("#btn_scrlBottom").die( "click" );
	$(".rightbox").die( "mouseover" );
	$(".rightbox").die( "mouseout" );
	$("#slider").slider("destroy");
	$(".barBox").empty();
	scrlBox_initialized = false;
}

// Check content height and scrollBox activation.
function scrlIsActive( sw )
{
	if( sw )
	{
		$(".barBox").css("visibility", "visible");
		initWheel(false);
	}
	else
	{
		$(".barBox").css("visibility", "hidden");
		initWheel(true);
		scrlByPix(0);
	}
}

// Scroll by pixel (.content margin-top)
function scrlByPix( pix, changeSlider, animate )
{
	if( scrlBox_initialized )
	{
		scrlY = pix;
		if( animate )
		{
			$(".content").animate( { marginTop: pix + "px" }, 500, "easeOutExpo" );
		}
		else
		{
			$(".content").css("margin-top", pix + "px");
		}
		if( changeSlider ) $("#slider").slider( "option", "value", 100-(Math.round( -scrlY / scrl_range * 100)) );
	}
}

// Scroll by parcent. call by slider UI.
function scrlByPar( parcent, changeSlider, animate ){ if( scrlBox_initialized ) scrlByPix( Math.round(scrl_range * parcent * -0.01), changeSlider, animate );}

// Scroll by mouse wheel
function scrlByWheel( delta )
{
	if( scrlBox_initialized ) scrlByPix( Math.min( 0, Math.max( -scrl_range , scrlY + (delta*100))) , true, false);
	if( flashIsActive )
	{
		$("#"+flashid)[0].externalMouseEvent( delta );
	}
}

// Scroll by object-id in div.content class
function scrlByID( id, animate ){	var vscrl = $("#"+ id ).position().top - scrlBox_y - 40 - scrlY;scrlByPix( -vscrl, true, animate );}

// Scroll to top with animation
function pageTop(){ if( scrlBox_initialized ) scrlByPix( 0, true, true );}

// Change Scroll Box Height
function updateScrlHeight()
{
	scrlBox_h = $(window).height() - scrlBox_y;
	scrl_range = content_h - scrlBox_h;
	$(".main").css("height", (scrlBox_h - 40) +"px");
	$("#slider").css("height", (scrlBox_h - 100) +"px" );
	scrlIsActive(( scrl_range > 0 ) );
}

// set wheel action
function initWheel( sw )
{
	if( sw )
	{
		if (window.addEventListener)
		{
			window.addEventListener('DOMMouseScroll', wheel, false);// for mozilla
		}
		window.onmousewheel = document.onmousewheel = wheel;
	}
	else
	{
		if (window.addEventListener) window.removeEventListener('DOMMouseScroll', wheel, false);
		window.onmousewheel = document.onmousewheel = null;
	}
}

// Event handler for mouse wheel event.
function wheel(event)
{
	var delta = 0;
	
	if (!event) event = window.event; /* For IE. */
			
	if (event.wheelDelta)
	{
		/* IE/Opera. */
		delta = event.wheelDelta/120;
		if (window.opera) delta = -delta;
	}
	else if (event.detail)
	{ 
		/** Mozilla case. */
		delta = -event.detail/3;
	}
	/** If delta is nonzero, handle it.
	 * Basically, delta is now positive if wheel was scrolled up,
	 * and negative, if wheel was scrolled down.
	 */
	if (delta) scrlByWheel( delta );

	if (event.preventDefault) event.preventDefault();
	
	event.returnValue = false;
}

/* ------------ Cookie -------------- */

function getCookie(key,  tmp1, tmp2, xx1, xx2, xx3) {
    tmp1 = " " + document.cookie + ";";
    xx1 = xx2 = 0;
    len = tmp1.length;
    while (xx1 < len) {
        xx2 = tmp1.indexOf(";", xx1);
        tmp2 = tmp1.substring(xx1 + 1, xx2);
        xx3 = tmp2.indexOf("=");
        if (tmp2.substring(0, xx3) == key) {
            return(unescape(tmp2.substring(xx3 + 1, xx2 - xx1 - 1)));
        }
        xx1 = xx2 + 1;
    }
    return("");
}
function setCookie(key, val, tmp) {
    tmp = key + "=" + escape(val) + "; ";
    // tmp += "path=" + location.pathname + "; ";
    tmp += "expires=Tue, 31-Dec-2030 23:59:59; ";
    document.cookie = tmp;
}
function clearCookie(key) {
    document.cookie = key + "=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
}

/* ------------ Animation, UI -------------- */

// コンテンツリンクボタンを作成
function initLinkBtn( selector )
{
	$(selector).click( function(){
		location.hash = $(this).attr("id");
		});
	$(selector).mouseover( function(){ onover($(this)); });
	$(selector).mouseout( function(){ onout($(this)); });
}
// BACKボタンにアクションを設定
function initBackBtn( selector )
{
	$(selector).click( function(){
		history.back();
		});
	$(selector).mouseover( function(){ onover($(this)); });
	$(selector).mouseout( function(){ onout($(this)); });
}
// イメージをフェードイン
function fadeInImage( selector )
{
	var jq = $(selector);
	jq.css( {opacity:0} );
	jq.load( function(){ $(this).animate( { opacity: 1 }, "slow" ) });
}
// 半透明に
function onover( target )
{
	target.css("filter","alpha(opacity=50)");
	target.css("-moz-opacity","0.5");
	target.css("opacity","0.5");
}
// 半透明解除
function onout( target )
{
	target.css("filter","alpha(opacity=100)");
	target.css("-moz-opacity","1");
	target.css("opacity","1");
}

/* ------------ Share SNS -------------- */

function shareFB()
{
	var href='http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.yebizo.com&t=%e7%ac%ac%ef%bc%94%e5%9b%9e%20%e6%81%b5%e6%af%94%e5%af%bf%e6%98%a0%e5%83%8f%e7%a5%ad%e3%80%80%e3%80%8c%e6%98%a0%e5%83%8f%e3%81%ae%e3%83%95%e3%82%a3%e3%82%b8%e3%82%ab%e3%83%ab%20How%20physical%e3%80%8d%e3%80%802%2e10fri%2d2%2e26sun%ef%bc%8f2012%ef%bc%8815days%ef%bc%89%20%5bClosed%20Mondays%5d%e3%80%80http%3a%2f%2fwww%2eyebizo%2ecom%2f&ampsrc=sp';
	window.open(href,'sharer','toolbar=0,status=0,width=626,height=436');
}

function shareTW()
{
	var href='http://twitter.com/share?text=%e7%ac%ac%ef%bc%94%e5%9b%9e%20%e6%81%b5%e6%af%94%e5%af%bf%e6%98%a0%e5%83%8f%e7%a5%ad%e3%80%80%e3%80%8c%e6%98%a0%e5%83%8f%e3%81%ae%e3%83%95%e3%82%a3%e3%82%b8%e3%82%ab%e3%83%ab%20How%20physical%e3%80%8d%e3%80%802%2e10fri%2d2%2e26sun%ef%bc%8f2012%ef%bc%8815days%ef%bc%89%20%5bClosed%20Mondays%5d';
	window.open(href,'sharer','toolbar=0,status=0,width=626,height=436');
}
