/*
     $Revision$
     $Id$

     File:          fac_widget_page.js
     Description:   Shared clientside functions for fac_show_widget_page.asp & fac_edit_widget_page.asp
*/

function resize_raw(frm)
{
    var doc = frm.contentDocument;
    var old_h = frm.height;
    frm.height = 0;
    var new_h = $(frm).closest("[data-widget-type='RAW']").attr("data-height") || 0;
    if (!new_h)
    {
        if (doc.body)
            new_h = Math.max(new_h, doc.body.scrollHeight, doc.body.offsetHeight);
        if (doc.html)
            new_h = Math.max(new_h, doc.html.clientHeight, doc.html.scrollHeight, doc.html.offsetHeight);
    }
    frm.height = new_h;
    if (old_h)
        frm.height = old_h;
    else
        frm.height = new_h > 150 ? new_h + "px" : "";

    frm.style.maxHeight = new_h + "px";
}

function resize_flr(img, x, y)
{
    var new_src;
    if (img.hasAttribute("thesrc"))
    {
        new_src = $(img).attr("thesrc");
        img.removeAttribute("thesrc");
    }
    else
        new_src = img.src;

    if (!x)
        x = parseInt($(img).closest(".widget-type-flr").width(), 10);

    if (x && x > 0)
    {
        if (new_src.indexOf("sizeX=") > -1)
            new_src = new_src.replace(/sizeX=\d+/, "sizeX=" + x);
        else if (new_src.indexOf("?") > -1)
            new_src = new_src + "&sizeX=" + x;
        else
            new_src = new_src + "?sizeX=" + x;
    }
    else if (x && x === -1)
    {
        if (new_src.indexOf("sizeX=") > -1)
            new_src = new_src.replace(/sizeX=\d+&?/, "sizeX=800");
    }

    if (y && y === -1)
    {
        img.height = 1;
        y = parseInt($(img).closest(".widget-type-flr").height(), 10);
        img.removeAttribute("height");
    }

    if (y && y > 0)
    {
        if (y <= 1) y = 800;
        if (new_src.indexOf("sizeY=") > -1)
            new_src = new_src.replace(/sizeY=\d+/, "sizeY=" + y);
        else if (new_src.indexOf("?") > -1)
            new_src = new_src + "&sizeY=" + y;
        else
            new_src = new_src + "?sizeY=" + y;
    }

    if (img.src != new_src)
        img.src = new_src;
}

function resizeOnActivate()
{
    $("[data-widget-type]").each(function () {
        var $widget_col = $(this).find("[class*=widget-type-]");
        switch ($(this).attr("data-widget-type")) {
            case "FLR":
                var x = parseInt($widget_col.width(), 10);
                var y = $(this).attr("data-height") || 800;
                resize_flr($widget_col.find("img")[0], x, y);
                break;
            case "RAW":
                resize_raw($widget_col.find("iframe")[0]);
                break;
            case "IMG":
                break;
            default:
                var $frm = $widget_col.find("iframe");
                if ($frm.length && FcltMgr._frmaccessible($frm[0].contentWindow) && $frm[0].contentWindow.FcltMgr)
                {
                    var doc = $frm[0].contentWindow.document;
                    if (doc && doc.body && doc.body.id === "searchbody")
                    {
                        var workFrame = $(doc.body).find("iframe#workFrame").get(0);
                        if (workFrame && FcltMgr._frmaccessible(workFrame.contentWindow) && workFrame.contentWindow.FcltMgr)
                            workFrame.contentWindow.FcltMgr.resized();
                    }
                    $frm[0].contentWindow.FcltMgr.resized();
                }
                break;
        }
    });

    // Kijkt of er ruimte is voor de tooltip en resized de (+) in edit mode indien nodig
    $(".widget-container").each(function () { checkRowClearance($(this)); });
}

// FSN#22791 refresh als we in een inactief tab zitten is overbodig
//           en (jqPlot) geeft errors
var pendingReload = [];
function fcltontabshow()
{
    var t;
    for (t in pendingReload)
        pendingReload[t]();
    pendingReload = [];

    $("iframe").each(function ()
    {
        if (this.hasAttribute("data-autorefresh"))
        {
            if (this.hasAttribute("srcdoc"))
                this.srcdoc = this.srcdoc;
            else
                this.src = this.src ;
        }
    });
}

function doReload(pId, pType, pTime)
{

    if (FcltMgr.inInvisibleTab())
        pendingReload.push(function () { doReload(pId, pType, pTime); });
    else
    {
        var id = "";
        switch (pType)
        {
            case "FAC":
            case "URL":
            case "NWS":
            case "RAP":
            case "RAW":
            case "FAQ":
                id = "frame_" + pId;
                break;
            case "IMG":
            case "FLR":
                id = "img_" + pId;
                break;
            case "MK":
            case "MI":
                return false; // geen refresh
            default:
                console.error("Refresher; unknown widget-type (" + pType + ")");
        }
        if (pType == "RAW")
            document.getElementById(id).srcdoc = document.getElementById(id).srcdoc;
        else
            document.getElementById(id).src = document.getElementById(id).src;
        setReloadTimer(pId, pType, pTime);
    }
};

function setReloadTimer(pId, pType, pTime)
{
    if ($('li[fcltclick^=doSubmit]', $("iframe:first").contents()).length > 0)
    {
        setTimeout('reloadFrameSelections("'+pId+'", "'+pType+'", '+pTime+');', pTime*1000);
    }
    else
    {
        setTimeout('doReload("'+pId+'", "'+pType+'", '+pTime+');', pTime*1000);
    }
}

function reloadFrameSelections(pId, pType, pTime)
{
    $('li[fcltclick^=doSubmit]', $("iframe:first").contents()).click();
    setReloadTimer(pId, pType, pTime);
}

// Start frame selections
function startFrameSelections(initializing)
{
    var $iframe_first = $("iframe:first").contents();
    var $searchblock = $("table[id^=searchblock] input:visible, table[id^=searchblock] select:visible", $iframe_first);
    $("iframe:not(:first)").each(
            function(i, frame_elem)
            {
                var $frame_searchblock = $("table[id^=searchblock]", $(frame_elem).contents());
                $searchblock.each(
                    function(i, field_elem)
                    {
                        let $fld = $(field_elem).hasClass("flddate") ? $("#" + ($(field_elem).attr("id") || "").replace(/^show_/, ""), $iframe_first) // clone het veld met de echte waarde
                                                                     : $(field_elem);
                        $("#" + $fld.attr("id"), $frame_searchblock).remove();                          // remove old searchfield
                        $("table[id^=searchblock]", $(frame_elem).contents()).append($fld.clone(true)); // put searchfield in frame
                        $("#" + $fld.attr("id"), $frame_searchblock).val($fld.val());          // transfer search values to frame
                    }
                );
                if (initializing === false) {
                    $('li[fcltclick^=doSubmit]', $(frame_elem).contents()).click();
                }
            }
    );
}

function hideSearchDiv() {
   $("nav.search-page-header", $(this).contents()).next("div.container-fluid").addBack().hide();
}

var widgetPageResolve;
var widgetPageLoading = new Promise(resolve => {
    widgetPageResolve = resolve;
});

// Pas als alle iframe (en plaatjes evt.) geladen zijn;
$(window).on("load", function ()
{
    if ($("iframe").length && FcltMgr._frmaccessible($("iframe:first")[0].contentWindow) &&
        ($("iframe:first").attr("src") || "").indexOf("fac_report.asp") > -1 && $("iframe:first").contents().find("nav.search-page-header").length)
    {
        $("iframe:not(:first)").each(hideSearchDiv);
        $("li[fcltclick^=doSubmit]", $("iframe:first").contents()).off().on("click", startFrameSelections.bind(null, false));
        startFrameSelections(true); // Neem alvast default waardes over zodat autosearch deze ook gelijk goed oppikt
    }
    widgetPageResolve();
});

$(function () {
    if (!Modernizr.srcdoc) {
        $(".widget-type-raw > iframe").each(function () {
            var doc = this.contentDocument;
            doc.open();
            doc.write($(this).attr("srcdoc"));
            doc.close();
        });
    }

    $(".widget-type-flr").each(function () {
        var x = parseInt($(this).width(), 10);
        var y = $(this).closest("[data-widget-type='FLR']").attr("data-height") || 800;
        resize_flr($(this).find("img")[0], x, y);
    });
})