﻿/**
 * @author Falko Zander, www.falko-zander.de
 */

/**
 * @param id String
 * @param parentid String
 * @param modal Boolean
 * @param onclose Function
 * @param style Object
 */
function cDialog(id, parentid, modal, onclose, style) {
    this.id = id || '';
    this.parentid = parentid || '';
    this.modal = modal || 1;
    this.elem = null;
    this.fader = null;
    this.onclose = (typeof onclose == 'function') ? onclose : function() {};
    this.always_aligned = 0;
    
    if (typeof style != 'undefined') this.setstyle(style);
}

/**
 * @param style Object
 */
cDialog.prototype.setstyle = function(style) {
    if (this.elem == null) {
        idx = this.register_();
    }

    for (var s in style) {
        this.elem.style[s] = style[s];
    }
}

cDialog.prototype.show = function() {
    if (this.elem == null) {
        idx = this.register_();
    }

    var THIS = this;
    var i = this.elem.getElementsByTagName('div')[0].getElementsByTagName('td')[1].firstChild;
    i.src = '/images/basic/close.png';
    i.onmouseover = function() { this.src = '/images/basic/close_hover.png'; };
    i.onmouseout = function() { this.src = '/images/basic/close.png'; };
    i.onclick = function() { THIS.close(); };

    if (this.always_aligned == 1) {
        this.set_position_();
    }

    if (this.modal == 1) {
        this.fader = ViewUtils.show_fader();
    }
    this.elem.style.visibility = 'visible';
}

cDialog.prototype.close = function() {
    if (this.elem == null) error('dialog: can not find element.');

    this.elem.style.visibility = 'hidden';
    if (this.modal == 1) {
        this.fader = ViewUtils.remove_fader(this.fader);
    }

    if (this.onclose != null) this.onclose();
}

cDialog.prototype.register_ = function() {
    this.elem = $(this.id);
    if (this.elem == null) error('dialog: can not find element ' + this.id);

    var e = this.elem;

    var c = e.getElementsByTagName('div')[0];
    var t = c.getElementsByTagName('td')[1];
    t.innerHTML = "<img src='/images/basic/close.png' width='12' height='12' alt='close' />"; //$NON-NLS-1$

    e.style.display = 'block';
    this.dragdrop = new cDndWidget(e, c);

    this.set_position_();
}

cDialog.prototype.set_position_ = function() {
    var p = $(this.parentid);
    var e = this.elem;

    if (p != null) {
        var d = getAbsoluteDimensions(p);
        e.style.left = (p.offsetWidth - e.offsetWidth) / 2 + d.offsetLeft + 'px';
        e.style.top = (p.offsetHeight - e.offsetHeight) / 2 + d.offsetTop + 'px';
    } else {
        var w = window.innerWidth || document.body.clientWidth;
        var h = window.innerHeight || document.body.clientHeight;
        e.style.left = (w - e.offsetWidth) / 2 + 'px';
        e.style.top = (h - e.offsetHeight) / 2 + 'px';
    }
}
