/**************** ビデオリスト ****************/

var currentKey;
var currentValue;
var artists;
var dragging = false;

var videoPage = 0;
var videoTotal = 0;
var videoTotalPage = 0;
var videoLimit = 12;

var genreLabelOriginal = $("#genre_label").html();
var areaLabelOriginal = $("#area_label").html();
var keywordLabelOriginal = $("#keyword_label").html();
var firstLoad = true;

currentVideoIdx = -1;

Array.prototype.shuffle = function() {
  var i = this.length;
  while(i){
    var j = Math.floor(Math.random()*i);
    var t = this[--i];
    this[i] = this[j];
    this[j] = t;
  }
  return this;
}

  function onDragStart(event, ui) {
	// ドラッグ時に再生しない
    dragging = true;
  }

  function onDragStop(event, ui) {
    setTimeout("dragging = false", 500);
    // ゼロより左、最終ページより右にドラッグさせない。
	// 吸着
    fitToLimit();
    // ページ数の調整
    refreshPageNumber();
    refreshPageIndication();
    // 次ページの遅延ロード
    invokeDelayedLoad();
  }

  function fitToLimit() {
    var x = $("#videoList").css("left");
    x = x.substr(0, x.lastIndexOf("px"));
    var maxLeft = (getTotalWidth() - (124 + 12) * 3) * -1;
    if (x > 0) {
      $("#videoList").animate({ left:"0px" }, "fast");
    } else if (x < maxLeft) {
      $("#videoList").animate({ left:maxLeft + "px" }, "fast");
    } else {
      var index = Math.ceil(x / (124 + 12)) * -1;
      var rest = (index + 1) * (124 + 12) - (x * -1); // あと何ピクセルで次のマスに到達するか
      if (rest > (124 + 12) / 2) {
        $("#videoList").animate({ left:(index * (124 + 12) * -1) + "px" }, "slow");
      } else {
        $("#videoList").animate({ left:((index + 1) * (124 + 12) * -1) + "px" }, "slow");
      }
    }
  }

  function invokeDelayedLoad() {
    var nextPageLast = (videoPage + 2) * 12 - 1;
    var prevPageFirst = (videoPage - 1) * 12;
    for (var i=nextPageLast; i>=prevPageFirst; i--) {
      delayedLoad(i);
    }
  }

  function load_artists_callback(data) {
    artists = eval(data);
    artists.shuffle();
    var from = videoLimit * videoPage;
    var to = from + videoLimit;

    replaceList();
    videoTotal = artists.length
    videoTotalPage = Math.ceil(videoTotal / videoLimit)
    refreshPageIndication();

    $("#videoList").draggable({
      axis: "x",
      cursor: "move"
    });
    $("#videoList").bind("dragstop", onDragStop);
    $("#videoList").bind("dragstart", onDragStart);

    if (artists.length > 12) {
      $("#videoList").draggable('enable');
    } else {
      $("#videoList").draggable('disable');
    }
    $("#videoList").animate({ left:"0px" });

    // ロード後ひとつめのビデオを再生
    if (firstLoad) {
        setTimeout(function() {
           if($("#player").is(":hidden")) playVideo(0);
        }, 7000);
        firstLoad = false;
    }
  }

  function load_artists(key, value, page) {
    if (key == null && value == null && page == null) {
      key = "permanent_key";
      value = "artist";
      page = 0;
    }
    currentKey = key;
    currentValue = value;
    videoPage = page;
    var arg = new Date().getTime();
    $.get("/pc/json/genre/" + key + "_" + value + ".json?" + arg, load_artists_callback);
    resetSelectLabels(key, value);
  }

  function resetSelectLabels(key, value) {
    $("#genre_label").html(genreLabelOriginal);
    $("#area_label").html(areaLabelOriginal);
    $("#keyword_label").html(keywordLabelOriginal);
    var labelNode = null;
    var label = null;
    if (key == "genre") {
      labelNode = $("#genre_label");
      label = genres[value];
    } else if (key == "residence_area") {
      labelNode = $("#area_label");
      label = areas[value];
    } else if(key != "permanent_key") {
      labelNode = $("#keyword_label");
      if (key == "type_of_band") {
        label = typeOfBands[value];
      } else if (key == "feature") {
        label = features[value];
      } else if (key == "generations") {
        label = generations[value];
      }
    }
    $(".genre_list").slideUp("fast");
    $(".area_list").slideUp("fast");
    $(".keyword_list").slideUp("fast");
    if (labelNode != null) {
      labelNode.html(digest(label));
    }
  }

  function digest(str) {
    if (countByte(str) < 18) {
      return str;
    }
    return substrByBytes(str, 14) + "..";
  }

  function countByte(str) {
    if (str == null) {
      return 0;
    }
    var count = 0;
    for(var i = 0; i < str.length; i++) {
      if (escape(str.charAt(i)).length < 4) {
        count++;
      } else {
        count += 2;
      }
    }
    return count;
  }

  function substrByBytes(str, bytes) {
    var count = 0;
    var result = "";
    for(var i = 0; i < str.length; i++) {
      result += str.charAt(i);
      if (escape(str.charAt(i)).length < 4) {
        count++;
      } else {
        count += 2;
      }
      if (count > bytes) {
        return result;
      }
    }
    return result;
  }

  function replaceList() {
    var result = "";
    for (var i=0; i<artists.length; i++) {
      if (i % 12 == 0) {
        result += '<div class="thumbnailColumn">';
      }
      result += createNode(i);
      if (i % 12 == 11 || i >=  artists.length - 1) {
        result += '</div>';
      }
    }
    $(".videoListMask .thumbnail").css("width", getTotalWidth() + "px");
    $("#videoList").html(result);
    for (var i=0; i<24; i++) {
      delayedLoad(i);
    }
  }

  function createNode(idx) {
    var artist = artists[idx];
    if (artist == null) {
      return "";
    }
    aid = artist["artist_id"];
    videoURL = artist["video_url"];
    videoId = squeezeVideoId(videoURL);
    thumbnailURL = "http://img.youtube.com/vi/" + videoId + "/1.jpg";
    result = '<p>';
    result += '<span id="videoThumbnail_' + idx + '" idx="' + idx + '" url="' + thumbnailURL + '" loaded="false">';
    result += '<img src="/pc/ss09/images/loading_thumbnail.gif" id="loading_' + idx + '" class="loading" />';
    result += '</span>';
    result += '</p>';
    return result;
  }
  
  function squeezeVideoId(url) {
    match = url.match(/\?v=([-_\+a-zA-Z0-9]+)&?.*$/);
    return RegExp.$1;
  }

  function delayedLoad(idx) {
    var node = $("#videoThumbnail_" + idx);
    if (node == null || node.attr("loaded") != "false") {
      return;
    }
    var url = node.attr("url");
    var html = "";
    //var html = '<a href="javascript:void(0);" onclick="playVideo(' + idx + ')" style="background-image:url(\'' + url + '\')"></a>';
    html += '<a id="indicator_' + idx + '" href="javascript:void(0);" onclick="playVideo(' + idx + ')"></a>';
    html += '<div class="thumbnailImage" style="background-image:url(\'' + url + '\')"></div>';
    node.html(html);
    node.attr("loaded", "true");
  }

  function nextVideoPage() {
    if (videoPage >= videoTotalPage - 1) {
      return;
    }
    videoPage ++;
    refreshList();
  }

  function prevVideoPage() {
    if (0 >= videoPage) {
      return;
    }
    videoPage --;
    refreshList();
  }

  function refreshList() {
    var x = ((124 + 12) * 3) * videoPage * -1;
    $("#videoList").animate({ left:x+"px" });
    refreshPageIndication();
    invokeDelayedLoad();
  }

  function refreshPageNumber() {
    // videoPage算出
    var x = $("#videoList").css("left");
    x = x.substr(0, x.lastIndexOf("px"));
    if (x > 0) {
      x = 0;
    }
    var maxLeft = (getTotalWidth() - (124 + 12) * 3) * -1;
    if (x < maxLeft) {
      x = parseInt(maxLeft);
    }
    videoPage = Math.floor(x / ((124 + 12) * 3 * -1));
  }

  function refreshPageNumberByIdx() {
    videoPage = Math.floor(currentVideoIdx / 12);
  }

  function refreshPageIndication() {
    $("#totalVideoPage").html(videoTotalPage);
    $("#currentVideoPage").html(videoPage + 1);
  }

  function getTotalWidth() {
    return Math.ceil(artists.length / 12) * ((124 + 12) * 3);
  }
 
 function videoTitledigest(str) {
    if (countByte(str) < 36) {
      return str;
    }
    return substrByBytes(str, 35) + "..";
  }
  
   function videoArtistNamedigest(str) {
    if (countByte(str) < 23) {
      return str;
    }
    return substrByBytes(str, 22) + "..";
  }
  function playVideo(idx) {
   

    if (dragging) {
      return;
    }
    toggleThumbnail(idx);
    currentVideoIdx = idx;
    artist = artists[idx];
    //alert(artist);
    videoId = squeezeVideoId(artist["video_url"]);
    result = '<object width="396" height="238">';
    result += '<param name="movie" value="http://www.youtube.com/v/' + videoId + '&hl=ja&fs=1&rel=0&autoplay=1"></param>';
    result += '<param name="allowFullScreen" value="false"></param>';
    result += '<param name="allowscriptaccess" value="always"></param>';
    result += '<embed src="http://www.youtube.com/v/' + videoId + '&hl=ja&fs=1&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="396" height="238"></embed>';
    result += '</object>';
    $("#screen").html(result);
    $("#player").css("display", "block").draggable({cursor: "move", handle: "div.handle"}).css("z-index","1500");
    $(".player_background").css("display", "block");
    $(".screen").css("display", "block");
    $("#videoTitle").html('"' + videoTitledigest(artist["video_title"]) + '"');
    $("#videoArtistName").html('<a href="/pc/artist/' + artist["artist_id"] + '.html"><span class="voteBtn"><span class="arrow"></span>' + videoArtistNamedigest(artist["name"]) + '</span></a>');
  }

  function toggleThumbnail(idx) {
    var activated = $("#indicator_" + currentVideoIdx);
    activated.removeClass("active");

    var activate =  $("#indicator_" + idx);
    activate.addClass("active");
  }

  function closeVideo() {
    $("#screen").html(null);
    $("#videoTitle").html(null);
    $("#videoArtistName").html(null);
    $(".screen").css("display", "none");
    $(".player_background").css("display", "none");
    $("#player").css("display", "none");
  }

  function nextVideo() {
    playVideo(currentVideoIdx + 1);
    refreshPageNumberByIdx();
    refreshList();
  }

  function prevVideo() {
    playVideo(currentVideoIdx - 1);
    refreshPageNumberByIdx();
    refreshList();
  }


  // 各種ラベル用マスタ

  var genres = new Array();
  genres[1] = "ポピュラー";
  genres[2] = "ロック";
  genres[3] = "パンク";
  genres[4] = "スカ / コア";
  genres[5] = "ヒップホップ";
  genres[6] = "レゲエ";
  genres[7] = "ソウル / R&B";
  genres[8] = "テクノ / エレクトロニカ";
  genres[9] = "ヴィジュアル";
  genres[10] = "ダンス";
  genres[11] = "ブルース / カントリー";
  genres[12] = "プログレ";
  genres[13] = "ラテンミュージック";
  genres[14] = "ユーロポップ";
  genres[15] = "ジャズ / ニュージャズ";
  genres[16] = "ワールドミュージック";
  genres[17] = "ヒーリング / ニューエイジ";
  genres[18] = "フォーク / ニューミュージック";
  genres[19] = "クラシック / 現代音楽";
  genres[20] = "邦楽 / 雅楽 / 伝統音楽";
  genres[21] = "その他";

  var areas = new Array();
  areas[1] = "北海道";
  areas[2] = "青森県";
  areas[3] = "岩手県";
  areas[4] = "宮城県";
  areas[5] = "秋田県";
  areas[6] = "山形県";
  areas[7] = "福島県";
  areas[8] = "茨城県";
  areas[9] = "栃木県";
  areas[10] = "群馬県";
  areas[11] = "埼玉県";
  areas[12] = "千葉県";
  areas[13] = "東京都";
  areas[14] = "神奈川県";
  areas[15] = "新潟県";
  areas[16] = "富山県";
  areas[17] = "石川県";
  areas[18] = "福井県";
  areas[19] = "山梨県";
  areas[20] = "長野県";
  areas[21] = "岐阜県";
  areas[22] = "静岡県";
  areas[23] = "愛知県";
  areas[24] = "三重県";
  areas[25] = "滋賀県";
  areas[26] = "京都府";
  areas[27] = "大阪府";
  areas[28] = "兵庫県";
  areas[29] = "奈良県";
  areas[30] = "和歌山県";
  areas[31] = "鳥取県";
  areas[32] = "島根県";
  areas[33] = "岡山県";
  areas[34] = "広島県";
  areas[35] = "山口県";
  areas[36] = "徳島県";
  areas[37] = "香川県";
  areas[38] = "愛媛県";
  areas[39] = "高知県";
  areas[40] = "福岡県";
  areas[41] = "佐賀県";
  areas[42] = "長崎県";
  areas[43] = "熊本県";
  areas[44] = "大分県";
  areas[45] = "宮崎県";
  areas[46] = "鹿児島県";
  areas[47] = "沖縄県";

  var generations = new Array();
  generations[30001] = "10代中心";
  generations[30002] = "20代中心";
  generations[30003] = "30代中心";
  generations[30004] = "40代中心";
  generations[30005] = "50代中心";
  generations[30006] = "ごちゃ混ぜ";

  var typeOfBands = new Array();
  typeOfBands[10001] = "ソロ";
  typeOfBands[10002] = "デュオ";
  typeOfBands[10003] = "3ピース";
  typeOfBands[10004] = "4〜6人構成";
  typeOfBands[10005] = "7人以上";

  var features = new Array();
  features[20001] = "楽器がユニーク";
  features[20002] = "管楽器がいます";
  features[20003] = "ツインボーカル";
  features[20004] = "女性ボーカル";
  features[20005] = "男性ボーカル";
  features[20006] = "衣装に特徴";
  features[20007] = "インスト中心";
  features[20008] = "家族・親戚で構成";
  features[20009] = "ヴィジュアル系";
  features[20010] = "イケメン";
  features[20011] = "ガールズバンド";
  features[20012] = "超絶技巧";
  features[20013] = "萌え";



/**************** ライブハウス推薦 ****************/

  var livehouses;
  var livehousePage = 0;
  var livehouseTotalPage = 0;
  var currentLivehouseArea = null;

  function load_livehouses(key) {
    if (key == null) {
      key = "tokyo";
    }
    currentLivehouseArea = key;
    livehousePage = 0;
    livehouseTotalPage = 0;
    $.get("/pc/livehouse/" + key + ".json", load_livehouses_callback);
  }

  function load_livehouses_callback(data) {
    var livehouses = eval(data);
    livehouses.shuffle();
    var html = "";
    $(".livehouse_list").css("width", getLivehouseTotalWidth(livehouses.length) + "px");
    livehouseTotalPage = Math.ceil(livehouses.length / 10);
    for (var i=0; i<livehouses.length; i++) {
      if (i % 10 == 0) {
        html += '<div class="livehouse_list_column">';
      }
      html += create_livehouse_node(livehouses[i], i);
      if (i % 10 == 9) {
        html += '</div>';
      }
    }
    $(".livehouse_list").html(html);
    $(".livehouse_list").animate({ left:"0px" }, "fast");
    refreshLivehousePageIndication();
    activateLivehouseTabs();
    setThumbnailMargin();
    //setFinalThumbnailMargin();
  }

  function create_livehouse_node(livehouse, idx) {
    var result = "";
    result += '<div class="livehouse_data">';
    result += '<a href="/pc/artist/' + livehouse["artist_id"] + '.html#livehouse_recommendation">';
    result += '<div class="thumbnail">';
    if (livehouse["image"] != null) {
      result += '<img src="' + livehouse["image"] + '" class="livehouseThumbnail"/>'
    }else{
      result += '<img src="/pc/ss09/images/na.gif" class="livehouseThumbnail"/>'
    }
    result += '</div>';
    result += '</a>';
    result += '<p>';
    result += '<a href="/pc/artist/' + livehouse["artist_id"] + '.html#livehouse_recommendation">' + livehouse["name"] + '</a>';
    result += '</p>';
    result += '</div>';
    return result;
  }

  function getLivehouseTotalWidth(length) {
    return Math.ceil(length / 10) * 700;
  }

  function nextLivehousePage() {
    if (livehousePage >= livehouseTotalPage - 1) {
      return;
    }
    livehousePage ++;
    var pos = getLivehousePos();
    $(".livehouse_list").animate({ left:pos+"px" });
    refreshLivehousePageIndication(); 
  }

  function prevLivehousePage() {
    if (livehousePage <= 0) {
      return;
    }
    livehousePage --;
    var pos = getLivehousePos();
    $(".livehouse_list").animate({ left:pos+"px" }, "fast");
    refreshLivehousePageIndication();
  }

  function getLivehousePos() {
    return 700 * livehousePage * -1;
  }

  function refreshLivehousePageIndication() {
    $(".livehousePage").html(livehousePage + 1);
    $(".livehouseTotalPage").html(livehouseTotalPage);
  }

  function setThumbnailMargin() {
    var thumbs = $(".livehouseThumbnail");
    for (var i=0; i<thumbs.length; i++) {
      thumbs[i].onload = function() {
        var height = this.height;
        if (height <= 96) {
          this.style.marginTop = (120 - height) / 2 + "px";
        }
      }
    }
  }

  function activateLivehouseTabs() {
    var tabs = $(".area_tab");
    for (var i=0; i<tabs.length; i++) {
      if (tabs[i].id == "area_tab_" + currentLivehouseArea) {
        $("#" + tabs[i].id).addClass("active");
      } else {
        $("#" + tabs[i].id).removeClass("active");
      }
    }
  }
  
    function setMargin() {
    var thumbs = $(".finalThumbnail");
    for (var i=0; i<thumbs.length; i++) {

    	thumbs[i].onload = function() {
    		alert("loaded");
    	};
    	}
    /*
      thumbs[i].onload = function() {
      alert("set height");
        var height = this.height;
        if (height <= 96) {
          this.style.marginTop = (96 - height) / 2 + "px";
        }
      }
    }
    */
  }


  /**************** ビデオリスト ****************/

  $(function(){  
    
    // Png Fix
    $(".player_background").pngfix();
    
    // Fet list
    $("ul#accordion .sub").hide();
    $("ul#accordion li.heading").click(function () {
      index = $("ul#accordion li.heading").index(this);
      $("ul.sub").eq(index).slideToggle("slow",function(){
        if ($(this).is(":hidden"))
          $("ul#accordion li.heading span").eq(index).css("background-position","-681px -50px");
        else
          $("ul#accordion li.heading span").eq(index).css("background-position","-692px -50px");
      });
    });
    
    // youtube filter
    $("ul.filter li.list_label").click(function (evt) {
      $.isCancelActive = false;
      var index = $("ul.filter li.list_label").index(this);
      var i = 0;
      $("ul.list").each(function() {
        if (i == index) {
          $(this).slideToggle("fast", function(){
            if ($(this).is(":hidden")){
              $.isCancelActive = false;
              resetLabelActive(index);
            } else {
              $.isCancelActive = true;
              $("ul.filter li.list_label p a").eq(index).addClass("active");
            }
          });

        } else {
          $(this).slideUp("fast");
          $("ul.filter li.list_label p a").eq(i).removeClass("active");
        }
        i++;
      });
    });

    $("body").click(function() {
      if ($.isCancelActive) {
        var idx = 0;
        $("ul.list").each(function() {
          $(this).slideUp("fast");
          resetLabelActive(idx);
          idx ++;
        })
        $.isCancelActive = false;
      }
    });

    function resetLabelActive(idx) {
      var labelNode = $("ul.filter li.list_label p a").eq(idx);
      var originalLabel = $(labelNode).children("span:first-child").attr("label");
      var currentLabel = $(labelNode).children("span:first-child").html();
      if (originalLabel == currentLabel) {
        labelNode.removeClass("active");
      } else {
        labelNode.addClass("active");
      }
    }

  });


  /**************** 寺岡呼人コメントの開閉 ****************/

$(".comment_toggle a").click(function () {
        $("#comment_more").slideToggle(300,function(){
       if ($(this).is(":hidden")) {
            $(".comment_toggle .arrow").css("background-position","-705px -50px");
            $(".comment_toggle_name").html("続きを読む");
          } else {
            $(".comment_toggle  .arrow").css("background-position","-654px -50px");
             $(".comment_toggle_name").html("閉じる");
          }
          });
      });
