/**************************************************************************
 * グローバル変数
 *************************************************************************/

// 店舗XMLデータオブジェクト 
var shopObj = null;

// 協業店舗表示フラグ 
var kyougyou = null;

// プロモーションコード
var pro_cd = null;

// フォームリストオブジェクト 
var formArray = new Array();

// ハンドラリストオブジェクト※キーはフォームID
var handlerArray = new Array();

// 店舗一覧タグID / 都道府県コード 
var shopListTagId = null;
var stateId = null;

// 各種URL
var yoyakuUrl;
var cloudUrl;
if ( location.hostname.indexOf( "iccheck." ) != -1 ) {
	yoyakuUrl = "http://iccheck.www.hokende.com/hokende2/shopcal/calendar.asp";
	cloudUrl = "http://iccheck.www.hokende.com/hokende2/shopcal/get_ShopList.asp?cb=setTempoJason";
} else if ( location.hostname.indexOf( "before." ) != -1 ) {
	yoyakuUrl = "http://before.www.hokende.com/hokende2/shopcal/calendar.asp";
	cloudUrl = "http://before.www.hokende.com/hokende2/shopcal/get_ShopList.asp?cb=setTempoJason";
} else {
	if ( location.protocol == "https:" ) {
		yoyakuUrl = "https://www.hokende.com/hokende2/shopcal/calendar.asp";
		cloudUrl = "https://www.hokende.com/hokende2/shopcal/get_ShopList.asp?cb=setTempoJason";
	} else {
		yoyakuUrl = "http://www.hokende.com/hokende2/shopcal/calendar.asp";
		cloudUrl = "http://www.hokende.com/hokende2/shopcal/get_ShopList.asp?cb=setTempoJason";
	}
}


// 動的更新対応ドメイン 
var domainList = new Array( 
	"hokende.com",
	"hoken-ichiba.com",
	"8798.net",
	"www.online-hoken.com",
	"www.hoken-sougou.com",
	"www.hoken-ichiba-navi.jp",
	"www.bestprice.net",
	"www.excite.co.jp/insurance",
	"woman.excite.co.jp/lifeplanning/insurance",
	"so-net.ne.jp/money/life-ins/lpo",
	"service.become.co.jp/insurance",

	"hoken-partner.com",
	"hoken-navi-walk.com",

	"atcity.jp",
	"hikaku-hokende.com",
	"hikakuyahonpo.jp",
	"hoken-hikakude.com",
	"hoken-hyakkaten.com",
	"hoken-sagasu.com",
	"idobata-hoken.com",
	"money-komichi.com",
	"seikatsu-avenue.com",
	"seikatsu-dori.com",
	"seikatsu-mart.com",
	"seikatu-techo.com"
);

var hokenIchibaGuideList = { area : [
		{ name : "【北海道・東北】---",
		  states : [
				{ name : "北海道",   url : "http://hokkaido.hoken-ichiba.com/"  },
				{ name : "青森県",   url : "http://aomori.hoken-ichiba.com/"    },
				{ name : "岩手県",   url : "http://iwate.hoken-ichiba.com/"     },
				{ name : "宮城県",   url : "http://miyagi.hoken-ichiba.com/"    },
				{ name : "秋田県",   url : "http://akita.hoken-ichiba.com/"     },
				{ name : "山形県",   url : "http://yamagata.hoken-ichiba.com/"  },
				{ name : "福島県",   url : "http://fukushima.hoken-ichiba.com/" }
			] },
		{ name : "【関東】-----------", 
		  states : [
				{ name : "茨城県",   url : "http://ibaraki.hoken-ichiba.com/"   },
				{ name : "栃木県",   url : "http://tochigi.hoken-ichiba.com/"   },
				{ name : "群馬県",   url : "http://gunma.hoken-ichiba.com/"     },
				{ name : "山梨県",   url : "http://yamanashi.hoken-ichiba.com/" },
				{ name : "埼玉県",   url : "http://saitama.hoken-ichiba.com/"   },
				{ name : "千葉県",   url : "http://chiba.hoken-ichiba.com/"     },
				{ name : "東京都",   url : "http://tokyo.hoken-ichiba.com/"     },
				{ name : "神奈川県", url : "http://kanagawa.hoken-ichiba.com/"  }
			] },
		{ name : "【信越・北陸】-----", 
		  states : [
				{ name : "新潟県",   url : "http://niigata.hoken-ichiba.com/"   },
				{ name : "富山県",   url : "http://toyama.hoken-ichiba.com/"    },
				{ name : "石川県",   url : "http://ishikawa.hoken-ichiba.com/"  },
				{ name : "福井県",   url : "http://fukui.hoken-ichiba.com/"     },
				{ name : "長野県",   url : "http://nagano.hoken-ichiba.com/"    }
			] },
		{ name : "【東海】-----------", 
		  states : [
				{ name : "岐阜県",   url : "http://gifu.hoken-ichiba.com/"      },
				{ name : "静岡県",   url : "http://shizuoka.hoken-ichiba.com/"  },
				{ name : "愛知県",   url : "http://aichi.hoken-ichiba.com/"     },
				{ name : "三重県",   url : "http://mie.hoken-ichiba.com/"       }
			] },
		{ name : "【近畿】-----------", 
		  states : [
				{ name : "滋賀県",   url : "http://shiga.hoken-ichiba.com/"     },
				{ name : "京都府",   url : "http://kyoto.hoken-ichiba.com/"     },
				{ name : "大阪府",   url : "http://osaka.hoken-ichiba.com/"     },
				{ name : "兵庫県",   url : "http://hyogo.hoken-ichiba.com/"     },
				{ name : "奈良県",   url : "http://nara.hoken-ichiba.com/"      },
				{ name : "和歌山県", url : "http://wakayama.hoken-ichiba.com/"  }
			] },
		{ name : "【中国】-----------", 
		  states : [
				{ name : "鳥取県",   url : "http://tottori.hoken-ichiba.com/"   },
				{ name : "島根県",   url : "http://shimane.hoken-ichiba.com/"   },
				{ name : "岡山県",   url : "http://okayama.hoken-ichiba.com/"   },
				{ name : "広島県",   url : "http://hiroshima.hoken-ichiba.com/" },
				{ name : "山口県",   url : "http://yamaguchi.hoken-ichiba.com/" }
			] },
		{ name : "【四国】-----------", 
		  states : [
				{ name : "徳島県",   url : "http://tokushima.hoken-ichiba.com/" },
				{ name : "香川県",   url : "http://kagawa.hoken-ichiba.com/"    },
				{ name : "愛媛県",   url : "http://ehime.hoken-ichiba.com/"     },
				{ name : "高知県",   url : "http://kochi.hoken-ichiba.com/"     }
			] },
		{ name : "【九州・沖縄】-----", 
		  states : [
				{ name : "福岡県",   url : "http://fukuoka.hoken-ichiba.com/"   },
				{ name : "佐賀県",   url : "http://saga.hoken-ichiba.com/"      },
				{ name : "長崎県",   url : "http://nagasaki.hoken-ichiba.com/"  },
				{ name : "熊本県",   url : "http://kumamoto.hoken-ichiba.com/"  },
				{ name : "大分県",   url : "http://oita.hoken-ichiba.com/"      },
				{ name : "宮崎県",   url : "http://miyazaki.hoken-ichiba.com/"  },
				{ name : "鹿児島県", url : "http://kagoshima.hoken-ichiba.com/" },
				{ name : "沖縄県",   url : "http://okinawa.hoken-ichiba.com/"   }
			] }
	]
};


/**************************************************************************
 * 店舗予約ページJUMP
 *
 * @param selectElement 店舗SELECTタグ
 * @param formId フォームID
 *************************************************************************/
function checkDomain() {
	var nowDomain = location.hostname;
	var nowUrl = location.href;

	/* 協業店舗表示フラグが立っていた場合は無条件に協業店舗を表示させる */
	if ( kyougyou != null ) {
		if ( kyougyou == true )
			return true;
		else
			return false;
	}

	for ( var i = 0; i<domainList.length; i++ ) {
		if ( nowDomain.indexOf( domainList[i] ) != -1 || nowUrl.indexOf( domainList[i] ) != -1 ) {
			return true;
		}
	}

	return false;
}


/**************************************************************************
 * 都道府県コンボボックス
 *
 * @param formId フォームID
 *
 * 「フォームID_pref」というIDを持つSELECTタグがない場合はレンダリングする。
 *
 *************************************************************************/
function select_preflist( formId, kyougyou_flg, pro_cdStr ) {
	pushFormArray( formId );

	if ( kyougyou_flg != undefined ) {
		if ( kyougyou == null ) {
			kyougyou = kyougyou_flg;
		}
	}

	var parentElement = document.getElementsByName( formId );

	if ( parentElement == null )
		return;

	var prefSelectElement = document.getElementById( formId + "_pref" );
	/* SELECTタグがなければレンダリング */
	if ( prefSelectElement == null ) {
		document.write( "<select id='" + formId + "_pref' name=\"pref\" class=\"reservation reservation-area\" onChange='render_shop( \"" + formId + "\" );'>\n" );
		document.write( "<option value=\"\">全国</option>\n" );
		document.write( "</select>" );
		// プロモーションコードが付加されていた場合 
		if ( pro_cdStr != undefined ) {
			pro_cd = pro_cdStr;
			document.write( "<input type='hidden' name='pro_cd' value='" + pro_cd + "' />" );
		}
	}

	render_pref();
}


/**************************************************************************
 * 店舗コンボボックス
 *
 * @param formId フォームID
 *
 * 「フォームID_shop」というIDを持つSELECTタグがない場合はレンダリングする。
 *
 *************************************************************************/
function select_shoplist( formId ){
	pushFormArray( formId );

	/* ハンドラ関数が指定されていた場合は格納しておく。 */
	if ( arguments.length >= 2 ) {
		handlerArray[formId] = arguments[1];
	}

	var parentElement = document.getElementsByName( formId );
	if ( parentElement == null )
		return;

	var shopSelectElement = document.getElementById( formId + "_shop" );
	/* SELECTタグがなければレンダリング */
	if ( shopSelectElement == null ) {
		document.write( "<select id=\"" + formId + "_shop\" name=\"shop_id\" class=\"reservation reservation-shop\" onChange=\"select_shop( this, '" + formId + "' );\">" );
		document.write( "<option value=\"\">店舗を選択してください。</option>\n" );
		document.write( "</select>" );
	}

	render_shop();
}


/**************************************************************************
 * 保険市場ガイドショップ一覧
 *************************************************************************/
function unordershoplist( tagId, todofukenID ) {
	shopListTagId = tagId;
	stateId = todofukenID;

	document.write( "<dl id='" + tagId + "'>\n" );
	document.write( "</dl>\n" );
}


/**************************************************************************
 * 保険市場ガイドショップ一覧レンダリング
 *************************************************************************/
function render_unordershoplist() {
	// XMLデータが存在していれば店舗アイテム追加 
	if ( shopObj != null ) {
		var ulElement = document.getElementById( shopListTagId );
		if ( ulElement != null ) {
			var length = 0;
			var brandname = null;
			for ( var i=0; i<shopObj['xml']['rs:data']['z:row'].length; i++ ) {
				if ( stateId == shopObj['xml']['rs:data']['z:row'][i]['-KOUMOKUMEI'] ){
					if ( length > 50 ) {
						var brElement = document.createElement( "br" );
						ulElement.appendChild( brElement );
						length = 0;
					}

					if ( brandname == null || brandname != shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'] ) {
						var divlement = document.createElement( "dt" );
						divlement.innerHTML = "【" + shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'] + "】";
						ulElement.appendChild( divlement );
						length = 0;
						brandname = shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'];
					}

					var liElement = document.createElement( "dd" );
					liElement.className="shop-total";
					liElement.innerHTML = "<a href='" + yoyakuUrl + "?shop_id=" + shopObj['xml']['rs:data']['z:row'][i]['-ID'] + "' target='_blank' rel='external'>" + shopObj['xml']['rs:data']['z:row'][i]['-DISPLAY_NAME'] + "</a>";
					ulElement.appendChild( liElement );
					length += (3 + shopObj['xml']['rs:data']['z:row'][i]['-DISPLAY_NAME'].length);
				}
			}
		}
	}
}


/**************************************************************************
 * 保険市場ガイド都道府県コンボボックス
 *
 * @param formId フォームID
 *************************************************************************/
function render_HokenIchibaGuide() {
	// JASONデータが存在していれば都道府県アイテム追加 
	if ( shopObj != null ) {
		var prefSelectElement = document.getElementById( 'hoken-ichiba-guide' );
		if ( prefSelectElement != null ) {
			prefSelectElement.innerHTML = '';

			if ( prefSelectElement.tagName == 'SELECT' ) {
				prefSelectElement.innerHTML = '';
				var todofukenCount = 0;

				prefSelectElement.length++;
				prefSelectElement.options[todofukenCount].value = "";
				prefSelectElement.options[todofukenCount].text = "都道府県を選択";
				todofukenCount++;

				// エリアループ 
				for ( var i = 0; i<hokenIchibaGuideList.area.length; i++ ) {
					var addAreaLine = false;
					// 登録都道府県ループ 
					for ( var j = 0; j<hokenIchibaGuideList.area[i].states.length; j++ ) {
						var foundState = false;
						for ( var k = 0; k<shopObj['xml']['rs:data']['z:row'].length; k++ ) {
							// 保険市場のみ 
							if ( shopObj['xml']['rs:data']['z:row'][k]['-COMPANY_ID'] != 1 )
								continue;

							if ( hokenIchibaGuideList.area[i].states[j].name == shopObj['xml']['rs:data']['z:row'][k]['-KOUMOKUMEI'] ) {
								foundState = true;
								break;
							}
						}
						if ( foundState == true ) {
							if ( addAreaLine == false ) {
								prefSelectElement.length++;
								prefSelectElement.options[todofukenCount].value = "";
								prefSelectElement.options[todofukenCount].text = hokenIchibaGuideList.area[i].name;
								todofukenCount++;
								addAreaLine = true;
							}
							prefSelectElement.length++;
							prefSelectElement.options[todofukenCount].value = hokenIchibaGuideList.area[i].states[j].url;
							prefSelectElement.options[todofukenCount].text = hokenIchibaGuideList.area[i].states[j].name;
							todofukenCount++;
						}
					}
				}
			}
		}
	}
}

/**************************************************************************
 * 都道府県コンボボックス
 *
 * @param formId フォームID
 *
 * １）「フォームID_pref」というIDを持つSELECTタグがない場合はレンダリングする。
 * ２）既にshopObjが生成されていた場合は、都道府県リスト追加も同時に行う。
 *
 * １と２を同時に行う理由は、Ajaxによる通信完了が初期レンダリングを追い越す場合が存在するからである
 *
 *************************************************************************/
function render_pref( formId ) {
	// JASONデータが存在していれば都道府県アイテム追加 
	if ( shopObj != null ) {
		var prefSelectElement = document.getElementById( formId + "_pref" );
		if ( prefSelectElement != null ) {
			if ( prefSelectElement.tagName == 'SELECT' ) {
				var todofukencode = null;
				var todofukenCount = 1;
				prefSelectElement.length = 1;
				for( var i=0; i<shopObj['xml']['rs:data']['z:row'].length; i++ ){
					if ( todofukencode == shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'] )
						continue;

					prefSelectElement.length++;
					prefSelectElement.options[todofukenCount].value = shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'];
					prefSelectElement.options[todofukenCount].text = shopObj['xml']['rs:data']['z:row'][i]['-KOUMOKUMEI'];
					todofukencode = shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'];
					todofukenCount++;
				}
			}
		}
	}
}


/**************************************************************************
 * 店舗コンボボックス
 *
 * @param formId フォームID
 *
 * １）「フォームID_shop」というIDを持つSELECTタグがない場合はレンダリングする。
 * ２）既にshopObjが生成されていた場合は、ショップリスト追加も同時に行う。
 *
 * １と２を同時に行う理由は、Ajaxによる通信完了が初期レンダリングを追い越す場合が存在するからである
 *
 *************************************************************************/
function render_shop( formId ){
	// JASONデータが存在していれば店舗アイテム追加 
	if ( shopObj != null ) {
		var prefSelectElement = document.getElementById( formId + "_pref" );
		var shopSelectElement = document.getElementById( formId + "_shop" );
		if ( shopSelectElement != null ) {
			shopSelectElement.length = 1;
			var shopCount = 1;
			var todoufukenCode = null;
			var brandname = null;
			for ( var i=0; i<shopObj['xml']['rs:data']['z:row'].length; i++ ) {
				if ( (prefSelectElement == null || prefSelectElement.value == '') && todoufukenCode != shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'] ) {
					shopSelectElement.length++;
					shopSelectElement.options[shopCount].value = "";
					shopSelectElement.options[shopCount].text = "------ " + shopObj['xml']['rs:data']['z:row'][i]['-KOUMOKUMEI'] + " -----------------------";
					shopCount++;
					todoufukenCode = shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'];
					brandname = null;
				}

				if ( prefSelectElement == null || prefSelectElement.value == '' || prefSelectElement.value == shopObj['xml']['rs:data']['z:row'][i]['-TODOFUKEN_CODE'] ){
					if ( checkDomain() == true ) {
						if ( brandname == null || brandname != shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'] ) {
							shopSelectElement.length++;
							shopSelectElement.options[shopCount].value = "";
							shopSelectElement.options[shopCount].text = "【" + shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'] + "】";
							shopCount++;
							brandname = shopObj['xml']['rs:data']['z:row'][i]['-BRAND_NAME'];
						}
					}

					var strShopName = "　" + shopObj['xml']['rs:data']['z:row'][i]['-DISPLAY_NAME'];
					if ( shopObj['xml']['rs:data']['z:row'][i]['-COMPANY_ID'] != 1 )
						strShopName = strShopName + "(協力店)";
					shopSelectElement.length++;
//					shopSelectElement.options[shopCount].value = shopObj['xml']['rs:data']['z:row'][i]['-TEMPO_CD'];
					shopSelectElement.options[shopCount].value = shopObj['xml']['rs:data']['z:row'][i]['-ID'];
					shopSelectElement.options[shopCount].text = strShopName;
					shopCount++;
				}
			}
		}
	}
}



/**************************************************************************
 * 店舗選択時ハンドラ関数呼び出し処理
 *
 * @param shopSelectElement 店舗SELECTタグ
 * @param formId フォームID
 *
 *************************************************************************/
function select_shop( shopSelectElement, formId ) {
	if ( shopSelectElement.value == "" )
		return;

	/* ハンドラ指定時はハンドラ関数呼び出し。指定がなければ相談予約ページへジャンプ  */
	if ( handlerArray[formId] != null ) {
		 handlerArray[formId]();
	} else {
		goSoudanYoyaku( shopSelectElement, formId );
	}
}


/**************************************************************************
 * フォームリスト追加
 *
 * @param text フォームID
 *
 *************************************************************************/
function pushFormArray( text ) {
	for ( var i = 0; i < formArray.length; i++ ) {
		if ( formArray[i] == text ) {
			return;
		}
	}

	formArray.push( text );
}


/**************************************************************************
 * 都道府県＆店舗レンダリング
 *************************************************************************/
function renderer() {
	for ( var i = 0; i < formArray.length; i++ ) {
		render_pref( formArray[i] );
		render_shop( formArray[i] );
	}

	render_unordershoplist();

	render_HokenIchibaGuide();
};


/**************************************************************************
 * 店舗XMLデータ設定
 *
 * @param xmldata 受信XMLデータ
 *************************************************************************/
function setTempoJason( xmldata ) {
	var xotree = new XML.ObjTree();
	shopObj = xotree.parseXML( xmldata );

	renderer();
}


/**************************************************************************
 * 店舗予約ページJUMP
 *
 * @param selectElement 店舗SELECTタグ
 * @param formId フォームID
 *************************************************************************/
function goSoudanYoyaku( selectElement, formId )
{
	var formElement = document.getElementById( formId );

	if ( formElement != null ) {
		sOriginalMethod = formElement.method;
		sOriginalTarget = formElement.target;
		sOriginalAction = formElement.action;

		formElement.method = "get";
		formElement.target = "_blank";
		formElement.action = yoyakuUrl;
		formElement.submit();

		//もとに戻しておく
		formElement.method = sOriginalMethod;
		formElement.target = sOriginalTarget;
		formElement.action = sOriginalAction;

	} else {
		//formが無かったら
		if ( selectElement.options[selectElement.selectedIndex].value != '' ) {
			if ( pro_cd == null )
				location.href = yoyakuUrl + "?shop_id=" + selectElement.options[selectElement.selectedIndex].value;
			else
				location.href = yoyakuUrl + "?shop_id=" + selectElement.options[selectElement.selectedIndex].value + "&pro_cd=" + pro_cd;
		}
	}
}


/**************************************************************************
 * レンダリングハンドラ設定
 *
 * @param selectElement 店舗SELECTタグ
 * @param formId フォームID
 *************************************************************************/
if ( window.attachEvent ) {
	window.attachEvent('onload', renderer);
} else {
	window.addEventListener('load', renderer, false);
}


/**************************************************************************
 * イベントハンドラ設定
 *************************************************************************/
var strProtocol
if ( location.protocol != 'https:' )
	strProtocol = "http:";
else
	strProtocol = "https:";
document.write( "<script language='javascript' type='text/javascript' src='" + strProtocol + "//www.hokende.com/js/ObjTree.js'></script>" );
if ( checkDomain() == true ) {
	document.write( "<script language='javascript' type='text/javascript' src='" + cloudUrl + "'></script>" );
} else {
	document.write( "<script language='javascript' type='text/javascript' src='" + cloudUrl + "&campany=1'></script>" );
}


