// Document Ready Functions
jQuery(document).ready(function () {
    // Init Frontpage Banner
    if (jQuery("#bannerContainer").length > 0) { //don't call the function, if the element you call it on, does not exist. /JAB
        jQuery("#bannerContainer").leSlide({ showMarkers: true, showNumbers: true });
    }

    // Init TopMenu Context Menus
    jQuery(".L1ContextItem").click(function () {
        var id = $(this).attr("class").slice($(this).attr("class").indexOf(' ') + 1, $(this).attr("class").length);
        var leftPos = $(this).prev().position().left + "px";
        var innerBorderPos = -(401 - ($(this).parent().outerWidth() - $(this).outerWidth())) + "px top";
        var topBorderWidth = $(this).parent().innerWidth() - 1 + "px top";

        if ($(this).parent().hasClass("ContextActive")) {
            $(this).parent().removeClass("ContextActive");

            $("#" + id).hide();
        }
        else {
            $(".L1Context").removeClass("ContextActive");
            $(this).parent().addClass("ContextActive");
            $(".ContextMenuContainer").hide();

            // Position Context Dropdown and Background Graphics According to Menu Position
            $("#" + id).css({
                "background-position": topBorderWidth,
                "left": leftPos
            });
            $("#" + id + " .ContextMenuInnerBorder").css("background-position", innerBorderPos);

            // Show Context Dropdown
            $("#" + id).show();
        }
    });

    // Append a Slash [/] to any image src attributes
    if (location.href.toLowerCase().indexOf("~/link.aspx?_id=") >= 0) {
        jQuery("#ThreeColumnWrapper img").each(function () {
            jQuery(this).attr("src", "/" + jQuery(this).attr("src"));
        });
        jQuery(".TemaPageBackground #ThreeColumnWrapper a").each(function () {
            if (jQuery(this).attr("href").indexOf('http://') < 0) {
                jQuery(this).attr("href", "/" + jQuery(this).attr("href"));
            }
        });
        jQuery(".SubPageBackground #ThreeColumnWrapper a").each(function () {
            if (jQuery(this).attr("href").indexOf('~') == 0) {
                jQuery(this).attr("href", "/" + jQuery(this).attr("href"));
            }

        });
    }
});

// Show dropdown menu in teaser box
function ShowDropDown(obj){
	var isDropdownContainer = $("#MainWrapper > #DropdownContainer");
	var DDParent = jQuery(obj).parent().parent().parent().parent();
	var DDObj = jQuery(DDParent).find('.Dropdown');
	var DDContainer = jQuery(obj).parent()[0];
	var objPosTop = jQuery(DDParent).position().top;
	var objPosLeft = jQuery(DDParent).position().left;
	
	if(isDropdownContainer.length==0 || jQuery("#DropdownContainer").css("display")=="none"){
		if(isDropdownContainer.length<=0){
			jQuery('<div id="DropdownContainer" class="Dropdown"></div>').appendTo("#MainWrapper");
		}
		jQuery("#DropdownContainer").css({
			"top":objPosTop+DDContainer.offsetTop+25,
			"left":objPosLeft
		});
		jQuery("#DropdownContainer").html("");
		jQuery("#DropdownContainer").html(jQuery(DDObj).html());
		jQuery("#DropdownContainer").show();
		
		/*jQuery("body").one(function() {
			jQuery("#DropdownContainer").hide();
		});*/


	}
	else{
		jQuery("#DropdownContainer").hide();
	}
}


//slideshow pugin
	(function($){
		/*
		#		TODO
		#		-set up single loop
		#		-set up in view option
		#		-set up arrow nav
		#		-set up callback
		#
		*/
		$.fn.leSlide = function(options){
			var settings = {
				'slideSpeed'		:10000,	 	// Duration of the animation in milliseconds, if 0 only slide on user request
				'showNumbers'		:false, 	// Show slide counter true|false
				'showMarkers'		:false, 	// Show bullet navigation true|false
				'showNavigation'	:false, 	// Show prev/next navigation true|false
				'showMarkers'		:false, 	// Show bullet navigation true|false
				'transition'		:'fade', 	// Transition between objects up|down|left|right|fade
				'inView'			:1,			// Number of slides to show in view
				'auto'				:true,		// Auto scroll on slides true|false
				'loop'				:true		// Loop slides at end true|false
			};
			return this.each(function(){
				if ( options ) { 
					$.extend( settings, options );
				}
				var elmCount = $('li',this).length;		
				//If no elements are found exit
				if(elmCount < 2){
					return;
				}
				var $this = $(this);
				$(this).append('<span class="leftArrow"></span><span class="rightArrow"></span>');
				var next = $(".leftArrow",this);
				//back = options.leftArrow ? $(options.leftArrow) : $("<span class='leftArrow'><</span>");
				//next = options.rightArrow ? $(options.rightArrow) : $("<span class='rightArrow'>></span>");
				var elmHeight = $('li:first',this).height();
				var elmWidth = $('li:first',this).width();
				var startPos;
				var pointer = 1;
				var prev = 0;

				switch(settings.transition){
					case 'fade':
						startPos =[0,0];
						thisIn ={opacity:1};
						thisOut ={opacity:0};
						break;
					case 'up':
						startPos =[0,elmHeight];
						thisIn ={'top':0};
						thisOut ={'top':-elmHeight};
						break;
					case 'down':
						startPos =[0,-elmHeight];
						thisIn ={top:0};
						thisOut ={top:elmHeight};
						break;
					case 'left':
						startPos =[elmWidth,0];
						thisIn ={left:0};
						thisOut ={left:-elmWidth};
						break;
					case 'right':
						startPos =[-elmWidth,0];
						thisIn ={left:0};
						thisOut ={left:elmWidth};
						break;
				};
				var displayWidth = $('li:first',this).width()*settings.inView;
				$('li',this).css({
					'position':'absolute',
					'left':startPos[0],
					'top':startPos[1]
				});
				$('li:first',this).css('z-index','999').addClass('current');
				if(settings.transition==='fade'){
					$("li:not(:first)",this).css({
						'opacity':0,
						'z-index':998
					});
				}
				else{
					$('li:first',this).css({
						'left':0,
						'top':0
					})
				}
				$(this).css({
					'position':'relative',
					'height':elmHeight,
					'width':elmWidth,
					'overflow':'hidden'
				});
				if(settings.auto===true) {//start the slides
					setInterval(function() {
						next.click();
					},settings.slideSpeed);
				}
				//add markers if requested
				if(settings.showMarkers===true){
					var str = '';
					for (var i=1; i<=elmCount; i++) {
						if(settings.showNumbers===true){
							str = str+'<li>'+i+'</li>';
						}
						else{
							str = str+'<li></li>';
						}
					};
					$(this).append('<ul class="markers"></ul>');
					$('.markers',this).append(str);
					$('.markers li:first',this).addClass('current');
					$('.markers li').click(function(){
						pointer=$('.markers li').index(this);
						next.click();
					});
				}

				next.click(function(){
					$('ul:first li.current',$this).animate(thisOut,600,'swing',function(){
						if(settings.transition!='fade'){
							$(this).css({
								'left':startPos[0],
								'top':startPos[1]
							});
						};
					}).css('z-index','998').removeClass('current');
					$('.markers li',$this).removeClass('current');
					$('.markers li:eq('+pointer+')',$this).addClass('current');
					$('li:eq('+pointer+')',$this).animate(thisIn,600,'swing').css('z-index','999').addClass('current');
					if(pointer+1===elmCount){
						pointer=0;
					}
					else{
						pointer++;
					}
				});
			});
		};
	})( jQuery );


// FAQ Function
function InitFaq(){
	jQuery(".FaqList .Question").toggle(
	function(){
		jQuery(this).next().slideDown('fast');
		jQuery(this).find(".QuestionIcon").css('background-position','0 -601px');
	},
	function(){
		jQuery(this).next().slideUp('fast');
		jQuery(this).find(".QuestionIcon").css('background-position','0 -562px');
	});
	
	jQuery(".FaqSection li").each(function(n){
		jQuery(this).click(
			function(){
				jQuery(".FaqSection .Active").removeClass("Active");
				jQuery(this).addClass('Active');
				jQuery(".FaqList .Visible").addClass('Hidden');
				jQuery(".FaqList .Visible").removeClass('Visible');
				jQuery(".FaqCategory:eq("+ n +")").removeClass('Hidden');
				jQuery(".FaqCategory:eq("+ n +")").addClass('Visible');
			});
		});
}

// Search function
var searchResultPathDK = "/DA/Soegeresultat.aspx";
var searchResultPathUK = "/EN/SearchResult.aspx";

function SearchResult() 
{
    this.LastQuery = "";
}

SearchResult.prototype.Search = function(query,isEnglish) {   

    var isEnglishBool = new String(isEnglish); 
        
    if(isEnglishBool.match('true'))  
        window.location = searchResultPathUK + '?query=' + encodeURI(Strip(query));
    else
        window.location = searchResultPathDK + '?query=' + encodeURI(Strip(query));
}

SearchResult.prototype.ShowAll = function(query, section, isEnglish) {

    var isEnglishBool = new String(isEnglish);

    if(isEnglishBool.match('true'))
        window.location = searchResultPathUK + '?query=' + encodeURI(Strip(query)) + "&section=" + encodeURI(Strip(section)) + "&showall=true";
    else
        window.location = searchResultPathDK + '?query=' + encodeURI(Strip(query)) + "&section=" + encodeURI(Strip(section)) + "&showall=true";
}    
var searchResult = new SearchResult();

function Strip(str){
	str.replace(/^\s+/, '');
	str.replace(/\s+$/, '');
	return str;
}

//Function to add/change/remove query string parameters
function goToParam(param,val){
	var path = location.search.replace('?','');
	if(path.match(param)==null){
		if(path==''){
			path=param+'='+val;
		}
		else{
			path=path+'&'+param+'='+val;
		}
	}
	else{
		path = path.split('&');
		for(i=0;i<path.length;i++){
			if(path[i].substring(0,path[i].indexOf('='))==param){
				if(val=='remove'){
					path.splice(i,1);
				}
				else{
					path[i] = path[i].replace(path[i].substring(path[i].indexOf('=')+1),val);
				}
			}
		}
		path=path.toString().replace(/,/g,'&');
	}
	window.location=location.pathname+'?'+path;
}

// Find query string
function getQueryString() {
   var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

   while (m = re.exec(queryString)) {
      result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
   }
   return result;
}

$(document).ready(function () {
   $(".chkBox input[type=radio]").addClass("hidden");

   $(".chkBox input:checked").each(function () {
      $(this).parent(".chkBox").addClass("checked");
   });

   $(".chkBox").click(function () {
      $(this).siblings(".chkBox").removeClass("checked");

      var $radio = $(this).find(":radio");
      $radio.attr("checked", "checked");

      $(this).addClass("checked");
   });

   $(".numOnly").keyup(function () {
      this.value = this.value.replace(/[^0-9\.]/g, '');
   });


   $(".lisSearchMethod").children("li").click(function () {
      location.href = $(this).children("a").attr("href");
   });


   // Put the current search method in the dropdown as a helper
   $(".lisSearchMethod").each(function () {
      var q = getQueryString()["searchType"];
      var t = "Fritekst";

      if (q == "postnummerInterval") {
         t = "Postnummmerinterval";
      } else if (q == "fritekst") {
         t = "Fritekst";
      } else if (q == "postnummer") {
         t = "Postnummer";
      } else if (q == "city") {
         t = "Bynavn";
      } else if (q == "virksomhed") {
         t = "Virksomhedsnavn";
      }

      $(".conSearchMethod").prepend("<span>" + t + "</span>");
   });


   // Toggle search method on custom radio buttons
   $(".conSearchMethod").click(function () {
      $(this).children(".lisSearchMethod").toggle();
   });

   $(".result-outer").hover(function () {
      $(this).css("background", "#fff");
      $(this).siblings("tr").css("background", "#eee");
   }, function () {
      $(".result-outer").css("background", "#fff");
      $(".result-outer:odd").css("background", "#fafafa");
   });

   $(".result-outer").click(function () {
      var url = $(this).find(".lnkResult").attr("href");
      window.open(url);
   });

   // Manipulate layout
   $("#searchResCon").each(function () {
      var q = getQueryString()["q"];
      var r = $("#searchCount span").text();
      var p = $("#searchPaging").children("a").length;

      // If there are no match, hide the table
      if (r < 1) {
         $("#searchPerPage, #searchResHead, .searchHideOn0").hide();
      } else if (r < 11) {
         $("#searchPerPage").hide();
      }

      // If there has been no query yet, hide the whole thing altogether
      if (typeof q === 'undefined') {
         $(this).hide();
      } else {
         $(this).delay(200).fadeIn(400);
      }

      if (p < 6) {
         $("#searchPaging").hide();
      }

   });

});


/* Cufon styling */
Cufon.replace(".SectionBanner h1");
Cufon.replace(".TemaPageBannerTitle h1");
Cufon.replace(".TemaTopBannerSubHeadline");
Cufon.replace(".TeaserTitle");
Cufon.replace(".L1Item");
Cufon.replace(".BannerContent h1");
Cufon.replace(".BannerContent h2");


