function text2Cloud(text) {
  this.text = text;
  this.dic = {};
}

text2Cloud.prototype = new GamMo();

text2Cloud.prototype.scoring = function(text) {
  var str = text || this.text;
  var words = this.Keyword(str);
  if (words.length) {
    for (var i = 0, l = words.length; i < l; i++) {
      if (words[i] in this.dic) {
        this.dic[words[i]]++;
      } else {
        this.dic[words[i]] = 1;
      }
    }
  }
}

text2Cloud.prototype.make = function() {
  this.scoring();
  var div = document.createElement("div");
  div.className = "cloudText";
  for (var k in this.dic) {
    if (this.dic[k] < 3) continue;
    var span = document.createElement("span");
    span.appendChild(document.createTextNode(k));
    span.style.fontSize = ((this.dic[k] >= 24) ? 36 : (this.dic[k] + 11)) + "px";
    span.title = k + "の出現数：" + this.dic[k] + "回";
    div.appendChild(span);
    div.appendChild(document.createTextNode(" "));
  }
  return div;
}

text2Cloud.prototype.sortData = function(order) {
  this.num = [];
  for (var k in this.dic) {
    this.num.push(this.dic[k]);
  }
  var result = [];
  var copyDic = (function() {
    var copy = {};
    for (var k in this.dic) {
      copy[k] = this.dic[k];
    }
    return copy;
  }).call(this);
  if (this.num.length) {
    this.num = this.num.sort(function(a, b) {return a - b});
    if (order != "ascending") this.num = this.num.reverse();
    //if (order == "descending")
    for (var i = 0; i < this.num.length; i++) {
      var n = this.num[i];
      for (var k in copyDic) {
        if (n == copyDic[k]) {
          var item = {};
          item[k] = copyDic[k];
          result.push(item);
          delete copyDic[k];
          break;
        }
      }
    }
  }
  return result;
}


/* ========================================================================== */

function selectMode() {
  var m = $("inputForm").mode;
  var mode = m[0].checked ? m[0].value : m[1].value;
  var t = $("inputText"), f = $("inputFeed"), c = $("clearButton");
  ts = t.style, fs = f.style, cs = c.style;
  if (mode == "text") {
    m[0].disabled = true;
    m[1].disabled = true;
    fs.display = "none";
    ts.display = "inline";
    var h = 2;
    var w = 30;
    var interval = setInterval (function() {
      ts.height = h + "em";
      if (w <= 42) ts.width = w + "em";
      h++;
      w++;
      if (h >= 18) {
        clearInterval(interval);
        cs.display = "inline";
        m[0].disabled = false;
      }
    }, 18);
  } else if (mode == "feed") {
    m[0].disabled = true;
    m[1].disabled = true;
    var fh = 18;
    var fw = 42;
    var interval = setInterval(function() {
      ts.height = fh + "em";
      if (fw >= 30) ts.width = fw + "em";
      fh--;
      fw--;
      if (fh < 2) {
        clearInterval(interval);
        ts.display = "none";
        cs.display = "none";
        fs.display = "inline";
        m[1].disabled = false;
      }
    }, 18);

  }
}

function analyze() {
  var m = $("inputForm").mode;
  var mode = m[0].checked ? m[0].value : m[1].value;
  var t = $("inputText"), f = $("inputFeed"), c = $("clearButton");
  if (mode == "text") {
    text2cloud();
  } else if (mode == "feed") {
    getRSS();
  }
}

// RSS を取得
function getRSS() {
  var feed = $("inputFeed").value;
  if (feed) {
    //processStart($("feed"));
    getRSSPipe(feed);
  } else {
    alert("フィードを入力してください。");
    buttonSW()
      return false;
  }
}

function text2cloud() {
  var text = $("inputText").value;
  if (text) {
    //console.log(deleteTag(text));
    makeCloud(text);
  } else {
    buttonSW()
      return false;
  }
}

function makeCloud(text) {
  text = deleteTag(text);
  var cloud = new text2Cloud(text);
  var c = cloud.make();
  var o = cloud.sortData("descending");
  var q = [];
  for (var i = 0; i < 10; i++) {
    for (var k in o[i]) {
      q.push(("text" + i) + "=" + encodeURIComponent(k) + "(" + o[i][k] + ")");
      q.push( ("value" + i) + "=" + o[i][k]);
    }
  }
  var div = document.createElement("div");
  div.className = "graphImage";
  var a = document.createElement("a");
  a.href = "http://graph.heartrails.com/";
  a.target = "_blank";
  a.appendChild(document.createTextNode("HeartRails Graph"));
  var img = document.createElement("img");
  var src = "http://graph.heartrails.com/api/?" + q.join("&");
  img.src = src;
  img.width = "400";
  img.height = "300";
  div.appendChild(img);
  div.appendChild(document.createElement("br"));
  div.appendChild(a);
  var box = document.createElement("div");
  box.className = "cloudBox";
  box.appendChild(div);
  box.appendChild(c);
  var r = $("result");
  r.innerHTML = "";
  r.style.display = "block";
  r.appendChild(box);
  setTimeout(function() {
    img.src = src + "&noCache=" + new Date().getTime();
  }, 5000);
  buttonSW();
}

/* =============================== Yahoo! Pipes ============================= */

function getRSSPipe(feed) {
  var pr = new PipesRequest();
  pr.query.id = "QNN3xpXR2xG_OY0DJxOy0Q";
  pr.query.callback = "responseRSS";
  pr.inputQuery = {"s": feed};
  pr.set();
}


// jsonp のコールバック関数
function responseRSS(json) {
  if (json) {
    var title = [], text = [];
    var items = json.value.items;
    for (var i = 0, len = items.length; i < len; i++) {
      //title.push(items[i].title);
      text.push(items[i].description);
    }
    //makeCloud(title.join(""));
    if (text.length) makeCloud(text.join(""));
    if (!items.length) {
      alert("フィードを読み込めませんでした。");
      buttonSW()
        return;
    }
  }
}

function deleteTag(str) {
  str = str.replace(/(&lt;|&gt;|&quot;|&amp;)/g, function(m0, m1) {
    return {"&lt;": "<", "&gt;": ">", "&quot;": '"', "&amp;": '&'}[m1];
  });
  str = str.replace(/<[^<]*>/g, "");
  return str;
}

function buttonSW() {
  var f = $("inputForm");
  var submit = $("submitButton");
  var timer;
  if (submit.disabled) {
    if (f.lastChild.tagName == "IMG") f.removeChild(f.lastChild);
    submit.disabled = false;
  } else {
    submit.disabled = true;
    var img = document.createElement("img");
    img.src = "../img/ajax-loader-ball.gif";
    img.alt = "loading...";
    f.appendChild(img);
    timer = setTimeout(function(){
      if (submit.disabled) buttonSW();
      clearTimeout(timer);}, 45000);
  }
}

addEvent(window, "load", function() {
  selectMode();
  addEvent($("feedRadio"), "click", selectMode, false);
  addEvent($("textRadio"), "click", selectMode, false);
  addEvent($("inputForm"), "submit", buttonSW, false);
}, false);

