//document.domain = 'bolius.dk';

jQuery.noConflict();

jQuery(document).ready(function($){ //jQuery onReady


	/*
	* Survey popups. Check cookie, and referrer.
	*/

	var curDate = new Date(),
		curMonth = curDate.getMonth();
		
	
	$('#survey-close').bind('click', function() {
		$.cookie('survey-disable', curMonth, { expires: 31 });
		$('#bolius-survey').hide();
		return false;
	});
	$('#survey-disable').bind('click', function() {
		$.cookie('survey-disable', curMonth, { expires: 31 });
		$('#bolius-survey').hide();
	});
	
	var hidden_survey = ($.cookie('survey-disable') && $.cookie('survey-disable') === curMonth);
	
	if (!hidden_survey) {
		$('#bolius-survey').show();
	}
	
	if (document.referrer.indexOf('mmm02.com') > 0) {
		$.cookie('subscribe', true, { expires: 92, path: '/' } );
	}

	if (!$.cookie('subscribe') && document.referrer.indexOf('google') > 0){
		$('#bolius-subscribe').show();
	}

	$('#subscribe-disable').bind('click', function() {
		$.cookie('subscribe', true, { expires: 92, path: '/' } );
		$('#bolius-subscribe').hide();
		return false;
	});



	/*
	* Bolius survey scrollable
	*/

	$('#content').append($('#bolius-survey'));
	if($('#bolius-survey-inner').offset()){
		var top = $('#bolius-survey-inner').offset().top - parseFloat($('#bolius-survey-inner').css('marginTop').replace(/auto/, 0));
		$(window).scroll(function (event) {
			// what the y position of the scroll is
			var y = $(this).scrollTop();
			// whether that's below the form
			if(y >= (top - 5)) {
				// if so, ad the fixed class
				$('#bolius-survey-inner').addClass('fixed');				
			} else {
				// otherwise remove it
				$('#bolius-survey-inner').removeClass('fixed');
			}
		});
	}



	/*
	* Fourcol news tabs
	*/
	$('.fourcolnews .ui-tabs-nav').each(function(){
		$(this).children('li').each(function(i){
			$(this).children('a').click(function(){
				//menu style
				$(this).parents().children('li').removeClass('ui-tabs-selected');
				$(this).parent().addClass('ui-tabs-selected');
				//hide'n'show divs
				$(this).parents().children('.ui-tabs-panel').hide();
				$(this).parents().children('.ui-tabs-panel').eq(i).show();
				return false;
			});
		});
	});
	

	
	/*
	* Anchor links
	*/

	// Anchor links in poll
	var a_id = $('.tx-jkpoll-pi1').prev().parent().attr('id');
	var action = $('.tx-jkpoll-pi1 form').attr('action') + '#' + a_id;
	$('.tx-jkpoll-pi1 form').attr('action',action);
	
	// Anchor links in mailformplus
	a_id = $('.tx-thmailformplus-pi1').parent().attr('id');
	action = $('.tx-thmailformplus-pi1 form').attr('action') + '#' + a_id;
	$('.tx-thmailformplus-pi1 form').attr('action',action);
	
	// Anchor links in pilmailform
	a_id = $('.tx-pilmailform-pi1').parent().attr('id');
	action = $('.tx-pilmailform-pi1 form').attr('action') + '#' + a_id;
	$('.tx-pilmailform-pi1 form').attr('action',action);

	
	
	/*
	* Remove link functionality from breadcrumb level 3 
	*/
	
	$('#main .breadcrumb .lvl3cur').click(function(){return false;});
	 
	
	
	/*
	* News single tables 
	*/
	
	$('.news-table-std').each(function(){
		$(this).find('table').each(function(){
			if($(this).children('tr:first').children('th').length < 1){
				$(this).find('tr:first td').each(function(){
					$(this).addClass('firsttd');
				});
			}
			$(this).children('tr:even td').addClass('odd');
			$(this).find('tr:last td').each(function(){
				if(!$(this).hasClass('odd')){
					$(this).addClass('lasttd');
				}
			});
		});
	});
	
	
	
	/*
	* News related tabs
	*/
	
	var lf_rel = $('#aside .lf_related'),
		inner = lf_rel.find('.inner'),
		startp = 1,
		endp = 5;
	
	inner
		.prepend('<div class="ui-tabs"> <ul class="ui-tabs-nav related-news-tabs"></ul></div>')
		.find('.news-single-related div').each(function(){
			lf_rel.find('.related-news-tabs').append('<li class="ui-state-default ui-corner-top ui-tabs-selected"><a href="">'+startp+'-'+endp+'</a></li>');
			startp = startp+5;
			endp = endp+5;
		});
	
	lf_rel.find('.ui-tabs-nav li').each(function(i){
		$(this).click(function(event){
			event.preventDefault();
			inner.find('.news-single-related div').hide();
			inner.find('.news-single-related div:eq('+i+')').show();
		});
	});
	
	

	/*
	* Remove form if it has been submitted 
	*/
	
	if($('.tx-lfsporgexpert-pi2').length > 0){
		$('.tx-lfsporgexpert-pi1').hide();
	}
	if($('#sporgexpert').length > 0){
		$('#sporgexpert').validate({
			rules: {
				'tx_lfsporgexpert_pi1[firstname]': "required",
				'tx_lfsporgexpert_pi1[lastname]': "required",
				'tx_lfsporgexpert_pi1[email]': {
					required: true,
					email: true
				}
			},
			messages: {
				'tx_lfsporgexpert_pi1[firstname]': "Fornavn mangler",
				'tx_lfsporgexpert_pi1[lastname]': "Efternavn mangler",
				'tx_lfsporgexpert_pi1[email]': {
					required: "Email mangler",
					email: "Angiv en korrekt email (navn@domæne.dk)"
				}
			}
		});
	}
	
	
	
	/*
	* Validate form in FCE Ask Counsellor (raadgivning)
	*/
	
	if($('#ask_counsellor').length > 0){
		$('#ask_counsellor').validate({
			rules: {
				'text': "required",
				'name': "required",
				'email': {
					required: true,
					email: true
				},
				'phone': {
					required:true,
					rangelength: [8,8]
				}
			},
			messages: {
				'text': "Spørgsmål mangler",
				'name': "Navn mangler",
				'email': {
					required: "Email mangler",
					email: "Angiv en korrekt email (navn@domæne.dk)"
				},
				'phone': {
					required: "Telefonnummer mangler",
					rangelength: "Indtast 8 cifre"
				}
			}
		});
	}



	/*
	* Commments remove if comments-disabled
	*/
	
	if($('.tx-comments-closed').length > 0 && $('.tx-comments-nocomments').length > 0){
		$('.tx-comments-pi1').remove();
	}
	
	
	
	/*
	* Remove border-right for last item in inspiration and xtra drop-down menus 
	*/
	
	$('#inspiration div:last-child, #xtra div:last-child').css('border',0);



	/*
	* Table of content in news start
	*/
				
	if($(".tx-lfcontentindex-pi1")){
		// Attach an anchor to all headers in content-inner
		$("#main .news-single-item h2").each(function(i){
			
			var header = $("#main .news-single-item h2:eq("+i+")").text();
			var headeritem = $("#main .news-single-item h2:eq("+i+")");
			
			if(headeritem.hasClass("noindex")){
			
			}else{
				// Trim header string	
				header = header.replace(/^\s+|\s+$/g,"");
				header = header.replace(/ /g, "-");
				header = header.replace(/\//g, "");
				header = header.replace(/\?/g, "");
				header = header.replace(/,/g, "");
				$("#main .news-single-item h2:eq("+i+")").before('<a name="' + header + '"></a>');
				$(".tx-lfcontentindex-pi1").append('<li><a href="'+location.pathname+'#' + header + '">' + $("#main  .news-single-item h2:eq("+i+")").text().replace(/^\s+|\s+$/g,"") + '</a></li>');
			}
		});
		
		$(".tx-lfcontentindex-pi1").wrapInner("<ul></ul>");
		$(".tx-lfcontentindex-pi1").prepend("<h2>Indhold på denne side</h2>");
	}



	/*
	* News img shadowbox link start
	*/

	$('.news-single-item .csc-textpic-image').each(function(){
		if($(this).children('dt').children('a').length > 0){
			var linkhref = $(this).children('dt').children('a').attr("href"),
				linkrel = $(this).children('dt').children('a').attr("rel"),
				linktarget = $(this).children('dt').children('a').attr("target"),
				linktitle = $(this).children('dt').children('a').attr("title"),
				zoomtxt = "Se stort billede";

			$(this).find('dt a').append($('<span>').addClass('enlargelink').html(zoomtxt));
		}
	});



	/*
	* Carousel
	*/
	
	$('.layout1 .jcarousel-skin-bolius').jcarousel({
		scroll: 2,
		initCallback: buildButtons,
		itemLastInCallback: updateButtons
		//wrap: 'circular'
	});
	$('.layout2 .jcarousel-skin-bolius').jcarousel({
		scroll: 1,
		initCallback: buildButtons,
		itemLastInCallback: updateButtons
		//wrap: 'circular'
	});
	$('.layout3 .jcarousel-skin-bolius').jcarousel({
		auto: 3,
		scroll: 1,
		initCallback: buildButtons,
		itemLastInCallback: updateButtons,
		wrap: 'last'
	});
	$('.layout4 .jcarousel-skin-bolius').jcarousel({
		scroll: 4,
		initCallback: buildButtons,
		itemLastInCallback: updateButtons
		//wrap: 'circular'
	});



	/*
	* Drop-down 
	*/
	
	$('#dropdown > div').each(function(i){
		$(this).appendTo($('#main-nav > ul > li').eq(i));
	});
	
	var isIframe = (window.location.href.indexOf('?id=1017') > -1); //true; //(window.location.href != window.top.location.href);
	
	$('#main-nav li').each(function(i){
		var li = $(this);
		li.hoverIntent(function(){
			li.addClass('over');
			if (isIframe) window.parent.resizeIframe(1);
		}, function(){
			li.removeClass('over');
			if (isIframe) window.parent.resizeIframe(2);
		});
		// Remove links
		li.find('a.mm').click(function(){
			return false;
		});
	});



	/*
	* Tilføj en even class til .imgtile elementerne
	*/

	$('.right2x2 .imgtile:nth-child(even)').addClass('even');



	/* 
	* This handles all the black mouseover effects on images - displays a border and the a title on mouseover.
	*
	* The structure must be like this :
	* <div class="imgtile">
	*  <a title="Categorytitle" href="#">
	*   <img src="someimage.jpg">
	*  </a>
	* </div>
	*/
	$('div.imgtile').each(function(){
		var t = $(this),
			a = t.find('a'),
			b = $('<div>').addClass('border').appendTo(a),
			d = $('<div>').text(a.attr('title')).appendTo(b);
		
		b.css({'padding-top': t.height()-d.height()-20}).hide();
			
		$(this).hover(function(){ 
			b.css({'left': t.position().left, 'top': t.position().top+4, 'width':t.find('img').width()-10, 'height':t.find('img').height()-b.css('padding-top')-10}).show(); 
		}, function() { b.hide(); });
	});

	setInterval(function(){ 
		if ($('iframe#sb-content').size()>0) {
			$('body').addClass('overflowhidden'); 
			$('body').removeClass('overflowauto'); 
		} else {
			$('body').removeClass('overflowhidden'); 
			$('body').addClass('overflowauto'); 
		}
	}, 1000 );



	/*
	* Laver en knap for at lukke shadowbox?
	*/
	
	$('.close-button').click(function(){ KeyCatcher.sendKeypress(27); });



	/*
	* Quiz - Gør alle sider i en quiz unikke
	* EGI, 06-09-11
	*/
	
	$('.tx-myquizpoll-pi1 form').each(function(){
		var f = $(this),
			a = f.attr('action'),
			q = f.find('input[name="tx_myquizpoll_pi1[uid1]"]').val();
			
		f.attr('action',a + '?q=' + q);
	});



	/*
	* Højre banner skal følge browservinduet når der scrolles
	* EGI: 07-09-11
	*/

	var top = 253;
 	$(window).scroll(function (event) {
    		// what the y position of the scroll is
    		var y = $(this).scrollTop();

		// whether that's below the form
    		if (y >= top) {
      			// if so, ad the fixed class
      			$('#fixed-banner').addClass('fixed');
    		} else {
      			// otherwise remove it
      			$('#fixed-banner').removeClass('fixed');
    		}
  	});	
  	
  	
  	
  	/*
  	* Slide relateret indhold ind 
  	* EGI: 19-10-11
  	*/
  	
	// V2	
	$('#main').find('.tx-lfrelatednews-pi1').each(function(){
	  	var item = $(this),
	  		height = item.height(),
	  		activate = $('.news-info:first').offset().top + height,
	  		y = 0;
	  		
	  	$(window).scroll(function (event) {
			y = $(this).scrollTop() + $(this).height(); // The distance from the top of the browser window to the to of the page + the browser window height
	    		if (y >= (activate) && y <= (activate+800)) {
				$('#main .tx-lfrelatednews-pi1').not(':animated').animate({bottom: 0}, 800);
		    	} else {
	      			$('#main .tx-lfrelatednews-pi1').not(':animated').animate({bottom: '-' + (height + 20) + 'px'}, 500);
	  		}
	  	});
	});
	/* Luk knap */
	$('#main .tx-lfrelatednews-pi1').append('<div id="lukrelnyt"><span>Luk</span></div>');
	$('#lukrelnyt').click(function(){
		$('#main .tx-lfrelatednews-pi1').remove();
	});
	
	
	// Video JS
	// EGI, 21.11.11
	VideoJS.setupAllWhenReady();
	
	
		
}); 				// End jQuery onReady



function buildButtons(carousel, state) {
	// Build buttons
	var carId = carousel.list.context.id;
	var carObj = jQuery('#' + carId);
	var buttonsNo = carousel.options.size;
	var howMany = carousel.options.scroll;
	
	if(buttonsNo > howMany){
		// Find containing div, and make a ul inside
		carObj.parents('.jcarousel-skin-bolius').prepend('<div class="jcarousel-control ' + carId + '"></div>');

		// Append controls to div
		for(button = 1; button <= buttonsNo; button = button+howMany){
			jQuery('.' + carId).append('<a href="#"><span>'+(button)+'</span>&nbsp;</a>');
		}
		// Bind click function to buttons
	 	jQuery('.' + carId + ' a').bind('click', function() {
			var scrollTo = jQuery.jcarousel.intval(jQuery(this).text());
			carousel.scroll(scrollTo);
			return false;
		});
	} else {
		carObj.parents('.jcarousel-skin-bolius').find('.jcarousel-prev, .jcarousel-next').hide();
	}
}



function updateButtons(carousel, item, idx, state) {
	// Update the position of the buttons
	var position = Math.ceil(idx / carousel.options.scroll);
	var carId = carousel.list.context.id;
	var carObj = jQuery('#' + carId);
	
	// Find the div, then find controls for that div and then update the active button
	carObj.parents('.jcarousel-skin-bolius').find('.jcarousel-control a').removeClass('active').eq(position-1).addClass('active');
}



function handleKeypress (keycode) {
	if (keycode==27 && typeof Shadowbox=='object') Shadowbox.close();
}


in_array = function (o, a) { for(var i = 0; i < a.length; i++) if(a[i] === o) return true; return false; }

var KeyCatcher = {};

// are all frames using KeyCatcher on same domain ?
// must be set to the same value in all instances on site
KeyCatcher.isSameDomain = true;

// list of all received data packets for avoiding circular transmission
KeyCatcher.handledData = [];

KeyCatcher.domain = '';

KeyCatcher.start = function () {
	kc = this;

	// setup keyboard events
	if (document.addEventListener) {
		document.addEventListener("keydown",kc.keydown,false);
	} else if (document.attachEvent) {
		document.attachEvent("onkeydown", kc.keydown);
	} else {
		document.onkeydown= kc.keydown;
	}

	jQuery(document).ready(function(){
		kc.domain = document.domain;

		if (!this.isSameDomain) {
			jQuery('body').attr('url', document.location.href);
		}
	});
};



// send data to all other windows
KeyCatcher.sendData = function (data) {
	if (this.isSameDomain) {
		// send up
		var kcobj = window.parent.KeyCatcher;
		if (typeof kcobj == 'object') kcobj.pushData(data);

		// send down
		for (var t=0; t<window.frames.length; t++) {
			try {
				var kcobj = window.frames[t].KeyCatcher;
				if (typeof kcobj == 'object') kcobj.pushData(data);
			} catch (E) {
			}
		}
	}
};



// used by other KeyCather objects to push data into this object
KeyCatcher.pushData = function (data) {
	this.handleData(data);
};


KeyCatcher.handleData = function (data) {
	this.handleKeypress (data);
};
	
// catches the keydown event
KeyCatcher.keydown = function(e){
	var kc=this;
	if (!e) e=event;
	if(e.target) element=e.target;
	else if(e.srcElement) element=e.srcElement;
	if(element.nodeType==3) element=element.parentNode;
	if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;

	var keycode = e.keyCode;

	if (!keycode || !in_array(keycode, [37, 39, 27])) return true;

	KeyCatcher.sendData(keycode);
	KeyCatcher.handleKeypress (keycode);
};

KeyCatcher.sendKeypress = function(keycode) {
	this.sendData (keycode);
};


KeyCatcher.handleKeypress = function (keycode) {
	if (typeof handleKeypress=='function')
		handleKeypress(keycode);
};

KeyCatcher.start();

function resizeIframe () { }
