// Require prototype.js
// Require cookiemanager.js
// Require functions.js
// Require wsse.js
// Require Condition.js
// Require Landmark.js
// Require User.js
// Require Topic.js
// Require LayerDialog.js
// Require WeatherType.js
// Require Banner.js

var cookiemanager;
var curUser = null;
var curCouponList = null;
var curBirthdayCouponList = null;
var curJoinCouponList = null;
var calenderTopicList = null;
var start_step = 0;
var todaysTopic = {};
var dialogWin;
var popupWin = {};
var headlineTab = {};
var topicheadline_viewNum = 14;
var topicheadline_viewPage = {};
var topicheadline_viewIndex = {};
var topicheadline_Total = {};

var recommendTab = {};
var topicrecommend_viewNum = 4;
var topicrecommend_viewPage = {};
var topicrecommend_viewIndex = {};
var topicrecommend_Total = {};
var hasTopicRecommend = false;

var r500m_userlogin = "0";
var r500m_userid = "0";
var r500m_user_class = "";
var r500m_nickname = "";
var r500m_userscope = "";
var r500m_address = "";
var r500m_latitude = "";
var r500m_longitude = "";
var r500m_spotname = "";
var r500m_spotid = "";

function toppage_init() { 

	var userid='0';
	start_step = 0;

//	$(document.body).startWaiting('bigWaiting');

	//ウエイト表示
	$('wait_area').style.display = "";
	$('wait_area').startWaiting('bigWaiting');

	var elm;
	if ((elm = $('r500m_userlogin'))) {
		r500m_userlogin = elm.value;
	}
	if ((elm = $('r500m_userid'))) {
		r500m_userid = elm.value;
	}
	if ((elm = $('r500m_user_class'))) {
		r500m_user_class = elm.value;
	}
	if ((elm = $('r500m_nickname'))) {
		r500m_nickname = elm.value;
	}
	if ((elm = $('r500m_userscope'))) {
		r500m_userscope = elm.value;
	}
	if ((elm = $('r500m_address'))) {
		r500m_address = elm.value;
	}
	if ((elm = $('r500m_latitude'))) {
		r500m_latitude = elm.value;
	}
	if ((elm = $('r500m_longitude'))) {
		r500m_longitude = elm.value;
	}
	if ((elm = $('r500m_spotname'))) {
		r500m_spotname = elm.value;
	}
	if ((elm = $('r500m_spotid'))) {
		r500m_spotid = elm.value;
	}

	if (r500m_spotid) {
		var curLandmark = readLandmark(r500m_spotid, '', '');

		if (curLandmark) {

			//名称
			var name = '';
			if ( elm = curLandmark.getName() ) {
				name = elm;
			}

			//住所
			var add = '';
			if ( elm = curLandmark.getAdd1() ) {
				add = elm;
			}
			if ( elm = curLandmark.getAdd2() ) {
				add += elm;
			}

			//緯度・経度
			var lat = '';
			if ( elm = curLandmark.getLatitude() ) {
				lat = elm;
			}
			var lon = '';
			if ( elm = curLandmark.getLongitude() ) {
				lon = elm;
			}

//			if ((name) && (add) && (lat) && (lon)) {
			if ((name) && (lat) && (lon)) {
				r500m_spotname = name;
				r500m_address = add;
				r500m_latitude = lat;
				r500m_longitude = lon;
			}
		}

	}

	if ((!r500m_userlogin) || (r500m_userlogin == "0")) {
		var cookiemanager = new CookieManager({shelfLife:30});
		var uid = cookiemanager.getCookie("r500m_userid");
		if (uid) {
			$('userid').value = uid;
		}
	}

	//エラーダイアログ作成
	init_error_dialog();

	//タブ
	maintabsetup();
	recommendtabsetup();

	//日時セット
	update_calendar();
	update_todays_date();

	//初期ヘッダー読み込み
	init_loginheader_contents(r500m_userid);

	//トップ部表示
	document.getElementById('header').style.display = "";

	//読み込み/表示
	setTimeout("toppage_start()", 100);
//	toppage_start();
}

/*
 * 読み込み/表示
 */
function toppage_start() { 

	//トップ部
	set_login_contents();

	//記事読み込み
	update_contents_bystep();

	//WAITタイムアウト
	setTimeout("show_contents()", 60000 * 3);
}

function show_contents() {

	//WAIT解除
	$('wait_area').stopWaiting();
	$('wait_area').style.display = "none";

	//ミドル部
	document.getElementById('contents').style.display = "";

	//ボトム部
	document.getElementById('banner_block').style.display = "";
	document.getElementById('globalnavigation').style.display = "";
	document.getElementById('footer').style.display = "";
}


/* =====================================
 *
 * ログイン・ログアウト
 *
 */

function logincheck() {

	var userid = $('userid').value;
	var userpassword = $('userpassword').value;

	if ( (!userid) || (!userpassword) ) {
		show_error_message('ログインエラー', 'ユーザーＩＤおよびパスワードを入力してください。', 400, 180, 200);
		return false;
	}

	var cookiemanager = new CookieManager({shelfLife:30});
	//cookiemanager.clearCookie("r500m_userid");
	cookiemanager.setCookie("r500m_userid", userid);

	return true;
}

function logoutcheck() {
	if (r500m_userid != "0") {
		var cookiemanager = new CookieManager({shelfLife:30});
		cookiemanager.setCookie("r500m_userid", r500m_userid);
	}
	return true;
}

function getbaseparam() {

	var ret = "";

	if (r500m_spotid) {
		//if ((r500m_address) && (r500m_latitude) && (r500m_longitude)) {
		if ((r500m_latitude) && (r500m_longitude)) {
			ret = "address=" + r500m_address + "&latitude=" + r500m_latitude + "&longitude=" + r500m_longitude;
		}
	}

	else if (r500m_spotname) {
		ret = "landmarkname=" + r500m_spotname;
	}

	else if ((r500m_address) && (r500m_latitude) && (r500m_longitude)) {
		ret = "address=" + r500m_address + "&latitude=" + r500m_latitude + "&longitude=" + r500m_longitude;
	}
	else if (r500m_address) {
		ret = "address=" + r500m_address;
	}
	else if ((r500m_latitude) && (r500m_longitude)) {
		ret = "latitude=" + r500m_latitude + "&longitude=" + r500m_longitude;
	}
	else if (r500m_userid) {
		ret = "user=" + r500m_userid;
	}
	//ログアウト状態
	else {
		ret = "user=0";
	}

	if (r500m_userscope) {
		ret += "&r=" + r500m_userscope;
	}

//	alert(ret);

	return ret;
}


/* =====================================
 *
 * トップ部
 *
 */
function ssl_host() {
       var ssl_host = location.host;
       if (ssl_host == "www.r500m.com") {
               ssl_host = "r500m.com";
       }
       return ssl_host;
}

function set_login_contents() { 

	//枠ボタン部

	//ログイン状態
	if ((r500m_userlogin) && (r500m_userlogin == "1")) {
		$('login_head').style.display = "block";
		$('logout_head').style.display = "none";
	}
	//ログアウト状態
	else {
		$('login_head').style.display = "none";
		$('logout_head').style.display = "block";
	}

	//メッセージ部
	var url = "https://" + ssl_host() + "/useredit.php?edit=1";
	var scope = "500";

	//検索半径
	if (r500m_userscope) {
		scope = r500m_userscope;
	}

	//スポットID指定
	if ((r500m_spotid) && (r500m_spotname)) {
		$('msg_user').innerHTML = r500m_spotname + "の半径" + scope + "mをサポートします";
	}

	//スポット名指定
	else if (r500m_spotname) {
		$('msg_user').innerHTML = r500m_spotname + "の半径" + scope + "mをサポートします";
	}

	//住所指定
	else if (r500m_address) {
		$('msg_user').innerHTML = toHankakuAddress(r500m_address) + "</ br>を中心に半径" + scope + "mをサポートします";
	}

	//緯度経度指定
	else if ((r500m_latitude) && (r500m_longitude)) {
		$('msg_user').innerHTML = "緯度：" + r500m_latitude + " 経度：" + r500m_longitude + "</ br>を中心に半径" + scope + "mをサポートします";
	}

	//ログイン状態
	else if ((r500m_userlogin) && (r500m_userlogin == "1")) {
		$('login_head').style.display = "block";
		$('logout_head').style.display = "none";

		$('msg_user').innerHTML = r500m_nickname + "さんの<a href=\"" + url + "\" >半径" + scope + "m</a>をサポートします";
	}
	//ログアウト状態
	else {
		$('login_head').style.display = "none";
		$('logout_head').style.display = "block";
		$('msg_user').innerHTML = "目黒・上大崎の半径" + scope + "mをサポートします";
	}

}


/* =====================================
 *
 * 初期化時のデータ読み込み
 *
 */
function init_loginheader_contents(userid) { 

	//クーポン取得
	clear_coupon();
	if ((r500m_userlogin) && (r500m_userlogin == "1")) {
		read_coupon();
	}


	//ごみ/天気記事の取得
	var catlist= "{" +
		"天気:今日の天気:0:1," +
		"ごみ収集日::0:1" +
		"}";

	var list = readTopicList(true, getbaseparam(), catlist, false, null);
	if (list) {
		topic_print(list);
	}
}

function update_contents_bystep() { 

	switch(start_step) {
	case 0:
		start_step++;

		//記事クリア
//		topic_clear();

		//記事取得
		topic_init(r500m_userid);

	 	//交通情報の取得
		traffic_update();

		//Pickup取得
		update_pickup();

	 	//バナー下の更新
		banner_bottom_init();
//		banner_bottom_update();
		break;

	case 1:
		start_step++;

		//ミドル以下表示
		show_contents();

		//スポット読み込み
//		landmark_init(r500m_userid);

        update_contents_bystep();

		break;

	case 2:
		start_step++;

		//トップライン開始
		clear_topline();
		init_topline();
		break;

	}

}


/* =====================================
 *
 * 記事更新
 *
 */
function topic_updateCB(list) {
	if (list) {
		topic_print(list);
	}
}

function topic_update() {

	//記事の取得(今日は)
	var catlist= "{" +
		"今日は::0:4" +
	"}";

	readTopicList(true, getbaseparam(), catlist, false, topic_updateCB);

	//記事の取得
	main_topic_update(r500m_userid, 'ニュース', false);
	main_topic_update(r500m_userid, '買い物|その他', false);
	main_topic_update(r500m_userid, '食事', false);
	main_topic_update(r500m_userid, 'コミュニティ', false);
	main_topic_update(r500m_userid, '定期休業', false);
	//main_topic_update(r500m_userid, 'ブログ', false);

	//記事の取得(おすすめ)
	recommend_update(r500m_userid, '買い物', false);
	recommend_update(r500m_userid, 'ランチ', false);
	recommend_update(r500m_userid, 'ディナー等', false);


	setTimeout("topic_update()", 60000 * 60);
//	setTimeout("topic_update()", 60000 * 1);
}


/*
 * 記事初期読み込み
 */
function topic_initCB(list) {
	topic_updateCB(list);
	update_contents_bystep();
}

function topic_init(userid) {

	//記事の取得
	main_topic_update(userid, 'ニュース', true);
	maintabset(0);
	main_topic_update(userid, '買い物|その他', true);
	main_topic_update(userid, '食事', true);
	main_topic_update(userid, 'コミュニティ', true);
	main_topic_update(userid, '定期休業', true);
	main_topic_update(userid, 'ブログ', true);
	main_topic_update(userid, 'Web更新', true);

	//おすすめ
	var numofShopping = recommend_update(userid, '買い物', true);
	var numofLunch = recommend_update(userid, 'ランチ', true);
	var numofEtc = recommend_update(userid, 'ディナー等', true);

	//タブ設定
	var now = new Date();
	var hours = now.getHours();
	var min = now.getMinutes();
	var sec = now.getSeconds();

	if ((!numofShopping) && (!numofLunch) && (!numofEtc)) {
		//おすすめ非表示
	}
	//6:00～14:00まではランチ優先
	else if ((numofLunch > 0) &&
			 (compareInttime( hours, min, sec, 6, 0, 0 ) >= 0) &&
			 (compareInttime( 14, 0, 0, hours, min, sec ) > 0)) {
		set_recommend_tab('ランチ');
	}
	//それ以外の時間はディナー等優先
	else if (numofEtc > 0) {
		set_recommend_tab('ディナー等');
	}
	else if ((numofShopping > numofLunch) && (numofShopping > numofEtc)) {
		set_recommend_tab('買い物');
	}
	else if ((numofEtc > numofLunch) && (numofEtc > numofLunch)) {
		set_recommend_tab('ディナー等');
	}
	else {
		set_recommend_tab('ランチ');
	}

	var catlist= "{" +
		"今日は::0:4"
		"}";

	readTopicList(true, getbaseparam(), catlist, false, topic_initCB);

	//掲示板更新
	//bbs_update(userid);

	//記事更新間隔セット
	setTimeout("topic_update()", 60000 * 60);
//	setTimeout("topic_update()", 60000 * 1);
}


/* =====================================
 *
 * main記事読み込み
 *
 */

var main_topic_tabtable = {
 'ニュース': 'topicheadline_news',
 '食事': 'topicheadline_dining',
 '買い物|その他': 'topicheadline_shopping',
 'コミュニティ': 'topicheadline_community',
 '定期休業': 'topicheadline_holiday',
 '地域の掲示板': 'topicheadline_bbs',
 'ブログ': 'topicheadline_blog',
 'Web更新': 'topicheadline_webupdate'
};

var main_topic_labeltable = {
 'ニュース': 'ニュース',
 '食事': '食事',
 '買い物|その他': '買い物・他',
 'コミュニティ': 'コミュニティ',
 '定期休業': '定期休業',
 '地域の掲示板': '掲示板',
 'ブログ': 'ブログ',
 'Web更新': 'Web更新(β)'
};

var maintab_count = 0;

function main_topic_dataset(cat, start, num, topicList) {

	var tabname = main_topic_tabtable[cat];
	var label = main_topic_labeltable[cat];
	var tab = headlineTab[tabname];
	var list = null;

	if (topicList) {
		list = topicList.getTopicAll();
	}

    //alert(cat);

	if ((list) && (list.length > 0)) {

		if (!tab) {
			tab = add_main_tab(tabname, label);
			headlineTab[tabname] = tab;
		}

		topicheadline_viewIndex[cat] = start;
		topicheadline_Total[cat] = topicList.getTotalRows();

	} else {

		//記事クリア
		if (cat == 'ニュース') {
			if (!tab) {
				tab = add_main_tab(tabname, label);
				headlineTab[tabname] = tab;
			}
			tab.innerHTML = 
				"<li class=\"end\" style = \"width:600px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;\">" + 
				"現在有効な記事はありません。" + "</li>";

		} else if (tab) {
			tab.innerHTML = '';
		}

		topicheadline_viewIndex[cat] = 0;
		topicheadline_Total[cat] = 0;

	}

	topic_headline_update(list, tab, topicheadline_viewPage[cat], 600, true, true, false, 1, false);
/*
	if (cat == 'ブログ') {
//		topic_headline_update(list, tab, topicheadline_viewPage[cat], 600, true, true, false, 0, true);
		topic_headline_update(list, tab, topicheadline_viewPage[cat], 600, true, true, false, 1, false);
	} else {
		topic_headline_update(list, tab, topicheadline_viewPage[cat], 600, true, true, false, 1, false);
	}
*/
}

function main_topic_updateCB(topicList) {

	if (topicList) {
		var cat = null;
		var start = 0;
		var num = 0;

		//カテゴリ取得
		var reqparam = topicList.getReqParam();
		if (reqparam) {
			var queryParam = reqparam.toQueryParams();
			var catlist = queryParam['categoryList'];
			if (catlist) {
				catlist = catlist.replace("{", "");
				var word = catlist.split(":");
				if (word) {
					if (word.length > 0) {
						cat = word[0];
					}
					if (word.length > 2) {
						start = toInt(word[2]);
					}
					if (word.length > 3) {
						num = toInt(word[3]);
					}
				}
			}
		}
		
		if (cat)	{
            //alert(cat);
			main_topic_dataset(cat, start, num, topicList);
		}

	} else {

		//ニュースタブがない場合は追加
		if (!headlineTab[main_topic_tabtable['ニュース']]) {
			main_topic_dataset('ニュース', 0, 0, null);
		}

	}
}

function main_topic_update(userid, cat, block) {

//    alert(cat);

	var isHeadline = true;

	if (cat == '地域の掲示板') {
		//bbs_update(userid);
		return;
	}

	if (cat == 'ブログ検索') {
//		isHeadline = false;
	}

	var start = 0;
	if (topicheadline_viewIndex[cat]) {
		start = topicheadline_viewIndex[cat];
	}
	if (!topicheadline_viewPage[cat]) {
		topicheadline_viewPage[cat] = topicheadline_viewNum;
	}
	var num = topicheadline_viewPage[cat];

	var catlist= "{" + cat + "::" + start + ":" + num + "}";

	var param = getbaseparam();
	if (cat == 'ブログ') {
		param += "&withallarea=1";
	}

//	alert(param + "  /////  " + catlist);

	if (block) {
		main_topic_updateCB(readTopicList(isHeadline, param, catlist, false, null));
	} else {
		readTopicList(isHeadline, param, catlist, false, main_topic_updateCB);
	}

}

function main_topic_reset() {

	for(cat in topicheadline_Total) {
		topicheadline_viewIndex[cat] = 0;
		topicheadline_Total[cat] = 0;
		topicheadline_viewPage[cat] = 0;
	}

}

function add_main_tab(tabname, label) {
	var tab = maintabadd(tabname, label);
	maintabsetCallback(tabname, setupHeadLinePageCtrl);

	if (++maintab_count == 6) {
		$('topicheadline_tab').className = "topicheadline_tab2";
	}

	return tab;
}


/* =====================================
 *
 * 記事ページ
 *
 */

function getCurrentTopicCategory(tabname) {

	if (!tabname) {
		tabname = get_currenttabname();
	}
	if (tabname) {
		//カテゴリ取得
		for(cat in main_topic_tabtable) {
			if (main_topic_tabtable[cat] == tabname) {
				return cat;
			}
		}
	}

	return null;
}

function get_currenttabname() {
	for (var key in headlineTab) {
		if (headlineTab[key] == getCurrentMaintab()) {
			return key;
		}
	}
	return null;
}

function setupHeadLinePageCtrl(tabname) {

	//カテゴリ取得
	var cat = getCurrentTopicCategory(tabname);
	if (!cat) return;

	if ( (!topicheadline_Total[cat]) || (!topicheadline_viewPage[cat]) ||
		 (topicheadline_Total[cat] <= topicheadline_viewPage[cat]) ) {
		$('topicheadline_pagectrl').style.display = "none";
		$('topicheadline_pagectrl_clear').style.display = "";
	} else {
		$('topicheadline_pagectrl').style.display = "";
		$('topicheadline_pagectrl_clear').style.display = "none";

		var numofpage = Math.ceil(topicheadline_Total[cat] / topicheadline_viewPage[cat]);

		var pagenum = 1;
		if (topicheadline_viewIndex[cat] > 0) {
			pagenum = Math.floor(topicheadline_viewIndex[cat] / topicheadline_viewPage[cat]) + 1;
		}

		$('topicheadline_pagecount').innerHTML = '　' + pagenum + ' / ' + numofpage + '　';

		if (pagenum == 1) {
			//最初のページ
			$('topicheadline_pagectrl_first').disabled = true;
			$('topicheadline_pagectrl_prev').disabled = true;
			$('topicheadline_pagectrl_next').disabled = false;
			$('topicheadline_pagectrl_last').disabled = false;
		}
		else if (pagenum == numofpage) {
			//最後のページ
			$('topicheadline_pagectrl_first').disabled = false;
			$('topicheadline_pagectrl_prev').disabled = false;
			$('topicheadline_pagectrl_next').disabled = true;
			$('topicheadline_pagectrl_last').disabled = true;
		}
		else {
			$('topicheadline_pagectrl_first').disabled = false;
			$('topicheadline_pagectrl_prev').disabled = false;
			$('topicheadline_pagectrl_next').disabled = false;
			$('topicheadline_pagectrl_last').disabled = false;
		}

	}

}

function topicheadline_first_page() {
	if (! $('topicheadline_pagectrl_first').disabled) {
		var cat = getCurrentTopicCategory(null);
		if (cat) {
			topicheadline_viewIndex[cat] = 0;
			main_topic_update(r500m_userid, cat, false);
			setupHeadLinePageCtrl(null);
		}
	}
}

function topicheadline_prev_page() {
	if (! $('topicheadline_pagectrl_prev').disabled) {
		var cat = getCurrentTopicCategory(null);
		if (cat) {
			topicheadline_viewIndex[cat] -= topicheadline_viewPage[cat];
			main_topic_update(r500m_userid, cat, false);
			setupHeadLinePageCtrl(null);
		}
	}
}

function topicheadline_next_page() {
	if (! $('topicheadline_pagectrl_next').disabled) {
		var cat = getCurrentTopicCategory(null);
		if (cat) {
			topicheadline_viewIndex[cat] += topicheadline_viewPage[cat];
			main_topic_update(r500m_userid, cat, false);
			setupHeadLinePageCtrl(null);
		}
	}
}

function topicheadline_last_page() {
	if (! $('topicheadline_pagectrl_last').disabled) {
		var cat = getCurrentTopicCategory(null);
		if (cat) {
			topicheadline_viewIndex[cat] = (Math.ceil(topicheadline_Total[cat] / topicheadline_viewPage[cat]) - 1) * topicheadline_viewPage[cat];
			main_topic_update(r500m_userid, cat, false);
			setupHeadLinePageCtrl(null);
		}
	}
}


/* =====================================
 *
 * おすすめ記事読み込み
 *
 */

var recommend_tabtable = {
 '買い物': 'topicrecommend_shopping',
 'ランチ': 'topicrecommend_lunch',
 'ディナー等': 'topicrecommend_dinner'
};

var recommend_labeltable = {
 '買い物': '買い物',
 'ランチ': 'ランチ',
 'ディナー等': 'ディナー等'
};

var recommendtab_count = 0;

function recommend_dataset(cat2, start, num, topicList) {

	var tabname = recommend_tabtable[cat2];
	var label = recommend_labeltable[cat2];
	var tab = recommendTab[tabname];
	var list = null;

	if (topicList) {
		list = topicList.getTopicAll();
	}

	if ((list) && (list.length > 0)) {

		if (!tab) {
			tab = add_recommend_tab(tabname, label);
			recommendTab[tabname] = tab;
		}

		topicrecommend_viewIndex[cat2] = start;
		topicrecommend_Total[cat2] = topicList.getTotalRows();
	} else {
		topicrecommend_viewIndex[cat2] = 0;
		topicrecommend_Total[cat2] = 0;
	}

	return topic_category_set(list, tab, topicrecommend_viewPage[cat2], 220, false, false, true, 2, false);
}


function recommend_updateCB(topicList) {

	var ret = 0;

	if (topicList) {
		var cat2 = null;
		var start = 0;
		var num = 0;

		//カテゴリ取得
		var reqparam = topicList.getReqParam();
		if (reqparam) {
			var queryParam = reqparam.toQueryParams();
			var catlist = queryParam['categoryList'];
			if (catlist) {
				catlist = catlist.replace("{", "");
				var word = catlist.split(":");
				if (word) {
					if (word.length > 1) {
						cat2 = word[1];
					}
					if (word.length > 2) {
						start = toInt(word[2]);
					}
					if (word.length > 3) {
						num = toInt(word[3]);
					}
				}
			}
		}

		if (cat2)	{
			ret = recommend_dataset(cat2, start, num, topicList);
		}

	} else {

		//記事なし
		//alert('記事なし');
	}

	setupRecommendPageCtrl(null);

	return ret;
}


function recommend_update(userid, cat2, block) {

	var isHeadline = true;
	var start = 0;
	var num = 0;

	topicrecommend_Total[cat2] = 0;
	if (topicrecommend_viewIndex[cat2]) {
		start = topicrecommend_viewIndex[cat2];
	}
	if (!topicrecommend_viewPage[cat2]) {
		topicrecommend_viewPage[cat2] = topicrecommend_viewNum;
	}
	var num = topicrecommend_viewPage[cat2];

	var catlist= "{おすすめ:" + cat2 + ":" + start + ":" + num + "}";

	var param = getbaseparam();

	if (block) {
		num = recommend_updateCB(readTopicList(isHeadline, param, catlist, false, null));
	} else {
		readTopicList(isHeadline, param, catlist, false, recommend_updateCB);
	}

	return num;
}


function recommend_reset() {

	for(cat2 in topicrecommend_Total) {
		topicrecommend_viewIndex[cat2] = 0;
		topicrecommend_Total[cat2] = 0;
		topicrecommend_viewPage[cat2] = 0;
	}

	setupRecommendPageCtrl(null);

}

function add_recommend_tab(tabname, label) {
	var tab = recommendtabadd(tabname, label);
	recommendtabsetCallback(tabname, setupRecommendPageCtrl);
	return tab;
}

function set_recommend_tab(cat2) {
	recommendtabsetbyobj( $( recommend_tabtable[ cat2 ] ));
}


/* =====================================
 *
 * おすすめページ
 *
 */

function getCurrentRecommendCategory(tabname) {

	if (!tabname) {
		tabname = get_currentrecommendtabname();
	}

	if (tabname) {
		//カテゴリ取得
		for(cat2 in recommend_tabtable) {
			if (recommend_tabtable[cat2] == tabname) {
				return cat2;
			}
		}
	}

	return null;
}

function get_currentrecommendtabname() {
	for (var key in recommendTab) {
		if (recommendTab[key] == getCurrentRecommendtab()) {
			return key;
		}
	}
	return null;
}

function setupRecommendPageCtrl(tabname) {

	//カテゴリ取得
	var cat2 = getCurrentRecommendCategory(tabname);
	if (!cat2) return;
	else if (cat2 == 'ランチ') {
		$('recommend_lunchmsg').style.display = "";
		$('recommend_lunchmsg_clear').style.display = "none";
	} else {
		$('recommend_lunchmsg').style.display = "none";
		$('recommend_lunchmsg_clear').style.display = "";
	}


	if ( (!topicrecommend_Total[cat2]) || (!topicrecommend_viewPage[cat2]) ||
		 (topicrecommend_Total[cat2] <= topicrecommend_viewPage[cat2]) ) {
		$('recommend_pagectrl').style.display = "none";
		$('recommend_pagectrl_clear').style.display = "";
	} else {
		$('recommend_pagectrl').style.display = "";
		$('recommend_pagectrl_clear').style.display = "none";

		var numofpage = Math.ceil(topicrecommend_Total[cat2] / topicrecommend_viewPage[cat2]);

		var pagenum = 1;
		if (topicrecommend_viewIndex[cat2] > 0) {
			pagenum = Math.floor(topicrecommend_viewIndex[cat2] / topicrecommend_viewPage[cat2]) + 1;
		}

		$('recommend_pagecount').innerHTML = '　' + pagenum + ' / ' + numofpage + '　';

		if (pagenum == 1) {
			//最初のページ
			$('recommend_pagectrl_first').disabled = true;
			$('recommend_pagectrl_prev').disabled = true;
			$('recommend_pagectrl_next').disabled = false;
			$('recommend_pagectrl_last').disabled = false;
		}
		else if (pagenum == numofpage) {
			//最後のページ
			$('recommend_pagectrl_first').disabled = false;
			$('recommend_pagectrl_prev').disabled = false;
			$('recommend_pagectrl_next').disabled = true;
			$('recommend_pagectrl_last').disabled = true;
		}
		else {
			$('recommend_pagectrl_first').disabled = false;
			$('recommend_pagectrl_prev').disabled = false;
			$('recommend_pagectrl_next').disabled = false;
			$('recommend_pagectrl_last').disabled = false;
		}

	}

	//すべて記事がない場合は表示しない。
	var total = 0;
	for(var key in topicrecommend_Total) {
		total += topicrecommend_Total [ key ];
	}


	//total = 0;

	//変更があった場合
	var changeRecommend = (! ( hasTopicRecommend == (total > 0 ) ) );

	//alert(hasTopicRecommend);


	hasTopicRecommend = (total > 0);
	if (hasTopicRecommend) {		
		$('recommend').style.display = "";
	} else {
		$('recommend').style.display = "none";
	}

	if(changeRecommend){
		traffic_changemode();
	}


}


function recommend_first_page() {
	if (! $('recommend_pagectrl_first').disabled) {
		var cat2 = getCurrentRecommendCategory(null);
		if (cat2) {
			topicrecommend_viewIndex[cat2] = 0;
			recommend_update(r500m_userid, cat2, false);
		}
	}
}

function recommend_prev_page() {
	if (! $('recommend_pagectrl_prev').disabled) {
		var cat2 = getCurrentRecommendCategory(null);
		if (cat2) {
			topicrecommend_viewIndex[cat2] -= topicrecommend_viewPage[cat2];
			recommend_update(r500m_userid, cat2, false);
		}
	}
}

function recommend_next_page() {
	if (! $('recommend_pagectrl_next').disabled) {
		var cat2 = getCurrentRecommendCategory(null);
		if (cat2) {
			topicrecommend_viewIndex[cat2] += topicrecommend_viewPage[cat2];
			recommend_update(r500m_userid, cat2, false);
		}
	}
}

function recommend_last_page() {
	if (! $('recommend_pagectrl_last').disabled) {
		var cat2 = getCurrentRecommendCategory(null);
		if (cat2) {
			topicrecommend_viewIndex[cat2] = (Math.ceil(topicrecommend_Total[cat2] / topicrecommend_viewPage[cat2]) - 1) * topicrecommend_viewPage[cat2];
			recommend_update(r500m_userid, cat2, false);
		}
	}
}


/* =====================================
 *
 * 記事表示
 *
 */
function topic_print(topicList) {

	var list;

	//ゴミの日
	update_todays_garbage(topicList);

	//天気
	update_todays_weather(topicList);

	//今日は
	update_todays_event(topicList);

	//交通情報☆
	//topic_category_update(topicList, 'headline_traffic', 4, '交通情報', '列車運行情報', 220, false, false, false, 0);
	traffic_update();
}

function topic_headline_update(list, obj, num, width,
								showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var topicdata = "";
	var numoftopic = 0;

	if (list) {

		numoftopic = list.length;
		var count = num;
		if (count > list.length) {
			count = list.length;
		}

		for(var idx = 0; idx < count; idx++) {

			if (idx == (count-1)) {
				topicdata += "<li class=\"end\">";
			} else {
				topicdata += "<li>";
			}

			var topic = list[idx];
			topicdata += getTopichtmlLine(topic, width, showCat2, showDate, boldHeadline, showOwnername, showContents);

			topicdata += "</li>";
		}

		obj.innerHTML = topicdata;
	}

	return numoftopic;
}


function topic_category_update(topicList, tag, num, category1, category2, width,
								showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var list = null;

	if (category1 == '*') {
		list = topicList.getTopicAll();
	} else if (category2 == '*') {
		list = topicList.getTopicC1(category1);
	} else {
		list = topicList.getTopic(category1, category2);
	}

	return topic_category_set(list, $(tag), num, width, showCat2, showDate, boldHeadline, showOwnername, showContents);
}

function topic_category_set(list, obj, num, width, showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var topicdata = "";
	var numoftopic = 0;


	if (list) {

	//☆
	//alert("記事の数  " + (list.length) + "　　最初の記事：" + list[0].getHeadline() );

		numoftopic = list.length;
		var count = num;
		if (count > list.length) {
			count = list.length;
		}

		for(var idx = 0; idx < count; idx++) {

			if (idx == (count-1)) {
				topicdata += "<li class=\"end\">";
			} else {
				topicdata += "<li>";
			}

			var topic = list[idx];
			//alert(topic.getHeadline());
			topicdata += getTopichtmlLine(topic, width, showCat2, showDate, boldHeadline, showOwnername, showContents);


			topicdata += "</li>";
		}

		obj.innerHTML = topicdata;
	}

	return numoftopic;
}


var cat2classtable = {
 'イベント': 'listicon_event',
 'オープン': 'listicon_open',
 '新規参加': 'listicon_newregist',
 'セール': 'listicon_sale',
 '不審者': 'listicon_fushin',
 '事故': 'listicon_jiko',
 '求人': 'listicon_job',
 '事件': 'listicon_jiken',
 'R500m': 'listicon_r500m',
 'お知らせ': 'listicon_info',
 'ブログ検索': 'listicon_blog',
 'オフィシャル': 'listicon_offcial'
};

function getTopichtmlLine(topic, width, showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var line = "";
	var str;
	var cname;

	if ((showCat2) && (str = topic.getCategory2()) && (str.length > 0) &&
	    (cname = cat2classtable[str]) && (cname.length > 0)) {
		line += "<span class=\"" + cname + "\"></span>";
		width -= 50;
	}

	if ((topic.getLink_class() == "2") && (str = topic.getUrl()) && (str.length > 0)) {
		line += "<a href=\"" + str + "\" target=\"_blank\" style = \"" +
				"width:" + width + "px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;\" >";
	} else {
		var url = getTopicURL(topic.getId());
		line += "<a href=\"" + url + "\" style = \"" +
				"width:" + width + "px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;" +
				"\"  target=\"_blank\" >";
	}

	if ((showDate) && (str = topic.getStart_date_short()) && (str.length > 0)) {
		line += "<strong>" + str + "</strong>"
	}

	if (boldHeadline) {
		line += "<strong>" + topic.getHeadline() + "</strong>";
	} else {
		line += topic.getHeadline();
	}

	if ((showOwnername) && (str = topic.getOwnername()) && (str.length > 0)) {
		if (showOwnername == 2) {
			line += "<p>（" + str + "）</p>";
		} else if (showOwnername == 1) {
			line += " - " + str;
		}
	}
	else if ((showContents) && (str = topic.getContents()) && (str.length > 0)) {
		line += " - " + str;
	}

	return line + "</a>";
}

/* =====================================
 *
 * 記事クリア
 *
 */
function topic_clear() {

	var tab;

	//ゴミの日
	clear_todays_garbage();

	//天気
	clear_todays_weather();

	//今日は
	clear_todays_event();
	
	//おすすめ/買い物
	if ((tab = recommendTab['topicrecommend_shopping'])) {
		tab.innerHTML = '';
	}

	//おすすめ-ランチ
	if ((tab = recommendTab['topicrecommend_lunch'])) {
		tab.innerHTML = '';
	}

	//おすすめ-ディナー等
	if ((tab = recommendTab['topicrecommend_dinner'])) {
		tab.innerHTML = '';
	}

	//ニュース
	if ((tab = headlineTab['topicheadline_news'])) {
		tab.innerHTML = 
			"<li class=\"end\" style = \"width:600px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;\">" + 
			"現在有効な記事はありません。" + "</li>";
	}

	//食事
	if ((tab = headlineTab['topicheadline_dining'])) {
		tab.innerHTML = '';
	}

	//買い物・その他
	if ((tab = headlineTab['topicheadline_shopping'])) {
		tab.innerHTML = '';
	}

	//コミュニティ
	if ((tab = headlineTab['topicheadline_community'])) {
		tab.innerHTML = '';
	}

	//定期休業
	if ((tab = headlineTab['topicheadline_holiday'])) {
		tab.innerHTML = '';
	}

	//地域の掲示板
	if ((tab = headlineTab['topicheadline_bbs'])) {
		tab.innerHTML = '';
	}

	//ブログ
	if ((tab = headlineTab['topicheadline_blog'])) {
		tab.innerHTML = '';
	}
    //Web更新
	if ((tab = headlineTab['topicheadline_webupdate'])) {
		tab.innerHTML = '';
	}
}



/* =====================================
 *
 * 掲示板表示
 *
 */

function bbs_updateCB(topicList) {

	var topicdata = '';

	if (topicList) {

		var start = 0;
		var num = 0;

		var reqparam = topicList.getReqParam();
		if (reqparam) {
			var queryParam = reqparam.toQueryParams();
			start = toInt(queryParam['start']);
			num = toInt(queryParam['num']);
		}

		var list = topicList.getTopicAll();
		if ((list) && (list.length > 0)) {

			topicheadline_viewIndex['地域の掲示板'] = start;
			topicheadline_Total['地域の掲示板'] = topicList.getTotalRows();

			var count = topicheadline_viewPage['地域の掲示板'];
			var endline = count - 1;

			if (count > list.length) {
				count = list.length;
			}

			for(var idx = 0; idx < count; idx++) {

				if (idx == endline) {
					topicdata += "<li class=\"end\">";
				} else {
					topicdata += "<li>";
				}

				var topic = list[idx];
				//alert(topic.getHeadline());

				var url = "/bbsview.html?id=" + topic.getId();

				topicdata += 
					"<a href=\"" + url + "\" style = \"" +
					"width:600px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;" +
					"\" target=\"_blank\" >" + 
					topic.getHeadline() + "</a></li>";

			}

		} else {
			topicheadline_viewIndex['地域の掲示板'] = 0;
			topicheadline_Total['地域の掲示板'] = 0;
		}

	}

	if ( ((r500m_userlogin) && (r500m_userlogin == "1")) &&
		 (!r500m_spotname) &&
		 (!r500m_address) && (!r500m_latitude) && (!r500m_longitude) ) {

		//ログインしていて座標移動がない時に追加
		topicdata += 
			"<li class=\"end\">" +
			"<a href=\"/bbsview.html\" style = \"" +
			"width:600px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:blue;" +
			"\" target=\"_blank\" >" + 
			"新しいトピックを書く" + "</a></li>";
	}

	//記事セット
	var tabname = main_topic_tabtable['地域の掲示板'];
	var label = main_topic_labeltable['地域の掲示板'];
	var tab = headlineTab[tabname];

	if ((topicdata) && (!tab)) {
		tab = add_main_tab(tabname, label);
		headlineTab[tabname] = tab;
	}

	if (tab) {
		tab.innerHTML = topicdata;
	}

}

function bbs_update(userid) {

	if (!topicheadline_viewPage['地域の掲示板']) {
		topicheadline_viewPage['地域の掲示板'] = topicheadline_viewNum;

		if ( ((r500m_userlogin) && (r500m_userlogin == "1")) &&
			 (!r500m_spotname) &&
			 (!r500m_address) && (!r500m_latitude) && (!r500m_longitude) ) {
			//ログインしていて座標移動がない時は－１
			topicheadline_viewPage['地域の掲示板'] = topicheadline_viewPage['地域の掲示板'] - 1;
		}
	}

	var start = 0;
	if (topicheadline_viewIndex['地域の掲示板']) {
		start = topicheadline_viewIndex['地域の掲示板'];
	}
	var num = topicheadline_viewPage['地域の掲示板'];

	readTopicList(true, "bbs&parent&noexpire&start=" + start + "&num=" + num + "&user=" + userid, null, true, bbs_updateCB);
}


/* =====================================
 *
 * 日時
 *
 */

function update_calendar() {

	//暦
	calenderTopicList = searchTopicHL("&category1=暦", null);
	if (calenderTopicList) {
		var list = calenderTopicList.getTopic("暦", "祭日");
		if ((list) && (list.length > 0)) {
			todaysTopic['holiday'] = list[0];
		}
	}
}


function update_todays_calendar(topicList) {

	//暦
	var list = topicList.getTopic("暦", "祭日");
	if ((list) && (list.length > 0)) {
		todaysTopic['holiday'] = list[0];
	}
}


var day_str = [ "日", "月", "火", "水", "木", "金", "土" ];
var day_str_color = [ "red", "black", "black", "black", "black", "black", "blue" ];

function update_todays_date() {

	var now = new Date();
	var year = now.getYear();
	if (year < 2000)	year += 1900;

	var str = 
		year + "年" +
		(now.getMonth()+1) + "月" +
		now.getDate() + "日";

	if (todaysTopic['holiday']) { //祭日
		str += "（" + day_str[now.getDay()].fontcolor(day_str_color[0]) + "）";
	} else {
		str += "（" + day_str[now.getDay()].fontcolor(day_str_color[now.getDay()]) + "）";
	}

	//時
	var val = now.getHours();
	if (val < 10) {
		str += " ";
	}
	str += val + ":";

	//分
	var val = now.getMinutes();
	if (val < 10) {
		str += "0";
	}
	str += val;
	//str += ":" + now.getSeconds();

	$('datestr').innerHTML = str;

	setTimeout("update_todays_date()", 60000);
}



/* =====================================
 *
 * 今日は
 *
 */
function update_todays_event(topicList) {

	var list = topicList.getTopic("今日は", null);

	var callist = null;
	if (calenderTopicList) {
		callist = calenderTopicList.getTopicAll();
	}

	if (list) {
		if (callist) {
			[].push.apply(list, callist);
		}
	} else {
		list = callist;
	}

	return topic_category_set(list, $('headline_today'), 4, 350, false, false, false, 1, 0);
}

function clear_todays_event() {
	$('headline_today').innerHTML = '';
}

/* =====================================
 *
 * ごみ収集日等
 *
 */
function update_todays_garbage(topicList) {

	//ゴミの日
	list = topicList.getTopicC1("ごみ収集日");
	if ((list) && (list.length > 0)) {
		var topic = list[0];
		var url = getTopicURL(topic.getId());
		$('msg_today').innerHTML = 
			"<a href=\"" + url + "\" style=\"color:#000000;\" target=\"_blank\" >" +
			topic.getHeadline() + "</a>";
	}

}

function clear_todays_garbage() {
	//ゴミの日
	$('msg_today').innerHTML = '';
}


/* =====================================
 *
 * 天気予報更新
 *
 */
function update_todays_weather(topicList) {

	//天気
	var list = topicList.getTopic("天気", "今日の天気");
	if ((list) && (list.length > 0)) {
		todaysTopic['weather_today'] = list[0];
		weather_update();
	}
//	weather_update();
}

function weather_update() {

	var topic = todaysTopic['weather_today'];
	if (!topic)	return;

	// * headlineフォーマット
	//	天気:最高気温:最低気温:降水確率0-6:降水確率6-12:降水確率12-18:降水確率18-24

	var data = topic.getHeadline().split(":");
//	var data = "曇後一時雨:32:999:999:999:40:50".split(":");
	var val;

	//天気/アイコン
	$('weather_line').innerHTML = "<p id=\"" + weather_icon[data[0]] + "\"><span>" + data[0] + "</span></p>";

	//最高気温
	val = data[1];
	if ((!val) || (val == '999')) {
		val = " -- ";
	} else {
		val = val + '℃';
	}
	$('weather_temp_max').innerHTML = val;

	//最低気温
	val = data[2];
	if ((!val) || (val == '999')) {
		val = " -- ";
	} else {
		val = val + '℃';
	}
	$('weather_temp_min').innerHTML = val;

	//降水確率
	var now = new Date();
	var idx = 0;
	if (now.getHours() > 0) {
		idx = Math.floor(now.getHours() / 6);
	}
	val = data[3 + idx];
	if ((!val) || (val == '999')) {
		val = "-- ";
	} else {
		val = val + '%';
	}
	$('weather_rain').innerHTML = val;

	$('weather_block').style.visibility = "visible";

	setTimeout("weather_update()", 60000 * 60);
}

function clear_todays_weather() {
	$('weather_line').innerHTML = '';
	$('weather_temp_max').innerHTML = '';
	$('weather_temp_min').innerHTML = '';
	$('weather_rain').innerHTML = '';
}

/* =====================================
 *
 * 交通情報の更新
 *
 */
var traffic_viewNum      = new Array();
    traffic_viewNum[0]   = 4;
    traffic_viewNum[1]   = 11;

var traffic_mode         = 0; //0:通常 1:LONG

//div の ID
var traffic_div     = new Array();
    traffic_div[0]  = 'traffic';
    traffic_div[1]  = 'traffic_long';

//Headline を表示する ul のID
var traffic_ul      = new Array();
    traffic_ul[0]   = 'headline_traffic';
    traffic_ul[1]   = 'headline_traffic_long';

//ページ送り領域
var traffic_pc      = new Array();
    traffic_pc[0]   = 'traffic_pagectrl';
    traffic_pc[1]   = 'traffic_pagectrl_long';

//ページ送り領域（非表示時）
var traffic_pcc     = new Array();
    traffic_pcc[0]  = 'traffic_pagectrl_clear';
    traffic_pcc[1]  = 'traffic_pagectrl_clear_long';

//最初へボタン
var traffic_pc_f     = new Array();
    traffic_pc_f[0]  = 'traffic_pagectrl_first';
    traffic_pc_f[1]  = 'traffic_pagectrl_first_long';

//次へボタン
var traffic_pc_n     = new Array();
    traffic_pc_n[0]  = 'traffic_pagectrl_next';
    traffic_pc_n[1]  = 'traffic_pagectrl_next_long';

//前へボタン
var traffic_pc_p     = new Array();
    traffic_pc_p[0]  = 'traffic_pagectrl_prev';
    traffic_pc_p[1]  = 'traffic_pagectrl_prev_long';

//最後へボタン
var traffic_pc_l     = new Array();
    traffic_pc_l[0]  = 'traffic_pagectrl_last';
    traffic_pc_l[1]  = 'traffic_pagectrl_last_long';

//ページ数表示
var traffic_pc_pn    = new Array();
    traffic_pc_pn[0] = 'traffic_pagecount';
    traffic_pc_pn[1] = 'traffic_pagecount_long';

var traffic_viewPage;
var traffic_viewIndex;
var traffic_Total;

var traffic_topiclist    = null;

function traffic_category_update(topicList, tag, num, category1, category2, width,
								showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var list = null;

	list = topicList.getTopic(category1, category2);

	return traffic_category_set(list, $(tag), num, width, showCat2, showDate, boldHeadline, showOwnername, showContents);
}

function traffic_category_set(list, obj, num, width, showCat2, showDate, boldHeadline, showOwnername, showContents) {

	var topicdata = "";
	var numoftopic = 0;

	if (list) {

		traffic_topiclist = list;

		traffic_viewPage  = 1;


		traffic_topic_set(traffic_viewPage,obj);



		//☆
		//alert("記事の数  " + (list.length) + "　　最初の記事：" + list[0].getHeadline() );

//		numoftopic = list.length;
//		var count = num;
//		if (count > list.length) {
//			count = list.length;
//		}

//		for(var idx = 0; idx < count; idx++) {
//
//			if (idx == (count-1)) {
//				topicdata += "<li class=\"end\">";
//			} else {
//				topicdata += "<li>";
//			}

//			var topic = list[idx];
//			//alert(topic.getHeadline());
//			topicdata += getTopichtmlLine(topic, width, showCat2, showDate, boldHeadline, showOwnername, showContents);
//			//alert(topic.getHeadline() + ":width=" + width + ":showcat2=" + showCat2 + ":showdate=" + showDate + ":boldheadline=" + boldHeadline + ":showOwnername=" + showOwnername + ":showContents=" + showContents);

//			topicdata += "</li>";
//		}

//		obj.innerHTML = topicdata;
	}else{
		traffic_topiclist = null;
	}

	return numoftopic;
}


//ページごとに記事を表示する
function traffic_topic_set(viewpage,obj){
	
	//記事件数の確認
	var maxpage = Math.ceil(traffic_topiclist.length / traffic_viewNum[traffic_mode]);
	if(maxpage < viewpage){
		viewpage = maxpage;
	}
	
	var startix = traffic_viewNum[traffic_mode] * (viewpage -1);
	var endix   = startix + traffic_viewNum[traffic_mode] -1;
	if(traffic_topiclist.length - 1 < endix ){
		endix = traffic_topiclist.length - 1;
	}
	
	var topichtml = "";
	for(var ix = startix ; ix <= endix ; ix++ ){
		if (ix == endix) {
			topichtml += "<li class=\"end\">";
		} else {
			topichtml += "<li>";
		}
		var onetopic = traffic_topiclist[ix];
		topichtml += getTopichtmlLine(onetopic, 220, false, false, false, 0, null);
		topichtml += "</li>";
	}
	
	obj.innerHTML = topichtml;
	
	traffic_viewPage = viewpage;
	
	traffic_pagectrl();
	
}

//下段ページ表示のリフレッシュ（記事表示の後に行う）
function traffic_pagectrl() {

	//記事がない場合は非表示
	if(!traffic_topiclist){
		$(traffic_pcc[traffic_mode]).style.display    = "";
		$(traffic_pc[traffic_mode]).style.display     = "none";
		$(traffic_pc_f[traffic_mode]).disabled        = true;
		$(traffic_pc_p[traffic_mode]).disabled        = true;
		$(traffic_pc_n[traffic_mode]).disabled        = false;
		$(traffic_pc_l[traffic_mode]).disabled        = false;
		$(traffic_pc_pn[traffic_mode]).innerHTML      = '　0 / 0　';
		return 0;
	}

	if(traffic_topiclist.length <= traffic_viewNum[traffic_mode] ){
		$(traffic_pcc[traffic_mode]).style.display    = "";
		$(traffic_pc[traffic_mode]).style.display     = "none";
		$(traffic_pc_f[traffic_mode]).disabled        = true;
		$(traffic_pc_p[traffic_mode]).disabled        = true;
		$(traffic_pc_n[traffic_mode]).disabled        = false;
		$(traffic_pc_l[traffic_mode]).disabled        = false;
		$(traffic_pc_pn[traffic_mode]).innerHTML      = '　0 / 0　';
		return 0;
	}


	//alert('1');

	//ページ位置により要素の表示・非表示を設定
	$(traffic_pcc[traffic_mode]).style.display = "none";
	$(traffic_pc[traffic_mode] ).style.display = "";

	//alert('traffic_viewPage:' + traffic_viewPage);

	//1ページ目の場合
	if(traffic_viewPage == 1){
		$(traffic_pc_f[traffic_mode]).disabled = true;
		$(traffic_pc_p[traffic_mode]).disabled  = true;
	}else{
		$(traffic_pc_f[traffic_mode]).disabled = false;
		$(traffic_pc_p[traffic_mode]).disabled  = false;
	}

	//alert('3');

	// ページ番号表示
	var maxpage = Math.ceil(traffic_topiclist.length / traffic_viewNum[traffic_mode]);
	$(traffic_pc_pn[traffic_mode]).innerHTML = '　' + traffic_viewPage + ' / ' + maxpage + '　';

	//alert('4');

	// 次へ・最後へボタンの設定
	if(traffic_viewPage == maxpage){
		$(traffic_pc_n[traffic_mode]).disabled = true;
		$(traffic_pc_l[traffic_mode]).disabled = true;
	}else{
		$(traffic_pc_n[traffic_mode]).disabled = false;
		$(traffic_pc_l[traffic_mode]).disabled = false;
	}

	//alert('5');


	return 0;

}

function traffic_firstpage(){

	traffic_topic_set(1,$(traffic_ul[traffic_mode]));

}

function traccic_prevpage(){

	if(traffic_viewPage > 1){
		traffic_topic_set(traffic_viewPage - 1,$(traffic_ul[traffic_mode]));
	}

}

function traffic_nextpage(){

	traffic_topic_set(traffic_viewPage + 1,$(traffic_ul[traffic_mode]));

}

function traffic_lastpage(){

	if(traffic_topiclist){
		var maxpage = Math.ceil(traffic_topiclist.length / traffic_viewNum[traffic_mode]);
		traffic_topic_set(maxpage,$(traffic_ul[traffic_mode]));
	}

}

function traffic_changemode(){

	if(hasTopicRecommend){
		// おすすめがある場合
		traffic_mode = 0;
		$(traffic_div[0]).style.display = "";
		$(traffic_div[1]).style.display = "none";
	}else{
		// おすすめがない場合
		traffic_mode = 1;
		$(traffic_div[0]).style.display = "none";
		$(traffic_div[1]).style.display = "";
	}

	traffic_update(true);

}




function traffic_update_readCB(numoftopic, topiclist) {

//	alert(numoftopic);
 	if (topiclist) {
		//alert("TOPICLIST行数" + topiclist.getTotalRows() );
		//topic_category_update(topiclist, 'headline_traffic', 4, '交通情報', '列車運行情報', 220, false, false, false, 0);
		
		traffic_category_update(topiclist, traffic_ul[traffic_mode] , traffic_viewNum[traffic_mode]
								, '交通情報', '列車運行情報', 220, false, false, false, 0);

 	}
	else {
		set_traffic_nothing(traffic_ul[traffic_mode], 220);
	}
}

function traffic_update(FLG) {


	if(!FLG){
		traffic_changemode();
		return 0;
	}

 	//交通情報の取得
	//var topiclist = searchTopicHL("&category1=列車運行情報&start=0&num=4&noexpire", traffic_update_readCB);
 	//searchTopicHL("&category1=交通情報&category2=列車運行情報&start=0&num=4", traffic_update_readCB);
 	searchTopicHL("&category1=交通情報&category2=列車運行情報&start=0", traffic_update_readCB);

	//交通情報間隔セット
	//traffic_changemode からの呼び出し時にはタイムアウト設定しない
	if(!FLG){
		setTimeout("traffic_update()", 60000 * 3);
	}

}

function set_traffic_nothing(tag, width) {
	$(tag).innerHTML = 
		"<li class=\"end\">" +
		"<a href=\"\" style = \"width:" + width + "px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;\"" +
		" onclick=\"return false\" >正常運行しています。</a></li>";

	traffic_viewPage = 1;
	traffic_pagectrl();

}




/* =====================================
 *
 * スポット
 *
 */

landmark_tag_list = {
	"緊急"				:	[ "navi1", null ],
	"行政"				:	[ "navi2", null ],
	"交通"				:	[ "navi3", null ],
	"インフラ"			:	[ "navi4", null ],
	"健康・美容"		:	[ "navi5", null ],
	"教育・子供"		:	[ "navi6", null ],
	"衣"				:	[ "navi8", null ],
	"食-ﾃﾞﾘﾊﾞﾘｰ"		:	[ "navi9", "direction_left" ],
	"食-店舗"			:	[ "navi10", "direction_left" ],
	"食-外食"			:	[ "navi11", "direction_left" ],
	"金融"				:	[ "navi7", null ],
	"住"				:	[ "navi12", null ],
	"遊・イベント"		:	[ "navi13", null ],
	"趣味・習い事"		:	[ "navi14", null ],
	"車とペット"		:	[ "navi15", null ],
	"ﾋﾞｼﾞﾈｽｻﾎﾟｰﾄ"		:	[ "navi16", null ],
	"冠婚葬祭"			:	[ "navi17", "direction_left" ],
	"介護・福祉"		:	[ "navi18", "direction_left" ],
	"コミュニティ"		:	[ "navi19", "direction_left" ]
};


function landmark_initCB(numoflandmark, landmarkList) {
	landmark_updateCB(numoflandmark, landmarkList);
	update_contents_bystep();
}

function landmark_init(userid) {
	searchLandmarkHL(getbaseparam() + "&withcouponcount=1", landmark_initCB);
}


function landmark_clear() {

	for(var key in landmark_tag_list) {
		var attr = landmark_tag_list [ key ];
		if ( attr ) {
			$(attr[0]).innerHTML = '';
		}
	}

	buildsubmenus_horizontal();
}



function landmark_updateCB(numoflandmark, landmarkList) {

	var cat1list = landmarkList.getCategories1();
	if (cat1list) {

		for(var key in landmark_tag_list) {
			var attr = landmark_tag_list [ key ];
			if ( attr ) {
				$(attr[0]).innerHTML = "<a>" + key + " ▼</a>" +
										get_landmark_category2line(landmarkList, key, attr[1]);
			}
		}

		buildsubmenus_horizontal();
	}

}

function landmark_update(userid) {
	searchLandmarkHL(getbaseparam() + "&withcouponcount=1", landmark_updateCB);
}

function get_landmark_category2line(landmarkList, cat1, attr) {

	var list = landmarkList.getCategories2(cat1);
	var html = "";

	if (list) {
		html += "<ul>";

		for(var idx = 0; idx < list.length; idx++) {
			var cat2 = list[idx];

			if (cat2) {
				html += "<li><a>" + cat2 + "</a>" + 
						get_landmark_category3line(landmarkList, cat1, cat2, attr) +
						"</li>";
			}
		}
		html += "</ul>";
	}

	return html;
}

function get_landmark_category3line(landmarkList, cat1, cat2, attr) {

	var list = landmarkList.getLandmark(cat1, cat2);
	var html = "";

	if (list) {

		if (landmarkList.hasCategory3(cat1, cat2)) {

			var catlist = landmarkList.getCategories3(cat1, cat2);

			html += "<ul>";
			for(var idx = 0; idx < catlist.length; idx++) {
				var cat3 = catlist[idx];
				if (cat3) {
					var lmlist = landmarkList.getLandmark3(cat1, cat2, cat3);

					if (attr) {
						html += "<li class=\"" + attr + "\">";
					} else {
						html += "<li>";
					}

					html += "<a>" + cat3 + "</a>" + get_landmark_landmarkline(landmarkList, lmlist, attr) + "</li>";
				}
			}
			html += "</ul>";

		}
		else {
			html = get_landmark_landmarkline(landmarkList, list, attr);
		}

	}

	return html;
}


function get_landmark_landmarkline(landmarkList, list, attr) {

	var html = "";

	if (attr) {
		html += "<ul class=\"" + attr + "\">";
	} else {
		html += "<ul>";
	}

	for(var idx = 0; idx < list.length; idx++) {
		var landmark = list[idx];
		if (landmark) {
			var lm;

			if (landmark.getLink_class() == '1') {
				lm = landmarkList.getLandmarkById(landmark.getLink_id());
			} else {
				lm = landmark;
			}

			var url = getLandmarkURL(landmark.getId());

			html += "<li><a href=\"" + url + "\" target=\"_blank\" >";

			if (lm) {

				//新着記事
				if (lm.getHasnewtopic() > 0) {
					html += "<span class=\"listicon_new\">新着記事</span>";
				}

				//クーポン
				if (lm.getHascoupon() > 0) {
					html += "<span class=\"listicon_coupon\">クーポン</span>";
				}

				//求人
				if (lm.getHasjob() > 0) {
					html += "<span class=\"listicon_job2\">求人</span>";
				}
			}

			html += landmark.getName() + "</a></li>"
		}
	}

	html += "</ul>";

	return html;
}



/* =====================================
 *
 * ご近所Pickup
 *
 */
function update_pickup_setCB(landmark) {

	var val;

	if (landmark) {

		//名称
		if ( val = landmark.getName() ) {
			var url = getLandmarkURL(landmark.getId());
			$('pickupname').innerHTML = 
				"<a href=\"" + url + "\" target=\"_blank\" >" + val + "</a>";
		}

		//ご近所Pickupメッセージ
		if ( val = landmark.getPickupmsg() ) {
			$('pickupmsg').innerHTML = val;
		} else {
			$('pickupmsg').innerHTML = '';
		}

		//ご近所Pickup写真ファイル名
		var url = "/photo/noimage.jpg";
		if ( val = landmark.getPickupphoto() ) {
			url = val;
		}

		$('pickupphoto').src = url;
		$('pickupphoto').onclick = "photoLopen(\'" + url + "\')";

		document.getElementById('pickup').style.display = "block";
	}
	else {
//		alert("error");
	}
}

function update_pickup() {

//	loadPickup("user=" + r500m_userid, update_pickup_setCB); 
	loadPickup(getbaseparam(), update_pickup_setCB); 

	setTimeout("update_pickup()", 60000*10);
}

function update_pickup_hidden() {
	document.getElementById('pickup').style.display = "none";
}

function clear_pickup() {
	$('pickupname').innerHTML = '';
	$('pickupmsg').innerHTML = '';
	$('pickupphoto').src = '';
	document.getElementById('pickup').style.display = "none";
}


/* =====================================
 *
 * クーポン
 *
 */
function read_coupon() {

	var list = readCouponList(true, getbaseparam(), null);

	if (list) {
		curCouponList = list.getTopicAll();
		curBirthdayCouponList = list.getTopic('クーポン', '誕生日');
		curJoinCouponList = list.getTopic('クーポン', '入会');
	}

}

function clear_coupon() {
	curCouponList = null;
	curBirthdayCouponList = null;
	curJoinCouponList = null;
}


/* =====================================
 *
 * トップライン
 *
 */

var toplineType = 0;
var toplineReadReq = 0;
var toplineReadCount = 0;
var toplineIndex = 0;
var toplineList = null;
var cyuihouIndex = 0;
var cyuihouList = null;

var updatereq_toplineID = null;
var stop_toplineID = null;
var restart_toplineID = null;
var draw_toplineID = null;

/*
updatereq_topline
stop_topline
restart_topline
draw_topline
*/

function init_topline() {

	//トップライン記事読み込み
	readTopicList(true, getbaseparam() + "&ontopline&withtopline", null, false, read_toplineCB);

	//トップライン記事再読み込み
	updatereq_toplineID = setTimeout("updatereq_topline()", 60000 * 10);
//	setTimeout("updatereq_topline()", 10000 * 1);
}

function clear_topline() {

	toplineType = 0;
	toplineReadReq = 0;
	toplineReadCount = 0;
	toplineIndex = 0;
	toplineList = [];
	cyuihouIndex = 0;
	cyuihouList = [];

	if (updatereq_toplineID) {
		clearTimeout(updatereq_toplineID);
		updatereq_toplineID = null;
	}
	if (stop_toplineID) {
		clearTimeout(stop_toplineID);
		stop_toplineID = null;
	}
	if (restart_toplineID) {
		clearTimeout(restart_toplineID);
		restart_toplineID = null;
	}
	if (draw_toplineID) {
		clearTimeout(draw_toplineID);
		draw_toplineID = null;
	}

	$('msg_headline').innerHTML = '';

}

function updatereq_topline() {

	if ((toplineList.length > 0) || (cyuihouList.length > 0)) {
		//表示中の場合は記事更新フラグを立てる
		toplineReadReq = 1;
	} else {
		//表示がない場合は読み込み
		update_topline();
	}

	updatereq_toplineID = setTimeout("updatereq_topline()", 60000 * 10);
//	setTimeout("updatereq_topline()", 10000 * 1);
}

function update_topline() {

	toplineReadReq = 0;

	if (++toplineReadCount >= 6) {
		toplineReadCount = 0;
		//すべて再読み込み
		readTopicList(true, getbaseparam() + "&ontopline&withtopline", null, false, read_toplineCB);
	} else {
		//注意報警報のみ読み込み
		readTopicList(true, getbaseparam() + "&ontopline&category2=注意報警報", null, false, read_cyuihouCB);
	}
}

function read_toplineCB(list) {

	toplineIndex = 0;
	toplineList = [];
	cyuihouIndex = 0;
	cyuihouList = [];

	if (curBirthdayCouponList) {
		topic = new Topic();
		topic.setCategory1('クーポン');
		topic.setCategory2('誕生日');
		topic.setHeadline( r500m_nickname + 'さんお誕生日おめでとうございます。お祝いのクーポンをご用意致しております。' );
		toplineList.push(topic);
	}

	if (curJoinCouponList) {
		topic = new Topic();
		topic.setCategory1('クーポン');
		topic.setCategory2('入会');
		topic.setHeadline( r500m_nickname + 'さんご入会ありがとうございます。ご入会感謝のクーポンをご用意致しております。' );
		toplineList.push(topic);
	}

	if (list) {
		var data = list.getTopicAll();
		for(var idx = 0; idx < data.length ; idx++){
			var topic = data[idx];

			if (topic.getCategory2() == '注意報警報') {
				cyuihouList.push(topic);
			} else {
				toplineList.push(topic);
			}
		}
	}

	if ((toplineList.length > 0) || (cyuihouList.length > 0)) {
		draw_topline();
	}
}

function read_cyuihouCB(list) {

	cyuihouIndex = 0;
	cyuihouList = [];

	if (list) {
		cyuihouList = list.getTopicAll();
	}

	if ((toplineList.length > 0) || (cyuihouList.length > 0)) {
		draw_topline();
	}
}

function get_topline_topic() {
	var topic = null;
	if ((toplineList) && (toplineList.length > 0)) {
		topic = toplineList[toplineIndex++];
		if (toplineIndex >= toplineList.length) {
			toplineIndex = 0;
		}
	}
	return topic;
}

function get_topline_cyuihou() {
	var topic = null;
	if ((cyuihouList) && (cyuihouList.length > 0)) {
		topic = cyuihouList[cyuihouIndex++];
		if (cyuihouIndex >= cyuihouList.length) {
			cyuihouIndex = 0;
		}
	}
	return topic;
}


function draw_topline() {

	var topic = null;

	if (toplineType == 0) {
		if (!(topic = get_topline_topic())) {
			topic = get_topline_cyuihou();
		}
	}
	else {
		if (!(topic = get_topline_cyuihou())) {
			topic = get_topline_topic();
		}
	}

	if (topic) {
		toplineType = 1 - toplineType;
		set_topline_msg(topic);
		stop_toplineID = setTimeout("stop_topline()", 1000 * 4);
	}
}

function stop_topline() {
	$('topline_marquee').stop();
	restart_toplineID = setTimeout("restart_topline()", 1000 * 12);
}

function restart_topline() {
	$('topline_marquee').behavior = "scroll";
	$('topline_marquee').start();

	if (toplineReadReq > 0) {
		//トップライン記事再読み込み
		update_topline();
	} else {
		draw_toplineID = setTimeout("draw_topline()", 1000 * 4);
	}
}


function set_topline_msg(topic) {

	if (topic) {

		var url;
		var str;

		if (topic.getCategory1() == 'クーポン') {
			url = "./couponview.php";
		}
		else {
			url = getTopicURL(topic.getId());
		}

		var style = "white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;";
		var hline = topic.getHeadline();

		if ((topic.getCategory2() == '注意報警報') && (hline)) {
			if (hline.indexOf('警報') >= 0) {
				style += "color:red;"
			} else {
//				style += "color:#999C18;"
				style += "color:#c0b000;"
//				style += "color:#ffc030;"
			}
		}

		var line = "<a href=\"" + url + "\" " +
			"style = \"" + style + "\" " +
			 " target=\"_blank\" >" +
			"<marquee id=\"topline_marquee\" behavior=\"slide\" direction=\"left\" hspace=\"5px\" scrolldelay=\"30\" truespeed loop=\"1\" width=\"620px\" >";

		//投稿者がランドマーク
		var owc = topic.getOwner_class();
		if ((owc) && ((owc == '80') || (owc == '81')) &&
			((str = topic.getOwnername())) && (str.length > 0)) {
			line += "<strong>" + topic.getStart_date_short() + "</strong>" + "　" + hline + " - " + str;
		} else {
			line += hline;
		}

		line += "</marquee></a>";

		$('msg_headline').innerHTML = line;
	}
}

/* =====================================
 *
 * ログインエラー
 *
 */
function init_error_dialog() {

	dialogWin = new LayerDialog('errormsg');
	dialogWin.setShadowOpacity(0.05);

	var loginerrorhtml  = 

'<div class="miniheader">' +
'  <table width="100%" border="0" cellspacing="13" cellpadding="0">' +
'    <tr>' +
'      <td align="left" width="80px;" width="20px;"><img src="img/common/minilogo.gif" ></td>' +
'      <td align="left"><h4 align="left"><span>ログインエラー</span></h4></td>' +
'    </tr>' +
'  </table>' +
'</div>' +

'<div style="padding:30px;">ユーザーまたはパスワードが違います。</div>' +
'<div class="minifooter" style="padding:10px;">' +
'  <h4><a href="" onclick="loginerror_regist();return false" style="font-size:80%;color:blue;">ユーザー登録する<a>' +
'      <span>　　</span>' +
'  <a href="" onclick="loginerror_close();return false" style="font-size:80%;color:white;">閉じる<a></h4>' +
'</div>';

	dialogWin.setHTML(loginerrorhtml);
}


function show_error_message(title, msg, width, height, top) {

	var loginerrorhtml  = 
'<div class="miniheader">' +
'  <table width="100%" border="0" cellspacing="13" cellpadding="0">' +
'    <tr>' +
'      <td align="left" width="80px;" width="20px;"><img src="img/common/minilogo.gif" ></td>' +
'      <td align="left"><h4 align="left"><span>' + title + '</span></h4></td>' +
'    </tr>' +
'  </table>' +
'</div>' +

'<div style="padding:30px;">' + msg + '</div>' +
'<div class="minifooter" style="padding:10px;">' +
'  <h4><a href="" onclick="loginerror_regist();return false" style="font-size:80%;color:blue;">ユーザー登録する<a>' +
'      <span>　　</span>' +
'  <a href="" onclick="loginerror_close();return false" style="font-size:80%;color:white;">閉じる<a></h4>' +
'</div>';

	dialogWin.setHTML(loginerrorhtml);

	dialogWin.showXCenter(width, height, top);
}


function loginerror_regist() {
	dialogWin.hide();
	location.href = "https://" + ssl_host() + "/useredit.php";
}

function loginerror_close() {
	dialogWin.hide();
}

function resize() {

	if (dialogWin) {
		dialogWin.resize();
	}
}


/* =====================================
 *
 * バナー
 *
 */
function banner_readCB(bannerList) {

	if (!bannerList) {
//		alert('バナーなし');
		$('banner_block').innerHTML = "";
		$('banner_block').style.marginBottom = '0';
		return;
	}else{
		$('banner_block').style.marginBottom = '20px';
	}


	var bannerdata = "<ul>";
	var count = 0;
	var list = bannerList.getBannerAll();

	if (list) {
		for(var idx = 0; idx < list.length; idx++) {
			var banner = list[idx];

			var imagefile = banner.getImage();

			if (imagefile) {
				imagefile = '/photo/' + imagefile;
			} else {
				imagefile = '/img/banner/banner_w.gif';
			}

			bannerdata += 
				'<li><a href="" onclick="banner_click(\'' + banner.getId() + '\'); return false">' +
				'<img src="' + imagefile + '" ></a></li>';
			count++;
		}
	}

	for(var idx=count; idx < 6; idx++) {
		//bannerdata += "<li><a href=\"#\"><img src=\"img/banner/banner_w.gif\" alt=\"\"></a></li>";
		bannerdata += "<li><a href=\"http://r500m.com\"><img src=\"/img/banner/r500m_banner_137x38.gif\" alt=\"\"></a></li>";
	}

	$('banner_block').innerHTML = bannerdata + "</ul>";
}


function banner_bottom_update() {

 	//バナー下の取得
	readBannerList(true, getbaseparam(), 0, 6, banner_readCB);

	setTimeout("banner_bottom_update()", 60000 * 10);
//	setTimeout("banner_bottom_update()", 60000 * 1);
}

function banner_bottom_init() {

 	//バナー下の取得
	var bannerList = readBannerList(true, getbaseparam(), 0, 6, null);
	banner_readCB(bannerList);
	if (!bannerList) {
		if (headlineTab[main_topic_tabtable['ブログ']]) {
			maintabsetbyobj( $( main_topic_tabtable['ブログ'] ) );
		}
	}

}

function banner_click(id) {

	var banner = readBanner(false, id, null, null);
	if (banner) {
		window.open(getLandmarkURL(banner.getOwnerid()), '', '');
	}
}


/* =====================================
 *
 */

/*
if (window.addEventListener) {
	window.addEventListener("load", toppage_init, false);
	window.addEventListener("resize", resize, false);
}
else if (window.attachEvent) {
	window.attachEvent("onload", toppage_init);
	window.attachEvent("onresize", resize);
}
*/


/* =====================================
 *
 * もっと見る
 *
 */

function popup_topic() {
	var cat = null;
	switch(get_currenttabname()) {
	case 'news':		cat = 'ニュース';	break;
	case 'dining':		cat = '食事';	break;
	case 'shopping':	cat = '買い物|その他';	break;
	case 'community':	cat = 'コミュニティ';	break;
	case 'bbs':			popup_bbs();	return;
	}
	_popup_open(cat, '/topic_win.html?category1=' + cat, 700, 440);

}

function popup_topic_cat(cat) {
	_popup_open(cat, './topic_win.html?category1=' + cat, 700, 440);
}

function popup_bbs() {
	_popup_open('BBS', './bbs_win.html', 700, 500);
}

function popup_recomend() {
	_popup_open('RECOMEND', './recomend_win.php', 328, 480);
}

function popup_traffic() {
	_popup_open('TRAFFIC', './traffic_win.html', 520, 500);
}

function _popup_open(key, url, w, h) {
	var win = popup_get(key);
	if (win) {
		win.focus();
	} else {
		popup_push(key, popopen(url, w, h));
	}
}


/* =====================================
 *
 * POPUPウィンドウ
 *
 */

function popup_push(key, win) {
	popupWin[key] = win;
}

function popup_pop(key) {
	popupWin[key] = null;
}

function popup_get(key) {
	return popupWin[key];
}

function popup_clear() {
	for(var key in popupWin) {
		var win = popupWin[key];
		if (win) {
			win.close();
			popupWin[key] = null;
		}
	}
}


/* =====================================
 *
 * exit
 *
 */
function exit_topwin() {

	//POPUPウインドウ
	popup_clear();

}


