/* Text changer - light version.
Let your text's font size customizable.
by Marco Rosella - http://www.centralscrutinizer.it/en/design/js-php/text-changer
v0.2 - May 18, 2006
*/
function initFontResize() {
	textChanger.init();
}
var textChanger = {
	defaultFS : 1,
	init: function() {
		var el = document.getElementsByTagName("body")[0];
		var sz = textChanger.getCookie();
		el.style.fontSize = sz ? sz + 'em' : textChanger.defaultFS + 'em';
		var incr = document.getElementById('increase');
		if(incr)
			incr.onclick = function(){textChanger.changeSize(1); return false;};
		var decr = document.getElementById('decrease');
		if(decr)
			decr.onclick = function(){textChanger.changeSize(-1); return false;};
		var reset = document.getElementById('reset');
		if(reset)
			reset.onclick = function(){textChanger.changeSize(0); return false;};
	},
	changeSize: function(val) {
		var el = document.getElementsByTagName("body")[0];
		var size = el.style.fontSize.substring(0, 4);
		var fSize = parseFloat(size, 10);
		if (val == 1)	{
			fSize += 0.1;
			if (fSize > textChanger.defaultFS*1.5) fSize = textChanger.defaultFS*1.5;
		}
		if (val == -1) {
			fSize -= 0.1;
			if (fSize < textChanger.defaultFS/1.5) fSize = textChanger.defaultFS/1.5;
		}
		if (val == 0) fSize = textChanger.defaultFS;
		el.style.fontSize = fSize.toFixed(2) + 'em';
		textChanger.updateCookie(fSize);
	},
	updateCookie: function(vl)	{
		var today = new Date();
		var exp = new Date(today.getTime() + (365*24*60*60*1000));
		document.cookie = 'textChangerL=size=' + vl + ';' +'expires=' + exp.toGMTString() + ';' +'path=/';
	},
	getCookie: function()	{
		var cname = 'textChangerL=size=';
		var start = document.cookie.indexOf(cname);
		var len = start + cname.length;
		if ((!start) && (cname != document.cookie.substring(0,cname.length))) {return null;}
		if (start == -1) return null;
		var end = document.cookie.indexOf(";",len);
		if (end == -1) end = document.cookie.length;
		return unescape(document.cookie.substring(len, end));
	}
}
if (window.addEventListener)
	window.addEventListener("load", initFontResize, false);
else if (window.attachEvent && !window.opera)
	window.attachEvent("onload", initFontResize);

var pagerstatus = false;
var forwardpaging = true;

// watermark swap function
jQuery(document).ready(function () {


    //shorten breadcrumb if to long
    shortenBreadcrumb({ breadcrumb: jQuery('div#breadcrumb > ul'), maxWidth: 560 });
    formatBookmarks();
   jQuery('.listitem').tooltip({
            track: true,
            delay: 0,
            showURL: false,
            fade: 0,
            top: 30,
            left: 30,
            fixPNG: true,
            bodyHandler: function() {

                var pop = jQuery(this).children('.popup').clone();
                return pop;
            }
        });
    
    // function to swap values in a watermarkbox
    swapValues = []; jQuery(".watermarkbox").each(function (i) { swapValues[i] = jQuery(this).val(); jQuery(this).focus(function () { if (jQuery(this).val() == swapValues[i]) { jQuery(this).val("") } }).blur(function () { if (jQuery.trim(jQuery(this).val()) == "") { jQuery(this).val(swapValues[i]) } }) })

    // Click on logo
    jQuery(".logo").click(function () { location.href = '/' });

    // Comments functions
    jQuery(".comment-link").click(function () {
        jQuery(".comment2").css("background", "#ffffff");
        jQuery(".comment-container").slideToggle("slow",
            function () {
                if (jQuery(".comment2").css("background") == "#f6f3ef") {
                    jQuery(".comment2").css("background", "#ffffff");
                } else {
                    jQuery(".comment2").css("background", "#f6f3ef");
                }
            }
        );
        jQuery(".navImages").toggle();
    });
    jQuery(".shortcut-container").click(function () {
        if (jQuery(this).hasClass("active")) {
            jQuery(this).removeClass("active");
            jQuery(".drop").hide();
        }
        else {
            jQuery(".shortcut-container").removeClass("active");
            jQuery(this).addClass("active");
            jQuery(".drop").hide();
            jQuery(".drop", this).show();
        }
    });

    jQuery("#translate-close").click(function (e) {
        jQuery(".translate-box").slideToggle("slow", function () {
            jQuery(".translate-box").toggleClass("translate-active");
        });
    });
    jQuery("#translate").click(function () {
        jQuery(".translate-box").show();
        jQuery(".translate-box").toggleClass("translate-active")

    });
    // Search functions 
    jQuery("#google_q").keyup(function () {
        jQuery("#search-query").val(jQuery("#google_q").val());
    });
    jQuery("#search-query").keyup(function () {
        jQuery("#google_q").val(jQuery("#search-query").val());
    });

    // Image Carousel functions
    jQuery(".carousel .link-prev").click(function () { forwardpaging = false; });
    jQuery(".carousel .link-next").click(function () { forwardpaging = true; });
    jQuery(".carousel").jCarouselLite({
        btnPrev: ".link-prev",
        btnNext: ".link-next",
        speed: 800,
        beforeStart: function (middleLi) {
            middleLi.find("div").attr("class", "");
        },
        afterEnd: function (middleLi) {
            middleLi.find("div").attr("class", "left");
            middleLi.next().find("div").attr("class", "");
            middleLi.next().next().find("div").attr("class", "right");

            if (!pagerstatus) {
                var nextPaginatorItem = forwardpaging ? jQuery(".paginator li.active").next() : jQuery(".paginator li.active").prev();
                if (nextPaginatorItem.length < 1) {
                    nextPaginatorItem = forwardpaging ? jQuery(".paginator li").first() : jQuery(".paginator li").last();
                }
                nextPaginatorItem.find("a").click();
            }
            pagerstatus = false;
        },
        btnGo: jQuery(".paginator a")
    });
    jQuery(".paginator a").click(function () {
        jQuery(".paginator li").removeClass("active");
        jQuery(this).parent().addClass("active");
        pagerstatus = true;
    });
    jQuery(".goog-logo-link").attr("alt", "Google Translate");
});

// Star rating system
(function(jQuery) {
    var buildRating = function(obj) {
        var rating = averageRating(obj),
                obj = buildInterface(obj),
                stars = jQuery("div.star", obj),
                cancel = jQuery("div.cancel", obj)

        var fill = function() {
            drain();
            jQuery("a", stars).css("width", "100%");
            stars.slice(0, stars.index(this) + 1).addClass("hover");
        },
                drain = function() {
                    stars.removeClass("on").removeClass("hover");
                },
                reset = function() {
                    drain();
                    stars.slice(0, rating[0]).addClass("on");
                    if (percent = rating[1] ? rating[1] * 10 : null) {
                        stars.eq(rating[0]).addClass("on").children("a").css("width", percent + "%");
                    }
                },
                cancelOn = function() {
                    drain();
                    jQuery(this).addClass("on");
                },
                cancelOff = function() {
                    reset();
                    jQuery(this).removeClass("on")
                }
        stars
                    .hover(fill, reset).focus(fill).blur(reset)
                    .click(function() {
                        rating = [stars.index(this) + 1, 0];
                        jQuery.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "http://" + window.location.hostname + "/OxygenSoftware/Comments/CommentService.asmx/RatePage",
                            data: "{'inRating': '" + rating + "','pageID': '" + obj.pageid + "'}",
                            dataType: "json",
                            success: function(msg) {
                                //jAlert("Din stemme er nu registreret", "Information");
                                jQuery(obj.summaryElement).html(msg[0]);
                                rating = msg[1].split(",");
                                reset(); stars.unbind().addClass("done");
                            },
                            error: function(msg) { alert(msg.status + '\n' + msg.statusText); }
                        });
                        jQuery(this).css("cursor", "default");
                        setPageIdCookie(obj.pageid);
                        return false;

                    });
        reset();
        if (hasVoted(obj.pageid)) { stars.unbind().addClass("done"); }
        return obj;
    }

    var buildInterface = function(divContainer) {
        var container = jQuery("<div></div>").attr({ "title": "Gennemsnit: " + divContainer.title, "class": divContainer.className });
        jQuery.extend(container, { pageid: jQuery(".divGuid", divContainer).text() });
        jQuery.extend(container, { summaryElement: jQuery("#divSummary") });
        var optGroup = jQuery("option", jQuery(divContainer));
        var size = optGroup.length;
        optGroup.each(function() {
            container.append(jQuery('<div class="star"><a href="#' + this.value + '" title="Giv ' + this.value + '/' + size + '">' + this.value + '</a></div>'));
        });
        jQuery(divContainer).after(container).remove();
        return container;
    }

    var averageRating = function(el) { return el.title.split(",") }
    jQuery.fn.rating = function() { return jQuery(jQuery.map(this, function(i) { return buildRating(i)[0] })); }
    if (jQuery.browser.msie) try { document.execCommand("BackgroundImageCache", false, true) } catch (e) { }
})(jQuery)

/* Cookie handler for rating system */
function hasVoted(pageId) {
    var cookieValue = readPageIdCookie();
    if (cookieValue) {
        if (cookieValue.indexOf(pageId) > -1)
            return true;
        return false;
    }
    return false;
}
function setPageIdCookie(pageId) {
    if (!hasVoted(pageId)) {
        document.cookie = "ok-rating=" + readPageIdCookie() + pageId + "; path=/";
    }
}
function readPageIdCookie() {
    var nameEQ = "ok-rating=";
    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;
}

// ************************************************* //
// ***** functions for manipulation breadcrumb ***** //
// ************************************************* //

function shortenBreadcrumb(options) {
    /*
    Shortens the breadcrumb to a specified width by removing the text from one list item
    at a time and replacing it with "..." - accepts an options object as an optional
    parameter with two options:
    shortenBreadcrumb({
    breadcrumb : jQuery('div#breadcrumb > ul'),
    maxWidth : 725
    });

        The first is the selector for the breadcrumb ul, the second is the maximum width you
    want it to be.
    */

    var breadcrumb = jQuery('div#breadcrumb > ul');
    var maxWidth = jQuery('div#breadcrumb').innerWidth();

    if (options != undefined) {
        if (options.breadcrumb != null) { breadcrumb = options.breadcrumb; }
        if (options.maxWidth != null) { maxWidth = options.maxWidth; }
    }

    var levelCount = breadcrumb.find('li').size();
    var shortEnough = false;
    var totalWidth;
    var numberOfCrumbs;
    var breadcrumbPosition = 1; // skip 'Forside'
    while (shortEnough == false) {
        breadcrumbPosition++;
        totalWidth = 0;
        breadcrumb.children('li').each(function() {
            totalWidth += jQuery(this).outerWidth(true);
        });
        if (totalWidth > maxWidth) {
            var li = breadcrumb.children('li').not('.short').eq(1);
            li.addClass('short');
            li.children('a').attr('title', li.children('a').html());
            if (breadcrumbPosition ==  levelCount)
            {
                li.children('a').html('Denne side');
            }
            else
            {
                li.children('a').html('..');
            }
        }
        else {
            shortEnough = true;
        }
    }
}

// ************************************************* //

function formatBookmarks() {
    var contentArea = jQuery('#content');
    jQuery('a', contentArea).each(function() {
        if (this.href == '' || (jQuery(this).attr('href') == '' || jQuery(this).attr('href') == '#') && this.name != '') {
            jQuery(this).after(this.innerHTML);
            this.innerHTML="";
        }
    })
}

// ************************************************* //


function checkEnter(e, caller) //e is event object passed from function invocation
{
    var characterCode //literal character code will be stored in this variable
    if (e && e.which || e.which == 0) { //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    }
    else {
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }
    if (characterCode == 13)//if generated character code is equal to ascii 13 (if enter key)
    {
        if (document.all) {
            e.returnValue = false;
            e.cancel = true;
        }
        else {
            e.preventDefault();
        }
        var obj = document.getElementById(caller);
        if (obj) {
            if (obj.click) {
                obj.click();
            }
        }
        return false
    }
    else {
        return true
    }
}

function Google404Script() {
    jQuery(".headline h1").text("Siden findes ikke");
    jQuery("#google_search_subtext").html("Det link du har klikket p&aring; gav ingen resultater.<br/>Brug s&oslash;gefeltet ovenfor til at finde den information du har brug for eller anvend listen nedenfor.");
    jQuery("#google_search_subtext").show();
    jQuery("#google_search_subtext").css("padding", "15px 0 0 0");
    jQuery("#google_search_spelling_text").html("S&oslash;gte du:");
}
