//ver1.1
//-----------------------------------------------------------------------------
// 初期処理
//-----------------------------------------------------------------------------
function init()
{
  //
  // オブジェクト生成
  //
  obj_in_status = document.getElementById("in_status");
						// JSON取得状態
  obj_in_url    = document.getElementById("in_url");
						// JSON取得リクエスト
  obj_in_view   = document.getElementById("in_view");
						// Viewボタン
  obj_in_result = document.getElementById("in_result");
						// 結果
  obj_out_txt   = document.getElementById("out_txt_data");
						// JSON表示領域(テキスト)
  obj_out_tree  = document.getElementById("out_tree_data");
						// JSON表示領域(ツリー)

  //
  // 初期化
  //
  out_txt  = "";				// JSON出力データ(テキスト)
  out_tree = "";				// JSON出力データ(ツリー)

  timeout_msec = 3000;				// リクエストタイムアウト時間
						// (ミリ秒)

  proc_flg = 0;					// 処理中フラグOFF

  img_sign_ok   = "/image/sign_ok.png";		// 結果画像(OK)
  img_sign_ng   = "/image/sign_ng.png";		// 結果画像(OK)
  img_sign_none = "/image/sign_none.png";	// 結果画像(空白)
  img_loading   = "/image/loading.gif";		// ローディング画像

  color_ok = "#91ca86";				// 結果カラー(OK)
  color_ng = "#ed6465";				// 結果カラー(NG)

  obj_in_status.src = img_sign_none;		// 入力URLチェック状態OFF

  obj_in_view.disabled = false;			// Viewボタン有効化

  //
  // HTTPステータスコード
  //
  http_status = new Array();

  http_status[100] = "Continue";
  http_status[101] = "Switching Protocols";
  http_status[102] = "Processing";
  http_status[200] = "OK";
  http_status[201] = "Created";
  http_status[202] = "Accepted";
  http_status[203] = "Non-Authoritative Information";
  http_status[204] = "No Content";
  http_status[205] = "Reset Content";
  http_status[206] = "Partial Content";
  http_status[207] = "Multi-Status";
  http_status[226] = "IM Used";
  http_status[300] = "Multiple Choices";
  http_status[301] = "Moved Permanently";
  http_status[302] = "Found";
  http_status[303] = "See Other";
  http_status[304] = "Not Modified";
  http_status[305] = "Use Proxy";
  http_status[306] = "(Unused)";
  http_status[307] = "Temporary Redirect";
  http_status[400] = "Bad Request";
  http_status[401] = "Unauthorized";
  http_status[402] = "Payment Required";
  http_status[403] = "Forbidden";
  http_status[404] = "Not Found";
  http_status[405] = "Method Not Allowed";
  http_status[406] = "Not Acceptable";
  http_status[407] = "Proxy Authentication Required";
  http_status[408] = "Request Timeout";
  http_status[409] = "Conflict";
  http_status[410] = "Gone";
  http_status[411] = "Length Required";
  http_status[412] = "Precondition Failed";
  http_status[413] = "Request Entity Too Large";
  http_status[414] = "Request-URI Too Long";
  http_status[415] = "Unsupported Media Type";
  http_status[416] = "Requested Range Not Satisfiable";
  http_status[417] = "Expectation Failed";
  http_status[418] = "I'm a teapot";
  http_status[422] = "Unprocessable Entity";
  http_status[423] = "Locked";
  http_status[424] = "Failed Dependency";
  http_status[425] = "(Unordered Collection)";
  http_status[426] = "Upgrade Required";
  http_status[500] = "Internal Server Error";
  http_status[501] = "Not Implemented";
  http_status[502] = "Bad Gateway";
  http_status[503] = "Service Unavailable";
  http_status[504] = "Gateway Timeout";
  http_status[505] = "HTTP Version Not Supported";
  http_status[506] = "Variant Also Negotiates";
  http_status[507] = "Insufficient Storage";
  http_status[510] = "Not Extended";

  http_status[901] = "Not JSON";		// JSON/JSONP以外のリクエスト
}

//-----------------------------------------------------------------------------
// 後処理
//-----------------------------------------------------------------------------
function last()
{
  //
  // 初期化
  //
  proc_flg = 0;					// 処理中フラグ

  out_txt  = "";				// JSON出力データ(テキスト)
  out_tree = "";				// JSON出力データ(ツリー)

  clearTimeout(timer_id);			// タイムアウト設定

  //
  // 有効化
  //
  obj_in_view.disabled = false;			// Viewボタン

}

//-----------------------------------------------------------------------------
// 処理中断
//-----------------------------------------------------------------------------
function abort_proc(msg)
{
  xmlHttp.abort();

  //
  // 中断表示
  //
  obj_in_status.src = img_sign_ng;
  obj_in_result.style.color = color_ng;
  obj_in_result.innerHTML = msg;

  last();
}

//-----------------------------------------------------------------------------
// 入力URL妥当性チェック
//-----------------------------------------------------------------------------
function in_check()
{
  //
  // URLチェック
  //
  in_url = obj_in_url.value;
  in_check_match = in_url.match(/^http:\/\//);	// URLチェック(以下がOK)
						// - http://〜
  //
  // Viewボタンの有効/無効化
  //
  if (in_check_match)				// URLチェックがOKなら
  {
    if (proc_flg != 1)				// 処理中でなければ
    {
      obj_in_view.disabled = false;		// Viewボタン有効化
    }
  }
  else
  {
    obj_in_view.disabled = true;		// Viewボタン無効化
  }
}

//-----------------------------------------------------------------------------
// JSON取得
//-----------------------------------------------------------------------------
function get_json()
{
  //
  // 表示領域クリア
  //
  obj_in_result.innerHTML = '';
  obj_out_txt.innerHTML = '';
  obj_out_tree.innerHTML = '';

  //
  // 処理
  //
  proc_flg = 1;					// 処理中フラグON

  obj_in_view.disabled = true;			// Viewボタン無効化

  xmlHttp = new createXMLHttp();		// XMLHttpRequest生成

  if(xmlHttp)
  {
    obj_in_status.src = img_loading;		// ローディング画像

    timer_id = setTimeout("abort_proc('invalid request or timeout')", timeout_msec);
						// タイムアウト設定

    var request = "get.cgi?url=" + escape(in_url);
						// リクエスト生成

    xmlHttp.open("GET", request, true);		// リクエスト送信

    xmlHttp.onreadystatechange = proc_json;	// リクエスト完了時処理定義

    xmlHttp.send(null);
  }
}

//
// リクエスト完了時のデータ正否チェック
//
function proc_json()
{
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
						// リクエスト正常終了
  {
    //
    // データ取得
    //
    var json_data_txt = xmlHttp.responseText;

    json_data_txt = json_data_txt.replace("<", "&lt;");
    json_data_txt = json_data_txt.replace(">", "&gt;");

    //
    // データなし
    //
    if (!json_data_txt)
    {
      obj_in_status.src = img_sign_ok;
      obj_in_result.style.color = color_ok;
      obj_in_result.innerHTML = "no data";

      last();

      return;
    }

    //
    // エラー
    //
    if(json_data_txt.match(/^error/))
    {
      var error_code = json_data_txt.split("|")[1];
	                                        // エラーNo取得

      obj_in_status.src = img_sign_ng;
      obj_in_result.style.color = color_ng;
      obj_in_result.innerHTML = http_status[parseInt(error_code)];

      last();

      return;
    }

    //
    // データあり(オリジナルデータ出力)
    //
    out_txt  = "<h3>Original</h3>\n";
    out_txt += "<h4>" + json_data_txt + "</h4>\n";
    out_txt += "<h5>(" + json_data_txt.length + "bytes)</h5>\n";
    out_txt += "<h6><img src='/image/arrow.gif' alt='' /></h6>\n";
    obj_out_txt.innerHTML = out_txt;

    //
    // データあり(ツリーデータ出力)
    //
    json_data_txt = json_data_txt.replace(/^[\w\s\.]+/, "");
							// コールバック関数除去
    json_data_txt = json_data_txt.replace(/[\n]$/, "");	// 最終改行コード除去
    json_data_txt = json_data_txt.replace(/\);$/, ")"); // 最終セミコロン除去

    out_tree = "<h3>Tree</h3>\n";

    var json_data = eval("(" + json_data_txt + ")");
						// JSONオブジェクト生成
    out_tree += '<div id="tree_box">\n';
    parse_json(json_data);			// JSONデータ解析
    out_tree += '</div>\n';

    obj_in_status.src = img_sign_ok;
    obj_in_result.innerHTML = "";

    obj_out_tree.innerHTML = out_tree;

    last();					// 終了処理
  }
}

//
// JSONデータ解析
//
function parse_json(json)
{
  out_tree += '<ul>\n';

  for (var key in json)
  {
    var data = json[key];

    out_tree += '<li class="key">' + key + '</li>\n';

    if (data instanceof Object || data instanceof Array)
						// データがオブジェクトや配列の
						// 場合
    {
      parse_json(data);				// 配下のデータを再帰的に取得
    }
    else					// データが文字列の場合
    {
      out_tree += '<li>' + data + '</li>\n';	// 出力
    }
  }

  out_tree += '</ul>\n';
}

//-----------------------------------------------------------------------------
// XMLHttpRequestオブジェクト定義(クロスブラウザ対応)
//-----------------------------------------------------------------------------
function createXMLHttp()
{
  var xmlHttp;

  if (window.XMLHttpRequest)			// Safari, Firefox, Opera...
  {
    xmlHttp = new XMLHttpRequest();
  }
  else						// IE4,5,6
  {
    if (window.ActiveXObject)
    {
      try
      {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e)
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  }

  return(xmlHttp);
}

