$(function(){

  // var officialHashTag = '#nowplaying'; //#sbh2010
  var players_api = base_url + 'timeline/players';
  var staff_api = base_url + 'timeline/staff';
  var fan_api = base_url + 'timeline/fan';
  var ticket_api = base_url + 'timeline/search_ticket';
  var event_api = base_url + 'timeline/search_event';
  var twitter_update_api = base_url + 'tweets/post/';
  var proxy_url = base_url + 'caution.php?url=';
  var unread_api = base_url + 'timeline/get_unread';

  //-----*-----*-----*-----*
  // Initial Status
  //-----*-----*-----*-----*
  // Get all latest timelines
  getPlayersTimeline();
  getStaffTimeline();
  getFanTimeline();
  getUnreadData();
  $.timer(60000, function(){
    getUnreadData();
  });

  //-----*-----*-----*------*----*
  // get initial players timeline
  //-----*-----*-----*------*----*
  function getPlayersTimeline (){
    var _cookie_name = 'player_current_page';
    $.cookie(_cookie_name, null);
    page = 1;
    api_url = players_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      $.each(json.timeline, function(i, item){
        render_players_timeline({'data':item,'index':i});
      });
    });
  };

  //-----*-----*-----*------*----*
  // Read more players timeline
  //-----*-----*-----*------*----*
  function readMorePlayersTimeline (){
    var _cookie_name = 'player_current_page';
    var page = parseInt($.cookie(_cookie_name));
    if(!page){
      page = 2;
    } else {
      page = page + 1;
    }
    var api_url = players_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      if(json.next_page=='false'){
        return false;
      } else {
        $.cookie(_cookie_name, page);
      }
      $.each(json.timeline, function(i, item){
        render_players_timeline({'data':item,'index':i,'mode':'more'});
      });
    });
  };

  function render_players_timeline(opt){
    var _target = $('#player');
    var template = $('<li class=" clearfix"> <div class="icon"><img src="" alt="" width="48" height="48" /></div> <div class="tweet"> <p><span class="screen_name"></span></p> <div class="time"></div> <div class="pr"><a href=""><img class="pr" src="" alt="プロフィール" title="プロフィール" width="24" height="24" /></a></div><div class="rt"><a href=""><img class="rt" src="" alt="リツイート" title="リツイート" width="24" height="24" /></a></div></div></li>');
    $('.icon img', template).attr('src',opt.data.profile_image_url);
    $('span.screen_name', template).text(opt.data.screen_name);
    $('p', template).append(opt.data.text);
    $('.time', template).text(opt.data.created_at);
    $('.description', template).text(opt.data.description);
    $('img.pr', template).attr('src', base_url + "images/pic/btn_pr_out.jpg");
    $('img.rt', template).attr('src', base_url + "images/pic/btn_rt_out.jpg");
    showProfilePopup(template, opt);
    showRetweetForm(template, opt);
    if(opt.mode == 'more'){
      $('.timeline ul', _target).append(template);
    }else{
      if(opt.index == 0){
        $('.timeline ul', _target).text('').append(template);
      }
      $('.timeline ul', _target).append(template);
    }
  };

  // プロフィールポップアップをクリック表示するイベント関数
  function showProfilePopup(template, opt){
    $('.pr a', template).bind("click", function(){
      $('#profOpen #profName span').text(opt.data.screen_name + ' (' + opt.data.name + ')');
      $('#profOpen #profImg img').attr('src', opt.data.profile_image_url + '?' + Math.floor(Math.random() * 10000));
      $('#profOpen #profUrl a').text(""); // clear first
      $('#profOpen #profUrl a').attr('href','').attr('href', proxy_url + opt.data.url).text(opt.data.url);
      $('#profOpen #profDiscription').text(opt.data.description);
      $('#profOpen').css('display','block');
      return false;
    });
  }

    /*------------------------------
      つぶやきフォーム表示(Fanのつぶやき用)
      --------------------------------*/
    $("#message.logined a").click(function(){
        $("#tweetForm #comment").val("");
        $('#tweetForm .status').text(" ");
        $("#tweetForm").css("display", "block");
        return false;
        });

  // Retweetフォームをクリックして表示するイベント設置関数（Player,Fan）
  function showRetweetForm(template,opt){
    $('.rt a', template).bind("click", function(){
      $('#tweetForm p.status').text(" ");
      $("#tweetForm").css("display", "block");
      $('#tweetForm #comment').val('').val('RT: @' + opt.data.screen_name + ' ' +  returnOrAddKeyword(removeTag(opt.data.post_text), officialHashTag) + ' ').focus();
      return false;
    });
  }

  // (ファン用)Retweetフォームをクリックして表示するイベント設置関数
  function showFanRetweetForm(template,opt){
    $('.rt a', template).bind("click", function(){
      $('#tweetForm p.status').text(" ");
      $("#tweetForm").css("display", "block");
      $('#tweetForm #comment').val("").val('RT: @' + opt.data.from_user + ' ' +  returnOrAddKeyword(opt.data.post_text, officialHashTag) + ' ').focus();
      return false;
    });
  }
  // (ファン用)Replyフォームをクリックして表示するイベント設置関数
  function showReplyForm(template,opt){
    $('.re a', template).bind("click", function(){
      $('#tweetForm p.status').text(" ");
      $("#tweetForm").css("display", "block");
      $('#tweetForm #comment').val("").val('@' + opt.data.from_user + ' ').focus();
      return false;
    });
  }

  // タグと改行を削除する関数
  function removeTag(str) {
    var regex_line_break = new RegExp(/\n/g);
    var line_break_removed = str.replace(regex_line_break, "");
    var inner_text = new RegExp(/>(.*?)</g);
    var line_breaked = line_break_removed.replace(inner_text, ">\n$1\n<");
    var rgexp = new RegExp(/<("[^"]*"|'[^']*'|[^'">])*>/g);
    var rtn = line_breaked.replace(rgexp, "");
    rtn = rtn.replace(/\r\n|\r|\n/g," ");
    return rtn;
  }

  // つぶやきフォーム送信イベント設置関数
  $('#eventSubmit input[type=button]').click(function() {
    var api_url = twitter_update_api;
    var comment_str = $('#comment').val();
    $('#tweetForm .status').text(" ");
    if(comment_str == ''){
        $('#tweetForm .status').text('つぶやきを入力してください').css("color", "red");
        return false;
    }
    $.post(api_url, { 'status': returnOrAddKeyword(removeTag(comment_str), officialHashTag)},
      function(data) {
        if(data.error){
            if(data.error == 1){
                $('#tweetForm .status').text('ログインしていません。').css("color", "red");
            }else{
                $('#tweetForm .status').text('送信に失敗しました。').css("color", "red");
            }
        }else{
            $("#tweetForm").css("display", "none");
        }
      }
    );
    return false;
  });

  //-----*-----*-----*------*----*
  // get initial staff timeline
  //-----*-----*-----*------*----*
  function getStaffTimeline (){
    var _cookie_name = 'staff_current_page';
    $.cookie(_cookie_name, null);
    page = 1;
    var api_url = staff_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      $.each(json.timeline, function(i, item){
        render_staff_timeline({'data':item,'index':i});
      });
    });
  };

  //-----*-----*-----*------*----*
  // Read more staff timeline
  //-----*-----*-----*------*----*
  function readMoreStaffTimeline (){
    var _cookie_name = 'staff_current_page';
    var page = parseInt($.cookie(_cookie_name));
    if(!page){
      page = 2;
    } else {
      page = page + 1;
    }
    var api_url = staff_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      if(json.next_page=='false'){
        return false;
      } else {
        $.cookie(_cookie_name, page);
      }
      $.each(json.timeline, function(i, item){
        render_staff_timeline({'data':item,'index':i,'mode':'more'});
      });
    });
  };

  function render_staff_timeline(opt){
    var _target = $('#staff');
    var template = $('<li class=" clearfix"> <div class="icon"><img src="" alt="" width="48" height="48" /></div> <div class="tweet"> <p><span class="screen_name"></span></p> <div class="time"></div> <div class="pr"><a href=""><img class="pr" src="" alt="プロフィール" title="プロフィール" width="24" height="24" /></a></div><div class="rt"><a href=""><img class="rt" src="" alt="リツイート" title="リツイート" width="24" height="24" /></a></div></div> </li>');
    $('.icon img', template).attr('src',opt.data.profile_image_url);
    $('span.screen_name', template).text(opt.data.screen_name);
    $('p', template).append(opt.data.text);
    $('.time', template).text(opt.data.created_at);
    $('.description', template).text(opt.data.description);
    $('img.rt', template).attr('src', base_url + "images/pic/btn_rt_out.jpg");
    $('img.pr', template).attr('src', base_url + "images/pic/btn_pr_out.jpg");
    showProfilePopup(template, opt);
    showRetweetForm(template, opt);
    if(opt.mode == 'more'){
      $('.timeline ul', _target).append(template);
    }else{
      if(opt.index == 0){
        $('.timeline ul', _target).text('').append(template);
      }
      $('.timeline ul', _target).append(template);
    }
  };

  //-----*-----*-----*------*----*
  // get initial fan timeline
  //-----*-----*-----*------*----*
  function getFanTimeline (){
    var _cookie_name = 'fan_current_page';
    $.cookie(_cookie_name, null);
    page = 1;
    var api_url = fan_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      $.each(json.timeline, function(i, item){
        render_fan_timeline({'data':item,'index':i});
      });
    });
  };
  //-----*-----*-----*------*----*
  // Read more fan timeline
  //-----*-----*-----*------*----*
  function readMoreFanTimeline (){
    var _cookie_name = 'fan_current_page';
    var page = parseInt($.cookie(_cookie_name));
    if(!page){
      page = 2;
    } else {
      page = page + 1;
    }
    var api_url = fan_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + '/' + Math.floor(Math.random() * 10000),{}, function(json) {
      if(json.next_page=='false'){
        return false;
      } else {
        $.cookie(_cookie_name, page);
      }
      $.each(json.timeline, function(i, item){
        render_fan_timeline({'data':item,'index':i,'mode':'more'});
      });
    });
  };

  function render_fan_timeline(opt){
    var _target = $('#fan');
    var template = $('<li class=" clearfix"> <div class="icon"><img src="" alt="" width="48" height="48" /></div> <div class="tweet"> <p><span class="screen_name"></span></p> <div class="time"></div><div class="pr"><a href="" target=""><img class="pr" src="" alt="プロフィール" title="プロフィール" width="24" height="24" /></a></div> <div class="rt"><a href=""><img class="rt" src="" alt="リツイート" title="リツイート" width="24" height="24" /></a></div> <div class="re"><a href=""><img class="rp" src="" alt="リプライ" title="リプライ" width="24" height="24" /></a></div></div></li>');
    $('.icon img', template).attr('src',opt.data.profile_image_url);
    $('span.screen_name', template).text(opt.data.from_user);
    $('p', template).append(opt.data.text);
    $('.time', template).text(opt.data.created_at);
    $('.description', template).text(opt.data.description);
    $('img.pr', template).attr('src', base_url + "images/pic/btn_pr_out.jpg");
    $('img.rt', template).attr('src', base_url + "images/pic/btn_rt_out.jpg");
    $('img.rp', template).attr('src', base_url + "images/pic/btn_rp_out.jpg");
    var profile_url = proxy_url + 'http://www.twitter.com/' + opt.data.from_user;
    $('div.pr a', template).attr('href', profile_url).attr('target', '_blank');
    showFanRetweetForm(template, opt);
    showReplyForm(template, opt);
    if(opt.mode == 'more'){
      $('.timeline ul', _target).append(template);
    }else{
      if(opt.index == 0){
        $('.timeline ul', _target).text('').append(template);
      }
      $('.timeline ul', _target).append(template);
    }
  };

//-----*-----*-----*------*----*
// get initial ticket timeline
//-----*-----*-----*------*----*
  function getTicketTimeline (){
    var _cookie_name = 'ticket_current_page';
    var api_url = ticket_api;
    $.cookie(_cookie_name, null);
    // getJSON and Render HTML
    $.getJSON(api_url + "/" + Math.floor(Math.random() * 10000),{}, function(json) {
        $.each(json.timeline, function(i, item){
          render_staff_timeline({'data':item,'index':i});
          });
        });
  };

//-----*-----*-----*------*----*
// Read more ticket timeline
//-----*-----*-----*------*----*
  function readMoreTicketTimeline (){
    var _cookie_name = 'ticket_current_page';
    var page = parseInt($.cookie(_cookie_name));
    if(!page){
      page = 2;
    } else {
      page = page + 1;
    }
    var api_url = ticket_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + "/" + Math.floor(Math.random() * 10000),{}, function(json) {
        if(json.next_page=='false'){
        return false;
        } else {
        $.cookie(_cookie_name, page);
        }
        $.each(json.timeline, function(i, item){
          render_staff_timeline({'data':item,'index':i,'mode':'more'});
          });
        });
  };

  //-----*-----*-----*------*----*
  // get initial event timeline
  //-----*-----*-----*------*----*
  function getEventTimeline (){
    var _cookie_name = 'event_current_page';
    var api_url = event_api;
    $.cookie(_cookie_name, null);
    // getJSON and Render HTML
    $.getJSON(api_url + "/" + Math.floor(Math.random() * 10000), {}, function(json) {
      $.each(json.timeline, function(i, item){
        render_staff_timeline({'data':item,'index':i});
      });
    });
  };

  //-----*-----*-----*------*----*
  // Read more event timeline
  //-----*-----*-----*------*----*
  function readMoreEventTimeline (){
    var _cookie_name = 'event_current_page';
    var page = parseInt($.cookie(_cookie_name));
    if(!page){
      page = 2;
    } else {
      page = page + 1;
    }
    var api_url = event_api + '/' + page;
    // getJSON and Render HTML
    $.getJSON(api_url + "/" + Math.floor(Math.random() * 10000), {}, function(json) {
      if(json.next_page=='false'){
        return false;
      } else {
        $.cookie(_cookie_name, page);
      }
      $.each(json.timeline, function(i, item){
        render_staff_timeline({'data':item,'index':i,'mode':'more'});
      });
    });
  };

  //-----*-----*-----*------*----*
  // Playerタイムライン上のボタン
  //-----*-----*-----*------*----*
  $('#player .confirm a').click(function(){
    removeUnreadCount('#player');
    getPlayersTimeline();
    return false;
  });
  $('#player .more a').click(function(){
    readMorePlayersTimeline();
    return false;
  });
  //-----*-----*-----*------*----*
  // スタッフタイムライン上のボタン
  //-----*-----*-----*------*----*
  // 未読を確認するボタン
  $('#staff .confirm a').click(function(){
    removeUnreadCount('#staff');
    // チケット情報表示中
    if($('#staff').hasClass('switchedToTicket')){
      getTicketTimeline();
    // イベント情報表示中
    } else if ($('#staff').hasClass('switchedToEvent')) {
      getEventTimeline();
    } else {
      getStaffTimeline();
    }
    return false;
  });

  // スタッフもっと読むボタン
  $('#staff .more a').click(function(){
    // チケット情報表示中
    if($('#staff').hasClass('switchedToTicket')){
      readMoreTicketTimeline();
    // イベント情報表示中
    } else if ($('#staff').hasClass('switchedToEvent')) {
      readMoreEventTimeline();
    } else {
      readMoreStaffTimeline();
    }
    return false;
  });

  // チケット情報ボタンをクリック
  $('#searchTicket a').click(function(){
    if($('#staff').hasClass('switchedToTicket')){
      // スタッフタイムラインに切り替え
      $('#staff').removeClass('switchedToTicket');
      $('#searchTicket img').attr('src', base_url + 'images/pic/btn_search_ticket_out.jpg')
      getStaffTimeline();
    } else{
      // チケット情報に切り替え
      $('#searchTicket img').attr('src', base_url + 'images/pic/btn_search_back.jpg')
      $('#searchEvent img').attr('src', base_url + 'images/pic/btn_search_event_out.jpg')
      $('#staff').addClass('switchedToTicket');
      $('#staff').removeClass('switchedToEvent');
      getTicketTimeline();
    }
    return false;
  });
  

  // イベント情報ボタンをクリック
  $('#searchEvent a').click(function(){
    if($('#staff').hasClass('switchedToEvent')){
      // スタッフタイムラインに切り替え
      $('#staff').removeClass('switchedToEvent');
      $('#searchEvent img').attr('src', base_url + 'images/pic/btn_search_event_out.jpg')
      getStaffTimeline();
    } else{
      // イベント情報に切り替え
      $('#searchEvent img').attr('src', base_url + 'images/pic/btn_search_back.jpg')
      $('#searchTicket img').attr('src', base_url + 'images/pic/btn_search_ticket_out.jpg')
      $('#staff').addClass('switchedToEvent');
      $('#staff').removeClass('switchedToTicket');
      getEventTimeline();
    }
    return false;
  });

  // ファンタイムライン「未読を確認」
  $('#fan .confirm a').click(function(){
    removeUnreadCount('#fan');
    getFanTimeline();
    return false;
  });
  // ファンタイムライン「もっと読む」
  $('#fan .more a').click(function(){
    readMoreFanTimeline();
    return false;
  });


  // No Ticket Info
  var open_ticket_dialog = function(){
    var _target = $("#ticket_info");
    _target.dialog({
        position: 'center',
        modal: 'true',
        title: 'チケット情報',
        buttons:{
          Cancel:function(){
            _target.dialog('close');
          }
        },
        open:function(){
          _target.text('チケット情報はありません。');
        }
    });
  }
  // No Event Info
  var open_event_dialog = function(){
    var _target = $("#event_info");
    _target.dialog({
        position: 'center',
        modal: 'true',
        title: 'イベント情報',
        buttons:{
          Cancel:function(){
            _target.dialog('close');
          }
        },
        open:function(){
          _target.text('イベント情報はありません');
        }
    });
  }

  // 現在の公開記事数をサーバーから取得する関数
  function getUnreadData(){
    var api = unread_api + '/' + Math.floor(Math.random() * 10000)
    $.getJSON(api, function(json){
      displayAllUnreadCounts(json.count);
    });
  }

  // ３つのタイムラインそれぞれに未読件数を表示させる処理
  function displayAllUnreadCounts(data){
    countUnread('#player', data.players);
    countUnread('#staff', data.staff);
    countUnread('#fan', data.fan);
  }

  // 未読件数を算出する関数
  function countUnread(elm, current_count){
    var data_area = $('.confirm', elm);
    var previous_count = parseInt(data_area.data("previous_count"));
    var current_count = parseInt(current_count);
    if(!previous_count){
      data_area.data({'previous_count':current_count});
      previous_count = current_count;
    }
    if(previous_count > current_count){
      return false;
    } else {
      var unread_count = current_count - previous_count;
    }
    if(unread_count){
      displayUnreadCount(unread_count, elm);
    }
  }
  // 未読件数を表示する関数
  function displayUnreadCount(unread_count, elm){
    var data_area = $('.confirm', elm);
    var template = $('<div class="unread"><span></span></div>');
    var contents = template.text(unread_count + '件の未読があります');
    // display_area.html(contents);
    $('div.unread',data_area).remove();
    data_area.append(contents);
  }

  // 未読件数を非表示にする関数
  function removeUnreadCount(elm){
    var data_area = $('.confirm', elm);
    data_area.data({"previous_count":0});
    $('div.unread', elm).remove();
  }

  // 引数strの文字列中にwordが含まれていればそのまま返し、
  // 含まれていなければ、末尾にwordを追加して返す関数
  function returnOrAddKeyword(str, word){
    var pattern = new RegExp(word, 'gi');
    if (str.match(pattern)){
      // console.log('matche: ' + str);
      return str;
    }
    // console.log('unmatche: ' + str);
    return str + ' ' + word;
  }
});


