// ROTATION ID
var _timerID;
// Twitter記事読込のインターバル
var INTERVAL = 120000
// ROTATIONするLINEのサイクル
var LINE_INTERVAL = 7000
// 表示できる最大個数 userTLの引数numが上限
var LIMIT;
// spam回避用
var NGW = [
"[ﾁｹｯﾄ",
"[9",
"[ﾗｲﾌﾞ",
"[最安値",
"[格安",
"[ﾁｹ",
"http://amelog.peewee.jp",
"twipple_kuji",
"pixiv",
"[激安",
"pecori.jp",
"parasite.jp",
"boyfriend.jp",
"人妻の部屋",
"お友達募集中ﾃﾞｽ",
"アソコ",
"写メ載",
"ダダ漏れ",
"ツイッターFM",
"cashokane.com",
"長谷川幸洋"
]


  //指定したユーザのタイムラインを表示
	function userTL(word1,word2,place,num) {
	  LIMIT = num
	  var plus = 15 // NG埋合せのためバッファをとる
	  var func = arguments.callee
		$.ajax({
			type: "GET",
			//url: "http://search.twitter.com/search.json?q=%23" + word1 + "+OR+%23" + word2,
		  url: "http://search.twitter.com/search.json?lang=ja&q=%23" + word1 + ((word2) ? "+OR+%23"+word2 : ""),
			lang: "ja",
			page: "1",
			data: { "rpp": (num+plus) },
			dataType: "jsonp",
			success: function(json) {
			  json.results.reverse() // 昇順
        $(place).empty()
        initialize(json, place, func)
        // 180秒間隔でタイムライン更新
        setTimeout(function(){
          if(_timerID) clearInterval(_timerID)
          func(word1, word2, place, num)
        },INTERVAL)
      }
    })
  }


  function initialize(json, place, func){
    // 透明化
    $("#tweetArea").css({"opacity":"0"})
    var counter = 0
    // 取得したTwittデータを降順にソート
    json.results.reverse()
    
    $.each(json.results, function(i,info){
      var item = info
      var delay_cnt = 0
      
      // NGWORD 
      if(!checkWords(item.text)) return;
      // 上限まできたら終了
      if(LIMIT < ++counter) return false;
  
      //投稿されたテキスト
      var tw_text = URLText(escapeHtml(item.text))
      //var tw_text = URLText(item.text)
      
      //投稿されたユーザー名
      var userName = item.from_user
      //ユーザーの画像
      var userImg = item.profile_image_url
      //ユーザーのリプライ
      var id = item.from_user_id
      var reply_url = "http://twitter.com/?status=@" + userName + "%20&in_reply_to_status_id=" + id + "&in_reply_to=" +userName && ""
      var reply = "<a href='" + reply_url + "' target='_blank'>返信</a>" && ""
      //投稿時間
      var create_time = dateConvertSearchTL(item.created_at) //&& "" //日付変換 ※表示するときは [&& ""] を削除

      /*var maxSize = 80 //文字列の最大サイズ（記号含む）
      if (tw_text.length > maxSize) {
        tw_text =	tw_text.substr(0, maxSize - 1) + "…" + "<span class='shortStr'><a target='_blank' href='http://twitter.com/" + userName + "' >続きを読む</a></span>"
      }*/

      var twHTML = "<p class='userIMG'><a href='http://twitter.com/" + userName	+"' target='_blank'><img width='48' src='" + userImg + "' /></a></p>"
      twHTML    += "<div class='userBox'><p class='author'><a href='http://twitter.com/"+ userName + "' target='_blank'>" + userName + "</a></p>"
      twHTML    += "<p class='date'><span>" + create_time + "</span>" + reply + "</p></div><p class='tweetText'>" + tw_text + "</p>"

      var node;
      var div = document.createElement("div")
      div.className = "even"
      if((i%2) == 0){
        div.className = "even"
        div.innerHTML = twHTML
          //node = "<div class='even'>" + twHTML + "</div>"
          //$(place).append("<div class='even'>" + twHTML + "</div>")
      } else {
        div.className = "add"
        div.innerHTML = twHTML
          //node = "<div class='add'>" + twHTML + "</div>"
          //$(place).append("<div class='add'>" + twHTML + "</div>")
      }
      
      if($(place).children().length < 1){
        $(place).append(div)
      } else {
        $(place).append(div)
        //$(place).get(0).insertBefore( div, $(place).children()[0])
      }
      
      // 負荷対策
      getElementFromClass('userIMG', div).style.cssText = 'float:left;width:26px;margin:0 0 5px 0'
      getElementFromClass('userBox', div).style.cssText = 'margin-left:60px'
      getElementFromClass('tweetText', div).style.cssText = 'clear:both;margin:0;font-size:11px;line-height:1.4'
      getElementFromClass('author', div).style.cssText = 'margin:0 0 4px 0'
      getElementFromClass('author', div).getElementsByTagName("a")[0].style.cssText = 'font-weight:bolder;color:#424242;font-size:12px'
      getElementFromClass('date', div).style.cssText   = 'margin:0 0 4px 0;font-size:12px;color:#999'
      getElementFromClass('date', div).getElementsByTagName("span")[0].style.cssText = 'margin:0;padding:0 5px 0 0;font-size:12px'
      div.style.cssText = 'margin:0;padding:10px 0 10px 0'
    })//each Loop End

    // ALPHA EFFECT
    $("#tweetArea").animate({opacity: 1}, 850)
    //$("#tweetArea").animate({opacity: 0}, 0).animate({opacity: 1}, 850)

    // ROTAION START
    //loop(place)
    // HEIGHT 固定
    //document.getElementById("tweetArea").style.height = document.getElementById("tweetArea").offsetHeight + "px"
  }

  function getElementFromClass(clsname, element){
    var cls = clsname
    var ele = element
    
    var d = ele.getElementsByTagName("*")
    var l = d.length
    var val
    for(var i=0; i<l; i++){
      if(d[i].className == cls){
        val = d[i]
        break
      }
    }
    return val
  }

  function hideTweetLine(ele, delay_cnt){
    var spot  = ele
    var delay = delay_cnt || 0
    spot.style.visibility = "hidden"
    $(spot).hide(0)
    $(spot).css({opacity:"0"})
    showTweetLine(spot,delay*100)
  }

  function showTweetLine(node, zure){
    var p = node
    var delay = zure || 0
    setTimeout(function(){
      $(p).show(650, function(){
        p.style.visibility = "visible"
        $(p).animate({opacity: 1}, 600)
      })
    }, delay)
  }

  function loop(place){
    _timerID = setInterval(function(){
      var mover = $(place).children()[$(place).children().length-1]
      $(place).get(0).removeChild($(place).children()[$(place).children().length-1])
      $(place).get(0).insertBefore( mover, $(place).children()[0])
      var spot = $(place).children()[0]
      spot.style.visibility = "hidden"
      $(spot).hide(0)
      $(spot).css({opacity:"0"})
      showTweetLine(spot,0)
    }, LINE_INTERVAL)
  
  }



  //指定したユーザのタイムラインを表示 (ID決め打ち)
	function fixUserTL(word,place,acount, num) {
		$.ajax({
			type: "GET",
			url: "http://twitter.com/statuses/user_timeline/" + word + ".json",
			lang: "ja",
			page: "1",
			data: {
				"q": word,
				"count": num
			},
			dataType: "jsonp",
			success: function(json) {
        $(place).empty()
        $.each(json, function(i, item){
          var tw_text = URLText(item.text)
          userName = item.user.screen_name
          userImg = item.user.profile_image_url
          var id = item.id
          var reply_url = "http://twitter.com/?status=@jwave813fm%20&in_reply_to_status_id=" + id + "&in_reply_to=jwave813fm"
          var reply = "<span class='replyclass'><a href='" + reply_url + "' target='_blank'>返信</a></span>"
          var create_time = item.created_at.split(" ")
          var post_date	= create_time[1] + " " + create_time[2] + ", " + create_time[5] + " " + create_time[3] 
          var time_value = new Date(post_date) 
          time_value.setHours(time_value.getHours() + 9)
          var mon	= time_value.getMonth() + 1
          var day	= time_value.getDate() 
          var minutes = (time_value.getMinutes() < 10) ?	"0" + time_value.getMinutes() : time_value.getMinutes()
          var date = mon + "月" + day + "日 " + time_value.getHours() + ":" + minutes
          //var maxSize = 20 //文字列の最大サイズ（記号含む）
          //if (tw_text.length > maxSize) {
          //tw_text =	tw_text.substr(0, maxSize - 1) + "…" + "<span class='shortStr'><a target='_blank' href='http://twitter.com/" + item.user.screen_name + "' >続きを読む</a></span>"
          //}

          var twHTML = "<p class='userIMG'><a href='http://twitter.com/" + userName	+"' target='_blank'><img width='48' src='" + userImg + "' /></a></p>"
          twHTML    += "<div class='userBox'><p class='author'><a href='http://twitter.com/"+ userName + "' target='_blank'>" + userName + "</a></p><p class='date'><span>" + date + "</span>" + reply + "</p></div>"
          twHTML    += "<p class='tweetText'>" + tw_text + "</p>"
          if((i%2) == 0){
              $(place).append("<div class='even'>" + twHTML + "</div>")
          } else {
              $(place).append("<div class='add'>" + twHTML + "</div>")
          }
          
          //スタイル設定
          $('.userIMG').css({"float":"left","width":"26px","margin":"0 0 5px 0"})
          $('.userBox').css({"margin-left":"60px"})
          $('.tweetText').css({"clear":"both","margin":"0","font-size":"11px","line-height":"1.4"})
          $('.author').css({"margin":"0 0 4px 0"})
          /* $('.shortStr a').css({"color":"#2a7eaa"}) */
          $('.author a').css({"font-weight":"bolder","color":"#424242","font-size":"12px"})
          $('.date').css({"margin":"0 0 4px 0","font-size":"12px","color":"#999"})
          $('.date a').css({"color":"#2a7eaa","font-size":"12px"})
          $('.date span').css({"margin":"0","padding":"0 5px 0 0","font-size":"12px"})
          $('.even').css({"margin":"0","padding":"10px 0 10px 0"})
          $('.add').css({"margin":"0","padding":"10px 0 10px 0"})

          /* $(place).append("<dl><dt>" + tw_text	+"</dt><dd>" + date	+ reply +"</dd></dl>") */
			  })
		  }
//				$(acount).append("<dl><dt id='accountIMG'><a href='http://twitter.com/komukuni' target='_blank'><img src='" + userImg + "' width='48' height='48' /></a></dt><dd><a href='http://twitter.com/komukuni' target='_blank'>" + userName + "</a></dd></dl>")
	  })
  }


	//世界標準時間から日本時間へ変換
	function dateConvertSearchTL(data){
		var create_time = data.split(" ")
		var post_date	= create_time[1] + " " + create_time[2] + ", " + create_time[4] + " " + create_time[3] 
		var time_value = new Date(post_date) 
		time_value.setHours(time_value.getHours() + 9)

		var mon	= time_value.getMonth() + 1
		var day	= time_value.getDate() 
		var minutes = (time_value.getMinutes() < 10) ?	"0" + time_value.getMinutes() : time_value.getMinutes()

		return mon + "月" + day + "日 " + time_value.getHours() + ":" + minutes
	}

  /*
   *  LINKとHASHTAGにanchor設定
   */
  function URLText(MyStr){
    var newtext="";
    var splittext = MyStr.split(" ");
    var hash_tags;
    var hash_html;
    var hash_name;
    for(var i=0; i<splittext.length; i++){
      //if(splittext[i].indexOf("http",0) < 0){
      if(splittext[i].match(/^https?:/) === null){
        continue;
      }
      url_text = splittext[i].replace(splittext[i],"<a target='_blank' href='"+splittext[i]+"'>" + splittext[i] +"</a>");
      splittext[i] = url_text;
    }

    for (var i=0; i<splittext.length; i++) {
      hash_tags = splittext[i].match(/\s*#[a-zA-Z0-9_\-]*[\s\r]*/g);
      if (!!hash_tags){
        hashtag_name = String(hash_tags);
        hash_name = hashtag_name.replace(/^\s*/,"").substr(1,hashtag_name.length);
        hash_html = '<a target="_blank" href="http://twitter.com/search?q=%23' + hash_name + '">'+ hashtag_name + '</a>';
        //newtext += hash_html + " ";
        newtext += splittext[i].replace(hashtag_name, hash_html) + " ";
      } else {
        newtext += splittext[i] + " ";
      }
    }
    return newtext;
  }

  /*
   * ESCAPE
   */
  function escapeHtml(word){
    var w = word || ""
    w = w.replace(/</, '&lt;')
    w = w.replace(/>/, '&gt;')
//    w = w.replace(/&/, '&amp;')
    
    return w
  }

  /*
   * Refusal NGWord
   */
  function checkWords(tubuyaki){
    var word = tubuyaki
    var isOK = true
    for(var i=0; i<NGW.length; i++){
      if(word.indexOf(NGW[i]) != -1){
        isOK = false
        break
      }
    }
    return isOK
  }
  
