// 1586510542.0
dojo.declare("gnr.GnrBagNode",null,{_counter:[0],constructor:function(parentbag,label,value,_attr,_resolver){this._id=this._counter[0]+=1;this.label=(label=='#id')?genro.time36Id():label;this.locked=false;this._value=null;this.setResolver(_resolver);this.setParentBag(parentbag);this.attr={};this._status='loaded';this._onChangedValue=null;if(_attr){var attr=objectUpdate({},_attr);this.setAttr(attr,false);}
if(value===undefined){value=null;}
if(!_resolver){this.setValue(value,false);this._status='loaded';}},getStringId:function(){return'n_'+this._id;},isExpired:function(){if(!this._resolver){return false;}
else{return this._resolver.expired();}},isLoaded:function(){return(this._status=='loaded');},isLoading:function(){return(this._status=='loading');},getParentNode:function(){if(this._parentbag){return this._parentbag._parentnode;}},getParentBag:function(){if(this._parentbag){return this._parentbag;}},orphaned:function(){this._parentbag=null;if(isBag(this._value)){this._value.clearBackRef();}
return this;},isChildOf:function(bagOrNode){var node=bagOrNode instanceof gnr.GnrBagNode?bagOrNode:bagOrNode.getParentNode();var curr=this;var parentNode;do{parentNode=curr.getParentNode();curr=parentNode;}while(parentNode&&parentNode!==node);return!isNullOrBlank(parentNode);},setParentBag:function(parentbag){this._parentbag=null;if(parentbag!=null){this._parentbag=parentbag;if(parentbag.hasBackRef()){if(isBag(this._value)){this._value.setBackRef(this,parentbag);}}}},getFullpath:function(mode,root){var segment;var fullpath='';var parentbag=this.getParentBag();if(parentbag){fullpath=parentbag.getFullpath(mode,root);if(mode=='#'||mode=='##'){segment=parentbag.getNodes().indexOf(this);if(mode=='##'){segment='#'+segment;}}else{segment=this.label;}
if(fullpath){fullpath=fullpath+'.'+segment;}
else{fullpath=segment;}}
return fullpath;},backrefOk:function(){return this._parentbag.backrefOk();},getValue2:function(mode,optkwargs){console.log('called by meToo')
var result=this.getValue('static');console.log('result getValue2',result)
return result;},getFormattedValue:function(kw,mode){var v=this.getValue(mode);kw=kw||{};kw.joiner=kw.joiner||'<br/>';kw.omitEmpty='omitEmpty'in kw?kw.omitEmpty:true;if(v instanceof gnr.GnrBag){if(this.attr._autoTable){v=v.asHtmlTable(objectUpdate(kw,{headers:true,cells:true}));}else{v=v.getFormattedValue(kw,mode);}}else{v=this.attr._formattedValue||this.attr._displayedValue||v;}
return(!isNullOrBlank(v)||!kw.omitEmpty)?((this.attr._valuelabel||this.attr.name_long||stringCapitalize(this.label))+': '+_F(v,null,this.attr.dtype)):'';},getValue:function(mode,optkwargs){mode=mode||'';if((this._resolver==null)||(mode.indexOf('static')>=0)||(this._status=='loading')){return this._value;}
if(this._resolver.isGetter){var finalize=function(r){return r;};var result=this._resolver.resolve(optkwargs,this);if(result instanceof dojo.Deferred){return result.addCallback(finalize);}else{return finalize(result);}}
else if(this._status=='resolving'){return this._resolver.meToo(dojo.hitch(this,"getValue2",mode,optkwargs));}
else if((this._status=='loaded')&&(!this._resolver.expired())&&(mode.indexOf('reload')<0)){return this._value;}
else{this._status='resolving';var fullpath=this.getFullpath();var result=this._resolver.resolve(optkwargs,this);var finalize=dojo.hitch(this,function(result){this._status='loading';this.setValue(result,(mode=='notrigger'?false:'resolver'));this._status='loaded';if(this._resolver._pendingDeferred.length>0){var pendingDeferred=this._resolver._pendingDeferred;this._resolver._pendingDeferred=[];setTimeout(dojo.hitch(this._resolver,"runPendingDeferred",pendingDeferred),1);}
if(this._resolver.onloaded){this._resolver.onloaded.call(this);}
return this._value;});if(result instanceof dojo.Deferred){return result.addCallback(finalize);}
else{return finalize(result);}}},clearValue:function(doTrigger){this.setValue(null,doTrigger);return this;},setValue:function(value,doTrigger,_attributes,_updattr,_fired){if(value instanceof gnr.GnrBagResolver){this.setResolver(value);value=null;}
else if(value instanceof gnr.GnrBagNode){var attr={};if(_updattr){objectUpdate(attr,this.attr);}
objectUpdate(attr,value.attr);objectUpdate(attr,_attributes||{});var resolver=value.getResolver();value=value._value;if(resolver){this.setResolver(resolver);}
_attributes=attr;}
if(doTrigger==null){doTrigger=true;}
if(this.locked==true){alert("error");}
var oldvalue=this._value;var oldattr;var updated_attr=false;this._value=value;if(_attributes){updated_attr=true;oldattr=objectUpdate({},this.attr);this.setAttr(_attributes,false,_updattr);}
if(this._onChangedValue){this._onChangedValue(this,value,oldvalue,doTrigger);}
if(this._parentbag&&this._parentbag._backref){if(oldvalue!==value){if(isBag(oldvalue)){oldvalue.clearBackRef();}}
if(isBag(value)){value.setBackRef(this,this._parentbag);}
if(doTrigger){this._parentbag.onNodeTrigger({'evt':'upd','node':this,'pathlist':[this.label],'oldvalue':oldvalue,'value':value,'oldattr':oldattr,'updvalue':true,'updattr':updated_attr,'reason':doTrigger,'fired':_fired});}}},refresh:function(always){if(always||this.isExpired()){this.getValue('reload');}},getStaticValue:function(){return this._value;},setStaticValue:function(value){this._value=value;},setResolver:function(resolver){if(resolver){resolver._parentNode=this;resolver.onSetResolver(this);}
this._resolver=resolver;this._status='unloaded';},getResolver:function(){return this._resolver;},resetResolver:function(){this._resolver.reset();},getAttr:function(label,_default){if(label){if(label in this.attr){return this.attr[label];}else{return _default||null;}}
return this.attr;},getInheritedAttributes:function(attrname){var curr=this;if(attrname){while(curr&&!curr.attr[attrname]){curr=curr.getParentNode();}
return curr?curr.attr[attrname]:null;}else{var inherited={};var parentnode=this.getParentNode();if(parentnode){inherited=parentnode.stopInherite?objectUpdate(inherited,parentnode.attr):parentnode.getInheritedAttributes();}
return objectUpdate(inherited,this.attr);}},isAncestor:function(n){do{if(n&&(n._id==this._id)){return true;}
n=n.getParentNode();}while(n)
return false;},isDescendant:function(n){return n.isAncestor(this);},attributeOwnerNode:function(attrname,attrvalue,caseInsensitive){var curr=this;var currattr=curr.attr||{};if(arguments.length==1){if(attrname.indexOf(',')<0){while(curr&&!(attrname in curr.attr)){curr=curr.getParentNode();}}else{attrname=attrname.split(',');while(curr&&!dojo.some(attrname,function(n){return(n in curr.attr)})){curr=curr.getParentNode();}}}else if(caseInsensitive){while(curr&&(curr.attr[attrname]||'').toLowerCase()!=(attrvalue||'').toLowerCase()){curr=curr.getParentNode();}}else{while(curr&&curr.attr[attrname]!=attrvalue){curr=curr.getParentNode();}}
return curr;},hasAttr:function(label,value){if(label in this.attr){if(value){return(this.attr[label]==value);}else{return true;}}else{return false;}},replaceAttr:function(attributes){this.attr={};this.setAttr(attributes);},setAttribute:function(label,value,doTrigger){var updDict={};updDict[label]=value;this.setAttr(updDict,doTrigger,'*',label);},updAttributes:function(attrDict,doTrigger){this.setAttr(attrDict,doTrigger,true);},setAttr:function(attr,doTrigger,updateAttr,changedAttr){if(doTrigger==null){doTrigger=true;}
var oldattr=objectUpdate({},this.attr);if(updateAttr){this.attr=objectUpdate(this.attr,attr,updateAttr=='*');}else{this.attr=attr;}
if(doTrigger){var changedAttributes={};for(var k in this.attr){if(!(k in oldattr)||oldattr[k]!==this.attr[k]){changedAttributes[k]=true;}}
if(this._parentbag&&this._parentbag._backref){this._parentbag.onNodeTrigger({'evt':'upd','node':this,'pathlist':[this.label],'oldattr':oldattr,'updattr':true,reason:doTrigger,'changedAttr':changedAttr,'changedAttributes':changedAttributes});}}},delAttr:function(attrToDelete){if(typeof(attrToDelete)=="string"){attrToDelete=attrToDelete.split(',');}
for(var i=0;i<attrToDelete.length;i++){delete this.attr[attrToDelete[i]];}},_toXmlBlock:function(kwargs){if(this.getResolver()){var nodeValue=this.getValue('static');}else{var nodeValue=this.getValue();}
var result='';if(isBag(nodeValue)){result=xml_buildTag(this.label,nodeValue.toXmlBlock(kwargs),objectUpdate({_T:'bag'},this.getAttr()),true);}else{result=xml_buildTag(this.label,nodeValue,this.getAttr());}
return result;},toJSONString:function(){return{'label':this.label,'value':this._value,'attr':this.attr}.toJSONString();},doWithValue:function(cb,kwargs){var value=this.getValue('',kwargs);if(value instanceof dojo.Deferred){return value.addCallback(cb);}else{return cb(value);}},parentshipLevel:function(node){if(this==node){return 0;}
var parentNode=this.getParentNode();var n=parentNode?parentNode.parentshipLevel(node):-1;return(n>=0)?n+1:n;}});dojo.declare("gnr.GnrBag",null,{_nodeFactory:gnr.GnrBagNode,constructor:function(source,kw){this._nodes=[];this._backref=false;this._parentnode=null;this._parent=null;this._symbols=null;this._subscribers={};if(source){this.fillFrom(source,kw);}},newNode:function(parentbag,label,value,_attr,_resolver){return new this._nodeFactory(parentbag,label,value,_attr,_resolver);},fillFrom:function(source,kw){var sourceType=guessDtype(source);var dest=this;if(sourceType=='AR'){var firstElemType=guessDtype(source[0]);if(firstElemType=='AR'){source.forEach(function(elem,idx){dest.setItem(elem[0],elem[1],elem[2]);});}else if(firstElemType=='OBJ'){source.forEach(function(elem,idx){dest.setItem('r_'+idx,new gnr.GnrBag(elem),{_autolist:true});});}}else if(sourceType=='X'){source.forEach(function(node){dest.setItem(node.label,node.getValue(),objectUpdate({},node.getAttr()));});}else if(sourceType=='T'){var parser=new window.DOMParser();this.fromXmlDoc(parser.parseFromString(source,'text/xml'),genro.clsdict);}
else if(sourceType=='OBJ'){for(var k in source){var val=source[k];var valType=guessDtype(val);if(valType=='FUNC'){continue;}else if(valType=='OBJ'||valType=='AR'){val=new gnr.GnrBag(val);}
this.setItem(k,val);}}},getParent:function(){if(this._parent)return this._parent;},setParent:function(parent){this._parent=parent;},setParentNode:function(node){this._parentnode=node;},getParentNode:function(){return this._parentnode;},attributes:function(){if(this._parentnode){return this._parentnode.attr;}},resolver:function(){if(this._parentnode){return this._parentnode._resolver;}},asHtmlTable:function(kw,mode){kw=kw||{};var datamode=kw.datamode||'bag';var headers=kw.headers;var h='';var hheadcel=datamode=='bag'?this.getItem('#0'):new gnr.GnrBag(this.getAttr('#0'));if(headers&&hheadcel){if(headers===true){headers='';hheadcel.forEach(function(n){var calclabel=(n.attr._valuelabel||n.attr.name_long||stringCapitalize(n.label));headers+=headers?','+calclabel:calclabel;})}
h='<thead>';headers=headers.split(',');dojo.forEach(headers,function(th){h+='<th>'+th+'</th>';});h+='</thead>';}
var rows='';var r,b,v,vnode,cell_kw,format,cells,dtype,style;if(kw.cells===true){cells=hheadcel.keys();}else{cells=kw.cells.split(',');}
this.forEach(function(n){r='';if(datamode=='bag'){b=n._value;}else{b=new gnr.GnrBag(n.attr);}
dojo.forEach(cells,function(cell){var align='left';vnode=b.getNode(cell);cell_kw=kw[cell]||{};if(vnode){v=vnode._value;if(v instanceof gnr.GnrBag){v=v.getFormattedValue(kw,mode);}else if(isNullOrBlank(v)){v='';}
else{dtype=cell_kw.dtype||vnode.attr.dtype||guessDtype(v);format=typeof(cell_kw)=='string'?cell_kw:cell_kw.format;if(format){v=_F(v,format,dtype);}else{v=vnode.attr._formattedValue||vnode.attr._displayedValue||v;}
if(dtype=='N'||dtype=='L'){align='right';}}}else{v='';}
if(cell_kw.width){v='<div style="width:'+cell_kw.width+';">'+v+'</div>'}
r+='<td style="text-align:'+align+'">'+v+'</td>';});rows+='<tr>'+r+'</tr>';},'static');return'<table class="selectable formattedBagTable">'+h+'<tbody>'+rows+'</tbody></table>';},asNestedTable:function(kw,mode){var rows=[];this.forEach(function(n){var v=n.getValue(mode);if(v instanceof gnr.GnrBag){v=n.attr._autoTable?v.asHtmlTable({headers:true,cells:true}):v.asNestedTable(kw,mode);}
if(kw.omitEmpty&&isNullOrBlank(v)){return;}
if(!n.attr._autolist){rows+='<tr><td class="_bagformat_lbl">'+n.label+'</td>';}
rows+='<td class="_bagformat_value">'+_F(v,null,n.attr.dtype)+'</td></tr>';},mode);return'<table class="nestedBagTable"><tbody>'+rows+'</tbody></table>';},getFormattedValue:function(kw,mode){kw=kw||{};kw.omitEmpty='omitEmpty'in kw?kw.omitEmpty:true;if(this._parentnode&&this._parentnode.attr.format_bag_cells){return this.asHtmlTable(objectExtract(this._parentnode.attr,'format_bag_*',true));}else if(kw.cells){return this.asHtmlTable(kw);}else if(kw.nested){return this.asNestedTable(kw,mode);}
var r=[];kw.joiner=kw.joiner||'<br/>';var fv;this.forEach(function(n){if(n.label[0]!='_'){fv=n.getFormattedValue(kw,mode);if(kw.omitEmpty&&isNullOrBlank(fv)){return;}
r.push(fv);}},mode);return r.join(kw.joiner);},getItem:function(path,dft,mode,optkwargs){var dft=(dft=='')?dft:dft||null;if(!path){return this;}
var finalize=function(res){var m=mode;var obj=res.value;var label=res.label;if(isBag(obj)){return obj.get(label,dft,m,optkwargs);}
else{return dft;}};var res=this.htraverse(path);if(res instanceof dojo.Deferred){return res.addCallback(finalize);}else{return finalize(res);}},sort:function(pars){var innerCmp=function(a,b,reverse,caseInsensitive){if(caseInsensitive){if(typeof(a)=='string'){var a=a.toLowerCase();}
if(typeof(b)=='string'){var b=b.toLowerCase();}}
if(a==b){return 0;}
else if(reverse){if(a<b){return 1;}
else{return-1;}}else{if(a>b){return 1;}
else{return-1;}}};var cmp=function(a,b,reverse,caseInsensitive){if(a===null&&b===null){return 0;}
if(a===null||b===null){var r=a===null?-1:1;return reverse?r*-1:r;}
if((a instanceof Date)&&(b instanceof Date)){a=a.valueOf();b=b.valueOf();}
return innerCmp(a,b,reverse,caseInsensitive);}
var pars=pars||'#k:a';var level,what,mode,reverse,caseInsensitive;var levels=pars.split(',');levels.reverse();for(var i=0;i<levels.length;i++){level=levels[i];if(level.indexOf(':')>=0){level=level.split(':');what=level[0];mode=level[1];}else{what=level;mode='a';}
what=stringStrip(what);mode=stringStrip(mode).toLowerCase();if(stringEndsWith(mode,'*')){caseInsensitive=true;mode=mode.slice(0,-1);}else{caseInsensitive=false;}
reverse=!((mode=='a')||(mode=='asc')||(mode=='>'));if(what=='#k'){this._nodes.sort(function(a,b){return cmp(a.label,b.label,reverse,caseInsensitive);});}else if(what=='#v'){this._nodes.sort(function(a,b){return cmp(a.getValue(),b.getValue(),reverse,caseInsensitive);});}else if(what.indexOf('#a')>=0){var attrname=what.slice(3);this._nodes.sort(function(a,b){return cmp(a.getAttr(attrname),b.getAttr(attrname),reverse,caseInsensitive);});}else{this._nodes.sort(function(a,b){return cmp(a.getValue().getItem(what),b.getValue().getItem(what),reverse,caseInsensitive);});}}},sum:function(path){var result=0;var n;path=path||'#v';if(path){var l=this.digest(path);for(var i=0;i<l.length;i++){n=l[i][0];if(typeof n=='number'){result=result+n;}}}
return result;},get:function(label,dflt,mode,optkwargs){var result=null;var currnode=null;var currvalue=null;var getter;var m;if(!label){currnode=this._parentnode;currvalue=this;}
else if(label=='#parent'){currnode=this._parent.getNode();}
else{m=label.match(/(.*?)([?|~])([^?|^=]*)(\??)(.*)/);if(m){label=m[1];}
var i=this.index(label);if(i<0){return dflt;}
else{currnode=this._nodes[i];}}
if(currnode){currvalue=currnode.getValue(mode,optkwargs);}
if(!m){return currvalue;}
var finalize=function(currvalue){var expr=m[5];if(m[2]=='?'){var attrname=m[3];if(attrname){if(attrname=='#attr'){return currnode.attr;}
if(attrname=='#keys'){return currvalue.keys();}
if(attrname=='#node'){return currnode;}
if(attrname.indexOf('#digest:')==0){return currvalue.digest(attrname.split(':')[1]);}
currvalue=currnode.getAttr(attrname)}else if(!expr){return currnode.attr;}}else if(m[2]=='~'){currvalue=(currnode._value instanceof gnr.GnrBag)?currnode._value.getItem(m[3]):currnode.getAttr(m[3]);}
if(!expr){return currvalue;}
if(expr.indexOf('=')==0){genro.__evalAuxValue=currvalue;expr=expr.slice(1).replace(/#v/g,'genro.__evalAuxValue');currvalue=dojo.eval(expr);return currvalue;}};if(currvalue instanceof dojo.Deferred){return currvalue.addCallback(finalize);}
else{return finalize(currvalue);}},htraverse:function(pathlist,autocreate){var curr=this;if(typeof pathlist=="string"){var m=pathlist.match(/(.*?)([?|~])(.*)/);if(m){pathlist=smartsplit(m[1].replace(/\.\.\//g,'#parent.'),'.');pathlist[pathlist.length-1]=pathlist[pathlist.length-1]+m[2]+m[3]}else{pathlist=smartsplit(pathlist.replace(/\.\.\//g,'#parent.'),'.');}
if(!pathlist){return{value:curr,label:''};}}
var label=pathlist.shift();while(label=='#parent'&&pathlist){curr=curr.getParent();label=pathlist.shift();}
if(pathlist.length==0){return{"value":curr,"label":label};}
var i=curr.index(label);if(i<0){if(autocreate){if(label&&label.charAt(0)=='#'){label=label.replace('#','_');}
i=curr._nodes.length;var newbag=new curr.constructor();var newnode=curr.newNode(curr,label,newbag);curr._nodes.push(newnode);if(curr._backref){curr.onNodeTrigger({'evt':'ins','node':newnode,'where':curr,'ind':i,'reason':'autocreate'});}}
else return{"value":null,"label":null};}
var finalize=dojo.hitch(this,function(newcurr){var isbag=isBag(newcurr);if(autocreate&&!isbag){var newcurr=new curr.constructor();this._nodes[i].setValue(newcurr,false);isbag=true;}
if(isbag){var result=newcurr.htraverse(pathlist,autocreate);if(result instanceof dojo.Deferred){return result.addCallback(function(r){return r;});}else{return result;}}
else{return{"value":newcurr,"label":pathlist.join(".")};}});var newcurr=curr._nodes[i].getValue();if(newcurr instanceof dojo.Deferred){return newcurr.addCallback(finalize);}else{return finalize(newcurr);}},len:function(){return this._nodes.length;},__str2__:function(mode){var mode=mode||'static';var outlist=[];var el=null;var attrString='';var j=0;var key;var value=null;for(var i=0;i<this._nodes.length;i++){el=this._nodes[i];for(key in el.attr){attrString=attrString+key+'='+el.attr[key]+' ';}
if(attrString!=''){attrString='||'+attrString+'||';}
value=el.getValue(mode);if(isBag(value)){outlist.push(i+'-('+value.declaredClass+') '+el.label+': '+attrString);if(el.visited){innerbagstr='visited at: '+el.label;}else{el.visited=true;var inner=value.__str2__(mode).split('\n');var auxlist=[];for(var u=0;u<inner.length;u++){var line=inner[u];auxlist.push('----'+line);}
var innerbagstr=auxlist.join('\n');}
outlist.push(innerbagstr);}else{outlist.push(i+'-('+(value.declaredClass||typeof value)+') '+el.label+': '+value.toString()+' '+attrString);}}
return outlist.join('<br/>');},__str__:function(mode){var mode=mode||'static';var outlist=[];var el=null;var attrString='';var j=0;var key;var value=null;for(var i=0;i<this._nodes.length;i++){el=this._nodes[i];for(var key in el.attr){attrString=attrString+key+'='+el.attr[key]+' ';}
if(attrString!=''){attrString='<'+attrString+'>';}
value=el.getValue(mode);if(isBag(value)){outlist.push(i+'-('+value.declaredClass+') '+el.label+': ');if(el.visited){innerbagstr='visited at: '+el.label;}else{el.visited=true;var inner=value.__str__(mode).split('\n');var auxlist=[];for(var u=0;u<inner.length;u++){var line=inner[u];auxlist.push('----'+line);}
var innerbagstr=auxlist.join('\n');}
outlist.push(innerbagstr);}else{var v=convertToText(value);outlist.push(i+'-('+v[0]+') '+el.label+': '+v[1]+' '+attrString);}}
return outlist.join('\n');},asString:function(){return this.__str2__();},keys:function(){var keys=[];for(var i=0;i<this._nodes.length;i++){keys.push(this._nodes[i].label);}
return keys;},values:function(){var values=[];for(var i=0;i<this._nodes.length;i++){values.push(this._nodes[i].getValue());}
return values;},items:function(){var items=[];for(var i=0;i<this._nodes.length;i++){items.push({key:this._nodes[i].label,value:this._nodes[i].getValue()});}
return items;},digest:function(what,asColumns){var obj=null;if(what==null){what='#k,#v,#a';}
if(what.indexOf(':')!=-1){var s=what.split(':');var where=s[0];what=s[1];obj=this.getNode(where);}
else{obj=this;}
var result=[];var nodes=obj._nodes;var wl=what.split(',');var w=null;var aux=[];var path='';var value=null;var x=null;for(var i=0;i<wl.length;i++){var ll=null;value=null;aux=[];w=wl[i];if(w=='#k'){for(var j=0;j<nodes.length;j++){aux.push(nodes[j].label);}
result.push(aux);}
else if(w=='#v'){for(var j=0;j<nodes.length;j++){aux.push(nodes[j].getValue());}
result.push(aux);}
else if(w.slice(0,3)=='#v.'){ll=w.split('.');w=ll.shift();path=ll.join('.');for(var j=0;j<nodes.length;j++){x=nodes[j];value=x.getValue();if(isBag(value)){aux.push(value.getItem(path));}
else{aux.push(null);}}
result.push(aux);}
else if(w=='#__v'){for(var j=0;j<nodes.length;j++){aux.push(nodes[j].getValue('static'));}
result.push(aux);}
else if(w.slice(0,2)=='#a'){var attr=null;if(w.indexOf('.')!=-1){ll=w.split('.');attr=ll[1];w=ll[0];}
if(w=='#a'){for(var j=0;j<nodes.length;j++){x=nodes[j];aux.push(x.getAttr(attr));}
result.push(aux);}}
else{for(var j=0;j<nodes.length;j++){x=nodes[j];value=x.getValue();if(isBag(value)){aux.push(value.getItem(w));}else{aux.push(null);}}
result.push(aux);}}
if(asColumns){return result;}
return zip(result);},columns:function(cols,attrMode){var mode=(attrMode)?'#a.':'';if(typeof(cols)=='string'){cols=cols.split(',');}
for(var i=0;i<cols.length;i++){cols[i]=mode+cols[i];};return this.digest(cols.join(','),true);},asObj:function(formatAttributes){var nodes=this._nodes;var result={};var v,node,attr;for(var i=0;i<nodes.length;i++){node=nodes[i];if(!node._resolver){result[node.label]=node.getValue();}else{result[node.label]='**';}}
for(attr in formatAttributes){result[attr]=asText(result[attr],formatAttributes[attr]);}
return result;},asObjList:function(labelAs,formatAttributes){formatAttributes=formatAttributes||{};var nodes=this._nodes;var result=[];for(var i=0;i<nodes.length;i++){var item=nodes[i].getValue().asObj(formatAttributes);if(labelAs){item[labelAs]=nodes[i].label;}
result.push(item);}
return result;},getResolver:function(path){return this.getNode(path).getResolver();},getNodes:function(condition){return condition?this._nodes.filter(condition):this._nodes;},pop:function(path,doTrigger){var n=this.popNode(path,doTrigger);if(n){return n.getValue()}},delItem:function(path,doTrigger){this.pop(path,doTrigger);},moveNode:function(fromPos,toPos,doTrigger){if(toPos<0){return;}
var doTrigger=(doTrigger==null)?true:doTrigger;var destlabel=this.getNodes()[toPos].label;if(fromPos instanceof Array&&fromPos.length>1){fromPos.sort();var delta=(fromPos[0]<toPos)?1:0;var popped=[];for(var i=fromPos.length-1;i>=0;i--){popped.push(this._pop('#'+fromPos[i],doTrigger));}
var toPos=this.index(destlabel)+delta;var bag=this;dojo.forEach(popped,function(n){bag._insertNode(n,toPos,doTrigger);});}else{if(fromPos instanceof Array){fromPos=fromPos[0];}
if(toPos!=fromPos){var node=this._pop('#'+fromPos,doTrigger);this._insertNode(node,toPos,doTrigger);}}},popNode:function(path,doTrigger){var node=this.htraverse(path);var obj=node.value;var label=node.label;if(obj){var n=obj._pop(label,doTrigger);if(n){return n.orphaned();}}},_pop:function(label,doTrigger){if(doTrigger==null){doTrigger=true;};var p=this.index(label);var node=null;if(p>=0){node=this._nodes[p];var sx=this._nodes.slice(0,p);var dx=this._nodes.slice(p+1,this._nodes.length);this._nodes=sx.concat(dx);if(this._backref&&doTrigger){this.onNodeTrigger({'evt':'del','node':node,'where':this,'ind':p,'reason':doTrigger});}}
return node;},clear:function(triggered){if(!triggered){this._nodes.splice(0,this._nodes.length);}else{var n;while(this._nodes.length>0){n=this._nodes.pop();if(this._backref)
this.onNodeTrigger({'evt':'del','node':n,'where':this,ind:this._nodes.length});}}},merge:function(){},update:function(bagOrObj,mode,reason){var kwargs;if(reason){kwargs={doTrigger:reason}}
if(!(bagOrObj instanceof gnr.GnrBag)){for(var k in bagOrObj){this.setItem(k,bagOrObj[k]);}
return;}
var that=this;bagOrObj.forEach(function(n){var node_resolver=n.getResolver();var node_value=null;if(!node_resolver||mode!='static'){node_value=n.getValue();node_resolver=null;}
var currNode=that.getNode(n.label);if(currNode){currNode.updAttributes(n.attr,reason);currNodeValue=currNode.getValue();if(node_resolver){currNode.setResolver(node_resolver);}
if((node_value instanceof gnr.GnrBag)&&(currNodeValue instanceof gnr.GnrBag)){currNodeValue.update(node_value,mode,reason)}else{currNode.setValue(node_value,reason);}}else{that.setItem(n.label,node_value,n.attr,kwargs);}},mode);},concat:function(b){if(!b){return;}
var that=this;dojo.forEach(b._nodes,function(n){n.setParentBag(that);that._nodes.push(n);});},deepCopy:function(deep){var mode=deep?'':'static';var result=new gnr.GnrBag();var node;var bagnodes=this.getNodes();for(var i=0;i<bagnodes.length;i++){node=bagnodes[i];var value=node.getValue(mode);value=isBag(value)?value.deepCopy(deep):value;result.setItem(node.label,value,objectUpdate({},node.attr));}
return result;},getNodeByAttr:function(attr,value,caseInsensitive){var existAttr=arguments.length==1;var value=caseInsensitive?value.toLowerCase():value;var f=function(n){if(attr in n.attr){if(existAttr||(caseInsensitive?((n.attr[attr]||'').toLowerCase()==value):(n.attr[attr]==value))){return n;}}};return this.walk(f,'static');},getNodeByValue:function(path,value){var nodes=this._nodes;var n;for(var i=0;i<nodes.length;i++){n=nodes[i];if(n.getValue().getItem(path)===value){return n;};}
return;},getNode:function(path,asTuple,autocreate,_default){if(!path){return this.getParentNode();}
var mynode=this.htraverse(path,autocreate);var obj=mynode.value;var label=mynode.label;var node=null;if(obj){if(label.indexOf('?')>=0){var splittedlabel=label.split('?');label=splittedlabel[0];node=obj._getNode(label,autocreate);if(_default){node.attr[splittedlabel[1]]=_default;}}else{node=obj._getNode(label,autocreate,_default);}
if(asTuple==true){return{"obj":obj,"node":node};}}
return node;},_getNode:function(label,autocreate,_default){var p=this.index(label);var node=null;if(p>=0){node=this._nodes[p];}
else if(autocreate){node=this.newNode(this,label,_default);var i=this._nodes.length;this._nodes=this._nodes.concat(node);if(this._backref){this.onNodeTrigger({'evt':'ins','node':node,'where':this,'ind':i,'reason':'autocreate'});}}
return node;},setAttr:function(path,attr,args){this.getNode(path,false,true).setAttr(attr);},getAttr:function(path,attr,dflt){var node=this.getNode(path);if(node!=null){return node.getAttr(attr,dflt);}else{return dflt;}},pathsplit:function(){},asDict:function(recursive,excludeNullValues){var isArray=this._nodes.some(function(n){return n.attr._autolist});var node,value;var result=isArray?[]:{};for(var i=0;i<this._nodes.length;i++){node=this._nodes[i];value=node.getValue();if(excludeNullValues){if(value===null||value instanceof gnr.GnrBag&&value.len()===0){continue;}}
if(recursive&&(value instanceof gnr.GnrBag)){if(recursive=='flat'){objectUpdate(result,value.asDict(recursive,excludeNullValues));continue;}else{value=value.asDict(recursive,excludeNullValues);}}
if(isArray){result.push(value);}else{if(typeof(value)!='string'||!stringEndsWith(value,'::JS')){result[node.label]=value;}}}
return result;},addItem:function(path,value,_attributes,kwargs){if(!kwargs){var kwargs={};}
kwargs['_duplicate']=true;return this.setItem(path,value,_attributes,kwargs);},fireItem:function(path,value,attributes,reason){value=value==null?true:value;this.setItem(path,value,attributes,{'doTrigger':reason==null?true:reason,fired:true});this.setItem(path,null,attributes,{'doTrigger':false});},rowchild:function(tag,kw){var label;if(tag.startsWith('#')){label=kw[tag.slice(1)];}else{label=tag+'_'+genro.time36Id();}
genro.assert(label,'Missing label in this node');this.setItem(label,null,kw);},setItem:function(path,value,_attributes,kwargs){if(!kwargs){var kwargs={};}
if(path==''){if(isBag(value)){for(var i=0;i<value.getNodes().length;i++){var node=value.getNodes()[i];var v=node.getResolver()||node.getValue();this.setItem(node.label,v,node.getAttr());}}
else if(value instanceof Object){for(var i in value){this.setItem(i,value[i].valueOf());}}
return this;}
else{var mynode=this.htraverse(path,true);var cb=function(mynode,value){var obj=mynode.value;var label=mynode.label;if(label.indexOf('?')>=0){var splittedlabel=label.split('?');label=splittedlabel[0];var attr=splittedlabel[1];var node=obj.getNode(label,false,true);if(kwargs.lazySet&&isEqual(node.attr[attr],value)){return;}
var auxattr={};auxattr[attr]=value;var _doTrigger=true;if('doTrigger'in kwargs){_doTrigger=kwargs.doTrigger;}
node.setAttr(auxattr,_doTrigger,'*',attr);return node;}
else{return obj.set(label,value,_attributes,kwargs);}};if(mynode instanceof dojo.Deferred){mynode.addCallback(cb,value);}
else{return cb(mynode,value);}}},set:function(label,value,_attributes,kwargs){if(!kwargs){var kwargs={};}
var resolver=null;var _duplicate=kwargs._duplicate||false;var _updattr=kwargs._updattr||false;var _doTrigger=true;if('doTrigger'in kwargs){_doTrigger=kwargs.doTrigger;}
if(value instanceof gnr.GnrBagResolver){resolver=value;value=null;if(objectSize(resolver.attributes)>=0){_attributes=objectUpdate({},_attributes);_attributes=objectUpdate(_attributes,resolver.attributes);}}
var i=_duplicate?-1:this.index(label);if(i<0){if((label!='#id')&&(label[0]=='#')){return null;}
else{var nodeToInsert=this.newNode(this,label,value,_attributes,resolver);kwargs._new_position=this._insertNode(nodeToInsert,kwargs._position,_doTrigger);kwargs._new_label=nodeToInsert.label;return nodeToInsert;}}
else{var node=this._nodes[i];if(resolver){node.setResolver(resolver);}
if(kwargs.lazySet){if(isEqual(node._value,value)){return node;}}
node.setValue(value,_doTrigger,_attributes,_updattr,kwargs.fired);return node;}},_insertNode:function(node,position,_doTrigger){var n=null;var label;if(typeof(position)=='number'){n=position;}
else if(position==0||position=='<'){n=0;}else if(!position||position=='>'){n=-1;}
else if(position.charAt(0)=='#'){n=parseInt(position.slice(1));}
else{if(position.charAt(0)=='<'||position.charAt(0)=='>'){label=position.slice(1);position=position.charAt(0);}
else{label=position;position='<';}
if(label.charAt(0)=='#'){n=parseInt(label.slice(1));}
else{n=this.index(label);}
if(position=='>'&&n>=0){n=n+1;}}
if(n<0){n=this._nodes.length;}
this._nodes.splice(n,0,node);if(this._backref&&_doTrigger){this.onNodeTrigger({'evt':'ins','node':node,'where':this,'ind':n,'reason':_doTrigger});}
return n;},index:function(label){var result=-1;var idx;if(label){if(label[0]=='#'){if(label.indexOf('=')!=-1){var myarr=label.slice(1).split('=');var k=myarr[0];var v=convertFromText(myarr[1]);if(!k)k='id';for(idx=0;idx<this._nodes.length;idx++){if(this._nodes[idx].attr[k]==v){result=idx;break;}}}
else{idx=parseInt(label.slice(1));if(idx<this._nodes.length){result=idx;}}}
else{for(idx=0;idx<this._nodes.length;idx++){if(this._nodes[idx].label==label){result=idx;break;}}}}
return result;},findNodeById:function(id){var f=function(n){if(n._id==id){return n;}};return this.walk(f,'static');},forEach:function(callback,mode,kw){this.walk(callback,'static',kw,true);},walk:function(callback,mode,kw,notRecursive){var result;var bagnodes=this.getNodes();for(var i=0;((i<bagnodes.length)&&((result==null)||(result=='__continue__')));i++){result=callback(bagnodes[i],kw,i);if(result==null&&!notRecursive){var value=bagnodes[i].getValue(mode);if(isBag(value)){result=value.walk(callback,mode,kw);}}}
return result;},getBackRef:function(){return this._backref;},hasBackRef:function(){return(this._backref==true);},setBackRef:function(node,parent){this._backref=true;this._parent=parent;this._parentnode=node;for(var i=0;i<this._nodes.length;i++){this._nodes[i].setParentBag(this);}},clearBackRef:function(){var node,value;if(this._backref){this._backref=false;this._parent=null;this._parentnode=null;for(var i=0;i<this._nodes.length;i++){node=this._nodes[i];value=node.getStaticValue();if(isBag(value)){value.clearBackRef();}}}},backrefOk:function(){return this._parentnode._parentbag===this._parent;},runTrigger:function(kw){var callbacks,cb;for(var subscriberId in this._subscribers){callbacks=this._subscribers[subscriberId];cb=callbacks[kw.evt]||callbacks.any;if(cb){cb(kw);}}},onNodeTrigger:function(kw){kw.pathlist=kw.pathlist||[kw.node.label];kw.base=this;this.runTrigger(kw);if(this._parent!=null){kw.pathlist=[this._parentnode.label].concat(kw.pathlist);this._parent.onNodeTrigger(kw);}},subscribe:function(subscriberId,kwargs){if(this._backref==false){this.setBackRef();}
this._subscribers[subscriberId]=kwargs;},unsubscribe:function(subscriberId,events){delete this._subscribers[subscriberId];},fromXmlDoc:function(source,clsdict){var attributes,aux;var j;var node;var attrname,attrvalue;var childnode,istxtnode,convertAs;var resolverPars=null;var js_resolver=null;var js_resolvedInfo=null;var root=source;if(root.nodeType==9){root=root.lastChild;}
for(var i=0;i<root.childNodes.length;i++){node=root.childNodes[i];convertAs='T';if(node.nodeType==1){var tagName=node.tagName||node.nodeName;attributes={};resolverPars=null;js_resolver=null;js_resolvedInfo=null;for(j=0;j<node.attributes.length;j++){attrname=node.attributes[j].name;attrvalue=node.attributes[j].value;if(attrname=='_resolvedInfo'){js_resolvedInfo=convertFromText(node.attributes[j].value);}
else if(attrname=='_resolver'){resolverPars=node.attributes[j].value;}
else if(attrname=='_resolver_name'){js_resolver=node.attributes[j].value;}
else if(attrname=='_tag'){tagName=node.attributes[j].value;}
else if(attrname=='_T'){convertAs=node.attributes[j].value;}
else{if(attrvalue.indexOf('::')>=0){attrvalue=convertFromText(attrvalue);}
attributes[attrname]=attrvalue;}}
var newcls=objectPop(attributes,'__cls');istxtnode=true;var textContent='';for(j=0;j<node.childNodes.length;j++){childnode=node.childNodes[j];if(!(childnode.nodeType==3||childnode.nodeType==4)){istxtnode=false;break;}
else{textContent=textContent+childnode.nodeValue;}}
if(istxtnode&&convertAs!='BAG'){var itemValue=textContent;if(convertAs!='T'){itemValue=convertFromText(itemValue,convertAs);}else if(stringContains(itemValue,'::')){itemValue=convertFromText(itemValue);}
if(convertAs=='H'){attributes.dtype=convertAs;}
if(resolverPars!=null){resolverPars=genro.evaluate(resolverPars);var cacheTime='cacheTime'in attributes?attributes.cacheTime:resolverPars.kwargs['cacheTime'];resolverPars['cacheTime']=0;itemValue=genro.rpc.remoteResolver('resolverRecall',{'resolverPars':resolverPars},{'cacheTime':cacheTime});}else if(js_resolver){itemValue=genro.getRelationResolver(attributes,js_resolver,this);}
this.addItem(tagName,itemValue,attributes);}
else{var resolver=null;var clsproto=this;if(clsdict!=null){if(newcls){newcls=clsdict[newcls];if(newcls){clsproto=newcls.prototype;}}}
var newBag=new clsproto.constructor();var newBagNode=this.addItem(tagName,newBag,attributes);if(js_resolver){var resolver=genro.getRelationResolver(attributes,js_resolver,this);newBagNode.setResolver(resolver);newBagNode._status='loaded';resolver.lastUpdate=new Date();objectUpdate(newBagNode.attr,js_resolvedInfo);}
newBag.fromXmlDoc(node,clsdict);}}}},toXml:function(kwargs){if(!kwargs){var kwargs={};}
var encoding=kwargs['encoding']||"utf-8";var result='<?xml version="1.0" encoding="'+encoding+'"?>\n';result=result+xml_buildTag('GenRoBag',this.toXmlBlock(kwargs),null,true);return result;},toXmlBlock:function(kwargs){var result=new Array();var nodes=this._nodes;for(var i=0;i<nodes.length;i++){result.push(nodes[i]._toXmlBlock(kwargs));}
return result.join('\n');},formula:function(formula,kwargs){this.setBackRef();if(this._symbols==null){this._symbols={};}
var path='formula:'+formula;var formula=this._symbols[path]||formula;var result=new gnr.GnrBagFormula(this,formula,this._symbols,kwargs);return result;},defineSymbol:function(kwargs){if(this._symbols==null){this._symbols={};}
objectUpdate(this._symbols,fromKwargs(kwargs));},defineFormula:function(kwargs){var path=null;if(this._symbols==null){this._symbols={};}
if(!(kwargs!=null)){kwargs=objectUpdate({},kwargs);}
for(key in kwargs){path='formula:'+key;this._symbols[path]=kwargs[key];}},setCallBackItem:function(path,callback,parameters,kwargs){if(!kwargs){var kwargs={};}
kwargs.method=callback;kwargs.parameters=parameters;var resolver=new gnr.GnrBagCbResolver(kwargs);this.setItem(path,resolver,kwargs);},get_modified:function(){return this._modified;},set_modified:function(value){if(value==null){this._modified=null;this.unsubscribe('modify__');}
else if(this._modified==null){this.subscribe('modify__',{'any':dojo.hitch(this,'_setModified')});}
this._modified=value;},_setModified:function(){this._modified=true;},getRoot:function(){var parent=this.getParent();if(parent==null){return this;}else{return parent.getRoot();}},getFullpath:function(mode,root){if(root==true){root=this.getRoot().getItem('#0');}
var fullpath='';var segment;var parentbag=this.getParent();if((parentbag!=null)&&(!this.isEqual(root))){var parentNode=this.getParentNode();if(mode=='#'||mode=='##'){segment=parentbag.getNodes().indexOf(parentNode)+'';if(mode=='##'){segment='#'+segment;}}else{segment=parentNode.label;}
fullpath=parentbag.getFullpath(mode,root);if(fullpath){fullpath=fullpath+'.'+segment;}else{fullpath=segment;}}
return fullpath;},getIndex:function(){var path=[];var resList=[];var exploredNodes=[this];this._deepIndex(path,resList,exploredNodes);return resList;},isEqual:function(otherbag){if(!otherbag){return false;}
if(this==otherbag){return true;};if(this._parentnode&&otherbag._parentnode){return this._parentnode._id==otherbag._parentnode._id;};return false;},_deepIndex:function(path,resList,exploredNodes){var node,v;for(var i=0;i<this._nodes.length;i++){node=this._nodes[i];v=node.getValue();resList.push([path.concat(node.label),node]);if('_deepIndex'in v){if(arrayIndexOf(exploredNodes,v)<0){exploredNodes.push(v);v._deepIndex(path.concat(node.label),resList,exploredNodes);}}}},getIndexList:function(asText){var l=this.getIndex();result=[];for(var i=0;i<l.length;i++){result.push(l[i][0].join('.'));}
if(asText){return result.join('\n');}else{return result;}},delParentRef:function(){this.parent=null;this._backref=false;},doWithItem:function(path,cb,dflt){var value=this.getItem(path,dflt);if(value instanceof dojo.Deferred){return value.addCallback(cb);}else{return cb(value);}}});dojo.declare("gnr.GnrBagResolver",null,{constructor:function(kwargs,isGetter,cacheTime,load){this._attributes={};this.setCacheTime(cacheTime||0);this.kwargs=kwargs;this.isGetter=isGetter;this.lastUpdate=null;this._pendingDeferred=[];if(load){this.load=load;}},onSetResolver:function(node){},setCacheTime:function(cacheTime){this.cacheTime=cacheTime;},getCacheTime:function(){return this.cacheTime;},reset:function(){this.lastUpdate=null;},expired:function(kwargs){var expired=false;if(this.cacheTime<0){if(this.lastUpdate==null){expired=true;}}
else{var now=new Date();var delta=(now-(this.lastUpdate||new Date(0)))/1000;expired=(delta>this.cacheTime);}
return expired;},resolve:function(optkwargs,destinationNode){var destFullpath=destinationNode?destinationNode.getFullpath(null,genro._data):'';var kwargs=objectUpdate({},this.kwargs);kwargs._destFullpath=destFullpath;if(optkwargs){objectUpdate(kwargs,optkwargs);}
if(this.isGetter){return this.load(kwargs);}
else{var finalize=dojo.hitch(this,function(r){this.lastUpdate=new Date();return r;});var result=this.load(kwargs,destinationNode);if(result instanceof dojo.Deferred){var that=this;return result.addCallback(finalize);}
else{return finalize(result,kwargs);}}},cancelMeToo:function(r){var _pendingDeferred=this._pendingDeferred||[];this._pendingDeferred=[];_pendingDeferred.forEach(function(d){d.cancel();});},meToo:function(cb){var newdeferred=new dojo.Deferred();newdeferred.addCallback(cb);this._pendingDeferred.push(newdeferred);return newdeferred;},runPendingDeferred:function(pendingDeferred){for(var i=0;i<pendingDeferred.length;i++){pendingDeferred[i].callback();}},load:function(kwargs,cb){return;},setParentNode:function(parentNode){this._parentNode=parentNode;},getParentNode:function(parentnode){return this._parentNode;},htraverse:function(kwargs){var pathlist=kwargs.pathlist;var autocreate=kwargs.autocreate;return this.resolve().htraverse(pathlist,autocreate);},keys:function(){return this.resolve().keys();},items:function(){return this.resolve().items();},values:function(){return this.resolve().values();},digest:function(k){var key=k||null;return this.resolve().digest(key);},sum:function(k){var key=k||null;return this.resolve().sum(key);},contains:function(){return this.resolve().contains();},len:function(){return this.resolve().len();},getAttr:function(){return this._attributes;},setAttr:function(attributes){objectUpdate(this._attributes,attributes);},resolverDescription:function(){return this.resolve().toString();}});dojo.declare("gnr.GnrBagFormula",gnr.GnrBagResolver,{constructor:function(root,expr,symbols,kwargs){this.root=root;if(symbols!=null){var symbols=objectUpdate({},symbols);}
else{var symbols={};}
objectUpdate(symbols,fromKwargs(kwargs));this.expr=templateReplace(expr,symbols);},load:function(){var root=this.root;var curr=this._parent;return eval(this.expr);}});var fromKwargs=function(kwargs){var key;var v=null;var bag='curr';var result={};for(key in kwargs){v=kwargs[key];if(stringStartsWith(key,'_')){result[key]=bag+".getResolver('"+v+"')";}
else{result[key]=bag+".getItem('"+v+"')";}}
return result;};dojo.declare("gnr.GnrBagGetter",gnr.GnrBagResolver,{constructor:function(bag,path,what){this.path=path;this.what=what||'node';},load:function(){var node=genro.getNode(this.path);if(thisWhat||this=='node'){return node;}
else if(thisWhat=='value'){return node.getValue();}
else if(thisWhat=='attr'){return node.getAttr();}}});dojo.declare("gnr.GnrBagCbResolver",gnr.GnrBagResolver,{constructor:function(kwargs,isGetter){this.method=kwargs.method;this.parameters=kwargs.parameters;this.isGetter=isGetter;},load:function(kwargs){var kw=objectUpdate({},this.parameters)
objectUpdate(kw,kwargs)
return this.method.call(this,kw);}});gnr.bagRealPath=function(path){if(path.indexOf('#parent')>0){var lpath=path.split('.');path=[];for(var i=0;i<lpath.length;i++){if(lpath[i]!='#parent'){path.push(lpath[i]);}else{path.pop();}}
path=path.join('.');}
return path;};



dojo.declare("gnr.GnrDomSourceNode",gnr.GnrBagNode,{constructor:function(){var mobile_kw=objectExtract(this.attr,'mobile_*');if(genro.isMobile&&objectNotEmpty(mobile_kw)){objectUpdate(this.attr,mobile_kw);}},application:function(){return this.getParentBag().getRoot().application;},freeze:function(){this._isFreezed=true;return this;},unfreeze:function(noRebuild){this._isFreezed=false;if(!noRebuild){this.rebuild();}},isFreezed:function(){var parentNode=this.getParentNode();return this._isFreezed?true:parentNode?parentNode.isFreezed():false;},getBuiltObj:function(){return this.getWidget(true)||this.getDomNode();},getParentBuiltObj:function(){var parentNode=this.getParentNode();if(parentNode){return parentNode.getBuiltObj();}},getDomNode:function(){if(this.domNode){return this.domNode;}
if(this.widget){return this.widget.focusNode||this.widget.containerNode||this.widget.domNode;}},getWidget:function(notEnclosed){if(this.domNode&&!notEnclosed){return dijit.getEnclosingWidget(this.domNode);}
var curr=this;var currvalue;while(curr&&!curr.widget&&!curr.domNode){currvalue=curr.getValue();if(currvalue instanceof gnr.GnrBag){curr=currvalue.getNode('#0');}else{return;}}
return curr?curr.widget:null;},_relativeGetter:function(prefix){var that=this;return function(path){return that.getRelativeData(prefix?prefix+path:path);};},getParentWidget:function(tagToFind){var tag=tagToFind?tagToFind.toLowerCase():none;var parentNode=this.getParentNode();if(parentNode){return(parentNode.widget&&(!tag||((parentNode.attr.tag||'').toLowerCase()==tag)))?parentNode.widget:parentNode.getParentWidget(tagToFind);}},destroy:function(){if(this.widget){this.widget.destroyRecursive();}
else if(this.domNode){var widgets=dojo.query('[widgetId]',this.domNode);widgets=widgets.map(dijit.byNode);dojo.forEach(widgets,function(widget){widget.destroy();});while(this.domNode.childNodes.length>0){dojo._destroyElement(this.domNode.childNodes[0]);}
dojo._destroyElement(this.domNode);}},getTriggerReason:function(pathToCheck,kw){if(kw.reason=='autocreate'){return;}
if(!pathToCheck){return;}
var eventpath=kw.pathlist.slice(1).join('.');var isValuePath=(pathToCheck.indexOf('?')<0);if(pathToCheck.indexOf('#parent')>0){pathToCheck=gnr.bagRealPath(pathToCheck);}
if(!isValuePath){if((kw.updattr)||(kw.evt=='fired')||(pathToCheck.indexOf('?=')>=0)){pathToCheck=pathToCheck.split('?')[0];}}
if(pathToCheck==eventpath){if(isValuePath&&kw.updattr&&!kw.updvalue){return;}
return'node';}else if(pathToCheck.indexOf(eventpath+'.')==0){return'container';}
else if(eventpath.indexOf(pathToCheck+'.')==0){return'child';}},trigger_data:function(prop,kw){var trigger_reason=this.getTriggerReason(this.attrDatapath(prop),kw)
if(trigger_reason){if((kw.evt=='fired')&&(trigger_reason=='child')){}else if(kw.evt=='invalid'){if(this.widget){this.widget.focus();}}else if(this._dataprovider){if(prop=='_timing'){this.setTiming(kw.value);}else{this.setDataNodeValue(kw.node,kw,trigger_reason);}}
else{if(kw.reason!=this){this.updateAttrBuiltObj(prop,kw,trigger_reason);}}}},fireNode:function(runKwargs){return this.setDataNodeValue(runKwargs);},setDataNodeValue:function(nodeOrRunKwargs,kw,trigger_reason,subscription_args){var currentAttributes=this.currentAttributes();var delay=currentAttributes._delay;if(delay=='auto'){delay=null;}
if(delay){if(this.pendingFire){clearTimeout(this.pendingFire);}
this.pendingFire=setTimeout(dojo.hitch(this,'setDataNodeValueDo',nodeOrRunKwargs,kw,trigger_reason,subscription_args),delay);}else if(this.attr._ask){if((kw&&kw.reason=='autocreate')||(trigger_reason!='node')){return;}
if(!this.attr._ask_if||funcApply('return ('+this.attr._ask_if+');',currentAttributes,this)){var that=this;var _ask_onCancel=this.attr._ask_onCancel||function(){};_ask_onCancel=funcCreate(_ask_onCancel,'kwargs',this);genro.dlg.ask(currentAttributes._ask_title||'Warning',currentAttributes._ask,null,{confirm:function(){that.setDataNodeValueDo(nodeOrRunKwargs,kw,trigger_reason,subscription_args);},cancel:function(){_ask_onCancel(currentAttributes)}});}}
else{return this.setDataNodeValueDo(nodeOrRunKwargs,kw,trigger_reason,subscription_args);}},setDataNodeValueDo:function(nodeOrRunKwargs,kw,trigger_reason,subscription_args){var node;var runKwargs={};var isFiredNode=!(nodeOrRunKwargs instanceof gnr.GnrBagNode)
if(isFiredNode){runKwargs=nodeOrRunKwargs;}else{node=nodeOrRunKwargs;}
var attributes=objectUpdate({},this.attr);var strippedKw=objectPop(attributes,'_strippedKwargs');var _userChanges=objectPop(attributes,'_userChanges');var _trace=objectPop(attributes,'_trace');var _trace_level=objectPop(attributes,'_trace_level')||0;if((kw&&kw.reason=='autocreate')||(_userChanges&&trigger_reason!='node')){return;}
objectExtract(attributes,'subscribe_*');var tag=objectPop(attributes,'tag').toLowerCase();var path=objectPop(attributes,'path');if(path=='dummy'){path=null;}
objectPop(attributes,'_onStart');objectPop(attributes,'_onBuilt');objectPop(attributes,'_fired_onStart');objectPop(attributes,'datapath');var destinationPath,dataNode;if(path){destinationPath=this.absDatapath(path);dataNode=genro.getDataNode(destinationPath,true);}
objectPop(attributes,'_init');objectPop(attributes,'_delay');var _if=objectPop(attributes,'_if');var _else=objectPop(attributes,'_else');var expr;if(tag=='dataformula'){expr=objectPop(attributes,'formula');}else if((tag=='datacontroller')||(tag=='datascript')){expr=objectPop(attributes,'script');}else{expr=objectPop(attributes,'method');expr=this.getAttributeFromDatasource('method');}
if(_trace){console.log("TRACE "+tag+"("+_trace+")");if(_trace_level>=2){console.log("trigger_reason="+trigger_reason);console.log("kw=");console.log(kw);}
if(_trace_level>=3){console.log("expr=");console.log(expr);}}
var argValues=[node,{'kw':kw,'trigger_reason':trigger_reason},trigger_reason];var argNames=['_node','_triggerpars','_reason'];var kwargs={};var strippedKwargs={};if(strippedKw){strippedKw.split(',').forEach(function(attr){if(!(attr in attributes)){argNames.push(attr);argValues.push(null);}})}
if(subscription_args){argNames.push(trigger_reason);argValues.push(subscription_args);if((subscription_args.length==1)&&(typeof(subscription_args[0])=='object')){for(var k in subscription_args[0]){argNames.push(k);argValues.push(subscription_args[0][k]);kwargs[k]=subscription_args[0][k];}
argNames.push('_subscription_kwargs');argValues.push(subscription_args[0]);kwargs['_subscription_kwargs']=subscription_args[0];}}
var val;if(_trace&&(_trace_level>0)){console.log('Arguments:');}
for(var attrname in attributes){argNames.push(attrname);val=this.getAttributeFromDatasource(attrname);argValues.push(val);kwargs[attrname]=val;if(_trace&&(_trace_level>0)){console.log("--- "+attrname+" ---");console.log(val);}}
objectUpdate(kwargs,runKwargs);var if_result=true;if(_if){if_result=funcCreate('return ('+_if+')',argNames.join(',')).apply(this,argValues);if(_trace&&(_trace_level>0)){console.log("_if="+if_result);}}
if(tag=='dataformula'||tag=='datascript'||tag=='datacontroller'||tag=='datarpc'){var val;if(!if_result){if(!_else){return;}
expr=_else;}
if(tag=='datarpc'&&(expr!=_else)){var doCall=true;var domsource_id=this.getStringId();var method=expr;var httpMethod=objectPop(kwargs,'httpMethod');httpMethod=httpMethod||(objectPop(kwargs,'_POST')===false?'GET':'POST');var _onResult=objectPop(kwargs,'_onResult');var _onError=objectPop(kwargs,'_onError');var _lockScreen=objectPop(kwargs,'_lockScreen');var _execClass=objectPop(kwargs,'_execClass');objectPop(kwargs,'nodeId');var _onCalling=objectPop(kwargs,'_onCalling');var origKwargs=objectUpdate({},kwargs);if(_onResult){_onResult=funcCreate(_onResult,'result,kwargs,old',this);}
if(_onError){_onError=funcCreate(_onError,'error,kwargs',this);}
var cb=function(result,error){error=error||result?result.error:null;if(_lockScreen){genro.lockScreen(false,domsource_id,_lockScreen);}
if(_execClass){genro.dom.removeClass(dojo.body(),_execClass);}
if(error){if(_onError){_onError(error,origKwargs);}}
else{var oldValue;if(dataNode){oldValue=dataNode.getValue();dataNode.setValue(result);dataNode._rpcNode_id=this._id;}
if(_onResult){_onResult(result,origKwargs,oldValue);}}
return result};if(_execClass){genro.dom.addClass(dojo.body(),_execClass);}
if(_onCalling){doCall=funcCreate(_onCalling,(['kwargs'].concat(argNames)).join(',')).apply(this,([kwargs].concat(argValues)));}
objectExtract(kwargs,'_*');if(doCall!=false){if(_lockScreen){genro.lockScreen(true,domsource_id,_lockScreen);}
if(!this._deferredRegister){this._deferredRegister={};}
kwargs['_sourceNode']=this;var deferred=genro.rpc.remoteCall(method,kwargs,null,httpMethod,null,cb);if(deferred){this._deferredRegister[deferred.id]=deferred;this._lastDeferred=deferred;var that=this;deferred.addCallback(function(result){that._lastRpcTs=new Date();delete that._deferredRegister[deferred.id];return result;});if(this._callbacks){this._callbacks.forEach(function(n){var kw=objectUpdate({},kwargs);kw['_isFiredNode']=isFiredNode;genro.rpc.addDeferredCb(deferred,n.getValue(),objectUpdate(kw,n.attr),that);});}}
return deferred;}}
else{var result;if(!expr){result=new gnr.GnrBag(kwargs);}else{expr=(tag=='dataformula')?'return '+expr:expr;var f=funcCreate(expr,(['_kwargs'].concat(argNames)).join(','));result=f.apply(this,([kwargs].concat(argValues)));}
if(destinationPath){this.setRelativeData(destinationPath,result);}}}
else{if(if_result){method=expr;var cacheTime=objectPop(attributes,'cacheTime',-1);var isGetter=objectPop(attributes,'isGetter',false);attributes.sync=('sync'in attributes)?attributes.sync:true;attributes['_sourceNode']=this;var resolvedValue=this._resolvedValue;var resolver=genro.rpc.remoteResolver(method,attributes,{'cacheTime':cacheTime,'isGetter':isGetter});dataNode.setValue(resolver,true,attributes);if(resolvedValue){dataNode._status='loaded';dataNode.setValue(resolvedValue,'resolver');dataNode._resolver.lastUpdate=new Date();delete this._resolvedValue;}}}},setAttributeInDatasource:function(attrname,value,doTrigger,attributes,forceChanges){doTrigger=(doTrigger==null)?this:doTrigger;var path=this.attrDatapath(attrname);var old_value=genro._data.getItem(path);if(!isEqual(value,old_value)||(forceChanges&&value!=null)){genro._data.setItem(path,value,attributes,{'doTrigger':doTrigger});}},defineForm:function(formId,formDatapath,controllerPath,pkeyPath,kw){this.form=new gnr.GnrFrmHandler(this,formId,formDatapath,controllerPath,pkeyPath,kw);},hasDynamicAttr:function(attr){return(this._dynattr&&(attr in this._dynattr));},getRelativeData:function(path,autocreate,dflt){var path=this.absDatapath(path);var value;if(path!=null){if(autocreate){var node=genro._data.getNode(path,false,autocreate,dflt);value=genro._data.getItem(path,null,null,{'_sourceNode':this});}else{value=genro._data.getItem(path,null,null,{'_sourceNode':this});}}
return value;},fireEvent:function(path,value,attributes,reason,delay){this.setRelativeData(path,value||true,attributes,true,reason,delay);},setRelativeData:function(path,value,attributes,fired,reason,delay,_kwargs){if(delay){setTimeout(dojo.hitch(this,'setRelativeData',path,value,attributes,fired,reason,null,_kwargs),delay);}else{reason=reason==null?true:reason;var oldpath=path;path=this.absDatapath(path);if(fired){genro._firingNode=this;genro._data.fireItem(path,value,attributes,{'doTrigger':reason});genro._firingNode=null;}else{genro._data.setItem(path,value,attributes,objectUpdate({'doTrigger':reason,lazySet:true},_kwargs));}}},getAttributeFromDatasource:function(attrname,autocreate,dflt){attrname=attrname||'value';var value=this.attr[attrname];value=this.currentFromDatasource(value,autocreate,dflt);if(((attrname=='innerHTML'))&&(this.attr.mask||this.attr.format||(value instanceof gnr.GnrBag))){var kw=objectUpdate({},this.attr);objectPop(kw,attrname);value=genro.formatter.asText(value,this.evaluateOnNode(kw));}
return value;},currentFromDatasource:function(value,autocreate,dflt){var path;if(typeof(value)=='string'){if(this.isPointerPath(value)){if(value.indexOf('==')==0){var argNames=[];var argValues=[];for(var attr in this.attr){var attrval=this.attr[attr];if((typeof(attrval)!='string')||(attrval.indexOf('==')!=0)){argNames.push(attr);argValues.push(this.getAttributeFromDatasource(attr));}}
try{value=funcCreate('return '+value.slice(2),argNames.join(',')).apply(this,argValues);}catch(e){if(console!=undefined){console.log('ERROR in '+value);console.log(e);console.log('arguments: ');for(var i=0;i<argNames.length;i++){console.log(argNames[i]+" = "+argValues[i]);}}
throw e;}}else{value=this.getRelativeData(value,autocreate,dflt);}}}
return value;},attrDatapath:function(attrname,targetNode){targetNode=targetNode||this;if(!attrname){return targetNode.absDatapath();}
var attrvalue=this.attr[attrname];var path=null;if(typeof(attrvalue)=='string'){if(this.isPointerPath(attrvalue)){attrvalue=attrvalue.slice(1);}
path=targetNode.absDatapath(attrvalue);}
return path;},isPointerPath:function(path){return path?((path.indexOf('^')===0)||(path.indexOf('=')===0)):false;},nodeById:function(nodeId){return genro.nodeById(nodeId,this);},wdgById:function(nodeId){return genro.wdgById(nodeId,this);},domById:function(nodeId){return genro.domById(nodeId,this);},getPathId:function(){return stringHash(this.getFullpath());},symbolicDatapath:function(path){var attachpath;var pathlist=path.split('.');var nodeId=pathlist[0].slice(1);var relpath=pathlist.slice(1).join('.');if(nodeId in genro._aliasDatapaths){return genro._aliasDatapaths[nodeId]+'.'+relpath;}
if(nodeId=='ROW'){return this.widget?this.widget.cellCurrentDatapath(path):null;}
if(nodeId=='WORKSPACE'){var node=this.attributeOwnerNode('_workspace');genro.assert(node,'with WORKSPACE path you need an ancestor node with attribute _workspace');if(node.attr._workspace_path){return node.absDatapath(node.attr._workspace_path)+'.'+relpath;}
var wsname=node.attr._workspace===true?(node.attr.nodeId||(node.attr.tag+'_'+node.getPathId())):node.attr._workspace;return'gnr.workspace.'+wsname+'.'+relpath;}
if(nodeId=='DATA'){return relpath;}
var currNode=this.nodeById(nodeId);if(!currNode){console.error('not existing nodeId:'+nodeId);}
if(relpath=='*S'){return currNode.getFullpath().replace('main.','*S.');}
path=currNode.absDatapath(relpath?'.'+relpath:'');return path;},absDatapath:function(path){path=path||'';if(this.isPointerPath(path)){path=path.slice(1);}
if(path.indexOf('#')===0){return this.symbolicDatapath(path);}
if(path=='.'){return this.absDatapath();}
var currNode=this;var datapath;while(currNode&&((!path)||path.indexOf('.')==0)){datapath=currNode.attr.datapath;if(typeof(datapath)=='function'){datapath=datapath.call(currNode,datapath);}
if(datapath){if(this.isPointerPath(datapath)){datapath=currNode.getAttributeFromDatasource('datapath');if(!datapath){return null;}}
if(datapath.indexOf('#')==0){datapath=currNode.symbolicDatapath(datapath);}
path=datapath+path;}
currNode=currNode.getParentNode();}
if(path.indexOf('.')==0){console.error('unresolved relativepath '+path);debugger}
path=path.replace('.?','?');if(path.indexOf('#parent')>0){path=gnr.bagRealPath(path);}
return path;},connect:function(target,eventname,handler){var eventname=((!eventname)||eventname=='action')?target.gnr._defaultEvent:eventname;var handler=dojo.hitch(this,funcCreate(handler));if(target.domNode){if(eventname in target){dojo.connect(target,eventname,handler);}else{dojo.connect(target.domNode,eventname,handler);}}
else{dojo.connect(target,eventname,handler);}},updateContent:function(kw){if(this._resolver){var mode=kw?'reload':null;this.getValue(mode,kw);this.widget.resize();}},setRemoteContent:function(kwargs){kwargs.sync=('sync'in kwargs)?kwargs.sync:true;var cacheTime=objectPop(kwargs,'cacheTime');var resolver=new gnr.GnrRemoteResolver(kwargs,false,cacheTime);resolver.updateAttr=true;this.setResolver(resolver);},_bld_data:function(){},_bld_dataremote:function(){},_bld_dataformula:function(){},_bld_datascript:function(){},_bld_datacontroller:function(){},_bld_datarpc:function(){this._callbacks=this.getValue();this._value=null;},_bld_script:function(){if(this.attr.src){genro.dom.loadJs(this.attr.src);}else{dojo.eval(this.getValue());}},_bld_stylesheet:function(){if(this.attr.href){genro.dom.loadCss(this.attr.href,this.attr.cssTitle);}else{console.log('_bld_stylesheet',this.getValue())
genro.dom.addStyleSheet(this.getValue(),this.attr.cssTitle);}},_bld_css:function(){genro.dom.addCssRule(this.getValue());},_bld_remote:function(){var kwargs=objectUpdate({},this.attr);objectPop(kwargs,'tag');this.getParentNode().setRemoteContent(kwargs);},registerDynAttr:function(attr){this._dynattr=this._dynattr||{};this._dynattr[attr]=null;},registerNodeDynAttr:function(returnCurrentValues){this._resetDynAttributes();var attributes={};var attrvalue;for(var attr in this.attr){attrvalue=this.attr[attr];attributes[attr]=attrvalue;if((typeof(attrvalue)=='string')&&this.isPointerPath(attrvalue)){if((attrvalue.indexOf('^')==0)){this.registerDynAttr(attr);}
if(returnCurrentValues){attributes[attr]=this.getAttributeFromDatasource(attr);}
if(attrvalue.indexOf('==')==0){this._formulaAttributes=this._formulaAttributes||{};this._formulaAttributes[attr]=attrvalue.slice(2);}}}
return attributes;},onNodeCall:function(func,kw){kw=objectUpdate(objectUpdate({},this.attr),kw);return funcApply(func,this.evaluateOnNode(kw),this);},evaluateOnNode:function(pardict,filterCb){var result={};for(var attr in pardict){var v=pardict[attr];if(filterCb&&typeof(v)=='string'&&this.isPointerPath(v)&&!filterCb(v)){result[attr]=v;}else{result[attr]=this.currentFromDatasource(v);}}
return result;},normalizeKwargs:function(str){return this.evaluateOnNode(normalizeKwargs(objectUpdate({},this.attr),str));},currentAttributes:function(){var attributes={};for(var attr in this.attr){attributes[attr]=this.getAttributeFromDatasource(attr);}
return attributes;},rebuild:function(){this.setValue(this._value);},build:function(destination,ind){genro.src.stripData(this);if(this.attr._attachPoint){var _attachPoint=this.attr._attachPoint.split('.');while(_attachPoint.length>0){destination=destination[_attachPoint.shift()];}}
if(!this.attr.tag){this._buildChildren(destination);return;}
var handler=genro.wdg.getHandler(this.attr.tag);if(handler&&handler._onBuilding){handler._onBuilding(this);}
if(this.attr.parentForm===false){this.form=null;}else{this._registerInForm();}
this._isBuilding=true;var aux='_bld_'+this.attr.tag.toLowerCase();if(aux in this){this[aux].call(this);}else{var attributes=this.registerNodeDynAttr(true);var tag=objectPop(attributes,'tag');this._doBuildNode(tag,attributes,destination,ind);this._setDynAttributes();}
this._isBuilding=false;},_buildChildren:function(destination){if(this.attr.remote){var that=this;this.watch('isVisibile',function(){return genro.dom.isVisible(that);},function(){setTimeout(function(){that.updateRemoteContent();},1);});}
var content=this.getValue('static');if(content instanceof gnr.GnrDomSource){content.forEach(function(node){node.build(destination,-1);},'static');}},_registerInForm:function(){var formHandler=this.getFormHandler();if(formHandler){this.form=formHandler;if(this.attr.parentForm!==false){formHandler.registerChild(this);genro.src.formsToUpdate[this.form.formId]=this.form;}}},_registerNodeId:function(nodeId){nodeId=this.attr.nodeId||nodeId;if(nodeId){var reg_node=genro.src._index[nodeId];if(reg_node){genro.assert(reg_node===this,'duplicate nodeId:'+nodeId);}
genro.src._index[nodeId]=this;}},_onDeleting:function(){if(this.form){this.form.unregisterChild(this);}
if(this._timing){clearInterval(this._timing);}
if(this._shortcuts){this._shortcuts.forEach(function(kw){var args=kw.args;kw.element.removeEventListener(args[0],args[1],args[2]);});}
if(this.watches){for(var w in this.watches){var interval=this.watches[w];if(interval){clearInterval(interval);}}}},_doBuildNode:function(tag,attributes,destination,ind){var bld_attrs=objectExtract(attributes,'onCreated,gnrId,tooltip,nodeId');var connections=objectExtract(attributes,'connect_*');if(objectPop(attributes,'autofocus')){attributes.subscribe_onPageStart="this.widget.focus()";}
var subscriptions=objectExtract(attributes,'subscribe_*');var selfsubscription=objectExtract(attributes,'selfsubscribe_*');var formsubscription=objectExtract(attributes,'formsubscribe_*');var attrname;ind=ind||0;var newobj=genro.wdg.create(tag,destination,attributes,ind,this);for(var selfsubscribe in selfsubscription){this.subscribe(selfsubscribe,selfsubscription[selfsubscribe]);}
if(this.form){var topic_pref='form_'+this.form.formId+'_';for(var formsubscribe in formsubscription){subscriptions[topic_pref+formsubscribe]=formsubscription[formsubscribe];}}
if(newobj===false){this._buildChildren(destination);return;}
if(bld_attrs.onCreated){funcCreate(bld_attrs.onCreated,'widget,attributes').call(this,newobj,attributes);}
this._registerNodeId(bld_attrs.nodeId);if(bld_attrs.gnrId){this.setGnrId(bld_attrs.gnrId,newobj);}
for(var eventname in connections){this.connect(newobj,eventname,connections[eventname]);}
for(var subscription in subscriptions){var handler=funcCreate(subscriptions[subscription]);this.registerSubscription(subscription,this,handler);}
if(this.attr._lazyBuild){var that=this;var cbtest;cbtest=function(){return genro.dom.isVisible(that)||that._buildNow;}
this.watch('lazyBuildWait',cbtest,function(){that.lazyBuildFinalize(newobj);});}else{this._buildChildren(newobj);}
if('startup'in newobj){newobj.startup();}
if((typeof(this.attr.value)=='string')&&(this.isPointerPath(this.attr.value))){newobj.gnr.connectChangeEvent(newobj);}
if(bld_attrs.tooltip){genro.wdg.create('tooltip',null,{label:bld_attrs.tooltip,tooltip_type:'help'}).connectOneNode(newobj.domNode||newobj);}
if(genro.src._started&&this.widget&&(this.widget instanceof dijit.form.ValidationTextBox)){var validations=objectExtract(this.attr,'validate_*',true);if(this.validationsOnChange&&objectNotEmpty(validations)){this.resetValidationError();var newval=this.validationsOnChange(this,attributes.value,true)['value'];this.updateValidationStatus();}}
this._built=true;this.onNodeBuilt(newobj);return newobj;},buildNow:function(){this._buildNow=true;},onNodeBuilt:function(newobj){return;},delayedCall:function(cb,delay,code){code=code||'delayedCall';var handlerName='_dc_'+code;delay=delay||1;if(this[handlerName]){clearTimeout(this[handlerName]);}
this[handlerName]=setTimeout(cb,delay);},_resetDynAttributes:function(){if(this._dynattr){delete this._dynattr;}
var stringId=this.getStringId();var nodeSubscribers=genro.src._subscribedNodes[stringId];if(nodeSubscribers){for(var attr in nodeSubscribers){dojo.forEach(nodeSubscribers[attr],function(n){dojo.unsubscribe(n);});}
delete genro.src._subscribedNodes[stringId];}},registerSubscription:function(topic,scope,handler,reason){var stringId=this.getStringId();reason=reason||topic;var subDict=genro.src._subscribedNodes[stringId];if(!subDict){subDict={};genro.src._subscribedNodes[stringId]=subDict;}
if(!(topic in subDict)){subDict[reason]=[];}
subDict[reason].push(dojo.subscribe(topic,scope,handler));},unregisterSubscription:function(reason){var stringId=this.getStringId();var subDict=genro.src._subscribedNodes[stringId];if(!subDict){return;}
if(reason in subDict){var l=objectPop(subDict,reason);if(l){dojo.forEach(l,function(s){dojo.unsubscribe(s)});}}},_setDynAttributes:function(){var stringId=this.getStringId();if(this._dynattr){var nodeSubscribers=genro.src._subscribedNodes[stringId]||{};var path,fn,prop;for(var attr in this._dynattr){nodeSubscribers[attr]=[this._subscriptionHandle(attr)];}
genro.src._subscribedNodes[stringId]=nodeSubscribers;}},_subscriptionHandle:function(attr){var prop=attr;return dojo.subscribe('_trigger_data',this,function(kw){this.trigger_data(prop,kw);});},setGnrId:function(gnrId,obj){var idLst=gnrId.split('.');var curr=genro;for(var i=0;i<idLst.length-1;i++){var id=idLst[i];if(!curr[id]){curr[id]={};};curr=curr[id];}
curr[idLst[idLst.length-1]]=obj;},publish:function(msg,kw,recursive){var topic=(this.attr.nodeId||this.getStringId())+'_'+msg;dojo.publish(topic,[kw]);if(recursive){var children=this.getValue('static');if(children instanceof gnr.GnrDomSource){children.walk(function(n){if(!n._built){return true;}
n.publish(msg,kw);});}}},subscribe:function(command,handler,subscriberNode){var that=this;var h=handler;handler=function(){var argNames=[];var argValues=[];for(var i=0;i<arguments.length;i++){argValues.push(arguments[i]);argNames.push('p_'+i);}
var currAttr=that.currentAttributes();funcApply(h,that.currentAttributes(),that,argNames,argValues);};var topic=(this.attr.nodeId||this.getStringId())+'_'+command;subscriberNode=subscriberNode||this;subscriberNode.registerSubscription(topic,this,handler);},lazyBuildFinalize:function(widget){var lazyBuild=objectPop(this.attr,'_lazyBuild');var content=this.getValue();if(content instanceof gnr.GnrBag){var nodes=content._nodes;content._nodes=[];dojo.forEach(nodes,function(n){content.setItem(n.label,n);});}
if(this.attr._onLazyBuilt){funcApply(this.attr._onLazyBuilt,null,this);}},getFrameNode:function(){if(this.attr.tag.toLowerCase()=='framepane'){return this;}
var parent=this.getParentNode();if(parent){return parent.getFrameNode();}},getFormHandler:function(){if('form'in this){return this.form;}
else if(this.attr.parentForm){if(typeof(this.attr.parentForm)=='string'){return genro.formById(this.attr.parentForm);}}
var parent=this.getParentNode();if(parent){return parent.getFormHandler();}else if(genro.parentIframeSourceNode){return genro.parentIframeSourceNode.getFormHandler();}},inheritedAttribute:function(attr){var node=this.attributeOwnerNode(attr);if(node){return node.getAttributeFromDatasource(attr);}},setHiderLayer:function(set,kw){if(!set){this.unwatch('isVisibile');this.getValue().popNode('hiderNode');}else if(!this.getValue().getNode('hiderNode')){var that=this;this.watch('isVisibile',function(){return genro.dom.isVisible(that);},function(){genro.dom.makeHiderLayer(that,kw);});}},updateAttrBuiltObj:function(attr,kw,trigger_reason){var re=new RegExp('\\b'+attr+'\\b');var isInFormula=false;if(this._formulaAttributes){for(var formulaAttribute in this._formulaAttributes){if(this._formulaAttributes[formulaAttribute].match(re)){this.doUpdateAttrBuiltObj(formulaAttribute,kw,trigger_reason);isInFormula=true;}}}
if(!isInFormula){this.doUpdateAttrBuiltObj(attr,kw,trigger_reason);}},doUpdateAttrBuiltObj:function(attr,kw,trigger_reason){if(stringStartsWith(attr,'attr_')){var valuepath=this.attr.value||this.attr.src||this.attr.innerHTML;if(valuepath){var updattr={};updattr[attr.slice(5)]=kw.value;genro.getDataNode(this.absDatapath(valuepath)).updAttributes(updattr);}}
if(this._original_attributes){this.setAttr(this._original_attributes,true);this._original_attributes=null;}
var autocreate=kw.reason=='autocreate';attr=attr||'value';var path;var value=null;var attr_lower=attr.toLowerCase();var valueNode=kw.node;if(trigger_reason=='container'&&attr=='value'&&kw.evt=='upd'){var vpath=this.attr.value;if(this.isPointerPath(vpath)){valueNode=genro._data.getNode(this.absDatapath(vpath),null,true);if(valueNode){var wdg_prefix=vpath.indexOf('?')<0?'wdg_*':'wdg_'+vpath.split('?')[1]+'_*';var wdg_modifiers=objectExtract(valueNode.attr,wdg_prefix);if(objectNotEmpty(wdg_modifiers)){this._original_attributes=objectUpdate({},this.attr);this.updAttributes(wdg_modifiers,true);}}}}
if(!(kw.evt=='ins'||kw.evt=='del')){value=this.getAttributeFromDatasource(attr,true);}
if(attr_lower=='disabled'){return this.setDisabled(value);}
if(attr=='datapath'){var absDatapath=this.absDatapath();if(absDatapath){genro.fireDataTrigger(absDatapath);}}
else if(attr=='zoomFactor'){if(this.setZoomFactor){this.setZoomFactor(value);}}
else if(this.externalWidget){if('gnr_'+attr in this.externalWidget){this.externalWidget['gnr_'+attr](value,kw,trigger_reason);}else{this.rebuild();}
return;}
else if(attr=='_class'){var oldvalue=('oldvalue'in kw)?kw.oldvalue:kw.changedAttr?kw.oldattr[kw.changedAttr]:null;var domnode;if(this.widget){domnode=this.widget.domNode;}
else{domnode=this.domNode;}
if(oldvalue){var old_class;if(oldvalue instanceof gnr.GnrBag){var q=kw.pathlist.length;var p=this.absDatapath(this.attr._class).split('.').slice(q-1);old_class=oldvalue.getItem(p.join('.'));}else{old_class=oldvalue;}
genro.dom.removeClass(domnode,old_class);}
genro.dom.addClass(domnode,value);}
else if(attr=='style'){genro.dom.style(this,value);}
else if(attr=='placeholder'){(this.widget?this.widget.focusNode:this.domNode).setAttribute('placeholder',value||'');}
else if(attr.indexOf('remote_')===0){this.updateRemoteContent(this);}
else if(this.widget){if(attr.indexOf('__')===0){return;}
else if(attr_lower=='readonly'){this.widget.setAttribute(attr,value?true:false);}
else if((attr=='storepath')&&(this.attr.storepath.indexOf('^')==0)){this.rebuild();}
else if(attr.indexOf('validate_')===0){if((trigger_reason=='node')||(kw.reason=='resolver')){this.resetValidationError();var currval=this.getAttributeFromDatasource('value');var newval=this.validationsOnChange(this,currval,true)['value'];this.updateValidationStatus();this.setAttributeInDatasource('value',newval);}}else if(attr.indexOf('condition_')===0){if('setCondition'in this.widget){if((trigger_reason=='node')||(kw.reason=='resolver')){this.widget.setCondition(value,kw);}}}
else{var setter='set'+stringCapitalize(attr);if(!(setter in this.widget)){setter='catch_'+attr.split('_')[0];}
if(setter in this.widget){var trgevt=kw.evt;if(attr!='value'){dojo.hitch(this.widget,setter)(value,kw,attr);return;}
var formHandler=this.getFormHandler();this.resetValidationError();if(formHandler&&trigger_reason=='container'&&this.attr.default_value&&formHandler.isNewRecord()&&(value==null)){value=this.attr.default_value;}
if('_lastValueReported'in this.widget){this.widget._lastValueReported=value;}
kw=false;if(this.attr['protected']){var parentAttr=this.getRelativeData('.?');if('_newrecord'in parentAttr){if(!parentAttr['_newrecord']){this.widget.setAttribute('readOnly',true);var wdg=this.widget;dojo.connect(wdg.domNode,'ondblclick',function(e){wdg.setAttribute('readOnly',false);});dojo.connect(wdg,'onBlur',function(){wdg.setAttribute('readOnly',true);});}}}
if(!this.widget._ignoreDataChanges){this.widget.setValue(value,kw);}
if(trgevt!='del'){if(this.hasValidations()){var formHandler=this.getFormHandler();if(formHandler&&!autocreate){formHandler.validateFromDatasource(this,value,trigger_reason);}}
var valueAttr=valueNode?valueNode.attr:null;var sourceNodeValueAttr=objectExtract(this.attr,'attr_*',true);if(objectNotEmpty(sourceNodeValueAttr)){objectUpdate(valueAttr,this.evaluateOnNode(sourceNodeValueAttr));}
if(this.attr.format||this.attr.mask){var valueToFormat=value;var nattr=this.currentAttributes();if(this.widget.getDisplayedValue){var _displayedValue=this.widget.getDisplayedValue();if(_displayedValue!=value){if(isNullOrBlank(_displayedValue)&&isNullOrBlank(value)){delete valueAttr._displayedValue;}else{valueAttr['_displayedValue']=_displayedValue;}}
if(typeof(value)=='string'||nattr.dtype=='T'){valueToFormat=_displayedValue;}}
valueNode.updAttributes({_formattedValue:genro.formatter.asText(valueToFormat,nattr)},this);}}}
else if(genro.dom.isStyleAttr(attr)){this.widget.domNode.setAttribute('style',objectAsStyle(genro.dom.getStyleDict(this.currentAttributes())));}
else{this.rebuild();}}}
else if(this.domNode){var domnode=this.domNode;var setter='set'+stringCapitalize(attr);if(setter in domnode.gnr){dojo.hitch(domnode.gnr,setter)(domnode,value,kw);}
else if(attr=='visible'){dojo.style(domnode,'visibility',(value?'visible':'hidden'));return;}
else if(attr=='hidden'){this.setHidden(value);return;}
else if(attr=='value'){if('value'in domnode){domnode.value=value;}
else{}}
else if(attr=='innerHTML'){domnode.innerHTML=value;}
else if(('template'in this.attr)&&((attr=='datasource')||attr.indexOf('tpl_')==0)){var ih=dataTemplate(this.getAttributeFromDatasource('template'),this,this.attr.datasource);if(this.isPointerPath(this.attr.innerHTML)){this.setRelativeData(this.attr.innerHTML,ih);}else{this.domNode.innerHTML=ih;}}
else if(genro.dom.isStyleAttr(attr)){genro.dom.style(domnode,genro.dom.getStyleDict(this.currentAttributes()));}
else if(attr in domnode){domnode[attr]=value;}
else{var attrdict={};this.setAttr(attrdict,this,true);}}else if(this.gnrwdg){var handler=this.gnrwdg['set'+stringCapitalize(attr)];if(!handler&&(attr in this.gnrwdg['catchers'])){handler=this.gnrwdg[this.gnrwdg['catchers'][attr]];}
if(handler){handler.call(this.gnrwdg,value,kw,trigger_reason);}}},_dataControllerSubscription:function(subscriptions){for(var subscription in subscriptions){var cb=function(node,trigger_reason){var reason=trigger_reason;node.registerSubscription(subscription,node,function(){node.setDataNodeValue(null,{},reason,arguments);});};cb(this,subscription);}},setTiming:function(timing){if(this._timing){clearInterval(this._timing);}
if(timing>0){var timerFunc=dojo.hitch(this,'setDataNodeValue');this._timing=setInterval(timerFunc,timing*1000);}},setHidden:function(hidden){var targets=this._hiddenTargets||[this.domNode||this.widget.domNode];targets.forEach(function(domNode){dojo.style(domNode,'display',(hidden?'none':''));});},updateRemoteContent:function(forceUpdate,async){var _onRemote=false;var currentValue=this.getValue('static');if(currentValue&&currentValue.len()>0&&!forceUpdate){return;}
if(this._remotebuilding){return;}
var remoteAttr=this.evaluateOnNode(objectExtract(this.attr,'remote_*',true));async=objectPop(remoteAttr,'_async',async);if(this._lastRemoteAttr&&this.attr._cachedRemote&&objectIsEqual(this._lastRemoteAttr,remoteAttr)){return;}
this._lastRemoteAttr=remoteAttr;if(remoteAttr._if){var condition=funcApply('return ('+remoteAttr._if+')',remoteAttr,this);if(!condition){if('_else'in remoteAttr){var elseval=remoteAttr._else;if(elseval&&typeof(elseval)=='string'){elseval=funcCreate(elseval).call(this);}
this.mergeRemoteContent(elseval);}
return;}}
var kwargs={};for(var attrname in remoteAttr){var value=remoteAttr[attrname];if(value instanceof Date){var abspath=this.absDatapath(this.attr['remote_'+attrname]);var node=genro._data.getNode(abspath);value=asTypedTxt(value,node.attr.dtype);}
if(attrname.indexOf('_')!=0){kwargs[attrname]=value;}else if(attrname=='_onRemote'){_onRemote=funcCreate(value,attrname._onRemote,this);}}
var method=this.attr.remote;var that=this;kwargs.sync=!async;if(objectPop(remoteAttr,'sendInheritedAttributes')){kwargs._inheritedAttributes=this.getInheritedAttributes();}
if(remoteAttr._waitingMessage){var waitingMessage=remoteAttr._waitingMessage===true?_T('Loading content'):remoteAttr._waitingMessage;waitingMessage='<div style="height:130px;opacity:.8;" class="waiting"></div>'+'<div style="font-size:13px">'+waitingMessage+'</div>'
this.setHiderLayer(true,{message:waitingMessage});kwargs.sync=false;}
this._remotebuilding=true;return genro.rpc.remoteCall(method,kwargs,null,'POST',null,function(result){if(result.error){genro.dlg.alert('Error in remote '+result.error,'Error');}else{that.watch('checkPendingRequirs',function(){return!objectNotEmpty(genro.dom.pendingHeaders);},function(){if(remoteAttr._waitingMessage){that.setHiderLayer(false);}
var t0=new Date();that.mergeRemoteContent(result);if(_onRemote){_onRemote();}});}
delete that._remotebuilding;return result;});},getValidationError:function(){if(this._validations){return this._validations.error;}},getValidationWarnings:function(){if(this._validations){return this._validations.warnings;}},isValidationRequired:function(){if((this._validations)&&(this._validations.required)){return true;}},hasValidationWarnings:function(){if((this._validations)&&(objectNotEmpty(this._validations.warnings))){return true;}},hasValidationError:function(){if((this._validations)&&(this._validations.error)){return true;}},resetValidationError:function(){if(this._validations){this._validations.error=null;this._validations.warnings=[];this._validations.required=null;this.updateValidationClasses();}},setValidationError:function(validation_result){this._validations.error=validation_result.error;this._validations.warnings=validation_result.warnings;this._validations.required=validation_result.required;this.updateValidationClasses();},setValidations:function(){this._validations={};},hasValidations:function(){if(this._validations){return true;}},getElementLabel:function(){return this.attr._valuelabel||this.attr.field_name_long||this.attr.name_long||stringCapitalize(this.label);},unwatch:function(watchId){if(this.watches&&this.watches[watchId]){clearInterval(this.watches[watchId]);delete this.watches[watchId];}},watch:function(watchId,conditionCb,action,delay){delay=delay||200;if(this.watches&&(watchId in this.watches)){this.unwatch(watchId);}
if(conditionCb()){action();}else{this.watches=this.watches||{};var that=this;this.watches[watchId]=setInterval(function(){if(conditionCb()){that.unwatch(watchId);action();}},delay);}},updateValidationStatus:function(kw){if(this.widget){if(this.widget.validate){this.widget.validate();}
this.updateValidationClasses();this.widget.state=this.hasValidationError()?'Error':null;this.widget._setStateClass();if(this.form){this.form.updateInvalidField(this,this.attrDatapath('value'));}}},updateValidationClasses:function(){if(this.widget.cellNode){var domnode=this.widget.cellNode;}else{var domnode=this.widget.focusNode;}
if(this.isValidationRequired()){genro.dom.addClass(domnode,'gnrrequired');}else{genro.dom.removeClass(domnode,'gnrrequired');}},isDisabled:function(){return this.getAttributeFromDatasource('disabled');},setDisabled:function(reason){var value=reason?true:false;this.disabled=reason||false;if(this.widget){if(dijit.form._FormWidget.prototype.setDisabled==this.widget.setDisabled){this.widget.setAttribute('disabled',value);}else if(this.widget.setDisabled){this.widget.setDisabled(value);}}else if(this.externalWidget){this.externalWidget.gnr_setDisabled(value);}else if(this.gnrwdg&&this.gnrwdg.setDisabled){this.gnrwdg.setDisabled(value);}
else if(this.domNode){genro.dom.setDomNodeDisabled(this.domNode,value);}},setSource:function(path,source){var content=this.getValue();var child;if(!content){content=new gnr.GnrDomSource();this.setValue(content,false);}else{if(!(content instanceof gnr.GnrDomSource)){this.setValue(content,false);}}
child=content.setItem(path,source.getNodes()[0]);return child;},replaceContent:function(value){var currval=this._value;if(currval instanceof gnr.GnrDomSource){dojo.forEach(currval._nodes,function(n){currval.popNode(n.label);});}else{currval=new gnr.GnrDomSource();this._value=currval;currval.setBackRef(this,this._parentbag);}
if(value){dojo.forEach(value._nodes,function(n){var node=value.popNode(n.label);currval.setItem(node.label,node);});}},mergeRemoteContent:function(value){var mergetable=this.attr.tag=='tbody';var currval=this._value;if(currval instanceof gnr.GnrDomSource){dojo.forEach(currval._nodes,function(n){if(!mergetable||stringStartsWith(n.label,'remote_merged_')){currval.popNode(n.label);}});}else{currval=new gnr.GnrDomSource();this._value=currval;currval.setBackRef(this,this._parentbag);}
if(value){if(mergetable){var valueNode=value.getNodeByAttr('tag','tbody');if(!valueNode){return;}
value=valueNode._value;}
dojo.forEach(value._nodes,function(n){var node=value.popNode(n.label);var label=mergetable?'remote_merged_'+node.label:node.label;currval.setItem(label,node);});}},_:function(tag,name,attributes,extrakw){var content=this.getValue();var child;if(!(content instanceof gnr.GnrDomSource)){content=new gnr.GnrDomSource();this.setValue(content,false);}
child=content._(tag,name,attributes,extrakw);return child;},_destroy:function(){return this.getParentBag().popNode(this.label);},getChild:function(childpath){var v=this._value;if(!v||!(v.getChild)){var clist=childpath.split('/')
if(clist[0]=='parent'){var node=this.getParentNode().getParentNode();v=node.getValue();}}
return v.getChild(childpath);}});dojo.declare("gnr.GnrStructData",gnr.GnrBag,{});dojo.declare("gnr.GnrDomSource",gnr.GnrStructData,{_validationPrefix:'structvalidate_',_nodeFactory:gnr.GnrDomSourceNode,_:function(tag,name,attributes,extrakw){var tag_UpperLower=null;var content;extrakw=extrakw||{};tag=tag.toLowerCase();if(tag){var tagHandler=genro.wdg.getHandler(tag);if(!tagHandler&&this.getParentNode()){var parentTag=this.getParentNode().attr.tag;var parentTagHandler=genro.wdg.getHandler(parentTag);if(parentTagHandler&&parentTagHandler.subtags&&tag.toLowerCase()in parentTagHandler.subtags){tag=parentTag.toLowerCase()+'_'+tag;}}
if(name instanceof Object){extrakw=attributes||{};var attributes=name||{};var name='';if('childname'in attributes){name=name||objectPop(attributes,'childname');}}
var attributes=attributes||{};tag=objectPop(attributes,'tag')||tag;if(attributes&&('remote'in attributes)&&(attributes.remote!='remoteBuilder')){if(typeof(attributes.remote)=="string"){attributes['remote_handler']=attributes.remote;}
else if(attributes.remote instanceof Object){attributes['remote_handler']=objectPop(attributes.remote,'method');for(var prop in attributes.remote){attributes['remote_'+prop]=attributes.remote[prop];};}
attributes.remote='remoteBuilder';}
name=name||'*_?';name=name.replace('*',tag).replace('?',this.len());if(attributes.content){content=attributes.content;delete attributes.content;}
if(content==null){content=new gnr.GnrDomSource();}
attributes.tag=tag;var handler=genro.wdg.getHandler(tag);if(handler&&handler.onStructChild){handler.onStructChild(attributes,this);}
var nIndex=this.index(name);if(nIndex>=0){this.popNode(name);extrakw._position=nIndex;}
this.setItem(name,content,attributes,extrakw);return content;}},component:function(){if(this.component!=null){return this._component;}else if(this.parent!=null){return this.parent.component();}},getChild:function(childpath){childpath=childpath.split('/');var curr=this;var node;dojo.forEach(childpath,function(childname){if(childname=='parent'){node=curr.getParentNode().getParentNode();curr=node.getValue();}else if(childname.indexOf('#')==0){node=curr.getParentNode();node=node.nodeById(childname.slice(1));curr=node.getValue();}
else{curr.forEach(function(n){if(n.attr._childname==childname){node=n;}},'static');if(node){return}
node=curr.walk(function(n){if('_childname'in n.attr){return n.attr._childname==childname?n:true;}},'static');if(node==true){return;}else{curr=node.getValue();if(!(curr instanceof gnr.GnrBag)){return;}}}});return node===true?null:node;}});



const _lf='\n';const _crlf='\r\n';const _tab='\t';function _px(v){v+='';if(v.indexOf('px')<0){v+='px';}
return v;};function _T(str,lazy){if(isNullOrBlank(str)){return str;}
var locale=genro.locale()||'en-EN';var language=locale.split('-')[0];var localekey='localsdict_'+language;var noLocMarker=(str.search(/^!!|\[!!/)<0);if(lazy&&noLocMarker){return str;}
var localsdict=genro.getFromStorage('local',localekey)||{};if(isNullOrBlank(localsdict[str])){var toTranslate=noLocMarker?'!!'+str:str;var result=genro.serverCall('getRemoteTranslation',{txt:toTranslate,language:language})||{};var localizedString=result['translation'];if(result.status!='OK'){localsdict[str]='<span class="unlocalized">'+localizedString+'</span>';}
localsdict[str]=localizedString;genro.setInStorage('local',localekey,localsdict);return localizedString;}else{return localsdict[str];}
return str;}
function _F(val,format,dtype){return gnrformatter.asText(val,{format:format,dtype:dtype});};function _IN(val,str){var l=str.split(',');return l.indexOf(val)>=0;};function isBag(value){return value&&(value.htraverse!=null);};function isNumericType(dtype){return dtype in{'R':null,'L':null,'I':null,'N':null};}
function pyref(ref,mode){var node=genro.src._main.getNodeByAttr('__ref',ref);if(mode=='w'){return node.widget;}
if(mode=='d'){return node.getDomNode();}
if(mode=='f'){return node.form;}
return node;};function bagAsObj(bag){var result={};var parentNode=bag.getParentNode();if(parentNode){result._a=parentNode.attr;}
dojo.forEach(bag.getNodes(),function(n){result[n.label]=n.getValue();});return result;};function objectAsGrid(obj,labels){var labels=labels||'label,value';labels=labels.split(',');var result=new gnr.GnrBag();if(!obj){return result;}
var i=0;var v;for(var k in obj){v=new gnr.GnrBag();v.setItem(labels[0],k);v.setItem(labels[1],obj[k]);result.setItem('r_'+i,v);i++;}
result.sort('#k');return result;};function objectAsHTMLTable(obj,labels){labels=labels||'label,value';var b=objectAsGrid(obj);return b.asHtmlTable({cells:labels});};function arrayContains(arr,item){for(var i=0;i<arr.length;i++){if(arr[i]==item){return true;}}
return false;}
function copyArray(arraylike){if(!arraylike){return[];}
var result=[];dojo.forEach(arraylike,function(n){result.push(n);});return result;};function arrayIndexOf(arr,item){for(var i=0;i<arr.length;i++){if(arr[i]==item){return i;}}
return-1;}
function arrayPushNoDup(arr,item){if(dojo.indexOf(arr,item)<0){arr.push(item);};};function arrayUniquify(arr){var result=[];dojo.forEach(arr,function(n){if(dojo.indexOf(result,n)<0){result.push(n);}});return result;};function arrayMatch(a,matchString){if(matchString.indexOf('*')>=0){matchString=matchString.replace('*','(.*)');}
return dojo.filter(a,function(item){return item.match(matchString);});}
function smartsplit(path,on){var escape="\\"+on;var pathlist=null;if(path.indexOf(escape)!=-1){var chrOne=new java.lang.Character(1);path=path.replace(escape,chrOne);pathlist=path.split(on);for(var i in pathlist){pathlist[i].replace(chrOne,on);}}
else pathlist=path.split(on);return pathlist;}
function stringSplit(s,c,n){if(n){var f=s.split(c,n);var g=s.split(c);if(f.length<g.length){f.push(g.slice(f.length).join(c));}
return f;}else{return s.split(c);}}
function stringEndsWith(s,v){return(s.slice(-v.length)==v);}
function stringStartsWith(s,v){return(s.slice(0,v.length)==v);}
function stringContains(s,v){return(s.indexOf(v)>=0);}
function stringCapitalize(str,firstOnly){if(firstOnly){return str[0].toUpperCase()+str.slice(1);}
return str.replace(/\w+/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1);});};function dataTemplate(str,data,path,showAlways,kw){var kw=kw||{};var defaults=kw.defaults||{};if(!str){return'';}
if(typeof(str)=='object'&&str.cb){var templateHandler=str;if(!templateHandler.template){templateHandler.cb.call(templateHandler);}
str=templateHandler.template;defaults=templateHandler.defaults||defaults;showAlways=showAlways||templateHandler.showAlways;}
var templates=kw.templates;var masks=kw.masks||{};var df_templates=kw.df_templates||{};var formats=kw.formats||{};var dtypes=kw.dtypes||{};var editcols=kw.editcols||{};var auxattr={};var scopeSourceNode=null;var regexpr=/\$(\#?\@?[a-zA-Z0-9_]+)(\.@?[a-zA-Z0-9_]+)*(\?[a-zA-Z0-9_]+)?(\^[a-zA-Z0-9_]+)?/g;var result;var is_empty=true;var has_field=false;if(str instanceof gnr.GnrBag){templates=str;var mainNode=templates.getNode('main');str=mainNode.getValue();masks=mainNode.attr.masks||masks;editcols=mainNode.attr.editcols||editcols;formats=mainNode.attr.formats||formats;df_templates=mainNode.attr.df_templates||df_templates;dtypes=mainNode.attr.dtypes||dtypes;}
if(data&&typeof(data)=='string'){data=genro._data.getItem(data);}
else if(data instanceof gnr.GnrDomSourceNode){auxattr=data.currentAttributes();scopeSourceNode=data;data=genro._data.getItem(data.absDatapath(path));}
if(!data&&!showAlways){return'';}
if(str.indexOf('${')>=0){str=str.replace(/\${(([^}]|\n)*)}/g,function(s0,content){if(!content){return'';}
var m=content.match(/\$([_a-z\\@][_a-z0-9\\(.|\n)\\@]*)/);if(!m){return'';}
var k=data.getItem?data.getItem(m[1]):data[m[1]];return isNullOrBlank(k)?'':content;});}
if(data instanceof gnr.GnrBag){if(!data&&!showAlways){return'';}
result=str.replace(regexpr,function(){var l=arguments.length;has_field=true;var path=arguments[0].slice(1);path=path.indexOf('^')>=0?path.split('^')[0]:path;var value,valueNode;var as_name=arguments[l-3];as_name=as_name?as_name.slice(1):path;var attrname=arguments[l-4];attrname=attrname?attrname.slice(1):null;var valueattr={};var dtype=dtypes[as_name];var editpars=editcols[as_name];if(scopeSourceNode&&stringStartsWith(path,'#')){valueNode=genro.getDataNode(scopeSourceNode.absDatapath(path));}else{valueNode=data.getNode(path);}
if(valueNode){valueattr=valueNode.attr;dtype=valueattr.dtype||dtype;value=attrname?valueattr[attrname]:valueNode.getValue(null,{_sourceNode:scopeSourceNode});if('values'in valueattr){value=objectFromString(valueattr.values)[value];}}else{value=auxattr[as_name]}
if(value instanceof gnr.GnrBag){var subtpl=templates?templates.getItem(as_name):null;if(subtpl){var subval=[];var vl;value.forEach(function(n){vl=n.getValue();subval.push(dataTemplate(subtpl,vl));});value=subval.join('');}else if(as_name in df_templates){value=dataTemplate(data.getItem(df_templates[as_name]),value);}else{value=value.getFormattedValue();}}else{if(editpars){if(editpars['relating_column']&&editpars['caption_field']){value=data.getItem(editpars['caption_field']);}}else{value=valueattr._displayedValue||value;}
if(formats[as_name]){value=gnrformatter.asText(value,{format:formats[as_name],dtype:dtype});}
if(editpars){value='<div class="gnrinlinewidget_container"><div class="gnreditabletext" ondblclick="inlineWidget(event)" varname="'+as_name+'" >'+(isNullOrBlank(value)?'&nbsp':value)+'</div></div>';}
if(masks[as_name]){value=gnrformatter.asText(value,{mask:masks[as_name]});}else if(valueattr._formattedValue){value=valueattr._formattedValue;}}
if(value!=null){is_empty=false;if(value instanceof Date){value=dojo.date.locale.format(value,{selector:dtype=='H'?'time':'date',format:'short'});}
return value;}else if(showAlways){is_empty=false;return defaults[as_name];}else{return'';}});}else{data=data||{};var p,plist,sub;result=str.replace(regexpr,function(path){has_field=true;plist=path.slice(1).split('.');p=plist[0];var value=data[p];if(value!=null){is_empty=false;sub=plist.slice(1);if(sub.length&&value instanceof gnr.GnrBag){return gnrformatter.asText(value.getItem(sub));}
return gnrformatter.asText(value,formats[p]);}else{return'';}});}
if(has_field&&is_empty&&!showAlways){return'';}else{return result;}};function stringStrip(s){if(!s)return s;return s.replace(/^[ \t\r\n]+/,'').replace(/[ \t\r\n]+$/,'');}
function splitStrip(s,sp){r=[];var sp=sp||',';dojo.forEach(s.split(sp),function(v){r.push(stringStrip(v));});return r;}
function argumentsReplace(s){return s.replace(/\$(\d+)/g,function(s,n){return"arguments["+(parseInt(n)-1)+"]";});}
function keyName(keyCode){var dk=dojo.keys;for(var keyName in dk){if(dk[keyName]==keyCode){return keyName;}}};function bagPathJoin(path1,path2){var path1=path1.split('.');while(path2.indexOf('../')==0){path2=path2.slice(3);path1.pop();}
path1=path1.concat(path2.split('.'));return path1.join('.');}
function objectPop(obj,key,dflt){var result;if(obj&&(key in obj)){result=obj[key];delete obj[key];}else{result=(typeof dflt=='undefined')?null:dflt;}
return result;}
function objectPopAll(obj){for(var key in obj){delete obj[key];}}
function objectKeyByIdx(obj,idx){var k=0;for(var prop in obj){if(k==idx){return prop;}
k++;}}
function isEqual(a,b){if((a===null||a===undefined)&&(b===null||b===undefined)){return true;}
if(a instanceof gnr.GnrBag&&b instanceof gnr.GnrBag){return a.isEqual(b);}
if(a instanceof Array&&b instanceof Array){return a.length==b.length&&!a.some(function(elem,idx){return!isEqual(elem,b[idx])});}
a=a instanceof Date?a.valueOf():a;b=b instanceof Date?b.valueOf():b;return objectIsEqual(a,b);};function objectIsEqual(obj1,obj2){if(obj1==obj2){return true;}else{if((obj1 instanceof Object)&&(obj2 instanceof Object)){for(a in obj1){if(!(obj2[a]===obj1[a])){return false;}}
for(a in obj2){if(!(obj2[a]===obj1[a])){return false;}}
return true;}else{return false;}}}
function isNullOrBlank(elem){return elem===null||elem===undefined||elem==='';}
function localType(dtype){return{'R':{places:2},'L':{places:0},'I':{places:0},'D':{date:'short'},'H':{time:'short'},'HZ':{time:'short'},'DH':{datetime:'short'},'DHZ':{datetime:'short'}}[dtype];}
function normalizeKwargs(kwargs,str){if(!kwargs){return;}
var p=objectPop(kwargs,str);var kw=objectExtract(kwargs,str+'_*');if(!p&&!objectNotEmpty(kw)){kw=null;}
if(p===true||p===null){return kw||(p?{}:null);}
if(typeof(p)=='object'){kw=objectUpdate(kw||{},p);}else{kw._=p;}
return kw;}
function objectExtract(obj,keys,dontpop,dontslice){if(!obj){return{};}
var result={};var key,m;if(keys.slice(-1)=='*'){key=keys.slice(0,-1);var key_len=key.length;for(var prop in obj){if(prop.slice(0,key_len)==key){result[dontslice?prop:prop.slice(key_len)]=obj[prop];if(!dontpop){delete obj[prop];}else if(dontpop!=true){if(!(prop in dontpop)){delete obj[prop];}}}}}else{keys=keys.split(',');for(var i=keys.length;i--;){key=stringStrip(keys[i]);if(key in obj){result[key]=obj[key];if(!(dontpop)){delete obj[key];}}}}
return result;}
function objectNotEmpty(obj){if(obj){for(var prop in obj){return true;}}
return false;}
function objectAny(obj,cb){if(obj){for(var k in obj){if(cb(k,obj[k])){return true;}}}
return false;}
function mapConvertFromText(value){if(isNullOrBlank(value)){return value;}
if(value instanceof Array){return value.map(mapConvertFromText);}
if(typeof(value)=='string'){return convertFromText(value);}
if(typeof(value)=='object'&&!(value instanceof Date)){var result={};for(var k in value){result[k]=mapConvertFromText(value[k]);}
return result;}
return value;}
function objectString(obj){var result=[];for(var prop in obj){result.push(prop+':'+obj[prop]);}
return result.join(',');}
function objectSize(obj){var n=0;for(var prop in obj){n=n+1;}
return n;}
function objectKeys(obj){var keys=[];for(var prop in obj){keys.push(prop);}
return keys;}
function objectItems(obj){var keys=[];for(var prop in obj){keys.push({key:prop,value:obj[prop]});}
return keys;}
function objectValues(obj){var values=[];for(var prop in obj){values.push(obj[prop]);}
return values;}
function objectFuncReplace(obj,funcname,func){var oldfunc=obj[funcname];obj[funcname]=func;if(oldfunc){obj[funcname+'_replaced']=oldfunc;}}
function objectMixin(obj,source){if(source){for(var prop in source){objectFuncReplace(obj,prop,source[prop]);}}
return obj;}
function objectMap(obj,func){for(var k in obj){obj[k]=func(obj[k]);}}
function copyJson(obj){return JSON.parse(JSON.stringify(obj));}
function objectUpdate(obj,source,removeNulls){if(source){if(source instanceof gnr.GnrBag){source=source.asDict();}
var val;for(var prop in source){val=source[prop];if(removeNulls&&(val==null)){delete obj[prop];}else{obj[prop]=source[prop];}}}
return obj;}
function objectIsContained(obj1,obj2){for(a in obj1){if(!(obj2[a]===obj1[a])){return false;}}
return true;}
function objectRemoveNulls(obj,blackList){blackList=blackList||[null];var result={};for(var prop in obj){if((obj[prop]!=null)&&(obj[prop]!='')){result[prop]=obj[prop];}}
return result;}
function objectDifference(objOld,objNew){var result={};for(var prop in objNew){if(!prop in objOld){result[prop]=['I',objNew[prop]];}else if(objOld[prop]!=objNew[prop]){result[prop]=['U',objOld[prop],objNew[prop]];}}
for(var prop in objOld){if(!(prop in objNew)){result[prop]=['D',objOld[prop]];}}
return result;}
function objectAsXmlAttributes_old(obj,sep){var sep=sep||' ';var val;var result=[];for(var prop in obj){val=obj[prop];if(typeof(val)=='string'){val=val.replace(/\</g,'&lt;');val=val.replace(/\&/g,'&amp;');val=val.replace(/\>/g,'&gt;');val=val.replace(/\"/g,'&quot;');val=val.replace(/\'/g,'&apos;');val=val.replace(/\n/g,'&#10;');val=val.replace(/\r/g,'&#13;');val=val.replace(/\t/g,'&#09;');result.push(prop+"="+quoted(val));}else if(typeof(obj[prop])!='function'){result.push(prop+"="+quoted(asTypedTxt(obj[prop])));}}
return result.join(sep);}
function objectAsXmlAttributes(obj,sep){sep=sep||' ';var val;var result=[];for(var prop in obj){val=obj[prop];if(typeof(val)=='function'){continue;}
if(typeof(val)!='string'){val=asTypedTxt(val);}
val=val.replace(/\</g,'&lt;');val=val.replace(/\&/g,'&amp;');val=val.replace(/\>/g,'&gt;');val=val.replace(/\"/g,'&quot;');val=val.replace(/\'/g,'&apos;');val=val.replace(/\n/g,'&#10;');val=val.replace(/\r/g,'&#13;');val=val.replace(/\t/g,'&#09;');result.push(prop+"="+quoted(val));}
return result.join(sep);}
function objectAsStyle(obj){var sep=sep||' ';var result=[];var val;for(var prop in obj){val=obj[prop];if(!isNullOrBlank(val)){result.push(prop+":"+obj[prop]+';');}}
return result.join(' ');}
function objectFromStyle(style){var result={};if(style){stylelist=style.split(';');for(var i=0;i<stylelist.length;i++){var onestyle=stylelist[i];if(stringContains(onestyle,':')){var kv=onestyle.split(':');result[stringStrip(kv[0])]=stringStrip(kv[1]);}}}
return result;};function objectFromString(values,sep,mode){if(!values){return{};}
var ch=sep||(values.indexOf('\n')>=0?'\n':',');values=values.split(ch);var result={};for(var i=0;i<values.length;i++){val=values[i];if(val.indexOf(':')>0){val=val.split(':');result[val[0]]=val[1];}else if(mode=='k'){result[val]=true;}else if(mode=='kv'){result[val]=val;}else{result['caption_'+i]=val;}}
return result;};stripBlank=function(string){var re=/\w+/;return re.exec(string);};templateReplace=function(string,symbolsdict){var re=/\$([\w]*)/;while(string.search(re)!=-1){var k=re.exec(string)[1];var v=symbolsdict[k]||'';string=string.replace(re,v);}
return string;};zip=function(list){var result=[];var curr=null;var tuple;var tc=list.length;if(tc==0){return[];}
var tn=list[0].length;for(var i=0;i<tn;i++){tuple=[];for(var j=0;j<tc;j++){tuple.push(list[j][i]);}
result.push(tuple);}
return result;};function asTypedTxt(value,dtype){if(typeof(value)=='function'){return;}
var typedText=convertToText(value,{'xml':true,'dtype':dtype});var valType=typedText[0];var valText=typedText[1];if(valType!=''&&valType!='T'){value=valText+'::'+valType;}
return value;};function quoted(astring){var mystring=new String(astring);if(mystring.indexOf('"')==-1){return'"'+mystring+'"';}
if(mystring.indexOf("'")==-1){return"'"+mystring+"'";}
else{return"invalid string";}};function convertFromText(value,t,fromLocale){if(isNullOrBlank(value)){return null}
if(typeof(value)!='string'){return value;}
if(!t){var k=value.lastIndexOf('::');if(k>=0){t=value.slice(k).slice(2);if(['HTML','JS','RPC','JSON','NN','BAG','A','T','L','N','I','B','D','H','DH','DHZ','P','X'].indexOf(t)>=0){value=value.slice(0,k);}}}
var t=t||'T';var result;t=t.toUpperCase();if(t=='NN'){return null;}
else if(t=='L'){if(fromLocale){value=dojo.number.parse(value);}else{value=parseInt(value);}
value._gnrdtype=t;return value;}
else if(t=='R'||t=='N'){if(fromLocale){value=dojo.number.parse(value);}else{value=parseFloat(value);}
value._gnrdtype=t;return value;}
else if(t=='B'){return(value.toLowerCase()=='true');}
else if((t=='D')||(t=='DH')||(t=='DHZ')){if(fromLocale){var selector=(t=='DH'||t=='DHZ')?'datetime':'date';result=dojo.date.locale.parse(value,{selector:selector});}else{if(t=='D'){value=value.split('.')[0].replace(/\-/g,'/');}
result=new Date(value);}
result._gnrdtype=t;return result;}
else if(t=='H'){if(fromLocale){result=dojo.date.locale.parse(value,{selector:'time'});}else{value=value.split(':');if(value.length<3){value.push('00');}
result=new Date(1971,null,null,Number(value[0]),Number(value[1]),Number(value[2]));}
result._gnrdtype=t;return result;}
else if(t=='JS'){if(window.genro){return genro.evaluate(value);}else{return dojo.fromJson(value);}}
else if(t=='BAG'||t=='X'){try{return new gnr.GnrBag(value);}catch(e){console.error('Parsing error',e.toString());return new gnr.GnrBag({error:e.toString()});}}
return value;}
var gnrformatter={asText:function(value,valueAttr){var formatKw=objectUpdate({},valueAttr);var dtype=objectPop(formatKw,'dtype');var formattedValue;var format=objectPop(formatKw,'format');if((value===null||value===undefined)&&dtype!='B'){if(isNumericType(dtype)&&format&&format.includes(';')){value=0;}else{return'';}}
dtype=dtype||guessDtype(value);if(format&&typeof(format)!='string'){var formatdict=format;format=objectPop(format,'format')||objectPop(format,'pattern');objectUpdate(formatKw,formatdict);}
if(format&&dtype=='L'&&format.indexOf('.')>=0){dtype='N';}
objectUpdate(formatKw,objectExtract(formatKw,'format_*'));var handler=this['format_'+dtype];var mask=formatKw.mask;if(handler){formattedValue=handler.call(this,value,format,formatKw);}else{formattedValue=value+'';}
if(!mask||!formattedValue){return formattedValue;}
return mask.replace(/%s/g,formattedValue);},format_P:function(value,format,formatKw){if(!format){return value;}
var c,c_zoom;if(typeof(format)=='string'&&stringStartsWith(format,'auto')){if(format.indexOf(':')){format=format.split(':')
var c_zoom=parseFloat(format[1]);}
if(value.indexOf('?')>=0){var parsedUrl=parseURL(value);format=objectExtract(parsedUrl.params,'v_*');value=value.split('?')[0];if(parsedUrl.params._pc){value=genro.addParamsToUrl(value,{_pc:parsedUrl.params._pc});}}}
if(typeof(format)=='string'){format=objectFromString(format);}
if(formatKw){format=objectUpdate(format,formatKw);}
format['style']=format['style']||'';if('h'in format){var c_style='';if(c_zoom){format['h']=format['h']*c_zoom;format['w']=format['w']*c_zoom;}
var c='<div style="height:'+format["h"]+'px;width:'+format["w"]+'px;overflow:hidden;'+format["style"]+'">';objectPop(format,'style');if(c_zoom){c_style="-webkit-transform:scale("+c_zoom+");-webkit-transform-origin:0px 0px;-moz-transform:scale("+c_zoom+");-moz-transform-origin:0px 0px;"}
c=c+'<div style="'+c_style+'">';}
var img_style='margin-top:'+(-parseFloat(format['y']||0))+'px; margin-left:'+(-parseFloat(format['x']||0))+'px;-webkit-transform:scale('+parseFloat(format['z']||1)+') rotate('+parseFloat(format['r']||0)+'deg); -moz-transform:scale('+parseFloat(format['z']||1)+') rotate('+parseFloat(format['r']||0)+'deg);';var img='<img style="'+img_style+(format['style']||'')+'" src="'+value+'"/>';if(c){return c_zoom?c+img+'</div></div>':c+img+'</div>';}
return img;},format_T:function(value,format,formatKw){if(value===''){return value;}
if(!format){return value;}
if(format=='autolink'){return highlightLinks(value);}
if(format=='mailto'){return makeLink('mailto:'+value,value);}
if(format=='phone'){return makeLink('tel:'+value,value);}
if(format=='skype'){return makeLink('skype:'+value,value);}
if(format=='download'){return makeLink(value,'Download',true);}
if(format=='playsound'){return makeLink('javascript:genro.lockScreen(true,"sound"); genro.playUrl("'+value+'",function(){genro.lockScreen(false,"sound")});','<div class="iconbox sound"></div>')}
if(typeof(format)=='string'&&format.indexOf('#')>=0){format=format.split('');value=value.split('');var result=[];dojo.forEach(format,function(n){if(n==value[0]||n=='#'){if(value.length>0){result.push(value.shift());}}else{result.push(n);}});result=result.concat(value);return result.join('');}},format_D:function(value,format,formatKw){if(!value){return'';}
var opt={selector:'date'};var standard_format='long,short,medium,full';var week_format=['-W','-w','-WD']
var result='';if(format){if(standard_format.indexOf(format)>=0){opt.formatLength=format;}else if(week_format.indexOf(format)>=0){return''+deltaWeeks(null,value,format.slice(1));;}else{opt.datePattern=format;}}
return dojo.date.locale.format(value,objectUpdate(opt,formatKw));},format_H:function(value,format,formatKw){var opt={selector:'time'};var standard_format='long,short,medium,full'
if(format){if(standard_format.indexOf(format)>=0){opt.formatLength=format;}else{opt.timePattern=format;}}
return dojo.date.locale.format(value,objectUpdate(opt,formatKw));},format_DHZ:function(value,format,formatKw){return this.format_DH(value,format,formatKw);},format_DH:function(value,format,formatKw){if(typeof(value)=="number"){value=new Date(value)}
var opt={selector:'datetime'};var standard_format='long,short,medium,full';var week_format=['-W','-w','-WD']
if(format){if(standard_format.indexOf(format)>=0){opt.formatLength=format;}else if(week_format.indexOf(format)>=0){return''+deltaWeeks(null,value,format.slice(1));}else{format=format.split('|');opt.datePattern=format[0];opt.timePattern=format[1];}}
return dojo.date.locale.format(value,objectUpdate(opt,formatKw));},format_B:function(value,format,formatKw){var format=format||'true,false';format=format.split(',');return(value===null&&format.length==3)?format[2]:(value?format[0]:format[1]);},format_L:function(value,format,formatKw){formatKw.places=0;return this.format_N(value,format,formatKw);},format_R:function(value,format,formatKw){return this.format_N(value,format,formatKw);},format_N:function(value,format,formatKw){var opt={};var standard_format='decimal,scientific,percent,currency';if(format){if(format.indexOf(';')>=0){var formats=format.split(';');if(value===0){return formats[1];}
if(value<0&&formats.length>2){format=formats[2];value=-value;}else{format=formats[0];}}
if(standard_format.indexOf(format)>=0){opt.type=format;}else{opt.pattern=format;}}
if(format=='meter'||format=='progress'){formatKw=formatKw||{};formatKw.min=formatKw.min||0;formatKw.max=formatKw.max||100;var p=[];for(var k in formatKw){p.push(k+'="'+formatKw[k]+'"')}
return'<'+format+' style="width:100%;" value="'+value+'"'+' '+p.join(' ')+' ></'+format+'>';}
if(format=='bytes'){var s=['Bytes','KB','MB','GB','TB'];if(value==0){return'0 Bytes'};var i=parseInt(Math.floor(Math.log(value)/Math.log(1024)));return(value/Math.pow(1024,i)).toFixed(1)+' '+s[[i]]}
if(format=='epoch'){return _F(new Date(value*1000))}
if(format=='DHMS'){var r=[]
var curr=value;r.push(curr%60+'s');curr=Math.floor(curr/60);if(curr){r.push(curr%60+'m');curr=Math.floor(curr/60);if(curr){r.push(curr%24+'h');curr=Math.floor(curr/24);if(curr){r.push(curr+'d');}}}
r.reverse();return r.join(' ')}
return(formatKw.currency?dojo.currency:dojo.number).format(value,objectUpdate(opt,formatKw))},format_X:function(value,format,formatKw){return value.getFormattedValue(format);},format_AR:function(value,joiner,formatKw){value=dojo.map(value,function(n){return _F(n)});return value.join(joiner||',');},format_NN:function(value,format,formatKw){return'';},format_FUNC:function(value,format,formatKw){return value.toString();},format_OBJ:function(value,format,formatKw){var result=[];var v;var indent=formatKw.indent||'';if(indent){result.push('')}
formatKw.format_indent=indent+'  ';for(var k in value){v=this.asText(value[k],formatKw);result.push(indent+k+':'+v);}
formatKw.format_indent=indent;return result.join(format||'\n');}}
function guessDtype(value){if(value instanceof File){return'FILE';}
if(value===null||value===undefined){return'NN';}
if(isBag(value)){return'X'}
if(value instanceof gnr.GnrBagNode){return'BAGNODE';}
var t=typeof(value);if(t=='string'){return'T';}
if(t=='boolean'){return'B';}
if(t=='number'){return value%1==0?'L':'N';}if(t=='function'){return'FUNC';}
if(value instanceof Date){if((value.getFullYear()==1970)&&(value.getMonth()==11)&&(value.getDate()==31)){return'H';}
if((value.getHours()==0)&&(value.getMinutes()==0)&&(value.getSeconds()==0)&&(value.getMilliseconds()==0)){return'D';}
return'DH';}
if(value instanceof Array){return'AR';}
return'OBJ';};function convertToText(value,params){if(value==null||value==undefined){return['NN',''];}
var result;var opt;params=objectUpdate({},params);var mask=objectPop(params,'mask');var format=objectPop(params,'format');var dtype=objectPop(params,'dtype');var forXml=objectPop(params,'xml');var t=typeof(value);if(t=='string'){result=['T',value];}
else if(t=='boolean'){format=format||'true,false';format=format.split(',');if(value===null&&format.length==3){result=format[2];}else{result=value?format[0]:format[1];}
result=['B',result];}else if(t=='number'){if(format){var v=numFormat(value,format);}else{var v=value.toString();}
if(dtype){result=[dtype,v];}
else{if(value==parseInt(v)){result=['L',v];}else{result=['N',v];}}}
else if(value instanceof Date){var selectors={'D':'date','H':'time','DH':null};if(!dtype){dtype=value._gnrdtype||(value.toString().indexOf('Thu Dec 31 1970')==0?'H':'D');}
var opt={'selector':selectors[dtype]};if(dtype=='DHZ'){return['DHZ',value.toISOString()]}
if(forXml){opt.timePattern='HH:mm:ss';opt.datePattern='yyyy-MM-dd';}else{opt=objectUpdate(opt,params);opt.formatLength=format;}
var result=[dtype||'D',v=dojo.date.locale.format(value,opt)];}
else if(value.toXml){result=['bag',value.toXml({mode:'static'})];}
else if(t=='object'){result=['JS',dojo.toJson(value)];}
if(mask){result[1]=mask.replace(/%s/g,result[1]);}
return result;};function asText(value,params){return convertToText(value,params)[1];};function numFormat(num,params){if(typeof(params)=='string'){var decimal_precision=params[2];var thousand_sep=params[0];var decimal_sep=params[1];}else{params=params||{};var decimal_precision=params['decimal_precision']||0;var thousand_sep=params['thousand_sep']||',';var decimal_sep=params['decimal_sep']||'.';}
num=num||0;if(typeof(num)=='string'){num=parseFloat(num);}
num_str=num.toFixed(decimal_precision);var arr,int_str,dec_str;if(num_str.indexOf('.')!=-1){arr=num_str.split('.');int_str=arr[0];dec_str=arr[1];}else{int_str=num_str;dec_str='0';}
var c=0;var sep_str="";for(var x=int_str.length;x>0;x--){c=c+1;if(c==4&&int_str[x-1]!='-'){c=0;sep_str=thousand_sep+sep_str;}
sep_str=int_str[x-1]+sep_str;}
if(decimal_precision>0){return sep_str+decimal_sep+dec_str;}else{return sep_str;}}
function parseArgs(arglist){var kwargs={};if(arglist.length>1){if(arglist[arglist.length-1]instanceof Object){kwargs=arglist.pop();}}
return[arglist,kwargs];}
function isdigit(value){return!(value.replace(/\d/g,""));}
function xml_buildTag(tagName,value,attributes,xmlMode){var dtype=attributes?attributes.dtype:null;var typedText=convertToText(value,{'dtype':dtype,xml:true});var valType=typedText[0];var valText=typedText[1];var attrAsText=objectAsXmlAttributes(attributes);var originalTag=tagName;tagName=originalTag.replace(/\W/g,'_').replace('__','_');if(isdigit(tagName.slice(0,1))){tagName='_'+tagName;}
if(tagName!=originalTag){var result='<'+tagName+' _tag="'+originalTag+'"';}else{var result='<'+tagName;}
if(valType!=''&&valType!='T'){result=result+' _T='+quoted(valType);}
if(attrAsText){result=result+' '+attrAsText;}
if(valText!=''){if(!xmlMode){if(valText.search(/<|>|&/)!=-1){valText='<![CDATA['+valText+']]>';}}
if(valText.indexOf('\n')!=-1){valText='\n'+valText+'\n';}
result=result+'>'+valText+'</'+tagName+'>';}
else{result=result+'/>';}
return result;}
function timeStamp(){var d=new Date();return d.valueOf();}
function macroExpand_GET(fnc){var macroGET=/(\W|^)GET (?:\s*)(\^?[\w\.\#\@\$\?-]+)/g;fnc=fnc.replace(macroGET,"$1this.getRelativeData('$2')");return fnc;}
function macroExpand_SET(fnc){var macroSET=/(\W|^)SET (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm;fnc=fnc.replace(/;SET/g,'; SET').replace(macroSET,"$1this.setRelativeData('$2', $3)$4 ");return fnc;}
function macroExpand_PUT(fnc){var macroSET=/(\W|^)PUT (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm;fnc=fnc.replace(/;PUT/g,'; PUT').replace(macroSET,"$1this.setRelativeData('$2', $3, null, false, false)$4 ");return fnc;}
function macroExpand_FIRE(fnc){var macroSET=/(\W|^)FIRE (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g;fnc=fnc.replace(/;FIRE/g,'; FIRE').replace(macroSET,"$1this.setRelativeData('$2', $3, null, true)$4 ");var macroSET=/(\W|^)FIRE (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)(;?)/g;fnc=fnc.replace(/;FIRE/g,'; FIRE').replace(macroSET,"$1this.setRelativeData('$2', true, null, true)$3 ");return fnc;}
function macroExpand_FIRE_AFTER(fnc){var macroSET=/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g;fnc=fnc.replace(/;FIRE_AFTER/g,'; FIRE_AFTER').replace(macroSET,"$1this.setRelativeData('$2', $3, null, true,null,10)$4 ");var macroSET=/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)(;?)/g;fnc=fnc.replace(/;FIRE_AFTER/g,'; FIRE_AFTER').replace(macroSET,"$1this.setRelativeData('$2', true, null, true,null,10)$3 ");return fnc;}
function macroExpand_PUBLISH(fnc){var macroSET=/(\W|^)PUBLISH (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g;fnc=fnc.replace(/;PUBLISH/g,'; PUBLISH').replace(macroSET,"$1genro.publish('$2', $3)$4 ");var macroSET=/(\W|^)PUBLISH (?:\s*)(\^?[\w\.\#\@\$\?-]+)(?:\s*)(;?)/g;fnc=fnc.replace(/;PUBLISH/g,'; PUBLISH').replace(macroSET,"$1genro.publish('$2')$3 ");return fnc;}
function cleanJsCode(code){return code.replace(/\n/g,'').replace(/;(\s)+/g,';');}
function escapeLiterals(code){return code.replace(/'/g,"\\\'").replace(/"/g,"\\\'");}
function eventToString(e){var result='';if(e.shiftKey){result+="Shift";}
if(e.ctrlKey){result+="Ctrl";}
if(e.altKey){result+="Alt";}
if(e.metaKey){result+="Meta";}
return result;}
function serialize(_obj){switch(typeof _obj){case'number':case'boolean':case'function':return _obj;break;case'string':return'\''+_obj+'\'';break;case'object':var str;if(_obj.constructor===Array||typeof _obj.callee!=='undefined'){str='[';var i,len=_obj.length;for(i=0;i<len-1;i++){str+=serialize(_obj[i])+',';}
str+=serialize(_obj[i])+']';}
else{str='{';var key;for(key in _obj){str+=key+':'+serialize(_obj[key])+',';}
str=str.replace(/\,$/,'')+'}';}
return str;break;default:return'UNKNOWN';break;}}
function stringHash(str){var result=str.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);return Math.abs(result);};function stringToColour(str){if(!str){return;}
while(str.length<30){str+=str;}
var hash=0;for(var i=0;i<str.length;i++){hash=str.charCodeAt(i)+((hash<<5)-hash);}
var colour='#';for(var i=0;i<3;i++){var value=(hash>>(i*8))&0xFF;colour+=('00'+value.toString(16)).substr(-2);}
return colour;};function parseURL(url){var a=document.createElement('a');a.href=url;return{source:url,protocol:a.protocol.replace(':',''),host:a.hostname,port:a.port,query:a.search,origin:a.origin,pathname:a.pathname,params:(function(){var ret={},seg=a.search.replace(/^\?/,'').split('&'),len=seg.length,i=0,s;for(;i<len;i++){if(!seg[i]){continue;}
s=seg[i].split('=');ret[s[0]]=s[1];}
return ret;})(),file:(a.pathname.match(/\/([^\/?#]+)$/i)||[,''])[1],hash:a.hash.replace('#',''),path:a.pathname.replace(/^([^\/])/,'/$1'),relative:(a.href.match(/tps?:\/\/[^\/]+(.+)/)||[,''])[1],segments:a.pathname.replace(/^\//,'').split('/')};}
function serializeURL(parsedUrl){var result=parsedUrl.origin+parsedUrl.pathname||'';return genro.addParamsToUrl(result,parsedUrl.params);};function funcCreate(fnc,pars,scope,showError){if(fnc){var pars=pars||'';if(typeof(fnc)=='string'){if(scope&&(fnc in scope)){return scope[fnc];}
var fnc=stringStrip(fnc);fnc=argumentsReplace(fnc);fnc=macroExpand_GET(fnc);fnc=macroExpand_SET(fnc);fnc=macroExpand_PUT(fnc);fnc=macroExpand_FIRE_AFTER(fnc);fnc=macroExpand_PUBLISH(fnc);fnc=macroExpand_FIRE(fnc);if(!stringStartsWith(fnc,'function')){fnc='function('+pars+'){'+fnc+'\n}';}
fnc=genro.evaluate(fnc,showError);if(scope){fnc=dojo.hitch(scope,fnc);}}
return fnc;}}
function makeLink(href,title,dl,target){var target=target||'';var dl=dl||false;if(dl){href=href+'?download=True';}
if(target){return"<a href='"+href+"' target=\"+target+\">"+title+"</a>";}
else{return"<a href='"+href+"'>"+title+"</a>";}}
function highlightLinks(text){var safedict={};var k=0;var safekey;text=text.replace(/(?:<a)(.*?)(?:a>)/gim,function(reallink){safekey='RLINK_'+k;safedict[safekey]=reallink;k++;return safekey;});text=text.replace(/(?:\b|\+)(?:mailto:)?([\w\.+#-]+)@([\w\.-]+\.\w{2,4})\b/g,function(address){return makeLink('mailto:'+address,address);});text=text.replace(/((\w+:\/\/)[-a-zA-Z0-9:@;?&=\/%\+\.\*!'\(\),\$_\{\}\^~\[\]`#|]+)/g,function(link){return makeLink(link,link,false,'_blank');});for(var k in safedict){text=text.replace(k,safedict[k]);}
return text;}
function funcApply(fnc,parsobj,scope,argNames,argValues,showError){var parsobj=parsobj||{};var argNames=argNames||[];var argValues=argValues||[];for(var attr in parsobj){argNames.push(attr);argValues.push(parsobj[attr]);}
argNames.forEach(function(arg,idx){if(!(arg in parsobj)){parsobj[arg]=argValues[idx];}});argNames.push('_kwargs');argValues.push(parsobj);if(typeof(fnc)=='function'){var signature=fnc.toString().match(/function *\(([\w \,]*)\)/)[1];var idx;if(signature){var argValuesCopy=copyArray(argValues);var valid=true;splitStrip(signature).reverse().forEach(function(par){idx=argNames.indexOf(par);if(idx>0){argNames=argNames.splice(idx,1).concat(argNames);argValuesCopy=argValuesCopy.splice(idx,1).concat(argValuesCopy);}else{valid=false;}});argValues=valid?argValuesCopy:argValues;}}else{fnc=funcCreate(fnc,argNames.join(','),scope,showError);}
return fnc.apply(scope,argValues);}
function deltaWeeks(dateStart,dateEnd,format){var today=new Date();var dd=deltaDays(dateStart||today,dateEnd||today);format=format||'w';if(format=='W'){return Math.trunc(dd/7);}
if(format=='w'){return Math.round10(dd/7,-2);}
if(format=='WD'){return`${Math.trunc(dd/7)}w${dd%7}d`}};function deltaDays(dateStart,dateEnd,excludeWD){var excludeWD=excludeWD||'';var delta=1;var result=0;var currDate=new Date(dateStart);var wd;if(dateStart>dateEnd){delta=-1;}
while(currDate.toLocaleDateString()!=dateEnd.toLocaleDateString()){result+=delta;currDate.setDate(currDate.getDate()+delta);wd=currDate.getDay();}
return result;};function addDaysToDate(dateStart,daysToAdd,excludeWD){var excludeWD=excludeWD||'';var currDate=new Date(dateStart);var delta=1;var wd;if(daysToAdd<0){daysToAdd=-daysToAdd;delta=-1;}
while(daysToAdd>0){currDate.setDate(currDate.getDate()+delta);wd=currDate.getDay();if(excludeWD.indexOf(wd)<0){daysToAdd--;}}
return currDate;};function localeParser(value,options){var info=dojo.date.locale._parseInfo(options);var tokens=info.tokens,bundle=info.bundle;var re=new RegExp("^"+info.regexp+"$");var match=re.exec(value);if(!match){return null;}
var widthList=['abbr','wide','narrow'];var result=new Date(1972,0);var expected={};var amPm="";dojo.forEach(match,function(v,i){if(!i){return;}
var token=tokens[i-1];var l=token.length;switch(token.charAt(0)){case'y':if(l!=2){result.setFullYear(v);expected.year=v;}else{if(v<100){v=Number(v);var year=''+new Date().getFullYear();var century=year.substring(0,2)*100;var yearPart=Number(year.substring(2,4));var cutoff=Math.min(yearPart+20,99);var num=(v<cutoff)?century+v:century-100+v;result.setFullYear(num);expected.year=num;}else{if(options.strict){return null;}
result.setFullYear(v);expected.year=v;}}
break;case'M':if(l>2){var months=bundle['months-format-'+widthList[l-3]].concat();if(!options.strict){v=v.replace(".","").toLowerCase();months=dojo.map(months,function(s){return s.replace(".","").toLowerCase();});}
v=dojo.indexOf(months,v);if(v==-1){return null;}}else{v--;}
result.setMonth(v);expected.month=v;break;case'E':case'e':var days=bundle['days-format-'+widthList[l-3]].concat();if(!options.strict){v=v.toLowerCase();days=dojo.map(days,"".toLowerCase);}
v=dojo.indexOf(days,v);if(v==-1){return null;}
break;case'd':result.setDate(v);expected.date=v;break;case'D':result.setMonth(0);result.setDate(v);break;case'a':var am=options.am||bundle.am;var pm=options.pm||bundle.pm;if(!options.strict){var period=/\./g;v=v.replace(period,'').toLowerCase();am=am.replace(period,'').toLowerCase();pm=pm.replace(period,'').toLowerCase();}
if(options.strict&&v!=am&&v!=pm){return null;}
amPm=(v==pm)?'p':(v==am)?'a':'';break;case'K':if(v==24){v=0;}
case'h':case'H':case'k':if(v>23){return null;}
result.setHours(v);break;case'm':result.setMinutes(v);break;case's':result.setSeconds(v);break;case'S':result.setMilliseconds(v);}});var hours=result.getHours();if(amPm==='p'&&hours<12){result.setHours(hours+12);}else if(amPm==='a'&&hours==12){result.setHours(0);}
if(expected.year&&result.getFullYear()!=expected.year){return null;}
if(expected.month&&result.getMonth()!=expected.month){return null;}
if((expected.date==28)&&(expected.month==4)&&(result.getDate()==27)){result.setDate(expected.date);}
if(expected.date&&result.getDate()!=expected.date){return null;}
return result;};function getRandomColor(){var letters='0123456789ABCDEF'.split('');var color='#';for(var i=0;i<6;i++){color+=letters[Math.floor(Math.random()*16)];}
return color;}
function flattenString(str,forbidden,replacer){replacer=replacer||'_';var forbidden=forbidden||['.'];var result=str;var pattern;forbidden.forEach(function(c){pattern=new RegExp("\\"+c,'g');result=result.replace(pattern,replacer);});return result;}
function canAccessIFrame(iframe){var html=null;try{var doc=iframe.contentDocument||iframe.contentWindow.document;html=doc.body.innerHTML;}catch(err){}
return(html!==null);}



dojo.require("dojo.data.util.filter");dojo.declare("gnr.GnrStoreBag",null,{_identifier:'#id',_staticStore:true,_rootNodeName:'root',hideValues:false,constructor:function(kw){dojo.mixin(this,kw);},rootDataNode:function(){if(this.datapath){return genro.getDataNode(this.datapath,true,new gnr.GnrBag());}else{if(!this.mainbag){this.mainbag=new gnr.GnrBag();}
return this.mainbag.getNode(this._rootNodeName,false,true,new gnr.GnrBag());}},rootData:function(){var rootData=this.rootDataNode().getValue();if(!(rootData instanceof dojo.Deferred)){if(!(rootData instanceof gnr.GnrBag)){rootData=new gnr.GnrBag();this.rootDataNode().setValue(rootData,false);}}
return rootData;},getFeatures:function(){genro.debug('getFeatures');return{'dojo.data.api.Read':true,'dojo.data.api.Write':true,'dojo.data.api.Identity':true,'dojo.data.api.Notification':true};},getValue:function(item,attribute,defaultValue){if(item==null){return;}
genro.debug('getValue: item='+item.label+' - attribute-name-string='+attribute+' - default='+defaultValue);if(!(item instanceof gnr.GnrBagNode)){return item[attribute];}
var attributes=item.attr;if(attribute=='#k'){return item.label;}
else if(attribute=='#v'){return item.getValue(null,{_sourceNode:this.sourceNode});}
else if(attribute.indexOf('.')==0){return item.getValue().getItem(attribute.slice(1));}
else if(attribute in attributes){var result=attributes[attribute];if(result==undefined){result=defaultValue;}
return result;}},getValues:function(item,attribute){genro.debug('getValues: item='+item.label+' - attribute-name-string='+attribute);var attributes=item.getAttr();if(attribute=='#v'){var itemvalue=item.getValue(null,{_sourceNode:this.sourceNode});if(itemvalue instanceof gnr.GnrBag){return itemvalue.getNodes(this.nodeFilter);}else if(this.isDictItem(itemvalue)){return new gnr.GnrBag(itemvalue).getNodes()}
else{return[{'id':item._id+'c','label':itemvalue,'attr':item.attr}];}}
else if(attribute.indexOf('.')==0){return[item.getValue().getItem(attribute.slice(1))];}
else{if(attribute in attributes){return[attributes[attribute]];}
else{return[];}}},getAttributes:function(item){var attributes=[];if(item){genro.debug('getAttributes: item='+item.label);for(var key in item.getAttr()){attributes.push(key);}}
return attributes;},hasAttribute:function(item,attribute){if(this.isItem(item)){genro.debug('hasAttribute: item='+item.label+' - attribute-name-string='+attribute);if(attribute=='#v'){var resolver=item.getResolver();if(resolver&&!resolver.lastUpdate){return'child_count'in item.attr?item.attr.child_count>0:true;}else{var result=item.getValue();if(this.hasChildrenCb&&this.hasChildrenCb(item)===false){return null;}
if(result instanceof gnr.GnrBag){return(result.getNodes(this.nodeFilter).length>0);}
else if(this.hideValues){return null;}
else{return true;}}}
else{return(attribute in item.attr);}}else{return false;}},containsValue:function(item,attribute,value){genro.debug('containsValue: item='+item.label+' - attribute-name-string='+attribute+' - value='+value+' ---->Unimplemeted','alert');return false;},isItem:function(something){genro.debug('isItem');return(something instanceof gnr.GnrBagNode);},isDictItem:function(something){return(typeof(something)=='object')&&!(something instanceof Date)&&!(something instanceof Array)},isItemLoaded:function(something){genro.debug('isItemLoaded: something='+something);if(this.isItem(something)){return something.isLoaded();}else{return true;}},loadItem:function(request){genro.debug('loadItem: keywordArgs='+objectString(request));if(!this.isItemLoaded(request.item)){var scope=request.scope?request.scope:dojo.global;var cb=dojo.hitch(scope,request.onItem);var result=request.item.getValue();if(result instanceof dojo.Deferred){result.addCallback(cb);}else{cb(result);}}},fetch:function(request){genro.debug('loadItem: request='+objectString(request));request=request||{};if(!request.store){request.store=this;}
var self=this;var _errorHandler=function(errorData,requestObject){if(requestObject.onError){var scope=requestObject.scope||dojo.global;requestObject.onError.call(scope,errorData,requestObject);}};var _fetchHandler=function(items,requestObject,fetchMetadata){fetchMetadata=fetchMetadata||{};var oldAbortFunction=requestObject.abort||null;var aborted=false;var startIndex,endIndex;if(fetchMetadata.totalrows){startIndex=0;endIndex=items.length;}else{startIndex=requestObject.start?requestObject.start:0;endIndex=requestObject.count?(startIndex+requestObject.count):items.length;}
requestObject.abort=function(){aborted=true;if(oldAbortFunction){oldAbortFunction.call(requestObject);}};var scope=requestObject.scope||dojo.global;if(!requestObject.store){requestObject.store=self;}
if(requestObject.onBegin&&items){requestObject.onBegin.call(scope,fetchMetadata.totalrows||items.length,requestObject);}
if(requestObject.sort){items.sort(dojo.data.util.sorter.createSortFunction(requestObject.sort,self));}
if(requestObject.onItem){for(var i=startIndex;(i<items.length)&&(i<endIndex);++i){var item=items[i];if(!aborted){requestObject.onItem.call(scope,item,requestObject);}}}
if(requestObject.onComplete&&!aborted){var subset=null;if(!requestObject.onItem){subset=items.slice(startIndex,endIndex);}
var s=requestObject.store;requestObject.onComplete.call(scope,subset,requestObject);}};this._doFetch(request,_fetchHandler,_errorHandler);return request;},_doFetch:function(request,findCallback,errCallback){var query=request.query;var finalize=dojo.hitch(this,function(r){var result=[];if(r){var items=r.getNodes();if(query){var ignoreCase=request.queryOptions?request.queryOptions.ignoreCase:false;result=this._applyQuery(query,ignoreCase,items);}else{for(var i=0;i<items.length;++i){var item=items[i];if(item!==null){result.push(item);}}}}
findCallback(result,request);});var rootData=this.rootData();if(rootData instanceof dojo.Deferred){return rootData.addCallback(finalize);}else{return finalize(rootData);}},close:function(request){genro.debug('close: keywordArgs='+objectString(keywordArgs)+' - request'+objectString(request)+'  ---->Unimplemented','alert');},getLabel:function(item){if(this.isItem(item)){genro.debug('getLabel: item='+item.label);if(this.labelAttribute){return item.attr[this.labelAttribute]||item.label;}else if(this.labelCb){return this.labelCb.call(item,this);}
return item.label;}else if(typeof(item)=='object'){if(this.labelCb){return this.labelCb.call(item,this);}else{return item.label;}}
else{return item;};},getLabelAttributes:function(item){genro.debug('getLabelAttributes: item='+item.label+'  ------>Unimplemented','alert');},newItem:function(keywordArgs,parentInfo){var newItem;genro.debug('newItem: item='+objectString(keywordArgs)+'  ------>Unimplemented','alert');return newItem;},deleteItem:function(item){genro.debug('deleteItem: item='+item.label+'  ------>Unimplemented','alert');return false;},setValue:function(item,attribute,value){genro.debug('setValue: item='+item.label+'  ------>Unimplemented','alert');return false;},setValues:function(item,attribute,values){genro.debug('setValues: item='+item.label+'  ------>Unimplemented','alert');return false;},unsetAttribute:function(item,attribute){genro.debug('unsetAttribute: item='+item.label+'  ------>Unimplemented','alert');return false;},save:function(keywordArgs){genro.debug('save: keywordArgs='+objectString(keywordArgs)+'  ------>Unimplemented','alert');},revert:function(){genro.debug('revert:   ------>Unimplemented','alert');return false;},isDirty:function(item){genro.debug('isDirty: item='+item.label+'  ------>Unimplemented','alert');return false;},getIdentity:function(item){if(!(item instanceof gnr.GnrBagNode)){return item.id;}
if(item&&item.attr._is_invalid_item){return null;}
genro.debug('getIdentity: item='+item.label);var identifier=this._identifier;if(identifier=='#id'){return item._id;}else if(identifier=='#k'){return item.label;}else if(identifier=='#i'){return item.getParentNode().getNodes().indexOf(item);}
else if(identifier=='#p'){return item.getFullpath('',this.rootData());}
else if(identifier=='##'){return item.getFullpath('##',this.rootData());}
else if(identifier.indexOf('.')==0){return item.getValue().getItem(identifier.slice(1));}else{return item.getAttr(identifier);}},getIdentityAttributes:function(item){genro.debug('getIdentityAttributes: item='+item.label+'  ------>Unimplemented','alert');return null;},fetchItemByIdentity:function(request){genro.debug('fetchItemByIdentity: identity='+request.identity);if(!isNullOrBlank(request.identity)){var id=request.identity;var item=null;var bagnode;var nodes=this.rootData().getNodes();genro.debug('trying fetchIdentity on '+nodes.length+' existing nodes');for(var i=0;i<nodes.length;i++){bagnode=nodes[i];if(this.getIdentity(bagnode)==id){item=bagnode;break;}}}
else{item=null;}
if(request.onItem){var scope=request.scope?request.scope:dojo.global;request.onItem.call(scope,item);}
else{return item;}},onSet:function(item,attribute,oldValue,newValue){},onNew:function(newItem,parentInfo){},onDelete:function(deletedItem){},_triggerUpd:function(kw){if(kw.updvalue){this.onSet(kw.node,'#v',kw.oldvalue,kw.value);}
if(kw.updattr){for(var attr in kw.node.attr){this.onSet(kw.node,attr,kw.oldattr[attr],kw.node.attr[attr]);}}},_triggerIns:function(kw){var parentNode=kw.where.getParentNode();if(parentNode===this.rootDataNode()){this.onNew(kw.node);}else{this.onNew(kw.node,{item:parentNode,attribute:'#v'});}},_triggerDel:function(kw){this.onDelete(kw.node);},_applyQuery:function(query,ignoreCase,items){var result=[];var regexpList={};for(var key in query){var value=query[key];if(typeof value==="string"){regexpList[key]=dojo.data.util.filter.patternToRegExp(value,ignoreCase);}}
for(var i=0;i<items.length;++i){var item=items[i];if(item!=null){var match=true;for(var key in query){var regexp=regexpList[key];match=dojo.some(this.getValues(item,key),function(v){if(v!==null&&!dojo.isObject(v)&&regexp){return(v.toString().match(regexp)!=null);}else if(v===query[key]){return true;}});if(!match){break;}}
if(match){result.push(item);}}}
return result;}});dojo.declare("gnr.GnrStoreGrid",gnr.GnrStoreBag,{_doFetch:function(request,findCallback,errCallback){var cb=function(node){var v=(node instanceof gnr.GnrBagNode)?node.getValue():null;if(v instanceof gnr.GnrBag){findCallback(v.getNodes(),request,node.getAttr());}else{findCallback([],request);}};if(request.start>=0){var kwargs={row_start:request.start,row_count:request.count};var value=this.rootDataNode().getValue('',kwargs);if(value instanceof dojo.Deferred){return value.addCallback(cb);}else{cb.call(this,value);}}},fetchItemByIdentity:function(request){genro.debug('fetchItemByIdentity: identity='+request.identity);if(!request.identity){genro.debug('fetchItemByIdentity: return null');return null;}else{var id=request.identity;var finalize=dojo.hitch(this,function(r){var scope=request.scope?request.scope:dojo.global;var result=r.getValue().getNode('#0');if(result){dojo.hitch(scope,request.onItem)(result);}});var result=this.rootDataNode().getValue('',{where:'id=:_pkey',_pkey:id});if(result instanceof dojo.Deferred){result.addCallback(finalize);}}}});dojo.declare("gnr.GnrStoreQuery",gnr.GnrStoreBag,{constructor:function(kw){this.cached_values={};this.cache_time=60;},clearCache:function(pkey){if(pkey){objectPop(this.cached_values,pkey);}else{this.cached_values={};}},fetchItemByIdentity:function(request){genro.debug('fetchItemByIdentity: identity='+request.identity);if(!request.identity){genro.debug('fetchItemByIdentity: return null');var result=new gnr.GnrBagNode();result.attr[this.searchAttr]='';var scope=request.scope?request.scope:dojo.global;dojo.hitch(scope,request.onItem)(result);}else{var id=request.identity;if(id in this.cached_values){var cached=this.cached_values[id];var age=(new Date()-cached.ts)/1000;if(age<this.cache_time){dojo.hitch(scope,request.onItem)(cached.result);return;}}
if(isNullOrBlank(id)){dojo.hitch(scope,request.onItem)(null);return;}
var parentSourceNode=this._parentSourceNode;if(parentSourceNode.widget&&parentSourceNode.widget._lastValue==request.identity){return;}
if(parentSourceNode&&parentSourceNode.widget){delete parentSourceNode.widget._lastQueryError;}
var selectedAttrs=objectExtract(parentSourceNode.attr,'selected_*',true)
if(!(('rowcaption'in parentSourceNode.attr)||parentSourceNode.attr._hdbselect||parentSourceNode.attr.condition||objectNotEmpty(selectedAttrs))){var recordNodePath=parentSourceNode.attr.value;recordNodePath=recordNodePath.slice(1);if(recordNodePath.indexOf('.')==0){recordNodePath=recordNodePath.slice(1);}
recordNodePath=recordNodePath.split('.');recordNodePath.push('@'+recordNodePath.pop());var parentBag=parentSourceNode.getRelativeData();var recordNode=parentBag?parentBag.getNode(recordNodePath):null;if(recordNode&&'caption'in recordNode.attr){var value=recordNode.attr._newrecord?'':recordNode.attr.caption;var scope=request.scope?request.scope:dojo.global;var result=new gnr.GnrBagNode();result.attr[this.searchAttr]=value;result.attr[this._identifier]=request.identity;dojo.hitch(scope,request.onItem)(result);return;}}
var finalize=dojo.hitch(this,function(r){var scope=request.scope?request.scope:dojo.global;if(r.attr.errors){this._parentSourceNode.widget._lastQueryError=r.attr.errors;this._parentSourceNode.setValidationError({error:r.attr.errors});}
var result=r.getValue();if(result instanceof gnr.GnrBag){result=result.getNode('#0');}else{result=null;}
this.cached_values[request.identity]={'result':result,'ts':new Date()};if(!result){}
dojo.hitch(scope,request.onItem)(result);});var result=this.rootDataNode().getValue('',{_id:id});if(result instanceof dojo.Deferred){result.addCallback(finalize);}else{return finalize(result);}}},_doFetch:function(request,findCallback,errCallback){var query=request.query;if(!query.caption){findCallback([],request);}else{if(this.switches){var sn=this._parentSourceNode;var foundmatch=false;for(var sw in this.switches){var sobj=this.switches[sw];var m=query.caption.match(sobj.search);if(m){var switchcb;if(sobj.set){switchcb=function(){sn.widget.setDisplayedValue(sn.currentFromDatasource(sobj.set),true);};}else if(sobj.value){switchcb=function(){sn.widget.setValue(sn.currentFromDatasource(sobj.value),true);};}else if(sobj.action){switchcb=function(){sobj.action(m);};}else{foundmatch=m;}
if(switchcb){sn.widget.focusNode.blur();sn.delayedCall(function(){if(!sn.widget||!sn.widget._focused){switchcb();}},1,'switch_'+sw);findCallback([],request);return;}}}
if(foundmatch){findCallback([],request);return;}}
var ignoreCase=request.queryOptions?request.queryOptions.ignoreCase:false;var kwargs={_id:'',_querystring:query.caption,ignoreCase:ignoreCase};var s_time=new Date();var cb=dojo.hitch(this,function(r){var result;if(r instanceof gnr.GnrBagNode&&r.getValue()){this.lastFetchAttrs=r.attr;result=r.getValue().getNodes();}
else{result=[];this.lastFetchAttrs={};}
findCallback(result,request);});if(this._parentSourceNode&&this._parentSourceNode.widget){delete this._parentSourceNode.widget._lastQueryError;}
if(this._parentSourceNode&&this._parentSourceNode.widget&&!this._parentSourceNode.widget._focused){kwargs.rpc_sync=true;}
var result=this.rootDataNode().getValue('',kwargs);if(result instanceof dojo.Deferred){return result.addCallback(cb);}else{return cb(result);}}}});



var dojo_version=dojo.version.major+'.'+dojo.version.minor;dojo.require("dojo.date");dojo.require('dijit.Tooltip');dojo.require('dojo.date.locale');dojo.require("dojo.currency");dojo.require("dojox.validate.web");dojo.require("dojo.number");dojo.require("dojo.cookie");dojo.require("dojo.fx");dijit.showTooltip=function(innerHTML,aroundNode){if(!dijit._masterTT){dijit._masterTT=new dijit._MasterTooltip();}
var tooltip_text=innerHTML;if(tooltip_text instanceof Function){tooltip_text=tooltip_text(aroundNode);}
return dijit._masterTT.show(tooltip_text,aroundNode);};window.onfocus=function(){window._IS_WINDOW_FOCUSED=true;};window.onblur=function(){window._IS_WINDOW_FOCUSED=false;}
dojo.declare('gnr.GenroClient',null,{constructor:function(kwargs){this.patchConsole();kwargs=mapConvertFromText(kwargs);this.domRootName=kwargs.domRootName||'mainWindow';this.page_id=kwargs.page_id;this.startArgs=kwargs.startArgs||{};this.debuglevel=kwargs.startArgs.debug||null;this.debug_sql=kwargs.startArgs.debug_sql;dojo.subscribe('gnrServerLog',this,'serverLog');dojo.subscribe('externalSetData',this,function(kw){genro.setData(kw.path,kw.value,kw.attr,{doTrigger:'externalSetData'});});this.websockets_url=objectPop(kwargs.startArgs,'websockets_url');this.pageMode=kwargs.pageMode;this.pageModule=kwargs.pageModule;this.baseUrl=kwargs.baseUrl;this.serverTime=objectPop(kwargs.startArgs,'servertime');var start_ts=new Date();this.serverTimeDelta=this.serverTime-start_ts;this.debugRpc=false;this.polling_enabled=false;this.auto_polling=-1;this.user_polling=-1;this.isDeveloper=objectPop(this.startArgs,'isDeveloper');this.isMobile=objectPop(this.startArgs,'isMobile');this.deviceScreenSize=objectPop(this.startArgs,'deviceScreenSize');this.extraFeatures=objectPop(this.startArgs,'extraFeatures');this.theme={};this.dojo=dojo;this.debugged_rpc={};this.ext={};this.watches={};this.userInfoCb=[];this.formatter=gnrformatter;this.timeProfilers=[];this.currProfilers={nc:0,st:0,sqlt:0,sqlc:0};this.rpcHeaderInfo={};this.profile_count=4;this.lastPing=start_ts;this._debugPaths={};this._aliasDatapaths={};this.sendAllEvents=true;this._lastMouseEvent={};this._longClickDuration=1500;this._lastUserEventTs=start_ts;this._lastChildUserEventTs=start_ts;this._lastGlobalUserEventTs=start_ts;this._lastRpc=start_ts;this.setBrowserIdentifier();for(var i=0;i<this.profile_count;i++){this.timeProfilers.push({nc:0,st:0,sqlt:0,sqlc:0});}
setTimeout(dojo.hitch(this,'genroInit'),1);},setAliasDatapath:function(alias,path){this._aliasDatapaths[alias]=path;},setBrowserIdentifier:function(){var browserIdentifier=this.getFromStorage('local','browserIdentifier');if(!browserIdentifier){browserIdentifier=this.page_id;this.setInStorage('local','browserIdentifier',browserIdentifier);}
this.browserIdentifier=browserIdentifier;},setDebugPath:function(path,kw){if(!kw.mode){objectPop(this._debugPaths,path);}else{this._debugPaths[path]=kw;}},patchConsole_debug:function(){if(arguments[0].dojoType=='cancel'){return;}else{console.zdebug(arguments);}},patchConsole_warn:function(){if(arguments[0].dojoType=='cancel'){return;}else{console.zdebug(arguments);}},patchConsole:function(){dojo.experimental=function(){};var patchers=objectExtract(this,'patchConsole_*',true);for(var p in patchers){if(p in console){console['z'+p]=console[p];console[p]=patchers[p];}}},genroInit:function(){this.startTime=new Date();this.lastTime=this.startTime;this.dialogStack=[];this.sounds={};this._serverstore_paths={};this._serverstore_changes=null;this._sharedObjects_paths={};this._sharedObjects={};this.pendingCallAfter={};var plugins=objectExtract(window,'genro_plugin_*');objectUpdate(genro,plugins);this.compareDict={'==':function(a,b){return(a==b);},'>':function(a,b){return(a>b);},'>=':function(a,b){return(a>=b);},'<':function(a,b){return(a<b);},'<=':function(a,b){return(a<=b);},'!=':function(a,b){return(a!=b);},'%':function(a,b){return(a.indexOf(b)>=0);},'!%':function(a,b){return(a.indexOf(b)<0);}};window.onbeforeunload=function(e){genro._windowClosing=true;var exit;if(genro.checkBeforeUnload&&!genro._checkedUnload){exit=genro.checkBeforeUnload();}
if(exit){return exit;}};window.onunload=function(e){genro.onWindowUnload(e);};this.rpc=new gnr.GnrRpcHandler(this);this.src=new gnr.GnrSrcHandler(this);this.wdg=new gnr.GnrWdgHandler(this);this.dev=new gnr.GnrDevHandler(this);this.dlg=new gnr.GnrDlgHandler(this);this.dom=new gnr.GnrDomHandler(this);this.vld=new gnr.GnrValidator(this);this.wsk=new gnr.GnrWebSocketHandler(this,this.websockets_url,{debug:false});this.som=new gnr.GnrSharedObjectHandler(this);if(dojo_version=='1.1'){if(dojo.isSafari){dojo.keys.DOWN_ARROW=40;dojo.keys.UP_ARROW=38;}
genropatches.dnd();genropatches.getDocumentWindow();genropatches.forEachError();genropatches.borderContainer();genropatches.tabContainer();genropatches.setStateClass();genropatches.menu();genropatches.comboBox();genropatches.tree();genropatches.parseNumbers();genropatches.dojoToJson();genropatches.sendAsBinary();genropatches.places();}
genropatches.decimalRound();this.clsdict={domsource:gnr.GnrDomSource,bag:gnr.GnrBag};this.eventPath='_sys.events';this.prefs={'recordpath':'tables.$dbtable.record','selectionpath':'tables.$dbtable.selection','limit':'50'};var mainWindow=dojo.byId('mainWindow');if('_scale'in genro.startArgs){mainWindow.style.zoom=genro.startArgs._scale;}
dojo.locale=dojo.i18n.normalizeLocale(dojo.locale);dojo.addOnLoad(genro,'start');},compare:function(op,a,b){if((a instanceof Date)&&(b instanceof Date)){a=a.valueOf();b=b.valueOf();}
return genro.compareDict[op](a,b);},timeIt:function(msg){var t=this.lastTime;this.lastTime=new Date();console.log('----timeIt:'+msg+':'+(this.lastTime-t)+' - totalTime:'+(this.lastTime-this.startTime));},ping:function(){genro.rpc.ping();},assert:function(condition,msg,level){if(!condition){console[level||'error'](msg);}},pluginCommand:function(kw){var plugin=objectPop(kw,'plugin');var command=objectPop(kw,'command');var cb=function(){if(command){genro[plugin][command](kw);}};if(plugin in genro){cb();}else{genro.dom.loadCss('/_rsrc/common/js_plugins/'+plugin+'/'+plugin+'.css',null,null,genro.isDeveloper);genro.dom.loadJs('/_rsrc/common/js_plugins/'+plugin+'/'+plugin+'.js',function(){genro[plugin]=genro[plugin]||objectPop(window,'genro_plugin_'+plugin);genro.wdg.updateWidgetCatalog();cb();},genro.isDeveloper);}},safetry:function(cb){try{return cb();}catch(e){console.error(e.message);console.log(e.stack);}},locale:function(){if(!this._locale){this._locale=genro.getData('gnr.locale');}
return this._locale;},bp:function(aux){console.log('bp ',arguments);if(aux===true){debugger;}},debugEvent:function(e,sourceNode,evt_type){if(!evt_type||(evt_type==e.type)){console.log('debugEvent ',e.keyCode,keyName(e.keyCode),e.type);}},onError:function(errorMsg,url,linenumber){var msg="<div style='white-space:nowrap;'>"+url+' line:'+linenumber+'</div>'+errorMsg;genro.dev.addError(msg,'js',true);},closePage:function(){if(genro.parentIframeSourceNode){genro.parentIframeSourceNode.domNode.parentNode.removeChild(genro.parentIframeSourceNode.domNode);}else{window.close();}},notifyPageClosing:function(){dojo.forEach(window.frames,function(f){try{if(f.genro){f.genro.notifyPageClosing();}}catch(e){}});this.rpc.remoteCall('onClosePage',{sync:true});genro.publish('onClosePage');if(genro._data){genro.saveContextCookie();};},onWindowUnload:function(e){if(genro.external_window_key){genro.mainGenroWindow.genro.publish('closeExternalWindow',{windowKey:genro.external_window_key});}
this.notifyPageClosing();},saveContextCookie:function(){var clientCtx=genro.getData('_clientCtx');if(clientCtx){dojo.cookie("genroContext",clientCtx.toXml(),{expires:5,path:genro.getData('gnr.homeUrl')});}},clientCtx:function(path){var path=path?'.'+path:'';return genro._('_clientCtx'+path);},warning:function(msg){console.warn(msg);genro.dlg.message(msg);},commandLink:function(href,content){return"<a onclick='if((genro.isMac&&!event.metaKey)||(!genro.isMac&&!event.ctrlKey)){dojo.stopEvent(event);}' class='gnrzoomcell' href='"+href+"'>"+content+"</a>";},childUserEvent:function(childgenro){genro._lastChildUserEventTs=new Date();genro._lastGlobalUserEventTs=genro._lastChildUserEventTs>genro._lastUserEventTs?genro._lastChildUserEventTs:genro._lastUserEventTs;genro.onUserEvent();},_registerUserEvents:function(){var cb=function(evt){if(genro.wsk.wsroot&&genro.sendAllEvents){genro.wsk.send('user_event',{event:{'type':evt.type,'modifiers':genro.dom.getEventModifiers(evt),'x':evt.x,'y':evt.y,'keyCode':evt.keyCode,'keyChar':evt.keyChar,'timeStamp':evt.timeStamp,'targetId':evt.target?evt.target.id:''}});}
genro._lastUserEventTs=new Date();genro._lastGlobalUserEventTs=new Date();if(genro.root_page_id){genro.mainGenroWindow.genro.childUserEvent();}else{genro.onUserEvent();}
genro.execUserInfoCb();};dojo.connect(window,'onclick',cb);dojo.connect(window,'onmousemove',cb);dojo.connect(window,'onkeydown',cb);dojo.connect(window,'onkeypress',cb);dojo.connect(window,'ondblclick',cb);setInterval(function(){genro.timeProfilers.push(genro.currProfilers);if(genro.timeProfilers.length>genro.profile_count){genro.timeProfilers=genro.timeProfilers.slice(-genro.profile_count);}
genro.currProfilers={nc:0,st:0,sqlt:0,sqlc:0};},15000);window.addEventListener("click",function(e){e._clickDuration=genro._lastMouseEvent.duration;e._longClick=genro._lastMouseEvent.longClick;genro._lastMouseEvent.mousedown=e;},true);window.addEventListener("mousedown",function(e){genro._lastMouseEvent.duration=null;genro._lastMouseEvent.longClick=null;genro._lastMouseEvent.mousedown=e;genro._lastKeyDown=null;var mu=genro._lastMouseEvent.mouseup;var hasRecentClick=mu&&(e.timeStamp-mu.timeStamp)<500;genro._lastMouseEvent.startMouseDown=setTimeout(function(){var topic=hasRecentClick?'clickAndHold':'longMouseDown';genro.publish(topic,{event:e});var target=e.target;var handler=target.getAttribute('on'+topic.toLowerCase());var sn=genro.dom.getSourceNode(e.target);if(handler){funcApply(handler,{event:e},sn||target);}
if(sn){sn.publish(topic,{event:e});}},1500);},true);window.addEventListener("mouseup",function(e){genro._lastMouseEvent.mouseup=e;var duration=genro._lastMouseEvent.mouseup.timeStamp-genro._lastMouseEvent.mousedown.timeStamp;var md=genro._lastMouseEvent.mousedown;genro._lastMouseEvent.duration=duration;clearTimeout(genro._lastMouseEvent.startMouseDown);if(duration>genro._longClickDuration&&e.target===md.target&&e.x==md.x&&e.y==md.y){genro._lastMouseEvent.longClick=true;}},true);window.addEventListener("keydown",function(e){genro._lastKeyDown=e;},true);},serverLog:function(data){var mode=data.mode||'log';if(mode=='log'||mode=='error'||mode=='warn'){if(data.kwargs&&data.kwargs instanceof gnr.GnrBag){data.kwargs=data.kwargs.asDict();}
console[mode]('*SERVER* >>'+data.msg,data.args,data.kwargs);}},execUserInfoCb:function(){if(genro.userInfoCb.length>0){var userInfoCb=genro.userInfoCb;genro.userInfoCb=[];dojo.forEach(userInfoCb,function(cb){cb();});}},getScreenLockTimeout:function(){if(!genro._screenlock_timeout){genro._screenlock_timeout=genro.userPreference('adm.general.screenlock_timeout')||genro.appPreference('adm.general.screenlock_timeout')||-1;}
return genro._screenlock_timeout;},onUserEvent:function(){if(genro.user_polling>0){if((genro._lastGlobalUserEventTs-genro.lastPing)/1000>genro.user_polling){genro.rpc.ping({'reason':'user'});}}
var st=genro.getScreenLockTimeout();if(st>0){genro.callAfter(function(){genro.publish('screenlock');},st*1000*60,this,'screenlock');}
if(genro.fast_polling){if(!genro.fast_polling_limiter){genro.setAutoPolling(true);}}
var now=new Date();for(var k in genro.rpc.rpc_register){var kw=genro.rpc.rpc_register[k];var age=now-kw.__rpc_started;if(k in this.debugged_rpc){return;}
if(age>5000){console.warn('slow rpc pending',kw,age);objectPop(genro.rpc.rpc_register,k);}}},loginDialog:function(loginUrl){genro.src.getNode()._('div','_loginDialog_');var node=genro.src.getNode('_loginDialog_').clearValue();var dlg=node._('dialog',{'_class':'lightboxDialog'});dlg._('iframe',{'height':'500px',width:'600px',border:0,src:loginUrl,background:'transparent'});dlg.getParentNode().widget.show();},login:function(data,kw){genro.serverCall('doLogin',objectUpdate({'login':data},kw),function(result){result=result.getValue()
var message=result.getItem('message')
if(message){genro.publish('invalid_login',{'message':message})}else{genro.mainGenroWindow.location.reload();}})},start:function(){this._dataroot=new gnr.GnrBag();this._dataroot.setBackRef();this._data=new gnr.GnrBag();this._dataroot.setItem('main',this._data);this.widget={};this._counter=0;this.dlg.createStandardMsg(document.body);this.contextIndex={};this.isMac=dojo.isMac!=undefined?dojo.isMac:navigator.appVersion.indexOf('Macintosh')>=0;this.isChrome=((navigator.appVersion.indexOf('Chrome')>=0));this.wsk.create();this.root_page_id=null;if(this.isMobile){this.mobile=new gnr.GnrMobileHandler(this);}
dojo.subscribe('debugstep',function(data){genro.dev.onDebugstep(data)});dojo.subscribe('closePage',function(){genro.closePage();});if(this.startArgs['_parent_page_id']){this.parent_page_id=this.startArgs['_parent_page_id'];}
if(this.externalParentWindow){this.mainGenroWindow=this.externalParentWindow;}else{this.mainGenroWindow=window;var parentGenro;try{parentGenro=window.frameElement&&window.parent.genro;this.mainGenroWindow=parentGenro.mainGenroWindow;this.root_page_id=this.mainGenroWindow.genro.page_id;this.parent_page_id=this.parent_page_id||parentGenro.page_id;this.startArgs['_root_page_id']=this.root_page_id;this.startArgs['_parent_page_id']=this.parent_page_id;this.parentIframeSourceNode=window.frameElement.sourceNode;}catch(e){parentGenro=false;}}
genro.src.getMainSource(function(mainBagPage){if(mainBagPage&&mainBagPage.attr&&mainBagPage.attr.redirect){var pageUrl=genro.absoluteUrl();if(pageUrl.slice(0,genro.baseUrl.length-1)==genro.baseUrl.slice(0,genro.baseUrl.length-1))
{pageUrl=pageUrl.slice(genro.baseUrl.length-1)||'/';}
var url=pageUrl&&pageUrl!='/'?genro.addParamsToUrl(mainBagPage.attr.redirect,{'fromPage':pageUrl}):mainBagPage.attr.redirect;genro.gotoURL(url);}else{var cnt=0;genro.watch('waitingRequires_main',function(){return!objectNotEmpty(genro.dom.pendingHeaders);},function(){genro.dostart(mainBagPage);},10);}});},dostart:function(mainBagPage){this.loadContext();genro.dom.addClass(dojo.body(),'startingPage');this.src.startUp(mainBagPage);genro.dom.removeClass('mainWindow','waiting');genro.dom.removeClass('_gnrRoot','notvisible');genro.dom.effect('_gnrRoot','fadein',{duration:400});dojo.connect(dojo.doc,'onkeydown',function(event){if((event.keyCode==dojo.keys.BACKSPACE)&&(event.target.size===undefined)&&(event.target.rows===undefined)){event.preventDefault();}})
genro.dragDropConnect();genro.standardEventConnection();if(genro.isDeveloper){genro.dom.addClass(dojo.body(),'isDeveloper');genro.dev.inspectConnect();}
if(this.startArgs.workInProgress){genro.dom.addClass(dojo.body(),'workInProgress');}
var _this=this;this._dataroot.subscribe('dataTriggers',{'any':dojo.hitch(this,"dataTrigger")});dojo.subscribe('ping',genro.ping);genro.dev.shortcut("Ctrl+Shift+D",function(){genro.dev.showInspector();});var dupKey=genro.isMac?"Cmd+D":"Ctrl+D";genro.dev.shortcut(dupKey,function(e){var sn=genro.dom.getSourceNode(e.target);if(sn){sn.publish('duplicateCommand',{targetDomNode:e.target});}});genro.dev.shortcut("Ctrl+Shift+I",function(){genro.dev.openGnrIde();});genro.dev.shortcut("Ctrl+Shift+T",function(){});genro.dev.shortcut("Ctrl+Shift+S",function(){genro.dev.takePicture();});genro.dev.shortcut("Shift+space",function(e){var wdg=dijit.getEnclosingWidget(e.target)
if(!wdg){return;}
var sn=wdg.sourceNode;if(sn.grid){sn.grid.gridEditor.copyFromCellAbove(sn);}
if('_lastSavedValue'in sn){if(sn.form&&sn.form.isNewRecord()&&isNullOrBlank(sn.widget.getValue())){sn.widget.setValue(sn._lastSavedValue,false);}}});dojo.subscribe("setWindowTitle",function(title){genro.dom.windowTitle(title);});genro.setData('gnr.debugger.debug_sql',this.debug_sql);this._registerUserEvents();if(!this.root_page_id){this.setAutoPolling();}
dojo.subscribe('/dnd/move/start',function(mover){mover.page_id=genro.page_id;genro.mainGenroWindow.genro.currentDnDMover=mover;});dojo.connect(window,'onmouseup',function(e){var currentDnDMover=genro.mainGenroWindow.genro.currentDnDMover;if(currentDnDMover&&(currentDnDMover.page_id!=genro.page_id)){genro.mainGenroWindow.genro.currentDnDMover=null;currentDnDMover.events=currentDnDMover.events||[];currentDnDMover.destroy();}
var currentResizeHandle=genro.mainGenroWindow.genro.currentResizeHandle;if(currentResizeHandle&&(currentResizeHandle.page_id!=genro.page_id)){currentResizeHandle._endSizing(e);}});dojo.connect(window,'onmousemove',function(e){var currentResizeHandle=genro.mainGenroWindow.genro.currentResizeHandle;if(currentResizeHandle&&(currentResizeHandle.page_id!=genro.page_id)){var screeStartPoint=currentResizeHandle.screenStartPoint;var startPoint=currentResizeHandle.startPoint;e.clientX=startPoint.x+e.screenX-screeStartPoint.x;e.clientY=startPoint.y+e.screenY-screeStartPoint.y;currentResizeHandle._updateSizing(e);}});this.windowStartHeight=window.outerHeight;this.windowStartWidth=window.outerWidth;dojo.connect(window,'onresize',function(e){genro.publish('gnrWindowResize',{});});genro.callAfter(function(){if(genro.root_page_id){genro._connectToParentIframe(window.frameElement);}
genro.windowMessageListener();genro.fireEvent('gnr.onStart');genro.publish('onPageStart');genro.dom.removeClass(dojo.body(),'startingPage');genro._pageStarted=true;},100);},setFastPolling:function(fast){this.fast_polling=fast;this.setAutoPolling(fast);},setAutoPolling:function(fast){var delay=fast?2:genro.auto_polling;if(genro.auto_polling_handler){clearInterval(genro.auto_polling_handler)}
genro.dom.removeClass('mainWindow','fast_polling');genro.auto_polling_handler=setInterval(function(){if((new Date()-genro.lastPing)/1000>genro.user_polling){genro.rpc.ping({'reason':'auto'});}},delay*1000);if(delay<genro.auto_polling){genro.dom.addClass('mainWindow','fast_polling');var limiter=function(){genro.fast_polling_limiter=setTimeout(function(){var ts=new Date();genro.fast_polling_limiter=null;var evtage=(ts-genro._lastGlobalUserEventTs)/1000;if(evtage>genro.user_polling){genro.setAutoPolling();}else{limiter();}},genro.user_polling*10000);}
limiter();}},unwatch:function(watchId){if(this.watches&&this.watches[watchId]){clearInterval(this.watches[watchId]);delete this.watches[watchId];}},watch:function(watchId,conditionCb,action,delay){delay=delay||200;if(this.watches&&(watchId in this.watches)){this.unwatch(watchId);}
if(conditionCb()){action();}else{this.watches=this.watches||{};var that=this;this.watches[watchId]=setInterval(function(){if(conditionCb()){that.unwatch(watchId);action();}},delay);}},windowMessageListener:function(){window.addEventListener("message",function(e){if(e.data){var kw=objectUpdate({},e.data);var topic=objectPop(kw,'topic')||'windowMessage';genro.publish(topic,kw);}},false);window._windowMessageReady=true;},parentFrameNode:function(){return this.parentIframeSourceNode;},getParentGenro:function(){if(this.parentIframeSourceNode){return window.parent.genro;}
if(this.root_page_id&&this.page_id!=this.root_page_id){return this.mainGenroWindow.genro;}},setDefaultShortcut:function(){genro.dev.shortcut('f1',function(e){if(genro.activeForm){genro.activeForm.publish('shortcut_save');}});genro.dev.shortcut('f3',function(e){genro.publish('shortcut_print',e);});},tooltipHelpModifier:function(value){if(value){this.setInStorage('local','tooltipHelpModifier',value);}else{var modifier=this.getFromStorage('local','tooltipHelpModifier')||'Shift';if(modifier=='*'){modifier=null;}
return modifier;}},_connectToParentIframe:function(parentIframe){var parentGenroData=genro.getParentGenro()._data;genro._data.setCallBackItem('_frames._parent',function(){return parentGenroData;},null,{isGetter:true});var parentIframeSourceNode=parentIframe.sourceNode;var frameName=parentIframeSourceNode.attr.frameName;if(frameName){var currentData=genro._data;parentGenroData.setCallBackItem('_frames.'+frameName,function(){return currentData;});}
parentIframeSourceNode._genro=this;parentIframeSourceNode.publish('pageStarted');},getChildWindow:function(page_id){var result;var cb=function(f,r){try{if(f.genro){if(f.genro.page_id==page_id){return f;}
return f.genro.getChildWindow(page_id);}}catch(error){}};for(var i=0;i<window.frames.length;i++){result=cb(window.frames[i]);if(result){return result;}}
if(this.externalWindowsObjects){for(var k in this.externalWindowsObjects){result=cb(this.externalWindowsObjects[k]);if(result){return result;}}}
return result;},getValueFromFrame:function(object_name,attribute_name,dtype){return asTypedTxt(window[object_name][attribute_name],dtype);},getServerLastTs:function(){return asTypedTxt(new Date(genro._lastUserEventTs.getTime()+(genro.serverTimeDelta||0)),'DH');},getServerLastRpc:function(){return asTypedTxt(new Date(genro._lastRpc.getTime()+(genro.serverTimeDelta||0)),'DH')},getTimeProfilers:function(){return dojo.toJson(this.timeProfilers);},getChildrenInfo:function(result){result=result||{};var cb=function(f,r){if(f.genro){var kw={_lastUserEventTs:f.genro.getServerLastTs(),_pageProfilers:f.genro.getTimeProfilers(),_lastRpc:f.genro.getServerLastRpc()};r[f.genro.page_id]=objectUpdate(kw,f.genro._serverstore_changes);f.genro._serverstore_changes=null;f.genro.getChildrenInfo(r);}};dojo.forEach(window.frames,function(f){try{cb(f,result);}catch(e){}});if(this.externalWindowsObjects){objectValues(this.externalWindowsObjects).forEach(function(f){try{cb(f,result);}catch(e){}});}
return objectUpdate({},result);},dragDropConnect:function(pane){var pane=pane||dojo.body();dojo.connect(pane,'dragstart',genro.dom,'onDragStart');dojo.connect(pane,'dragend',genro.dom,'onDragEnd');dojo.connect(pane,'dragover',genro.dom,'onDragOver');dojo.connect(pane,'drop',genro.dom,'onDrop');},setLastSelection:function(focusNode){try{if(focusNode.selection||focusNode.selectionStart||focusNode.selectionEnd){genro._lastSelection={domNode:focusNode,start:focusNode.selectionStart,end:focusNode.selectionEnd};}else{genro._lastSelection={};}}catch(e){genro._lastSelection={};}},setCurrentFocused:function(wdg){var sourceNode=wdg.sourceNode;if(sourceNode.grid){return;}
var destform=sourceNode.form;var changedForm=destform!=genro.activeForm;if(changedForm){if(genro.activeForm){genro.activeForm.onBlurForm();}
genro.activeForm=destform;}
if(genro.activeForm){genro.activeForm.onFocusElement(wdg);if(changedForm){destform.onFocusForm();}}},hasPendingChanges:function(){return(this.activeForm&&this.activeForm.changed)||this.childrenHasPendingChanges();},childrenHasPendingChanges:function(){var f;for(var i=0;i<window.frames.length;i++){f=window.frames[i];try{if(f.genro&&f.genro.hasPendingChanges()){return true;}}catch(e){}}
return false;},checkBeforeUnload:function(){var parentGenro=this.getParentGenro();if(parentGenro&&parentGenro._windowClosing){return}
if(genro.hasPendingChanges()){return _T('You have an active form with pending changes')}},standardEventConnection:function(pane){var pane=pane||genro.domById('mainWindow');if(this.isDeveloper){dojo.connect(dojo.body(),'onmouseover',function(e){if(e.shiftKey&&e.altKey){var sn=genro.getSourceNode(e);if(sn){console.log(sn.absDatapath());}}});}},playUrl:function(url,onEnd){var sound=new Audio(url);if(onEnd){sound.addEventListener('ended',function(){onEnd.call();},false);}
sound.play();},playSound:function(name,path,ext){if(name.indexOf('$')==0){var name=genro.userPreference('sys.sounds.'+name.slice(1));if(!name){return;}}
if(!(name in genro.sounds)){var path=path||'/_gnr/11/sounds/';var ext=ext||'wav';genro.sounds[name]=new Audio(path+name+'.'+ext);}
genro.sounds[name].play();},setInServer:function(path,value,pageId){genro.rpc.remoteCall('setInServer',{path:path,value:value,pageId:pageId});},loadContext:function(){var contextBag=new gnr.GnrBag();var cookie=dojo.cookie("genroContext");if(cookie){var cookiestring=genro.dom.parseXmlString(cookie);contextBag.fromXmlDoc(cookiestring);}
genro.setData('_clientCtx',contextBag);genro.publish('onCookieLoaded');},fireEvent:function(path,msg){msg=(msg!=null)?msg:true;var path=genro.src.getNode().absDatapath(path);genro._data.setItem(path,msg);genro._data.setItem(path,null,null,{'doTrigger':false});},test:function(v){console.log(v);},resizeAll:function(){genro.wdgById('_gnrRoot').resize();},callAfter:function(cb,timeout,scope,reason){scope=scope||genro;cb=funcCreate(cb);if(reason){if(this.pendingCallAfter[reason]){clearTimeout(this.pendingCallAfter[reason]);}
this.pendingCallAfter[reason]=setTimeout(dojo.hitch(scope,cb),timeout);}
else{setTimeout(dojo.hitch(scope,cb),timeout);}},fireAfter:function(path,msg,timeout){var timeout=timeout||1;var _path=path;var _msg=msg;if(this.pendingCallAfter[path]){clearTimeout(this.pendingCallAfter[path]);}
this.pendingCallAfter[path]=setTimeout(function(){genro.fireEvent(_path,_msg);},timeout);},setDataAfter:function(path,value,timeout){setTimeout(function(){genro.setData(path,value);},timeout||1);},sendMouseEvent:function(target,evtstr,delay){var delay=delay||100;var evtstr=evtstr||'click';var cb=dojo.hitch(target,function(){var newevt=document.createEvent("MouseEvents");newevt.initMouseEvent(evtstr,true,true,window,0,0,0,0,0,false,false,false,false,0,null);this.dispatchEvent(newevt);});setTimeout(cb,100);},getPref:function(prefname,pars){if(pars){return templateReplace(genro.prefs[prefname],pars);}else{return genro.prefs[prefname];}},userPreference:function(pref){return genro._('gnr.user_preference.'+pref);},appPreference:function(pref){return genro._('gnr.app_preference.'+pref);},setUserPreference:function(path,data,pkg){genro.serverCall('setUserPreference',{path:path,data:data,pkg:pkg},function(){});},setAppPreference:function(path,data){genro.serverCall('setPreference',{path:path,data:data,pkg:pkg},function(){});},chat:function(){return this.mainGenroWindow.ct_chat_utils;},format:function(v,f,m){if(f.dtype=='P'){return genro.formatter.asText(v,f);}
if(v instanceof Date&&!f.format){var opt=objectUpdate({},f);if(opt['time']){opt.selector='time';opt.formatLength=opt['time'];}
else if(opt['datetime']){opt.selector='datetime';opt.formatLength=opt['datetime'];}else{opt.selector='date';opt.formatLength=opt['date'];}
v=dojo.date.locale.format(v,opt);}
else if(typeof(v)=='number'){f.locale=f.locale||dojo.locale;if(f.format){return genro.formatter.asText(v,{format:f.format.format||f.format,format_max:f.max,format_min:f.min,format_high:f.high,format_low:f.low,format_optimal:f.optimal,format_currency:f.currency});}
if(!f.places&&f.dtype=='L'){f.places=0;}
if(!f.pattern&&f.places==0){f.pattern='##########';}
if(!f.currency){v=stringStrip(dojo.number.format(v,f));}
else
{v=stringStrip(dojo.currency.format(v,f));}}else if(v instanceof Array){v=genro.formatter.asText(v,f.joiner);}else if(v instanceof gnr.GnrBag){v=v.getFormattedValue(objectExtract(f,'bag_*',true));}else if(v&&f.dtype=='X'){console.warn('DEPRECATED')
var b=new gnr.GnrBag();try{var parser=new DOMParser();var xmlDoc=parser.parseFromString(v,"text/xml");b.fromXmlDoc(xmlDoc,genro.clsdict);if(b.keys().length>0){v=b.getFormattedValue(objectExtract(f,'bag_*',true));}else{v='';}}catch(e){v='';}}
else if(typeof(v)=='boolean'||f.dtype=='B'){if(typeof(v)=='string'){return(v[0]=='^'||v[0]=='=')?'&nbsp;':v;}
var divcontent,divclass;var falsecontent=f['false']||(f['falseclass']?'':'false');var truecontent=(f['true']||(f['trueclass']?'':'true'));var trueclass=(f['trueclass']?f['trueclass']:'');var falseclass=(f['falseclass']?f['falseclass']:'');if(f['nullclass']||f['null']){var nullclass=(f['nullclass']?f['nullclass']:'');var nullcontent=(f['null']||(f['nullclass']?'':'null'));divcontent=(v===true)?truecontent:(v===false)?falsecontent:nullcontent;divclass=(v===true)?trueclass:(v===false)?falseclass:nullclass;}else{divcontent=v?truecontent:falsecontent;divclass=v?trueclass:falseclass;}
divclass=(divclass&&!divcontent)?'class="'+divclass+'"':'';var event_attrs='';var events=objectExtract(f,'on*',true);if(events){for(var event_type in events){var cellPars=f['cellPars']||{};var jsCode="genro.src.onEventCall(event,'"+escapeLiterals(events[event_type])+"',"+serialize(cellPars)+");";event_attrs+=" on"+event_type+'="'+cleanJsCode(jsCode)+'"';}}
v="<div "+event_attrs+" style='margin:auto;' "+divclass+">"+divcontent+"</div>";}
if(f['apply']){var cb=funcCreate(f['apply'],'value');v=cb.apply(window,[v]);}
else if(!v){if(f['isbutton']){var divclass=f['buttonclass'];divclass=divclass?'class="'+divclass+'"':'';var event_attrs='';var events=objectExtract(f,'on*',true);var title=f['tip']||'';var label=typeof(f['isbutton'])=='string'?f['isbutton']:'&nbsp;';if(events){for(var event_type in events){var cellPars=f['cellPars']||{};var jsCode="genro.src.onEventCall(event,'"+escapeLiterals(events[event_type])+"',"+serialize(cellPars)+");";event_attrs+=" on"+event_type+'="'+cleanJsCode(jsCode)+'"';}}
v="<div title='"+title+"'"+event_attrs+" style='margin:auto;' "+divclass+">"+label+"</div>";}
else if(f['inlineedit']==true){v="<span style='font-family: wingdings; text-decoration: underline;'>&nbsp;&nbsp;&nbsp;&nbsp;&#x270d;&nbsp;&nbsp;&nbsp;&nbsp;</span>";}}
if(f['showlinks']&&v){if(v instanceof Array){v=v.join(f['joiner']||',')}
v=highlightLinks(v);}
if(f.format){v=genro.formatter.asText(v,{format:f.format.format||f.format,mask:f.mask,dtype:f.dtype});}
return v;},setdebug:function(topic,level){if(!topic&&this.debugtopics){delete this.debugtopics;}else{if(!this.debugtopics){this.debugtopics={};}
this.debugtopics[topic]=level||'console';}},debug:function(msg,debuglevel,topic){if(this.debugtopics){var debuglevel=this.debugtopics[topic];}else{var debuglevel=debuglevel||this.debuglevel;}
if(debuglevel=='console'){console.debug((new Date())+msg);}
else if(debuglevel=='alert'){alert(msg);}},log:function(source,reason){var logpath='gnr._dev.logger';reason=reason?'\n-----------------\n'+reason+'\n-----------------':'';var log=genro.getData(logpath)+reason+'\n'+source;genro.setData(logpath,log);},clearlog:function(){genro.setData('gnr._dev.logger','');},isLocalPageId:function(page_id){if(page_id==genro.page_id){return true;}
return dojo.some(window.frames,function(f){try{return f.genro?f.genro.page_id==page_id:false}catch(error){return false;}});},getCounter:function(what,reset){what=what?'_counter_'+what:'_counter';if(reset==true){this[what]=0;}else{this[what]=(this[what]||0)+1;}
return this[what];},time36Id:function(){var t=new Date().getTime();if(this.last_time36Id!=t){this.last_time36Id=t;this.last_time36Id_cnt=0;}
this.last_time36Id_cnt+=1;return((this.last_time36Id*1000)+this.last_time36Id_cnt).toString(36);},bagToTable:function(kwargs){var bag=genro.getData(kwargs.path);var result=new gnr.GnrBag();var columns=[];for(var i=0;i<kwargs.columns.length;i++){var col=kwargs.columns[i].split(':');result.setItem('headers.'+col[0],null,{label:col[1]});columns.push(col[0]);}
var node;var tblId;for(var i=0;i<bag.len();i++){node=bag.getNodes()[i];for(var j=0;j<columns.length;j++){if(columns[j]==kwargs.key){result.setItem('rows.'+node.label+'.'+columns[j],node.label);}
else{result.setItem('rows.'+node.label+'.'+columns[j],node.getAttr(columns[j]));}}}
return result;},recordToPDF:function(table,pkey,template){genro.download("",{table:table,pkey:pkey,template:template,method:"app.recordToPDF",mode:'text'});},rpcDownload:function(method,kwargs,onload_cb){genro.download('',genro.rpc.getRpcUrlArgs(method,kwargs),onload_cb);},download:function(url,args,onload_cb){var args=args||{};if(onload_cb=='print'){onload_cb="genro.dom.iFramePrint(this.domNode);";}
else{args.download=true;}
url=genro.makeUrl(url,args);genro.src.getNode()._('div','_dlframe');var node=genro.src.getNode('_dlframe').clearValue().freeze();var params={'src':url,display:'none',width:'0px',height:'0px'};if(onload_cb){params['connect_onload']=onload_cb;};frm=node._('htmliframe',params);node.unfreeze();},makeUrl:function(url,kwargs){if(url.indexOf('://')==-1){if(url.slice(0,1)!='/'){var base=document.location.pathname;if(base==null||base=='/'){base='/index';}
url=base+'/'+url;};url=document.location.protocol+'//'+document.location.host+url;};return genro.addKwargs(url,kwargs);},addKwargs:function(url,kwargs){if(kwargs){var currParams={};var parameters=[];currParams['page_id']=genro.page_id;currParams['_no_cache_']=genro.getCounter();objectUpdate(currParams,kwargs);for(var key in currParams){parameters.push(key+'='+encodeURIComponent(currParams[key]));}
url=url+'?'+parameters.join('&');}else{url=url+document.location.search;}
return url;},_invalidNodes:function(databag,sourceNode){if(typeof(databag)=='string'){if(sourceNode){databag=sourceNode.absDatapath(databag);}
databag=genro.getData(databag);}
return databag.invalidNodes('@');},dataValidate:function(databag,sourceNode){var r=this._invalidNodes(databag,sourceNode);return(r.length==0);},focusOnError:function(databag,sourceNode){var invalidNodes=this._invalidNodes(databag,sourceNode);if(invalidNodes.length>0){var node=invalidNodes[0];var kw={'evt':'invalid','node':node,'pathlist':node.getFullpath().split('.')};dojo.publish('_trigger_data',[kw]);}
return(invalidNodes.length==0);},dataTrigger:function(kw){var dpath=kw.pathlist.slice(1).join('.');if(dpath in genro._debugPaths){var dkw=genro._debugPaths[dpath];if(!dkw.condition||funcApply('return '+dkw.condition,kw)){if(dkw.mode=='D'){debugger;}else{console.log('** dataTrigger debug **','evt',kw.evt,'reason',kw.reason,'updattr',kw.updvalue,kw);}}}
if(kw.evt=='upd'&&kw.reason!='serverChange'){for(var registered_path in genro._serverstore_paths){if(dpath.indexOf(registered_path)==0){var inner=dpath.slice(registered_path.length);if(!inner||inner[0]=='.'){genro._serverstore_changes=genro._serverstore_changes||{};genro._serverstore_changes[genro._serverstore_paths[registered_path]+inner]=asTypedTxt(kw.value);break;}}}}
if(kw.reason!='serverChange'){for(var shared_path in genro._sharedObjects_paths){var shared_id=genro._sharedObjects_paths[shared_path];if(dpath.indexOf(shared_path)==0){var so=genro._sharedObjects[shared_id];if(so.privilege!='readwrite'){console.error('you are not allowed to write the shared data:',shared_id,'privilege:',so.privilege)}else{var inner=dpath.slice(shared_path.length+1);var commandict={shared_id:shared_id,path:inner,value:kw.node._value,attr:kw.node.attr,evt:kw.evt,'fired':kw.fired}
genro.wsk.send('som.datachange',commandict);}
break;}}}
dojo.publish('_trigger_data',[kw]);},fireDataTrigger:function(path){var node=genro.getDataNode(path);var kw={'evt':'fired','node':node,'pathlist':('main.'+path).split('.')};dojo.publish('_trigger_data',[kw]);},getSourceNode:function(obj){return genro.src.getNode(obj);},pathResolve:function(obj){if(!obj){debugger;}
if(typeof(obj)=='string'){if(!genro.src.getNode()){return obj;}
return genro.src.getNode().absDatapath(obj);}
if(obj instanceof gnr.GnrDomSourceNode){return obj.absDatapath();}
if(obj.sourceNode){return obj.sourceNode.absDatapath();}},getItem:function(path){if(stringStartsWith(path,'*S')){return genro.src._main.getItem(path.slice(3));}else if(stringStartsWith(path,'*D')){path=path.slice(3);}
return genro._data.getItem(path);},getDataNode:function(path,autocreate,dflt){var path;if(path){path=this.pathResolve(path);if(path){if(stringStartsWith(path,'*S')){return genro.src.getNode(path.slice(3));}
if(stringStartsWith(path,'*D')){path=path.slice(3);}
if(path){return this._data.getNode(path,false,autocreate,dflt);}else{return this._dataroot.getNode('main');}}}},getDataAttr:function(path,attr,dflt){var node=this.getDataNode(path);if(node){return node.getAttr(attr,dflt);}},getData:function(path,dflt,cb){var dflt=(dflt!=undefined)?dflt:null;if(path){var node=this.getDataNode(path);if(node){var value=node.getValue();if(value==null){value=dflt;}
return value;}else{return dflt;}}else{return this._data;}},_:function(path,dflt){return genro.src.getNode().getRelativeData(path);},resetData:function(path){var node=genro.getDataNode(path);if('_loadedValue'in node.attr){node.setValue(node.attr._loadedValue);}},copyData:function(path,sourcepath,changebackref){var node=genro.getDataNode(sourcepath);var value=node.getValue();if(changebackref){value.clearBackRef();}
genro.setData(path,value,node.getAttr());},doCallback:function(cb,_this){var obj;if(cb instanceof Function){return cb;}
else if((typeof(cb)=='string')){cb=cb.split('.');if(cb[0]=='this'){obj=_this;cb.pop(0);}else{var obj=window;}
for(var i=0;i<cb.length;i++){obj=obj[cb[i]];}
return obj;}
else{return cb.obj[cb.func];}},setData:function(path,value,attributes,doTrigger){var path=genro.pathResolve(path);genro._data.setItem(path,value,attributes,{'doTrigger':doTrigger,lazySet:true});},setDataFromRemote:function(path,method,params,attributes){genro.setData(path,genro.rpc.remoteCall(method,params));},dataSubscribe:function(path,subscriberId,kwargs){var bag=genro.getData(path);if(bag instanceof dojo.Deferred){return bag.addCallback(function(result){return result.subscribe(subscriberId,kwargs);});}else{return genro.getData(path).subscribe(subscriberId,kwargs);}},dataNodeSubscribe:function(path,subscriberId,kwargs){return genro.getDataNode(path).subscribe(subscriberId,kwargs);},subscribeEvent:function(object,eventname,obj,func){var objId=object.widgetId;dojo.subscribe(objId+'/'+eventname,obj,func);},_publish_new:function(topic,kw){var args=[];if(typeof(topic)=='string'){for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
dojo.publish(topic,args);return;}
var target=objectPop(topic,'target');},publish:function(topic,kw){var args=[];if(typeof(topic)=='string'){for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
dojo.publish(topic,args);return;}
var parent=topic['parent'];var iframe=topic['iframe'];var extWin=topic['extWin'];var kw=topic['kw']||kw;if('nodeId'in topic){var node=genro.nodeById(topic['nodeId']);if(node){node.publish(topic['topic'],kw);}}else if('form'in topic){var form=genro.getForm(topic['form']);if(form){form.publish(topic['topic'],kw);}}else{genro.publish(topic['topic'],kw);}
if(extWin){var extWindow=genro.externalWindowsObjects[extWin];if(extWindow){kw=kw||{};kw.topic=topic.topic;genro.dom.windowMessage(extWindow,kw);}
return;}
if(iframe){var t=objectUpdate({},topic);objectPop(t,'parent');if(iframe=='*'){dojo.forEach(window.frames,function(f){try{if(f.genro){f.genro.publish(t,kw);}}catch(e){}});}else{var iframeNode=genro.domById(iframe);if(iframeNode){var f=iframeNode.contentWindow;try{if(f&&f.genro){f.genro.publish(t,kw);}}catch(error){}}}}
if(parent){var parentGenro=this.getParentGenro();var t=objectUpdate({},topic);objectPop(t,'iframe');objectPop(t,'parent');parentGenro.publish(t,kw);}},absoluteUrl:function(url,kwargs,avoidCache){var base=document.location.pathname;var avoidCache=avoidCache===false?false:true;if(url){var sep=url.slice(0,1)=='?'?'':'/';url=base+sep+url;}
else{url=base;}
if(kwargs){var currParams={};currParams['page_id']=genro.page_id;if(avoidCache!=false){currParams['_no_cache_']=genro.getCounter();}
objectUpdate(currParams,kwargs);var parameters=[];for(var key in currParams){parameters.push(key+'='+escape(currParams[key]));}
url=url+'?'+parameters.join('&');}else{url=url+document.location.search;}
return url;},setInStorage:function(sessionType,key,value){var sessionType=sessionType||'session';var storage=(sessionType=='local')?localStorage:sessionStorage;storage.setItem(key,asTypedTxt(value));},getFromStorage:function(sessionType,key){var sessionType=sessionType||'session';var storage=(sessionType=='local')?localStorage:sessionStorage;var value=storage.getItem(key);return convertFromText(value);},addParamsToUrl:function(url,params){if(!url){return}
if(!objectNotEmpty(params)){return url;}
var parameters=[];for(var key in params){if(!isNullOrBlank(params[key])){parameters.push(key+'='+encodeURIComponent(params[key]));}}
var sep=(url.indexOf('?')!=-1)?'&':'?';return url+sep+parameters.join('&');},getFormChanges:function(formId){var fh=genro.formById(formId);if(fh){return fh.getFormChanges();}},getFormData:function(formId){var fh=genro.formById(formId);if(fh){return fh.getFormData();}},getFormCluster:function(formId){var fh=genro.formById(formId);if(fh){return fh.getFormCluster();}},getForm:function(frameCode){var frameNode=genro.getFrameNode(frameCode);return frameNode?frameNode.form:genro.formById(frameCode);},getStore:function(storeCode){return genro.nodeById(storeCode+'_store').store;},getFrameNode:function(frameCode,side){var frameNode=genro.nodeById(frameCode+'_frame');if(!frameNode){return;}
if(side=='frame'){return frameNode;}
var containerNode=frameNode.getValue().getNodes()[0];if(!side){return containerNode;}
return containerNode.getValue().getNodeByAttr('region',side);},formById:function(formId){var node=genro.nodeById(formId);if(node){return node.form;}},nodeById:function(nodeId,scope){var childpath,node;if(nodeId[0]=='/'){childpath=nodeId.slice(1);if(scope.attr.nodeId){node=scope;}else{if(scope.attr._childname){childpath=scope.attr._childname+'/'+childpath;}
node=scope.getParentNode();while(node&&!node.attr.nodeId){if(node.attr._childname){childpath=node.attr._childname+'/'+childpath;}
node=node.getParentNode();}}}
else{if(nodeId.indexOf('/')>=0){childpath=nodeId.split('/');nodeId=childpath[0];childpath=childpath.slice(1).join('/');}
if(nodeId.indexOf('FORM')==0){node=scope.attributeOwnerNode('formId,_fakeform')||scope.getParentNode();}else if(nodeId.indexOf('ANCHOR')==0){node=scope.attributeOwnerNode('_anchor')||scope.getParentNode();}}
var node=node||genro.src._index[nodeId];if(!node&&genro.src.building){node=genro.src._main.getNodeByAttr('nodeId',nodeId);}
return childpath?node.getChild(childpath):node;},domById:function(nodeId,scope){var node=this.nodeById(nodeId,scope);if(node){return node.getDomNode();}else{return dojo.byId(nodeId);}},wdgById:function(nodeId,scope){var node=this.nodeById(nodeId,scope);if(node){return node.getWidget();}},byId:function(id){var obj=dojo.widget.byId(id);if(obj==null){obj=dojo.byId(id);}
return obj;},remoteUrl:function(method,args,sourceNode,avoidCache){return genro.rpc.rpcUrl(method,args,sourceNode,avoidCache);},setUrlRemote:function(widget,method,args){var url=genro.rpc.rpcUrl(method,args);widget.setHref(url);},setLocStatus:function(status){if((status=='missingLoc')||(!genro.getData('gnr.localizerStatus'))){genro.setData('gnr.localizerStatus',status);}},setUrl:function(widget,url){widget.setUrl(url);},gotoURL:function(url,relative){if(relative){url=genro.constructUrl(url);}else{url=genro.joinPath(genro.getData('gnr.homeUrl')||'',url);}
window.location.assign(url);},joinPath:function(){var result=arguments[0];var i;for(i=1;i<arguments.length;i++){var p=arguments[i];if(result.substr(-1)!="/"){result+="/";}
if(p.substr(0,1)=="/"){p=p.substr(1);}
result+=p;}
return result;},gotoHome:function(){window.location.assign(genro.getData('gnr.homepage'));},webcalUrl:function(path,params){console.log(path);},constructUrl:function(path,params){var url=genro.getData('gnr.homeFolder')+path;if(params){var parameters=[];for(var key in params){parameters.push(key+'='+encodeURIComponent(params[key]));}
url=url+'?'+parameters.join('&');};return url;},logout:function(){genro.lockScreen(true,'logout');this.serverCall('connection.logout',null,'genro.gotoHome();');},remoteJson:function(method,params){return genro.rpc.remoteCall(method,params,'json');},serverCall:function(method,params,async_cb,mode,httpMethod){var cb=funcCreate(async_cb);var httpMethod=httpMethod||'POST';return genro.rpc.remoteCall(method,params,mode,httpMethod,null,cb);},makeDeferred:function(cb){var deferred=new dojo.Deferred();setTimeout(function(){deferred.callback(cb());},1);return deferred;},setSelectedVal:function(obj,value){var dataNode=genro.getDataNode(obj.sourceNode);dataNode.setAttr({'selectedValue':value});},evaluate:function(expr,showError){try{var toEval='genro.auxresult=('+expr+')';dojo.eval(toEval);return genro.auxresult;}catch(e){var showError=showError===false?false:true;if((console!=undefined)&&showError){console.log('genro.evaluate() failed:');console.log(expr);console.log(e);}
throw e;}},isEqual:function(a,b){var a=a instanceof Date?a.valueOf():a;var b=b instanceof Date?b.valueOf():b;return a==b;},connect:function(target,funcName,objToConnect){if(typeof objToConnect=='function'){dojo.connect(target,funcName,objToConnect);}else{dojo.connect(target,funcName,objToConnect['obj'],objToConnect['func']);}},call:function(objToCall){if(typeof objToCall=='function'){objToCall.apply(null,arguments);}else{objToCall['obj'][objToConnect['func']].apply(objToCall['obj'],arguments);}},pageReload:function(params,replaceParams){if(params){if(!replaceParams){var oldparams=parseURL(window.location)['params']||{};params=objectUpdate(params||{},oldparams);}
if(objectNotEmpty(params)){params['_no_cache_']=genro.getCounter();var plist=[];for(k in params){plist.push(k+'='+encodeURIComponent(params[k]));}
window.location.search=plist.join('&');}else{window.location.search='';}}else{window.location.assign(window.location.href);}},pageBack:function(){window.history.back();},goBack:function(){var pathlist=window.location.pathname.split('/');if(pathlist.slice(-1)!=''){window.location.pathname=pathlist.slice(0,-1).join('/');}else{window.location.pathname=pathlist.slice(0,-2).join('/');}},getSource:function(item){return item.sourceNode.getValue();},viewPDF:function(filename,forcedownload){var url=genro.rpc.rpcUrl("app.downloadPDF",{filename:filename,forcedownload:forcedownload});if(forcedownload){genro.dev.exportUrl(url);}else{genro.openWindow(url,filename);}},openWindow:function(url,name,params){params=params||{height:'600',width:'900'};if(params){if(typeof(params)!='string'){parlist=[];for(var par in params){parlist.push(par+'='+params[par]);}
params=parlist.join(',');}}
url=genro.dom.detectPdfViewer(url);var newwindow=window.open(url,name,params);if(window.focus){try{newwindow.focus();}catch(error){console.warn('newindow blocked focus');}}
return newwindow},openBrowserTab:function(url){url=genro.dom.detectPdfViewer(url);window.open(url)},childBrowserTab:function(url,parent_page_id){url=genro.addParamsToUrl(url,{_parent_page_id:(parent_page_id||genro.page_id)});url=genro.dom.detectPdfViewer(url);window.open(url);},dynamicDataProvider:function(table,columns,where,params){var method='app.getSelection';var cacheTime=-1;var isGetter=true;var attributes={'sync':true,'table':table,'columns':columns,'where':where,'recordResolver':false,'selectionName':'grid_'+table.replace(/\./g,'_')};attributes=objectUpdate(attributes,params);return genro.rpc.remoteResolver(method,attributes,{'cacheTime':cacheTime,'isGetter':isGetter});},getRelationResolver:function(params,resolverName,parentbag){params=objectUpdate({},params);var resolverName=resolverName||objectPop(params,'_resolver_name');var resolver=genro.rpc['remote_'+resolverName];if(resolver){return resolver.call(genro.rpc,params,parentbag);}},loadUserObject:function(path,params){var result=genro.rpc.remoteCall('app.loadUserObject',{'id':params['id'],'code':params['code'],'objtype':params.objtype,'userid':params.userid,'table':params.table},null,'GET').getValue();genro.setData(path,result.getItem('userobject'),result.getAttr('userobject'));},saveUserObject:function(path){var userobjectnode=genro.getDataNode(path);var userobjectbag=new gnr.GnrBag();userobjectbag.setItem('userobject',userobjectnode.getValue(),userobjectnode.getAttr());genro.rpc.remoteCall('app.saveUserObject',{'userobject':userobjectbag},null,'POST');},deleteUserObject:function(path){var qnode=genro.getDataNode(path);var pkey=qnode.getAttr('id');if(pkey){genro.rpc.remoteCall('app.deleteUserObject',{'pkey':pkey},null,'GET');}
objectPopAll(qnode.attr);qnode.setValue(new gnr.GnrBag());},PATCHED_KEYS:{LEFT_ARROW:37,UP_ARROW:38,RIGHT_ARROW:39,DOWN_ARROW:40,TAB:9,SHIFT:16,CTRL:17,ALT:18,ESCAPE:27,ENTER:13},formInfo:function(name){var name=name||'formPane';var controllerPath=genro.formById(name).controllerPath;return genro._(controllerPath);},invalidFields:function(name){return genro.formInfo(name).getItem('invalidFields');},google:function(key){if(!this._googleHandler){this._googleHandler=this.wdg.getHandler('GoogleLoader')
this._googleHandler._mapkey=key||genro.getData('gnr.mapkey')}
return this._googleHandler;},lockScreen:function(locking,reason,options){if(options===true){options={};}
options=options||{};var sourceNode=genro.nodeById(options.nodeId||'_gnrRoot');reason=reason||sourceNode.getStringId();sourceNode._lockingElements=sourceNode._lockingElements||{};sourceNode._lockingElements[reason]=reason;if(locking){var message='<div class="form_waiting"></div>';if(options.thermo){genro.setData('gnr.lockScreen.thermo',message);message=options.thermo===true?'^gnr.lockScreen.thermo':options.thermo;}else if(options.message){message=options.message;}
sourceNode.setHiderLayer(true,{message:message,z_index:999998});}else{objectPop(sourceNode._lockingElements,reason);if(!objectNotEmpty(sourceNode._lockingElements)){delete sourceNode._lockingElements;}
if(!sourceNode._lockingElements){sourceNode.setHiderLayer(false);}}}});dojo.declare("gnr.GnrClientCaller",gnr.GnrBagResolver,{constructor:function(kwargs){if(typeof kwargs.callback=='string'){this.callback=genro.evaluate(kwargs.callback);}else{this.callback=kwargs.callback;}
if(typeof kwargs.params=='string'){this.evaluate='this.params = '+kwargs.params;this.params={};}else{this.evaluate=null;this.params=kwargs.params;}},load:function(kwargs){if(this.evaluate){genro.evaluate(this.evaluate);}
if(kwargs){objectUpdate(this.params,kwargs);}
if(this.callback instanceof Function){return this.callback(this.params);}
else{return this.callback.obj[this.callback.func](this.params);}}});



var genropatches={};genropatches.places=function(){var placeOnScreenAroundElement=dijit.placeOnScreenAroundElement;dijit.placeOnScreenAroundElement=function(node,aroundNode,aroundCorners,layoutNode){var result=placeOnScreenAroundElement(node,aroundNode,aroundCorners,layoutNode);var bodyWidth=dojo.body().clientWidth;var coords=dojo.coords(node);var delta=bodyWidth-(coords.l+coords.w+5);if(delta<0){node.style.left=parseInt(node.style.left)+delta+'px';result.w=result.w+result.overflow;result.overflow=null;}
return result;};};genropatches.forEachError=function(){var fe=dojo.forEach;dojo['forEach']=function(arr,cb,scope){if(arr==null){if(genro.isDeveloper){debugger;}else{console.error('ERROR FOREACH',arguments,cb);return;}}
fe.call(dojo,arr,cb,scope);}};genropatches.setStateClass=function(){dojo.require('dijit.form._FormWidget');dijit.form._FormWidget.prototype._setStateClass_original=dijit.form._FormWidget.prototype._setStateClass;dijit.form._FormWidget.prototype._setStateClass=function(){if(this.stateNode||this.domNode){this._setStateClass_original();}};}
genropatches.getDocumentWindow=function(){dijit.getDocumentWindow=function(doc){if(dojo.isSafari&&!doc._parentWindow){var fix=function(win){win.document._parentWindow=win;for(var i=0;i<win.frames.length;i++){try{fix(win.frames[i]);}catch(e){}}}
try{fix(window.top);}catch(e){}}
if(dojo.isIE&&window!==document.parentWindow&&!doc._parentWindow){doc.parentWindow.execScript("document._parentWindow = window;","Javascript");var win=doc._parentWindow;doc._parentWindow=null;return win;}
return doc._parentWindow||doc.parentWindow||doc.defaultView;}}
genropatches.sendAsBinary=function(){if(!XMLHttpRequest.prototype.sendAsBinary){XMLHttpRequest.prototype.sendAsBinary=function(datastr){function byteValue(x){return x.charCodeAt(0)&0xff;}
var ords=Array.prototype.map.call(datastr,byteValue);var ui8a=new Uint8Array(ords);this.send(ui8a.buffer);}}};genropatches.dojoToJson=function(){dojo.toJson=function(it,prettyPrint,_indentStr){if(it===undefined){return"null";}
if(it instanceof gnr.GnrBag){console.log('object_to_json',it);}
var objtype=typeof it;if(objtype=="number"||objtype=="boolean"){return it+"";}
if(it===null){return"null";}
if(dojo.isString(it)){return dojo._escapeString(it);}
if(it.nodeType&&it.cloneNode){return"";}
var recurse=arguments.callee;var newObj;_indentStr=_indentStr||"";var nextIndent=prettyPrint?_indentStr+dojo.toJsonIndentStr:"";if(typeof it.__json__=="function"){newObj=it.__json__();if(it!==newObj){return recurse(newObj,prettyPrint,nextIndent);}}
if(typeof it.json=="function"){newObj=it.json();if(it!==newObj){return recurse(newObj,prettyPrint,nextIndent);}}
var sep=prettyPrint?" ":"";var newLine=prettyPrint?"\n":"";if(dojo.isArray(it)){var res=dojo.map(it,function(obj){var val=recurse(obj,prettyPrint,nextIndent);if(typeof val!="string"){val="null";}
return newLine+nextIndent+val;});return"["+res.join(","+sep)+newLine+_indentStr+"]";}
if(objtype=="function"){return null;}
var output=[];for(var key in it){var keyStr;if(typeof key=="number"){keyStr='"'+key+'"';}else if(typeof key=="string"){keyStr=dojo._escapeString(key);}else{continue;}
val=recurse(it[key],prettyPrint,nextIndent);if(typeof val!="string"){continue;}
output.push(newLine+nextIndent+keyStr+":"+sep+val);}
return"{"+output.join(","+sep)+newLine+_indentStr+"}";}};genropatches.dnd=function(){dojo.require("dojo.dnd.Moveable");var mvbl=dojo.dnd.Moveable;mvbl.prototype.onMouseDown_replaced=mvbl.prototype.onMouseDown;mvbl.prototype.onMouseDown=function(e){var contextclick=(e.button==2||genro.dom.getEventModifiers(e)=='Ctrl');if(!contextclick){this.onMouseDown_replaced(e);}}};genropatches.tabContainer=function(){dojo.require("dijit.layout.StackContainer");dijit.layout.StackController.prototype.onCloseButtonClick=function(page){var container=dijit.byId(this.containerId);container.deletePage(page);};};genropatches.menu=function(){dojo.require('dijit.Menu');dijit.Menu.prototype._openMyself=function(e){if(this.leftClickToOpen&&e.button>0){return;}
dojo.stopEvent(e);var x,y;if(dojo.isSafari||this._contextMenuWithMouse){x=e.pageX;y=e.pageY;}else{var coords=dojo.coords(e.target,true);x=coords.x+10;y=coords.y+10;}
var self=this;var savedFocus=dijit.getFocus(this);function closeAndRestoreFocus(){dijit.focus(savedFocus);dijit.popup.close(self);}
var popupKw={popup:this,x:x,y:y,onExecute:closeAndRestoreFocus,onCancel:closeAndRestoreFocus,orient:this.isLeftToRight()?'L':'R'};this.onOpeningPopup(popupKw);dijit.popup.open(popupKw);var that=this;setTimeout(function(){that.focus();},1)
this._onBlur=function(){this.inherited('_onBlur',arguments);dijit.popup.close(this);}};};genropatches.comboBox=function(){dojo.require('dijit.form.ComboBox');dojo.declare("gnr.Gnr_ComboBoxMenu",dijit.form._ComboBoxMenu,{templateString:"<ul class='dijitMenu' dojoAttachEvent='onmousedown:_onMouseDown,onmouseup:_onMouseUp,onmouseout:_onMouseOut' tabIndex='-1' style='overflow:\"auto\";'>"
+"<li class='dijitMenuItem dijitMenuPreviousButton' dojoAttachPoint='previousButton'></li>"
+"<li class='dijitMenuItem dijitMenuNextButton' dojoAttachPoint='nextButton'></li>"
+"</ul>",createOptions:function(results,dataObject,labelFunc){var lfa=dataObject.store.lastFetchAttrs;var columns=lfa.columns.split(',');var headers=lfa.headers.split(',');var tblclass='multiColumnSelect'+' '+lfa.resultClass;genro.dom.scrollableTable(this.domNode,results[0].getParentBag(),{'columns':columns,'headers':headers,'tblclass':tblclass});this.domNode.onmouseover=dojo.hitch(this,'onmouseover');},tblrows:function(){return dojo.query('tbody tr',this.domNode);},clearResultList:function(){while(this.domNode.childNodes.length>2){this.domNode.innerHtml='';}},getItems:function(){return this.tblrows();},getListLength:function(){return this.tblrows().length;},onmouseup:function(evt){evt.preventDefault();dojo.stopEvent(evt);if(evt.target===this.domNode){return;}else{var tgt=this.getHighlightedOption();if(tgt){this.setValue({target:tgt},true);};}},onmouseover:function(evt){if(dojo.isIE>0){return;}
if(evt.target===this.domNode){return;}
var tgt=evt.target;if(tgt){if(tgt.getAttribute('id')){this._focusOptionNode(tgt);}else if(tgt.parentNode.getAttribute('id')){this._focusOptionNode(tgt.parentNode);}};},_page:function(up){return;},getHighlightedOption:function(){return this._highlighted_option;},_focusOptionNode:function(node){if(this._highlighted_option!=node){this._blurOptionNode();this._highlighted_option=node;dojo.addClass(this._highlighted_option,"multiColumnSelectHover");}},_blurOptionNode:function(){if(this._highlighted_option){dojo.removeClass(this._highlighted_option,"multiColumnSelectHover");this._highlighted_option=null;}},_highlightNextOption:function(){var domnode_bottom=this.domNode.getBoundingClientRect().bottom;var nextNode;var hop=this.getHighlightedOption();if(!this.getHighlightedOption()){nextNode=this.tblrows()[0];}else if(hop.nextSibling&&hop.style.display!="none"){nextNode=hop.nextSibling;}
if(nextNode){brect=nextNode.getBoundingClientRect();this._focusOptionNode(nextNode);if(brect.bottom>domnode_bottom){var delta=brect.bottom-brect.top;var scrollTop=this.domNode.children[0].children[1].scrollTop;this.domNode.children[0].children[1].scrollTop=scrollTop+20;}}},highlightFirstOption:function(){this._focusOptionNode(this.tblrows()[0]);},highlightLastOption:function(){var rows=this.tblrows();this._focusOptionNode(rows[rows.length-1]);},_highlightPrevOption:function(){if(!this.getHighlightedOption()){var rows=this.tblrows();this._focusOptionNode(rows[rows.length-1]);}else if(this._highlighted_option.previousSibling&&this._highlighted_option.previousSibling.style.display!="none"){this._focusOptionNode(this._highlighted_option.previousSibling);}},handleKey:function(evt){switch(evt.keyCode){case dojo.keys.DOWN_ARROW:this._highlightNextOption();break;case dojo.keys.PAGE_DOWN:this.pageDown();break;case dojo.keys.UP_ARROW:this._highlightPrevOption();break;case dojo.keys.PAGE_UP:this.pageUp();break;}}});var dijit_form_ComboBoxMixin_onKeyPress=function(evt){if(evt.altKey||(evt.ctrlKey&&evt.charCode!=118)){return;}
var doSearch=false;var pw=this._popupWidget;var dk=dojo.keys;if(this._isShowingNow){pw.handleKey(evt);}
var evt_keycode=evt.keyCode;if((evt_keycode==dk.UP_ARROW&&evt.keyChar=='&')||(evt_keycode==dk.DOWN_ARROW&&evt.keyChar=='(')){evt_keycode=0;}
switch(evt_keycode){case dk.PAGE_DOWN:case dk.DOWN_ARROW:if(!this._isShowingNow||this._prev_key_esc){this._arrowPressed();doSearch=true;}else{this._announceOption(pw.getHighlightedOption());}
dojo.stopEvent(evt);this._prev_key_backspace=false;this._prev_key_esc=false;break;case dk.PAGE_UP:case dk.UP_ARROW:if(this._isShowingNow){this._announceOption(pw.getHighlightedOption());}
dojo.stopEvent(evt);this._prev_key_backspace=false;this._prev_key_esc=false;break;case dk.ENTER:var highlighted;if(!this._isShowingNow){evt.preventDefault();dojo.stopEvent(evt);break;}
if(this._isShowingNow&&(highlighted=pw.getHighlightedOption())){if(highlighted==pw.nextButton){this._nextSearch(1);dojo.stopEvent(evt);break;}else if(highlighted==pw.previousButton){this._nextSearch(-1);dojo.stopEvent(evt);break;}}else{this.setDisplayedValue(this.getDisplayedValue());}
evt.preventDefault();case dk.TAB:var newvalue=this.getDisplayedValue();if(pw&&(newvalue==pw._messages["previousMessage"]||newvalue==pw._messages["nextMessage"])){break;}
if(this._isShowingNow){this._prev_key_backspace=false;this._prev_key_esc=false;if(pw.getHighlightedOption()){pw.setValue({target:pw.getHighlightedOption()},true);}
this._hideResultList();}
break;case dk.ESCAPE:this._prev_key_backspace=false;this._prev_key_esc=true;if(this._isShowingNow){dojo.stopEvent(evt);this._hideResultList();}
this.inherited(arguments);break;case dk.DELETE:case dk.BACKSPACE:this._prev_key_esc=false;this._prev_key_backspace=true;doSearch=true;break;case dk.RIGHT_ARROW:case dk.LEFT_ARROW:this._prev_key_backspace=false;this._prev_key_esc=false;break;default:this._prev_key_backspace=false;this._prev_key_esc=false;if(dojo.isIE||evt.charCode!=0){doSearch=true;}}
if(this.searchTimer){clearTimeout(this.searchTimer);}
if(doSearch){setTimeout(dojo.hitch(this,"_startSearchFromInput"),1);}}
dijit_form_ComboBoxMixin_onKeyPress.nom='_onKeyPress';dijit.form.ComboBoxMixin.prototype._onKeyPress=dijit_form_ComboBoxMixin_onKeyPress;dijit.form.ComboBox.prototype._onKeyPress=dijit_form_ComboBoxMixin_onKeyPress;};genropatches.borderContainer=function(){dojo.require("dijit.layout.BorderContainer");dojo.require("dijit.layout._LayoutWidget");dojo.declare("dijit.layout.BorderContainer",dijit.layout._LayoutWidget,{design:"headline",liveSplitters:true,persist:false,_splitterClass:"dijit.layout._Splitter",postCreate:function(){this.inherited(arguments);this._splitters={};this._splitterThickness={};dojo.addClass(this.domNode,"dijitBorderContainer");},startup:function(){if(this._started){return;}
dojo.forEach(this.getChildren(),function(child){this._setupChild(child);var region=child.region;if(this._splitters[region]){dojo.place(this._splitters[region],child.domNode,"after");this._computeSplitterThickness(region);}},this);this.inherited(arguments);},_setupChild:function(child){var region=child.region;if(region){child.domNode.style.position="absolute";var ltr=this.isLeftToRight();if(region=="leading"){region=ltr?"left":"right";}
if(region=="trailing"){region=ltr?"right":"left";}
this["_"+region+"Widget"]=child;this["_"+region]=child.domNode;if(child.splitter&&!this._splitters[region]){var _Splitter=dojo.getObject(this._splitterClass);var flip={left:'right',right:'left',top:'bottom',bottom:'top',leading:'trailing',trailing:'leading'};try{var oppNodeList=dojo.query('[region='+flip[child.region]+']',this.domNode);}catch(e){var oppNodeList=Array();oppNodeList.constructor=dojo.NodeList;dojo._mixin(oppNodeList,dojo.NodeList.prototype);}
var splitter=new _Splitter({container:this,child:child,region:region,oppNode:oppNodeList[0],live:this.liveSplitters});this._splitters[region]=splitter.domNode;}
child.region=region;}},_computeSplitterThickness:function(region){var re=new RegExp("top|bottom");this._splitterThickness[region]=dojo.marginBox(this._splitters[region])[(re.test(region)?'h':'w')];},layout:function(){this._layoutChildren();},addChild:function(child,insertIndex){this.inherited(arguments);this._setupChild(child);if(this._started){var region=child.region;if(this._splitters[region]){dojo.place(this._splitters[region],child.domNode,"after");this._computeSplitterThickness(region);}
this._layoutChildren();}},removeChild:function(child){var region=child.region;var splitter=this._splitters[region];if(splitter){dijit.byNode(splitter).destroy();delete this._splitters[region];delete this._splitterThickness[region];}
this.inherited(arguments);delete this["_"+region];delete this["_"+region+"Widget"];if(this._started){this._layoutChildren(child.region);}},_layoutChildren:function(changedRegion){var sidebarLayout=(this.design=="sidebar");var topHeight=0,bottomHeight=0,leftWidth=0,rightWidth=0;var topStyle={},leftStyle={},rightStyle={},bottomStyle={},centerStyle=(this._center&&this._center.style)||{};var changedSide=/left|right/.test(changedRegion);var cs=dojo.getComputedStyle(this.domNode);var pe=dojo._getPadExtents(this.domNode,cs);pe.r=parseFloat(cs.paddingRight);pe.b=parseFloat(cs.paddingBottom);var layoutSides=!changedRegion||(!changedSide&&!sidebarLayout);var layoutTopBottom=!changedRegion||(changedSide&&sidebarLayout);if(this._top){topStyle=layoutTopBottom&&this._top.style;topHeight=dojo.marginBox(this._top).h;}
if(this._left){leftStyle=layoutSides&&this._left.style;leftWidth=dojo.marginBox(this._left).w;}
if(this._right){rightStyle=layoutSides&&this._right.style;rightWidth=dojo.marginBox(this._right).w;}
if(this._bottom){bottomStyle=layoutTopBottom&&this._bottom.style;bottomHeight=dojo.marginBox(this._bottom).h;}
var splitters=this._splitters;var topSplitter=splitters.top;var bottomSplitter=splitters.bottom;var leftSplitter=splitters.left;var rightSplitter=splitters.right;var splitterThickness=this._splitterThickness;var topSplitterThickness=splitterThickness.top||0;var leftSplitterThickness=splitterThickness.left||0;var rightSplitterThickness=splitterThickness.right||0;var bottomSplitterThickness=splitterThickness.bottom||0;if(leftSplitterThickness>50||rightSplitterThickness>50){setTimeout(dojo.hitch(this,function(){for(var region in this._splitters){this._computeSplitterThickness(region);}
this._layoutChildren();}),50);return false;}
var splitterBounds={left:(sidebarLayout?leftWidth+leftSplitterThickness:0)+pe.l+"px",right:(sidebarLayout?rightWidth+rightSplitterThickness:0)+pe.r+"px"};if(topSplitter){dojo.mixin(topSplitter.style,splitterBounds);topSplitter.style.top=topHeight+pe.t+"px";}
if(bottomSplitter){dojo.mixin(bottomSplitter.style,splitterBounds);bottomSplitter.style.bottom=bottomHeight+pe.b+"px";}
splitterBounds={top:(sidebarLayout?0:topHeight+topSplitterThickness)+pe.t+"px",bottom:(sidebarLayout?0:bottomHeight+bottomSplitterThickness)+pe.b+"px"};if(leftSplitter){dojo.mixin(leftSplitter.style,splitterBounds);leftSplitter.style.left=leftWidth+pe.l+"px";}
if(rightSplitter){dojo.mixin(rightSplitter.style,splitterBounds);rightSplitter.style.right=rightWidth+pe.r+"px";}
dojo.mixin(centerStyle,{top:pe.t+topHeight+topSplitterThickness+"px",left:pe.l+leftWidth+leftSplitterThickness+"px",right:pe.r+rightWidth+rightSplitterThickness+"px",bottom:pe.b+bottomHeight+bottomSplitterThickness+"px"});var bounds={top:sidebarLayout?pe.t+"px":centerStyle.top,bottom:sidebarLayout?pe.b+"px":centerStyle.bottom};dojo.mixin(leftStyle,bounds);dojo.mixin(rightStyle,bounds);leftStyle.left=pe.l+"px";rightStyle.right=pe.r+"px";topStyle.top=pe.t+"px";bottomStyle.bottom=pe.b+"px";if(sidebarLayout){topStyle.left=bottomStyle.left=leftWidth+(this.isLeftToRight()?leftSplitterThickness:0)+pe.l+"px";topStyle.right=bottomStyle.right=rightWidth+(this.isLeftToRight()?0:rightSplitterThickness)+pe.r+"px";}else{topStyle.left=bottomStyle.left=pe.l+"px";topStyle.right=bottomStyle.right=pe.r+"px";}
var janky=dojo.isIE||dojo.some(this.getChildren(),function(child){return child.domNode.tagName=="TEXTAREA";});if(janky){var borderBox=function(n,b,s){n=dojo.byId(n);s=s||dojo.getComputedStyle(n);if(!b){return dojo._getBorderBox(n,s);}
var me=dojo._getMarginExtents(n,s);dojo._setMarginBox(n,b.l,b.t,b.w+me.w,b.h+me.h,s);return null;};var resizeWidget=function(widget,dim){if(widget){(widget.resize?widget.resize(dim):dojo.marginBox(widget.domNode,dim));}};var thisBorderBox=borderBox(this.domNode,null,cs);var containerHeight=thisBorderBox.h-pe.t-pe.b;var middleHeight=containerHeight;if(this._top){middleHeight-=topHeight;}
if(this._bottom){middleHeight-=bottomHeight;}
if(topSplitter){middleHeight-=topSplitterThickness;}
if(bottomSplitter){middleHeight-=bottomSplitterThickness;}
var centerDim={h:middleHeight};var sidebarHeight=sidebarLayout?containerHeight:middleHeight;if(leftSplitter){leftSplitter.style.height=sidebarHeight;}
if(rightSplitter){rightSplitter.style.height=sidebarHeight;}
resizeWidget(this._leftWidget,{h:sidebarHeight});resizeWidget(this._rightWidget,{h:sidebarHeight});var containerWidth=thisBorderBox.w-pe.l-pe.r;var middleWidth=containerWidth;if(this._left){middleWidth-=leftWidth;}
if(this._right){middleWidth-=rightWidth;}
if(leftSplitter){middleWidth-=leftSplitterThickness;}
if(rightSplitter){middleWidth-=rightSplitterThickness;}
centerDim.w=middleWidth;var sidebarWidth=sidebarLayout?middleWidth:containerWidth;if(topSplitter){topSplitter.style.width=sidebarWidth;}
if(bottomSplitter){bottomSplitter.style.width=sidebarWidth;}
resizeWidget(this._topWidget,{w:sidebarWidth});resizeWidget(this._bottomWidget,{w:sidebarWidth});resizeWidget(this._centerWidget,centerDim);}else{var resizeList={};if(changedRegion){resizeList[changedRegion]=resizeList.center=true;if(/top|bottom/.test(changedRegion)&&this.design!="sidebar"){resizeList.left=resizeList.right=true;}else if(/left|right/.test(changedRegion)&&this.design=="sidebar"){resizeList.top=resizeList.bottom=true;}}
dojo.forEach(this.getChildren(),function(child){if(child.resize&&(!changedRegion||child.region in resizeList)){try{child.resize();}catch(error){return;}}},this);}}});dojo.extend(dijit._Widget,{region:'',splitter:false,minSize:0,maxSize:Infinity});dojo.require("dijit._Templated");dojo.declare("dijit.layout._Splitter",[dijit._Widget,dijit._Templated],{live:true,templateString:'<div class="dijitSplitter" dojoAttachEvent="onkeypress:_onKeyPress,onmousedown:_startDrag" tabIndex="0" waiRole="separator"><div class="dijitSplitterThumb"></div></div>',postCreate:function(){this.inherited(arguments);this.horizontal=/top|bottom/.test(this.region);dojo.addClass(this.domNode,"dijitSplitter"+(this.horizontal?"H":"V"));this._factor=/top|left/.test(this.region)?1:-1;this._minSize=this.child.minSize;this._computeMaxSize();this.connect(this.container,"layout",dojo.hitch(this,this._computeMaxSize));this._cookieName=this.container.id+"_"+this.region;if(this.container.persist){var persistSize=dojo.cookie(this._cookieName);if(persistSize){this.child.domNode.style[this.horizontal?"height":"width"]=persistSize;}}},_computeMaxSize:function(){var dim=this.horizontal?'h':'w';var available=dojo.contentBox(this.container.domNode)[dim]-(this.oppNode?dojo.marginBox(this.oppNode)[dim]:0);this._maxSize=Math.min(this.child.maxSize,available);},_startDrag:function(e){if(!this.cover){this.cover=dojo.doc.createElement('div');dojo.addClass(this.cover,"dijitSplitterCover");dojo.place(this.cover,this.child.domNode,"after");}else{this.cover.style.zIndex=1;}
if(this.fake){dojo._destroyElement(this.fake);}
if(!(this._resize=this.live)){(this.fake=this.domNode.cloneNode(true)).removeAttribute("id");dojo.addClass(this.domNode,"dijitSplitterShadow");dojo.place(this.fake,this.domNode,"after");}
dojo.addClass(this.domNode,"dijitSplitterActive");var factor=this._factor,max=this._maxSize,min=this._minSize||10;var axis=this.horizontal?"pageY":"pageX";var pageStart=e[axis];var splitterStyle=this.domNode.style;var dim=this.horizontal?'h':'w';var childStart=dojo.marginBox(this.child.domNode)[dim];var splitterStart=parseInt(this.domNode.style[this.region]);var resize=this._resize;var region=this.region;var mb={};var childNode=this.child.domNode;var layoutFunc=dojo.hitch(this.container,this.container._layoutChildren);var de=dojo.doc.body;this._handlers=(this._handlers||[]).concat([dojo.connect(de,"onmousemove",this._drag=function(e,forceResize){var delta=e[axis]-pageStart,childSize=factor*delta+childStart,boundChildSize=Math.max(Math.min(childSize,max),min);if(resize||forceResize){mb[dim]=boundChildSize;dojo.marginBox(childNode,mb);layoutFunc(region);}
splitterStyle[region]=factor*delta+splitterStart+(boundChildSize-childSize)+"px";}),dojo.connect(de,"onmouseup",this,"_stopDrag")]);dojo.stopEvent(e);},_stopDrag:function(e){try{if(this.cover){this.cover.style.zIndex=-1;}
if(this.fake){dojo._destroyElement(this.fake);}
dojo.removeClass(this.domNode,"dijitSplitterActive");dojo.removeClass(this.domNode,"dijitSplitterShadow");this._drag(e);this._drag(e,true);}finally{this._cleanupHandlers();delete this._drag;}
if(this.container.persist){dojo.cookie(this._cookieName,this.child.domNode.style[this.horizontal?"height":"width"]);}},_cleanupHandlers:function(){if(this._handlers){dojo.forEach(this._handlers,dojo.disconnect);}
delete this._handlers;},_onKeyPress:function(e){this._resize=true;var horizontal=this.horizontal;var tick=1;var dk=dojo.keys;switch(e.charOrCode){case horizontal?dk.UP_ARROW:dk.LEFT_ARROW:tick*=-1;break;case horizontal?dk.DOWN_ARROW:dk.RIGHT_ARROW:break;default:return;}
var childSize=dojo.marginBox(this.child.domNode)[horizontal?'h':'w']+this._factor*tick;var mb={};mb[this.horizontal?"h":"w"]=Math.max(Math.min(childSize,this._maxSize),this._minSize);dojo.marginBox(this.child.domNode,mb);this.container._layoutChildren(this.region);dojo.stopEvent(e);},destroy:function(){this._cleanupHandlers();delete this.child;delete this.container;delete this.fake;this.inherited(arguments);}});};genropatches.tree=function(){dojo.require('dijit.Tree');dijit.Tree.prototype._expandNode_replaced=dijit.Tree.prototype._expandNode;dijit.Tree.prototype._collapseNode_replaced=dijit.Tree.prototype._collapseNode;dijit.Tree.prototype._expandNode=function(node){if(node.item&&node.item._resolver&&node.item._resolver.expired()){node.state='UNCHECKED';}
if(node.__eventmodifier=='Shift'&&node.isExpandable){var was_expanded=node.isExpanded;this._expandNode_replaced(node);if(!was_expanded){this.expandAll(node);}}else{return this._expandNode_replaced(node);}}
dijit.Tree.prototype._collapseNode=function(node){if(node.item&&node.item._resolver&&node.item._resolver.expired()){node.state='UNCHECKED';}
if(node.__eventmodifier=='Shift'&&node.isExpandable){var was_expanded=node.isExpanded;this._collapseNode_replaced(node);if(was_expanded){this.collapseAll(node);}}else{return this._collapseNode_replaced(node);}}
dijit._TreeNode.prototype.setLabelNode=function(label){this.labelNode.innerHTML="";var itemattr=this.item.attr||{};if((typeof(label)=='string')&&(label.indexOf('innerHTML:')>=0)){this.labelNode.innerHTML=label.replace('innerHTML:','');}
else{this.labelNode.appendChild(dojo.doc.createTextNode(label));};if('node_class'in itemattr){dojo.addClass(this.domNode,itemattr.node_class);}
if(itemattr.tip){this.domNode.setAttribute('title',itemattr.tip);}
var sourceNode=this.tree.sourceNode;var draggable=sourceNode.attr.draggable;if(draggable&&(this.item instanceof gnr.GnrBagNode)){this.domNode.setAttribute('draggable',draggable);}};};genropatches.parseNumbers=function(){dojo.require('dojo.number');dojo.number._integerRegexp=function(flags){flags=flags||{};if(!("signed"in flags)){flags.signed=[true,false];}
if(!("separator"in flags)){flags.separator="";}else if(!("groupSize"in flags)){flags.groupSize=3;}
var signRE=dojo.regexp.buildGroupRE(flags.signed,function(q){return q?"[-+]":"";},true);var numberRE=dojo.regexp.buildGroupRE(flags.separator,function(sep){if(!sep){return"(?:\\d+)";}
sep=dojo.regexp.escapeString(sep);if(sep==" "){sep="\\s";}
else if(sep=="\xa0"){sep="\\s\\xa0";}
var grp=flags.groupSize,grp2=flags.groupSize2;if(grp2){var grp2RE="(?:0|[1-9]\\d{0,"+(grp2-1)+"}(?:["+sep+"]\\d{"+grp2+"})*["+sep+"]\\d{"+grp+"})";return((grp-grp2)>0)?"(?:"+grp2RE+"|(?:0|[1-9]\\d{0,"+(grp-1)+"}))":grp2RE;}
return"(?:0|[1-9]\\d{0,"+(grp-1)+"}(?:["+sep+"]\\d{"+grp+"})*)";},true);return signRE+numberRE;};};genropatches.decimalRound=function(){function decimalAdjust(type,value,exp){if(typeof exp==='undefined'||+exp===0){return Math[type](value);}
value=+value;exp=+exp;if(isNaN(value)||!(typeof exp==='number'&&exp%1===0)){return NaN;}
value=value.toString().split('e');value=Math[type](+(value[0]+'e'+(value[1]?(+value[1]-exp):-exp)));value=value.toString().split('e');return+(value[0]+'e'+(value[1]?(+value[1]+exp):exp));}
if(!Math.round10){Math.round10=function(value,exp){if(exp===undefined){exp=-2;}
return decimalAdjust('round',value,exp);};}
if(!Math.floor10){Math.floor10=function(value,exp){return decimalAdjust('floor',value,exp);};}
if(!Math.ceil10){Math.ceil10=function(value,exp){return decimalAdjust('ceil',value,exp);};}};



dojo.declare("gnr.GnrRemoteResolver",gnr.GnrBagResolver,{constructor:function(kwargs,isGetter,cacheTime){this.xhrKwargs={'handleAs':'xml','timeout':50000,'load':'resultHandler','error':'errorHandler','sync':false,'preventCache':false};var k;for(k in this.xhrKwargs){if(k in kwargs){this.xhrKwargs[k]=objectPop(kwargs,k);}}
this.xhrKwargs.load=dojo.hitch(this,this.xhrKwargs.load);this.xhrKwargs.error=dojo.hitch(this,this.xhrKwargs.error);this.httpMethod=objectPop(kwargs,'httpMethod')||'POST';this.onloading=null;this.onResult=objectPop(kwargs,'_onResult');},load:function(kwargs){if(this.onloading){this.onloading(kwargs);}
var xhrKwargs=objectUpdate({},this.xhrKwargs);objectUpdate(xhrKwargs,objectExtract(kwargs,'rpc_*'));var sync=xhrKwargs.sync;if(kwargs._sourceNode&&kwargs.resolverPars&&kwargs.resolverPars.kwargs){kwargs.resolverPars.kwargs=kwargs._sourceNode.evaluateOnNode(kwargs.resolverPars.kwargs);}
var kw=objectUpdate({},kwargs);var onResult=this.onResult;var result;if(this.httpMethod=='WSK'){result=genro.wsk.call(kw);result.addErrback(function(error){console.error(error);});if(onResult){result.addCallback(function(value){funcApply(onResult,{result:value},kwargs._sourceNode);});}
return result;}else{result=genro.rpc._serverCall(kwargs,xhrKwargs,this.httpMethod);if(sync){result.addCallback(function(value){result=value;if(onResult){funcApply(onResult,{result:result},kwargs._sourceNode);}});}else if(onResult){result.addCallback(function(value){funcApply(onResult,{result:value},kwargs._sourceNode);});}}
return result;},errorHandler:function(response,ioArgs){return genro.rpc.errorHandler(response,ioArgs);},resultHandler:function(response,ioArgs){if(response.documentElement.tagName=='parsererror'){debugger;}
var result=genro.rpc.resultHandler(response,ioArgs,(this.updateAttr?this._parentNode.attr:null));return result}});dojo.declare("gnr.GnrServerCaller",gnr.GnrBagResolver,{constructor:function(kwargs){alert("GnrServerCaller");if(typeof kwargs.params=='string'){this.evaluate='this.params = '+kwargs.params;this.params={};}else{this.evaluate=null;this.params=kwargs.params;}
this.methodname=kwargs.methodname;this.respars=kwargs.respars||{};},load:function(kwargs,cb){if(this.evaluate){eval(this.evaluate);}
if(kwargs){objectUpdate(this.params,kwargs);}
return genro.rpc.remoteCall(this.methodname,this.params,this.respars.mode||'bag',null,null,cb);}});dojo.declare("gnr.GnrRpcHandler",null,{constructor:function(application){this.application=application;this.counter=0;this.rpc_register={};this.rpc_counter=0;this.rpc_level=0;this.dynRequires={js:{},css:{}};},hasPendingCall:function(){return objectNotEmpty(this.rpc_register);},register_call:function(kw){this.rpc_counter=this.rpc_counter+1;this.rpc_level=this.rpc_level+1;kw.content.callcounter=this.rpc_counter;kw['__rpc_counter']=this.rpc_counter;kw['__rpc_started']=new Date();this.rpc_register['r_'+this.rpc_counter]=kw;},unregister_call:function(ioArgs){this.rpc_level=this.rpc_level-1;var rpc_counter=ioArgs.args['__rpc_counter'];genro.dev.removeFromDebugged(rpc_counter);delete this.rpc_register['r_'+rpc_counter];},suspend_call:function(rpc_counter){var c=this.rpc_register['r_'+rpc_counter];if(c&&c._deferred_){c._deferred_.ioArgs.args.timeout=3600*1000;}},serverCall:function(callKwargs,xhrKwargs,httpMethod){},_serverCall:function(callKwargs,xhrKwargs,httpMethod){httpMethod=httpMethod||'POST';if(genro._serverstore_changes){callKwargs._serverstore_changes=genro._serverstore_changes;genro._serverstore_changes=null;}
var delayOnCall=objectPop(callKwargs,'_delayOnCall');var sourceNode=callKwargs['_sourceNode'];var sysrpc=objectPop(callKwargs,'sysrpc');if(sourceNode){objectUpdate(callKwargs,objectExtract(sourceNode.attr,'dbenv_*',true,true));}
callKwargs=this.serializeParameters(genro.src.dynamicParameters(callKwargs));objectPop(callKwargs,'_destFullpath');var content=objectUpdate({},callKwargs);content.page_id=this.application.page_id;var kw=objectUpdate({},xhrKwargs);kw.start_time=new Date();kw.url=kw.url||this.pageIndexUrl();if(genro.startArgs.aux_instance){content.aux_instance=genro.startArgs.aux_instance;}
var req_dbstore=genro.getData('current.context_dbstore');if(sourceNode){req_dbstore=req_dbstore||sourceNode.inheritedAttribute('context_dbstore');}
if(req_dbstore){content.temp_dbstore=req_dbstore;}else if(req_dbstore===false){content.temp_dbstore='_main_db';}
if(genro.startArgs._avoid_module_cache){content._avoid_module_cache=true;}
if(genro.debug_sql||genro.debug_py){if(genro.debug_py){content.debug_py=genro.debug_py;}
if(genro.debug_sql){content.debug_sql=genro.debug_sql;}
content.callcounter=genro.getCounter('debug');}
kw.content=content;kw.handleAs=kw.handleAs||'xml';this.register_call(kw);var xhrResult;if(!sysrpc){genro._lastRpc=new Date();}
if(genro.debugRpc){this.debugRpc(kw);}
if(delayOnCall){}else{var deferred=this._serverCall_execute(httpMethod,kw,callKwargs);kw._deferred_=deferred;return deferred;}},_serverCall_execute:function(httpMethod,kw,callKwargs){var xhrResult;if(this.debug){console.log('_serverCall_execute:start --- ',kw.method,'httpMethod',httpMethod,'kw',kw,'callKwargs',callKwargs)}
if(httpMethod=='GET'){xhrResult=dojo.xhrGet(kw);}
else if(httpMethod=='POST'){if('postData'in callKwargs){xhrResult=dojo.rawXhrPost(kw);}else{xhrResult=dojo.xhrPost(kw);}}
else if(httpMethod=='DELETE'){xhrResult=dojo.xhrDelete(kw);}
else if(httpMethod=='PUT'){if('putData'in callKwargs){xhrResult=dojo.rawXhrPut(kw);}else{xhrResult=dojo.xhrPut(kw);}}
if(this.debug){console.log('_serverCall_execute:end --- ',kw.method,'httpMethod',httpMethod,'kw',kw,'callKwargs',callKwargs,'result',xhrResult)}
return xhrResult;},debugRpc:function(kw){var method=kw.content?kw.content.method:'';method=method=='resolverRecall'?method+' : '+kw.content.resolverPars:method;console.log('method:'+method+' sync:'+kw.sync);console.log(kw);},errorCallback:function(type,errObj){alert("errorCallback");var status=errObj.xhr.status;if(status==200){alert('there was a server error');}
else if(status==401){genro.pageReload();}
else{genro.iobindError=status;}},remoteCallAsync:function(method,params,async_cb){alert("remoteCallAsync");return this.remoteCall(method,params,null,null,null,async_cb);},downloadCall:function(method,kwargs){var cb=function(result){genro.download(result);};genro.rpc.remoteCall(method,objectUpdate(kwargs,{'mode':'text'}),null,'POST',null,cb);},remoteCall:function(method,params,mode,httpMethod,preventCache,async_cb){var callKwargs=objectUpdate({},params);callKwargs.method=method;mode=mode||'bag';var preprocessor,handleAs,result;if((mode=='bag')||(mode=='xml')){handleAs='xml';preprocessor=dojo.hitch(this,'resultHandler');}
else{handleAs=mode;preprocessor=function(response,ioArgs){return response;};}
var cb;var sync=objectPop(callKwargs,'sync',false);if(async_cb){cb=dojo.hitch(this,function(response,ioArgs){var result=preprocessor(response,ioArgs);var error=(result&&typeof(result)=='object')?result.error:null;genro.safetry(function(){return async_cb(result,error);});return result;});}else{cb=dojo.hitch(this,function(response,ioArgs){ioArgs.syncresult=preprocessor(response,ioArgs);});sync=true;}
var timeout=objectPop(callKwargs,'timeout',50000);if(sync){genro.dom.addClass(dojo.body(),'gnr_sync_rpc');}
var xhrKwargs={'handleAs':handleAs,'timeout':timeout,'load':cb,'error':dojo.hitch(this,'errorHandler'),'sync':sync,'preventCache':preventCache};if(httpMethod=='WSK'){result=genro.wsk.call(callKwargs);result.addErrback(dojo.hitch(genro.wsk,'errorHandler'));if(async_cb){result.addCallback(async_cb);}
return result;}else{var deferred=this._serverCall(callKwargs,xhrKwargs,httpMethod);if(sync){genro.dom.removeClass(dojo.body(),'gnr_sync_rpc');}
return sync?deferred.ioArgs.syncresult:deferred;}},errorHandler:function(response,ioArgs){this.unregister_call(ioArgs);genro.dev.handleRpcHttpError(response,ioArgs);},setDatachangesInData:function(datachanges){var changenodes=datachanges.getNodes();for(var i=0;i<changenodes.length;i++){var changenode=changenodes[i];var value=changenode.getValue();var attr=objectExtract(changenode.attr,'change_*');var isDelete=objectPop(attr,'delete');var changepath=attr.path;var fired=attr.fired;var reason=attr.reason;var change_ts=attr.ts;attr=attr.attr||{};attr._change_ts=change_ts;var updater=function(path,value,attr,reason){value=convertFromText(value);attr=mapConvertFromText(attr);if(genro._data.getItem(path)!=value){genro._data.setItem(path,value,attr,reason!=null?{'doTrigger':reason,_updattr:true}:null);}};if(reason=='serverChange'){for(var clientpath_prefix in genro._serverstore_paths){var serverpath_prefix=genro._serverstore_paths[clientpath_prefix];if(stringStartsWith(changepath,serverpath_prefix)){clientpath=clientpath_prefix+changepath.slice(serverpath_prefix.length);updater(clientpath,value,attr,reason);}}}
else if(isDelete){genro._data.delItem(changepath);}
else{updater(changepath,value,attr,reason);if(fired){genro._data.setItem(changepath,null,null,{'doTrigger':false});}}}},loadRequires:function(envelope){var js_requires=envelope.getItem('js_requires');var css_requires=envelope.getItem('css_requires');var jslist=[];var csslist=[];var k;for(k in js_requires){if(!(k in this.dynRequires.js)){if(js_requires[k]){jslist.push({htype:'script',src:js_requires[k]});}
this.dynRequires.js[k]=true;}}
for(k in css_requires){if(!(k in this.dynRequires.css)){if(css_requires[k]){jslist.push({htype:'link',href:css_requires[k]});}
this.dynRequires.css[k]=true;}}
var urlist=jslist.concat(csslist);if(urlist.length){genro.dom.addHeaders(urlist,function(){genro.wdg.updateWidgetCatalog();});}},resultHandler:function(response,ioArgs,currentAttr){genro._last_rpc={response:response,ioArgs:ioArgs};this.unregister_call(ioArgs);var siteMaintenance=ioArgs.xhr.getResponseHeader('X-GnrSiteMaintenance');genro.dev.siteLockedStatus(siteMaintenance!=null);var envelope=new gnr.GnrBag();try{envelope.fromXmlDoc(response,genro.clsdict);}
catch(e){console.log('error in fromXmlDoc',e);console.log(response);return;}
this.profileTime(ioArgs.xhr);if(genro.debug_sql||genro.debug_py){var xmltime=parseFloat(ioArgs.xhr.getResponseHeader('X-GnrXMLTime')||0);var xmlsize=parseFloat(ioArgs.xhr.getResponseHeader('X-GnrXMLSize')||0);var callcounter=ioArgs.args.content.callcounter;if(callcounter!=null){genro.rpcHeaderInfo[callcounter]={xml_time:xmltime,xml_size:xmlsize};}}
var envNode=envelope.getNode('result');var resultAsNode=(envelope.getItem('resultType')=='node')||currentAttr;var changenode,attr,value,changepath,serverpath,as_fired,reason;var datachanges=envelope.getItem('dataChanges');if(datachanges){genro.rpc.setDatachangesInData(datachanges);}
var req,url;this.loadRequires(envelope);var childDataChanges=envelope.getItem('childDataChanges');if(childDataChanges){childDataChanges.forEach(function(n){var w=genro.getChildWindow(n.label);w.genro.rpc.setDatachangesInData(n._value);},'static');}
var runningBatch=envelope.getItem('runningBatch');genro.dom.setClass(dojo.body(),'runningBatch',runningBatch);var error=envelope.getItem('error');if(!error){var locStatus=envelope.getItem('_localizerStatus');if(locStatus){genro.setLocStatus(locStatus);}
if(currentAttr){attr=objectUpdate({},currentAttr);if(!envNode){console.log(envNode);debugger;}
envNode.attr=objectUpdate(attr,envNode.attr);}}else{setTimeout(dojo.hitch(genro.dev,'handleRpcError',error,envNode));return{'error':error};}
if(resultAsNode){return envNode;}else{if(envNode==null){debugger;}
return envNode.getValue();}},profileTime:function(xhr){var servertime=parseFloat(xhr.getResponseHeader('X-GnrTime')||0);var sqltime=parseFloat(xhr.getResponseHeader('X-GnrSqlTime')||0);var sqlcount=parseFloat(xhr.getResponseHeader('X-GnrSqlCount')||0);var cp=genro.currProfilers;cp.nc=cp.nc+1;cp.st=cp.st+servertime;cp.sqlt=cp.sqlt+sqltime;cp.sqlc=cp.sqlc+sqlcount;},getRecordCount:function(field,value,cb,kw){var rpckw={'field':field,'value':value};var kw=kw||{};objectUpdate(rpckw,kw);var result=genro.rpc.remoteCall('app.getRecordCount',rpckw,null,'GET',null,cb);return result;},pageIndexUrl:function(){return genro.currentUrl||document.location.pathname;},remoteResolver:function(methodname,params,kw){kw=kw||{};var cacheTime=kw.cacheTime==null?-1:kw.cacheTime;var isGetter=kw.isGetter||null;var kwargs=objectUpdate({'sync':true},params);kwargs.method=methodname;var resolver=new gnr.GnrRemoteResolver(kwargs,isGetter,cacheTime);return resolver;},getURLParams:function(source){if(source==null){source=window.location.search;}
var result={};source.replace(/(?:[\?&])?([^=]+)=([^&]+)/g,function(str,key,value){result[key]=unescape(value);});return result;},updateUrlParams:function(params,source){return dojo.io.argsFromMap(objectUpdate(genro.rpc.getURLParams(source),params,true));},getRpcUrlArgs:function(method,kwargs,sourceNode,avoidCache){avoidCache=avoidCache===false?false:true;var currParams={};currParams.page_id=this.application.page_id;currParams.method=method;currParams.mode='text';if(avoidCache!=false){currParams._no_cache_=genro.getCounter();}
var req_dbstore=genro.getData('current.context_dbstore');if(sourceNode){req_dbstore=req_dbstore||sourceNode.inheritedAttribute('context_dbstore');}
if(req_dbstore){currParams.temp_dbstore=req_dbstore;}else if(req_dbstore===false){currParams.temp_dbstore='_main_db';}
return objectUpdate(currParams,this.serializeParameters(genro.src.dynamicParameters(kwargs,sourceNode)));},rpcUrl:function(method,kwargs,sourceNode,avoidCache){var urlargs=genro.rpc.getRpcUrlArgs(method,kwargs,sourceNode,avoidCache);var url=genro.absoluteUrl(null,urlargs,avoidCache);return url;},makoUrl:function(template,kwargs){this.counter=this.counter+1;var currParams={};currParams['page_id']=this.application.page_id;currParams['mako']=template;currParams['_no_cache_']=this.counter;objectUpdate(currParams,kwargs);var parameters=[];for(var key in currParams){parameters.push(key+'='+escape(currParams[key]));}
return this.application.absoluteUrl('?'+parameters.join('&'));},serializeParameters:function(kwargs){var cntrlstr=[];var currarg,nodeattrs;for(var attr in kwargs){currarg=kwargs[attr];if((currarg instanceof gnr.GnrBag)&&(currarg.getParentNode()!=null)){nodeattrs=currarg.getParentNode().getAttr();if(objectNotEmpty(nodeattrs)){kwargs[attr+'_attr']=asTypedTxt(nodeattrs);}}
kwargs[attr]=asTypedTxt(currarg);cntrlstr.push(attr+'_'+kwargs[attr]);}
return kwargs;},addDeferredCb:function(deferred,func,cblocals,sourceNode){if(sourceNode){var cblocals=sourceNode.evaluateOnNode(cblocals);}
var isErrBack=objectPop(cblocals,'_isErrBack');var cb=function(result){cblocals['result']=result;var newresult=funcApply(func,cblocals,sourceNode);return newresult===undefined?result:newresult;};if(isErrBack){deferred.addErrback(cb);}else{deferred.addCallback(cb);}},ping:function(kw){if(genro.pollingRunning||!genro.polling_enabled){return;}
var kw=kw||{reason:null};genro.rpc.setPollingStatus(true);var xhrKwargs={'handleAs':'xml','url':document.location.protocol+'//'+document.location.host+genro.baseUrl+'_ping','timeout':10000,'load':dojo.hitch(this,function(response,ioArgs){var result=genro.rpc.resultHandler(response,ioArgs);if(genro.ping_classes){genro.callAfter(function(){genro.dom.removeClass(dojo.body(),'ping_start');},1000);}
genro.rpc.setPollingStatus(false);return result;}),'error':dojo.hitch(this,function(response,ioArgs){genro.rpc.setPollingStatus(false);if(genro.ping_classes){genro.dom.removeClass(dojo.body(),'ping_start');genro.dom.addClass(dojo.body(),'ping_error');}
if(!genro._ping_error){genro._ping_error=true;}
genro.rpc.errorHandler(response,ioArgs);}),'sync':false,'preventCache':false};var pingKw={page_id:genro.page_id,reason:kw.reason,_no_cache_:genro.getCounter()};if(!genro.root_page_id){pingKw._children_pages_info=genro.getChildrenInfo();}
pingKw._lastUserEventTs=genro.getServerLastTs();pingKw._lastRpc=genro.getServerLastRpc();pingKw._pageProfilers=genro.getTimeProfilers();pingKw.sysrpc=true;genro.lastPing=new Date();if(genro.ping_classes){genro.dom.removeClass(dojo.body(),'ping_error');genro.dom.addClass(dojo.body(),'ping_start');}
this._serverCall(pingKw,xhrKwargs,'POST');},setPollingStatus:function(status){genro.pollingRunning=status;},remote_relOneResolver:function(params,parentbag){var kw={};var cacheTime=-1;var isGetter=false;var sync=('sync'in params)?objectPop(params,'sync'):true;var kwargs={'sync':sync,'from_fld':params._from_fld,'target_fld':params._target_fld,'_debug_info':params._target_fld,'sqlContextName':params._sqlContextName,'virtual_columns':params._virtual_columns,'_resolver_kwargs':params._resolver_kwargs,'_storename':params._storename};var storefield=params._storefield;var resolver_kwargs=params._resolver_kwargs;kwargs.method='app.getRelatedRecord';var resolver=new gnr.GnrRemoteResolver(kwargs,isGetter,cacheTime);resolver.updateAttr=true;resolver.onloading=function(kwargs){if(storefield){kwargs['_storename']=this.getParentNode().getParentBag().getItem(storefield);}else if(storefield===false){kwargs['_storename']=false;}
if(resolver_kwargs){var parentRecordBag=this.getParentNode().getParentBag();for(var k in resolver_kwargs){var p=resolver_kwargs[k];if((p+'').indexOf('=')==0){p=p.slice(1);resolver_kwargs[k]=p.indexOf('.')==0?parentRecordBag.getItem(p.slice(1)):genro.getData(p);}}
kwargs['resolver_kwargs']=resolver_kwargs;}
var target=kwargs.target_fld.split('.');var table=target[0]+'_'+target[1];var loadingParameters=genro.getData('gnr.tables.'+table+'.loadingParameters');var rowLoadingParameters=objectPop(kwargs,'rowLoadingParameters');if(rowLoadingParameters){loadingParameters=loadingParameters||new gnr.GnrBag();var nodes=rowLoadingParameters.getNodes();for(var i=0;i<nodes.length;i++){if(nodes[i].label[0]!='@'){loadingParameters.setItem(nodes[i].label,nodes[i].getValue(),nodes[i].attr);}};}
kwargs['loadingParameters']=loadingParameters;};resolver.onloaded=function(){var f=this.attr._from_fld||this.attr._target_fld||table;genro.publish('resolverOneLoaded_'+f.replace(/\./g,'_'),{path:this.getFullpath(),node:this});}
var _related_field=params._target_fld.split('.')[2];if(params._auto_relation_value){resolver.relation_fld=params._auto_relation_value;var dataprovider=function(){return this.getParentNode().getParentBag().getItem(this.relation_fld);};kwargs[_related_field]=dojo.hitch(resolver,dataprovider);var valNode=parentbag.getNode(resolver.relation_fld);var reloader=function(n,val,oldval,doTrigger){if(val==oldval||(isNullOrBlank(val)&&isNullOrBlank(oldval))){return;}
var optkw={}
if(doTrigger instanceof gnr.GnrDomSourceNode){optkw._sourceNode=doTrigger;}
this.getParentNode().getValue('reload',optkw);};if(valNode){valNode._onChangedValue=dojo.hitch(resolver,reloader);}else{console.log('missing valNode')}}else{kwargs[_related_field]=params._relation_value;}
return resolver;},remote_relManyResolver:function(params){var kw={};var cacheTime=-1;var isGetter=false;var kwargs={'sync':true,'columns':'==gnr.getGridColumns(_destFullpath);','from_fld':params._from_fld,'target_fld':params._target_fld,'relation_value':params._relation_value,'sqlContextName':params._sqlContextName,order_by:params._many_order_by};kwargs.method='app.getRelatedSelection';var resolver=new gnr.GnrRemoteResolver(kwargs,isGetter,cacheTime);resolver.updateAttr=true;resolver.onSetResolver=function(node){node.newBagRow=function(defaultArgs){var childResolverParams=this.attr.childResolverParams;var table=childResolverParams._target_fld.split('.').slice(0,2).join('_');var loadingParameters=genro.getData('gnr.tables.'+table+'.loadingParameters');if(defaultArgs instanceof Array){}else{var resolver=genro.getRelationResolver(objectUpdate(childResolverParams,{'sync':true}));resolver.kwargs.rowLoadingParameters=new gnr.GnrBag(defaultArgs);var attr=objectUpdate({},childResolverParams);for(var label in defaultArgs){attr[label.replace(/\W/g,'_')]=defaultArgs[label];};if(loadingParameters){var nodes=loadingParameters.getNodes();for(var i=0;i<nodes.length;i++){var n=nodes[i];attr[n.label]=n.getValue();};}
var result=new gnr.GnrBagNode(null,'label',null,attr,resolver);return result;}};};resolver.updateAttr=true;return resolver;},uploadMultipartFiles:function(filebag,kw){kw=kw||{};var uploaderId=kw.uploaderId;var onFileUploaded=kw.onFileUploaded||function(){genro.publish(uploaderId+'_done',arguments);};kw.onProgress=kw.onProgress||function(){genro.publish(uploaderId+'_progress',arguments);};kw.onError=kw.onError||function(){genro.publish(uploaderId+'_error',arguments);};kw.onAbort=kw.onAbort||function(){genro.publish(uploaderId+'_upload_aborted',arguments);};var onUploaded=function(node){onFileUploaded(node);filebag.pop(node.label);genro.rpc.uploadMultipartFiles(filebag,kw);};var setProgress=function(statusNode,evt){if(statusNode.last_execution_time&&(new Date()-statusNode.last_execution_time<500)){return;}
var percentComplete='';if(evt.lengthComputable){percentComplete=100*dojo.number.round(evt.loaded/evt.total,2);percentComplete+=' %';}
statusNode.attr.loaded=evt.loaded;statusNode.attr.total=evt.total;var message='SENDING: '+percentComplete;kw.onProgress(statusNode,evt);statusNode.setValue(message);statusNode.last_execution_time=new Date();genro.upload_progress=null;};if(filebag.len()>0){var firstNode=filebag.getNode('#0');var statusNode=firstNode.getValue().getNode('_status',false,true);var params=firstNode.getValue().asObj();var file=objectPop(params,'_file');objectExtract(params,'_*');var innerKw=objectUpdate({},kw);innerKw.onResult=function(e){onUploaded(firstNode);};innerKw.onProgress=function(e){setProgress(statusNode,e);};genro.rpc.uploadMultipart_oneFile(file,params,innerKw);}else{if(kw.onResult){kw.onResult();}}},uploadMultipart_oneFile:function(file,params,kw){params=params||{};var content=new FormData();params['rpc']=kw.method||'rpc.upload_file';params['page_id']=genro.page_id;params['uploaderId']=kw.uploaderId;params['uploadPath']=kw.uploadPath;params['filename']=kw.filename;var sourceNode=kw.uploaderId?genro.nodeById(kw.uploaderId):null;params=this.serializeParameters(genro.src.dynamicParameters(params,sourceNode));for(key in params){content.append(key,params[key]);}
var sender=new XMLHttpRequest();var errorCb=function(){console.log(arguments);};if(kw.onProgress){sender.upload.addEventListener("progress",function(evt){evt._sender=sender;kw.onProgress(evt)},false)};if(kw.onError){sender.upload.addEventListener("error",function(evt){evt._sender=sender;(kw.onError||errorCb)(evt)},false)};if(kw.onAbort){sender.upload.addEventListener("abort",function(evt){evt._sender=sender;kw.onAbort(evt);},false)};var onResult=objectPop(kw,'onResult');if(typeof(file)=='string'){content.append('dataUrl',file);}else{content.append('file_handle',file);}
sender.open("POST",genro.rpc.pageIndexUrl(),true);if(onResult){dojo.connect(sender,'onload',onResult);}
sender.send(content);return sender;}});



dojo.require('dijit.Menu');function inlineWidget(evt){var domNode=evt.target;var varname=domNode.getAttribute('varname');var chunkNode=genro.dom.getBaseSourceNode(domNode);if(chunkNode.form&&chunkNode.form.isDisabled()){return;}
var templateHandler=chunkNode._templateHandler;var colattr=templateHandler.template.getAttr('main')['editcols'][varname];var containerNode=domNode.parentNode;if(!templateHandler._editRootNode){templateHandler._editRootNode=chunkNode.getValue().getNode('_chunk_inline_editor_',null,true);templateHandler._editRootNode.attr.datapath=chunkNode.absDatapath(chunkNode.attr.datasource);}
var dt=colattr['dtype'];var widgets={'L':'NumberTextBox','I':'NumberTextBox','D':'DateTextbox','R':'NumberTextBox','N':'NumberTextBox','H':'TimeTextBox','B':'CheckBox'};colattr['tag']=widgets[dt]||'Textbox';if('related_table'in colattr){colattr['tag']='dbselect';colattr['dbtable']=colattr['related_table'];if(colattr['related_table_lookup']&&!'hasDownArrow'in colattr){colattr['hasDownArrow']=true;}}if('values'in colattr){colattr['tag']=colattr.values.indexOf(':')>=0?'filteringselect':'combobox';}
var sizer=templateHandler._editRootNode._('span',{_parentDomNode:containerNode,position:'absolute',width:'auto',top:-9999,left:-9999}).getParentNode();sizer.domNode.innerHTML=domNode.innerHTML;if(colattr['tag'].toLowerCase()=='datetextbox'){colattr['width']='7em';}else{colattr['width']=domNode.clientWidth+'px';colattr['connect_onkeyup']=function(){var fn=this.widget.focusNode;sizer.domNode.innerHTML=fn.value;var dn=this.widget.domNode;dn.style.width=sizer.domNode.clientWidth+8+'px'}}
colattr['min_width']='30px';colattr['value']='^.'+colattr['field'];colattr['_parentDomNode']=containerNode;colattr['rejectInvalid']=true;colattr['connect_onBlur']=function(){var dataNodeAttr=genro.getDataNode(this.absDatapath(this.attr.value)).attr;this._destroy();sizer._destroy();genro.dom.removeClass(containerNode,'inlineediting')}
colattr['attr__displayedValue']
genro.dom.addClass(containerNode,'inlineediting')
var widgetNode=templateHandler._editRootNode._(colattr.tag,colattr).getParentNode();widgetNode.widget.focus()};dojo.declare("gnr.GnrWdgHandler",null,{constructor:function(application){this.application=application;this.noConvertStyle={'table':['width','border'],'editor':['height'],'embed':['width','height'],'img':['width','height'],'canvas':['width','height']};this.tagParameters={};this.tagParameters['button']={'caption':'input'};this.tagParameters['contentpane']={'label':'input','layoutAlign':'select:top,bottom,left,right,client'};this.tagParameters['splitcontainer']={'activeSizing':'checkbox','sizerWidth':'input'};this.catalog=new gnr.GnrBag();this.namespace={};var htmlspace=['a','abbr','acronym','address','area','b','base','bdo','big','blockquote','body','br','button','caption','cite','code','col','colgroup','dd','del','div','dfn','dl','dt','em','fieldset','form','frame','frameset','h1','h2','h3','h4','h5','h6','head','hr','html','i','iframe','htmliframe','img','input','ins','kbd','label','legend','li','link','map','meta','noframes','noscript','object','ol','optgroup','option','p','param','pre','q','samp','script','select','small','span','strong','style','sub','sup','table','tbody','td','textarea','tfoot','th','thead','title','tr','tt','ul','var','embed','audio','video','canvas','progress'];for(var i=0;i<htmlspace.length;i++){tag=htmlspace[i];this.namespace[tag.toLowerCase()]=['html',tag];}
this.widgetcatalog={'CheckBox':'dijit.form.CheckBox','RadioButton':'dijit.form.CheckBox','ComboBox':'dijit.form.ComboBox','CurrencyTextBox':'dijit.form.CurrencyTextBox','DateTextBox':'dijit.form.DateTextBox','FilteringSelect':'dijit.form.FilteringSelect','InlineEditBox':'dijit.InlineEditBox','NumberSpinner':'dijit.form.NumberSpinner','NumberTextBox':'dijit.form.NumberTextBox','HorizontalSlider':'dijit.form.Slider','VerticalSlider':'dijit.form.Slider','SimpleTextarea':'dijit.form.SimpleTextarea','MultiSelect':'dijit.form.MultiSelect','TextBox':'dijit.form.TextBox','TimeTextBox':'dijit.form.TimeTextBox','ValidationTextBox':'dijit.form.ValidationTextBox','AccordionContainer':'dijit.layout.AccordionContainer','AccordionPane':'dijit.layout.AccordionContainer','ContentPane':'dijit.layout.ContentPane','BorderContainer':'dijit.layout.BorderContainer','LayoutContainer':'dijit.layout.LayoutContainer','SplitContainer':'dijit.layout.SplitContainer','StackContainer':'dijit.layout.StackContainer','TabContainer':'dijit.layout.TabContainer','Button':'dijit.form.Button','ToggleButton':'dijit.form.Button','ComboButton':'dijit.form.Button,dijit.Menu','DropDownButton':'dijit.form.Button,dijit.Menu','Menu':'dijit.Menu','MenuItem':'dijit.Menu','MenuSeparator':'dijit.Menu','PopupMenuItem':'dijit.Menu','Toolbar':'dijit.Toolbar','ToolbarSeparator':'dijit.Toolbar','Dialog':'dijit.Dialog','TooltipDialog':'dijit.Dialog','ProgressBar':'dijit.ProgressBar','TitlePane':'dijit.TitlePane','Tooltip':'dijit.Tooltip','ColorPalette':'dijit.ColorPalette','Editor':'dijit.Editor,dijit._editor.plugins.LinkDialog,dijit._editor.plugins.FontChoice,dijit._editor.plugins.TextColor','Tree':'dijit.Tree','FloatingPane':'dojox.layout.FloatingPane','Dock':'dojox.layout.FloatingPane','RadioGroup':'dojox.layout.RadioGroup','ResizeHandle':'dojox.layout.ResizeHandle','SizingPane':'dojox.layout.SizingPane','FisheyeList':'dojox.widget.FisheyeList','Loader':'dojox.widget.Loader','Toaster':'dojox.widget.Toaster','FileInput':'dojox.widget.FileInput','FileInputBlind':'dojox.widget.FileInputAuto','FileInputAuto':'dojox.widget.FileInputAuto','ColorPicker':'dojox.widget.ColorPicker','SortList':'dojox.widget.SortList','TimeSpinner':'dojox.widget.TimeSpinner','Iterator':'dojox.widget.Iterator','Gallery':'dojox.image.Gallery','Lightbox':'dojox.image.Lightbox','SlideShow':'dojox.image.SlideShow','ThumbnailPicker':'dojox.image.ThumbnailPicker','Deck':'dojox.presentation.Deck','Slide':'dojox.presentation.Slide','DojoGrid':'dojox.grid.Grid:dojox.Grid','VirtualGrid':'dojox.grid.VirtualGrid:dojox.VirtualGrid','GoogleMap':'','StaticMap':'','Image':'','GoogleChart':'','GoogleVisualization':'','CkEditor':'','dygraph':'','protovis':'','codemirror':'','LightButton':''};this.updateWidgetCatalog();},updateWidgetCatalog:function(){var tag;for(tag in this.widgetcatalog){this.namespace[tag.toLowerCase()]=['dojo',tag];}
this.widgets={};for(var wdg in gnr.widgets){this.widgets[wdg.toLowerCase()]=wdg;}},makeDomNode:function(tag,destination,ind){var ind=ind==null?-1:ind;var domnode=document.createElement(tag);if(destination.containerNode){destination.containerNode.appendChild(domnode);}
else if(destination.domNode){destination.domNode.appendChild(domnode);}
else{if(typeof(ind)=='object'){destination.replaceChild(domnode,ind);}else if(ind<0||ind>=destination.childNodes.length){destination.appendChild(domnode);}else{destination.insertBefore(domnode,destination.childNodes[ind]);}}
return domnode;},getHandler:function(tag){var lowertag=tag.toLowerCase();var handler=this.widgets[lowertag];if(!handler){var nsItem=this.namespace[lowertag];if(!nsItem){return;}
handler=this.widgets[('base'+nsItem[0]).toLowerCase()];}
if(typeof(handler)=='string'){this.widgets[lowertag]=new gnr.widgets[handler]();handler=this.widgets[lowertag];}
return handler;},create:function(tag,destination,attributes,ind,sourceNode){attributes=attributes||{};var newobj,domnode,domtag;var handler=this.getHandler(tag);genro.assert(handler,'missing handler for tag:'+tag);if(handler._beforeCreation){var goOn=handler._beforeCreation(attributes,sourceNode);if(goOn===false){return false;}
console.warn('should never happen _beforeCreation not returning false');domtag=objectPop(attributes,'domtag');}
var onCreating=objectPop(attributes,'onCreating');if(onCreating){funcCreate(onCreating).call(sourceNode,attributes,handler);}
var zoomToFit=objectPop(attributes,'zoomToFit')
domtag=domtag||handler._domtag||tag;if(ind=='replace'){domnode=destination;}else if(domtag=='*'){domnode=null;}else{var _attachTo=attributes._attachTo||handler._attachTo;destination=_attachTo?dojo.byId(_attachTo):destination;domnode=this.makeDomNode(domtag,destination,ind);}
if(typeof(ind)=='object'){ind=-1;}
var tip=objectPop(attributes,'tip');if('visible'in attributes&&!objectPop(attributes,'visible')){attributes.visibility='hidden';}
var currentHidden;if('hidden'in attributes){currentHidden=objectPop(attributes,'hidden');if(currentHidden){attributes.display='none';}}
var kw={'postCreation':handler._creating(attributes,sourceNode),'readonly':objectPop(attributes,'readonly'),'_style':objectAsStyle(genro.dom.getStyleDict(attributes,(this.noConvertStyle[domtag.toLowerCase()]))),'_class':objectPop(attributes,'_class')};if(!handler._dojowidget){if(tip){attributes['title']=tip;}
var extracted=objectExtract(attributes,'_*',{'_type':null});newobj=this.createHtmlElement(domnode,attributes,kw,sourceNode);if(zoomToFit){newobj=genro.dom.autoScaleWrapper(newobj,zoomToFit);}
this.linkSourceNode(newobj,sourceNode,kw);newobj.gnr=handler;}
else{newobj=this.createDojoWidget(tag,domnode,attributes,kw,sourceNode);if(tip){newobj.domNode.setAttribute('title',tip);}
else{newobj.domNode.setAttribute('title',"");}
this.linkSourceNode(newobj,sourceNode,kw);newobj.gnr=handler;if(destination&&destination.addChild){if(ind<0){destination.addChild(newobj);}
else{destination.addChild(newobj,ind);}}
if(newobj.setHidden&&currentHidden){genro.src.onBuiltCall(function(){newobj.setHidden(currentHidden);});}}
handler._created(newobj,kw.postCreation,sourceNode,ind);return newobj;},linkSourceNode:function(newobj,sourceNode,kw){if(sourceNode){if(newobj.domNode){sourceNode.widget=newobj;}else{sourceNode.domNode=newobj;}
newobj.sourceNode=sourceNode;}},createHtmlElement:function(domnode,attributes,kw,sourceNode){var innerHTML=objectPop(attributes,'innerHTML');if((innerHTML==undefined)&&sourceNode){var template=objectPop(attributes,'template');if(template){objectPop(attributes,'datasource');innerHTML=dataTemplate(sourceNode.getAttributeFromDatasource('template'),sourceNode,sourceNode.attr.datasource);}else{innerHTML=sourceNode.getValue();innerHTML=(innerHTML instanceof gnr.GnrBag)?null:innerHTML;}}
if(kw._style){domnode.style.cssText=kw._style;}
if(kw._class){genro.dom.addClass(domnode,kw._class);}
if('disabled'in attributes){if(attributes.disabled){attributes['disabled']='disabled';}
else{delete attributes['disabled'];}}
if(kw.readonly){attributes['readonly']='readonly';}
for(var oneattr in attributes){var vattr=attributes[oneattr];if((vattr===null||vattr===undefined)&&oneattr=='value'){vattr='';}
domnode.setAttribute(oneattr,vattr);}
if(innerHTML!=undefined){domnode.innerHTML=innerHTML;}
return domnode;},getWidgetFactory:function(tag,handler){var dojotag=this.namespace[(handler._dojotag||tag).toLowerCase()];var wdgpath;if(!dojotag){wdgpath=handler._dojotag.split('.');}else{dojotag=dojotag[1];var requires=this.widgetcatalog[dojotag];if(stringContains(requires,':')){requires=requires.split(':');wdgpath=requires[1].split('.');requires=requires[0].split(',');}
else{requires=requires.split(',');wdgpath=requires[0].split('.');wdgpath[wdgpath.length-1]=dojotag;}
for(var i=0;i<requires.length;i++){dojo.require(requires[i]);}}
var wdgfactory=window;for(var i=0;i<wdgpath.length;i++){wdgfactory=wdgfactory[wdgpath[i]];}
return wdgfactory;},createDojoWidget:function(tag,domnode,attributes,kw,sourceNode){var handler=this.getHandler(tag);var wdgFactory=this.getWidgetFactory(tag,handler);var kw=kw||{};if(kw._style){attributes['style']=kw._style;}
if(kw._class){attributes['class']=kw._class;}
var proto=wdgFactory.prototype;objectPop(attributes,'format');for(var attr in attributes){if(attr in proto){if(typeof(proto[attr])=='function'){attributes[attr]=funcCreate(attributes[attr]);}}}
var attrmixins=objectExtract(handler,'attributes_mixin_*',true);var dojoAttributes=objectExtract(handler,'dojo_*',true);var validations=objectExtract(attributes,'validate_*');var extracted=objectExtract(attributes,'_*',{'_type':null,'_identifier':null});objectUpdate(attributes,attrmixins);objectUpdate(attributes,dojoAttributes);var newobj=handler.createDojoWidget(wdgFactory,attributes,domnode,sourceNode);if(kw.readonly){var field=dojo.byId(newobj.id);field.readOnly=true;field.style.cursor='default';dojo.connect(field,'onfocus',function(){field.blur();});}
if(objectNotEmpty(validations)||handler._validatingWidget){sourceNode.setValidations();this.setIsValidMethod(newobj);dojo.connect(newobj,'onFocus',function(e){var errormessage=sourceNode.getValidationError();var warnings=sourceNode.getValidationWarnings();if(errormessage){setTimeout(function(){sourceNode.widget.displayMessage(errormessage);},1);}else if(warnings&&warnings.length>0){warnings=warnings.join('<br />');setTimeout(function(){sourceNode.widget.displayMessage(warnings);},1);}});}
this.doMixin(newobj,handler,tag,sourceNode);return newobj;},setIsValidMethod:function(obj){if(obj.isValid){obj.isValid=function(isFocused){if(isFocused){this.sourceNode.editing=true;return true;}else{if(this.sourceNode.editing){this.sourceNode.editing=false;if(this.gnr._validatingWidget){}else{return true;}}
return!this.sourceNode.hasValidationError();}};}},doMixin:function(obj,handler,tag,sourceNode){var oldfunc,funcname,prefix,newfunc;var versionpatch='versionpatch_'+dojo.version.major+dojo.version.minor+'_';var ispatch;for(var prop in handler){funcname=null;if(prop.indexOf('mixin_')==0){ispatch=false;funcname=prop.replace('mixin_','');}
else if(stringStartsWith(prop,'versionpatch_')){ispatch=true;if(stringStartsWith(prop,versionpatch)){funcname=prop.replace(versionpatch,'');}}
else if(stringStartsWith(prop,'patch_')){ispatch=true;funcname=prop.replace('patch_','');}else if(stringStartsWith(prop,'nodemixin_')){sourceNode[prop.replace('nodemixin_','')]=handler[prop];}else if(stringStartsWith(prop,'validatemixin_')){if(sourceNode&&(sourceNode.hasValidations())){sourceNode[prop.replace('validatemixin_','')]=handler[prop];}}
if(funcname){oldfunc=obj[funcname];if(ispatch){obj[funcname]=handler[prop];if(oldfunc){obj[funcname+'_replaced']=oldfunc;}else if((!handler._basedojotag)||(handler._dojotag==handler._basedojotag)){genro.warning(tag+' - Patch '+prop+': cannot find the replaced method.');}}else{if(oldfunc){genro.warning(tag+' - Mixin '+prop+': method already existing.');obj[funcname+'_replaced']=oldfunc;}
obj[funcname]=handler[prop];}}}
return obj;},filterEvent:function(e,modifiers,validclass){modifiers=modifiers?modifiers.toLowerCase():modifiers;var result=false;var target=e.target;if(validclass){if(!target.className||(target.className&&dojo.every(validclass.split(','),function(item){return target.className.indexOf(item)<0;}))){target=null;}}
if(target){var modif=(modifiers||"").replace('*','')||'';var moddict={'shiftKey':'shift','ctrlKey':'ctrl','altKey':'alt','metaKey':'meta'};for(var c in moddict){if(e[c]){if(modif.indexOf(moddict[c])<0){return false;}
modif=modif.replace(moddict[c],'');}}
modif=modif.replace(/,/g,'').replace(/ /g,'');if(modif==''){result=true;}}
return result;}});dojo.declare("gnr.RowEditor",null,{constructor:function(gridEditor,rowNode){this.gridEditor=gridEditor;this.grid=this.gridEditor.grid;rowNode.attr._pkey=rowNode.attr._pkey||rowNode.label;var row=this.grid.rowFromBagNode(rowNode,true);this.rowId=this.grid.rowIdentity(row);this._pkey=rowNode.attr._pkey;this.original_values=objectUpdate({},row);this.newrecord=rowNode.attr._newrecord;this.rowLabel=rowNode.label;rowNode._rowEditor=this;this.grid.currRenderedRowIndex=this.grid.storebag().index(this.rowLabel);var data=rowNode.getValue();if(data){data.clearBackRef();this.inititializeData(data);data.setBackRef(rowNode,rowNode._parentbag);}else{this.inititializeData();rowNode.setValue(this.data);}},replaceData:function(newdata,reason){var rowNode=this.data.getParentNode();rowNode.setValue(newdata,reason);this.data=newdata;},inititializeData:function(data){data=data||new gnr.GnrBag();this.data=data;var cellmap=this.grid.cellmap;default_kwargs=objectUpdate({},this.gridEditor.editorPars.default_kwargs);var k;for(k in cellmap){objectPop(default_kwargs,k);var kw={dtype:cellmap[k].dtype};var wdg_dtype=data.getAttr(k,'wdg_dtype');if(!kw.dtype&&wdg_dtype){kw.dtype=wdg_dtype;kw.wdg_dtype=wdg_dtype;}
data.setItem(k,this.original_values[k],kw);}
if(this.newrecord){for(k in default_kwargs){data.setItem(k,this.original_values[k]);}
this.checkNotNull();}},checkNotNull:function(){var cellmap=this.grid.cellmap;var data=this.data;var n,err,v;this.grid.currRenderedRowIndex=this.grid.storebag().index(this.rowLabel);for(var k in cellmap){var cell=cellmap[k];var editpars=cell.edit;if(this.grid.sourceNode.currentFromDatasource(cell.editDisabled)){continue;}
if(editpars&&editpars!==true){editpars=this.grid.sourceNode.evaluateOnNode(editpars);if('validate_notnull'in editpars){n=data.getNode(k);if(editpars.validate_notnull){err=editpars.validate_notnull_error||'not null';v=n.getValue();if(isNullOrBlank(v)){n.attr._validationError=err;}else if(n.attr._validationError==err){delete n.attr._validationError;}}else{delete n.attr._validationError;}}}}},hasChanges:function(){var changed=false;if(this.newrecord){return true}
if(this.data.getNodeByAttr('_loadedValue')){changed=true;}
return changed;},getChangeset:function(){if(this.hasChanges()){return this.data.deepCopy()}},getErrors:function(){var errors={};this.data.forEach(function(n){if(n.attr._validationError){errors[n.label]=n.attr._validationError;}});if(objectNotEmpty(errors)){return errors;}
return null;},endEditCell:function(editingInfo){this.grid.currRenderedRowIndex=this.grid.storebag().index(this.rowLabel);this.checkNotNull();this.gridEditor.updateStatus();this.gridEditor.lastEditTs=new Date();this.currentCol=null;if(this.grid.pendingSort){this.grid.refreshSort();}},startEditCell:function(colname){this.currentCol=colname;this.gridEditor.lastEditTs=null;this.gridEditor.updateStatus();},deleteRowEditor:function(){var rowIndex=this.grid.indexByRowAttr('_pkey',this.rowId);if(rowIndex>=0){this.grid.updateRow(rowIndex);}
var rowNode=this.data.getParentNode();if(this.grid.datamode!='bag'&&rowNode){rowNode.clearValue();delete rowNode._rowEditor;}},checkRowEditor:function(){var rowIndex=this.grid.indexByRowAttr('_pkey',this.rowId);if(rowIndex>=0){this.grid.updateRow(rowIndex);}}});dojo.declare("gnr.GridEditor",null,{constructor:function(grid){this.grid=grid;var that=this;var sourceNode=grid.sourceNode;sourceNode.subscribe('duplicateCommand',function(e){if(that.enabled()){grid.addRows(null,e,true);}});this.viewId=sourceNode.attr.nodeId;this.table=sourceNode.attr.table;this.editorPars=objectUpdate({},sourceNode.attr.gridEditorPars);this.autoSave=this.editorPars.autoSave||false;if(this.autoSave===true){this.autoSave=3000;}
this.remoteRowController=sourceNode.attr.remoteRowController;this.remoteRowController_default=sourceNode.attr.remoteRowController_default;if(this.remoteRowController_default){var caller_kw={'script':"this.getParentNode().widget.gridEditor.callRemoteControllerBatch('*')",'_delay':500,'_userChanges':true};objectUpdate(caller_kw,this.remoteRowController_default);sourceNode._('dataController','remoteRowController_default_caller',caller_kw);}
this.status={};this.columns={};this.formId=sourceNode.getInheritedAttributes()['formId'];this.deletedRows=new gnr.GnrBag()
this._status_list=['error','changed'];this.grid.rows.isOver=function(inRowIndex){return((this.overRow==inRowIndex)&&!grid.gnrediting);};this.grid.selection.isSelected=function(inRowIndex){return this.selected[inRowIndex]&&!grid.gnrediting;};var sourceNodeContent=sourceNode.getValue();var gridEditorNode=sourceNodeContent.getNodeByAttr('tag','grideditor',true);this.widgetRootNode=sourceNodeContent.getNode('_grideditor_',null,true);if(gridEditorNode){console.warn('legacy mode: use new grid and edit attribute in cell instead of this way')
var gridEditorColumns=gridEditorNode.getValue();var attr;gridEditorColumns.forEach(function(node){attr=objectUpdate({},node.attr);genro.assert(attr.gridcell,"Missing gridcell parameter");that.addEditColumn(attr.gridcell,attr);});gridEditorNode.setValue(null,false);gridEditorNode.attr.tag=null;}else{if(sourceNode.form&&sourceNode.attr.parentForm!==false){sourceNode.form.registerGridEditor(sourceNode.attr.nodeId,this);}
sourceNode.subscribe('onNewDatastore',function(){that.resetEditor();});sourceNode.subscribe('saveChangedRows',function(){that.saveChangedRows();});if(this.autoSave){var autoSave=this.autoSave;this.widgetRootNode.watch('autoSave',function(){if(that.grid.sourceNode.form&&that.grid.sourceNode.form.isNewRecord()){return false;}
if(that.lastEditTs){if((new Date()-that.lastEditTs)>autoSave){that.lastEditTs=null;if(that.grid.sourceNode.form&&that.grid.sourceNode.form.opStatus){return;}
that.saveChangedRows();}}
return false;},function(){},500);}}
this.applyStorepath();var _this=this;if(genro.isMobile){sourceNode.subscribe('doubletap',function(info){var e=info.event;if(_this.enabled()&&_this.editableCell(e.cellIndex,e.rowIndex,true)&&!grid.gnrediting){_this.startEdit(e.rowIndex,e.cellIndex,e.dispatch);}})}else{var editOn=this.widgetRootNode.attr.editOn||'onCellDblClick';editOn=stringSplit(editOn,',',2);var modifier=editOn[1];dojo.connect(grid,editOn[0],function(e){if(genro.wdg.filterEvent(e,modifier)){if(_this.enabled()&&_this.editableCell(e.cellIndex,e.rowIndex,true)&&!grid.gnrediting){e.stopPropagation();e.preventDefault();_this.startEdit(e.rowIndex,e.cellIndex,e.dispatch);}}});}},applyStorepath:function(){var sourceNode=this.grid.sourceNode;var absStorepath=sourceNode.absDatapath(sourceNode.attr.storepath)
if(sourceNode.form&&sourceNode.attr.parentForm!==false){this.storeInForm=sourceNode.attr.storeInForm||absStorepath.indexOf(sourceNode.form.sourceNode.absDatapath(sourceNode.form.formDatapath))==0}
this.widgetRootNode.attr.datapath=absStorepath;},batchAssign:function(){var fields=[];var editable_cols=this.columns;this.grid.getColumnInfo().keys().forEach(function(f){var c=editable_cols[f];if(!c){return;}
if(c.attr.batch_assign){var wdgkw=objectUpdate({lbl:c.attr.original_name,value:'^.'+c.attr.field},c.attr);objectExtract(wdgkw,'selectedSetter,selectedCb')
fields.push(wdgkw);}});var grid=this.grid;var promptkw={widget:fields,action:function(result){grid.getSelectedRowidx().forEach(function(idx){result.forEach(function(node){grid.gridEditor.setCellValue(idx,node.label,node.getValue());});});}};genro.dlg.prompt(_T('Multi assigment'),promptkw);},onFormatCell:function(cell,inRowIndex,renderedRow){if(this.invalidCell(cell,inRowIndex)){cell.customClasses.push('invalidCell');}
if(renderedRow._newrecord&&this.grid.sourceNode.attr.table&&this.grid.sourceNode.form&&this.grid.sourceNode.form.store&&!this.grid.sourceNode.form.store.autoSave){cell.customClasses.push('newRowCell');}},resetEditor:function(){this.deletedRows=new gnr.GnrBag();this.updateStatus(true);},updateStatus:function(reset){var status;if(!reset){status=this.deletedRows.len()>0?'changed':null;var store=this.grid.collectionStore();if(store.hasErrors()){status='error';}else if(store.hasChanges()){status='changed';}}
this.status[this.grid.sourceNode.attr.storepath]=status;var viewNode=genro.getFrameNode(this.grid.sourceNode.attr.frameCode);dojo.forEach(this._status_list,function(st){genro.dom.setClass(viewNode,'editGrid_'+st,st==status);});this.grid.sourceNode.setRelativeData('.editor.status',status);if(this.grid.sourceNode.form){this.grid.sourceNode.form.updateStatus();}},addEditColumn:function(colname,colattr){colattr['parentForm']=false;var edit=objectPop(colattr,'edit');objectPop(colattr,'width');if(edit!==true){colattr=objectUpdate(colattr,edit);}
if(!('tag'in colattr)){var dt=colattr['dtype'];var widgets={'L':'NumberTextBox','I':'NumberTextBox','D':'DateTextbox','DH':'DatetimeTextbox','R':'NumberTextBox','N':'NumberTextBox','H':'TimeTextBox','B':'CheckBox'};colattr['tag']=widgets[dt]||'Textbox';if('related_table'in colattr){colattr['tag']='dbselect';colattr['dbtable']=colattr['related_table'];if(colattr['related_table_lookup']){colattr['hasDownArrow']=true;}}if('values'in colattr){colattr['tag']=colattr.values.indexOf(':')>=0?'filteringselect':'combobox';}}
var lowertag=colattr['tag'].toLowerCase();var wdghandler=genro.wdg.getHandler(colattr['tag']);wdghandler.cell_onCreating(this,colname,colattr);this.columns[colname.replace(/\W/g,'_')]={'tag':colattr.tag,'attr':colattr};},delEditColumn:function(colname){objectPop(this.columns,colname.replace(/\W/g,'_'));},enabled:function(){var gridSourceNode=this.grid.sourceNode;var form=gridSourceNode.form;var gridstore=this.grid.collectionStore?this.grid.collectionStore():null;if(gridstore){return!gridstore.locked;}
if(form&&form.store){return!form.isDisabled();}else{return'editorEnabled'in gridSourceNode.attr?this.grid.editorEnabled:true;}},onEditCell:function(start,rowIdx,cellIdx){var grid=this.grid;grid.gnrediting=start;genro.dom.setClass(grid.sourceNode,'editingGrid',start);grid.sourceNode.publish('onEditCell',{editing:start,rowIdx:rowIdx,cellIdx:cellIdx});grid.updateRowStyles(rowIdx)
grid.currentEditedRow=start?rowIdx:null;dojo.setSelectable(grid.domNode,grid.gnrediting);},invalidCell:function(cell,row){var rowNode=this.grid.dataNodeByIndex(row);if(!rowNode){console.log('missing rowNode');return;}
var rowData=rowNode.getValue('static');if(rowData){var datanode=rowData.getNode(cell.field);return datanode?datanode.attr._validationError:false;}},onSavedChangedRows:function(changeset,result){var that=this;var grid=this.grid;var updated=changeset.getItem('updated');var inserted=changeset.getItem('inserted');if(updated){updated.forEach(function(n){var rowId=n.attr.rowId;var rowEditor=grid.getRowEditor({rowId:rowId});if(rowEditor){rowEditor.deleteRowEditor();}});}
if(inserted){inserted.forEach(function(n){var rowId=n.attr.rowId;var rowEditor=grid.getRowEditor({rowId:rowId});if(rowEditor){rowEditor.deleteRowEditor();}});}
var insertedRows=result.getItem('insertedRecords');if(insertedRows){insertedRows.forEach(function(n){var r=that.grid.storebag().getNode(n.attr.rowId);r.attr._pkey=n.getValue();r._value=null;r.label=n.label;delete r.attr._newrecord;});}
this.resetEditor();this.grid.sourceNode.publish('savedRows');this.updateStatus();},saveChangedRows:function(){var that=this;var changeset=this.getChangeset(true);var sourceNode=this.grid.sourceNode;if(changeset.len()>0){that.grid.updateRowCount();genro.serverCall(that.editorPars.saveMethod,{table:that.table,changeset:changeset,_sourceNode:sourceNode},function(result){that.onSavedChangedRows(changeset,result);});}},getChangeset:function(sendingStatus){var changeset=new gnr.GnrBag();var collectionStore=this.grid.collectionStore();if(collectionStore.pendingLoading){return changeset;}
collectionStore.getData().forEach(function(n){var rowEditor=n._rowEditor;if(rowEditor&&rowEditor.hasChanges()){var cannotSave=this.autoSave&&(rowEditor.getErrors()||rowEditor.currentCol);if(!cannotSave){var prefix=rowEditor.newrecord?'inserted.':'updated.';changeset.setItem(prefix+'#id',rowEditor.getChangeset(),{_pkey:rowEditor.newrecord?null:rowEditor._pkey,rowId:rowEditor.rowId});rowEditor.sendingStatus=sendingStatus;}}});var deletedRows=new gnr.GnrBag();this.deletedRows.forEach(function(n){deletedRows.setItem('#id',null,{_pkey:n.attr._pkey});});if(deletedRows.len()>0){var unlinkfield=collectionStore.unlinkdict?collectionStore.unlinkdict.field:null;changeset.setItem('deleted',deletedRows,{unlinkfield:unlinkfield});}
return changeset;},deleteSelectedRows:function(pkeys,protectPkeys){if(pkeys=='*'){pkeys=this.grid.getAllPkeys();}
var existingPkeys=[];var that=this;var grid=this.grid;var storebag=this.grid.storebag();dojo.forEach(pkeys,function(n){var rowEditor=grid.getRowEditor({rowId:n});if(rowEditor&&rowEditor.newrecord){var rowLabel=rowEditor.rowLabel;rowEditor.deleteRowEditor();storebag.popNode(rowLabel);}else if(!isNullOrBlank(n)){existingPkeys.push(n);}});if(existingPkeys.length>0){if(this.autoSave){var that=this;this.grid.collectionStore().deleteAsk(existingPkeys,protectPkeys,function(){that.markDeleted(pkeys)});}else{this.markDeleted(existingPkeys);}}},markDeleted:function(pkeys){var that=this;var grid=this.grid;var storebag=this.grid.storebag();dojo.forEach(pkeys,function(pkey){var node=grid.rowBagNodeByIdentifier(pkey);node=storebag.popNode(node.label);that.deletedRows.setItem(node.label,node);var rowEditor=node._rowEditor;if(rowEditor){rowEditor.deleteRowEditor();}});if(this.autoSave&&pkeys&&pkeys.length>0){this.lastEditTs=new Date();}
this.grid.updateCounterColumn();if(this.storeInForm){var n=storebag.getParentNode().attributeOwnerNode('dtype','X');if(n){n.attr._sendback=true;}}
this.updateStatus();},getNewRowDefaults:function(externalDefaults){var editorDefaults=this.editorPars.default_kwargs;if(typeof(editorDefaults)=='function'){editorDefaults=editorDefaults.call();}
var default_kwargs=objectUpdate({},(editorDefaults||{}));if(externalDefaults){default_kwargs=objectUpdate(default_kwargs,externalDefaults);}
var result=this.widgetRootNode.evaluateOnNode(default_kwargs);var cellmap=this.grid.cellmap;var queries=new gnr.GnrBag();var rcol,hcols;for(var k in cellmap){var cmap=cellmap[k];if(cmap.related_table){rcol=cmap.relating_column;if(result[rcol]){hcols=[];for(var j in cellmap){if(cellmap[j].relating_column==rcol&&result[cellmap[j].field_getter]===undefined){hcols.push(cellmap[j].related_column);}}
if(hcols.length>0){queries.setItem(rcol,null,{table:cellmap[rcol].related_table,columns:hcols.join(','),pkey:result[rcol],where:'$pkey =:pkey'});}}}}
if(queries.len()>0){var sourceNode=this.grid.sourceNode;var remoteDefaults=genro.serverCall('app.getMultiFetch',{'queries':queries,_sourceNode:sourceNode},null,null,'POST');var node,keyAttr;for(var k in cellmap){rcol=cellmap[k].relating_column;if(rcol){node=remoteDefaults.getNode(rcol+'.#0');keyAttr=cellmap[k].related_column.replace(/\W/g,'_');if(node&&keyAttr in node.attr){result[cellmap[k].field_getter]=node.attr[keyAttr];}}}}
return result;},startEditRemote:function(n,colname,rowIndex){var rowData=n.getValue();var rowId=this.grid.rowIdByIndex(rowIndex);if(!rowId&&n.attr._newrecord){rowId=n.attr._pkey=n.label;}
var rowEditor=this.grid.getRowEditor({rowId:rowId});if(!rowEditor){rowEditor=this.newRowEditor(n);if(rowEditor.newrecord){this.grid.updateRow(rowIndex);}}
if(rowEditor.sendingStatus){return;}
var rowData=rowEditor.data;if(rowData.index(colname)<0){rowData.setItem(colname,n.attr[colname],{_loadedValue:n.attr[colname]});}
rowEditor.startEditCell(colname);return rowId;},newRowEditor:function(rowNode){var rowEditor=new gnr.RowEditor(this,rowNode);return rowEditor;},addNewRows:function(rows){var that=this;dojo.forEach(rows,function(n){that.addNewRows_one(n);});this.updateStatus();this.grid.collectionStore().sort();this.grid.updateRowCount();this.lastEditTs=new Date()},addNewRows_one:function(row){var grid=this.grid;var label='#id';if(grid.rowIdentity(row)){label=flattenString(grid.rowIdentity(row),['.',' '])}
var newnode=grid.addBagRow(label,'*',grid.newBagRow(row));this.newRowEditor(newnode);},updateRowFromRemote:function(rowId,value){var rowEditor=this.grid.getRowEditor({rowId:rowId});if(!rowEditor){rowEditor=this.newRowEditor(this.grid.rowBagNodeByIdentifier(rowId));}
if(this.grid.datamode=='bag'){rowEditor.replaceData(value,'remoteController');}else{var row_attributes=value.pop('_row_attributes');if(row_attributes){rowEditor.data.getParentNode().updAttributes(row_attributes,false);}
rowEditor.data.update(value,null,'remoteController');}
rowEditor.checkNotNull();rowEditor.checkRowEditor();},callRemoteControllerBatch:function(rows,kw){var that=this;kw=kw||objectUpdate({},this.remoteRowController_default);if(rows=='*'){rows=this.grid.storebag().deepCopy();}
var result=genro.serverCall('remoteRowControllerBatch',objectUpdate(kw,{handlerName:this.remoteRowController,rows:rows,_sourceNode:this.grid.sourceNode}));var grid=this.grid;result.forEach(function(n){that.updateRowFromRemote(grid.rowIdentity(grid.rowFromBagNode(n))||n.label,n.getValue());},'static');this.updateStatus();this.grid.sourceNode.publish('remoteRowControllerDone',{result:result})
return result},callRemoteController:function(rowNode,field,oldvalue,batchmode){var rowId=this.grid.rowIdentity(this.grid.rowFromBagNode(rowNode))||rowNode.label;var field_kw=field?this.grid.cellmap[field]['edit']['remoteRowController']:{};var kw=objectUpdate({},this.remoteRowController_default);objectUpdate(kw,field_kw)
if(batchmode){this._pendingRemoteController=this._pendingRemoteController||[];this._pendingRemoteController.push(rowId);genro.callAfter(function(){var rows=new gnr.GnrBag();var store=this.grid.storebag();this._pendingRemoteController.forEach(function(l){var n=store.getNode(l);if(n){rows.setItem(n.label,n.getValue(),objectUpdate({},n.attr));}});var result=this.callRemoteControllerBatch(rows,kw);this._pendingRemoteController=null;this.grid.sourceNode.publish('remoteRowControllerDone',{result:result});},1,this,'callRemoteControllerBatch_'+this.grid.sourceNode._id);return;}
var that=this;var row=rowNode.getValue().deepCopy();objectUpdate(kw,{field:field,row:row,row_attr:objectUpdate({},rowNode.attr)});kw['_sourceNode']=this.grid.sourceNode;var result=genro.serverCall(this.remoteRowController,kw);this.updateRowFromRemote(rowId,result);this.updateStatus()
var editingWidgetNode=this.widgetRootNode._value?this.widgetRootNode._value.getNode('cellWidget'):null;if(editingWidgetNode){var widget=editingWidgetNode.widget||editingWidgetNode.externalWidget;if(widget._focused){widget.cellNext='RIGHT';widget.focusNode.blur();}else if(widget.focusManager&&widget.focusManager.hasFocus){widget.cellNext='RIGHT';widget.focusManager.blur();}}
this.grid.sourceNode.publish('remoteRowControllerDone',{result:result})},updateRow:function(rowNode,updkw){var row=this.grid.rowFromBagNode(rowNode,true);var rowEditor=this.grid.getRowEditor({row:row});if(!rowEditor){rowEditor=this.newRowEditor(rowNode);}
for(var k in updkw){if(k in this.grid.cellmap){var rowData=rowEditor.data;var m=this.grid.cellmap[k];if(rowData.index(k)<0){rowData.setItem(k,row[k],{_loadedValue:row[k]});}
rowData.setItem(k,updkw[k]);}}
this.lastEditTs=new Date();this.updateStatus();},copyFromCellAbove:function(sourceNode){if(sourceNode.editedRowIndex>0){sourceNode.widget.setValue(this.getCellValue(sourceNode.editedRowIndex-1,sourceNode.attr.field),true);}},getCellValue:function(rowIdx,cellname){return this.grid.rowByIndex(rowIdx,true)[cellname];},setCellValue:function(rowIdxOrNode,cellname,value,valueCaption){var grid=this.grid;var rowNode=typeof(rowIdxOrNode)=='number'?grid.dataNodeByIndex(rowIdxOrNode):rowIdxOrNode;var row=grid.rowFromBagNode(rowNode,true);var rowEditor=this.grid.getRowEditor({row:row});if(!rowEditor){rowEditor=this.newRowEditor(rowNode);}
var cellmap=this.grid.cellmap;genro.assert(cellname in cellmap,'cell '+cellname,+' does not exist');var cell=cellmap[cellname];if(cell.edit||cell.counter||cell.isCheckBoxCell){var n=rowEditor.data.setItem(cellname,value);delete n.attr._validationError
this.updateStatus();this.lastEditTs=new Date();}
var newAttr={};newAttr[cellname]=value;var rtable=cell.related_table;if(!valueCaption&&cell.field!=cell.field_getter&&rtable){var queries=new gnr.GnrBag();var hcols=[cell.related_column];var selectedKw=objectExtract(cell.edit,'selected_*',true);if(objectNotEmpty(selectedKw)){hcols=hcols.concat(objectKeys(selectedKw));}
queries.setItem(cellname,null,{table:rtable,columns:hcols.join(','),pkey:value,where:'$pkey =:pkey'});var r=genro.serverCall('app.getMultiFetch',{'queries':queries},null,null,'POST');var rnode=r.getNode('#0.#0');var kw=rnode?rnode.attr:{};valueCaption=objectPop(kw,cell.related_column);for(var selected in selectedKw){var p=selectedKw[selected].split('.');p=p[p.length-1];this.setCellValue(rowNode,p,kw[selected]);}}if(valueCaption!=undefined){newAttr[cell.field_getter]=valueCaption}
this.grid.collectionStore().updateRowNode(rowNode,newAttr);},updateCounterColumn:function(rowNode,k,counterField){var row=this.grid.rowFromBagNode(rowNode);if(row[counterField]!=k){this.setCellValue(k-1,counterField,k);}},startEdit:function(row,col,dispatch){var grid=this.grid;var cell=grid.getCell(col);var colname=cell.field;var fldDict=this.columns[colname];var gridcell=fldDict.attr.gridcell||colname;var rowDataNode=grid.dataNodeByIndex(row);if(rowDataNode&&rowDataNode.attr._is_readonly_row){return;}
var datachanged=false;var editedRowId=null;if(rowDataNode&&rowDataNode._resolver&&rowDataNode._resolver.expired()){datachanged=true;}
editedRowId=this.startEditRemote(rowDataNode,colname,row);if(!editedRowId){return;}
this.widgetRootNode.form=null;var rowData=rowDataNode.getValue();var cellDataNode=rowData.getNode(gridcell);if(!cellDataNode){datachanged=true;cellDataNode=rowData.getNode(gridcell,null,true);}
else if(cellDataNode._resolver&&cellDataNode._resolver.expired()){datachanged=true;cellDataNode.getValue();}
if(datachanged){setTimeout(dojo.hitch(this,'startEdit',row,col),1);return;}
if(cellDataNode.attr._editable===false){return;}
var rowLabel=rowDataNode.label;var cellNode=cell.getNode(row);if(!cellNode){grid.scrollToRow(row);cellNode=cell.getNode(row);}
var attr=objectUpdate({},fldDict.attr);objectExtract(attr,'editDisabled,editLazy,hidden');var lastRenderedRowIndex=grid.currRenderedRowIndex;grid.currRenderedRowIndex=row;attr=grid.sourceNode.evaluateOnNode(attr,function(path){return path.indexOf('#ROW')>=0});var remote=fldDict.attr.remote;if('fields'in attr||'contentCb'in attr||remote){var fields=attr.fields;if(typeof(fields)=='string'){fields=funcApply(fields,{rowDataNode:rowDataNode,grid:grid},this);}
if(attr.mode=='dialog'||remote){var currdata;if(attr.rowEdit==true){currdata=rowData.deepCopy();}else{currdata=rowDataNode.getValue().getItem(attr.field);}
var that=this;var promptkw={widget:attr.contentCb||attr.fields,dflt:currdata?currdata.deepCopy():null,mandatory:attr.validate_notnull,action:function(result){if(attr.rowTemplate){rowData.update(result);}else{that.setCellValue(row,attr.field,result);}}};if(remote){var remotekw=objectExtract(fldDict.attr,'remote_*',true,true)
remotekw.remote=remote;objectUpdate(promptkw,remotekw);}
var dlgkw=objectExtract(fldDict.attr,'dlg_*',true,true);objectUpdate(promptkw,dlgkw);genro.dlg.prompt(attr.original_name||attr.field,promptkw,grid.sourceNode);}else{var rowpath=this.widgetRootNode.absDatapath('.'+rowLabel);genro.dlg.quickTooltipPane({datapath:rowpath,fields:attr.fields,domNode:cellNode,modal:attr.modal},funcCreate(attr.contentCb,'pane,kw',grid.sourceNode),{rowDataNode:rowDataNode,grid:grid,cell:cell});}
return}
if(attr.editOnOpening&&funcApply(attr.editOnOpening,{rowIndex:row,field:attr.field,rowData:rowData,cellNode:cellNode},this)===false){return;}
grid.currRenderedRowIndex=lastRenderedRowIndex;grid.selection.select(grid.currRenderedRowIndex);attr.datapath=this.widgetRootNode.absDatapath('.'+rowLabel);attr.width=attr.width||(cellNode.clientWidth-10)+'px';if(attr.tag.toLowerCase()=='checkbox'){attr.margin_left=((cellNode.clientWidth-10-16)/2)+'px';attr.margin_top='1px';}
if('value'in attr){if(attr.tag.toLowerCase()=='dbselect'){attr.selectedCaption='.'+gridcell;}}
else{attr['value']='^.'+gridcell;}
if(this.viewId){if(attr.exclude==true){attr.exclude='==genro.wdgById("'+this.viewId+'").getColumnValues("'+attr['value']+'")';}};var editingInfo={'cellNode':cellNode,'contentText':cellNode.innerHTML,'row':row,'col':col,'editedRowId':editedRowId};cellNode.innerHTML=null;var cbKeys=function(e){var keyCode=e.keyCode;var keys=genro.PATCHED_KEYS;var widget=this.widget||this.externalWidget;if((keyCode==keys.SHIFT)||(keyCode==keys.CTRL)||(keyCode==keys.ALT)){return;}
if(keyCode==keys.TAB){widget.cellNext=e.shiftKey?'LEFT':'RIGHT';}
if((e.shiftKey)&&((keyCode==keys.UP_ARROW)||(keyCode==keys.DOWN_ARROW)||(keyCode==keys.LEFT_ARROW)||(keyCode==keys.RIGHT_ARROW))){if(keyCode==keys.UP_ARROW){widget.cellNext='UP';}else if(keyCode==keys.DOWN_ARROW){widget.cellNext='DOWN';}else if(keyCode==keys.LEFT_ARROW){widget.cellNext='LEFT';}else if(keyCode==keys.RIGHT_ARROW){widget.cellNext='RIGHT';}
dojo.stopEvent(e);if(widget.focusManager){widget.focusManager.blur();}else{widget.focusNode.blur();}}};var gridEditor=this;var cbBlur=function(e){var widget=this.widget||this.externalWidget;var deltaDict={'UP':{'r':-1,'c':0},'DOWN':{'r':1,'c':0},'LEFT':{'r':0,'c':-1},'RIGHT':{'r':0,'c':1},'STAY':{'r':0,'c':0}};var cellNext=widget.cellNext;widget.cellNext=null;if(dojo.isSafari&&widget&&widget.focusNode&&widget.focusNode.type=='checkbox'){if(genro._lastMouseEvent.mousedown.target===widget.focusNode){widget.focus();return;}}
setTimeout(function(){gridEditor.endEdit(widget,deltaDict[cellNext],editingInfo);},1);};attr._parentDomNode=cellNode;attr._class=attr._class?attr._class+' widgetInCell':'widgetInCell';attr.connect_keydown=cbKeys;attr.connect_onBlur=cbBlur;attr._autoselect=true;attr._inGridEditor=true;var wdgtag=fldDict.tag;if(cellDataNode.attr.wdg_dtype||!wdgtag&&attr.autoWdg){var dt=cellDataNode.attr.wdg_dtype||convertToText(cellDataNode.getValue())[0];wdgtag={'L':'NumberTextBox','I':'NumberTextBox','D':'DateTextbox','R':'NumberTextBox','N':'NumberTextBox','H':'TimeTextBox','B':'CheckBox'}[dt]||'Textbox';attr.tag=wdgtag;}
this.onEditCell(true,row,col);var editWidgetNode=this.widgetRootNode._(wdgtag,'cellWidget',attr).getParentNode();editWidgetNode.setCellValue=function(cellname,value,valueCaption){gridEditor.setCellValue(this.editedRowIndex,cellname,value,valueCaption);};editWidgetNode.editedRowIndex=row;if(cellDataNode.attr._validationError||cellDataNode.attr._validationWarnings){editWidgetNode._validations={'error':cellDataNode.attr._validationError,'warnings':cellDataNode.attr._validationWarnings};editWidgetNode.updateValidationStatus();}
if(editWidgetNode.widget&&editWidgetNode.widget.focus){editWidgetNode.widget.focus();}
editWidgetNode.grid=gridEditor.grid;},endEdit:function(blurredWidget,delta,editingInfo){var cellNode=editingInfo.cellNode;var contentText=editingInfo.contentText;var editWidgetNode=this.widgetRootNode._value.getNode('cellWidget');var that=this;editWidgetNode.watch('waiting_rpc',function(){return!(editWidgetNode._waiting_rpc||editWidgetNode._exitValidation);},function(){var h=editWidgetNode.widget||editWidgetNode.gnrwdg||editWidgetNode.domNode;h.gnr.cell_onDestroying(editWidgetNode,that,editingInfo);editWidgetNode._destroy();editingInfo.cellNode.innerHTML=contentText;that.onEditCell(false,editingInfo.row,editingInfo.col);if(editingInfo.editedRowId){var rowEditor=that.grid.getRowEditor({rowId:editingInfo.editedRowId});if(rowEditor){rowEditor.endEditCell(editingInfo);that.grid.currRenderedRowIndex=null;that.grid.updateRow(editingInfo.row);}}
if(delta){var rc=that.findNextEditableCell({row:editingInfo.row,col:editingInfo.col},delta);if(rc){that.startEdit(rc.row,rc.col);}}});},editableCell:function(col,row,clicked){var cell=this.grid.getCell(col);if(!(cell.field in this.columns)){return false;}
if((cell.classes||'').indexOf('hiddenColumn')>=0){return false}
this.grid.currRenderedRowIndex=row;var rowdict=this.grid.rowByIndex(row);if(rowdict._is_readonly_row){return false;}
if(this.grid.sourceNode.currentFromDatasource(cell.editDisabled)){return false;}else if(clicked){return true;}else if(this.grid.sourceNode.currentFromDatasource(cell.editLazy)){var editpars=cell.edit==true?{}:this.grid.sourceNode.evaluateOnNode(cell.edit);return(editpars.validate_notnull&&this.grid.rowByIndex(row)[cell.field]===null);}else{return true;}},onExternalChange:function(pkey){var rowEditor=this.grid.getRowEditor({rowId:pkey});if(rowEditor){rowEditor.checkRowEditor();}
this.updateStatus();},statusColGetter:function(rowdata,idx){var statusClass='rowEditorStatus_noedit';var rowId=this.grid.rowIdentity(rowdata);var rowEditor=this.grid.getRowEditor({rowId:rowId});if(rowEditor){if(rowEditor.sendingStatus){statusClass='waiting16';}else if(rowEditor.getErrors()){statusClass='redLight';}else if(rowEditor.hasChanges()){statusClass='yellowLight';}}
return'<div class="'+statusClass+'"></div>'},findNextEditableCell:function(rc,delta){var row=rc.row;var col=rc.col;var grid=this.grid;do{col=col+delta.c;if(col>=grid.layout.cellCount){col=0;row=row+1;}
if(col<0){col=grid.layout.cellCount-1;row=row-1;}
row=row+delta.r;if((row>=grid.rowCount)||(row<0)){return;}}while(!this.editableCell(col,row));rc.col=col;rc.row=row;return rc;}});dojo.declare("gnr.GridFilterManager",null,{constructor:function(grid){this.grid=grid;},filterset:function(){return this.grid.sourceNode.getRelativeData('.filterset');},isInFilterSet:function(row){var gridNode=this.grid.sourceNode;var cb_attr,cb;return this.activeFilters().some(function(kw){cb_attr=gridNode.evaluateOnNode(kw.cb_attr);objectUpdate(cb_attr,row);for(var k in gridNode.widget.cellmap){cb_attr[k]=cb_attr[k]||null;}
return funcApply("return "+kw.cb,cb_attr,gridNode);});},activeFilters:function(){var result=[];var fn;this.filterset().forEach(function(n){var data=n.getValue().getItem('data');var current=n.getValue().getItem('current');if(!(current&&data&&data.len())){return;}
current.split(',').forEach(function(f){fn=data.getNode(f);if(!fn){console.error('missing filter',n.label+'.'+f)}
if(fn.attr.cb){result.push({cb:fn.attr.cb,cb_attr:objectExtract(fn.attr,'cb_*',true)})}});});return result;},hasActiveFilter:function(){return this.activeFilters().length>0;}});dojo.declare("gnr.GridChangeManager",null,{constructor:function(grid){this.grid=grid;this.sourceNode=grid.sourceNode;this.initialize();var that=this;this.sourceNode.subscribe('onNewDatastore',function(){that.grid.storebag().subscribe('rowLogger',{'upd':dojo.hitch(that,"triggerUPD"),'ins':dojo.hitch(that,"triggerINS"),'del':dojo.hitch(that,"triggerDEL")});that.resolveCalculatedColumns();that.resolveTotalizeColumns();});this.sourceNode.subscribe('onSetStructpath',function(){this.delayedCall(function(){if(that.grid.storebag()){that.resolveCalculatedColumns();that.resolveTotalizeColumns();}},1,'resolveCalculatedColumns')});},initialize:function(){this.formulaColumns={};this.totalizeColumns={};this.triggeredColumns={};this.remoteControllerColumns={};this.sourceNode.unregisterSubscription('cellpars');this.cellpars={};},resolveCalculatedColumns:function(){var cellmap=this.grid.cellmap;for(var k in this.formulaColumns){if(cellmap[k].calculated){this.recalculateOneFormula(k);}}},resolveTotalizeColumns:function(){for(var k in this.totalizeColumns){this.updateTotalizer(k);}},calculateFilteredTotals:function(){var filteredStore;var selectedIdx=this.grid.getSelectedRowidx();if(selectedIdx.length>1){filteredStore=new gnr.GnrBag();this.grid.getSelectedNodes().forEach(function(n){filteredStore.setItem(n.label,n._value,n.attr);});}else if(this.grid.isFiltered()){filteredStore=this.grid.storebag(true);}else{this.sourceNode.setRelativeData('.filtered_totalize',null);return}
var filtered_totalize=new gnr.GnrBag();for(let k in this.totalizeColumns){var totvalue=filteredStore.sum(this.grid.datamode=='bag'?k:'#a.'+k);filtered_totalize.setItem(k,totvalue);}
this.sourceNode.setRelativeData('.filtered_totalize',filtered_totalize);},updateTotalizer:function(k){var storebag=this.grid.storebag();var storeattr=storebag.getParentNode().attr;var _serverTotalizeColumns=this.grid.sourceNode._serverTotalizeColumns||{};if((k in _serverTotalizeColumns)&&!isNullOrBlank(storeattr['sum_'+k])){return;}
var totvalue=this.grid.storebag().sum(this.grid.datamode=='bag'?k:'#a.'+k);totvalue=Math.round10(totvalue);this.sourceNode.setRelativeData(this.grid.cellmap[k].totalize,totvalue);this.sourceNode.publish('onUpdateTotalize',{'column':k,'value':totvalue});},recalculateOneFormula:function(key){var that=this;var isBagMode=this.grid.datamode=='bag';this.grid.storebag().walk(function(n){if('pageIdx'in n.attr){return;}
that.calculateFormula(key,n);},'static',null,isBagMode);},addRemoteControllerColumn:function(field,kw){this.remoteControllerColumns[field]=true;},addFormulaColumn:function(field,kw){var cellmap=this.grid.cellmap;var formula=kw.formula;var re,par,dependencies;if(field in this.formulaColumns){this.delFormulaColumn(field);}
for(var k in cellmap){par=cellmap[k].field;re=new RegExp('\\b'+par+'\\b');if(formula.match(re)){dependencies=this.triggeredColumns[par];if(!dependencies){dependencies={}
this.triggeredColumns[par]=dependencies;}
dependencies[field]=true;}}
this.formulaColumns[field]=formula;},delFormulaColumn:function(field){for(var p in this.triggeredColumns){delete this.triggeredColumns[p][field];}
delete this.formulaColumns[field];},addTotalizer:function(field,kw){this.totalizeColumns[field]=kw.totalize;},delTotalizer:function(field,kw){delete this.totalizeColumns[field];},calculateFormula:function(formulaKey,rowNode){var formula=this.formulaColumns[formulaKey];var result;var pars=this.grid.rowFromBagNode(rowNode,true);if(formula.startsWith("+=")||formula.startsWith("%=")){var masterField=formula.slice(2).trim();var store=this.grid.collectionStore();if(!masterField){return;}
if(formula.startsWith("+=")){let idx=store.getIdxFromPkey(pars._pkey);let prev_row_value=idx<=0?0:Math.round10((store.rowByIndex(idx-1)[formulaKey]||0));formula=prev_row_value+' + '+masterField;}else if(formula.startsWith("%=")){let masterTotal=store.sum(masterField);if(masterTotal instanceof dojo.Deferred){}else{formula='Math.round10('+masterField+'/'+masterTotal+' * 100)';}}}
var cellmap=this.grid.cellmap;pars._currcell=cellmap[formulaKey];pars._rowNode=rowNode;for(var cl in cellmap){pars[cl]=pars[cl];}
var struct=this.grid.structBag.getItem('#0.#0');var bagcellattr=struct.getNode(cellmap[formulaKey]._nodelabel).attr;var dynPars=objectExtract(bagcellattr,'formula_*',true);dynPars=this.sourceNode.evaluateOnNode(dynPars);objectUpdate(pars,dynPars);var values={};if(formula=='#'){result=rowNode.attr.rowidx||this.grid.currRenderedRowIndex;}else{try{result=funcApply('return '+formula,pars,this.sourceNode);}catch(e){result=null;}}
values[formulaKey]=result;this.grid.collectionStore().updateRowNode(rowNode,values);},registerParameters:function(){if(objectNotEmpty(this.cellpars)){this.sourceNode.registerSubscription('_trigger_data',this,this.onDataChange,'cellpars');}},onDataChange:function(kw){var dpath=kw.pathlist.slice(1).join('.');var struct=this.grid.structBag.getItem('#0.#0');var cellmap=this.grid.cellmap;var rebuildStructure=false;for(var p in this.cellpars){var trigger_reason=this.sourceNode.getTriggerReason(this.sourceNode.absDatapath(p),kw);if(trigger_reason&&trigger_reason!='child'){for(var f in this.cellpars[p]){var reasons=this.cellpars[p][f];for(var reason in reasons){if(reason.indexOf('formula_')==0){if(f in this.formulaColumns){this.recalculateOneFormula(f);}}else if(reason.indexOf('condition_')==0){console.log('condition');}else{rebuildStructure=true;}}}}}
if(rebuildStructure){var grid=this.grid;this.sourceNode.delayedCall(function(){grid.setStructpath();},1);}},addDynamicCellPar:function(cell,parname,parpath){var dependences=this.cellpars[parpath];if(!dependences){dependences={};this.cellpars[parpath]=dependences;}
dependences[cell.field]=dependences[cell.field]||{};dependences[cell.field][parname]=true;},triggerUPD:function(kw){var changedPars={};var k;var rowNode;var idx;var sourceNode=this.sourceNode;var that=this;if(kw.updvalue&&kw.value instanceof gnr.GnrBag){var storeNode=this.grid.storebag().getParentNode();var parent_lv=kw.node.parentshipLevel(storeNode);if(parent_lv<2){if(kw.reason=='remoteController'){sourceNode.delayedCall(function(){that.resolveCalculatedColumns();that.resolveTotalizeColumns();},1,'resolveCalculatedColumns')}
return;}}
if(kw.updvalue&&this.grid.datamode=='bag'){var l=kw.node.label;if(l in this.triggeredColumns){changedPars[l]=true;}
rowNode=kw.node.getParentBag().getParentNode();if(l in this.totalizeColumns){this.updateTotalizer(l);}}else if(kw.updattr){rowNode=kw.node;var newattr=kw.node.attr;var oldattr=kw.oldattr;for(k in newattr){if((k in this.triggeredColumns)&&(newattr[k]!=oldattr[k])){changedPars[k]=true;}
if(k in this.totalizeColumns){this.updateTotalizer(k);}}}
if(objectNotEmpty(changedPars)){var toRecalculate={};for(k in changedPars){for(var f in this.triggeredColumns[k]){toRecalculate[f]=true;}}
for(k in toRecalculate){this.calculateFormula(k,rowNode);}}
if(kw.updvalue){var gridEditor=this.grid.gridEditor;var cell=this.grid.cellmap[kw.node.label];if(kw.value!=kw.oldvalue&&gridEditor&&((kw.node.label in gridEditor.columns)||(cell&&(cell.counter||cell.isCheckBoxCell)))){var attr=kw.node.attr;if(!('_loadedValue'in attr)){if(kw.oldvalue instanceof gnr.GnrBag){attr['_loadedValue']=kw.oldvalue.deepCopy()}else{attr['_loadedValue']=kw.oldvalue;}}else if(attr._loadedValue==kw.value||(isNullOrBlank(kw.value)&&isNullOrBlank(attr._loadedValue))){delete attr._loadedValue;}}
if(kw.reason!='remoteController'&&kw.node.label in this.remoteControllerColumns){this.grid.sourceNode.delayedCall(function(){gridEditor.callRemoteController(kw.node.getParentNode(),kw.node.label,kw.oldvalue);that.resolveCalculatedColumns();that.resolveTotalizeColumns();},1,'afterRemoteController')}}},triggerINS:function(kw){if(kw.reason=='remoteController'){return;}
var storeNode=this.grid.storebag().getParentNode();var parent_lv=kw.node.parentshipLevel(storeNode);var gridEditor=this.grid.gridEditor;if(gridEditor&&parent_lv<2){var rowEditor=this.grid.getRowEditor({rowId:kw.node.label});if(!rowEditor){rowEditor=gridEditor.newRowEditor(kw.node);if(gridEditor.remoteRowController&&rowEditor.data.getItem(this.grid.masterEditColumn())!==null){gridEditor.callRemoteController(kw.node,null,null,true);}}}
this.resolveTotalizeColumns();this.resolveCalculatedColumns();},triggerDEL:function(kw){this.resolveTotalizeColumns();if(this.grid.gridEditor){this.grid.gridEditor.updateStatus();}}});



dojo.declare("gnr.GnrSrcHandler",null,{constructor:function(application){this.application=application;this._main=new gnr.GnrDomSource();this._main.application=this.application;this._main.setBackRef();this._main.subscribe('sourceTriggers',{'any':dojo.hitch(this,"nodeTrigger")});this._subscribedNodes={};this._started=false;this._index={};this._deletingNodeContent=0;this.pendingBuild=[];this.afterBuildCalls=[];this.building=false;this.datatags={'data':null,'dataformula':null,'datascript':null,'datarpc':null,'dataremote':null,'datacontroller':null};this.layouttags={'contentpane':null,'bordercontainer':null,'stackcontainer':null,'tabcontainer':null,'accordioncontainer':null,'newincludedview':null,'framepane':null};this.highlightedNode=null;},getMainSource:function(cb){return genro.rpc.remoteCall('main',objectUpdate({timeout:50000},genro.startArgs),'bag',null,null,cb);},updatePageSource:function(nodeId){nodeId=nodeId||'_pageRoot';this.getMainSource(function(newpage){var newcontent=newpage._value.getNodeByAttr('nodeId',nodeId);genro.nodeById(nodeId).mergeRemoteContent(newcontent.getValue());});},highlightNode:function(sourceNode){if(typeof(sourceNode)=='string'){sourceNode=this.sourceRoot.getValue().getNode(sourceNode);}
if(this.highlightedNode){domnode=this.highlightedNode.getDomNode();if(domnode){genro.dom.removeClass(domnode,'gnrhighlight');}}
this.highlightedNode=sourceNode;if(sourceNode){domnode=this.highlightedNode.getDomNode();if(domnode){genro.dom.addClass(domnode,'gnrhighlight');}}},onBuiltCall:function(cb,delay){if(delay){delay=typeof(delay)=='number'?delay:1;}
this.afterBuildCalls.push(delay?function(){setTimeout(cb,delay);}:cb);},nodeTrigger:function(kw){if(kw.node.isFreezed()||kw.node._isBuilding){return;}
this.pendingBuild.push(kw);if(!this.building){this.building=true;while(this.pendingBuild.length>0){kw=this.pendingBuild.pop();dojo.hitch(this,'_trigger_'+kw.evt)(kw);}
this.building=false;}},_trigger_ins:function(kw){if(kw.reason=='autocreate'){return;}
var node=kw.node;var where=objectPop(node.attr,'_parentDomNode');if(!where){var wherenode=kw.where.getParentNode();if(wherenode){where=wherenode.widget||wherenode.domNode;if(!where){console.error('Missing destination node in trigger_ins',kw);}}else{where=dojo.byId(genro.domRootName);node.domNode=where;}}
var ind=kw.ind;this.buildNode(node,where,ind);if(where.onChangedContent){where.onChangedContent(node);}
else if(where._checkIfSingleChild){where._checkIfSingleChild();where.resize();}},_trigger_upd:function(kw){var updatingNode=kw.node;genro.assert(!updatingNode._isComponentNode);updatingNode._onDeleting();if(updatingNode.externalWidget&&updatingNode.externalWidget.destroy){updatingNode.externalWidget.destroy();}
var destination=kw.node.getParentBuiltObj();if(!destination){console.log('missing destination in rebuild');}
this._onDeletingContent(kw.oldvalue);var domNode=kw.node.getDomNode();var newNode=document.createElement('div');var widget=kw.node.widget;var ind=-1;var selectedIndex=null;if(widget){if(widget.sizeShare){kw.node.attr.sizeShare=widget.sizeShare;}
if(destination.getChildren){var children=destination.getChildren();ind=children.indexOf(widget);if(destination.getSelectedIndex){selectedIndex=destination.getSelectedIndex();}
if('removeChild'in destination){destination.removeChild(widget);}
this.widgetDestroyAndUnlink(widget);}else if(destination._singleChild){destination.destroyDescendants();}
else{this.widgetDestroyAndUnlink(widget);if(domNode.parentNode){domNode.parentNode.replaceChild(newNode,domNode);}}}else{if(domNode.parentNode){domNode.parentNode.replaceChild(newNode,domNode);ind=newNode;}
var widgets=dojo.query('[widgetId]',domNode);while(widgets.length>0){widgets=widgets.map(dijit.byNode);this.widgetDestroyAndUnlink(widgets[0]);widgets=dojo.query('[widgetId]',domNode);}
while(domNode.childNodes.length>0){dojo._destroyElement(domNode.childNodes[0]);}}
this.refreshSourceIndexAndSubscribers();if(!kw.node._value){return;}
this.buildNode(kw.node,destination,ind);if(destination._checkIfSingleChild){destination._checkIfSingleChild();}
if(selectedIndex){destination.setSelected(selectedIndex);}},widgetDestroyAndUnlink:function(widget){var sourceNode=widget.sourceNode;if(sourceNode){delete sourceNode.widget;}
widget.domNode=widget.domNode||{};widget.destroyRecursive();},_onDeletingContent:function(oldvalue){if(oldvalue instanceof gnr.GnrBag){oldvalue.walk(function(n){if(n._onDeleting){n._onDeleting();}},'static');}},_trigger_del:function(kw){var deletingNode=kw.node;deletingNode._onDeleting();if(deletingNode._isComponentNode){this.deleteNodeContent(deletingNode);}else{this._onDeletingContent(deletingNode._value);this.deleteChildrenExternalWidget(deletingNode);var widget=deletingNode.widget;var domNode=deletingNode.domNode;var externalWidget=deletingNode.externalWidget;if(widget){var parentWdg=widget.getParent?widget.getParent():null;if(parentWdg&&parentWdg.onDestroyingChild){parentWdg.onDestroyingChild(widget);}
if(!widget.containerNode){if(deletingNode._value&&deletingNode._value.len()>0){this.deleteDomNodeContent(widget.domNode);}}
this.widgetDestroyAndUnlink(widget);}else if(domNode){this.deleteDomNodeContent(domNode);}else if(deletingNode.externalWidget){deletingNode.externalWidget.destroy();}}
this.refreshSourceIndexAndSubscribers();},deleteChildrenExternalWidget:function(deletingNode){if(deletingNode._value&&deletingNode._value.len()>0){deletingNode._value.walk(function(n){if(n.externalWidget&&n.externalWidget.destroy){n.externalWidget.destroy();}},'static');}},deleteDomNodeContent:function(domNode){var widgets=dojo.query('[widgetId]',domNode);widgets=widgets.map(dijit.byNode);var that=this;dojo.forEach(widgets,function(widget){that.widgetDestroyAndUnlink(widget);});dojo._destroyElement(domNode);},deleteNodeContent:function(sourceNode){var children=sourceNode._value;this._deletingNodeContent=this._deletingNodeContent+1;children.forEach(function(n){children.popNode(n.label);})
this._deletingNodeContent=this._deletingNodeContent-1;},buildNode:function(sourceNode,where,ind){this.formsToUpdate={};this.afterBuildCalls=[];sourceNode.build(where,ind);var cb;while(this.afterBuildCalls.length>0){cb=this.afterBuildCalls.pop();cb.call();}
if(genro._pageStarted){for(var formId in this.formsToUpdate){var form=this.formsToUpdate[formId];form.applyDisabledStatus();}}},getSource:function(path){if(path){return this._main.getItem('main.'+path);}
else{return this._main.getItem('main');}},getNode:function(obj,autocreate){autocreate=autocreate===false?false:true;if(!obj){return this._main.getNode('main');}
if(typeof(obj)=='string'){if(obj.indexOf('main.')!=0){obj='main.'+obj;}
return this._main.getNode(obj,false,autocreate);}
if(obj.declaredClass=='gnr.GnrDomSourceNode'){return obj;}
if(obj.sourceNode){return obj.sourceNode;}
if(obj.target){return obj.target.sourceNode||dijit.getEnclosingWidget(obj.target).sourceNode;}},nodeBySourceNodeId:function(identifier){return this._main.findNodeById(identifier);},newRoot:function(){return new gnr.GnrDomSource();},setSource:function(path,value,attributes,kw){if(!attributes&&(value instanceof gnr.GnrDomSource)){value=value.getNodes()[0];}
this._main.setItem('main.'+path,value,attributes,kw);},delSource:function(path){this._main.delItem('main.'+path);},startUp:function(source){this._main.setItem('main',source);this.sourceRoot=source;this._started=true;},setInRootContainer:function(label,item){alert('removed : setInRootContainer in genro_src');},enclosingSourceNode:function(item){if(item.sourceNode){return item.sourceNode;}
if(item.widget){var widget=item.widget;}else{var widget=dijit.getEnclosingWidget(item);}
if(widget){if(widget.sourceNode){return widget.sourceNode;}else{return genro.src.enclosingSourceNode(widget.domNode.parentNode);}}},onEventCall:function(e,code,kw){var sourceNode=genro.src.enclosingSourceNode(e.target);var func=funcCreate(code,'kw,e',sourceNode);func(kw,e);dojo.stopEvent(e);},checkSubscribedNodes:function(){var subscribedNodes=this._subscribedNodes;for(var strid in subscribedNodes){var srcnode=genro.src._main.findNodeById(strid.slice(2));console.log(strid,srcnode,srcnode.getParentNode())}
return;},refreshSourceIndexAndSubscribers:function(){if(this._deletingNodeContent>0){return;}
var oldSubscribedNodes=this._subscribedNodes;var oldIndex=this._index;this._index={};this._subscribedNodes={};var refresher=dojo.hitch(this,function(n){var id=n.getStringId();var oldSubscriber=oldSubscribedNodes[id];if(oldSubscriber){genro.src._subscribedNodes[id]=oldSubscriber;oldSubscribedNodes[id]=null;}
if(n.attr.nodeId){if(!(n.attr.nodeId in oldIndex)){return;}
genro.src._index[n.attr.nodeId]=n;}});this._main.walk(refresher,'static');for(var subscriber in oldSubscribedNodes){if(oldSubscribedNodes[subscriber]){for(var attr in oldSubscribedNodes[subscriber]){dojo.forEach(oldSubscribedNodes[subscriber][attr],function(n){dojo.unsubscribe(n);});}}}},stripData:function(node){this.stripDataNode(node);var content=node.getValue('static');if(content instanceof gnr.GnrDomSource){content.forEach(function(node){genro.src.stripDataNode(node);},'static');}},stripDataNode:function(node){if(node.attr.tag&&!node._alreadyStripped){if(node.attr.tag.toLowerCase()in genro.src.datatags){this.moveData(node);}
else{var nodeattr=node.attr;var attrvalue;var specialattr={}
var dflt;for(var attr in nodeattr){attrvalue=nodeattr[attr];if((typeof(attrvalue)=='string')&&node.isPointerPath(attrvalue)){if(attr=='value'){dflt=nodeattr['default']||nodeattr['default_value'];}else{dflt=nodeattr['default_'+attr];}
if((typeof(dflt)=='string')&&node.attr.dtype){dflt=convertFromText(dflt,node.attr.dtype);}
var currval=node.getAttributeFromDatasource(attr,true,dflt);if(!isNullOrBlank(dflt)&&isNullOrBlank(currval)){node.setAttributeInDatasource(attr,dflt);}}
if(attr.indexOf('attr_')==0){specialattr[attr.slice(5)]=attrvalue;}}
if(objectNotEmpty(specialattr)){var valuepath=nodeattr['value']||nodeattr['src']||nodeattr['innerHTML'];if(valuepath){var valueNode=genro.getDataNode(node.absDatapath(valuepath));if(valueNode){valueNode.updAttributes(node.evaluateOnNode(specialattr));}}}}}
node._alreadyStripped=true;},moveData:function(node){node._registerNodeId();var attributes=node.registerNodeDynAttr(false);var tag=objectPop(attributes,'tag');var path=objectPop(attributes,'path');var value;if(tag=='data'&&attributes.remote){attributes['method']=objectPop(attributes,'remote');tag='dataRemote';}
if(tag=='data'){path=node.absDatapath(path);value=node.getValue('static');node._value=null;if(value instanceof gnr.GnrBag){value.clearBackRef();}
var serverpath=objectPop(attributes,'serverpath');if(serverpath){genro._serverstore_paths[node.absDatapath(path)]=serverpath;}
var shared_id=objectPop(attributes,'shared_id');if(shared_id){var shared_kw=objectExtract(attributes,'shared_*');setTimeout(function(){genro.som.registerSharedObject(node.absDatapath(path),shared_id,shared_kw);},1);}
if(!genro.getDataNode(path)||(value!==null)){genro.setData(path,value,attributes);}}else if(tag=='dataRemote'){node._dataprovider=tag;var isResolved=objectPop(node.attr,'_resolved');objectPop(attributes,'_resolved');if(isResolved){value=node.getValue('static');path=node.absDatapath(path);node._value=null;node._resolvedValue=value;}
node.setDataNodeValue();}else{var initialize=objectPop(attributes,'_init');node._dataprovider=tag;if(initialize){node.setDataNodeValue();}else{path=node.absDatapath(path);genro.getDataNode(path,true);}
var timing=objectPop(attributes,'_timing');if(timing){node.setTiming(timing);}
var onStart=objectPop(attributes,'_onStart');var onBuilt=objectPop(attributes,'_onBuilt');var subscriptions=objectExtract(attributes,'subscribe_*');var selfsubscriptions=objectExtract(attributes,'selfsubscribe_*');var formsubscriptions=objectExtract(attributes,'formsubscribe_*');var nid=node.attr.nodeId||node.getStringId();for(var selfsubcription in selfsubscriptions){subscriptions[nid+'_'+selfsubcription]=selfsubscriptions[selfsubcription];}
if(objectNotEmpty(formsubscriptions)||node.attr.parentForm){var cb=function(){var form=node.getFormHandler();if(form){node.form=form;var fid=form.formId;var subscriptions={};for(var formsubcription in formsubscriptions){subscriptions['form_'+fid+'_'+formsubcription]=formsubscriptions[formsubcription];}
node._dataControllerSubscription(subscriptions);}};genro.src.afterBuildCalls.push(cb);}
node._dataControllerSubscription(subscriptions);if(onStart){node.attr._fired_onStart='^gnr.onStart';node.registerDynAttr('_fired_onStart');if(typeof(onStart)=="number"&&!node.attr._delay){node.attr._delay=onStart;}}
if(onBuilt){this.onBuiltCall(function(){if(typeof(onBuilt)=='number'){setTimeout(function(){node.setDataNodeValue();},onBuilt);}else{node.setDataNodeValue();}})}}
node._setDynAttributes();},dynamicParameters:function(source,sourceNode){var obj={};var path;if((source!='')&(typeof source=='string')){source=genro.evaluate(source);}
if(source){sourceNode=sourceNode||objectPop(source,'_sourceNode');var formulaProp=[];for(var prop in source){var val=source[prop];if(typeof(val)=='string'&&val.length>1){var dynval=stringStrip(val);var sourceNodeKw=sourceNode?sourceNode.attr:{};var toConvert=((dynval[0]=='=')||(dynval[0]=='^'))&&!((prop in sourceNodeKw)&&(sourceNodeKw[prop]!=dynval));if(toConvert){if(dynval.indexOf('==')==0){formulaProp.push(prop);}else{path=dynval.slice(1);if(sourceNode){path=sourceNode.absDatapath(path);}else{if(path.indexOf('.')==0){throw"Unresolved relative path in dynamicParameters: "+path;}}
val=genro._data.getItem(path);}}}else if(typeof(val)=='function'){val=val();}
obj[prop]=val;}
if(formulaProp.length>0){dojo.forEach(formulaProp,function(prop){obj[prop]=funcApply("return "+stringStrip(source[prop]).slice(2),obj,sourceNode);});}}
return obj;},create:function(widget,pars,path){return genro.src.getNode()._('div',path)._(widget,path,pars);}});



gnr.convertFuncAttribute=function(sourceNode,name,parameters){if(sourceNode.attr[name]&&(typeof(sourceNode.attr[name])=='string')){sourceNode.attr[name]=funcCreate(sourceNode.attr[name],parameters,sourceNode);}};gnr.setOrConnectCb=function(widget,name,cb){if(name in widget){dojo.connect(widget,name,cb);}else{widget[name]=cb;}};gnr.menuFromBag=function(bag,appendTo,menuclass,basepath){var menuline,attributes,newmenu,valuelabel;var bagnodes=bag.getNodes();for(var i=0;i<bagnodes.length;i++){var bagnode=bagnodes[i];attributes=objectUpdate({},bagnode.attr);valuelabel=null;if(typeof(bagnode._value)=='string'){valuelabel=bagnode._value;}
attributes.label=attributes.caption||attributes.label||valuelabel||bagnode.label;attributes.fullpath=basepath?basepath+'.'+bagnode.label:bagnode.label;menuline=appendTo._('menuline',attributes);if(bagnode.getResolver()){newmenu=menuline._('menu',{fullpath:attributes.fullpath,'_class':menuclass,'content':bagnode.getResolver()});}
else{var menucontent=bagnode.getValue();if(menucontent instanceof gnr.GnrBag){newmenu=menuline._('menu',{'_class':menuclass});gnr.menuFromBag(menucontent,newmenu,menuclass,attributes.fullpath);}}}};dojo.declare("gnr.widgets.baseHtml",null,{_defaultValue:'',_defaultEvent:'onclick',constructor:function(application){this._domtag=null;this._dojotag=null;this._dojowidget=false;},connectChangeEvent:function(obj){if('value'in obj){dojo.connect(obj,'onchange',this,'onChanged');}},onChanged:function(evt){var domnode=evt.target;this._doChangeInData(domnode,domnode.sourceNode,domnode.value);},setValueInData:function(sourceNode,value,valueAttr){if(sourceNode.attr_kw){var attr_kw=sourceNode.evaluateOnNode(sourceNode.attr_kw);for(var k in attr_kw){valueAttr[k]=attr_kw[k];}}
var path=sourceNode.attrDatapath('value');valueAttr=valueAttr||{};value=this.onSettingValueInData(sourceNode,value,valueAttr);if(sourceNode.attr.mask||sourceNode.attr.format){var valueToFormat=(typeof(value)=='string'&&'_displayedValue'in valueAttr)?valueAttr['_displayedValue']:value;var formattedValue=genro.formatter.asText(valueToFormat,sourceNode.currentAttributes());this.setFormattedValue(sourceNode,formattedValue);valueAttr['_formattedValue']=formattedValue;}
if('_valuelabel'in sourceNode.attr){valueAttr['_valuelabel']=sourceNode.attr['_valuelabel'];}
if(sourceNode.attr.rejectInvalid&&!sourceNode.widget.isValid()){return;}
genro._data.setItem(path,value,valueAttr,{'doTrigger':sourceNode,lazySet:true});sourceNode.publish('onSetValueInData',value);},onSettingValueInData:function(sourceNode,value,valueAttr){return value;},setFormattedValue:function(sourceNode,formattedValue){return;},_doChangeInData:function(domnode,sourceNode,value,valueAttr){this.setValueInData(sourceNode,value,valueAttr);this.doChangeInData(sourceNode,value,valueAttr);},doChangeInData:function(sourceNode,value,valueAttr){},_makeInteger:function(attributes,proplist){dojo.forEach(proplist,function(prop){if(prop in attributes){attributes[prop]=attributes[prop]/1;}});},onBuilding:function(sourceNode){},_onBuilding:function(sourceNode){if(sourceNode.getParentNode()&&sourceNode.getParentNode().widget&&sourceNode.getParentNode().widget.gnr.onChildBuilding){return sourceNode.getParentNode().widget.gnr.onChildBuilding(sourceNode.getParentNode(),sourceNode);}
var lbl=objectPop(sourceNode.attr,'lbl');if(lbl){var inherited_attr=sourceNode.getInheritedAttributes();var lbl_attr=objectExtract(inherited_attr,'lbl_*');var wrp_attr=objectExtract(inherited_attr,'wrp_*')
var attr=objectUpdate({},sourceNode.attr)
var tag=objectPop(attr,'tag');var moveable=objectPop(attr,'moveable');if(moveable){wrp_attr.moveable=moveable;objectUpdate(wrp_attr,objectExtract(attr,'top,left,position'));lbl_attr.id='handle_'+sourceNode.getStringId()
wrp_attr.moveable_handle=lbl_attr.id;}
var children=sourceNode.getValue();sourceNode._value=null;var side=lbl_attr['side']||'top';sourceNode.attr=objectUpdate({tag:'div',_class:'innerLblWrapper innerLbl_'+side+' innerLblWrapper_widget_'+tag.toLowerCase()},wrp_attr);sourceNode._('div',objectUpdate({innerHTML:lbl,_class:'innerLbl'},lbl_attr),{'doTrigger':false});var c=sourceNode._(tag,attr,{'doTrigger':false});if(children&&children.len()){c.concat(children);}}else{this.onBuilding(sourceNode);}},_creating:function(attributes,sourceNode){var extension=objectPop(attributes,'extension');if(extension){sourceNode[extension]=new gnr.ext[extension](sourceNode);}
this._makeInteger(attributes,['sizeShare','sizerWidth']);var savedAttrs={};if('speech'in attributes){objectPop(attributes,'speech');if(genro.isChrome){savedAttrs['speech']=true;}}
if(attributes.moveable){savedAttrs['moveable']=objectPop(attributes,'moveable');savedAttrs['moveable_kw']=objectExtract(attributes,'moveable_*');}
savedAttrs['touchEvents']=objectPop(attributes,'touchEvents');objectExtract(attributes,'onDrop,onDrag,dragTag,dropTag,dragTypes,dropTypes');objectExtract(attributes,'onDrop_*');savedAttrs['dropTarget']=objectPop(attributes,'dropTarget');savedAttrs['dropTargetCb']=objectPop(attributes,'dropTargetCb');savedAttrs['dropTargetCb_extra']=objectExtract(attributes,'dropTargetCb_*');savedAttrs.connectedMenu=objectPop(attributes,'connectedMenu');savedAttrs.onEnter=objectPop(attributes,'onEnter');savedAttrs._watchOnVisible=objectPop(attributes,'_watchOnVisible');objectUpdate(savedAttrs,this.creating(attributes,sourceNode));var formId=objectPop(attributes,'formId');if(attributes._for){attributes['for']=objectPop(attributes,'_for');}
if(attributes.onShow){attributes['onShow']=funcCreate(attributes.onShow,'console.log("showing")',sourceNode);}
if(attributes.onHide){attributes['onHide']=funcCreate(attributes.onHide,'',sourceNode);}
if(sourceNode&&sourceNode.attr.default_value&&sourceNode.attr.dtype){sourceNode.attr.default_value=convertFromText(sourceNode.attr.default_value,sourceNode.attr.dtype);}
if(sourceNode&&formId){if(sourceNode.attr.nodeId&&(sourceNode.attr.nodeId!=formId)){alert('formId '+formId+' will replace nodeId '+sourceNode.attr.nodeId);}
var controllerPath=objectPop(attributes,'controllerPath');var pkeyPath=objectPop(attributes,'pkeyPath');var formDatapath=objectPop(attributes,'formDatapath')||sourceNode.absDatapath();sourceNode.attr.nodeId=formId;sourceNode.defineForm(formId,formDatapath,controllerPath,pkeyPath,objectExtract(sourceNode.attr,'form_*'));}
if(dojo.isIE>0){if(attributes['colspan']){attributes.colSpan=attributes['colspan'];}}
if(attributes.drawer&&attributes.region){attributes.splitter=true;}
return savedAttrs;},creating:function(attributes,sourceNode){return{};},setControllerTitle:function(attributes,sourceNode){var iconClass=objectPop(attributes,'iconClass');var title=attributes['title'];if(iconClass){if(attributes['title']){attributes['title']='<span class="'+iconClass+'"/><span style="padding-left:20px;">'+attributes['title']+'</span>';}
else if(attributes['title_tip']){attributes['title']='<div class="'+iconClass+'" title="'+attributes['title_tip']+'"/>';}
else{attributes['title']='<div class="'+iconClass+'"/>';}}
if(attributes.title){var tip=objectPop(attributes,'tip')||title||'';attributes.title='<span title="'+tip+'">'+attributes.title+'</span>';}},setDraggable:function(domNode,value){domNode.setAttribute('draggable',value);},setDropTarget:function(domNode,value){domNode.sourceNode.dropTarget=value;},_created:function(newobj,savedAttrs,sourceNode,ind){if(sourceNode){sourceNode.attr_kw=objectExtract(sourceNode.attr,'attr_*',true);}
this.created(newobj,savedAttrs,sourceNode);if(savedAttrs._watchOnVisible){sourceNode.watch('_watchOnVisible',function(){return genro.dom.isVisible(sourceNode);},function(){sourceNode.publish('isVisible');});}
if(this.formattedValueHandler){this.formattedValueHandler(newobj,savedAttrs,sourceNode);}
if('speech'in savedAttrs){if(newobj.focusNode){newobj.focusNode.setAttribute("x-webkit-speech","x-webkit-speech");newobj.focusNode.onwebkitspeechchange=function(){if('onSpeechEnd'in newobj){if(typeof(newobj.onSpeechEnd)=='function'){newobj.onSpeechEnd();}else{newobj.sourceNode.onNodeCall(newobj.onSpeechEnd);}}};}}
var domNode=newobj.domNode||newobj;if('moveable'in savedAttrs){var moveable_kw=savedAttrs.moveable_kw;var constrain=objectPop(moveable_kw,'constrain');genro.src.onBuiltCall(function(){var publishOn;if(constrain===false){sourceNode.mover=new dojo.dnd.Moveable(domNode,moveable_kw);publishOn=genro;}else{dojo.require('dojo.dnd.move');moveable_kw.within=true;sourceNode.mover=new dojo.dnd.move.parentConstrainedMoveable(domNode,moveable_kw);publishOn=sourceNode.getParentNode();}
var coords=dojo.coords(domNode);publishOn.publish('onMoveable',{'action':'created','sourceNode':sourceNode,'top':coords.t+'px','left':coords.l+'px'});dojo.connect(sourceNode.mover,"onMove",function(mover,topLeft){publishOn.publish('onMoveable',{'action':'moved','sourceNode':sourceNode,top:mover.node.style.top,left:mover.node.style.left});});});}
if(savedAttrs.connectedMenu){var menu=savedAttrs.connectedMenu;if(typeof(menu)=='string'){menu=dijit.byId(menu);}
if(menu){menu.bindDomNode(domNode);}}
if(!sourceNode){return;}
if(savedAttrs.dropTargetCb){sourceNode.dropTargetCb=funcCreate(savedAttrs.dropTargetCb,'dropInfo',sourceNode);}
if(savedAttrs.dropTargetCb_extra&&objectNotEmpty(savedAttrs.dropTargetCb_extra)){sourceNode.dropTargetCbExtra={};for(var key in savedAttrs.dropTargetCb_extra){sourceNode.dropTargetCbExtra[key]=funcCreate(savedAttrs.dropTargetCb_extra[key],'dropInfo,data',sourceNode);}}
if(savedAttrs.dropTarget){if(newobj.setDropTarget){newobj.setDropTarget(savedAttrs.dropTarget);}else{newobj.gnr.setDropTarget(newobj,savedAttrs.dropTarget);}};if(savedAttrs.zoomFactor){sourceNode.setZoomFactor(savedAttrs.zoomFactor);}
var draggable=sourceNode.getAttributeFromDatasource('draggable');if(draggable&&'setDraggable'in newobj){newobj.setDraggable(draggable);}
var detachable=sourceNode.getAttributeFromDatasource('detachable');if(detachable){domNode=newobj.domNode||newobj;dojo.connect(domNode,'onmousemove',function(e){if(e.shiftKey){dojo.addClass(domNode,'detachable');}});dojo.connect(domNode,'onmouseout',function(e){dojo.removeClass(domNode,'detachable');});dojo.connect(domNode,'onmousedown',function(e){if(e.shiftKey){dojo.addClass(domNode,'detachable');domNode.draggable=true;}else{domNode.draggable=false;}});dojo.connect(domNode,'onmouseup',function(e){domNode.draggable=false;});}
var parentNode=sourceNode.getParentNode();if(parentNode.attr.tag){var parentTagLower=parentNode.attr.tag.toLowerCase()
if(parentTagLower=='tabcontainer'){objectFuncReplace(newobj,'setTitle',function(title){if(title){if(this.controlButton){this.controlButton.setLabel(title);}}});}
else if(parentTagLower=='accordioncontainer'){objectFuncReplace(newobj,'setTitle',function(title){this.titleTextNode.innerHTML=title;});}
else if(parentTagLower=='stackcontainer'){newobj.setTitle=function(title){return;}}}
if(savedAttrs.onEnter){var callback=savedAttrs.onEnter==true?null:dojo.hitch(sourceNode,funcCreate(savedAttrs.onEnter));var kbhandler=function(evt){if(evt.keyCode==genro.PATCHED_KEYS.ENTER){evt.target.blur();if(callback){setTimeout(callback,100);}}};var domnode=newobj.domNode||newobj;dojo.connect(domnode,'onkeypress',kbhandler);};if(newobj.domNode&&newobj.isFocusable()){dojo.connect(newobj,'onFocus',function(e){genro.setCurrentFocused(newobj);});if(!('onBlur'in sourceNode.attr)){dojo.connect(newobj,'onBlur',function(e){genro.setLastSelection(newobj.focusNode||newobj.domNode);});}}
if(sourceNode.attr.placeholder){var placeholder=sourceNode.getAttributeFromDatasource('placeholder');if(sourceNode.widget){newobj.focusNode.setAttribute('placeholder',placeholder);}else{newobj.setAttribute('placeholder',placeholder);}}
if(newobj.validate){newobj.validate_replaced=newobj.validate;newobj.validate=function(isFocused){if(this._isvalid==false&&this.value){this.sourceNode._validations.error=_T('Invalid');}
var isValid=this.validate_replaced(isFocused);var sourceNode=this.sourceNode;var gridwidget=sourceNode.attr.gridcell;if(sourceNode.form&&!isFocused&&!gridwidget){sourceNode.form.dojoValidation(this,isValid);}
return isValid;};}
if(sourceNode.attr.keepable){this.setKeepable(sourceNode);}
if(sourceNode.getParentNode()&&sourceNode.getParentNode().widget&&sourceNode.getParentNode().widget.gnr.onChildCreated){sourceNode.getParentNode().widget.gnr.onChildCreated(sourceNode.getParentNode(),sourceNode);}},_getKeeperRoot:function(sourceNode){return sourceNode.widget.domNode;},setKeepable:function(sourceNode){genro.dom.addClass(sourceNode.widget.focusNode,'iskeepable');var keeper=document.createElement('div');keeper.setAttribute('title','Keep this value');genro.dom.addClass(keeper,'fieldkeeper');var keeper_in=document.createElement('div');keeper.appendChild(keeper_in);var dn=this._getKeeperRoot(sourceNode);dn.appendChild(keeper);var npath=sourceNode.absDatapath(sourceNode.attr.value);sourceNode.widget.setKeeper=function(v){genro.dom.setClass(dn.parentNode,'keeper_on',v);var n=genro.getDataNode(npath);n.attr._keep=v;if(sourceNode.form){sourceNode.form.setKeptData(npath.replace(sourceNode.absDatapath()+'.',''),n._value,n.attr._keep);}};keeper.onclick=function(e){dojo.stopEvent(e);var n=genro.getDataNode(npath);var currvalue=n.attr._keep;sourceNode.widget.setKeeper(!currvalue);}
sourceNode.subscribe('onSetValueInData',function(value){var n=genro.getDataNode(npath);if(sourceNode.form){sourceNode.form.setKeptData(npath.replace(sourceNode.absDatapath()+'.',''),value,n.attr._keep);}});},onDragStart:function(dragInfo){var event=dragInfo.event;var sourceNode=dragInfo.sourceNode;if('dragValue'in sourceNode.attr){value=sourceNode.currentFromDatasource(sourceNode.attr['dragValue']);}
else if('value'in sourceNode.attr){value=sourceNode.getAttributeFromDatasource('value');}
else if('innerHTML'in sourceNode.attr){value=sourceNode.getAttributeFromDatasource('innerHTML');}
else{value=dragInfo.domnode.innerHTML;}
return{'text/plain':value};},fillDragInfo:function(dragInfo){},fillDropInfo:function(dropInfo){dropInfo.outline=dropInfo.domnode;},setTrashPosition:function(dragInfo){},created:function(newobj,savedAttrs,sourceNode){return null;},cell_onCreating:function(gridEditor,colname,colattr){},cell_onDestroying:function(sourceNode,gridEditor,editingInfo){}});dojo.declare("gnr.widgets.htmliframe",gnr.widgets.baseHtml,{constructor:function(){this._domtag='iframe';},creating:function(attributes,sourceNode){if(!attributes.src){objectPop(attributes,'src');}
var savedAttrs={};savedAttrs['shield']=objectPop(attributes,'shield');savedAttrs['shield_kw']=objectExtract(attributes,'shield_*')||{};savedAttrs['shield_kw']['_class']=(savedAttrs['shield_kw']['_class']||'')+'shield_layer'
return savedAttrs;},created:function(newobj,savedAttrs,sourceNode){if(savedAttrs.shield){var shield_kw=savedAttrs['shield_kw'];shield_kw.z_index=10;shield_kw.opacity=.2;sourceNode.getParentNode().setHiderLayer(true,shield_kw);}
if(genro.isMobile){genro.dom.setAutoSizer(sourceNode,newobj.parentNode,function(w,h){newobj.style.width=w+'px';newobj.contentWindow.postMessage({topic:'setClientWidth',width:w},'*');});dojo.connect(newobj,'onload',function(){newobj.contentWindow.document.body.classList.add('touchDevice');setTimeout(function(){genro.dom.resetAutoSizer(sourceNode);},50);});}if(sourceNode.attr.autoScale){dojo.connect(newobj,'onload',function(){var scalables=newobj.contentWindow.document.getElementsByClassName('gnrAutoScale');for(var i=scalables.length-1;i>=0;i--){genro.dom.setAutoScale(scalables[i],sourceNode.attr.autoScale);};});}},});dojo.declare("gnr.widgets.iframe",gnr.widgets.baseHtml,{_default_ext:'py,png,jpg,jpeg,gif,html,pdf',creating:function(attributes,sourceNode){sourceNode.savedAttrs=objectExtract(attributes,'rowcount,tableid,src,rpcCall,onLoad,autoSize,onStarted,documentClasses,avoidCache,externalSite');objectExtract(attributes,'rpc_*');objectUpdate(sourceNode.savedAttrs,objectExtract(sourceNode.attr,'rpc_*',true,true));var condFunc=objectPop(attributes,'condition_function');var condValue=objectPop(attributes,'condition_value');var onUpdating=objectPop(attributes,'onUpdating');if(onUpdating){sourceNode.attr.onUpdating=funcCreate(onUpdating,'',sourceNode);}
if(condFunc){sourceNode.condition_function=funcCreate(condFunc,'value');}
return sourceNode.savedAttrs;},created:function(newobj,savedAttrs,sourceNode){if(savedAttrs.rowcount&&savedAttrs.tableid){var rowcount=savedAttrs.rowcount;var tableid=savedAttrs.tableid;var fnc=dojo.hitch(newobj,function(){var nlines=0;var tbl=this.contentDocument.getElementById(tableid);if(tbl){nlines=tbl.rows.length;}
genro.setData(rowcount,nlines);});dojo.connect(newobj,'onload',fnc);}
if(savedAttrs.onLoad){dojo.connect(newobj,'onload',funcCreate(savedAttrs.onLoad));}
var mainGenro=genro.mainGenroWindow.genro;dojo.connect(newobj,'onload',function(){var cw=this.contentWindow;try{if(!cw.location.host){return;}}catch(e){console.warn('not loaded frame');return;}
genro.dom.removeClass(this,'waiting');if(this.sourceNode.attr.documentClasses){genro.dom.removeClass(this,'emptyIframe');if(!cw.document.body.innerHTML){genro.dom.addClass(this,'emptyIframe');}}
if(!cw.genro){dojo.connect(cw,'onmouseup',function(e){var currentDnDMover=mainGenro.currentDnDMover;if(currentDnDMover){currentDnDMover.destroy();}});}});if(savedAttrs.onStarted){sourceNode.subscribe('pageStarted',funcCreate(savedAttrs.onStarted));}
if(savedAttrs.documentClasses){genro.dom.addClass(newobj,'emptyIframe');}
sourceNode.reloadIframe=function(delay){genro.callAfter(function(){this.domNode.gnr.setSrc(this.domNode)},delay||200,sourceNode,'reloadingIframe_'+sourceNode._id);};this.setSrc(newobj,savedAttrs.src);dojo.connect(sourceNode,'_onDeleting',function(){newobj.src=null;});},autoSize:function(iframe){console.log('autosize',iframe);},prepareSrc:function(domnode){var sourceNode=domnode.sourceNode;var attributes=sourceNode.attr;if(attributes.src){return sourceNode.getAttributeFromDatasource('src');}else if(attributes.rpcCall){params=sourceNode.evaluateOnNode(objectExtract(sourceNode.savedAttrs,'rpc_*',true));var httpMethod=objectPop(params,'httpMethod');if(httpMethod=='POST'){params._sourceNode=sourceNode;params.resultAs='url';genro.serverCall(attributes.rpcCall,params,function(resultSrc){domnode.src=resultSrc;},null,httpMethod);return null;}else{params.mode=params.mode?params.mode:'text';return genro.remoteUrl(attributes.rpcCall,params,sourceNode,false);}}},set_print:function(domnode,v,kw){genro.dom.iFramePrint(domnode);},set_if:function(domnode,v,kw){domnode.gnr.setSrc(domnode);},setCondition_value:function(domnode,v,kw){domnode.sourceNode.condition_value=v;domnode.gnr.setSrc(domnode);},set_reloader:function(domnode,v,kw){domnode.gnr.setSrc(domnode);},setSrc:function(domnode,v,kw){var that=this;var sourceNode=domnode.sourceNode;sourceNode.rebuild();domnode=sourceNode.domNode;domnode.sourceNode.watch('isVisibile',function(){return genro.dom.isVisible(domnode);},function(){that.setSrc_do(domnode,v,kw);});},setSrc_do:function(domnode,v,kw){var sourceNode=domnode.sourceNode;var attributes=objectUpdate({},sourceNode.attr);var main_call=objectPop(attributes,'main');var main_kwargs=objectExtract(attributes,'main_*')||{};var src_kwargs=objectExtract(attributes,'src_*')||{};objectUpdate(src_kwargs,main_kwargs);if(!sourceNode.savedAttrs.externalSite){src_kwargs._calling_page_id=genro.page_id;}
if(attributes._if&&!sourceNode.getAttributeFromDatasource('_if')){v='';}else if(sourceNode.condition_function&&!sourceNode.condition_function(sourceNode.condition_value)){v='';}
else{v=v||this.prepareSrc(domnode);}
if(main_call){v=v||window.location.pathname;src_kwargs.main_call=main_call;}
if(v){if(sourceNode.attr.documentClasses){genro.dom.removeClass(domnode,'emptyIframe');genro.dom.addClass(domnode,'waiting');}
src_kwargs=sourceNode.evaluateOnNode(src_kwargs);if(sourceNode.savedAttrs.avoidCache){src_kwargs._nocache=genro.time36Id();}
v=genro.addParamsToUrl(v,src_kwargs);v=genro.dom.detectPdfViewer(v,sourceNode.attr.jsPdfViewer);var doset=this.initContentHtml(domnode,v);if(doset){sourceNode.watch('absurlUpdating',function(){var absUrl=document.location.protocol+'//'+document.location.host+v;return absUrl!=domnode.src;},function(){if(domnode.src&&sourceNode.attr.onUpdating){sourceNode.attr.onUpdating();}
domnode.src=v;});}}else{domnode.src='';}},initContentHtml:function(domnode,src){var parsedSrc=parseURL(src);var loadingpath;if(parsedSrc.file&&parsedSrc.file.split('.')[1]&&this._default_ext.indexOf(parsedSrc.file.split('.')[1].toLowerCase())<0){loadingpath=document.location.protocol+'//'+document.location.host+'/_gnr/11/css/icons/download_file.png';domnode.contentWindow.document.body.innerHTML='<a href="'+src+'"><div style="height:100%;width:100%;background:#F6F6F6 url('+loadingpath+') no-repeat center center;"></div></a>';return false;}else if(!parsedSrc.file){domnode.src='';return false;}
genro.dom.addClass(domnode,'waiting');return true;},postMessage:function(sourceNode,message){sourceNode.watch('windowMessageReady',function(){return sourceNode.domNode.contentWindow&&sourceNode.domNode.contentWindow._windowMessageReady;},function(){genro.dom.windowMessage(sourceNode.domNode.contentWindow,message);});}});dojo.declare("gnr.widgets.canvas",gnr.widgets.baseHtml,{creating:function(attributes,sourceNode){var savedAttrs={};return savedAttrs;},created:function(newobj,savedAttrs,sourceNode){sourceNode.savePhoto=function(kw){this.domNode.gnr.savePhoto(sourceNode,kw);};sourceNode.takePhoto=function(video,kw){this.domNode.gnr.takePhoto(sourceNode,video,kw);};if('effect'in sourceNode.attr){genro._PixasticReady='loading'
genro.dom.loadJs('/_rsrc/js_libs/pixastic.js',function(){genro._PixasticReady=true;sourceNode.pixasticEffects=objectKeys(Pixastic.Actions);});sourceNode._currentEffect=sourceNode.getAttributeFromDatasource('effect');}},savePhoto:function(sourceNode,kw){var kw=kw||{};var photo=sourceNode.domNode;var ext=kw.ext||'png';var toDataURLContent="image/"+ext;var data=photo.toDataURL(toDataURLContent);kw=sourceNode.evaluateOnNode(kw);if(kw.uploadPath){this.uploadContent(sourceNode,data,kw)}else{data=data.replace(toDataURLContent,"image/octet-stream");document.location.href=data;}},uploadContent:function(sourceNode,data,kw){if(!kw.filename){genro.dlg.alert("Missing info to upload the image",'Warning');return false;}
genro.rpc.uploadMultipart_oneFile(data,null,{uploadPath:kw.uploadPath,filename:kw.filename,onResult:function(result){var url=this.responseText;}});},setEffect:function(domnode,v,kw){domnode.sourceNode._currentEffect=v;},takePhoto:function(sourceNode,video,kw){var that=this;var kw=kw||{}
var video=genro.dom.getDomNode(video);var canvas=sourceNode.domNode;var context=canvas.getContext('2d');if(kw.mirror){context.translate(canvas.width,0);context.scale(-1,1);}
var ghostcanvas=document.createElement('canvas');ghostcanvas.width=canvas.width;ghostcanvas.height=canvas.height;var imageData;var gctx=ghostcanvas.getContext('2d');if(kw.sync){var draw=function(){requestAnimationFrame(draw);var effect=sourceNode._currentEffect;if(effect&&(effect!='_')){gctx.drawImage(video,0,0,canvas.width,canvas.height);var options={};Pixastic.process(ghostcanvas,effect,options,function(resultcanvas){imageData=resultcanvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);context.putImageData(imageData,0,0);});}else{context.drawImage(video,0,0,canvas.width,canvas.height);}}
draw();}else{context.drawImage(video,0,0,canvas.width,canvas.height);}}});dojo.declare("gnr.widgets.video",gnr.widgets.baseHtml,{creating:function(attributes,sourceNode){objectExtract(attributes,'currentTime,playing,tracks,range_start,range_end');if(!attributes.src){objectPop(attributes,'src')}},created:function(newobj,savedAttrs,sourceNode){if(sourceNode.attr.currentTime||sourceNode.attr.playing){dojo.connect(newobj,'play',function(evt){var d=evt.target;if(d.sourceNode._currentTimeSetter){return;}
d.sourceNode._currentTimeSetter=setInterval(function(){d.gnr.setPlaying(d);if(d.sourceNode.attr.currentTime){d.sourceNode.setAttributeInDatasource('currentTime',Math.round(d.currentTime*10)/10,'player');}},100);});dojo.connect(newobj,'pause',function(evt){var d=evt.target;var sn=d.sourceNode;d.gnr.setPlaying(d);if(sn._currentTimeSetter){clearInterval(sn._currentTimeSetter);delete sn._currentTimeSetter;}});}
sourceNode.startCapture=function(kw){if(objectNotEmpty(kw)){this.domNode.gnr.startCapture(sourceNode,kw);}};sourceNode.takePhoto=function(canvas){if(canvas){this.domNode.gnr.takePhoto(sourceNode,canvas);}};var that=this;newobj.addEventListener("loadedmetadata",function(){that.setTracks(newobj);});},startCapture:function(sourceNode,capture_kw){var onErrorGetUserMedia=objectPop(capture_kw,'onReject');var onAccept=objectPop(capture_kw,'onAccept');var onErr=function(e){if(onErrorGetUserMedia){funcApply(onErrorGetUserMedia,{e:e});}else{genro.dlg.alert('Not allowed video capture '+e,'Error');}};var onOk=function(stream){if(onAccept){funcApply(onAccept,{},sourceNode);}
sourceNode.domNode.src=window.URL?window.URL.createObjectURL(stream):stream;};if(navigator.webkitGetUserMedia){navigator.webkitGetUserMedia(capture_kw,onOk,onErr);}else{navigator.getUserMedia(capture_kw,onOk,onErr);}},setCurrentTime:function(domNode,currentTime,kw){var roundedCT=Math.round(domNode.currentTime*10)/10;var givenCT=Math.round(currentTime*10)/10;if(roundedCT!=givenCT){domNode.currentTime=givenCT;}},setPlaying:function(domNode){var sourceNode=domNode.sourceNode;if(sourceNode.attr.playing){sourceNode.setAttributeInDatasource('playing',!(domNode.paused||domNode.ended));}},addTrack:function(domNode,kw){var track=document.createElement('track');var cue_path=objectPop(kw,'cue_path');kw.label=kw.label||kw.kind+'_'+kw.srclang;kw['src']=dataTemplate(kw['src'],kw);kw['idx']=domNode.textTracks.length;var hidden=objectPop(kw,'hidden');var mode=hidden?'hidden':'showing';if(kw.default===false){objectPop(kw,'default');}else{kw.default=true;}
if(!stringEndsWith(kw['src'],'.vtt')){kw['src']+='.vtt';}
objectExtract(kw,'_*');for(var k in kw){track[k]=kw[k];}
track.addEventListener("load",function(){this.mode=mode;domNode.textTracks[this.idx].mode=mode;domNode.textTracks[this.idx].oncuechange=function(){var cue=this.activeCues[0];if(cue_path&&cue){domNode.sourceNode.setRelativeData(cue_path,new gnr.GnrBag({'id':cue.id,text:cue.text,startTime:cue.startTime,endTime:cue.endTime}));}}});domNode.appendChild(track);},setSrc:function(domNode,src){dojo.forEach(domNode.children,function(c){domNode.removeChild(c)});domNode.setAttribute('src',src);},setTracks:function(domNode){var sn=domNode.sourceNode;var tracks=sn.attr.tracks;dojo.query('track',domNode).forEach(function(dn){domNode.removeChild(dn);})
if(tracks){var that=this;tracks.forEach(function(kw){kw=sn.evaluateOnNode(kw);that.addTrack(domNode,kw);});}},});dojo.declare("gnr.widgets.baseDojo",gnr.widgets.baseHtml,{_defaultEvent:'onClick',constructor:function(application){this._domtag='div';this._dojowidget=true;},createDojoWidget:function(factory,attributes,domnode,sourceNode){if('tabindex'in attributes){attributes['tabIndex']=objectPop(attributes,'tabindex');}
if(this.customizedTemplate){attributes['templateString']=this.customizedTemplate(sourceNode,factory.prototype.templateString);}
return new factory(attributes,domnode);},_doChangeInData:function(domnode,sourceNode,value,valueAttr){if(sourceNode._modifying){return;}
var path=sourceNode.attrDatapath('value');var datanode=genro._data.getNode(path,null,true);var inattr=sourceNode.getInheritedAttributes();if(inattr.blankIsNull!==false){value=value===''?null:value;}
if(datanode.getValue()===value){return;}
objectExtract(valueAttr,'_displayedValue,_formattedValue')
var validateresult;valueAttr=objectUpdate(objectUpdate({},datanode.attr),valueAttr);if(typeof(value)=='string'&&sourceNode._shortcutsDict){value=value.replace(/\b(\w)+\b/gim,function(m){if(m){return sourceNode._shortcutsDict[m]||m;}
return m;});if(sourceNode.widget){sourceNode.widget.setValue(value)}}
if(sourceNode.hasValidations()){validateresult=sourceNode.validationsOnChange(sourceNode,value);value=validateresult['value'];objectExtract(valueAttr,'_validation*');var formHandler=sourceNode.getFormHandler();var fldname=sourceNode.attr._valuelabel||datanode.attr.name_long||datanode.label;if(validateresult['error']){valueAttr._validationError=validateresult['error'];if(validateresult.error&&formHandler){formHandler.publish('message',{message:fldname+': '+validateresult.error,sound:'$onerror',messageType:'error'});}else{genro.publish('floating_message',{message:fldname+': '+validateresult.error,sound:'$onerror',messageType:'error'});return}}
if(validateresult['warnings'].length){if(validateresult.warnings&&formHandler){formHandler.publish('message',{message:fldname+': '+validateresult.warnings.join(','),sound:'$onwarning',messageType:'warning',font_size:'1.1em',font_weight:'bold'});}
valueAttr._validationWarnings=validateresult['warnings'];}}
this.doChangeInData(sourceNode,value,valueAttr);this.setValueInData(sourceNode,value,valueAttr);},mixin_setTip:function(tip){this.setAttribute('title',tip);},mixin_setDraggable:function(value){this.domNode.setAttribute('draggable',value);},mixin_setDropTarget:function(value){this.sourceNode.dropTarget=value;},validatemixin_validationsOnChange:function(sourceNode,value,validateOnly){var result=genro.vld.validate(sourceNode,value,true,validateOnly);if(result['modified']&&!validateOnly){sourceNode._modifying=true;sourceNode.widget.setValue(result['value']);sourceNode._modifying=false;}
sourceNode.setValidationError(result);var formHandler=sourceNode.getFormHandler();if(formHandler){formHandler.updateInvalidField(sourceNode,sourceNode.attrDatapath('value'));}
return result;},connectChangeEvent:function(widget){if('onChange'in widget){dojo.connect(widget,'onChange',dojo.hitch(this,function(val){if(!widget.disabled){this.onChanged(widget,val);}}));}},onChanged:function(widget,value){this._doChangeInData(widget.domNode,widget.sourceNode,value);this.onDataChanged(widget);},onDataChanged:function(widget){},setUrlRemote:function(widget,method,args){var url=genro.rpc.rpcUrl(method,args);widget.setHref(url);},mixin_setVisible:function(visible){dojo.style(this.domNode,'visibility',(visible?'visible':'hidden'));},mixin_setShortcuts:function(shortcuts){this.sourceNode._value.popNode('shortcutsMenu');delete this.sourceNode._shortcutsDict;var shortcutsDict={};var shortcutKeys=[];if(!shortcuts){return;}
if(shortcuts===true){shortcuts=genro.getData('gnr.shortcuts.store');if(!shortcuts||shortcuts.len()==0){return;}}
if(shortcuts instanceof gnr.GnrBag){shortcuts.forEach(function(n){shortcutsDict[n.attr.keycode]=n.attr.phrase;shortcutKeys.push(n.attr.keycode)});}else{var hasKeyCode=shortcuts.indexOf(':')>=0;if(!hasKeyCode){this.sourceNode._('menu','shortcutsMenu',{'_class':'smallmenu',action:"genro.dom.setTextInSelection($2,($1.fullpath.indexOf('caption_')==0?$1.label:$1.fullpath));",values:shortcuts});return;}
shortcutKeys=shortcuts.split(',').map(function(n){return n.split(':')[0]});shortcutsDict=objectFromString(shortcuts);}
var values=new gnr.GnrBag()
var i=0;var tpl='<div style="position:relative; padding-right:60px;">$phrase <div style="position:absolute;right:0;top:0;font-weight:bold;">$keycode</div></div>';shortcutKeys.forEach(function(keycode){values.setItem('r_'+i,null,{caption:dataTemplate(tpl,{keycode:keycode,phrase:shortcutsDict[keycode]}),phrase:shortcutsDict[keycode],keycode:keycode});i++;});if(values.len()){this.sourceNode._('menu','shortcutsMenu',{'_class':'smallmenu',action:"genro.dom.setTextInSelection($2,$1.phrase);",values:values});this.sourceNode._shortcutsDict=shortcutsDict;}},mixin_setHidden:function(hidden){this.sourceNode.setHidden(hidden);},mixin_setSizeShare:function(value){this.sizeShare=value;dijit.byId(this.domNode.parentNode.id).layout();}});dojo.declare("gnr.widgets.Dialog",gnr.widgets.baseDojo,{constructor:function(application){this._attachTo='mainWindow';this._domtag='div';this._dojotag='Dialog';},patch_show:function(cb){this.onShowing();this.show_replaced(cb);genro.callAfter(this.afterShow,1,this,'afterShow_'+this.sourceNode._id);},mixin_afterShow:function(){if(this.sourceNode.attr.autoSize){this.autoSize();}
var ds=genro.dialogStack;var parentDialog=ds.length>1?ds[ds.length-2]:null;this.adjustDialogSize(parentDialog);var that=this;setTimeout(function(){that.resize()},1);},mixin_autoSize:function(){if(this.containerNode.firstChild.scrollWidth>this.containerNode.firstChild.clientWidth){this.containerNode.firstChild.style.width=this.containerNode.firstChild.scrollWidth+'px';}},mixin_onShowing:function(){},mixin_onWindowResize:function(e){this.dialogResize();},mixin_dialogResize:function(parentDialog){this.adjustDialogSize(parentDialog);var ds=genro.dialogStack;if(ds.length>1){var idx=ds.indexOf(this);var childDialog=ds[idx+1];if(childDialog){var that=this;this.sourceNode.delayedCall(function(){childDialog.dialogResize(that);},10);}}},mixin_containerNodeResize:function(){var fc=this.containerNode.firstChild;var c=dojo.coords(this.domNode);var t=dojo.coords(this.titleBar);var innercoords={h:c.h-t.h-2,w:this.containerNode.clientWidth};if(fc.attributes.widgetid){var innerLayout=dijit.getEnclosingWidget(fc);innerLayout.resize(innercoords);if(innerLayout.layout){innerLayout.layout();}}else{fc.style.min_width=innercoords.w+'px';fc.style.min_height=innercoords.h+'px';}},mixin_adjustDialogSize:function(parentDialog){var w={h:Math.floor(window.innerHeight*.98),w:Math.floor(window.innerWidth*.98)};var windowRatio=this.sourceNode.attr.windowRatio;var parentRatio=this.sourceNode.attr.parentRatio;var c=dojo.coords(this.domNode);var doResize=false;var starting;if(parentRatio){w=parentDialog?dojo.coords(parentDialog.domNode):w;c['w']=Math.floor(w.w*parentRatio);c['h']=Math.floor(w.h*parentRatio);doResize=true;}
else if(windowRatio){c['w']=Math.floor(w.w*windowRatio);c['h']=Math.floor(w.h*windowRatio);doResize=true;}else{for(var k in w){starting='_starting_'+k;if(c[k]>w[k]){if(!this[starting]){this[starting]=c[k];}
c[k]=w[k];doResize=true;}else if(this[starting]){if(this[starting]<=w[k]){c[k]=this[starting];delete this[starting];}else{c[k]=w[k];}
doResize=true;}}}
if(doResize){this.resize(c);}
this.layout();},creating:function(attributes,sourceNode){objectPop(attributes,'parentDialog');objectPop(attributes,'centerOn');objectPop(attributes,'position');objectPop(attributes,'autoSize');var closable=('closable'in attributes)?objectPop(attributes,'closable'):false;attributes.title=attributes.title||'';if(!closable){attributes.templateString="<div class=\"dijitDialog\" tabindex=\"-1\" waiRole=\"dialog\" waiState=\"labelledby-${id}_title\">\n\t<div dojoAttachPoint=\"titleBar\" class=\"dijitDialogTitleBar\">\n\t<span dojoAttachPoint=\"titleNode\" class=\"dijitDialogTitle\" id=\"${id}_title\">${title}</span>\n\t</div>\n\t\t<div dojoAttachPoint=\"containerNode\" class=\"dijitDialogPaneContent\"></div>\n</div>\n";}else if(closable!=true){var closeAction;if(closable=='ask'){closeAction='onAskCancel';}else if(closable=='publish'){closeAction='onCancelPublish';}
attributes.templateString="<div class=\"dijitDialog\" tabindex=\"-1\" waiRole=\"dialog\" waiState=\"labelledby-${id}_title\">\n\t<div dojoAttachPoint=\"titleBar\" class=\"dijitDialogTitleBar\">\n\t<span dojoAttachPoint=\"titleNode\" class=\"dijitDialogTitle\" id=\"${id}_title\">${title}</span>\n\t<span dojoAttachPoint=\"closeButtonNode\" class=\"dijitDialogCloseIcon\" dojoAttachEvent=\"onclick: "+closeAction+"\">\n\t\t<span dojoAttachPoint=\"closeText\" class=\"closeText\">x</span>\n\t</span>\n\t</div>\n\t\t<div dojoAttachPoint=\"containerNode\" class=\"dijitDialogPaneContent\"></div>\n</div>\n";sourceNode.closeAttrs=objectExtract(attributes,'close_*');}},created:function(widget,savedAttrs,sourceNode){if(dojo_version=='1.5'){var position=sourceNode.attr.position;if(position){position=position.split(',');widget._relativePosition={x:position[0],y:position[1]};}}
if(dojo_version=='1.1'){var startZindex=800;if(sourceNode.attr.noModal){startZindex=500;}
var ds=genro.dialogStack;dojo.connect(widget,"show",widget,function(){var parentDialog=ds.length>0?ds[ds.length-1]:null;if(this!=ds.slice(-1)[0]){ds.push(this);let zIndex=widget.sourceNode.attr.z_index||(startZindex+ds.length*2);dojo.style(this._underlay.domNode,'zIndex',zIndex);dojo.style(this.domNode,'zIndex',zIndex+1);if(parentDialog){dojo.forEach(parentDialog._modalconnects,dojo.disconnect);parentDialog._modalconnects=[];if(sourceNode.attr.stacked){var parentNodeStyle=parentDialog.domNode.style;dojo.style(this.domNode,'top',(parseInt(parentNodeStyle.top)+16)+'px');dojo.style(this.domNode,'left',(parseInt(parentNodeStyle.left)+16)+'px');}}}
if(!parentDialog&&!this._windowConnectionResize){this._windowConnectionResize=dojo.connect(window,'onresize',widget,'onWindowResize');}});dojo.connect(widget,"hide",widget,function(){if(this==ds.slice(-1)[0]){ds.pop();var parentDialog=ds.length>0?ds[ds.length-1]:null;if(parentDialog){parentDialog._modalconnects.push(dojo.connect(window,"onscroll",parentDialog,"layout"));parentDialog._modalconnects.push(dojo.connect(dojo.doc.documentElement,"onkeypress",parentDialog,"_onKey"));}}
if(this._windowConnectionResize){dojo.disconnect(this._windowConnectionResize);delete this._windowConnectionResize;}});}
genro.dragDropConnect(widget.domNode);if(genro.isDeveloper){genro.dev.inspectConnect(widget.domNode);}
dojo.connect(widget,'resize',widget,'containerNodeResize');},versionpatch_11__onKey:function(){},versionpatch_11__position:function(){var centerOn=this.sourceNode.attr.centerOn;if(genro.isMobile){genro.dom.centerOn(this.domNode,centerOn,null,0);return;}
var xRatio=this.sourceNode.attr.xRatio;var yRatio=this.sourceNode.attr.yRatio;if(centerOn||xRatio||yRatio){centerOn=this.sourceNode.currentFromDatasource(centerOn);genro.dom.centerOn(this.domNode,centerOn,xRatio,yRatio);}else{this._position_replaced();}},attributes_mixin_onAskCancel:function(){var closeAttrs=this.sourceNode.closeAttrs;var _this=this;var closeAction;if(closeAttrs.action){closeAction=dojo.hitch(this.sourceNode,funcCreate(closeAttrs.action));}else{closeAction=dojo.hitch(this,'onCancel');}
genro.dlg.ask('',closeAttrs['msg'],{confirm:closeAttrs['confirm'],cancel:closeAttrs['cancel']},{confirm:closeAction,cancel:''});},attributes_mixin_onCancelPublish:function(event){if(genro.activeForm&&genro.activeForm.currentFocused){genro.activeForm.currentFocused.focusNode.blur();genro.activeForm.currentFocused=null;this.sourceNode.publish('close',{modifiers:genro.dom.getEventModifiers(event)});return;}
this.sourceNode.publish('close',{modifiers:genro.dom.getEventModifiers(event)});},mixin_setTitle:function(title){this.titleNode.innerHTML=title;}});dojo.declare("gnr.widgets.Editor",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='textarea';},creating:function(attributes,sourceNode){dojo.require("dijit._editor.plugins.AlwaysShowToolbar");dojo.require("dijit._editor.plugins.FontChoice");dojo.require("dijit._editor.plugins.TextColor");dojo.require("dijit._editor.plugins.LinkDialog");var extraPlugins=objectPop(attributes,'extraPlugins');var disabled=objectPop(attributes,'disabled');if(extraPlugins){attributes.extraPlugins=extraPlugins.split(',');}},created:function(newobj,savedAttrs,sourceNode){if(sourceNode.attr['disabled']){var disabled=sourceNode.getAttributeFromDatasource('disabled');if(disabled){setTimeout(function(){newobj.setDisabled(true);},10);}};if(sourceNode.attr['value']){var value=sourceNode.getAttributeFromDatasource('value');if(value!=null){newobj.setValue(value);}};}});dojo.declare("gnr.widgets.SimpleTextarea",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='textarea';},onBuilding:function(sourceNode){var areaAttr=objectUpdate({},sourceNode.attr);var speech=objectPop(areaAttr,'speech');var editor=objectPop(areaAttr,'editor');var tag=this._domtag;var notrigger={'doTrigger':false};if(editor){var parentNode=sourceNode.getParentNode();var insideTable=parentNode&&parentNode.attr.tag=='td';var _class='textAreaWrapper';if(insideTable){_class+=' textAreaWrapperInTable';}
if(editor){_class+=' textAreaIsEditor';}
var currAttr=sourceNode.attr;sourceNode.attr={'tag':'div',_class:_class};objectExtract(currAttr,'tag,width');var tKw=objectUpdate({overflow:'hidden',_class:'textAreaWrapperArea'},currAttr);if(editor){tKw['border']='1px solid silver';tKw['rounded']=4;}
var top=sourceNode._('div',tKw,notrigger);var bottom=sourceNode._('div',{_class:'textAreaWrapperButtons',transition:'1s all'},notrigger)
if(editor){bottom._('div',{_class:'TAeditorPalette',connect_onclick:function(){genro.dlg.floatingEditor(textarea,{});}},{'doTrigger':false})
tag='ckeditor';objectPop(areaAttr,'tag')
areaAttr['toolbar']=false;areaAttr['config_height']=objectPop(areaAttr,'height');areaAttr['config_width']=objectPop(areaAttr,'width');this._dojotag=null;}
var textarea=top._(tag,areaAttr,notrigger).getParentNode();}},onSpeechEnd:function(sourceNode,v){var lastSelection=genro._lastSelection;if(lastSelection&&(lastSelection.domNode==sourceNode.widget.domNode)){var oldValue=sourceNode.getAttributeFromDatasource('value');var fistchunk=oldValue.slice(0,lastSelection.start);var secondchunk=oldValue.slice(lastSelection.end);v=fistchunk+v+secondchunk;}
setTimeout(function(){sourceNode.setAttributeInDatasource('value',v,true);sourceNode.widget.domNode.focus();},1);},connectFocus:function(widget,savedAttrs,sourceNode){if(sourceNode.attr._autoselect&&!genro.isMobile){dojo.connect(widget,'onFocus',widget,function(e){setTimeout(dojo.hitch(this,'selectAllInputText'),1);});}},mixin_selectAllInputText:function(){dijit.selectInputText(this.focusNode);},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'value,shortcuts');return savedAttrs;},created:function(newobj,savedAttrs,sourceNode){if(savedAttrs.value){newobj.setValue(savedAttrs.value);}
if(savedAttrs.shortcuts){setTimeout(function(){newobj.setShortcuts(savedAttrs.shortcuts)},1)}
dojo.connect(newobj.domNode,'onchange',dojo.hitch(this,function(){this.onChanged(newobj);}));dojo.connect(sourceNode,'setValidationError',function(result){newobj.state=result.error?'Error':null;})
this.connectFocus(newobj,savedAttrs,sourceNode);},cell_onCreating:function(gridEditor,colname,colattr){colattr['z_index']=1;colattr['height']=colattr['height']||'100px';},onChanged:function(widget){var value=widget.getValue();this._doChangeInData(widget.domNode,widget.sourceNode,value);},mixin_displayMessage:function(message){if(isNullOrBlank(this.value)){return;}
if(this._message==message){return;}
this._message=message;dijit.hideTooltip(this.domNode);if(message){dijit.showTooltip(message,this.domNode,this.tooltipPosition);}}});dojo.declare("gnr.widgets.ProgressBar",gnr.widgets.baseDojo,{mixin_setProgress:function(value){if(value==undefined){value=null;}
this.update({'progress':value,'indeterminate':(value==null)});},mixin_setIndeterminate:function(value){if(value!=null){this.update({'indeterminate':value});}},mixin_setMaximum:function(value){this.update({'maximum':value});},mixin_setPlaces:function(value){this.update({'places':value});}});dojo.declare("gnr.widgets.StackContainer",gnr.widgets.baseDojo,{creating:function(attributes,sourceNode){objectPop(attributes,'selected');objectPop(attributes,'selectedPage');return{};},created:function(widget,savedAttrs,sourceNode){sourceNode.subscribe('switchPage',function(page){this.widget.switchPage(page);});widget.gnrPageDict={};dojo.connect(widget,'addChild',dojo.hitch(this,'onAddChild',widget));dojo.connect(widget,'removeChild',dojo.hitch(this,'onRemoveChild',widget));},mixin_switchPage:function(p){var handler=(p==parseInt(p))?'setSelected':'setSelectedPage';this[handler](p);},mixin_setHiddenChild:function(child,value){},patch_selectChild:function(page){var sourceNode=this.sourceNode;if(sourceNode.attr.nodeId){var oldselected=this.selectedChildWidget;if(oldselected){var oldpagename=oldselected.sourceNode.attr.pageName;if(oldpagename){sourceNode.publish('hiding',{pageName:oldpagename});}}
var newpagename=page.sourceNode.attr.pageName;if(newpagename){sourceNode.publish('showing',{pageName:newpagename});}}
this.selectChild_replaced(page);},mixin_setSelected:function(p){var child=this.getChildren()[p||0];if(this.getSelected()!=child){this.selectChild(child);}},mixin_setSelectedPage:function(pageName){var child=this.gnrPageDict[pageName];if(child&&this.getSelected()!=child){this.selectChild(child);}},mixin_hasPageName:function(pageName){return pageName in this.gnrPageDict;},mixin_getSelected:function(){var selected={n:null};dojo.forEach(this.getChildren(),function(n){if(n.selected){selected.n=n;}});return selected.n;},mixin_getSelectedIndex:function(){return this.getChildIndex(this.getSelected());},mixin_getChildIndex:function(obj){return dojo.indexOf(this.getChildren(),obj);},onShowHideChild:function(widget,child,st){if(widget._duringLayoutCall){return;}
var sourceNode=widget.sourceNode;var selpath=sourceNode.attr['selected'];var selpage=sourceNode.attr['selectedPage'];var nodeId=sourceNode.attr.nodeId;var cbUpd=function(path,newpage,st){if(st){if(genro.src.building){setTimeout(function(){if(!sourceNode.getRelativeData(path)){sourceNode.setRelativeData(path,newpage);}},1);}else{sourceNode.setRelativeData(path,newpage);}}
sourceNode.publish('selected',{'change':newpage+'_'+(st?'show':'hide'),'page':newpage,'selected':st});};if(selpath){cbUpd(selpath,widget.getChildIndex(child),st);}
if(selpage){cbUpd(selpage,child.sourceNode.attr.pageName,st);}},onAddChild:function(widget,child){if(!child.getParent){child.getParent=function(){return widget;};}
child.setHidden=function(value){widget.setHiddenChild(this,value);};gnr.setOrConnectCb(child,'onShow',dojo.hitch(this,'onShowHideChild',widget,child,true));gnr.setOrConnectCb(child,'onHide',dojo.hitch(this,'onShowHideChild',widget,child,false));var pageName=child.sourceNode.attr.pageName;if(pageName){widget.gnrPageDict=widget.gnrPageDict||{};widget.gnrPageDict[pageName]=child;}},mixin_deletePage:function(page){var pageNode=page.sourceNode;pageNode.getParentBag().popNode(pageNode.label);},mixin_onDestroyingChild:function(child){this.removeChild(child);},onRemoveChild:function(widget,child){var pageName=child.sourceNode.attr.pageName;if(pageName){objectPop(widget.gnrPageDict,pageName);}
setTimeout(function(){if(child.selected&&widget.getChildren().length==0){var sourceNode=widget.sourceNode;var selpath=sourceNode.attr['selected'];var selpage=sourceNode.attr['selectedPage'];if(selpath){sourceNode.setRelativeData(selpath,null);}
if(selpage){sourceNode.setRelativeData(selpage,null);}}},1);}});dojo.declare("gnr.widgets.TabContainer",gnr.widgets.StackContainer,{___created:function(widget,savedAttrs,sourceNode){},___onAddChild:function(widget,child){},mixin_setHiddenChild:function(child,hidden){if(hidden&&child.selected){var otherChildren=this.getChildren().filter(function(other){return other!==child});if(otherChildren.length>0){var that=this;this.switchPage(this.getChildIndex(otherChildren[0]));}}
genro.dom.toggleVisible(child.controlButton.domNode,!hidden);},versionpatch_11_layout:function(){if(!this.doLayout){return;}
var titleAlign=this.tabPosition.replace(/-h/,"");var children=[{domNode:this.tablist.domNode,layoutAlign:titleAlign},{domNode:this.containerNode,layoutAlign:"client"}];dijit.layout.layoutChildren(this.domNode,this._contentBox,children);this._containerContentBox=dijit.layout.marginBox2contentBox(this.containerNode,children[1]);if(this.selectedChildWidget){this._duringLayoutCall=true;this._showChild(this.selectedChildWidget);this._duringLayoutCall=false;if(this.doLayout&&this.selectedChildWidget.resize){this.selectedChildWidget.resize(this._containerContentBox);}}}});dojo.declare("gnr.widgets.BorderContainer",gnr.widgets.baseDojo,{creating:function(attributes,sourceNode){if(dojo_version!='1.1'){attributes.gutters=attributes.gutters||false;}
this.setControllerTitle(attributes,sourceNode);},created:function(widget,savedAttrs,sourceNode){widget._saved_size={};dojo.connect(widget,'startup',dojo.hitch(this,'afterStartup',widget));if(dojo_version=='1.1'){dojo.connect(widget,'addChild',dojo.hitch(this,'onAddChild',widget));dojo.connect(widget,'removeChild',dojo.hitch(this,'onRemoveChild',widget));}},addClosableHandle:function(bc,pane,kw){var side=pane.attr.region;var orientation=['left','right'].indexOf(side)>=0?'vertical':'horizontal';if(bc._splitters[side]){genro.dom.setClass(bc._splitters[side],'tinySplitter',true);}
var togglecb=function(){var toClose=!dojo.hasClass(pane.widget.domNode,'closedSide');genro.dom.setClass(pane,'closedSide','toggle');if(bc._splitters[side]){genro.dom.setClass(bc._splitters[side],'hiddenSplitter','toggle');}
if(toClose){if(orientation=='vertical'){pane.__currDimension=pane.widget.domNode.style.width;dojo.style(pane.widget.domNode,'width',null);}else{pane.__currDimension=pane.widget.domNode.style.height;dojo.style(pane.widget.domNode,'height',null);}}else if(pane.__currDimension){dojo.style(pane.widget.domNode,orientation=='vertical'?'width':'height',pane.__currDimension);}
bc._layoutChildren(side);bc.layout();}
genro.dom.setClass(pane,'closableSide_'+orientation,true);var closablePars=objectExtract(kw,'closable_*');var iconClass=objectPop(closablePars,'iconClass');if('top'in closablePars){closablePars['margin_top']=closablePars['margin_top']||0;}
if('left'in closablePars){closablePars['margin_left']=closablePars['margin_left']||0;}
var splitter=objectPop(closablePars,'splitter');if(kw.closable=='close'){togglecb()}
var _class='slotbarOpener'+' slotbarOpener_'+orientation+' slotbarOpener_'+side;var label=objectPop(closablePars,'label');var opener=pane._('div',objectUpdate({_class:_class,connect_onclick:togglecb},closablePars),{doTrigger:false});if(label){opener._('div',{'innerHTML':label,_class:'slotbarOpener_label_'+orientation},{doTrigger:false});}
if(iconClass){opener._('div',{_class:iconClass},{doTrigger:false});}},onChildCreated:function(sourceNode,childSourceNode){if(childSourceNode.attr.closable){var closable_kw=objectExtract(childSourceNode.attr,'closable_*',true,true)
closable_kw.closable=childSourceNode.attr.closable;this.addClosableHandle(sourceNode.widget,childSourceNode,closable_kw);}},onChildBuilding:function(sourceNode,childSourceNode){if(!childSourceNode.attr.region||childSourceNode.attr.tag.toLowerCase()=='bordercontainer'||!childSourceNode.attr.closable){return;}
var wrapperNode=childSourceNode;var parentContent=sourceNode.getValue();var childLabel=childSourceNode.label;var wrapperAttr=childSourceNode.attr;var childContent=childSourceNode.getValue();childSourceNode.setValue(new gnr.GnrDomSource(),false);var childTag=objectPop(wrapperAttr,'tag');var childAttr=objectUpdate({},wrapperAttr);objectExtract(wrapperAttr,'margin,background,style,_class,nodeId,overflow');objectExtract(childAttr,'height,width,border,left,right,top,bottom')
objectExtract(childAttr,'margin_*');objectExtract(childAttr,'border_*');objectPop(childAttr,'closable');objectExtract(childAttr,'closable_*');wrapperAttr.tag='borderContainer';wrapperNode.attr._class='closableWrapper'
wrapperNode.label='wrapper_'+childAttr.region;childAttr.region='center';childAttr.content=childContent;var src=wrapperNode._(childTag,childLabel,childAttr,{doTrigger:false});src.getParentNode().setValue(childContent,false);},afterStartup:function(widget){var sourceNode=widget.sourceNode;if(dojo_version!='1.7'){widget._splitterConnections={};var region,splitter;for(region in widget._splitters){if(!widget._splitterConnections[region]){splitter=dijit.byNode(widget._splitters[region]);widget._splitterConnections[region]=dojo.connect(splitter,'_stopDrag',dojo.hitch(this,'onSplitterStopDrag',widget,splitter));}}}
if(sourceNode.attr.regions){widget.sourceNode.watch('untillIsVisible',function(){return widget.domNode?genro.dom.isVisible(widget.domNode):false;},function(){var regions=sourceNode.getRelativeData(sourceNode.attr.regions);if(!regions){regions=new gnr.GnrBag();sourceNode.setRelativeData(sourceNode.attr.regions,regions);}
var regions=regions.getNodes();for(var i=0;i<regions.length;i++){widget.setRegions(null,{'node':regions[i]});}});}},onRemoveChild:function(widget,child){delete child.parentBorderContainer;},onAddChild:function(widget,child){child.parentBorderContainer=widget;var splitter=widget._splitters[child.region];if(splitter){if(child.domNode.style.display=='none'){dojo.style(splitter,'display','none');}
if(child.sourceNode.attr.drawer){widget.addDrawerHandle(child)}}},onSplitterStopDrag:function(widget,splitter){var sourceNode=widget.sourceNode;if(sourceNode.attr.regions){var region=splitter.region;var regions=sourceNode.getRelativeData(sourceNode.attr.regions);var value=splitter.child.domNode.style[splitter.horizontal?"height":"width"];regions.setItem(region,value,null,{'doTrigger':sourceNode});}},mixin_setRegions:function(value,kw){var region=kw.node.label;if(('_'+region)in this){var size=kw.node.getValue();if(size){this['_'+region].style[(region=='top'||region=='bottom')?"height":"width"]=size;this._layoutChildren();}}
if('show'in kw.node.attr){this.showHideRegion_one(region,kw.node.attr.show);}},mixin_getRegionVisibility:function(region){return(this._splitterThickness[region]!=0);},mixin_showHideRegion:function(region,show){var regions=region.split(',');for(var i=0;i<regions.length;i++){show=this.showHideRegion_one(regions[i],show);};return show;},mixin_showHideRegion_one:function(region,show){if(this._splitters[region]){this._computeSplitterThickness(region);}
var regionNode=this['_'+region];if(regionNode){if(show=='toggle'){show=!this.isRegionVisible(region);}
var disp=show?'':'none';var splitterNode=this._splitters[region];if(splitterNode){var tk=this._splitterThickness['_'+region]||this._splitterThickness[region];this._splitterThickness['_'+region]=tk;this._splitterThickness[region]=show?tk:0;dojo.style(splitterNode,(region=='left'||region=='right')?'width':'height',this._splitterThickness[region]+'px');}
dojo.style(regionNode,'display',disp);if(!show){this._saved_size[region]=(region=='left'||region=='right')?regionNode.style.width:regionNode.style.height;}else if(region in this._saved_size){if(region=='left'||region=='right'){regionNode.style.width=this._saved_size[region];}else{regionNode.style.height=this._saved_size[region];}}
this._layoutChildren();}
return show;},mixin_setRegionVisible:function(region,show){var regionbox=this['_'+region];if(show=='toggle'){var show=regionbox.style.display=='none';}
dojo.style(regionbox,'display',show?'block':'none');if(this._splitters[region]){dojo.style(this._splitters[region],'display',show?'block':'none');}
this._layoutChildren(region);this.layout();return show;},mixin_isRegionVisible:function(region){return this['_'+region].style.display!='none';},mixin_addDrawerHandle:function(child){var bc=this;var pane=child.sourceNode;var kw=objectUpdate({},pane.attr);var side=pane.attr.region;var splitter=bc._splitters[side];var drawerDom=document.createElement('div');splitter.appendChild(drawerDom);var drawerClass=objectPop(kw,'drawer_class');var drawerStyle=objectPop(kw,'drawer_style');var drawer_kw=objectExtract(kw,'drawer_*');var drawerLabel=objectPop(drawer_kw,'label');var styledict_kw=genro.dom.getStyleDict(drawer_kw);drawerDom.setAttribute('style',objectAsStyle(objectUpdate(objectFromStyle(drawerStyle),styledict_kw)));genro.dom.addClass(drawerDom,'drawerHandle');if(drawerClass){genro.dom.addClass(drawerDom,drawerClass);}
if(drawerLabel){drawerDom.innerHTML=drawerLabel;}
var drawer=pane.getAttributeFromDatasource('drawer');genro.dom.addClass(splitter,'drawerSplitter '+'drawer_region_'+side);if(!pane.getAttributeFromDatasource('splitter')){genro.dom.addClass(splitter,'drawerFixed')
dijit.getEnclosingWidget(splitter)._startDrag=function(){};}
if(drawer=='close'){dojo.connect(bc,'startup',function(){bc.showHideRegion(side,false);});}
dojo.connect(drawerDom,'onclick',function(e){var show=bc.showHideRegion(side,'toggle');if(drawer_kw.onclick){funcApply(drawer_kw.onclick,{evt:e,show:show},pane);}})}});dojo.declare("gnr.widgets.TitlePane",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='TitlePane';},created:function(widget,savedAttrs,sourceNode){if(sourceNode.hasDynamicAttr('open')){var isOpen=sourceNode.getAttributeFromDatasource('open');if(widget.open!=isOpen){widget.toggle();}
dojo.connect(widget,'toggle',function(e){sourceNode.setAttributeInDatasource('open',widget.open);});}},mixin_setOpen:function(isOpen,pc){if(this.open!=isOpen){this.toggle();}}});dojo.declare("gnr.widgets.ResizeHandle",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='ResizeHandle';genro.dom.loadCss("/_dojo/11/dojo/dojox/layout/resources/ResizeHandle.css");}});dojo.declare("gnr.widgets.FloatingPane",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._attachTo='mainWindow';this._dojotag='FloatingPane';genro.dom.loadCss("/_dojo/11/dojo/dojox/layout/resources/FloatingPane.css");genro.dom.loadCss("/_dojo/11/dojo/dojox/layout/resources/ResizeHandle.css");},creating:function(attributes,sourceNode){objectPop(attributes,'persist')
attributes.width='2px';attributes.height='2px';},created:function(widget,savedAttrs,sourceNode){widget._startZ=700;var nodeId=sourceNode.attr.nodeId;if(nodeId){dojo.connect(widget,'show',function(){genro.publish(nodeId+'_show');});}
dojo.subscribe("/dnd/move/stop",function(mover){var node=mover.host.node;var c=dojo.coords(node);if(c.y<0){node.style.top="0px";}});if(widget.resizeHandle){dojo.connect(widget,'startup',function(){dojo.connect(this._resizeHandle,'_beginSizing',function(e){genro.dom.addClass(dojo.body(),'active_click_palette');this.screenStartPoint={x:e.screenX,y:e.screenY};this.page_id=genro.page_id;genro.mainGenroWindow.genro.currentResizeHandle=this;});dojo.connect(this._resizeHandle,'_endSizing',function(e){genro.mainGenroWindow.genro.currentResizeHandle=null;genro.dom.removeClass(dojo.body(),'active_click_palette');});});}
dojo.connect(widget,'maximize',function(){this.resize({'t':'0','l':'0'});});dojo.connect(sourceNode,'_onDeleting',function(){widget.destroyRecursive();});},patch_close:function(cb){this.saveRect();this.sourceNode.getParentBag().popNode(this.sourceNode.label);},patch_hide:function(cb){this.saveRect();this.hide_replaced(cb);},patch_show:function(cb){this.restoreRect();this.onShowing();var that=this;this.show_replaced(cb);this.bringToTop();},mixin_onChangedContent:function(){if(this.sourceNode.attr.autoSize!=false){this.autoSize();}},mixin_restoreRect:function(){var rect;if(this.sourceNode.attr.nodeId){var storeKey='palette_rect_'+genro.getData('gnr.pagename')+'_'+this.sourceNode.attr.nodeId;rect=genro.getFromStorage("local",storeKey,dojo.coords(this.domNode));if(rect){this._size_from_cache=true;}}
var oh=this.domNode.parentElement.offsetHeight;var ow=this.domNode.parentElement.offsetWidth;if(!rect||this.sourceNode.attr.persist===false||this.sourceNode.attr.fixedPosition){var currAttr=this.sourceNode.currentAttributes();rect={};var p={'left':'l','top':'t','width':'w','height':'h'};for(var k in p){if(currAttr[k]){rect[p[k]]=parseInt(currAttr[k]);}}
if(!rect.l&&currAttr.right){rect.l=ow-rect.w-parseInt(currAttr.right);}}
if(rect.w+20>ow){rect.w=ow-20;}
rect.l=Math.max(rect.l,10);if(rect.l+rect.w>ow-10){rect.l=ow-rect.w-10;}
if(rect.h+20>oh){rect.h=oh-20;}
rect.t=Math.max(rect.t,10);if(rect.t+rect.h>oh-10){rect.t=oh-rect.h-10;}
this.resize(rect);},mixin_saveRect:function(){if(this.sourceNode.attr.nodeId&&genro.dom.isVisible(this.domNode)&&!this._maximized&&(this.sourceNode.attr.persist!==false)){var storeKey='palette_rect_'+genro.getData('gnr.pagename')+'_'+this.sourceNode.attr.nodeId;genro.setInStorage("local",storeKey,dojo.coords(this.domNode));}},mixin_onShowing:function(){if(this.sourceNode.attr.autoSize!=false&&(this.sourceNode.attr._lazyBuild||this.sourceNode._value._nodes.length==0)){var domNode=this.domNode;var oldwidth=domNode.style.width;var oldleft=domNode.style.left;domNode.style.left=parseInt(oldleft)+parseInt(oldwidth)+'px';domNode.style.width='1px';domNode.style.height='1px';}},mixin_autoSize:function(){var domNode=this.domNode;var layoutcoords=dojo.coords(this.containerNode.firstChild);var newcoords=dojo.coords(domNode);newcoords['l']=newcoords['l']-(layoutcoords['w']-newcoords['w']);newcoords['h']=layoutcoords['h']+16;newcoords['w']=layoutcoords['w'];this.resize(newcoords);},mixin_setBoxAttributes:function(kw){var dimensionDict={'height':'h','width':'w','left':'l','right':'r','t':'top'};var resizer={};for(var k in kw){if(k in dimensionDict){resizer[dimensionDict[k]]=parseInt(kw[k].replace('px',''));}else{this.setAttribute(k,kw[k]);}}
if(objectNotEmpty(resizer)){this.resize(resizer);}}});dojo.declare("gnr.widgets.ColorPicker",gnr.widgets.baseDojo,{created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onChange',function(){console.log(arguments);});}});dojo.declare("gnr.widgets.ColorPalette",gnr.widgets.baseDojo,{created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onChange',function(){return;});},mixin_setValue:function(value){this.value=value;},mixin_getValue:function(){return this.value;}});dojo.declare('gnr.widgets.AccordionPane',gnr.widgets.baseDojo,{constructor:function(application){this._domtag='*';var dojotag=dojo_version>'1.4'?'ContentPane':'AccordionPane';this._dojotag=dojotag;this._basedojotag=dojotag;}});dojo.declare("gnr.widgets.Menuline",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='*';this._dojotag='MenuItem';this._basedojotag='MenuItem';},creating:function(attributes,sourceNode){var savedAttrs={};objectPop(attributes,'action');if(attributes.draggable){savedAttrs['draggable']=objectPop(attributes,'draggable');}
if(sourceNode.attr.label=='-'){this._dojotag='MenuSeparator';}
else{if(sourceNode.getResolver()){this._dojotag='PopupMenuItem';}
else{var content=sourceNode.getValue();if(content instanceof gnr.GnrBag&&content.len()>0){this._dojotag='PopupMenuItem';}else{this._dojotag='MenuItem';}}}
if(attributes.checked){attributes.iconClass='tick_icon10';}
if(attributes.favorite){attributes.iconClass='box16 star';}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.draggable){widget.focusNode.setAttribute('draggable',true);}},mixin_setChecked:function(val,kw){if(val){dojo.addClass(this.iconNode,'tick_icon10');}else{dojo.removeClass(this.iconNode,'tick_icon10');}},mixin_addChild:function(popUpContent){if(popUpContent.declaredClass=='dijit.Menu'){this.popup=popUpContent;}
if(this.addChild_replaced){this.addChild_replaced.call(this,popUpContent);}},patch_onClick:function(evt){var sourceNode=this.sourceNode;var ctxSourceNode=this.getParent().ctxTargetSourceNode||genro._lastCtxTargetSourceNode||sourceNode;var menuAttr=sourceNode.getAttr();var inAttr=sourceNode.getInheritedAttributes();var actionScope=sourceNode.attributeOwnerNode('action');var action=inAttr.action;if(ctxSourceNode&&ctxSourceNode.attr.action){action=ctxSourceNode.attr.action;actionScope=ctxSourceNode;}
f=funcCreate(action);if(f){f.call(actionScope,menuAttr,ctxSourceNode,evt);}
var selattr=objectExtract(inAttr,'selected_*',true);if(ctxSourceNode){selattr=objectUpdate(selattr,objectExtract(ctxSourceNode.getInheritedAttributes(),'selected_*',true));}
for(var sel in selattr){ctxSourceNode.setRelativeData(selattr[sel],sourceNode.attr[sel],null,null,sourceNode);}
if(inAttr.selected){ctxSourceNode.setRelativeData(inAttr.selected,sourceNode.label,null,null,sourceNode);}}});dojo.declare("gnr.widgets.ContentPane",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='ContentPane';},creating:function(attributes,sourceNode){attributes.isLoaded=true;this.setControllerTitle(attributes,sourceNode);},created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'startup',dojo.hitch(this,'afterStartup',widget));},afterStartup:function(widget){if(widget._singleChild&&widget._singleChild.sourceNode&&(widget._singleChild.sourceNode.attr.tag.toLowerCase()in genro.src.layouttags)){widget.domNode.style.overflow='hidden';}}});dojo.declare("gnr.widgets.Menu",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='*';this._dojotag='Menu';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'modifiers,validclass,storepath,values');if(savedAttrs.storepath){sourceNode.registerDynAttr('storepath');}
if(!attributes.connectId){savedAttrs['connectToParent']=true;}
if(attributes.menuItemCb){attributes['menuItemCb']=funcCreate(attributes.menuItemCb,'item',sourceNode);}
if(attributes.disabledItemCb){attributes['disabledItemCb']=funcCreate(attributes.disabledItemCb,'item',sourceNode);}
if(attributes.hiddenItemCb){attributes['hiddenItemCb']=funcCreate(attributes.hiddenItemCb,'item',sourceNode);}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.values){var contentBag;if(typeof(savedAttrs.values)=='string'){contentBag=new gnr.GnrBag(objectFromString(savedAttrs.values,null,'kv'));}else{contentBag=savedAttrs.values;}
var menubag=new gnr.GnrDomSource();gnr.menuFromBag(contentBag,menubag,sourceNode.attr._class);sourceNode.setValue(menubag,false);}
else if(savedAttrs.storepath){var contentNode=genro.getDataNode(sourceNode.absDatapath(savedAttrs.storepath));if(contentNode){var content=contentNode.getValue('static');if(content){var menubag=new gnr.GnrDomSource();gnr.menuFromBag(content,menubag,sourceNode.attr._class);sourceNode.setValue(menubag,false);}else if(contentNode.getResolver()){sourceNode.setResolver(contentNode.getResolver());}else{}}else{}}
if(sourceNode&&savedAttrs['connectToParent']){var parentNode=sourceNode.getParentBag().getParentNode();var parentWidget=parentNode.widget;if(parentWidget){if(!(('dropDown'in parentWidget)||('popup'in parentWidget))){if(parentWidget.downArrowNode){parentWidget._downArrowMenu=true;if(parentWidget.sourceNode.attr.connectedMenu!=sourceNode.attr.id){widget.bindDomNode(parentWidget.downArrowNode);}}else{widget.bindDomNode(parentWidget.domNode);}}}else if(parentNode.domNode){widget.bindDomNode(parentNode.domNode);}else{widget.bindDomNode(dojo.byId(genro.domRootName));}
if(parentNode.attr.tag!='menuline'){sourceNode.stopInherite=true;}}
dojo.connect(widget,'onOpen',function(){genro.dom.addClass(document.body,'openingMenu');});dojo.connect(widget,'onClose',function(){genro.dom.removeClass(document.body,'openingMenu');});widget.modifiers=savedAttrs['modifiers'];widget.validclass=savedAttrs['validclass'];},mixin_setStorepath:function(val,kw){this.sourceNode.rebuild();},mixin_setChecked:function(menuline,val){if(this.currentChecked&&this.currentChecked!=menuline){this.currentChecked.setChecked(false);}
menuline.setChecked(val);this.currentChecked=val?menuline:null;},patch_destroy:function(){if(this._bindings){var menu=this;dojo.forEach(this._bindings,function(b){dojo.forEach(b,function(n){menu.unBindDomNode(n[0]);});});delete this._bindings;}
this.destroy_replaced.call(this);},versionpatch_11__contextMouse:function(e){this.originalContextTarget=e.target;if(genro.dom.isDisabled(this.originalContextTarget,true)){return;}
var ctxSourceNode;if(this.originalContextTarget){if(this.originalContextTarget.sourceNode){ctxSourceNode=this.originalContextTarget.sourceNode;}
else{var w=genro.dom.getBaseWidget(this.originalContextTarget);if(w){ctxSourceNode=w.sourceNode;}}}
genro._lastCtxTargetSourceNode=ctxSourceNode;this.ctxTargetSourceNode=ctxSourceNode;var sourceNode=this.sourceNode;var wdg=sourceNode.widget;if((wdg.modifiers||wdg.validclass)&&!(genro.wdg.filterEvent(e,wdg.modifiers,wdg.validclass))){return;}
var contextclick=(e.button==2||genro.dom.getEventModifiers(e)=='Ctrl');if(!wdg.modifiers){if(!contextclick){return;}}
if(sourceNode){var resolver=sourceNode.getResolver();if(resolver&&resolver.expired()){if(sourceNode.attr.onOpeningMenu){var optkwargs=funcApply(sourceNode.attr.onOpeningMenu,{evt:e},sourceNode);}
var result=sourceNode.getValue('notrigger',optkwargs);if(result instanceof gnr.GnrBag){var menubag=new gnr.GnrDomSource();var old_bindings=[];dojo.forEach(this._bindings,function(k){old_bindings.push(k[0][0]);});gnr.menuFromBag(result,menubag,sourceNode.attr._class,sourceNode.attr.fullpath);sourceNode.setValue(menubag);var new_bindings=[];dojo.forEach(sourceNode.widget._bindings,function(k){new_bindings.push(k[0][0]);});dojo.forEach(old_bindings,function(n){if(dojo.indexOf(new_bindings,n)<0){sourceNode.widget.bindDomNode(n);}});}else{sourceNode.setValue(result);}}}
wdg=sourceNode.widget;var widgetChildren=wdg.getChildren();widgetChildren.forEach(function(item){if(item.onOpen){funcApply(item.onOpen,null,sourceNode,['item','evt'],[item,e]);}
if(wdg.menuItemCb){wdg.menuItemCb(item,e)}
if(wdg.disabledItemCb){item.setDisabled(wdg.disabledItemCb(item,e));}
if(wdg.hiddenItemCb){item.setHidden(wdg.hiddenItemCb(item,e));}});if(wdg.modifiers){wdg._contextMouse_replaced.call(wdg,e);wdg._openMyself_replaced.call(wdg,e);}
else if(contextclick){wdg._contextMouse_replaced.call(wdg,e);}},versionpatch_11__openMyself:function(e){var contextclick=(e.button==2||genro.dom.getEventModifiers(e)=='Ctrl');if(this.validclass&&!genro.wdg.filterEvent(e,null,this.validclass)){return;}
if(contextclick&&(!this.modifiers)){this._openMyself_replaced.call(this,e);}},patch__openPopup:function(e){var sourceNode=this.focusedChild.popup.sourceNode;if(sourceNode){var resolver=sourceNode.getResolver();if(resolver&&resolver.expired()){var result=sourceNode.getValue('notrigger');if(result instanceof gnr.GnrBag){var menubag=new gnr.GnrDomSource();gnr.menuFromBag(result,menubag,sourceNode.attr._class,sourceNode.attr.fullpath);sourceNode.setValue(menubag);}else{sourceNode.setValue(result);}
this.focusedChild.popup=sourceNode.widget;}}
this.focusedChild.popup.originalContextTarget=this.originalContextTarget;this._openPopup_replaced.call(this,e);},mixin_onOpeningPopup:function(popupKwargs){var kw=this.sourceNode.currentAttributes();var aroundWidget=kw.attachTo?kw.attachTo.widget:null;if(!aroundWidget&&this.originalContextTarget){var enclosingWidget=dijit.getEnclosingWidget(this.originalContextTarget);if(enclosingWidget.sourceNode){var cmenu=enclosingWidget.sourceNode.attr.connectedMenu;if(cmenu&&cmenu==this.sourceNode.attr.id){aroundWidget=enclosingWidget;}}}
if(aroundWidget){this.gnrPlaceAround(popupKwargs,aroundWidget);}},mixin_gnrPlaceAround:function(popupKwargs,widget){popupKwargs.popup.domNode.style.width=widget.domNode.clientWidth+'px';popupKwargs.orient=this.isLeftToRight()?{'BL':'TL','BR':'TR','TL':'BL','TR':'BR'}:{'BR':'TR','BL':'TL','TR':'BR','TL':'BL'};popupKwargs.around=widget.domNode;}});dojo.declare("gnr.widgets.Tooltip",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='*';this._dojotag='Tooltip';},creating:function(attributes,sourceNode){var callback=objectPop(attributes,'callback');attributes.showDelay=attributes.showDelay||attributes.tooltip_type=='help'?2000:null;if(callback){attributes['label']=funcCreate(callback,'n',sourceNode);}else if(attributes.recordTemplate){var recordTemplate=objectPop(attributes,'recordTemplate');var tpltable=recordTemplate.table;var tplname=recordTemplate.template||'tooltip';var pkeyCb=recordTemplate.pkeyCb;attributes['label']=function(n){var pkey=pkeyCb?funcApply(pkeyCb,null,n.sourceNode):n.attr.pkey;return genro.serverCall('renderTemplate',{record_id:pkey,table:tpltable,tplname:tplname},null,null,'POST');}}
var savedAttrs=objectExtract(attributes,'modifiers,validclass');if(!attributes.connectId){savedAttrs['connectToParent']=true;}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){widget.modifiers=savedAttrs['modifiers'];widget.validclass=savedAttrs['validclass'];if(sourceNode&&savedAttrs['connectToParent']){var parentNode=sourceNode.getParentBag().getParentNode();var domnode=parentNode.domNode||parentNode.widget.domNode;widget.connectOneNode(domnode);}},patch__onHover:function(e){var defaultMod;if(this.tooltip_type=='help'){defaultMod=genro.tooltipHelpModifier();}
var modifiers=(this.modifiers||defaultMod);if(genro.wdg.filterEvent(e,modifiers,this.validclass)){var showDelay=modifiers?50:this.showDelay;if(!this._showTimer){var target=e.target;this._showTimer=setTimeout(dojo.hitch(this,function(){this.open(target)}),showDelay);}}},attributes_mixin_postCreate:function(){if(dojo_version=='1.1'){if(this.srcNodeRef){this.srcNodeRef.style.display="none";}}else{dojo.addClass(this.domNode,"dijitTooltipData");}
this.connectAllNodes(this.connectId);},attributes_mixin_connectAllNodes:function(nodes){var node;this._connectNodes=[];dojo.forEach(nodes,function(node){if(typeof(node)=='string'){node=dojo.byId(node);}
this.connectOneNode(node);});},mixin_connectOneNode:function(node){this._connectNodes.push(node);var eventlist;if(dojo_version=='1.1'){eventlist=["onMouseOver","onMouseOut","onFocus","onBlur","onHover","onUnHover"];}
else if(dojo_version=='1.5'){eventlist=["onTargetMouseEnter","onTargetMouseLeave","onTargetFocus","onTargetBlur","onHover","onUnHover"];}
else{eventlist=["onMouseEnter","onMouseLeave","onFocus","onBlur"];}
dojo.forEach(eventlist,function(evt){this.connect(node,evt.toLowerCase(),"_"+evt);},this);if(dojo.isIE){node.style.zoom=1;}}});dojo.declare("gnr.widgets._ButtonLogic",null,{clickHandler:function(sourceNode,e){e.stopPropagation();e.preventDefault();if(sourceNode.disabled){return;}
var inattr=sourceNode.getInheritedAttributes();var _delay=inattr._delay;if(!_delay){sourceNode.setDisabled('*pendingclick*');sourceNode._clickTimeout=setTimeout(function(){sourceNode._clickTimeout=null;if(sourceNode.disabled=='*pendingclick*'){sourceNode.setDisabled(false);}},200);return this._clickHandlerDo(sourceNode,e,inattr);}
if(sourceNode._pendingClick){var pc=sourceNode._pendingClick;delete sourceNode._pendingClick
clearTimeout(pc);}
var that=this;sourceNode._pendingClickCount=(sourceNode._pendingClickCount||0)+1;sourceNode._pendingClick=setTimeout(function(){var count=sourceNode._pendingClickCount;sourceNode._pendingClickCount=0;that._clickHandlerDo(sourceNode,e,inattr,count);},_delay);},_clickHandlerDo:function(sourceNode,e,inattr,count){var modifier=eventToString(e);var action=inattr.action;var modifiers=genro.dom.getEventModifiers(e);var argnames=['event','_counter','modifiers'];var argvalues=[e,count,modifiers];if(action){var action_attributes=sourceNode.currentAttributes();var ask_params=sourceNode._ask_params;var skipOn,askOn,doAsk,_if;if(ask_params){skipOn=ask_params.skipOn;askOn=ask_params.askOn;askIf=ask_params.askIf;if(askIf){askIf=funcApply('return '+askIf,action_attributes,sourceNode);}
doAsk=askIf||!(askOn||skipOn)||(askOn&&askOn==modifiers)||(skipOn&&skipOn!=modifiers);}
if(ask_params&&doAsk){var promptkw=objectUpdate({},sourceNode._ask_params);promptkw.fields=promptkw.fields.map(function(kw){kw=objectUpdate({},kw);if(kw['name']in action_attributes){kw['default_value']=action_attributes[kw['name']];}
kw['value']='^.'+kw['name'];return kw;})
promptkw.widget=objectPop(promptkw,'fields');promptkw.action=function(result){if(result&&result.len()){result=result.asDict();objectUpdate(action_attributes,result);action_attributes._askResult=result;}
funcApply(action,objectUpdate(action_attributes,{}),sourceNode,argnames,argvalues);}
genro.dlg.prompt(objectPop(promptkw,'title','Parameters'),promptkw,sourceNode);}else{funcApply(action,objectUpdate(action_attributes,{}),sourceNode,argnames,argvalues);}
return;}
if(sourceNode.attr.fire){var s=eventToString(e)||true;sourceNode.setRelativeData(sourceNode.attr.fire,s,{modifier:modifier,_counter:count},true);}
if(sourceNode.attr.publish){genro.publish(sourceNode.attr.publish,true);}
var fire_list=objectExtract(sourceNode.attr,'fire_*',true);for(var fire in fire_list){sourceNode.setRelativeData(fire_list[fire],fire,{modifier:modifier,_counter:count},true);}}});dojo.declare("gnr.widgets.LightButton",[gnr.widgets.baseHtml,gnr.widgets._ButtonLogic],{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'fire_*');var label=objectPop(attributes,'label');attributes.innerHTML=attributes.innerHTML||label;savedAttrs['action']=objectPop(attributes,'action');savedAttrs['fire']=objectPop(attributes,'fire');savedAttrs['publish']=objectPop(attributes,'publish');savedAttrs['ask_params']=objectPop(attributes,'ask');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var that=this;dojo.connect(widget,'onclick',function(e){that.clickHandler(sourceNode,e);});objectExtract(sourceNode._dynattr,'fire_*');objectExtract(sourceNode._dynattr,'fire,publish');if(savedAttrs.ask_params){sourceNode._ask_params=savedAttrs.ask_params;}}});dojo.declare("gnr.widgets.Button",[gnr.widgets.baseDojo,gnr.widgets._ButtonLogic],{constructor:function(application){this._domtag='div';this._dojotag='Button';},creating:function(attributes,sourceNode){var buttoNodeAttr='height,width,padding,background,background_color';var savedAttrs=objectExtract(attributes,'fire_*');savedAttrs.shortcut=objectPop(attributes,'_shortcut');savedAttrs['_style']=genro.dom.getStyleDict(objectExtract(attributes,buttoNodeAttr));savedAttrs['action']=objectPop(attributes,'action');savedAttrs['fire']=objectPop(attributes,'fire');savedAttrs['publish']=objectPop(attributes,'publish');savedAttrs['ask_params']=objectPop(attributes,'ask');var focusOnTab=objectPop(attributes,'focusOnTab');if(attributes.iconRight){attributes.templateString="<div class=\"dijit dijitReset dijitLeft dijitInline\"\n\tdojoAttachEvent=\"onclick:_onButtonClick,onmouseenter:_onMouse,onmouseleave:_onMouse,onmousedown:_onMouse\"\n\twaiRole=\"presentation\"\n\t><button class=\"dijitReset dijitStretch dijitButtonNode dijitButtonContents\" dojoAttachPoint=\"focusNode,titleNode\"\n\t\ttype=\"${type}\" waiRole=\"button\" waiState=\"labelledby-${id}_label\"\n\t\t><div class=\"dijitReset dijitInline\"><center class=\"dijitReset dijitButtonText\" id=\"${id}_label\" dojoAttachPoint=\"containerNode\">${label}</center></div\n\t><span class=\"dijitReset dijitInline ${iconClass}\" dojoAttachPoint=\"iconNode\" \n \t\t\t><span class=\"dijitReset dijitToggleButtonIconChar\">&#10003;</span \n\t\t></span\n\t\t></button\n></div>\n";}
if(!focusOnTab){attributes['tabindex']=32767;}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var that=this;dojo.connect(widget,'onClick',function(e){that.clickHandler(sourceNode,e)});objectExtract(sourceNode._dynattr,'fire_*');objectExtract(sourceNode._dynattr,'fire,publish');if(savedAttrs['_style']){var buttonNode=dojo.query(".dijitButtonNode",widget.domNode)[0];dojo.style(buttonNode,savedAttrs['_style']);}
if(savedAttrs.ask_params){sourceNode._ask_params=savedAttrs.ask_params;}
if(savedAttrs.shortcut){genro.dev.shortcut(savedAttrs.shortcut,function(e){var domNode=sourceNode.getDomNode();if(!genro.dom.isVisible(domNode)||!genro.dom.isActiveLayer(domNode)){return;}
if(sourceNode.widget&&sourceNode.widget.disabled){return;}
if(sourceNode.attr._shortcut_activeForm){if(genro.activeForm&&sourceNode.form!=genro.activeForm){return;}}
that.clickHandler(sourceNode,e);},null,sourceNode);}},mixin_setIconClass:function(iconClass){var domNode=this.iconNode;dojo.removeClass(domNode,this.iconClass);this.iconClass=iconClass;dojo.addClass(domNode,this.iconClass);}});dojo.declare("gnr.widgets.Calendar",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='Calendar';},creating:function(attributes,sourceNode){var storepath=sourceNode.absDatapath(objectPop(attributes,'storepath'));sourceNode.registerDynAttr('storepath',storepath);},created:function(widget,savedAttrs,sourceNode){var bagnodes=widget.getStorebag().getNodes();for(i=0;i<bagnodes.length;i++){widget.setCalendarEventFromBagNode(bagnodes[i]);}},mixin_setStorepath:function(val,kw){if(kw.evt=='ins'){this.setCalendarEventFromBagNode(kw.node);}
else if(kw.evt=='upd'){var bagnodes=this.getStorebag().getNodes();this.emptyCalendar();for(i=0;i<bagnodes.length;i++){this.setCalendarEventFromBagNode(bagnodes[i]);}}},mixin_getStorebag:function(){var storepath=this.sourceNode.absDatapath(this.sourceNode.attr['storepath']);var storebag=genro.getData(storepath);if(!storebag){storebag=new gnr.GnrBag();genro.setData(storepath,storebag);}
return storebag;},mixin_setCalendarEventFromBagNode:function(node){var event_record=node.attr;this.addCalendarEntry(node.attr.date,event_record);},patch_onValueChanged:function(date,mode){var bagnodes=this.getStorebag().getNodes();for(i=0;i<bagnodes.length;i++){this.setCalendarEventFromBagNode(bagnodes[i]);}},patch_onChangeEventDate:function(item_id,newDate){this.getStorebag().getNode(item_id).attr.date.setDate(newDate.getDate());},patch_onChangeEventTime:function(item,newDate){var bagnodes=this.getStorebag().getNodes();for(i=0;i<bagnodes.length;i++){this.setCalendarEventFromBagNode(bagnodes[i]);}},patch_onChangeEventDateTime:function(item,newDate,newTime){var bagnodes=this.getStorebag().getNodes();for(i=0;i<bagnodes.length;i++){this.setCalendarEventFromBagNode(bagnodes[i]);}}});dojo.declare("gnr.widgets.RadioButton",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='RadioButton';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'action,callback');var label=objectPop(attributes,'label');objectPop(attributes,'width');attributes.name=objectPop(attributes,'group');if(label){attributes['id']=attributes['id']||'id_'+sourceNode._id;savedAttrs['label']=label;savedAttrs['labelattrs']=objectExtract(attributes,'label_*');}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var label=savedAttrs['label'];if(label){var labelattrs=savedAttrs['labelattrs'];labelattrs['for']=widget.id;labelattrs['margin_left']=labelattrs['margin_left']||'3px';var domnode=genro.wdg.create('label',widget.domNode.parentNode,labelattrs);domnode.innerHTML=label;}
if(sourceNode.hasDynamicAttr('value')){var value=sourceNode.getAttributeFromDatasource('value');widget.setAttribute('checked',value);}},patch_onClick:function(e){var action=this.sourceNode.getInheritedAttributes().action;if(action){dojo.hitch(this.sourceNode,funcCreate(action))(this.sourceNode.attr,this.sourceNode,e);}},patch_setValue:function(value,pc){if(value==null){value="";}
this.setAttribute('checked',value);}});dojo.declare("gnr.widgets.CheckBox",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='CheckBox';},creating:function(attributes,sourceNode){objectPop(attributes,'width');var savedAttrs=objectExtract(attributes,'action,callback');var label=objectPop(attributes,'label');if(label){attributes['id']=attributes['id']||'id_'+sourceNode._id;savedAttrs['label']=label;savedAttrs['labelattrs']=objectExtract(attributes,'label_*');}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){if(sourceNode._gnrcheckbox_wrapper){if(sourceNode._gnrcheckbox_wrapper.parentNode){sourceNode._gnrcheckbox_wrapper.parentNode.removeChild(sourceNode._gnrcheckbox_wrapper);}
delete sourceNode._gnrcheckbox_wrapper;}
var label=savedAttrs['label'];var dn=widget.domNode;var pn=widget.domNode.parentNode;var gnrcheckbox_wrapper=document.createElement('div')
gnrcheckbox_wrapper.setAttribute('class','gnrcheckbox_wrapper')
pn.replaceChild(gnrcheckbox_wrapper,dn);gnrcheckbox_wrapper.appendChild(dn);sourceNode._gnrcheckbox_wrapper=gnrcheckbox_wrapper;if(label){if(sourceNode._labelNode){sourceNode._labelNode.parentNode.removeChild(sourceNode._labelNode);delete sourceNode._labelNode;}
var labelattrs=savedAttrs['labelattrs'];labelattrs['for']=widget.id;labelattrs['margin_left']=labelattrs['margin_left']||'3px';var domnode=genro.wdg.create('label',widget.domNode.parentNode,labelattrs);domnode.innerHTML=label;sourceNode._labelNode=domnode;}
if(sourceNode.hasDynamicAttr('value')){var value=sourceNode.getAttributeFromDatasource('value');widget.setAttribute('checked',value);}},mixin_setHidden:function(hidden){if(this.sourceNode._hiddenTargets){this.sourceNode.setHidden(hidden);}else{dojo.style(this.sourceNode._gnrcheckbox_wrapper,'display',(hidden?'none':''));}},_getKeeperRoot:function(sourceNode){return sourceNode._gnrcheckbox_wrapper;},mixin_displayMessage:function(){},patch_onClick:function(e){var actionScope=this.sourceNode.attributeOwnerNode('action');if(actionScope){var action=actionScope.attr.action;if(action&&actionScope.attr.tag!='button'){dojo.hitch(this,funcCreate(action))(this.sourceNode.attr,this.sourceNode,e);}}},patch_setValue:function(value,pc){this.setAttribute('checked',value);},cell_onCreating:function(gridEditor,colname,colattr){colattr['margin']='auto';},});dojo.declare("gnr.widgets.TextArea_",gnr.widgets.baseDojo,{constructor:function(){this._domtag='textarea';this._dojotag='TextArea';},creating:function(attributes,sourceNode){var x=1;},created:function(widget,savedAttrs,sourceNode){var x=1;}});dojo.declare("gnr.widgets._BaseTextBox",gnr.widgets.baseDojo,{formattedValueHandler:function(widget,savedAttrs,sourceNode){if((sourceNode.attr.format||sourceNode.attr.mask)&&sourceNode.attr.displayFormattedValue){sourceNode.freeze();sourceNode._('span',{'innerHTML':sourceNode.attr.value+'?_formattedValue',_class:'formattedViewer',_attachPoint:'focusNode.parentNode'});sourceNode.unfreeze();dojo.addClass(widget.focusNode.parentNode,'formattedTextBox');}},patch_displayMessage:function(message){if(!isNullOrBlank(this.value)){this.displayMessage_replaced(message);}},connectFocus:function(widget,savedAttrs,sourceNode){if(sourceNode.attr._autoselect&&!genro.isMobile){dojo.connect(widget,'onFocus',widget,function(e){setTimeout(dojo.hitch(this,'selectAllInputText'),1);});}},mixin_selectAllInputText:function(){dijit.selectInputText(this.focusNode);},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'shortcuts');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){this._baseTextBox_created(widget,savedAttrs,sourceNode);},_baseTextBox_created:function(widget,savedAttrs,sourceNode){if(genro.isMobile){widget.focusNode.setAttribute('autocapitalize','none');widget.focusNode.setAttribute('autocomplete','off');widget.focusNode.setAttribute('autocorrect','off');}
this.connectFocus(widget,savedAttrs,sourceNode);if(savedAttrs.shortcuts){setTimeout(function(){widget.setShortcuts(savedAttrs.shortcuts)},1)}},cell_onDestroying:function(sourceNode,gridEditor,editingInfo){dijit.hideTooltip(sourceNode.widget.domNode);}});dojo.declare("gnr.widgets.TextBox",gnr.widgets._BaseTextBox,{constructor:function(application){this._domtag='input';this._dojotag='ValidationTextBox';},creating:function(attributes,sourceNode){objectPop(attributes,'multivalue');objectPop(attributes,'multivalueCb');attributes.trim=(attributes.trim==false)?false:true;var savedAttrs=objectExtract(attributes,'shortcuts');return savedAttrs;},onBuilding:function(sourceNode){var attr=sourceNode.attr;var multivalue=attr.multivalue||attr.multivalueCb;if(attr.multivalueCb){sourceNode._getMultiValue=funcCreate('return '+attr.multivalueCb,null,sourceNode);}
if(multivalue){sourceNode.freeze();sourceNode._('tooltipMultivalue',{});sourceNode.unfreeze(true);}},onSettingValueInData:function(sourceNode,value,valueAttr){if(sourceNode._onSettingValueInData){sourceNode._onSettingValueInData(sourceNode,value,valueAttr);}
return value;}});dojo.declare("gnr.widgets.DateTextBox",gnr.widgets._BaseTextBox,{constructor:function(){this._domtag='input';this._dojotag='DateTextBox';},onChanged:function(widget,value){if(value){this._doChangeInData(widget.domNode,widget.sourceNode,value,{dtype:'D'});}
else{this._doChangeInData(widget.domNode,widget.sourceNode,null);}},patch__onFocus:function(evt){},creating:function(attributes,sourceNode){attributes.constraints=objectExtract(attributes,'formatLength,datePattern,fullYear,min,max,strict,locale');if('popup'in attributes&&(objectPop(attributes,'popup')==false)){attributes.popupClass=null;}
if(this.dojo__selector=='datetime'){attributes.popup=false;sourceNode.attr.noIcon=true;if(objectPop(attributes,'seconds')){attributes.constraints.timePattern='HH:mm:ss';}}},created:function(widget,savedAttrs,sourceNode){if(!sourceNode.attr.noIcon){var focusNode;var curNode=sourceNode;genro.dom.addClass(widget.focusNode,'comboArrowTextbox')
var box=sourceNode._('div',{cursor:'pointer',width:'20px',tabindex:-1,position:'absolute',top:0,bottom:0,right:0,connect_onclick:function(){widget._open();}});box._('div',{_class:'dateTextBoxCal',position:'absolute',top:0,bottom:0,left:0,right:0,tabindex:-1});this.connectFocus(widget,savedAttrs,sourceNode);}},patch_parse:function(value,constraints){if(value&&!this._focused){var r,d1,d2,y;var info=dojo.date.locale._parseInfo(constraints);var tokens=info.tokens;var datesplit=value.split(' ');var match=datesplit[0].match(/^(\d{2})(\d{2})(\d{2}|\d{4})$/);var doSetValue=false;if(match){datesplit[0]=match[1]+'/'+match[2]+'/'+match[3];doSetValue=true;}
if(constraints.selector=='datetime'){doSetValue=true;var timestr=datesplit[1];var timematch=timestr.match(/^(\d{2})(\d{2})?(\d{2})?$/);if(!timematch){timematch=timestr.match(/^(\d{2}):(\d{2})(?::(\d{2}))?$/);}
if(!timematch){timematch=['00:00:00','00','00','00'];}
var tl=[timematch[1],timematch[2]];if(constraints.timePattern=='HH:mm:ss'){tl.push(timematch[3]||'00');}
datesplit[1]=tl.join(':');}
value=datesplit.join(' ');var re=new RegExp("^"+info.regexp+"$");match=re.exec(value);if(match){var d,m,y,hours,minutes,seconds;if(tokens[0][0]=='d'){d=match[1];m=match[2];}else{d=match[2];m=match[1];}
d=parseInt(d);m=parseInt(m)-1;y=parseInt(match[3]);if(constraints.selector=='datetime'){hours=parseInt(match[4]||'0');minutes=parseInt(match[5]||'0');seconds=parseInt(match[6]||'0');}else{hours=0;minutes=0;seconds=0;}
if(y<100){var pivotYear='pivotYear'in this.sourceNode.attr?this.sourceNode.attr.pivotYear:20;var year=''+new Date().getFullYear();var century=year.substring(0,2)*100;var cutoff=Math.min(Number(year.substring(2,4))+pivotYear,99);var y=(y<cutoff)?century+y:century-100+y;}
r=new Date(y,m,d,hours,minutes,seconds);if(doSetValue){var that=this;setTimeout(function(){that.setValue(r,true);});}
return r;}else{var that=this;this.setValue(null);var sn=this.sourceNode;sn._waiting_rpc=true;genro.serverCall('decodeDatePeriod',{datestr:value},function(v){if(v.getItem('from')){that.setValue(v.getItem('from'),true);}
if(that.sourceNode.attr.period_to){that.sourceNode.setRelativeData(that.sourceNode.attr.period_to,v.getItem('to'));}
sn._waiting_rpc=false;});return;}}
return dojo.date.locale.parse(value,constraints)||undefined;}});dojo.declare("gnr.widgets.DatetimeTextBox",gnr.widgets.DateTextBox,{dojo__selector:'datetime'});dojo.declare("gnr.widgets.TimeTextBox",gnr.widgets._BaseTextBox,{onChanged:function(widget,value){if(value){this._doChangeInData(widget.domNode,widget.sourceNode,value,{dtype:'H'});}
else{this._doChangeInData(widget.domNode,widget.sourceNode,null);}},creating:function(attributes,sourceNode){if('ftype'in attributes){attributes.constraints['type']=objectPop(attributes['ftype']);}
if('popup'in attributes&&(objectPop(attributes,'popup')==false)){attributes.popupClass=null;}},mixin_setPickInterval:function(interval){var timeInt='T00:'+interval+':00';this.constraints.clickableIncrement=timeInt;}});dojo.declare("gnr.widgets.NumberTextBox",gnr.widgets._BaseTextBox,{constructor:function(application){this._domtag='input';this._dojotag='NumberTextBox';},creating:function(attributes,sourceNode){attributes._class=attributes._class?attributes._class+' numberTextBox':'numberTextBox';var format=objectPop(attributes,'format');var places=objectPop(attributes,'places');attributes.constraints=objectExtract(attributes,'min,max,pattern,round,currency,fractional,symbol,strict,locale');attributes.constraints.pattern=attributes.constraints.pattern||format;if(!places&&attributes.constraints.pattern&&attributes.constraints.pattern.indexOf('.')){var s=attributes.constraints.pattern.split('.')[1];if(s){places='0,'+s.length;}}
sourceNode._parseDict=places?{places:places}:{};if('ftype'in attributes){attributes.constraints['type']=objectPop(attributes['ftype']);}},created:function(widget,savedAttrs,sourceNode){this._baseTextBox_created(widget,savedAttrs,sourceNode);if(dojo.number._parseInfo().decimal==','){dojo.connect(widget,'onkeyup',function(evt){if(evt.key=='.'){widget.textbox.value=widget.textbox.value.replace('.',',');}});}
widget.setValue(sourceNode.getRelativeData(sourceNode.attr.value));},onSettingValueInData:function(sourceNode,value,valueAttr){if(isNullOrBlank(value)){value=null;}
return value;},patch_format:function(v,c){if(isNullOrBlank(v)){return'';}else{return this.format_replaced(v,c);}},patch_getValue:function(){var displayedValue=this.getDisplayedValue();var result=this.parse(displayedValue,this.constraints);if(isNaN(result)){result=this.parse(displayedValue,this.sourceNode._parseDict)}
return result;},patch_isValid:function(isFocused){if(isFocused){return true;}
return this.validator(this.textbox.value,this.sourceNode._parseDict)||this.validator(this.textbox.value,this.constraints);},cell_onCreating:function(gridEditor,colname,colattr){if(colattr._formats){colattr.format=colattr.format||colattr._formats.format;}}});dojo.declare("gnr.widgets.CurrencyTextBox",gnr.widgets.NumberTextBox,{constructor:function(application){this._domtag='input';this._dojotag='CurrencyTextBox';}});dojo.declare("gnr.widgets.NumberSpinner",gnr.widgets.NumberTextBox,{constructor:function(application){this._domtag='input';this._dojotag='NumberSpinner';}});dojo.declare("gnr.widgets.Slider",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='CurrencyTextBox';},created:function(widget,savedAttrs,sourceNode){dojo.connect(widget.sliderHandle,'onmousedown',function(){widget._ignoreDataChanges=true;})
dojo.connect(window,'onmouseup',function(){widget._ignoreDataChanges=false;})}});dojo.declare("gnr.widgets.HorizontalSlider",gnr.widgets.Slider,{constructor:function(application){this._domtag='div';this._dojotag='HorizontalSlider';}});dojo.declare("gnr.widgets.VerticalSlider",gnr.widgets.Slider,{constructor:function(application){this._domtag='div';this._dojotag='VerticalSlider';}});dojo.declare("gnr.widgets.BaseCombo",gnr.widgets.baseDojo,{creating:function(attributes,sourceNode){objectExtract(attributes,'maxLength,_type');var values=objectPop(attributes,'values');var val,xval;if(values){var store=this.storeFromValues(values);attributes.searchAttr='caption';}else{var storeAttrs=objectExtract(attributes,'storepath,storeid,storecaption');var savedAttrs={};var store=new gnr.GnrStoreBag({datapath:sourceNode.absDatapath(storeAttrs.storepath)});attributes.searchAttr=store.rootDataNode().attr['caption']||storeAttrs['storecaption']||'caption';attributes.autoComplete=attributes.autoComplete||false;store._identifier=store.rootDataNode().attr['id']||storeAttrs['storeid']||'id';}
store.searchAttr=attributes.searchAttr;attributes.store=store;return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var tag='cls_'+sourceNode.attr.tag;dojo.addClass(widget.domNode.childNodes[0],tag);this.connectFocus(widget);this.connectForUpdate(widget,sourceNode);if(dojo_version=='1.1'){if(dojo.isSafari){dojo.connect(widget.focusNode,'onkeydown',widget,'_onKeyPress');}}},mixin_onSpeechEnd:function(){this._startSearchFromInput();},storeFromValues:function(values){var localStore=new gnr.GnrBag();if(!values){values=[];}else{var ch=values.indexOf('\n')>=0?'\n':',';values=values.split(ch);}
for(var i=0;i<values.length;i++){val=values[i];xval={};if(val.indexOf(':')>0){val=val.split(':');xval['id']=val[0];xval['caption']=val[1];}else{xval['id']=val;xval['caption']=val;}
localStore.setItem('root.r_'+i,null,xval);}
var newstore=new gnr.GnrStoreBag({mainbag:localStore});newstore._identifier='id';return newstore;},mixin_setValues:function(values){this.store=this.gnr.storeFromValues(values);},connectFocus:function(widget,savedAttrs,sourceNode){var timeoutId=null;if(!genro.isMobile){dojo.connect(widget,'onFocus',widget,function(e){timeoutId=setTimeout(dojo.hitch(this,'selectAllInputText'),300);});}
dojo.connect(widget,'onBlur',widget,function(e){clearTimeout(timeoutId);this.validate(e);});},mixin_selectAllInputText:function(){dijit.selectInputText(this.focusNode);},mixin__updateSelect:function(item){var row=item&&this.isValid()?(item.attr||{}):{};if(this.sourceNode.attr.selectedRecord){var path=this.sourceNode.attrDatapath('selectedRecord');this.sourceNode.setRelativeData(path,new gnr.GnrBag(row));}
if(this.sourceNode.attr.selectedCaption){var path=this.sourceNode.attrDatapath('selectedCaption');this.sourceNode.setRelativeData(path,row['caption'],null,false,'selected_');}
var selattr=objectExtract(this.sourceNode.attr,'selected_*',true);var val;for(var sel in selattr){var path=this.sourceNode.attrDatapath('selected_'+sel);val=row[sel];if(this.sourceNode._selectedSetter){this.sourceNode._selectedSetter(path,val);}
else{this.sourceNode.setRelativeData(path,val,null,false,'selected_');}}
if(this.sourceNode.selectedCb){this.sourceNode.selectedCb(item);}
if(this.sourceNode._selectedCb){this.sourceNode._selectedCb(item);}},connectForUpdate:function(widget,sourceNode){var selattr=objectExtract(widget.sourceNode.attr,'selected_*',true);if(objectNotEmpty(selattr)||sourceNode.attr.selectedCaption){dojo.connect(widget,'_doSelect',widget,function(){this._updateSelect(this.item);});}},doChangeInData:function(sourceNode,value,valueAttr){var displayedValue=sourceNode.widget.getDisplayedValue();if(value!=displayedValue){valueAttr['_displayedValue']=displayedValue;}},patch_displayMessage:function(message){if(!isNullOrBlank(this.value)){this.displayMessage_replaced(message);}}});dojo.declare("gnr.widgets.GeoCoderField",gnr.widgets.BaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='ComboBox';},creating:function(attributes,sourceNode){objectExtract(attributes,'maxLength,_type,country');if(sourceNode.attr._virtual_column){attributes.value='^.$'+sourceNode.attr._virtual_column;sourceNode.attr.value=attributes.value;attributes.readOnly=false;}
var savedAttrs={};var localStore=new gnr.GnrBag();var store=new gnr.GnrStoreBag({mainbag:localStore});attributes.searchAttr='caption';attributes.hasDownArrow=false;store._identifier='id';attributes.store=store;return savedAttrs;},mixin_onSpeechEnd:function(){this.geocodevalue();},mixin_geocodevalue:function(){var address=this.textbox.value;if(address==this.geocoder.resultAddress&&address.length==1){return;}
clearTimeout(this.waitingDelay);this.waitingDelay=setTimeout(dojo.hitch(this,function(){var geopars={'address':address}
if(this.sourceNode.attr.country){var country=this.sourceNode.getAttributeFromDatasource('country')
if(country){geopars['componentRestrictions']={'country':country}}}
this.geocoder.geocode(geopars,dojo.hitch(this,'handleGeocodeResults'));}),200);},patch__onKeyPress:function(evt){if(evt.altKey||(evt.ctrlKey&&evt.charCode!=118)){return;}
var doSearch=false;var pw=this._popupWidget;var dk=dojo.keys;if(this._isShowingNow){pw.handleKey(evt);}
switch(evt.keyCode){case dk.PAGE_DOWN:case dk.DOWN_ARROW:if(!this._isShowingNow||this._prev_key_esc){this._arrowPressed();doSearch=true;}else{this._announceOption(pw.getHighlightedOption());}
dojo.stopEvent(evt);this._prev_key_backspace=false;this._prev_key_esc=false;break;case dk.PAGE_UP:case dk.UP_ARROW:if(this._isShowingNow){this._announceOption(pw.getHighlightedOption());}
dojo.stopEvent(evt);this._prev_key_backspace=false;this._prev_key_esc=false;break;case dk.ENTER:var highlighted;if(this._isShowingNow&&(highlighted=pw.getHighlightedOption())){if(highlighted==pw.nextButton){this._nextSearch(1);dojo.stopEvent(evt);break;}else if(highlighted==pw.previousButton){this._nextSearch(-1);dojo.stopEvent(evt);break;}}else{this.setDisplayedValue(this.getDisplayedValue());}
evt.preventDefault();case dk.TAB:var newvalue=this.getDisplayedValue();if(pw&&(newvalue==pw._messages["previousMessage"]||newvalue==pw._messages["nextMessage"])){break;}
if(this._isShowingNow){this._prev_key_backspace=false;this._prev_key_esc=false;if(pw.getHighlightedOption()){pw.setValue({target:pw.getHighlightedOption()},true);}
this._hideResultList();}
break;case dk.SPACE:this._prev_key_backspace=false;this._prev_key_esc=false;if(this._isShowingNow&&pw.getHighlightedOption()){dojo.stopEvent(evt);this._selectOption();this._hideResultList();}else{doSearch=true;}
break;case dk.ESCAPE:this._prev_key_backspace=false;this._prev_key_esc=true;if(this._isShowingNow){dojo.stopEvent(evt);this._hideResultList();}
this.inherited(arguments);break;case dk.DELETE:case dk.BACKSPACE:this._prev_key_esc=false;this._prev_key_backspace=true;doSearch=true;break;case dk.RIGHT_ARROW:case dk.LEFT_ARROW:this._prev_key_backspace=false;this._prev_key_esc=false;break;default:this._prev_key_backspace=false;this._prev_key_esc=false;if(dojo.isIE||evt.charCode!=0){doSearch=true;}}
if(this.searchTimer){clearTimeout(this.searchTimer);}
if(doSearch){setTimeout(dojo.hitch(this,"geocodevalue"),1);}},patch__onBlur:function(){if(this._popupWidget&&!this.item){this._popupWidget.highlightFirstOption();var highlighted=this._popupWidget.getHighlightedOption();this._popupWidget.setValue({target:highlighted.item?highlighted.item:null},true);}
this.store.mainbag=new gnr.GnrBag();},created:function(widget,savedAttrs,sourceNode){var tag='cls_'+sourceNode.attr.tag;dojo.addClass(widget.domNode.childNodes[0],tag);this.connectForUpdate(widget,sourceNode);if(dojo_version=='1.1'){if(dojo.isSafari){dojo.connect(widget.focusNode,'onkeydown',widget,'_onKeyPress');}}
genro.google().setGeocoder(widget);},mixin_handleGeocodeResults:function(results,status){this.store.mainbag=new gnr.GnrBag();if(status==google.maps.GeocoderStatus.OK){for(var i=0;i<results.length;i++){formatted_address=results[i].formatted_address;var details={id:i,caption:formatted_address,formatted_address:formatted_address};var address_components=results[i].address_components;for(var a in address_components){var address_component=address_components[a];details[address_component.types[0]]=address_component.short_name;details[address_component.types[0]+'_long']=address_component.long_name;}
details['street_address']=details['route_long']+', '+(details['street_number']||'??');var street_number=details['street_number']||'??';if(details['subpremise']){street_number=details['subpremise']+'/'+street_number;}
details['street_address_eng']=street_number+' '+details['route_long'];var position=results[i].geometry.location;details['position']=position.lat()+','+position.lng();this.store.mainbag.setItem('root.r_'+i,null,details);}}else if(status==google.maps.GeocoderStatus.ZERO_RESULTS){this._updateSelect(this.store.mainbag);};var firstline=this.store.mainbag.getItem('#0');if(false&&firstline&&firstline.len()==1){this.setValue(this.store.mainbag.getItem('#0.#0?caption'),true);this._updateSelect(this.store.mainbag.getNode('#0.#0'));}
else{this._startSearch("");}
this.searchOnBlur=false;}});dojo.declare("gnr.widgets.DynamicBaseCombo",gnr.widgets.BaseCombo,{_autoselectFirstOption:false,creating:function(attributes,sourceNode){var savedAttrs={};attributes.httpMethod=attributes.httpMethod||genro.extraFeatures.wsk_dbselect?'WSK':null;var hasDownArrow;if(attributes.hasDownArrow){attributes.limit=attributes.limit||0;}else{attributes.hasDownArrow=false;}
if(attributes.readOnly){attributes.hasDownArrow=false;attributes['tabindex']=-1;}
var resolverAttrs=objectExtract(attributes,'method,columns,limit,auxColumns,hiddenColumns,alternatePkey,rowcaption,order_by,preferred,invalidItemCondition');resolverAttrs['notnull']=attributes['validate_notnull'];savedAttrs['auxColumns']=resolverAttrs['auxColumns'];var selectedColumns=objectExtract(attributes,'selected_*');var selectedCb=objectPop(attributes,'selectedCb');if(selectedCb){sourceNode._selectedCb=funcCreate(selectedCb,'item',sourceNode);}
var selectedSetter=objectPop(attributes,'selectedSetter');if(selectedSetter){sourceNode._selectedSetter=funcCreate(selectedSetter,'path,value',sourceNode);}
if(objectNotEmpty(selectedColumns)){var hiddenColumns;if('hiddenColumns'in resolverAttrs){hiddenColumns=resolverAttrs['hiddenColumns'].split(',');for(var i=0;i<hiddenColumns.length;i++){selectedColumns[hiddenColumns[i]]=null;}}
hiddenColumns=[];for(hiddenColumn in selectedColumns){hiddenColumns.push(hiddenColumn);}
resolverAttrs['hiddenColumns']=hiddenColumns.join(',');}
objectExtract(attributes,'condition_*');resolverAttrs['condition']=sourceNode.attr.condition;objectUpdate(resolverAttrs,objectExtract(sourceNode.attr,'condition_*',true));resolverAttrs['exclude']=sourceNode.attr['exclude'];resolverAttrs._id='';resolverAttrs._querystring='';var storeAttrs=objectExtract(attributes,'store_*');var store;savedAttrs['record']=objectPop(storeAttrs,'record');attributes.searchAttr=storeAttrs['caption']||'caption';var sw=objectExtract(attributes,'switch_*');var switches={};for(var k in sw){var ks=k.split('_');if(ks.length==1){switches[k]={'search':new RegExp('^'+sw[k])};objectUpdate(switches[k],objectExtract(sourceNode.attr,'switch_'+k+'_*',true));if(switches[k].action){switches[k].action=funcCreate(switches[k].action,'match',sourceNode);}}}
switches=objectNotEmpty(switches)?switches:null;store=new gnr.GnrStoreQuery({'searchAttr':attributes.searchAttr,_parentSourceNode:sourceNode,switches:switches});store._identifier=resolverAttrs['alternatePkey']||storeAttrs['id']||'_pkey';resolverAttrs._sourceNode=sourceNode;var resolver=this.resolver(sourceNode,attributes,resolverAttrs,savedAttrs);resolver.sourceNode=sourceNode;store.rootDataNode().setResolver(resolver);attributes.searchDelay=attributes.searchDelay||300;attributes.autoComplete=attributes.autoComplete||false;attributes.ignoreCase=(attributes.ignoreCase==false)?false:true;attributes.store=store;savedAttrs['connectedArrowMenu']=sourceNode.attr.connectedMenu;savedAttrs['connectedMenu']=null
return savedAttrs;},versionpatch_11__onArrowMouseDown:function(e){if(this._downArrowMenu){dojo.stopEvent(e);}else{this._onArrowMouseDown_replaced(e);}},mixin_clearCache:function(pkey){this.store.clearCache(pkey);},mixin_setCondition:function(value,kw){var vpath=this.sourceNode.attr.value;var currvalue=this.sourceNode.getRelativeData(vpath);var reskwargs=this.store.rootDataNode().getResolver().kwargs;if(reskwargs.notnull){reskwargs=objectUpdate({},reskwargs);var reskwargs=objectUpdate(reskwargs,{limit:2,_querystring:'*',notnull:true});var singleOption=genro.serverCall(objectPop(reskwargs,'method'),reskwargs);if(singleOption._value.len()==1){currvalue=singleOption._value.getAttr('#0')[this.store._identifier];}}
if(!isNullOrBlank(currvalue)){this.clearCache();this.setValue(null,true);this.setValue(currvalue,true);}},mixin_onSetValueFromItem:function(item,priorityChange){if(!item.attr.caption){return;}
if(priorityChange&&!this.item){this.item=item;}
if(this.sourceNode.editedRowIndex!=null&&priorityChange){this._updateSelect(item);}
else{if(priorityChange){this._updateSelect(item);}else{}}},connectForUpdate:function(widget,sourceNode){return;},onDataChanged:function(widget){},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.auxColumns){widget._popupWidget=new gnr.Gnr_ComboBoxMenu({onChange:dojo.hitch(widget,widget._selectOption)});dojo.connect(widget,'open',function(){var popup=this._popupWidget.domNode.parentNode;var popupcoords=dojo.coords(popup);var bodycoords=dojo.coords(dojo.body());var popupDeltaOverflow=(popupcoords.x+popupcoords.w)-bodycoords.w+10;if(popupDeltaOverflow>0){popup.style.left=(parseInt(popup.style.left)-popupDeltaOverflow)+'px';}
var that=this;setTimeout(function(){if(that.gnr._autoselectFirstOption){that._popupWidget.highlightFirstOption();}},1);});}else{dojo.connect(widget,'_openResultList',function(){if(widget.gnr._autoselectFirstOption){widget._popupWidget.highlightFirstOption();}});}
this.connectForUpdate(widget,sourceNode);var tag='cls_'+sourceNode.attr.tag;dojo.addClass(widget.domNode.childNodes[0],tag);this.connectFocus(widget,savedAttrs,sourceNode);if(dojo_version=='1.1'){if(dojo.isSafari){dojo.connect(widget.focusNode,'onkeydown',widget,'_onKeyPress');}}
if(savedAttrs.connectedArrowMenu&&widget.downArrowNode){var connectedMenu=savedAttrs.connectedArrowMenu;genro.src.onBuiltCall(function(){var menu=dijit.byId(connectedMenu);if(menu){menu.bindDomNode(widget.downArrowNode);widget._downArrowMenu=true;}});}},});dojo.declare("gnr.widgets.dbBaseCombo",gnr.widgets.DynamicBaseCombo,{resolver:function(sourceNode,attributes,resolverAttrs,savedAttrs){objectUpdate(resolverAttrs,objectExtract(attributes,'dbtable,table,selectmethod,weakCondition,excludeDraft,ignorePartition,distinct,httpMethod,dbstore'));resolverAttrs.dbtable=resolverAttrs.dbtable||objectPop(resolverAttrs,'table');if('_storename'in sourceNode.attr){resolverAttrs._storename=sourceNode.attr._storename;}
if(resolverAttrs.dbstore){resolverAttrs.temp_dbstore=objectPop(resolverAttrs,'dbstore')}
resolverAttrs['method']=resolverAttrs['method']||'app.dbSelect';savedAttrs['dbtable']=resolverAttrs['dbtable'];sourceNode.registerSubscription('changeInTable',sourceNode,function(kw){if(this.attr.dbtable==kw.table){this.widget.clearCache(kw.pkey);}});return new gnr.GnrRemoteResolver(resolverAttrs,true,0);},mixin_setDbtable:function(value){this.store.rootDataNode()._resolver.kwargs.dbtable=value;}});dojo.declare("gnr.widgets.LocalBaseCombo",gnr.widgets.DynamicBaseCombo,{resolver:function(sourceNode,attributes,resolverAttrs){objectUpdate(resolverAttrs,objectExtract(attributes,'kw_*'));var callback=objectPop(attributes,'callback');if(callback){var callback=funcCreate(callback,'kw');resolverAttrs.method=function(kw){var envelope=new gnr.GnrBag();var result=new gnr.GnrBag();var resultObj=callback.call(this,kw);var headers=resultObj.headers;var rows=resultObj.data||[];var i=0;rows.forEach(function(r){result.setItem('r_'+i,null,r);i++;})
var resultAttr={};if(headers){var columnslist=[];var headerslist=[];headers.split(',').forEach(function(c){c=c.split(':');columnslist.push(c[0]);headerslist.push(c[1]);})
resultAttr.columns=columnslist.join(',');resultAttr.headers=headerslist.join(',');}
envelope.setItem('result',result,resultAttr);return envelope.popNode('result');};}else{resolverAttrs.method=funcCreate(resolverAttrs.method,'kw');}
return new gnr.GnrBagCbResolver({method:objectPop(resolverAttrs,'method'),parameters:resolverAttrs},true);}});dojo.declare("gnr.widgets.RemoteBaseCombo",gnr.widgets.DynamicBaseCombo,{resolver:function(sourceNode,attributes,resolverAttrs){objectUpdate(resolverAttrs,objectExtract(attributes,'kw_*'));return new gnr.GnrRemoteResolver(resolverAttrs,true,0);}});dojo.declare("gnr.widgets.FilteringSelect",gnr.widgets.BaseCombo,{_validatingWidget:true,constructor:function(application){this._domtag='div';this._dojotag='FilteringSelect';},patch_setValue:function(value,priorityChange){var self=this;var handleFetchByIdentity=function(item,priorityChange){if(!isNullOrBlank(item)){if(self.store.isItemLoaded(item)){self._callbackSetLabel([item],undefined,priorityChange);}else{self.store.loadItem({item:item,onItem:function(result,dataObject){self._callbackSetLabel(result,dataObject,priorityChange);}});}}else{self.valueNode.value=null;self.setDisplayedValue('')}};this.store.fetchItemByIdentity({identity:value,onItem:function(item){handleFetchByIdentity(item,priorityChange);}});},});dojo.declare("gnr.widgets.ComboBox",gnr.widgets.BaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='ComboBox';}});dojo.declare("gnr.widgets.BaseSelect",null,{_validatingWidget:true,_autoselectFirstOption:true,constructor:function(application){this._domtag='div';this._dojotag='FilteringSelect';},connectForUpdate:function(widget,sourceNode){dojo.connect(widget,'_setValueFromItem',widget,'onSetValueFromItem');if(!("validate_select"in sourceNode.attr)){sourceNode.attr.validate_select=true;}
if(!("validate_select_error"in sourceNode.attr)){sourceNode.attr.validate_select_error='Not existing value';}},versionpatch_11__setBlurValue:function(){var displayedValue=this.getDisplayedValue();var lastValueReported=this._lastValueReported;var value;if(this._lastDisplayedValue==displayedValue){value=this.getValue();}
var pw=this._popupWidget;if(pw&&(displayedValue==pw._messages["previousMessage"]||displayedValue==pw._messages["nextMessage"])){this.setValue(this._lastValueReported,true);}else{if(isNullOrBlank(displayedValue)){this.setValue(null,true);this.setDisplayedValue('');}else{if(isNullOrBlank(value)){this.setValue(null,true);this.sourceNode._wrongSearch=displayedValue;if(!this.sourceNode.attr.firstMatchDisabled){this.setDisplayedValue(displayedValue,true);}}else
{this.setValue(value,true);}}}},cell_onCreating:function(gridEditor,colname,colattr){if(!gridEditor.editorPars){return;}
var cellmap=gridEditor.grid.cellmap;var related_setter={};var grid=gridEditor.grid;colattr['dbtable']=colattr['dbtable']||colattr['related_table'];var hiddencol=colattr['hiddenColumns']?colattr['hiddenColumns'].split(','):[];for(var k in cellmap){if(cellmap[k].relating_column==colname){hiddencol.push(cellmap[k].related_column);related_setter[cellmap[k].related_column.replace(/\W/g,'_')]=cellmap[k].field_getter;}}
colattr['hiddenColumns']=hiddencol.join(',');colattr.selectedSetter=function(path,value){if(path.indexOf('.')>=0){path=path.split('.');path=path[path.length-1];}
this.setCellValue(path,value);}
colattr.selectedCb=function(item){var selectRow=item?objectUpdate({},item.attr):{};var rowNode=this.getRelativeData().getParentNode();var values={};for(var k in related_setter){values[related_setter[k]]=selectRow[k];}
grid.collectionStore().updateRow(this.editedRowIndex,values);}}});dojo.declare("gnr.widgets.dbSelect",[gnr.widgets.dbBaseCombo,gnr.widgets.BaseSelect],{});dojo.declare("gnr.widgets.CallBackSelect",[gnr.widgets.LocalBaseCombo,gnr.widgets.BaseSelect],{});dojo.declare("gnr.widgets.RemoteSelect",[gnr.widgets.RemoteBaseCombo,gnr.widgets.BaseSelect],{});dojo.declare("gnr.widgets.dbComboBox",gnr.widgets.dbBaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='ComboBox';},connectForUpdate:function(widget,sourceNode){var selattr=objectExtract(widget.sourceNode.attr,'selected_*',true);if('selectedRecord'in widget.sourceNode.attr||objectNotEmpty(selattr)){dojo.connect(widget,'setValue',function(kw,priorityChange){if(priorityChange){var item=this.item||{attr:{}};this._updateSelect(item);}})}}});dojo.declare("gnr.widgets.DropDownButton",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='DropDownButton';},creating:function(attributes,sourceNode){var savedAttrs={};var buttoNodeAttr='height,width,padding';var savedAttrs=objectExtract(attributes,'fire_*');savedAttrs['_style']=genro.dom.getStyleDict(objectExtract(attributes,buttoNodeAttr));savedAttrs['action']=objectPop(attributes,'action');savedAttrs['fire']=objectPop(attributes,'fire');savedAttrs['arrow']=objectPop(attributes,'arrow');attributes['label']=attributes['label']||'';return savedAttrs;},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.arrow==false){var arrow=dojo.query(".dijitArrowButtonInner",widget.domNode);if(arrow.length>0){arrow=arrow[0];arrow.parentNode.removeChild(arrow);}}
if(savedAttrs['_style']){var buttonNode=dojo.query(".dijitButtonNode",widget.domNode)[0];dojo.style(buttonNode,savedAttrs['_style']);}},patch_addChild:function(dropDownContent){this.dropDown=dropDownContent;},patch_destroy:function(){if(this.dropDown){this.dropDown.destroyRecursive();}
this.destroy_replaced.call(this);},versionpatch_15_openDropDown:function(){var sourceNode=this.dropDown.sourceNode;if(sourceNode){sourceNode.refresh();this.dropDown=sourceNode.widget;}
this.openDropDown_replaced();},versionpatch_11__openDropDown:function(evtDomNode){var sourceNode=this.dropDown.sourceNode;if(sourceNode){sourceNode.refresh();this.dropDown=sourceNode.widget;}
var dropDown=this.dropDown;var oldWidth=dropDown.domNode.style.width;var self=this;var openKw={parent:this,popup:dropDown,around:evtDomNode||this.domNode,orient:this.isLeftToRight()?{'BL':'TL','BR':'TR','TL':'BL','TR':'BR'}:{'BR':'TR','BL':'TL','TR':'BR','TL':'BL'},onExecute:function(){self._closeDropDown(true);},onCancel:function(){self._closeDropDown(true);},onClose:function(){dropDown.domNode.style.width=oldWidth;self.popupStateNode.removeAttribute("popupActive");this._opened=false;}};if(this.sourceNode.attr.onOpeningPopup){this.sourceNode.attr.onOpeningPopup.call(this.sourceNode,openKw,evtDomNode);}
dijit.popup.open(openKw);if(this.domNode.offsetWidth>dropDown.domNode.offsetWidth){var adjustNode=null;if(!this.isLeftToRight()){adjustNode=dropDown.domNode.parentNode;var oldRight=adjustNode.offsetLeft+adjustNode.offsetWidth;}
dojo.marginBox(dropDown.domNode,{w:this.domNode.offsetWidth});if(adjustNode){adjustNode.style.left=oldRight-this.domNode.offsetWidth+"px";}}
this.popupStateNode.setAttribute("popupActive","true");this._opened=true;if(this.sourceNode.attr.onOpenedPopup){this.sourceNode.attr.onOpenedPopup.call(this.sourceNode,openKw,evtDomNode);}
if(dropDown.focus){dropDown.focus();}},patch__onBlur:function(){if(this.sourceNode.attr.modal){return;}
this._onBlur_replaced();},patch_startup:function(){if(!this.dropDown){var dropDownNode=dojo.query("[widgetId]",this.dropDownContainer)[0];this.dropDown=dijit.byNode(dropDownNode);delete this.dropDownContainer;}
dojo.body().appendChild(this.dropDown.domNode);this.dropDown.domNode.style.display="none";}});dojo.declare("gnr.widgets.uploadable",gnr.widgets.baseHtml,{onBuilding:function(sourceNode){var attr=sourceNode.attr;var crop=objectExtract(attr,'crop_*');var that=this;if(objectNotEmpty(crop)){var innerImage=objectExtract(attr,'src,placeholder,height,width,edit,upload_maxsize,upload_folder,upload_filename,upload_ext,zoomWindow,format,mask,border');if(innerImage.placeholder===true){innerImage.placeholder='/_gnr/11/css/icons/placeholder_img_dflt.png'}
innerImage.cr_width=crop.width;innerImage.cr_height=crop.height;innerImage['onerror']="this.sourceNode.setRelativeData(this.sourceNode.attr.src,null);"
attr.tag='div';objectUpdate(attr,crop)
attr.overflow='hidden';sourceNode._(this._domtag,innerImage,{'doTrigger':false});}else{var uploadAttr=objectExtract(attr,'upload_*');var cropAttr=objectExtract(attr,'cr_*',true);if(objectNotEmpty(uploadAttr)){attr.dropTarget=true;attr.dropTypes='Files,text/plain';attr.drop_ext=uploadAttr.ext||this._default_ext;var src=sourceNode.attr.src;attr.onDrop_text_html=function(dropInfo,data){console.log('texthtml',dropInfo,data)}
attr.onDrop_text_plain=function(dropInfo,data){if(sourceNode.form&&sourceNode.form.isDisabled()){genro.dlg.alert("The form is locked",'Warning');return false;}
sourceNode.domNode.onload=function(){that.centerImage(sourceNode,cropAttr);};sourceNode.setRelativeData(src,that.decodeUrl(sourceNode,data).formattedUrl);};var cbOnDropData=function(dropInfo,data){if(uploadAttr.maxsize&&data.size>uploadAttr.maxsize){var size_kb=uploadAttr.maxsize/1000
genro.dlg.alert("Image exeeds size limit ("+size_kb+"KB)",'Error');return false;}
if(sourceNode.form&&sourceNode.form.isDisabled()){genro.dlg.alert("The form is locked",'Warning');return false;}
if(objectNotEmpty(cropAttr)){var domnode=sourceNode.domNode;domnode.onload=function(){that.centerImage(sourceNode,cropAttr);};}
var filename=sourceNode.currentFromDatasource(uploadAttr.filename);if(!filename){genro.dlg.alert("Missing info to upload the image",'Warning');return false;}
if(uploadAttr.folder=='*'){var reader=new FileReader();reader.onload=function(event){sourceNode.setRelativeData(src,event.target.result);}
reader.readAsDataURL(data);}else{genro.rpc.uploadMultipart_oneFile(data,null,{uploadPath:sourceNode.currentFromDatasource(uploadAttr.folder),filename:filename,onResult:function(result){var url=this.responseText;sourceNode.setRelativeData(src,that.decodeUrl(sourceNode,url).formattedUrl);}});}}
sourceNode._('input','fakeinput',{hidden:true,type:'file',connect_onchange:function(evt){cbOnDropData({evt:evt},evt.target.files[0]);this.domNode.value=null;}});var uploadhandler_key=genro.isMobile?'selfsubscribe_doubletap':'connect_ondblclick';attr[uploadhandler_key]=function(){this.getValue().getNode('fakeinput').domNode.click();};attr.onDrop_dataUrl=function(dropInfo,data){cbOnDropData(dropInfo,data)}
attr.onDrop=function(dropInfo,files){cbOnDropData(dropInfo,files[0]);};}}},creating:function(attributes,sourceNode){var edit=objectPop(attributes,'edit');var savedAttrs={'edit':edit,zoomWindow:objectPop(attributes,'zoomWindow')};objectUpdate(attributes,this.decodeUrl(sourceNode,objectPop(attributes,'src')));if((!attributes.src)&&('placeholder'in sourceNode.attr)){attributes.src=sourceNode.getAttributeFromDatasource('placeholder');if(sourceNode.attr.cr_height){attributes.style="width:100%;height:100%";}}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var that=this;if(savedAttrs.edit){widget.onmousedown=function(e){return that.onMouseDown(e)}};if(savedAttrs.zoomWindow){dojo.connect(widget,'ondblclick',function(e){genro.openWindow(sourceNode.currentFromDatasource(this.src),'imagedetail',{'height':this.height,'width':this.width,'location':'no','menubar':'no','resizable':'yes','top':e.clientY,'left':e.clientX,'toolbar':'no','titlebar':'no','status':'no'});});};var url=widget.getAttribute('src')},setPlaceHolder:function(sourceNode){var domnode=sourceNode.domNode;var src=sourceNode.getAttributeFromDatasource('placeholder');domnode.setAttribute('src',src);if(sourceNode.attr.cr_height){domnode.setAttribute('style',"width:100%;height:100%");}},centerImage:function(sourceNode,cropAttr){var domnode=sourceNode.domNode;var margin_top=(domnode.clientHeight-parseInt(cropAttr.height))/2;var margin_left=(domnode.clientWidth-parseInt(cropAttr.width))/2;var currUrl=sourceNode.getAttributeFromDatasource('src');if(currUrl){var parsedUrl=parseURL(currUrl);if(parsedUrl.protocol=='data'){return;}
var params=parsedUrl.params;params=objectUpdate(params,{'v_y':margin_top,'v_x':margin_left});var url=this.encodeUrl(parsedUrl);sourceNode.setAttributeInDatasource('src',url,true);}},onEditImage:function(sourceNode,e){var dx=sourceNode.s_x-e.clientX;var dy=sourceNode.s_y-e.clientY;var body=dojo.body();sourceNode.s_x=e.clientX;sourceNode.s_y=e.clientY;var src=sourceNode.getAttributeFromDatasource('src');var parsedUrl=parseURL(src);var imgkw=parsedUrl.params;var v_x=parseInt(imgkw['v_x'])||0;var v_y=parseInt(imgkw['v_y'])||0;var v_z=parseFloat(imgkw['v_z'])||1;var v_r=parseInt(imgkw['v_r'])||0;if(sourceNode.edit_mode=='move'){imgkw['v_x']=parseInt((v_x+(dx/v_z)));imgkw['v_y']=parseInt((v_y+(dy/v_z)));body.style.cursor='move';}else if(sourceNode.edit_mode=='zoom'){v_z=v_z-(dy/100);imgkw['v_z']=(v_z<0.05?0.05:v_z).toFixed(2);body.style.cursor=dy>0?'n-resize':'s-resize';}else if(sourceNode.edit_mode=='rotate'){imgkw['v_r']=v_r+dy;body.style.cursor='crosshair';}
if(sourceNode.attr.cr_height){imgkw['v_h']=parseInt(sourceNode.attr.cr_height);imgkw['v_w']=parseInt(sourceNode.attr.cr_width);}
src=this.encodeUrl(parsedUrl);sourceNode.setAttributeInDatasource('src',src,true);},onEndEdit:function(sourceNode){dojo.body().style.cursor='auto';dojo.forEach(sourceNode.editConnections,function(c){dojo.disconnect(c);})},onMouseDown:function(e){var that=this;var modifiers=genro.dom.getEventModifiers(e);var sourceNode=e.target.sourceNode;sourceNode.edit_mode=(modifiers==='')?'move':(modifiers=='Shift')?'zoom':(modifiers=='Alt')?'rotate':null
if(sourceNode.edit_mode){e.stopPropagation();e.preventDefault();var src=sourceNode.getAttributeFromDatasource('src');if(!src||(sourceNode.form&&sourceNode.form.isDisabled())){return;}
sourceNode.s_x=e.clientX;sourceNode.s_y=e.clientY;var domnode=sourceNode.domNode;sourceNode.editConnections=[dojo.connect(domnode,"onmousemove",function(e){that.onEditImage(sourceNode,e);}),dojo.connect(document,"onmouseup",function(e){that.onEndEdit(sourceNode);})];};},decodeUrl:function(sourceNode,url){if(!url){return{};}
if(url.startsWith('data:')){return{src:url};}
var parsedUrl=parseURL(url);var p=parsedUrl.params;if(!p._pc){p['_pc']=new Date().getMilliseconds()}
p['v_x']=parseFloat((p['v_x']||0));p['v_y']=parseFloat((p['v_y']||0));p['v_z']=parseFloat((p['v_z']||1));p['v_r']=parseFloat((p['v_r']||0));if(sourceNode.attr.cr_height){p['v_h']=parseFloat(sourceNode.attr.cr_height);p['v_w']=parseFloat(sourceNode.attr.cr_width);}else{objectExtract(p,'v_h,v_w');}
var result={src:this.encodeUrl(parsedUrl,true),formattedUrl:this.encodeUrl(parsedUrl),styledict:{'margin_left':(-p['v_x'])+'px','margin_top':(-p['v_y'])+'px','transform_scale':p['v_z'],'transform_rotate':p['v_r']},originalKw:parsedUrl.params};return result;},encodeUrl:function(parsedUrl,dropFormatters){var kw=objectUpdate({},parsedUrl.params);var baseUrl;if(window.location.protocol.replace(':','')==parsedUrl.protocol&&window.location.hostname==parsedUrl.host&&window.location.port==parsedUrl.port){baseUrl=parsedUrl.path;}else{baseUrl=parsedUrl.protocol+'://'+parsedUrl.host+parsedUrl.path;}
if(parsedUrl.protocol=='data'){return baseUrl;}
if(dropFormatters){objectExtract(kw,'v_*');}
return genro.addParamsToUrl(baseUrl,kw);},setSrc:function(domnode,v){var sourceNode=domnode.sourceNode;if(v&&v.startsWith('data:')){domnode.setAttribute('src',v);return;}
var kwimg=this.decodeUrl(sourceNode,v);var src=objectPop(kwimg,'src');if(src){if(src!=domnode.getAttribute('src')){domnode.setAttribute('src',src);}
var currStyle=objectFromStyle(domnode.style.cssText);if('cr_height'in sourceNode.attr){objectPop(currStyle,'height');objectPop(currStyle,'width');}
var newStyle=genro.dom.getStyleDict(kwimg['styledict'])
var style=objectAsStyle(objectUpdate(currStyle,newStyle));domnode.setAttribute('style',style);}
else if(('placeholder'in sourceNode.attr)){this.setPlaceHolder(sourceNode);}
var valueNode=genro.getDataNode(sourceNode.absDatapath(sourceNode.attr.src));if(valueNode){var formattedValue=genro.formatter.asText(kwimg.formattedUrl,{dtype:'P',format:sourceNode.attr.format,mask:sourceNode.attr.mask});valueNode.updAttributes({_formattedValue:formattedValue},sourceNode);}}});dojo.declare("gnr.widgets.img",gnr.widgets.uploadable,{constructor:function(application){this._domtag='img';this._default_ext='png,jpg,jpeg,gif,svg';}});dojo.declare("gnr.widgets.embed",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='embed';},setSrc:function(domnode,v){domnode.sourceNode.rebuild();}});dojo.declare("gnr.widgets.StaticMap",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='img';},creating:function(attributes,sourceNode){var urlPars=objectExtract(attributes,'map_*');if(!urlPars['center']){attributes['src']=null;return attributes;}
urlPars.sensor=false;var sizeKw=objectExtract(attributes,'height,width');var height=sizeKw.height?sizeKw.height.replace('px',''):'200';var width=sizeKw.width?sizeKw.width.replace('px',''):'200';urlPars.size=urlPars.size||(width+'x'+height);var markersBag=attributes.markers;var markersDict=objectExtract(attributes,'marker_*');var markers=[];if(attributes.centerMarker){markers.push('label:C%7C'+urlPars.center);}
if(typeof(markersBag)=='string'){markersBag=sourceNode.getRelativeData(markersBag);}
if(markersDict){for(var k in markersDict){markers.push('label:'+k[0].toUpperCase()+'%7C'+markersDict[k]);}}
if(markersBag){markersBag.forEach(function(n){var nattr=n.attr;var str='';if('color'in nattr){str+='color:'+nattr.color+'%7C';}
if('label'in nattr){str+='label:'+nattr.label[0].toUpperCase()+'%7C';}
markers.push(str);});}
var url=genro.addParamsToUrl('http://maps.googleapis.com/maps/api/staticmap',urlPars);if(markers.length){markers=markers.join('&markers=');url+='&markers='+markers;}
attributes['src']=url;return attributes;}});dojo.declare("gnr.widgets.GoogleMap",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';this.markers_types={};},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'map_*');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){sourceNode.markers={};var that=this;genro.google().setGeocoder(sourceNode,function(){that.markers_types['default']=google.maps.Marker;that.makeMap(sourceNode,savedAttrs);});sourceNode.gnr=this;},makeMap:function(sourceNode,kw){kw.mapTypeId=objectPop(kw,'type')||'roadmap';kw.zoom=kw.zoom||8;var that=this;if(kw.center||sourceNode.attr.autoFit){this.onPositionCall(sourceNode,kw.center,function(center){kw.center=center;sourceNode.map=new google.maps.Map(sourceNode.domNode,kw);var events=objectExtract(kw,'event_*');for(let k in events){sourceNode.map.addListener(k,funcCreate(events[k],'kw',sourceNode));}
var centerMarker=sourceNode.attr.centerMarker;if(centerMarker){that.setMarker(sourceNode,'center_marker',kw.center,centerMarker==true?{}:centerMarker);}});}},clearMarkers:function(sourceNode){for(var k in sourceNode.markers){sourceNode.markers[k].setMap(null);delete sourceNode.markers[k];}},setMarker:function(sourceNode,marker_name,marker,kw){var kw=kw||{};if(marker_name in sourceNode.markers){sourceNode.markers[marker_name].setMap(null);objectPop(sourceNode.markers,marker_name);}
if(!marker){return;}
var gnr=this;var marker_type=objectPop(kw,'marker_type')||'default';var onClick=objectPop(kw,'onClick')
this.onPositionCall(sourceNode,marker,function(position){if(position){kw.position=position;kw.title=kw.title||marker_name;kw.map=sourceNode.map;if(kw.color){objectUpdate(kw,gnr._markerColorKwargs(kw.color))}
sourceNode.markers[marker_name]=new gnr.markers_types[marker_type](kw);if(onClick){sourceNode.markers[marker_name].addListener('click',function(e){onClick(marker_name,e)});}}});if(sourceNode.attr.autoFit){sourceNode.delayedCall(function(){var bounds=new google.maps.LatLngBounds();for(var k in sourceNode.markers){bounds.extend(sourceNode.markers[k].position);}
sourceNode.map.fitBounds(bounds);},10,'fitBounds');}},addMarkerType:function(code,cls){this.markers_types[code]=cls},_markerColorKwargs:function(color,shadow){var result={};if(color){result.icon=new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color,new google.maps.Size(21,34),new google.maps.Point(0,0),new google.maps.Point(10,34));}
if(shadow){result.shadow=new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",new google.maps.Size(40,37),new google.maps.Point(0,0),new google.maps.Point(12,35));}
return result;},setMap_center:function(domnode,v){var sourceNode=domnode.sourceNode;if(!sourceNode.map){var kw=objectExtract(sourceNode.attr,'map_*',true);kw.center=v;return this.makeMap(sourceNode,kw);}
var that=this;this.onPositionCall(sourceNode,v,function(center){if(center){sourceNode.map.setCenter(center);var centerMarker=sourceNode.attr.centerMarker;if(centerMarker){that.setMarker(sourceNode,'center_marker',center,centerMarker==true?{}:centerMarker);}}});},setMap_zoom:function(domnode,v){var sourceNode=domnode.sourceNode;sourceNode.map.setZoom(v);},setMap_type:function(domnode,v){var sourceNode=domnode.sourceNode;sourceNode.map.setMapTypeId(v);},setMap_markers:function(domnode,v){var sourceNode=domnode.sourceNode;sourceNode.map.setMapTypeId(v);},onPositionCall:function(sourceNode,v,cb){var result;if(typeof(v)!='string'){cb(v);return;}
if(v.indexOf(',')){var c=v.split(',');c0=parseFloat(c[0]);if(c0){c1=parseFloat(c[1]);if(c1){result=new google.maps.LatLng(c0,c1);cb(result);return;}}}
sourceNode.geocoder.geocode({'address':v},function(results,status){if(status==google.maps.GeocoderStatus.OK){cb(results[0].geometry.location);}});}});dojo.declare("gnr.widgets.fileInput",gnr.widgets.baseDojo,{constructor:function(){this._domtag='input';this._dojotag='FileInput';},creating:function(attributes,sourceNode){dojo.require("dojo.io.iframe");var remotePars=objectExtract(attributes,'remote_*');var savedAttrs=objectExtract(attributes,'method');savedAttrs.onUpload=objectPop(attributes,'onUpload','alert("Upload Done")');savedAttrs.remotePars=remotePars;return savedAttrs;},created:function(widget,savedAttrs,sourceNode){widget.savedAttrs=savedAttrs;},mixin_uploadFile:function(){var fname=this.fileInput.value;if(!fname||this._sent){return;}
var ext=fname.slice(fname.lastIndexOf('.'));this.savedAttrs.remotePars.ext=ext;var remotePars=genro.rpc.serializeParameters(genro.src.dynamicParameters(this.savedAttrs.remotePars));var method=this.savedAttrs.method;var url=genro.remoteUrl(method,remotePars);var _newForm=document.createElement('form');_newForm.setAttribute("enctype","multipart/form-data");var node=dojo.clone(this.fileInput);_newForm.appendChild(this.fileInput);this.fileInput.setAttribute('name','fileHandle');dojo.body().appendChild(_newForm);var handle=dojo.hitch(this,funcCreate(this.savedAttrs.onUpload));dojo.io.iframe.send({url:url,form:_newForm,handleAs:"text",handle:handle});}});dojo.declare("gnr.widgets.fileInputBlind",gnr.widgets.fileInput,{constructor:function(){this._domtag='input';this._dojotag='fileInputBlind';}});dojo.declare("gnr.widgets.fileUploader",gnr.widgets.baseDojo,{constructor:function(){this._domtag='textarea';this._dojotag='dojox.widget.FileInputAuto';},creating:function(attributes,sourceNode){var uploadPars=objectUpdate({},sourceNode.attr);uploadPars.mode='html';objectExtract(uploadPars,'tag,method,blurDelay,duration,uploadMessage,cancelText,label,name,id,onComplete');var savedAttrs=objectExtract(attributes,'method');dojo.require("dojox.widget.FileInputAuto");var onComplete=objectPop(attributes,'onComplete');savedAttrs.uploadPars=uploadPars;if(onComplete){attributes.onComplete=funcCreate(onComplete);}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){widget.savedAttrs=savedAttrs;},mixin__sendFile:function(e){if(!this.fileInput.value||this._sent){return;}
var uploadPars=genro.rpc.serializeParameters(genro.src.dynamicParameters(this.savedAttrs.uploadPars));var method=this.savedAttrs.method;var url=genro.remoteUrl(method,uploadPars);dojo.style(this.fakeNodeHolder,"display","none");dojo.style(this.overlay,"opacity","0");dojo.style(this.overlay,"display","block");this.setMessage(this.uploadMessage);dojo.fadeIn({node:this.overlay,duration:this.duration}).play();var _newForm=document.createElement('form');_newForm.setAttribute("enctype","multipart/form-data");var node=dojo.clone(this.fileInput);_newForm.appendChild(this.fileInput);this.fileInput.setAttribute('name','fileHandle');dojo.body().appendChild(_newForm);dojo.io.iframe.send({url:url,form:_newForm,handleAs:"text",handle:dojo.hitch(this,"_handleSend")});},mixin__handleSend:function(data,ioArgs){if(!dojo.isIE){this.overlay.innerHTML="";}
this._sent=true;dojo.style(this.overlay,"opacity","0");dojo.style(this.overlay,"border","none");dojo.style(this.overlay,"background","none");this.overlay.style.backgroundImage="none";this.fileInput.style.display="none";this.fakeNodeHolder.style.display="none";dojo.fadeIn({node:this.overlay,duration:this.duration}).play(250);dojo.disconnect(this._blurListener);dojo.disconnect(this._focusListener);alert('fatto:'+data);this.onComplete(data,ioArgs,this);},onComplete:function(data,ioArgs,widget){if(data){var d=dojo.fromJson(data);if(d.status&&d.status=="success"){widget.overlay.innerHTML="success!";}else{widget.overlay.innerHTML="error? ";}}else{}}});



dojo.declare("gnr.widgets.Tree",gnr.widgets.baseDojo,{constructor:function(){this._domtag='div';this._dojotag='Tree';},onBuilding_searchOn:function(sourceNode){var searchOn=normalizeKwargs(sourceNode.attr,'searchOn');if(!searchOn){return;}
var boxkw=objectExtract(sourceNode.attr,'height,max_height,width,max_width,overflow,border,top,bottom,left,right,position');var treeattr=objectUpdate({},sourceNode.attr);sourceNode.attr=objectUpdate(boxkw,{tag:'div',_class:'searchtree_container'});var searchCode=searchOn.searchCode||'search_'+sourceNode.getStringId();searchOn.nodeId=searchCode+'_searchbox';searchOn.parentForm=false;treeattr.searchCode=searchCode;sourceNode._('div','t_searchbox',{_class:'tree_searchbox'},{doTrigger:false})._('div',{display:'inline-block',position:'absolute',right:'8px'},{doTrigger:false})._('SearchBox',searchOn,{doTrigger:false});sourceNode._('div','t_scrollbox',{_class:'tree_scrollbox'},{doTrigger:false})._('tree',treeattr,{doTrigger:false});},onBuilding_popup:function(sourceNode){var popup_kw=normalizeKwargs(sourceNode.attr,'popup');if(!popup_kw){return;}
popup_kw=objectUpdate({tag:'menu',modifiers:'*',_class:'menupane'},popup_kw);var treeattr=objectUpdate({},sourceNode.attr);treeattr.max_height=treeattr.max_height||'300px';treeattr.min_width=treeattr.min_width||'220px';treeattr.searchOn=normalizeKwargs(treeattr,'searchOn');var closeEvent=objectPop(popup_kw,'closeEvent');popup_kw.datapath=objectPop(treeattr,'datapath');popup_kw.connect_onOpen=function(evt){var box=this.getValue().getItem('m_item.m_spacer');var treeNode=box.getNodeByAttr('tag','tree',true);if(!treeNode){box._('tree','treemenu',objectUpdate({openOnClick:true,hideValues:true,autoCollapse:true,labelAttribute:'caption',selectedLabelClass:'selectedFieldTreeNode',parentMenu:this,_class:"branchtree noIcon"},treeattr));if(closeEvent){var that=this;var wdg=box.getNode('treemenu').widget;var connectNode;connectNode=closeEvent=='onClick'?wdg:wdg.domNode;dojo.connect(connectNode,closeEvent,function(e){that.widget.onCancel();});}
treeNode=box.getNodeByAttr('tag','tree',true);}
treeNode.widget.originalContextTarget=this.widget.originalContextTarget;};var box_kw=objectExtract(popup_kw,'max_height,min_width');sourceNode.attr=popup_kw;var connect_onclick=function(e){e.stopPropagation();e.preventDefault();};var mi=sourceNode._('menuItem','m_item',{},{doTrigger:false});var spacer_padding_top='4px';if(treeattr.searchOn){spacer_padding_top=0;}
mi._('div','m_spacer',{padding_top:spacer_padding_top,padding_bottom:'4px',connect_onclick:connect_onclick},{doTrigger:false});return true;},onBuilding:function(sourceNode){if(this.onBuilding_popup(sourceNode)){return;}
if(sourceNode.attr.height||sourceNode.attr.max_height||sourceNode.attr.width||sourceNode.attr.max_width){sourceNode.attr.overflow='auto';}
if(this.onBuilding_searchOn(sourceNode)){return;}},creating:function(attributes,sourceNode){dojo.require("dijit.Tree");var storepath=sourceNode.absDatapath(objectPop(attributes,'storepath'));var labelAttribute=objectPop(attributes,'labelAttribute');var labelCb=objectPop(attributes,'labelCb');var hideValues=objectPop(attributes,'hideValues');var _identifier=objectPop(attributes,'identifier')||'#id';var hasChildrenCb=objectPop(attributes,'hasChildrenCb');var nodeFilter=objectPop(attributes,'nodeFilter');if(hasChildrenCb){hasChildrenCb=funcCreate(hasChildrenCb,null,sourceNode);}
if(labelCb){labelCb=funcCreate(labelCb,null,sourceNode);}
if(nodeFilter){nodeFilter=funcCreate(nodeFilter,null,sourceNode);}
var store=new gnr.GnrStoreBag({datapath:storepath,_identifier:_identifier,hideValues:hideValues,labelAttribute:labelAttribute,labelCb:labelCb,hasChildrenCb:hasChildrenCb,nodeFilter:nodeFilter,sourceNode:sourceNode});var model=new dijit.tree.ForestStoreModel({store:store,childrenAttrs:["#v"]});attributes.model=model;attributes.showRoot=false;attributes.persist=attributes.persist||false;if(attributes['getLabel']){var labelGetter=funcCreate(attributes['getLabel'],'node');attributes.getLabel=function(node){if(node.attr){return labelGetter(node);}};}
if(!attributes['getLabelClass']){attributes['getLabelClass']=function(node,opened){var labelClass;if(opened){return node.attr.labelClassOpened||node.attr.labelClass;}else{return node.attr.labelClassClosed||node.attr.labelClass;}};}
var labelClassGetter=funcCreate(attributes['getLabelClass'],'node,opened');var selectedLabelClass=attributes['selectedLabelClass'];attributes.getLabelClass=function(node,opened){if(node.attr){var labelClass=labelClassGetter.call(this,node,opened)||'';if(selectedLabelClass){return(this.currentSelectedNode&&this.currentSelectedNode.item==node)?labelClass+' '+selectedLabelClass:labelClass;}else{return labelClass;}}};if(attributes['getIconClass']){var iconGetter=funcCreate(attributes['getIconClass'],'node,opened');attributes.getIconClass=function(node,opened){if(node.attr){return iconGetter(node,opened);}};}
attributes.onChecked=attributes.onChecked||('checkedPaths'in attributes)||('checked'in attributes)||objectNotEmpty(objectExtract(sourceNode.attr,'checked_*',true))
if(attributes.onChecked){attributes.getIconClass=function(node,opened){if(!(node instanceof gnr.GnrBagNode)){return;}
if(node.attr){var checked='checked'in node.attr?node.attr.checked:node.getInheritedAttributes()['checked'];if(checked=='disabled:on'){return'checkboxOn dimmed';}else if(checked=='disabled:off'){return'checkboxOff dimmed';}
if(!('checked'in node.attr)){node.attr.checked=this.tree.checkBoxCalcStatus(node);}
return(node.attr.checked==-1)?"checkboxOnOff":node.attr.checked?"checkboxOn":"checkboxOff";}};if(attributes.checkedPaths){sourceNode.registerDynAttr('checkedPaths');}}
if(attributes.selectedPath){sourceNode.registerDynAttr('selectedPath');}
var tooltipAttrs=objectExtract(attributes,'tooltip_*');var savedAttrs=objectExtract(attributes,'inspect,autoCollapse,onChecked,editable');if(objectNotEmpty(tooltipAttrs)){savedAttrs['tooltipAttrs']=tooltipAttrs;}
attributes.sourceNode=sourceNode;return savedAttrs;},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.tooltipAttrs){var funcToCall=funcCreate(savedAttrs.tooltipAttrs.callback,'sourceNode,treeNode',widget);var cb=function(n){var item=dijit.getEnclosingWidget(n).item;return funcToCall(item,n);};genro.wdg.create('tooltip',null,{label:cb,validclass:'dijitTreeLabel',modifiers:savedAttrs.tooltipAttrs.modifiers}).connectOneNode(widget.domNode);}
if(savedAttrs.inspect){var modifiers=(savedAttrs.inspect===true)?'':savedAttrs.inspect;genro.wdg.create('tooltip',null,{label:function(n){return genro.dev.bagAttributesTable(n);},validclass:'dijitTreeLabel',modifiers:modifiers}).connectOneNode(widget.domNode);}
var storepath=widget.model.store.datapath;if((storepath=='*D')||(storepath=='*S'))
widget.sourceNode.registerSubscription('_trigger_data',widget,function(kw){this.setStorepath('',kw);});else{sourceNode.registerDynAttr('storepath');}
if(savedAttrs.onChecked){widget.checkBoxTree=true;if(savedAttrs.onChecked!==true){widget.onChecked=funcCreate(savedAttrs.onChecked,'node,event');}}
if(savedAttrs.autoCollapse){dojo.connect(widget,'_expandNode',function(node){if(this._filteringValue){return;}
this.collapseAll(node.getParent(),node);});}
var nodeId=sourceNode.attr.nodeId;if(savedAttrs.editable){var editmodifiers=savedAttrs.editable===true?'Shift':savedAttrs.editable;dojo.connect(widget,'onClick',function(item,treeNode){if(treeNode.__eventmodifier==editmodifiers){var origin=storepath.startsWith('*S')?'*S':null;genro.dev.openBagNodeEditorPalette(item.getFullpath(null,origin!='*S'?genro._data:null),{name:nodeId||'inspector_'+sourceNode.getPathId(),origin:origin});}});}
var searchCode=sourceNode.attr.searchCode===false?false:sourceNode.attr.searchCode||(sourceNode.getInheritedAttributes().frameCode||nodeId);if(searchCode){var searchId=searchCode+'_searchbox';var searchBoxNode=genro.nodeById(searchId);if(searchBoxNode){sourceNode.registerSubscription(searchId+'_changedValue',widget,function(v,field,search_kw){var was_filtering=!isNullOrBlank(this._filteringValue);var end_filtering=isNullOrBlank(v);if(was_filtering){if(this._filteringValue!=v){this.stopApplyFilter();if(end_filtering){this.collapseAll();this._filteringValue=null;this.applyFilter(search_kw);return;}}else{return;}}
if(end_filtering){return;}
this._filteringValue=v;var vl=v.length;var delay=vl==1?3000:vl==2?1000:vl==3?300:150;var that=this;sourceNode.delayedCall(function(){that.applyFilter(search_kw);},delay,'shortSeed_delay');});sourceNode.registerSubscription(searchId+'_stopSearch',widget,function(kw){if(objectNotEmpty(this._pending_deferred)){this.stopApplyFilter();}else{kw.finalize();}});}}},fillDragInfo:function(dragInfo){dragInfo.treenode=dragInfo.widget;dragInfo.widget=dragInfo.widget.tree;dragInfo.treeItem=dragInfo.treenode.item;},fillDropInfo:function(dropInfo){dropInfo.treenode=dropInfo.widget;dropInfo.widget=dropInfo.widget.tree;dropInfo.treeItem=dropInfo.treenode.item;dropInfo.outline=dropInfo.treenode.domNode;},onDragStart:function(dragInfo){var item=dragInfo.treenode.item;var caption=dragInfo.treenode.label;var result={};result['text/plain']=dragInfo.treenode.label;result['text/xml']=dragInfo.treenode.label;result['nodeattr']=item.attr;result['treenode']={'fullpath':item.getFullpath(),'relpath':item.getFullpath(null,dragInfo.treenode.tree.model.store.rootData())};return result;},attributes_mixin_checkBoxCalcStatus:function(bagnode){var checked,ck;if(bagnode._resolver&&bagnode._resolver.expired()){return false;}else if(bagnode._value instanceof gnr.GnrBag){bagnode._value.forEach(function(node){var checked=('checked'in node.attr)?(node.attr.checked||false):-1;ck=(ck===null)?checked:(ck!=checked)?-1:ck;},'static');}
return ck;},mixin_collapseAll:function(curr,exceptNode){curr=curr||this.rootNode;var tree=this;dojo.forEach(curr.getChildren(),function(n){if(n.isExpanded&&n!==exceptNode){tree.collapseAll(n);tree._collapseNode(n);}});},mixin_stopApplyFilter:function(){var _pending_deferred=this._pending_deferred;this._pending_deferred={};var pd,r;if(_pending_deferred){for(var token in _pending_deferred){pd=_pending_deferred[token];pd.deferred.cancel();r=pd.bagNode.getResolver();r.reset();delete _pending_deferred[token];}}},mixin_applyFilter:function(search_kw){search_kw=search_kw||{};var search=this._filteringValue;var treeNodes=dojo.query('.dijitTreeNode',this.domNode);treeNodes.removeClass('hidden');var searchmode=null;var filterRegExp=new RegExp('('+(search||'[]')+')','ig');if(search&&search.indexOf('#')===0){var k=search.indexOf('=');if((k<0)||(k==(search.length-1))){return;}
search=search.split('=');searchmode=search[0];search=search[1];}
var that=this;var label;var searchColumn=this.sourceNode.attr.searchColumn;var cb_match=function(n){if(!searchmode){label=searchColumn?n.attr[searchColumn]:that.getLabel(n);label=label||'';return label.match(filterRegExp);}else if(searchmode=='#'){console.log('ss');}else{label=n.attr[searchmode.slice(1)]+'';if(label){return label.match(filterRegExp);}}};var root=this.model.store.rootData();var cb=function(n){if(cb_match(n)){var fullpath=n.getFullpath(null,root);that.showNodeAtPath(fullpath);}};this._pending_deferred={};var filterForEach=function(b,cb,mode,valid_paths){b.forEach(function(n){if(mode=='async'&&n.getResolver()&&n.getResolver().expired()){if(valid_paths&&valid_paths.indexOf(n.label)<0){return;}
var deferred=n.getValue(null,{rpc_sync:false});var token='treesearch_'+genro.getCounter('treesearch');that._pending_deferred[token]={'deferred':deferred,'bagNode':n};deferred.addCallback(function(result){delete that._pending_deferred[token];if(result instanceof gnr.GnrBag){filterForEach(result,cb,'async',valid_paths);that.sourceNode.delayedCall(function(){showResult();},30,'applyFilter_asyncSearch');}});}else{var v=n.getValue(mode=='static'?'static':null);if(v instanceof gnr.GnrBag){filterForEach(v,cb,mode);}else{cb(n);}}});};var showResult=function(){treeNodes=dojo.query('.dijitTreeNode',that.domNode);treeNodes.addClass('hidden');treeNodes.forEach(function(n){var tn=dijit.getEnclosingWidget(n);var parent=tn.getParent();if((!parent)||cb_match(tn.item)||!search){dojo.removeClass(tn.domNode,'hidden');var item=tn.item;if(!searchColumn){var label=that.getLabel(item);if(label){tn.labelNode.innerHTML=label.replace(filterRegExp,"<span class='search_highlight'>$1</span>");}}
while(parent&&dojo.hasClass(parent.domNode,'hidden')){dojo.removeClass(parent.domNode,'hidden');parent=parent.getParent();}}});};var m=('searchMode'in this.sourceNode.attr)?this.sourceNode.attr.searchMode:'async';if(!('_searchRpcProxy'in this)){this._searchRpcProxy={kw:{},cache:[],_sourceNode:this.sourceNode};var data_inattr=root.getParentNode().getInheritedAttributes();if(!('rpcmethod'in search_kw)){var rootattr=objectUpdate({},root.getParentNode().attr);var search_attr=objectExtract(rootattr,'search_*');var storeRpcSearch=objectPop(search_attr,'method');if(storeRpcSearch){this._searchRpcProxy.method=storeRpcSearch;this._searchRpcProxy.kw=search_attr;}}else{this._searchRpcProxy.method=objectPop(search_kw,'rpcmethod');}}
if(this._filteringValue&&this._searchRpcProxy.method){if(this._searchRpcProxy.cache.some(function(c){return that._filteringValue.match(c);})){filterForEach(root,cb,m,[]);showResult();}else{var rpc_kw=objectUpdate({},this._searchRpcProxy.kw);objectUpdate(rpc_kw,search_kw);rpc_kw.seed=this._filteringValue;this._searchRpcProxy.cache.push(new RegExp('('+this._filteringValue+')','ig'));genro.serverCall(this._searchRpcProxy.method,rpc_kw,function(result){if(result){filterForEach(root,cb,m,result);showResult();}});}}else{filterForEach(root,cb,m);showResult();}},mixin_updateLabels:function(){var n;for(var k in this._itemNodeMap){n=this._itemNodeMap[k];if(n){n.setLabelNode(this.getLabel(n.item));}}},mixin_storebag:function(){return this.sourceNode.getRelativeData(this.sourceNode.attr.storepath);},mixin_clickOnCheckbox:function(bagnode,e){if(bagnode.attr.checked=='disabled:on'||bagnode.attr.checked=='disabled:off'){return;}
var checked=bagnode.attr.checked?false:true;var walkmode=this.sourceNode.attr.eagerCheck?null:'static';var updBranchCheckedStatus=function(bag){bag.forEach(function(n){if(n.attr.checked=='disabled:on'||n.attr.checked=='disabled:off'){return;}
var v=n.getValue(walkmode);if((v instanceof gnr.GnrBag)&&v.len()){updBranchCheckedStatus(v);var checkedStatus=dojo.every(v.getNodes(),function(cn){return cn.attr.checked===true;});if(!checkedStatus){var allUnchecked=dojo.every(v.getNodes(),function(cn){return cn.attr.checked===false;});checkedStatus=allUnchecked?false:-1;}
n.setAttr({'checked':checkedStatus},true,true);}else if(n._resolver&&n._resolver.expired()){n.setAttr({'checked':false},true,true);}else{n.setAttr({'checked':checked},true,true);}});};if(bagnode.getValue){var value=bagnode.getValue();if((value instanceof gnr.GnrBag)&&this.sourceNode.attr.checkChildren!==false){updBranchCheckedStatus(value);}}
bagnode.setAttr({'checked':checked},true,true);var parentNode=bagnode.getParentNode();var rootNodeId=genro.getDataNode(this.model.store.datapath)._id;if(this.sourceNode.attr.checkChildren!==false){while(parentNode&&(parentNode._id!=rootNodeId)){parentNode.setAttr({'checked':this.checkBoxCalcStatus(parentNode)},true,true);parentNode=parentNode.getParentNode();}}
if(this.sourceNode.attr.nodeId){genro.publish(this.sourceNode.attr.nodeId+'_checked',bagnode);}
this.updateCheckedAttr();},mixin_updateCheckedAttr:function(){var checked_attr=objectExtract(this.sourceNode.attr,'checked_*',true)
var checked_attr_joiners={};var p;for(var k in checked_attr){p=checked_attr[k];if(p.indexOf(':')>=0){p=p.split(':');checked_attr[k]=p[0]
checked_attr_joiners[k]=p[1];}}
var checkedPaths=this.sourceNode.attr.checkedPaths;var checkedPaths_joiner=this.sourceNode.attr.checkedPaths_joiner;if(objectNotEmpty(checked_attr)||checkedPaths){var propagate=this.sourceNode.attr.checkChildren!==false;var walkmode=this.sourceNode.attr.eagerCheck?null:'static';var store=this.sourceNode.getRelativeData(this.sourceNode.attr.storepath);var result={};var cp=[];var p;for(var k in checked_attr){result[k]=[];}
store.walk(function(n){var v=n.getValue(walkmode);if(propagate&&(v instanceof gnr.GnrBag)&&(v.len()>0)){return;}else if(n.attr.checked===true){for(var k in checked_attr){var av=n.attr[k];if(result[k].indexOf(av)<0){result[k].push(av)}}
if(checkedPaths){p=n.getFullpath('static',store);if(cp.indexOf(p)<0){cp.push(p);}}}},walkmode);for(var k in checked_attr){this.sourceNode.setRelativeData(checked_attr[k],result[k].join(checked_attr_joiners[k]||','),null,null,this);}
if(checkedPaths){this.sourceNode.setRelativeData(checkedPaths,cp.join(checkedPaths_joiner||','),null,null,this);}}},versionpatch_11__onClick:function(e){var nodeWidget=dijit.getEnclosingWidget(e.target);if(dojo.hasClass(e.target,'dijitTreeIcon')&&this.tree.checkBoxTree){var bagnode=nodeWidget.item;if(bagnode instanceof gnr.GnrBagNode){var onCheck=this.onChecked?this.onChecked(bagnode,e):true;if(onCheck!=false){this.tree.clickOnCheckbox(bagnode,e);}}
dojo.stopEvent(e);return;}
nodeWidget=dijit.getEnclosingWidget(e.target);if(nodeWidget==nodeWidget.tree.rootNode){return;}
nodeWidget.__eventmodifier=eventToString(e);this._onClick_replaced(e);if(genro.wdg.filterEvent(e,'*','dijitTreeLabel,dijitTreeContent,treeCellContent')){this.setSelected(nodeWidget,e);}},versionpatch_15__onClick:function(nodeWidget,e){if(dojo.hasClass(e.target,'dijitTreeIcon')&&this.tree.checkBoxTree){var bagnode=nodeWidget.item;if(bagnode instanceof gnr.GnrBagNode){var onCheck=this.onChecked?this.onChecked(bagnode,e):true;if(onCheck!=false){this.tree.clickOnCheckbox(bagnode,e);}}
dojo.stopEvent(e);return;}
if(nodeWidget.htmlLabel&&(!dojo.hasClass(e.target,'dijitTreeExpando'))){return;}
if(nodeWidget==nodeWidget.tree.rootNode){return;}
nodeWidget.__eventmodifier=eventToString(e);this._onClick_replaced(nodeWidget);if(genro.wdg.filterEvent(e,'*','dijitTreeLabel,dijitTreeContent')){this.setSelected(nodeWidget,e);}},mixin_getItemById:function(id){return this.model.store.rootData().findNodeById(id);},mixin_saveExpanded:function(){var that=this;this.sourceNode._savedExpandedStatus=dojo.query('.dijitTreeContentExpanded',that.domNode).map(function(n){return that.model.store.getIdentity(dijit.getEnclosingWidget(n).item);});},mixin_restoreExpanded:function(){if(this.sourceNode._savedExpandedStatus){var that=this;dojo.forEach(this.sourceNode._savedExpandedStatus,function(n){if(n){var tn=that._itemNodeMap[n];if(tn){that._expandNode(tn);}}});}
delete this.sourceNode._savedExpandedStatus;},mixin_expandAll:function(rootNode){var that=this;var nodes=dojo.query('.dijitTreeExpando.dijitTreeExpandoClosed',rootNode.domNode);nodes.forEach(function(n){var n=that.model.store.getIdentity(dijit.getEnclosingWidget(n).item);var tn=that._itemNodeMap[n];that._expandNode(tn);});},attributes_mixin__saveState:function(){return;if(!this.persist){return;}
var cookiepars={};if(this.persist=='site'){cookiepars.path=genro.getData('gnr.homeUrl');}
var ary=[];for(var id in this._openedItemIds){ary.push(id);}
dojo.cookie(this.cookieName,ary.join(","),cookiepars);},attributes_mixin_loadState:function(val,kw){this._openedItemIds={};},mixin_setDynamicStorepath:function(newstorepath){if(newstorepath!=this.sourceNode.attr.storepath){this.sourceNode.attr.storepath=newstorepath;this.sourceNode.rebuild();}},mixin_setStorepath:function(val,kw){var storeAbsPath=this.sourceNode.absDatapath(this.sourceNode.attr.storepath);var eventPath=kw.pathlist.join('.').slice(5);if(kw.evt=='upd'){if(kw.updvalue){if(kw.value instanceof gnr.GnrBag){if(storeAbsPath.indexOf(eventPath)==0){this.sourceNode.rebuild();}else{this._onItemChildrenChange(kw.node,kw.value.getNodes());}}else{this._onItemChange({id:kw.node._id+'c',label:kw.value});}}else if(kw.updattr){this._onItemChange(kw.node);}}else if(kw.evt=='ins'){if(undefined in this._itemNodeMap&&objectSize(this._itemNodeMap)==1){this.sourceNode.rebuild();}else{this.model.store._triggerIns(kw);}}else if(kw.evt=='del'){this._onItemChildrenChange(kw.where.getParentNode(),kw.where.getNodes());}},patch__onItemChildrenChange:function(n,nodes){var that=this;var identifier;dojo.forEach(nodes,function(n){identifier=that.model.store.getIdentity(n);objectPop(that._itemNodeMap,identifier);});this._onItemChildrenChange_replaced(n,nodes);},mixin_setCheckedPaths:function(path,kw){if(kw.reason==this||kw.reason=='autocreate'){return;}
var store=this.sourceNode.getRelativeData(this.sourceNode.attr.storepath);store.walk(function(n){n.setAttr({'checked':false},true,true);},'static');var paths=this.sourceNode.getRelativeData(this.sourceNode.attr.checkedPaths);if(!paths){this.updateCheckedAttr();return;}
paths=paths.split(this.sourceNode.attr.checkedPaths_joiner||',');var that=this;var treeNode;paths.forEach(function(path){var n=store.getNode(path);if(n){that.clickOnCheckbox(n);}});},mixin_setSelectedPath:function(path,kw){if(kw.reason==this){return;}
var curr=this.model.store.rootData();var currNode,treeNode;if(!kw.value){this.setSelected(null);return;}
var pathList=kw.value.split('.');for(var i=0;i<pathList.length;i++){if(!curr){return;}
if(!(curr instanceof gnr.GnrBag)){console.warn('TREE setSelectedPath warn curr is not a bag',curr);return;}
currNode=curr.getNode(pathList[i]);if(!currNode){return;}
var identity=this.model.store.getIdentity(currNode);treeNode=this._itemNodeMap[identity];if(i<pathList.length-1){if(!treeNode.isExpanded){this._expandNode(treeNode);}}
curr=currNode.getValue();}
var currTree=this;setTimeout(function(){currTree.focusNode(treeNode);currTree.setSelected(treeNode);if(kw.expand){currTree._expandNode(treeNode);}},100);},mixin_showNodeAtPath:function(path){var curr=this.model.store.rootData();var pathList=path.split('.');var treeNode;for(var i=0;i<pathList.length;i++){var currNode=curr.getNode(pathList[i]);if(!currNode){return;}
var identity=this.model.store.getIdentity(currNode);treeNode=this._itemNodeMap[identity];curr=currNode.getValue('static');if(i<pathList.length-1){if(!treeNode.isExpanded){this._expandNode(treeNode);}}}
return treeNode;},mixin_setSelected:function(node,e){if(node){if(node.item.attr._isSelectable===false||(this.sourceNode.attr.openOnClick===true&&node.item.attr.child_count)){return;}}
var prevSelectedNode=this.currentSelectedNode;this.currentSelectedNode=node;if(prevSelectedNode){prevSelectedNode._updateItemClasses(prevSelectedNode.item);}
if(node){node._updateItemClasses(node.item);this._updateSelect(node.item,node,e);}},mixin_isSelectedItem:function(item){return this.currentSelectedNode?this.currentSelectedNode.item==item:false;},mixin_getContainingtMenu:function(){return this.sourceNode.attributeOwnerNode('tag','menu',true);},mixin__updateSelect:function(item,node){var modifiers=objectPop(node,'__eventmodifier');var reason=this;var attributes={};var setterNode=this.sourceNode;var countainingMenu=this.getContainingtMenu();var path;if(countainingMenu){var targetDomNode=countainingMenu.widget.originalContextTarget;if(targetDomNode.sourceNode){setterNode=targetDomNode.sourceNode;}else{var targetWdg=dijit.getEnclosingWidget(targetDomNode);setterNode=targetWdg?targetWdg.sourceNode:setterNode;}}
if(modifiers){attributes._modifiers=modifiers;}
if(!item){item=new gnr.GnrBagNode();}
else if(!item._id){item=node.getParent().item;}
var root=this.model.store.rootData();var itemFullPath=item.getFullpath(null,root);if(this.sourceNode.attr.selectedLabel){path=this.sourceNode.attrDatapath('selectedLabel',setterNode);setterNode.setRelativeData(path,item.label,attributes,null,reason);}
if(this.sourceNode.attr.selectedItem){path=this.sourceNode.attrDatapath('selectedItem',setterNode);setterNode.setRelativeData(path,item,attributes,null,reason);}
if(this.sourceNode.attr.selectedPath){path=this.sourceNode.attrDatapath('selectedPath',setterNode);setterNode.setRelativeData(path,itemFullPath,objectUpdate(attributes,item.attr),null,reason);}
var selattr=objectExtract(this.sourceNode.attr,'selected_*',true);var attrval;for(var sel in selattr){path=this.sourceNode.attrDatapath('selected_'+sel,setterNode);attrval=item.attr[sel];if(isNullOrBlank(attrval)&&item.attr._record){attrval=item.attr._record[sel];}
attributes=objectNotEmpty(attributes)?attributes:null;setterNode.setRelativeData(path,attrval,attributes,null,reason);}
if(this.sourceNode.attr.onSelectedFire){setterNode.fireEvent(this.sourceNode.attr.onSelectedFire,true);}
this.sourceNode.publish('onSelected',{path:itemFullPath,item:item,node:node});}});



gnr.getGridColumns=function(storeNode){var storeNodeId,destFullpath;if(typeof(storeNode)=='string'){destFullpath=storeNode;}else{storeNodeId=storeNode.attr.nodeId;}
var columns={};var storeCode;genro.src._main.walk(function(n){if(n.widget&&n.widget.selectionKeeper){storeCode=n.attr.store||n.attr.nodeId;if((storeCode+'_store'==storeNodeId)||(destFullpath==n.widget.absStorepath())){var cols=n.widget.query_columns.split(',');dojo.forEach(cols,function(c){columns[c]=c;});}}},'static');var result=objectKeys(columns).join(',');if(storeNodeId){storeNode._previousColumns=storeNode._currentColumns;storeNode._currentColumns=result;}
return result;};gnr.columnsFromStruct=function(struct,columns){if(isNullOrBlank(columns)){columns=[];}
if(!struct){return'';}
var nodes=struct.getNodes();for(var i=0;i<nodes.length;i++){var node=nodes[i];var fld=node.attr.queryfield||node.attr.field;if(node.attr.group_aggr){fld=fld+'_'+node.attr.group_aggr.toLowerCase().replace(/\W/g,'_');}
if(node.attr.template_columns){node.attr.template_columns.split(',').forEach(function(n){arrayPushNoDup(columns,(n[0]=='$'||n[0]=='@')?n:'$'+n);});}
if(node.attr.rowTemplate||node.attr.calculated||(fld&&fld.indexOf(':')>=0)){continue;}
if(fld){if(node.attr.caption_field){var caption_field=node.attr.caption_field;caption_field=(stringStartsWith(caption_field,'$')||stringStartsWith(caption_field,'@'))?caption_field:'$'+caption_field;arrayPushNoDup(columns,caption_field);}
if(node.attr['_joiner_storename']){arrayPushNoDup(columns,node.attr['_external_name']);arrayPushNoDup(columns,node.attr['_external_fkey']);arrayPushNoDup(columns,node.attr['_joiner_storename']+' AS _external_store');}
if(node.attr._subtable){fld='*'+fld;}
if((!stringStartsWith(fld,'$'))&&(!stringStartsWith(fld,'@'))&&(!stringStartsWith(fld,'*'))){fld='$'+fld;}
arrayPushNoDup(columns,fld);if(node.attr.zoom_pkey){var zoom_pkey=node.attr.zoom_pkey;if((!stringStartsWith(zoom_pkey,'$'))&&(!stringStartsWith(zoom_pkey,'@'))){zoom_pkey='$'+zoom_pkey;}
arrayPushNoDup(columns,zoom_pkey);}}
if(node.getValue()instanceof gnr.GnrBag){gnr.columnsFromStruct(node.getValue(),columns);}}
return columns.join(',');};dojo.declare("gnr.widgets.DojoGrid",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='DojoGrid';if(dojo_version=='1.1'){if(!dojox.grid){dojo.require('dojox.grid._grid.builder');}
if(!dojox.grid.Builder.prototype._gnrpatch){dojox.grid.Builder.prototype._gnrpatch=true;dojox.grid.Builder.prototype.findCellTarget=function(inSourceNode,inTopNode){var n=inSourceNode;try{while(n&&(!this.isCellNode(n)||(dojox.grid.gridViewTag in n.offsetParent.parentNode&&n.offsetParent.parentNode[dojox.grid.gridViewTag]!=this.view.id))&&(n!=inTopNode)){n=n.parentNode;}
return n!=inTopNode?n:null;}catch(e){return;}};}}},patch__textSizeChanged:function(){if(dojo.getComputedStyle(this.domNode)){this._textSizeChanged_replaced();}},mixin_setStructpath:function(val,kw){kw=kw||{};this.structBag=genro.getData(this.sourceNode.attrDatapath('structpath'))||new gnr.GnrBag();this.cellmap={};try{this.setStructure(this.gnr.structFromBag(this.sourceNode,this.structBag,this.cellmap));this.onSetStructpath(this.structBag,kw);this.sourceNode.publish('onSetStructpath');}catch(error){console.error('error in structure',error);}},mixin_getColumnInfo:function(cell){var result=new gnr.GnrBag();if(!this.views.views[0]){return result;}
var headerList=dojo.query('th',this.viewsHeaderNode);var structureList=this.views.views[0].structure.rows[0];var hiddenBetween=0;var headerNode,isHidden,rel_index;structureList.forEach(function(n){headerNode=headerList[n.index];isHidden=!genro.dom.isVisible(headerNode);rel_index=n.index;if(isHidden){hiddenBetween+=1;rel_index=-1;}else{rel_index-=hiddenBetween;}
result.setItem(n.field,null,{cell:n,headerNode:headerNode,isHidden:isHidden,rel_index:rel_index});});return cell?result.getAttr(cell):result;},onBuilding:function(sourceNode){sourceNode.attr.scaleX=sourceNode.attr.scaleX||'^.scaleX';sourceNode.attr.scaleY=sourceNode.attr.scaleY||'^.scaleY';if(sourceNode._wrapperNode){return;}
var extendedLayout=objectPop(sourceNode.attr,'_extendedLayout');if(extendedLayout){var content=sourceNode._value;var footers=new gnr.GnrBag();var node;content.digest('#k,#a.tag').forEach(function(n){if(n[1]=='footer'){node=content.popNode(n[0]);footers.addItem(node.label,node._value,node.attr);}});var structInfo=sourceNode.getRelativeData(sourceNode.absDatapath(sourceNode.attr.structpath)+'.info')||new gnr.GnrBag();var columnsets=structInfo.getItem('columnsets');var autoFooter=objectPop(sourceNode.attr,'footer');var autoColumnset=objectExtract(sourceNode.attr,'columnset_*');if(objectNotEmpty(autoColumnset)&&!columnsets){columnsets=new gnr.GnrBag();for(var k in autoColumnset){var cl=k.split('_');var cn=columnsets.getNode(cl[0],null,true);cn.attr[cl[1]||'name']=autoColumnset[k];}
sourceNode.setRelativeData(sourceNode.absDatapath(sourceNode.attr.structpath)+'.info.columnsets',columnsets,null,false);}
var gridattr=objectUpdate({},sourceNode.attr);var _columnsetsNode,_footersNode;var containerAttr=objectExtract(gridattr,'region,pageName,title,margin,height,width');containerAttr.tag='BorderContainer';sourceNode.attr=containerAttr;sourceNode.label='grid_wrapper';sourceNode.setValue(new gnr.GnrDomSource(),false);var top=sourceNode._('ContentPane','columnsets',{region:'top',datapath:gridattr.datapath,hidden:true},{'doTrigger':false});_columnsetsNode=top.getParentNode();top._('div','scrollbox',{_class:'gr_columnset gr_scrollbox'},{'doTrigger':false});var bottom=sourceNode._('ContentPane','footers',{region:'bottom',datapath:gridattr.datapath,hidden:true},{'doTrigger':false});_footersNode=bottom.getParentNode();bottom._('div','scrollbox',{_class:'gr_footer gr_scrollbox'},{'doTrigger':false});gridattr.fillDown=gridattr.fillDown===false?false:true;var center=sourceNode._('ContentPane','gridpane',{region:'center'},{'doTrigger':false});var gridNode=center.setItem('grid',content,gridattr,{'doTrigger':false});gridNode._columnsetsNode=_columnsetsNode;gridNode._footersNode=_footersNode;gridNode._footers=footers;gridNode._autoFooter=autoFooter;gridNode._wrapperNode=sourceNode;}},mixin_catch_columnset:function(value,kw,attr){this.updateColumnsetsAndFooters();},mixin_columnsetsAndFooters_size:function(){var headerList=dojo.query('th',this.viewsHeaderNode);var headerTable=dojo.query('table',this.viewsHeaderNode)[0];var totalWidth=headerTable?headerTable.clientWidth:0;var cb=function(container){if(!container){return;}
container.updAttributes({width:(totalWidth+2+'px')});var tr=container.getValue().getItem('#0.#0.#0');var idx=0;tr.forEach(function(n){var c=headerList[n.attr.idx];var width=c.clientWidth+'px';n.updAttributes({width:width});idx++;});};var columnsets=this.structBag.getItem('info.columnsets');var showColumnset=columnsets&&columnsets.len()>0;if(this.sourceNode._columnsetsNode){this.sourceNode._wrapperNode.widget.setRegionVisible('top',showColumnset);cb(this.sourceNode._columnsetsNode.getValue().getNode('scrollbox.itemcontainer'));}
if(this.sourceNode._footersNode){var showFooter=true;if(this.sourceNode._footers.len()==1&&this.sourceNode._footers.getItem('#0').len()==0){showFooter=false;}
genro.dom.setClass(this.sourceNode._footersNode,'gr_noFooter',!showFooter);this.sourceNode._wrapperNode.widget.setRegionVisible('bottom',showFooter||showColumnset);genro.dom.setClass(this.sourceNode._wrapperNode,'gr_wrap_footers',showFooter||showColumnset);cb(this.sourceNode._footersNode.getValue().getNode('scrollbox.itemcontainer'));}},mixin__columnsetsAndFooters_one:function(parent,source,colinfo,autoTitle){var scrollbox=parent._value.getNode('scrollbox');var tbl=scrollbox._('div','itemcontainer',{_class:'gr_itemcontainer'})._('table','tableNode',{_class:'gr_table selectable'});var tbody=tbl._('tbody',{});var headerList=dojo.query('th',this.viewsHeaderNode);var totCols=0;var h=tbody._('tr','fakeHeader',{height:'0'});var idx=0;headerList.forEach(function(th){if(genro.dom.isVisible(th)){h._('th',{idx:idx,'border_right':'1px solid transparent'});totCols++;}
idx++;});var that=this;source.forEach(function(n){that._columnsetsAndFooters_row(tbody,n,colinfo,totCols,n.label=='footer_auto'?autoTitle:null);});},mixin__columnsetsAndFooters_row:function(pane,dataNode,colinfo,totCols,autoTitle){var data=dataNode.getValue();if(!data||data.len()===0){return;}
var rowattr=objectUpdate({},dataNode.attr);objectPop(rowattr,'tag');rowattr._class='columnsets_footers_row';var sourceNode=this.sourceNode;var rootsrc=genro.src.newRoot();var tr=rootsrc._('tr',rowattr);var currIdx=0;var sum_columns;if(this.collectionStore()){sum_columns=this.collectionStore().storeNode.getRelativeData('.sum_columns_source');}
var itemlist=[];data.forEach(function(n){var item=objectUpdate({},n.attr);objectPop(item,'tag');var infopars=colinfo.getAttr(item.field);var cell=infopars.cell;item.idx=infopars.rel_index;var value=objectPop(item,'value');if(item.footerCell&&!value){if(cell.totalize){if(isNumericType(cell.dtype)){value='^'+cell.totalize;item._totalized_value=value;item._filtered_totalized_value='^.filtered_totalize.'+cell.field;item.text_align='right';item.innerHTML='==_filtered_totalized_value!==null?_filtered_totalized_value:_totalized_value';}else{item.innerHTML=cell.totalize;}}else if(sum_columns&&sum_columns.getItem(cell.field)){}else{value='&nbsp;';}}else{item.innerHTML=value;}
itemlist.push(item);});itemlist.sort(function(a,b){return a.idx-b.idx;});itemlist.forEach(function(item){var colspan;var idx=objectPop(item,'idx');if(idx!=currIdx){colspan=idx-currIdx;tr._('td',{colspan:colspan,idx:currIdx})._('div',{innerHTML:autoTitle||'&nbsp;',text_align:'right'});autoTitle=null;}
colspan=objectPop(item,'colspan')||1;currIdx=idx+colspan;item._class=(item._class)||''+' groupcontent';item.selfsubscribe_clickAndHold=function(kw){if(sourceNode.attr.configurable&&kw.event.shiftKey){sourceNode.widget.configuratorColsetTooltip(this.attr,kw.event);}};tr._('td',item.field,{idx:idx,colspan:colspan})._('div',item);});if(currIdx<totCols){tr._('td',{colspan:totCols-currIdx,idx:currIdx})._('div',{innerHTML:'&nbsp;',width:'100%'});}
var n=rootsrc.popNode('#0');return pane.addItem(n.label,n._value,n.attr);},mixin_columnsetsAndFooters_autodata:function(){var colinfo=this.getColumnInfo();var autoRow=new gnr.GnrBag();var row_kw=this.sourceNode.evaluateOnNode(objectExtract(this.sourceNode.attr,'footer_*',true));colinfo.forEach(function(n){if(n.attr.isHidden){return;}
var cell=n.attr.cell;var footer_kw=objectExtract(cell,'footer_*',true);if(cell.totalize||objectNotEmpty(footer_kw)){footer_kw.footerCell=true;footer_kw.idx=cell.index;footer_kw.field=cell.field;footer_kw.dtype=cell.dtype;if(cell._formats){footer_kw.format=footer_kw.format||cell._formats.format||cell._formats.pattern;}
footer_kw.format=footer_kw.format||row_kw.format;autoRow.setItem(cell.field,null,footer_kw);}});this.sourceNode._footers.setItem('footer_auto',autoRow,row_kw,{_position:0});var columnsets=this.structBag.getItem('info.columnsets');if(columnsets){var sn=this.sourceNode;var columnset_groups={};columnsets.forEach(function(n){columnset_groups[n.label]=objectUpdate({},n.attr);columnset_groups[n.label].value=objectPop(columnset_groups[n.label],'name');});var columnsetRow=new gnr.GnrBag();colinfo.forEach(function(n){var cell=n.attr.cell;if(!n.attr.isHidden&&(cell.columnset&&cell.columnset in columnset_groups)){var columnset_kw=columnset_groups[cell.columnset];var idx=n.attr.rel_index;if((!('last_idx'in columnset_kw))||(idx-columnset_kw.last_idx>1)){columnset_kw.idx=idx;columnset_kw.field=cell.field;columnset_kw.colspan=1;}else{columnset_kw.colspan+=1;}
columnset_kw.last_idx=idx;var cnode=columnsetRow.getNode(columnset_kw.field,null,true);objectUpdate(cnode.attr,columnset_kw);}});this.sourceNode._columnsets=new gnr.GnrBag();this.sourceNode._columnsets.setItem('columnset_auto',columnsetRow);}else{this.sourceNode._columnsets=new gnr.GnrBag();this.sourceNode._columnsets.setItem('columnset_auto',new gnr.GnrBag());}},mixin_columnsetsAndFooters_make:function(){var that=this;var colinfo=this.getColumnInfo();var scrollbox;var sourceNode=this.sourceNode;if(sourceNode._columnsetsNode){this._columnsetsAndFooters_one(sourceNode._columnsetsNode,sourceNode._columnsets,colinfo);}
if(sourceNode._footersNode){var autoTitle=sourceNode._autoFooter;autoTitle=autoTitle&&typeof(autoTitle)=='string'?autoTitle:null;this._columnsetsAndFooters_one(sourceNode._footersNode,sourceNode._footers,colinfo,autoTitle);scrollbox=sourceNode._footersNode._value.getNode('scrollbox');genro.dom.setEventListener(scrollbox.domNode,'scroll',function(e){var sn=that.views.views[0].scrollboxNode;sn.scrollLeft=e.target.scrollLeft;if(sourceNode._columnsetsNode){sourceNode._columnsetsNode._value.getNode('scrollbox').domNode.scrollLeft=e.target.scrollLeft;}});}else{genro.dom.setEventListener(sourceNode.widget.domNode,'scroll',function(e){if(e.target===that.views.views[0].scrollboxNode){sourceNode._columnsetsNode._value.getNode('scrollbox').domNode.scrollLeft=e.target.scrollLeft;}},true);}},mixin_drawFiller:function(){if(!this.views.views[0]){return;}
var sb=this.views.views[0].scrollboxNode;if(this.sourceNode._footersNode){sb.style.height=this.sourceNode.getParentNode().widget.domNode.clientHeight-this.viewsHeaderNode.clientHeight+1+'px';}
var delta=sb.clientHeight-sb.firstElementChild.clientHeight;var filler=dojo.query('.fillernode',sb)[0];if(delta<=0){if(filler){sb.removeChild(filler);}
return;}
if(!filler){filler=document.createElement('div');filler.setAttribute('class','fillernode');sb.appendChild(filler);}
var vn=dojo.query('table',this.viewsHeaderNode)[0];if(!vn){return;}
filler.style.height=delta+'px';var totalWidth=vn.clientWidth-1;var tdlist=[];var colinfo=this.getColumnInfo();var cellinfo;dojo.query('th',this.viewsHeaderNode).forEach(function(n,idx){if(!n.clientWidth){return;}
var style="width:"+n.clientWidth+"px;";if(colinfo){cellinfo=colinfo.getAttr('#'+idx);if(cellinfo&&cellinfo.cell&&cellinfo.cell.cellStyles){style+=cellinfo.cell.cellStyles;}}
return tdlist.push('<td style="'+style+'"></td>');});filler.innerHTML='<table class="grid_filler" style="width:'+totalWidth+'px;"><tbody><tr>'+tdlist.join('')+'</tr></tbody></table>';},mixin_setDraggable_row:function(draggable,view){if(genro.isMobile){return;}
view=view||this.views.views[0];draggable=draggable===false?false:true;var builder=view.content;builder._table=builder._table.replace('<table draggable="true" ','<table ');if(draggable){builder._table=builder._table.replace('<table ','<table draggable="true" ');}
dojo.query('.dojoxGrid-row-table',this.domNode).forEach(function(n){n.draggable=draggable;});},mixin_setDropTarget_row:function(value){this.sourceNode.dropModes.row=value;},mixin_setDropTarget_column:function(value){this.sourceNode.dropModes.column=value;},mixin_setDropTarget_cell:function(value){this.sourceNode.dropModes.cell=value;},mixin_onSetStructpath:function(structure){return;},mixin_openLinkedForm:function(e){var idx=e.rowIndex;this.sourceNode.publish('editrow',{pkey:this.rowIdByIndex(idx)});},mixin_linkedFormLoad:function(e){var idx=e.rowIndex;this.sourceNode.publish('editrow',{pkey:this.rowIdByIndex(idx)});},selfDragColumnsPrepare:function(sourceNode){if(sourceNode.attr.selfDragColumns!='trashable'){gnr.convertFuncAttribute(sourceNode,'selfDragColumns','info');}
sourceNode.attr.draggable_column=true;var onDropCall=function(dropInfo,col){this.widget.moveColumn(col,dropInfo.column);};sourceNode.attr['onDrop_selfdragcolumn_'+sourceNode._id]=onDropCall;if(sourceNode.attr.configurable){var frameNode=genro.getFrameNode(sourceNode.attr.frameCode);sourceNode.registerSubscription('endDrag',sourceNode,function(){genro.dom.removeClass(sourceNode.attr.configuratorId||frameNode,'treeShowTrash');});sourceNode._showTrash=function(show){genro.dom.addClass(sourceNode.attr.configuratorId||frameNode,'treeShowTrash');};sourceNode.attr.onTrashed=sourceNode.attr.onTrashed||'this.widget.deleteColumn(data);';}},selfDragRowsPrepare:function(sourceNode){gnr.convertFuncAttribute(sourceNode,'selfDragRows','info');gnr.convertFuncAttribute(sourceNode,'onSelfDropRows','rows,dropInfo');gnr.convertFuncAttribute(sourceNode,'afterSelfDropRows','rows,dropInfo');sourceNode.attr.draggable_row=true;var row_counter_changes;var onDropCall=function(dropInfo,rows){if(!('row'in dropInfo)||(dropInfo.row<0)){return;}
if(sourceNode.attr.onSelfDropRows){sourceNode.attr.onSelfDropRows(rows,dropInfo);}else if(sourceNode.form&&sourceNode.form.isDisabled()){return;}else{dropInfo.widget.moveRow(rows,dropInfo.row);row_counter_changes=dropInfo.widget.updateCounterColumn();}
if(sourceNode.attr.afterSelfDropRows){sourceNode.attr.afterSelfDropRows(rows,dropInfo,row_counter_changes);}};sourceNode.attr['onDrop_selfdragrow_'+sourceNode._id]=onDropCall;},creating_common:function(attributes,sourceNode){if(!sourceNode.attr.storepath){if(sourceNode.attr.store){var storeNode=genro.nodeById(sourceNode.attr.store+'_store');if(!storeNode){console.log('missing storepath');}else{sourceNode.attr.storepath=storeNode.absDatapath(storeNode.attr.storepath);sourceNode._useStore=true;if(storeNode.store&&storeNode.store._linkedGrids){genro.src.onBuiltCall(function(){storeNode.store._linkedGrids.push(sourceNode.widget);},1);}}}}
sourceNode.attr.nodeId=sourceNode.attr.nodeId||'grid_'+sourceNode.getStringId();if(sourceNode.attr.controllerPath&&sourceNode.attr.controllerPath!=true){sourceNode.gridControllerPath=sourceNode.attr.controllerPath;}
else{var relativeWorkspace=sourceNode.attr.controllerPath||sourceNode.attr.relativeWorkspace;sourceNode.gridControllerPath=relativeWorkspace?sourceNode.absDatapath():'grids.'+sourceNode.attr.nodeId;}
if(sourceNode.attr.selfDragRows){this.selfDragRowsPrepare(sourceNode);}
if(sourceNode.attr.selfDragColumns||(sourceNode.attr.configurable&&sourceNode.attr.selfDragColumns!==false)){this.selfDragColumnsPrepare(sourceNode);}
objectExtract(attributes,'selected*');var savedAttrs={};var identifier=attributes.identifier||'_pkey';attributes.datamode=attributes.datamode||'attr';attributes.rowsPerPage=attributes.rowsPerPage||10;attributes.rowCount=attributes.rowCount||0;attributes.fastScroll=attributes.fastScroll||false;sourceNode.dropModes=objectExtract(sourceNode.attr,'dropTarget_*',true);if(!sourceNode.dropTarget&&objectNotEmpty(sourceNode.dropModes)){sourceNode.dropTarget=true;}
var attributesToKeep='_class,pageName,autoHeight,autoRender,autoWidth,defaultHeight,elasticView,fastScroll,keepRows,model,rowCount,rowsPerPage,singleClickEdit,structure,';var styleDict=genro.dom.getStyleDict(attributes);if(styleDict.width=='auto'){delete styleDict.width;attributes.autoWidth=true;}
if(styleDict.height=='auto'){delete styleDict.height;attributes.autoHeight=true;}
attributes.style=objectAsStyle(styleDict);attributesToKeep=attributesToKeep+'style,scaleX,scaleY,datamode,sortedBy,filterColumn,excludeCol,excludeListCb,editorEnabled,editorSaveMethod,autoInsert,autoDelete';var gridAttributes=objectExtract(attributes,attributesToKeep);objectPopAll(attributes);objectUpdate(attributes,gridAttributes);attributes._identifier=identifier;sourceNode.highlightExternalChanges=sourceNode.attr.highlightExternalChanges||true;if(sourceNode.attr.userSets){sourceNode.registerDynAttr('userSets');var userSets=new gnr.GnrBag();sourceNode.setRelativeData(sourceNode.attr.userSets,userSets);sourceNode._usersetgetter=function(cellname,row,idx){var currSet=sourceNode.getRelativeData(sourceNode.attr.userSets+'.'+cellname);var checkedField=this.widget.cellmap[cellname].checkedField;if(currSet){return currSet.match(new RegExp('(^|,)'+row[checkedField]+'($|,)'))!==null;}else{return false;}}}
return savedAttrs;},creating_structure:function(attributes,sourceNode){var structBag=sourceNode.getRelativeData(sourceNode.attr.structpath);if(structBag&&genro.grid_configurator){sourceNode.setRelativeData('.resource_structs.__baseview__',structBag.deepCopy(),{caption:_T('Base View')});}
attributes.structBag=structBag;sourceNode.registerDynAttr('structpath');attributes.cellmap={};attributes.structure=this.structFromBag(sourceNode,attributes.structBag,attributes.cellmap);},mixin_onAddedView:function(view){var draggable_row=this.sourceNode.getAttributeFromDatasource('draggable_row');if(draggable_row){this.setDraggable_row(true,view);}},created_common:function(widget,savedAttrs,sourceNode){var nodeId=sourceNode.attr.nodeId;var gridContent=sourceNode.getValue()||new gnr.GnrDomSource();if(genro.grid_configurator){if(sourceNode.attr.configurable){genro.src.onBuiltCall(function(){genro.grid_configurator.addGridConfigurator(sourceNode);genro.grid_configurator.setFavoriteView(sourceNode.attr.nodeId);},1);}}
if(sourceNode._useStore){widget.setEditableColumns();widget.setChangeManager();}
var gridEditorNode=gridContent.getNodeByAttr('tag','grideditor',true);if(gridEditorNode){widget.gridEditor=new gnr.GridEditor(widget);}
var menuNode=gridContent.getNodeByAttr('tag','menu',true);if(!menuNode&&sourceNode.attr.gridplugins!==false){sourceNode.setRelativeData('.contextMenu',this.pluginContextMenuBag(sourceNode));sourceNode._('menu','contextMenu',{storepath:'.contextMenu',_class:'smallmenu'},{doTrigger:false});gridContent=sourceNode.getValue();menuNode=gridContent.getNode('contextMenu');}
if(menuNode){widget.onCellContextMenu=function(e){menuNode.rowIndex=e.rowIndex;menuNode.cellIndex=e.cellIndex;};}
if('draggable_row'in sourceNode.attr){dojo.connect(widget.views,'addView',dojo.hitch(widget,'onAddedView'));if(widget.views.views.length>0){var draggable_row=sourceNode.getAttributeFromDatasource('draggable_row');widget.setDraggable_row(draggable_row,widget.views.views[0]);}}
if(sourceNode.attr.openFormEvent){dojo.connect(widget,sourceNode.attr.openFormEvent,widget,'openLinkedForm');}
if(sourceNode.attr.loadFormEvent){dojo.connect(widget,sourceNode.attr.loadFormEvent,widget,'linkedFormLoad');}
objectFuncReplace(widget.selection,'clickSelectEvent',function(e){if(sourceNode.attr.selectGroupColumns&&(e.shiftKey&&(e.ctrlKey||e.metaKey))){sourceNode.widget.groupColumnsSelect(e.rowIndex,sourceNode.attr.selectGroupColumns);}else{this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);}});sourceNode.registerSubscription(nodeId+'_reload',widget,function(keep_selection){this.reload(keep_selection!==false);});sourceNode.registerSubscription(nodeId+'_serverAction',widget,function(kw){if(this.serverAction){this.serverAction(kw);}});sourceNode.registerSubscription(nodeId+'_printRows',widget,function(kw){if(this.printRows){this.printRows(kw);}});sourceNode.subscribe('pluginCommand',function(kw){kw.grid=this.widget;genro.pluginCommand(kw);});sourceNode.subscribe('updatedSelectedRow',function(){var selectedIndex=this.widget.selection.selectedIndex;this.widget.sourceNode.setAttributeInDatasource('selectedId',this.widget.rowIdByIndex(selectedIndex),null,this.widget.rowByIndex(selectedIndex),true);});sourceNode.subscribe('configuratorPalette',function(){this.widget.configuratorPalette();});sourceNode.subscribe('clickAndHold',function(kw){var event=kw.event;if(this.attr.configurable&&event.shiftKey){this.widget.configuratorCellTooltip(event);}});if(sourceNode.getRelativeData('.filterset')){widget.filterManager=new gnr.GridFilterManager(widget);sourceNode.attr.filterset='.filterset';sourceNode.registerDynAttr('filterset');}
var searchBoxCode=(sourceNode.attr.frameCode||nodeId)+'_searchbox';var searchBoxNode=genro.nodeById(searchBoxCode);if(searchBoxNode){if(searchBoxNode.getRelativeData('.menu_auto')){_this=this;var cb=function(){genro.publish(searchBoxCode+'_updmenu',_this._getFilterAutoValues(widget,searchBoxNode.getRelativeData('.menu_dtypes')));};dojo.connect(widget,'onSetStructpath',widget,cb);dojo.connect(widget,'newDataStore',function(){searchBoxNode.setRelativeData('.currentValue','');searchBoxNode.setRelativeData('.value','');});setTimeout(function(){cb.call(widget);},1);}
sourceNode.registerSubscription(searchBoxCode+'_changedValue',widget,function(v,field){this.applyFilter(v,null,field);genro.dom.setClass(this.domNode,'filteredGrid',v);this.updateTotalsCount();});sourceNode.registerSubscription(searchBoxCode+'_stopSearch',widget,function(kw){kw.finalize();});sourceNode.subscribe('command',function(){widget[arguments[0]](arguments.slice(1));});}
if(widget.sourceNode.attr.filteringGrid){widget.filteringMode=widget.sourceNode.currentFromDatasource(sourceNode.attr.filteringMode)||'exclude';var filteringColumn=sourceNode.attr.filteringColumn.replace(/\./g,'_').replace(/@/g,'_');var filteredColumn=filteringColumn;if(filteringColumn.indexOf(':')>=0){filteringColumn=filteringColumn.split(':');filteredColumn=filteringColumn[1];filteringColumn=filteringColumn[0];}
var connectFilteringGrid=function(){var filteringGrid=widget.sourceNode.currentFromDatasource(widget.sourceNode.attr.filteringGrid);filteringGrid=filteringGrid.widget;if(filteringGrid.gridEditor){dojo.connect(filteringGrid,'setStorepath',function(p,kw){if(kw.node.label==filteredColumn||kw.evt=='ins'||kw.evt=='del'||kw.reason=='loadData'){widget.filterToRebuild(true);widget.updateRowCount('*');}});}else{dojo.connect(filteringGrid,'newDataStore',function(){widget.filterToRebuild(true);widget.updateRowCount('*');});}
widget.excludeListCb=function(){return filteringGrid.getColumnValues(filteredColumn);};widget.excludeCol=filteringColumn;};genro.src.onBuiltCall(connectFilteringGrid);}
if(sourceNode.attr.rowCustomClassesCb){widget.rowCustomClassesCb=funcCreate(sourceNode.attr.rowCustomClassesCb,'row');}
if(sourceNode.attr.fillDown||sourceNode._wrapperNode){dojo.connect(widget,'postrender',function(){if(!sourceNode._columnsetAndFootersInitialized){var widget=this;sourceNode.delayedCall(function(){widget.updateColumnsetsAndFooters();},1,'updateColumnsetsAndFooters');}
if(this.sourceNode.attr.fillDown){this.drawFiller();}});dojo.connect(sourceNode.getParentNode().getParentNode().widget,'resize',function(){sourceNode._columnsetAndFootersInitialized=false;});if(sourceNode.attr.fillDown){dojo.connect(widget,'updateRowCount',function(){var that=this;setTimeout(function(){that.drawFiller();},1);});}}
dojo.connect(widget,'onKeyEvent',function(e){if(e.type=='keydown'&&!widget.gnrediting){var kt=keyName(e.keyCode);if(kt){if((kt=='DOWN_ARROW')||(kt=='UP_ARROW')){widget.moveSelectedRow((kt=='DOWN_ARROW'?1:-1),true);e.preventDefault();}}}});dojo.connect(sourceNode.widget,'setCellWidth',function(inIndex,inUnitWidth){this.structBag.getItem('view_0.rows_0').getNode('#'+inIndex).updAttributes({width:inUnitWidth});});dojo.connect(widget,'onFocus',function(){this.changedFocus(true);this.sourceNode.publish('onFocus',{});});dojo.connect(widget,'onBlur',function(){this.changedFocus(false);this.sourceNode.publish('onBlur',{});});dojo.connect(widget,'onCellDblClick',function(evt){if(evt.cell.remoteEdit){this.remoteCellEdit(evt.cell,evt.rowIndex);}});dojo.connect(widget,'onCellClick',function(evt){this.sourceNode.publish('onCellClick',{evt:evt,cellNode:evt.cellNode});});if(sourceNode.attr.autoInsert){dojo.connect(widget,'setStorepath',function(val,kw){if(kw.evt=='upd'&&kw.reason!='autoRow'&&kw.node.label==widget.masterEditColumn()){if(!isNullOrBlank(kw.value)&&isNullOrBlank(kw.oldvalue)&&this.autoInsert){this.autoInsertHandler();}}});}
var gridData=sourceNode.getRelativeData();gridData.setCallBackItem('menuColsConfigMenu',function(){var result=new gnr.GnrBag();var grid=sourceNode.widget;var cells=grid.getColumnInfo();cells.getNodes().forEach(function(n,idx){result.addItem(n.label,null,{caption:n.attr.cell.name,cell:n.attr.cell});});result.addItem('-',null,{caption:'-'});result.addItem('_newcol',null,{caption:_T('New formula cell'),cell:'newcell'});return result;});setTimeout(function(){widget.updateRowCount('*');},1);},cm_plugin_configurator:function(sourceNode,menu){menu.setItem('#id',null,{caption:_T('Configure grid'),action:"$2.widget.configuratorPalette();"});},cm_plugin_export_xls:function(sourceNode,menu){menu.setItem('#id',null,{caption:_T('Export XLS'),action:"$2.widget.serverAction({command:'export',allRows:true,opt:{export_mode:'xls',downloadAs:$2.attr.nodeId+'_export'}});"});},cm_plugin_print:function(sourceNode,menu){menu.setItem('#id',null,{caption:_T('Print'),action:'$2.publish("printRows");'});},cm_plugin_chartjs:function(sourceNode,menu){menu.setItem('#id',genro.dev.userObjectMenuData({'objtype':'chartjs','flags':genro.getData('gnr.pagename')+'_'+sourceNode.attr.nodeId,'table':sourceNode.attr.table},[{pkey:'__newchart__',caption:_T('New chart')}]),{caption:_T('Charts'),action:"$2.publish('pluginCommand',{plugin:'chartjs',command:'openGridChart',pkey:$1.pkey,caption:$1.caption});"});},cm_plugin_stats:function(sourceNode,menu){menu.setItem('#id',genro.dev.userObjectMenuData({'objtype':'stats','flags':genro.getData('gnr.pagename')+'_'+sourceNode.attr.nodeId,'table':sourceNode.attr.table},[{pkey:'__newobj__',caption:_T('New stats')}]),{caption:_T('Stats'),action:"$2.publish('pluginCommand',{plugin:'statspane',command:'openGridStats',pkey:$1.pkey,caption:$1.caption});"});},pluginContextMenuBag:function(sourceNode){var gridplugins=sourceNode.attr.gridplugins;if(!gridplugins){gridplugins='chartjs,export_xls,print';if(sourceNode.attr.configurable&&genro.grid_configurator){gridplugins='configurator,'+gridplugins;}}
var contextMenuBag=sourceNode.getRelativeData('.contextMenu')||new gnr.GnrBag();gridplugins=gridplugins?gridplugins.split(','):[];var that=this;if(gridplugins){contextMenuBag.setItem('r_'+contextMenuBag.len(),null,{caption:'-'});gridplugins.forEach(function(cm_plugin){that['cm_plugin_'+cm_plugin](sourceNode,contextMenuBag);});}
contextMenuBag.setItem('r_'+contextMenuBag.len(),null,{caption:_T('Toggle line number'),checked:'^'+sourceNode.attr.structpath+'.info.showLineNumber',action:function(line,gridNode){gridNode.widget.toggleLineNumberColumn()}})
return contextMenuBag;},mixin_printRows:function(){var kw={res_type:'print',table:this.sourceNode.attr.table,resource:'_common/print_gridres',gridId:this.sourceNode.attr.nodeId};objectUpdate(kw,this.currentSelectionPars());if(kw.selectedPkeys){kw.allSelectionPkeys=this.getAllPkeys();}
genro.publish('table_script_run',kw);},mixin_setAutoInsert:function(autoInsert){this.autoInsert=autoInsert;},mixin_setAutoDelete:function(autoDelete){this.autoDelete=autoDelete;},mixin_setFilteringMode:function(filteringMode){this.filteringMode=filteringMode||'exclude';this.filterToRebuild(true);this.updateRowCount();},mixin_changedFocus:function(focus){genro.dom.setClass(this.domNode,'focusedGrid',focus);this.sourceNode.setRelativeData('.focused',focus);this.isFocused=focus;if(this.autoInsert){var that=this;var wastabbed=genro._lastKeyDown?genro._lastKeyDown.code=='Tab':false;var slen=that.storebag().len();setTimeout(function(){var insertedNode=that.autoInsertHandler();if(insertedNode){that.domNode.focus();}
if(wastabbed||slen==0){that.editBagRow(genro._lastKeyDown&&genro._lastKeyDown.shiftKey?-1:0);}},1);}},mixin_autoInsertHandler:function(){},mixin_rowBagNodeByIdentifier:function(identifier){return this.storebag().getNodeByAttr(this.rowIdentifier(),pkey);},mixin_updateTotalsCount:function(countBoxNode){var countBoxCode=(this.sourceNode.attr.frameCode||this.sourceNode.attr.nodeId)+'_countbox';countBoxNode=genro.nodeById(countBoxCode);if(countBoxNode){var shown=this.storeRowCount();var total=this.storeRowCount(true);genro.dom.setClass(countBoxNode,'unfilteredCount',shown==total);genro.dom.setClass(countBoxNode,'countBoxVisible',total>=0);countBoxNode.setRelativeData('.shown',shown);countBoxNode.setRelativeData('.total',total);}},_getFilterAutoValues:function(widget,dtypes){var structbag=widget.structbag();var values=[];var auto=[];values.push(null);var struct=widget.structbag();var cellsbag=struct&&struct.getItem('#0.#0')?struct.getItem('#0.#0'):new gnr.GnrBag();var caption,cellattr,cell_cap,cell_field,fltList,colList,col;var cellmap=widget.cellmap;var cellobj;var fld;cellsbag.forEach(function(n){cellattr=n.attr;cell_cap=cellattr.name||cellattr.field;cell_field=n.attr.field.replace(/\W/g,'_');if(n.attr.group_aggr){cell_field+='_'+n.attr.group_aggr.toLowerCase().replace(/\W/g,'_');}
cellobj=cellmap[cell_field];if(cellobj.classes&&cellobj.classes.indexOf('hiddenColumn')>=0){return;}
cell_field=cellobj.field_getter;if(!dtypes||(dtypes.indexOf(cellattr.dtype)>=0)){values.push(cell_cap+':'+cell_field);auto.push(cell_field);}});values[0]='Auto:'+auto.join('+');return values.join(',');},created:function(widget,savedAttrs,sourceNode){this.created_common(widget,savedAttrs,sourceNode);dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');genro.src.onBuiltCall(dojo.hitch(widget,'render'));dojo.connect(widget,'modelAllChange',dojo.hitch(sourceNode,this.modelAllChange));},modelAllChange:function(){if(this.attr.rowcount){this.setRelativeData(this.attr.rowcount,this.widget.rowCount);}},mixin_columnNodelist:function(idx,includeHeader){var condition='td.dojoxGrid-cell[idx="'+idx+'"]';if(includeHeader){condition='td.dojoxGrid-cell[idx="'+idx+'"], th.dojoxGrid-cell[idx="'+idx+'"]';}
return dojo.query(condition,this.domNode);},mixin_rowIdByIndex:function(idx){if(idx!==null){return this.rowIdentity(this.rowByIndex(idx));}},mixin_rowByIndex:function(idx){return this.model.getRow(idx);},mixin_rowIdentity:function(row){if(row){return row[this.rowIdentifier()];}else{return null;}},mixin_rowIdentifier:function(row){return this.model.store._identifier;},mixin_rowItemByIndex:function(idx){identifier=this.rowIdentity(this.rowByIndex(idx));return this.model.store.fetchItemByIdentity({identity:identifier});},mixin_rowItemByIdentity:function(identifier){return this.model.store.fetchItemByIdentity({identity:identifier});},mixin_moveSelectedRow:function(delta,cycle){var row=(this.selection.selectedIndex||0)+delta;var rowMax=this.rowCount-1;if((row>rowMax)||(row<0)){if(cycle){row=row>rowMax?0:rowMax;this.selection.select(row);this.scrollToRow(row);}}else{if(row>(this.scroller.lastVisibleRow)){this.scrollToRow(row);}else if(row<this.scroller.firstVisibleRow){this.scrollToRow(row);}
this.selection.select(row);}},mixin__gnrUpdateSelect:function(idx){if(this.sourceNode.attr.selectedDataPath){var selectedDataPath=null;if(idx>=0){selectedDataPath=this.dataNodeByIndex(idx).getFullpath(null,true);}
this.sourceNode.setAttributeInDatasource('selectedDataPath',selectedDataPath);}
if(this.sourceNode.attr.selectedLabel){var selectedLabel=null;if(idx>=0){var datanode=this.dataNodeByIndex(idx);selectedLabel=datanode?this.dataNodeByIndex(idx).label:null;}
this.sourceNode.setAttributeInDatasource('selectedLabel',selectedLabel);}
var selattr=objectExtract(this.sourceNode.attr,'selected_*',true);var selectedPkeys=this.getSelectedPkeys();var row={};var selectedId=null;if(idx>=0){row=this.rowByIndex(idx);selectedId=this.rowIdentity(row);}
for(var sel in selattr){this.sourceNode.setRelativeData(selattr[sel],row[sel]);}
if(this.sourceNode.attr.selectedIndex){this.sourceNode.setAttributeInDatasource('selectedIndex',((idx<0)?null:idx));}
if(this.sourceNode.attr.selectedPkeys){this.sourceNode.setAttributeInDatasource('selectedPkeys',selectedPkeys);}
if(this.sourceNode.attr.selectedRowidx){this.sourceNode.setAttributeInDatasource('selectedRowidx',this.getSelectedRowidx().join(','));}
if(this.sourceNode.attr.selectedNodes){var nodes=this.getSelectedNodes();var selNodes;if(nodes){selNodes=new gnr.GnrBag();dojo.forEach(nodes,function(node){selNodes.setItem(node.label,null,node.getAttr());});}
genro.setData(this.sourceNode.attrDatapath('selectedNodes'),selNodes,{'count':selNodes.len()});}
if(this.sourceNode.attr.selectedId){this.sourceNode.setAttributeInDatasource('selectedId',selectedId,null,row,true);}
if(this.sourceNode.attr.selectedRowData){var rowDataBag=new gnr.GnrBag(row);rowDataBag.popNode('_pkey');this.sourceNode.setAttributeInDatasource('selectedRowData',rowDataBag);}
this.sourceNode.setRelativeData('.currentSelectedPkeys',selectedPkeys);this.sourceNode.publish('onSelectedRow',{'idx':idx,'selectedId':selectedId,'grid':this,'selectedPkeys':selectedPkeys});},mixin_indexByRowAttr:function(attrName,attrValue,op,backward){op=op||'==';var that=this;var cmp=genro.compareDict[op];var cb=function(row){return cmp.call(that,row[attrName],attrValue);};var result=this.indexByCb(cb,backward);return result;},mixin_indexByCb:function(cb,backward){var n=this.rowCount;for(var i=0;i<n;i++){var k_i=backward?n-i:i;if(cb(this.rowByIndex(k_i))){return k_i;}}
return-1;},mixin_hasRow:function(attr,value){if(typeof(attr)=='function'){cb=attr;}else{cb=function(n){return n[attr]==value;};}
return this.indexByCb(cb)>=0;},mixin_selectByRowAttr:function(attrName,attrValue,op,scrollTo,default_idx){var selection=this.selection;var idx=-1;if(attrValue instanceof Array&&attrValue.length==1){attrValue=attrValue[0];}
if(attrValue instanceof Array){selection.unselectAll();var grid=this;dojo.forEach(attrValue,function(v){var idx=grid.indexByRowAttr(attrName,v);if(idx>=0){selection.addToSelection(idx);}});}else{var idx=this.indexByRowAttr(attrName,attrValue,op);if(idx<0&&default_idx!=null&&default_idx>=0){idx=default_idx;}
if(idx>=0){selection.select(idx);}}
if(scrollTo===true&&typeof(idx)=='number'&&idx>=0){scrollTo=idx;}
if(scrollTo){this.scrollToRow(scrollTo);}
return idx;},mixin_rowBagNode:function(idx){var idx=(idx==null)?this.selection.selectedIndex:idx;return this.model.store.rootData().getNodes()[idx];},mixin_rowBagNodeUpdate:function(idx,data){var bagnode=this.rowBagNode(idx);var attributes=bagnode.attr;for(var attr in attributes){var newvalue=data.getItem(attr);if(newvalue!=null){attributes[attr]=newvalue;}}
bagnode.setAttr(attributes);},mixin_getSelectedPkeys:function(caption_field){var sel=this.selection.getSelected();var result=[];var r;if(sel.length>0){for(var i=0;i<sel.length;i++){r=this.rowByIndex(sel[i]);result.push(caption_field?{'pkey':this.rowIdentity(r),'caption':r[caption_field]}:this.rowIdentity(r))}}
return result;},mixin_getAllPkeys:function(caption_field){if(this.collectionStore){return this.collectionStore().currentPkeys(caption_field);}else{var result=[];for(var i=0;i<this.rowCount;i++){result.push(this.rowIdByIndex(i));}
return result;}},mixin_cellCurrentDatapath:function(path){console.error('not implemented')},mixin_getSelectedRow:function(){return this.rowByIndex(this.selection.selectedIndex);},mixin_longTouch:function(e){alert('longtouch');},mixin_getSelectedRowidx:function(){var sel=this.selection.getSelected();var result=[];for(var i=0;i<sel.length;i++){var row=this.rowByIndex(sel[i]);result.push(row.rowidx);}
return result;},structFromBag_cellFormatter:function(sourceNode,cell,formatOptions,cellClassCB){var cellClassFunc;if(cellClassCB){cellClassFunc=funcCreate(cellClassCB,'cell,v,inRowIndex,originalValue',this);}
return function(v,inRowIndex){var opt=objectUpdate({},formatOptions);var renderedRow=this.grid.currRenderedRow;if(!objectNotEmpty(renderedRow)){return'<div class="cellContent">'+'&nbsp;'+'</div>';}
var baseStyleDict=objectUpdate(objectFromStyle(this.cellStyles),sourceNode.evaluateOnNode(genro.dom.getStyleDict(objectUpdate({},this),['width'])))
var ranges=objectExtract(cell,'range_*',true);if(objectNotEmpty(ranges)){var rangepars=objectUpdate({},renderedRow);rangepars.value=v;rangepars._kwargs=rangepars;for(var rng in ranges){if(stringEndsWith(rng,'_condition')||rng.indexOf('_')<=0){var condition=funcApply('return '+ranges[rng],rangepars,sourceNode);if(condition){var prefix=rng.replace('_condition','');var styleKw=objectExtract(ranges,prefix+'_*',true);objectUpdate(baseStyleDict,sourceNode.evaluateOnNode(genro.dom.getStyleDict(styleKw,['width'])))}}}}
var styles=objectExtract(renderedRow,'style_'+cell.field+'_*',true);objectUpdate(baseStyleDict,styles);this.customStyles.push(objectAsStyle(baseStyleDict));if(cellClassFunc){var cellClassFuncResult=cellClassFunc(this,v,inRowIndex,renderedRow[cell.field]);if(cellClassFuncResult){this.customClasses.push(cellClassFuncResult);}}
var cellCustomClass=renderedRow['_customClass_'+cell.field];if(cellCustomClass){this.customClasses.push(cellCustomClass);}
if(this.edit||this.remoteEdit){this.customClasses.push('cell_editable');if(this.editDisabled){if(this.grid.sourceNode.currentFromDatasource(this.editDisabled)){this.customClasses.push('cell_disabled');}}
if(this.editLazy){if(this.grid.sourceNode.currentFromDatasource(this.editLazy)){this.customClasses.push('cell_editLazy');}}}
opt['cellPars']={rowIndex:inRowIndex};if(typeof(v)=='number'){if(v<0){this.customClasses.push('negative_number');}
if(this.emptyZero&&v===0){v=null;}}
if(this.grid.gridEditor){this.grid.gridEditor.onFormatCell(this,inRowIndex,renderedRow);}
for(let k in opt){let vopt=opt[k];if(typeof(vopt)=='string'&&vopt.startsWith('#ROW.')){vopt=renderedRow[vopt.slice(5)];}
opt[k]=vopt;}
v=genro.format(v,opt);if(v==null){v='&nbsp;';}
var template=opt.template;if(template){if(template.indexOf('$'+cell.field)>=0){v=dataTemplate(template,renderedRow);}else{v=template.replace(/#/g,v);}}
if(opt.js){v=opt.js(v,this.grid.storebag().getNodes()[inRowIndex]);}
var zoomAttr=objectExtract(opt,'zoom_*',true);var draggable=this.draggable?' draggable=true ':'';if(objectNotEmpty(zoomAttr)){return"<div "+draggable+" class='cellContent gnrzoomcell' onclick='if(event.shiftKey){dojo.stopEvent(event); genro.dlg.zoomFromCell(event);}'>"+v+"</div>";}else{return'<div '+draggable+'class="cellContent">'+v+'</div>';}};},subtableGetter:function(row,idx){var cellattr=this.grid.cellmap[this.field];var data=row[cellattr._subtable];if(cellattr.key){data=data[this.grid.sourceNode.currentFromDatasource(cellattr.key)];}
if(data){return data[cellattr._subfield];}},structFromBag_cell:function(sourceNode,cellNode,columnsets){var rowattrs=objectUpdate({},cellNode.getParentNode().attr);rowattrs=objectExtract(rowattrs,'classes,headerClasses,cellClasses');var cell=objectUpdate({field:cellNode.label},rowattrs);var columnset=cellNode.attr.columnset;if(columnset){var columnsetAttrs=columnsets.getAttr(columnset)||{};objectUpdate(cell,objectExtract(columnsetAttrs,'cells_*',true));}
cell=objectUpdate(cell,cellNode.attr);if(!cell.width&&cell.dfltwidth){cell.width=cell.dfltwidth;}
var dtype=cell.dtype;var cell_name=_F(sourceNode.currentFromDatasource(cell.name),cell.name_format);cell.original_field=cell.field;cell.original_name=cell_name;cell._nodelabel=cellNode.label;var userSets=objectPop(cell,'userSets');if(userSets){cellNode.attr['calculated']=true;cell=this.getNewSetKw(sourceNode,cell);dtype='B';}
var rowBasedAttr={};for(var k in cell){if(typeof(cell[k])=='string'&&cell[k].indexOf('#ROW')>=0){rowBasedAttr[k]=cell[k];}}
for(k in rowBasedAttr){delete cell[k];}
cell.name='<div '+((sourceNode.attr.draggable_column)?'draggable="true"':'')+' class="cellHeaderContent" >'+cell_name||'&nbsp;'+'</div>';if(cell.field){if(cell.field.indexOf(':')>=0&&!cell._customGetter){var f=cell.field.split(':');cell._customGetter=this.subtableGetter;cell._subtable=f[0];cell._subfield=f[1];}
if(typeof(cell.values)=='string'){var values=sourceNode.currentFromDatasource(cell.values);if(values.indexOf(':')>=0){var valuesdict=objectFromString(values);cell._customGetter=function(rowdata,idx){var currvalue=rowdata[this.field_getter];if(currvalue){var valuetoset=[];currvalue=(currvalue+'').split(',');dojo.forEach(currvalue,function(n){valuetoset.push(valuesdict[n]);});return valuetoset.join(',');}
return currvalue;};}}
if(cell.rowTemplate){cell.rowTemplate=sourceNode.currentFromDatasource(cell.rowTemplate);}
cell.field=cell.field.replace(/\W/g,'_');if(cell.group_aggr){cell.field+='_'+cell.group_aggr.toLowerCase().replace(/\W/g,'_');if(cell.dtype=='D'||cell.dtype=='DH'){dtype='T';}}
cell.field_getter=cell.caption_field?cell.caption_field.replace(/\W/g,'_'):cell.field;if(cell.caption_field||cell.values){dtype='T';}
var checkboxPars=objectPop(cell,'checkBoxColumn');if(checkboxPars){cell=this.getCheckBoxKw(checkboxPars,sourceNode,cell);cell.isCheckBoxCell=true;this.setCheckedIdSubscription(sourceNode,cell);dtype='B';}
if(dtype){cell.cellClasses=(cell.cellClasses||'')+' cell_'+dtype;}
var zoomAttr=objectExtract(cell,'zoom_*',true,true);cell.cellStyles=objectAsStyle(objectUpdate(objectFromStyle(cell.cellStyles),genro.dom.getStyleDict(cell,['width'])));var formats=objectExtract(cell,'format_*');var format=objectPop(cell,'format');var template=objectPop(cell,'template');var js=objectPop(cell,'js');if(template){formats['template']=template;}
formats['dtype']=dtype;if(js){formats['js']=genro.evaluate(js);}
if(objectNotEmpty(zoomAttr)){objectUpdate(formats,zoomAttr);}
if(format){formats['format']=format;}
if(cell.counter){sourceNode.attr.counterField=cell.field;dtype='L';}
if('hidden'in cell&&sourceNode.currentFromDatasource(cell.hidden)){cell.classes=(cell.classes||'')+' hiddenColumn';}
if(dtype){if(!formats.pattern){formats=objectUpdate(objectUpdate({},localType(dtype)),formats);}}
var cellClassCB=objectPop(cell,'cellClassCB');var _customGetter=objectPop(cell,'_customGetter');if(_customGetter){cell._customGetter=funcCreate(_customGetter);}
if(dtype=='B'){formats['trueclass']=formats['trueclass']||"checkboxOn";formats['falseclass']=formats['falseclass']||"checkboxOff";}
if(cell.totalize){cell.totalize=cell.totalize===true?'.totalize.'+cell.field:cell.totalize;}
if(cell.semaphore){formats['trueclass']='greenLight';formats['falseclass']='redLight';}else if(cell.inv_semaphore){formats['falseclass']='greenLight';formats['trueclass']='redLight';}else if(cell.highlight_semaphore){formats['falseclass']=' ';formats['trueclass']='yellowLight';}
objectUpdate(formats,objectExtract(rowBasedAttr,'format_*'));cell._formats=formats;cell.formatter=this.structFromBag_cellFormatter(sourceNode,cell,formats,cellClassCB);delete cell.tag;objectUpdate(cell,rowBasedAttr);return cell;}},structFromBag:function(sourceNode,struct,cellmap){cellmap=cellmap||{};var result=[];if(struct){sourceNode._serverTotalizeColumns={};var bagnodes=struct.getNodes();var columnsets=struct.getItem('info.columnsets')||new gnr.GnrBag();var formats,dtype,editor;var view,viewnode,rows,rowsnodes,i,k,j,cellsnodes,row,cell,rowattrs,rowBag;var editorPars=sourceNode.attr.gridEditorPars;var cellsort=[];for(let i=0;i<bagnodes.length;i++){viewnode=bagnodes[i];if(viewnode.label=='info'){continue;}
view=objectUpdate({},viewnode.attr);delete view.tag;rows=[];rowsnodes=viewnode.getValue().getNodes();for(var k=0;k<rowsnodes.length;k++){rowBag=rowsnodes[k].getValue();if(!(rowBag instanceof gnr.GnrBag)){rowBag=new gnr.GnrBag();rowsnodes[k].setValue(rowBag,false);}
if(rowBag.getNode('_rowEditorStatus')){rowBag.popNode('_rowEditorStatus',false);}
if(editorPars&&editorPars.statusColumn&&dojo.some(rowBag.getNodes(),function(n){return n.attr.edit;})){rowBag.setItem('_rowEditorStatus',null,{dtype:'T',width:'2em',field:'_rowEditorStatus',cellClasses:'rowEditorStatus',headerClasses:'rowEditorStatus',name:' ',calculated:true,_customGetter:function(rowdata,rowIdx){return this.grid.gridEditor.statusColGetter(rowdata,rowIdx);}},{'doTrigger':false});}
row=[];var showLineNumber=sourceNode.getRelativeData(sourceNode.attr.structpath+'.info.showLineNumber');if(isNullOrBlank(showLineNumber)){showLineNumber=sourceNode.attr.showLineNumber;}
if(showLineNumber){if(!rowBag.getNode('_linenumber')){rowBag.setItem('_linenumber',null,{'calculated':true,'dtype':'L','name':' ','width':'3em','classes':'gnrgridlineno','field':'_linenumber','format':'#,###','_customGetter':function(row,idx){return idx+1;}},{_position:0});}}else{rowBag.popNode('_linenumber');}
if(sourceNode.attr.rowStatusColumn){if(!rowBag.getNode('_protectionStatus')){rowBag.setItem('_protectionStatus',null,{field:'_protectionStatus',name:' ',width:'20px',calculated:true,_customGetter:function(){return'<div class="_statusIcon"></div>'}},{_position:0});}}
if(genro.isMobile&&sourceNode.attr.draggable_row){if(!rowBag.getNode('drag_handle')){rowBag.setItem('drag_handle',null,{field:'_drag_handle',name:' ',width:'23px',calculated:true,_customGetter:function(){return'<div class="menu_white_svg" style="background-color:#888; height:22px;border-radius:4px;" draggable="true">&nbsp;</div>';}},{_position:0});}}
if(sourceNode.attr.multiStores){if(!rowBag.getNode('_storenameCol')){rowBag.setItem('_storenameCol',null,{field:'_dbstore_',name:_T('Storename'),width:'15em',calculated:true});}}
var that=this;rowBag.forEach(function(n){cell=that.structFromBag_cell(sourceNode,n,columnsets);row.push(cell);cellmap[cell.field]=cell;if(cell.sort){cellsort.push(`${cell.field_getter}:${cell.sort}`);}},'static');rows.push(row);}
if(sourceNode.attr.sortedBy&&cellsort.length){sourceNode.setRelativeData(sourceNode.attr.sortedBy,cellsort.join(','));}
view.rows=rows;result.push(view);}}
return result;},groupByFromStruct:function(struct,grouppable){if(grouppable==undefined){grouppable=[];}
var nodes=struct.getNodes();for(var i=0;i<nodes.length;i++){var node=nodes[i];if(node.attr.group_by){var fld=node.attr.field;if((!stringStartsWith(fld,'$'))&&(!stringStartsWith(fld,'@'))){fld='$'+fld;}
grouppable.push(fld);}
if(node.getValue()instanceof gnr.GnrBag){this.groupByFromStruct(node.getValue(),grouppable);}}
return grouppable.join(',');},mixin_deleteColumn:function(col){var colsBag=this.structBag.getItem('#0.#0');colsBag.popNode('#'+col);},mixin_moveColumn:function(col,toPos){if(toPos!=col){var colsBag=this.structBag.getItem('#0.#0');var nodeToMove=colsBag.popNode('#'+col,false);colsBag.setItem(nodeToMove.label,null,nodeToMove.attr,{'_position':toPos});}},mixin_moveRow:function(row,toPos){if(toPos!=null&&toPos>=0&&toPos!=row){var storebag=this.storebag();storebag.moveNode(row,toPos,'movingRows');}},mixin_addColumn:function(col,toPos,kw){var colsBag=this.structBag.getItem('#0.#0');if(!kw){kw={'width':'8em','name':col.fullcaption,'dtype':col.dtype,'field':col.fieldpath,'tag':'cell'};if(col._owner_package){kw._owner_package=col._owner_package;}
if(kw.field.length>63){var hashname='relation_'+stringHash(kw.field)+'_'+kw.field.split('.').slice(-1);kw.queryfield=kw.field+' AS '+hashname;kw.field=hashname;}
objectUpdate(kw,objectExtract(col,'cell_*'));kw.format_pattern=col.format;objectUpdate(kw,objectExtract(col,'format_*',null,true));}
colsBag.setItem('cellx_'+genro.time36Id(),null,kw,{'_position':toPos+1});},onDragStart:function(dragInfo){var dragmode=dragInfo.dragmode;var event=dragInfo.event;var widget=dragInfo.widget;var value={};if(widget.gridEditor&&widget.gnrediting){return false;}
if(dragmode=='row'){var cells=widget.structure[0]['rows'][0];var sel=widget.selection.getSelected();var rowdata=widget.rowByIndex(dragInfo.row);if(sel.length==1){sel=[];}
if(sel.indexOf(dragInfo.row)<0){sel.push(dragInfo.row);}
sel.sort();var rowset=[];var pkeys=[];var valTextPlain=[];var valTextXml=[];var valTextHtml=[];var innerHtml=[];var idx=0;var rn;var innerHtmlTxt=sel.length>20?'<div style="width:600px;text-align:center;">'+sel.length+' '+widget.sourceNode.attr.item_name_plural+' </div>':null;dojo.forEach(sel,function(k){var rdata=widget.rowByIndex(k);pkeys.push(widget.rowIdentity(rdata));rowset.push(rdata);var r=[];var r_xml=[];var r_html=[];cells.forEach(function(n){var field=n.field;var v=convertToText(rdata[field],{'xml':true,'dtype':+n.dtype})[1];r.push(v);r_xml.push('<'+field+'>'+v+'</'+field+'>');r_html.push('<td name="'+field+'">'+v+'</td>');});if(!innerHtmlTxt){rn=widget.views.views[0].rowNodes[k];if(rn){innerHtml.push(rn.innerHTML);}}
valTextPlain.push(r.join('\t'));valTextXml.push('<r_'+idx+'>'+r_xml.join('')+'</r_'+idx+'>');valTextHtml.push('<tr>'+r_html.join('')+'</tr>');idx=idx+1;});var selfDragRows=dragInfo.sourceNode.attr.selfDragRows;if(typeof(selfDragRows)=='function'){selfDragRows=selfDragRows(dragInfo);}
if(selfDragRows){value['selfdragrow_'+dragInfo.sourceNode._id]=sel;}
value['text/plain']=valTextPlain.join('\n');value['text/xml']=valTextXml.join('\n');value['text/html']='<table>\n'+valTextHtml.join('\n')+'\n</table>';value['gridrow']={'row':dragInfo.row,'rowdata':rowdata,'rowset':rowset,'gridId':widget.sourceNode.attr.nodeId};if(widget.collectionStore&&widget.collectionStore()){var storeAttr=widget.collectionStore().storeNode.attr;value['dbrecords']={table:storeAttr['table'],pkeys:pkeys,objtype:'record'};}
if(sel.length>0){var auxDragImage=dragInfo.dragImageNode=dojo.byId('auxDragImage');dragInfo.dragImageNode=document.createElement('div');var auxnode=document.createElement('div');dojo.addClass(auxnode,'rowsetdragging');dragInfo.dragImageNode.appendChild(auxnode);auxnode.innerHTML=innerHtmlTxt||innerHtml.join('');dojo.addClass(dragInfo.dragImageNode,'rowsetdragging_background');auxDragImage.appendChild(dragInfo.dragImageNode);dragInfo.event.dataTransfer.setDragImage(auxDragImage.firstChild,0,0);setTimeout(function(){auxDragImage.removeChild(dragInfo.dragImageNode);},1);}}else if(dragmode=='cell'){var celldata=widget.rowByIndex(dragInfo.row)[event.cell.field];var rowdata=widget.rowByIndex(dragInfo.row);value['gridcell']={'row':dragInfo.row,'column':dragInfo.column,'celldata':celldata,'rowdata':rowdata,'gridId':widget.sourceNode.attr.nodeId};value['text/plain']=convertToText(celldata)[1];}else if(dragmode=='column'){var textcol='';var field=event.cell.field;columndata=[];for(var i=0;i<widget.rowCount;i++){var row=widget.rowByIndex(i,true);var v=row?row[field]:'';if(!isBag(v)){columndata.push(v);}
textcol=textcol+convertToText(v)[1]+'\n';}
value.gridcolumn={'column':dragInfo.column,'columndata':columndata,'gridId':widget.sourceNode.attr.nodeId,'field':field,'original_field':event.cell.original_field,'group_aggr':event.cell.group_aggr};value['text/plain']=textcol;var selfDragColumns=dragInfo.sourceNode.attr.selfDragColumns;if(typeof(selfDragColumns)=='function'){selfDragColumns=selfDragColumns(dragInfo);}
if(selfDragColumns){value['selfdragcolumn_'+dragInfo.sourceNode._id]=dragInfo.column;if(selfDragColumns=='trashable'){if(dragInfo.sourceNode._showTrash){dragInfo.sourceNode._showTrash(true);}
value['trashable']=dragInfo.column;}}}
return value;},fillDropInfo:function(dropInfo){var dragSourceInfo=dropInfo.dragSourceInfo;var event=dropInfo.event;var draggedTypes=genro.dom.dataTransferTypes(event.dataTransfer);var dropModes=dropInfo.sourceNode.dropModes;var dropmode;var selfdrop=(genro.page_id==dragSourceInfo.page_id)&&(dragSourceInfo._id==dropInfo.sourceNode._id);for(var k in dropModes){if(k=='grid'&&selfdrop){continue;}
if(dojo.filter(dropModes[k].split(','),function(value){return arrayMatch(draggedTypes,value).length>0;}).length>0){dropmode=k;break;};}
if(!dropmode&&dragSourceInfo.dragmode=='row'&&(dojo.indexOf(draggedTypes,'selfdragrow_'+dropInfo.sourceNode._id)>=0)){var selfDragRows=dropInfo.sourceNode.attr.selfDragRows;if(typeof(selfDragRows)=='function'){selfDragRows=selfDragRows(dropInfo);}
if(selfDragRows){dropmode='row';}}
if(!dropmode&&dragSourceInfo.dragmode=='column'&&(dojo.indexOf(draggedTypes,'selfdragcolumn_'+dropInfo.sourceNode._id)>=0)){var selfDragColumns=dropInfo.sourceNode.attr.selfDragColumns;if(typeof(selfDragColumns)=='function'){selfDragColumns=selfDragColumns(dropInfo);}
if(selfDragColumns){dropmode='column';}}
if(!dropmode){return false;}
var widget=dropInfo.widget;if(dropmode=='grid'){dropInfo.outline=widget.domNode;}
else if(dropmode=='column'){dropInfo.column=event.cellIndex;dropInfo.outline=widget.columnNodelist(event.cellIndex,true);}else{dropInfo.row=event.rowIndex;if(dropmode=='cell'){dropInfo.column=event.cellIndex;dropInfo.outline=event.cellNode;}else if(dropmode=='row'){dropInfo.outline=event.rowNode;if(widget&&dropInfo.row!=null){dropInfo.targetRowData=widget.rowByIndex(dropInfo.row);}}}
dropInfo.widget=widget;dropInfo.sourceNode=widget.sourceNode;},customEventInfo:function(info){var event=info.event;var widget=info.widget;if(widget.grid){widget.content.decorateEvent(event);widget=widget.grid;}else{widget.views.views[0].header.decorateEvent(event);}
info.column=event.cellIndex;info.row=event.rowIndex;info.widget=widget;info.sourceNode=widget.sourceNode;},fillDragInfo:function(dragInfo){var widget=dragInfo.widget;var event=dragInfo.event;if(event.cell&&event.cell.field=='_drag_handle'){event.cellIndex=-1;}
if((event.cellIndex>=0)&&(event.rowIndex==-1)){dragInfo.dragmode='column';dragInfo.outline=widget.columnNodelist(event.cellIndex,true);dragInfo.colStruct=widget.cellmap[event.cell.field];}else if((event.cellIndex==-1)&&(event.rowIndex>=0)){dragInfo.dragmode='row';dragInfo.outline=event.rowNode;}else if((event.cellIndex>=0)&&(event.rowIndex>=0)){dragInfo.dragmode='cell';dragInfo.outline=event.cellNode;dragInfo.colStruct=widget.cellmap[event.cell.field];}},setTrashPosition:function(dragInfo){var cellNode=dragInfo.event.cellNode;if(cellNode){var trash=genro.dom.getDomNode('trash_drop');var mb=dojo.marginBox(trash);var vp=dojo.coords(cellNode);trash.style.left=Math.floor(vp.x)+"px";trash.style.top=Math.floor(vp.y+vp.h+1)+"px";return true;}}});dojo.declare("gnr.widgets.VirtualGrid",gnr.widgets.DojoGrid,{constructor:function(application){this._domtag='div';this._dojotag='VirtualGrid';},creating:function(attributes,sourceNode){var savedAttrs=this.creating_common(attributes,sourceNode);this.creating_structure(attributes,sourceNode);var storepath=sourceNode.absDatapath(sourceNode.attr.storepath);attributes.storebag=genro.getDataNode(storepath,true,new gnr.GnrBag());if(!(attributes.storebag.getValue()instanceof gnr.GnrBag)){attributes.storebag.setValue(new gnr.GnrBag());}
attributes.get=function(inRowIndex){var grid=this.grid;if(grid.currRenderedRowIndex!=inRowIndex){grid.currRenderedRowIndex=inRowIndex;grid.currRenderedRow=grid.rowByIndex(inRowIndex);}
return grid.currRenderedRow[this.field];};attributes.canSort=function(info){return true;};return savedAttrs},created:function(widget,savedAttrs,sourceNode){this.created_common(widget,savedAttrs,sourceNode);dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');},mixin_canEdit:function(inCell,inRowIndex){return false;},mixin_loadBagPageFromServer:function(pageIdx){var row_start=pageIdx*this.rowsPerPage;var kw=this.storebag.attr;var data=genro.rpc.remoteCall(kw.method,{'selectionName':kw.selectionName,'row_start':row_start,'row_count':this.rowsPerPage,'sortedBy':this.sortedBy,'table':kw.table,'recordResolver':false});data=data.getValue();this.storebag.getValue().setItem('P_'+pageIdx,data);return data;},patch_sort:function(){var sortInfo=this.sortInfo;var order;if(sortInfo<0){order='d';sortInfo=-sortInfo;}else{order='a';}
var cell=this.layout.cells[sortInfo-1];var sortedBy=cell.field+':'+order;if((cell.dtype=='A')||(cell.dtype=='T')){sortedBy=sortedBy+'*';}
var path=this.sourceNode.attrDatapath('sortedBy');genro._data.setItem(path,sortedBy);},mixin_clearBagCache:function(){this.storebag.getValue().clear();this.currRenderedRowIndex=null;this.currRenderedRow=null;this.currCachedPageIdx=null;this.currCachedPage=null;},mixin_setSortedBy:function(sortedBy){this.sortedBy=sortedBy;var rowcount=this.rowCount;this.updateRowCount(0);this.clearBagCache();this.updateRowCount(rowcount);},mixin_rowBagNodeUpdate:function(idx,data,pkey){if(idx==-1){var storebag=this.storebag.getValue();var cells=this.layout.cells;var row={};var cell;for(var i=0;i<cells.length;i++){cell=cells[i];row[cell.field]=data.getItem(cell.field);}
var identifier=this.rowIdentifier();data[identifier]=pkey;row[identifier]=pkey;storebag.setItem(pkey,null,row);this.updateRowCount(storebag.len());}
else{var attributes=this.rowByIndex(idx);for(var attr in attributes){var newvalue=data.getItem(attr);if(newvalue!=null){attributes[attr]=newvalue;}}
var identifier=this.rowIdentifier();attributes[identifier]=pkey;this.updateRow(idx);}},mixin_rowIdByIndex:function(idx){if(idx!=null){return this.rowIdentity(this.rowByIndex(idx));}},mixin_rowByIndex:function(inRowIndex,lazy){var rowIdx=inRowIndex%this.rowsPerPage;var pageIdx=(inRowIndex-rowIdx)/this.rowsPerPage;if(this.currCachedPageIdx!=pageIdx){this.currCachedPageIdx=pageIdx;this.currCachedPage=this.storebag.getValue().getItem('P_'+pageIdx);if(!this.currCachedPage){if(lazy){return;}
this.currCachedPage=this.loadBagPageFromServer(pageIdx);}}
return this.currCachedPage?this.currCachedPage.getNodes()[rowIdx].attr:null;},mixin_rowIdentity:function(row){if(row){return row[this.rowIdentifier()];}else{return null;}},mixin_rowIdentifier:function(row){return this._identifier;},patch_onStyleRow:function(row){var attr=this.rowByIndex(row.index);if(attr){if(attr._protection_info=='DU'){row.customClasses=row.customClasses?row.customClasses+' _gnrReadOnlyRow':'_gnrReadOnlyRow';}else if(attr.__protection_tag){row.customClasses=row.customClasses?row.customClasses+' _gnrProtectionPass':'_gnrProtectionPass';}
if(attr._customClasses){var customClasses=null;if(typeof(attr._customClasses)=='function'){customClasses=attr._customClasses(row);}
if(attr._customClasses.slice(0,1)=='!'){customClasses=attr._customClasses.slice(1);}else{customClasses=row.customClasses+' '+attr._customClasses;}
row.customClasses=customClasses;}
if(attr._customStyles){row.customStyles=(typeof(_customStyles)=='function')?attr._customStyles(row):attr._customStyles;}}
row.over=this.enableOver&&row.over;this.onStyleRow_replaced(row);}});dojo.declare("gnr.widgets.VirtualStaticGrid",gnr.widgets.DojoGrid,{constructor:function(application){this._domtag='div';this._dojotag='VirtualGrid';},creating:function(attributes,sourceNode){var savedAttrs=this.creating_common(attributes,sourceNode);this.creating_structure(attributes,sourceNode);sourceNode.registerDynAttr('storepath');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){this.created_common(widget,savedAttrs,sourceNode);genro.src.onBuiltCall(dojo.hitch(widget,'render'));dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');widget.updateRowCount('*');},attributes_mixin_get:function(inRowIndex,ignoreFilter){var rowdata;if(!ignoreFilter){rowdata=this.grid.rowCached(inRowIndex);}else{rowdata=this.grid.rowByIndex(inRowIndex,true,true);}
if(!rowdata){console.log('no rowdata:',rowdata);}
var result;if(this._customGetter){try{return this._customGetter.call(this,rowdata,inRowIndex)}catch(e){console.error(e)
return'err';}}else if(this.rowTemplate){var formats={};var c;for(var k in this.grid.cellmap){c=this.grid.cellmap[k];formats[c.field]=c._formats;}
return dataTemplate(this.rowTemplate,new gnr.GnrBag(rowdata),null,null,{formats:formats});}else{return rowdata[this.field_getter];}},mixin_rowCached:function(inRowIndex){if(this.currRenderedRowIndex!==inRowIndex){this.currRenderedRowIndex=inRowIndex;this.currRenderedRow=this.rowByIndex(inRowIndex,true);}
return this.currRenderedRow;},attributes_mixin_canSort:function(colindex){var cellattr=this.getCell(colindex-1)||{};var canSort='canSort'in this.sourceNode.attr?this.sourceNode.attr.canSort:true;if(typeof(canSort)=='string'){canSort=funcCreate(canSort);}
return typeof(canSort)=='function'?funcCreate(canSort.call(this,colindex)):'sortable'in cellattr?cellattr.sortable:canSort;},mixin_filterToRebuild:function(value){if(this._filtered){this._filterToRebuild=value;}},mixin_invalidFilter:function(){return this._filterToRebuild;},mixin_resetFilter:function(){this.setClass('gridFilterActive',false);return this._filtered=null;},mixin_isFiltered:function(){return this._filtered!==null;},mixin_applyFilter:function(filterValue,rendering,filterColumn){if(filterColumn){this.filterColumn=filterColumn;}
this.currentFilterValue=(filterValue===true)?this.currentFilterValue:filterValue;var colType;if(this.filterColumn){var col=this.cellmap[this.filterColumn];var colType='A';if(col){colType=(this.filterColumn.indexOf('+')>0)?'T':(this.cellmap[this.filterColumn]['dtype']||'A');}}
this.createFiltered(this.currentFilterValue,this.filterColumn,colType);if(!rendering){this.updateRowCount('*');}
if(this.changeManager&&objectNotEmpty(this.changeManager.totalizeColumns)){if(isNullOrBlank(this.currentFilterValue)){this.sourceNode.setRelativeData('.filtered_totalize',null);}else{this.changeManager.calculateFilteredTotals();}}
this.setClass('gridFilterActive',this.isFiltered());},mixin_setClass:function(cls,set){genro.dom.setClass((this.sourceNode._wrapperNode||this.sourceNode),cls,set);},mixin_compileFilter:function(value,filterColumn,colType){if(value==null){return null;}
var cb;if(colType in{'A':null,'T':null}){var regexp=new RegExp(value,'i');cb=function(rowdata,index,array){var columns=filterColumn.split('+');var txt='';for(var i=0;i<columns.length;i++){txt=txt+' '+rowdata[columns[i]];}
return regexp.test(txt);};}else{var toSearch=/^(\s*)([\<\>\=\!\#]+)(\s*)(.+)$/.exec(value);if(toSearch){var val;var op=toSearch[2];if(op=='='){op='==';}
if((op=='!')||(op=='#')){op='!=';}
if(isNumericType(colType)){val=dojo.number.parse(toSearch[4]);}else if(colType=='D'){val=dojo.date.locale.parse(toSearch[4],{formatLength:"short",selector:'date'});}else if(colType=='DH'){val=dojo.date.locale.parse(toSearch[4],{formatLength:"short"});}
cb=function(rowdata,index,array){return genro.compare(op,rowdata[filterColumn],val);};}}
return cb;},mixin_createFiltered:function(currentFilterValue,filterColumn,colType){var cb=this.compileFilter(currentFilterValue,filterColumn,colType);if(!cb&&!this.excludeListCb){this._filtered=null;return null;}
var filtered=[];var excludeList=null;if(this.excludeListCb){excludeList=this.excludeListCb.call(this.sourceNode);}
dojo.forEach(this.storebag().getNodes(),function(n,index,array){var rowdata=this.rowFromBagNode(n);var result=cb?cb(rowdata,index,array):true;if(result){if((!excludeList)||(dojo.indexOf(excludeList,rowdata[this.excludeCol])==-1)){filtered.push(index);}}},this);this._filtered=filtered;this._filterToRebuild=false;},mixin_getCellText:function(field,rowIdx,ignoreFilter){var c=this.layout.cells.filter(function(n){return n.field==field});if(c.length){return c[0].get(rowIdx,ignoreFilter);}},mixin_getRowText:function(rowIdx,joiner,fields,ignoreFilter){var result=[];var cb;if(fields){cb=function(c){if(fields.indexOf(c.field_getter||c.field)>=0){result.push(c.get(rowIdx,ignoreFilter));}}}else{cb=function(c){if(!c.classes||c.classes.indexOf('hiddenColumn')<0){result.push(c.get(rowIdx,ignoreFilter));}}}
this.layout.cells.forEach(cb);return result.join(joiner||'');},mixin_getRowTextObj:function(rowIdx,ignoreFilter){var result={};this.layout.cells.forEach(function(c){result[c.field]=c.get(rowIdx,ignoreFilter);});return result;},mixin_sortStore:function(){console.warn('OLD GRID FIX ME')
if(this.sortedBy){var storebag=this.storebag();var sortedBy=this.sortedBy;if(this.datamode!='bag'){sortedBy=sortedBy.split(',');var l=[];dojo.forEach(sortedBy,function(n){l.push('#a.'+n);});sortedBy=l.join(',');}
storebag.sort(sortedBy);}},mixin_fillServerTotalize:function(){},mixin_newDataStore:function(){this.updateRowCount(0);this.resetFilter();if(this.excludeCol){this.filterToRebuild(true);}
this.sortStore();this.sourceNode.publish('onNewDatastore');this.updateRowCount('*');this.restoreSelectedRows();this.fillServerTotalize();},mixin_restoreSelectedRows:function(){this.selection.unselectAll();this.selectionKeeper('load');if(this.autoSelect&&(this.selection.selectedIndex<0)){var sel=this.autoSelect==true?0:this.autoSelect();this.selection.select(sel);}},patch_onCellDblClick:function(e){if(dojo.isIE){this.edit.setEditCell(this._click[1].cell,this._click[1].rowIndex);}else if(this._click[0]&&this._click[0].rowIndex!=this._click[1].rowIndex){this.edit.setEditCell(this._click[0].cell,this._click[0].rowIndex);}else{this.edit.setEditCell(e.cell,e.rowIndex);}
this.onRowDblClick(e);},mixin_setFilterset:function(val,kw){if(kw.reason=='autocreate'){return;}
this.applyFilter();},mixin_setStorepath:function(val,kw){if(kw.reason=='autocreate'){return;}
else if((!this._updatingIncludedView)&&(!this._batchUpdating)){if(kw.evt=='fired'){var storepath=this.absStorepath();var storenode=genro._data.getNode(storepath);if(storenode instanceof dojo.Deferred){console.log('Deferred!!');}else{this.updateRowCount();}}else{this._updatingIncludedView=true;this.currRenderedRowIndex=null;var storebag=this.storebag();var parentNode=this.domNode.parentNode;var storeNode=storebag.getParentNode();var parent_lv=kw.node.parentshipLevel(storeNode);if(kw.evt=='upd'){if(parent_lv>0){var rowIdx=this.sourceNode.updateGridCellAttr(kw,true);if((!(this.gnrediting&&this.gridEditor.editorPars))||(rowIdx!=this.currentEditedRow)){this.updateRow(this.absIndex(rowIdx,true));}}else{this.newDataStore();}}else if(kw.evt=='ins'){if(parent_lv==1||(parent_lv==2&&this.datamode=='bag')){this.updateRowCount();}else{}}else if(kw.evt=='del'){if(parent_lv==1){var currSelectedIdx=this.selection.selectedIndex;this.selection.unselectAll()
var lastSelectable=this.storebag().len()-1;if(currSelectedIdx>lastSelectable){currSelectedIdx=lastSelectable;}
this.filterToRebuild(true);this.updateRowCount();var that=this;if(lastSelectable>=0){setTimeout(function(){that.setSelectedIndex(lastSelectable);},1);}}else{}}
this._updatingIncludedView=false;}}},mixin_setSelectedIndex:function(idx){var nrow=this.rowCount;if(nrow==0){this.selection.unselectAll();}else{if(idx>=nrow){idx=nrow-1;}
this.selection.select(idx);}},patch_onSelectionChanged:function(){this.onSelectionChanged_replaced();var idx=this.selection.getFirstSelected();if(!this._batchUpdating){this._gnrUpdateSelect(idx);}
var selectedMany=this.selection.getSelected().length>1;if(this.changeManager){this.changeManager.calculateFilteredTotals();}
this.setClass('multiSelectionActive',selectedMany);},patch_sort:function(){var sortInfo=this.sortInfo;var order,sortedBy;if(sortInfo<0){order='d';sortInfo=-sortInfo;}else{order='a';}
var cell=this.layout.cells[sortInfo-1];if(this.datamode=='bag'){sortedBy=cell.field+':'+order;}else{sortedBy='#a.'+cell.field+':'+order;}
if((cell.dtype=='A')||(cell.dtype=='T')){sortedBy=sortedBy+'*';}
if(!this.sourceNode.attr.sortedBy){this.setSortedBy(sortedBy);}else{var path=this.sourceNode.attrDatapath('sortedBy');genro._data.setItem(path,sortedBy);}},mixin_absStorepath:function(){return this.sourceNode.absDatapath(this.sourceNode.attr.storepath);},mixin_setRefreshOn:function(){},patch_onStyleRow:function(row){var attr=this.rowCached(row.index);var customClasses=null;if(attr._is_readonly_row){row.customClasses=row.customClasses?row.customClasses+' _gnrReadOnlyRow':'_gnrReadOnlyRow';}else if(attr._is_readonly_row===false){row.customClasses=row.customClasses?row.customClasses+' _gnrProtectionPass':'_gnrProtectionPass';}
if(attr._is_invalid_row){row.customClasses=row.customClasses?row.customClasses+' _gnrInvalidRow':'_gnrInvalidRow';}else if(attr._is_invalid_row===false){row.customClasses=row.customClasses?row.customClasses+' _gnrRegularRow':'_gnrRegularRow';}
if(this.rowCustomClassesCb){row.customClasses=(row.customClasses||'')+' '+(this.rowCustomClassesCb(attr)||'');}
if(attr._customClasses){if(attr._customClasses.slice(0,1)=='!'){customClasses=attr._customClasses.slice(1);}else{customClasses=row.customClasses+' '+attr._customClasses;}
row.customClasses=customClasses;}
if(attr._customStyles){row.customStyles=attr._customStyles;}
row.over=this.enableOver&&row.over;this.onStyleRow_replaced(row);},mixin_canEdit:function(inCell,inRowIndex){return false;},patch_onStartEdit:function(inCell,inRowIndex){},patch_onApplyCellEdit:function(inValue,inRowIndex,inFieldIndex){var dtype=this.cellmap[inFieldIndex].dtype;if((dtype)&&(dtype!='T')&&(typeof(inValue)=='string')){inValue=convertFromText(inValue,this.cellmap[inFieldIndex].dtype,true);}
var editnode=this.dataNodeByIndex(inRowIndex);if(this.datamode=='bag'){editnode.getValue().setItem(inFieldIndex,inValue);}else{editnode.setAttr(inFieldIndex,inValue);}},patch_updateRowCount:function(n){if(this.sourceNode._isBuilding&&this.sourceNode._useStore){return;}
if((n==null)||(n=='*')){if(this.invalidFilter()){this.applyFilter(true,true);}}
if(n=='*'){this.updateRowCount_replaced(0);this.selection.unselectAll();n=null;}
if(n==null){var n=this.hideAllRows?0:this.storeRowCount();}
var view=this.views.views[0];var scrollBox,scrollLeft;if(view){scrollBox=view.scrollboxNode;scrollLeft=scrollBox.scrollLeft;this.currRenderedRowIndex=null;this.currRenderedRow=null;try{this.updateRowCount_replaced(n);}catch(e){console.warn('error in updaterowcount',e);}
this.updateTotalsCount();scrollBox.scrollLeft=scrollLeft;}},mixin_setSortedBy:function(sortedBy){this.sortedBy=sortedBy;var storebag=this.storebag();storebag.sort(this.sortedBy);this.filterToRebuild(true);this.updateRowCount('*');},mixin_rowBagNodeUpdate:function(idx,data,pkey){if(idx==-1){var storebag=this.storebag();var cells=this.layout.cells;var row={};var cell;for(var i=0;i<cells.length;i++){cell=cells[i];row[cell.field]=data.getItem(cell.field);}
var identifier=this.rowIdentifier();data[identifier]=pkey;row[identifier]=pkey;storebag.setItem(pkey,null,row);this.updateRowCount();}
else{var attributes=this.rowByIndex(idx);for(var attr in attributes){var newvalue=data.getItem(attr);if(newvalue!=null){attributes[attr]=newvalue;}}
this.updateRow(idx);}},mixin_rowIdByIndex:function(idx){if(idx!=null){return this.rowIdentity(this.rowByIndex(idx));}},mixin_storebag:function(){var storepath=this.absStorepath();var storebag=genro._data.getItem(storepath);if(storebag instanceof gnr.GnrBag){return storebag;}
else if(storebag instanceof dojo.Deferred){return storebag;}
else if(!storebag){storebag=new gnr.GnrBag();genro.setData(storepath,storebag);return storebag;}
else{storebag=new gnr.GnrBag();genro.setData(storepath,storebag);return storebag;}},mixin_setReloader:function(){var filterNode=genro.nodeById(this.sourceNode.attr.nodeId+'_filterReset');if(filterNode){filterNode.fireNode();}
this.reload(true);},mixin_selectionKeeper:function(flag,loadkw){if(flag=='save'){var prevSelectedIdentifiers=[];var prevSelectedIndexes=this.selection.getSelected();var identifier=this._identifier;var that=this;var k;dojo.forEach(prevSelectedIndexes,function(idx){k=that.rowIdByIndex(idx);if(k){prevSelectedIdentifiers.push(k);}});this.prevSelectedIdentifiers=prevSelectedIdentifiers;this.prevFirstVisibleRow=this.scroller.firstVisibleRow;this.prevSelectedIdx=(prevSelectedIndexes.length==1)?prevSelectedIndexes[0]:-1;return{prevSelectedIdentifiers:this.prevSelectedIdentifiers,prevFirstVisibleRow:this.prevFirstVisibleRow,prevSelectedIdx:this.prevSelectedIdx};}else if(flag=='clear'){this.prevSelectedIdentifiers=null;}else if(flag=='load'){loadkw=loadkw||this._saved_selections;if(loadkw){this.prevSelectedIdentifiers=loadkw.prevSelectedIdentifiers;this.prevFirstVisibleRow=loadkw.prevFirstVisibleRow;this.prevSelectedIdx=loadkw.prevSelectedIdx;this._saved_selections=null;}
if((this.prevSelectedIdentifiers)&&(this.prevSelectedIdentifiers.length>0)){this.selectByRowAttr(this._identifier,this.prevSelectedIdentifiers,null,this.prevFirstVisibleRow,this.prevSelectedIdx);this.prevSelectedIdx=null;this.prevSelectedIdentifiers=null;this.prevFirstVisibleRow=null;}else if(this.prevFirstVisibleRow){this.scrollToRow(this.prevFirstVisibleRow);this.prevFirstVisibleRow=null;}}},mixin_reload:function(keep_selection){this.selectionKeeper(keep_selection?'save':'clear');var nodeId=this.sourceNode.attr.nodeId;var storebag=this.storebag();var storeParent=storebag.getParentNode();if(storeParent.getResolver()){storeParent.refresh(true);}
else{var selectionNode=genro.nodeById(nodeId+'_store')||genro.nodeById(this.sourceNode.attr.store+'_store');this.filterToRebuild(true);if(selectionNode.store){selectionNode.store.loadData();}
else{selectionNode.fireNode();}}
if(nodeId){genro.publish(nodeId+'_data_loaded');}},mixin_setScaleY(v){this._setScale();},mixin_setScaleX(v){this._setScale();},mixin__setScale(v){var scaleX=this.sourceNode.getAttributeFromDatasource('scaleX')||1;var scaleY=this.sourceNode.getAttributeFromDatasource('scaleY')||1;scalecb=function(domNode){domNode.style.transform="scale("+scaleX+","+scaleY+")";domNode.style.transformOrigin='0 0';}
if(this.sourceNode._footersNode||this.sourceNode._columnsetsNode){if(this.sourceNode._columnsetsNode){scalecb(this.sourceNode._columnsetsNode.widget.domNode);}
if(this.sourceNode._footersNode){scalecb(this.sourceNode._footersNode.widget.domNode);}}
scalecb(dojo.query('.dojoxGrid-row-table',this.viewsHeaderNode)[0]);scalecb(dojo.query('.dojoxGrid-content',this.domNode)[0]);},mixin_onSetStructpath:function(structBag,kw){this.query_columns=this.gnr.getQueryColumns(this.sourceNode,structBag);if(this.sourceNode._useStore){this.setEditableColumns();}
this.setChangeManager();kw=kw||{};if(this.sourceNode._useStore){var store=this.collectionStore();if(store){store.onChangedView();}}
this.updateColumnsetsAndFooters();},mixin_updateColumnsetsAndFooters:function(){if(this.sourceNode._footersNode||this.sourceNode._columnsetsNode){if(!genro.dom.isVisible(this.sourceNode._wrapperNode)){return;}
this.columnsetsAndFooters_autodata();this.columnsetsAndFooters_make();this.columnsetsAndFooters_size();this.sourceNode._wrapperNode.widget.resize();this.sourceNode._columnsetAndFootersInitialized=true;}},mixin_absIndex:function(idx,reverse){if(!this._filtered){return idx;}
return reverse?dojo.indexOf(this._filtered,idx):this._filtered[idx];},mixin_storeRowCount:function(all){if(this._filtered&&!all){return this._filtered.length;}else{return this.storebag().len();}},mixin_rowByIndex:function(inRowIndex){if(inRowIndex<0){return{};}
inRowIndex=this.absIndex(inRowIndex);var nodes=this.storebag().getNodes();if(nodes.length>inRowIndex){return this.rowFromBagNode(nodes[inRowIndex]);}else{return{};}},mixin_dataNodeByIndex:function(inRowIndex){inRowIndex=this.absIndex(inRowIndex);var storebag=this.storebag();if(storebag instanceof gnr.GnrBag){var nodes=storebag.getNodes();if(nodes.length>inRowIndex){return nodes[inRowIndex];};}},mixin_getSelectedNodes:function(){var sel=this.selection.getSelected();var result=[];for(var i=0;i<sel.length;i++){var n=this.dataNodeByIndex(sel[i]);if(n){result.push(n);}}
return result;},mixin_getSelectedProtectedPkeys:function(reason){var that=this;var protectPkeys=[];this.getSelectedNodes().forEach(function(n){if(reason=='delete'&&n.attr._protect_delete===false){protectPkeys.push(that.rowIdentity(n.attr));return;};if(n.attr._protect_delete||n.attr._is_readonly_row){protectPkeys.push(that.rowIdentity(n.attr));}});return protectPkeys.length?protectPkeys:null;},mixin_rowIdentity:function(row){if(row){return row[this.rowIdentifier()];}else{return null;}},mixin_rowIdentifier:function(row){return this._identifier;},mixin_getRowIdxFromNode:function(node){var storebag=this.storebag();var subPath=node.getFullpath(null,storebag).split('.');return storebag.index(subPath[0]);},mixin_getColumnValues:function(col){var storebag=this.storebag();if(col.slice(0,2)=='^.'){col=col.slice(2);}
if(this.datamode!='bag'){col='#a.'+col;}
return storebag.columns(col)[0];},mixin_rowFromBagNode:function(node){var result=objectUpdate({},node.attr);if(this.datamode=='bag'){var value=node.getValue();if(value){for(var cellname in this.cellmap){var cell=this.cellmap[cellname];result[cell.field]=value.getItem(cell.original_field);}};}
return result;},nodemixin_updateGridCellAttr:function(kw){var grid=this.widget;var storebag=grid.storebag();var subPath=kw.node.getFullpath(null,storebag).split('.');var rowLabel=subPath[0];var fldName=subPath[1];if(fldName&&grid.datamode!='bag'){var chNode=storebag.getNode(rowLabel);var cellAttr,value,gridfield;var currAttr=objectUpdate({},chNode.attr);var fld;var cells=grid.cellmap;for(fld in cells){cellAttr=grid.cellmap[fld];if(cellAttr.original_field.indexOf(fldName)==0){value=chNode.getValue().getItem(cellAttr.original_field);gridfield=cellAttr.field;currAttr[gridfield]=value;}};chNode.updAttributes(currAttr);}
var idx=storebag.index(rowLabel);if(grid._filtered){idx=dojo.indexOf(grid._filtered,idx);}
return idx;},mixin_editBagRow:function(r,delay){if(r==-1){r=this.storeRowCount()-1;}
if(r==null){var r=this.selection.selectedIndex;}
var rc=this.gridEditor.findNextEditableCell({row:r,col:-1},{r:0,c:1});var grid=this;var ge=this.gridEditor;if(rc){if(ge.remoteRowController){var d=new Date();this.sourceNode.watch('pendingRemoteController',function(){return!ge._pendingRemoteController},function(){ge.startEdit(rc.row,rc.col);},10);}
else if(delay){if(this._delayedEditing){clearTimeout(this._delayedEditing);}
this._delayedEditing=setTimeout(function(){ge.startEdit(rc.row,rc.col);},delay);}else{ge.startEdit(rc.row,rc.col);}}},mixin_newBagRow:function(defaultArgs){var defaultArgs=(this.gridEditor?this.gridEditor.getNewRowDefaults(defaultArgs):defaultArgs)||{};var newRowDefaults=this.sourceNode.attr.newRowDefaults;var newrow;if(newRowDefaults){if(typeof(newRowDefaults)=='string'){newRowDefaults=funcCreate(newRowDefaults)();}
newRowDefaults=genro.src.dynamicParameters(newRowDefaults);objectUpdate(defaultArgs,newRowDefaults);}
var dataproviderNode=this.storebag().getParentNode();if('newBagRow'in dataproviderNode){if(defaultArgs instanceof Array){result=[];for(var i=0;i<defaultArgs.length;i++){result.push(this.newBagRow(defaultArgs[i]));};return result;}
else{newrow=dataproviderNode.newBagRow(defaultArgs);}}else{if(defaultArgs instanceof Array){result=[];for(var i=0;i<defaultArgs.length;i++){result.push(this.newBagRow(defaultArgs[i]));};return result;}
if(this.datamode=='bag'){newrow=new gnr.GnrBagNode(null,'label',new gnr.GnrBag(defaultArgs));}else{newrow=new gnr.GnrBagNode(null,'label',null,defaultArgs);}}
newrow.attr._newrecord=true;return newrow;},mixin_updateCounterColumn:function(){var storebag=this.storebag();var cb;var k=1;var changes=[];var serializableChanges=[];var that=this;var counterField=this.sourceNode.attr.counterField;if(!counterField){return;}
if(this.datamode=='bag'||this.gridEditor){var ge=this.gridEditor;if(this.collectionStore&&ge){var cb=function(n){ge.updateCounterColumn(n,k,counterField);k++;}}
else{cb=function(n){var row=n.getValue();var oldk=row.getItem(counterField);if(k!=oldk){row.setItem(counterField,k);}
k++;};}}else{cb=function(n){var row=n.attr;var oldk=row[counterField];if(k!=oldk){n.setAttribute(counterField,k);changes.push({'node':n,'old':oldk,'new':k});oldk=oldk||-1;serializableChanges.push({'_pkey':that.rowIdentity(n.attr),'old':oldk,'new':k});}
k++;};}
storebag.forEach(cb,'static');if(changes.length>0){var collectionStore=this.collectionStore;if(collectionStore){this.collectionStore().onCounterChanges(counterField,serializableChanges);}else{this.sourceNode.publish('counterChanges',{'changes':serializableChanges,'table':this.sourceNode.attr.table});}}
return changes;},mixin_addBagRow:function(label,pos,newnode,event,nodupField){var label=label||'r_'+newnode._id;this.resetFilter();var storebag=this.storebag();if(nodupField){var nodupValue;var colvalues=this.getColumnValues(nodupField);if(this.datamode=='bag'){nodupValue=newnode.getValue().getItem(nodupField);}else{nodupValue=newnode.attr[nodupField];}
if(dojo.indexOf(colvalues,nodupValue)!=-1){return;}}
event=event||{};var addRowMode=this.sourceNode.attr.addRowMode;if(addRowMode){pos=addRowMode;}
if(pos=='*'){var curSelRow=this.absIndex(this.selection.selectedIndex);if(curSelRow<0){pos=event.shiftKey?0:'>';}else{pos=event.shiftKey?curSelRow:curSelRow+1;}}
var kw={'_position':pos};newnode=storebag.setItem(label,newnode,null,kw);this.updateCounterColumn();return newnode;},mixin_delBagRow:function(pos,many,params){var pos=(pos=='*')?this.absIndex(this.selection.selectedIndex):pos;var storebag=this.storebag();var removed=[];if(many){var selected=this.selection.getSelected();this.batchUpdating(true);this.loadingContent(true);var pos;for(var i=selected.length-1;i>=0;i--){pos=this.absIndex(selected[i]);removed.push(storebag.popNode('#'+pos));}
this.batchUpdating(false);this.loadingContent(false);}else{removed.push(storebag.popNode('#'+pos));}
removed.reverse();this.filterToRebuild(true);this.updateCounterColumn();this.updateRowCount('*');var newpos=pos>0?pos-1:0;this.selection.select(newpos);var delpath;if(this.sourceNode.attr.delstorepath){delpath=this.sourceNode.attr.delstorepath;}else{var storenode=storebag.getParentNode();if(storenode.label.indexOf('@')==0){delpath=storenode.getFullpath(null,true)+'_removed';}}
if(delpath){for(var i=0;i<removed.length;i++){if(!removed[i].attr._newrecord){genro._data.setItem(delpath+'.'+removed[i].label,removed[i].value,removed[i].attr,{'doTrigger':'_removedRow'});}}}
return removed;},mixin_exportData:function(mode){var mode=mode||'csv';var meta=objectExtract(this.sourceNode.attr,'meta_*',true);var pars=objectUpdate({'structbag':this.structbag(),'storebag':this.storebag()},meta);var curgrid=this;curgrid.loadingContent(true);genro.rpc.remoteCall(mode,pars,'bag','POST',null,function(url){genro.download(url);curgrid.loadingContent(false);});},mixin_printData:function(){var meta=objectExtract(this.sourceNode.attr,'meta_*',true);var pars=objectUpdate({'structbag':this.structbag(),'storebag':this.storebag()},meta);var curgrid=this;curgrid.loadingContent(true);genro.rpc.remoteCall('app.printStaticGrid',pars,'bag','POST',null,function(url){genro.download(url,null,'print');curgrid.loadingContent(false);});},mixin_structbag:function(){return genro.getData(this.sourceNode.absDatapath(structpath));},patch_dokeydown:function(e){},patch_doclick:function(e){if(this.gnrediting){dojo.stopEvent(e);}else{if(e.cellNode){this.onCellClick(e);}else{this.onRowClick(e);}}}});dojo.declare("gnr.widgets.IncludedView",gnr.widgets.VirtualStaticGrid,{constructor:function(application){this._domtag='div';this._dojotag='VirtualGrid';},creating:function(attributes,sourceNode){var savedAttrs=this.creating_common(attributes,sourceNode);this.creating_structure(attributes,sourceNode);sourceNode.registerDynAttr('storepath');attributes.query_columns=this.getQueryColumns(sourceNode,attributes.structBag);if(attributes.excludeListCb){attributes.excludeListCb=funcCreate(attributes.excludeListCb);}
return savedAttrs;},mixin_setEditableColumns:function(){var cellmap=this.cellmap;var batch_assign=false;for(var k in cellmap){if(cellmap[k].edit){if(cellmap[k].edit!==true&&cellmap[k].edit.batch_assign){batch_assign=true;}
if(!this.gridEditor){this.gridEditor=new gnr.GridEditor(this);}
this.gridEditor.addEditColumn(cellmap[k].field,objectUpdate({},cellmap[k]));}else if(this.gridEditor){this.gridEditor.delEditColumn(cellmap[k].field);}}
this.sourceNode.setRelativeData('.batchAssignEnabled',batch_assign);},mixin_setChangeManager:function(){var that=this;if(!this.structBag){return;}
var getChangeManager=function(){if(!that.changeManager){that.changeManager=new gnr.GridChangeManager(that);}
return that.changeManager;};var struct=this.structBag.getItem('#0.#0');var cellmap=this.cellmap;var cm=this.changeManager;if(cm){cm.initialize();}
for(var k in cellmap){var cell=cellmap[k];var structNode=struct.getNode(cell._nodelabel);if(!structNode){continue;}
var bagcellattr=structNode.attr;for(var p in bagcellattr){if(typeof(bagcellattr[p])=='string'&&bagcellattr[p].indexOf('^')==0){getChangeManager().addDynamicCellPar(cell,p,bagcellattr[p].slice(1));}}
if(cell.edit){var cm=getChangeManager()
if(cell.edit.remoteRowController){cm.addRemoteControllerColumn(cellmap[k].field,objectUpdate({},cellmap[k]));}}
if(cell.formula){getChangeManager().addFormulaColumn(cellmap[k].field,objectUpdate({},cellmap[k]));}else if(this.changeManager){this.changeManager.delFormulaColumn(cellmap[k].field);}
if(cell.totalize&&isNumericType(cell.dtype)){var snode=genro.nodeById(this.sourceNode.attr.store+'_store');var virtualStore=snode.attr.selectionName&&snode.attr.row_count;var selectionStore=snode.attr.method=='app.getSelection';if(selectionStore&&!cell.formula&&!this.gridEditor){this.sourceNode._serverTotalizeColumns[cell.field]=cell.totalize;}
if(!virtualStore){getChangeManager().addTotalizer(cellmap[k].field,objectUpdate({},cellmap[k]));}}else if(this.changeManager){this.changeManager.delTotalizer(cellmap[k].field);}}
if(this.changeManager){this.changeManager.registerParameters();}},getQueryColumns:function(sourceNode,structure){var columns=gnr.columnsFromStruct(structure);if(sourceNode.attr.hiddencolumns){columns=columns+','+sourceNode.attr.hiddencolumns;}
if(columns){sourceNode.setRelativeData(sourceNode.gridControllerPath+'.columns',columns);}
return columns;},mixin_onCheckedColumn:function(idx,fieldname,evt){if(this.sourceNode.attr.parentForm!==false&&this.sourceNode.form&&this.sourceNode.form.isDisabled()){return;}
var kw=this.cellmap[fieldname];if(kw===true){kw={};}
var rowIndex=this.absIndex(idx);var rowpath='#'+rowIndex;var sep=this.datamode=='bag'?'.':'?';var storebag=this.storebag();var valuepath=rowpath+sep+kw.original_field;var checked=storebag.getItem(valuepath);var selectedIdx;if(kw.radioButton===true){selectedIdx=[idx];}else{selectedIdx=this.getSelectedRowidx();if(selectedIdx.indexOf(idx)<0){selectedIdx=[idx];}}
var that=this;selectedIdx.forEach(function(idx){that.onCheckedColumn_one(idx,fieldname,checked,kw,evt);});},mixin_onCheckedColumn_one:function(idx,fieldname,checked,cellkw,evt){var rowIndex=this.absIndex(idx);var grid=this;var rowpath='#'+rowIndex;var sep=this.datamode=='bag'?'.':'?';var valuepath=rowpath+sep+cellkw.original_field;var storebag=this.storebag();var currNode=storebag.getNode(rowpath);var checked=storebag.getItem(valuepath);var checkedField=cellkw.checkedField||this.rowIdentifier();var checkedRowClass=cellkw.checkedRowClass;var action=cellkw.action;var action_delay=cellkw.action_delay;var sourceNode=this.sourceNode;var gridEditor=this.gridEditor;var cellsetter;var currpath;var changedFields=[];if(gridEditor){cellsetter=function(idx,cellname,value){gridEditor.setCellValue(idx,cellname,value);}}else{cellsetter=function(idx,cellname,value){currpath='#'+grid.absIndex(idx)+sep+cellname;storebag.setItem(currpath,value,null,{lazySet:true});}}
if(currNode.attr.disabled){return;}
var newval=!checked;if(cellkw.radioButton){if(checked&&!evt.shiftKey){return;}
if(cellkw.radioButton===true){var oldcheckedpath;for(var i=0;i<storebag.len();i++){oldcheckedpath='#'+i+sep+fieldname;if(storebag.getItem(oldcheckedpath)){if(gridEditor){gridEditor.setCellValue(i,fieldname,false);}else{storebag.setItem(oldcheckedpath,false,null,{lazySet:true});}
break;}}
cellsetter(idx,fieldname,true);}else{for(var c in this.cellmap){var s_cell=this.cellmap[c];if(s_cell.radioButton==cellkw.radioButton){changedFields.push(s_cell.original_field);cellsetter(idx,s_cell.original_field,(fieldname==s_cell.original_field)&&!evt.shiftKey);}}}}else{cellsetter(idx,cellkw.original_field,!checked);}
if(cellkw.checkedId){var checkedKeys=this.getCheckedId(fieldname,checkedField)||'';setTimeout(function(){sourceNode.setRelativeData(cellkw.checkedId,checkedKeys,null,null,sourceNode);},1);}
var gridId=this.sourceNode.attr.nodeId;if(gridId){genro.publish(gridId+'_row_checked',currNode.label,newval,currNode.attr);}
if(action){var changedRow=this.rowByIndex(rowIndex);var changedKey=changedRow[checkedField];var changedValue=changedRow[fieldname];var actionKw={_idx:rowIndex,_row:changedRow,_fields:changedFields};actionKw[changedKey]=changedValue;if(!action_delay){action.call(this.sourceNode,actionKw);}else{if(sourceNode._pendingCheck){clearTimeout(sourceNode._pendingCheck);var changes=sourceNode._pendingChanges;if(changedKey in changes){objectPop(changes,changedKey);}else{changes[changedKey]=changedValue;}}else{sourceNode._pendingChanges=actionKw;}
sourceNode._pendingCheck=setTimeout(function(){sourceNode._pendingCheck=null;if(objectNotEmpty(sourceNode._pendingChanges)){action.call(sourceNode,sourceNode._pendingChanges);}},action_delay);}}},mixin_addCheckBoxColumn:function(kw){this.gnr.addCheckBoxColumn(kw,this.sourceNode);this.gnr.setCheckedIdSubscription(this.sourceNode,kw);},addCheckBoxColumn:function(kw,sourceNode){var celldata=this.getCheckBoxKw(kw,sourceNode);var structbag=sourceNode.getRelativeData(sourceNode.attr.structpath);var position=objectPop(kw,'position')||0;genro.callAfter(function(){structbag.setItem('view_0.rows_0.cell_'+celldata.field,null,celldata,{_position:position});},1);},setCheckedIdSubscription:function(sourceNode,kw){if(kw.checkedId&&!sourceNode.attr.checkedId){sourceNode.attr.checkedId=kw.checkedId;sourceNode.registerDynAttr('checkedId');var checkedIdPath=kw.checkedId;var fieldname=kw.field;var checkedField=kw.checkedField;sourceNode.subscribe('onNewDatastore',function(){var checkedInStore=sourceNode.widget.getCheckedId(fieldname,checkedField);if(typeof(getCheckedId)=='string'){sourceNode.setRelativeData(checkedIdPath,checkedInStore,null,null,sourceNode);}else{genro.callAfter(function(){sourceNode.widget.setCheckedId(checkedIdPath,kw);},1);}});if(kw.checkedOnRowClick){dojo.connect(sourceNode.widget,'onRowClick',function(e){sourceNode.widget.onCheckedColumn(e.rowIndex,fieldname,e);});}}},getCheckBoxKw:function(kw,sourceNode,celldata){var kw=kw||{};var celldata=celldata||{};var fieldname=kw.field||celldata['field']||'_checked';var radioButton=kw.radioButton||false;celldata['field']=fieldname;celldata['name']=kw.name||celldata.name||' ';celldata['dtype']='B';celldata['width']=celldata.width||'20px';celldata['radioButton']=radioButton;celldata['format_trueclass']=kw.trueclass||(radioButton?'radioOn':'checkboxOn');celldata['classes']=kw.classes||'row_checker';celldata['format_falseclass']=kw.falseclass||(radioButton?'radioOff':'checkboxOff');celldata['calculated']=kw.calculated;celldata['checkedId']=kw.checkedId;celldata['checkedField']=kw.checkedField;celldata['action']=kw.action?funcCreate(kw.action,'changes',sourceNode):null;celldata['action_delay']=kw.action_delay;if(kw.remoteUpdate&&sourceNode.attr.table){celldata.action=function(changes){genro.serverCall("app.updateCheckboxPkeys",{table:sourceNode.attr.table,field:fieldname,changesDict:changes});};celldata['action_delay']=typeof(kw.remoteUpdate)=='number'?kw.remoteUpdate:1000;}
celldata['format_onclick']="this.widget.onCheckedColumn(kw.rowIndex,'"+fieldname+"',e)";return celldata;},mixin_getCheckedId:function(fieldname,checkedField){checkedField=checkedField||this.rowIdentifier();var checkedIdList=[];var that=this;var row;var instore=false;this.storebag().forEach(function(n){row=that.rowFromBagNode(n);if(fieldname in row){instore=true;}
if(row[fieldname]){checkedIdList.push(row[checkedField]);}},'static');return instore?checkedIdList.join(','):false;},mixin_setCheckedId:function(path,kw,trigger_reason){var value=this.sourceNode.getRelativeData(path);if(typeof(value)!='string'){return;}
var pkeys=value?value.split(','):[];var datamodeBag=this.datamode=='bag';var checkedField=kw.checkedField||this.rowIdentifier();var fieldname=kw.field||'_checked';var grid=this;var v;this.storebag().forEach(function(n){var row=grid.rowFromBagNode(n);var pkey=row[checkedField];v=dojo.indexOf(pkeys,pkey)>=0?true:false;if(datamodeBag){n.getValue('static').setItem(fieldname,v);}else{var newattr={};newattr[fieldname]=v;n.updAttributes(newattr);}},'static');},mixin_serverAction:function(kw){var options=objectPop(kw,'opt');var method=objectPop(options,"method")||"app.includedViewAction";var kwargs=objectUpdate({},options);kwargs['action']=objectPop(kw,'command');kwargs['data']=this.storebag();kwargs['datamode']=this.datamode;kwargs['struct']=this.structbag();var cb=function(result){genro.download(result);};kwargs['meta']=objectExtract(this.sourceNode.attr,'meta_*',true);genro.rpc.remoteCall(method,kwargs,null,'POST',null,cb);},created:function(widget,savedAttrs,sourceNode){this.created_common(widget,savedAttrs,sourceNode);var selectionId=sourceNode.attr['selectionId']||sourceNode.attr.nodeId+'_store';widget.autoSelect=sourceNode.attr['autoSelect'];if(typeof(widget.autoSelect)=='string'){widget.autoSelect=funcCreate(widget.autoSelect,null,widget);}
widget.linkedSelection=genro.nodeById(selectionId);genro.src.onBuiltCall(dojo.hitch(widget,'render'));dojo.connect(widget,'modelAllChange',dojo.hitch(sourceNode,this.modelAllChange));if(sourceNode.attr.editbuffer){sourceNode.registerDynAttr('editbuffer');}
if(sourceNode.attr.multiSelect==false){widget.selection.multiSelect=false;}
var addCheckBoxColumn=sourceNode.attr.addCheckBoxColumn;if(addCheckBoxColumn){var kw=addCheckBoxColumn==true?null:addCheckBoxColumn;widget.addCheckBoxColumn(kw);}
widget.updateRowCount('*');},mixin_structbag:function(){return genro.getData(this.sourceNode.absDatapath(this.sourceNode.attr.structpath));},mixinex_structbag:function(){var structure=this.sourceNode.getValue();if(structure){structure=structure.getItem('struct');}else{structure=genro.getData(this.sourceNode.absDatapath(this.sourceNode.attr.structpath));}
return structure;},mixin_loadingContent:function(flag){var scrollnode=dojo.query('.dojoxGrid-scrollbox',this.domNode)[0];var contentnode=dojo.query('.dojoxGrid-content',this.domNode)[0];if(flag){if(scrollnode){genro.dom.addClass(scrollnode,'waiting');};if(contentnode){genro.dom.addClass(contentnode,'dimmed');};}else{if(scrollnode){genro.dom.removeClass(scrollnode,'waiting');};if(contentnode){genro.dom.removeClass(contentnode,'dimmed');};}},mixin_deleteSelectedRows:function(){this.delBagRow('*',true);this.sourceNode.publish('onDeletedRows');},mixin_addRows:function(counterOrSource,evt,duplicate,onEditNode){if(duplicate&&!this.gridEditor){var pkeys=this.getSelectedPkeys();this.collectionStore().duplicateRows(pkeys);return;}
if(this.sourceNode.attr.defaultPrompt){var defaultPrompt=this.sourceNode.attr.defaultPrompt;if(typeof(counterOrSource)=='number'){counterOrSource={};}
var that=this;genro.dlg.prompt(defaultPrompt.title||_T('Fill parameters'),{widget:defaultPrompt.fields,action:function(result){objectUpdate(counterOrSource,result.asDict());that.addRowsDo([counterOrSource],evt,duplicate,onEditNode);}});return;}
this.addRowsDo(counterOrSource,evt,duplicate,onEditNode);},mixin_addRowsDo(counterOrSource,evt,duplicate,onEditNode){var addrow_kwargs=this.sourceNode.evaluateOnNode(objectExtract(this.sourceNode.attr,'addrow_*',true));var source=[];counterOrSource=counterOrSource||1;if(!(counterOrSource instanceof Array)){for(var i=0;i<counterOrSource;i++){source.push(null);}}else{source=counterOrSource;}
var firstRow;var that=this;if(duplicate){var sel=this.selection.getSelected();var row;var identifier=this.rowIdentifier();sel.forEach(function(n){row=that.rowByIndex(n);objectPop(row,identifier);that.addBagRow('#id',null,that.newBagRow(row),evt)});}else{var that=this;source.forEach(function(dflt){firstRow=firstRow||that.addBagRow('#id',addrow_kwargs.position||'*',that.newBagRow(dflt),evt);});}
this.sourceNode.publish('onAddedRows');if(!duplicate){var doEdit=true;if(onEditNode){doEdit=onEditNode(firstRow);}
if(this.gridEditor&&doEdit!==false){this.editBagRow(this.storebag().index(firstRow.label));}}
return firstRow;},mixin_batchUpdating:function(state){this._batchUpdating=state;},mixin_setEditorEnabled:function(enabled){this.editorEnabled=enabled;}});dojo.declare("gnr.widgets.NewIncludedView",gnr.widgets.IncludedView,{mixin_rowByIndex:function(inRowIndex,bagFields,ignoreFilter){var store=this.collectionStore();if(ignoreFilter){return this.rowFromBagNode(store.getItems()[inRowIndex],bagFields);}
return store.rowByIndex(inRowIndex,bagFields);},mixin_absIndex:function(idx,reverse){return this.collectionStore().absIndex(idx,reverse);},mixin_rowFromBagNode:function(node,bagFields){return this.collectionStore().rowFromItem(node,bagFields);},mixin_rowBagNodeByIdentifier:function(identifier){return this.collectionStore().rowBagNodeByIdentifier(identifier);},mixin_setStoreBlocked:function(reason,doset){this.collectionStore().setBlockingReason(reason,doset);},mixin_setSelectedId:function(pkey){var nrow=this.rowCount;if(nrow==0||isNullOrBlank(pkey)){this.selection.unselectAll();}else{var idx=this.collectionStore().getIdxFromPkey(pkey);if(idx>=nrow){idx=nrow-1;}
this.selection.select(idx);}},mixin_configuratorPalette:function(){if(this.sourceNode.attr.configurable&&genro.grid_configurator){genro.grid_configurator.configuratorPalette(this.sourceNode.attr.nodeId||this.sourceNode._id);}},mixin_configuratorColsetTooltip:function(colset,event){if(this.sourceNode.attr.configurable&&genro.grid_configurator){genro.grid_configurator.configuratorColsetTooltip(this.sourceNode.attr.nodeId||this.sourceNode._id,colset,event);}},mixin_configuratorCellTooltip:function(event){if(this.sourceNode.attr.configurable&&genro.grid_configurator){genro.grid_configurator.configuratorCellTooltip(this.sourceNode.attr.nodeId||this.sourceNode._id,event.cell,event.target);}},mixin_setDynamicStorepath:function(newstorepath){newstorepath=newstorepath||'.store';var store=this.collectionStore();store.setNewStorepath(newstorepath);},mixin_absStorepath:function(){return this.collectionStore().storepath;},mixin_getSelectedRowidx:function(){var sel=this.selection.getSelected();if(!this._virtual){return sel.sort();}
var result=[];for(var i=0;i<sel.length;i++){var row=this.rowByIndex(sel[i]);result.push(row.rowidx);}
return result.sort();},mixin_cellCurrentDatapath:function(path,inRowIndex){inRowIndex=inRowIndex==null?this.currRenderedRowIndex:inRowIndex;var node=this.collectionStore().itemByIdx(inRowIndex);genro.assert(node,'missing storenode');return path.replace('#ROW.',node.getFullpath(null,genro._data)+'~')},mixin_rowIdByIndex:function(inRowIndex){if(inRowIndex!==null){return this.rowIdentity(this.rowByIndex(inRowIndex));}},mixin_getRowEditor:function(kw){var rowId=kw.rowId;if(!rowId){if(kw.rowIndex){rowId=this.rowIdByIndex(kw.rowIndex);}else{rowId=this.rowIdentity(kw.row);}}
var rowNode=this.rowBagNodeByIdentifier(rowId);if(rowNode){return rowNode._rowEditor;}},mixin_filteredRowsIndex:function(filteringObject){return this.collectionStore().filteredRowsIndex(filteringObject);},mixin_groupColumnsSelect:function(inIndex,columns){var selection=this.selection;selection.unselectAll(inIndex);var baserow=this.rowByIndex(inIndex);var groupRows=this.filteredRowsIndex(objectExtract(baserow,columns));selection.beginUpdate();dojo.forEach(groupRows,function(idx){selection.addToSelection(idx);})
selection.endUpdate();},mixin_fillServerTotalize:function(){var totalizeColumns=this.sourceNode._serverTotalizeColumns;if(!objectNotEmpty(totalizeColumns)){return;}
var data=this.storebag();var result_attr=data.getParentNode().attr;for(var field in totalizeColumns){var sfield='sum_'+field;if(sfield in result_attr){this.sourceNode.setRelativeData(totalizeColumns[field],result_attr[sfield]);}}},mixin_indexByCb:function(cb,backward){return this.collectionStore().indexByCb(cb,backward);},mixin_storeRowCount:function(all){return this.collectionStore().len(!all);},mixin_storebag:function(filtered){return this.collectionStore().getData(filtered);},mixin_masterEditColumn:function(){if(this.sourceNode.attr.masterColumn){return this.sourceNode.attr.masterColumn;}
var colinfo=this.getColumnInfo();var colnodes=colinfo.getNodes()
var item,n;for(var i=0;i<colnodes.length;i++){item=colnodes[i].attr;if(!item.isHidden&&item.cell.edit){return item.cell.field;}}},mixin_autoInsertHandler:function(){var data=this.storebag();var lastidx=data.len()-1;var masterEditColumn=this.masterEditColumn();var emptyRowCb=function(n){var result=isNullOrBlank(n.getValue().getItem(masterEditColumn));return result;};if(this.isFocused&&!(lastidx>=0&&emptyRowCb(data.getNode('#'+lastidx)))){return data.setItem('#id',this.newBagRow(),null,{doTrigger:'autoRow'});}
else if(!this.isFocused&&!this.gnrediting){var idxToDel=[lastidx];if(this.autoDelete){idxToDel=data.getNodes().map(function(n,idx){return emptyRowCb(n)?idx:-1});}
idxToDel.filter(function(idx){return idx>=0}).sort(function(a,b){return b>a?1:-1}).forEach(function(idx){data.popNode('#'+idx,'autoRow');});}},mixin_toggleLineNumberColumn:function(kw){let currShow=this.sourceNode.getRelativeData(this.sourceNode.attr.structpath+'.info.showLineNumber');this.sourceNode.setRelativeData(this.sourceNode.attr.structpath+'.info.showLineNumber',!currShow);},mixin_addNewSetColumn:function(kw){this.gnr.addNewSetColumn(this.sourceNode,kw);;},addNewSetColumn:function(sourceNode,kw){var position=objectPop(kw,'position')||0;var celldata=this.getNewSetKw(sourceNode,kw);genro.callAfter(function(){var structbag=sourceNode.getRelativeData(sourceNode.attr.structpath);structbag.setItem('view_0.rows_0.cell_'+celldata.field,null,celldata,{_position:position});},1);},mixin_setUserSets:function(v,kw){this.updateRowCount();},getNewSetKw:function(sourceNode,celldata){var celldata=celldata||{};var fieldname=celldata['field']||'_set_'+genro.getCounter();var radioButton=objectPop(celldata,'radioButton')||false;celldata['field']=fieldname;celldata['name']=celldata.name||' ';celldata['dtype']='B';celldata['width']=celldata.width||'20px';celldata['radioButton']=radioButton;celldata['format_trueclass']=objectPop(celldata,'trueclass')||(radioButton?'radioOn':'checkboxOn');celldata['classes']=celldata.classes||'row_checker';celldata['format_falseclass']=objectPop(celldata,'falseclass')||(radioButton?'radioOff':'checkboxOff');celldata['calculated']=true;celldata['checkedId']=sourceNode.attr.userSets+'.'+fieldname;if(celldata['userSets_caption']){celldata['checkedCaption']=sourceNode.attr.userSets+'_caption.'+fieldname;}
var identifier=sourceNode.widget?sourceNode.widget.rowIdentifier():sourceNode.attr.identifier;celldata['checkedField']=celldata['checkedField']||identifier||'_pkey';celldata['userSets']=true;celldata['format_onclick']="this.widget.onChangeSetCol(kw.rowIndex,'"+fieldname+"',e)";celldata['_customGetter']=celldata['_customGetter']||function(rowdata,rowIdx){return sourceNode._usersetgetter(this.field,rowdata,rowIdx)};return celldata;},mixin_onChangeSetCol:function(rowIndex,fieldname,e){dojo.stopEvent(e);var changeset=function(currSet,elements,ischecked){dojo.forEach(elements,function(element){var m=currSet.match(new RegExp('(^|,)'+element+'($|,)'));if(ischecked){if(m){currSet=currSet.replace(m[0],(m[1]+m[2])==',,'?',':'');}}else if(!m){currSet=currSet?currSet+','+element:element;}});return currSet;}
var modifiers=genro.dom.getEventModifiers(e);var structbag=this.sourceNode.getRelativeData(this.sourceNode.attr.structpath);var kw=this.cellmap[fieldname];var store=this.collectionStore();var node=store.itemByIdx(rowIndex);var currSet=this.sourceNode.getRelativeData(kw['checkedId'])||'';var currSetCaption=this.sourceNode.getRelativeData(kw['checkedCaption'])||'';var checkedElement=node.attr[kw['checkedField']];var ischecked=currSet.match(new RegExp('(^|,)'+checkedElement+'($|,)'))!=null;var pkeys;var caption_field=kw['userSets_caption'];var pl=[];var cl=[];if(modifiers=='Shift'){pkeys=this.getAllPkeys(caption_field);}else{pkeys=this.getSelectedPkeys(caption_field);}
if(caption_field){pkeys.forEach(function(n){pl.push(n.pkey);cl.push(n.caption)});pkeys=pl;}
if(modifiers!='Shift'&&(dojo.indexOf(pkeys,checkedElement)<0)){pkeys=[checkedElement];if(caption_field){cl=[node.attr[caption_field]]}}
if(!ischecked){var group=kw['userSets_group'];if(group){var relatedcell;var pset;var cset;for(var c in this.cellmap){relatedcell=this.cellmap[c];if(relatedcell.userSets_group==group&&c!=fieldname){pset=this.sourceNode.getRelativeData(relatedcell['checkedId']);if(pset){this.sourceNode.setRelativeData(relatedcell['checkedId'],changeset(pset,pkeys,true));}
if(relatedcell.userSets_caption){cset=this.sourceNode.getRelativeData(relatedcell['checkedCaption']);if(cset){this.sourceNode.setRelativeData(relatedcell['checkedCaption'],changeset(cset,cl,true));}}}}}}
this.sourceNode.setRelativeData(kw['checkedId'],changeset(currSet,pkeys,ischecked));if(caption_field){this.sourceNode.setRelativeData(kw['checkedCaption'],changeset(currSetCaption,cl,ischecked));}},patch_sort:function(){var sortInfo=this.sortInfo;var order;if(sortInfo<0){order='d';sortInfo=-sortInfo;}else{order='a';}
var cell=this.layout.cells[sortInfo-1];var sortedBy=cell.field_getter+':'+order;this.sourceNode.publish('setSortedBy',sortedBy);if('sortedBy'in this.sourceNode.attr){var sortpath=this.sourceNode.attr['sortedBy'];if(this.sourceNode.isPointerPath(sortpath)){this.sourceNode.setAttributeInDatasource('sortedBy',sortedBy)}}
this.sortStore(sortedBy);},mixin_setSortedBy:function(sortedBy){if(sortedBy.indexOf(':')<0){sortedBy+=':a';}
var s=sortedBy.split(':');var sortIndex=this.layout.cells.map(function(c){return c.field}).indexOf(s[0]);if(sortIndex>=0){this.setSortIndex(sortIndex,s[1][0]=='a');}},mixin_sortStore:function(sortedBy){var store=this.collectionStore();if(!sortedBy){var storeSortedBy=store.storeNode.getAttributeFromDatasource('sortedBy');if(store.storeNode&&storeSortedBy==this.sortedBy){return;}
sortedBy=this.sortedBy||storeSortedBy;}
this.sortedBy=sortedBy;store.sortedBy=sortedBy;if(this._virtual){var rowcount=this.rowCount;this.updateRowCount(0);store.clearBagCache();this.updateRowCount(rowcount);}
else{store.sort();store.filterToRebuild(true);this.updateRowCount('*');}
this.pendingSort=false;},mixin_refreshSort:function(){this.setSortedBy(this.sortedBy);},mixin_collectionStore:function(){if(!this._collectionStore){var storeNode=genro.nodeById(this.sourceNode.attr.store+'_store');this._collectionStore=storeNode.store;var that=this;storeNode.subscribe('updateRows',function(){var wasfocused=that._focused;that.updateRowCount();});var store=this._collectionStore;this._virtual=store.storeType=='VirtualSelection';if(this._virtual){this.domNode.addEventListener("scroll",function(e){var lastRow=that.scroller.lastVisibleRow;if(store._scroll_timeout){clearTimeout(store._scroll_timeout);}else{store.isScrolling=true;}
store._scroll_timeout=setTimeout(function(){store.isScrolling=false;store._scroll_timeout=null;if(lastRow!=that.scroller.lastVisibleRow){storeNode.publish('updateRows');}},50);},true);}}
if(this.sortedBy){this._collectionStore.sortedBy=this.sortedBy;}
return this._collectionStore;},mixin_currentSelectionPars:function(){var kw={};var store=this.collectionStore();if(store.storeType=='VirtualSelection'){kw.selectionName=store.selectionName;}else if(store.storeType=='Selection'&&!store.storeNode.attr.groupByStore){kw.selectedPkeys=this.getSelectedPkeys()||[];if(kw.selectedPkeys.length==0){kw.selectedPkeys=this.getAllPkeys();}else if(kw.selectedPkeys.length==1){kw.allPkeys=this.getAllPkeys();}}else{kw.currentData=this.currentData(null,true);if(this.getSelectedRowidx()==1){kw.allGridData=this.storebag().deepCopy();}}
if(this.cellmap._selected){kw.selectedPkeys=this.sourceNode.getRelativeData('.sets._selected');}else{kw.selectedRowidx=this.getSelectedRowidx();}
kw.selectionCount=store.len(true);return kw;},mixin_createFiltered:function(currentFilterValue,filterColumn,colType){return this.collectionStore().createFiltered(this,currentFilterValue,filterColumn,colType);},mixin_getSelectedNodes:function(){var sel=this.selection.getSelected();var result=[];var store=this.collectionStore();if(!store||!store.len(true)){return result;}
var n;for(var i=0;i<sel.length;i++){n=store.itemByIdx(sel[i]);if(n){result.push(n);}}
return result;},mixin_deleteSelectedRows:function(){var pkeys=this.getSelectedPkeys();var protectPkeys;if(this.collectionStore().allowLogicalDelete){protectPkeys=this.getSelectedProtectedPkeys('delete');}
if(this.gridEditor){this.gridEditor.deleteSelectedRows(pkeys,protectPkeys);this.sourceNode.publish('onDeletedRows');}else{var store=this.collectionStore();if(store.askToDelete){store.deleteAsk(pkeys,protectPkeys);}else{store.deleteRows(pkeys,protectPkeys);}}},mixin_archiveSelectedRows:function(kw){var pkeys=this.getSelectedPkeys();var protectPkeys;if(this.collectionStore().allowLogicalDelete){protectPkeys=this.getSelectedProtectedPkeys();}
this.collectionStore().archiveAsk(pkeys,protectPkeys);},mixin_filterToRebuild:function(value){return this.collectionStore().filterToRebuild(value);},mixin_invalidFilter:function(){return this.collectionStore().invalidFilter();},mixin_resetFilter:function(value){this.sourceNode.setRelativeData('.filtered_totalize',null);this.setClass('gridFilterActive',false);return this.collectionStore().resetFilter();},mixin_isFiltered:function(){return this.collectionStore().isFiltered();},mixin_currentData:function(nodes,rawData,filtered){var nodes=nodes||(this.getSelectedRowidx().length<1?'all':'selected');var result=new gnr.GnrBag();var nodes;if(rawData===true){var filtered=this.collectionStore()._filtered||[];if(nodes=='all'){nodes=this.collectionStore().getData().getNodes();}else if(nodes=='selected'){nodes=this.getSelectedNodes();}
nodes.forEach(function(n,idx){if(filtered.length==0||filtered.indexOf(idx)>=0){result.addItem(n.label,n);}});}else{var col_fields=this.structbag().getItem('#0.#0').digest('#a.field,#a.hidden');var col_names=[];dojo.forEach(col_fields,function(c){if(!c[1])col_names.push(c[0].replace(/\W/g,'_'))});var col_length=col_fields.length;var selector=nodes=='selected'?'.dojoxGrid-view .dojoxGrid-row-selected .dojoxGrid-cell':'.dojoxGrid-view .dojoxGrid-cell';var cells=dojo.query(selector,this.domNode);var curr_row=0;var cell_attrs={};var cell_idx;for(var i=0;i<cells.length;i++){var cell=cells[i];cell_idx=i%col_length;cell_attrs[col_names[cell_idx]]=cell.childNodes[0].innerHTML.replace('&nbsp;','');if((i+1)%col_length==0){result.addItem('r_'+curr_row,null,cell_attrs);cell_attrs={};curr_row+=1;}}}
return result;},mixin_serverAction:function(kw){var options=objectPop(kw,'opt');var allRows=objectPop(options,'allRows');var method=objectPop(options,"method")||"app.includedViewAction";var kwargs=objectUpdate({},options);var useRawData=options['rawData']===true;kwargs['action']=objectPop(kw,'command');var sourceNode=this.sourceNode;genro.lockScreen(true,sourceNode.getStringId());if(this.collectionStore().storeType=='VirtualSelection'){kwargs['selectionName']=this.collectionStore().selectionName;kwargs['selectedRowidx']=allRows?[]:this.getSelectedRowidx();}else{kwargs['data']=this.currentData(allRows?'all':null,useRawData,true);}
kwargs['table']=this.sourceNode.attr.table;kwargs['datamode']=useRawData?this.datamode:'attr';kwargs['struct']=this.getExportStruct();kwargs['_sourceNode']=sourceNode;var cb=function(result){genro.lockScreen(false,sourceNode.getStringId());genro.download(result);};kwargs['meta']=objectExtract(this.sourceNode.attr,'meta_*',true);genro.rpc.remoteCall(method,kwargs,null,'POST',null,cb);},mixin_getExportStruct:function(){var struct=this.structbag().deepCopy();var cells=struct.getItem('#0.#0');var sourceNode=this.sourceNode;var headerList=dojo.query('th',this.viewsHeaderNode);var headerTable=dojo.query('table',this.viewsHeaderNode)[0];const totalWidth=headerTable?headerTable.clientWidth:0;cells._nodes.forEach(function(n,idx){if((n.attr.hidden&&(n.attr.hidden==true||sourceNode.getRelativeData(n.attr.hidden)))||!genro.dom.isVisible(headerList[idx])){cells.popNode(n.label);return;}
n.attr.q_width=Math.round10(headerList[idx].clientWidth/totalWidth)});return struct;},mixin_remoteCellEdit:function(cell,rowIndex){const table=this.sourceNode.attr.table;if(!table){return}
if(cell.customClasses.indexOf('cell_disabled')>=0){return;}
let remoteEdit=cell.remoteEdit;let store=this.collectionStore();if(store.locked){return;}
if(remoteEdit===true){remoteEdit={value:`^.${cell.field}`,lbl:cell.original_name};}
if(!(remoteEdit instanceof Array)){remoteEdit=[remoteEdit];}
let promptkw={};let row=this.rowByIndex(rowIndex);promptkw.dflt=new gnr.GnrBag(row);promptkw.widget=remoteEdit;var pkey=this.rowIdentity(row);promptkw.action=function(result){genro.serverCall('app.updateRecord',{'pkey':pkey,'table':table,'record':result},function(){});}
genro.dlg.prompt(_T('Edit'),promptkw);}});



dojo.declare("gnr.widgets.gnrwdg",null,{constructor:function(application){this._domtag='div';},_beforeCreation:function(attributes,sourceNode){sourceNode.gnrwdg=objectUpdate({'gnr':this,'sourceNode':sourceNode},objectExtract(this,'gnrwdg_*',true));attributes=sourceNode.attr;sourceNode._saved_attributes=objectUpdate({},attributes);sourceNode.attr={};sourceNode.attr.tag=objectPop(attributes,'tag');var catchersHandlers=objectExtract(this,'gnrwdg_catch_*',true);sourceNode.gnrwdg.catchers={};for(var k in sourceNode._dynattr){if(this['gnrwdg_set'+stringCapitalize(k)]){sourceNode.attr[k]=attributes[k];}else{for(var c in catchersHandlers){if(k.indexOf(c+'_')===0){sourceNode.attr[k]=attributes[k];sourceNode.gnrwdg.catchers[k]='catch_'+c;break;}}}}
var datapath=objectPop(attributes,'datapath');if(datapath){sourceNode.attr.datapath=datapath;}
else if(datapath===false){sourceNode.attr.datapath='';}
var contentKwargs=this.contentKwargs(sourceNode,attributes);if(!this.createContent){return false;}
sourceNode.freeze();var children=sourceNode.getValue();sourceNode._value=null;var subTagItems=this.subtags?this.popSubTagItems(sourceNode.attr.tag,children):{};var content=this.createContent(sourceNode,contentKwargs,children,subTagItems);genro.assert(content,'create content must return');content.concat(children);sourceNode._isComponentNode=true;genro.src.stripData(sourceNode);sourceNode.unfreeze(true);return false;},popSubTagItems:function(maintag,children){var result={};for(var tag in this.subtags){var sc=children._nodes.filter(function(n){return n.attr.tag==(maintag+'_'+tag).toLowerCase();});var subtag_items=new gnr.GnrBag();sc.forEach(function(n){delete n.attr.tag;subtag_items.setItem(n.label,children.popNode(n.label));});subtag_items._subtag_handler=this.subtags[tag];result[tag]=subtag_items;}
return result;},onStructChild:function(attributes,source){var parentNode=source.getParentNode();var attr=parentNode?parentNode.attr:{};if(attr.datapath==null&&attributes.datapath==null){var defaultDatapath=this.defaultDatapath(attributes);if(defaultDatapath){attributes.datapath=defaultDatapath;}}},contentKwargs:function(sourceNode,attributes){return attributes;},defaultDatapath:function(attributes){return null;},cell_onCreating:function(gridEditor,colname,colattr){},cell_onDestroying:function(sourceNode,gridEditor,editingInfo){},});dojo.declare("gnr.widgets.TooltipPane",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var ddbId=kw.openerId||sourceNode.getStringId();var modifiers=objectPop(kw,'modifiers')||'*';var onOpening=objectPop(kw,'onOpening');var onClosing=objectPop(kw,'onClosing');var modal=objectPop(kw,'modal');if(onOpening){onOpening=funcCreate(onOpening,'e,sourceNode,dialogNode,kwargs',sourceNode);}
if(onClosing){onClosing=funcCreate(onClosing,'e,sourceNode,dialogNode,kwargs',sourceNode);}
var evt=objectPop(kw,'evt')||'onclick';var parentDomNode;var sn=sourceNode;var placingId=objectPop(kw,'placingId');var noConnector=objectPop(kw,'noConnector');while(!parentDomNode){sn=sn.getParentNode();parentDomNode=sn.getDomNode();}
var ddkw={hidden:true,nodeId:ddbId,modifiers:modifiers,evt:evt,modal:modal,selfsubscribe_open:function(kw){if(!onOpening||onOpening(kw.evt,kw.domNode.sourceNode,this._value.getNode('ttd'),kw)!==false){this.widget.dropDown._lastEvent=kw.evt;this.widget._openDropDown(kw.domNode);}},selfsubscribe_close:function(kw){if(!onClosing||onClosing(kw.evt,kw.evt.target.sourceNode,this._value.getNode('ttd'),kw)!==false){this.widget._closeDropDown();}}};if(placingId){ddkw.onOpeningPopup=function(openKw,evtDomNode){var placingDomNode=genro.domById(placingId);if(placingDomNode){openKw.around=placingDomNode;openKw.popup.domNode.setAttribute('connector',"none");}};}
var ddb=sourceNode._('dropDownButton',ddkw);kw['connect_onOpen']=function(){var wdg=this.widget;if(modal){genro.nodeById('_gnrRoot').setHiderLayer(true,{z_index:1000,opacity:kw.hiderOpacity||0,connect_onclick:function(evt){genro.publish({topic:'close',nodeId:ddbId},{evt:evt});}});}
setTimeout(function(){wdg.resize();},1)};if(modal){kw['connect_onClose']=function(){genro.nodeById('_gnrRoot').setHiderLayer(false);};kw.z_index=1001;}
kw.doLayout=true;var tdialog=ddb._('TooltipDialog','ttd',kw);dojo.connect(parentDomNode,evt,function(e){if(genro.wdg.filterEvent(e,modifiers)){genro.publish(ddbId+'_open',{'evt':e,'domNode':e.target});}});return tdialog;}});dojo.declare("gnr.widgets.MenuDiv",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var buttonkw=objectExtract(kw,'btn_*');var iconClass=objectPop(kw,'iconClass');var label=objectPop(kw,'label');var disabled=objectPop(kw,'disabled');var parentForm=objectPop(kw,'parentForm');buttonkw.hidden=objectPop(kw,'hidden');var tip=objectPop(kw,'tip');iconClass=iconClass?'iconbox '+iconClass:null;var box_kw=objectUpdate({_class:'menuButtonDiv buttonDiv',disabled:disabled,tip:tip},buttonkw);if(parentForm){box_kw.parentForm=parentForm;}
var box=sourceNode._('div',box_kw);if(label&&!iconClass){box._('div',objectUpdate({innerHTML:label,display:'inline-block'},objectExtract(kw,'label_*')));}
if(iconClass){box._('div',{_class:iconClass});}
kw._class=kw._class||'smallmenu';kw.modifiers=kw.modifiers||'*';return box._('menu',kw);}});dojo.declare("gnr.widgets.ColorTextBox",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var chromapars=objectExtract(kw,'colors,steps,menupath,mode,extraLines');var gnrwdg=sourceNode.gnrwdg;kw._autoselect=true;sourceNode.attr._workspace=true;sourceNode.attr.mode=chromapars.mode;sourceNode.attr.colors=chromapars.colors;sourceNode.attr.steps=chromapars.steps;gnrwdg.extraLines=chromapars.extraLines;gnrwdg.menupath=chromapars.menupath||'#WORKSPACE.colormenu';var value=kw.value;if(!value){console.error('Missing value in ColorTextBox');return;}
kw.background='^#WORKSPACE.currentBackground';kw.color='^#WORKSPACE.currentForeground';var tb=sourceNode._('textbox',kw);gnrwdg.tbNode=tb.getParentNode();tb._('comboMenu',{'storepath':gnrwdg.menupath,'_class':'menupane colormenu','selected_color':value.replace('^','')});tb._('dataController',{script:'sn.gnrwdg.setTextBoxColors();','v':kw.value,sn:sourceNode});if(!window.chroma){genro.dom.loadJs('/_rsrc/js_libs/chroma.min.js',function(){gnrwdg.loadMenuData();gnrwdg.setTextBoxColors();});}else{gnrwdg.loadMenuData();gnrwdg.setTextBoxColors();}
return tb;},gnrwdg_setTextBoxColors:function(){var tbNode=this.sourceNode.gnrwdg.tbNode;this.sourceNode.setRelativeData('^#WORKSPACE.currentBackground',null);this.sourceNode.setRelativeData('^#WORKSPACE.currentForeground',null);var v=tbNode.getAttributeFromDatasource('value');if(!v){tbNode.setAttributeInDatasource('value',null);return;}
var c;try{c=chroma(v);}catch(e){return;}
var mode=this.sourceNode.getAttributeFromDatasource('mode')||'hex';var csscolor=mode=='rgba'?c.css():c.hex();if(csscolor!=v){if(this.tbNode.widget){this.tbNode.widget.setValue(csscolor,true);}}
var foreground=chroma.contrast(csscolor,"white")>chroma.contrast(csscolor,"#444")?"white":"#444";this.sourceNode.setRelativeData('^#WORKSPACE.currentBackground',csscolor);this.sourceNode.setRelativeData('^#WORKSPACE.currentForeground',foreground);},gnrwdg_loadMenuData:function(){var kw=this.sourceNode.currentAttributes();var mode=kw.mode||'hex';var b=new gnr.GnrBag();var colors=kw.colors||genro.getData('app_preference.sys.theme.palette_colors')||'black,white,red,green,yellow,blue,purple';var steps=kw.steps||genro.getData('app_preference.sys.theme.palette_steps')||20;var s=chroma.scale(colors.split(',')).colors(steps);var foreground,caption,csscolor,colorcaption;var rescontent;var opSteps=[1.0,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1];var opacityCb=function(color,foregroundColor){var result=new gnr.GnrBag();opSteps.forEach(function(v,idx){var hcolor=chroma(color).alpha(v);var hf=v>=0.5?foregroundColor:"#444";var hcsscolor=hcolor.css();var hcaption='<div style="width:5em;text-align:right;padding-right:5px;background:'+hcsscolor+';"><div style="display:inline-block;font-family:courier;color:'+hf+'">'+v*100+'%</div></div>';result.setItem('r_'+idx,null,{caption:hcaption,color:hcsscolor,foregroundColor:hf});});return result;};var l=s.forEach(function(n,idx){foreground=chroma.contrast(n,"white")>chroma.contrast(n,"#444")?"white":"#444";csscolor=n;rescontent=null;if(mode=='rgba'){csscolor=chroma(n).css();var c=n;var fc=foreground;rescontent=new gnr.GnrBagCbResolver({method:function(){return opacityCb(c,fc);}},true);}
caption='<div style="width:100%;text-align:left;padding-left:5px;background:'+csscolor+';"><div style="display:inline-block;font-family:courier;color:'+foreground+'">'+csscolor+'</div></div>';b.setItem('r_'+idx,rescontent,{caption:caption,color:csscolor,foregroundColor:foreground});});if(this.extraLines){b.setItem('r_'+b.len(),null,{caption:'-'});this.extraLines.split(',').forEach(function(l,idx){b.setItem('r_'+b.len(),null,{caption:l,color:l});});}
this.sourceNode.setRelativeData(this.menupath,b);},gnrwdg_setColors:function(){this.loadMenuData();},gnrwdg_setSteps:function(){this.loadMenuData();},gnrwdg_setMode:function(){this.loadMenuData();},cell_onCreating:function(gridEditor,colname,colattr){console.log('cell_onCreating');},cell_onDestroying:function(sourceNode,gridEditor,editingInfo){console.log('cell_onDestroying');}});dojo.declare("gnr.widgets.ColorFiltering",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var value=kw.value;var gnrwdg=sourceNode.gnrwdg;sourceNode.attr._workspace=true;if(!value){console.error('Missing value in ColorTextBox');return;}
kw.callback=function(kw){var _id=kw._id;var _querystring=kw._querystring;var colorsDict=chroma.colors;var data=objectKeys(colorsDict).sort().map(function(n){return{name:n,_pkey:colorsDict[n],color:'<div style="background:'+colorsDict[n]+';">&nbsp;&nbsp;<div>',caption:n};});var cbfilter=function(n){return true;};if(_querystring){_querystring=_querystring.slice(0,-1).toLowerCase();cbfilter=function(n){return n.name&&n.name.toLowerCase().indexOf(_querystring)>=0;};}else if(_id){cbfilter=function(n){return n._pkey==_id;};}
data=data.filter(cbfilter);return{headers:'name:Color,color:Sample',data:data};};kw.background='^#WORKSPACE.currentBackground';kw.color='^#WORKSPACE.currentForeground';kw.auxColumns='name,color';kw.hasDownArrow=true;kw.limit=0;var tb=sourceNode._('callbackSelect',kw);gnrwdg.tbNode=tb.getParentNode();tb._('dataController',{script:'sn.gnrwdg.setTextBoxColors(v);','v':kw.value,sn:sourceNode});if(!window.chroma){genro.dom.loadJs('/_rsrc/js_libs/chroma.min.js',function(){gnrwdg.setTextBoxColors();});}else{gnrwdg.setTextBoxColors();}
return tb;},gnrwdg_setTextBoxColors:function(){var tbNode=this.sourceNode.gnrwdg.tbNode;var v=tbNode.getAttributeFromDatasource('value');if(!v){tbNode.setAttributeInDatasource('value',null);return;}
var foreground=chroma.contrast(v,"white")>chroma.contrast(v,"#444")?"white":"#444";this.sourceNode.setRelativeData('^#WORKSPACE.currentBackground',v);this.sourceNode.setRelativeData('^#WORKSPACE.currentForeground',foreground);},});dojo.declare("gnr.widgets.TooltipMultivalue",gnr.widgets.TooltipPane,{createContent:function(sourceNode,kw,children){var that=this;var textboxNode=sourceNode.getParentNode();textboxNode.attr.mask='==this._getCurrentMask();';textboxNode._('span',{'innerHTML':textboxNode.attr.value+'?_formattedValue',_class:'formattedViewer',_attachPoint:'focusNode.parentNode'});dojo.addClass(textboxNode.widget.focusNode.parentNode,'formattedTextBox');var valuepath=textboxNode.absDatapath(textboxNode.attr.value);var sourcepath=valuepath+'_mv';textboxNode._getCurrentMask=function(){var data=genro.getData(sourcepath);var mainNode=data?data.getNodeByValue('mv_main',true):null;if(!mainNode){return'';}
return'%s<div class="mv_mask" >'+mainNode.getValue().getItem('mv_label')+'<div>';};textboxNode._mvhandler=this;textboxNode._onSettingValueInData=function(tn,value){that.onSetMainValue(tn,value);};var arrowNode=sourceNode._('comboArrow','arrowNode',{_class:'',iconClass:'mv_iconbox',width:'12px'});arrowNode._('dataController',{script:'genro.dom.setClass( this.getParentNode()._value.getNode("iconNode"),"mv_is_multi",(data&&data.len()>1));',data:'^'+sourcepath});var tooltipPars=objectExtract(kw,'tooltip_*');tooltipPars.onOpening=function(e,sourceNode,dialogNode){var data=genro.getData(sourcepath);that.onSetMainValue(textboxNode,textboxNode.widget.getValue());if(genro.dom.getEventModifiers(e)=='Shift'){that.openMultiValueEditor('new',textboxNode,{sourcepath:sourcepath,valuepath:valuepath});return false;}
that.multivalueTable(dialogNode,textboxNode,{sourcepath:sourcepath,valuepath:valuepath});};var tt=arrowNode._('tooltipPane',tooltipPars);tt._('div','tooltipContent',{padding:'5px',connect_onclick:function(e){if(!sourceNode.form.isDisabled()){that.onSelectedRow(e,this,{sourcepath:sourcepath,valuepath:valuepath});}},connect_ondblclick:function(e){if(!sourceNode.form.isDisabled()){var r=e.target.parentElement.getAttribute('r');that.openMultiValueEditor(r,textboxNode,{sourcepath:sourcepath,valuepath:valuepath});}}});return tt;},openMultiValueEditor:function(r,sourceNode,kw){var that=this;var title=sourceNode.attr.field_name_long;var data=genro.getData(kw.sourcepath);var labels=sourceNode._getMultiValue?sourceNode._getMultiValue():sourceNode.getAttributeFromDatasource('multivalue');var editedRow;if(r=='new'){editedRow=new gnr.GnrBag({mv_label:labels.split(',')[0]});}else{editedRow=data.getItem('#'+r).deepCopy();}
genro.setData('gnr.multivalue.data',editedRow);var dlg=genro.dlg.quickDialog(title,{_showParent:true,width:'280px',datapath:'gnr.multivalue.data'});var bar=dlg.bottom._('slotBar',{slots:'2,deletebtn,*,cancel,confirm,2',action:function(){dlg.close_action();var result=genro.getData('gnr.multivalue').popNode('data').getValue();if(this.attr.command=='delete'&&r!='new'){result.setItem('mv_value',null);}
if(this.attr.command!='cancel'){that.changeMultivalueRow(sourceNode,objectUpdate({result:result,r:r},kw));}}});bar._('button','deletebtn',{'label':_T('Delete'),command:'delete'});bar._('button','cancel',{'label':_T('Cancel'),command:'cancel'});bar._('button','confirm',{'label':_T('Confirm'),command:'confirm'});var box=dlg.center._('div',{padding:'5px'});var fb=genro.dev.formbuilder(box,2,{border_spacing:'3px',width:'270px'});var b=fb.addField('div',{text_align:'right'})
b._('div',{innerHTML:'^.mv_label',_class:'mv_labels'})
b._('menu',{values:labels,action:'SET .mv_label=$1.label',modifiers:'*',_class:'smallmenu'});fb.addField('TextBox',{value:'^.mv_value',width:'13em'});fb.addField('div',{innerHTML:_T('Notes'),td_vertical_align:'top',text_align:'right'})
fb.addField('SimpleTextArea',{value:'^.mv_note',width:'13em',colspan:2});dlg.show_action();},changeMultivalueRow:function(sourceNode,kw){var result=kw.result;result.forEach(function(n){n.attr={};});var r=kw.r;var resultvalue=result.getItem('mv_value');var data=genro.getData(kw.sourcepath);if(r=='new'&&resultvalue){data.setItem('#id',result);}else{var path='#'+r;var editedNode=data.getNode(path);var databag=editedNode.getValue();var is_main=databag.getItem('is_main');databag.setItem('mv_label',result.getItem('mv_label'));databag.setItem('mv_value',resultvalue);databag.setItem('mv_note',result.getItem('mv_note'));genro.setData(kw.valuepath,resultvalue);}
this.cleanMultivalueData(data);},onSetMainValue:function(textboxNode,value){value=value||'';var currvalue=textboxNode.getAttributeFromDatasource('value');var original_value=value;if(currvalue==value){return;}
if(isNullOrBlank(value)&&isNullOrBlank(currvalue)){return;}
var labels=textboxNode._getMultiValue?textboxNode._getMultiValue():textboxNode.getAttributeFromDatasource('multivalue');var multivalues=textboxNode.getRelativeData(textboxNode.attr.value+'_mv');if(!multivalues){multivalues=new gnr.GnrBag();textboxNode.setRelativeData(textboxNode.attr.value+'_mv',multivalues,{});}
var mainNode=multivalues.getNodeByValue('mv_main',true);var m;if(value.indexOf('@')>=0){m=value.match(/(\s*[A-Za-z\d\_\-\+\.]+@(?:[A-Za-z\d\_\-]+\.)+[A-Za-z]{2,})(\s+)?([A-Za-z]+)?(\s+)?([\w\s]+)?/);}else{m=value.match(/(^\s*\d+[\d\s\.\-\+\/]+)(\s+)?([A-Za-z]+)?(\s+)?([\w\s]+)?/);}
var label,notes,r;if(m){value=m[1];label=m[3];notes=m[5];if(label){var k=labels.toLowerCase().split(',').indexOf(label.toLowerCase());if(k>=0){label=labels.split(',')[k];}else{notes=label+' '+notes;label=null;}}
notes=notes?notes.trim():null;}
if(mainNode){r=mainNode._value;label=label||r.getItem('mv_label');}else{r=new gnr.GnrBag();multivalues.setItem('#id',r);label=label||labels.split(',')[0];}
r.setItem('mv_value',value);r.setItem('mv_label',label);if(notes){r.setItem('mv_note',notes);}
this.cleanMultivalueData(multivalues);setTimeout(function(){textboxNode.setRelativeData(textboxNode.attr.value,value);},1);},cleanMultivalueData:function(data){if(data){dojo.forEach(data.getNodes(),function(n){var r=n.getValue();if(!r||!r.getItem('mv_value')){data.popNode(n.label);}});if(data.len()===0){data.getParentNode().setValue(null);}else if(data.len()==1||!data.getNodeByValue('mv_main',true)){data.setItem('#0.mv_main',true);}}},multivalueTable:function(sourceNode,textboxNode,kw){var currmainvalue=textboxNode.widget.getValue();textboxNode.setRelativeData(kw.valuepath,currmainvalue);var data=genro.getData(kw.sourcepath);var contentDomNode=sourceNode._value.getNode('tooltipContent').domNode;contentDomNode.innerHTML=this.multivalueHtmlFromData(data);return;},multivalueHtmlFromData:function(data){var tbody=[];var path,mv_main;var r=0;if(data){data.forEach(function(n){mv_main=n._value.getItem('mv_main')?'true':'false';tbody.push(dataTemplate('<tr r="'+r+'"><td mv_main="'+mv_main+'"></td><td>$mv_label</td><td>$mv_value</td><td>$mv_note</td><tr>',n._value));r++;});}
tbody.push('<tr r="new"><td colspan="4"></td></tr>');return'<table class="mv_table"><tbody>'+tbody.join('')+'</tbody></table>';},onSelectedRow:function(e,sourceNode,kw){if(e.target.getAttribute('mv_main')=='false'){var data=genro.getData(kw.sourcepath);var r=e.target.parentElement.getAttribute('r');if(r=='new'){return;}
data.getNodeByValue('mv_main',true)._value.setItem('mv_main',false)
var newmain=data.getItem('#'+r);newmain.setItem('mv_main',true);genro.setData(kw.valuepath,newmain.getItem('mv_value'));sourceNode.domNode.innerHTML=this.multivalueHtmlFromData(data);}}});dojo.declare("gnr.widgets.Palette",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var left=objectPop(attributes,'left');var right=objectPop(attributes,'right');var top=objectPop(attributes,'top');var bottom=objectPop(attributes,'bottom');var persist=objectPop(attributes,'persist');var lazyContent=objectPop(attributes,'lazyContent');var paletteCode=objectPop(attributes,'paletteCode');if(paletteCode){attributes['datapath']=attributes['datapath']||'gnr.palettes.'+paletteCode;}
if((left===null)&&(right===null)&&(top===null)&&(bottom===null)){this._last_floating=this._last_floating||{top:0,right:0};this._last_floating['top']+=10;this._last_floating['right']+=10;top=this._last_floating['top']+'px';right=this._last_floating['right']+'px';}
var dockTo=objectPop(attributes,'dockTo');var dockButton=objectPop(attributes,'dockButton')||objectExtract(attributes,'dockButton_*');if(dockButton===true){dockButton={iconClass:'iconbox app'};}
if(objectNotEmpty(dockButton)){dockTo='dummyDock';if(!dockButton.label){dockButton._class='iconOnly slotButtonIconOnly';}
attributes.dockButton=dockButton;}
var floating_kwargs=objectUpdate(attributes,{dockable:true,closable:false,visibility:'hidden'});floating_kwargs['templateString']="<div class=\"dojoxFloatingPane\" id=\"${id}\"><div tabindex=\"0\" waiRole=\"button\" class=\"dojoxFloatingPaneTitle\" dojoAttachPoint=\"focusNode\"><span dojoAttachPoint=\"closeNode\" dojoAttachEvent=\"onclick: close\" class=\"dojoxFloatingCloseIcon\"></span><span dojoAttachPoint=\"maxNode\" dojoAttachEvent=\"onclick: maximize\" class=\"dojoxFloatingMaximizeIcon\"></span><span dojoAttachPoint=\"restoreNode\" dojoAttachEvent=\"onclick: _restore\" class=\"dojoxFloatingRestoreIcon\"></span><span dojoAttachPoint=\"dockNode\" dojoAttachEvent=\"onclick: minimize\" class=\"dojoxFloatingMinimizeIcon\"></span><span dojoAttachPoint=\"titleNode\" class=\"dijitInline dijitTitleNode\"></span></div><div dojoAttachPoint=\"canvas\" class=\"dojoxFloatingPaneCanvas\"><div dojoAttachPoint=\"containerNode\" waiRole=\"region\" tabindex=\"-1\" class=\"${contentClass}\"></div><span dojoAttachPoint=\"resizeHandle\" class=\"dojoxFloatingResizeHandle\"></span></div></div>";var showOnStart=false;if(dockTo===false){floating_kwargs.closable=true;floating_kwargs.dockable=false;showOnStart=true;}else if(dockTo&&dockTo.indexOf(':open')>=0){dockTo=dockTo.split(':')[0];objectPop(floating_kwargs,'visibility');showOnStart=true;}
floating_kwargs.subscribe_onClosePage=function(){this.widget.saveRect();};floating_kwargs.onCreated=function(widget){setTimeout(function(){if(showOnStart){widget.show();widget.bringToTop();}},1);};if(!dockTo&&dockTo!==false){dockTo='default_dock';}
if(dockTo){floating_kwargs.dockTo=dockTo;}
return objectUpdate({height:'350px',width:'300px',top:top,right:right,left:left,bottom:bottom,persist:persist,resizable:true},floating_kwargs);},createContent:function(sourceNode,kw){if(kw.dockTo=='*'){var dockId=sourceNode._id+'_dock';sourceNode._('dock',{id:dockId});kw.dockTo=dockId;}
if(kw.dockButton){kw.dockButton['action']=function(){var widget=genro.wdgById(kw.nodeId);widget.show();widget.bringToTop();};kw.dockButton['label']=kw.dockButton['label']||kw.title;kw.dockButton['showLabel']=kw.dockButton['showLabel']||!kw.dockButton.iconClass;sourceNode._('button',kw.dockButton);}
if(kw.nodeId){var that=this;kw.connect_show=function(){genro.publish(kw.nodeId+'_showing');};kw.connect_hide=function(){genro.publish(kw.nodeId+'_hiding');};}
return sourceNode._('floatingPane',kw);}});dojo.declare("gnr.widgets.PalettePane",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var inattr=sourceNode.getInheritedAttributes();var groupCode=inattr.groupCode;attributes.nodeId=attributes.nodeId||'palette_'+attributes.paletteCode;attributes._class=attributes._class||"basePalette";if(groupCode){attributes.groupCode=groupCode;attributes.pageName=attributes.paletteCode;}
return attributes;},defaultDatapath:function(attributes){return'gnr.palettes.'+attributes.paletteCode;},createContent:function(sourceNode,kw){var paletteCode=objectPop(kw,'paletteCode');var contentWidget=objectPop(kw,'contentWidget')||'ContentPane';var groupCode=objectPop(kw,'groupCode');if(groupCode){var pane=sourceNode._('ContentPane',objectUpdate({overflow:'hidden'},objectExtract(kw,'title,pageName')))._(contentWidget,objectUpdate({'detachable':true},kw));var controller_kw={'script':"SET gnr.palettes._groups.pagename."+groupCode+" = paletteCode;",'paletteCode':paletteCode};controller_kw['subscribe_show_palette_'+paletteCode]=true;pane._('dataController',controller_kw);return pane;}else{var palette_kwargs=objectExtract(kw,'title,dockTo,top,left,right,bottom,maxable,height,width,maxable,resizable');palette_kwargs.dockButton=objectPop(kw,'dockButton')||objectExtract(kw,'dockButton_*');palette_kwargs['nodeId']=paletteCode+'_floating';palette_kwargs['title']=palette_kwargs['title']||'Palette '+paletteCode;objectUpdate(palette_kwargs,objectExtract(kw,'palette_*'));palette_kwargs['subscribe_'+paletteCode+'_show']=function(){this.widget.show();this.widget.bringToTop();};palette_kwargs.selfsubscribe_showing=function(){genro.publish('palette_'+paletteCode+'_showing');};palette_kwargs.selfsubscribe_hiding=function(){genro.publish('palette_'+paletteCode+'_hiding');};var floating=sourceNode._('palette',palette_kwargs);return floating._(contentWidget,kw);}}});dojo.declare("gnr.widgets.FramePane",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var node;var frameCode=kw.frameCode;genro.assert(frameCode,'Missing frameCode');if(frameCode.indexOf('#')>=0){kw.frameCode=frameCode=frameCode.replace('#',sourceNode.getStringId());}
var frameId=frameCode+'_frame';genro.assert(!genro.nodeById(frameId),'existing frame');sourceNode.attr.nodeId=frameId;sourceNode._registerNodeId();objectPop(kw,'datapath');var rounded_corners=genro.dom.normalizedRoundedCorners(kw.rounded,objectExtract(kw,'rounded_*',true));var centerPars=objectExtract(kw,'center_*');var bc=sourceNode._('BorderContainer',kw);var slot,slotcontent,v,sidepane,sideKw;var sides=kw.design=='sidebar'?['left','right','top','bottom']:['top','bottom','left','right'];var corners={'left':['top_left','bottom_left'],'right':['top_right','bottom_right'],'top':['top_left','top_right'],'bottom':['bottom_left','bottom_right']};children.walk(function(n){if(n.attr.frameTarget&&!n.attr.nodeId){n.attr.nodeId=frameCode+'_target';}},'static');dojo.forEach(sides,function(side){slot=children.popNode(side);slotcontent=null;sidepane=null;if(slot){slotcontent=slot.getValue();node=slotcontent.popNode('#0');if(slot.attr.tag=='autoslot'){objectPop(slot.attr,'tag');}}else{node=children.popNode('#side='+side);}
if(node){node.attr['frameCode']=frameCode;sideKw=slot?objectUpdate(slot.attr,{'region':side}):{'region':side};sideKw.splitter=sideKw.splitter||objectPop(node.attr,'splitter');objectPop(node.attr,'side');dojo.forEach(corners[side],function(c){v=objectPop(rounded_corners,c);if(v){node.attr['rounded_'+c]=v;}});node.attr['_childname']=node.attr['_childname']||side;sidepane=bc._('ContentPane',sideKw);sidepane.setItem('#id',node._value,node.attr);}
if(sidepane&&slotcontent&&slotcontent.len()>0){dojo.forEach(slotcontent.getNodes(),function(n){n.attr['frameCode']=frameCode;sidepane.setItem('#id',n._value,n.attr);});}});slot=children.popNode('center');var centerNode=slot?slot.getValue().getNode('#0'):children.popNode('#side=center');var center;var rounded={};var frameChild;frameChild=children.popNode('#_frame=true::B');while(frameChild){objectPop(frameChild.attr,'_frame');bc.setItem(frameChild.label,frameChild._value,frameChild.attr);frameChild=children.popNode('#_frame=true::B');}
for(var k in rounded_corners){rounded['rounded_'+k]=rounded_corners[k];}
if(centerNode){objectPop(centerNode.attr,'side');centerNode.attr['region']='center';centerNode.attr['_childname']=centerNode.attr['_childname']||'center';bc.setItem('center',centerNode._value,objectUpdate(rounded,centerNode.attr));center=centerNode._value;}else{centerPars['region']='center';centerPars['_childname']=centerPars['_childname']||'center';centerPars['widget']=centerPars['widget']||'ContentPane';center=bc._(centerPars['widget'],'center',objectUpdate(rounded,centerPars));}
return center;}});dojo.declare("gnr.widgets.BoxForm",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var formId=objectPop(kw,'formId');var storeNode=children.popNode('store');kw._class=(kw._class||'')+' fh_content';var store;if(storeNode){store=this.createStoreFromStoreNode(storeNode);}else{var storekw=objectExtract(kw,'store_*');storekw.handler=storekw.handler||objectPop(kw,'store')||'memory';var storeType=objectPop(kw,'storeType');var parentStore=objectPop(kw,'parentStore');storeType=storeType||(parentStore?'Collection':'Item');store=new gnr.formstores[storeType](storekw,{});}
var controllerPath=objectPop(kw,'controllerPath')||'#WORKSPACE.controller';var pkeyPath=objectPop(kw,'pkeyPath')||'#WORKSPACE.pkey';var formDatapath=objectPop(kw,'formDatapath');return sourceNode._('div',objectUpdate({controllerPath:controllerPath,formDatapath:formDatapath,pkeyPath:pkeyPath,formId:formId,form_store:store,_workspace:true},kw));},createStoreFromStoreNode:function(storeNode){var storeContent=storeNode.getValue();var action,callbacks;storeNode._value=null;var handlers={};if(storeContent){storeContent.forEach(function(n){action=objectPop(n.attr,'action');if(action){objectPop(n.attr,'tag');handlers[action]=n.attr;callbacks=n.getValue();if(callbacks){handlers[action]['callbacks']=callbacks;}}});}
var kw=storeNode.attr;var storeType=objectPop(kw,'storeType');storeType=storeType||(kw.parentStore?'Collection':'Item');return new gnr.formstores[storeType](kw,handlers);}});dojo.declare("gnr.widgets.FrameForm",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var formId=objectPop(kw,'formId');var storeNode=children.popNode('store');var contentNode=children.getNode('center');genro.assert(contentNode,'missing contentNode:  attach to form.center a layout widget');if(contentNode.attr.tag=='autoslot'){contentNode=children.getNode('center.#0');genro.assert(contentNode,'missing contentNode:  attach to form.center a layout widget');}
contentNode.attr['_class']=(contentNode.attr['_class']||'')+' fh_content';var store=this.createStore(storeNode);var frameCode=kw.frameCode;formId=formId||frameCode+'_form';var frame=sourceNode._('FramePane',objectUpdate({controllerPath:'.controller',formDatapath:'.record',pkeyPath:'.pkey',formId:formId,form_store:store},kw));return frame;},createStore:function(storeNode){var storeContent=storeNode.getValue();var action,callbacks;storeNode._value=null;var handlers={};if(storeContent){storeContent.forEach(function(n){action=objectPop(n.attr,'action');if(action){objectPop(n.attr,'tag');handlers[action]=n.attr;callbacks=n.getValue();if(callbacks){handlers[action]['callbacks']=callbacks;}}});}
var kw=storeNode.attr;var storeType=objectPop(kw,'storeType');storeType=storeType||(kw.parentStore?'Collection':'Item');return new gnr.formstores[storeType](kw,handlers);}});dojo.declare("gnr.widgets.PaletteMap",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){return attributes;},createContent:function(sourceNode,kw,children){var paletteCode=kw.paletteCode;kw.frameCode=paletteCode;kw['contentWidget']='FramePane';var mapKw=objectExtract(kw,'map_*',false,true)
var pane=sourceNode._('PalettePane',kw);var centerMarker=objectPop(kw,'centerMarker',true);if(centerMarker){mapKw.centerMarker=true;}
var mapNode=pane._('GoogleMap',objectUpdate({'height':'100%',map_type:'roadmap'},mapKw)).getParentNode();var paletteNode=pane.getParentNode();paletteNode.addMapMarker=function(marker_name,marker){var kw={title:marker_name,draggable:true}
mapNode.gnr.setMarker(mapNode,marker_name,marker,kw)};paletteNode.removeMapMarker=this.removeMapMarker;return pane;}});dojo.declare("gnr.widgets.PaletteGrid",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var gridId=attributes.gridId||attributes.paletteCode+'_grid';attributes['frameCode']=attributes.paletteCode;return attributes;},createContent:function(sourceNode,kw,children){kw['contentWidget']='FramePane';kw['center_overflow']='hidden';var pane=sourceNode._('PalettePane',kw);if(kw.viewResource){return this.createContent_remoteTableHandler(pane,sourceNode,kw);}else{return this.createContent_paletteGrid(pane,sourceNode,kw);}},createContent_remoteTableHandler:function(pane,sourceNode,kw){var paletteCode=kw.paletteCode;kw['grid_onDrag']="dragValues['"+paletteCode+"']=dragValues.gridrow.rowset;"
kw['nodeId']=kw.paletteCode
return pane._('ContentPane','remoteTH',{overflow:'hidden',remote:'th_remoteTableHandler',remote_py_requires:'th/th:TableHandler',remote_thkwargs:kw});},createContent_paletteGrid:function(pane,sourceNode,kw){var gridId=objectPop(kw,'gridId')||frameCode+'_grid';var storepath=objectPop(kw,'storepath');var structpath=objectPop(kw,'structpath');var store=objectPop(kw,'store');var _newGrid=objectPop(kw,'_newGrid',true);var frameCode=kw.frameCode;var paletteCode=kw.paletteCode;structpath=structpath?sourceNode.absDatapath(structpath):'.struct';var gridKwargs={'nodeId':gridId,'datapath':'.grid','table':objectPop(kw,'table'),'configurable':true,'structpath':structpath,'frameCode':frameCode,'autoWidth':false,'store':store,'relativeWorkspace':true};gridKwargs.onDrag=function(dragValues,dragInfo){if(dragInfo.dragmode=='row'){dragValues[paletteCode]=dragValues.gridrow.rowset;}};gridKwargs.draggable_row=true;objectUpdate(gridKwargs,objectExtract(kw,'grid_*'));if(kw.searchOn){pane._('SlotBar',{'side':'top',slots:'*,searchOn',searchOn:objectPop(kw,'searchOn'),toolbar:true});}
pane._(_newGrid?'newIncludedView':'includedview','grid',gridKwargs);var gridnode=pane.getNode('grid');return pane;}});dojo.declare("gnr.widgets.TreeFrame",gnr.widgets.gnrwdg,{getRoot:function(sourceNode,kw){return sourceNode._('FramePane',kw);},subtags:{column:true},createContent:function(sourceNode,kw,children,subTagItems){kw.frameCode=kw.frameCode||kw.paletteCode;var frameCode=kw.frameCode;var editable=objectPop(kw,'editable');var treeId=objectPop(kw,'treeId')||frameCode+'_tree';var storepath=objectPop(kw,'storepath')||'.store';var draggableFolders=objectPop(kw,'draggableFolders');var infoPanel=normalizeKwargs(kw,'infoPanel');var default_onDrag=function(dragValues,dragInfo,treeItem){if(treeItem.attr.child_count&&treeItem.attr.child_count>0&&!draggableFolders){return false;}
dragValues['text/plain']=treeItem.attr.caption;dragValues[frameCode]=treeItem.attr;};var tree_kwargs={_class:'fieldsTree',hideValues:true,margin:'6px',nodeId:treeId,draggable:true,'frameCode':frameCode,onDrag:default_onDrag,storepath:storepath,labelAttribute:'caption',};objectUpdate(tree_kwargs,objectExtract(kw,'tree_*'));var searchOn=objectPop(kw,'searchOn');var pane=this.getRoot(sourceNode,kw);var bc;if(searchOn){pane._('SlotBar',{'side':'top',slots:'*,searchOn',searchOn:true,toolbar:true});}
if(editable){var bagNodeEditorId=treeId+'_editbagbox';var origin=stringStartsWith(storepath,'*S')?'*S':null
tree_kwargs.selfsubscribe_onSelected=function(kw){genro.publish(bagNodeEditorId+'_currentPath',kw.item.getFullpath(null,origin!='*S'?genro._data:null))}
bc=pane._('BorderContainer',{'side':'center'});var bottom=bc._('ContentPane',{'region':'bottom',height:'30%',splitter:true,overflow:'hidden'});bottom._('BagNodeEditor',{nodeId:bagNodeEditorId,datapath:'.bagNodeEditor',origin:origin});pane=bc._('ContentPane',{'region':'center'});}else if(infoPanel){bc=pane._('BorderContainer',{'side':'center'});infoPanel.region=infoPanel.region||'right';if(['left','right'].indexOf(infoPanel.region)>=0){infoPanel.width=infoPanel.width||'300px';}
infoPanel.remote=objectPop(infoPanel,'_');bc._('ContentPane',infoPanel);pane=bc._('ContentPane',{'region':'center'});}
if(subTagItems['column']&&subTagItems['column'].len()){var tg=pane._('treegrid',tree_kwargs);subTagItems['column'].forEach(function(n){tg._('column',null,n.attr);});}else{pane._('tree',tree_kwargs);}
return pane;}});dojo.declare("gnr.widgets.PaletteTree",gnr.widgets.TreeFrame,{getRoot:function(sourceNode,kw){kw['contentWidget']='FramePane';return sourceNode._('PalettePane',kw);}});dojo.declare("gnr.widgets.PaletteImporter",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var frameCode=kw.frameCode=kw.paletteCode;var table=objectPop(kw,'table');var gnrwdg=sourceNode.gnrwdg;gnrwdg.table=table;gnrwdg.match_values=objectPop(kw,'match_values');var uploadPath=objectPop(kw,'uploadPath');var filename=objectPop(kw,'filename');var maxsize=objectPop(kw,'maxsize');var keepFilename=objectPop(kw,'keepFilename');if(!keepFilename){gnrwdg.filename=filename||frameCode+'latest';}
gnrwdg.uploadPath=uploadPath;kw.height=kw.height||'400px';kw.width=kw.width||'650px';sourceNode.attr.nodeId=frameCode;sourceNode._registerNodeId();gnrwdg.matchColumns=objectPop(kw,'matchColumns');gnrwdg.importButtonKw=objectExtract(kw,'importButton_*');gnrwdg.importMethod=objectPop(kw,'rpcmethod');var errorCb=objectPop(kw,'errorCb');gnrwdg.errorCb=errorCb?funcCreate(errorCb,'error',sourceNode):null;gnrwdg.batchParameters=objectExtract(kw,'batch_*');gnrwdg.uploaderId=sourceNode.attr.nodeId+'_uploader';gnrwdg.constant_kwargs=objectExtract(kw,'constant_*',false,true);gnrwdg.sql_mode=objectPop(kw,'sql_mode');var palette=sourceNode._('PalettePane',kw);var bc=palette._('BorderContainer',{_lazyBuild:true});var slots='2,prevtitle,importselector,*,limit,5';var limit=objectPop(kw,'previewLimit')||20;var filetype=objectPop(kw,'filetype');var dropMessage=objectPop(kw,'dropMessage')||'!!Drop import file here';if(!gnrwdg.matchColumns){gnrwdg.matchGrid(bc);}
var frame=bc._('FramePane',{frameCode:frameCode,region:'center',_class:'pbl_roundedGroup',margin:'2px'});var bar=frame._('SlotBar',{'side':'top',slots:slots,searchOn:true,_class:'pbl_roundedGroupLabel'});bar._('div','prevtitle',{innerHTML:"==_current_title || 'Import'",_current_title:'^.current_title',color:'#666'});if(!filetype){bar._('filteringSelect','importselector',{value:'^.filetype',width:'4em',values:'excel,csv,tab,xml',margin_top:'2px'});}else{bar._('div','importseletor')}
bar._('div','limit',{innerHTML:_T('The lines in preview are limited to')+' '+limit,font_style:'italic',font_size:'.8em'});var dropAreaKw={};if(kw.importerStructure){dropAreaKw.rpc_importerStructure=objectPop(kw,'importerStructure');}
dropAreaKw.nodeId=frameCode+'_uploader';dropAreaKw.onUploadingCb=function(dropInfo,data){var uploaderNode=genro.nodeById(gnrwdg.uploaderId);uploaderNode.setRelativeData('.current_title',data.name);};dropAreaKw.rpc_limit=limit;dropAreaKw.rpc_table=table;dropAreaKw.rpc_filetype=filetype||'=.filetype';dropAreaKw.rpc_collection_path='=.collection_path';dropAreaKw.rpc_row_tag='=.row_tag';objectUpdate(dropAreaKw,objectExtract(kw,'drop_*',false,true));dropAreaKw.onResult=function(result){if(result.currentTarget.responseText){gnrwdg.onImportCheck(new gnr.GnrBag(result.currentTarget.responseText));}}
dropAreaKw.filename=gnrwdg.filename;dropAreaKw.uploadPath=gnrwdg.uploadPath;var sc=bc._('StackContainer',{region:'bottom',height:'30px',selected:'^.import_page_status',border_top:'1px solid silver',background:'white'});sc._('ContentPane',{overflow:'hidden'})._('DropUploader','msgslot',objectUpdate({label:_T(dropMessage),font_size:'1.2em',position:'absolute',top:0,left:'3px',right:'3px',bottom:0,color:'#666',text_align:'center',onUploadedMethod:'utils.tableImporterCheck',_class:'importerPaletteDropUploaderBox',cursor:'pointer',nodeId:gnrwdg.uploaderId},dropAreaKw))
var confirmPane=sc._('ContentPane',{});var footerbar=confirmPane._('slotBar',{slots:'5,resetButton,*,importButton,5',margin_top:'5px'});footerbar._('slotButton','resetButton',{label:'Clear',width:'8em',font_size:'1em',padding:'2px',action:function(){gnrwdg.resetImporter();}});var importButtonKw=objectUpdate({label:'Import',width:'8em',font_size:'1em',padding:'2px',imported_file_path:'=.imported_file_path',match:'=.match',action:function(){if(objectNotEmpty(gnrwdg.batchParameters)){genro.publish('table_script_run',this.evaluateOnNode(gnrwdg.batchParameters));gnrwdg.resetImporter();genro.wdgById(frameCode+'_floating').hide();}else{gnrwdg.importDo(this);}},disabled:'^.imported_file_path?=!#v'},gnrwdg.importButtonKw)
footerbar._('slotButton','importButton',importButtonKw);var qg=frame._('borderContainer',{'side':'center'})._('quickGrid',{value:'^.importing_data',region:'center'});gnrwdg.gridNode=qg.getParentNode();var bcnode=bc.getParentNode();gnrwdg.rootNode=bcnode;sourceNode.subscribe('onResult',function(kw){if(kw instanceof gnr.GnrBag){kw={error:kw.pop('error'),message:kw.pop('message'),closeImporter:kw.pop('closeImporter')}}
if(kw.error){if(gnrwdg.errorCb){gnrwdg.errorCb(kw.error);}else{genro.dlg.floatingMessage(bcnode,{message:kw.error,messageType:'error'});}}
else{this.gnrwdg.resetImporter();var closeCb=function(){genro.wdgById(frameCode+'_floating').hide()}
if(kw.message){genro.dlg.floatingMessage(bcnode,{message:kw.message,onClosedCb:kw.closeImporter?closeCb:null})}else if(kw.closeImporter){closeCb();}}});return bc;},gnrwdg_matchGrid:function(bc){var gnrwdg=this;var frame=bc._('FramePane',{frameCode:this.uploaderId+'_matchframe',_anchor:true,region:'left',_class:'pbl_roundedGroup',margin:'2px',drawer:'close',width:'320px',splitter:true})
bar=frame._('slotBar',{slots:'2,matchtitle,*',side:'top',_class:'pbl_roundedGroupLabel'});bar._('div','matchtitle',{innerHTML:'Match columns'});bar=frame._('slotBar',{slots:'2,fbbottom,*',side:'bottom',_class:'slotbar_dialog_footer'});var fb=genro.dev.formbuilder(bar._('div','fbbottom'),3,{border_spacing:'1px'});fb.addField('filteringSelect',{value:'^.import_method',width:'7em',lbl_text_align:'right',lbl_class:'gnrfieldlabel',lbl:_T('Method'),values:'^.methodlist',lbl_hidden:'^.methodlist?=!#v',hidden:'^.methodlist?=!#v',parentForm:false});fb.addField('filteringSelect',{value:'^.import_mode',width:'7em',lbl_text_align:'right',lbl_class:'gnrfieldlabel',lbl:_T('Mode'),lbl_hidden:'^.import_modes?=!#v',hidden:'^.import_modes?=!#v',values:'^.import_modes',parentForm:false});if(this.table&&!this.sql_mode){fb.addField('checkbox',{value:'^.sql_mode',label:_T('SQL Mode'),parentForm:false});}
var grid=frame._('BorderContainer',{'side':'center',overflow:'hidden'})._('quickGrid',{value:'^.match',_class:'noselect',region:'center'});grid.getParentNode().importer_gnrwdg=this;var onclick="this.getParentNode().importer_gnrwdg.onCheckedMatch(this,kw);"
var editdestpars=true;if(this.match_values){editdestpars={tag:'combobox',values:this.match_values,validate_onAccept:"if(value){this.setRelativeData('.do_import',true)}"};}
grid._('column',{name:'Key',field:'is_key',width:'2em',dtype:'B',hidden:'^#ANCHOR.import_mode?=#v!="update_only"',checkBoxColumn:{radioButton:true},cellStyles:'border-bottom:1px solid lightgray;background:white;'})
grid._('column',{name:'Source Column',field:'source_field',width:'10em',cellStyles:'background:#666;color:whitesmoke;text-align:right; border-left:0px;border-bottom:1px solid whitesmoke;'})
grid._('column',{name:'Dest.Column',field:'dest_field',cellStyles:'border-bottom:1px solid lightgray;background:white;',edit:editdestpars,width:'10em'})
if(!this.table){grid._('column',{name:'Type',field:'dtype',cellStyles:'border-bottom:1px solid lightgray;background:white;',edit:{values:'T:Text,L:Integer,N:Decimal,D:Date,B:Boolean,H:Time,P:Image',tag:'filteringSelect'},width:'7em'})}
grid._('column',{name:' ',field:'do_import',width:'2em',dtype:'B',format_onclick:onclick,cellStyles:'border-bottom:1px solid lightgray;background:white;'})},gnrwdg_resetImporter:function(){var uploaderNode=genro.nodeById(this.uploaderId);uploaderNode.setRelativeData('.current_title',null);uploaderNode.setRelativeData('.methodlist','');uploaderNode.setRelativeData('.import_modes','');uploaderNode.setRelativeData('.import_mode','');uploaderNode.setRelativeData('.importing_data',null);uploaderNode.setRelativeData('.file_columns',null);uploaderNode.setRelativeData('.match',null);uploaderNode.setRelativeData('.imported_file_path',null);uploaderNode.setRelativeData('.import_page_status',0);this.gridNode.gnrwdg.setColumns(new gnr.GnrBag());},gnrwdg_onImportCheck:function(data){var errors=data.getItem('errors');if(errors){genro.dlg.floatingMessage(this.rootNode,{message:errors,messageType:'error'});return;}
var columns=data.getItem('columns');var match_data=data.getItem('match_data');var warning=false;if(this.matchColumns&&this.matchColumns!='*'){var colkeys=columns.keys();var matchColumns=this.matchColumns.split(',');if(matchColumns.length!=colkeys.length||matchColumns.some(function(n,idx){return n!=colkeys[idx]})){genro.dlg.floatingMessage(this.rootNode,{message:_T('Columns mismatch'),messageType:'error'})
return;}}
this.gridNode.gnrwdg.setColumns(columns);this.gridNode.gnrwdg.guessColumns=false;var uploaderNode=genro.nodeById(this.uploaderId);uploaderNode.setRelativeData('.methodlist',data.getItem('methodlist'));uploaderNode.setRelativeData('.import_modes',data.getItem('import_modes'));uploaderNode.setRelativeData('.import_mode',data.getItem('import_mode'));uploaderNode.setRelativeData('.importing_data',data.getItem('rows'));uploaderNode.setRelativeData('.file_columns',columns);uploaderNode.setRelativeData('.match',match_data);uploaderNode.setRelativeData('.imported_file_path',data.getItem('imported_file_path'));uploaderNode.setRelativeData('.import_page_status',1);},gnrwdg_onCheckedMatch:function(matchGrid,kw){var p='#'+kw.rowIndex+'.do_import';var s=matchGrid.widget.collectionStore().getData();s.setItem(p,!s.getItem(p));var previewStructCells=this.gridNode.getRelativeData('#WORKSPACE.struct.#0.#0')
var importfields=s.values().forEach(function(v){var nprev=previewStructCells.getNode(v.getItem('source_field'));if(v.getItem('do_import')){delete nprev.attr.hidden;}else{nprev.attr.hidden=true;}});this.gridNode.setRelativeData('#WORKSPACE.struct?_updated',genro.getCounter());},gnrwdg_importDo:function(buttonNode){var match_index;var match=buttonNode.getRelativeData('.match');if(match&&match.len()){match_index={};match.values().forEach(function(v){if(v&&v.getItem('do_import')){match_index[v.getItem('source_field')]=v.getItem('dest_field')||v.getItem('source_field');if(v.getItem('is_key')){match_index._updater_keyfield=v.getItem('dest_field');}}})}
var that=this;genro.lockScreen(true,'import_data',{thermo:true});var importerKw={table:this.table,file_path:'=.imported_file_path',match_index:match_index,import_method:'=.import_method',import_mode:'=.import_mode',filetype:'=.filetype',sql_mode:this.sql_mode||'=.sql_mode',timeout:3600000,_sourceNode:buttonNode};if(this.constant_kwargs){objectUpdate(importerKw,this.constant_kwargs);}
genro.serverCall(this.importMethod||'utils.tableImporterRun',importerKw,function(result){genro.dlg.floatingMessage(that.rootNode,{message:_T('Import finished')});if(result&&result.warnings){genro.dlg.floatingMessage(that.rootNode,{message:result.warnings});}
that.resetImporter();genro.lockScreen(false,'import_data');});}});dojo.declare("gnr.widgets.VideoPickerPalette",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var paletteKw=objectExtract(kw,'palette_*')
var paletteCode=paletteKw.paletteCode=objectPop(kw,'paletteCode')||'capturePicker';paletteKw.height=paletteKw.height||'700px';paletteKw.width=paletteKw.width||'420px';paletteKw.dockButton='dockButton'in paletteKw?paletteKw.dockButton:true;paletteKw.selfsubscribe_showing=function(){genro.publish(paletteCode+'_video'+'_startCapture');}
var palette=sourceNode._('PalettePane',paletteKw);var bc=palette._('BorderContainer')
var top=bc._('framePane',{frameCode:paletteCode+'_cam',region:'top',height:'350px',splitter:true});var bar=top._('SlotBar',{'side':'bottom',slots:'*,zoomSlider,5,snap,5',toolbar:true});bar._('horizontalSlider','zoomSlider',{value:'^.currentZoom','default':0.3,minimum:0.3,maximum:1,intermediateChanges:true,width:'15em',margin_top:'2px'});bar._('slotButton','snap',{label:'Take picture',iconClass:'iconbox photo',action:function(){genro.publish(paletteCode+'_video'+'_takePicture');}})
top._('video',{autoplay:true,height:'300px',width:'400px',margin:'10px',nodeId:paletteCode+'_video',selfsubscribe_takePicture:function(){var box=genro.nodeById(paletteCode+'_preview');var c=box._('canvas',{height:'300px',width:'400px',display:'inline-block',margin:'5px',draggable:true,onDrag:function(dragValues,dragInfo){dragValues['dataUrl']=dragInfo.sourceNode.domNode.toDataURL('image/png');}})
c.getParentNode().takePhoto(this);},selfsubscribe_startCapture:function(){this.startCapture({video:true})}});var center=bc._('FramePane',{frameCode:paletteCode+'_viewer',region:'center'});center._('div','box',{position:'absolute',overflow:'auto',top:'2px',left:'2px',right:'2px',bottom:'2px',nodeId:paletteCode+'_preview',zoom:'^.currentZoom'});return palette;}});dojo.declare("gnr.widgets.MultiValueEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;gnrwdg.editNodeValue=objectPop(kw,'editNodeValue');gnrwdg.origin=objectPop(kw,'origin');sourceNode.attr.exclude=objectPop(kw,'exclude');sourceNode.attr.value=objectPop(kw,'value');var grid_kwargs=objectExtract(kw,'grid_*');var tools=objectPop(kw,'tools');var tools_kw=objectExtract(kw,'tools_*');var readOnly=objectPop(kw,'readOnly');if(tools==undefined&&!readOnly){tools='delrow,addrow';}
gnrwdg.exclude=sourceNode.currentFromDatasource(sourceNode.attr.exclude);var container=sourceNode._('BorderContainer',objectUpdate({selfsubscribe_setSource:function(source){gnrwdg.setSource(source);}},kw));gnrwdg.containerNode=container.getParentNode();var grid=container._('ContentPane',{region:'center',overflow:'hidden'})._('quickGrid',objectUpdate({value:'^#WORKSPACE.value',_workspace:true,_class:'multiValueEditor noheader',storeInForm:true,border:'1px solid #efefef',selfsubscribe_addrow:function(addkw){var grid=this.widget;setTimeout(function(){gnrwdg.addEditorRow(grid,addkw);},500)}},grid_kwargs));grid._('column',{name:'Key',field:'attribute_key',width:'15em',cellStyles:'background:#BBB;color:#333;border-bottom:1px solid white;font-weight:bold;'})
grid._('column',{name:'Value',field:'attribute_value',edit:!readOnly,width:'100%',cellStyles:'border-bottom:1px solid lightgray;'})
if(tools){var t=grid._('tools',objectUpdate({tools:tools,custom_tools:{addrow:{content_class:'iconbox add_row',ask:{title:'New Line',fields:[{name:'attribute_key',lbl:'Key',validate_notnull:true},{name:'dtype',lbl:'Datatype',values:'T:Text,B:Boolean,L:Integer,N:Decimal,D:Date,H:Time',wdg:'filteringSelect',default_value:'T'},{name:'attribute_value',lbl:'Value'}]}}}},tools_kw))}
gnrwdg.gridNode=grid.getParentNode();if(sourceNode.attr.value){gnrwdg.setSource(sourceNode.attr.value);}
var dc=gnrwdg.gridNode._('dataController',{script:'this._onGridChangedData(data,_triggerpars)',data:'^#WORKSPACE.value'})
dc.getParentNode()._onGridChangedData=function(data,_triggerpars){gnrwdg.tempBagTrigger(data,_triggerpars)}
return grid},gnrwdg_addEditorRow:function(grid,kw){var key=kw.attribute_key;var value=kw.attribute_value;var dtype=kw.dtype;if(!key){genro.dlg.floatingMessage(this.containerNode,{messageType:'error',message:'Missing key'})
return;}
if(this.exclude&&this.exclude.split(',').indexOf(key)>=0){genro.dlg.floatingMessage(this.containerNode,{messageType:'error',message:'You cannot add this key'})
return;}
grid.addRows([{'attribute_key':key,'attribute_value':value}],null,null,function(firstRow){var valueNode=firstRow._value.getNode('attribute_value');valueNode.attr.wdg_dtype=dtype||'T';if(!isNullOrBlank(value)){valueNode.setValue(value);return false;}});},gnrwdg_setExclude:function(value){this.exclude=value;this.setTempStore();},gnrwdg_setValue:function(value,kw,reason){if(reason=='child'){return;}
this.setTempStore();},gnrwdg_setSource:function(value){if(typeof(value)!='string'){this.source_item=value;}else{if(this.origin=='*S'){this.source_root=genro.src._main;this.valuepath=value;}else{this.source_root=genro._data;this.valuepath=this.sourceNode.absDatapath(value);}}
this.setTempStore();},gnrwdg_getSource:function(){if(this.source_item){return this.source_item;}
var result=isNullOrBlank(this.valuepath)?this.source_root:this.source_root.getItem(this.valuepath,null,'static');if(!result&&this.valuepath){result=new gnr.GnrBag();this.source_root.setItem(this.valuepath,result,null,{doTrigger:false});}
return result;},gnrwdg_setTempStore:function(){var exclude=(this.exclude||'').split(',');var addRow=function(where,key,value,dtype){if(exclude.indexOf(key)>=0){return;}
var r=new gnr.GnrBag();var keyattr,rowattr;if(value instanceof gnr.GnrBag){value='*bag*';}
if(key=='*value'){keyattr={editDisabled:true};rowattr={_protect_delete:true};}
r.setItem('attribute_key',key,keyattr);var value_attr={wdg_dtype:dtype||guessDtype(value)||'T'};if(value_attr.wdg_dtype=='X'){value_attr['editDisabled']=true;}
r.setItem('attribute_value',value,value_attr);where.setItem('#id',r,rowattr);}
var source=this.getSource();var result=new gnr.GnrBag();if(source instanceof gnr.GnrBagNode){if(this.editNodeValue){addRow(result,'*value',source.getValue('static'));}
source=source.attr;}
if(source instanceof gnr.GnrBag){source.forEach(function(n){addRow(result,n.label,n.getValue(),n.attr.dtype);});}else{for(var k in source){addRow(result,k,source[k]);}}
this.gridNode.setRelativeData('#WORKSPACE.value',result,null,null,'loadData');},gnrwdg_tempBagTrigger:function(data,_triggerpars){var trigger_kwargs=_triggerpars.kw;if(trigger_kwargs.reason=='initStore'||trigger_kwargs.reason=='loadData'){return;}
var evt=trigger_kwargs.evt;var k,v,vn;var source=this.getSource();if(evt=='upd'){var r=trigger_kwargs.node.getParentBag()
k=r.getItem('attribute_key');vn=r.getNode('attribute_value');if(!vn){return;}
v=vn.getValue();if(vn.attr.dtype=='AR'){v=v.split(',');}
if(source instanceof gnr.GnrBagNode){if(k=='*value'){source.setValue(v,true);}else{source.setAttribute(k,v,true);}}else{if(source instanceof gnr.GnrBag){source.setItem(k,v,null,{lazySet:true});}else{source[k]=v;}}}else if(evt=='del'){k=trigger_kwargs.node._value.getItem('attribute_key');if(source instanceof gnr.GnrBagNode){source.setAttribute(k,null);}else{if(source instanceof gnr.GnrBag){source.popNode(k);}else{objectPop(source,k);}}}}});dojo.declare("gnr.widgets.PaletteBagNodeEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var pane=sourceNode._('PalettePane',kw);var nodePath=objectPop(kw,'nodePath');var multiValuePars=objectExtract(kw,'origin,exclude')
var bc=pane._('BorderContainer',{_class:'bagNodeEditor'});if(genro.isDeveloper){var bottom=bc._('ContentPane',{'region':'bottom',color:'#666',font_style:'italic'});bottom._('span',{'innerHTML':'Path : '});bottom._('span',{'innerHTML':nodePath,_class:'selectable'});}
bc._('ContentPane',{region:'center',margin:'2px',overflow:'hidden'})._('MultiValueEditor',objectUpdate({value:nodePath+'?#node'},multiValuePars))
return pane;}});dojo.declare("gnr.widgets.PaletteBagEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var palette_kw=objectExtract(kw,'paletteCode,groupCode,dockTo,title');objectUpdate(palette_kw,objectExtract(kw,'palette_*',null,true));palette_kw.palette_width=kw.palette_width||'500px';var pane=sourceNode._('PalettePane',palette_kw);pane._('FlatBagEditor',kw);return pane;}});dojo.declare("gnr.widgets.FlatBagEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;var path=objectPop(kw,'path');var toolskw=objectExtract(kw,'addrow,delrow');var multiValuePars=objectExtract(kw,'origin,exclude');var box_kw=objectUpdate({},objectExtract(kw,'box_*'));var bc=sourceNode._('BorderContainer',box_kw);var grid_region=objectPop(kw,'grid_region','left');var boxpars={region:grid_region,_class:'noheader no_over',margin:'2px',border:'1px solid #efefef',splitter:true};if(grid_region=='left'||grid_region=='right'){boxpars.width='30%';}else{boxpars.height='50%';}
var left=bc._('ContentPane',boxpars);var grid_attr={value:'^'+path,datamode:'attr',selfDragRows:true,selfsubscribe_onSelectedRow:function(kw){if(kw.idx>=0){var n=this.widget.collectionStore().itemByIdx(kw.idx);gnrwdg.mveNode.gnrwdg.setSource(path+'.'+n.label+'?#node');}},onCreated:function(){var w=this.widget;setTimeout(function(){w.updateRowCount();},1);}};objectUpdate(grid_attr,objectExtract(kw,'grid_*'));var g=left._('quickGrid','nodeListGrid',grid_attr);g._('column',{field:'field',name:'Cells',width:'100%'});var t=[];if(toolskw.delrow){t.push('delrow');if(toolskw.delrow===true){objectPop(toolskw,'delrow')}}
if(toolskw.addrow){t.push('addrow');if(toolskw.addrow===true){objectPop(toolskw,'addrow')}}
if(t.length){g._('tools',{tools:t.join(','),custom_tools:toolskw,title:_T('Rows')});}
multiValuePars.tools_title=_T('Attributes');var mve=bc._('ContentPane',{region:'center',margin:'2px',overflow:'hidden'})._('MultiValueEditor','mve',multiValuePars);gnrwdg.mveNode=mve.getParentNode();return bc;}});dojo.declare("gnr.widgets.BagNodeEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;var nodeId=objectPop(kw,'nodeId');var readOnly=objectPop(kw,'readOnly',false);var showBreadcrumb=objectPop(kw,'showBreadcrumb',true);var bc=sourceNode._('BorderContainer',{detachable:true,_class:'bagNodeEditor',nodeId:nodeId,selfsubscribe_currentPath:function(nodePath){gnrwdg.setCurrentPath(nodePath);}});if(showBreadcrumb){var bottom=bc._('ContentPane',{'region':'bottom',color:'#666',font_style:'italic'});bottom._('span',{'innerHTML':'Path : '});bottom._('span',{'innerHTML':'^.currentEditedPath',_class:'selectable'});}
var box=bc._('ContentPane',{'region':'center',_class:'formgrid',overflow:'hidden'});var mve=box._('MultiValueEditor','mve',{origin:kw.origin,editNodeValue:true})
gnrwdg.mveNode=mve.getParentNode();return box;},gnrwdg_setCurrentPath:function(nodePath){this.sourceNode.setRelativeData('.currentEditedPath',nodePath);this.mveNode.gnrwdg.setSource(nodePath+'?#node');}});dojo.declare("gnr.widgets.SearchBox",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){attributes.onKeyUp=function(e){var sourceNode=e.target.sourceNode;genro.dom.setClass(sourceNode.getParentNode(),'activeSearch',!isNullOrBlank(e.target.value));sourceNode.setRelativeData('.currentValue',e.target.value);};return attributes;},defaultDatapath:function(attributes){return'.searchbox';},createContent:function(sourceNode,kw){var searchOn=objectPop(kw,'searchOn')||true;var searchDtypes;if(searchOn[0]=='*'){searchDtypes=searchOn.slice(1);searchOn=true;}
var nodeId=objectPop(kw,'nodeId');var menubag;var databag=new gnr.GnrBag();var defaultLabel=objectPop(kw,'searchLabel')||'Search';databag.setItem('menu_dtypes',searchDtypes);databag.setItem('caption',defaultLabel);databag.setItem('searchDelay',1000);this._prepareSearchBoxMenu(searchOn,databag,sourceNode);databag.setItem('value','');sourceNode.setRelativeData(null,databag);var searchbox=sourceNode._('form',{autocomplete:'false',action:'javascript:void(0);'})._('table',{nodeId:nodeId})._('tbody')._('tr');var delay=objectPop(kw,'delay')||objectPop(search_kw,'delay')||100;var search_kw=objectPop(kw,'search_kw')||{};sourceNode._('dataController',{'script':'genro.publish(searchBoxId+"_changedValue",currentValue,field,this.evaluateOnNode(search_kw));','searchBoxId':nodeId,currentValue:'^.currentValue',field:'=.field',_userChanges:true,_delay:delay,search_kw:search_kw});var searchlbl=searchbox._('td');searchlbl._('div',{'innerHTML':'^.caption',_class:'buttonIcon searchboxLabel'});searchlbl._('menu',{'modifiers':'*',_class:'smallmenu',storepath:'.menubag',selected_col:'.field',selected_caption:'.caption',action:'SET .value = null;SET .currentValue = null;'});searchbox._('td')._('div',{_class:'searchInputBox',connect_onclick:function(e){if(e.target.tagName.toLowerCase()!='input'){var that=this;var finalize=function(){that.setRelativeData('.value',null);that.setRelativeData('.currentValue',null);genro.dom.removeClass(that,'activeSearch');};genro.publish(nodeId+"_stopSearch",{inputSourceNode:this,finalize:finalize});}}})._('input',{'value':'^.value',connect_onkeyup:kw.onKeyUp,parentForm:false,width:objectPop(kw,'width')||'6em',tabindex:"-1",connect_focus:function(){this.domNode.select()}});sourceNode.registerSubscription(nodeId+'_updmenu',this,function(searchOn){menubag=this._prepareSearchBoxMenu(searchOn,sourceNode.getRelativeData(),sourceNode);});return searchbox;},_prepareSearchBoxMenu:function(searchOn,databag,sourceNode){var menubag=new gnr.GnrBag();var i=0;if(searchOn===true){databag.setItem('menu_auto',menubag);}
else{dojo.forEach(searchOn.split(','),function(col){col=dojo.trim(col);var caption=col;if(col.indexOf(':')>=0){col=col.split(':');caption=col[0];col=col[1];}
col=col.replace(/[.@]/g,'_');let attr={col:col,caption:caption,child:''};attr=sourceNode.evaluateOnNode(attr);menubag.setItem('r_'+i,null,attr);i++;});}
databag.setItem('field',menubag.getItem('#0?col'));var defaultLabel=menubag.getItem('#0?caption');if(defaultLabel){databag.setItem('caption',defaultLabel);}
databag.setItem('menubag',menubag);}});dojo.declare("gnr.widgets.PaletteGroup",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var groupCode=objectPop(kw,'groupCode');var palette_kwargs=objectExtract(kw,'title,dockTo,top,left,right,bottom,height,width,maxable,resizable');palette_kwargs.dockButton=objectPop(kw,'dockButton')||objectExtract(kw,'dockButton_*');palette_kwargs['nodeId']=palette_kwargs['nodeId']||groupCode+'_floating';palette_kwargs['overflow']='hidden'
palette_kwargs.selfsubscribe_showing=function(){genro.publish('palette_'+this.getRelativeData('gnr.palettes._groups.pagename.'+groupCode)+'_showing');};palette_kwargs['title']=palette_kwargs['title']||'Palette '+groupCode;var floating=sourceNode._('palette',palette_kwargs);var tab_kwargs=objectUpdate(kw,{selectedPage:'^gnr.palettes._groups.pagename.'+groupCode,groupCode:groupCode,_class:'smallTabs',margin:'2px'});var tc=floating._('tabContainer',tab_kwargs);return tc;}});dojo.declare("gnr.widgets.DownloadButton",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){kw._rpcpars=objectUpdate({},objectExtract(kw,'rpc_*'));kw.action="var pars = this.evaluateOnNode(_rpcpars); var method = objectPop(pars,'method'); genro.rpcDownload(method,pars)";var wdg=objectPop(kw,'wdg')||'Button';return sourceNode._(wdg,kw);}});dojo.declare("gnr.widgets.DocumentFrame",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var framekw=objectExtract(kw,'frame_*');var barkw=objectExtract(kw,'pdf,print,download,title')
var resource=objectPop(kw,'resource');var rpcCall=objectPop(kw,'rpcCall');var _delay=objectPop(kw,'_delay');var emptyMessage=objectPop(kw,'emptyMessage','Missing');var _if=objectPop(kw,'_if');var _reloader=objectPop(kw,'_reloader')||'^#WORKSPACE.reload_iframe';if(resource){resource=resource.split(':');kw['table']=resource[0];kw['respath']=resource[1];kw['pdf']=kw.html?false:true;kw['record']=kw.pkey;rpcCall='callTableScript';}
framekw.frameCode='document_frame_#'
framekw['_workspace']=true;var frame=sourceNode._('framePane',framekw);var iframekw={height:'100%',width:'100%',border:0,rpcCall:'callTableScript'};for(var k in kw){var val=kw[k];if(val&&typeof(val)=='string'){val=val.replace('^','=');}
iframekw['rpc_'+k]=val;}
iframekw['_reloader']=_reloader;iframekw['_if']='^#WORKSPACE.enabled';iframekw['rpcCall']=rpcCall;iframekw['_delay']=_delay;iframekw['documentClasses']=true;objectUpdate(iframekw,objectExtract(kw,'iframe_*'));var iframe=frame._('ContentPane','center',{overflow:'hidden'})._('iframe',iframekw);var scriptkw=objectUpdate({'script':"SET #WORKSPACE.enabled = true; FIRE #WORKSPACE.reload_iframe;",'_delay':100,_if:_if,_else:'SET #WORKSPACE.enabled = false;'},kw);frame._('dataController',scriptkw);return frame;}});dojo.declare("gnr.widgets.IframeDiv",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var value=objectPop(kw,'value');kw.border=kw.border||0;sourceNode.attr.value=value;var iframe=sourceNode._('iframe',kw);var gnrwdg=sourceNode.gnrwdg;gnrwdg.zoom=objectPop(kw,'zoom');gnrwdg.iframeNode=iframe.getParentNode();return iframe;},gnrwdg_setValue:function(value,kw,trigger_reason){if(this.zoom){value='<div style="zoom:'+this.zoom+'">'+value+'</div>';}
this.iframeNode.domNode.contentWindow.document.body.innerHTML=value;}});dojo.declare("gnr.widgets.QuickEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){kw['constrain_margin']='1px';kw['toolbar']=kw['toolbar']||false;var boxpars=objectExtract(kw,'height,width,z_index,position,top,left,right,bottom,_class');boxpars.height=boxpars.height;boxpars.position=boxpars.position||'relative'
boxpars._class=(boxpars._class||'')+' quickEditorWrapper';var box=sourceNode._('div',boxpars);var editor=box._('div',{_class:'quickEditor'})._('div',{position:'absolute',top:'1px',bottom:'2px',left:'1px',right:'1px'})._('ckeditor',kw);box._('div',{_class:'quickEditorButton fakeButton'})._('div',{_class:'dijitArrowButtonInner',height:'17px',width:'18px',cursor:'pointer',connect_onclick:function(){genro.dlg.dialogEditor(editor.getParentNode(),{});}})
return editor;},cell_onCreating:function(gridEditor,colname,colattr){colattr['z_index']=1;colattr['constrain_overflow']='hidden'
colattr['height']=colattr['height']||'18px';}});dojo.declare("gnr.widgets.QuickTree",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var value=objectPop(kw,'value');kw.storepath=sourceNode.absDatapath(value);return sourceNode._('tree',kw);}});dojo.declare("gnr.widgets.CodeEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var value=objectPop(kw,'value');var readOnly=objectPop(kw,'readOnly');if(readOnly==undefined){readOnly=true;}
var editor_kwargs=objectExtract(kw,'editor_*');var tree_kwargs=objectExtract(kw,'tree_*');sourceNode.attr.value=value;var gnrwdg=sourceNode.gnrwdg;gnrwdg.rpcSourceBrowserGetter=objectPop(kw,'rpcSourceBrowser')||'dev.rpcSourceBrowserGetter';gnrwdg.rpcSourceCodeGetter=objectPop(kw,'rpcSourceCodeGetter')||'dev.loadModuleElement';gnrwdg.rpcSourceCodeSaver=objectPop(kw,'rpcSourceCodeSaver')||'dev.saveModuleElement';sourceNode.attr._workspace=true;kw.frameCode=kw.frameCode||'CodeEditor_'+genro.getCounter();var frame=sourceNode._('FramePane','rootNode',kw);var bc=frame._('BorderContainer',{side:'center'});var pref=kw.frameCode?kw.frameCode+'_':'';var center=bc._('ContentPane','sourceViewer',{region:'center',overflow:'hidden'});var editor=center._('codemirror','sourceEditor',objectUpdate({value:'^#WORKSPACE.currentSourceElement',readOnly:readOnly,config_mode:'python',config_lineNumbers:true,config_indentUnit:4,config_keyMap:'softTab',height:'100%'},editor_kwargs));gnrwdg.editorNode=editor.getParentNode();return bc;},gnrwdg_setValue:function(value){var module=this.sourceNode.getAttributeFromDatasource('value');var sourceNode=this.sourceNode;if(!module){sourceNode.setRelativeData('#WORKSPACE.currentSourceElement_loadedValue','');sourceNode.setRelativeData('#WORKSPACE.currentSourceElement','');return}
genro.serverCall('dev.loadModuleSource',{module:module},function(result){sourceNode.setRelativeData('#WORKSPACE.currentSourceElement_loadedValue',result);sourceNode.setRelativeData('#WORKSPACE.currentSourceElement',result);});},gnrwdg_onSelectedBrowserNode:function(kw){sourceNode.setRelativeData('#WORKSPACE.currentSelectedElement',kw.path);this.loadModuleElement();},gnrwdg_loadModuleElement:function(){var module=this.sourceNode.getAttributeFromDatasource('value');var currentSelectedElement=this.sourceNode.getRelativeData('#WORKSPACE.currentSelectedElement');var sourceNode=this.sourceNode;genro.serverCall(this.rpcSourceCodeGetter,{module:module,element:currentSelectedElement},function(result){sourceNode.setRelativeData('#WORKSPACE.currentSourceElement_loadedValue',result);sourceNode.setRelativeData('#WORKSPACE.currentSourceElement',result);});},gnrwdg_saveChanges:function(){var module=this.sourceNode.getAttributeFromDatasource('value');var currentSelectedElement=this.sourceNode.getRelativeData('#WORKSPACE.currentSelectedElement');var sourceNode=this.sourceNode;},});dojo.declare("gnr.widgets.TreeGrid",gnr.widgets.gnrwdg,{subtags:{column:true},createContent:function(sourceNode,kw,children,subTagItems){sourceNode.attr._workspace=true;var gnrwdg=sourceNode.gnrwdg;var that=this;var columns=objectPop(kw,'columns');var boxpars=objectExtract(kw,'box_*');gnrwdg.width=0;gnrwdg.labelAttribute=objectPop(kw,'labelAttribute');gnrwdg.headers=objectPop(kw,'headers');gnrwdg.footers=objectPop(kw,'footers');gnrwdg.headers_footers_kw=objectExtract(kw,'headers_*',false,true);objectUpdate(gnrwdg.headers_footers_kw,objectExtract(kw,'footers_*',false,true));if(!columns){columns='^#WORKSPACE.columns';sourceNode.registerDynAttr('columns');}
gnrwdg.columns_bag=this._getColumnsBag(sourceNode,columns,subTagItems['column']);var searchColumn=gnrwdg.columns_bag.getNode('#0').attr.field;var checked_attr=objectExtract(kw,'checked_*',true);var hasCheckbox=objectNotEmpty(checked_attr)||kw.onChecked;var defaultKw={autoCollapse:true,hideValues:true,background:'white',searchColumn:searchColumn,_class:hasCheckbox?'treegrid branchtree':'treegrid branchtree noIcon',connect__expandNode:function(){gnrwdg.updateScroll();},labelCb:function(store){return gnrwdg.labelCb(this,store)}};var boxclass=hasCheckbox?'treegridcheckbox treeGridLayout ':'treeGridLayout ';var box=sourceNode._('div',objectUpdate({_class:boxclass+(objectPop(kw,'_class')||''),onCreated:function(){var that=this;this.watch('setWidth',function(){var currentWidth=that.domNode.clientWidth;if(!that._isBuilding&&currentWidth!=gnrwdg.width){gnrwdg.width=currentWidth;gnrwdg.refresh();}},function(){});}},boxpars));gnrwdg.layoutNode=box.getParentNode();if(gnrwdg.headers){gnrwdg.headerNode=box._('div',{_class:'treeGridHeader'}).getParentNode();}
if(gnrwdg.footers){gnrwdg.footerNode=box._('div',{_class:'treeGridFooter'}).getParentNode();}
var center=box._('div',{_class:'treeGridCenter'});gnrwdg.scrollerNode=box._('div',{_class:'treeGridScroller'}).getParentNode();var tree=center._('tree',objectUpdate(defaultKw,kw));gnrwdg.centerNode=center.getParentNode();gnrwdg.treeNode=tree.getParentNode();gnrwdg.absStorepath=gnrwdg.treeNode.absDatapath(kw.storepath);gnrwdg.treeNode.componentHandler=gnrwdg;return tree},gnrwdg_footersHeadersHandler:function(w){var ws=w+'s';if(this[ws]){this[w+'Node'].domNode.innerHTML=null;var hf=this[ws]==true?['']:this[ws].split(',');var that=this;hf.forEach(function(h){var pars=objectExtract(that.headers_footers_kw,h?ws+'_'+h+'_*':ws+'_*',true);that.setHeaderFooter(h?w+'_'+h:w,pars,w);});}},gnrwdg_refresh:function(){var that=this;this.mainCellSize=parseInt(this.columns_bag.getAttr('#0').size);if(!this.mainCellSize){var otherSize=0;this.columns_bag.getNodes().slice(1).forEach(n=>otherSize+=parseInt(n.attr.size));this.mainCellSize=Math.max((this.centerNode.domNode.clientWidth-70-otherSize),200);}
this.treeNode.widget.updateLabels();this.footersHeadersHandler('header');this.footersHeadersHandler('footer');this.centerNode.domNode.style.top=this.headerNode?this.headerNode.domNode.clientHeight+1+'px':'0px';this.centerNode.domNode.style.bottom=this.footerNode?this.footerNode.domNode.clientHeight+1+'px':'0px';this.currentScroll=0;this.setScroller();setTimeout(function(){that.updateScroll();},1);},gnrwdg_setScroller:function(){this.scrollerNode._value.popNode('viewport');var layoutDomNode=this.layoutNode.domNode;var gnrwdg=this;var viewport=this.scrollerNode._('div','viewport',{position:'absolute',right:0,bottom:0,top:0,width:this.viewPortWidth+'px',overflow:'auto',connect_onscroll:function(evt){gnrwdg.currentScroll=evt.target.scrollLeft;gnrwdg.updateScroll();}});viewport._('div',{height:'2px',width:this.cellsWidth+'px'})},gnrwdg_updateScroll:function(){var that=this;dojo.query('.treeerow_viewport',this.layoutNode.domNode).forEach(function(n){n.style.overflow='scroll'
n.scrollLeft=that.currentScroll;n.style.overflow='hidden'});},htmlCellContent:function(content,cell){if(content&&content.attr){content=cell.contentCb?funcApply(cell.contentCb,{field:cell['field']},content):content.attr[cell['field']];}
content=content||cell.emptyValue;var format=cell['format'];var dtype=cell['dtype']||'T';content=_F(content,format,dtype)||'&nbsp;';return'<div class="treeCellContent">'+content+'</div>'},gnrwdg_setHeaderFooter:function(contentKey,pars,mode){if(!this.width){return;}
if(pars.hidden){return}
var columns_bag=this.columns_bag;var mainCell=columns_bag.getAttr('#0');mainCell=this.sourceNode.evaluateOnNode(mainCell);var maxwidth=this.width;var currx=0;var cell;var l=[];var htmlCellContent=this.gnr.htmlCellContent;var n;var sn=this.sourceNode;var colkeys=this.columns_bag.keys().slice(1);var tplpars={};var mainCellSize=this.mainCellSize+21;var colswidth=maxwidth-this.mainCellSize-35;var customKw,cellstyle,objStyle,conten,sizet;colkeys.forEach(function(key){n=columns_bag.getNode(key);cell=sn.evaluateOnNode(n.attr);objectUpdate(cell,pars);customKw=objectExtract(cell,contentKey+'_*');objectExtract(cell,'dtype,format,style,cellClass');objectUpdate(cell,customKw);if(!cell.hidden){size=parseInt(cell.size);if(stringEndsWith((size+''),'%')){size=Math.round(maxwidth*parseInt(size)/100)}
objStyle=objectUpdate(objectFromStyle(cell._style),sn.evaluateOnNode(genro.dom.getStyleDict(objectUpdate({},cell),['width'])))
objStyle['width']=size+'px'
cellstyle=objectAsStyle(objStyle)
content=cell[contentKey];cell.dtype=cell.dtype||guessDtype(content);l.push('<div class="treecell cell_'+(cell.dtype||'T')+' '+(cell.cellClass||'')+' " style="'+cellstyle+'">'+htmlCellContent(content,cell)+'</div>');currx+=size+1||0;}})
var storeNode=genro.getDataNode(this.absStorepath);var rowwidth=maxwidth;objectExtract(mainCell,'dtype,format,style,cellClass');objectUpdate(mainCell,pars);customKw=objectExtract(mainCell,contentKey+'_*');objectUpdate(mainCell,customKw);objStyle=objectUpdate(objectFromStyle(mainCell._style),sn.evaluateOnNode(genro.dom.getStyleDict(objectUpdate({},mainCell),['width'])))
objStyle['width']=mainCellSize+'px';objStyle['overflow']='hidden';cellstyle=objectAsStyle(objStyle)
this.cellsWidth=currx;this.viewPortWidth=colswidth;tplpars['maincell']='<div class="treecell maincell'+(mainCell.cellClass||'')+' " style="'+cellstyle+'"><div class="treeCellContent">'+(mainCell[contentKey]||'&nbsp;')+'</div></div>';tplpars['columns']='<div class="treeerow_viewport" style="width:'+colswidth+'px;"><div class="treerow_columns" style="width:'+(currx+1)+'px;">'+l.join('')+'</div></div>'
var elem=document.createElement('div');elem.innerHTML=dataTemplate('<div class="treerow treerow_'+mode+'" style="width:'+rowwidth+'px;">$maincell $columns</div>',tplpars);this[mode+'Node'].domNode.appendChild(elem.removeChild(elem.firstChild));},gnrwdg_labelCb:function(item,store){if(!this.width){return;}
var k=10;var mainLabel=item.label;var columns_bag=this.columns_bag;var mainCell=columns_bag.getAttr('#0');var maxwidth=this.width-35;var colswidth=maxwidth-this.mainCellSize;var currx=0;var cell;var l=[];var htmlCellContent=this.gnr.htmlCellContent;var n;var sn=this.sourceNode;var colkeys=this.columns_bag.keys().slice(1);var tplpars={};colkeys.forEach(function(key){n=columns_bag.getNode(key);cell=sn.evaluateOnNode(n.attr);if(!cell.hidden){var size=parseInt(cell.size);if(stringEndsWith((size+''),'%')){size=Math.round(maxwidth*parseInt(size)/100)}
var objStyle=objectUpdate(objectFromStyle(cell._style),sn.evaluateOnNode(genro.dom.getStyleDict(objectUpdate({},cell),['width'])))
objStyle['width']=size+'px'
var cellstyle=objectAsStyle(objStyle)
l.push('<div class="treecell cell_'+(cell.dtype||'T')+' '+(cell.cellClass||'')+' " style="'+cellstyle+'">'+htmlCellContent(item,cell)+'</div>');currx+=size+1||0;}})
var storeNode=genro.getDataNode(this.absStorepath);var level=(item.parentshipLevel(storeNode)-1);var folder=store.hasAttribute(item,'#v')?' treerow_folder ':'';var rowwidth=maxwidth-level*k;var objStyle=objectUpdate(objectFromStyle(mainCell._style),sn.evaluateOnNode(genro.dom.getStyleDict(objectUpdate({},mainCell),['width'])))
objStyle['width']=(this.mainCellSize-level*k)+'px';objStyle['overflow']='hidden';var cellstyle=objectAsStyle(objStyle)
this.cellsWidth=currx;this.viewPortWidth=colswidth;tplpars['maincell']='<div class="treecell maincell cell_'+(mainCell.dtype||'T')+' '+(mainCell.cellClass||'')+' " style="'+cellstyle+'">'+htmlCellContent(item,mainCell)+'</div>';tplpars['columns']='<div class="treeerow_viewport" style="width:'+colswidth+'px;"><div class="treerow_columns" style="width:'+currx+'px;">'+l.join('')+'</div></div>'
return dataTemplate('innerHTML:<div class="treerow treerow_level_'+level+folder+'">$maincell $columns</div>',tplpars)},_getColumnsBag:function(sourceNode,columns,childrenColumns){var columns_bag=sourceNode.getRelativeData(columns)||new gnr.GnrBag();;childrenColumns.forEach(function(n){var attr=n.attr;attr.field=attr.field||n.label;columns_bag.setItem(attr.field,null,attr);})
return columns_bag;}});dojo.declare("gnr.widgets.VideoPlayer",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var frameKw=objectExtract(kw,'height,width,region,title,border,splitter,_class,style,frameCode,datapath,rounded');var subtitlePane=objectPop(kw,'subtitlePane');frameKw.frameCode=frameKw.frameCode||'videoplayer_'+genro.getCounter();var frame=sourceNode._('FramePane',frameKw);var slots=objectPop(kw,'slots');var manageCue=objectPop(kw,'manageCue');var controllerSide=objectPop(kw,'controllerSide')||'top';var center=frame._('BorderContainer',{side:'center',connect_resize:function(){var minH=30;var maxH=100;var bcdn=this.widget.domNode;var top=this.widget._top;var centerDN=this.widget._center;var video=top.children[0];var subH=bcdn.clientHeight-top.clientHeight;if(subH<(minH-3)){var topH=(bcdn.clientHeight-minH);video.style.height=topH+'px';video.style.width=null;}else if(top.clientWidth<video.clientWidth){video.style.height=null;video.style.width='100%';}else if(subH>maxH){video.style.height=null;video.style.width='100%';}}});var gnrwdg=sourceNode.gnrwdg;kw.src='^.videoSrc';kw.currentTime='^.currentTime';kw.playing='.playing';kw.width=kw.video_width||'100%';kw.border=kw.video_border||0;var urlPars=objectExtract(kw,'url,timerange');gnrwdg.urlPars=urlPars;kw.connect_loadedmetadata=function(){gnrwdg.onLoadedVideo(this);this.getParentNode().getParentNode().widget.layout()}
sourceNode.attr.videoCurrentTime=kw.currentTime
if(frameKw.frameCode&&!kw.nodeId){kw.nodeId=frameKw.frameCode+'_video';}
gnrwdg.videoNodeId=kw.nodeId;center._('dataFormula',{path:'.videoSrc',formula:"url?genro.addParamsToUrl(url,{'#t':timerange}):null;",url:urlPars.url,timerange:urlPars.timerange,_onBuilt:true,_delay:1});center._('dataFormula',{path:'.playerTime',formula:"currentTime-(range_start||0)",currentTime:'^.currentTime',range_start:'=.range_start',_if:'_triggerpars.kw.reason=="player" && !editingPlayerSearch',editingPlayerSearch:'=.editingPlayerSearch'});center._('dataController',{script:"var currentTime = playerTime+range_start; if(currentTime>=range_end){ FIRE .resetPlayer;}else{ SET .currentTime=currentTime;}",playerTime:'^.playerTime',range_start:'=.range_start',range_end:'=.range_end'});center._('dataController',{script:'genro.domById(videoNodeId).pause(); SET .playerTime = 0;',_fired:'^.resetPlayer',videoNodeId:gnrwdg.videoNodeId})
var video=center._('ContentPane',{region:'top',overflow:'hidden'})._('video','video',kw);if(subtitlePane){var subpane=center._('ContentPane',{region:'center',min_height:'100px'})._('div',{innerHTML:'^.mainsub.text'});gnrwdg.subtitleNode=subpane.getParentNode();}
gnrwdg.preparePlayerBar(frame,slots,manageCue,controllerSide);return video;},gnrwdg_onLoadedVideo:function(videoSourceNode){var videoDomNode=videoSourceNode.domNode;var videoDuration=Math.round(videoDomNode.duration*10)/10;var playerDuration=videoDuration;var sn=this.sourceNode;sn.setRelativeData('.duration',videoDuration);var urlPars=sn.evaluateOnNode(this.urlPars);var timerange=urlPars.timerange;if(timerange){var r=timerange.split(',').map(function(n){return parseInt(n)});sn.setRelativeData('.range_start',r[0]);sn.setRelativeData('.range_end',r[1]);playerDuration=Math.round((r[1]-r[0])*10)/10;}else{sn.setRelativeData('.range_start',0);sn.setRelativeData('.range_end',playerDuration);}
sn.setRelativeData('.playerTime',0);sn.setRelativeData('.playerDuration',playerDuration);},gnrwdg_preparePlayerBar:function(frame,slots,manageCue,controllerSide){slots=slots||'10,playbutton,playerslider,searchBox,*'
if(manageCue){slots=slots+',cuebutton,10';}
var bar=frame._('SlotBar','bar',{slots:slots,side:controllerSide,height:'21px',toolbar:true,playerslider_width:'100%'});var slotsKw={};var videoNodeId=this.videoNodeId;slotsKw.playbutton={tag:'slotButton',label:'==_playing?"Pause":"Play"',action:function(){var kw=arguments[arguments.length-1]
var _video=genro.domById(kw._videoNodeId);if(kw._playing){_video.pause()}else{_video.play()};},_playing:'^.playing',iconClass:'==_playing?"player_pause":"player_play"',_videoNodeId:this.videoNodeId};slotsKw.playerslider={tag:'horizontalSlider',value:'^.playerTime',minimum:0,maximum:'^.playerDuration',intermediateChanges:false,width:'100%',parentForm:false};slotsKw.searchBox='videoSearchBox';slotsKw.cuebutton={tag:'slotButton',label:"==_start_time?'Make cue':'Start cue';",_start_time:'^.start_time',iconClass:'==_start_time? "iconbox comment_check":"iconbox comment_plus"',action:function(){var start_time=this.getRelativeData('.start_time');var currentTime=this.getRelativeData('.currentTime');var video=genro.domById(videoNodeId);if(start_time){video.pause();this.setRelativeData('.start_time',null);video.sourceNode.publish('addCue',{start_time:start_time,end_time:currentTime});}else{if(!this.getRelativeData('.playing')){video.play();}
this.setRelativeData('.start_time',currentTime);}}};var that=this;slots.split(',').forEach(function(s){if(s in slotsKw){var handler=slotsKw[s];if(typeof(handler)=='string'){that[handler](bar,s);}else{var skw=objectUpdate({},handler);var tag=objectPop(skw,'tag');bar._(tag,s,skw);}}});},gnrwdg_videoSearchBox:function(bar,slotName){var sb=bar._('div',slotName)
var fb=genro.dev.formbuilder(sb,1,{border_spacing:'1px',font_size:'.9em'});var videoNodeId=this.videoNodeId;var that=this;fb.addField('callbackSelect',{value:'^.playerTime',width:'6em',lbl_text_align:'right',lbl:_T('Search'),lbl_color:'#444',rounded:6,parentForm:false,validate_onAccept:function(){this.widget.focusNode.blur();},auxColumns:'start,end',_class:'numberTextBox',connect_onFocus:function(){this.setRelativeData('.editingPlayerSearch',true);},connect__onBlur:function(){this.setRelativeData('.editingPlayerSearch',false);},callback:function(kw){var _id=kw._id;var _querystring=kw._querystring;var videoDomNode=genro.domById(videoNodeId);var sn=videoDomNode.sourceNode;var currentTextTrack=sn.getAttributeFromDatasource('searchTrack')||0;var cues=videoDomNode.textTracks[currentTextTrack].cues;var range_start=sn.getRelativeData('.range_start');var range_end=sn.getRelativeData('.range_end');var data=[];if(_querystring){_querystring=_querystring.slice(0,-1).toLowerCase();if(parseFloat(_querystring)>=0){_id=parseFloat(_querystring);_querystring=null;}}
if(_querystring){dojo.forEach(cues,function(c){if(c.startTime<range_start||c.startTime>range_end){return;}
var start_offset=r[0]||0;var startTime=c.startTime-start_offset;var endTime=c.endTime-start_offset;if(c.text.indexOf(_querystring)>=0){data.push({txt:c.text,_pkey:startTime,start:startTime,end:endTime,caption:_F(startTime,'###.00')})}})}else if(_id){data=[{_pkey:_id,caption:_F(_id,'###.00'),start:_id,endTime:_id,txt:_F(_id,'###.00')}];}
return{data:data,headers:'txt:Text,start:Start,end:End'}}});}});dojo.declare("gnr.widgets.GridGallery",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var grid_pars=objectExtract(kw,'items,columns');grid_pars.selfDragRows=genro.isDeveloper;objectUpdate(grid_pars,objectExtract(kw,'grid_*'));var onContentSaved=objectPop(kw,'onSaved');var items=objectPop(grid_pars,'items');var docpars=objectExtract(kw,'di_*');var navigation=objectPop(kw,'navigation');var sharedObjectId=objectPop(kw,'sharedObjectId');if(!items&&objectNotEmpty(docpars)){items='^gnr.language?=#v?"_doc.content.'+docpars.store+'.'+docpars.key+'.'+docpars.contentpath+'."+#v:"emptypath"';}
if(onContentSaved){onContentSaved=funcCreate(onContentSaved);}else{onContentSaved=function(){sourceNode.publish('onContentSaved');}}
var viewer_pars=objectExtract(kw,'viewer_*');var itemspath=sourceNode.absDatapath(items);var grid_region=grid_pars.region||'left';var gnrwdg=sourceNode.gnrwdg;kw.selfsubscribe_toggle_grid=function(){this.widget.setRegionVisible(grid_region,'toggle');}
kw.selfsubscribe_next=function(){var next_idx=this.getRelativeData('#WORKSPACE.selectedIndex')+1;var tot=this.getRelativeData('#WORKSPACE.total_pages')-1;next_idx=(next_idx>=tot)?tot:next_idx;this.setRelativeData('#WORKSPACE.selectedIndex',next_idx);}
kw.selfsubscribe_prev=function(){var prev_idx=this.getRelativeData('#WORKSPACE.selectedIndex')-1;this.setRelativeData('#WORKSPACE.selectedIndex',prev_idx>=0?prev_idx:0);}
kw.selfsubscribe_zoom=function(){var s=gnrwdg.viewerBC.widget.setRegionVisible('top','toggle');var dn=gnrwdg.iframecontainerNode.domNode;genro.dom.setClass(gnrwdg.iframecontainerNode,'expanded_gallery_iframe',!s);if(s===false){gnrwdg.iframecontainerNode._zoomed=true;dojo.body().appendChild(dn);}else{gnrwdg.iframecontainerNode._zoomed=false;gnrwdg.centerframeNode.widget.domNode.appendChild(dn);}}
var showcase=objectPop(kw,'showcase');if(sourceNode.isPointerPath(items)){grid_pars.dynamicStorepath=itemspath;}else{grid_pars.value=itemspath;}
grid_pars.autoSelect=true;grid_pars['store_sortedBy']='_row_count';kw._workspace=true;kw.design=kw.design||'sidebar';if(showcase){kw._class=(kw._class||'')+' showcase_'+(showcase==true?'light':showcase);}
var bc=sourceNode._('BorderContainer',kw);var rootnode=bc.getParentNode();rootnode._('dataFormula',{path:'#WORKSPACE.total_pages',formula:'typeof(v)=="string"?(this.getRelativeData(v)?this.getRelativeData(v).len():0):(v?v.len():0)',v:'^'+itemspath});if(showcase&&sharedObjectId&&genro.wsk.wsroot){sourceNode._('SharedObject',{shared_id:sharedObjectId,shared_path:'showcase_remote',expire:60});rootnode._('dataFormula',{path:'showcase_remote',script:"new gnr.GnrBag({slide_index:slide_index,minutes:minutes,comment:comment,total_pages:total_pages,zoomEnabled:zoomEnabled,current_time:current_time,started:started});",slide_index:'^#WORKSPACE.selectedIndex',minutes:'=#WORKSPACE.minutes',comment:'=#WORKSPACE.comment',total_pages:'=#WORKSPACE.total_pages',zoomEnabled:'=#WORKSPACE.iframe_src?=#v?true:false',current_time:'=showcase_remote.current_time',started:'=showcase_remote.started',_delay:1});rootnode._('dataController',{script:"this.getParentNode().publish(command);",command:'^showcase_remote.command',_userChanges:true});}
if(showcase){bar=bc._('ContentPane',{region:'bottom',_class:'showcase_bar'})._('slotBar',{slots:'5,toggle,15,prev,5,next,*,slide_cnt,2',side:'bottom'});bar._('lightbutton','toggle',{tip:_T('!!Toggle'),action:function(){rootnode.publish('toggle_grid');},_class:'showcase_button showcase_toggle'});bar._('lightbutton','prev',{tip:_T('!!Prev'),action:function(){rootnode.publish('prev');},_class:'showcase_button showcase_prev'});bar._('lightbutton','next',{tip:_T('!!Next'),action:function(){rootnode.publish('next');},_class:'showcase_button showcase_next'});bar._('div','slide_cnt',{template:"$_curr/$_tot ($_minutes)",_curr:"^#WORKSPACE.selectedIndex?=#v+1",_tot:'^#WORKSPACE.total_pages',_minutes:'^#WORKSPACE.minutes?=#v?#v:"..."',width:'6em',_class:'showcase_counter'});grid_pars.hidden=true;}
var dpath=rootnode.absDatapath('#WORKSPACE.curr_datapath');var emptypath=rootnode.absDatapath('#WORKSPACE.emptypath');sourceNode.setRelativeData(dpath,emptypath);grid_pars.connect_onSelected=function(rowIndex){if(rowIndex>=0&&this.widget.storebag().len()>0){this.setRelativeData(dpath,this.widget.collectionStore().itemByIdx(rowIndex).getFullpath().slice(5));setTimeout(function(){gnrwdg.viewerBC.widget.resize();},1)}}
grid_pars.selected_minutes=rootnode.absDatapath('#WORKSPACE.minutes');grid_pars.selected_comment=rootnode.absDatapath('#WORKSPACE.comment');grid_pars.selected_iframe_src=rootnode.absDatapath('#WORKSPACE.iframe_src');grid_pars.selectedIndex='^'+rootnode.absDatapath('#WORKSPACE.selectedIndex');grid_pars.selfsubscribe_addrow=function(addkw){var grid=this.widget;setTimeout(function(){gnrwdg.addNewPage(grid,addkw);},500);}
var gridpane_kw=objectExtract(grid_pars,'width,_class,drawer,hidden');gridpane_kw._class=showcase?'grid_gallery_grid_showcase':'grid_gallery_grid noheader';objectUpdate(gridpane_kw,objectExtract(grid_pars,'drawer_*'));var gp=bc._('ContentPane','gridpane',objectUpdate({region:'left'},gridpane_kw))
var g=gp._('quickGrid','grid',grid_pars);if(genro.isDeveloper){g._('tools',{tools:'delrow,addrow',custom_tools:{addrow:{content_class:'iconbox add_row',ask:{title:_T('New Page'),fields:[{name:'label',lbl:'Label',validate_notnull:true},{name:'iframe_src',lbl:'Src'}]}}},position:'BR'});g._('column',{field:'_row_count',counter:true,hidden:!showcase,name:'N.',width:'3em'});g._('column',{field:'label',name:'Label',width:'100%',edit:true});if(showcase){g._('column',{field:'minutes',name:'Min',width:'4em',dtype:'L',edit:true});}}else{g._('column',{field:'_row_count',counter:true,hidden:true})
g._('column',{field:'label',name:'Label',width:'100%'});}
var content_kw=objectExtract(kw,'content_*');content_kw.innerHTML='^.content';content_kw._class='doc_item selectable '+(content_kw._class||'');content_kw.min_height='30px';content_kw.stlyes='^.';if(genro.isDeveloper){content_kw.connect_ondblclick=function(){var that=this;genro.dlg.prompt(_T('Edit'),{dlg_noModal:true,widget:function(pane){var tc=pane._('tabContainer',{height:'600px',width:'1000px',margin:'2px'});tc._('ContentPane',{title:'Content',overflow:'hidden'})._('ckeditor',{value:'^.content'});var pane=tc._('ContentPane',{title:'Metadata',overflow:'hidden'})
var fb=genro.dev.formbuilder(pane._('div',{margin:'10px'}),3,{border_spacing:'1px',width:'100%',margin_bottom:'12px'});fb.addField('textbox',{value:'^.iframe_src',width:'25em',lbl_text_align:'right',lbl:_T('Example src'),lbl_color:'#444',parentForm:false,colspan:3});fb.addField('numberTextBox',{value:'^.scale_min',width:'6em',lbl_text_align:'right',lbl:_T('Scale min'),lbl_color:'#444',parentForm:false});fb.addField('numberTextBox',{value:'^.scale_max',width:'6em',lbl_text_align:'right',lbl:_T('Scale max'),lbl_color:'#444',parentForm:false});fb.addField('numberTextBox',{value:'^.minutes',width:'6em',lbl_text_align:'right',lbl:_T('Minutes'),lbl_color:'#444',parentForm:false});fb.addField('SimpleTextArea',{value:'^.comment',width:'40em',height:'450px',lbl_text_align:'right',lbl:_T('Comment'),lbl_color:'#444',parentForm:false,lbl_vertical_align:'top',colspan:3});tc._('ContentPane',{title:'HTML Source',overflow:'hidden'})._('codemirror',{value:'^.content',config_mode:'htmlmixed',height:'100%',config_lineNumbers:true});tc._('ContentPane',{title:'Content Styles',overflow:'hidden'})._('codemirror',{value:'^.content_styles',config_mode:'css',config_lineNumbers:true,height:'100%'});},action:function(value){that.setRelativeData('.content',value.getItem('content'));that.setRelativeData('.comment',value.getItem('comment'));that.setRelativeData('.minutes',value.getItem('minutes'));that.setRelativeData('.scale_min',value.getItem('scale_min'));that.setRelativeData('.scale_max',value.getItem('scale_max'));that.setRelativeData('.content_styles',value.getItem('content_styles'));that.setRelativeData('.iframe_src',value.getItem('iframe_src'));onContentSaved();},dflt:this.getRelativeData().deepCopy()});}}
var viewer=bc._('BorderContainer',objectUpdate({region:'center',_class:'grid_gallery_box',datapath:'^'+dpath},viewer_pars))
sourceNode.gnrwdg.viewerBC=viewer.getParentNode();content_kw.overflow='auto';content_kw.style='^.content_styles';var vtop=viewer._('ContentPane',{region:'top'})
vtop._('div',content_kw);centerframe=viewer._('ContentPane',{region:'center',overflow:'hidden'});var iframecontainer=centerframe._('div',{_class:'gallery_iframe_container',hidden:'^.iframe_src?=!#v'});var iframe=iframecontainer._('iframe',{src:'^.iframe_src',height:'100%',width:'100%',border:0,onLoad:function(){var smax=gnrwdg.viewerBC.getRelativeData('.scale_max');var smin=gnrwdg.viewerBC.getRelativeData('.scale_min');this.contentDocument.body.style.zoom=this.parentNode.sourceNode._zoomed?(smax||null):(smin||null);}});gnrwdg.iframecontainerNode=iframecontainer.getParentNode();gnrwdg.iframeNode=iframe.getParentNode();gnrwdg.centerframeNode=centerframe.getParentNode();iframecontainer._('div',{position:'absolute',_class:'iconbox resize',position:'absolute',top:'2px',right:'2px',z_index:2,connect_onclick:function(){rootnode.publish('zoom');},hidden:'^.iframe_src?=!#v'})
return bc;},gnrwdg_addNewPage:function(grid,kw){var label=kw.label;var iframe_src=kw.iframe_src;var dtype=kw.dtype;if(!label){genro.dlg.floatingMessage(this.containerNode,{messageType:'error',message:'Missing Label'})
return;}
grid.addRows([{'label':label,iframe_src:iframe_src}]);}});dojo.declare("gnr.widgets.BagField",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children,subTagItems){value=objectPop(kw,'value')
var valuepath=value?sourceNode.absDatapath(value):null;kw.remote_field=objectPop(kw,'field')||valuepath.split('.').slice(-1)[0];kw.remote_resource=objectPop(kw,'resource');kw.remote_table=objectPop(kw,'table');kw.remote_bfhandler=objectPop(kw,'bfhandler');kw.remote_version=objectPop(kw,'version');if(kw.remote_resource){kw.remote__if='resource'}
kw.remote_valuepath=valuepath;kw.overflow='hidden';kw.remote='bagFieldDispatcher'
kw.min_height=kw.min_height||'1px';kw.min_width=kw.min_width||'1px';kw.remote_async=true;kw.remote__waitingMessage=true;var root=sourceNode;if(genro.isDeveloper){root=sourceNode._('tabContainer');kw.pageName='view';kw.title='View';kw.remote__onRemote="this.setRelativeData('.$_source',this._value.getNode('#0').attr.bagfieldmodule)"}
var result=root._('contentPane','bagFieldRemote',kw);if(genro.isDeveloper){root._('contentPane',{pageName:'edit',title:'Edit',overflow:'hidden'})._('codeEditor',{'value':'^.$_source',height:'100%',readOnly:false});}
return result;}});dojo.declare("gnr.widgets.QuickGrid",gnr.widgets.gnrwdg,{subtags:{column:true,selectionstore:true,tools:true},createContent:function(sourceNode,kw,children,subTagItems){objectPop(kw,'_workspace')
sourceNode.attr._workspace=kw.nodeId||true;var gnrwdg=sourceNode.gnrwdg;var value=objectPop(kw,'value');var dynamicStorepath=objectPop(kw,'dynamicStorepath');var columns=objectPop(kw,'columns');sourceNode.attr.fields=objectPop(kw,'fields');gnrwdg.guessColumns=sourceNode.attr.fields;gnrwdg.infoInCellAttributes=objectPop(kw,'infoInCellAttributes');if(!columns){columns='^#WORKSPACE.columns';sourceNode.registerDynAttr('columns');}
sourceNode.attr.columns=columns;var columns_bag=this._getColumnsBag(sourceNode,columns,subTagItems['column']);if(columns_bag.len()==0){gnrwdg.guessColumns=gnrwdg.guessColumns||'*';}
if(gnrwdg.guessColumns){gnrwdg.columns_extra={};columns_bag.forEach(function(n){gnrwdg.columns_extra[n.attr.field]=n.attr;});columns_bag=new gnr.GnrBag();}
sourceNode.setAttributeInDatasource('columns',columns_bag);var default_kwargs=objectExtract(kw,'default_*');if(default_kwargs){kw.gridEditorPars={default_kwargs:function(){return sourceNode.evaluateOnNode(default_kwargs);}};}
var selected_kwargs=objectExtract(kw,'selected_*',true,true);if(kw.selectedId){kw.selectedId=sourceNode.absDatapath(kw.selectedId);}
for(var k in selected_kwargs){selected_kwargs[k]=sourceNode.absDatapath(selected_kwargs[k])}
objectUpdate(kw,selected_kwargs);var valuepath=value?sourceNode.absDatapath(value):null;dynamicStorepath=dynamicStorepath?'^'+sourceNode.absDatapath(dynamicStorepath):null;var store_kwargs=objectExtract(kw,'store_*');kw.nodeId=kw.nodeId||'_qg_'+genro.getCounter();kw.store=kw.nodeId;kw.datamode=kw.datamode||'bag';kw.structpath=kw.structpath||'#WORKSPACE.struct';kw.controllerPath='#WORKSPACE.controllers';kw.frameTarget=kw.frameTarget===false?false:true;kw.selfsubscribe_addrow=kw.selfsubscribe_addrow||'$1 = $1 || {}; this.widget.addRows($1._askResult? [$1._askResult]:$1._counter,$1.evt);';kw.selfsubscribe_delrow=kw.selfsubscribe_delrow||'this.widget.deleteSelectedRows();';kw.selfsubscribe_export=kw.selfsubscribe_export||function(kwargs){this.widget.serverAction({command:"export",opt:{rawData:true,export_mode:kwargs.export_mode,downloadAs:kwargs.downloadAs||'export_'+genro.getCounter()}});};kw.selfsubscribe_duprow=kw.selfsubscribe_duprow||'this.widget.addRows($1._counter,$1.evt,true);';var currentValue=sourceNode.getAttributeFromDatasource('value');var currentColumns=sourceNode.getAttributeFromDatasource('columns');var struct=new gnr.GnrBag();sourceNode.setRelativeData(kw.structpath,struct)
if(dynamicStorepath){kw.dynamicStorepath=dynamicStorepath;valuepath='.dummystore';}
sourceNode._('BagStore',objectUpdate({storepath:valuepath,nodeId:kw.nodeId+'_store',datapath:kw.controllerPath,storeType:kw.datamode=='bag'?'ValuesBagRows':'AttributesBagRows'},store_kwargs));var tools=subTagItems.tools;var gridRoot=tools.len()?this.toolsGridRoot(sourceNode,kw,tools.getAttr('#0')):sourceNode;kw.datapath=kw.controllerPath;kw.gridplugins=false;var grid=gridRoot._('newIncludedView',kw);gnrwdg.gridNode=grid.getParentNode();gnrwdg.setColumns(sourceNode.getRelativeData(columns));return grid;},_getColumnsBag:function(sourceNode,columns,childrenColumns){var columns_bag=sourceNode.getRelativeData(columns)||new gnr.GnrBag();;childrenColumns.forEach(function(n){var attr=n.attr;attr.field=attr.field||n.label;columns_bag.setItem(attr.field,null,attr);})
return columns_bag;},toolsGridRoot:function(sourceNode,kw,tools_kw){var tools=objectPop(tools_kw,'tools');tools_kw=tools_kw||{};var tools_bar_class,container_class;var centerkw={region:'center',border:objectPop(kw,'border'),overflow:'hidden'};if(tools_kw.title){tools_bar_class='slotbar_toolbar_standard';tools_kw.position='TR';centerkw.border_top='1px solid silver';}
var bckw={height:objectPop(kw,'height'),width:objectPop(kw,'width'),_class:'quickgrid_container'}
objectUpdate(tools_kw,objectExtract(kw,'tools_*'));var custom_tools=objectPop(tools_kw,'custom_tools');var default_tools={'addrow':{content_class:'iconbox add_row',_delay:500},'delrow':{content_class:'iconbox delete_row'},'duprow':{content_class:'iconbox copy'},'export':{content_class:'iconbox export',export_mode:'xls',downloadAs:'',localized_data:true,ask:{title:'Export selection',skipOn:'Shift',fields:[{name:'downloadAs',lbl:'Download as'},{name:'allRows',label:'All rows',wdg:'checkbox'},{name:'export_mode',wdg:'filteringSelect',values:'xls:Excel,csv:CSV',lbl:'Mode'},{name:'localized_data',wdg:'checkbox',label:'Localized data'}]}}}
if(custom_tools){objectUpdate(default_tools,custom_tools);}
tools=tools==true?'addrow,delrow':tools;var tools_position=objectPop(tools_kw,'position')||'TR';var tool_region=(tools_position[0]=='T')?'top':'bottom';var bc=sourceNode._('borderContainer',bckw);var tpane=bc._('contentPane',{region:tool_region,height:'22px',overflow:'hidden',datapath:'#WORKSPACE.tools',_class:tools_bar_class});if(tools_kw.title){tpane._('div',{innerHTML:tools_kw.title,position:'absolute',left:'5px',top:'3px',font_weight:'bold',font_size:'.9em',color:'#444'});}
var posdict={'TR':{right:'0',_class:'quickgrid_toolsbox_top quickgrid_toolsbox'},'TL':{left:'0',_class:'quickgrid_toolsbox_top quickgrid_toolsbox'},'BR':{right:'0',_class:'quickgrid_toolsbox_bottom quickgrid_toolsbox'},'BL':{left:'0',_class:'quickgrid_toolsbox_bottom quickgrid_toolsbox'}}
var mb=tpane._('div',objectUpdate(posdict[tools_position],{position:'absolute'}))._('multibutton',{value:'^.command',sticky:false});tools.split(',').forEach(function(t){mb._('item',t,default_tools[t]);});tpane._('datacontroller',{script:"genro.publish({topic:value.action,nodeId:target},value)",value:'^.command',target:kw.nodeId})
return bc._('contentPane',centerkw)},gnrwdg_guessDtypeAndWidth:function(rows,fields){var types={}
var sizes={}
var w,dtype,v
if(!rows||rows.len()==0){return{types:null,sizes:null};}
var store=this.gridNode.widget.collectionStore();if(!fields||fields=='*'){var firstNode=store.getData().getNode('#0');var nodeValue=firstNode.getValue();fields=nodeValue?nodeValue.keys():objectKeys(firstNode.attr);}else{fields=fields.split(',');}
var infoInCellAttributes=this.infoInCellAttributes;var columns_extra=this.columns_extra||{};rows.forEach(function(n){var r=store.rowFromItem(n);fields.forEach(function(field){var v=r[field];if(!(field in types)){types[field]=null
sizes[field]=0
if(infoInCellAttributes){columns_extra[field]=n.getValue().getAttr(field);}}
if(!isNullOrBlank(v)){dtype=types[field]
if(!dtype){dtype=guessDtype(v)
types[field]=dtype;}
w=8
if(dtype=='D'){w=8}
else if(dtype=='H'){w=6}
else if(dtype=='DH'){w=12}
if((dtype=='T')||(dtype=='N')||(dtype=='L')){sizes[field]=Math.max(sizes[field]||field.length,v.toString().length)}
else if(sizes[field]==0){w=8;if(dtype=='D'){w=8}
else if(dtype=='H'){w=6}
else if(dtype=='DH'){w=12}
sizes[field]=Math.max(field.length,w)}}})})
for(var t in types){if(!types[t]){types[t]='T'}
sizes[t]=(2+(sizes[t]||8)*.5)+'em'}
if(objectNotEmpty(columns_extra)){this.columns_extra=columns_extra;}
return{types:types,sizes:sizes}},gnrwdg_setFields:function(fields){var columns=this.getColumnsFromValue(this.gridNode.widget.storebag());this.setColumns(columns);},gnrwdg_getColumnsFromValue:function(value){var columns=new gnr.GnrBag();var columns_extra=this.columns_extra||{};var fields=this.sourceNode.getAttributeFromDatasource('fields');var guess=this.guessDtypeAndWidth(value,fields);var kw;for(var label in guess.types){kw={'field':label,'dtype':guess.types[label],'width':guess.sizes[label],'name':stringCapitalize(label.replace(/_/g,' '))}
if(label in columns_extra){var customColumn=columns_extra[label];if(customColumn){objectUpdate(kw,customColumn);}}
columns.setItem(label,null,kw);}
return columns;},gnrwdg_catch_column:function(attr,value){this.setColumns(this.getColumnsFromValue(this.gridNode.widget.storebag()));},gnrwdg_setColumns:function(columns){this.gridNode.getRelativeData(this.gridNode.attr.structpath).setItem('view_0.rows_0',columns);},gnrwdg_setValue:function(value,kw,trigger_reason){if((trigger_reason=='container')||(kw.node.parentshipLevel(this.gridNode.widget.storebag().getParentNode())==0)){if(this.guessColumns){this.sourceNode.setRelativeData(this.sourceNode.attr.columns,this.getColumnsFromValue(value));}}}});dojo.declare("gnr.widgets.BagEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;var selectedBranch=kw.selectedBranch||'#WORKSPACE.selectedBranch';var treekw=objectExtract(kw,'storepath,labelAttribute');var barkw=objectExtract(kw,'addrow,delrow,addcol,searchOn,export');sourceNode.attr._workspace=true;objectUpdate(treekw,{hideValues:true,selectedLabelClass:'selectedTreeNode',_class:"branchtree noIcon",autoCollapse:true});objectUpdate(treekw,objectExtract(kw,'tree_*'));treekw.selectedPath=selectedBranch;var that=this;treekw.selfsubscribe_onSelected=function(kw){var rows=this.getRelativeData(this.attr.storepath).getItem(kw.path);that.onSelectedBranch(rows,gnrwdg.gridNode);}
var bc=sourceNode._('BorderContainer');var treepane=bc._('ContentPane',{region:'left',width:objectPop(treekw,'width')||'200px',splitter:true,border_right:'1px solid #efefef',background:'#EBEBEB'})._('div',{position:'absolute',top:'1px',left:'1px',right:'1px',bottom:'1px',overflow:'auto'})
var tree=treepane._('tree',treekw);gnrwdg.treeNode=tree.getParentNode();var frameCode='bagEditor_'+genro.getCounter();var gridId=frameCode+'_grid';var gridframe=bc._('framePane',{frameCode:frameCode,region:'center',target:gridId,margin_left:'4px'});if(objectNotEmpty(barkw)){var slots='*,'+['delrow','addrow','addcol','export','searchOn'].filter(function(n){return n in barkw}).join(',')+',5';var bar=gridframe._('SlotBar',{'side':'top',slots:slots,toolbar:true});if(barkw.delrow){bar._('SlotButton','delrow',{label:_T('Delete row'),publish:'delrow',iconClass:'iconbox delete_row'});}
if(barkw.addrow){bar._('SlotButton','addrow',{label:_T('Add row'),publish:'addrow',iconClass:'iconbox add_row'});}
if(barkw.addcol){bar._('SlotButton','addcol',{label:_T('Add column'),publish:'addcol'});}
if(barkw.export){bar._('SlotButton','export',{iconClass:'iconbox export',opt_export_mode:'xls',opt_downloadAs:'',opt_localized_data:true,publish:'serverAction',command:'export',ask:{title:'Export selection',skipOn:'Shift',fields:[{name:'opt_downloadAs',lbl:'Download as'},{name:'opt_allRows',label:'All rows',wdg:'checkbox'},{name:'opt_export_mode',wdg:'filteringSelect',values:'xls:Excel,csv:CSV',lbl:'Mode'},{name:'opt_localized_data',wdg:'checkbox',label:'Localized data'}]}})}}
var gridkw=objectExtract(kw,'grid_*');gridkw.nodeId=gridId;gridkw.frameCode=frameCode;gridkw.selfDragRows=true;gridkw.datapath='#WORKSPACE.grid';var branchPath=kw.branchPath||'#WORKSPACE.branchBag';gridkw.controllerPath=gridkw.datapath;gridkw.structpath='#WORKSPACE.grid.struct';gridkw.store=frameCode;gridkw.selfsubscribe_delrow=function(){this.widget.deleteSelectedRows();};gridkw.selfsubscribe_addrow=function(){var that=this;genro.dlg.prompt(_T('Add row'),{lbl:'Nodelabel',action:function(result){var b=that.widget.storebag();b.setItem(result,new gnr.GnrBag({nodelabel:result}));}});}
gridkw.selfsubscribe_addcol=function(){var that=this;genro.dlg.prompt(_T('Add col'),{'widget':[{lbl:'name',value:'^.field'},{lbl:'dtype',value:'^.dtype',wdg:'filteringSelect',values:'T:Text,N:Number,B:Boolean'}],action:function(result){var b=genro.getData(that.attrDatapath('structpath'));var kw=result.asDict();kw.name=kw.field;kw.edit=true;b.setItem('#0.#0.cell_'+genro.getCounter(),null,kw);}});}
gridframe._('BagStore',{storepath:branchPath,_identifier:'nodelabel',nodeId:frameCode+'_store'});var grid=gridframe._('newIncludedView',gridkw);gnrwdg.gridNode=grid.getParentNode();sourceNode._('dataController',{'script':"this.getParentNode().gnrwdg.updateBranchBag(branch,_node,_reason,_triggerpars.kw);",branch:'^'+branchPath});return bc;},onSelectedBranch:function(rows,gridNode){var struct=new gnr.GnrBag();var header=new gnr.GnrBag();struct.setItem('view_0.rows_0',header);var store=new gnr.GnrBag();var i=0;var f;header.setItem('cell_0',null,{field:'nodelabel',width:'12em',name:'Node Label'});if(rows&&rows.len&&rows.len()){rows._nodes.forEach(function(n,idx){var attr=objectUpdate({},n.attr);for(var k in attr){f=k.replace(/\W/g,'_');attr[f]=objectPop(attr,k);if(!header.getNodeByAttr('field',f)){header.setItem('cell_'+genro.getCounter(),null,{field:f,width:'10em',name:f,dtype:guessDtype(attr[f]),original_field:k,edit:true});}}
attr.nodelabel=n.label;store.setItem('r_'+idx,new gnr.GnrBag(attr));i++;},'static');}
gridNode.setRelativeData(gridNode.attr.structpath,struct);gridNode.setRelativeData(gridNode.attr.storepath,store);},gnrwdg_updateBranchBag:function(branch,branchNode,reason,kw){var b=this.treeNode.getRelativeData(this.treeNode.attr.storepath).getItem(this.treeNode.getRelativeData(this.treeNode.attr.selectedPath));var nv=branchNode.getValue();if(reason=='child'){if(kw.updvalue){var nl=branchNode.getParentNode().label;var updkw={};updkw[branchNode.label]=kw.value;b.getNode(nl).updAttributes(updkw);}else if(kw.evt=='ins'&&nv instanceof gnr.GnrBag){var pos=branch.index(branchNode.label);b.setItem(branchNode.label,null,nv.asDict(),{_position:pos>=0?pos:null});}else if(kw.evt=='del'&&nv instanceof gnr.GnrBag){b.popNode(branchNode.label);}}}});dojo.declare("gnr.widgets.PagedHtml",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var pagingKw=objectExtract(kw,'sourceText,pagedText,letterheads,extra_bottom,printAction,bodyStyle,editor,datasource,letterhead_id');kw['height']='100%';kw['position']='relative';kw['background']='white';kw['_workspace']=true;var gnrwdg=sourceNode.gnrwdg;gnrwdg.datasource=pagingKw.datasource;gnrwdg.tpl_kwargs=objectExtract(kw,'tpl_*',false,true);gnrwdg.extra_bottom=pagingKw.extra_bottom||10;gnrwdg.pagedTextPath=pagingKw.pagedText.replace('^','');gnrwdg.letterheadsPath=pagingKw.letterheads.replace('^','');gnrwdg.sourceTextPath=pagingKw.sourceText.replace('^','');if(pagingKw.editor){gnrwdg.editorNode=sourceNode.currentFromDatasource(pagingKw.editor);}
sourceNode.attr.sourceText=pagingKw.sourceText;sourceNode.attr.letterheads=pagingKw.letterheads;sourceNode.attr.letterhead_id=pagingKw.letterhead_id;sourceNode.subscribe('paginate',function(){gnrwdg.paginate();});kw['style']=pagingKw.bodyStyle;var container=sourceNode._('div',kw);var top=container._('div',{position:'absolute',top:'0',left:0,right:0,height:'20px',gradient_from:'silver',gradient_to:'whitesmoke',gradient_deg:-90,border_bottom:'1px solid silver'})
top._('horizontalSlider',{value:'^#WORKSPACE.zoom','default':0.3,minimum:0.3,maximum:1,intermediateChanges:true,width:'15em',margin_top:'2px'})
if(pagingKw.printAction){top._('div',{_class:'iconbox print',connect_onclick:pagingKw.printAction,position:'absolute',right:'2px',top:'0px'})}
var b=container._('div',{position:'absolute',top:'20px',left:0,bottom:0,right:0});var rootKw={innerHTML:pagingKw.pagedText,position:'absolute',top:'0',left:0,right:0,bottom:0,zoom:'^#WORKSPACE.zoom',overflow:'auto',_class:'pe_preview_box'};rootKw.connect_onclick=function(evt){gnrwdg.onClick(evt);}
gnrwdg.pagesRoot=b._('div',rootKw).getParentNode();return container;},gnrwdg_onClick:function(evt){var target=evt.target;while(target&&target.getAttribute&&!target.getAttribute('orig_idx')){target=target.parentNode;}
if(target&&target.getAttribute&&target.getAttribute('orig_idx')){var c=parseInt(target.getAttribute('orig_idx'));}else{var c=-1;}
if(this.editorNode){this.editorNode.externalWidget.gnr_highlightChild(c);}},gnrwdg_setLetterhead_id:function(letterhead_id,kw,reason){if(reason=='container'){return;}
this.paginate();},gnrwdg_addPage:function(){var rn=this.pagesRoot.domNode;var p=document.createElement('div');var content_node;var letterheads=this.sourceNode.getRelativeData(this.letterheadsPath);if(letterheads){var lnumber=rn.childElementCount;var max_lnumber=letterheads.len()-1;if(lnumber>max_lnumber){lnumber=max_lnumber;}
var letterhead_page=letterheads.getItem('#'+lnumber);this.sourceBag.setItem('p',rn.childElementCount+1);p.innerHTML=dataTemplate(letterhead_page,this.sourceBag,null,true);var p=p.children[0];content_node=dojo.query('div[content_node=t]',p)[0];}else{genro.dom.addClass(p,'pe_pages');content_node=p;}
rn.appendChild(p);genro.dom.addClass(content_node,'pe_content')
return content_node;},gnrwdg_setSourceText:function(value,kw,trigger_reason){if(trigger_reason!='container'){this.paginate();}},gnrwdg_onPaginating:function(){var pagesDomNode=this.pagesRoot.domNode;this.pagesDomNodeParent=pagesDomNode.parentNode;dojo.body().appendChild(pagesDomNode);var sn=this.sourceNode;this.sourceBag=sn.getRelativeData(this.datasource).deepCopy();this.sourceBag.setItem('pp','#PP');for(var k in this.tpl_kwargs){this.sourceBag.setItem(k,sn.currentFromDatasource(this.tpl_kwargs[k]));}
pagesDomNode.style.visibility='hidden';this.currentZoom=pagesDomNode.style.zoom;pagesDomNode.style.zoom='1';},gnrwdg_onPaginated:function(){var pagesDomNode=this.pagesRoot.domNode;this.pagesDomNodeParent.appendChild(pagesDomNode)
pagesDomNode.innerHTML=pagesDomNode.innerHTML.replace(/\#PP/g,pagesDomNode.childElementCount);pagesDomNode.style.zoom=this.currentZoom;pagesDomNode.style.visibility='visible';},gnrwdg_paginate:function(){var sourceHtml=this.sourceNode.getRelativeData(this.sourceTextPath);var pagesDomNode=this.pagesRoot.domNode;pagesDomNode.innerHTML='';if(sourceHtml){this.onPaginating();var page=this.addPage();var dest=document.createElement('div');page.appendChild(dest);var src=document.createElement('div');src.innerHTML=sourceHtml;var children=src.children;var node;var idx=0;while(children.length){node=src.removeChild(children[0]);node.setAttribute('orig_idx',idx);genro.dom.addClass(node,'pe_node');dest.appendChild(node);if((dest.clientHeight+this.extra_bottom>=page.clientHeight)||(node.innerHTML.indexOf('--//--')>=0)){node=dest.removeChild(node);page=this.addPage();dest=document.createElement('div');page.appendChild(dest);if(node.innerHTML.indexOf('--//--')<0){dest.appendChild(node);}}
idx++;}
this.onPaginated();}
this.sourceNode.setRelativeData(this.pagedTextPath,pagesDomNode.innerHTML,null,null,this.pagesRoot);}});dojo.declare("gnr.widgets.TemplateChunk",gnr.widgets.gnrwdg,{getVirtualColumns:function(tpl_vc,curr_vc){curr_vc=curr_vc?curr_vc.split(','):[]
tpl_vc=tpl_vc?tpl_vc.split(','):[];if(!curr_vc){curr_vc=tpl_vc;}else{dojo.forEach(tpl_vc,function(c){if(dojo.indexOf(curr_vc,c)<0){curr_vc.push(c)}});}
return curr_vc;},loadTemplateEditData:function(sourceNode){var paletteNode=sourceNode._connectedPalette;var templateHandler=sourceNode._templateHandler;paletteNode.setRelativeData('.data',templateHandler.data?templateHandler.data.deepCopy():new gnr.GnrBag());var respath=templateHandler.dataInfo.respath;if(respath&&respath.indexOf('_custom')>=0){paletteNode.setRelativeData('.data.metadata.custom',true);}},gnrwdg_setTemplate:function(templateBag){if(this.chunkNode._connectedPalette){this.gnr.loadTemplateEditData(this.chunkNode);}},openTemplatePalette:function(sourceNode,editorConstrain,showLetterhead){var paletteCode='template_editor_'+sourceNode._id;var tplpars=sourceNode.attr._tplpars;var templateHandler=sourceNode._templateHandler;var handler=this;var paletteId=paletteCode+'_floating';if(sourceNode._connectedPalette){var paletteNode=sourceNode._connectedPalette;paletteNode.getWidget().show();}else{var table=tplpars.table;var remote_datasourcepath=sourceNode.absDatapath(sourceNode.attr.datasource);var showLetterhead=typeof(showLetterhead)=='string'?(sourceNode.getRelativeData(showLetterhead)||true):showLetterhead;var kw={'paletteCode':paletteCode,'dockTo':'dommyDock:open',title:'Template Edit '+table?table.split('.')[1]:'',width:'750px',maxable:true,height:'500px',remote:'te_chunkEditorPane',remote_table:table,remote_paletteId:paletteId,remote_resource_mode:!table||(templateHandler.dataInfo.respath!=null),remote_datasourcepath:remote_datasourcepath,remote_showLetterhead:showLetterhead,remote_editorConstrain:editorConstrain};kw.remote__onRemote=function(){handler.loadTemplateEditData(sourceNode);}
kw.palette_selfsubscribe_savechunk=function(){tplpars=sourceNode.evaluateOnNode(tplpars);var template=tplpars.template||new gnr.GnrBag();var data=this.getRelativeData('.data').deepCopy();var custom=data.pop('metadata.custom');if(typeof(template)=='string'){var respath=handler.saveTemplate(sourceNode,data,tplpars,custom);templateHandler.dataInfo.respath=respath;}else{var tplpath=sourceNode.attr._tplpars.template;var currdata=sourceNode.getRelativeData(tplpath,data)
if(!currdata){currdata=new gnr.GnrBag();sourceNode.setRelativeData(tplpath,currdata)}
currdata.clear();data.forEach(function(n){currdata.setItem(n.label,n._value,n.attr)});}
templateHandler.setNewData({data:data,template:data.getItem('compiled'),dataInfo:templateHandler.dataInfo});sourceNode.updateTemplate();sourceNode.publish('onChunkEdit');this.widget.hide();}
var palette=sourceNode._('palettePane',kw);var paletteNode=palette.getParentNode();sourceNode._connectedPalette=paletteNode;}},updateVirtualColumns:function(sourceNode,datasourceNode,dataProvider,mainNode){var vc,curr_vc;if(dataProvider){curr_vc=dataProvider.attr.virtual_columns
vc=this.getVirtualColumns(mainNode.attr.virtual_columns,curr_vc);if(vc){dataProvider.attr.virtual_columns=vc.join(',');dataProvider.fireNode();}}else{curr_vc=datasourceNode.attr._virtual_columns;vc=this.getVirtualColumns(mainNode.attr.virtual_columns,curr_vc);if(vc){if(datasourceNode._resolver){datasourceNode._resolver.kwargs.virtual_columns=vc.join(',');datasourceNode._resolver.lastUpdate=null;sourceNode.attr._virtual_column=dojo.map(vc,function(c){return datasourceNode.label+'.'+c;}).join(',');}else{sourceNode.attr._virtual_column=vc.join(',');}}}},loadTemplate:function(sourceNode,kw){kw.template=kw.template||new gnr.GnrBag();if(kw.template instanceof gnr.GnrBag){var data=kw.template;return{data:data,dataInfo:{},template:data.getItem('compiled')};}
var template_address=(kw.table||'')+':'+kw.template;var result=genro.serverCall("loadTemplate",{template_address:template_address,asSource:kw.asSource});if(result.attr.html){var content=result.getValue().getItem('content');return{template:content,dataInfo:result.attr,data:new gnr.GnrBag({'content':content})};}
if(kw.asSource){var data=result.getValue();return{data:data,dataInfo:result.attr,template:data instanceof gnr.GnrBag?data.getItem('compiled'):''};}
return{template:result};},saveTemplate:function(sourceNode,data,kw,custom){var template_address=(kw.table||'')+':'+kw.template;var templateHandler=sourceNode._templateHandler;if(custom){template_address=template_address+',custom'}
return genro.serverCall("saveTemplate",{template_address:template_address,data:data},null,null,'POST');},createContent:function(sourceNode,kw,children){var resource=objectPop(kw,'resource');if(resource){console.warn('templateChunk warning: use "template" param instead of "resource" param');}
var tplpars=objectExtract(kw,'table,template,editable');tplpars.table=tplpars.table||'';var editorConstrain=objectExtract(kw,'constrain_*',null,true);var showLetterhead=objectPop(kw,'showLetterhead');if(typeof(showLetterhead)=='string'){showLetterhead=sourceNode.absDatapath(showLetterhead);}
var record_id=objectPop(kw,'record_id');genro.assert((record_id||kw.datasource),'record_id or datasource are mandatory in templatechunk');if(record_id){sourceNode.attr.record_id=record_id;}
sourceNode.attr.template=tplpars.template;for(var k in editorConstrain){var c=editorConstrain[k];if(typeof(c)=='string'&&(c[0]=='^'||c[0]=='=')){editorConstrain[k]=c[0]+sourceNode.absDatapath(c);}}
var showAlways=tplpars.editable;tplpars.template=tplpars.template||resource;kw._tplpars=tplpars;kw._tplpars.editable=kw._tplpars.editable||(genro.isDeveloper?'developer':false);kw._tplpars.showAlways=kw._tplpars.editable===true;kw._tplpars.asSource=kw._tplpars.editable!=null;kw._class=(kw._class||'')+' selectable'
var dataProvider=objectPop(kw,'dataProvider');if(dataProvider){dataProvider=sourceNode.currentFromDatasource(dataProvider);}
var handler=this;if(tplpars.editable){kw.selfsubscribe_openTemplatePalette=function(){handler.openTemplatePalette(this,editorConstrain,showLetterhead);}
kw.connect_ondblclick=function(evt){if(tplpars.editable==true||evt.shiftKey){handler.openTemplatePalette(this,editorConstrain,showLetterhead);}};}
kw.onCreated=function(domnode,attributes){this._templateHandler={};var templateHandler=this._templateHandler
templateHandler.showAlways=showAlways;if(record_id){handler.createServerChunk(this,record_id,tplpars);}
else{handler.createClientChunk(this,dataProvider,tplpars);}}
var chunk=sourceNode._('div','templateChunk',kw)
sourceNode.gnrwdg.chunkNode=chunk.getParentNode();return chunk;},createClientChunk:function(sourceNode,dataProvider,tplpars){var templateHandler=sourceNode._templateHandler;var cls=this;templateHandler.cb=function(){this.setNewData(cls.loadTemplate(sourceNode,sourceNode.evaluateOnNode(tplpars)));};templateHandler.setNewData=function(result){this.data=result.data;this.dataInfo=result.dataInfo;this.template=result.template;this.defaults={};var datasourcePath=sourceNode.absDatapath(sourceNode.attr.datasource);var datasourceNode=genro.getDataNode(datasourcePath);if(this.template instanceof gnr.GnrBag){var varsbag=this.data.getItem('varsbag');var defaults=this.defaults;if(varsbag){varsbag.forEach(function(n){var v=n.getValue();defaults[v.getItem('fieldpath')]='<span class="chunkeditor_varplaceholder">'+(v.getItem('fieldname')||'')+'</span>';},'static');}
var mainNode=this.template.getNode('main');cls.updateVirtualColumns(sourceNode,datasourceNode,dataProvider,mainNode)}else{this.template=this.template||'<div class="chunkeditor_emptytemplate">Template not yet created</div>';}};sourceNode.updateTemplate=function(){this._templateHandler.template=null;var result=dataTemplate(this._templateHandler,this,this.attr.datasource);if(this.isPointerPath(this.attr.innerHTML)){this.setRelativeData(this.attr.innerHTML,result);}else{this.domNode.innerHTML=result;}}
sourceNode.attr.template=templateHandler;sourceNode._('dataController',{'script':"this.getParentBag().getParentNode().updateTemplate();",_fired:tplpars.template});},createServerChunk:function(sourceNode,record_id,tplpars){var templateHandler=sourceNode._templateHandler;sourceNode.updateTemplate=function(pkey){var that=this;if(pkey){genro.serverCall('te_renderChunk',{record_id:pkey,template_address:tplpars.table+':'+tplpars.template,_sourceNode:sourceNode},function(resultNode){var r=resultNode.getValue();templateHandler.dataInfo=resultNode.attr;if(r instanceof gnr.GnrBag){that.domNode.innerHTML=r.getItem('rendered');templateHandler.data=r.popNode('template_data').getValue();}else{that.domNode.innerHTML=r;templateHandler.data=new gnr.GnrBag();}},null,'POST');}else{sourceNode.domNode.innerHTML='';templateHandler.dataInfo={};templateHandler.data=new gnr.GnrBag();}}
templateHandler.setNewData=function(result){sourceNode.updateTemplate(sourceNode.getRelativeData(record_id));}
sourceNode.registerSubscription('changeInTable',sourceNode,function(kw){var mainNode=this.getParentNode();var currpkey=mainNode.getAttributeFromDatasource('record_id');if(kw.table==this.attr._tplpars.table&&currpkey==kw.pkey){mainNode.gnrwdg.refresh();}});},gnrwdg_refresh:function(){var pkey;var tnode=this.sourceNode._value.getNode('templateChunk');if(this.sourceNode.attr.record_id){pkey=this.sourceNode.getAttributeFromDatasource('record_id');}
tnode.updateTemplate(pkey);},gnrwdg_setRecord_id:function(pkey){var tnode=this.sourceNode._value.getNode('templateChunk');tnode.updateTemplate(pkey);}});dojo.declare("gnr.widgets.DropUploaderGrid",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var uploaderPars=objectExtract(kw,'onUploadedMethod,onUploadingMethod');var uploaderKw=objectExtract(kw,'uploadPath,filename,onResult,onError,onProgress,onAbort');objectUpdate(uploaderPars,objectExtract(kw,'rpc_*'));var nodeId=objectPop(kw,'nodeId')||'uploader_'+genro.getCounter()
uploaderKw.uploadPath=uploaderKw.uploadPath||'page:'+nodeId;var label=objectPop(kw,'label');var containerKw=objectExtract(kw,'position,top,left,right,bottom,height,width,border,rounded,_class,style,region');var rootbc=sourceNode._('bordercontainer',containerKw);var grid=rootbc._('contentPane',{'region':'center'})._('quickGrid',{value:kw.storepath||'^gnr.uploadedFiles',nodeId:nodeId,dropTarget_grid:'Files',dropTypes:'Files',selfsubscribe_doUpload:function(){genro.rpc.uploadMultipartFiles(this.widget.storebag(),{onResult:funcCreate(uploaderKw.onResult,'result',this),uploadPath:uploaderKw.uploadPath,uploaderId:nodeId});},onDrop:function(dropInfo,files){var filebag=this.widget.storebag();files.forEach(function(f){let row={_name:f.name,_size:f.size,_type:f.type,_file:f,_uploaderId:nodeId};let label=(f.name+'_'+f.size+'_'+f.type).replace(/\W/g,'_');if(filebag.index(label)<0){filebag.addItem(label,new gnr.GnrBag(row));}});}});grid._('column',{name:_T('Filename'),field:'_name',width:'15em',edit:true});grid._('column',{name:_T('Size'),field:'_size',width:'5em','dtype':'L'});grid._('column',{name:_T('Type'),field:'_type',width:'10em'});grid._('column',{name:_T('Status'),field:'_status',width:'10em'});grid._('tools',{tools:'delrow',title:label||_T('Drop here files to upload')});return rootbc;}});dojo.declare("gnr.widgets.DropUploader",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var gnrwdg=sourceNode.gnrwdg;var uploaderPars=objectExtract(kw,'onUploadedMethod,onUploadingMethod');var uploaderKw=objectExtract(kw,'uploadPath,filename,onResult,onError,onProgress,onAbort');objectUpdate(uploaderPars,objectExtract(kw,'rpc_*'));var nodeId=objectPop(kw,'nodeId')||'uploader_'+genro.getCounter()
uploaderKw.uploadPath=uploaderKw.uploadPath||'page:'+nodeId;var label=objectPop(kw,'label');var dropAreaKw={nodeId:nodeId,dropTarget:objectPop(kw,'dropTarget',true),dropTypes:objectPop(kw,'dropTypes','Files'),_class:'dropUploaderBoxInner'};var containerKw=objectExtract(kw,'position,top,left,right,bottom,height,width,border,rounded,_class,style')
gnrwdg.pendingHandlers=[];var uploadhandler_key=genro.isMobile?'selfsubscribe_doubletap':'connect_ondblclick'
dropAreaKw[uploadhandler_key]=function(){if(gnrwdg.pendingHandlers.length){genro.dlg.ask(_T("Abort upload"),_T("Are you sure?"),null,{confirm:function(){gnrwdg.pendingHandlers.forEach(function(h){if(h._progressDiv){gnrwdg.rootNode.domNode.removeChild(h._progressDiv);}
h.abort()});gnrwdg.pendingHandlers=[];}});}else{gnrwdg.fakeinputNode.domNode.click();}}
dropAreaKw.innerHTML=dropAreaKw.innerHTML||label||'&nbsp;';var maxsize=objectPop(kw,'maxsize');uploaderKw.uploaderId=dropAreaKw.nodeId;var onUploadingCb=objectPop(kw,'onUploadingCb')||function(){};onUploadingCb=funcCreate(onUploadingCb,'dropInfo,data',sourceNode);var progressBar=objectPop(kw,'progressBar',true);if(uploaderKw.onResult){uploaderKw.onResult=funcCreate(uploaderKw.onResult,'evt',sourceNode);}
if(uploaderKw.onError){uploaderKw.onError=funcCreate(uploaderKw.onError,'evt',sourceNode);}
if(uploaderKw.onAbort){uploaderKw.onAbort=funcCreate(uploaderKw.onAbort,'evt',sourceNode);}
if(uploaderKw.onProgress){uploaderKw.onProgress=funcCreate(uploaderKw.onProgress,'evt',sourceNode);}else if(progressBar){uploaderKw.onProgress=function(evt){var d=evt._sender._progressDiv;if(d){d.style.width=(evt.loaded*100)/evt.total+'%';if(evt.loaded==evt.total){gnrwdg.rootNode.domNode.removeChild(d);gnrwdg.pendingHandlers.splice(evt._sender._counter,1);}}};}
var cbOnDropData=function(dropInfo,data){var doUpload=onUploadingCb(dropInfo,data);if(doUpload===false){return false;}
return genro.rpc.uploadMultipart_oneFile(data,objectUpdate({},uploaderPars),objectUpdate({filename:data.name},uploaderKw));}
var onFiles=function(dropInfo,files){gnrwdg.pendingHandlers=[];if(sourceNode.form&&sourceNode.form.isDisabled()){genro.dlg.alert("The form is locked",'Warning');return false;}
var totSize=0;if(maxsize){dojo.forEach(function(f){totSize+=f.size;});if(totSize>maxsize){var size_kb=maxsize/1000
genro.dlg.alert("File exeeds size limit ("+size_kb+"KB)",'Error');return false;}}
var c=0;var height=Math.round(100/files.length)
dojo.forEach(files,function(f){var h=cbOnDropData(dropInfo,f);if(h){gnrwdg.pendingHandlers.push(h);if(progressBar){var pb=document.createElement('div');pb.style.position='absolute';pb.style.top=c*height+'%';pb.style.left=0;pb.style.height=height+'%';pb.style.background='rgba(11,121,171,0.30)';gnrwdg.rootNode.domNode.appendChild(pb);h._counter=c;h._progressDiv=pb;}
c+=1;}});};dropAreaKw.onDrop=onFiles;containerKw._class=containerKw._class||'dropUploaderBox';var container=sourceNode._('div',containerKw);var fakeinput=container._('input',{hidden:true,type:'file',connect_onchange:function(evt){onFiles({evt:evt},evt.target.files);this.domNode.value=null;}});gnrwdg.fakeinputNode=fakeinput.getParentNode();container._('div',objectUpdate(dropAreaKw,kw))
gnrwdg.rootNode=container.getParentNode();return container;}});dojo.declare("gnr.widgets.SlotButton",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var inherithed=sourceNode.getInheritedAttributes();kw['showLabel']=kw.iconClass?(kw['showLabel']||false):true;if(!kw['showLabel']){kw['_class']=kw['_class']?kw['_class']+' slotButtonIconOnly':' slotButtonIconOnly';}
var targetNode,prefix;var tag='button';var target=objectPop(kw,'target')||inherithed.target;if(target!=false){if(target){targetNode=genro.nodeById(target,sourceNode);prefix=targetNode?(targetNode.attr.nodeId||targetNode.getStringId()):target;}else if(inherithed.frameCode){var framePane=genro.getFrameNode(inherithed.frameCode);if(framePane){targetNode=framePane.getValue().getNodeByAttr('frameTarget',true);if(targetNode){prefix=targetNode.attr.nodeId||inherithed.frameCode+'_target';}}}}else{prefix=inherithed.slotbarCode;}
var publish=objectPop(kw,'publish');if(kw.menupath){kw['storepath']=objectPop(kw,'menupath');tag='menudiv';}
if(!kw.action&&publish){kw.topic=prefix?prefix+'_'+publish:publish;kw.command=kw.command||null;if(tag=='button'){kw['action']="genro.publish(topic,{'command':command,modifiers:genro.dom.getEventModifiers(event),opt:objectExtract(_kwargs,'opt_*'),evt:event,_counter:_counter});";}else{kw['action']="objectPop($1,'caption');genro.publish('"+kw.topic+"',{'command':'"+(kw.command||'')+"' ||null,modifiers:genro.dom.getEventModifiers(event),evt:event,opt:$1});";}}
return sourceNode._(tag,kw);}});dojo.declare("gnr.widgets.DocItem",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var _class=objectPop(kw,'_class');kw._class=_class?'doc_item selectable '+_class:'doc_item selectable';var docpars=objectExtract(kw,'store,key,contentpath');kw._docKey=docpars.key;kw._docStore=docpars.store;kw._docContentPath=docpars.contentpath;kw.datapath='==(_docStore && _docKey && _docContentPath)?"_doc.content."+_docStore+"."+_docKey+"."+_docContentPath:"_emptypath"';kw.connect_ondblclick="genro.publish('editDocItem',{docItem:this});"
kw.connect_onclick="genro.publish('focusDocItem',{docItem:this});"
return sourceNode._('div',kw)._('div',{innerHTML:'==(_allcontent&&_current_lang)?(_allcontent.getItem(_current_lang)?_allcontent.getItem(_current_lang):_allcontent.getItem("#0")):"";','_class':'^.?contentClasses','style':'^.?contentStyles',_current_lang:'^gnr.language',_allcontent:'^.'})}});dojo.declare("gnr.widgets.MultiButton",gnr.widgets.gnrwdg,{subtags:{'item':true,'store':true},createContent:function(sourceNode,kw,children,subTagItems){var value=objectPop(kw,'value');var values=objectPop(kw,'values');var items=objectPop(kw,'items');var multibuttonstore=objectPop(subTagItems,'store');var storepath=objectPop(kw,'storepath');var identifier=objectPop(kw,'identifier');var caption=objectPop(kw,'caption')||'caption';sourceNode.attr._workspace=true;var gnrwdg=sourceNode.gnrwdg;if(storepath){sourceNode.registerDynAttr('items');items='^'+storepath;}
if(multibuttonstore.len()){var storeattr=multibuttonstore.getAttr('#0');storeattr.storepath=storeattr.storepath||'#WORKSPACE.store';identifier=storeattr._identifier||'_pkey';items='^'+storeattr.storepath;sourceNode.registerDynAttr('items')
storeattr.linkedWidgetNode=sourceNode;sourceNode._('SelectionStore','store',storeattr);}
identifier=identifier||'code';var multivalue=objectPop(kw,'multivalue');var sticky=objectPop(kw,'sticky')==false?false:true;var mandatory=objectPop(kw,'mandatory',sticky);var deleteAction=objectPop(kw,'deleteAction');var showAlways=objectPop(kw,'showAlways');var items_bag=items?sourceNode.getRelativeData(items):new gnr.GnrBag();var childItemsPost=new gnr.GnrBag();var childItemsPrev=new gnr.GnrBag();subTagItems['item'].forEach(function(n){var attr=n.attr;attr.code=attr.code||n.label;if(attr.prev){childItemsPrev.setItem(attr.code,null,attr);}
childItemsPost.setItem(attr.code,null,attr);});gnrwdg.childItemsPrev=childItemsPrev;gnrwdg.childItemsPost=childItemsPost;gnrwdg.showAlways=showAlways;gnrwdg.sticky=sticky;gnrwdg.mandatory=mandatory;gnrwdg.identifier=identifier;gnrwdg.caption=caption;gnrwdg.caption_format=objectPop(kw,'caption_format');gnrwdg.caption_dtype=objectPop(kw,'caption_dtype');if(values){items_bag=gnrwdg.itemsFromValues(values);}
items=items||'^#WORKSPACE.items';sourceNode.registerDynAttr('items');if(deleteAction){if(deleteAction===true){deleteAction="this._value.getNode('store').gnrwdg.store.deleteAsk([value])"}
gnrwdg.deleteAction=funcCreate(deleteAction,'value,caption',gnrwdg.sourceNode);gnrwdg.deleteSelectedOnly=objectPop(kw,'deleteSelectedOnly');}
sourceNode.attr.value=value;sourceNode.attr.values=values;sourceNode.attr.items=items;var containerKw={_class:'multibutton_container'};if(sticky){var btn_action=function(event){var sn=event.target?genro.dom.getBaseSourceNode(event.target):null;if(sn){var mcode=sn.getInheritedAttributes()['multibutton_code'];if(mcode){if(event.shiftKey&&multivalue){var prevmcode=sourceNode.getRelativeData(value);if(prevmcode){prevmcode=prevmcode.split(',');var j=prevmcode.indexOf(mcode);if(j<0){prevmcode.push(mcode);}else if(prevmcode.length>1||!mandatory){prevmcode.splice(j,1);}
mcode=prevmcode.join(',');}}
sourceNode.setRelativeData(value,mcode);}}};}else{var btn_action=function(_kwargs){var event=_kwargs.event
var sn=event.target?genro.dom.getBaseSourceNode(event.target):null;if(sn){var mcode=sn.getInheritedAttributes()['multibutton_code'];if(mcode){this.fireEvent(value,objectUpdate(_kwargs,{action:mcode}))}}}}
containerKw.action=btn_action;containerKw.selfsubscribe_appendItem=function(kw){gnrwdg.appendItem(kw);}
var multibutton=sourceNode._('div','multibutton',objectUpdate(containerKw,kw));gnrwdg.multibuttonSource=multibutton;if(items_bag){sourceNode.setRelativeData(sourceNode.attr.items,items_bag);gnrwdg.makeButtons(items_bag);}
return multibutton;},gnrwdg_itemsFromValues:function(values){var result=new gnr.GnrBag();if(!values){return result;}
if(this.sourceNode.isPointerPath(values[0])){values=this.sourceNode.getAttributeFromDatasource('values')}
if(!values){return result;}
var l;var attr;var that=this;values.split(',').forEach(function(n){l=n.split(':');attr={};attr[that.identifier]=l[0];attr[that.caption]=l[1]||l[0];result.setItem(l[0],null,attr);});return result;},gnrwdg_selectByNumber:function(buttonNumber,defaultLast){var items=this.getItems();if(!items||items.len()==0){return;}
if(buttonNumber>items.len()-1){buttonNumber=defaultLast?(items.len()-1):0;}
var node=items.getNode('#'+buttonNumber);this.sourceNode.setRelativeData(this.sourceNode.attr.value,node.attr[this.identifier])},gnrwdg_setValue:function(value,kw){if(this.sticky){var mb=this.multibuttonSource;if(value&&mb){value=value.split(',');var identifier=this.identifier;var code;mb.forEach(function(n){if('multibutton_code'in n.attr){code=n.attr.multibutton_code;}else{console.warn('missing multibutton_code');code=n.attr[identifier]||n.attr['code']||n.label;}
genro.dom.setClass(n,'multibutton_selected',value.indexOf(code)>=0);});}}},gnrwdg_setValues:function(values,kw){this.sourceNode.setRelativeData(this.sourceNode.attr.items,this.itemsFromValues(values));},gnrwdg_appendItem:function(kw){var selectLast=objectPop(kw,'selectLast');var store=this.sourceNode.getRelativeData(this.sourceNode.attr.items);var identifier=kw[this.identifier];store.setItem(flattenString(identifier),null,kw);if(selectLast){this.sourceNode.setRelativeData(this.sourceNode.attr.value,identifier);}},gnrwdg_defaultDeleteAction:function(key,value){var store=this.sourceNode.getRelativeData(this.sourceNode.attr.items);var nodeToDel=store.getNodeByAttr(this.identifier,key);store.popNode(nodeToDel.label);},gnrwdg_setItems:function(items,kw,trigger_reason){var sn=this.sourceNode;var currentSelected=sn.getRelativeData(sn.attr.value);if(currentSelected&&!this.getItemNode(currentSelected)){sn.setRelativeData(sn.attr.value,null);}
this.makeButtons(this.getItems());},gnrwdg_getItemNode:function(identifier){var items=this.getItems();if(!items){return;}
return items.getNodeByAttr(this.identifier,identifier);},gnrwdg_getItems:function(){return this.sourceNode.getRelativeData(this.sourceNode.attr.items);},gnrwdg_makeButtons:function(items){items=items||new gnr.GnrBag();var sourceNode=this.sourceNode;var mb=this.multibuttonSource;var child_count=items.len();var deleteAction=this.deleteAction;var customDelete;var gnrwdg=this;mb.clear(true);if(mb){var btn,content_kw,btn_class,code,caption,kw;var firstItem=items.getNode('#0');var currentSelected=sourceNode.getRelativeData(sourceNode.attr.value);var that=this;this.childItemsPrev.forEach(function(n){that.oneButton(n,currentSelected,'code','caption');},'static');items.forEach(function(n){that.oneButton(n,currentSelected);},'static');this.childItemsPost.forEach(function(n){that.oneButton(n,currentSelected,'code','caption');},'static');if(!currentSelected&&this.mandatory&&this.multibuttonSource.len()){var currentSelectedNode=this.multibuttonSource.getNode('#0');if(currentSelectedNode&&!currentSelectedNode.attr.action){currentSelectedNode.attr['_class']+=' multibutton_selected';currentSelected=currentSelectedNode.attr[this.identifier]||currentSelectedNode.attr['code']||currentSelectedNode.label;}}
sourceNode.setRelativeData(sourceNode.attr.value,currentSelected);}},gnrwdg_oneButton:function(n,currentSelected,identifier,caption){var mb=this.multibuttonSource;var kw=objectUpdate({},n.attr);var content_kw=objectExtract(kw,'content_*');content_kw._class=objectPop(content_kw,'class');var captionKey=caption||this.caption;var codeKey=identifier||this.identifier;var caption=kw[captionKey];var code=kw[codeKey]||n.label;var btn_class=code==currentSelected?'multibutton multibutton_selected':'multibutton';var customDelete=kw.deleteAction;if(typeof(customDelete)=='string'){customDelete=funcCreate(kw.deleteAction,'value,caption')}
var deleteAction=customDelete===false?false:(customDelete||this.deleteAction);if(kw._is_readonly_row){btn_class=btn_class+' _is_readonly_row';}
else if(deleteAction){btn_class=btn_class+' multibutton_closable';}
kw.multibutton_code=code;kw._class=(kw._class||'')+' '+btn_class;content_kw.innerHTML=_F(caption,this.caption_format,this.caption_dtype);content_kw._class=(content_kw._class||'')+' '+'multibutton_caption';var btn=mb._('lightbutton',kw);btn._('div',content_kw);var gnrwdg=this;if(deleteAction){btn._('div',{_class:'multibutton_closer framecloserIcon'+(this.deleteSelectedOnly?' deleteSelectedOnly':''),connect_onclick:function(e){dojo.stopEvent(e);if(deleteAction===true){console.log('defaultDeleteAction');gnrwdg.defaultDeleteAction(code,caption);}else{deleteAction.call(this.sourceNode,code,caption);}}});}},gnrwdg_isVisible:function(){return genro.dom.isVisible(this.sourceNode.getParentNode())}});dojo.declare("gnr.widgets.StackButtons",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){return attributes;},createContent:function(sourceNode,kw,children){var frameCode=objectPop(kw,'frameCode');var stackNode=objectPop(kw,'stack');if(!stackNode){genro.assert(kw.stackNodeId,'Need the stack node or the stackNodeId')
stackNode=genro.nodeById(kw.stackNodeId);}
var that=this;kw=objectUpdate({connect_onclick:function(e){var childSourceNode=e.target.sourceNode?e.target.sourceNode.getInheritedAttributes()['_childSourceNode']:null;var buttonNode=genro.dom.getBaseSourceNode(e.target);var buttonAttr=buttonNode.currentAttributes();if(buttonAttr.disabled){return;}
if(childSourceNode){stackNode.widget.selectChild(childSourceNode.widget);}},_class:'multibutton_container'},kw);var tabButtonsNode=sourceNode._('div',kw);stackNode._n_children=0
if(children&&children.len()>0){stackNode._n_children=children.len();}
stackNode._stackButtonsNodes=stackNode._stackButtonsNodes||[];stackNode._stackButtonsNodes.push(tabButtonsNode.getParentNode());dojo.connect(stackNode,'onNodeBuilt',function(widget){genro.callAfter(function(){that.initButtons(stackNode);dojo.connect(widget.gnr,'onShowHideChild',that,'onShowHideChild');dojo.connect(widget.gnr,'onAddChild',that,'onAddChild');dojo.connect(widget.gnr,'onRemoveChild',that,'onRemoveChild');dojo.connect(widget,'setHiddenChild',function(child,value){that.setHiddenChild(this,child,value);});},1)})
return tabButtonsNode;},onAddChild:function(widget,child){var sn=widget.sourceNode;var controllerNodes=sn._stackButtonsNodes;if((!controllerNodes)||sn._isBuilding){return;}
var that=this;sn.delayedCall(function(){var cn=sn._stackButtonsNodes;if(cn){dojo.forEach(cn,function(c){that.makeTabButton(c,child.sourceNode,sn);});}},100);},onRemoveChild:function(widget,child){var sn=widget.sourceNode;var controllerNodes=sn._stackButtonsNodes;if((!controllerNodes)||sn._isBuilding){return;}
var paneId=this.getPaneId(child.sourceNode);setTimeout(function(){dojo.forEach(controllerNodes,function(c){c._value.popNode(paneId);});},1)},setHiddenChild:function(widget,child,value){var sn=widget.sourceNode;var controllerNodes=sn._stackButtonsNodes;if((!controllerNodes)||sn._isBuilding){return;}
var paneId=this.getPaneId(child.sourceNode);dojo.forEach(controllerNodes,function(c){genro.dom.setClass(c._value.getNode(paneId),'hidden',value)})},onShowHideChild:function(widget,child,st){if(!child){return;}
var sn=widget.sourceNode;var paneId=this.getPaneId(child.sourceNode);var controllerNodes=widget.sourceNode._stackButtonsNodes;if((!controllerNodes)||sn._isBuilding){return;}
dojo.forEach(controllerNodes,function(c){genro.dom.setClass(c._value.getNode(paneId),'multibutton_selected',st)})},initButtons:function(stackNode){var controllerNodes=stackNode._stackButtonsNodes;var sc=stackNode.widget;var page;var that=this;if(!controllerNodes){return;}
stackNode._value.forEach(function(n){if(n.getWidget()){dojo.forEach(controllerNodes,function(c){that.makeTabButton(c,n,stackNode);});}});},getPaneId:function(childSourceNode){var result=childSourceNode.attr.pageName||childSourceNode.attr.nodeId||childSourceNode.getStringId();return flattenString(result);},makeTabButton:function(sourceNode,childSourceNode,stackNode){var widget=childSourceNode.getWidget();var childSourceNode=widget.sourceNode;if(childSourceNode.attr.title){var btn_class=widget.selected?'multibutton multibutton_selected':'multibutton';if(childSourceNode.attr.closable){btn_class+=' multibutton_closable'}
var stackbag=stackNode.getValue();var childattr=childSourceNode.attr;var multibutton_kw=objectExtract(childattr,'stackbutton_*');var btn_kw={_class:btn_class,_childSourceNode:childSourceNode};var btn=sourceNode._('div',this.getPaneId(childSourceNode),btn_kw,{_position:stackbag.len()-stackNode._n_children});var title=childSourceNode.attr.title;var iconTitle=childSourceNode.attr.iconTitle;if(title&&title[0]=='^'){title='^'+childSourceNode.absDatapath(title);}
if(iconTitle){multibutton_kw.innerHTML='&nbsp;'
multibutton_kw._class='multibutton_caption '+iconTitle
multibutton_kw.tip=title;}else{multibutton_kw.innerHTML=title;multibutton_kw._class='multibutton_caption';}
btn._('div',multibutton_kw);if(childSourceNode.attr.closable){var stack=stackNode.widget;var onClosingCb=childSourceNode.attr.onClosingCb;var closeFinalize=function(){genro.callAfter(function(){if(stackbag.len()>1){var idx=stack.getSelectedIndex()-1;idx=idx>=0?idx:0;stack.switchPage(idx);}
stackbag.popNode(childSourceNode.label);},1);};btn._('div',{_class:'multibutton_closer framecloserIcon',connect_onclick:function(evt){dojo.stopEvent(evt);if(onClosingCb){var r=funcApply(onClosingCb,{evt:evt},childSourceNode);if(r===false){return}else if(typeof(r)=='string'){genro.dlg.ask(_T('Closing page')+childSourceNode.getRelativeData(title),r,{confirm:_T('Close anyway'),cancel:_T('Cancel')},{confirm:function(){closeFinalize();},cancel:function(){}});}else{closeFinalize();}}else{closeFinalize();}}});}}}});dojo.declare("gnr.widgets.UserObjectBar",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;if(objectPop(kw,'_workspace')!==false){sourceNode.attr._workspace=true;}
var userObjectPars=objectExtract(kw,'table,flags,objtype');gnrwdg.newcaption=_T(objectPop(kw,'newcaption')||'New empty '+userObjectPars.objtype);objectUpdate(userObjectPars,objectExtract(kw,'userobject_*'));gnrwdg.userObjectPars=userObjectPars;gnrwdg.startUserObjectIdOrCode=kw.userObjectId;gnrwdg.dataIndex=objectExtract(kw,'source_*');gnrwdg.defaults=objectExtract(kw,'default_*');let metadataPath=kw.metadata||'#WORKSPACE.metadata';gnrwdg.metadataPath=metadataPath;gnrwdg.handleFavorites=objectPop(kw,'handleFavorites');gnrwdg.mainIdentifier=objectPop(kw,'mainIdentifier');if(kw.onLoaded){gnrwdg.onLoaded=funcCreate(kw.onLoaded,'dataIndex','resoultValue','resoultAttr',sourceNode);}
return gnrwdg.buildToolbar(sourceNode);},gnrwdg_buildToolbar:function(sourceNode){this.setLoadMenuData();var bar=sourceNode._('slotBar','uo_bar',{toolbar:true,side:'top',slots:'5,loadMenu,2,objTitle,*,favoritebtn,saveBtn,deletebtn,5'});if(this.mainIdentifier){let barNode=bar.getParentNode();var that=this;let cb=function(){console.log('register subscription',`${that.mainIdentifier}_newObject`)
barNode.registerSubscription(`${that.mainIdentifier}_newObject`,that,function(kwargs){this.loadObject('__newobj__');});barNode.registerSubscription(`${that.mainIdentifier}_loadObject`,that,function(kwargs){this.loadObject(kwargs.userobject);});barNode.registerSubscription(`${that.mainIdentifier}_loadObject`,that,function(kwargs){this.saveObject();});}
genro.src.onBuiltCall(cb);}
var that=this;var favorite;bar._('div','objTitle',{innerHTML:'^.description?=(#v || "New")',datapath:this.metadataPath,font_weight:'bold',font_size:'.9em',color:'#666'});if(this.mainIdentifier&&this.handleFavorites){bar._('slotButton','favoritebtn',{'label':_T('Default'),action:function(){that.setCurrentAsFavorite();},iconClass:'highlightable iconbox star'});favorite=this.getFavorite();}
bar._('slotButton','loadMenu',{iconClass:'iconbox folder',label:'Load',menupath:'#WORKSPACE.loadMenu',action:function(item){that.loadObject(item.pkey);}});bar._('slotButton','saveBtn',{iconClass:'iconbox save',label:'Save',action:function(){that.saveObject();}});bar._('slotButton','deletebtn',{'label':_T('Delete'),iconClass:'iconbox trash',action:function(){that.deleteCurrentObject();}});if(favorite){this.loadObject(favorite||'__newobj__');}
return bar;},gnrwdg_resetMenuData:function(){var n=this.sourceNode.getRelativeData('#WORKSPACE').getNode('loadMenu');n.getResolver().reset();},gnrwdg_setLoadMenuData:function(){var that=this;this.sourceNode.setRelativeData('#WORKSPACE.loadMenu',genro.dev.userObjectMenuData(objectUpdate({},this.userObjectPars),[{pkey:'__newobj__',caption:this.newcaption},{pkey:'',caption:_T('New from current'),action:function(){that.newFromCurrent();}}]));},gnrwdg_setCurrentAsFavorite:function(){var metadata=this.sourceNode.getRelativeData(this.metadataPath);var pkey=metadata.getItem('pkey');genro.setInStorage("local",this.storageKey(),pkey);this.checkFavorite();},gnrwdg_getFavorite:function(){return genro.getFromStorage("local",this.storageKey());},gnrwdg_checkFavorite:function(){var pkey=this.sourceNode.getRelativeData(`${this.metadataPath}.pkey`);genro.dom.setClass(this.sourceNode.getParentNode(),'highlighted',pkey==this.getFavorite());},gnrwdg_storageKey:function(){return this.userObjectPars.objtype+genro.getData('gnr.pagename')+'_'+this.mainIdentifier;},gnrwdg_deleteCurrentObject:function(){var metadata=this.sourceNode.getRelativeData(this.metadataPath);var pkey=metadata.getItem('pkey');var that=this;if(pkey){genro.serverCall('_table.adm.userobject.deleteUserObject',{pkey:pkey},function(){that.loadObject('__newobj__');that.resetMenuData();});}else{that.loadObject('__newobj__');}},gnrwdg_saveObject:function(){var kw=objectUpdate({},this.userObjectPars);kw.dataIndex=objectUpdate({},this.dataIndex);kw.metadataPath=this.metadataPath;kw.title=_T('Save '+this.userObjectPars.objtype);var onSaved=objectPop(kw,'onSaved');var that=this;if(!onSaved){onSaved=function(result){that.resetMenuData();};}
genro.dev.userObjectSave(this.sourceNode,kw,onSaved);},gnrwdg_loadObject:function(userObjectId,kw){kw=kw||this.userObjectPars;kw=objectUpdate({},kw);kw.userObjectIdOrCode=userObjectId;kw.metadataPath=this.metadataPath;var that=this;kw.onLoaded=function(dataIndex,resultValue,resultAttr){if(that.onLoaded){that.onLoaded(dataIndex,resultValue,resultAttr);}
that.checkFavorite();}
if(userObjectId=='__newobj__'){kw.dataIndex=this.dataIndex;kw.defaults=this.sourceNode.evaluateOnNode(this.defaults);}
genro.dev.userObjectLoad(this.sourceNode,kw);},gnrwdg_newFromCurrent:function(){var code=this.sourceNode.getRelativeData(`${this.metadataPath}.code`);this.sourceNode.setRelativeData(this.metadataPath,new gnr.GnrBag(this.userObjectPars));genro.publish('floating_message',{message:_T(`New from ${code}`)});},});dojo.declare("gnr.widgets.UserObjectLayout",gnr.widgets.gnrwdg,{objtype:null,default_configurator_pars:null,newcaption:null,createContent:function(sourceNode,kw){var gnrwdg=sourceNode.gnrwdg;sourceNode.attr.nodeId=objectPop(kw,'nodeId');if(objectPop(kw,'_workspace')!==false){sourceNode.attr._workspace=true;}
var userObjectPars=objectExtract(kw,'table,flags,objtype');userObjectPars.objtype=userObjectPars.objtype||this.objtype;gnrwdg.newcaption=_T(objectPop(kw,'newcaption')||this.newcaption||'New '+userObjectPars.objtype);gnrwdg.table=userObjectPars.table;objectUpdate(userObjectPars,objectExtract(kw,'userobject_*'));gnrwdg.userObjectPars=userObjectPars;var bc=sourceNode._('BorderContainer','rootbc',objectExtract(kw,'top,bottom,left,right,border,margin,height,width,rounded,region,side'));kw.userObjectId=gnrwdg.getFavorite()||kw.userObjectId;gnrwdg.startUserObjectIdOrCode=kw.userObjectId;kw.configurator=kw.configurator===false?false:(kw.configurator||this.default_configurator_pars);if(kw.configurator){gnrwdg.prepareConfiguratorFrame(bc,kw);}
gnrwdg.prepareViewerFrame(bc,kw);return bc;},gnrwdg_resetMenuData:function(){var n=this.sourceNode.getRelativeData('#WORKSPACE').getNode('loadMenu');n.getResolver().reset();},gnrwdg_setLoadMenuData:function(){this.sourceNode.setRelativeData('#WORKSPACE.loadMenu',genro.dev.userObjectMenuData(objectUpdate({},this.userObjectPars),[{pkey:'__newobj__',caption:this.newcaption}]));},gnrwdg_prepareViewerFrame:function(bc,kw){var frame=bc._('FramePane','viewer',{region:'center',frameCode:this.sourceNode.attr.nodeId+'_viewer'});this.viewerFrame(frame);},gnrwdg_viewerFrame:function(frame,kw){},gnrwdg_configuratorFrame:function(frame,kw){},gnrwdg_prepareConfiguratorFrame:function(bc,kw){var confkw=objectPop(kw,'configurator');confkw=confkw===true?{region:'right',splitter:true,border_left:'1px solid #ccc',width:'320px'}:confkw;var confroot=bc;this.setLoadMenuData();var frame;if(confkw.palette){confkw.paletteCode=this.sourceNode.attr.nodeId+'_conf_palette';this.conf_paletteCode=confkw.paletteCode;frame=bc._('PalettePane','configurator',confkw)._('framePane',{frameCode:this.sourceNode.attr.nodeId+'_conf'});}else{if(!('drawer'in confkw)){confkw.drawer=(kw.userObjectId&&kw.userObjectId!='__newobj__')?'close':true;}
frame=bc._('FramePane','configurator',objectUpdate(confkw,{frameCode:this.sourceNode.attr.nodeId+'_conf'}));}
var bar=frame._('slotBar',{toolbar:true,side:'top',slots:'5,loadMenu,2,objTitle,*,favoritebtn,saveBtn,deletebtn,5'});var that=this;bar._('div','objTitle',{innerHTML:'^#WORKSPACE.metadata.description?=(#v || "New")',font_weight:'bold',font_size:'.9em',color:'#666'});bar._('slotButton','favoritebtn',{'label':_T('Default'),action:function(){that.setCurrentAsFavorite();},iconClass:'highlightable iconbox star'});bar._('slotButton','loadMenu',{iconClass:'iconbox folder',label:'Load',menupath:'#WORKSPACE.loadMenu',action:function(item){that.loadObject(item.pkey);}});bar._('slotButton','saveBtn',{iconClass:'iconbox save',label:'Save',action:function(){that.saveObject();}});bar._('slotButton','deletebtn',{'label':_T('Delete'),iconClass:'iconbox trash',action:function(){that.deleteCurrentObject();}});this.configuratorFrame(frame,kw);},gnrwdg_setCurrentAsFavorite:function(){var metadata=this.sourceNode.getRelativeData('#WORKSPACE.metadata');var pkey=metadata.getItem('pkey');genro.setInStorage("local",this.storageKey(),pkey);this.checkFavorite();},gnrwdg_getFavorite:function(){return genro.getFromStorage("local",this.storageKey());},gnrwdg_checkFavorite:function(){var metadata=this.sourceNode.getRelativeData('#WORKSPACE.metadata')||new gnr.GnrBag();var pkey=metadata.getItem('pkey');var currfavorite=this.getFavorite();genro.dom.setClass(this.sourceNode.getValue().getNode('rootbc'),'highlighted',currfavorite==pkey);},gnrwdg_storageKey:function(){return this.userObjectPars.objtype+genro.getData('gnr.pagename')+'_'+this.sourceNode.attr.nodeId;},gnrwdg_userObjectData:function(){return new gnr.GnrBag();},gnrwdg_deleteCurrentObject:function(){var metadata=this.sourceNode.getRelativeData('#WORKSPACE.metadata');var pkey=metadata.getItem('pkey');var that=this;if(pkey){genro.serverCall('_table.adm.userobject.deleteUserObject',{pkey:pkey},function(){that.loadObject('__newobj__');that.resetMenuData();});}else{that.loadObject('__newobj__');}},gnrwdg_saveObject:function(){var datapath=this.sourceNode.absDatapath('#WORKSPACE.metadata');var instanceCode=this.sourceNode.getRelativeData('#WORKSPACE.metadata.code');var data=this.userObjectData();var that=this;saveCb=function(dlg,event,counter,modifiers){var metadata=genro.getData(datapath);metadata.setItem('flags',that.userObjectPars.flags);genro.serverCall('_table.adm.userobject.saveUserObject',{'objtype':that.userObjectPars.objtype,'metadata':metadata,'data':data,table:that.userObjectPars.table},function(result){dlg.close_action();metadata.setItem('pkey',result.getValue());that.resetMenuData();});};genro.dev.userObjectDialog(instanceCode?'Save '+this.userObjectPars.objtype+' '+instanceCode:'Save '+this.newcaption,datapath,saveCb);},gnrwdg_loadObject:function(userObjectId,firstLoad){this.onLoadingObject(userObjectId,firstLoad);if(userObjectId=='__newobj__'){this.sourceNode.setRelativeData('#WORKSPACE.metadata',null);this.onLoadedObject(null,userObjectId,firstLoad);}else{var that=this;genro.serverCall('_table.adm.userobject.loadUserObject',{userObjectIdOrCode:userObjectId,objtype:this.userObjectPars.objtype,tbl:this.userObjectPars.table,flags:this.userObjectPars.flags},function(result){if(result){that.sourceNode.setRelativeData('#WORKSPACE.metadata',new gnr.GnrBag(result.attr));that.onLoadedObject(result,userObjectId,firstLoad);}else{var currfavorite=that.getFavorite();if(currfavorite==userObjectId){genro.setInStorage("local",that.storageKey(),null);}}
that.checkFavorite();});}},gnrwdg_onLoadingObject:function(userObjectId,firstLoad){},gnrwdg_onLoadedObject:function(result,userObjectId,firstLoad){},});dojo.declare("gnr.widgets.SharedObject",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){sourceNode.gnrwdg.sharedKw=objectUpdate({},kw);kw.script="this.getParentNode().gnrwdg.handleSubscriptions(_triggerpars.kw.oldvalue);";var dc=sourceNode._('dataController',kw);sourceNode.gnrwdg.handleSubscriptions();return dc;},gnrwdg_handleSubscriptions:function(old_shared_id){var sharedKw=this.sourceNode.evaluateOnNode(this.sharedKw);var shared_id=objectPop(sharedKw,'shared_id');var path=objectPop(sharedKw,'shared_path');if(old_shared_id){genro.som.unregisterSharedObject(old_shared_id);}
if(shared_id&&path){genro.som.registerSharedObject(this.sourceNode.absDatapath(path),shared_id,sharedKw);}}});dojo.declare("gnr.widgets.ComboArrow",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,childSourceNode){var focusNode;var curNode=sourceNode;while(!focusNode){if(curNode.widget){focusNode=curNode.widget.focusNode;}
curNode=curNode.getParentBag().getParentNode()}
genro.dom.addClass(focusNode.parentNode,'comboArrowTextbox')
var iconClass=objectPop(kw,'iconClass')||'dijitArrowButtonInner';var box=sourceNode._('div',objectUpdate({'_class':'fakeButton',cursor:'pointer',width:'20px',position:'absolute',top:0,bottom:0,right:0,tabindex:-1},kw))
box._('div','iconNode',{_class:iconClass,position:'absolute',top:0,bottom:0,left:0,right:0})
return box;}});dojo.declare("gnr.widgets.PackageSelect",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,childSourceNode){kw.hasDownArrow=true;kw.onCreating=function(attributes){var that=this;genro.serverCall('app.dbStructure',{path:''},function(result){that._cbstore=result.getNodes().map(function(n){return{_pkey:n.label,pkg:n.label,caption:n.label,name:n.attr.caption};});});};kw.callback=function(cbkw){var _id=cbkw._id;var _querystring=cbkw._querystring;var cbfilter=function(n){return true};if(_querystring){_querystring=_querystring.slice(0,-1).toLowerCase();cbfilter=function(n){return(n.name&&n.name.toLowerCase().indexOf(_querystring)>=0)||n.pkg.indexOf(_querystring)>=0;};}else if(_id){cbfilter=function(n){return n._pkey==_id;}}
return{headers:'pkg:Pkgid,name:Name',data:this.sourceNode._cbstore.filter(cbfilter)}};return sourceNode._('CallbackSelect',kw);}});dojo.declare("gnr.widgets.TableSelect",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,childSourceNode){kw.hasDownArrow=true;if(kw.pkg){kw.pkg=kw.pkg.replace('^','=');}
kw.onCreating=function(attributes){var that=this;genro.serverCall('app.getTablesTree',{},function(result){that._cbstore=result;});};kw.callback=function(cbkw){var currentPkg=this.sourceNode.getAttributeFromDatasource('pkg');var tblmapcb=function(n){var caption=currentPkg?n.label:n.attr.tableid;return{_pkey:n.attr.tableid,tbl:n.attr.tableid,pkg:n.attr.tableid.split('.')[1],name:caption,caption:caption,pkeyField:n.attr.tableid};};var data;if(currentPkg){data=this.sourceNode._cbstore.getItem(currentPkg).getNodes();}else{data=[];this.sourceNode._cbstore.values().forEach(function(pkgcontent){data=data.concat(pkgcontent.getNodes());});}
data=data.map(tblmapcb);var _id=cbkw._id;var _querystring=cbkw._querystring;var cbfilter=function(n){return true};if(_querystring){_querystring=_querystring.slice(0,-1).toLowerCase();cbfilter=function(n){return n.name.toLowerCase().indexOf(_querystring)>=0||n.tbl.indexOf(_querystring)>=0;};}else if(_id){cbfilter=function(n){return n._pkey==_id;}}
return{headers:'tbl:Table,name:Name,pkeyField:Pkey',data:data.filter(cbfilter)}};return sourceNode._('CallbackSelect',kw);}});dojo.declare("gnr.widgets.ComboMenu",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,childSourceNode){kw['modifiers']=kw['modifiers']||'*';kw['attachTo']=sourceNode.getParentBag().getParentNode();return sourceNode._('comboArrow')._('menu',kw);}});dojo.declare("gnr.widgets.MultiLineTextbox",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,childSourceNode){var tb=sourceNode._('textbox',kw);var tbNode=tb.getParentNode();var valuepath=tbNode.absDatapath(kw.value);tb._('comboArrow',{connect_onclick:function(){var curval=tbNode.widget.getValue();var dflt=curval?curval.replace(/\,/g,'\n'):null
genro.dlg.prompt(_T('Multiline value'),{widget:'simpleTextArea',wdg_height:'200px',wdg_margin_right:'10px',action:function(value){tbNode.setRelativeData(valuepath,value.replace(/\n/g,','));},dflt:dflt,onEnter:null});}});return tb;}});dojo.declare("gnr.widgets.CheckBoxText",gnr.widgets.gnrwdg,{checker:'checkbox',contentKwargs:function(sourceNode,attributes){return attributes;},createContent:function(sourceNode,kw,children){var value=objectPop(kw,'value');sourceNode.attr.value=value;var originalKwargs=objectUpdate({},kw);kw=sourceNode.evaluateOnNode(kw);var popup=objectPop(kw,'popup');var values=objectPop(kw,'values');var codeSeparator=objectPop(kw,'codeSeparator');var tb;var gnrwdg=sourceNode.gnrwdg;var has_code;gnrwdg.identifier=objectPop(kw,'identifier')
gnrwdg.labelAttribute=objectPop(kw,'labelAttribute')
gnrwdg._valuelabel=kw._valuelabel;gnrwdg.remoteValuesRpc=objectPop(kw,'remoteValues');gnrwdg.valuesCb=objectPop(kw,'valuesCb');gnrwdg.tree_extrakw=objectExtract(kw,'tree_*');var onOpening;if(codeSeparator!==false){codeSeparator=codeSeparator||':'}
if(values instanceof gnr.GnrBag){has_code=true;}else{has_code=(codeSeparator&&values)?values.indexOf(codeSeparator)>=0:false;}
if(!values){var table=objectPop(originalKwargs,'table');if(table||gnrwdg.remoteValuesRpc){var hierarchical=objectPop(kw,'hierarchical');var condition_kw=objectExtract(originalKwargs,'condition_*',null,hierarchical);var condition=objectPop(originalKwargs,'condition');var dbstore=objectPop(originalKwargs,'dbstore');var query_kw={};objectUpdate(query_kw,condition_kw)
query_kw.table=table;query_kw.order_by=objectPop(originalKwargs,'order_by')||condition_kw.order_by;if(hierarchical){popup=true;gnrwdg.hierarchical=hierarchical;gnrwdg.treestorepath=kw.treestorepath||'gnr.workspace._hierarchicalStores.'+(kw.nodeId||table.replace('.','_'));gnrwdg.checkedpath=gnrwdg.treestorepath+'_checkedpaths';query_kw.dbstore=dbstore;query_kw.related_kwargs=objectExtract(originalKwargs,'related_*');query_kw.condition=condition;query_kw.resolved=objectPop(kw,'resolved');query_kw.parent_id=objectPop(originalKwargs,'parent_id');query_kw.root_id=objectPop(originalKwargs,'root_id');query_kw.caption_field=originalKwargs.labelAttribute;query_kw.alt_pkey_field=objectPop(originalKwargs,'alt_pkey_field');gnrwdg.omitRoot=objectPop(kw,'omitRoot',true);}else{query_kw.caption_field=originalKwargs.labelAttribute;query_kw.where=condition;query_kw._storename=dbstore;query_kw.alt_pkey_field=objectPop(originalKwargs,'alt_pkey_field');kw.cols=kw.cols||1;}
for(var k in query_kw){sourceNode.attr['query_'+k]=query_kw[k];}
gnrwdg.query_kw=query_kw;values=sourceNode.gnrwdg.getRemoteValuesFromQuery();has_code=true;}else if(gnrwdg.valuesCb){popup=true;has_code=true;onOpening=function(){var v=funcApply(gnrwdg.valuesCb,null,sourceNode);gnrwdg.has_code=(codeSeparator&&v)?v.indexOf(codeSeparator)>=0:false;gnrwdg.setValues(v);}}}
var rootNode=sourceNode;var table_kw=objectExtract(kw,'table_*');if(popup){var textBoxId='placingTextbox_'+genro.getCounter();var tbkw={'value':has_code?value+'?_displayedValue':value,position:'relative',readOnly:true,nodeId:textBoxId};objectExtract(originalKwargs,'table,values,cols,identifier,labelAttribute,popup')
objectUpdate(tbkw,originalKwargs);tb=sourceNode._('textbox',tbkw);gnrwdg.textboxNode=tb.getParentNode();rootNode=tb._('comboArrow')._('tooltipPane',{placingId:textBoxId,onOpening:onOpening})._('div',{padding:'5px',overflow:'auto',max_height:'300px',min_width:'200px'});}else{table_kw['tooltip']=objectPop(kw,'tooltip');objectExtract(originalKwargs,'table,values,cols,identifier,labelAttribute,popup')
objectUpdate(table_kw,originalKwargs);}
gnrwdg.rootNode=rootNode;if(!gnrwdg.hierarchical){var tbl=rootNode._('table',table_kw)._('tbody')
var tblNode=tbl.getParentNode();gnrwdg.captionDict={};gnrwdg.valuesDict={};gnrwdg.tblNode=tblNode;gnrwdg.has_code=has_code;gnrwdg.codeSeparator=codeSeparator;gnrwdg.kw=objectUpdate({},kw);tblNode.attr.action=function(attr,cbNode,e){if(e.shiftKey&&attr.tag.toLowerCase()=='checkbox'){tblNode._value.walk(function(n){if(n.attr.tag=='checkbox'){n.widget.setAttribute('checked',cbNode.widget.checked);}});}
sourceNode.gnrwdg.onCheck();};}
gnrwdg.setValues(values);return popup?tb:tbl;},gnrwdg_setValues:function(values,kw){if(this.values==values){return;}
var gnrwdg=this;if(this.hierarchical){if(this.omitRoot){values=values.getItem('root');}
this.sourceNode.setRelativeData(this.treestorepath,values);if(!this.treeNode){this.createTreeCheckbox();}
var currval=this.sourceNode.getRelativeData(this.sourceNode.attr.value);var cb=function(){gnrwdg.setHierarchicalCheckedPaths(currval);};}
else{if(values instanceof gnr.GnrBag){var l=[];var identifier=this.identifier;var labelAttribute=this.labelAttribute;values.forEach(function(n){var k=n.label;var caption=n.label;if(identifier){k=n._value?n._value.getItem(identifier):n.attr[identifier];}
if(labelAttribute){caption=n._value?n._value.getItem(labelAttribute):n.attr[labelAttribute];}
l.push(k+':'+caption);},'static');values=l.join(',');}
this.values=values;this.createCheckers();cb=function(){gnrwdg.alignCheckedValues();gnrwdg.onCheck();}}
if(!this.sourceNode._isBuilding){cb();}else{this.sourceNode.watch('buildingNode',function(){return!gnrwdg.sourceNode._isBuilding;},function(){cb();},10);}},gnrwdg_createTreeCheckbox:function(){var valuepath=this.sourceNode.attr.value.replace('^','');var treekw={storepath:this.treestorepath,hideValues:true,identifier:'treeIdentifier',labelAttribute:'caption',selectedLabelClass:'',_class:'pickerCheckboxTree',checked_pkey:valuepath,checkedPaths:this.checkedpath,checked_caption:valuepath+'?_displayedValue',onChecked:true};objectUpdate(treekw,this.tree_extrakw);var tree=this.rootNode._('tree',treekw);this.treeNode=tree.getParentNode();},gnrwdg_catch_condition:function(value,kw,trigger_reason){this.setValues(this.getRemoteValuesFromQuery());},gnrwdg_cbgroupReason:function(){return'cbgroup_'+this.sourceNode._id;},gnrwdg_setHierarchicalCheckedPaths:function(value){this._notrigger=true;this.sourceNode.setRelativeData(this.checkedpath,null,null,null,this.cbgroupReason());if(value){var pathsFromPkeys=genro.serverCall('_table.'+this.query_kw.table+'.getHierarchicalPathsFromPkeys',{pkeys:value,related_kwargs:this.query_kw.related_kwargs,dbstore:this.query_kw.dbstore,parent_id:this.query_kw.parent_id,alt_pkey_field:this.query_kw.alt_pkey_field,_sourceNode:this.sourceNode});this.sourceNode.setRelativeData(this.checkedpath,pathsFromPkeys,null,null,this.cbgroupReason());}
this._notrigger=false;},gnrwdg_setValue:function(value,kw,trigger_reason){if(kw.reason==this.cbgroupReason()||this._notrigger){return;}
if(this.hierarchical){var inEditingGrid=this.sourceNode.grid?this.sourceNode.grid.gnrediting:false;if(kw.reason&&kw.reason.sourceNode==this.treeNode){return;}
if(!inEditingGrid){this.setHierarchicalCheckedPaths(value);}
return;}
this.alignCheckedValues();},gnrwdg_isValidValue:function(value){if(!value){return true;}
var valuesDict=this.valuesDict;return value.split(this.separator).every(function(c){return(c in valuesDict)});},gnrwdg_getLabelsFromValue:function(value){if(!value){return}
var valuesDict=this.valuesDict;return value.split(this.separator).map(function(c){return valuesDict[c]}).join(this.separator)},gnrwdg_getValue:function(){return this.sourceNode.getAttributeFromDatasource('value');},gnrwdg_getDisplayedValue:function(){if(this.hierarchical){return this.sourceNode.getRelativeData(this.sourceNode.attr.value+'?_displayedValue');}else{return this.has_code?this.sourceNode.getRelativeData(this.sourceNode.attr.value+'?_displayedValue'):this.sourceNode.getAttributeFromDatasource('value');}},gnrwdg_getRemoteValuesFromQuery:function(){if(this.hierarchical){return genro.serverCall('_table.'+this.query_kw.table+'.getHierarchicalData',objectUpdate({_sourceNode:this.sourceNode},this.query_kw))}else{var rpc=this.remoteValuesRpc||'app.getValuesString';return genro.serverCall(rpc,objectUpdate({_sourceNode:this.sourceNode},this.query_kw));}},gnrwdg_alignCheckedValues:function(){var sourceNode=this.sourceNode;var textvalue=sourceNode.getAttributeFromDatasource('value')||'';if(!this.isValidValue(textvalue)){return;}
var splitter=this.separator;var checkcodes=textvalue&&this.has_code;if(checkcodes){splitter=',';}
var values=splitStrip(textvalue,splitter);var v;var checker=this.gnr.checker;var compareCb=function(node,value){if(checkcodes){return node.attr._code==value;}
return node.attr.label.toLowerCase()==value.toLowerCase()};sourceNode._value.walk(function(n){if(n.attr.tag==checker){n.widget.setAttribute('checked',dojo.some(values,function(v){return compareCb(n,v)}));}});if(this.has_code){this.sourceNode.setRelativeData(this.sourceNode.attr.value+'?_displayedValue',this.getLabelsFromValue(textvalue),null,null,this.cbgroupReason())}},gnrwdg_createCheckers:function(){var values=this.values;var tblNode=this.tblNode;var kw=this.kw;var has_code=this.has_code;var codeSeparator=this.codeSeparator;kw=objectUpdate({},kw);tblNode._value.clear(true);if(!values){return;}
var defaultSep=values.indexOf('\n')>=0?'\n':',';this.separator=kw.separator||defaultSep;var valuelist=splitStrip(values,this.separator);var cols=objectPop(kw,'cols');if(valuelist[0][0]=='/'){cols=valuelist.shift();cols=parseInt(cols.slice(1))||1;}
var curr_row=tblNode._('tr',row_kw);var cell,cbpars,label,_code;var i=1;var colspan;var cell_kw=objectExtract(kw,'cell_*');var row_kw=objectExtract(kw,'row_*');var label_kw=objectExtract(kw,'label_*',null,true);var wdgtag=this.gnr.checker;var ghrwdg=this;ghrwdg.captionDict={};ghrwdg.valuesDict={};dojo.forEach(valuelist,function(v){if(v=='/'){curr_row=tblNode._('tr',row_kw);i=1;return;}
if(cols&&i>cols){i=1;curr_row=tblNode._('tr',row_kw);}
label=v;if(has_code){v=v.split(codeSeparator);_code=v[0];label=v[1];}
colspan=1;if(label.indexOf('\\')>=0){label=label.split('\\');colspan=parseInt(label[1]);label=label[0];}
var z=objectUpdate(cell_kw,{colspan:colspan});cell=curr_row._('td',z);cbpars={label:label,_code:_code};var key=_code||label;var value=label||_code;ghrwdg.captionDict[value]=key;ghrwdg.valuesDict[key]=value;if(kw.group){cbpars.group=kw.group;}
cell._(wdgtag,objectUpdate(cbpars,label_kw));i=i+colspan;})},gnrwdg_onCheck:function(){var sourceNode=this.sourceNode;var separator=this.separator;var has_code=this.has_code;var i=0;var labels=[];var codes=[];var rows=sourceNode.getValue().getItem('#0');var sourceNodes=dojo.query('.dijitCheckBoxInput',this.tblNode.domNode).map(function(n){return dijit.getEnclosingWidget(n).sourceNode});dojo.forEach(sourceNodes,function(cbNode){if(cbNode.widget.checked){if(has_code){codes.push(cbNode.attr._code);}
labels.push(cbNode.attr.label)}});var fkw={};if(this._valuelabel){fkw._valuelabel=this._valuelabel;}
if(has_code){fkw._displayedValue=labels.length?labels.join(separator):null;sourceNode.setRelativeData(sourceNode.attr.value,codes.length>0?codes.join(','):null,fkw,null,this.cbgroupReason(),null,{_updattr:true});}else{sourceNode.setRelativeData(sourceNode.attr.value,labels.length>0?labels.join(separator):null,fkw,null,this.cbgroupReason(),null,{_updattr:true});}},cell_onCreating:function(gridEditor,colname,colattr){colattr['popup']=true;colattr['onCreated']='this.widget.focusNode.focus()'},cell_onDestroying:function(sourceNode,gridEditor,editingInfo){var newAttr={};if(sourceNode._saved_attributes.field_getter!=sourceNode._saved_attributes.field){newAttr[sourceNode._saved_attributes.field_getter]=sourceNode.gnrwdg.getDisplayedValue();}
sourceNode.gnrwdg._notrigger=true;gridEditor.grid.collectionStore().updateRow(editingInfo.row,newAttr);sourceNode.gnrwdg._notrigger=false;}});dojo.declare("gnr.widgets.RadioButtonText",gnr.widgets.CheckBoxText,{checker:'radiobutton',contentKwargs:function(sourceNode,attributes){attributes.group=attributes.group||genro.getCounter();return attributes;}});dojo.declare("gnr.widgets.FieldsTree",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){return attributes;},createContent:function(sourceNode,kw,children){var table=objectPop(kw,'table');var trash=objectPop(kw,'trash');var box_kw=objectExtract(kw,'box_*');var box=sourceNode._('div',objectUpdate({_class:'fieldsTreeBox',_lazyBuild:true},box_kw));var explorerPath=objectPop(kw,'explorerPath');if(explorerPath){kw.explorerPath=sourceNode.absDatapath(explorerPath);}
if(trash){var trashKw={_class:'treeTrash'};trashKw.dropTarget=true;trashKw.dropTypes='trashable';trashKw.onDrop_trashable=function(dropInfo,data){var sourceNode=genro.src.nodeBySourceNodeId(dropInfo.dragSourceInfo._id);if(sourceNode&&sourceNode.attr.onTrashed){funcCreate(sourceNode.attr.onTrashed,'dropInfo,data',sourceNode)(dropInfo,data);}};sourceNode._('div',trashKw);}
genro.dev.fieldsTree(box,table,kw);return box;}})
dojo.declare("gnr.widgets.SlotBar",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var frameNode=sourceNode.getParentNode().getParentNode();var side=sourceNode.getParentNode().attr.region;var framePars=frameNode.attr;var sidePars=objectExtract(framePars,'side_*',true);var default_orientation=side?((side=='top')||(side=='bottom'))?'horizontal':'vertical':'horizontal';var orientation=attributes.orientation||default_orientation;attributes.orientation=orientation;var buildKw={};dojo.forEach(['table','row','cell','lbl'],function(k){buildKw[k]=objectExtract(attributes,k+'_*');buildKw[k]['_class']=(buildKw[k]['_class']||'')+' slotbar_'+k;});if(orientation=='horizontal'){if('height'in attributes){buildKw.cell['height']=objectPop(attributes,'height');}}else{if('width'in attributes){buildKw.cell['width']=objectPop(attributes,'width');}}
attributes['_class']=(attributes['_class']||'')+' slotbar  slotbar_'+orientation+' slotbar_'+side;var toolbar=objectPop(attributes,'toolbar');if(toolbar===true){toolbar='top';}
side=side||toolbar;if(side){attributes['side']=side;attributes['slotbarCode']=attributes['slotbarCode']||attributes['frameCode']+'_'+side;if(toolbar){attributes['_class']+=' slotbar_toolbar slotbar_toolbar_standard slotbar_toolbar_side_'+side;attributes['gradient_from']=attributes['gradient_from']||sidePars['gradient_from'];attributes['gradient_to']=attributes['gradient_to']||sidePars['gradient_to'];var css3Kw={'left':[0,'right'],'top':[-90,'bottom'],'right':[180,'left'],'bottom':[90,'top']};if(attributes.gradient_from||attributes.gradient_to){attributes['border_'+css3Kw[side][1]]=attributes['border_'+css3Kw[side][1]]||'1px solid '+attributes['gradient_from']||genro.dom.themeAttribute('toolbar','gradient_from','silver');attributes['gradient_deg']=css3Kw[side][0];}}}
buildKw.lbl['_class']=buildKw.lbl['_class']||'slotbar_lbl';buildKw.lbl_cell=objectExtract(buildKw.lbl,'cell_*');attributes['buildKw']=buildKw;return attributes;},createContent:function(sourceNode,kw,children){if(kw.closable){var pane=sourceNode.getParentNode();var bc=pane.widget.parentBorderContainer;bc.gnr.addClosableHandle(bc,pane,kw)}
var slots=objectPop(kw,'slots');var orientation=objectPop(kw,'orientation');var result=this['createContent_'+orientation](sourceNode,kw,kw.slotbarCode,slots,children);dojo.forEach(children._nodes,function(n){if(n.attr.tag=='slot'){children.popNode(n.label);}});return result;},createContent_horizontal:function(sourceNode,kw,slotbarCode,slots,children){var buildKw=objectPop(kw,'buildKw');var lblPos=objectPop(buildKw.lbl,'position')||'N';var table=sourceNode._('div',kw)._('table',buildKw.table)._('tbody');var rlabel;if(lblPos=='T'){rlabel=table._('tr');}
var r=table._('tr',buildKw.row);if(lblPos=='B'){rlabel=table._('tr');}
var attr,cell,slotNode,slotValue,slotKw,slotValue;var children=children||new gnr.GnrBag();var that=this;var attr,kwLbl,lbl,labelCell,k;var slotArray=splitStrip(slots);var counterSpacer=dojo.filter(slotArray,function(s){return s=='*';}).length;var spacerWidth=counterSpacer?100/counterSpacer:100;var cellKwLbl=buildKw.lbl_cell;dojo.forEach(slotArray,function(slot){if(rlabel){labelCell=rlabel._('td',cellKwLbl);}else if(lblPos=='L'){cellKwLbl['width']=cellKwLbl['width']||'1px';labelCell=r._('td',cellKwLbl);}
if(slot=='*'){r._('td',{'_class':'slotbar_elastic_spacer',width:spacerWidth+'%'});return;};if(slot==parseInt(slot)){r._('td')._('div',{width:slot+'px'});return;};if(slot=='|'){r._('td')._('div',{_class:'slotbar_spacer'});return;};cell=r._('td',objectUpdate({_slotname:slot},buildKw.cell));if(lblPos=='R'){cellKwLbl['width']=cellKwLbl['width']||'1px';labelCell=r._('td',cellKwLbl);};slotNode=children.popNode(slot);if(!that['slot_'+slot]&&slotNode){if(slotNode.attr.tag=='slot'){slotValue=slotNode.getValue();}else{slotValue=new gnr.GnrBag({'slot':slotNode});}
if(slotValue instanceof gnr.GnrBag){k=0;slotValue.forEach(function(n){attr=n.attr;kwLbl=objectExtract(attr,'lbl_*');lbl=objectPop(attr,'lbl');cell.setItem(n.label,n._value,n.attr);if((k==0)&&labelCell){kwLbl=objectUpdate(objectUpdate({},buildKw.lbl),kwLbl);labelCell._('div',objectUpdate({'innerHTML':lbl,'text_align':'center'},kwLbl));}
k++;});}}
slotKw=objectExtract(kw,slot+'_*');if(slotKw.width){cell.getParentNode().attr['width']=slotKw.width;slotKw.width='100%';}
if(slotKw.text_align){cell.getParentNode().attr['text_align']=slotKw.text_align;}
if(cell.len()==0){if(that['slot_'+slot]){slotValue=objectPop(kw,slot);lbl=objectPop(slotKw,'lbl');kwLbl=objectExtract(slotKw,'lbl_*');kwLbl=objectUpdate(objectUpdate({},buildKw.lbl),kwLbl);that['slot_'+slot](cell,slotValue,slotKw,kw.frameCode);if(labelCell){labelCell._('div',objectUpdate({'innerHTML':lbl,'text_align':'center'},kwLbl));}}else{var textSlot=kw[slot];if(textSlot){cell.setItem('div_0',null,objectUpdate({innerHTML:textSlot,tag:'div'},objectExtract(kw,slot+'_*')));}}}});return r;},createContent_vertical:function(sourceNode,kw,slotbarCode,slots,children){var buildKw=objectPop(kw,'buildKw');var lblPos=objectPop(buildKw.lbl,'position')||'N';var table=sourceNode._('div',kw)._('table',buildKw.table)._('tbody');var attr,row,cell,slotNode,slotValue,slotKw,slotValue;var children=children||new gnr.GnrBag();var that=this;var attr,kwLbl,lbl,labelCell,k;var slotArray=splitStrip(slots);var cellKwLbl=buildKw.lbl_cell;dojo.forEach(slotArray,function(slot){if(slot=='*'){table._('tr');return;}
if(slot=='|'){table._('tr',{'height':'1px'})._('td')._('div',{_class:'slotbar_spacer'});return;}
if(slot==parseInt(slot)){table._('tr',{height:slot+'px'});return;}
row=table._('tr',buildKw.row)
cell=row._('td',objectUpdate({_slotname:slot,position:'relative'},buildKw.cell));slotNode=children.popNode(slot);if(slotNode){slotValue=slotNode.getValue();if(slotValue instanceof gnr.GnrBag){k=0;slotValue.forEach(function(n){attr=n.attr;kwLbl=objectExtract(attr,'lbl_*');lbl=objectPop(attr,'lbl');cell.setItem(n.label,n._value,n.attr);k++;});}
slotKw=objectUpdate({},slotNode.attr);}else{slotKw={};}
objectExtract(slotKw,'tag,_childname')
slotKw=objectUpdate(slotKw,objectExtract(kw,slot+'_*'));if(slotKw.height){row.getParentNode().attr['height']=slotKw.height;slotKw.height='100%';}
if(cell.len()==0&&(that['slot_'+slot])){slotValue=objectPop(kw,slot);lbl=objectPop(slotKw,'lbl');kwLbl=objectExtract(slotKw,'lbl_*');kwLbl=objectUpdate(objectUpdate({},buildKw.lbl),kwLbl);that['slot_'+slot](cell,slotValue,slotKw,kw.frameCode);if(labelCell){labelCell._('div',objectUpdate({'innerHTML':lbl,'text_align':'center'},kwLbl));}}});return table;},slot_searchOn:function(pane,slotValue,slotKw,frameCode){var div=pane._('div');var searchId=objectPop(slotKw,'nodeId')||frameCode+'_searchbox';var searchCode=objectPop(slotKw,'searchCode');if(searchCode){searchId=searchCode+'_searchbox';}
div._('SearchBox',{searchOn:slotValue,nodeId:searchId,datapath:'.searchbox',parentForm:false,'width':objectPop(slotKw,'width'),search_kw:slotKw});},slot_stackButtons:function(pane,slotValue,slotKw,frameCode){var scNode=objectPop(slotKw,'stackNode');if(scNode){scNode=pane.getParentNode().currentFromDatasource(scNode);}
if(!scNode){var stackNodeId=objectPop(slotKw,'stackNodeId');scNode=stackNodeId?genro.nodeById(stackNodeId):genro.getFrameNode(frameCode,'center');}
pane._('StackButtons',objectUpdate({stack:scNode},slotKw));},slot_parentStackButtons:function(pane,slotValue,slotKw,frameCode){slotKw['height']=slotKw['height']||'20px'
pane._('StackButtons',objectUpdate(objectUpdate({stack:pane.getParentNode().attributeOwnerNode('tag','StackContainer')},slotKw)));},slot_fieldsTree:function(pane,slotValue,slotKw,frameCode){var table=objectPop(slotKw,'table');table=pane.getParentNode().currentFromDatasource(table);var checkPermissions=objectPop(slotKw,'checkPermissions');var dragCode=objectPop(slotKw,'dragCode');var treeKw=objectExtract(slotKw,'tree_*')||{};treeKw.dragCode=dragCode;slotKw.text_align='left';var currRecordPath=objectPop(slotKw,'currRecordPath');var explorerPath=objectPop(slotKw,'explorerPath');var slot=pane._('div',slotKw);slot._('FieldsTree',objectUpdate({table:table,trash:true,currRecordPath:currRecordPath,explorerPath:explorerPath,checkPermissions:checkPermissions},treeKw));},slot_count:function(pane,slotValue,slotKw,frameCode){var row=pane._('table',{datapath:'.count',nodeId:frameCode+'_countbox',_class:'countBox'})._('tbody')._('tr');row._('td')._('div',{innerHTML:'^.shown',_class:'countBoxPartial'});row._('td')._('div',{innerHTML:'^.total',_class:'countBoxTotal'});},slot_messageBox:function(pane,slotValue,slotKw,frameCode){var mbKw=objectUpdate({duration:1000,delay:2000},slotKw);var subscriber=objectPop(mbKw,'subscribeTo');var default_delay=objectPop(mbKw,'delay');var default_duration=objectPop(mbKw,'duration');mbKw['subscribe_'+subscriber]=function(){var kwargs=arguments[0];var domNode=this.domNode;var sound=objectPop(kwargs,'sound');var duration=objectPop(kwargs,'duration')||default_duration;var delay=objectPop(kwargs,'delay')||default_delay;if(sound){genro.playSound(sound);}
var message=objectPop(kwargs,'message');var msgnode=document.createElement('span');msgnode.innerHTML=message;genro.dom.style(msgnode,kwargs);domNode.appendChild(msgnode);var customOnEnd=kwargs.onEnd;genro.dom.effect(domNode,'fadeout',{duration:duration,delay:delay,onEnd:function(){domNode.innerHTML=null;if(customOnEnd){customOnEnd();}}});};pane._('span',mbKw);},slot_dashboardSaver:function(pane,slotValue,slotKw,frameCode){var kw={title:_T('Save as dashboard item'),iconClass:'iconbox case',action:function(evt){var dashboardRoot=this.attributeOwnerNode('_dashboardRoot');if(dashboardRoot){dashboardRoot.publish('saveDashboard');}}};pane._('slotButton',objectUpdate(kw,slotKw));}});dojo.declare("gnr.widgets.SelectionStore",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){if('name'in attributes){attributes['_name']=objectPop(attributes,'name');}
if('content'in attributes){attributes['_content']=objectPop(attributes,'content');}
attributes.columns=attributes.columns||'==gnr.getGridColumns(this);';attributes.sum_columns=attributes.sum_columns||'==this.store.getSumColumns();';attributes.method=attributes.method||'app.getSelection';if(!('checkPermissions'in attributes)){attributes.checkPermissions=true;}
if('chunkSize'in attributes&&!('selectionName'in attributes)){attributes['selectionName']='*';}
return attributes;},createContent:function(sourceNode,kw,children){var chunkSize=objectPop(kw,'chunkSize',0);var storeType=objectPop(kw,'storeType')||(chunkSize?'VirtualSelection':'Selection');kw.row_count=chunkSize;var identifier=objectPop(kw,'_identifier')||'_pkey';var _onError=objectPop(kw,'_onError');var deleteRows=objectPop(kw,'deleteRows');var allowLogicalDelete=objectPop(kw,'allowLogicalDelete');var linkedWidgetNode=objectPop(kw,'linkedWidgetNode');var skw=objectUpdate({_cleared:false},kw);skw.script="if(_cleared){this.store.clear();}else{if(this.form && this.form._reloadingAfterSave && !this.store.hasChanges()){return;}this.store.loadData();}";objectExtract(skw,'nodeId,_onCalling,_onResult,columns')
var selectionStarter=sourceNode._('dataController',skw).getParentNode();objectExtract(kw,'_onStart,_cleared,_fired,_delay')
var v;for(var k in kw){v=kw[k];if(typeof(v)=='string'){if(v[0]=='^'){kw[k]=v.replace('^','=');}}}
if(!'_POST'in kw){kw['_POST']=true;}
var selectionStore=sourceNode._('dataRpc',kw);var rpcNode=selectionStore.getParentNode();rpcNode.attr['_onError']=function(error,originalKwargs){if(_onError){funcApply(_onError,{error:error,kwargs:originalKwargs},rpcNode);}
rpcNode.store.clear();rpcNode.store.gridBroadcast(function(grid){grid.sourceNode.publish('loadingData',{loading:false});});};var storeKw={'identifier':identifier,'chunkSize':kw.row_count,'storeType':storeType,'unlinkdict':kw.unlinkdict,'deletemethod':kw.deletemethod,'allowLogicalDelete':allowLogicalDelete,'deleteRows':deleteRows,'linkedWidgetNode':linkedWidgetNode};if('startLocked'in kw){storeKw.startLocked=kw.startLocked;}
var storeInstance=new gnr.stores[storeType](rpcNode,storeKw);rpcNode.store=storeInstance;selectionStarter.store=storeInstance;sourceNode.gnrwdg.store=storeInstance;return selectionStore;}});dojo.declare("gnr.widgets.BagStore",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){if(kw.data){kw.selfUpdate=kw.selfUpdate||false;kw.script="this.store.loadData(data,selfUpdate);";}
var identifier=objectPop(kw,'_identifier')||'_pkey';var storeType=objectPop(kw,'storeType')||'ValuesBagRows';var deleteRows=objectPop(kw,'deleteRows');var store=sourceNode._('dataController',kw);var storeNode=store.getParentNode();storeNode.store=new gnr.stores[storeType](storeNode,{identifier:identifier,deleteRows:deleteRows});return store;},onChangedView:function(){return;}});dojo.declare("gnr.stores._Collection",null,{messages:{delete_one:"!!You are about to delete the selected record.<br/>You can't undo this",delete_logical_one:"!!The record cannot be removed.<br/>It will be hidden instead.",delete_many:"!!You are about to delete $count records.<br/>You can't undo this",delete_logical_many:"!!You are about to delete $count records <br/> Some of them cannot be deleted but will be hidden instead.",unlink_one:"!!You are about to remove the selected record from current $master",unlink_many:"!!You are about to discard the selected $count records from current $master",archive_one:"!!You are about to set archiviation date in the selected record",archive_many:"!!You are about to set archiviation date in the selected $count records"},constructor:function(node,kw){this.storeNode=node;this.storepath=this.storeNode.absDatapath(this.storeNode.attr.storepath);var startData=this.storeNode.getRelativeData(this.storepath,true);this.locked=null;this.inherithLock=false;this.inheritProtect=false;var deleteRows=objectPop(kw,'deleteRows');if(deleteRows){this.deleteRows=funcCreate(deleteRows,'pkeys,protectPkeys',this);}
var startLocked='startLocked'in kw?objectPop(kw,'startLocked'):false;for(var k in kw){this[k]=kw[k];}
var that=this;var cb=function(){that.storeNode.subscribe('setLocked',function(v){that.setLocked(v);});var parentForm=that.storeNode.attr.parentForm===false?false:that.storeNode.getFormHandler();if(parentForm){that.inherithLock='inherithLock'in that.storeNode.attr?that.storeNode.attr.inherithLock:true;that.inheritProtect='inheritProtect'in that.storeNode.attr?that.storeNode.attr.inheritProtect:true;}
if(parentForm===false){startLocked=false;this.locked=false;}
else if(that.inherithLock&&parentForm){that.storeNode.registerSubscription('form_'+parentForm.formId+'_onDisabledChange',that,function(kwargs){this.setLocked(kwargs.locked);});}
dojo.subscribe('onPageStart',function(){startLocked=parentForm?parentForm.isDisabled():startLocked;that.setLocked(startLocked);});};genro.src.onBuiltCall(cb);},setNewStorepath:function(newstorepath){this.storeNode.attr.storepath=newstorepath;this.storepath=this.storeNode.absDatapath(this.storeNode.attr.storepath);var storepath=this.storepath;var that=this;this.gridBroadcast(function(grid){grid.sourceNode.attr.storepath=storepath;if(grid.gridEditor){grid.gridEditor.applyStorepath();}
grid.newDataStore();});},getSumColumns:function(){return;},clear:function(){this.storeNode.setRelativeData(this.storepath,new gnr.GnrBagNode(null,'',new gnr.GnrBag(),{}),null,null,'loadData');},gridBroadcast:function(cb){this.linkedGrids().forEach(cb);},setBlockingReason:function(reason,doset){this._blocking_reasons=this._blocking_reasons||{};if(doset=='toggle'){doset=!(reason in this._blocking_reasons);}
if(doset===true){this._blocking_reasons[reason]=true;}else if(doset===false){objectPop(this._blocking_reasons,reason);}},isEnabledStore:function(){this._blocking_reasons=this._blocking_reasons||{};return!objectNotEmpty(this._blocking_reasons)&&(this.hasVisibleClients()||this.loadInvisible);},hasVisibleClients:function(){if(this.linkedWidgetNode){return this.linkedWidgetNode.gnrwdg.isVisible();}
return this.linkedGrids().some(function(grid){return genro.dom.isVisible(grid.sourceNode);});},runQuery:function(cb,runKwargs){var result=this.storeNode.fireNode(runKwargs);if(result instanceof dojo.Deferred){result.addCallback(function(r){cb(r)});}else{result=cb(result);}
return result;},onLoading:function(){},onLoaded:function(result){this.storeNode.setRelativeData(this.storepath,result,null,null,'loadData');return result;},onChangedView:function(){return;},loadData:function(){return;},onStartEditItem:function(form){this._editingForm=form;},onEndEditItem:function(form){this._editingForm=false;},currentPkeys:function(){console.warn('currentPkeys not implemented in this store',this);return null;},setLocked:function(value){if(value=='toggle'){value=!this.locked;}
this.locked=value;var parentForm=this.storeNode.getFormHandler();var parentProtect=(parentForm&&this.inheritProtect)?parentForm.isProtectWrite():false;this.storeNode.setRelativeData('.locked',value);this.storeNode.setRelativeData('.disabledButton',value||parentProtect);this.storeNode.publish('onLockChange',{'locked':this.locked});},deleteRows:function(pkeys,protectPkeys){return;},duplicateRows:function(pkeys){},archiveRows:function(){console.error('archiveRows not implemented')},archiveAsk:function(pkeys,protectPkeys,cb){var count=pkeys.length;var cb=cb||this.archiveRows;if(count==0){return;}
var dlg=genro.dlg.quickDialog('Alert',{_showParent:true,width:'280px'});var msg=count==1?'one':'many';dlg.center._('div',{innerHTML:_T(this.messages['archive_'+msg]).replace('$count',count),text_align:'center',_class:'alertBodyMessage'});var that=this;var slotbar=dlg.bottom._('slotBar',{slots:'*,cancel,archive',action:function(){dlg.close_action();if(this.attr.command=='archiveRows'){cb.call(that,pkeys,protectPkeys,genro.getData('gnr._dev.archiveAsk.date'));}}});slotbar._('button','cancel',{label:_T('Cancel'),command:'cancel'});var btnattr={label:_T('Confirm'),command:'archiveRows'};var fb=genro.dev.formbuilder(dlg.center,1,{border_spacing:'1px',width:'100%',margin_bottom:'12px'});genro.setData('gnr._dev.archiveAsk.date',genro.getData('gnr.workdate'));fb.addField('dateTextBox',{value:'^gnr._dev.archiveAsk.date',width:'8em',lbl_text_align:'right',lbl:_T('Date'),lbl_color:'#444',parentForm:false});if(count>1){fb.addField('numberTextBox',{value:'^gnr._dev.archiveAsk.count',width:'5em',lbl_text_align:'right',lbl:_T('N.Records'),lbl_color:'#444',parentForm:false});btnattr['disabled']='==_count!=_tot;';btnattr['_tot']=count;fb._('data',{path:'gnr._dev.archiveAsk.count',content:null});btnattr['_count']='^gnr._dev.archiveAsk.count';}
slotbar._('button','archive',btnattr);dlg.show_action();},deleteAsk:function(pkeys,protectPkeys,deleteCb){var count=pkeys.length;var deleteCb=deleteCb||this.deleteRows;if(count==0){return;}
var dlg=genro.dlg.quickDialog('Alert',{_showParent:true,width:'280px'});var msg=count==1?'one':'many';var del_type,master;if(this.unlinkdict){del_type='unlink';master=_T(this.unlinkdict.one_name);}else{del_type='delete';master='';if(this.allowLogicalDelete&&protectPkeys){del_type='delete_logical';}}
dlg.center._('div',{innerHTML:_T(this.messages[del_type+'_'+msg]).replace('$count',count).replace('$master',master),text_align:'center',_class:'alertBodyMessage'});var that=this;var slotbar=dlg.bottom._('slotBar',{slots:'*,cancel,delete',action:function(){dlg.close_action();if(this.attr.command=='deleteRows'){deleteCb.call(that,pkeys,protectPkeys);}}});slotbar._('button','cancel',{label:_T('Cancel'),command:'cancel'});var btnattr={label:_T('Confirm'),command:'deleteRows'};if(count>1){var fb=genro.dev.formbuilder(dlg.center,1,{border_spacing:'1px',width:'100%',margin_bottom:'12px'});fb.addField('numberTextBox',{value:'^gnr._dev.deleteask.count',width:'5em',lbl_text_align:'right',lbl:_T('Records to delete'),lbl_color:'#444',parentForm:false});btnattr['disabled']='==_count!=_tot;';btnattr['_tot']=count;fb._('data',{path:'gnr._dev.deleteask.count',content:null});btnattr['_count']='^gnr._dev.deleteask.count';}
slotbar._('button','delete',btnattr);dlg.show_action();},onCounterChanges:function(counterField,changes){},getData:function(filtered){var result=this.storeNode.getRelativeData(this.storepath);if(!result){result=new gnr.GnrBag();this.storeNode.setRelativeData(this.storepath,result,null,null,'loadData');}
if(!(filtered&&this._filtered)){return result;}
var filteredResult=new gnr.GnrBag();var fn;this._filtered.forEach(function(nodeIdx){fn=result.getNode('#'+nodeIdx);filteredResult.setItem(fn.label,fn._value instanceof gnr.GnrBag?fn._value.deepCopy():fn._value,objectUpdate({},fn.attr));});return filteredResult;},getItems:function(){return this.getData()._nodes;},len:function(filtered){if(filtered&&this._filtered){return this._filtered.length;}
return this.getItems().length||0;},sum:function(field){},indexByCb:function(cb,backward){var n=this.len(true);for(var i=0;i<n;i++){var k_i=backward?n-i:i;if(cb(this.rowByIndex(k_i))){return k_i;}}
return-1;},absIndex:function(idx,reverse){if(!this._filtered){return idx;}
return reverse?dojo.indexOf(this._filtered,idx):this._filtered[idx];},getKeyFromIdx:function(idx,filtered){var data=this.getData();if(!data){return;}
var item;data=data.getNodes();if((idx<0)||(idx>(data.length-1))){return null;}
if(filtered&&this._filtered){idx=this._filtered[idx];}
return this.keyGetter(data[idx]);},getIdxFromPkey:function(pkey,fiteredIndex){var result=-1;var data=this.getData();var that=this;if(pkey&&data){data=data.getNodes();var k=-1;dojo.some(data,function(n){k++;if(that.keyGetter(n)==pkey){result=k;return true;}});if(fiteredIndex!==false&&result>=0&&this._filtered){return this._filtered.indexOf(result);}
return result;}},rowBagNodeByIdentifier:function(pkey){var idx=this.getIdxFromPkey(pkey);if(idx>=0){return this.itemByIdx(idx);}},rowByIndex:function(idx,bagFields){var rowdata={};var node=this.itemByIdx(idx);if(node){this.setExternalChangeClasses(node);return this.rowFromItem(node,bagFields);}
return rowdata;},setExternalChangeClasses:function(node){},filterToRebuild:function(value){this._filterToRebuild=value;},invalidFilter:function(){return this._filterToRebuild;},resetFilter:function(){return this._filtered=null;},isFiltered:function(){return this._filtered!==null;},compileFilter:function(grid,value,filterColumn,colType){var cbsearch;var cb;if(!isNullOrBlank(value)){if(colType in{'A':null,'T':null}){var regexp=new RegExp(value,'i');cbsearch=function(rowdata,index,array){return regexp.test(grid.getRowText(index,' ',filterColumn.split('+'),true));};}else{var toSearch=/^(\s*)([\<\>\=\!\#]+)(\s*)(.+)$/.exec(value);if(toSearch){var val;var op=toSearch[2];if(op=='='){op='==';}
if((op=='!')||(op=='#')){op='!=';}
if(colType in{'R':null,'L':null,'I':null,'N':null}){val=dojo.number.parse(toSearch[4]);}else if(colType=='D'){val=dojo.date.locale.parse(toSearch[4],{formatLength:"short",selector:'date'});}else if(colType=='DH'){val=dojo.date.locale.parse(toSearch[4],{formatLength:"short"});}
cbsearch=function(rowdata,index,array){return genro.compare(op,rowdata[filterColumn],val);};}}}
if(grid.filterManager&&grid.filterManager.hasActiveFilter()){cb=function(rowdata,index,array){return grid.filterManager.isInFilterSet(rowdata)&&(cbsearch?cbsearch(rowdata,index,array):true);};}else{cb=cbsearch;}
return cb;},createFiltered:function(grid,currentFilterValue,filterColumn,colType){var cb=this.compileFilter(grid,currentFilterValue,filterColumn,colType);if(!cb&&!grid.excludeListCb){this._filtered=null;return null;}
var filtered=[];var filteringList=null;if(grid.excludeListCb){filteringList=grid.excludeListCb.call(this.storeNode);}
var filteringMode=grid.filteringMode||'exclude';var that=this;var sn=grid.sourceNode
sn.__evaluated_attrs=sn.evaluateOnNode(sn.attr)
dojo.forEach(this.getItems(),function(n,index,array){var rowdata=that.rowFromItem(n);var result=cb?cb.apply(sn,[rowdata,index,array]):true;var include;if(result){if(filteringMode=='exclude'){include=((!filteringList)||(dojo.indexOf(filteringList,rowdata[grid.excludeCol])==-1));}else if(filteringMode=='disabled'){include=true;}else{include=filteringList&&(dojo.indexOf(filteringList,rowdata[grid.excludeCol])>=0);}
if(include){filtered.push(index);}}});this._filtered=filtered;this._filterToRebuild=false;},linkedGrids:function(){if(this._linkedGrids){return this._linkedGrids;}
var result=[];var storeCode;var storeNodeId=this.storeNode.attr.nodeId;genro.src._main.walk(function(n){if(n.widget&&n.widget.selectionKeeper){storeCode=n.attr.store||n.attr.nodeId;if(storeCode+'_store'==storeNodeId){result.push(n.widget);}}},'static');this._linkedGrids=result;return result;},hasErrors:function(){},hasChanges:function(){}});dojo.declare("gnr.stores.BagRows",gnr.stores._Collection,{loadData:function(data,selfUpdate){if(selfUpdate){dojo.forEach(this.linkedGrids(),function(grid){grid.selectionKeeper('save');grid._batchUpdating=true;});}
data=data?data.deepCopy():new gnr.GnrBag();this.storeNode.setRelativeData(this.storepath,data,null,null,'loadData');if(this.sortedBy){this.sort();}
if(selfUpdate){dojo.forEach(this.linkedGrids(),function(grid){grid.applyFilter(true);grid._batchUpdating=false;grid.restoreSelectedRows();});}},getRowByIdx:function(idx){return;},getItems:function(){var data=this.getData();return data?data.getNodes():[];},deleteRows:function(pkeys,protectPkeys){var data=this.getData()
this.gridBroadcast(function(grid){grid.selection.unselectAll()});var that=this;pkeys.forEach(function(n){data.popNode(n);});this.linkedGrids().forEach(function(grid){grid.sourceNode.publish('onDeletedRows',{pkeys:pkeys,protectPkeys:protectPkeys})});},itemByIdx:function(idx){var item=null;if(idx>=0){idx=this.absIndex(idx);var nodes=this.getItems();if(idx<=this.len()){item=nodes[idx];}}
return item;},updateRow:function(idx,updDict){var rowNode=this.itemByIdx(idx);if(rowNode){return this.updateRowNode(rowNode,updDict);}},filteredRowsIndex:function(filteringObject){var items=this.getItems();var r;var result=[];for(var i=0;i<items.length;i++){if(objectIsContained(filteringObject,this.rowFromItem(items[i]))){result.push(i);}};return result;},hasChanges:function(){var data=this.getData()
if(data.getNodeByAttr('_newrecord')){return true}
return this.getData().getNodeByAttr('_loadedValue')!=null;},hasErrors:function(){return this.getData().getNodeByAttr('_validationError')!=null;}});dojo.declare("gnr.stores.ValuesBagRows",gnr.stores.BagRows,{rowFromItem:function(item,bagFields){var result=objectUpdate({},item.attr);var value=item.getValue();if(value){var v;value.forEach(function(n){v=n.getValue();if(v instanceof gnr.GnrBag){v=bagFields?v:null;}
result[n.label]=v;})}
result[this.identifier]=isNullOrBlank(result[this.identifier])?item.label:result[this.identifier];return result;},updateRowNode:function(rowNode,updDict){var rowData=rowNode.getValue();var idx=this.getData().index(rowNode.label);for(var k in updDict){var n=rowData.getNode(k,'static');if(!n){rowData.setItem(k,null,null,{doTrigger:false});}
rowData.setItem(k,updDict[k],null,{doTrigger:{editedRowIndex:idx},lazySet:true});}},keyGetter:function(n){return this.rowFromItem(n)[this.identifier];},sort:function(sortedBy){this.sortedBy=sortedBy||this.sortedBy;if(!this.sortedBy){return;}
var data=this.getData();var sl=[];dojo.forEach(this.sortedBy.split(','),function(n){sl.push(n);});sl=sl.join(',');data.sort(sl);},onCounterChanges:function(counterField,changes){},sum:function(field){return this.getData().sum('#v.'+field);}});dojo.declare("gnr.stores.AttributesBagRows",gnr.stores.BagRows,{rowFromItem:function(item,bagFields){var result=objectUpdate({},item.attr);if(!bagFields){for(var k in result){if(isBag(result[k])){objectPop(result,k);}}}
result[this.identifier]=isNullOrBlank(result[this.identifier])?item.label:result[this.identifier];return result;},updateRowNode:function(rowNode,updDict){var idx=this.getData().index(rowNode.label);rowNode.updAttributes(updDict,{editedRowIndex:idx});},keyGetter:function(n){return n.attr[this.identifier];},sort:function(sortedBy){this.sortedBy=sortedBy||this.sortedBy;if(!this.sortedBy){return;}
var data=this.getData();var sl=[];dojo.forEach(this.sortedBy.split(','),function(n){if(n.slice(0,3)!='#a.'){n='#a.'+n;}
sl.push(n);});sl=sl.join(',');data.sort(sl);},sum:function(field){return this.getData().sum('#a.'+field);}});dojo.declare("gnr.stores.RpcBase",gnr.stores.AttributesBagRows,{askToDelete:true,loadData:function(){var that=this;if(!this.isEnabledStore()){this.storeNode.watch('isEnabledStore',function(){return that.isEnabledStore();},function(){that.loadingDataDo();});return;}
return this.loadingDataDo();},loadingDataDo:function(){var that=this;this.loadingData=true;this.gridBroadcast(function(grid){grid.selectionKeeper('save');grid.sourceNode.publish('loadingData',{loading:true});});var cb=function(result){that.resetFilter();that.onLoaded(result);that.loadingData=false;that.gridBroadcast(function(grid){grid.sourceNode.publish('loadingData',{loading:false});});};this.onLoading();return this.runQuery(cb);},onDeletedRows:function(pkeys){return this.loadData()},deleteRows:function(files,protectPkeys){var that=this;var unlinkfield=this.unlinkdict?this.unlinkdict.field:null;var rpcdelete=this.deletemethod;genro.assert(rpcdelete,'missing delete rpc')
genro.serverCall(rpcdelete,{files:files},function(result){that.onDeletedRows(files);},null,'POST');},});dojo.declare("gnr.stores.FileSystem",gnr.stores.RpcBase,{askToDelete:true,deleteRows:function(files,protectPkeys){var that=this;var unlinkfield=this.unlinkdict?this.unlinkdict.field:null;var rpcdelete=this.deletemethod||'app.deleteFileRows';genro.serverCall(rpcdelete,{files:files},function(result){that.onDeletedRows(files);},null,'POST');}});dojo.declare("gnr.stores.Selection",gnr.stores.AttributesBagRows,{askToDelete:true,constructor:function(){var liveUpdate=this.storeNode.attr.liveUpdate||'LOCAL';var liveUpdateExcludeReason=this.storeNode.getAttributeFromDatasource('liveUpdateExcludeReason');if(liveUpdate=='NO'){return;}
var that=this;this.pendingChanges=[];this.lastLiveUpdate=new Date()
this._editingForm=false;this.loadInvisible=this.storeNode.getAttributeFromDatasource('loadInvisible');this.liveUpdateDelay=this.storeNode.getAttributeFromDatasource('liveUpdateDelay');this.externalLiveUpdateDelay=this.storeNode.getAttributeFromDatasource('externalLiveUpdateDelay');this.liveUpdateUnattended=this.storeNode.getAttributeFromDatasource('liveUpdateUnattended');var cb=function(){that.storeNode.registerSubscription('dbevent_'+that.storeNode.attr.table.replace('.','_'),that,function(kw){var from_page_id=kw.changeattr.from_page_id;var dbevent_reason=kw.changeattr.dbevent_reason;if(liveUpdateExcludeReason&&liveUpdateExcludeReason==dbevent_reason){return;}
if(liveUpdate=='PAGE'){if(genro.page_id!=from_page_id){return;}}
if(liveUpdate=='LOCAL'){if(!genro.isLocalPageId(from_page_id)){return;}}
if(that.freezedStore()){return;}
var isExternal=from_page_id!=genro.page_id;dojo.forEach(kw.changelist,function(c){c._isExternal=isExternal;that.pendingChanges.push(c);});that.storeNode.watch('externalChangesDisabled',function(){if(that._editingForm||that.loadInvisible){return genro.dom.isWindowVisible();}
if(that.storeNode.form&&that.storeNode.form.opStatus){return false;}
var currDelay=isExternal?that.externalLiveUpdateDelay:that.liveUpdateDelay;var doUpdate=currDelay&&that.lastLiveUpdate?(new Date()-that.lastLiveUpdate)/1000>currDelay:true;if(doUpdate&&!that.liveUpdateUnattended){doUpdate=(genro._lastUserEventTs>that.lastLiveUpdate)||((new Date()-that.lastLiveUpdate)/1000)>60;}
return that.hasVisibleClients()&&doUpdate;},function(){that.lastLiveUpdate=new Date();var changelist=that.pendingChanges;that.pendingChanges=[];if(changelist.length>0){if(that.storeNode.attr.groupByStore){that.loadData();}else{that.onExternalChange(changelist);}}});});};genro.src.onBuiltCall(cb);},getSumColumns:function(){var sum_columns=this.storeNode.getRelativeData('.sum_columns');sum_columns=sum_columns?sum_columns.split(','):[];this.linkedGrids().forEach(function(grid){if(grid.sourceNode._serverTotalizeColumns&&!grid.gridEditor){for(var field in grid.sourceNode._serverTotalizeColumns){arrayPushNoDup(sum_columns,field);}}});return sum_columns.join(',');},loadData:function(runKwargs){var that=this;this.pendingLoading=true;if(!(this.isEnabledStore())){this.storeNode.watch('isEnabledStore',function(){return that.isEnabledStore();},function(){that.loadingDataDo(runKwargs);});return;}
this.loadingDataDo(runKwargs);},loadingDataDo:function(runKwargs){var that=this;this.loadingData=true;this.gridBroadcast(function(grid){grid.sourceNode.publish('loadingData',{loading:true});});var cb=function(result){that.resetFilter();that.onLoaded(result);that.loadingData=false;that.gridBroadcast(function(grid){grid.sourceNode.publish('loadingData',{loading:false});});};this.onLoading();return this.runQuery(cb,runKwargs);},cleanColumns:function(cols){var result={};if(!cols){return;}
cols.split(',').forEach(function(n){n=n.toLowerCase();if(n.indexOf(' as ')>=0){n=n.split(' as ')[1]}else{n=n.trim().split(' ')[0].replace('$','').replace(/\./g,'_').replace(/@/g,'_');}
result[n]=true;});return result;},onChangedView:function(){var data=this.getData();var n=this.len(true)-1;if(n>=0){var k=0;var dataColumns={};do{dataColumns=this.rowByIndex(k,true);k++;}while(k<=n&&('_newrecord'in dataColumns))
if('_newrecord'in dataColumns){return;}
gnr.getGridColumns(this.storeNode);var newColumns=this.cleanColumns(this.storeNode._currentColumns);var previousColumns=this.cleanColumns(this.storeNode._previousColumns)||{};var addedColumns=[];for(var k in newColumns){if(k in previousColumns){objectPop(previousColumns,k);}else{addedColumns.push(k);}}
if(addedColumns.length>0){this.loadData();}else if(this.storeNode.attr.groupByStore&&objectNotEmpty(previousColumns)){for(var k in previousColumns){if(!['_avg','_sum','_min','_max'].some(function(aggr){return k.endsWith(aggr);})){this.loadData();return;}}}}},currentPkeys:function(caption_field){var data=this.getData();var result=[];var r;data.forEach(function(n){r=n.attr;result.push(caption_field?{'pkey':r['_pkey'],'caption':r[caption_field]}:r['_pkey']);});return result;},freezedStore:function(){if(this.freezed){return true;}
var if_condition=this.storeNode.attr._if;if(if_condition){var if_result=funcApply('return '+if_condition,this.storeNode.currentAttributes(),this.storeNode);if(!if_result){return true;}}
return false;},onExternalChange:function(changelist){var eventdict={};var dbevt,pkeys,wasInSelection,willBeInSelection;var insOrUpdKeys=[];var delKeys=[];var data=this.getData();var that=this;if(!data){return;}
var isExternalDict={};dojo.forEach(changelist,function(change){if(change['dbevent']=='D'){if(dojo.indexOf(delKeys,change.pkey)<0){delKeys.push(change.pkey);}}else{if(dojo.indexOf(insOrUpdKeys,change.pkey)<0){insOrUpdKeys.push(change.pkey);if(change._isExternal){isExternalDict[change.pkey]=change._isExternal;}}
if(change.old_pkey&&change.old_pkey!=change.pkey){var changedNode=data.getNodeByAttr('_pkey',change.old_pkey);if(changedNode){changedNode.attr['_pkey']=change.pkey;}}}});if(insOrUpdKeys.length>0){var original_condition=this.storeNode.attr.condition;var newcondition=' ( $pkey IN :store_chpkeys ) ';var chpkeys=insOrUpdKeys;var condition=original_condition?original_condition+' AND '+newcondition:newcondition;if(this.freezedStore()){return;}
this.runQuery(function(result){willBeInSelection={};result.getValue().forEach(function(n){willBeInSelection[n.attr['_pkey']]=n;},'static');that.checkExternalChange(delKeys,insOrUpdKeys,willBeInSelection,isExternalDict);return result;},{store_chpkeys:chpkeys,condition:condition,applymethod:null});}else if(delKeys.length>0){this.checkExternalChange(delKeys,[],[],isExternalDict);}},onCounterChanges:function(counterField,changes){genro.serverCall('app.counterFieldChanges',{table:this.storeNode.attr.table,counterField:counterField,changes:changes});},checkExternalChange:function(delKeys,insOrUpdKeys,willBeInSelection,isExternalDict){var linkedGrids=this.linkedGrids();var selectedPkeysDict={};var selectedIndex,selectedPkey;var data=this.getData();dojo.forEach(linkedGrids,function(grid){genro.dom.removeClass(grid.sourceNode,'onExternalChanged');selectedIndex=grid.selection.selectedIndex;if(selectedIndex!=null&&selectedIndex>=0){selectedPkey=grid.rowIdByIndex(selectedIndex);selectedPkeysDict[selectedPkey]=selectedPkeysDict[selectedPkey]||[];selectedPkeysDict[selectedPkey].push(grid);}
grid._saved_selections=grid.selectionKeeper('save');});var changedRows={};var that=this;var toUpdate=false;var wasInSelectionNode,willBeInSelectionNode,pkey;this.externalChangedKeys=this.externalChangedKeys||{};var wasInSelectionCb=function(pkeys){var result={};data.forEach(function(n){if(dojo.indexOf(pkeys,n.attr._pkey)>=0){result[n.attr._pkey]=n;}},'static');return result;};var insOrUpdKeys_wasInSelection=wasInSelectionCb(insOrUpdKeys);var delKeys_wasInSelection=wasInSelectionCb(delKeys);var changeCount=objectSize(willBeInSelection)+objectSize(insOrUpdKeys_wasInSelection)+objectSize(delKeys_wasInSelection);var rt=this.reload_treshold||0.3;var sum_columns=this.storeNode.getAttributeFromDatasource('sum_columns');var applymethod=this.storeNode.getAttributeFromDatasource('applymethod');var fullReloadOnChange=this.storeNode.getAttributeFromDatasource('fullReloadOnChange');if(changeCount>0&&((changeCount>this.len()*rt)||sum_columns||fullReloadOnChange||applymethod)){this.loadData();return}
if(delKeys.length>0){for(pkey in delKeys_wasInSelection){toUpdate=true;data.popNode(delKeys_wasInSelection[pkey].label);}}
if(insOrUpdKeys.length>0){dojo.forEach(insOrUpdKeys,function(pkey){wasInSelectionNode=insOrUpdKeys_wasInSelection[pkey];willBeInSelectionNode=willBeInSelection[pkey];if(wasInSelectionNode){toUpdate=true;if(willBeInSelectionNode){var rowNode=data.getNodeByAttr('_pkey',willBeInSelectionNode.attr._pkey);var rowValue=rowNode.getValue('static');var newattr=objectUpdate({},willBeInSelectionNode.attr);if(pkey in isExternalDict){for(var attrname in willBeInSelectionNode.attr){changedRows[rowNode.attr._pkey]=rowNode;if(!isEqual(rowNode.attr[attrname],willBeInSelectionNode.attr[attrname])){if(rowValue instanceof gnr.GnrBag){var editedNode=rowValue.getNode(attrname);if(editedNode){editedNode.updAttributes({'_loadedValue':objectPop(newattr,attrname)},false);}}
if(attrname in newattr){newattr['_customClass_'+attrname]='externalChangedCell';}}else if(rowValue instanceof gnr.GnrBag){var editedNode=rowValue.getNode(attrname);if(editedNode){editedNode.updAttributes({'_loadedValue':objectPop(newattr,attrname)},false);}}}}
rowNode.updAttributes(newattr,true);if(selectedPkeysDict[pkey]){dojo.forEach(selectedPkeysDict[pkey],function(grid){grid.sourceNode.publish('updatedSelectedRow');});}}else{data.popNode(wasInSelectionNode.label);}}else if(willBeInSelectionNode){toUpdate=true;data.setItem('#id',willBeInSelectionNode);}});}
if(toUpdate&&this.sortedBy){this.mustBeSorted=true;}
var that=this;dojo.forEach(linkedGrids,function(grid){if(toUpdate){if(!grid.gnrediting){if(that.mustBeSorted){that.sort();if(that._filtered){that.filterToRebuild(true);}
that.mustBeSorted=false;}
grid.updateRowCount('*');}else{grid.pendingSort=true;}
grid.restoreSelectedRows();}
for(var k in changedRows){var n=changedRows[k];objectExtract(n.attr,'_customClass_*');if(grid.gridEditor){grid.gridEditor.onExternalChange(k);}}
genro.userInfoCb.push(function(){genro.dom.addClass(grid.sourceNode,'onExternalChanged');});grid.sourceNode.publish('onExternalChanged');});},duplicateRows:function(pkeys){var lockreason=this.storeNode.attr.nodeId+'_'+'deletingDbRows';var that=this;const n_records=pkeys.length;genro.dlg.ask(_T('Duplicate rows'),_T("You are going to duplicate")+' '+n_records+' '+_T('records'),null,{confirm:function(){genro.lockScreen(true,lockreason,{thermo:true});genro.serverCall('app.duplicateDbRows',{pkeys:pkeys,table:that.storeNode.attr.table,_sourceNode:that.storeNode,timeout:0},function(result){genro.lockScreen(false,lockreason,'duplicatingRecords');},null,'POST');}});},deleteRows:function(pkeys,protectPkeys){var that=this;var unlinkfield=this.unlinkdict?this.unlinkdict.field:null;var lockreason=this.storeNode.attr.nodeId+'_'+'deletingDbRows';genro.lockScreen(true,lockreason,{thermo:true});genro.serverCall('app.deleteDbRows',{pkeys:pkeys,table:this.storeNode.attr.table,unlinkfield:unlinkfield,protectPkeys:protectPkeys,_sourceNode:this.storeNode,timeout:0},function(result){genro.lockScreen(false,lockreason,'deletingDbRows');that.onDeletedRows(result);},null,'POST');},archiveRows:function(pkeys,protectPkeys,date){var that=this;var unlinkfield=this.unlinkdict?this.unlinkdict.field:null;genro.serverCall('app.archiveDbRows',{pkeys:pkeys,table:this.storeNode.attr.table,archiveDate:date,unlinkfield:unlinkfield,protectPkeys:protectPkeys,_sourceNode:this.storeNode},function(result){that.onDeletedRows(result);},null,'POST');},onDeletedRows:function(result){var that=this;this.gridBroadcast(function(grid){genro.callAfter(function(){grid.updateCounterColumn();},300,grid,that.storeNode.attr.nodeId);});},onLoading:function(){this.pendingChanges=[];this.externalChangedKeys=null;},onLoaded:function(result){delete this.pendingLoading;this.storeNode.setRelativeData(this.storepath,result,null,null,'loadData');return result;}});dojo.declare("gnr.stores.VirtualSelection",gnr.stores.Selection,{askToDelete:true,constructor:function(){this.pendingPages={};this.lastIdx=0;},sort:function(){return;},len:function(filtered){var data=this.getData();if(!data){return 0;}
var dataNode=data.getParentNode();if(!dataNode){return 0;}
var len=dataNode.attr['totalrows']||0;if(!filtered){len=dataNode.attr['totalRowCount']||len;}
return len;},onLoaded:function(result){if(result==null){console.warn('missing result')
return}
if(result.error){return;}
this.clearBagCache();var selection=result.getValue();var data=new gnr.GnrBag();var resultattr=result.attr;data.setItem('P_0',result.getValue(),{pageIdx:0});this.rowtotal=resultattr.rowcount;this.totalRowCount=resultattr.totalRowCount;this.selectionName=resultattr.selectionName;this.storeNode.setRelativeData(this.storepath,data,resultattr,null,'loadData');if(resultattr.prevSelectedIdx&&resultattr.prevSelectedIdx.length>0){var pagetoload={};var cs=this.chunkSize;dojo.forEach(resultattr.prevSelectedIdx,function(idx){pagetoload[(idx-idx%cs)/cs]=true;});for(var page in pagetoload){this.loadBagPageFromServer(page,true,data);}
this.gridBroadcast(function(grid){grid.selection.select(resultattr.prevSelectedIdx);grid.scrollToRow(resultattr.prevSelectedIdx);});}
return result;},onExternalChangeResult:function(changelist){if(changelist.length>0){var that=this;this.externalChangedKeys=this.externalChangedKeys||{};dojo.forEach(changelist,function(n){if(n._isExternal){that.externalChangedKeys[n.pkey]=true;}});var prevSelected={};dojo.forEach(this.linkedGrids(),function(grid){dojo.forEach(grid.selection.getSelected(),function(idx){prevSelected[grid.rowIdByIndex(idx)]=true;});grid._saved_selections=grid.selectionKeeper('save');});this.storeNode.setRelativeData('.query.prevSelectedDict',prevSelected);var that=this;var cb=function(result){dojo.forEach(that.linkedGrids(),function(grid){grid.sourceNode.publish('onExternalChanged');});return result;};var result=this.loadData();if(result instanceof dojo.Deferred){result.addCallback(function(r){cb(r)});}else{result=cb(result);}}},onExternalChange:function(changelist){var parentNodeData=this.getData().getParentNode();if(!parentNodeData){return;}
var selectionKw=parentNodeData.attr;if(!selectionKw.selectionName){return;}
var that=this;var rpc_attr=objectUpdate({},this.storeNode.attr);objectExtract(rpc_attr,'_*');objectUpdate(rpc_attr,{'selectionName':selectionKw.selectionName,'changelist':changelist,'_sourceNode':this.storeNode});genro.rpc.remoteCall('app.checkFreezedSelection',rpc_attr,null,null,null,function(result){if(result){that.onExternalChangeResult(changelist);}
return result;});},currentPkeys:function(caption_field){var parentNodeData=this.getData().getParentNode();if(!parentNodeData){return[];}
var selectionKw=parentNodeData.attr;if(!selectionKw.selectionName){return[];}
var kw={'table':selectionKw.table,selectionName:selectionKw.selectionName,caption_field:caption_field}
return genro.rpc.remoteCall('app.freezedSelectionPkeys',kw,null,null,null,function(result){return result||[];});},clearBagCache:function(){var data=this.getData();if(data){data.clear();}
this.currRenderedRowIndex=null;this.currRenderedRow=null;this.currCachedPageIdx=null;this.currCachedPage=null;},itemByIdx:function(idx,sync){var delta=idx-this.lastIdx;this.lastIdx=idx;var dataPage;var rowIdx=idx%this.chunkSize;var pageIdx=(idx-rowIdx)/this.chunkSize;if(this.currCachedPageIdx!=pageIdx){if(!sync){dataPage=this.getDataChunk(pageIdx);}else{dataPage=this.getData().getItem('P_'+pageIdx);if(!dataPage){dataPage=this.loadBagPageFromServer(pageIdx,sync);}}
if(dataPage){this.currCachedPageIdx=pageIdx;this.currCachedPage=dataPage;}else{this.currCachedPageIdx=-1;this.currCachedPage=null;}}else{if(((delta>0)&&((rowIdx/this.chunkSize)>.7))||((delta<0)&&((rowIdx/this.chunkSize)<.3))){var guessPage=delta>0?pageIdx+1:pageIdx-1;if(guessPage>0){if(guessPage!=this.guessPage){this.getDataChunk(guessPage);this.guessPage=guessPage;}}}}
if(this.currCachedPage){return this.currCachedPage.getNodes()[rowIdx];}},setExternalChangeClasses:function(item){var externalChangedKeys=this.externalChangedKeys||{};var row=item.attr;var pkey=row['_pkey'];if(pkey in externalChangedKeys){row['_customClasses']=row._customClasses?row._customClasses+' externalChangedRow':'externalChangedRow';row['_externalChangedRowTS']=new Date();objectPop(externalChangedKeys,pkey);}else if(row['_customClasses']&&row['_externalChangedRowTS']&&(new Date()-row['_externalChangedRowTS']>1000)){delete row['_externalChangedRowTS'];row['_customClasses']=row['_customClasses'].replace('externalChangedRow','');}},getDataChunk:function(pageIdx){if(pageIdx in this.pendingPages){return;}else{var pageData=this.getData().getItem('P_'+pageIdx);if(pageData){return pageData;}
if(this.isScrolling&&this.storeNode.attr.httpMethod!='WSK'){return;}
if(this.pendingTimeout){if(this.pendingTimeout.idx==pageIdx){return;}else{clearTimeout(this.pendingTimeout.handler);this.pendingTimeout={};}}
var that=this;this.pendingTimeout={'idx':pageIdx,'handler':setTimeout(function(){that.loadBagPageFromServer(pageIdx);},10)};return;}},onChunkLoaded:function(result,pageIdx){var data=result.getValue();this.getData().setItem('P_'+pageIdx,data,{pageIdx:pageIdx},{'doTrigger':false});objectPop(this.pendingPages,pageIdx);this.storeNode.publish('updateRows');this.pendingTimeout={};return data;},loadBagPageFromServer:function(pageIdx,sync,buffer){var that=this;var row_start=pageIdx*this.chunkSize;var kw=this.getData().getParentNode().attr;var result=genro.rpc.remoteCall(kw.method,{'selectionName':kw.selectionName,'row_start':row_start,'row_count':this.chunkSize,'sortedBy':this.sortedBy,'table':kw.table,'recordResolver':false},null,this.storeNode.attr.httpMethod,null,sync?null:function(result){return that.onChunkLoaded(result,pageIdx);});if(sync){if(buffer){buffer.setItem('P_'+pageIdx,result.getValue(),{pageIdx:pageIdx});}else{return this.onChunkLoaded(result,pageIdx);}}else{this.pendingPages[pageIdx]=result;}},getIdxFromPkey:function(pkey){var result=-1;var dataNode=this.getData().getNodeByAttr(this.identifier,pkey);if(dataNode){result=dataNode.attr.rowidx;}
return result;},getKeyFromIdx:function(idx){var dataNode=this.itemByIdx(idx,true);return dataNode?this.keyGetter(dataNode):null;},indexByCb:function(cb,backward){var n=this.len(true);var pages=this.getData().getNodes();var n_pages=pages.length;for(var p=0;p<n_pages;p++){var k_p=backward?n_pages-p:p;var page=pages[k_p].getValue();var rowNodes=page.getNodes();var n=rowNodes.length;for(var i=0;i<n;i++){var k_i=backward?n-i:i;if(cb(this.rowFromItem(rowNodes[i]))){return parseInt(pages[k_p].label.slice(2))*this.chunkSize+k_i;}}}
return-1;},filteredRowsIndex:function(){console.error('filteredRowsIndex not implemented in virtualstore');return[];},sum:function(field){var storeattr=this.getData().getParentNode().attr;if('sum_'+field in storeattr){return storeattr['sum_'+field];}else{var sum_columns=this.getSumColumns();sum_columns=sum_columns?sum_columns.split(','):[];arrayPushNoDup(sum_columns,field);this.storeNode.setRelativeData('.sum_columns',sum_columns.join(','));var rpc_attr={'selectionName':this.selectionName,sum_column:field};rpc_attr.sum_column=field;storeattr['sum_'+field]=genro.rpc.remoteCall('app.sumOnFreezedSelection',rpc_attr,null,null,null,function(result){storeattr['sum_'+field]=result;});return storeattr['sum_'+field];}}});



dojo.declare("gnr.GnrFrmHandler",null,{constructor:function(sourceNode,formId,formDatapath,controllerPath,pkeyPath,formAttr){var that=this;genro.src.onBuiltCall(function(){that.onStartForm();});for(var k in formAttr){this[k]=formAttr[k];}
if(!('autoFocus'in this)){this.autoFocus=!genro.isMobile;}
if(this.isRootForm){genro._rootForm=this;}
this.formId=formId;this.changed=false;this.childForms={};this.gridEditors={};this.opStatus=null;this.locked=this.locked||false;this.parentLock=this.parentLock==null?'auto':this.parentLock;this.current_field=null;this.controllerPath=controllerPath;this.formErrors=new gnr.GnrBag();if(!this.store){this.controllerPath=this.controllerPath||'gnr.forms.'+this.formId;}
this.formDatapath=formDatapath;this.pkeyPath=pkeyPath;this.sourceNode=sourceNode;var formCenter=this.sourceNode.getValue().getNode('center');this.contentSourceNode=this.store?(formCenter?formCenter:sourceNode):sourceNode;this.frameCode=sourceNode.attr.frameCode;if(this.frameCode){this.formParentNode=genro.getFrameNode(this.frameCode,'frame').getParentNode().getParentNode();}else{this.formParentNode=this.sourceNode.getParentNode();}
this.subscribe('save,reload,load,goToRecord,abort,loaded,setLocked,navigationEvent,newrecord,pendingChangesAnswer,dismiss,deleteItem,deleteConfirmAnswer,message,shortcut_save');this.sourceNode.registerSubscription('setInClientRecord',this,this.setInClientRecord);this._register={};this._status_list=['ok','error','changed','readOnly','noItem'];this.autoRegisterTags={'textbox':null,'simpletextarea':null,'checkbox':null,'numbertextbox':null,'currencytextbox':null,'timetextbox':null,'horizzontalslider':null,'radiobutton':null,'verticalslider':null,'combobox':null,'filteringselect':null,'dbselect':null,'dbcombobox':null,'input':null,'textarea':null,'datetextbox':null,'geocoderfield':null,'ckeditor':null};this.checkLastSavedTags={'textbox':null,'numbertextbox':null,'currencytextbox':null,'timetextbox':null,'combobox':null,'filteringselect':null,'dbselect':null,'dbcombobox':null,'datetextbox':null,};var tblname=this.getControllerData('table?name_long');var pref=tblname?tblname+' record':'Record';this.msg_saved=pref+' saved ';this.msg_deleted=pref+' deleted';this.table_name=tblname||formId;this.msg_unsaved_changes="Current record has been modified.";this.msg_confirm_delete="You are going to delete the current record.";},getParentForm:function(){return this.sourceNode.getParentNode().getFormHandler();},canBeSaved:function(kw){kw=kw||{};return!this.opStatus&&(this.record_changed||kw.always)&&(this.isValid()||this.allowSaveInvalid)&&this.status!='noItem';},saveDisabled:function(){if(this.disabledStatus()=='unlocked_readOnly'){return this.getChangesLogger().getNodes().some(n=>!n.attr.allowed);}
return this.isDisabled();},doAutoSave:function(){var that=this;if(this.canBeSaved()&&!this.isNewRecord()){genro.callAfter(function(){that.lazySave();},this.autoSave,this.sourceNode,'autoSaveForm_'+this.formId);}},shortcut_save:function(kw){if(this.saveDisabled()){this.publish('message',{message:_T('Cannot save. Blocked Form'),sound:'$error',messageType:'warning'});return;}
kw=kw||{};this.save(kw.forced);},lazySave:function(savedCb,kw,errorCb){savedCb=savedCb?funcCreate(savedCb,{},this):false;if(this.canBeSaved(kw)){var d=this.save(objectUpdate({onSaved:'lazyReload',waitingStatus:false},kw));this.getFormData().walk(function(n){delete n.attr._loadedValue;},'static');if(savedCb){d.addCallback(savedCb);}
return d;}else if(errorCb){errorCb.call(this);}else if(savedCb){savedCb.call(this);}},onStartForm:function(kw){kw=kw||{};this.formDomNode=this.sourceNode.getDomNode();this.formContentDomNode=this.contentSourceNode.getDomNode();if(this.store){var that=this;this.store.init(this);dojo.connect(this.formContentDomNode,'onclick',function(e){var wdg=dijit.getEnclosingWidget(e.target);if(wdg&&wdg.sourceNode&&wdg.sourceNode.form&&wdg.isFocusable&&!wdg.isFocusable()&&wdg.sourceNode&&(wdg.sourceNode.form!=genro.activeForm)){wdg.sourceNode.form.focusCurrentField();}});if(this.store.autoSave){this.autoSave=this.store.autoSave===true?2000:this.store.autoSave;dojo.connect(this,'updateStatus',this.doAutoSave);}
var startKey=kw.startKey||this.store.startKey||this.getCurrentPkey();if(startKey){startKey=this.sourceNode.currentFromDatasource(startKey);}
this.sourceNode.getAttributeFromDatasource(startKey);if(startKey){this.sourceNode.watch('pageStarted',function(){return genro._pageStarted;},function(){that.load({destPkey:startKey});});}
var parentForm=this.getParentForm();if(parentForm){parentForm.subscribe('onLoaded',function(kw){if(kw.pkey!=that.parentFormPkey){that.parentFormPkey=kw.pkey;if(that.status!='noItem'){that.abort();}
that.publish('changedParent');}});}
var parentStore=this.store.parentStore;if(parentStore){parentStore.storeNode.subscribe('onLockChange',function(kw){if(that.parentLock=='auto'){that.setLocked(kw.locked);}
that.publish('onParentLockChange',kw);},this.sourceNode);this.locked=parentStore.locked;}else if(parentForm){parentForm.subscribe('onLockChange',function(kw){if(that.parentLock=='auto'){that.setLocked(kw.locked);}},null,this.sourceNode);this.locked=parentForm.locked;}
dojo.subscribe('onPageStart',function(){that.setLocked(that.locked);that.updateStatus();});}},reset:function(){this.resetGridEditors();this.resetChanges();this.resetInvalidFields();},resetGridEditors:function(){for(var k in this.gridEditors){this.gridEditors[k].resetEditor();}},publish:function(command,kw,topic_kw){var topic={'topic':'form_'+this.formId+'_'+command,parent:this.publishToParent}
objectUpdate(topic,topic_kw)
genro.publish(topic,kw);},message:function(kw){if(!(kw instanceof Array)){kw=[kw]}
var msgKw=kw.shift();if(typeof(msgKw)=='string'){msgKw={message:msgKw};}
var that=this;if(kw.length){msgKw.onClosedCb=function(){that.message(kw)}}
msgKw=objectUpdate({duration_in:3,duration_out:4,yRatio:.8},msgKw);genro.dlg.floatingMessage(this.sourceNode,msgKw);},subscribe:function(command,cb,scope,subscriberNode){if(command.indexOf(',')>=0){var that=this;dojo.forEach(command.split(','),function(command){that.subscribe(command);});return;}
var topic='form_'+this.formId+'_'+command;scope=scope||this;cb=cb||this[command];subscriberNode=subscriberNode||this.sourceNode;subscriberNode.registerSubscription(topic,scope,cb);},applyDisabledStatus:function(){var form_disabled=this.isDisabled();var disabled_status=this.disabledStatus();this.publish('onDisabledChange',{disabled:form_disabled,locked:this.locked});genro.dom.setClass(this.sourceNode,'lockedContainer',form_disabled);var node,disabled;for(var k in this._register){node=this._register[k];if(disabled_status=='unlocked_readOnly'&&node.attr.tag.toLowerCase()in this.autoRegisterTags){disabled=this._protectedNode(genro.getDataNode(node.absDatapath(node.attr.value))||node);}else{disabled=form_disabled;}
if(disabled===false){disabled='disabled'in node.attr?node.getAttributeFromDatasource('disabled'):false;if(disabled==false&&'unmodifiable'in node.attr){disabled=!this.isNewRecord();}}
node.setDisabled(disabled);}},_protectedNode:function(node){var recAttr=this.getDataNodeAttributes();var protect_write=recAttr._protect_write;if(protect_write===true){return true;}
if('protected_by'in node.attr){return node.attr.protected_by;}
var protect_write_reasons=protect_write?protect_write.split(','):[];var protected_by_kwargs=objectExtract(node.attr,'protected_by_*',true);return!protect_write_reasons.some(fld=>protected_by_kwargs[fld]===false);},resetKeepable:function(){for(var k in this._register){var node=this._register[k];if(node.attr.keepable){node.widget.setKeeper(false);}}},isDisabled:function(){return this.locked||this.status=='readOnly'||this.status=='noItem';},disabledStatus:function(){var result=[];result.push(this.locked?'locked':'unlocked');if(this.status=='readOnly'||this.status=='noItem'){result.push(this.status);}
return result.join('_')||false;},setLocked:function(value){if(value=='toggle'){value=!this.locked;}
this.locked=value;this.applyDisabledStatus();this.setControllerData('locked',value);this.publish('onLockChange',{'locked':this.locked},{iframe:'*'});},registerChild:function(sourceNode){var ltag=sourceNode.attr.tag.toLowerCase();if(sourceNode.attr.parentForm||(ltag in this.autoRegisterTags)){if(!this._firstField){if(ltag in this.autoRegisterTags){this._firstField=sourceNode;}}
this._register[sourceNode._id]=sourceNode;return;}},setLastSavedValues:function(){var k,node,ltag;for(k in this._register){node=this._register[k];if(node.attr.tag.toLowerCase()in this.checkLastSavedTags){node._lastSavedValue=node.getRelativeData(node.attr.value);}}},registerGridEditor:function(nodeId,gridEditor){this.gridEditors[nodeId]=gridEditor;},unregisterChild:function(sourceNode){if(this._register[sourceNode._id]){delete this._register[sourceNode._id];}
if(sourceNode.widget&&sourceNode.widget.gridEditor){objectPop(this.gridEditors,sourceNode.attr.nodeId);}},getSemaphoreStatus:function(){var i;if(this.status=='noItem'){return'<div class="form_errorslogger">No record loaded</div>';}
if(this.status=='readOnly'){var readOnlyMsg='Read Only';var protectWriteMessage=this.getDataNodeAttributes()._protect_write_message;return'<div class="form_errorslogger">'+protectWriteMessage||readOnlyMsg+'</div>';}
if(this.status=='ok'){return'<div class="form_okmessage">No changes to save</div>';}
if(this.status=='changed'){if(this.isNewRecord()){return'The record can be saved';}
var changes=this.getChangesLogger()
var content=new gnr.GnrBag();i=0;changes.forEach(function(n){if(n.attr.from!=n.attr.to){var r=new gnr.GnrBag();r.setItem('fieldname','<div style="font-weight: bold;">'+n.attr._valuelabel+'</div>',{_valuelabel:'Field'});r.setItem('from',n.attr.from,{_valuelabel:'From'});r.setItem('to',n.attr.to,{_valuelabel:'To'});content.setItem('r_'+i,r)}
i++;});var c=content.asHtmlTable({cells:'fieldname,from,to',headers:true})
return'<div class="form_changeslogger">Changed fields</div><div class="form_contentlogger">'+c+'</div>';}
if(this.status=='error'){var content=new gnr.GnrBag();var invfields=this.getInvalidFields();var invdojo=this.getInvalidDojo();i=0;if(invfields){invfields.forEach(function(n){var sn=genro.src.nodeBySourceNodeId(objectValues(n.getValue())[0]);if(!sn){return;}
var r=new gnr.GnrBag();r.setItem('fieldname','<div style="font-weight: bold;">'+sn.getElementLabel()+'</div>',{_valuelabel:'Field'});r.setItem('error',sn._validations.error,{_valuelabel:'Error'});i++;content.setItem('r_'+i,r)});}
if(invdojo){invdojo.forEach(function(n){var r=new gnr.GnrBag();r.setItem('fieldname','<div style="font-weight: bold;">'+n.attr._valuelabel+'</div>',{_valuelabel:'Field'});r.setItem('error','Invalid data',{_valuelabel:'Error'});content.setItem('r_'+i,r)
i++;});}
var formErrorsMessages=this.getFormErrors();if(formErrorsMessages.length){formErrorsMessages.forEach(function(message){content.setItem('r_'+i+'.error',message);i++;})}
content=content.asHtmlTable({cells:'fieldname,error',headers:true});return'<div class="form_errorslogger">Wrong fields</div><div class="form_contentlogger">'+content+'</div>';}},dismiss:function(modifiers){this.publish('navigationEvent',{'command':'dismiss',modifiers:modifiers});},resetChanges:function(){var formData=this.getFormData();if(formData){formData.subscribe('dataLogger',{'upd':dojo.hitch(this,"triggerUPD"),'ins':dojo.hitch(this,"triggerINS"),'del':dojo.hitch(this,"triggerDEL")});}
this.resetChangesLogger();},validateFromDatasource:function(sourceNode,value,trigger_reason){if(trigger_reason=='container'){this.addPendingValidation(sourceNode);}else if(trigger_reason=='node'){var result=genro.vld.validate(sourceNode,value);if(result['modified']){sourceNode.widget.setValue(result['value']);}
sourceNode.setValidationError(result);sourceNode.updateValidationStatus();}},forceIgnoreReadOnly:function(evt){if(genro.dom.getEventModifiers(evt)=='Shift'){this.reload({ignoreReadOnly:true});}},reload:function(kw){kw=kw||{};var destPkey=this.getCurrentPkey();if(destPkey=='*newrecord*'){this.newrecord(this.last_default_kw);return;}
this.load(objectUpdate({destPkey:destPkey},kw));},goToRecord:function(pkey,ts){if(pkey!=this.getCurrentPkey()||(ts&&!isEqual(new Date(this.getDataNodeAttributes().lastTS),ts))){this.load({destPkey:pkey});}},load:function(kw){if(this.opStatus=='loading'){return;}
var that=this;if(objectNotEmpty(this.childForms)){var onAnswer=function(command){if(command=='cancel'){return;}
that.load(kw);};for(var k in this.childForms){var childForm=this.childForms[k];if(childForm.changed){childForm.openPendingChangesDlg({destPkey:'*dismiss*',onAnswer:onAnswer});return;}}}
if(this.store&&this.changed&&this.saveOnChange&&this.isValid()){var deferred=this.store.save();deferred.addCallback(function(){that.reset();});return;}
kw=kw||{};if(this.store){if(!kw.destPkey&&this.store instanceof gnr.formstores.SubForm){kw.destPkey="*subform*";}
kw.destPkey=kw.destPkey||this.store.getDefaultDestPkey();var destPkey=kw.destPkey;if(typeof(destPkey)=='string'&&destPkey.indexOf('*|')>=0){var pkeyChoices=destPkey.split('|');var chosedPkey;while(!chosedPkey&&pkeyChoices.length){chosedPkey=pkeyChoices.shift();if(['*next*','*prev*','*last*','*first*'].indexOf(chosedPkey)>-1){chosedPkey=this.store.getNavigationPkey(chosedPkey.slice(1,-1),this.getCurrentPkey());}}
kw.destPkey=chosedPkey||'*norecord*';}
if(kw['destPkey']=='*norecord*'){kw['destPkey']=null;this.store.setNavigationStatus('*norecord*');this.setFormData();this.setCurrentPkey();this.loaded();}
this.load_store(kw);}else{if('destPkey'in kw){var currentPkey=this.getCurrentPkey();if(this.changed&&(kw.destPkey!=currentPkey)){this.openPendingChangesDlg(kw);return;}}
this.doload_loader(kw);}},load_store:function(kw){var currentPkey=this.getCurrentPkey();if(!kw.discardChanges&&this.changed&&kw.destPkey&&(currentPkey=='*newrecord*'||(kw.destPkey!=currentPkey))){if(kw.modifiers=='Shift'||this.autoSave){this.save(kw);}else{this.openPendingChangesDlg(kw);}
return;}
var defaultPrompt='defaultPrompt'in kw?kw.defaultPrompt:this.defaultPrompt;if(kw.destPkey=='*newrecord*'&&defaultPrompt){var that=this;kw.default_kw=kw.default_kw||{};genro.dlg.prompt(_T(defaultPrompt.title||'Fill parameters'),{widget:defaultPrompt.fields,dflt:new gnr.GnrBag(kw.default_kw),cols:defaultPrompt.cols,datapath:'.controller.defaultPrompt',action:function(result){objectUpdate(kw.default_kw,result.asDict());if(defaultPrompt.doSave&&that.store.table){that.insertAndLoad(kw.default_kw);}else{that.doload_store(kw);}}},this.sourceNode);return;}
this.doload_store(kw);},abort:function(){this.doload_store({destPkey:'*dismiss*'});},norecord:function(){this.load({destPkey:'*norecord*'});},newrecord:function(default_kw){this.load({destPkey:'*newrecord*',default_kw:default_kw});},insertAndLoad:function(default_kw){var that=this;var record=new gnr.GnrBag(objectExtract(this.store.prepareDefaults('*newrecord*',default_kw),'default_*'));genro.serverCall('app.insertRecord',{table:this.store.table,record:record},function(resultPkey){that.doload_store({destPkey:resultPkey});});},deleteItem:function(kw){kw=kw||{};this.deleteConfirmDlg(kw);},deleteConfirmDlg:function(kw){var dlg=genro.dlg.quickDialog('Alert',{_showParent:true,width:'280px'});dlg.center._('div',{innerHTML:this.msg_confirm_delete,text_align:'center',_class:'alertBodyMessage'});var form=this;var slotbar=dlg.bottom._('slotBar',{slots:'*,cancel,delete',action:function(){dlg.close_action();kw.command=this.attr.command;form.publish('deleteConfirmAnswer',kw);}});slotbar._('button','cancel',{label:'Cancel',command:'cancel'});slotbar._('button','delete',{label:'Delete',command:'deleteItem'});dlg.show_action();},deleteConfirmAnswer:function(kw){var command=objectPop(kw,'command');if(this.store){var that=this;if(command=='deleteItem'){this.do_deleteItem(kw);}else{if(kw.cancelCb){kw.cancelCb();}
this.publish('onCancel',{formEvent:'deleteRecord'});}}},do_deleteItem:function(kw){kw=kw||{};kw.pkey=kw.pkey||this.getCurrentPkey();this.setOpStatus('deleting');var r=this.store.deleteItem(kw.pkey,kw);if(kw.onDeleted){var onDeleted=funcCreate(kw.onDeleted,'result',this);if(r instanceof dojo.Deferred){r.addCallback(onDeleted);}else{onDeleted(r);}}},recordSearchBox:function(kw){var datapath=this.sourceNode.absDatapath()+'.temp.jump';var that=this;var table=this.getControllerData('table');var cdata=this.getControllerData();var tableattr=this.getControllerData().getAttr('table');var searchattr=objectExtract(tableattr,'search_*',true)
if(that._jumperOpen){return;}
that._jumperOpen=true;genro.dlg.lightboxDialog(function(dlg,closecb){var box=dlg._('div',{padding:'5px',font_size:'1.2em'});var onEnter=function(){var pkey=genro.getData(datapath+'.pkey');if(pkey){that.goToRecord(pkey);}
delete that._jumperOpen;closecb();}
fb=genro.dev.formbuilder(box,1,{border_spacing:'1px',onEnter:onEnter,width:'100%',fld_width:'100%'});fb.addField('dbselect',objectUpdate({value:'^'+datapath+'.pkey',dbtable:table,padding:'3px',validate_onAccept:function(value,userChange){if(userChange){onEnter();}},padding_left:'5px',padding_right:'5px',rounded:6,width:'30em',lbl:that.table_name+': '},searchattr));});},pendingChangesAnswer:function(kw){var command=objectPop(kw,'command');var onAnswer=objectPop(kw,'onAnswer');var res;if(this.store){var that=this;if(command=='save'){res=this.save({destPkey:kw.destPkey});}
else if(command=='discard'){res=this.doload_store(kw);}else{var cancelCb=kw.cancelCb||this.cancelCb;if(cancelCb){cancelCb=funcCreate(cancelCb);cancelCb();}
this.publish('onCancel',{formEvent:'loadRecord'});}
if(onAnswer&&res instanceof dojo.Deferred){res.addCallback(onAnswer);}else if(onAnswer){onAnswer(command);}}else{if(command=='save'){this.setCurrentPkey(kw.destPkey);this.save();}
else if(command=='discard'){this.doload_loader(kw);}else{if(kw.cancelCb){kw.cancelCb();}}}},waitingStatus:function(waiting){this.sourceNode.setHiderLayer(waiting,{message:'<div class="form_waiting"></div>',z_index:999999});},setFormError:function(errorcode,message){if(message===false){this.formErrors.popNode(errorcode);}else{this.formErrors.setItem(errorcode,message);this.publish('message',{message:message,sound:'$error',messageType:'error'});}
this.updateStatus();},getFormErrors:function(){var result=[];this.formErrors.walk(function(n){var v=n.getValue();if(typeof(v)=='string'){result.push(v);}});return result;},openPendingChangesDlg:function(kw,saveSlot){if(this.avoidPendingChangesDialog){kw.command='discard';this.publish('pendingChangesAnswer',kw);return;}
saveSlot=saveSlot===undefined?true:saveSlot;var dlg=genro.dlg.quickDialog('Pending changes in '+this.table_name.toLowerCase(),{_showParent:true,width:'280px'});dlg.center._('div',{innerHTML:this.msg_unsaved_changes,text_align:'center',_class:'alertBodyMessage'});var form=this;var slotbar=dlg.bottom._('slotBar',{slots:saveSlot?'discard,*,cancel,save':'discard,*,cancel',action:function(){dlg.close_action();kw.command=this.attr.command;form.publish('pendingChangesAnswer',kw);}});slotbar._('button','discard',{label:'Discard changes',command:'discard'});slotbar._('button','cancel',{label:'Cancel',command:'cancel'});if(saveSlot){slotbar._('button','save',{label:'Save',command:'save'});}
dlg.show_action();},setOpStatus:function(opStatus){this.opStatus=opStatus;this.publish('onSetOpStatus',this.opStatus);},doload_loader:function(kw){kw=kw||{};var sync=kw.sync;this.setControllerData('loading',true);this.setOpStatus('loading');if('destPkey'in kw){var destPkey=kw.destPkey||'*newrecord*';this.setCurrentPkey(destPkey);}
if(!sync){this.setHider(true);}
this.resetInvalidFields();genro.setData('_temp.grids',null);var loaderNode=genro.nodeById(this.formId+'_loader');if(loaderNode){loaderNode.fireNode();if(sync){this.loaded();}}else{console.log('missing loader');this.loaded();}},doload_store:function(kw){if(kw.destPkey=='*dismiss*'){this.reset();this.setCurrentPkey(null);if(this.store.parentStore){this.store.parentStore.onEndEditItem(this);};genro.callAfter(function(){genro.dlg.removeFloatingMessage(this.sourceNode);this.publish('onDismissed');},('onReload'in kw)?1000:1,this);return;}else if(kw['destPkey']=='*duplicate*'){this.store.duplicateRecord(null,kw.howmany);return;}
kw=kw||{};var sync=kw.sync;this.setControllerData('loading',true);var pkey=('destPkey'in kw)?kw.destPkey:this.store.getStartPkey();this.setCurrentPkey(pkey);this.publish('onLoading',{destPkey:pkey});if(pkey){if(!sync&&!this.autoSave){this.setHider(true);}
this.resetInvalidFields();this.setOpStatus('loading',pkey);var deferredOrResult=this.store.load(kw);if(kw.onReload){if(deferredOrResult instanceof dojo.Deferred){deferredOrResult.addCallback(kw.onReload);}else{kw.onReload(deferredOrResult);}}}else{this.updateStatus();}},setHider:function(show){this.sourceNode.setHiderLayer(show);},deleted:function(result,kw){var destPkey=kw.destPkey||this.deleted_destPkey||'*dismiss*';this.load({destPkey:destPkey});this.publish('message',{message:this.msg_deleted,sound:'$ondeleted'});this.publish('onDeleted');},loaded:function(data){var controllerData=this.getControllerData();var that=this;controllerData.setItem('temp',null);if(data){this.setFormData(data);}
this.publish('onLoaded',{pkey:this.getCurrentPkey(),data:data});this.setHider(false);this.reset();this.protect_write=this.isProtectWrite();genro.dom.setClass(this.sourceNode,'form_logical_deleted',this.isLogicalDeleted());genro.dom.setClass(this.sourceNode,'form_protect_write',this.protect_write);genro.dom.setClass(this.sourceNode,'form_draft',this.isDraft());this.protect_delete=this.isProtectDelete();genro.dom.setClass(this.sourceNode,'form_protect_delete',this.protect_delete);this.newRecord=this.isNewRecord();genro.dom.setClass(this.sourceNode,'form_new_record',this.newRecord);this._recordcaption=data instanceof gnr.GnrBagNode?data.attr.caption:'';controllerData.setItem('protect_write',this.protect_write,null,{lazySet:true});controllerData.setItem('protect_delete',this.protect_delete,null,{lazySet:true});controllerData.setItem('is_newrecord',this.newRecord,null,{lazySet:true});controllerData.setItem('loading',false,null,{lazySet:true});var loadedPkey=(this.getCurrentPkey()||'*norecord*');setTimeout(function(){controllerData.fireItem('loaded',loadedPkey);delete that._reloadingAfterSave;},1);this.updateStatus();this.setOpStatus();this.currentFocused=null;var onLoadingError=this.onLoadingError();if(onLoadingError){genro.dlg.alert(onLoadingError,'Error',null,null,{confirmCb:function(){that.abort();}});return;}else{this.handleLoadedMessage();}
if(this.store){if(this.store.parentStore){this.store.parentStore.onStartEditItem(this);}
this.applyDisabledStatus();this.handlePendingValidations();that=this;var parentForm=this.getParentForm();if(!parentForm||!parentForm.currentFocused){if(this.autoFocus&&this.isNewRecord()){setTimeout(function(){that.focus();},1);}}}},getRecordCaption:function(){return this._recordcaption;},focus:function(node){if(!this.isDisabled()){var formContentDomNode=this.formContentDomNode||this.sourceNode.widget.domNode;if(this.sourceNode.widget&&this.sourceNode.widget.getSelected){formContentDomNode=this.sourceNode.widget.getSelected().domNode;}
if(!node&&this._firstField){node=this._firstField.widget?this._firstField.widget.focusNode:this._firstField.domNode;}
if(node){node.focus();}}},onFocusForm:function(){genro.dom.addClass(this.sourceNode,'form_activeForm');this.focusCurrentField();},onBlurForm:function(){if(this.autoSave&&this.changed){this.doAutoSave();}
genro.dom.removeClass(this.sourceNode,'form_activeForm');},isRegisteredWidget:function(wdg){return(wdg.sourceNode._id in this._register);},isEmptyForm:function(){var has_filled_field=objectValues(this._register).some(function(n){var v=n.getAttributeFromDatasource('value');if(!isNullOrBlank(v)){return true;}})
return!has_filled_field;},onFocusElement:function(wdg){if(this.isRegisteredWidget(wdg)&&(typeof(wdg.focus)=='function')){this.currentFocused=wdg;}else{this.currentFocused=null;}},focusCurrentField:function(e){if(!this.isDisabled()){if(this.currentFocused){this.currentFocused.focus();}}},copyPasteMenu:function(){var result=new gnr.GnrBag();var currentPkey=this.getCurrentPkey();var that=this;var clipboard=this.getControllerData('clipboard');var disabled=this.isDisabled();var copyDisabled=currentPkey==null||currentPkey=='*newrecord*'||this.changed;result.setItem('r_0',null,{caption:_T('Copy current record'),disabled:copyDisabled,action:function(){that.copyCurrentRecord();}});if(clipboard){result.setItem('r_1',null,{caption:'-'});clipboard.forEach(function(n){result.setItem(n.label,null,{caption:n.attr.caption,action:function(item){that.pasteClipboard(item.fullpath)},disabled:disabled});});}
result.setItem('r_2',null,{caption:'-'});result.setItem('r_3',null,{caption:_T('Clear clipboard')});return result;},copyCurrentRecord:function(){var controller=this.getControllerData();var clipboard=controller.getItem('clipboard')||new gnr.GnrBag();var copy=new gnr.GnrBag();var record=this.getFormData();record.forEach(function(n){if(n.label[0]!='@'&&n.label[0]!='$'&&!n.attr._sysfield){var value=n._value;if(isNullOrBlank(value)){return;}
if(value instanceof gnr.GnrBag){value=value.deepCopy();}
copy.setItem(n.label,value,n.attr);}},'static');clipboard.setItem(this.getCurrentPkey(),copy,{caption:this.getRecordCaption()})
controller.setItem('clipboard',clipboard);},pasteClipboard:function(path){var copybag;var controllerdata=this.getControllerData();var clipboard=controllerdata.getItem('clipboard')
var copy=clipboard.getNode(path);copybag=copy.getValue().deepCopy();this.updateFormData(copybag);},updateFormData:function(sourceBag){var destdata=this.getFormData();sourceBag.forEach(function(n){var value=n._value;if(value instanceof gnr.GnrBag){value=value.deepCopy();}
var destnode=destdata.getNode(n.label);destnode.setValue(value);});},clearClipboard:function(){this.getControllerData().setItem('clipboard',new gnr.GnrBag());},checkPendingGridEditor:function(){var pendingEditor;for(var k in this.gridEditors){if(this.gridEditors[k].grid.gnrediting){pendingEditor=this.gridEditors[k];break;}}
return pendingEditor;},save:function(kw,modifiers){var pendingEditor=this.checkPendingGridEditor(kw,modifiers);if(pendingEditor){var that=this;this.sourceNode.watch('pendingEditor',function(){return pendingEditor._exitCellTimeout==null;},function(){that.save(kw,modifiers);});return;}
kw=kw||{};var always;if(typeof(kw)=='object'){always=kw.command||kw.always;if(kw.modifiers=='Shift'){always=true;}}else{always=kw;kw={};}
if(!this.opStatus){always=always||this.getControllerData('is_newrecord');var invalid=!this.isValid();if(invalid&&!this.allowSaveInvalid){this.fireControllerData('save_failed','invalid');return'invalid:'+invalid;}
if(this.changed||always||this.isNewRecord()){return this.do_save(kw);}else{this.fireControllerData('save_failed','nochange');if(kw.destPkey){this.load({destPkey:kw.destPkey});}}}
else if(!this.autoSave){genro.playSound('Basso');return false;}},do_save:function(kw){if(!kw.forced&&this.saveDisabled()){this.publish('message',{message:_T('Cannot save. Blocked Form'),sound:'$error',messageType:'warning'});return;}
var destPkey=kw.destPkey;this.setOpStatus('saving');this.fireControllerData('saving');var saverNode=genro.nodeById(this.formId+'_saver');if(saverNode){saverNode.fireNode();return saverNode._lastDeferred;}else if(this.store){var onSaved=objectPop(kw,'onSaved')||this.store.onSaved;if(destPkey=='*dismiss*'){onSaved='dismiss';}
var onReload=objectPop(kw,'onReload');this.setLastSavedValues();var deferred=this.store.save(kw);if(deferred===false){this.setOpStatus();return;}
var that,cb;that=this;if(onSaved=='reload'||(destPkey&&(destPkey!=this.getCurrentPkey()))||(this.isNewRecord()&&onSaved=='lazyReload')){cb=function(resultDict){resultDict=resultDict||{};if(resultDict.error){if(resultDict.error!='gnrsilent'){that.publish('message',{message:'Error in save '+resultDict.error,sound:'$onsaved',messageType:'error'});}
that.setOpStatus();return;}
destPkey=destPkey||resultDict.savedPkey;if(resultDict.loadedRecordNode){that.setCurrentPkey(destPkey);that.store.loaded(destPkey,resultDict.loadedRecordNode);}else if(destPkey=='*duplicate*'){that.store.duplicateRecord(resultDict.savedPkey,kw.howmany);}else{that._reloadingAfterSave=(that.getCurrentPkey()==destPkey);that.setCurrentPkey(destPkey);if(that.store){that.doload_store({'destPkey':destPkey,'onReload':onReload});}else{that.doload_loader({'destPkey':destPkey});}}};}else{cb=function(result){result=result||{};if(result.error){that.publish('message',{message:'Error in save '+result.error,sound:'$onsaved',messageType:'error'});that.setOpStatus();return;}
that.reset();if(onSaved in that){that[onSaved](result);}else if(onSaved){funcApply(onSaved,{result:result},this);}
return result;};}
if(deferred){deferred.addCallback(function(result){cb(result);return result;});}else{this.reset();}
return deferred;}},lazyReload:function(result){var savedPkey=result.savedPkey;this.setCurrentPkey(savedPkey);var data=this.getFormData();var savedAttr=result.savedAttr;if(savedAttr){if(savedAttr.lastTS){data.getParentNode().attr.lastTS=result.savedAttr.lastTS;data.setItem('__mod_ts',convertFromText(result.savedAttr.lastTS),null,{doTrigger:false});}
var relatedLastTs=objectExtract(result.savedAttr,'lastTS_*');var rn,t;for(var k in relatedLastTs){rn=data.getNode('@'+k);t=relatedLastTs[k];rn.attr.lastTS=t;rn.getValue().setItem('__mod_ts',convertFromText(t),null,{doTrigger:false})}}
this.reset();this.setOpStatus();this.__last_save=new Date()
var invalidFields=this.getDataNodeAttributes()['_invalidFields'];if(invalidFields&&objectNotEmpty(invalidFields)){for(var p in invalidFields){data.setItem(p,data.getItem(p));}}},setInClientRecord:function(kw){var table=this.getControllerData('table');var that=this;if(kw.table==table&&kw.pkey==this.getCurrentPkey()&&!this.opStatus){var updater=convertFromText(kw.updater);updater.getNodes().forEach(function(n){that.externalChange(n.label,n.getValue(),!kw.silent);});}},setKeptData:function(valuepath,value,set){var keptData=this.keptData||{};if(set){keptData[valuepath]=value;}else{objectPop(keptData,valuepath);}
this.keptData=objectNotEmpty(keptData)?keptData:null;},saved:function(result){this.fireControllerData('saved');this.setOpStatus('saved');var savedPkey=result;if(this.store&&result){savedPkey=result.savedPkey;}
this.publish('onSaved',{pkey:savedPkey,saveResult:result});if(!this.autoSave){var savedAttr=(result?result.savedAttr:null)||{};this.publish('message',savedAttr.saved_message||{message:this.msg_saved,sound:'$onsaved'});}
return result;},openForm:function(idx,pkey){if(this.store&&false){this.load({destPkey:pkey});}else{this.fireControllerData('openFormPkey',pkey);this.fireControllerData('openFormIdx',idx);}},externalChange:function(field,value,triggerChanges){this.sourceNode.setRelativeData(this.formDatapath+'.'+field,value,triggerChanges?{}:{_loadedValue:value});},getFormData:function(){return this.sourceNode.getRelativeData(this.formDatapath,true,new gnr.GnrBag());},getControllerData:function(path){var cd=this.sourceNode.getRelativeData(this.controllerPath,true,new gnr.GnrBag());return path?cd.getItem(path):cd;},setControllerData:function(path,value){this.getControllerData().setItem(path,value,null,{lazySet:true});},fireControllerData:function(path,value,reason){this.getControllerData().fireItem(path,value,reason);},setFormData:function(data){if(data&&this.keptData){var newrecord=data.attr._newrecord;var n;var record=data._value;for(var k in this.keptData){n=record.getNode(k);if(newrecord){n.setValue(this.keptData[k]);}
n.attr._keep=true;}}
data=data||new gnr.GnrBag();this.sourceNode.setRelativeData(this.formDatapath,data);this.getDataNodeAttributes().record_root=true;},getDataNodeAttributes:function(){var data=this.sourceNode.getRelativeData(this.formDatapath);if(data){return data.getParentNode().attr;}
return{};},isNewRecord:function(){return this.getDataNodeAttributes()._newrecord;},onLoadingError:function(){return this.getDataNodeAttributes()._onLoadingError;},handleLoadedMessage:function(){var loadedMessage=this.getDataNodeAttributes().loaded_message;if(loadedMessage){this.message(loadedMessage);}},isProtectWrite:function(){var parentForm=this.getParentForm();var recAttr=this.getDataNodeAttributes();var protect_write=recAttr._protect_write;if(parentForm&&this.inheritProtect!==false){protect_write=protect_write||parentForm.isProtectWrite();}
return(protect_write?true:false)||this.readOnly||false;},isLogicalDeleted:function(){var logical_deleted=this.getDataNodeAttributes()._logical_deleted;return logical_deleted;},isDraft:function(){return this.getDataNodeAttributes()._draft;},setDraft:function(set){this.sourceNode.setRelativeData('.record.__is_draft',set);this.getDataNodeAttributes()._draft=set;genro.dom.setClass(this.sourceNode,'form_draft',set);},isProtectDelete:function(){return this.getDataNodeAttributes()._protect_delete;},hasChanges:function(){return this.getControllerData('changed');},getFormChanges:function(fullRecord){var data=this._getRecordCluster(this.getFormData(),!fullRecord);for(var k in this.gridEditors){var ge=this.gridEditors[k];if(!ge.storeInForm){var changeset=this.gridEditors[k].getChangeset();if(this.gridEditors[k].table&&changeset.len()>0){data.setItem('grids.'+k,changeset,{table:this.gridEditors[k].table});}}}
return data;},getFormCluster:function(){return this._getRecordCluster(this.getFormData(),false);},getCurrentPkey:function(){return this.pkeyPath?this.sourceNode.getRelativeData(this.pkeyPath):null;},setCurrentPkey:function(pkey){var currentPkey=this.getCurrentPkey()
this.sourceNode.setRelativeData(this.pkeyPath,pkey);if(pkey!=currentPkey&&this.store){this.store.loadedIndex=-1;}},getVirtualColumns:function(){var virtual_columns=[];this.sourceNode._value.walk(function(n){if(n.attr._virtual_column){virtual_columns.push(n.attr._virtual_column);}},'static');return virtual_columns.join(',');},_getRecordCluster:function(record,changesOnly,result,removed,parentpath){if(record){var parentpath=parentpath||this.sourceNode.absDatapath(this.formDatapath);var data=new gnr.GnrBag();data.__isRealChange=false;var node,sendBag,value,currpath,sendback;var recInfo=record.attributes();var isNewRecord=recInfo._newrecord;var bagnodes=record.getNodes();for(var i=0;i<bagnodes.length;i++){node=bagnodes[i];sendback=changesOnly?node.attr._sendback:true;if(sendback==false||node.label.slice(0,1)=='$'||node.attr.virtual_column){continue;}
currpath=parentpath?parentpath+'.'+node.label:node.label;value=node.getValue('static');if(removed){data.setItem(node.label,null,objectUpdate(node.attr,{'_deleterecord':true}));data.__isRealChange=true;}
else if(stringEndsWith(node.label,'_removed')){this._getRecordCluster(value,changesOnly,data,true,currpath);}
else if((node.attr.mode=='O')||(node.attr.mode=='M')||('_pkey'in node.attr)){this._getRecordCluster(value,changesOnly,data,false,currpath);}
else if(value instanceof gnr.GnrBag){var isRealChange=false;var gridEditorChanged=false;if(objectNotEmpty(this.gridEditors)){for(var k in this.gridEditors){var ge=this.gridEditors[k];if(node._id==ge.grid.storebag().getParentNode()._id){if(ge.status=='changed'){isRealChange=true;gridEditorChanged=true;};break;}}}
var hasLoadedValue=value.getNodeByAttr('_loadedValue')!=null;if(gridEditorChanged||(sendback==true)||isNewRecord||hasLoadedValue){value=value.deepCopy();if(hasLoadedValue){isRealChange=true;value.walk(function(n){if('_loadedValue'in n.attr){var loadedValue=objectPop(n.attr,'_loadedValue');var rowNode=n.getParentNode();if(rowNode&&!rowNode.attr._newrecord){n.attr.__old=asTypedTxt(loadedValue,n.attr.dtype);}}},'static');}
if(value.len()>0||!isNewRecord){data.setItem(node.label,value,objectUpdate({'_gnrbag':true},node.attr));data.__isRealChange=data.__isRealChange||isRealChange;}}}
else if((sendback==true)||isNewRecord||('_loadedValue'in node.attr)){var attr_dict={'dtype':node.attr.dtype};if(node.attr.promised){attr_dict.promised=node.attr.promised;}
if('_loadedValue'in node.attr){attr_dict.oldValue=asTypedTxt(node.attr._loadedValue,attr_dict['dtype']);data.__isRealChange=true;}
if(recInfo._alwaysSaveRecord){data.__isRealChange=true;}
data.setItem(node.label,value,attr_dict);}}
if(((data.len()>0)&&(data.__isRealChange))||(!result)){var result=result||new gnr.GnrBag();var recordNode=record.getParentNode();var resultattr=objectExtract(recordNode.attr,'_pkey,_newrecord,lastTS,mode,one_one,_invalidFields',true);result.setItem(recordNode.label,data,resultattr);result.__isRealChange=data.__isRealChange;}
return result;}},triggerUPD:function(kw){for(var k in this.gridEditors){var ge=this.gridEditors[k];if(ge.storeInForm){var storebag=ge.grid.storebag();if(kw.node.isChildOf(storebag)){return;}}}
if(kw.reason=='resolver'||kw.node.getFullpath().indexOf('$')>0||kw.node.attr.virtual_column){var invalidFields=this.getInvalidFields();var invalidDojo=this.getInvalidDojo();var ck=this.getChangeKey(kw.node);if(invalidFields&&invalidFields.len()){invalidFields._nodes.forEach(function(n){if(n.label.indexOf(ck)==0){invalidFields.popNode(n.label);}})}
return;}
var allowed=!this.isDisabled();if(this.disabledStatus()=='unlocked_readOnly'){allowed=!this._protectedNode(kw.node);}
if(kw.value==kw.oldvalue||(isNullOrBlank(kw.value)&&isNullOrBlank(kw.oldvalue))){if(kw.updattr&&kw.changedAttr){var cattr=kw.changedAttr;var oldvalue=kw.oldattr[cattr];var newvalue=kw.node.attr[cattr];var changekey=this.getChangeKey(kw.node)+cattr;var changes=this.getChangesLogger();var n=changes.getNode(changekey);if(n){if(n.attr.from==newvalue){changes.popNode(changekey);}else{n.attr.to=newvalue;}}else{changes.setItem(changekey,null,{_valuelabel:kw.reason.getElementLabel?kw.reason.getElementLabel():cattr,from:oldvalue,to:newvalue,allowed:allowed});}
this.updateStatus();}
return;}
if(kw.value instanceof gnr.GnrBag&&kw.reason!='_valuebag_'){}else if(kw.evt=='upd'){if(kw.updvalue){var changed=null;var changes=this.getChangesLogger();var changekey=this.getChangeKey(kw.node);if(!('_loadedValue'in kw.node.attr)){kw.node.attr._loadedValue=kw.oldvalue;changed=true;}else if(kw.node.attr._loadedValue==kw.value||(isNullOrBlank(kw.value)&&isNullOrBlank(kw.node.attr._loadedValue))){delete kw.node.attr._loadedValue;changed=false;}
if(changed!==false){changes.setItem(changekey,null,{_valuelabel:kw.reason.getElementLabel?kw.reason.getElementLabel():kw.node.label,from:kw.node.attr._loadedValue,to:kw.value,allowed:allowed});}else{changes.pop(changekey);}
this.updateStatus();}else{}}else{}},triggerINS:function(kw){if(kw.node.getFullpath().indexOf('$')>0){return;};if(kw.reason=='autocreate'||kw.reason=='_removedRow'){return;}
var changes=this.getChangesLogger();if(!('_loadedValue'in kw.node.attr)){kw.node.attr._loadedValue=null;}
var changekey=this.getChangeKey(kw.node);changes.setItem(changekey,null,{isNewNode:true});this.updateStatus();},triggerDEL:function(kw){var changes=this.getChangesLogger();var changekey=this.getChangeKey(kw.node);if(changes.getAttr(changekey,'isNewNode')){changes.pop(changekey);}else{changes.setItem(changekey,null);}
dojo.forEach(changes.getNodes(),function(n){if((changekey!=n.label)&&(n.label.indexOf(changekey)==0)){changes.popNode(n.label);}});this.updateStatus();},getChangeKey:function(changekey){if(typeof(changekey)!='string'){changekey=changekey.getFullpath(null,true);}
return changekey.replace(/[\.\?]/g,'_');},isNodeInFormData:function(datanode){if(!datanode){return false;}
var res=datanode.isChildOf(this.getFormData());return res;},updateInvalidField:function(sourceNode,changepath){var changeDataNode=genro.getDataNode(changepath);if(!this.isNodeInFormData(changeDataNode)){return;}
if(sourceNode==true){return;}
if(sourceNode.attr.rejectInvalid){return;}
var changekey=this.getChangeKey(changepath);if(changekey.indexOf('emptypath')>=0){return;}
var invalidfields=this.getInvalidFields();var invalidnodes=invalidfields.getItem(changekey);var sourceNode_id=sourceNode.getStringId();var isInvalid;if(sourceNode.hasValidationError()){isInvalid=true;if(!invalidnodes){invalidnodes={};invalidfields.setItem(changekey,invalidnodes);}
invalidnodes[sourceNode_id]=sourceNode._id;}else{isInvalid=false;objectPop(invalidnodes,sourceNode_id);if(!objectNotEmpty(invalidnodes)){invalidfields.pop(changekey);}}
if(this.allowSaveInvalid&&this.getCurrentPkey()&&!this.opStatus){this.setRecordInvalidFields(changeDataNode,isInvalid,sourceNode._validations)}
this.updateStatus();},recordOwnerNode:function(changeDataNode){var rnode=changeDataNode.getParentNode();while(rnode&&!(rnode.label=='record'||rnode.label[0]=='@'||rnode.attr.record_root)){rnode=rnode.getParentNode();}
return rnode;},setRecordInvalidFields:function(changeDataNode,invalid,validationsDict){var recordOwnerNode=this.recordOwnerNode(changeDataNode)
var _invalidFields=recordOwnerNode.attr['_invalidFields']||{};var fpath=changeDataNode.getFullpath('static',recordOwnerNode.getValue('static'));if(invalid){_invalidFields[fpath]={error:validationsDict.error,fieldcaption:changeDataNode.attr.name_long||fpath};}else{delete _invalidFields[fpath];}
recordOwnerNode.attr['_invalidFields']=_invalidFields;},handlePendingValidations:function(){if(objectNotEmpty(this._pendingValidations)){var that=this;var _pendingValidations=this._pendingValidations;this._pendingValidations=null;var sourceNode;for(var k in _pendingValidations){sourceNode=genro.src.nodeBySourceNodeId(_pendingValidations[k]);if(sourceNode){this.resolvePendingValidation(sourceNode);}}}},resolvePendingValidation:function(sourceNode){var vpath=sourceNode.absDatapath(sourceNode.attr.value);var datanode=genro.getDataNode(vpath);var recordOwnerNode=this.recordOwnerNode(datanode);if(!recordOwnerNode){return;}
var _invalidFields=recordOwnerNode.attr['_invalidFields']||{};var fpath=datanode.getFullpath('static',recordOwnerNode.getValue('static'));var result=genro.vld.validate(sourceNode,sourceNode.getAttributeFromDatasource('value'),false,true,(fpath in _invalidFields)?null:['notnull']);sourceNode.setValidationError(result);sourceNode.updateValidationStatus();},addPendingValidation:function(sourceNode){this._pendingValidations=this._pendingValidations||{};this._pendingValidations[sourceNode.getStringId()]=sourceNode._id;},isValid:function(){return((this.formErrors.len())==0&&(this.getInvalidFields().len()==0)&&(this.getInvalidDojo().len()==0))&&this.registeredGridsStatus()!='error';},setProtectWrite:function(set){set=set===undefined?true:set;var recAttr=this.getDataNodeAttributes();recAttr._protect_write=set;this.updateStatus();},registeredGridsStatus:function(storeInForm){var status=null;for(var k in this.gridEditors){if(storeInForm&&!this.gridEditors[k].storeInForm){continue;}
var gridstatus=objectValues(this.gridEditors[k].status);if(gridstatus.indexOf('error')>=0){return'error';}else if(gridstatus.indexOf('changed')>=0){status='changed';}}
return status;},updateStatus:function(){var isValid=this.isValid();this.setControllerData('valid',isValid);var status;var changes=this.getChangesLogger();var changed=(changes.len()>0||this.registeredGridsStatus()=='changed');this.record_changed=changes.len()>0||this.registeredGridsStatus(true);this.changed=changed;this.setControllerData('record_changed',this.record_changed);this.setControllerData('changed',changed);if(this.pkeyPath&&!this.getCurrentPkey()){status='noItem';}
else if(this.isProtectWrite()){status='readOnly';}
else if(!isValid){status='error';}
else{status=this.changed?'changed':'ok';}
if(this.status!=status){this.status=status;this.publish('onStatusChange',{'status':this.status});var formDomNode=this.formDomNode;var side;var formNodeWdg=this.sourceNode.widget;dojo.forEach(this._status_list,function(st){genro.dom.setClass(formDomNode,'form_'+st,st==status);for(var sidename in{'top':true,'bottom':true,'left':true,'right':true}){side=formNodeWdg?formNodeWdg['_'+sidename]:null;if(side){genro.dom.setClass(side,'formside_'+st,st==status);}}});}
this.applyDisabledStatus();},checkInvalidFields:function(){var node,sourceNode,node_identifiers,idx,changekey;var invalidfields=this.getInvalidFields();var invalidnodes=invalidfields.getNodes();for(var i=0;i<invalidnodes.length;i++){node=invalidnodes[i];node_identifiers=node.getValue();objectKeys(node_identifiers).forEach(function(idx){if(!genro.src.nodeBySourceNodeId(node_identifiers[idx])){objectPop(node_identifiers,idx);}})
if(!objectNotEmpty(node_identifiers)){invalidfields.popNode(node.label);continue;}
objectKeys(node_identifiers).forEach(function(idx){sourceNode=genro.src.nodeBySourceNodeId(node_identifiers[idx]);result=genro.vld.validate(sourceNode,sourceNode.getAttributeFromDatasource('value'));if(result['modified']){sourceNode.widget.setValue(result['value']);}
sourceNode.setValidationError(result);})}
var invalidDojo=this.getInvalidDojo();invalidDojo.keys().forEach(function(k){if(!genro.src.nodeBySourceNodeId(k)){invalidDojo.popNode(k);}})
this.updateStatus();},dojoValidation:function(wdg,isValid){var sn=wdg.sourceNode;var node_identifier=sn.getStringId();var dojoValid=this.getInvalidDojo();var changedNode=genro.getDataNode(wdg.sourceNode.absDatapath(wdg.sourceNode.attr.value));if(!this.isNodeInFormData(changedNode)){return;}
if(changedNode&&!changedNode.attr._loadedValue){return;}
if(isValid){dojoValid.popNode(node_identifier);}else{if(sn.attr.rejectInvalid){return;}
dojoValid.setItem(node_identifier,'Invalid value',{_valuelabel:sn.getElementLabel()});}
this.updateStatus();},focusFirstInvalidField:function(){if(dojo.isIE>0){return;}
var invalidFields=this.getInvalidFields();var first=invalidFields.getItem("#0");var key=objectKeyByIdx(first,0);var sourceNode=genro.src.nodeBySourceNodeId(first[key]);if(sourceNode&&sourceNode.widget){sourceNode.widget.focus();}},getInvalidFields:function(){return this.getControllerData().getItem('invalidFields')||new gnr.GnrBag();},getInvalidDojo:function(){return this.getControllerData().getItem('invalidDojo')||new gnr.GnrBag();},resetInvalidFields:function(){this.getControllerData().setItem('invalidFields',new gnr.GnrBag());this.getControllerData().setItem('invalidDojo',new gnr.GnrBag());this.formErrors=new gnr.GnrBag();this.updateStatus();},getChangesLogger:function(){return this.getControllerData().getItem('changesLogger')||new gnr.GnrBag();},resetChangesLogger:function(){this.getControllerData().setItem('changesLogger',new gnr.GnrBag());this.updateStatus();},hasChangesAtPath:function(path){var changesLogger=this.getChangesLogger();var chpath=path.replace(/\./g,'_');var labels=changesLogger.keys();for(var i=0;i<labels.length;i++){if(stringStartsWith(labels[i],chpath)){return true;}}},navigationEvent:function(kw){var loadkw={modifiers:kw.modifiers,cancelCb:kw.cancelCb}
var command=kw.command;if(command=='add'){loadkw.destPkey='*newrecord*';}else if(command=='dismiss'){loadkw.destPkey='*dismiss*';}else if(command=='duplicate'){loadkw.destPkey='*duplicate*';loadkw.howmany=kw.howmany}
else{loadkw.destPkey=this.store.navigationEvent(kw);}
this.load(loadkw);}});dojo.declare("gnr.GnrValidator",null,{validationTags:['select','notnull','empty','case','len','min','max','email','regex','call','gridnodup','nodup','exist','remote'],getCurrentValidations:function(sourceNode){return sourceNode.evaluateOnNode(objectExtract(sourceNode.attr,'validate_*',true));},validate:function(sourceNode,value,userChange,validateOnly,validationTags){var validations=this.getCurrentValidations(sourceNode);var result=this._validate(sourceNode,value,validations,validationTags||this.validationTags,userChange);if(!validateOnly){this.exitValidation(result,sourceNode,validations,userChange);}
return result;},_validate:function(sourceNode,value,validations,validationTags,userChange){var validation,validreturn;var result={'warnings':[]};result['value']=value;var parameters=objectUpdate({},validations);parameters.userChange=userChange;objectExtract(parameters,this.validationTags.join(','));for(var i=0;i<validationTags.length;i++){validation=validationTags[i];if((validation in validations)&&((validations[validation])||(validations[validation]===0))){validreturn=this.callValidation(validation,result['value'],sourceNode,validations,parameters);if(validreturn!=true){if(validreturn['required']){result['required']=validreturn['required'];}
if(validreturn['modified']){result['value']=validreturn['value'];result['modified']=true;}
if(validreturn['errorcode']){if(validreturn['iswarning']){result['warnings'].push(validreturn['message']);}else{result['error']=validreturn['message'];break;}}}}};return result;},callValidation:function(validation,value,sourceNode,validations,parameters){var errorcode,modified,iswarning,errormessage;var val_condition=objectPop(validations,validation+'_if');if(val_condition){var satisfy_cond=funcApply('return '+val_condition,objectUpdate({'value':value},parameters),sourceNode);if(!satisfy_cond){return true;}}
if(validation+'_iswarning'in validations){iswarning=validations[validation+'_iswarning'];}else{iswarning=((validations[validation+'_warning'])&&(!validations[validation+'_error']));}
var validHandler=this['validate_'+validation];var validreturn=validHandler.call(this,validations[validation],value,sourceNode,parameters);if((validreturn==null)||(validreturn==true)){return true;}else if(typeof(validreturn)=='object'){iswarning=validreturn['iswarning']||iswarning;if(('value'in validreturn)&&!(validreturn['value']===value)){modified=true;value=validreturn['value'];}
errorcode=validreturn['errorcode'];errormessage=validreturn.message;}else{if(validreturn==false){errorcode=iswarning?'warning':'error';}else if(typeof(validreturn)=='string'){errorcode=validreturn;}
validreturn={};}
if(errorcode&&!errormessage){var msgorder=[validation+'_'+errorcode];if(iswarning){msgorder.push(validation+'_warning');msgorder.push(validation+'_error');}else{msgorder.push(validation+'_error');msgorder.push(validation+'_warning');}
for(var i=0;i<msgorder.length;i++){errormessage=validations[msgorder[i]];if(errormessage)break;};errormessage=errormessage?errormessage:errorcode;}
validreturn['value']=value;validreturn['modified']=modified;validreturn['errorcode']=errorcode;validreturn['iswarning']=iswarning;if(errormessage){errormessage=dataTemplate(errormessage,validreturn);}
validreturn['message']=errormessage;return validreturn;},exitValidation:function(result,sourceNode,validations,userChange){var func;if(result['error']){if(validations['onReject']){func=funcCreate(validations['onReject'],'value,result,validations,rowIndex,userChange');}}else{if(validations['onAccept']){func=funcCreate(validations['onAccept'],'value,result,validations,rowIndex,userChange');}}
if(func){sourceNode._exitValidation=true;genro.callAfter(function(){func.call(sourceNode,result['value'],result,validations,sourceNode.editedRowIndex,userChange);delete sourceNode._exitValidation;},1);}},validate_notnull:function(param,value){if(isNullOrBlank(value)){return{'errorcode':'notnull','required':true};}},validate_select:function(param,value,sourceNode,parameters){if(dojo.isIE>0){return;}
var result;if(sourceNode.widget.item&&sourceNode.widget.item.attr._is_invalid_item){var invalidItemMsg=sourceNode.attr.invalidItem_message||_T('Invalid item');result={'errorcode':'invalidItem','message':invalidItemMsg,value:null};sourceNode.widget._lastValueReported=null;return result;}
if(sourceNode.widget._lastQueryError){return{'errorcode':'query_error','message':sourceNode.widget._lastQueryError};}
delete sourceNode.widget._lastQueryError;var validate_notnull=sourceNode.getAttributeFromDatasource('validate_notnull');if((value==undefined)||(value=='')||(value==null)){if(sourceNode.widget._lastDisplayedValue!=""){sourceNode.widget._updateSelect();result=validate_notnull?{'errorcode':'missing'}:null;if(!validate_notnull){genro.callAfter(function(){if(isNullOrBlank(sourceNode.widget.getValue())){sourceNode.widget.setDisplayedValue('');}},1);if(sourceNode._wrongSearch){result={'iswarning':'Not existing','errorcode':'missing'}}}
delete sourceNode._wrongSearch;}
sourceNode.widget._lastValueReported=null;return result;}},validate_empty:function(param,value){if(value==null||value===''){return{'value':param};}},validate_case:function(param,value,sourceNode){if(value){var original=value;param=param.toLowerCase();var oldvalue=sourceNode.getAttributeFromDatasource('value')||'';if(param=='upper'||param=='u'){value=value.toUpperCase();}else if(param=='lower'||param=='l'){value=value.toLowerCase();}else if(oldvalue.toLowerCase()!=value.toLowerCase()){if((param=='title'||param=='t')){value=stringCapitalize(value.toLowerCase());}else if(param=='capitalize'||param=='c'){value=value[0].toUpperCase()+value.slice(1);}}
if(original!=value){return{'value':value};}}},validate_min:function(param,value){return Math.round10(value,-9)>=Math.round10(param,-9);},validate_max:function(param,value){return Math.round10(value,-9)<=Math.round10(param,-9);},validate_len:function(param,value){if(value){if(param.indexOf(':')>=0){var sl=param.split(':');if(sl[1]){if(value.length>parseInt(sl[1])){return'too long';}}
if(sl[0]){if(value.length<parseInt(sl[0])){return'too short';}}}else{if(value.length!=parseInt(param)){return'wrong lenght';}}}},validate_regex:function(param,value){if(value){var not=false;param=param.trim()
if(param[0]=='!'){not=true;param=param.slice(1);}
var r=new RegExp(param);var result=r.test(value);return not?!result:result;}},validate_call:function(param,value,sourceNode,parameters){return funcApply(param,objectUpdate({'value':value},parameters),sourceNode);},validate_remote:function(param,value,sourceNode,parameters){if(value==null){return;}
var rpcresult=genro.rpc.remoteCall(param,objectUpdate({'value':value},parameters),null,'POST');if(parameters['_onResult']){var kw=objectUpdate({},parameters);kw['result']=rpcresult;funcApply(parameters['_onResult'],null,sourceNode,['result','kwargs'],[rpcresult,parameters]);}
if(rpcresult instanceof gnr.GnrBag){var result={};result['errorcode']=rpcresult.getItem('errorcode');result['iswarning']=rpcresult.getItem('iswarning');if(rpcresult.getNode('value')){result['value']=rpcresult.getItem('value');}
var datachanges=rpcresult.getItem('data');if(datachanges){var sdata=sourceNode.getRelativeData();sdata.update(datachanges);}
return result;}else{return rpcresult;}},validate_email:function(param,value){if(value){var r=new RegExp("^"+dojox.regexp.emailAddress()+"$","i");if(!r.test(value)){return{'iswarning':'checkit','errorcode':'Check email format'};}}},validate_gridnodup:function(param,value,sourceNode){var col=((typeof(param)=='string')&&param)?param:sourceNode.attr.field;if(value&&sourceNode.grid){var colvalues=sourceNode.grid.getColumnValues(col);var n=dojo.indexOf(colvalues,value);if((n!=-1)&&(n!=sourceNode.editedRowIndex)){return false;}}},validate_nodup:function(param,value,sourceNode,kwargs){var nodupkwargs=objectExtract(kwargs,'nodup_*');var relative=objectPop(nodupkwargs,'relative');if(relative){var _parent=sourceNode.getRelativeData('#FORM.record.'+relative);nodupkwargs['condition']="$"+relative+"=:_parent";nodupkwargs['_parent']=_parent;}
var dbfield=((typeof(param)=='string')&&param)?param:sourceNode.getAttributeFromDatasource('dbfield');if(value){var n=genro.rpc.getRecordCount(dbfield,value,null,nodupkwargs);if(n!=0){if(kwargs.warning){return{'iswarning':'duplicated_value','errorcode':kwargs.warning===true?'duplicated_value':kwargs.warning};}else{return{'errorcode':kwargs.error||'duplicated_value'};}}}},validate_exist:function(param,value,sourceNode){var dbfield=((typeof(param)=='string')&&param)?param:sourceNode.getAttributeFromDatasource('dbfield');if(value){var n=genro.rpc.getRecordCount(dbfield,value);if(n==0){return false;}}}});dojo.declare("gnr.formstores.Base",null,{recordCluster_onSaved:'reload',constructor:function(kw,handlers){objectPop(kw,'tag');this.handlers=handlers;this.storepath='.record';this.parentStoreCode=objectPop(kw,'parentStore');var base_handler_type=objectPop(kw,'handler');this.base_handler_type=base_handler_type;var handlerKw=objectExtract(kw,'handler_*');var handler,handler_type,method,actionKw,callbacks,defaultCb;var that=this;var rpcmethod;dojo.forEach(['save','load','del'],function(action){actionKw=objectExtract(handlerKw,action+'_*');handler=objectUpdate({},that.handlers[action]);handler_type=objectPop(handler,'handler_type')||objectPop(handlerKw,action)||base_handler_type;if(typeof(handler_type)=='function'){method=handler_type;}else if(that[action+'_'+handler_type]){method=that[action+'_'+handler_type];}else{method=funcCreate(handler_type);}
callbacks=objectPop(handler,'callbacks');rpcmethod=objectPop(handler,'rpcmethod');defaultCb=funcCreate(objectPop(handler,'defaultCb'),'kw');that.handlers[action]={'kw':objectUpdate(actionKw,handler),'method':method,'callbacks':callbacks,'rpcmethod':rpcmethod,defaultCb:defaultCb};});for(var k in kw){this[k]=kw[k];}
if(!this.onSaved){var handler_onSaved=this.handlers.save.kw.onSaved;this.onSaved=handler_onSaved==null?this[base_handler_type+'_onSaved']:handler_onSaved;}},init:function(form){this.form=form;if(this.parentStoreCode){this.parentStore=genro.getStore(this.parentStoreCode);if(this.base_handler_type=='memory'){this.locationpath=this.parentStore.storeNode.absDatapath(this.parentStore.storepath)}}},getStartPkey:function(){return;},getParentStoreData:function(){return this.parentStore.getData();},load_dummy:function(loadkw){var result=this.form.getFormData().deepCopy();this.loaded('*newrecord*',result);return result;},save_dummy:function(loadkw){},load_document:function(kw){var default_kw=kw.default_kw;var form=this.form;var that=this;var currPkey=this.form.getCurrentPkey();var data;var loader=this.handlers.load;var kw=loader.kw||{};var maincb=kw._onResult?funcCreate(kw._onResult,'result',form.sourceNode):function(){};kw=form.sourceNode.evaluateOnNode(kw);var envelope=new gnr.GnrBag();var path=currPkey;this.prepareDefaults(null,default_kw,kw);this.handlers.load.rpcmethod=loader.rpcmethod||'getSiteDocument';var deferred=genro.rpc.remoteCall(loader.rpcmethod,objectUpdate({'path':path},kw),null,'POST',null,maincb);deferred.addCallback(function(result){var contentNode=result.popNode('content');var content=contentNode.getValue();var rec;if(content instanceof gnr.GnrBag){rec=contentNode;}else{rec=new gnr.GnrBag({'content':content})}
that.loaded(path,rec);return result;})
if(loader.callbacks){this.handle_deferredCallBacks(deferred,loader.callbacks,kw);}
return deferred;},save_document:function(kw){var data=this.form.getFormData();if(this.handlers.save.stripLoadedValue){data.walk(function(n){delete n.attr._loadedValue;});}
this.handlers.save.rpcmethod=this.handlers.save.rpcmethod||'saveSiteDocument';var saver=this.handlers.save;var that=this;var path=this.form.getCurrentPkey();var rpc_kw=this.form.sourceNode.evaluateOnNode(this.handlers.save.kw);rpc_kw.path=path;if(path=='*newrecord*'&&this.getNewPath){path=funcApply(this.getNewPath,{record:formData},form);}
var data=data.deepCopy();rpc_kw.data=data;var deferred=genro.rpc.remoteCall(saver.rpcmethod,rpc_kw,null,'POST',null,function(){});deferred.addCallback(function(result){result=result||{};var resultDict={};var pkeyNode=result;resultDict.savedPkey=result.path||path;that.form.setCurrentPkey(resultDict.savedPkey);that.saved(resultDict);var deferred;if(that.parentStore){deferred=that.parentStore.loadData();}
that.loaded(resultDict.savedPkey,data);if(deferred instanceof dojo.Deferred){deferred.addCallback(function(){that.setNavigationStatus(resultDict.savedPkey);})}
return result;})
if(saver.callbacks){this.handle_deferredCallBacks(deferred,saver.callbacks,kw);}
return deferred;},del_document:function(pkey,callkw){var deleter=this.handlers.del;var form=this.form;var that=this;var kw=form.sourceNode.evaluateOnNode(this.handlers.del.kw);pkey=pkey||form.getCurrentPkey();var default_deletemethod=this.parentStore?this.parentStore.deletemethod||'app.deleteFileRows':'app.deleteFileRows';this.handlers.del.rpcmethod=this.handlers.del.rpcmethod||default_deletemethod;var that=this;var deferred=genro.rpc.remoteCall(this.handlers.del.rpcmethod,objectUpdate({'files':pkey,'_sourceNode':form.sourceNode},kw),null,'POST',null,function(){if(that.parentStore){that.parentStore.loadData();}});var cb=function(result){that.deleted(result,callkw);return result;};deferred.addCallback(cb);if(deleter.callbacks){this.handle_deferredCallBacks(deferred,deleter.callbacks,kw);}
return deferred;},prepareDefaults:function(pkey,default_kw,kw){var form=this.form;var loader=this.handlers.load;kw=kw||objectUpdate({},loader.kw);var default_kwargs=objectPop(kw,'default_kwargs')||{};form.last_default_kw=objectUpdate({},default_kw);if(default_kwargs){default_kwargs=form.sourceNode.evaluateOnNode(default_kwargs);}
if(!pkey||pkey=='*newrecord*'){default_kw=default_kw||{}
if(loader.defaultCb){default_kw=objectUpdate(default_kw,(loader.defaultCb.call(form,kw)||{}));}
objectUpdate(default_kwargs,form.sourceNode.evaluateOnNode(default_kw));}
if(objectNotEmpty(default_kwargs)){for(var k in default_kwargs){kw['default_'+k]=default_kwargs[k]}}
return kw;},duplicateRecord:function(srcPkey,howmany){var form=this.form;var that=this;var srcPkey=srcPkey||this.form.getCurrentPkey();var howmany=howmany||1;if(howmany=='?'){var that=this;genro.dlg.prompt('How many',{msg:_T('How many copies of current record?'),lbl:_T('How many'),widget:'numberTextBox',action:function(value){that.duplicateRecord(srcPkey,value);}});return}
genro.assert(this.table,'only form with table allow duplicate');genro.serverCall('app.duplicateRecord',{table:this.table,pkey:srcPkey,howmany:howmany},function(resultPkey){form.doload_store({destPkey:resultPkey});})},handle_deferredCallBacks:function(deferred,cblist,kw){kw=kw||{};var thatnode=this.form.sourceNode;cblist.forEach(function(n){var defkw=objectUpdate({},kw);genro.rpc.addDeferredCb(deferred,n.getValue(),objectUpdate(defkw,n.attr),thatnode);});},load_recordCluster:function(loadkw){var default_kw=loadkw.default_kw;var ignoreReadOnly=loadkw?objectPop(loadkw,'ignoreReadOnly'):null;var form=this.form;var that=this;var currPkey=this.form.getCurrentPkey();var loader=this.handlers.load;var cb=function(result){that.loaded(currPkey,result);return result;};var kw=loader.kw||{};var maincb=kw._onResult?funcCreate(kw._onResult,'result',form.sourceNode):function(){};kw=form.sourceNode.evaluateOnNode(kw);this.prepareDefaults(currPkey,default_kw,kw);loader.rpcmethod=loader.rpcmethod||'loadRecordCluster';kw.sqlContextName=('sqlContextName'in kw)?kw.sqlContextName:form.formId;var virtual_columns=objectPop(kw,'virtual_columns');var form_virtual_columns=form.getVirtualColumns();virtual_columns=virtual_columns?virtual_columns.split(','):[]
form_virtual_columns=form_virtual_columns?form_virtual_columns.split(','):[]
virtual_columns=virtual_columns.concat(form_virtual_columns);kw['_sourceNode']=form.sourceNode;kw.ignoreReadOnly=ignoreReadOnly;var dbstoreOnDeferred=false;if(this.form.dbstoreField){objectPop(that.form.sourceNode.attr,'context_dbstore')
dbstoreOnDeferred=true;var row;if(this.parentStore){let rowNode=this.parentStore.rowBagNodeByIdentifier(currPkey);if(rowNode){row=this.parentStore.rowFromItem(rowNode);}}
if(row&&row[this.form.dbstoreField]){this.form.sourceNode.attr.context_dbstore=row[this.form.dbstoreField];dbstoreOnDeferred=false;}}
var deferred=genro.rpc.remoteCall(loader.rpcmethod,objectUpdate({'pkey':currPkey,'virtual_columns':arrayUniquify(virtual_columns).join(','),'table':this.table,timeout:0},kw),null,'POST',null,maincb);if(dbstoreOnDeferred){deferred.addCallback(function(result){var dbstore=result.getValue().getItem(that.form.dbstoreField);if(dbstore){that.form.sourceNode.attr.context_dbstore=dbstore;}
return result;});}
deferred.addCallback(cb);if(loader.callbacks){this.handle_deferredCallBacks(deferred,loader.callbacks,kw);}
return deferred;},save_recordCluster:function(kw){var form=this.form;var that=this;var saver=this.handlers.save;var saveKw=objectUpdate({},kw);var originalSaveKw=objectUpdate({},kw)
var destPkey=objectPop(saveKw,'destPkey');var kw=form.sourceNode.evaluateOnNode(this.handlers.save.kw);objectUpdate(kw,saveKw);var fullRecord=objectPop(kw,'fullRecord');var onSaving=objectPop(kw,'onSaving');kw['_sourceNode']=form.sourceNode;kw['_autoreload']=kw['_autoreload']||false;if(kw._autoreload){if(destPkey){kw._autoreload=destPkey;}else if(this.onSaved=='reload'||this.form.isNewRecord()){kw._autoreload=true;}}
var autoreload=kw._autoreload;var data=form.getFormChanges(fullRecord);var cb=function(result){var resultDict={};if(result){if(result.error){resultDict['error']=result.error;}
else if(autoreload){var loadedRecordNode=result.getNode('loadedRecord');var pkeyNode=result.getNode('pkey');resultDict.savedPkey=pkeyNode.getValue();resultDict.savedAttr=pkeyNode.attr;resultDict.loadedRecordNode=loadedRecordNode;}else{var pkeyNode=result;resultDict.savedPkey=pkeyNode.getValue();resultDict.savedAttr=pkeyNode.attr;}}
that.saved(resultDict);form.waitingStatus(false);return resultDict;};this.handlers.save.rpcmethod=this.handlers.save.rpcmethod||'saveRecordCluster';var rpckw=objectUpdate({'data':data,'table':this.table,save_kw:originalSaveKw},kw);if(onSaving){var dosave=funcApply(onSaving,rpckw,this);if(dosave===false){return false;}}
var waitingStatus=objectPop(rpckw,'waitingStatus');form.waitingStatus(waitingStatus===false?false:true);var deferred=genro.rpc.remoteCall(this.handlers.save.rpcmethod,rpckw,null,'POST',null,function(){});deferred.addCallback(cb);if(saver.callbacks){this.handle_deferredCallBacks(deferred,saver.callbacks,kw);}
return deferred;},del_recordCluster:function(pkey,callkw){var deleter=this.handlers.del;var form=this.form;var that=this;var kw=form.sourceNode.evaluateOnNode(this.handlers.del.kw);pkey=pkey||form.getCurrentPkey();this.handlers.del.rpcmethod=this.handlers.del.rpcmethod||'deleteDbRow';var deferred=genro.rpc.remoteCall(this.handlers.del.rpcmethod,objectUpdate({'pkey':pkey,'table':this.table,'_sourceNode':form.sourceNode},kw),null,'POST',null,function(){});var cb=function(result){that.deleted(result,callkw);return result;};deferred.addCallback(cb);if(deleter.callbacks){this.handle_deferredCallBacks(deferred,deleter.callbacks,kw);}
return deferred;},loaded:function(pkey,result){this.setNavigationStatus(pkey);this.form.loaded(result);},deleted:function(result,kw){this.form.deleted(result,kw);},saved:function(result){return this.form.saved(result);},save:function(kw){return this.handlers.save.method.call(this,kw);},load:function(loadkw){return this.handlers.load.method.call(this,loadkw);},deleteItem:function(pkey,kw){return this.handlers.del.method.call(this,pkey,kw);},setNavigationStatus:function(){return;},navigationEvent:function(kw){},getDefaultDestPkey:function(){}});dojo.declare("gnr.formstores.SubForm",gnr.formstores.Base,{load_memory:function(){var form=this.form;var parentForm=form.getParentForm();var subRecordKeys=form.getFormData().keys();var r=new gnr.GnrBag();var parentRecord=parentForm.getFormData();dojo.forEach(subRecordKeys,function(field){var n=parentRecord.getNode(field);if(n){r.setItem(field,n.getValue());}});this.loaded('*subform*',r);},save_memory:function(kw){var saveKw=objectUpdate({},kw);var form=this.form;var parentForm=form.getParentForm();var subRecord=form.getFormData();var parentRecord=parentForm.getFormData();subRecord.forEach(function(n){parentRecord.setItem(n.label,n.getValue());});this.saved({});form.loaded();if(kw.destPkey=='*dismiss*'){form.dismiss(kw);}},getDefaultDestPkey:function(){return'*subform*';}});dojo.declare("gnr.formstores.Item",gnr.formstores.Base,{setLocationPath:function(locationpath,onchanged){if(this.form.changed){onchanged=onchanged||'ignore';if(onchanged=='raise'){genro.dlg.alert('You cannot change locationpath to this form','Warning');return;}
if(onchanged=='save'){this.form.save();}else{this.form.load();}}
this.locationpath=locationpath;},load_memory:function(loadkw){var default_kw=loadkw.default_kw||{};var destPkey=loadkw.destPkey;var form=this.form;var that=this;var data;var loader=this.handlers.load;var kw=loader.kw||{};var maincb=kw._onResult?funcCreate(kw._onResult,'result',form.sourceNode):function(){};kw=form.sourceNode.evaluateOnNode(kw);var envelope=new gnr.GnrBag();var recordLoaded=new gnr.GnrBag();var sourceBag=form.sourceNode.getRelativeData(this.locationpath);kw._newrecord=(destPkey=='*newrecord*'||sourceBag==null||sourceBag.len()===0);if(kw._newrecord){default_kw=objectExtract(this.prepareDefaults(null,default_kw),'default_*');for(var k in default_kw){recordLoaded.setItem(k,objectPop(default_kw,k));}}
else if(sourceBag&&this.locationpath){var kw=objectExtract(sourceBag.getParentNode().attr,'lastTS,caption,_protect_delete,_protect_write,_pkey',true);var d=sourceBag.deepCopy();d.walk(function(n){n.attr={}})
d.forEach(function(n){recordLoaded.setItem(n.label,n.getValue());});}
envelope.setItem('record',recordLoaded,kw);var result=envelope.getNode('record');this.loaded('',result);return result;},save_memory:function(kw){var saveKw=objectUpdate({},kw);var form=this.form;var sourceBag=form.sourceNode.getRelativeData(this.locationpath);if(!sourceBag){sourceBag=new gnr.GnrBag();form.sourceNode.setRelativeData(this.locationpath,sourceBag);}
var formData=form.getFormData();var oldsubbag,path;formData.walk(function(n){var v=n.getValue();var kw={dtype:n.attr.dtype};path=n.getFullpath('static',formData);if('_displayedValue'in n.attr){kw._displayedValue=n.attr._displayedValue;}
if('_formattedValue'in n.attr){kw._formattedValue=n.attr._formattedValue;}
if('_valuelabel'in n.attr){kw._valuelabel=n.attr._valuelabel;}
if(v instanceof gnr.GnrBag){oldsubbag=sourceBag.getItem(path);if(oldsubbag){sourceBag.pop(path);}
sourceBag.setItem(path,v);return'__continue__';}
sourceBag.setItem(path,n.getValue(),{dtype:n.attr.dtype},{lazySet:true});});var result={};this.saved(result);this.form.reset();this.form.load(kw);},getDefaultDestPkey:function(){return'*loaditem*';}});dojo.declare("gnr.formstores.Collection",gnr.formstores.Base,{getDefaultDestPkey:function(){return'*norecord*';},getStartPkey:function(){return this.getNavigationPkey(0);},setNavigationStatus:function(pkey){var currIdx=-1;if(pkey!='*norecord*'&&pkey!='*newrecord*'){var currIdx=this.parentStore.getIdxFromPkey(pkey,true);if(this.loadedIndex!=null&&this.loadedIndex>=0&&currIdx<0){return;}}
var kw={};if(currIdx<0){kw.first=true;kw.last=true;}
else{if(currIdx==0){kw.first=true;}
if(currIdx>=this.parentStore.len(true)-1){kw.last=true;}}
this.loadedIndex=currIdx;this.form.publish('navigationStatus',kw);return;},navigationEvent:function(kw){var command=kw.command;return this.getNavigationPkey(command,this.form.getCurrentPkey());},getNavigationPkey:function(nav,currentPkey){var idx=nav==parseInt(nav)&&nav;if(!idx){if(nav=='first'){idx=0;}else if(nav=='last'){idx=this.parentStore.len(true)-1;}else{idx=this.parentStore.getIdxFromPkey(currentPkey,true);if(idx<0){if(this.loadedIndex>=0){idx=nav=='next'?this.loadedIndex:this.loadedIndex-1;}else{console.log('out of selection');}}else{idx=nav=='next'?idx+1:idx-1;}}}
return this.parentStore.getKeyFromIdx(idx,true);},load_memory:function(loadkw){var default_kw=loadkw.default_kw;var form=this.form;var that=this;var currPkey=this.form.getCurrentPkey();var data;var loader=this.handlers.load;var kw=loader.kw||{};var maincb=kw._onResult?funcCreate(kw._onResult,'result',form.sourceNode):function(){};kw=form.sourceNode.evaluateOnNode(kw);var envelope=new gnr.GnrBag();if(currPkey=='*newrecord*'){data=new gnr.GnrBag();this.prepareDefaults(currPkey,default_kw,kw);data.update(objectExtract(kw,'default_*'));envelope.setItem('record',data,{_newrecord:true,lastTS:null,caption:kw.newrecord_caption});}else{var dataNode=this.parentStore.rowBagNodeByIdentifier(currPkey);genro.assert(dataNode,'Missing data for currentPath',currPkey);var kw=objectExtract(dataNode.attr,'lastTS,caption,_protect_delete,_protect_write,_pkey',true);var recordLoaded=new gnr.GnrBag();var d=dataNode.getValue().deepCopy();d.walk(function(n){n.attr={}})
d.forEach(function(n){recordLoaded.setItem(n.label,n.getValue());});envelope.setItem('record',recordLoaded,kw);}
var result=envelope.getNode('record');this.loaded(currPkey,result);return result;},save_memory:function(kw){var form=this.form;var saveKw=form.sourceNode.evaluateOnNode(this.handlers.save.kw);saveKw=objectUpdate(saveKw,kw);var destPkey=objectPop(saveKw,'destPkey');var sourceBag=form.sourceNode.getRelativeData(this.locationpath);var formData=form.getFormData();var onSaving=objectPop(saveKw,'onSaving');if(onSaving){var dosave=funcApply(onSaving,{data:formData},this);if(dosave===false){this.form.setOpStatus(null);return;}}
var currPkey=form.getCurrentPkey();var pkeyField=this.pkeyField||'_pkey';var newPkey=pkeyField?formData.getItem(pkeyField):null;var data,olddata;var newrecord=currPkey=='*newrecord*';if(newrecord){data=new gnr.GnrBag();if(!newPkey){if(this.newPkeyCb){newPkey=funcApply(this.newPkeyCb,{record:formData},form);}else{newPkey='r_'+(sourceBag?sourceBag.len():0);}
data.setItem(pkeyField,newPkey);formData.setItem(pkeyField,newPkey);}
sourceBag.setItem(flattenString(newPkey,['.',' ']),data);}else{data=sourceBag.getItem(currPkey);if(currPkey!=newPkey){data.getParentNode().label=newPkey;}}
form.setCurrentPkey(newPkey);var path,v,oldsubbag;formData.walk(function(n){v=n.getValue();path=n.getFullpath('static',formData);if(v instanceof gnr.GnrBag){oldsubbag=data.getItem(path);if(oldsubbag){data.pop(path);}
data.setItem(path,v)
return'__continue__';}
data.setItem(path,n.getValue(),{dtype:n.attr.dtype},{lazySet:true});});var result={};this.saved(result);if(destPkey){this.form.reset();this.form.load({destPkey:destPkey});}else{this.form.load({destPkey:newPkey});}},del_memory:function(pkey,callkw){var sourceBag=this.form.sourceNode.getRelativeData(this.locationpath);var currPkey=this.form.getCurrentPkey();sourceBag.popNode(currPkey);this.deleted(null,callkw);}});dojo.declare("gnr.formstores.Hierarchical",gnr.formstores.Base,{});



dojo.declare("gnr.GnrDevHandler",null,{constructor:function(application){this.application=application;},inspectConnect:function(pane){pane=pane||genro.domById('mainWindow');dojo.connect(pane,'onmousemove',function(e){if(e.altKey&&e.shiftKey){var sourceNode=genro.src.enclosingSourceNode(e.target);genro.src.highlightNode(sourceNode);genro.publish('srcInspector_editnode',sourceNode);}else{genro.src.highlightNode();}});dojo.connect(pane,'onmouseout',function(e){genro.src.highlightNode();});dojo.connect(pane,'onclick',function(e){if(e.altKey&&e.shiftKey){var sourceNode=genro.src.enclosingSourceNode(e.target);genro.dev.openBagNodeEditorPalette(sourceNode.getFullpath(),{name:'_devSrcInspector_',title:'Sourcenode Inspector',origin:'*S'});console.log('------current edit node:-------');genro.publish('srcInspector_editnode',sourceNode);console.log(sourceNode);window._sourceNode_=sourceNode;}});},openBagNodeEditorPalette:function(nodePath,kw){var root=genro.src.newRoot();var name=kw.name||'_currentBagNodeEditor_';genro.src.getNode()._('div',name);var node=genro.src.getNode(name).clearValue();node.freeze();node._('PaletteBagNodeEditor','currentEditor',objectUpdate({'paletteCode':name,'dockTo':false,title:kw.title||'BagNode editor','nodePath':nodePath},kw));node.unfreeze();},openBagInspector:function(path,kw){kw=kw||{};var code=objectPop(kw,'code')||path.replace(/\./g,'_').replace(/@/g,'_');var wdg=genro.wdgById(code+'_floating');if(wdg){wdg.show();wdg.bringToTop();return;}
var root=genro.src.newRoot();var name=kw.name||'_currentBagEditor_'+code;genro.src.getNode()._('div',name);var node=genro.src.getNode(name).clearValue();node.freeze();node._('paletteTree',{'paletteCode':code,title:objectPop(kw,'title')||'Edit Bag '+path,storepath:path,searchOn:true,tree_inspect:'shift',tree_searchMode:'static','tree_selectedLabelClass':'selectedTreeNode',editable:true,tree_labelAttribute:null,tree_hideValues:false,dockTo:'dummyDock:open'});node.unfreeze();},openBagEditorPalette:function(path,kw){kw=kw||{};var root=genro.src.newRoot();var name=kw.name||'_currentPaletteBagEditor_';genro.src.getNode()._('div',name);var node=genro.src.getNode(name).clearValue();node.freeze();node._('PaletteBagEditor','currentBagEditor',objectUpdate({'paletteCode':name,'dockTo':false,title:kw.title||'Bag editor','path':path},kw));node.unfreeze();return;},siteLockedStatus:function(set){var maingenro=genro.mainGenroWindow.genro;var sn=maingenro.nodeById('_gnrRoot');if(!sn){return;}
if(set){if(!maingenro.site_locked){maingenro.site_locked=true;sn.setHiderLayer(true,{message:'Site temporary unavailable',z_index:999998,message_color:'white',message_font_size:'30pt',message_background:'red',message_padding:'20px',message_margin:'20%'});}}else if(maingenro.site_locked){maingenro.site_locked=false;sn.setHiderLayer(false);}},debugMessage:function(msg,level,duration){level=level||'MESSAGE';duration=duration||50;dojo.publish("standardDebugger",{message:msg,type:level.toUpperCase(),duration:duration});},handleRpcHttpError:function(response,ioArgs){if(response.dojoType=='cancel'){return;}
var xhr=ioArgs.xhr;if(response.dojoType=='cancel'){return;}
var status=xhr.status;var statusText=xhr.statusText;var readyState=xhr.readyState;var responseText=xhr.responseText;if(status==400){genro.dlg.alert('Client HTTP error','Error',null,null,{confirmCb:genro.pageReload});return;}
else if(status==412){var mainGenroWindow=genro.mainGenroWindow.genro;mainGenroWindow.polling_enabled=false;mainGenroWindow.dlg.alert('No longer existing page','Error',null,null,{confirmCb:genro.pageReload});return;}else if(status===0){var msg='status: '+xhr.status+' - statusText:'+xhr.statusText+' - readyState:'+xhr.readyState+' - responseText:'+responseText;console.log(ioArgs.url);console.log(msg);console.log(ioArgs);}
else{console.log('handleRpcHttpError');debug_url=ioArgs.xhr.getResponseHeader('X-Debug-Url');if(!debug_url){console.error('RESPONSE',response,'ioArgs',ioArgs,responseText)
genro.dev.addError("An HTTP error occurred: "+response.message,'SERVER',true);if(genro.isDeveloper){}}
else{if(genro.isDeveloper){genro.openWindow(debug_url,'Internal Server Error',{scrollbars:'yes'});}else{genro.dlg.ask('Server error','<h2 align="">Sorry. There was a server error</h2>. <br/> <i>For more details see</i> <br/>'+_F(debug_url,'autolink'),{confirm:'Reload',cancel:'Ignore'},{confirm:function(){genro.pageReload();}});}}}},handleRpcError:function(error,envNode){if(error=='gnrsilent'){var v=envNode.getValue();if(v instanceof gnr.GnrBag){if(v.getItem('topic')){genro.publish(v.getItem('topic'),v.getItem('parameters').asDict());}}
return;}
if(error=='gnrexception'){if(genro.src.getNode()){genro.dlg.alert('<h2 align="center">'+envNode.getValue()+'</h2> <br/>','Warning');}else{dojo.byId('mainWindow').innerHTML='<h2 class="selectable" style="color:red;" align="center">'+envNode.getValue()+'</h2> <br/>';}
return;}else if(error=='server_exception'){if(genro.src.getNode()){genro.dlg.alert('<h3 align="center">'+envNode.getValue()+'</h3> <br/>','Error');}else{dojo.byId('mainWindow').innerHTML='<h2 class="selectable" style="color:red;" align="center">'+envNode.getValue()+'</h2> <br/>';}
return;}
if(error=='expired'){genro.dlg.message('expired session');genro.dlg.ask('Expired session','<h2 align="">Sorry. The session is expired</h2>.<br/>',{confirm:'Reload'},{confirm:function(){genro.mainGenroWindow.genro.pageReload();}});}
else if(error=='clientError'){genro.dlg.alert('clientError');}else if(error=='serverError'){var root=genro.src.newRoot();var fpane=root._('dialog','traceback',{title:'Trace',nodeId:'traceback_main',_class:'tracebackDialog'});fpane.setItem('',envNode.getValue());genro.src.setSource('traceback',root);genro.wdgById('traceback_main').show();}},serverWriteError:function(error_description,error_type,kw){var kw=kw||{};objectUpdate(kw,{description:error_description,error_type:error_type});genro.serverCall('site.writeError',kw,function(){console.warn(error_type,error_description)});},formbuilder:function(node,col,tblattr){var defautlLblAttr=objectExtract(tblattr,'lbl_*');var tbl=node._('table',tblattr||{})._('tbody');tbl.col_max=col||1;tbl.col_count=tbl.col_max+1;tbl.addField=function(tag,kw){if(this.col_count>this.col_max){this.curr_tr=this._('tr');this.col_count=1;}
var colspan=objectPop(kw,'colspan')||1;colspan=colspan==1?colspan:colspan*2;var lbl=_T(objectPop(kw,'lbl'));if(kw.label){kw.label=_T(kw.label);}
var lblpars={innerHTML:lbl?_T(lbl,true):null,_class:'gnrfieldlabel',hidden:kw.hidden,text_align:'right'};lblpars=objectUpdate(defautlLblAttr,lblpars);objectUpdate(lblpars,objectExtract(kw,'lbl_*'));var tr=this.curr_tr;tr._('td',lblpars);var res=tr._('td',objectUpdate({colspan:colspan},objectExtract(kw,'td_*')))._(tag,kw);var default_value=objectPop(kw,'default_value');var resNode=res.getParentNode();if(default_value&&resNode.attr.value){resNode.setRelativeData(resNode.attr.value,default_value);}
this.col_count=this.col_count+colspan;return res;};return tbl;},relationExplorer:function(table,title,rect){rect=rect||{'top':'10px','right':'10px','height':'300px','width':'200px'};var code=table.replace('.','_');genro.src.getNode()._('div','_relationExplorer_'+code);var node=genro.src.getNode('_relationExplorer_'+code).clearValue();node.freeze();var fpane=node._('floatingPane',{title:title,top:rect.top,bottom:rect.bottom,left:rect.left,right:rect.right,height:rect.height,width:rect.width,resizable:true,dockable:false,_class:'shadow_4',closable:true});this.fieldsTree(fpane,table);node.unfreeze();fpane.getParentNode().widget.bringToTop();},tableUserConfiguration:function(table){var onSavedCb=null;genro.dlg.zoomPalette({height:'600px',width:'700px',table:'adm.tblinfo',pkey:table,formResource:'FormFromTH',main_call:'main_form',onSavedCb:onSavedCb,top:'30px',right:'40px'});},fieldsTree:function(pane,table,kw){kw=kw||{};var path=kw.explorerPath||'gnr.relation_explorers.'+table;var checkPermissions=objectPop(kw,'checkPermissions');var dragCode=objectPop(kw,'dragCode')||'gnrdbfld_'+table.replace('.','_');genro.setData(path,genro.rpc.remoteResolver('relationExplorer',{'table':table,'currRecordPath':objectPop(kw,'currRecordPath'),omit:'_',item_type:'FTREE',checkPermissions:checkPermissions}));var treeattr=objectUpdate({storepath:path,margin:'4px'},kw);treeattr.labelAttribute='caption';treeattr._class='fieldsTree noIcon noExpando';treeattr.hideValues=true;treeattr.autoCollapse=true;treeattr.openOnClick=true;treeattr.getLabelClass=function(item){var dtype=item.attr.dtype;var _class=[];if(!dtype||dtype=='RM'||dtype=='RO'||item.attr.subfields){_class.push('fieldsTree_folder');}
dtype=dtype||(item.attr.isRoot?'root':'group');_class.push('fieldsTree_'+dtype);return _class.join(' ');};treeattr.onDrag=function(dragValues,dragInfo,treeItem){if(!(treeItem.attr.dtype&&treeItem.attr.dtype!='RM'&&treeItem.attr.dtype!='RO')){return false;}
var fldinfo=objectUpdate({},treeItem.attr);fldinfo._nodelabel=treeItem.label;fldinfo['maintable']=table;dragValues['text/plain']=treeItem.attr.fieldpath;dragValues[dragCode]=fldinfo;};treeattr.draggable=true;treeattr.getIconClass='return "treeNoIcon";';pane._('tree',treeattr);},startDebug:function(callcounter){if(this._debuggerWindow){console.log('callcounter',callcounter)
this._debuggerWindow.focus();}else{this.openGnrIde();}},openGnrIde:function(){var url=window.location.host+'/sys/gnride/'+genro.page_id;url=window.location.protocol+'//'+url;var w=genro.openWindow(url,'debugger',{location:'no',menubar:'no'});console.log('w,h',window.clientWidth,window.clientHeight)
w.resizeTo(window.screen.width,window.screen.height);var debuggedModule=genro.pageModule;var mainGenro=genro;this._debuggerWindow=w;genro.wsk.addhandler('do_focus_debugger',function(callcounter){setTimeout(function(){genro.dev.startDebug(callcounter);},100)});w.addEventListener('load',function(){var dbg_genro=this.genro;dbg_genro.ext.mainGenro=mainGenro;dbg_genro.ext['startingModule']=debuggedModule;});},onDebugstep:function(data){var callcounter=data.callcounter;if(!('r_'+callcounter in genro.debugged_rpc)){this.addToDebugged(callcounter,data)
this.updateDebuggerStepBox(callcounter,data);}},updateDebuggerStepBox:function(callcounter,data){var debugger_box=dojo.byId('pdb_root');var debuggerStepBox=dojo.byId('_debugger_step_'+callcounter);if(!debuggerStepBox){debuggerStepBox=document.createElement('div');debuggerStepBox.setAttribute('id','_debugger_step_'+callcounter);debuggerStepBox.setAttribute('class','pdb_debugger_step');debugger_box.appendChild(debuggerStepBox);}else{dojo.removeClass(debuggerStepBox,'pdb_running');debuggerStepBox.removeChild(debuggerStepBox.firstChild);}
var container=document.createElement('div');var message=document.createElement('div');var footer=document.createElement('div');footer.setAttribute('class','pdb_debugger_step_footer');container.appendChild(message);container.appendChild(footer);debuggerStepBox.appendChild(container);message.innerHTML=dataTemplate('<table><tbody><tr><td class="pdb_label">Rpc:</td><td>$methodname</td></tr><tr><td class="pdb_label">Module:</td><td>$filename</td><tr><td class="pdb_label">Function:</td><td>$functionName</td></tr><td class="pdb_label">Line:</td><td>$lineno</td></tr></tbody></table>',data);var link=document.createElement('div');link.setAttribute('class','pdb_footer_button pdb_footer_button_right');link.innerHTML='Debug';link.setAttribute('onclick',dataTemplate("genro.dev.openDebugInIde('$pdb_id','$debugger_page_id');",data));footer.appendChild(link);link=document.createElement('div');link.setAttribute('class','pdb_footer_button pdb_footer_button_left');link.innerHTML='Continue';link.setAttribute('onclick',dataTemplate("dojo.addClass(dojo.byId('_debugger_step_"+callcounter+"'),'pdb_running'); genro.dev.continueDebugInIde('$pdb_id','$debugger_page_id',"+callcounter+");",data));footer.appendChild(link);},continueDebugInIde:function(pdb_id,debugger_page_id,callcounter){genro.wsk.publishToClient(debugger_page_id,"debugCommand",{cmd:'c',pdb_id:pdb_id});setTimeout(function(){genro.dev.removeFromDebugged(callcounter);},1000)},openDebugInIde:function(pdb_id,debugger_page_id){if(genro.mainGenroWindow){genro.mainGenroWindow.genro.framedIndexManager.openGnrIDE();}else{genro.wsk.publishToClient(debugger_page_id,'bringToTop')}},addToDebugged:function(callcounter,data){var dbgpars={debugger_page_id:data.debugger_page_id,pdb_id:data.pdb_id};genro.debugged_rpc['r_'+callcounter]=dbgpars;genro.rpc.suspend_call(callcounter);},removeFromDebugged:function(callcounter){var dbgpars=objectPop(genro.debugged_rpc,'r_'+callcounter);var debuggerStepBox=dojo.byId('_debugger_step_'+callcounter);if(debuggerStepBox){dojo.byId('pdb_root').removeChild(debuggerStepBox);}},handleDebugPath:function(dataNode){if(dataNode.getFullpath){var path=dataNode.getFullpath(null,true);var existing=genro._debugPaths[path];genro.dlg.prompt('Set breakpoint',{widget:[{lbl:'Mode',tag:'filteringSelect',values:'D:Debugger,C:Console',value:'^.mode'},{lbl:'Condition',value:'^.condition',width:'20em',margin_right:'5px'}],action:function(result){genro.setDebugPath(path,result.asDict());},dflt:existing?new gnr.GnrBag(existing):null});}},openInspector:function(){var root=genro.src.newRoot();genro.src.getNode()._('div','_devInspector_');var node=genro.src.getNode('_devInspector_').clearValue();node.freeze();var cbLog=function(e){if(e.altKey){var wdg=dijit.getEnclosingWidget(e.target);console.log(wdg.item);}};var pg=node._('paletteGroup',{'groupCode':'devTools','dockTo':false,id:'gnr_devTools',title:'Developer tools ['+genro._('gnr.pagename')+']',width:'500px',maxable:true});pg._('paletteTree',{'paletteCode':'cliDatastore',title:'Data',storepath:'*D',searchOn:true,tree_inspect:'shift',tree_searchMode:'static','tree_connect_onclick':cbLog,'tree_selectedLabelClass':'selectedTreeNode',tree_connect_ondblclick:function(e){var wdg=dijit.getEnclosingWidget(e.target);var item=wdg.item;genro.dev.handleDebugPath(item);},editable:true,tree_labelAttribute:null,tree_hideValues:false});var sourcePane=pg._('paletteTree',{'paletteCode':'cliSourceStore',title:'Source',storepath:'*S',searchOn:true,tree_inspect:'shift',tree_searchMode:'static',editable:true,'tree_connect_onclick':cbLog,tree_getLabel:function(n){return n.label+'['+n.attr.tag+':'+(n.attr.nodeId||n._id)+']';},tree_selectedPath:'.tree.selectedPath'});sourcePane._('dataController',{'script':'genro.src.highlightNode(fpath)','fpath':'^gnr.palettes.cliSourceStore.tree.selectedPath'});pg._('paletteTree',{'paletteCode':'dbmodel',title:'Model',tree_searchMode:'static',searchOn:true,tree_inspect:'shift',tree_labelAttribute:null,editable:true});genro.setDataFromRemote('gnr.palettes.dbmodel.store',"app.dbStructure",{checkPermission:true});this.sqlDebugPalette(pg);this.devUtilsPalette(pg);node.unfreeze();},moverSavingDlg:function(sourceNode,saveaction){var dlg=genro.dlg.quickDialog('Save Mover');var center=dlg.center;var box=center._('div',{datapath:sourceNode.absDatapath(),padding:'20px'});var fb=genro.dev.formbuilder(box,1,{border_spacing:'6px'});fb.addField('textbox',{lbl:_T("Mover"),value:'^.dlg.movername',width:'10em'});var bottom=dlg.bottom._('div');var saveattr={'float':'right',label:_T('Save')};var data=new gnr.GnrBag();saveattr.action=function(){saveaction(dlg);}
bottom._('button',saveattr);bottom._('button',{'float':'right',label:_T('Cancel'),action:dlg.close_action});return dlg;},_getHeaderInfo_getcell:function(row,field){var h=genro.rpcHeaderInfo[row['r_count']];return h?h[field]:'';},sqlDebugPalette:function(parent){var bc=parent._('palettePane',{'paletteCode':'devSqlDebug',title:'Sql',contentWidget:'borderContainer',frameCode:'devSqlDebug',margin:'2px',rounded:4});bc._('dataController',{'script':"genro.debug_sql=sqldebug",'sqldebug':'^gnr.debugger.sqldebug'});var top=bc._('framePane',{frameCode:'debugger_rpcgrid',region:'top',height:'200px',splitter:true,_class:'pbl_roundedGroup',margin:'2px',center_overflow:'hidden'});var topbar=top._('SlotBar',{_class:'pbl_roundedGroupLabel',slots:'5,vtitle,*,activator_sql,5,clearConsole,5',side:'top'})
topbar._('div','vtitle',{innerHTML:'RPC grid'})
var sn=bc.getParentNode();topbar._('checkbox','activator_sql',{'value':'^gnr.debugger.sqldebug','label':'Debug sql'});topbar._('slotButton','clearConsole',{'label':'Clear',action:'genro.setData("gnr.debugger.main",null);genro.rpcHeaderInfo = {};genro.getCounter("debug",true);'});if(!genro.getData('gnr.debugger.main')){genro.setData('gnr.debugger.main',new gnr.GnrBag());}
var rowstruct=new gnr.GnrBag();rowstruct.setItem('cell_0',null,{field:'r_count',name:'N',width:'2em',dtype:'L'});rowstruct.setItem('cell_1',null,{field:'methodname',name:'Method',width:'18em'});rowstruct.setItem('cell_5',null,{field:'debug_info',name:'Debug info',width:'15em'});rowstruct.setItem('cell_2',null,{field:'server_time',name:'Server',width:'4em',dtype:'N'});rowstruct.setItem('cell_8',null,{field:'xml_size',name:'Size(kb)',width:'4em',dtype:'N',_customGetter:function(row){return Math.floor((genro.dev._getHeaderInfo_getcell(row,'xml_size')/1024));}});rowstruct.setItem('cell_7',null,{field:'xml_time',name:'XMLTime',width:'4em',dtype:'N',_customGetter:function(row){return genro.dev._getHeaderInfo_getcell(row,'xml_time')}});rowstruct.setItem('cell_3',null,{field:'sql_count',name:'N.Sql',width:'4em',dtype:'N'});rowstruct.setItem('cell_4',null,{field:'sql_total_time',name:'Sql time',width:'4em',dtype:'N'});rowstruct.setItem('cell_6',null,{field:'not_sql_time',name:'Py time',width:'4em',dtype:'N'});genro.setData('gnr.debugger.rpccall_grid.struct.view_0.row_0',rowstruct);var rpcgrid=top._('includedView',{nodeId:'sql_debugger_grid_rpccall',storepath:'gnr.debugger.main',structpath:'gnr.debugger.rpccall_grid.struct',datapath:'gnr.debugger.rpccall_grid',selectedIndex:'gnr.debugger.rpccall_grid.currentRowIndex',relativeWorkspace:true});rpcgrid._('dataController',{script:'SET gnr.debugger.sqlquery_grid.store = (sind&&sind)!=-1?mainbag.getItem("#"+sind).deepCopy():null;',sind:'^gnr.debugger.rpccall_grid.currentRowIndex',mainbag:'=gnr.debugger.main',_if:'mainbag && mainbag.len()'})
rpcgrid._('dataController',{script:'SET gnr.debugger.sqlquery_grid.store = null;',mainbag:'^gnr.debugger.main',_delay:1})
var center=bc._('framePane',{frameCode:'debugger_sqlgrid',region:'center',_class:'pbl_roundedGroup',margin:'2px',center_widget:'borderContainer'});center._('contentPane','top',{_class:'pbl_roundedGroupLabel'})._('div',{'innerHTML':'Sql query grid'})
var rowstruct=new gnr.GnrBag();rowstruct.setItem('cell_0',null,{field:'_type',name:'T',width:'2em'});rowstruct.setItem('cell_1',null,{field:'_description',name:'Description',width:'9em'});rowstruct.setItem('cell_2',null,{field:'_execution_time',name:'Time',width:'8em',dtype:'N'});genro.setData('gnr.debugger.sqlquery_grid.struct.view_0.row_0',rowstruct);center._('contentPane',{region:'left',width:'220px',overflow:'hidden',splitter:true})._('includedView',{nodeId:'sql_debugger_grid_sqlquery',storepath:'gnr.debugger.sqlquery_grid.store',structpath:'gnr.debugger.sqlquery_grid.struct',datapath:'gnr.debugger.sqlquery_grid',relativeWorkspace:true,selectedIndex:'.currentRowIndex'});var tc=center._('tabContainer',{region:'center',margin:'2px'});tc._('dataController',{script:'var n=store.getNode("#"+currentRowIndex); if(n){this.setRelativeData(".output.sqltext",n._value);this.setRelativeData(".output.params",objectAsHTMLTable(n.attr))}',currentRowIndex:'^.currentRowIndex',store:'=.store',_if:'store',_else:'SET .output=null;',datapath:'gnr.debugger.sqlquery_grid'})
tc._('contentPane',{title:'Sql'})._('div',{innerHTML:'^gnr.debugger.sqlquery_grid.output.sqltext',height:'100%',style:'white-space: pre;background:white;',overflow:'auto',padding:'5px',_class:'selectable'});tc._('contentPane',{title:'Arguments'})._('div',{innerHTML:'^gnr.debugger.sqlquery_grid.output.params',height:'100%',overflow:'auto',_class:'debug_params'});},devUtilsPalette:function(parent){var pane=parent._('palettePane',{'paletteCode':'devUtils',title:'Utils',contentWidget:'FramePane',frameCode:'devUtils',center_overflow:'hidden'});var dbchangelog=function(result,kwargs){var txt='';result.walk(function(n){if(n.attr.changes){txt=txt+'\n'+n.attr.changes;}else{txt=txt+'\n----- pkg:'+n.label;}});genro.log(txt,'Check db');};sb=pane._('SlotBar',{'side':'top',slots:'pollingSwitch,5,rpcAnalyzer,*,actionMenu,5',toolbar:true,font_size:'.8'});pane._('dataRpc',{'path':'.checkDb',method:'checkDb',subscribe_devUtils_checkDb:true,_onResult:dbchangelog});pane._('dataRpc',{'path':'.applyChangesToDb',method:'applyChangesToDb',subscribe_devUtils_dbsetup:true,_onResult:'genro.log("DB Change applied","applyChangesToDb")'});sb._('checkbox','pollingSwitch',{'label':'Polling',value:'^gnr.polling.polling_enabled'});var m=sb._('DropDownButton','actionMenu',{label:'Commands'})._('menu',{_class:'smallMenu'})
m._('menuline',{'label':'Clear LS',action:function(){localStorage.clear()}});m._('menuline',{'label':'Clear SS',action:function(){sessionStorage.clear()}});m._('menuline',{'label':'CheckDb',publish:'devUtils_checkDb'});m._('menuline',{'label':'DbSetup',publish:'devUtils_dbsetup'});m._('menuline',{'label':'Clear log',action:'genro.clearlog()'});pane._('simpleTextArea',{'value':'^gnr._dev.logger',readOnly:true,height:'100%',style:'white-space: pre;'});},printUrl:function(url){genro.dev.deprecation("genro.dev.printUrl(url)","genro.download(url,'print')");genro.download(url,null,'print');},exportUrl:function(url){genro.dev.deprecation('genro.dev.exportUrl','genro.download');genro.download(url);},deprecation:function(oldval,newval){console.warn('Deprecation warning: '+oldval+' was replaced with '+newval,'WARNING');},dataDebugTrigger:function(kw){var path=kw.pathlist.join('.');var msg="A bag trigger : "+kw.evt;if(kw.evt=='upd_value'){var msg="The value of node '"+path+"' was changed from "+kw.oldvalue+" to "+kw.node.getValue();}
else if(kw.evt=='ins'){var msg="A node was inserted at path '"+path+"' position="+kw.ind+" value="+kw.node.getValue();}
else if(kw.evt=='del'){var msg="A node was deleted at path '"+path+"' position="+kw.ind+" oldvalue="+kw.node.getValue();}
dojo.publish("triggerBag",{message:msg});},getSourceBlock:function(path){var node=this.application.source.getNode(path,false,true,new gnr.GnrDomSource());if(node){var block=node.getValue();if(!block){block=new gnr.GnrDomSource();node.setValue(block,false);}
return block;}},dictToHtml:function(obj,tblclass){var result=["<table class='"+tblclass+"'><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>"];for(key in obj){result.push("<tr><td>"+key+"</td><td>"+obj[key]+"</td></tr>");}
result.push("</tbody></table>");return result.join('\n');},bagAttributesTable:function(node){var item=dijit.getEnclosingWidget(node).item;if(item){return genro.dev.dictToHtml(item.attr,'bagAttributesTable');}},showInspector:function(){if(!dijit.byId("gnr_devTools")){genro.dev.openInspector();}},shortcut:function(shortcut,callback,opt,sourceNode){if(shortcut[0]=='@'){shortcut=shortcut.slice(1).split(':');shortcut=genro.getData('gnr.user_preference.sys.shortcuts.'+shortcut[0])||shortcut[1];if(!shortcut){return;}}
var default_options={'type':'keydown','propagate':false,'target':document};if(!opt)opt=default_options;else{for(var dfo in default_options){if(typeof opt[dfo]=='undefined')opt[dfo]=default_options[dfo];}}
var ele=opt.target;if(typeof opt.target=='string')ele=document.getElementById(opt.target);var ths=this;var func=function(e){e=e||window.event;var code;if(e.keyCode)code=e.keyCode;else if(e.which)code=e.which;var character=String.fromCharCode(code).toLowerCase();var keys=shortcut.toLowerCase().split("+");var kp=0;var shift_nums={"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"};var special_keys={'esc':27,'escape':27,'tab':9,'space':32,'return':13,'enter':13,'backspace':8,'scrolllock':145,'scroll_lock':145,'scroll':145,'capslock':20,'caps_lock':20,'caps':20,'numlock':144,'num_lock':144,'num':144,'pause':19,'break':19,'insert':45,'home':36,'delete':46,'end':35,'pageup':33,'page_up':33,'pu':33,'pagedown':34,'page_down':34,'pd':34,'left':37,'up':38,'right':39,'down':40,'f1':112,'f2':113,'f3':114,'f4':115,'f5':116,'f6':117,'f7':118,'f8':119,'f9':120,'f10':121,'f11':122,'f12':123};for(var i=0;i<keys.length;i++){var k=keys[i];if(k=='ctrl'||k=='control'){if(e.ctrlKey)kp++;}else if(k=='cmd'||k=='command'){if(e.metaKey)kp++;}
else if(k=='shift'){if(e.shiftKey)kp++;}else if(k=='alt'){if(e.altKey)kp++;}else if(k.length>1){if(special_keys[k]==code)kp++;}else{if(character==k)kp++;else{if(shift_nums[character]&&e.shiftKey){character=shift_nums[character];if(character==k)kp++;}}}}
if(kp==keys.length){callback(e);if(!opt['propagate']){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault();}
return false;}}};if(ele.addEventListener){ele.addEventListener(opt['type'],func,false);if(sourceNode){if(!sourceNode._shortcuts){sourceNode._shortcuts=[];}
sourceNode._shortcuts.push({args:[opt['type'],func,false],element:ele});}}
else if(ele.attachEvent)ele.attachEvent('on'+opt['type'],func);else ele['on'+opt['type']]=func;},userObjectSave:function(sourceNode,kw,onSaved){var datapath=sourceNode.absDatapath(kw.metadataPath);var saveAs=objectPop(kw,'saveAs');var currentMetadata=genro.getData(datapath);var userObjectIsLoaded=currentMetadata&&currentMetadata.getItem('code');var preview=objectPop(kw,'preview');var saveCb=function(dlg,evt,counter,modifiers){var data=new gnr.GnrBag();if(kw.dataIndex){for(var key in kw.dataIndex){data.setItem(key,sourceNode.getRelativeData(kw.dataIndex[key]));}
data.setItem('__index__',new gnr.GnrBag(kw.dataIndex));}else if(kw.dataSetter){funcApply(kw.dataSetter,{data:data},sourceNode);}
var metadata=new gnr.GnrBag();metadata.update(genro.getData(datapath));if(!metadata.getItem('code')){genro.publish('floating_message',{message:_T('Missing code'),messageType:'error'});return;}
return genro.serverCall('_table.adm.userobject.saveUserObject',{'objtype':kw.objtype,'table':kw.table,flags:kw.flags,'data':data,metadata:metadata},function(result){if(dlg){dlg.close_action();}else{var objname=result.attr.description||result.attr.code;genro.publish('floating_message',{message:_T('Saved object '+objname)});}
if(kw.loadPath){sourceNode.setRelativeData(kw.loadPath,result.attr.code);}
if(onSaved){funcApply(onSaved,{result:result},sourceNode);}
genro.setData(datapath,new gnr.GnrBag(result.attr));return result;});};if(userObjectIsLoaded&&!saveAs){return saveCb();}
this.userObjectDialog(objectPop(kw,'title'),datapath,saveCb,preview);},userObjectLoad:function(sourceNode,kw){var metadataPath=objectPop(kw,'metadataPath');var onLoaded=objectPop(kw,'onLoaded');var onLoading=objectPop(kw,'onLoading');var resback=function(result){var resultValue,resultAttr,dataIndex;if(!result){resultValue=new gnr.GnrBag();resultAttr=objectUpdate({},kw);objectExtract(resultAttr,'userObjectIdOrCode,code,description,pkey');dataIndex=kw.dataIndex;if(kw.defaults){let defaults=kw.defaults;if(defaults instanceof gnr.GnrBag){defaults=defaults.asDict();}
for(let k in defaults){let v=defaults[k];if(v instanceof gnr.GnrBag){v=v.deepCopy();}
resultValue.setItem(k,v);}}}else{resultValue=result._value.deepCopy();resultAttr=objectUpdate({},result.attr);dataIndex=resultValue.pop('__index__');}
if(onLoading){funcApply(onLoading,null,sourceNode,['dataIndex','resoultValue','resoultAttr'],[dataIndex,resultValue,resultAttr]);}
sourceNode.setRelativeData(metadataPath,new gnr.GnrBag(resultAttr));if(dataIndex){if(dataIndex instanceof gnr.GnrBag){dataIndex=dataIndex.asDict();}
for(let k in dataIndex){sourceNode.setRelativeData(dataIndex[k],resultValue.getItem(k));}}
if(onLoaded){funcApply(onLoaded,null,sourceNode,['dataIndex','resoultValue','resoultAttr'],[dataIndex,resultValue,resultAttr]);}};if(kw.userObjectIdOrCode==='__newobj__'){return resback();}
genro.serverCall('_table.adm.userobject.loadUserObject',kw,resback);},userObjectDialog:function(title,datapath,saveCb,preview){var dlg=genro.dlg.quickDialog(title);var center=dlg.center;var box=center._('div',{datapath:datapath,padding:'20px'});var fb=genro.dev.formbuilder(box,2,{border_spacing:'6px'});fb.addField('textbox',{lbl:_T("Code"),value:'^.code',width:'10em'});fb.addField('checkbox',{label:_T("Private"),value:'^.private'});fb.addField('textbox',{lbl:_T("Name"),value:'^.description',width:'100%',colspan:2});fb.addField('textbox',{lbl:_T("Authorization"),value:'^.authtags',width:'100%',colspan:2});fb.addField('simpleTextArea',{lbl:_T("Notes"),value:'^.notes',width:'100%',height:'5ex',colspan:2,lbl_vertical_align:'top'});if(preview){fb.addField('button',{action:function(){var that=this;dlg.getParentNode().widget.hide();genro.dev.takePicture(function(data){dlg.getParentNode().widget.show();that.setRelativeData('.preview',data);});},label:_T('Screenshot')});fb.addField('br',{});fb.addField('img',{src:'^.preview',height:'50px',width:'200px',boder:'1px solid silver'});}
var bottom=dlg.bottom._('div');var saveattr={'float':'right',label:_T('Save')};saveattr.action=function(evt,counter,modifiers){saveCb(dlg,evt,counter,modifiers);};bottom._('button',saveattr);var meta=genro.getData(datapath)||new gnr.GnrBag();if(meta.getItem('id')||meta.getItem('pkey')){var savecopy={'float':'right',label:_T('Duplicate as')};savecopy.action=function(evt,counter,modifiers){genro.getData(datapath).setItem('id',null);genro.getData(datapath).setItem('pkey',null);saveCb(dlg,evt,counter,modifiers);};bottom._('button',savecopy);}
bottom._('button',{'float':'right',label:_T('Cancel'),action:dlg.close_action});dlg.show_action();},userObjectMenuData:function(kw,extraRows){if(extraRows){kw._onResult=function(result){var offset=result.len();if(offset){result.setItem('r_'+offset,null,{caption:'-'});}
offset+=1;extraRows.forEach(function(n,i){result.setItem('r_'+(i+offset),null,n);});};}
var resolver=genro.rpc.remoteResolver('_table.adm.userobject.userObjectMenu',kw);return resolver;},translateQueryPars:function(currwhere){var parslist=[];var cb=function(node,parslist,idx){if(node.attr.value_caption){if(node.attr.value_caption[0]=='?'){var relpath=node.getFullpath('static',currwhere);var result=objectUpdate({},node.attr);var value_caption=node.attr.value_caption.slice(1);var vl=value_caption.split('|');result.lbl=vl[0];result.dflt=vl[1];result.relpath=relpath;result.parcode=flattenString(result.lbl,['.',' ']);parslist.push(result);}else if(node.attr.value_caption&&node.attr.value_caption.indexOf('set:')==0){return;}else{node.setValue(node.attr.value_caption);}}};currwhere.walk(cb,'static',parslist);return parslist;},dynamicQueryParsFb:function(sourceNode,wherebag,parslist,cols){parslist=parslist||this.translateQueryPars(wherebag);var queryform=genro.dev.formbuilder(sourceNode,cols||1,{border_spacing:'3px',onEnter:confirm,margin_top:'6px'});var tr,attrs;for(var i=0;i<parslist.length;i++){attrs=parslist[i];var lbl=attrs.lbl||attrs.value_caption.slice(1);var dflt;if(!('dflt'in attrs)){if(lbl.indexOf('|')){var l=lbl.split('|');lbl=l[0];dflt=l[1];}}else{dflt=attrs.dflt;}
if(dflt){wherebag.setItem(attrs.relpath,dflt);}
if(attrs.column_relationTo){var ro=attrs.column_relationTo.split('.');queryform.addField('dbselect',{lbl:lbl,value:'^.'+attrs.relpath,width:'12em',dbtable:ro[0]+'.'+ro[1]});}else{queryform.addField('textbox',{lbl:lbl,value:'^.'+attrs.relpath,width:'12em'});}}},addError:function(error,error_type,show){var msg="<div style='text-align:center;font-size:1em;font-weight:bold;'>"+error_type.toUpperCase()+" Error "+_F(new Date(),'short')+"</div>"+error;if(show){genro.dlg.message(msg,null,'error',3000);}
var errorbag=genro.getData('gnr.errors');if(!errorbag){errorbag=new gnr.GnrBag();genro.setData('gnr.errors',errorbag);}
errorbag.setItem(error_type+'.#id',msg,{ts:new Date()});var toterr=0;errorbag.forEach(function(n){toterr+=n.getValue().len();});errorbag.getParentNode().setAttribute('counter',toterr,true);},errorPalette:function(parent){if(!parent){var root=genro.src.newRoot();genro.src.getNode()._('div','_helpdesk_');var parent=genro.src.getNode('_devErrors_').clearValue();}
parent.freeze();var pane=parent._('palettePane',{'paletteCode':'gnrerrors','dockTo':false,title:'Current errors'});pane._('div',{innerHTML:'==genro.dev.formatErrors(_errors)',_errors:'^gnr.errors',padding:'5px',border:'1px solid silver',background:'whitesmoke',rounded:6,margin:'5px'});parent.unfreeze();},formatErrors:function(errorbag){var errors=[];errorbag.forEach(function(n){n.getValue().forEach(function(errorNode){errors.push(errorNode.getValue());})})
return errors.join('<br/><hr/>');},openHelpDesk:function(){var root=genro.src.newRoot();genro.src.getNode()._('div','_helpdesk_');var parent=genro.src.getNode('_helpdesk_').clearValue();parent.freeze();genro.setData('gnr.helpdesk',new gnr.GnrBag());var pane=parent._('palettePane',{'paletteCode':'helpdesk','dockTo':false,title:_T('Helpdesk'),height:'550px',width:'400px','z_index':100000});var sc=pane._('stackContainer',{selectedPage:'^.page',datapath:'gnr.helpdesk'});var pages=[['index',_T('Index'),true],['documentation',_T('Documentation')],['help',_T('Help')],['bug_report',_T('Report a bug')],['new_ticket',_T('New ticket'),true]];pages.forEach(function(page,idx){var bc=sc._('borderContainer',{'pageName':page[0]});var bottom;if(idx>0){bottom=bc._('contentPane',{region:'bottom',height:'40px'});if(!page[2]){bottom._('lightbutton',{innerHTML:_T('Back'),action:"SET .page=pageName;",pageName:pages[0][0],_class:'helpdesk_btn helpdesk_footer',position:'absolute',left:'3px',top:'2px'});}}
genro.dev['openHelpDesk_'+page[0]](bc._('contentPane',{region:'center'}),bottom,pages);});parent.unfreeze();},openHelpDesk_index:function(pane,bottom,pages){pages.forEach(function(p){var nobutton=p[2];if(nobutton){return;}
pane._('lightbutton',{innerHTML:p[1],action:"SET .page=pageName;",pageName:p[0],_class:'helpdesk_btn helpdesk_'+p[0]});});},openHelpDesk_documentation:function(pane){},_helpDeskTicketTemplate:function(){var t='';t+='<div class="helpdesk_ticket_top">';t+='<div class="helpdesk_ticket_subject">$subject</div>';t+='<div class="helpdesk_ticket_date">$date</div>';t+='</div>';t+='<div class"helpdesk_ticket_body">';t+='<div class"helpdesk_ticket_summary">$summary</div>';t+='</div>';t+='<div class"helpdesk_ticket_bottom">';t+='&nbsp;';t+='</div>';return t;},openHelpDesk_bug_report:function(pane,bottom){var template=this._helpDeskTicketTemplate();genro.serverCall('dev.getCurrentTickets',{},function(reported_tickets){if(reported_tickets){reported_tickets.forEach(function(n){pane._('div',{innerHTML:dataTemplate(template,n.attr),_class:'helpdesk_ticket_box'});});}
bottom._('lightbutton',{innerHTML:_T('New ticket'),'float':'right',_class:'helpdesk_btn helpdesk_footer',position:'absolute',right:'3px',top:'2px',action:'SET .page=pageName',pageName:'new_ticket'});});},openHelpDesk_new_ticket:function(pane,bottom){var fb=genro.dev.formbuilder(pane._('div',{margin:'5px'}),1,{border_spacing:'6px',datapath:'.record'});fb.addField('textbox',{value:'^.title',lbl:_T('Subject'),width:'30em'});var sn=pane.getParentNode();genro.serverCall('dev.getNewTicketInfo',{},function(result){var priorities=result.getItem('priorities');var questions=result.getItem('questions');var locale=genro.locale();var lang=(locale=='it-IT')?'it':'en';if(questions){questions=questions.getItem(lang);if(questions){fb.addField('checkboxText',{value:'^.ticket_answers',values:questions,cols:1});}}
if(result.getItem('tasks')){fb.addField('filteringSelect',{value:'^.task_id',values:result.getItem('tasks'),lbl:_T('Topic'),placeholder:_T('Current page')});}
fb.addField('filteringSelect',{value:'^.priority',values:priorities,lbl:_T('Priority')});fb.addField('simpleTextArea',{value:'^.notes',lbl:'Notes',lbl_vertical_align:'top',height:'80px',width:'300px'});fb.addField('button',{action:function(){var that=this;genro.wdgById('helpdesk_floating').hide();genro.dev.takePicture(function(data){genro.wdgById('helpdesk_floating').show();sn.setRelativeData('.record.screenshot',data);});},label:_T('Screenshot')});fb.addField('br',{});fb.addField('img',{src:'^.screenshot',height:'100px',width:'300px',boder:'1px solid silver'});});var savekw={innerHTML:_T('Save ticket'),_class:'helpdesk_btn helpdesk_footer',position:'absolute',right:'3px',top:'2px'};savekw.action=function(){var record=sn.getRelativeData('.record');var extra_info=new gnr.GnrBag();if(genro.getData('gnr.errors')){extra_info.setItem('js_errors',genro.getData('gnr.errors').deepCopy());}
record.setItem('extra_info',extra_info);genro.serverCall('dev.saveNewTicket',{record:record},function(result){if(result&&result.getItem('error')){genro.dlg.floatingMessage(pane.getParentNode(),{message:result.getItem('error'),messageType:'error'});}else{pane.getParentNode().setRelativeData('.record',new gnr.GnrBag());genro.wdgById('helpdesk_floating').hide();}});}
bottom._('lightbutton',savekw);bottom._('lightbutton',{innerHTML:_T('Back'),_class:'helpdesk_btn helpdesk_footer',action:'SET .page=pageName',pageName:'bug_report',left:'3px',top:'2px'});},openHelpDesk_help:function(pane){},takePicture:function(sendPars,onResult){genro.publish('onPageSnapshot',{setting:true});const divOffset=1;var overlay=document.createElement('div');dojo.style(overlay,{position:'fixed',top:'0',bottom:'0',left:'0',right:'0',opacity:'.3',background:'white',zIndex:1000,cursor:'crosshair'});dojo.body().appendChild(overlay);var sel=document.createElement('div');dojo.style(sel,{position:'absolute',top:'0',width:'0',height:'0',display:'none',border:'2px solid black'});overlay.appendChild(sel);sendPars=sendPars||{uploadPath:'site:screenshots/'+genro.getData('gnr.pagename')};if(typeof(sendPars)=='string'){sendPars={uploadPath:sendPars};}
var pos=[0,0];var x1,x2,y1,y2,xDif,yDif=0;var isSelection,isBottomRight,isTopRight,isTopLeft,isBottomLeft=false
dojo.connect(overlay,'mousedown',function(event){isSelection=true
x1=event.pageX-pos[0]
y1=event.pageY-pos[1]
sel.style.setProperty('display','block')
sel.style.setProperty('left',event.pageX+"px")
sel.style.setProperty('top',event.pageY+"px")
sel.style.setProperty('width','0px')
sel.style.setProperty('height','0px')});dojo.connect(overlay,'mouseup',function(event){isSelection=false;if(isBottomRight){x2=event.pageX-pos[0]
y2=event.pageY-pos[1]
xDif=x2-x1
yDif=y2-y1}else if(isBottomLeft){y2=event.pageY-pos[1]
yDif=y2-y1
xDif=x1-x2
x1=x1-xDif}else if(isTopRight){x2=event.pageX-pos[0]
xDif=x2-x1
yDif=y1-y2
y1=y1-yDif}else if(isTopLeft){xDif=x1-x2
x1=x1-xDif
yDif=y1-y2
y1=y1-yDif}
sel.style.setProperty('display','none');dojo.body().removeChild(overlay);var onResultSnapshot=function(){if(onResult){onResult();}
genro.publish('onPageSnapshot',{setting:false});}
var kw={sendPars:sendPars,onResult:onResultSnapshot,crop:{x:x1,y:y1,deltaX:xDif,deltaY:yDif}};genro.dom.htmlToCanvas(dojo.body(),kw)});dojo.connect(overlay,'mousemove',function(event){if(isSelection){x2=event.pageX-pos[0]
y2=event.pageY-pos[1]
if(x2>x1&&y2>y1){isBottomRight=true
isBottomLeft=false
isTopLeft=false
isTopRight=false
xDif=x2-x1
yDif=y2-y1
sel.style.setProperty('width',xDif+'px')
sel.style.setProperty('height',yDif+'px')}else if(x2<x1&&y2>y1){isBottomLeft=true
isTopLeft=false
isTopRight=false
isBottomRight=false
xDif=x1-x2
yDif=y2-y1
sel.style.setProperty('left',x2+'px')
sel.style.setProperty('width',xDif+'px')
sel.style.setProperty('height',yDif+'px')}else if(x2>x1&&y2<y1){isTopRight=true
isTopLeft=false
isBottomLeft=false
isBottomRight=false
xDif=y1-y2
yDif=x2-x1
sel.style.setProperty('top',y2+'px')
sel.style.setProperty('width',yDif+'px')
sel.style.setProperty('height',xDif+'px')}else if(x2<x1&&y2<y1){isTopLeft=true
isTopRight=false
isBottomLeft=false
isBottomRight=false
yDif=y1-y2
xDif=x1-x2
sel.style.setProperty('left',x2+pos[0]+divOffset+'px')
sel.style.setProperty('top',y2+pos[1]+divOffset+'px')
sel.style.setProperty('width',xDif+'px')
sel.style.setProperty('height',yDif+'px')}}})}});



dojo.declare("gnr.GnrDlgHandler",null,{constructor:function(application){this.application=application;this.alert_count=0;this._quickDialogDestroyTimeout=500;},recordChange:function(record_path,selected_pkey){var pkey_now=genro.getDataNode(record_path).attr.pkey;if(pkey_now==selected_pkey){return true;}else{if(genro.getData(record_path).get_modified()){var todo=request('vuoi salvare?');if(todo=='salva'){salva();return true;}else if(todo=='non salvare'){return true;}else{return false;}}}},dialog:function(msg,cb,buttons){var root=genro.getNode()._('div','_dlg');dlg=root._('dialog','dialogbox',{gnrId:'dialogbox',toggle:"fade",toggleDuration:250});dlg._('layoutcontainer',{height:'100%'});dlg._('contentpane',{'_class':'dojoDialogInner',layoutAling:'client'})._('span',{content:msg});var bottom=dlg._('contentpane',{layoutAling:'bottom'})._('div',{'align':'right'});buttons=buttons||[{'caption':'OK',result:'OK'},{'caption':'cancel',result:'cancel'}];for(btn in buttons){btn.action=function(){genro.dialogbox.hide();cb(btn.result);};bottom._('button',btn);}
dlg.show();},showMenuPane:function(nodeId){var root=genro.nodeById(nodeId);root.freeze();var mc=root._('contentPane',{'_class':'menucontainer','background_color':'red','height':'3em',margin_left:'1em',margin_right:'1em',layoutAlign:'top'});dojo.fx.wipeIn({node:root.getDomNode(),duration:1000}).play();},connectTooltipDialog:function(wdg,btnId){dojo.connect(wdg,'onclick',function(e){genro.wdgById(btnId)._openDropDown(e.target);});},genericWipePane:function(nodeId,msgpth,over){var nodeId=nodeId||'standardmsgpane';var msgpth=msgpth||'gnr.message';var msg=genro.getData(msgpth);var root=genro.nodeById(nodeId);root.clearValue().freeze();if(over==true){root.attr['z_index']=999;root.attr['position']='absolute';};var mc=root._('div',{'background_color':'silver','height':'3em',width:'400px'});mc._('span',{content:msg});var cb=function(argument){dojo.fx.wipeOut({node:root.getDomNode(),duration:1000}).play();};mc._('button',{label:'close',onClick:cb});root.unfreeze();dojo.fx.wipeIn({node:root.getDomNode(),duration:1000}).play();},createStandardMsg:function(domnode){dojo.require("dojox.widget.Toaster");var toaster=new dojox.widget.Toaster({positionDirection:"tl-down",duration:1000,separator:'<hr>',messageTopic:'standardMsg'});dojo.connect(toaster,'setContent',this,'onMsgShow');domnode.appendChild(toaster.domNode);this.messanger=toaster;},onMsgShow:function(){if(this.messanger.forcedPos){dijit.placeOnScreenAroundElement(genro.dlg.messanger.domNode,this.messanger.forcedPos,{'TL':'BL','BL':'TL'});}},removeFloatingMessage:function(sourceNode){sourceNode._value.popNode('_floatingmess');},makeFloatingMessage:function(sourceNode,kw){console.warn('Use floatingMessage instead of makeFloatingMessage');this.floatingMessage(sourceNode,kw);},floatingMessage:function(sourceNode,kw){kw=objectUpdate({},kw)
var yRatio=objectPop(kw,'yRatio');var xRatio=objectPop(kw,'xRatio');var duration=objectPop(kw,'duration')||2;var duration_in=objectPop(kw,'duration_in')||duration;var duration_out=objectPop(kw,'duration_out')||duration;var sound=objectPop(kw,'sound');var message=objectPop(kw,'message');var msgType=objectPop(kw,'messageType')||'message';var transition='opacity '+duration_in+'s';var onClosedCb=objectPop(kw,'onClosedCb');if(onClosedCb){onClosedCb=funcCreate(onClosedCb,null,sourceNode)}
var messageBox=sourceNode._('div','_floatingmess',{_class:'invisible fm_box fm_'+msgType,transition:transition}).getParentNode()
kw.innerHTML=message;messageBox._('div',kw);var deleteCb=function(){that._value.popNode('_floatingmess');if(onClosedCb){onClosedCb();}};messageBox._('div',{_class:'dlg_closebtn',connect_onclick:deleteCb});genro.dom.centerOn(messageBox,sourceNode,xRatio,yRatio);var that=sourceNode;if(sound){genro.playSound(sound);}
var t1=setTimeout(function(){genro.dom.removeClass(messageBox,'invisible');setTimeout(function(){if(duration_out>0){var dt=duration_out/2;setTimeout(function(){genro.dom.addClass(messageBox,'invisible');setTimeout(function(){deleteCb();},dt*1000)},(dt*1000)+1)}},(duration_in*1000)+1);},1)},iframeDialog:function(iframeId,kw){var dialogId=iframeId+'_dlg';var dlgNode=genro.nodeById(dialogId);var openKw=kw.openKw;if(!dlgNode){var root=genro.src.getNode()._('div','_dlg_iframe');var parentRatio=objectPop(kw,'parentRatio');var windowRatio=objectPop(kw,'windowRatio');var dlg=root._('dialog',{title:kw.title,closable:kw.closable,nodeId:dialogId,parentRatio:parentRatio,windowRatio:windowRatio});var iframekw={src:kw.src,border:0,height:'100%',width:'100%',nodeId:iframeId};objectUpdate(iframekw,objectExtract(kw,'iframe_*'));iframekw.selfsubscribe_close="this.dialog.hide();";var onIframeStarted=objectPop(kw,'onIframeStarted');if(onIframeStarted||openKw){iframekw.onStarted=function(){if(onIframeStarted){onIframeStarted(this,genro.wdgById(dialogId));}
if(openKw){this.domNode.gnr.postMessage(this,openKw);}};}
objectUpdate(iframekw,objectExtract(kw,'selfsubscribe_*',true,true));var iframe;if(!(parentRatio||windowRatio)){iframe=dlg._('div',{height:kw.height,width:kw.width,overflow:'hidden'})._('iframe','iframe',iframekw);}else{iframe=dlg._('borderContainer')._('ContentPane',{'region':'center',overflow:'hidden'})._('iframe','iframe',iframekw);}
dlgNode=dlg.getParentNode();dlgNode._iframeNode=iframe.getParentNode();dlgNode._iframeNode.dialog=dlgNode.widget;dlgNode.widget.show();}else{dlgNode.widget.show();if(openKw){dlgNode._iframeNode.domNode.gnr.postMessage(dlgNode._iframeNode,openKw);}}
return dlgNode;},thIframeDialog:function(kw,openKw){kw.src=this._prepareThIframeUrl(kw);if(openKw.pkey){openKw.topic='main_form_open';kw.main_call='main_form';}
var iframeId=kw.nodeId||'th_'+kw.table.replace('.','_')+(kw.formResource||'')+(kw.main_call||'');openKw=openKw||{};var onSavedCb=objectPop(kw,'onSavedCb');kw.closable=kw.closable===false?false:true;kw.openKw=openKw;var fixedTitle=objectPop(kw,'fixedTitle');kw.onIframeStarted=function(iframeNode,wdg){if(iframeNode._genro._rootForm){if(kw.main_call=='main_form'){iframeNode._genro._rootForm.subscribe('onDismissed',function(){wdg.hide();});}
if(!fixedTitle){iframeNode._genro._rootForm.subscribe('onChangedTitle',function(kw){wdg.setTitle(kw.title);});}}else if(kw.lookup){iframeNode._genro.nodeById('lookup_root').subscribe('lookup_cancel',function(){wdg.hide();});}
if(onSavedCb){iframeNode._genro._rootForm.subscribe('onSaved',function(kw){onSavedCb(kw);});}};this.iframeDialog(iframeId,kw);},lightboxDialog:function(kwOrCb,onClosedCb){genro.src.getNode()._('div','_dlg_lightbox');var node=genro.src.getNode('_dlg_lightbox').clearValue().freeze();onClosedCb=onClosedCb?funcCreate(onClosedCb):null;var dlg=node._('dialog',{_class:'lightboxDialog',nodeId:'_dlg_lightbox',connect_hide:function(){if(onClosedCb){onClosedCb.call(this);}
genro.src.getNode('_dlg_lightbox').clearValue();}});var closecb=function(){if(genro.wdgById("_dlg_lightbox")){genro.wdgById("_dlg_lightbox").hide();}};dlg._('div',{_class:'dlg_closebtn',connect_onclick:closecb,top:'-20px',right:'-20px'});if(typeof(kwOrCb)=='function'){kwOrCb(dlg,closecb);}else{dlg._(objectPop(kwOrCb,'tag'),kwOrCb);}
node.unfreeze();genro.wdgById('_dlg_lightbox').show();},lightboxVideo:function(url,kw){this.lightboxDialog(function(dlg){kw=kw||{};var caption=objectPop(kw,'caption');var box=dlg._('div',{padding:'10px',background:'white',rounded:6});if(caption){dlg._('div',{innerHTML:caption,text_align:'center',color:'#999',font_weight:'bold'});}
box._('htmliframe',objectUpdate({src:url,height:'500px',width:'600px',border:'0',nodeId:'_videoiframe_'},kw))},function(){genro.domById('_videoiframe_').setAttribute('src','');});},alert:function(msg,title,buttons,resultPath,kw){var root=genro.src.getNode();if(!root){genro.bp(true);alert(msg);return;}
var alertCode='_dlg_alert_'+this.alert_count;root._('div',alertCode);title=title||'';buttons=buttons||{confirm:'OK'};kw=kw||{};confirmCb=objectPop(kw,'confirmCb');resultPath=resultPath;var that=this;var node=genro.src.getNode(alertCode).clearValue().freeze();var dlg=node._('dialog',objectUpdate({nodeId:alertCode,title:title,_class:'dlg_alert',connect_show:function(){that.alert_count+=1;},connect_hide:function(){that.alert_count-=1;},toggle:"fade",toggleDuration:250},kw))._('div',{_class:'dlg_ask',action:function(){genro.wdgById(alertCode).hide();if(resultPath){genro.fireEvent(resultPath,this.attr.actCode);}
if(confirmCb){funcApply(confirmCb);}}});dlg._('div',{'innerHTML':msg,'_class':'selectable dlg_ask_msg'});for(var btn in buttons){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn});}
node.unfreeze();genro.wdgById(alertCode).show();},serverMessage:function(msgpath){var msgnode=genro.getDataNode(msgpath);var msgtext=msgnode.getValue();var msgattr=msgnode.attr;genro.src.getNode()._('div','_dlg_alert');var node=genro.src.getNode('_dlg_alert').clearValue().freeze();var title=msgattr['title']||'Message from '+msgattr['from_user'];genro.dlg.alert(msgtext,title)},ask:function(title,msg,buttons,resultPathOrActions,kw){var alertCode='_dlg_ask_'+this.alert_count;genro.src.getNode()._('div',alertCode);kw=kw||{};buttons=buttons||{confirm:'Confirm',cancel:'Cancel'};var action,actions;var that=this;var node=genro.src.getNode(alertCode).clearValue().freeze();if(typeof(resultPathOrActions)=='string'){var resultPath=resultPathOrActions;actions={};action="genro.wdgById('"+alertCode+"').hide();genro.fireEvent('"+resultPath+"',this.attr.actCode);";}
else{actions=resultPathOrActions||{};action="genro.wdgById('"+alertCode+"').hide();if (this.attr.act){funcCreate(this.attr.act).call();};";}
var dlg=node._('dialog',{nodeId:alertCode,title:title,_class:'dlg_alert',connect_show:function(){that.alert_count+=1;},connect_hide:function(){that.alert_count-=1;},centerOn:'_pageRoot'})._('div',{_class:'dlg_ask','action':action});dlg._('div',{'content':msg,'_class':'selectable dlg_ask_msg',width:kw.width});objectKeys(buttons).sort().reverse().forEach(function(btn){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn,'act':actions[btn]});});node.unfreeze();genro.wdgById(alertCode).show();},batchMonitor:function(thermopath){thermopath=thermopath||'_thermo';genro.src.getNode()._('div','_thermo_floating');var node=genro.src.getNode('_thermo_floating').clearValue().freeze();var floatingPars={};floatingPars.title='public floating';floatingPars._class='shadow_4';floatingPars.nodeId='batchMonitor';floatingPars.datapath=thermopath;floatingPars.top='80px';floatingPars.left='20px';floatingPars.width='400px';floatingPars.closable=true;floatingPars.resizable=true;floatingPars.dockable=false;floatingPars.resizeAxis='y';floatingPars.maxable=false;floatingPars.duration=400;var floating=node._('floatingPane',floatingPars);var container=floating._('div',{datapath:'.data','margin_bottom':'12px'});var create_thermoline=function(node,kw,i){var innerpane=kw.pane._('div',{datapath:'.'+node.label});innerpane._('div',{innerHTML:'^.?message',font_size:'8px',text_align:'center',color:'black'});innerpane._('progressBar',{progress:'^.?progress',maximum:'^.?maximum',indeterminate:'^.?indeterminate',places:'^.?places',width:'100%',height:'10px',font_size:'9px'});};var create_thermopane=function(node,kw,i){var innerpane=kw.pane._('div',{_class:'thermopane',border:'1px solid gray',margin:'2px',datapath:'.'+node.label});var titlediv=innerpane._('div',{background:'gray',color:'white',font_size:'9px',padding:'2px',height:'8px'});titlediv._('div',{innerHTML:'^.?thermotitle','float':'left'});titlediv._('a',{innerHTML:'Stop','float':'right'});var pane=innerpane._('div',{datapath:'.lines',padding:'3px'});var lines=node.getValue().getItem('lines');if(lines){lines.forEach(create_thermoline,null,{'pane':pane});}};var thermobag=genro._(thermopath+'.data');thermobag.forEach(create_thermopane,null,{'pane':container});node.unfreeze();var bm=genro.wdgById('batchMonitor');dojo.connect(bm,'close',function(){genro.setData('_thermo.monitor',false);});genro.setData('_thermo.monitor',true);},message:function(msg,position,level,duration){this.messanger.forcedPos=position;var level=level||'message';var duration=duration||4000;if(level=='error'){if(!dojo.query('.countBoxErrors').length){return;}}
dojo.publish("standardMsg",[{message:msg,type:level,duration:duration}]);},remoteDialog:function(name,remote,remoteKw,dlgKw){remoteKw=remoteKw||{};dlgKw=dlgKw||{};dlgKw.nodeId='remote_dlg_'+name;var dlgNode=genro.nodeById(dlgKw.nodeId);if(!dlgNode){dlgKw.autoSize=false;dlgKw.closable=true;var dlg=genro.src.create('dialog',dlgKw,'_rmt_dlg');var kw={};for(var k in remoteKw){kw['remote_'+k]=remoteKw[kw];}
kw.min_height='1px';kw.min_width='1px';kw.remote__onRemote=function(){setTimeout(function(){dlgNode.widget.adjustDialogSize();},1)};kw.remote=remote;dlg._('div',kw);dlgNode=dlg.getParentNode();}
dlgNode.widget.show();},prompt:function(title,kw,sourceNode){kw=kw||{};var dlg_kw=objectExtract(kw,'dlg_*');var msg=kw.msg;var confirmCb=kw.action||'';var cancelCb=kw.cancelCb;var wdg=kw.widget||'textbox';var remote=kw.remote;var dflt=kw.dflt;var cols=objectPop(kw,'cols')||1;genro.dlg.prompt_counter=genro.dlg.prompt_counter||0;genro.dlg.prompt_counter++;var prompt_datapath=kw.datapath||'gnr.promptDlg.prompt_'+genro.dlg.prompt_counter;if(sourceNode){prompt_datapath=sourceNode.absDatapath(prompt_datapath);}
var promptvalue_path=prompt_datapath+'.promptvalue';genro.setData(promptvalue_path,dflt||null);dlg_kw=objectUpdate({_showParent:true,width:'280px',datapath:prompt_datapath,_class:'dlg_prompt',autoSize:true},dlg_kw);var dlg=genro.dlg.quickDialog(title,dlg_kw,sourceNode);var mandatory=objectPop(kw,'mandatory');var actionCb=function(command){var error_message;command=command||this.attr.command;if(command=='confirm'){var validDojo=true;dlg.center.walk(function(n){if(n.widget&&n.widget.isValid&&n.widget.isValid()===false){validDojo=false;}});if(!validDojo){return;}
var v=genro.getData(promptvalue_path);if(mandatory&&isNullOrBlank(v)){return;}
error_message=funcApply(confirmCb,{value:genro.getData(promptvalue_path)},(sourceNode||this));if(!error_message){genro.setData(promptvalue_path,null,null,false);}}else if(command=='cancel'&&cancelCb){error_message=funcApply(cancelCb,{},(sourceNode||this));}
if(error_message){genro.dlg.floatingMessage(dlg.center.getParentNode(),{message:error_message,messageType:'error'});}
else{dlg.close_action();genro.dlg.prompt_counter--;if(!genro.dlg.prompt_counter){setTimeout(function(){genro._data.popNode('gnr.promptDlg');},genro.dlg._quickDialogDestroyTimeout+1);}}};var bar=dlg.bottom._('slotBar',{slots:'*,cancel,confirm',action:actionCb});bar._('button','cancel',{'label':'Cancel',command:'cancel'});var confirmbtnKW={'label':'Confirm',command:'confirm'};if(mandatory){confirmbtnKW.disabled='^.promptvalue?=(#v==null) || (#v=="")';}
bar._('button','confirm',confirmbtnKW);var kwbox={};if(remote){kwbox.padding='10px';kwbox.remote=remote;objectUpdate(kwbox,objectExtract(kw,'remote_*',false,true));kwbox.remote_valuepath='.promptvalue';kwbox.remote__onRemote=function(){setTimeout(function(){dlg.getParentNode().widget.adjustDialogSize();},1);};dlg.center._('div',kwbox);}else if(typeof(wdg)=='function'){kwbox.datapath='.promptvalue';wdg.call(sourceNode,dlg.center._('div',kwbox));}else if(wdg=='multiValueEditor'){dlg.center._('multiValueEditor',objectUpdate({value:'^.promptvalue',height:'250px',width:'350px'},objectExtract(kw,'wdg_*')));}
else{kwbox.padding='10px';kwbox.width=dlg_kw.width;var box=dlg.center._('div',kwbox);var fb;var onEnter='onEnter'in kw?kw.onEnter:function(){actionCb('confirm');};if(msg){box._('div',{innerHTML:msg,color:'#666',margin_bottom:'10px',_class:'selectable'});}
if(typeof(wdg)=='string'){fb=genro.dev.formbuilder(box,cols,{border_spacing:'1px',onEnter:onEnter,width:'100%',fld_width:'100%'});fb.addField(wdg,objectUpdate({value:'^.promptvalue',lbl:kw.lbl,lbl_color:'#666',lbl_text_align:'right'},objectExtract(kw,'wdg_*')));}else{fb=genro.dev.formbuilder(box,cols,{border_spacing:'4px',width:'100%',onEnter:onEnter,fld_width:'100%',datapath:'.promptvalue'});wdg.forEach(function(n){n=objectUpdate({},n);var w=objectPop(n,'wdg','textbox');fb.addField(w,objectUpdate({lbl_color:'#666',lbl_text_align:'right'},n));});}}
dlg.show_action(function(){setTimeout(function(){var inputNodes=dojo.query('input',dlg.getParentNode().widget.domNode)||[];if(inputNodes.length){inputNodes[0].focus();}},500);});},paletteMap:function(kw){kw=kw||{};kw.paletteCode=kw.paletteCode||'mapViewer';var paletteWdg=genro.wdgById(kw.paletteCode+'_floating');if(!paletteWdg){var node=objectPop(kw,'sourceNode');if(!node){genro.src.getNode()._('div','_map_palette');node=genro.src.getNode('_map_palette').clearValue();}
node.freeze();kw.dockTo=kw.dockTo||'dummyDock:open';var paletteNode=node._('PaletteMap',kw).getParentNode();node.unfreeze();paletteWdg=paletteNode.getWidget();}else{paletteWdg.show();}},request:function(title,msg,buttons,resultPath,valuePath){genro.src.getNode()._('div','_dlg_request');var buttons=buttons||{confirm:'Confirm',cancel:'Cancel'};var node=genro.src.getNode('_dlg_request').clearValue().freeze();var dlg=node._('dialog',{nodeId:'_dlg_request',title:title})._('div',{_class:'dlg_ask','action':"genro.wdgById('_dlg_request').hide();genro.setData('"+resultPath+"',this.attr.actCode);"});dlg._('div',{'content':msg,'_class':'selectable dlg_ask_msg'});dlg._('textBox',{'value':'^'+valuePath});for(var btn in buttons){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn});}
node.unfreeze();genro.wdgById('_dlg_request').show();},floating:function(kw){var float_id=kw.nodeId;genro.src.getNode()._('div','_gnr_float_'+float_id);var node=genro.src.getNode('_gnr_float_'+float_id).clearValue();return node._('floatingPane',kw);},quickTooltipPane:function(kw,contentCb,contentCbKw){kw=objectUpdate({},kw);kw.evt=kw.evt||false;var nodeId=kw.nodeId||'td_'+'tempTooltip';var quickRoot='_dlgTooltip_quick_'+nodeId;genro.src.getNode()._('div',quickRoot);var node=genro.src.getNode(quickRoot).clearValue();var domNode=objectPop(kw,'domNode');var openerId=kw.openerId||nodeId+'_opener';kw.openerId=openerId;node.freeze();if(domNode){kw.onCreated=function(){setTimeout(function(){genro.publish(openerId+'_open',{domNode:domNode});},1);};}
var fields=objectPop(kw,'fields');var cols=objectPop(kw,'cols',1);var tp=node._('tooltipPane',kw);if(fields){if(fields instanceof Array){tp=tp._('div',{_class:'quickTooltipContainer'});var fb=genro.dev.formbuilder(tp,cols,{border_spacing:'4px',width:'100%',fld_width:'100%'});fields.forEach(function(n){n=objectUpdate({},n);var w=objectPop(n,'wdg','textbox');fb.addField(w,objectUpdate({},n));});}}else if(contentCb){contentCbKw=contentCbKw||{};contentCbKw.tooltipOpenerId=openerId;contentCb(tp,contentCbKw);}
node.unfreeze();return tp;},quickDialog:function(title,kw,rootNode){kw=objectUpdate({_class:'dlg_prompt'},kw);var quickRoot='_dlg_quick_'+genro.getCounter();var node;if(!rootNode){genro.src.getNode()._('div',quickRoot);node=genro.src.getNode(quickRoot).clearValue();}else{rootNode._('div',quickRoot,{_attachTo:'mainWindow',parentForm:false});node=rootNode.getValue().getNode(quickRoot).clearValue();}
node.freeze();var kwdimension=objectExtract(kw,'height,width,background,padding');if(kw.closable){kw.connect_hide=function(){var that=this;setTimeout(function(){that._destroy();},genro.dlg._quickDialogDestroyTimeout);};}
var dlg=node._('dialog',objectUpdate({title:title},kw));var box=dlg._('div',kwdimension);var center=box._('div',{_class:'pbl_dialog_center'});if(kw.dialog_bottom!==false){var bottom=box._('div',{_class:'dialog_bottom'});dlg.bottom=bottom;}
dlg.center=center;dlg.close_action=function(){dlg.getParentNode().widget.hide();setTimeout(function(){var ndlg=dlg.getParentNode();if(ndlg){ndlg.getParentNode()._value.popNode(ndlg.label);}},genro.dlg._quickDialogDestroyTimeout);};dlg.show_action=function(onShowCb){var node=this.getParentNode().getParentNode();node.unfreeze();var wdg=this.getParentNode().widget;genro.callAfter(function(){wdg.show();if(onShowCb){onShowCb();}},1);};return dlg;},multiUploaderDialog:function(title,kw,sourceNode){var uploaderKw=objectExtract(kw,'nodeId,height,width,uploadPath,onUploadedMethod,onUploadingMethod,onResult');kw.closable=true;var dlg=this.quickDialog(title,kw,sourceNode);uploaderKw.height=uploaderKw.height||'300px';uploaderKw.width=uploaderKw.width||'500px';uploaderKw.nodeId=uploaderKw.nodeId||'multiuploader_'+genro.getCounter();var onResult=objectPop(uploaderKw,'onResult')||function(result){};uploaderKw.onResult=function(result){funcApply(onResult,{result:result},this);dlg.close_action();};uploaderKw.storepath=uploaderKw.storepath||'^gnr.multiupload_store';genro.setData('gnr.multiupload_store',new gnr.GnrBag());var g=dlg.center._('DropUploaderGrid',uploaderKw);dlg.show_action();var actionCb=function(){genro.nodeById(uploaderKw.nodeId).publish('doUpload');};dlg.bottom._('button','confirm',{float:'right',action:actionCb,label:_T('Upload files')});return dlg;},zoomPaletteFromSourceNode:function(sourceNode,evt){var zoomAttr=sourceNode.evaluateOnNode(sourceNode.attr._zoomKw);var attr=sourceNode.currentAttributes();objectUpdate(zoomAttr,objectExtract(attr,'_zoomKw_*'));zoomAttr.evt=evt;this.makeZoomElement(zoomAttr);},makeZoomElement:function(kw){var mode=objectPop(kw,'mode')||'palette';if(mode=='palette'){this.zoomPalette(kw);}else if(mode=='page'&&genro.mainGenroWindow){var pageKw={};kw['main_call']='main_form';pageKw['file']=this._prepareThIframeUrl(kw);pageKw['label']=kw.title;pageKw['subtab']=true;genro.mainGenroWindow.genro.publish('selectIframePage',pageKw);}
else if(mode=='window'&&genro.root_page_id){var pageKw={};kw['main_call']='main_form';pageKw['file']=this._prepareThIframeUrl(kw);pageKw['label']=kw.title;genro.mainGenroWindow.genro.publish('newBrowserWindowPage',pageKw);}},iframePalette:function(kw){var paletteCode=kw.paletteCode||'external_'+genro.getCounter();var wdg=genro.wdgById(paletteCode+'_floating');if(wdg){wdg.show();wdg.bringToTop();return;}
var zoomUrl=objectPop(kw,'url');genro.src.getNode()._('div',paletteCode,{_class:'hiddenDock'});var node=genro.src.getNode(paletteCode).clearValue();node.freeze();var paletteAttr={'paletteCode':paletteCode,title:kw.title,overflow:'hidden',dockTo:false,width:'1px',height:'1px'};if(kw.evt){paletteAttr.top=_px(evt.clientY);paletteAttr.left=_px(evt.clientX);}
paletteAttr.palette_selfsubscribe_resize="$1.top='100px';this.widget.setBoxAttributes($1);";objectUpdate(paletteAttr,kw);var palette=node._('palettePane',paletteCode,paletteAttr);palette._('iframe','iframeNode',{'src':zoomUrl,height:'100%',width:'100%',border:0});node.unfreeze();return palette;},zoomFromCell:function(evt){var view=dijit.getEnclosingWidget(evt.target);view.content.decorateEvent(evt);var cellIndex=evt.cellIndex;var rowIndex=evt.rowIndex;var grid=view.grid;var structbag=grid.structbag();var cellattr=structbag.getNode('view_0.rows_0.#'+cellIndex).attr;var zoomAttr=objectExtract(cellattr,'zoom_*',true);zoomAttr['pkey']=grid.currRenderedRow[(zoomAttr['pkey']?zoomAttr['pkey']:grid._identifier).replace(/\./g,'_').replace(/@/g,'_')];zoomAttr['main_call']='main_form';zoomAttr['evt']=evt;zoomAttr['title']=grid.currRenderedRow[(cellattr['caption_field']||cellattr['field']).replace(/\W/g,'_')]
zoomAttr['url_th_linker']=zoomAttr.linker||true;zoomAttr['paletteCode']=zoomAttr['pkey']+(zoomAttr['formResource']||'');zoomAttr=grid.sourceNode.evaluateOnNode(zoomAttr);var mode=objectPop(zoomAttr,'mode')||'palette';if(mode=='palette'){this.zoomPalette(zoomAttr);}else if(mode=='page'&&genro.root_page_id){var pageKw={};pageKw['file']=this._prepareThIframeUrl(zoomAttr);pageKw['label']=zoomAttr.title;pageKw['subtab']=true;genro.mainGenroWindow.genro.publish('selectIframePage',pageKw);}
else if(mode=='window'&&genro.root_page_id){var pageKw={};pageKw['file']=this._prepareThIframeUrl(zoomAttr);pageKw['label']=zoomAttr.title;genro.mainGenroWindow.genro.publish('newBrowserWindowPage',pageKw);}},zoomPage:function(kw){kw=kw||{};kw.main_call=kw.main_call||'main_form';kw['file']=this._prepareThIframeUrl(kw);kw['label']=kw.title;kw['subtab']=true;genro.mainGenroWindow.genro.publish('selectIframePage',kw)},floatingEditor:function(sourceNode,kw){kw=kw||{};var paletteCode=kw.paletteCode||'floatingEditor_'+sourceNode.getStringId();var wdg=genro.wdgById(paletteCode+'_floating');if(wdg){wdg.show();wdg.bringToTop();return;}
genro.src.getNode()._('div',paletteCode,{_class:'hiddenDock'});var node=genro.src.getNode(paletteCode).clearValue();node.freeze();var kw=kw||{};var paletteAttr={'paletteCode':paletteCode,title:'Editor',overflow:'hidden',dockTo:'dummyDock:open',width:'800px',height:'400px',maxable:true};var palette=node._('palettePane',paletteCode,paletteAttr);var valuepath=kw.valuepath||sourceNode.attr.innerHTML||sourceNode.attr.value;valuepath='^'+sourceNode.absDatapath(valuepath);palette._('ckeditor',objectUpdate(kw,{value:valuepath}));node.unfreeze();},dialogEditor:function(sourceNode,kw){var kw=kw||{};var dlg_kw={closable:true,width:'800px',autoSize:true,dialog_bottom:false};var dlg=genro.dlg.quickDialog('Editor',objectUpdate(dlg_kw,kw));var valuepath=kw.valuepath||sourceNode.attr.innerHTML||sourceNode.attr.value;valuepath='^'+sourceNode.absDatapath(valuepath);dlg.center._('ckeditor',objectUpdate(kw,{value:valuepath}));dlg.show_action()},thIframePalette:function(kw,openKw){if(objectPop(kw,'rootPalette')){kw.th_from_package=genro.getData("gnr.package")
kw.url_forced_parent_page_id=genro.page_id;return genro.mainGenroWindow.genro.dlg.thIframePalette(kw,openKw);}
var table=kw.table;var paletteCode=kw.paletteCode||'th_'+table.replace('.','_')+(kw.formResource||'')+(kw.main_call||'');var paletteNode=genro.nodeById(paletteCode+'_floating');openKw=openKw||{};var openKw=objectUpdate(openKw,objectExtract(kw,'default_*',false,true));if(kw.pkey){openKw.pkey=objectPop(kw,'pkey');}
if(paletteNode){paletteNode.widget.show();paletteNode.widget.bringToTop();}else{var zoomUrl=this._prepareThIframeUrl(kw);genro.src.getNode()._('div',paletteCode,{_class:'hiddenDock'});var node=genro.src.getNode(paletteCode).clearValue();node.freeze();var default_height='300px';var default_width='500px';var palette_height=objectPop(kw,'palette_height');var palette_width=objectPop(kw,'palette_width');var sizeFromContent=objectPop(kw,'sizeFromContent');var fixedTitle=objectPop(kw,'fixedTitle');var paletteKwargs=objectExtract(kw,'palette_*',false,true);var dockTo=kw.dockTo===false?false:(kw.dockTo||'dummyDock:open');var paletteAttr={'paletteCode':paletteCode,title:kw.title||'Palette:'+table,overflow:'hidden',dockTo:dockTo,width:sizeFromContent?'1px':(palette_width||default_width),height:sizeFromContent?'1px':(palette_height||default_height),fixedPosition:true};objectUpdate(paletteAttr,paletteKwargs);var palette=node._('palettePane',paletteCode,paletteAttr);var onSavedCb=objectPop(kw,'onSavedCb');var iframeNode=palette._('iframe',{'src':zoomUrl,height:'100%',width:'100%',border:0,onStarted:function(){var paletteNode=palette.getParentNode();var wdg=paletteNode.getWidget();if(this._genro._rootForm){if(sizeFromContent){palette_height=palette_height||this._genro.getData('gnr.rootform.size.height')||default_height;palette_width=palette_width||this._genro.getData('gnr.rootform.size.width')||default_width;}
if(kw.main_call=='main_form'){this._genro._rootForm.subscribe('onDismissed',function(){if(!dockTo){wdg.close();}else{wdg.hide();}})}
if(!fixedTitle){this._genro._rootForm.subscribe('onChangedTitle',function(kw){wdg.setTitle(kw.title)});}}else if(kw.lookup){this._genro.nodeById('lookup_root').subscribe('lookup_cancel',function(){wdg.close();});}
if(onSavedCb){this._genro._rootForm.subscribe('onSaved',function(kw){onSavedCb(kw);});}
if(sizeFromContent&&!wdg._size_from_cache){wdg.setBoxAttributes({height:palette_height||default_height,width:palette_width||default_width});}}}).getParentNode();node.unfreeze();var paletteNode=genro.nodeById(paletteCode+'_floating');paletteNode._iframeNode=iframeNode;}
if(objectNotEmpty(openKw)){openKw.topic=openKw.topic||'main_form_open';paletteNode._iframeNode.domNode.gnr.postMessage(paletteNode._iframeNode,openKw);}
return paletteNode;},_prepareThIframeUrl:function(kw){var prefix=kw.lookup?'/sys/lookuptables/':'/sys/thpage/';var zoomUrl=kw.zoomUrl||prefix+kw.table.replace('.','/');var dbstore=genro.getData('gnr.dbstore');if(dbstore){zoomUrl='/'+dbstore+zoomUrl;}
var urlKw=objectExtract(kw,'url_*');urlKw.th_public=objectPop(kw,'public')||false;if(kw.pkey){urlKw.th_pkey=kw.pkey;}
if(kw.formResource){urlKw.th_formResource=kw.formResource;}
if(kw.viewResource){urlKw.th_viewResource=kw.viewResource;}
if(kw.main_call){urlKw['main_call']=kw.main_call;}
if(kw.readOnly){urlKw['readOnly']=kw.readOnly;}
objectUpdate(urlKw,objectExtract(kw,'current_*',false,true));urlKw['th_from_package']=kw.th_from_package||genro.getData("gnr.package");urlKw['_parent_page_id']=objectPop(urlKw,'forced_parent_page_id')||genro.page_id;return genro.addParamsToUrl(zoomUrl,urlKw);},zoomPalette:function(kw,openKw){var evt=objectPop(kw,'evt');if(evt){kw.palette_top=_px(evt.clientY);kw.palette_left=_px(evt.clientX);kw.sizeFromContent=true;}
return this.thIframePalette(kw,openKw);},quickPalette:function(paletteCode,kw,content){var kw=kw||{};kw=objectUpdate({paletteCode:paletteCode,dockTo:'dummyDock:open'},kw);var wdg=genro.wdgById(paletteCode+'_floating');var evt=kw.evt;if(wdg){wdg.show();wdg.bringToTop();return;}
genro.src.getNode()._('div',paletteCode,{_class:'hiddenDock'});var node=genro.src.getNode(paletteCode).clearValue();node.freeze();if(evt){kw.top=_px(evt.clientY);kw.left=_px(evt.clientX);}
var palette=node._('palettePane',paletteCode,kw);if(content){if(typeof(content)=='string'){palette._('div',{innerHTML:content});}else if(content instanceof gnr.GnrDomSourceNode){palette.setItem(content.label,content._value,content.attr);}else if(typeof(content)=='function'){content(palette);}else{var tag=objectPop(content,'tag')||'div';palette._(tag,content);}}
node.unfreeze();return palette.getParentNode();},lazyTip:function(domNode,rpcmethod){var kw={};var k=0;for(var i=2;i<arguments.length;i++){kw['p_'+k]=arguments[i];k++;}
var to=setTimeout(function(){var result=genro.serverCall(rpcmethod,kw);domNode.setAttribute('title',result);domNode.setAttribute('onmouseover','');},1000);domNode.onmouseout=function(){clearTimeout(to);};},listChoice:function(title,msg,buttons,resultPath,valuePath,storePath){genro.src.getNode()._('div','_dlg_listChoice');var buttons=buttons||{confirm:'Confirm',cancel:'Cancel'};var node=genro.src.getNode('_dlg_listChoice').clearValue().freeze();var dlg=node._('dialog',{nodeId:'_dlg_listChoice',title:title})._('div',{_class:'dlg_ask','action':"genro.wdgById('_dlg_listChoice').hide();genro.setData('"+resultPath+"',this.attr.actCode);"});dlg._('div',{'content':msg,'_class':'selectable dlg_ask_msg'});dlg._('filteringSelect',{'value':'^'+valuePath,'storepath':storePath,'ignoreCase':true});for(var btn in buttons){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn});}
node.unfreeze();genro.wdgById('_dlg_listChoice').show();},uploaderDialog:function(title,method,kw){var kw=kw||{};var dlg_kw=objectUpdate({closable:true,autoSize:true,dialog_bottom:false},objectExtract(kw,'dlg_*'));var dlg=genro.dlg.quickDialog(title,dlg_kw);kw.label=_T(kw.label||'Drop the file to import here');kw.onUploadedMethod=method;kw.onResult=function(handler){var result=handler.currentTarget.responseText;if(kw.onImport){kw.onImport(result);}
if(kw.resultPath){genro.setData(kw.resultPath,result);}
dlg.close_action();};dlg._('div',{padding:'10px'})._('dropUploader',(objectUpdate({progressBar:true,width:'300px'},kw)))
dlg.show_action();},upload:function(title,method,resultPath,remotekw,label,cancel,send,fireOnSend){label=label||'Browse...';cancel=cancel||'Cancel';send=send||'Send';var title=title;genro.src.getNode()._('div','_dlg_ask');var node=genro.src.getNode('_dlg_ask').clearValue().freeze();var dlgRoot=node._('div');var baseId=node.getValue().getNodes()[0].getStringId();var kw={width:'340px',height:'25px',margin:'15px',label:label,cancel:cancel,id:baseId+'_uploader',method:method,onUpload:'genro.setData("'+resultPath+'", $1);'};if(remotekw){for(var par in remotekw){kw['remote_'+par]=remotekw[par];}}
var dlg=dlgRoot._('dialog',{id:baseId+'_dlg',title:title})._('div',{_class:'dlg_ask'});dlg._('div')._('fileInput',kw);var cb=function(){var dlgid=baseId+'_dlg';var uploaderid=baseId+'_uploader';dijit.byId(dlgid).onCancel();if(fireOnSend){genro.fireEvent(fireOnSend);}
dijit.byId(uploaderid).uploadFile();};dlg._('div')._('button',{label:send,margin_right:'15px',margin_bottom:'1px',onClick:cb});node.unfreeze();dijit.byId(baseId+'_dlg').show();}});



dojo.declare("gnr.GnrDomHandler",null,{constructor:function(application){this.application=application;this.pendingHeaders={};this.css3AttrNames=['rounded','gradient','shadow','transform','transition','zoom','filter'];this.styleAttrNames=['height','width','top','left','right','bottom','resize','visibility','opacity','overflow','float','clear','display','line_height','z_index','border','position','padding','margin','cursor','color','white_space','vertical_align','background','font','text'].concat(this.css3AttrNames);},isStyleAttr:function(name){for(var i=0;i<this.styleAttrNames.length;i++){if((name==this.styleAttrNames[i])||(name.indexOf(this.styleAttrNames[i]+'_')==0)){return true;}}},iFramePrint:function(iframe){var contentWindow=genro.dom.iframeContentWindow(iframe);setTimeout(function(){contentWindow.print();},1);},iframeContentWindow:function(iframe_el){var win=dijit.getDocumentWindow(genro.dom.iframeContentDocument(iframe_el))||genro.dom.iframeContentDocument(iframe_el)['__parent__']||(iframe_el.name&&document.frames[iframe_el.name])||null;return win;},iframeContentDocument:function(iframe_el){var doc=iframe_el.contentDocument||(iframe_el.contentWindow&&iframe_el.contentWindow.document)||(iframe_el.name&&document.frames[iframe_el.name]&&document.frames[iframe_el.name].document)||null;return doc;},addStyleSheet:function(cssText,cssTitle){var style=document.createElement("style");style.setAttribute("type","text/css");style.setAttribute('title',cssTitle);if(style.styleSheet){var setFunc=function(){style.styleSheet.cssText=cssStr;};if(style.styleSheet.disabled){setTimeout(setFunc,10);}else{setFunc();}}else{cssText=document.createTextNode(cssText);style.appendChild(cssText);}
document.getElementsByTagName("head")[0].appendChild(style);style.disabled=false;},loadCss:function(url,cssTitle,cb,avoidCache){if(avoidCache){url=genro.addParamsToUrl(url,{nocache:timeStamp()});}
var e=document.createElement("link");e.href=url;e.type="text/css";e.rel="stylesheet";e.media="screen";document.getElementsByTagName("head")[0].appendChild(e);if(cb){e.onload=cb;}},loadJs:function(url,cb,avoidCache){if(avoidCache){url=genro.addParamsToUrl(url,{nocache:timeStamp()});}
var e=document.createElement("script");e.src=url;e.type="text/javascript";document.getElementsByTagName("head")[0].appendChild(e);if(cb){e.onload=cb;}},loadExternal:function(urlList,avoidCache){if(typeof(urlList)=='string'){if(urlList.indexOf(',')>-1){urlList=urlList.split(',');}
else{urlList=[urlList];}}
dojo.forEach(urlList,function(url){var name=url.split('?')[0];var splitted_name=name.split('.');var file_ext=splitted_name[splitted_name.length-1].toLowerCase();if(file_ext=='js'){this.loadJs(url,null,avoidCache);}
else if(file_ext=='css'){this.loadCss(url,null,null,avoidCache);}});},addHeaders:function(headers,cb){if(typeof(headers)=='string'){headers=headers.split(',');}
var firstHead=document.getElementsByTagName("head")[0];var waitCb=function(url){objectPop(genro.dom.pendingHeaders,url);if(!objectNotEmpty(genro.dom.pendingHeaders)){cb();}};headers.forEach(function(h){if(typeof(h)=='string'){h={url:h,htype:stringEndsWith(h,'.js')?'script':'link'};}
var original_h=objectUpdate({},h);h=objectUpdate({},h);var htype=objectPop(h,'htype');var e=document.createElement(htype);var url=objectPop(h,'url');if(htype=='script'){e.type="text/javascript";e.src=objectPop(h,'src')||url;url=e.src;}else if(htype=='link'){e.href=objectPop(h,'href')||url;e.type=objectPop(h,'type')||"text/css";e.rel=objectPop(h,'rel')||"stylesheet";e.media=objectPop(h,'media')||"screen";url=e.href;}
for(var k in h){e[k]=h[k];}
genro.dom.pendingHeaders[url]=true;firstHead.appendChild(e);e.onload=function(){waitCb(url);};});},addClass:function(where,cls){if(typeof(cls)=='string'){var domnode=this.getDomNode(where);if(!domnode)return;var classes=cls.split(' ');for(var i=0;i<classes.length;i++){if(domnode.addClass){domnode.addClass(classes[i]);}else{dojo.addClass(domnode,classes[i]);}}}},themeAttribute:function(topic,property,dflt){var topic=genro.theme[topic];return topic?topic[property]:dflt;},style:function(where,attr,value){var domnode=this.getDomNode(where);if(typeof(attr)=='string'&&attr.indexOf(':')>=0){attr=objectFromStyle(attr);}
if(domnode){if(typeof(attr)=='string'){dojo.style(domnode,genro.dom.dojoStyleAttrName(attr),value);}else{var kw={};for(var k in attr){kw[genro.dom.dojoStyleAttrName(k)]=attr[k];}
dojo.style(domnode,kw);}}},dojoStyleAttrName:function(attr){if(attr.indexOf('_')){attr=attr.split('_');}else if(attr.indexOf('-')){attr=attr.split('-');}else{return attr;}
var r=attr.splice(0,1);dojo.forEach(attr,function(n){r=r+stringCapitalize(n);});return r;},getDomNode:function(where){if(typeof(where)=='string'){var where=genro.domById(where);}
if(!where){return;}
if(where instanceof gnr.GnrDomSourceNode){where=where.getDomNode();}else if(where instanceof gnr.GnrDomSource){where=where.getParentNode().getDomNode();}
return where;},removeClass:function(where,cls){if(typeof(cls)=='string'){var domnode=this.getDomNode(where);if(!domnode)return;var classes=cls.split(' ');for(var i=0;i<classes.length;i++){if(domnode.removeClass){domnode.removeClass(classes[i]);}else{dojo.removeClass(domnode,classes[i]);}}}},setClass:function(where,cls,set){if(set=='toggle'){genro.dom.toggleClass(where,cls);}
else if(set){this.addClass(where,cls);}else{this.removeClass(where,cls);}},toggleClass:function(where,cls){if(typeof(cls)=='string'){var toggle=function(n,c){dojo[dojo.hasClass(n,c)?'removeClass':'addClass'](n,c);};var domnode=this.getDomNode(where);if(!domnode)return;var classes=cls.split(' ');for(var i=0;i<classes.length;i++){if(domnode.forEach){domnode.forEach(function(n){toggle(n,classes[i]);});}else{toggle(domnode,classes[i]);}}}},bodyClass:function(cls,set){genro.dom.setClass(dojo.body(),cls,set);},disable:function(where){this.addClass(where,'disabled');},enable:function(where){this.removeClass(where,'disabled');},hide:function(where){this.addClass(where,'hidden');},show:function(where){this.removeClass(where,'hidden');},toggleVisible:function(where,visible){if(visible){this.show(where);}else{this.hide(where);}},effect:function(where,effect,kw){var anim;var effect=effect.toLowerCase();var kw=kw||{};if(typeof(where)=='string'){var where=genro.domById(where);}
if(!where){return;}
kw.node=where;kw.duration=kw.duration||300;if(effect=='fadein'){genro.dom.style(where,{opacity:0});anim=dojo.fadeIn(kw);}
else if(effect=='fadeout'){genro.dom.style(where,{opacity:1});anim=dojo.fadeOut(kw);}
else if(effect=='wipein'){anim=dojo.fx.wipeIn(kw);}
else if(effect=='wipeout'){anim=dojo.fx.wipeOut(kw);}
else{return;}
anim.play();return anim;},html_maker:function(kw,bagnode){kw=genro.evaluate(kw);return genro.dom['html_'+kw.widget](kw,bagnode);},html_checkbox:function(kw,bagnode){if('value'in kw){var path=kw.value;kw.onclick=dojo.hitch(bagnode,function(e){var v=e.target.checked;this.setAttr(path,v);});kw.checked=bagnode.getAttr(path);}
return'<input type="checkbox" name="'+kw.name+'" checked="'+kw.checked+'" id="'+kw.id+'" onclick="'+kw.onclick+'"><label for="'+kw.id+'">'+kw.label+'</label>';},html_select:function(kw){var values=kw.values.split(',');var wdg='<label for="'+kw.id+'">'+kw.label+'</label>';wdg=wdg+'<select name="'+kw.name+'" id="'+kw.id+'" onchange="'+kw.onchange+'" size="1">';wdg=wdg+'<option value="false">&nbsp</option>';for(var i=0;i<values.length;i++){var val=values[i];var subwdg=null;if(val.indexOf(':')){val=val.split(':');subwdg='<option value="'+val[0]+'">'+val[1]+'</option>';}else{subwdg='<option value="'+val+'">'+val+'</option>';}
wdg=wdg+subwdg;};wdg=wdg+'</select>';return wdg;},setDomNodeDisabled:function(domNode,disabled){domNode.disabled=disabled;if(disabled){domNode.setAttribute('disabled',disabled);}else{domNode.removeAttribute('disabled');}},resizeContainer:function(wdgt){if(wdgt.parent&&wdgt.parent.isContainer){this.resizeContainer(wdgt.parent);}else if(wdgt&&wdgt.isContainer){wdgt.onResized();}},getStyleDict:function(attributes,noConvertStyle){if(attributes.gnrIcon){attributes.iconClass='gnrIcon gnrIcon'+objectPop(attributes,'gnrIcon');}
noConvertStyle=noConvertStyle||[];var styledict=objectFromStyle(objectPop(attributes,'style'));var attrname;dojo.forEach(this.css3AttrNames,function(name){var valuedict=objectExtract(attributes,name+'_*');if((name in attributes)||objectNotEmpty(valuedict)){var value=objectPop(attributes,name);genro.dom['css3style_'+name](value,valuedict,styledict,noConvertStyle);}});for(var i=0;i<this.styleAttrNames.length;i++){attrname=this.styleAttrNames[i];if(attrname in attributes&&arrayIndexOf(noConvertStyle,attrname)==-1){styledict[attrname.replace('_','-')]=objectPop(attributes,attrname);}}
this.style_setall('min',styledict,attributes,noConvertStyle);this.style_setall('max',styledict,attributes,noConvertStyle);this.style_setall('background',styledict,attributes,noConvertStyle);this.style_setall('text',styledict,attributes,noConvertStyle);this.style_setall('font',styledict,attributes,noConvertStyle);this.style_setall('margin',styledict,attributes,noConvertStyle);this.style_setall('padding',styledict,attributes,noConvertStyle);this.style_setall('border',styledict,attributes,noConvertStyle);this.style_setall('overflow',styledict,attributes,noConvertStyle);return styledict;},css3style_filter:function(value,valuedict,styledict,noConvertStyle){var result='';var key=dojo.isSafari?'-webkit-filter':'-moz-filter';if('rotate'in valuedict){result+='hue-rotate('+(valuedict['rotate']||'0')+'deg) ';}
if('invert'in valuedict){result+='invert('+(valuedict['invert']||'0')+') ';}
if('contrast'in valuedict){result+='contrast('+(valuedict['contrast']||'0')+') ';}
styledict[key]=(styledict[key]||'')+result;},css3style_zoom:function(value,valuedict,styledict,noConvertStyle){if(dojo.isSafari){styledict['zoom']=value;}else{styledict['-moz-transform']=(styledict['-moz-transform']||'')+'scale('+value+') ';styledict['-moz-transform-origin']='0px 0px ';}},css3style_transform:function(value,valuedict,styledict,noConvertStyle){var key=dojo.isSafari?'-webkit-transform':'-moz-transform';var result='';if('rotate'in valuedict){result+='rotate('+(valuedict['rotate']||'0')+'deg ) ';}
if('translate'in valuedict){result+='translate('+valuedict['translate']+') ';}
if('translate_x'in valuedict){result+='translatex('+(valuedict['translate_x']||'0')+'px) ';}
if('translate_y'in valuedict){result+='translatey('+(valuedict['translate_y']||'0')+'px) ';}
if('scale'in valuedict){result+='scale('+(valuedict['scale']||0)+') ';}
if('origin'in valuedict){styledict['transform-origin']=valuedict['origin'];}
if('scale_x'in valuedict){result+='scalex('+(valuedict['scale_x']||1)+') ';}
if('scale_y'in valuedict){result+='scaley('+(valuedict['scale_y']||1)+') ';}
if('skew'in valuedict){result+='skew('+valuedict['skew']+') ';}
if('skew_x'in valuedict){result+='skewx('+(valuedict['skew_x']||0)+'deg) ';}
if('skew_y'in valuedict){result+='skewy('+(valuedict['skew_y']||0)+'deg) ';}
styledict[key]=(styledict[key]||'')+result;},css3style_transition:function(value,valuedict,styledict,noConvertStyle){var key=dojo.isSafari?'-webkit-transition':'-moz-transition';transition_property='width,height';if(value){styledict[key]=value;}
for(var prop in valuedict){value=valuedict[prop];if(prop=='function'){prop='timing-function';}
if(((prop=='duration')||(prop=='delay'))&&((value+'').indexOf('s')<0)){value=value+'s';}
styledict[key+'-'+prop]=value;}},css3style_shadow:function(value,valuedict,styledict,noConvertStyle){var inset=false;var value=value||'0px 0px 0px gray';if(value.indexOf('inset')>=0){inset=true;value=value.replace('inset','');}
var shadow=splitStrip(value,' ');var x=((valuedict['x']||shadow[0])+'').replace('px','');var y=((valuedict['y']||shadow[1])+'').replace('px','');var blur=((valuedict['blur']||shadow[2])+'').replace('px','');var color=valuedict['color']||shadow[3];var inset='inset'in valuedict?valuedict['inset']:inset;var result=x+'px '+y+'px '+blur+'px '+color;if(inset){result+=' inset';}
var key='box-shadow';styledict[key]=result;},css3style_gradient:function(value,valuedict,styledict,noConvertStyle){if(value){styledict['background-image']=value;}
if(objectNotEmpty(valuedict)){var colordict=objectExtract(valuedict,'color_*');var colors=[];for(var col in colordict){colors.push(col);}
colors.sort();var color_from=valuedict['from'];var color_to=valuedict['to'];if(dojo.isSafari){var d=parseInt(valuedict['deg']||0);d=(d+360)%360;if((d>=0)&&(d<45)){x1=0;x2=100;y1=50+(d/45)*50;y2=100-y1;}
else if((d>=45)&&(d<135)){y2=0;y1=100;x2=((135-d)/90)*100;x1=100-x2;}
else if((d>=135)&&(d<225)){x1=100;x2=0;y1=((225-d)/90)*100;y2=100-y1;}
else if((d>=225)&&(d<315)){y2=100;y1=0;x1=((315-d)/90)*100;x2=100-x1;}
else if((d>=315)&&(d<360)){x1=0;x2=100;y1=50-(((360-d)/45)*50);y2=100-y1;}
var r=[Math.round(x1,2),Math.round(y1,2),Math.round(x2,2),Math.round(y2,2)];var result="-webkit-gradient(linear, ";result+=r[0]+"% "+r[1]+"%,"+r[2]+"% "+r[3]+"% ";if(colors.length>0){dojo.forEach(colors,function(col){var c=(colordict[col]+',0').split(',');result+=", color-stop("+c[1]+"%, "+c[0]+")";});}else{result+=", from("+valuedict['from']+"), to("+valuedict['to']+")";}}else{var result='-moz-'+(valuedict['type']||'linear');result+='-gradient(';result+=(valuedict['deg']||0)+'deg ';if(colors.length>0){dojo.forEach(colors,function(col){var c=(colordict[col]+',0').split(',');result+=", "+c[0]+" "+c[01]+"%";});}else{result+=','+color_from+','+color_to;}}
styledict['background-image']=result+')';}},css3style_rounded:function(value,valuedict,styledict,noConvertStyle){var v;var cb=function(y,x){return'border-'+y+'-'+x+'-radius';};var rounded_corners=this.normalizedRoundedCorners(value,valuedict);for(var k in rounded_corners){v=rounded_corners[k];k=k.split('_');styledict[cb(k[0],k[1])]=v+'px';}},normalizedRoundedCorners:function(rounded,rounded_dict){var result={};var v,m;rounded_dict['all']=rounded||0;var converter=[['all','tr','tl','br','bl'],['top','tr','tl'],['bottom','br','bl'],['right','tr','br'],['left','tl','bl'],['top_left','tl'],['left_top','tl'],['top_right','tr'],['right_top','tr'],['bottom_left','bl'],['left_bottom','bl'],['bottom_right','br'],['right_bottom','br']];if(objectNotEmpty(rounded_dict)){dojo.forEach(converter,function(k){if(k[0]in rounded_dict){v=rounded_dict[k[0]];for(var i=1;i<k.length;i++){m=k[i];result[(m[0]=='t'?'top':'bottom')+'_'+(m[1]=='l'?'left':'right')]=v;}}});}
return result;},style_setall:function(label,styledict,attributes,noConvertStyle){for(var attrname in attributes){if(stringStartsWith(attrname,label+'_')&&arrayIndexOf(noConvertStyle,attrname)==-1){styledict[attrname.replace('_','-')]=objectPop(attributes,attrname);}}},addCssRule:function(rule){var styles=document.styleSheets;for(var i=0;i<styles.length;i++){var stylesheet=styles[i];if(stylesheet.title=='localcss'){if(stylesheet.insertRule){stylesheet.insertRule(rule,0);}
else{splittedrule=/(.*)\{(.*)\}/.exec(rule);if(splittedrule[1]&&splittedrule[2])stylesheet.addRule(splittedrule[1],splittedrule[2]);}
break;}}},cssRulesToBag:function(rules){var result=new gnr.GnrBag();var _importRule=3;var _styleRule=1;var rule,label,value,attr;for(var i=0,len=rules.length;i<len;i++){r=rules.item(i);switch(r.type){case _styleRule:label='r_'+i;value=genro.dom.styleToBag(r.style);result.setItem(label,value,{selectorText:r.selectorText,_style:r.style});this.css_selectors[r.selectorText]=value;break;case _importRule:attr={href:r.href};label=r.title||'r_'+i;result.setItem(label,genro.dom.cssRulesToBag(r.styleSheet.cssRules),attr);break;}};return result;},setSelectorStyle:function(selector,kw,path){var path=path||'gnr.stylesheet';var selectorbag=this.css_selectors[selector];for(var st in kw){selectorbag.setItem(st,kw[st]);}},getSelectorBag:function(selector){return this.css_selectors[selector];},styleSheetBagSetter:function(value,kw){var setters=objectExtract(kw,'_set_*',true);for(var setter in setters){var setlist=setters[setter].split(':');var s={};s[setter.replace('_','-')]=genro.evaluate(setlist.slice(1).join(':').replace('#',value));genro.dom.setSelectorStyle(setlist[0],s);}},styleSheetsToBag:function(src){src=src||document;var styleSheets=document.styleSheets;var result=new gnr.GnrBag();var label,value,attr;var cnt=0;this.css_selectors={};dojo.forEach(styleSheets,function(s){label=s.title||'s_'+cnt;attr={'type':s.type,'title':s.title};value=genro.dom.cssRulesToBag(s.cssRules);result.setItem(label,value,attr);cnt++;});return result;},styleToBag:function(s){var result=new gnr.GnrBag();var rule;for(var i=s.length;i>=0;i--){var st=s[i];result.setItem(st,s.getPropertyValue(st));}
return result;},windowTitle:function(title){document.title=title;},styleTrigger:function(kw){var parentNode=kw.node.getParentNode();var st=parentNode.attr._style;if(!st){return;}
if(kw.evt=='upd'){st.setProperty(kw.node.label,kw.value,null);}else if(kw.evt=='ins'){st.setProperty(kw.node.label,kw.node.getValue(),null);}
var stylebag=genro.dom.styleToBag(st);parentNode.setValue(stylebag);this.css_selectors[parentNode.attr.selectorText]=stylebag;},cursorWait:function(flag){if(flag){genro.dom.addClass(document.body,'cursorWait');}else{genro.dom.removeClass(document.body,'cursorWait');}},makeReadOnlyById:function(fieldId){var field=dojo.byId(fieldId);field.readOnly=true;field.style.cursor='default';dojo.connect(field,'onfocus',function(){field.blur();});},showHideSubRows:function(evt){var row=evt.target.parentNode.parentNode;var currlevel=row.getAttribute('lvl');var newstatus='';if(row.getAttribute('isclosed')!='y'){newstatus='y';}
row.setAttribute('isclosed',newstatus);var rows=row.parentNode.rows;var rowlevel,sublevel;for(var i=0;i<rows.length;i++){rowlevel=rows[i].getAttribute('lvl');if(rowlevel.indexOf(currlevel)==0){if(rowlevel!=currlevel){if(newstatus=='y'){rows[i].setAttribute('rowhidden',newstatus);if(rowlevel.slice(-2)!='._'){rows[i].setAttribute('isclosed',newstatus);}}else{sublevel=rowlevel.replace(currlevel+'.','');if(sublevel.indexOf('.')<0){rows[i].setAttribute('rowhidden',newstatus);}}}}}},parseXmlString:function(txt){var result;if(dojo.isIE){result=new ActiveXObject("Microsoft.XMLDOM");result.async="false";result.loadXML(txt);}else{var parser=new DOMParser();result=parser.parseFromString(txt,'text/xml');}
return result;},dispatchKey:function(keycode,domnode){var domnode=domnode||document.body;var e=document.createEvent('KeyboardEvent');e.initKeyEvent('keydown',true,true,window,false,false,false,false,keycode,0);domnode.dispatchEvent(e);},canBeDropped:function(dataTransfer,sourceNode){var dragSourceInfo=genro.dom.getDragSourceInfo(dataTransfer);if(objectNotEmpty)
if(dragSourceInfo.detachable){return'detach';}
var inherited=sourceNode.getInheritedAttributes();var supportedTypes=sourceNode.getInheritedAttributes().dropTypes;supportedTypes=supportedTypes?splitStrip(supportedTypes):[];for(var k in objectExtract(inherited,'onDrop_*',true)){supportedTypes.push(k);}
var draggedTypes=genro.dom.dataTransferTypes(dataTransfer);var matchCb=function(supportedType){return arrayMatch(draggedTypes,supportedType).length>0;};if(dojo.filter(supportedTypes,matchCb).length==0){return false;}
var dropTags=sourceNode.getInheritedAttributes().dropTags;if(!dropTags){return true;}
var dragTags=dragSourceInfo.dragTags;if(!dragTags){return false;}
var dragTags=splitStrip(dragTags,',');var or_conditions=splitStrip(dropTags,',');valid=false;for(var i=0;((i<or_conditions.length)&&!valid);i++){var valid=true;var or_condition=or_conditions[i].replace(/' NOT '/g,' AND !');or_condition=splitStrip(or_condition,' AND ');for(var j=0;((j<or_condition.length)&&valid);j++){var c=or_condition[j];exclude=false;if(c[0]=='!'){c=c.slice(1);exclude=true;}
var match=dojo.some(dragTags,function(k){return k==c;});valid=exclude?!match:match;};};return valid;},onDragOver:function(event){if(genro._lastDropTarget!=event.target){if(genro._lastDropTarget){genro.dom.onDragLeave(event);}
genro._lastDropTarget=event.target;genro.dom.onDragEnter(event);}
if(event.target.sourceNode&&event.target.sourceNode.getInheritedAttributes().dragOverCb){event.target.sourceNode.getInheritedAttributes().dragOverCb.call(this,event);}
event.stopPropagation();event.preventDefault();event.dataTransfer.dropEffect="move";},getBaseWidget:function(domnode){var widget=dijit.getEnclosingWidget(domnode);if(widget){return widget.sourceNode?widget:(widget.grid||widget.tree);}},getSourceNode:function(domnode){var sourceNode=domnode.sourceNode
if(!sourceNode){var wdg=genro.dom.getBaseWidget(domnode)
if(wdg){sourceNode=wdg.sourceNode}}
return sourceNode},getBaseSourceNode:function(domnode){while(domnode&&!domnode.sourceNode){domnode=domnode.parentNode;}
return domnode?domnode.sourceNode:null;},getEventInfo:function(event){var domnode=event.target;while(!domnode.getAttribute){domnode=domnode.parentNode;}
var info={'domnode':domnode};info.modifiers=genro.dom.getEventModifiers(event);var handler,sourceNode,widget,baseSourceNode;if(domnode.sourceNode){info.handler=domnode.gnr;info.sourceNode=domnode.sourceNode;info.nodeId=domnode.sourceNode.attr.nodeId;}
else{var baseSourceNode=this.getBaseSourceNode(domnode);var widget=dijit.getEnclosingWidget(domnode);var rootwidget=this.getBaseWidget(domnode);if(!rootwidget&&!baseSourceNode){return;}
if(!rootwidget||(baseSourceNode&&(baseSourceNode.isChildOf(rootwidget.sourceNode)))){info.handler=baseSourceNode.domNode.gnr;info.sourceNode=baseSourceNode;info.nodeId=baseSourceNode.attr.nodeId;info.domnode=baseSourceNode.domNode;}else if(widget){info.widget=widget;info.handler=rootwidget.gnr;info.sourceNode=rootwidget.sourceNode;info.nodeId=info.sourceNode.attr.nodeId;}else{return;}}
info.event=event;if(info.handler.customEventInfo){info.handler.customEventInfo(info);}
return info;},getDragDropInfo:function(event){var info=this.getEventInfo(event);if(!info){return;}
var domnode=info.domnode;if(event.type=='dragstart'){info.dragmode=domnode.getAttribute('dragmode');info.handler.fillDragInfo(info);info.drag=true;}else{info.drop=true;info.isTarget=true;var sourceNode=info.sourceNode;var attr=sourceNode.attr;var dropTarget=sourceNode.dropTarget||attr.selfDragRows||attr.selfDragColumns;var dropTargetCb=sourceNode.dropTargetCb;var dropTargetCbExtra=sourceNode.dropTargetCbExtra;info.dragSourceInfo=genro.dom.getDragSourceInfo(event.dataTransfer);if(info.dragSourceInfo.detachable){return info;}
if(dropTarget||dropTargetCb||dropTargetCbExtra){info.sourceNodeId=info.dragSourceInfo.nodeId;info.selfdrop=(info.nodeId&&(info.nodeId==info.sourceNodeId));var continueDrop=!(info.handler.fillDropInfo(info)===false);if(dropTargetCbExtra){for(var k in dropTargetCbExtra){continueDrop=dropTargetCbExtra[k](info,genro.dom.getFromDataTransfer(info.event.dataTransfer,k));if(!continueDrop){break}}}
if(!continueDrop||(dropTargetCb&&(!dropTargetCb(info)))){info.isTarget=false}}
else{info=null;}}
return info;},onDragLeave:function(event){if(genro.dom._dragLastOutlined){genro.dom.removeClass(genro.dom._dragLastOutlined,'canBeDropped');genro.dom.removeClass(genro.dom._dragLastOutlined,'cannotBeDropped');genro.dom._dragLastOutlined=null;}},onDragEnter:function(event){var dropInfo=this.getDragDropInfo(event);if(!dropInfo){return;}
event.stopPropagation();event.preventDefault();var sourceNode=dropInfo.sourceNode;var dataTransfer=event.dataTransfer;var canBeDropped=this.canBeDropped(dataTransfer,sourceNode);dataTransfer.effectAllowed=canBeDropped?'move':'none';dataTransfer.dropEffect=canBeDropped?'move':'none';if(canBeDropped!='detach'){genro.dom.outlineShape(dropInfo.outline,canBeDropped&&dropInfo.isTarget,event);}},outlineShape:function(shape,canBeDropped){if(genro.dom._dragLastOutlined){genro.dom.removeClass(genro.dom._dragLastOutlined,'canBeDropped');genro.dom.removeClass(genro.dom._dragLastOutlined,'cannotBeDropped');genro.dom._dragLastOutlined=null;}
if(shape){genro.dom.setClass(shape,'cannotBeDropped',!canBeDropped);genro.dom.setClass(shape,'canBeDropped',canBeDropped);genro.dom._dragLastOutlined=shape;}else{genro.dom.removeClass(dojo.body(),'drag_started');genro.publish('endDrag');}},onDetach:function(sourceNode,dropInfo){var domnode=sourceNode.getDomNode();var coords=dojo.coords(domnode);var title=sourceNode.getInheritedAttributes().title||'Untitled';var detached_id='detached_'+sourceNode._id;if(sourceNode.isPointerPath(title)){var pointer=title[0];title=sourceNode.absDatapath(title);title=pointer+title;}
var floating=genro.dlg.floating({'nodeId':'floating_'+sourceNode._id,'title':title,'top':dropInfo.event.pageY+'px','left':dropInfo.event.pageX+'px',resizable:true,dockable:true,closable:false,dockTo:'dummyDock',autoSize:false});var floatingWidget=floating.getParentNode().widget;var containerNode=floatingWidget.containerNode;containerNode.removeChild(containerNode.firstChild);var placeholderSource=floating._('div',{height:coords.h+'px',width:coords.w+'px',_class:'detached_placeholder',id:detached_id,persist:false});var placeholder=floatingWidget.containerNode.firstElementChild;var placeholder_content=placeholderSource._('div',{_class:'detached_placeholder_content'})
if(title){placeholder_content._('div',{_class:'detached_placeholder_title',innerHTML:title})}
var currentParent=domnode.parentNode;var extra_height=dojo.coords(floatingWidget.domNode).h;currentParent.replaceChild(placeholder,domnode);floatingWidget.containerNode.style.position='relative';floatingWidget.containerNode.appendChild(domnode);sourceNode.attr.isDetached=true;dojo.connect(floatingWidget,'hide',function(){var parentDomNode=placeholder.parentNode;var widget=dijit.getEnclosingWidget(parentDomNode);if(widget.domNode===parentDomNode){widget.setContent(domnode);}else{parentDomNode.replaceChild(domnode,placeholder);}
sourceNode.attr.isDetached=false;setTimeout(function(){floatingWidget.close();},1000);});floatingWidget.show();floatingWidget.bringToTop();coords.h=coords.h+extra_height;floatingWidget.resize(coords);},onDrop:function(event){genro.dom.outlineShape(null);event.stopPropagation();event.preventDefault();var dropInfo=this.getDragDropInfo(event);if(!dropInfo||!dropInfo.isTarget){return;}
var domnode=dropInfo.domnode;var sourceNode=dropInfo.sourceNode;var dataTransfer=event.dataTransfer;var dragSourceInfo=genro.dom.getDragSourceInfo(dataTransfer);if(dragSourceInfo.detachable){genro.dom.onDetach(genro.src.nodeBySourceNodeId(dragSourceInfo._id),dropInfo);return;}
var canBeDropped=this.canBeDropped(dataTransfer,sourceNode);if(canBeDropped){var inherited=sourceNode.getInheritedAttributes();var dropped=null;var dataTransferTypes=genro.dom.dataTransferTypes(dataTransfer);var dropTypes=(inherited.dropTypes||'text/plain').split(',');var params={'dropInfo':dropInfo};if((dojo.indexOf(dataTransferTypes,'Files')>=0)&&(dojo.indexOf(dropTypes,'Files')>=0)){genro.dom.onDrop_files(dataTransfer,inherited,params,sourceNode);}else{genro.dom.onDrop_standard(dataTransfer,inherited,params,sourceNode,dropTypes,dataTransferTypes);}}},onDrop_files:function(dataTransfer,inherited,params,sourceNode){var onDropAction=inherited.onDrop;if(!onDropAction){return;}
var drop_ext=inherited.drop_ext;var valid_ext=drop_ext?splitStrip(drop_ext.toLowerCase()):null;var files=[];dojo.forEach(dataTransfer.files,function(f){if((!valid_ext)||(dojo.indexOf(valid_ext,f['name'].toLowerCase().split('.').pop())>=0)){files.push(f);}});if(files.length>0){params['files']=files;funcApply(onDropAction,params,sourceNode);}},onDrop_standard:function(dataTransfer,inherited,params,sourceNode,dropTypes,dataTransferTypes){var onDropAction=inherited.onDrop;var values={};for(var i=0;i<dataTransferTypes.length;i++){var datatype=dataTransferTypes[i];if(datatype.indexOf('dragsourceinfo')==0){continue;}
var datatype_code=datatype.replace(/\W/g,'_');var inDropTypes=(dojo.filter(dropTypes,function(dropType){return datatype.match(dropType.replace('*','(.*)'));}).length>0);if(inherited['onDrop_'+datatype_code]||inDropTypes){var value=genro.dom.getFromDataTransfer(dataTransfer,datatype);if(inherited['onDrop_'+datatype_code]){params['data']=value;funcApply(inherited['onDrop_'+datatype_code],params,sourceNode);}else if(inDropTypes){values[datatype_code]=value;}}}
if(objectNotEmpty(values)&&onDropAction){params['data']=values;funcApply(onDropAction,params,sourceNode);}},_datatransfer:function(dt){if(dt){genro.setInStorage('local','_transferObj',dt);return;}
return genro.getFromStorage('local','_transferObj')||{};},onDragStart:function(event){genro.dom.addClass(dojo.body(),'draggingElement');if(event.target&&event.target.tagName&&event.target.tagName.toLowerCase()=='img'){if(dojo.isFF){event.dataTransfer.setData('text/html',null)}
return;}
event.stopPropagation();if(event.target.draggable===false){event.preventDefault();return false;}
var dragInfo=this.getDragDropInfo(event);var sourceNode=dragInfo.sourceNode;if(dragInfo.sourceNode.getAttributeFromDatasource('detachable')){if(!event.shiftKey||sourceNode.attr.isDetached){event.preventDefault();return;}}
var dragValues=dragInfo.handler.onDragStart(dragInfo);if(dragValues===false){event.preventDefault();return false;}
var inherited=sourceNode.getInheritedAttributes();var onDragCbDict=objectExtract(inherited,'onDrag_*');var doDrag;if('onDrag'in inherited){doDrag=funcCreate(inherited['onDrag'],'dragValues,dragInfo,treeItem')(dragValues,dragInfo,dragInfo.treeItem);}
if(objectNotEmpty(onDragCbDict)){for(var c in onDragCbDict){funcCreate(onDragCbDict[c],'dragValues,dragInfo,treeItem')(dragValues,dragInfo,dragInfo.treeItem);}}else if(doDrag===false){event.preventDefault();return;}
var domnode=dragInfo.target;var widget=dragInfo.widget;genro.dom._datatransfer({});var dataTransfer=event.dataTransfer;if(!dragInfo.dragImageNode){var dragClass=inherited['dragClass']||'draggedItem';if(dragClass){genro.dom.addClass(dragInfo.domnode,dragClass);dragInfo.dragClass=dragClass;setTimeout(function(){genro.dom.removeClass(dragInfo.domnode,dragClass);},1);}}
var dragTags=inherited['dragTags'];var local_dragTags=objectPop(dragValues,'dragTags');dragTags=dragTags?(local_dragTags?dragTags+','+local_dragTags:dragTags):local_dragTags;genro.dom.setDragSourceInfo(dragInfo,dragValues,dragTags);for(var k in dragValues){genro.dom.setInDataTransfer(dataTransfer,k,dragValues[k]);}
genro.dom._lastDragInfo=dragInfo;genro.dom.addClass(dojo.body(),'drag_started');},setInDataTransfer:function(dataTransfer,k,v){var v=convertToText(v);v=((k.indexOf('text/')==0)||(v[0]=='')||(v[0]=='T'))?v[1]:v[1]+'::'+v[0];dataTransfer.setData(k,v);var dt=genro.dom._datatransfer();dt[k]=v;genro.dom._datatransfer(dt);},setDragSourceInfo:function(dragInfo,dragValues,dragTags){var result={};if(dragInfo.nodeId){result['nodeId']=dragInfo.nodeId;}
if(dragInfo.sourceNode){result['_id']=dragInfo.sourceNode._id;if(dragInfo.sourceNode.getAttributeFromDatasource('detachable')){result['detachable']=true;}}
if(dragInfo.dragmode){result['dragmode']=dragInfo.dragmode;}
result['page_id']=genro.page_id;if(dragTags){result['dragTags']=dragTags;}
dragValues['dragsourceinfo']=result;},getDragSourceInfo:function(dataTransfer){return genro.dom.getFromDataTransfer(dataTransfer,'dragsourceinfo',true)||{};},getFromDataTransfer:function(dataTransfer,k){return convertFromText(genro.dom._datatransfer()[k]||dataTransfer.getData(k));},dataTransferTypes:function(dataTransfer){var transferobj=this._datatransfer();var dt=[];for(var k in transferobj){dt.push(k);}
var t;var types=dataTransfer.types;if(!types){return dt;}
for(var i=0;i<dataTransfer.types.length;i++){t=dataTransfer.types[i];if(dojo.indexOf(dt,t)<0){dt.push(t);}};return dt;},onDragEnd:function(event){genro.dom.outlineShape(null);genro.dom.removeClass(dojo.body(),'draggingElement');},getEventModifiers:function(e){var m=[];if(e.shiftKey){m.push('Shift');}
if(e.ctrlKey){m.push('Ctrl');}
if(e.altKey){m.push('Alt');}
if(e.metaKey){m.push('Meta');}
return m.join();},scrollableTable:function(domnode,gridbag,kw){var max_height=kw.max_height||'180px';var columns=kw.columns;var headers=kw.headers;var tblclass=kw.tblclass;var thead='<thead onmouseup="dojo.stopEvent(event)"><tr>';for(var k=0;k<columns.length;k++){thead=thead+"<th>"+headers[k]+"</th>";}
thead=thead+"<th style='width:13px;'>&nbsp</th></thead>";var nodes=gridbag.getNodes();var item,r,value,v,_customClasses,rowvalidation;var tbl=["<tbody>"];for(var i=0;i<nodes.length;i++){r="";item=nodes[i].attr;rowvalidation=' _is_valid_item="true" ';if(item._is_invalid_item){rowvalidation=' onmouseup="dojo.stopEvent(arguments[0]);" _is_valid_item="false" '}
_customClasses=objectPop(item,'_customclasses')||objectPop(item,'_customClasses');more_customclasses=objectExtract(item,'_customclasses_*')
if(more_customclasses){_customClasses=(_customClasses||'');for(var cck in more_customclasses){_customClasses=_customClasses+' '+more_customclasses[cck];}}
_customClasses=_customClasses?'class="'+_customClasses+'"':'';for(var k=0;k<columns.length;k++){v=item[columns[k]];value=v==null?'&nbsp':v;r=r+"<td>"+_F(value)+"</td>";}
tbl.push('<tr id="'+nodes[i].label+'"  '+_customClasses+rowvalidation+'>'+r+'</tr>');}
tbl.push("</tbody>");var tbody=tbl.join('');var cbf=function(cgr){var cgr_h=cgr?'<colgroup>'+cgr+'<col width=11 /></colgroup>':'';var cgr_b=cgr?'<colgroup>'+cgr+'</colgroup>':'';return'<div class="'+tblclass+'"><div><table>'+cgr_h+''+thead+'</table></div><div onmouseup="if(event.target===event.currentTarget){dojo.stopEvent(event)};" style="overflow-y:auto;overflow-x:hidden;max-height:'+max_height+';"><table>'+cgr_b+tbody+'</table></div></div>';};domnode.innerHTML=cbf('');var cb=function(){var hdrtr=dojo.query('thead tr',domnode)[0].children;var bodytr=dojo.query('tbody tr',domnode);var bodytr_first=bodytr[0].children;var colgroup="";for(var i=0;i<bodytr_first.length;i++){var wh=hdrtr[i].clientWidth;var wb=bodytr_first[i].clientWidth;var wt=wh>wb?wh:wb;colgroup=colgroup+'<col width="'+wt+'"/>';};domnode.innerHTML=cbf(colgroup);dojo.style(domnode,{width:'auto'});var rows=dojo.query('tbody tr',domnode);for(var i=0;i<rows.length;i++){rows[i].item=nodes[i];};};setTimeout(cb,1);},setTextInSelection:function(sourceNode,valueToPaste){var fn=sourceNode.widget.focusNode;var ss=fn.selectionStart;var se=fn.selectionEnd;var v=fn.value;var fistchunk=v.slice(0,ss);var secondchunk=v.slice(se);sourceNode.widget.setValue(fistchunk+valueToPaste+secondchunk,true);},isDisabled:function(domNode,inherited){var isDisabled=domNode.getAttribute('disabled');if(isDisabled){return true;}
if(inherited){var domNode=domNode.parentNode;return(domNode!=dojo.body())?this.isDisabled(domNode,true):null;}},centerOn:function(what,where,xRatio,yRatio){var whatDomNode=this.getDomNode(what);var whereDomNode=where?this.getDomNode(where):whatDomNode.parentNode;var viewport=dojo.coords(whereDomNode);var mb=dojo.marginBox(whatDomNode);var result={};var style=whatDomNode.style;var whereposition=whereDomNode.style.position;var deltax=viewport.l;var deltay=viewport.t;var onlyX,onlyY;xRatio=xRatio||0;yRatio=yRatio||0;if(xRatio===true){onlyX=true;}
if(yRatio===true){onlyY=true}
if(!onlyY){style.left=Math.floor((deltax+(viewport.w-mb.w)*(1+xRatio)/2))+"px";}
if(!onlyX){style.top=Math.floor((deltay+(viewport.h-mb.h)*(1+yRatio)/2))+"px";}},sizedOn:function(what,where){var whatDomNode=this.getDomNode(what);var whereDomNode=where?this.getDomNode(where):whatDomNode.parentNode;wherecoords=dojo.coords(whereDomNode);if(what.sourceNode){if(what.sourceNode.widget&&what.sourceNode.widget.resize()){what.sourceNode.widget.resize(wherecoords);}else{for(var s in{'height':null,'width':null,'top':null,'left':null,'right':null,'bottom':null}){whatDomNode.style[s]=whereDomNode.style[s];}}}},makeHiderLayer:function(parentId,kw){var rootNode;var message=objectPop(kw,'message');var messageArgs=objectExtract(kw,'message_*');if(typeof(parentId)=='string'){rootNode=parentId?genro.nodeById(parentId):genro.src.getNode();}else{rootNode=parentId;parentId=rootNode.getStringId();}
var default_kw={'position':'absolute',top:'0',left:'0',right:'0','bottom':0,z_index:399,background_color:'rgba(255,255,255,0.5)',id:parentId+'_hider',connect_ondblclick:function(evt){if(evt.shiftKey){var sn=evt.target.sourceNode;while(sn.label!='hiderNode'){sn=sn.getParentNode();}
sn.getParentNode().getValue().popNode('hiderNode');}}};var kw=objectUpdate(default_kw,kw);var hider=rootNode._('div','hiderNode',kw).getParentNode();if(message){messageArgs=objectNotEmpty(messageArgs)?messageArgs:{_class:'hiderMessage'};var button=objectPop(kw,'button');if(button){messageArgs['connect_onclick']=button;messageArgs['cursor']='pointer';}
messageArgs.innerHTML=message;var t=hider._('table',{'height':'100%',width:'100%',border:0})._('tbody');t._('tr',{'height':'100%'})._('td',{'height':'100%',width:'100%',text_align:'center'})._('div',messageArgs);}
return hider;},isWindowVisible:function(){if(genro.parentIframeSourceNode){return window.parent.genro.dom.isVisible(genro.parentIframeSourceNode);}
return true;},isVisible:function(what){what=this.getDomNode(what);if(what){var cs=dojo.getComputedStyle(what);if(!cs||cs.display=='none'||cs.visibility=='hidden'){return false;}
if(what.clientHeight==0||what.clientWidth==0){return false;}
return this.isWindowVisible();}
return false;},isActiveLayer:function(what){var sourceNode=this.getSourceNode(this.getDomNode(what));return genro.dialogStack.length===0||sourceNode.isChildOf(genro.dialogStack.slice(-1)[0].sourceNode);},setAutoSizer:function(sourceNode,domNode,cb,timing){sourceNode._autoSizer=setInterval(function(){if((domNode.clientHeight!=sourceNode._current_height)||(domNode.clientWidth!=sourceNode._current_width)){sourceNode._current_height=domNode.clientHeight;sourceNode._current_width=domNode.clientWidth;cb(sourceNode._current_width,sourceNode._current_height);}},timing||50);},resetAutoSizer:function(sourceNode){sourceNode._current_width=null;},autoSize:function(widget){var box;var maxHeight=0;var maxWidth=0;dojo.forEach(widget.getChildren(),function(child){box=child.containerNode.firstChild;maxHeight=Math.max(box.clientHeight,maxHeight);maxWidth=Math.max(box.clientWidth,maxWidth);});widget.resize({h:maxHeight+27,w:maxWidth+3});},preventGestureBackForward:function(pane){var pane=pane||window;var filterEvent=function(e,delta_x){if(delta_x){if(e.target.scrollLeft==0&&delta_x<0){e.preventDefault();e.stopPropagation();return false;}
else if(e.target.scrollRight==0&&delta_x>0){e.preventDefault();e.stopPropagation();return false;}}
return true;}
pane.addEventListener('DOMMouseScroll',function(e){if(e.axis==e.HORIZONTAL_AXIS){return filterEvent(e,e.detail);}});},setRootStyle:function(rs){if(rs instanceof gnr.GnrBag){var mw=dojo.byId('mainWindow');mw.style.cssText=objectAsStyle(genro.dom.getStyleDict(rs.asDict(),{}));}},printElementContent:function(where,title,doprint){var where=this.getDomNode(where);var title=title||'Print'
var coords=dojo.coords(where);var disp_setting="toolbar=yes,location=no,";disp_setting+="directories=yes,menubar=yes,";disp_setting+="scrollbars=yes,width="+coords.w+10+", height="+coords.h+10+", left=100, top=25";var content_vlue=where.innerHTML;var docprint=window.open("","",disp_setting);docprint.document.open();docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');docprint.document.write('<head><title>'+title+'</title>');docprint.document.write('<style type="text/css">body{ margin:0px;');docprint.document.write('font-family:verdana,Arial;color:#000;');docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}');docprint.document.write('a{color:#000;text-decoration:none;} </style>');docprint.document.write('</head><body onLoad="setTimeout(function(){window.print()},100);"><div style="margin:5px">');docprint.document.write(content_vlue);docprint.document.write('</div></body></html>');docprint.document.close();docprint.focus();},windowMessage:function(w,message){if(w=='parent'){w=window.parent;}
w.postMessage(message,'*');},htmlToCanvas:function(where,kw){if(!window.html2canvas){genro.dom.loadJs('/_rsrc/js_libs/html2canvas.js',function(){genro.dom.htmlToCanvas(where,kw);});return;}
var domNode=this.getDomNode(where);var onrendered=kw.cb;var uploadPath=kw.uploadPath;var sendPars=objectPop(kw,'sendPars');var uploaderId;if(sendPars){uploaderId=objectPop(sendPars,'uploaderId');}
if(uploadPath||sendPars){onrendered=function(canvas){var data;if(kw.crop){var crop=kw.crop;var tempcanvas=document.createElement('canvas');var ctxDest=tempcanvas.getContext("2d");tempcanvas.width=crop.deltaX;tempcanvas.height=crop.deltaY;ctxDest.drawImage(canvas,crop.x,crop.y,crop.deltaX,crop.deltaY,0,0,crop.deltaX,crop.deltaY);canvas=tempcanvas;}
data=canvas.toDataURL("image/png");if(typeof(sendPars)=='function'){return sendPars(data,canvas);}
genro.dlg.prompt('Upload screenshot',{cancelCb:kw.onResult,widget:function(center){var preview=center._('div',{margin:'2px',height:'150px',border:'1px solid silver',overflow:'auto',onCreated:function(domnode){dojo.style(canvas,{zoom:'.5'})
domnode.appendChild(canvas)}})
var fb=genro.dev.formbuilder(center,1,{border_spacing:'4px',width:'100%',fld_width:'100%'});fb.addField('textbox',{lbl_color:'#666',lbl_text_align:'right',lbl:'Name',value:'^.filename'});},action:function(result){var filename=result.getItem('filename');filename=(filename||'img_'+genro.getCounter())+'.png';sendKw={uploadPath:uploadPath,uploaderId:uploaderId,onResult:function(result){var url=this.responseText;if(kw.onResult){kw.onResult(result);}}}
sendKw.filename=filename;genro.rpc.uploadMultipart_oneFile(data,sendPars,sendKw);}})}}
html2canvas(domNode,{onrendered:function(canvas){onrendered(canvas);}});},autoScaleWrapper:function(newobj,zoomToFit){var zoomEnvelope=document.createElement('div');zoomEnvelope.style.display='inline-block';newobj.appendChild(zoomEnvelope);this.setAutoScale(zoomEnvelope,zoomToFit);return zoomEnvelope;},setAutoScale:function(domNode,zoomToFit,originalDomnode){domNode._autoScale=setInterval(function(){originalDomnode=originalDomnode||domNode.parentNode;var zoom_x=1;var zoom_y=1;var delta_x=0;var delta_y=0;if(zoomToFit===true||zoomToFit=='x'){delta_x=domNode.clientWidth-originalDomnode.clientWidth;}
if(zoomToFit===true||zoomToFit=='y'){delta_y=domNode.clientHeight-originalDomnode.clientHeight;}
if(delta_x>0){zoom_x=originalDomnode.clientWidth/domNode.clientWidth;}
if(delta_y>0){zoom_y=originalDomnode.clientHeight/domNode.clientHeight;}
if(zoomToFit===true){zoom_x=Math.min(zoom_x,zoom_y);zoom_y=zoom_x;}
domNode.style.transform="scale("+zoom_x+","+zoom_y+")";domNode.style.transformOrigin='0';},50);},setEventListener:function(domNode,evtname,cb,capture,code){code=code||evtname;var oldlistener=domNode['_listener_'+code];if(oldlistener){domNode.removeEventListener(evtname,oldlistener[0],oldlistener[1]);}
domNode['_listener_'+code]=[cb,capture];domNode.addEventListener(evtname,cb,capture);},styleSheetExpandedList:function(styleSheet){var result=[];dojo.forEach(styleSheet.cssRules,function(cr){if(cr instanceof CSSStyleRule){result.push(cr.cssText);}else if(cr instanceof CSSImportRule){result=result.concat(genro.dom.styleSheetExpandedList(cr.styleSheet));}});return result;},cssRulesToText:function(){var result=[];dojo.forEach(document.styleSheets,function(ss){result=result.concat(genro.dom.styleSheetExpandedList(ss));});return result.join('\n');},exportNodeAsPdf:function(nodeIds,kw){kw=kw||{}
kw.style=this.cssRulesToText();var extrastyles=objectPop(kw,'extrastyles');if(extrastyles){kw.style+=('\n'+extrastyles);}
nodeIds=typeof(nodeIds)=='string'?nodeIds.split(','):nodeIds;kw.pages=nodeIds.map(function(n){return genro.dom.getDomNode(n).innerHTML;})
genro.serverCall('utils.exportPdfFromNodes',kw);},detectPdfViewer:function(src,jsPdfViewer){var folderUrl=genro.getData('gnr.homeFolder');var parsedFolder=parseURL(folderUrl)||{};var parsedSrc=parseURL(src);var jsPdfViewer=isNullOrBlank(jsPdfViewer)?genro.getData('gnr.app_preference.sys.jsPdfViewer'):jsPdfViewer;if(parsedSrc.file&&stringEndsWith(parsedSrc.file,'.pdf')&&(genro.isMobile||jsPdfViewer||window.electron)){if(parsedFolder.host==parsedSrc.host&&parsedSrc.protocol!=parsedFolder.protocol){src=parsedFolder.protocol+'://'+parsedSrc.host+parsedSrc.relative;}
src='/_rsrc/js_libs/pdfjs/web/viewer.html?file='+encodeURIComponent(src);}
return src;},styleFields:function(parent,kw){var whitelist=kw.whitelist||[];var blacklist=kw.blacklist||[];var prefix=kw.prefix||'';var fb=kw.parentFb?parent:genro.dev.formbuilder(parent,1,{border_spacing:'6px'});var stylefield=function(tag,pars){var f=objectPop(pars,'field');if(blacklist.indexOf(f)>=0){return;}
if(whitelist.length==0||whitelist.indexOf(f)>=0){f=prefix+f;pars.value='^.'+f;fb.addField(tag,pars);}}
stylefield('textbox',{lbl:_T('Height'),field:'height'});stylefield('textbox',{lbl:_T('Width'),field:'width'});stylefield('textbox',{lbl:_T('Border'),field:'border'});stylefield('colorTextBox',{lbl:_T("Background"),field:'background',width:'10em',mode:'rgba'});stylefield('colorTextBox',{lbl:_T("Color"),field:'color',width:'10em'});stylefield('textbox',{lbl:_T('Font size'),field:'font_size'});stylefield('filteringSelect',{lbl:_T('Font style'),field:'font_style',values:'italic,underline'});stylefield('filteringSelect',{lbl:_T('Font weight'),field:'font_weight',values:'bold,bolder'});stylefield('textbox',{lbl:_T('Font variant'),field:'font_variant'});stylefield('textbox',{lbl:_T('Font family'),field:'font_family'});},editableStyles:['height','width','border','background','color','font_size','font_style','font_weight','font_variant','font_family']});



dojo.declare("gnr.widgets.GoogleLoader",null,{geocoder:{module_name:'maps',other_params:"sensor=false",version:'3.26',language:navigator.language},constructor:function(application){this.pending_commands=[];this.ready=true;var that=this;if(!window.google){this.ready=false;genro.dom.loadJs("https://www.google.com/jsapi",function(){that.ready=true;dojo.forEach(that.pending_commands,function(cb){cb.call(that);});that.pending_commands=[];});}},runCommand:function(module,cb){var that=this;if(!this.ready){this.pending_commands.push(function(){that.runCommand(module,cb);});return;}
var handler=google[module.module_name];if(handler&&handler._loaded){cb.call(this);}
else if('pending_calls'in module){module.pending_calls.push(cb);}
else{var kw=objectUpdate({},module);var pending_calls=[cb];module.pending_calls=pending_calls;var module_name=objectPop(kw,'module_name');var version=objectPop(kw,'version');kw.callback=function(){handler=google[module_name];handler._loaded=true;dojo.forEach(pending_calls,function(cb){cb.call(that);});};google.load(module_name,version,kw);}},setGeocoder:function(widget,cb){var obj=widget;if(this._mapkey){this.geocoder.other_params+=('&key='+this._mapkey);}
this.runCommand(this.geocoder,function(){obj.geocoder=new google.maps.Geocoder();if(cb){cb();}});}});dojo.declare("gnr.widgets.codemirror",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},getAddOnDict:function(key){return{search:{command:'find',js:['addon/search/search.js','addon/search/searchcursor.js','addon/dialog/dialog.js'],css:['addon/dialog/dialog.css'],},lint:{command:'lint',js:['//ajax.aspnetcdn.com/ajax/jshint/r07/jshint.js','addon/lint/lint.js','addon/lint/javascript-lint.js'],css:['addon/lint/lint.css'],}}[key];},creating:function(attributes,sourceNode){var cmAttrs=objectExtract(attributes,'config_*');var readOnly=objectPop(attributes,'readOnly');var lineWrapping=objectPop(attributes,'lineWrapping');if(readOnly){cmAttrs.readOnly=readOnly;}
if(lineWrapping){cmAttrs.lineWrapping=lineWrapping;}
cmAttrs.value=objectPop(attributes,'value')||'';return{cmAttrs:cmAttrs}},created:function(widget,savedAttrs,sourceNode){var that=this;var cmAttrs=objectPop(savedAttrs,'cmAttrs');var mode=cmAttrs.mode;var theme=cmAttrs.theme;var addon=cmAttrs.addon;if(addon){addon=addon.split(',');}
var cb=function(){that.load_mode(mode,function(){if(theme){that.load_theme(theme,function(){that.initialize(widget,cmAttrs,sourceNode)})}
else{that.initialize(widget,cmAttrs,sourceNode);}});if(addon){addon.forEach(function(addon){that.load_addon(addon)})}}
if(!window.CodeMirror){this.loadCodeMirror(cb);}else{cb();}},loadCodeMirror:function(cb){var urlist=['/_rsrc/js_libs/codemirror/lib/codemirror.js','/_rsrc/js_libs/codemirror/lib/codemirror.css'];genro.dom.addHeaders(urlist,function(){genro.dom.loadJs('/_rsrc/js_libs/codemirror/addon/mode/overlay.js',cb);});},defineKeyMap:function(name,keyMap){CodeMirror.keyMap[name]=objectUpdate(keyMap,CodeMirror.keyMap['default']);},initialize:function(widget,cmAttrs,sourceNode){this.defineKeyMap('softTab',{'Tab':function(cm){var spaces=Array(cm.getOption("indentUnit")+1).join(" ");cm.replaceSelection(spaces);}});dojo.style(widget,{position:'relative'})
var cm=CodeMirror(widget,cmAttrs);dojo.style(widget.firstChild,{height:'inherit',top:0,left:0,right:0,bottom:0,position:'absolute'})
cm.refresh();cm.sourceNode=sourceNode;cm.gnr=this;sourceNode.externalWidget=cm;for(var prop in this){if(prop.indexOf('mixin_')==0){cm[prop.replace('mixin_','')]=this[prop];}}
cm.on('update',function(){sourceNode.delayedCall(function(){var v=sourceNode.externalWidget.getValue();sourceNode.setRelativeData(sourceNode.attr.value,v,null,null,sourceNode);},sourceNode.attr._delay||500,'updatingContent')})},load_theme:function(theme,cb){genro.dom.loadCss('/_rsrc/js_libs/codemirror/theme/'+theme+'.css','codemirror_'+theme,cb);},load_addon:function(addon,cb){var that=this;var addondict=this.getAddOnDict(addon);if(!CodeMirror.commands[addondict.command]){addondict.js.forEach(function(path){if(path[0]=='/'){genro.dom.loadJs(path);}else{genro.dom.loadJs('/_rsrc/js_libs/codemirror/'+path);}})
addondict.css.forEach(function(path){genro.dom.loadCss('/_rsrc/js_libs/codemirror/'+path);})}},load_mode:function(mode,cb){var that=this;if(!(mode in CodeMirror.modes)){genro.dom.loadJs('/_rsrc/js_libs/codemirror/mode/'+mode+'/'+mode+'.js',function(){if(CodeMirror.modes[mode].dependencies){var i=0;CodeMirror.modes[mode].dependencies.forEach(function(dep){i++;if(CodeMirror.modes[mode].dependencies.length==i){that.load_mode(dep,function(){setTimeout(function(){cb()},10);});}else{that.load_mode(dep);}});}
else if(cb){cb()}});}
else if(cb){cb();}},mixin_gnr_value:function(value,kw,trigger_reason){this.setValue(value||'');var that=this;var sourceNode=this.sourceNode;sourceNode.watch('isVisible',function(){return genro.dom.isVisible(sourceNode);},function(){that.refresh();});},mixin_gnr_setDisabled:function(disabled){genro.dom.setDomNodeDisabled(this.sourceNode.domNode,disabled);this.gnr_readOnly(disabled);},mixin_gnr_readOnly:function(value,kw,trigger_reason){this.setOption('readOnly',value?'nocursor':false);},mixin_gnr_lineWrapping:function(value,kw,trigger_reason){this.setOption('lineWrapping',value);},mixin_gnr_quoteSelection:function(startchunk,endchunk){endchunk=endchunk||startchunk;var oldtxt=this.doc.getSelection();var newtxt=startchunk+oldtxt+endchunk;this.doc.replaceSelection(newtxt);}});dojo.declare("gnr.widgets.chartjs",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='canvas';},creating:function(attributes,sourceNode){sourceNode.registerDynAttr('storepath');var savedAttrs=objectExtract(attributes,'chartType,filter,datasets,captionField,options,data,scalesBag,onClick');return savedAttrs;},created:function(domNode,savedAttrs,sourceNode){var data=savedAttrs.data;var dataset=savedAttrs.dataset;var filter=savedAttrs.filter;var captionField=savedAttrs.captionField;var options=savedAttrs.options||{maintainAspectRatio:false};if(savedAttrs.onClick){options.onClick=funcCreate(savedAttrs.onClick,'event,elements',sourceNode);}
var chartType=savedAttrs.chartType;var scalesBag=savedAttrs.scalesBag;var scalesOpt;var that=this;dojo.connect(sourceNode,'_onDeleting',function(){});if(scalesBag){if(scalesBag){scalesOpt=scalesBag.asDict(true,true);objectPop(scalesOpt,'radiant');if(objectNotEmpty(scalesOpt)){options.scales=scalesOpt;}else{scalesOpt=false;}}}
sourceNode.freeze();var cb=function(){sourceNode.unfreeze(true);var chartjs=new Chart(domNode,{'type':chartType,options:options});sourceNode.externalWidget=chartjs;chartjs.sourceNode=sourceNode;chartjs.gnr=that;for(var prop in that){if(prop.indexOf('mixin_')===0){chartjs[prop.replace('mixin_','')]=that[prop];}}
sourceNode.publish('chartReady');if(sourceNode.attr.optionsBag){var optionsBag=sourceNode.getAttributeFromDatasource('optionsBag');if(optionsBag&&optionsBag.getNodeByAttr('_userChanged')){optionsBag.walk(function(n){if(n.attr._userChanged){n.setValue(n._value);}});}else{sourceNode.setAttributeInDatasource('optionsBag',new gnr.GnrBag(chartjs.options));}
if(!scalesOpt){sourceNode.setAttributeInDatasource('scalesBag',new gnr.GnrBag(chartjs.options.scales));}}
chartjs.gnr_updateChart();};if(!window.Chart){var url='/_rsrc/js_libs/Chart.js';genro.dom.loadJs(url,function(){genro.setData('gnr.chartjs.defaults',new gnr.GnrBag(Chart.defaults));cb();});}else{setTimeout(cb,1);}},autoColors:function(dataset){var colorParNames=['backgroundColor:0.7','borderColor:1','pointBackgroundColor:1','pointBorderColor:1'];var result={};colorParNames.forEach(function(n){n=n.split(':');if(dataset[n[0]]=='*'){dataset[n[0]]=[];result[n[0]]=n[1];}});return result;},makeDataset:function(kw){var field=objectPop(kw,'field');var dataset=objectUpdate({data:[]},kw.pars);var autoColorsDict=this.autoColors(dataset);objectPop(dataset,'enabled');var idx=0;var k;var caption;var isBagMode=kw.datamode=='bag';kw.rows.walk(function(n){if('pageIdx'in n.attr){return;}
var row=isBagMode?n.getValue('static').asDict():n.attr;var pkey=row._pkey||n.label;if(kw.filterCb(pkey,row)){var chart_row_pars=objectExtract(row,'chart_*');caption=row[kw.captionField]||(dataset.label||field)+' '+idx;if('labels'in kw){kw.labels.push(caption);}
dataset.data.push(row[field]);var autocol=chroma(stringToColour(caption));for(k in autoColorsDict){dataset[k].push(chroma(autocol).alpha(autoColorsDict[k]).css());}
for(k in chart_row_pars){if(isNullOrBlank(dataset[k])){dataset[k]=[];}
if(dataset[k]instanceof Array){dataset[k].push(chart_row_pars[k]);}}
idx++;}
return'__continue__';},'static',null,isBagMode);return dataset;},mixin_gnr_updateChart:function(){if(this.sourceNode.isFreezed()){return;}
var that=this;this.sourceNode.delayedCall(function(){var data=that.sourceNode.getAttributeFromDatasource('data');if(!data){var rows=that.sourceNode.getRelativeData(that.sourceNode.attr.storepath);var filter=that.sourceNode.getAttributeFromDatasource('filter');var datasets=that.sourceNode.getAttributeFromDatasource('datasets');var captionField=that.sourceNode.getAttributeFromDatasource('captionField');var filterCb;if(typeof(filter)=='string'){filter=filter.split(',');}
if(typeof(filter)!='function'){filterCb=filter?function(pkey,row){return filter.length===0||filter.indexOf(pkey)>=0;}:function(){return true;};}else{filterCb=filter;}
var attrs,dslabel,dsfield;var datamode=that.sourceNode.attr.datamode||'attr';data={labels:[],datasets:[]};var dskw={'rows':rows,'datamode':datamode,'filterCb':filterCb,'labels':data.labels,'captionField':captionField};if(datasets){datasets._nodes.forEach(function(n){var v=n.getValue();if(!(v.getNode('enabled'))||v.getItem('enabled')){dskw.pars=v.getItem('parameters').asDict(true,true);dskw.pars.type=v.getItem('chartType');dskw.field=v.getItem('field');data.datasets.push(that.gnr.makeDataset(dskw));objectPop(dskw,'labels');}});}}
objectUpdate(that.data,data);that.update();that.resize();},1,'updateChart');},mixin_gnr_storepath:function(value,kw,trigger_reason){this.gnr_updateChart();},mixin_gnr_chartType:function(value,kw,trigger_reason){if(this.sourceNode.isFreezed()){return;}
this.sourceNode.rebuild();},mixin_gnr_datasets:function(value,kw,trigger_reason){if(kw.node.label=='xAxisID'||kw.node.label=='yAxisID'){var axes=kw.node.label=='xAxisID'?'xAxes':'yAxes';var axeslist=this.options.scales[axes];if(!axeslist.some(function(n){return n.id==value;})){this.sourceNode.publish('addAxis',{axes:axes,id:kw.value});return;}}
this.gnr_updateChart();},mixin_gnr_filter:function(value,kw,trigger_reason){this.gnr_updateChart();},mixin_gnr_captionField:function(value,kw,trigger_reason){this.gnr_updateChart();},mixin_gnr_scalesBag:function(value,kw,trigger_reason){var scalesBag=this.sourceNode.getAttributeFromDatasource('scalesBag');if(kw.node._id==scalesBag.getParentNode()._id){return;}
this.gnr_updateOptionsObject(kw.node,this.options.scales,scalesBag);},mixin_gnr_optionsBag:function(value,kw,trigger_reason){var optionsBag=this.sourceNode.getAttributeFromDatasource('optionsBag');if(kw.node._id==optionsBag.getParentNode()._id){return;}
this.gnr_updateOptionsObject(kw.node,this.options,optionsBag);},mixin_gnr_updateOptionsObject:function(triggerNode,curr,optionsBagChunk){var optpath=triggerNode.getFullpath(null,optionsBagChunk);var currOptionBag=optionsBagChunk;var node,val;var optlist=optpath.split('.');var lastLabel=optlist.pop();var k;optlist.forEach(function(chunk){node=currOptionBag.getNode(chunk);if(node.attr._autolist){k=currOptionBag.index(chunk);if(isNullOrBlank(curr[k])){curr[k]={};}
curr=curr[k];}else{if(!(chunk in curr)){curr[chunk]={};}
curr=curr[chunk];}
currOptionBag=node.getValue();});var lastValue=currOptionBag.getItem(lastLabel);lastValue=lastValue instanceof gnr.GnrBag?lastValue.asDict(true,true):lastValue;if(curr instanceof Array){var lastIdx=currOptionBag.index(lastLabel);if(curr.length>lastIdx){curr[lastIdx]=lastValue;}else{curr.push(lastValue);}}
if(curr[lastLabel]!=lastValue){triggerNode.attr._userChanged=true;curr[lastLabel]=lastValue;}
if(this.sourceNode.isFreezed()){return;}
this.update();this.resize();}});dojo.declare("gnr.widgets.dygraph",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'data,options,columns');return savedAttrs;},created:function(domNode,savedAttrs,sourceNode){var dygraph_root=document.createElement('div');domNode.appendChild(dygraph_root);var data=savedAttrs.data;var options=savedAttrs.options;if(options instanceof gnr.GnrBag){options=options.asDict(true);}
if(sourceNode.attr.title){options.title=options.title||sourceNode.attr.title;}
if(sourceNode.attr.detachable){options.title=options.title||'Untiled Graph';}
if(data instanceof gnr.GnrBag){sourceNode.labelKeys=sourceNode.labelKeys||savedAttrs.columns.split(',');data=this.getDataFromBag(sourceNode,data);}
var that=this;var cb=function(){sourceNode._current_height=domNode.clientHeight;sourceNode._current_width=domNode.clientWidth;options.height=sourceNode._current_height;options.width=sourceNode._current_width;var dygraph=new Dygraph(dygraph_root,data,options);sourceNode.externalWidget=dygraph;dygraph.sourceNode=sourceNode;dygraph.gnr=that;for(var prop in that){if(prop.indexOf('mixin_')===0){dygraph[prop.replace('mixin_','')]=that[prop];}}
genro.dom.setAutoSizer(sourceNode,domNode,function(w,h){dygraph.resize(w,h);});};if(!window.Dygraph){genro.dom.loadJs('/_rsrc/js_libs/dygraph-combined.js',cb);}else{setTimeout(cb,1);}},getDataFromBag:function(sourceNode,data){var result=[];var labelKeys=sourceNode.labelKeys;var datagetter=function(n,l){return n.attr[l];};if(data.getItem('#0')){datagetter=function(n,l){return n._value.getItem(l);};}
data.forEach(function(n){var row=[];labelKeys.forEach(function(l){row.push(datagetter(n,l));});result.push(row);});return result;},mixin_gnr_columns:function(value,kw,trigger_reason){this.sourceNode.labelKeys=value.split(',');this.sourceNode.rebuild();},mixin_gnr_data:function(value,kw,trigger_reason){var data=this.sourceNode.getAttributeFromDatasource('data');if(data instanceof gnr.GnrBag){data=this.gnr.getDataFromBag(this.sourceNode,data);}
this.updateOptions({'file':data});},mixin_gnr_options:function(options,kw,trigger_reason){options=this.sourceNode.getAttributeFromDatasource('options');if(options instanceof gnr.GnrBag){options=options.asDict(true);}
this.updateOptions(options);}});dojo.declare("gnr.widgets.CkEditor",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},toolbar_dict:{'simple':[['Source','-','Bold','Italic','-','NumberedList','BulletedList','-','Image','Table','HorizontalRule','PageBreak'],['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],['Styles','Format','Font','FontSize','TextColor','BGColor']],'standard':[['Source','-','Bold','Italic','-','NumberedList','BulletedList','-','Link','Unlink','-','Templates'],['Image','Table','HorizontalRule','PageBreak'],['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],['Styles','Format','Font','FontSize'],['TextColor','BGColor'],['Maximize','ShowBlocks']]},creating:function(attributes,sourceNode){attributes.id=attributes.id||'ckedit_'+sourceNode.getStringId();var toolbar=objectPop(attributes,'toolbar');var config=objectExtract(attributes,'config_*');var stylesheet=objectPop(attributes,'stylesheet');var customStyles=objectPop(attributes,'customStyles');var contentsCss=objectPop(attributes,'contentsCss');if(stylesheet){config.extraPlugins='stylesheetparser';config.contentsCss=stylesheet;}
if(customStyles){var l=[];customStyles.forEach(function(n){l.push({name:n.name,element:n.element,styles:objectFromStyle(n.styles),attributes:objectFromStyle(n.attributes)});})
customStyles=l;}
var showtoolbar=true;if(toolbar===false){toolbar=[];showtoolbar=false;}
if(typeof(toolbar)=='string'){if(toolbar in this.toolbar_dict){toolbar=this.toolbar_dict[toolbar];}else{toolbar=genro.evaluate(toolbar);}};if(toolbar){config.toolbar='custom';config.toolbar_custom=toolbar;};var savedAttrs={'config':config,showtoolbar:showtoolbar,enterMode:objectPop(attributes,'enterMode'),bodyStyle:objectPop(attributes,'bodyStyle',{margin:'2px'})};savedAttrs.customStyles=customStyles;savedAttrs.contentsCss=contentsCss;savedAttrs.constrainAttr=objectExtract(attributes,'constrain_*')
return savedAttrs;},dialog_tableProperties:function(definition,ckeditor){this.dialog_table(definition,ckeditor);},dialog_table:function(definition,ckeditor){definition.getContents('info').get('txtBorder')['default']=null;definition.getContents('advanced').get('advStyles')['default']='border-collapse:collapse;';definition.addContents({id:'gnr_tableProperties',label:'Genropy',accessKey:'G',elements:[{id:'row_datasource',type:'text',label:'Row Datasource',setup:function(i){this.setValue(i.getAttribute('row_datasource')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('row_datasource',this.getValue());else j.removeAttribute('row_datasource');}},{id:'row_condition',type:'text',label:'Row Condition',setup:function(i){this.setValue(i.getAttribute('row_condition')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('row_condition',this.getValue());else j.removeAttribute('row_condition');}},{id:'row_sort',type:'text',label:'Row Sort',setup:function(i){this.setValue(i.getAttribute('row_sort')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('row_sort',this.getValue());else j.removeAttribute('row_sort');}}]});},mixin_gnr_constrain_height:function(height,kw,trigger_reason){this.document.getBody()['$'].style.height=height;},mixin_gnr_constrain_width:function(width,kw,trigger_reason){this.document.getBody()['$'].style.width=width;},mixin_gnr_assignConstrain:function(){var that=this;this.sourceNode.watch('hasDocument',function(){return that.document;},function(){var constrainAttr=objectExtract(that.sourceNode.attr,'constrain_*',true);constrainAttr=that.sourceNode.evaluateOnNode(constrainAttr);var b=that.document.getBody()['$'];b.style.cssText=objectAsStyle(objectUpdate(objectFromStyle(b.style.cssText),genro.dom.getStyleDict(constrainAttr)));});},makeEditor:function(widget,savedAttrs,sourceNode){var showtoolbar=objectPop(savedAttrs,'showtoolbar');var enterMode=objectPop(savedAttrs,'enterMode')||'div';var bodyStyle=objectPop(savedAttrs,'bodyStyle');var enterModeDict={'div':CKEDITOR.ENTER_DIV,'p':CKEDITOR.ENTER_P,'br':CKEDITOR.ENTER_BR};if(showtoolbar===false){objectUpdate(savedAttrs.config,{toolbar:'Custom',toolbarStartupExpanded:false,toolbarCanCollapse:false,toolbar_Custom:''});}
if(savedAttrs.customStyles){var csname='customStyles_'+sourceNode.getStringId();CKEDITOR.stylesSet.add(csname,savedAttrs.customStyles);savedAttrs.config.stylesSet=csname}
savedAttrs.config.enterMode=enterModeDict[enterMode];if(savedAttrs.contentsCss){var currlst=CKEDITOR.config.contentsCss;if(typeof(currlst)=='string'){currlst=currlst.split(',')}
savedAttrs.config.contentsCss=currlst.concat(savedAttrs.contentsCss.split(','));}
CKEDITOR.replace(widget,savedAttrs.config);var ckeditor_id='ckedit_'+sourceNode.getStringId();var ckeditor=CKEDITOR.instances[ckeditor_id];sourceNode.externalWidget=ckeditor;ckeditor.sourceNode=sourceNode;ckeditor.gnr=this;for(var prop in this){if(prop.indexOf('mixin_')==0){ckeditor[prop.replace('mixin_','')]=this[prop];}}
ckeditor.gnr_getFromDatastore();var parentWidget=dijit.getEnclosingWidget(widget);ckeditor.gnr_readOnly('auto');var parentDomNode=sourceNode.getParentNode().getDomNode();ckeditor.on('currentInstance',function(ev){console.log('currentInstance',constrainAttr);});var cbResize=function(){sourceNode._rsz=null;try{ckeditor.gnr_assignConstrain();ckeditor.resize(parentDomNode.clientWidth,parentDomNode.clientHeight);}catch(e){}};ckeditor.on('instanceReady',function(ev){var editor=ev.editor;editor.gnr_assignConstrain();var dropHandler=function(evt){setTimeout(function(){ckeditor.gnr_setInDatastore();},1);};if(editor.document.$.addEventListener){editor.document.$.addEventListener('drop',dropHandler,true);}else if(editor.document.$.attachEvent){editor.document.$.attachEvent('ondrop',dropHandler,true);}
editor.document.$.addEventListener('keydown',function(evt){ckeditor.lastKey=evt.keyCode;});if(sourceNode.attr.onStarted){funcApply(sourceNode.attr.onStarted,{editor:editor},sourceNode);}
cbResize();if(sourceNode.attr._inGridEditor){var that=this;setTimeout(function(){that.focus()},100);}});dojo.connect(parentWidget,'resize',function(){if(sourceNode._rsz){clearTimeout(sourceNode._rsz);}
sourceNode._rsz=setTimeout(cbResize,100);});var that=this;if(!CKEDITOR._dialog_patched){CKEDITOR.on('dialogDefinition',function(ev){if(that['dialog_'+ev.data.name]){that['dialog_'+ev.data.name].call(that,ev.data.definition);}});CKEDITOR._dialog_patched=true;}
var ckeditor=sourceNode.externalWidget;dojo.connect(ckeditor.focusManager,'blur',function(evt){ckeditor.gnr_setInDatastore();if(sourceNode.attr.connect_onBlur){if(ckeditor._blurTimeOut){clearTimeout(ckeditor._blurTimeOut)
ckeditor._blurTimeOut=null}
ckeditor._blurTimeOut=setTimeout(function(){if(sourceNode.attr._inGridEditor&&sourceNode.externalWidget.lastKey==9){sourceNode.externalWidget.cellNext='RIGHT';}
funcApply(sourceNode.attr.connect_onBlur,{evt:evt},sourceNode);clearTimeout(ckeditor._blurTimeOut)
ckeditor._blurTimeOut=null},200)}});dojo.connect(ckeditor.focusManager,'focus',function(evt){if(ckeditor._blurTimeOut){clearTimeout(ckeditor._blurTimeOut)
ckeditor._blurTimeOut=null}});dojo.connect(ckeditor.editor,'paste',ckeditor,'gnr_onPaste');ckeditor['on']('paste',function(e){var lastSelection=sourceNode.externalWidget.getSelection().getNative();var data=e.data.html||'';if(data[0]=='<'){var anchorNode=lastSelection.anchorNode;if(anchorNode.innerHTML=='<br>'){anchorNode.innerHTML='&nbsp;';var an=anchorNode.firstChild;lastSelection.anchorNode.parentNode.replaceChild(an,anchorNode);lastSelection.anchorNode=an;}}
genro.callAfter(function(){this.gnr_onTyped();this.gnr_setInDatastore();},1,this,'typing');})
ckeditor['on']('key',function(kw){if(!sourceNode.attr._inGridEditor){genro.callAfter(function(){this.gnr_onTyped();this.gnr_setInDatastore();},1000,this,'typing');}});return ckeditor;},onSpeechEnd:function(sourceNode,v){var lastSelection=sourceNode.externalWidget.getSelection().getNative();if(lastSelection){var oldValue=sourceNode.getAttributeFromDatasource('value')||'';var fistchunk=oldValue.slice(0,lastSelection.start);var secondchunk=oldValue.slice(lastSelection.end);v=fistchunk+v+secondchunk;}
setTimeout(function(){sourceNode.setAttributeInDatasource('value',v,true);},1);},created:function(widget,savedAttrs,sourceNode){var that=this;var cb=function(){that.makeEditor(widget,savedAttrs,sourceNode);sourceNode.publish('editorCreated');};if(!window.CKEDITOR){var suff=genro.newCkeditor?'_new':'';genro.dom.loadJs('/_rsrc/js_libs/ckeditor'+suff+'/ckeditor.js',function(){cb();});return;}
cb();},mixin_gnr_value:function(value,kw,reason){if(!this.focusManager.hasFocus){this.setData(value);}},mixin_gnr_getFromDatastore:function(){this.setData(this.sourceNode.getAttributeFromDatasource('value')||'');},mixin_gnr_setInDatastore:function(){var value=this.getData();if(this.sourceNode.getAttributeFromDatasource('value')!=value){this.sourceNode.setAttributeInDatasource('value',value);}},mixin_gnr_onPaste:function(){this.gnr_setInDatastore();},mixin_gnr_onTyped:function(){},mixin_gnr_setDisabled:function(disabled){this.gnr_setReadOnly(disabled);},mixin_gnr_highlightChild:function(idx){var cs=this.sourceNode.externalWidget.document.$.getElementById('customstyles');if(!cs){var cs=this.sourceNode.externalWidget.document.$.createElement('style');cs.setAttribute('id','customstyles');this.sourceNode.externalWidget.document.getHead().$.appendChild(cs)}
cs.textContent=idx>=0?"body>*:nth-child("+(idx+1)+"){background:yellow;}":"";if(idx>=0){var b=this.sourceNode.externalWidget.document.getBody().$;var higlightedNode=b.children[idx];var ht=higlightedNode.offsetTop;b.scrollTop=ht-100;}},mixin_gnr_cancelEvent:function(evt){evt.cancel();},mixin_gnr_readOnly:function(value,kw,reason){var value=(value!='auto')?value:this.sourceNode.getAttributeFromDatasource('readOnly');this.gnr_setReadOnly(value);},mixin_gnr_setReadOnly:function(isReadOnly){if(!this.document){return;}
CKEDITOR.env.ie?this.document.$.body.contentEditable=!isReadOnly:this.document.$.designMode=isReadOnly?"off":"on";this[isReadOnly?'on':'removeListener']('key',this.gnr_cancelEvent,null,null,0);this[isReadOnly?'on':'removeListener']('selectionChange',this.gnr_cancelEvent,null,null,0);var command,commands=this._.commands,mode=this.mode;for(var name in commands){command=commands[name];isReadOnly?command.disable():command[command.modes[mode]?'enable':'disable']();this[isReadOnly?'on':'removeListener']('state',this.gnr_cancelEvent,null,null,0);}}});



dojo.declare("gnr.GnrMobileHandler",null,{constructor:function(application){this.application=application;for(var k in this){if(stringStartsWith(k,'patch_')){this[k]();}}
this.initialize();},initialize:function(){dojo.addClass(document.body,'touchDevice');dojo.addClass(document.body,'bodySize_'+genro.deviceScreenSize);this.lastTouchEnd=0;document.addEventListener('touchend',function(event){var now=(new Date()).getTime();if(now-genro.mobile.lastTouchEnd<=300){event.preventDefault();}
genro.mobile.lastTouchEnd=now;},false);this.startHammer(document.body);document.body.onorientationchange=function(e){genro.setData('touch.orientation',window.orientation);};},startHammer:function(domNode){this.hammertime=new Hammer(domNode);this.hammertime.on('tap',function(ev){genro.mobile.handleMobileEvent(ev);});this.hammertime.on('doubletap',function(ev){genro.mobile.handleMobileEvent(ev);});this.hammertime.on('press',function(ev){genro.mobile.handleMobileEvent(ev);});this.hammertime.on('swipe',function(ev){genro.mobile.handleMobileEvent(ev);});},handleMobileEvent:function(ev){var info=genro.dom.getEventInfo(ev);if(!info||!info.sourceNode){return;}
info.sourceNode.publish(info.event.type,info);genro.publish('mobile_'+info.event.type,info);},touchEventString:function(e){var b='';for(var k in e){b=b+k+':'+e[k]+'<br/>';}
return b;},patch_splitter:function(){dojo.require("dijit.layout.BorderContainer");dojo.require("dijit.layout._LayoutWidget");dijit.layout._Splitter.prototype.templateString=dijit.layout._Splitter.prototype.templateString.replace('onmousedown','ontouchstart');dijit.layout._Splitter.prototype._startDrag=function(e){if(!this.cover){this.cover=dojo.doc.createElement('div');dojo.addClass(this.cover,"dijitSplitterCover");dojo.place(this.cover,this.child.domNode,"after");}else{this.cover.style.zIndex=1;}
if(this.fake){dojo._destroyElement(this.fake);}
if(!(this._resize=this.live)){(this.fake=this.domNode.cloneNode(true)).removeAttribute("id");dojo.addClass(this.domNode,"dijitSplitterShadow");dojo.place(this.fake,this.domNode,"after");}
dojo.addClass(this.domNode,"dijitSplitterActive");var factor=this._factor,max=this._maxSize,min=this._minSize||10;var axis=this.horizontal?"pageY":"pageX";var pageStart=e[axis];var splitterStyle=this.domNode.style;var dim=this.horizontal?'h':'w';var childStart=dojo.marginBox(this.child.domNode)[dim];var splitterStart=parseInt(this.domNode.style[this.region]);var resize=this._resize;var region=this.region;var mb={};var childNode=this.child.domNode;var layoutFunc=dojo.hitch(this.container,this.container._layoutChildren);var de=dojo.doc.body;this._handlers=(this._handlers||[]).concat([dojo.connect(de,"ontouchmove",this._drag=function(e,forceResize){var delta=e[axis]-pageStart,childSize=factor*delta+childStart,boundChildSize=Math.max(Math.min(childSize,max),min);if(resize||forceResize){mb[dim]=boundChildSize;dojo.marginBox(childNode,mb);layoutFunc(region);}
splitterStyle[region]=factor*delta+splitterStart+(boundChildSize-childSize)+"px";}),dojo.connect(de,"ontouchend",this,"_stopDrag")]);dojo.stopEvent(e);};},patch_moveable:function(){dojo.require("dojo.dnd.Moveable")
var pr=dojo.dnd.Moveable.prototype
pr._constructor=function(node,params){this.node=dojo.byId(node);if(!params){params={};}
this.handle=params.handle?dojo.byId(params.handle):null;if(!this.handle){this.handle=this.node;}
this.delay=params.delay>0?params.delay:0;this.skip=params.skip;this.mover=params.mover?params.mover:dojo.dnd.Mover;this.events=[dojo.connect(this.handle,"ontouchstart",this,"onMouseDown"),dojo.connect(this.handle,"ondragstart",this,"onSelectStart"),dojo.connect(this.handle,"onselectstart",this,"onSelectStart")];};pr.onMouseDown=function(e){if(this.skip&&dojo.dnd.isFormElement(e)){return;}
if(this.delay){this.events.push(dojo.connect(this.handle,"ontouchmove",this,"onMouseMove"));this.events.push(dojo.connect(this.handle,"ontouchend",this,"onMouseUp"));this._lastX=e.pageX;this._lastY=e.pageY;}else{new this.mover(this.node,e,this);}
if(e.type!='touchstart'){dojo.stopEvent(e);}};dojo.require("dojo.dnd.Mover");var pr=dojo.dnd.Mover.prototype
pr._constructor=function(node,e,host){this.node=dojo.byId(node);this.marginBox={l:e.pageX,t:e.pageY};this.mouseButton=e.button;var h=this.host=host,d=node.ownerDocument,firstEvent=dojo.connect(d,"ontouchmove",this,"onFirstMove");this.events=[dojo.connect(d,"ontouchmove",this,"onMouseMove"),dojo.connect(d,"ontouchend",this,"onMouseUp"),dojo.connect(d,"ondragstart",dojo,"stopEvent"),dojo.connect(d,"onselectstart",dojo,"stopEvent"),firstEvent];if(h&&h.onMoveStart){h.onMoveStart(this);}}}});



dojo.declare("gnr.GnrWebSocketHandler",null,{constructor:function(application,wsroot,options){this.application=application;this.wsroot=wsroot;this.url=(window.location.protocol=='https:'?'wss://':'ws://')+window.location.host+wsroot;this.options=objectUpdate({debug:false,reconnectInterval:4000,ping_time:1000},options);this.waitingCalls={};},create:function(){if(this.wsroot){this.socket=new ReconnectingWebSocket(this.url,null,this.options);var that=this;this.socket.onopen=function(){that.onopen();};this.socket.onclose=function(){that.onclose();};this.socket.onmessage=function(e){that.onmessage(e);};this.socket.onerror=function(error){that.onerror(error);};}},addhandler:function(name,cb){this[name]=cb;},onopen:function(){that=this;this.send('connected',{'page_id':genro.page_id});this._interval=setInterval(function(){genro.wsk.ping();},this.options.ping_time);},onclose:function(){clearInterval(this._interval);console.log('disconnected websocket');},onerror:function(error){console.error('WebSocket Error '+error);},ping:function(){this.send('ping',{lastEventAge:(new Date()-genro._lastUserEventTs)});},onmessage:function(e){var data=e.data;if(data=='pong'){return;}
if(data.indexOf('<?xml')==0){var result=this.parseResponse(e.data);var token=result.getItem('token')
if(token){this.receivedToken(token,result.getItem('envelope'))}else{this.receivedCommand(result.getItem('command'),result.getItem('data'))}}else{genro.publish('websocketMessage',data)}},receivedCommand:function(command,data){var handler;if(command){if(command.indexOf('.')>0){comlst=command.split('.')
handler=genro[comlst[0]]['do_'+comlst.splice(1).join('.')]}
else{handler=this['do_'+command]||this.do_publish}}else{handler=this.do_publish}
handler.apply(this,[data])},receivedToken:function(token,envelope){var deferred=objectPop(this.waitingCalls,token);envelope=envelope||new gnr.GnrBag();var dataNode=envelope.getNode('data');var error=envelope.getItem('error');if(error){deferred.callback({'error':error,'dataNode':dataNode});}
else{deferred.callback(dataNode);}},do_alert:function(data){alert(data)},do_set:function(data){var path=data.getItem('path')
var valueNode=data.getNode('data')
var fired=data.getItem('fired')
genro.setData(path,valueNode._value,valueNode.attr,true)
if(fired){genro.setData(path,null,null,false)}},do_setInClientData:function(data){var value=data.getItem('value');var attributes=data.getItem('attributes');if(attributes){attributes=attributes.asDict();}
var path=data.getItem('path');var reason=data.getItem('reason');var fired=data.getItem('fired');var nodeId=data.getItem('nodeId');var noTrigger=data.getItem('noTrigger');var root=nodeId?genro.nodeById(nodeId):genro.src.getNode();root.setRelativeData(path,value,attributes,fired,reason,null,noTrigger?{doTrigger:false}:null)},do_datachanges:function(datachanges){genro.rpc.setDatachangesInData(datachanges)},do_sharedObjectChange:function(data){var shared_id=data.getItem('shared_id');var path=data.getItem('path');var value=data.getItem('value');var attr=data.getItem('attr');var evt=data.getItem('evt');var from_page_id=data.getItem('from_page_id');var so=genro._sharedObjects[shared_id];if(!so){return;}
var sopath=so.path;var fullpath=path?sopath+'.'+path:sopath;if(evt=='del'){genro._data.popNode(fullpath,'serverChange')}else{genro._data.setItem(fullpath,value,attr,objectUpdate({'doTrigger':'serverChange',lazySet:true}));}},do_publish:function(data){var topic=data.getItem('topic')
var nodeId=data.pop('nodeId');var iframe=data.pop('iframe');var parent=data.pop('parent');if(!topic){topic='websocketMessage';}else{var data=data.getItem('data');if(data instanceof gnr.GnrBag){data=data.asDict();}}
if(nodeId||iframe||parent){topic={topic:topic,nodeId:nodeId,iframe:iframe,parent:parent};}
genro.publish(topic,data)},call:function(kw,omitSerialize,cb){var deferred=new dojo.Deferred();var kw=objectUpdate({},kw);var _onResult=objectPop(kw,'_onResult');var _onError=objectPop(kw,'_onError');var token='wstk_'+genro.getCounter('wstk');kw['result_token']=token;kw['command']=kw['command']||'call';if(!omitSerialize){kw=genro.rpc.serializeParameters(genro.src.dynamicParameters(kw));}
this.waitingCalls[token]=deferred;this.socket.send(dojo.toJson(kw));deferred.addCallback(function(result){if(result&&result.error){if(_onError){funcApply(_onError,{result:result});}else{console.error('WSK ERROR',result.error);genro.setData('gnr.wsk.lastErrorTraceback',result.dataNode);genro.dev.openBagInspector('gnr.wsk.lastErrorTraceback',{title:'WSK error'});}}
return result;});if(_onResult){deferred.addCallback(_onResult);}
return deferred;},send:function(command,kw){var kw=kw||{};kw['command']=command
kw=genro.rpc.serializeParameters(genro.src.dynamicParameters(kw));var msg=dojo.toJson(kw);this.socket.send(msg);},parseResponse:function(response){var result=new gnr.GnrBag();var parser=new window.DOMParser()
result.fromXmlDoc(parser.parseFromString(response,"text/xml"),genro.clsdict);return result},sendCommandToPage:function(page_id,command,data){var envelope=new gnr.GnrBag({'command':command,'data':data})
this.send('route',{'target_page_id':page_id,'envelope':envelope.toXml()})},setInClientData:function(page_id,path,data){this.sendCommandToPage(page_id,'set',new gnr.GnrBag({'data':data,'path':path}))},fireInClientData:function(page_id,path,data){this.sendCommandToPage(page_id,'set',new gnr.GnrBag({'data':data,'path':path,'fired':true}))},publishToClient:function(page_id,topic,data){this.sendCommandToPage(page_id,'publish',new gnr.GnrBag({'data':data,'topic':topic}))},errorHandler:function(error){console.log('wsk errorHandler',error)}});(function(global,factory){if(typeof define==='function'&&define.amd){define([],factory);}else if(typeof module!=='undefined'&&module.exports){module.exports=factory();}else{global.ReconnectingWebSocket=factory();}})(this,function(){if(!('WebSocket'in window)){return;}
function ReconnectingWebSocket(url,protocols,options){var settings={debug:false,automaticOpen:true,reconnectInterval:1000,maxReconnectInterval:30000,reconnectDecay:1.5,timeoutInterval:2000,maxReconnectAttempts:null}
if(!options){options={};}
for(var key in settings){if(typeof options[key]!=='undefined'){this[key]=options[key];}else{this[key]=settings[key];}}
this.url=url;this.pendingMessagesToSend=[]
this.reconnectAttempts=0;this.readyState=WebSocket.CONNECTING;this.protocol=null;var self=this;var ws;var forcedClose=false;var timedOut=false;var eventTarget=document.createElement('div');eventTarget.addEventListener('open',function(event){self.onopen(event);});eventTarget.addEventListener('close',function(event){self.onclose(event);});eventTarget.addEventListener('connecting',function(event){self.onconnecting(event);});eventTarget.addEventListener('message',function(event){self.onmessage(event);});eventTarget.addEventListener('error',function(event){self.onerror(event);});this.addEventListener=eventTarget.addEventListener.bind(eventTarget);this.removeEventListener=eventTarget.removeEventListener.bind(eventTarget);this.dispatchEvent=eventTarget.dispatchEvent.bind(eventTarget);function generateEvent(s,args){var evt=document.createEvent("CustomEvent");evt.initCustomEvent(s,false,false,args);return evt;};this.open=function(reconnectAttempt){ws=new WebSocket(self.url,protocols||[]);if(reconnectAttempt){if(this.maxReconnectAttempts&&this.reconnectAttempts>this.maxReconnectAttempts){return;}}else{eventTarget.dispatchEvent(generateEvent('connecting'));this.reconnectAttempts=0;}
if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','attempt-connect',self.url);}
var localWs=ws;var timeout=setTimeout(function(){if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','connection-timeout',self.url);}
timedOut=true;localWs.close();timedOut=false;},self.timeoutInterval);ws.onopen=function(event){clearTimeout(timeout);if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','onopen',self.url);}
self.protocol=ws.protocol;self.readyState=WebSocket.OPEN;self.reconnectAttempts=0;var e=generateEvent('open');e.isReconnect=reconnectAttempt;reconnectAttempt=false;eventTarget.dispatchEvent(e);while(self.pendingMessagesToSend.length>0){console.log('send pending')
self.send(self.pendingMessagesToSend.shift())}};ws.onclose=function(event){clearTimeout(timeout);ws=null;if(forcedClose){self.readyState=WebSocket.CLOSED;eventTarget.dispatchEvent(generateEvent('close'));}else{self.readyState=WebSocket.CONNECTING;var e=generateEvent('connecting');e.code=event.code;e.reason=event.reason;e.wasClean=event.wasClean;eventTarget.dispatchEvent(e);if(!reconnectAttempt&&!timedOut){if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','onclose',self.url);}
eventTarget.dispatchEvent(generateEvent('close'));}
var timeout=self.reconnectInterval*Math.pow(self.reconnectDecay,self.reconnectAttempts);setTimeout(function(){self.reconnectAttempts++;self.open(true);},timeout>self.maxReconnectInterval?self.maxReconnectInterval:timeout);}};ws.onmessage=function(event){if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','onmessage',self.url,event.data);}
var e=generateEvent('message');e.data=event.data;eventTarget.dispatchEvent(e);};ws.onerror=function(event){if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','onerror',self.url,event);}
eventTarget.dispatchEvent(generateEvent('error'));};}
if(this.automaticOpen==true){this.open(false);}
this.send=function(data){if(ws){if(self.debug||ReconnectingWebSocket.debugAll){console.debug('ReconnectingWebSocket','send',self.url,data);}
return ws.send(data);}else{console.log('socket not ready - adding to queue')
this.pendingMessagesToSend.push(data)}};this.close=function(code,reason){if(typeof code=='undefined'){code=1000;}
forcedClose=true;if(ws){ws.close(code,reason);}};this.refresh=function(){if(ws){ws.close();}};}
ReconnectingWebSocket.prototype.onopen=function(event){};ReconnectingWebSocket.prototype.onclose=function(event){};ReconnectingWebSocket.prototype.onconnecting=function(event){};ReconnectingWebSocket.prototype.onmessage=function(event){};ReconnectingWebSocket.prototype.onerror=function(event){};ReconnectingWebSocket.debugAll=false;ReconnectingWebSocket.CONNECTING=WebSocket.CONNECTING;ReconnectingWebSocket.OPEN=WebSocket.OPEN;ReconnectingWebSocket.CLOSING=WebSocket.CLOSING;ReconnectingWebSocket.CLOSED=WebSocket.CLOSED;return ReconnectingWebSocket;});



dojo.declare("gnr.GnrSharedObjectHandler",null,{constructor:function(application){this.application=application;this.lockedPaths={}},do_sharedObjectChange:function(data){var shared_id=data.getItem('shared_id');var path=data.getItem('path');var value=data.getItem('value');var attr=data.getItem('attr');if(attr&&attr instanceof gnr.GnrBag){attr=attr.asDict();}
var evt=data.getItem('evt');var fired=data.getItem('fired');var from_page_id=data.getItem('from_page_id');var so=genro._sharedObjects[shared_id];if(!so){return;}
var sopath=so.path;var fullpath=path?sopath+'.'+path:sopath;if(evt=='del'){genro._data.popNode(fullpath,'serverChange');}else{if(fired){genro._data.fireItem(fullpath,value,attr,'serverChange');}else{genro._data.setItem(fullpath,value,attr,objectUpdate({'doTrigger':'serverChange',lazySet:true}));}}},registerSharedObject:function(path,shared_id,kw){kw=kw||{};var on_unregistered=objectPop(kw,'on_unregistered');var on_registered=objectPop(kw,'on_registered');var that=this;if(!(shared_id in genro._sharedObjects)){genro._sharedObjects[shared_id]={shared_id:shared_id,path:path,ready:false,on_unregistered:on_unregistered};var onResult=function(resultNode){var data=resultNode.getValue();genro.som.do_sharedObjectChange(data);var privilege=data.getItem('privilege');var so=genro._sharedObjects[shared_id];var innerPath=data.getItem('path');so.ready=true;so.privilege=privilege;genro._sharedObjects_paths[path]=shared_id;genro.publish('shared_'+shared_id,{ready:true,privilege:privilege});var sharedValuePath=function(domnode,path){var sourceNode=genro.dom.getSourceNode(domnode);if(sourceNode&&sourceNode.attr.value){var valuePath=sourceNode.absDatapath(sourceNode.attr.value)
if(valuePath.indexOf(path)===0){return valuePath;}}}
window.addEventListener("focus",function(e){var curr_path=sharedValuePath(e.target,path)
if(curr_path){genro.wsk.send('som.onPathFocus',{shared_id:shared_id,curr_path:curr_path,focused:true});}},true)
window.addEventListener("blur",function(e){var curr_path=sharedValuePath(e.target,path)
if(curr_path){genro.wsk.send('som.onPathFocus',{shared_id:shared_id,curr_path:curr_path,focused:false});}},true)
if(on_registered){on_registered(shared_id);}}
genro.wsk.call(objectUpdate({command:'som.subscribe',shared_id:shared_id,_onResult:onResult},kw));}else{console.warn('shared_id',shared_id,'is already subscribed')}},unregisterSharedObject:function(shared_id){if(shared_id in genro._sharedObjects){genro.wsk.call({command:'som.unsubscribe',shared_id:shared_id,_onResult:function(){var so=objectPop(genro._sharedObjects,shared_id);objectPop(genro._sharedObjects_paths,so.path);if(so.on_unregistered){so.on_unregistered(shared_id)}}});}},saveSharedObject:function(shared_id){genro.wsk.call({command:'som.saveSharedObject',shared_id:shared_id,_onResult:function(){console.log('saved saveSharedObject',shared_id);}});},loadSharedObject:function(shared_id){genro.wsk.call({command:'som.loadSharedObject',shared_id:shared_id,_onResult:function(){console.log('loaded loadSharedObject',shared_id);}});},do_onPathLock:function(data){var lock_path=data.getItem('lock_path');var locked=data.getItem('locked');var user=data.getItem('user');if(locked){genro.som.lockedPaths[lock_path]=user}else{delete(genro.som.lockedPaths[lock_path])}
var lockedNode=genro.src.getSource().walk(function(n){if(n instanceof gnr.GnrDomSourceNode){var p=n.absDatapath(n.attr.value);if(p==lock_path){return n}}},'static')
if(lockedNode){lockedNode.setDisabled(locked)}}});



