/*
	Copyright James Matteson 2011. All rights reserved.
*/
var ytplayer;
var myUI = new ui();
var loaded = false;
var changingQuality = false;
var removingPlaying = false;
var canSearchMore = true;

function onYouTubePlayerReady(playerID){
   ytplayer = document.getElementById("myytplayer");
   ytplayer.addEventListener("onStateChange", "onYouTubePlayerStateChange");
   ytplayer.addEventListener("onError", "onYouTubePlayerError");
	   
   if (!loaded){
      myUI.load(playerID);   
      loaded = true;
   }else{
      changingQuality = false;
      myPlaylist.reload();
   }   
}
function onYouTubePlayerStateChange(state){
   myUI.stateChange(state);
}
function onYouTubePlayerError(e){
   document.fire('error:notfound', { 'error': e });
}

// allowScriptAccess must be set to allow the Javascript from one domain to access the swf on the youtube domain
var params = { allowScriptAccess: "always", wmode: "transparent"  };
// this sets the id of the object or embed tag to 'myytplayer'. You then use this id to access the swf and make calls to the player's API
var atts = { id: "myytplayer" };
var ytquality = 1; // Low = 0, High = 1
var data = "http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer&version=3";
var dataHigh = "http://www.youtube.com/apiplayer?ap=%2526fmt%3D18&enablejsapi=1&amp;playerapiid=ytplayer&amp;version=3";
//swfobject.embedSWF("http://www.youtube.com/apiplayer?ap=%2526fmt%3D18&enablejsapi=1&playerapiid=ytplayer&version=3", "ytapiplayer", "480", "360", "8", null, null, params, atts);
swfobject.embedSWF(dataHigh, "ytapiplayer", myUI.getPlayerWidth(), myUI.getPlayerHeight(), "8", null, null, params, atts);

function ui(){
   var oThis = this;
   var HIDEPLAYERINTERVAL = 1000;
   var SEARCHTEXT = 'Search...';
   var isFullScreen = false;
   var searchFocus = false;
   var shareFocus = false;
   var pos, pos2;
   var switchingVideos = false;
   var fullScreenInterval;
   var overFullScreenMenu = false;   
   var prevQuery = '';
   var currentUrl = '';
   
   /* Events */
            /* Load */
   document.observe('dom:loaded', function(){
      Element.scrollTo($('main'), 0, 0);
      
      // Clear
      $('txtSearch').addClassName('inactive');
      $('txtSearch').value = SEARCHTEXT;
      $('ddlCategory').selectedIndex = 0; // All
      $('ddlOrderBy').selectedIndex = 2; // relevance
      $('cbQuality').checked = false;
      clearSearch();
             
      // No Select
      myUtils.noSelect($('header').select('img')[0]);
      myUtils.noSelect($('currentTime2'));
      myUtils.noSelect($('timeRemaining'));
      myUtils.noSelect($('timeRemaining2'));
      myUtils.noSelect($('positionBar'));
      myUtils.noSelect($('positionBar2'));
      myUtils.noSelect($('fullscreenMenu'));
      myUtils.noSelect($('btnPlay'));
      myUtils.noSelect($('btnPlay2'));
      myUtils.noSelect($('btnPrev'));
      myUtils.noSelect($('btnPrev2'));
      myUtils.noSelect($('btnNext'));
      myUtils.noSelect($('btnNext2'));
      
      // Nifty type-anywhere search
      document.observe('keydown', function(e){
         if (!myUtils.isEsc(e) && !searchFocus && !shareFocus){
            $('txtSearch').value = '';
            $('txtSearch').focus();
         }
      });
      
      // Search textbox
      $('txtSearch').observe('keyup', function(e){
         if (myUtils.isEnter(e)){
            var query = $('txtSearch').value.strip();
            
            if (query.length > 0){
               $('btnCancel').src = imgPath + 'cancel.png';
               $('btnCancel').addClassName('active');
               performSearch($('txtSearch').value);
               $('txtSearch').blur();
            }
         }
      });
      $('txtSearch').observe('focus', function(e){
         searchFocus = true;
         $('txtSearch').removeClassName('inactive');
         
         if ($('txtSearch').value == SEARCHTEXT){
            $('txtSearch').value = '';
         }
      });
      $('txtSearch').observe('blur', function(e){
         searchFocus = false;
         
         if ($('txtSearch').value.strip().length == 0){
            $('txtSearch').addClassName('inactive');
            $('txtSearch').value = SEARCHTEXT;
         }
      });
      $('btnCancel').observe('click', cancelSearch);
      
      // Other events
      $('ddlCategory').observe('change', function(){
         performSearch(prevQuery);
      });
      $('ddlOrderBy').observe('change', function(){
         reorderSearch();
      });
      $('main').observe('scroll', function(){
         oThis.checkForMore();
      });
      $('cbQuality').observe('click', function(){
         oThis.changeQuality($('cbQuality').checked)
      });
      $('btnFullScreen').observe('click', function(){
         oThis.toggleFullScreen();
      });
      $('btnFullScreen2').observe('click', function(){
         oThis.toggleFullScreen();
      });
                  
      // Buttons
      $('btnPlay').observe('click', myPlaylist.playPause);
      $('btnPlay2').observe('click', myPlaylist.playPause);
      $('btnPrev').observe('click', myPlaylist.playPrev);
      $('btnPrev2').observe('click', myPlaylist.playPrev);
      $('btnNext').observe('click', myPlaylist.playNext);
      $('btnNext2').observe('click', myPlaylist.playNext);
      
      // Tabs
      $('header').select('li').each(function(tab){
         tab.observe('click', function(){
            // Set active
            $('header').select('li').each(function(li){
               li.removeClassName('active');
            });
            
            tab.addClassName('active');
            
            // Show tab
            $('header').select('.search-menu')[0].hide();
            $('header').select('.empty-menu')[0].hide();
            $('main').hide();
            $('about').hide();
            $('donate').hide();
               
            if (tab.hasClassName('search-tab')){
               $('header').select('.search-menu')[0].show();
               $('main').show();
            }else if (tab.hasClassName('about-tab')){
               $('about').show();
               Element.scrollTo($('about'), 0, 0);
               $('header').select('.empty-menu')[0].show();
            }else if (tab.hasClassName('donate-tab')){
               $('donate').show();
               $('header').select('.empty-menu')[0].show();
            }
            
            oThis.resize();
         });
      });
      
      // Share
      function shareOver(){
         $('shareContainer').select('.hover-container')[0].show();
         $('shareContainer').select('.hover-container p')[0].show();
         $('shareContainer').select('.hover-container div')[0].hide();
         $('txtShare').value = '';
         myPlaylist.getUrl('myUI.cbUrl');
      }
      function shareOut(){
         $('shareContainer').select('.hover-container')[0].hide();
         $('txtShare').blur();
         shareFocus = false;
      }
      jQuery('#shareContainer').hover(
         shareOver, 
         shareOut
       );
      $('txtShare').observe('click', function(){
         $('txtShare').select();
         shareFocus = true;
      });
            
      // Load playlist from link
      myPlaylistLoader.load();
            
      /* FullScreen menu */
      document.observe('mousemove', function(){
         if (!$('fullscreenMenu').visible()){
            showFullPlayer();
         
            if (!overFullScreenMenu){
               startFullScreenInterval();
            }
         }
      });
      jQuery('#fullscreenMenu').hover(
         function(){
            overFullScreenMenu = true;
            showFullPlayer();
         }, 
         function(){
            overFullScreenMenu = false;
            startFullScreenInterval();
         }
       );       
   });
   Event.observe(window, 'load', function(){
      // Screen
      oThis.resize();
   });
   window.onbeforeunload = function(){
      // todox return "Are you sure you want to do that?  This action will stop the video.  Remember to save your playlist link!";
   };
         /* Screen */
   Event.observe(window, 'resize', function(){
      oThis.resize();
   });
   document.observe('keyup', function(e){
      if (myUtils.isEsc(e)){
         oThis.toggleFullScreen();
      }
   });
   
   /* Private */
   function isCatSearch(){
      return (oThis.getCategory() != 'Discography');
   }
   function performSearch(query, isNext){ // New
      prevQuery = query;
      
      if (isNext == null) isNext = false;
      searchBegin(!isNext);
                   
      if (isCatSearch()){
         mySearchUI.search(query, isNext);
      }else if (query.length > 0){
         myDiscUI.findArtist(query);
      }
   }
   function clearSearch(){ // New
      if (isCatSearch()){
         performSearch('');
      }else{
         myDiscUI.clear();
      }
   }
   function reorderSearch(){ // New
      if (isCatSearch()){
         performSearch(prevQuery);
      }else{
         myDiscUI.orderByChange();
      }
   }
   function searchBegin(clearSearch){
      canSearchMore = false;
      oThis.showLoading();
      
      if (isCatSearch()){
         $('searchResults').show();
         myDiscUI.hide();
         
         if (clearSearch != null && clearSearch){
            $('searchResults').innerHTML = '';
         }
      }else{
         $('searchResults').hide();
         myDiscUI.show();
         
         if (clearSearch != null && clearSearch){
            myDiscUI.clear();
         }
      }
   }
   function searchMore(){
      performSearch(prevQuery, true);
   }
   function cancelSearch(){
      if ($('btnCancel').hasClassName('active')){
         $('btnCancel').src = imgPath + 'cancel-disabled.png';
         $('btnCancel').removeClassName('active');
         $('txtSearch').addClassName('inactive');
         $('txtSearch').value = SEARCHTEXT;
         clearSearch();
      }
   }
   function syncVolumes(){
      if (!ytplayer.getVolume) return; // Happens when video quality changes
      jQuery('#volumeBar').slider("moveTo", ytplayer.getVolume());
      jQuery('#volumeBar2').slider("moveTo", ytplayer.getVolume());
   }
         /* FullScreen menu */
   function showFullPlayer(){
      if (isFullScreen){
         clearFullScreenInterval();
         $('fullscreenMenu').show();
         syncVolumes();
      }
   }
   function clearFullScreenInterval(){
      if (fullScreenInterval >= 0) 
         clearInterval(fullScreenInterval); 
   }
   function startFullScreenInterval(){
      clearFullScreenInterval();
      fullScreenInterval = setInterval(function(){
         // Hide Full Player
         clearFullScreenInterval();
         $('fullscreenMenu').hide();
         syncVolumes();  
      }, HIDEPLAYERINTERVAL);
   }
         /* */
   function clearPositions(){		   
		pos.clear();
      pos2.clear();
   }
   
   /* Public */
   this.load = function(playerID){
      // Position
      pos = new position('positionBar', 'positionBarLoaded', null, 'timeRemaining');
      pos2 = new position('positionBar2', 'positionBarLoaded2', 'currentTime2', 'timeRemaining2');
      pos.start();
      pos2.start();
      
      // Volume
      jQuery('#volumeBar').slider({
         handle: '#volumeHandle',
         min: 0,
         max: 100,
         startValue: 100,
         slide: function(e, ui){ ytplayer.setVolume(ui.value); }
      });
      jQuery('#volumeBar2').slider({
         handle: '#volumeHandle2',
         min: 0,
         max: 100,
         startValue: 100,
         slide: function(e, ui){ ytplayer.setVolume(ui.value); }
      });
      ytplayer.setVolume(100);
   }
   this.toggleFullScreen = function(){
      isFullScreen = !isFullScreen;
		oThis.resize();
   }
   this.changeQuality = function(high){
      changingQuality = true;
      
      if (high){
         quality = 1;
         ytplayer.data = dataHigh;
         $('positionBarLoaded').show();
         $('positionBarLoaded2').show();
      }else{
         ytquality = 0;
         ytplayer.data = data;
         $('positionBarLoaded').hide();
         $('positionBarLoaded2').hide();
      }
      
      clearPositions();
      myPlaylist.clear();
   }
   this.resize = function(){
      if (isFullScreen){
         $(document.body).addClassName('fullscreen');
         $('content').hide();
         $('options').hide();
         $('playlist').hide();
         $('shareContainer').hide();
         $('playerControls').hide();
         $('positionBar').hide();
         oThis.hideLoading();
         
         if (ytplayer != null){
            ytplayer.height = document.viewport.getHeight() + 'px';
            ytplayer.width = document.viewport.getWidth() + 'px';
            // ytplayer.setSize(320, 240);
         }
      }else{
         $(document.body).removeClassName('fullscreen');
         $('content').show();
         $('options').show();
         $('playlist').show();
         $('shareContainer').show();
         $('playerControls').show();
         $('positionBar').show();
         $('fullscreenMenu').hide();
         
         if (ytplayer != null){
            ytplayer.height = myUI.getPlayerHeight() + 'px';
            ytplayer.width = myUI.getPlayerWidth() + 'px';
            syncVolumes();
         }
                           
         $('main').style.height = $('main').getHeight() - 1 + 'px'; // kludge for browsers that don't update scrollbar height
         $('main').style.height = document.viewport.getHeight() - $('header').getHeight() + 'px';
         $('about').style.height = document.viewport.getHeight() - $('header').getHeight() + 'px';
         $('donate').style.height = document.viewport.getHeight() - $('header').getHeight() + 'px';
         $('donate').style.width = $('content').getWidth();
                  
         if (Prototype.Browser.IE){
            $('playlist').style.height = document.viewport.getHeight() - 210 - $('shareContainer').getHeight() + 'px';
         }else{
            $('playlist').style.height = document.viewport.getHeight() - $('playerRelated').getHeight() - $('shareContainer').getHeight() + 'px';
         }
      }
   }
   this.checkForMore = function(){
      if (canSearchMore && $('more').viewportOffset().top - 150 <= document.viewport.getHeight()){
         searchMore();
      }
   }
   this.showLoading = function(){
      $('loading').show();
   }
   this.hideLoading = function(){
      $('loading').hide();
   }
   this.stateChange = function(state){
      if (switchingVideos && state == 0){
         switchingVideos = false;
         return;
      }
      var play = true;
      
      switchingVideos = false;
      				
      if (state == -1){
         // unstarted
      }else if (state == 0){
         // ended
         if (!changingQuality && !removingPlaying){
            myPlaylist.playNext();
         }
      }else if (state == 1){
         // playing   
         play = false;
			ytplayer.setPlaybackQuality('highres');
      }else if (state == 2){
         // paused
      }else if (state == 3){
         // buffering
         play = false;
			ytplayer.setPlaybackQuality('highres');
      }else if (state == 5){
         // video cued
      }
      
      if (play){
         $('btnPlay').src = imgPath + 'play.png';
         $('btnPlay2').src = imgPath + 'play.png';
      }else{
         $('btnPlay').src = imgPath + 'pause.png';
         $('btnPlay2').src = imgPath + 'pause.png';
      }
   }
   
         /* Getters */
   this.getPlayerHeight = function(){
      return 120;
   }
   this.getPlayerWidth = function(){
      return 160;
   }
   this.getCategory = function(){
      return $('ddlCategory').options[$('ddlCategory').selectedIndex].value;
   }
   this.getOrderBy = function(){
      return $('ddlOrderBy').options[$('ddlOrderBy').selectedIndex].value;
   }
         /* Setters */
   this.setSwitchingVideos = function(value){
      switchingVideos = value;
      clearPositions();
   }
   
         /* Utility */
   this.addVideo = function(videoID, videoTitle, videoImg, play){
      myPlaylist.add(videoID, videoTitle, videoImg);
            
      if (play){
         myPlaylist.play(videoID);
      }
   }
   this.divClear = function(){
      return new Element('div', { 'class': 'clear' });
   }
   this.createVideo = function(videoID, videoTitle, videoImg, videoDuration){
      var li = new Element('li', {});
      var div = new Element('div', {
         'class': 'wrapper'
      });
      var img = new Element('img', {
         'src': videoImg
      });
      var title = new Element('p', {
         'class': 'title'
      });
      var duration = new Element('p', {
         'class': 'duration'
      });
               
      li.observe('click', function(e){
         myUI.addVideo(videoID, videoTitle, videoImg, false)
      });
      li.observe('dblclick', function(e){
         myUI.addVideo(videoID, videoTitle, videoImg, true)
      });
      
      title.innerHTML = videoTitle;
      duration.innerHTML = myUtils.formatTime(videoDuration);
      div.insert(img);
      div.insert(title);
      div.insert(duration);
      div.insert(oThis.divClear());
      li.insert(div);
      myUtils.noSelect(li);
            
      return li;
   }
   
   /* Callbacks */
   this.cbUrl = function(resp){
      currentUrl = resp.tinyurl;
      $('shareContainer').select('.hover-container p')[0].hide();
      $('shareContainer').select('.hover-container div')[0].show();
      $('txtShare').value = resp.tinyurl;
      $('hlShare').href = "mailto:?Subject=Movie%20Louvre%20Playlist&Body=" + resp.tinyurl + "";
   }
}



var mySearchUI = new searchUI();
function searchUI(){
   var oThis = this;
   
   function fillVideos(container, root){
      if (root.feed.entry == null) return;
      
      if (root.feed.entry.length > 0){
         var lists = container.select('ul');
         var addList = true;
         var ul;
                  
         if (lists.length > 0){
            ul = lists[0];
            addList = false;
         }else{
            ul = new Element('ul', {});
         }
         
         for (var i = 0, len = root.feed.entry.length; i < len; i++){
            var item = root.feed.entry[i];
            var videoID;
            
            try{ // YouTube changed what it passes as the url
               videoID = item.link[0].href.split("?v=")[1].split("&")[0];
            }catch(e){
               videoID = item.link[0].href.split("?v=")[1];
            }
            
            var videoTitle = item.title.$t;
            var videoImg = item.media$group.media$thumbnail[0].url;
            var videoDuration = item.media$group.yt$duration.seconds;
            ul.insert(myUI.createVideo(videoID, videoTitle, videoImg, videoDuration));
         }
         
         if (root.feed.entry.length == mySearch.getMaxResults()){
            canSearchMore = true;
         }
         
         if (addList){
            container.insert(ul);
         }
         
         myUI.resize();
         myUI.checkForMore();
      }
   }
   
   /* Public */
   this.search = function(query, isNext){
      mySearch.search(query, isNext, 'mySearchUI.cbSearch');
   }
   this.cbSearch = function(root){ 
      myUI.hideLoading();
      fillVideos($('searchResults'), root);
   }
}

var myPlaylistLoader = new playlistLoader();
function playlistLoader(){
   this.load = function(){
      myUtils.getSharedItems().each(function(id){
         id = id.strip();
            
         if (id.length > 0){
            mySearch.getVideo(id, 'myPlaylistLoader.loadSharedItem');
         }
      });
   }
   this.loadSharedItem = function(root){
      var item = root.entry;
      var myID;
            
      try{ // YouTube changed what it passes as the url
         myID = item.link[0].href.split("?v=")[1].split("&")[0];
      }catch(e){
         myID = item.link[0].href.split("?v=")[1];
      }
      
      var myImg = item.media$group.media$thumbnail[0];
      var myTitle = item.title.$t;
      
      myPlaylist.addSharedItem(myID, myTitle, myImg.url);
   }
}

var myDiscUI = new discUI();
function discUI(){
   var oThis = this;
   var callbackIndex = 0;
   var mbArtists;
   var mbArtist;
   var mbAlbums;
   var mbTracks;
   var selectedAlbum;
   var defaultImg = imgPath + 'emptyart.png';
   
   /* Constructor */
   document.observe('dom:loaded', function(){
      $('btnIncorrect').observe('click', function(){
         if (mbArtists != null){
            oThis.showSection('incorrect');
            
            for(var i = 0, len = mbArtists.value.items.length; i < len; i++){
               loadIncorrectArtist(mbArtists.value.items[i]);
            }
         }
      });
      
      $('discography').select('.menu li.official')[0].observe('click', function(){
         selectMenu(this);
         myDiscUI.getAlbums('Official', 'Album');
      });
      $('discography').select('.menu li.compilation')[0].observe('click', function(){
         selectMenu(this);
         myDiscUI.getAlbums('Compilation', '');
      });
      $('discography').select('.menu li.bootleg')[0].observe('click', function(){
         selectMenu(this);
         myDiscUI.getAlbums('Bootleg', '');
      });      
   });
   
   /* Private */
   function addCallback(cb){
      var index = callbackIndex;
      
      oThis.callbacks[index] = {
         'index': index,
         'run': function(result){
            // If the index I have equals the current index + 1 then I'm still the current callback
            if (this.index + 1 == callbackIndex){
               cb(result);
            }
         }
      };
      callbackIndex++;
      
      return index;
   }
   function loadIncorrectArtist(artist){
      var container = new Element('div', {});
      var namecontainer = new Element('p', {
         'class': 'name-container'
      });
      var name = new Element('span', {});
                  
      name.innerHTML = artist.name;
      name.observe('click', function(){
         oThis.loadArtist(artist);
      });
      namecontainer.insert(name);
      container.insert(namecontainer);
      
      if (artist.disambiguation != null){
         var desc = new Element('p', {
            'class': 'desc'
         });
         desc.innerHTML = artist.disambiguation;
         container.insert(desc);
      }
      
      $('discography').select('.incorrect')[0].insert(container);
   }
   function getAlbumImg(album){
      if (album.asin == null){
         return defaultImg;
      }else{
         return 'http://ec2.images-amazon.com/images/P/' + album.asin + '.01.TZZZZZZZ.jpg'; // T, M, L
      }
   }
   function loadAlbum(album){
      if (album.id != null){
         var div = new Element('div', {});
         var img = new Element('img', {});
         var p = new Element('p', {});
         
         img.src = getAlbumImg(album);
         img.observe('load', function(){
            if (img.getWidth() == 1){
               img.src = defaultImg;
            }
         });
         
         p.innerHTML = album.title;
         
         div.observe('click', function(){
            selectedAlbum = album;
            oThis.getTracks();
         });
         div.insert(img);
         div.insert(p);
         $('discography').select('.albums')[0].insert(div);
      }
   }
   function loadTrack(track, i){
      var div = new Element('div', {
         'class': 'track'
      });
      var title = new Element('p', {
         'class': 'track-title'
      });
      
      title.innerHTML = "<span>" + (i + 1) + '.</span>' + track.title;
      div.insert(title);
      div.insert(myUI.divClear());
      
      if (track.youtube[0].entry != null){
         var ul = new Element('ul', {});
         
         if (track.youtube[0].entry.length == null){
            // One video
            ul.insert(getTrackVideo(track.youtube[0].entry));
         }else{
            // Multiple videos
            for(var j = 0, len2 = track.youtube[0].entry.length; j < len2; j++){
               ul.insert(getTrackVideo(track.youtube[0].entry[j]));
            }
         }
         
         div.insert(ul);
         div.insert(myUI.divClear());
      }else{
         title.addClassName('track-title-empty');
      }
      
      $('discography').select('.tracks')[0].insert(div);
   }
   function getTrackVideo(video){
      var videoID;
            
      try{ // YouTube changed what it passes as the url
         videoID = video.link[0].href.split("?v=")[1].split("&")[0];
      }catch(e){
         videoID = video.link[0].href.split("?v=")[1];
      }
      
      var videoTitle = video.title.content;
      var videoImg = video['media:group']['media:thumbnail'][0].url;            
      var videoDuration = video['media:group']['yt:duration'].seconds;
      return myUI.createVideo(videoID, videoTitle, videoImg, videoDuration);
   }
   function selectMenu(li){
      $('discography').select('.menu li.active').each(function(item){
         item.removeClassName('active');
      });
      
      if (li != null){
         li.addClassName('active');
      }
   }
   function showSelectedAlbum(){
      if (selectedAlbum != null){
         $('discography').select('.album img')[0].src = getAlbumImg(selectedAlbum);
         $('discography').select('.album .name')[0].innerHTML = selectedAlbum.title;
         $('discography').select('.album')[0].show();
      }
   }
      
   /* Public */
   this.show = function(){
      $('discography').show();
   }
   this.hide = function(){
      $('discography').hide();
   }
   this.searchBegin = function(){
      oThis.clear();
      $('discography').select('.blank')[0].hide();
   }
   this.orderByChange = function(){
      if (selectedAlbum != null){
         myDiscUI.getTracks();
      }
   }
   this.clear = function(){
      $('discography').select('.artist-menu')[0].hide();
      $('discography').select('.artist')[0].innerHTML = '';
      $('discography').select('.menu')[0].hide();
      oThis.clearSection();
      oThis.showSection('blank');
   }
   this.clearSection = function(){
      $('discography').select('.albums')[0].innerHTML = '';
      $('discography').select('.tracks')[0].innerHTML = '';
      $('discography').select('.incorrect')[0].innerHTML = '';
      
      $('discography').select('.blank')[0].hide();
      $('discography').select('.albums')[0].hide();
      $('discography').select('.tracks')[0].hide();
      $('discography').select('.incorrect')[0].hide();
      $('discography').select('.album')[0].hide();
   }
   this.showSection = function(section){
      myUI.hideLoading();
      oThis.clearSection();
      
      if (section == 'albums'){
         selectedAlbum = null;
         $('discography').select('.albums')[0].show();
      }else if (section == 'tracks'){
         showSelectedAlbum();
         $('discography').select('.tracks')[0].show();
      }else if (section == 'incorrect'){
         selectMenu(null);
         selectedAlbum = null;
         $('discography').select('.incorrect')[0].show();
      }else{
         selectedAlbum = null;
         $('discography').select('.blank')[0].show();
      }
   }
   this.loadArtist = function(artist){
      mbArtist = artist;
      $('discography').select('.artist-menu')[0].show();
      $('discography').select('.artist')[0].innerHTML = mbArtist.name;
      $('discography').select('.menu')[0].show();
      
      if (mbArtists.value.items.length > 1){
         $('btnIncorrectContainer').show();
      }else{
         $('btnIncorrectContainer').hide();
      }
      
      selectMenu($('discography').select('.menu li.official')[0]);
      oThis.getAlbums('Official', 'Album');
   }
   
   /* Callback Initiators */
   this.findArtist = function(query){
      oThis.searchBegin();
      myUI.showLoading();
      mySearch.getArtists(query, 'myDiscUI.callbacks[' + addCallback(oThis.cbArtists) + '].run');
   }
   this.getAlbums = function(releaseTypes, releaseFilter){
      if (mbArtist != null){
         oThis.clearSection();
         myUI.showLoading();
         mySearch.getAlbums(mbArtist.id, releaseTypes, releaseFilter, 'myDiscUI.callbacks[' + addCallback(oThis.cbAlbums) + '].run');
      }
   }
   this.getTracks = function(){
      if (selectedAlbum != null){
         oThis.clearSection();
         myUI.showLoading();
         mySearch.getTracks(selectedAlbum.artist.name, selectedAlbum.id, 'myDiscUI.callbacks[' + addCallback(oThis.cbTracks) + '].run');
      }
   }
   this.callbacks = [];
   
   /* Callbacks */
   this.cbArtists = function(root){
      mbArtists = root;
      myUI.hideLoading();
      
      if (root.value.items[0].id != null){
         oThis.loadArtist(root.value.items[0]);
      }else{
         oThis.clear();
      }
   }
   this.cbAlbums = function(root){
      myUI.hideLoading();
      mbAlbums = root;
      oThis.showSection('albums');
      
      for(var i = 0, len = root.value.items.length; i < len; i++){
         loadAlbum(root.value.items[i]);
      }
   }
   this.cbTracks = function(root){
      myUI.hideLoading();
      mbTracks = root;
      oThis.showSection('tracks');
            
      for(var i = 0, len = root.value.items.length; i < len; i++){
         loadTrack(root.value.items[i], i);
      }
   }
}
