﻿/* Created 2009-01-29 by Jonas Johansson, Capitex AB
Version: 2.0

För att denna ska fungera så måste följande uppfyllas:
- Sidan som innehåller den Iframe som ska vara dynamisk MÅSTE vara i TOP fönstret.
- De obligatoriska parametrarna måste anges (se nedan).
- Samtliga sidor (innehållssidan måste ha en giltig referens till DynamicIFrame.js)

Obligatoriska parametrar som anges i URL:en (CASE SENSITIVE!!!)
iframeurl: URL:en till resizeIframe.htm som ska ligga på samma domän som den sidan som har iframen som ska resizas.
iframeId: ID på Iframen som ska vara dynamisk.


Anropa enligt följande:
var o = new DynamicIframe();
o.Debug = true;
o.ResizeHeight = true;
o.MaxHeight = 1000;
o.Resize();

/--------------- OBSOLETE!!! -----------------------------/
Funktionen SetIFrameSize köras på sidan som är innehållet.
SetIFrameSize(bResizeHeight, bResizeWidth, debug);
Möjliga värden för debug är:
'true', 'remote', 'local'

Ex:
- För vanlig postback: SetIFrameSize(true, false);
- För AJAX ASP.NET: ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "DynamicIFrame", "SetIFrameSize(true, false);", True)

Ex:
Denna Iframe ligger i en sida på domänen www.newsec.se och anropar en lista som ligger på newsecv2.capitex.se.
resizeIframe.htm ligger på samma domän (iframeurl=http://www.newsec.se/resizeIframe.htm) som sidan.
<iframe id="ctl00_MainBodyOuter_MainBody_MainBodyRegion_capitexIframe" width="684" scrolling="no" src="http://newsecv2.capitex.se/Lista.aspx?t=CMBoLgh&amp;iframeId=ctl00_MainBodyOuter_MainBody_MainBodyRegion_capitexIframe&amp;iframeurl=http://www.newsec.se/resizeIframe.htm"></iframe>

Lista.aspx kör:
ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "DynamicIFrame", "SetIFrameSize(true, false);", True)
/--------------- SLUT OBSOLETE!!! -----------------------------/

En array för att hålla koll på alla dynamicIframes objekten */
var dynamicIframeGlobalObjectsArray = new Array();
function InitDynamicIframeFromGlobalObjects(globalIndex) {
    if (globalIndex > -1 && dynamicIframeGlobalObjectsArray[globalIndex] != null)
        return dynamicIframeGlobalObjectsArray[globalIndex];

    return null;
}

function DynamicIframe() {
    /* <Publika properties> */
    this.Debug = false; //Object (true, false, 'local', 'remote')
    this.ResizeHeight = true; //Boolean
    this.ResizeWidth = true; //Boolean
    this.MinHeight = null; //Int
    this.MaxHeight = null; //Int
    this.MinWidth = null; //Int
    this.MaxWidth = null; //Int
    /* </Publika properties> */

    /* <Privata variabler> */
    this._dynamicIframeGlobalObjectsArrayIndex = -1;
    this._iframeId = null;
    this._iframeurl = null;
    this._scriptPath = null;

    this._lastHeight = -1;
    this._lastWidth = -1;
    this._timesChecked = 0;
    /* </Privata variabler> */


    /* <Publika funktioner> */
    this.GetIframeurl = function() {
        if (this._iframeurl == null)
            return getParameter('iframeurl');
        return this._iframeurl;
    };

    this.GetIframeId = function() {
        if (this._iframeId == null)
            this._iframeId = getParameter('iframeId');
        return this._iframeId;
    };

    this.GetScriptPath = function() {
        if (this._scriptPath == null) {
            var scriptTags = document.getElementsByTagName("script");
            for (var i = 0; i < scriptTags.length; i++) {
                var src = scriptTags[i].getAttribute('src');

                if (src != null && src.toLowerCase().indexOf("dynamiciframe.js") > -1) {

                    var protocol = document.location.protocol;
                    var host = document.location.host;
                    var path = document.location.pathname;

                    var srcEndsWithSlash = src.charAt(0) == "/" || src.charAt(0) == "\\";

                    if (path.length > 0) {
                        var endIndex = path.lastIndexOf("\\");
                        var endIndexSlash = path.lastIndexOf("/");

                        if (endIndex > -1 && endIndex > endIndexSlash) {
                            if (!srcEndsWithSlash)
                                endIndex += 1;

                            path = path.substring(0, endIndex);
                        }
                        else if (endIndexSlash > -1) {
                            if (!srcEndsWithSlash)
                                endIndexSlash += 1;

                            path = path.substring(0, endIndexSlash);
                        }
                    }

                    if (src.charAt(0) == "/" || src.charAt(0) == "\\") {
                        this._scriptPath = protocol + "//" + host + src;
                    }
                    else {
                        this._scriptPath = protocol + "//" + host + path + src;
                    }


                    i = scriptTags.length;
                }
            }
        }

        return this._scriptPath;
    };

    this.Resize = function() {
        if (window.parent != window) {
            if (this._dynamicIframeGlobalObjectsArrayIndex < 0)
                this._dynamicIframeGlobalObjectsArrayIndex = dynamicIframeGlobalObjectsArray.push(this) - 1;

            if (this.Debug == null)
                this.Debug = getParameter("debug");

            if (this._dynamicIframeGlobalObjectsArrayIndex >= 0) {
                if (this.GetIframeurl() == null)
                    alert('The parameter "iframeurl" is missing och incorrect. It\'s case sensitive!');

                if (this.GetIframeId() == null)
                    alert('The parameter "iframeId" is missing och incorrect. It\'s case sensitive!');

                if (this.GetScriptPath() == null)
                    alert('Unable to extract script');

                window.setTimeout("InternalSetIFrameSize(" + this._dynamicIframeGlobalObjectsArrayIndex + ")", 10);
            }
        }
        else
            this._showDebugMessage('local', 'The page is not in an iframe!');
    };
    /* </Publika funktioner> */

    /* <Privata funktioner> */
    this._showDebugMessage = function(debugLevel, msg) { //Visar debugmeddelanden
        if (this.Debug != null && this.Debug != false) {
            if (this.Debug == true) {
                alert(msg);
            }
            else if (this.Debug.toString().toLowerCase() == debugLevel.toLowerCase()) {
                alert(msg);
            }
        }
    }

    this._CallResizeIframe = function() { //Hämtar documenthöjd och skapar url för att anropa resizeIframe.htm som ligger på huvudsidan.
        var path = this.GetIframeurl();
        var iframeId = this.GetIframeId();

        if (path != "" && iframeId != "") {
            var height = Math.max(document.body.offsetHeight, document.body.scrollHeight);
            var width = Math.max(document.body.offsetWidth, document.body.scrollWidth);

            if ((this.ResizeHeight && height != this._lastHeight) || (this.ResizeWidth && width != this._lastWidth)) {

                this._showDebugMessage('local', "LOCAL DEBUGGING:\nHeight: " + height + "\nWidth: " + width);

                var iframe = document.getElementById('DynamicIframeResizer');
                if (iframe == null) {
                    iframe = document.createElement("iframe");
                    iframe.id = "DynamicIframeResizer";
                    iframe.style.visibility = 'hidden';
                    iframe.style.position = 'absolute';
                    iframe.style.width = '1px';
                    iframe.style.height = '1px';
                    iframe.style.top = '0px';
                    iframe.style.left = '0px';
                    document.body.appendChild(iframe);
                }

                var url = unescape(path) + '?iframeId=' + iframeId;
                if (this.ResizeWidth) {
                    var w = width;
                    if (this.MinWidth != null && w < this.MinWidth) {
                        w = this.MinWidth;
                        this._showDebugMessage('local', "LOCAL DEBUGGING:\nChanging width from: " + width + " to: " + w + " (MinWidth reached).");
                    }

                    if (this.MaxWidth != null && w > this.MaxWidth) {
                        w = this.MaxWidth;
                        this._showDebugMessage('local', "LOCAL DEBUGGING:\nChanging width from: " + width + " to: " + w + " (MaxWidth reached).");
                    }

                    url += '&width=' + w;
                }

                if (this.ResizeHeight) {
                    var h = height;
                    if (this.MinHeight != null && h < this.MinHeight) {
                        h = this.MinHeight;
                        this._showDebugMessage('local', "LOCAL DEBUGGING:\nChanging height from: " + height + " to: " + h + " (MinHeight reached).");
                    }

                    if (this.MaxHeight != null && h > this.MaxHeight) {
                        h = this.MaxHeight;
                        this._showDebugMessage('local', "LOCAL DEBUGGING:\nChanging height from: " + height + " to: " + h + " (MaxHeight reached).");
                    }

                    url += '&height=' + h;
                }

                url += "&script=" + this.GetScriptPath();

                if (this.Debug)
                    url += "&debug=" + this.Debug;

                this._showDebugMessage('local', "LOCAL DEBUGGING:\niframeURL: " + url);

                iframe.src = url;

                this._lastHeight = height;
                this._lastWidth = width;
            }

            if (this._timesChecked++ < 10)
                window.setTimeout("InternalSetIFrameSize(" + this._dynamicIframeGlobalObjectsArrayIndex + ")", 500);
        }
    }
    /* </Privata funktioner> */
}

//<----------- OBSOLETE --------------> Använd objektet istället.
function SetIFrameSize(bResizeHeight, bResizeWidth, debug) {
    var o = new DynamicIframe();
    o.ResizeHeight = bResizeHeight;
    o.ResizeWidth = bResizeWidth;
    o.Debug = debug;
    o.Resize();
}
//</----------- OBSOLETE -------------->

/* <Funktioner som används på local-sidan> */
function InternalSetIFrameSize(globalIndex) {
    var obj = new DynamicIframe();
    obj = InitDynamicIframeFromGlobalObjects(globalIndex);
    obj._CallResizeIframe();
}

function getParameter(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
/* </Funktioner som används på local-sidan> */

/* <Funktioner som används på remote-sidan> */
function ResizeIFrame(iframeId, height, width) {
    if (iframeId != null) {
        var iframe = document.getElementById(iframeId);
        if (iframe != null) {
            if (height != null && height != "")
                iframe.setAttribute("height", height + 'px');

            if (width != null && width != "")
                iframe.setAttribute("width", width + 'px');
        }
    }
}

function CallTopResizeIFrame() {
    var iframeId = getParameter("iframeId");
    var height = getParameter("height");
    var width = getParameter("width");
    var debug = getParameter("debug");

    if (iframeId != null) {
        try {
            var iframe = window.top.document.getElementById(iframeId);
            if (iframe != null) {
                var browser = navigator.appName;
                var frameBorder = iframe.getAttribute("frameborder");
                if (browser == "Microsoft Internet Explorer" && (frameBorder == "1" || frameBorder == "" || frameBorder == null)) {
                    if (height != "")
                        height = parseInt(height) + 4;
                    if (width != "")
                        width = parseInt(width) + 4;
                }

                if (debug == "true" || debug == "remote")
                    alert('REMOTE DEBUGGING:\nCurrent:\n   Height: ' + iframe.offsetHeight + '\n   Width: ' + iframe.offsetWidth + '\n   Frameborder: ' + frameBorder + ' \n\nNew:\n   Height: ' + height + "\n" + '   Width: ' + width);

                if (height != null && height != "") {
                    iframe.setAttribute("height", height + 'px');
                    iframe.style.height = height + 'px';
                }

                if (width != null && width != "") {
                    iframe.setAttribute("width", width + 'px');
                    iframe.style.width = width + 'px';
                }
            }
            else {
                if (debug == "true" || debug == "remote")
                    alert('REMOTE DEBUGGING: Unable to find iframe with Id: ' + iframeId);
            }
        }
        catch (e) {
            if (debug == "true" || debug == "remote")
                alert('REMOTE DEBUGGING: Error:\n' + e.description);
        }
    }
    else {
        if (debug == "true" || debug == "remote")
            alert('iframeId is missing!');
    }
}
/* </Funktioner som används på remote-sidan> */


