var ROOT = "http://itsabluworld.com/wp-content/themes/bluworld/";
var izea = function() {
  var update_tweets = function(text) {
    $("#recent_tweets").removeClass("loading").html(text.join(''));
  }
  return {
    init: function() {
      this.resize_content();
      $(window).resize(this.resize_content);
    },
    resize_content: function() {
      var height = $("html").height() - $("#header").height();
      $("#content").css("min-height", height);
    },
    update_recent_tweets: function(search_response) {
      for(var i=0, length=search_response.results.length, text=[]; i<length; i++) {
        var result = search_response.results[i];
        text.push("<li"+(i==0 ? ' class=\"first\"' : '')+"><a href='http://twitter.com/"+result.from_user+"' target='_blank'><img src='"+result.profile_image_url+"' width='48' height='48' alt='Avatar for "+result.from_user+"'/></a> <div><blockquote>"+result.text+"</blockquote> <a href='http://twitter.com/"+result.from_user+"/status/"+result.id+"' target='_blank' rel='nofollow'>View</a></div></li>");
      }
      update_tweets(text);
    },
    ie6: function() {
      if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
  	    var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
        if (ieversion<=6) { return true; }
      }
      return false;
    }
  }
}();


$(function(){ izea.init(); });


var app = {
  
  video: {
  
    list: [],
    list_by_views: [],
    list_by_discussed: [],
    total: 0,
    cur_page: 0,
    per_page: 16,
    total_pages: 0,
    which_selected: "latest",
    shifted: 0,
  
    api: {
      index: 1,
      calls: 0,
      max_results: 50, // should be youtubes max of 50 unless testing
      account: "BluFrogEnergy"
    },
  
    get_videos: function(){
      app.video.api.calls = app.video.api.calls + 1;
      var s = document.createElement("script");
      s.src = this.get_videos_url();
      document.getElementsByTagName("head")[0].appendChild(s);
    },
  
    get_videos_url: function(){
      return "http://gdata.youtube.com/feeds/users/" + app.video.api.account + "/uploads" + 
             "?alt=json-in-script" + 
             "&format=5" + 
             "&max-results=" + app.video.api.max_results + 
             "&start-index=" + app.video.api.index + 
             "&callback=app.video.retrieve" + 
             "&orderby=published";
    },
  
    retrieve: function(data){
      if(!data.feed.entry){ this.set_up_videos(); return; } // No results came back, so proceed to next step
      var data = data.feed.entry;
      app.video.shifted = 0;
      for(i=0,len=data.length;i<len;i++){
        var data_row = data[i]
        var vid = this.format_vid_to_json(data_row)
        this.list.push(vid);
        
        var views = ("yt$statistics" in data_row) ? data_row.yt$statistics.viewCount : 0
        views = (views == "0") ? 0 : parseInt(views)
        this.add_to_list_by_views_array(views, vid);
        
        var discussions = ("gd$comments" in data_row) ? data_row.gd$comments.gd$feedLink.countHint : 0
        discussions = (discussions == "0") ? 0 : parseInt(discussions)
        this.add_to_list_by_discussed_array(discussions, vid);
      }
      if(data.length == app.video.api.max_results){ // There MAY be more videos...
        app.video.api.index = (app.video.api.max_results * app.video.api.calls) + 1
        this.get_videos()
      }else{
        this.set_up_videos()
      }
    },
  
    add_to_list_by_views_array: function(count, vid){
      if(count == 0){
        this.list_by_views.unshift(vid)
        app.video.shifted++;
        return
      }
      count = count + app.video.shifted
      if(this.list_by_views[count]){
        var a = this.list_by_views.splice(count, 0, vid)
        app.video.shifted++;
      }else{
        this.list_by_views[count] = vid
      }
    },
  
    add_to_list_by_discussed_array: function(count, vid){
      if(count == 0){
        this.list_by_discussed.unshift(vid)
        app.video.shifted++;
        return
      }
      count = count + app.video.shifted
      if(this.list_by_discussed[count]){
        var a = this.list_by_discussed.splice(count, 0, vid)
        app.video.shifted++;
      }else{
        this.list_by_discussed[count] = vid
      }
    },
  
    format_vid_to_json: function(d){
      app.video.total = app.video.total + 1
      return {
        "title":          d.title.$t,
        "published_on":   d.published.$t,
        "description":    d.media$group.media$description.$t,
        "view_count":     ("yt$statistics" in d) ? d.yt$statistics.viewCount : 0,
        "average_rating": ("gd$rating" in d) ? d.gd$rating.average : 0,
        "duration":       d.media$group.yt$duration.seconds,
        "link_to_video":  d.media$group.media$player[0].url,
        "thumbnail":      d.media$group.media$thumbnail[0].url
      }
    },
  
    clean_video_arrays: function(arr){
      var newArray = new Array();
      for(var i = 0; i<arr.length; i++){
          if(arr[i]) newArray.push(arr[i]);
      }
      return newArray;
    },
  
    set_up_pagination: function(){
      var pp = app.video.per_page;
      var tt = app.video.total;
      if(tt > pp){
        app.video.total_pages = Math.ceil(tt/pp);
        var page_links = "";
        for(i=0;i<app.video.total_pages;i++){
          page_links += "<a class='vid_pagination_num_" + ( (i==0) ? "on" : "off" ) + "' id='vid_pagination_page_" + i + "' href='#' onclick='app.video.jump_to(" + i + ");return false;'>" + (i+1) + "</a>";
        }
        document.getElementById("video_pages").innerHTML = page_links;
        document.getElementById("videos_footer").style.display = "block";
      }
    },
  
    set_up_videos: function(){
      // All vids received, clean up some things...
      this.list_by_views = this.clean_video_arrays(this.list_by_views)
      this.list_by_views = this.list_by_views.reverse();
      this.list_by_discussed = this.clean_video_arrays(this.list_by_discussed)
      this.list_by_discussed = this.list_by_discussed.reverse();
      this.set_up_pagination()
      document.getElementById("videos").innerHTML = "";
      // now draw...
      this.draw_video_header();
      this.draw_videos();
    },
  
    draw_video_header: function(){
      var div = document.getElementById("videos_total")
      div.innerHTML = this.list.length + " videos"
      document.getElementById("videos_header").style.display = "block"
    },
  
    draw_videos: function(){
      var vid_list = this.determine_list_to_draw_from();
      var start = app.video.cur_page * app.video.per_page;
      var end = start + app.video.per_page;
      for(i=start;i<end;i++){
        var div = document.createElement("div");
        div.className = "video";
        div.innerHTML = this.video_html(vid_list[i]);
        document.getElementById("videos").appendChild(div);
      }
    
    },
  
    determine_list_to_draw_from: function(){
      if(this.which_selected == "latest") return this.list;
      if(this.which_selected == "views") return this.list_by_views;
      if(this.which_selected == "discussed") return this.list_by_discussed;
    },
  
    video_html: function(vid){
      if(!vid) return ""
      var html = new Array();
      html.push("<div class='video_thumbnail_container'>");
      html.push("  <div class='video_thumbnail'><img src='" + vid.thumbnail + "' width='126' height='86'></div>");
      html.push("  <div class='video_thumbnail'><a href='" + vid.link_to_video + "' target='_blank'><img src='" + ROOT + "/images/video/border.png'></a></div>");
      html.push("  <div class='video_plus_icon'><a href='" + vid.link_to_video + "' target='_blank'><img src='" + ROOT + "/images/video/plus_icon.gif'></a></div>");
      html.push("  <div class='video_duration'>");
      html.push("    <div style='float:right;'><img src='"+ROOT+"/images/video/duration_cap.gif' width='1' height='12'></div>");
      html.push("    <div class='video_dur_time'>" + this.format_duration(vid.duration) + "</div>");
      html.push("    <div style='float:right;'><img src='"+ROOT+"/images/video/duration_cap.gif' width='1' height='12'></div>");
      html.push("    <br style='clear:both;height:0;'/>");
      html.push("  </div>");
      html.push("</div>");
      html.push("<div class='video_title'><a href='" + vid.link_to_video + "' target='_blank'>" + this.clean_title(vid.title) + "</a></div>");
      html.push("<div class='video_other'>" + app.dates.to_ago(vid.published_on) + "</div>");
      html.push("<div class='video_other'>" + vid.view_count + " views</div>");
      html.push("<div class='view_rating'>" + app.video.stars(vid.average_rating) + "</div>");
      return html.join("");
    },
  
    clean_title: function(str){
      if(str.indexOf("Blu Frog ") == 0){
        str = str.substring(9, str.length)
      }
      str = app.tools.truncate(str, 17)
      return str
    },
  
    format_duration: function(dur){
      if(dur < 60){
        dur = "0:" + dur;
      }else if(dur == 60){
        dur = "1:00";
      }else{
        mins = Math.floor(dur/60);
        secs = (dur % 60) + "";
        if(secs.length == 1) secs = "0" + secs;
        dur = mins + ":" + secs;
      }
      return dur
    },
  
    stars: function(rating){
      var html = new Array();
      for(s=0;s<5;s++){
        star_type = (s < rating) ? "on" : "off";
        star_style = (izea.ie6()) ? " style='padding-bottom:4px;'" : "";
        html[s] = "<img class='rating_star'" + star_style + " src='" + ROOT + "/images/video/star_" + star_type + ".jpg'>";
      }
      return html.join("")
    },
  
    go_to_video: function(url){
      document.location.href = url
    },
  
    switch_to: function(which){
      document.getElementById("videos").innerHTML = "";
      document.getElementById("sort_by_" + app.video.which_selected).className = "video_sort_link_on";
      document.getElementById("sort_by_" + which).className = "video_sort_link_off";
      app.video.which_selected = which;
      this.jump_to(0);
    },
  
    jump_to: function(page){
      if(page < 0) return;
      if(page >= app.video.total_pages && app.video.total_pages > 0) return;
      if(app.video.total_pages > 0){
        if(page == 0){
          document.getElementById("video_previous").className = "vid_pagination_off";
        }else{
          document.getElementById("video_previous").className = "vid_pagination_on";
        }
        if(page == app.video.total_pages - 1){
          document.getElementById("video_next").className = "vid_pagination_off";
        }else{
          document.getElementById("video_next").className = "vid_pagination_on";
        }
        document.getElementById("vid_pagination_page_" + app.video.cur_page).className = "vid_pagination_num_off";
        document.getElementById("vid_pagination_page_" + page).className = "vid_pagination_num_on";
      }
      document.getElementById("videos").innerHTML = "";
      app.video.cur_page = page;
      this.draw_videos();
    }
  
  },

  tools: {
  
    truncate: function(text, len){
      if(text.length > len){
        text = text.substring(0, len) + "...";
      }
      return text;
    }
  
  },

  dates: {
  
    to_ago: function(d){
      days = this.days_ago(d)
      if(days <= 1) return "Today"
      if(days < 7) return days + " days ago"
      if(days >= 7){
        return Math.floor(days / 7) + " weeks ago"
      }
    },
  
    clean_date: function(d){
      if(typeof(d) == "string"){
        if(d.substring(d.length-1, d.length) == "Z"){
          d = d.substring(0, d.length-1)
        }
        if(d.indexOf("T") > -1){
          d = d.split("T")[0]
          d = d.split("-")
          d = d[1] + "/" + d[2] + "/" + d[0]
        }
        d = Date.parse(d)
      }
      return d
    },
  
    days_ago: function(d){
      var ONE_DAY     = 1000 * 60 * 60 * 24
      var date1_ms    = new Date()
      date1_ms        = date1_ms.getTime()
      var date2_ms    = this.clean_date(d)
      var diff_ms     = date1_ms - date2_ms
      diff_ms         = diff_ms < 0 ? 0 : diff_ms
      return Math.round(diff_ms/ONE_DAY)  
    }
  
  }
}

