var DR = '';
if (document.location.href.match(/\/deutscheoperberlin(?!\.de)/)) {
   DR = '/deutscheoperberlin';
}

function closeThickbox() {
   $('body, html').css('overflow', '');
   $('#TB2_overlay, #TB2_window, #TBA_overlay, #TBA_window').remove();
   $('#TB2_overlay, #TB2_window, #TB2_HideSelect, #TBA_overlay, #TBA_window, #TBA_HideSelect').remove();
}

$(function () {

   var fadingDuration = 500;

   // Fix styles.
   $('.head .presenter .image .tickets').css('opacity', 0.95);
   $('.head .presenter .info-background-1, #home-magazine .major-entries a .info-background, #interviews .info-background').css('opacity', 0.9);

   if ($.browser.msie) {
      // IE 6 and lower
      if ($.browser.version < 7) {
         $('#banner').css({
            width:    '706px',
            overflow: 'hidden'
         });
         $('.body .home-magazine .major-entries a.left-box, .body .home-magazine .major-entries a.middle-box').css({
            marginRight: '5px'
         });
      }

      // IE 7 and lower
      if ($.browser.version < 8) {
         $('#home-magazine').css({
            paddingBottom: '4px'
         }).find('.minor-entries').css({
            position:   'relative',
            top:        '4px',
            paddingTop: '0px'
         }).find('.date').height(19);
      }
   }

   // Loads a player for the given film.
   var loadPlayer = function(id, target, options) {
      options = $.extend({
         width:     690,
         height:    450,
         autostart: false,
         playerId:  'player-object'
      }, options || {});

      $.getJSON(DR+'/ajax.php?action=getFilm&id='+id, function(data) {
         // file docroot
         var fDR = 'http://dev1.heimat.de/playertest/new_player/';

         // params: swfFile, id, width, height, flashVersion, ?
         var so = new SWFObject(fDR+'player-viral.swf', options.playerId, options.width, options.height, '9', '#ffffff');
         so.addParam('allowfullscreen', 'true');
         so.addParam('allowscriptaccess', 'always');
         so.addParam('wmode', 'opaque');
         so.addVariable('icons', 'false');
         so.addVariable('controlbar', 'none');
         so.addVariable('repeat', 'list');
         so.addVariable('image', data.image);
         so.addVariable('plugins', fDR+'player_style02.swf');
         so.addVariable('skindata', fDR+'style02_skindata.xml');
         so.addVariable('filmdata', encodeURIComponent(DR+'/ajax.php?action=getFilmXML&id='+id));
         so.addVariable('moduldir', fDR+'mod');
         so.addVariable('file', data.file);

         if (options.autostart) {
            so.addVariable('autostart', true);
         }

         so.write(target);
      });
   };

   // Truncates a given string to fit a given length.
   var truncate = function(string, maxLength, append) {
      append = append || '...';

      if (string.length > maxLength) {
         string = string.substr(0, maxLength)+append;
      }

      return string;
   };

   // Preloads all images that are passed.
   var preload = (function () {
      var images = [];

      return function () {
         for (var i = 0; i < arguments.length; i += 1) {
            var image = document.createElement('img');
            image.src = arguments[i];
            images.push(image);
         }
      };
   }());

   /*
    * Presenter
    */
   (function(data) {
      if (data && data.length > 0) {

         // Stores the parent element of all news related stuff.
         var parent = $('#presenter');

         // Indicates the current image index.
         var dataPos = 0;

         // Stores the interval used to automatically switch to the next image.
         var autoNextInterval = null;

         // Sets the current image index to the next image.
         var nextData = function () {
            dataPos = (dataPos + 1) % data.length;
            parent.find('.info .switch .position').text(dataPos + 1);
         };

         // Sets the current image index to the previous image.
         var prevData = function () {
            dataPos -= 1;

            if (dataPos < 0) {
               dataPos = data.length - 1;
            }

            parent.find('.info .switch .position').text(dataPos + 1);
         };

         // Determines image at the current index.
         var getData = function () {
            return data[dataPos];
         };

         // Determines the url to the transformed image.
         var getUrl = function(path) {
            return 'http://data.heimat.de/transform.php?file='+encodeURIComponent(path)+'&width=980&height=414&do=cropOut';
         };

         // Populates the presenter with the given data.
         var populate = (function () {
            var image = $('<img class="presented" src="" alt="" />');
            parent.find('.image').append(image);

            return function(data) {
               parent.find('.info .text .title').text(data.title);
               parent.find('.info .text .subtitle').html(data.desc);

               if (data.event) {
                  parent.find('.image .tickets .price').html(data.event.price);
                  parent.find('.image .tickets a.ticketbutton').attr('href', data.event.price_url);
                  parent.find('.image .tickets .date').text(data.event.formatted_date);
               } else {
                  parent.find('.image .tickets .date').text('');
               }

               if (data.video) {
                  parent.find('a.videobutton').attr('href', '#'+data.video);
               }

               image.attr('src', getUrl(data.full_path));
            };
         }());

         // Apply the current data to the entry markup.
         var applyData = (function () {
            var ticketInfoVisible = false;
            var firstApplication = true;

            return function () {
               var currentData = getData();

               if (!currentData.event && ticketInfoVisible) {
                  ticketInfoVisible = false;
                  parent.find('.image .tickets').fadeOut(fadingDuration);
               } else if (currentData.event && !ticketInfoVisible) {
                  ticketInfoVisible = true;
                  parent.find('.image .tickets').fadeIn(fadingDuration);
               }

               var playIconVisible = parent.find('a.videobutton').css('display') != 'none';

               if (!currentData.video && playIconVisible) {
                  parent.find('a.videobutton, .videobutton-caption').fadeOut(fadingDuration);
               } else if (currentData.video && !playIconVisible) {
                  parent.find('a.videobutton, .videobutton-caption').fadeIn(fadingDuration);
               }

               if (firstApplication) {
                  populate(currentData);
               } else {
                  var img = parent.find('.image > img.presented');
                  var oldImg = img.clone();
                  populate(currentData);
                  oldImg.appendTo(parent.find('.image')).fadeOut(fadingDuration, function () {
                     $('#presenter-player').hide();
                     $('#presenter-player-obejct').remove();
                     $(this).remove();
                  });
               }

               firstApplication = false;
            };
         }());

         // Bind stuff.
         if (data.length > 1) {
            parent.find('.info .switch a.prev').click(function () {
               window.clearInterval(autoNextInterval);
               prevData();
               applyData();
               return false;
            });
            parent.find('.info .switch a.next, .image > img.presented').click(function () {
               window.clearInterval(autoNextInterval);
               nextData();
               applyData();
               return false;
            });
         } else {
            parent.find('.info .switch').hide();
         }

         parent.find('a.videobutton').click(function () {
            var id = parseInt($(this).attr('href').replace(/^.*#/, ''), 10);

            $(this).add(parent.find('.videobutton-caption')).fadeOut(fadingDuration);

            window.clearInterval(autoNextInterval);

            $('#presenter-player').show();
            loadPlayer(id, 'presenter-player', {
               playerId:  'presenter-player-object',
               autostart: true,
               width:     690,
               height:    414
            });

            return false;
         });

         // Initialize.
         $.each(data, function(index, value) {
            preload(getUrl(value.full_path));
         });

         applyData();

         autoNextInterval = window.setInterval(function () {
            nextData();
            applyData();
         }, 10000);

      }
   }(DATA.presenter));

   /*
    * News
    */
   (function(data) {
      if (data && data.length > 0) {

         // Stores the parent element of all news related stuff.
         var parent = $('#home-magazine');

         // Indicates which entry is the first to be displayed.
         var dataPos = 0;

         // Shifts the data position to display the next set of data.
         var nextData = function () {
            dataPos += 3;
         };

         // Determines data at the current offset.
         var getData = function () {
            var currentData = [];

            for (var i = 0; i < 6; i += 1) {
               currentData.push(data[(i + dataPos) % data.length]);
            }

            return currentData;
         };

         // Determines the url to the transformed image.
         var getUrl = function(path) {
            return 'http://data.heimat.de/transform.php?file='+encodeURIComponent(path)+'&width=230&height=250&do=cropOut';
         };

         // Determines a major entry element by position.
         var getMajorEntryElement = function(position) {
            return parent.find('.major-entries a').eq(position);
         };

         // Populates a major entry.
         var populateMajorEntry = function(element, data) {
            element.attr('href', '?page=intro_detail&textId='+data.id);
            element.find('.date').text(data.formatted_date);

            if (data.pic) {
               element.css('background-image', 'url('+getUrl(data.pic)+')');
            } else {
               element.css('background-image', 'none');
            }
            
            element.attr('title', data.title).find('.info .wrap').text(truncate(data.title, 75));
         };

         // Populates all major entries.
         var populateMajorEntries = function(data) {
            for (var i = 0; i < 3; i += 1) {
               var element = getMajorEntryElement(i);

               if (data[i]) {
                  element.show();
                  populateMajorEntry(element, data[i]);
               } else {
                  element.hide();
               }
            }
         };

         // Determines a minor entry element by position.
         var getMinorEntryElement = function(position) {
            return parent.find('.minor-entries a').eq(position);
         };

         // Populates a minor entry.
         var populateMinorEntry = function(element, data) {
            element.attr('href', '?page=intro_detail&textId='+data.id);
            element.find('.date').text(data.formatted_date);
            element.attr('title', data.title).find('.headline').text(truncate(data.title, 75));
            element.find('.teaser').text(data.text);
         };

         // Populates all minor entries.
         var populateMinorEntries = function(data) {
            for (var i = 3; i < 6; i += 1) {
               var element = getMinorEntryElement(i - 3);

               if (data[i]) {
                  element.show();
                  populateMinorEntry(element, data[i]);
               } else {
                  element.hide();
               }
            }
         };

         // Apply the current data to the entry markup.
         var applyData = (function () {
            var firstApplication = true;

            return function () {
               var currentData = getData();

               if (firstApplication) {
                  populateMajorEntries(currentData);
                  populateMinorEntries(currentData);
               } else {
                  parent.find('.major-entries, .minor-entries').fadeOut(fadingDuration, function () {
                     populateMajorEntries(currentData);
                     populateMinorEntries(currentData);

                     $(this).fadeIn(fadingDuration);
                  });
               }

               firstApplication = false;
            };
         }());

         // Bind stuff.
         parent.find('a.entries-shifter').click(function () {
            nextData();
            applyData();
            return false;
         });

         // Initialize.
         $.each(data, function(index, value) {
            if (value.pic) {
               preload(getUrl(value.pic));
            }
         });

         applyData();

      }
   }(DATA.news));

   /*
    * Weekly
    */
   (function(data) {
      if (data && data.length > 0) {

         // Stores the parent element.
         var parent = $('#weekly-media');

         // Indicates the current image index.
         var dataPos = 0;

         // Sets the current image index to the next image.
         var nextData = function () {
            dataPos = (dataPos + 1) % data.length;
            parent.find('.info .switch .position').text(dataPos + 1);
         };

         // Sets the current image index to the previous image.
         var prevData = function () {
            dataPos -= 1;

            if (dataPos < 0) {
               dataPos = data.length - 1;
            }

            parent.find('.info .switch .position').text(dataPos + 1);
         };

         // Determines image at the current index.
         var getData = function () {
            return data[dataPos];
         };

         // Determines the url to the transformed image.
         var getUrl = function(path) {
            return 'http://data.heimat.de/transform.php?file='+encodeURIComponent(path)+'&width=350&height=240&do=cropOut';
         };

         // Populates the presenter with the given data.
         var populate = (function () {
            var image = $('<img class="presented" src="" alt="" />');
            parent.find('.image').append(image);

            return function(item) {
               parent.find('.info .title .headline').text(item.title);
               parent.find('.info .title .subtitle').text(item.sub_title);

               if (item.event) {
                  parent.find('.info .details').html(truncate(item.event.werkinfoGesamt, 350).replace(/\n/g, "\n<br />"));
                  parent.find('.info a.ticketbutton').show().attr('href', item.event.price_url);
               } else {
                  parent.find('.info .details').html(item.desc || '');
                  parent.find('.info a.ticketbutton').hide();
               }
               
               parent.find('.info .title').attr('href', item.keyword.length > 0
                                                           ? item.keyword
                                                           : (item.event
                                                                 ? '?page=spielplandetail&id_event_date='+item.event.id_event_date
                                                                 : '#'));

               if (item.video) {
                  parent.find('a.videobutton').attr('href', 'http://dev1.heimat.de/player/'+DATA.currentLanguage+'/'+item.video+'/dob/?KeepThis=true&TB2_iframe=true&height=480&width=780');
               }

               if (item.mdbSeries) {
                  parent.find('a.seriesbutton').unbind().click(function () {
                     displayMdbSeriesShadowbox(item.mdbSeries);
                     return false;
                  });
               } else {
                  parent.find('a.seriesbutton').unbind();
               }

               image.attr('src', getUrl(item.full_path));
            };
         }());

         // Apply the current data to the entry markup.
         var applyData = (function () {
            var isVideoButtonVisible = false;
            var isSeriesButtonVisible = false;
            var isFirst = true;

            return function () {
               var currentData = getData();

               if (!currentData.video && isVideoButtonVisible) {
                  isVideoButtonVisible = false;
                  parent.find('a.videobutton').fadeOut(fadingDuration);
               } else if (currentData.video && !isVideoButtonVisible) {
                  isVideoButtonVisible = true;
                  parent.find('a.videobutton').fadeIn(fadingDuration);
               }

               if (currentData.mdbSeries && isSeriesButtonVisible) {
                  isSeriesButtonVisible = false;
                  parent.find('a.seriesbutton').fadeIn(fadingDuration);
               } else if (!currentData.mdbSeries && !isSeriesButtonVisible) {
                  isSeriesButtonVisible = true;
                  parent.find('a.seriesbutton').fadeOut(fadingDuration);
               }

               if (isFirst) {
                  populate(currentData);
               } else {
                  var img = parent.find('.image > img.presented');
                  var oldImg = img.clone();
                  populate(currentData);
                  oldImg.appendTo(parent.find('.image')).fadeOut(fadingDuration, function () {
                     $('#weekly-player').hide();
                     $('#weekly-player-obejct').remove();
                     $(this).remove();
                  });
               }

               isFirst = false;
            };
         }());

         // Bind stuff.
         if (data.length > 1) {
            parent.find('.info .switch a.prev').click(function () {
               prevData();
               applyData();
               return false;
            });
            parent.find('.info .switch a.next').click(function () {
               nextData();
               applyData();
               return false;
            });
         } else {
            parent.find('.info .switch').hide();
         }

         // Initialize.
         $.each(data, function(index, item) {
            // Determine existence of an mdb-series.
            var keywordMatches = item.keyword.match(/mdbseries\((\d+?)\)/);
            item.mdbSeries = keywordMatches ? parseInt(keywordMatches[1], 10) : null;

            // Preload the items image.
            preload(getUrl(item.full_path));
         });
         
         applyData();

      }
   }(DATA.weekly));

   /*
    * Interviews
    */
   (function(data) {
      if (data && data.length > 0) {

         // Stores the parent element.
         var parent = $('#interviews');

         // Indicates the current image index.
         var dataPos = 0;

         // Sets the current image index to the next image.
         var nextData = function () {
            dataPos = (dataPos + 1) % data.length;
            parent.find('.switch .position').text(dataPos + 1);
         };

         // Sets the current image index to the previous image.
         var prevData = function () {
            dataPos -= 1;

            if (dataPos < 0) {
               dataPos = data.length - 1;
            }

            parent.find('.switch .position').text(dataPos + 1);
         };

         // Determines image at the current index.
         var getData = function () {
            return data[dataPos];
         };

         // Determines the url to the transformed image.
         var getUrl = function(path) {
            return 'http://data.heimat.de/transform.php?file='+encodeURIComponent(path)+'&width=350&height=240&do=cropOut';
         };

         // Populates the presenter with the given data.
         var populate = (function () {
            var image = $('<img class="presented" src="" alt="" />');
            parent.find('.image').append(image);

            return function(data) {
               parent.find('.image').attr('href', '?page=intro_detail&textId='+data.id).attr('title', data.title);
               image.attr('src', getUrl(data.pic));
               parent.find('.info .title').text(truncate(data.title, 85));
            };
         }());

         // Apply the current data to the entry markup.
         var applyData = (function () {
            var firstApplication = true;

            return function () {
               var currentData = getData();

               if (firstApplication) {
                  populate(currentData);
               } else {
                  var img = parent.find('.image > img.presented');
                  var oldImg = img.clone();
                  populate(currentData);
                  oldImg.appendTo(parent.find('.image')).fadeOut(fadingDuration, function () {
                     $(this).remove();
                  });
               }

               firstApplication = false;
            };
         }());

         // Bind stuff.
         if (data.length > 1) {
            parent.find('.switch a.prev').click(function () {
               prevData();
               applyData();
               return false;
            });
            parent.find('.switch a.next').click(function () {
               nextData();
               applyData();
               return false;
            });
         } else {
            parent.find('.switch').hide();
         }

         // Initialize.
         $.each(data, function(index, value) {
            preload(getUrl(value.pic));
         });

         applyData();

      }
   }(DATA.interviews));

   // Style bug workaround.
   $('.body .interviews .info, .body .interviews .info-background').click(function () {
      $(this).closest('.interviews').find('a.image').click();
      return false;
   });

   /*
    * Twitter
    */
   $.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?callback=?', {
      user_id:          185669447,
      trim_user:        true,
      count:            true,
      include_entities: true
   }, function(tweet) {
      tweet = tweet[0];

      // Convert urls to links.
      var textMarkup = tweet.text;
      
      if (tweet.entities.urls) {
         $.each(tweet.entities.urls, function (index, entity) {
            textMarkup = textMarkup.replace(entity.url, '<a href="'+entity.url+'">'+entity.url+'</a>');
         });
      }

      // Insert tweet into the DOM.
      $('#twitter .tweet').html(textMarkup);
   });

});
