//2007-7 iTsmy 修改提高天气精确度

//var xmlhttp;   //发送网页请求的对象 
//var url = "http://weather.tq121.com.cn/detail.php?city=";
var url = "http://search.weather.com.cn/static/url_gb.php?CityInfo=";
var isValid = false;  
var lastUpdateTime; 
var timehandle;
var hint,hint2,hint3,hint4;
var isRefreshing = false; //正在刷新
var mhandle; 
var isMiniState=false;
//当天天气代码 
var SkyCode;  
//今天的天气信息; 
var DayDate,weatherIcon,weatherIcon,weatherText,weatherText,tmpHigh,tmpLow,wind;
var DayDateArray=[],weatherIconArray=[],weatherTextArray=[],tmpHighArray=[],tmpLowArray=[],windArray=[];
//1-5天的日期文字 例如  DayData1 = '4月8日' 
var DayDate1,DayDate2,DayDate3,DayDate4,DayDate5;
//1-5天的上午天气图标序号  
var weatherIcon1,weatherIcon2,weatherIcon3,weatherIcon4,weatherIcon5;
//1-5天的下午天气图标序号  
var weatherIcon1PM,weatherIcon2PM,weatherIcon3PM,weatherIcon4PM,weatherIcon5PM;
//1-5天的上午天气文字  
var weatherText1,weatherText2,weatherText3,weatherText4,weatherText5;
//1-5天的下午天气文字  
var weatherText1PM,weatherText2PM,weatherText3PM,weatherText4PM,weatherText5PM;
//1-5天的最高温度 
var tmp1High,tmp2High,tmp3High,tmp4High,tmp5High;
//1-5天的最低温度 
var tmp1Low,tmp2Low,tmp3Low,tmp4Low,tmp5Low;
//1-5天的风向风力 
var wind1,wind2,wind3,wind4,wind5;

//将所有天气数据赋值到控件 
function AssignWeatherInfoToControls()
{
  //先锁定刷新，方式闪动 
  LockRefresh;
  
  if(isValid)
  {
    hint = GetSetting( 'city' ) + ' 今日天气' ; 
    hint = hint + '\n温度: ' + tmpLow + ' - ' + tmpHigh + '°' ;
    hint = hint + '\n上午: ' + weatherText ;
    hint = hint + '\n下午: ' + weatherText ;
    hint = hint + '\n风力: ' + wind;
    hint = hint + '\n月相: ' + MoonState_cn();
  
    hint2 = DayDateArray[0]; 
    hint2 = hint2 + '\n温度: ' + tmpLowArray[0] + ' - ' + tmpHighArray[1] + '°' ;
    hint2 = hint2 + '\n上午: ' + weatherTextArray[0] ;
    hint2 = hint2 + '\n下午: ' + weatherTextArray[0] ;
    hint2 = hint2 + '\n风力: ' + windArray[0];
    //hint = hint + '\n月相: ' + MoonState_cn();
  
    hint3 = DayDateArray[1]; 
    hint3 = hint3 + '\n温度: ' + tmpLowArray[1] + ' - ' + tmpHighArray[1] + '°' ;
    hint3 = hint3 + '\n上午: ' + weatherTextArray[1] ;
    hint3 = hint3 + '\n下午: ' + weatherTextArray[1] ;
    hint3 = hint3 + '\n风力: ' + windArray[1];
    //hint = hint + '\n月相: ' + MoonState_cn();

    hint4 = DayDateArray[2]; 
    hint4 = hint4 + '\n温度: ' + tmpLowArray[2] + ' - ' + tmpHighArray[2] + '°' ;
    hint4 = hint4 + '\n上午: ' + weatherTextArray[2] ;
    hint4 = hint4 + '\n下午: ' + weatherTextArray[2] ;
    hint4 = hint4 + '\n风力: ' + windArray[2];
    //hint = hint + '\n月相: ' + MoonState_cn();
  }




  if(isPM()) lastUpdateTime=2
  else if(isNight()) lastUpdateTime=3
  else lastUpdateTime=1;  

  if((dockedOnSidebar)||(widget.pageIndex==1))
  {
    sidebarOn();
  }
  else
  {
   sidebarOff();
  } 
  
  if(isRefreshing)
  {
    txtDockedCity.caption = '刷新...'
    txtCity.caption = '刷新...';
  }
     
  
   //解除刷新锁定 
   UnLockRefresh;  
   Refresh;
   timer1.enabled = true;
}
//取得与城市对应的网页url地址 
function getWeatherUrl(ss){
  var tmpstr,startPos,endPos;
  startPos = ss.indexOf("URL=")+4;
  endPos = ss.indexOf("\">");
  if(startPos<1 || endPos<1){
    txtCity.caption ='查询失败';
    txtDockedCity.caption = '查询失败';
    return;
  }
  ss=ss.substring(startPos,endPos);  
  if(ss.indexOf("http://")!=0){
    txtCity.caption ='查询失败';
    txtDockedCity.caption = '查询失败';
    return;  
  }
  Print(ss);
  DownLoadFileAsync( ss , "weather.tmp" ,"getWebSource" ); //function  onDownFile(fileName,errorCode)
}
//根据url参数,解析出相应网页中的天气信息 
function getWebSource(){
  try
  {
    var oStream = new ActiveXObject("ADODB.Stream");
  }
  catch(e)
  {
    oStream = null;    
    return;  
  }
  if(oStream == null)
    alert("您的机器不支持ADODB.Stream,请将IE浏览器的安全级别设低一些.")
  else{
    try{
      oStream.Type=2;
      oStream.Mode=3;     
      oStream.Charset="utf-8";
      oStream.Open() ;
      oStream.LoadFromFile( widgetPath + "\weather.tmp");
      var htmlCode = oStream.ReadText();
      oStream.Close();
      oStream = null;
    }catch(e){
      oStrem=null;
      return;
    }
    parseHtml(htmlCode);
  }    
}

function returnIconNum(txt){
  var res;
  switch(txt){
    case "阴"    : res=26;break;
    case "多云"  : res=26;break;
    case "晴"    : res=31;break;
    case "阵雨"  : res=9;break;
    case "雷阵雨": res=1;break;
    case "小雨"  : res=39;break;
    case "中雨"  : res=10;break;
    case "大雨"  : res=10;break;
    case "暴雨"  : res=40;break;
    case "大暴雨": res=40;break;    
    case "特大暴雨":res=40;break;
    case "雨加雪": res=13;break;
    case "小雪"  : res=13;break;
    case "中雪"  : res=13;break;
    case "大雪"  : res=16;break; 
    case "暴雪"  : res=13;break;   
    case "雾"    : res=17;break;
    case "冻雨"  : res=18;break;
    case "沙尘暴"  : res=19;break;    
    case "浮尘"  : res=19;break;
    case "扬沙"  : res=23;break;                 
    default : 
      if(txt.indexOf("云")>=0){
        res=26;break;
      }else if(txt.indexOf("晴")>=0){
        res=31;break;
      }else if(txt.indexOf("阴")>=0){
        res=26;break;       
      }else if(txt.indexOf("暴雨")>=0){
        res=40;break;
      }else if(txt.indexOf("阵雨")>=0){
        res=9;break;
      }else if(txt.indexOf("雨")>=0){
        res=10;break;
      }else if(txt.indexOf("雪")>=0){
        res=13;break;       
      }else if(txt.indexOf("雾")>=0){
        res=17;break;
      }else if(txt.indexOf("沙")>=0){
        res=23;break;
      }else{
        res=31;break;
      } 
  }
  return res;
}

//解析下载的html网页获得天气信息 
function parseHtml(htmlStr)
{
   var str,tmpstr,targetStr,i;
   var startPos,endPos;
   str = htmlStr;
   startPos=str.indexOf("<em><strong>");
   str=str.substr(startPos);
   endPos=str.indexOf("<br/>");
   //   得到形如一下结构的字符串 
   //   <em><strong>小雨转阴</strong></em>
   //   <em class="no_today">9℃/ 5℃</em>
   //   <em>南风小于3级</em>
   str=str.substring(0,endPos);
   endPos=str.indexOf("</strong></em>");
   weatherText=str.substring(12,endPos);          //得到今天的天气文字信息 
   str=str.substr(endPos+14);
   startPos=str.indexOf('<em class="no_today">');
   endPos=str.indexOf("</em>");
   tmpstr=str.substring(startPos+21,endPos);      //得到今天温度信息 
   if(parseInt(tmpstr.split("/")[0])>parseInt(tmpstr.split("/")[1])){        
     tmpHigh=parseInt(tmpstr.split("/")[0]);
     tmpLow=parseInt(tmpstr.split("/")[1]);
   }else{
     tmpLow=parseInt(tmpstr.split("/")[0]);
     tmpHigh=parseInt(tmpstr.split("/")[1]);   
   } 
   str=str.substr(endPos+5);
   startPos=str.indexOf("<em>");
   endPos=str.indexOf("</em>");
   wind=str.substring(startPos+4,endPos);         //得到今天的风力信息  
   weatherIcon=returnIconNum(weatherText);        //得到今天天气所对应的图片序号
   Print( tmpHigh);
   Print( tmpLow);
   Print(weatherText);   
   Print( wind);
   Print( weatherIcon);
   
   
 
   //得到未来1-3的天气信息                              
   str=htmlStr;
   startPos=str.indexOf('<div class="fut_weather" id="dd_0">');
   str=str.substr(startPos);
   for(i=0;i<3;i++){
     startPos=str.indexOf('<div class="fut_weatherbox7">');
     endPos=str.indexOf('</div>');
     tmpstr=str.substring(startPos+30,endPos);
     startPos=tmpstr.indexOf('<h3>');
     endPos=tmpstr.indexOf('</h3>');
     DayDateArray[i]=tmpstr.substring(startPos+4,endPos);
     for(j=0;j<4;j++){
       targetStr='<h4 class="temp0'+j+'_dn">';
       startPos=tmpstr.indexOf(targetStr);
       endPos=tmpstr.indexOf('</h4>');
       switch(j){
         case 0: 
           weatherTextArray[i]=tmpstr.substring(startPos+22,endPos);
           tmpstr=tmpstr.substr(endPos+5);           
           break; 
         case 1:
           tmpHighArray[i]=parseInt(tmpstr.substring(startPos+22,endPos).split("：")[1]);
           tmpstr=tmpstr.substr(endPos+5);
           break;
         case 2:
           tmpLowArray[i]=parseInt(tmpstr.substring(startPos+22,endPos).split("：")[1]);
           tmpstr=tmpstr.substr(endPos+5);
           break;
         case 3:
           windArray[i]=tmpstr.substring(startPos+22,endPos);
           break;
         default:
           break;       
       }
     }
     if(i!=2)str=str.substr(str.indexOf('</div>')+6);
     weatherIconArray[i]=returnIconNum(weatherTextArray[i]);     
   }  
   Print( DayDateArray[2]);
   Print( weatherTextArray[2]);
   Print( tmpHighArray[2]);
   Print( tmpLowArray[2]);
   Print( windArray[2]);      

  //将所有天气数据赋值到控件 
  AssignWeatherInfoToControls();
  //刷新
  Refresh; 
}

function  onDownFile(fileName,errorCode)
{
  isRefreshing = false; 
  if(errorCode<1)
  {
    //alert("连接服务器出错: " + xmlhttp.statusText + " (" + xmlhttp.status  + ")");
    result = "";
    isRefreshing = false;
    isValid = false;
    hint = "连接服务器出错: " + xmlhttp.statusText + " (" + xmlhttp.status  + ")";  
    AssignWeatherInfoToControls();
    Print( errorCode );
    Print( hint );
    return;
  }
  isValid = true;
  parseHtml( readFile(fileName));
  deleteFile(  fileName );
  
   

}

//下载指定url网址的html代码 
function StartGetUrlHtmlString(url)
{
  try
  {
    var oStream = new ActiveXObject("ADODB.Stream");
  }
  catch(e)
  {
    oStream = null;
    //如果无法建立 ADODB.Stream 则改用内置下载函数直接来获取天气预报信息
    DownLoadFileAsync( url , "weatherinfo.tmp" ,"onDownFile" );      
    return;
  
  }

  //先创建一个xmlhttp的对象
  var xmlhttp=createXmlhttp(); 
  if(!xmlhttp){
    alert("启用XMLHttpRequest出错!");
    return;
  }
  //构造请求，获取网页信息
  try{
    xmlhttp.open("GET", url , true);
  } catch(e){ }
  //设置异步响应事件的函数,当request获得了网页源码后会调用此函数 
  xmlhttp.onreadystatechange = function() 
  {
    //判断请求返回的状态 
  　if (xmlhttp.readyState == 4) 
    {
  　　if (xmlhttp.status == 200) 
      {
        
        isRefreshing = false;

  　　　 //var response = xmlhttp.responseText; 
         //var response = xmlhttp.responseXml;
        
        //用stream方式返回，防止中文乱码。如果全为英文，可以直接用  xmlhttp.responseText 来返回 
        //Print( xmlhttp.responseText );
	if(oStream == null)
  	  alert("您的机器不支持ADODB.Stream,请将IE浏览器的安全级别设低一些.")
	else
	{
	  isValid = true;
          oStream.Type=1;
          oStream.Mode=3;
          oStream.Open() ;
          oStream.Write(xmlhttp.responseBody);
          oStream.Position= 0;
          oStream.Type= 2;
          //设置编码方式 
          oStream.Charset="gb2312";
          //获得下载到的html源码，并传入解析函数
          var str = oStream.ReadText();
          //Print(str)
          getWeatherUrl(str); 
          //parseHtml(str);
          oStream.Close();
          oStream = null;
          return;
	}
  　　} 
      else
      {
        //alert("连接服务器出错: " + xmlhttp.statusText + " (" + xmlhttp.status  + ")");
        result = "";
        isRefreshing = false;
        isValid = false;
        hint = "连接服务器出错: " + xmlhttp.statusText + " (" + xmlhttp.status  + ")";  
        AssignWeatherInfoToControls();
      }
  　}
  }
  //完成发送请求 
  xmlhttp.send(null);
}

//创建 request对象的通用函数，以下代码主要是为了兼容不同版本的ie内核做的防错处理 
function createXmlhttp() {
  var xmlhttp;
　try {
　　xmlhttp = new XMLHttpRequest();
　} catch (trymicrosoft) {
　　try {
　　　xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
　　} catch (othermicrosoft) {
　　　try {
　　　　xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
　　　} catch (failed) {
　　　　xmlhttp = false;
　　　}
　　}
　}
  return xmlhttp;
}

function nMenu1OnClick()
{
  //刷新天气信息 
  RefreshWeatherInfo(); 
}

function widgetOnDock()
{
  LockRefresh;
  widget.pageIndex = 1;
  widgetWidth = 130;
  widgetHeight = 67; 
  UnLockRefresh;
  //将所有天气数据赋值到控件 
  AssignWeatherInfoToControls(); 
}

function widgetOnUnDock()
{
  LockRefresh;
  widget.pageIndex = 2;
  widgetWidth = 264;
  widgetHeight = 194; 
  
  UnLockRefresh; 
  
  //将所有天气数据赋值到控件 
  AssignWeatherInfoToControls(); 

}

function transTq121Code(code)
{
    var res,a;
    a =  parseInt(code);
    switch ( a ) 
    {
        case (0) : res = 31; break;//晴
        case (1) : res = 26;  break;//多云
        case (2) : res = 26; break;//阴
        case (3) : res = 9; break;//阵雨
        case (4) ://雷阵雨
        case (5) : res = 1; break;//雷阵雨并伴有冰雹
        case (6) : res = 13; break;//雨加雪
        case (7) : res = 39; break;//小雨
        case (8) : res = 10; break;//中雨
        case (9) : res = 10; break;//大雨
        case (10) : res = 40; break;//暴雨
        case (11) : res = 40; break;//大暴雨
        case (12) : res = 40; break;//特大暴雨
        case (13) : res = 13; break;//阵雪
        case (14) : res = 13; break;//小雪
        case (15) : res = 13; break;//中雪
        case (16) : res = 16; break;//大雪
        case (17) : res = 16; break;//暴雪
        case (18) : res = 17; break;//雾
        case (19) : res = 18; break;//冻雨
        case (20) : res = 19; break;//沙尘暴
        case (21) ://小雨-中雨
        case (22) ://中雨-大雨
        case (23) ://大雨-暴雨 
        case (24) ://暴雨-大暴雨 
        case (25) : res = 9; break;//大暴雨-特大暴雨
        case (26) : res = 13; break;//小雪-中雪
        case (27) : res = 13; break;//中雪-大雪
        case (28) : res = 16; break;//大雪-暴雪
        case (29) : res = 19; break;//浮尘
        case (30) : res = 23; break;//扬沙
        case (31) : res = 23; break;//强沙尘暴
        default: res = 31
   }     
        
   return res;
  
}

function trim(str)
{
  // 用正则表达式将前后空格
  // 用空字符串替代。
  return str.replace(/(^\s*)|(\s*$)/g, "");
}


function WeatherState(Code) 
{
    var theWeatherState;
    switch ( Code ) 
    {
        case (26) : case (27) : case (28) :
            theWeatherState = "cloudy";
            break;
        case (35) : case (39) : case (45) : case (46) : 
            theWeatherState = "few-showers";
            break;
        case (19) : case (20) : case (21) : case (22) :
            theWeatherState = "foggy";
            break;
        case (29) : case (30) : case (33) :
            theWeatherState = "partly-cloudy";
            break;
        case (5) : case (13) : case (14) : case (15) : case (16) : case (18) : case (25) : case (41) : case (42) : case (43) : 
            theWeatherState = "snow";
            break;
        case (1) : case (2) : case (3) : case (4) : case (37) : case (38) : case (47) : 
            theWeatherState = "thunderstorm";
            break;
        case (31) : case (32) : case (34) : case (36) : case (44) :        // Note 44- "Data Not Available"
            theWeatherState = "sun";
            break;
        case (23) : case (24) :
            theWeatherState = "windy";
            break;
        case (9) : case (10) : case (11) : case (12) : case (40) :
            theWeatherState = "Rainy";
            break;
        case (6) : case (7) : case (8) : case (17) : 
            theWeatherState = "hail";
            break;
        default:
            theWeatherState = "sun";
            break;
      }
      return theWeatherState;
}


function toChineseString(code, str)
{
//iTsmy更改获取天气文字函数
    var a;
    var theWeatherState = str;
    a =  parseInt(code);
    switch ( a ) 
    {
        case (0) : theWeatherState = "晴"; break;
        case (1) : theWeatherState = "多云";  break;
        case (2) : theWeatherState = "阴"; break;
        case (3) : theWeatherState = "阵雨"; break;
        case (4) : theWeatherState = "雷阵雨"; break;
        case (5) : theWeatherState = "雷阵雨并伴有冰雹"; break;
        case (6) : theWeatherState = "雨加雪"; break;
        case (7) : theWeatherState = "小雨"; break;
        case (8) : theWeatherState = "中雨"; break;
        case (9) : theWeatherState = "大雨"; break;
        case (10) :theWeatherState = "暴雨"; break;
        case (11) : theWeatherState = "大暴雨"; break;
        case (12) : theWeatherState = "特大暴雨"; break;
        case (13) : theWeatherState = "阵雪"; break;
        case (14) : theWeatherState = "小雪"; break;
        case (15) : theWeatherState = "中雪"; break;
        case (16) : theWeatherState = "大雪"; break;
        case (17) : theWeatherState = "暴雪"; break;
        case (18) : theWeatherState = "雾"; break;
        case (19) : theWeatherState = "冻雨"; break;
        case (20) : theWeatherState = "沙尘暴"; break;
        case (21) : theWeatherState = "小雨-中雨"; break;
        case (22) : theWeatherState = "中雨-大雨"; break;
        case (23) : theWeatherState = "大雨-暴雨"; break; 
        case (24) : theWeatherState = "暴雨-大暴雨"; break; 
        case (25) : theWeatherState = "大暴雨-特大暴雨"; break;
        case (26) : theWeatherState = "小雪-中雪"; break;
        case (27) : theWeatherState = "中雪-大雪"; break;
        case (28) : theWeatherState = "大雪-暴雪"; break;
        case (29) : theWeatherState = "浮尘"; break;
        case (30) : theWeatherState = "扬沙"; break;
        case (31) : theWeatherState = "强沙尘暴"; break;
        default: theWeatherState = "晴"
   }     
        
   return theWeatherState;
}


function nMenu2OnClick()
{
  var city = prompt("请输入城市名称", GetSetting("city") );
  if(city=='<undefined>' )
    return;
  SetSetting("city",city);
  SaveSetting('city');
  
  //刷新天气信息 
  RefreshWeatherInfo(); 
}


//刷新天气信息 
function RefreshWeatherInfo()
{
  isRefreshing = true;
  timer1.enabled = false;
  txtDockedCity.caption = '刷新...'
  txtCity.caption = '刷新...'; 
  print(  url + GetSetting( 'city' ) + "&" + (new Date).getTime() );
  StartGetUrlHtmlString( url + GetSetting( 'city' ) + "&" + (new Date).getTime() );
}


function widgetOnDBClick()
{ 
  //RefreshWeatherInfo();
   nMenuSwitchnClick(); 
}

//判断是否是晚上 
function isNight() 
{
  var d = new Date();
  // Before SunRise or after Sunset means it's Night 
  return ((d.getHours()<6)||(d.getHours()>18));
}
//判断是否是下午 
function isPM() 
{
  var d = new Date();
 
  return (  (!isNight())  && (d.getHours()>12)  );
}

//背景图片前缀 
function GetBackgroundPngHead()
{ 
    var theBackground = "BLUE";
    var theDisplayMode;
    
    switch ( SkyCode ) 
    {
      default : 
      case (26) : case (27) : case (28) :
      case (35) : case (39) : case (45) : case (46) : 
      case (19) : case (20) : case (21) : case (22) :
      case (1) : case (2) : case (3) : case (4) : case (5) : case (37) : case (38) : case (47) : 
      case (9) : case (10) : case (11) : case (12) : case (40) : case (41) : case (42) : case (43) :
      case (6) : case (7) : case (8) : case (17) : case (13) : case (14) : case (15)  : case (16) : case (18) :
        theBackground = "BLUE";
        break;
      case (29) : case (30) : case (33) : case (34) :
      case (31) : case (32) : case (36) : case (44) :        
      case (23) : case (24) : case (25) : 
        theBackground = "GRAY";
        break;
    }  
    
    if (isNight()) 
    { 
      theBackground = "BLACK";  
    }
    
    
    if ( !isValid )
    { 
      theBackground = "BLUE";  
    }
    
    if(widget.pageIndex==1)   //(dockedOnSidebar)
    {
      theBackground = theBackground + 'docked';
    }
    
    return theBackground;
}

////////////////////////////////////////////////////////////////////////////////
//
// GMTTime() - returns time adjusted to GMT (Universal Time)
//
////////////////////////////////////////////////////////////////////////////////
function GMTTime() 
{ 
  var aDate = new Date();
  var aDateAdjustedToGMTInMS = aDate.getTime();// + (aDate.getTimezoneOffset() * 60 * 1000);
  return ( new Date( aDateAdjustedToGMTInMS ) );
}  

function widgetOnStart()
{
  //mhandle = setTimeout( 'moshi' , 100 );
  RefreshWeatherInfo();
}

function moshi()
{
  Print( 'moshi' );
  clearTimeout(mhandle);
  if(!dockedOnSidebar)
  {
    if(ReadIni( 'uimode' )=='mini')
      widget.pageIndex = 1
    else
      widget.pageIndex = 2;    
  }
  
}

function widgetOnInit()
{
  lastUpdateTime = -1;
  timer0.interval = 1 * 60 * 60 * 1000;  //每小时刷新
  timer0.enabled = true; 
  
}

function timer0OnTimer()
{
  RefreshWeatherInfo();
}

function MoonState() 
{ 
  return computePhaseOfMoon(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate()); 
}

function MoonState_cn() 
{ 
  return computePhaseOfMoon_cn(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate()); 
}

////////////////////////////////////////////////////////////////////////////////
//中文月相 
// computePhaseOfMoon_cn(Year, Month, Day) - Computes Phase of Moon based on Date
//
////////////////////////////////////////////////////////////////////////////////
function computePhaseOfMoon_cn(Year, Month, Day) 
{
  // Variable names used: J, K1, K2, K3, MM, P2, V, YY
  var P2 = 3.14159 * 2;    
  var YY = Year - parseInt((12 - Month)/10);
  var MM = Month + 9;
  if (MM >= 12) { MM = MM-12; }
  var K1 = parseInt(365.25 * (YY+4712));
  var K2 = parseInt(30.6 * MM + .5);
  var K3 = parseInt(parseInt((YY/100) + 49) * .75) - 38;
  // J is the Julian date at 12h UT on day in question
  var J = K1+K2+Day+59;             
  // Adjust for Gregorian calendar, if applicable   
  if (J > 2299160) { J = J-K3; }    
  // Calculate illumination (synodic) phase
  var V = (J - 2451550.1)/29.530588853;
  V = V - parseInt(V);
  // Normalize values to range from 0 to 1
  if (V<0) { V=V+1; }
  // Moon's age in days from New Moon
  var AG = V*29.53;    

  switch (true) 
  { 
    // Each phase lasts approximately 3.28 days
    case ((AG > 27.6849270496875) || (AG <= 1.8456618033125)) :
      var retVal = '朔月';
      break;
    case ((AG > 1.8456618033125) && (AG <= 5.5369854099375)) :
      var retVal = '眉月';
      break;
    case ((AG > 5.5369854099375) && (AG <= 9.2283090165625)) :
      var retVal = '上弦月';
      break;
    case ((AG > 9.2283090165625) && (AG <= 12.9196326231875)) : 
      var retVal = '盈凸月';
      break;
    case ((AG > 12.9196326231875) && (AG <= 16.6109562298125)) :
      var retVal = '满月';
      break;
    case ((AG > 16.6109562298125) && (AG <= 20.3022798364375)) :
      var retVal = '盈凸月';
      break;
    case ((AG > 20.3022798364375) && (AG <= 23.9936034430625)) :
      var retVal = '下弦月';
      break;
    case ((AG > 23.9936034430625) && (AG <= 27.6849270496875)) :
      var retVal = '残月';
      break;
    default : 
      var retVal = '满月';
      break;
  }    
  return retVal;
}


////////////////////////////////////////////////////////////////////////////////
//
// computePhaseOfMoon(Year, Month, Day) - Computes Phase of Moon based on Date
//
////////////////////////////////////////////////////////////////////////////////
function computePhaseOfMoon(Year, Month, Day) 
{
  // Variable names used: J, K1, K2, K3, MM, P2, V, YY
  var P2 = 3.14159 * 2;    
  var YY = Year - parseInt((12 - Month)/10);
  var MM = Month + 9;
  if (MM >= 12) { MM = MM-12; }
  var K1 = parseInt(365.25 * (YY+4712));
  var K2 = parseInt(30.6 * MM + .5);
  var K3 = parseInt(parseInt((YY/100) + 49) * .75) - 38;
  // J is the Julian date at 12h UT on day in question
  var J = K1+K2+Day+59;             
  // Adjust for Gregorian calendar, if applicable   
  if (J > 2299160) { J = J-K3; }    
  // Calculate illumination (synodic) phase
  var V = (J - 2451550.1)/29.530588853;
  V = V - parseInt(V);
  // Normalize values to range from 0 to 1
  if (V<0) { V=V+1; }
  // Moon's age in days from New Moon
  var AG = V*29.53;    

  switch (true) 
  { 
    // Each phase lasts approximately 3.28 days
    case ((AG > 27.6849270496875) || (AG <= 1.8456618033125)) :
      var retVal = 'New';
      break;
    case ((AG > 1.8456618033125) && (AG <= 5.5369854099375)) :
      var retVal = 'Waxing-Crescent';
      break;
    case ((AG > 5.5369854099375) && (AG <= 9.2283090165625)) :
      var retVal = 'First-Quarter';
      break;
    case ((AG > 9.2283090165625) && (AG <= 12.9196326231875)) : 
      var retVal = 'Waxing-Gibbous';
      break;
    case ((AG > 12.9196326231875) && (AG <= 16.6109562298125)) :
      var retVal = 'Full';
      break;
    case ((AG > 16.6109562298125) && (AG <= 20.3022798364375)) :
      var retVal = 'Waning-Gibbous';
      break;
    case ((AG > 20.3022798364375) && (AG <= 23.9936034430625)) :
      var retVal = 'Last-Quarter';
      break;
    case ((AG > 23.9936034430625) && (AG <= 27.6849270496875)) :
      var retVal = 'Waning-Crescent';
      break;
    default : 
      var retVal = 'Full';
      break;
  }    
  return retVal;
}

////////////////////////////////////////////////////////////////////////////////
//
// makesSenseToDisplayTheMoon - boolean indicating whether it makes sense to 
//                              display the moon.  Dependant on weather state
//
////////////////////////////////////////////////////////////////////////////////
function makesSenseToDisplayTheMoon() 
{
  var retVal = false;
  if ( isNight() ) 
  { 
    var theWeatherState = WeatherState();
    if ( ( theWeatherState=="sun" ) || ( theWeatherState=="partly-cloudy" )  ) 
    {
      retVal = true;
    }
  }
  return retVal;
}





function OnAllSettingsSaved()
{
  SaveSetting('city');
  
  //刷新天气信息 
  RefreshWeatherInfo();   
}

function timer1OnTimer()
{
  var nowtm;
  if(isPM()) nowtm=2
  else if(isNight()) nowtm=3
  else nowtm=1;  
  
  
  if(nowtm!=lastUpdateTime) 
  {
     lastUpdateTime = nowtm;
     RefreshWeatherInfo();
  }
}

function nMenuSwitchnClick()
{
  //先锁定刷新，方式闪动 
  LockRefresh;
  
  if(widget.pageIndex == 1)
  {
    //如果已经停靠在边栏了，就不需要再放大了 
    if(dockedOnSidebar)
      return;
      
    widget.pageIndex = 2;
    WriteIni('uimode' ,'full' ); 
    //sidebarOff();
     
    //WriteIni( 'myState' , 'Normal' );
  }
  else
  {
    widget.pageIndex = 1;
    WriteIni('uimode' ,'mini' ); 
    
    //sidebarOn();
     
    //WriteIni( 'myState' , 'mini' );
  }
  
  UnLockRefresh;

  AssignWeatherInfoToControls()
  Refresh;  
  
  if(( widgetWidth+widget.Left>DesktopWidth)) // || ( (!dockedOnSidebar)&&(widget.pageIndex = 1)  ) )
    timehandle = setTimeout( 'duiqi' , 100 );
}

function duiqi()
{
  clearTimeout(timehandle);
  widget.Left = DesktopWidth - widgetWidth;
     
}


function sidebarOn()
{
    //停靠状态下
    var bgNameHead = GetBackgroundPngHead(); 
    dockedBg.Src = 'images\/' + GetBackgroundPngHead() + '-base.png';
    dockhl1.Src = 'images\/' + bgNameHead + '-highlight-02.png'; 
    dockhl2.Src = 'images\/' + bgNameHead + '-highlight-01.png'; 

    if ( makesSenseToDisplayTheMoon() ) 
    {
      dockedIcon.Src =  'images\/icons\/docked_moon-' + MoonState() + '.png';
    }
    else
    {
      if(!isPM())
        dockedIcon.Src =  'images\/icons\/docked_'+ WeatherState( weatherIcon )  + '.png'
      else
        dockedIcon.Src =  'images\/icons\/docked_'+ WeatherState( weatherIcon ) + '.png';
    } 

    if(isValid)
    { 
      txtDockedCity.caption = GetSetting( 'city' )
      txtDockedTmp.caption = tmpLow + '~' + tmpHigh + '°';
      txtDockedCity.tooltip = hint;
    }
    else
    {
      txtDockedCity.caption = GetSetting( 'city' ) + "!";
      txtDockedTmp.caption = "";
      txtDockedCity.tooltip = "链接网络失败";
    }
    
//    txtDay2.tooltip = hint2;
//    txtDay3.tooltip = hint3;
//    txtDay4.tooltip = hint4;
   
   }
   
function sidebarOff()
{
    //未停靠状态下
    var bgNameHead = GetBackgroundPngHead();
    bg.Src = 'images\/' + bgNameHead + '-base.png';
    hl1.Src = 'images\/' + bgNameHead + '-highlight-01.png'; 
    hl2.Src = 'images\/' + bgNameHead + '-highlight-01.png'; 

    txtWeatherInfo.caption = weatherText;
    if ( makesSenseToDisplayTheMoon() ) 
    {
      bigIcon.Src =  'images\/icons\/undocked_moon-' + MoonState() + '.png';
      txtCity.tooltip = MoonState_cn();
    }
    else
    {
      if(!isPM())
        bigIcon.Src =  'images\/icons\/undocked_'+ WeatherState( weatherIcon ) + '.png'
      else
        bigIcon.Src =  'images\/icons\/undocked_'+ WeatherState( weatherIcon )  + '.png';
    } 
    if(isPM())
    {
      iconDay2.Src =  'images\/small\/'+ weatherIconArray[0]  + '.png';
      iconDay3.Src =  'images\/small\/'+ weatherIconArray[1]  + '.png';
      iconDay4.Src =  'images\/small\/'+ weatherIconArray[2]  + '.png';
    }
    else
    {
      iconDay2.Src =  'images\/small\/'+ weatherIconArray[0]  + '.png';
      iconDay3.Src =  'images\/small\/'+ weatherIconArray[1]  + '.png';
      iconDay4.Src =  'images\/small\/'+ weatherIconArray[2]  + '.png';
    }
    txtBigTmp.caption = parseInt(( parseInt(tmpLow) + parseInt(tmpHigh) )/2) + '°'; 
    txtTodayTmp.caption = tmpLow + '  -  ' + tmpHigh + '°';
    txtCity.caption = GetSetting( 'city' );
    txtDay2.caption = DayDateArray[0];
    txtDay3.caption = DayDateArray[1];
    txtDay4.caption = DayDateArray[2];

    txtTmpH2.caption =  tmpHighArray[0] + '°';
    txtTmpH3.caption =  tmpHighArray[1] + '°';
    txtTmpH4.caption =  tmpHighArray[2] + '°';

    txtTmpL2.caption =  tmpLowArray[0] + '°';
    txtTmpL3.caption =  tmpLowArray[1] + '°';
    txtTmpL4.caption =  tmpLowArray[2] + '°';

    txtCity.tooltip = hint;  
    txtDay2.tooltip = hint2;
    txtDay3.tooltip = hint3;
    txtDay4.tooltip = hint4;
    

}

function copyrightOnClick()
{
  OpenLink( url + GetSetting( 'city' ) );
}

function widgetOnPopupMenu()
{
  if(dockedOnSidebar)
  {
    nMenu4.Visible = false;
  
  }
  else
  {
    nMenu4.Visible = true;
    if(widget.pageIndex==1)
      nMenu4.caption = '切换到详细模式'
    else
      nMenu4.caption = '切换到迷你模式';
  
  }
}

function widgetOnClose()
{
  if(widget.pageIndex == 1)
  {
    WriteIni('uimode' ,'full' ); 
  }
  else
  {
    WriteIni('uimode' ,'mini' ); 
  }
  
}

function btRefresh2OnClick()
{
  RefreshWeatherInfo();   
}