<odds>
    <style scoped>
		.no_select{
			display:none!important;
		}
    </style>

	<div if={ race_status >= '90' } class="Race_Infomation_Box">本レースは中止となりました</div>
	<div if={ no_odds_info && race_status < '90' } class="Race_Infomation_Box">車券発売後、順次公開されます</div>

	<virtual if={ Object.keys(cur_race).length > 0 && race_status < '90' }>

		<!-- 式別・方式選択ボタンタイプ -->
		<vurtual if={ bet_mode == 'add' }>

			<div class="RaceOdds_MenuArea">
				<ul class="RaceOdds_MenuArea_list betting">
					<li each={ sno, label in disp_shikibetu }  class="RaceOdds_MenuArea_listInner">
						<button class="{ (sno == cur_shikibetu) ? 'Active' : '' }" onClick={ act_shikibetu.bind(this, sno) }>{ label }</button>
					</li>
				</ul>
			</div>
			<div if={ (1 < cur_shikibetu) } class="RaceOdds_MenuArea RaceOdds_MenuArea02">
				<ul class="RaceOdds_MenuArea_list RaceOdds_MenuArea_list02">
					<li each={ hno1 in display_houshiki_button1 } class="RaceOdds_MenuArea_listInner col_{ hno1 >= 10 ? '2' : '3' }" if={ edit_houshiki_button1_disable(hno1) }>
						<button class="{ (hno1 == cur_houshiki_1) ? 'Active' : ''}" onClick={ act_houshiki_1.bind(this, hno1) }>{ houshiki_button1[hno1] }</button>
					</li>
				</ul>
			</div>
			<div class="RaceOdds_MenuArea RaceOdds_MenuArea02" if={ ('3' == cur_houshiki_1 && '8' <= cur_shikibetu) || ('3' == cur_houshiki_1 && '6' == cur_shikibetu) }>
				<ul>
					<li class="{ (hno2 == cur_houshiki) ? 'Active' : '' }" each={ label2,hno2 in houshiki_button2[cur_shikibetu] }>
						<a href="javascript:void(0)" onClick={ act_houshiki.bind(this, hno2)  }>{ label2 }</a>
					</li>
				</ul>
				<div class="Multi_Select" if={multi_attr}>
					<span><input type="checkbox" class="MultiCheck" onClick={ act_multi.bind(this) } checked={ (multi) ? 'checked' : '' } id="MultiCheck"/>
					<label for="MultiCheck">マルチ</label></span>
				</div>
			</div>
		</vurtual>

	<div class="RaceOdds_List mt10">
		<!--div if={ cur_houshiki == '10' } class="RaceOdds_PopularList">
			<div class="RaceOdds_PopularList_inner">
				<div class=""><span>1～100人気</span></div>
				<select id="sort-select" name="sort-select">
					<option each={ label, idx in ninki_select_box } value="{idx}">{ label }</option>
				</select>
			</div>
		</div-->

		<div if={ cur_houshiki == '11' } class="RaceOdds_OddsChart">
			<div class="OddsChart_player" if={ cur_shikibetu == '8' || cur_shikibetu == '9' }>
				<div>
					<label for="entry_axis">軸：</label>
					<div class="RaceOdds_OddsChart_inner">
						<div class=""><span>{ jiku_select }. { race_horse[jiku_select]['name'] }</span></div>
						<select id="entry_axis" name="entry_axis" onchange={ act_select_jiku.bind(this) }>
							<option value="{ idx }" each={ val, idx in race_horse } >{val['syaban']}. {val['name']}</option>
						</select>
					</div>
				</div>
			</div>
			<div class="OddsChart_rank" if={ cur_shikibetu == '9' }>
				<div>
					<div class="RaceOdds_OddsChart_inner">
						<div class=""><span>{ chaku_select }着</span></div>
						<select id="number_axis" name="number_axis" onchange={ act_select_chaku.bind(this) }>
							<option value="1">1着</option>
							<option value="2">2着</option>
							<option value="3">3着</option>
						</select>
					</div>
				</div>
			</div>
		</div>

		<div>
			<div class="Contents_Header">
				<div class="Type_Sec Type_BgColor0{ cur_shikibetu }">
					<h2>{disply_bet_label[cur_shikibetu]}</h2>
				</div><!-- /.Title_Sec -->
			</div>

			<!-- 単勝選択時 -->
			<div if={ cur_shikibetu == 1 } class="TableSlideArea">
				<table summary="単勝オッズ" class="RaceCard_Table RaceCard_Simple_Table OddsSelectTable">
					<tbody>
						<tr class="Header">
							<th class="RaceCard_Th01 Result_Num">人<br>気</th>
							<th class="RaceCard_Th01 WakuCell">車番</th>
							<th class="RaceCard_Th01 Shirusi">印</th>
							<th class="RaceCard_Th01 CheckMark">選択</th>
							<th class="Player_Info">選手名</th>
							<th class="RaceCard_Th02" style="width:88px">オッズ</th>
						</tr>
						<!--tr class="PlayerList { race_horse[uix + 1]['sales_sts'] == '1' || race_horse[uix + 1]['sales_sts'] == '3' ? 'torikeshi' : ''}" id="tr_{uix+ 1}" each={ ary_row,uix in data_number_v }-->
						<tr class="PlayerList { race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] == '1' || race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] == '3' ? 'torikeshi' : ''} { select_odds_active(ary_row[0].replace(/^0/, '')) ? 'Selected' : '' }" id="tr_{uix}" onClick={act_select_number.bind(this, ary_row[0].replace(/^0/, ''))} each={ ary_row,uix in odds_ninki[cur_shikibetu] }>
							<td class="RaceCardCell01 Result_Num">{ uix + 1 }</td>
							<td class="RaceCardCell01 Waku{ ary_row[0].replace(/^0/, '') }">{ ary_row[0].replace(/^0/, '') }</td>
							<td class="RaceCardCell01 Shirusi">
								<!--span if={ my_mark[race_horse[uix]['syaban']] } class="MarkIcon Mark{ my_mark[race_horse[uix]['syaban']] }"></span-->
								<!--span>{ my_mark_label[my_mark[race_horse[uix]['syaban']]] }</span-->
								<svg if={ my_mark[race_horse[ary_row[0].replace(/^0/, '')]['syaban']] } class="Icon_Shirushi01 Icon_{ edit_kaime_mark(my_mark[race_horse[ary_row[0].replace(/^0/, '')]['syaban']], true, cur_shikibetu) }">
									<use xlink:href="/common/img/icon/icon_shirushi.svg#icon-{ edit_kaime_mark(my_mark[race_horse[ary_row[0].replace(/^0/, '')]['syaban']], false, cur_shikibetu) }"></use>
								</svg>
							</td>
							<td if={ race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] != '1' &&  race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] != '3' } class="Player_Select">
								<div>
									<input type="checkbox" class="HorseCheck_Select" id="uc-{uix}" name="" value="1"
										checked={select_odds_active(ary_row[0].replace(/^0/, '')) ? true : false}
										onClick={act_select_number.bind(this, ary_row[0].replace(/^0/, ''))}
										/>
									<label for="uc-{uix}" class="Check01Btn_Off" ></label>
								</div>
							</td>
							<td if={ race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] == '1' || race_horse[ary_row[0].replace(/^0/, '')]['sales_sts'] == '3' } class="Player_Select">
								<div>取消</div>
							</td>
							<td class="Player_Info">{ race_horse[ary_row[0].replace(/^0/, '')]['name'] }</td>
							<td class="RaceCardCell01"><span class="{ check_odds(ary_row[1]) }">{ ijyo_list[ary_row[0].replace(/^0/, '')] ? '取消' : sprintf("%0.1f", ary_row[1]) }</span></td>
						</tr>
					</tbody>
				</table>
			</div><!-- /.TableSlideArea -->

			<!-- 単勝以外の選択時 -->
			<div class="TableSlideArea" if={ bet_mode == 'add' && '1' != cur_shikibetu && 10 > cur_houshiki }>
				<div class="umaban_container">
					<table class="RaceCard_Table RaceOdds_HorseList_Table">
						<thead>
							<tr class="col_label">
								<th class="Waku">枠番</th>
								<th class="Waku">車番</th>
								<th class="Mark">予想</th>
								<th>選手名</th>
								<th each={ tmp,rix in data_number_v[0] } if={ edit_show_column(rix, 'in') } style="width: 50px;">
									<span>{edit_label(rix)}</span>
								</th>
							</tr>
						</thead>
						<tbody>
							<tr if={ race_horse[uix + 1] } class="{ race_horse[uix + 1]['sales_sts'] == '1' || race_horse[uix + 1]['sales_sts'] == '3' ? 'torikeshi' : ''}" id="tr_{uix+ 1}" each={ ary_row,uix in data_number_v }>
								<td class="Waku">{race_horse[uix + 1]['wakuban']}</td>
								<td class="Waku{ uix + 1 }">{ uix + 1 }</td>
								<td class="Mark_User">
									<!--span if={ my_mark[race_horse[uix + 1]['syaban']] } class="MarkIcon Mark{ my_mark[race_horse[uix + 1]['syaban']] }"></span-->
									<!--span>{ my_mark_label[my_mark[race_horse[uix + 1]['syaban']]] }</span-->
									<svg if={ my_mark[race_horse[uix + 1]['syaban']] } class="Icon_Shirushi01 Icon_{ edit_kaime_mark(my_mark[race_horse[uix + 1]['syaban']], true, cur_shikibetu) }">
										<use xlink:href="/common/img/icon/icon_shirushi.svg#icon-{ edit_kaime_mark(my_mark[race_horse[uix + 1]['syaban']], false, cur_shikibetu) }"></use>
									</svg>
								</td>
								<td class="Player_Info">
									<dl>
										<dt class="PlayerName">
										{ race_horse[uix + 1]['name'] }
										</dt>
										<dd class="PlayerFrom">{ race_horse[uix + 1]['fuken'] } { race_horse[uix + 1]['age'] }歳</dd>
										<!--dd class="PlayerClass">{ race_horse[uix + 1]['graduate'] }期 { race_horse[uix + 1]['kyu'] }{ race_horse[uix + 1]['han'] } <em>{ sprintf('%.2f', race_horse[uix + 1]['rating']) }</em></dd-->
									</dl>
								</td>
								<td each={ row,rix in ary_row } if={ race_horse[uix + 1]['sales_sts'] != '1' &&  race_horse[uix + 1]['sales_sts'] != '3' && edit_show_column(rix, 'in') } class="Player_Select">
									<div if={ edit_show_column(rix, 'in') }>
										<input type="{ edit_show_input_type(rix) }" class="HorseCheck_Select" id="uc-{rix}-{uix + 1}" name="" value="1"
											checked={edit_number_active(rix,uix + 1) ? true : false}
											disabled={edit_number_disable(rix,uix + 1) ? true : false}
											onClick={act_number.bind(this, rix, uix + 1)}/>
										<label for="uc-{rix}-{uix + 1}" class="Check01Btn_Off" ></label>
									</div>
								</td>
								<td if={ race_horse[uix + 1]['sales_sts'] == '1' || race_horse[uix + 1]['sales_sts'] == '3' } class="Player_Select" colspan="{ check_column(rix, 'in') }">
									<div>取消</div>
								</td>
							</tr>
							<tr class="ActionBtn">
								<td colspan="4" class="Txt">
									<div>
										<span>印の選手を選択</span>
									</div>
								</td>
								<td each={ tmp, rix in btn_func } if={ edit_show_column(rix, 'in') }>
									<div if={ edit_show_column(rix, 'all') }>
										<virtual if={ !btn_func_stat['mark'][rix] }>
											<input type="checkbox" id="btn_mark_{rix}" class="Mark_Action" checked={ btn_func_stat['mark' ][rix] ? true : false} onClick={ act_ext_func.bind(this,'mark', rix) }>
											<label for="btn_mark_{rix}"></label>
										</virtual>
										<virtual if={ btn_func_stat['mark'][rix] }>
											<input type="checkbox" id="btn_mark_{rix}" class="Mark_Action" checked={ btn_func_stat['mark'][rix] ? true : false} onClick={ act_ext_func.bind(this,'clear', rix) }>
											<label for="btn_mark_{rix}"></label>
										</virtual>
									</div>
								</td>
							</tr>
							<tr class="ActionBtn">
								<td colspan="4" class="Txt">
									<div>
										<span>すべてを選択</span>
									</div>
								</td>
								<td each={ tmp, rix in btn_func } if={ edit_show_column(rix, 'in') }>
									<div if={ edit_show_column(rix, 'all') }>
										<virtual if={ !btn_func_stat['all'][rix] }>
											<input type="checkbox" id="btn_all_{rix}" class="All_Action" checked={ btn_func_stat['all'][rix] ? true : false} onClick={ act_ext_func.bind(this, 'all', rix) }>
											<label for="btn_all_{rix}"></label>
										</virtual>
										<virtual if={ btn_func_stat['all'][rix] }>
											<input type="checkbox" id="btn_all_{rix}" class="All_Action" checked={ btn_func_stat['all'][rix] ? true : false} onClick={ act_ext_func.bind(this, 'clear', rix) }>
											<label for="btn_all_{rix}"></label>
										</virtual>
									</div>
								</td>
							</tr>
					    </tbody>
					</table>
				</div><!-- /.umaban_container -->
			</div> <!-- /.select_item -->

			<!-- 人気順選択時 -->
			<div if={ cur_houshiki == 10 } class="TableSlideArea">
				<table summary="オッズ人気順" class="RaceCard_Table RaceCard_Simple_Table OddsSelectTable">
					<tbody>
						<tr class="Header">
							<th class="RaceCard_Th01 Result_Num">人気</th>
							<th class="RaceCard_Th01 CheckMark">選択</th>
							<th class="Player_Info">選手名</th>
							<th class="RaceCard_Th02" style="width: 88px;">オッズ</th>
						</tr>
						<tr each={ val, ninki in odds_ninki[cur_shikibetu] } if={ check_ijyo(val[0]) } class="PlayerList { select_odds_active(val[0]) ? 'Selected' : '' }" onClick={act_select_number.bind(this, val[0])}>
							<td class="RaceCardCell01 Result_Num">{ninki + 1}</td>
							<td class="Player_Select">
								<input type="checkbox" class="HorseCheck_Select" name="" id="uc-{val[0]}" value="1"
									checked={select_odds_active(val[0]) ? true : false}
									onClick={act_select_number.bind(this, val[0])}
									/>
								<label for="uc-{val[0]}" class="Check01Btn_Off" ></label>
							</td>
							<td class="Combi">
								<div class="Combi_inner">
									<virtual each={ row in edit_combination(val[0], cur_shikibetu, cur_houshiki) }>
										<div>
											<span class="Waku{ row.no }">{ row.no }</span>
											<p>{ race_horse[row.no]['names'] }</p>
										</div>
										<div class="{ (1 == row.type) ? 'hyphen_box' : 'arrow_box' }" if={ row.type > 0}>
											<span></span>
										</div>
									</virtual>
								</div>
							</td>
							<td class="RaceCardCell01"><span class="{ val[1] <= 10 ? 'Highest' : '' }">{ sprintf("%0.1f", val[1]) }</span><span if={ cur_shikibetu == '7' }>～</span><span if={ cur_shikibetu == '7' } class="{ val[2] <= 10 ? 'Highest' : '' }">{ sprintf("%0.1f", val[2]) }</span></td>
						</tr>
					</tbody>
				</table>
			</div><!-- /.TableSlideArea -->

			<!-- オッズ表選択時 -->
			<vvurtual if={ cur_houshiki == 11 } >
				<div class="Odds_MainChart">
					<div>
						<div class="Odds_MainChart_fixed">
							<table>
								<thead>
									<tr>
										<th colspan="2" class="">1着</th>
									</tr>
									<tr>
										<th if={ (cur_shikibetu == 8 || cur_shikibetu == 9) && chaku_select != 3 } colspan="2" class="">2着</th>
										<th if={ (cur_shikibetu == 8 || cur_shikibetu == 9) && chaku_select == 3 } rowspan="{ max_uma }" class="">2着</th>
										<th if={ cur_shikibetu != 8 && cur_shikibetu != 9 } rowspan="{ max_uma + 1 }" class="">2着</th>
									</tr>
									<tr if={ (cur_shikibetu == 8 || cur_shikibetu == 9) && chaku_select != 3 }>
										<th rowspan="{ max_uma }" style="width:48px;">3着</th>
									</tr>
									<tr each={ val, idx in race_horse } if={ is_column(val['syaban']) }>
										<th scope="row" class="Waku{ val['syaban'] } Waku_row">{ val['syaban'] }</th>
									</tr>

									<tr if={ (cur_shikibetu == 8 || cur_shikibetu == 9) && chaku_select == 3 }>
										<th colspan="2" style="width:48px;">3着</th>
									</tr>

								</thead>
							</table>
						</div>
						<div class="Odds_MainChart_static">
							<table class="Odds_MainChart_staticHead">
								<thead>
									<tr>
										<th colspan="2" class="">1着</th>
									</tr>
									<tr>
										<th colspan="2" class="">2着</th>
									</tr>
									<tr if={ cur_shikibetu == 8 || cur_shikibetu == 9 }>
										<th rowspan="{ max_uma }" style="width:48px;">3着</th>
									</tr>
									<tr>
										<th scope="row" class="Waku2 Waku_row">2</th>
									</tr>
									<tr>
										<th scope="row" class="Waku3 Waku_row">3</th>
									</tr>
									<tr>
										<th scope="row" class="Waku4 Waku_row">4</th>
									</tr>
									<tr>
										<th scope="row" class="Waku5 Waku_row">5</th>
									</tr>
									<tr>
										<th scope="row" class="Waku6 Waku_row">6</th>
									</tr>
								</thead>
							</table>
							<table class="Odds_MainChart_staticBody">
								<caption class="Waku{ jiku_select }" if={ (cur_shikibetu == 8 || cur_shikibetu == 9) && chaku_select != 2 } style="caption-side : { chaku_select == 1 ? 'top' : 'bottom' };border-top : { chaku_select == 1 ? '' : 'none' }">
									<div><span class="">{ jiku_select }</span>{ race_horse[jiku_select]['name'] }</div>
								</caption>
								<thead>
									<tr>
										<th each={ val, idx in race_horse } class="Waku{ val['syaban'] }" if={ val['syaban'] != jiku_select || cur_shikibetu != 8 && cur_shikibetu != 9 }>
											<span class="">{ val['syaban'] }</span>{ val['names'] }
										</th>
									</tr>
									<tr if={ chaku_select == 2 }>
										<th class="Waku{ jiku_select }" colspan="5"><span class="">{ jiku_select }</span>{ race_horse[jiku_select]['name'] }</th>
									</tr>
								</thead>
								<tbody>
									<tr each={ tr_val, tr_idx in race_horse } if={ is_column(tr_val['syaban']) }>
										<td each={ val, idx in race_horse } if={ idx != jiku_select || cur_shikibetu != 8 && cur_shikibetu != 9 } class="{ get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) ) ? '' : 'none' }">
											<div if={ get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) ) }>
												<div class="" if={ check_ijyo( '0' + jiku_select + '0' + val['syaban'] + '0' + tr_val['syaban'] ) }>
													<input id="{ make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) }" type="checkbox"
														checked={ select_odds_active( make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) ) ? true : false }
														onClick={act_select_number.bind(this, make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) )}>
													<label for="{ make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) }">
														<span>
															<span class="{ check_odds( get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban'])) ) }">{ get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban']) ) }</span>
															<span if={ cur_shikibetu == '7' }>
																<span>～</span>
																<span class="{ check_odds( get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban'])), true ) }">{ get_odds( make_odds_key(jiku_select, val['syaban'], tr_val['syaban']), true ) }</span>
															</span>
														</span>
													</label>
												</div>
												<div class="none cancel" if={ ! check_ijyo( '0' + jiku_select + '0' + val['syaban'] + '0' + tr_val['syaban'] ) }>
													取消
												</div>
											</div>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</div>
				<div class="Title_Sec">
					<h2>選択済みオッズ一覧</h2>
				</div>
				<div class="TableSlideArea">
					<table class="Odds_SubChart RaceCard_Table ResultRefund">
						<!-- オッズを選択していない時に表示 -->
						<caption class="none_title" if={ Object.keys(select_odds).length <= 0 }>選択しているオッズがありません</caption>
						<!-- オッズを選択していない時に表示 -->
						<thead>
							<tr>
								<th class="">選択</th>
								<th class="">組み合わせ</th>
								<th class="">オッズ</th>
							</tr>
						</thead>
						<tbody if={ Object.keys(select_odds).length >= 1 }>
							<tr class="PlayerList" each={ bool, kaime in select_odds } onclick={ act_select_odds.bind(this, kaime) } >
								<td class="Player_Select">
									<input type="checkbox" id="odds_card_{ kaime }" name="{ kaime }" class="HorseCheck_Select" value="" checked="{ select_odds[kaime] ? true : false }">
									<label for="odds_card_{ kaime }" class="HorseCheckBtn"></label>
								</td>
								<td class="Combi">
									<div class="Combi_inner">
										<virtual each={ row in edit_combination(kaime, cur_shikibetu, cur_houshiki) }>
											<div>
												<span class="Waku{ row.no }">{ row.no }</span>
												<p>{ race_horse[row.no]['names'] }</p>
											</div>
											<div class="{ (1 == row.type) ? 'hyphen_box' : 'arrow_box' }" if={ row.type > 0}>
												<span></span>
											</div>
										</virtual>
									</div>
								</td>
								<td class="RaceCardCell01">
									<span class="">
										<span class="{ check_odds( odds[cur_shikibetu][kaime][1] ) }">{ sprintf("%0.1f", odds[cur_shikibetu][kaime][0]) }</span>
										<span if={ cur_shikibetu == '7' }>～</span>
										<span if={ cur_shikibetu == '7' } class="{ check_odds( odds[cur_shikibetu][kaime][1] ) }">{ sprintf("%0.1f", odds[cur_shikibetu][kaime][1]) }</span>
									</span>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</vurtual>
		</div>
	</div>

		<!--div class="BetTable Bet01"-->
		<div if={ bet_mode == 'add' && cur_shikibetu != '1' && 10 > cur_houshiki } class="BetTable Bet01 { select_kaime ? 'color' : '' }">

			<table class="RaceOdds_Result_Table04" if={ bet_mode == 'add' && odds[cur_shikibetu] && select_bet_odds.length > 0}>
				<thead>
					<tr>
						<th class="th_col_keys Sort_Btn01" onclick={ act_select_odds_sort.bind(this, select_bet_odds, 'kaime') }><button class="sort">組み合わせ</button></th>
						<th class="th_col_odds Sort_Btn01" onclick={ act_select_odds_sort.bind(this, select_bet_odds, 'odds') }><button class="sort">オッズ</button></th>
						<th class="th_col_select">選択</th>
					</tr>
				</thead>

				<tbody class="list">

					<!--tr class="PlayerList" each={ odds_obj, idx in select_bet_odds }>
						<td class="Combi">
							<div class="Combi_inner">
								<virtual each={ row in edit_combination(Object.keys(odds_obj)[0], cur_shikibetu, cur_houshiki) }>
									<div>
										<span class="Waku{ row.no }">{ row.no }</span>
										<p>{ race_horse[row.no]['names'] }</p>
									</div>
									<div class="{ (1 == row.type) ? 'hyphen_box' : 'arrow_box' }" if={ row.type > 0}>
										<span></span>
									</div>
								</virtual>
							</div>
						</td>
						<td class="RaceCardCell01">
							<span class=""><span class="">{ odds[cur_shikibetu][Object.keys(odds_obj)[0]][0] }</span></span>
						</td>
						<td class="Player_Select">
							<input type="checkbox" id="odds_card_{ Object.keys(odds_obj)[0] }" name="{ Object.keys(odds_obj)[0] }" class="HorseCheck_Select" value="" onclick={ act_select_odds.bind(this, Object.keys(odds_obj)[0]) } checked="{ select_odds[Object.keys(odds_obj)[0]] ? true : false }">
							<label for="odds_card_{ Object.keys(odds_obj)[0] }" class="HorseCheckBtn"></label>
						</td>
					</tr-->

					<tr each={ odds_obj, idx in select_bet_odds } class="{ select_odds[Object.keys(odds_obj)[0]] ? 'bg-danger' : '' }" onclick={ act_select_odds.bind(this, Object.keys(odds_obj)[0]) } >
						<td class="Apart">
							<div class="Num">
								<virtual each={ syaban, k in Object.keys(odds_obj)[0].split('0') }>
									<div class="Shaban_InBox ">
										<span if={ syaban != 0 } class="Wakuban Waku{ (cur_shikibetu == 3 || cur_shikibetu == 4) ? '1' : syaban }">{syaban}</span>
										<p if={ race_horse[syaban] }>{ race_horse[syaban]['names'] }</p>
									</div>
									<span if={ k != 0 && Object.keys(odds_obj)[0].split('0').length > k+1 } class={ edit_kaime_class(cur_shikibetu) }></span>
								</virtual>
							</div>
						</td>
						<td class="AssumedOdds">
							<span class="OddsData01" if={ cur_shikibetu != '7' }>{sprintf("%0.1f", Object.values(odds_obj)[0])}</span>
							<span class="OddsData01" if={ cur_shikibetu == '7' }>{sprintf("%0.1f", Object.values(odds_obj)[0].split('_')[0])}</span>
							<span class="OddsData01" if={ cur_shikibetu == '7' }>～</span>
							<span class="OddsData01" if={ cur_shikibetu == '7' }>{sprintf("%0.1f", Object.values(odds_obj)[0].split('_')[1])}</span>
						</td>
						<td class="Select">
							<input class="BuyCheck_Select disp_none" type="checkbox" value="1" id="p-chk_sel_comb_{idx}" onclick={ act_select_odds.bind(this, Object.keys(odds_obj)[0]) } checked="{ select_odds[Object.keys(odds_obj)[0]] ? true : false }" >
							<label class="Check01Btn_Off" for="p-chk_sel_comb_{idx}"> </label>
						</td>
					</tr>
				</tbody>
			</table>
			<div class="Selected_Table" if={ cur_houshiki <= 10 }>
				<div class="Selected_Table_Inner">
					<div class="BetKaime_Table">
						<div id="select_kumiawase" class="kaime_view FormationType">
							<div class="Kenshu">{disply_bet_label[cur_shikibetu]} {houshiki[cur_shikibetu][cur_houshiki]}&nbsp;</div>

							<div class="LabelWrap" if={ btn_uno } each={ tmp,rix in data_number_v[0] }>
								<div class="LabelArrow" if={ edit_label(rix) != '--' }> <span>{edit_label(rix)}</span> </div>
								<div class="Num">
									<virtual if={ btn_uno[rix] && Object.keys(btn_uno[rix]).length >= 1 }>
									<div class="Shaban_InBox" each={ bool, syaban in btn_uno[rix] } if={ bool }>
										<span class="Wakuban Waku{ (cur_shikibetu == 3 || cur_shikibetu == 4) ? '1' : syaban }">{syaban}</span>
										<svg if={ my_mark[syaban] && cur_shikibetu != 3 && cur_shikibetu != 4  } class="Icon_Shirushi01 Icon_{ edit_kaime_mark(my_mark[syaban], true, cur_shikibetu) }">
											<use xlink:href="/common/img/icon/icon_shirushi.svg#icon-{ edit_kaime_mark(my_mark[syaban], false, cur_shikibetu) }"></use>
										</svg>
									</div>
									</virtual>
								</div>
							</div>
							<span class="OddsData01" if={ select_bet_odds.length > 0 }>{select_min_odds}倍 ～ {select_max_odds}倍</span>
						</div>
						<div class="pay FormationType">
							<div class="FormationTypeWrap">
								<div class="AssumedOdds FormationType">
									<dl class="PayData01"> <dt><span class="kumiawase_kensu"><em>{bet_count}</em>点</span></dt> </dl>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="Select">
					<input class="BuyCheck_Select disp_none" type="checkbox" value="1" id="p-chk_sel_1" onclick={ act_select_kaime.bind(this) } checked={ select_kaime ? true : false } disabled={ bet_count <= 0 ? true : false }>
					<label class="Check01Btn_Off" for="p-chk_sel_1"></label>
				</div>
			</div>
		</div>

		<virtual if={ bet_mode == 'add'} >
			<p class="RaceInfo_Notice01">※結果・成績・オッズなどのデータは、必ず主催者発表のものと照合しご確認ください。</p>
			<div class="InputFixedArea_Wrap">
				<!-- div class="InputFixedArea01 odds_fixed" -->
				<div class="InputFixedArea01">
					<div class="TotalBetDL">
						<dl if={ !select_kaime && bet_count > 0 } class="TotalBetDL">
							<dt id="total_bet">組み合わせ：{ bet_count }点 / 選択済：<span id="odds_select">{ edit_select_count() }</span><span>件</span></dt>
						</dl>
						<virtual if={ select_kaime  }>
							<p id="total_bet" style="display:block;"　class ="{ edit_select_count() <= 0 ? 'no_select' : '' }">選択済み：<span id="select_count">{disply_bet_label[cur_shikibetu]} {houshiki[cur_shikibetu][cur_houshiki]} { bet_count }</span><span>組</span></p>
						</virtual>
						<virtual if={ cur_shikibetu == 1 || cur_houshiki >= 10 }>
							<p id="total_bet" style="display:block;" class ="{ edit_select_count() <= 0 ? 'no_select' : '' }">選択済み：<span id="select_count">{ Object.keys(select_odds).length }</span><span>組</span></p>
						</virtual>
						<p style="display: none; font-size:77.78%">PIST6の車券投票はTIPSTARアプリから行えます</p>
					</div>
					<ul style="display:block;">
						<li>
							<div class="InputBtnBox">
								<a href="" class="SubmitBtn" onClick={ act_add_bet.bind(this) } disabled ="{ edit_select_count() <= 0 ? 'disabled' : '' }" id="action_bet">金額入力へすすむ</a>
							</div>
						</li>
						<!--li><div class="InputBtnBox"><button class="Btn01 BtnCol01" onClick={ act_add_bet.bind(this) } disabled ="{ edit_select_count() <= 0 ? 'disabled' : '' }">買い目追加</button></div></li-->
					</ul>
					<ul style="display: none;">
						<li>
							<div class="InputBtnBox"><button class="Btn01 BtnCol01" style="width:100%;background:#efefef;position:relative" onClick="location.href='https://tipstar.onelink.me/sXko/nk'">TIPSTARアプリをインストールする</button></div>
						</li>
					</ul>
				</div>
			</div>
		</virtual><!-- endif -->

    </virtual>

    <script>
     // $Id: odds.tag 436 2017-09-11 07:51:07Z ysimizu $
     "use strict"

     var self = this;
     self.args = self.opts;
     self.debug = true;
     self.param = null;
     if (self.debug) console.log('sel.args: %O', self.args);

     //self.selection_type = 2;	// 1: プルダウン,簡易表示 2: ボタン,俺プロ仕様
     self.phase = 0 // 入力フェーズ(メニューの抑制)
     // 0: 競車場選択(初期化)
     // 1: レース選択
     // 2: 式別選択(単勝,複勝...)
     // 3: 方式選択(通常,BOX,フォーメーション...)
     // 式別・方式による、車番ボタンの状態、印選択・全選択の使用可否・チェックルーチン、ラベル
     // 左から
     //   key:   1桁目: 式別  2桁目: 方式
     //   in:    軸が入力可能か否か  1: 可  0: 不可
     //   all:   印で選択、全選択ボタンが使用可能か否か 1: 可 0: 不可
     //   check: チェック関数
     //      0: なし
     //      'radio' : 単一選択(既に選択中の車番は選択解除)
     //      'nodupp': 他の軸の同一車番が選択不可
     //      'max'   : 番号の選択最大数チェック :n は引数
     //   label: 式別、方式による表題

     self.houshiki_attr = {
	     // 単勝
	     '10': {in: [1,0,0], all: [0,0,0], check: [0,0,0], label: ['--','--','--']}, // 通常
	     // 複勝
//	     '20': {in: [1,0,0], all: [0,0,0], check: ['radio',0,0], label: ['--','--','--']}, // 通常
	     // 枠複
	     '30': {in: [1,1,0], all: [0,0,0], check: ['radio','radio',0], label: ['枠1','枠2','--']}, // 通常
	     '31': {in: [1,1,0], all: [1,1,0], check: [0,0,0], label: ['枠1','枠2','--']},  // フォーメーション
	     '32': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['--','--','--']}, // BOX
	     '33': {in: [1,1,0], all: [0,1,0], check: ['radio',0,0], label: ['軸','相手','--']},  // ながし
	     // 車連
//             '50': {in: [1,0,0], all: [0,0,0], check: ['max:2',0,0], label: ['--','--','--']}, // 通常
             '51': {in: [1,1,0], all: [1,1,0], check: [0,0,0], label: ['車1','車2','--']},  // フォーメーション
             '52': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']}, // BOX
             '53': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['軸','相手','--']},  // ながし
	     // ワイド
             '70': {in: [1,0,0], all: [0,0,0], check: ['max:2',0,0], label: ['--','--','--']}, // 通常
             '71': {in: [1,1,0], all: [1,1,0], check: [0,0,0], label: ['車1','車2','--']},  // フォーメーション
             '72': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']}, // BOX
             '73': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['軸','相手','--']},  // ながし
	     // 2車単
	     '60': {in: [1,1,0], all: [0,0,0], check: ['radio&nodupp','radio&nodupp',0], label: ['1着','2着','--']}, // 通常
	     '61': {in: [1,1,0], all: [1,1,0], check: [0,0,0], label: ['軸','相手','--']},  // フォーメーション
	     '62': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']}, // BOX
	     '63': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['1着軸','相手','--']},  // 1着ながし
	     '64': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['2着軸','相手','--']},  // 2着ながし
	     // 3連複
             '80': {in: [1,1,1], all: [0,0,0], check: ['radio&nodupp','radio&nodupp','radio&nodupp'], label: ['車1','車2','車3']}, // 通常
             '81': {in: [1,1,1], all: [1,1,1], check: [0,0,0], label: ['車1','車2','車3']},   // フォーメーション
             '82': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']},  // BOX
             '83': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['軸','相手','--']},  // 軸1頭ながし
             '86': {in: [1,1,1], all: [0,0,1], check: ['radio&nodupp','radio&nodupp',0], label: ['軸1','軸2','相手']},   // 軸2頭ながし
	     // 3連単
             '90': {in: [1,1,1], all: [0,0,0], check: ['radio&nodupp','radio&nodupp','radio&nodupp'], label: ['1着 ','2着 ','3着']}, // 通常
             '91': {in: [1,1,1], all: [1,1,1], check: [0,0,0], label: ['1着 ','2着 ','3着']},   // フォーメーション
             '92': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']}, // BOX
             '93': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['1着軸','相手','--']},  // 1着ながし
             '94': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['2着軸','相手','--']},  // 2着ながし
             '95': {in: [1,1,0], all: [0,1,0], check: ['radio&nodupp',0,0], label: ['3着軸','相手','--']},  // 3着ながし
             '96': {in: [1,1,1], all: [0,0,1], check: ['radio&nodupp','radio&nodupp'], label: ['1着軸','2着軸','相手']},   // 1,2着ながし
             '97': {in: [1,1,1], all: [0,0,1], check: ['radio&nodupp','radio&nodupp',0], label: ['1着軸','3着軸','相手']},   // 1,3着ながし
             '98': {in: [1,1,1], all: [0,0,1], check: ['radio&nodupp','radio&nodupp',0], label: ['2着軸','3着軸','相手']},   // 2,3着ながし
	     // 2枠単
	     '40': {in: [1,1,0], all: [0,0,0], check: ['radio&nodupp','radio&nodupp',0], label: ['1着','2着','--']}, // 通常
	     '41': {in: [1,1,0], all: [1,1,0], check: [0,0,0], label: ['1着','2着','--']},  // フォーメーション
	     '42': {in: [1,0,0], all: [1,0,0], check: [0,0,0], label: ['選択','--','--']}, // BOX
	     '43': {in: [1,1,0], all: [0,1,0], check: ['radio',0,0], label: ['1着軸','相手','--']},  // 1着ながし
	     '44': {in: [1,1,0], all: [0,1,0], check: ['radio',0,0], label: ['2着軸','相手','--']},  // 2着ながし
     };

     // 方式別チェック
     //  eq:1 １つのみ選択
     //  gt:1 １つ以上選択
     //  配列順は、軸に紐づく
     self.houshiki_check = {
	     // 単勝
	     '10': {chk: ['gt:1']}, // 通常
	     // 複勝
//	     '20': {chk: ['eq:1']}, // 通常
	     // 枠連
	     '30': {chk: ['eq:1','eq:1']}, // 通常
	     '31': {chk: ['gt:1','gt:1']}, // フォーメーション
	     '32': {chk: ['gt:2']}, // BOX
	     '33': {chk: ['eq:1','gt:1']}, // ながし
              // 2車複
	     //'50': {chk: ['eq:2']}, // 通常
	     '50': {chk: ['gt:1','gt:1']}, // 通常
	     '51': {chk: ['gt:1','gt:1']},  // フォーメーション
	     '52': {chk: ['gt:2']}, // BOX
	     '53': {chk: ['eq:1','gt:1']},  // ながし
	     // ワイド
             '70': {chk: ['gt:1','gt:1']}, // 通常
//             '70': {chk: ['eq:2']}, // 通常
             '71': {chk: ['gt:1','gt:1']},  // フォーメーション
             '72': {chk: ['gt:2']}, // BOX
             '73': {chk: ['eq:1','gt:1']},  // ながし
	     // 2車単
	     '60': {chk: ['eq:1','eq:1']}, // 通常
	     '61': {chk: ['gt:1','gt:1']},  // フォーメーション
	     '62': {chk: ['gt:2']}, // BOX
	     '63': {chk: ['eq:1','gt:1']},  // 1着ながし
	     '64': {chk: ['eq:1','gt:1']},  // 2着ながし
	     // 3連複
             '80': {chk: ['eq:1','eq:1','eq:1']}, // 通常
             '81': {chk: ['gt:1','gt:1','gt:1']},   // フォーメーション
             '82': {chk: ['gt:3']},  // BOX
             '83': {chk: ['eq:1','gt:1']},  // 軸1頭ながし
             '86': {chk: ['eq:1','eq:1','gt:1']},   // 軸2頭ながし
	     // 3連単
             '90': {chk: ['eq:1','eq:1','eq:1']}, // 通常
             '91': {chk: ['gt:1','gt:1','gt:1']},   // フォーメーション
             '92': {chk: ['gt:3']}, // BOX
             '93': {chk: ['eq:1','gt:2']},  // 1着ながし
             '94': {chk: ['eq:1','gt:2']},  // 2着ながし
             '95': {chk: ['eq:1','gt:2']},  // 3着ながし
             '96': {chk: ['eq:1','eq:1','gt:1']},   // 1,2着ながし
             '97': {chk: ['eq:1','eq:1','gt:1']},   // 1,3着ながし
             '98': {chk: ['eq:1','eq:1','gt:1']},   // 2,3着ながし
	     // 枠単
	     '40': {chk: ['eq:1','eq:1']}, // 通常
	     '41': {chk: ['gt:1','gt:1']},  // フォーメーション
	     '42': {chk: ['gt:2']}, // BOX
	     '43': {chk: ['eq:1','gt:1']},  // 1着ながし
	     '44': {chk: ['eq:1','gt:1']},  // 2着ながし
     }

     // 表示用 ボタン選択型 方式選択1
     self.display_houshiki_button1 = [10,11,1,2,3];
     // ボタン選択型 方式選択1
     self.houshiki_button1 = {
//	     '0': '通常',
	     '3': 'ながし',
	     '2': 'ボックス',
	     '1': 'フォーメーション',
	     '10': '人気順',
	     '11': 'オッズ表'
     }
     // ボタン選択型 方式選択2
     self.houshiki_button2 = {
	     '6': { '3': '1着', '4': '2着' },
	     '8': { '3': '軸1', '6': '軸2' },
	     '9': { '3': '1着', '4': '2着','5': '3着','6': '1・2着', '7': '1・3着', '8': '2・3着' },
             '4': { '3': '軸1', '4': '軸2' },
     };

     // レース情報
     self.kaisai_list = {}; // 開催リスト
     self.race_list = {}; // 出車表リスト
     self.cur_jyo_cd = ''; // 選択中の競車場
     self.cur_jyo_name = ''; // 選択中の競車場名
     self.cur_race_id = ''; // 選択中のレースID
     self.cur_race_name = ''; // 選択中のレース名
     self.cur_race = {}; // 選択中のレース情報
     self.mawari = {'1': '左', '2': '右', '3': '直'};	// 回り
     //self.tenko_icon = {'1':'01','2':'02','3':'03','4':'03','5':'04','6':'04'};	// 天候アイコン
     self.grade_icon = {
	     'A999':'1','B999':'2','C999':'3','D999':'4','F999':'10','G999':'11','H999':'12',
	     '999':'5','016':'6','010':'7','005':'9'
	     ,'701':'','703':''	// iconなし
     };

     //
     self.shikibetu = {}; // 式別(単勝,複勝,...)
     self.cur_shikibetu = -1; // 選択中の式別
     self.disp_shikibetu = {}; // 表示用の式別(ソートされている)
     self.houshiki = {}; // 方式(通常,フォーメーション,...)
     self.cur_houshiki = -1; // 選択中の方式
     self.disply_houshiki_label = {'1': 'フォーメーション', '2': 'ボックス'};
     self.data_number = [];
     self.data_number_v = [];
     self.btn_func = [];
     self.btn_func_stat = {};
     self.mulit_attr = false; // マルチ(表示する/しない)
     self.mulit = false; // マルチ on,off

     self.btn_uno = {}; // 車番ボタン(選択中はtrue,falseで表現)
     self.btn_uno_disable = {}; // 選択できない車番ボタン
     self.max_uma = 0; // 車番(最大頭数)
     self.max_waku = 0; // 枠番(最大頭数)

     // 投票
     self.bet_money = 100; // 金額
     self.race = {}; // 投票中のレース情報
     self.race_id = ''; // 投票中のレースID
     self.race_horse = {}; // 出走車データ
     self.waku_horse = {}; // 枠番順の出走車配列

     self.bet_view = []; // 買い目、投票内容表示
     self.bet_select = {}; // 買い目、
     self.bet_select_all = false; //
     self.bet_count = 0; // 現在の買い目点数
     self.bet_odds_list = {}; //フォーメーション、流しのオッズ一覧
     self.disply_bet_view = {}; //表示用(券種ごとにまとめる)
     self.disply_bet_order = [1,9,6,8,5,7]; //['単勝','3連単','2車単','3連複','2車複','2枠単','2枠複','ワイド'];   // 順番
     self.disply_bet_label = {'1':'単勝','9':'3連単','6':'2車単','8':'3連複','5':'2車複','4':'2枠単','3':'2枠複','7':'ワイド'};
     self.isam_domain = ''; // 'ipat'+YYMMDD(開催日)
     self.isam_domain_mark = 'umark_';
     self.is_tipstar_modal = false; //tipstar遷移案内フラグ
     self.is_cahrge = false;

     self.my_mark = {};
     self.my_mark_label = {'0':'--','1':'◎','2':'○','3':'▲','4':'△','5':'☆','6':'注','98':'✓','99':'消'};

     self.total_bet_money = 0;
     self.odds = {}; // オッズデータ
     self.odds_ninki = {}; // オッズデータ(人気順)
     self.ijyo_waku_list = {};
     self.ijyo_list = {};
     self.select_bet_odds = []; //選択中のオッズ
     self.is_odds_open = false; //買い目一覧のオッズ表示
     self.select_odds_sort_mode = 'asc';
     self.is_edit = false; //買い目一覧の削除モード
     self.select_kaime = false; //買い目一覧の組み合わせ選択
     self.select_odds = {};
     self.odds_update_timer = false;
     self.is_charge = false;
     self.show_regist = false;
     self.iframe_url = '';
     self.ninki_select_box = [];
     self.ninki_dispay_limit = 100;
     self.jiku_select = 1; //オッズ表の軸
     self.chaku_select = 1; //オッズ表の着
     self.no_odds_info = false;
     self.race_status = 0;

     self.on('update', function() {
         //	     console.error('self.update()');
     });
     self.on('updated', function() {
         //	     console.error('self.updated()');
     });


     // 下記、edit_xxxxx関数は、HTMLテンプレートのレンダリング時(riot=update)に動作する

     /*
      * 方式(通常、フォーメーション、BOX...)によるチェックボックス表示/非表示
      */
     edit_show_column(rix, mode)
     {
	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     if (undefined === self.houshiki_attr[id]) {
	         return false;
	     } else {
	         return self.houshiki_attr[id][mode][rix];
	     }
	     return false;
     }

     /*
      * 方式(通常、フォーメーション、BOX...)による、ラベル切り替え
      */
     edit_label(rix)
     {
	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     if (undefined === self.houshiki_attr[id]) {
	         return '--';
	     } else {
	         return self.houshiki_attr[id]['label'][rix];
	     }
     }

     //--------------------------------------------------
     edit_number_active(rix, uix)
     {
	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     if (undefined === self.houshiki_attr[id]) {
	         return false;
	     } else {
	         if (undefined === self.btn_uno[rix]) {
		         //		 console.log('edit_number_active(%s,%s) false(1)',rix,uix);
		         return false;
	         } else if (self.btn_uno[rix][uix]) {
		         //		 console.log('edit_number_active(%s,%s) true',rix,uix);
		         return true;
	         } else {
		         //		 console.log('edit_number_active(%s,%s) false(2)',rix,uix);
		         return false;
	         }
	     }
     }
     //--------------------------------------------------
     edit_number_disable(rix, uix)
     {
	     //	 console.log('edit_number_disable(%s,%s)',rix,uix);
	     if (undefined !== self.btn_uno_disable[rix] && self.btn_uno_disable[rix][uix]) {
	         return true;
	     } else {
	         return false;
	     }
     }

     //--------------------------------------------------
     edit_houshiki_button1_disable( h )
     {
	     var id = sprintf("%1d%1d", self.cur_shikibetu, h);
	     if(h >= 10){
	     	return true;
	     }
	     if(undefined !== self.houshiki_attr[id]){
	         return true;
	     }else{
	         return false;
	     }
     }

     //--------------------------------------------------
     edit_kaime_label( s, h, line_no )
     {
	     var id = sprintf("%1d%1d", s,h);
	     if(undefined !== self.houshiki_attr[id]){
	         return self.houshiki_attr[id]['label'][line_no];
	     }
	     return '';
     }

     //--------------------------------------------------
     edit_combination( comb, s, h )
     {
	     var val = comb.split(/0/);
	     var ret = [];
	     for(var i=1; i < val.length; i++){
	         var row = {};
	         row['no'] = parseInt(val[i]);	// '0'サプレス
	         if(6 == s || 9 == s){	// 車単、３連単
		         row['type'] = 2;	// 車番の間(矢印)
	         }else{
		         row['type'] = 1;	// 車番の間(ハイフン)
	         }
	         if(i == val.length - 1){
		         row['type'] = -1;
	         }
	         ret.push( row );
	     }
	     //	 console.error('s:%s h: %s ret: %O',s,h,ret);
	     return ret;
     }

     //--------------------------------------------------
     number_format(num)
     {
	     return num.toString().replace(/(\d+?)(?=(?:\d{3})+$)/g, function(x) {
	         return x + ',';
	     });
     }

    //--------------------------------------------------
    // 2020/10/26 masahiro.tsuboi
    //     開発者スキルが低く、
    //     aタグをbootstrap無効化にする方法がうまくいかなかったので、直接styleに書いている。
    //--------------------------------------------------
    edit_shikibetsu_disable(shikibetsu)
    {
        //枠連、枠単はオッズで判定
        if(shikibetsu == 3 && Object.keys(self.odds['3']).length <= 0){
            return 'none; color: #dbdbdb;';
        }else if(shikibetsu == 4 && Object.keys(self.odds['4']).length <= 0){
            return 'none; color: #dbdbdb;';
        }else{
            return 'auto;';
        }
    }

    /*
        * 特定の順番にソートしてから、keyと値を反転させる
        *      ※どうやら、jsは数値文字列indexだけだと、ブラウザで勝手に数値の昇順にソートすると思われる。
    */
    disp_sorted_shikibetsu()
    {

        if (!self.shikibetu) return false;

        //const order = ['2車複','2車単','3連複','3連単','ワイド','2枠複','2枠単'];   // 順番
        const order = ['単勝','3連単','2車単','3連複','2車複','ワイド'];   // 順番
        var sorted_shikibetsu = Object.entries(self.shikibetu).sort(function(a, b){ return order.indexOf(a[1]) - order.indexOf(b[1]) });
        var flip_shikibetsu = {};
        for (var [key, value] of sorted_shikibetsu) {
            flip_shikibetsu[value] = key;
        }

        return flip_shikibetsu;
     }

    edit_ary_maxmin(arr, mode)
    {
        if(mode == 'max'){
            var ret = arr.reduce(function(a, b) {
                return Math.max(a, b);
            });
        }else{
            var ret = arr.reduce(function(a, b) {
                return Math.min(a, b);
            });
        }
        return ret;
    }

    edit_payment_diff(payback, total)
    {
        if((payback - total) < 0){
            return 'minus';
        }else{
            return 'plus';
        }
    }

    //--------------------------------------------------
    edit_kaime_class(shikibetu)
    {
        if(4 == shikibetu || 6 == shikibetu || 9 == shikibetu){	// 枠単,2車単,３連単
            // 馬番の間(矢印)
            return 'Kaime_Arrow'
        }else{
            // 馬番の間(ハイフン)
            return 'Hyphen';
        }
    }

    //--------------------------------------------------
    edit_kaime_mark(mark, upper, shikibetu)
    {
        if(shikibetu == 3 || shikibetu == 4){
            return '';
        }
        var mark_list = {
             1: 'honmei',
             2: 'taikou',
             3: 'kurosan',
             4: 'shirosan',
             5: 'hoshi',
             98: 'check',
             99: 'keshi'
        }
        if(mark_list[mark]){
            if(upper){
                return mark_list[mark].substring(0, 1).toUpperCase() + mark_list[mark].substring(1);
            }else{
                return mark_list[mark];
            }
        }else{
            return '';
        }
    }

     edit_check_bet_money(bet_money)
     {
          if(bet_money < 0){
              return '';
          }else{
              return bet_money / 100;
          }
     }

    edit_select_count()
    {
        var count = 0;
        if(self.select_kaime){
            count = 1;
        }else if(Object.keys(self.select_odds).length >= 1){
            count = Object.keys(self.select_odds).length;
        }
        return count;
    }

     /*
      * チェックボックス or ラジオボタン
      */
    edit_show_input_type(rix)
    {
        var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
        if (undefined === self.houshiki_attr[id]) {
            return 'checkbox';
        }
        if(/^radio/. test(self.houshiki_attr[id]['check'][rix])){
            return 'radio';
        }
        else {
            return 'checkbox';
        }
    }

    edit_bet_count_all()
    {
        var bet_count_all = 0;
        for(var i = 0; i < self.bet_view.length; i++){
            if(self.bet_view[i]['comb']){
                bet_count_all += self.bet_view[i]['comb'].length;
            }else{
                bet_count_all += 1;
            }
        }
        console.log(bet_count_all);
        return bet_count_all;
    }

    check_column(rix, mode)
    {
        var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
        if (undefined === self.houshiki_attr[id]) {
            return 0;
        } else {
            var count_column
            count_column = self.houshiki_attr[id][mode].filter(function(int){
                if(int >= 1){
                    return true;
                }
            });
            return count_column.length;
        }
    }

    //--------------------------------------------------
    select_odds_active(kaime)
    {
        //console.log(kaime);
        //console.log(self.select_odds);
        return self.select_odds[kaime] ? true : false;
    }

    act_select_jiku()
    {
        self.jiku_select = document.getElementById("entry_axis").value;
    }

    act_select_chaku()
    {
        self.chaku_select = document.getElementById("number_axis").value;
    }

    is_column(syaban)
    {
        if(self.cur_shikibetu == 5 || self.cur_shikibetu == 7 ){
            if(syaban == 1){
                return false;
            }else{
                return true;
            }
        }else if(self.cur_shikibetu == 8){
            if(syaban == 1 || self.jiku_select == 1 && syaban == 2 || syaban == self.jiku_select){
                return false;
            }else{
                return true;
            }
        }else if(self.cur_shikibetu == 9){
            if(syaban == self.jiku_select){
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }

    get_odds(kaime, wide_flag = false)
    {
        if(!kaime){
            return false;
        }
        //if(!self.check_ijyo(kaime)){
        //    return false;
        //}
        if(self.odds[self.cur_shikibetu][kaime]){
            if(!wide_flag){
                return sprintf("%0.1f", self.odds[self.cur_shikibetu][kaime][0]);
            }else{
                return sprintf("%0.1f", self.odds[self.cur_shikibetu][kaime][1]);
            }
        }else{
            return false;
        }
    }

    check_odds(odds)
    {
        var Highest = 10;
        if(self.cur_shikibetu == 1){
            var Highest = 5;
        }
        if(parseInt(odds) <= Highest){
            return 'Highest';
        }else{
            return '';
        }
    }

    /*
      * 画面初期化(mount)
      */
     self.on('mount', function() {
	     if (self.debug)  console.log('mount %s', self.args.tag_name);
	     self.args.obs.trigger('tag_mounted', {tag: self.args.tag_name});
     });

     /*
      * 画面表示(parent -> trigger -> render_xxxx)
      */
     self.args.obs.on('render_' + self.args.tag_name, function(p) {
	     if (self.debug) console.log('render_%s start p: %O', self.args.tag_name, p);

	     self.param = p;

	     // 各種、初期化
	     self.kaisai_list = {}; // 開催リスト
	     self.race_list = {}; // 出車表リスト
	     self.cur_jyo_cd = ''; // 選択中の競車場
	     self.cur_jyo_name = ''; // 選択中の競車場名
	     self.cur_race_id = ''; // 選択中のレースID
	     self.cur_race_name = ''; // 選択中のレース名
	     self.cur_race = {}; // 選択中のレース情報
	     self.cur_shikibetu = -1; // 選択中の式別
	     self.cur_houshiki = -1; // 選択中の方式
	     self.phase = 0;
	     self.bet_mode = 'add';
	     if(p['mode'] == 'add'){
	     	self.bet_mode = 'add';
	     	$('.DeployYoso').show();
	     }
         self.cur_shikibetu = 1;
         if(p['shikibetu']){
             self.cur_shikibetu = p['shikibetu'];
         }
         self.cur_houshiki = 10;
         if(p['houshiki']){
             self.cur_houshiki = p['houshiki'];
         }
	     self.show_data(p);
     });

     // 行・列変換
     var transpose = function(a) {
	     return Object.keys(a[0]).map(function(c) {
	         return a.map(function(r) {
		         return r[c];
	         });
	     });
     }

     /*
      * データ取得、編集
      *  URLパラメータ date   : 日時(必須)
      *                race_id: レースID(省略可)
      *                         レースID指定時は、競車場、 レース番号が選択状態
      *                         レースID省略時は、競車場、 レース番号が未選択状態
      */
     self.show_data = function(p) {
	     if (self.debug) console.log('self.show_data');

	     var ipat = new IpatDataModel();
	     self.shikibetu = ipat.get_shikibetu();
         self.disp_shikibetu = self.disp_sorted_shikibetsu();

	     var tmp_h = ipat.get_houshiki();
	     self.houshiki = {};
	     for (var key in tmp_h) {
	         var s = key.substr(0, 1);
	         var h = key.substr(1, 1);
	         if (undefined === self.houshiki[s]) {
		         self.houshiki[s] = {};
	         }
	         self.houshiki[s][h] = tmp_h[key];
	     }

	     var api = new AplApiRace(self.args.api_url, true, 'json'/*, true*/);

         if(!p['race_id']){
             console.error("empty parameter 'race_id'");
             return false;
         }

         if(p['date']){
             self.kaisai_date = p['date'];
         }else{
             self.kaisai_date = p['race_id'].substr(0, 8);
         }

	     var year = self.kaisai_date.substr(0, 4);

	     self.isam_domain = sprintf("bet_%s", p['race_id']);
	     if (self.debug) console.log('self.isam_domain: %s', self.isam_domain);

	     // 開催スケジュールを取得
	     //api.get('AplKaisai',{'year': year, 'syusai': 'pist6'}, function(ary_kaisai) {
	     //    for (var i = 0; i < ary_kaisai.length; i++) {
		 //        if (self.kaisai_date == ary_kaisai[i]['kaisai_date']) {
		 //            self.kaisai_list = ary_kaisai[i];
		 //            break;
		 //        }
	     //    }
	         if (self.debug) console.log('self.kaisai_list: %O', self.kaisai_list);

	         // レース一覧を取得
	         api.get('AplRace', {'kaisai_date': self.kaisai_date, 'syusai': 'pist6'}, function(ary_race) {
		         var selected_race = {};

		         for (var i = 0; i < ary_race.length; i++) {
		             self.race_list[ary_race[i].jyo_cd] = ary_race[i].list;

		             if (undefined !== p['race_id']) {
			             for (var idx in ary_race[i].list) {
			                 var row = ary_race[i].list[idx];
			                 if (row['race_id'] == p['race_id']) {
				                 selected_race = row;
			                 }
			             }
		             }
		         }
		         if (self.debug) console.log('self.race_list: %O', self.race_list);
		         self.race_status = selected_race['race_status'];
		         if (undefined !== p['race_id']) {
		             // race_id 指定あり、選択状態を再現
		             if (self.debug) console.log('selected_race: %O', selected_race);
		            self.get_race_odds(p['race_id'], function(odds_data){
		                //オッズデータ整形
		                for (var i = 1; i <= 9; i++) {
		                    if (undefined === odds_data['list_' + i]) {
			                    continue;
		                    }
		                    self.odds[i] = {};
		                    self.odds_ninki[i] = {};
		                    var ninki = [];
		                    for(var j = 0; j < odds_data['list_' + i].length; j++) {
			                    var oval = odds_data['list_' + i][j];
			                    self.odds[i][oval[0]] = [oval[1], oval[2], oval[3]];
			                    //self.odds_ninki[i][oval[3]] = [oval[0], oval[1], oval[2]];
			                    ninki.push(oval);
		                    }

                            ninki.sort(function(a,b){
                                    if( parseInt(a[3]) < parseInt(b[3]) ) return -1;
                                    if( parseInt(a[3]) > parseInt(b[3]) ) return 1;
                                    return 0;
                            });
		                    self.odds_ninki[i] = ninki;
		                }
		                //	     console.error('self.odds: %O',self.odds);
		                if (self.debug) console.log('self.odds: %O', self.odds);
		                console.log(self.odds_ninki);
		                if(Object.keys(self.odds).length >= 1){
		                    // 競車場
		                    self.act_jyo(selected_race['jyo_cd'], selected_race['jyo']);
		                    // レース番号
		                    self.act_race(selected_race['race_id'], selected_race['race_name'], selected_race['jyoken']);
		                }else{
		                    self.no_odds_info = true;
		                    self.update();
		                }
		            });
		         } else {
		             self.update();
		         }
	         });
	     //});
     }

     /*
      * 印を取得(local stolage)
      */
    self.get_shutuba_mark = function(race_id, fn) {
        if (self.debug) console.log('self.get_shutuba_mark(%s)', race_id);

        var cart = new NDCartApi(self.args.cart_url, 'json');
        var group_id = sprintf("SensyuMark_%s", race_id);

        // リスト取得
        cart.get_item_list(group_id, function(data) {
            if ('OK' == data.status) {
            var mark = {};
            // 出馬表の印は、馬番でなく通番
            for (var seq in data.data) {
                var val = data.data[seq]['_cd'].split(/_/);
                if ('0' == val[1])
                continue; // 印を消してもカートに存在
                mark[seq] = val[1];
            }
            self.my_mark = mark;
            if (self.debug) console.log('self.my_mark: %O', self.my_mark);
                    if(undefined !== fn){
                        fn();
                    }
            }
        });

     }

     /*
      * レースデータ切替え
      */
     self.change_race_horse = function(race_id, fn) {
	     if (self.debug) console.log('self.change_race_horse(%s)', race_id);

	     var api = new AplApiRace(self.args.api_url, true, 'json'/*, true*/);

	     // 出走車情報取得
	     api.get('AplRaceHorse', {'race_id': race_id}, function(data) {
                 if (self.debug) console.log('=============AplRaceHorse=============');
                 if (self.debug) console.log(data);
             var rh = {};
	         for (var i = 0; i < data.length; i++) {
		         if ('' == data[i]['syaban']) {
		             alert('出車表に車番がない');
		         }
		         rh[data[i]['syaban']] = data[i];
	         }
	         self.race_horse = rh;
	         if (self.debug) console.log('self.race_horse: %O', self.race_horse);

	         var ary_waku = {};
	         for (var u in self.race_horse) {
		         var w = self.race_horse[u]['wakuban'];
		         if (undefined === ary_waku[w]) {
		             ary_waku[w] = {};
		         }
		         ary_waku[w][self.race_horse[u]['syaban']] = {
//		             seq: self.race_horse[u]['seq'],
		             syaban: self.race_horse[u]['syaban'],
		             name: self.race_horse[u]['name'],
		             sales_sts: self.race_horse[u]['sales_sts'],
		             fuken: self.race_horse[u]['fuken'],
		             age: self.race_horse[u]['age'],
		             graduate: self.race_horse[u]['graduate'],
		             kyu: self.race_horse[u]['kyu'],
		             han: self.race_horse[u]['han'],
		             rating: self.race_horse[u]['rating']
		         };
		         if(self.race_horse[u]['sales_sts'] == '1' || self.race_horse[u]['sales_sts'] == '3'){
		             self.ijyo_list[self.race_horse[u]['syaban']] = true;
                     if(self.ijyo_waku_list[w] === undefined){
                         self.ijyo_waku_list[w] = {};
                     }
                     self.ijyo_waku_list[w][self.race_horse[u]['syaban']] = true;
		         }
	         }
	         self.waku_horse = ary_waku;

	         // 最大車番を求める
	         var waku_keys = Object.keys(self.waku_horse);
	         self.max_waku = waku_keys.length;
	         if(self.debug) console.log('self.max_waku: %s',self.max_waku);

//	         if(self.max_uma < 9 || self.cur_race['jyo_cd'].substr(0,1) >= 'A'){
//		         // 9頭未満、海外は枠連なし
//		         for(var key in self.shikibetu){
//		             if('3' == key){
//			             delete self.shikibetu[key];// 枠連をメニューから除外
//		             }
//		         }
//	         }

	         if (self.debug) console.log('self.waku_horse: %O', self.waku_horse);
	         fn();
	     });
     }

     /*
      * 車番ボタンリセット
      *  line: 対象となる行 (-1は、全て)
      */
     self.reset_uno = function(line, mode) {
	     if (self.debug) console.log('self.reset_uno(%s,%s)', line, mode);

	     self.btn_uno = {};
	     for (var i = 0; i < 3; i++) {
	         if (line < 0 || (line >= 0 && i == line)) {
		         self.btn_uno_disable[i] = {};
	         }
	         for (var j = 0; j <= self.max_uma; j++) {
		         if (1 == mode) {
		             // 1: 全てをenable
		             self.btn_uno_disable[i][j] = false;
		         } else {
		             // 0: 全てをdiasble
		             self.btn_uno_disable[i][j] = true;
		         }
	         }
	     }
     }

     /*
      * 競車場選択
      */
     self.act_jyo = function(jyo_cd, jyo_name) {
	     if (self.debug) console.log('self.act_jyo(%s,%s)', jyo_cd, jyo_name);

	     self.cur_jyo_cd = jyo_cd;
	     self.cur_jyo_name = jyo_name;

	     self.cur_race_id = ''; // レース選択クリア
	     self.cur_race_name = '';
	     self.phase = 1;
     }

     /*
      * レース番号選択
      */
     self.act_race = function(race_id, race_name, jyoken, ev) {
	     if (self.debug) console.log('self.act_race(%s,%s,%s)', race_id, race_name, jyoken);

	     if (undefined !== ev) {
	         console.log('self.act_race :%O', ev);
	     }

	     if (undefined !== ev)
	         ev.preventUpdate = true;

	     // !! ここ重要 メニュー選択した段階では、riot update()しない 出走車データ取得(非同期)が完了してから、ev.preventUpdate = false でriot update()する でないと配列(self.race_horse)が完成していないので、不定となる。

	     //self.cur_shikibetu = -1; // 式別クリア
	     //self.cur_houshiki = -1; // 方式クリア

	     self.cur_race_id = race_id;
	     self.cur_race_name = ('' != race_name) ? race_name : jyoken;

	     for (var key in self.race_list[self.cur_jyo_cd]) {
	         var row = self.race_list[self.cur_jyo_cd][key];
	         if (race_id == row['race_id']) {
		         self.cur_race = self.race_list[self.cur_jyo_cd][key];
		         break;
	         }
	     }

	     //self.max_uma = self.cur_race['tosu'];
	     self.max_uma = Object.keys(self.race_horse).length;
//	     self.max_uma = 6;
         //         console.error('self.cur_race',self.cur_race);
         //         console.error('self.max_uma',self.max_uma);

	     self.data_number = []; // 車番作成
	     for (var i = 0; i < 3; i++) {
	         self.data_number[i] = [];
	         for (var j = 1; j <= self.max_uma; j++) {
		         self.data_number[i][j] = true;
	         }
	     }

	     self.data_number_v = transpose(self.data_number);

	     console.log(self.data_number_v);
	     self.phase = 2;

	     if (self.debug) console.log('self.cur_race: %O', self.cur_race);
	     if (self.debug) console.log('self.max_uma: %s', self.max_uma);

	     var ipat = new IpatDataModel();
	     self.shikibetu = ipat.get_shikibetu();
         self.disp_shikibetu = self.disp_sorted_shikibetsu();

	     self.change_race_horse(race_id, function() {
         if (undefined !== ev)
	         ev.preventUpdate = false;
		     self.render_bet_list();
		     if(self.args.odds_update){
		     self.odds_auto_update();
		     }
		     //初期表示の時に買い目がなかったら買い目追加ページを表示
		     if(self.bet_view.length <= 0){
		         self.bet_mode = 'add';
		         $('.DeployYoso').show();
		     }
             self.get_shutuba_mark(self.cur_race_id, function(){
                //初期表示を単勝デフォルトにする
                self.act_shikibetu(self.cur_shikibetu);
                self.update();
                self.list_mark_check();
             });
	     });
     }

    self.get_race_odds = function(race_id, fn){
        var api = new AplApiRace(self.args.api_url, true, 'json'/*, true*/);
        // オッズ取得
        api.get('AplRaceOdds', {'race_id': race_id}, function(odds_data) {
            if (self.debug) console.log('=============AplRaceOdds=============');
            if (self.debug) console.log(odds_data);
            fn(odds_data);
        });
    }

     /*
      * 式別選択
      */
     self.act_shikibetu = function(sno) {
	     if (self.debug) console.log('self.act_shikibetu(%s)', sno);

	     self.cur_shikibetu = sno;

	     if('3' == sno || '4' == sno){
	         self.max_uma = self.max_waku;
	     }else{
	         //self.max_uma = self.cur_race['tosu'];
	         self.max_uma = Object.keys(self.race_horse).length;
	     }
	     //	     console.error('self.max_uma: %s',self.max_uma);
	     self.data_number = []; // 車番(枠番)作成
	     for (var i = 0; i < 3; i++) {
	         self.data_number[i] = [];
	         for (var j = 1; j <= self.max_uma; j++) {
		         self.data_number[i][j] = true;
	         }
	     }
	     self.data_number_v = transpose(self.data_number);
	     self.btn_func = [0, 1, 2];

	     self.reset_uno(-1, 0); // 車番ボタンリセット
	     self.bet_select = {}; // 選択中の投票内容
	     self.btn_func_stat = {
	         all: [0, 0, 0],
	         mark: [0, 0, 0]
	     };

	     // 全選択・クリア、印で選択初期化
	     self.bet_money = 100; // 金額クリア
	     self.bet_count = 0; // 買い目点数

	     self.phase = 3;

	     self.multi_attr = false;
	     self.multi = false;

	     var ninki_select_list = Math.ceil(Object.keys(self.odds_ninki[self.cur_shikibetu]).length / 100);
	     self.ninki_select_box = [];
	     for(var i = 1; i <= ninki_select_list; i++){
	     	var end = i * 100;
	     	var start = end - 99;
	     	if(end >= Object.keys(self.odds_ninki[self.cur_shikibetu]).length){
	     		end = Object.keys(self.odds_ninki[self.cur_shikibetu]).length;
	     	}
	     	var label = sprintf("%s~%s人気", start, end);
	     	//console.log(label);
	     	self.ninki_select_box.push(label);
	     }

	     if(self.param['houshiki']){
		     self.act_houshiki(self.param['houshiki']); // デフォルトは、通常が選択された状態
		     self.act_houshiki_1(self.param['houshiki']); // デフォルトは、通常が選択された状態
		     //self.act_houshiki(1); // デフォルトは、通常が選択された状態
		     //self.act_houshiki_1(1); // デフォルトは、通常が選択された状態

	     }else{
		     self.act_houshiki(10); // デフォルトは、通常が選択された状態
		     self.act_houshiki_1(10); // デフォルトは、通常が選択された状態
	     }
     }

     /*
      * 方式選択(ボタンタイプ、ラッパー)
      */
     self.act_houshiki_1 = function(hno1) {
	     if(self.debug) console.log('self.act_houshiki_1(%s)', hno1);
	     self.cur_houshiki_1 = hno1;
	     self.act_houshiki(hno1);
	     //制作
	     self.list_mark_check();
     }

     /*
      * 方式選択
      */
     self.act_houshiki = function(hno) {
	     if (self.debug) console.log('self.act_houshiki(%s)', hno);

	     self.cur_houshiki = hno;
	     self.btn_uno = {};
	     self.select_kaime = false;
	     self.select_bet_odds = [];
	     self.select_odds = {};
	     // 全選択・クリア、印で選択を初期化
	     self.btn_func_stat = {all: [0, 0, 0], mark: [0, 0, 0]};
	     self.bet_count = 0; // 買い目点数クリア
	     self.bet_money = 100; // 金額クリア
         self.multi = false;  // マルチクリア
        if(self.cur_shikibetu == 1){
        	//単勝の場合は通常のみ
            self.cur_houshiki = 0;
        }
        self.jiku_select = 1; //オッズ表の軸
        self.chaku_select = 1; //オッズ表の着

	     self.phase = 4;
	     // マルチが選択不可な場合は、非表示
	     if (('6' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki))
	         || ('9' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki || '5' == self.cur_houshiki || '6' == self.cur_houshiki || '7' == self.cur_houshiki || '8' == self.cur_houshiki))
                 || ('4' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki))
             ) {
	         self.multi_attr = true;
	     } else {
	         self.multi_attr = false;
	     }
	     if(self.cur_houshiki < 10){
		     // 車番ボタンをenable
		     var ary_i = self.houshiki_attr[sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki)]['in'];
		     for (var i = 0; i < 3; i++) {
		         for (var j = 1; j <= self.max_uma; j++) {
			         if (ary_i[i]) {
			             self.btn_uno_disable[i][j] = false; // 入力可
			         } else {
			             self.btn_uno_disable[i][j] = true; // 入力不可
			         }
		         }
		     }

	     }
	     //制作
	     self.list_mark_check();
     }

     /*
      * 車番号選択
      */
     self.act_number = function(rix, uix, ev) {
	     if (self.debug) console.log('self.act_number(%s,%s)', rix, uix);

	     if (undefined === self.btn_uno[rix]) {
	         self.btn_uno[rix] = {};
	     }

	     // 選択->未選択(削除)、未選択->選択(追加)
	     if (true == self.btn_uno[rix][uix]) {
	         delete self.btn_uno[rix][uix];
	     } else {
	         self.btn_uno[rix][uix] = true;
	     }

        //枠系の取り消し対応
        if(self.cur_shikibetu == '3' || self.cur_shikibetu == '4'){
            if(self.ijyo_waku_list[uix]){
                if(rix == 0){
                    self.btn_uno_disable[rix + 1][uix] = true;
                }else if(rix == 1){
                    self.btn_uno_disable[rix - 1][uix] = true;
                }
                //初期化
                if(!self.btn_uno[rix][uix]){
                    if(rix == 0){
                        self.btn_uno_disable[rix + 1][uix] = false;
                    }else if(rix == 1){
                        self.btn_uno_disable[rix - 1][uix] = false;
                    }
                    self.btn_uno_disable[rix][uix] = false;
                }
            }
        }

	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     if (undefined === self.houshiki_attr[id]['check']) {
	         return;
	     }

	     // 点数を表示するため組合せを生成
	     var info = self.make_bet(100);

	     if(info < 0){
	         self.bet_count = 0;
	         self.select_bet_odds = [];
	         self.select_kaime = false;
	     }else{
	         self.bet_count = info['bet_count'];
	         //選択中のオッズ一覧
	         var ret = self.make_select_bet_odds(info);
	         self.select_bet_odds = ret['odds_list'];
	         self.select_max_odds = ret['max_odds'];
	         self.select_min_odds = ret['min_odds'];
	         self.select_kaime = true;
	     }

	     if(Object.keys(self.select_odds) >= 1){
	     	self.select_kaime = false;
	     }

	     var rule = self.houshiki_attr[id]['check'][rix];
	     if (!rule) {
	         return;
	     }

	     var func = [];
	     if (rule.match(/&/)) {
	         func = rule.split(/&/);
	     } else {
	         func.push(rule);
	     }

	     for (var f = 0; f < func.length; f++) {
	         if (func[f].match(/max:/)) {
		         var val = func[f].split(/:/);
		         self.max_uno(rix, uix, val[1]);
	         }
	         if ('radio' == func[f]) {
		         self.radio_uno(rix, uix);
	         }
	         if ('nodupp' == func[f]) {
		         self.nodupp_uno(rix, uix);
	         }
	     }
     }

    self.act_select_number = function(syaban, ev){
        console.log('syaban', syaban);
        self.act_select_odds(syaban);
    }

     //------------------------------------------------------------
     self.make_bet = function( bet_money, normal_flg = false )
     {
	     if(self.debug) console.log('self.make_bet(%s,%s)',bet_money, normal_flg);

	     if (bet_money < 0) {
	         // 金額が未入力、あるいは正しくありません
	         return -1;
	     }
	     var ukey = Object.keys(self.btn_uno);
	     if(ukey.length < 1){
	         //	車番が正しく、選択されていません(未選択)
	         return -2;
	     }

	     var err = self.check_umaban_selection(normal_flg);
	     if (err) {
	         //	車番が正しく、選択されていません
	         return -2;
	     }

	     var kaime = [];
	     var kaime_id = '';

	     // 選択中の車番ボタンから買い目を作成

	     for (var i in self.btn_uno) {
	         var row = self.btn_uno[i];
	         var k = [];
	         for (var uno in row) {
		         if (true == row[uno]) {
		             k.push(uno);
		         }
	         }
	         if (k.length < 1) {

	         } else if (k.length > 1) {
		         if ('0' == self.cur_houshiki) {
		             kaime.push(k.join('_'));
		         } else {
		             kaime.push(k.join('-'));
		         }
	         } else {
		         kaime.push(k);
	         }
	     }
	     if('3' == self.cur_shikibetu && normal_flg){
	         var w_chk = {};
	         for (var w in self.waku_horse) {
		         var num = Object.keys(self.waku_horse[w]).length;
		         if (num > 1) {
		             w_chk[w] = true;
		         }
	         }
	         var w1 = kaime[0][0] || 0;
	         var w2 = kaime[1][0] || 0;
	         //	     console.error('w_chk: ',w_chk);
	         //	     console.error('w1: %s w2: %s',w1,w2);
	         if(w1 == w2){
		         if(! w_chk[w1] || ! w_chk[w2]){
		             return -2;
		         }
	         }
	     }

	     if (kaime.length > 1) {
	         kaime_id = kaime.join('_');
	     } else {
	         kaime_id = kaime.join('');
	     }

	     // 17.12.3 枠連、３連複の通常買いが車番の昇順でない件
	     if( ('3' == self.cur_shikibetu || '7' == self.cur_shikibetu)
	      && normal_flg ){
	         var val = kaime_id.split(/_/);
	         val.sort(function(a,b){
		         if( parseInt(a) < parseInt(b) ) return -1;
		         if( parseInt(a) > parseInt(b) ) return 1;
		         return 0;
	         });
	         kaime_id = val.join('_');
	         //	     console.error('kaime_id: %O',kaime_id);
	     }

	     // マルチ
	     if (self.multi) {
	         kaime_id += '_1';
	     }
	     if (self.debug) console.log('kaime: %O kaime_id: %s', kaime, kaime_id);

	     // 買い目コード作成
	     var year = self.cur_race_id.substr(0, 4);
	     var month = self.cur_race_id.substr(4, 2);
	     var day = self.cur_race_id.substr(6, 2);
	     var date = new Date(year, month - 1 , day);
	     var youbi_cd = date.getDay();
	     var jyo_cd = self.cur_race_id.substr(8, 2);

	     var race_no = parseInt(self.cur_race_id.substr(10, 2));
	     var houshiki = normal_flg ? '0' : self.cur_houshiki;
	     var bet_id = sprintf("a%1s-%1s-%1s_b%1s_c%s_%s", youbi_cd, jyo_cd, race_no, self.cur_shikibetu, houshiki, kaime_id);
	     var bet_info =  self.bet_gen(bet_id, bet_money);
	     bet_info['open'] = 0;
	     return bet_info;
     }

     /*
      * 車番号選択  全選択・全解除('all'),印で選択('mark')
      */
     self.act_ext_func = function(mode, rix) {
	     if (self.debug) console.log('self.act_ext_func(%s,%s)', mode, rix);

	     if ('all' == mode) {
	         // 全てを選択・クリア
	         for (var j = 1; j <= self.max_uma; j++) {
		         if (self.btn_uno_disable[rix][j])
		             continue;
		         if(self.ijyo_list[j]){
		         	continue
		         };

		         if (undefined === self.btn_uno[rix]) {
		             self.btn_uno[rix] = {};
		         }
		         if (0 == self.btn_func_stat['all'][rix]) {
		             self.btn_uno[rix][j] = 1;
		         } else {
		             self.btn_uno[rix][j] = 0;
		         }
	         }
	         // 全選択ボタンの状態
	         if (0 == self.btn_func_stat['all'][rix]) {
		         self.btn_func_stat['all'][rix] = 1;
		         self.btn_func_stat['mark'][rix] = 0;
	         } else {
		         self.btn_func_stat['all'][rix] = 0;
	         }
	     } else if ('mark' == mode) {
	         // 印で選択・クリア

	         var waku_mark = {};
	         if ('3' == self.cur_shikibetu || '4' == self.cur_shikibetu) {
		         // 枠連の場合、車番に印がついている枠を調べておく
		         // console.error('self.my_mark: %O',self.my_mark);
		         var uma2waku = {};
		         var uma2seq = {};
		         for(var key in self.race_horse){
		             uma2seq[ self.race_horse[key]['syaban'] ] = self.race_horse[key]['syaban'];
		             uma2waku[ self.race_horse[key]['syaban'] ] = self.race_horse[key]['wakuban'];
		         }
//		         console.error('uma2seq: %O',uma2seq);
//		         console.error('uma2waku: %O',uma2waku);

		         for (var umaban in uma2waku) {
		             waku_mark[uma2waku[umaban]] = 0;
		         }
		         for (var umaban in uma2waku) {
		             var seq = uma2seq[umaban];
		             if (self.my_mark[seq] && '99' != self.my_mark[seq]) {
			             waku_mark[uma2waku[umaban]]++;
		             }
		         }
		         if(self.debug) console.log('waku_mark: %O',waku_mark);
	         }
	         for (var j = 1; j <= self.max_uma; j++) {
		         if (self.btn_uno_disable[rix][j])
		             continue;
		         if (undefined === self.btn_uno[rix]) {
		             self.btn_uno[rix] = {};
		         }

		         if (0 == self.btn_func_stat['mark'][rix]) {
		             if ('3' == self.cur_shikibetu || '4' == self.cur_shikibetu) {
			             self.btn_uno[rix][j] = (waku_mark[j] > 0) ? true : false;
		             } else {
			             var uma2seq = {};
			             for(var key in self.race_horse){
			                 uma2seq[ self.race_horse[key]['syaban'] ] = self.race_horse[key]['syaban'];
			             }
			             var seq = uma2seq[j];
			             if (self.my_mark[seq] && '99' != self.my_mark[seq]) {
			                 // 印がある('99':消以外)
			                 self.btn_uno[rix][j] = true;
			             } else {
			                 self.btn_uno[rix][j] = false;
			             }
		             }
		         } else {
		             self.btn_uno[rix][j] = false;
		         }
	         }

	         // 印で選択ボタンの状態
	         if (0 == self.btn_func_stat['mark'][rix]) {
		         self.btn_func_stat['mark'][rix] = 1;
		         self.btn_func_stat['all'][rix] = 0;
	         } else {
		         self.btn_func_stat['mark'][rix] = 0;
	         }
	     } else if ('clear' == mode) {
		     self.btn_uno[rix] = {};
			 self.btn_func_stat['mark'][rix] = 0;
			 self.btn_func_stat['all'][rix] = 0;
	     }
	     console.log(self.btn_uno);
             //  console.log(self.btn_func_stat);
	     //	 console.log('self.btn_func_stat: %O',self.btn_func_stat);

	     // 点数を表示するため組合せを生成
	     var info = self.make_bet(100);
	     //info = self.make_bet(100);
	     if(info < 0){
	         self.bet_count = 0;
	         self.select_bet_odds = [];
	         self.select_kaime = false;
	     }else{
	         self.bet_count = info['bet_count'];
	         //選択中のオッズ一覧
	         var ret = self.make_select_bet_odds(info);
	         self.select_bet_odds = ret['odds_list'];
	         self.select_max_odds = ret['max_odds'];
	         self.select_min_odds = ret['min_odds'];
	         self.select_kaime = true;
	     }
     }

     /*
      * 車番選択、汎用関数(選択数上限あり)
      */
     self.max_uno = function(rix, uix, max) {
	     if (self.debug) console.log('self.max_uno(%s,%s,max)', rix, uix, max);

	     if (self.count_bet() > max) {
	         alert(sprintf("%d車以上は選択できません。", parseInt(max) + 1));
	         delete self.btn_uno[rix][uix];

	         self.update();
	         // 一度、再描画し、チェックを外す
	         var elm = document.getElementById(sprintf("uc-%d-%d", rix, uix));
	         elm.checked = false;
	     }
     }

     // 車番の選択数を調べる
     self.count_bet = function() {
	     var cnt = 0;
	     for (var r in self.btn_uno) {
	         for (var c in self.btn_uno[r]) {
		         cnt++;
	         }
	     }
	     //	 console.log('self.count_bet cnt: %s',cnt);
	     return cnt;
     }

     /*
      * 車番選択、汎用関数(単一選択)
      */
     self.radio_uno = function(rix, uix) {
	     if (self.debug)
	         console.log('self.radio_uno(%s,%s)', rix, uix);

	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     var b_uix = -1;
	     if (undefined !== self.btn_uno[rix]){
	         for (var u=0; u<=self.max_uma; u++){
		         if(u == uix)	continue;
		         if(self.btn_uno[rix][u]){
		             b_uix = u;
		             break;
		         }
	         }
	     }
	     //	 console.log('b_uix: %s',b_uix);
	     //	 console.log('self.btn_uno: %O',self.btn_uno);
	     //	 console.log('self.btn_uno_disable: %O',self.btn_uno_disable);
	     for(var i=0; i<3; i++){
	         if (! self.houshiki_attr[id]['in'][i])
		         continue;
	         if(rix != i && undefined !== self.btn_uno[i] && self.btn_uno[i][uix]) {
		         delete self.btn_uno[i][uix];
		         //		 console.log('delete(current) i: %s uix: %s',i,uix);
	         }
	         if(b_uix >0 && undefined !== self.btn_uno[i] && self.btn_uno[i][b_uix]) {
		         delete self.btn_uno[i][b_uix];
		         //		 console.log('delete(before) i: %s b_uix: %s',i,b_uix);
	         }
	         if(b_uix > 0){
		         self.btn_uno_disable[i][b_uix] = false;
	         }
	     }
     }

     /*
      * 車番選択、汎用関数(その他の軸の同一車番を選択解除、選択不可)
      */
     self.nodupp_uno = function(rix, uix) {
	     if (self.debug) console.log('self.nodupp_uno(%s,%s)', rix, uix);

	     // 選択不可を一旦クリア
	     var id = sprintf("%1d%1d", self.cur_shikibetu, self.cur_houshiki);
	     // その他の軸の同ー車番は、選択不可にする
	     for(var i=0; i<3; i++){
	         for (var u=1; u<=self.max_uma; u++) {
		         if (! self.houshiki_attr[id]['in'][i])
		             continue;
		         if(u == uix){
		             self.btn_uno_disable[i][u] = true;
		         }
	         }
	     }
	     //	 console.error('***: rix: %s uix: %s',rix,uix);
	     //	 console.error('***: %O',self.btn_uno_disable)
	     if (self.debug) console.log('self.btn_uno_disable: %O', self.btn_uno_disable);
     }

     /*
      * マルチ選択
      */
     self.act_multi = function(ev) {
	     if (self.debug) console.log('self.act_multi(%s)', ev.target.checked);

	     self.multi = ev.target.checked;

	     // 点数を表示するため組合せを生成
	     var info = self.make_bet(100);
	     if(info < 0){
	         self.bet_count = 0;
	         self.select_bet_odds = [];
	         self.select_kaime = false;
	     }else{
	         self.bet_count = info['bet_count'];
	         //選択中のオッズ一覧
	         var ret = self.make_select_bet_odds(info);
	         self.select_bet_odds = ret['odds_list'];
	         self.select_max_odds = ret['max_odds'];
	         self.select_min_odds = ret['min_odds'];
	         self.select_kaime = true;
	     }
     }

     /*
      * 金額入力
      */
     self.act_input_money = function(ev) {
	     if (self.debug) console.log('self.act_input_money(%s)', ev.target.value);

	     self.bet_money = ev.target.value * 100;
     }

     /*
      * 買い目一覧表示
      */
     self.render_bet_list = function() {
	     if (self.debug) console.log('self.render_bet_list');

	     self.bet_view = [];
	     self.total_bet_money = 0;
	     self.bet_odds_list = [];
	     self.disply_bet_view = {};
	     // 買い目取得(local)
	     var ndisam = new NDIsam();
	     var list = ndisam.list(self.isam_domain);

	     if(false === list){
	         console.error('isam empty..');
	         return;
	     }

	     for (var bet_no in list) {
	         var bet_info = self.bet_gen(list[bet_no]['bet_id'], list[bet_no]['bet_money']);
	         // オッズ配当計算
	         if ('0' == bet_info['houshiki']) {
		         // 通常(バラ買い)
		         var key = '';
		         if ('1' == bet_info['shikibetu'] || '2' == bet_info['shikibetu']) {
		             key = sprintf("%02d", bet_info['kaime1']);
		         } else if ('3' == bet_info['shikibetu'] || '4' == bet_info['shikibetu'] || '5' == bet_info['shikibetu'] || '6' == bet_info['shikibetu'] || '7' == bet_info['shikibetu']) {
		             key = sprintf("%02d%02d", bet_info['kaime1'], bet_info['kaime2']);
		         } else if ('8' == bet_info['shikibetu'] || '9' == bet_info['shikibetu']) {
		             key = sprintf("%02d%02d%02d", bet_info['kaime1'], bet_info['kaime2'], bet_info['kaime3']);
		         }
		         var payback = 0;
		         if (undefined === self.odds[bet_info['shikibetu']]){
		             if(self.debug) console.error('empty odds shikibetu: %s',bet_info['shikibetu']);
		         }else if (undefined === self.odds[bet_info['shikibetu']][key]){
		             if(self.debug) console.error('unkown key : %s', key);
		             payback = 0;
		         } else {
		             var payback = self.odds[bet_info['shikibetu']][key][0] * bet_info['bet_money'];
		             payback = Math.round(payback);
		             if(self.bet_odds_list[bet_info['bet_id']] === undefined){
		                 self.bet_odds_list[bet_info['bet_id']] = [];
		             }
		             self.bet_odds_list[bet_info['bet_id']].push(self.odds[bet_info['shikibetu']][key][0]);
		         }
		         bet_info['payback'] = payback;
	         } else {
		         // 以外(組合せ買い)
		         bet_info['payback'] = [];
		         bet_info['comb_odds'] = [];
		         for (var i = 0; i < bet_info['comb'].length; i++) {
		             var val = bet_info['comb'][i].split(/-/);
		             var comb_odds = '';
		             var key = '';
		             for (var j = 0; j < val.length; j++) {
			             key += sprintf("%02d", val[j]);
		             }
		             if (undefined === self.odds[bet_info['shikibetu']]){
			             if(self.debug) console.error('empty odds shikibetu: %s',bet_info['shikibetu']);
		             }else if(undefined === self.odds[bet_info['shikibetu']][key]){
			             if(self.debug) console.error('unkown key : %s', key);
			             payback = 0;
			             comb_odds = '0.0';
		             } else {
			             payback = self.odds[bet_info['shikibetu']][key][0] * bet_info['bet_money'];
			             payback = Math.round(payback);
			             comb_odds = self.odds[bet_info['shikibetu']][key][0];
			             if(self.bet_odds_list[bet_info['bet_id']] === undefined){
			                 self.bet_odds_list[bet_info['bet_id']] = [];
			             }
			             self.bet_odds_list[bet_info['bet_id']].push(self.odds[bet_info['shikibetu']][key][0]);
		             }
		             //if (self.debug) console.log('payback: %s:', payback);
		             bet_info['payback'].push(payback);
			         bet_info['comb_odds'].push(comb_odds);
		         }
	         }
	         bet_info['bet_no'] = bet_no;
	         bet_info['open'] = 0;
	         self.bet_view.push(bet_info);

	         self.disply_bet_view = self.make_bet_view_obj();
	         // 総合計金額
	         self.total_bet_money += parseInt(bet_info['bet_money_total']);
	     }
	     if (self.debug) console.log('self.total_bet_money: %s', self.total_bet_money);
	     if (self.debug) console.log('self.bet_view: %O', self.bet_view);
	     if (self.debug) console.log('self.bet_odds_list: %O', self.bet_odds_list);
     }

     /*
      * 式別・方式別の車番選択、妥当性チェック
      */
     self.check_umaban_selection = function(normal_flg) {
	     if (self.debug) console.log('self.check_umaban_selection');

	     var umaban_num = [0, 0, 0];
	     // 選択中の車番ボタンを行毎にカウント
	     for (var i in self.btn_uno) {
	         var row = self.btn_uno[i];
	         for (var uno in row) {
		         if (true == row[uno]) {
		             umaban_num[i]++;
		         }
	         }
	     }
	     var houshiki = normal_flg ? '0' : self.cur_houshiki;

	     var key = sprintf("%1d%1d", self.cur_shikibetu, houshiki);

	     if (self.debug) console.log('umaban_num: %O', umaban_num);
	     if (self.debug) console.log('key: %s', key);

	     var ary_rule = self.houshiki_check[key]['chk'];

	     //	 console.error('ary_rule: %O',ary_rule);
	     var err = false;
	     for (var i = 0; i < ary_rule.length; i++) {
	         var r = ary_rule[i].split(/:/);
	         // r[0] = ルール  'eq:1' １つのみ                'gt:1' １つ以上
	         if ('eq' == r[0]) {
		         if (umaban_num[i] != r[1]) {
		             err = true;
		         }
	         } else if ('gt' == r[0]) {
		         if (umaban_num[i] < r[1]) {
		             err = true;
		         }
	         }
	     }

	     if (self.debug) console.log('err: %s', err);
	     return err;
     }

     /*
      * 買い目追加
      */
    self.act_add_bet = function(ev) {
         if (self.debug) console.log('self.act_add_bet()');

        self.phase = 5;
         //デフォルト100円
         self.bet_money = 100;
        // 18.6.1 小数点で入力可能な不具合
        var chk_money = self.bet_money / 100;
        if(Math.round(chk_money) !== chk_money || chk_money < 1){
             self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
            //alert("\n金額が未入力、あるいは正しくありません。\n");
            return false;
        }
        console.log(self.btn_uno);
        console.log(self.select_kaime);
        if(!self.select_kaime && Object.keys(self.select_odds).length >= 1){
             //各買い目のオッズを選択時
             self.set_bet_odds(self.select_odds);
        }else{
            //組み合わせ選択
            self.set_bet();
        }

        //$(".SetListBtn").addClass("BetPlusClick");
        //setTimeout(function () {
        //    $(".SetListBtn").removeClass("BetPlusClick");
        //}, 1500);

        self.reset_uno(-1, 1); // 車番ボタンエリア初期化
        self.bet_select = {}; // 買い目選択
        self.bet_select_all = false; // 買い目選択(全選択・全解除)
        self.bet_money = -1; // 金額クリア

        // 全選択・クリア、印で選択を初期化
        self.btn_func_stat = {all: [0, 0, 0], mark: [0, 0, 0]};

        // マルチが選択不可な場合は、非表示
        if (('6' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki))
            || ('9' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki || '5' == self.cur_houshiki || '6' == self.cur_houshiki || '7' == self.cur_houshiki || '8' == self.cur_houshiki))
                 || ('4' == self.cur_shikibetu && ('3' == self.cur_houshiki || '4' == self.cur_houshiki))
            ) {
            self.multi_attr = true;
        } else {
            self.multi_attr = false;
        }
        self.multi = false;	     // マルチon,offをクリア
        self.select_kaime = false; //買い目選択on.offをクリア
        self.select_odds = {};
        self.select_bet_odds = [];
        self.bet_count = 0; // 買い目点数クリア
        var url = sprintf("%sbet/editor.html?date=%s&race_id=%s&m=bet_list", self.args.keirin_url, self.kaisai_date, self.cur_race_id);
        location.href = url;
        return;
    }

    self.set_bet = function(normal_flg){
        console.log('self.set_bet');
        var bet_info = self.make_bet(self.bet_money, normal_flg);

        if(-1 == bet_info){
            self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
            return false;
        }else if(-2 == bet_info){
            //self.err_info_swal('車番が正しく、選択されていません。', false);
            //return false;
        }

        if(bet_info['bet_count'] < 1){
            self.err_info_swal('組み合わせがありません。', false);
            return false;
        }else{
            if (bet_info['bet_money'] <= 0) {
                self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
                return false;
            }
        }

        if(bet_info != -2){
            var ndisam = new NDIsam();
            // 投票管理番号を生成 (キーは現在時刻、ミリ秒まで)
            var rand = Math.floor(Math.random() * 99); //稀にキーがかぶるので乱数追加
            var bet_no = sprintf("%s_%s_%s",self.cur_race_id,CybozuLabs.MD5.calc(Date.now()), rand);
console.log(bet_no);
            bet_info['bet_no'] = bet_no;

            var ret = ndisam.replace(self.isam_domain, bet_no, {
                bet_id: bet_info['bet_id'],
                bet_money: self.bet_money
            });
            if(ret){
                self.bet_view.push(bet_info);
            }
        }
    }

     //------------------------------------------------------------
     self.bet_gen = function(bet_id, bet_money) {
	     if (self.debug) console.log('self.bet_gen(%s,%s)', bet_id, bet_money)

	     if(undefined === bet_id){
	         return {};
	     }

	     var part = bet_id.split(/_/);
	     var s = part[1].substr(1, 1);
	     var h = part[1].substr(1, 1) + part[2].substr(1, 1);

	     var ipat = new IpatDataModel();
	     var info = [];
	     var waku_check = []; // 枠連の場合は、複数頭の枠番号を配列で渡す

	     for (var w in self.waku_horse) {
	         var num = Object.keys(self.waku_horse[w]).length;
	         if (num > 1) {
	         	for(var key in self.waku_horse[w]){
	         		var ijyo_check = false;
	         		if(self.waku_horse[w][key]['sales_sts'] == '1' || self.waku_horse[w][key]['sales_sts'] == '3'){
	         			ijyo_check = true;
	         			break;
	         		}
	         	}
	         	if(!ijyo_check){
		         	waku_check.push(w);
	         	}
	         }
	     }
	     if (self.debug) console.log('waku_check: %O',waku_check);
	     info = ipat.cvt_bet(bet_id, bet_money, waku_check);

	     // 競車場、レース番号
	     var p = part[0].split(/-/);
	     var ary_jyo = {
	         1: '札幌',
	         2: '函館',
	         3: '福島',
	         4: '新潟',
	         5: '東京',
	         6: '中山',
	         7: '中京',
	         8: '京都',
	         9: '阪神',
	         a: '小倉'
	     };
	     info['race_name'] = sprintf("%s %02dR", ary_jyo[p[1]], p[2]);

	     if ('0' == h.substr(1, 1)) {
	         var str = '';
	         if ('1' == info['shikibetu'] || '2' == info['shikibetu']) {
		         str = sprintf("%d", info['kaime1']);
	         } else if ('3' == info['shikibetu'] || '4' == info['shikibetu'] || '5' == info['shikibetu'] || '6' == info['shikibetu']) {
		         str = sprintf("%d-%d", info['kaime1'], info['kaime2']);
	         } else if ('8' == info['shikibetu'] || '9' == info['shikibetu']) {
		         str = sprintf("%d-%d-%d", info['kaime1'], info['kaime2'], info['kaime3']);
	         }
	         info['kumi_name'] = str;
	     }

	     // 17.10.28
	     info['ary_kaime'] = [];
	     for(var i=1; i<=3; i++){
	         if('' != info['kaime'+i]){
		         var val = info['kaime'+i].split(/-/);
		         info['ary_kaime'].push(val);
	         }
	     }
	     return info;
     }

     /*
      * 買い目の選択
      */
     self.act_kaime_select = function(bix, bcix) {
	     if (self.debug) console.log('self.act_kaime_select(%s,%s)', bix, bcix);

	     var sel = 'c';
	     if (bcix < 0) { // 親を選択
	         sel = 'p';
	         bcix = 0;
	     }

	     // トグルの動作
	     if (self.bet_select[bix * 1000 + bcix]) {
	         delete self.bet_select[bix * 1000 + bcix]; // 選択を解除する
	     } else {
	         // 別の組合せの選択を解除する(ToDo)
	         for (var key in self.bet_select) {
		         var p = Math.floor(key / 1000);
		         var c = Math.floor(key % 1000);
		         console.error('p: %s c: %s',p,c);
		         if('c' == sel) {
		             if(bix == p)	continue;
		             //console.log('remove child: %s',key);
		             delete self.bet_select[key]; // 選択を解除する
		         }
		         if ('p' == sel) { // 親を選択の場合
		             if(c != 0){
			             //console.log('remove parent: %s',key);
			             delete self.bet_select[key]; // 選択を解除する
		             }
		         }
	         }
	         if ('c' == sel) { // 子を選択の場合
			     self.bet_select_all = false; //全選択解除
		         var p = Math.floor(bcix / 1000);
		         //console.log('remove my parent: %s',(p+1) * 1000);
		         delete self.bet_select[(p + 1) * 1000]; // その親の選択も解除
	         }

	         self.bet_select[bix * 1000 + bcix] = true; // 選択済みにする
	     }
	     if (self.debug) console.log('self.bet_select: %O', self.bet_select);
     }

     /*
      * 買い目の全選択・全選択解除
      */
     self.act_kaime_select_all = function() {
	     if (self.debug) console.log('self.act_kaime_select_all()');

	     if (false === self.bet_select_all) { // 全解除
	         self.bet_select_all = true;
	         for (var i = 0; i < self.bet_view.length; i++) {
		         self.bet_select[i * 1000] = true;
	         }
	     } else {
	         self.bet_select_all = false;
	         self.bet_select = {};
	     }
	     if (self.debug) console.log('self.bet_select: %O', self.bet_select);
     }


     /*
      * 金額変更モーダル表示
      */
//     self.act_change_money_open = function() {
//	window.setTimeout(function () {
//		$('.BatchInputValue input').trigger('focus');
//	},300);
//     }

     /*
      * 買い目の金額変更
      */
     self.act_change_money = function(exec) {
	     if (self.debug) console.log('self.act_change_money(%s)', exec);
	     	console.log(self.bet_money);
	     if (exec) {
	         // 18.6.1 小数点で入力可能な不具合 1 -> 100
	         var chk_money = self.bet_money / 100;
	         //if(Math.round(chk_money) !== chk_money || chk_money < 1) {
		     //    alert("\n金額が未入力、あるいは正しくありません。\n");
		     //    return false;
	         //}

	         var c = 0;
	         var p = 0;
	         for (var key in self.bet_select) {
		         var id = Math.floor(key / 1000);
		         var mod = Math.floor(key % 1000);
		         if (mod == 0) {
		             p++;
		         } else {
		             c++;
		         }
	         }
	         if (self.debug) console.log('p: %s c: %s', p, c);

	         if (p > 0) {
		         // 買い目金額変更(local)
		         var ndisam = new NDIsam();

		         for (var key in self.bet_select) {
		             var id = Math.floor(key / 1000);
		             var up_data = {
			             bet_id: self.bet_view[id]['bet_id'],
			             bet_money: self.bet_money
		             };
		             ndisam.replace(self.isam_domain, self.bet_view[id]['bet_no'], up_data);
		         }
		         self.render_bet_list();
		         self.bet_select = {};
		         self.bet_money = -1;
		         self.is_edit = false;
	         } else if (c > 0) {
                self.err_info_swal("買い目が展開されますが、よろしいですか？", function(){
                    self.change_money_bet_child();
                    self.render_bet_list();
                    self.bet_select = {};
                    self.bet_money = -1;
                    self.is_edit = false;
                    self.update();
                });
	         }
	     }
	     $('#m-change_money').modal('hide'); // モーダル非表示
     }

     /*
      * 買い目の削除
      */
     self.act_kaime_delete = function() {
	     if (self.debug) console.log('self.act_kaime_delete()');

	     var c = 0;
	     var p = 0;
	     for (var key in self.bet_select) {
	         var id = Math.floor(key / 1000);
	         var mod = Math.floor(key % 1000);
	         if (mod == 0) {
		         p++;
	         } else {
		         c++;
	         }
	     }
	     if (self.debug) console.log('p: %s c: %s', p, c);

	     if (p > 0) {
	         // 親レコードの削除
            self.err_info_swal("本当に削除してもよろしいですか？", function(){
                // 買い目削除(local)
                var ndisam = new NDIsam();
                for (var key in self.bet_select) {
                    var id = Math.floor(key / 1000);
                    console.log(id);
                    ndisam.remove(self.isam_domain, self.bet_view[id]['bet_no']);
                }
                self.render_bet_list();
                self.bet_select = {};
                self.is_edit = false;
                self.bet_select_all = false;
                self.update();
            });
	     } else if (c > 0) {
            self.err_info_swal("本当に削除してもよろしいですか？", function(){
                self.delete_bet_child();
                self.render_bet_list();
                self.bet_select = {};
                self.is_edit = false;
                self.bet_select_all = false;
                self.update();
            });
	     }
     }

     /*
      * 買い目削除(ゴミ箱)
      */
     self.act_kaime_delete_trashbox = function(bix, bcix) {
	     if (self.debug) console.log('self.act_kaime_delete_trashbox()');
	     self.act_kaime_select(bix, bcix);
	     self.act_kaime_delete();
     }

     /*
      * 組合せ買い(フォーメーション、BOX,流し)の展開形を部分的に削除する
      */
     self.delete_bet_child = function() {
	     if (self.debug) console.log('self.delete_bet_child');

	     var del_c = {};
	     var p_id = -1;
	     for (var key in self.bet_select) {
	         p_id = Math.floor(key / 1000);
	         var c_id = Math.floor(key % 1000);
	         del_c[c_id - 1] = true;
	     }
	     if (self.debug) console.log('del_c: %O', del_c);

	     var add_c = [];
	     for (var i = 0; i < self.bet_view[p_id]['comb'].length; i++) {
	         var kaime = self.bet_view[p_id]['comb'][i];
	         if(self.debug) console.log('kaime: %s',kaime);
	         if (!del_c[i]) {
		         add_c.push(kaime);
	         }
	     }
	     if (self.debug) console.log('add_c: %O', add_c);

	     // 新たな買い目コードを作成
	     var part = self.bet_view[p_id]['bet_id'].split(/_/);
	     if (self.debug) console.log('part: %O', part);

	     var new_part = [part[0], part[1], ''];
	     var del_bet_no = self.bet_view[p_id]['bet_no'];
	     if (self.debug) console.log('del_bet_no: %s', del_bet_no);

	     new_part[2] = 'c0'; // 方式=通常

	     // 買い目取得(local)
	     var ndisam = new NDIsam();
	     ndisam.remove(self.isam_domain, del_bet_no);
	     for (var i = 0; i < add_c.length; i++) {
	         // 10が1となるバグ、暫定
	         //	     new_part[3] = add_c[i].replace(/0/g, '');
	         //	     new_part[3] = new_part[3].replace(/-/g, '_');
	         var ary_val = add_c[i].split(/-/);
	         for(var x=0; x<ary_val.length; x++){
		         ary_val[x] = parseInt(ary_val[x]);
	         }
	         new_part[3] = ary_val.join('_');
	         //	     console.error('new_part[3]: %s',new_part[3]);
	         var bet_id = new_part.join('_');
	         if (self.debug) console.log('bet_id: %s', bet_id);

	         // 投票管理番号を生成 (キーは現在時刻、ミリ秒まで)
	         var str_rand = Date.now() + i;
	         if(self.debug) console.log('str_rand: %s',str_rand);
	         var bet_no = sprintf("%s_%s",self.cur_race_id,CybozuLabs.MD5.calc(str_rand));
	         // 買い目を保存(local)
	         var bet_money = self.bet_view[p_id]['bet_money'];
	         //		 console.log('bet_id: %s bet_money: %s bet_no: %s',bet_id,bet_money,bet_no);
	         ndisam.replace(self.isam_domain, bet_no, {
		         bet_id: bet_id,
		         bet_money: bet_money
	         });
	     }
     }

     /*
      * 組合せ買い(フォーメーション、BOX,流し)の展開形を部分的に金額変更する
      */
     self.change_money_bet_child = function() {
	     if (self.debug) console.log('self.change_money_bet_child');
	     if (self.debug) console.log('self.bet_select: %O',self.bet_select);

	     var del_c = {};
	     var p_id = -1;
	     for (var key in self.bet_select) {
	         p_id = Math.floor(key / 1000);
	         var c_id = Math.floor(key % 1000);
	         del_c[c_id - 1] = true;
	     }
	     if (self.debug) console.log('del_c: %O p_id: %s', del_c,p_id);

	     var add_c = {};
	     for (var i = 0; i < self.bet_view[p_id]['comb'].length; i++) {
	         var kaime = self.bet_view[p_id]['comb'][i];
	         if(self.debug) console.log('kaime: %s',kaime);
	         if (del_c[i]) {
		         // 選択されていたら、変更後金額
		         add_c[kaime] = self.bet_money;
	         } else {
		         // 未選択は、元の金額
		         add_c[kaime] = self.bet_view[p_id]['bet_money'];
	         }
	     }
	     if (self.debug) console.log('add_c: %O', add_c);


	     // 新たな買い目コードを作成
	     var part = self.bet_view[p_id]['bet_id'].split(/_/);
	     if (self.debug) console.log('part: %O', part);

	     var new_part = [part[0], part[1], ''];
	     var del_bet_no = self.bet_view[p_id]['bet_no'];
	     if (self.debug) console.log('del_bet_no: %s', del_bet_no);

	     new_part[2] = 'c0'; // 方式=通常

	     // 買い目取得(local)
	     var ndisam = new NDIsam();
	     ndisam.remove(self.isam_domain, del_bet_no);
	     console.log(add_c);
	     var i = 0;
	     for (var key in add_c) {
	         // 10が1となるバグ、暫定
	         //	     new_part[3] = key.replace(/^0/g, '');
	         //	     new_part[3] = new_part[3].replace(/-/g, '_');
	         var ary_val = key.split(/-/);
	         for(var x=0; x<ary_val.length; x++){
		         ary_val[x] = parseInt(ary_val[x]);
	         }
	         new_part[3] = ary_val.join('_');
	         //	     console.error('new_part[3]: %s',new_part[3]);
	         var bet_id = new_part.join('_');
	         if (self.debug) console.log('bet_id: %s', bet_id);

	         // 投票管理番号を生成 (キーは現在時刻、ミリ秒まで)
	         var str_rand = Date.now() + i;
	         if(self.debug) console.log('str_rand: %s',str_rand);
	         var bet_no = sprintf("%s_%s",self.cur_race_id,CybozuLabs.MD5.calc(str_rand));
             console.log('bet_no: ',bet_no);
	         // 買い目を保存(local)
	         var bet_money = add_c[key];
	         if (self.debug) console.log('bet_id: %s bet_money: %s bet_no: %s', bet_id, bet_money, bet_no);
	         ndisam.replace(self.isam_domain, bet_no, {
		         bet_id: bet_id,
		         bet_money: bet_money
	         });
	         i++;
	     }
     }

    /*
     * tipstarに投票をする
     */
    self.tipstar_bet = function(type) {

        if (self.debug) console.log('self.tipstar_bet');

        if(!self.cur_race['sale_status'] || self.cur_race['sale_status'] <= 0){
            self.err_info_swal('このレースは発売時間外です。', false);
            return;
        }

        var now = new Date();
        var year = self.cur_race_id.substr(0, 4);
        var month = self.cur_race_id.substr(4, 2);
        var day = self.cur_race_id.substr(6, 2);
        var time = self.cur_race['close'].split(':');
        var endtime = new Date(year,month - 1,day,time[0],time[1]);
        if(now.getTime() >= endtime.getTime()){
            self.err_info_swal('このレースの投票は締め切りました。', false);
            return;
        }

        //ログイン必須
        if(!self.args.sns_user_id){
            self.show_registor_popup();
            return;
        }

        //PC確認(tipstar.jsから抜粋)
        if(!matchSmallLayout().matches) {
             modalTipstarShow("tipstar_pc.html");
             return;
        }

        var ts_race_id = sprintf("%s-%s-%s_%s_%s", self.cur_race_id.substr(0,4), self.cur_race_id.substr(4,2), self.cur_race_id.substr(6,2), self.cur_race_id.substr(8,2), self.cur_race_id.substr(10,2));
        var tipstar_bet = self.make_tipstar_bet(ts_race_id);
        console.log(tipstar_bet);
        if(!tipstar_bet){
            return;
        }

        //tip遷移案内確認
        if(IsMcShow && type == 'bet'){
            //モーダル表示
            self.is_tipstar_modal = true;
            self.update();
            self.show_tipstar_modal();
            return;
        }
        if(type == 'modal'){
            //cookieセット
            checkModalNone();
        }

        //var bet_id = self.args.hash + now.getTime();
        var raceChannelId = self.cur_race_id.substr(8,2); //jyo_cd

        //テスト中(tipstarの向き先変更)
        const tipstarOrigin = self.args.tipstar_url;
        self.tab = window.open(tipstarOrigin + '/raceChannels/' + raceChannelId + '/' + ts_race_id + '/bets');

        //const tipstarOrigin = 'https://zrace.sp.netkeiba.com';
        //self.tab = window.open(tipstarOrigin + '/race/tipstar.html' + '?raceChannels=' + raceChannelId + '&race_id=' + ts_race_id);
        //テスト中ここまで

        const eventListenerCallback = (e) => {
            if (e.origin !== tipstarOrigin) {
                return;
            }
            if (e.data.action === "HandShake") {
                //買い目をredisに保存
                var ndisam = new NDIsam();
                var list = ndisam.list(self.isam_domain);
                var ary_bet = [];
                if(false !== list){
                    for(var bet_key in list){
                        ary_bet.push({bet_id: list[bet_key]['bet_id'], money: list[bet_key]['bet_money']});
                    }
                }

                //user_bet_sessionTBLに挿入
                //bet_id = yyyymmdd + 00000001(8桁 + 8桁)
                var _data = {};
                _data.output = 'json';
                _data.mode = 'add';
                _data.bet_list = ary_bet;
                _data.race_id = self.cur_race_id;
                $.ajax({
                    type     : 'POST',
//                    type     : 'get',
                    url      : self.args.keirin_url + '/bet/api_post_tipstar_bet.html',
                    data     : _data,
                    dataType : _data.output,
                    success  : function( ret ){
                        console.log(ret);
                        if(ret['status'] == 'OK'){
                            self.bet_id = ret['bet_id'];
                            var bet_complete_url = sprintf("%sbet/api_post_tipstar_bet.html?mode=update&bet_id=%s", self.args.keirin_url, self.bet_id);
                            console.log(bet_complete_url);

                            // MEMO: messageに任意のJSONをいれる
                            self.tab.postMessage({
                                action: 'SendNetKeirinTickets',
                                message: {
                                    bet_id: self.bet_id,//netkririn側投票ID(NDで管理するユニークなID)
                                    netkeibaId: self.args.sns_user_id,
                                    bet_complete_url: encodeURI(bet_complete_url), //bet_idをパラメータをつける(tip側ではこのURLを実行してもらう)
                                    redirect_url: encodeURI(sprintf("%s/shishi/", self.args.keirin_url)), //tipstar側でタブが閉じられなかったときの遷移先
                                    tickets: tipstar_bet,
                                },
                            }, tipstarOrigin);
                            // MEMO: 車券情報の送信が終わったらイベントリスナを削除する
                            window.removeEventListener("message", eventListenerCallback);
                            //オッズのアップデート停止
                            if(self.odds_update_timer){
                                clearInterval(self.odds_update_timer);
                            }
                            //セットインターバル(500ms,購入完了状態を確認,api_post_tipstar_bet check, キーがbet_id)
                            self.count = 0;
                            self.check_bet_status();
                        }

                    },
                    error  : function(XMLHttpRequest, textStatus, errorThrown){
                        console.log('XMLHttpRequest: %O',XMLHttpRequest);
                        console.log('textStatus: %s',textStatus);
                    }
                });
            }
        }
        window.addEventListener("message", eventListenerCallback);
    }

    /*
     * TIPSTAR用の買い目作成
     */
    self.make_tipstar_bet = function(ts_race_id) {
        if (self.debug) console.log('self.make_tipstar_bet');
        var odds_type = {
             '3' : 'niwakufuku', //枠複
             '4' : 'niwakutan', //枠単
             '5' : 'nishafuku', //２車複
             '6' : 'nishatan', //２車単
             '7' : 'wide', //ワイド
             '8' : 'sanrenfuku', //３連複
             '9' : 'sanrentan', //３連単
        };
        var ndisam = new NDIsam();
        var list = ndisam.list(self.isam_domain);
        if(!list || Object.keys(list).length <= 0){
            self.err_info_swal('買い目がありません', false);
            return false;
        }
        var ipat = new IpatDataModel();
        var waku_check = []; // 枠連の場合は、複数頭の枠番号を配列で渡す
        for (var w in self.waku_horse) {
            var num = Object.keys(self.waku_horse[w]).length;
            if (num > 1) {
                waku_check.push(w);
            }
        }
        var bet_list = [];
        for (var bet_no in list) {
            var info = ipat.cvt_bet(list[bet_no]['bet_id'], list[bet_no]['bet_money'], waku_check);
            //金額チェック
            var chk_money = list[bet_no]['bet_money'] / 100;
            if(Math.round(chk_money) !== chk_money || chk_money < 1) {
                self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
                return false;
            }

            if(info['comb']){
                //買い目をばらす
                var tmp_ts_bet = info['comb'].map(function(kaime){
                    var betNumbers = kaime.split('-').map(function(k){
                        return parseInt(k.replace(/^0/, ''));
                    });
                    var ts_bet = {
                        'betCoin': 0,
                        'betMoney': list[bet_no]['bet_money'],
                        'betNumbers': betNumbers,
                        'betType': odds_type[info['shikibetu']],
                        'keirinRaceId': ts_race_id,
                    };
                    return ts_bet;
                });
                bet_list = bet_list.concat(tmp_ts_bet);
            }else{
                var ts_kaime = [];
                ts_kaime.push(parseInt(info['kaime1']), parseInt(info['kaime2']));
                if(info['kaime3']){
                    ts_kaime.push(parseInt(info['kaime3']));
                }
                var tmp_ts_bet = {
                    'betCoin': 0,
                    'betMoney': list[bet_no]['bet_money'],
                    'betNumbers': ts_kaime,
                    'betType': odds_type[info['shikibetu']],
                    'keirinRaceId': ts_race_id,
                };
                bet_list.push(tmp_ts_bet);
            }
        }
        return bet_list;
    }

    /*
     * 投票を確定する
     */
    self.act_bet_complete = function(){
        if (self.debug) console.log('self.act_bet_complete');
        //ログイン必須
        if(!self.args.sns_user_id){
            return;
        }

        //買い目をローカルストレージからcartに入れる
        var ndisam = new NDIsam();
        var list = ndisam.list(self.isam_domain);
        var ary_bet = [];
        if(false !== list){
            for(var bet_key in list){
            ary_bet.push({bet_id: list[bet_key]['bet_id'], money: list[bet_key]['bet_money']});
            }
        }

        var group_bet = 'bet_'+self.cur_race_id;
        var cart_api = new NDCartApi(self.args.cart_url);
        cart_api.clear_item(group_bet, function(resp){
            console.log('clear_item : ', resp);
            var ary_item_id = [];
            var ary_item_value = [];
            var ary_item_price = [];
            var ary_client_data = [];
            for(var i in ary_bet){
                ary_item_id.push(ary_bet[i]['bet_id']);
                ary_item_value.push(1);
                ary_item_price.push(ary_bet[i]['money']);
                ary_client_data.push('');
            }
            $.ajax({
                url:  self.args.cart_url,
                type: 'post',
                dataType: 'json',
                data: {
                    action: 'add',
                    group: group_bet,
                    item_id: ary_item_id,
                    item_value: ary_item_value,
                    item_price: ary_item_price,
                    client_data: ary_client_data,
                },
                success  : function( data ){
                    //tipstarに投票する
                    //self.tipstar_bet();
                    //ストレージ削除
                    ndisam.clear(self.isam_domain);
                    //My収支に遷移
                    var location_url = sprintf("%s/bet/bet_complete.html?race_id=%s", self.args.keirin_url, self.cur_race_id);
                    console.log(location_url);
                    window.location.href = location_url;
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                    console.error('textStatus: ',textStatus);
                    console.error('errorThrown.message: ',errorThrown.message);
                }
            });
        });
    }

    self.tipstar_charge = function(){
        console.log('self.tipstar_charge');
        var location_url = sprintf("%s/charge?fromUrl=%s", self.args.tipstar_url, encodeURIComponent(location.href));
        console.log(location_url);
        location.href = location_url;
    }

    self.act_change_mode = function(mode){
        if(mode == 'add'){
            //買い目一覧
            //self.bet_mode = 'bet';
            $('.DeployYoso').hide();
        }else{
            //買い目追加
            self.bet_mode = 'add';

            $('.DeployYoso').show();
        }
        console.log('act_change_mode: ',self.bet_mode);
        self.act_shikibetu(9);
        var topOffset = $(".IpatVote").offset().top;
        $(window).scrollTop(topOffset);
    }

     /*
      * 金額入力
      */
     self.act_change_money_single = function(ev) {
		if (self.debug) console.log('self.act_chenge_money(%O)', ev);

		if (ev) {
			var bet_id = ev.item.bet.bet_no;
			var kaime = ev.item.bet.bet_id;
			self.bet_money = ev.target.value * 100;
	    	// 18.6.1 小数点で入力可能な不具合 1 -> 100
	    	//var chk_money = self.bet_money / 100;
	    	//if(Math.round(chk_money) !== chk_money || chk_money < 1) {
			//	alert("\n金額が未入力、あるいは正しくありません。\n");
			//	//return false;
	    	//}
			// 買い目金額変更(local)
			var ndisam = new NDIsam();
			ndisam.replace(self.isam_domain, bet_id, {bet_id: kaime, bet_money: self.bet_money});
			self.render_bet_list();
			self.bet_select = {};
			self.bet_money = -1;
	    }else{
	    	self.is_change_money = false;
	    }
	 }

     /*
      * 金額変更ボタン
      */
     self.act_money_change_btn = function(act, ev) {
		if (self.debug) console.log('self.act_money_change_btn(%O)', ev);

		if (!ev.item.comb) {
			//親選択
	 		var bet_id = ev.item.bet.bet_no;
	 		var kaime = ev.item.bet.bet_id;
	 		if(act == 'm'){
	 			self.bet_money = ev.item.bet.bet_money - 100;
	 		}else{
	 			self.bet_money = ev.item.bet.bet_money + 100;
	 		}
	    	// 18.6.1 小数点で入力可能な不具合 1 -> 100
	    	var chk_money = self.bet_money / 100;
	    	if(Math.round(chk_money) !== chk_money || chk_money < 0) {
	    	//if(Math.round(chk_money) !== chk_money || chk_money < 1) {
				//self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
				return false;
	    	}
			// 買い目金額変更(local)
			var ndisam = new NDIsam();
			ndisam.replace(self.isam_domain, bet_id, {bet_id: kaime, bet_money: self.bet_money});
			self.render_bet_list();
			self.bet_select = {};
			self.bet_money = -1;
	    }
	 }

     /*
      * 金額変更ボタン
      */
    self.act_money_change_btn_child = function(bet_money, bix, bcix, act) {
        if (self.debug) console.log('self.act_money_change_btn_child');
        //子選択
            if(act == 'm'){
                self.bet_money = bet_money - 100;
            }else{
                self.bet_money = bet_money + 100;
            }
            var chk_money = self.bet_money / 100;
            if(Math.round(chk_money) !== chk_money || chk_money < 0) {
            //if(Math.round(chk_money) !== chk_money || chk_money < 1) {
                //self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
                return false;
            }

        self.err_info_swal("買い目が展開されますが、よろしいですか？", function(){

            self.act_kaime_select(bix, bcix);
            self.change_money_bet_child();
            self.render_bet_list();
            self.bet_select = {};
            self.bet_money = -1;
            self.update();
        });
    }

     /*
      * 金額変更(入力)
      */
    self.act_money_change_child = function(bix, bcix, ev) {
        if (self.debug) console.log('self.act_money_change_child', ev.target.value);
        self.chk_money = ev.target.value;
         //if(self.chk_money < 1){
         if(self.chk_money < 0){
             //self.err_info_swal('金額が未入力、あるいは正しくありません。', false);
             return false;
         }
        //子選択
        self.err_info_swal("買い目が展開されますが、よろしいですか？", function(){
            self.bet_money = self.chk_money * 100;
            self.act_kaime_select(bix, bcix);
            self.change_money_bet_child();
            self.render_bet_list();
            self.bet_select = {};
            self.bet_money = -1;
            self.update();
        });
    }

    self.act_money_check = function(ev){
        if (self.debug) console.log('self.act_money_check', ev.target.value);
        self.before_money = 0;
        if(ev.target.value){
            self.before_money = ev.target.value;
        }
        ev.target.select();
    }

     /*
      * swalの共通関数
      */
    self.err_info_swal = function(err_msg, fn) {
       if(!err_msg){
           return;
       }
       var option = {title: err_msg}

       if(fn){
           option['showCancelButton'] = true;
           option['cancelButtonText'] = 'やめる';
       }
        swal.fire(option).then(function(ret){
            if(true == ret.value && fn){
               fn();
            }else{
                if(self.before_money){
                    console.log(self.before_money);
                    $('.child_input').val(self.before_money);
                }
            }
        });
    }

    self.login_error = function(){
        swal.fire({
            title: "<p class='login'>ご利用には連携サイト「netkeiba.com」のアカウント登録が必要です。</p>\n<p class='to-account'>すでにnetkeiba.comをご利用中の方はログインをお願いいたします。</p>",
            confirmButtonText: 'netkeibaID登録',
        }).then(function(ret){
            if(true == ret.value){
                $(window).on('message', function(event){
                  if (event.originalEvent.origin !== self.args.regist_netkeiba_url ) return;
                  if (event.originalEvent.data === 'register_done' ) {
                      location.reload();
                  }
                });
                var return_url = location.href;
                document.cookie = 'url=' + return_url + '; path=/; domain=' + self.args.cookie_domain + ';';
                $('.swal2-confirm').colorbox({
                    iframe:true,
                    width: "94%",
                    height:"450px",
                    maxWidth:"360px",
                    speed:'200',
                    open:true,
                    fixed: true,
                    href: self.args.regist_netkeiba_url + '/?pid=regist_form&action=nk_input&nmlma=1&nterms=1&from=keirin'
                });
            }
        });
    }

     /*
      * 購入ステータス確認
      */
    self.check_bet_status = function() {
        //console.log('self.check_bet_status');
        //console.log(self.bet_id);
        self.count++;
        var limit = 300;
        var timer_id = setTimeout(self.check_bet_status, 1000);
        var _data = {};
        _data.output = 'json';
        _data.mode = 'check';
        _data.bet_id = self.bet_id;
        $.ajax({
            type     : 'POST',
            url      : self.args.keirin_url + '/bet/api_post_tipstar_bet.html',
            data     : _data,
            dataType : _data.output,
            success  : function( ret ){
                console.log(ret);
                if(ret['status'] == 'OK'){
                    console.log('stop');
                    clearTimeout( timer_id );
                    //ストレージ削除
                    var ndisam = new NDIsam();
                    ndisam.clear(self.isam_domain);
                    //tipstarのタブを閉じる
                    //self.tab.close();
                    //My収支に遷移
                    var location_url = sprintf("%sshushi/?bet_id=%s", self.args.keirin_url, self.bet_id);
                    console.log(location_url);
                    window.location.href = location_url;
                }
            },
            error  : function(XMLHttpRequest, textStatus, errorThrown){
                console.log('XMLHttpRequest: %O',XMLHttpRequest);
                console.log('textStatus: %s',textStatus);
            }
        });
        if(self.count > limit){
            //時間内にstatusが変わらなかったら・・・
            clearTimeout( timer_id );
        }
    }

     /*
      * 買い目を表示用のオブジェクトに変換
      */
    self.make_bet_view_obj = function(){
        console.log('self.make_bet_view_obj');
        var disply_bet_view = {};
        for(var i = 0; i < self.bet_view.length; i++){
            var shikibetu = self.bet_view[i]['shikibetu'];
            if(!disply_bet_view[shikibetu]){
                disply_bet_view[shikibetu] = [];
            }
            self.bet_view[i]['idx'] = i;
            disply_bet_view[shikibetu].push(self.bet_view[i]);
        }
        console.log('disply_bet_view: ', disply_bet_view);
        return disply_bet_view;
    }

    self.show_tipstar_modal = function(){
        var current_scrollY = $(window).scrollTop();
        $(".HalfModal").addClass("OpenDraw");
        $(".Wrap").addClass("HalfModalViewOut");
        $(".Wrap.HalfModalViewOut").css({
            top: -1 * current_scrollY,
            height:'auto'
        });
        $("footer.SpFooter,footer.PcFooter").css({visibility: 'hidden',});
        $(".Wrap").append("<div class='ModalOverlay HalfModalOver'></div>");
        $(document).on("touchend click", ".HalfModal_CloseBtn,.Disagree button,.ModalOverlay", function() {
            $(".HalfModal").addClass("SlideOut");
            setTimeout(function () {
                $(".HalfModal").removeClass("OpenDraw");
                $(".HalfModal").removeClass("SlideOut");
            }, 200);
            $(".Wrap.HalfModalViewOut").attr({ style: ''}).removeClass("HalfModalViewOut");
            $(".HalfModalOver").remove();
            $('body').css({'position':'static'});
            $("footer.SpFooter,footer.PcFooter").css({visibility: 'visible'});
            $( 'html, body' ).prop( { scrollTop: current_scrollY } );
            self.is_tipstar_modal = false;
            self.is_cahrge = false;
            self.show_regist = false;
            self.update();
            return false;
            event.preventDefault();
        });
    }

    self.make_select_bet_odds = function(info){
        console.log('self.make_select_bet_odds', info);
        var odds_list = [];
        var tmp_odds = [];
        if(self.cur_shikibetu != '1'){
            for(var i = 0; i < info['comb'].length; i++){
                var tmp_kaime = info['comb'][i].replace(/-/g, '');
                var odds = {};
                if(self.cur_shikibetu == '7'){
                    odds[tmp_kaime] = self.odds[self.cur_shikibetu][tmp_kaime][0] + '_' + self.odds[self.cur_shikibetu][tmp_kaime][1];
                }else{
                    odds[tmp_kaime] = self.odds[self.cur_shikibetu][tmp_kaime][0];
                }
                tmp_odds.push(self.odds[self.cur_shikibetu][tmp_kaime][0]);
                odds_list.push(odds);
            }
        }else{
            var tmp_kaime = info['kaime1'];
            var odds = {};
            odds[tmp_kaime] = self.odds[self.cur_shikibetu][tmp_kaime][0];
            tmp_odds.push(self.odds[self.cur_shikibetu][tmp_kaime][0]);
            odds_list.push(odds);
        }

        var max = 0;
        var min = 0;
        if(tmp_odds.length > 0){
            max = tmp_odds.reduce(function(a, b) {
                return Math.max(a, b);
            });
            min = tmp_odds.reduce(function(a, b) {
                return Math.min(a, b);
            });
        }
        var result = {
            'odds_list' : odds_list,
            'min_odds' : min,
            'max_odds' : max
        }
        return result;
    }

    //買い目一覧のオッズ開閉
    self.act_odds_open = function(){
        if(self.is_odds_open){
            self.is_odds_open = false;
        }else{
            self.is_odds_open = true;
        }
    }

    self.act_select_odds_sort = function(odds_list, mode){
        console.log('self.act_select_odds_sort', odds_list, mode);
        if(self.select_odds_sort_mode == 'asc'){
              self.select_odds_sort_mode = 'desc';
        }else{
              self.select_odds_sort_mode = 'asc';
        }

        self.select_bet_odds = odds_list.sort(function(a,b){
            if(mode == 'kaime'){
                var data_a = Object.keys(a)[0];
                var data_b = Object.keys(b)[0];
            }else{
                var data_a = Object.values(a)[0];
                var data_b = Object.values(b)[0];
            }
            if(self.select_odds_sort_mode == 'asc'){
                if( parseInt(data_a) < parseInt(data_b) ) return 1;
                if( parseInt(data_a) > parseInt(data_b) ) return -1;
            }else{
                if( parseInt(data_a) < parseInt(data_b) ) return -1;
                if( parseInt(data_a) > parseInt(data_b) ) return 1;
            }
            return 0;
        });
    }

    //買い目選択時
    self.act_select_kaime = function(){
        console.log('self.act_select_kaime');
        self.select_odds = {};
        if(self.select_kaime){
            self.select_kaime = false;
        }else{
            self.select_kaime = true;
        }
        console.log(self.select_odds);
    }

    //オッズから選択時
    self.act_select_odds = function(kaime){
        console.log('self.act_select_odds', kaime);
        self.select_kaime = false;
        if(!self.select_odds[kaime]){
            self.select_odds[kaime] = true;
        }else{
            delete self.select_odds[kaime];
        }
        console.log(self.select_odds);
//        self.update();
    }

    self.act_chenge_edit_mode = function(){
        console.log('self.act_chenge_edit_mode');
        if(self.is_edit){
            self.is_edit = false;
        }else{
            self.is_edit = true;
        }
    }

    //選択した買い目を追加
    self.set_bet_odds = function(select_odds){
        console.log('self.set_bet_odds');
        //オッズから選択時の方式は通常
        //self.cur_houshiki = 0;
        for(var kaime in select_odds) {
            var new_btn_uno = {};
            var select_syaban = kaime.split('0');
            for(var i = 0; i < select_syaban.length; i++){
                var syaban = select_syaban[i].replace(/^0/, '');
                if(syaban){
                    if(i <= 1){
                        if(!new_btn_uno[0]){
                            new_btn_uno[0] = {};
                        }
                        new_btn_uno[0][syaban] = true;
                    }else if(i == 2){
                        if(!new_btn_uno[1]){
                            new_btn_uno[1] = {};
                        }
                        new_btn_uno[1][syaban] = true;
                    }else if(i == 3){
                        if(!new_btn_uno[2]){
                            new_btn_uno[2] = {};
                        }
                        new_btn_uno[2][syaban] = true;
                    }
                }
            }
            self.btn_uno = new_btn_uno;
            self.set_bet(true);
        }
    }

    //オッズ自動更新
    self.odds_auto_update = function(){
        console.log('self.odds_auto_update');

        var api = new AplApiRace(self.args.api_url, true, 'json'/*, true*/);
        self.odds_update_timer = setInterval(function(){
            var bet_list = [];
            if(self.bet_mode == 'add'){
                // 点数を表示するため組合せを生成
                var info = self.make_bet(100);
                if(info < 0){
                    return false;
                }else{
                    bet_list.push(info);
                }
            }else if(self.bet_view.length > 0){
                bet_list =  self.bet_view;
            }

            if(bet_list.length <= 0){
                return false;
            }
            // オッズ取得
            api.get('AplRaceOdds', {'race_id': self.cur_race_id}, function(odds_data) {
                if (self.debug) console.log('=============AplRaceOdds=============');
                if (self.debug) console.log(odds_data);
                for (var i = 1; i <= 9; i++) {
                    self.odds[i] = {};
                    if (undefined === odds_data['list_' + i]) {
                        continue;
                    }
                    for(var j = 0; j < odds_data['list_' + i].length; j++) {
                        var oval = odds_data['list_' + i][j];
                        self.odds[i][oval[0]] = [oval[1], oval[2], oval[3]];
                    }
                }
                if (self.debug) console.log('self.odds: %O', self.odds);
                if(self.bet_mode == 'add'){
                    self.select_bet_odds = [];
                }else{
                    self.bet_odds_list = [];
                }
                for (var idx = 0; idx < bet_list.length; idx++) {
                    var bet_info = self.bet_gen(bet_list[idx]['bet_id'], bet_list[idx]['bet_money']);
                    if(self.bet_mode == 'add'){
                        //選択中のオッズ一覧
                        var info = self.make_bet(100);
                        if(info < 0){
                            return false;
                        }else{
                            var ret = self.make_select_bet_odds(bet_info);
                            self.select_bet_odds = ret['odds_list'];
                            self.select_max_odds = ret['max_odds'];
                            self.select_min_odds = ret['min_odds'];
                        }
                    }else{
                        // オッズ配当計算
                        if ('0' == bet_info['houshiki']) {
                            // 通常(バラ買い)
                            var key = '';
                            if ('1' == bet_info['shikibetu'] || '2' == bet_info['shikibetu']) {
                                key = sprintf("%02d", bet_info['kaime1']);
                            } else if ('3' == bet_info['shikibetu'] || '4' == bet_info['shikibetu'] || '5' == bet_info['shikibetu'] || '6' == bet_info['shikibetu'] || '7' == bet_info['shikibetu']) {
                                key = sprintf("%02d%02d", bet_info['kaime1'], bet_info['kaime2']);
                            } else if ('8' == bet_info['shikibetu'] || '9' == bet_info['shikibetu']) {
                                key = sprintf("%02d%02d%02d", bet_info['kaime1'], bet_info['kaime2'], bet_info['kaime3']);
                            }
                            var payback = 0;
                            if (undefined === self.odds[bet_info['shikibetu']]){
                                if(self.debug) console.error('empty odds shikibetu: %s',bet_info['shikibetu']);
                            }else if (undefined === self.odds[bet_info['shikibetu']][key]){
                                if(self.debug) console.error('unkown key : %s', key);
                                payback = 0;
                            } else {
                                var payback = self.odds[bet_info['shikibetu']][key][0] * bet_info['bet_money'];
                                payback = Math.round(payback);
                                if(self.bet_odds_list[bet_info['bet_id']] === undefined){
                                    self.bet_odds_list[bet_info['bet_id']] = [];
                                }
                                self.bet_odds_list[bet_info['bet_id']].push(self.odds[bet_info['shikibetu']][key][0]);
                            }
                            bet_info['payback'] = payback;
                        } else {
                            // 以外(組合せ買い)
                            bet_info['payback'] = [];
                            bet_info['comb_odds'] = [];
                            for (var i = 0; i < bet_info['comb'].length; i++) {
                                var val = bet_info['comb'][i].split(/-/);
                                var comb_odds = '';
                                var key = '';
                                for (var j = 0; j < val.length; j++) {
                                    key += sprintf("%02d", val[j]);
                                }
                                if (undefined === self.odds[bet_info['shikibetu']]){
                                    if(self.debug) console.error('empty odds shikibetu: %s',bet_info['shikibetu']);
                                }else if(undefined === self.odds[bet_info['shikibetu']][key]){
                                    if(self.debug) console.error('unkown key : %s', key);
                                    payback = 0;
                                    comb_odds = '0.0';
                                } else {
                                    payback = self.odds[bet_info['shikibetu']][key][0] * bet_info['bet_money'];
                                    payback = Math.round(payback);
                                    comb_odds = self.odds[bet_info['shikibetu']][key][0];
                                    if(self.bet_odds_list[bet_info['bet_id']] === undefined){
                                        self.bet_odds_list[bet_info['bet_id']] = [];
                                    }
                                    self.bet_odds_list[bet_info['bet_id']].push(self.odds[bet_info['shikibetu']][key][0]);
                                }
                                //if (self.debug) console.log('payback: %s:', payback);
                                bet_info['payback'].push(payback);
                                bet_info['comb_odds'].push(comb_odds);
                            }
                        }
                        bet_list[idx]['payback'] = bet_info['payback'];
                        bet_list[idx]['comb_odds'] = bet_info['comb_odds'];
                        if(self.bet_view.length > 0){
                            self.bet_view[idx] = bet_list[idx];
                        }
                        self.disply_bet_view = self.make_bet_view_obj();
                    }

                }
                if (self.debug) console.log('self.select_bet_odds: %s', self.select_bet_odds);
                if (self.debug) console.log('self.bet_odds_list: %O', self.bet_odds_list);
                self.update();
            });
        }, 15000);// 15秒
    }

    self.act_link_charge = function(){
        console.log('self.act_link_charge');
        self.is_cahrge = true;
        //モーダル表示
        self.is_tipstar_modal = true;
        self.update();
        self.show_tipstar_modal();
        return;
//        OnLinkClick(self.args.tipstar_url + '/charge');
    }


    self.show_registor_popup = function(){
        console.log('show_registor_popup');
        $(window).on('message', function(event){
            if (event.originalEvent.origin !== self.args.regist_netkeiba_url ) return;
            if (event.originalEvent.data === 'register_done' ) {
                location.reload();
            }
        });
        self.iframe_url = self.args.keirin_url + '/regist/regist_netkeiba.html?from=bet';
        var return_url = location.href;
        var host = location.host.split('.');
        var cookie_domain = '.' + host[1] + '.' + host[2];
        document.cookie = 'keirin_url=' + return_url + '; path=/; domain=' + cookie_domain + ';';
        //モーダル表示
        self.is_tipstar_modal = true;
        self.show_regist = true;
        self.update();
        self.show_tipstar_modal();
    }

    self.make_odds_key = function(syaban_1, syaban_2, syaban_3){
        var syaban_list = [];
//        console.log(syaban_1, syaban_2, syaban_3);
        if(self.cur_shikibetu == 9){
            //3連単
            if(self.chaku_select == 1){
                return sprintf('%02d%02d%02d', syaban_1, syaban_2, syaban_3);
            }else if(self.chaku_select == 2){
                return sprintf('%02d%02d%02d', syaban_2, syaban_1, syaban_3);
            }else if(self.chaku_select == 3){
                return sprintf('%02d%02d%02d', syaban_2, syaban_3, syaban_1);
            }
        }else if(self.cur_shikibetu == 6){
            //2車単
            return sprintf('%02d%02d', syaban_2, syaban_3);
        }else{
            if(syaban_2 >= syaban_3){
                return '';
            }
            if(self.cur_shikibetu == 8){
                //3連複
                syaban_list.push(syaban_1, syaban_2, syaban_3);
            }else{
                //2車複,ワイド
                syaban_list.push(syaban_2, syaban_3);
            }
            syaban_list.sort(function(a,b){
                    if( a < b ) return -1;
                    if( a > b ) return 1;
                    return 0;
            });
//            console.log(syaban_list);
            if(syaban_list[2]){
                return sprintf('%02d%02d%02d', syaban_list[0], syaban_list[1], syaban_list[2]);
            }else{
                return sprintf('%02d%02d', syaban_list[0], syaban_list[1]);
            }
        }
    }

    self.check_ijyo = function(kaime){
        var syaban_list = kaime.split('0');
        for(var ijyo in self.ijyo_list){
            if(syaban_list.includes(ijyo)){
                return false;
            }
        }
        return true;
    }


    //制作
    self.list_mark_check = function(){

/*
	var BetHead = $('.BetRaceHead_Wrap');
	var offset = BetHead.offset();
	var floatBetHead = function() {
		if($(window).scrollTop() > offset.top) {
			BetHead.addClass('Fixed');
		} else {
			BetHead.removeClass('Fixed');
		}
	}
	$(window).scroll(floatBetHead);
	$('body').bind('touchmove', floatBetHead);

		$('.RaceOdds_HorseList_Table tbody tr').each(function(){
			if($(this).find('.MarkIcon').length){
				$(this).addClass('selected');
			}
		});
		$(window).scroll(function () {
			var footHeight = $('.Find_FootArea').outerHeight() + 100;
			var scrollHeight = $(document).height();
			var scrollPosition = window.innerHeight + $(window).scrollTop();
			if (scrollHeight - scrollPosition <= footHeight) {
				$(".InputFixedArea01").css({
					"position": "relative"
				});
			} else {
				$(".InputFixedArea01").css({
					"position": "fixed",
					"bottom": "0px"
				});
			}
		});
*/


    }
	/* モック 吸着フッター箇所(仮) */

$(window).scroll(function() {
	var OddsBtnWrapTop = $('.InputFixedArea_Wrap').offset().top;
	var OddsBtnWrapBottom = $('.InputFixedArea_Wrap').offset().top + $('.InputFixedArea_Wrap').height();
	var scrollPosition = $(window).height() + $(window).scrollTop();
	if ( scrollPosition > $(window).height()) {
		$(".InputFixedArea01").fadeIn();
	} else {
		$(".InputFixedArea01").fadeOut();
	}
	if (scrollPosition > OddsBtnWrapBottom) {
		$(".InputFixedArea01").removeClass('odds_fixed');
	} else {
		$(".InputFixedArea01").addClass('odds_fixed');
	}
});
	/* モック 吸着フッター箇所(仮) */
	$('#TotalBetDL').hide();
    </script>

</odds>
