<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="initial-scale=1">
        <style type="text/css">
            body {
                padding: 0;
                margin: 0;
            }
        </style>
		<script src="./scripts/location.js"></script>
		<script src="./scripts/prefecture.js"></script>
		<script src="./scripts/telop.js"></script>
        <script>
			const title = "今日の天気";
			var locationCode = "960044101"; /*千代田区*/

			var result = [];

            var Daily_forecastDate = [];
            var Daily_weatherCode = [];
			var Daily_tempHigh = [];
			var Daily_tempLow  = [];
			var Daily_probPrecip = [];
			var Daily_windStatus = [];
			
			const Daily_numForecasts = 3; //3日間分の予報
			
			var Hourly_time = [];
			var Hourly_weather = [];
			var Hourly_temp = [];
			var Hourly_Precip = [];
			var Hourly_windSpeed = [];
			var Hourly_windDirection = [];
			var Hourly_snowFall = [];
			var Hourly_humidity = [];
			
			const Hourly_numForecasts = 15; //15時間分の予報
			const Hourly_Day1_Start   =  0; //表示開始時間
			const Hourly_Day1_Step    =  3; //表示時間間隔
			const Hourly_Day1_number  =  5; //表示個数
			
			var Hourly_Index = [];
			
			// Window size
			//
			// POPE: 1920x1080 (16:9)
			// Type2: 1443x812 (16:9)
			//
			// 横長
			// size1; 1504 x 846 を超える
			// size2: 1024 x 576 を超える
			// size3:  720 x 405 を超える
			// size4:  544 x 306 を超える
			// size5:  352 x 198 を超える
			// size6:  192 x 108 を超える
			// size6:  192 x 108 以下
			//
			// 縦長
			// size1T; 846 x 1504 を超える
			// size2T: 576 x 1024 を超える
			// size3T: 405 x  720 を超える
			// size4T: 306 x  544 を超える
			// size5T: 198 x  352 を超える
			// size6T: 108 x  192 を超える
			// size6T: 108 x  192 以下
			
			const screenWidth  = window.innerWidth;
			const screenHeight = window.innerHeight;
			
			const widthThreshold1  = 1504;
			const widthThreshold2  = 1024;
			const widthThreshold3  = 720;
			const widthThreshold4  = 544;
			const widthThreshold5  = 352;
			const widthThreshold6  = 192;
			
			const heightThreshold1 = 846;
			const heightThreshold2 = 576;
			const heightThreshold3 = 405;
			const heightThreshold4 = 306;
			const heightThreshold5 = 198;
			const heightThreshold6 = 108;
			
			var interval = intervalDefault;
			var debug = false;

			var pageData = "";

            function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
                return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }
            function getDayOfTheWeek (weekday) {
				const wotd = ["<span class=\"sun\">(日)</span>",
							  "<span class=\"weekday\">(月)</span>", 
							  "<span class=\"weekday\">(火)</span>", 
							  "<span class=\"weekday\">(水)</span>", 
							  "<span class=\"weekday\">(木)</span>", 
							  "<span class=\"weekday\">(金)</span>", 
							  "<span class=\"sat\">(土)</span>"];
				if (weekday < 0) weekday = 0;
				if (weekday > 6) weekday = 6;
				return wotd[weekday];
			}
            function getWeatherIcon (weatherCode) {
                var weatherIcon = "./icons/" + weatherCode + "." + "png" ;

                //alert(weatherIcon);
                return weatherIcon;
            }
            
            function getJWAdataDaily(locationCode) {

                // var dataUrl = "./JWAdata/daily/117130-" + locationCode.substring(0,6) + "_Latest.json";
                var dataUrl = "https://s3.ap-northeast-1.amazonaws.com/weather-data.stg.signage.ricoh/daily/117130-" + locationCode.substring(0,6) + "_Latest.json";
                // alert("dataUrl="+dataUrl);

                // Get weather forecast data
                var req = new XMLHttpRequest();
                req.open("get", dataUrl, false);
                //req.responseType = "json";
                req.send(null);

                // HTTP Get (ASYNC operation)
                if (req.status == 200) {

                    var weatherData = JSON.parse(req.responseText);

					var productData = weatherData.product;
					var pointData = productData[0].point;
                    for (var i=0; i<pointData.length; i++) {
                        if (locationCode == pointData[i].Code) {
							var forecast = pointData[i].forecast;
							
							for (var j=0; j < Daily_numForecasts; j++) {
								var timePeriod = forecast[j].timePeriod;
								if (timePeriod != null) {
									Daily_forecastDate[j] = timePeriod.substr(0,10);
								}
								else {
									Daily_forecastDate[j] = "";
									alert("timePeriod is NULL!");
								}
								var weatherTelop = forecast[j].WeatherTelop;
								if (weatherTelop != null) {
									Daily_weatherCode[j] = weatherTelop[0].$t;
								}
								else {
									Daily_weatherCode[j] = "0";
									alert("WeatherTelop is NULL!");
								}
								var precip = forecast[j].probPrecip;
								if (precip != null) {
									Daily_probPrecip[j] = precip[0].$t;
								}
								else {
									Daily_probPrecip[j] = "0";
									alert("probPrecip is NULL!");
								}
								var minTemp = forecast[j].minTemp;
								if (minTemp != null) {
									Daily_tempLow[j] = minTemp[0].$t;
								}
								else {
									Daily_tempLow[j] = "0";
									alert("minTemp is NULL!");
								}
								var maxTemp = forecast[j].maxTemp;
								if (maxTemp != null) {
									Daily_tempHigh[j] = maxTemp[0].$t;
								}
								else {
									Daily_tempHigh[j] = "0";
									alert("maxTemp is NULL!");
								}
								var synopsisWind = forecast[j].synopsisWind;
								if (synopsisWind != null) {
									Daily_windStatus[j] = synopsisWind[0];
								}
								else {
									Daily_windStatus[j] = "unknown";
									alert("synopsisWind is NULL!");
								}
							}
                        }
                    }
					return (true);

                }
				else {
					alert("location code:"+locationCode+" not found in daily forecast!");
					return (false);
				}
            }
            
            function getJWAdataHourly(locationCode) {

                // var dataUrl = "./JWAdata/daily/117111-" + locationCode.substring(0,6) + "_Latest.json";
                var dataUrl = "https://s3.ap-northeast-1.amazonaws.com/weather-data.stg.signage.ricoh/hourly/117111-" + locationCode.substring(0,6) + "_Latest.json";
                // alert("dataUrl="+dataUrl);

                // Get weather forecast data
                var req = new XMLHttpRequest();
                req.open("get", dataUrl, false);
                //req.responseType = "json";
                req.send(null);

                // HTTP Get (ASYNC operation)
                if (req.status == 200) {

                    var weatherData = JSON.parse(req.responseText);

					var productData = weatherData.product;
					var pointData = productData[0].point;
                    for (var i=0; i<pointData.length; i++) {
                        if (locationCode == pointData[i].code) {
							var forecast = pointData[i].forecast;
							
							for (var j=0; j < Hourly_numForecasts; j++) {
								var timeData = forecast[j].time;
								if (timeData != null) {
									Hourly_time[j] = timeData;
								}
								else {
									Hourly_time[j] = "";
									alert("time is NULL!");
								}
								var weatherData = forecast[j].weather;
								if (weatherData != null) {
									Hourly_weather[j] = weatherData[0];
								}
								else {
									Hourly_weather[j] = "0";
									alert("Weather is NULL!");
								}
								var precip = forecast[j].Precip;
								if (precip != null) {
									Hourly_Precip[j] = precip[0];
								}
								else {
									Hourly_Precip[j] = "0.0";
									alert("Precip is NULL!");
								}
								var tempData = forecast[j].temp;
								if (tempData != null) {
									Hourly_temp[j] = tempData[0];
								}
								else {
									Hourly_temp[j] = "0.0";
									alert("temp is NULL!");
								}
								var windSpeed = forecast[j].windSpeed;
								if (windSpeed != null) {
									Hourly_windSpeed[j] = windSpeed[0];
								}
								else {
									Hourly_windSpeed[j] = "0";
									alert("windSpeed is NULL!");
								}
								var windDirection = forecast[j].windDirection;
								if (windDirection != null) {
									Hourly_windDirection[j] = windDirection[0];
								}
								else {
									Hourly_windDirection[j] = "0";
									alert("windDirection is NULL!");
								}
								var snowFall = forecast[j].snowFall;
								if (snowFall != null) {
									Hourly_snowFall[j] = snowFall[0];
								}
								else {
									Hourly_snowFall[j] = "0.0";
									alert("snowFall is NULL!");
								}
								var humidity = forecast[j].humidity;
								if (humidity != null) {
									Hourly_humidity[j] = humidity[0];
								}
								else {
									Hourly_humidity[j] = "0";
									alert("humidity is NULL!");
								}
							}
                        }
                    }
					return (true);

                }
				else {
					alert("location code:"+locationCode+" not found in hourly forecast!");
					return (false);
				}
            }
            
            //Get current JWA data and select image file to show
            function drawTable() {

                //alert("screen.width      : " + screen.width + "Pixels¥n"+
                //      "screen.height     : " + screen.height + "Pixels¥n"+
                //      "window.parent.screen.width : " + window.parent.screen.width  + "Pixels¥n"+
                //      "window.parent.screen.height: " + window.parent.screen.height + "Pixels¥n"+
                //      "window.innerWidth : " + window.innerWidth  + "Bits¥n"+
                //      "window.innerHeight: " + window.innerHeight + "Bits");

                var width  = window.innerWidth;
                var height = window.innerHeight;                

				// Get URL parameter for location, such as "location=960044101"
				param = getParameterByName("location");
				// Retrieve location code
				if (param != "") {
					locationCode = param;
				}
				//alert("location="+locationCode);

				// Get URL parameter for debug, such as "debug=on"
				param = getParameterByName("debug");
				// Retrieve debug mode
				if (param != "" && param == "on") {
					debug = true;
				}
				//alert("debug="+debug);
				
                // Get daily weather forecast data
				if (getJWAdataDaily(locationCode) == false) {
					alert("getJWAdataDaily error!");
				}

                // Get hourly weather forecast data
				if (getJWAdataHourly(locationCode) == false) {
					alert("getJWAdataHourly error!");
				}
				
				// find hourly data indexes to show
				findIndexes();

				// create table HTML
               	saveHtml();

                // Draw HTML page
				drawPage();
			}
			
			function findIndexes() {
				
				for (var i=Hourly_Day1_Start; i<=Hourly_Day1_End; i+=Hourly_Day1_Step) {
					Hourly_numDay1 ++;
				}

				// write day2 hourly titles
				for (var i=Hourly_Day2_Start; i<=Hourly_Day2_End; i+=Hourly_Day2_Step) {
					Hourly_numDay2 ++;
				}

				// find day1 indexes to show
				var date1Start = new Date(Hourly_time[0]);
				var hour1Start = date1Start.getHours();
				
				if (hour1Start <= Hourly_Day1_Start) {
					Hourly_Index[0] = Hourly_Day1_Start - hour1Start;
					for (var j=1;j<Hourly_numDay1;j++) {
						Hourly_Index[j] = Hourly_Index[j-1]+Hourly_Day1_Step;
					}
					
				}
				else {
					Hourly_Index[0] = -1;
					for (var j=1;j<Hourly_numDay1;j++) {
						var hour1 = Hourly_Day1_Start+Hourly_Day1_Step*j;
						if (hour1Start <= hour1) {
							Hourly_Index[j] = hour1 - hour1Start
						}
						else {
							Hourly_Index[j] = -1;
						}
					}
				}
				
				// find day2 start index
				
				var day1 = new Date(Hourly_time[0]);
				var day2 = new Date(day1);
				day2.setDate(day2.getDate()+1);
				day2.setHours(0);
				day2.setMinutes(0);
				day2.setSeconds(0);
				day2.setMilliseconds(0);
				
				var date2StartIndex = -1;
				for (var i=Hourly_Index[Hourly_numDay1-1]+1; i<Hourly_numForecasts; i++) {
					var date2 = new Date(Hourly_time[i]);
					if (date2.getTime() == day2.getTime()) {
						date2StartIndex = i;
						break;
					} 
				}
				
				// find day2 indexes to show
				var date2Start = new Date(Hourly_time[date2StartIndex]);
				var hour2Start = date2Start.getHours();
				var hour2Index = Hourly_numDay1-1;
				
				if (hour2Start <= Hourly_Day2_Start) {
					Hourly_Index[hour2Index] = Hourly_Day2_Start - hour2Start;
					for (var j=hour2Index+1;j<Hourly_numDay1+Hourly_numDay2;j++) {
						Hourly_Index[j] = Hourly_Index[j-1]+Hourly_Day2_Step;
					}
				}
			}
			
			function saveHtml() {

				// Draw dates
				var date1 = new Date(Daily_forecastDate[0]);
				var date2 = new Date(Daily_forecastDate[1]);
				
				var buf = "<table class=\"main\"><thead class=\"main\"><tr class=\"thr\">";
				buf += "<th colspan=\"5\" class=\"th1\"><span class=\"date\">本日 " + (date1.getMonth()+1) + "月" + (date1.getDate())+ "日" + "</span>"+ getDayOfTheWeek(date1.getDay()) + "</th>";
				
				buf += "<th colspan=\"5\" class=\"th1\"><span class=\"date\">明日 " + (date2.getMonth()+1) + "月" + (date2.getDate())+ "日" + "</span>"+ getDayOfTheWeek(date2.getDay()) + "</th>";
				
				buf += "</tr></thead>";

				// Draw daily forecasts for today and tomorrow
				buf += "<tbody class=\"main\">";
				
				buf += "<tr class=\"tr1\">";
				// write today's weather icon
				buf += "<td colspan=\"2\" rowspan=\"2\" class=\"td1\"><img class=\"telopMain\" src=\"" + getWeatherIcon(Daily_weatherCode[0]) + "\" alt=\""+Daily_weatherCode[0]+"\"></img></td>";

				// write today's temp-high
				buf += "<td class=\"td2\"><span class=\"tempHighTitle\">最高</span></td>";
				buf += "<td colspan=\"2\" class=\"td3\"><span class=\"tempHigh\">" + Daily_tempHigh[0] + "°c</span></td>";
				
				// write tomorrow's weather icon
				buf += "<td colspan=\"2\" rowspan=\"2\" class=\"td1\"><img class=\"telopMain\" src=\"" + getWeatherIcon(Daily_weatherCode[1]) + "\" alt=\""+Daily_weatherCode[1]+"\"></img></td>";

				// write tomorrow's temp-high
				buf += "<td class=\"td2\"><span class=\"tempHighTitle\">最高</span></td>";
				buf += "<td colspan=\"2\" class=\"td3\"><span class=\"tempHigh\">" + Daily_tempHigh[1] + "°c</span></td>";

				buf += "</tr><tr class=\"tr1\">";
				// write today's temp-low
				buf += "<td class=\"td2\"><span class=\"tempLowTitle\">最低</span></td>";
				buf += "<td colspan=\"2\" class=\"td3\"><span class=\"tempLow\">" + Daily_tempLow[0] + "°c</span></td>";
				// write tomorrow's temp-low
				buf += "<td class=\"td2\"><span class=\"tempLowTitle\">最低</span></td>";
				buf += "<td colspan=\"2\" class=\"td3\"><span class=\"tempLow\">" + Daily_tempLow[1] + "°c</span></td>";

				buf += "</tr><tr class=\"tr2\">";

				// Show hourly data
				
				// write day1 hourly titles
				buf += "<td class=\"td4\"><span class=\"title\">時間</span></td>";
				for (var i=Hourly_Day1_Start; i<=Hourly_Day1_End; i+=Hourly_Day1_Step) {
					buf += "<td class=\"td5\"><span class=\"hour\">"+i+"</span></td>";
				}

				// write day2 hourly titles
				buf += "<td class=\"td4\"><span class=\"title\">時間</span></td>";
				for (var i=Hourly_Day2_Start; i<=Hourly_Day2_End; i+=Hourly_Day2_Step) {
					buf += "<td class=\"td5\"><span class=\"hour\">"+i+"</span></td>";
				}

				buf += "</tr><tr class=\"tr2\">";

				// write day1 weather
				buf += "<td class=\"td4\"><span class=\"title\">天気</span></td>";
				for (var i=0; i<Hourly_numDay1;i++) {
					buf += "<td class=\"td6\">";
					buf += "<img class=\"telopSub\" src=\"";
					if (Hourly_Index[i] >= 0) {
						buf += getWeatherIcon(Hourly_weather[Hourly_Index[i]]) + "\" alt=\""+Hourly_weather[Hourly_Index[i]]+"\">";
					}
					else {
						buf += "./icons/blank.png" + "\">";
					}
					buf += "</img></td>";;
				}

				// write day2 weather
				buf += "<td class=\"td4\"><span class=\"title\">天気</span></td>";
				for (var i=Hourly_numDay1; i<Hourly_numDay1+Hourly_numDay2;i++) {
					buf += "<td class=\"td6\"><img class=\"telopSub\" src=\"" + getWeatherIcon(Hourly_weather[Hourly_Index[i]]) + "\" alt=\""+Hourly_weather[Hourly_Index[i]]+"\"></img></td>";;
				}

				buf += "</tr><tr class=\"tr2\">";

				// write day1 temp
				buf += "<td class=\"td4\"><span class=\"title\">気温</span></td>";
				for (var i=0; i<Hourly_numDay1;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">";
					if (Hourly_Index[i] >= 0) {
						buf += Hourly_temp[Hourly_Index[i]] + "°c";
					}
					else {
						buf += "--";
					}
					buf += "</span></td>";;
				}

				// write day2 temp
				buf += "<td class=\"td4\"><span class=\"title\">気温</span></td>";
				for (var i=Hourly_numDay1; i<Hourly_numDay1+Hourly_numDay2;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">" + Hourly_temp[Hourly_Index[i]] + "°c</span></td>";;
				}

				buf += "</tr><tr class=\"tr2\">";

				// write day1 Precip
				buf += "<td class=\"td4\"><span class=\"title\">降水量</span></td>";
				for (var i=0; i<Hourly_numDay1;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">";
					if (Hourly_Index[i] >= 0) {
						buf += Hourly_Precip[i] + "mm/h";
					}
					else {
						buf += "--";
					}
					buf += "</span></td>";
				}

				// write day2 Precip
				buf += "<td class=\"td4\"><span class=\"title\">降水量</span></td>";
				for (var i=Hourly_numDay1; i<Hourly_numDay1+Hourly_numDay2;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">" + Hourly_Precip[i] + "mm/h</span></td>";;
				}

				buf += "</tr><tr class=\"tr2\">";

				// write day1 humidity
				buf += "<td class=\"td4\"><span class=\"title\">湿度</span></td>";
				for (var i=0; i<Hourly_numDay1;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">";
					if (Hourly_Index[i] >= 0) {
						buf += Hourly_humidity[i] + "%";
					}
					else {
						buf += "--";
					}
					buf += "</span></td>";;
				}

				// write day2 humidity
				buf += "<td class=\"td4\"><span class=\"title\">湿度</span></td>";
				for (var i=Hourly_numDay1; i<Hourly_numDay1+Hourly_numDay2;i++) {
					buf += "<td class=\"td6\"><span class=\"data\">" + Hourly_humidity[i] + "%</span></td>";;
				}

				buf += "</tr>";

				buf += "</tbody></table><br>";

				pageData = buf;
			}

			function drawPage(page) {
				var pref = findPref(locationCode.substr(4,2));
				var loc  = findLocation(locationCode);

				document.open();
				document.write("<head><meta charset=\"UTF-8\">");
				document.write("<meta name=\"viewport\" content=\"width=device-width, height=device-height, initial-scale=1, maximum-scale=1\">");
				if (screenHeight <= heightThreshold3) {
					document.write("<link rel=\"stylesheet\" href=\"LocalWeather2daysXSmall.css\" type=\"text/css\">");
				}
				else if (screenHeight <= heightThreshold2) {
					document.write("<link rel=\"stylesheet\" href=\"LocalWeather2daysSmall.css\" type=\"text/css\">");
				}
				else if (screenHeight <= heightThreshold1) {
					document.write("<link rel=\"stylesheet\" href=\"LocalWeather2days.css\" type=\"text/css\">");
				}
				else {
					document.write("<link rel=\"stylesheet\" href=\"LocalWeather2days1K.css\" type=\"text/css\">");

				}
				document.write("<body>");
				document.write("<div width=window.innerWidth, height=window.innerHeight, align=\"center\">");
				
				// write title
				document.write("<table class=\"title\"><tr><td class=\"title\">");
				document.write(title);
				document.write(" <span class=\"zone\"> - " + pref.Prefecture + "</span>" + "<span class=\"city\">(" + loc + ") - </span>");
				if (debug) {
					document.write(" <span class=\"debug\">"+screenWidth+"x"+screenHeight+"</span>");
				}
				document.write("</td></tr></table>");
				
				document.write(pageData);
				document.write("</div>");
				document.write("</body>");
				document.close();
			}

        </script>
    </head>
    <body onload="drawTable()">
    </body>
</html>
