// Photo Viewre -- (C) 2006 - 2008 Takafumi Kasai
// Works with prototype.js


// ======================================================================================
// グローバル変数定義

var Current  = 0; /* Current page number */
var Page_Min = 0; /* First page number */
var Page_Max;     /* Max page number */

var Page_Data     = new Array(); // 各ページの情報(HTML)
var Pagelist_title_len = 8;
var Pagelist_width = 140;
var Pagelist_margin = new Array(  50, 120 );
var Pagelist_min    = new Array( 120, 120 );


var Previos_scrolltop;  // 直前の、縦スクロール量

// 音楽再生用
var Player;    // Windows Media Player オブジェクト
var Playable;  // ↑が使用可能か格納するフラグ

var Music_selector;       // 曲選択用プルダウンオブジェクト (画面上では隠れている)
var Music_controller;     // 再生･停止ボタンオブジェクト
var Music_default_volume; // デフォルト音量
var Music_current_volume; // 現在の音量
var Music_index;          // ページごとの曲番号
var Music_fade_interval = 300; // 音楽のフェードアウトを1段階進めるのに要する秒数 (ミリ秒)


// ======================================================================================
// クラス定義

	var Photomenu_group = Class.create();
	Photomenu_group.prototype = {
		member: new Array(),
		initialize: function(members){
			if ( members ){
				this.member = members;
			}
		}
	};

	var Photomenu = Class.create();
		 Photomenu.setMask = function(){
			if ( this.useMask ){
				$("click_sheld").style.visibility = "visible";
				setTimeout("Effect.Appear('scratch_mask', {duration:0.2, to: 0.8})", 1);
			}
		};
		 Photomenu.unsetMask = function(){
			if ( this.useMask ){
				$("click_sheld").style.visibility = "hidden";
				setTimeout("Effect.Fade('scratch_mask', {duration:0.2})", 1);
			}
		};
		 Photomenu.open = function(){
			for ( var i = 0; i < this.group.member.length; i++){
				if ( this.group.member[i].id != this.id ){
					this.group.member[i].close(this.useMask);
				}
			}
			this.setMask();
			if ( this.useMask ){
			//	document.body.style.overflowY = "hidden";
			}
			
			this.style.visibility = "visible";
			this.show();
			this.isOpen = true;
			this.postOpen();
		};
		 Photomenu.close = function( remain_mask ){
			if ( !remain_mask ){
				if ( this.useMask ){
				//	document.body.style.overflowY = "";
				}
				this.unsetMask();
			}
			this.hide();
			this.style.visibility = "hidden";
			this.isOpen = false;
		};
		 Photomenu.toggle = function(){
			if ( this.isOpen ){
				this.close();
			} else {
				this.open();
			}
		};
		Photomenu.gotoOrg = function(){
			var curTop   = this.getStyle("top");
			var curLeft  = this.getStyle("left");
		//	var curRight = this.getStyle("right");
			
			curTop   = curTop   ? curTop.replace(/\w\w$/, "") : 0;
			curLeft  = curLeft  ? curLeft.replace(/\w\w$/, "") : 0;
		//	curRight = curRight ? curRight.replace(/\w\w$/, "") : 0;
			
			var ydiff = this.orgTop  - curTop;
			var xdiff = this.orgLeft - curLeft;
			new Effect.Move(this, {x: xdiff, y:ydiff, duration: Search_result_anime_delay});
		};
		 Photomenu.init = function(group){
//			alert(this.getStyle("left").replace(/\w\w$/, ""));
			this.group = group;
			this.orgTop   = this.getStyle("top");
			this.orgLeft  = this.getStyle("left");
		//	this.orgRight = this.getStyle("right");
			
			this.orgTop   = this.orgTop   ? this.orgTop.replace(/\w\w$/, "") : 0;
			this.orgLeft  = this.orgLeft  ? this.orgLeft.replace(/\w\w$/, "") : 0;
		//	this.orgRight = this.orgRight ? this.orgRight.replace(/\w\w$/, "") : 0;
		};

	Photomenu.prototype = {
		group: undefined,
		isOpen: false,
		useMask: true,
		setMask: Photomenu.setMask,
		unsetMask: Photomenu.unsetMask,
		gotoOrg: Photomenu.gotoOrg,
		orgTop: undefined,
		orgLeft: undefined,
		orgRight: undefined,
		locate: undefined,
		keyscan: function(){},

		open : Photomenu.open,
		postOpen: function(){},
		close: Photomenu.close,
		toggle: Photomenu.toggle,
		initialize: Photomenu.init
	};

// ページロード(Ajax経由含む)時の初期化関数
function init( first_page, is_ajax ){
	// 直前に表示していたページに関するデータの初期化

	page_list.pages  = new Array();  // ページ一覧をクリア
	page_list.groups = new Array();  // ページ一覧をクリア
	page_list.currentGroup = 0;

	Music_index = new Array();    // ページごとの曲番号を格納する配列を初期化

	if ( ! Is_ie ){
			Pagelist_title_len = 6;
	}

	// 読み込み済みページデータを解析し、配列 Page_Data に代入
	// ページ一覧の生成もここで行う
	Page_Data = set_pagedata( "div", "page", "data_", "data" );
	
	// ページ数を取得し、画面(ツールバー)に反映
	Page_Max = Page_Data.length - 1;
	$("total_number").innerHTML = ( Page_Max + 1);


	// 最後のページに、カテゴリ一覧表示用のリンクを追加
	var div = document.createElement('div');
	div.className = "last_page_notify";
	div.innerHTML = '<p>最後のページです。'
		+ '<span class = "pseudo_a"'
		+ 'style = "font-size: 105%; border: solid 2px #332; padding: 3px; background-color: #330;"'
		+ 'onMouseover = "this.style.borderColor=\'#443\'; this.style.backgroundColor=\'#551\';"'
		+ 'onMouseout  = "this.style.borderColor=\'#332\'; this.style.backgroundColor=\'#330\';"'
		+ 'onClick     = "$(\'item_scratch\').open();"'
		+ '>▼他のカテゴリに移動</span></p>';

	$( Page_Data[ Page_Max ] ).appendChild( div );

	if( !is_ajax ){	// Ajax での再描画時に繰り返さなくてもよい処理をスキップ
		// メニューにメソッド・プロパティを継承
		var right_form = $("right_form");
		Object.extend( right_form, Photomenu_group.prototype );
		 right_form.initialize( [ search_result, page_list, item_scratch ] );
		
		right_form.member.each( function(id){
			Object.extend( id, Photomenu.prototype );
			id.initialize(right_form);
		} );
		search_result.useMask = false;
		search_result.setStyle({opacity: 0.93});
		page_list.postOpen = function(){ toggle_pagelist_navi( page_list.groups.length ); blink_pagelist("page_list_" + Current) };
		
		button_prev_label.title = Message.title_back;
		button_next_label.title = Message.title_next;
		
		// ページ縦スクロールに、パネルを追随させる為の前処理
		Previos_scrolltop = document.body.scrollTop;

		// 音楽再生機能の初期化
		Playable = init_player("music_track", "music_switch");
		
		// 検索パネルに、Enter キー押下時のイベント(検索開始する)を登録
		if( window.captureEvents ) { // NS
			window.captureEvents( Event.KEYDOWN );
			window.onkeydown = function(e){ keypress_handle( e, e.which, e.shiftKey, e.altKey ) };
		}
		else { // IE
			document.onkeydown = function(){ keypress_handle( event, window.event.keyCode, window.event.shiftKey, window.event.altKey ) };
		}

		// 本文背景の黒半透明の四角を表示
		background_mask.style.display = "block";

		// ページへのリンク文字列表示
		link_copier.show();

		// png 画像を表示 ( IE は除く )
		if ( ! Is_ie ){
			$("toolbar_shadow").src = "shadow.png";   // ツールバー背景の影
			$("toolbar_shadow").style.left = "30px";
			$("toolbar_shadow").style.top  = "-8px";
			$("toolbar_shadow").style.width = "100%";
			$("title_logo").src     = "logo_q.png";   // タイトルロゴ
			$("button_prev").src    = "btn_back.png"; // 戻る
			$("button_next").src    = "btn_next.png"; // 進む
		
		}
		
		resize_object();
	}


	// 最初のページを表示
	arrange_list_page("page_list");
	if ( first_page != undefined ){	// init の引数に、最初に表示するページが指定されていた場合
		change( String(first_page) );
	}
	else {
		var last_cookie = getCookie("Lastpage_" + Category);
		if ( last_cookie != ""){  // cookie に、最後に表示したページが残っていた場合。そこから始める
			change( last_cookie );
		}
		else{  // その他の場合。先頭のページから始める
			change( "0" );
		}
	}
	
	repaint_pagelist("page_list", undefined, Current);
}

function keypress_handle(e, k, shift, alt) {
	if ( k == Event.KEY_RETURN ){
		if ( Search_in ){
			check_search_form();
		} else {
			search_field.focus();
		}
	} else if ( k == Event.KEY_ESC ){
		close_all_menu("right_form");
		search_field.blur();
		
		if ( Music_status == "PLAY" ){
			button_mouseupdown('music_switch', '2px');
			setTimeout("button_mouseupdown('music_switch', '0px');", 130);
			music_stop();
		}
	} else if ( ( k == 33 || k == 34 ) && page_list.isOpen ){
		repaint_pagelist('page_list', k == 34 ? '+1' : '-1' );
	} else if ( k == 36 ){
		var target = shift ? "page_list" : "item_scratch";
		
		new Effect.Highlight("caller_" + target,  {startcolor:'#ffff00', endcolor:'#ffcc55',duration:0.2});
		$(target).toggle();
	} else {
		if ( k == Event.KEY_LEFT && !Search_in && !alt ){
			button_mouseupdown('button_prev', '1px');
			button_hover('button_prev', 'btn_back_a.png');
			change("-1");
			
			setTimeout("button_mouseupdown('button_prev', '0px', true); button_hover('button_prev', 'btn_back.png');", 130);
			Event.stop(e);
		}
		else if ( k == Event.KEY_RIGHT && !Search_in && !alt ){
			button_mouseupdown('button_next', '1px');
			button_hover('button_next', 'btn_next_a.png');
			change("+1");
			
			setTimeout("button_mouseupdown('button_next', '0px', true); button_hover('button_next', 'btn_next.png');", 130);
			Event.stop(e);
		}
	}
}

// ウィンドウサイズと、各コンポーネントのサイズを連動させる
function resize(){
	resize_object();
	kick_pagelist_arrange();
}

function resize_object(){
	var win = Get_body_size();

	scratch_mask.style.height = click_sheld.style.height = document.body.scrollHeight;
	scratch_mask.style.width  = click_sheld.style.width  = document.body.scrollWidth;

	item_scratch.style.left = ( - parseInt(win[0] - 729) / 2 + 40 ) + "px";

	var cont = contents_area.style;
	var mask = background_mask.style;
	var maskshadow  = background_mask_shadow.style;
	var linkcopier  = link_copier.style;

	var base_x = ( win[0] - 729 ) / 5;
	var base_y = ( win[1] - 229 ) / 10;
	base_y = base_y < 30 ? 30 : base_y;

	cont.left = ( base_x - 15 ) + "px";
	cont.top  = ( base_y - 80 ) + "px";

	mask.left = base_x + "px";
	mask.top  = base_y + "px";

	maskshadow.left = ( base_x + 10 ) + "px";
	maskshadow.top  = ( base_y + 10 ) + "px";
	
	linkcopier.right = ( win[0] - base_x - 670 ) + "px";
	linkcopier.top   = ( base_y + 20 ) + "px";

	var searchresult = search_result.style;
	var searchLeft = searchresult.left.replace(/\\w\\w\$/, "");

	if ( Number(searchLeft) + 230 > win[0] ){
		searchresult.left = (win[0] - 240) + "px";
	}
	search_result.orgLeft = win[0] - 240;

	var list_width = parseInt( -0.9 * win[0] + 738 );
	var list_size  = parseInt( win[0] * 0.8 );

	page_list.setStyle({ left: list_width + 'px', width: list_size + "px" });

}

function kick_pagelist_arrange(){
	// ページ一覧の再アレンジ
	// パフォーマンス低下を避けるため、最後のリサイズから 300ms 秒間、再度リサイズされなかった場合にのみキックされる。
	if ( Pagelist_arrange ){
		clearTimeout( Pagelist_arrange );
		Pagelist_arrange = undefined;
	}
	Pagelist_arrange = setTimeout("arrange_list_page('page_list'); repaint_pagelist('page_list', undefined, Current);",300);

}


// ======================================================================================

/* データスタック(id="data")にある HTML を解析し、各ページの内容を得る
   1) 各ページデータが括られているタグ名
   2) 　　　〃　　　　　　　　　　クラス名
   3) 各ページに付与する ID の接頭語
   4) 各ページデータの元データが存在する場所(オブジェクト) (指定しなければ、document 配下から探す)
   
   */
	function change_self_src(url){ this.src = url; };
	
	// ページ一覧のページを変更する
	// ページ一覧オブジェクト, 変更量(+/-) or 変更後ページ番号, 特定の文書のあるページに飛びたい場合、その文書のページ
	function change_list_page( o_pagelist, dest, content_page ){
		// 現在のページ値を読む
		var o_page_now   = $(o_pagelist).$("page_now"  );
		var o_page_total = $(o_pagelist).$("page_total");
		
		var page_now   = o_page_now.innerHTML   - 1;
		var page_total = o_page_total.innerHTML - 1;
		
		// 値を変更
		if ( content_page != undefined ){
			page_now = search_page( o_pagelist, content_page );
		} else if ( String(dest).match(/^[\+\-]/) ){
			page_now += Number(dest);
		} else {
			page_now = dest;
		}
		// 総計が1ページの場合、矢印エリア( arrow_ares )全体を消す
		if ( page_total == 0 ){
			$(o_pagelist).$("arrow_area").hide();
		} else {
			$(o_pagelist).$("arrow_area").show();
		}
		
		// 上限・下限チェック (矢印を消すため、境界値でも処理する)
		if ( page_now >= page_total ) {
			page_now = page_total;
			$(o_pagelist).$("arrow_next").hide();
		} else {
			$(o_pagelist).$("arrow_next").show();
		}
		if ( page_now <= 0 ) {
			page_now = 0;
			$(o_pagelist).$("arrow_back").hide();
		} else {
			$(o_pagelist).$("arrow_back").show();
		}

		// 書き換え
		o_page_now.innerHTML = page_now;

		return page_now;
	};
	function search_page( o_pagelist, content_page ) {
		var page
	};

	// ページ一覧アイコンのイベントハンドラ
	var Page_item_mouseOver = function(e){ this.style.backgroundColor = '#553'; };
	var Page_item_mouseOut  = function(e){ this.style.backgroundColor = '#223'; };
	var Page_item_click     = function(e){
		var i = this.id.replace(/page_list_/,"");
		change(i);
		page_list.close();
	};

	var accept_area_mouseover = function(e){
		 	e.getElementsByTagName("img")[0].src = 'closebox_red.gif';
		 	e.style.color = 'pink';
		};
	var accept_area_mouseout = function(e){
		 	e.getElementsByTagName("img")[0].src = 'closebox.gif';
		 	e.style.color = '#aaa';
		};
	var accept_area_click = function(e){
		 	page_list.toggle();
		};


function set_pagedata( tag, class_name, id_prefix, target_obj ){
	target_obj = target_obj ? $(target_obj).childNodes : document.childNodes;
	var target_len = target_obj.length;
	
	var result        = new Array();
	var page_count    = 0;
	var include_new   = false;
	
	var iconpaste_area = $("pagelist_iconarea");
		 iconpaste_area.innerHTML = "";
	
	var elems = new Array();
	for (var i = 0; i < target_len; i++){
		var elem = target_obj[i];
		if ( elem.className == class_name ){
			elems[page_count++] = elem;
		}
	}

	var page_num = elems.length;
	for(var i = 0; i < page_num; i++){
		var elem = elems[i];
		
		var id_str = elem.id = id_prefix + i;

		var page_title = title_str = elem.getElementsByTagName("h1")[0].innerHTML;
		if ( title_str.length > Pagelist_title_len ){
			title_str = title_str.substring(Pagelist_title_len,0) + "...";
		}
		
		var first_img;
		if ( elem.getElementsByTagName("img")[0] ){
			first_img = elem.getElementsByTagName("img")[0].src;
		} else if ( elem.getElementsByTagName("object")[0] ){
			first_img = "/icon_movie.png";
		} else {
			first_img = "/icon_nophoto.png";
		}

		var div = document.createElement('div');
		div.className = "pagelist_item";
		div.id        = "page_list_" + i;
		div.title     = page_title;
		
		div.onmouseover = Page_item_mouseOver.bindAsEventListener(div);
		div.onmouseout  = Page_item_mouseOut.bindAsEventListener(div);
		div.onclick     = Page_item_click.bindAsEventListener(div);
	
		div.innerHTML = "<div class='icon_head'><span class='icon_no'>" + (i+1) + "</span><span class='icon_title'>" + title_str + "</span></div><img src='" + first_img + "' class='first_img'>";
		
		iconpaste_area.appendChild(div);

			// 真面目に調べるとすごく遅いので省略…
			//	var w = div.style.width;
			//	var h = div.style.height;
			//	w = w.replace(/[a-z]+$/, "");
			//	h = h.replace(/[a-z]+$/, "");
		page_list.pages[page_list.pages.length] = ( [155, 112] );

		// 各ページの 音楽・背景矩形スタイル取得
		// 音楽
		Music_index.push( elem.getAttributeNode("x_bgm") ? elem.getAttributeNode("x_bgm").value : 1 );
		
		// 背景矩形スタイル
		//for ( j in View ){
		//	if ( elem.style[j] ){
		//		View[j][i] = elem.style[j];
		//	}
		//}

		result[result.length] = id_str;
	}

	var go_top = document.createElement("div");
	var inc_new = '<span style="float: right; padding-top: 7px;" class="pseudo_a" onClick="$(\'page_list\').toggle(); search(\'category:' + Category + ' new\')" onMouseover="this.style.backgroundColor=\'#aa3\'; this.style.color=\'#833\';" onMouseout="this.style.backgroundColor=\'transparent\'; this.style.color=\'#ff9\';" title="このカテゴリに最近追加された写真を、一覧表示します。">最近追加された写真を検索...</span>';
	
	go_top.className = "more";
	go_top.innerHTML = '<div class="more_left" style="text-align: left">' + inc_new + '<a href="/" title="トップページに戻ります。"><img src="go_back.gif" alt="←"> トップページに戻る</a></div>';

	$("pagelist_foot").innerHTML = "";
	$("pagelist_foot").appendChild( go_top );

	
	return result;
}

// ページ一覧を、ウィンドウサイズにあわせて複数ページに分割する。
function arrange_list_page( id ){
	var win        = Get_body_size();
	var list_size  = new Array( parseInt(win[0]*0.8), parseInt(win[1]*0.8) );
	var avail      = new Array( list_size[0] - Pagelist_margin[0] ,list_size[1] - Pagelist_margin[1] );

	if ( avail[0] < Pagelist_min[0] ){
		throw("ウィンドウサイズ(横幅)が小さすぎるため、ページ一覧を開けません。"
			+ "(必要ピクセル数: " + Pagelist_min[0] + " / 現在のピクセル数: " + list_size[0] + ")"
			+ "ウィンドウをリサイズしてから、もう一度お試し下さい。");
	}
	if ( avail[1] < Pagelist_min[1] ){
		throw("ウィンドウサイズ(縦幅)が小さすぎるため、ページ一覧を開けません。"
			+ "(必要ピクセル数: " + Pagelist_min[1] + " / 現在のピクセル数: " + list_size[1] + ")"
			+ "ウィンドウをリサイズしてから、もう一度お試し下さい。");
	}

	var pagelist_range = new Array();
	var range_s        = 0;
	var current        = new Array(0,0);
	
	var pages    = $(id).pages;
	var page_len = pages.length;
	
	for ( var i = 0; i < page_len ; i++ ){
		var next_w = pages[i][0];
		var next_h = pages[i][1];
		
		if (  Number(next_w) + current[0] > avail[0] ){
			current[0] = 0;
			if ( Number(next_h) + current[1] > avail[1] ){
				pagelist_range.push( [range_s, i-1] );
				range_s = i;
				current[1] = 0;
			} else {
				current[1] += Number(next_h);
			}
		}
		current[0] += Number(next_w);
		pages[i][2] = pagelist_range.length;
	}
	if ( range_s != Page_Max ){
		pagelist_range.push( [range_s, Page_Max] );
	} else{
		pagelist_range.push( [Page_Max, Page_Max] );
	}

	$(id).groups = pagelist_range;
}

function inact_pagelist_range( current, max ){
	if ( current <= 0 ){
		$("back_pl_img").src = "go_back_g.gif";
	} else {
		$("back_pl_img").src = "go_back.gif";
	}
	
	if ( current >= max ){
		$("next_pl_img").src = "go_next_g.gif";
	} else {
		$("next_pl_img").src = "go_next.gif";
	}
}

function rewrite_groups_str(obj){
	var indicate_str = "";
	
	for ( var i = 0; i < obj.groups.length; i++ ){
		var isMe, myComment;
		if ( i == obj.currentGroup ){
			myComment = "現在表示中"; isMe = "is_me"; 
		} else {
			var ft = obj.groups[i]; isMe = "";
			myComment = (ft[0]+1) + " ～ " + (ft[1]+1) + "ページを表示";
		}

		indicate_str += "<span class='pagelist_indicate " + isMe + "'"
		 + " onMouseout='this.style.color=\"\"; this.style.backgroundColor=\"transparent\"'"
		 + " onMouseover='this.style.color=\"#000\"; this.style.backgroundColor=\"#ff0\"'"
		 + " onClick='repaint_pagelist(\"page_list\", " + i + ")' title='" + myComment + "'>" + (i+1) + "</span>";
	}
	$("pagelist_indicate").innerHTML = indicate_str;
}

function repaint_pagelist( id, group_op, page ){
	var page_list    = $(id);
	
	var currentGroup = page_list.currentGroup;

	if ( group_op != undefined ){
		if ( String(group_op).match(/^[\+\-]/) ){
			currentGroup += Number( group_op );
		} else {
			currentGroup = Number( group_op );
		}
		
		if ( currentGroup < 0 ){
			currentGroup = 0;
		} else if ( currentGroup >= page_list.groups.length ){
			currentGroup = page_list.groups.length - 1;
		}
	}
	
	
	if ( page ){
		currentGroup = page_list.pages[page][2];
	}
	
	inact_pagelist_range( currentGroup, page_list.groups.length - 1 );
	var pagelist_len = page_list.groups.length;
	for ( var i = 0; i < pagelist_len; i++ ){
		var style_val = currentGroup == i ? "inline" : "none";
		var f = page_list.groups[i][0];
		var t = page_list.groups[i][1];
			//alert(f + "," + t);
		for ( var j = f; j <= t; j++ ){
			document.getElementById("page_list_" + j).style.display = style_val;
		}
	}
	toggle_pagelist_navi( page_list.groups.length );
	
	page_list.currentGroup = currentGroup;
	rewrite_groups_str( page_list );
}


// ======================================================================================

function change( seq ){
	var cur = Current;
	
	document.getElementById("page_list_" + Current).style.fontWeight = "normal";
	document.getElementById("page_list_" + Current).style.color = "";
	var previous_group = page_list.currentGroup;

	if ( String(seq).match(/^[\+\-]/) ){
		Current += Number( seq );
	} else{
		Current = Number( seq );
	}
	
	pageover_check();
	repaint_background_mask(Category, Current);
	
	contents_area.innerHTML = document.getElementById( Page_Data[ Current ] ).innerHTML;

	document.getElementById("page_list_" + Current ).style.fontWeight = "bold";
	document.getElementById("page_list_" + Current ).style.color = "#f52";
	
	if ( previous_group != page_list.pages[Current][2] ){
		repaint_pagelist( "page_list", undefined , Current );
	} else {
		rewrite_groups_str( page_list );
	}

	if ( page_list.isOpen ){
		blink_pagelist("page_list_" + Current);
	}
	
	page_number.innerHTML = ( Current + 1 );
	link_copier_a.href    = "photo.cgi?c=" + Category + "&p=" + Current;

	setCookie("Lastpage_" + Category, Current);

	if ( Playable && Music_status == "PLAY" && Music_auto == 1 ){
		var next_music = music_uri( Music_index[ Current ] );
		if ( Music_now != next_music ){
			Music_now = next_music;
			music_fadeout( 0.1, "AUTO" );
		}
	}
}

// ======================================================================================

function load_page( page ){
	
}

// ======================================================================================

var Button_is_hidden;
function pageover_check(){
	var cur = Current;
	
	/* ### overflow check ### */
	if ( cur <= Page_Min ){   // 最初のページの場合
		cur = Page_Min;

		if ( Button_is_hidden == "button_next" ){ // 既に[次へ]が消えている場合、回復させる
			pageover_check_recover( Button_is_hidden );
		}
		button_hover( "button_prev", "btn_back_g.png" );
		button_prev_label.style.color = "#8ac";
		button_prev_label.title       = Message.title_first;
		Button_is_hidden = "button_prev";
	}
	else if ( cur >= Page_Max ) {  // 最後のページの場合
		cur = Page_Max;

		if ( Button_is_hidden == "button_prev" ){ // 既に[戻る]が消えている場合、回復させる
			pageover_check_recover( Button_is_hidden );
		}

		button_hover( "button_next", "btn_next_g.png" );
		button_next_label.style.color = "#8ac";
		button_next_label.title       = Message.title_last;
		Button_is_hidden = "button_next";
	}
	else if ( Button_is_hidden ){ // その他の(最初でも最後でもない)場合、消えているものを回復させる
		pageover_check_recover( Button_is_hidden );
	}
	
	Current = cur;
}
function pageover_check_recover( id ){ // 与えられた id の矢印を回復させるルーチン
	if ( Button_is_hidden == "button_next" ){
	//	$(button_next).src = "/btn_next.png";
		button_next_label.style.color="#edf";
		button_next_label.title = Message.title_next;
		button_hover( "button_next", "btn_next.png", 1 );
	}
	else{
	//	$(button_prev).src = "/btn_back.png";
		button_prev_label.style.color="#edf";
		button_prev_label.title = Message.title_back;
		button_hover( "button_prev", "btn_back.png", 1 );
	}
	Button_is_hidden = undefined;
}

// ======================================================================================

// 進む・戻るボタンの hover 処理
function button_hover(id, newsrc, flag){
	var obj = document.getElementById(id);
	var checker = Is_ie ? obj.style.filter : obj.src;
	if (
		(  checker.match(/_g\.png/) && flag ) ||
		( !checker.match(/_g\.png/) )
	){
		png( id, newsrc );
	}
}
// 進む・戻るボタンの mousedown/up 処理
function button_mouseupdown(id, diff, flag){
	var obj = document.getElementById(id);
	var checker = Is_ie ? obj.style.filter : obj.src;
	if (
		(  checker.match(/_g\.png/) && flag ) ||
		( !checker.match(/_g\.png/) )
	){
		obj.style.top = diff;
	}
}// ボタンの mousedown/up 処理
function button_clickcolor(obj, color){
	if ( obj ){
		setTimeout("document.getElementById('" + obj.id + "').style.backgroundColor = '" + obj.style.backgroundColor + "';", 130);
		obj.style.backgroundColor = color;
	}
}
// 本文背後の黒い矩形をリサイズ & 再描画する
function repaint_background_mask( category, page ){
	var mask         = background_mask.style;
	var mask_shadow  = background_mask_shadow.style; //alert(background_mask_shadow.style.width);
	var mask_scratch = scratch.style;
	
	if ( Is_ie ){
		var opacity = valid_view( "-k-mask-alpha", category, page );
		opacity *= 100;
		mask.filter = "Alpha(opacity=" + opacity + ")";
	}
	else {
		mask.MozOpacity = valid_view( "-k-mask-alpha", category, page  );
	}
	mask.width           = valid_view( "-k-mask-width-max",  category, page );
	mask.height          = valid_view( "-k-mask-height-max", category, page );
	mask_shadow.width    = valid_view( "-k-mask-width-max",  category, page );
	mask_shadow.height   = valid_view( "-k-mask-height-max", category, page );
	mask_scratch.width   = mask.width;
}

// ======================================================================================

// 現在表示中のページ・カテゴリにおける有効なスタイルを返す
function valid_view( property, category, page  ){
	var obj = View[property];
	return  obj[page] || obj[category] || obj["GLOBAL"];
}

// ======================================================================================

/* ========= Dynamic category translation ========= */

var Dynamic_trans_id;
function dynamic_trans( id, jp, page ){
	contents_area.innerHTML = "<div class='loading'><div style='padding: 0px 15px 7px 0px;'><img src='ajax-loader.gif' style='margin-right: 0.7em;'><span style='font-size: 120%; font-family: HGPｺﾞｼｯｸE; color: #dda'><span id='dynamic_trans_indicator'>" + jp
	 + '</span></span></div>'
	 + '<img src="category_photo/' + id + '.jpg" style="z-index: 6; position: absolute;" id="dynamic_load_icon">'
	 + '<img src="category_photo/' + id + '.jpg" style="z-index: 5; visibility: hidden"  id="dynamic_load_icon_l">'
	 + '</div>';

	Effect.Puff( "dynamic_load_icon", {
		duration:0.3,
		from: 1,
		to: 0.12,
		afterFinish: function(){
			if ( $("dynamic_load_icon_l") ){
				$("dynamic_load_icon_l").style.visibility = 'visible';
			}
		}
	} );

	Dynamic_trans_id = setTimeout("dynamic_trans_exec('" + id + "', '" + jp + "', " + page + ")", 300);
}

function dynamic_trans_exec( id, jp, page ){
	var style = new Array();
	var body;

	var ajax_data = get_http("category.cgi?c=" + id);

	if ( ajax_data[0] != 200 ){
		alert( "読込みに失敗しました。\n" + ajax_data[1] );
		change( Current );
		return;
	}
	
	var page_data = ajax_data[1].split("==BOUND==");


	$("dynamic_trans_indicator").innerHTML = "準備中...";
	document.getElementById('icon_loading_' + id).src = 'space.gif';

	// ウィンドウタイトルを更新
	document.title = Category_jp[id];
	category_title.innerHTML = Category_jp[id];
	
	// category.cgi の出力した Javascript コードを実行。配列 x_arg がエクスポートされる
	eval(page_data[0]);
	
	// ページ内のデータスタックに、Ajax で読んだデータ本文を書き込む
	data.innerHTML = page_data[1];

	// Ajax で読んだデータ中のスタイルを読み込む
	if ( x_arg["background-image"] ){
		var dummy = x_arg["background-image"].match(/url\((.*?)\)/);
		var uri = RegExp.$1; 
		if ( uri ){
			change_image("background_image", uri );
		}
	}
	
	for ( i in View ){
		if ( x_arg[i] ){
			View[i][id] = x_arg[i];
		}
	}

	// 最初のページをロード
	var current = $("searchresult_" + Category);
	if ( current ){
		current.style.backgroundImage = "url(bggreen.gif)";
		current.title = "分類: " + Category_jp[Category] + " に切り替えます。";
	}
	Category = id;
	var newcategory = $("searchresult_" + id);
	if ( newcategory ){
		newcategory.style.backgroundImage = "url(bgorange.gif)";
		newcategory.title = "現在表示中のカテゴリです。";
	}
	
	if ( page ){
		setCookie("Lastpage_" + id, page);
	}
	Current = page || 0;
	init(Current, true);
}


// ======================================================================================

function change_image( id, next_uri ){
	var img = $( id );
	
	if ( document.all && img.filters ){
		img.filters[0].Apply();
	}
	
	if ( img.src ){
		img.src = next_uri;
	}
	
	if ( document.all && img.filters ){
		img.filters[0].Play();
	}
}

// ======================================================================================

/* ========= Get remote files ========= */

function get_http( url ){
	var req = createXMLHttpRequest();
	var res = new Array();

	req.open("GET", url, false);
	req.send(null);

	res[0] = req.status;
	res[1] = res[0] == 200 ? req.responseText : req.status +" "+ req.statusText;
	
	return res;
}

function createXMLHttpRequest() {
	return this.XMLHttpRequest ? 
	new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}


// ======================================================================================

/* ========= Search box ============== */

	/* 検索ボックスにフォーカスが当たった/はずれた時の処理 */
function search_click( obj ){
	if ( obj.value == '検索'){
		obj.value = "";
		obj.style.color = "black";
		$("search_again").style.visibility = "visible";
	} else {
		obj.select();
	}
	
	Search_in=1;
	Search_prev = obj.value;
}
function search_blur(obj){
	if ( obj.value == ''){
		obj.value = "検索";
		obj.style.color = "gray";
		$("search_again").style.visibility = "hidden";
	};
	Search_in = 0;
}

// ======================================================================================

	/* 外部ファイルに切り離すに当たって: Category_all */
var Found_html;
function search( keywords ){
	$("search_result").open();
	$("search_field").focus();
	
	var search_indicator = $("search_indicator");
	var result_table     = $("result_table");
	
	result_table.innerHTML = "";
	search_indicator.innerHTML = "<div style='cursor: move;color: #ccc;height: 24px; text-align: right;'"
		+ " onMouseover='this.style.backgroundColor=\"#48c\"'"
		+ " onMouseout ='this.style.backgroundColor=\"\"'"
		+ " ><span style='float: left'><img src='ajax-loader.gif' alt=''>検索中... </span><span style='position: relative: left: -16px;cursor: pointer; font-size: 80%; vertical-align: bottom'"
		+ " onMouseover='$(\"search_stop\").src=\"closebox_red.gif\"; this.style.color=\"pink\"'"
		+ " onMouseout ='$(\"search_stop\").src=\"closebox.gif\"; this.style.color=\"#ccc\"'"
		+ " onMousedown='this.style.marginTop=\"1px\";' title='検索を中断します' "
		+ " onClick='$(\"search_result\").close();'"
		+ " >閉じる<img src='closebox.gif' "
		+ " id='search_stop'></span></div>";

	setTimeout("search_remote('" + keywords + "')", 300);
}

// ======================================================================================

function search_remote( keywords ){
	var search_indicator = $("search_indicator");
	var result_table     = $("result_table");
	result_table.hide();

	var res = new Array();
	res = get_http( "/search_category.cgi?k=" + encodeURL(keywords) );

	search_indicator.innerHTML = "<div style='cursor: move;color: #ccc;height: 24px; text-align: right;'"
		+ " onMouseover='this.style.backgroundColor=\"#48c\"'"
		+ " onMouseout ='this.style.backgroundColor=\"\"'"
		+ " ><span style='cursor: pointer; position: relative; top: 10px; left: -16px; font-size: 80%; vertical-align: bottom'"
		+ " onMouseover='$(\"search_stop\").src=\"closebox_red.gif\"; this.style.color=\"pink\"'"
		+ " onMouseout ='$(\"search_stop\").src=\"closebox.gif\"; this.style.color=\"#ccc\"'"
		+ " onMousedown='this.style.marginTop=\"1px\";' title='検索結果を閉じます' "
		+ " onClick='$(\"search_result\").close();'"
		+ " >閉じる<img src='closebox.gif' "
		+ " id='search_stop'></span></div>";

	result_table.innerHTML = res[0] ? res[1] : "検索サーバに接続できませんでした。申し訳ありません。";

	if ( $("search_field").value == "" ){
		$("search_field").blur();
	}
	
	var current = $("searchresult_" + Category);
	if ( current ){
		current.style.backgroundImage = "url(bgorange.gif)";
		current.title = "現在表示中のカテゴリです。";
	}
	new Effect.SlideDown(result_table, {duration:.3, fps:30});
}


// ======================================================================================

var Search_prev;
var Search_in;
function check_search_form( k ) {
	if( Search_in == 1 ){
		if ( $("search_field").value.match(/^[\s　]*$/) ){
			$("search_field").blur();
		} else {
			exec_search();
		}
	}
}
function exec_search (){
	search( $("search_field").value );
	$("search_field").blur();
}

// ======================================================================================

var Blink_id;
function blink_pagelist( id ){
	if ( Blink_id ){
		clearTimeout(Blink_id);
		Blink_id = undefined;
	}

	setTimeout('new Effect.Highlight("' + id + '", {startcolor:"#999933", endcolor:"#222233",duration:1.8})', 1);
	if ( $("page_list").isOpen ){
		Blink_id = setTimeout('blink_pagelist("page_list_' + Current + '")', 1800);
	}
}

function toggle_pagelist_navi(range, force){
	var navi = $("pagelist_navi");
	if ( range == 1 ){
		navi.style.visibility = "hidden";
	} else {
		if ( force || $("page_list").isOpen ){
			navi.style.visibility = "visible";
		}
	}
}

function close_all_menu( parent ){
	$(parent).member.each( function(obj){ obj.close(); } );
}

// ###################### Load PNG image 
function png(obj, src){
	if (typeof obj == 'string'){
		obj = document.getElementById(obj);
	}

	if ( Is_ie ) {
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "')";
	} else {
		obj.src = src;
	}
}


// ======================================================================================
// ページの上下スクロールに、ツールバーを追随させる
function follow_scroll(id){
	if ( ! Is_ie ){
		return; // Gecko は戻る
	}
	var current_scrolltop = document.body.scrollTop;
	var delta_scrolltop   = current_scrolltop - Previos_scrolltop;

	var toppx = String($(id).style.top);
	toppx = Number( toppx.substring(0, toppx.indexOf("p")) );

	$(id).style.top = String( toppx + delta_scrolltop) + "px";
	Previos_scrolltop = current_scrolltop;
}

// ======================================================================================

function addRule(rule){
	if( document.styleSheets && document.styleSheets.length ){
		var a   = document.styleSheets[0];
		var arr = rule.replace(/}.*/,'').split('{');
		var arr2;
		var i;

		if( a.insertRule ){
			a.insertRule( rule, 0 );
		}
		else if( a.addRule ){
			arr2 = arr[0].split( /,/ );
			for( i=0; i < arr2.length; i++ ){
				a.addRule( arr2[i], arr[1] );
			}
		}
	}
}

// ======================================================================================

function mod_class_style( class_name, item, val ){ 
	if ( Is_ie ){
		document.styleSheets[0].addRule( class_name, item + ":" + val );
	}
	else{
		var sheet = $(style_main).sheet;
		sheet.insertRule( class_name + " { " + item + ": " + val + "; }", sheet.length);
	}
}


function deselect() {
	if (document.selection){
		document.selection.empty();
	} else if (window.getSelection){
		window.getSelection().removeAllRanges();
	}
}

// ================================================== 音楽再生機能
var Music_status = "STOP";
var Music_auto   = 1;

// 音楽再生機能の初期化
function init_player ( music_track, music_switch ){
	Player = $("player");
	
	if ( Player.settings ){
		Music_selector   = $(music_track);
		Music_controller = $(music_switch);

		Music_default_volume = Player.settings.volume; // WMP の現在の(ページロード時の)音量を、デフォルト音量とする
		Music_current_volume = Music_default_volume;
		
		return true;
	}
	else{
		return false;
	}
}

function music_changetrack( track ){
	if ( !Playable ){
		return;
	}
	
	if ( track == "STOP" ){
		Music_auto = 0;
		music_stop();
	}
	else if ( track == "AUTO" ){
		Music_auto = 1;
		music_start( track );
	}
	else{
		Music_auto = 0;
		music_start( track );
	}
}

function music_button( ){
	if ( !Playable ){
		return;
	}
	/* when the button is clicked */
	if ( Music_status == "PLAY" ){
		music_stop();
		Music_selector.selectedIndex = 0;
	}
	else if ( Music_status == "STOP" ){
		var track  = Music_selector.options[Music_selector.selectedIndex].value;
		if ( track == "STOP" ){
			Music_selector.selectedIndex = 1;
			track = Music_selector.options[Music_selector.selectedIndex].value;
		}
		
		music_start( track );
		
		return;
	}
	else{
	}
	
}

function music_uri( id ){
	var uri;
	var auto_index = parseInt( id );

	if ( auto_index >= 0 ){
		if  ( Music_selector.options[ auto_index + 1 ] ){
			uri = Music_selector.options[ auto_index + 1 ].value;
		}
	}
	else{
		uri = "";
	}
	
	return uri;
}

function music_start( uri ){
	if ( !Playable ){
		return;
	}
	
	if ( uri == "AUTO" ){
		Music_auto = 1;
		uri = music_uri( Music_index[ Current ] );
	}
	Music_status = "PLAY";

	Player.URL = uri;
	if ( uri ){
		Music_now = uri;
		Player.controls.play();
		setTimeout("music_waitloading()", Music_fade_interval);
	}

	setTimeout("Music_controller.src   = 'ajax-loader1.gif'", 20);
	$("music_switch").title = $("music_sw_area").title = "音楽を読込み中です。(クリックで中止)";
}

function music_stop(){
	if ( !Playable || Music_status != "PLAY" ){
		return;
	}
	Player.controls.stop();

	Music_status         = "STOP";
	setTimeout('Music_controller.src = "music_play.gif"', 10); // setTimeout is for IE bug
	$("music_switch").title = $("music_sw_area").title =  "音楽を再生します。";
}

function music_waitloading( ){
	if ( !Playable ){
		return;
	}
	var code = Player.openState;
	if ( code == 13 ){
		Music_controller.src = "music_stop.gif";
		$("music_switch").title = $("music_sw_area").title =  "音楽を停止します。";
	}
	else{
		setTimeout("music_waitloading()", Music_fade_interval);
	}
}

function music_fadeout( width, next ){
	if ( !Playable ){
		return;
	}
	if ( Music_current_volume > 0 ){
		var delta = parseInt( Music_default_volume * width );
		Music_current_volume -= delta;
		if ( Music_current_volume < 0 ){
			Music_current_volume = 0;
		}
		
		Player.settings.volume = Music_current_volume;
		setTimeout("music_fadeout(" + width + ", '" + next + "')", Music_fade_interval);
		return;
	}
	
	music_stop();
	Player.settings.volume = Music_default_volume;
	Music_current_volume   = Music_default_volume;
	music_start( next );
}



