/**
 * weather.js
 */
var weather = new function () {
	var FORECAST_DATA = {'0': 'きょうの天気', '1': 'あすの天気'};
	var DEFAULT_AREA = {'AreaCode' : '13113', 'CityCode': '1311300'};
	var WEATHER_DATA =
	{
		'c010' : '晴',
		'c020' : '曇',
		'c030' : '雨',
		'c038' : '暴風雨',
		'c040' : '雪',
		'c048' : '暴風雪',
		'c112' : '晴のち曇',
		'c113' : '晴のち雨',
		'c114' : '晴のち雪',
		'c121' : '曇のち晴',
		'c123' : '曇のち雨',
		'c124' : '曇のち雪',
		'c131' : '雨のち晴',
		'c132' : '雨のち曇',
		'c134' : '雨のち雪',
		'c141' : '雪のち晴',
		'c142' : '雪のち曇',
		'c143' : '雪のち雨',
		'c212' : '晴時々曇',
		'c213' : '晴時々雨',
		'c214' : '晴時々雪',
		'c221' : '曇時々晴',
		'c223' : '曇時々雨',
		'c224' : '曇時々雪',
		'c231' : '雨時々晴',
		'c232' : '雨時々曇',
		'c234' : '雨時々雪',
		'c241' : '雪時々晴',
		'c242' : '雪時々曇',
		'c243' : '雪時々雨'
	};
	var AREA_LIST =
	[
		{'code': '1','name': '北海道'},
		{'code': '2','name': '青森県'},
		{'code': '3','name': '岩手県'},
		{'code': '4','name': '宮城県'},
		{'code': '5','name': '秋田県'},
		{'code': '6','name': '山形県'},
		{'code': '7','name': '福島県'},
		{'code': '13','name': '東京都'},
		{'code': '14','name': '神奈川県'},
		{'code': '11','name': '埼玉県'},
		{'code': '12','name': '千葉県'},
		{'code': '8','name': '茨城県'},
		{'code': '9','name': '栃木県'},
		{'code': '10','name': '群馬県'},
		{'code': '19','name': '山梨県'},
		{'code': '20','name': '長野県'},
		{'code': '15','name': '新潟県'},
		{'code': '16','name': '富山県'},
		{'code': '17','name': '石川県'},
		{'code': '18','name': '福井県'},
		{'code': '23','name': '愛知県'},
		{'code': '21','name': '岐阜県'},
		{'code': '22','name': '静岡県'},
		{'code': '24','name': '三重県'},
		{'code': '27','name': '大阪府'},
		{'code': '28','name': '兵庫県'},
		{'code': '26','name': '京都府'},
		{'code': '25','name': '滋賀県'},
		{'code': '29','name': '奈良県'},
		{'code': '30','name': '和歌山県'},
		{'code': '31','name': '鳥取県'},
		{'code': '32','name': '島根県'},
		{'code': '33','name': '岡山県'},
		{'code': '34','name': '広島県'},
		{'code': '35','name': '山口県'},
		{'code': '36','name': '徳島県'},
		{'code': '37','name': '香川県'},
		{'code': '38','name': '愛媛県'},
		{'code': '39','name': '高知県'},
		{'code': '40','name': '福岡県'},
		{'code': '41','name': '佐賀県'},
		{'code': '42','name': '長崎県'},
		{'code': '43','name': '熊本県'},
		{'code': '44','name': '大分県'},
		{'code': '45','name': '宮崎県'},
		{'code': '46','name': '鹿児島県'},
		{'code': '47','name': '沖縄県'}
	];
	var WEATHER_LOADING_HTML='<div class="loading"><img src="/topmenu/1103_img/weather_sm/loading.gif"/></div>';

	var AREA_INFO_CGI    = 'http://cgi4.nhk.or.jp/weather2/getareainfo3.cgi';
	var AREA_LIST_CGI    = 'http://cgi4.nhk.or.jp/weather2/getarealist3.cgi';
	var WEATHER_INFO_CGI = 'http://cgi4.nhk.or.jp/weather2/getweatherinfo3.cgi';
	var WEATHER_SETTING_PATH = 'http://www3.nhk.or.jp/toppage/weather/';
	var WEATHER_PATH         = 'http://www3.nhk.or.jp/weather/';
	
	var areaCode;
	var cityCode;
	var zipCode;
	var amedasCode;
	var isZipSearch;
	
	var areaInfoData;
	var areaListData;
	var weatherInfoData;
	
	var spinner;
	
	/**
	 * 開始
	 */
	$(function()
	{
		$.ajaxSetup(
		{
			cache: true,
			crossDomain: true,
			dataType: 'script'
		});
		appendContainer();
		checkCookie();
		isZipSearch = false;
		loadAreaInfo();
	});
	
	
	/**
	 * クッキーチェック
	 */
	var checkCookie = function ()
	{
		nol.load();
		if(nol.data.weather)
		{
			areaCode = nol.data.weather.AreaCode;
			cityCode = nol.data.weather.CityCode;
		}
		else
		{
			areaCode = DEFAULT_AREA.AreaCode;
			cityCode = DEFAULT_AREA.CityCode;
		}
	}
	
	
	/**
	 * リロード
	 */
	var reload = function ()
	{
		nol.load();
		nol.data.weather = {'AreaCode' : areaCode, 'CityCode': cityCode};
		nol.save();
		$('div#weather div.display').empty();
		if(isZipSearch)
		{
			$('div#weather div.display').append(g_loadinghtml);
			spinner = $('div#weather div.display div.loading');
			loadWeatherInfo();
		}
		else
		{
			isZipSearch = false;
			loadAreaInfo();
		}
	}
	
	
	/**
	 * 地域情報ロード
	 */
	var loadAreaInfo = function ()
	{
		if(spinner) spinner.remove();
		areaInfoData = {};
		if(isZipSearch)
		{
			$('div#weather div.zipSearch div.result p.func').prepend(WEATHER_LOADING_HTML);
			spinner = $('div#weather div.zipSearch div.result div.loading');
			$.ajax({
				url : AREA_INFO_CGI + '?zip=' + zipCode
			});
		}
		else
		{
			$('div#weather div.display').append(g_loadinghtml);
			spinner = $('div#weather div.display div.loading');
			$.ajax({
				url : AREA_INFO_CGI + '?zip=&area=' + areaCode + '&city=' + cityCode
			});
		}
	}
	
	
	/**
	 * 地域情報リストロード
	 */
	var loadAreaList = function (code)
	{
		if(spinner) spinner.remove();
		$('div#weather div.areaSearch div.result p.func').prepend(WEATHER_LOADING_HTML);
		spinner = $('div#weather div.areaSearch div.result div.loading');
		areaListData = {};
		$.ajax({
			url : AREA_LIST_CGI + '?pref=' + code
		});
	}
	
	
	/**
	 * 天気情報ロード
	 */
	var loadWeatherInfo = function ()
	{
		weatherInfoData = null;
		$.ajax({
			url : WEATHER_INFO_CGI + '?amedas=' + amedasCode + '&city=' + cityCode
		});
	}
	
	
	/**
	 * 天気コンテナー表示
	 */
	var appendContainer = function ()
	{
		if(!g_smapho)
		{
			//PC版
			$('div#weather').append([
				'<h2>きょうの天気</h2>',
				'<p class="infoButton"><a href="/weather/?from=tp_pn09"><img src="/topmenu/1103_img/weather/weatherinfo2.png" alt="気象・災害情報" width="81" height="18" class="rollover" /></a></p>',
				'<div class="display">',
				'</div>'
			].join(''));
		}
		else
		{
			//スマホ版
			$('div#newsweb').after([
				'<div id="weather">',
				'<h2>きょうの天気</h2>',
				'<p class="disaster"><a href="' + WEATHER_PATH + '"><img src="/topmenu/1103_img/sm/bt_saigai_0804.png" alt="気象・災害"></a></p>',
				'<div class="display">',
				'</div>'
			].join(''));
		}
	}
	
	
	/**
	 * 天気情報表示
	 */
	var appendWeatherInfo = function (isSystemError)
	{
		$('div#weather').empty();
		var systemError = '';
		if(isSystemError) systemError = '<p class="systemError">システム障害のため、一部の情報が表示できません。ご了承ください。</p>';
		if(!g_smapho)
		{
			//PC版
			$('div#weather').append([
				'<h2>' + FORECAST_DATA[weatherInfoData.ForecastFlag] + '</h2>',
				'<p class="infoButton"><a href="/weather/?from=tp_pn09"><img src="/topmenu/1103_img/weather/weatherinfo2.png" alt="気象・災害情報" width="81" height="18" class="rollover" /></a></p>',
				'<div class="display">',
					'<p class="icon"><img src="/topmenu/1103_img/weather/icn' + weatherInfoData.ForecastCode + '.png" alt="' + WEATHER_DATA['c' + weatherInfoData.ForecastCode] + '" width="108" height="48" /></p>',
					'<p class="temperature"><span class="max">' + weatherInfoData.TMax + '<span class="degree">℃</span></span>/<span class="min">' + weatherInfoData.TMin + '<span class="degree">℃</span></span></p>',
					'<p class="rain">降水確率 <span class="num">' + weatherInfoData.RainfallProbability + '</span>％</p>',
					systemError,
					'<div class="setting">',
						'<p class="area">' + areaInfoData.AreaName + '</p>',
						'<p class="settingButton"><a href="' + WEATHER_SETTING_PATH + '"><img src="/topmenu/1103_img/weather/weathersetting.png" alt="設定する" width="38" height="18" class="rollover" /></a></p>',
					'</div>',
				'</div>'
			].join(''));
		}
		else
		{
			//スマホ版
			$('div#weather').append([
					'<h2>' + FORECAST_DATA[weatherInfoData.ForecastFlag] + '</h2>',
					'<p class="disaster"><a href="' + WEATHER_PATH + '"><img src="/topmenu/1103_img/sm/bt_saigai_0804.png" alt="気象・災害"></a></p>',
					'<div class="display">',
						'<p class="icon"><img src="/topmenu/1103_img/weather_sm/icn' + weatherInfoData.ForecastCode + '.jpg" alt="' + WEATHER_DATA['c' + weatherInfoData.ForecastCode] + '" width="135" height="80" /></p>',
						'<div>',
							'<p class="temperature"><span class="max">' + weatherInfoData.TMax + '<span class="degree">℃</span></span>/<span class="min">' + weatherInfoData.TMin + '<span class="degree">℃</span></span></p>',
							'<p class="rain">降水確率 <span class="num">' + weatherInfoData.RainfallProbability + '</span>％</p>',
						'</div>',
					'</div>',
					systemError,
					'<div class="setting"></div>'
			].join(''));
			//天気設定表示
			appendWeatherSetting(areaInfoData.AreaName);
		}
	}
	
	
	/**
	 * 天気設定表示
	 */
	var appendWeatherSetting = function (areaName)
	{
		$('div#weather div.setting').empty();
		$('div#weather div.setting').append([
			'<p class="area">' + areaName + '</p>',
			'<p class="settingButton"><img src="/topmenu/1103_img/weather_sm/weathersetting.png" alt="設定する" width="87" height="22"></p>',
			'<div class="search">',
				'<p class="radio"><label id="selectAreaSearch"><input type="radio" name="searchSelect" checked="checked" />地域</label><label id="selectZipSearch"><input type="radio" name="searchSelect" />郵便番号</label>',
				'<div class="areaSearch">',
					'<p class="select">',
					'<select id="areaList1" name="areaList1">',
					'<option value="none" selected>都道府県</option>',
					'</select>',
					'<select id="areaList2" name="areaList2" disabled="disabled">',
					'<option value="none" selected>市区町村</option>',
					'</select>',
					'</p>',
					'<div class="result">',
					'<p class="func"><img src="/topmenu/1103_img/weather_sm/close.png" alt="閉じる" width="72" height="22" class="close" /></p>',
					'</div>',
				'</div>',
				'<div class="zipSearch">',
					'<p class="note">※7桁の郵便番号で検索してください。</p>',
					'<p><input type="text" size="10" maxlength="7" id="zipSearchInput"><input type="button" id="zipSearchButton" value="検索" /></p>',
					'<div class="result">',
					'<p class="func"><img src="/topmenu/1103_img/weather_sm/close.png" alt="閉じる" width="72" height="22" class="close" /></p>',
					'</div>',
				'</div>',
				'<div>',
				'</div>',
			'</div>'
		].join(''));
		
		//都道府県リスト
		var list = [];
		for (var i = 0; i < AREA_LIST.length; i++) {list.push('<option value="' + AREA_LIST[i].code + '">' + AREA_LIST[i].name + '</option>');}
		$('select#areaList1 option').after(list.join(''));
		$('select#areaList1').change(function ()
		{
			if($('select#areaList1 option:selected').val() != 'none')
			{
				loadAreaList($('select#areaList1 option:selected').val());
			}
		});
		
		//郵便番号検索
		$('input#zipSearchButton').click(function ()
		{
			if(inputCheck($('input#zipSearchInput').val()) == 0)
			{
				zipCode = convertZenToHan($('input#zipSearchInput').val());
				isZipSearch = true;
				loadAreaInfo();
			}
		});
		
		$(window).keydown(function (evt)
		{
			if(evt.keyCode == 13)
			{
				if(inputCheck($('input#zipSearchInput').val()) == 0)
				{
					zipCode = convertZenToHan($('input#zipSearchInput').val());
					isZipSearch = true;
					loadAreaInfo();
				}
			}
		});
		
		$('div#weather div.search').hide();
		$('div#weather div.zipSearch').hide();
		$('div#weather p.settingButton img').click(function ()
		{
			$('div#weather div.search').toggle();
		});
		$('#selectAreaSearch').click(function ()
		{
			$('div#weather div.areaSearch').show();
			$('div#weather div.zipSearch').hide();
		});
		$('#selectZipSearch').click(function ()
		{
			$('div#weather div.areaSearch').hide();
			$('div#weather div.zipSearch').show();
		});
		$('div#weather img.close').click(function ()
		{
			$('div#weather div.search').hide();
		});
	}
	
	
	/**
	 * 市区町村リスト表示
	 */
	var appendAreaList2 = function ()
	{
		if(spinner) spinner.remove();
		var list = [];
		for (var i = 0; i < areaListData.AreaInfo.length; i++) {list.push('<option value="area' + i + '">' + areaListData.AreaInfo[i].AreaName + '</option>');}
		$('select#areaList2').attr('disabled', false).empty().append('<option value="none" selected>市区町村</option>').unbind('change');
		$('select#areaList2 option').after(list.join(''));
		$('select#areaList2').change(function ()
		{
			if($('select#areaList2 option:selected').val() != 'none')
			{
				appendAreaResult($('select#areaList2 option:selected').val().replace('area',''));
			}
		});
	}
	
	
	/**
	 * 地域検索結果表示
	 */
	var appendAreaResult = function (index)
	{
		$('div#weather div.areaSearch div.result').empty();
		$('div#weather div.areaSearch div.result').append([
			'<div>',
			'<p class="areaName">' + areaListData.AreaInfo[index].AreaName + '</p>',
			'<p class="func"><img src="/topmenu/1103_img/weather_sm/close.png" alt="閉じる" width="72" height="22" class="close" /><img src="/topmenu/1103_img/weather_sm/setting.png" alt="設定する" width="72" height="22" class="setting" /></p>',
			'</div>'
		].join(''));
		$('div#weather div.areaSearch div.result img.setting').click(function ()
		{
			areaCode = areaListData.AreaInfo[index].AreaCode;
			cityCode = areaListData.AreaInfo[index].CityCode;
			amedasCode = areaListData.AreaInfo[index].AmedasCode;
			isZipSearch = false;
			reload();
		});
		$('div#weather img.close').click(function ()
		{
			$('div#weather div.search').hide();
		});
	}
	
	
	/**
	 * 郵便番号検索結果表示
	 */
	var appendZipResult = function ()
	{
		$('div#weather div.zipSearch div.result').empty();
		$('div#weather div.zipSearch div.result').append([
			'<div>',
			'<p class="areaName">' + areaInfoData.AreaName + '</p>',
			'<p class="func"><img src="/topmenu/1103_img/weather_sm/close.png" alt="閉じる" width="72" height="22" class="close" /><img src="/topmenu/1103_img/weather_sm/setting.png" alt="設定する" width="72" height="22" class="setting" /></p>',
			'</div>'
		].join(''));
		$('div#weather div.zipSearch div.result img.setting').click(function ()
		{
			areaCode = areaInfoData.AreaCode;
			cityCode = areaInfoData.CityCode;
			amedasCode = areaInfoData.AmedasCode;
			isZipSearch = true;
			reload();
		});
		$('div#weather img.close').click(function ()
		{
			$('div#weather div.search').hide();
		});
	}
	
	
	/**
	 * 地域再設定表示
	 */
	var appendSettingAgain = function ()
	{
		if(!g_smapho)
		{
			//PC版
			$('div#weather').empty();
			$('div#weather').append([
				'<h2>きょうの天気</h2>',
				'<div class="maintenance">',
				'<p>地域を再設定してください。</p>',
				'<p><a href="' + WEATHER_SETTING_PATH + '"><img src="/topmenu/1103_img/weather/weathersetting.png" alt="設定する" width="38" height="18" class="rollover"></a></p>',
				'</div>'
			].join(''));
		}
		else
		{
			//スマホ版
			if(isZipSearch)
			{
				//郵便番号検索
				if(spinner) spinner.remove();
				var zipResult = $('div#weather div.zipSearch div.result');
				var zipError = zipResult.find('p.zipError');
				if(zipError) zipError.remove();
				zipResult.prepend([
					'<p class="zipError"><span>対象の地域が見つかりません。もう一度入力してください。</span></p>'
				].join(''));
			}
			else
			{
				//天気情報検索
				$('div#weather').empty();
				$('div#weather').append([
					'<h2>きょうの天気</h2>',
					'<p class="disaster"><a href="' + WEATHER_PATH + '"><img src="/topmenu/1103_img/sm/bt_saigai_0804.png" alt="気象・災害"></a></p>',
					'<div class="maintenance">',
					'<p>地域を再設定してください。</p>',
					'<div class="setting"></div>',
					'</div>'
				].join(''));
				//天気設定表示
				appendWeatherSetting(areaInfoData.AreaName);
			}
		}
	}
	

	/**
	 * メンテ中表示
	 */
	var appendMaintenance = function ()
	{
		if(!g_smapho)
		{
			//PC版
			$('div#weather').append([
				'<h2>きょうの天気</h2>',
				'<p class="infoButton"><a href="/weather/?from=tp_pn09"><img src="/topmenu/1103_img/weather/weatherinfo2.png" alt="気象・災害情報" width="81" height="18" class="rollover"></a></p>',
				'<div class="maintenance">',
				'<p>ただいまメンテナンス中です。</p>',
				'</div>'
			].join(''));
		}
		else
		{
			//スマホ版
			$('div#weather').html([
				'<h2>きょうの天気</h2>',
				'<p class="disaster"><a href="' + WEATHER_PATH + '"><img src="/topmenu/1103_img/sm/bt_saigai_0804.png" alt="気象・災害"></a></p>',
				'<div class="maintenance">',
				'<p>ただいまメンテナンス中です。</p>',
				'</div>'
			].join(''));
		}
	}
	
	
	/**
	 * 入力チェック
	 */
	var inputCheck = function (str)
	{
		var zipResult = $('div#weather div.zipSearch div.result');
		var errorCount = 0;
		
		//検索エラー
		var zipError = zipResult.find('p.zipError');
		if(zipError) zipError.remove();
				
		//数字チェック
		var numError = zipResult.find('p.numError');
		if(numError) numError.remove();
		if( str.match( /[^0-9０-９]+/ ) )
		{
			zipResult.prepend([
				'<p class="numError"><span>郵便番号は数字のみで入力してください。</span></p>'
			].join(''));
			errorCount++;
		}
		
		//桁数チェック
		var digitError = zipResult.find('p.digitError');
		if(digitError) digitError.remove();
		if( str.length != 7 )
		{
			zipResult.prepend([
				'<p class="digitError"><span>郵便番号は7桁で入力してください。</span></p>'
			].join(''));
			errorCount++;
		}
		return errorCount;
	}
	
	
	/**
	 * 全角英数→半角英数に変換
	 */
	var convertZenToHan = function (str)
	{
		var han= '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@-.,:';
		var zen= '１２３４５６７８９０ａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ＠－．，：';
		var len = han.length;
		for(i = 0; i < len; i++)
		{
			var regex = new RegExp(zen.charAt(i),"gm");
			str = str.replace(regex,han.charAt(i));
		}
		return str;
	}
	
	
	/**
	 * 地域情報ロード成功
	 */
	this.onSuccessAreaInfo = function(data)
	{
		if(data.Result[0].ResultCode == '1')
		{
			areaInfoData = data.AreaList[0].AreaInfo[0];
			if(isZipSearch)
			{
				appendZipResult();
			}
			else
			{
				amedasCode = areaInfoData.AmedasCode;
				loadWeatherInfo();
			}
		}
		else
		{
			//エラー
			if(isZipSearch)
			{
				if(data.Result[0].ErrorCode == '10')
				{
					//該当する郵便番号なし
					appendSettingAgain();
				}
				else
				{
					//その他
					appendMaintenance();
				}
			}
			else
			{
				//その他
				appendMaintenance();
			}
		}
	}
	
	
	/**
	 * 地域情報リストロード成功
	 */
	this.onSuccessAreaList = function(data)
	{
		if(data.Result[0].ResultCode == '1')
		{
			areaListData = data.AreaList[0];
			appendAreaList2();
		}
		else
		{
			appendMaintenance();
		}
	}
	
	
	/**
	 * 天気情報ロード成功
	 */
	this.onSuccessWeatherInfo = function(data)
	{
		if(data.Result[0].ResultCode == '1')
		{
			//正常
			weatherInfoData = null;
			weatherInfoData = data.WeatherInfo[0];
			appendWeatherInfo();
		}
		else
		{
			//エラー
			if(data.Result[0].ErrorCode == '90')
			{
				//システム障害（データはあり）
				weatherInfoData = data.WeatherInfo[0];
				appendWeatherInfo(true);
			}
			else if(data.Result[0].ErrorCode == '10')
			{
				//アメダスコードなし（地域再設定）
				appendSettingAgain();
			}
			else
			{
				//その他
				appendMaintenance();
			}
		}
	}
}


/**
 * 地域情報CGIのコールバック
 */
function RAreaInfo(data)
{
	weather.onSuccessAreaInfo(data);
}


/**
 * 地域情報リストCGIのコールバック
 */
function RAreaList(data)
{
	weather.onSuccessAreaList(data);
}


/**
 * 天気情報CGIのコールバック
 */
function RWeatherInfo(data)
{
	weather.onSuccessWeatherInfo(data);
}





