/**
 * Part of weather codes are taken from Ubiquity (Mozilla Labs project) weather command
 * The author of weather command is mitcho (Michael Yoshitaka Erlewine) - mitcho@mitcho.com
 **/

var WEATHER_CODE_MAP = {
  "unknown": [44, "拿不准"],
  "drizzle": [9, "小雨"],
  "drizzle mist": [9, "小雨"],
  "rain": [12, "雨"],
  "rain mist": [12, "雨"],
  "snow": [16, "雪"],
  "heavy snow": [43, "大雪"],
  "snow grains": [14, "小阵雪"],
  "ice crystals": [17, "冰雹"],
  "ice pellets": [17, "冰雹"],
  "hail": [17, "冰雹"],
  "mist": [12, "雨"],
  "fog": [20, "雾"],
  "smoke": [22, "烟尘"],
  "volcanic ash": [21, "烟雾"],
  "widespread dust": [19, "尘"],
  "sand": [23, "沙尘"],
  "haze": [21, "烟雾"],
  "spray": [44, "拿不准"],
  "dust whirls": [19, "尘"],
  "sandstorm": [23, "沙尘暴"],
  "low drifting snow": [16, "雪"],
  "low drifting widespread dust": [19, "尘"],
  "low drifting sand": [23, "沙尘"],
  "blowing snow": [15, "风雪"],
  "blowing widespread dust": [19, "尘"],
  "blowing sand": [19, "沙尘"],
  "rain showers": [40, "零星阵雨"],
  "snow showers": [46, "阵雪"],
  "snow mist": [14, "小阵雪"],
  "light snow showers": [14, "小阵雪"],
  "ice pellet showers": [35, "雨夹冰雹"],
  "hail showers": [17, "冰雹"],
  "small hail showers": [17, "冰雹"],
  "thunderstorm": [4, "雷雨"],
  "thunderstorms and rain": [4, "雷雨"],
  "thunderstorms and snow": [5, "雨夹雪"],
  "thunderstorms and ice pellets": [35, "雨夹冰雹"],
  "thunderstorms with hail": [35, "雨夹冰雹"],
  "thunderstorms with small hail": [35, "雨夹冰雹"],
  "freezing drizzle": [8, "冷毛毛雨"],
  "freezing rain": [5, "雨夹雪"],
  "freezing fog": [20, "雾"],
  "overcast": [26, "多云"],
  "clear": [31, "晴"],
  "partly cloudy": [29, "多云"],
  "mostly cloudy": [27, "多云"],
  "scattered clouds": [29, "多云"],
  "flurries": [13, "小雪"],
  "sleet": [18, "雨夹雪"],
  "thunderstorms": [4, "雷雨"],
  "a thunderstorm": [4, "雷雨"],
  "cloudy": [26, "多云"],
  "mostly sunny": [32, "阳光明媚"],
  "partly sunny": [32, "阳光明媚"],
  "sunny": [32, "阳光明媚"]
};

var FORECASTDAY_COUNT = 6;

var WeatherPage = {
  today_condition: '',
  today_temp: '',

  init: function(){
    var self = this;
    function load(city) {
      self.initPage(city);
      window.setTimeout(function() {
        self.startLoading(city);
      }, 0);
    }

    var cityLocation = '';
    try {
      var [, , cityInput] = window.location.href.match(/^(.*)\?(.*)$/);
      cityLocation = jQuery.trim(decodeURIComponent(cityInput));
    } catch (e) {
      cityLocation = "";
    }
    if (cityLocation && cityLocation.length > 0) {
      cityLocation = cityLocation.split('&')[0];
      document.title = document.title + " - " + cityLocation;
      load(cityLocation);
    } else {
      this.initPage('未知位置');
      this.showMessage("* 正在获取您的地理位置......您也可以手动搜索 ⇩")
    }

    window.addEventListener("hashchange", function() {
      if (location.hash == '#error') {
        self.showMessage("* 获取您的地理位置失败，请手动搜索");
      }
    }, false);
  },

  initPage: function(city) {
    this.showMessage("* 正在读取......");

    $('#city-name').text(city.toUpperCase());

    var now = new Date();
    var dayName = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    for (var i = 0; i < FORECASTDAY_COUNT; i += 1) {
      var weatherItem = $('<div>').attr('id', 'weather-day-' + i)
          .attr('class', 'forecast-item');
      weatherItem.html($('#weather-day-template').html());
      weatherItem.insertBefore("#footer");
      $('#weather-day-' + i + " > .forecast-day").text(dayName[(now.getDay() + i) % 7]);
    }

    if (FORECASTDAY_COUNT % 2 == 0) {
      $('#footer').css('background', "rgb(55, 86, 117)");
    }
  },

  showMessage: function(text) {
    $('#footer').text(text);
  },

  showSuccessMessage: function() {
    if (this.today_condition !== 'clear' && this.today_condition.indexOf('sunny') == -1
        && this.today_condition.indexOf('snow') == -1) {
      this.showMessage("! 变天咯，要注意阿～");
    } else if (this.today_condition.indexOf('snow') != -1) {
      this.showMessage("! 下雪啦～～");
    } else if (parseInt(this.today_temp) <= 15) {
      this.showMessage('! 好冷阿，记得加衣服阿～');
    } else if (parseInt(this.today_temp) > 30) {
      this.showMessage('! 热死，水～水～水～');
    } else {
      var greetings = [
        "今天天气不错，挺风和日丽的～",
        "好天气，去郊游吧～",
        "天气这么好，约朋友打球吧"
      ];
      this.showMessage(greetings[Math.floor(Math.random() * greetings.length)]);
    }
  },

  startLoading: function(city){
    var self = this;

    function getGeoDone(data) {
      contentAPI.makeObjAccessible(data);
      if (data != null && data.Status.code === 200) {
        if (data.Placemark.length > 0) {
          var coordinates = {
            longitude: data.Placemark[0].Point.coordinates[0],
            latitude: data.Placemark[0].Point.coordinates[1]
          };
          self.getWeatherData(coordinates);

          var countryInfo = data.Placemark[0].AddressDetails.Country;
          var cityName = city;
          if ('Locality' in countryInfo) {
            cityName = countryInfo.Locality.LocalityName;
          } else if ('AdministrativeArea' in countryInfo){
            cityName = countryInfo.AdministrativeArea.Locality.LocalityName;
          }
          $('#city-name').text(cityName.toUpperCase());
          return;
        }
      }
      self.showMessage("* 无法读取地理信息，请检查输入的地名是否正确...");
    }

    this.getGeoLocation(city, getGeoDone);
  },

  getGeoLocation: function(city, callback){
    // Please apply your own key for such application development, it is free, :)
    var params = {
      key: "ABQIAAAASCaOeo3ta_dogUbwquyfCxSpqFEWLxmF2C8ASAeMYkWcm8RXShQKtE5gb4GQJT6JrnWVPp5dE67yyw",
      q: encodeURIComponent(city),
      sensor: false,
      output: 'json',
      oe: 'utf-8'
    };
    var requestLink = "http://ditu.google.cn/maps/geo?" + [[key, params[key]].join('=') for (key in params)].join('&');

    contentAPI.ajax({
      url: requestLink,
      method: 'GET',
      dataType: 'json',
      beforeSend: function(request) {
        contentAPI.setRequestHeader(request, 'Referer', 'http://g-fox.cn/');
      },
      success: function(data) {
        callback(data);
      },
      error: function(request, status) {
        contentAPI.log("[livemargins] Weather geo service error: " + status);
        callback(null);
      },
    });
  },

  getConditionCode: function(condition) {
    var conditionCode = condition.toLowerCase();
    if (conditionCode != 'heavy snow' && conditionCode != 'light snow showers')
      conditionCode = conditionCode.replace(/^(heavy|light) /,'');

    conditionCode = conditionCode.replace(/^chance of /,'');

    return conditionCode;
  },

  getYahooWeatherImage: function(condition, dayOrNight) {
     var conditionCode = this.getConditionCode(condition);
    var weatherId = 44;
    if (conditionCode in WEATHER_CODE_MAP) {
      weatherId = WEATHER_CODE_MAP[conditionCode][0];
    }
    var imgSrc = "http://l.yimg.com/us.yimg.com/i/us/nws/weather/gr/";
    var now = new Date();
    if (dayOrNight === null) {
      dayOrNight = 'd';
      if (now.getHours() < 7 || now.getHours() >= 18) {
        dayOrNight = 'n'
      }
    }
    imgSrc += weatherId + dayOrNight + ".png";
    return imgSrc;
  },

  getWeatherData: function(coord){
    var self = this;

    var windDirName = {
      "East": "东风", "South": "南风", "West": "西风", "North": "北风",
      "SE": "东南风", "ESE": "东南风", "SSE": "东南风",
      "SW": "西南风", "WSW": "西南风", "SSW": "西南风",
      "NE": "东北风", "NNE": "东北风", "ENE": "东北风",
      "NW": "西北风", "NNW": "西北风", "WNW": "西北风",
      'Variable': "可变风向"
    };
    var windLevelThreshold = [0, 1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 133];

    var query = encodeURIComponent(coord.latitude + ',' + coord.longitude);
    contentAPI.ajax({
      url: "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + query,
      method: 'GET',
      dataType: 'text',
      beforeSend: function(request) {
      },
      success: function(text) {
        if (text) {
          var xml = jQuery.parseXML(text);
          var condition = jQuery.trim($('current_observation > weather', xml).text());
          if (condition && condition.length > 0) {
            var weather = {};
            weather.condition = condition.toLowerCase();
            weather.temp = $('current_observation > temp_c', xml).text();
            weather.wind_dir = $('current_observation > wind_dir', xml).text();
            if (weather.wind_dir in windDirName) {
              weather.wind_dir = windDirName[weather.wind_dir];
            }
            var wind_speed = parseFloat($('current_observation > wind_mph', xml).text()) * 1.6;

            for (var i = 0; i < windLevelThreshold.length; i += 1) {
              if (wind_speed < windLevelThreshold[i]) {
                weather.wind_speed = String(i - 1);
                break;
              }
            }

            weather.humidity = $('current_observation > relative_humidity', xml).text();

            self.today_condition = weather.condition;
            self.today_temp = weather.temp;
            var conditionCode = self.getConditionCode(weather.condition);
            if (conditionCode) {
              var image = $('<img>').attr('src', self.getYahooWeatherImage(weather.condition, null));
              var fakeDiv = $('<div>').append(image);
              $('#weather-today-image').html(fakeDiv.html());

              if (conditionCode in WEATHER_CODE_MAP) {
                weather.condition = WEATHER_CODE_MAP[conditionCode][1];
              } else {
                weather.condition = weather.condition.toUpperCase();
              }
            }
            $('#today-temp').text(weather.temp + "°C - " + weather.condition);
            $('#today-wind').text(weather.wind_dir + " " + weather.wind_speed + "级");
            $('#today-humidity').text("湿度：" + weather.humidity);

            // success to get result, call forecast data;
            self.getForecastData(coord);
          } else {
            // fail to retrieve the data, show some information
            self.showMessage("* 无法读取到今天的天气信息...");
          }
        }
      },
      error: function(request, status) {
        contentAPI.log("[livemargins] Weather service error: " + status);
        self.showMessage("* 无法读取到今天的天气信息...");
      },
    });
  },

  getForecastData: function(coord) {
    var self = this;

    var query = encodeURIComponent(coord.latitude + ',' + coord.longitude);
    contentAPI.ajax({
      url: 'http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=' + query,
      method: 'GET',
      dataType: 'text',
      beforeSend: function(request){
      },
      success: function(text){
        if (text) {
          var xml = jQuery.parseXML(text);
          var forecastSets = $('forecast > simpleforecast', xml);
          var forecastDays = forecastSets.find("forecastday");
          if (forecastDays.length > 0) {
            for (var i = 0; i < forecastDays.length && i < FORECASTDAY_COUNT; i += 1) {
              var highTemp = $('high > celsius', forecastDays[i]).text();
              var lowTemp = $('low > celsius', forecastDays[i]).text();
              var condition = $('conditions', forecastDays[i]).text().toLowerCase();

              var conditionCode = self.getConditionCode(condition);
              var image = $('<img>').attr('src', self.getYahooWeatherImage(condition, (i == 0 ? null : 'd')))
                  .attr('style', "height: 32px;");
              var fakeDiv = $('<div>').append(image);
              $('#weather-day-' + i + " > .forecast-image").html(fakeDiv.html());

              var tempHtml = highTemp + '°C <span style="color: rgb(129, 157, 181);">' + lowTemp + '°C</span>';
              $('#weather-day-' + i + " > .forecast-temp").html(tempHtml);
            }
            self.showSuccessMessage();
          }
        }
      },
      error: function(request, status){
        self.showMessage("* 无法读取到预报信息...");
      },
    });
  },

};

function init() {
  WeatherPage.init();
};
