﻿// Autore : ermanno.astolfi@gmail.com
// VERSIONE 20101211
// Licenza : GPL2

// un array è "un array"
Array.prototype.IS_ARRAY = true;

// ciclo sugli elementi
Array.prototype.foreach = function(i,fn)
{
    if (fn==undefined)
    { 
        fn=i; 
        i=0;
    }
    if (typeof(fn)!='function')
    {
        fn = new Function('el,idx',fn);
    }
    for(i; i<this.length; i++)
    {
        fn.apply(this,[this[i],i]);
    }
    return this;
}
Array.prototype.x = Array.prototype.foreach;

// inserimento da un altra collezione o array
Array.prototype.merge = function()
{
    for(var i = 0; i<arguments.length; i++)
    {
        //this.push(arguments[i]);
        if (!arguments[i] || arguments[i].length==undefined) this.push(arguments[i]);
        else for(var j=0; j<arguments[i].length; j++) this.push(arguments[i][j]); //arguments.caller.apply(this,arguments[i]);//
    }
    return this;
}

// indice di un elemento attraverso la funzione identità o user defined
Array.prototype.idx = function(el)
{
    var f = el;
    if (typeof(el)!='function') f = function(a){return a == el;}
    for(var i=0; i<this.length; i++)
    {
        if (f(this[i])) return i;
    }
    return -1;
}

// l'elemento è presente
Array.prototype.has = function (el)
{
    return this.idx(el)+1;
}

// rimozione elemento
Array.prototype.remove = function(el)
{
    var i = this.idx(el);
    if (i>=0) this.splice(i,1);
    return this;
}

// aggiunta dell'elemento se non è presente 
Array.prototype.add = function(el)
{
    if (!this.has(el))
    {
        this.push(el);
        var ar = this;
        if (typeof(el)!='string') lrx.ev_add(el,'#RM',function(){ar.remove(this)});
    }
    return this;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function strclean(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+", "g"), "");
}

function GET(el,p)
{
    if (!el) return '';
    switch(p)
    {
    case 'class': return el.className;
    case 'style': return el.style && el.style.cssText;
    }
    return el.getAttribute?el.getAttribute(p):el[p];
}
function SET(el,p,v)
{
    if (!el) return;
    switch(p)
    {
    case 'class': 
        el.className = v;
        break;
    case 'style': 
        if(el.style) el.style.cssText=v;
        break;
    }
    el.setAttribute?el.setAttribute(p,v):el[p]=v;
    return el;
}
function AR (o)
{
    // wrapping soft in un array ... o è un array oppure se ha una proprietà lenght viene "assimilata" 
    if(!o) return [];
    if (o.IS_ARRAY) return o;
    return [].merge(o);
}
function WAR (o)
{
    // wrapping forzato di un array ... o è un array o viene messo in un array
    if(!o) return [];
    if (o.IS_ARRAY) return o;
    return [o];
}
function lower(s){return (s+'').toLowerCase();}
function upper(s){return (s+'').toUpperCase();}
function max()
{
    var r = undefined;
    AR(arguments).foreach(function(el)
    {
        if (r==undefined || el>r) r=el;
    });
    return r;
}
function min()
{
    var r = undefined;
    AR(arguments).foreach(function(el)
    {
        if (r==undefined || el<r) r=el;
    });
    return r;
}
function nvl()
{
    var arg = AR(arguments);
    var val = undefined;
    while(!(val = arg.shift())&& arg.length) ;
    return val;
}

// // // // // // // // // // // // // // //

var dsk;

var lrx = new (function()
{    
    function has_lrx(el,p)
    {
        if (!el) return false;
        if (!el['_lrx']) return false;
        if (el._lrx[p]===undefined) return false;
        return true;
    }
    function ini_lrx(el,o,v)
    {
        if (!el) return el;
        if (!el['_lrx']) el._lrx = {};
        if (el._lrx[o]===undefined) el._lrx[o] = v;
        return el;
    }
    function get_lrx(el,o,d)
    {
        //if (!d) d = {};
        if (!el) return el;
        ini_lrx(el,o,d);
        return el._lrx[o];
    }
    
    function found (a,b)
    {
        if (!b) return false;
        switch(typeof(a))
        {
        case 'string':
            return lower(b.tagName)==lower(a);
        case 'function':
            return a(b);
        case 'object':
            for (e in a) 
            switch(e)
            {
            case '#tag':
                if (lower(a[e])!=lower(b.tagName)) return false;
                break;
            default:
                if (a[e]!=GET(b,e)) return false;
                break;
            }
            return true;
        }
    }
    function childs()
    {
        var args = AR(arguments);
        var root = args.shift();
        var res = [];
        
        if (root) AR(root.childNodes).foreach(function (ch)
        {
            if (ch.nodeType!=1) return;
            try
            {
                if (!args.length) throw '--found--';
                args.foreach(function(arg)
                {
                    if (found(arg,ch)) throw '--found--';
                });
            }
            catch(ex)
            {
                if (ex=='--found--') res.push(ch);
            }
        });
        
        return res;
    }

    function search()
    {
        var args = AR(arguments);
        var res = []; 
        AR(childs(args[0])).foreach(function(ch)
        {
            try
            {
                args.foreach(1,function(a){if(found(a,ch)) throw '--found--'});
            }
            catch(ex)
            {
                if (ex=='--found--') res.push(ch);
            }
            // ricerca ricorsiva sui figli
            args[0]=ch;
            res.merge(search.apply(lib,args));
        });
        return res;
    }
    function rand(b,m)
    {
        if (!b) b = '_base_';
        if (!m) m = 10000000;
        return b+Math.ceil(Math.random()*m);
    }
    function get_win(el)
    { 
        var d = el && el.ownerDocument;
        var w = null;
        if (!w && d && d.defaultView) w = d.defaultView;
        if (!w && d && d.parentWindow) w = d.parentWindow;
        return w || el;
    }

    // gestione eventi
    var _ev_dom = 'load,unload,mousedown,mouseup,mouseover,mouseout,click,dblclick'.split(',');
    function ev_new(ev)
    {
        if (!ev) ev = window.event;
        if (!ev.target) ev.target = ev.srcElement;
        if (!ev.preventDefault) ev.preventDefault = function(){};
        if (!ev.stopPropagation) ev.stopPropagation = function()
        {
            this.cancelBubble = true;
        }
        if(ev['pageX'] || ev['pageY'])
        {
            ev['x'] = ev.pageX;
            ev['y'] = ev.pageY;
        }
        else
        {
            ev['x'] = ev.clientX + document.body.scrollLeft - document.body.clientLeft;
            ev['y'] = ev.clientY + document.body.scrollTop  - document.body.clientTop;
        }
        if (ev['which']!=undefined) 
        {
            // firefox ... se il carattere è 0 ma keycode è positivo
            // allora è un carattere speciale
            ev['chCode'] = ev.which;
            if (!ev.chCode && ev.keyCode) ev.chCode = -ev.keyCode;
        }
        else ev['chCode'] = ev.keyCode;    
        ev['ch'] = '';
        if (ev.chCode>0) ev.ch = String.fromCharCode(ev.chCode);
        
        return ev;
    }
    function ev_add (el,ev,fnc)
    {
        if (!el) return;
        var evs = get_lrx(el,'ev',{});
        var dom = get_lrx(el,'dom',[]);
        if (!evs[ev]) evs[ev] = [];
        // è un evento di interfaccia non ancora gestito e presente nell'elemento?
        if (_ev_dom.has(ev) && !dom.has(ev))
        {
            dom.push(ev);           // gestito ...
            var ff = el['on'+ev];   // funzione iniziale
            if (ff)
            {
                evs[ev].push(
                {
                    a : 1,
                    f : ff,
                    start : function(args)
                    {
                        var w = get_win (el);
                        if (!w || w.closed || !this.a) return;
                        if (this.f) this.f.apply(el,args);
                    },
                    rm : function()
                    {
                        this._a = 0;
                        evs[ev].remove(this);
                    }
                });
            }
            el['on'+ev] = function(evn){try{ev_start(this,ev,ev_new(evn)); return true;}catch(e){return false;}};
        }
        var h = {a : 1,
                 f : fnc,
                 rm: function(){
                    this.a=0;
                    evs[ev].remove(this);
                 },
                 start: function(args){
                    var w = get_win (el);
                    if (!w || w.closed || !this.a) return;
                    if (this.f) this.f.apply(el,args);
                 }
                };
        evs[ev].push(h);
        return h;
    }
    function ev_obs()
    {
        var args = AR(arguments);
        var el = args.shift();
        if (!el) return;
        var obs = get_lrx(el,'obs',[]);
        AR(args.shift()).foreach(function(ob)
        {
            if (!ob) return;
            obs.add(ob);
        });
    }
    function ev_obs_del()
    {
        var args = AR(arguments);
        var el = args.shift();
        if (!el) return;
        var obs = get_lrx(el,'obs',[]);
        obs = [];
    }
    function ev_start()
    {
        var args = AR(arguments);
        var argo = AR(arguments);
        var el = args.shift();
        var ev = args.shift();
        var evs = get_lrx(el,'ev',{});
        var obs = get_lrx(el,'obs',[]);
        var cmd = GET(el,'ev_'+ev);
        // evento come attributo
        if(cmd)
        {
            // viene eseguito ...
            
            var f = cmd;
            var w = get_win(el);
            if (typeof(f)!='function') f = new w.Function('args',cmd);
            try{f.apply(el,[args]);}
            catch(e){alert(e+' :: '+cmd);}
        }
        // evento registrato
        if (evs[ev]) evs[ev].foreach(function(h)
        {
            h.start(args)
        });
        // evento osservatori
        obs.foreach(function(ob)
        {
            argo[0]=ob;
            ev_start.apply(get_win(ob),argo);
        });
    }
    
    // // // function export
    
    this.has_lrx = has_lrx;
    this.ini_lrx = ini_lrx;
    this.get_lrx = get_lrx;
    
    this.ev_new = ev_new;
    this.ev_add = ev_add;
    this.ev_obs = ev_obs;
    this.ev_obs_del = ev_obs_del;
    this.ev_start = ev_start;
    
    this.childs = childs;
    this.search = search;
       
    var lib = this;
    this.fx = function()
    {
        var act = AR(arguments);
        var el = act.shift();
        var ff = new Function(act.shift(),act.shift());
        return ff.apply(el,act);
    }
    function abs(v)
    {
        if (v<0) return -v;
        return v;
    }
    // // // wrapper tag
    function wrap(el)
    {
        this.El = function(){return el}
        function u(e){return (e&&e.El)?e.El():e;}
        this.Att   = function (a,b){if (b==undefined) return GET(el,a); SET(el,a,b); return this;}
        this.Add = function(e)
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
			if (!e) return e;
            if (typeof(e)=='string') 
            {
                el.innerHTML += e; 
                return this;
            }
            el.appendChild(u(e));
            return W(e);
        }
        this.Rm = function ()
        {
            if (!el) return;
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            if(el)
            {
                if (el.parentNode) el.parentNode.removeChild(el);
                lrx.ev_start(el,'#RM');
            } 
            return this;
        }
        this.Ins = function (a,post)
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            if (!el) return this;
            a = u(a);
            if (post) 
            {
                // viene inserito dopo this
                if (el.nextSibling) el.parentNode.insertBefore(a,el.nextSibling);
                else el.parentNode.appendChild(a);
            }
            else
            {
                // viene inserito prima
                el.parentNode.insertBefore(a,el);
            }
            return W(a);
        }
        this.Par = function (tag,sk)
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            sk = nvl(sk,0);
            if (!el) return this;
            function _p(el)
            {
                if (!el) return el;
                // ricerca veloce del parent cercato
                if (!tag) if (sk--<=0) return el;
                if (found(tag,el)) if (sk--<=0) return el;
                return _p(el.parentNode);
            }
            // wrapping del solo risultato
            return W(_p(el.parentNode));
        }
        this.Fst = function (e)
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            if (!el) return this;
            e = u(e);
            (el.firstChild)?el.insertBefore(e,el.firstChild):
                            el.appendChild(e);
            return W(e);
        }
        this.evAdd = function(a,b,c)
        { 
            var h = ev_add(el,a,b); 
            if (c) return h; 
            return this;
        }
        this.evStart = function()
        {
            ev_start.apply(lib,[el].merge(arguments));
            return this;
        }
        this.Cld = function()
        {
            return childs.apply(lib,[el].merge(arguments))
        }
        this.Src = function()
        {
            return search.apply(lib,[el].merge(arguments))
        },
        this.Last = function()
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            return W(this.Cld().pop())
        },
        this.AppTo = function(el)
        {
            if (!el.nodeType) return;
            if (el.nodeType!=1) return;
            W(el).Add(this);
            return this;
        },
        this.ScrollLeft = function(o,k,t,s)
        {
            if (o.isScrolling) return;
            function scroll()
            {
                o.isScrolling = true;
                t = nvl(t,100);
                s = nvl(s,20);
                var l = parseInt(el.style.left);
                if (abs(k-l)<s)
                {
                    el.style.left = k+'px';
                    o.isScrolling = false;
                    return;
                }
                if (l<k) 
                {
                    el.style.left = (l+(s-2))+'px';
                }
                else if (l>k) 
                {
                    el.style.left = (l-(s-2))+'px';
                }
                setTimeout(scroll,t);
            }
            scroll();
        }
    }
    
    
    
    function W()
    {
        var args = AR(arguments);
        var el = args.shift();
        if (typeof(el)=='string') el = ID(el);
        if (el&&el.El)
        {
            if (args.length) el.evStart.apply(el,args);
            return el;
        }
        var w = get_lrx(el,'wrap');
        if (!w) ini_lrx(el,'wrap',w = new wrap(el));
        if (args.length) w.evStart.apply(w,args);
        return w;
    }
    window.W = this.W = W;
    
    function id(el)
    {
        if (!el) return el; 
        if (typeof(el)=='string') el = document.getElementById(el); 
        return el;
    };
    window.ID = this.id = id;
    
    function tag (t,a,c)
    {
        if (!a) a = {};
        var d = W(document.createElement(t));
        for(e in a)
        switch(typeof(a[e]))
        {
        case 'function' :
            d.El    ()[e] = a[e];
            break;
        default:
            d.Att(e,a[e]);
            break;
        }
        if (c)
        {
            d.Add(c);
        }
        return d.Rm().El();
    }

    this.tag = tag;
    this.rand = rand;
    this.get_win = get_win;

    function att(a)
    {
        var s = [];
        for (e in a) s.push(e+='="'+a[e]+'"');
        return s.join(' ');
    }
    // inizializzazione desktop
    this.init_dsk = function(w)
    {
        dsk = w || ((window.frameElement && window.frameElement.dsk) || window);
        return dsk;
    }
    
    this.is_dsk = function(){return window==dsk;}
    
    this.init_dsk();
    
    function get_pos(e,delta)
    {
        if (!delta) delta = {};
    	var left = nvl(delta.x,0);
    	var top  = nvl(delta.y,0);
        var width = e.offsetWidth||0;
        var height = e.offsetHeight||0;
        if (e.style && e.style.position=='absolute')
        {
            return {x:parseInt(e.style && e.style.left)||e.offsetLeft, y:parseInt(e.style && e.style.top)||e.offsetTop, w:width, h:height};
        }
    	while (e.offsetParent){
    		left += e.offsetLeft||0;
    		top  += e.offsetTop||0;
    		e     = e.offsetParent;
            if (!e.offsetParent)
            {
                var w = get_win(e);
                if (w!=window && w.frameElement) e = w.frameElement;
            }
    	}
    
    	left += e.offsetLeft||0;
    	top  += e.offsetTop||0;
    
    	return {x:left, y:top, w:width, h:height};
    }
    this.opacity = function(el,p)
    {
        el.style.opacity = (p/100);
        el.style.filter = 'alpha(opacity='+p+')';
        return el;
    }
    function set_pos(el,pos)
    {
        el.pos = pos;
        el.style.position = 'absolute';
        el.style.left = pos.x+'px';
        el.style.top = pos.y+'px';
        return el;
    }
    this.set_pos = set_pos;

    function center(el)
    {
        var d = dsk.document.documentElement;
        var ui = {'sh':d.scrollHeight,
                  'sw':d.scrollWidth,
                  'st':d.scrollTop,
                  'sl':d.scrollLeft,
                  'ch':d.clientHeight,
                  'cw':d.clientWidth};
        return set_pos(el, {'x':max(((ui.cw-el.offsetWidth)/2 + ui.sl),0),
               'y':max(((ui.ch-el.offsetHeight)/2 + ui.st),0)});
    }
    this.center = center;
    this.expande = function(el,noresize)
    {
        el.style.position ='absolute';
        el.style.top      = '0px'; 
        el.style.left     = '0px'; 
        // l'oggetto viene nascosto
        el.style.display = 'none';
        // lettura dimensioni
        var b = dsk.document.documentElement;
        var ui = {'sh':b.scrollHeight,
                  'sw':b.scrollWidth,
                  'st':b.scrollTop,
                  'sl':b.scrollLeft,
                  'ch':b.clientHeight,
                  'cw':b.clientWidth};
        // l'oggetto viene rivisualizzato
        el.style.display = '';
        el.style.width    = ui.sw+'px'; 
        el.style.height   = ui.sh+'px';
        if (!noresize)
        {
            // viene legato al resize della finestra
            h = lrx.ev_add(window,'resize',function()
            {
                lib.expande(el,1);
            })
            lrx.ev_add(el,'#RM',function(){h.rm()});
        }
        return el;
    }
    function table(topt)
    {
        topt = nvl(topt,{});
        var tbl = tag('table',{'cellpadding':'0',
                                   'cellspacing':'0',
                                   'width':nvl(topt.width,'')});
        function cc(tbl,t,el,opt)
        {
            if (!tbl.tr_cur) tbl.Row();
            if (opt.make=='left')
            {
                tbl.cl_cur = W(tbl.tr_cur).Fst(tag(t)).El();
            }
            else
            {
                tbl.cl_cur = W(tbl.tr_cur).Add(tag(t)).El();
            }
            W(tbl.cl_cur).Add(el);
        }
        tbl.Row = function ()
        {
            this.tr_cur = W(this).Add(tag('tr')).El();
            return this.tr_cur;
        }
        tbl.Cell = function(el,opt)
        {
            if (!opt) opt = {};
            if (typeof(opt)!='object') opt = {'ret':opt};
            cc(this,'td',el,opt);
            if (opt.ret) return el;
            return this.cl_cur;
        }
        tbl.Head = function(el,opt)
        {
            if (!opt) opt = {};
            if (typeof(opt)!='object') opt = {'ret':opt};
            cc(this,'th',el,opt);
            if (opt.ret) return el;
            return this.cl_cur;
        }
        return tbl;
    }
    function getMouseOffset(target, ev)
    {
        var docPos    = get_pos(target);
        return {x:ev.x - docPos.x, y:ev.y - docPos.y, w: docPos.w-ev.x, h: docPos.h-ev.y};
    }    
    var mv_obj = null;
    var mv_cover = null;
    function resize(o,e,k)
    {
        mv_obj = o;
        if (!mv_obj)
        {
            W(mv_cover).Rm();
            document.onmousemove = null;
            document.onmouseout = null;
            document.onmouseup = null;
            return;   
        }
        e = lrx.ev_new(e);
        var mv_gap = getMouseOffset(o, e);
        mv_cover = tag('div',{'style':['position:absolute',
                                               'background-color: yellow',
                                               'height:12px',
                                               'width:100%',
                                               'text-align:center',
                                               'font-weight:bold'].join('; ')});
        W(document.body).Add(mv_cover);
        lib.expande(mv_cover);
        lib.opacity(mv_cover,10);
        document.onmousemove = function(ev)
        {
            if (!mv_obj) return;
            ev = ev_new(ev);
            
            mv_obj && W(mv_obj).evStart('setSize',{'w':mv_gap.w+ev.x,'h':mv_gap.h+ev.y-nvl(k,0)});
            return false;
        }
        document.onmouseup  = function(e)
        { 
            resize(); // stop
        }
        document.onmouseout = function(e)
        {
            e = ev_new(e);
            if(e.fromElement) {if (e.toElement) return;}
            else{if (e.target != document.documentElement) return;}
            resize();
        }
    }
    function move(o,e)
    {
        mv_obj = o;
        if (!mv_obj)
        {
            W(mv_cover).Rm();
            document.onmousemove = null;
            document.onmouseout = null;
            document.onmouseup = null;
            return;   
        }
        e = ev_new(e);
        mv_obj.style.position = 'absolute';
        var mv_gap = getMouseOffset(o, e);
        mv_cover = tag('div',{'style':['position:absolute',
                                       'background-color: yellow',
                                       'height:12px',
                                       'width:100%',
                                       'text-align:center',
                                       'font-weight:bold'].join('; ')});
        W(document.body).Add(mv_cover);
        lib.expande(mv_cover);
        lib.opacity(mv_cover,10);
        document.onmousemove = function(ev)
        {
            if (!mv_obj) return;
            ev = ev_new(ev);
            
            if(mv_obj)
            {
                mv_obj.pos = {y:max(ev.y - mv_gap.y,0), 
                              x:max(ev.x - mv_gap.x,0),
                              block:true};
                mv_obj.style.top      = mv_obj.pos.y+'px';
                mv_obj.style.left     = mv_obj.pos.x+'px';
                mv_cover.innerHTML = '<div style="padding-top:30px;">y : '+mv_gap.y+' , x : '+mv_gap.x+'</div>';
                return false;
            }       
        }
        document.onmouseup  = function(e)
        { 
            move(); // stop
        }
        document.onmouseout = function(e)
        {
            e = lrx.ev_new(e);
            if(e.fromElement) {if (e.toElement) return;}
            else{if (e.target != document.documentElement) return;}
            move();
            
        }
    }
    function rm(el)
    {
        if (!el) return el;
        return W(el).Rm().El();
    }
    function par(el,tag,sk)
    {
        var p = W(el).Par(tag,sk);
        return p?p.El():p;
    }
    
    this.move = move;
    this.resize = resize;
    this.rm = rm;
    this.par = par;
    
    function _form_var(f,opt)
    {
        if (opt.form || opt.vars)
        {
            W(f).Att('method',nvl(opt.method,'POST'));
            // si effettua il POST
            var vv = [];
            var n = null;
            if(opt.form) AR(opt.form.elements).foreach(function(inp)
            {
                if(!inp.name) return;
                if(inp.disabled) return;
                switch(inp.type)
                {
                case 'radio':
                case 'checkbox':
                    if (!inp.checked) return;
                }
                if (GET(inp,'lrx_post')=='no') return;
                n = inp.cloneNode(true);
                try{
                    n.value = inp.value;
                }catch(e){}                
                vv.push(n);
            });
            
            
            if(opt.vars) 
            {
                if (opt.vars.IS_ARRAY)
                {
                    opt.vars.foreach(function(el)
                    {
                        vv.push(tag('texarea',el,el.value));
                    });
                }
                else
                {
                    for(e in opt.vars)
                    {
                        vv.push(tag('textarea',{'name':e},opt.vars[e]));
                    }
                }
            }
            vv.foreach(function(el)
            {
                W(f).Add(el);
            });
        }
        else
        {
            W(f).Att('method','GET');
        }
    }
    function debug(msg)
    {
        if (!lib.is_dsk()) return dsk.lrx.debug(msg);
        var dbg = id('__debug__');
        if (!dbg) dbg = W(tag('div',{'id':'__debug__'})).AppTo(document.body).El();
        dbg.innerHTML = msg;
    }
    this.debug = debug;
    
    function box(el, opt, obs)
    {
        var pos = {};
        var d;
        pos.w = nvl(opt.w,50);
        pos.h = nvl(opt.h,30);
        pos.x = nvl(opt.x,0);
        pos.y = nvl(opt.y,0);
        if (opt.target)
        {
            d = tag('div',{'style': ['width:'+pos.w+'px',
                                     'left:'+pos.x+'px',
                                     'top:'+pos.y+'px',
                                     'position:absolute',
                                     'visibility:hidden',
                                     'background-color:white',
                                     'border:2px solid silver',
                                     nvl(opt.style,'')].join('; ')});
            d.ifr = window.frames[opt.target];
        }
        else
        {
            d = tag('div',{'style': ['width:'+pos.w+'px',
                                     'left:'+pos.x+'px',
                                     'top:'+pos.y+'px',
                                     'position:absolute',
                                     'visibility:hidden',
                                     'background-color:white',
                                     'border:2px solid silver',
                                     nvl(opt.style,'')].join('; ')},
                             '<iframe '+att({'onload':"if (this.contentWindow.document.location=='about:blank') return; lrx.W(this).Par().evStart('init',this.contentWindow,this)",
                                             'style':"width:100%; height:"+pos.h+"px;",
                                             'frameborder':'0',
                                             'name':lrx.rand('box')})+'></iframe>');
            d.ifr = W(d).Last().El();
        }
        d.ifr.dsk = dsk;
        d.ifr.win = d;
        d.frm = W(d).Add(lrx.tag('form',{'target':GET(d.ifr,'name'),
                                      'action':nvl(opt.src,location),
                                      'enctype':'multipart/form-data',
                                      'method':'post',
                                      'style':'display:none'})).El();
        _form_var(d.frm,opt);
        
        W(d).evAdd('setSize',function(sz)
        {
            this.style.width = sz.w+'px';
            this.ifr.style.height = sz.h+'px';
            var msz = {};
            W(this).evStart('getMinSize',msz); 
//            debug(msz.w+' '+msz.h);
            if (msz.w && this.offsetWidth<msz.w) this.style.width = msz.w+'px';
            if (msz.h && this.ifr.offsetHeight<msz.h) this.ifr.style.height = msz.h+'px';
            d.style.visibility='';
        })
        .evAdd('getMinSize',function(sz)
        {
            var bb = this.ifr.contentWindow.document;
            //debug(bb.body.scrollWidth+' '+max(sz.w,bb.body.scrollWidth));
            var b = nvl(bb.documentElement,bb.body);
            sz.w = max(sz.w,b.offsetWidth);
            sz.h = max(sz.h,b.offsetHeight);
        })
        .evAdd('setPos',function(p)
        {
            set_pos(this,p);
        })
        .evAdd('getPos',function(p)
        {
            var pp = get_pos(this);
            p.x=pp.x, 
            p.y=pp.y, 
            p.w=pp.w, 
            p.h=pp.h;
        })
        .evAdd('#rm',function()
        {
            setTimeout(function(){rm(d)},100);
        })
        .evAdd('init',function(win,ifr)
        {
			ev_start(opt,'init',win,ifr);
            W(this).evStart('#init',win,ifr); // prima di invocare gli init vengono invocati gli #init
        })
        .evAdd('close',function()
        {
            W(this).evStart('#rm');
        })
        .evAdd('#start',function()
        {
            W(document.body).Add(d);
            d.frm.submit();
        });
        if (obs &&obs.location) 
        {
            //alert(obs.location);
        }
        lrx.ev_obs(d.ifr,[el,d].merge(WAR(obs)));
        
        return d;
    }
    
    this.box = function (el, opt, obs)
    {
        if (!opt) opt = {};
		if (typeof(opt)=='string') opt = {'src':opt};
		opt.src = nvl(opt.src,location);
        if (!lib.is_dsk()) return dsk.lrx.box(el,opt,obs);
        var pos = get_pos(el);
        opt.x = pos.x;
        opt.y = pos.y+pos.h;
        var b = box(el,opt,obs);
        b.style.zIndex = 1000;
        var h = W(dsk).evAdd('docClick',function(ww)
        {
            if (ww != b.ifr.contentWindow) W(b).evStart('close');
        },1);  
        W(b).evAdd('init',function(win)
        {
            try{
                var d = win.document;
                var bdy = d.body;
                W(b).evStart('setSize',{'w':bdy.scrollWidth,'h':bdy.scrollHeight});
            }catch(e){
                W(b).evStart('setSize',{'w':500,'h':400});
            }
			W(win).evStart('show');
        })
        .evAdd('#rm',function(){h.rm()})
        .evStart('#start');
        return b;     
    }	
    this.win = function (el,opt, obs)
    {
        if (!opt) opt = {};
		if (typeof(opt)=='string') opt = {'src':opt};
		opt.src = nvl(opt.src,location);
        
        if (!lib.is_dsk()) return dsk.lrx.win(el,opt,obs);
        var blk = W(document.body).Add(tag('div',{'style':'background-color:#000000;'})).El();
        var dw = box(el,opt,obs);
        dw.blk = lib.opacity(lrx.expande(blk),30);
        var foot  = W(dw).Fst(lrx.tag('pre',{'style':'position:absolute; bottom:0px; right:0px; cursor:se-resize; font-size: 12px; margin:0px; padding:0px 1px 1px 0px; color:#777777;',
                                         'onselectstart':'return false;',
                                         'onmousedown':"event.preventDefault && event.preventDefault();"},'::')).El();
        var title = W(dw).Fst(lrx.tag('div',{'style':'background-color:#ceddef; border-bottom:1px solid silver; height:22px; overflow:hidden;',
                                         'onselectstart':'return false;',
                                         'onmousedown':"event.preventDefault && event.preventDefault();"})).El();
        var tcmd = W(title).Add(table()).El();
        W(dw).evAdd('getMinSize',function(sz)
		{
            sz.w = max(parseInt(tcmd.offsetWidth),sz.w);
        });
        title.cnt = tcmd.Cell(lrx.tag('div',{'style':'cursor:move; padding:2px 2px 2px 10px; font-weight:bold; white-space:pre;'},'title'),1);
        W(title.cnt).evAdd('mousedown',function(e){move(dw,e);});
        title.cmd = W(tcmd.Cell(table()))
                        .Att('width','1%')
                        .Last()
                        .El();
        title.cmd.bt = {};
        W(dw.ifr).evAdd('#cmd',function(c,o,f)
        {
            if (!o) o = {};
            switch(c)
            {
            case 'add':
                if (typeof(o)=='string') o = {'image':o};
                if (!o['id']) o.id = rand('cmd_');
                var bt;
                if (o.image) bt = tag('img',{'src':o.image,'alt':'Image'});
                else bt = tag('div',{'style':'padding: 2px; margin:3px 3px 3px 0px; border:1px solid silver;'},o.text);
                
                W(bt).evAdd('click',function(ev)
                {
                    f.apply(dw.ifr,[dw.ifr.contentWindow]);
                }); 
                rm(title.cmd.bt[o.id]);
                title.cmd.bt[o.id]=W(title.cmd.Cell(bt,{'make':'left'})).Att('style','cursor:pointer').El();
                break;
            case 'disable':
                break;
            case 'enable':
                break;
            case 'rm':
                if (typeof(o)=='string') o = {'id':o};
                rm(title.cmd.bt[o.id]);
                break;
            case 'pos':
                opt.pos  = function(dw)
                {
                    if (o.x) {dw.style.left = o.x+'px'}
                    if (o.y) {dw.style.top = o.y+'px'}
                }
                break;
            case 'resize':
                if (o=='no') foot.style.display = 'none';
                break;
            }
        });
        W(dw.ifr)
        .evStart('#cmd','add',{'id':'close','text':'x'},function(win)
        {
            lrx.ev_start(dw,'close');
        })
        .evStart('#cmd','add',{'id':'reload','text':'r'},function(win)
        {
            if (win.document.forms[0])
            {
                win.document.forms[0].submit();
            }
            else if (dw.frm)
            {
                dw.frm.submit();
            }
        })
        .evStart('#cmd','resize',opt.resize);
        
        W(foot).evAdd('mousedown',function(e){resize(dw,e,get_pos(title).h);});
        W(dw).evAdd('setTitle',function(ttl)
		{
			title.cnt.innerHTML = ttl;
		}).evAdd('close',function()
        {
            rm(dw.blk);
        }).evAdd('init',function(win)
        {
            function a(el,b,c){if (el.style.visibility=='hidden') return b; return c;}
            try{
                var d = win.document;
                var bdy = d.body;
                W(dw).evStart('setTitle',d.title)
                     .evStart('setSize',{'w':a(this,bdy.scrollWidth,bdy.offsetWidth),'h':a(this,bdy.scrollHeight,bdy.offsetHeight)});
            }catch(e){
                W(dw).evStart('setTitle','Window')
                     .evStart('setSize',{'w':500,'h':400});
            }
            var pp = nvl(opt.pos,center);
            
            switch(typeof(pp))
            {
            case 'function':
                if (!dw.pos) pp(dw,get_pos(dw));
                break;
            }
			if (!opt.noshow) W(win).evStart('show');
        })
        .evStart('#start');
        return dw;
    }
    
    this.exe = function (root,opt,obs)
    {
        if (!opt) opt = {};
        if (GET(root,'exe_msg') && !confirm(GET(root,'exe_msg'))) return;
		if (typeof(opt)=='string') opt = {'src':opt};
		opt.src = nvl(opt.src,location);
        if (!opt.form) opt.form = nvl(root.form,document.forms[0]);
        opt.style='display:none';
		opt.noshow = 1;
        //var w = this.win(root,opt,obs);
        var w = box(root,opt,obs);
        lrx.ev_add(w,'#init',function(win,ifr)
        {
            if (ifr.debug || !(win.document && win.document.body)) 
            {
                w.style.display='';
                lrx.ev_add(w,'click',function(){lrx.ev_start(w,'#rm')});
                return;
            }
            else
            {
                lrx.ev_start(w,'#rm');
            }
            
        });
        lrx.ev_start(w,'#start');
    }
    this.req = function(el,opt,obs)
    {
        var ifr = null;
        var fatr = {'method':'post'};
        if (opt.target) 
        {
            fatr['target'] = opt.target;
            ifr = window.frames[opt.target];
        }
        var f = W(document.body).Add(tag('form',fatr)).El();
        _form_var(f,opt);
        if (ifr)
        {
            lrx.ev_obs_del(ifr);
            lrx.ev_obs(ifr,[el].merge(WAR(obs)));
        }
        f.submit();
        rm(f);
    }
    this.cl_rm = function(el,tag)
    {
        if (el) el.className = el.className.split(' ').remove(tag).join(' ');    
    }
    this.cl_add = function(el,tag)
    {
        if (el) el.className = el.className.split(' ').add(tag).join(' ');
    }
    this.cl_has = function(el,tag)
    {
        if (!el) return false;
        return el.className.split(' ').has(tag);
    }
})();

// quando clicco sul documento lo comunico al dsk
lrx.ev_add(document,'mousedown',function()
{
    lrx.ev_start(dsk,'docClick',window);
});
lrx.ev_add(window,'submit',function(f)
{
	f=nvl(f,document.forms[0]);
	f && f.submit();
});
lrx.ev_add(window,'error',function(msg)
{
    alert('ERRORE : '+msg);
});
lrx.ev_add(window,'href',function(lnk)
{
    location = lnk;
});


