// Version SVN: $Id: webtv.js.php 8189 2009-02-16 16:31:17Z sven $
var playlist = new Object();
playlist.scrollElement = null;
playlist.currentMedia = null;
playlist.currentUser = null;
playlist.itemWidth = null;
playlist.playlistID = null;
playlist.dragID = null;
playlist.autofill = true;
playlist.tweener = null;
playlist.autofillEffect = null;
playlist.autofillElementColor = null;
playlist.autofillElementColorSelected = null;
playlist.hideTimeout = null;

var contentBrowser = new Object();
contentBrowser.displayItems = 8;
contentBrowser.activeTab = null;
contentBrowser.tabs = null;
contentBrowser.tabElements = null;
contentBrowser.lists = null;
contentBrowser.tabState = new Array();
contentBrowser.tabIndexes = new Object();

var playerInstance = null;

function initWebTV() {
  document.ondragstart = function () { return false; }; //IE drag hack

  // Create a test playlist element
  playlist.currentMedia = currentMedia;
  playlist.currentUser = currentUser;
  var test = addPlaylistItem({'id': 0, 'description_pic': '', 'title': ''});
  playlist.itemWidth = test.getSize().x;
  removePlaylistItem(test);

  // Initialize the scroller and browsers
  playlist.scrollElement = new Fx.Scroll('playlistcontainer');
  playlist.scrollElement.addEvent('complete', function() { $('playlistitems').set('container_scroll', $('playlistcontainer').scrollLeft); $('playlistitems').set('targetmargin', $('playlistcontainer').scrollLeft); });

  playlist.tweener = new Fx.Tween('playlistitems', {'property': 'margin-left', 'link': 'chain'});
  $('playlistitems').set('targetmargin', 0);

  if ($('searchfield')) {
    $('searchfield').addEvent('change', changeSearch);
    $('searchfield').addEvent('keyup', keyUpSearch);
  }

  playlist.autofillEffect = new Fx.Morph('autofillselect', {link: 'chain', duration: 'long', transition: Fx.Transitions.Sine.easeInOut});
  playlist.autofillElementColorSelected = $('autofillselect').getStyle('color');
  $('autofillselect').removeClass('selected');
  playlist.autofillElementColor = $('autofillselect').getStyle('color');

  contentBrowser.tabs = $('browsertabs').getChildren();
  for (var i = 0; i < contentBrowser.tabs.length; i++) {
    eval('contentBrowser.tabs['+ i +'].addEvent(\'click\', function() { setContentActiveTab('+ i +');});');
    contentBrowser.tabState[i] = {'type' : contentBrowser.tabs[i].getProperty('id').slice(11), 'loaded' : false, 'changed' : true, 'offset' : 0, 'numElements' : 24, 'search' : ''};
    contentBrowser.tabIndexes[contentBrowser.tabState[i].type] = i;
    contentBrowser.tabState[i].loader = $('loader_'+ contentBrowser.tabState[i].type);

    switch (contentBrowser.tabState[i].type) {
      case 'related':
        contentBrowser.tabState[i].search = playlist.currentMedia;
        break;

      case 'user':
        contentBrowser.tabState[i].search = playlist.currentUser;
        break;

      case 'search':
        contentBrowser.tabState[i].loaded = true;
        contentBrowser.tabState[i].changed = false;
        break;
    }
  }

  contentBrowser.tabElements = $$('.contentcontainer');
  contentBrowser.lists = $$('.contentitems');

  if ($('autofillselect')) {
    $('autofillselect').set('html', (playlist.autofill) ? language.playlist_autofill_on : language.playlist_autofill_off);
  }

  hideAllContentTabs();
  setContentActiveTab(0);
}

function playerLoadComplete() {
  playerInstance = swfobject.getObjectById('flvplayer');
  if (playerInstance) {
    try {
      playerInstance.setAutoMode(playlist.autofill);
    }
    catch (e) {
      alert(language.playerobject_not_found);
      playlist.autofill = false;

      if ($('autofillselect')) {
        $('autofillselect').set('html', (playlist.autofill) ? language.playlist_autofill_on : language.playlist_autofill_off);
      }
    }
  }
}

function str_replace(search, replace, subject) {
  return subject.split(search).join(replace);
}

function typeOf(value) {
  var s = typeof value;
  if (s === 'object') {
    s = (value) ? ((value instanceof Array) ? 'array' : 'object') : 'null';
  }

  return s;
}

function genRatingStars(rating) {
  var stars = '';
  rating = Math.floor(rating);
  for (var i = 0; i < 5; i++) {
    var star = (rating >= i+1) ? 'star-on.png' : 'star-off.png';
    stars += str_replace('{$star}', star, ratingStar);
  }

  return stars;
}

function genDuration(seconds) {
  seconds = parseInt(seconds);
  if (seconds < 60) {
    return '0:'+ ((seconds < 10) ? '0' : '') + seconds;
  }

  var minutes = Math.floor(seconds / 60);
  seconds -= minutes * 60;

  return minutes +':'+ ((seconds < 10) ? '0' : '') + seconds;
}

/**
 *  Callback functions for the player
 */
function playNextMedia() {
  var element = $$('.playlistitem.act');
  if (!element.length) {
    return;
  }
  element = element[0];

  if (element.getNext()) {
    seekToMedia(element.getNext().get('mediaid'));
  }
  else {
    seekToMedia(element.getParent().getFirst().get('mediaid'));
  }
}

function playPreviousMedia() {
  var element = $$('.playlistitem.act');
  if (!element.length) {
    return;
  }
  element = element[0];

  if (element.getPrevious()) {
    seekToMedia(element.getPrevious().get('mediaid'));
  }
  else {
    seekToMedia(element.getParent().getLast().get('mediaid'));
  }
}

function seekToMedia(id) {
  if (id == playlist.currentMedia) {
    return;
  }

  var newElement = $('playlistitem_'+ id);
  if (!newElement) {
    return;
  }

  playlist.currentMedia = id;
  playlist.currentUser = newElement.get('user');

  var relatedTabIndex = getContentTabIndexByType('related');
  var userTabIndex = getContentTabIndexByType('user');

  if (relatedTabIndex != null) {
    contentBrowser.tabState[relatedTabIndex].search = playlist.currentMedia;
    contentBrowser.tabState[relatedTabIndex].changed = true;
    reloadContentTab(relatedTabIndex);
  }
  if (userTabIndex != null) {
    if (contentBrowser.tabState[userTabIndex].search != playlist.currentUser) {
      contentBrowser.tabState[userTabIndex].search = playlist.currentUser;
      contentBrowser.tabState[userTabIndex].changed = true;
      reloadContentTab(userTabIndex);
    }
  }

  $$('.playlistitem.act').removeClass('act');
  newElement.addClass('act');

  itemStart = newElement.getPosition($('playlistitems')).x;
  if (itemStart < $('playlistcontainer').scrollLeft) {
    scrollPlaylist(Math.floor(itemStart / playlist.itemWidth), true);
  }
  else if ((itemStart + playlist.itemWidth) > ($('playlistcontainer').scrollLeft + parseInt($('playlistcontainer').getStyle('width')))) {
    scrollPlaylist(Math.floor(itemStart / playlist.itemWidth), true);
  }
}

function playMedia() {
}

function pauseMedia() {
}

function teaseMedia() {
}

function addToPlaylist(items, position, autoFill) {
  if (typeof autoFill == 'string') {
    autoFill = (autoFill == 'true');
  }
  else {
    autoFill = autoFill || false;
  }

  // For now, we'll accept only one element since flash seems to mess up JavaScript arrays
  addPlaylistItem(items, position, autoFill);
/*	for (var i = 0; i < items.length; i++) {
    addPlaylistItem(items[i]);
  }*/
}

function syncPlaylist(items) {
  $('playlistitems').empty();
  addToPlaylist(items);
}

/**
 * General functions
 */
function removeItem(item) {
  item.destroy();
}

function webTVHTMLResult(container, r) {
  showPlaylistManager(false);

  if (!r.responseXML || !r.responseXML.documentElement) {
    return;
  }

  var docElement = r.responseXML.documentElement;

  var action = docElement.getElementsByTagName('action')[0].firstChild.data;
  var result = docElement.getElementsByTagName('result')[0].firstChild.data;

  switch (action) {
    case 'display':
      showPlaylistManager(true);
      $(container).set('html', result);
      break;

    case 'playlistsaved':
      playlist.playlistID = result;
      var content = docElement.getElementsByTagName('content')[0].firstChild.data;

      if (content) {
        showPlaylistManager(true);
        $(container).set('html', content);
        playlist.hideTimeout = window.setTimeout(function() { showPlaylistManager(false); }, 2000);
      }
      break;

    case 'loadplaylist':
      playlist.playlistID = result;
      if (playlist.autofill) {
        toggleAutoFill();
      }
      if (playerInstance) {
        try {
          playerInstance.loadPlaylist(result);
        } catch (e) { }
      }
      break;

    case 'deleteplaylist':
      playlist.playlistID = 0;
      var content = docElement.getElementsByTagName('content')[0].firstChild.data;

      if (content) {
        showPlaylistManager(true);
        $(container).set('html', content);
        playlist.hideTimeout = window.setTimeout(function() { showPlaylistManager(false); }, 2000);
      }
      break;
  }
}

/**
 * Playlist
 */
function newPlaylist() {
  if (playlist.autofill) {
    toggleAutoFill();
  }

  clearPlaylist();
}

function clearPlaylist(internal) {
  internal = internal || false;
  if (!internal && playerInstance) {
    try {
      playerInstance.clearPlaylist();
    } catch (e) { }
  }
  $('playlistitems').empty();

  playlist.playlistID = null;
  playlist.currentMedia = null;
  playlist.currentUser = 0;

  updatePlaylistWidth();
  showPlaylistManager(false);
  scrollPlaylist(0, true);
}

function savePlaylist() {
  if (!playlist.playlistID) {
    var playlistItems = $('playlistitems').getChildren();
    var playlistIDs = new Array();
    for (i = 0; i < playlistItems.length; i++) {
      if (!playlistItems[i].get('mediaid')) {
        continue;
      }
      playlistIDs[playlistIDs.length] = playlistItems[i].get('mediaid');
    }
    var ids = 'ids='+playlistIDs.join(',');

    showPlaylistManager(true);
    new Request(
      {
        url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=saveplaylist',
        method: 'post',
        onComplete: function(){webTVHTMLResult('playlistmanage', this.xhr);},
        onFailure: function(e){showError(this.xhr)},
        data: ids
      }
    ).send();
  }
  else {
    savePlaylistAs();
  }
}

function showLoadPlaylist() {
  new Request(
    {
      url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=loadplaylist',
      method: 'post',
      onComplete: function(){webTVHTMLResult('playlistmanage', this.xhr);},
      onFailure: function(e){showError(this.xhr)}
    }
  ).send();
}

function loadPlaylist() {
  var playlistIdentifier = '';
  if ($('playlistid_id')) {
    playlistIdentifier = 'playlistid='+ $('playlistid_id').value;
  }

  new Request(
    {
      url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=loadplaylist',
      method: 'post',
      onComplete: function(){webTVHTMLResult('playlistmanage', this.xhr);},
      onFailure: function(e){showError(this.xhr)},
      data: playlistIdentifier
    }
  ).send();
}

function showDeletePlaylist() {
  new Request(
    {
      url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=deleteplaylist',
      method: 'post',
      onComplete: function(){webTVHTMLResult('playlistmanage', this.xhr);},
      onFailure: function(e){showError(this.xhr)}
    }
  ).send();
}

function deletePlaylist() {
  var playlistIdentifier = '';
  if ($('playlistid_id')) {
    playlistIdentifier = 'playlistid='+ $('playlistid_id').value;
  }

  new Request(
    {
      url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=deleteplaylist',
      method: 'post',
      onComplete: function(){webTVHTMLResult('playlistmanage', this.xhr);},
      onFailure: function(e){showError(this.xhr)},
      data: playlistIdentifier
    }
  ).send();
}

function savePlaylistAs() {
  // Save a playlist under a given name
  var playlistName = ($('playlistname_id')) ? $('playlistname_id').value : '';
  var playlistIdentifier = '';

  if (playlist.playlistID) {
    playlistIdentifier = 'playlistid='+ playlist.playlistID;
  }
  else {
    if (playlistName) {
      playlistIdentifier = 'name='+ playlistName;
    }
  }

  if (playlistIdentifier) {
    var playlistItems = $('playlistitems').getChildren();
    var playlistIDs = new Array();
    for (i = 0; i < playlistItems.length; i++) {
      if (!playlistItems[i].get('mediaid')) {
        continue;
      }
      playlistIDs[playlistIDs.length] = playlistItems[i].get('mediaid');
    }
    var ids = 'ids='+playlistIDs.join(',');

    new Request(
      {
        url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=saveplaylist',
        method: 'post',
        onComplete: function(e){webTVHTMLResult('playlistmanage', this.xhr)},
        onFailure: function(e){showError(this.xhr)},
        data: ids +'&save=1&'+ playlistIdentifier
      }
    ).send();
  }
}

function showPlaylistManager(status) {
  if (playlist.hideTimeout) {
    window.clearTimeout(playlist.hideTimeout);
    playlist.hideTimeout = null;
  }

  $('playlistcontainer').setStyle('display', (status) ? 'none' : 'block');
  $('playlistmanage').setStyle('display', (status) ? 'block' : 'none');
  $('playlistmanage').empty();
}

function scrollPlaylist(amount, isAbsolute) {
  isAbsolute = isAbsolute || false;
  var scroll = amount * playlist.itemWidth;
  if (!isAbsolute) {
    scroll += $('playlistcontainer').scrollLeft;
  }
  playlist.scrollElement.start(scroll, 0);
}

function scrollPlaylistDrag(amount, isAbsolute) {
  isAbsolute = isAbsolute || false;
  var scroll = amount * playlist.itemWidth
  if (!isAbsolute) {
    scroll = parseInt($('playlistitems').get('targetmargin')) - scroll;
  }

  var size = $('playlistcontainer').getSize();

  if (scroll > 0) {
    scroll = 0;
  }
  else if ((size.x - scroll) > $('playlistitems').getStyle('width')) {
    scroll = $('playlistitems').getStyle('width') - size.x;
  }

  $('playlistitems').set('targetmargin', scroll);
  playlist.tweener.start(parseInt($('playlistitems').get('targetmargin')), scroll);
//	$('playlistitems').tween('margin-left', $('playlistitems').getStyle('margin-left'), scroll);
//	$('playlistitems').setStyle('margin-left', scroll);
}

function createPlaylistItem(itemData) {
  var content = playlistItem;
  itemData['rating_stars'] = genRatingStars(itemData['rating']);
  itemData['duration'] = genDuration(itemData['duration_sec']);
  for (var item in itemData) {
    content = str_replace('{$'+ item +'}', itemData[item], content);
  }

  newElement = new Element('li', {'id': 'playlistitem_'+ itemData['id'], 'class': 'playlistitem', 'html': content});
  newElement.set('mediaid', itemData['id']);
  newElement.set('user', itemData['author']);

  addIEHover(newElement);

  return newElement;
}

function addPlaylistItem(itemData, position, autoFill) {
  if (typeOf(itemData) != 'object') {
    return;
  }

  if (typeOf(position) == 'undefined') {
    position = -1;
  }
  else if ((position > 0) && !$('playlistitem_'+ position)) {
    position = -1;
  }

  autoFill = autoFill || false;

  if ($('playlistitem_'+ itemData['id'])) {
    return;
  }

  var newItem = createPlaylistItem(itemData);
  if (playlist.currentMedia == null) {
    playlist.currentMedia = itemData['id'];
    newItem.addClass('act');
  }
  else if (playlist.currentMedia == itemData['id']) {
    $$('.playlistitem.act').removeClass('act');
    newItem.addClass('act');
  }
  if (playlist.currentUser == null) {
    playlist.currentUser = itemData['author'];
  }

  if (position <= 0) {
    $('playlistitems').grab(newItem, (position == -1) ? 'bottom' : 'top');
  }
  else {
    newItem.inject($('playlistitem_'+ position), 'after');
  }
  updatePlaylistWidth();

  addPlaylistDrag(newItem);

  if (autoFill) {
    if (playlist.autofillEffect) {
      playlist.autofillEffect.start({'color': playlist.autofillElementColorSelected}).start({'color': playlist.autofillElementColor});
    }

    itemStart = newItem.getPosition($('playlistitems')).x;

    if ((itemStart + playlist.itemWidth) > ($('playlistcontainer').scrollLeft + parseInt($('playlistcontainer').getStyle('width')))) {
      scrollPlaylist(Math.floor(itemStart / playlist.itemWidth), true);
    }
  }

  return newItem;
}

function addPlaylistDrag(item) {
  item.addEvent('mousedown', function(e) {
    e = new Event(e).stop();
    this.set('pageX', e.event.pageX);
    this.set('pageY', e.event.pageY);

    item.addEvent('mouseup', function(e) {
      this.removeEvents('mouseup');
      this.removeEvents('mousemove');
    });

    item.addEvent('mousemove', function(e) {
      if (typeOf(playlist.dragID) != 'null') {
        return;
      }

      var posX = e.event.pageX;
      var posY = e.event.pageY;
      var origX = this.get('pageX');
      var origY = this.get('pageY');

      if (origX == '') {
        this.set('pageX', posX);
      }
      if (origY == '') {
        this.set('pageY', posY);
      }

      var dist = Math.sqrt(Math.pow(posX - origX, 2) + Math.pow(posY - origY, 2));
      if (dist < 5) {
        return;
      }

      playlist.scrollElement.set(0, 0);
      $('playlistitems').set('targetmargin', -$('playlistitems').get('container_scroll'));
      playlist.tweener.set(-$('playlistitems').get('container_scroll'));
//      $('playlistitems').setStyle('margin-left', -$('playlistitems').get('container_scroll'));

      this.removeEvents('mouseup');
      this.removeEvents('mousemove');

      playlist.dragID = this.getProperty('id');
      var dragIndex = getPlaylistIndexByMedia(this.get('mediaid'));

      e = new Event(e).stop();

      var clone = this.clone();
      clone.removeEvents();

      // Set classes and add droppables to the playlist
      var playlistItems = $('playlistitems').getChildren();

      var droppable = new Element('li', {'class': 'droppable', 'html': '<div class="highlight">&nbsp;</div>'});
      droppable.setStyles({'float': 'none', 'z-index': 4, 'position': 'absolute', 'top': '0', 'width': playlist.itemWidth});

      for (var i = 0; i < playlistItems.length; i++) {
        playlistItems[i].setStyles({'float': 'none', 'z-index': 5, 'position': 'absolute', 'left': (i * playlist.itemWidth), 'top': 0});
        var newDroppable = droppable.clone();

        if ((i == dragIndex) || (i == dragIndex + 1)) {
          newDroppable.addClass('nodrop');
        }

        var move = i - dragIndex;
        if (i > dragIndex) {
          move--;
        }
        newDroppable.set('move', move);
        if (i == 0) {
          newDroppable.addClass('firstdroppable');
          newDroppable.setStyles({'left': 0, 'width': playlist.itemWidth / 2});
        }
        else {
          newDroppable.setStyles({'left': (i * playlist.itemWidth) - (playlist.itemWidth / 2)});
        }
        newDroppable.inject(playlistItems[i], 'before');
      }
      if (dragIndex != playlistItems.length - 1) {
        droppable.setStyles({'left': (playlistItems.length * playlist.itemWidth) - (playlist.itemWidth / 2), 'width': playlist.itemWidth / 2});
        droppable.addClass('lastdroppable');
        droppable.inject(playlistItems[playlistItems.length-1], 'after');
      }

      dropItems = $$('.droppable');

      var position = this.getPosition($('webtv_wrap'));
      clone.addClass('dragging');
      xPosition = position['x'];
      clone.setStyles({'z-index': 6, 'position': 'absolute', 'top': position['y'], 'left': xPosition});
      clone.inject($('playlistdrag'));

      var drag = clone.makeDraggable({
        droppables: dropItems,
        onDrop: function(el, droppable) {
          var savePos = parseInt($('playlistitems').get('targetmargin'));
          playlist.tweener.set(0);
          $('playlistitems').set('targetmargin', 0);
//          $('playlistitems').setStyle('margin-left', 0);
          playlist.scrollElement.set(-savePos, 0);
          $('playlistitems').set('container_scroll', $('playlistcontainer').scrollLeft);

          if (droppable) {
            var position = droppable.getPosition($('playlistcontainer'));
            if (!droppable.hasClass('nodrop')) {
              $(playlist.dragID).replaces(droppable);
              if (playerInstance) {
                try {
                  playerInstance.moveMedia($(playlist.dragID).get('mediaid'), droppable.get('move'));
                } catch (e) { }
              }
            }
          }
          playlist.dragID = null;

          el.destroy();
          $$('.droppable').destroy();
          var playlistItems = ($('playlistitems')).getChildren();
          for (i = 0; i < playlistItems.length; i++) {
            playlistItems[i].setStyles({'position': 'static', 'float': ''});
          }
        },
        onEnter: function(el, droppable) {
          var position = droppable.getPosition($('playlistcontainer'));
          var scroll = 0;
          if (position.x < 0) {
            scrollPlaylistDrag(-1);
          }
          else if ((position.x + droppable.getSize().x) > $('playlistcontainer').getSize().x) {
            scrollPlaylistDrag(1);
          }

          droppable.addClass('over');
        },
        onLeave: function(el, droppable) {
          droppable.removeClass('over');
        }
      });
      drag.start(e);
    });
  });
}

function getPlaylistIndexByMedia(mediaId) {
  var items = $('playlistitems').getChildren();
  if (!items.length) {
    return null;
  }

  for (var i = 0; i < items.length; i++) {
    if (items[i].get('mediaid') == mediaId) {
      return i;
    }
  }

  return null;
}

function removePlaylistItem(item) {
  if (typeOf(item) != 'object') {
    item = $('playlistitem_'+ item);
  }

  if (!item) {
    return;
  }

  if (playerInstance && item.get('mediaid')) {
    try {
      playerInstance.removeMedia(item.get('mediaid'));
    } catch (e) { }
  }

  removeItem(item);
  updatePlaylistWidth();
  if ($('playlistcontainer').scrollLeft && (($('playlistcontainer').scrollLeft + $('playlistcontainer').getSize()['x']) > parseInt($('playlistitems').getStyle('width')))) {
    scrollPlaylist(-1);
  }
}

function playPlaylistItem(id) {
  if (!$('playlistitem_'+ id)) {
    return;
  }

  if (playerInstance) {
    try {
      playerInstance.playMedia(id);
    } catch(e) { }
  }
  seekToMedia(id);
}

function updatePlaylistWidth() {
  var width = $('playlistitems').getChildren().length;
  if ($('playlistitemcount')) {
    $('playlistitemcount').set('html', width);
  }
  width *= playlist.itemWidth;
  $('playlistitems').setStyle('width', width);
}

function toggleAutoFill() {
  playlist.autofill = !playlist.autofill;
  if (playerInstance) {
    try {
      playerInstance.setAutoMode(playlist.autofill);
    } catch (e) { }
  }

  if ($('autofillselect')) {
    $('autofillselect').set('html', (playlist.autofill) ? language.playlist_autofill_on : language.playlist_autofill_off);
  }
}

/**
 * Content browser
 */
function hideAllContentTabs() {
  for (var i = 0; i < contentBrowser.tabElements.length; i++) {
    contentBrowser.tabElements.setStyle('display', 'none');
  }
}

function addContentMedia(id, play) {
  if (!playerInstance) {
    return;
  }

  if ($('playlistitem_'+ id)) {
    if (!play) {
      return;
    }

    playPlaylistItem(id);
    return;
  }

  try {
    playerInstance.addMedia(id, -1, play);
  } catch(e) { }
}

function setContentActiveTab(tabIndex) {
  if (tabIndex == contentBrowser.activeTab) {
    if (contentBrowser.tabState[tabIndex].type != 'search') {
      reloadContentTab(tabIndex);
    }

    return;
  }

  if ((contentBrowser.tabState[tabIndex].type == 'categories') && contentBrowser.tabState[tabIndex].search) {
    contentBrowser.tabState[tabIndex].search = 0;
    contentBrowser.tabState[tabIndex].changed = true;
  }

  hideAllContentTabs();

  if (contentBrowser.activeTab != null) {
    contentBrowser.tabs[contentBrowser.activeTab].removeClass('act');
  }
  contentBrowser.tabs[tabIndex].addClass('act');
  contentBrowser.tabElements[tabIndex].setStyle('display', 'block');
  contentBrowser.activeTab = tabIndex;

  if (!contentBrowser.tabState[tabIndex].loaded || contentBrowser.tabState[tabIndex].changed) {
    reloadContentTab(tabIndex);
  }
}

function scrollContentBrowser(amount) {
  var displayItems = ((contentBrowser.tabState[contentBrowser.activeTab].type == 'categories') && contentBrowser.tabState[contentBrowser.activeTab].search) ? (contentBrowser.displayItems - 1) : contentBrowser.displayItems;
  if (!contentBrowser.tabState[contentBrowser.activeTab].loaded || contentBrowser.tabState[contentBrowser.activeTab].changed) {
    var newOffset = 0;
    contentBrowser.tabState[contentBrowser.activeTab].offset = 0;
    contentBrowser.tabState[contentBrowser.activeTab].numElements = 0;
  }
  else {
    var newOffset = Math.max(0, Math.min(contentBrowser.tabState[contentBrowser.activeTab].offset + (amount * displayItems), contentBrowser.tabState[contentBrowser.activeTab].numElements - displayItems));
  }

  if (newOffset == contentBrowser.tabState[contentBrowser.activeTab].offset) {
    return;
  }

  contentBrowser.tabState[contentBrowser.activeTab].offset = newOffset;
  reloadContentTab(contentBrowser.activeTab);
}

function reloadContentTab(tabIndex) {
  if (contentBrowser.tabState[tabIndex].loader) {
    contentBrowser.tabState[tabIndex].loader.setStyle('visibility', 'visible');
  }
  contentBrowser.tabState[tabIndex].loaded = true;
  contentBrowser.tabState[tabIndex].changed = false;
  var displayItems = ((contentBrowser.tabState[tabIndex].type == 'categories') && contentBrowser.tabState[tabIndex].search) ? (contentBrowser.displayItems - 1) : contentBrowser.displayItems;

  new Request(
    {
      url: 'http://www.showtube.de/webtv_dev.php/media/ajax?action=webtvcontent',
      method: 'post',
      onComplete: function(){updateContentTab(tabIndex, this.xhr);},
      onFailure: function(e){showError(this.xhr)},
      data:'type=' + encodeURI(contentBrowser.tabState[tabIndex].type) + '&limit=' + displayItems + '&offset=' + contentBrowser.tabState[tabIndex].offset + '&search=' + encodeURI(contentBrowser.tabState[tabIndex].search)
    }
  ).send();
}

function updateContentTab(tabIndex, r) {
  if (contentBrowser.tabState[tabIndex].loader) {
    contentBrowser.tabState[tabIndex].loader.setStyle('visibility', 'hidden');
  }

  if (!r.responseXML) {
    return;
  }

  var docElement = r.responseXML.documentElement;
  contentBrowser.tabState[tabIndex].numElements = docElement.getElementsByTagName('numitems')[0].firstChild.data;
  var medias = docElement.getElementsByTagName('media');
  clearContentTab(tabIndex);

  if ((contentBrowser.tabState[tabIndex].type == 'categories') && contentBrowser.tabState[tabIndex].search) {
    addContentBackItem(tabIndex);
  }

  for (var i = 0; i < medias.length; i++) {
    addContentItem(tabIndex, medias[i], ((contentBrowser.tabState[tabIndex].type == 'categories') && !contentBrowser.tabState[tabIndex].search));
  }
}

function addContentItem(tabIndex, mediaXMLData, isCategory) {
  var mediaData = extractMediaData(mediaXMLData);

  var newItem = createContentItem(mediaData, isCategory);
  contentBrowser.lists[tabIndex].grab(newItem, 'bottom');
}

function createContentItem(itemData, isCategory) {
  var content = (isCategory) ? categoryContentItem : contentItem;
  itemData['rating_stars'] = genRatingStars(itemData['media_rating']);
  itemData['duration'] = genDuration(itemData['media_duration']);
  for (var item in itemData) {
    content = str_replace('{$'+ item +'}', itemData[item], content);
  }

  newElement = new Element('li', {'html': content});

  addIEHover(newElement);

  return newElement;
}

function extractMediaData(XMLData) {
  var data = new Object();
  for (var i = 0; i < XMLData.childNodes.length; i++) {
    data[XMLData.childNodes[i].tagName] = (XMLData.childNodes[i].firstChild) ? XMLData.childNodes[i].firstChild.nodeValue : '';
  }

  return data;
}

function clearContentTab(tabIndex) {
  contentBrowser.lists[tabIndex].empty()
}

function browseCategoryContent(categoryId) {
  tabIndex = contentBrowser.tabIndexes['categories'];

  contentBrowser.tabState[tabIndex].offset = 0;
  contentBrowser.tabState[tabIndex].numElements = 0;
  contentBrowser.tabState[tabIndex].search = categoryId;
  reloadContentTab(tabIndex);
}

function addContentBackItem(tabIndex) {
  contentBrowser.lists[tabIndex].grab(new Element('li', {'html': categoryContentBackItem}), 'bottom');
}

function getContentTabIndexByType(type) {
  return (typeof contentBrowser.tabIndexes[type] == 'number') ? contentBrowser.tabIndexes[type] : null;
}

function changeSearch(e) {
  tabIndex = contentBrowser.tabIndexes['search'];
  var searchString = $('searchfield').value;
  if (!searchString || (contentBrowser.tabState[tabIndex].search == searchString)) {
    return;
  }

  contentBrowser.tabState[tabIndex].search = searchString;
  contentBrowser.tabState[tabIndex].offset = 0;
  contentBrowser.tabState[tabIndex].numElements = 0;
  reloadContentTab(tabIndex);
}

function keyUpSearch(e) {
  var keyCode = (window.event) ? event.keyCode : e['code'];
  if (keyCode == 13) {
    changeSearch(e);
  }
}

function addIEHover(element) {
  if ((Browser.Engine.name != 'trident') || (Browser.Engine.version >= 5)) {
    return;
  }

  element.addEvents({
    'mouseover': function() {
      this.addClass('hover');
    },
    'mouseout': function() {
      this.removeClass('hover');
    }
  });
}
