var preLoadMedium = 0;

var galleryBuffer = null;
var gallerySelector = 0;
var galleryActive = 0;

/* 
 * Initialize Mediathek Links onclick event
 */
function mediathekInitLinks() {

  $('#mediathek_lightbox').remove();

  var mediathekDiv = '<div id="mediathek_tooltip"></div>';
  mediathekDiv += '<div id="mediathek_lightbox">';
  mediathekDiv += '<div class="load"></div>';
  mediathekDiv += '<h1 class="title"><img src="' + str_mediathek_title_image + '" alt="' + str_mediathek_title + '" /></h1>';
  mediathekDiv += '<a class="close"><img src="' + str_mediathek_close_image + '" alt="' + str_mediathek_close + '" /></a>';
  mediathekDiv += '<div class="categories_title">' + str_mediathek_cattitle + '</div>';
  mediathekDiv += '<div class="medialist_title">' + str_mediathek_mediatitle + '</div>';
  mediathekDiv += '<div class="media" id="mediathek_media"></div>';
  mediathekDiv += '<div class="search"><input type="text" name="searchfor" value="' + str_mediathek_search + '"/></div>';
  mediathekDiv += '</div>';

  $('body').prepend(mediathekDiv);

  $('#mediathek_lightbox .search input').focus( function () { $(this).val(''); });
  $('#mediathek_lightbox .search input').keyup( function () { mediathekAjaxSearch($(this).val()); });
  
  $('a.mediathekMenuLink').overlay({

    target: '#mediathek_lightbox',

    close: '.close', 
    
    expose: { color: '#000', loadSpeed: 200, opacity: 0.8 },

    closeOnClick: false,

    onBeforeLoad: prepareMediathek,
    onLoad: mediathekRun,
    onClose: mediathekClose,

    absolute: true,
    top: "50%", 
    left: "50%"

  });

}


function prepareMediathek(eventObject) {

  $.getScript('/fileadmin/templates/scripts/jquery.corner.js', function() { $('#mediathek_lightbox').corner('30px'); });

}

function mediathekClose(eventObject) {
  $('#mediathek_lightbox .media').html('');
}

/*
 * Mediathek link clicked, JS enabled
 */
function mediathekRun(eventObject) {

  // Load scripts
  $.getScript('/fileadmin/templates/scripts/tools.tooltip.js');
  $.getScript('/fileadmin/templates/scripts/jquery.mousewheel.js');
  $.getScript('/fileadmin/templates/scripts/jquery.em.js');
  $.getScript('/fileadmin/templates/scripts/jScrollPane.js');
  $.getScript('/fileadmin/flowplayer/flowplayer-3.1.4.min.js');
  
  ET_Event.click('Mediathek', '');
  
  mediathekDoAjax();

  // handle direct link to a specific medium 
  if(this.getTrigger().attr('rel') != 'default') {
	  preLoadMedium = this.getTrigger().attr('rel');
	  mediathekShowMedium();

  }

}

function mediathekDoAjax() {
  // AJAX query for categories...
  $.ajax({
    url: 'index.php?L=' + str_mediathek_languid,
    type: 'GET',
//    data: { eID: 'user_mediathek_pi1', input: 'categories', L: str_mediathek_languid },
    data: { type: '100', get: 'categorylist', L: str_mediathek_languid },
    dataType: 'json',

    success: function(response) {
      /* Successfully received categories */
      $('#mediathek_lightbox .categories').remove();

      $('#mediathek_lightbox').append('<div class="categories"></div>');
      
      // eTracker = '<!-- Copyright (c) 2000-2010 etracker GmbH. All rights reserved. --><!-- This material may not be reproduced, displayed, modified or distributed --><!-- without the express prior written permission of the copyright holder. -->';
      // eTracker += '<!-- BEGIN etracker Tracklet 3.0 -->'; //<script type="text/javascript" src="http://code.etracker.com/t.js?et=BCmDbb"></script>';
      // eTracker += '<script type="text/javascript">_etc();</script>';
      // eTracker += '<img style="border:0px;" alt="" src="https://www.etracker.com/nscnt.php?et=BCmDbb" /><!-- etracker CODE END -->';
      // $('#mediathek_lightbox').append( eTracker );
      
      $('#mediathek_lightbox .categories').html('<ul id="categorieslistpane" class="scroll-pane"></ul>');

      $.each(response, function(i, row) {

        var aTag = $('<a></a>');

        aTag.html(row.title);

        aTag.attr('rel', row.uid);
        aTag.click(mediathekLoadCategory);

        $('<li></li>').html(aTag).appendTo('#categorieslistpane');
  
      }); 
      
    },

    error: function(error) { }
  });
  
  mediathekLoadCategory();
}

function mediathekShowMedium(o) {

  if(!galleryActive) {
    $('#mediathek_lightbox .medialist a.act').removeClass('act');
    $(this).addClass('act');
    $('#galleryBack').remove();
    $('#galleryNext').remove();
  }

  $('#mediathek_lightbox .load').css('display', 'block');

  $('#mediathek_lightbox .subtitle').remove();
  $('#mediathek_lightbox .text').remove();

  $('#mediathek_lightbox .media').html('');

  var loadMedium = $(this).attr('rel');

  
  if(preLoadMedium > 0)
  {
    loadMedium = 'tx_dam_' + preLoadMedium;
    preLoadMedium = 0;
  }

  $.ajax({
    url: 'index.php?L=' + str_mediathek_languid,
    type: 'GET',
//    data: { eID: 'user_mediathek_pi1', input: 'medium', uid: $(this).attr('rel'), L: str_mediathek_languid },
    data: { type: '100', get: 'media', uid: loadMedium, L: str_mediathek_languid },
    dataType: 'json',

    success: function(response) {
      /* Successfully received categories */
      $.each(response, function(i, row) {
    
        //$('<div></div>').attr('id', 'mediathek_media').addClass('media').appendTo('#mediathek_lightbox');

        if(row.title && row.title.length > 0) {
          $('<p></p>').addClass('subtitle').html(row.title).appendTo('#mediathek_lightbox');
        }

        if(row.description && row.description.length > 0) {
          $('<p></p>').addClass('text').html(row.description).appendTo('#mediathek_lightbox');
        }


        if(row.player == 'flowplayer')
        {
          // Set tracking event (eTracker)
          ET_Event.click( $('#categorieslistpane > li > a[class=act]').text() + ' / ' + row.title, $('#categorieslistpane > li > a[class=act]').text() );
                    
          // Create flowplayer instance
          var flowplayer = $f(
            'mediathek_media', 
            '/fileadmin/flowplayer/flowplayer-3.1.4.swf', 
            {
              playlist: [ 
                { url: "http://www.mbw-team.de"+row.flowplayer_image, scaling: 'scale' },
                { url: "http://www.mbw-team.de/"+row.file, autoBuffering: false, autoPlay: false }
              ],

              canvas: {
                backgroundColor: "#000000",
                backgroundGradient: 'none'
              },

              plugins: { 
                controls: {
                  fullscreen: true,
                  stop: true,
                  mute: true,
                  buttonColor: '#000000',
                  buttonOverColor: '#333333',
                  backgroundColor: '#222222',
                  backgroundGradient: 'none',
                  progressGradient: 'none',
                  progressColor: '#000000',
                  sliderColor: '#353535',
                  sliderGradient: 'none',
                  bufferColor: '#444444',
                  bufferGradient: 'none',
                  tooltipTextColor: '#ffffff',
                  tooltipColor: '#5F747C',
                  borderRadius: '0px',
                  timeColor: '#FFFFFF',
                  timeBgColor: '#222222',
                  durationColor: '#ffffff',
                  volumeSliderColor: '#000000',
                  volumeSliderGradient: 'none',
                  height: 20,
                  opacity: 1.0
                },

                audio: { 
                  url: '/fileadmin/flowplayer/flowplayer.audio-3.1.2.swf'
                } 
              }
            });

        }
        else if(row.player == 'gallery') 
        {
          // Set tracking event (eTracker)
          ET_Event.click( $('#categorieslistpane > li > a[class=act]').text() + ' / ' + $('#medialistpane > li > a[class=act]').text(), $('#categorieslistpane > li > a[class=act]').text() );
          
          galleryBuffer = row.gallery;
          gallerySelector = 0;             

          var backButton = $('<a id="galleryBack" class="galleryBack_' + str_mediathek_langcode + '"></a>');
          var nextButton = $('<a id="galleryNext" class="galleryNext_' + str_mediathek_langcode + '"></a>');

          backButton.click(galleryBack);
          nextButton.click(galleryNext);

          $('#mediathek_lightbox').append(backButton);
          $('#mediathek_lightbox').append(nextButton);

          galleryActive = 1;
          preLoadMedium = galleryBuffer[0];
          mediathekShowMedium();
          galleryActive = 0;
        }
        else if(row.player == 'image')
        {
        //        $('<img />').attr('src', row.file).appendTo('#mediathek_media');

        $('<div></div>').attr('class', 'image').css('background-image', "url('" + row.file + "')").appendTo('#mediathek_media');

        /*  $('<img />').css('visibility', 'hidden').attr('src', row.file).appendTo('#mediathek_media');
      	/*  $('#mediathek_media img').each(function () {

		        var image = $(this);	
	
		        for(var i = 0; i < 5000; i++) { }

          		var fixed_height = 271 - $(this).height();
		
      		    if(fixed_height > 0 && fixed_height < 135) {
			          fixed_height = Math.round(fixed_height / 2);
      			    image.css('margin-top', fixed_height + 'px');
      		    }
		
      		    image.css('visibility', 'visible');
		
	        });*/

        }
        else if(row.player == 'news') 
        {
         
          // Set tracking event (eTracker)
          ET_Event.click( $('#categorieslistpane > li > a[class=act]').text() + ' / ' + row.title, $('#categorieslistpane > li > a[class=act]').text() );
         
          var news = '<div class="scrollcontent">' + row.image + '<div class="bodytext">' + row.bodytext + '</div><div class="files">' + row.news_files + '</div></div>';

          $('#mediathek_media').html(news); 
          $('#mediathek_media .scrollcontent').jScrollPane({showArrows: true, scrollbarWidth: 13, arrowSize: 13} );
        }



      }); 
      
        $('#mediathek_lightbox .load').css('display', 'none');
    },

    error: function(error) { }
  });
    



}


function mediathekLoadCategory(o) {

  var loadUid = $(this).attr('rel');

  $('#mediathek_lightbox .categories a').attr('class', '');


  if(!loadUid) {
    loadUid = 0;
    $('#mediathek_lightbox .categories li:first a').attr('class', 'act');
  }
  else {
    $(this).attr('class', 'act');
  }
  

  
  $('#mediathek_lightbox .load').css('display', 'block');

  $.ajax({
    url: 'index.php?L=' + str_mediathek_languid,
    type: 'GET',
//    data: { eID: 'user_mediathek_pi1', input: 'media', uid: loadUid, L: str_mediathek_languid },
    data: { type: '100', get: 'medialist', uid: loadUid, L: str_mediathek_languid },
    dataType: 'json',

    success: function(response) {
      /* Successfully received categories */
      $('#mediathek_lightbox .medialist').remove();

      $('#mediathek_lightbox').append('<div class="medialist"></div>');
      $('#mediathek_lightbox .medialist').html('<ul id="medialistpane" class="scroll-pane"></ul>');

      $.each(response, function(i, row) {

        var aTag = $('<a></a>');

        aTag.html(row.title);

        if(row.caption && row.caption.length > 0) {
          aTag.attr('title', row.caption);
        }

        aTag.attr('rel', row.uid);
        aTag.click(mediathekShowMedium);

        $('<li></li>').html(aTag).appendTo('#medialistpane');

        $('#mediathek_lightbox .search input').val(str_mediathek_search);

      }); 
 
      $('#medialistpane a[title]').tooltip({ tip: '#mediathek_tooltip', position: 'top right', lazy: false});
      $('#medialistpane').jScrollPane({showArrows: true, scrollbarWidth: 13, arrowSize: 13} );

      $('#mediathek_lightbox .load').css('display', 'none');

    },

    error: function(error) { }
  });

}

function mediathekAjaxSearch(s) {

  var loadUid = $('#mediathek_lightbox .categories li a.act').attr('rel');

  if(!loadUid) 
    loadUid = $('#mediathek_lightbox .categories li:first a').attr('rel');

  if(!loadUid)
    loadUid = -1;

  $('#mediathek_lightbox .load').css('display', 'block');

  $.ajax({
    url: 'index.php?L=' + str_mediathek_languid,
    type: 'GET',
    data: { type: 100, get: 'search', uid: loadUid, query: s, L: str_mediathek_languid },
    dataType: 'json',

    success: function(response) {
      /* Successfully received categories */
      $('#mediathek_lightbox .medialist').remove();

      $('#mediathek_lightbox').append('<div class="medialist"></div>');
      $('#mediathek_lightbox .medialist').html('<ul id="medialistpane" class="scroll-pane"></ul>');

      $.each(response, function(i, row) {

        var aTag = $('<a></a>');

        aTag.html(row.title); 

        if(row.caption && row.caption.length > 0) {
          aTag.attr('title', row.caption);
        }

        aTag.attr('rel', row.uid);
        aTag.click(mediathekShowMedium);

        $('<li></li>').html(aTag).appendTo('#medialistpane');


      }); 
 
      $('#medialistpane a[title]').tooltip({ tip: '#mediathek_tooltip', position: 'top right', lazy: false});
      $('#medialistpane').jScrollPane({showArrows: true, scrollbarWidth: 13, arrowSize: 13} );

      $('#mediathek_lightbox .load').css('display', 'none');

    },

    error: function(error) { }
  });


}

function galleryBack(o) {

    if(--gallerySelector < 0)
      gallerySelector = galleryBuffer.length - 1;

    galleryActive = 1;

    preLoadMedium = galleryBuffer[gallerySelector]; 
    mediathekShowMedium();

    galleryActive = 0;
}

function galleryNext(o) {

    if(++gallerySelector >= galleryBuffer.length)
      gallerySelector = 0;

    galleryActive = 1;

    preLoadMedium = galleryBuffer[gallerySelector]; 
    mediathekShowMedium();

    galleryActive = 0;
}

$(document).ready(mediathekInitLinks);

