/*
*   Copyright 2007 Copyright Basis Applied Technology, Inc. All rights are reserved.
*   author James Sas (james@gobasis.com)
*/
app.include(BF_SCRIPTDIR+'app.js');
app.include(BF_SCRIPTDIR+'css.js');
app.include(BF_SCRIPTDIR+'xmlrpc.js');
app.include(BF_SCRIPTDIR+'functor.js');
app.include(BF_SCRIPTDIR+'dialogs/genericmessage.js');
//app.include(BF_SCRIPTDIR+'dialogs/simpleprogress.js');

function webbler() {
    if (!__wmmod.__instance) {
        __wmmod.__instance = new __wmmod(WM_INIT);
    }
    return __wmmod.__instance;
}
function stm() {
    if (!__wmstm.__instance) {
        __wmstm.__instance = new __wmstm();
    }
    return __wmstm.__instance;
}
// public interface ----------------------------------------
app.include(BF_SCRIPTDIR+'dialogs.js');

function webblerprogressdialog() {
    return this;
};
webblerprogressdialog.prototype.construct = function(cbCancel) {
    this.m_cbCancel = cbCancel;
    return dialogbase.prototype.construct.call(this);
};
webblerprogressdialog.prototype.update = function(cbCancel) {
    this.m_cbCancel = cbCancel;
    this.m_dlg_td.innerHTML = this.fetchdialog();
}
webblerprogressdialog.prototype.fetchdialog = function() {
    if (Functor.isFunctor(this.m_cbCancel) || app.isFunction(this.m_cbCancel)) {
        return '<div class="dialogwindow" style="width:50px;padding:10px;"><img src="'+WM_IMAGEDIR+'spinner.gif" /><a href="Cancel" onclick="app.getdialog().cancel();return false;" >Cancel</a></div>';
    } else {
        return '<div class="dialogwindow" style="width:30px;padding:10px;"><img src="'+WM_IMAGEDIR+'spinner.gif" /></div>';
    }
};
webblerprogressdialog.prototype.cancel = function() {
    var cb = this.m_cbCancel;
    this.update();
    var args = [];
    for(var i=0;i<arguments.length;i++) args.push(arguments[i]);
    Functor.fire(cb, args);
};

function __wmmod(init) {
    this.mProxy = init ? app.xmlrpc.makeProxy(init.sClass, BF_KEY, init.aIFace, 'json', 'xmlrpc') : null;
}
__wmmod.prototype.proxy = function() {
    return this.mProxy;
};
__wmmod.prototype.render = function(uuid, args, target, show_fault, async, cb) {
    if (async) {
        this.proxy().setAsync(async, new Functor(this, this.cbRender, [uuid, target, show_fault, async, cb]));
    }
    var out = this.proxy().RenderTemplate(uuid, args);
    if (!async) {
        out = this.cbRender(uuid, target, show_fault, async, cb, out);
    }
    return out;
};
__wmmod.prototype.renderDialog = function(uuid, args, cb, async) {
    this.endWait();
    var dlg = new __wmmod_dlg();
    if (!dlg.construct(uuid, args, cb, async)) {
        return false;
    }
    return true;
};
__wmmod.prototype.showFault = function(err, cb) {
    if (app.xmlrpc.fault(err,false)) {
        this.showMessage(err.faultString, cb);
        return true;
    }
    return false;
};
__wmmod.prototype.showMessage = function(message, cb, mask) {
    this.endWait();
    var dlg = new genericmessagedialog();
    mask = app.rVal(mask, DLG_OK_ONLY|DLG_DEFAULT1);
    if (!dlg.construct(message, mask, new Functor(this, this.cbShowMessage, [dlg, cb]))) {
        alert(message);
        if (Functor.isFunctor(cb)) { setTimeout(function(){cb.fire([DLG_OK]);},1); }
        else if (app.isFunction(cb)) { setTimeout(function(){cb(DLG_OK);},1); }
    }
};
__wmmod.prototype.startWait = function(cbCancel) {
    if (this.mWdlg) {
        this.mWdlg.update(cbCancel);
    } else {
        var dlg = new webblerprogressdialog();
        dlg.construct(cbCancel);
        this.mWdlg = dlg;
    }
};
__wmmod.prototype.endWait = function() {
    if (this.mWdlg) {
        this.mWdlg.destroy();
        this.mWdlg = null;
    }
};
__wmmod.prototype.startProgress = function(message) {
    this.endProgress();
    var dlg = new simpleprogressdialog();
    dlg.construct();
    dlg.setprogress(0, message);
    dlg.__ProgIncrement = 1;
    var cbUpdate = new Functor(this, this._stepProgress, [dlg]);
    dlg.__ProgInterval = setInterval(function(){cbUpdate.fire();}, 200);
    this.mPdlg = dlg;
};
__wmmod.prototype.endProgress = function() {
    if (this.mPdlg) {
        this.mPdlg.destroy();
        clearInterval(this.mPdlgInterval);
        this.mPdlg = this.mPdlgInterval = null;
    }
};
__wmmod.prototype._stepProgress = function(dlg) {
    var inc = dlg.__ProgIncrement;
    var pos = inc + dlg.getprogress();
    if (inc < 0) {
        pos = Math.max(pos,0);
        if (pos == 0)
        { dlg.__ProgIncrement = (-dlg.__ProgIncrement); }
    } else {
        pos = Math.min(pos,99);
        if (pos == 99)
        { dlg.__ProgIncrement = (-dlg.__ProgIncrement); }
    }
    dlg.setprogress(pos);
};
__wmmod.prototype.svc = function(sClass, oCB, iTimeout) {
    if (!this._aSvcs) this._aSvcs={};
    if (!this._aSvcs[sClass]) {
        var oSvc = {};
        oSvc.iface    = app.xmlrpc.Call(BF_WS_URL, BF_KEY, "WebblerModule.CallService", [sClass+".WSInterface"]);
        oSvc._async   = false;
        oSvc._functor = null;
        oSvc.setAsync = function(b,h){this._async=b;this._functor=(b?h:null);}
        oSvc.setTimeout = function(t){this._timeout=t;}
        oSvc._timeout = 30000;
        for(var i=0;i<oSvc.iface.length;i++)
        {oSvc[oSvc.iface[i]] = new Function("",'var arr=["'+sClass+'.'+oSvc.iface[i]+'"]; for(var i=0;i<arguments.length;i++){arr.push(arguments[i]);}; var _timeout = app.xmlrpc.timeout; app.xmlrpc.timeout = this._timeout ; var ret = app.xmlrpc.Call(BF_WS_URL,BF_KEY, "WebblerModule.CallService", arr, 0, this._async, this._functor); app.xmlrpc.timeout = _timeout; this._async=false; this._functor=null; return ret;');}
        this._aSvcs[sClass] = oSvc;
    }
    if (Functor.isFunctor(oCB)) this._aSvcs[sClass].setAsync(true,oCB);
    if (app.isInt(iTimeout)) this._aSvcs[sClass].setTimeout(iTimeout);
    return this._aSvcs[sClass];
};
__wmmod.prototype.include = function(uuid) {
    app.include("/wmdata/javascript/"+uuid+".js");
};
__wmmod.prototype.isFault = function(f) {
    return app.xmlrpc.fault(f,false);
};
// stm ----------------------------------------
function __wmstm() {

    this.m_tbls={};
    return this;
}
__wmstm.prototype.table = function(tbl) {
    if (!this.m_tbls[tbl]) {
        this.m_tbls[tbl] = new __wmstmtbl(webbler().proxy().GetStringTable(tbl));
    }
    return this.m_tbls[tbl];
};
// stmtbl ----------------------------------------
function __wmstmtbl(tbl) {
    this.m_tbl=tbl;
    return this;
}
__wmstmtbl.prototype.string = function(str) {
    str = str.toUpperCase();
    if (this.m_tbl[str]) {
        return this.m_tbl[str];
    }
    return '';
};

// callbacks ----------------------------------------
__wmmod.prototype.cbRender = function(uuid, target, show_fault, async, cb, out) {
    var is_fault = app.xmlrpc.fault(out, false);
    if (is_fault) {
        if (show_fault) {
            if (async) this.showFault(out, cb); else alert(out);
        } else if (async) {
            Functor.fire(cb, [out]);
        }
    } else {
        if (out !== undefined) { // cancelled
            if (target) {
                target.innerHTML = out.html;
                for(var i=0;i<out.stylesheets.length;i++) {if(!app.sheetExists(out.stylesheets[i].href))app.applyCSS(out.stylesheets[i].href, out.stylesheets[i].css, out.stylesheets[i].media);}
                for(var i=0;i<out.javascript.length;i++)app.applyScript(out.javascript[i].script, out.javascript[i].href, false);
                for(var i=0;i<out.executables.length;i++) app.applyScript(out.executables[i], null, true);
            }
        }
        if (async) Functor.fire(cb, [out]);
    }
    return out;
};
__wmmod.prototype.cbShowMessage = function(dlg, cb, ret, code) {
    dlg.destroy();
    delete dlg;
    Functor.fire(cb, [ret]);
};
// ajax dialog ----------------------------------------

function __wmmod_dlg() {
    return this;
}
__wmmod_dlg.prototype.m_sLoadingTpl = '<div class="dialogwindow" style="width:30px;padding:10px;"><img src="'+WM_IMAGEDIR+'spinner.gif" /></div>';
__wmmod_dlg.prototype.construct = function(uuid, args, cb, async) {
    this.m_uuid = uuid;
    this.m_args = args;
    this.m_cb = cb;
    this.m_async = async;
    if (dialogbase.prototype.construct.call(this)) {
        if (!this.m_async) {
            this.applyelements(this.m_out);
        }
        return true;
    }
    return false;
};
__wmmod_dlg.prototype.applyelements = function(out) {
    for(var i=0;i<out.stylesheets.length;i++)if(!app.sheetExists(out.stylesheets[i].href))app.applyCSS(out.stylesheets[i].href, out.stylesheets[i].css, out.stylesheets[i].media);
    for(var i=0;i<out.javascript.length;i++)app.applyScript(out.javascript[i].script, out.javascript[i].href, false);
    for(var i=0;i<out.executables.length;i++) app.applyScript(out.executables[i], null, true);
};
__wmmod_dlg.prototype.fetchdialog = function() {
    if (this.m_async) {
        webbler().render(this.m_uuid, this.m_args, null, false, true, new Functor(this, this.onfetched));
        return this.m_sLoadingTpl;
    } else {
        webbler().proxy().setAsync(false);
        var out = webbler().proxy().RenderTemplate(this.m_uuid, this.m_args);
        if (!app.xmlrpc.fault(out, true)) {
            this.m_out = out;
            return out['html'];
        }
    }
    return false;
};
__wmmod_dlg.prototype.onfetched = function(out) {
    if (!app.xmlrpc.fault(out, false)) {
        var dlg_td = this.m_base.getElementsByTagName('td')[0];
        dlg_td.innerHTML = out['html'];
        this.applyelements(out);
    } else {
        this.fire(out);
    }
}
__wmmod_dlg.prototype.fire = function() {
    var cb = this.m_cb;
    this.destroy();
    if(cb) {
        var args = [];
        for(var i=0;i<arguments.length;i++) args.push(arguments[i]);
        Functor.fire(cb, args);
    }
};