// 1299843464.59
dojo.declare("gnr.GnrBagNode",null,{_counter:[0],constructor:function(parentbag,label,value,_attr,_resolver){this._id=this._counter[0]+=1;this.label=(label=='#id')?this.getStringId():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(this._value instanceof gnr.GnrBag){this._value.clearBackRef();}
return this;},setParentBag:function(parentbag){this._parentbag=null;if(parentbag!=null){this._parentbag=parentbag;if(parentbag.hasBackRef()){if(this._value instanceof gnr.GnrBag){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;},getValue2:function(mode,optkwargs){return this.getValue(mode,optkwargs);},getValue:function(mode,optkwargs){var 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);}
return;}
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);}
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){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();var value=value._value;if(resolver){this.setResolver(resolver);}
var _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);}
if(this._parentbag&&this._parentbag._backref){if(value instanceof gnr.GnrBag){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});}}},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(){var inherited={};var parentbag=this.getParentBag();if(parentbag){var parentnode=parentbag.getParentNode();if(parentnode){if(parentnode.stopInherite){inherited=objectUpdate(inherited,parentnode.attr);}else{inherited=parentnode.getInheritedAttributes();}}}
return objectUpdate(inherited,this.attr);},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,true);},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);}else{this.attr=attr;}
if(doTrigger){if(this._parentbag&&this._parentbag._backref){this._parentbag.onNodeTrigger({'evt':'upd','node':this,'pathlist':[this.label],'oldattr':oldattr,'updattr':true,reason:doTrigger,'changedAttr':changedAttr});}}},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(nodeValue instanceof gnr.GnrBag){result=xml_buildTag(this.label,nodeValue.toXmlBlock(kwargs),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){this._nodes=[];this._backref=false;this._parentnode=null;this._parent=null;this._symbols=null;this._subscribers={};if(source){this.fillFrom(source);}},newNode:function(parentbag,label,value,_attr,_resolver){return new this._nodeFactory(parentbag,label,value,_attr,_resolver);},fillFrom:function(source){if(source instanceof Array){for(var i=0;i<source.length;i++){this.setItem(source[i][0],source[i][1]);}}else if(source instanceof gnr.GnrBag){var dest=this;source.forEach(function(node){dest.setItem(node.label,node.getValue(),objectUpdate({},node.getAttr()));});}
else if(source instanceof Object){for(var k in source){this.setItem(k,source[k]);}}},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;}},getItem:function(path,dft,mode){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(obj instanceof gnr.GnrBag){return obj.get(label,dft,m);}
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 cmp=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 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;var 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){var result=null;var currnode=null;var currvalue=null;if(!label){currnode=this._parentnode;currvalue=this;}
else if(label=='#parent'){currnode=this._parent.getNode();}
else{if(label.indexOf('?')>=0){var flabel=label.split('?');label=flabel[0];var getter=flabel[1]||'#attr';}
var i=this.index(label);if(i<0){return dflt;}
else{currnode=this._nodes[i];}}
if(currnode){currvalue=currnode.getValue();}
if(!getter){return currvalue;}
var finalize=function(currvalue){if(getter.indexOf('=')==0){genro.__evalAuxValue=currvalue;var expr=getter.slice(1).replace(/#v/g,'genro.__evalAuxValue');currvalue=dojo.eval(expr);return currvalue;}
if(getter.indexOf('#')<0){return currnode.getAttr(getter);}
if(getter=='#attr'){return currnode.attr;}
if(getter=='#keys'){return currvalue.keys();}
if(getter=='#node'){return currnode;}
if(getter=='#digest:'){return currvalue.digest(mode.split(':')[1]);}};if(currvalue instanceof dojo.Deferred){return currvalue.addCallback(finalize);}
else{return finalize(currvalue);}},htraverse:function(pathlist,autocreate){var curr=this;if(typeof pathlist=="string"){if(pathlist.indexOf('?')>=0){var pl=pathlist.split('?');pathlist=smartsplit(pl[0].replace(/\.\.\//g,'#parent.'),'.');pathlist[pathlist.length-1]=pathlist[pathlist.length-1]+'?'+pl[1];}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=(newcurr instanceof gnr.GnrBag);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(value instanceof gnr.GnrBag){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(value instanceof gnr.GnrBag){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(value instanceof gnr.GnrBag){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(value instanceof gnr.GnrBag){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 this._nodes;},pop:function(path,doTrigger){var node=this.htraverse(path);var obj=node.value;var label=node.label;if(obj!=null){var n=obj._pop(label,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(){},concat:function(b){if(!b){return;}
var that=this;dojo.forEach(b._nodes,function(n){n._parentbag=that;that._nodes.push(n);})},deepCopy:function(){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('static');value=(value instanceof gnr.GnrBag)?value.deepCopy():value;result.setItem(node.label,value,objectUpdate({},node.attr));}
return result;},getNodeByAttr:function(attr,value,caseInsensitive){var value=caseInsensitive?value.toLowerCase():value;var f=function(n){if((attr in n.attr)&&(caseInsensitive?(n.attr[attr].toLowerCase()==value):(n.attr[attr]==value))){return n;}};return this.walk(f,'static');},getNode:function(path,asTuple,autocreate,_default){if(!path){return this.getParentNode();}
var mynode=this.htraverse(path,autocreate);if(mynode instanceof dojo.Deferred){}
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);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(){var result={};var node;for(var i=0;i<this._nodes.length;i++){node=this._nodes[i];result[node.label]=node.getValue();};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){this.setItem(path,value,attributes,{'doTrigger':reason==null?true:reason});this.setItem(path,null,attributes,{'doTrigger':false});},setItem:function(path,value,_attributes,kwargs){if(!kwargs){var kwargs={};}
if(path==''){if(value instanceof gnr.GnrBag){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&&node.attr[attr]===value){return;}
var auxattr={};auxattr[attr]=value;var _doTrigger=true;if('doTrigger'in kwargs){_doTrigger=kwargs.doTrigger;}
node.setAttr(auxattr,_doTrigger,true,attr);}
else{obj.set(label,value,_attributes,kwargs);}};if(mynode instanceof dojo.Deferred){mynode.addCallback(cb,value);}
else{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=this.index(label);if(i<0||_duplicate){if((label!='#id')&&(label[0]=='#')){return null;}
else{var toInsert=this.newNode(this,label,value,_attributes,resolver);kwargs._new_position=this._insertNode(toInsert,kwargs._position,_doTrigger);kwargs._new_label=toInsert.label;}}
else{var node=this._nodes[i];if(resolver){node.setResolver(resolver);}
if(kwargs.lazySet){if(node._value===value){return;}}
node.setValue(value,_doTrigger,_attributes,_updattr);}},_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,mode,kw,true);},walk:function(callback,mode,kw,notRecursive){var result;var bagnodes=this.getNodes();for(var i=0;((i<bagnodes.length)&&(result==null));i++){result=callback(bagnodes[i],kw,i);if(result==null){var value=bagnodes[i].getValue(mode);if((!notRecursive)&&(value instanceof gnr.GnrBag)){result=value.walk(callback,mode,kw);}}}
return result;},getBackRef:function(){return this._backref;},hasBackRef:function(){return(this._backref==true);},setBackRef:function(node,parent){if(this._backref!=true){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(value instanceof gnr.GnrBag){value.clearBackRef();}}}},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 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;for(j=0;j<node.attributes.length;j++){attrname=node.attributes[j].name;attrvalue=node.attributes[j].value;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){aux=attrvalue.split('::');attrvalue=convertFromText(aux[0],aux[1]);}
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){var itemValue=textContent;if(convertAs!='T'){itemValue=convertFromText(itemValue,convertAs);}else if(stringContains(itemValue,'::')){itemValue=itemValue.split('::');convertAs=itemValue[1];itemValue=convertFromText(itemValue[0],convertAs);}
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 clsproto=this;if(clsdict!=null){if(newcls){newcls=clsdict[newcls];if(newcls){clsproto=newcls.prototype;}}}
var newBag=new clsproto.constructor();this.addItem(tagName,newBag,attributes);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){return result.addCallback(finalize);}
else{return finalize(result,kwargs);}}},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,{init:function(kwargs){this.method=kwargs.method;this.parameters=kwargs.parameters;},load:function(){return this.method.call(this,this.parameters);}});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,{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.widget||this.domNode;},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.domNode;}},getParentDomNode:function(){var parentNode=this.getParentNode();if(parentNode){return parentNode.getDomNode();}},getWidget:function(){return this.widget||dijit.getEnclosingWidget(this.domNode);},getParentWidget:function(){var parentNode=this.getParentNode();if(parentNode){return parentNode.getWidget();}},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);}},trigger_data:function(prop,kw){var dpath=kw.pathlist.slice(1).join('.');var mydpath=this.attrDatapath(prop);if(mydpath==null){return;}
if(mydpath.indexOf('#parent')>0){mydpath=gnr.bagRealPath(mydpath);}
if(mydpath.indexOf('?')>=0){if((kw.updattr)||(mydpath.indexOf('?=')>=0)){mydpath=mydpath.split('?')[0];}}
var trigger_reason=null;var eqpath=(mydpath==dpath);if(eqpath){trigger_reason='node';}
var changed_container=(mydpath.indexOf(dpath+'.')==0);if(changed_container){trigger_reason='container';}
var changed_child=(dpath.indexOf(mydpath+'.')==0);if(changed_child){trigger_reason='child';}
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(){this.setDataNodeValue();},setDataNodeValue:function(node,kw,trigger_reason,subscription_args){if('_delay'in this.attr){if(this.pendingFire){clearTimeout(this.pendingFire);}
this.pendingFire=setTimeout(dojo.hitch(this,'setDataNodeValueDo',node,kw,trigger_reason),this.attr._delay);}else{this.setDataNodeValueDo(node,kw,trigger_reason,subscription_args);}},setDataNodeValueDo:function(node,kw,trigger_reason,subscription_args){var attributes=objectUpdate({},this.attr);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');objectPop(attributes,'_onStart');objectPop(attributes,'_onBuilt');objectPop(attributes,'_fired_onStart');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={};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];}}}
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);}}
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,'_POST')?'POST':'GET';var _onResult=objectPop(kwargs,'_onResult');var _onError=objectPop(kwargs,'_onError');var _lockScreen=objectPop(kwargs,'_lockScreen');objectPop(kwargs,'nodeId');var _onCalling=objectPop(kwargs,'_onCalling');var origKwargs=objectUpdate({},kwargs);objectExtract(kwargs,'_*');if(_onResult){_onResult=funcCreate(_onResult,'result,kwargs,old',this);}
if(_onError){_onError=funcCreate(_onError,'error,kwargs',this);}
var cb=function(result,error){if(_lockScreen){genro.lockScreen(false,domsource_id);}
if(error){if(_onError){_onError(error,origKwargs);}
else{genro.dlg.alert(error,'Server error');}}
else{var oldValue;if(dataNode){oldValue=dataNode.getValue();dataNode.setValue(result);}
if(_onResult){_onResult(result,origKwargs,oldValue);}}};if(_onCalling){doCall=funcCreate(_onCalling,(['kwargs'].concat(argNames)).join(',')).apply(this,([kwargs].concat(argValues)));}
if(_lockScreen){genro.lockScreen(true,domsource_id);}
if(doCall!=false){if(!this._deferredRegister){this._deferredRegister={}}
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){delete that._deferredRegister[deferred.id];return result})
if(this._callbacks){this._callbacks.forEach(function(n){var kw=objectUpdate({},kwargs);genro.rpc.addDeferredCb(deferred,n.getValue(),objectUpdate(kw,n.attr),that);})}}}}
else{var result;if(!expr){result=new gnr.GnrBag(kwargs);}else{expr=(tag=='dataformula')?'return '+expr:expr;result=funcCreate(expr,argNames.join(',')).apply(this,argValues);}
if(dataNode){dataNode.setValue(result);}}}
else{if(if_result){var 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 resolver=genro.rpc.remoteResolver(method,attributes,{'cacheTime':cacheTime,'isGetter':isGetter});dataNode.setValue(resolver,true,attributes);}}},setAttributeInDatasource:function(attrname,value,doTrigger,attributes,forceChanges){var doTrigger=(doTrigger==false)?doTrigger:this;var path=this.attrDatapath(attrname);var old_value=genro._data.getItem(path);if(old_value!=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);if(path.indexOf('?')>=0){value=genro._data.getItem(path);}else if(node){value=node.getValue(null,{'_sourceNode':this});}}else{if(path.indexOf('?')>=0){value=genro._data.getItem(path);}else{var node=genro._data.getNode(path);if(node){value=node.getValue(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){if(delay){setTimeout(dojo.hitch(this,'setRelativeData',path,value,attributes,fired,reason),delay);}else{var reason=reason==null?true:reason;var oldpath=path;var 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,{'doTrigger':reason,lazySet:true});}}},getAttributeFromDatasource:function(attrname,autocreate,dflt){var attrname=attrname||'value';var value=this.attr[attrname];value=this.currentFromDatasource(value,autocreate,dflt);if(((attrname=='value')||(attrname=='innerHTML'))&&(this.attr.mask||this.attr.format)){value=asText(value,this.attr);}
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){if(!attrname){return this.absDatapath();}
var attrvalue=this.attr[attrname];var path=null;if(typeof(attrvalue)=='string'){if(this.isPointerPath(attrvalue)){attrvalue=attrvalue.slice(1);}
path=this.absDatapath(attrvalue);}
return path;},isPointerPath:function(path){return path?((path.indexOf('^')==0)||(path.indexOf('=')==0)):false;},symbolicDatapath:function(path){var pathlist=path.split('.');var nodeId=pathlist[0].slice(1);currNode=nodeId?genro.nodeById(nodeId):this;if(!currNode){console.error('not existing nodeId:'+nodeId);}
var relpath=pathlist.slice(1).join('.');if(relpath=='*S'){return currNode.getFullpath().replace('main.','*S.');}
path=currNode.absDatapath(relpath?'.'+relpath:'');return path;},absDatapath:function(path){var path=path||'';if(this.isPointerPath(path)){path=path.slice(1);}
if(path.indexOf('#')==0){return this.symbolicDatapath(path);}
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=this.symbolicDatapath(datapath);}
path=datapath+path;}
currNode=currNode.getParentNode();}
if(path.indexOf('.')==0){console.error('unresolved relativepath '+path);}
path=path.replace('.?','?');if(path.indexOf('#parent')>0){path=gnr.bagRealPath(path);}
return path;},connect:function(target,eventname,handler,parameters){var eventname=((!eventname)||eventname=='action')?target.gnr._defaultEvent:eventname;var handler=dojo.hitch(this,funcCreate(handler,parameters));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{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);}}}
return attributes;},evaluateOnNode:function(pardict){var result={};for(var attr in pardict){result[attr]=this.currentFromDatasource(pardict[attr]);}
return result;},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){this._stripData(true);this._isBuilding=true;var attributes=this.registerNodeDynAttr(true);var tag=objectPop(attributes,'tag');if(!tag){this._buildChildren(destination);}else{this._registerInForm();this._doBuildNode(tag,attributes,destination,ind);this._setDynAttributes();}
this._isBuilding=false;},_buildChildren:function(destination){if(this.attr.remote){dojo.connect(this.widget,'onShow',this,'updateRemoteContent');}
var content=this.getValue('static');if(content instanceof gnr.GnrDomSource){var sourceNodes=content.getNodes();var node;var newobj;for(var i=0;i<sourceNodes.length;i++){node=sourceNodes[i];if(node.attr.tag){var aux='_bld_'+node.attr.tag.toLowerCase();if(aux in node){node._stripData(true);node._registerInForm();node[aux].call(node);}else{node.build(destination,-1);}}}}},_registerInForm:function(){var formHandler=this.getFormHandler();if(formHandler){this.form=formHandler;if(this.attr.parentForm!==false){formHandler.registerChild(this)}}},_registerNodeId:function(nodeId){var nodeId=this.attr.nodeId||nodeId;if(nodeId){genro.src._index[nodeId]=this;}},_doBuildNode:function(tag,attributes,destination,ind){var bld_attrs=objectExtract(attributes,'onCreating,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 attrname;var ind=ind||0;if(bld_attrs.onCreating){funcCreate(bld_attrs.onCreating).call(this,attributes);}
var newobj=genro.wdg.create(tag,destination,attributes,ind,this);for(var selfsubscribe in selfsubscription){this.subscribe(selfsubscribe,selfsubscription[selfsubscribe]);}
if(this.form){var formsubscription=objectExtract(attributes,'formsubscribe_*');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(newobj.onShow){var that=this;dojo.connect(newobj,'onShow',this,function(){setTimeout(function(){that.finalizeLazyBuildChildren()},1)});}
if(!this.attr._lazyBuild){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}).connectOneNode(newobj.domNode||newobj);}
this._built=true;return newobj;},_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.unsubscribe(nodeSubscribers[attr]);}
delete genro.src._subscribedNodes[stringId];}},_setDynAttributes:function(){var stringId=this.getStringId();if(this._dynattr){var nodeSubscribers={};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;},finalizeLazyBuildChildren:function(){if(this.attr._lazyBuild){this.lazyBuildFinalize();}else{this.getValue('static').walk(function(n){if(n.attr._lazyBuild){n.lazyBuildFinalize();return true;}});}},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);});}}},registerSubscription:function(topic,scope,handler){var stringId=this.getStringId();var subDict=genro.src._subscribedNodes[stringId];if(!subDict){subDict={};genro.src._subscribedNodes[stringId]=subDict;}else{if(subDict[topic]){console.warn('existing subscription for topic '+topic);return;}}
subDict[topic]=dojo.subscribe(topic,scope,handler);},subscribe:function(command,handler){var topic=(this.attr.nodeId||this.getStringId())+'_'+command;this.registerSubscription(topic,this,funcCreate(handler))},lazyBuildFinalize:function(){if(this.attr._lazyBuild){var lazyBuild=objectPop(this.attr,'_lazyBuild');var parent=this.getParentBag();var content;if(lazyBuild!==true){content=genro.serverCall('remoteBuilder',objectUpdate({handler:lazyBuild},objectExtract(this.attr,'remote_*')));console.log('content lazybuild')}
else{content=this._value;}
this.setValue(content);var that=this;setTimeout(function(){that._value.walk(function(n){if(n.attr._onBuilt){n.fireNode();}});},1);}},lazyBuildFinalize_new:function(){if(this.attr._lazyBuild){var lazyBuild=objectPop(this.attr,'_lazyBuild');var parent=this.getParentBag();var content;if(lazyBuild!==true){content=genro.serverCall('remoteBuilder',objectUpdate({handler:lazyBuild},objectExtract(this.attr,'remote_*')));console.log('content lazybuild')}
else{content=this._value;}
var parent=this.getParentBag();var label=this.label
var node=parent.popNode(label);parent.setItem(label,content,this.attr);var that=parent.getNode(label);setTimeout(function(){that._value.walk(function(n){if(n.attr._onBuilt){n.fireNode();}});},1);}},getFrameNode:function(){if(this.attr.tag.toLowerCase()=='framepane'){return this;}
var parent=this.getParentNode();if(parent){return parent.getFrameNode();}},getFormHandler:function(){if(this.form){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();}},updateAttrBuiltObj:function(attr,kw,trigger_reason){var attr=attr||'value';var attr_lower=attr.toLowerCase();var path;var value=null;if(!(kw.evt=='ins'||kw.evt=='del')){value=this.getAttributeFromDatasource(attr,true);}
value=(value!=null)?value:'';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);}
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){if(oldvalue instanceof gnr.GnrBag){var q=kw.pathlist.length;var p=this.absDatapath(this.attr._class).split('.').slice(q-1);var old_class=oldvalue.getItem(p.join('.'));}else{var old_class=oldvalue;}
genro.dom.removeClass(domnode,old_class);}
genro.dom.addClass(domnode,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'){this.resetValidationError();var currval=this.getAttributeFromDatasource('value');var newval=this.validationsOnChange(this,currval)['value'];this.updateValidationStatus();this.setAttributeInDatasource('value',newval);}}
else{var setter='set'+stringCapitalize(attr);if(setter in this.widget){var trgevt=kw.evt;if(attr=='value'){this.resetValidationError();if('_lastValueReported'in this.widget){this.widget._lastValueReported=value;}
kw=false;if(this.attr.unmodifiable){var parentAttr=this.getRelativeData('.?');if('_newrecord'in parentAttr){this.widget.setAttribute('readOnly',!parentAttr['_newrecord']);}}}
dojo.hitch(this.widget,setter)(value,kw);if((trgevt!='del')&&(attr=='value')&&(this.hasValidations())){var formHandler=this.getFormHandler();if(formHandler){formHandler.validateFromDatasource(this,value,trigger_reason);}}}else{this.rebuild();}}}
else if(this.domNode){var domnode=this.domNode;var setter='set'+stringCapitalize(attr);if(attr=='visible'){dojo.style(domnode,'visibility',(value?'visible':'hidden'));return;}
else if(attr=='hidden'){dojo.style(domnode,'display',(value?'none':''));return;}
else if(attr=='value'){if('value'in domnode){domnode.value=value;}
else{}}
else if(attr=='datasource'){domnode.innerHTML=dataTemplate(this.attr.template,this,this.attr.datasource);}
else if(attr=='innerHTML'){domnode.innerHTML=value;}
else if(genro.dom.isStyleAttr(attr)){domnode.setAttribute('style',objectAsStyle(genro.dom.getStyleDict(this.currentAttributes())));}
else if(setter in domnode.gnr){dojo.hitch(domnode.gnr,setter)(domnode,value,kw);}
else{var attrdict={};this.setAttr(attrdict,this,true);}}},_stripData:function(shallow){var content=this.getValue('static');var dflt;if(content instanceof gnr.GnrBag){var bagnodes=content.getNodes();var node,v;for(var i=0;i<bagnodes.length;i++){node=bagnodes[i];if(node.attr.tag){if(node.attr.tag.toLowerCase()in genro.src.datatags){node._moveData(node);}
else{var nodeattr=node.attr;for(var attr in nodeattr){if((typeof(nodeattr[attr])=='string')&&node.isPointerPath(nodeattr[attr])){dflt=(attr=='value')?(nodeattr['default']||nodeattr['default_value']||''):nodeattr['default_'+attr];node.getAttributeFromDatasource(attr,true,dflt);}}}
if(!shallow){node._stripData();}}}}},_moveData:function(){this._registerNodeId();var attributes=this.registerNodeDynAttr(false);var tag=objectPop(attributes,'tag');var path=objectPop(attributes,'path');if(tag=='data'&&attributes.remote){attributes['method']=objectPop(attributes,'remote');tag='dataRemote';}
if(tag=='data'){path=this.absDatapath(path);var value=this.getValue();this._value=null;if(value instanceof gnr.GnrBag){value.clearBackRef();}
var serverpath=objectPop(attributes,'_serverpath');if(serverpath){genro._serverstore_paths[this.absDatapath(path)]=serverpath;}
if(!genro.getDataNode(path)||(value!==null)){genro.setData(path,value,attributes);}}else if(tag=='dataRemote'){this._dataprovider=tag;this.setDataNodeValue();}else{var initialize=objectPop(attributes,'_init');this._dataprovider=tag;if(initialize){this.setDataNodeValue();}else{path=this.absDatapath(path);genro.getDataNode(path,true);}
var timing=objectPop(attributes,'_timing');if(timing){this.setTiming(timing);}
var onStart=objectPop(attributes,'_onStart');objectPop(attributes,'_onBuilt');var subscriptions=objectExtract(attributes,'subscribe_*');var selfsubscriptions=objectExtract(attributes,'selfsubscribe_*');var formsubscriptions=objectExtract(attributes,'formsubscribe_*');var nid=this.attr.nodeId||this.getStringId();for(var selfsubcription in selfsubscriptions){subscriptions[nid+'_'+selfsubcription]=selfsubscriptions[selfsubcription];}
if(objectNotEmpty(formsubscriptions)||this.attr.parentForm){var that=this;var cb=function(){var form=that.getFormHandler();if(form){that.form=form;var fid=form.formId;var subscriptions={};for(var formsubcription in formsubscriptions){subscriptions['form_'+fid+'_'+formsubcription]=formsubscriptions[formsubcription];}
that._dataControllerSubscription(subscriptions);}}
genro.src.afterBuildCalls.push(cb);}
this._dataControllerSubscription(subscriptions);if(onStart){this.attr._fired_onStart='^gnr.onStart';this.registerDynAttr('_fired_onStart');if(typeof(onStart)=="number"&&!this.attr._delay){this.attr._delay=onStart;}}}
this._setDynAttributes();},_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);}},updateRemoteContent:function(forceUpdate){var _onRemote=false;var currentValue=this.getValue('static');if(currentValue&&currentValue.len()>0&&!forceUpdate){return;}
var kwargs={};for(var attrname in this.attr){if(attrname.indexOf('remote_')==0){var value=this.getAttributeFromDatasource(attrname);if(value instanceof Date){var abspath=this.absDatapath(this.attr[attrname]);var node=genro._data.getNode(abspath);value=asTypedTxt(value,node.attr.dtype);};var sendattr=attrname.slice(7);if(sendattr.indexOf('_')!=0){kwargs[sendattr]=value;}else if(sendattr=='_onRemote'){_onRemote=funcCreate(value,'',this);}}}
var method=this.attr.remote;var _sourceNode=this;kwargs.sync=true;genro.rpc.remoteCall(method,kwargs,null,null,null,function(result){_sourceNode.setValue(result);if(_onRemote){_onRemote();}});},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;}},updateValidationStatus:function(kw){if(this.widget){this.updateValidationClasses();this.widget.state=this.hasValidationError()?'Error':null;this.widget._setStateClass();}},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');}},setDisabled:function(value){var value=value?true: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.domNode){this.domNode.disabled=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;},_: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(){this.getParentBag().delItem(this.label);}});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;tag=tag.toLowerCase();if(tag){if(name instanceof Object){var extrakw=attributes;var attributes=name;var name='';}
var attributes=attributes||{};if(attributes&&('remote'in attributes)){var remattr=objectUpdate({},objectPop(attributes,'remote'));remattr['handler']=objectPop(remattr,'method');remattr['method']='remoteBuilder';var cacheTime=objectPop(remattr,'cacheTime');content=new gnr.GnrRemoteResolver(remattr,false,cacheTime);content.updateAttr=true;}
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.setItem(name,content,attributes,extrakw);return content;}},replaceContent:function(b){this._nodes=b.getNodes();},component:function(){if(this.component!=null){return this._component;}else if(this.parent!=null){return this.parent.component();}}});



var _lf='\n';var _crlf='\r\n';var _tab='\t';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 arrayContains(arr,item){for(var i=0;i<arr.length;i++){if(arr[i]==item){return true;}}
return false;}
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 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){return str.replace(/\w+/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1);});};function dataTemplate(str,data,path,showAlways){if(!str){return'';}
var regexpr=/\$([a-z0-9.@?_]+)/g;var result;var is_empty=true;if(!data&&!showAlways){return'';}
else if(typeof(data)=='string'){data=genro._data.getItem(data);}
else if(data instanceof gnr.GnrDomSourceNode){data=genro._data.getItem(data.absDatapath());}
if(data instanceof gnr.GnrBag){if(path){data=data.getItem(path);}
if(!data&&!showAlways){return'';}
result=str.replace(regexpr,function(path){var value=data.getItem(path.slice(1));if(value!=null){is_empty=false;if(value instanceof Date){value=dojo.date.locale.format(value,{selector:'date',format:'short'});}
return value;}else{return'';}});}else{data=data||{};return str.replace(regexpr,function(path){var value=data[path.slice(1)];if(value!=null){is_empty=false;if(value instanceof Date){value=dojo.date.locale.format(value,{selector:'date',format:'short'});}
return value;}else{return'';}});}
if(is_empty){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 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 instanceof Object)&&(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 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 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 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 objectUpdate(obj,source,removeNulls){if(source){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 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 objectRemoveNulls(obj,blackList){var 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(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 objectAsStyle(obj){var sep=sep||' ';var result=[];for(var prop in obj){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;}
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;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){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(value==null){return null}
if(!t&&value.indexOf('::')>=0){value=value.split('::');t=value[1];value=value[0];}
var t=t||'T';t=t.toUpperCase();if(t=='NN'){return null;}
else if(t=='L'){if(fromLocale){value=dojo.number.parse(value);}else{value=parseInt(value);}
value.genrodtype=t;return value;}
else if(t=='R'||t=='N'){if(fromLocale){value=dojo.number.parse(value);}else{value=parseFloat(value);}
value.genrodtype=t;return value;}
else if(t=='B'){return(value.toLowerCase()=='true');}
else if((t=='D')||(t=='DH')){if(fromLocale){var selector=(t=='DH')?'datetime':'date';return dojo.date.locale.parse(value,{selector:selector});}else{return new Date(value.split('.')[0].replace(/\-/g,'/'));}}
else if(t=='H'){if(fromLocale){return dojo.date.locale.parse(value,{selector:'time'});}else{value=value.split(':');if(value.length<3){value.push('00');}
return new Date(1971,null,null,Number(value[0]),Number(value[1]),Number(value[2]));}}
else if(t=='JS'){return genro.evaluate(value);}
else if(t='BAG'&&!value){return new gnr.GnrBag();}
return value;}
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'){if(value){result=['B','true'];}else{result=['B','false'];}}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=['R',v];}}}
else if(value instanceof Date){var selectors={'D':'date','H':'time','DH':null};if(!dtype){dtype=value.toString().indexOf('Thu Dec 31 1970')==0?'H':'D';}
var opt={'selector':selectors[dtype]};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 instanceof gnr.GnrBag){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 funcCreate(fnc,pars,scope){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);if(scope){fnc=dojo.hitch(scope,fnc);}}
return fnc;}}
function highlightLinks(text){var makeLink=function(href,title){return"<a href='"+href+"'>"+title+"</a>"}
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)});return text;}
function funcApply(fnc,parsobj,scope){var argNames=[];var argValues=[];for(var attr in parsobj){argNames.push(attr);argValues.push(parsobj[attr]);}
var func=funcCreate(fnc,argNames.join(','));var result=func.apply(scope,argValues);return result;}
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;};



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){genro.debug('getValue: item='+item.label+' - attribute-name-string='+attribute+' - default='+defaultValue);var attributes=item.attr;if(attribute=='#k'){return item.label;}
else if(attribute=='#v'){return item.getValue();}
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();if(itemvalue instanceof gnr.GnrBag){return 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(result instanceof gnr.GnrBag){return(result.len()>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);},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){var 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);}
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);}
return item.label;}else if(typeof(item)=='object'){if(this.labelCb){return this.labelCb.call(item);}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;}
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(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,{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(this.cachePrefix){value=genro.getFromStorage(this.storageMode,this.cachePrefix+request.identity);if(value){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 result;var scope=request.scope?request.scope:dojo.global;result=r.getValue();if(result instanceof gnr.GnrBag){result=result.getNode('#0');}else{result=null;}
if(result){if(this.cachePrefix){genro.setInStorage(this.storageMode,this.cachePrefix+request.identity,result.attr[this.searchAttr]);}
dojo.hitch(scope,request.onItem)(result);}});var result=this.rootDataNode().getValue('',{_id:id});if(result instanceof dojo.Deferred){result.addCallback(finalize);}}},_doFetch:function(request,findCallback,errCallback){var query=request.query;if(!query.caption){findCallback([],request);}else{if((this._lastSelectedItem)&&(this._lastSelectedCaption==query.caption)){findCallback([this._lastSelectedItem],request);}else{this._lastSelectedCaption=null;this._lastSelectedItem=null;var ignoreCase=request.queryOptions?request.queryOptions.ignoreCase:false;var kwargs={_id:'',_querystring:query.caption,ignoreCase:ignoreCase};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);});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);};dojo.declare('gnr.GenroClient',null,{constructor:function(kwargs){this.domRootName=kwargs.domRootName||'mainWindow';this.page_id=kwargs.page_id;this.startArgs=kwargs.startArgs||{};this.debuglevel=kwargs.startArgs.debug||null;this.debugopt=kwargs.startArgs.debugopt||null;this.pageMode=kwargs.pageMode;this.baseUrl=kwargs.baseUrl;this.lockingElements={};this.debugRpc=false;this.isDeveloper=this.startArgs.isDeveloper;this.theme={};setTimeout(dojo.hitch(this,'genroInit'),1);},genroInit:function(){this.startTime=new Date();this.lastTime=this.startTime;this.dialogStack=[];this.sounds={};this._serverstore_paths={};this._serverstore_changes=null;this.pendingFireAfter={};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){var exit;if(genro.checkBeforeUnload){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);if(dojo_version=='1.1'){if(dojo.isSafari){dojo.keys.DOWN_ARROW=40;dojo.keys.UP_ARROW=38;}
genropatches.borderContainer();genropatches.comboBox();genropatches.tree();genropatches.parseNumbers();}
this.clsdict={domsource:gnr.GnrDomSource,bag:gnr.GnrBag};this.eventPath='_sys.events';this.prefs={'recordpath':'tables.$dbtable.record','selectionpath':'tables.$dbtable.selection','limit':'50'};dojo.addOnLoad(this,'start');},start:function(){setTimeout(dojo.hitch(this,'dostart'),1);},compare:function(op,a,b){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);}},bp:function(aux){console.log('bp '+aux);if(aux===true){debugger;}},onWindowUnload:function(e){this.rpc.remoteCall('onClosePage',{sync:true});if(genro._data){genro.saveContextCookie();}},saveContextCookie:function(){var clientCtx=genro.getData('_clientCtx');genro.publish('onCookieSaving');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);},_registerUserEvents:function(){this.auto_polling=-1;this.user_polling=-1;genro._lastUserEventTs=new Date();var cb=function(e){if(genro.user_polling>0){genro._lastUserEventTs=new Date();if((genro._lastUserEventTs-genro.lastRpc)/1000>genro.user_polling){genro.rpc.ping({'reason':'user'});}}};dojo.connect(window,'onmousemove',cb);dojo.connect(window,'onkeypress',cb);},dostart: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={};var mainBagPage=this.rpc.remoteCall('main',this.startArgs,'bag');if(mainBagPage&&mainBagPage.attr.redirect){var url=this.addParamsToUrl(mainBagPage.attr.redirect,{'fromPage':this.absoluteUrl()});this.gotoURL(url);}
this.loadContext();this.src.startUp(mainBagPage);genro.dom.removeClass('mainWindow','waiting');genro.dom.removeClass('_gnrRoot','notvisible');genro.dom.effect('_gnrRoot','fadein',{duration:400});genro.dragDropConnect();genro.standardEventConnection();if(genro.isDeveloper){genro.dev.inspectConnect();}
var _this=this;this._dataroot.subscribe('dataTriggers',{'any':dojo.hitch(this,"dataTrigger")});genro.dev.shortcut("Ctrl+Shift+D",function(){genro.dev.showDebugger();});genro.callAfter(function(){genro.fireEvent('gnr.onStart');genro.publish('onPageStart');},100);genro.dev.shortcut('f1',function(e){genro.publish('SAVERECORD',e)})
genro.dev.shortcut('f3',function(e){genro.publish('PRINTRECORD',e)})
var windowTitle=this.getData('gnr.windowTitle');if(windowTitle){genro.dom.windowTitle(windowTitle);}
if(this.debugopt){genro.setData('gnr.debugger.sqldebug',this.debugopt.indexOf('sql')>=0);}
this.isMac=dojo.isMac!=undefined?dojo.isMac:navigator.appVersion.indexOf('Macintosh')>=0;this.isTouchDevice=((navigator.appVersion.indexOf('iPad')>=0)||(navigator.appVersion.indexOf('iPhone')>=0));this.isChrome=((navigator.appVersion.indexOf('Chrome')>=0));this._registerUserEvents();if(this.isTouchDevice){genro.dom.startTouchDevice();}},dragDropConnect:function(pane){var pane=pane||genro.domById('mainWindow');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');},setActiveForm:function(destform){if(destform!=genro.activeForm){if(genro.activeForm){genro.activeForm.onBlurForm();}
if(destform){destform.onFocusForm();}
genro.activeForm=destform;}},setCurrentFocused:function(wdg){var sourceNode=wdg.sourceNode;var destform=sourceNode.form;this.setActiveForm(sourceNode.form);if(genro.activeForm){genro.activeForm.onFocusElement(wdg);}},standardEventConnection:function(pane){var pane=pane||genro.domById('mainWindow');dojo.connect(pane,'onclick',function(e){var wdg=dijit.getEnclosingWidget(e.target);if(wdg){if(wdg.isFocusable()){return}
var sourceNode=wdg.sourceNode;if(sourceNode){genro.setActiveForm(sourceNode.form);}else{console.log(wdg);}}else{}});},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(){},callAfter:function(cb,timeout,scope){scope=scope||genro;cb=funcCreate(cb);setTimeout(dojo.hitch(scope,cb),timeout);},fireAfter:function(path,msg,timeout){var timeout=timeout||1;var _path=path;var _msg=msg;if(this.pendingFireAfter[path]){clearTimeout(this.pendingFireAfter[path]);}
this.pendingFireAfter[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);},format:function(v,f,m){if(v instanceof Date){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'){if(!f.places&&f.dtype=='L'){f.places=0;}
if(!f.pattern&&f.places==0){f.pattern='##########';}
v=stringStrip(dojo.currency.format(v,f));}
else if(typeof(v)=='boolean'||f.dtype=='B'){var divcontent=v?(f['true']||(f['trueclass']?'':'true')):(f['false']||(f['falseclass']?'':'false'));var divclass=v?(f['trueclass']?f['trueclass']:''):(f['falseclass']?f['falseclass']:'');divclass=divclass?'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']===true){var divclass=f['buttonclass'];divclass=divclass?'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+">"+'&nbsp;'+"</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>";}}
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','');},getCounter:function(){this._counter=this._counter+1;return this._counter;},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._('iframe',params);node.unfreeze();},makeUrl:function(url,kwargs){if(url.indexOf('://')==-1){if(url.slice(0,1)!='/'){var base=document.location.pathname;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+'='+escape(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){if(kw.evt=='upd'){var dpath=kw.pathlist.slice(1).join('.');if(dpath in genro._serverstore_paths&&kw.reason!='serverChange'){genro._serverstore_changes=genro._serverstore_changes||{};genro._serverstore_changes[genro._serverstore_paths[dpath]]=kw.value;}}
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();}},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(2);}
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});},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: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 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(iframe){var t=objectUpdate({},topic)
objectPop(t,'parent')
if(iframe=='*'){dojo.forEach(window.frames,function(f){if(f.genro){f.genro.publish(t,kw);}});}else{var iframeNode=genro.domById(iframe);if(iframeNode){var f=iframeNode.contentWindow;if(f&&f.genro){f.genro.publish(t,kw);}}}}
if(parent&&(window.parent!=window)&&window.parent.genro){var t=objectUpdate({},topic)
objectPop(t,'iframe');objectPop(t,'parent');window.parent.genro.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,value);console.log('Stored in '+sessionType+'Storage at key:'+key+'  value:'+value);},getFromStorage:function(sessionType,key){var sessionType=sessionType||'session';var storage=(sessionType=='local')?localStorage:sessionStorage;var value=storage.getItem(key);if(value){}else{}
return value;},addParamsToUrl:function(url,params){var parameters=[];for(var key in params){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:null},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){var node=genro.src._index[nodeId];if(!node&&genro.src.building){node=genro.src._main.getNodeByAttr('nodeId',nodeId);}
return node;},domById:function(nodeId){var node=this.nodeById(nodeId);if(node){return node.getDomNode();}else{return dojo.byId(nodeId);}},wdgById:function(nodeId){var node=this.nodeById(nodeId);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,arguments,sourceNode,avoidCache){return genro.rpc.rpcUrl(method,arguments,sourceNode,avoidCache);},setUrlRemote:function(widget,method,arguments){var url=genro.rpc.rpcUrl(method,arguments);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(){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){var cb=funcCreate(async_cb);return genro.rpc.remoteCall(method,params,mode,null,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){try{var toEval='genro.auxresult=('+expr+')';dojo.eval(toEval);return genro.auxresult;}catch(e){if(console!=undefined){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){if(params){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.reload();}},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){if(params){if(typeof(params)!='string'){parlist=[];for(var par in params){parlist.push(par+'='+params[par]);}
params=parlist.join(',');}}
var newwindow=window.open(url,name,params);if(window.focus){newwindow.focus();}},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');return genro.rpc['remote_'+resolverName].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');},lockScreen:function(locking,reason,options){if(reason){genro.lockingElements[reason]=reason;}
if(locking){if(!reason){return;}
document.createElement("div");var hider=document.createElement("div");hider.id="mainWindow_hider";dojo.addClass(hider,'formHider');if(options){var waiting=document.createElement("div");dojo.addClass(waiting,'waiting');hider.appendChild(waiting);}
if(!genro.domById('mainWindow_hider')){genro.domById('mainWindow').appendChild(hider);}}else{if(reason){objectPop(genro.lockingElements,reason);}else{genro.lockingElements={};}
if(!objectNotEmpty(genro.lockingElements)){genro.domById('mainWindow').removeChild(genro.domById('mainWindow_hider'));}}}});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.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){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;}}});};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]=child.domNode;this["_"+region+"Widget"]=child;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'};var oppNodeList=dojo.query('[region='+flip[child.region]+']',this.domNode);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)){child.resize();}},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(){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._TreeNode.prototype.setLabelNode=function(label){this.labelNode.innerHTML="";if((typeof(label)=='string')&&(label.indexOf('innerHTML:')>=0)){this.labelNode.innerHTML=label.replace('innerHTML:','');this.htmlLabel=true;}
else{this.labelNode.appendChild(dojo.doc.createTextNode(label));};if(this.item.attr&&'node_class'in this.item.attr){dojo.addClass(this.domNode,this.item.attr.node_class);}
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;};};



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');this.onloading=null;},load:function(kwargs){if(this.onloading){this.onloading(kwargs);}
var sync=this.xhrKwargs.sync;var sourceNode=objectPop(kwargs,'_sourceNode');var result=genro.rpc._serverCall(kwargs,this.xhrKwargs,this.httpMethod,sourceNode);if(sync){result.addCallback(function(value){result=value;});}
return result;},errorHandler:function(response,ioArgs){return genro.rpc.errorHandler(response,ioArgs);},resultHandler:function(response,ioArgs){if(response.documentElement.tagName=='parsererror'){debugger;}
return genro.rpc.resultHandler(response,ioArgs,(this.updateAttr?this._parentNode.attr:null));}});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;},register_call:function(kw){this.rpc_counter=this.rpc_counter+1;this.rpc_level=this.rpc_level+1;kw['__rpc_counter']=this.rpc_counter;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'];delete this.rpc_register['r_'+rpc_counter];},serverCall:function(callKwargs,xhrKwargs,httpMethod){},_serverCall:function(callKwargs,xhrKwargs,httpMethod,sourceNode){var httpMethod=httpMethod||'GET';if(genro._serverstore_changes){callKwargs._serverstore_changes=genro._serverstore_changes;genro._serverstore_changes=null;};var delayOnCall=objectPop(callKwargs,'_delayOnCall');callKwargs=this.serializeParameters(genro.src.dynamicParameters(callKwargs,sourceNode));objectPop(callKwargs,'_destFullpath');callKwargs._lastUserEventTs=asTypedTxt(genro._lastUserEventTs,'DH');if(genro.auto_polling>0){this._call_auto_polling();}
var content=objectUpdate({},callKwargs);content.page_id=this.application.page_id;var kw=objectUpdate({},xhrKwargs);kw.url=kw.url||this.pageIndexUrl();if(this.application.debugopt){content.debugopt=this.application.debugopt;content.callcounter=this.application.getCounter();}
kw.content=content;kw.handleAs=kw.handleAs||'xml';this.register_call(kw);var xhrResult;genro.lastRpc=new Date();if(genro.debugRpc){this.debugRpc(kw);};if(delayOnCall){}else{var deferred=this._serverCall_execute(httpMethod,kw,callKwargs);return deferred;}},_serverCall_execute:function(httpMethod,kw,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('PUT'){if('putData'in callKwargs){xhrResult=dojo.rawXhrPut(kw);}else{xhrResult=dojo.xhrPut(kw);}}
return xhrResult;},_call_auto_polling:function(){if(this._auto_polling_handler){clearTimeout(this._auto_polling_handler);}
this._auto_polling_handler=setTimeout(function(){genro.rpc.ping({reason:'auto'});},genro.auto_polling*1000);},setPolling:function(auto_polling,user_polling){genro.user_polling=user_polling==null?genro._('gnr.polling.user_polling'):user_polling;auto_polling=auto_polling==null?genro._('gnr.polling.auto_polling'):auto_polling;if(auto_polling!=genro.auto_polling){genro.auto_polling=auto_polling;this._call_auto_polling();};},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;var 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;try{async_cb(result,error);}catch(e){console.error(e);throw e;}
return result;});}else{cb=dojo.hitch(this,function(response,ioArgs){ioArgs.syncresult=preprocessor(response,ioArgs);});sync=true;}
var timeout=objectPop(callKwargs,'timeout',50000);var xhrKwargs={'handleAs':handleAs,'timeout':timeout,'load':cb,'error':dojo.hitch(this,'errorHandler'),'sync':sync,'preventCache':preventCache};var deferred=this._serverCall(callKwargs,xhrKwargs,httpMethod);return sync?deferred.ioArgs.syncresult:deferred;},errorHandler:function(response,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){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});}}};},resultHandler:function(response,ioArgs,currentAttr){this.unregister_call(ioArgs);var envelope=new gnr.GnrBag();try{envelope.fromXmlDoc(response,genro.clsdict);}
catch(e){console.log('error in fromXmlDoc');console.log(response);return;}
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 error=envelope.getItem('error');if(!error){var locStatus=envelope.getItem('_localizerStatus');if(locStatus){genro.setLocStatus(locStatus);}
if(currentAttr){var 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();}},getRecordCount:function(field,value,cb){var result=genro.rpc.remoteCall('app.getRecordCount',{'field':field,'value':value},null,'GET',null,cb);return result;},pageIndexUrl:function(){return document.location.pathname;},remoteResolver:function(methodname,params,kw){var kw=kw||{};var cacheTime=kw.cacheTime||-1;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){var 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();}
return objectUpdate(currParams,this.serializeParameters(genro.src.dynamicParameters(kwargs,sourceNode)));},rpcUrl:function(method,kwargs,sourceNode,avoidCache){return genro.absoluteUrl(null,genro.rpc.getRpcUrlArgs(method,kwargs,sourceNode,avoidCache),avoidCache);},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){return;}
var kw=kw||{reason:null};genro.rpc.setPollingStatus(true);var xhrKwargs={'handleAs':'xml','url':'http://'+document.location.host+'/_ping','timeout':10000,'load':dojo.hitch(this,function(response,ioArgs){var result=genro.rpc.resultHandler(response,ioArgs);genro.rpc.setPollingStatus(false);return result;}),'error':dojo.hitch(this,function(response,ioArgs){genro.rpc.errorHandler(response,ioArgs);genro.rpc.setPollingStatus(false);}),'sync':false,'preventCache':false};this._serverCall({page_id:genro.page_id,reason:kw.reason,_no_cache_:genro.getCounter()},xhrKwargs,'GET');},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,'sqlContextName':params._sqlContextName,'virtual_columns':params._virtual_columns};kwargs.method='app.getRelatedRecord';var resolver=new gnr.GnrRemoteResolver(kwargs,isGetter,cacheTime);resolver.updateAttr=true;resolver.onloading=function(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;};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(){this.getParentNode().getValue('reload');};valNode._onChangedValue=dojo.hitch(resolver,reloader);}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}));if(!defaultArgs){}
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){var 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 paramValue=function(param,value){param.push('');param.push(value);param.push('');return param.join(_crlf);};var textParam=function(name,value){var param=[];param.push('Content-Disposition: form-data; name="'+name+'"');param.push('Content-Type: text/plain');return paramValue(param,value);};var fileParam=function(filedata){var param=[];param.push('Content-Disposition: form-data; name="file_handle"; filename="'+file['name']+'"');param.push('Content-Type: application/octet-stream');return paramValue(param,file.getAsBinary());};var addContentLength=function(content){return"Content-Length: "+content.length+_crlf+_crlf+content;};var content=[];content.push('');params['rpc']=kw.method||'rpc.upload_file';params['page_id']=genro.page_id;params['uploaderId']=kw.uploaderId;params['uploadPath']=kw.uploadPath;var sourceNode=kw.uploaderId?genro.nodeById(kw.uploaderId):null;params=this.serializeParameters(genro.src.dynamicParameters(params,sourceNode));for(key in params){content.push(textParam(key,params[key]));}
var boundary='------multipartformboundary'+(new Date).getTime();var sender=new XMLHttpRequest();var errorCb=function(){console.log(arguments);};if(kw.onResult)sender.upload.addEventListener("load",kw.onResult,false);if(kw.onProgress)sender.upload.addEventListener("progress",kw.onProgress,false);if(kw.onError)sender.upload.addEventListener("error",kw.onError||errorCb,false);if(kw.onAbort)sender.upload.addEventListener("abort",kw.onAbort,false);var filereader=new FileReader();var sendData=function(){content.push(fileParam(filereader.result));content=content.join('--'+boundary+_crlf)+boundary+'--'+_crlf;content=addContentLength(content);sender.open("POST",genro.rpc.pageIndexUrl(),true);sender.setRequestHeader("Content-Type",'multipart/form-data; boundary='+boundary);sender.sendAsBinary(content);};filereader.addEventListener("loadend",sendData,false);filereader.readAsBinaryString(file);}});



dojo.require('dijit.Menu');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','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'];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','Grid':'dojox.grid.Grid:dojox.Grid','VirtualGrid':'dojox.grid.VirtualGrid:dojox.VirtualGrid','Calendar':'mywidgets.widget.Calendar,mywidgets.widget.Timezones','GoogleMap':'','GoogleChart':'','GoogleVisualization':'','CkEditor':'','protovis':''};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||-1;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){var attributes=attributes||{};var newobj,domnode;var handler=this.getHandler(tag);if(handler._beforeCreation){var goOn=handler._beforeCreation(sourceNode);if(goOn===false){return false;}}
var domtag=handler._domtag||tag;if(ind=='replace'){domnode=destination;}else if(domtag=='*'){domnode=null;}else{destination=handler._attachTo?dojo.byId(handler._attachTo):destination;domnode=this.makeDomNode(domtag,destination,ind);}
if(typeof(ind)=='object'){ind=-1;}
var tip=objectPop(attributes,'tip');var visible=objectPop(attributes,'visible');if(visible==false){attributes.visibility='hidden';}
var hidden=objectPop(attributes,'hidden');if(hidden==true){attributes.display='none';}
var kw={'postCreation':handler._creating(attributes,sourceNode),'readonly':objectPop(attributes,'readonly'),'_style':objectAsStyle(genro.dom.getStyleDict(attributes,(this.noConvertStyle[tag.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);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);}}}
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)&&sourceNode){var template=objectPop(attributes,'template');if(template){objectPop(attributes,'datasource');innerHTML=dataTemplate(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){domnode.setAttribute(oneattr,attributes[oneattr]);}
if(innerHTML){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;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 validations=objectExtract(attributes,'validate_*');var extracted=objectExtract(attributes,'_*',{'_type':null,'_identifier':null});objectUpdate(attributes,attrmixins);var newobj=new wdgFactory(attributes,domnode);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)||this.wdgIsSelect(sourceNode)){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=warnings.join('<br />');setTimeout(function(){sourceNode.widget.displayMessage(warnings);},1);}});}
this.doMixin(newobj,handler,tag,sourceNode);return newobj;},wdgIsSelect:function(sourceNode){if(sourceNode){return(sourceNode.attr.tag.toLowerCase()in{'dbselect':null,'filteringselect':null});}},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(genro.wdg.wdgIsSelect(this.sourceNode)){}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&&target.className&&dojo.every(validclass.split(','),function(item){return target.className.indexOf(item)<0;})){target=null;}
if(target){var modif=(modifiers||"").replace('*','')||'';if(modif){if(e.shiftKey){modif=modif.replace('shift','');}
if(e.ctrlKey){modif=modif.replace('ctrl','');}
if(e.altKey){modif=modif.replace('alt','');}
if(e.metaKey){modif=modif.replace('meta','');}
modif=modif.replace(/,/g,'').replace(/ /g,'');}
if(modif==''){result=true;};}
return result;}});dojo.declare("gnr.GridEditor",null,{constructor:function(widget,sourceNode,gridEditorNode){var gridEditorColumns=gridEditorNode.getValue();this.grid=widget;var grid=this.grid;this.viewId=sourceNode.attr.nodeId;this.formId=sourceNode.getInheritedAttributes()['formId'];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 columns={};var attr;this.widgetRootNode=gridEditorNode;gridEditorColumns.forEach(function(node){attr=node.attr;if(!attr.gridcell){throw"Missing gridcell parameter";}
columns[attr.gridcell.replace(/\W/g,'_')]={'tag':attr.tag,'attr':attr};});this.columns=columns;gridEditorNode.setValue(null,false);gridEditorNode.attr.tag=null;gridEditorNode.attr.datapath=sourceNode.absDatapath(sourceNode.attr.storepath);var editOn=gridEditorNode.attr.editOn||'onCellDblClick';editOn=stringSplit(editOn,',',2);var modifier=editOn[1];var _this=this;dojo.connect(widget,editOn[0],function(e){if(genro.wdg.filterEvent(e,modifier)){if(grid.editorEnabled&&_this.editableCell(e.cellIndex)&&!grid.gnrediting){dojo.stopEvent(e);if(_this.grid._delayedEditing){clearTimeout(_this.grid._delayedEditing);}
_this.grid._delayedEditing=setTimeout(function(){_this.startEdit(e.rowIndex,e.cellIndex);},1);}}});},onEditCell:function(start){var grid=this.grid;grid.gnrediting=start;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;}},startEdit:function(row,col){var grid=this.grid;var cell=grid.getCell(col);var colname=cell.field;var fldDict=this.columns[colname];var gridcell=fldDict.attr.gridcell;var rowDataNode=grid.dataNodeByIndex(row);var datachanged=false;if(rowDataNode&&rowDataNode._resolver&&rowDataNode._resolver.expired()){datachanged=true;}
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);var attr=objectUpdate({},fldDict.attr);attr.datapath='.'+rowLabel;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};cellNode.innerHTML=null;var cbKeys=function(e){var keyCode=e.keyCode;var keys=genro.PATCHED_KEYS;var widget=this.widget;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);widget.focusNode.blur();}};var gridEditor=this;var cbBlur=function(e){var cellNext=this.widget.cellNext;this.widget.cellNext=null;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}};setTimeout(dojo.hitch(gridEditor,'endEdit',this.widget,deltaDict[cellNext],editingInfo),300);};attr._parentDomNode=cellNode;attr._class=attr._class?attr._class+' widgetInCell':'widgetInCell';attr.connect_keydown=cbKeys;attr.connect_onBlur=cbBlur;attr._autoselect=true;var wdgtag=fldDict.tag;if(attr.autoWdg){var dt=convertToText(cellDataNode.getValue())[0];wdgtag={'L':'NumberTextBox','D':'DateTextbox','R':'NumberTextBox','N':'NumberTextBox','H':'TimeTextBox'}[dt]||'Textbox';}
var editWidgetNode=this.widgetRootNode._(wdgtag,attr).getParentNode();editWidgetNode.editedRowIndex=row;this.onEditCell(true);if(cellDataNode.attr._validationError||cellDataNode.attr._validationWarnings){editWidgetNode._validations={'error':cellDataNode.attr._validationError,'warnings':cellDataNode.attr._validationWarnings};editWidgetNode.updateValidationStatus();};editWidgetNode.widget.focus();editWidgetNode.grid=gridEditor.grid;},endEdit:function(editWidget,delta,editingInfo){var cellNode=editingInfo.cellNode;var contentText=editingInfo.contentText;editWidget.sourceNode._destroy();editingInfo.cellNode.innerHTML=contentText;this.onEditCell(false);if(delta){var rc=this.findNextEditableCell({row:editingInfo.row,col:editingInfo.col},delta);if(rc){this.startEdit(rc.row,rc.col);}}},editableCell:function(col){return(this.grid.getCell(col).field in this.columns);},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));rc.col=col;rc.row=row;return rc;}});



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._index={};this.pendingBuild=[];this.afterBuildCalls=[];this.building=false;this.datatags={'data':null,'dataformula':null,'datascript':null,'datarpc':null,'dataremote':null,'datacontroller':null};this.highlightedNode=null;},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');}}},nodeTrigger:function(kw){if(kw.node.isFreezed()){return;}
this.pendingBuild.push(kw);if(!this.building){this.building=true;while(this.pendingBuild.length>0){var 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){var where=wherenode.widget||wherenode.domNode;if(!where){alert('_trigger_ins error????');}}else{var where=dojo.byId(genro.domRootName);node.domNode=where;}}
var ind=kw.ind;this.buildNode(node,where,ind);},_trigger_del:function(kw){var domNode=kw.node.getDomNode();if(!domNode){return;}
var widget=kw.node.widget;if(widget){var parentWdg=widget.sourceNode.getParentBuiltObj();if(parentWdg&&parentWdg.onDestroyingChild){parentWdg.onDestroyingChild(widget);}
widget.destroyRecursive();}else{var widgets=dojo.query('[widgetId]',domNode);widgets=widgets.map(dijit.byNode);dojo.forEach(widgets,function(widget){widget.destroyRecursive();});dojo._destroyElement(domNode);}
this.refreshSourceIndexAndSubscribers();var node=kw.node;},_trigger_upd:function(kw){var destination=kw.node.getParentBuiltObj();if(!destination){console.log('missing destination in rebuild');};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){var selectedIndex=destination.getSelectedIndex();}
if('removeChild'in destination){destination.removeChild(widget);}
widget.destroyRecursive();}else if(destination._singleChild){destination.destroyDescendants();}
else{if(domNode.parentNode){domNode.parentNode.replaceChild(newNode,domNode);}
widget.destroyRecursive();}}else{if(domNode.parentNode){domNode.parentNode.replaceChild(newNode,domNode);}
var widgets=dojo.query('[widgetId]',domNode);while(widgets.length>0){widgets=widgets.map(dijit.byNode);widgets[0].destroyRecursive();widgets=dojo.query('[widgetId]',domNode);}
while(domNode.childNodes.length>0){dojo._destroyElement(domNode.childNodes[0]);}
ind=newNode;}
this.refreshSourceIndexAndSubscribers();this.buildNode(kw.node,destination,ind);if(destination._checkIfSingleChild){destination._checkIfSingleChild();}
if(selectedIndex){destination.setSelected(selectedIndex);}},buildNode:function(sourceNode,where,ind){this.afterBuildCalls=[];sourceNode.build(where,ind);var cb;while(this.afterBuildCalls.length>0){cb=this.afterBuildCalls.pop();cb.call();}},getSource:function(path){if(path){return this._main.getItem('main.'+path);}
else{return this._main.getItem('main');}},getNode:function(obj,autocreate){var 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;},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);},refreshSourceIndexAndSubscribers:function(){var oldSubscribedNodes=this._subscribedNodes;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){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.unsubscribe(oldSubscribedNodes[subscriber][attr]);}}}},dynamicParameters:function(source,sourceNode){var obj={};var path;if((source!='')&(typeof source=='string')){source=genro.evaluate(source);}
if(source){for(var prop in source){var val=source[prop];if(typeof(val)=='string'){var dynval=stringStrip(val);if(dynval.indexOf('==')==0){val=funcApply("return "+dynval.slice(2),source,sourceNode)}else if((dynval.indexOf('^')==0)||(dynval.indexOf('=')==0)){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;}}
return obj;},create:function(widget,pars,path){var path=path||'_temp.'+this.getNode()._id;var source=genro.src.getNode(path).getParentBag();source.delItem('#0');return source._(widget,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.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())){n.widget.selectionKeeper('save');var cols=n.widget.query_columns.split(',');dojo.forEach(cols,function(c){columns[c]=c;});}}},'static')
var result='';for(var k in columns){result+=k+',';}
return result;};gnr.columnsFromStruct=function(struct,columns){if(columns==undefined){columns=[];}
if(!struct){return'';}
var nodes=struct.getNodes();for(var i=0;i<nodes.length;i++){var node=nodes[i];if(node.attr['calculated']){continue;}
var fld=node.attr.field;if(fld){if((!stringStartsWith(fld,'$'))&&(!stringStartsWith(fld,'@'))){fld='$'+fld;}
arrayPushNoDup(columns,fld);if(node.attr.zoomPkey){var zoomPkey=node.attr.zoomPkey;if((!stringStartsWith(zoomPkey,'$'))&&(!stringStartsWith(zoomPkey,'@'))){zoomPkey='$'+zoomPkey;}
arrayPushNoDup(columns,zoomPkey);}}
if(node.getValue()instanceof gnr.GnrBag){gnr.columnsFromStruct(node.getValue(),columns);}}
return columns.join(',');};gnr.menuFromBag=function(bag,appendTo,menuclass,basepath){var menuline,attributes;var bagnodes=bag.getNodes();for(var i=0;i<bagnodes.length;i++){var bagnode=bagnodes[i];attributes=objectUpdate({},bagnode.attr);attributes.label=attributes.caption||attributes.label||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){var 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);},_doChangeInData:function(domnode,sourceNode,value,valueAttr){var valueAttr=valueAttr||null;var path=sourceNode.attrDatapath('value');genro._data.setItem(path,value,valueAttr,{'doTrigger':sourceNode});},_makeInteger:function(attributes,proplist){dojo.forEach(proplist,function(prop){if(prop in attributes){attributes[prop]=attributes[prop]/1;}});},_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={};objectExtract(attributes,'onDrop,onDrag,dragTag,dropTag,dragTypes,dropTypes');objectExtract(attributes,'onDrop_*');savedAttrs['dropTarget']=objectPop(attributes,'dropTarget');savedAttrs['dropTargetCb']=objectPop(attributes,'dropTargetCb');savedAttrs.connectedMenu=objectPop(attributes,'connectedMenu');savedAttrs.onEnter=objectPop(attributes,'onEnter');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.zoomFactor){savedAttrs['zoomFactor']=objectPop(attributes,'zoomFactor');sourceNode.setZoomFactor=function(factor){if(typeof(factor)=='string'&&factor[factor.length-1]=='%'){factor=factor.slice(0,factor.length-1)/100;}
domNode=this.getDomNode();dojo.style(domNode,'zoom',factor);dojo.style(domNode,'MozTransformOrigin','top left');dojo.style(domNode,'MozTransform','scale('+factor+')');};}
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'];}}
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){this.created(newobj,savedAttrs,sourceNode);if(savedAttrs.connectedMenu){var menu=savedAttrs.connectedMenu;var domNode=newobj.domNode||newobj;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.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){var 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){if(parentNode.attr.tag.toLowerCase()=='tabcontainer'){objectFuncReplace(newobj,'setTitle',function(title){if(title){if(this.controlButton){this.controlButton.setLabel(title);}}});}
else if(parentNode.attr.tag.toLowerCase()=='accordioncontainer'){objectFuncReplace(newobj,'setTitle',function(title){this.titleTextNode.innerHTML=title;});}};if(savedAttrs.onEnter){var callback=dojo.hitch(sourceNode,funcCreate(savedAttrs.onEnter));var kbhandler=function(evt){if(evt.keyCode==genro.PATCHED_KEYS.ENTER){evt.target.blur();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(sourceNode.attr['hasGhost']){var _textbox=newobj.textbox;dojo.connect(newobj.textbox,'onfocus',function(e){genro.dom.ghostOnEvent(e);});dojo.connect(newobj.textbox,'onblur',function(e){genro.dom.ghostOnEvent(e);});dojo.connect(newobj.textbox,'onkeyup',function(e){genro.dom.ghostOnEvent(e);});dojo.connect(newobj,'setValue',function(value){genro.dom.ghostOnEvent({type:'setvalue',value:value,obj:newobj});});dojo.connect(newobj,'onChange',function(value){genro.dom.ghostOnEvent({type:'setvalue',value:value,obj:newobj});});}},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;}});dojo.declare("gnr.widgets.iframe",gnr.widgets.baseHtml,{creating:function(attributes,sourceNode){sourceNode.savedAttrs=objectExtract(attributes,'rowcount,tableid,src,rpcCall,onLoad');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));}
this.setSrc(newobj,savedAttrs.src);},prepareSrc:function(domnode){var sourceNode=domnode.sourceNode;var attributes=sourceNode.attr;if(attributes['src']){return sourceNode.getAttributeFromDatasource('src');}else if(attributes['rpcCall']){params=objectExtract(attributes,'rpc_*',true);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 sourceNode=domnode.sourceNode;if(sourceNode.attr._if&&!sourceNode.getAttributeFromDatasource('_if')){var v='';}else if(sourceNode.condition_function&&!sourceNode.condition_function(sourceNode.condition_value)){var v='';}
else{var v=v||this.prepareSrc(domnode);}
if(sourceNode.currentSetTimeout){clearTimeout(sourceNode.currentSetTimeout);}
if(v){sourceNode.currentSetTimeout=setTimeout(function(d,url){var absUrl=document.location.protocol+'//'+document.location.host+url;if(absUrl!=d.src){if(d.src&&sourceNode.attr.onUpdating){sourceNode.attr.onUpdating();}
d.src=url;}},sourceNode.attr.delay||1,domnode,v);}}});dojo.declare("gnr.widgets.baseDojo",gnr.widgets.baseHtml,{_defaultEvent:'onClick',constructor:function(application){this._domtag='div';this._dojowidget=true;},_doChangeInData:function(domnode,sourceNode,value,valueAttr){if(sourceNode._modifying){return;}
var path=sourceNode.attrDatapath('value');var datanode=genro._data.getNode(path,null,true);if(datanode.getValue()===value){return;}
var validateresult;valueAttr=objectUpdate(objectUpdate({},datanode.attr),valueAttr);if(sourceNode.hasValidations()){validateresult=sourceNode.validationsOnChange(sourceNode,value);value=validateresult['value'];objectExtract(valueAttr,'_validation*');if(validateresult['error']){valueAttr._validationError=validateresult['error'];}
if(validateresult['warnings'].length){valueAttr._validationWarnings=validateresult['warnings'];}}
value=this.convertValueOnBagSetItem(sourceNode,value);genro._data.setItem(path,value,valueAttr,{'doTrigger':sourceNode});},mixin_setTip:function(tip){this.setAttribute('title',tip);},convertValueOnBagSetItem:function(sourceNode,value){return value;},mixin_setDraggable:function(value){this.domNode.setAttribute('draggable',value);},mixin_setDropTarget:function(value){this.sourceNode.dropTarget=value;},validatemixin_validationsOnChange:function(sourceNode,value){var result=genro.vld.validate(sourceNode,value,true);if(result['modified']){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;},mixin_mainDomNode:function(){return this.inputNode||this.textInputNode||this.domNode;},connectChangeEvent:function(widget){if('onChange'in widget){dojo.connect(widget,'onChange',dojo.hitch(this,function(val){this.onChanged(widget,val);}));}},onChanged:function(widget,value){this._doChangeInData(widget.domNode,widget.sourceNode,value);},setUrlRemote:function(widget,method,arguments){var url=genro.rpc.rpcUrl(method,arguments);widget.setHref(url);},mixin_setVisible:function(visible){dojo.style(this.domNode,'visibility',(visible?'visible':'hidden'));},mixin_setHidden:function(hidden){dojo.style(this.domNode,'display',(hidden?'none':''));},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';},creating:function(attributes,sourceNode){objectPop(attributes,'parentDialog');objectPop(attributes,'centerOn');objectPop(attributes,'position');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'){dojo.connect(widget,"show",widget,function(){if(this!=genro.dialogStack.slice(-1)[0]){var ds=genro.dialogStack
ds.push(this);var zIndex=widget.sourceNode.attr.z_index||(500+ds.length*2);dojo.style(this._underlay.domNode,'zIndex',zIndex);dojo.style(this.domNode,'zIndex',zIndex+1);if(genro.dialogStack.length>1){var parentDialog=genro.dialogStack.slice(-2)[0];dojo.forEach(parentDialog._modalconnects,dojo.disconnect);parentDialog._modalconnects=[];}}});dojo.connect(widget,"hide",widget,function(){if(this==genro.dialogStack.slice(-1)[0]){genro.dialogStack.pop();if(genro.dialogStack.length>0){var parentDialog=genro.dialogStack.slice(-1)[0];parentDialog._modalconnects.push(dojo.connect(window,"onscroll",parentDialog,"layout"));parentDialog._modalconnects.push(dojo.connect(dojo.doc.documentElement,"onkeypress",parentDialog,"_onKey"));}}});}
genro.dragDropConnect(widget.domNode);if(genro.isDeveloper){genro.dev.inspectConnect(widget.domNode);}},versionpatch_11__position:function(){var centerOn=this.sourceNode.attr.centerOn;if(!centerOn){this._position_replaced();}
else{genro.dom.centerOn(this.domNode,centerOn);}},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){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';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'value');return savedAttrs;},created:function(newobj,savedAttrs,sourceNode){if(savedAttrs.value){newobj.setValue(savedAttrs.value);};dojo.connect(newobj.domNode,'onchange',dojo.hitch(this,function(){this.onChanged(newobj);}));},onChanged:function(widget){var value=widget.getValue();this._doChangeInData(widget.domNode,widget.sourceNode,value);}});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);});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_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_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);}}
if(nodeId){genro.publish(nodeId+'_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){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_onDestroyingChild:function(child){this.removeChild(child);},onRemoveChild:function(widget,child){var pageName=child.sourceNode.attr.pageName;if(pageName){objectPop(widget.gnrPageDict,pageName);}}});dojo.declare("gnr.widgets.TabContainer",gnr.widgets.StackContainer,{___created:function(widget,savedAttrs,sourceNode){},___onAddChild:function(widget,child){},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){dojo.connect(widget,'startup',dojo.hitch(this,'afterStartup',widget));if(dojo_version=='1.7'){dojo.connect(widget,'addChild',dojo.hitch(this,'onAddChild',widget));}},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){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]});};}},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._splitterThickness[region]==0);}
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;var st=dojo.style(splitterNode,'display',disp);}
dojo.style(regionNode,'display',disp);this._layoutChildren();}
return show;}});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.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");},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.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(sourceNode.attr.label=='-'){this._dojotag='MenuSeparator';}
if(attributes.checked){attributes.iconClass='tick_icon10';}
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';}}}
return savedAttrs;},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 originalTarget=this.getParent().originalContextTarget;var ctxSourceNode;var sourceNode=this.sourceNode;if(!originalTarget){ctxSourceNode=sourceNode;}else{if(originalTarget.sourceNode){ctxSourceNode=originalTarget.sourceNode;}
else{ctxSourceNode=dijit.getEnclosingWidget(originalTarget).sourceNode;}}
var inAttr=sourceNode.getInheritedAttributes();var actionScope=sourceNode;var action=inAttr.action;if(ctxSourceNode&&ctxSourceNode.attr.action){action=ctxSourceNode.attr.action;actionScope=ctxSourceNode;}
f=funcCreate(action);if(f){f.call(actionScope,sourceNode.getAttr(),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);}});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');if(savedAttrs.storepath){sourceNode.registerDynAttr('storepath');}
if(!attributes.connectId){savedAttrs['connectToParent']=true;}
return savedAttrs;},created:function(widget,savedAttrs,sourceNode){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());}}}
if(sourceNode&&savedAttrs['connectToParent']){var parentNode=sourceNode.getParentBag().getParentNode();var parentWidget=parentNode.widget;if(parentWidget){if(!(('dropDown'in parentWidget)||('popup'in parentWidget))){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){dojo.forEach(this._bindings,function(b){dojo.forEach(b,dojo.disconnect);});delete this._bindings;}
this.destroy_replaced.call(this);},versionpatch_11__contextMouse:function(e){this.originalContextTarget=e.target;var sourceNode=this.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();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);}}}
if((e.button==2)&&(!this.modifiers)){this._contextMouse_replaced.call(this,e);}
else if(this.modifiers&&genro.wdg.filterEvent(e,this.modifiers,this.validclass)){this._contextMouse_replaced.call(this,e);var wdg=sourceNode.widget;wdg._openMyself_replaced.call(wdg,e);}},versionpatch_15__openMyself:function(e){this.originalContextTarget=e.target;var sourceNode=this.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);}}}
if((e.button==2)&&(!this.modifiers)){this._openMyself_replaced.call(this,e);}
else if(this.modifiers&&genro.wdg.filterEvent(e,this.modifiers,this.validclass)){this._openMyself_replaced.call(this,e);}},versionpatch_11__openMyself:function(e){if((e.button==2)&&(!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);}});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');if(callback){attributes['label']=funcCreate(callback,'n',sourceNode);}
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){if(genro.wdg.filterEvent(e,this.modifiers,this.validclass)){this._onHover_replaced.call(this,e);}},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.Button",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='Button';},creating:function(attributes,sourceNode){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['publish']=objectPop(attributes,'publish');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onClick',sourceNode,this.onClick);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']);}},onClick:function(e){var modifier=eventToString(e);var action=this.getInheritedAttributes().action;if(action){funcApply(action,objectUpdate(this.currentAttributes(),{event:e}),this);}
if(this.attr.fire){var s=eventToString(e)||true;this.setRelativeData(this.attr.fire,s,{modifier:modifier},true);}
if(this.attr.publish){genro.publish(this.attr.publish,true);}
var fire_list=objectExtract(this.attr,'fire_*',true);for(var fire in fire_list){this.setRelativeData(fire_list[fire],fire,{modifier:modifier},true);}},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){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);}},mixin_displayMessage:function(){},patch_onClick:function(e){var action=this.sourceNode.getInheritedAttributes().action;if(action){dojo.hitch(this,funcCreate(action))(this.sourceNode.attr,this.sourceNode,e);}},patch_setValue:function(value,pc){this.setAttribute('checked',value);}});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.DateTextBox",gnr.widgets.baseDojo,{onChanged:function(widget,value){if(value){this._doChangeInData(widget.domNode,widget.sourceNode,value,{dtype:'D'});}
else{this._doChangeInData(widget.domNode,widget.sourceNode,null);}},constructor:function(){this._domtag='input';this._dojotag='DateTextBox';},creating:function(attributes,sourceNode){if('popup'in attributes&&(objectPop(attributes,'popup')==false)){attributes.popupClass=null;}}});dojo.declare("gnr.widgets.TextBox",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='input';this._dojotag='ValidationTextBox';},creating:function(attributes,sourceNode){var savedAttrs={};attributes.trim=(attributes.trim==false)?false:true;return savedAttrs;},created:function(widget,savedAttrs,sourceNode){this.connectFocus(widget,savedAttrs,sourceNode);},connectFocus:function(widget,savedAttrs,sourceNode){if(sourceNode.attr._autoselect){dojo.connect(widget,'onFocus',widget,function(e){setTimeout(dojo.hitch(this,'selectAllInputText'),1);});}},mixin_selectAllInputText:function(){dijit.selectInputText(this.focusNode);}});dojo.declare("gnr.widgets.TimeTextBox",gnr.widgets.baseDojo,{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.baseDojo,{constructor:function(application){this._domtag='input';this._dojotag='NumberTextBox';},creating:function(attributes,sourceNode){attributes._class=attributes._class?attributes._class+' numberTextBox':'numberTextBox';attributes.constraints=objectExtract(attributes,'min,max,places,pattern,round,currency,fractional,symbol,strict,locale');if('ftype'in attributes){attributes.constraints['type']=objectPop(attributes['ftype']);};},convertValueOnBagSetItem:function(sourceNode,value){if(value===""){value=null;}
return value;}});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.Grid",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='Grid';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;}};}}},mixin_setStructpath:function(val,kw){this.structBag=genro.getData(this.sourceNode.attrDatapath('structpath'));this.cellmap={};this.setStructure(this.gnr.structFromBag(this.sourceNode,this.structBag,this.cellmap));this.onSetStructpath(this.structBag);},mixin_setDraggable_column:function(draggable){if(draggable===undefined){var draggable=this.sourceNode.getAttributeFromDatasource('draggable_column');}
dojo.query('[role="wairole:columnheader"]',this.domNode).forEach(function(n){n.draggable=true;});},mixin_setDraggable_row:function(draggable,view){var view=view||this.views.views[0];var 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=true;});},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;genro.formById(this.sourceNode.attr.linkedForm).openForm(idx,this.rowIdByIndex(idx));},mixin_linkedFormLoad:function(e){var idx=e.rowIndex;genro.formById(this.sourceNode.attr.linkedForm).load({destPkey:this.rowIdByIndex(idx),destIdx: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;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 onDropCall=function(dropInfo,rows){if(!('row'in dropInfo)||(dropInfo.row<0)){return;}
if(sourceNode.attr.onSelfDropRows){sourceNode.attr.onSelfDropRows(rows,dropInfo);}
else{dropInfo.widget.moveRow(rows,dropInfo.row);var 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.attr.nodeId=sourceNode.attr.nodeId||'grid_'+sourceNode.getStringId();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){this.selfDragColumnsPrepare(sourceNode);}
var savedAttrs=objectExtract(attributes,'selected*');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='autoHeight,autoRender,autoWidth,defaultHeight,elasticView,fastScroll,keepRows,model,rowCount,rowsPerPage,singleClickEdit,structure,';attributesToKeep=attributesToKeep+'datamode,sortedBy,filterColumn,excludeCol,excludeListCb,editorEnabled';var gridAttributes=objectExtract(attributes,attributesToKeep);objectPopAll(attributes);objectUpdate(attributes,gridAttributes);attributes._identifier=identifier;return savedAttrs;},creating_structure:function(attributes,sourceNode){var structBag=sourceNode.getRelativeData(sourceNode.attr.structpath);if(structBag){sourceNode.baseStructBag=structBag.deepCopy();}
if(genro.grid_configurator){structBag=genro.grid_configurator.onStructCreating(sourceNode,structBag);}
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();if(genro.grid_configurator){dojo.connect(widget,'newDataStore',function(){if(sourceNode.attr.configurable&&!sourceNode._gridConfiguratorBuilt){genro.grid_configurator.addGridConfigurator(sourceNode);}});}
if(gridContent instanceof gnr.GnrBag){var gridEditorNode=gridContent.getNodeByAttr('tag','grideditor',true);if(gridEditorNode){widget.gridEditor=new gnr.GridEditor(widget,sourceNode,gridEditorNode);};};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('draggable_column'in sourceNode.attr){dojo.connect(widget,'postrender',dojo.hitch(widget,'setDraggable_column'));}
if(sourceNode.attr.openFormEvent){dojo.connect(widget,sourceNode.attr.openFormEvent,widget,'openLinkedForm');if(genro.isTouchDevice){dojo.connect(widget,'longTouch',widget,'openLinkedForm');}}
objectFuncReplace(widget.selection,'clickSelectEvent',function(e){this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);});dojo.subscribe(nodeId+'_reload',widget,function(keep_selection){this.reload(keep_selection!==false)});dojo.subscribe(nodeId+'_serverAction',widget,function(kw){if(this.serverAction){this.serverAction(kw);}});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);setTimeout(function(){cb.call(widget)},1);}
dojo.subscribe(searchBoxCode+'_changedValue',widget,function(v,field){this.applyFilter(v,null,field);});};},_getFilterAutoValues:function(widget,dtypes){var structbag=widget.structbag();var values=[];var auto=[];values.push(null)
var cellsbag=widget.structbag().getItem('#0.#0');var caption,cellattr,cell_cap,cell_field,fltList,colList,col;cellsbag.forEach(function(n){cellattr=n.attr;cell_cap=cellattr.name||cellattr.field;cell_field=cellattr.field;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.afterBuildCalls.push(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__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);if(objectNotEmpty(selattr)){var row=this.rowByIndex(idx);var value;for(var sel in selattr){if(idx>=0){value=row[sel];}else{value=null;}
var path=this.sourceNode.setRelativeData(selattr[sel],value);}}
if(this.sourceNode.attr.selectedIndex){this.sourceNode.setAttributeInDatasource('selectedIndex',((idx<0)?null:idx),null,null,true);}
if(this.sourceNode.attr.selectedPkeys){this.sourceNode.setAttributeInDatasource('selectedPkeys',this.getSelectedPkeys(),null,null,true);}
if(this.sourceNode.attr.selectedRowidx){this.sourceNode.setAttributeInDatasource('Rowidx',this.getSelectedRowidx(),null,null,true);}
if(this.sourceNode.attr.selectedNodes){var nodes=this.getSelectedNodes();if(nodes){var selNodes=new gnr.GnrBag();dojo.forEach(nodes,function(node){selNodes.setItem(node.label,null,node.getAttr());});}
var path=this.sourceNode.attrDatapath('selectedNodes');genro.setData(path,selNodes,{'count':selNodes.len()});}
if(this.sourceNode.attr.selectedId){var selectedId=null;var row={};if(idx>=0){selectedId=this.rowIdentity(this.rowByIndex(idx));var row=this.rowByIndex(idx);}
this.sourceNode.setAttributeInDatasource('selectedId',selectedId,null,row,true);}
this.sourceNode.publish('onSelectedRow',{'idx':idx,'selectedId':idx>=0?this.rowIdentity(this.rowByIndex(idx)):null,'grid':this})},mixin_indexByRowAttr:function(attrName,attrValue,op,backward){var op=op||'==';if(backward){for(var i=this.rowCount-1;i>=0;i--){var row=this.rowByIndex(i);if(genro.compareDict[op].call(this,row[attrName],attrValue,op)){return i;}};}
else{for(var i=0;i<this.rowCount;i++){var row=this.rowByIndex(i);if(genro.compareDict[op].call(this,row[attrName],attrValue,op)){return i;}}}
return-1;},mixin_indexByCb:function(cb,backward){if(backward){for(var i=this.rowCount-1;i>=0;i--){if(cb(this.rowByIndex(i))){return i;}};}
else{for(var i=0;i<this.rowCount;i++){if(cb(this.rowByIndex(i))){return 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){var selection=this.selection;if(typeof(attrValue)=='object'){selection.unselectAll();var grid=this;dojo.forEach(attrValue,function(v){selection.addToSelection(grid.indexByRowAttr(attrName,v));});}else{selection.select(this.indexByRowAttr(attrName,attrValue,op));}},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(noneIsAll){var sel=this.selection.getSelected();var result=[];if(sel.length>0){for(var i=0;i<sel.length;i++){result.push(this.rowIdByIndex(sel[i]));}}else if(noneIsAll){for(var i=0;i<this.rowCount;i++){result.push(this.rowIdByIndex(i));}}
return result;},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:function(sourceNode,struct,cellmap){var cellmap=cellmap||{};var result=[];var _cellFormatter=function(formatOptions,cellClassCB){var opt=objectUpdate({},formatOptions);var cellClassFunc;if(cellClassCB){cellClassFunc=funcCreate(cellClassCB,'cell,v,inRowIndex');}
return function(v,inRowIndex){if(cellClassFunc){cellClassFunc(this,v,inRowIndex);}
opt['cellPars']={rowIndex:inRowIndex};var zoomPage=opt['zoomPage'];if(typeof(v)=='number'&&v<0){this.customClasses.push('negative_number');}
if(this.grid.gridEditor&&this.grid.gridEditor.invalidCell(this,inRowIndex)){this.customClasses.push('invalidCell');}
v=genro.format(v,opt);if(v==null){return'&nbsp;';}
var template=opt['template'];if(template){v=template.replace(/#/g,v);}
if(opt['js']){v=opt['js'](v,this.grid.storebag().getNodes()[inRowIndex]);};if(zoomPage){var zoomPkey=opt['zoomPkey'];if(zoomPkey){zoomPkey=zoomPkey.replace(/\W/g,'_');}
var key=this.grid.currRenderedRow[zoomPkey?zoomPkey:this.grid._identifier];v="<a onclick='if((genro.isMac&&!event.metaKey)||(!genro.isMac&&!event.ctrlKey)){dojo.stopEvent(event);}' class='gnrzoomcell' href='/"+zoomPage+"?pkey="+key+"&autoLinkFrom="+genro.page_id+"'>"+v+"</a>";}
var draggable=this.draggable?' draggable=true ':'';return'<div '+draggable+'class="cellContent">'+v+'</div>';};};if(struct){var bagnodes=struct.getNodes();var formats,dtype,editor;var view,viewnode,rows,rowsnodes,i,k,j,cellsnodes,row,cell,rowattrs,rowBag;var localTypes={'R':{places:2},'L':{places:0},'I':{places:0},'D':{date:'short'},'H':{time:'short'},'DH':{datetime:'short'}};for(i=0;i<bagnodes.length;i++){viewnode=bagnodes[i];view=objectUpdate({},viewnode.attr);delete view.tag;rows=[];rowsnodes=viewnode.getValue().getNodes();for(k=0;k<rowsnodes.length;k++){rowattrs=objectUpdate({},rowsnodes[k].attr);rowattrs=objectExtract(rowattrs,'classes,headerClasses,cellClasses');rowBag=rowsnodes[k].getValue();if(!(rowBag instanceof gnr.GnrBag)){rowBag=new gnr.GnrBag();rowsnodes[k].setValue(rowBag,false);}
if(genro.isTouchDevice){var cellattr={'format_isbutton':true,'format_buttonclass':'zoomIcon buttonIcon','format_onclick':'this.widget.openLinkedForm(kw);','width':'30px','calculated':true,'field':'_edit_record','name':' '};rowBag.setItem('cell_editor',null,cellattr,{doTrigger:false});}
cellsnodes=rowBag.getNodes();row=[];for(j=0;j<cellsnodes.length;j++){cell=objectUpdate({},rowattrs);cell=objectUpdate(cell,cellsnodes[j].attr);dtype=cell.dtype;cell.original_field=cell.field;if(cell.field){cell.field=cell.field.replace(/\W/g,'_');if(dtype){cell.cellClasses=(cell.cellClasses||'')+' cell_'+dtype;}
cell.cellStyles=objectAsStyle(objectUpdate(objectFromStyle(cell.cellStyles),genro.dom.getStyleDict(cell,['width'])));formats=objectExtract(cell,'format_*');format=objectExtract(cell,'format');var zoomPage=objectPop(cell,'zoomPage');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(zoomPage)
formats['zoomPage']=zoomPage;formats['zoomPkey']=objectPop(cell,'zoomPkey');if(format){formats['format']=format;}
if(cell.counter){sourceNode.attr.counterField=cell.field;dtype='L';}
if(cell.hidden){cell.classes=(cell.classes||'')+' hiddenColumn';}
if(dtype){formats=objectUpdate(objectUpdate({},localTypes[dtype]),formats);}
var cellClassCB=objectPop(cell,'cellClassCB');cell.formatter=_cellFormatter(formats,cellClassCB);delete cell.tag;row.push(cell);cellmap[cell.field]=cell;}}
rows.push(row);}
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);colsBag.setItem(nodeToMove.label,null,nodeToMove.attr,{'_position':toPos});}},mixin_moveRow:function(row,toPos){if(toPos!=row){var storebag=this.storebag();storebag.moveNode(row,toPos);}},mixin_addColumn:function(col,toPos){var colsBag=this.structBag.getItem('#0.#0');colsBag.setItem('cellx_'+genro.getCounter(),null,{'width':'8em','name':col.fullcaption,'dtype':col.dtype,'field':col.fieldpath,'tag':'cell'},{'_position':toPos+1});},onDragStart:function(dragInfo){var dragmode=dragInfo.dragmode;var event=dragInfo.event;var widget=dragInfo.widget;var value={};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 valTextPlain=[];var valTextXml=[];var valTextHtml=[];var innerHtml=[];var idx=0;dojo.forEach(sel,function(k){var rdata=widget.rowByIndex(k);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>');});innerHtml.push(widget.views.views[0].rowNodes[k].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(sel.length>1){var auxDragImage=dragInfo.dragImageNode=dojo.byId('auxDragImage');dragInfo.dragImageNode=document.createElement('div');dragInfo.dragImageNode.innerHTML=innerHtml.join('');dojo.addClass(dragInfo.dragImageNode,'draggedItem rowsetdragging');auxDragImage.appendChild(dragInfo.dragImageNode);dragInfo.event.dataTransfer.setDragImage(auxDragImage,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]:'';columndata.push(v);textcol=textcol+convertToText(v)[1]+'\n';};value['gridcolumn']={'column':dragInfo.column,'columndata':columndata,'gridId':widget.sourceNode.attr.nodeId};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'){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;for(var k in dropModes){if(dojo.filter(dropModes[k].split(','),function(value){return arrayMatch(draggedTypes,value).length>0;}).length>0){dropmode=k;break;};}
dropmode=dropmode||dragSourceInfo.dragmode;if(!dropmode&&(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&&(dojo.indexOf(draggedTypes,'selfdracolumn_'+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(widget.grid){widget.content.decorateEvent(event);widget=widget.grid;}else{widget.views.views[0].header.decorateEvent(event);}
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;}}
dropInfo.widget=widget;dropInfo.sourceNode=widget.sourceNode;},fillDragInfo:function(dragInfo){var event=dragInfo.event;var widget=dragInfo.widget;if(widget.grid){widget.content.decorateEvent(event);widget=widget.grid;}else{widget.views.views[0].header.decorateEvent(event);}
dragInfo.column=event.cellIndex;dragInfo.row=event.rowIndex;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];}
dragInfo.widget=widget;dragInfo.sourceNode=widget.sourceNode;},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.Grid,{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(){return true;};},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._customClasses){var customClasses=null;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;}}
this.onStyleRow_replaced(row);}});dojo.declare("gnr.widgets.VirtualStaticGrid",gnr.widgets.Grid,{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');},created:function(widget,savedAttrs,sourceNode){this.created_common(widget,savedAttrs,sourceNode);genro.src.afterBuildCalls.push(dojo.hitch(widget,'render'));dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');widget.updateRowCount('*');},attributes_mixin_get:function(inRowIndex){var rowdata=this.grid.rowCached(inRowIndex);if(!rowdata){console.log('no rowdata:',rowdata);}
return this._customGetter?this._customGetter.call(this,rowdata):rowdata[this.field];},mixin_rowCached:function(inRowIndex){if(this.currRenderedRowIndex!==inRowIndex){this.currRenderedRowIndex=inRowIndex;this.currRenderedRow=this.rowByIndex(inRowIndex);}
return this.currRenderedRow;},attributes_mixin_canSort:function(){return('canSort'in this.sourceNode.attr)?this.sourceNode.attr.canSort:true;},mixin_filterToRebuild:function(value){if(this._filtered){this._filterToRebuild=value;}},mixin_invalidFilter:function(){return this._filterToRebuild;},mixin_resetFilter: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=(this.filterColumn.indexOf('+')>0)?'T':(this.cellmap[this.filterColumn]['dtype']||'A');this.createFiltered(this.currentFilterValue,this.filterColumn,colType);if(!rendering){this.updateRowCount('*');}},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(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"});}
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();}
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_newDataStore:function(val,kw){this.updateRowCount(0);this.resetFilter();if(this.sortedBy){var storebag=this.storebag();storebag.sort(this.sortedBy);}
this.updateRowCount();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);}},mixin_setStorepath:function(val,kw){if((!this._updatingIncludedView)&&(!this._batchUpdating)){if(kw.evt=='fired'){var storepath=this.sourceNode.absDatapath(this.sourceNode.attr.storepath);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);this.updateRow(rowIdx);}else{this.newDataStore();}}else if(kw.evt=='ins'){if(parent_lv==1||(parent_lv==2&&this.datamode=='bag')){this.updateRowCount();this.setSelectedIndex(kw.ind);}else{}}else if(kw.evt=='del'){if(parent_lv==1){this.updateRowCount();this.setSelectedIndex(kw.ind);}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);}},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_setRefreshOn:function(){},patch_onStyleRow:function(row){var attr=this.rowCached(row.index);if(attr._customClasses){var customClasses=null;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;}
this.onStyleRow_replaced(row);},mixin_canEdit:function(inCell,inRowIndex){return false;},patch_onStartEdit:function(inCell,inRowIndex){},patch_onApplyCellEdit:function(inValue,inRowIndex,inFieldIndex){console.log('patch_onApplyCellEdit');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){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.storeRowCount();}
this.currRenderedRowIndex=null;this.currRenderedRow=null;this.updateRowCount_replaced(n);},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.sourceNode.absDatapath(this.sourceNode.attr.storepath);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){if(flag=='save'){var prevSelectedIdentifiers=[];var identifier=this._identifier;dojo.forEach(this.getSelectedNodes(),function(node){if(node){prevSelectedIdentifiers.push(node.attr[identifier]);};});this.prevSelectedIdentifiers=prevSelectedIdentifiers;this.prevScrollTop=this.scrollTop;}else if(flag=='clear'){this.prevSelectedIdentifiers=null;}else if(flag=='load'){if((this.prevSelectedIdentifiers)&&(this.prevSelectedIdentifiers.length>0)){this.selectByRowAttr(this._identifier,this.prevSelectedIdentifiers);this.prevSelectedIdentifiers=null;if(this.prevScrollTop){this.setScrollTop(this.prevScrollTop);this.prevScrollTop=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');if(selectionNode){this.filterToRebuild(true);selectionNode.fireNode();}}
if(nodeId){genro.publish(nodeId+'_data_loaded');}},mixin_onSetStructpath:function(structBag){this.query_columns=this.gnr.getQueryColumns(this.sourceNode,structBag);},mixin_absIndex:function(inRowIndex){if(this.invalidFilter()){console.log('invalid filter');}
return this._filtered?this._filtered[inRowIndex]:inRowIndex;},mixin_storeRowCount:function(){if(this._filtered){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++){result.push(this.dataNodeByIndex(sel[i]));}
return result;},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'&&!this.gridEditor){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){var chNode=storebag.getNode(rowLabel);var cellAttr,value,gridfield;var currAttr=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;}};}
return storebag.index(rowLabel);},mixin_editBagRow:function(r,delay){var r=r||this.selection.selectedIndex;var rc=this.gridEditor.findNextEditableCell({row:r,col:-1},{r:0,c:1});var grid=this;if(rc){if(delay){if(this._delayedEditing){clearTimeout(this._delayedEditing);}
this._delayedEditing=setTimeout(function(){grid.gridEditor.startEdit(rc.row,rc.col);},delay);}else{this.gridEditor.startEdit(rc.row,rc.col);}}},mixin_newBagRow:function(defaultArgs){var defaultArgs=defaultArgs||{}
var newRowDefaults=this.sourceNode.attr.newRowDefaults
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);}}
return newrow;},mixin_updateCounterColumn:function(){var storebag=this.storebag();var cb;var k=0;var changes=[];var serializableChanges=[];var that=this;var counterField=this.sourceNode.attr.counterField;if(!counterField){return;}
if(this.datamode=='bag'||this.gridEditor){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){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;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||{};if(pos=='*'){var curSelRow=this.absIndex(this.selection.selectedIndex);if(curSelRow<0){pos=event.shiftKey?0:storebag.len();}else{pos=event.shiftKey?curSelRow:curSelRow+1;}}
var kw={'_position':pos};storebag.setItem(label,newnode,null,kw);this.updateCounterColumn();return kw._new_position;},mixin_delBagRow:function(pos,many,params){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{pos=(pos=='*')?this.absIndex(this.selection.selectedIndex):pos;removed.push(storebag.popNode('#'+pos));}
removed.reverse();this.filterToRebuild(true);this.updateCounterColumn();this.updateRowCount('*');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){if(this.gnrediting){}else if(dijit.getEnclosingWidget(e.target)==this){this.onKeyDown(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);var addCheckBoxColumn=sourceNode.attr.addCheckBoxColumn;if(addCheckBoxColumn){var kw=addCheckBoxColumn==true?null:addCheckBoxColumn;this.addCheckBoxColumn(kw,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);}},mixin_absStorepath:function(){return this.sourceNode.absDatapath(this.sourceNode.attr.storepath);},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){var fieldname=fieldname||'_checked';var rowpath='#'+idx;var storebag=this.storebag();var currNode=storebag.getNode(rowpath);if(currNode.attr.disabled){return;}
var newval=!currNode.attr[fieldname];var kwset={};kwset[fieldname]=newval;currNode.setAttr(kwset,true,true);var gridId=this.sourceNode.attr.nodeId;if(gridId){genro.publish(gridId+'_row_checked',currNode.label,newval,currNode.attr);}},mixin_addCheckBoxColumn:function(kw){this.gnr.addCheckBoxColumn(kw,this.sourceNode);},addCheckBoxColumn:function(kw,sourceNode){var kw=kw||{};var position=kw.position||0;var structbag=sourceNode.getRelativeData(sourceNode.attr.structpath);var celldata={};var fieldname=kw.field||'_checked';celldata['field']=fieldname;celldata['name']=kw.name||' ';celldata['dtype']='B';celldata['width']='20px';celldata['format_trueclass']='checkboxOn';celldata['classes']=kw.classes||'row_checker';celldata['format_falseclass']='checkboxOff';celldata['calculated']=true;celldata['format_onclick']='this.widget.onCheckedColumn(kw.rowIndex,kw.fieldname);';structbag.setItem('view_0.rows_0.cell_checked',null,celldata,{_position:position});},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.afterBuildCalls.push(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;}
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_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){return this.collectionStore().getGridRowDataByIdx(this,inRowIndex);},mixin_storeRowCount:function(){return this.collectionStore().len(true);},patch_sort:function(){if(!this._virtual){return this.sort_replaced();}
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+'*';}
this.setSortedBy(sortedBy);},mixin_setSortedBy:function(sortedBy){this.sortedBy=sortedBy;var store=this.collectionStore();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('*');}},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(){that.updateRowCount();});var store=this._collectionStore;this._virtual=store.storeType=='VirtualSelection';this.domNode.addEventListener("scroll",function(){if(store._scroll_timeout){clearTimeout(store._scroll_timeout)}else{store.isScrolling=true}
store._scroll_timeout=setTimeout(function(){store.isScrolling=false;store._scroll_timeout=null;storeNode.publish('updateRows');},500);},true);}
return this._collectionStore;},mixin_storeRowCount:function(){var rowcount=this.collectionStore().len(true);return rowcount;},mixin_createFiltered:function(currentFilterValue,filterColumn,colType){return this.collectionStore().createFiltered(this,currentFilterValue,filterColumn,colType);},mixin_filterToRebuild:function(value){return this.collectionStore().filterToRebuild(value);},mixin_invalidFilter:function(){return this.collectionStore().invalidFilter();},mixin_resetFilter:function(value){return this.collectionStore().resetFilter();},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['selectedRowIdx']=this.getSelectedRowidx();kwargs['table']=this.sourceNode.attr.table;kwargs['datamode']=this.datamode;kwargs['struct']=this.structbag();kwargs['data']=this.collectionStore().getData();var cb=function(result){genro.download(result);};kwargs['meta']=objectExtract(this.sourceNode.attr,'meta_*',true);genro.rpc.remoteCall(method,kwargs,null,'POST',null,cb);}});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 localStore=new gnr.GnrBag();values=values.split(',');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['caption']=val;}
localStore.setItem('root.r_'+i,null,xval);}
var store=new gnr.GnrStoreBag({mainbag:localStore});attributes.searchAttr='caption';store._identifier='id';}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';}
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');}}},connectFocus:function(widget,savedAttrs,sourceNode){var timeoutId=null;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?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];this.sourceNode.setRelativeData(path,val,null,false,'selected_');}},connectForUpdate:function(widget,sourceNode){return;}});dojo.declare("gnr.widgets.dbBaseCombo",gnr.widgets.BaseCombo,{creating:function(attributes,sourceNode){var savedAttrs={};var hasDownArrow;if(attributes.hasDownArrow){attributes.limit=attributes.limit||0;}else{attributes.hasDownArrow=false}
var resolverAttrs=objectExtract(attributes,'method,dbtable,columns,limit,condition,alternatePkey,auxColumns,hiddenColumns,rowcaption,order_by,selectmethod,weakCondition,storename');var selectedColumns=objectExtract(attributes,'selected_*');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(',');}
resolverAttrs['method']=resolverAttrs['method']||'app.dbSelect';var clientCache=objectPop(attributes,'clientCache',genro.cache_dbselect);resolverAttrs['notnull']=attributes['validate_notnull'];savedAttrs['dbtable']=resolverAttrs['dbtable'];savedAttrs['auxColumns']=resolverAttrs['auxColumns'];var storeAttrs=objectExtract(attributes,'store_*');objectExtract(attributes,'condition_*');objectUpdate(resolverAttrs,objectExtract(sourceNode.attr,'condition_*',true));resolverAttrs['exclude']=sourceNode.attr['exclude'];resolverAttrs._id='';resolverAttrs._querystring='';var store;savedAttrs['record']=objectPop(storeAttrs,'record');attributes.searchAttr=storeAttrs['caption']||'caption';store=new gnr.GnrStoreQuery({'searchAttr':attributes.searchAttr});store._identifier=resolverAttrs['alternatePkey']||storeAttrs['id']||'_pkey';if(clientCache){var storageMode='sessionStorage'in window?'session':'localStorage'in window?'local':null;if(storageMode){store.storageMode=storageMode;store.cachePrefix='DBSEL_'+savedAttrs['dbtable']+'_';}}
resolverAttrs._sourceNode=sourceNode;var resolver=new gnr.GnrRemoteResolver(resolverAttrs,true,0);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;return savedAttrs;},mixin_setDbtable:function(value){this.store.rootDataNode()._resolver.kwargs.dbtable=value;},mixin_onSetValueFromItem:function(item,priorityChange){if(!item.attr.caption){return;}
this.store._lastSelectedItem=item;this.store._lastSelectedCaption=this.labelFunc(item,this.store);if(this.sourceNode.attr.gridcell){this._updateSelect(item);if(priorityChange){this.cellNext='RIGHT';this.onBlur();}}
else{if(this._hasBeenBlurred){this._updateSelect(item);this._hasBeenBlurred=false;}}},connectForUpdate:function(widget,sourceNode){return;},created:function(widget,savedAttrs,sourceNode){if(savedAttrs.auxColumns){widget._popupWidget=new gnr.Gnr_ComboBoxMenu({onChange:dojo.hitch(widget,widget._selectOption)});}
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');}}}});dojo.declare("gnr.widgets.FilteringSelect",gnr.widgets.BaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='FilteringSelect';},patch_setValue:function(value,priorityChange){this.setValue_replaced(value,priorityChange);if(!this._isvalid){this.valueNode.value=null;this.setDisplayedValue('');}},connectForUpdate:function(widget,sourceNode){var selattr=objectExtract(widget.sourceNode.attr,'selected_*',true);if(objectNotEmpty(selattr)){dojo.connect(widget,'_doSelect',widget,function(){this._updateSelect(this.item);});}}});dojo.declare("gnr.widgets.ComboBox",gnr.widgets.BaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='ComboBox';}});dojo.declare("gnr.widgets.dbSelect",gnr.widgets.dbBaseCombo,{constructor:function(application){this._domtag='div';this._dojotag='FilteringSelect';},connectForUpdate:function(widget,sourceNode){dojo.connect(widget,'_setValueFromItem',widget,'onSetValueFromItem');if(!("validate_dbselect"in sourceNode.attr)){sourceNode.attr.validate_dbselect=true;}
if(!("validate_dbselect_error"in sourceNode.attr)){sourceNode.attr.validate_dbselect_error='Not existing value';}}});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,'_doSelect',widget,function(){this._updateSelect(this.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;dijit.popup.open({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.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(dropDown.focus){dropDown.focus();}},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.Tree",gnr.widgets.baseDojo,{constructor:function(){this._domtag='div';this._dojotag='Tree';},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';if(labelCb){labelCb=funcCreate(labelCb);}
var store=new gnr.GnrStoreBag({datapath:storepath,_identifier:_identifier,hideValues:hideValues,labelAttribute:labelAttribute,labelCb:labelCb});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);}};}
if(attributes.onChecked){attributes.getIconClass=function(node,opened){if(!(node instanceof gnr.GnrBagNode)){return;}
if(node.attr){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.selectedPath){sourceNode.registerDynAttr('selectedPath');}
var tooltipAttrs=objectExtract(attributes,'tooltip_*');var savedAttrs=objectExtract(attributes,'inspect,autoCollapse,onChecked');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._datasubscriber=dojo.subscribe('_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){dojo.forEach(node.getParent().getChildren(),function(n){if(n!=node&&n.isExpanded){n.tree._collapseNode(n);}});});}
var nodeId=sourceNode.attr.nodeId;if(nodeId){var searchBoxCode=(sourceNode.attr.frameCode||nodeId)+'_searchbox';var searchBoxNode=genro.nodeById(searchBoxCode);if(searchBoxNode){dojo.subscribe(searchBoxCode+'_changedValue',widget,function(v,field){this.applyFilter(v);});}
var editBagBoxNode=genro.nodeById(nodeId+'_editbagbox');if(editBagBoxNode){dojo.connect(widget,'_updateSelect',function(item,node){if(!(item instanceof gnr.GnrBagNode)){if(item===null){return;}
item=node.getParent().item;}
genro.publish(nodeId+'_editbagbox_editnode',item)});}}},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 result={};if(item instanceof gnr.GnrBagNode){var v=item.getValue('static');result['text/plain']=v;result['text/xml']=v;}else{result['text/plain']=item.label;}
result['treenode']={'fullpath':item.getFullpath(),'relpath':item.getFullpath(null,dragInfo.treenode.tree.model.store.rootData())};return result;},attributes_mixin_checkBoxCalcStatus:function(bagnode){var checked;if(bagnode._resolver&&bagnode._resolver.expired()){return false;}else if(bagnode._value instanceof gnr.GnrBag){var ck=null;bagnode._value.forEach(function(node){var checked=('checked'in node.attr)?node.attr.checked:-1;ck=(ck==null)?checked:(ck!=checked)?-1:ck;},'static');}
return ck;},mixin_applyFilter:function(search){var treeNodes=dojo.query('.dijitTreeNode',this.domNode)
treeNodes.removeClass('hidden')
if(!search){return}
var searchmode=null;if(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 _this=this;cb_match=function(n){if(!searchmode){var label=_this.getLabel(n)
return(label.toLowerCase().indexOf(search)>=0)}else if(searchmode=='#'){console.log('ss')}else{var label=n.attr[searchmode.slice(1)]+'';if(label){return(label.toLowerCase().indexOf(search)>=0);}}}
var root=this.model.store.rootData()
cb=function(n){if(cb_match(n)){var fullpath=n.getFullpath(null,root)
_this.showNodeAtPath(fullpath)}}
root.walk(cb,'static')
treeNodes.addClass('hidden')
treeNodes.forEach(function(n){var tn=dijit.getEnclosingWidget(n);var parent=tn.getParent()
if((!parent)||cb_match(tn.item)){dojo.removeClass(tn.domNode,'hidden')
while(parent&&dojo.hasClass(parent.domNode,'hidden')){dojo.removeClass(parent.domNode,'hidden')
parent=parent.getParent()}};})},mixin_clickOnCheckbox:function(bagnode,e){var checked=bagnode.attr.checked?false:true;var walkmode=this.sourceNode.attr.eagerCheck?null:'static';var updBranchCheckedStatus=function(bag){bag.forEach(function(n){var v=n.getValue(walkmode);if(v instanceof gnr.GnrBag){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){updBranchCheckedStatus(value);}}
bagnode.setAttr({'checked':checked},true,true);var parentNode=bagnode.getParentNode();var rootNodeId=genro.getDataNode(this.model.store.datapath)._id;while(parentNode&&(parentNode._id!=rootNodeId)){parentNode.setAttr({'checked':this.checkBoxCalcStatus(parentNode)},true,true);var parentNode=parentNode.getParentNode();}
if(this.sourceNode.attr.nodeId){genro.publish(this.sourceNode.attr.nodeId+'_checked',bagnode);}},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;}
var nodeWidget=dijit.getEnclosingWidget(e.target);if(nodeWidget.htmlLabel&&(!dojo.hasClass(e.target,'dijitTreeExpando'))){return;}
if(nodeWidget==nodeWidget.tree.rootNode){return;}
nodeWidget.__eventmodifier=eventToString(e);this._onClick_replaced(e);if(genro.wdg.filterEvent(e,'*','dijitTreeLabel,dijitTreeContent')){this.setSelected(nodeWidget);this._updateSelect(nodeWidget.item,nodeWidget);}},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,e);if(genro.wdg.filterEvent(e,'*','dijitTreeLabel,dijitTreeContent')){this.setSelected(nodeWidget);this._updateSelect(nodeWidget.item,nodeWidget);}},mixin_getItemById:function(id){return this.model.store.rootData().findNodeById(id);},attributes_mixin__saveState:function(){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);},mixin_loadState:function(val,kw){var cookie=dojo.cookie(this.cookieName);this._openedItemIds={};if(cookie){dojo.forEach(cookie.split(','),function(item){this._openedItemIds[item]=true;},this);}},mixin_setStorepath:function(val,kw){if(kw.evt=='upd'){if(kw.updvalue){if(kw.value instanceof gnr.GnrBag){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'){this.model.store._triggerIns(kw);}else if(kw.evt=='del'){this._onItemChildrenChange(kw.where.getParentNode(),kw.where.getNodes());}},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);this._updateSelect(null);return;}
var pathList=kw.value.split('.');for(var i=0;i<pathList.length;i++){currNode=curr.getNode(pathList[i]);treeNode=this._itemNodeMap[currNode._id];curr=currNode.getValue();if(i<pathList.length-1){if(!treeNode.isExpanded){this._expandNode(treeNode);}}};var currTree=this;setTimeout(function(){currTree.focusNode(treeNode);currTree.setSelected(treeNode);currTree._updateSelect(currNode);},100);},mixin_showNodeAtPath:function(path){var curr=this.model.store.rootData();var pathList=path.split('.');for(var i=0;i<pathList.length;i++){var currNode=curr.getNode(pathList[i]);if(!currNode){return;}
var treeNode=this._itemNodeMap[currNode._id];curr=currNode.getValue('static');if(i<pathList.length-1){if(!treeNode.isExpanded){this._expandNode(treeNode);};}}},mixin_setSelected:function(node){var prevSelectedNode=this.currentSelectedNode;this.currentSelectedNode=node;if(prevSelectedNode){prevSelectedNode._updateItemClasses(prevSelectedNode.item);}
if(node){node._updateItemClasses(node.item);};},mixin_isSelectedItem:function(item){return this.currentSelectedNode?this.currentSelectedNode.item==item:false;},mixin__updateSelect:function(item,node){var modifiers=objectPop(node,'__eventmodifier');var reason=this;var attributes={};if(modifiers){attributes._modifiers=modifiers;}
if(!item){var item=new gnr.GnrBagNode();}
else if(!item._id){item=node.getParent().item;}
if(this.sourceNode.attr.selectedLabel){var path=this.sourceNode.attrDatapath('selectedLabel');this.sourceNode.setRelativeData(path,item.label,attributes,null,reason);}
if(this.sourceNode.attr.selectedItem){var path=this.sourceNode.attrDatapath('selectedItem');this.sourceNode.setRelativeData(path,item,attributes,null,reason);}
if(this.sourceNode.attr.selectedPath){var path=this.sourceNode.attrDatapath('selectedPath',reason);var root=this.model.store.rootData();this.sourceNode.setRelativeData(path,item.getFullpath(null,root),objectUpdate(attributes,item.attr),null,reason);}
var selattr=objectExtract(this.sourceNode.attr,'selected_*',true);for(var sel in selattr){var path=this.sourceNode.attrDatapath('selected_'+sel);this.sourceNode.setRelativeData(path,item.attr[sel],attributes,null,reason);}}});dojo.declare("gnr.widgets.GoogleMap",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){savedAttrs=objectExtract(attributes,'map_*');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){var center=(savedAttrs.center||"37.4419,-122.1419").split(',');var maptype=savedAttrs.maptype||'normal';var controls=savedAttrs.controls;var zoom=savedAttrs.zoom||13;if(GBrowserIsCompatible()){var map=new GMap2(widget);sourceNode.googleMap=map;map.setCenter(new GLatLng(parseFloat(center[0]),parseFloat(center[1])),zoom);map.setMapType(window['G_'+maptype.toUpperCase()+'_MAP']);if(controls){controls=controls.split(',');for(var i=0;i<controls.length;i++){var cnt=window['G'+controls[i]+'Control'];map.addControl(new cnt());}}
var mapcommands=objectExtract(this,'map_*',true);for(var command in mapcommands){sourceNode[command]=mapcommands[command];}}else{alert('not compatible browser');}},map_getMapLoc:function(center){var c=center.split(',');return new GLatLng(parseFloat(c[1]),parseFloat(c[0]));},map_newMarker:function(center){return new GMarker(this.getMapLoc(center));}});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');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.gnrwdg",null,{constructor:function(application){this._domtag='div';},_beforeCreation:function(sourceNode){sourceNode.gnrwdg={'gnr':this,'sourceNode':sourceNode};var attributes=sourceNode.attr;sourceNode.attr={};sourceNode.attr.tag=objectPop(attributes,'tag')
var datapath=objectPop(attributes,'datapath')
if(datapath){sourceNode.attr.datapath=datapath;}
var contentKwargs=this.contentKwargs(sourceNode,attributes);if(!this.createContent){return false;}
sourceNode.freeze();var children=sourceNode.getValue();sourceNode.clearValue();var content=this.createContent(sourceNode,contentKwargs,children);content.concat(children);sourceNode._stripData(true);sourceNode.unfreeze(true);return false;},onStructChild:function(attributes){if(!attributes.datapath){var defaultDatapath=this.defaultDatapath(attributes);if(defaultDatapath){attributes.datapath=defaultDatapath;}}},contentKwargs:function(sourceNode,attributes){return attributes;},defaultDatapath:function(attributes){return null;}});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');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 floating_kwargs=objectUpdate(attributes,{dockable:true,closable:false,visibility:'hidden'});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;}
if(showOnStart){floating_kwargs.onCreated=function(widget){setTimeout(function(){widget.show();widget.bringToTop();},1);};}
if(!dockTo&&dockTo!==false){dockTo='default_dock';}
if(dockTo){floating_kwargs.dockTo=dockTo;}
return objectUpdate({height:'400px',width:'300px',top:top,right:right,left:left,bottom:bottom,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.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',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');palette_kwargs['nodeId']=paletteCode+'_floating';palette_kwargs['title']=palette_kwargs['title']||'Palette '+paletteCode;objectUpdate(palette_kwargs,objectExtract(kw,'palette_*'));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');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,v;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']}
dojo.forEach(sides,function(side){slot=children.popNode(side);node=slot?slot.getValue().getNode('#0'):children.popNode('#side='+side);if(node){node.attr['frameCode']=frameCode;objectPop(node.attr,'side');dojo.forEach(corners[side],function(c){v=objectPop(rounded_corners,c)
if(v){node.attr['rounded_'+c]=v;}})
bc._('ContentPane',{'region':side}).setItem('#id',node._value,node.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';bc.setItem('#id',centerNode._value,objectUpdate(rounded,centerNode.attr));center=centerNode._value;}else{centerPars['region']='center';centerPars['widget']=centerPars['widget']||'ContentPane'
center=bc._(centerPars['widget'],objectUpdate(rounded,centerPars));}
return center;}});dojo.declare("gnr.widgets.FrameForm",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var formId=objectPop(kw,'formId');var storeNode=children.popNode('formStore');var store=this.createStore(storeNode);var storepath=store.storepath;var frameCode=kw.frameCode;formId=formId||frameCode+'_form';var frame=sourceNode._('FramePane',objectUpdate({controllerPath:'.controller',formDatapath:storepath,pkeyPath:'.pkey',formId:formId,form_store:store},kw));if(kw.hasBottomMessage!==false){frame._('SlotBar',{'side':'bottom',slots:'*,messageBox,*',_class:'fh_bottom_message',messageBox_subscribeTo:'form_'+formId+'_message'});}
var storeId=kw.store+'_store';var centerPars=objectExtract(kw,'center_*');centerPars['widget']=objectPop(centerPars,'widget')||'ContentPane';frame._(centerPars['widget'],objectUpdate({side:'center','_class':'fh_content','nodeId':formId+'_content',datapath:storepath},centerPars));return frame;},createStore:function(storeNode){var storeCode=storeNode.attr.storeCode;storeNode.attr.storepath=storeNode.attr.storepath||'.record';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.PaletteGrid",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var gridId=attributes.gridId||attributes.paletteCode+'_grid';attributes['frameCode']=attributes.paletteCode;var reloadOnShow=objectPop(attributes,'reloadOnShow');attributes.selfsubscribe_showing=function(){var grid=genro.wdgById(gridId);if(grid.storebag().len()==0||reloadOnShow==true){grid.reload();}}
return attributes;},createContent:function(sourceNode,kw,children){var frameCode=kw.frameCode;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');var paletteCode=kw.paletteCode
structpath=structpath?sourceNode.absDatapath(structpath):'.struct';var gridKwargs={'nodeId':gridId,'datapath':'.grid','table':objectPop(kw,'table'),'margin':'6px','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_*'));kw['contentWidget']='FramePane';var pane=sourceNode._('PalettePane',kw)
if(kw.searchOn){pane._('SlotBar',{'side':'top',slots:'*,searchOn',searchOn:objectPop(kw,'searchOn'),toolbar:true});}
pane._(_newGrid?'NewIncludedView':'includedview',gridKwargs);return pane;}});dojo.declare("gnr.widgets.PaletteTree",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){attributes['frameCode']=attributes.paletteCode;attributes.tree_onDrag=function(dragValues,dragInfo,treeItem){if(treeItem.attr.child_count&&treeItem.attr.child_count>0){return false;}
dragValues['text/plain']=treeItem.attr.caption;dragValues[attributes.paletteCode]=treeItem.attr;};attributes.tree_draggable=true;return attributes;},createContent:function(sourceNode,kw){var frameCode=kw.frameCode;var editable=objectPop(kw,'editable');var treeId=objectPop(kw,'treeId')||frameCode+'_tree';var storepath=objectPop(kw,'storepath')||'.store';var tree_kwargs={_class:'fieldsTree',hideValues:true,margin:'6px',nodeId:treeId,'frameCode':frameCode,storepath:storepath,labelAttribute:'caption'};objectUpdate(tree_kwargs,objectExtract(kw,'tree_*'));var searchOn=objectPop(kw,'searchOn');kw['contentWidget']='FramePane';var pane=sourceNode._('PalettePane',kw);if(searchOn){pane._('SlotBar',{'side':'top',slots:'*,searchOn',searchOn:true,toolbar:true});}
if(editable){var bc=pane._('BorderContainer',{'side':'center'});var bottom=bc._('ContentPane',{'region':'bottom',height:'30%',splitter:true});bottom._('BagNodeEditor',{nodeId:treeId+'_editbagbox',datapath:'.bagNodeEditor',bagpath:pane.getParentNode().absDatapath(storepath)});pane=bc._('ContentPane',{'region':'center'});}
pane._('tree',tree_kwargs);return pane;}});dojo.declare("gnr.widgets.PaletteBagNodeEditor",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw){var nodeId=objectPop(kw,'nodeId');var pane=sourceNode._('PalettePane',kw);pane._('BagNodeEditor',{nodeId:nodeId,datapath:'.bagNodeEditor',bagpath:kw.bagpath});return pane;}});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 valuePath=objectPop(kw,'valuePath');var showBreadcrumb=objectPop(kw,'showBreadcrumb',true);var bc=sourceNode._('BorderContainer',{'nodeId':nodeId,detachable:true,_class:'bagNodeEditor'});if(showBreadcrumb){var top=bc._('ContentPane',{'region':'top',background_color:'navy',color:'white'});top._('span',{'innerHTML':'Path : '});top._('span',{'innerHTML':'^.currentEditPath'});}
var box=bc._('ContentPane',{'region':'center',_class:'formgrid'});var gridId=nodeId+'_grid';var topic=nodeId+'_editnode';var bagpath=objectPop(kw,'bagpath');this.prepareStruct();gnrwdg.bagpath=bagpath;gnrwdg.valuePath=valuePath;gnrwdg.readOnly=readOnly;dojo.subscribe(topic,this,function(item){gnrwdg.gnr.setCurrentNode(gnrwdg,item)});var grid=box._('includedview',{'storepath':'.data','structpath':'gnr._dev.bagNodeEditorStruct','datamode':'bag','relativeWorkspace':true,'nodeId':gridId,autoWidth:false,'editorEnabled':true});if(!readOnly){var gridEditor=grid._('gridEditor');var cellattr={'gridcell':'attr_value','autoWdg':true};cellattr.validate_onAccept=function(value,result,validations,rowIndex,userChange){var dataNode=this.grid.storebag().getParentNode().attr.dataNode;var attr_name=this.getRelativeData('.attr_name');if(attr_name=='*value'){dataNode.setValue(value);}else{var newattr=!('attr_name'in dataNode.attr);dataNode.setAttribute(attr_name,value);if(!value){objectPop(dataNode.attr,attr_name);}
if(newattr||!value)
setTimeout(function(){genro.publish(topic,dataNode);},300);}};gridEditor._('textbox',{gridcell:'attr_name'});gridEditor._('textbox',cellattr);}
return box;},setCurrentNode:function(gnrwdg,item){var bagpath=gnrwdg.bagpath;var sourceNode=gnrwdg.sourceNode;if(typeof(item)=='string'){item=sourceNode.getRelativeData(bagpath).getNode(item);}
var itempath=item.getFullpath(null,sourceNode.getRelativeData(bagpath));sourceNode.setRelativeData('.currentEditPath',itempath);gnrwdg.currentEditPath=itempath;var newstore=new gnr.GnrBag();for(var k in item.attr){var row=new gnr.GnrBag();row.setItem('attr_name',k,{_editable:false});row.setItem('attr_value',item.attr[k]);newstore.setItem('#id',row);}
var itemvalue=item.getValue('static');if(gnrwdg.valuePath){sourceNode.setRelativeData(gnrwdg.valuePath,itemvalue);}else{var editable=true;row=new gnr.GnrBag();row.setItem('attr_name','*value',{_editable:false});if(itemvalue instanceof gnr.GnrBag){var editable=false;itemvalue='*bag*';}
row.setItem('attr_value',itemvalue,{_editable:editable});newstore.setItem('#id',row);}
newstore.sort('attr_name');if(!gnrwdg.readOnly){newstore.setItem('#id',new gnr.GnrBag({'attr_name':null,'attr_value':null}));}
sourceNode.setRelativeData('.data',newstore,{'dataNode':item});},prepareStruct:function(){if(genro.getData('gnr._dev.bagNodeEditorStruct')){return;}
var rowstruct=new gnr.GnrBag();rowstruct.setItem('cell_0',null,{field:'attr_name',name:'Name',width:'30%',cellStyles:'background:gray;color:white;border-bottom:1px solid white;'});rowstruct.setItem('cell_1',null,{field:'attr_value',name:'Value',width:'70%',cellStyles:'border-bottom:1px solid lightgray;'});genro.setData('gnr._dev.bagNodeEditorStruct.view_0.row_0',rowstruct);}});dojo.declare("gnr.widgets.SearchBox",gnr.widgets.gnrwdg,{contentKwargs:function(sourceNode,attributes){var delay='delay'in attributes?objectPop(attributes,'delay'):100;attributes.onKeyUp=function(e){var sourceNode=e.target.sourceNode;if(sourceNode._onKeyUpCb){clearTimeout(sourceNode._onKeyUpCb);}
var v=e.target.value;sourceNode._onKeyUpCb=setTimeout(function(){sourceNode.setRelativeData('.currentValue',v);},delay);};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);this._prepareSearchBoxMenu(searchOn,databag);sourceNode.setRelativeData(null,databag);var searchbox=sourceNode._('table',{nodeId:nodeId,width:'100%'})._('tbody')._('tr');sourceNode._('dataController',{'script':'genro.publish(searchBoxId+"_changedValue",currentValue,field)','searchBoxId':nodeId,currentValue:'^.currentValue',field:'^.field'});var searchlbl=searchbox._('td');searchlbl._('div',{'innerHTML':'^.caption',_class:'buttonIcon'});searchlbl._('menu',{'modifiers':'*',_class:'smallmenu',storepath:'.menubag',selected_col:'.field',selected_caption:'.caption'});searchbox._('td')._('div',{_class:'searchInputBox'})._('input',{'value':'^.value',connect_onkeyup:kw.onKeyUp});dojo.subscribe(nodeId+'_updmenu',this,function(searchOn){menubag=this._prepareSearchBoxMenu(searchOn,databag);});return searchbox;},_prepareSearchBoxMenu:function(searchOn,databag){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,'_');menubag.setItem('r_'+i,null,{col:col,caption:caption,child:''});i++;});}
databag.setItem('field',menubag.getItem('#0?col'));var defaultLabel=menubag.getItem('#0?caption');if(defaultLabel){databag.setItem('caption',defaultLabel);}
databag.setItem('menubag',menubag);databag.setItem('value','');}});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');palette_kwargs['nodeId']=palette_kwargs['nodeId']||groupCode+'_floating';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'});var tc=floating._('tabContainer',tab_kwargs);return tc;}});dojo.declare("gnr.widgets.SlotButton",gnr.widgets.gnrwdg,{createContent:function(sourceNode,kw,children){var slotbarCode=sourceNode.getInheritedAttributes().slotbarCode;var target=kw.target||sourceNode.getInheritedAttributes().target;kw['showLabel']=kw.iconClass?(kw['showLabel']||false):true;var topic=(target||slotbarCode)+'_'+objectPop(kw,'publish');if(!kw.action){kw.topic=topic;kw.command=kw.command||null;kw.opt=objectExtract(kw,'opt_*');kw['action']="genro.publish(topic,{'command':command,modifiers:genro.dom.getEventModifiers(event),opt:opt})";}
return sourceNode._('button',kw);}});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 orientation=attributes.orientation||'horizontal';if(side){orientation=((side=='top')||(side=='bottom'))?'horizontal':'vertical';}
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';attributes['gradient_from']=attributes['gradient_from']||sidePars['gradient_from']||genro.dom.themeAttribute('toolbar','gradient_from','silver');attributes['gradient_to']=attributes['gradient_to']||sidePars['gradient_to']||genro.dom.themeAttribute('toolbar','gradient_to','whitesmoke');var css3Kw={'left':[0,'right'],'top':[-90,'bottom'],'right':[180,'left'],'bottom':[90,'top']}
attributes['border_'+css3Kw[side][1]]='1px solid '+attributes['gradient_from'];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){var slots=objectPop(kw,'slots');return this['createContent_'+objectPop(kw,'orientation')](sourceNode,kw,kw.slotbarCode,slots,children);},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++;})}}
if(cell.len()==0){if(that['slot_'+slot]){slotKw=objectExtract(kw,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]?kw[slot]: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,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;}
cell=table._('tr',buildKw.row)._('td',objectUpdate({_slotname:slot},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++;});}}
if(cell.len()==0&&(that['slot_'+slot])){slotKw=objectExtract(kw,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',{'width':slotKw.width||'15em'});div._('SearchBox',{searchOn:slotValue,nodeId:frameCode+'_searchbox',datapath:'.searchbox'});},slot_messageBox:function(pane,slotValue,slotKw,frameCode){var mbKw=objectUpdate({duration:1000,delay:2000},slotKw);var subscriber=objectPop(mbKw,'subscribeTo');mbKw['subscribe_'+subscriber]=function(){var kwargs=arguments[0];var domNode=this.domNode;var sound=objectPop(kwargs,'sound');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:objectPop(mbKw,'duration'),delay:objectPop(mbKw,'delay'),onEnd:function(){domNode.innerHTML=null;if(customOnEnd){customOnEnd();}}});}
pane._('span',mbKw);}});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.method=attributes.method||'app.getSelection';return attributes;},createContent:function(sourceNode,kw,children){var chunkSize=objectPop(kw,'chunkSize',0);var storeType=chunkSize?'VirtualSelection':'Selection';kw.row_count=chunkSize;var storeType=kw.row_count?'VirtualSelection':'Selection';var identifier=objectPop(kw,'_identifier')||'_pkey';var selectionStore=sourceNode._('dataRpc',kw);var cb="this.store.onLoaded(result);"
selectionStore._('callBack',{content:cb});var rpcNode=selectionStore.getParentNode();rpcNode.store=new gnr.stores[storeType](rpcNode,{'identifier':identifier,'chunkSize':kw.row_count,'storeType':storeType});return selectionStore;}});dojo.declare("gnr.stores._Collection",null,{constructor:function(node,kw){this.storeNode=node;this.storepath=this.storeNode.attr.storepath;this.storeNode.setRelativeData(this.storepath,null);for(var k in kw){this[k]=kw[k];}},onLoaded:function(result){this.storeNode.setRelativeData(this.storepath,result);return result;},getData:function(){return this.storeNode.getRelativeData(this.storepath);},getItems:function(){return this.getData();},len:function(filtered){if(filtered&&this._filtered){return this._filtered.length;}
return this.getItems().length;},sort:function(sortedBy){this.sortedBy=sortedBy||this.sortedBy;var data=this.getData();data.sort(this.sortedBy);},absIndex:function(idx){if(this.filterToRebuild()){console.log('invalid filter');}
return this._filtered?this._filtered[idx]:idx;},rowFromItem:function(item,grid){if(grid){return grid.rowFromBagNode(item);}
return item;},getNavigationPkey:function(nav,currentPkey){var idx=nav==parseInt(nav)&&nav;if(!idx){if(nav=='first'){idx=0;}else if(nav=='last'){idx=this.len()-1;}else{idx=this.getIdxFromPkey(currentPkey);idx=nav=='next'?idx+1:idx-1;}}
return this.getKeyFromIdx(idx);},getKeyFromIdx:function(idx){var data=this.getData();if(!data){return;}
var item;data=data.getNodes()
if((idx<0)||(idx>(data.length-1))){return null;}
return this.keyGetter(data[idx]);},getIdxFromPkey:function(pkey){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;}});return result;}},getGridRowDataByIdx:function(grid,idx){var rowdata={}
var node=this.itemByIdx(idx);if(node){rowdata=grid.rowFromBagNode(node);}
return rowdata;},filterToRebuild:function(value){this._filterToRebuild=value;},invalidFilter:function(){return this._filterToRebuild;},resetFilter:function(){return this._filtered=null;},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(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"});}
cb=function(rowdata,index,array){return genro.compare(op,rowdata[filterColumn],val);};}}
return cb;},createFiltered:function(grid,currentFilterValue,filterColumn,colType){var cb=this.compileFilter(currentFilterValue,filterColumn,colType);if(!cb&&!grid.excludeListCb){this._filtered=null;return null;}
var filtered=[]
var excludeList=null;if(grid.excludeListCb){excludeList=grid.excludeListCb();}
dojo.forEach(this.getItems(),function(n,index,array){var rowdata=grid.rowFromBagNode(n);var result=cb?cb(rowdata,index,array):true;if(result){if((!excludeList)||(dojo.indexOf(excludeList,rowdata[grid.excludeCol])==-1)){filtered.push(index);}}});this._filtered=filtered;this._filterToRebuild=false;}})
dojo.declare("gnr.stores.BagRows",gnr.stores._Collection,{keyGetter:function(n){return n.getValue('static').getItem(this.identifier);},getRowByIdx:function(idx){return},getItems:function(){var data=this.getData();return data?data.getNodes():[];},rowFromItem:function(n,grid){if(grid){return grid.rowFromBagNode(n);}
return n.getValue();}});dojo.declare("gnr.stores.Selection",gnr.stores.BagRows,{keyGetter:function(n){return n.attr[this.identifier];},rowFromItem:function(n,grid){if(grid){return grid.rowFromBagNode(n);}
return n.attr();},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}});dojo.declare("gnr.stores.VirtualSelection",gnr.stores.Selection,{constructor:function(){this.pendingPages={};this.lastIdx=0;},len:function(){if(!this.getData()){return 0;}
return this.getData().getParentNode().attr['totalrows'];},onLoaded:function(result){var selection=result.getValue();var data=new gnr.GnrBag();var resultattr=result.attr;data.setItem('P_0',result.getValue());this.rowtotal=resultattr.rowcount;this.totalRowCount=resultattr.totalRowCount;this.selectionName=resultattr.selectionName;this.storeNode.setRelativeData(this.storepath,data,resultattr);return result;},clearBagCache:function(){this.getData().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
return this.currCachedPage.getNodes()[rowIdx]}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;}}}
return this.currCachedPage.getNodes()[rowIdx]}},getDataChunk:function(pageIdx){if(pageIdx in this.pendingPages){return}else{var pageData=this.getData().getItem('P_'+pageIdx);if(pageData){return pageData;}
if(this.isScrolling){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,null,{'doTrigger':false});objectPop(this.pendingPages,pageIdx);this.storeNode.publish('updateRows');this.pendingTimeout={};return data;},loadBagPageFromServer:function(pageIdx,sync){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,null,null,sync?null:function(result){return that.onChunkLoaded(result,pageIdx)});if(sync){return this.onChunkLoaded(result,pageIdx);}else{this.pendingPages[pageIdx]=result;}},getIdxFromPkey:function(pkey){var result=-1;var dataNode=this.getData().getNodeByAttr('_pkey',pkey);if(dataNode){result=dataNode.attr.rowidx;}
return result;},getKeyFromIdx:function(idx){var dataNode=this.itemByIdx(idx,true);return this.keyGetter(dataNode);}});



dojo.declare("gnr.GnrFrmHandler",null,{constructor:function(sourceNode,formId,formDatapath,controllerPath,pkeyPath,formAttr){var that=this;genro.src.afterBuildCalls.push(function(){that.onStartForm();});for(var k in formAttr){this[k]=formAttr[k];}
if(this.subforms){this.subforms=this.subforms.split(',');}
this.formId=formId;this.changed=false;this.opStatus=null;this.locked=this.locked||false;this.current_field=null;this.controllerPath=controllerPath;if(!this.store){this.controllerPath=this.controllerPath||'gnr.forms.'+this.formId;}
this.formDatapath=formDatapath;this.pkeyPath=pkeyPath;this.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,load,loaded,setLocked,navigationEvent,newrecord,pendingChangesAnswer,dismiss,deleteItem,deleteConfirmAnswer');this._register={};this._status_list=['ok','error','changed','readOnly','noItem'];this.autoRegisterTags={'textbox':null,'simpletextarea':null,'checkbox':null,'numbertextbox':null,'timetextbox':null,'horizzontalslider':null,'radiobutton':null,'verticalslider':null,'combobox':null,'filteringselect':null,'dbselect':null,'dbcombobox':null,'input':null,'textarea':null,'datetextbox':null};this.msg_saved='Saved';this.msg_deleted='Deleted';this.msg_unsaved_changes="Current record has been modified.";this.msg_confirm_delete="You are going to delete the current record.";},onStartForm:function(kw){var kw=kw||{};this.formDomNode=genro.domById(this.formId);if(this.store){var contentSourceNode=genro.nodeById(this.formId+'_content');this.formContentDomNode=contentSourceNode.widget.domNode;this.store.init(this);var that=this;dojo.connect(this.formContentDomNode,'onclick',function(e){if(genro.activeForm!=that){that.focusCurrentField();}});var startKey=kw.startKey||this.store.startKey||this.getCurrentPkey();if(startKey){this.load({destPkey:startKey});}}},reset:function(){this.resetChanges();this.resetInvalidFields();},publish:function(command,kw){dojo.publish('form_'+this.formId+'_'+command,[kw]);},subscribe:function(command,cb,scope){if(command.indexOf(',')>=0){var that=this;dojo.forEach(command.split(','),function(command){that.subscribe(command);});return;}
var topic='form_'+this.formId+'_'+command;var scope=scope||this;var cb=cb||this[command];dojo.subscribe(topic,scope,cb);},setDisabled:function(disable){disable=disable||this.isProtected();for(var k in this._register){this._register[k].setDisabled(disable);}},isProtected:function(){return this.locked||this.status=='readOnly'||this.status=='noItem'},setLocked:function(value){if(value=='toggle'){value=!this.locked;}
this.locked=value;this.setDisabled(this.locked);this.publish('onLockChange',{'locked':this.locked});},registerChild:function(sourceNode){if(sourceNode.attr.parentForm||(sourceNode.attr.tag.toLowerCase()in this.autoRegisterTags)){this._register[sourceNode._id]=sourceNode;return;}},dismiss:function(modifiers){this.publish('navigationEvent',{'command':'dismiss',modifiers:modifiers});},resetChanges:function(){this.getFormData().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'){var result=genro.vld.validateInLoading(sourceNode,value);}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();this.updateInvalidField(sourceNode,sourceNode.attrDatapath('value'));},load:function(kw){var kw=kw||{};if(kw['destPkey']=='*norecord*'){kw['destPkey']=null;this.store.setNavigationStatus('*norecord*');this.setFormData();}
if(this.store){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(this.changed&&kw.destPkey&&(kw.destPkey!=currentPkey)){if(kw.modifiers=='Shift'){this.do_save(kw.destPkey);}else{this.openPendingChangesDlg(kw);}
return;}
this.doload_store(kw);},newrecord:function(){this.load({destPkey:'*newrecord*'});},deleteItem:function(kw){this.deleteConfirmDlg(kw);},deleteConfirmDlg:function(kw){var dlg=genro.dlg.quickDialog('Alert',{_showParent:true,width:'250px'});dlg.center._('div',{innerHTML:this.msg_confirm_delete,text_align:'center',height:'50px'})
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.store.deleteItem(kw.pkey);}else{if(kw.cancelCb){kw.cancelCb();}}}},pendingChangesAnswer:function(kw){var command=objectPop(kw,'command');if(this.store){var that=this;if(command=='save'){this.do_save(kw.destPkey);}
else if(command=='discard'){this.doload_store(kw);}else{if(kw.cancelCb){kw.cancelCb();}}}else{var that=this;if(command=='save'){this.setCurrentPkey(kw.destPkey);this.do_save()}
else if(command=='discard'){this.doload_loader(kw);}else{if(kw.cancelCb){kw.cancelCb();}}}},openPendingChangesDlg:function(kw){var dlg=genro.dlg.quickDialog('Pending changes',{_showParent:true,width:'250px'});dlg.center._('div',{innerHTML:this.msg_unsaved_changes,text_align:'center',height:'50px'})
var form=this;var slotbar=dlg.bottom._('slotBar',{slots:'discard,*,cancel,save',action:function(){dlg.close_action();kw.command=this.attr.command;form.publish('pendingChangesAnswer',kw);}});slotbar._('button','discard',{label:'Discard',command:'discard'});slotbar._('button','cancel',{label:'Cancel',command:'cancel'});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){var 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._showHider();}
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.publish('onDismissed');return;}
var 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',pkey);if(pkey){if(!sync){this._showHider();}
this.resetInvalidFields();this.setOpStatus('loading',pkey);this.store.load(pkey);}else{this.setDisabled(true);this.updateStatus();}},_showHider:function(){var formDomNode=genro.domById(this.formId);genro.dom.addClass(formDomNode,'loadingForm');var formHider=document.createElement("div");formHider.id=this.formId+"_hider";dojo.addClass(formHider,'formHider');formDomNode.appendChild(formHider);},_hideHider:function(){genro.dom.removeClass(this.formId,'loadingForm');var hider=dojo.byId(this.formId+"_hider");if(hider){genro.domById(this.formId).removeChild(hider);}},deleted:function(kw){this.load({destPkey:'*norecord*'});this.publish('message',{message:this.msg_deleted,sound:'$ondeleted'});this.publish('onDeleted');},loaded:function(data){if(data){this.setFormData(data);}
this.publish('onLoaded',{pkey:this.getCurrentPkey()});this._hideHider()
this.resetChanges();var controllerData=this.getControllerData();this.readOnly=this.isReadOnly();this.newRecord=this.isNewRecord();controllerData.setItem('is_newrecord',this.newRecord,null,{lazySet:true});controllerData.setItem('loading',false,null,{lazySet:true});controllerData.fireItem('loaded');this.updateStatus();this.setOpStatus();this.currentFocused=null;if(this.store){this.setDisabled(false)}
this.focus();},focus:function(node){if(!this.isProtected()){var formContentDomNode=this.formContentDomNode||this.sourceNode.widget.domNode;if(this.sourceNode.widget.getSelected){formContentDomNode=this.sourceNode.widget.getSelected().domNode;}
var node=node||dijit.getFirstInTabbingOrder(formContentDomNode);if(node){node.focus();}}},onFocusForm:function(){genro.dom.addClass(this.sourceNode,'form_activeForm');this.focusCurrentField();},onBlurForm:function(){genro.dom.removeClass(this.sourceNode,'form_activeForm');},isRegisteredWidget:function(wdg){return(wdg.sourceNode._id in this._register)},onFocusElement:function(wdg){if(this.isRegisteredWidget(wdg)&&(typeof(wdg.focus)=='function')){this.currentFocused=wdg;}},focusCurrentField:function(e){if(!this.isProtected()){if(this.currentFocused){this.currentFocused.focus();}}},save:function(always){if(!this.opStatus){var always=always||this.getControllerData('is_newrecord');if(this.changed||always){var invalidfields=this.getInvalidFields();var invalid=(invalidfields.len()>0);if(invalid){this.fireControllerData('save_failed','invalid');return'invalid:'+invalid;}
return this.do_save();}else{this.fireControllerData('save_failed','nochange');}}
else{genro.playSound('Basso');}},do_save:function(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=this.store.onSaved;if(destPkey=='*dismiss*'){onSaved='dismiss';}
var deferred=this.store.save(destPkey);var that,cb;that=this;if(onSaved=='reload'||(destPkey&&(destPkey!=this.getCurrentPkey()))||this.isNewRecord()){cb=function(resultDict){destPkey=destPkey||resultDict.savedPkey;if(resultDict.loadedRecord){that.setCurrentPkey(destPkey);that.store.loaded(destPkey,resultDict.loadedRecordNode);}else{that.setCurrentPkey(destPkey);that.load({'destPkey':destPkey});}}}else{cb=function(result){that.reset();if(onSaved=='dismiss'){that.publish('onDismissed');}};}
if(deferred){deferred.addCallback(function(result){cb(result);return result});}
return deferred;}},saved:function(result){this.fireControllerData('saved');this.setOpStatus('saved');var savedPkey=result;if(this.store){savedPkey=result.savedPkey;}
this.publish('onSaved',{pkey:savedPkey});this.publish('message',{message:this.msg_saved,sound:'$onsaved'});return result;},openForm:function(idx,pkey){if(this.store&&false){console.log('idx',idx,'pkey',pkey);this.load({destPkey:pkey});}else{this.fireControllerData('openFormPkey',pkey);this.fireControllerData('openFormIdx',idx);}},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){this.sourceNode.setRelativeData(this.formDatapath,data||new gnr.GnrBag());},getDataNodeAttributes:function(){var data=this.sourceNode.getRelativeData(this.formDatapath);if(data){return data.getParentNode().attr;}
return{};},isNewRecord:function(){return this.getDataNodeAttributes()._newrecord;},isReadOnly:function(){return this.getDataNodeAttributes()._readonly;},hasChanges:function(){return this.getControllerData('changed');},getFormChanges:function(){return this._getRecordCluster(this.getFormData(),true);},getFormCluster:function(){return this._getRecordCluster(this.getFormData(),false);},getCurrentPkey:function(){return this.pkeyPath?this.sourceNode.getRelativeData(this.pkeyPath):null;},setCurrentPkey:function(pkey){this.sourceNode.setRelativeData(this.pkeyPath,pkey);},getVirtualColumns:function(){var virtual_columns=[];this.sourceNode.getValue().walk(function(n){if(n.attr._virtual_column){virtual_columns.push(n.attr._virtual_column)}});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){sendBag=(sendback==true)||this.hasChangesAtPath(currpath);if(sendBag){value.walk(function(n){if('_loadedValue'in n.attr){var loadedValue=objectPop(n.attr,'_loadedValue');n.attr.__old=asTypedTxt(loadedValue,n.attr.dtype);}},'static')
data.setItem(node.label,value,objectUpdate({'_gnrbag':true},node.attr));data.__isRealChange=true;}}
else if((sendback==true)||(isNewRecord&&value!=null)||('_loadedValue'in node.attr)){var attr_dict={'dtype':node.attr.dtype};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',true);result.setItem(recordNode.label,data,resultattr);result.__isRealChange=data.__isRealChange;}
return result;}},triggerUPD:function(kw){if(kw.reason=='resolver'||kw.node.getFullpath().indexOf('$')>0){return;};if(kw.value instanceof gnr.GnrBag){}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){delete kw.node.attr._loadedValue;changed=false;}
if(changed){changes.setItem(changekey,null);}else if(changed===false){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();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,'_');},updateInvalidField:function(sourceNode,changekey){if(sourceNode==true){return;}
changekey=this.getChangeKey(changekey);if(changekey.indexOf('emptypath')>=0){return;}
var invalidfields=this.getInvalidFields();var invalidnodes=invalidfields.getItem(changekey);var sourceNode_id=sourceNode.getStringId();if(sourceNode.hasValidationError()){if(!invalidnodes){invalidnodes={};invalidfields.setItem(changekey,invalidnodes);}
invalidnodes[sourceNode_id]=sourceNode;}else{objectPop(invalidnodes,sourceNode_id);if(!objectNotEmpty()){invalidfields.pop(changekey);}}
this.updateStatus();},updateStatus:function(){var invalidfields=this.getInvalidFields();var invalid=(invalidfields.len()>0);this.setControllerData('valid',!invalid);var status;if(this.pkeyPath&&!this.getCurrentPkey()){status='noItem';}
else if(this.isReadOnly()){status='readOnly';}
else if(invalid){status='error'}
else{var changes=this.getChangesLogger();var changed=(changes.len()>0)
this.changed=changed;this.setControllerData('changed',changed);status=this.changed?'changed':'ok';}
if(this.status!=status){this.status=status;this.publish('onStatusChange',{'status':this.status});var formDomNode=this.formDomNode
dojo.forEach(this._status_list,function(st){genro.dom.setClass(formDomNode,'form_'+st,st==status);});}},checkInvalidFields:function(){var node,sourceNode,changekey;var invalidfields=this.getInvalidFields();var invalidnodes=invalidfields.getNodes();for(var i=0;i<invalidnodes.length;i++){node=invalidnodes[i];sourceNode=node.getValue();changekey=node.label;result=genro.vld.validate(sourceNode,sourceNode);if(result['modified']){sourceNode.widget.setValue(result['value']);}
sourceNode.setValidationError(result);return result['value'];}},focusFirstInvalidField:function(){if(dojo.isIE>0){return;}
var invalidFields=this.getInvalidFields();var first=invalidFields.getItem("#0");var key=objectKeyByIdx(first,0);first[key].widget.focus();},getInvalidFields:function(){return this.getControllerData().getItem('invalidFields')||new gnr.GnrBag();},resetInvalidFields:function(){this.getControllerData().setItem('invalidFields',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 command=kw.command;var pkey;if(command=='add'){pkey='*newrecord*';}else if(command=='dismiss'){pkey='*dismiss*';}
else{pkey=this.store.navigationEvent(kw);}
this.load({destPkey:pkey,modifiers:kw.modifiers,cancelCb:kw.cancelCb});}});dojo.declare("gnr.GnrValidator",null,{validationTags:['dbselect','notnull','empty','case','len','email','regex','call','nodup','exist','remote'],getCurrentValidations:function(sourceNode){return sourceNode.evaluateOnNode(objectExtract(sourceNode.attr,'validate_*',true));},validateInLoading:function(sourceNode,value){var validations=this.getCurrentValidations(sourceNode);return this._validate(sourceNode,value,validations,['notnull']);},validate:function(sourceNode,value,userChange){var validations=this.getCurrentValidations(sourceNode);var result=this._validate(sourceNode,value,validations,this.validationTags,userChange);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'];}else{if(validreturn==false){errorcode=iswarning?'warning':'error';}else if(typeof(validreturn)=='string'){errorcode=validreturn;}
validreturn={};}
if(errorcode){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){genro.callAfter(dojo.hitch(sourceNode,func,result['value'],result,validations,sourceNode.editedRowIndex,userChange),1);}},validate_notnull:function(param,value){if((value==='')||(value==null)){return{'errorcode':'notnull','required':true};}},validate_dbselect:function(param,value,sourceNode,parameters){if(dojo.isIE>0){return;}
var validate_notnull=sourceNode.attr.validate_notnull;var result;if((value==undefined)||(value=='')||(value==null)){if(sourceNode.widget._lastDisplayedValue!=""){sourceNode.widget._updateSelect();result={'errorcode':'missing'};}
sourceNode.widget._lastValueReported=null;return result;}},validate_empty:function(param,value){if(value==null||value===''){return{'value':param};}},validate_case:function(param,value){if(value){var original=value;param=param.toLowerCase();if(param=='upper'||param=='u'){value=value.toUpperCase();}else if(param=='lower'||param=='l'){value=value.toLowerCase();}else if(param=='capitalize'||param=='c'){value=stringCapitalize(value.toLowerCase());}else if(param=='title'||param=='t'){value=value[0].toUpperCase()+value.slice(1);}
if(original!=value){return{'value':value};}}},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'max';}}
if(sl[0]){if(value.length<parseInt(sl[0])){return'min';}}}else{if(value.length!=parseInt(param)){return'fixed';}}}},validate_regex:function(param,value){if(value){var not=false;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){var rpcresult=genro.rpc.remoteCall(param,objectUpdate({'value':value},parameters),null,'GET');if(rpcresult instanceof gnr.GnrBag){var result={};result['errorcode']=rpcresult.getItem('errorcode');result['iswarning']=rpcresult.getItem('iswarning');if(rpcresult.getItem('value')){result['value']=rpcresult.getItem('value');}
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 false;}}},validate_gridnodup:function(param,value,sourceNode){var col=((typeof(param)=='string')&&param)?param:sourceNode.getAttributeFromDatasource('value');if(value){var colvalues=genro.wdgById(sourceNode.gridId).getColumnValues(col);var n=dojo.indexOf(colvalues,value);if((n!=-1)&&(n!=sourceNode.editedRowIndex)){return false;}}},validate_nodup: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;}}},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,{constructor:function(kw,handlers){objectPop(kw,'tag');this.handlers=handlers;this.storepath=objectPop(kw,'storepath');this.parentStoreCode=objectPop(kw,'parentStore');var base_handler_type=objectPop(kw,'handler');var handlerKw=objectExtract(kw,'handler_*');var handler,handler_type,method,actionKw,callbacks;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');that.handlers[action]={'kw':objectUpdate(actionKw,handler),'method':method,'callbacks':callbacks,rpcmethod:rpcmethod};});for(k in kw){this[k]=kw[k];}},init:function(form){this.form=form;if(this.parentStoreCode){this.parentStore=genro.getStore(this.parentStoreCode);}},getStartPkey:function(){return;},getParentStoreData:function(){return this.parentStore.getData();},load_memory:function(){var sourcebag=this.form.sourceNode.getRelativeData(this.sourcepath);var fields=this.fields.split(',');var result=new gnr.GnrBag();dojo.forEach(fields,function(n){result.setItem(n,sourcebag.getItem(n));});this.loaded(null,result);},save_memory:function(){var fields=this.fields.split(',');var sourcebag=this.form.sourceNode.getRelativeData(this.sourcepath);var form=this.form;dojo.forEach(fields,function(n){sourcebag.setItem(n,form.getFormData(n));});this.saved();},delete_memory:function(){},load_recordCluster:function(){var form=this.form;var that=this;var currPkey=this.form.getCurrentPkey();var cb=function(result){that.loaded(currPkey,result);};var kw=form.sourceNode.evaluateOnNode(this.handlers.load.kw);this.handlers.load.rpcmethod=this.handlers.load.rpcmethod||'loadRecordCluster';genro.rpc.remoteCall(this.handlers.load.rpcmethod,objectUpdate({'pkey':currPkey,'virtual_columns':form.getVirtualColumns(),'table':this.table},kw),null,'POST',null,cb);},save_recordCluster:function(destPkey){var form=this.form;var that=this;var saver=this.handlers.save;var kw=form.sourceNode.evaluateOnNode(this.handlers.save.kw);if(destPkey){kw._autoreload=destPkey}else if(this.onSaved=='reload'||this.form.isNewRecord()){kw._autoreload=true}
var autoreload=kw._autoreload;var cb=function(result){if(result){var resultDict={}
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);return resultDict;};this.handlers.save.rpcmethod=this.handlers.save.rpcmethod||'saveRecordCluster';var deferred=genro.rpc.remoteCall(this.handlers.save.rpcmethod,objectUpdate({'data':form.getFormChanges(),'table':this.table},kw),null,'POST',null,function(){});deferred.addCallback(cb);if(saver.callbacks){var thatnode=form.sourceNode;saver.callbacks.forEach(function(n){var defkw=objectUpdate({},kw);genro.rpc.addDeferredCb(deferred,n.getValue(),objectUpdate(defkw,n.attr),thatnode);});}
return deferred;},del_recordCluster:function(pkey){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},kw),null,'POST',null,function(){});var cb=function(result){that.deleted(result);return result;}
deferred.addCallback(cb);if(deleter.callbacks){var thatnode=form.sourceNode;deleter.callbacks.forEach(function(n){var defkw=objectUpdate({},kw);genro.rpc.addDeferredCb(deferred,n.getValue(),objectUpdate(defkw,n.attr),thatnode);});}
return deferred;},loaded:function(pkey,result){this.setNavigationStatus(pkey)
this.form.loaded(result);},deleted:function(result){this.form.deleted(result);},saved:function(result){return this.form.saved(result);},save:function(destPkey){return this.handlers.save.method.call(this,destPkey);},load:function(){return this.handlers.load.method.call(this);},deleteItem:function(pkey){return this.handlers.del.method.call(this,pkey)},setNavigationStatus:function(){return;},navigationEvent:function(kw){}});dojo.declare("gnr.formstores.Item",gnr.formstores.Base,{});dojo.declare("gnr.formstores.Collection",gnr.formstores.Base,{getStartPkey:function(){return this.getNavigationPkey(0);},setNavigationStatus:function(pkey){var currIdx=this.parentStore.getIdxFromPkey(pkey);var kw={}
if(currIdx<0){kw.first=true;kw.last=true;}
else if(currIdx==0){kw.first=true;}else if(currIdx>=this.parentStore.len()-1){kw.last=true;}
this.form.publish('navigationStatus',kw);return;},navigationEvent:function(kw){var command=kw.command;return this.parentStore.getNavigationPkey(command,this.form.getCurrentPkey());}});dojo.declare("gnr.formstores.Hierarchical",gnr.formstores.Base,{});



dojo.declare("gnr.GnrDevHandler",null,{constructor:function(application){this.application=application;},inspectConnect:function(pane){var 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){if(!dijit.byId("gnr_srcInspector")){genro.dev.openSrcInspector();}
var sourceNode=genro.src.enclosingSourceNode(e.target);console.log('------current edit node:-------');console.log(sourceNode);genro.publish('srcInspector_editnode',sourceNode)}});},openSrcInspector:function(){var root=genro.src.newRoot();genro.src.getNode()._('div','_devSrcInspector_');var node=genro.src.getNode('_devSrcInspector_').clearValue();node.freeze();node._('PaletteBagNodeEditor',{'paletteCode':'srcInspector',nodeId:'srcInspector',id:'gnr_srcInspector','dockTo':false,title:'Source Node Inspector',style:"font-family:monaco;",'bagpath':'*S'});node.unfreeze();},debugMessage:function(msg,level,duration){var level=level||'MESSAGE';var duration=duration||50;dojo.publish("standardDebugger",{message:msg,type:level.toUpperCase(),duration:duration});},handleRpcHttpError:function(response,ioArgs){var xhr=ioArgs.xhr;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');genro.pageReload();return;}
else if(status==412){genro.dlg.alert('No longer existing page');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){genro.dlg.message("An HTTP error occurred: "+response.message,null,'error');}
else{genro.openWindow(debug_url,'Internal Server Error',{scrollbars:'yes'});}}},handleRpcError:function(error,envNode){if(error=='expired'){genro.dlg.message('expired session');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();}},formbuilder:function(node,col,tblattr){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 lblpars={innerHTML:objectPop(kw,'lbl')};objectUpdate(lblpars,objectExtract(kw,'lbl_*'));var tr=this.curr_tr;tr._('td',lblpars);tr._('td')._(tag,kw);this.col_count=this.col_count+1;};return tbl;},relationExplorer:function(table,title,rect){var 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 path='gnr.relation_explorers.'+table;genro.setData(path,genro.rpc.remoteResolver('relationExplorer',{'table':table}));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});var treeattr={storepath:path,margin:'4px'};treeattr.labelAttribute='caption';treeattr._class='fieldsTree';treeattr.hideValues=true;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['maintable']=table;dragValues['text/plain']=treeItem.attr.fieldpath;dragValues['gnrdbfld_'+code]=fldinfo;};treeattr.draggable=true;treeattr.getIconClass='if(node.attr.dtype){return "icnDtype_"+node.attr.dtype}';fpane._('tree',treeattr);node.unfreeze();fpane.getParentNode().widget.bringToTop();},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',style:"font-family:monaco;"});pg._('paletteTree',{'paletteCode':'cliDatastore',title:'Data',storepath:'*D',searchOn:true,tree_inspect:'shift','tree_connect_onclick':cbLog,editable:true,tree_labelAttribute:null,tree_hideValues:false});var sourcePane=pg._('paletteTree',{'paletteCode':'cliSourceStore',title:'Source',storepath:'*S',searchOn:true,tree_inspect:'shift',editable:true,'tree_connect_onclick':cbLog,tree_getLabel:function(n){return 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',searchOn:true,tree_inspect:'shift',editable:true});genro.setDataFromRemote('gnr.palettes.dbmodel.store',"app.dbStructure");this.sqlDebugPalette(pg);this.devUtilsPalette(pg);node.unfreeze();},sqlDebugPalette:function(parent){var pane=parent._('palettePane',{'paletteCode':'devSqlDebug',title:'Sql'});var bc=pane._('borderContainer');var top=bc._('contentPane',{'region':'top'})._('toolbar',{'height':'18px'});top._('checkbox',{'value':'^gnr.debugger.sqldebug','label':'Debug SQL'});top._('button',{'label':'Clear',action:'genro.setData("gnr.debugger.main",null)'});var bc=bc._('borderContainer',{'region':'center'});var right=bc._('contentPane',{'region':'right','splitter':true,width:'50%'});var treeId='palette_debugger_tree';var storepath='gnr.debugger.main';right._('BagNodeEditor',{'nodeId':treeId+'_editbagbox','datapath':'.grid','bagpath':storepath,'readOnly':true,'valuePath':'.bottomData','showBreadcrumb':false});var bottom=bc._('contentPane',{'region':'bottom','splitter':true,height:'50%','overflow':'hidden'});bottom._('div',{'innerHTML':'^.grid.bottomData',height:'100%',style:'white-space: pre;background:white;',overflow:'auto'});var center=bc._('contentPane',{'region':'center'});center._('tree',{'storepath':storepath,fired:'^gnr.debugger.tree_redraw','margin':'6px','nodeId':treeId,'getIconClass':"return 'treeNoIcon'",'_class':'fieldsTree','hideValues':true});center._('dataController',{'script':"genro.debugopt=sqldebug?'sql':null",'sqldebug':'^gnr.debugger.sqldebug'});center._('dataController',{'script':"FIRE gnr.debugger.tree_redraw;",'sqldebug':'^gnr.debugger.main','_delay':1});},devUtilsPalette:function(parent){var pane=parent._('palettePane',{'paletteCode':'devUtils',title:'Utils'});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');};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")'});var bc=pane._('borderContainer');var top=bc._('contentPane',{'region':'top',font_size:'.9em'})._('toolbar',{'height':'18px'});top._('button',{'label':'CheckDb',publish:'devUtils_checkDb'});top._('button',{'label':'DbSetup',publish:'devUtils_dbsetup'});top._('button',{'label':'Clear log',action:'genro.clearlog()'});var center=bc._('contentPane',{'region':'center',font_size:'.9em',overflow:'hidden'});center._('simpleTextArea',{'value':'^gnr._dev.logger',readOnly:true,height:'100%',style:'white-space: pre;'});},openLocalizer:function(){noValueIndicator="<span >&nbsp;</span>";genro.src.getNode()._('div','_localizer');var node=genro.src.getNode('_localizer').clearValue().freeze();genro.setData('gnr.pageLocalization',genro.rpc.remoteCall('localizer.pageLocalizationLoad'));var dlg=node._('dialog',{nodeId:'_localizer',title:'Localizer',width:'40em','padding':'2px'});var xx=dlg._('div',{height:'400px',overflow:'auto',background_color:'#eee',border:'1px inset'});var saveData=function(){var data=genro.getData('gnr.pageLocalization');var cb=function(){genro.pageReload();};genro.rpc.remoteCall('localizer.pageLocalizationSave',{data:data},'bag','POST',null,cb);};dlg._('button',{label:'Save',margin:'4px','float':'right',onClick:saveData});var nodes=genro.getData('gnr.pageLocalization').getNodes();var tbl=xx._('table',{_class:'localizationTable',width:'100%'});var thead=tbl._('thead');var r=thead._('tr');r._('th',{content:'Key'});r._('th',{content:'Value'});var tbody=tbl._('tbody');for(var i=0;i<nodes.length;i++){var r=tbody._('tr',{datapath:'gnr.pageLocalization.r_'+i});r._('td',{width:'15em'})._('div',{innerHTML:'^.key'});r._('td')._('inlineeditbox',{value:'^.txt',noValueIndicator:noValueIndicator});}
node.unfreeze();genro.wdgById('_localizer').show();},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');}},showDebugger:function(){if(!dijit.byId("gnr_devTools")){genro.dev.openInspector();}},shortcut:function(shortcut,callback,opt){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=='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);else if(ele.attachEvent)ele.attachEvent('on'+opt['type'],func);else ele['on'+opt['type']]=func;}});



dojo.declare("gnr.GnrDlgHandler",null,{constructor:function(application){this.application=application;},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'});var 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'});}},alert:function(msg,title,buttons,resultPath,kw){genro.src.getNode()._('div','_dlg_alert');var title=title||'';var buttons=buttons||{confirm:'OK'};var kw=kw||{};var resultPath=resultPath||'dummy';var node=genro.src.getNode('_dlg_alert').clearValue().freeze();var dlg=node._('dialog',objectUpdate({nodeId:'_dlg_alert',title:title,toggle:"fade",toggleDuration:250,centerOn:'_pageRoot'},kw))._('div',{_class:'dlg_ask','action':"genro.wdgById('_dlg_alert').hide();genro.fireEvent('"+resultPath+"',this.attr.actCode);"});dlg._('div',{'innerHTML':msg,'_class':'dlg_ask_msg'});var buttonBox=dlg._('div',{'_class':'dlg_ask_btnBox'});for(var btn in buttons){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn});}
node.unfreeze();genro.wdgById('_dlg_alert').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'];var dlg=node._('dialog',{nodeId:'_dlg_alert',title:'',toggle:"fade",toggleDuration:250,centerOn:'_pageRoot'})._('div');var tbl=dlg._('table',{});tbl=tbl._('tbody',{});var r=tbl._('tr');r._('td',{content:'From'});r._('td',{})._('div',{innerHTML:msgattr['from_user']});r=tbl._('tr');r._('td',{content:'Message'});r._('td',{})._('div',{innerHTML:msgtext});node.unfreeze();genro.wdgById('_dlg_alert').show();},ask:function(title,msg,buttons,resultPathOrActions){genro.src.getNode()._('div','_dlg_ask');var buttons=buttons||{confirm:'Confirm',cancel:'Cancel'};var action;var node=genro.src.getNode('_dlg_ask').clearValue().freeze();if(typeof(resultPathOrActions)=='string'){var resultPath=resultPathOrActions;var actions={};action="genro.wdgById('_dlg_ask').hide();genro.fireEvent('"+resultPath+"',this.attr.actCode);";}
else{var actions=resultPathOrActions||{};action="genro.wdgById('_dlg_ask').hide();if (this.attr.act){funcCreate(this.attr.act).call();};";}
var dlg=node._('dialog',{nodeId:'_dlg_ask',title:title,centerOn:'_pageRoot'})._('div',{_class:'dlg_ask','action':action});dlg._('div',{'content':msg,'_class':'dlg_ask_msg'});var buttonBox=dlg._('div',{'_class':'dlg_ask_btnBox'});for(var btn in buttons){dlg._('button',{'_class':'dlg_ask_btn','label':buttons[btn],'actCode':btn,'act':actions[btn]});}
node.unfreeze();genro.wdgById('_dlg_ask').show();},thermoFloating:function(thermopath){},batchMonitor:function(thermopath){var 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;dojo.publish("standardMsg",[{message:msg,type:level,duration:duration}]);},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':'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);},quickDialog:function(title,kw){var kw=kw||{};genro.src.getNode()._('div','_dlg_quick');var node=genro.src.getNode('_dlg_quick').clearValue();node.freeze();var dlg=node._('dialog',objectUpdate({title:title},kw));var center=dlg._('div',{_class:'pbl_dialog_center'});var bottom=dlg._('div',{_class:'dialog_bottom'});dlg.center=center;dlg.bottom=bottom;dlg.close_action=function(){dlg.getParentNode().widget.hide()};dlg.show_action=function(){node.unfreeze();dlg.getParentNode().widget.show()};return dlg;},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':'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();},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.css3AttrNames=['rounded','gradient','shadow','transform','transition'];this.styleAttrNames=['height','width','top','left','right','bottom','visibility','overflow','float','clear','display','z_index','border','position','padding','margin','color','white_space','vertical_align','background'].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{var cssText=document.createTextNode(cssText);style.appendChild(cssText);}
document.getElementsByTagName("head")[0].appendChild(style);style.disabled=false;},loadCss:function(url,cssTitle){var e=document.createElement("link");e.href=url;e.type="text/css";e.rel="stylesheet";e.media="screen";document.getElementsByTagName("head")[0].appendChild(e);},loadJs:function(url){var e=document.createElement("script");e.src=url;e.type="text/javascript";document.getElementsByTagName("head")[0].appendChild(e);},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(domnode){if(typeof(attr)=='string'){dojo.style(domnode,genro.dom.dojoStyleAttrName(attr),value);}else{var kw={};for(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;},ghostOnEvent:function(evt){evt_type=evt.type;if(evt_type=='focus'||evt_type=='blur'){genro.dom[evt_type=='focus'?'addClass':'removeClass'](evt.target.id+"_label","ghostpartial");}
else if(evt_type=='keyup'||evt_type=='keypress'){genro.dom[evt.target.value.length>0?'addClass':'removeClass'](evt.target.id+"_label","ghosthidden");}else if(evt_type=='setvalue'){genro.dom[evt.value.length>0?'addClass':'removeClass'](evt.obj.id+"_label","ghosthidden");}},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;},enableDisableNodes:function(where){if(typeof(where)=='string'){var where=genro.domById(where);}},resizeContainer:function(wdgt){if(wdgt.parent&&wdgt.parent.isContainer){this.resizeContainer(wdgt.parent);}else if(wdgt.isContainer){wdgt.onResized();}},getStyleDict:function(attributes,noConvertStyle){if(attributes.gnrIcon){attributes.iconClass='gnrIcon gnrIcon'+objectPop(attributes,'gnrIcon');}
var noConvertStyle=noConvertStyle||[];var styledict=objectFromStyle(objectPop(attributes,'style'));var attrname;dojo.forEach(this.css3AttrNames,function(name){var value=objectPop(attributes,name);var valuedict=objectExtract(attributes,name+'_*');if(value||objectNotEmpty(valuedict)){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_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('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]=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=dojo.isSafari?'-webkit-box-shadow':'-moz-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_*');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=dojo.isSafari?function(y,x){return'-webkit-border-'+y+'-'+x+'-radius';}:function(y,x){return'-moz-border-radius-'+y+x;};var rounded_corners=this.normalizedRoundedCorners(value,valuedict);for(var k in rounded_corners){var 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;if(rounded){rounded_dict['all']=rounded;}
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(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(){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){result=new gnr.GnrBag();var rule;for(var i=s.length;s--;){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);}else if(kw.evt=='del'){}
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(dragSourceInfo.detachable){return'detach';}
var inherited=sourceNode.getInheritedAttributes();var supportedTypes=sourceNode.getInheritedAttributes().dropTypes;var 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);}
event.stopPropagation();event.preventDefault();event.dataTransfer.dropEffect="move";},getDragDropInfo:function(event){var domnode=event.target;while(!domnode.getAttribute){domnode=domnode.parentNode;}
var info={'domnode':domnode};info.modifiers=genro.dom.getEventModifiers(event);var widget,handler,sourceNode;if(domnode.sourceNode){info.handler=domnode.gnr;info.sourceNode=domnode.sourceNode;info.nodeId=domnode.sourceNode.attr.nodeId;}
else{widget=dijit.getEnclosingWidget(domnode);if(!widget){return;}
var rootwidget=widget.sourceNode?widget:widget.grid||widget.tree;info.widget=widget;if(!rootwidget){return;}
info.handler=rootwidget.gnr;info.sourceNode=rootwidget.sourceNode;info.nodeId=info.sourceNode.attr.nodeId;}
info.event=event;if(event.type=='dragstart'){info.dragmode=domnode.getAttribute('dragmode');info.handler.fillDragInfo(info);info.drag=true;}else{info.drop=true;var sourceNode=info.sourceNode;var attr=sourceNode.attr;var dropTarget=sourceNode.dropTarget||attr.selfDragRows||attr.selfDragColumns;var dropTargetCb=sourceNode.dropTargetCb;info.dragSourceInfo=genro.dom.getDragSourceInfo(event.dataTransfer);if(info.dragSourceInfo.detachable){return info;}
if(dropTarget||dropTargetCb){info.sourceNodeId=info.dragSourceInfo.nodeId;info.selfdrop=(info.nodeId&&(info.nodeId==info.sourceNodeId));info.hasDragType=function(){var draggedTypes=genro.dom.dataTransferTypes(event.dataTransfer);return(dojo.filter(arguments,function(value){return dojo.indexOf(draggedTypes,value)>=0;}).length>0);};var continueDrop=!(info.handler.fillDropInfo(info)===false);if(!continueDrop||(dropTargetCb&&(!dropTargetCb(info)))){info=null;}}
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,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.dom.removeClass(dojo.body(),'drag_to_trash');}},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:detached_id});floating._('div',{height:coords.h+'px',width:coords.w+'px',_class:'detatched_placeholder',id:detached_id});floating=floating.getParentNode().widget;var placeholder=floating.containerNode.firstElementChild;var currentParent=domnode.parentNode;currentParent.replaceChild(placeholder,domnode);floating.containerNode.appendChild(domnode);sourceNode.attr.isDetached=true;dojo.connect(floating,'hide',function(){var widget=dijit.getEnclosingWidget(placeholder);widget.setContent(domnode);sourceNode.attr.isDetached=false;floating.close();});floating.show();coords.h=coords.h+dojo.coords(floating.domNode).h;floating.resize(coords);},onDrop:function(event){genro.dom.outlineShape(null);event.stopPropagation();var dropInfo=this.getDragDropInfo(event);if(!dropInfo){event.preventDefault();return;}
var domnode=dropInfo.domnode;var sourceNode=dropInfo.sourceNode;var dataTransfer=event.dataTransfer;var dragSourceInfo=genro.dom.getDragSourceInfo(dataTransfer);if(dragSourceInfo.detachable){event.preventDefault();genro.dom.onDetach(genro.src.nodeBySourceNodeId(dragSourceInfo._id),dropInfo);return;}
var canBeDropped=this.canBeDropped(dataTransfer,sourceNode);if(canBeDropped){var inherited=sourceNode.getInheritedAttributes();event.preventDefault();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):null;var files=[];dojo.forEach(dataTransfer.files,function(f){if((!valid_ext)||(dojo.indexOf(valid_ext,f['name'].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('sourceNode_')==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);}},onDragStart:function(event){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){return false;}
var inherited=sourceNode.getInheritedAttributes();if('onDrag'in inherited){var doDrag=funcCreate(inherited['onDrag'],'dragValues,dragInfo,treeItem')(dragValues,dragInfo,dragInfo.treeItem);if(doDrag===false){return;}}
var domnode=dragInfo.target;var widget=dragInfo.widget;genro.dom._transferObj={};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);}}
if('trashable'in dragValues){if(widget){if(widget.gnr.setTrashPosition(dragInfo)){genro.dom.addClass(dojo.body(),'drag_to_trash');};}}
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);if(genro.dom.dragDropPatch()){genro.dom._transferObj[k]=v;}},setDragSourceInfo:function(dragInfo,dragValues,dragTags){if(dragInfo.nodeId){dragValues['sourceNode_nodeId:'+dragInfo.nodeId]=null;}
if(dragInfo.sourceNode){dragValues['sourceNode__id:'+dragInfo.sourceNode._id]=null;if(dragInfo.sourceNode.getAttributeFromDatasource('detachable')){dragValues['sourceNode_detachable:true']=null;}}
if(dragInfo.dragmode){dragValues['sourceNode_dragmode:'+dragInfo.dragmode]=null;}
dragValues['sourceNode_page_id:'+genro.page_id]=null;if(dragTags){dragValues['sourceNode_dragTags:'+dragTags]=null;}},getDragSourceInfo:function(dataTransfer){var draggedTypes=genro.dom.dataTransferTypes(dataTransfer);var dt;var result={};for(var i=0;i<draggedTypes.length;i++){if(draggedTypes[i].indexOf('sourceNode_')==0){dt=draggedTypes[i].slice(11).split(':');result[dt[0]]=dt[1];}};return result;},getFromDataTransfer:function(dataTransfer,k){var value=genro.dom.dragDropPatch()?(genro.dom._transferObj?genro.dom._transferObj[k]:null):dataTransfer.getData(k);return convertFromText(value);},dataTransferTypes:function(dataTransfer){if(genro.dom.dragDropPatch()){var dt=[];if(genro.dom._transferObj){for(var k in genro.dom._transferObj){dt.push(k);}}
for(var i=0;i<dataTransfer.types.length;i++){dt.push(dataTransfer.types[i]);};return dt;}else{return dataTransfer.types;}
return dataTransfer.types;},onDragEnd:function(event){genro.dom.outlineShape(null);},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();},dragDropPatch:function(){return(genro.isChrome);},startTouchDevice:function(){document.body.ontouchmove=function(e){e.preventDefault();};document.body.onorientationchange=function(e){genro.setData('touch.orientation',window.orientation);};dojo.connect(document.body,'gestureend',function(e){genro.dom.logTouchEvent('gesture',e);});},logTouchEvent:function(path,e){var b='';for(var k in e){b=b+k+':'+e[k]+'<br/>';}
genro.setData('touch.event.'+path,b);},scrollableTable:function(domnode,gridbag,kw){var columns=kw.columns;var headers=kw.headers;var tblclass=kw.tblclass;var thead='<thead><tr>';for(var k=0;k<columns.length;k++){thead=thead+"<th>"+headers[k]+"</th>";}
thead=thead+"<th style='width:10px; background-color:transparent;'>&nbsp</th></thead>";var nodes=gridbag.getNodes();var item,r,value;var tbl=["<tbody>"];for(var i=0;i<nodes.length;i++){r="";item=nodes[i].attr;for(var k=0;k<columns.length;k++){value=item[columns[k]]||'&nbsp';r=r+"<td>"+genro.format(value,{date:'short'});+"</td>";}
tbl.push("<tr id='"+nodes[i].label+"'>"+r+"</tr>");}
tbl.push("</tbody>");var tbody=tbl.join('');var cbf=function(cgr){var cgr_h=cgr?'<colgroup>'+cgr+'<col width=10 /></colgroup>':'';var cgr_b=cgr?'<colgroup>'+cgr+'</colgroup>':'';return'<div class="'+tblclass+'"><div><table>'+cgr_h+''+thead+'</table></div><div style="overflow-y:auto;max-height:180px;"><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);},centerOn:function(what,where,onlyX,onlyY){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;if(!onlyY){style.left=Math.floor((deltax+(viewport.w-mb.w)/2))+"px";}
if(!onlyX){style.top=Math.floor((deltay+(viewport.h-mb.h)/2))+"px";}},makeHiderLayer:function(parentId,kw){var rootNode=parentId?genro.nodeById(parentId):genro.src.getNode();var default_kw={'position':'absolute',top:'0',left:'0',right:'0','bottom':0,z_index:1000,background_color:'rgba(255,255,255,0.5)',id:parentId+'_hider'};var kw=objectUpdate(default_kw,kw);return rootNode._('div',kw).getParentNode();}});



dojo.declare("gnr.widgets.protovis",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){if(sourceNode.attr.storepath){sourceNode.registerDynAttr('storepath');}},created:function(newobj,savedAttrs,sourceNode){dojo.subscribe(sourceNode.attr.nodeId+'_render',this,function(){this.render(newobj);});},setStorepath:function(obj,value){obj.gnr.update(obj);},attachToDom:function(domNode,vis){var span=document.createElement('span');var fc=domNode.firstElementChild;if(fc){domNode.replaceChild(span,fc);}else{domNode.appendChild(span);}
vis.$dom=span;return span;},update:function(domNode){var sourceNode=domNode.sourceNode;if((sourceNode.vis)&&(!sourceNode.visError)){sourceNode.vis.render();}else{this.render(domNode);}},render:function(domNode){var sourceNode=domNode.sourceNode;try{this._doRender(domNode);sourceNode.visError=null;}catch(e){console.log('error in rendering protovis '+sourceNode.attr.nodeId+' : '+e);sourceNode.visError=e;}},_doRender:function(domNode){var sourceNode=domNode.sourceNode;if(sourceNode.attr.js){var vis=new pv.Panel();var protovis=pv.parse(sourceNode.getAttributeFromDatasource('js'));funcApply(protovis,objectUpdate({'vis':vis},sourceNode.currentAttributes()),sourceNode);}
else if(sourceNode.attr.storepath){var storepath=sourceNode.attr.storepath;var visbag=sourceNode.getRelativeData(storepath).getItem('#0');var vis;_this=this;sourceNode.protovisEnv={};visbag.forEach(function(n){vis=_this.bnode(sourceNode,n)||vis;});}
this.attachToDom(domNode,vis);sourceNode.vis=vis;vis.render();},storegetter:function(sourceNode,path){var p=path;var s=sourceNode;return function(){return s.getRelativeData(p);};},bnode:function(sourceNode,node,parent){var env=sourceNode.protovisEnv;var storepath=sourceNode.attr.storepath;var attr=objectUpdate({},node.attr);var tag=objectPop(attr,'tag');if(tag=='env'){console.log(node.getValue());env[node.label]=eval(node.getValue());return;}
var obj=parent?parent.add(pv[tag]):new pv[tag]();this._convertAttr(sourceNode,obj,attr);var v=node.getValue();_this=this;if(v instanceof gnr.GnrBag){v.forEach(function(n){_this.bnode(sourceNode,n,obj);});}
return obj;},_convertAttr:function(sourceNode,obj,attr){var env=sourceNode.protovisEnv;var storepath=sourceNode.attr.storepath;for(var k in attr){var v=attr[k];if(stringEndsWith(k,'_js')){k=k.slice(0,-3);v=genro.evaluate(v);}
else if(stringEndsWith(k,'_fn')){k=k.slice(0,-3);v=genro.evaluate('function(){return '+v+'}');}
else if(k.indexOf('_fn_')>0){k=k.split('_fn_');var fn='function('+k[1]+'){return ('+v+')}';v=genro.evaluate(fn);k=k[0];}
if((typeof(v)=='string')&&(v[0]=='=')){path=v.slice(1);if(path[0]=='.'){path=storepath+path;}
v=this.storegetter(sourceNode,path);}
if(k.indexOf('_')>0){k=k.split('_');obj[k[0]](k[1],v);}else{obj[k](v);}}}});dojo.declare("gnr.widgets.CkEditor",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){attributes.id=attributes.id||'ckedit_'+sourceNode.getStringId();var toolbar=objectPop(attributes,'toolbar');var config=objectExtract(attributes,'config_*');if(typeof(toolbar)=='string'){toolbar=genro.evaluate(toolbar);};if(toolbar){config.toolbar='custom';config.toolbar_custom=toolbar;};var savedAttrs={'config':config};return savedAttrs;},created:function(widget,savedAttrs,sourceNode){CKEDITOR.replace(widget,savedAttrs.config);var ckeditor_id='ckedit_'+sourceNode.getStringId();var ckeditor=CKEDITOR.instances[ckeditor_id];sourceNode.externalWidget=ckeditor;ckeditor.sourceNode=sourceNode;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');},connectChangeEvent:function(obj){var ckeditor=obj.sourceNode.externalWidget;dojo.connect(ckeditor.focusManager,'blur',ckeditor,'gnr_setInDatastore');dojo.connect(ckeditor.editor,'paste',ckeditor,'gnr_setInDatastore');},mixin_gnr_value:function(value,kw,reason){this.setData(value);},mixin_gnr_getFromDatastore:function(){this.setData(this.sourceNode.getAttributeFromDatasource('value'));},mixin_gnr_setInDatastore:function(){this.sourceNode.setAttributeInDatasource('value',this.getData());},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);}}});




