var start_player = false;
var omroepStart = false;

jQuery(function($) {
  $.fn.runningClock = function() {
    return $(this).each(function() {
      var $time = $(this);
      var match = $time.html().match(/([0-9]{2}):([0-9]{2})/)
      
      if(match) {
        var hours   = parseInt(match[1].replace(/^0/, ''));
        var minutes = parseInt(match[2].replace(/^0/, ''));
        
        var localTime  = new Date();
        var serverTime = new Date(localTime.getFullYear(),
                                  localTime.getMonth(),
                                  localTime.getDate(),
                                  hours, minutes,
                                  localTime.getSeconds());
        
        $time.updateClock(serverTime);
      }
    })
  };
  
  $.fn.updateClock = function(serverTime) {
    var update = function(startTime, $element) {
      return function() {
        var newTime = new Date(startTime.getTime() + 1000);        
        var hours   = newTime.getHours() < 10 ? "0" + newTime.getHours() : newTime.getHours();
        var minutes = newTime.getMinutes() < 10 ? "0" + newTime.getMinutes() : newTime.getMinutes();  
             
        $element.html(hours + ":" + minutes);        
        $element.updateClock(newTime);
      }
    }(serverTime, $(this));
    
    setTimeout(update, 1000);
  }
  
  $.fn.suckyNews = function() {
    return this.each(function() {
      var $archive = $(this);
      $archive.children('.images').slice(0,1).remove();
    });
  }
  
  $.fn.awesomeNews = function() {
    return this.each(function() {
      var $archive = $(this);
      var $images  = $archive.find('.image img');
      
      if($archive.is('.awesome')) {
        return this;
      } else {
        $archive.addClass('awesome');
      }
      
      if($images.length > 0) {
        $archive.children('.articles').before('<ol class="images"></ol>');
        
        $images.each(function($_archive) {
          return function() {
            var $image   = $(this);
            var $article = $image.parents('.article');
            var $title   = $article.find('h2 a').slice(0,1);
            var $anchor  = $image.parent();
            var $_container = $_archive.children('ol.images').slice(0,1);

            $_container.append('<li><img src="' + $anchor.attr('href') + '"><a href="' + $title.attr('href') + '">' + $title.html() + '</a></li>');  
          }
        }($archive));
      }
      
      $archive.find('.article').awesomeArticle().slice(0,1).mouseover();
    });
  }
  
  $.fn.awesomeArticle = function() {
    return this.each(function() {
      var $article = $(this);
      
      if($article.is('.awesome')) {
        return this;
      } else {
        $article.addClass('awesome');
      }
      
      var $archive = $article.parents('.archive');
      var $title   = $article.find('h2 a').slice(0,1);
      var $images  = $archive.children('ol.images');
      var $image   = $images.find('a[href$="' + $title.attr('href') + '"]').parent();
      
      $article.mouseover(function($_images, $_image) {
        return function() {
          $_images.find('.active').removeClass('active');
          $_image.addClass('active');
        }
      }($images, $image));
      
      $article.click(function() {
        var $anchor = $(this).find('a').slice(0,1);
        window.location = $anchor.attr('href');
        return false;
      }).css('cursor', 'pointer')
      
      $image.click(function() { return false; })
    });
  }
  
  $.fn.toggleMedia = function() {
    return this.each(function() {
      var $media  = $(this);    

      if($media.is('.collapsed')) {
        $media.openMedia();
      } else {
        $media.closeMedia();
      }
    });
  }
  
  $.fn.embedPlayer = function() {
    var $media = $(this);
    if($media.is('.audio')) {
      var $audio = $media.find('.media');
      var file   = $audio.find('a').attr('href');
      
      var variables  = { 'file' : file };
      var parameters = { 'allowfullscreen' : 'true',
                         'allowscriptaccess' : 'always',
                         'wmode' : 'opaque',
                         'id' : $audio.attr('id') };
      var attributes = { 'id' : $audio.attr('id'), 'name' : $audio.attr('id') };
    
      swfobject.embedSWF('/javascripts/media_player/player.swf',$audio.attr('id'),'560','20','9.0.124',false,variables,parameters,attributes);
    }
  }
  
  $.fn.openMedia = function() {
    return this.each(function() {
      var $media = $(this);
      $media.embedPlayer();
      
      var $media_to_close = $media.parents('.audio_collection, .video_collection').find('li.audio:not(.collapsed), li.video:not(.collapsed)');
      $media_to_close.closeMedia();
      
      $media.removeClass('collapsed');
      var new_height = $media.height();
      
      $media.addClass('collapsed');
      $media.animate({ 'height' : new_height }, 750, function() { $(this).removeClass('collapsed').css({ 'height': '' }); });
      
      if($media.is('.audio')) {
        $media.startPlaying();
      }
    });
  }
  
  $.fn.closeMedia = function() {
    return this.each(function() {
      var $media = $(this);
      
      $media.stopPlaying();

      var current_height = $media.height();            
      $media.css({ 'height' : '' }).addClass('collapsed');  
                
      var new_height = $media.height();
      $media.removeClass('collapsed');
      
      $media.css({ 'height' : current_height });
      $media.animate({ 'height' : new_height }, 800, function() { $(this).addClass('collapsed').css({ 'height': '' }); });
    });   
  }
  
  $.fn.collapsableMedia = function() {
    return this.each(function() {
      var $media  = $(this);    
      var $header = $media.find('h3');

      if($header.find('.collapse-state').length == 0) {
        $header.append('<span class="collapse-state"></span>'); 
        $media.addClass('collapsed');
        
        $header.click(function() { $(this).parent('li.audio,li.video').toggleMedia(); });
      }
    })
  }
  
  $.fn.startPlaying = function() {
    return this.each(function() {
      window.setTimeout(function() {
        $(this).find('object, embed').each(function() { this.sendEvent("PLAY", true); });
      }, 1000);
    });
  }
  
  $.fn.stopPlaying = function() {
    return this.each(function() {
      window.setTimeout(function() {
        $(this).find('object, embed').each(function() { this.sendEvent("STOP", true); });
      }, 1000);
    });
  }
  
  $.fn.poll = function() {
    var $poll = $(this);
    var $form = $poll.find('form');

    $form.find('input[type=submit]').hide();
    $form.find('input[type=radio]').change(function($_poll, $_form) {
      return function() {
        var $input = $(this);
        
        var attributes = {};
        attributes[$input.attr('name')] = $input.attr('value');

        $.post($_form.attr('action'), attributes,
          function(data, textStatus) {
            $_poll.replaceWith(data);
          }
        );
      }
    }($poll, $form));
  }
  
  $.fn.pollArchive = function() {
    var $archive = $(this);
    
    $archive.find('.older a:not(.poll-archive-click-added), .older .poll:not(.poll-archive-click-added)').click(function() {
      var $anchor = $(this).is('a')   ? $(this) : $(this).parents('.older > li').find('a');
      var $poll = $(this).is('.poll') ? $(this) : $(this).parent().find('.poll');
      var $visible_polls = $(this).parents('.older').find('li .poll:visible');

      if($poll.is(":hidden")) {
        $anchor.hide();
        $poll.show();
      }
      
      $visible_polls.each(function() {
        var $poll   = $(this);
        var $anchor = $(this).parents('.older > li').find('a');
        $poll.hide();
        $anchor.show();
      });
      
      return false;
    }).addClass('poll-archive-click-added');
  }
  
  $.omroepStart = function() {
    $('.date-and-time .time').runningClock();
    $('.poll').poll();
    $('#content .archive').awesomeNews();
    $('#content > .video_collection li.video, ' +
      '#content > .cms-container > .cms-content > .video_collection li.video, ' +
      '#content > .audio_collection li.audio, ' +
      '#content > .cms-container > .cms-content > .audio_collection li.audio').collapsableMedia();
    $('.poll_collection').pollArchive();
    $('#aside .program').tabs({});
    $('#aside .program .ui-tabs-panel, #aside .program .ui-tabs-nav').css({display:''});
  }
  
  $.omroepStart();
    
  jQuery(function($) {    
    if(typeof $.monster != 'undefined') {
      if(!$.omroepStartLoaded) {
        $.getScript("/themes/omroep_start/javascript/omroepstart.js", function() {
          $.monster.afterChange($.omroepStart);    
        });

        $.omroepStartLoaded = true;
      }
    }
  });
});