//グローバル変数の定義
var httpObj = 0;           // HTTP通信用オブジェクト
var timerId;               // HTTP通信用タイマーオブジェクト
var timeout_sec = 300;     // HTTP通信タイムアウト秒数

var xml_url = './index.xml';


/********************************************************OnLoad************/

//onload = function () { 
//  // XMLをHTTP通信で取得
//  httpXmlRequest(xml_url, 'wn', 'GET', '', dispXmlElement, httpError);
//}

function showWhatsNew() {
  // XMLをHTTP通信で取得
  httpXmlRequest(xml_url, 'wn', 'GET', '', dispXmlElement, httpError);
}

/********************************************************前処理************/
// 引数に与えられたURLにHTTPリクエストを行ない、指定された関数を実行
function httpXmlRequest(target_url, id, method, data, success_func, error_func) {
  if (! httpObj){
    httpObj = XmlHttpRequestWrapper();
  }

  if (! httpObj || httpObj.readyState == 1 || httpObj.readyState == 2 || httpObj.readyState == 3){
    return; 
  }

  timerId = setInterval('timeoutCheck()', 1000);
  httpObj.open(method, target_url, true);
  httpObj.onreadystatechange = function() {
    if (httpObj.readyState == 4) {
      clearInterval(timerId);
      if (httpObj.status == 200) {
        success_func(httpObj.responseXML, id);
      } else {
        error_func(httpObj.status + ' : ' + httpObj.statusText);
        return false;
      }
    }
  }
  httpObj.send(data);
}


/********************************************************Main(XML解析/表示)************/
function dispXmlElement(xml, id) {
  // entry要素参照の配列
  var entry = xml.getElementsByTagName('item');
  var i;
  for (i=0; i<entry.length; i++) {
    // 情報を格納する変数の初期化
    var title = '';
    var link = '';
    var author = '';
    // entry要素内の子要素の情報を取得
    var j;
    for(j=0; j<entry[i].childNodes.length; j++) {
      var child = entry[i].childNodes[j];
      if(child.tagName == 'title') {
          if(child.firstChild) {
              title = child.firstChild.nodeValue;
          }
      } else if(child.tagName == 'link') {
          if(child.firstChild) {
              link = child.firstChild.nodeValue;
          }
      } else if(child.tagName == 'author') {
          if(child.firstChild) {
              author = child.firstChild.nodeValue;
          }
      }
    }
    // 書き出し処理
    document.getElementById(id).innerHTML += "<li><a href=\"" + link + "\">" + title + "更新&nbsp;" + author + "</a></li>";
  }
}


/********************************************************Error処理************/
function httpError(error) {
  alert(error);
}


/********************************************************HTTPタイムアウト処理************/
function timeoutCheck() {
  timeout_sec --;
  if(timeout_sec <= 0) {
    // タイマーをストップする
    clearInterval(timerId);
    // HTTPリクエストを中断する
    httpObj.abort();
    // エラーダイアログを表示
    alert('タイムアウトです。');
    return false;
  }
}

