﻿
// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc;
var gPopupIsShown = false;
var gWidth;
var gHeight;
var gTitleBarTitle;
var gTitleBarClass;
var gTitleBarDescription;
var gTitleBarCrumbInfo;
var gWaitForUnload = false;
var gDocLoaded = false;
var gBody = null;

var gHideSelects = false;
var loadingURL = '';


var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A", "BUTTON", "TEXTAREA", "INPUT", "IFRAME");

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
    document.onkeypress = keyDownHandler;
}



/**
* Initializes popup code on load.	
*/
function initPopUp() {
    // Add the HTML to the body
    gBody = $("body").get(0); // aBe edit - was getting #content
    popmask = document.createElement('div');
    popmask.id = 'popupMask';
    popcont = document.createElement('div');
    popcont.id = 'popupContainer';
    popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupControls">' +
					'<a class="ico_close" href="javascript:void closePopWin();">close</a>' +
				'</div>' +
				'<div id="popupTitle">Loading...</div>' +
			'</div>' +
			'<div>' +
			'<iframe src="' + serverVars.docRoot + 'scripts/plugins/loading.html" onload="popWinLoad();" style="height:100%;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
			'</div>' +
		'</div>';
    gBody.appendChild(popmask);
    gBody.appendChild(popcont);

    gPopupMask = document.getElementById("popupMask");
    gPopupContainer = document.getElementById("popupContainer");
    gPopFrame = document.getElementById("popupFrame");

    // check to see if this is IE version 6 or lower. hide select boxes if so
    // maybe they'll fix this in version 7?
    var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
    if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
        gHideSelects = true;
    }
    // Add onclick handlers to 'a' elements of class submodal or submodal-width-height
    var elms = document.getElementsByTagName('a');
    for (i = 0; i < elms.length; i++) {
        if (elms[i].className.indexOf("submodal") == 0) {
            // var onclick = 'function (){showPopWin(\''+elms[i].href+'\','+width+', '+height+', null);return false;};';
            // elms[i].onclick = eval(onclick);
            elms[i].onclick = function() {
                // default width and height
                var width = 400;
                var height = 200;
                // Parse out optional width and height from className
                params = this.className.split('-');
                if (params.length == 3) {
                    width = parseInt(params[1]);
                    height = parseInt(params[2]);
                }
                showPopWin(this.href, width, height, null); return false;
            }
        }
    }
}

function redrawPop() {
    if (!gPopupIsShown)
        return;
    var w = gWidth;
    var h = gHeight;
    var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);

    if (w > $(window).width() - 60)
        w = $(window).width() - 60;
    if (h > $(window).height() - 60 - titleBarHeight)
        h = $(window).height() - 60 - titleBarHeight;

    // calculate where to place the window on screen
    centerPopWin(w, h);


    gPopupContainer.style.width = w + "px";
    gPopupContainer.style.height = (h + titleBarHeight) + "px";
    // need to set the width of the iframe to the title bar width because of the dropshadow
    // some oddness was occuring and causing the frame to poke outside the border in IE6
    //gPopFrame.style.width = (parseInt(document.getElementById("popupTitleBar").offsetWidth, 10)-24) + "px";
    gPopFrame.style.height = (h) + "px";
}
function resizePopBy(width, height) {
    gWidth = gWidth + width;
    gHeight = gHeight + height;

    redrawPop();

}

/**
* @argument width - int in pixels
* @argument height - int in pixels
* @argument url - url to display
* @argument returnFunc - function to call when returning true from the window.
*/

function showPopWin(url, width, height, returnFunc, titleBarTitle, titleBarClass, titleBarDescription, titleBarCrumbInfo, waitForUnload) {
    if (gPopupMask == null)//sometimes called before init, wait for it.
    {
        setTimeout("showPopWin('" + url + "'," + width + "," + height + "," + returnFunc + ",'" + titleBarTitle + "','" + titleBarClass + "','" + titleBarDescription + "','" + titleBarCrumbInfo + "');", 100);
        return;
    }
    gPopupIsShown = true;
    disableTabIndexes();
    gPopupMask.style.display = "block";
    gPopupContainer.style.display = "block";
    $(gBody).css("overflow", "hidden").attr("scroll", "no");

    gTitleBarTitle = titleBarTitle;
    gTitleBarClass = titleBarClass;
    gTitleBarDescription = titleBarDescription;
    gTitleBarCrumbInfo = titleBarCrumbInfo;

    gWidth = 0;
    gHeight = 0;

    gWaitForUnload = waitForUnload;

    resizePopBy(width, height);
    
    
    // set the url
    gDocLoaded = false; // reset the popup
    gPopFrame.src = url;

    gReturnFunc = returnFunc;
    // for IE
    if (gHideSelects == true) {
        hideSelectBoxes();
    }

    window.setTimeout("setPopTitle();", 600);
}

//
var gi = 0;
function centerPopWin(width, height) {
    if (gPopupIsShown == true) {
        if (width == null || isNaN(width)) {
            width = gPopupContainer.offsetWidth;
        }
        if (height == null) {
            height = gPopupContainer.offsetHeight;
        }

        var fullHeight = $(window).height();
        var fullWidth = $(window).width();

        var scTop = parseInt($(window).scrollTop(), 10);
        var scLeft = parseInt($(window).scrollLeft(), 10);

        gPopupMask.style.top = scTop + "px";
        gPopupMask.style.left = scLeft + "px";
        gPopupMask.style.height = "100%";
        gPopupMask.style.width = "100%";
        if (window.navigator.userAgent.indexOf("MSIE") > -1) {
            gPopupMask.style.height = fullHeight + "px";
            gPopupMask.style.width = fullWidth + "px";
        }

        //window.status = gPopupMask.style.top + " " + gPopupMask.style.left + " " + gi++;

        var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);
        var topcentering = ((fullHeight - (height + titleBarHeight)) / 2) - 20;
        if (topcentering < 0)
            topcentering = 0;

        gPopupContainer.style.top = (scTop + topcentering + 10) + "px";
        gPopupContainer.style.left = (scLeft + ((fullWidth - width) / 2)) + "px";
        //alert(fullWidth + " " + width + " " + gPopupContainer.style.left);
    }
}
$(window).resize(redrawPop);
$(window).scroll(redrawPop);


// If we want to wait for the unload event to fire, then just listen to the load event.
// Instead of hiding the popup when they click the 'X', we will change the URL.  If the 
// user cancels the unload event, this load event will never fire and we will not actually
// hide the popup.  If they allow it to go through, this event will fire and we will force the
// popup to hide.
function popWinLoad() {
    if (gWaitForUnload && gDocLoaded) {
        // The frame has already changed - time to go away
        doHidePopWin(false);
    }
    gDocLoaded = true;
}

function closePopWin() {
    // Currently, safari and chrome do not behave when changing the URL on the iframe.  So, for now, we will just
    // confirm manually until the bug is fixed (specifically in Zoho)
    if (gWaitForUnload && ($.browser.safari)) {
        if (confirm("Any unsaved changes will be lost.\nDo you wish to continue?")) {
            hidePopWin(true);
        }
    }
    else {
        hidePopWin(true);
    }
}

/**
* @argument callReturnFunc - bool - determines if we call the return function specified
* @argument returnVal - anything - return value 
*/
function hidePopWin(callReturnFunc) {
    if (gWaitForUnload) {
        // Just change the src and wait until the load event fires, which means
        // that the window.onunload event from the iframe has passed
        gPopFrame.src = serverVars.docRoot + 'scripts/plugins/loading.html';

        if (callReturnFunc == true && gReturnFunc != null) {
            gReturnFunc(window.frames["popupFrame"].returnVal);
        }

    }
    else {
        doHidePopWin(callReturnFunc);
    }
}

function doHidePopWin(callReturnFunc) {

    gPopupIsShown = false;
    restoreTabIndexes();
    if (gPopupMask == null) {
        return;
    }
    gPopupMask.style.display = "none";
    gPopupContainer.style.display = "none";
    $(gBody).css("overflow", "auto").attr("scroll", "yes");

    if (callReturnFunc == true && gReturnFunc != null) {
        gReturnFunc(window.frames["popupFrame"].returnVal);
    }

    if (!gWaitForUnload) {
        gPopFrame.src = serverVars.docRoot + 'scripts/plugins/loading.html';
    }

    // display all select boxes
    if (gHideSelects == true) {
        displaySelectBoxes();
    }
}

/**
* Sets the popup title based on the title of the html document it contains.
* Uses a timeout to keep checking until the title is valid.
*/
var gTitleAlreadySet = null;
function setPopTitle(html) {
    var location = null;
    try {
        location = window.frames["popupFrame"].document.location.href;
    }
    catch (exc) { }
    if (html) {
        gTitleAlreadySet = location;
        //console.debug(gTitleAlreadySet,"html");
        document.getElementById("popupTitle").innerHTML = html;
    }
    else if (gTitleBarTitle != null && gTitleBarTitle.length > 0) {
    gTitleAlreadySet = location;
    //console.debug(gTitleAlreadySet, "gtitlebartitle");
        document.getElementById("popupTitle").innerHTML = '' +
		'<div class="' + gTitleBarClass + '">' +
		    gTitleBarTitle.replace("&apos;", "'") +
			'<div class="description">' +
				gTitleBarDescription.replace("&apos;", "'") +
			'</div>' +
			'<div class="crumbs">' +
				gTitleBarCrumbInfo.replace("&apos;", "'") +
			'</div>' +
		'</div>';

        redrawPop();
    }
    else if (gTitleAlreadySet != location) {
        try {
            if (window.frames["popupFrame"].document.title == null || window.frames["popupFrame"].document.title == "Loading") {
                document.getElementById("popupTitle").innerHTML = "Loading...";
                window.setTimeout("setPopTitle();", 100);
            } else {
                document.getElementById("popupTitle").innerHTML = window.frames["popupFrame"].document.title;
            }
        }
        catch (exc) { }
    }
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9) return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
    if (document.all) {
        var i = 0;
        for (var j = 0; j < gTabbableTags.length; j++) {
            var tagElements = document.getElementsByTagName(gTabbableTags[j]);
            for (var k = 0; k < tagElements.length; k++) {
                gTabIndexes[i] = tagElements[k].tabIndex;
                tagElements[k].tabIndex = "-1";
                i++;
            }
        }
    }
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
    if (document.all) {
        var i = 0;
        for (var j = 0; j < gTabbableTags.length; j++) {
            var tagElements = document.getElementsByTagName(gTabbableTags[j]);
            for (var k = 0; k < tagElements.length; k++) {
                tagElements[k].tabIndex = gTabIndexes[i];
                tagElements[k].tabEnabled = true;
                i++;
            }
        }
    }
}


/**
* Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*
* Thanks for the code Scott!
*/
function hideSelectBoxes() {
    for (var i = 0; i < document.forms.length; i++) {
        for (var e = 0; e < document.forms[i].length; e++) {
            if (document.forms[i].elements[e].tagName == "SELECT") {
                document.forms[i].elements[e].style.visibility = "hidden";
            }
        }
    }
}

/**
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function displaySelectBoxes() {
    for (var i = 0; i < document.forms.length; i++) {
        for (var e = 0; e < document.forms[i].length; e++) {
            if (document.forms[i].elements[e].tagName == "SELECT") {
                document.forms[i].elements[e].style.visibility = "visible";
            }
        }
    }
}
