/*
 * TOTO Re-model.jp
 * 
 */

jQuery(function(){

	/* 現在の市区町村リスト */
	var CurrentLocations = null;

	/**
	 * 選択された都道府県に対する市区町村リストを取得
	 *
	 * 関数設定対象要素：都道府県選択要SELECT要素
	 *
	 * locationSelectId 市区町村選択SELECT要素のID文字列
	 * allSelect        trueの場合、「全域」という項目を入れる
	 * disableSelectId  SELECT要素のID文字列
	 *                  このSELECT要素に含む市区町村はリストに表示されない
	 */
	$.fn.getLoation = function(locationSelectId, allSelect, disableSelectId){
		var locSel = document.getElementById(locationSelectId);
		if ( this.val() )
		{
			$.getJSON('/webapp/jis_locations/location/' + this.val(), function(json){
				CurrentLocations = json;
			});
		}

		this.change(function(e){
			var err_handle_timer = setTimeout(function(){
				alert('タイムアウトしました');
			}, 3000);
			$.getJSON('/webapp/jis_locations/location/' + this.options[this.selectedIndex].value, function(json){
				clearTimeout(err_handle_timer);
				CurrentLocations = json;
				setLocations(locSel, null, allSelect, disableSelectId);
			});
		});
	};

	/**
	 * 市区町村リストのフィルタリング
	 *
	 * 関数設定対象要素：ヨミ頭文字（ア行、カ行、など）選択用SELECT要素
	 *
	 * locationSelectId 市区町村選択SELECT要素のID文字列
	 */
	$.fn.filterLocation = function(locationSelectId){
		var locSel = document.getElementById(locationSelectId);
		this.change(function(e){
			var c = this.options[this.selectedIndex].value;
			setLocations(locSel, c);
		});
	};

	/**
	 * SELECT要素の選択状態解除
	 *
	 * 関数設定対象要素：SELECT要素。
	 *                   この要素のonChangeイベントに設定される。
	 *
	 * locationCSelectId 選択状態を解除するSELECT要素のID文字列
	 */
	$.fn.resetLoationC = function(locationCSelectId){
		var locSel = document.getElementById(locationCSelectId);
		this.change(function(e){
			locSel.selectedIndex = 0;
		});
	};

	/**
	 * 市区町村設定用
	 *
	 * locSel           市区町村リスト用SELECT要素 HTML SELECTオブジェクト
	 * c                フィルタリング頭文字
	 * allSelect        trueの場合、「全域」という項目を入れる
	 * disableSelectId  SELECT要素のID文字列
	 *                  このSELECT要素に含む市区町村はリストに表示されない
	 */
	setLocations = function(locSel, c, allSelect, disableSelectId)
	{
		locSel.options.length = 0;

		if ( disableSelectId )
		{
			$('option:selected', $('#' + disableSelectId)).each(function(){ $(this).attr('selected', ''); });
		}

		var opt = document.createElement('option');
		if ( allSelect )
		{
			var prefCode = Math.floor(CurrentLocations[0].JisLocation.id / 1000) * 1000;
			if ( locationExists(prefCode, disableSelectId) )
			{
				return;
			}
			opt.text  = '全域';
			opt.value = prefCode;
		}
		else
		{
			opt.text  = '選択してください';
			opt.value = '';
		}
		locSel.options[locSel.options.length] = opt;

		for ( var i = 0; i < CurrentLocations.length; i++ )
		{
			if ( (c && cc(CurrentLocations[i].JisLocation.address2_kana, c)) || ! c )
			{
				var code = CurrentLocations[i].JisLocation.id;
				if ( ! locationExists(code, disableSelectId) )
				{
					opt = document.createElement('option');
					opt.text  = CurrentLocations[i].JisLocation.address2;
					opt.value = code;
					locSel.options[locSel.options.length] = opt;
				}
			}
		}
	};

	/**
	 * 指定要素に指定コード値の項目が含まれるかどうか
	 * 含まれる場合は true を返す
	 *
	 * code           コード値
	 * targetSelectId 対象のSELECT要素のID文字列
	 */
	locationExists = function(code, targetSelectId)
	{
		if ( ! code || ! targetSelectId )
		{
			return false;
		}
		var _opts = $('option', $('#' + targetSelectId));
		for ( var i = 0; i < _opts.length; i++ )
		{
			if ( $(_opts[i]).val() == code )
			{
				$(_opts[i]).attr('selected', 'selected');
				return true;
			}
		}
		return false;
	}

	/**
	 * 頭文字チェック
	 * マッチするか否かを返す
	 *
	 * str チェック対象文字列
	 * c   ヨミ頭文字（ア行、カ行、など）
	 */
	cc = function(str, c)
	{
		if ( c == 'ア' )
		{
			return (
				str.indexOf('ア') == 0 ||
				str.indexOf('イ') == 0 ||
				str.indexOf('ウ') == 0 ||
				str.indexOf('エ') == 0 ||
				str.indexOf('オ') == 0 );
		}
		else if ( c == 'カ' )
		{
			return (
				str.indexOf('カ') == 0 || str.indexOf('ガ') == 0 ||
				str.indexOf('キ') == 0 || str.indexOf('ギ') == 0 ||
				str.indexOf('ク') == 0 || str.indexOf('グ') == 0 ||
				str.indexOf('ケ') == 0 || str.indexOf('ゲ') == 0 ||
				str.indexOf('コ') == 0 || str.indexOf('ゴ') == 0 );
		}
		else if ( c == 'サ' )
		{
			return (
				str.indexOf('サ') == 0 || str.indexOf('ザ') == 0 ||
				str.indexOf('シ') == 0 || str.indexOf('ジ') == 0 ||
				str.indexOf('ス') == 0 || str.indexOf('ズ') == 0 ||
				str.indexOf('セ') == 0 || str.indexOf('ゼ') == 0 ||
				str.indexOf('ソ') == 0 || str.indexOf('ゾ') == 0 );
		}
		else if ( c == 'タ' )
		{
			return (
				str.indexOf('タ') == 0 || str.indexOf('ダ') == 0 ||
				str.indexOf('チ') == 0 || str.indexOf('ヂ') == 0 ||
				str.indexOf('ツ') == 0 || str.indexOf('ヅ') == 0 ||
				str.indexOf('テ') == 0 || str.indexOf('デ') == 0 ||
				str.indexOf('ト') == 0 || str.indexOf('ド') == 0 );
		}
		else if ( c == 'ナ' )
		{
			return (
				str.indexOf('ナ') == 0 ||
				str.indexOf('ニ') == 0 ||
				str.indexOf('ヌ') == 0 ||
				str.indexOf('ネ') == 0 ||
				str.indexOf('ノ') == 0 );
		}
		else if ( c == 'ハ' )
		{
			return (
				str.indexOf('ハ') == 0 || str.indexOf('バ') == 0 || str.indexOf('パ') == 0 ||
				str.indexOf('ヒ') == 0 || str.indexOf('ビ') == 0 || str.indexOf('ピ') == 0 ||
				str.indexOf('フ') == 0 || str.indexOf('ブ') == 0 || str.indexOf('プ') == 0 ||
				str.indexOf('ヘ') == 0 || str.indexOf('ベ') == 0 || str.indexOf('ペ') == 0 ||
				str.indexOf('ホ') == 0 || str.indexOf('ボ') == 0 || str.indexOf('ポ') == 0 );
		}
		else if ( c == 'マ' )
		{
			return (
				str.indexOf('マ') == 0 ||
				str.indexOf('ミ') == 0 ||
				str.indexOf('ム') == 0 ||
				str.indexOf('メ') == 0 ||
				str.indexOf('モ') == 0 );
		}
		else if ( c == 'ヤ' )
		{
			return (
				str.indexOf('ヤ') == 0 ||
				str.indexOf('ユ') == 0 ||
				str.indexOf('ヨ') == 0 );
		}
		else if ( c == 'ラ' )
		{
			return (
				str.indexOf('ラ') == 0 ||
				str.indexOf('リ') == 0 ||
				str.indexOf('ル') == 0 ||
				str.indexOf('レ') == 0 ||
				str.indexOf('ロ') == 0 );
		}
		else if ( c == 'ワ' )
		{
			return (
				str.indexOf('ワ') == 0 ||
				str.indexOf('ヲ') == 0 ||
				str.indexOf('ン') == 0 );
		}
		return false;
	};

	/**
	 * RC検索結果一覧チェックボックス処理
	 */
	$.fn.inquiryRcSelect = function(){

		var selectedRcList = $.cookie('inquiryRcSelect');
		if ( selectedRcList )
		{
			selectedRcList = selectedRcList.split(',');
		}
		else
		{
			selectedRcList = Array();
		}

		this.each(function(){
			for ( i = 0; i < selectedRcList.length; i++ )
			{
				if ( this.value == selectedRcList[i] )
				{
					this.checked = true;
				}
			}
		});

		this.click(function(){
			if ( this.checked )
			{
				if ( selectedRcList.length < 5 )
				{
					selectedRcList[selectedRcList.length] = this.value;
				}
				else
				{
					alert('最大5件までしか選択できません');
					this.checked = false;
				}
			}
			else
			{
				var newList = Array();
				for ( i = 0; i < selectedRcList.length; i++ )
				{
					if ( selectedRcList[i] != this.value )
					{
						newList[newList.length] = selectedRcList[i];
					}
				}
				selectedRcList = newList;
			}
			$.cookie('inquiryRcSelect', selectedRcList.join(','), { path:'/', expires:0 });
		});
	};

	/**
	 * 選択中RC店保持COOKIEのリセット
	 */
	resetInquiryRcSelect = function()
	{
		$.cookie('inquiryRcSelect', '', { path:'/', expires:0 });
	};

	/**
	 * 選択中RC店保持COOKIEを使った問い合わせフォーム遷移
	 */
	entryInquiryByRcSelect = function()
	{
		var selectedRcList = $.cookie('inquiryRcSelect');
		if ( selectedRcList )
		{
			selectedRcList = selectedRcList.split(',');
		}
		else
		{
			selectedRcList = Array();
		}

		if ( selectedRcList.length > 0 )
		{
			var tmp = Array();
			for ( i = 0; i < selectedRcList.length; i++ )
			{
				tmp[tmp.length] = 'id[]=' + selectedRcList[i];
			}
			window.location.href = '/webapp/inquiry/entry?' + tmp.join('&');
		}
		else
		{
			alert('リモデルクラブ店が選択されていません。');
			return false;
		}
		return true;
	};

	/**
	 * こだわり要件設定点数合計値表示用
	 */
	$.fn.autoCalc = function(totalViewId){
		var inputs = this.find('li input');
		calc = function(){
			var total = 0;
			inputs.each(function(){
				if ( ! this.value.match('^[0-9]{1,2}$') )
				{
					this.value = '0';
				}
				total += parseInt(this.value);
			});
			$(totalViewId).text(total);
			$(totalViewId).css('color', total == 70 ? 'black' : 'red');
			$(totalViewId).css('font-weight', total == 70 ? 'normal' : 'bold');
		};
		inputs.each(function(){
			$(this).change(calc);
		});
		calc();
	};

	/**
	 * FORM要素の各属性値を変更してsubmit
	 */
	$.fn.otherSubmit = function(formId, params){
		var f = $(formId);
		this.click(function(){
			var _save = {
				action:f.attr('action'),
				target:f.attr('target'),
				method:f.attr('method')
			};

			var _new = $.extend({
				action:f.attr('action'),
				target:f.attr('target'),
				method:f.attr('method')
			}, params);
			f.attr('action', _new.action);
			f.attr('target', _new.target);
			f.attr('method', _new.method);
			f.submit();

			f.attr('action', _save.action);
			f.attr('target', _save.target);
			f.attr('method', _save.method);

			return false;
		});
	};

	/** 
	 * 対応エリア設定 対応エリアの追加
	 *
	 * selectId   市区町村選択用SELECT要素指定セレクタ文字列
	 * locationId 選択された市区町村表示用SELECT要素指定セレクタ文字列
	 * prefId     都道府県選択用SELECT要素指定セレクタ文字列
	 */
	$.fn.addLocation = function(selectId, locationId, prefId){
		var _sel = $(selectId);
		var _loc = $(locationId);
		var _pref = $(prefId);
		this.click(function(){
			var prefCode = parseInt($($('option', _sel)[0]).val());
			var prefName = '';
			var prefOptions = $('option', _pref);
			var selectedOptions = $('option:selected', _sel);
			for ( i = 0; i < prefOptions.length; i++ )
			{
				if ( parseInt($(prefOptions[i]).val()) == prefCode )
				{
					prefName = $(prefOptions[i]).text();
					break;
				}
			}

			$('option:selected', _loc).each(function(){ $(this).attr('selected', ''); });
			for ( i = 0; i < selectedOptions.length; i++ )
			{
				var loc = document.getElementById(_loc.attr('id'));
				var selectCode = parseInt($(selectedOptions[i]).val());
				var selectName = $(selectedOptions[i]).text();
				if ( selectCode == prefCode )
				{
					/* 全域 */
					$('option', _loc).each(function(){
						var code = parseInt($(this).val());
						if ( code >= prefCode && code < (prefCode + 1000) )
						{
							$(this).remove();
						}
					});
					var ix = loc.options.length;
					loc.options[ix] = new Option(prefName, prefCode);
					loc.options[ix].selected = true;
					$('option', _sel).each(function(){ $(this).remove(); });
					return false;
				}
				else
				{
					var codeExists = false;
					$('option', _loc).each(function(){
						var code = parseInt($(this).val());
						if ( code == prefCode || code == selectCode )
						{
							codeExists = true;
						}
					});
					if ( ! codeExists )
					{
						var ix = loc.options.length;
						loc.options[ix] = new Option(prefName + selectName, selectCode);
						loc.options[ix].selected = true;
					}
				}
			}
			selectedOptions.each(function(){ $(this).remove(); });
			return false;
		});
	};

	/** 
	 * 対応エリア設定 対応エリアの削除
	 *
	 * locationId 選択された市区町村表示用SELECT要素指定セレクタ文字列
	 * selectId   市区町村選択用SELECT要素指定セレクタ文字列
	 */
	$.fn.removeLocation = function(locationId, selectId){
		var _loc = $(locationId);
		this.click(function(){
			$('option:selected', _loc).each(function(){
				$(this).remove();
			});
			$(selectId).change();
			return false;
		});
	};

	/**
	 * 対応エリア設定フォーム用
	 */
	$.fn.areaForm = function(locationId){
		var _loc = $(locationId);
		this.submit(function(){
			var tmp = $('option', _loc);
			if ( tmp.length == 0 )
			{
				alert('エリアが指定されていません');
				return false;
			}
			else
			{
				$('option', _loc).each(function(){
					$(this).attr('selected', 'selected');
				});
				return true;
			}
		});
	};

	/**
	 * 対応エリア設定フォーム用（管理機能）
	 */
	$.fn.areaFormAdmin = function(locationId){
		var _loc = $(locationId);
		this.submit(function(){
			var tmp = $('option', _loc);
			$('option', _loc).each(function(){
				$(this).attr('selected', 'selected');
			});
			return true;
		});
	};

	/**
	 * 見比べリスト関連
	 */
	getCompareList = function(){
		var compareList = $.cookie('RcCompareList');
		if ( compareList )
		{
			compareList = compareList.split(',');
		}
		else
		{
			compareList = Array();
		}
		return compareList;
	};
	setCompareList = function(list){
		$.cookie('RcCompareList', list.join(','), { path:'/', expires:0 });
	};
	disableCompareListAddButton = function(img){
		img.src = '/shared/images/search/btn-12_void.gif';
	};
	viewCompareList = function(){
		var compareList = getCompareList();
		if ( compareList.length > 0 )
		{
			window.location.href = '/webapp/remodel_club/compare';
		}
		else
		{
			alert('比較対象のリモデルクラブ店が1件も選択されていません');
		}
	}
	compareListRemoveAll = function(){
		setCompareList(Array());
		window.location.reload();
	};
	$.fn.setCompareListCount = function(){
		var compareList = getCompareList();
		this.each(function(){
			$(this).text(compareList.length);
		});
	};
	$.fn.registCompareList = function(countViewSelector, type){
		if ( type != 'view' )
		{
			var compareList = getCompareList();
			this.each(function(){
				for ( var i = 0; i < compareList.length; i++ )
				{
					if ( this.id == compareList[i] )
					{
						disableCompareListAddButton(this);
					}
				}
			});
		}
		$(countViewSelector).setCompareListCount();

		this.click(function(){
			var compareList = getCompareList();
			var exist = false;
			for ( var i = 0; i < compareList.length; i++ )
			{
				if ( this.id == compareList[i] )
				{
					exist = true;
					break;
				}
			}
			if ( ! exist )
			{
				if ( compareList.length < 5 )
				{
					compareList[compareList.length] = this.id;
					setCompareList(compareList);
					$(countViewSelector).setCompareListCount();
					if ( type == 'view' )
					{
						alert('見比べリストへ追加しました');
						firstTracker._trackEvent('見比べリストに追加', this.id, '店舗詳細');
					}
					else
					{
						disableCompareListAddButton(this);
						firstTracker._trackEvent('見比べリストに追加', this.id, '検索結果一覧');
					}
				}
				else
				{
					alert('比較対象のリモデルクラブ店は最大5件です\n既に5件選択されています');
				}
			}
			else
			{
				if ( type == 'view' )
				{
					alert('既に見比べリストへ追加済みです');
				}
			}
		});
	};
	$.fn.removeCompareList = function(){
		this.click(function(){
			var compareList = getCompareList();
			var newList = Array();
			for ( var i = 0; i < compareList.length; i++ )
			{
				if ( this.id != compareList[i] )
				{
					newList[newList.length] = compareList[i];
				}
			}
			setCompareList(newList);
			window.location.reload();
		});
	};

	checkCompareEntryForm = function()
	{
		var checked = false;
		$('input.entryCheckbox').each(function(){
			if ( this.checked )
			{
				checked = true;
			}
		});
		if ( ! checked )
		{
			alert('リモデルクラブ店が選択されていません');
			return false;
		}
		return true;
	};
});


