/**
* Generic player interface
*/
function Player(el, controls, playlist) {

  this.formatTime = function(seconds) {
    if(seconds == NaN) {
      return '00:00';
    }
    seconds = Math.round(seconds);
    minutes = Math.floor(seconds / 60);
    minutes = (minutes >= 10) ? minutes : "0" + minutes;
    seconds = Math.floor(seconds % 60);
    seconds = (seconds >= 10) ? seconds : "0" + seconds;
    return minutes + ":" + seconds;
  };

  this.live = false;
  this.progressInterval;
  this.el = el;
  this.box = $(el).parents('.box');
  this.controlsEl = controls;
  this.playlistEl = playlist;
  this.controls = {
    'play':      $(this.controlsEl).find('.play').get(0),
    'pause':     $(this.controlsEl).find('.pause').get(0),
    'time':      $(this.controlsEl).find('.time').get(0),
    'progress':  $(this.controlsEl).find('.progress').get(0),
    'len':       $(this.controlsEl).find('.len').get(0),
    'prev':      $(this.controlsEl).find('.prev').get(0),
    'next':      $(this.controlsEl).find('.next').get(0),
    'list':      $(this.controlsEl).find('.list').get(0)
  };

  if($(this.el).attr('controls')) {
    this.el.removeAttribute("controls");
  }

  this.init();

}

Player.prototype.track = function(){
  var that = this;
  this.progressInterval = setInterval(function() { that.updateProgress(); }, 33);
};

Player.prototype.updateProgress = function(){
  var w = $(this.controls.progress).width(),
      pw = Math.floor((w/this.el.duration)*this.el.currentTime);
  if(!this.live) {
    $(this.controls.time).html(this.formatTime(this.el.currentTime));
    $(this.controls.len).html(this.formatTime(this.el.duration));
    $(this.controls.progress).children().css('width', pw+'px');
  } else {
    $(this.controls.time).html(this.formatTime(this.el.currentTime));
    $(this.controls.len).html('Live');
  }
};

Player.prototype.stopTrack = function(){
  clearInterval(this.progressInterval);
};

Player.prototype.load = function(src, live){
  this.pause();
  if(live) {
    this.live = true;
  } else {
    this.live = false;
  }
  this.el.src = src;
  this.el.load();
  $(this.controls.time).html('00:00');
  $(this.controls.len).html('00:00');
  $(this.controls.progress).children().css('width', '1px');
  this.play();
};

Player.prototype.play = function(){
  var box = $(this.el).parents('.box');
  if(this.el.paused) {
    $(this.controls.play).removeClass('paused').addClass('playing');
    $(this.controls.pause).removeClass('paused').addClass('playing');
    $(this.box).removeClass('paused').addClass('playing');
    this.el.play();
    this.track();
  } else {
    this.pause();
  }
};

Player.prototype.pause = function(){
  if(this.el.paused) {
    this.play();
  } else {
    $(this.controls.play).removeClass('playing').addClass('paused');
    $(this.controls.pause).removeClass('playing').addClass('paused');
    $(this.box).removeClass('playing').addClass('paused');
    this.el.pause();
    this.stopTrack();
  }
};

Player.prototype.list = function(){
  $(this.playlistEl).toggle();
};

Player.prototype.navigate = function(dir) {
  var urls = $(this.playlistEl).find('a'),
      next;
  for (var i=0; i < urls.length; i++) {
    if(urls[i].href == this.el.src) {
      if(dir == 'prev' && urls[i-1]) {
        next = urls[i-1].href;
        break;
      } else if(urls[i+1]) {
        next = urls[i+1].href;
        break;
      }
    }
  };
  if(!next && dir == 'prev') {
    next = urls[urls.length-1];
  } else if(!next && dir == 'next') {
    next = urls[0];
  }
  if(next) {
    if($(next).hasClass('live')) {
      this.load(next.href, true);
    } else {
      this.load(next.href, false);
    }
  }
};

Player.prototype.prev = function(){
  this.navigate('prev');
};

Player.prototype.next = function(){
  this.navigate('next');
};

Player.prototype.jump = function(e, target){
  e.stopPropagation();
  e.preventDefault();
  var url = $(e.srcElement).attr('href');
  if(this.el) {
    if($(e.srcElement).hasClass('live')) {
      this.load(url, true);
    } else {
      this.load(url, false);
    }
  }
};

Player.prototype.init = function(){
  var that = this;
  $(this.controls.play).click($.proxy(this.play, this));
  $(this.controls.pause).click($.proxy(this.pause, this));
  $(this.controls.list).click($.proxy(this.list, this));
  $(this.playlistEl).click(function(e) { that.jump(e, this); });
  $(this.controls.prev).click($.proxy(this.prev, this));
  $(this.controls.next).click($.proxy(this.next, this));
  $(this.controls.progress).html('<span></span>');
  if(this.el.autoplay) {
    this.track();
  }
};


$(function(){

  if($('#_position').length) {
    $('#_position').submit(function(e) {
      var boxes = $('.box'),
          data = '',
          box;
      for (var i=0; i < boxes.length; i++) {
        box = $(boxes[i]);
        if(box.data('id')) {
          data += '"'+box.data('id')+'": ["'+box.css('left').slice(0, -2)+'", "'+box.css('top').slice(0, -2)+'"],';
        }
      };
      $(this['d']).val('{'+data.slice(0, -1)+'}');
    });
  }

  $('.toggle').each(function(e) {
    $(this).css('display', 'none');
  });

  $('.clock').each(function(e) {

    var clock = this;
    $(this).html('00:00:00');
    var tick = setInterval(function() { 
      var d = new Date(),
          h = d.getHours(),
          m = d.getMinutes(),
          s = d.getSeconds();
      m = (m < 10 ? '0' : '') + m;
      s = (s < 10 ? '0' : '') + s;
      $(clock).html(h+':'+m+':'+s);
    }, 1000);

  });

  $('div.player').each(function(e) {
    var links = $(this).find('a');
    var p, playerEl, container;

    if($('html').hasClass('no-video') 
        || $('html').hasClass('no-audio')) {

      $(this).find('*').remove();
      $(this).append('<div class="flowplayer"></div><div class="mask"></div>');

      if($(this).data('audio')) {
        p = flowplayer($(this).find('.flowplayer').get(0), {
          wmode: 'transparent',
          log: { level: 'debug' },
          src: '/assets/flowplayer/flowplayer-3.2.7.swf'}, { 
            plugins: { 
              controls: null,
              audio: { url: '/assets/flowplayer/flowplayer.audio-3.2.2.swf' }
            },
            clip:  {
              autoPlay: false,
              autoBuffering: $(this).hasClass('video') ? true : false,
              scaling: 'fit',
              url: $(this).hasClass('video') ? $(this).data('video') : $(this).data('audio')
            }
        });
      } else {
        p = flowplayer($(this).find('.flowplayer').get(0), {
          wmode: 'transparent',
          log: { level: 'debug' },
          src: '/assets/flowplayer/flowplayer-3.2.7.swf'}, { 
            plugins: { 
              controls: null
            },
            clip:  {
              autoPlay: false,
              autoBuffering: $(this).hasClass('video') ? true : false,
              scaling: 'fit',
              url: $(this).hasClass('video') ? $(this).data('video') : $(this).data('audio')
            }
        });
      }

      $(this).find('.mask').click(function() {
        if($(this).parents('.box').hasClass('just-dragged')) {
          $(this).parents('.box').removeClass('just-dragged');
        } else {
          if(p.isPlaying()) {
            p.pause();
          } else {
            p.play();
          }
        }
      });

    } else {

      container = this;
      if($(this).find('video').length) {
        $(container).find('.playlist').hide();
        playerEl = $(this).find('video')[0];
      } else if($(this).find('audio').length) {
        playerEl = $(this).find('audio')[0];
        if(!$(this).find('controls').length) {
          $(this).append('<ul class="controls"><li class="play"></li><li class="paused"></li></ul>');
        }
      }

      p = new Player(playerEl, $(container).find('.controls'), $(container).find('.playlist'));

      $(this).find('.mask').click(function() {
        if($(this).parents('.box').hasClass('just-dragged')) {
          $(this).parents('.box').removeClass('just-dragged');
        } else {
          p.play();
        }
      });

    }

  });

  // set up click/tap panels
  $('.flip-logo').click(function(e) {
    if($(this).hasClass('flipped')) {
      $(this).removeClass('flipped');
    } else {
      $(this).addClass('flipped');
    }
  });

  /**
  * Show/hide events based on their category type
  */
  if($('#spielplan .controls').length) {
    $('#spielplan .controls a').each(function() {
      var sid = $(this).data('filter'),
          els = $('#spielplan tr.category-'+sid);
      if(sid && !els.length) {
        $(this).parent().remove();
      }
    });
    $('#spielplan .controls').addClass('length-'+$('#spielplan .controls a').length);
    $('#spielplan .controls a').click(function(e) {
      e.preventDefault();
      if($(this).parent().hasClass('disabled')) {
        return;
      }
      var id = $(this).data('filter');
      if(id > 0) {
        $('#spielplan tr').hide();
        $('#spielplan .controls li').removeClass('selected');
        $('#spielplan tr.category-'+id).show();
        $('#spielplan tr:visible').each(function(e) {
          $('#spielplan tr.'+$(this).data('month')).show();
        });
        $(this).parent().addClass('selected');
      } else {
        $('#spielplan tr').show();
        $('#spielplan .controls li').removeClass('selected').first().addClass('selected');
      }
    });
  }

  $('#spielplan tr a.more').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var id = this.href.slice(this.href.indexOf('#')+1);
    if($('#'+id).is(':visible')) {
      $('.box').css('zIndex', 0);
      $('#'+id).css('zIndex', 1);
    } else {
      $('.box').css('zIndex', 0);
      $('#'+id).show().css('zIndex', 1);
    }
  });

  $('a.switch').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var id = this.href.slice(this.href.indexOf('#')+1);
    if($('#'+id+' .playlist').length
        && $('#'+id+' video').length
        && $(this).parents('div').find('.playlist').length) {
    } else {
      $('#'+id).toggle();
    }
  });

  $('.closeable, .hideable').each(function() {
    var text = 'schließen';
    if($('html').hasClass('en')) {
      text = 'close';
    }
    if($(this).find('controls').length) {
      $(this).find('controls').append('<li class="close"><a>'+text+'</a></li>');
    } else {
      $(this).find('.wrapper').append('<ul class="controls"><li class="close"><a>'+text+'</a></li></ul>');
    }
  });

  /**
  * Collect text into columns based on a "split" <HR> el
  */
  if($('.columns').length) {
    $('.columns').each(function() {
      var el = $(this).find('.wrapper'),
          hr = $(this).find('hr'),
          children = $(el).children(':not(h1)'),
          cols = [],
          h = 0;
      cols[h] = document.createElement('div');
      if(hr.length > 0) {
        for (var i=0; i < children.length; i++) {
          if(children[i] == hr[h]) {
            h++;
            cols[h] = document.createElement('div');
          } else {
            $(cols[h]).append($(children[i]).clone(true));
          }
        };
      }
      $(el).find(':not(h1)').remove();
      $(cols).addClass('col').each(function(e) {
        $(el).find('*').show();
        $(el).append(this);
      });
    });
  }

  /**
  * Destory and re-build all iframes in the context element.  This is the
  * hack to stop YouTube/Vimeo/etc videos from playing once the window is
  * closed.
  */
  var reFrame = function() {
    var iframes = $(this).find('iframe'),
        clone;
    if(iframes.length) {
      for (var i=0; i < iframes.length; i++) {
        clone = $(iframes[i]).clone(true);
        $(iframes[i]).replaceWith(clone);
      };
    }
  };

  /**
  * Open a .closeable box
  */
  var openBox = function() {
    $(this).removeClass('closed');
    $(this).find('.wrapper').children().show();
    $('.closeable').css('zIndex', 0);
    $(this).css('zIndex', 1); 
  };

  /**
  * Close a .closeable box
  */
  var closeBox = function() {

    var el = this;

    if($(this).find('.wrapper').length) {
      el = $(this).find('.wrapper').get(0);
    }

    $(el).children().hide();
    $(el).find('>:first-child').show();

    if(!$(this).hasClass('closed')) {
      $(this).addClass('closed');
    }

    reFrame.apply(this);

  };

  if($('.closed').length) {
    $('.closed').each(closeBox);
  }

  $('.closeable .close').click(function(e) {
    e.stopPropagation();
    closeBox.apply($(this).parents('.box'));
  });

  $('.closeable >:first-child').click(function(e) {
    openBox.apply($(this).parents('.box'));
  });

  $('.hideable .close').click(function() {
    $(this).parents('.box').hide();
    reFrame.apply($(this).parents('.box'));
  });

  $('.box').each(function() {
    var x = $(this).data('x'),
        y = $(this).data('y');
    if(x) {
      $(this).css('left', x+'px');
    }
    if(y) {
      $(this).css('top', y+'px');
    }
  });

  $('.drag').draggable({
    start: function(e) { 
      $('.drag').css('zIndex', 0);
      $(this).css('zIndex', 1); 
      $(this).addClass('just-dragged'); 
    }
  });

  $('.box').click(function(e) {
    $('.box').css('zIndex', 0);
    $(this).css('zIndex', 1); 
  });

  if(window.location.hash.length > 0) {
    var sid = window.location.hash.slice(1);
    if($('#'+sid).length) {
      if($('body').hasClass('service')) {
        openBox.apply($('#'+sid));
      } else {
        $('#'+sid).show();
      }
    }
  }

  // if($('body').hasClass('service') && window.location.hash.length) {
  //   var match = window.location.hash.match(/open-(.*)/);
  //   if (match[1]) {
  //     var el = $('.'+match[1]);
  //     openBox.apply(el);
  //   }
  // }

});
