var validatorContactForm = null;

$(document).ready(function () {
    $('.bookframe').iframeAutoHeight();

    if ($('.bookframe').length == 1) {
        $('.bookframe').load(function () {
            bookframe = this;
            bookframeHeight = $(bookframe.contentWindow.document.body).height();
            bookframeWatchTimer = window.setTimeout(watchCallbackBookFrame, 500);
        });
    }

    $(".huvudnavlagerTreKolumn").each(function (index) {
        var maxLi = 0;
        $(this).find("ul.equalLi").each(function () {
            var c = $(this).find('li').length;
            if (c > maxLi) maxLi = c;
        });
        $(this).find("ul.equalLi").each(function () {
            while ($(this).find('li').length < maxLi) {
                $(this).append('<li></li>');
            }
        });
    });

    $(".huduvnavigeringlager").each(function (index) {
        $(this).find("section:last").addClass("lankkolumnSist");
    });

    $("#huduvnavigering .submenu .huvudnavlagerEnKolumn").each(function (index) {
        var menuItemWidth = $(this).parent().width();
        var dropDownWidth = $(this).width();
        var diff = dropDownWidth - menuItemWidth;
        $(this).attr("style", "margin-left:-" + diff / 2 + "px");
    });

    if ($("input.disablepaste").length > 0) {
        $("input.disablepaste").live("paste", function (e) {
            e.preventDefault();
        });
    }

    if ($(".autoScroll").length > 0) {
        // Initialize scrollable if autoScroll exists
        $(".autoScroll").scrollable({
            size: 1,
            speed: 1000,
            clickable: false
        }).autoscroll(5000).circular().navigator();
    }

    // Add JavaScript-active class
    $("body").addClass("js");
    $("#panel li:last").addClass("last");

    $("#huduvnavigering li.submenu").hoverIntent({
        sensitivity: 7,
        interval: 100,
        over: showMenu,
        timeout: 10,
        out: hideMenu
    });

    $("#huduvnavigering li").not('.submenu').hover(
		function () {
		    $(this).addClass("aktiv");
		}, function () {
		    $(this).removeClass("aktiv");
		});


    $(".verktyg .trigger").bind("click", function () {
        if ($(this).hasClass('triggerAktiv')) {
            $(this).removeClass('triggerAktiv').next().slideUp();
        } else {
            $(this).addClass('triggerAktiv').next().slideDown();
        }
    });

    // Switch input values and Active-class
    $('.sokText .inmatning input, .kontakt .form input[type="text"], .kontakt .form textarea').not('.sokTextInputAktiv').each(function () {
        var DefaultValue = this.value;
        $(this).focus(function () {
            if (this.value == DefaultValue) {
                this.value = '';
            } else {
            }
        });
        $(this).blur(function () {
            if (this.value == '') {
                this.value = DefaultValue;
            } else {
            }
        });
    });

    $('.sokText .inmatning input').each(function () {
        if ($(this).val() == defaultSearchText) {
            if (window.location.href.indexOf("#") == -1) {
                $(this).focus();
                setTimeout("initSokText($('.sokText .inmatning input'), true);", 50);
            }
        }
        else {
            initSokText($('.sokText .inmatning input'), false);
        }
        $(this).blur(function () {
            if ($(this).val() == defaultSearchText) {
                $(this).addClass('standardSokText');
            }
            $(this).parent().parent().removeClass('sokTextAktiv');
        });
        $(this).keydown(function () {
            $(this).removeClass('standardSokText');
            $(this).parent().parent().addClass('sokTextAktiv');
            if ($(this).val() == defaultSearchText) {
                $(this).val("");
            }
            $("#sokrad #multiselect_1").multiSelectOptionsHide();
            $("#sokrad #multiselect_2").multiSelectOptionsHide();
        });
    });

    var isShiftPressed = false;

    $(document).keydown(function (event) {
        if (event.keyCode == 16) {
            isShiftPressed = true;
        }
    });

    $(document).keyup(function (event) {
        if (event.keyCode == 16) {
            isShiftPressed = false;
        }
    });

    $('.sokText .inmatning input').keydown(function (event) {
        if (event.keyCode == 9) {
            if (!isShiftPressed) {
                $("#sokrad #multiselect_1").multiSelectOptionsShow();
                if ($(this).val() == "") {
                    $(this).addClass('standardSokText');
                    $(this).val(defaultSearchText);
                }
                return false;
            }
        }
    });

    $('#sokrad .sokVadContainer #sokPlats').keydown(function (event) {
        if (event.keyCode == 9) {
            $("#sokrad #multiselect_1").multiSelectOptionsHide();
            if (isShiftPressed) {
                $("#sokrad .sokText").addClass("sokTextAktiv");
                $("#sokrad .sokText input").focus();
            }
            else {
                $("#sokrad #multiselect_2").multiSelectOptionsShow();
            }
            return false;
        }
        else if (event.keyCode == 13) {
            $("#sokrad input.submit").click();
            return false;
        }
    });

    $('#sokrad .sokNarContainer #sokDatum').keydown(function (event) {
        if (event.keyCode == 9) {
            $("#sokrad #multiselect_2").multiSelectOptionsHide();
            if (isShiftPressed) {
                $("#sokrad #multiselect_1").multiSelectOptionsShow();
            }
            else {
                $("#sokrad input.submit").focus();
            }
            return false;
        }
        else if (event.keyCode == 13) {
            $("#sokrad input.submit").click();
            return false;
        }
    });

    $("#sokrad input.submit").keydown(function (event) {
        if (event.keyCode == 9) {
            if (isShiftPressed) {
                $("#sokrad #multiselect_2").multiSelectOptionsShow();
            }
            return false;
        }
    });

    $(".sokText .toggle").bind("click", function () {
        if ($(this).parent().parent().hasClass('sokTextAktiv')) {
            $(this).parent().parent().removeClass('sokTextAktiv');
        } else {
            $(this).parent().parent().addClass('sokTextAktiv');
        }
    });

    $(".sokText .radera").bind("click", function () {
        $('.sokText .inmatning input').removeAttr('value');
    });

    var selectOptions = '.radera'
    var selectChildren = '.autocomplete, .datum'
    $('.sokSelect').each(function () {
        $(this).children(selectChildren).hide();
        $(this).children().children(selectOptions).hide();
    });


    $(".sokSelect .toggle").bind("click", function () {
        if ($(this).parent().parent().hasClass('sokSelectAktiv')) {
            $(this).parent().parent().removeClass('sokSelectAktiv');
            $(this).parent().children(selectOptions).hide();
            $(this).parent().parent().children(selectChildren).hide();
        } else {
            $(this).parent().children(selectOptions).show();
            $(this).parent().parent().children(selectChildren).show();
            $(this).parent().parent().addClass('sokSelectAktiv');
        }
    });

    $(".sokSelect .radera").bind("click", function () {
        $(this).prev().html('');
    });

    $(".kontaktTrigger").bind("click", function (e) {
        e.preventDefault();
        if ($(this).hasClass('kontaktTriggerAktiv')) {
            $(this).removeClass('kontaktTriggerAktiv');
            $(this).parent().parent().parent().children('.skicka').hide();
            $(this).parent().parent().parent().children('.bekraftelse').hide();
            $(this).parent().parent().parent().children('.form-error').hide();
            $(this).parent().parent().parent().children().children('.form').hide();
        } else {
            $(this).addClass('kontaktTriggerAktiv');
            $(this).parent().parent().parent().children('.bekraftelse').hide();
            $(this).parent().parent().parent().children('.form-error').hide();
            $(this).parent().parent().parent().children('.skicka').show();
            $(this).parent().parent().parent().children().children('.form').show();
        }
    });

    $(".kontaktStang").bind("click", function () {
        $(".kontakt .kontaktTrigger").removeClass('kontaktTriggerAktiv');
        $(".kontakt .skicka, .kontakt .form, .kontakt .bekraftelse, .kontakt .form-error").hide();
    });

    $(".konfirmering .stang").bind("click", function () {
        $(this).parent().hide();
        $(".kontakt .kontaktTrigger").removeClass('kontaktTriggerAktiv');
        $(".kontakt .skicka, .kontakt .form").hide();
    });

    // TEMP För att visa konfirmering
    $("#submitTrigger").bind("click", function () {
        $(".konfirmering").show().delay(1500).fadeOut(400, function () {
            $(".kontakt .kontaktTrigger").removeClass('kontaktTriggerAktiv');
            $(".kontakt .skicka, .kontakt .form").hide();
        });

    });

    $(".amnesomraden .innehall li:even").addClass("forst");

    $("table.Editortabell tr:even").addClass("trJamn");

    $("table.Editortabell tr:last td:first").addClass("tdSistVanster");
    $("table.Editortabell tr:last td:last").addClass("tdSistHoger");

    $('table.Editortabell tr').each(function () {
        $(this).children("td:first").addClass("tdForst");
        $(this).children("td:last").addClass("tdSist");
        $(this).children("th:first").addClass("thForst");
        $(this).children("th:last").addClass("thSist");
    });

    $(".selekteringToggle").bind("click", function () {
        if ($(this).hasClass('selekteringToggleAktiv')) {
            $(this).removeClass('selekteringToggleAktiv');
            $(this).next().hide();
        } else {
            $(this).addClass('selekteringToggleAktiv');
            $(this).next().show();
        }
    });

    // Clickable
    $(".clickable").css("cursor", "pointer");
    $(".clickable").click(function () {
        var location = $(this).children().find('a:first').attr("href");
        var target = $(this).children().find('a:first').attr("target");
        if (target == "_blank") {
            window.open(location, '', '');
        }
        else {
            window.location = location;
        }
        return false;
    });

    $(".anmalningsvillkor").bind("click", function (e) {
        e.preventDefault();
        $('body').append('<div class="overlay"></div>');
        $('#kursanmalan-villkor').show();
    });

    $("#kursanmalan-villkor .stang").bind("click", function () {
        $('.overlay').remove();
        $('#kursanmalan-villkor').hide();
    });

    $("#kursanmalan .foretag h2.toggle span").bind("click", function () {
        $(this).parent().toggleClass("toggleAktiv");
        $(this).parent().next().toggleClass("toggleInnehallAktiv");
    });

    $("#favorit-information .stang").bind("click", function () {
        $('#favorit-information').hide();
        $('.overlay').remove();
    });

    $(".lankkolumner h4 a").click(function () {
        var ul = $(this).parent().parent().find("ul");
        if ($(ul).is(':visible')) {
            $(ul).slideUp();
        }
        else {
            $(this).parent().parent().parent().parent().find("ul").slideUp();
            $(ul).slideDown();
        }
    });

    if ($('#ExpandableGuide').length > 0) {
        $('#ExpandableGuide').find('aside').find('header').click(function () {
            scope = $(this).parent();
            var isOpen = scope.hasClass('open');
            var index = 0;
            $('#ExpandableGuide').find('aside.open').find('.content').slideUp(300, function () { $(this).parent().removeClass('open') });
            if (!isOpen) {
                scope.find('.content').slideDown(300, function () { $(this).parent().addClass('open') });
                index = scope.attr("index");
            }

            TrackExpandableGuidePageview(index);
        });

        $('#ExpandableGuide').find('.button').click(function () {
            scope = $(this);
            var next = scope.hasClass('next');
            var prev = scope.hasClass('prev');
            var open = $('#ExpandableGuide').find('aside.open');
            var index = 0;
            if (scope.hasClass('firstStep')) {
                if (open.length > 0) {
                    open.find('.content').slideUp(300, function () { $(this).parent().removeClass('open') });
                }
                $($('#ExpandableGuide').find('aside')[0]).find('.content').slideDown(300, function () { $(this).parent().addClass('open') });
                index = $($('#ExpandableGuide').find('aside')[0]).attr("index");
            }
            else {
                open.find('.content').slideUp(300, function () { $(this).parent().removeClass('open') });
                if (next) {
                    open.next('aside').find('.content').slideDown(300, function () { $(this).parent().addClass('open') });
                    index = open.next('aside').attr("index");
                }
                if (prev) {
                    open.prev('aside').find('.content').slideDown(300, function () { $(this).parent().addClass('open') });
                    index = open.prev('aside').attr("index");
                }
            }

            TrackExpandableGuidePageview(index);

            return false;
        });

        var asides = $('#ExpandableGuide').find('aside');

        asides.each(function (index) {
            var next = $(this).find('a.next');
            var prev = $(this).find('a.prev');

            $(this).attr("index", index + 1);

            if (index == 0) {
                prev.hide();
            }
            if (index == (asides.length - 1)) {
                next.hide();
            }
        });
    }


    initFavorites();

    initKPI();
    initBreadcrumb();

    initModulAmnen();

    if ($("#kontakt.kontakt").length > 0) {
        var container = $("#kontakt.kontakt .form-error");
        validatorContactForm = $("form").validate({ errorContainer: container,
            errorLabelContainer: $("ul", container),
            wrapper: 'li',
            meta: "validate",
            onkeyup: false,
            onfocusout: false,
            onsubmit: false,
            onclick: false
        });
    }

    initSearchResultFilter();
    initSearchResultHoverIntent($('table.searchResultHoverIntent'));
});

function TrackExpandableGuidePageview(index) {
    if (index > 0 && _gaq != null) {
        var url = window.location.href.replace("http://", "").replace("https://", "");
        var urlItems = url.split("/");
        var path = "/";
        for (var i = 0; i < urlItems.length; i++) {
            if (i > 0 && urlItems[i] != "") {
                path += urlItems[i] + "/";
            }
        }
        path = "/virtuell" + path + index + "/";
        _gaq.push(['_trackPageview', path]);
    }
}

function watchCallbackBookFrame() {
    if (bookframe) {
        var val = $(bookframe.contentWindow.document.body).height();
        if (val != bookframeHeight) {
            bookframeHeight = val;
            $('.bookframe').css("height", bookframeHeight + 'px');
        }
        bookframeWatchTimer = window.setTimeout(watchCallbackBookFrame, 500);
    }
}

function ValidateContactForm() {
    var inputName = $("#kontakt.kontakt input[id$=txtName]");
    var inputEmail = $("#kontakt.kontakt input[id$=txtEmail]");
    var selectContact = $("#kontakt.kontakt select[id$=DropDownContacts]");
    var isDefaultName = inputName.val() == "Fyll i ditt namn";
    if (isDefaultName) {
        inputName.val("");
    }
    
    var isNameValid = validatorContactForm.element(inputName);
    var isEmailValid = validatorContactForm.element(inputEmail);
    var isContactValid = true;
    if (selectContact.length > 0) {
        isContactValid = validatorContactForm.element(selectContact);
    }

    if (isDefaultName) {
        inputName.val("Fyll i ditt namn");
    }

    return isNameValid && isEmailValid && isContactValid;
}

function initModulAmnen() {
    var lis = $(".column300 .amnen .innehall ul li");
    if (lis) {
        var num = lis.length;
        if (num > 0) {
            for (var i = 0; i < num; i = i + 2) {
                var a1 = $(lis[i]).find("a");
                var a2 = $(lis[i + 1]).find("a");
                if (a1 && a2 && a1.length > 0 && a2.length > 0) {
                    var h1 = a1.height();
                    var h2 = a2.height();
                    if (h1 < 15) {
                        a1.height(15);
                    }
                    if (h2 < 15) {
                        a2.height(15);
                    }
                    if (h1 > h2) {
                        if ((h1 - h2) > 5) {
                            a2.height(h1);
                        }
                    }
                    else if (h2 > h1) {
                        if ((h2 - h1) > 5) {
                            a1.height(h2);
                        }
                    }
                }
            }
        }
    }
}

function initFavorites() {
    if ($("#genvagar section.sparadekurser a span#antalfavoriter").length > 0) {
        Folkuniversitetet.CMS.Services.AjaxScriptService.GetNumberOfCourseFavorites(GetNumberOfCourseFavorites_onSuccess, GetNumberOfCourseFavorites_onFail);
    }
}

function GetNumberOfCourseFavorites_onSuccess(result) {
    if (result) {
        var response = Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
        if (response.Success) {
            $("#genvagar section.sparadekurser a span#antalfavoriter").html("(" + response.NumberOfFavorites + ")");
        }
        else {
            GetNumberOfCourseFavorites_onFail();
        }
    }
    else {
        GetNumberOfCourseFavorites_onFail();
    }
}

function GetNumberOfCourseFavorites_onFail() {
    $("#genvagar section.sparadekurser a span#antalfavoriter").html("(0)");
}

function initSokText(obj, isDefault) {
    if (isDefault) {
        $(obj).val(defaultSearchText).setCursorPosition(0);
    }
    $(obj).focus(function () {
        $(obj).removeClass('standardSokText');
        $(obj).parent().parent().addClass('sokTextAktiv');
        $("#sokrad #multiselect_1").multiSelectOptionsHide();
        $("#sokrad #multiselect_2").multiSelectOptionsHide();
    });
}

var breadcumbMaxLength = 940;

function initBreadcrumb() {
    var breadcrumb = $("#pagewrap #pageinnehall #innehall #brodsmulor");
    var widthBreadcrumb = getBreadcrumbWidth();
    var i = 0;
    var liCount = $(breadcrumb).find("li").length;
    while (widthBreadcrumb > breadcumbMaxLength && i < liCount) {
        $(breadcrumb).find("li").each(function(index) {
            if (index == i)
            {
                $(this).find("a").html("...");
            }
        });
        widthBreadcrumb = getBreadcrumbWidth();
        i++;
    }
}

function getBreadcrumbWidth() {
    var breadcrumb = $("#pagewrap #pageinnehall #innehall #brodsmulor");
    var widthBreadcrumb = 0;
    var a = $(breadcrumb).find("a.tillbaka");
    if ($(a).length > 0) {
        widthBreadcrumb += getWidth(a);
    }
    $(breadcrumb).find("li").each(function(index) {
        widthBreadcrumb += getWidth(this);
    });
    return widthBreadcrumb;
}

function getWidth(el) {
    var width = 0;
    width += $(el).width();
    width += parseInt($(el).css("margin-left"));
    width += parseInt($(el).css("margin-right"));
    width += parseInt($(el).css("padding-left"));
    width += parseInt($(el).css("padding-right"));
    return width;
}

function showMenu(){
	if ($("#huduvnavigering li.submenu:not(this)").children(".huduvnavigeringlager").hasClass('visible')) {
		var self = this
		var selfTrigger = $(this).children("a.top")
		$(".huduvnavigeringlager").parent().removeClass("aktiv").end().removeClass("visible").hide(1, function(){
			$(self).addClass("aktiv").children(".huduvnavigeringlager").show(1).addClass("visible");
		});
		selfTrigger.append("<span class='indikator'></span>");
	} else {
		$(this).addClass("aktiv").children(".huduvnavigeringlager").show(1).addClass("visible");
		$(this).children("a.top").append("<span class='indikator'></span>");
	}
}

function hideMenu(){
	$(this).removeClass("aktiv").children(".huduvnavigeringlager").hide(1).removeClass("visible");
	$(this).children("a.top").children(".indikator").remove();
}

function GetFlickrLatestPhotos(containerId, numOfPhotos, userId, photoSetId, isLargePhotos, displayTitleInPopup) {
    $("#" + containerId).parent().find("img.Loading").css("display", "block");
    Folkuniversitetet.CMS.Services.AjaxScriptService.GetFlickrLatestPhotos(containerId, numOfPhotos, userId, photoSetId, isLargePhotos, displayTitleInPopup, GetFlickrLatestPhotos_onSuccess, GetFlickrLatestPhotos_onFail);
}

function GetFlickrLatestPhotos_onSuccess(result) {
    if (result && result.Success) {
        var container = $("#" + result.ContainerId);
        container.html("");
        
        container.append("<div class='lightboxholder'>");
        
        for (var i = 0; i < result.Photos.length; i++) {
            var title = "";
            if (result.DisplayTitleInPopup) {
                title = result.Photos[i].Title;
            }
            result.Photos[i].Title;
            var a = "<a class='imagesBox' href='" + result.Photos[i].Url + "' target='_blank' rel='" + result.ContainerId + "' title='" + title + "'><img src='" + result.Photos[i].PhotoUrl + "' title='" + result.Photos[i].Title + "' /></a>";
            if (i > 0 && i % 3 == 0) {
                container.append("<li class='last'>" + a + "</li>");
            }
            else {
                container.append("<li>" + a + "</li>");
            }
        }
        
        container.append("</div>");
        
        container.append("<div class='clear'></div>");

        $(".imagesBox").fancybox({
            cyclic: true,
            centerOnScroll: true,
            padding: 20,
            titlePosition: 'inside'
        });
    }
    else if (result) {
        var container = $("#" + result.ContainerId);
        container.html("<li>Systemfel</li>");
    }
}

function GetFlickrLatestPhotos_onFail() {

}

function GetTwitterFeed(username, count, containerId) {
    Folkuniversitetet.CMS.Services.AjaxScriptService.GetTwitterFeed(username, count, containerId, GetTwitterFeed_onSuccess, GetTwitterFeed_onFail);
    //$.getJSON(url, function(data) { GetTwitterUserTimeline_Callback(data, containerId); });
}

function GetTwitterFeed_onSuccess(result) {
    if (result && result.Success) {
        var container = $("#" + result.ContainerId);
        container.parent().find(".twitterkHeader").css("display", "block");
        var twitterHeaderContent = "<img src='" + result.ProfileImageUrl + "' /><strong>" + result.ScreenName + "</strong>";
        if (result.Description && result.Description != "") {
            twitterHeaderContent += " - " + result.Description;
        }
        container.parent().find(".twitterkHeader p").html(twitterHeaderContent);
        container.find("ul").html("");
        for (var j = 0; j < result.Items.length; j++) {
            var createdAt = $.browser.msie ? relativeTwitterTime(result.Items[j].CreatedAt) : $.timeago(dateFormat(result.Items[j].CreatedAt, "isoUtcDateTime"));
            var li = "<li><p class='runin'>" + replaceURLWithHTMLLinks(result.Items[j].Text) + "</p><p class='lighten'>" + createdAt + " via " + result.Items[j].Source + "</p></li>";
            container.find("ul").append(li);
        };
    }
    else if (result) {
        var container = $("#" + result.ContainerId);
        container.parent().find(".twitterkHeader").css("display", "block");
        container.parent().find(".twitterkHeader p").html("Systemfel");
        container.css("display", "none");
    }
}

function GetTwitterFeed_onFail() {

}

function GetTwitterUserTimeline_Callback(data, containerId) {
    var container = $("#" + containerId);
    if (data != null && data.items != null && data.items.length > 0) {
        container.parent().find(".twitterHeader").css("display", "block");
        container.parent().find(".twitterHeader p").html("<img src='" + data.items[0].user.profile_image_url + "' />" + data.items[0].screen_name);
        $("#" + containerId).find("ul").html("");
        $.each(data, function (i, item) {
            var createdAt = $.browser.msie ? relativeTwitterTime(item.created_at) : $.timeago(dateFormat(item.created_at, "isoUtcDateTime"));
            var li = "<li><p class='runin'>" + replaceURLWithHTMLLinks(item.text) + "</p><p class='lighten'>" + createdAt + " via " + item.source + "</p></li>";
            $("#" + containerId).find("ul").append(li);
        });
    }
}

function replaceURLWithHTMLLinks(text) {
    if (text != null) {
        var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
        return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
    }
    return "";
}

function relativeTwitterTime(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    return relativeTime(relative_to, parsed_date);
}

function relativeTime(relative_to, parsed_date) {
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    var r = '';
    if (delta == 0) {
        r = '1 sekund sedan';
    }
    else if (delta < 60) {
        r = delta + ' sekunder sedan';
    } else if (delta < (45 * 60)) {
        r = (parseInt(delta / 60)).toString() + ' minuter sedan';
    } else if (delta < (90 * 60)) {
        r = '1 timme sedan';
    } else if (delta < (24 * 60 * 60)) {
        r = '' + (parseInt(delta / 3600)).toString() + ' timmar sedan';
    } else if (delta < (48 * 60 * 60)) {
        r = '1 dag sedan';
    } else {
        r = (parseInt(delta / 86400)).toString() + ' dagar sedan';
    }

    return r;
}

function GetFacebookFeed(id, count, containerId) {
    Folkuniversitetet.CMS.Services.AjaxScriptService.GetFacebookFeed(id, count, containerId, GetFacebookFeed_onSuccess);
}

function GetFacebookFeed_onSuccess(response) {
    if (response != null) {
        var container = $("#" + response.ContainerId);
        var ul = container.find("ul").html("");
        if (response.Success) {
            for (var j = 0; j < response.Items.length; j++) {
                ul.append("<li><p>" + response.Items[j].Description + "</p><p class='lighten date'>" + jQuery.timeago(response.Items[j].PubDate) + "</p></li>");
            }
        }
        else {
            ul.append("<li><p>Ett fel uppstod i kommunikationen med Facebook</p></li>");
        }
    }
}

function initKPI() {
    // KPI for payment form
    $("#kursanmalan .form-kursanmalan input").each(function(index) {
        $(this).focus(function() {
            var isGaq = $("input[id$=InputIsKursanmalanFocusGaq]").val();
            if (isGaq == "") {
                _gaq.push(['_trackPageview', '/virtuell/Kursanmalan/formular/markerat-falt/']);
                $("input[id$=InputIsKursanmalanFocusGaq]").val("1");
            }
        });
    });
    // KPI external links, document links
    $("a").each(function(index) {
        var href = $(this).attr("href");
        if (href != null && href != "") {
            if ($(this).attr("href").indexOf("mailto:") > -1) {
                var path = $(this).attr("href").replace("mailto:", "").replace("@", "-");
                $(this).click(function() {
                    _gaq.push(['_trackPageview', '/virtuell/e-post/' + path + '/'], ['_trackEvent', 'kontakt', 'e-postkontakt', 'count', 1]);
                    return true;
                });
            }
            else if (href.indexOf(siteHost) == -1 && (href.indexOf("http://") > -1 || href.indexOf("https://") > -1)) {
                $(this).click(function() {
                    _gaq.push(['_trackPageview', '/virtuell/external/' + href.replace("http://", "").replace("https://", "")]);
                    return true;
                });
            }
            else if (href.indexOf("/Global/DOKUMENTBANKEN/") > -1) {
                var virtualHref = GetKPIDocumentVirtualHref(href);
                if (virtualHref != "") {
                    $(this).click(function() {
                        _gaq.push(['_trackPageview', virtualHref]);
                        return true;
                    });
                }
            }
        }
    });
}

function GetKPIDocumentVirtualHref(href) {
    var items = href.split('?');
    if (items != null && items.length > 0) {
        var fileType = "";
        if (items[0].match(/pdf$/)) {
            fileType = "pdf";
        }
        else if (items[0].match(/doc$/)) {
            fileType = "doc";
        }
        else if (items[0].match(/docx$/)) {
            fileType = "docx";
        }
        else if (items[0].match(/ppt$/)) {
            fileType = "ppt";
        }
        else if (items[0].match(/pptx$/)) {
            fileType = "pptx";
        }
        else if (items[0].match(/pps$/)) {
            fileType = "pps";
        }
        else if (items[0].match(/ppsx$/)) {
            fileType = "ppsx";
        }
        else if (items[0].match(/xls$/)) {
            fileType = "xls";
        }
        else if (items[0].match(/xlsx$/)) {
            fileType = "xlsx";
        }
        else if (items[0].match(/zip$/)) {
            fileType = "zip";
        }
        else if (items[0].match(/vcf$/)) {
            fileType = "vcf";
        }

        if (fileType != "") {
            return "/virtuell/download/" + fileType + href.replace("http://", "").replace("https://", "");
        }
    }

    return "";
}

/* ---------------------------------------------------------------------------------------------
    sf = SearchFilter - prefix for searchfilter utility functions
--------------------------------------------------------------------------------------------- */
function sfGetHeaderRowHtml(msg, id) {
    return '<p id="' + id + '" class="header"><strong><a href="" class="close">Stäng</a> <span>' + msg + '</span></strong></p>';
}
function sfGetNormalRowHtml(msg, id) {
    return '<p id="' + id + '"><a href="" class="close">Stäng</a> <span>' + msg + '</span></p>';
}
function sfGetLabelText($pLabel) {
    var $lblCopy = $pLabel.clone();
    $lblCopy.find('span').remove();
    return $lblCopy.html().trim();
}
function getTimeFormat(pTime) {
    var num = parseInt(pTime, 10);
    var timeFormat = String(pTime);
    if (num < 10) {
        timeFormat = '0' + timeFormat;
    }
    return (timeFormat += ':00');
}
function sfGetCheckboxIdClass($pCheckbox) {
    return $pCheckbox.attr('class').replace('checkbox', '').trim();
}
function sfCheckSectionState(pCheckbox, $scope) {
    var $checkbox = $(pCheckbox);
    var checkId = sfGetCheckboxIdClass($checkbox);
    var $currentElem = $scope.find('#' + checkId);
    var $visibleSiblings = $currentElem.siblings(':visible').not('hr').not('p.header');
    var $section = $currentElem.closest('.section');
    var $searchFilter = $scope.find('.searchFilter');
    var $listContent = $searchFilter.find('.listContent');

    if ($checkbox.is(':checked') || $visibleSiblings.length) {
        $section.css('display', 'block');
        $searchFilter.css('display', 'block');
    }
    else {
        $section.css('display', 'none');
        if ($listContent.find('.section:visible').length !== 0) { // check if other sections have visible elements
            $searchFilter.css('display', 'block');
        }
        else {
            $searchFilter.css('display', 'none');
        }
    }
}
function sfShowInFilter(itemId) {
    var $filterRow = $('#' + itemId);
    //var $section = $filterRow.closest('.section'); // REMOVE - unused variable
    $filterRow.css('display', 'block');
}
function sfHideInFilter(itemId) {
    $('#' + itemId).css('display', 'none');
}
function sfGetIdFormat(index, index2) {
    return 'sf' + index + '-' + index2;
}
function sfGetSectionsHtml($pSections) {
    var section = "";
    $pSections.each(function (index) {
        var $labels = $(this).find('label');
        $labels.each(function (index2) {
            var itemId = sfGetIdFormat(index, index2);
            var labelText = sfGetLabelText($(this));
            if (index2 !== 0) {
                section += sfGetNormalRowHtml(labelText, itemId) + '\n';
            }
            else {
                section += '<div class="section">' + sfGetHeaderRowHtml(labelText, itemId) + '\n';
            }
            //$(this).closest('li').addClass(itemId);
            $(this).siblings('input[type=checkbox]').addClass(itemId);
        });
        section += '<hr /></div>\n';
    });
    return section;
}

/* =====================================================================
    SearchFilter - init and main functions
   ===================================================================== */
function initFilterBox($pScope) {
    var $searchFilter = $pScope.find('.searchFilter');
    var $listContent = $searchFilter.find('.listContent');
    var $searchTopics = $pScope.find('.searchTopics');
    var $sections = $searchTopics.children('li');
    $listContent.html(sfGetSectionsHtml($sections));
}

function initTimeSlider() {
    var $tsMin = $('#tsMin');
    var $tsMax = $('#tsMax');

    var start = 8;
    var end = 21;

    var htsMin = $('input[id$=HiddenTsMin]');
    var htsMax = $('input[id$=HiddenTsMax]');

    if (htsMin.length > 0 && htsMin.val() != "") {
        start = parseInt(htsMin.val());
    }
    if (htsMax.length > 0 && htsMax.val() != "") {
        end = parseInt(htsMax.val());
    }

    var slider = $('#timeSlider').slider({
        range: true,
        min: 8,
        max: 21,
        values: [start, end],
        create: function () {
            $(this).slider('widget').find('.ui-slider-handle').each(function (index) {
                if (index === 0) {
                    $(this).addClass('ui-handle-left');
                }
                else if (index === 1) {
                    $(this).addClass('ui-handle-right');
                };
            });

            $tsMin.val(getTimeFormat(start));
            $tsMax.val(getTimeFormat(end));
        },
        slide: function (event, ui) {
            if (ui.values[0] === (ui.values[1])) {
                return false;
            }
            $tsMin.val(getTimeFormat(ui.values[0]));
            $tsMax.val(getTimeFormat(ui.values[1]));

            var htsMin = $('input[id$=HiddenTsMin]');
            var htsMax = $('input[id$=HiddenTsMax]');

            if (htsMax.length > 0) {
                htsMax.val(getTimeFormat(ui.values[0]));
            }
            if (htsMax.length > 0) {
                htsMax.val(getTimeFormat(ui.values[1]));
            }
        }
    });
}

function addCheckboxClickListener($scope) {
    $scope.find('input[type=checkbox]').click(function () {
        var $childBoxes = $(this).closest('li').find('li input[type=checkbox]');
        if ($(this).is(':checked')) {
            /* Note: Only one of the two rows below should be uncommented at one time */
            //$childBoxes.attr('checked', true);    // select sub rows
            $childBoxes.attr('checked', false).change();     // unselect sub rows
        }
        else {
            $childBoxes.attr('checked', false).change();
        }

        var lisToUncheck = $(this).parents('li:eq(0)').parentsUntil('.searchTopics > li').filter('li');
        lisToUncheck.each(function () {
            $(this).find('input[type=checkbox]:eq(0)').attr('checked', false).change();
        });

        sfCheckSectionState(this, $scope);

        $('.searchResultFilter').trigger('tsCheckbox', [$(this).parentsUntil('.searchTopics').filter('.searchTopics > li').index()]);
    });
}

function addCheckboxChangeListener($scope) {
    $scope.find('input[type=checkbox]').change(function () {
        var $self = $(this);
        var itemId = sfGetCheckboxIdClass($self);
        if ($self.is(':checked')) {
            sfShowInFilter(itemId);
        }
        else {
            sfHideInFilter(itemId);
        }
    });
}

function addFilterItemCloseListener($scope) {
    $scope.find('.searchFilter .listContent .close').live('click', function (evt, callTrigger) {
        evt.preventDefault();
        var $elem = $(this).closest('p');
        var elemId = $elem.attr('id');
        var $checkbox = $scope.find('.searchTopics .' + elemId);
        if (!$elem.hasClass('header')) {
            $checkbox.attr('checked', false).change();
            sfCheckSectionState($checkbox, $scope);
        }
        else { // user clicked close section button
            var numItems = $elem.siblings('p:visible').length;
            numItems -= 1;
            var callTriggerOnLast = callTrigger ? false : true;
            callTrigger = 'preventDefault';
            $elem.siblings('p:visible').each(function (index) { // close all elements in the section
                $(this).find('.close').trigger('click', [callTrigger]);
                if (callTriggerOnLast && numItems === index) {
                    $('.searchResultFilter').trigger('tsClose', [elemId[2]]);
                }
            });
        }

        if (!callTrigger) {
            $('.searchResultFilter').trigger('tsClose', [elemId[2]]);
        }
    });
}

function addFilterItemResetListener($scope) {
    $scope.find('.searchFilter .reset').live('click', function () {
        $scope.find('.section:visible').find('.header .close').trigger('click', ['preventTrigger']);
        $('.searchResultFilter').trigger('tsReset');
    });
}

/* if elem has one of the two classes (class1 or class2)
the function removes the matched class and adds the unmatched */
function switchClass($elem, class1, class2) {
    if ($elem.hasClass(class1) | $elem.hasClass(class2)) {
        if ($elem.hasClass(class1)) {
            $elem
                .removeClass(class1)
                .addClass(class2);
        }
        else if ($elem.hasClass(class2)) {
            $elem
                .removeClass(class2)
                .addClass(class1);
        }
    }
}

/* toggle the li-class on label-click */
function addLabelClickListener($scope) {
    $scope.find('li label').click(function () {
        var $parentLi = $(this).closest('li');
        switchClass($parentLi, 'closed', 'open');
    });
}

/* toggle the li-class on fieldset-click */
function addFieldsetClickListener($scope) {
    $scope.find('li fieldset').click(function (evt) {
        if (evt.target === this) {
            var $parentFieldset = $(this).closest('li');
            switchClass($parentFieldset, 'closed', 'open');
        }
    });
}

function updateFilter() {
    var $scope = $('.searchResultFilter');
    var $checked = $scope.find('.checkbox:checked');

    $checked.each(function () {
        var idClass = sfGetCheckboxIdClass($(this));
        sfShowInFilter(idClass);
        $('#'+idClass).closest('.section').show();
    });
    $scope.find('.searchFilter').show();
}

function initSearchResultFilter() {
    var $self = $('.searchResultFilter');
    if ($self.length) {
        addLabelClickListener($self);
        addFieldsetClickListener($self);
        addCheckboxClickListener($self);
        addCheckboxChangeListener($self);
        addFilterItemCloseListener($self);
        addFilterItemResetListener($self);
    }
    initFilterBox($self);
    initTimeSlider();
    //$self.find('.updateButton').click(function (evt) { evt.preventDefault(); updateFilter(); }); // REMOVE - placed here for now, for test
}

function closeAllMoreInfo($scope) {
    $scope.find('.moreInfoOpened').removeClass('moreInfoOpened');
}

function openMoreInfo() {
    var $self = $(this);
    closeAllMoreInfo($self.closest('table'));
    $self.next().addClass('moreInfoOpened');

    GetMoreInfoCourseListing($self);
}

function searchResultToggleableClick(evt) {
    var $currTarget = $(evt.currentTarget);
    var $scope = $currTarget.closest('table');
    var $target = $(evt.target);

    if (!$target.is('a')) {
        if (!($currTarget.next().hasClass("moreInfoOpened"))) {
            GetMoreInfoCourseListing($currTarget);
        }
        var $elemToToggle = $currTarget.next().toggleClass('moreInfoOpened');

        // check if other elems are open
        if ($scope.find('.moreInfoOpened').not($currTarget.next()).length) {
            $scope.find('.moreInfoOpened').not($currTarget.next()).removeClass('moreInfoOpened');
        }
    }
}

function GetMoreInfoCourseListing(container) {
    var $input = $(container).next().find("input.documentid");
    if ($input.length > 0) {
        var pageId = parseInt($input.val());
        $input.remove();
        Folkuniversitetet.CMS.Services.AjaxScriptService.GetMoreInfoCourseListing(pageId, GetMoreInfoCourseListing_onSuccess, GetMoreInfoCourseListing_onFail);
    }
}

function initSearchResultHoverIntent($scope) {
    var config = {
        over: openMoreInfo,
        interval: 500,      // milliseconds
        out: function (){}  // empty function - do nothing
    };
    $scope.find('tr.toggle')
        .hoverIntent(config)
        .click(function (evt) { searchResultToggleableClick(evt); });
}

new function($) {
    $.fn.setCursorPosition = function(pos) {
        try{
            if ($(this).get(0).setSelectionRange) {
                $(this).get(0).setSelectionRange(pos, pos);
            }
            else if ($(this).get(0).createTextRange) {
                var range = $(this).get(0).createTextRange();
                range.collapse(true); range.moveEnd("character", pos);
                range.moveStart("character", pos); range.select();
            }
        }
        catch (ex){
        }
    }
} (jQuery);


function GetMoreInfoCourseListing_onSuccess(response) {
    if (response.Success) {
        var html = "<div class=\"mainInfo\">";
        html += "<p class=\"header\">Mer information om kursen:</p>";
        html += "<p>" + response.Intro + "</p>";
        html += "</div>";

        if (response.Teacher != "") {
            html += "<div class=\"sideInfo\">";
            html += "<p class=\"header\">Kursledare:</p>";
            html += "<p>" + response.Teacher + "</p>";
            html += "</div>";
        }
        if (response.WeekCount != "") {
            html += "<div class=\"sideInfo sideInfoSmall\">";
            html += "<p class=\"header\">Antal veckor:</p>";
            html += "<p>" + response.WeekCount + "</p>";
            html += "</div>";
        }
        if (response.AvailableSeats != "") {
            html += "<div class=\"sideInfo sideInfoSmall\">";
            html += "<p class=\"header\">Platser kvar:</p>";
            html += "<p>" + response.AvailableSeats + "</p>";
            html += "</div>";
        }

        $(".kurslista #MoreInfo" + response.PageId).find("td div.content").html(html);
    }
    else {
        $(".kurslista #MoreInfo" + response.PageId).find("td div.content").html("<div class=\"mainInfo\">" + response.Intro + "</div>");
    }
}

function GetMoreInfoCourseListing_onFail() {

}

function ValidateSecurityNumber(value) {
    var nr = value;
    if (nr.length > 11) {
        nr = nr.substring(2);
    }
    var valid = false;
    if (!nr.match(/^(\d{2})(\d{2})(\d{2})\-(\d{4})$/)) { return false; }
    var now = new Date(); this.nowFullYear = this.now.getFullYear() + ""; this.nowCentury = this.nowFullYear.substring(0, 2); this.nowShortYear = this.nowFullYear.substring(2, 4);
    var year = RegExp.$1; this.month = RegExp.$2; this.day = RegExp.$3; this.controldigits = RegExp.$4;
    var fullYear = (this.year * 1 <= this.nowShortYear * 1) ? (this.nowCentury + this.year) * 1 : ((this.nowCentury * 1 - 1) + this.year) * 1;
    var months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (fullYear % 400 == 0 || fullYear % 4 == 0 && fullYear % 100 != 0) { months[1] = 29; }
    if (month * 1 < 1 || month * 1 > 12 || day * 1 < 1 || day * 1 > months[month * 1 - 1]) { return false; }
    var alldigits = this.year + this.month + this.day + this.controldigits;
    var nn = "";
    for (var n = 0; n < this.alldigits.length; n++) { nn += ((((n + 1) % 2) + 1) * alldigits.substring(n, n + 1)); }
    var checksum = 0;
    for (var n = 0; n < nn.length; n++) { checksum += nn.substring(n, n + 1) * 1; }
    valid = (this.checksum % 10 == 0) ? true : false;

    return valid;
}

$.validator.addMethod("ssn", function (value, element) {

    if (value == "") {
        return true;
    }

    // Remove dash
    value = value.replace("-", "");

    if (value.length == 12) {
        value = value.substr(2, 10);
    }

    var check = parseInt(value.substr(9, 1), 10);

    // Remove century and check number
    if (value.length == 10) {
        value = value.substr(0, 9);
    } else {
        return false;
    }

    var result = 0;

    // Calculate check number
    for (var i = 0; i < value.length; i++) {

        var tmp = parseInt(value.substr(i, 1), 10);

        if ((i % 2) == 0) {
            tmp = (tmp * 2);
        }

        if (tmp > 9) {
            result += (1 + (tmp % 10));
        } else {
            result += tmp;
        }
    }

    return (((check + result) % 10) == 0);
});

