$.fn.outline = function(options, counters){
    var options  = $.extend({}, $.fn.outline.defaults, options),
        counters = counters || [];

    this.each(function(){
       $(this).children('li').each(function(i){
           var ct = counters.concat([i + 1]);
           if(counters.length){
             $('<span></span>')
                .addClass(options.numberClass)
                .text(ct.join('.') + ' ')
                .prependTo(this);
           }
           $(this).children('ol').outline(options, ct);
       })
    });

    if(!counters.length) this.addClass(options.processedClass)
}

$.fn.outline.defaults = {
       numberClass: 'pseudo-num',
    processedClass: 'pseudo-processed'
}

var oprah =
{
	init: function ()
	{
		$("#terms-ol").outline();
		var hash = window.location.hash;
		hash = hash.replace("#", "");
		
		var src = $("#oprah-frame").attr("src");
		$("#oprah-frame").attr("src", src + "?p=" + hash);
		
		$("#oprah-frame").load(function ()
		{
			var iframe = $(this).contents();
			iframe.find(".parent-blank").click(function (e)
			{
				e.preventDefault();
				window.open(this.href, '_blank');
			});
		
			window.parent.parent.scrollTo(0,0);
			iframe.find(".terms").click(function (e)
			{
				e.preventDefault();
				loadPopbox('terms', [388,533], true);
			});
		})		
	}
}

$(document).ready(function(){
  if ($.browser.msie) {
    window.onbeforeunload = function(){
      $('embed,object').each(function(){
        $(this).wrap('<div style="height:'+$(this).height()+'px"></div>');
        $(this).remove();
      });
    }
  }

  alanredBanner();
  if ($("#oprah-frame")) oprah.init();
  initWelcome();
  initPopboxLinks();
  renderFonts();
  searchDefault();
  newsDefault();
  initStills();
});

function initWelcome() {
  var welcome = $('#welcome');
  var ref = ref_site();
  if (welcome.length && ref != false && !readCookie('welcome_'+ref)) {
    var intro = '';
    if (ref == 'Google') {
      intro = 'Wil je als eerste op de hoogte zijn van backstagevideo\'s met BN\'ers, winacties, nieuws en funfacts?';
    } else if (ref == 'Twitter') {
      intro = 'Wil je als eerste op de hoogte zijn van backstagevideo\'s met BN\'ers, winacties, nieuws en funfacts?';
    } else {
      intro = 'Wil je als eerste op de hoogte zijn van backstagevideo\'s met BN\'ers, winacties, nieuws en funfacts?';
    }
    welcome.html('<h2>Welkom <span>via '+ref+'</span></h2><p>Fijn dat je LINDAmagazine.nl gevonden hebt via '+ref+'.<br />'+intro+'<br /><br />Meld je dan aan voor de gratis LINDA. nieuwsbrief:</p><form method="post" action=""><label for="newsletter_email">E-mailadres:</label><input type="text" value="" name="newsletter_email" id="newsletter_email" /><input type="submit" id="newsletter_submit" value="Aanmelden" /></form><p class="latest"><a href="'+latest_newsletter_url+'" target="_blank" class="newsletter" rel="popbox">Klik hier om de laatste nieuwsbrief te bekijken.</a></p>').show();
    createCookie('welcome_'+ref, 'true', 364);
  }
}

function ref_site() {
  if (!document.referrer) {
    return false;
  }

  if (document.referrer.indexOf('google.com') != -1 || document.referrer.indexOf('google.nl') != -1)
  {
    return 'Google';
  }

  if (document.referrer.indexOf('rtl.nl/actueel/rtlboulevard') != -1)
  {
    return 'RTL Boulevard';
  }

  if (document.referrer.indexOf('shownieuws.tv') != -1)
  {
    return 'SBS6 Shownieuws';
  }

  if (document.referrer.indexOf('nu.nl') != -1)
  {
    return 'NU.nl';
  }

  if (document.referrer.indexOf('twitter.com') != -1)
  {
    return 'Twitter';
  }

  return false;
}

var stills_rotation = false;
function initStills() {
  var stills = $('#carrousel li');
  if (!stills.length) return false;

  clearInterval(stills_rotation);
  stills_rotation = setInterval("stillNext()", 5000);
}

function stillPrev() {
  var stills = $('#carrousel li');
  if (!stills.length) return false;

  var active = $('#carrousel li.active');
  if (active.prev().length) {
    active.prev().addClass('active');
  } else {
    $('#carrousel li:last').addClass('active');
  }
  active.removeClass('active');
  initStills();
}

function stillNext() {
  var stills = $('#carrousel li');
  if (!stills.length) return false;

  var active = $('#carrousel li.active');
  if (active.next().length) {
    active.next().addClass('active');
  } else {
    $('#carrousel li:first').addClass('active');
  }
  active.removeClass('active');
  initStills();
}

function renderFonts() {
  Cufon.replace('p.date, p.category', {fontFamily: 'CenturyBook'});
}

function searchDefault() {
  var default_text = 'Zoeken';
  var el = $('#s');
  if (el) {
    el.val(default_text);
    el.focus(function(){
      if (el.val() == default_text) {
        el.val('');
      }
    });
    el.blur(function(){
      if (el.val() == '') {
        el.val(default_text);
      }
    });
  }
}

function newsDefault() {
  var default_text = 'Je e-mailadres';
  var el = $('#newsletter_email');
  if (el) {
    el.val(default_text);
    el.focus(function(){
      if (el.val() == default_text) {
        el.val('');
      }
    });
    el.blur(function(){
      if (el.val() == '') {
        el.val(default_text);
      }
    });
  }
}

function toggleShare(id) {
  $('#'+id).toggle();
}

function alanredBanner() {
  if ($('#alanredbanner').length) {
    var flashvars = {};
    flashvars.play = true;
    flashvars.loop = true;
    swfobject.embedSWF(image_path+'banner/032411-AR-movie-web.swf', 'alanredbanner', '336', '280', '9.0.0', image_path+'images/expressInstall.swf', flashvars);
  }
}

function mailFriend(id) {
  if ($('#share-'+id).length) {
    $('#share-'+id).hide();
  }
  if ($('#share-sidebar-'+id).length) {
    $('#share-sidebar-'+id).hide();
  }

  loadPopbox('sendfriend-'+id, [400,405]);
}



// popbox
function showPopbox(size) {
  var viewport = vp();
  var offset = os();
  if (typeof document.body.style.maxHeight === "undefined") {
    $('html').css('overflow', 'hidden');
  }
  $('body').append('<div id="overlay"></div>');
  var overlay = $('#overlay');
  var height = body_height();
  overlay.css('height', height+'px');
  detectMac() ? overlay.addClass('overlay_mac') : overlay.addClass('overlay');
  overlay.click(function(){
    hidePopbox();
  });
  $('body').append('<div id="popbox"></div>');
  var popbox = $('#popbox');
  document.onkeydown = function (e) {
    keycode = (e == null) ? event.keyCode : keycode = e.which;
    if (keycode == 27) {
      hidePopbox();
    }
  };
  if (size) {
    popbox.css({'width': size[0]+'px', 'height': size[1]+'px'});
  }
  var popbox_width = popbox.width();
  var popbox_height = popbox.height();
  var left = Math.round((viewport[0] - popbox_width) / 2);
  left = (left < 0) ? 0 : left;
  var top = Math.round(((viewport[1] - popbox_height) / 2) + offset[1]);
  top = (top < 0) ? 0 : top;
  popbox.css({'left': left+'px', 'top': top+'px', 'display': 'block'});
  popbox.show();
}

function loadPopbox(id, size, no_remove) {
  var el = $('#'+id);
  if (el) {
    showPopbox(size);
    $('#popbox').html(el.html());
    if (!no_remove) {
      el.remove();
    }
  }
}

function loadPopboxUrl(url, dimensions) {
  if (!dimensions) {
    dimensions = [542,542];
  }
  showPopbox(dimensions);
  $('#popbox').css('padding', 0).html('<iframe src="'+url+'" frameborder="0" style="overflow:auto;width:100%;height:505px;margin-top:37px"></iframe><a href="#" onclick="hidePopbox();return false" class="close" style="top:10px;right:10px">sluiten</a>');
}

function hidePopbox() {
  document.onkeydown = '';
  $('#popbox').remove();
  $('#overlay').remove();
  $('html').css({overflow: ''});
}

function initPopboxLinks() {
  $('a[rel="popbox"]').each(function(){
    var href = $(this).attr('href');
    if (href.substr(0,1) == '/') {
      href = site_url + href;
    }
    if ($(this).hasClass('newsletter')) {
      $(this).click(function(){loadPopboxUrl(href, [640,542]); return false;});
    } else {
      $(this).click(function(){loadPopboxUrl(href); return false;});
    }
  });
}

function overlaySize() {
  var overlay = $('#overlay');
  if (overlay.length) {
    var height = body_height();
    overlay.css('height', height+'px');
  }
}

function detectMac() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('firefox') != -1) {
    return true;
  }
}

function vp() {
  var x, y;

  if (self.innerHeight) {
    x = self.innerWidth;
    y = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  } else if (document.body) {
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }

  return [x, y];
}

function os() {
  var x, y;

  if (self.pageYOffset) {
    x = self.pageXOffset;
    y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  } else if (document.body) {
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }

  return [x, y];
}

function body_height() {
  if (document.documentElement.clientHeight > document.documentElement.scrollHeight) {
    return document.documentElement.clientHeight;
  } else {
    return document.documentElement.scrollHeight;
  }
}

function createCookie(name, value, days) {
  name = name.replace(/ /gi, '');
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = '; expires='+date.toGMTString();
  } else {
    var expires = '';
  }
  document.cookie = name+'='+value+expires+'; path=/';
}

function readCookie(name) {
  name = name.replace(/ /gi, '');
  var nameEQ = name + '=';
  var ca = document.cookie.split(';');
  for (var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name, '', -1);
}
