﻿var $gallery;
var $slideshow;
var $_today = new Date();
var $today = ($_today.getFullYear()) + "-" + ($_today.getMonth()+1) + "-" + $_today.getDate();

$(document).ready(function () {
    // remove nojs class
    $("body").removeClass("nojs").addClass("js");
    // open link to rss new window
    $("a.rss").click(function () {
        window.open(this.href);
        return false;
    });

    $.fn.toggleFontSizeHowTo = function () {
        return this.each(function () {
            $closeButton = $("<button></button>").addClass("close minimal").html("&times; Skjul veiledningen");
            $el = $(this);
            $fontsizeHowto = $("div.fontsize-howto", $el);
            $el.toggle(function () {
                $fontsizeHowto
                    .hide()
                    .removeClass("visuallyhidden")
                    .slideDown();
            }, function () {
                $fontsizeHowto.slideUp();
            });

            $("div.fontsize-howto button.close", $el).click(function () {
                $fontsizeHowto.slideUp();
            });
            $closeButton.clone().appendTo($fontsizeHowto);
            $closeButton.clone().prependTo($fontsizeHowto);
        });
    };

    // show/hide font size howto
    $("#font-size").toggleFontSizeHowTo();

    // helper texts for inputs
    $("input.helper").focus(function () {
        if ($(this).val() == $(this).attr("alt")) {
            $(this).val("");
        }
    }).blur(function () {
        if ($(this).val() == $(this).attr("alt") || $(this).val() == "") {
            $(this).val($(this).attr("alt"));
        }
    });

    // menu
    $("#menu li a").mouseover(function () {
        $(this).addClass("hover");
    }).mouseout(function () {
        $(this).removeClass("hover");
    });
    $("#menu ul").mouseover(function () {
        $(this).parent().find("a").addClass("hover");
    });
    function show() {
        var menu = $(this);
        menu.children("ul").slideDown(50);
        menu.find("a:first").addClass("hover");
    }
    function hide() {
        var menu = $(this);
        menu.children("ul").slideUp(50, function () {
            menu.find("a:first").removeClass("hover");
        });
    }
    if ($("#menu li").length) {
        $("#menu li").hoverIntent({
            sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
            interval: 100,  // number = milliseconds for onMouseOver polling interval
            over: show,     // function = onMouseOver callback (required)
            timeout: 300,   // number = milliseconds delay before onMouseOut
            out: hide       // function = onMouseOut callback (required)
        });
    }

    // text resize
    //    $("#tools li.font-size a").click(function () {
    //        if ($(this).hasClass("increase")) {
    //            $(this).attr("class", "decrease").attr("title", "Reduser skriftstørrelsen");
    //            $('html').css('font-size', 18);
    //        } else {
    //            $(this).attr("class", "increase").attr("title", "Øk skriftstørrelsen");
    //            $('html').css('font-size', 16);
    //        }
    //        return false;
    //    });

    // show more info
    $("h4.more-info a").click(function () {
        $(this).parent().parent().find("div.more-info").slideToggle(600);
        if ($(this).hasClass("opened")) {
            $(this).text("Åpne for mer informasjon").removeClass("opened");
        } else {
            $(this).text("Vis færre detaljer").addClass("opened");
        }
        return false;
    });

    // show question
    $("ul.questions a.view-more").click(function () {
        $(this).parent().find("div").slideToggle();
        $(this).parent().toggleClass("opened");
        return false;
    });

    // live slideshow 
    if ($("ul.slides-nav a.active").length) {
        $slideshow = setInterval("slideshow()", 7000);
        $("ul.slides-nav li a").click(function () {
            clearInterval($slideshow);
            var $slide = $(this).text();
            slide($slide);
            return false;
        });
    }
    $("#live-slideshow, #home-slideshow, #slideshow").mouseover(function () {
        if ($("ul.slides-nav li").length > 1) {
            $("ul.slides-nav").show();
        }
    });
    $("#live-slideshow, #home-slideshow, #slideshow").mouseout(function () {
        $("ul.slides-nav").hide();
    });

    // live gallery
    if ($("#live-gallery").length) {
        $("#live-gallery img.active").show();
        $("#live-gallery").css({ background: "none" });
        $gallery = setInterval("gallery()", 8000);
    }
    $("#live-gallery-controls a.play").click(function () {
        $gallery = setInterval("gallery()", 8000);
        return false;
    });
    $("#live-gallery-controls a.pause").click(function () {
        clearInterval($gallery);
        return false;
    });
    $("#live-gallery-controls a.prev").click(function () {
        clearInterval($gallery);
        var $max = $("#live-gallery img").size();
        var $curr = $("#live-gallery img.active").attr("name").replace("pic-", "");
        var $prev = (parseInt($curr) == 1) ? $max : parseInt($curr) - 1;
        picture($prev);
        return false;
    });
    $("#live-gallery-controls a.next").click(function () {
        clearInterval($gallery);
        var $max = $("#live-gallery img").size();
        var $curr = $("#live-gallery img.active").attr("name").replace("pic-", "");
        var $next = (parseInt($curr) >= $max) ? 1 : parseInt($curr) + 1;
        picture($next);
        return false;
    });
    $("li.live-gallery").mouseover(function () {
        $("#live-gallery-controls").show();
    });
    $("li.live-gallery").mouseout(function () {
        $("#live-gallery-controls").hide();
    });

    // datepicker
    var $locale = {
        days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
        daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
        daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
        months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
        monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"],
        weekMin: 'wk'
    };
    $("input.date").each(function (i) {
        $dateinput = $("input[name='" + $(this).attr("name") + "']");
        $dateinput.DatePicker({
            format: 'd.m.Y',
            locale: $locale,
            date: $dateinput.val(),
            current: $dateinput.val(),
            starts: 1,
            onBeforeShow: function () {
                $_dateinput = $("input[name='" + $(this).attr("name") + "']");
                $_date = $_dateinput.val();
                if ($_date == "") {
                    var $today = new Date();
                    $_date = $today.getDate() + "." + ($today.getMonth() + 1) + "." + ($today.getFullYear());
                }
                $_dateinput.DatePickerSetDate($_date, true);
            },
            onChange: function (formated, dates) {
                $_dateinput.val(formated);
                $(this).hide();
            }
        });
    });
    $("button.date").click(function () {
        $(this).prev("input.date").trigger("click");
    });
    if ($("#dp_date_from").length) {
        $('#dp_date_from').DatePicker({
            flat: true,
            date: [$today],
            format: 'Y-m-d',
            locale: $locale,
            calendars: 1,
            mode: 'single',
            onChange: function (formated, dates) {
                $("input[name='date_from']").val(formated);
            },
            starts: 0
        });
    }
    if ($("#dp_date_from").length) {
        $('#dp_date_to').DatePicker({
            flat: true,
            date: [$today],
            format: 'Y-m-d',
            locale: $locale,
            calendars: 1,
            mode: 'single',
            onChange: function (formated, dates) {
                $("input[name='date_to']").val(formated);
            },
            starts: 0
        });
    }

    // equal heights
    /*if ($("#sidebar").height() != null) {
    $height = (($("#sidebar").height() - 5) - $("#container").height() + $("div.content:last").height());
    if ($("div.content:last").height() < $height) {
    $("div.content:last").css({ 'height': $height + "px", 'min-height': $height + "px" });
    }
    }*/

    $("#home-sections:not('body.skole #home-sections'), ul.equal-height").equalHeights();
    $("body.skole #home-sections").equalHeights(".wrap");

    //rating
    $("ul.rating li a").click(function () {
        if (!$(this).parent().parent().hasClass("disabled")) {
            $stars = new Array("one", "two", "three", "four", "five");
            $star = $stars[parseInt($(this).text()) - 1];
            $value = parseInt($(this).text());
            $url = $(this).attr("href");
            if ($(this).parent().parent().hasClass("commentform")) {
                $(this).parent().parent().attr("class", "rating commentform " + $star);
                $("input.val-" + $value).attr("checked", "checked");
                $('div.radioValue').empty();
                $('div.radioValue').append($value);
            } else {
                $(this).parent().parent().attr("class", "rating disabled " + $star);
                $.post($url);
            }
        }
        return false;
    });

    // popup
    //	$("#toolbox li.email, #share li.email").click(function(){
    //		window.open('/Templates/Public/Pages/ShareEmail.aspx','mywindow','menubar=0,resizable=yes,width=327,height=405');
    //		return false;
    //	});
    $("a.close").click(function () {
        self.close();
        return false;
    });

    //	$("#toolbox li.emailNewspaper").click(function(){
    //		window.open('/Templates/Public/Pages/ShareEmailNewspaper.aspx','mywindow','menubar=0,resizable=yes,width=327,height=405');
    //		return false;
    //	});
    //	$("a.close").click(function(){
    //		self.close();
    //		return false;
    //	});

    /* image captions */
    $("img.ImageRightWithTxt, img.ImageLeftWithTxt").addCaption();

    // sort tables ansattliste
    if ($("#skoleansatte").length) {
        $("#skoleansatte").tablesorter({
            headers: {
                0: {
                    sorter: false
                },
                4: {
                    sorter: false
                },
                5: {
                    sorter: false
                }
            }

        });
    }

    // remove icon if external link contains image
    $("#container div#content a > img, body.skole #home-wrapper a > img, #sidebar div.content a > img").each(function () {
        $(this).parent().addClass("noicon");
    });

});

/* slideshow */
function slideshow(){
	if($("ul.slides-nav a.active").length) {
		var $max  = $("ul.slides-nav li").length;
		var $curr = $("ul.slides-nav a.active").text();
		var $next = (parseInt($curr) >= $max) ? 1 : parseInt($curr)+1 ;
		slide($next);
	}
}
function slide($index){
	var $curr = $("ul.slides-nav a.active").text();
	if($curr!=$index) {
		$("ul.slides li").fadeOut(1500);
		$("ul.slides li").eq($index-1).fadeIn(1500);
		$("ul.slides-nav a").removeClass("active");
		$("ul.slides-nav li a").eq($index-1).addClass("active");
	}
}

/* gallery */
function gallery(){
	var $max  = $("#live-gallery img").size();
	var $curr = $("#live-gallery img.active").attr("name").replace("pic-", "");
	var $next = (parseInt($curr) >= $max) ? 1 : parseInt($curr)+1 ;
	picture($next);
}
function picture($index){
	var $curr = $("#live-gallery img.active").attr("name").replace("pic-", "");
	if($curr!=$index) {
		$("#live-gallery img").fadeOut(1500);
		$("#live-gallery img").eq($index-1).fadeIn(1500);
		$("#live-gallery img").removeClass("active");
		$("#live-gallery img").eq($index-1).addClass("active");
	}
}

$.fn.addCaption = function () {
    return this.each(function () {
        var title = $(this).attr("title");
        if (title.length) {
            $caption = $("<p/>");
            var imageClass = $(this).attr("class");
            var width = $(this).width() ? $(this).width() : $(this).attr("width");
            var cssWidth = $(this).css("width");

            if (!width) {
                $caption.css("width", $(this).css("width"));
            } else {
                $caption.css("width", width + "px");
            }
            $caption.addClass(imageClass + " ImageCaptionText").html(title);
            $(this).after($caption);
        }
    });
};

$.fn.equalHeights = function (element) {
    $(this).each(function () {
        var currentTallest = 0;
        $(this).children().each(function (i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        if (element)
            $(this).find(element).css({ 'min-height': currentTallest - 54 });
        else
            $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};

