var dialogUtil = new Object();

window.dialogUtil = dialogUtil;

var MULTIPLIER = 10;
var MAX_SKIP_COUNT = 2;

/* document overlay */
dialogUtil.overlay = null;
dialogUtil.navigation = null; // needed for dialog movement

dialogUtil.overlayFrame = null;
dialogUtil.isInModalOverlay = false;  // helps to prevent infinite loop if the onresize handler is set improperly
dialogUtil.navigationFrame = null; // needed for dialog movement

dialogUtil.skipCounter = 0;      // helps with improving the performance, we don't want to redraw for every movement
dialogUtil.closePressed = false; // helps with handling event bubbling

// This is needed in case the user scrolls the page by moving the mouse out of the page with the left button pressed
dialogUtil.viewportX = 0;       
dialogUtil.viewportY = 0;        

/* a stack to reference all the visible stack, in the order of when they are opened */
/* the last element is always the active dialog */
dialogUtil.visibleDialogStack = new Array();

dialogUtil.dragElem = null; // the element we're dragging
dialogUtil.currentX = null; // current x position on the page before event firing
dialogUtil.currentY = null; // current y position on the page before event firing
dialogUtil.maxX = null;     // max allowed x position in the view
dialogUtil.maxY = null;     // max allowed y position in the view

dialogUtil.showDialog = function(dialogId, baseURL, width, height, urlParamNames, urlParamValues) {
    var dialog = dialogSet.getOrCreateDialog(dialogId, null, width, height);
    if (dialog == null) return;

	if(urlParamNames == null) {
		urlParamNames = new Array();
	}

	if(urlParamValues == null) {
		urlParamValues = new Array();
	}

    dialog.display.style.display = "";
    // use the unencoded url params
    dialogUtil.getInIFrame(dialog.iframe, baseURL, urlParamNames, urlParamValues);
    dialogUtil.showFormDialog(dialogId, dialog.iframe.contentWindow.document.forms["IFRAME_POST_FORM"], width, height);
}

dialogUtil.showDialogNoURL = function(dialogId, width, height) {
    var dialog = dialogSet.getOrCreateDialog(dialogId, null, width, height);
    if (dialog == null) return;

    dialog.display.style.display = "";
    // use the unencoded url params
    dialogUtil.showFormDialogNoSubmit(dialogId, width, height);
}

dialogUtil.getDocumentDialog = function(dialogId) {
	var dialog = dialogSet.getDialogById(dialogId);
	return  dialog.iframe.contentWindow.document;
}

dialogUtil.showFormDialogNoSubmit = function(dialogId, width, height) {
    var dialog = dialogSet.getOrCreateDialog(dialogId, null, width, height);
    if (dialog == null) return;

    // check to see if the dialog is shown already
    for (var i = 0; i < dialogUtil.visibleDialogStack.length; i++) {
        if (dialogUtil.visibleDialogStack[i] == dialog) {
            return;
        }
    }
    if(window.onresize && !dialogUtil.origOnresize)
        dialogUtil.origOnresize = window.onresize;

    // Reset the width and height every time in case they are different than previous values
    this.setWidthAndHeight(dialogId, width, height);
    // add active dialog to the model dialog stack
    dialogUtil.visibleDialogStack.push(dialog);
    dialogUtil.handleModalOverlay();
    dialog.display.style.display = "";
    dialog.closed = false;
    dialogUtil.positionDialog();
    window.onresize = dialogUtil.handleModalOverlay;

    document.onkeydown = null;

    // This automatic submit loads the dialog URL into the iframe
}

dialogUtil.showFormDialog = function(dialogId, form, width, height) {
    var dialog = dialogSet.getOrCreateDialog(dialogId, null, width, height);
    if (dialog == null) return;

    // check to see if the dialog is shown already
    for (var i = 0; i < dialogUtil.visibleDialogStack.length; i++) {
        if (dialogUtil.visibleDialogStack[i] == dialog) {
            return;
        }
    }
    if(window.onresize && !dialogUtil.origOnresize)
        dialogUtil.origOnresize = window.onresize;

    // Reset the width and height every time in case they are different than previous values
    this.setWidthAndHeight(dialogId, width, height);
    // add active dialog to the model dialog stack
    dialogUtil.visibleDialogStack.push(dialog);
    dialogUtil.handleModalOverlay();
    dialog.display.style.display = "";
    dialog.closed = false;
    dialogUtil.positionDialog();
    window.onresize = dialogUtil.handleModalOverlay;

    document.onkeydown = null;

    // This automatic submit loads the dialog URL into the iframe
    form.target = dialog.iframe.id;
    form.submit();
}

dialogUtil.positionDialog = function() {
    // Re-center the dialog DIV
    var width = 1024;
    var height = 768;
    
    if(document.body.parentElement && document.body.parentElement.clientWidth) {
        width = document.body.parentElement.clientWidth;
        height = document.body.parentElement.clientHeight;
    } else if (document.body && document.body.clientWidth) {
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }

	// dialog may be in an iframe 
    var topWidth = 1024;
    var topHeight = 768;
    if(top.document.body.parentElement && top.document.body.parentElement.clientWidth) {
        topWidth = top.document.body.parentElement.clientWidth;
        topHeight = top.document.body.parentElement.clientHeight;
    } else if (top.document.body && top.document.body.clientWidth) {
        topWidth = top.document.body.clientWidth;
        topHeight = top.document.body.clientHeight;
    }
	
    var stackSize = dialogUtil.visibleDialogStack.length;
    if (stackSize > 0 && dialogUtil.visibleDialogStack[stackSize - 1].display) {
        var currDialog = dialogUtil.visibleDialogStack[stackSize - 1];

        var offsetWidth = currDialog.content.offsetWidth;
        var offsetHeight = currDialog.content.offsetHeight;
        var newLeft = (Math.round((width - offsetWidth) / 2) + document.body.scrollLeft);
        var newTop = (Math.round((height - offsetHeight) / 2) + document.body.scrollTop);

        if (newLeft < 0) newLeft = document.body.scrollLeft;
        if (newTop < 0) newTop = document.body.scrollTop;
        /*
        if (topWidth != width) { // dialog within iframe
        	var scrollLeft = top.document.body.scrollLeft;
        	newLeft = Math.round(scrollLeft*2/3);
        }
        if (topHeight != height) { // dialog within iframe
        	var scrollTop = top.document.body.scrollTop;
        	newTop = Math.round(scrollTop*2/3);
        }
        */
        newLeft = newLeft + "px";
        newTop = newTop + "px";

        currDialog.display.style.left = newLeft;
        currDialog.display.style.top = newTop;
    }
}
dialogUtil.getInIFrame = function(iFrame, baseURL, urlParamNames, urlParamValues) {
	iFrame.contentWindow.document.write("<html><body></body></html>");
	
	var doc = iFrame.contentWindow.document;
	var body = doc.body;
	var form = doc.createElement("FORM");
	form.name = "IFRAME_POST_FORM";
	form.id = "IFRAME_POST_FORM";
	form.method = "GET";
	form.action = baseURL;
	body.appendChild(form);
	if(urlParamNames) {
		for(var i = 0; i < urlParamNames.length; i++) {
	        var input = doc.createElement('INPUT');
	        input.type = "hidden";
	        input.name = urlParamNames[i];
	        input.value = urlParamValues[i];
	        form.appendChild(input);
	    }
	}
	
}

dialogUtil.setWidthAndHeight = function(dialogId, width, height) {
    var shadow = document.getElementById(dialogId + 'Shadow');
    if (shadow != null) {
        shadow.style.width = width + "px";
        var h = (height*1 + 19);
        shadow.style.height =  h + "px";
    }
    var content = document.getElementById(dialogId + 'Content');
    if (content != null) {
        content.style.width = width + "px";
        content.style.height = height + "px";
    }
    var header = document.getElementById(dialogId + 'Header');
    if (header != null) {
        header.style.width = width + "px";
    }
}

dialogUtil.hideDialogSelects = function() {
    var dialogDiv = dialogUtil.overlay;
    var hideSelectFrame = dialogUtil.overlayFrame;
    if (!dialogDiv || (dialogDiv && dialogDiv.style.display == "none")) {
        // if the overlay doesn't exist or it is not shown, hide the iframe as well
        hideSelectFrame.style.display = "none";
    } else {
        // overlay is shown.  Put the iframe immediately below it to hide the select elements
        hideSelectFrame.style.width = dialogDiv.offsetWidth;
        hideSelectFrame.style.height = dialogDiv.offsetHeight;
        hideSelectFrame.style.zIndex = (dialogDiv.style.zIndex-1);
        hideSelectFrame.style.display = "block";
    }
}
dialogUtil.handleModalOverlay = function() {
    if(!dialogUtil.isInModalOverlay) {
        dialogUtil.isInModalOverlay = true;
        if(!dialogUtil.overlay) {
            // create the modal overlay if don't have it yet
            dialogUtil.overlay = document.createElement("DIV");
            dialogUtil.overlay.className = "dialog-overlay";
            dialogUtil.overlay.style.display = "";
            dialogUtil.overlay.onclick="commonUtil.cancelBubble(event); window.event.returnValue=false;";
            dialogUtil.overlay.onkeydown="commonUtil.cancelBubble(event); window.event.returnValue=false;";
            dialogUtil.overlay.onkeypress="commonUtil.cancelBubble(event); window.event.returnValue=false;";
            dialogUtil.overlay.onkeyup="commonUtil.cancelBubble(event); window.event.returnValue=false;";
            document.body.appendChild(dialogUtil.overlay);

            // create a transparent overlay frame to hide select elements under it
            dialogUtil.overlayFrame = document.createElement("IFrame");
            dialogUtil.overlayFrame.src = "about:blank";  
            dialogUtil.overlayFrame.style.position = "absolute";
            dialogUtil.overlayFrame.style.top = "0px";
            dialogUtil.overlayFrame.style.left = "0px";
            dialogUtil.overlayFrame.style.filter = "alpha(opacity=0)";
            dialogUtil.overlayFrame.style.display = "block";
            document.body.appendChild(dialogUtil.overlayFrame);
        }
        if (dialogUtil.visibleDialogStack.length > 0) {
            dialogUtil.overlay.style.display = "";
            dialogUtil.overlayFrame.style.display = "block";
            
            dialogUtil.visibleDialogStack[dialogUtil.visibleDialogStack.length-1].display.style.zIndex = dialogUtil.visibleDialogStack.length*MULTIPLIER;
            dialogUtil.overlay.style.zIndex = dialogUtil.visibleDialogStack[dialogUtil.visibleDialogStack.length-1].display.style.zIndex-1;
            dialogUtil.overlay.style.width = document.body.scrollWidth;
            dialogUtil.overlay.style.height = document.body.scrollHeight;

            dialogUtil.overlayFrame.style.zIndex = dialogUtil.overlay.style.zIndex - 1;
            dialogUtil.overlayFrame.style.width = document.body.scrollWidth;
            dialogUtil.overlayFrame.style.height = document.body.scrollHeight;
        } else {
            dialogUtil.overlay.style.display = "none";
            dialogUtil.overlayFrame.style.display = "none";
            document.body.style.overflow = "auto";
            if(dialogUtil.origOnresize != null)
            {
                window.onresize = dialogUtil.origOnresize;
                dialogUtil.origOnresize = null;
            }
        }
        if(commonUtil.browserIsIE()) {
            dialogUtil.hideDialogSelects();
        }
        dialogUtil.isInModalOverlay = false;
    }
    else
        return;
}


/*************************************************************
 * Dialog "X" button actions
 *************************************************************/
dialogUtil.buttonOver = function(imgElem) {
    imgElem.src = "images/close_dialog_hover.gif";
}

dialogUtil.buttonOut = function(imgElem) {
    imgElem.src = "images/close_dialog.gif";
}

dialogUtil.buttonPress = function(imgElem, isUp) {
    if (isUp == 1) {
        imgElem.src = "images/close_dialog.gif";
    } else {
        dialogUtil.closePressed = true;
        imgElem.src = "images/close_dialog_press.gif";
    }
}

/*************************************************************
 * Draggable functionality
 *************************************************************/
dialogUtil.drag = function(event, elem) {
    if(dialogUtil.closePressed == true) {
        dialogUtil.closePressed = false;
        return;
    }

    dialogUtil.dragElem = elem;
    dialogUtil.currentX = (event.clientX - parseInt(elem.style.left));
    dialogUtil.currentY = (event.clientY - parseInt(elem.style.top));
    dialogUtil.viewportX = document.body.scrollLeft;
    dialogUtil.viewportY = document.body.scrollTop;

    // check the max left and top position for the dialog based on the shadow's width and height
    var shadowDiv = document.getElementById(dialogUtil.dragElem.id + "Shadow");
    var cWidth = 1024;
    var cHeight = 768;

    if(document.body.parentElement && document.body.parentElement.clientWidth) {
        cWidth = document.body.parentElement.clientWidth;
        cHeight = document.body.parentElement.clientHeight;
    } else if (document.body && document.body.clientWidth) {
        cWidth = document.body.clientWidth;
        cHeight = document.body.clientHeight;
    }
    dialogUtil.maxX = Math.max(cWidth-parseInt(shadowDiv.style.width), 0);
    dialogUtil.maxY = Math.max(cHeight-parseInt(shadowDiv.style.height), 0);
    dialogUtil.handleNavigationPlane();
    dialogUtil.navigation.onmousemove = dialogUtil.dragOnMouseMove;
    dialogUtil.navigationFrame.onmousemove = dialogUtil.dragOnMouseMove;
    dialogUtil.navigation.onmouseup = dialogUtil.dragOnMouseDrop;
    dialogUtil.navigationFrame.onmouseup = dialogUtil.dragOnMouseDrop;


    event.returnValue = false;
}

dialogUtil.dragOnMouseMove = function(e) {
    e = (e ? e : window.event);
    if (dialogUtil.dragElem == null) return false;

    sLeft = document.body.scrollLeft;
    sTop = document.body.scrollTop;

    dLeft = e.clientX - dialogUtil.currentX;
    dTop = e.clientY - dialogUtil.currentY;

    dialogUtil.skipCounter += 1;
    if(dialogUtil.skipCounter == MAX_SKIP_COUNT) {
        dialogUtil.skipCounter = 0;
        dialogUtil.dragElem.style.left = dLeft + 'px';
        dialogUtil.dragElem.style.top = dTop + 'px';
    }

    e.returnValue = false;
}

dialogUtil.handleNavigationPlane = function() {
    if(!dialogUtil.navigation) {
        // create the modal navigation if when don't have it already
        dialogUtil.navigation = document.createElement("DIV");
        dialogUtil.navigation.className = "navigation-overlay";
        dialogUtil.navigation.style.display = "";
        dialogUtil.navigation.onclick="commonUtil.cancelBubble(event); window.event.returnValue=false;";
        document.body.appendChild(dialogUtil.navigation);

        // create a transparent navigation frame to hide select elements under it
        dialogUtil.navigationFrame = document.createElement("IFrame");
        dialogUtil.navigationFrame.src = "about:blank";  // need this for https
        dialogUtil.navigationFrame.style.position = "absolute";
        dialogUtil.navigationFrame.style.top = "0px";
        dialogUtil.navigationFrame.style.left = "0px";
        dialogUtil.navigationFrame.style.filter = "alpha(opacity=0)";
        dialogUtil.navigationFrame.style.display = "block";
        document.body.appendChild(dialogUtil.navigationFrame);
    }

    if (dialogUtil.visibleDialogStack.length > 0) {
        dialogUtil.navigation.style.display = "";
        dialogUtil.navigationFrame.style.display = "block";

        // see comment (top of the file) on MULTIPLIER on how zIndex for dialogs are ordered
        dialogUtil.navigation.style.zIndex = dialogUtil.visibleDialogStack[dialogUtil.visibleDialogStack.length-1].display.style.zIndex+2;
        dialogUtil.navigation.style.width = document.body.scrollWidth;
        dialogUtil.navigation.style.height = document.body.scrollHeight;

        dialogUtil.navigationFrame.style.zIndex = dialogUtil.navigation.style.zIndex - 1;
        dialogUtil.navigationFrame.style.width = document.body.scrollWidth;
        dialogUtil.navigationFrame.style.height = document.body.scrollHeight;
    } else {
        dialogUtil.navigation.style.display = "none";
        dialogUtil.navigationFrame.style.display = "none";
    }

    var dialogDiv = dialogUtil.navigation;
    var hideSelectFrame = dialogUtil.navigationFrame;
    if (!dialogDiv || (dialogDiv && dialogDiv.style.display == "none")) {
        // if the overlay doesn't exist or it is not shown, hide the iframe as well
        hideSelectFrame.style.display = "none";
    } else {
        // overlay is shown.  Put the iframe immediately below it to hide the select elements
        hideSelectFrame.style.width = dialogDiv.offsetWidth;
        hideSelectFrame.style.height = dialogDiv.offsetHeight;
        hideSelectFrame.style.zIndex = (dialogDiv.style.zIndex-1);
        hideSelectFrame.style.display = "block";
    }
}


dialogUtil.dragOnMouseDrop = function(e) {
    dialogUtil.navigation.style.display = "none";
    dialogUtil.navigationFrame.style.display = "none";

    var acIFrame = dialogSet.getDialogById(dialogUtil.dragElem.id).iframe;
    var popupDoc = acIFrame.contentWindow ? acIFrame.contentWindow.document : acIFrame.contentDocument;

    var inputTags = popupDoc.getElementsByTagName("input");
    for(var i = 0; i < inputTags.length; i++)
    {
        try {
            if(inputTags[i].type != 'hidden' && !inputTags[i].disabled && inputTags[i].style.display != 'none' && inputTags[i].style.visibility != 'hidden') {
                inputTags[i].focus();
                break;
            }
        }
        catch(e)
        {}
    }

    dialogUtil.dragElem = null;
}

dialogUtil.hideDialogRefresh = function(dialogId) {	
	dialogUtil.hideDialog(dialogId);
	window.location.href = window.location.href;
}

dialogUtil.hideDialog = function(dialogId) {
    var dialog = dialogSet.getDialogById(dialogId);

    if (dialog == null) return;

    if (dialogUtil.visibleDialogStack.length > 0) {
    	var i = 0;
    	for (i = 0; i < dialogUtil.visibleDialogStack.length &&
    		   dialog.displayId != dialogUtil.visibleDialogStack[i].displayId; i++);
    		   
		if ((i < dialogUtil.visibleDialogStack.length) && (dialog.displayId == dialogUtil.visibleDialogStack[i].displayId)) {
	    	for (; i < dialogUtil.visibleDialogStack.length-1; i++) {
	    		dialogUtil.visibleDialogStack[i] = dialogUtil.visibleDialogStack[i+1];
	    	}
    		dialogUtil.visibleDialogStack.length--; 
    	}
    	
        dialog.display.style.display = "none";
        dialog.closed = true;
        dialogUtil.handleModalOverlay();
        document.onkeydown = dialog.parentKeyDown;
    }
}