
var elHead = document.getElementsByTagName('head')[0];
var elSheet = document.createElement('link');
elSheet.setAttribute('href','/static/snsreaal/css/js_enhanced.css');
elSheet.setAttribute('rel','stylesheet');
elSheet.setAttribute('type','text/css');
elSheet.setAttribute('media','screen');
elHead.appendChild(elSheet);


var app = null;
var player = null;
var autoplay = false;
var isPlaying = false;



/**
 * ## third party browser detection module
 * http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
 */

(function() {
    
    var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i=0;i<data.length;i++)    {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {     string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {        // for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            {         // for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS : [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]
    
    };
    
    BrowserDetect.init();
    
    window.$.client = { os : BrowserDetect.OS, browser : BrowserDetect.browser };
    
})();

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/***
 * ##ACCORDION
 */
function AccordionPeer() {}
AccordionPeer.prototype = {
  accordions: [],

  init: function() {
    var that = this;
    $('div.accordion div.bellow').each(function(index, item) {
      var acc = new Accordion();
      acc.init(item, that);
      that.accordions.push(acc);
    });
  },

  open: function(accName) {
    if(!accName) {
      return false;
    }
    document.location.hash = accName;
    $(this.accordions).each(function(index, item) {
      if(item.name == accName) {
        item.open();
      }
    });
  },

  close: function(accName) {
    $(this.accordions).each(function(index, item) {
      if(item.name == accName) {
        item.close();
      }
    });
  },

  toggle: function(accName) {
    $(this.accordions).each(function(index, item) {
      if(item.name == accName) {
        item.toggle();
      }
    });
  },

  goTo: function(accName) {
    var accContainer = $(accName + '-container');
    if(accContainer.length) {
      $.scrollToElement(accContainer);
    }
  }
};

function Accordion() {}
Accordion.prototype = {
  el: null,
  name: null,
  peer: null,
  header: null,
  body: null,

  init: function(item, peer) {
    this.el = item;
    this.body = $('div.bellow-body', this.el);
    this.el.id = $('div.bellow-body', this.el).attr('id') + '-container';
    $('div.bellow-body', this.el).attr('id', $('div.bellow-body', this.el).attr('id') + '-body')

    if($(this.el).hasClass('bellow-static')) {
      return false;
    }

    this.peer = peer;
    var that = this;
    $('.bellow-header a', this.el).each(function(index, item) {
       that.name = $(this).attr('href');
       $(item).click(function(e) {
         that.toggle(that.name);
         e.preventDefault();
       });
    });
  },

  open: function() {
/*    if(!$(this.el).hasClass('bellow-closed')) {
      return false;
    }*/
    var that = this;
    if (jQuery.browser.safari && jQuery.client.os == 'Windows'){
      $('div.bellow-body', this.el).css('visibility','visible');
    }
    $('div.bellow-body', this.el).show('slow', function() {
      $.scrollToElement($(that.el));
      $(that.el).removeClass('bellow-closed');
    });
    return false;
  },

  setHashAndOpen: function() {
    if(!$(this.el).hasClass('bellow-closed')) {
      return false;
    }
    if(document.location.hash == this.name) {
      this.open();
    }
    document.location.hash = this.name;
  },

  close: function() {
    var that = this;
    $(this.el).addClass('bellow-closing');
    if (jQuery.browser.safari && jQuery.client.os == 'Windows'){
      $('div.bellow-body', this.el).css('visibility','hidden');
    }
    $('div.bellow-body', this.el).hide('slow', function() {
      //alert('--' + jQuery.browser.safari)
      $(that.el).addClass('bellow-closed');
      $(that.el).removeClass('bellow-closing');
    });
  },

  toggle: function() {
    if($(this.el).hasClass('bellow-closed')) {
      this.setHashAndOpen();
    }
    else {
      this.close();
    }
  },

  goTo: function(accName) {
    var el = $('#tabs-demo');
    if(el.length) {
      $.scrollToElement(el);
    }
  }
};
/* end - Accordion */


/***
 * ##KWICKS
 */
function FABKwicksPeer() {}
FABKwicksPeer.prototype = {
  FKwicks: [],

  init: function() {
    var that = this;
    $('div.kwicks').each(function(index, el) {
      var k = new FABKwick();
      k.init(el);
      that.FKwicks.push(k);
    });
  }
};

function FABKwick() {}
FABKwick.prototype = {
  hoverTimer: null,

  init: function(el) {
    this.el = el;
    var that = this;
    $('ul', this.el).kwicks({
      max: 500,
      duration: 600,
      spacing: 0,
      event: 'mouseenter'
    });


    $('li.kwick', this.el).each(function(index, item) {
      $(item).attr('id', 'kwick-' + index);
    });

    this.setupHeight();
    this.setupHovers();
  },
  
  setupHeight: function() {
    var that = this;
    $(window).load(function() {
      var h = 0;
      $('div.kwick-inner-primary', that.el).each(function(index, elm) {
        if(h < $(elm).height()) {
          h = $(elm).height();
        }
      });
      $('div.kwick-inner-secondary', that.el).each(function(index, elm) {
        if(h < ($(elm).height() + 20)) {
          h = $(elm).height() + 20;
        }
      });
      $(that.el).height(h);
      $('div.kwick-inner', that.el).height(h);
    });  
  }, 

  setupHovers: function() {

    var that = this;
    // Kwicks container
    $(this.el).mouseenter(function() {
      $(this).addClass('kwicks-hover');
    });
    $(this.el).mouseleave(function(e) {
      if(e.toElement === null){
        return;
      }
      $(this).removeClass('kwicks-hover');
    });

    // Kwick part
    $('li.kwick', this.el).mouseenter(function() {
      that.determineRightKwicks($(this).attr('id'));
    });
    $('li.kwick', this.el).mouseleave(function(e) {
      if(e.toElement === null){
        return;
      }
      that.clearRightKwicks();
    });
  },
  
  determineRightKwicks: function(kwickId) {
    kwickId = kwickId.replace('kwick-','');
    $('li.kwick', this.el).each(function(index, el) {
      if(index > kwickId) {
        $(el).addClass('kwick-right');
      }
      else {
        $(el).removeClass('kwick-right');      
      }
    });
  },
  
  clearRightKwicks: function() {
    $('li.kwick', this.el).removeClass('kwick-right');
  }
};
/* end - kwicks */


/***
 * ##IE7FIXES
 */
function IEFix() {}
IEFix.prototype = {
  init: function() {
    this.fixNav();
  },

  fixNav: function() {
    $('<div></div>').insertBefore($('div#navigation'));
  }
};
/* end - ie7fixes */



/***
 * ##SELECTPICKERPEER
 */
function SelectpickerPeer() {}
SelectpickerPeer.prototype = {
  selectpickers: [],

  init: function() {
    var that = this;
    $('div.selectpicker').each(function(index, el) {
      var s = new Selectpicker();
      s.init(el, index);
      that.selectpickers.push(s);
    });
  }
};
function Selectpicker() {}
Selectpicker.prototype = {
  el: null,
  id: null,
  internalLinks: [],
  name: null,
  label: null,

  init: function(el, index) {
    this.el = el;
    this.id = index;
    this.name = $('ul', this.el).attr('class');
    this.label = $('h2', this.el).text();
    var that = this;
    
    var formHtml = '<form action="http://www.snsreaal.nl/" method="get">';
    formHtml += '  <div class="formfield-container selectfield-container rounded">';
    formHtml += '    <label for="id_selector_' + this.id + '">' + this.label + '</label>';
    formHtml += '    <select name="' + this.name + '" id="id_selector_' + this.id + '">';
    $('ul li a', this.el).each(function(index, aEl) {
      if($(aEl).attr('href').substring(0,1) == '#') {
        var linkName = $(aEl).attr('href').replace('#','');
        that.internalLinks.push(linkName);
      }
      var isCurrent = '';
      if($(aEl).parent().hasClass('current')) {
        isCurrent = ' selected="selected" ';
      }
      formHtml += '<option value="' + $(aEl).attr('href') + '"' + isCurrent + '>' + $(aEl).text() + '</option>';
    });
    formHtml += '    </select>';
    formHtml += '  </div>';
    formHtml += '</form>';
    $(this.el).html(formHtml);
    this.showInternalLink('#' + this.internalLinks[0]);
    
    $('select', this.el).change(function(e) {
      if($(this).attr('value').substring(0,1) == '#') {
        that.showInternalLink($(this).attr('value'));
      }
      else {
        document.location.href = $(this).attr('value');
      }
      e.preventDefault();
    });
  },
  
  showInternalLink: function(linkUrl) {
    for(var i=0, len=this.internalLinks.length; i<len; i++) {
      var internalLinksUrl = '#' + this.internalLinks[i];
      if(internalLinksUrl == linkUrl) {
        $(internalLinksUrl).removeClass('related-documents-hidden');      
      }
      else {
        $(internalLinksUrl).addClass('related-documents-hidden');
      }
    }  
  }
};
/* end - selectpickerpeer */



/***
 * ##BRANDBOX
 */
function BrandboxPeer() {}
BrandboxPeer.prototype = {
  brandboxes: [],

  init: function() {
    var that = this;
    $('div.brandbox-section').each(function(index, el) {
      var b = new Brandbox();
      b.init(el);
      that.brandboxes.push(b);
    });
  }
};

function Brandbox() {}
Brandbox.prototype = {
  el: null,
  hyperlink: null,
  cssClassnames: [],

  init: function(el) {
    this.el = el;
    if($(this.el).attr('class')) {
      this.cssClassnames = $(this.el).attr('class').split(' ');
    }
    this.hyperlink = $('a', this.el);
    var that = this;

    $('div.brandbox-description', this.el).css({
      'top': that.getCssTop(),
      'left': that.getCssLeft()
    });
/*
    $(this.el).click(function(e) {
      document.location.href = $(that.hyperlink).attr('href');
      e.stopPropagation();
    });
*/
  },


  getCssTop: function() {
    var cssTop = '20';
    for(var i=0, len=this.cssClassnames.length; i<len; i++) {
      if(this.cssClassnames[i].indexOf('csstop-') > -1) {
        cssTop = this.cssClassnames[i].replace('csstop-','');
      }
    }
    return cssTop + 'px';
  },


  getCssLeft: function() {
    var cssLeft = '20';
    for(var i=0, len=this.cssClassnames.length; i<len; i++) {
      if(this.cssClassnames[i].indexOf('cssleft-') > -1) {
        cssLeft = this.cssClassnames[i].replace('cssleft-','');
      }
    }
    return cssLeft + 'px';
  }
};
/* end - brandbox */



/***
 * ##BRANDBOX
 */
function PhotogalleryPeer() {}
PhotogalleryPeer.prototype = {
  photogalleries: [],

  init: function() {
    var that = this;
    $('div.photogallery-section').each(function(index, el) {
      var p = new Photogallery();
      p.init(el, index);
      that.photogalleries.push(p);
    });
  }
};

function Photogallery() {}
Photogallery.prototype = {
  el: null,

  init: function(el, index) {
    if(typeof $ == 'undefined' || typeof $.fancybox == 'undefined') {
      return false;
    }

    this.el = el;
    this.index = index;
    $(this.el).attr('id',this.index);

    $("a.to-visual", this.el).fancybox({
        'width': 500,
      'height': 430,
      'margin': 0,
      'padding': 0,
      'autoScale': false,
      'type': 'iframe',
      'overlayOpacity': '0.7',
      'overlayColor': '#fff',
      'onStart': function() {
        $(document.body).addClass('mediabox-enabled');
      },
      'onClosed': function() {
        $(document.body).removeClass('mediabox-enabled');
      }
    });
  }
};
/* end - brandbox */



/***
 * ##SEARCHBOX
 */
function Searchbox() {}
Searchbox.prototype = {
  init: function(sel) {
    this.inputField = $(sel);
    $(this.inputField).each(function(index, el) {
      var f = new Formfield();
      f.init(el);
   });
  }
}

function Formfield() {}
Formfield.prototype = {
  el: null,
  defaultMessage: null,

  init: function(el) {
    this.el = el;
    if(this.el.length == 0) {
      return false;
    }
    this.defaultMessage = $(this.el).attr('value');
    
    var that = this;
    $(this.el).focus(function() {
      if(($(this).attr('value') == that.defaultMessage) && !($(this).get(0).nodeName.toLowerCase() == 'select' && $.browser.msie)) {
        that.setEmpty();
      }
    });
    $(this.el).blur(function() {
      if(($(this).attr('value') == '') || ($(this).attr('value') == that.defaultMessage)) {
        that.setDefaultMessage();
      }
    });
    this.setDefaultMessage();
  },

  setDefaultMessage: function() {
    if(($(this.el).attr('value') == '') || ($(this.el).attr('value') == this.defaultMessage)) {
      $(this.el).attr('value', this.defaultMessage);
      $(this.el).addClass('default-state');
    }
  },

  setEmpty: function() {
    if($(this.el).attr('value') == this.defaultMessage) {
      $(this.el).attr('value', '');
      $(this.el).removeClass('default-state');
    }
  }
}

/* end - searchbox */



/***
 * ##ORNAMENTS
 */
function Ornaments() {}
Ornaments.prototype = {
  init: function() {
    this.setupRoundedCorners();
    this.setupShadows();
    this.setupArrows();
  },

  setupRoundedCorners: function() {
    var corners = ['corner-tl', 'corner-tr', 'corner-br', 'corner-bl'];
    $('.rounded').each(function(index, el) {
      for(var i=0, len=corners.length; i < len; i++) {
        $(el).append($('<span class="corner ' + corners[i] + '"></span>'));
      }
    });
  },

  setupShadows: function() {
    var shadows = ['shadow-tl', 'shadow-t', 'shadow-tr', 'shadow-r', 'shadow-br', 'shadow-b', 'shadow-bl', 'shadow-l'];
    $('.shadows').each(function(index, el) {
      for(var i=0, len=shadows.length; i < len; i++) {
        $(el).append($('<span class="shadow ' + shadows[i] + '"></span>'));
      }
    });
    $('div.bellow').each(function(index, el) {
      for(var i=0, len=shadows.length; i < len; i++) {
        $(el).append($('<span class="shadow ' + shadows[i] + '"></span>'));
      }
    });
    $('div.kwick-inner').each(function(index, el) {
      for(var i=0, len=shadows.length; i < len; i++) {
        $(el).append($('<span class="shadow ' + shadows[i] + '"></span>'));
      }
    });
  },

  setupArrows: function() {
    if(!$.browser.msie) {
      return false;
    }
    $('div.primary div.news-section div.newsitem p.singular a').append('<span class="ornament arrow">&nbsp;</span>');
    $('div.news-headlines-section div.newsitem p.singular a').append('<span class="ornament arrow">&nbsp;</span>');
  }
}
/* end - ornaments */



/***
 * ##STARTERBLOCKS
 */
function StarterBlocks() {}
StarterBlocks.prototype = {
  init: function() {
    return;
    var startersHeight = 0;
    $('div.starter-section').each(function(index, el) {
      if($(el).height() > startersHeight) {
        startersHeight = $(el).height();
      }
    });
    $('div.starter-section').each(function(index, el) {
      $(el).height(startersHeight);
    });
  }
}
/* end - starterblocks */



/***
 * ##SHAREBLOCKS
 */
function ShareBlocks() {}
ShareBlocks.prototype = {
  involvedEl: [],
  shareboxOverlay: null,

  init: function() {
    var that = this;
    if(typeof $ == 'undefined' || typeof $.fancybox == 'undefined') {
      return false;
    }

    $('a.to-share').each(function(index, el) {
      $($(el).attr('href')).addClass('share-subsection-hidden');
    });

    $('a.to-share').fancybox({
      'width': 310,
      'height': 150,
      'margin': 0,
      'padding': 0,
      'autoScale': false,
      'autoDimensions': false,
      'overlayOpacity': '0.7',
      'overlayColor': '#fff',
      'titleShow' : false,
      'onStart': function(el) {
        $(document.body).addClass('sharebox-enabled');
        if($(el).parent().parent().hasClass('resultcell-inner')) {
          $(el).parent().parent().addClass('resultcell-inner-focus');
        }
        if($(el).hasClass('to-share-up')) {
          $(document.body).addClass('sharebox-up-enabled');
        }
        $(document.body).addClass('sharebox-animating');
      },
      'onComplete': function(el) {
        if($(el).hasClass('to-share-up')) {
          $('#fancybox-wrap').css({
            'top': ($(el).offset().top - 232) + 'px',
            'left': ($(el).offset().left - 40) + 'px'
          });
        }
        else {
          $('#fancybox-wrap').css({
            'top': ($(el).offset().top + 60) + 'px',
            'left': ($(el).offset().left - 300) + 'px'
          });
        }
        $(document.body).removeClass('sharebox-animating');
      },
      'onCleanup': function() {
        $(document.body).addClass('sharebox-animating');
      },
      'onClosed': function() {
        $(document.body).removeClass('sharebox-animating');
        $(document.body).removeClass('sharebox-enabled');
        $('div.resultcell-inner-focus').removeClass('resultcell-inner-focus');
      }
    });
  }
}
/* end - shareblocks */



/***
 * ##APPLICATION
 */
function Application() {}
Application.prototype = {

  init: function() {
    if($.browser.msie) {
      this.ieFixes = new IEFix();
      this.ieFixes.init();
    }

    //this.setupSmoothScroll();

    this.FKwicks = new FABKwicksPeer();
    this.FKwicks.init();

    this.SelectpickerPeer = new SelectpickerPeer();
    this.SelectpickerPeer.init();

    //this.brandpickerPeer = new BrandpickerPeer();
    //this.brandpickerPeer.init();

    this.brandboxPeer = new BrandboxPeer();
    this.brandboxPeer.init();
    
    this.videoPeer = new VideoplayerPeer();
    this.videoPeer.init();

    this.accordionPeer = new AccordionPeer();
    this.accordionPeer.init();

    this.sb = new StarterBlocks();
    this.sb.init();

    var visualOrnaments = new Ornaments();
    visualOrnaments.init();

    var pgallPeer = new PhotogalleryPeer();
    pgallPeer.init();

    var shareb = new ShareBlocks();
    shareb.init();

    //this.registerClientInfo();
    this.setupHashUrls();
    this.setupHovers();
    this.setupPrint();
    this.setupLightboxes();
    this.setupForms();
    this.setupExternalLinks();
    this.fixBreadcrumbs();
    this.setupBrandsCarousel();
  },

  setupSmoothScroll: function() {
    $('#nav a').click(function(e) {
      var str = $(this).attr('href');
      $.scrollToElement($(str));
      e.preventDefault();
    });
  },

  setupHashUrls: function() {
    var that = this;
    $(window).bind('hashchange', function() {
      that.processUrl();
    });
    this.processUrl();
    this.accordionPeer.open(document.location.hash);
  },


  processUrl: function() {
    //this.FTabs.openTabOnHash(document.location.hash);
    this.accordionPeer.open(document.location.hash);
  },


  setupLightboxes: function() {
    if(typeof $ == 'undefined' || typeof $.fancybox == 'undefined') {
      return false;
    }

    $("a.to-video").fancybox({
      'width': 500,
      'height': 440,
      'margin': 0,
      'padding': 0,
      'autoScale': false,
      'type': 'iframe',
      'overlayOpacity': '0.7',
      'overlayColor': '#fff',
      'titleShow' : false,
      'onStart': function() {
        $(document.body).addClass('mediabox-enabled');
      },
      'onClosed': function() {
        $(document.body).removeClass('mediabox-enabled');
      }
    });
  },

  registerClientInfo: function() {
    var userOSAgent = navigator.userAgent.toLowerCase();
    jQuery.platform = {
      mac: /mac/.test(userOSAgent),
      osx: /mac os x/.test(userOSAgent),
      win: /win/.test(userOSAgent),
      linux: /linux/.test(userOSAgent)
    };
    $('body').addClass(navigator.userAgent.toLowerCase());
  },

  setupPrint: function() {
    $('div.column-secondary div.related-documents ul li.singular, .helper-tools ul li.singular').before('<li class="singular"><a href="#print" class="to-print"><span>print</span></a></li>');
    $('div.column-secondary div.related-documents ul li.singular .to-print, .helper-tools ul li.singular .to-print').click(function(e) {
      print();
      e.preventDefault();
    });
  },


  setupHovers: function() {
    /* Brands section */

    /* Searchresult section */
    $('div.searchresults tr.result').mouseenter(function() {
      $(this).addClass('result-hover');
    });
    $('div.searchresults tr.result').mouseleave(function() {
      $(this).removeClass('result-hover');
    });

    /* Jobssearchresult section */
    $('div.searchresults td.result-jobtitle div.resultcell-inner').mouseenter(function() {
      $(this).addClass('resultcell-inner-hover');
    });
    $('div.searchresults td.result-jobtitle div.resultcell-inner').mouseleave(function() {
      $(this).removeClass('resultcell-inner-hover');
    });

    /* Buttons */
    $('button').mouseenter(function() {
      $(this).addClass('button-hover');
    });
    $('button').mouseleave(function() {
      $(this).removeClass('button-hover');
    });

    /* Brandbox section */
/*
    $('div.brandbox-section').mouseenter(function() {
      $(this).addClass('brandbox-section-hover');
    });
    $('div.brandbox-section').mouseleave(function() {
      $(this).removeClass('brandbox-section-hover');
    });
*/

    /* Searchresults */
    $('body.searchresultspage div.searchresults div.result').mouseenter(function() {
      $(this).addClass('result-hover');
    });
    $('body.searchresultspage div.searchresults div.result').mouseleave(function() {
      $(this).removeClass('result-hover');
    });
    $('body.searchresultspage div.searchresults div.result').click(function() {
      document.location.href = $('h3 a', this).attr('href');
    });

    /* Main navigation */
    $('#navigation ul.nav-primary a').each(function(index, item) {
      $(item).append('<span class="ornament navarrow"></span>');
    });
  },

  
  setupForms: function() {
    // Textfield
    $('div.textfield-container input').focus(function(e) {
      $(this).addClass('has-focus');
      e.preventDefault();
    });
    $('div.textfield-container input').blur(function(e) {
      $(this).removeClass('has-focus');
      e.preventDefault();
    });

    // Textareafield
    $('div.textareafield-container textarea').focus(function(e) {
      $(this).addClass('has-focus');
      e.preventDefault();
    });
    $('div.textareafield-container textarea').blur(function(e) {
      $(this).removeClass('has-focus');
      e.preventDefault();
    });

    // Selectfield
    $('div.selectfield-container select').focus(function(e) {
      $(this).addClass('has-focus');
      e.preventDefault();
    });
    $('div.selectfield-container select').blur(function(e) {
      $(this).removeClass('has-focus');
      e.preventDefault();
    });

    var textfields = new Searchbox();
    textfields.init('div.textfield-container input.default-state');

    var selectfields = new Searchbox();
    selectfields.init('div.selectfield-container select.default-state');
  },


  setupExternalLinks: function() {
    $('a[rel=external]').each(function(index, el) {
      el.target = '_blank'; 1 
    });
  },

  // Fix breadcrumbs: hack for whitespace in breadcrumblinks
  fixBreadcrumbs: function() {
    var brCrumbs = [];
    $('#breadcrumbs a').each(function(index, el) {
      $(el).text(jQuery.trim($(el).text()));
      brCrumbs.push($(el).clone());
    });
    $('#breadcrumbs p').html('');
    for(var i=0, len=brCrumbs.length; i < len; i++) {
      $('#breadcrumbs p').append(brCrumbs[i]);
    }
  },

  // brands carousel
  setupBrandsCarousel: function() {
    if (typeof $.fn.jCarouselLite == 'undefined'){
      return;
    }
    var carouselContainer = $("div.brand-clipper");
    var numItems = carouselContainer.hasClass("brand-clipper-wide") ? 6 : 5;
    $("div.brands-section", carouselContainer).jCarouselLite({
     btnNext: ".carousel-next",
     btnPrev: ".carousel-previous",
     visible: numItems,
     auto: 4000,
     speed: 800
    });
  }
}
/* end - application */

/* start - tabbedcarousel */

// add this piece of code to catch the console.log calls if firebug is not available
try {
    console.log('core initiated');
} catch (e) {
    console = {};
    console.log = function(msg) {
        // do nothing
    }
}

/**
 * Tabbed Carousel
 * This is the main class "the controller"
 *
 * @static
 */
var TabbedCarousel = {
    /**
     * @var boolean
     */
    auto_play: false,

    /**
     * @var jQuery Element
     */
    root_element: null,

    /**
     * The tabbed carousel elements
     *
     * @var array TabbedCarouselElement objects
     * @static
     */
    tab_element_arr: [],

    /**
     * The slider/animation object
     *
     * @var TabbedCarouselSlider
     */
    slider: null,

    /**
     * The menu object
     *
     * @var TabbedCarouselMenu
     */
    menu: null,

    /**
     * The info object
     *
     * @var TabbedCarouselInfo
     */
    info: null,

    /**
     * The player object
     *
     * @var TabbedCarouselPlayer
     */
    player: null,

    /**
     * The trigger object
     *
     * @var TabbedCarouselTrigger
     */
    trigger: null,

    /**
     * Initialize the carousel
     *
     * @param int
     * @return void
     * @static
     */
    initialize: function(start_element_index) {
        // console.log('TabbedCarousel.initialize()');
        // get flash plugin version
        var version = deconcept.SWFObjectUtil.getPlayerVersion();

        // guard: stop if not the right flash plugin version is found
        if (version.major < 9) {
            alert('Please install flash version 9 or higher');
            return;
        }

        // get the root element
        TabbedCarousel.root_element = jQuery('div.tabs.media-carrousel');

        // get the elements
        TabbedCarousel.tab_element_arr = TabbedCarouselElement.getElements(TabbedCarousel.root_element);

        // guard: stop if there are no elements
        if (!TabbedCarousel.tab_element_arr.length) {
            return;
        }

        // determine the active element index
        var active_element_index = (start_element_index != undefined) ? start_element_index : Math.round(Math.random() * (TabbedCarousel.tab_element_arr.length - 1));

        // check if we are on the homepage
        var is_homepage = jQuery('body').hasClass('homepage');

        // create the slider
        TabbedCarousel.slider = new TabbedCarouselSlider(TabbedCarousel.root_element, TabbedCarousel.tab_element_arr, active_element_index);

        // create the menu
        TabbedCarousel.menu = new TabbedCarouselMenu(TabbedCarousel.root_element, TabbedCarousel.tab_element_arr, active_element_index);

        // create the info
        if (!is_homepage) {
            TabbedCarousel.info = new TabbedCarouselInfo(TabbedCarousel.root_element, TabbedCarousel.tab_element_arr, active_element_index);
        }

        // create the player
        TabbedCarousel.player = new TabbedCarouselPlayer(TabbedCarousel.root_element, TabbedCarousel.tab_element_arr);

        // create the trigger
        TabbedCarousel.trigger = new TabbedCarouselTrigger(TabbedCarousel.root_element, TabbedCarousel.tab_element_arr, is_homepage, active_element_index);

        // start the slideshow
        this.slider.startSlideshow();
    },
    

    /**
     * @return void
     */
    handleVideoFinished: function() {
        // stop the player, remove the html element and hide the player container
        TabbedCarousel.player.stop();
        
        // show the trigger
        TabbedCarousel.trigger.show();

        // show the menu
        TabbedCarousel.menu.show();

        // show the next element
        TabbedCarousel.slider.startSlideshow(1000);
    },

    /**
     * @return void
     */
    handleVideoPlaying: function() {
        TabbedCarousel.auto_play = true;

        // console.log('TabbedCarousel.handleVideoPlaying()');
        TabbedCarousel.menu.hide();
    },

    /**
     * @return void
     */
    handleVideoMouseOver: function() {
        // console.log('TabbedCarousel.handleVideoMouseOver()');
        if (TabbedCarousel.player.isPlaying()) {
            TabbedCarousel.menu.show();
        }
    },

    /**
     * @return void
     */
    handleVideoMouseOut: function() {
        // console.log('TabbedCarousel.handleVideoMouseOut()');
        if (TabbedCarousel.player.isPlaying()) {
            TabbedCarousel.menu.hide();
        }
    },

    /**
     * Handle for the event when the slide animation is finished
     *
     * @param int
     * @return void
     */
    handleStartSliding: function(index) {
        //console.log('TabbedCarousel.handleStartSliding');

        // hide the trigger
        TabbedCarousel.trigger.setInActive(index);

        // hide the info
        if (TabbedCarousel.info) {
            TabbedCarousel.info.setInActive(index);
        }
    },

    /**
     * Handle for the event when the slide animation is finished
     *
     * @param int
     * @return void
     */
    handleFinishedSliding: function(index) {
        //console.log('TabbedCarousel.handleFinishedSliding');

        // set the active menu item
        TabbedCarousel.menu.setActive(index);

        // show the trigger
        TabbedCarousel.trigger.setActive(index);

        // show the info
        if (TabbedCarousel.info) {
            TabbedCarousel.info.setActive(index);
        }

        // check for autoplay
        if (TabbedCarousel.auto_play && TabbedCarousel.tab_element_arr[index].hasVideo()) {

            // use a short delay to slide to the requested element
            setTimeout(function() {
                TabbedCarousel.slider.stopSlideshow();
                TabbedCarousel.trigger.setInActive(index);
                TabbedCarousel.player.show(index);

            }, 500);
        }
    },

    /**
     * Handle a click on the menu
     *
     * @param int
     * @return void
     */
    handleMenuClick: function(index) {
        //console.log('TabbedCarousel.handleMenuClick');
        TabbedCarousel.auto_play = false;

        // check if the player is busy
        if (TabbedCarousel.player.isPlaying()) {
            // stop the player, remove the html element and hide the player container
            TabbedCarousel.player.stop();

            // use a short delay to slide to the requested element
            setTimeout(function() {
                TabbedCarousel.slider.queue(index);
            }, 100);
        } else {
            // stop the player
            TabbedCarousel.player.stop();

            // queue the requested index for the slide animation
            TabbedCarousel.slider.queue(index);
        }

        // make sure the menu is shown
        TabbedCarousel.menu.show();
    },

    /**
     * Handle a click on a trigger
     *
     * @param int
     * @return void
     */
    handleTriggerClick: function(index) {
        //console.log('TabbedCarousel.handleTriggerClick');

        // hide the trigger
        TabbedCarousel.trigger.hide();

        // stop the slideshow
        TabbedCarousel.slider.stopSlideshow();

        // get the tab element
        var tab_element = TabbedCarousel.tab_element_arr[index];

        // check if it has video or is a "branbox'
        if (tab_element.hasVideo()) {
            TabbedCarousel.player.show(index);
        } else {
            document.location = tab_element.getBrandboxUrl();
        }
    },

    /**
     * @return void
     */
    handlePlayerReady: function() {
        //console.log('TabbedCarousel.handlePlayerReady');
        // check for auto play
        TabbedCarousel.player.play();
    }
};

/**
 * Tabbed Carousel Trigger
 *
 * @param jQuery Element
 * @param array TabbedCarouselElement objects
 * @param boolean
 * @param int
 */
var TabbedCarouselTrigger = function(root_element, tab_element_arr, show_title, active_element_index) {

    //console.log('new TabbedCarouselTrigger()');
    this.tab_element_arr = tab_element_arr;
    this.show_title = show_title;

    // set the active index
    this.active_element_index = active_element_index;

    // create a container element
    this.container = this.createContainer(root_element);

    // get the width of an element
    this.element_width = this.getElementWidth();

    

    // show the trigger
    this.show();
};
TabbedCarouselTrigger.prototype = {
    /**
     * @var jQuery Element
     */
    container: null,

    /**
     * @var array
     */
    tab_element_arr: [],

    /**
     * @var boolean
     */
    show_title: false,

    /**
     * @var int
     */
    fade_duration: 200,

    /**
     * The width of an element
     *
     * @var int
     */
    element_width: 0,

    /**
     * @var int
     */
    active_element_index: null,
    
    trigger_container: null,
    /**
     * Get the width of an element
     *
     * @return int
     */
    getElementWidth: function() {
        //console.log('TabbedCarouselSlider.getElementWidth()');
        // get the first tab element
        var tab_element = this.tab_element_arr[0];

        // return the width
        return tab_element.getWidth();
    },

    /**
     * @param int
     * @return void
     */
    setActive: function(index) {

        // set the active index
        this.active_element_index = index;

        // show the trigger
        this.show();
    },

    /**
     * @param int
     * @return void
     */
    setInActive: function(index) {
        // hide the trigger
        this.hide();
    },

    /**
     * Show the trigger
     * @return void
     */
    show: function() {
        this.container.css('display', 'block');
        
        if (this.show_title) {
            this.updateTriggerText();
        }
        // position the container
        this.position();
    },

    /**
     * Hide the trigger
     * @return void
     */
    hide: function() {
        this.container.css('display', 'none');
    },

    /** 
     * Position the conatiner
     *
     * @return void
     */
    position: function() {
        // get the width of the container
        var container_width = this.container.width();

        // calculate the left position so that the container is centered
        var left = Math.round((this.element_width - container_width) / 2);

        // apply the style
        this.container.css('left', left);
    },
    
    updateTriggerText: function(root_element){
        var tab_element = this.tab_element_arr[this.active_element_index];
        var title = tab_element.getTitle(); 
        this.trigger_container.text(title);
    },
    
    /**
     * Create the container element
     *
     * @param jQuery Element
     * @return jQuery Element
     */
    createContainer: function(root_element) {
        
        // IE8 fix; if omitted, ie8 will not execute click handle correctly
        root_element.append(jQuery('<div class="ie8fix"></div>')); 
        
        // with title case
        var container = jQuery('<div class="trigger"></div>');       
        
        this.trigger_container = container;
        // insert a new div element that will be the container
        root_element.append(container);

        // add extra class
        if (this.show_title) {
            this.trigger_container.addClass('with-text');
        }

        // add event
        var self = this;
        container.click(function() {
            this.blur();
            TabbedCarousel.handleTriggerClick(self.active_element_index);
        });

        return container;
    }
};

/**
 * Tabbed Carousel Slider
 *
 * @param jQuery Element
 * @param array TabbedCarouselElement objects
 * @param int
 */
var TabbedCarouselSlider = function(root_element, tab_element_arr, active_element_index) {
    // console.log('new TabbedCarouselSlider()');
    // get the element width
    this.element_width = this.getElementWidth(tab_element_arr);

    // set the active element index
    this.active_element_index = active_element_index;

    // create a container element
    this.container = this.createContainer(root_element);

    // get the elements
    this.element_arr = this.getElements(tab_element_arr);

    // see what James wrote about this
    // http://www.bennadel.com/blog/1856-Using-jQuery-s-Animate-Step-Callback-Function-To-Create-Custom-Animations.htm
    this.fx = jQuery({left: 0});
};
TabbedCarouselSlider.prototype = {
    /**
     * @var jQuery Element
     */
    container: null,

    /**
     * @var array, the image elements
     */
    element_arr: [],

    /**
     * @var int, the width of one element
     */
    element_width: 0,

    /**
     * The current active element index
     *
     * @var int
     */
    active_element_index: 0,

    /**
     * The interval for
     * @var int
     */
    slideshow_timeout: null,

    /**
     * The time it takes for the next image to show
     *
     * @var int
     */
    slideshow_timeout_time: 4000,

    /**
     * Indicates if the slideshow may show the next element
     * @var boolean
     */
    slideshow_loop: true,

    /**
     * The time it takes for the next image to show
     *
     * @var int
     */
    animation_time: 1400,

    /**
     * @var Object, used for animation
     */
    fx: null,

    /**
     * @var boolean
     */
    animation_in_progress: false,

    /**
     * @var int
     */
    queued_index: null,

    /**
     * Start the slideshow
     *
     * @param int
     * @return void
     */
    startSlideshow: function(time) {
        // console.log('TabbedCarouselSlider.startSlideshow()');
        if (!time) {
            time = this.slideshow_timeout_time;
        }

        // clear the timeout (if it exists)
        clearTimeout(this.slideshow_timeout);

        // set the slideshow in loop modus
        this.slideshow_loop = true;

        // a reference to this object
        var self = this;

        // set the timeout to show the next element
        this.slideshow_timeout = setTimeout(function() {
            self.next();
        }, time);
    },

    /**
     * Stop the slideshow
     *
     * @return void
     */
    stopSlideshow: function() {
        // console.log('TabbedCarouselSlider.stopSlideshow()');
        // clear the interval
        clearTimeout(this.slideshow_timeout);

        // set the slideshow NOT in loop modus
        this.slideshow_loop = false;
    },

    /**
     * Show the next image
     *
     * @return void
     */
    next: function() {
        // console.log('TabbedCarouselSlider.next()');
        // get the index for the next image
        var next_index = this.active_element_index + 1;

        // check if the index is valid
        if (next_index > this.element_arr.length - 1) {
            next_index = 0;
        }

        // start the animation
        this.show(next_index);
    },

    /**
     * @param int
     * @return void
     */
    show: function(index) {
        // console.log('TabbedCarouselSlider.show('+ index +') current active '+ this.active_element_index);
        // this class tells us that there is a animation in progress
        this.animation_in_progress = true;

        // clear the timeout (if it exists)
        clearTimeout(this.slideshow_timeout);

        // reference to this object
        var self = this;

        // get the necessary elements
        var active_element     = this.element_arr[this.active_element_index];
        var new_active_element = this.element_arr[index];

        // set the new active element on the right position
        new_active_element.css('left', this.element_width);

        // tell that the animation starts
        TabbedCarousel.handleStartSliding(this.active_element_index);

        // start the animation
        this.fx.animate({
                left: this.fx.attr('left') - this.element_width
            }, {
                duration: this.animation_time,
                //easing: 'easeInOutSine',
                step: function() {
                    self.setPosition(active_element, new_active_element, Math.round(this.left));
                },
                complete: function() {
                    self.animationFinished(index, active_element, new_active_element);
                }
            }
        );
    },

    /**
     * @param int
     * @return void
     */
    queue: function(index) {
        // console.log('TabbedCarouselSlider.queue('+ index +') current active: '+ this.active_element_index);
        this.slideshow_loop = true;

        // guard: do not queue the already active one
        if (index == this.active_element_index) {
            if (!this.animation_in_progress) {
                // tell that the animation finished
                TabbedCarousel.handleFinishedSliding(this.active_element_index);
            }

            return;
        }

        // check if there is a animation in progress
        if (!this.animation_in_progress) {
            // no animation in progress just show it
            this.show(index);
        } else {
            // queue the index
            this.queued_index = index;
        }
    },

    /**
     * @param Element
     * @param Element
     * @param int
     * @return void
     */
    setPosition: function(active_element, new_active_element, left) {
        // set the position of the two animating elements
        active_element.css('left', left);
        new_active_element.css('left', left + this.element_width);
    },

    /**
     * Animation is finished
     *
     * @param int
     * @param Element
     * @param Element
     * @return void
     */
    animationFinished: function(active_element_index, active_element, new_active_element) {
        // console.log('TabbedCarouselSlider.animationFinished('+ active_element_index +')');

        // make sure the elments are positioned correctly at their final position
        active_element.css('left', -this.element_width);
        new_active_element.css('left', 0);

        // reset the fx
        this.fx.attr('left', 0);

        // set the current active index
        this.active_element_index = active_element_index;

        // tell that the animation finished
        TabbedCarousel.handleFinishedSliding(this.active_element_index);

        // tell that the animation is stopped
        this.animation_in_progress = false;

        // stop
        if (!this.slideshow_loop) {
            return;
        }

        // check if there is a queued index
        if (this.queued_index && this.queued_index != this.active_element_index) {
            // show the queued index
            this.show(this.queued_index);
        } else {
            // reset the queued index
            this.queued_index = null;

            // start the slideshow
            this.startSlideshow();
        }
    },

    /**
     * Get the width of an element
     *
     * @param array
     * @return int
     */
    getElementWidth: function(tab_element_arr) {
        //console.log('TabbedCarouselSlider.getElementWidth()');
        // get the first tab element
        var tab_element = tab_element_arr[0];

        // return the width
        return tab_element.getWidth();
    },

    /**
     * Place the preview images
     *
     * @param array TabbedCarouselElement
     * @return array
     */
    getElements: function(tab_element_arr) {
        //console.log('TabbedCarouselSlider.getElements()');
        var element_arr = [];

        // loop through the tab elements
        for (var i = 0; i < tab_element_arr.length; i++) {
            // get the tab element
            var tab_element = tab_element_arr[i];

            // get the image
            var element = tab_element.getPreview();

            // set the position
            if (i == this.active_element_index) {
                element.css('left', 0);
            } else {
                element.css('left', this.element_width);
            }

            // place the image in the container
            this.container.append(element);

            // store the image
            element_arr.push(element);
        }

        return element_arr;
    },

    /**
     * Create the container element
     *
     * @param jQuery Element
     * @return jQuery Element
     */
    createContainer: function(root_element) {
        //console.log('TabbedCarouselSlider.createContainer()');
        // create the container
        var container = jQuery('<div class="slider" style="height: '+ root_element.innerHeight() +'px; width: '+ this.element_width +'px"></div>');

        // insert a the element in the DOM
        root_element.append(container);

        return container;
    }
};

/**
 * Tabbed Carousel Player
 *
 * @param jQuery Element
 * @param array TabbedCarouselElement objects
 */
var TabbedCarouselPlayer = function(root_element, tab_element_arr) {
    //console.log('new TabbedCarouselPlayer()');
    // store the object in the static var so it can be accessed by the functions called by flash
    TabbedCarouselPlayer.instance = this;

    // store the array
    this.tab_element_arr = tab_element_arr;

    // create a container element
    this.container = this.createContainer(root_element);

    // add event handlers
    this.addEventHandlers();

};
TabbedCarouselPlayer.prototype = {
    /**
     * @var jQuery Element
     */
    container: null,

    /**
     * @var array
     */
    tab_element_arr: [],

    /**
     * @var int
     */
    active_element_index: [],

    /**
     * @var SWFObject
     */
    flash: null,

    /**
     * @var string
     */
    status: 'IDLE',

    /**
     * @var string
     */
    streaming_server: 'rtmp://fms.quadiatv.com/quadiatv_v3',

    /**
     * Get the player status
     *
     * @return string
     */
    getStatus: function() {
        return this.status;
    },

    /**
     * Add event handlers
     *
     * @return void
     */
    addEventHandlers: function() {
        // reference to this object
        var self = this;

        // add some events
        this.container.mousemove(function() {
            TabbedCarousel.handleVideoMouseOver();
        });
        this.container.mouseleave(function() {
            TabbedCarousel.handleVideoMouseOut();
        });

    },
    
    /**
     * Set the player status
     *
     * @param string
     * @return string
     */
    setStatus: function(status) {
        // console.log('TabbedCarouselPlayer.setStatus() '+ status);
        this.status = status;

        if (this.status == 'COMPLETED') {
            TabbedCarousel.handleVideoFinished();
        } else if (this.status == 'PLAYING') {
            TabbedCarousel.handleVideoPlaying();
        }
    },

    /**
     * @return boolean
     */
    isPlaying: function() {
        // console.log('TabbedCarouselPlayer.isPlaying()');
        if (this.status == 'IDLE') {
            return false;
        }

        return true;
    },

    /**
     * Stop the player by removing the html element and hide the container
     *
     * @return void
     */
    stop: function() {
    
        //leaking ie7
        if (jQuery.browser.msie) {
            var player = document.getElementById('kraken-'+ this.active_element_index);
            removeFlaskLeakInIE('kraken-'+ this.active_element_index);
        }
        
        // kill the object
        delete this.flash;

        // empty the container
        this.container.empty();
        
        // set the status to idle
        this.status = 'IDLE';
    },

    /**
     * Play the movie
     *
     * @param int
     * @return void
     */
    show: function(index) {
        //console.log('TabbedCarouselPlayer.show()');

        this.active_element_index = index;
        // get the tab element
        var tab_element = this.tab_element_arr[index];

        // create the SWFObject for JW Player and set the flashvars for the flv/caption/preview/audio
        this.flash = new SWFObject('http://static.quadiatv.com/player/2010269-SNSReaal/player.swf', 'kraken-'+ this.active_element_index, 620, 349, '9');
        this.flash.addParam('allowfullscreen', 'true');
        this.flash.addParam('allowscriptaccess', 'always');
        this.flash.addParam('wmode', 'transparent');
        this.flash.addVariable('file', tab_element.getVideo());
        //this.flash.addVariable('image', tab_element.getPreviewSource());
        this.flash.addVariable('controlbar', 'over');
        this.flash.addVariable('screencolor', '0xffffff');
        this.flash.addVariable('stretching', 'fill');
        this.flash.addVariable('dock', 'false');
        
        //plugins
        var strPlugins = '';
        var strPluginsDelimiter = '';
        if (tab_element.getCaptions()){
          this.flash.addVariable('captions.file', tab_element.getCaptions());
          strPlugins += 'captions';
          strPluginsDelimiter = ',';
        }
        if (tab_element.getAudio()){
          this.flash.addVariable('audiodescription.file', tab_element.getAudio());
          strPlugins += strPluginsDelimiter + 'audiodescription';
        }
        this.flash.addVariable('plugins', strPlugins);
        
        //language switch
        var language = $('html').attr('lang') == 'en' ? 'en' : 'nl';
        this.flash.addVariable('language', language);

        // check if it is a streaming server
        if (tab_element.isStreamingVideo()) {
            //console.log('is streaming');
            this.flash.addVariable('streamer', this.streaming_server);
        }

        // place the flash in the container
        this.flash.write(this.container.attr('id'));

        // get the player element, do it the old fashioned way otherwise it will not work
        var player = document.getElementById('kraken-'+ this.active_element_index);

        // make it visible by setting the left position
        jQuery(player).css('left', 0);
        //console.log('kraken-'+ this.active_element_index);
        
        // build cookie value array if the video only has to be shown once. 
        // It is read by the server language and if exists does not render the entire tab element
        if (tab_element.isShownOnce()){
          this.handleOnceShown(tab_element.getVideo());
        }
    },
    
    
    handleOnceShown: function(videoURL) {
        
        var cookie_value = $.cookie('once-shown-videos') || '';
        if (cookie_value){
            cookie_value = '|' + cookie_value;
        }
        
        var new_value = '|' + videoURL;
            
        //remove possible existing values
        var cookie_value = cookie_value.replace(new_value, '', 'g');
        
        //and paste them in front
        cookie_value = new_value + cookie_value;
        
        //remove first pipe
        var cookie_value = cookie_value.substring(1, cookie_value.length);
        
        //now make sure there are not more then 20 items because of cookie limit 4096 bytes
        var cookie_array = cookie_value.split('|');
        if (cookie_array.length > 20){
            cookie_array.length = 20;
        }
        cookie_value = cookie_array.join('|');
        
        // set the cookies
        $.cookie('once-shown-videos', cookie_value, { expires: 365, path: '/'}); 
    },
    
    /**
     * @return void
     */
    play: function() {
        //console.log('TabbedCarouselPlayer.play()');
        // get the player element, do it the old fashioned way otherwise it will not work
        var player = document.getElementById('kraken-'+ this.active_element_index);

        // make it visible by setting the left position
        // jQuery(player).css('left', 0);

        // play the movie
        player.sendEvent('PLAY');
        
        
    },

    /**
     * Create the container element
     *
     * @param jQuery Element
     * @return jQuery Element
     */
    createContainer: function(root_element) {
        //console.log('TabbedCarouselPlayer.createContainer()');
        // create the container
        var container = jQuery('<div class="videoplayer player" id="player"></div>');

        // insert the element in the DOM
        root_element.append(container);

        return container;
    }
};
/**
 * @var TabbedCarouselPlayer
 * @static
 */
TabbedCarouselPlayer.instance = null;

/**
 * Hooks for flash - javascript communication
 */

/**
 * This method is called by flash
 *
 * @param Flash
 * @return void
 */
function playerReady(flash) {
    //console.log('playerReady');
    // get the flash emebed element
    var player = document.getElementById(flash.id);

    // guard
    if (!player) {
        console.log('Error: playerReady() - player not found');
        return;
    }

    // listen to flash callbacks
    player.addModelListener('STATE', 'stateListener');

    // handle the fact that the layer is ready
    TabbedCarousel.handlePlayerReady();
};

/**
 * This method is called by flash
 *
 * @param Object, (newstate: status, oldstate: status) possible statuses: IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
 * @return void
 */
function stateListener(obj) {
    //console.log('stateListener() '+ obj.newstate);
    // set the status
    TabbedCarouselPlayer.instance.setStatus(obj.newstate);
};

/**
 * Tabbed Carousel Menu
 *
 * @param jQuery Element
 * @param array TabbedCarouselElement objects
 * @param int
 */
var TabbedCarouselMenu = function(root_element, tab_element_arr, active_element_index) {
    //console.log('new TabbedCarouselMenu()');
    this.tab_element_arr = tab_element_arr;
    this.active_element_index = active_element_index;

    // create a container element
    this.container = this.createContainer(root_element);

    // create a preview element
    this.preview = this.createPreview(root_element);

    // get the elements
    this.element_arr = this.createElements();
};
TabbedCarouselMenu.prototype = {
    /**
     * @var jQuery Element
     */
    container: null,

    /**
     * @var jQuery Element
     */
    preview: null,

    /**
     * @var int
     */
    active_element_index: null,

    /**
     * @var int
     */
    preview_element_index: null,

    /**
     * @var array
     */
    tab_element_arr: [],

    /**
     * @var array
     */
    element_arr: [],

    /**
     * @var int
     */
    hide_preview_timeout: null,

    /**
     * @var int
     */
    hide_menu_timeout: null,

    /**
     * @return void
     */
    hide: function() {
        // console.log('TabbedCarouselMenu.hide()');
        clearTimeout(this.hide_menu_timeout);

        var self = this;
        
        // hide with a delay
        this.hide_menu_timeout = setTimeout(function() {
            // hide the preview
            self.hidePreview();
            var quadiaplayer = document.getElementById('kraken-'+ TabbedCarousel.player.active_element_index);
            if(quadiaplayer){
                quadiaplayer.sendEvent('CONTROLBAR_HIDE');
            };
            // hide the menu
            self.container.css('visibility', 'hidden');
        }, 2100);
    },

    /**
     * @return void
     */
    show: function() {
        // console.log('TabbedCarouselMenu.show()');
        clearTimeout(this.hide_menu_timeout);

        // show the menu
        this.container.css('visibility', 'visible');
        var quadiaplayer = document.getElementById('kraken-'+ TabbedCarousel.player.active_element_index);
        if(quadiaplayer){
            quadiaplayer.sendEvent('CONTROLBAR_SHOW');
        };
    },

    /**
     * @param inr
     * @return void
     */
    setActive: function(index) {
        //console.log('TabbedCarouselMenu.setActive()');
        // check if this item is already active
        if (this.active_element_index === index) {
            return;
        }

        // un activate the old active
        if (this.active_element_index !== null) {
            this.element_arr[this.active_element_index].removeClass('current');
        }

        // activate the new active
        this.active_element_index = index;
        this.element_arr[this.active_element_index].addClass('current');
    },

    /**
     * @return array
     */
    createElements: function() {
        //console.log('TabbedCarouselMenu.createElements()');
        var element_arr = [];

        // get the ul element
        var ul = jQuery('ul', this.container);

        // loop through the tab elements
        for (var i = 0; i < this.tab_element_arr.length; i++) {
            // create the menu item and store it in the array
            element_arr.push(this.createElement(this.tab_element_arr[i], i, ul));
        }

        return element_arr;
    },

    /**
     * @param TabbedcarouselElement
     * @param int
     * @aparam Element
     * @return Element
     */
    createElement: function(tab_element, index, ul) {
        //console.log('TabbedCarouselMenu.createElement()');
        // create the element
        var element = jQuery('<li class="menu-item menu-item-'+ index +'"><a href="javascript:void(null);">'+ tab_element.getLabel() +'</a></li>');

        // check if it is the active element
        if (index == this.active_element_index) {
            element.addClass('current');
        }

        // insert the element in the url
        ul.append(element);

        // reference to this object
        var self = this;

        // add some events
        element.click(function() {
            this.blur();

            TabbedCarousel.handleMenuClick(index);
        });
        element.mouseover(function() {
            self.showPreview(index);
        });
        element.mouseout(function() {
            self.onMouseOut(); // hides the preview with a delay
        });

        return element;
    },

    /**
     * @return void
     */
    onMouseOut: function() {
        var self = this;

        // clear the timeout that is used to hide the preview
        clearTimeout(this.hide_preview_timeout);

        // use a short delay to slide to the requested element
        this.hide_preview_timeout = setTimeout(function() {
            self.hidePreview();
        }, 600);
    },

    /**
     * @return void
     */
    onMouseOver: function() {
        // clear the timeout that is used to hide the preview
        clearTimeout(this.hide_preview_timeout);
    },

    /**
     * @return void
     */
    hidePreview: function() {
        //console.log('TabbedCarouselMenu.hidePreview()');
        // clear the timeout that is used to hide the preview
        clearTimeout(this.hide_preview_timeout);

        // hide the preview
        this.preview.css('visibility', 'hidden');

        // get the menu element that is in the preview
        var element = this.element_arr[this.preview_element_index];

        // check if it is an element
        if (element) {
            // add the hover class
            element.removeClass('hover');
        }

        // reset the index
        this.preview_element_index = null;
    },

    /**
     * @var int
     * @return void
     */
    showPreview: function(index) {
        // console.log('TabbedCarouselMenu.showPreview()');
        // clear the timeout that is used to hide the preview
        clearTimeout(this.hide_preview_timeout);

        if (this.preview_element_index !== null && this.preview_element_index !== index) {
            // get the menu element that is in the preview
            var element = this.element_arr[this.preview_element_index];

            // add the hover class
            element.removeClass('hover');
        }

        // store the index
        this.preview_element_index = index;

        // get the tab element belonging to this index
        var tab_element = this.tab_element_arr[index];

        // claculate the left position for the preview, so it lines up with the hovered menu item
        var element  = this.element_arr[index];
        var position = element.position();
        var left     = position.left + (element.width() / 2);

        // set html and make it visible
        this.preview.html(tab_element.getThumbnail());
        this.preview.css({
            'left': left,
            'visibility': 'visible'
        });

        // add the hover class
        element.addClass('hover');
    },

    /**
     * Create the preview element
     *
     * @return jQuery Element
     */
    createPreview: function(root_element) {
        //console.log('TabbedCarouselMenu.createContainer()');

        // get the container
        var preview = jQuery('<div class="preview"></div>');

        // insert the element in the DOM
        root_element.append(preview);

        // reference to object
        var self = this;

        // add some event handlers
        preview.mouseover(function() {
            self.onMouseOver();
        });
        preview.mouseout(function() {
            self.onMouseOut();
        });

        return preview;
    },

    /**
     * Create the container element
     *
     * @param jQuery Element
     * @return jQuery Element
     */
    createContainer: function(root_element) {
        //console.log('TabbedCarouselMenu.createContainer()');
        // create the container
        var container = jQuery('<div class="tabs-navigation"><ul></ul></div>');

        // insert the element in the DOM
        root_element.append(container);

        // if ie 6
        if (jQuery.browser.msie && jQuery.browser.version == '6.0') {
            this.fixZIndex(container);
        }

        return container;
    },

    /**
     * Fix the ie z-index hell
     * Every parent element has to have a z-index
     *
     * @return void
     */
    fixZIndex: function(container) {
        var zIndex  = '';
        var element = container;

        // go from the current element to the parent elements till you reach the body
        while (element.get(0).tagName != 'BODY') {
            // get the z-index from the element
            zIndex = element.css('z-index');

            // if the element has no z-index set it
            if (!zIndex) {
                element.css('z-index', 1);
            }

            // get the parent
            element = element.parent();
        }
    }
};

/**
 * Tabbed Carousel Info
 *
 * @param jQuery Element
 * @param array TabbedCarouselElement objects
 * @param int
 */
var TabbedCarouselInfo = function(root_element, tab_element_arr, active_element_index) {
    //console.log('new TabbedCarouselInfo()');
    this.tab_element_arr = tab_element_arr;

    // create a container element
    this.container = this.createContainer(root_element);

    // set the active one
    this.setActive(active_element_index);
};
TabbedCarouselInfo.prototype = {
    /**
     * @var jQuery Element
     */
    container: null,

    /**
     * @var array
     */
    tab_element_arr: [],

    /**
     * @var int
     */
    active_element_index: null,

    /**
     * @var int
     */
    fade_duration: 200,

    /**
     * @param int
     * @return void
     */
    setActive: function(index) {
        //console.log('TabbedCarouselMenu.setActive()');
        if (index == this.active_element_index) {
            return;
        }

        this.active_element_index = index;

        // set the opacity to 0
        this.container.css('opacity', 0);

        // get the tab element
        var tab_element = this.tab_element_arr[index];

        // get the info of the tab element and set it as the content of the container
        this.container.html(tab_element.getInfo());

        // start the fade in animation
        this.container.animate({opacity: 1}, this.fade_duration);
    },

    /**
     * @param int
     * @return void
     */
    setInActive: function(index) {
        //console.log('TabbedCarouselMenu.setInActive()');

        // start the fade out animation
        this.container.animate({opacity: 0}, this.fade_duration);
    },

    /**
     * Create the container element
     *
     * @param jQuery Element
     * @return jQuery Element
     */
    createContainer: function(root_element) {
        //console.log('TabbedCarouselMenu.createContainer()');
        // create the container
        var container = jQuery('<div class="info media-info"></div>');

        // insert the element in the DOM
        root_element.append(container);

        return container;
    }
};

/**
 * Tabbed Carousel Element
 *
 * @param int, the index
 * @param Element, the DOM Element
 */
var TabbedCarouselElement = function(index, element) {
    //console.log('new TabbedCarouselElement()');
    this.index   = index;
    this.element = jQuery(element);
};
TabbedCarouselElement.prototype = {
    /**
     * @var int
     */
    index: null,

    /**
     * @var jQuery Element
     */
    element: null,

    /**
     * @var jQuery Element
     */
    preview: null,

    /**
     * @var string
     */
    info: null,

    /**
     * @var string
     */
    title: null,

    /**
     * @var string
     */
    thumbnail: null,

    /**
     * @var string
     */
    video: null,

    /**
     * @var string
     */
    captions: null,

    /**
     * @var string
     */
    audio: null,

    /**
     * @var string
     */
    brandbox_url: null,

    /**
     * @var int
     */
    width: 0,

    /**
     * @var boolean
     */
    is_streaming_video: null,

    /**
     * @var string
     */
    label: null,

    /**
     * Get the label
     *
     * @return string
     */
    getLabel: function() {
        //console.log('TabbedCarouselElement.getLabel()');
        if (!this.label) {
            this.label = jQuery('span.tabitem-label', this.element).html();
        }

        return this.label;
    },

    /**
     * Get the width of the element (the width of the preview image)
     *
     * @return int
     */
    getWidth: function() {
        //console.log('TabbedCarouselElement.getWidth()');
        if (!this.width) {
            // get the preview image
            var preview = this.getPreview();

            // return the width
            this.width = preview.width();
        }

        return this.width;
    },

    /**
     * @return boolean
     */
    hasVideo: function() {
        //console.log('TabbedCarouselElement.hasVideo()');
        // get the video
        var video = this.getVideo();

        if (video) {
            return true;
        } else {
            return false;
        }
    },

    /**
     * @return string
     */
    getBrandboxUrl: function() {
        //console.log('TabbedCarouselElement.getBrandboxUrl()');
        if (!this.brandbox_url) {
            this.brandbox_url = jQuery('a.brandbox-wide', this.element).attr('href');
        }

        return this.brandbox_url;
    },

    /**
     * @return string
     */
    getVideo: function() {
        //console.log('TabbedCarouselElement.getVideo()');
        if (!this.video) {
            var video = jQuery('.to-video a', this.element).attr('href');

            if (video && video.substr(0,7) !== 'http://' && video.charAt(0) !== '/') {
                video = '../' + video;
            }

            this.video = video;
        }

        return this.video;
    },

    /**
     * @return boolean
     */
    isStreamingVideo: function() {
        if (!this.is_streaming_video) {
            var video = this.getVideo();

            if (video.substr(0,7) !== 'http://' && video.substr(0,8) !== 'https://' && video.indexOf(':') !== -1 && video.indexOf('/') !== -1) {
                this.is_streaming_video = true;
            }
        }

        return this.is_streaming_video;
    },
    
    /**
     * @return boolean
     */
    isShownOnce: function() {
        return this.element.hasClass('show-once');
    },

    /**
     * @return string
     */
    getAudio: function() {
        //console.log('TabbedCarouselElement.getAudio()');
        if (!this.audio) {
            this.audio = jQuery('.to-audiofragment a', this.element).attr('href');
        }

        return this.audio;
    },

    /**
     * @return string
     */
    getCaptions: function() {
        //console.log('TabbedCarouselElement.getCaptions()');
        if (!this.captions) {
            this.captions = jQuery('.to-subtitles a', this.element).attr('href');
        }

        return this.captions;
    },

    /**
     * @return string
     */
    getTitle: function() {
        //console.log('TabbedCarouselElement.getTitle()');
        if (!this.title) {
            this.title = jQuery('h2', this.element).html();

            // if no h2 found, get the alt of the preview
            if (!this.title) {
                var preview = this.getPreview();

                // get the alt text
                this.title = preview.attr('alt');
            }
        }

        return this.title;
    },

    /**
     * @return string
     */
    getThumbnail: function() {
        //console.log('TabbedCarouselElement.getThumbnail()');
        if (!this.thumbnail) {
            this.thumbnail = '<img src="'+ jQuery('img.video-thumbnail-preview', this.element).attr('src') +'" alt="'+ this.getTitle() +'" />';
        }

        return this.thumbnail;
    },

    /**
     * @return string
     */
    getInfo: function() {
        //console.log('TabbedCarouselElement.getInfo()');
        if (!this.info) {
            this.info = jQuery('div.media-info', this.element).html();
        }

        return this.info;
    },

    /**
     * Get the preview image
     *
     * @return Element
     */
    getPreview: function() {
        //console.log('TabbedCarouselElement.getPreview()');
        if (!this.preview) {
            // get the element
            this.preview = jQuery('img.video-preview,a.brandbox-wide img', this.element);
        }

        return this.preview;
    },

    /**
     * Get the preview image source
     *
     * @return Element
     */
    getPreviewSource: function() {
        //console.log('TabbedCarouselElement.getPreviewSource()');
        var preview = this.getPreview();

        return preview.attr('src');
    }
};
/**
 * Element factory
 *
 * @param jQuery Element
 * @return array TabbedCarouselElement objects
 * @static
 */
TabbedCarouselElement.getElements = function(root_element) {
    //console.log('TabbedCarouselElement.getElements()');
    var tab_element_arr = [];

    // get the elements and create TabbedCarouselElement objects
    jQuery('div.tab', root_element).each(function(index, element) {
        // create the TabbedCarouselElement
        var tab_element = new TabbedCarouselElement(index, element);

        // store the element in the array
        tab_element_arr.push(tab_element);
    });

    return tab_element_arr;
};

/* end - tabbedcarousel */

/* start - boardlist */
BoardList = {
    /**
     * @var Element (li)
     */
    active: null,

    /**
     * @return void
     */
    initialize: function() {
        // get the container
        var container = jQuery('div.board-list');

        // guard
        if (!container) {
            return;
        }

        // get the active one
        BoardList.active = jQuery('li.sel', container);
        
        BoardListItem = jQuery('li span', container);

        // add event handler
        BoardListItem.mouseover(function(event) {
            event.preventDefault();

            BoardList.handleMouseOver(event);

        });
    },

    /**
     * @param Event
     * @return void
     */
    handleMouseOver: function(event) {
        var target = jQuery(event.target);

        target = target.closest('li');

        if (!target) {
            return;
        }

        if (this.active == target) {
            return;
        }

        if (this.active) {
            this.active.removeClass('sel');
        }

        this.active = target;
        this.active.addClass('sel');
    }
};
/* end - boardlist */


/***
 * ##VIDEOPLAYER STANDALONE
 */
function VideoplayerPeer() {}
VideoplayerPeer.prototype = {
  players: [],
  init: function() {
    var that = this;
    $('div.article-section div.videoplayer').each(function(index, el) {
      $(el).attr('id','videoplayer-' + index);
      that.players[index] = new Videoplayer();
      that.players[index].init($(el), index);
      that.players[index].render();
    });
  },

  addPlayer: function() {}
};
function Videoplayer() {}
Videoplayer.prototype = {
  el: null,
  id: null,
  so: null,
  videoFile: null,
  preview: null,
  subtitles: null,
  audioFile: null,
  width: 620,
  height: 340,
  type: 'default', /* is either 'default' or 'tabbed' and should be in contant */

  init: function(el, id) {
    this.el = el;
    this.id = id;
    this.videoFile = $('p.to-video a', this.el).attr('href');
    if((this.videoFile.substr(0,7) !== 'http://') && (this.videoFile.charAt(0) !== '/')) {
      this.videoFile = '../' + this.videoFile;
    }
    this.videoPreview = $('img.video-preview', this.el).attr('src');
    this.subtitles = $('p.to-subtitles a', this.el).attr('href');
    this.audioFile = $('p.to-audiofragment a', this.el).attr('href');

    if(($(this.el).width() > 320) && ($(this.el).width() < 620)) {
      this.width = 460;
      this.height = 260;
    }

    var that = this;
    $('div.tab').each(function(index, el) {
      $('#' + $(that.el).attr('id'), el).each(function(indexJ, elJ) {
        that.type = 'tabbed';
      })
    });
  },

  render: function() {
    var so = new SWFObject('http://static.quadiatv.com/player/2010269-SNSReaal/player_klein.swf', 'quadiaplayer-small-' + this.id, this.width, this.height,'9');
    so.addParam('allowfullscreen','true');
    so.addParam('allowscriptaccess','always');
    so.addParam('wmode','transparent');
    so.addVariable('file',this.videoFile);
    so.addVariable('image',this.videoPreview);
    so.addVariable('controlbar','over');
    so.addVariable('screencolor','0xffffff');
    so.addVariable('stretching','fill');
    so.addVariable('dock','false');
    
    
    so.addVariable('captions.file', this.subtitles);
    so.addVariable('plugins','captions,audiodescription');
    so.addVariable('audiodescription.file', this.audioFile);
    
    //language switch
    var language = $('html').attr('lang') == 'en' ? 'en' : 'nl';
    so.addVariable('language', language);
    so.write(this.el.attr('id'));
    this.so = so;
  }
};

/* end - videoplayer */

jQuery(document).ready(function(){
  $('body').addClass('js-enhanced');
  app = new Application();
  app.init();
});

// these scripts need that all images are loaded
jQuery(window).load(function(){

    // start the tabbed carousel
    // accepts an argument for the active tab, this is the array index of the tab (e.g. the third tab has index 2)
    // if no active element is provided a random tab will be activated
    TabbedCarousel.initialize();

    // start the boardlist
    BoardList.initialize();
});

/* ie zut */
function removeFlaskLeakInIE(id) {
    var obj = document.getElementById(id);
        if (obj) {
            for (var i in obj) {
                if (typeof obj[i] == "function") {
                obj[i] = null;
                }
        }
        obj.parentNode.removeChild(obj);
    }
}
