﻿//requests a page and calls responsePage() automatically when recieved response, giving over the containerId and the followupFunction
//parameters: QueryString-ParameterString
//followupFunction: the function called, after the content has been set in responsePage
function requestPage(url, parameters, containerId, followupFunction) {
    lastRequestedUrl = url;
    if (lastRequestedUrl.indexOf("?") > -1)
        lastRequestedUrl = lastRequestedUrl.substr(0, lastRequestedUrl.indexOf("?"));
   
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/html');
         }
     } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
           try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
     }
     if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
     }
     http_request.onreadystatechange = function() {
        responsePage(containerId, followupFunction);
     }
     http_request.open('GET', url + parameters, true);
     http_request.send(null);
}

//will be called from requestPage, you may call it after requesting a page
//the function will wait for the response to come. content of the requested page will be set into container with containerId.
//will be called from requestPage
function responsePage(containerId, followupFunction) {
    responseContainer = document.getElementById(containerId);
    if (responseContainer != null) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                var text = http_request.responseText;



                //we need to remove the form around the content (if not, IE is not happy)
                var firstIndex = text.indexOf("<form");
                if (firstIndex > -1) {
                    firstIndex += text.substr(firstIndex).indexOf(">") + 1;
                    var lastIndex = text.indexOf("</form>") - 1;
                    text = text.substr(firstIndex, lastIndex - firstIndex);
                }
                responseContainer.innerHTML = text;
                var inlineScript = null;
                if (text.match("<\s*script.*?>(.*?)<\/\s*?script[^>\w]*?>") != null)
                    inlineScript = text.match("<\s*script.*?>(.*?)<\/\s*?script[^>\w]*?>")[1];
                eval(inlineScript);
                if (followupFunction)
                    followupFunction();
            }
        }
    }
}

var hinderPopup = false;
var openDivRequested = false;
var divFixed = false;
var divClickFixed = false;

//prevent a time-delayed div popup; usually called from onmouseout, after requesting time-delayed div popup on mouseover
function preventPopup() {
    hinderPopup = true;
}

//removes the div currently open and also purges it for IE
function removeDivPopup() {
    if (currentOpenId)
        removeDivPopup(currentOpenId);
}

//removes a div popup and also purges it for IE (there are heavy problems with IE, if more time look at this function to improve)
function removeDivPopup(containerId) {
    openDivRequested = false;
    var container = document.getElementById(containerId);
    try {
        if (container) {
            //this should not be used (is because of IE not able to remove the container, and I don't know why)
            container.style.visibility = "hidden";

            purge(container);
            //here IE always breaks up (and apparently there is no reason for that??)
            document.forms[0].removeChild(container);
        }
    }
    catch (ex) {
        //alert(ex.toString());
    }
}


//those are just calls of the function openDivPopup, so that in markup the call is much shorter:
//Ecommerce (kgv)
function openDivPopupShop(url, e, useDelay) {
    if (useDelay) {
        openDivPopup(url, "", "ShopDetailDiv", "ShopDetailInnerDiv", "ShopDetailCloseButton", "[x]", true, e, -150, -200, 400, true);
    }
    else {
        openDivPopup(url, "", "ShopDetailDiv", "ShopDetailInnerDiv", "ShopDetailCloseButton", "[x]", true, e, -150, -200);
    }
}
//Organigramm (kgv)
function openDivPopupOrganigramm(userId, culture, e) {
    openDivPopupSpecific("OrganigrammDetailDiv", "/Bytix/WebParts/Company/Organigramm_files/UserDetail.aspx", "?Id=" + userId.toString() + "&culture=" + culture, "OrganigrammDetailDiv", "OrganigrammDetailInnerDiv", "OrganigrammDetailCloseButton", "", true, e, -50, 50, null, false);
}
function removeDivPopupOrganigramm() {
    removeDivPopup("OrganigrammDetailDiv");
}

//DataPool (kgv)
function openDivPopupDataPoolPermission(dataPoolID, userID, e) {
    openDivPopup("/CMSWebParts/KgvWebParts/DataPoolControls/DataPoolPermissionOverview.aspx?DataPoolID=" + dataPoolID.toString() + "&UserID=" + userID.toString(), "", "DataPoolDetailDiv", "DataPoolDetailInnerDiv", "DataPoolDetailCloseButton", "[x]", true, e, 100, 100, null, false);
}

// Return Confirm of Deletion of Text
function confirmDeleteDataPool(message, url) {
    var answer = confirm(message);
    if (answer) {
        window.location = url;
    }
}

var currentOpenId = null;

function openDivPopup(url, parameters, containerClass, innerContainerClass, closeButtonClass, closeButtonText, useEventPosition, e, offsetTop, offsetLeft, delayMilliSeconds, closeOnMouseOut) {
    var containerID = Math.random().toString().replace(".", "");
    openDivPopupSpecific(containerID, url, parameters, containerClass, innerContainerClass, closeButtonClass, closeButtonText, useEventPosition, e, offsetTop, offsetLeft, delayMilliSeconds, closeOnMouseOut);
    currentOpenId = containerID;
}

//opens a page (url) in a container div with a close button to close it
//(useEventPosition and e are optional and used if you want to display the popup on cursor position, use offsetTop and offsetLeft for correction of the postition)
//(delayMilliSeconds is optional and used to delay the openDivPopup (usually used with onmouseover))
//(closeOnMouseOut is optional and used to determin, whether the container should be removed on mouse-out event or not)
function openDivPopupSpecific(containerID, url, parameters, containerClass, innerContainerClass, closeButtonClass, closeButtonText, useEventPosition, e, offsetTop, offsetLeft, delayMilliSeconds, closeOnMouseOut) {
    if (openDivRequested) {
        return;
    }
    var container = document.createElement("div");
    container.setAttribute("id", containerID);
    //container.setAttribute("class", containerClass);
    container.className = containerClass;
    if (closeOnMouseOut) {
        container.onmousemover = function() {
            divFixed = true;
        }
        container.onmouseover = function() {
            divFixed = true;
        }
        container.onmouseout = function() {
            divFixed = false;
            setTimeout(function() {
                if (!divFixed && !divClickFixed) {
                    removeDivPopup(containerID);
                }
            }, 500);
        };
        container.onclick = function() {
            divClickFixed = true;
        };
    }
    
    var innerContainerID = Math.random().toString().replace(".", "");
    while (innerContainerID == containerID)
        innerContainerID = Math.random().toString().replace(".", "");
    var innerContainer = document.createElement("div");
    //innerContainer.setAttribute("class", innerContainerClass);
    innerContainer.className = innerContainerClass;
    innerContainer.setAttribute("id", innerContainerID);
    container.appendChild(innerContainer);
    
    var closeButton = document.createElement("a");
    //closeButton.setAttribute("class", closeButtonClass);
    closeButton.className = closeButtonClass;
    closeButton.innerHTML = closeButtonText;
    closeButton.onclick = function() {
        removeDivPopup(containerID);
    };
    container.appendChild(closeButton);

    if (useEventPosition) {
        var cursor = { x: 0, y: 0 };
        cursor = getPosition(e);
        var x = cursor.x;
        
        if (offsetLeft)
            x += offsetLeft;
        var y = cursor.y;
        if (offsetTop)
            y += offsetTop;
        if (x < 0)
            x = 0;
        if (y < 0)
            y = 0; 
        container.style.left = x.toString() + "px";
        container.style.top = y.toString() + "px";
    }

    if (delayMilliSeconds) {
        hinderPopup = false;
        divClickFixed = false;
        setTimeout(function() {
            openDivPopupDelayed(container, url, parameters, innerContainerID)
        }, delayMilliSeconds);
    }
    else {
        document.forms[0].appendChild(container);
        requestPage(url, parameters, innerContainerID, null);
        openDivRequested = true;
    }
}

//this method is intended to be used by openDivPopup() when delay has been activated
function openDivPopupDelayed(container, url, parameters, innerContainerID) {
    if (!hinderPopup) {
        document.forms[0].appendChild(container);
        requestPage(url, parameters, innerContainerID, null);
        openDivRequested = true;
    }
}

//gets the cursor-position of an event (e)
function getPosition(e) {
    e = e || window.event;
    var cursor = { x: 0, y: 0 };
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX +
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY +
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

//completely removes an element from the browser cache
//should be used whenever adding elements programmatically (only IE needs that)
//always call this method BEFORE you remove the element from the form
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
