/* 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
$(document).ready(function() {


    //shorten breadcrumb if to long
    shortenBreadcrumb({ breadcrumb: $('div#breadcrumb > ul'), maxWidth: 560 });
    formatBookmarks();

    // function to swap values in a watermarkbox
    swapValues = []; $(".watermarkbox").each(function(i) { swapValues[i] = $(this).val(); $(this).focus(function() { if ($(this).val() == swapValues[i]) { $(this).val("") } }).blur(function() { if ($.trim($(this).val()) == "") { $(this).val(swapValues[i]) } }) })

    // Click on logo
    $(".logo").click(function() { location.href = '/' });

    // Comments functions
    $(".comment-link").click(function() {
        $(".comment2").css("background", "#ffffff");
        $(".comment-container").slideToggle("slow",
            function() {
                if ($(".comment2").css("background") == "#f6f3ef") {
                    $(".comment2").css("background", "#ffffff");
                } else {
                    $(".comment2").css("background", "#f6f3ef");
                }
            }
        );
        $(".navImages").toggle();
    });
    $(".shortcut-container").click(function() {
        if ($(this).hasClass("active")) {
            $(this).removeClass("active");
            $(".drop").hide();
        }
        else {
            $(".shortcut-container").removeClass("active");
            $(this).addClass("active");
            $(".drop").hide();
            $(".drop", this).show();
        }
    });

    $("#translate-close").click(function(e) {
        $(".translate-box").slideToggle("slow", function() {
            $(".translate-box").toggleClass("translate-active");
        });
    });
    $("#translate").click(function() {
        $(".translate-box").show();
        $(".translate-box").toggleClass("translate-active")

    });
    // Search functions 
    $("#google_q").keyup(function() {
        $("#search-query").val($("#google_q").val());
    });
    $("#search-query").keyup(function() {
        $("#google_q").val($("#search-query").val());
    });

    // Image Carousel functions
    $(".carousel .link-prev").click(function() { forwardpaging = false; });
    $(".carousel .link-next").click(function() { forwardpaging = true; });
    $(".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 ? $(".paginator li.active").next() : $(".paginator li.active").prev();
                if (nextPaginatorItem.length < 1) {
                    nextPaginatorItem = forwardpaging ? $(".paginator li").first() : $(".paginator li").last();
                }
                nextPaginatorItem.find("a").click();
            }
            pagerstatus = false;
        },
        btnGo: $(".paginator a")
    });
    $(".paginator a").click(function() {
        $(".paginator li").removeClass("active");
        $(this).parent().addClass("active");
        pagerstatus = true;
    });
    $(".goog-logo-link").attr("alt", "Google Translate");
});

// Star rating system
(function($) {
    var buildRating = function(obj) {
        var rating = averageRating(obj),
                obj = buildInterface(obj),
                stars = $("div.star", obj),
                cancel = $("div.cancel", obj)

        var fill = function() {
            drain();
            $("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();
                    $(this).addClass("on");
                },
                cancelOff = function() {
                    reset();
                    $(this).removeClass("on")
                }
        stars
                    .hover(fill, reset).focus(fill).blur(reset)
                    .click(function() {
                        rating = [stars.index(this) + 1, 0];
                        $.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");
                                $(obj.summaryElement).html(msg[0]);
                                rating = msg[1].split(",");
                                reset(); stars.unbind().addClass("done");
                            },
                            error: function(msg) { alert(msg.status + '\n' + msg.statusText); }
                        });
                        $(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 = $("<div></div>").attr({ "title": "Gennemsnit: " + divContainer.title, "class": divContainer.className });
        $.extend(container, { pageid: $(".divGuid", divContainer).text() });
        $.extend(container, { summaryElement: $("#divSummary") });
        var optGroup = $("option", $(divContainer));
        var size = optGroup.length;
        optGroup.each(function() {
            container.append($('<div class="star"><a href="#' + this.value + '" title="Giv ' + this.value + '/' + size + '">' + this.value + '</a></div>'));
        });
        $(divContainer).after(container).remove();
        return container;
    }

    var averageRating = function(el) { return el.title.split(",") }
    $.fn.rating = function() { return $($.map(this, function(i) { return buildRating(i)[0] })); }
    if ($.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 : $('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 = $('div#breadcrumb > ul');
    var maxWidth = $('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 += $(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 = $('#content');
    $('a', contentArea).each(function() {
        if (this.href == '' || ($(this).attr('href') == '' || $(this).attr('href') == '#') && this.name != '') {
            $(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
    }
}