

/*
Helper function for creating DOM elements
*/    
var DOM = {};
DOM.createElement = function() {
  if ( typeof( arguments[0] ) != "string" ||
       typeof( arguments[1] ) != "object" ) return false;
  var el = document.createElement( arguments[0] );
  for( var prop in arguments[1] ) el.setAttribute( prop, arguments[1][prop] );
  if ( arguments[2] ) el.appendChild( document.createTextNode( arguments[2] ) );
  return el;
}      

/*
Toggle the content area of music. Areas can be collapsed by default
*/
TogglePanel = function( obj ) {
  if (  !bbcjs  || !bbcjs.dhtml || !obj.id || !DOM  ) { return false }
  this.obj = obj;
  this.build();
}
TogglePanel.prototype = {
  build : function() { 
    if ( $( this.obj.id ) ) {  
      this.container      = $( this.obj.id );
      this.collapsed      = ( this.obj.collapsed ) ? this.obj.collapsed : false;      
      this.container.head = this.container.getElementsByTagName( 'h2' )[0];
      var divs            = this.container.getElementsByTagName( 'div' );
      if ( !divs ) { return false };
      for ( var i=0; i<divs.length; i++ ) {
        if ( divs[i].className == "content" ) { this.container.content = divs[i]; }
      }    
      if (  this.container      && 
            this.container.head && 
            this.container.content ) { this.applyHandlers(); } 
      else { return false; }    
    }
  },
  applyHandlers : function() {    
    var aTag = DOM.createElement( 'a', { href: "#" }, "-" ); 
    aTag.className = "showing";
    aTag.containerId=this.container.id;
    aTag.content = this.container.content;
    //aTag.writeToCookie=true;
    aTag.onclick = function() { 
      return doToggle(this,true);
    } 
    doToggle=function(panel,writeToCookie){
      if ( panel.content.style.display == "none" ) { 
        panel.content.style.display = "";
        panel.className = "showing";
        panel.innerHTML = "-";
        if(writeToCookie){
          toggleToCookie(panel.containerId,false);
        }
        return false;
      } else { 
        panel.content.style.display = "none";
        panel.className = "hidden";
        panel.innerHTML = "+";
        if(writeToCookie){
          toggleToCookie(panel.containerId,true);
        }
        return false;
      }      
    }   
    this.container.head.appendChild( aTag );
    if ( this.collapsed ){ 
      return doToggle(aTag,false);
    }
    
  }    
}

/*
This takes the album list and displays it in a different way.
First creating a list of images that once clicked supply more
information in the promo area.
*/
var AlbumStacker = function() {
  if ( !bbcjs || !bbcjs.dhtml ) { return false }
  this.build();       
}
AlbumStacker.prototype = {
  build : function() {             
    if ( $( 'album-promo' ) && $( 'album-list' ) ) {    
      this.promoHolder     = $( 'album-promo' ); 
      this.albumListHolder = $( 'album-list'  ); 
      this.list            = this.albumListHolder.getElementsByTagName( 'li' );
      this.showList();
      this.randomPromo();
    }
  },      
  showList : function() {   
    for ( var i=0; i<this.list.length; i++ ) { 
      var cur = this.list[i];
      var albumDetails = cur.getElementsByTagName( 'div' )[0]; 
      if( !albumDetails || albumDetails.className != 'album-details' ) { return false; }
      albumDetails.style.display = 'none';               
      cur.callBack  = this;                     
      cur.onclick   = function() { 
        this.callBack.promote( this ); 
        return false; 
      } 
      this.albumListHolder.className = 'album-list-dynamic';
    }
  },
  promote : function( li ) {    
    var liClone      = li.cloneNode( true );
    var albumDetails = liClone.getElementsByTagName( 'div' )[0];
    var image        = liClone.getElementsByTagName('img')[0]; 
    if ( !image || !albumDetails ) { return false }; 
    albumDetails.style.display = "block";    
    image.width  = "140"; 
    image.height = "140"; 
    this.clearPromote();  
    this.promoHolder.appendChild( liClone ); 
    var lis = $('album-list').getElementsByTagName( 'li' ); 
    for ( var i=0; i<lis.length; i++ ) { 
      lis[i].className = ( lis[i].id == li.id ) ? "active" : "";
    }
  },
  clearPromote : function() { this.promoHolder.innerHTML = ""; },
  randomPromo : function() {
    var rand = Math.floor( Math.random() * this.list.length );
    this.promote( this.list[ rand ] );
  }        
}

  
/*
Handlers, these handle the returned data from the Ajax request on specific widget/active areas.
*/      
genrePromoHandler = {
  onLoad : function() {
    $("genre-list").innerHTML   = this.req.responseText;     
    $("genre-loader").style.display = "none"; 
    $("genre-pagination").style.display = "block";
    genrePromoHandler.highlightLink( this.pass );     
  },
  onLoading : function() {
    $("genre-pagination").style.display = "none"; 
    $("genre-loader").innerHTML = "Loading...";
    $("genre-loader").style.display = "block";                             
  },
  onError : function() {
    $("genre-loader").innerHTML = "There was an error whilst loading the genre data."; 
    $("genre-pagination").style.visibility = "visible"; 
  },
  highlightLink : function( aTag ) {
    for ( var i=1; i<=aTag.pages; i++ ) {
      $("genre-page-" + i + "-link").className = ( i == aTag.page ) ? "highlight" : "";             
    }
  }
}
albumPromoHandler = {
  onLoad : function() {
    $("album-list").innerHTML   = this.req.responseText;   
    new AlbumStacker();         
    $("album-loader").style.display = "none"; 
    $("album-pagination").style.display = "block";
    albumPromoHandler.highlightLink( this.pass ); 
  },
  onLoading : function() {          
    $("album-pagination").style.display = "none";
    $("album-loader").innerHTML = "Loading...";
    $("album-loader").style.display = "block";           
  },
  onError : function() {
    $("album-loader").innerHTML = "There was an error whilst loading the album data"; 
    $("album-pagination").style.visibility = "visible"; 
  },
  highlightLink : function( aTag ) {
    for ( var i=1; i<=aTag.pages; i++ ) {
      $("album-page-" + i + "-link").className = ( i == aTag.page ) ? "highlight" : "";             
    }          
  }
}      


/*
Control the pagination links for the album and genre promo areas
*/
Paginator = function( obj ) {
  if (  !obj['groupedBy']  ||
        !obj['id']         ||
        !DOM  ) { return false }
  this.groupedBy  = obj['groupedBy'];
  this.id         = obj['id'];
  this.pages = [];
  this.calcPages();
  this.buildElements();
}      
Paginator.prototype = {
  //get the genres and splice them into the amount set, to create pages.
  calcPages : function() {          
    for ( var i=0; i<config.genres.length; i+=this.groupedBy ) {
      this.pages.push( config.genres.slice( i, i+this.groupedBy ) );
    }
  },
  buildElements : function() {
    var ul = $( this.id + "-pagination" );
    var li_back     = DOM.createElement( 'li', {} );   
    var span_back   = DOM.createElement( 'span', {} ); //for hiding the text
    var a_back_text = document.createTextNode( "<" );                          
    var a_back      = DOM.createElement( 'a', { href: "#", id: this.id + "-back" } );
    span_back.appendChild( a_back_text );
    span_back.className = "hide";
    a_back.appendChild( span_back );
    li_back.appendChild( a_back );
    a_back.linksId = this.id;
    a_back.pages   = this.pages;          
    a_back.onclick = function() {
      for ( var i=2; i<=this.pages.length; i++ ) {
        if ( $(this.linksId + "-page-" + i + "-link").className == "highlight" ) {
          $(this.linksId + "-page-" + (i-1) + "-link").onclick();
          return false;
        }              
      }
      return false;
    }
    var li_next     = DOM.createElement( 'li', {} );
    var span_next   = DOM.createElement( 'span', {} ); //for hiding the text
    var a_next_text = document.createTextNode( ">" ); 
    var a_next      = DOM.createElement( 'a', { href: "#", id: this.id + "-next" } );
    span_next.appendChild( a_next_text );
    span_next.className = "hide";
    a_next.appendChild( span_next );
    li_next.appendChild( a_next );          
    a_next.linksId = this.id;
    a_next.pages   = this.pages;
    a_next.onclick = function() {
      for ( var i=1; i<this.pages.length; i++ ) {
        if ( $(this.linksId + "-page-" + i + "-link").className == "highlight" ) {
          $(this.linksId + "-page-" + (i+1) + "-link").onclick();
          return false;
        }        
      }
      return false;
    }                    
    //insert elements
    ul.insertBefore( li_back, ul.firstChild );
    ul.appendChild( li_next );          
  }
}

createGenrePagination = function() {
  $("genre-pagination").style.visibility = "hidden";
  var genrePagination = new Paginator( { groupedBy: 3, id: "genre" } );        
  var genrePages = genrePagination.pages;        
  //hide any buttons, from the default view
  for ( var i=genrePages.length+1; i<=4; i++ ) {
    $("genre-page-" + i + "-link").parentNode.style.display = "none"; //hide the li
  }  
  //apply AJAX event to genre pagination links
  for ( var i=1; i<=genrePages.length; i++ ) {
    var el   = $("genre-page-" + i + "-link");
    var span = $("genre-page-" + i + "-link").getElementsByTagName("span")[0];
    span.className = "hide";
    el.genres = genrePages[i-1];
    el.pages  = genrePages.length;
    el.page   = i;
    el.className = "js";
    el.onclick = function() {   
      this.apiCall = new Api.Query({
        api       : Api.GENRE_PROMO,          
        onLoad    : genrePromoHandler.onLoad,
        onLoading : genrePromoHandler.onLoading, 
        onError   : genrePromoHandler.onError,
        pass      : this
      });        
      this.apiCall.send();
      return false;
    }   
  }
  //default action so the pagination can work
  $("genre-page-1-link").className = "highlight";  
  $("genre-pagination").style.visibility = "visible";       
}

createAlbumPagination = function() {
  $("album-pagination").style.visibility = "hidden";
  var albumPagination = new Paginator( { groupedBy: 6, id: "album" } );        
  var albumPages = albumPagination.pages;        
  //hide any buttons, from the default view
  for ( var i=albumPages.length+1; i<=2; i++ ) {
    $("album-page-" + i + "-link").parentNode.style.display = "none"; //hide the li
  }  
  //apply AJAX event to album pagination links
  for ( var i=1; i<=albumPages.length; i++ ) {
    var el2   = $("album-page-" + i + "-link");
    var span2 = $("album-page-" + i + "-link").getElementsByTagName("span")[0];
    span2.className = "hide";
    el2.genres = albumPages[i-1];
    el2.pages  = albumPages.length;
    el2.page   = i;
    el2.className = "js";
    el2.onclick = function() {   
      this.apiCall = new Api.Query({
        api       : Api.ALBUM_PROMO,          
        onLoad    : albumPromoHandler.onLoad,
        onLoading : albumPromoHandler.onLoading, 
        onError   : albumPromoHandler.onError,
        pass      : this
      });        
      this.apiCall.send();
      return false;
    }   
  }   
  //default action so the pagination can work
  $("album-page-1-link").className = "highlight";  
  $("album-pagination").style.visibility = "visible";    
}

/* 
build the behaviour layer
*/
build = function() {      
  if ( $("genre-pagination" ) && $("genre-page-1-link" ) ) { createGenrePagination(); }
  if ( $("album-pagination" ) && $("album-page-1-link" ) ) { createAlbumPagination(); }       
}


/*  Read from cookie and set correct panels to collapsed status */
toggleFromCookie=function(){
  bbcjs.cookies.loadCookies();
  if(bbcjs.cookies.cookieData['bbc-music']){
    bbcjs.forEach(bbcjs.cookies.cookieData['bbc-music'],panelState);
  }
  function panelState(value,key){
    if (value == 'collapsed'){
    new TogglePanel( { id : key,  collapsed : true } );
    }
  };
}
/* Store panel states in cookie */

toggleToCookie=function(a,b){
  bbcjs.cookies.loadCookies();
  if (!bbcjs.cookies.cookieData['bbc-music']){
    bbcjs.cookies.setCookie('bbc-music',"",'+3M','/music');
    bbcjs.cookies.loadCookies();    
  };
  var musicCookie = bbcjs.cookies.cookieData['bbc-music'];
  if(b==false){musicCookie[a]=""} else {musicCookie[a]='collapsed'};
  bbcjs.cookies.setCookie('bbc-music',musicCookie,'+3M','/music');

}