/*
	jQuery.styleCheckRadio
	Author Atli Adalsteinsson
*/
(function(b){b.fn.styleCheckRadio=function(){return b(this).not(".styled").each(function(){var i=0,f=b(this),d=b("<span />"),c=null,h=function(a){a=a+(this.checked?3:0)-1;return{"background-position":"0 "+-(a===0&&b(this).data("over")?i*6:i*a)+"px"}},g=function(){var a=b(this),e=a.next();a.css(h.call(e[0],a.data("over")?2:1))},l=function(){b(this).parent().is(".over")||(b(this).data("over",!1),g.call(this))},m=function(){var a=b(this),e=a.next();a.data("over",!0);a.css(h.call(e[0],2))},n=function(){var a=
b(this),e=a.next();a.css(h.call(e[0],3))},j=function(){var a=b(this),e=a.prev(),c=a.attr("type")==="radio"?b(":radio[name='"+a.attr("name")+"']:last").parent():b(this).parent();g.call(e[0]);b(".confirmedMark, .errorMark",c).remove();a.data("label").removeClass("labelError")},k=function(a){a.stopImmediatePropagation();a.stopPropagation();a=b(this).next();a[0].checked=!a[0].checked;a.attr("type")==="radio"&&b(":radio[name='"+a.attr("name")+"']").trigger("update");a.change();return!1};f.before(d).data({error:!1}).change(function(){g.call(b(this).prev()[0])}).bind("error",
function(){var a=b(this),c=a.prev(),d=a.attr("type")==="radio"?b(":radio[name='"+a.attr("name")+"']:last").parent():b(this).parent();a.data("error",!0);d.children(".errorMark").length===0&&(j.call(this),d.append("<span class='errorMark' />"));a.data("label").addClass("labelError");g.call(c[0])}).bind("confirm",function(){var a=b(this),c=a.prev(),d=a.attr("type")==="radio"?b(":radio[name='"+a.attr("name")+"']:last").parent():b(this).parent();d.children(".confirmedMark").length===0&&(j.call(this),d.append("<span class='confirmedMark' />"));
a.data("label").removeClass("labelError");g.call(c[0])}).bind("clear",j).bind("check",function(a){k.call(b(this).prev()[0],a)}).bind("update",function(a){b(this).data("error",!0);g.call(b(this).prev()[0],a)}).bind("reset",function(){this.checked=!1;b(this).triggerHandler("clear");b(this).triggerHandler("update")}).css("display","none").addClass("styled");d.addClass(f.attr("type")).data({over:!1}).click(k).mouseenter(m).mouseleave(l).mousedown(n);i=d.height();d.css(h.call(f[0],1));d.parents("label").length>
0?c=d.parents("label"):f.attr("id").length>0&&(c=b("label[for='"+f.attr("id")+"']:first"),c=c.length?c:null);if(c!==null)f.data("label",c),c[0].span=d[0],c.mouseenter(function(a){b(this).addClass("over");m.call(this.span,a)}).mouseleave(function(a){b(this).removeClass("over");l.call(this.span,a)}).mousedown(function(a){n.call(this.span,a)}).mouseup(function(a){a.preventDefault()}).click(function(a){a.preventDefault();k.call(this.span,a)})})}})(jQuery);




$j = $.noConflict();

$j(document).ready(function () {

    // * * * * * * * * * * * * * * * * * * * * * * * * * 
    $j(".filterBox input:checkbox").styleCheckRadio();

    //this fixes print viewport area so scaling is made right
    $j('#content_container .content').prepend('<img src="/images/trans.gif" alt="" width="960" height="1" class="printFix" />');

    if (isEditMode) {
        $j('.splash_link_overlay').hide();
    }

    $j("#print_icon").click(function () {
        window.print();
        return false;
    });



    $j(".fancy_video").click(function () {
        $j.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'width': 680,
            'height': 495,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }

        });
        return false;
    });

    if (!isEditMode) {
        $j("a").each(function () {
            if ($j(this).attr("href") && $j(this).attr("href").indexOf("/lightboxes/") > 0) {
                $j(this).click(function () {
                    $j.fancybox({
                        'width': 375,
                        'height': 500,
                        'scrolling': 'auto',
                        'padding': 15,
                        'autoScale': false,
                        'transitionIn': 'none',
                        'transitionOut': 'none',
                        'href': this.href,
                        //'onComplete': resizeFancyBox,
                        'type': 'iframe'
                    });

                    $j.fancybox.resize();
                    return false;
                });

            }
        });
    }

    $j("#toppanel div.top-search input").keypress(function (event) {
        var $Input = $j(this);
        if (event.which === 13) {
            $Input.blur();
            var searchString = $Input.val();
            if (searchString !== "" && searchString !== $Input[0].defaultValue) {
                window.location.href = $Input.next().attr("href") + "?search=" + encodeURIComponent(searchString);
            }
            return false
        }
    }).focus(function () {
        var $Input = $j(this)
        if ($Input.val() === $Input.attr("title")) {
            $Input.val("");
        }
    }).blur(function () {
        var $Input = $j(this);
        if ($Input.val() === "") {
            $Input.val($Input.attr("title"));
        }
    }).map(function () {
        var $Input = $j(this);
        if ($Input.val() === "") {
            $Input.val($Input.attr("title"));
        }
    });


    //main nav login hover      
    hiConfig = {
        sensitivity: 3,
        interval: 100,
        timeout: 200,
        over: function () {
            if ($j(this).children('ul').length > 0) {
                $j(this).children('ul').removeClass('hidden');
            }
        },
        out: function () {
            if ($j(this).children('ul').length > 0) {
                $j(this).children('ul').addClass('hidden');
            }
        }
    }
    $j('#main_nav li').hoverIntent(hiConfig);


    //subnav
    hiConfig = {
        sensitivity: 3,
        interval: 100,
        timeout: 200,
        over: function () {

            var li = $j(this),
                div = li.children('div');

            if (div.length > 0) {

                $j('#sub_nav').find('ul > li > div').addClass('hidden');
                div.removeClass('hidden');
                $j('#sub_nav').find('.content > ul > li').removeClass('active');
                li.addClass('active');


                if (li.index() === 0) { //fÃ¸rste menupunkt
                    if (div.width() > li.parent().width()) {
                        div.css('left', -(div.width() - li.parent().width()) + 2 + "px");
                    }
                }

                if (li.index() === 1) { //midterste menupunkt

                    var right = li.next('.last').width();
                    center = li.width() / 2 - div.width() / 2 - 2;

                    div.css('left', (-center > right) ? -div.width() + li.width() + right + 2 : center);
                }
            }
        },
        out: function () {
            $j(this).removeClass('active');
            $j(this).children('div').addClass('hidden');
        }
    }

    $j('#sub_nav').find('.content > ul > li').hoverIntent(hiConfig);

    //initiate dynamic text size
    dynamicText();

    //make dropdowns clickable
    $j('.dropdown li a.main').live('click', function () {

        $j(this).parent().children('ul').fadeToggle('fast');

        if ($j(this).parent().children('input').length > 0) {
            current_input = $j(this).parent().children('input');
            $j(this).parent().children('ul').children('li').children('a').click(function () {
                $j(this).parent().parent().parent().children('input').val($j(this).attr('href'));
                $j(this).parent().parent().parent().children('a').text($j(this).text());
                $j(this).parent().parent().parent().children('ul').hide();

                return false;
            });
        }
        return false;

    });

    (function ($) {

        //add class to last of four boxes
        var boxes = $('#horisontal_boxes > .box'),
            maxHeight = 0;
        boxes.each(function () {
            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
        boxes.height(maxHeight + "px");


        if (boxes.size() == 4) {
            boxes.last().attr('class', boxes.last().attr('class') + ' last');
        }

    } ($j));


    //add classes to rish_text_module lister hvis de har anchors
    $j(".rich_text_module ul li").each(function () {
        if ($j(this).children("a").length > 0) {
            $j(this).addClass('has_anchors');
            $j(this).parent().css('margin-left', 0);
        }
    });

    //add footer to custom selects
    if ($j('.sbOptions').length > 0) {
        $j('.sbOptions').each(function () {
            $j(this).append('<li class="ftr"></li>');
        });
    }



    if ($j('#splash_subtitle').length > 0) {

        var subtitle_text = "";

        if (!isEditMode) {
            //fetch the top splash subheader and manipulate it
            subtitle_text = $j('#splash_subtitle').html();
            subtitle_text = subtitle_text.replace("<BR>", "<br>");
            subtitle_text = subtitle_text.replace("<br>", "<br />")
            subtitle_text = subtitle_text.split("<br />");


            $j('#splash_subtitle').html('');

            $j.each(subtitle_text, function (key, value) {
                $j('#splash_subtitle').append('<p> ' + value + ' </p>');
            });
        }
    }

    //Frontpage slider
    if ($j('#media_slider').length > 0) {
        var num_slides = 3,
            current_slide = 1,
            current_news_slide = 1;

        $j('#media_slider_left').click(function () {
            current_slide--;

            if (current_slide >= 1) {
                $j('#media_slider_wrapper').animate({
                    left: '+=960px'
                }, 700, function () {
                    // Animation complete.
                });
            }
            if (current_slide == 1) {
                $j(this).fadeTo('medium', 0.2);
            }
            if (current_slide < 1) {
                current_slide = 1;
            }

            $j('#media_slider_right').fadeTo('medium', 1);
            return false;
        });

        $j('#media_slider_right').click(function () {
            current_slide++;

            if (current_slide <= num_slides) {
                $j('#media_slider_wrapper').animate({
                    left: '-=960px'
                }, 700, function () {
                    // Animation complete.
                });
            }
            if (current_slide == num_slides) {
                $j(this).fadeTo('medium', 0.2);
            }
            if (current_slide > num_slides) {
                current_slide = num_slides;
            }

            $j('#media_slider_left').fadeTo('medium', 1);
        });

        //round corners on media slider tags
        if (!isEditMode) {
            $j('#media_slider_wrapper ul li p span').corner("cc:#737373 notch 1px");
        }
    }



    //Newsticker
    if ($j('#news').length > 0) {
        //initiate infinite news croller, clone the first 2 visible list elements
        $j('#news ul li:lt(2)').clone().appendTo('#news ul');

        //Miliseconds between news scroll
        var newstimer = 6000;

        //call the function
        setTimeout("change_news(" + newstimer + ")", newstimer);


        //Each list has a different width, so we need to set the width of each second list,
        //to make sure that a set of two, is 100% wide, so that we can slide it correctly
        $j('#news ul li.first').each(function () {
            second_list_width = (690 - $j(this).width());
            $j(this).next().css('width', second_list_width);
        });
    }

   //prevent crawlers to gain access to emails directly
    $j('a.mail-link').each(function() {
        var $Link = $j(this),
        mail = $Link.text().replace('%', '@');
        $Link.text(mail).attr('href', 'mailto:' + mail).css('visibility', 'visible');
    });

});

var current_news_slide = 1;

function change_news(newstimer, total_news_slides) {
    
    current_news_slide++;

    total_news_slides = $j('#news ul li').length;
    total_news_slides = total_news_slides / 2;

    $j('#news ul').animate({
        left: '-=690px'
    }, 700, function () {
        //alert(total_news_slides);
        if (current_news_slide == total_news_slides) {
            current_news_slide = 1;
            $j('#news ul').css('left', 0);
        }
    });

    setTimeout("change_news(" + newstimer + ")", newstimer);
}


function dynamicText() {
    var font_size = 20,
        $this;
    $j('.dynamic_text').each(function () {
        $this = $j(this);
        if ($this.text() == '') return;
        while ($this.width() < $this.parent().width() - 10) {
            font_size++;
            $this.css('font-size', font_size + 'px');
        }
    });
}


/* Since the .net setup requires a form to wrap the content, and therefore the frontend code can't contain
forms, I need to extend the jQuery serialize() method, to be able to serialize anything, and not just input 
fields in a form, but also input fields in a specific block element for instance */
(function($) {
    $.fn.serializeAll = function() {
        var returnData  = [];
        var els = $(this).find(':input').get();
        $.each(els, function() {
            if (this.name && !this.disabled && (this.checked || /text|hidden|password/i.test(this.type) || /select|textarea/i.test(this.nodeName))) {
                var val = $(this).val();
                returnData.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
            }
        });
        return returnData.join("&").replace(/%20/g, "+");
    }
})(jQuery); 

(function($) {
	/*
	 * Cufon line-height below 1.2em bugfix - http://groups.google.com/group/cufon/browse_thread/thread/91b60873e7e02ca1/3b3a29aa90a22461
	 */
	window.fixLineHeight = function($replaced, lineHeight, clearFloat) { 
		
	    $replaced.each(function(){ 
	            var $current = $(this); 
	            if (clearFloat==null) { 
	                    clearFloat = false; 
	            } 
	            var clearFloatClassname = 'fltbox'; 
	            var $cufonWords = $current.children('cufon') 
	            var $cufonSiblings = $current.children(':not(cufon)'); 
	            if ($(this).css('display')=='inline') { 
	                    $cufonWords.css('display','inline-block'); 
	            } else { 
	                    $cufonWords.css('float','left'); 
	                    $cufonWords.css('display','inline');// IE floats margin bug 
	                    $cufonSiblings.each(function(){ 
	                            $sib = $(this); 
	                            if (!($sib.css('float')=='left' || $sib.css('float')=='right') ) { 
	                                    $sib.css('float','left'); 
	                                    $sib.css('display','inline');// IE floats margin bug 
	                            } 
	                    }); 
	                    if (clearFloat && !$current.hasClass(clearFloatClassname)) { // 
	                            $current.addClass(clearFloatClassname); 
	                    } 
	            } 
	            $current.css('line-height', lineHeight); 
	            $cufonWords.css('height', lineHeight); 
	    }); 
	} 
})(jQuery); 

