var VideoControl = VideoControl || {};
VideoControl = (function(){
  
  var $album_id = 1532796; // The current album
  var $container_id = "video_container"; // Id of the video container element
  var $per_page = 20;      // Videos per page
  
  var page_num = 1;      // The current album page
  var video_player_id = 'vc-player'; // The container for videos to play in
  
  var $container; // Set during initialize, used to reference video container directly

  config = {
  	user_login_url : "http://www.goallpower.com/wp-content/themes/n/login.post.php",
  	user_videos_url : "http://www.goallpower.com/wp-content/themes/n/videos.php",
 	album_url : "http://www.goallpower.com/wp-content/themes/n/album.php" }
  
  var Page = (function(){
    var video_storage = ['blah']; // Used to store videos

		return {
		  
		  all : function() {
  	    return video_storage;
  	  },

  	  first : function() {
  	    return video_storage[0];
  	  },

  	  last : function() {
  	    return video_storage[(video_storage.length -1)];
  	  },

      push : function(video) {
  			video_storage.push(video);
  			return video_storage;
  		},
  		
  		reset : function() {
  		  video_storage = [];
  		}

		};

  })();
  
  var User = function() {
		var played_video_storage = [];
		this.played_videos = function () {
      return played_video_storage;
		};
		this.unplayed_videos = function() {
		  var played_videos = this.played_videos();
			var video_ids = $.map(Page.all(), function(element, index) {
				return element.id;
			});
			var unplayed_videos = $.grep(video_ids, function(element, index) {
				return $.inArray(element, played_videos) == -1;
			});
			return unplayed_videos;			
		};
		this.unlocked_videos = function() {
			var played_videos = new Array();
			$.each(this.played_videos(), function(index, element) {
				played_videos.push(element);
			});
			played_videos.push(this.next_unlocked_video());
			return played_videos;
		};
		this.next_unlocked_video = function(level) {
			return this.unplayed_videos()[0];
		};
		this.is_playing_video = function(video, callback) {
			this.add_played_video(video);
	    $.post(config.user_videos_url, {vId: video}, callback);
			return this.played_videos;
		};
		this.add_played_video = function(video) {
			played_video_storage.push(video);
			return this.played_videos();
		};
		this.has_played = function(video_id) {
		  return ($.inArray(video_id, this.played_videos()) != -1);
		};
	};

	var user = new User;

  function video_control() {
    $.getJSON(config.user_videos_url, function(data){
      $.each(data.videos, function(i, video){
        user.add_played_video(video.videoid);
      });
      load();
    });
  }
  
  function load(i) {
    if (!i) i = 0;
    var page = page_num = page_num+i;

    $container.addClass('loading');
    $.getJSON(config.album_url+'?id='+$album_id+'&page='+page+'&per_page='+$per_page, function(data) {
      if (data.stat == "ok") {
        
        Page.reset();
        
        var template = "<li> \
    	    <a href=\"#"+video_player_id+"\" id={id}><img src='{thumbnail}' title='{title} {id}' alt='{title}'></a> \
    	  </li>";
        
        var list_content = '';
        $.each(data.videos.video, function(index, video) {
          video.thumbnail = video.thumbnails.thumbnail[1]._content;
          Page.push(video);

          list_item = $.nano(template, video);
          
          list_content += list_item;
        });
        
        $container.hide().
          find(".videos").html($("<ul id=\"album-"+$album_id+"-"+page_num+"\"></ul>").append(list_content)).end().
          fadeIn().end();

        $container.find("ul li a").live('click', play);

        $container.find("ul li a").each(function(){
          $(this).append('<div class="play">&nbsp;</div>');
          if (user.has_played(this.id)) {
            $(this).addClass('played');
          }
          if (this.id == user.next_unlocked_video()) {
            $(this).addClass('unlocked');
          }
        });
        
        // Handle previous/next
        if ( (data.videos.page*data.videos.perpage) < data.videos.total ) {
          $container.find("a.next").addClass("enabled");
        } else {
          $container.find("a.next").removeClass("enabled");
          $container.find("a.next").hide();
        }
        
        if ($container.find("ul li a.played").length == $container.find("ul li a").length) {
          $container.find("a.next.enabled").show();
        } else { $container.find("a.next").hide(); }

        if ( data.videos.page > 1 ) $container.find("a.previous").show();
        else $container.find("a.previous").hide();
        
        $container.removeClass('loading');
      }
    });
  }
  
  function play() {
    var video_id = this.id;
    
    if ( $.inArray(video_id, user.unlocked_videos()) != -1 ) {
    
      $('#'+video_player_id).parents('.video-panel').show();
      user.is_playing_video(video_id);
      $("#"+video_id).addClass('played');
    
      $('#'+video_player_id).html('<iframe src="http://player.vimeo.com/video/'+video_id+'?title=0&amp;byline=0&amp;portrait=0&amp;color=ffffff" width="585" height="301" frameborder="0"></iframe>');
      
      $('div#grab_area').hide();
      $('#'+video_player_id).show();
      
      $container.find("ul li a").removeClass('next');
      $("a#" + user.next_unlocked_video()).addClass('unlocked');
      
      // Handle next button
      if ($container.find("ul li a.played").length == $container.find("ul li a").length) {
        $container.find("a.next.enabled").fadeIn();
      }

    }
    else {
      alert('You should finish watching the previous video(s)');
      return false;
    }
    return true;
  }
	
	return {
		initialize: function(album_id, container_id, per_page) {
		  if (album_id) $album_id = album_id; // Set the album_id if passed. Default is used otherwise
		  if (container_id) $container_id = container_id;
		  if (per_page) $per_page = per_page;
		  
		  $container = $("#" + $container_id);
      
		  $.getJSON(config.user_login_url, function(response) {
        if (response.status == true) {
          video_control();
        }
      });
		},
		load: function(i) {
		  load(i);
		}
	};
	
});

level1 = new VideoControl;
level2 = new VideoControl;

// namespace global variables for backwards compatibility
GOALLPOWER = {
  video_control : function() {
    level1.initialize(1532796, 'vc-level-1', 20);
    level2.initialize(1532834, 'vc-level-2', 20);
  }
};

// Function to highlight LEVEL 2 Tab
function highlightL2() {
  if (ted2 == 0) {
    $('#tabs').tabs('select', 1);
  }
  return false;
}

(function($) {
  $(document).ready(function()
  {
    GOALLPOWER.video_control();
  });
})(jQuery);
