/**
 *
 * TEAM PAGE JS 
 * 
 *  
 */  

//Add the onload actions
window.addEvent('domready', function() {
  
  //hover effect on the teammates images
  teammatesHover();
  
  //tips for the competitions games
  //competitionGamesTips();
  
  //competition knhb standen
  if( $('currentTeam') ) {
    showCurrentTeamStanden();
  }
  
  //competition game accordion
  showAccordionCompetitionGames();
  
  //Agenda navigation
  if( $('agendaForm' ) ) {
    showAgendaNavigation();
  }
  
  if( $('gameScoredUserID') ) {
    initPlayersScored();
  }
  
  if( $('give-presence') ) {
    initPlayerPresence();
  }
  
  //Accordeon finance
  showAccordionFinanceData();
  
  
  if( $('moderateFinance') ) {
    moderateFinance();
  }
  
  
});


function moderateFinance() {
  var form = $('moderateFinance');
  
  //init approve/disapprove clicks
  $$('div.finance-approve-block').each( function(block) {
    var approve = block.getElement('img.approve');
    var disapprove = block.getElement('img.disapprove');
    
    if( approve ) {
      approve.addEvent( 'click', function(el) {
        form.getElement('input#ID').value = block.get('dataID');
        form.getElement('input#maction').value = 'approve';
        form.submit();
      });
    }
    if( disapprove ) {
      disapprove.addEvent( 'click', function(el) {
        form.getElement('input#ID').value = block.get('dataID');
        form.getElement('input#maction').value = 'disapprove';
        if( confirm('Weet je zeker dat je deze wilt verwijderen?') ) { form.submit(); }
      });
    }
  });
}


function initPlayerPresence()
{
  //init block
  var wrapper = $('give-presence');
  wrapper.getElements('div').each( function(el) {
    el.addEvent('click', function() {
      var inputElem = this.getElement('input');
      inputElem.checked = 'true';
    });
    el.setStyle('cursor', 'pointer');
  });
}


function showAgendaNavigation()
{
  var form = $('agendaForm' );
  var buttons = [ $('lastMonth') , $('nextMonth') ];
  
  buttons.each( function(button) {
    button.addEvent( 'click', function( el )
    {
      var monthYear = this.get('rel').split('|');
      form.getElement('input[name=month]').value = monthYear[0];
      form.getElement('input[name=year]').value = monthYear[1];
      form.submit();
      return false;
    });
  });
  
  
}

function showAccordionCompetitionGames()
{
  //Accordeon
  $$('div.accordion').each( function(el) {
    var myAccordion = new Accordion( $(el.id), 'h3.game-toggler', 'div.game-element', {
      opacity: false,
      onActive: function(toggler, element){
        toggler.set('class', 'game-toggler-selected');
        element.set('class', 'game-element-selected');
      },
      onBackground: function(toggler, element){
        toggler.set('class', 'game-toggler');
        element.set('class', 'game-element');
        
      }
    });  
  });
}

function showCurrentTeamStanden()
{
  if( $('currentTeam') ) {
    $('currentTeam').getParent().setStyle( 'background-color', '#FFE28A' );
  }
}

function competitionGamesTips()
{
  if( !$('competitionGames') ) return;
  
  $('competitionGames').getElements('div.gamelist').each( function(element) 
    {
    //Set cursor
  element.setStyle('cursor', 'pointer');  
    
  //Set the title & text of the tip
  element.store('tip:title', element.get('tiptitle') );
  element.store('tip:text', element.get('tiptext') );
  
  //Only show the Tip when it has a title
  if( element.get('tiptitle') ) {
      log( 'tip: ' + element.className );
      var showTips = new Tips( element, {
        showDelay: 100,
        hideDelay: 400,
        fixed: true,
        offsets: {'x': element.offsetWidth + 20, 'y': 0}
      
        ,onShow: function(tip) { tip.fade('in'); },
        onHide: function(tip) { tip.fade('out'); }
        });
      }
   });
}

function teammatesHover()
{
  
  if( $('teammates-block') )
  {
    $('teammates-block').getElements('img').addEvents( {
      
      'mouseover' : function() 
      { 
        this.setStyle('border','0px solid green');
        
        this.morph( {
          'border' : '2px solid green' ,
          duration: 'short'
        }); 
      },
      
      'mouseleave'  : function() 
      { 
        this.get('morph').start( { 'border' : '0px solid green' } );
        //this.setStyle('border', 'none') 
      }
    });
  }
}


function agendaMorph()
{
  var el = $$('#agendaOverview li');
  var color = el.getStyle('backgroundColor');
  
  $$('#agendaOverview li').addEvents( 
  {
      mouseenter: function() {
        // We set the cursor to pointer so users know they can click this region
        this.setStyle('cursor','pointer');

        // Change background color on mouseover
        this.morph({
          'background-color': '#BDF09F',
          'background-image': 'url(http://www.schoolmaster.nl/Portals/0/Schoolmaster%202007/Icons/agenda_icon.png)'
        });
      },
      
      mouseleave: function() {
          // Morphes back to the original style
          this.morph({
              duration: 'short',
              'background-image': 'none',
              backgroundColor: color
          });
      }
      
  });
}




/**
 * Fades images in and out
 * @author: MennoB 
 */ 
var ImageFader = new Class({
  
  Implements: Options,
  options: {
    imageSwitchDelay : 10000,
    imageFadeTime : 2000,
    maxOpacity : 0.8
  },
  
  
  initialize: function( imageElement ) {
    //log('loaded image fader');
    this.activeImage = $(imageElement);
    //this.activeImage.set('style', 'position:absolute; z-index:2; top:0; left:0;');
    this.activeImage.getParent().set('style', 'position:relative;');
    
    //create the second image
    this.passiveImage = new Element ( 'img' , {} );
    //this.passiveImage.set('opacity','0');
    this.passiveImage.set('style','display:none;');
    //this.passiveImage.set('position','absolute');
    this.passiveImage.set('id','passiveImage');
    this.passiveImage.inject( this.activeImage.getParent() );
    
    //Set the array of images and add the first one
    this.images = [];
    
    //this.startFader();
  },
  
  /**
   * Adds the image to the image array
   */     
  addImage : function( url ) 
  {
    this.images.include( url );
  },
  
  /**
   * Returns a [random] image from the images array
   * always a different one than the current active image   
   */     
  getImage : function()
  {
    var newImage = this.images.getRandom();
    while( this.activeImage.get('src') == newImage ) {
      newImage = this.images.getRandom();
    }
    return newImage;
  },
  
  /**
   * Start the periodical fading
   */     
  startFader : function()
  {
    //Only work when there are at least 2 images    
    if( this.images.length > 1 )
    {
      //Preload all images and when done start a recurring function
      var loader = new Asset.images( this.images, {  
        onComplete: function() { 
          //log('[done] preloading images');
          var run = function() { this.showImage()}.bind(this);
          run.periodical( this.options.imageSwitchDelay );  
        }.bind(this)
      });  
    }
    
    //this.secondImage.set('src', this.getImage() );
    
    //this.showImage();
  },
  
  /**
   * Shows the new image by fading the old one away
   */     
  showImage : function()
  {
    //Set the new passive image
    //log( 'setting new passive image' );
    this.passiveImage.style.display = 'block';
    this.passiveImage.src = this.getImage();
    
    //Start fading the active image and start un-fading the passive image
      //fade the active image
      //log( 'fade active image' );
      var fade = new Fx.Tween( this.activeImage , {duration: this.options.imageFadeTime} );
      fade.set('opacity',this.options.maxOpacity);
      fade.start('opacity', this.options.maxOpacity, 0 ); 
      
      //unfade the passive image
      //log( 'unfade passive image' );
      var fade = new Fx.Tween( this.passiveImage , {duration: this.options.imageFadeTime} );
      fade.set('opacity',0);
      fade.start('opacity', 0, this.options.maxOpacity ); 
    
    //switch the active & passive image
    var tempImage = $( this.activeImage.id );
    this.activeImage = this.passiveImage;
    this.passiveImage = tempImage;
    
  }
  

});


























/**
 * Enable/disable [toggle] the given input element
 */ 
function toggleInputEnabled( inputID ) {
  if ($( inputID ).disabled == false ) { $( inputID ).disabled = true; }
  else{ $( inputID ).disabled = false; }
}

/**
 * Set the tabs value and submit the form
 */ 
function tabSwitch( formID, setTabID, tabValue )
{
  $(setTabID).value = tabValue;
  $(formID).submit();
}





function initPlayersScored()
{
  var select = $('gameScoredUserID');
  
  //Add the change event to the select
  select.addEvent('change', function(el) {
    showGameAddPlayerScored();
  });
  
  //init the players scored
  getAllPlayerGoals();
  
  
  var bucket = $('players-scored'); //players bucket
  
  bucket.getElements('div.player').each( function(el) {
    
    //remove all the selected players from the option
    var userID = el.getElement('input').get('userID');
    //get the option with the value of userID
    for (i = select.length - 1; i>=0; i--) {
      if (select.options[i].value == userID ) {
        select.remove(i);
      }
    }
    
    //set the onclick event of the image
    el.getElement('img').addEvent('click', function() {
      removePlayerGoal( this.getParent() );
    });
  });
}


function showGameAddPlayerScored()
{
  var playerSelect = $('gameScoredUserID');        //player selected
  var playerOption = playerSelect.options[playerSelect.selectedIndex]; //current selected option
  var playerID = playerOption.value
  var bucket = $('players-scored'); //player bucket
  var canAdd = true;
  
  //firs check if the mail isnt already present
  bucket.getElements('div.player').each( function(el) {
    var userID = el.getElement('input').get('userID');
    if( userID == playerID ) canAdd = false;
  });
  
  //check if the mail input value is correct
  if( playerID != '' && canAdd == true ) {
    
    //remove the option
    playerSelect.remove(playerSelect.selectedIndex);
    
    //Add the player
    var div = new Element('div', {
      'class': 'player'
    }).set('opacity','0');
    
      var playerHtml = playerOption.text;
      var span = new Element('span', {
        'class' : 'name',        
        'html' : playerHtml
      });
      
      var input = new Element('input', {
        'class' : 'nrOfGoals',        
        'type' : 'text',
        'userID' : playerID,
        'name' : 'goals' + playerID,
        'id' : 'goals' + playerID,
        'value' : '1',
        'maxlength' : '2'
      });
      
      var img = new Element('img', {
        'style' : 'float:right;cursor:pointer;',
        'alt' : 'Verwijder email adres',
        'src' : host + 'images/icons/user_delete.png'
      }).addEvent('click', function(el) {
        removePlayerGoal( this.getParent() );
      });
      
    div.adopt( span );
    div.adopt( input );
    div.adopt( img);
    
    bucket.adopt( div );
    div.fade('in');
    
    //update
    getAllPlayerGoals();
  }
}

function removePlayerGoal( container )
{
  container.fade('out');
  
  //remove timeout since fade
  setTimeout( function() { 
    //first re-add the option to the select
    var option = new Option( container.getElement('span').innerHTML , container.getElement('input').get('userID') );
    $('gameScoredUserID')
    try
    {
      $('gameScoredUserID').add( option, null);
    }
    catch (err)
    {
      $('gameScoredUserID').add( option );
    }
    
    container.destroy(); 
    getAllPlayerGoals(); 
  }, 400 );
}


/**
 * Sets [json] all the player goals in the input goals
 */ 
function getAllPlayerGoals()
{
  var bucket = $('players-scored'); //players bucket
  var players = [];
  
  bucket.getElements('div.player').each( function(el) {
    var userID = el.getElement('input').get('userID');
    players.include( userID );
  });
  
  var result = JSON.encode( players );
  $('goalPlayerIds').value = result;
}



function showAccordionFinanceData()
{
  //Accordeon
  $$('div.accordion').each( function(el) {
    var myAccordion = new Accordion( $(el.id), 'h3.finance-toggler', 'div.finance-element', {
      opacity: false,
      onActive: function(toggler, element){
        toggler.set('class', 'finance-toggler-selected');
        element.set('class', 'finance-element-selected');
      },
      onBackground: function(toggler, element){
        toggler.set('class', 'finance-toggler');
        element.set('class', 'finance-element');
        
      },
      start:'all-close'
    });  
  });
}























