/**
 * Legt ein Default-Value fuer eine Textbox fest.
 * Wird auf die Textbox geklickt, die den Default-Value enthaelt, wird dieser aus der
 * Textbox geloescht. Wird die Textbox ohne Eingabe verlassen, wird der Inhalt wieder
 * auf den Default-Value zurueckgesetzt.
 *
 * @param value string Default-Wert der Textbox
 * @param options Object
 *                  - class : CSS-Klasse der Textbox die den Default-Value enthaelt
 *
 * @version 1.0
 */
$.fn.setDefaultValue = function (options) {
    var options = $.extend({
        css: 'txt_default'
    }, options);

    return this.each(function () {
        var $this = $(this);

        var value = $this.attr('value');

        $(this).attr('autocomplete', 'off');

        if ($this.val().length <= 0 || $this.val() == value) {
            $this.addClass(options.css);
            $this.val(value);
        }

        $this.click(clear);

        $this.blur(fill);

        $this.focus(clear).blur();

        function clear() {
            if ($this.hasClass(options.css) || $this.val() == value) {
                $this.val('');
                $this.removeClass(options.css);
            }
        }

        function fill() {
            if ($this.val().length <= 0) {
                $this.addClass(options.css);
                $this.val(value);
            }
        }
        $(window).unload(clear); // Firefox-Autocomplete
    });
}; /* End of input plugin */


var windowFocus = true;

$(window).bind("blur", function() {
    windowFocus = false;
});

$(window).bind("focus", function() {
    windowFocus = true;
});


/* Slider plugin */
$.fn.slider = function (options) {

    var options = $.extend({
        content: "img",
        duration: 200,
		autoRotateDuration: 0,
        //defult settings for animation speed
        easing: "easeOutSine" //default for easing effect
    }, options);


    return this.each(function () {

        var $this = $(this);
		
		var autoRotateTimer;

        var content = options.content;

        var duration = options.duration;
        if ($.browser.msie) {
            duration = 0;
        }
		
		var autoRotateDuration = options.autoRotateDuration;
		

        //console.log(content);
        $this.find(content).hide();

        var contentFirstChild = content + ":first-child";

        //console.log(contentFirstChild);
        $this.find(contentFirstChild).addClass("current").show();

        $this.find(content).each(function (n) {

            $this.find("ul").append("<li rel='slide_" + (n + 1) + "'></li>");

            $(this).attr("id", "slide_" + (n + 1));


        });

        $this.find(".control ul li:first-child").addClass("current");


        $this.find(".control ul li").click(function () {
			
			clearInterval(autoRotateTimer);
			
            var rel = "#" + $(this).attr("rel");


            var head = $this.find(rel).attr("head");
            var text = $this.find(rel).attr("text");
			var url = $this.find(rel).attr("link");

            var contentCurrent = content + ".current";

            //console.log(contentCurrent);
            $this.find(contentCurrent).fadeOut(duration);

            $this.find(".control .head").fadeOut(duration, function () {

                $(this).text(head);

            }).fadeIn(duration);

            $this.find(".control p").fadeOut(duration, function () {

                $(this).text(text);

            }).fadeIn(duration);
			
			$this.find(rel).click(function() {
				(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
			});
			$this.find(".control .head").click(function() {
				(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
			});
			$this.find(".control p").click(function() {
				(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
			});

            $this.find(rel).addClass("current").fadeIn(duration);

            $(this).parent("ul").find("li.current").removeClass("current");

            $(this).addClass("current");

        });
		
		windowFocus = true;
			this.rotate = function() {
				
				//console.log(windowFocus);
				
				if (!windowFocus) return;
				
				var allNavs = $this.find(".control ul li");
				
				var current = $this.find(".control ul li.current");
				
				var next;
				
				for (i = 0; i < allNavs.length; i++) {
					
					if (current.attr("rel") == $(allNavs[i]).attr("rel") && i != allNavs.length-1) {
						next = $(allNavs[i+1]);
						break;
					} else {
						next = $(allNavs[0]);
					}
				}
				
				var rel = "#" + $(next).attr("rel");
	
				var head = $this.find(rel).attr("head");
				var text = $this.find(rel).attr("text");
				var url = $this.find(rel).attr("link");
				
	
				var contentCurrent = content + ".current";
	
				//console.log(contentCurrent);
				$this.find(contentCurrent).fadeOut(duration);
	
				$this.find(".control .head").fadeOut(duration, function () {
	
					$(this).text(head);
	
				}).fadeIn(duration);
	
				$this.find(".control p").fadeOut(duration, function () {
	
					$(this).text(text);
	
				}).fadeIn(duration);
				
				$this.find(rel).click(function() {
					(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
				});
				$this.find(".control .head").click(function() {
					(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
				});
				$this.find(".control p").click(function() {
					(url != "undefined") ? window.location = url : window.location = "javascript:void(0);";
				});
	
				$this.find(rel).addClass("current").fadeIn(duration);
	
				$(next).parent("ul").find("li.current").removeClass("current");
	
				$(next).addClass("current");
				
				
				//var obj = this;
			
				//setInterval(function() {obj.rotate();}, autoRotateDuration);
				//setTimeout(function(myObject) { myObject.rotate(); }, autoRotateDuration, this);
	
				
				}
		
		if (autoRotateDuration > 0) {	
			var obj = this;
			
			autoRotateTimer = setInterval(function() {obj.rotate();}, autoRotateDuration);
		
			//setTimeout(function(myObject) { myObject.rotate(); }, autoRotateDuration, this);
		}


    });
};

/* End slider plugin */



/* Tab plugin */

$.fn.ctabs = function (options) {

    var options = $.extend({
        enter: "hover",
        content: ".tab-content",
        tabs: ".tabs",
        duration: 200,
        easing: "easeOutSine"

    }, options);


    return this.each(function () {
        var $this = $(this);

        var content = options.content;
        var tabs = options.tabs;
        var enter = options.enter;

        var duration = options.duration;
        if ($.browser.msie) {
            duration = 0;
        }

        $this.children(content).children("div").hide();
        $this.children(content).children("ol").hide();

        $this.children(content).children("div:first-child").addClass("current").show();
        $this.children(content).children("ol:first-child").addClass("current").show();
        $this.children(tabs).find("li:first-child").addClass("current");

        if (enter == "hover") {

            $this.children(tabs).find("li").mouseenter(function () {

                var currentstat = $(this).attr("class");

                if (currentstat != "current") {

                    var rel = "#" + $(this).attr("rel");

                    $(this).parent().find(".current").removeClass("current");

                    $(this).addClass("current");

                    $this.children(content).find(".current").removeClass("current").fadeOut(duration, function () {

                        var tab = content + " " + rel;

                        $this.find(tab).addClass("current").fadeIn(duration);
                    });

                    resizeLeftNavigation();

                } else {}

            });

        } else {

            $this.children(tabs).find("li").click(function () {

                var currentstat = $(this).attr("class");

                if (currentstat != "current") {

                    var rel = "#" + $(this).attr("rel");

                    $(this).parent().find(".current").removeClass("current");

                    $(this).addClass("current");

                    $this.children(content).children(".current").removeClass("current").fadeOut(duration, function () {

                        var tab = content + " " + rel;

                        $this.find(tab).addClass("current").fadeIn(duration);
                    });

                    resizeLeftNavigation();

                } else {}

            });



        }


    });
};


function sPropagation() {

    $('.nav-tabs, .navigation, .tab').click(function (event) {
        event.stopPropagation();
    });

}

function sum(arr) {
    var result = 0,
        n = arr.length || 0; //may use >>> 0 to ensure length is Uint32
    while (n--) {
        result += +arr[n]; // unary operator to ensure ToNumber conversion
    }
    return result;
}



/* End of Tab plugin */

// Get parameters

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens, re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

// End get parameters
// search function

function search(phrase, page) {

    var url = "/search.aspx?id=7048";
    if (page != undefined) {
        url = url + "&page=" + page;
    }

    $.getJSON(encodeURI(url + "&q=" + phrase), function (data) {
        $('#pagesearch').text('');
        $('#pagesearchpaging').text('');
        $('#container').scrollTop();
        $('#pagesearch_results_tabs').html("<h2>Fann " + data.result.count + " s&iacute;&eth;ur</h2>");
        var results = data.result.items;


        $("#pagesearch").append("<ul id='pagesearch_results_list'>");

        for (i = 0; i < results.length - 1; i++) {
//            $("#pagesearch_results_list").append('<li onclick="window.location=\'default.aspx?id=' + results[i].pageID + '\';"><h2>' + results[i].number + ' ' + results[i].titleClear + ' (' + results[i].weight + ')</h2><p>' + results[i].summary + '</p></li>');
			$("#pagesearch_results_list").append('<li><h2><a href="default.aspx?id=' + results[i].pageID + '">' + results[i].titleClear + ' (' + results[i].weight + ')</a></h2><p>' + results[i].summary + '</p></li>');
           
		   
		   
		   /* if (i < results.length - 2) {
                $("#pagesearch").append("<hr />");
            }
			*/
        }

        $("#pagesearch").append("</ul>");

        if (page > 1 && data.result.countpages > 1) {
            $("#pagesearchpaging").append('<span onclick="search(\'' + phrase + '\',\'' + (page - 1) + '\');"> <-- aftur </span>');
        }
        for (i = 0; i < data.result.countpages; i++) {
            $("#pagesearchpaging").append('<span class="' + ((page == i + 1 || (page == undefined && i == 0)) ? "current" : "") + '" onclick="search(\'' + phrase + '\',\'' + (i + 1) + '\');"> ' + (i + 1) + ' </span>');
        }
        if ((page == undefined || page < data.result.countpages) && data.result.countpages > 1) {
            $("#pagesearchpaging").append('<span onclick="search(\'' + phrase + '\',\'' + (((page == undefined) ? 2 : parseInt(page) + 1)) + '\');"> fram --> </span>');
        }
    /*
		$("#searchwrapper").ctabs({
				enter: "click",
				
		 });
	*/
	});
	
}




// end search function
// search HR function

function HRsearch(phrase, page) {

    var url = "/Default.aspx?ID=7124";
    if (page != undefined) {
        url = url + "&page=" + page;
    }

    $.getJSON(encodeURI(url + "&SearchWord=" + phrase), function (data) {
        $('#pagesearch').text('');
        $('#pagesearchpaging').text('');
        $('#container').scrollTop();
        $('#pagesearchtabtitle').html("S&iacute;&eth;ur (" + data.result.count + ")");
        var results = data.result.items;

        $("#pagesearch").append("<ul>");

        for (i = 0; i < results.length - 1; i++) {
            $("#pagesearch").append('<li onclick="window.location=\'default.aspx?id=' + results[i].pageID + '\';"><h2>' + results[i].number + ' ' + results[i].titleClear + ' (' + results[i].weight + ')</h2><p>' + results[i].summary + '</p></li>');
            if (i < results.length - 2) {
                $("#pagesearch").append("<hr />");
            }
        }

        $("#pagesearch").append("</ul>");

        if (page > 1 && data.result.countpages > 1) {
            $("#pagesearchpaging").append('<span onclick="search(\'' + phrase + '\',\'' + (page - 1) + '\');"> <-- aftur </span>');
        }
        for (i = 0; i < data.result.countpages; i++) {
            $("#pagesearchpaging").append('<span class="' + ((page == i + 1 || (page == undefined && i == 0)) ? "current" : "") + '" onclick="search(\'' + phrase + '\',\'' + (i + 1) + '\');"> ' + (i + 1) + ' </span>');
        }
        if ((page == undefined || page < data.result.countpages) && data.result.countpages > 1) {
            $("#pagesearchpaging").append('<span onclick="search(\'' + phrase + '\',\'' + (((page == undefined) ? 2 : parseInt(page) + 1)) + '\');"> fram --> </span>');
        }
    });
}


// end HR search function

// adjust left navigation

function resizeLeftNavigation() {
    if ($("#left_navigation").length > 0 && $("#left_navigation").height() < $("#content").height()) $("#left_navigation").height($("#content").height());
}
// end adjust left navigation

//execute when the dom has finished loading
$(document).ready(function () {

    // Internet Explorer 6 check
    if ($.browser.msie && $.browser.version == "6.0") {
        //$("body").html("T? hevur ein sera gamlan og ?tryggan heimas??u kagara (web browser). Fyri at dagf?ra t?n kagara heinta n?ggjastu ?tg?vunar her:<br /><br />Internet Explorer<br />Firefox<br />Google Chrome");
    };

    // end Internet Explorer 6 check
	
	
	// News page pageing links start
	
	if($("#news_paging_links").length > 0){
		
		var currentPage = 1;
		if($.query.get('currentPage')) currentPage = $.query.get('currentPage');
		
		//alert(currentPage);
			
		var news_paging_links = $("#news_paging_links");
		var news_paging_links_children = news_paging_links.children();
		var hvussu_nogvar_sidur = news_paging_links_children.length;
		
		
			if(news_paging_links_children.length < 11){
				
			}else{
				var longd = news_paging_links_children.length;
				var nyggjar_leinkjur = new Array();
				for(i=0; i < news_paging_links_children.length; i++){
					$(news_paging_links_children[i]).attr("style", "display:none;");
				}
				
				// vís 5 tær fyrstur leinkjurnar
				var fimm_fyrstu = '';
				
				// avgerða hvar man skal byrja - um currentPage < 4, so byrja frá síðu 1, annars byrja frá currentPage-2
				
				var firstpage = 0;
				var lastpage = 7;
				var go_to_first_page = '';
				if(currentPage > 3){
					//ger leinkju til "First page"
					var kid = $(news_paging_links_children[0]);
					go_to_first_page = '<a style="text-decoration:none;" href="'+kid.attr('href')+'" class="news_paging_link" >1</a> ... ';
					fimm_fyrstu += go_to_first_page;
					// set nýggj start/stop punkt
					firstpage = currentPage-3;
					lastpage = currentPage+1;
					
					if((currentPage+1) == hvussu_nogvar_sidur){
						//alert('almost there');	
						firstpage = currentPage-4;
						lastpage = currentPage;
					}
					if(currentPage == hvussu_nogvar_sidur){
						//alert('yup -  there');
						firstpage = currentPage-4;
						lastpage = currentPage-1;
					}
					
				}
				
				
				
				
				for(i=firstpage; i < lastpage+1; i++){
						var kid = $(news_paging_links_children[i]);	
						var sidu_tal = i+1;
						var sidu_leinkja_class = ' class="news_paging_link" ';
						if(sidu_tal == currentPage) sidu_leinkja_class = ' class="news_paging_link current" '; 
						fimm_fyrstu += '<a style="text-decoration:none;" href="'+kid.attr('href')+'" '+ sidu_leinkja_class +' >'+sidu_tal+'</a>&nbsp;';
				}
				
				
				
				
				// vís tí seinastu leinkjurna
				var fimm_seinastu = '';
				var millumrum = '';
				var kid = $(news_paging_links_children[hvussu_nogvar_sidur-1]);	
				if(currentPage < (hvussu_nogvar_sidur-3)){
					millumrum = ' ... ';
					fimm_seinastu += '<a style="text-decoration:none;" href="'+kid.attr('href')+'" class="news_paging_link">'+hvussu_nogvar_sidur+'</a>&nbsp;';
				}
				
				
				// tjekka um ein "Aftur" knappur skal gerast
				var blada_eina_sidu_aftur = '';
				if(currentPage != 1){
					var kid = $(news_paging_links_children[currentPage-2]);
					blada_eina_sidu_aftur = '<a style="text-decoration:none;" href="'+kid.attr('href')+'" class="news_paging_link">Aftur</a>&nbsp;';
				}
				
				
				// tjekka um ein "fram" knappur skal gerast
				var blada_eina_sidu_fram = '';
				if(currentPage != hvussu_nogvar_sidur){
					var kid = $(news_paging_links_children[currentPage]);
					blada_eina_sidu_fram = '<a style="text-decoration:none;" href="'+kid.attr('href')+'" class="news_paging_link">Fram</a>&nbsp;';
				}

				var new_links_to_render = blada_eina_sidu_aftur + fimm_fyrstu + millumrum + fimm_seinastu + blada_eina_sidu_fram;
				
				$("#news_paging_links").html(new_links_to_render);
			}
			
	}
	
	// News page pageing links end
	
	
    // tabs
    var tabElements = $(".tab_element");

    if (tabElements.length > 0) {
        $("#content_wrapper").prepend('<div id="tabs_content" class="tab-content"></div>');
        $("#content_wrapper").prepend('<ul id="forth_level_menu" class="tabs buttons"></ul>');
        for (i = 0; i < tabElements.length; i++) {
            $("#forth_level_menu").append('<li rel="te' + i + '">' + $(tabElements[i]).find('.tab_title').html() + '</li>');
            $("#tabs_content").append('<div id="te' + i + '">' + $(tabElements[i]).find('.tab_content').html() + '</div>');
        }

        $("#content_wrapper").addClass("no_padding");
        $("#hogra_breddi").addClass("using_tabs");

        $("#content_wrapper").ctabs({
            enter: "click"
        });
        if ($(".hogri_kassi").length > 0) $("#tabs_content").addClass("with_right_column");
    }

    // end tabs
    // gera tabbar a forsiduni til tidindi
    $("#tidindi_forsida").ctabs({
        enter: "click"
    });

    // end tabbar a forsidu

    // topgraphic
    var topElements = $(".topgraphic_element");

    if (topElements.length == 1) {
        $("#topgraphic").html('<div id="topgraphic_single">' + $(topElements[0]).html() + '</div>');
    } else {
        $("#topgraphic").append('<div id="topgraphic_tabs" class="tab-content"></div>');
        $("#topgraphic").append('<ul id="navigation_tabs" class="tabs buttons"></ul>');
        for (i = 0; i < topElements.length; i++) {
            $("#navigation_tabs").append('<li rel="e' + i + '"></li>');
            $("#topgraphic_tabs").append('<div id="e' + i + '" class="topgraphic_elm">' + $(topElements[i]).html() + '</div>');
        }
        $("#topgraphic").ctabs();
    }
	
	if(topElements.length == 0){
		$("#topgraphic").attr("style", "display:none;");
	}

    // end topgraphic

    // topgraphic on frontpage
    var topElements = $(".topgraphic_element");
    var slideshow = $(".slideshow");
    var kbit = "";
    if (slideshow.length > 0) {

        if (topElements.length == 1) {

            $("#topgraphic").html('<div id="topgraphic_single">' + $(topElements[0]).html() + '</div>');
        } else {
            for (i = 0; i < topElements.length; i++) {
                var headline = $(topElements[i]).find('h2').html();
                var tekstur = $(topElements[i]).find('p').html();
                var mynd = $(topElements[i]).find('img').attr("src");
                var link_url = $(topElements[i]).find('a').attr("href");
				var temp = "";
				if (link_url != "undefined") {
                	temp = '<img alt="" src="' + mynd + '" head="' + headline + '" text="' + tekstur + '" link="' + link_url + '" onclick="window.location=\'' + link_url + '\';"/>';
				} else {
					temp = '<img alt="" src="' + mynd + '" head="' + headline + '" text="' + tekstur + '" link="' + link_url + '"/>';
				}

                $(".slideshow").append(temp);
            }

            var headline = $(topElements[0]).find('h2').html();
            var tekstur = $(topElements[0]).find('p').html();
            var leinkja_tekstur = $(topElements[0]).find('a').html();
            var leinkja_url = $(topElements[0]).find('a').attr("href");

            var temp = '<div class="control">';
            temp += '<h1 class="head" onclick="window.location=\'' + leinkja_url + '\'">' + headline + '</h1>';
            temp += '<p onclick="window.location=\'' + leinkja_url + '\'">' + tekstur + '</p>';
            //temp += '<a class="link" href="'+leinkja_url+'">'+leinkja_tekstur+'</a>';
            temp += '<ul></ul></div>';
            $(".slideshow").append(temp);
        }

    }
    // end topgraphic on frontpage


    // Hogri breddi
    var hogribreddar = $("div.hogri_kassi");
    var erutabbar = $("#tabs_content");

    if (erutabbar.length == 0) {

        if (hogribreddar.length > 0) {

            $("#content_wrapper").addClass("vid_hogra_bredda");

            $("#content").append('<div id="hogribreddi"></div>');

            for (i = 0; i < hogribreddar.length; i++) {

                $("#hogribreddi").append('<div class="hogri_kassi">' + $(hogribreddar[i]).html() + '</div>');
                $(hogribreddar[i]).remove();
            }
        }

    }
    // end hogri breddi


    // fixa haedd a vinstra menu kassa
    var innihald_hadd = $("#content").outerHeight(true);
    var vinstramenu_hadd = $("#left_navigation").outerHeight(true);

    //alert('innihald: ' + innihald_hadd);
    //alert('vinstramenu: ' + vinstramenu_hadd);
    if (innihald_hadd > vinstramenu_hadd) {
        $("#left_navigation").height(innihald_hadd);
    }


    //



    // Search autocomplete

    function log(message) {
        $("<div/>").text(message).prependTo("#log");
        $("#log").attr("scrollTop", 0);
    }

    var resultCount = 0;

    $("#search").autocomplete({
        minLength: 3,
        source: function (request, response) {

            $.ajax({
                url: "Default.aspx?ID=7124",
                data: encodeURI("SearchWord=" + request.term + ""),
                dataSource: "json",
                contentType: "application/json; charset=utf-8",
                type: "GET",
                dataFilter: function (HRdata) {
                    return HRdata;
                },
                success: function (HRdata) {

                    var HRObj = $.parseJSON(HRdata);

                    $.ajax({
                        url: "search.aspx?ID=7048",
                        data: encodeURI("q=" + request.term + ""),
                        dataSource: "json",
                        contentType: "application/json; charset=utf-8",
                        type: "GET",
                        dataFilter: function (PageData) {
                            return PageData;
                        },
                        success: function (PageData) {
                            var PageObj = $.parseJSON(PageData);

                            var objs = $.merge(HRObj.Items, PageObj.result.items);

                            response($.map(objs, function (item) {
                                if (resultCount++ < 100) {
                                    if (item.titleClear != undefined || item.Name != undefined) {
                                        return {
                                            value: (item.titleClear != undefined) ? item.titleClear : item.Name + " " + item.LastName,
                                            data: item,
                                            type: (item.titleClear != undefined) ? 'page' : 'hr'
                                        }
                                    }
                                }
                            }))
                        }
                    });
                }
            });
        },
        select: function (event, ui) {
            selectedItemData = ui.item.data;
            window.location = "http://" + document.domain + "/?ID=" + ui.item.data.pageID;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        if (item.label != undefined) {
            ul.attr("id", "autocomplete_dropdown");
            return $("<li></li>").data("item.autocomplete", item).append((item.type == 'page') ? "<a><h1>" + item.label + "</h1><br />" + item.data.summary + "</a>" : "<div class='search_autocomplete_staff'><h1>" + item.label + "</h1>" + ((item.data.JobTitle != "") ? item.data.JobTitle + "<br />" : "") + "Teldupostur: " + item.data.Email + "<br />Telefon: " + item.data.Phone + "</div>").appendTo(ul);
    //        return $("<li></li>").data("item.autocomplete", item).append((item.type == 'page') ? "<a><h1>" + item.label + "</h1><br />" + item.data.summary + "</a>" : "<div><h1>" + item.label + "</h1><br />" + ((item.data.JobTitle != "") ? item.data.JobTitle + "<br />" : "") + "Teldupostur: " + item.data.Email + "<br />Telefon: " + item.data.Phone + "</div>").appendTo(ul);
}
    };

    // end search autocomplete
    // Mega menu
    $("ul#nav > li").each(function () {

/*
                                                                $(this).bind({
                                                                                                mouseover: function() {
                                                                                                                        $(this).children("ul").attr("style","display:inline;");
                                                                                                                        $(this).addClass("active");
                                                                                                },
                                                                                                mouseout: function() {
                                                                                                                        $(this).children("ul").attr("style","display:none;");
                                                                                                                        $(this).removeClass("active");
                                                                                                }
                                                                                        });
*/
        var maxHeight = 400;
        var heightLeft = maxHeight;
        var output = "";
        $("body").append("<div id='calculateheight'></div>");
        $("#calculateheight").attr("style", "display:inline;"); // hack to get height of elements
        $("#calculateheight").attr("style", "visibility:hidden;");


        var container = $(this).children("ul");
        var elements = $(this).children("ul").each(function () {
            var childElements = $(this).children("li");
            output += '\n<li class="curtaincolumn">';
            childElements.each(function () {
                var currentElement = $("#calculateheight");
                $(currentElement).html("<ul><li>" + $(this).html() + "</li></ul>");

                if ($(currentElement).height() < heightLeft) {
                    output += "<ul><li>" + $(this).html() + "</li></ul>";
                } else {
                    heightLeft = maxHeight;
                    output += '</li>\n<li class="curtaincolumn">';
                    output += "<ul><li>" + $(this).html() + "</li></ul>";
                }
                heightLeft = heightLeft - $(currentElement).height();
                //$("body").append("Debug: " + $(currentElement).height() + "<br />");
                //$("body").append("Debug: " + $(currentElement).html() + "<br />");
            });
            output += '</li>\n';

        });
        container.html(output);

        //                                                              $(this).children("ul").attr("style","visibility:normal;"); // hack to get height of elements
        //                                                              $(this).children("ul").attr("style","display:none;");
    });
    $("#calculateheight").attr("style", "display:none;"); // hack to get height of elements

    // end Mega menu
    // Feedback function
	/*
    $("body").prepend('<div id="feedback_dialog" style="display: none;" title="Feedback"><iframe style="clear:both;" src="/?id=7053&url=' + document.location + '" width="350px" height="300px" frameborder="0"></iframe><div style="clear:both;"></div></div>');
    $(".first-nav").prepend('<div id="feedback"><a href="javascript:void(0);" onclick="$(\'#feedback_dialog\').dialog({modal: true, closeText: \'Lat aftur\', minWidth: 400, minHeight: 350});window.scrollTo(0,0);">Feedback</a></div>');
*/
    // end feedback function

    //$("*:last-child").addClass("last-child");
    //$("*:first-child").addClass("first-child");
    $("#nav *:first-child").addClass("first-child");
    $("#nav *:last-child").addClass("last-child");
    $("#nav .current").next().addClass("first-child");
    $("#sec_level_menu *:first-child").addClass("first-child");
    $("#left_navigation *:first-child").addClass("first-child");
    $("#tabs_content *:first-child").addClass("first-child");

    $('input[type="text"]').addClass('text_input');
    $('input[type="Textbox"]').addClass('text_input');
    $('input[type="radio"]').addClass('radio');
    $('input[type="submit"]').addClass('submit');
    $('input[type="reset"]').addClass('submit');	
    $('input[type="button"]').addClass('submit');
	$('input[type="Button"]').addClass('submit');

    $("input[type~='text'], input[type~='number']").setDefaultValue();

    $(".container.two .box").find("img").parents(".box").addClass("img");

    $(".slideshow").slider({autoRotateDuration: 7500});

    $(".container.one .service").ctabs();



    $(".content-tabs").ctabs({
        enter: "click"
    });
    $(".tabs").ctabs({
        enter: "click"
    });

    $(".content-tabs .tab-content > div").ctabs();

    $(".content-tabs-child").ctabs({
        enter: "click",
        content: ".tab-content-child",
        tabs: ".tabs-child"
    })

    //Function to add span insted of regular radio buttons, for better styling
    $("radio, input[type=radio]").each(function () {

        var check = $(this).is(':checked');

        var id = (Math.floor(Math.random() * 1000000 + 1));


        if (check == true) {

            $(this).before("<span class='radiobutton checked' rel='" + id + "'></span>");
            $(this).parents("tr").addClass("checked");
        } else {

            $(this).before("<span class='radiobutton' rel='" + id + "'></span>");
            $(this).parents("tr").removeClass("checked");
        }

        $(this).attr("id", id).addClass(id).hide();

    });

    $("span.radiobutton").click(function () {

        var id = $(this).attr("rel");

        input = "input[id='" + id + "']";


        $(this).parents(".radio").find(".checked").removeClass("checked");
        $(this).addClass("checked");
        document.getElementById(id).checked = true;

    });



    //clear floats for container div
    $(".sidemap, .container.two, .articles, .articles .article-wrap, .content-tabs-child, .content-tabs, form.search, form").append("<div class='clear' />");
    $(".first-nav").after("<div class='clear' />");


    //activate select manu styling plugin
    //$("form select").selectmenu({width: 240});
    $(".boxes select").selectmenu({
        width: 170
    });


    //add class "current" to the current position in main navigation
    $(".frontpage .navigation .frontpage, .privat .navigation .privat, .kundi .navigation .kundi").addClass("current");


    //styling fixes
    $(".content-tabs-child").each(function () {

        var height = $(this).height() - 60;

        //console.log(height);
        $(this).find(".tabs-child").height(height);

    });


    //faq
    $("body.faq .content ul li h3").click(function () {

        $(this).siblings("p").slideToggle(200);
        $(this).siblings(".how").slideToggle(200);

        var classid = $(this).siblings(".icon").attr("class").split(" ");

        //console.log(classid)
        if (jQuery.inArray("current", classid) > -1) {

            $(this).siblings(".icon").removeClass("current");

            // console.log("remove");
        } else {
            $(this).siblings(".icon").addClass("current"); //console.log("add");
        }


    });



    //function for the navigation tabs
/*
       
        $(".navigation li").click(function() {
       
            $(".nav-tab").appendTo(".nav-tabs").removeClass("nav-tab").removeAttr("style");
           
            $(".navigation").find(".current").removeClass("current");
                   
            //$(".nav-tab").appendTo("body");
           
            $(".navigation .current").removeClass("current");
           
            $(this).addClass("current");
       
            var width = $(this).outerWidth(true);
            var height = $(this).outerHeight(true);
           
            var offset = $(this).offset();
            var position = $(this).position();
           
            var classit = $(this).attr("class").split(" ");
           
            //console.log(classit);
           
            var tabclass = ".nav-tabs ." + classit[0];
           
           // console.log(tabclass);
           
           if($.browser.msie ) {
           
           
               $(tabclass).addClass("nav-tab").css({"top": (position.top + height + 79), "display": "block", "left": position.left}).appendTo(".header");
           }
           
           else {
           
            $(tabclass).addClass("nav-tab").css({"top": (position.top + height + 79), "display": "block", "left": position.left}).appendTo(".header");
           
            }
           
           
        });
       
        $("body").click(function(){
       
            $(".nav-tab").appendTo(".nav-tabs").removeClass("nav-tab").removeAttr("style");
           
            $(".navigation").find(".current").removeClass("current");
           
           //sPropagation()
       
        });
       
        sPropagation();
        */

    resizeLeftNavigation();


});
//End of document.ready

//execute when all content has been loaded
$(window).load(function () {

    $(".navigation > li.dir > ul").each(function () {

        var widthArray = new Array();

        $(this).children("li").each(function (n) {

            var thiswidth = $(this).outerWidth(true);
            var thisheight = $(this).outerHeight(true);

            widthArray[n + 0] = thiswidth;
            //$(this).append('<div style="font-size:9px; color:#fff;">' + thiswidth + ' x ' + thisheight +  '</div>');
        });
        var t = sum(widthArray) + 90;
        if (t > 750) {
            t = 750;
        }

        $(this).width(t);

        //$(this).append('<div style="font-size:9px; color:#fff;">' + t +  '</div>');
    });

    $("ul.dropdown ul.curtain").hover(function () {
        $(this).css('visibility', 'visible').siblings('a').addClass('hover');
    }, function () {
        $(this).css('visibility', 'hidden').siblings('a').removeClass('hover');
    });

    $('ul.dropdown > li.dir').mouseover(function () {
        var li = $(this);
        var offset = li.position().left;

        var parent = li.parent('ul.dropdown');
        var parentWidth = parent.outerWidth(true);

        var curtain = li.children('ul.curtain');
        var width = curtain.outerWidth(true);
        var positionLeft = curtain.position().right;

        if (parentWidth - (offset + width) < 0) {
            curtain.css('left', 'auto');
            curtain.css('right', '0');
        } else {
            curtain.css('left', '0');
            curtain.css('right', 'auto');
        }
    });
});
//end of window.load
//execute every time the browser window is resized
$(window).resize(function () {


});
//end of window.resize

//execute when the user scrolls the page
$(window).scroll(function () {


});
//End of window.scroll


// Logga a nettaenastur - dropdown
/*

var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();

    ddmenuitem = $(".logga_a_nettanastu_dd").css('display', 'block');
}

function jsddm_close() {
    if (ddmenuitem) ddmenuitem.css('display', 'none');
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(function () {
    $('#logga_a_nettanastu_knappur').bind('mouseover', jsddm_open)
    $('.logga_a_nettanastu_dd').bind('mouseover', jsddm_open)
    $('#logga_a_nettanastu_knappur').bind('mouseout', jsddm_timer)
    $('.logga_a_nettanastu_dd').bind('mouseout', jsddm_timer)


    $(".logga_a_nettanastu_dd").position({
        of: $("#logga_a_nettanastu_knappur"),
        my: "left top",
        at: "left bottom",
        offset: '0 -30',
        collision: 'none'
    });

});

document.onclick = jsddm_close;

*/
// Logga a nettaenastur - dropdown END



