// 1269525773.0
dojo.declare("gnr.GnrBagNode",null,{_counter:[0],constructor:function(parentbag,label,value,_attr,_resolver){this._id=this._counter[0]+=1;this.label=(label=='#id')?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;}},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'));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);},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];}
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=='#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);},popNode:function(path,doTrigger){var node=this.htraverse(path);var obj=node.value;var label=node.label;if(obj){return obj._pop(label,doTrigger);}},_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(){},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,path){var bags=[];if(!path){var path=[];}
for(var i=0;i<this._nodes.length;i++){var node=this._nodes[i];if(node.hasAttr(attr,value)){path.push(node.label);return node;}
if(node.getValue('static')instanceof gnr.GnrBag){bags.push(node);}}
for(var i=0;i<bags.length;i++){var node=bags[i];var nl=[node.label];n=node.getValue('static').getNodeByAttr(attr,value,nl);if(n){path.concat(nl);return n;}}},getNode:function(path,asTuple,autocreate,_default){if(path==null){return;}
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});}}
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);},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 auxattr={};auxattr[attr]=value;var node=obj.getNode(label,false,true);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);}
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=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('::');itemValue=convertFromText(itemValue[0],itemValue[1]);convertAs=itemValue[1];}
if(convertAs=='H'){attributes.dtype=convertAs;}
if(resolverPars!=null){resolverPars=genro.evaluate(resolverPars);var cacheTime=resolverPars['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!=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;},_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);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);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;};



var dojoversion=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.dnd.Source");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;setTimeout(dojo.hitch(this,'genroInit'),1);},genroInit:function(){this.startTime=new Date();this.lastTime=this.startTime;this.dialogStack=[];this.sounds={};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);genropatches.comboBox();genropatches.tree();genropatches.parseNumbers();if(dojoversion=='1.1'){genropatches.borderContainer();}
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();},bp:function(aux){console.log('bp '+aux);},onWindowUnload:function(e){if(genro._data){this.rpc.remoteCall('onClosePage',{sync:true});genro.saveContextCookie();}},saveContextCookie:function(){var clientCtx=genro.getData('_clientCtx');if(clientCtx){dojo.cookie("genroContext",clientCtx.toXml(),{expires:5,path:genro.getData('gnr.homeUrl')});}},clientCtx:function(path){var path=path?'.'+path:'';return genro._('_clientCtx'+path);},warning:function(msg){console.warn(msg);genro.dlg.message(msg);},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.dev.srcInspector(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});var _this=this;this._dataroot.subscribe('dataTriggers',{'any':dojo.hitch(this,"dataTrigger")});genro.dev.shortcut("Ctrl+Shift+D",function(){genro.dev.showDebugger();});genro.dev.shortcut("Ctrl+Shift+B",function(){genro.dev.showBottomHelper();});genro.callAfter(function(){genro.fireEvent('gnr.onStart');},100);dojo.publish('onPageStart',[]);var windowTitle=this.getData('gnr.windowTitle');if(windowTitle){genro.dom.windowTitle(windowTitle);}
if(this.debugopt){genro.setData('debugger.sqldebug',this.debugopt.indexOf('sql')>=0);genro.setData('debugger.pydebug',this.debugopt.indexOf('py')>=0);genro.dev.showBottomHelper();}},playSound:function(name,path,ext){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){genro.rpc.remoteCall('setInServer',{path:path,value:value});},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);},fireEvent:function(path,msg){msg=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(){return;},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;setTimeout(function(){genro.fireEvent(_path,_msg);},timeout);},setDataAfter:function(path,value,timeout){var timeout=timeout||1;var _path=path;var _msg=msg;setTimeout(function(){genro.setData(_path,_msg);},timeout);},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];}},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>";}
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);}},getCounter:function(){this._counter=this._counter+1;return this._counter;},blurCurrent:function(a,b,c){if(genro.currentFocusedElement){genro.currentFocusedElement.blur();}},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:'hidden',width:'0px',height:'0px'};if(onload_cb){if(onload_cb=='print'){onload_cb="genro.dom.iFramePrint(this.domNode);";}
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['xxcnt']=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){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(typeof(obj)=='string'){return 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){var path=genro.src.getNode().absDatapath(path);return this._data.getItem(path,dflt);},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){var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
dojo.publish(topic,args);},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['xxcnt']=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){console.log('Loaded from '+sessionType+'Storage at key:'+key+'  value:'+value);}else{console.log('Not existing in '+sessionType+'Storage key:'+key);}
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();}},formById:function(formId){var node=genro.nodeById(formId);if(node){return node.formHandler;}},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);},setSelectedVal:function(obj,value){var dataNode=genro.getDataNode(obj.sourceNode);dataNode.setAttr({'selectedValue':value});},evaluate:function(expr){if(genro._lastEvaluated){console.warn('there was an error during evaluation:'+genro._lastEvaluated);};var toEval='genro.auxresult=('+expr+')';genro._lastEvaluated=toEval;dojo.eval(toEval);genro._lastEvaluated=null;return genro.auxresult;},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['xxcnt']=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');}});dojo.declare("gnr.GnrClientCaller",gnr.GnrBagsResolver,{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);}}});



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={};savedAttrs.connectedMenu=objectPop(attributes,'connectedMenu');savedAttrs.dragDrop=objectExtract(attributes,'dnd_*');savedAttrs.onEnter=objectPop(attributes,'onEnter');objectUpdate(savedAttrs,this.creating(attributes,sourceNode));if(sourceNode&&objectNotEmpty(savedAttrs.dragDrop)&&(!attributes.id)){attributes['id']=sourceNode.getStringId();savedAttrs.dom_id=attributes['id'];}
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 dlgId=objectPop(attributes,'dlgId');sourceNode.attr.nodeId=formId;sourceNode.defineForm(formId,sourceNode.absDatapath(),dlgId);}
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');if(iconClass){if(attributes['title']){attributes['title']='<span class="'+iconClass+'"/><span style="padding-left:20px;">'+attributes['title']+'</span>';}
else{attributes['title']='<div class="'+iconClass+'"/>';}};if(attributes['title']){var tip=objectPop(attributes,'tip');attributes['title']='<span title="'+tip+'">'+attributes['title']+'</span>';};},dndSettings:function(newobj,sourceNode,savedAttrs){var dragDrop=savedAttrs.dragDrop;var domNode=newobj.domNode||newobj;if(!domNode){return;}
var checkAcceptance=function(source,nodes){if(this==source){return true;}else if(source.tree){return true;}else{for(var i=0;i<nodes.length;++i){var type=source.getItem(nodes[i].id).type;var flag=false;for(var j=0;j<type.length;++j){if(type[j]in this.accept){flag=true;break;}}
if(!flag){return false;}}
return true;}};if(dragDrop.source||dragDrop.target){var dndPars={isSource:dragDrop.source||false,horizontal:dragDrop.horizontal||false,copyOnly:dragDrop.copyOnly||false,skipForm:dragDrop.skipForm||false,withHandles:dragDrop.withHandles||false,accept:dragDrop.accept?dragDrop.accept.split(','):[],singular:(dragDrop.singular==false)?false:true};if(dragDrop.onDndDrop){dndPars.onDndDrop=dragDrop.onDndDrop;}
sourceNode.dndSource=new dojo.dnd.Source(savedAttrs.dom_id,dndPars);sourceNode.dndSource.checkAcceptance=checkAcceptance;}else if(dragDrop.target){sourceNode.dndTarget=new dojo.dnd.Target(savedAttrs.dom_id);sourceNode.dndTarget.checkAcceptance=checkAcceptance;}else if(dragDrop.allowDrop){sourceNode.dndTarget=new dojo.dnd.Target(savedAttrs.dom_id);var checkAcceptanceFunc=funcCreate(dragDrop.allowDrop||'return true;','item');sourceNode.dndTarget.checkAcceptance=function(source,nodes){if(source.tree){return checkAcceptanceFunc.call(sourceNode,source.tree.getItemById(nodes[0].id));}else{}};}else if(dragDrop.itemType){var dndSource=domNode.sourceNode.getParentNode().dndSource;if(dndSource){dojo.addClass(domNode,'dojoDndItem');dndSource.setItem(domNode.id,{data:null,type:dragDrop.itemType});}}
if(dragDrop['onDrop']){var onDndDropFunc=funcCreate(dragDrop['onDrop'],'item, copy');sourceNode.dndTarget.onDndDrop=function(source,nodes,copy){if(source.tree){if(this==dojo.dnd.manager().target){onDndDropFunc.call(sourceNode,source.tree.getItemById(nodes[0].id),copy);}}else{}};}},_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(savedAttrs.zoomFactor){sourceNode.setZoomFactor(savedAttrs.zoomFactor);}
if(!sourceNode){return;}
if(objectNotEmpty(savedAttrs.dragDrop)){this.dndSettings(newobj,sourceNode,savedAttrs);}
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);};dojo.connect(newobj,'onfocus',function(e){genro.currentFocusedElement=newobj.domNode||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});});}},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 oldvalue=genro._data.getItem(path);if(oldvalue===value){return;}
var validateresult;var valueAttr=valueAttr||null;if(sourceNode.hasValidations()){validateresult=sourceNode.validationsOnChange(sourceNode,value);value=validateresult['value'];}
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;},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');var closable=('closable'in attributes)?objectPop(attributes,'closable'):true;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=='ask'){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: onAskCancel\">\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(newobj,savedAttrs,sourceNode){dojo.connect(newobj,"show",newobj,function(){if(this!=genro.dialogStack.slice(-1)[0]){genro.dialogStack.push(this);if(genro.dialogStack.length>1){genro.dialogStack.slice(-2)[0].hide();}}});dojo.connect(newobj,"hide",newobj,function(){if(this==genro.dialogStack.slice(-1)[0]){genro.dialogStack.pop();if(genro.dialogStack.length>0){genro.dialogStack.slice(-1)[0].show();}}});},patch__position:function(){var centerOn=this.sourceNode.attr.centerOn;if(!centerOn){this._position_replaced();}
else
{var viewport=dojo.coords(genro.domById(centerOn));viewport.l=viewport.x;viewport.t=viewport.y;var mb=dojo.marginBox(this.domNode);var style=this.domNode.style;style.left=Math.floor((viewport.l+(viewport.w-mb.w)/2))+"px";style.top=Math.floor((viewport.t+(viewport.h-mb.h)/2))+"px";}},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:''});},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){var selpath=sourceNode.attr['selected'];var selpage=sourceNode.attr['selectedPage'];widget.gnrPageDict={};if(selpath||selpage){var controller=widget.tablist||widget;var evt=(controller==widget)?'selectChild':'onSelectChild';dojo.connect(controller,evt,dojo.hitch(widget,function(child){if(!widget.sourceNode._isBuilding){if(selpath){this.sourceNode.setRelativeData(selpath,this.getChildIndex(child));}
if(selpage){this.sourceNode.setRelativeData(selpage,child.sourceNode.attr.pageName);}}}));dojo.connect(widget,'addChild',dojo.hitch(this,'onAddChild',widget));dojo.connect(widget,'removeChild',dojo.hitch(this,'onRemoveChild',widget));}},mixin_setSelected:function(p){var child=this.getChildren()[p||0];if(this.sourceNode.attr['selectedPage']){this.sourceNode.setAttributeInDatasource('selectedPage',child.sourceNode.attr.pageName);}
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_setSelectedPage:function(pageName){var child=this.gnrPageDict[pageName];if(child){if(this.sourceNode.attr['selected']){this.sourceNode.setAttributeInDatasource('selected',this.getChildIndex(child));}
this.selectChild(child);}},mixin_getChildIndex:function(obj){return dojo.indexOf(this.getChildren(),obj);},onAddChild:function(widget,child){var pageName=child.sourceNode.attr.pageName;if(pageName){widget.gnrPageDict[pageName]=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){}});dojo.declare("gnr.widgets.BorderContainer",gnr.widgets.baseDojo,{creating:function(attributes,sourceNode){if(dojoversion!='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(dojoversion=='1.7'){dojo.connect(widget,'addChild',dojo.hitch(this,'onAddChild',widget));}},afterStartup:function(widget){var sourceNode=widget.sourceNode;if(dojoversion!='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.FloatingPane",gnr.widgets.baseDojo,{constructor:function(application){this._domtag='div';this._dojotag='FloatingPane';}});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';}
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_addChild:function(popUpContent){if(popUpContent.declaredClass=='dijit.Menu'){this.popup=popUpContent;}
if(this.addChild_replaced){this.addChild_replaced.call(this,popUpContent);}},patch_onClick:function(){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);}
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();},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);},patch__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();gnr.menuFromBag(result,menubag,sourceNode.attr._class,sourceNode.attr.fullpath);sourceNode.setValue(menubag);}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);this._openMyself_replaced.call(this,e);}},patch__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);}},patch_postCreate:function(){if(dojoversion=='1.1'){if(this.srcNodeRef){this.srcNodeRef.style.display="none";}}else{dojo.addClass(this.domNode,"dijitTooltipData");}
this.connectAllNodes(this.connectId);},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(dojoversion=='1.1'){eventlist=["onMouseOver","onMouseOut","onFocus","onBlur","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');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onClick',sourceNode,this.onClick);objectExtract(sourceNode._dynattr,'fire_*');objectPop(sourceNode._dynattr,'fire');if(savedAttrs['_style']){var buttonNode=dojo.query(".dijitButtonNode",widget.domNode)[0];dojo.style(buttonNode,savedAttrs['_style']);}},onClick:function(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,null,true);}
var fire_list=objectExtract(this.attr,'fire_*',true);for(var fire in fire_list){this.setRelativeData(fire_list[fire],fire,null,true);}}});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');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){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']);}},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(dojoversion=='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){var structure=genro.getData(this.sourceNode.attrDatapath('structpath'));this.cellmap={};this.setStructure(this.gnr.structFromBag(structure,this.cellmap,this.gnreditors));this.onSetStructpath(structure);},mixin_onSetStructpath:function(structure){return;},created:function(widget,savedAttrs,sourceNode){genro.src.afterBuildCalls.push(dojo.hitch(widget,'render'));dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');dojo.connect(widget,'modelAllChange',dojo.hitch(sourceNode,this.modelAllChange));objectFuncReplace(widget.selection,'clickSelectEvent',function(e){this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);});},modelAllChange:function(){if(this.attr.rowcount){this.setRelativeData(this.attr.rowcount,this.widget.rowCount);}},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);}},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_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_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(struct,cellmap,gnreditors){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');}
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='var ev = arguments[0]; if(!ev.metaKey){dojo.stopEvent(ev);}' class='gnrzoomcell' href='/"+zoomPage+"?pkey="+key+"&autoLinkFrom="+genro.page_id+"'>"+v+"</a>";}
return v;};};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);}
cellsnodes=rowBag.getNodes();row=[];for(j=0;j<cellsnodes.length;j++){cell=objectUpdate({},rowattrs);cell=objectUpdate(cell,cellsnodes[j].attr);dtype=cell.dtype;if(gnreditors[cell.field]){this.setCellEditor(cell,gnreditors[cell.field]);}
cell.original_field=cell.field;if(!cell.field){console.log('line 1747');}
cell.field=cell.field.replace(/\W/g,'_');if(dtype){cell.cellClasses=(cell.cellClasses||'')+' cell_'+dtype;}
cell.cellStyles=objectAsStyle(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(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(',');}});dojo.declare("gnr.widgets.VirtualGrid",gnr.widgets.Grid,{constructor:function(application){this._domtag='div';this._dojotag='VirtualGrid';},creating:function(attributes,sourceNode){var savedAttrs=objectExtract(attributes,'selected*');var sortedBy=objectPop(attributes,'sortedBy');var identifier=objectPop(attributes,'identifier','_pkey');var gridAttributes=objectExtract(attributes,'autoHeight,autoRender,autoWidth,defaultHeight,elasticView,fastScroll,keepRows,model,rowCount,rowsPerPage,singleClickEdit,structure');objectPopAll(attributes);objectUpdate(attributes,gridAttributes);attributes.rowsPerPage=attributes.rowsPerPage||10;attributes.rowCount=attributes.rowCount||0;attributes.fastScroll=attributes.fastScroll||false;var structpath=sourceNode.attr.structpath;var storepath=sourceNode.absDatapath(sourceNode.attr.storepath);sourceNode.registerDynAttr('structpath');structure=genro.getData(sourceNode.absDatapath(structpath));attributes._identifier=identifier;attributes.cellmap={};attributes.gnreditors={};attributes.structure=this.structFromBag(structure,attributes.cellmap,attributes.gnreditors);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.sortedBy=sortedBy;attributes.canSort=function(){return true;};sourceNode.attr.nodeId=sourceNode.attr.nodeId||'grid_'+sourceNode.getStringId();},created:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');objectFuncReplace(widget.selection,'clickSelectEvent',function(e){this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);});},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){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){this.currCachedPage=this.loadBagPageFromServer(pageIdx);}}
return this.currCachedPage.getNodes()[rowIdx].attr;},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=objectExtract(attributes,'selected*');var sortedBy=objectPop(attributes,'sortedBy');var identifier=objectPop(attributes,'identifier','_pkey');var datamode=objectPop(attributes,'datamode','attr');var gridAttributes=objectExtract(attributes,'autoHeight,autoRender,autoWidth,defaultHeight,elasticView,fastScroll,keepRows,model,rowCount,rowsPerPage,singleClickEdit,structure,filterColumn');objectPopAll(attributes);sourceNode.registerDynAttr('storepath');sourceNode.registerDynAttr('structpath');objectUpdate(attributes,gridAttributes);attributes.rowCount=0;attributes.rowsPerPage=attributes.rowsPerPage||10;attributes.fastScroll=attributes.fastScroll||false;var structpath=sourceNode.attr.structpath;structure=genro.getData(sourceNode.absDatapath(structpath));attributes.cellmap={};attributes.gnreditors={};attributes.structure=this.structFromBag(structure,attributes.cellmap,attributes.gnreditors);attributes._identifier=identifier;attributes.sortedBy=sortedBy;attributes.datamode=datamode;sourceNode.attr.nodeId=sourceNode.attr.nodeId||'grid_'+sourceNode.getStringId();},created:function(widget,savedAttrs,sourceNode){genro.src.afterBuildCalls.push(dojo.hitch(widget,'render'));dojo.connect(widget,'onSelected',widget,'_gnrUpdateSelect');objectFuncReplace(widget.selection,'clickSelectEvent',function(e){this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);});widget.updateRowCount('*');},attributes_mixin_get:function(inRowIndex){return this.grid.rowCached(inRowIndex)[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_filterExcluded:function(rowdata,index){if(this.excludeList){if(dojo.indexOf(this.excludeList,rowdata[this.excludeCol])!=-1){return;}}
this.filtered.push(index);},mixin_applyFilter:function(filtered_value,rendering){var cb;this.excludeList=null;if(this.excludeListCb){this.excludeList=this.excludeListCb();}
if((!filtered_value)||((filtered_value==true)&&(!this.filtered_value))){this.filtered=null;if(this.excludeList){cb=function(node,index,array){var rowdata=this.rowFromBagNode(node);this.filterExcluded(rowdata,index);};this.filtered=[];dojo.forEach(this.storebag().getNodes(),cb,this);}
this.filtered_value=null;this.filtered_compvalue=null;}else{this.filtered=null;this.filtered_value=(filtered_value==true)?this.filtered_value:filtered_value;this.filtered_compvalue=null;var cb,colType;if(this.filterColumn.indexOf('+')>0){colType='T';}else{colType=this.cellmap[this.filterColumn]['dtype']||'A';}
if(colType in{'A':null,'T':null}){this.filtered_compvalue=new RegExp(this.filtered_value,'i');cb=function(node,index,array){var result;var columns=this.filterColumn.split('+');var txt='';var rowdata=this.rowFromBagNode(node);for(var i=0;i<columns.length;i++){txt=txt+' '+rowdata[columns[i]];};result=this.filtered_compvalue.test(txt);if(result){this.filterExcluded(rowdata,index);}};}else{cb=function(node,index,array){var op=this.filtered_compvalue.op;var val=this.filtered_compvalue.val;var rowdata=this.rowFromBagNode(node);var result=this.filtered_compvalue.func.apply(this,[rowdata[this.filterColumn],val]);if(result){this.filterExcluded(rowdata,index);}};var toSearch=/^(\s*)([\<\>\=\!\#]+)(\s*)(.+)$/.exec(this.filtered_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}){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"});}
if(op&&val){var func="return (colval "+op+" fltval)";func=funcCreate(func,'colval,fltval');this.filtered_compvalue={'op':op,'val':val,'func':func};}}}
if(this.filtered_compvalue){this.filtered=[];dojo.forEach(this.storebag().getNodes(),cb,this);}}
this.filterToRebuild=false;if(!rendering){this.updateRowCount('*');}},mixin_newDataStore:function(val,kw){this.updateRowCount(0);this.filtered=null;if(this.sortedBy){var storebag=this.storebag();storebag.sort(this.sortedBy);}
this.updateRowCount();this.selection.unselectAll();if((this.prevSelectedIdentifiers)&&(this.prevSelectedIdentifiers.length>0)){this.selectByRowAttr(this._identifier,this.prevSelectedIdentifiers);this.prevSelectedIdentifiers=null;}
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){}}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){this.updateRowCount();this.setSelectedIndex(kw.ind);}else{}}else if(kw.evt=='del'){if(parent_lv==1){this.updateRowCount();this.setSelectedIndex(kw.ind);}else{}}
this.renderOnIdle();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){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((n==null)||(n=='*')){if(this.filterToRebuild){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_reload:function(keep_selection){if(keep_selection){var prevSelectedIdentifiers=[];var identifier=this._identifier;dojo.forEach(this.getSelectedNodes(),function(node){if(node){prevSelectedIdentifiers.push(node.attr[identifier]);};});this.prevSelectedIdentifiers=prevSelectedIdentifiers;}else{this.prevSelectedIdentifiers=null;}
var storebag=this.storebag();var storeParent=storebag.getParentNode();if(storeParent.getResolver()){storeParent.refresh(true);}
else{var selectionNode=genro.nodeById(this.sourceNode.attr.nodeId+'_selection');if(selectionNode){if(this.filtered){this.filterToRebuild=true;}
selectionNode.fireNode();}}},mixin_onSetStructpath:function(structure){var columns=gnr.columnsFromStruct(structure);if(this.sourceNode.hiddencolumns){columns=columns+','+this.sourceNode.hiddencolumns;}
this.query_columns=columns;if(this.rpcViewColumns){this.rpcViewColumns.call();}
this.reload();},mixin_absIndex:function(inRowIndex){if(this.filterToRebuild){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 nodes=this.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'){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){var node;for(var i=0;i<value._nodes.length;i++){node=value._nodes[i];result[node.label]=node.attr.caption?node.attr.caption:node.getValue();};};}
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){var r=r||this.selection.selectedIndex;var rc=this.findNextEditableCell({row:r,col:-1},{r:0,c:1});if(rc){this.fireEditCell(rc);}},mixin_newBagRow:function(defaultArgs){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{return 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'){return new gnr.GnrBagNode(null,'label',new gnr.GnrBag(defaultArgs));}else{return new gnr.GnrBagNode(null,'label',null,defaultArgs);}}},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);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.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));},mixin_getCellEditor:function(row,col){var cell=this.getCell(col);var editWidget=genro.wdgById(this.editorId+'_'+cell.field);if(editWidget){var cellNode=cell.getNode(row);editWidget.cellNode=cellNode;editWidget.cellRow=row;editWidget.cellCol=col;editWidget.cell=cell;}
return editWidget;},mixin_startEditCell:function(row,col){var editWidget=this.getCellEditor(row,col);if(!editWidget){return;}
this.gnrediting=true;var currentEditedRow=genro._('_temp.grids.'+this.sourceNode.attr.nodeId+'.currentRow');if(currentEditedRow!=row){var selectedDataPath=this.dataNodeByIndex(row).getFullpath(null,true);this.sourceNode.setRelativeData('_temp.grids.'+this.sourceNode.attr.nodeId+'.edit_datapath',selectedDataPath);this.sourceNode.setRelativeData('_temp.grids.'+this.sourceNode.attr.nodeId+'.currentRow',row);setTimeout(dojo.hitch(this,'startEditCell',row,col),1);return;}
editWidget.sourceNode.editedRowIndex=row;editWidget.replacedNode=editWidget.cellNode.childNodes[0];if(editWidget.replacedNode){editWidget.cellNode.replaceChild(editWidget.domNode,editWidget.replacedNode);}else{editWidget.cellNode.appendChild(editWidget.domNode,editWidget.replacedNode);}
editWidget.focus();},mixin_endEditCell:function(editWidget,delta){if(editWidget.cellNode){if(editWidget.cellNode.childNodes[0]==editWidget.domNode){if(editWidget.replacedNode){editWidget.cellNode.replaceChild(editWidget.replacedNode,editWidget.domNode);}
else{editWidget.cellNode.removeChild(editWidget.domNode);}}
if(editWidget.sourceNode.hasValidationError()){}else{}}
var nextEditWidget;if(delta){var rc=this.findNextEditableCell({row:editWidget.cellRow,col:editWidget.cellCol},delta);if(rc){this.fireEditCell(rc);}}
this.gnrediting=false;editWidget.sourceNode.editedRowIndex=null;},mixin_findNextEditableCell:function(rc,delta){var row=rc.row;var col=rc.col;var nextEditWidget;do{col=col+delta.c;if(col>=this.layout.cellCount){col=0;row=row+1;}
if(col<0){col=this.layout.cellCount-1;row=row-1;}
row=row+delta.r;if((row>=this.rowCount)||(row<0)){return;}
nextEditWidget=this.getCellEditor(row,col);}while(!nextEditWidget);rc.col=col;rc.row=row;return rc;},mixin_fireEditCell:function(rc){if(this.startEditTimeout){clearTimeout(this.startEditTimeout);}
this.startEditTimeout=setTimeout(dojo.hitch(this,'startEditCell',rc.row,rc.col),1);},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.GridEditor",gnr.widgets.baseHtml,{constructor:function(application){this._domtag='div';},creating:function(attributes,sourceNode){var viewId=sourceNode.getParentNode().attr.nodeId;attributes.display='none';sourceNode.attr.nodeId='grided_'+sourceNode.getStringId();sourceNode.attr.datapath='^_temp.grids.'+viewId+'.edit_datapath';sourceNode.registerDynAttr('datapath');var childnodes=sourceNode.getValue().getNodes();var node;for(var i=0;i<childnodes.length;i++){node=childnodes[i];node.attr.nodeId=sourceNode.attr.nodeId+'_'+node.attr.gridcell.replace(/\W/g,'_');if('value'in node.attr){if(node.attr.tag.toLowerCase()=='dbselect'){node.attr.selectedCaption='.'+node.attr.gridcell;}}
else{node.attr['value']='^.'+node.attr.gridcell;}
if(node.attr.exclude==true){node.attr.exclude='==genro.wdgById("'+viewId+'").getColumnValues("'+node.attr['value']+'")';}
var dflt=node.attr['default']||node.attr['default_value']||'';node.getAttributeFromDatasource('value',true,dflt);};},created:function(widget,savedAttrs,sourceNode){var gridnode=sourceNode.getParentNode();var grid=gridnode.widget;grid.editorId='grided_'+sourceNode.getStringId();var editOn=sourceNode.attr.editOn||'onCellDblClick';editOn=stringSplit(editOn,',',2);var modifier=editOn[1];dojo.connect(grid,editOn[0],function(e){if(genro.wdg.filterEvent(e,modifier)){if(grid.editorEnabled){grid.fireEditCell({row:e.rowIndex,col:e.cellIndex});}}});}});dojo.declare("gnr.widgets.IncludedView",gnr.widgets.VirtualStaticGrid,{constructor:function(application){this._domtag='div';this._dojotag='VirtualGrid';},creating:function(attributes,sourceNode){var sortedBy=objectPop(attributes,'sortedBy');var multiSelect=objectPop(attributes,'multiselect');var datamode=objectPop(attributes,'datamode','attr');var savedAttrs=objectExtract(attributes,'selected*');var hiddencolumns=objectPop(attributes,'hiddencolumns');var gridAttributes=objectExtract(attributes,'autoHeight,autoRender,autoWidth,defaultHeight,elasticView,fastScroll,keepRows,model,rowCount,rowsPerPage,singleClickEdit,structure,filterColumn,excludeCol,excludeListCb,editorEnabled');objectPopAll(attributes);objectUpdate(attributes,gridAttributes);var structure,gnreditors,contents;var inAttrs=sourceNode.getInheritedAttributes();var ctxRoot=sourceNode.absDatapath(inAttrs.sqlContextRoot);var abs_storepath=sourceNode.absDatapath(sourceNode.attr.storepath);var relation_path=abs_storepath;if(abs_storepath.indexOf(ctxRoot)==0){relation_path=abs_storepath.replace(ctxRoot+'.','');}
sourceNode.registerDynAttr('storepath');var structpath=sourceNode.attr.structpath;sourceNode.registerDynAttr('structpath');structure=genro.getData(sourceNode.absDatapath(sourceNode.attr.structpath));attributes.gnreditors={};attributes.cellmap={};attributes.structure=this.structFromBag(structure,attributes.cellmap,attributes.gnreditors);var columns=gnr.columnsFromStruct(structure);if(hiddencolumns){columns=columns+','+hiddencolumns;}
attributes.query_columns=columns;attributes.relation_path=relation_path;attributes.sqlContextName=inAttrs['sqlContextName'];attributes.sqlContextTable=inAttrs['sqlContextTable'];if(attributes.excludeListCb){attributes.excludeListCb=funcCreate(attributes.excludeListCb);}
attributes._identifier='_pkey';attributes.sortedBy=sortedBy;attributes.rowCount=0;attributes.datamode=datamode;sourceNode.attr.nodeId=sourceNode.attr.nodeId||'grid_'+sourceNode.getStringId();if(attributes.query_columns){var controllerPath=sourceNode.absDatapath()||'grids.'+sourceNode.attr.nodeId;sourceNode.setRelativeData(controllerPath+'.columns',attributes.query_columns);}},created:function(widget,savedAttrs,sourceNode){var selectionId=sourceNode.attr['selectionId']||sourceNode.attr.nodeId+'_selection';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');}
objectFuncReplace(widget.selection,'clickSelectEvent',function(e){this.clickSelect(e.rowIndex,e.ctrlKey||e.metaKey,e.shiftKey);});if(sourceNode.attr.multiSelect==false){widget.selection.multiSelect=false;}
widget.rpcViewColumns();widget.updateRowCount('*');},useGridContent_OLD:function(gridcontent){var node,structure,attr,tag;var nodes=gridcontent.getNodes();var gnreditors={};for(var i=0;i<nodes.length;i++){node=nodes[i];if(node.label=='struct'){structure=node.getValue();}else{attr=objectUpdate({},node.attr);tag=objectPop(attr,'tag');gnreditors[attr.linkedCol]=genro.wdg.create(tag,null,attr);}};return{'gnreditors':gnreditors,'structure':structure};},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;},mixin_rpcViewColumns:function(){if((this.relation_path)&&(this.relation_path.indexOf('@')==0)){genro.rpc.remoteCall('setViewColumns',{query_columns:this.query_columns,contextName:this.sqlContextName,contextTable:this.sqlContextTable,relation_path:this.relation_path});}}});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);},connectFocus:function(widget,savedAttrs,sourceNode){dojo.connect(widget,'onFocus',widget,function(e){setTimeout(dojo.hitch(this,'selectAllInputText'),1);});dojo.connect(widget,'onBlur',widget,'validate');},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.hasDownArrow=false;}
var resolverAttrs=objectExtract(attributes,'method,dbtable,columns,limit,condition,alternatePkey,auxColumns,hiddenColumns,rowcaption,order_by,selectmethod,weakCondition');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_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);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);}});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);},patch__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.dndSource");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']){var labelClassGetter=funcCreate(attributes['getLabelClass'],'node,opened');attributes.getLabelClass=function(node,opened){if(node.attr){return labelClassGetter(node,opened);}};}
if(attributes['getIconClass']){var iconGetter=funcCreate(attributes['getIconClass'],'node,opened');attributes.getIconClass=function(node,opened){if(node.attr){return iconGetter(node,opened);}};}
var savedAttrs=objectExtract(attributes,'inspect,autoCollapse');return savedAttrs;},created:function(widget,savedAttrs,sourceNode){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.autoCollapse){dojo.connect(widget,'_expandNode',function(node){dojo.forEach(node.getParent().getChildren(),function(n){if(n!=node&&n.isExpanded){n.tree._collapseNode(n);}});});}},patch__onClick:function(e){var nodeWidget=dijit.getEnclosingWidget(e.target);if(!nodeWidget||!nodeWidget.isTreeNode){return;}
if(nodeWidget==nodeWidget.tree.rootNode){return;}
nodeWidget.__eventmodifier=eventToString(e);this._onClick_replaced(e);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.evt=='ins'){this.model.store._triggerIns(kw);}else if(kw.evt=='del'){this._onItemChildrenChange(kw.where.getParentNode(),kw.where.getNodes());}},mixin__updateSelect:function(item,node){var modifiers=objectPop(node,'__eventmodifier');var attributes={};if(modifiers){attributes._modifiers=modifiers;};if(!item){return;}
if(!item._id){item=node.getParent().item;}
if(this.sourceNode.attr.selectedLabel){var path=this.sourceNode.attrDatapath('selectedLabel');genro.setData(path,item.label,attributes);}
if(this.sourceNode.attr.selectedItem){var path=this.sourceNode.attrDatapath('selectedItem');genro.setData(path,item,attributes);}
if(this.sourceNode.attr.selectedPath){var path=this.sourceNode.attrDatapath('selectedPath');genro.setData(path,item.getFullpath(),attributes);}
var selattr=objectExtract(this.sourceNode.attr,'selected_*',true);for(var sel in selattr){var path=this.sourceNode.attrDatapath('selected_'+sel);genro.setData(path,item.attr[sel],attributes);}}});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.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');},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);}}});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.rpc.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.rpc.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.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){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;},serverCall:function(callKwargs,xhrKwargs,httpMethod){},_serverCall:function(callKwargs,xhrKwargs,httpMethod,sourceNode){var httpMethod=httpMethod||'GET';callKwargs=this.serializeParameters(this.dynamicParameters(callKwargs,sourceNode));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';var xhrResult;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;},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);},remoteUpload_old:function(formElement,method,params,cb){alert("remoteUpload");dojo.require('dojo.io.IframeIO');var serverUrl=genro.rpc.rpcUrl(method,params);var cb=cb||function(type,data){alert(data.toString());};dojo.io.bind({url:serverUrl,handler:cb,mimetype:'text/plain',formNode:formElement,sync:false});},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'){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);async_cb(result);});}else{cb=dojo.hitch(this,function(response,ioArgs){result=preprocessor(response,ioArgs);});sync=true;}
var timeout=objectPop(params,'timeout',50000);var xhrKwargs={'handleAs':handleAs,'timeout':timeout,'load':cb,'error':dojo.hitch(this,'errorHandler'),'sync':sync,'preventCache':preventCache};this._serverCall(callKwargs,xhrKwargs,httpMethod);return result;},errorHandler:function(response,ioArgs){genro.dev.handleRpcHttpError(response,ioArgs);},resultHandler:function(response,ioArgs,currentAttr){var envelope=new gnr.GnrBag();envelope.fromXmlDoc(response,genro.clsdict);var envNode=envelope.getNode('result');var resultAsNode=(envelope.getItem('resultType')=='node')||currentAttr;genro.lastRpc=new Date();var changenode,_client_path,fired;var dataChanges=envelope.getItem('dataChanges');if(dataChanges){var changenodes=dataChanges.getNodes();for(var i=0;i<changenodes.length;i++){changenode=changenodes[i];_client_path=objectPop(changenode.attr,'_client_path');fired=objectPop(changenode.attr,'fired');if(changenode.attr._error){setTimeout(dojo.hitch(genro.dev,'handleRpcError',changenode.attr._error,changenode));}else{genro.setData(_client_path,changenode.getValue(),changenode.attr);if(fired){genro._data.setItem(_client_path,null,null,{'doTrigger':false});}}};}
var error=envelope.getItem('error');if(!error){var locStatus=envelope.getItem('_localizerStatus');if(locStatus){genro.setLocStatus(locStatus);}
if(currentAttr){var attr=objectUpdate({},currentAttr);envNode.attr=objectUpdate(attr,envNode.attr);}}else{setTimeout(dojo.hitch(genro.dev,'handleRpcError',error,envNode));return null;}
if(resultAsNode){return envNode;}else{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_OLD:function(){var url;var curloc=document.location.pathname;if(stringEndsWith(curloc,'/')){curloc=curloc.slice(0,curloc.length-1);}
if(stringEndsWith(curloc,'.py')||this.application.pageMode!='legacy'){url=curloc;}else{url=curloc+'/index';}
return url;},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['xxcnt']=genro.getCounter();}
return objectUpdate(currParams,this.serializeParameters(this.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['xxcnt']=this.counter;objectUpdate(currParams,kwargs);var parameters=[];for(var key in currParams){parameters.push(key+'='+escape(currParams[key]));}
return this.application.absoluteUrl('?'+parameters.join('&'));},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=genro.evaluate(dynval.slice(2));}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;},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;},managePolling:function(freq){if(freq==null){freq=genro.getData('gnr.polling');}
if(genro.polling){clearInterval(genro.polling);genro.polling=null;}
if(freq>0){genro.lastRpc=new Date();genro.polling=setInterval(function(){var now=new Date();if((!genro.pollingRunning)&&((now-genro.lastRpc)>(freq*1000))){genro.rpc.ping();}},1000);}},ping:function(){genro.pollingRunning=true;genro.rpc.remoteCall('ping',null,null,null,null,function(){genro.pollingRunning=false;});},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};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,'from_fld':params._from_fld,'target_fld':params._target_fld,'relation_value':params._relation_value,'sqlContextName':params._sqlContextName};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;}});



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 tblclass='multiColumnSelect'+' '+lfa['resultClass'];var cols=lfa.columns.split(',');var hdr=lfa.headers.split(',');var thead='<thead><tr>';for(var k=0;k<cols.length;k++){thead=thead+"<th>"+hdr[k]+"</th>";}
var item,r,value;var tbl=["<table class='"+tblclass+"'>"+thead+"</tr></thead><tbody>"];for(var i=0;i<results.length;i++){r="";item=results[i].attr;for(var k=0;k<cols.length;k++){value=item[cols[k]]||'';r=r+"<td>"+genro.format(value,{date:'short'});+"</td>";}
tbl.push("<tr id='"+results[i].label+"'>"+r+"</tr>");}
tbl.push("</tbody></table>");this.domNode.innerHTML=tbl.join('');var rows=this.domNode.firstChild.lastChild.childNodes;for(var i=0;i<rows.length;i++){rows[i].item=results[i];}
this.tblrows=rows;this.domNode.onmouseover=dojo.hitch(this,'onmouseover');},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();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.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(){if(!this.getHighlightedOption()){var n=this.tblrows[0];this._focusOptionNode(n);}else if(this._highlighted_option.nextSibling&&this._highlighted_option.nextSibling.style.display!="none"){this._focusOptionNode(this._highlighted_option.nextSibling);}},highlightFirstOption:function(){this._focusOptionNode(this.tblrows[0]);},highlightLastOption:function(){this._focusOptionNode(this.tblrows[this.tblrows.length-1]);},_highlightPrevOption:function(){if(!this.getHighlightedOption()){this._focusOptionNode(this.tblrows[this.tblrows.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.isTreeNode=false;}else{this.labelNode.appendChild(dojo.doc.createTextNode(label));};};};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.GnrDevHandler",null,{constructor:function(application){this.application=application;},editSourceNode:function(treenode){var sourceNode=this.application.getDataNode(treenode);var dest=genro.inspector_struct_pane.sourceNode;var form=dest.getValue();var r,c;var nodeAttr=sourceNode.getAttr();dest.setValue(null,false);form.clear();var tbody=form._('table')._('tbody');var tagParameters=this.application.wdg.tagParameters[nodeAttr.tag.toLowerCase()];var currBag=new gnr.GnrBag();if(tagParameters){for(var par in tagParameters){var r=tbody._('tr');r._('td',{'content':par});var v=tagParameters[par].split(':');var c=r._('td');if(v[0]=='input'){c._('input',{datasource:':'+par});}
currBag.setItem(par,null);}}
for(var i=0;i<this.application.dom.styleAttrNames.length;i++){var stl=this.application.dom.styleAttrNames[i];var r=tbody._('tr');r._('td',{'content':stl});var c=r._('td');c._('input',{datasource:':'+stl});currBag.setItem(stl,null);}
for(attr in nodeAttr){if(attr!='tag'){if(currBag.index(attr)<0){var r=tbody._('tr');r._('td',{'content':attr});var c=r._('td');c._('input',{datasource:':'+attr});}
currBag.setItem(attr,nodeAttr[attr]);}}
currBag['editedNode']=sourceNode;currBag.subscribe('sourceTriggers',{'any':{obj:this,func:'editSourceNode_trigger'}});dest.setValue(form);genro.setData('currentnode',currBag);},editSourceNode_trigger:function(kw){var currBagNode=kw.node;var sourceNode=currBagNode.getParentBag().editedNode;var newValue=currBagNode.getValue()||null;var nodeAttrs=objectUpdate({},sourceNode.getAttr());var attrname=currBagNode.label;if(kw.evt=='upd_del'||newValue==null){delete(nodeAttrs[attrname]);}else{nodeAttrs[attrname]=newValue;}
sourceNode.setAttr(nodeAttrs);},srcInspector:function(node){var showInspector=function(domnode){var sourceNode=domnode.sourceNode;if(!sourceNode){var wdg=dijit.getEnclosingWidget(domnode);if(wdg){sourceNode=wdg.sourceNode;}}
if(sourceNode){var showDict=objectUpdate({},sourceNode.attr);showDict.absDatapath=sourceNode.absDatapath();return genro.dev.dictToHtml(showDict,'bagAttributesTable');}else{return'No sourceNode';}};genro.wdg.create('tooltip',null,{label:showInspector,modifiers:'alt'}).connectOneNode(node);},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){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();}},openInspector:function(){var root=genro.src.newRoot();this.application.setData('_dev.dbstruct',null,{remote:"app.dbStructure"});var fpane=root._('floatingPane','inspector',{title:'Debug',top:'100px',left:'100px',height:'300px',width:'400px',resizable:true,maxable:true,dockable:false,closable:true,gnrId:'inspector_main'});var accordion=fpane._('accordionContainer',{height:'100%'});accordion._('accordionPane',{title:'Data'})._('tree',{gnrId:'inspector_data',datasource:'*D'});var structInsp=fpane._('accordionPane',{title:'Structure'});var splitter=structInsp._('SplitContainer',{height:'100%'});splitter._('ContentPane',{sizeShare:30})._('tree',{gnrId:'inspector_struct',datasource:'*S'});splitter._('ContentPane',{sizeShare:70,gnrId:'inspector_struct_pane',background_color:'silver',datasource:'currentnode'})._('div');accordion._('accordionPane',{title:'Widgets'})._('tree',{gnrId:'inspector_widgets',datasource:'_dev.widgets'});accordion._('accordionPane',{title:'Db Structure'})._('tree',{gnrId:'inspector_db',datasource:'_dev.dbstruct'});dojo.connect(genro.inspector_struct,'onSelect',function(treenode){genro.dev.editSourceNode(treenode);});genro.src.setInRootContainer('inspector',root.getNode('inspector'));},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(){var open=genro._data.getItem('_clientCtx.mainBC.right?show');genro._data.setItem('_clientCtx.mainBC.right?show',!open);},showBottomHelper:function(){var open=genro._data.getItem('_clientCtx.mainBC.bottom?show');genro._data.setItem('_clientCtx.mainBC.bottom?show',!open);},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.GnrViewEditor",null,{constructor:function(widget){this.widget=widget;}});



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=objectUpdate({'width':'20em'},kw);var resultPath=resultPath||'dummy';var node=genro.src.getNode('_dlg_alert').clearValue().freeze();var dlg=node._('dialog',{nodeId:'_dlg_alert',title:title,toggle:"fade",toggleDuration:250,centerOn:'_pageRoot'})._('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(msg){genro.dlg.alert(msg,'Warning');},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;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();},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();},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.GnrFrmHandler",null,{constructor:function(form_id,formDatapath,controllerNodeId){this.form_id=form_id;this.changed=false;this.status=null;this.current_field=null;this.controllerPath=controllerNodeId?genro.nodeById(controllerNodeId).absDatapath()+'.form':'gnr.forms.'+this.form_id;this.invalidFieldsPath=this.controllerPath+'.invalidFields';this.formDatapath=formDatapath;},reset:function(){this.resetChanges();this.resetInvalids();},resetChanges:function(){var sourceNode=genro.nodeById(this.form_id);sourceNode.getRelativeData('',true,new gnr.GnrBag()).subscribe('dataLogger',{'upd':dojo.hitch(this,"triggerUPD"),'ins':dojo.hitch(this,"triggerINS"),'del':dojo.hitch(this,"triggerDEL")});this.changesLogger=this.controllerPath+'.changesLogger';genro.setData(this.changesLogger,new gnr.GnrBag());this._setChangeStatus(false);},resetInvalids:function(){genro.setData(this.invalidFieldsPath,new gnr.GnrBag());this._setInvalidStatus(false);},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(sync){genro.setData(this.controllerPath+'.loading',true);this.status='loading';if(!sync){var formDomNode=genro.domById(this.form_id);genro.dom.addClass(formDomNode,'loadingForm');var formHider=document.createElement("div");formHider.id=this.form_id+"_hider";dojo.addClass(formHider,'formHider');formDomNode.appendChild(formHider);}
this.resetInvalids();genro.setData('_temp.grids',null);var loaderNode=genro.nodeById(this.form_id+'_loader');if(loaderNode){loaderNode.fireNode();if(sync){this.loaded();}}else{genro._data.setItem(this.formDatapath,new gnr.GnrBag());this.loaded();}},loaded:function(){genro.dom.removeClass(this.form_id,'loadingForm');var hider=dojo.byId(this.form_id+"_hider");if(hider){genro.domById(this.form_id).removeChild(hider);}
this.resetChanges();genro.setData(this.controllerPath+'.is_newrecord',genro.getDataNode(this.formDatapath).attr._newrecord);genro.setData(this.controllerPath+'.loading',false);genro.fireEvent(this.controllerPath+'.loaded');this.status=null;},save:function(always,onSavedCb){if(!this.status){var always=always||genro._(this.controllerPath+'.is_newrecord');if(this.changed||always){var invalidfields=this.getInvalidFields();var invalid=(invalidfields.len()>0);if(invalid){genro.fireEvent(this.controllerPath+'.save_failed','invalid');return'invalid:'+invalid;}
genro.fireEvent(this.controllerPath+'.saving');this.status='saving';this.onSavedCb=onSavedCb;genro.nodeById(this.form_id+'_saver').fireNode();}else{genro.fireEvent(this.controllerPath+'.save_failed','nochange');}}},saved:function(){this.status=null;var onSavedCb=objectPop(this,'onSavedCb');genro.fireEvent(this.controllerPath+'.saved');if(onSavedCb){onSavedCb();}},getFormData:function(){return genro._(this.formDatapath);},hasChanges:function(){return;},getFormChanges:function(){return this._getRecordCluster(this.getFormData(),true);},getFormCluster:function(){return this._getRecordCluster(this.getFormData(),false);},_getRecordCluster:function(record,changesOnly,result,removed,parentpath){if(record){var parentpath=parentpath||genro.nodeById(this.form_id).absDatapath('');var data=new gnr.GnrBag();data.__isRealChange=false;var node,sendBag,value,currpath,sendback;var isNewRecord=record.attributes()._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)=='$'){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){data.setItem(node.label,value,objectUpdate({'_gnrbag':true},node.attr));}}
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;}
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.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._setChangeStatus((changes.len()>0));}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._setChangeStatus((changes.len()>0));},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);}
this._setChangeStatus((changes.len()>0));},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);}}
var invalid=(invalidfields.len()>0);this._setInvalidStatus(invalid);},_setInvalidStatus:function(invalid){genro.setData(this.controllerPath+'.valid',!invalid);},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'];};},getInvalidFields:function(){return genro.getData(this.invalidFieldsPath)||new gnr.GnrBag();},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();},getChangesLogger:function(){return genro.getData(this.changesLogger);},_setChangeStatus:function(changed){genro.setData(this.controllerPath+'.changed',changed);this.changed=changed;},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;}}}});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);}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 r=new RegExp(param);if(!r.test(value)){return false;}}},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.GnrLstHandler",null,{constructor:function(application){this.application=application;},getRecord:function(table,id,datapath){genro.rpc._serverCall(callKwargs,xhrKwargs,httpMethod);},saveRecord:function(table,id,datapath){},changeRecord:function(table,id,datapath){},deleteRecord:function(table,id,datapath){}});



dojo.declare("gnr.GnrDomHandler",null,{constructor:function(application){this.application=application;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'];},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){genro.dom.iframeContentWindow(iframe).print();},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;},insertCss:function(css){if(stringContains(css,'{')){dojo.html.insertCssText(css);}else{dojo.html.insertCssFile(css);}},addClass:function(where,cls){if(typeof(cls)=='string'){if(typeof(where)=='string'){var where=genro.domById(where);}
if(where instanceof gnr.GnrDomSourceNode){where=where.getDomNode();}
var classes=cls.split(' ');for(var i=0;i<classes.length;i++){dojo.addClass(where,classes[i]);}}},removeClass:function(where,cls){if(typeof(cls)=='string'){if(typeof(where)=='string'){var where=genro.domById(where);}
if(!where){return;}
if(where instanceof gnr.GnrDomSourceNode){where=where.getDomNode();}
var classes=cls.split(' ');for(var i=0;i<classes.length;i++){dojo.removeClass(where,classes[i]);}}},setClass:function(where,cls,set){if(set){this.addClass(where,cls);}else{this.removeClass(where,cls);}},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);}},style:function(where,kw){if(typeof(where)=='string'){var where=genro.domById(where);}
dojo.style(where,kw);},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");}else{console.log('line 179 genro_dom');}},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;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;},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;}}},windowTitle:function(title){document.title=title;},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);}});



dojo.declare("gnr.GnrDomSourceNode",gnr.GnrBagNode,{application:function(){return this.getParentBag().getRoot().application;},freeze:function(){this._savedparentbag=this._parentbag;this._parentbag=null;if(this._value instanceof gnr.GnrDomSource){this._value.clearBackRef();}
return this;},unfreeze:function(){this._parentbag=this._savedparentbag;if(this._value instanceof gnr.GnrDomSource){this._value.setBackRef(this,this._parentbag);this.rebuild();}},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(node.childNodes[0]);}}},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&&(kw.evt!='del')){if(this.attr._delay>0){setTimeout(dojo.hitch(this,'setDataNodeValue',kw.node,kw,trigger_reason),this.attr._delay);}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){var attributes=objectUpdate({},this.attr);var _userChanges=objectPop(attributes,'_userChanges');if((kw&&kw.reason=='autocreate')||(_userChanges&&trigger_reason!='node')){return;}
var tag=objectPop(attributes,'tag');var path=objectPop(attributes,'path');objectPop(attributes,'_onStart');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');}
var argValues=[node,{'kw':kw,'trigger_reason':trigger_reason}];var argNames=['_node','_triggerpars'];var kwargs={};var val;for(var attrname in attributes){argNames.push(attrname);val=this.getAttributeFromDatasource(attrname);argValues.push(val);kwargs[attrname]=val;}
var if_result=true;if(_if){if_result=funcCreate('return ('+_if+')',argNames.join(',')).apply(this,argValues);}
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 method=expr;var httpMethod=objectPop(kwargs,'_POST')?'POST':'GET';var _onResult=objectPop(kwargs,'_onResult');objectPop(kwargs,'nodeId');var _onCalling=objectPop(kwargs,'_onCalling');var origKwargs=objectUpdate({},kwargs);objectExtract(kwargs,'_*');if(_onResult){_onResult=funcCreate(_onResult,'result,kwargs',this);}
var cb=function(result){dataNode.setValue(result);if(_onResult){_onResult(result,origKwargs);}};if(_onCalling){doCall=funcCreate(_onCalling,(['kwargs'].concat(argNames)).join(',')).apply(this,([kwargs].concat(argValues)));}
if(doCall!=false){genro.rpc.remoteCall(method,kwargs,null,httpMethod,null,cb);}}
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(form_id,formDatapath,controllerNodeId){this.formHandler=new gnr.GnrFrmHandler(form_id,formDatapath,controllerNodeId);},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;},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.setItem(path,value,attributes,{'doTrigger':reason});genro._data.setItem(path,null,attributes,{'doTrigger':false});genro._firingNode=null;}else{if(genro._data.getItem(path)!=value){genro._data.setItem(path,value,attributes,{'doTrigger':reason});}}}},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));}}
value=funcCreate('return '+value.slice(2),argNames.join(',')).apply(this,argValues);}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){if(path&&(path.indexOf('^')==0)||(path.indexOf('=')==0)){return true;}},symbolicDatapath:function(path){var pathlist=path.split('.');var nodeId=pathlist[0].slice(1);currNode=nodeId?genro.nodeById(nodeId):this;if(!currNode){alert('not existing nodeId:'+nodeId);}
var relpath=pathlist.slice(1).join('.');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(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(){},_bld_script:function(){dojo.eval(this.getValue());},_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){for(var attr in pardict){pardict[attr]=this.currentFromDatasource(pardict[attr]);}
return pardict;},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._isBuilding=true;var attributes=this.registerNodeDynAttr(true);var tag=objectPop(attributes,'tag');if(!tag){this._buildChildren(destination);}else{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[aux].call(node);}else{node.build(destination,-1);}}}}},_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.focus()";}
var subscriptions=objectExtract(attributes,'subscribe_*');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);this._registerNodeId(bld_attrs.nodeId);if(bld_attrs.gnrId){this.setGnrId(bld_attrs.gnrId,newobj);}
this._buildChildren(newobj);if('startup'in newobj){newobj.startup();}
if((typeof(this.attr.value)=='string')&&(this.isPointerPath(this.attr.value))){newobj.gnr.connectChangeEvent(newobj);}
for(var eventname in connections){this.connect(newobj,eventname,connections[eventname]);}
for(var subscription in subscriptions){var handler=funcCreate(subscriptions[subscription]);dojo.subscribe(subscription,newobj,handler);}
if(bld_attrs.onCreated){funcCreate(bld_attrs.onCreated,'widget,attributes').call(this,newobj,attributes);}
if(bld_attrs.tooltip){genro.wdg.create('tooltip',null,{label:bld_attrs.tooltip}).connectOneNode(newobj.domNode||newobj);}
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;},getFormHandler:function(){if(this.formHandler!=null){return this.formHandler;}else{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=='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(this.widget){if(attr.indexOf('remote_')==0){this.updateRemoteContent(this);}
else if(attr.indexOf('__')==0){return;}
else if((attr_lower=='disabled')||(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;}
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=='disabled'){domnode.disabled=value?true:false;return;}
else 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)){var attr=attr.replace('_','-');dojo.style(domnode,attr,value);}
else if(setter in domnode.gnr){dojo.hitch(domnode.gnr,setter)(domnode,value,kw);}
else{var attrdict={};this.setAttr(attrdict,this,true);}}},_stripData:function(){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);}}}
node._stripData();}}}},_moveData:function(){this._registerNodeId();var attributes=this.registerNodeDynAttr(false);var tag=objectPop(attributes,'tag');var path=this.absDatapath(objectPop(attributes,'path'));if(tag=='data'&&attributes.remote){attributes['method']=objectPop(attributes,'remote');tag='dataRemote';}
if(tag=='data'){var value=this.getValue();this._value=null;if(value instanceof gnr.GnrBag){value.clearBackRef();}
var context=objectPop(attributes,'context');genro.setData(path,value,attributes);if(context){if(!(value instanceof gnr.GnrBag)){value=new gnr.GnrBag();genro.setData(path,value,attributes);}
if(!genro.contextIndex[context]){genro.contextIndex[context]=this;value.subscribe('context',{'any':dojo.hitch(this,"contextChange")});}else{alert("Context name conflict: "+context);}}}else if(tag=='dataRemote'){this._dataprovider=tag;this.setDataNodeValue();}else{var initialize=objectPop(attributes,'_init');this._dataprovider=tag;if(initialize){this.setDataNodeValue();}else{genro.getDataNode(path,true);}
var timing=objectPop(attributes,'_timing');if(timing){var timerFunc=dojo.hitch(this,'setDataNodeValue');setInterval(timerFunc,timing*1000);}
var onStart=objectPop(attributes,'_onStart');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();},updateRemoteContent:function(forceUpdate){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){kwargs[attrname.slice(7)]=this.getAttributeFromDatasource(attrname);}}
var method=this.attr.remote;var _sourceNode=this;kwargs.sync=true;genro.rpc.remoteCall(method,kwargs,null,null,null,function(result){_sourceNode.setValue(result);});},getValidationError:function(){if(this._validations){return this._validations.error;}},getValidationWarnings:function(){if(this._validations){return this._validations.warnings;}},isValidationRequired:function(){if((this._validations)&&(this._validations.required)){return true;}},hasValidationWarnings:function(){if((this._validations)&&(objectNotEmpty(this._validations.warnings))){return true;}},hasValidationError:function(){if((this._validations)&&(this._validations.error)){return true;}},resetValidationError:function(){if(this._validations){this._validations.error=null;this._validations.warnings=[];this._validations.required=null;this.updateValidationClasses();}},setValidationError:function(validation_result){this._validations.error=validation_result.error;this._validations.warnings=validation_result.warnings;this._validations.required=validation_result.required;this.updateValidationClasses();},setValidations:function(){this._validations={};},hasValidations:function(){if(this._validations){return true;}},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');}},contextChange:function(kw){if(kw.reason!='autocreate'){genro.rpc.remoteCall('updateSessionContext',{'context':this.attr.context,'value':kw.node._value,'attr':kw.node.attr,'evt':kw.evt,'path':kw.pathlist.join('.')},null,'GET');}},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){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._(tag,name,attributes);return child;}});dojo.declare("gnr.GnrStructData",gnr.GnrBag,{});dojo.declare("gnr.GnrDomSource",gnr.GnrStructData,{_validationPrefix:'structvalidate_',_nodeFactory:gnr.GnrDomSourceNode,_:function(tag,name,attributes){var tag_UpperLower=null;var name,content;tag=tag.toLowerCase();if(tag){if(name instanceof Object){var attributes=name;var name='';}
var attributes=attributes||{};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;this.setItem(name,content,attributes);return content;}},component:function(){if(this.component!=null){return this._component;}else if(this.parent!=null){return this.parent.component();}}});



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']};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'];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','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','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':''};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){handler=this.widgets[('base'+this.namespace[lowertag][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);var domtag=handler._domtag||tag;if(attributes.gridcell){attributes._class=attributes._class||'widgetInCell';}
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 disabled=objectPop(attributes,'disabled')?true:false;var kw={'postCreation':handler._creating(attributes,sourceNode),'readonly':objectPop(attributes,'readonly'),'disabled':disabled,'_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(disabled){newobj.setAttribute('disabled',true);}
if(tip){newobj.domNode.setAttribute('title',tip);}
else{newobj.domNode.setAttribute('title',"");}
this.linkSourceNode(newobj,sourceNode,kw);newobj.gnr=handler;if(destination&&destination.addChild){if(ind<0){destination.addChild(newobj);}
else{destination.addChild(newobj,ind);}}
if(attributes.gridcell){dojo.connect(newobj.focusNode,'keydown',dojo.hitch(newobj,function(e){if((e.keyCode==genro.PATCHED_KEYS.SHIFT)||(e.keyCode==genro.PATCHED_KEYS.CTRL)||(e.keyCode==genro.PATCHED_KEYS.ALT)){return;}
if(e.keyCode==genro.PATCHED_KEYS.TAB){if(e.shiftKey){this.cellNext='LEFT';}else{this.cellNext='RIGHT';}}
if((e.shiftKey)&&((e.keyCode==genro.PATCHED_KEYS.UP_ARROW)||(e.keyCode==genro.PATCHED_KEYS.DOWN_ARROW)||(e.keyCode==genro.PATCHED_KEYS.LEFT_ARROW)||(e.keyCode==genro.PATCHED_KEYS.RIGHT_ARROW))){if(e.keyCode==genro.PATCHED_KEYS.UP_ARROW){this.cellNext='UP';}else if(e.keyCode==genro.PATCHED_KEYS.DOWN_ARROW){this.cellNext='DOWN';}else if(e.keyCode==genro.PATCHED_KEYS.LEFT_ARROW){this.cellNext='LEFT';}else if(e.keyCode==genro.PATCHED_KEYS.RIGHT_ARROW){this.cellNext='RIGHT';}
this.focusNode.blur();this._onBlur();}}));var grid=sourceNode.getParentNode().getParentNode().widget;dojo.connect(newobj,'onBlur',dojo.hitch(newobj,function(e){var cellNext=this.cellNext;this.cellNext=null;deltaDict={'UP':{'r':-1,'c':0},'DOWN':{'r':1,'c':0},'LEFT':{'r':0,'c':-1},'RIGHT':{'r':0,'c':1}};setTimeout(dojo.hitch(grid,'endEditCell',this,deltaDict[cellNext]),1);}));}}
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(kw.disabled){attributes['disabled']='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='patch_'+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(prop.indexOf('patch_')==0){ispatch=true;if(prop.indexOf(versionpatch)==0){funcname=prop.replace(versionpatch,'');}
else{funcname=prop.replace('patch_','');}}else if(prop.indexOf('nodemixin_')==0){sourceNode[prop.replace('nodemixin_','')]=handler[prop];}else if(prop.indexOf('validatemixin_')==0){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){var result=false;var target=e.target;if(validclass&&target.className&&target.className.indexOf(validclass)<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.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._main.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){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){var node=kw.node;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();var widget=kw.node.widget;if(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();},_trigger_upd:function(kw){var destination=kw.node.getParentBuiltObj();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();}
destination.removeChild(widget);widget.destroyRecursive();}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(selectedIndex){destination.setSelected(selectedIndex);}},buildNode:function(sourceNode,where,ind){this.afterBuildCalls=[];sourceNode._stripData();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){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,true);}
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;}},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);},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]);}}}}});



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 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){var lastIndex=s.lastIndexOf(v);return(lastIndex>=0)?(lastIndex+v.length==s.length):false;}
function stringStartsWith(s,v){return(s.indexOf(v)==0);}
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){var regexpr=/\$([a-z0-9.@?_]+)/g;var result;var is_empty=true;if(!data){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){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{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 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(typeof dflt=='undefined'){var dflt=null;}
if((obj instanceof Object)&&(key in obj)){result=obj[key];delete obj[key];}else{result=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){var result={};var key,m;if(/[\*]$/.test(keys)){key='^'+keys.replace('*','(.*)');for(var prop in obj){m=prop.match(key);if(m){result[m[1]]=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=0;i<keys.length;i++){key=stringStrip(keys[i]);if(key in obj){result[key]=obj[key];if(!(dontpop)){delete obj[key];}}}}
return result;}
function objectExtract_(obj,keys,dontpop){keys=keys.split(',');var result={};var key;for(var i=0;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{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){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 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_FIRE(fnc);if(!stringStartsWith(fnc,'function')){fnc='function('+pars+'){'+fnc+'}';}
fnc=genro.evaluate(fnc);if(scope){fnc=dojo.hitch(scope,fnc);}}
return fnc;}}
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(){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){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){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){for(var key in item.getAttr()){attributes.push(key);}}
return attributes;},hasAttribute:function(item,attribute){if(this.isItem(item)){if(attribute=='#v'){if(item.getResolver()){return 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){return false;},isItem:function(something){return(something instanceof gnr.GnrBagNode);},isItemLoaded:function(something){if(this.isItem(something)){return something.isLoaded();}else{return true;}},loadItem:function(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){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){},getLabel:function(item){if(this.isItem(item)){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){},newItem:function(keywordArgs,parentInfo){var newItem;return newItem;},deleteItem:function(item){return false;},setValue:function(item,attribute,value){return false;},setValues:function(item,attribute,values){return false;},unsetAttribute:function(item,attribute){return false;},save:function(keywordArgs){},revert:function(){return false;},isDirty:function(item){return false;},getIdentity:function(item){if(!(item instanceof gnr.GnrBagNode)){return item.id;}
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){return null;},fetchItemByIdentity:function(request){if(request.identity){var id=request.identity;var item=null;var bagnode;var nodes=this.rootData().getNodes();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){if(!request.identity){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){if(!request.identity){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;result={attr:{}};result.attr[this.searchAttr]=value;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){this.lastFetchAttrs=r.attr;var result;if(r instanceof gnr.GnrBagNode&&r.getValue()){result=r.getValue().getNodes();}
else{result=[];}
findCallback(result,request);});var result=this.rootDataNode().getValue('',kwargs);return result.addCallback(cb);}}}});




