var UtlYuiDialogShowUsrCb = [];
function utlYui_addDialogShowCb(cb)
{
    UtlYuiDialogShowUsrCb.push(cb);
}

var UtlYuiDialogHideUsrCb = [];
function utlYui_addDialogHideCb(cb)
{
    UtlYuiDialogHideUsrCb.push(cb);
}

function utlYuiDialogHideCb() 
{
    d = arguments[2];

    /* This is especially important to make flash movies stop 
     * playing in the background. */
    if( d.vick_resetContainerOnHide ) {
        if( isFunction(d.vick_resetContainerOnHide) ) {
            (d.vick_resetContainerOnHide)();
        } else {
            /* id is d.id */
            d.element.innerHTML = "";
        }
    }

    for(i=0; i<UtlYuiDialogHideUsrCb.length; i++) {
        (UtlYuiDialogHideUsrCb[i])();
    }
}

function utlYuiDialogShowCb() 
{
    for(i=0; i<UtlYuiDialogShowUsrCb.length; i++) {
        (UtlYuiDialogShowUsrCb[i])();
    }
}

/* Integrates with the rest of the windowing system. */
function utlYuiIntegrate(d, divId, resetContainerOnHide)
{
    var klc = new YAHOO.util.KeyListener(document, { keys:27 },
        { fn:d.hide, scope:d, correctScope:true }, "keyup" );

    var kls = new YAHOO.util.KeyListener(document, { keys:13 },
        { fn:d.submit, scope:d, correctScope:true }, "keyup" );

    d.cfg.queueProperty("keylisteners", [ klc, kls ]);

    /* d.hideEvent and d.showEvent are also available,
     * however if used, utlYuiDialogHideCb will trigger
     * d.showEvent which will hide the other dialogs in turn etc. */
    d.beforeHideEvent.subscribe(utlYuiDialogHideCb, d);     
    d.beforeShowEvent.subscribe(utlYuiDialogShowCb, d);     

    /* These are custom properties. */
    d.vick_resetContainerOnHide = resetContainerOnHide;

    /* If there is a form in the document and the user hits <enter>,
     * this will unfortunately result in a double submit: one by the 
     * key listeners above and one by the form. The solution is to
     * create a hidden submit button (if there isn't one already) and
     * set its "onclick" method to do nothing. */
    var div = document.getElementById(divId);
    var forms = div.getElementsByTagName("form");
    if( ! forms || 1 != forms.length ) {
        return;
    }
    var frm = forms[0];
    frm.setAttribute('method', "post");
    var inputs = frm.getElementsByTagName("input");
    var sbtn = null;
    for( var k=0; k < inputs.length; k++ ) {
        var input = inputs[k];
        if( input.getAttribute("type") == "submit" ) {
            sbtn = input;
            break;
        }
    }
    if( null == sbtn ) {
        sbtn = document.createElement("input");
        /* For some reason setAttribute needs to be called before appendChild.*/
        sbtn.setAttribute('type', 'submit');
        sbtn.setAttribute("onclick", "return false");
        sbtn.style.width = '0px';
        sbtn.style.height = '0px';
        sbtn.style.visibility = 'hidden';
        sbtn.style.display = 'none';
        frm.appendChild(sbtn);
    }
}

function utlYuiSetButtons(dialog, /* optional: */ submitTxt, submitHandler, 
    cancelTxt, cancelHandler)
{
    var submitWasDefined = true;
    if( ! isDefined(submitTxt) || null == submitTxt ) {
        submitWasDefined = false;
        submitTxt = "Close";
    }

    if( ! isDefined(submitHandler) || null == submitHandler ) {
        submitWasDefined = false;
        submitHandler = dialog.hide;
    }

    var b;
    if( ! submitWasDefined ) {
        /* Submit argument was just a cancel argument. */
        b = [ { text:submitTxt, handler:submitHandler, isDefault:true } ];
    } else
    if( isDefined(cancelTxt) && isDefined(cancelHandler) ) {
        b = [ { text:cancelTxt, handler:cancelHandler },
              { text:submitTxt, handler:submitHandler, isDefault:true } ];
    } else {
        b = [ { text:"Cancel", handler:dialog.hide },
              { text:submitTxt, handler:submitHandler, isDefault:true } ];
    }

    dialog.cfg.queueProperty( "buttons", b );
    dialog.submit = submitHandler;
}

function utlYui_dialogSimple(hdr, txt, 
    /* optional: */ usrHandleYes, usrHandleNo)
{
    var handleYes = function() {
        if( isDefined(usrHandleYes) ) { (usrHandleYes)(); }
        this.hide();
    };
    var handleNo = function() {
        if( isDefined(usrHandleNo) ) { (usrHandleNo)(); }
        this.hide();
    };

    /* Hardcode width otherwise Windows/IE7 simple dialogs look bad 
     * (partially transparent). Use the same value accross all
     * platforms for consistency. 
     *
     * iframe:true is needed so that dialogs go on top of flash, however 
     * this creates iframes that might not be needed for non-flash pages.
     * TODO: make this an option. */
    var d = new YAHOO.widget.SimpleDialog( "MyYuiSimpleDialog1", 
        { fixedcenter:true, visible:false, draggable:true, 
          close: true, constraintoviewport: true, text: txt,
          width:"300px", height:"auto", iframe:true, 
          icon: YAHOO.widget.SimpleDialog.ICON_HELP } );

    d.setHeader(hdr);

    utlYuiSetButtons(d, "Ok", handleYes, "Cancel", handleNo);
    utlYuiIntegrate(d, "MyYuiSimpleDialog1", true);
    
    /* The container id is needed for SimpleDialog. */
    d.render(document.body);

    YAHOO.util.Event.addListener("show", "click", d.show, d, true);
    YAHOO.util.Event.addListener("hide", "click", d.hide, d, true);
    d.show();
}
/* resetOnHide: if bool, innerHTML will be reset; If function, it will 
 * be called on hide. */
function utlYui_createDialog(divId, widthArg, /* optional: */ resetOnHide, 
    submitTxt, submitHandler, cancelTxt, cancelHandler)
{
    /* Some divs set themselves to zero height and width, so that they don't 
     * take any space on rendering. For those divs, dragging the window
     * doesn't work unless the height is readjusted here to "auto". 
     *
     * iframe:true is needed so that dialogs go on top of flash, however 
     * this creates iframes that might not be needed for non-flash pages.
     * TODO: make this an option. */
    var d = new YAHOO.widget.Dialog(divId, 
        { width:widthArg, height:"auto", fixedcenter:true, visible:false, 
          draggable:true, constraintoviewport:true, iframe:true });

    utlYuiSetButtons(d, submitTxt, submitHandler, cancelTxt, cancelHandler);
    utlYuiIntegrate(d, divId, resetOnHide);

    d.render();
    return d;
}

function utlYuiGetDialogDiv(baseName, title)
{
    var divId = baseName + 'MainDivId';

    var div = document.getElementById(divId);
    if( ! div ) {
        div = document.createElement('div');
        div.setAttribute('id', divId);
        document.body.appendChild(div);
    }

    var divTitleId = baseName + 'TitleDivId';
    var divTitle = document.getElementById(divTitleId);
    if( ! divTitle ) {
        divTitle = document.createElement('div');
        divTitle.setAttribute('id', divTitleId);
        divTitle.className = 'hd';
        div.appendChild(divTitle);
    }

    if( isDefined(title) ) {
        divTitle.innerHTML = title;
    }

    return div;
}

function utlYuiGetDialogIFrame(div, baseName, title, scroll)
{
    var ifrId = baseName + 'ContentIFrameId';
    var ifrName = baseName + 'ContentIFrameName';
    var ifr = utlFindIFrameByName(ifrName);
    if( null == ifr ) {
        ifr = document.createElement('iframe');
        ifr.setAttribute('id', ifrId);
        ifr.setAttribute('name', ifrName);
        ifr.className = 'bd';
        ifr.setAttribute('frameborder', '0');
        if( isDefined(scroll) ) {
            ifr.setAttribute('frameborder', scroll);
        }
        div.appendChild(ifr);
    }

    return ifr;
}

/* IE 6 doesn't display a video properly unless some text (say,
 * "Video:") preceeds it. */
function utlYui_showDialog(htmlText, widthArg, title, scroll)
{
    var baseName = 'UtlYuiDialog';
    var div = utlYuiGetDialogDiv(baseName, title);

    div.innerHTML = htmlText;

    var d = utlYui_createDialog(div.id, widthArg, true /* resetOnHide */);
    d.show();
}

/* Opens a window through yui. When yui not available, use
 * utlOpenWindow. */
function utlYui_showDialogExtern( width, height, title, externFileName,
    /* optional: auto/yes/1/no/0 */ scroll, html )
{
    var baseName = 'UtlYuiDialogExtern';
    var div = utlYuiGetDialogDiv(baseName, title);
    var ifr = utlYuiGetDialogIFrame(div, baseName, title, scroll);

    ifr.src = externFileName;
    ifr.width = width - utlGetScrollerWidth();
    if( "Explorer" == utl_browserName() ) {
        ifr.width = ifr.width - 20;
    }
    ifr.style.height = height;

    var d = utlYui_createDialog(div.id, width, true);
    d.show();
}
