/*******************************************************************************
date   refnum    version who description
081015 c26877    9.ajax  jdk uwindow should be created without ID
date   refnum    version who description
*******************************************************************************/
/*global UNIFACE document window */
/*global uwindow*/
/*global navigator*/
var uwindow=(function() {

// Background opacity
var OVERLAY_OPACITY = 70;

// Multiple message windows:
var MW_SETSIZE = 10;    // This many windows per diagonal row
var MW_GAP = 25;        // Gap between consecutive windows (in the same row)
var MW_OFFSET = 5;      // Additional vertical offset between rows

// Multi-line related constants:
var MAX_LINES = 8;      // More lines will result in a scroll bar.
var PIX_PER_LINE = 16;

// constants
var CLS_WINDOW = "uwindow";
var CONTENT_HTML = "html";
var CONTENT_IFRAME = "iframe";


var windowBackground;
var windowContainer;

function createNode(tagName, className, parentNode) {
    var node = document.createElement(tagName);
    if (className != null) {   // @pragma(allow-loose-compare)
        node.className = className;
    }
    if (parentNode != null) {  // @pragma(allow-loose-compare)
        parentNode.appendChild(node);
    }
    return node;
}

function findUfrmFromInnerNode(node) {
    while (node.tagName.toLowerCase() !== "div" || node.className !== "uwindow") {
        node = node.parentNode;
    }
    return node;
}

function appendTextNodes(parentNode, text) {
    var l_lines = text.split("\n");
    if (l_lines.length > 0) {
        parentNode.appendChild(document.createTextNode(l_lines[0]));
    }
    for (var i = 1; i < l_lines.length; i++) {
        parentNode.appendChild(document.createElement("br")); // preserve line breaks
        if (l_lines[i]) {
            parentNode.appendChild(document.createTextNode(l_lines[i]));
        }
    }
    return l_lines.length;
}

return {
createWindow:function(titlebarText,statusLineString) {
    var i;
    var ufrm = createNode("div", "uwindow");    // form window div
    var titlebar = createNode("div", "utitlebar", ufrm);
    titlebar.appendChild(document.createTextNode(titlebarText));
    var wincontrols = createNode("div", "wincontrols", titlebar);
    var closeButton = createNode("img", null, wincontrols);
    closeButton.src = "../common/images/uwindow/close.jpg";
    closeButton.title = "Close";
    closeButton.onclick = uwindow.closeWindow;
    var clientwindow = createNode("div", "clientwindow", ufrm);
    if (statusLineString !== "") {
        var statusline = createNode("div", "statusline", ufrm);
        statusline.appendChild(document.createTextNode(statusLineString)); 
    }
    ufrm.clientwindow = clientwindow;
    ufrm.utitlebar = titlebar;

    ufrm.utitlebar.onmousedown=uwindow.wmbuttondown;
    ufrm.utitlebar.hparent=ufrm; // save handle to parent 
    ufrm.style.position = "fixed";
    ufrm.style.zIndex = 1;
    
    ufrm.windowToFront = function() {
        var container = this.parentNode;
        if (container != null) { // @pragma(allow-loose-compare)
            container.removeChild(this);
            container.appendChild(this);
        }
    };
    ufrm.buttonFocus = function () {
        var inputs = this.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i = i+1) {
            if (inputs[i].name == "defaultButton") {
                inputs[i].focus();
                break;
            }
        }
    };
    ufrm.takeFocus = function() {
        this.windowToFront();
        this.buttonFocus();
    };
    ufrm.onclick = function(event) {
        // We do not want ufrm to take focus if it contains an iframe,
        // because that hides the iframe (in windowToFront)...
        if (this.clientwindow.contenttype != CONTENT_IFRAME) {
            this.takeFocus();
        }
    };

    // Make the window 'modal', by doing the following:
    // - Use a 'background' window that overlays the whole page.
    // - Use a container that has the background-div and the popup-div
    //   as children.
    // This way the whole page is covered by the popup implementation,
    // making the page inaccessible until the popup is clicked away.
    if (windowBackground == null) { // @pragma(allow-loose-compare)
        // Create the background window.
        windowBackground = document.createElement("div");
        windowBackground.className = "usurroundings";
        windowBackground.style.position = "fixed";
        windowBackground.style.top = "0";
        windowBackground.style.left = "0";
        windowBackground.style.width = "100%";
        windowBackground.style.height = "100%";
        windowBackground.style.zIndex = 0;
        windowBackground.style.opacity = OVERLAY_OPACITY / 100;                    // FF
        windowBackground.style.filter = "alpha(opacity=" + OVERLAY_OPACITY + ")";  // IE, Opera
        // Create the container for the background and the uwindow instances.
        windowContainer = document.createElement("div");
        windowContainer.className = "uontop";
        // Add the background window to the container.
        windowContainer.appendChild(windowBackground);
        // Add the container to the document.
        document.body.appendChild(windowContainer);
    }
    // Add the window to the container, and make the container visible.
    windowContainer.appendChild(ufrm);
    windowContainer.style.display = "block";

    return ufrm;
},
moreinfo:function() {
    var ufrm = findUfrmFromInnerNode(this);
    uwindow.setClientContent(ufrm,'iframe', ufrm.moreinfo);
    uwindow.sizePosWindow(ufrm,'center','center',500,250);
},
showFailure:function(titlebartext,messageTxt,statusLineString, moreInfoText)
{   // Hardcoded errorbox with more info button for the total error page
    // Make a windows like gray background and center the stuff.
    var innerHTML = createNode("div");
    innerHTML.style.cssText = "text-align: center; height: 100%;";
    createNode("br", null, innerHTML);
    var img = createNode("img", null, innerHTML);
    img.title = "Close";
    img.src = "../common/images/uwindow/error.gif";
    img.align = "middle";
    var lineCount = appendTextNodes(innerHTML, "\n" + messageTxt);
    createNode("br", null, innerHTML);
    createNode("br", null, innerHTML);
    var okButton = createNode("input", null);
    okButton.type = "button";
    okButton.value = "OK";
    okButton.name = "defaultButton";
    okButton.onclick = uwindow.closeWindow;
    innerHTML.appendChild(okButton);    // Could not do this in the createNode call above (because of IE...)
    innerHTML.appendChild(document.createTextNode("\u00A0\u00A0\u00A0"));
    var moreInfoButton = createNode("input", null);
    moreInfoButton.id = "moreinfo";
    moreInfoButton.type = "button";
    moreInfoButton.value = "More info...";
    moreInfoButton.name = "more";
    moreInfoButton.onclick = uwindow.moreinfo;
    innerHTML.appendChild(moreInfoButton);
    createNode("br", null, innerHTML);
    var ufrm = uwindow.createWindow(titlebartext,statusLineString);
    ufrm.moreinfo = moreInfoText;
    uwindow.setClientContent(ufrm,'html',innerHTML);
    uwindow.sizePosWindow(ufrm,'center','center',220,89+Math.min(lineCount,MAX_LINES)*PIX_PER_LINE);
    uwindow.showWindow(ufrm);
},
showMessage:function(a_title,messageData,buttontext,cx,cy,messageType) /* Create standard window  returns the id as handle */
{
    var cxLeft = 50; /* 20px margin plus image*/
    var cxDef  = 190;
    var cyDef = 89;
    var lineCount;
    var cxTotal; 
    var innerHTML = createNode("div");
    innerHTML.style.cssText = "text-align:center; height:100%;";
    createNode("br", null, innerHTML);
    var img = createNode("img", null, innerHTML);
    img.title = "Close";
    img.src = "../common/images/uwindow/" + messageType + ".gif";
    img.align = "middle";
    lineCount = appendTextNodes(innerHTML, "\n" + messageData);
    createNode("br", null, innerHTML);
    createNode("br", null, innerHTML);
    var defaultButton = createNode("input", null);
    defaultButton.type = "button";
    defaultButton.value = buttontext;
    defaultButton.name = "defaultButton";
    defaultButton.onclick = uwindow.closeWindow;
    innerHTML.appendChild(defaultButton);
    createNode("br", null, innerHTML);
    var ufrm = uwindow.createWindow(a_title,"");

    /* 12 chars requires approx 240 pixels */
    if (messageData.length) {
        cxDef = messageData.length * 10;
    }
    if (cx === 0){
        cxTotal = cxDef+cxLeft;
        cxTotal = Math.min(cxTotal,400);
    } else {
        cxTotal = cx;
    }
    if (cy !== 0){
       cyDef = cy;
    }
    cyDef = cyDef + Math.min(lineCount,MAX_LINES) * PIX_PER_LINE;
    uwindow.setClientContent(ufrm,'html',innerHTML);
    uwindow.sizePosWindow(ufrm,'center','center',cxTotal,cyDef);
    uwindow.showWindow(ufrm);
},
getviewpoint:function(){
    var ie=document.all && !window.opera;
    var domclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth,10) || 100000;
    this.standardbody=(document.compatMode==="CSS1Compat")? document.documentElement : document.body;
    this.scroll_top=0;//(ie)? this.standardbody.scrollTop : window.pageYOffset;
    this.scroll_left=0;//(ie)? this.standardbody.scrollLeft : window.pageXOffset;
    this.docwidth=(ie)? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16);
    this.docheight=(ie)? this.standardbody.clientHeight: window.innerHeight;
},
sizeWindow:function(ufrm,cx,cy){
    ufrm.style.width=Math.max(parseInt(cx,10),150)+"px";
    ufrm.clientwindow.style.height=Math.max(parseInt(cy,10),75)+"px";
},
sizePosWindow:function(ufrm,x,y,cx,cy){
    this.getviewpoint();
    var extraOffset = 0;
    var count = windowContainer.childNodes.length+MW_SETSIZE/2 - 2;
    if (x === "center") {
        extraOffset = MW_GAP * ((count % MW_SETSIZE - Math.floor(count / MW_SETSIZE)) - MW_SETSIZE/2);
        ufrm.style.left = this.scroll_left+(this.docwidth-ufrm.offsetWidth)/2+extraOffset+"px";
    } else {
        ufrm.style.left = this.scroll_left+parseInt(x,10)+"px";
    }
    if (y === "center") {
        extraOffset = MW_GAP * ((count % MW_SETSIZE) - MW_SETSIZE/2) + MW_OFFSET * Math.floor(count / MW_SETSIZE);
        ufrm.style.top = this.scroll_top+(this.docheight-ufrm.offsetHeight)/2+extraOffset+"px";
    } else {
        ufrm.style.top = this.scroll_top+parseInt(y,10)+"px";
    }
    this.sizeWindow(ufrm,cx,cy);
},
killChildNode:function(ufrm){
    // remove child div or child iframe
    ufrm.clientwindow.removeChild(ufrm.clientwindow.childNodes[0]);
    ufrm.clientwindow.contenttype="";
},
closeWindow:function() {
    var ufrm = findUfrmFromInnerNode(this);
    if (ufrm.clientwindow.contenttype !== "")
    {// remove child div or child iframe
        ufrm.clientwindow.removeChild(ufrm.clientwindow.childNodes[0]);
    }
    ufrm.clientwindow.contenttype="";
    ufrm.clientwindow.contenttype="";
    ufrm.clientwindow.style.overflow="";
    ufrm.clientwindow.innerHTML="";
    ufrm.parentNode.removeChild(ufrm);
    ufrm.style.display="none";
    ufrm = null;
    // If the windowBackground is the only child of the window container,
    // then it contains no actual windows anymore.
    var windowCount = windowContainer.childNodes.length - 1;
    if (windowCount <= 0) {
        // Hide the window container.
        windowContainer.style.display = "none";
    } else {
        // Find the last window.
        ufrm = windowContainer.childNodes[windowCount];
        ufrm.takeFocus();
    }
},
showWindow:function(ufrm){
    ufrm.style.display="block";
    ufrm.style.visibility = "visible";
    ufrm.buttonFocus();
},
setClientContent:function(ufrm,contenttype,contentsource){
    var lFrame = null;
    var lName  = null;
    var oldContenttype = ufrm.clientwindow.contenttype;
    // if switching from html to iframe, we remove first the div children from the
    // clientwindow.
    if ( oldContenttype ==CONTENT_HTML || oldContenttype ==CONTENT_IFRAME){
        uwindow.killChildNode(ufrm);
    }
    if (contenttype==CONTENT_IFRAME)
    {
        lFrame = window.document.createElement("iframe");
        lFrame.style.cssText = "margin:0; padding:0; width:100%; height: 100%";
        ufrm.clientwindow.style.overflow="hidden";
        ufrm.clientwindow.contenttype = contenttype;
        lName = "wnd_name";
        lFrame.name = lName;
        ufrm.clientwindow.appendChild(lFrame);
    }
    if (contenttype==CONTENT_IFRAME && lFrame !== null ) 
    {   var oDoc = lFrame.contentWindow || lFrame.contentDocument;
        if (oDoc.document) {
            oDoc = oDoc.document;
        }
        oDoc.open();
        oDoc.write(contentsource);
        oDoc.close();
    }else if (contenttype==CONTENT_HTML){
        ufrm.clientwindow.style.overflow="";
        //ufrm.clientwindow.innerHTML=contentsource;
        ufrm.clientwindow.appendChild(contentsource);
        ufrm.clientwindow.contenttype = contenttype;
    }
},
wmbuttondown:function(evt){
    var e;
    var ufrm=this.hparent; // get parent handle
    var f = uwindow;
    f.clickedObj=this;
    e=window.event || evt;
    f.xpos=e.clientX;
    f.ypos=e.clientY;
    f.initx=parseInt(ufrm.offsetLeft,10);
    f.inity=parseInt(ufrm.offsetTop,10);
    f.width=parseInt(ufrm.offsetWidth,10);
    f.clientwindowheight=parseInt(ufrm.clientwindow.offsetHeight,10);
    if (ufrm.clientwindow.contenttype===CONTENT_IFRAME){
        ufrm.clientwindow.style.visibility="hidden";
    }
    document.onmousemove=f.wmmousemove;
    document.onmouseup=function()
    {
        if (ufrm.clientwindow.contenttype ===CONTENT_IFRAME)
        {
            ufrm.clientwindow.style.backgroundColor="white";
            ufrm.clientwindow.style.visibility="visible";
        }
        f.clickedObj=null;
        document.onmousemove=null;
        document.onmouseup=null;
    };
    return false;
},
wmmousemove:function(evt){
    var e;
    var f = uwindow; 
    var hparent;
    e=window.event || evt;
    f.dx=e.clientX-f.xpos;
    f.dy=e.clientY-f.ypos;
    if (f.clickedObj.className==="utitlebar")
    {
        hparent = f.clickedObj.hparent; 
        hparent.style.left=f.dx+f.initx+"px";
        hparent.style.top=f.dy+f.inity+"px";
    }
    return false;
}
};
}());

UNIFACE.extension.register("popupWindow", uwindow);
