
$(function () {

    $(window).load(function () {

        //force the descriptions to fill the available vertical space
        $("#MainMenu .Level2 > .Description").each(function () {
            $(this).height($(this).siblings("ul").outerHeight() - (parseInt($(this).css("padding-top")) + parseInt($(this).css("padding-bottom"))));
        });

        //force the extra column to fill the available vertical space
        var tmp_iColMainHeight = $(".ColumnCenter .ColumnMain").height();
        var tmp_iColExtraHeight = $(".ColumnCenter .ColumnExtra").height();
        if (tmp_iColMainHeight > tmp_iColExtraHeight) $(".ColumnCenter .ColumnExtra").height(tmp_iColMainHeight);

        //allow excess menuitems to have a submenu underneath
        var tmp_oExcessItems = $("#MainMenu .Level1>ul>li:gt(3)");
        tmp_oExcessItems.find(">.Level2").addClass("Compact").css("left", "auto").width(tmp_oExcessItems.width() || "auto").each(function () {
            $(".Description", this).css("width", "auto");
            $(">ul", this).css("marginLeft", "10px");
        });

        //add shading
        if ($.browser.msie && parseInt($.browser.version) < 7) return;
        if (typeof (m_bEditMode) == "undefined") {
            $("img[src*='TechniekTalent.gif']").parent().addClass("TechniekTalentBanner");
            $("img[src*='BureauTop.gif']").parent().addClass("BureauTopBanner");
            $("img[src*='PACTT.gif']").parent().addClass("PACTTBanner");
            $("img[src*='vacature.gif']").parent().addClass("VacatureBanner");
            $("img[src*='vacature2.gif']").parent().addClass("VacatureBanner2");
            $("img[src*='spiegelbeeld.gif']").parent().addClass("SpiegelbeeldBanner");
            $("img[src*='Kennisavondbanner.png']").parent().addClass("KennisavondBanner");
            $("img[src*='banner_OWB.gif']").parent().addClass("OWBBanner");

            $(".QRegioManagerPart .Groen, .QPopup, .QRegioManagerPart hr+a, .SubmitLink, .TechniekTalentBanner, .VacatureBanner, #QCP_COLUMN_RIGHT .QImagePanelPartOverlay").prepend("<div class='ShadeBottom'><div></div></div><div class='ShadeRight'><div></div></div><div class='ShadeBottomRight'></div>");
            $(".ShadeBottom").each(function () { $(this).width($(this).width() - 3) });
            $(".ShadeRight").each(function () { $(this).height($(this).height() - 3) });

            $("#QCP_COLUMN_RIGHT_EXTRA a img[src*='pijl.png']").addClass("Arrow");
        }

        //make sure the gezichtenboek divides into rows
        var tmp_oVisibleGroup = $(".QGezichtenboekPart>ul>li>div:visible");
        $(".QGezichtenboekPart>ul>li").each(function (index, element) {
            var tmp_oLink = $("<a>").attr("href", "#").click(function (link) {
                if ($("div:visible:eq(0)", element).length) return false;
                tmp_oVisibleGroup.slideToggle(1000);
                tmp_oVisibleGroup = $("div:eq(0)", element).slideToggle(1000);
                return false;
            }).text($("h1", element).text());
            $("h1", element).empty().append(tmp_oLink);
        });

        //Enable Cue texts in browsers that do not support Cue texts
        if (typeof (m_bEditMode) == "undefined") {
            if (!('placeholder' in document.createElement('input'))) {
                $("input[type='text'][placeholder]").each(function () {
                    var tmp_oInput = $(this);
                    tmp_oInput
                .before($("<span></span>")
                    .addClass("PlaceHolder")
                    .text(tmp_oInput.attr("placeholder"))
                    .css({
                        "font-family": tmp_oInput.css("font-family"),
                        "font-size": tmp_oInput.css("font-size"),
                        "height": tmp_oInput.outerHeight() + "px",
                        "width": tmp_oInput.outerWidth() + "px",
                        "line-height": tmp_oInput.height() + "px"
                    })
                    .click(function () { tmp_oInput.focus(); })
                    .hide()
                    )
                .focus(function () { if (!tmp_oInput.val() && tmp_oInput.prev().is(".PlaceHolder")) tmp_oInput.prev().hide(); })
                .blur(function () { if (!tmp_oInput.val() && tmp_oInput.prev().is(".PlaceHolder")) tmp_oInput.prev().show(); })
                .blur();
                });
            }
        }
    });

    $(".QExitMetingLogin .SubmitButton").each(function () {
        this.oldonclick = this.onclick;
        this.onclick = null;
    }).click(function () {
        var tmp_oInput = $(this).parents(".QExitMetingLogin:eq(0)").find("input[type=text]");
        if (!!$.trim(tmp_oInput.val()).length) window.open("http://www.exitmeting.nl/surveys/oom/?a=" + tmp_oInput.val());
        else setTimeout(this.oldonclick, 1);
    })

    $(".QRegiodeskBezwaarForm").each(function () {
        if (typeof (m_bEditMode) == "undefined") {
            var tmp_oToggleVisibility = function () {
                var tmp_bWerkgever = ($(".WerkgeverKeuze input:checked").val().toLowerCase() == "werkgever");
                $(tmp_bWerkgever ? ".WerknemerOnly" : ".WerkgeverOnly").hide();
                $(tmp_bWerkgever ? ".WerkgeverOnly" : ".WerknemerOnly").show();
            };
            $(".WerkgeverKeuze input").click(tmp_oToggleVisibility);
            tmp_oToggleVisibility();
        }
    });

    //add table captions based on the tabel title
    if (typeof (m_bEditMode) == "undefined") {
        $(".ContentPart table[title]").each(function () {
            $(this).prepend($("<caption>").append($("<span>").text($(this).attr("title"))));
        });
    }

    // remove css menu logic, and replace it with a jquery implementation
    $("#MainMenu .ShowChildren").removeClass("ShowChildren").hoverIntent(
        function () { $(this).css("background-position", "right 0px").find(">div").css({ "visibility": "visible" }); },
        function () { $(this).css("background-position", "right bottom").find(">div").css("visibility", "hidden"); }
    );

    //force the bounds of QImagePanelParts/QInterviewPreviewPart when its top or bottom aligned
    $(".QImagePanelPart:has(.Top,.Bottom) img, .QInterviewPreviewPart:has(.Top,.Bottom) img").load(function () {
        //determine the width because IE6/7 doesnt assume the correct width
        var tmp_oPanel = $(this).parent().find(".QImagePanelPartOverlay");
        var tmp_iWidth = parseInt($(tmp_oPanel).css("marginLeft")) + parseInt($(tmp_oPanel).css("marginRight")) + parseInt($(tmp_oPanel).css("paddingLeft")) + parseInt($(tmp_oPanel).css("paddingRight"));
        $(this).parent().width($(this).width()).height($(this).height()).find(".QImagePanelPartOverlay").width($(this).width() - tmp_iWidth)
    }).load();

    //make the font size of the path menu smaller the more distant the page
    $.each($("#PathMenu ul li a").get().reverse(), function (index) { $(this).css("font-size", parseInt($(this).css("font-size")) - index); });

    $(".GalleryImage")
        .load(function () {
            $(this).css("visibility", "visible").width("auto").height("auto");
            $(".GalleryFrame").width($(this).width());
            $(".GalleryLoading").hide();
            $(".GalleryDescription").show();
        });

    $(".GalleryNext, .GalleryImage").click(function () {
        var tmp_iIndex = $(".GalleryContainer").data("index") + 1;
        if (tmp_iIndex + 1 > $(".GalleryContainer").data("count")) tmp_iIndex = 0;
        showGalleryImage(tmp_iIndex);
        return false;
    })

    $(".GalleryPrevious").click(function () {
        var tmp_iIndex = $(".GalleryContainer").data("index") - 1;
        if (tmp_iIndex < 0) tmp_iIndex = $(".GalleryContainer").data("count") - 1;
        showGalleryImage(tmp_iIndex);
        return false;
    })

    $(".GalleryClose").click(function () {
        closeGallery();
    });

    $(window).resize(function () {
        $(".GalleryOverlay:visible").height($(document).height());
    }).resize();

    $(document).keyup(function (event) {
        if (event.keyCode == 27) {
            if ($(".GalleryFrame:visible").length)
                closeGallery();
        }
    });

    $(".SitemapPartRoot a[RID]").click(function (event) {

        $(".SitemapPartRoot a[RID]").removeClass("Highlight");
        $(this).addClass("Highlight");

        $(".SitemapPartTree>ul:visible").toggle();
        $(".SitemapPartTree ul[parentRID=" + $(this).attr("RID") + "]").each(function () {
            $(this).find("ul").andSelf().toggle();
        })

        return false;
    });



    if (window.name.indexOf("Type=CursusCatalogusWN") > -1) {
        $(".QCursusAanbodSelecteerButton").css("display", "block");
    } else if (window.name.indexOf("Type=CursusCatalogusWG") > -1) {
        $(".QCursusAanbodSelecteerLocatieSelect, .QCursusAanbodSelecteerLocatieButton").css("display", "block");
    } else if (window.name.indexOf("Type=OntwikkelCatalogus") > -1) {
        $(".QCursusAanbodSelecteerButton").css("display", "block");
    }

    $(".QCursusAanbodSelecteerLocatieButton, .QCursusAanbodSelecteerButton").click(function () {
        try {

            //check communications frame and the current cursus
            if (window.name.indexOf("://") < 0 || (!m_oCurrentCursus))
                return;

            if ($(this).hasClass("QCursusAanbodSelecteerLocatieButton")) {

                //add location
                m_oCurrentCursus.locatie = $(".QCursusAanbodSelecteerLocatieSelect").val();

                //require location
                if (m_oCurrentCursus.locatie == "") {
                    alert("Selecteer eerst een plaats.");
                    return;
                }
            }
            else { m_oCurrentCursus.locatie = ""; }

            //set result
            window.top.location.href = window.name + "&ClosePopup=True&" + $.param(m_oCurrentCursus);
            //window.location.href = window.name + "&ClosePopup=True&" + $.param(m_oCurrentCursus);

        } catch (e) { alert(e.message); }

    });

    //For every link that refers a popup, add an eventhandler
    $("a[href*='IFramePopup=true'], a[href*='TemplateIFrameDefault.aspx']").click(function (e) {
        showIFramePopup($(this).attr("href"));
        return false;
    });

    //If the Url contains "#Popup=", popup that url in an IFrame:
    var tmp_iPopupStartIndex = window.location.href.indexOf("#Popup=")
    var tmp_iPopupEndIndex = tmp_iPopupStartIndex + "#Popup=".length;
    if (tmp_iPopupStartIndex >= 0) {
        showIFramePopup(window.location.href.substring(tmp_iPopupEndIndex));
    }

    //add .ieTarget as a workaround for lack of :target support
    if ($.browser.msie) {
        $(window).bind("hashchange", function () {
            $(".ieTarget").removeClass("ieTarget");
            var tmp_sNewTarget = document.location.hash.replace("#", "");
            if (tmp_sNewTarget) $("#" + tmp_sNewTarget).addClass("ieTarget");
        }).trigger("hashchange");
    }
})

function hideIFramePopup() {
    $("#IFrameOverlay, #IFrameAndIE8ShadeContainer").css("display", "none");
}

function showIFramePopup(url) {

    if (!this.overlayInitialized) {
        $(document).keyup(function (e) { if (e.keyCode == 27) hideIFramePopup(); });
        this.overlayInitialized = true;
    }

    if (url.indexOf("IFramePopup=true") < 0) {
        url += ((url.indexOf("?") > 0) ? "&" : "?") + "IFramePopup=true";
    }

    $("#IFrameContainer iframe").attr("src", url);
    $("#IFrameOverlay, #IFrameAndIE8ShadeContainer").css("display", "block");
}

function setIFrameHeight(height) {
    var tmp_iHeight = $("#IFrameAndIE8ShadeContainer").height();
    //If it shrinks, scroll back to top.
    if (height < tmp_iHeight) {
        $(window).scrollTop(0);
    }
    if (tmp_iHeight != height) {
        $("#IFrameAndIE8ShadeContainer").height(height);
    }
}

function closeGallery() {
    $(".GalleryContainer").hide();
    $(".GalleryOverlay").fadeOut("normal");
}

function hideGalleryImage() {
    //hide the image
    $(".GalleryImage").attr("src", "").css("visibility", "hidden");
    
    //hide the description
    $(".GalleryDescription").hide();
    
    //show the loading indicator
    $(".GalleryLoading").show();
}

function openGallery(sender) {
    var tmp_oGallery = $(sender).parent(".GalleryPart");

    $(".GalleryOverlay").height($(document).height());
    $(".GalleryOverlay").fadeIn("normal");
    
    hideGalleryImage();

    $(".GalleryFrame").width("auto");
    $(".GalleryImage").width(300).height(200);
    
    //show the gallery
    $(".GalleryContainer").show();

    //store gallery information
    $(".GalleryContainer")
        .data("count", parseInt(tmp_oGallery.attr("imagecount")))
        .data("source", tmp_oGallery);

    //show the first image
    showGalleryImage(0);
    
    return false;
}

function showGalleryImage(index) {

    hideGalleryImage();

    var tmp_oGallery  = $(".GalleryContainer").data("index", index).data("source");
    $(".GalleryImage").attr("src", tmp_oGallery.attr("image" + index));
    $(".GalleryDescription").hide().text(
        (index + 1 + "/" + $(".GalleryContainer").data("count")) + 
        (tmp_oGallery.attr("imagedescription" + index) ? ": " + tmp_oGallery.attr("imagedescription" + index) : "")
        );
}
