// Dialog -*- javascript -*-
// (c) 2007-2008 Maptuit Corporation

Dialog.instances = new Object();

function Dialog(id,cgi,callback,callerid,callerdata) {

    this.id = id;
    this.callback = callback;
    this.callerid = callerid;
    this.callerdata = callerdata;
    
    this.container = document.createElement('div');
    this.container.className = 'dlgContainer';

    var glass = document.createElement('div');
    glass.className = 'glass';
    glass.onclick = function() { dlgCloseDialog(id); };
    this.container.appendChild(glass);
        
    var dialog = document.createElement('iframe');
    dialog.className = 'dlg';
    dialog.frameBorder = '0';
    dialog.marginWidth = '0';
    dialog.marginHeight = '0';
    if (cgi.match(/[?]/)) {
        dialog.src = cgi + '&dlgid='+this.id;
    } else {
        dialog.src = cgi + '?dlgid='+this.id;
    }
    this.container.appendChild(dialog);
    this.dialog = dialog;

    var btn = document.createElement('a');
    btn.className = 'closeme';
    btn.innerHTML = '<img src="/_img/close-sm.gif" border="none">';
    btn.href = "javascript:dlgCloseDialog('"+id+"');";
    this.container.appendChild(btn);
    this.closeme = btn;
    
    document.body.appendChild(this.container);
    document.body.style.cursor = 'wait';
    
    Dialog.instances[id] = this;
}

function dlgCloseDialog(id,data) {

    var dlg = Dialog.instances[id];
    if (dlg) {
        document.body.removeChild(DOMpurge(dlg.container));
        if (dlg.callback) dlg.callback(dlg.callerid,data,dlg.callerdata);
    }
    Dialog.instances[id] = null;
    document.body.style.cursor = 'default';

    if (window.show_ads) show_ads();
}

function dlgInitDialog(id,w,h,trkid) {

    var dlg = Dialog.instances[id];
    if (!dlg) return;
    
    if (!w) w = 400;
    if (!h) h = 200;
    
    with (dlg.dialog.style) {
        h += 14;
        w += 14;
        marginLeft = '-'+parseInt(w/2)+'px';
        marginTop = '-'+parseInt(h/2)+'px';
        width = w+'px';
        height = h+'px';
    }
    with (dlg.closeme.style) {
        // 16 is width of closeme icon
        marginLeft = (parseInt(w/2)-16-7)+'px';
        marginTop = '-'+(parseInt(h/2)-7)+'px';
        visibility = 'visible';
    }
    
    dlg.dialog.style.visibility = 'visible';
    document.body.style.cursor = 'default';
    
    if (window.hide_ads) hide_ads(); // for Opera
    if (window.page_view) page_view('dialog-'+(trkid? trkid:id));
}

function DOMpurge(d,childrenOnly) {
    var a = d.attributes, i, l, n;
    if (a && !childrenOnly) {
        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) {
            DOMpurge(d.childNodes[i]);
        }
    }

    return d;
}
