var background = {
  update: false,
  
  check: function()
  {
    if(background.update)
    {
      background.update = false;
      background.draw();
    }
  },
  
  init: function()
  {
    this.timer = setInterval(this.check, 1000);
    this.draw();
  },
  
  draw: function()
  {
    var logo = $('#logo');
    var position = logo.offset();
    var width = logo.outerWidth();
    var height = logo.outerHeight();
    var margin = 20;
    
    var canvas = document.getElementById("background");
    $(canvas).attr('width', $(window).width() * 1.5);
    $(canvas).attr('height', $(document).height());
    var ctx = canvas.getContext("2d");
    
    for(var i=-38; i<$(window).width() * 1.5; i+=228)
    {
      for(var j=-64, k=0; j<600; j+=64, k++)
      {
        if(
          i + ((k%2)*114) > margin + (position.left + width) ||
          margin + i + ((k%2)*114) + 152 < position.left ||
          j > margin + position.top + height
        )
        {
          this.createSprite(ctx, i + ((k%2)*114), j);
        }
      }
    }
  },
  
  createSprite: function(ctx, startX, startY)
  {
    var random = Math.round(Math.random()*1);
    var colors = Array(
      '199,52,140',
      '92,36,131',
      '176,170,167',
      '250,220,235',
      '238,119,139',
      '237,188,129',
      '212,214,161',
      '145,210,243',
      '0,147,189',
      '166,198,234',
      '118,198,193',
      '231,65,25',
      '234,75,111',
      '236,236,236',
      '231,209,171',
      '0,87,124',
      '2,88,100',
      '204,94,3',
      '60,60,60',
      '243,156,162',
      '198,184,26',
      '223,59,75',
      '202,213,17',
      '107,29,47',
      '207,91,114'
    );
    switch(random)
    {
      case 1:
        ctx.fillStyle = "rgb(" + colors[Math.round(Math.random()*colors.length)] + ")";
        ctx.beginPath();
        ctx.moveTo(startX, startY + 64);
        ctx.lineTo(startX + 38, startY);
        ctx.lineTo(startX + 38 + 76, startY + 128);
        ctx.lineTo(startX + 38, startY + 128);
        ctx.fill();
            
        ctx.fillStyle = "rgb(" + colors[Math.round(Math.random()*colors.length)] + ")";
        ctx.beginPath();
        ctx.moveTo(startX + 38, startY);
        ctx.lineTo(startX + 38 + 76, startY);
        ctx.lineTo(startX + 38 + 76 + 38, startY + 64);
        ctx.lineTo(startX + 38 + 76, startY + 128);
        ctx.fill();
      break;
      default:
        ctx.fillStyle = "rgb(" + colors[Math.round(Math.random()*colors.length)] + ")";
        ctx.beginPath();
        ctx.moveTo(startX, startY + 64);
        ctx.lineTo(startX + 38, startY);
        ctx.lineTo(startX + 38 + 76, startY);
        ctx.lineTo(startX + 38, startY + 128);
        ctx.fill();
        
        ctx.fillStyle = "rgb(" + colors[Math.round(Math.random()*colors.length)] + ")";
        ctx.beginPath();
        ctx.moveTo(startX + 38 + 76, startY);
        ctx.lineTo(startX + 38 + 76 + 38, startY + 64);
        ctx.lineTo(startX + 38 + 76, startY + 128);
        ctx.lineTo(startX + 38, startY + 128);
        ctx.fill();
      break;
    }
  }
}

var counter = {
  timer: null,
  eday: new Date("September 20, 2012 09:30:00"),
  edayEnd: new Date("September 20, 2012 19:00:00"),
  eday2012: new Date("September 12, 2013 00:00:00"),
  msPerDay: 24 * 60 * 60 * 1000,
  init: function() {
    counter.draw();

    counter.timer = setInterval(function(){
      counter.draw();
    }, 1000);
  },
  draw: function() {

    var time = new Date();
    var timeLeft = counter.eday.getTime() - time.getTime();
    var counting = false;
    var past = false;
    if(timeLeft < 0){
      counting = true;
      timeLeft = counter.edayEnd.getTime() - time.getTime();
    }
    if(timeLeft < 0){
      counting = false;
      past = true;
      timeLeft = counter.eday2012.getTime() - time.getTime();
    }

    var tempDaysLeft = timeLeft / counter.msPerDay;
    var daysLeft = Math.floor(tempDaysLeft);

    var tempHoursLeft = (tempDaysLeft - daysLeft)*24;
    var hoursLeft = Math.floor(tempHoursLeft);

    var tempMinutesLeft = (tempHoursLeft - hoursLeft)*60;
    var minutesLeft = Math.floor(tempMinutesLeft);

    var tempSecondsLeft = (tempMinutesLeft - minutesLeft)*60;
    var secondsLeft = Math.floor(tempSecondsLeft);
    
    var text = 'Emerce eDay ' + (counting ? 'eindigt' : 'begint')  + ' over:<div id="countdown"><div id="days">' + daysLeft + ' <span>dag' + (daysLeft != 1 ? 'en' : '') + '</span>' + '</div><div id="hours">' + (hoursLeft > 0 ? hoursLeft + ' <span>uur</span> ' : '') + '</div><div id="minutes">' + (minutesLeft > 0 ? minutesLeft + ' <span>' + (minutesLeft == 1 ? 'minuut' : 'minuten') + '</span> ' : '') + '</div><div id="seconds">' + secondsLeft + ' <span>' + (secondsLeft == 1 ? 'seconde' : 'seconden') + '</span></div></div>';

    $('#counter').html(text);
  }
}

var spotlight = {
  current: 0,
  interval: null,

  init: function()
  {
    $('a', '#spotlight-pagination').live('click', function(e)
    {
      e.preventDefault();
      clearInterval(spotlight.interval);
      $('#spotlight').load($(this).attr('href'));
    });

    spotlight.interval = setInterval(function()
    {
      spotlight.current++;
      if(spotlight.current > $('a', '#spotlight-pagination').length - 1)
      {
        spotlight.current = 0;
      }
      $('#spotlight').load($('a:eq(' + spotlight.current + ')', '#spotlight-pagination').attr('href'));
    }, 5000);
  }
}

var myEday = {
  init: function(){
    $('#my-eday-preview li a.remove').live('click', function(e){
      e.preventDefault();

      var answer = confirm('Weet u zeker dat u dit programma uit uw My Eday wilt verwijderen?');

      if(answer){
        var link = $(this);
        var textHolder = link.next();
        var text = textHolder.text();
        var newText = '';
        var i = 0;

        $.ajax({
          url: link.attr('href')
        });

        link.data('interval', setInterval(function(){
          if(i < text.length){
            newText+= text.substr(i, 2);
            i+= 2;
            textHolder.html('<span>' + newText + '</span>' + text.substr(i, text.length - 1));
          }else{
            clearInterval(link.data('interval'));
            link.parent().slideUp();
          };
        }, 50));
      };
    });
  }
};

var program = {
  section: 'indoor',
  
  init: function()
  {
    if($('#program').length)
    {
      this.setTips();
      
      this.navigation = $('#navigation');
      this.titlesHolder = $('#room-titles-holder');
      this.titles = $('#room-titles');
      var self = this;
      
      $(window)
        .scroll(function()
        {
          self.setFixedObjects();
        })
        .resize(function()
        {
          self.setFixedObjects();
        });
      
      $('.remove-program, .add-program')
        .live('click', function(e){
          var page = window.location;
          e.preventDefault();
  
          $.ajax({
            url: $(this).attr('href'),
            success: function(response){
              $('#timetable-holder').html(response);
              $('#timetable .presentation').fhHover();
              $('#popup-message').achtung({timeout:4});
            }
          });
        });
      
      this.btnOutdoor = $('#btn-outdoor');
      this.btnIndoor = $('#btn-indoor').addClass('inactive');
      
      $('#btn-print').bind('click', function(e)
      {
        e.preventDefault();
        window.print();
      });
      this.btnOutdoor.bind('click', function(e)
      {
        e.preventDefault();
        $(this).addClass('inactive');
        self.btnIndoor.removeClass('inactive');
        $('#program-shade').fadeOut();
        if(self.section == 'indoor')
        {
          self.section = 'outdoor';
          $('#room-contents, #room-titles').animate(
          {
            'left': 921 - $('#room-contents').outerWidth() + 1
          }, 500);
        }
      });
      this.btnIndoor.bind('click', function(e)
      {
        e.preventDefault();
        $(this).addClass('inactive');
        self.btnOutdoor.removeClass('inactive');
        $('#program-shade').fadeIn();
        if(self.section == 'outdoor')
        {
          self.section = 'indoor';
          $('#room-contents, #room-titles').animate(
          {
            'left': 0
          }, 500);
        }
      });
    }
  },
  
  setFixedObjects: function()
  {
    var scrollPosition = $(window).scrollTop();
    this.roomsOffset = $('#room-contents').offset();
    this.timetableOffset = $('#timetable').offset();
    if((this.roomsOffset.top - 100) - scrollPosition <= 0)
    {
      this.navigation.css({
        'position': 'fixed',
        'left': this.timetableOffset.left + 56
      });
      this.titlesHolder.css({
        'position': 'fixed',
        'left': this.timetableOffset.left + 57,
        'top': 31         
      });
      this.titles.css({
        'position': 'absolute',
        'left': this.roomsOffset.left - (this.timetableOffset.left + 57),
        'top': 0
      });
    }
    else
    {  
      this.navigation.css({
        'position': 'absolute',
        'left': 56
      });
      this.titlesHolder.css({
        'position': 'relative',
        'left': 0,
        'top': 0          
      }); 
      this.titles.css({
        'position': 'relative',
        'left': (this.section == 'indoor' ? 0 : 921 - $('#room-contents').outerWidth() + 1),
        'top': 0
      });
    }
  },

  setTips: function(){
    $('.presentation', '#timetable').each(function(index){
      var link = $(this).find('[rel=fhhLocation]');
      if(link.length){
        $(this).qtip({
          content: {
            url: link.attr('href')
          },
          show: {
            delay: 500
          },
          hide: {
            fixed: true,
            delay: 300
          },
          style: {
            width: 300,
            padding: 5,
            border: {
              width: 7,
              radius: 5
            },
            tip: 'bottomMiddle',
            name: 'light'
          },
          position: {
            corner: {
              target: 'topMiddle',
              tooltip: 'bottomMiddle'
            }
          }
        });
      };
    });
  }
};

var sponsors = {
  init: function()
  {
    $('#silver-sponsors-preview, #bronze-sponsors-preview, #playgrounders-preview, #partners-preview').cycle({ 
      fx:      'scrollLeft', 
      speed:    500,
      timeout:  4000
    });
  }
}

$(function(){
  counter.init();
  spotlight.init();
  myEday.init();
  program.init();
  sponsors.init();

  if($.fn.fhHover){
    $('#timetable .presentation, #news-list li, #speakers-list li, #hotels li').fhHover();
  }

  if($.fn.gzGallery){
    $('#partners, #playgrounders, #silver-sponsors, #bronze-sponsors').gzGallery({
      method: 'slide',
      counter: false
    });
  }
  
  $('[rel*=external]').live('click', function(e)
  {
    $(this).attr('target', '_blank');
  });

});
