
Runner.namespace('Runner.util');(function(){var createDelayed=function(hn,delay,scope){return function(){var args=arguments;setTimeout(function(){hn.apply(scope,args);},delay);};};var createSingle=function(hn,e,fn,scope){return function(){e.removeListener(fn,scope);return hn.apply(scope,arguments);};};var createBuffered=function(hn,buffer,scope){var task=new Runner.util.DelayedTask();return function(){task.delay(buffer,hn,scope,Array.prototype.slice.call(arguments));};};Runner.util.Event=function(obj,name){this.name=name;this.obj=obj;this.listeners=[];};Runner.util.Event.prototype={createListener:function(fn,scope,options){var hn=fn;scope=scope||this.obj;options=options||{};if(options.delay){hn=createDelayed(hn,options.delay,scope);}
if(options.single){hn=createSingle(hn,this,fn,scope);}
if(options.buffer){hn=createBuffered(hn,options.buffer,scope);}
return{fn:fn,fireFn:hn,scope:scope,options:options};},fire:function(){var i,ls;if(this.listeners.length>0){this.firing=true;for(i=0;i<this.listeners.length;i++){ls=this.listeners[i];if(ls.fireFn.apply(ls.scope||this.obj||window,arguments)===false){this.firing=false;return false;}}
this.firing=false;}
return true;},on:function(fn,scope,options){scope=scope||this.obj;if(!this.isListening(fn,scope)){var ls=this.createListener(fn,scope,options);this.listeners.push(ls);}},isListening:function(fn,scope){return this.getListenerIndex(fn,scope)!=-1;},getListenerIndex:function(fn,scope){var length=this.listeners.length,i,ls;scope=scope||this.obj;for(i=0;i<length;i++){ls=this.listeners[i];if(ls.fn==fn&&ls.scope==scope){return i;}}
return-1;},removeListener:function(fn,scope){var index=this.getListenerIndex(fn,scope);if(index===-1){return;}
if(this.firing){this.listeners=this.listeners.slice(0);}
this.listeners.splice(index,1);}};})();Runner.util.Observable=Runner.extend(Runner.emptyFn,{events:null,filterOptRe:/^(?:scope|delay|buffer|single)$/,addEvents:function(){var eventsNames=Array.prototype.slice.call(arguments),evName,i;this.events=this.events||{};for(i=0;i<eventsNames.length;i++){evName=eventsNames[i].toLowerCase();this.events[evName]=this.events[evName]||true;}},fireEvent:function(){var evName=arguments[0],ce;if(this.isEventExist(evName)){ce=this.events[evName.toLowerCase()];return ce.fire.apply(ce,Array.prototype.slice.call(arguments,1));}
return true;},isEventExist:function(evName){if(this.eventsSuspended===true){return false;}
var ce=this.events[evName.toLowerCase()];return ce instanceof Runner.util.Event;},on:function(evName,fn,scope,options){var event,ce;if(typeof evName==="object"){options=evName;for(event in options){if(this.filterOptRe.test(event)){continue;}
if(typeof options[event]==="function"){this.on(event,options[event],options.scope,options);}else{this.on(event,options[event].fn,options[event].scope,options[event]);}}
return;}
options=options||{};evName=evName.toLowerCase();ce=this.events[evName];if(!(ce instanceof Runner.util.Event)){ce=new Runner.util.Event(this,evName);this.events[evName]=ce;}
ce.on(fn,scope,options);},un:function(evName,fn,scope){var ce=this.events[evName.toLowerCase()];if(ce instanceof Runner.util.Event){ce.removeListener(fn,scope);}},purgeListeners:function(){for(var event in this.events){if(this.events[event]instanceof Runner.util.Event){this.events[event].listeners=[];}}},suspendEvents:function(){this.eventsSuspended=true;},resumeEvents:function(){this.eventsSuspended=false;}});Runner.namespace('Runner.util');Runner.util.getHiddenDimensions=function($elem){var position,cloned=false;if($elem.is(":hidden")){$elem=$elem.clone().css({display:"inline-block",position:"absolute",visibility:"hidden"}).appendTo($elem.closest(":visible"));cloned=true;}
position={outerWidth:$elem.outerWidth(),outerHeight:$elem.outerHeight(),width:$elem.width(),height:$elem.height()};if(cloned){$elem.remove();}
return position;};Runner.util.getChildDisplayedElems=function(elem){var foundElems=[];$.each(elem.children(),function(i,item){if($(item).css("display")!="none"){foundElems.push(item);}});return foundElems;};Runner.util.dropPositionSet=function($dropButton){if(!Runner.isBootstrap()){return;}
$dropButton.parent().on("shown.bs.dropdown",function(){var $el=$(this),$ul=$el.children(".dropdown-menu"),$button=$el.children(".dropdown-toggle"),ulOffset=$ul.offset(),spaceUp=ulOffset.top-$button.height()-$ul.height()-$(window).scrollTop(),spaceDown=$(window).scrollTop()+$(window).height()-ulOffset.top-$ul.height();if(spaceDown<0&&(spaceUp>=0||spaceUp>spaceDown)){$el.addClass("dropup");}}).on("hidden.bs.dropdown",function(){$(this).removeClass("dropup");});};Runner.util.DelayedTask=function(fn,scope,args){var id=null,delay,time;var call=function(){var now=new Date().getTime();if(now-time>=delay){clearInterval(id);id=null;fn.apply(scope,args||[]);}};this.started=function(){return id!=null;}
this.delay=function(newDelay,newFn,newScope,newArgs){if(id){this.cancel();}
delay=newDelay;time=new Date().getTime();fn=newFn||fn;scope=newScope||scope;args=newArgs||args;if(!id){id=setInterval(call,delay);}};this.cancel=function(){if(id){clearInterval(id);id=null;}};};Runner.util.getDeviceClass=function(){var w=window.screen.width,h=window.screen.height;if(w>=1281){return Runner.pages.constants.DESKTOP;}
if(w==768&&h==1024){return Runner.pages.constants.TABLET_10_IN;}
if(w>=1025&&w<=1280&&h<=1023||h>=1025&&h<=1280&&w<=1023){return Runner.pages.constants.TABLET_10_IN;}
if(h>=421&&h<=800&&w>=421&&w<=1024||w>=421&&w<=800&&h>=421&&h<=1024){return Runner.pages.constants.TABLET_7_IN;}
if(w>h&&(h<=420||w<=420)){return Runner.pages.constants.SMARTPHONE_LANDSCAPE;}
if(w<h&&(h<=420||w<=420)){return Runner.pages.constants.SMARTPHONE_PORTRAIT;}
return Runner.pages.constants.DESKTOP;}
Runner.util.getDeviceMacroClass=function(){var c=Runner.util.getDeviceClass();if(c==Runner.pages.constants.SMARTPHONE_LANDSCAPE||Runner.pages.constants.SMARTPHONE_PORTRAIT){return 2;}
if(c==Runner.pages.constants.TABLET_7_IN||c==Runner.pages.constants.TABLET_10_IN){return 1;}
return 0;}
Runner.util.ScriptLoader=Runner.extend(Runner.util.Observable,{cssFiles:[],jsFiles:[],session:0,loadedSes:[],constructor:function(cfg){Runner.util.ScriptLoader.superclass.constructor.call(this,cfg);this.addEvents();this.onFilesLoaded(function(){if(Runner.pages){Runner.pages.PageManager.initPages();}},this);},addJS:function(files){var isAdded,i,j;for(i=0;i<files.length;i++){isAdded=false;for(j=0;j<this.jsFiles.length;j++){if(this.jsFiles[j].name==files[i]){isAdded=true;break;}}
if(!isAdded){this.jsFiles.push({name:files[i],isLoaded:false,requirements:Array.prototype.slice.call(arguments,1),session:parseInt(this.session)});}}},cssProxy:(function(){return function(url){return url;}})(),isCSSfileLoaded:function(fileName){for(var i=0;i<this.cssFiles.length;i++){if(this.cssFiles[i].name==fileName&&this.cssFiles[i].isLoaded){return true;}}
return false;},loadCSS:function(files){var _self=this;if(!files){return;}
files=typeof files==="string"?[files]:files;jQuery.each(files,function(i,file){if(!file){return;}
file=_self.cssProxy(file);if(_self.isCSSfileLoaded(file)){return;}
_self.cssFiles.push({name:file,isLoaded:true})
var existInHead=false,head,css,filePath;$('head link[rel="stylesheet"]').each(function(index,element){if($(element).attr('href')==file){existInHead=true;return false;}});if(!existInHead){head=$(document).find('head')[0];filePath=files[i];css=document.createElement('link');css.setAttribute('rel','stylesheet');css.setAttribute('type','text/css');css.setAttribute('href',filePath);head.appendChild(css);}});},load:function(){if(this.jsFiles.length==0){this.fireEvent('filesLoaded'+this.session);}
this.session=this.session+1;for(var i=0;i<this.jsFiles.length;i++){this.loadJS(i);}},loadJS:function(idx){if(!this.jsFiles[idx]){return false;}
if(this.jsFiles[idx].isLoaded){this.jsFiles[idx].session=this.session-1;this.postLoad(idx);return true;}
if(!this.checkReq(this.jsFiles[idx])){return false;}
if(this.jsFiles[idx].isStarted){return false;}
this.jsFiles[idx].isStarted=true;var self=this,js=document.createElement('script'),runnerWebRootPath=decodeURIComponent(window.runnerWebRootPath),initFuncName=this.jsFiles[idx].name.replace('.js','').replace(/[\/\\.\-]/g,"_").replace(/^_+/,'')+'_init',postLoadFunction=function(){var tl=true;if(typeof Runner[initFuncName]==="function"){tl=Runner[initFuncName].call(self,idx);}
if(tl!==false){self.postLoad(idx);}};if(runnerWebRootPath!==""&&initFuncName.indexOf(runnerWebRootPath)==0){initFuncName=initFuncName.substring(runnerWebRootPath.length);}
js.setAttribute('type','text/javascript');if(Runner.isIE){js.onreadystatechange=function(){if(js.readyState=='complete'||js.readyState=='loaded'){postLoadFunction();}};}else{js.onload=postLoadFunction;}
js.setAttribute('src',this.jsFiles[idx].name);document.getElementsByTagName('HEAD')[0].appendChild(js);return true;},checkReq:function(fileObj){for(var i=0;i<fileObj.requirements.length;i++){for(var j=0;j<this.jsFiles.length;j++){if(fileObj.requirements[i]==this.jsFiles[j].name&&!this.jsFiles[j].isLoaded){return false;}}}
return true;},postLoad:function(idx,session){var loadedAll=true;if(idx!==undefined){this.jsFiles[idx].isLoaded=true;this.loadDependent(idx);var session=this.jsFiles[idx].session;}
for(var i=0;i<this.jsFiles.length;i++){if(!this.jsFiles[i].isLoaded){loadedAll=false;break;}}
if(loadedAll){if($.inArray(session,this.loadedSes)==-1){this.fireEvent('filesLoaded'+session);this.loadedSes.push(session);}
if(idx!==undefined){for(var i=0;i<this.session;i++){this.postLoad(undefined,i);}}}},onFilesLoaded:function(callback,scope){this.on('filesLoaded'+this.session,callback,scope,{single:true});},loadDependent:function(idx){for(var i=0;i<this.jsFiles.length;i++){for(var j=0;j<this.jsFiles[i].requirements.length;j++){if(i!=idx&&this.jsFiles[i].requirements[j]==this.jsFiles[idx].name){this.loadJS(i);}}}}});Runner.util.ScriptLoader=new Runner.util.ScriptLoader();Runner.Charts={chartModifyHandlers:{},createChart:function(chartParams){if(typeof anychart==="undefined"){return;}
var modifyChartHandler=this.chartModifyHandlers[chartParams.chartName];anychart.licenseKey('xlinesoft-9faa5dd-332123fd');$.get(chartParams.xmlFile,function(data){var chart,gwidth,i,pageObj,hHeight,fHeight;if(chartParams.pageId!==undefined){pageObj=Runner.pages.PageManager.getById(chartParams.pageId);}
if(data.noDataMessage){if(pageObj){pageObj.showPageMessageWithErrorText(data.noDataMessage);}else if(chartParams.pageId!==undefined){Runner.util.ScriptLoader.onFilesLoaded(function(){pageObj=Runner.pages.PageManager.getById(chartParams.pageId);pageObj.showPageMessageWithErrorText(data.noDataMessage);pageObj.asyncInitCall();});}
return;}
if(data.gauge){gwidth=Math.round(chartParams.width/data.gauge.length)-15;$('<div id="'+chartParams.containerId+'_header"></div>').width(chartParams.width).html(data.header).css("text-align","center").appendTo($("#"+chartParams.containerId));$('<div id="'+chartParams.containerId+'_footer"></div>').width(chartParams.width).html(data.footer).css({"text-align":"center","clear":"both"}).appendTo($("#"+chartParams.containerId));hHeight=$("#"+chartParams.containerId+"_header").height();fHeight=$("#"+chartParams.containerId+"_footer").height();for(i=0;i<data.gauge.length;i++){$('<div id="'+chartParams.containerId+'g'+i+'"></div>').css({width:gwidth+"px",height:chartParams.height-hHeight-fHeight+"px","float":"left","margin-right":"15px"}).insertAfter($("#"+chartParams.containerId+"_header"));Runner.Charts.setupChart(data.gauge[i],{height:chartParams.height-hHeight-fHeight,refreshTime:chartParams.refreshTime,pageId:chartParams.pageId,containerId:chartParams.containerId+'g'+i,width:gwidth,chartName:chartParams.chartName,seriaNum:i,chartType:'Gauge'},modifyChartHandler);}
return;}
chart=Runner.Charts.setupChart(data,chartParams,modifyChartHandler);if(pageObj){pageObj.setChart(chart);}
chart.listen("pointClick",function(event){var clickData=data.chart.singleSeries?data.chart.clickData:data.chart.series&&data.chart.series[0].clickData;if(!clickData||clickData[event.pointIndex]===null||isNaN(event.pointIndex)){return;}
if(clickData[event.pointIndex].url){location.href=clickData[event.pointIndex].url;return;}
if(!pageObj){pageObj=Runner.pages.PageManager.getById(chartParams.pageId);pageObj.setChart(chart);}
if(pageObj.handleChartClick){pageObj.handleChartClick(clickData[event.pointIndex]);}});},'json');},setupChart:function(data,chartParams,modifyChartHandler){if(typeof anychart==="undefined"){return;}
var chart=anychart.fromJson(data),pageObj,credits;chart.width=chartParams.width;chart.height=chartParams.height;chart.wMode='opaque';chart.id='chart_'+chartParams.chartName;if(data.gauge){chart.id+='g'+chartParams.seriaNum;}
chart.container(chartParams.containerId);if(chartParams.pageId){pageObj=Runner.pages.PageManager.getById(chartParams.pageId);}
if(modifyChartHandler){modifyChartHandler.call(pageObj,chart,pageObj.proxy,pageObj);}
chart.draw();if(data.chart&&data.chart.type==="financial"){chart.xScale().minimum(chart.xScale().minimum());chart.xScale().maximum(chart.xScale().maximum());}
if(chartParams.refreshTime){chartParams.singleSeries=data.chart&&data.chart.singleSeries;chart.reloadIntervalId=setInterval(function(){Runner.Charts.updateChart(chart,chartParams,data.chart||data.gauge);},chartParams.refreshTime*1000);}
return chart;},updateChart:function(chart,chartParams,currentChartData){var pageObj=Runner.pages.PageManager.getById(chartParams.pageId),params={action:'refresh',rndval:Math.random(),chartname:chartParams.chartName,showDetails:chartParams.showDetails,pageId:chartParams.pageId};if(chartParams.dashChart){params.dashChart=chartParams.dashChart.toString();params.dashTName=chartParams.dashTName.toString();params.dashElementName=chartParams.dashElementName.toString();}
$.post(Runner.getPageUrl("dchartdata"),params,function(json){var i,masterData,seriesData=JSON.parse(json),firstMasterData=null,masterKeysUpdated=true;if(currentChartData.type==="financial"){chart.xScale().minimum(null);chart.xScale().maximum(null);}
if(chartParams.chartType==="Gauge"||chartParams.singleSeries){chart.data(anychart.data.set(seriesData[chartParams.seriaNum||0].data));if(chartParams.chartType==="Gauge"){chart.label().text(seriesData[chartParams.seriaNum||0].labelText);}else{currentChartData.clickData=seriesData[0].clickData;}}else{for(i=0;i<seriesData.length;i++){chart.getSeriesAt(i).data(seriesData[i].data);}
currentChartData.series[0].clickData=seriesData[0].clickData;}
chart.draw();if(currentChartData.type==="financial"){chart.xScale().minimum(chart.xScale().minimum());chart.xScale().maximum(chart.xScale().maximum());}
if(chartParams.dashChart&&seriesData.length>1){for(i=0;i<seriesData.length;i+=2){masterData=seriesData[i+1].clickData;firstMasterData=firstMasterData||masterData;if(pageObj.checkIfMasterKeysUpdated(masterData)){masterKeysUpdated=false;}}
pageObj.refreshDChartData(firstMasterData,masterKeysUpdated);}});}};Runner.Async=function(){this.stack=[];this.loop=function(_collection,_handler){var stackHead;if(typeof _handler==="undefined"){_handler=_collection;_collection=[null];}
if(!this.stack.length){this.stack.push({buffer:[]});}
stackHead=this.stack[this.stack.length-1];stackHead.buffer.push({collection:_collection,index:0,handler:_handler});setTimeout(this.processFunc,0);}
this.processFunc=$.proxy(function(){var stackHead,element,bufLength,handlerResult,stackLength=this.stack.length;if(!stackLength){return;}
stackHead=this.stack[stackLength-1];element=stackHead.buffer[0];if(element.index<element.collection.length){bufLength=stackHead.buffer.length;handlerResult=element.handler.call(null,element.index,element.collection[element.index]);if(stackHead.buffer.length>bufLength){this.stack.push({buffer:stackHead.buffer.splice(bufLength,stackHead.buffer.length-bufLength)});}}
element.index++;if(element.index>=element.collection.length&&this.stack.length==stackLength||handlerResult===false){stackHead.buffer.splice(0,1);if(!stackHead.buffer.length){this.stack.splice(stackLength-1,1);}}
setTimeout(this.processFunc,0);},this);}
Runner.Async=new Runner.Async();Runner.Hash={get:function(){var vars={},hash,splitter,hashes,pos,i;if(!this.oldbrowser()){pos=window.location.href.indexOf('?');hashes=(pos!=-1)?decodeURIComponent(window.location.href.substr(pos+1)):'';splitter='&';}else{hashes=decodeURIComponent(window.location.hash.substr(1));splitter='/';}
if(!hashes.length){return null;}
hashes=hashes.split(splitter);for(i in hashes){if(hashes.hasOwnProperty(i)){hash=hashes[i].split('=');if(typeof hash[1]==='undefined'){vars['anchor']=hash[0];}else{vars[hash[0]]=hash[1];}}}
return vars;},set:function(vars,isReplace){var hash='',i;for(i in vars){if(vars.hasOwnProperty(i)){hash+='&'+i+'='+vars[i];}}
if(hash){hash='?'+hash.substr(1);}
if(this.oldbrowser()){window.location.hash=hash;return;}
if(isReplace){window.history.replaceState(hash,'',document.location.pathname+hash);}else{window.history.pushState(hash,'',document.location.pathname+hash);}},changeUrlHandler:function(callback){var urlParams=Runner.Hash.get(),newUrl="",i;if(!urlParams){return;}
if(urlParams.goto===undefined){urlParams.goto=1;}
if(urlParams.orderby===undefined){urlParams.orderby="noorder";}
if(urlParams.f===undefined){urlParams.f="all";}
for(i in urlParams){if(urlParams.hasOwnProperty(i)){newUrl+='&'+i+'='+urlParams[i];}}
if(newUrl){newUrl='?'+newUrl.substr(1);}
callback(newUrl);},changeUrlListener:function(listnerCallBack){var self=this;if(!this.oldbrowser()){$(window).on("popstate",function(){self.changeUrlHandler(listnerCallBack);});}else if(window.addEventListener){window.addEventListener("hashchange",function(){self.changeUrlHandler(listnerCallBack);});}},add:function(key,val){var hash=this.get()||{};hash[key]=val;this.set(hash);},remove:function(key){var hash=this.get();if(hash){delete hash[key];this.set(hash);}},clear:function(){this.set({},true);},oldbrowser:function(){return!window.history||!history.pushState;}};Runner.arraysEqual=function(arr1,arr2,typeInsensitive){if(arr1.length!==arr2.length){return false;}
for(var i=arr1.length;i--;){if(!typeInsensitive&&arr1[i]!==arr2[i]||typeInsensitive&&arr1[i]!=arr2[i]){return false;}}
return true;}
Runner.normalizeClickActionSettings=function(model){var normalizeSubmodel=function(submodel){submodel=submodel||{};submodel.action=submodel.action||"noaction";submodel.openData=submodel.openData||{};submodel.gridData=submodel.gridData||{};submodel.codeData=submodel.codeData||{};return submodel;}
if(!model||typeof model!=="object"){model={};}
model.row=normalizeSubmodel(model.row);model.fields=model.fields||{};for(var f in model.fields){model.fields[f]=normalizeSubmodel(model.fields[f]);}
return model;}
Runner.md5=(function(){function md5cycle(x,k){var a=x[0],b=x[1],c=x[2],d=x[3];a=ff(a,b,c,d,k[0],7,-680876936);d=ff(d,a,b,c,k[1],12,-389564586);c=ff(c,d,a,b,k[2],17,606105819);b=ff(b,c,d,a,k[3],22,-1044525330);a=ff(a,b,c,d,k[4],7,-176418897);d=ff(d,a,b,c,k[5],12,1200080426);c=ff(c,d,a,b,k[6],17,-1473231341);b=ff(b,c,d,a,k[7],22,-45705983);a=ff(a,b,c,d,k[8],7,1770035416);d=ff(d,a,b,c,k[9],12,-1958414417);c=ff(c,d,a,b,k[10],17,-42063);b=ff(b,c,d,a,k[11],22,-1990404162);a=ff(a,b,c,d,k[12],7,1804603682);d=ff(d,a,b,c,k[13],12,-40341101);c=ff(c,d,a,b,k[14],17,-1502002290);b=ff(b,c,d,a,k[15],22,1236535329);a=gg(a,b,c,d,k[1],5,-165796510);d=gg(d,a,b,c,k[6],9,-1069501632);c=gg(c,d,a,b,k[11],14,643717713);b=gg(b,c,d,a,k[0],20,-373897302);a=gg(a,b,c,d,k[5],5,-701558691);d=gg(d,a,b,c,k[10],9,38016083);c=gg(c,d,a,b,k[15],14,-660478335);b=gg(b,c,d,a,k[4],20,-405537848);a=gg(a,b,c,d,k[9],5,568446438);d=gg(d,a,b,c,k[14],9,-1019803690);c=gg(c,d,a,b,k[3],14,-187363961);b=gg(b,c,d,a,k[8],20,1163531501);a=gg(a,b,c,d,k[13],5,-1444681467);d=gg(d,a,b,c,k[2],9,-51403784);c=gg(c,d,a,b,k[7],14,1735328473);b=gg(b,c,d,a,k[12],20,-1926607734);a=hh(a,b,c,d,k[5],4,-378558);d=hh(d,a,b,c,k[8],11,-2022574463);c=hh(c,d,a,b,k[11],16,1839030562);b=hh(b,c,d,a,k[14],23,-35309556);a=hh(a,b,c,d,k[1],4,-1530992060);d=hh(d,a,b,c,k[4],11,1272893353);c=hh(c,d,a,b,k[7],16,-155497632);b=hh(b,c,d,a,k[10],23,-1094730640);a=hh(a,b,c,d,k[13],4,681279174);d=hh(d,a,b,c,k[0],11,-358537222);c=hh(c,d,a,b,k[3],16,-722521979);b=hh(b,c,d,a,k[6],23,76029189);a=hh(a,b,c,d,k[9],4,-640364487);d=hh(d,a,b,c,k[12],11,-421815835);c=hh(c,d,a,b,k[15],16,530742520);b=hh(b,c,d,a,k[2],23,-995338651);a=ii(a,b,c,d,k[0],6,-198630844);d=ii(d,a,b,c,k[7],10,1126891415);c=ii(c,d,a,b,k[14],15,-1416354905);b=ii(b,c,d,a,k[5],21,-57434055);a=ii(a,b,c,d,k[12],6,1700485571);d=ii(d,a,b,c,k[3],10,-1894986606);c=ii(c,d,a,b,k[10],15,-1051523);b=ii(b,c,d,a,k[1],21,-2054922799);a=ii(a,b,c,d,k[8],6,1873313359);d=ii(d,a,b,c,k[15],10,-30611744);c=ii(c,d,a,b,k[6],15,-1560198380);b=ii(b,c,d,a,k[13],21,1309151649);a=ii(a,b,c,d,k[4],6,-145523070);d=ii(d,a,b,c,k[11],10,-1120210379);c=ii(c,d,a,b,k[2],15,718787259);b=ii(b,c,d,a,k[9],21,-343485551);x[0]=add32(a,x[0]);x[1]=add32(b,x[1]);x[2]=add32(c,x[2]);x[3]=add32(d,x[3]);}
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>(32-s)),b);}
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t);}
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t);}
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t);}
function md51(s){var n=s.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],state=[1732584193,-271733879,-1732584194,271733878],i;for(i=64;i<=s.length;i+=64){md5cycle(state,md5blk(s.substring(i-64,i)));}
s=s.substring(i-64);for(i=0;i<s.length;i++){tail[i>>2]|=s.charCodeAt(i)<<((i%4)<<3);}
tail[i>>2]|=0x80<<((i%4)<<3);if(i>55){md5cycle(state,tail);for(i=0;i<16;i++){tail[i]=0;}}
tail[14]=n*8;md5cycle(state,tail);return state;}
function md5blk(s){var md5blks=[],i;for(i=0;i<64;i+=4){md5blks[i>>2]=s.charCodeAt(i)
+(s.charCodeAt(i+1)<<8)
+(s.charCodeAt(i+2)<<16)
+(s.charCodeAt(i+3)<<24);}
return md5blks;}
var hex_chr='0123456789abcdef'.split('');function rhex(n){for(var s='',j=0;j<4;j++){s+=hex_chr[(n>>(j*8+4))&0x0F]+hex_chr[(n>>(j*8))&0x0F];}
return s;}
function hex(x){for(var i=0;i<x.length;i++){x[i]=rhex(x[i]);}
return x.join('');}
function md5(s){return hex(md51(s));}
function add32(a,b){return(a+b)&0xFFFFFFFF;}
if(md5('hello')!='5d41402abc4b2a76b9719d911017c592'){function add32(x,y){var lsw=(x&0xFFFF)+(y&0xFFFF),msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}}
return md5;}());Runner.getCustomLabel=function(name){return Runner.lang.customlabels[Runner.lang.customlabels.prefix+name];};Runner.util.absToFixed=function($e){var offsetParent=null,css={position:'fixed',right:'auto',bottom:'auto'},offset=$e.offset(),parentOffset;if(!Runner.isIE&&!Runner.isIE11){$e.parents().each(function(i,p){if($(p).css('transform')!='none'){offsetParent=p;return false;}});}
if(offsetParent===null){css.top=offset.top-($(document.body).scrollTop()||$(window).scrollTop());css.left=offset.left-$(document.body).scrollLeft();}else{parentOffset=$(offsetParent).offset();css.top=offset.top-parentOffset.top;css.left=offset.left-parentOffset.left;}
$e.css(css);};Runner.Tabs=function($tabContext){var $tabNav=$("ul.nav-tabs",$tabContext),$tabContent=$(".tab-content",$tabContext),preventTabShow=function(e){e.preventDefault();};this.count=function(){return $tabNav.children("li").length;};this.activate=function(n){var $li=$tabNav.children("li").eq(n);if($li.is(":visible")&&!$li.hasClass("disable")){$("a[data-toggle='tab']",$li).tab("show");}};this.activeIdx=function(){$activeLi=$tabNav.children("li.active");return $tabNav.children("li").index($activeLi);};this.hide=function(n){var $newActiveLi,$liToHide=$tabNav.children("li").eq(n);if(n==this.activeIdx()){$newActiveLi=$tabNav.children("li:visible").not(".active",".disabled");$("a[data-toggle='tab']",$newActiveLi).tab("show");if(!$newActiveLi.length){this.bodyElement(n).removeClass("active");$liToHide.removeClass("active");}}
$liToHide.hide();};this.show=function(n){$tabNav.children("li").eq(n).show();if(this.activeIdx()===-1){this.activate(n);}};this.disable=function(n){var $li=$tabNav.children("li").eq(n);$li.addClass("disabled");$("a[data-toggle='tab']",$li).on("show.bs.tab",preventTabShow);};this.enable=function(n){var $li=$tabNav.children("li").eq(n);$li.removeClass("disabled");$("a[data-toggle='tab']",$li).off("show.bs.tab",preventTabShow);};this.headerElement=function(n){return $("a[data-toggle='tab']",$tabNav.children("li").eq(n));};this.bodyElement=function(n){var idSelector=$("a[data-toggle='tab']",$tabNav.children("li").eq(n)).attr("href");return $(idSelector,$tabContent);};this.addTab=function(headerHtml,panelHtml){var tabIdx=this.count()+1,tabId="newTab"+tabIdx,$a=$('<a role="tab" data-toggle="tab" href="#'+tabId+'"></a>').html(headerHtml);$('<li></li>').append($a).appendTo($tabNav);$('<div id="'+tabId+'" role="tabpanel" class="tab-pane"></div>').html(panelHtml).appendTo($tabContent);$a.tab();return tabIdx;};this.removeTab=function(n){var $li=$tabNav.children("li").eq(n),$content=$tabContent.children("div").eq(n);if($li.length){$li.remove();$content.remove()
this.activate(0);}};this.moveTo=function(n,m){var $liToMove=$tabNav.children("li").eq(n);if(m==n||!$liToMove.length){return;}
if(m<1){$tabNav.prepend($liToMove);return;}
if(m>=this.count()){$tabNav.append($liToMove);return;}
if(n<m){$liToMove.insertAfter($tabNav.children("li").eq(m));}else{$liToMove.insertBefore($tabNav.children("li").eq(m));}};};Runner.Section=function($context){var $toggler=$('[data-toggle="collapse"]',$context),$toggledPanel=$($toggler.attr("href"),$context);this.headerElement=function(){return $('[data-toggle="collapse"]',$context);};this.bodyElement=function(){return $toggledPanel.children(".panel-body");};this.expand=function(){$toggledPanel.collapse("show")};this.collapse=function(){$toggledPanel.collapse("hide");};this.get=function(){return $toggledPanel;};};+function($){'use strict';var backdrop='.dropdown-backdrop'
var toggle='[data-toggle="nested-dropdown"]'
var Dropdown=function(element){$(element).on('click.bs.dropdown',this.toggle)}
Dropdown.VERSION='3.3.5'
function getParent($this){var selector=$this.attr('data-target')
if(!selector){selector=$this.attr('href')
selector=selector&&/#[A-Za-z]/.test(selector)&&selector.replace(/.*(?=#[^\s]*$)/,'')}
var $parent=selector&&$(selector)
return $parent&&$parent.length?$parent:$this.parent()}
function clearMenus(e){if(e&&e.which===3)return
$(backdrop).remove()
$(toggle).each(function(){var $this=$(this)
var $parent=getParent($this)
var relatedTarget={relatedTarget:this}
if(!$parent.hasClass('open'))return;if(e&&e.type=='click'&&/input|textarea/i.test(e.target.tagName)&&$.contains($parent[0],e.target))return
if(e&&!$(e.target).parent().is($parent)&&$parent.has(e.target).length)
return;$parent.trigger(e=$.Event('hide.bs.dropdown',relatedTarget))
if(e.isDefaultPrevented())return
$this.attr('aria-expanded','false')
$parent.removeClass('open').trigger('hidden.bs.dropdown',relatedTarget)})}
Dropdown.prototype.toggle=function(e){var $this=$(this)
if($this.is('.disabled, :disabled'))return
var $parent=getParent($this)
var isActive=$parent.hasClass('open')
clearMenus(e)
if(!isActive){if('ontouchstart'in document.documentElement&&!$parent.closest('.navbar-nav').length){$(document.createElement('div')).addClass('dropdown-backdrop').insertAfter($(this)).on('click',clearMenus)}
var relatedTarget={relatedTarget:this}
$parent.trigger(e=$.Event('show.bs.dropdown',relatedTarget))
if(e.isDefaultPrevented())return
$this.trigger('focus').attr('aria-expanded','true')
$parent.toggleClass('open').trigger('shown.bs.dropdown',relatedTarget)}
return false}
Dropdown.prototype.keydown=function(e){if(!/(38|40|27|32)/.test(e.which)||/input|textarea/i.test(e.target.tagName))return
var $this=$(this)
e.preventDefault()
e.stopPropagation()
if($this.is('.disabled, :disabled'))return
var $parent=getParent($this)
var isActive=$parent.hasClass('open')
if(!isActive&&e.which!=27||isActive&&e.which==27){if(e.which==27)$parent.find(toggle).trigger('focus')
return $this.trigger('click')}
var desc=' li:not(.disabled):visible a'
var $items=$parent.find('.dropdown-menu'+desc)
if(!$items.length)return
var index=$items.index(e.target)
if(e.which==38&&index>0)index--
if(e.which==40&&index<$items.length-1)index++
if(!~index)index=0
$items.eq(index).trigger('focus')}
function Plugin(option){return this.each(function(){var $this=$(this)
var data=$this.data('bs.dropdown')
if(!data)$this.data('bs.dropdown',(data=new Dropdown(this)))
if(typeof option=='string')data[option].call($this)})}
var old=$.fn.dropdown
$.fn.dropdown=Plugin
$.fn.dropdown.Constructor=Dropdown
$.fn.dropdown.noConflict=function(){$.fn.dropdown=old
return this}
$(document).on('click.bs.dropdown.data-api',clearMenus).on('click.bs.dropdown.data-api','.dropdown form',function(e){e.stopPropagation()}).on('click.bs.dropdown.data-api',toggle,Dropdown.prototype.toggle).on('keydown.bs.dropdown.data-api',toggle,Dropdown.prototype.keydown).on('keydown.bs.dropdown.data-api','.dropdown-menu',Dropdown.prototype.keydown)}(jQuery);Runner.namespace('Runner.bricks');Runner.bricks.BrickManager=Runner.extend(Runner.emptyFn,{elem:null,layoutVersion:2,name:'',pageCont:null,baseName:'',baseClass:'',hiddenClass:'',constructor:function(cfg){Runner.apply(this,cfg);this.baseName="rnr-";},getElemName:function(elem){if(this.name){return;}
if(typeof elem=='undefined'){elem=this.elem;}
if(!elem.attr('class')){return;}
var cls=elem.attr('class').split(' '),i,pos;for(i=0;i<cls.length;i++){if(cls[i]){pos=cls[i].indexOf(this.baseClass);if(pos>-1){this.name=cls[i].substr(pos+this.baseClass.length).trim();break;}}}},hide:function(){if(this.layoutVersion!=3){if(!this.elem.hasClass(this.hiddenClass)){this.elem.addClass(this.hiddenClass);}}else{this.elem.attr("data-hidden",'');}},show:function(){this.elem.removeClass(this.hiddenClass);if(this.layoutVersion==3){this.elem.removeAttr("data-hidden");}},toggle:function(toggler){toggler?this.show():this.hide();},visible:function(){if(this.layoutVersion==3){return!this.elem.is("[data-hidden]");}
return!this.elem.hasClass(this.hiddenClass);}});Runner.bricks.Brick=Runner.extend(Runner.bricks.BrickManager,{contObj:false,contentElem:false,name:"",constructor:function(cfg){Runner.bricks.Brick.superclass.constructor.call(this,cfg);this.baseClass=this.baseName+'b-';this.hiddenClass=this.baseName+'hiddenbrick';this.getElemName();this.getContainer();this.getContentElem();if(this.elem.hasClass(this.baseClass+"wrapper")){this.hiddenClass=this.baseName+"hiddencontainer";}},getBrickObjs:function(name,pageCont,all,version,pageId){var query,brickObjs=[],self=this;version=version||2;if(version==2){query=all?'[class*=rnr-b-]':'.rnr-b-'+name;$(query,pageCont).each(function(){var $elem=$(this),foundPageClass=false,foundPageCont=false;$elem.parents().each(function(n,parentElem){if(Runner.bricks.Brick.prototype.hasPageClass(parentElem)){if(foundPageClass){return false;}
foundPageClass=true;}
if($(pageCont).is(parentElem)){foundPageCont=true;return false;}});if(!foundPageCont){return;}
brickObjs.push(new Runner.bricks.Brick({name:name,elem:$elem,pageCont:pageCont,layoutVersion:version}));});}else{query='[data-pageid='+pageId+']'+(all?'[data-brick]':'[data-brick='+name+']');$(query,pageCont).each(function(){brickObjs.push(new Runner.bricks.Brick({name:name,elem:$(this),pageCont:pageCont,layoutVersion:version}));});}
return brickObjs;},hasPageClass:function(container){var $container=container instanceof jQuery?container:$(container),classes=$container.attr("class"),classRegExp=/^\s*page-|\s*page-/;return classRegExp.test(classes);},getPageClass:function(container){var $container=container instanceof jQuery?container:$(container),classes=$container.attr("class"),classRegExp=/^\s*page-[^\s]+|\s*page-[^\s]+/;return classRegExp.exec(classes)[0].trim();},getContentElem:function(){var brickContents=$('.'+this.baseName+'brickcontents',this.elem);this.contentElem=brickContents.length?brickContents:this.elem;},getContainer:function(){var contElem,_self=this;if(this.layoutVersion==3){contElem=this.elem.closest('[data-pageid='+this.elem.data('pageid')+'][data-container]');}else{this.elem.parents('div:not(".not-container")').each(function(){var classes=[],i,$elem=$(this);if($elem.attr('class')!==undefined){classes=$elem.attr('class').split(' ');}
for(i=0;i<classes.length;i++){if(classes[i].indexOf(_self.baseName+"s-")===0){contElem=$elem;return false;}}});}
if(contElem&&contElem.length){this.contObj=new Runner.bricks.Container({elem:contElem,pageCont:this.pageCont,layoutVersion:this.layoutVersion});}},hide:function(){Runner.bricks.Brick.superclass.hide.call(this);if(this.contObj){this.contObj.updateVisibility();}},show:function(){Runner.bricks.Brick.superclass.show.call(this);if(this.contObj){this.contObj.show();}},prepareToReplaceWith:function(newHTML,isHidden){this.toggle(!isHidden&&newHTML);},replaceWith:function(newHTML){this.prepareToReplaceWith(newHTML);this.elem.replaceWith(newHTML);},replaceHTMLWith:function(newHTML){this.prepareToReplaceWith(newHTML.html,newHTML.isHidden);this.elem.empty().html(newHTML.html);},replaceContentWith:function(newContent){this.prepareToReplaceWith(newContent);this.contentElem.replaceWith(newContent);},replaceContentHTMLWith:function(newHTML){this.prepareToReplaceWith(newHTML);this.contentElem.empty().html(newHTML);},moveTo:function(newContainer){var oldContainer=this.contObj;this.elem.after(this.createPlaceholder());newContainer.addBrick(this);this.contObj=newContainer;newContainer.updateVisibility();oldContainer.updateVisibility();},createPlaceholder:function(){var tagName=this.elem.get(0).tagName;return $('<'+tagName+' class="rnr-ph-'+this.name+'"></'+tagName+'>');},visible:function(){var isVisible=Runner.bricks.Brick.superclass.visible.call(this);if(this.contObj){isVisible=isVisible&&this.contObj.visible();}
return isVisible;}});Runner.bricks.Container=Runner.extend(Runner.bricks.BrickManager,{blockObj:false,constructor:function(cfg){Runner.bricks.Container.superclass.constructor.call(this,cfg);this.baseClass=this.baseName+'c-';this.hiddenClass=this.baseName+'hiddencontainer';this.getElemName();this.getBlock();},getElemName:function(){Runner.bricks.Container.superclass.getElemName.call(this,$('.'+this.baseName+'c:first',this.elem));},updateVisibility:function(){var bricks=this.getBricks(),visible=false,i;for(i=0;i<bricks.length;i++){if(bricks[i].visible()){visible=true;break;}}
this.toggle(visible);},hide:function(){Runner.bricks.Container.superclass.hide.call(this);if(this.layoutVersion!=3){var $bWrapperParent=this.getBWrapperParent();if($bWrapperParent.length){new Runner.bricks.Brick({elem:$bWrapperParent,layoutVersion:this.layoutVersion,pageCont:this.pageCont}).hide();return;}}else if(this.elem.parent('[data-container]').length){new Runner.bricks.Container({elem:this.elem.parent(),pageCont:this.pageCont,layoutVersion:this.layoutVersion}).updateVisibility();}
if(this.blockObj){this.blockObj.updateVisibility();}},getBWrapperParent:function(){if(this.pageCont){return $(this.pageCont).find($(this.elem).closest('.'+this.baseName+'b-wrapper'));}
return $(this.elem).closest('.'+this.baseName+'b-wrapper');},show:function(){Runner.bricks.Container.superclass.show.call(this);var $bWrapperParent=this.getBWrapperParent();if(this.layoutVersion!=3){if($bWrapperParent.length){new Runner.bricks.Brick({elem:$bWrapperParent,layoutVersion:this.layoutVersion,pageCont:this.pageCont}).show();return;}}else if(this.elem.parent('[data-container]').length){new Runner.bricks.Container({elem:this.elem.parent(),pageCont:this.pageCont,layoutVersion:this.layoutVersion}).show();}
if(this.blockObj){this.blockObj.show();}},getBricks:function(){var bricksArr=[],_self=this;if(this.layoutVersion==3){$('[data-pageid='+this.elem.data('pageid')+'][data-brick]',this.elem).each(function(){bricksArr.push(new Runner.bricks.Brick({elem:$(this),layoutVersion:_self.layoutVersion}));})}else{$('[class*="'+this.baseName+'b-"]',this.elem).each(function(){var $elem=$(this),foundContainer=false;$elem.parents().each(function(n,parentElem){if(Runner.bricks.Brick.prototype.hasPageClass(parentElem)||$(parentElem).hasClass("rnr-dbelemtable")){return false;}
if(_self.elem.is(parentElem)){foundContainer=true;return false;}});if(!foundContainer){return;}
bricksArr.push(new Runner.bricks.Brick({elem:$(this),layoutVersion:_self.layoutVersion}));});}
return bricksArr;},getBlock:function(elem){var blockSelector,blockElem;if(this.layoutVersion==2){blockSelector='.rnr-top, .rnr-left, .rnr-center, .rnr-right, .rnr-bottom';}else if(this.layoutVersion==3){blockSelector='.bs-topmiddle, .bs-left, .bs-center, .bs-right, .sidebar';}else{blockSelector='td';}
if(typeof elem=='undefined'){blockElem=this.elem.closest(blockSelector);}else{blockElem=elem.parent().closest(blockSelector);}
if(blockElem.hasClass(this.baseName+'wrapper')){this.getBlock(blockElem);return;}
if(blockElem.length){this.blockObj=new Runner.bricks.Block({elem:blockElem,layoutVersion:this.layoutVersion});}},cloneEmpty:function(){var bricks=this.getBricks(),clone=this.elem,cloner;cloner=function(_clone){var cloned,i,$elem=$(this),matchedBrick=null;for(i=bricks.length-1;i>=0;--i){if(bricks[i].elem.is(this)){matchedBrick=bricks[i];break;}}
if($elem.hasClass("rnr-hfiller")||$elem.hasClass("filler")){return;}
if(matchedBrick){if(_clone){$(_clone).append(matchedBrick.createPlaceholder());}
return;}
cloned=$elem.get(0).cloneNode(false);if(_clone){$(_clone).append(cloned);}
$elem.children().each(function(){cloner.call(this,cloned);});return cloned;}
return new Runner.bricks.Container({elem:$(cloner.call(this.elem)),pageCont:this.pageCont,layoutVersion:this.layoutVersion});},appendTo:function(elem){$(elem).append(this.elem);},addBrick:function(brick){var placeholder=this.findPlaceholder(brick.name);if(placeholder.length){placeholder.replaceWith(brick.elem);}else{this.elem.children().first().append(brick.elem);}},findPlaceholder:function(name){return $(".rnr-ph-"+name,this.elem);},is:function(contObj){return this.elem.is(contObj.elem);}});Runner.bricks.Block=Runner.extend(Runner.bricks.BrickManager,{constructor:function(cfg){Runner.bricks.Block.superclass.constructor.call(this,cfg);this.baseClass=this.baseName;this.hiddenClass=this.baseName+'hiddenblock';this.getElemName();},getContainers:function(){var contsArr=[],selector='[class*="'+this.baseName+'s-"]',block=this;if(this.layoutVersion==3){selector='[data-container]';}
$(selector,this.elem).each(function(){contsArr.push(new Runner.bricks.Container({elem:$(this),layoutVersion:block.layoutVersion}));});return contsArr;},updateVisibility:function(){var conts=this.getContainers(),visible=false;for(var i=0;i<conts.length;i++){if(conts[i].visible()){visible=true;break;}}
this.toggle(visible);}});Runner.namespace('Runner.menu');Runner.menu.Manager=Runner.extend(Runner.emptyFn,{isDirRTL:false,init:function(){var dir=$('html').attr('dir')||'';if(dir.toLowerCase()=='rtl'){this.isDirRTL=true;}},itemClickHandler:function(event){var target=event.target,link=$('a:first',this)[0];if(typeof link==="undefined"){return false;}
if($(this).hasClass('Group')&&target.nodeName!='IMG'&&!link.href){$('.groupImg:first',this).click();return;}
if(target.nodeName=="A"){if(target.rel=='external'){$(target).attr('target',"_blank");}
return;}
Runner.Event.prototype.stopEvent(event);if(link.href){if(link.rel=='external'){return!window.open(link.href);}
window.location=link.href;}}});Runner.menu.QuickJump=Runner.extend(Runner.emptyFn,{selectCurrent:-1,init:function(){var menuObj=this;$(".runner-quickjump:first").prop("initialized","true");$(".runner-quickjump").bind({focus:function(){menuObj.selectCurrent=this.selectedIndex;},change:function(){if(this.options[this.selectedIndex].value){if($(this.options[this.selectedIndex]).attr('link')=='External'){window.open(this.options[this.selectedIndex].value);}else{window.location.href=this.options[this.selectedIndex].value;}}else{this.selectedIndex=menuObj.selectCurrent;}}});}});Runner.menu.Horizontal=Runner.extend(Runner.menu.Manager,{maxSubMenuWidth:0,maxGroupWidth:0,maxItemWidth:0,topItemAbsPos:null,itemHovered:false,subMenu:[],init:function(){Runner.menu.Horizontal.superclass.init.call(this);this.bindHoverOnItems();this.bindClickOnItems();this.setRaquoToTopItems();$(".runner-hmenu:first").prop("initialized","true");},findSubMenu:function(elem){this.subMenu=$('ul:first:has(li)',elem);},manageActiveClass:function(elem,toggle){if($(elem).hasClass('Separator')){return;}
if($('table:first',elem).length){$('.runner-menutab',elem).toggleClass('active',toggle);return;}
$(elem).toggleClass('active',toggle);},manageExpandedClass:function(elem,toggle){if($('table:first',elem).length){$('.runner-menutab',elem).toggleClass('expanded',toggle);return;}
$(elem).toggleClass('expanded',toggle);},bindHoverOnItems:function(){var menuObj=this;$('.runner-hmenu td, .runner-hmenu ul li').hover(function(){var isTopItem,$raquo;menuObj.manageActiveClass(this,true);menuObj.findSubMenu(this);if(!menuObj.subMenu.length){return;}
menuObj.manageExpandedClass(this,true);menuObj.maxGroupWidth=0;isTopItem=$(this).is("td");if(isTopItem){menuObj.topItemAbsPos=$(this).position();menuObj.maxItemWidth=menuObj.topItemAbsPos.width;}
$('li[parent='+(menuObj.subMenu.attr('id'))+'] a',menuObj.subMenu).each(function(){if(menuObj.maxGroupWidth<this.offsetWidth){menuObj.maxGroupWidth=this.offsetWidth}});if(isTopItem&&menuObj.maxGroupWidth<menuObj.maxItemWidth){menuObj.maxSubMenuWidth=menuObj.maxItemWidth;}else{menuObj.maxSubMenuWidth=menuObj.maxGroupWidth;}
menuObj.maxSubMenuWidth+=10;menuObj.subMenu.css('width',menuObj.maxSubMenuWidth+'px');if(isTopItem){if(menuObj.isDirRTL){menuObj.subMenu.css('left',menuObj.topItemAbsPos.left+($(this).outerWidth()-menuObj.subMenu[0].offsetWidth)+'px');}else{menuObj.subMenu.css('left',menuObj.topItemAbsPos.left+'px');}
menuObj.subMenu.css('top',menuObj.topItemAbsPos.top+$(this).outerHeight()-1+'px');}else{$raquo=$('.raquo',this);leftPosition=$raquo.position().left+$raquo.get(0).offsetWidth-$raquo.position().left+10;if($(this).outerWidth()<leftPosition){leftPosition=$(this).outerWidth()-1;}
menuObj.subMenu.css({'top':this.offsetTop+'px','left':leftPosition+'px'});}
$('li[parent='+menuObj.subMenu.attr('id')+']',menuObj.subMenu).each(function(){$(this).css('width',menuObj.maxSubMenuWidth+'px');$('ul:first',this).css((menuObj.isDirRTL?'right':'left'),menuObj.maxSubMenuWidth+'px');});},function(){menuObj.findSubMenu(this);if(menuObj.subMenu.length){menuObj.manageExpandedClass(this,false);}
menuObj.manageActiveClass(this,false);});},bindClickOnItems:function(){$('.runner-hmenu td, .runner-hmenu ul li').click(this.itemClickHandler);},setRaquoToTopItems:function(){var curTopItem;$('a:first','.runner-hmenu td:has(ul:has(li)), .runner-hmenu li:has(ul:has(li))').each(function(){if(!$('b',this).length){$(this).after('<b class="raquo">&nbsp;&raquo;</b>');}});curTopItem=$('.runner-hmenu td:has(ul:has(li.current))');$('b.raquo:first',curTopItem).append("&nbsp;<b class='subcur'>"+$(".runner-hmenu .curlink").attr('itemtitle')+"</b>");$('tr.runner-menutab',curTopItem).addClass('current');$('.runner-hmenu ul li ul li ul').css('top','0px');}});Runner.menu.SimpleVmenu=Runner.extend(Runner.menu.Manager,{subMenu:[],init:function(){Runner.menu.SimpleVmenu.superclass.init.call(this);this.bindHoverOnItems();this.bindClickOnItems();this.setRaquoToTopItems();$(".runner-vmenu.simple:first").prop("initialized","true");},findSubMenu:function(elem){this.subMenu=$('ul:first:has(li)',elem);},manageActiveClass:function(elem,toggle){if(!$(elem).hasClass('Separator')){$(elem).toggleClass('active',toggle);}},manageExpandedClass:function(elem,toggle){$(elem).toggleClass('expanded',toggle);},bindHoverOnItems:function(){var menuObj=this;$('.runner-vmenu.simple, .runner-vmenu.simple ul li').hover(function(){var elParentUlPosition,elParentUlWidth,offsetHSide,offsetValue,isTopItem;menuObj.manageActiveClass(this,true);menuObj.findSubMenu(this);if(!menuObj.subMenu.length){return;}
menuObj.manageExpandedClass(this,true);isTopItem=$(this).hasClass("runner-vmenu");elParentUlWidth=isTopItem?$(this).width():$(this).closest("ul").width();elParentUlPosition=$(this).position();offsetHSide=menuObj.isDirRTL?'right':'left';if(!isTopItem){offsetValue=elParentUlWidth;}else{offsetValue=menuObj.isDirRTL?$(window).width()-elParentUlPosition.left:elParentUlWidth+elParentUlPosition.left;}
menuObj.subMenu.css(offsetHSide,offsetValue+'px');menuObj.subMenu.css('top',(elParentUlPosition.top)+'px');},function(){menuObj.findSubMenu(this);if(menuObj.subMenu.length){menuObj.manageExpandedClass(this,false);}
menuObj.manageActiveClass(this,false);});},bindClickOnItems:function(){$('.runner-vmenu.simple, .runner-vmenu.simple ul li').click(this.itemClickHandler);},setRaquoToTopItems:function(){var curTopItem;$('.runner-vmenu.simple:has(ul:has(li)), .runner-vmenu.simple li:has(ul:has(li))').find('a:first').each(function(){if(!$('b',this).length){$(this).after('<b class="raquo">&nbsp;&raquo;</b>');}});curTopItem=$('.runner-vmenu.simple:has(ul:has(li.current))');curTopItem.find("b.raquo:first").append("&nbsp;<b class='subcur'>"+$(".runner-vmenu.simple a.curlink").attr('itemtitle')+"</b>");curTopItem.addClass('current');}});Runner.menu.TreeLikeVmenu=Runner.extend(Runner.menu.Manager,{cookieRoot:"",curItem:null,curItemId:"",curItemLevel:-1,init:function(){if($('.runner-vmenu.tree .curlink').length){this.curItem=$('.runner-vmenu.tree .curlink').closest('tr');this.curItemId=$(this.curItem).attr('id');this.curItemLevel=this.getItemLevel(this.curItem);}
$('.runner-vmenu.tree[parent]').addClass('runner-hiddenelem');this.bindHoverOnItems();this.setCurrentStyle();this.toggleMenuGroup();this.manageExpandCollapse();this.openMenuOnLoad();$(".runner-vmenu.tree:first").prop("initialized","true");},getItemLevel:function(item){var clsItem=$(item).attr('class'),pos=clsItem.indexOf("level");if(pos==-1){return 0;}
return parseInt(clsItem.substr(pos+5,1),10);},bindHoverOnItems:function(){$('.runner-vmenu.tree[id^=item]').hover(function(){if($(this).parent().attr('class')!='Separator'){$(this).addClass('active');}},function(){if($(this).parent().attr('class')!='Separator'){$(this).removeClass('active');}});$('.runner-vmenu.tree[id^=item]').click(this.itemClickHandler);},setCurrentStyle:function(){$('.runner-vmenu.tree.Group[view=topitem]').each(function(){var group=this;$('.runner-vmenu.tree[topparent='+this.id+']').each(function(){if($(this).hasClass('current')){$(group).addClass('current');}});});},toggleMenuGroup:function(){var menuObj=this;$('.runner-vmenu.tree.Group span').click(function(){var spanItem=$(this).closest("tr"),spanItemId=spanItem.attr('id');if($('.groupImg',this).attr('src')==Runner.pages.constants.PLUS_GIF){menuObj.showGroupChildren(spanItem,spanItemId);}else if($('.groupImg',this).attr('src')==Runner.pages.constants.MINUS_GIF){menuObj.hideGroupChildren(spanItem,spanItemId);if(spanItemId!=menuObj.curItemId&&menuObj.curItemLevel>menuObj.getItemLevel(spanItem)&&menuObj.hasCurrentItem(spanItem,spanItemId)){spanItem.addClass('current');}}
return false;});},showGroupChildren:function(item,itemId){var menuObj=this;if(!itemId){itemId=$(item).attr('id');}
$('.groupImg',item).attr('src',Runner.pages.constants.MINUS_GIF);if(itemId!=this.curItemId&&$(item).hasClass('current'))
$(item).removeClass('current');$('.runner-vmenu.tree[parent='+itemId+']').each(function(){$(this).removeClass('runner-hiddenelem');if($(this).hasClass('Group')&&menuObj.curItemLevel>menuObj.getItemLevel(this)&&menuObj.hasCurrentItem(this)){menuObj.showGroupChildren(this);}});this.addToCookie(itemId);},hideGroupChildren:function(item,itemId){var menuObj=this;if(!itemId){itemId=$(item).attr('id');}
$('.groupImg',item).attr('src',Runner.pages.constants.PLUS_GIF);$('.runner-vmenu.tree[parent='+itemId+']').each(function(){$(this).addClass('runner-hiddenelem');if($(this).hasClass('Group'))
menuObj.hideGroupChildren(this);});this.removeFromCookie(itemId);},hasCurrentItem:function(item,itemId){if(!itemId){itemId=$(item).attr('id');}
if($('.runner-vmenu.tree.[parent='+itemId+']').hasClass('current')){return true;}
var colSubGroups=$('.runner-vmenu.tree.Group.[parent='+itemId+']').length;for(var i=0;i<colSubGroups;i++){if(this.hasCurrentItem($('.runner-vmenu.tree.Group.[parent='+itemId+']').get(i)))
return true;}
return false;},manageExpandCollapse:function(){var menuObj=this,expand=false;if($('.runner-vmenu.tree.Group[view=topitem]').length){$('.manage').css('display','inline');$('.manage a').click(function(){if(expand){expand=false;$('.runner-vmenu.tree[parent]').addClass('runner-hiddenelem');$('.manage a').empty();$('img.groupImg').attr('src',Runner.pages.constants.PLUS_GIF);$('.manage a').append('<img src=\"'+Runner.pages.constants.PLUS_GIF+'\" border=0> &nbsp;&nbsp;'+Runner.lang.constants.TEXT_EXPAND_ALL);delete_cookie('openMenuGroupIds',menuObj.cookieRoot,'');if(menuObj.curItem){$('#'+menuObj.curItem.attr('topparent')).addClass('current');}}else{expand=true;$('.runner-vmenu.tree[parent]').removeClass('runner-hiddenelem');$('.manage a').empty();$('img.groupImg').attr('src',Runner.pages.constants.MINUS_GIF);$('.manage a').append('<img src=\"'+Runner.pages.constants.MINUS_GIF
+'\" border=0> &nbsp;&nbsp;'+Runner.lang.constants.TEXT_COLLAPSE_ALL);$('.runner-vmenu.tree.Group').each(function(){menuObj.addToCookie(this.id);});if(menuObj.curItem){$('#'+menuObj.curItem.attr('topparent')).removeClass('current');}}
return false;});}},addToCookie:function(menuGroupId){var openMenuGroupIds=get_cookie('openMenuGroupIds');if(openMenuGroupIds){if(openMenuGroupIds.indexOf(menuGroupId)==-1){openMenuGroupIds+=";"+menuGroupId;}}else{openMenuGroupIds=menuGroupId;}
set_cookie('openMenuGroupIds',openMenuGroupIds,'',this.cookieRoot);this.toggleExpandCollapse();},removeFromCookie:function(menuGroupId){var openMenuGroupIds=get_cookie('openMenuGroupIds');if(openMenuGroupIds){openMenuGroupIds=openMenuGroupIds.replace((";"+menuGroupId),"");openMenuGroupIds=openMenuGroupIds.replace(menuGroupId,"");if(openMenuGroupIds.indexOf(';')==0)
openMenuGroupIds=openMenuGroupIds.substr(1,openMenuGroupIds.length);set_cookie('openMenuGroupIds',openMenuGroupIds,'',this.cookieRoot);}
setTimeout(function(){Runner.menu.TreeLikeVmenu.prototype.toggleExpandCollapse();},500);},toggleExpandCollapse:function(){var visibleLength=$(".runner-vmenu.tree.subitem:visible").length,hiddenLength=$(".runner-vmenu.tree.subitem:hidden").length;if(visibleLength==0&&hiddenLength>0){$('.manage a').empty();$('.groupImg').attr('src',Runner.pages.constants.PLUS_GIF);$('.manage a').append('<img src=\"'+Runner.pages.constants.PLUS_GIF+'\" border=0> &nbsp;&nbsp;'+Runner.lang.constants.TEXT_EXPAND_ALL);}else if(visibleLength!=0&&hiddenLength==0){$('.manage a').empty();$('.groupImg').attr('src',Runner.pages.constants.MINUS_GIF);$('.manage a').append('<img src=\"'+Runner.pages.constants.MINUS_GIF+'\" border=0> &nbsp;&nbsp;'+Runner.lang.constants.TEXT_COLLAPSE_ALL);}},openMenuOnLoad:function(){this.cookieRoot=Runner.getCookieRoot();var openMenuGroupIds=get_cookie('openMenuGroupIds');if(openMenuGroupIds){var groupForOpenArr=openMenuGroupIds.split(";");for(var i=0;i<groupForOpenArr.length;i++){if(groupForOpenArr[i].indexOf('item')==-1){continue;}
var group=$('#'+groupForOpenArr[i]);group.removeClass('runner-hiddenelem');$('.runner-vmenu.tree[parent='+groupForOpenArr[i]+']').removeClass('runner-hiddenelem');$(".groupImg",group).attr("src",Runner.pages.constants.MINUS_GIF);}
this.afterOpenMenuOnLoad();}
this.toggleExpandCollapse();},afterOpenMenuOnLoad:function(item){if(typeof item=='undefined'){if(!this.curItem){return;}
item=this.curItem;}
if(item.attr('view')=='topitem'){return;}
$('#'+item.attr('topparent')).removeClass('current');var itemPar=$('#'+item.attr('parent'));if($(".groupImg",itemPar).attr('src')==Runner.pages.constants.PLUS_GIF){itemPar.addClass('current');if(itemPar.attr('view')!='topitem'){this.afterOpenMenuOnLoad(itemPar);}}}});Runner.menu.QuickJumpNew=Runner.extend(Runner.emptyFn,{selectCurrent:-1,init:function(){var menuObj=this;$(".rnr-quickjump:first").prop("initialized","true");$(".rnr-quickjump").focus(function(){menuObj.selectCurrent=this.selectedIndex;}).change(function(){if(this.options[this.selectedIndex].value){if($(this.options[this.selectedIndex]).attr('link')=='External'){window.open(this.options[this.selectedIndex].value);return;}
window.location.href=this.options[this.selectedIndex].value;return;}
this.selectedIndex=menuObj.selectCurrent;});}});Runner.menu.SimpleVmenuNew=Runner.extend(Runner.menu.Manager,{menuContainer:{},init:function(jQmenuElem){this.setMenuObject(jQmenuElem);this.bindHoverOnItems();this.bindClickOnItems();this.setRaquoToTopItems();this.setRaquoToSubItems();},setMenuObject:function(jQmenuElem){this.menuContainer=jQmenuElem;},bindHoverOnItems:function(){$('.current',this.menuContainer).attr('data-current',1);$("li",this.menuContainer).hover(function(){$(this).parentsUntil(".rnr-b-vmenu.simple",".rnr-b-vmenu.simple li").addClass("expanded").removeClass("current");},function(){var $items=$(this).parent().closest('.rnr-b-vmenu.simple li').removeClass("expanded");$items.filter("[data-current=1]").addClass("current");});},bindClickOnItems:function(){$('li',this.menuContainer).on('click',this.itemClickHandler).on('touchend',function(){$(this).trigger('click');});},setRaquoToTopItems:function(){var curTopItem=this.menuContainer.children(':has(ul:has(li.current))'),title=this.menuContainer.find("li.current:last").find("a:first").attr('itemtitle'),currentSubitemText="<b class='subcur'>&nbsp;&raquo;&nbsp;"+title+"&nbsp;</b>",raquo='<b class="raquo">&raquo;</b>',margin=Runner.isDirRTL()?"margin-left":"margin-right";this.menuContainer.children('*:has(ul:has(li))').find('a:first').each(function(index,elem){var $elem=$(elem),$rightMostElem=$elem;if($elem.siblings('b').length){return;}
if($elem.closest(curTopItem).length){$rightMostElem=$(currentSubitemText).insertAfter($elem);if(!$rightMostElem.is(":visible")){$rightMostElem=$elem;}}
$elem.parent().on('touchstart'+(navigator.msMaxTouchPoints?' pointerover':''),function(){var $groups=$elem.parents('.Group'),$groups=$groups.length?$groups:$elem.parents('.menuGroup'),$currentGroup=$groups.eq(0),toggler=!$currentGroup.hasClass('touchHover');$groups.addClass('touchHover');$currentGroup.toggleClass('touchHover',toggler);}).prepend(raquo);$rightMostElem.css(margin,"1em");});},setRaquoToSubItems:function(){var raquo='<b class="raquo">&raquo;</b>',margin=Runner.isDirRTL()?"margin-left":"margin-right";;$('ul li:has(ul:has(li))',this.menuContainer).find('a:first').each(function(index,elem){var $elem=$(elem);if($elem.siblings('b').length){return;}
$elem.css(margin,Runner.isIE?"1em":"0.2em")
$elem.parent().on('touchstart'+(navigator.msMaxTouchPoints?' pointerover':''),function(){var $groups=$elem.parents('.Group'),$groups=$groups.length?$groups:$elem.parents('.menuGroup'),$currentGroup=$groups.eq(0),toggler=!$currentGroup.hasClass('touchHover');$groups.addClass('touchHover');$currentGroup.toggleClass('touchHover',toggler);}).prepend(raquo);});}});Runner.menu.HorizontalNew=Runner.extend(Runner.menu.Manager,{menuContainer:{},init:function(jQmenuContainer){this.setMenuObject(jQmenuContainer);this.bindHoverOnItems();this.bindClickOnItems();this.setRaquoToTopItems();this.setRaquoToSubItems();},setMenuObject:function(jQmenuContainer){this.menuContainer=jQmenuContainer;},bindHoverOnItems:function(){$('.current',this.menuContainer).attr('data-current',1);$('.rnr-b-hmenu, .rnr-b-hmenu li',this.menuContainer).hover(function(){$(this).parentsUntil(".rnr-ch",".rnr-b-hmenu li, .rnr-b-hmenu").addClass("expanded").removeClass("current");},function(){var $items=$(this).parent().closest('.rnr-b-hmenu li, .rnr-b-hmenu').removeClass("expanded");$items.filter("[data-current=1]").addClass("current");});},bindClickOnItems:function(){$('.rnr-b-hmenu li, .rnr-b-hmenu > div:has(a[id^="itemlink"])',this.menuContainer).on('click',this.itemClickHandler).on('touchend',function(){$(this).trigger('click');});},setRaquoToTopItems:Runner.menu.SimpleVmenuNew.prototype.setRaquoToTopItems,setRaquoToSubItems:Runner.menu.SimpleVmenuNew.prototype.setRaquoToSubItems});Runner.menu.TreeLikeVmenuNew=Runner.extend(Runner.menu.Manager,{menuContainer:{},menuName:"",initialized:false,allExpanded:false,init:function(jQmenuElem){this.setMenuObject(jQmenuElem);this.bindClickOnItems();this.initSubItems();this.bindShowHideGroupClick();this.bindExpandAllClick();this.openMenuOnLoad();this.toggleExpandCollapse();this.initialized=true;},setMenuObject:function(jQmenuElem){this.menuContainer=jQmenuElem;this.menuName=jQmenuElem.data('menuname');},bindClickOnItems:function(){$('.menuLeaf',this.menuContainer).on('click',this.itemClickHandler);},initSubItems:function(){var subItems=this.menuContainer.children('.subitem');subItems.addClass('rnr-hiddenelem').on('click',this.itemClickHandler);},getItemLevel:function(item){return parseInt($(item).attr("level"),10);},getCurrentElements:function(){return this.menuContainer.children('.current');},hideGroup:function(item){var childItems=this.getChildItems(item),menuObj=this;if(!childItems.length){return;}
if(this.initialized){childItems.filter(":not([level=1])").slideUp(100,function(){menuObj.toggleExpandCollapse();});}else{childItems.filter(":not([level=1])").hide();}
childItems.each(function(){menuObj.hideGroup(this);});this.removeFromCookie($(item).attr('id'));$(".groupImg",item).attr('src',Runner.pages.constants.PLUS_GIF);},showGroup:function(item){var childItems=this.getChildItems(item),menuObj=this;if(childItems.length){if(this.initialized){childItems.slideDown(100,function(){menuObj.toggleExpandCollapse();});}else{childItems.show();}
this.addToCookie($(item).attr('id'));$(".groupImg",item).attr('src',Runner.pages.constants.MINUS_GIF);}},setCurrentItemStyle:function(){var $items=this.getCurrentElements();$('.current',this.menuContainer).removeClass('current');while($items.length){$items.each(function(itemId,item){var $grCtrl=$('.groupImg',item);if(!$grCtrl.length||$grCtrl.attr('src')!==Runner.pages.constants.MINUS_GIF){$(item).addClass('current');}});if($items.is(':visible')){break;}
$items=this.getParentItem($items);}},bindShowHideGroupClick:function(){var menuObj=this;$('.groupImg',this.menuContainer).closest('li').click(function(e){var target=$(e.target),liElement,show;if(target.is('a')&&target.href&&target.href!=="#"){return;}
liElement=$(this);show=$('.groupImg',this).attr('src')===Runner.pages.constants.PLUS_GIF;show?menuObj.showGroup(liElement):menuObj.hideGroup(liElement);menuObj.setCurrentItemStyle();return false;});},getParentItem:function(item){var level=this.getItemLevel(item);return $(item).prevUntil("[level="+(level-1)+"]").add(item).first().prev();},getChildItems:function(item){var level=this.getItemLevel(item);if(isNaN(level)){return this.menuContainer.children("[level=1]");}
return $(item).nextUntil("[level="+level+"]","[level="+(level+1)+"]");},bindExpandAllClick:function(){var menuObj=this;$(".manage",this.menuContainer).click(function(){if(menuObj.allExpanded){menuObj.hideGroup();delete_cookie('openMenuGroupIds_'+menuObj.menuName,menuObj.cookieRoot,'');}else{menuObj.menuContainer.children('[level]').each(function(){menuObj.showGroup(this);});}
return false;});},addToCookie:function(menuGroupId){var key='openMenuGroupIds_'+this.menuName,openMenuGroupIds=get_cookie(key);if(openMenuGroupIds&&openMenuGroupIds.indexOf(menuGroupId)===-1){openMenuGroupIds+=";"+menuGroupId;}
set_cookie(key,openMenuGroupIds||menuGroupId,'',this.cookieRoot);},removeFromCookie:function(menuGroupId){var key='openMenuGroupIds_'+this.menuName,openMenuGroupIds=get_cookie(key);if(!openMenuGroupIds){return;}
openMenuGroupIds=openMenuGroupIds.replace(";"+menuGroupId,"");openMenuGroupIds=openMenuGroupIds.replace(menuGroupId,"");if(openMenuGroupIds.indexOf(';')===0){openMenuGroupIds=openMenuGroupIds.substr(1);}
set_cookie(key,openMenuGroupIds,'',this.cookieRoot);},toggleExpandCollapse:function(){var menuContainer=this.menuContainer,manageBlock=menuContainer.children('.manage'),hiddenSubItems=$(".subitem:hidden",menuContainer),src;this.allExpanded=!hiddenSubItems.length;src=this.allExpanded?Runner.pages.constants.MINUS_GIF:Runner.pages.constants.PLUS_GIF;$('.expand',manageBlock).toggle(!this.allExpanded);$('.hide',manageBlock).toggle(this.allExpanded);$('img',manageBlock).attr('src',src);this.setCurrentItemStyle();},openMenuOnLoad:function(){var openMenuGroupIds,groupForOpenArr,i;this.cookieRoot=Runner.getCookieRoot();openMenuGroupIds=get_cookie('openMenuGroupIds_'+this.menuName);if(!openMenuGroupIds){return;}
groupForOpenArr=openMenuGroupIds.split(";");for(i=0;i<groupForOpenArr.length;i++){if(groupForOpenArr[i].indexOf('item')!==-1){$('#'+groupForOpenArr[i]+' .groupImg',this.menuContainer).click();}};}});Runner.controls.constants={FORMAT_NONE:'',FORMAT_DATE_SHORT:"Short Date",FORMAT_DATE_LONG:"Long Date",FORMAT_DATE_TIME:"Datetime",FORMAT_TIME:"Time",FORMAT_CURRENCY:"Currency",FORMAT_PERCENT:"Percent",FORMAT_HYPERLINK:"Hyperlink",FORMAT_EMAILHYPERLINK:"Email Hyperlink",FORMAT_FILE_IMAGE:"File-based Image",FORMAT_DATABASE_IMAGE:"Database Image",FORMAT_DATABASE_FILE:"Database File",FORMAT_FILE:"Document Download",FORMAT_LOOKUP_WIZARD:"Lookup wizard",FORMAT_PHONE_NUMBER:"Phone Number",FORMAT_NUMBER:"Number",FORMAT_HTML:"HTML",FORMAT_CHECKBOX:"Checkbox",FORMAT_MAP:"Map",FORMAT_CUSTOM:"Custom",EDIT_FORMAT_NONE:"",EDIT_FORMAT_TEXT_FIELD:"Text field",EDIT_FORMAT_TEXT_AREA:"Text area",EDIT_FORMAT_RTE:"RTE",EDIT_FORMAT_RTEINNOVA:"RTEINNOVA",EDIT_FORMAT_RTECK:"RTECK",EDIT_FORMAT_PASSWORD:"Password",EDIT_FORMAT_DATE:"Date",EDIT_DATE_SIMPLE:0,EDIT_DATE_SIMPLE_INLINE:2,EDIT_DATE_SIMPLE_DP:11,EDIT_DATE_DD:12,EDIT_DATE_DD_INLINE:5,EDIT_DATE_DD_DP:13,EDIT_FORMAT_TIME:"Time",EDIT_FORMAT_RADIO:"Radio button",EDIT_FORMAT_CHECKBOX:"Checkbox",EDIT_FORMAT_DATABASE_IMAGE:"Database image",EDIT_FORMAT_DATABASE_FILE:"Database file",EDIT_FORMAT_FILE:"Document upload",EDIT_FORMAT_LOOKUP_WIZARD:"Lookup wizard",EDIT_FORMAT_HIDDEN:"Hidden field",EDIT_FORMAT_READONLY:"Readonly",LCT_DROPDOWN:0,LCT_AJAX:1,LCT_LIST:2,LCT_CBLIST:3,LCT_RADIO:4,LT_LISTOFVALUES:0,LT_LOOKUPTABLE:1,LT_CUSTOM:2,MODE_ADD:0,MODE_EDIT:1,MODE_SEARCH:2,MODE_LIST:3,MODE_PRINT:4,MODE_VIEW:5,MODE_INLINE_ADD:6,MODE_INLINE_EDIT:7,MODE_EXPORT:8,FILTER_FORMAT_VALUES_LIST:"Values list",FILTER_FORMAT_BOOLEAN:"Options list",FILTER_FORMAT_INTERVAL_LIST:"Interval list",FILTER_FORMAT_INTERVAL_SLIDER:"Interval slider",FILTER_MULTISELECT_NONE:0,FILTER_MULTISELECT_ON_DEMAND:1,FILTER_MULTISELECT_ALWAYS:2,FILTER_KNOBS_BOTH:0,FILTER_KNOBS_MIN_ONLY:1,FILTER_KNOBS_MAX_ONLY:2,FILTER_STEP_SEC:0,FILTER_STEP_MIN:1,FILTER_STEP_HOUR:2,FILTER_STEP_DAY:3,FILTER_STEP_MONTH:4,FILTER_STEP_YEAR:5,GOOGLE_MAPS:0,OPEN_STREET_MAPS:1,BING_MAPS:2};Runner.Event=Runner.extend(Runner.emptyFn,{events:null,listeners:null,elemsForEvent:null,suspendedEvents:null,eventsAreInitialized:false,constructor:function(){this.listeners=[];this.elemsForEvent=[];this.suspendedEvents=[];},init:function(){if(!this.events.length){return;}
var i,eventName;for(i=0;i<this.events.length;i++){eventName=this.events[i];if(typeof this[eventName]=="function"){this.on(eventName,this[eventName]);}else if(typeof this[eventName]=="object"){this.on(eventName,this[eventName].fn,this[eventName].options,this[eventName].scope);}}
this.eventsAreInitialized=true;},suspendEvent:function(eventArr){for(var i=0;i<eventArr.length;i++){if($.inArray(eventArr[i],this.suspendedEvents)===-1){this.suspendedEvents.push(eventArr[i]);}}},resumeEvent:function(eventArr){var eventInd,i;for(i=0;i<eventArr.length;i++){eventInd=$.inArray(eventArr[i],this.suspendedEvents);if(eventInd!==-1){this.suspendedEvents.splice(eventInd,1);}}},createDelayed:function(handler,timeout){return function(){var obj=this,args=arguments;setTimeout(function(){handler.apply(obj,args);},timeout||10);};},createBuffered:function(handler,buffer){var task=new Runner.util.DelayedTask(handler);return function(){task.delay(buffer,handler,null,Array.prototype.slice.call(arguments));};},createSingle:function(handler,eventName){var eventObj=this,singleHandler=function(){handler.apply(eventObj,arguments);eventObj.clearEventHandler(eventName,singleHandler);};return singleHandler},bindHn:function(eventName,callHandler){if(!callHandler||!eventName){return;}
for(var i=0;i<this.elemsForEvent.length;i++){$(this.elemsForEvent[i]).bind(eventName,{hn:callHandler,obj:this},callHandler);}},unbindHn:function(eventName,callHandler){if(!callHandler||!eventName){return;}
for(var i=0;i<this.elemsForEvent.length;i++){$(this.elemsForEvent[i]).unbind(eventName,callHandler);}},on:function(eventName,fn,options,scope){if(!this.elemsForEvent.length||!fn){return false;}
eventName=eventName.toLowerCase();this.addEvent([eventName]);if(eventName.indexOf("on")===0){eventName=eventName.slice(2);}
var callHandler,scope=scope||this,objScope=this,options=options||{},args=options.args||[],single=options.single||false,timeout=options.timeout||0,buffer=options.buffer||0;callHandler=function(e){if($.inArray(eventName,objScope.suspendedEvents)!==-1){return;}
var newArgs=Array.prototype.slice.call(arguments);fn.apply(scope,newArgs.slice(0,1).concat(args).concat(newArgs.slice(1)));}
if(timeout){callHandler=this.createDelayed(callHandler,timeout);}
if(single){callHandler=this.createSingle(callHandler,eventName)}
if(buffer){callHandler=this.createBuffered(callHandler,buffer);}
this.listeners.push({name:eventName,handler:fn,callHandler:callHandler,options:options,scope:scope,index:this.listeners.length});this.bindHn(eventName,callHandler);return true;},addEvent:function(eventNameArr){this.events=this.events||[];this.addEvent=function(eventNameArr){for(var i=0;i<eventNameArr.length;i++){if($.inArray(eventNameArr[i],this.events)===-1){this.events.push(eventNameArr[i]);}}}
this.addEvent(eventNameArr);},killEvent:function(eventName){var eventInd=$.inArray(eventName,this.events)
if(eventInd===-1){return;}
this.clearEvent(eventName);this.unbindHn(eventName,this[eventName]);delete this[eventName];this.events.splice(eventInd,1);},purgeListeners:function(){if(!this.events){return;}
var copyEvents=this.events.slice(0),i;for(i=0;i<copyEvents.length;i++){this.killEvent(copyEvents[i]);}},clearEvent:function(eventName){for(var i=this.listeners.length;i--;){if(this.listeners[i].name==eventName){this.unbindHn(eventName,this.listeners[i].callHandler);this.listeners.splice(i,1);}}},clearEventHandler:function(eventName,callHandler){for(var i=this.listeners.length;i--;){if(this.listeners[i].name==eventName&&this.listeners[i].callHandler===callHandler){this.unbindHn(eventName,callHandler);this.listeners.splice(i,1);}}},stopEvent:function(e){this.stopPropagation(e);this.preventDefault(e);},stopPropagation:function(e){e=this.getEvent(e);if(e&&e.stopPropagation){e.stopPropagation();}else if(e){e.cancelBubble=true;}},preventDefault:function(e){e=this.getEvent(e);if(e&&e.preventDefault){e.preventDefault();}else if(e){e.returnValue=false;}},getEvent:function(e){return e||window.event;},getTarget:function(e){if(e){return e.target||e.srcElement;}},fireEvent:function(eventName){var listeners=this.getListeners(eventName);for(var i=0;i<listeners.length;i++){listeners[i].callHandler.apply(this,[null].concat(Array.prototype.slice.call(arguments,1)));}},getListeners:function(eventName){var listeneresArr=[];for(var i=0;i<this.listeners.length;i++){if(this.listeners[i].name==eventName){listeneresArr.push(this.listeners[i]);}}
return listeneresArr;}});Runner.validation={validatorConsts:{predefined:1,user:2,notFound:3,userNew:4},userValidators:[],newUserValidators:{},predefinedValidatorsArr:['isrequired','isnumeric','ispassword','isemail','ismoney','iszipcode','isphonenumber','isstate','isssn','iscc','istime','regexp','denyduplicated','checkstrongpassword'],arrStates:['AL','AK','AS','AZ','AR','CA','CO','CT','DE','DC','FM','FL','GA','GU','HI','ID','IL','IN','IA','KS','KY','LA','ME','MH','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','MP','OH','OK','OR','PW','PA','PR','RI','SC','SD','TN','TX','UT','VT','VI','VA','WA','WV','WI','WY'],control:{},validate:function(validArr,control){var validationRes,validatorName,validatorType,i,result=this.getTrueValidationResult(validArr);this.control=control;for(i=0;i<validArr.length;i++){if(!validArr[i]){continue;}
validatorName=validArr[i];validatorType=this.getValidatorType(validatorName);switch(validatorType){case this.validatorConsts.predefined:validationRes=this[validatorName](control.getStringValue());break;case this.validatorConsts.user:validatorName=control.validationArr[i];validationRes=window[validatorName](control.getStringValue());break;case this.validatorConsts.userNew:validatorName=control.validationArr[i];validationRes=this.newUserValidators[validatorName].validate(control.getStringValue(),control);if(validationRes===false){validationRes=this.newUserValidators[validatorName].message;}
break;default:validationRes=true;};this.updateResultObject(validationRes,validatorName,result);}
return result;},getTrueValidationResult:function(validArr){return{result:true,messagesData:{},delayedValidators:this.getDelayedValidators(validArr)};},getDelayedValidators:function(validArr){if($.inArray("DenyDuplicated",validArr)===-1){return[];}
return["DenyDuplicated"];},getValidatorType:function(validatorName){var userValidatorType;if($.inArray(validatorName.toString().toLowerCase(),this.predefinedValidatorsArr)!==-1){return this.validatorConsts.predefined;}
if(typeof this.newUserValidators[validatorName]!="undefined"){return this.validatorConsts.userNew;}
userValidatorType=typeof window[validatorName];if(userValidatorType==='function'||userValidatorType==='object'&&Runner.isIE){return this.validatorConsts.user;}
return this.validatorConsts.notFound;},extractValidationMessage:function(validatorName,messagesData){if(!messagesData[validatorName]){return""}
return messagesData[validatorName].join("<br>");},updateResultObject:function(res,validatorName,resultObj){if(res===true){return;}
var messages=[];resultObj.result=false;if(Runner.isArray(res)){for(var i=0;i<res.length;i++){messages.push(res[i]);}}else{messages.push(res);}
resultObj.messagesData[validatorName]=messages;},registerCustomValidation:function(ctrl){var validatorType,i;for(i=0;i<ctrl.validationArr.length;i++){if(!ctrl.validationArr[i]){continue;}
validatorType=this.getValidatorType(ctrl.validationArr[i]);if(validatorType===this.validatorConsts.predefined){continue;}
if($.inArray(ctrl.validationArr[i],this.userValidators)===-1){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/validate/'+ctrl.validationArr[i]+'.js']);Runner.util.ScriptLoader.load();this.userValidators.push(ctrl.validationArr[i]);}}},"IsRequired":function(){if(this.control.isEmpty()){return Runner.lang.constants.TEXT_INLINE_FIELD_REQUIRED;}
return true;},"IsNumeric":function(sVal){sVal=sVal.replace(/,/g,"");if(isNaN(sVal)){return Runner.lang.constants.TEXT_INLINE_FIELD_NUMBER;}
return true;},"IsPassword":function(sVal){var regexp1=/^password$/,regexp2=/.{4,}/;if(sVal.match(regexp1)){return Runner.lang.constants.TEXT_INLINE_FIELD_PASSWORD1;}
if(!sVal.match(regexp2)){return Runner.lang.constants.TEXT_INLINE_FIELD_PASSWORD2;}
return true;},"IsEmail":function(sVal){var regexp=/^[^\@\.\s][^\@]*\@[-\w]+(\.[\w-]+)*$/;if(sVal.match(/.+/)&&!sVal.match(regexp)){return Runner.lang.constants.TEXT_INLINE_FIELD_EMAIL;}
return true;},"IsMoney":function(sVal){var regexp=/^(\d*)[.,]?(\d*)$/;if(sVal.match(/.+/)&&!sVal.match(regexp)){return Runner.lang.constants.TEXT_INLINE_FIELD_CURRENCY;}
return true;},"IsZipCode":function(sVal){var regexp=/^\d{5}([\-]\d{4})?$/;if(sVal.match(/.+/)&&!sVal.match(regexp)){return Runner.lang.constants.TEXT_INLINE_FIELD_ZIPCODE;}
return true;},"IsPhoneNumber":function(sVal){var regexp=/^\(\d{3}\)\s?\d{3}\-\d{4}$/,stripped=sVal.replace(/[\(\)\.\-\ ]/g,'');if(sVal.match(/.+/)&&(isNaN(parseInt(stripped))||stripped.length!=10)){return Runner.lang.constants.TEXT_INLINE_FIELD_PHONE;}
return true;},"IsState":function(sVal){if(sVal.match(/.+/)&&$.inArray(sVal,this.arrStates)===-1){return Runner.lang.constants.TEXT_INLINE_FIELD_STATE;}
return true;},"IsSSN":function(sVal){var regexp=/^\d{3}(-|\s)\d{2}(-|\s)\d{4}$/;if(sVal.match(/.+/)&&!sVal.match(regexp)){return Runner.lang.constants.TEXT_INLINE_FIELD_SSN;}
return true;},"IsCC":function(sVal){var regexp=/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/;if(sVal.match(/.+/)&&!sVal.match(regexp)){return Runner.lang.constants.TEXT_INLINE_FIELD_CC;}
return true;},"IsTime":function(sVal){if(sVal===""){return true;}
var common24Rgxp=/^(?:[0-1]?[0-9]|2[0-3])(?::[0-5][0-9](?::[0-5][0-9])?)?$/,common12Rgxp=/^(?:1[0-2]|0?[1-9])(?::[0-5][0-9](?::[0-5][0-9])?)?[\s]{0,2}(?:am|pm)?$/i,localTimeRgxp;sVal=sVal.trim();if(common24Rgxp.test(sVal)||common12Rgxp.test(sVal)){return true;}
localTimeRgxp=new RegExp(this.control.regExp,"i");if(localTimeRgxp.test(sVal)){return true;}
return Runner.lang.constants.TEXT_INLINE_FIELD_TIME;},"RegExp":function(sVal){if(sVal===""){return true;}
var re=new RegExp(this.control.regExp),regExpMessageData=this.control.customValidationFailedMessages["RegExp"];if(!re.test(sVal)||re.exec(sVal)[0]!=sVal){if(regExpMessageData.messageType==='Text'){return regExpMessageData.message;}
return Runner.getCustomLabel(regExpMessageData.message);}
return true;},"DenyDuplicated":function(sVal){var control=this.control,pageObj=Runner.pages.PageManager.getAt(control.table,control.id),defaultValue=control.getDefaultControlValue(),strValue,messageData,ajaxParams;if(control.isEmpty()||control.pageType===Runner.pages.constants.PAGE_EDIT&&sVal===defaultValue){if(pageObj){pageObj.fireEvent("ddValidationResolved",control.fieldName,false);}
return true;}
strValue=control.getStringValue();messageData=control.customValidationFailedMessages["DenyDuplicated"];control.isInvalid=false;ajaxParams={tableName:control.shortTableName,pageType:control.pageType,fieldName:control.fieldName,fieldControlType:control.ctrlType,value:sVal};Runner.runnerAJAX(Runner.getPageUrl("checkduplicates"),ajaxParams,function(respObj){var message;if(!respObj.success){return;}
if(pageObj){pageObj.fireEvent("ddValidationResolved",control.fieldName,respObj.hasDuplicates);}
if(!respObj.hasDuplicates){if(!control.isInvalid){control.clearInvalid();}
return;}
message=messageData.messageType==='Text'?messageData.message:Runner.getCustomLabel(messageData.message);message=message.replace('%value%',strValue.slice(0,100));control.markInvalidWidthCusttomMessages("DenyDuplicated",[message]);if(control.isFocusAllowed()&&!control.isSetFocus&&Runner.pages.RunnerPage.prototype.isFirstInvalidControl(control)){control.setFocus();}});return true;},"CheckStrongPassword":function(sVal){this.control.clearInvalid();if(!sVal.length){return true;}
var messages=[],pwdLen=Runner.pages.PageSettings.getGlobalData("pwdLen"),pwdUnique=Runner.pages.PageSettings.getGlobalData("pwdUnique"),pwdDigits=Runner.pages.PageSettings.getGlobalData("pwdDigits"),pwdUpperLower=Runner.pages.PageSettings.getGlobalData("pwdUpperLower");if(pwdLen&&sVal.length<pwdLen){messages.push(Runner.lang.constants.SEC_PWD_LEN.replace('%%',pwdLen));}
if(pwdUnique){var cUnique={},countUnique=0;for(var i=0;i<sVal.length;i++){cUnique[sVal[i]]=1;}
for(var c in cUnique){countUnique++;}
if(countUnique<pwdUnique){messages.push(Runner.lang.constants.SEC_PWD_UNIQUE.replace('%%',pwdUnique));}}
if(pwdDigits){var regExpDigit=/(\d)|([^A-Za-z0-9])/g,result=sVal.match(regExpDigit);if(!result||result.length<pwdDigits){messages.push(Runner.lang.constants.SEC_PWD_DIGIT.replace('%%',pwdDigits));}}
if(pwdUpperLower){var regExpLower=/([a-z])/g,regExpUpper=/([A-Z])/g;if((!sVal.match(regExpLower)||!sVal.match(regExpUpper))&&pwdUpperLower){messages.push(Runner.lang.constants.SEC_PWD_CASE);}}
if(messages.length){return messages;}
return true;},addUserValidator:function(params){this.newUserValidators[params.name]=params;}}
Runner.controls.ControlManager=function(){return{register:function(control){if(!control){return false;}
return Runner.controls.ControlStorage.register(control.id,control.table,control.fieldName,control.ctrlInd,control);},getAt:function(tName,rowId,fName,ctrlInd){if(typeof fName=="undefined"||fName===false){if(!rowId){return Runner.controls.ControlStorage.byTable(tName);}
return Runner.controls.ControlStorage.byId(rowId);}
ctrlInd=ctrlInd||0;return Runner.controls.ControlStorage.byAll(rowId,fName,ctrlInd||0);},};}();Runner.controls.ControlStorage=(function(){var idxMain={},idxIdField={},idxIdFIELD={},idxTableId={};return{register:function(id,table,field,ctrlInd,control){idxMain[id]=idxMain[id]||{};idxMain[id][field]=idxMain[id][field]||{};idxMain[id][field][ctrlInd]=control;idxTableId[table]=idxTableId[table]||{};idxTableId[table][id]=idxMain[id];if(!ctrlInd){idxIdField[id]=idxIdField[id]||{};idxIdField[id][field]=control;idxIdFIELD[id]=idxIdFIELD[id]||{};idxIdFIELD[id][field.toUpperCase()]=control;}},unregister:function(id,field,ctrlInd){var control=this.byAll(id,field,ctrlInd);if(!control){console.log('error deleting control');return;}
if(typeof control.destructor==="function"){control.destructor();}
delete idxMain[id][field][ctrlInd];if(0==ctrlInd){delete idxIdField[id][field];delete idxIdFIELD[id][field.toUpperCase()];}},unregisterById:function(id){var field,ctrlInd,controls=[],objField;for(field in idxMain[id]){objField=idxMain[id][field];for(ctrlInd in objField)
this.unregister(id,field,ctrlInd);}
delete idxMain[id];return;},byIdField:function(id,field){return(idxIdField[id]||{})[field]||(idxIdFIELD[id]||{})[field.toUpperCase()];},byTable:function(table){var id,field,ctrlInd,controls=[],objId,objField;for(id in idxTableId[table]||{}){objId=idxTableId[table][id];for(field in objId){objField=objId[field];for(ctrlInd in objField)
controls.push(objField[ctrlInd]);}}
return controls;},byId:function(id){var field,ctrlInd,controls=[],objField;for(field in idxMain[id]){objField=idxMain[id][field];for(ctrlInd in objField)
controls.push(objField[ctrlInd]);}
return controls;},byAll:function(id,field,ctrlInd){return((idxMain[id]||{})[field]||{})[ctrlInd];}}})();Runner.namespace('Runner.form');Runner.form.Button=Runner.extend(Runner.Event,{id:"",btnName:"",messageCont:null,elem:null,constructor:function(cfg){Runner.apply(this,cfg);Runner.form.Button.superclass.constructor.call(this,cfg);this.elem=$('#'+this.id);this.elem=this.elem.length?this.elem:$('<input type="button">');this.elemsForEvent=[this.elem.get(0)];},init:function(args){this.on("click",this.clickHandler,args);},setDisabled:function(){if(this.elem.is("input")){this.elem.prop("disabled",true);return;}
this.suspendEvent(['click']);},setEnabled:function(){if(this.elem.is("input")){this.elem.prop("disabled",false);return;}
this.resumeEvent(['click']);},setMessage:function(txt){this.initMessCont();this.setMessage=function(txt){this.messageCont.html(txt);}
this.setMessage(txt);},removeMessage:function(){this.initMessCont();this.removeMessage=function(){this.messageCont.empty();}
this.removeMessage();},initMessCont:function(){if(this.messageCont){return;}
var messContId=this.id+"_messCont";this.messageCont=$('<div id="'+messContId+'"></div>').insertAfter(this.elem);},getRowData:function(pageObj,isInlineAdd){var i,addedRow,$button=this.elem,$row=$button.closest('[id^="gridRow"]'),$cell=$button.closest('[data-record-id]'),rowData={id:-1,keys:[],fields:{}};if($cell.length){rowData.id=$cell.data('record-id');}else{if(!$row.length){return rowData;}
rowData.id=parseInt($row.attr('id').substr(7),10);$row.children().each(function(){if(this.recordId){rowData.id=this.recordId;}
if($button.closest(this).length){return false;}});}
if(rowData.id){if(typeof pageObj.controlsMap.gridRows!=='undefined'&&!isInlineAdd){for(i=0;i<pageObj.controlsMap.gridRows.length;i++){if(pageObj.controlsMap.gridRows[i].id==rowData.id){rowData.keys=pageObj.controlsMap.gridRows[i].keys;break;}}}
if(isInlineAdd){addedRow=pageObj.inlineAdd.getRowById(rowData.id);rowData.keys=addedRow.keys;}
if(typeof pageObj.listFields!=='undefined'){for(i=0;i<pageObj.listFields.length;i++){rowData.fields[pageObj.listFields[i]]=Runner.getFieldSpan(pageObj.listFields[i],rowData.id);}}}
return rowData;},getInlineRow:function(pageObj,rowId){if(pageObj.inlineAdd||pageObj.inlineEdit){return(pageObj.inlineAdd||pageObj.inlineEdit).getRowById(rowId);}
var inlineEdit=new Runner.util.inlineEditing.InlineEdit({id:pageObj.pageId,tName:pageObj.tName,fNames:pageObj.listFields||[],rows:pageObj.controlsMap&&pageObj.controlsMap.gridRows||[]});return inlineEdit.getRowById(rowId);},clickHandler:function(e,pageObj,proxy,pageid,isInlineAdd,inlineAddRow){if(Runner.isDisabledButton(this.elem)){e.preventDefault();e.stopPropagation();return;}
var ctrl=this,rowData=this.getRowData(pageObj,isInlineAdd),params={buttId:this.btnName,rndVal:new Date().getTime(),fieldsData:{},masterData:{},masterTable:pageObj.masterTable||null,},isManyKeys=0,keyObject={},location,res,$checkboxes,i,j,reqParams,row=null,recordControls=[],masterPageObj=null;if(inlineAddRow||rowData.id!==-1){row=new Runner.AjaxRow(inlineAddRow||this.getInlineRow(pageObj,rowData.id));recordControls=Runner.controls.ControlStorage.byId(row.row.id);location="grid";}else if(pageObj.pageType==Runner.pages.constants.PAGE_EDIT||pageObj.pageType==Runner.pages.constants.PAGE_ADD){recordControls=pageObj.getFormControls();}
if(recordControls.length){$.each(recordControls,function(i,control){params.fieldsData[control.fieldName]=control.getValue();});}
if(pageObj.pageMode===Runner.pages.constants.MODE_LIST_DETAILS){masterPageObj=Runner.pages.PageManager.getAt(pageObj.masterTName,pageObj.parId);if(masterPageObj.pageType===Runner.pages.constants.PAGE_ADD||masterPageObj.pageType===Runner.pages.constants.PAGE_EDIT){$.each(masterPageObj.getFormControls(),function(i,control){params.masterData[control.fieldName]=control.getValue();});}}
this.setDisabled();res=pageObj.buttonEventBefore[this.btnName](params,ctrl,pageObj,proxy,pageid,rowData,row);if(res==false){this.setEnabled();e.preventDefault();e.stopPropagation();return;}
if(pageObj.keys){keyObject=pageObj.keys;location=pageObj.pageType;}
else if($('input[type=checkbox][name^=selection]',pageObj.pageCont).length){$checkboxes=$('input[type="checkbox"][id^="check"][name^="selection"]:checked',pageObj.pageCont);if($checkboxes.length){location=pageObj.pageType;isManyKeys=1;j=0;if(rowData.keys.length){keyObject[j++]=rowData.keys.join('&');location='grid';}
$checkboxes.each(function(idx,checkbox){keyObject[j++]=checkbox.value;})}}
if(!isManyKeys&&rowData.keys.length){keyObject=rowData.keys;location='grid';}
reqParams={params:JSON.stringify(params),keys:JSON.stringify(keyObject),isManyKeys:isManyKeys,location:location||""};$.post(Runner.getPageUrl("buttonhandler"),reqParams,function(resp){var result;try{result=JSON.parse(resp);}catch(e){Runner.pages.RunnerPage.prototype.displayGenericAjaxError(resp);}
if(result!==undefined){pageObj.buttonEventAfter[ctrl.btnName](result,ctrl,pageObj,proxy,pageid,rowData,row);ctrl.setEnabled();}});e.preventDefault();e.stopPropagation();}});Runner.AjaxRow=function(inlineRow){this.row=inlineRow;if(!inlineRow){this.row={id:1,gridLayout:""};}}
Runner.AjaxRow.prototype={fieldCell:function(fName){var $span=Runner.getFieldSpan(fName,this.row.id);if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT){return $span.closest("div");}
return $span.closest("[data-field]");},getFieldText:function(fName){var $span=Runner.getFieldSpan(fName,this.row.id);return $span.html();},setFieldText:function(fName,text){var $span=Runner.getFieldSpan(fName,this.row.id);$span.html(text);},getFieldValue:function(fName){if(this.row.rowVals&&typeof this.row.rowVals[fName]!='undefined'){return this.row.rowVals[fName];}
var $span=Runner.getFieldSpan(fName,this.row.id);return $span.attr("val").trim();},setFieldValue:function(fName,value){var $span=Runner.getFieldSpan(fName,this.row.id);$span.attr("val",value);},record:function(){if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){return $(".panel-body","[data-record-id='"+this.row.id+"']");}
return $("[data-record-id='"+this.row.id+"'][data-field]");},getDefaultMessageCell:function(){if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){return this.record();}
return this.record().eq(0);},setMessage:function(message,container){var $messageWrap;if(!container&&this.row.messageContainer){this.row.messageContainer.html(message);return;}
container=container||this.getDefaultMessageCell();$messageWrap=$(".row-message",container);if($messageWrap.length){this.row.messageContainer=$messageWrap.html(message);return;}
if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){this.row.messageContainer=$("<div class='row-message'></div>").html(message).prependTo(container);}else{this.row.messageContainer=$("<span class='row-message'></span>").html(message).appendTo(container);}},getMessage:function(){if(this.row.messageContainer){return this.row.messageContainer.html();}
return"";},id:function(){return this.row.id;},getRowObject:function(){return this.row;}};Runner.controls.ControlFactory=function(baseCfg,pageType,isInline,pageObj){pageType=baseCfg.mode==Runner.controls.constants.MODE_SEARCH?Runner.pages.constants.PAGE_SEARCH:pageType;var tName=pageObj.tName,fName=baseCfg.fieldName,cfg={rowId:baseCfg.id,table:tName,pageObj:pageObj,isInline:isInline,pageType:pageType,goodFieldName:Runner.goodFieldName(baseCfg.fieldName),shortTableName:Runner.pages.PageSettings.getShortTName(tName),editFormat:Runner.pages.PageSettings.getEditFormat(tName,fName,pageType),validation:Runner.pages.PageSettings.getValidations(tName,fName,pageType),ajaxLikeEventsData:Runner.pages.PageSettings.getFieldData(tName,fName,"events",pageType)};cfg=Runner.apply(cfg,baseCfg);switch(cfg.editFormat){case Runner.controls.constants.EDIT_FORMAT_NONE:case Runner.controls.constants.EDIT_FORMAT_PASSWORD:case Runner.controls.constants.EDIT_FORMAT_TEXT_FIELD:cfg.mask=Runner.pages.PageSettings.getFieldData(tName,fName,"mask",pageType);return new Runner.controls.TextField(cfg);case Runner.controls.constants.EDIT_FORMAT_TEXT_AREA:if(cfg.RTEType===undefined){cfg.RTEType=Runner.pages.PageSettings.getFieldData(tName,fName,"RTEType",pageType);}
switch(cfg.RTEType){case Runner.controls.constants.EDIT_FORMAT_RTE:return new Runner.controls.RTEInnova(cfg);case Runner.controls.constants.EDIT_FORMAT_RTEINNOVA:cfg.useRTE="INNOVA";return new Runner.controls.RTEInnova(cfg);case Runner.controls.constants.EDIT_FORMAT_RTECK:return new Runner.controls.RTECK(cfg);default:return new Runner.controls.TextArea(cfg);}
case Runner.controls.constants.EDIT_FORMAT_DATE:if(cfg.dateEditType===undefined){cfg.dateEditType=Runner.pages.PageSettings.getFieldData(tName,fName,"dateEditType",pageType);}
cfg.ctrlType="date"+cfg.dateEditType;switch(cfg.dateEditType){case Runner.controls.constants.EDIT_DATE_SIMPLE_INLINE:cfg.useDatePicker=true;cfg.usejQueryDatePicker=true;return new Runner.controls.DateTextField(cfg);case Runner.controls.constants.EDIT_DATE_SIMPLE_DP:cfg.useDatePicker=true;cfg.useYuiDatePicker=true;return new Runner.controls.DateTextField(cfg);case Runner.controls.constants.EDIT_DATE_DD:return new Runner.controls.DateDropDown(cfg);case Runner.controls.constants.EDIT_DATE_DD_INLINE:cfg.useDatePicker=true;cfg.usejQueryDatePicker=true;return new Runner.controls.DateDropDown(cfg);case Runner.controls.constants.EDIT_DATE_DD_DP:cfg.useDatePicker=true;cfg.useYuiDatePicker=true;return new Runner.controls.DateDropDown(cfg);case Runner.controls.constants.EDIT_DATE_SIMPLE:default:return new Runner.controls.DateTextField(cfg);}
case Runner.controls.constants.EDIT_FORMAT_TIME:return new Runner.controls.TimeField(cfg);case Runner.controls.constants.EDIT_FORMAT_CHECKBOX:if(cfg.mode==Runner.controls.constants.MODE_SEARCH){cfg.ctrlType="checkbox";return new Runner.controls.DropDownLookup(cfg);}
return new Runner.controls.CheckBox(cfg);case Runner.controls.constants.EDIT_FORMAT_DATABASE_IMAGE:return new Runner.controls.ImageField(cfg);case Runner.controls.constants.EDIT_FORMAT_DATABASE_FILE:return new Runner.controls.FileField(cfg);case Runner.controls.constants.EDIT_FORMAT_FILE:if(Runner.pages.PageSettings.getFieldData(tName,fName,"compatibilityMode",pageType)){return new Runner.controls.FileField(cfg);}
cfg.autoUpload=Runner.pages.PageSettings.getFieldData(tName,fName,"autoUpload",pageType);cfg.acceptFileTypes=Runner.pages.PageSettings.getFieldData(tName,fName,"acceptFileTypes",pageType);cfg.maxFileSize=Runner.pages.PageSettings.getFieldData(tName,fName,"maxFileSize",pageType);cfg.maxTotalFilesSize=Runner.pages.PageSettings.getFieldData(tName,fName,"maxTotalFilesSize",pageType);cfg.maxNumberOfFiles=Runner.pages.PageSettings.getFieldData(tName,fName,"maxNumberOfFiles",pageType);return new Runner.controls.MultiUploadField(cfg);case Runner.controls.constants.EDIT_FORMAT_LOOKUP_WIZARD:cfg.lcType=Runner.pages.PageSettings.getLCT(tName,fName,pageType);cfg.lookupTable=Runner.pages.PageSettings.getLookupTable(tName,fName,pageType);cfg.parentFieldNames=Runner.pages.PageSettings.getFieldData(tName,fName,"parentFields",pageType)||[];cfg.linkField=Runner.pages.PageSettings.getFieldData(tName,fName,"linkField",pageType);cfg.dispField=Runner.pages.PageSettings.getFieldData(tName,fName,"dispField",pageType);cfg.multiSelectionAllowed=Runner.pages.PageSettings.getFieldData(tName,fName,"Multiselect",pageType);cfg.isHorizontalLookup=Runner.pages.PageSettings.getFieldData(tName,fName,"HorizontalLookup",pageType);cfg.autoCompleteFields=Runner.pages.PageSettings.getFieldData(tName,fName,"autoCompleteFields",pageType);cfg.masterTName=pageObj.masterTable;cfg.masterTId=pageObj.parId;cfg.mainFields=Runner.pages.PageSettings.getFieldData(tName,fName,"mainFields",pageType)||[];cfg.mainMasterFields=Runner.pages.PageSettings.getFieldData(tName,fName,"mainMasterFields",pageType)||[];switch(cfg.lcType){case Runner.controls.constants.LCT_DROPDOWN:cfg.selectSize=Runner.pages.PageSettings.getLookupSize(tName,fName,pageType);return new Runner.controls.DropDownLookup(cfg);case Runner.controls.constants.LCT_AJAX:cfg.freeInput=Runner.pages.PageSettings.getFieldData(tName,fName,"freeInput",pageType);return new Runner.controls.EditBoxLookup(cfg);case Runner.controls.constants.LCT_LIST:return new Runner.controls.ListPageLookup(cfg);case Runner.controls.constants.LCT_CBLIST:cfg.lcSize=2;return new Runner.controls.CheckBoxLookup(cfg);case Runner.controls.constants.LCT_RADIO:cfg.lcSize=2;return new Runner.controls.RadioControl(cfg);default:throw('Invalid lookup wizard type = '+cfg.lcType+'. Cannot create lookup!');return;};case Runner.controls.constants.EDIT_FORMAT_READONLY:return new Runner.controls.ReadOnly(cfg);default:if(typeof Runner.controls.constants["Edit"+cfg.editFormat]!=="undefined"){return new Runner.controls["Edit"+cfg.editFormat](cfg);}
throw('Invalid control edit format = '+cfg.editFormat+'. Cannot create control!');return;};};Runner.controls.Control=Runner.extend(Runner.Event,{fieldName:"",goodFieldName:"",shortTableName:"",id:"",rowId:"",cached:false,pageType:"",css:"",style:"",valContId:"",valueElem:null,spanContId:"",spanContElem:null,errContId:"",errContainer:null,validationArr:null,defaultValue:null,isClearHappend:false,table:"",regExp:null,ctrlType:"",showStatus:true,ctrlInd:-1,isSetFocus:false,hidden:false,hiddenByField:false,mode:'',isInvalid:false,customValidationFailedMessages:{},dependentCtrls:null,pageObj:null,isInline:false,ajaxLikeEventsData:null,$tooltipContainer:null,constructor:function(cfg){Runner.apply(this,cfg);Runner.controls.Control.superclass.constructor.call(this,cfg);this.initValidationParams(cfg.validation);this.assignBasicElementsIdValues();this.assignValueElem();this.assignSpanContainerElem();this.$tooltipContainer=$('[data-signal-error-for='+this.goodFieldName+this.rowId+'] [data-helpfor='+this.goodFieldName+']');if(cfg.hidden){this.hide();}
this.setDefaultValue();this.dependentCtrls=[];this.addStyle(this.style);this.addClass(this.css);Runner.controls.ControlManager.register(this);this.initCustomEvents();},initValidationParams:function(validationParams){this.validationArr=validationParams.validationArr||[];this.customValidationFailedMessages=validationParams.customMessages||{}
this.regExp=validationParams.regExp;Runner.validation.registerCustomValidation(this);},assignBasicElementsIdValues:function(){this.valContId="value"+(this.ctrlInd||"")+"_"+this.goodFieldName+"_"+this.rowId;this.errContId="errorCont"+this.ctrlInd+"_"+this.valContId;},assignValueElem:function(){this.valueElem=this.valueElem||$("#"+this.valContId);},assignsElemsForEvent:function(){if(this.appearOnPage()&&!this.elemsForEvent.length){this.elemsForEvent=[this.valueElem.get(0)];}},assignListOfEvents:function(){this.addEvent(["click","blur","change","keyup","edited","editing","input"]);},initCustomEvents:function(){this.assignsElemsForEvent();this.assignListOfEvents();Runner.controls.Control.superclass.init.call(this);this.addEditEditingListeners();(this.ajaxLikeEventsData||[]).forEach(function(data,idx){this.on(data.type,function(e,updateContext){if(typeof Runner.pages.fieldsEvents[data.name]==="function"){Runner.pages.fieldsEvents[data.name].call(this,this.pageObj,this.rowId);}});},this);},assignSpanContainerElem:function(){this.spanContId="edit"+this.rowId+"_"+this.goodFieldName+"_"+this.ctrlInd;this.spanContElem=$("#"+this.spanContId);},addEditEditingListeners:function(){this.on("change",function(e,updateContext){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};this.fireEvent("edited",updateContext);this.fireEvent("editing",updateContext);});},"edited":function(nullEvent,updateContext){var valArr=this.getPreparedValidationArray();if(valArr.length){this.validate(valArr);}
this.clearInvalidOnDependences();},getPreparedValidationArray:function(){var valArr=this.validationArr.slice(0),i;if(!this.invalid()){for(i=0;i<valArr.length;i++){if(valArr[i]=="IsRequired"){valArr.splice(i,1);break;}}}
return valArr;},destructor:function(){this.purgeListeners();delete this.dependentCtrls;},unregister:function(){Runner.controls.ControlStorage.unregister(this.rowId,this.fieldName,this.ctrlInd);},initToolTip:function(text,pageObj){if(this.isSearchControl()){return;}
var $toolTipElem=$(this.valueElem);$toolTipElem=$toolTipElem.is(":visible")?$toolTipElem:this.spanContElem;$toolTipElem.addClass('titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:Runner.isFlyPage(pageObj),el:this.getToolTipPositionElem()});this.initToolTip=Runner.emptyFn;},getToolTipPositionElem:function(){return null;},addStyle:function(styleToAdd){if(!styleToAdd||!(this.valueElem instanceof jQuery)){return;}
var stylesArr=styleToAdd.split(';'),i,style,propertyName,value;for(i=0;i<stylesArr.length;i++){style=stylesArr[i].split(":");propertyName=style[0].toString().trim();if(propertyName){value=style[1].toString().trim();this.valueElem.css(propertyName,value);}}},validate:function(valArr){if(!this.appearOnPage()||this.hiddenByField){this.isInvalid=false;return Runner.validation.getTrueValidationResult();}
var validators=valArr||this.validationArr,vRes=Runner.validation.validate(validators,this);if(validators.length){if(!vRes.result){this.markInvalid(validators,vRes.messagesData);}else{this.clearInvalid(vRes.delayedValidators);}}
return vRes;},removeValidation:function(vType){if(typeof vType!=="string"){this.regExp=null;vType="RegExp";}
for(var i=0;i<this.validationArr.length;i++){if(this.validationArr[i]==vType){this.validationArr.splice(i,1);return true;}}
return false;},addValidation:function(vType){if(this.isSearchControl()){return;}
if(typeof vType!="string"){this.regExp=vType;vType="RegExp";}
if(!this.isSetValidation(vType)){this.validationArr.push(vType);}},isSetValidation:function(vType){if(!Runner.validation[vType]){return false;}
for(var i=0;i<this.validationArr.length;i++){if(this.validationArr[i]==vType){return true;}}
return false;},validateAs:function(vType){if(!this.appearOnPage()){this.isInvalid=false;return Runner.validation.getTrueValidationResult();}
Runner.validation.control=this;return Runner.validation[vType](this.getValue());},initErrorCont:function(){var $helpContainer=this.pageObj.isBootstrap()?$('[data-helpfor='+this.goodFieldName+']'):[];if(this.pageObj.isBootstrap()){if(!this.isInline){this.errContainer=$('<strong ></strong>');}else{this.errContainer=$('<span class="help-block"></span>');}}else{this.errContainer=$('<div></div>').addClass('rnr-error-text');}
this.errContainer.attr('id',this.errContId).css('display','none');if($helpContainer.length){this.errContainer.prependTo($helpContainer);}else{this.errContainer.appendTo(this.spanContElem);}
this.initErrorCont=Runner.emptyFn;},markInvalid:function(validators,messagesData){this.initErrorCont();this.markInvalid=function(validators,messagesData){var that=this,obj={};this.pageObj.validateTimer=setTimeout(function(){that.errContainer.show();if(that.pageObj){that.pageObj.adjustHeightAndWidth();}},100);if(this.pageObj.isBootstrap()){$('[data-signal-error-for='+this.goodFieldName+this.rowId+']').toggleClass('has-error',true);}
this.addValidationMessagesToErrorCont(validators,messagesData);this.isInvalid=true;}
this.markInvalid(validators,messagesData);},markInvalidWidthCusttomMessages:function(validatorName,messages){var messagesData={};messagesData[validatorName]=messages;this.markInvalid([validatorName],messagesData);},addValidationMessagesToErrorCont:function(validators,messagesData){var i,message,suffix=this.goodFieldName+"_"+this.rowId;for(i=0;i<validators.length;i++){message=Runner.validation.extractValidationMessage(validators[i],messagesData)
if(message==""&&validators[i]=="DenyDuplicated"){continue;}
this.setValidationMessage(validators[i]+suffix,message);}},setValidationMessage:function(contId,message){var validatorContainer=this.getValidationMessageContainer(contId);validatorContainer.html(message).show();},getValidationMessageContainer:function(contId){var validatorContainer=$("#"+contId,this.errContainer);if(!validatorContainer.length){validatorContainer=$('<div id="'+contId+'"></div>').appendTo(this.errContainer);}
return validatorContainer;},getValidationMessagesContainers:function(){return this.errContainer.children('div');},clearInvalid:function(delayedValidators){this.initErrorCont();this.clearInvalid=function(delayedValidators){this.isInvalid=false;this.hideNotDelayeValidationMessages(delayedValidators||[],this.goodFieldName+"_"+this.rowId);this.updateErrorsContainerVisibility();if(this.pageObj.isBootstrap()){$('[data-signal-error-for='+this.goodFieldName+this.rowId+']').toggleClass('has-error',false);}}
this.clearInvalid();},updateErrorsContainerVisibility:function(){if(!this.errContainer.children("div:visible").length){this.errContainer.hide();}},hideNotDelayeValidationMessages:function(delayedValidators,suffix){var messageConts=this.getValidationMessagesContainers(),i
for(i=0;i<delayedValidators.length;i++){this.getValidationMessageContainer(delayedValidators[i]+suffix).addClass("delayedValidation");}
messageConts.not(".delayedValidation").hide().empty();messageConts.filter(".delayedValidation").removeClass("delayedValidation");},invalid:function(){return this.isInvalid;},scrollToElem:function(elem){var offsetParent=elem.offsetParent(),elemPosition=elem.position(),elemWidth=elem.width(),scrollTo=offsetParent.scrollTop()+elemPosition.top,scrollLeft=offsetParent.scrollLeft()+elemPosition.left+elemWidth-offsetParent.width(),inlineMode=this.mode===Runner.pages.constants.PAGE_INLINE_EDIT||this.mode===Runner.pages.constants.PAGE_INLINE_ADD;if(offsetParent.css("position")==="static"){offsetParent=$("html");scrollTo=elemPosition.top;offsetLeft=offsetParent.scrollLeft()+elemPosition.left+elemWidth-$(window).width();}
if(this.pageType===Runner.pages.constants.PAGE_LIST&&inlineMode){offsetParent.scrollLeft(scrollLeft+5);return;}
offsetParent.scrollTop(scrollTo-5);},reset:function(updContext){this.setValue(this.defaultValue,true,updContext);this.clearInvalid();},clear:function(){this.isClearHappend=true;this.setValue('',false);this.clearInvalid();this.isClearHappend=false;},hide:function(){this.spanContElem.css("display","none");this.showStatus=false;},show:function(){this.spanContElem.css("display","");this.showStatus=true;},toggle:function(visibility){if(visibility){this.show();}else{this.hide();}},toggleHide:function(){this.toggle(!this.showStatus);},getValue:function(){if(this.valueElem instanceof jQuery&&this.valueElem.length){return this.valueElem.val();}
return false;},setDefaultValue:function(){this.defaultValue=this.getValue();},getStringValue:function(){return this.getValue();},setValue:function(val,triggerEvent,updContext){var readOnly=this.isReadonly();if(this.valueElem instanceof jQuery){if(readOnly){this.makeReadWrite();}
this.valueElem.val(val);if(triggerEvent===true){this.fireEvent("change",updContext);}
if(readOnly){this.makeReadonly();}
return true;}
return false;},setDisabled:function(){if(this.valueElem.length){this.valueElem.prop("disabled",true);return true;}
return false;},setEnabled:function(){if(this.valueElem.length){this.valueElem.prop("disabled",false);return true;}
return false;},isFocusAllowed:function(){return!this.hiddenByField;},setFocus:function(triggerEvent){var ctrlElem;this.isSetFocus=false;if(!this.appearOnPage()||this.valueElem.prop('disabled')||!this.showStatus){return;}
ctrlElem=this.valueElem.get(0);if(!this.valueElem.is(":visible")){$captchaBlock=this.valueElem.parents(".captcha_block");if($captchaBlock.length){this.valueElem.attr("type","text");ctrlElem.focus();this.isSetFocus=true;this.valueElem.attr("type","hidden");}
return;}
try{if(ctrlElem!==document.activeElement&&ctrlElem.focus){ctrlElem.focus();this.isSetFocus=true;if(triggerEvent===true){this.fireEvent("focus");}
return false;}}catch(e){}},isEmpty:function(){return this.getValue().toString()==="";},"blur":function(e){this.stopEvent(e);this.isSetFocus=false;},"click":function(e){this.isSetFocus=true;},removeCSS:function(className){this.valueElem.removeClass(className);},removeClass:function(className){if(this.valueElem instanceof jQuery){this.valueElem.removeClass(className);}},addCSS:function(className){if(this.valueElem instanceof jQuery&&className){this.valueElem.addClass(className);}},addClass:function(className){if(this.valueElem instanceof jQuery&&className){this.valueElem.addClass(className);}},getAttr:function(attrName){return this.valueElem.attr(attrName);},getDispElem:function(){return this.valueElem;},getForSubmit:function(){return this.appearOnPage()?[this.valueElem.clone().val(this.valueElem.val())]:[];},makeReadonly:function(){if(!this.appearOnPage()||this.isReadonly()){return false;}
this.readonlyElem=this.valueElem.clone();this.readonlyElem.val(this.valueElem.val());this.readonlyElem.prop({'id':'readonly_'+this.valContId,'name':'readonly_'+this.valContId,'disabled':true,'readonly':true});this.readonlyElem.prependTo(this.spanContElem);this.valueElem.hide();return true;},makeReadWrite:function(){if(!this.appearOnPage()||!this.isReadonly()){return false;}
this.readonlyElem.remove();this.readonlyElem=undefined;this.valueElem.css('display','');return true;},isReadonly:function(){return!!$('#readonly_'+this.valContId).length;},appearOnPage:function(){return!!this.valueElem.length;},getFieldSetting:function(key){return Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,key,this.pageType);},getDisplayValue:function(){return this.getValue();},getDefaultControlValue:function(){return this.defaultValue;},checkDuplicates:function(){if(!this.isSetValidation('DenyDuplicated')){return;}
this.validate(['DenyDuplicated']);},updateAppearance:function(searchOption){},useSearchSuggests:function(){return this.editFormat===Runner.controls.constants.EDIT_FORMAT_TEXT_FIELD;},implySuggests:function(){return this.editFormat===Runner.controls.constants.EDIT_FORMAT_TEXT_FIELD;},setDependencies:function(tName,pageId){},getParentLookupFieldNames:function(){return[];},hasDependencies:function(){return false;},addDependentCtrls:function(ctrlsArr){for(var i=0;i<ctrlsArr.length;i++){this.dependentCtrls.push(ctrlsArr[i]);}},reloadDependentCtrls:function(updContext,e){if(!this.dependentCtrls||!this.dependentCtrls.length){return;}
if(!updContext||typeof updContext!=="object"){updContext={initiator:this.fieldName};}
for(var i=0;i<this.dependentCtrls.length;i++){if(this.dependentCtrls[i]&&updContext.initiator!=this.dependentCtrls[i].fieldName){this.dependentCtrls[i].reload(updContext);}}},clearInvalidOnDependences:function(){if(!this.dependentCtrls){return;}
for(var i=0;i<this.dependentCtrls.length;i++){if(this.dependentCtrls[i]){this.dependentCtrls[i].clearInvalid();}}},isLookupWizard:function(){return false;},isSearchControl:function(){return this.mode===Runner.controls.constants.MODE_SEARCH;},getDispId:function(){var dispElem=this.getDispElem();if(dispElem instanceof jQuery){return dispElem.attr('id');}
jQuery.each(dispElem,function(i,obj){if(obj instanceof jQuery){return obj.attr('id');}});return'';},getPeer:function(fieldName){return Runner.controls.ControlStorage.byIdField(this.rowId,fieldName);},getTooltip:function(){return this.$tooltipContainer.find('.text-muted').html();},setTooltip:function(html){return this.$tooltipContainer.find('.text-muted').html(html);},addTooltip:function(html){return this.$tooltipContainer.find('.text-muted').append($('<div></div>').html(html));},setInvalid:function(message){var validator="userInvalidation"+this.rowId+this.fieldName,messagesObj={};Runner.validation.addUserValidator({name:validator,message:message,validate:function(){return false;}});this.addValidation(validator);messagesObj[validator]=[message];this.markInvalid([validator],messagesObj);},setValid:function(){var validator="userInvalidation"+this.rowId+this.fieldName;this.removeValidation(validator);this.clearInvalid();},deleteOptions:function(){},addOption:function(value,label){},getControlsData:function(){var data={},ctrls;if(this.isInline){ctrls=Runner.controls.ControlStorage.byId(this.rowId);}else{ctrls=this.pageObj.getFormControls();}
ctrls.forEach(function(ctrl,i){data[ctrl.fieldName]=ctrl.getStringValue();});return data;},getParentControlsData:function(){var data={},i,dFieldName,value;if(!this.parentCtrls){return data;}
for(i=0;i<this.parentCtrls.length;i++){dFieldName=this.parentCtrls[i].isLookupWizard()?this.parentCtrls[i].originalField:this.parentCtrls[i].fieldName;value=this.parentCtrls[i].getStringValue();if(this.parentCtrls[i].editFormat=="Checkbox"){value=(value=="on")?"1":"0";}
data[dFieldName]=value;}
return data;},});Runner.controls.MockControlFactory=function(baseCfg,pageType,tName,pageObj){var cfg={id:baseCfg.id,fieldName:baseCfg.fieldName,pageType:pageType,pageObj:pageObj,goodFieldName:Runner.goodFieldName(baseCfg.fieldName),table:tName,shortTableName:Runner.pages.PageSettings.getShortTName(baseCfg.table),ctrlInd:baseCfg.ctrlInd,ajaxLikeEventsData:Runner.pages.PageSettings.getFieldData(tName,baseCfg.fieldName,"events",pageType)};switch(pageType){case Runner.pages.constants.PAGE_VIEW:return new Runner.controls.ViewMockControl(cfg);default:return false;}};Runner.controls.MockControl=Runner.extend(Runner.Event,{id:"",fieldName:"",goodFieldName:"",shortTableName:"",table:"",pageContext:null,pageType:"",ctrlInd:-1,spanContId:"",spanContElem:null,pageObj:null,constructor:function(cfg){var ctrl=this;Runner.apply(this,cfg);Runner.controls.MockControl.superclass.constructor.call(this,cfg);this.assignSpanContainerElem();Runner.controls.ControlManager.register(this);(this.ajaxLikeEventsData||[]).forEach(function(data,idx){this.on(data.type,function(e,updateContext){if(typeof Runner.pages.fieldsEvents[data.name]==="function"){Runner.pages.fieldsEvents[data.name].call(ctrl,ctrl.pageObj,ctrl.id);}});},this);}});Runner.controls.ViewMockControl=Runner.extend(Runner.controls.MockControl,{assignSpanContainerElem:function(){this.spanContId="view"+this.id+"_"+this.goodFieldName;this.spanContElem=$("#"+this.spanContId);},getDispElem:function(){return this.spanContElem;},hide:function(){this.getDispElem().css("display","none");},show:function(){this.getDispElem().css("display","");},getValue:function(){if(this.getDispElem()instanceof jQuery){return this.getDispElem().html();}
return false;},getStringValue:function(){return this.getValue();},setValue:function(val){if(this.getDispElem()instanceof jQuery){this.getDispElem().html(val);return true;}
return false;},clear:function(){return this.setValue("");},addStyle:function(styleToAdd){if(!styleToAdd||!(this.getDispElem()instanceof jQuery)){return;}
var stylesArr=styleToAdd.split(';'),i,style,propertyName,value;for(i=0;i<stylesArr.length;i++){style=stylesArr[i].split(":");propertyName=style[0].toString().trim();if(propertyName){value=style[1].toString().trim();this.getDispElem().css(propertyName,value);}}},addClass:function(className){if(this.getDispElem()instanceof jQuery&&className){this.getDispElem().addClass(className);}},removeClass:function(className){if(this.getDispElem()instanceof jQuery){this.getDispElem().removeClass(className);}},on:function(eventName,call){if(this.getDispElem()instanceof jQuery&&eventName){this.getDispElem().on(eventName,call);}},isFocusAllowed:function(){return false;}});Runner.viewControls.ViewControlFactory=function(baseCfg,pageType,pageContext,pageObject){var cfg={table:pageObject.tName,pageType:pageType,goodFieldName:Runner.goodFieldName(baseCfg.fieldName),pageContext:pageContext,pageObject:pageObject};Runner.apply(cfg,baseCfg);if(typeof Runner.viewControls[cfg.viewFormat]==="function"){return new Runner.viewControls[cfg.viewFormat](cfg);}
throw('Invalid control view format = '+cfg.viewFormat+'. Cannot create control!');};Runner.viewControls.ViewControl=Runner.extend(Runner.emptyFn,{fieldName:"",goodFieldName:"",shortTableName:"",table:"",pageContext:null,pageType:"",constructor:function(cfg){Runner.apply(this,cfg);},init:Runner.emptyFn});Runner.viewControls.ViewVideoField=Runner.extend(Runner.viewControls.ViewControl,{constructor:function(cfg){Runner.viewControls.ViewVideoField.superclass.constructor.call(this,cfg);},init:function(){setTimeout(function(){$("video",this.pageContext).each(function(){var obj=$(this);projekktor(obj,{controls:true,volume:0.5,width:obj.attr("width"),height:obj.attr("height"),playerFlashMP4:Runner.getFullResourcePath('jarisplayer.swf'),playerFlashMP3:Runner.getFullResourcePath('jarisplayer.swf')});});},10);}});Runner.viewControls["Video file"]=Runner.viewControls.ViewVideoField;Runner.viewControls["Database video"]=Runner.viewControls.ViewVideoField;Runner.viewControls.ViewImageField=Runner.extend(Runner.viewControls.ViewControl,{pageObject:null,constructor:function(cfg){Runner.viewControls.ViewImageField.superclass.constructor.call(this,cfg);},init:function(){var ctrl=this,pageObj=this.pageObject,pageContent=this.pageContext,recalculateGridSize=typeof this.pageObject.recalculationGridSize==="function";setTimeout(function(){var hasSliders=false,isRTL=Runner.isDirRTL(),$zoomboxes=$('.zoombox',pageContent),$heightHolderDiv=$('<div></div>').css({display:"inline",width:"1px;"});;if($zoomboxes.length){$zoomboxes.zoombox({theme:'zoombox',opacity:0.8,duration:400,animation:false,gallery:false,autoplay:false});;}
$(".presudoslider",pageContent).each(function(){var $presudoslider=$(this),$bigThumbnailsContainer=$('.big-thumbnails',$presudoslider),$smallThumbnails,$bigThumbnails;if(isRTL){$presudoslider.closest('td').attr('dir','LTR').attr("style","text-align: left !important;");}
if(!$bigThumbnailsContainer.length){$presudoslider.removeClass('presudoslider').addClass('sudoslider').sudoSlider();hasSliders=true;return;}
$bigThumbnails=$bigThumbnailsContainer.find('a');ctrl.initToolTips($bigThumbnails,$bigThumbnailsContainer);$smallThumbnails=$presudoslider.find('ul:first li a').click(function(){var bigThumbnailLink=$(this).attr('href'),activeBigPictureLinkElem=$bigThumbnails.filter('.active'),activeBigPicture=$('img',activeBigPictureLinkElem);$heightHolderDiv.height(activeBigPicture.height()).insertAfter(activeBigPictureLinkElem);activeBigPictureLinkElem.removeClass('active').fadeOut(100,function(){$bigThumbnails.filter('[href="'+bigThumbnailLink+'"]').css('display','inline').addClass('active').fadeIn(200,function(){if(recalculateGridSize){pageObj.recalculationGridSize();}});}).css("display","inline");return false;});$smallThumbnails.parent().addClass("rnr-small-thumbnails").show();if(!$bigThumbnails.hasClass('zoombox')){$bigThumbnails.on("click",function(){return false;});}
$bigThumbnails.filter(':first').addClass('active').show();$presudoslider.removeClass('presudoslider').addClass('presudoslider-disable');});if(pageObj.pageType=='view'&&pageObj.tabsPresented||pageObj.checkIfSectionPresented()){setTimeout(function(){ctrl.resizeSliders(ctrl.pageContext);},100);}
if(recalculateGridSize){pageObj.recalculationGridSize();}},100);},resizeSliders:function(container){$(".sudoslider",container).each(function(){var $sudoDiv=$(this),$image;if($sudoDiv.width()!==0){return;}
$image=$('li img',sudoDiv).eq(0);if(!$image.length){return;}
$sudoDiv.width($image.width());$sudoDiv.height($image.height());$('.prevBtn',$sudoDiv.parent()).hide();});},initToolTips:function($bigThumbnails,$bigThumbnailsContainer){if(!$bigThumbnails.hasClass('zoombox')){return;}
var $bigThumbnailTooltip=$('<span />').text('(+)');if($bigThumbnailsContainer.height()>=28&&$bigThumbnailsContainer.width()>=175){$bigThumbnailTooltip.text('Click here to view full size (+)');}
$bigThumbnails.children('img').after($bigThumbnailTooltip);}});Runner.viewControls["File-based Image"]=Runner.viewControls.ViewImageField;Runner.viewControls.ViewFileField=Runner.extend(Runner.viewControls.ViewControl,{pageObject:null,constructor:function(cfg){Runner.viewControls.ViewFileField.superclass.constructor.call(this,cfg);},init:function(){var self=this;setTimeout(function(){var zoomboxes=$('.zoombox',self.pageContext);if(zoomboxes.length){zoomboxes.zoombox({theme:'zoombox',opacity:0.8,duration:400,animation:false,gallery:false,autoplay:false});}},100);}});Runner.viewControls["Document Download"]=Runner.viewControls.ViewFileField;Runner.viewControls.ViewDatabaseImageField=Runner.extend(Runner.viewControls.ViewControl,{constructor:function(cfg){Runner.viewControls.ViewDatabaseImageField.superclass.constructor.call(this,cfg);},init:function(){var self=this;setTimeout(function(){var zoomboxes=$('.zoombox',self.pageContext);if(zoomboxes.length){zoomboxes.zoombox({theme:'zoombox',opacity:0.8,duration:400,animation:false,gallery:false,autoplay:false});}},100);}});Runner.viewControls["Database Image"]=Runner.viewControls.ViewDatabaseImageField;Runner.viewControls["Old file-based Image"]=Runner.viewControls.ViewDatabaseImageField;Runner.controls.ReadOnly=Runner.extend(Runner.controls.Control,{readonlyElem:null,constructor:function(cfg){Runner.controls.ReadOnly.superclass.constructor.call(this,cfg);if(this.pageType===Runner.pages.constants.PAGE_ADD&&!this.isEmpty()){this.linkField=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"linkField",this.pageType);this.autoCompleteFields=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"autoCompleteFields",this.pageType);this.doAutoCompleteFields();}},assignValueElem:function(){Runner.controls.ReadOnly.superclass.assignValueElem.call(this);this.readonlyElem=$('#readonly_'+this.valContId);if(this.pageType===Runner.pages.constants.PAGE_ADD&&this.value!==''){this.linkField=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"linkField",this.pageType);this.autoCompleteFields=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"autoCompleteFields",this.pageType);this.doAutoCompleteFields();}},initCustomEvents:Runner.emptyFn,validate:function(){return{result:true};},isFocusAllowed:function(){return false;},setFocus:Runner.emptyFn,setValue:function(val,triggerEvent,updContext){Runner.controls.ReadOnly.superclass.setValue.call(this,val,triggerEvent,updContext);this.readonlyElem.empty().html(val);},doAutoCompleteFields:function(){Runner.controls.LookupWizard.prototype.doAutoCompleteFields.call(this);},makeReadonly:Runner.emptyFn,makeReadWrite:Runner.emptyFn});Runner.controls.TextArea=Runner.extend(Runner.controls.Control,{constructor:function(cfg){Runner.controls.TextArea.superclass.constructor.call(this,cfg);},addEditEditingListeners:function(){this.on("change",function(e,updateContext){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};this.fireEvent("edited",updateContext);});this.on("keyup",function(e,updateContext){if(!e||!Runner.isAcceptableKeyCode(e)){return false;}
this.fireEvent("editing",updateContext);},{buffer:300});},"editing":function(nullEvent,updateContext){this.checkDuplicates();this.clearInvalidOnDependences();this.reloadDependentCtrls(updateContext,nullEvent);},getForSubmit:function(){if(!this.appearOnPage()){return[];}
return[this.valueElem.clone().val(this.getValue())];}});Runner.controls.TextField=Runner.extend(Runner.controls.Control,{mask:"",constructor:function(cfg){Runner.controls.TextField.superclass.constructor.call(this,cfg);if(this.isSetValidation('DenyDuplicated')){this.valueElem.attr('autocomplete','off');}
if(this.mask!==""&&this.mask!==false){this.valueElem.mask(this.mask);}},addEditEditingListeners:function(){this.on("change",function(e,updateContext){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};this.fireEvent("edited",updateContext);});this.on("keyup",function(e,updateContext){if(!e||!Runner.isAcceptableKeyCode(e)){return false;}
this.fireEvent("editing",updateContext);},{buffer:300});},"editing":function(nullEvent,updateContext){this.checkDuplicates();this.clearInvalidOnDependences();this.reloadDependentCtrls(updateContext,nullEvent);}});Runner.controls.TimeField=Runner.extend(Runner.controls.Control,{typeHiddId:"",typeHiddElem:null,rangeSec:[],pageType:"",timePmLetter:"PM",timeAmLetter:"AM",timeDelimiter:":",leadingZero:true,constructor:function(cfg){Runner.controls.TimeField.superclass.constructor.call(this,cfg);this.typeHiddId="type_"+this.goodFieldName+"_"+this.rowId;this.typeHiddElem=$("#"+this.typeHiddId);if(this.isSetValidation('DenyDuplicated')){this.valueElem.attr('autocomplete','off');}
this.timePmLetter=Runner.pages.PageSettings.getGlobalData("locale").timePmLetter;this.timeAmLetter=Runner.pages.PageSettings.getGlobalData("locale").timeAmLetter;this.timeDelimiter=Runner.pages.PageSettings.getGlobalData("locale").timeDelimiter;if(Runner.pages.PageSettings.getGlobalData("locale").leadingZero=="1"){this.leadingZero=true;}
this.imgTime=$("#trigger-test-"+this.valContId).css('visibility','visible');this.assignRangeSeconds();this.initTimePicker();},assignRangeSeconds:function(){for(var i=0;i<60;i++){this.rangeSec[i]=i<10?"0"+i:" "+i;}},addEditEditingListeners:function(){var ctrl=this;this.on("change",function(e,updateContext,triggered){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};if(!this.imgTime.length||e===null||triggered){this.fireEvent("edited",updateContext);}});this.on("keyup",function(e){if(!e||!Runner.isAcceptableKeyCode(e)){return false;}
this.fireEvent("editing");});if(this.pageObj.isBootstrap()){this.valueElem.parents(".input-group").on("dp.change",function(e){ctrl.fireEvent("change",null);});}},initBSTimePicker:function(){var ctrl=this,settings=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'timePick',this.pageType),hourFormat,timeFormat,$pickerElem=this.valueElem.parents(".input-group");if($.isEmptyObject(settings)){return;}
hourFormat=settings['convention']==24?'H':'h',hourFormat=this.leadingZero?hourFormat:hourFormat+hourFormat;timeFormat=hourFormat+this.timeDelimiter+'mm';if(settings['showSec']){timeFormat+=this.timeDelimiter+'ss';}
timeFormat+=settings['convention']==12?" a":"";this.imgTime.on("click",function(){ctrl.setCorrectAmPmMoment();});this.setCorrectAmPmMoment();$pickerElem.datetimepicker({showClose:true,format:timeFormat,stepping:settings['minutes']});if(this.isInline||this.pageObj.openMode!=Runner.pages.constants.OPENMODE_PRELOADED){$pickerElem.on("dp.show",function(e){Runner.util.absToFixed($(".bootstrap-datetimepicker-widget",this));});}},setCorrectAmPmMoment:function(){var ctrl=this;moment.updateLocale('en',{meridiem:function(hour,minute,isLowercase){if(hour>=12){return ctrl.timePmLetter||'pm';}
return ctrl.timeAmLetter||'am';},});},initTimePicker:function(){if(this.pageObj.isBootstrap()){this.initBSTimePicker();return;}
var ctrl=this,valueElem=this.valueElem,initializer=function(e){var settings=Runner.pages.PageSettings.getFieldData(ctrl.table,ctrl.fieldName,'timePick',ctrl.pageType),params,picker;params={handle:"#"+ctrl.imgTime.attr("id"),updateLive:false,trigger:'click',convention:settings['convention'],seconds:settings['showSec'],rangeMin:settings['rangeMin'],rangeSec:ctrl.rangeSec};if(settings['convention']==24){params.rangeHour24=[$.range(0,24),[]];params.prefix=[];}
ctrl.imgTime.unbind("click",initializer);valueElem.timepickr(params);picker=valueElem.data('timepickr');valueElem.on('keyup',function(e){if(!Runner.isAcceptableKeyCode(e)){return;}
var val=valueElem.data('timepickr.initialValue');val.h=val.m=val.s="";valueElem.data('timepickr.initialValue',val);picker.hide();}).on('click',function(){var elementOffset=valueElem.offset();picker._dom.menu.css({'left':elementOffset.left+"px",'top':(elementOffset.top+valueElem.outerHeight())+"px"});if(settings['convention']==24){picker._dom.prefix.height(0).trigger('mouseover');}}).click();picker._dom.menu.css('direction','ltr');}
this.imgTime.bind("click",initializer);},destructor:function(){Runner.controls.TimeField.superclass.destructor.call(this);if(typeof this.valueElem.timepickr==="function"){$(".ui-timepickr").remove();this.valueElem.timepickr('destroy');}},getToolTipPositionElem:function(){return this.imgTime;},addValidation:function(type){if(type!="IsRequired"&&type!="DenyDuplicated"||this.mode===Runner.controls.constants.MODE_SEARCH){return;}
Runner.controls.TimeField.superclass.addValidation.call(this,type);},getForSubmit:function(){return[this.valueElem.clone(),this.typeHiddElem.clone()];},setDisabled:function(){if(this.valueElem.length&&this.imgTime){this.valueElem.get(0).disabled=true;this.imgTime.css('visibility','hidden');return true;}
return false;},setEnabled:function(){if(this.valueElem.length){this.valueElem.get(0).disabled=false;if(!Runner.isIE){this.imgTime.css('visibility','visible');}
return true;}
return false;},makeReadonly:function(){Runner.controls.TimeField.superclass.makeReadonly.call(this);this.imgTime.hide();return true;},makeReadWrite:function(){Runner.controls.TimeField.superclass.makeReadWrite.call(this);this.imgTime.show();return true;}});Runner.controls.RTEField=Runner.extend(Runner.controls.Control,{controlElementToDisable:{},disabledContorlElement:{},delayedEventsHandlers:[],iframeElemId:"",iframeElem:null,useRTE:false,constructor:function(cfg){Runner.controls.RTEField.superclass.constructor.call(this,cfg);this.delayedEventsHandlers=[];this.disabledContorlElement={};this.disabledControlElementId="disabledRTE"+this.fieldName+'_'+this.rowId;this.initCustomEvents=Runner.controls.RTEField.superclass.initCustomEvents;},initCustomEvents:Runner.emptyFn,assignValueElem:function(){Runner.controls.RTEField.superclass.assignValueElem.call(this);this.initIframeElem();},initIframeElem:function(){if(!this.iframeElemId){this.iframeElemId=this.valContId;}
if(!this.iframeElem){this.iframeElem=$('#'+this.iframeElemId);}},addValidation:function(type){if(type!="IsRequired"&&type!="DenyDuplicated"||this.mode===Runner.controls.constants.MODE_SEARCH){return;}
Runner.controls.RTEField.superclass.addValidation.call(this,type);},getForSubmit:function(){if(!this.appearOnPage()){return[];}
var clElem=$('<input type="hidden" name="'+this.iframeElemId+'">').val(this.getValue());return[clElem];},setDisabled:function(){if(!this.controlElementToDisable){return false;}
if(!this.disabledContorlElement.length){this.disabledContorlElement=$('<div id="'+this.disabledControlElementId+'"></div>').prependTo(this.spanContElem);}
this.controlElementToDisable.hide();this.disabledContorlElement.html(this.getValue()).show();return true;},setEnabled:function(){if(!this.controlElementToDisable){return false;}
this.controlElementToDisable.show();this.disabledContorlElement.hide();return true;},makeReadonly:function(){var ctrl=this;if(this.isIframeElemLoaded()){this.setDisabled();return;}
this.iframeElem.bind('load',function(e){ctrl.setDisabled();});},makeReadWrite:function(){var ctrl=this;if(this.isIframeElemLoaded()){this.setEnabled();return;}
this.iframeElem.bind('load',function(e){ctrl.setEnabled();});},isIframeElemLoaded:function(){if(this.loadIframe){return true;}
if(this.isIframeLoaded(this.iframeElem)){this.loadIframe=true;return true;}
return false;},isIframeLoaded:function($iframe){if(!$iframe.length||!$iframe.is("iframe")){return false;}
var iframeDoc=$iframe[0].contentDocument||$iframe[0].contentWindow.document;return iframeDoc.readyState==='complete';},isDisabled:function(){return this.disabledContorlElement.length&&this.disabledContorlElement.is(':visible');},addDelayedCustomEvent:function(eventName,handler,options,scope){this.delayedEventsHandlers.push({eventName:eventName,handler:handler,options:options,scope:scope});},addDelayedEventsListeners:function(){var i,data;for(i=0;i<this.delayedEventsHandlers.length;i++){data=this.delayedEventsHandlers[i];this.on(data.eventName,data.handler,data.options,data.scope);}
this.delayedEventsHandlers=[];},on:function(eventName,fn,options,scope){if(this.eventsAreInitialized){this.on=Runner.controls.Control.superclass.on;this.on(eventName,fn,options,scope);return;}
this.addDelayedCustomEvent(eventName,fn,options,scope);}});Runner.controls.RTEInnova=Runner.extend(Runner.controls.RTEField,{disabledControlElementId:'',innerIframeId:null,loadIframe:false,constructor:function(cfg){Runner.controls.RTEInnova.superclass.constructor.call(this,cfg);this.useRTE=cfg.useRTE||false;this.controlElementToDisable=this.iframeElem;this.initControlEvents();},assignsElemsForEvent:function(){var bodyElem=this.getEditorBodyElem();this.elemsForEvent=[bodyElem.get(0)];},assignListOfEvents:function(){this.addEvent(["keyup","editing","edited"]);},addEditEditingListeners:function(){this.on("keyup",function(e){if(!e||!Runner.isAcceptableKeyCode(e)){return;}
this.fireEvent("edited");this.fireEvent("editing");});this.addDelayedEventsListeners();},initControlEvents:function(){var pageObj,ctrl=this;if(!this.isIframeElemLoaded()){this.iframeElem.bind('load',function(e){ctrl.initCustomEvents();ctrl.loadIframe=true;});return;}
if(!ctrl.getEditorBodyElem().length){this.iframeElem.bind('load',function(e){ctrl.initCustomEvents();});return;}
pageObj=Runner.pages.PageManager.getAt(this.table,this.rowId);if(pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP){pageObj.on("windowSizeCorrected",function(){ctrl.initCustomEvents();});return;}
ctrl.initCustomEvents();},getEditorBodyElem:function(){if(this.useRTE!=='INNOVA'){return this.iframeElem.contents().find('#'+this.iframeElemId).contents().find('body');}
if(!this.innerIframeId){this.innerIframeId='idContentoEdit'+this.goodFieldName+'_'+this.rowId;}
return this.iframeElem.contents().find('#'+this.innerIframeId).contents().find('body');},setDefaultValue:function(){var bodyElem=this.getEditorBodyElem(),editor=this;if(this.isIframeElemLoaded()&&bodyElem.length){this.defaultValue=bodyElem.html();}
this.iframeElem.bind('load',function(e){var bodyElem=editor.getEditorBodyElem();editor.defaultValue=bodyElem.html();editor.loadIframe=true;});this.defaultValue='';},getValue:function(){var val,jQvalDiv,bodyElem;if(!this.iframeElem){return false;}
bodyElem=this.getEditorBodyElem();if(!bodyElem.length){return false;}
val=this.isViewSourceModeSet()?bodyElem.text():bodyElem.html();val=val.replace(/\n/gm,"");jQvalDiv=$('<div>'+val+'</div>');if(!jQvalDiv.find(":not(br)").length&&!jQvalDiv.text().trim()){val='';}
return val;},setValue:function(val){var bodyElem,ctrl=this,readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
if(this.isIframeElemLoaded()){bodyElem=this.getEditorBodyElem();bodyElem.html(val);if(this.isViewSourceModeSet()){bodyElem.text(val);}
readOnly&&this.makeReadonly();return;}
this.iframeElem.bind('load',function(e){bodyElem=ctrl.getEditorBodyElem();bodyElem.html(val);if(this.isViewSourceModeSet()){bodyElem.text(val);}
readOnly&&this.makeReadonly();})},isViewSourceModeSet:function(){return this.useRTE!=='INNOVA'&&this.iframeElem.contents().find('#chkSrc'+this.iframeElemId).is(':checked')},setFocus:function(triggerEvent){if(!this.appearOnPage()||!this.showStatus||this.isDisabled()){return;}
var ctrl=this;this.scrollToElem(this.valueElem);if(this.useRTE!=='INNOVA'){$(this.iframeElem).bind('load',function(){var fontOptions=ctrl.iframeElem.contents().find("#fontname_"+ctrl.iframeElemId+" option");fontOptions.each(function(index,opt){var $opt=$(opt);if(!$opt.prop('selected')){$opt.prop('selected',true);return false;}});});}
if(triggerEvent===true){this.fireEvent("focus");}}});Runner.controls.RTECK=Runner.extend(Runner.controls.RTEField,{constructor:function(cfg){Runner.controls.RTECK.superclass.constructor.call(this,cfg);this.controlElementToDisable=$("#disabledCKE_"+this.valContId);this.setWidthHeight();this.initCustomEvents();},setWidthHeight:function(){var nWidth,nHeight;nWidth=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'nWidth',this.pageType);nHeight=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'nHeight',this.pageType);if(this.appearOnPage()){CKEDITOR.replace(this.valContId,{"width":nWidth,"height":nHeight});}},assignListOfEvents:function(){this.addEvent(["edited","editing"]);},addEditEditingListeners:function(){var ctrl=this,editor=this.getEditor();if(!editor){return;}
editor.on('instanceReady',function(){editor.document.on("keyup",function(e){if(!e||!Runner.isAcceptableKeyCode(e)){return;}
ctrl.fireEvent("editing");});});editor.on("blur",function(e){ctrl.fireEvent("edited");});this.addDelayedEventsListeners();},getEditor:function(){if(!window.CKEDITOR){return false;}
if(typeof window.CKEDITOR.instances[this.valContId]==='undefined'){return false;}
return window.CKEDITOR.instances[this.valContId];},destructor:function(){var editor=this.getEditor();if(editor!==false){CKEDITOR.remove(editor);}},getValue:function(){var editor=this.getEditor();if(!editor){return false;}
return editor.getData();},setValue:function(val){var readOnly=this.isReadonly(),editor;if(readOnly){this.makeReadWrite();}
editor=this.getEditor();if(!editor){readOnly&&this.makeReadonly();return false;}
editor.setData(val);readOnly&&this.makeReadonly();return true;},initToolTip:function(text,pageObj){if(this.mode===Runner.controls.constants.MODE_SEARCH||!this.spanContElem.length){return;}
this.spanContElem.addClass('titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP});this.initToolTip=Runner.emptyFn;},makeReadonly:function(){this.setDisabled();},makeReadWrite:function(){this.setEnabled();},setFocusOnEditor:function(){var ctrl=this,editor=this.getEditor();if(!editor){return false;}
if(!editor.container){editor.on('instanceReady',function(){editor.focus();ctrl.scrollToElem($(editor.container.$));});return;}
editor.focus();this.scrollToElem($(editor.container.$));},setFocus:function(triggerEvent){var pageObj,ctrl=this;if(!this.appearOnPage()||!this.showStatus||this.isDisabled()){return false;}
pageObj=Runner.pages.PageManager.getAt(this.table,this.rowId);if(pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP){pageObj.on("windowSizeCorrected",function(){ctrl.setFocusOnEditor();});}
this.setFocusOnEditor();if(triggerEvent===true){this.fireEvent("focus");}
return true;}});Runner.controls.FileControl=Runner.extend(Runner.controls.Control,{radioElemsName:"",radioElems:null,notEmptyCntrl:0,constructor:function(cfg){this.radioElems={};Runner.controls.FileControl.superclass.constructor.call(this,cfg);var notEmpty=$("#notempty_"+this.goodFieldName+"_"+this.rowId);this.notEmptyCntrl=parseInt($(notEmpty).val());},assignValueElem:function(){Runner.controls.FileControl.superclass.assignValueElem.call(this);this.radioElemsName="type_"+this.goodFieldName+"_"+this.rowId;if($('#'+this.radioElemsName).length){this.getChekedRadio=function(){return false;}}
this.getRadioControls();},assignListOfEvents:function(){this.addEvent(["change","click","edited","editing"]);},"change":function(e){if(e){this.stopEvent(e);}
this.changeRadio("updateRadio");},changeRadio:function(radioToCheck){for(var radio in this.radioElems){if(radio==radioToCheck&&this.radioElems[radio]!=false){this.radioElems[radio].elem.get(0).checked=true;this.radioElems[radio].cheked=true;}else if(radio==radioToCheck&&this.radioElems[radio]==false){return false;}else if(this.radioElems[radio]!=false){this.radioElems[radio].elem.get(0).checked=false;this.radioElems[radio].cheked=false;}}
return true;},getRadioControls:function(){var keepRadio=$('#'+this.radioElemsName+'_keep'),deleteRadio=$('#'+this.radioElemsName+'_delete'),updateRadio=$('#'+this.radioElemsName+'_update'),ctrl=this;keepRadio.bind('click',function(e){ctrl.changeRadio('keepRadio');});deleteRadio.bind('click',function(e){ctrl.changeRadio('deleteRadio');});updateRadio.bind('click',function(e){ctrl.changeRadio('updateRadio');});this.radioElems["keepRadio"]=keepRadio.length?{elem:keepRadio,cheked:true}:false;this.radioElems["deleteRadio"]=deleteRadio.length?{elem:deleteRadio,cheked:false}:false;this.radioElems["updateRadio"]=updateRadio.length?{elem:updateRadio,cheked:false}:false;},getChekedRadio:function(){for(var radio in this.radioElems){if(this.radioElems[radio]!=false&&this.radioElems[radio].cheked===true){return radio;}}
return false;},validate:function(valArr){if(this.notEmptyCntrl&&(this.mode==Runner.pages.constants.PAGE_EDIT||this.mode==Runner.pages.constants.PAGE_INLINE_EDIT)){return Runner.validation.getTrueValidationResult();}
return Runner.controls.FileControl.superclass.validate.call(this,valArr);},getForSubmit:function(){var radio=this.getChekedRadio();var cloneArr=[];if(radio){var radioClone=document.createElement('input');$(radioClone).attr('type','hidden');$(radioClone).attr('id',this.radioElems[radio].elem.attr('id'));$(radioClone).attr('name',this.radioElems[radio].elem.attr('name'));$(radioClone).val(this.radioElems[radio].elem.val());cloneArr.push($(radioClone));}else if($('#'+this.radioElemsName).length){cloneArr.push($('#'+this.radioElemsName));}
var realFile=this.valueElem;var clone=this.valueElem.clone(true);clone.insertAfter(realFile);cloneArr.push(realFile);this.valueElem=clone;return cloneArr;},makeReadonly:function(){this.valueElem.attr('disabled',true);if(this.radioElems.keepRadio){this.radioElems.keepRadio.elem.attr('disabled',true);}
if(this.radioElems.updateRadio){this.radioElems.updateRadio.elem.attr('disabled',true);}
if(this.radioElems.deleteRadio){this.radioElems.deleteRadio.elem.attr('disabled',true);}
return true;},makeReadWrite:function(){this.valueElem.attr('disabled',false);if(this.radioElems.keepRadio){this.radioElems.keepRadio.elem.attr('disabled',false);}
if(this.radioElems.updateRadio){this.radioElems.updateRadio.elem.attr('disabled',false);}
if(this.radioElems.deleteRadio){this.radioElems.deleteRadio.elem.attr('disabled',false);}
return true;},isEmpty:function(){if(this.mode==Runner.pages.constants.PAGE_EDIT||this.mode==Runner.pages.constants.PAGE_INLINE_EDIT){if(this.notEmptyCntrl){return false;}else{if(typeof(this.fileNameElem)!='undefined'&&this.fileNameElem){if(this.fileNameElem.get(0).value==''){this.fileNameElem.get(0).value=this.fileNameElem.get(0).defaultValue;}}
return(this.radioElems["keepRadio"].cheked===true||this.getValue().toString()==""||this.radioElems["updateRadio"].cheked===false)}}else{if(typeof(this.fileNameElem)!='undefined'&&this.fileNameElem){if(!(this.getValue().toString()=="")&&(this.fileNameElem.get(0).value==''))
this.fileNameElem.get(0).value=this.fileNameElem.get(0).defaultValue;}
return(this.getValue().toString()=="")}},resetRadio:function(){for(var radio in this.radioElems){if(this.radioElems[radio]!=false){this.radioElems[radio].elem.get(0).checked=this.radioElems[radio].elem.get(0).defaultChecked;this.radioElems[radio].cheked=this.radioElems[radio].elem.get(0).defaultChecked;}}}});Runner.controls.ImageField=Runner.extend(Runner.controls.FileControl,{imgElem:null,constructor:function(cfg){Runner.controls.ImageField.superclass.constructor.call(this,cfg);},assignValueElem:function(){Runner.controls.ImageField.superclass.assignValueElem.call(this);this.imgElemId="image_"+this.goodFieldName+"_"+this.rowId;this.imgElem=$("#"+this.imgElemId);},setValue:function(val,triggerEvent,updContext){var src=$(val).attr('src');if(src){this.imgElem.attr('src',(src+"&rndVal="+Math.random()));return;}
Runner.controls.ImageField.superclass.setValue.call(this,val,triggerEvent,updContext);if(updContext&&updContext.resetHappend){this.resetRadio();}}});Runner.controls.FileField=Runner.extend(Runner.controls.FileControl,{addTimeStamp:false,fileNameElemId:"",fileNameElem:null,fileHiddElemId:"",fileHiddElem:null,constructor:function(cfg){Runner.controls.FileField.superclass.constructor.call(this,cfg);this.fileHiddElemId="filenameHidden_"+this.goodFieldName+"_"+this.rowId;this.fileHiddElem=$("#"+this.fileHiddElemId).length?$("#"+this.fileHiddElemId):null;for(var radio in this.radioElems){if(this.radioElems[radio]){var objScope=this;this.radioElems[radio].elem.bind('click',function(e){var radioTypeStartFrom=this.id.lastIndexOf('_');var radioTypeName=this.id.substring(radioTypeStartFrom+1)+'Radio';objScope.changeControlsStyles(radioTypeName);});}}
setTimeout(function(){var zoomboxes=$('.zoombox');if(zoomboxes.length)
zoomboxes.zoombox({theme:'zoombox',opacity:0.8,duration:400,animation:false,gallery:false,autoplay:false});},10);},assignValueElem:function(){Runner.controls.FileField.superclass.assignValueElem.call(this);this.fileNameElemId="filename_"+this.goodFieldName+"_"+this.rowId;this.fileNameElem=$("#"+this.fileNameElemId).length?$("#"+this.fileNameElemId):null;this.addTimeStamp=this.addTimeStamp||Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'isUseTimeStamp',this.pageType);},addValidation:function(type){if(type!="IsRequired"&&type!="DenyDuplicated"||this.mode===Runner.controls.constants.MODE_SEARCH){return;}
Runner.controls.FileField.superclass.addValidation.call(this,type);},getFileNameFromPath:function(path){var wpos=path.lastIndexOf('\\');var upos=path.lastIndexOf('/');var pos=wpos;if(upos>wpos)
pos=upos;return path.substr(pos+1);},setValue:function(val,triggerEvent,updContext){var valWithStamp="",fileName="",readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
if(this.fileNameElem!=null||this.addTimeStamp){fileName=this.getFileNameFromPath(this.valueElem.val());}
if(this.addTimeStamp){valWithStamp=this.addTimestamp(fileName);}
if(this.fileNameElem!=null){this.fileNameElem.val(valWithStamp||fileName);this.fileNameElem.get(0).defaultValue=(valWithStamp||fileName);}
if(updContext&&updContext.resetHappend){this.valueElem.val(updContext.values[this.fieldName]);if(this.fileNameElem!=null){this.fileNameElem.val(this.fileNameElem.get(0).defaultValue);}
this.resetRadio();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
if(readOnly){this.makeReadonly();}},addTimestamp:function(filename){var wpos=filename.lastIndexOf('.');if(wpos<0){return filename+'-'+this.getTimestamp();}
return filename.substring(0,wpos)+'-'+this.getTimestamp()+filename.substring(wpos);},getTimestamp:function(){var ts="",now=new Date();ts+=now.getFullYear();ts+=this.padDateValue(now.getMonth()+1,false);ts+=this.padDateValue(now.getDate(),false)+'-';ts+=this.padDateValue(now.getHours(),false);ts+=this.padDateValue(now.getMinutes(),false);ts+=this.padDateValue(now.getSeconds(),false);return ts;},padDateValue:function(value,threedigits){if(!threedigits){if(value>9){return''+value;}
return'0'+value;}
if(value>9){if(value>99){return''+value;}
return'0'+value;}
return'00'+value;},"change":function(e){if(e){this.stopEvent(e);}
var vRes=null;if(!arguments[1]||!arguments[1].resetHappend){this.changeRadio("updateRadio");vRes=this.validate();if(vRes.result){var vl=this.getValue();this.setValue(vl,false);}}
else
vRes=this.validate();},"edited":function(eNull,updateContext){},changeRadio:function(radioToCheck){this.changeControlsStyles(radioToCheck);Runner.controls.FileField.superclass.changeRadio.call(this,radioToCheck);},changeControlsStyles:function(radioToCheck){if(!this.radioElems[radioToCheck]){return false;}
if(this.fileNameElem==null){return false;}
if(radioToCheck=="deleteRadio"){this.fileNameElem.css('backgroundColor','gainsboro');this.fileNameElem[0].disabled=true;return true;}
if(radioToCheck=="updateRadio"||radioToCheck=="keepRadio"){this.fileNameElem.css('backgroundColor','white');this.fileNameElem[0].disabled=false;return true;}
return false;},getFileName:function(){if(this.fileHiddElem){return this.fileHiddElem.val();}else{return false;}},setFileName:function(fileName){if(this.fileHiddElem){this.fileHiddElem.val(fileName);return true;}else{return false;}},getForSubmit:function(){var cloneArr=Runner.controls.ImageField.superclass.getForSubmit.call(this);if(this.fileNameElem){cloneArr.push(this.fileNameElem.clone());}
if(this.fileHiddElem){cloneArr.push(this.fileHiddElem.clone());}
return cloneArr;}});Runner.controls.MultiUploadField=Runner.extend(Runner.controls.Control,{uploadForm:null,fileArray:null,autoUpload:false,maxFileSize:undefined,maxTotalFilesSize:undefined,maxNumberOfFiles:undefined,acceptFileTypes:undefined,isInline:false,errorHappened:false,errorHappenedOnAdd:false,filesToUploadCount:0,$dropZone:null,$filesTable:null,$progressBar:null,$progressLabel:null,constructor:function(cfg){Runner.controls.MultiUploadField.superclass.constructor.call(this,cfg);this.initTemplates();},assignListOfEvents:function(){this.addEvent(["click","change","edited","editing"]);},initTemplates:function(){this.uploadForm=$("#fileupload_"+this.goodFieldName+"_"+this.rowId);this.$progressBar=this.uploadForm.find('.progress');this.$progressLabel=this.uploadForm.find('.progress-extended');this.$filesTable=this.uploadForm.find('.mupload-files');if(!this.uploadForm.length){return;}
var $buttonAddFiles=$(".filesUpload",this.uploadForm[0]),$fileInput=$("input.fileinput-button-input",this.uploadForm[0]),buttonPos=Runner.util.getHiddenDimensions($buttonAddFiles);$buttonAddFiles.css("position","relative");$fileInput.css({"left":0,"top":0,"width":buttonPos.outerWidth+"px","height":buttonPos.outerHeight+"px"});this.fileArray=$("#value_"+this.goodFieldName+"_"+this.rowId);this.uploadForm[0].action+="?table="+encodeURIComponent(this.table)+"&field="+encodeURIComponent(this.fieldName)+"&pageType="+this.pageType
+"&formStamp="+$("#formStamp_"+this.goodFieldName+"_"+this.rowId,this.uploadForm).val();this.uploadForm.fileupload();this.uploadForm.fileupload("option",{autoUpload:true,acceptFileTypes:new RegExp(this.acceptFileTypes,"i"),dropZone:this.uploadForm,maxFileSize:this.maxFileSize,maxTotalFilesSize:this.maxTotalFilesSize,maxNumberOfFiles:this.maxNumberOfFiles!=0?this.maxNumberOfFiles-$.parseJSON(this.fileArray.val()).length:0,constMaxNumberOfFiles:this.maxNumberOfFiles});var control=this,controlId=this.goodFieldName+"_"+this.rowId;this.reloadFiles();this.showDropZone();this.uploadForm.bind('fileuploadadded',function(e,data){control.hideDropZone();if(data.files){if(!data.files[0].error){control.filesToUploadCount++;}else{control.errorHappenedOnAdd=true;}}
control.uploadForm.fileupload('setUploadAndCancelButtonState',control.filesToUploadCount>0);control.fireEvent('change');});this.uploadForm.bind('fileuploaddone',function(e,data){if(control.filesToUploadCount>0){control.filesToUploadCount--;}
control.uploadForm.fileupload('setUploadAndCancelButtonState',control.filesToUploadCount>0);if(data.textStatus!='success'||!data.result||data.result.length==0){control.errorHappened=true;return;}
if(!data.result[0].error){var fileArray=$.parseJSON(control.fileArray.val()),newFile=data.result[0];newFile.isNew=true;fileArray.push(newFile)
control.uploadForm.fileupload('setDeleteButtonState',fileArray.length>0);control.fileArray.val(JSON.stringify(fileArray));}else{control.errorHappened=true;}
control.clearInvalid();});this.uploadForm.bind('fileuploadfail',function(e,data){if(data.errorThrown&&data.jqXHR&&data.jqXHR.responseText){Runner.pages.RunnerPage.prototype.displayGenericAjaxError(data.jqXHR.responseText,Runner.lang.constants.ERROR_UPLOAD);}
if(control.filesToUploadCount>0){control.filesToUploadCount--;}
control.uploadForm.fileupload('setUploadAndCancelButtonState',control.filesToUploadCount>0);});this.uploadForm.bind('fileuploadfailed',function(e,data){control.showDropZone();});this.uploadForm.bind('fileuploaddestroyed',function(e,data){var fileArray=$.parseJSON(control.fileArray.val()),newFileArray=[];$.each(fileArray,function(index,element){if(element.name!=data.name)
newFileArray.push(element);});control.uploadForm.fileupload('setDeleteButtonState',newFileArray.length>0);control.fileArray.val(JSON.stringify(newFileArray));control.showDropZone();control.fireEvent('change');});this.uploadForm.fileupload({destroy:function(e,data){var that=$(this).data('fileupload'),button=$(data.context.context),data={context:button.closest('.template-download'),url:e.data.fileupload.element[0].action,type:'POST',dataType:e.data.fileupload.options.dataType,name:button.attr('data-name'),data:{_action:"DELETE",fileName:button.attr('data-name')}};$.ajax(data);that._adjustMaxNumberOfFiles(1);that._transition(data.context).done(function(){$(this).remove();that._trigger('destroyed',e,data);});}});},isFileApiSupported:function(){var div=document.createElement('div');return!!window.FileReader&&('draggable'in div||('ondragstart'in div&&'ondrop'in div));},hideDropZone:function(){if(this.$dropZone){this.$dropZone.hide();}
this.$progressBar.css('display','');this.$progressLabel.css('display','');},showDropZone:function(){if(this.$filesTable.children().children().length>0||this.errorHappenedOnAdd||$.parseJSON(this.fileArray.val()).length!=0||this.filesToUploadCount!=0||!this.isFileApiSupported()||Runner.isMobile){this.hideDropZone();return;}
this.$progressBar.css('display','none');this.$progressLabel.css('display','none');if(this.$dropZone!==null){this.$dropZone.show();return;}
this.$dropZone=$("<div><div>").addClass('rnr-dragndrop-area').appendTo(this.uploadForm.find(".fileupload-buttonbar")).append($("<div></div>").addClass('rnr-dragtext').text(Runner.lang.constants.UPLOAD_DRAG));$(document).off("drop.multiupload").off("dragover.multiupload").on("drop.multiupload dragover.multiupload",function(e){e.preventDefault();})},reloadFiles:function(){var initialFileArray=$.parseJSON(this.fileArray.val());this.uploadForm.fileupload("option",{maxNumberOfFiles:this.maxNumberOfFiles!=0?this.maxNumberOfFiles-initialFileArray.length:0});this.uploadForm.fileupload('option','done').call(this.uploadForm,null,{result:initialFileArray});this.uploadForm.fileupload('refreshMaxFilesState');this.uploadForm.fileupload('setDeleteButtonState',initialFileArray.length>0);this.uploadForm.fileupload('setUploadAndCancelButtonState',this.filesToUploadCount>0);return initialFileArray.length;},reset:function(updContext){this.setValue(this.defaultValue,true,updContext);this.clearInvalid();this.filesToUploadCount=0;$('table tbody',this.uploadForm).empty();this.reloadFiles();this.showDropZone();},"change":function(e){if(e){this.stopEvent(e);}},getForSubmit:function(){var cloneArr=[];cloneArr.push(this.valueElem.clone());cloneArr.push($("#formStamp_"+this.goodFieldName+"_"+this.rowId,this.uploadForm).clone());return cloneArr;},setDisabled:function(){return this.makeReadonly();},setEnabled:function(){return this.makeReadWrite();},makeReadonly:function(){this.valueElem.prop('disable',true);this.uploadForm.fileupload('setDeleteButtonState',false);$(".fileupload-buttonbar",this.uploadForm).hide();return true;},makeReadWrite:function(){this.valueElem.prop('disable',false);this.uploadForm.fileupload('setDeleteButtonState',true);$(".fileupload-buttonbar",this.uploadForm).show();return true;},isEmpty:function(){return this.getValue().toString()==""||this.getValue().toString()=="[]";},setFocus:function(triggerEvent){var addButtonElem=$(".fileinput-button-input",this.uploadForm);if(!this.appearOnPage()||!this.showStatus||this.valueElem.is("disabled")||!addButtonElem.length){return;}
addButtonElem.focus();if(triggerEvent===true){this.fireEvent("focus");}},getToolTipPositionElem:function(){return this.uploadForm;}});Runner.controls.DateField=Runner.extend(Runner.controls.Control,{datePickerHiddId:"",datePickerHiddElem:null,imgCal:null,useDatePicker:false,dateFormatHiddId:"",dateFormat:"",showTime:false,dateFormatHiddElem:null,dataPicker:null,timeBox:null,dateDelimiter:"/",startWeekDay:0,is24hoursFormat:false,timePmLetter:"PM",timeAmLetter:"AM",timeDelimiter:":",leadingZero:true,monthNames:[Runner.lang.constants.TEXT_MONTH_JAN,Runner.lang.constants.TEXT_MONTH_FEB,Runner.lang.constants.TEXT_MONTH_MAR,Runner.lang.constants.TEXT_MONTH_APR,Runner.lang.constants.TEXT_MONTH_MAY,Runner.lang.constants.TEXT_MONTH_JUN,Runner.lang.constants.TEXT_MONTH_JUL,Runner.lang.constants.TEXT_MONTH_AUG,Runner.lang.constants.TEXT_MONTH_SEP,Runner.lang.constants.TEXT_MONTH_OCT,Runner.lang.constants.TEXT_MONTH_NOV,Runner.lang.constants.TEXT_MONTH_DEC],dayNames:[Runner.lang.constants.TEXT_DAY_SU,Runner.lang.constants.TEXT_DAY_MO,Runner.lang.constants.TEXT_DAY_TU,Runner.lang.constants.TEXT_DAY_WE,Runner.lang.constants.TEXT_DAY_TH,Runner.lang.constants.TEXT_DAY_FR,Runner.lang.constants.TEXT_DAY_SA],calendar:null,constructor:function(cfg){Runner.controls.DateField.superclass.constructor.call(this,cfg);this.useDatePicker=cfg.useDatePicker||false;this.useYuiDatePicker=cfg.useYuiDatePicker||false;this.usejQueryDatePicker=cfg.usejQueryDatePicker||false;this.dateDelimiter=Runner.pages.PageSettings.getGlobalData("locale")["dateDelimiter"];this.startWeekDay=(parseInt(Runner.pages.PageSettings.getGlobalData("locale").startWeekDay)+1)%7;this.showTime=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"showTime",this.pageType);this.timePmLetter=Runner.pages.PageSettings.getGlobalData("locale").timePmLetter;this.timeAmLetter=Runner.pages.PageSettings.getGlobalData("locale").timeAmLetter;this.timeDelimiter=Runner.pages.PageSettings.getGlobalData("locale").timeDelimiter;if(Runner.pages.PageSettings.getGlobalData("locale").leadingZero=="1"){this.leadingZero=true;}
if(Runner.pages.PageSettings.getGlobalData("locale").is24hoursFormat=="1"){this.is24hoursFormat=true;}
this.dateFormatHiddId="type"+(cfg.ctrlInd||"")+"_"+this.goodFieldName+"_"+this.rowId;this.dateFormatHiddElem=$("#"+this.dateFormatHiddId);if(this.pageObj.isBootstrap()){this.usejQueryDatePicker=false;this.useYuiDatePicker=false;this.initBSDatepicker();}else{this.initjQueryDatePicker();this.initYUIDatePicker();}},initBSDatepicker:function(){if(!this.useDatePicker){return;}
var ctrl=this,$pickerElem,initialYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'initialYear',this.pageType),lastYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'lastYear',this.pageType),options={showTodayButton:true,showClose:true,minDate:moment().subtract(initialYear,'years').startOf("year"),maxDate:moment().add(lastYear,'years').endOf("year"),},outerContainerForIE;if(this.pageObj.openMode==Runner.pages.constants.OPENMODE_POPUP&&(Runner.isIE||Runner.isIE11)){outerContainerForIE=$("#pickerContainer");if(outerContainerForIE.length===0){outerContainerForIE=$("<div id='pickerContainer' style='position:relative; z-index:9999'></div>");outerContainerForIE.appendTo("body");}
options.widgetParent=outerContainerForIE;}
if(this.dateEditType===Runner.controls.constants.EDIT_DATE_DD_INLINE||this.dateEditType===Runner.controls.constants.EDIT_DATE_DD_DP){$pickerElem=$("#"+this.valContId).parents('.bs-date-control');options.format="YYYY-M-D";options.widgetPositioning={horizontal:Runner.isDirRTL()?'left':'right'};$pickerElem.datetimepicker(options);ctrl.on("focus",function(){$pickerElem.data("DateTimePicker").hide();});$pickerElem.on("dp.change",function(e){ctrl.setValue(e.date.toDate(),true);});this.imgCal=$('#imgCal_'+this.valContId).on('click',function(){ctrl.setCorrectAmPmMoment();$pickerElem.data("DateTimePicker").toggle();}).on("blur",function(){$pickerElem.data("DateTimePicker").hide();});}else if(this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_INLINE||this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_DP){$pickerElem=this.valueElem.parents(".input-group");ctrl.setCorrectAmPmMoment();options.format=this.getDateFormatString().replace(/yy/g,"YYYY").toUpperCase();options.format+=this.showTime?' '+this.getTimeFormatString():'';$pickerElem.datetimepicker(options);this.imgCal=$('#imgCal_'+this.valContId).on('click',function(){ctrl.setCorrectAmPmMoment();});}
if(!outerContainerForIE&&$pickerElem&&(this.isInline||this.pageObj.openMode!=Runner.pages.constants.OPENMODE_PRELOADED)){$pickerElem.on("dp.show",function(e){Runner.util.absToFixed($(".bootstrap-datetimepicker-widget",this));});}},setCorrectAmPmMoment:function(){var ctrl=this;moment.updateLocale('en',{months:ctrl.monthNames,monthsShort:jQuery.map(ctrl.monthNames,function(val){return val.substr(0,3);}),weekdaysMin:ctrl.dayNames,week:{dow:ctrl.startWeekDay,},meridiem:function(hour,minute,isLowercase){if(hour>=12){return ctrl.timePmLetter;}
return ctrl.timeAmLetter;}});},initjQueryDatePicker:function(){if(!this.usejQueryDatePicker){return;}
var ctrl=this,options=this.getjQueryDatePickerDaseOptions(),imageCallId,datePickerId,imgCalClickHandler,documentClickHandler,datePickerInstance,calendarAreaClick,currentValue;this.patchjQueryUIDatepickerTodayHandler();if(this.dateEditType===Runner.controls.constants.EDIT_DATE_SIMPLE_INLINE){options.onBeforeShowHandler=function(input,inst){!ctrl.getValue()&&ctrl.setValue('');};options.onSelectHandler=function(dt,inst,isTimepicker){var $input=$(inst.input);if(!isTimepicker){$input.datepicker('hide');}
if($input.data("todaySelected")){currentValue=new Date();$input.data("todaySelected",false);}
ctrl.setValue(dt+" "+ctrl.printTime(currentValue),true);};this.valueElem.datepicker(options);datePickerInstance=this.valueElem.data("datepicker");datePickerInstance._possibleChars=function(format){var chars=$.datepicker._possibleChars(format);return chars+" :";}
datePickerInstance.dpDiv.addClass('rnr-datepicker');this.valueElem.unbind("focus",$.datepicker._showDatepicker).on("focus",function(e){if(!ctrl.invalid()){$.datepicker._showDatepicker(e);currentValue=ctrl.getValue();}}).on("click",function(e){var position=$.datepicker._findPos(this),offset={left:position[0],top:position[1]};if(offset.left>0){offset=$.datepicker._checkOffset(datePickerInstance,offset);}
$.datepicker._showDatepicker(e);datePickerInstance.dpDiv.css({left:offset.left,top:offset.top+this.offsetHeight}).show();}).on("change",function(e){currentValue=ctrl.getValue();});;return;}
if(this.dateEditType===Runner.controls.constants.EDIT_DATE_DD_INLINE){imageCallId='imgCal_'+this.valContId;datePickerId=imageCallId+'_datepicker';this.calendar=$('#'+datePickerId);if(!this.calendar.length){this.calendar=$('<div />').attr('id',datePickerId).css({'display':'none','position':'absolute','z-index':'9999'}).appendTo('body');}
calendarAreaClick=false;this.unbindOnDestroy=[];documentClickHandler=function(e){if(!calendarAreaClick&&e.target!=ctrl.calendar.get(0)&&!ctrl.calendar.has(e.target).length||$(e.target).data('handler')==='today'){ctrl.calendar.hide();}
calendarAreaClick=false;};this.unbindOnDestroy.push({object:$(document),event:'click',handler:documentClickHandler});imgCalClickHandler=function(){ctrl.calendar.addClass('rnr-datepicker');imgCalClickHandler=function(){var position,isVisible=ctrl.calendar.is(':visible');$(document).unbind('click',documentClickHandler).bind('click',documentClickHandler);if(isVisible){ctrl.calendar.hide();return false;}
position=ctrl.spanContElem.offset();ctrl.calendar.css({left:position.left,top:position.top+20});ctrl.calendar.show();return false;};imgCalClickHandler();$(this).unbind('click').bind('click',imgCalClickHandler);return false;};this.imgCal=$('#'+imageCallId).bind('click',imgCalClickHandler);options.onChangeMonthYear=function(year,month,inst){calendarAreaClick=true;};options.onSelectHandler=function(dt,inst){$(this).datepicker('hide');var dt=ctrl.parseDateTime(dt,ctrl.dateFormat);ctrl.setValue(dt,true);setTimeout(function(){ctrl.calendar.hide();},0);};this.calendar.datepicker(options);}},patchjQueryUIDatepickerTodayHandler:function(){if($.datepicker._gotoToday.patched){return;}
var gotoToday=$.datepicker._gotoToday;$.datepicker._gotoToday=function(id){var inst;gotoToday.call($.datepicker,id);inst=$.datepicker._getInst($(id).get(0));$(inst.input).data("todaySelected",true);$.datepicker._selectDate(id);};$.datepicker._gotoToday.patched=true;},getDateFormatString:function(){var dateFormat;switch(parseInt(this.dateFormat)){case 0:dateFormat='mm/dd/yy'.replace(/\//g,this.dateDelimiter);break;case 1:dateFormat='dd/mm/yy'.replace(/\//g,this.dateDelimiter);break;case 2:dateFormat='yy/mm/dd'.replace(/\//g,this.dateDelimiter);break;case-1:default:dateFormat='dd-mm-yy';}
return dateFormat;},getTimeFormatString:function(){var timeFormat,hourFormat=this.is24hoursFormat?'H':'h';hour=this.leadingZero?hourFormat:hourFormat+hourFormat,minute=!this.leadingZero?'m':'mm',secound=!this.leadingZero?'s':'ss';timeFormat=hour;timeFormat+=this.timeDelimiter+minute;timeFormat+=this.timeDelimiter+secound;timeFormat+=!this.is24hoursFormat?" a":"";return timeFormat;},getjQueryDatePickerDaseOptions:function(){var ctrl=this,initialYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'initialYear',this.pageType),lastYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'lastYear',this.pageType);return{currentText:Runner.lang.constants.TEXT_TODAY,closeText:Runner.lang.constants.TEXT_HIDE,changeMonth:true,changeYear:true,dayNames:this.dayNames,dayNamesShort:this.dayNames,dayNamesMin:this.dayNames,monthNames:this.monthNames,monthNamesShort:this.monthNames,firstDay:this.startWeekDay,isRTL:Runner.isDirRTL(),dateFormat:this.getDateFormatString(),prevText:'',nextText:'',yearRange:'-'+initialYear+':+'+lastYear,showButtonPanel:true,beforeShow:function(input,inst){var inst=inst.inst||inst;if(inst.settings.onBeforeShowHandler){inst.settings.onBeforeShowHandler(input,inst);}},onSelect:function(dt,inst){var isTimepicker=!!inst.inst,inst=inst.inst||inst;if(inst.settings.onSelectHandler){inst.settings.onSelectHandler(dt,inst,isTimepicker);}},onClose:function(dt,inst){if(inst.settings.onCloseHandler){inst.settings.onCloseHandler(dt,inst);}},onCloseHandler:function(dt,inst){var dt=ctrl.parseDateTime(dt,ctrl.dateFormat);if(dt&&dt.toString()!==ctrl.getValue().toString()){ctrl.setValue(dt,true);}}};},initYUIDatePicker:function(){if(!this.useYuiDatePicker){this.initYUIDatePicker=Runner.emptyFn;return;}
var dateControl=this,afterCreateHandler=$.proxy(this.initYUICalendar,this),afterCloseHandler=$.proxy(this.destroyYUICalendar,this);this.datePickerHiddId="tsvalue"+(this.ctrlInd||"")+"_"+this.goodFieldName+"_"+this.rowId;this.datePickerHiddElem=$("#"+this.datePickerHiddId);this.imgCal=$('#imgCal_'+this.valContId).bind("click",function(e){var winArgs={modal:true,resize:false,centered:true};Runner.pages.PageManager.createFlyWin(winArgs,false,afterCreateHandler,afterCloseHandler);return false;});},destroyYUICalendar:function(winWrapper){var calWin=winWrapper._obj
this.calendar.destroy();setTimeout(function(){calWin.destroy(true);},0);},initYUICalendar:function(winWrapper){var Y=Runner.Y,dateControl=this,calWin;if(!Y){return;}
calWin=winWrapper._obj;Y.use('calendar','datatype-date',function(Y){var date=new Date(),currentYear=date.getFullYear(),initialYear=Runner.pages.PageSettings.getFieldData(dateControl.table,dateControl.fieldName,"initialYear",dateControl.pageType),lastYear=Runner.pages.PageSettings.getFieldData(dateControl.table,dateControl.fieldName,"lastYear",dateControl.pageType),startYear=dateControl.startYear=currentYear-initialYear,endYear=dateControl.endYear=currentYear+lastYear,addCalId="cal"+(new Date().getTime()+''+Math.floor(Math.random()*100)),calendar,timeSpan,selDate,node=calWin.get("srcNode").getDOMNode(),width,centered;calWin.set('bodyContent','<div id="'+addCalId+'"></div>');if(Runner.isDirRTL()){Y.Plugin.CalendarNavigator.CALENDARNAV_STRINGS.prev_month_class=Y.ClassNameManager.getClassName('calendarnav','nextmonth');Y.Plugin.CalendarNavigator.CALENDARNAV_STRINGS.next_month_class=Y.ClassNameManager.getClassName('calendarnav','prevmonth');}
calendar=new Y.Calendar({contentBox:'#'+addCalId,minimumDate:new Date("1/1/"+startYear),maximumDate:new Date("12/31/"+endYear),showPrevMonth:true,showNextMonth:true});dateControl.calendar=calendar;if(Runner.isIE){calendar.set('width','250px');calendar.set('height','204px');}
calendar.set("strings.first_weekday",dateControl.startWeekDay);calendar.set("strings.weekdays",dateControl.dayNames);calendar.set("strings.short_weekdays",dateControl.dayNames);calendar.set("strings.very_short_weekdays",dateControl.dayNames);calendar.set("headerRenderer",function(curDate){var curYear=curDate.getFullYear(),curMonth=curDate.getMonth(),minYear=this.get('minimumDate').getFullYear(),maxYear=this.get('maximumDate').getFullYear(),monthDD,yearDD,i;this.yearDDId=this._calendarId+'_year_dd';this.monthDDId=this._calendarId+'_month_dd';monthDD='<select class="rnr-calMonthDD" id="'+this.monthDDId+'">';for(i=0;i<dateControl.monthNames.length;i++){monthDD+='<option value="'+i+'"';if(i==curMonth){monthDD+='selected="selected"';}
monthDD+='>'+dateControl.monthNames[i]+'</option>';}
monthDD+='</select>';yearDD='<select class="rnr-calYearDD" id="'+this.yearDDId+'">';for(i=minYear;i<=maxYear;i++){yearDD+='<option value="'+i+'"';if(i==curYear){yearDD+='selected="selected"';}
yearDD+='>'+i+'</option>';}
yearDD+='</select>';return monthDD+yearDD;});var selectionHandler=function(e){var selDate,currentDate;if(!calendar.get("selectedDates").length){return;}
selDate=calendar.get("selectedDates")[0];currentDate=dateControl.getValue();selDate.setHours(currentDate?currentDate.getHours():0);selDate.setMinutes(currentDate?currentDate.getMinutes():0);selDate.setSeconds(currentDate?currentDate.getSeconds():0);dateControl.setValue(selDate,true);dateControl.destroyYUICalendar({_obj:calWin});e.stopImmediatePropagation();};calendar.on("dateClick",selectionHandler);calendar.after("render",function(){var contentBox=$(calendar.get('contentBox').getDOMNode());contentBox.delegate('#'+calendar.yearDDId,'change',function(e){var val=parseInt(this.value),oldDate;if(val<endYear+1&&val>startYear-1){oldDate=calendar.get("date");calendar.set("date",new Date(val,oldDate.getMonth(),1));}});contentBox.delegate('#'+calendar.monthDDId,'change',function(e){var val=parseInt(this.value),oldDate=calendar.get("date");calendar.set("date",new Date(oldDate.getFullYear(),val,1));});});function todayHandler(){calendar.today=new Date();if(!this.showTime){calendar.today.setHours(0);calendar.today.setMinutes(0);calendar.today.setSeconds(0);}
calendar.selectDates(calendar.today);this.setValue(calendar.today,true);this.destroyYUICalendar({_obj:calWin});};calWin.addButton({value:Runner.lang.constants.TEXT_TODAY,section:Y.WidgetStdMod.BODY,classNames:'rnr-calTodayBut',action:function(e){e.preventDefault();todayHandler.call(dateControl);}});$(".rnr-calTodayBut").parent().css({"display":"block","text-align":"center"});selDate=dateControl.getValue();if(selDate){calendar.set('date',selDate);calendar.selectDates(selDate);}
calendar.render();calWin.render();calWin.show();width=Runner.isIE?270:$(node).width();$(node).width(width);if(Runner.isDirRTL()){centered=$(window).scrollLeft()+Math.floor(($(window).width()-node.offsetWidth)/2);calWin.set("x",centered);}});},parseDateTime:function(str,dmy){if(str==null){return null;}
var dt,i,stringDateTime,arr=str.match(/\d+/g),amRegular="(a\.?m\.?)"+(this.timeAmLetter?"|("+this.timeAmLetter+")":""),pmRegular="(p\.?m\.?)"+(this.timePmLetter?"|("+this.timePmLetter+")":""),amRegExp=new RegExp(amRegular,"gi"),pmRegExp=new RegExp(pmRegular,"gi"),isAm=str.match(amRegExp),isPm=str.match(pmRegExp);if(arr==null||arr.length<3){return null;}
for(i=arr.length;i<6;i++){arr[i]=0;}
if(arr[0]>100){dmy=2;}
if(dmy==1){stringDateTime=arr[2]+"/"+arr[1]+"/"+arr[0];}else if(dmy==0){stringDateTime=arr[2]+"/"+arr[0]+"/"+arr[1];}else{stringDateTime=arr[0]+"/"+arr[1]+"/"+arr[2];}
stringDateTime+=" "+arr[3]+":"+arr[4]+":"+arr[5];if(arr[3]>0&&arr[3]<=12){if(isAm){stringDateTime+=" AM";}else if(isPm){stringDateTime+=" PM";}}
dt=new Date(stringDateTime);if(isNaN(dt)){return null;}
return dt;},addValidation:function(type){if(type!=="IsRequired"&&type!=="DenyDuplicated"||this.mode===Runner.controls.constants.MODE_SEARCH){return;}
Runner.controls.DateField.superclass.addValidation.call(this,type);},setValue:function(newDate){},printDateTime:function(value,format,skipDayMonthZeroes){var date,time,day=value.getDate(),month=value.getMonth()+1,year=value.getFullYear();format=parseInt(format);if(!skipDayMonthZeroes){day=day<10?'0'+day:day;month=month<10?'0'+month:month;}
switch(format){case-1:date=day+'-'+month+'-'+year;break;case 0:date=month+this.dateDelimiter+day+this.dateDelimiter+year;break;case 1:date=day+this.dateDelimiter+month+this.dateDelimiter+year;break;default:date=year+this.dateDelimiter+month+this.dateDelimiter+day;}
if(!this.showTime){return date;}
time=this.printTime(value);return date+' '+time;},printTime:function(value){if(!this.isDateObject(value)){return"";}
var hours=value.getHours(),minutes=value.getMinutes(),seconds=value.getSeconds(),time,ampm="";if(!this.is24hoursFormat){ampm=" ";if(hours>12){hours=hours-12;ampm+=this.timePmLetter;}else if(hours==12){ampm+=this.timePmLetter;}else if(hours===0){hours=12;ampm+=this.timeAmLetter;}else{ampm+=this.timeAmLetter;}}
time=(this.leadingZero&&hours<10)?'0'+hours:hours;time+=this.timeDelimiter+((this.leadingZero&&minutes<10)?'0'+minutes:minutes);time+=this.timeDelimiter+((this.leadingZero&&seconds<10)?'0'+seconds:seconds);return time+ampm;},isDateObject:function(value){return Object.prototype.toString.call(value)==="[object Date]";},getToolTipPositionElem:function(){return this.imgCal;}});Runner.controls.DateTextField=Runner.extend(Runner.controls.DateField,{constructor:function(cfg){Runner.controls.DateTextField.superclass.constructor.call(this,cfg);if(this.isSetValidation('DenyDuplicated')){this.valueElem.attr('autocomplete','off');}},assignValueElem:function(){Runner.controls.DateField.superclass.assignValueElem.call(this);if(typeof this.dateFormat==="undefined"||this.dateFormat===""){this.dateFormat=Runner.pages.PageSettings.getGlobalData("locale").dateFormat;}},assignListOfEvents:function(){this.addEvent(["click","blur","change","keyup","edited","editing"]);},addEditEditingListeners:function(){var ctrl=this;this.on("change",function(e,updateContext){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};this.fireEvent("edited",updateContext);this.fireEvent("editing");});this.on("keyup",function(e){if(!e||!Runner.isAcceptableKeyCode(e)){return false;}
this.fireEvent("editing");});if(this.pageObj.isBootstrap()){if(this.dateEditType===Runner.controls.constants.EDIT_DATE_DD_INLINE||this.dateEditType===Runner.controls.constants.EDIT_DATE_DD_DP){this.valueElem.parents(".bs-date-control").on("dp.change",function(e){ctrl.fireEvent("change",null);});}else if(this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_INLINE||this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_DP){this.valueElem.parents(".input-group").on("dp.change",function(e){ctrl.fireEvent("change",null);});}}},getValue:function(){var parsedTime=this.parseDateTime(this.valueElem.val(),this.dateFormat);if(parsedTime==null){return"";}
return parsedTime;},setValue:function(newDate,triggerEvent,updContext){var dt,dateObj=newDate,readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
if(typeof newDate==="string"){dateObj=this.parseDateTime(newDate,this.dateFormat);}
if(this.isDateObject(dateObj)){dt=this.printDateTime(dateObj,this.dateFormat);this.valueElem.val(dt);if(this.useYuiDatePicker){dt=this.printDateTime(dateObj,-1);this.datePickerHiddElem.val(dt);}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return true;}
this.valueElem.val("");if(this.useYuiDatePicker){this.datePickerHiddElem.val("");}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return false;},"blur":function(e){this.stopEvent(e);this.focusState=false;},"edited":function(nullEvent,updateContext){var valArr=this.getPreparedValidationArray(),vRes=this.validate(valArr),newValue=this.getValue();if(vRes.result&&this.useDatePicker&&newValue){this.setValue(newValue);}
this.clearInvalidOnDependences();this.reloadDependentCtrls(updateContext,nullEvent);},setDisabled:function(){if(!this.valueElem.length){return false;}
this.valueElem.prop('disabled',true);if(this.imgCal){this.imgCal.css('visibility','hidden');}
return true;},setEnabled:function(){if(!this.valueElem.length){return false;}
this.valueElem.prop('disabled',false);if(this.imgCal){this.imgCal.css('visibility','visible');}
return true;},getForSubmit:function(){return[this.valueElem.clone(),this.dateFormatHiddElem.clone()];},makeReadonly:function(){Runner.controls.DateTextField.superclass.makeReadonly.call(this);if(this.imgCal){this.imgCal.css('display','none');}
return true;},makeReadWrite:function(){Runner.controls.DateTextField.superclass.makeReadWrite.call(this);if(this.imgCal){this.imgCal.css('display','');}
return true;},getStringValue:function(){return this.valueElem.val();},getDefaultControlValue:function(){if(this.defaultValue===""){return this.defaultValue;}
return this.printDateTime(this.defaultValue,this.dateFormat);},destructor:function(){Runner.controls.DateTextField.superclass.destructor.call(this);if(this.usejQueryDatePicker&&$.contains(document.documentElement,this.valueElem.get(0))){this.valueElem.datepicker('hide').datepicker('destroy');}}});Runner.controls.DateDropDown=Runner.extend(Runner.controls.DateField,{hiddValueElem:null,hiddElemId:"",unbindOnDestroy:null,constructor:function(cfg){Runner.controls.DateDropDown.superclass.constructor.call(this,cfg);if(Runner.lang.constants.TEXT_MONTH_JAN){this.addYearOptions(cfg.yearVal);this.addMonthOptions(cfg.monthVal);this.addDayOptions(cfg.dayVal);}
if(this.hiddValueElem.length){this.setValue(this.parseDateTime(this.hiddValueElem.val(),2));}
this.defaultValue=this.getValue();},assignValueElem:function(){if(typeof this.dateFormat==="undefined"||this.dateFormat===""){this.dateFormat=Runner.pages.PageSettings.getGlobalData("locale").dateFormat;}
this.valueElem={"day":$("#day"+this.valContId),"month":$("#month"+this.valContId),"year":$("#year"+this.valContId)};this.hiddElemId=this.valContId;this.hiddValueElem=$("#"+this.hiddElemId);},assignsElemsForEvent:function(){this.elemsForEvent=[this.valueElem["day"].get(0),this.valueElem["month"].get(0),this.valueElem["year"].get(0)];},assignListOfEvents:function(){this.addEvent(["click","change","edited","editing"]);},destructor:function(){Runner.controls.DateDropDown.superclass.destructor.call(this);this.valueElem['day'].remove();this.valueElem['month'].remove();this.valueElem['year'].remove();if(!this.usejQueryDatePicker){return;}
this.calendar.hide();this.calendar.datepicker('destroy');if(!this.unbindOnDestroy){return;}
var i,unbindData;for(i=0;i<this.unbindOnDestroy.length;i++){unbindData=this.unbindOnDestroy[i];$(unbindData.object).unbind(unbindData.event,unbindData.handler);}},initToolTip:function(text,pageObj){if(!this.valueElem['day'].length||!this.valueElem['month'].length||!this.valueElem['year'].length){return;}
var options={div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP,el:this.getToolTipPositionElem()};this.valueElem['day'].addClass('titleHintBox').inputHintBox(options);this.valueElem['month'].addClass('titleHintBox').inputHintBox(options);this.valueElem['year'].addClass('titleHintBox').inputHintBox(options);},addYearOptions:function(selectedYear){var dt=new Date(),currentYear=dt.getFullYear(),initialYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"initialYear",this.pageType),lastYear=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"lastYear",this.pageType),startYear=currentYear-initialYear,endYear=currentYear+lastYear,opt=$('<option>').val('').html('&nbsp;'),i;this.valueElem["year"].html('').append(opt);for(i=startYear;i<=endYear;i++){opt=$('<option>').val(i).html(i);if(i==selectedYear){opt.attr("selected","selected");}
this.valueElem["year"].append(opt);};this.addYearOptions=Runner.emptyFn;},addMonthOptions:function(selectedMonth){var i,opt=$('<option>').val('').html('&nbsp;');this.valueElem["month"].html('').append(opt);for(i=0;i<this.monthNames.length;i++){opt=$('<option>').val(i+1).html(this.monthNames[i]);if(i+1==selectedMonth){opt.attr("selected","selected");}
this.valueElem["month"].append(opt);}
if(!this.valueElem["month"].css('width')){this.valueElem["month"].css('width','90px');}
this.addMonthOptions=Runner.emptyFn;},addDayOptions:function(selectedDay){var i,opt=$('<option>').val('').html('&nbsp;');this.valueElem["day"].html('').append(opt);for(i=1;i<=31;i++){opt=$('<option>').val(i).html(i);if(i===selectedDay){opt.attr("selected","selected");}
this.valueElem["day"].append(opt);};this.addDayOptions=Runner.emptyFn;},"change":function(e){if(e){this.stopEvent(e);}},"edited":function(nullEvent,updateContext){var name,vRes,newValue=this.getValue();for(name in this.valueElem){if(this.valueElem[name].val()===''){this.hiddValueElem.val('');if(this.useYuiDatePicker){this.datePickerHiddElem.val("");}
return;}}
vRes=this.validate();if(vRes.result){this.setValue(this.getValue());}
this.clearInvalidOnDependences();this.reloadDependentCtrls(updateContext,nullEvent);},getValue:function(){var dayVal=this.valueElem["day"].val(),monthVal=this.valueElem["month"].val(),yearVal=this.valueElem["year"].val();if(!dayVal||!monthVal||!yearVal){return false;}
return new Date(yearVal,monthVal-1,dayVal,00,00,00);},setValue:function(newDate,triggerEvent,updContext){var day,month,year,dateObj=newDate,readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
if(typeof newDate==="string"){dateObj=this.parseDateTime(newDate,this.dateFormat);}
if(this.isDateObject(dateObj)){day=dateObj.getDate();month=dateObj.getMonth()+1;year=dateObj.getFullYear();this.hiddValueElem.val(year+'-'+month+'-'+day);this.valueElem["day"].get(0).selectedIndex=day;this.valueElem["month"].get(0).selectedIndex=month;this.valueElem["year"].val(year).attr('selected','selected');if(this.useDatePicker){if(this.useYuiDatePicker){this.datePickerHiddElem.val(day+'-'+month+'-'+year);}else if(this.usejQueryDatePicker&&this.calendar){this.calendar.datepicker('setDate',dateObj);}else if(this.pageObj.isBootstrap()){this.hiddValueElem.parents(".bs-date-control").data("DateTimePicker").date(dateObj);}}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return true;}
this.hiddValueElem.val('');this.valueElem["day"].get(0).selectedIndex=0;this.valueElem["month"].get(0).selectedIndex=0;this.valueElem["year"].get(0).selectedIndex=0;if(this.useYuiDatePicker){this.datePickerHiddElem.val("");}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return false;},makeReadonly:function(){this.setDisabled();return true;},makeReadWrite:function(){this.setEnabled();return true;},setDisabled:function(){if(!this.valueElem.day||!this.valueElem.month||!this.valueElem.year){return false;}
this.valueElem.day.prop('disabled',true);this.valueElem.month.prop('disabled',true);this.valueElem.year.prop('disabled',true);if(this.imgCal){this.imgCal.css('visibility','hidden');}
return true;},setEnabled:function(){this.valueElem.day.prop('disabled',false);this.valueElem.month.prop('disabled',false);this.valueElem.year.prop('disabled',false);if(this.imgCal){this.imgCal.css('visibility','visible');}
return true;},getForSubmit:function(){return[this.hiddValueElem.clone(),this.dateFormatHiddElem.clone()];},setFocus:function(triggerEvent){var ctrl=this;this.isSetFocus=false;if(!this.showStatus){return;}
$.each(this.valueElem,function(ind,elem){var $elem=$(elem);if($elem.is(':disabled')||!$elem.is(':visible')){return;}
if($elem.parent().find('select:first').attr('id')!=$elem.attr('id')){return;}
elem.focus();ctrl.isSetFocus=true;if(triggerEvent===true){ctrl.fireEvent("focus");}
return false;});},isEmpty:function(){return this.valueElem["day"].val()==""||this.valueElem["month"].val()==""||this.valueElem["year"].val()=="";},getStringValue:function(datePassed){var date=datePassed||this.getValue(),day,month,year;if(this.isDateObject(date)){day=date.getDate();month=date.getMonth()+1;year=date.getFullYear();return year+'-'+month+'-'+day;}
return'';},appearOnPage:function(){return!!this.valueElem["day"].length&&!!this.valueElem["month"].length&&!!this.valueElem["year"].length;},getDefaultControlValue:function(){if(this.defaultValue===false){return'';}
return this.getStringValue(this.defaultValue);}});Runner.controls.LookupWizard=Runner.extend(Runner.controls.Control,{parentCtrls:null,parentFieldNames:null,multiSelectionAllowed:false,addNew:null,lookupTable:"",pageId:-1,dispField:"",linkField:"",preloadData:null,autoCompleteFields:null,originalTable:null,originalField:null,masterTName:"",masterTId:0,mainFields:null,mainMasterFields:null,constructor:function(cfg){this.parentCtrls=[];this.autoCompleteFields=[];Runner.controls.LookupWizard.superclass.constructor.call(this,cfg);this.initAddNewLink();if(this.pageType===Runner.pages.constants.PAGE_ADD&&!this.isEmpty()){this.doAutoCompleteFields();}
if(Runner.pages.PageSettings.getTableData(this.table,"entityType")===Runner.pages.constants.titDASHBOARD){this.originalTable=this.getFieldSetting("originalTable");this.originalField=this.getFieldSetting("originalField");this.shortTableName=Runner.pages.PageSettings.getShortTName(this.originalTable)}else{this.originalTable=this.table;this.originalField=this.fieldName;}
if(this.preloadData){this.preload(this.preloadData.vals,this.preloadData.fVal);this.setDefaultValue();}},assignListOfEvents:function(){this.addEvent(["click","change","edited","editing"]);},initAddNewLink:function(){var control=this;this.addNew=$("#addnew_"+this.valContId).on("click",function(e){var params=control.getPageParams();control.pageId=Runner.pages.PageManager.openPage(params);return false;});},getToolTipPositionElem:function(){return this.addNew.length?this.addNew:null;},getPageParams:function(){var pageParams={modal:true,lookupCtrl:this,tName:this.lookupTable,pageType:Runner.pages.constants.PAGE_ADD,baseParams:{parId:this.rowId,field:this.fieldName,pageType:this.pageType,table:this.shortTableName,editType:Runner.pages.constants.ADD_ONTHEFLY},afterSave:{fn:function(respObj,formObj,fieldControls,pageObj){if(respObj.success){this.processNewFlyAdded(respObj.vals[this.dispField],respObj.vals[this.linkField])
return;}
if(respObj.message){pageObj.displayHalfPreparedMessage(respObj.message,true);}
if(pageObj.isBootstrap()){pageObj.bsWin.animate({scrollTop:0});}
else{pageObj.adjustPopWindowHeightByContent();$(pageObj.win.bodyNode.getDOMNode()).animate({scrollTop:0});}
Runner.delDisabledClass(pageObj.saveButton);return false;},scope:this}};if(!!this.parentCtrls.length){pageParams.baseParams.parentsExist=true;pageParams.baseParams.parentCtrlsData=JSON.stringify(this.getParentControlsData());}
return pageParams;},clearChildrenLinks:function(triggerReload){for(var i=0;i<this.dependentCtrls.length;i++){if(this.dependentCtrls[i]){this.dependentCtrls[i].clearParents(triggerReload);}}},clearParents:function(triggerReload){this.paretCtrls=[];if(triggerReload===true){this.reload();}},setDependencies:function(tName,pageId,parentFData,triggerReload){if(!this.hasDependencies()){return;}
if(this.isSearchControl()&&parentFData){this.setSearhcLookupDependencies(tName,parentFData,triggerReload);return;}
this.setLookupDependencies(tName,pageId);},setSearhcLookupDependencies:function(tName,parentFData,triggerReload){var i,pfName,rowId,ctrlIndex,parentCtrl,loaded;for(i=0;i<this.parentFieldNames.length;i++){pfName=this.parentFieldNames[i];if(!parentFData[pfName]){continue;}
parentCtrl=Runner.controls.ControlManager.getAt(tName,parentFData[pfName].rowId,pfName,parentFData[pfName].ctrlIndex);if(!parentCtrl||!parentCtrl.showStatus||!parentCtrl.isLookupWizard()){continue;}
this.parentCtrls.push(parentCtrl);parentCtrl.addDependentCtrls([this]);if(triggerReload){parentCtrl.fireEvent('change');continue;}
if(!loaded&&this.preloadData){this.preload(this.preloadData.vals,this.preloadData.fVal);loaded=true;}}
if(!loaded){this.reload();}},setLookupDependencies:function(tName,pageId){var i,ctrl;for(i=0;i<this.parentFieldNames.length;i++){ctrl=Runner.controls.ControlManager.getAt(tName,pageId,this.parentFieldNames[i]);if(!ctrl){continue;}
this.parentCtrls.push(ctrl);ctrl.addDependentCtrls([this]);}
for(i=0;i<this.mainFields.length;i++){ctrl=Runner.controls.ControlManager.getAt(tName,pageId,this.mainFields[i]);if(ctrl){ctrl.addDependentCtrls([this]);}}
if(this.masterTName&&this.masterTId){for(i=0;i<this.mainMasterFields.length;i++){ctrl=Runner.controls.ControlManager.getAt(this.masterTName,this.masterTId,this.mainMasterFields[i]);if(ctrl){ctrl.addDependentCtrls([this]);}}
if(this.mainMasterFields.length){this.reload();}}},preload:function(vals,selectValue){},getMasterContolData:function(){var masterData={};this.mainMasterFields.forEach(function(mField,idx){var ctrl=Runner.controls.ControlManager.getAt(this.masterTName,this.masterTId,mField);if(ctrl){masterData[mField]=ctrl.getStringValue();}},this);return masterData;},reload:function(updContext){var ctrl=this,ajaxParams={mode:this.mode,field:this.originalField,pageType:this.pageType,isExistParent:!!this.parentCtrls.length?1:0,parentCtrlsData:JSON.stringify(this.getParentControlsData()),data:JSON.stringify(this.getControlsData()),masterTable:this.masterTName,shortTName:Runner.pages.PageSettings.getShortTName(this.table)},selectedValue=this.getValue(true),oldValue=this.getValue(),reloadHn,paramsString;if(this.masterTName&&this.mainMasterFields.length){ajaxParams.masterData=JSON.stringify(this.getMasterContolData());}
reloadHn=function(respObj){updContext.ajaxRequests[ctrl.fieldName][paramsString]=respObj;ctrl.updateLookupData(respObj.data||[],selectedValue,updContext);ctrl.processAutofillDataOnReload(updContext);if(oldValue!==ctrl.getValue()){ctrl.fireEvent("change",updContext);}
ctrl.clearInvalid();};updContext.ajaxRequests=updContext.ajaxRequests||{};updContext.ajaxRequests[this.fieldName]=updContext.ajaxRequests[this.fieldName]||{};paramsString=JSON.stringify(ajaxParams);if(updContext.ajaxRequests[this.fieldName][paramsString]){reloadHn.call(this,updContext.ajaxRequests[this.fieldName][paramsString]);return;}
Runner.runnerAJAX(Runner.getPageUrl("autocomplete"),ajaxParams,reloadHn);},processAutofillDataOnReload:function(updContext){if(updContext&&updContext.values&&updContext.values[this.fieldName]){this.setValue(updContext.values[this.fieldName],false,updContext);}},doAutoCompleteFields:function(updContext){if(!updContext||typeof updContext!=="object"){updContext={initiator:this.fieldName};}
if(!this.autoCompleteFields.length||updContext.resetHappend){return;}
updContext.autofillStarted=updContext.autofillStarted||[];if($.inArray(this.fieldName,updContext.autofillStarted)!=-1){return;}
updContext.autofillStarted.push(this.fieldName);var ajaxParams={shortTName:Runner.pages.PageSettings.getShortTName(this.table),mainField:this.fieldName,linkFieldVal:this.getValue(),pageType:this.pageType,data:JSON.stringify(this.getControlsData()),masterTable:this.masterTName};Runner.runnerAJAX(Runner.getPageUrl('autofillfields'),ajaxParams,$.proxy(function(respObj){if(!respObj.success){return false;}
var data=respObj.data,valToFill,i,ctrl;updContext.values=updContext.values||{};for(i=0;i<this.autoCompleteFields.length;i++){updContext.values[this.autoCompleteFields[i].masterF]=[data[this.autoCompleteFields[i].lookupF]];}
for(i=0;i<this.autoCompleteFields.length;i++){ctrl=Runner.controls.ControlManager.getAt(this.table,this.rowId,this.autoCompleteFields[i].masterF);if(!ctrl||updContext.initiator===this.autoCompleteFields[i].masterF){continue;}
valToFill=data[this.autoCompleteFields[i].lookupF];valToFill=valToFill===null||valToFill===undefined?'':valToFill;ctrl.setValue(valToFill,true,updContext);}},this));},"change":function(e,updContext){this.doAutoCompleteFields(updContext);this.reloadDependentCtrls(updContext,e);return false;},getParentLookupFieldNames:function(){return this.parentFieldNames;},hasDependencies:function(){return this.parentFieldNames&&this.parentFieldNames.length||this.mainFields&&this.mainFields.length||this.mainMasterFields&&this.mainMasterFields.length;},isLookupWizard:function(){return true;}});Runner.controls.RadioControl=Runner.extend(Runner.controls.LookupWizard,{radioElemsId:"",radioElemsArr:[],radioElemsNameAttr:"",radioElem:null,radioElemsCount:0,constructor:function(cfg){Runner.controls.RadioControl.superclass.constructor.call(this,cfg);},assignValueElem:function(){Runner.controls.RadioControl.superclass.assignValueElem.call(this);this.radioElemsId="radio_"+this.goodFieldName+"_"+this.rowId+"_";this.radioElemsNameAttr="radio_"+this.goodFieldName+"_"+this.rowId;this.radioElem=$('input[name='+this.radioElemsNameAttr+']');this.radioElemsCount=this.radioElem.length;this.radioElemsArr=[];for(var i=0;i<this.radioElemsCount;i++){this.radioElemsArr.push($("#"+this.radioElemsId+i));}},assignsElemsForEvent:function(){for(var i=0;i<this.radioElemsCount;i++){this.elemsForEvent.push(this.radioElemsArr[i].get(0));}},assignListOfEvents:function(){this.addEvent(["change","keyup","edited","editing"]);},setValue:function(val,triggerEvent,updContext){var choosen=false,readOnly=this.isReadonly(),i;if(readOnly){this.makeReadWrite();}
for(i=0;i<this.radioElemsCount;i++){if(this.radioElemsArr[i].val()==val){this.radioElemsArr[i].prop("checked",true);this.valueElem.val(val);choosen=true;}else{this.radioElemsArr[i].prop("checked",false);}}
if(!choosen){this.valueElem.val('');}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return choosen;},setDisabled:function(){for(var i=0;i<this.radioElemsCount;i++){this.radioElemsArr[i].get(0).disabled=true;}
return true;},setEnabled:function(){for(var i=0;i<this.radioElemsCount;i++){this.radioElemsArr[i].get(0).disabled=false;}
return true;},"change":function(e,updContext){if(e&&e.target.value!=this.getValue()){this.setValue(e.target.value,false);this.doAutoCompleteFields();}
this.reloadDependentCtrls(updContext,e);},initToolTip:function(text,pageObj){if(this.mode===Runner.controls.constants.MODE_SEARCH||!this.spanContElem.length){return;}
this.spanContElem.addClass('titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP});this.initToolTip=Runner.emptyFn;},makeReadonly:function(){this.setDisabled();return true;},makeReadWrite:function(){this.setEnabled();return true;},getDisplayValue:function(){var value=this.valueElem.val(),i;for(i=0;i<this.radioElemsCount;i++){if(this.radioElemsArr[i].val()==value&&this.radioElemsArr[i].prop("checked")){return $("#label_"+this.radioElemsArr[i].attr("id")).text();}}
return"";},preload:function(vals,selectValue){this.clearCtrl();this.addRadioByArr(vals);this.setValue(selectValue,false);},updateLookupData:function(data,selectValue,updContext){this.clearCtrl();this.addRadioByArr(data);this.setValue(selectValue,false);},clearCtrl:function(){var $divWrapper=this.spanContElem.find('div[data-lookup-options]');$divWrapper.children().remove();this.radioElemsArr=[];this.radioElemsCount=0;},addRadio:function(text,value){var $radioButton,$radioLabel,delim='&nbsp;',ind=this.radioElemsArr.length,$divWrapper=$('div[data-lookup-options]',this.spanContElem),$spanWrapper=$('<span class="radio"><label></label></span>').appendTo($divWrapper),$label=$('label',$spanWrapper);$divWrapper.addClass(this.isHorizontalLookup?'rnr-horizontal-lookup':'rnr-vertical-lookup');$radioButton=$('<input>').attr('id',this.radioElemsId+ind).addClass('rnr-radio-button').attr('type','radio').attr('name',this.radioElemsId).val(value);$radioLabel=$('<span>').attr('id','label_'+this.radioElemsId+ind).addClass('rnr-radio-label').html(text);$label.append($radioButton).append(delim).append($radioLabel);this.radioElemsArr.push($radioButton);this.radioElemsCount++;},addRadioByArr:function(radioElemsArr){var i;for(i=0;i<radioElemsArr.length-1;i=i+2){this.addRadio(radioElemsArr[i+1],radioElemsArr[i]);}
this.radioElem=$('input[name='+this.radioElemsNameAttr+']');this.radioElemsCount=this.radioElemsArr.length;this.purgeListeners();this.initCustomEvents();},setFocus:function(triggerEvent){if(!this.appearOnPage()||!this.showStatus||!this.radioElemsArr.length||this.radioElemsArr[0].is(':disabled')){this.isSetFocus=false;return;}
this.radioElemsArr[0].focus();this.isSetFocus=true;if(triggerEvent===true){this.fireEvent("focus");}},processNewFlyAdded:function(text,value){this.addRadio(text,value);this.setValue(value,true);this.purgeListeners();this.initCustomEvents();},getForSubmit:function(){if(!this.appearOnPage()){return[];}
var cloneElem=this.valueElem.clone(),val=this.valueElem.val(),i,rButton;if(!val){for(i=0;i<this.radioElemsArr.length;i++){rButton=this.radioElemsArr[i];if(rButton.is(":checked")||$("#"+rButton.attr("id")).is(":checked")){val=rButton.val();break;}}}
return[cloneElem.val(val)];}});Runner.controls.DropDownLookup=Runner.extend(Runner.controls.LookupWizard,{selectSize:1,optionsDOM:null,simpleSearchBox:{},multiSelectionWithTabsEnabled:false,constructor:function(cfg){Runner.controls.DropDownLookup.superclass.constructor.call(this,cfg);},assignValueElem:function(){Runner.controls.DropDownLookup.superclass.assignValueElem.call(this);this.optionsDOM=this.appearOnPage()?this.valueElem.get(0).options:[];this.initMultiselectionWithTabs();if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")&&!this.multiSelectionWithTabsEnabled){this.simpleSearchBox=$("#"+this.valContId+"_simpleSearchBox");}
this.initChanginAppearance();},assignsElemsForEvent:function(){Runner.controls.DropDownLookup.superclass.assignsElemsForEvent.call(this);if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")&&!this.multiSelectionWithTabsEnabled){this.elemsForEvent.push(this.simpleSearchBox.get(0));}},assignListOfEvents:function(){Runner.controls.DropDownLookup.superclass.assignListOfEvents.call(this);if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")&&!this.multiSelectionWithTabsEnabled){this.addEvent(["keyup"]);}},initMultiselectionWithTabs:function(){var self=this;if(this.selectSize==1&&this.multiSelectionAllowed){this.valueElem.chosen({placeholder_text_multiple:Runner.lang.constants.TEXT_PLEASE_SELECT,width:this.pageObj.isBootstrap()?"100%":this.valueElem.width()+"px",});var chosen=this.valueElem.data("chosen");chosen.container.css("position","static");chosen.dropdown.css("top",0);this.valueElem.on("chosen:showing_dropdown",function(e,data){var chosen=data.chosen,position=chosen.container.position(),offset=chosen.container.offset();if(self.pageObj.isBootstrap()&&self.pageObj.openMode==Runner.pages.constants.OPENMODE_POPUP){chosen.dropdown.css({position:"fixed",width:chosen.container.width(),top:offset.top-chosen.dropdown.parents(".modal-dialog").offset().top+chosen.container.outerHeight(),left:offset.left-chosen.dropdown.parents(".modal-dialog").offset().left,}).show();}
else{chosen.dropdown.css({width:chosen.container.width(),top:position.top+chosen.container.outerHeight(),left:position.left}).show();}}).on("chosen:hiding_dropdown",function(e,data){data.chosen.dropdown.hide();});this.multiSelectionWithTabsEnabled=true;}},setDefaultValue:function(){this.defaultValue=this.getValue(true);},setValue:function(pvals,triggerEvent,updContext){var vals=Runner.isArray(pvals)?pvals:[pvals],ctrl=this,choosen=0,readOnly=this.isReadonly(),j;if(readOnly){this.makeReadWrite();}
this.valueElem.find('option').each(function(i,option){for(j=0;j<vals.length;j++){if(option.value==vals[j]){try{ctrl.optionsDOM[i].selected=true;choosen++;}catch(e){};if(ctrl.multiSelectionAllowed){break;}
ctrl.valueElem.prop("selectedIndex",i);return false;}
try{ctrl.optionsDOM[i].selected=false;}catch(e){};}
if(!vals.length){ctrl.optionsDOM[i].selected=false;}});if(!!vals.length&&!choosen||!this.multiSelectionWithTabsEnabled&&choosen>this.selectSize){readOnly&&this.makeReadonly();return false;}
if(this.multiSelectionWithTabsEnabled){this.valueElem.trigger("chosen:updated");}
if(readOnly){this.makeReadonly();}
if(triggerEvent===true){this.fireEvent("change",updContext);}
return true;},getValue:function(returnArray){var selVals=[],i;if(!this.optionsDOM){return"";}
for(i=0;i<this.optionsDOM.length;i++){if(this.optionsDOM[i].selected){selVals.push(this.optionsDOM[i].value)}}
if(!this.optionsDOM.length&&this.appearOnPage()){this.valueElem.find('option:selected').each(function(i,option){selVals.push(option.value);});}
if(returnArray===true||selVals.length>1){return selVals;}
if(selVals.length===1){return selVals[0];}
return"";},getStringValue:function(valueArray){var valsArr=valueArray||this.getValue(true),i;if(!this.multiSelectionAllowed){return valsArr[0];}
for(i=0;i<valsArr.length;i++){if(valsArr[i].indexOf(',')!==-1||valsArr[i].indexOf('"')!==-1){valsArr[i]='"'+valsArr[i].replace(/"/g,'""')+'"';}}
return valsArr.join(",");},getDefaultControlValue:function(){if(this.defaultValue===''){return'';}
return this.getStringValue(this.defaultValue);},isEmpty:function(){var selVals=this.getValue();return selVals==="";},removeOptions:function(){var select=this.valueElem.get(0),i;for(i=this.optionsDOM.length;i--;){select.remove(i);}
if(this.multiSelectionWithTabsEnabled){this.valueElem.trigger("chosen:updated");}},addOption:function(text,val){$('<option></option>').attr('value',val).text(text).appendTo(this.valueElem);if(this.multiSelectionWithTabsEnabled){this.valueElem.trigger("chosen:updated");}},addOptionsArr:function(optionsArr){for(var i=0;i<optionsArr.length-1;i=i+2){this.addOption(optionsArr[i+1],optionsArr[i]);}},preload:function(vals,selectValue){this.removeOptions();if(!this.multiSelectionAllowed){this.addOption(Runner.lang.constants.TEXT_PLEASE_SELECT,"");}
this.addOptionsArr(vals);if(selectValue!==null&&selectValue!==''){this.setValue(selectValue,false);return;}
if(this.optionsDOM.length>0&&this.mode!==Runner.controls.constants.MODE_SEARCH){this.setValue([this.optionsDOM[0].value],false);}},updateLookupData:function(data,selectedValues,updContext){this.removeOptions();if(!this.multiSelectionAllowed){this.addOption(Runner.lang.constants.TEXT_PLEASE_SELECT,"");}
this.addOptionsArr(data);if(this.optionsDOM.length==2&&!this.multiSelectionAllowed||this.optionsDOM.length==1&&this.multiSelectionAllowed){this.setValue([this.optionsDOM[this.optionsDOM.length-1].value],false);}else{this.setValue(selectedValues,false);}},initChanginAppearance:function(){if(this.mode!==Runner.controls.constants.MODE_SEARCH||!this.valueElem.data("usesuggests")||!this.simpleSearchBox.length){this.updateAppearance=Runner.emptyFn;return;}
this.getStringValue=function(valueArray){if(this.simpleSearchBox.is(":visible")&&!valueArray){return this.simpleSearchBox.val();}
return Runner.controls.DropDownLookup.prototype.getStringValue.call(this,valueArray);};this.isEmpty=function(){if(this.simpleSearchBox.is(":visible")){return this.simpleSearchBox.val()==="";}
return Runner.controls.DropDownLookup.prototype.isEmpty.call(this);};this.makeReadonly=function(){this.simpleSearchBox.prop({'disabled':true,'readonly':true});return Runner.controls.DropDownLookup.prototype.makeReadonly.call(this);};this.makeReadWrite=function(){this.simpleSearchBox.prop({'disabled':false,'readonly':false});return Runner.controls.DropDownLookup.prototype.makeReadWrite.call(this);};this.setDisabled=function(){this.simpleSearchBox.prop('disabled',true);return Runner.controls.DropDownLookup.prototype.setDisabled.call(this);};this.setEnabled=function(){this.simpleSearchBox.prop('disabled',false);return Runner.controls.DropDownLookup.prototype.setDisabled.call(this);};this.getValue=function(returnArray){if(this.simpleSearchBox.is(":visible")){return this.simpleSearchBox.val();}
return Runner.controls.DropDownLookup.prototype.getValue.call(this,returnArray);};this.setValue=function(value){if(this.simpleSearchBox.is(":visible")){return this.simpleSearchBox.val(value);}
return Runner.controls.DropDownLookup.prototype.setValue.call(this,value);};this.preload=function(vals,selectValue){if(this.simpleSearchBox.is(":visible")){return;}
return Runner.controls.DropDownLookup.prototype.preload.call(this,vals,selectValue);};this.reload=function(updContext){if(this.simpleSearchBox.is(":visible")){return;}
return Runner.controls.DropDownLookup.prototype.reload.call(this,updContext);};this.getDispElem=function(){if(this.simpleSearchBox.is(":visible")){return this.simpleSearchBox;}
return Runner.controls.DropDownLookup.prototype.getDispElem.call(this);};this.implySuggests=function(){return this.simpleSearchBox.is(":visible");};},updateAppearance:function(searchOption){var simpleControlOptions=["Contains","NOT Contains","Starts with","NOT Starts with"];if($.inArray(searchOption,simpleControlOptions)===-1){(this.isReadonly()?this.readonlyElem:this.valueElem).show();this.simpleSearchBox.hide();return;}
(this.isReadonly()?this.readonlyElem:this.valueElem).hide();this.simpleSearchBox.show();},setDisabled:function(){if(!this.valueElem){return false;}
this.valueElem.prop('disabled',true);if(this.addNew){this.addNew.css('visibility','hidden');}
if(this.multiSelectionWithTabsEnabled){$('option',this.valueElem).prop('disabled',true);this.valueElem.trigger("chosen:updated");}
return true;},setEnabled:function(){if(!this.valueElem){return false;}
this.valueElem.prop('disabled',false);if(this.addNew){this.addNew.css('visibility','visible');}
if(this.multiSelectionWithTabsEnabled){$('option',this.valueElem).prop('disabled',false);this.valueElem.trigger("chosen:updated");}
return true;},getForSubmit:function(){if(!this.appearOnPage()){return[];}
var $clone=this.valueElem.clone(),selVals=this.getValue(true),cloneOpt=$clone.get(0).options,i,j;if(this.multiSelectionWithTabsEnabled&&this.isReadonly()){$clone.prop("disabled",false);$(cloneOpt).prop("disabled",false);}
for(i=0;i<cloneOpt.length;i++){for(j=0;j<selVals.length;j++){if(cloneOpt[i].value==selVals[j]){if(!this.multiSelectionAllowed){$clone.get(0).selectedIndex=i;}
cloneOpt[i].selected=true;break;}
cloneOpt[i].selected=false;}
if(!selVals.length){cloneOpt[i].selected=false;}}
if(this.multiSelectionWithTabsEnabled&&!cloneOpt.length||!selVals.length){$clone.append('<option selected="selected" value=""></option>');}
return[$clone];},makeReadonly:function(){this.addNew.hide();if(this.multiSelectionWithTabsEnabled){this.valueElem.prop("disabled",false);$('option',this.valueElem).prop('disabled',true);this.valueElem.trigger("chosen:updated");return;}
Runner.controls.DropDownLookup.superclass.makeReadonly.call(this);},isReadonly:function(){if(this.multiSelectionWithTabsEnabled){return $('option',this.valueElem).prop("disabled");}
return!!$('#readonly_'+this.valContId).length;},makeReadWrite:function(){this.addNew.show();if(this.multiSelectionWithTabsEnabled){this.valueElem.prop("disabled",false);$('option',this.valueElem).prop("disabled",false);this.valueElem.trigger("chosen:updated");return;}
Runner.controls.DropDownLookup.superclass.makeReadWrite.call(this);},getDisplayValue:function(){var displayValues=[],i=this.multiSelectionAllowed?0:1;for(;i<this.optionsDOM.length;i++){if(this.optionsDOM[i].selected){displayValues.push(this.optionsDOM[i].text);}}
return displayValues.join(", ");},processNewFlyAdded:function(text,value){var values;if(this.multiSelectionAllowed){values=this.getValue(true);values.push(value);}else{values=[value];}
this.addOption(text,value);this.setValue(values,true);},clear:function(){this.clearInvalid();if(!this.multiSelectionWithTabsEnabled){this.setValue('',false);$("#"+this.valContId+"_simpleSearchBox").val("");}else{$('option:selected',this.valueElem).prop('selected',false);this.valueElem.trigger("chosen:updated");}},setFocus:function(triggerEvent){if(!this.multiSelectionWithTabsEnabled){Runner.controls.DropDownLookup.superclass.setFocus.call(this,triggerEvent);return;}
var chosenCtrl=this.valueElem.data('chosen');if(!this.appearOnPage()||this.valueElem.prop('disabled')||!this.showStatus||!chosenCtrl.container.is(':visible')){return;}
chosenCtrl.search_field.focus();this.isSetFocus=true;},useSearchSuggests:function(){return this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")&&!this.multiSelectionWithTabsEnabled;},deleteOptions:function(){var select=this.valueElem.get(0),i;for(i=this.optionsDOM.length;i--;){if(this.optionsDOM[i].value!==Runner.lang.constants.TEXT_PLEASE_SELECT){select.remove(i);}}
if(this.multiSelectionWithTabsEnabled){this.valueElem.trigger("chosen:updated");}}});Runner.controls.CheckBox=Runner.extend(Runner.controls.Control,{typeElem:null,constructor:function(cfg){Runner.controls.CheckBox.superclass.constructor.call(this,cfg);},assignValueElem:function(){Runner.controls.CheckBox.superclass.assignValueElem.call(this);this.typeElem=$("#"+"type_"+this.goodFieldName+"_"+this.rowId);},setValue:function(value,triggerEvent,updContext){var readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
this.valueElem.prop("checked",value&&value!=="0");if(triggerEvent===true){this.fireEvent("change",updContext);}
if(readOnly){this.makeReadonly();}
return true;},getValue:function(){if(this.valueElem.is(":checked")){return this.valueElem.val();}
return"";},isEmpty:function(){return!this.valueElem.is(":checked");},getForSubmit:function(){var cloneArr=[],$cbClone;if(this.valueElem.is(":checked")){$cbClone=$('<input>').attr('type','hidden').attr('id',this.valueElem.attr('id')).attr('name',this.valueElem.attr('name')).val(this.valueElem.val());cloneArr.push($cbClone.get(0));}
cloneArr.push(this.typeElem);return cloneArr;},initToolTip:function(text,pageObj){if(this.mode===Runner.controls.constants.MODE_SEARCH||!this.spanContElem.length){return;}
this.spanContElem.addClass('titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP});this.initToolTip=Runner.emptyFn;},makeReadonly:function(){if(!this.appearOnPage()){return false;}
var $readonlyElem=this.valueElem.clone(),elId=this.valueElem.attr("id");$readonlyElem.prop({id:"readonly_"+elId,name:"readonly_"+elId,disabled:true});this.valueElem.before($readonlyElem).hide();return true;},makeReadWrite:function(){if(!this.appearOnPage()||!this.isReadonly()){return false;}
$('#readonly_'+this.valueElem.attr("id")).remove();this.valueElem.show();return true;},isReadonly:function(){return!!$('#readonly_'+this.valueElem.attr("id")).length;}});Runner.controls.CheckBoxLookup=Runner.extend(Runner.controls.LookupWizard,{typeElem:null,checkBoxCount:0,checkBoxesArr:null,constructor:function(cfg){this.checkBoxesArr=[];Runner.controls.CheckBoxLookup.superclass.constructor.call(this,cfg);},assignValueElem:function(){var $checkBox,typeElemId,control=this;Runner.controls.CheckBoxLookup.superclass.assignValueElem.call(this);typeElemId="type_"+this.goodFieldName+"_"+this.rowId;this.typeElem=$("#"+typeElemId);$("[id^='"+this.valContId+"_']").each(function(){control.checkBoxesArr.push($(this));});},assignsElemsForEvent:function(){for(var i=0;i<this.checkBoxesArr.length;i++){this.elemsForEvent.push(this.checkBoxesArr[i].get(0));}},setValue:function(value,triggerEvent,updContext){var readOnly=this.isReadonly(),valsArr=[],checkCount=0,i,j;if(readOnly){this.makeReadWrite();}
if(value===true&&this.checkBoxesArr.length==1){this.checkBoxesArr[0].get(0).checked=true;}else if(!value){for(i=0;i<this.checkBoxesArr.length;i++){this.checkBoxesArr[i].get(0).checked=false;}}else{valsArr=typeof value==='string'?[value]:value;for(i=0;i<this.checkBoxesArr.length;i++){this.checkBoxesArr[i].get(0).checked=false;for(j=0;j<valsArr.length;j++){if(this.checkBoxesArr[i].val()==valsArr[j]){this.checkBoxesArr[i].get(0).checked=true;checkCount++;break;}}}}
if(triggerEvent===true){this.fireEvent("change",updContext);}
if(readOnly){this.makeReadonly();}
return checkCount==valsArr.length&&checkCount<=this.checkBoxesArr.length;},getValue:function(){var checkedArr=this.getCheckedBoxes(),valsArr=[];for(var i=0;i<checkedArr.length;i++){valsArr.push(checkedArr[i].val());}
return valsArr;},getStringValue:function(valueArray){var valsArr=valueArray||this.getValue(),i;for(i=0;i<valsArr.length;i++){if(valsArr[i].indexOf(',')!==-1||valsArr[i].indexOf('"')!==-1){valsArr[i]='"'+valsArr[i].replace(/"/g,'""')+'"';}}
return valsArr.join(",");},getDefaultControlValue:function(){return this.getStringValue(this.defaultValue);},isEmpty:function(){return!this.getValue().length;},setDisabled:function(){for(var i=0;i<this.checkBoxesArr.length;i++){this.checkBoxesArr[i].prop('disabled',true);}
return true;},setEnabled:function(){for(var i=0;i<this.checkBoxesArr.length;i++){this.checkBoxesArr[i].prop('disabled',false);}
return true;},getCheckedBoxes:function(){var chekedArr=[],i,checkBox;for(i=0;i<this.checkBoxesArr.length;i++){checkBox=this.checkBoxesArr[i];if(checkBox.is(":checked")||$("#"+checkBox.attr("id")).is(":checked")){chekedArr.push(this.checkBoxesArr[i]);}}
return chekedArr;},getForSubmit:function(){var checkedArr=this.getCheckedBoxes(),cloneArr=[],realCb,cbClone,i;for(i=0;i<checkedArr.length;i++){realCb=checkedArr[i];cbClone=$('<input>').attr('type','hidden').attr('id',realCb.attr('id')).attr('name',realCb.attr('name')).val(realCb.val());cloneArr.push(cbClone.get(0));}
cloneArr.push(this.typeElem);return cloneArr;},removeCheckBoxes:function(){var $divWrapper=this.spanContElem.find('div[data-lookup-options]');$divWrapper.children().remove();this.checkBoxesArr=[];this.checkBoxCount=0;},addCheckBoxArr:function(checkBoxesArr){if(!checkBoxesArr){return;}
for(var i=0;i<checkBoxesArr.length-1;i=i+2){this.addCheckBox(checkBoxesArr[i+1],checkBoxesArr[i]);}
this.purgeListeners();this.initCustomEvents();},addCheckBox:function(text,value){var $checkBox,$boxLabel,delim='&nbsp;',ind=this.checkBoxesArr.length,$divWrapper=$('div[data-lookup-options]',this.spanContElem),$spanWrapper=$('<span class="checkbox"><label></label></span>').appendTo($divWrapper),$label=$('label',$spanWrapper);$divWrapper.addClass(this.isHorizontalLookup?'rnr-horizontal-lookup':'rnr-vertical-lookup');$checkBox=$('<input>').attr('id',this.valContId+"_"+ind).addClass('rnr-checkbox').attr('type','checkbox').attr('name',this.valContId+'[]').val(value);$boxLabel=$('<b>').attr('id','data_'+this.valContId+'_'+ind).addClass('rnr-checkbox-label').html(text);$label.append($checkBox).append(delim).append($boxLabel);this.checkBoxesArr.push($checkBox);this.checkBoxCount++;},preload:function(vals,selectValue){this.removeCheckBoxes();this.addCheckBoxArr(vals);this.setValue(selectValue,false);},updateLookupData:function(data,selectedValues,updContext){this.removeCheckBoxes();this.addCheckBoxArr(data);this.setValue(selectedValues,false);},initToolTip:function(text,pageObj){if(this.mode===Runner.controls.constants.MODE_SEARCH||!this.spanContElem.length){return;}
this.spanContElem.addClass('titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP});this.initToolTip=Runner.emptyFn;},makeReadonly:function(){if(!this.appearOnPage()){return false;}
for(var i=0;i<this.checkBoxesArr.length;i++){var elemChk=this.checkBoxesArr[i],readonlyElem=elemChk.clone(),elId=elemChk.get(0).id;readonlyElem.prop({id:"readonly_"+elId,name:"readonly_"+elId,disabled:true});elemChk.before(readonlyElem).hide();}
return true;},makeReadWrite:function(){if(!this.appearOnPage()||!this.isReadonly()){return false;}
for(var i=0;i<this.checkBoxesArr.length;i++){var elemChk=this.checkBoxesArr[i],elId=elemChk.get(0).id;$('#readonly_'+elId).remove();elemChk.show();}
return true;},isReadonly:function(){for(var i=0;i<this.checkBoxesArr.length;i++){if($('#readonly_'+this.checkBoxesArr[i].get(0).id).length){return true;}}
return false;},getDisplayValue:function(){var displayValues=[];for(var i=0;i<this.checkBoxesArr.length;i++){if(this.checkBoxesArr[i].prop("checked")){displayValues.push($("#data_"+this.checkBoxesArr[i].attr("id")).text());}}
return displayValues.join(", ");},appearOnPage:function(){return this.checkBoxesArr.length;},setFocus:function(triggerEvent){var firstValueElem=this.checkBoxesArr[0];this.isSetFocus=false;if(!this.appearOnPage()||!this.showStatus||firstValueElem.is(':disabled')){return;}
firstValueElem.focus();this.isSetFocus=true;if(triggerEvent===true){this.fireEvent("focus");}},processNewFlyAdded:function(text,value){var values=this.getValue();values.push(value);this.addCheckBox(text,value);this.setValue(values,true);this.purgeListeners();this.initCustomEvents();}});Runner.controls.TextFieldLookup=Runner.extend(Runner.controls.LookupWizard,{displayElem:null,defaulOptionsData:null,constructor:function(cfg){Runner.controls.TextFieldLookup.superclass.constructor.call(this,cfg);},assignValueElem:function(){Runner.controls.TextFieldLookup.superclass.assignValueElem.call(this);this.displayElem=$("#display_"+this.valContId);this.initMultiselectionWithTabs();},initMultiselectionWithTabs:function(){if(!this.multiSelectionAllowed){return;}
var ctrl=this,chosenCtrl;this.valueElem.chosen({disable_search:false,placeholder_text_multiple:" ",width:this.pageObj.isBootstrap()?"100%":this.valueElem.width()+"px",});chosenCtrl=this.valueElem.data("chosen");this.valueElem.on("chosen:showing_dropdown",function(){chosenCtrl.results_showing=true;chosenCtrl.results_hide();}).on("change",function(e,data){if(data&&data.deselected){ctrl.removeMultiselectOption(data.deselected);}});},assignListOfEvents:function(){this.addEvent(["blur"]);Runner.controls.TextFieldLookup.superclass.assignListOfEvents.call(this);},setDefaultValue:function(){var ctrl=this;if(!this.multiSelectionAllowed){this.defaultValue=[this.getValue(),this.getDisplayValue()];return;}
this.defaultValue=this.getValue(true);this.defaulOptionsData=[];$('option',this.valueElem).each(function(ind,option){var $option=$(option);ctrl.defaulOptionsData.push({linkVal:$option.val(),dispVal:$option.text()});});},setDisplayValue:function(val){if(this.displayElem){return this.displayElem.val(val);}
return false;},getDisplayValue:function(){if(this.displayElem){return this.displayElem.val();}
return false;},setValue:function(value,triggerEvent,updContext){if(this.freeInput){this.setLookupValue(value,triggerEvent,value,updContext);return;}
var ctrl=this,multiselection=this.multiSelectionAllowed&&Runner.isArray(value),ajaxParams={searchByLinkField:true,pageType:this.pageType,table:this.shortTableName,searchField:this.goodFieldName,searchFor:multiselection?value.join(","):value,isExistParent:!!this.parentCtrls.length?1:0,parentCtrlsData:JSON.stringify(this.getParentControlsData()),multiselection:multiselection,data:JSON.stringify(this.getControlsData()),masterTable:this.pageObj.masterTable};Runner.runnerAJAX(Runner.getPageUrl("lookupsuggest"),ajaxParams,function(respObj){if(!respObj.success){return false;}
var data=respObj.data,i,j;for(i=0,j=0;i<data.length-1;i=i+2,j++){if(multiselection&&$.inArray(data[i],value)!==-1||data[i]==value){ctrl.setLookupValue(data[i],triggerEvent,data[i+1],updContext);}}});},setLookupValue:function(linkVal,triggerEvent,dispVal,updContext){var readOnly=this.isReadonly(),changed,isSetDispVal;if(readOnly){this.makeReadWrite();}
if(this.multiSelectionAllowed){this.addMultiselectOption(linkVal,dispVal);readOnly&&this.makeReadonly();return;}
changed=this.valueElem.val()!==linkVal;if(this.displayElem){changed=changed||this.displayElem.val()!==dispVal;}
if(changed){this.valueElem.val(linkVal);isSetDispVal=this.setDisplayValue(dispVal);}
if(isSetDispVal===false){changed=false;}
if(readOnly){this.makeReadonly();}
if(changed&&triggerEvent===true){this.fireEvent("change",updContext,true);}
return changed;},getValue:function(returnArray){if(!this.multiSelectionAllowed){return this.valueElem.val();}
var optionValues=[];$('option:selected',this.valueElem).each(function(ind,option){optionValues.push(option.value);})
if(returnArray||optionValues.length>1){return optionValues;}
if(optionValues.length===1){return optionValues[0];}
return"";},reset:function(updContext){var ctrl=this;this.clearInvalid();if(!this.multiSelectionAllowed){this.setLookupValue(this.defaultValue[0],true,this.defaultValue[1],updContext);return;}
this.removeMultiselectOptions(!!this.defaulOptionsData.length);$.each(this.defaulOptionsData,function(idx,optionData){ctrl.addMultiselectOption(optionData['linkVal'],optionData['dispVal'],true);});this.fireEvent("change",updContext);},setDisabled:function(){if(this.multiSelectionAllowed){$('option',this.valueElem).prop('disabled',true);}
if(this.displayElem){this.displayElem.prop('disabled',true);}
return this.displayElem||this.multiSelectionAllowed;},setEnabled:function(){if(this.multiSelectionAllowed){$('option',this.valueElem).prop('disabled',false);}
if(this.displayElem){this.displayElem.prop('disabled',false);}
return this.displayElem||this.multiSelectionAllowed;},setFocus:function(triggerEvent){this.isSetFocus=false;if(!this.displayElem||!this.displayElem.length||this.displayElem.prop("disabled")){return;}
this.displayElem.get(0).focus();this.isSetFocus=true;if(triggerEvent===true){this.fireEvent("focus");}},removeCSS:function(className){this.displayElem.removeClass(className);},removeClass:function(className){var $displayElem=this.getDispElem();$displayElem.removeClass(className);},addCSS:function(className){this.displayElem.addClass(className);},addClass:function(className){var $displayElem=this.getDispElem();$displayElem.addClass(className);},getAttr:function(attrName){return this.displayElem.attr(attrName);},getDispElem:function(){if(this.multiSelectionAllowed){return this.valueElem.data('chosen').container;}
return this.displayElem;},isEmpty:function(){if(!this.multiSelectionAllowed){return this.getDisplayValue().toString()=="";}
return this.getValue(true).length==0;},preload:function(vals,selectValue){for(var i=0;i<vals.length-1;i=i+2){if(this.multiSelectionAllowed&&$.inArray(vals[i],selectValue)!==-1||!this.multiSelectionAllowed&&vals[i]===selectValue){this.setLookupValue(vals[i],false,vals[i+1]);}}},processAutofillDataOnReload:function(updContext){if(updContext&&updContext.values&&updContext.values[this.fieldName]){this.removeMultiselectOptions();var triggerEvent=this.getValue()!=updContext.values[this.fieldName][0];if(updContext.values[this.fieldName].length==2){this.setLookupValue(updContext.values[this.fieldName][0],triggerEvent,updContext.values[this.fieldName][1],updContext);}else{this.setValue(updContext.values[this.fieldName],triggerEvent,updContext);}}},updateLookupData:function(data,selectedValues,updContext){this.clearTextLookup();if(data.length==2){this.setLookupValue(data[0],selectedValues!=data[0],data[1],updContext);this.removeClass("highlight");}else{this.setValue(selectedValues);}},initToolTip:function(text,pageObj){if(this.mode===Runner.controls.constants.MODE_SEARCH){return;}
var options=this.getTooltipOptions(text,pageObj);this.displayElem.addClass('titleHintBox').inputHintBox(options);this.initToolTip=Runner.emptyFn;},getTooltipOptions:function(text,pageObj){return{div:$('#shiny_box'),div_sub:'.shiny_box_body',html:text,isFly:pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP,el:this.getToolTipPositionElem()};},makeReadonly:function(){if(!this.appearOnPage()){return false;}
this.addNew.hide();this.displayElem.prop({"disabled":true,"readonly":true});if(this.multiSelectionAllowed){$('option',this.valueElem).prop('disabled',true);}},makeReadWrite:function(){if(!this.appearOnPage()){return false;}
this.addNew.show();this.displayElem.prop({"disabled":false,"readonly":false});if(this.multiSelectionAllowed){$('option',this.valueElem).prop('disabled',false);}},getDefaultControlValue:function(){if(!this.multiSelectionAllowed){return this.defaultValue[0];}
if(this.defaultValue[0]===''){return'';}
return this.getStringValue(this.defaultValue);},getMultiselectOption:function(linkVal){return $('option',this.valueElem).filter(function(){return this.value==linkVal;});},addMultiselectOption:function(linkVal,dispVal,notFireChangeEvent){if(!this.multiSelectionAllowed||this.getMultiselectOption(linkVal).length){return;}
$('<option selected="selected"></option>').attr('value',linkVal).text(dispVal).appendTo(this.valueElem);this.valueElem.trigger("chosen:updated");if(!notFireChangeEvent){this.fireEvent("change");}},clear:function(){this.clearInvalid();this.clearTextLookup();},clearTextLookup:function(){if(this.multiSelectionAllowed){$('option',this.valueElem).remove();this.valueElem.trigger("chosen:updated");return;}
this.setLookupValue('',false,'');},removeMultiselectOptions:function(notFireChangeEvent){if(this.multiSelectionAllowed){$('option',this.valueElem).remove();if(!notFireChangeEvent){this.valueElem.trigger("chosen:updated");this.fireEvent("change");}}},removeMultiselectOption:function(linkVal){if(!this.multiSelectionAllowed){return;}
this.getMultiselectOption(linkVal).remove();this.valueElem.trigger("chosen:updated");this.fireEvent("change");},"editing":function(nullEvent,updateContext){this.reloadDependentCtrls(updateContext,nullEvent);},"edited":function(nullEvent,updateContext){var valArr=this.getPreparedValidationArray();if(valArr.length){this.validate(valArr);}
this.clearInvalidOnDependences();}});Runner.controls.EditBoxLookup=Runner.extend(Runner.controls.TextFieldLookup,{focusState:false,cursor:-1,suggestValues:null,lookupValues:null,lookupDivId:"",lookupDiv:null,lookupIframe:null,isSetSuggestVal:false,freeInput:false,isError:false,submitTimout:null,simpleSearchControlMode:false,ajaxTask:null,onChangeTask:null,constructor:function(cfg){this.suggestValues=[];this.lookupValues=[];Runner.controls.EditBoxLookup.superclass.constructor.call(this,cfg);this.freeInput=this.freeInput||this.mode==Runner.controls.constants.MODE_SEARCH;this.lookupDivId='lookupSuggest_'+this.valContId;this.delegateSuggestsContainerDestroying();this.ajaxTask=new Runner.util.DelayedTask(this.lookupAjax,this);this.onChangeTask=new Runner.util.DelayedTask(function(){this.fireEvent("change");},this);},assignValueElem:function(){Runner.controls.EditBoxLookup.superclass.assignValueElem.call(this);this.simpleSearchControlMode=!this.multiSelectionAllowed&&this.displayElem.data("simpleSearchMode");},initMultiselectionWithTabs:function(){if(!this.multiSelectionAllowed){return;}
Runner.controls.EditBoxLookup.superclass.initMultiselectionWithTabs.call(this);var chosenCtrl=this.valueElem.data('chosen');this.displayElem=chosenCtrl.search_field.unbind('keyup.chosen').unbind('keydown.chosen').width(100);},assignsElemsForEvent:function(){this.elemsForEvent=[this.displayElem.get(0)];},assignListOfEvents:function(){this.addEvent(["focus","keydown","input"]);Runner.controls.EditBoxLookup.superclass.assignListOfEvents.call(this);},addEditEditingListeners:function(){this.on("change",function(e,updateContext,lookupValueSet){updateContext=updateContext&&typeof updateContext==="object"?updateContext:{};if(e===null&&(lookupValueSet||this.multiSelectionAllowed)){this.fireEvent("edited",updateContext);}});this.on("input",function(e){this.fireEvent("editing");});},delegateSuggestsContainerDestroying:function(){var ctrl=this,destroySuggestDivDelegate=function(e){$target=$(e.target);if(!$target.hasClass("suggest_link_over")&&!$target.hasClass("suggest_link")){ctrl.destroyDiv();}};$('body, a').on('click',destroySuggestDivDelegate);$('body').on('click','input',destroySuggestDivDelegate);},setFrame:function(errorHappend){this.isError=errorHappend&&this.getDisplayValue()!==""&&!this.freeInput;if(this.isError){if(this.pageObj.isBootstrap()){$('[data-signal-error-for='+this.goodFieldName+this.rowId+']').addClass('has-error',true);}
else{this.addClass("highlight");}}
else{if(this.pageObj.isBootstrap()){$('[data-signal-error-for='+this.goodFieldName+this.rowId+']').removeClass('has-error',true);}
else{this.removeClass("highlight");}}},reset:function(updContext){Runner.controls.EditBoxLookup.superclass.reset.call(this,updContext);this.setFrame(false);},destructor:function(){Runner.controls.EditBoxLookup.superclass.destructor.call(this);this.destroyDiv();this.ajaxTask.cancel();this.onChangeTask.cancel();},isEmpty:function(){return Runner.controls.EditBoxLookup.superclass.isEmpty.call(this)||this.isError;},"input":function(e){var changed;if(this.freeInput&&!this.multiSelectionAllowed){changed=this.getDisplayValue()!==this.getValue();this.setLookupValue(this.getDisplayValue(),false,this.getDisplayValue());if(changed){this.onChangeTask.delay(500);}}
if(this.getDisplayValue()===""){this.ajaxTask.cancel();this.destroyDiv();this.setFrame(false);this.setValue("",true);return;}
this.isSetSuggestVal=false;this.ajaxTask.delay(500);},"keydown":function(e){switch(e.keyCode){case 38:this.moveUp();break;case 40:this.moveDown();break;case 13:if(this.multiSelectionAllowed){this.setSuggestValueToControl(this.lookupValues[this.cursor],this.suggestValues[this.cursor].replace(/\<(\/b|b)\>/gi,""));}
this.destroyDiv();this.stopEvent(e);return;}},showSuggests:function(divsArr){this.destroyDiv();if(!divsArr.length){return;}
this.lookupDiv=$('<div id="'+this.lookupDivId+'" class="search_suggest"></div>').css("visibility","visible").appendTo(document.body).on('mouseenter',function(e){$(this).data("hovered",true);}).on('mouseleave',function(e){$(this).data("hovered",false);});for(var i=0;i<divsArr.length;i++){this.lookupDiv.append(divsArr[i]);}
this.setDivPos();},destroyDiv:function(){if(this.lookupDiv){this.lookupDiv.remove();}
this.cursor=-1;this.lookupDiv=null;},setDivPos:function(){if(!this.lookupDiv){return;}
var $displayedElem=this.getDispElem(),dElementOffset=$displayedElem.offset();this.lookupDiv.css({top:dElementOffset.top+$displayedElem.outerHeight()+"px",left:dElementOffset.left+(Runner.isDirRTL()?$displayedElem.outerWidth()-this.lookupDiv.outerWidth():0)+"px"});if(this.pageObj.isBootstrap()){this.lookupDiv.addClass('dropdown-menu').css({display:"block",width:$displayedElem.width()+"px"});}
this.lookupDiv.css("z-index",2000);},suggestOver:function(divHovered){this.cursor=Number(divHovered.id.substring(10));this.dispSuggestVal(true);},suggestOut:function(divValue){divValue.className='suggest_link';this.isSetSuggestVal=false;},lookupAjax:function(){var ctrl=this,ajaxParams={table:Runner.pages.PageSettings.getShortTName(this.table),pageType:this.pageType,searchFor:this.getDisplayValue(),searchField:this.goodFieldName,isExistParent:!!this.parentCtrls.length?1:0,parentCtrlsData:JSON.stringify(this.getParentControlsData()),data:JSON.stringify(this.getControlsData()),masterTable:this.pageObj.masterTable};ctrl.focusState=true;Runner.runnerAJAX(Runner.getPageUrl("lookupsuggest"),ajaxParams,function(respObj){if(!respObj.success){ctrl.setFrame(true);ctrl.destroyDiv();return;}
var data=respObj.data,dispVal=ctrl.getDisplayValue(),found=ctrl.freeInput,divsArr=[],i,j,eventsFlag;ctrl.suggestValues=[];ctrl.lookupValues=[];for(i=0,j=0;i<data.length-1;i=i+2,j++){if(ctrl.focusState){divsArr.push(ctrl.getSuggestContainer('suggestDiv'+j,data[i+1],data[i]));}
ctrl.suggestValues[j]=data[i+1];ctrl.lookupValues[j]=data[i];if(!found&&ctrl.suggestValues[j]==dispVal){eventsFlag=ctrl.lookupValues[j]!==ctrl.getValue();ctrl.setLookupValue(ctrl.lookupValues[j],true,ctrl.suggestValues[j]);found=true;}}
ctrl.setFrame(!found);if(!found&&!ctrl.multiSelectionAllowed){eventsFlag=ctrl.getValue()!=="";ctrl.setLookupValue("",eventsFlag,dispVal);}
if(!ctrl.focusState){return;}
ctrl.showSuggests(divsArr);});},getSuggestContainer:function(containerId,suggestValue,lookupValue){var ctrl=this;return $('<div id="'+containerId+'" class="suggest_link"></div>').css("cursor","pointer").html(suggestValue).bind("mouseover",function(){ctrl.suggestOver(this);}).bind("mouseout",function(){ctrl.suggestOut(this);}).bind("click",function(){ctrl.setFrame(false);ctrl.setSuggestValueToControl(lookupValue,suggestValue);ctrl.destroyDiv();});},moveDown:function(){if(!this.lookupDiv){return;}
var $suggests=this.lookupDiv.children();if(!$suggests.length||this.cursor>=$suggests.length){return;}
this.cursor++;this.dispSuggestVal();if(this.cursor==$suggests.length){this.cursor=-1;this.focus();}},moveUp:function(){if(!this.lookupDiv){return;}
var $suggests=this.lookupDiv.children();if(!$suggests.length||this.cursor<-1){return;}
this.cursor--;if(this.cursor==-2){this.cursor=$suggests.length-1;this.focus();}
this.dispSuggestVal();},dispSuggestVal:function(hover){var ctrl=this;this.lookupDiv.children().each(function(index,suggest){var suggestVal,lookupVal;suggest.className=index===ctrl.cursor?"suggest_link_over":"suggest_link";if(index!==ctrl.cursor){return;}
if(hover){ctrl.isSetSuggestVal=true;return;}
suggestVal=ctrl.suggestValues[ctrl.cursor].replace(/\<(\/b|b)\>/gi,"");lookupVal=ctrl.lookupValues[ctrl.cursor];if(ctrl.getValue()!=lookupVal){ctrl.setFrame(false);}
if(!ctrl.multiSelectionAllowed){ctrl.setLookupValue(lookupVal,true,suggestVal);}});},setDisabled:function(){var res=Runner.controls.EditBoxLookup.superclass.setDisabled.call(this);if(res){this.addNew.css('visibility','hidden');}
return res;},setEnabled:function(){var res=Runner.controls.EditBoxLookup.superclass.setEnabled.call(this);if(res){this.addNew.css('visibility','visible');}
return res;},"blur":function(e){var ctrl=this,dispValue=this.getDisplayValue();if(this.freeInput&&this.multiSelectionAllowed&&(!this.lookupDiv||!this.lookupDiv.data('hovered'))&&dispValue.trim()!==""){this.setSuggestValueToControl(dispValue,dispValue);}
this.focusState=false;if(!this.multiSelectionAllowed&&!this.freeInput&&!this.isSetSuggestVal&&this.suggestValues.length){this.setFrame(dispValue!==""&&$.inArray(dispValue,this.suggestValues)===-1);}
if(this.multiSelectionAllowed&&!this.freeInput){this.setFrame(false);}
setTimeout(function(){ctrl.destroyDiv();if(ctrl.multiSelectionAllowed){ctrl.displayElem.width(100);}},500);this.stopEvent(e);this.isSetFocus=false;if(this.ajaxTask.started()){this.ajaxTask.delay(0);}
if(this.onChangeTask.started()){this.onChangeTask.delay(0);}},"focus":function(e){if(!this.multiSelectionAllowed){this.stopEvent(e);}
this.focusState=true;},getStringValue:function(valueArray){if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.simpleSearchControlMode){return this.getDisplayValue();}
if(this.multiSelectionAllowed){var valsArr=valueArray||this.getValue(true),i;for(i=0;i<valsArr.length;i++){if(valsArr[i].indexOf(',')!==-1||valsArr[i].indexOf('"')!==-1){valsArr[i]='"'+valsArr[i].replace(/"/g,'""')+'"';}}
return valsArr.join(",");}
return this.getValue();},updateAppearance:function(searchOption){if(this.multiSelectionAllowed){return;}
var simpleControlOptions=["Contains","NOT Contains","Starts with","NOT Starts with"];this.simpleSearchControlMode=$.inArray(searchOption,simpleControlOptions)!==-1;},preload:function(vals,selectValue){if(this.simpleSearchControlMode){return;}
if(this.freeInput&&this.multiSelectionAllowed){for(var i=0;i<selectValue.length;i++){this.setLookupValue(selectValue[i],false,selectValue[i]);}
return;}
Runner.controls.EditBoxLookup.superclass.preload.call(this,vals,selectValue);},reload:function(updContext){if(this.simpleSearchControlMode){return;}
Runner.controls.EditBoxLookup.superclass.reload.call(this,updContext);},getForSubmit:function(){if(!this.appearOnPage()){return[];}
var cloneElem=this.valueElem.clone(),$options;if(this.multiSelectionAllowed){$options=$('option',cloneElem).prop('selected',true);if(!$options.length){cloneElem.append('<option selected="selected" value=""></option>');}
return[cloneElem];}
if(this.freeInput||!this.multiSelectionAllowed&&this.getDisplayValue()===""){return[cloneElem.val(this.displayElem.val())];}
return[cloneElem.val(this.valueElem.val())];},processNewFlyAdded:function(text,value){if(!this.suggestValues){return;}
this.suggestValues.push(text);this.lookupValues.push(value);this.setSuggestValueToControl(value,text);this.setFrame(false);},getTooltipOptions:function(text,pageObj){var options=Runner.controls.EditBoxLookup.superclass.getTooltipOptions.call(this,text,pageObj);if(!this.freeInput){options.incrementLeft=4;}
return options;},setSuggestValueToControl:function(linkVal,dispVal){if(!this.multiSelectionAllowed){this.setLookupValue(linkVal,true,dispVal);return;}
$option=this.getMultiselectOption(linkVal);if(!$option.length){this.addMultiselectOption(linkVal,dispVal);}},reloadDependentCtrls:function(updContext,e){if(this.freeInput||e===null){Runner.controls.EditBoxLookup.superclass.reloadDependentCtrls.call(this,updContext,e);}}});Runner.controls.ListPageLookup=Runner.extend(Runner.controls.TextFieldLookup,{selectLinkElem:null,lookupVals:null,constructor:function(cfg){Runner.controls.ListPageLookup.superclass.constructor.call(this,cfg);this.initClearableInput();this.initSelectLink();this.initChanginAppearance();},assignListOfEvents:function(){Runner.controls.ListPageLookup.superclass.assignListOfEvents.call(this);if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")){this.addEvent(["keyup"]);}},assignsElemsForEvent:function(){Runner.controls.ListPageLookup.superclass.assignsElemsForEvent.call(this);if(this.mode===Runner.controls.constants.MODE_SEARCH&&this.valueElem.data("usesuggests")){this.elemsForEvent.push(this.displayElem.get(0));}},initSelectLink:function(){var ctrl=this,pageParams={tName:this.lookupTable,pageType:Runner.pages.constants.PAGE_LIST,lookupCtrl:this,modal:true,baseParams:{firstTime:1,parId:this.rowId,table:this.table,field:this.fieldName,pageType:this.pageType,mode:Runner.pages.constants.MODE_LOOKUP,mainRecordMasterTable:this.masterTName},afterCreateHn:function(){ctrl.lookupVals=this.controlsMap.lookupVals;ctrl.dispFieldAlias=this.controlsMap.dispFieldAlias;}},selectLinkId="open_lookup_"+this.goodFieldName+"_"+this.rowId;this.selectLinkElem=$("#"+selectLinkId).on("click",function(e){if(ctrl.selectLinkElem.hasClass("disabled")){return false;}
if($("#search_suggest").length>0&&typeof DestroySuggestDiv!="undefined"){DestroySuggestDiv();}
if(!!ctrl.parentCtrls.length){pageParams.baseParams.parentsExist=true;pageParams.baseParams.parentCtrlsData=JSON.stringify(ctrl.getParentControlsData());}
pageParams.baseParams.data=JSON.stringify(ctrl.getControlsData());ctrl.pageId=Runner.pages.PageManager.openPage(pageParams);ctrl.setDisabled();return false;});},getLookupParams:function(pageId){var lookupParams={id:pageId,table:this.table,field:this.fieldName,pageType:this.pageType,mode:Runner.pages.constants.MODE_LOOKUP,data:JSON.stringify(this.getControlsData()),mainRecordMasterTable:this.masterTName};if(!!this.parentCtrls.length){lookupParams.parentsExist=true;lookupParams.parentCtrlsData=JSON.stringify(this.getParentControlsData());}
return lookupParams;},initMultiselectionWithTabs:function(){if(!this.multiSelectionAllowed){return;}
Runner.controls.ListPageLookup.superclass.initMultiselectionWithTabs.call(this);var ctrl=this,chosenCtrl=this.valueElem.data("chosen");chosenCtrl.search_field.prop('readonly',true);chosenCtrl.container.on('click',function(e){ctrl.selectLinkElem.trigger('click');});},getToolTipPositionElem:function(){return this.selectLinkElem;},initChanginAppearance:function(){if(this.mode!==Runner.controls.constants.MODE_SEARCH||this.multiSelectionAllowed){this.updateAppearance=Runner.emptyFn;return;}
var ctrl=this;this.displayElem.on("change",function(e){var dispVal=$(this).val();ctrl.setLookupValue(dispVal,true,dispVal);}).on("keyup",function(e){if(!Runner.isAcceptableKeyCode(e)){return;}
var dispVal=$(this).val();ctrl.setLookupValue(dispVal,true,dispVal);});},updateAppearance:function(searchOption){var simpleControlOptions=["Contains","NOT Contains","Starts with","NOT Starts with"];if($.inArray(searchOption,simpleControlOptions)===-1){this.displayElem.prop('readonly',true);this.selectLinkElem.css('visibility','visible');return;}
this.displayElem.prop('readonly',false);this.selectLinkElem.css('visibility','hidden');},preload:function(vals,selectValue){if(!this.multiSelectionAllowed&&!this.displayElem.prop('readonly')){return;}
Runner.controls.ListPageLookup.superclass.preload.call(this,vals,selectValue);},reload:function(updContext){if(!this.multiSelectionAllowed&&!this.displayElem.prop('readonly')){return;}
Runner.controls.ListPageLookup.superclass.reload.call(this,updContext);},implySuggests:function(){return!this.multiSelectionAllowed&&!this.displayElem.prop('readonly');},setDisabled:function(){var res=Runner.controls.ListPageLookup.superclass.setDisabled.call(this);if(res&&this.selectLinkElem){this.selectLinkElem.css('visibility','hidden').addClass('disabled');}
return res;},setEnabled:function(){var res=Runner.controls.ListPageLookup.superclass.setEnabled.call(this);if(res&&this.selectLinkElem){this.selectLinkElem.css('visibility','visible').removeClass('disabled');}
return res;},setValByInd:function(valInd){var $option,linkVal=this.lookupVals[valInd].linkVal,dispVal=this.lookupVals[valInd].dispVal;if(!this.multiSelectionAllowed){this.setLookupValue(linkVal,true,dispVal);return;}
$option=this.getMultiselectOption(linkVal);if(!$option.length){this.addMultiselectOption(linkVal,dispVal);}},addLookupVal:function(linkVal,dispVal){return this.lookupVals.push({'linkVal':linkVal,'dispVal':dispVal})-1;},makeReadonly:function(){Runner.controls.ListPageLookup.superclass.makeReadonly.call(this);this.selectLinkElem.addClass('disabled').hide();},makeReadWrite:function(){Runner.controls.ListPageLookup.superclass.makeReadWrite.call(this);this.selectLinkElem.removeClass('disabled').show();},setValue:function(value,triggerEvent,updContext){Runner.controls.ListPageLookup.superclass.setValue.call(this,value,triggerEvent,updContext);if(this.multiSelectionAllowed){this.valueElem.trigger("chosen:updated");}
return true;},getForSubmit:function(){if(!this.multiSelectionAllowed){return Runner.controls.ListPageLookup.superclass.getForSubmit.call(this);}
if(!this.appearOnPage()){return[];}
var cloneElem=this.valueElem.clone(),$options=$('option',cloneElem).prop('selected',true);if(!$options.length){cloneElem.append('<option selected="selected" value=""></option>');}
return[cloneElem];},getStringValue:function(valueArray){if(!this.multiSelectionAllowed){return Runner.controls.ListPageLookup.superclass.getStringValue.call(this);}
var valsArr=valueArray||this.getValue(true),i;for(i=0;i<valsArr.length;i++){if(valsArr[i].indexOf(',')!==-1||valsArr[i].indexOf('"')!==-1){valsArr[i]='"'+valsArr[i].replace(/"/g,'""')+'"';}}
return valsArr.join(",");},useSearchSuggests:function(){return this.mode===Runner.controls.constants.MODE_SEARCH&&!this.multiSelectionAllowed&&this.valueElem.data("usesuggests");},initClearableInput:function(){var $valueElem=this.valueElem,iconSize=this.pageObj.isBootstrap()?25:18;this.displayElem.on('mousemove',function(e){if(this.value){$(this).toggleClass('onX',Runner.isDirRTL()?iconSize>e.clientX-this.getBoundingClientRect().left:this.offsetWidth-iconSize<e.clientX-this.getBoundingClientRect().left);}}).on('touchstart click',function(e){if(Runner.isDirRTL()?iconSize>e.clientX-this.getBoundingClientRect().left:this.offsetWidth-iconSize<e.clientX-this.getBoundingClientRect().left&&this.value){e.preventDefault();$valueElem.val('');$(this).removeClass('x onX').val('').change();}});}});Runner.namespace('Runner.pages');Runner.pages.constants={NOT_TABLE_BASED_TNAME:".global",PAGE_LIST:"list",PAGE_ADD:"add",PAGE_INLINE_ADD:"inline_add",PAGE_EDIT:"edit",PAGE_INLINE_EDIT:"inline_edit",PAGE_VIEW:"view",PAGE_SEARCH:"search",PAGE_REPORT:"report",PAGE_CHART:"chart",PAGE_DREPORT:"dreport",PAGE_DCHART:"dchart",PAGE_PRINT:"print",PAGE_REPORT_PRINT:"rprint",PAGE_EXPORT:"export",PAGE_IMPORT:"import",PAGE_ADMIN_MEMBERS:"admin_members",PAGE_ADMIN_RIGHTS:"admin_rights",PAGE_MASTER_INFO_LIST:"masterlist",PAGE_MASTER_INFO_PRINT:"masterprint",PAGE_REGISTER:"register",PAGE_MENU:"menu",PAGE_REMIND:"remind",PAGE_CHANGEPASS:"changepwd",PAGE_LOGIN:"login",PAGE_DASHBOARD:"dashboard",PAGE_DASHMAP:"map",LIST_SIMPLE:0,LIST_LOOKUP:1,LIST_DETAILS:3,LIST_AJAX:4,RIGHTS_PAGE:5,MEMBERS_PAGE:6,LIST_DASHBOARD:7,LIST_DASHDETAILS:8,MAP_DASHBOARD:9,GRIDBASED_MAP_DASHBOARD:10,CHART_SIMPLE:0,CHART_POPUPDETAILS:1,CHART_DASHBOARD:2,CHART_DETAILS:3,CHART_DASHDETAILS:4,ADD_SIMPLE:0,ADD_INLINE:1,ADD_ONTHEFLY:2,ADD_MASTER:3,ADD_POPUP:4,ADD_DASHBOARD:5,ADD_MASTER_POPUP:6,ADD_MASTER_DASH:7,EDIT_SIMPLE:0,EDIT_INLINE:1,EDIT_ONTHEFLY:2,EDIT_POPUP:3,EDIT_DASHBOARD:4,EDIT_SELECTED_SIMPLE:5,EDIT_SELECTED_POPUP:6,SEARCH_DASHBOARD:1,MODE_AJAX:"ajax",MODE_SIMPLE:"",MODE_LOOKUP:"lookup",MODE_LIST_DETAILS:"listdetails",OPENMODE_POPUP:1,OPENMODE_CONTAINER:2,OPENMODE_PRELOADED:3,OPENMODE_FULLSCREEN:4,OPENMODE_DASHCONTAINER:5,OPENMODE_DASHTABS:6,OPENMODE_TABVIEW:7,OPENMODE_PRELOADED_CONTAINER:8,DP_POPUP:0,DP_INLINE:1,DP_NONE:2,DL_SINGLE:0,DL_INDIVIDUAL:1,DL_NONE:2,SEARCH_OPTIONS:{"Contains":"contains","Equals":"equals","Starts with":"startswith","More than":"morethan","Less than":"lessthan","Between":"between","Empty":"empty","NOT Contains":"notcontain","NOT Equals":"notequal","NOT Starts with":"notstartwith","NOT More than":"lessequal","NOT Less than":"moreequal","NOT Between":"notbetween","NOT Empty":"notempty"},MINUS_GIF:Runner.getFullResourcePath("images/minus.gif"),PLUS_GIF:Runner.getFullResourcePath("images/plus.gif"),CLOSE_RED_GIF:"remove",OK_GIF:"iesave",CANCEL_GIF:"iecancel",HORIZONTAL_LAYOUT:0,VERTICAL_LAYOUT:1,COLUMNS_LAYOUT:2,FLEXIBLE_LAYOUT:3,LOGIN_SEPARATE:0,LOGIN_POPUP:1,LOGIN_EMBEDED:2,PORTRAIT_PRINT_ORIENTATION:0,LANDSCAPE_PRINT_ORIENTATION:1,STEPPED_LAYOUT:0,BLOCK_LAYOUT:1,OUTLINE1_LAYOUT:2,ALIGN1_LAYOUT:3,TABULAR_LAYOUT:6,REPORT_MODE_PRINT_FRIENDLY:0,REPORT_MODE_PRINT_WHOLE_REPORT:1,REPORT_PRINT_PAGE_FIT:0,REPORT_PRINT_FIXED_GROUPS:1,REPORT_TYPE_STANDART:0,REPORT_TYPE_CROSSTAB:1,REPORT_SIMPLE:0,REPORT_POPUPDETAILS:1,REPORT_DASHBOARD:2,REPORT_DETAILS:3,REPORT_DASHDETAILS:4,VPRINT_PAGE_WIDTH:700,VPRINT_PAGE_HEIGHT:900,HPRINT_PAGE_WIDTH:1000,HPRINT_PAGE_HEIGHT:700,DASHBOARD_LIST:0,DASHBOARD_CHART:1,DASHBOARD_REPORT:2,DASHBOARD_RECORD:3,DASHBOARD_SEARCH:4,DASHBOARD_DETAILS:5,DASHBOARD_MAP:6,DASHBOARD_SNIPPET:7,AA_TO_LIST:0,AA_TO_ADD:1,AA_TO_VIEW:2,AA_TO_EDIT:3,AA_TO_DETAIL_ADD:4,AA_TO_DETAIL_LIST:5,AE_TO_LIST:0,AE_TO_EDIT:1,AE_TO_VIEW:2,AE_TO_NEXT_EDIT:3,AE_TO_PREV_EDIT:4,AE_TO_DETAIL_LIST:5,titTABLE:0,titVIEW:1,titREPORT:2,titCHART:3,titDASHBOARD:4,BOOTSTRAP_LAYOUT:3,SMALL_MODAL_WIDTH:700,SSEARCH_PARAMS_TYPE:1,CRESIZE_PARAMS_TYPE:2,SHFIELDS_PARAMS_TYPE:3,FORDER_PARAMS_TYPE:4,DESKTOP:1,TABLET_10_IN:2,TABLET_7_IN:3,SMARTPHONE_LANDSCAPE:4,SMARTPHONE_PORTRAIT:5};Runner.apply(Runner,Runner.pages.constants);Runner.namespace('Runner.util.inlineEditing');Runner.util.inlineEditing.InlineEditor=Runner.extend(Runner.util.Observable,{id:-1,tName:"",pageType:"",shortTName:"",rowPref:"gridRow",rows:null,fNames:null,totalFields:null,ajaxRequestUrl:"",baseParams:null,pageObj:null,saveAllButt:null,cancelAllButt:null,massRecButtEditMode:false,loadSettings:false,isEditOwn:false,isOldLayout:false,rowFocussed:false,classNameHidden:"",classNameRow:"",classNameBottomRow:"",classNameMessage:"",classNameInlineError:"",classNameLocking:"",dashGridBased:false,rowsOrderData:[],lookupParams:null,lookupFieldInfo:null,showEditInPopup:false,showViewInPopup:false,constructor:function(cfg){this.rows=[];this.fNames=[];this.baseParams={};Runner.apply(this,cfg);this.showEditInPopup=Runner.pages.PageSettings.getTableData(this.tName,"showEditInPopup")&&!Runner.isMobile;this.showViewInPopup=Runner.pages.PageSettings.getTableData(this.tName,"showViewInPopup")&&!Runner.isMobile;Runner.util.inlineEditing.InlineEditor.superclass.constructor.call(this,cfg);this.pageObj=Runner.pages.PageManager.getAt(this.tName,this.id);this.isEditOwn=Runner.pages.PageSettings.getTableData(this.tName,"isEditOwn");this.totalFields=Runner.pages.PageSettings.getTableData(this.tName,"totalFields");this.ajaxRequestUrl=Runner.getPageUrl(this.shortTName,this.pageType);this.listGridLayout=Runner.pages.PageSettings.getTableData(this.tName,"listGridLayout");this.assignClassNames();this.addEvents('rowsEdited','createControls','beforeSubmit','afterSubmit','afterSave','submitFailed','beforeProcessNewRow','revertRow','validationFailed','afterInit','afterPageReady','beforeRequestControls','recalcGridSize','beforeCancel','cancel');},assignClassNames:function(){var classPrefix=this.isOldLayout?'runner-':'rnr-';this.classNameHidden=classPrefix+"hiddenelem";this.classNameRow=classPrefix+"row";this.classNameBottomRow=classPrefix+"bottomrow";this.classNameMessage=classPrefix+"message";;this.classNameInlineError=classPrefix+"inline-error";this.classNameLocking=classPrefix+"locking";},getSubmitUrl:function(){return Runner.getPageUrl(this.shortTName,this.pageType);},init:function(){this.fillGridRowsData();this.initButtons();this.initEvents();},fillGridRowsData:function(){this.rowsOrderData=[];for(var i=0;i<this.rows.length;i++){this.rowsOrderData.push({id:this.rows[i].id,keys:this.rows[i].keys});}},initEvents:function(){var events=Runner.pages.PageSettings.getTableEventsData(this.tName,this.pageType),evName,eventHnArr,i;for(evName in events){if(evName!=='afterInit'&&evName!=='afterPageReady'){continue;}
eventHnArr=events[evName];for(i=0;i<eventHnArr.length;i++){this.on(evName,eventHnArr[i].hn,eventHnArr[i].scope||this.pageObj||this);}}
this.on('rowsEdited',function(){this.toggleMassRecButt();this.calcTotals();},this);},reInit:function(gridRows){this.rows=gridRows;this.fillGridRowsData();if(this.pageObj.pageMode===Runner.pages.constants.MODE_LIST_DETAILS||this.pageObj.pageMode===Runner.pages.constants.LIST_DASHBOARD){this.initButtons();}},resetSelectAll:function(){var $selectAllButton=$('#select_all'+this.id);if($selectAllButton.length){$selectAllButton.get(0).checkAllStatus=false;$selectAllButton.html(Runner.lang.constants.SELECT_ALL);}
if($('.chooseAll'+this.id).length){$('input[type="checkbox"][id^="chooseAll_'+this.id+'"]').prop("checked",false);}},initButtons:function(){var inlineObj=this;this.editAllButt=$("[id=edit_selected"+this.id+"]");this.cancelAllButt=$("[id=revertall_edited"+this.id+"]");this.saveAllButt=$("[id=saveall_edited"+this.id+"]").bind("click",function(e){inlineObj.saveAll();inlineObj.resetSelectAll();return false;});if(!this.pageObj.inlineButtonsIntialized){this.cancelAllButt.bind("click",function(e){inlineObj.cancelAll();inlineObj.resetSelectAll();return false;});}
this.pageObj.inlineButtonsIntialized=true;},reinitButtons:function(){this.initButtons();},parseForTotals:function(val,format){if(format=='Time'){var timeArr=val.split(':');if(timeArr.length!==3){return'';}
return parseInt(timeArr[2],10)+parseInt(timeArr[1],10)*60+parseInt(timeArr[0],10)*3600;}
if(format=='Number'){return parseFloat(val.replace(',','.'));}
return parseFloat(val.toString().trim());},calcTotalField:function(totalFieldData){var fName=totalFieldData.fName,format=totalFieldData.format,i,fVal,s,m,h,d,totalVal=0;for(i=0;i<this.rows.length;i++){if(!this.rows[i].data||this.rows[i].data[fName]===undefined){this.getValuesFromSpan(this.rows[i]);}
fVal=this.parseForTotals(this.getValueFromSpan(this.rows[i],fName),format);if(isNaN(fVal)){continue;}
totalVal+=fVal;}
if(format=='Number'){totalVal=totalVal.toFixed(totalFieldData.numberOfDigits);}else if(format=='Time'){s=totalVal%60;totalVal-=s;totalVal/=60;m=totalVal%60;totalVal-=m;totalVal/=60;h=totalVal%24;totalVal-=h;totalVal/=24;d=totalVal;totalVal=(d>0?d+'d ':'')+(h==0?'00':h)+':'+(m>9?m:(m==0?'00':'0'+m))+':'+(s>9?s:(s==0?'00':'0'+s));}
$("#total"+this.id+"_"+Runner.goodFieldName(fName)).html(totalVal);},calcCountField:function(fName,format){var fVal,i,row,fieldSpan,totalVal=0,gfName=Runner.goodFieldName(fName),totalId="total"+this.id+"_"+gfName;for(i=0;i<this.rows.length;i++){row=this.rows[i];if(row.rowVals&&typeof row.rowVals[fName]==="string"){fVal=row.rowVals[fName].trim();}else{fieldSpan=Runner.getFieldSpan(fName,row.id);fVal=fieldSpan.attr("val").trim();}
if(format==Runner.controls.constants.FORMAT_CHECKBOX&&(fVal==0||fVal==""||fVal=="False")){continue;}
if(fVal){totalVal++;}}
$("#"+totalId).html(totalVal);},calcAverageField:function(totalFieldData){var fName=totalFieldData.fName,format=totalFieldData.format,i,fVal,s,m,h,d,totalVal=0,numRows=0;for(i=0;i<this.rows.length;i++){if(!this.rows[i].data||this.rows[i].data[fName]===undefined){this.getValuesFromSpan(this.rows[i]);}
fVal=this.parseForTotals(this.getValueFromSpan(this.rows[i],fName),format);if(isNaN(fVal)){continue;}
totalVal+=fVal;numRows+=1;}
if(format=='Time'&&numRows){totalVal=Math.round(totalVal/numRows);s=totalVal%60;totalVal-=s;totalVal/=60;m=totalVal%60;totalVal-=m;totalVal/=60;h=totalVal%24;totalVal-=h;totalVal/=24;d=totalVal;totalVal=(d>0?d+'d ':'')+(h==0?'00':h)+':'+(m>9?m:(m==0?'00':'0'+m))+':'+(s>9?s:(s==0?'00':'0'+s));}else if(numRows){totalVal=Math.round((totalVal/numRows)*100)/100;if(format=='Number'){totalVal=totalVal.toFixed(totalFieldData.numberOfDigits);}}else{totalVal="";}
$("#total"+this.id+"_"+Runner.goodFieldName(fName)).html(totalVal);},calcTotals:function(){if(this.pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP||!this.totalFields.length){return;}
var totalsTr,i,totalField;for(i=0;i<this.totalFields.length;i++){totalField=this.totalFields[i];if(totalField.type=="TOTAL"){this.calcTotalField(totalField);continue;}
if(totalField.type=="COUNT"){this.calcCountField(totalField.fName,totalField.format);continue;}
if(totalField.type=="AVERAGE"){this.calcAverageField(totalField);}};totalsTr=$('tr[rowid="totals"]',this.pageObj.gridElem);if(totalsTr.css('display')=='none'){totalsTr.show();}},initForm:function(row){row.basicForm=row.basicForm||this.createRowForm(row);row.basicForm.id=row.id;row.basicForm.setFocus=!this.rowFocussed;row.basicForm.baseParams.id=row.id;row.basicForm.fieldControls=Runner.controls.ControlStorage.byId(row.id);if(this.dashGridBased){row.basicForm.baseParams.dashTName=this.pageObj.dashboard.tName;}},createRowForm:function(row){var inlineObj=this,baseParams=Runner.apply(this.baseParams,{id:row.id,editType:'inline',a:this.pageType===Runner.pages.constants.PAGE_ADD?'added':'edited',});return new Runner.form.BasicForm({isFileUpload:true,submitUrl:this.getSubmitUrl(),baseParams:baseParams,successSubmit:{fn:function(respObj,formObj,fieldControls){if(!respObj.success){if(respObj.fatalError){formObj.clearForm();}
this.fireEvent("submitFailed",respObj,this,formObj,fieldControls);inlineObj.makeError(respObj.message,row);}else{if(respObj['nonEditable']){row.isEditable=false;}
this.afterSubmit(row,respObj);if(typeof row.onAfterSubmit!="undefined"){row.onAfterSubmit();}}
if(row.saveLink){row.saveLink.removeClass('disabled');}},scope:this},submitFailed:{fn:function(respObj,formObj,fieldControls){if(respObj.success===false){this.makeError(respObj.message,row);}else{this.makeError(respObj,row);}
this.fireEvent("submitFailed",{},this,formObj,fieldControls);if(row.saveLink){row.saveLink.removeClass('disabled');}},scope:this},beforeSubmit:{fn:function(formObj){if(typeof row.onBeforeSubmit!="undefined"){var rowBeforeResult=row.onBeforeSubmit();if(rowBeforeResult===false){return false;}}
return this.fireEvent("beforeSubmit",row,this,formObj);},scope:this},validationFailed:{fn:function(formObj,fieldControls){this.fireEvent("validationFailed",formObj,fieldControls);inlineObj.rowFocussed=true;if(row.saveLink){row.saveLink.removeClass('disabled');}},scope:this}});},cancelAll:function(){var canceledAll=true,i;for(i=0;i<this.rows.length;i++){if(!this.rows[i].submitted){if(this.rows[i].isAdd){if(Runner.util.inlineEditing.InlineAdd.prototype.cancelButtonHn.call(this,this.rows[i],true)){i--;}else{canceledAll=false;}}else if(this.pageObj.inlineEdit){this.pageObj.inlineEdit.cancelButtonHn(this.rows[i],true);}}}
if(canceledAll){this.fireEvent("recalcGridSize");this.toggleMassRecButt();}},submit:function(row){row.revertted=false;this.initForm(row);row.basicForm.submit();},saveAll:function(){var allVals=[],allKeys=[],allRowIds=[];this.rowFocussed=false;for(var i=0,l=this.rows.length;i<l;i++){allVals.push(this.rows[i].data);allKeys.push(this.rows[i].keys);allRowIds.push(this.rows[i].id);if(this.rows[i].submitted===false&&this.rows[i].cancelLink.length){return false;}}
this.fireEvent('rowsEdited',allVals,this.fNames,allKeys,allRowIds);return true;},cancelButtonHn:function(){$('div.shiny_box').hide();},getControls:function(pageObj,row,hideRevertButt,hideSaveButt){var i,ind,inlineObject=this,masterKeys=pageObj.controlsMap.masterKeys,reqParams={id:row.id,editType:"inline",screenWidth:window.screen.width,screenHeight:window.screen.height,orientation:Runner.getOrientation(),masterpagetype:Runner.pages.PageSettings.getTableData(this.tName,"masterPageType")||"",isNeedSettings:this.loadSettings||!Runner.pages.PageSettings.checkSettings(this.tName)};if(this.lookupParams){reqParams=Runner.apply(reqParams,this.lookupParams);}
if(this.dashGridBased&&this.pageObj){reqParams['dashTName']=this.pageObj.dashboard.tName;}
for(ind in masterKeys){reqParams[ind.toLowerCase()]=masterKeys[ind];}
this.fireEvent('beforeRequestControls',this,row,reqParams);for(i=0;i<row.keys.length;i++){reqParams['editid'+(i+1)]=row.keys[i];}
if(pageObj.baseParams&&pageObj.baseParams.mastertable){reqParams.mastertable=pageObj.baseParams.mastertable;}
Runner.runnerAJAX(this.ajaxRequestUrl,reqParams,function(ctrlsJSON){var proxy;if(ctrlsJSON.success!==false){if(inlineObject.loadSettings&&ctrlsJSON.settings){Runner.pages.PageSettings.addSettings(inlineObject.tName,ctrlsJSON.settings,false);}
Runner.applyPagesData(ctrlsJSON.pagesData);proxy=jQuery.extend({},inlineObject.pageObj.proxy,Runner.pagesData[row.id].proxy);var init=function(){inlineObject.makeRowEditable(row,ctrlsJSON);inlineObject.lockRow(row,ctrlsJSON);inlineObject.getEditBlock(row,hideRevertButt,hideSaveButt);inlineObject.setFocusOntheFirstControl(row);if(Runner.pages.PageSettings.getGlobalData("s508"))
inlineObject.pageObj.s508Obj.s508inlineSaveCancel(row.id);inlineObject.fireEvent('afterInit',inlineObject.pageObj,proxy,row.id,row,inlineObject);};if(ctrlsJSON.additionalCSS){Runner.util.ScriptLoader.loadCSS(ctrlsJSON.additionalCSS);}
if(ctrlsJSON.additionalJS){for(var jsFile in ctrlsJSON.additionalJS){Runner.util.ScriptLoader.addJS([jsFile],ctrlsJSON.additionalJS[jsFile]);}
Runner.util.ScriptLoader.onFilesLoaded(function(){init();inlineObject.fireEvent('afterPageReady',inlineObject.pageObj,proxy,row.id,row,inlineObject);},inlineObject);Runner.util.ScriptLoader.load();return;}
init();}
inlineObject.makeError(ctrlsJSON.message,row);inlineObject.showRowButtons(row);});},getFieldLabelElement:function(row,field){var spanCont;if(this.pageObj.isBootstrap()&&this.listGridLayout===Runner.pages.constants.VERTICAL_LAYOUT){spanCont=Runner.getFieldSpan(field,row.id);return spanCont.closest('.bs-viewform-group').find('.bs-view-label');}else if(this.pageObj.isBootstrap()&&this.listGridLayout===Runner.pages.constants.COLUMNS_LAYOUT){spanCont=Runner.getFieldSpan(field,row.id);return spanCont.closest('table').find('[data-field="'+Runner.goodFieldName(field)+'"] > label');}
return $();},revertFieldLabels:function(row){var inlineEditor=this;if(row.labelElements!=undefined){jQuery.each(row.labelElements,function(i,label){if(inlineEditor.pageObj.isBootstrap()&&inlineEditor.listGridLayout===Runner.pages.constants.VERTICAL_LAYOUT){label.attr("for","");label.removeClass("control-label");}});}},makeRowEditable:function(row,ctrlsJSON){var ctrlsMap=ctrlsJSON.controlsMap[this.tName][this.pageType][row.id].controls,ctrlsArr=[],spanCont,i,ctrl;row.labelElements=row.labelElements||{};for(i=0;i<this.fNames.length;i++){spanCont=Runner.getFieldSpan(this.fNames[i],row.id,this.pageObj.pageCont);if(row.isAdd){spanCont.append(ctrlsJSON['html'][this.fNames[i]]);}else{spanCont.html(ctrlsJSON['html'][this.fNames[i]]);}
row.labelElements[this.fNames[i]]=this.getFieldLabelElement(row,this.fNames[i]);if(this.pageObj.isBootstrap()){if(this.listGridLayout===Runner.pages.constants.VERTICAL_LAYOUT){row.labelElements[this.fNames[i]].addClass("control-label");row.labelElements[this.fNames[i]].parent().attr('data-signal-error-for',Runner.goodFieldName(this.fNames[i])+row.id);}else if(this.listGridLayout===Runner.pages.constants.HORIZONTAL_LAYOUT||this.listGridLayout===Runner.pages.constants.FLEXIBLE_LAYOUT){spanCont.closest('td').attr('data-signal-error-for',Runner.goodFieldName(this.fNames[i])+row.id);}else if(this.listGridLayout===Runner.pages.constants.COLUMNS_LAYOUT){spanCont.closest('table').find('[data-field="'+Runner.goodFieldName(this.fNames[i])+'"]').attr('data-signal-error-for',Runner.goodFieldName(this.fNames[i])+row.id);row.labelElements[this.fNames[i]].addClass("control-label");}}}
for(i=0;i<ctrlsMap.length;i++){if($.inArray(ctrlsMap[i].fieldName,this.fNames)===-1){continue;}
ctrl=Runner.controls.ControlFactory(ctrlsMap[i],this.pageType,true,this.pageObj);ctrlsArr.push(ctrl);row.labelElements[ctrlsMap[i].fieldName].attr('for',ctrl.getDispId());}
for(i=0;i<ctrlsArr.length;i++){ctrlsArr[i].setDependencies(this.tName,row.id);}
Runner.pages.RunnerPage.prototype.initToolTips.call(this.pageObj,ctrlsJSON.controlsMap[this.tName][this.pageType][row.id].toolTips,this.tName);this.fireEvent('createControls',row,ctrlsArr);},setFocusOntheFirstControl:function(row){if(this.pageObj.pageMode===Runner.pages.constants.MODE_LIST_DETAILS&&Runner.pages.PageManager.getAt(this.pageObj.masterTName,this.pageObj.parId).pageType===Runner.pages.constants.PAGE_ADD){return;}
Runner.pages.RunnerPage.prototype.setFirstFocus.call(this.pageObj,row.id);},getSaveLink:function(row,hideSaveButt){var inlineObj=this,$link,$imgButt,linkHtml;if(row.saveLink&&row.saveLink.length&&!hideSaveButt){row.saveLink.show();return row.saveLink;}else if(hideSaveButt){return false;}
if(this.pageObj.controlsMap.layoutVersion!=Runner.pages.constants.BOOTSTRAP_LAYOUT)
linkHtml='<a id="saveLink'+row.id+'" href="#" data-icon="'+Runner.pages.constants.OK_GIF+'"></a>';else
linkHtml='<a id="saveLink'+row.id+'" href="#" class="glyphicon glyphicon-ok inline-save"></a>';$link=$(linkHtml).attr('title',Runner.lang.constants.TEXT_SAVE).addClass('saveEditing');if(hideSaveButt){$link.css('display','none');}
$link.bind("click",function(e){if(row.saveLink.hasClass('disabled')){return false;}
row.saveLink.addClass('disabled');row.fileFieldsCount=0;row.upploadErrorHappened=false;$('div.shiny_box').hide();inlineObj.rowFocussed=false;inlineObj.fromSaveBtn=true;inlineObj.waitForFilesUpload(row);return false;});return row.saveLink=$link;},waitForFilesUpload:function(row){var inlineObj=this,index,controls=Runner.controls.ControlStorage.byId(row.id);for(index=0;index<controls.length;index++){if(controls[index].editFormat==Runner.controls.constants.EDIT_FORMAT_FILE&&controls[index].filesToUploadCount>0){row.fileFieldsCount++;controls[index].errorHappened=false;controls[index].uploadForm.bind('fileuploadstopped',{ctrl:controls[index]},function(e,data){row.fileFieldsCount--;$(this).unbind('fileuploadstopped');if(e.data.ctrl.errorHappened){row.upploadErrorHappened=true;inlineObj.errorHn(row);}else{inlineObj.callSaveHn(row);}});$(".btn-primary.start",controls[index].uploadForm).click();}}
if(row.fileFieldsCount<1){this.callSaveHn(row);}},errorHn:function(row){if(row.fileFieldsCount<1){row.saveLink.removeClass('disabled');}},callSaveHn:function(row){if(row.fileFieldsCount<1&&!row.upploadErrorHappened){this.submit(row);this.toggleMassRecButt();this.resetSelectAll();}},getCancelLink:function(row,hideRevertButt){var inlineObj=this,$link,$imgButt,linkHtml;if(row.cancelLink&&row.cancelLink.length&&!hideRevertButt){row.cancelLink.show();return row.cancelLink;}
if(this.pageObj.controlsMap.layoutVersion!=Runner.pages.constants.BOOTSTRAP_LAYOUT)
linkHtml='<a id="revertLink'+row.id+'" href="#" data-icon="'+Runner.pages.constants.CANCEL_GIF+'"></a>';else
linkHtml='<a id="revertLink'+row.id+'" href="#" class="glyphicon glyphicon-ban-circle inline-cancel"></a>';$link=$(linkHtml).attr('title',Runner.lang.constants.TEXT_CANCEL).addClass('revertEditing');if(hideRevertButt){$link.css('display','none');}
$link.bind("click",function(e){inlineObj.cancelButtonHn(row);if(inlineObj.rows.length!==0){inlineObj.toggleMassRecButt();}
inlineObj.resetSelectAll();return false;});return row.cancelLink=$link;},getEditBlock:function(row,hideRevertButt,hideSaveButt){if(!row.saveLink||!row.saveLink.length||!row.cancelLink||!row.cancelLink.length){if(row.iEditLink.length){row.iEditLink.parent("td").addClass("rnr-nowrap");row.iEditLink.after(this.getCancelLink(row,hideRevertButt)).after(this.getSaveLink(row,hideSaveButt));}else{if(Runner.isBootstrap()){$("#ieditbuttonsholder"+row.id).after(this.getCancelLink(row,hideRevertButt)).after(this.getSaveLink(row,hideSaveButt));}else{var span,i;for(i=0;i<this.fNames.length;i++){span=Runner.getFieldSpan(this.fNames[i],row.id)
if(span.length){span.parent("td").addClass("rnr-nowrap");span.prepend(this.getCancelLink(row,hideRevertButt)).prepend(this.getSaveLink(row,hideSaveButt));break;}}}}
return;}
this.getCancelLink(row,hideRevertButt);this.getSaveLink(row,hideSaveButt);},revertRow:function(row){Runner.controls.ControlStorage.unregisterById(row.id);this.fireEvent('revertRow',row);},removeRowData:function(row,ind){if(row.basicForm&&row.basicForm.destructor){row.basicForm.destructor();}
if(row.row){row.row.remove();}
if(row.srow){row.srow.remove();}
if(this.rows.length===1){this.pageObj.hideBrick("grid");$("thead tr, tr.footer, tr."+this.classNameBottomRow,this.pageObj.gridElem).addClass(this.classNameHidden);this.toggleRecordControlButtons(false);}
this.rows.splice(ind||this.getRowInd(row),1);this.removeGridRowData(row.id);},removeGridRowData:function(rowId){for(var i=0;i<this.rowsOrderData.length;i++){if(this.rowsOrderData[i].id==rowId){break;}}
this.rowsOrderData.splice(i,1);},getRowInd:function(row){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id===row.id){return i;}}
return-1;},getRowById:function(rowId){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id===parseInt(rowId,10)){return this.rows[i];}}
return null;},getRowOrderIndex:function(rowId){for(var i=0;i<this.rowsOrderData.length;i++){if(this.rowsOrderData[i].id===rowId){return i;}}
return-1;},getRowKeysByOrderIndex:function(ordInd){if(this.rowsOrderData[ordInd]!==undefined){return this.rowsOrderData[ordInd].keys;}
return[];},getRowIdByOrderIndex:function(ordInd){if(this.rowsOrderData[ordInd]!==undefined){return this.rowsOrderData[ordInd].id;}
return-1;},makeError:function(msg,row){row.errorMess=msg;if(!this.pageObj.gridElem){return;}
if(!row.errorDiv){var inlineObj=this,$span=$("span[id^=edit"+row.id+"_]:eq(0)",this.pageObj.gridElem),$errorLink=$('<a href="#" id="error_'+row.id+'" style="white-space:nowrap;"></a>').html(Runner.lang.constants.TEXT_INLINE_ERROR+' >>');row.errorDiv=$("<div></div>").addClass(this.classNameInlineError).append($errorLink).appendTo($span);if(!this.errCont){this.errCont=$("<div></div>");if(inlineObj.pageObj.isBootstrap()){this.errCont.addClass("alert alert-danger");}
else{this.errCont.addClass("error").addClass(this.classNameMessage);}
this.errCont.appendTo(document.body).hide();}
$errorLink.bind("mouseenter",function(e){var errorPos=$errorLink.offset(),topPos=errorPos.top,adjustment;topPos+=$errorLink.height();adjustment=$(document).height()-topPos-inlineObj.errCont.height();if(adjustment<0){errorPos+=adjustment;}
inlineObj.errCont.css({"top":topPos+"px","left":errorPos.left+$errorLink.width()+"px","z-index":inlineObj.pageObj.isBootstrap()?1100:100,"position":"absolute"}).show();}).bind("mouseleave",function(e){inlineObj.errCont.hide();});}
this.errCont.html(msg);},clearError:function(row){delete row.errorMess;if(row.errorDiv){row.errorDiv.remove();delete row.errorDiv;}},updateTableRow:function(row,newData){var checkBoxVals,i,$rowElement;row.data=Runner.apply({},newData.vals);if(!newData.fNamesSelected){row.keys=newData.keys;row.keyFields=newData.keyFields;}
row.rowVals=newData.rawVals;for(i=0;i<this.rowsOrderData.length;i++){if(this.rowsOrderData[i].id===row.id){this.rowsOrderData[i].keys=newData.keys;break;}}
if(row.checkBox&&row.checkBox.length&&!newData.noKeys&&!newData.fNamesSelected){checkBoxVals=[];for(i=0;i<newData.keys.length;i++){checkBoxVals.push(newData.keys[i]);}
row.checkBox.val(checkBoxVals.join("&")).prop("checked",false).show();}
if(!newData.noKeys&&!newData.fNamesSelected){this.changeLinksKeys(row);}
this.checkRowMasterKeys(row,newData.detKeys);if(newData.hrefs){for(i=0;i<newData.hrefs.length;i++){$("#"+newData.hrefs[i].id+row.id).attr("href",newData.hrefs[i]["href"]);}}
if(this.lookupParams&&this.lookupFieldInfo&&newData.linkValue){newData.vals[this.lookupFieldInfo.linkField]=newData.linkValue;newData.vals[this.lookupFieldInfo.dispFieldAlias||this.lookupFieldInfo.dispField]=newData.displayValue;}
this.setValuesIntoSpans(row,newData.fNamesSelected);this.revertFieldLabels(row);if(newData.noKeys!==true){this.showRowButtons(row);}
$rowElement=$("#gridRow"+row.id).removeClass("recently-added").addClass("just-added");setTimeout(function(){$rowElement.removeClass("just-added").addClass("recently-added");},10);row.submitted=true;if(row.isAdd){row.isAdd=false;}},afterSubmit:function(row,newData,extPageObj){this.fireEvent("beforeProcessNewRow",row,newData.vals,newData.fields,newData.keys);Runner.controls.ControlStorage.unregisterById(row.id);this.updateTableRow(row,newData);this.fireEvent('afterSubmit',newData.vals,newData.fields,newData.keys,row.id,newData,extPageObj);if(row.basicForm){setTimeout(function(){row.basicForm.destructor();row.basicForm=null;},0);}
if(this.rows.length===1){this.pageObj.hideBrick("message");}
if(Runner.pages.PageSettings.getGlobalData("s508")){this.pageObj.s508Obj.s508setFocusToRow(row.id);}},fireUserEventAfterInline:function(row){var fieldsData=[],i;for(i=0;i<this.fNames.length;i++){fieldsData[i]={name:this.fNames[i],value:row.rowVals[this.fNames[i]],text:row.data[this.fNames[i]],container:Runner.getFieldSpan(this.fNames[i],row.id)};}
this.fireEvent("afterSave",fieldsData);for(i=0;i<this.fNames.length;i++){row.rowVals[this.fNames[i]]=fieldsData[i].value;row.data[this.fNames[i]]=fieldsData[i].text;}},setValuesIntoSpans:function(row,fNames){var inlineObj=this,fName,pos,fSpan,viewFormat,i,j;fNames=fNames||this.fNames;this.fireEvent("beforeSetVals",row,this.fNames);if(!row.revertted){this.fireUserEventAfterInline(row);}
for(i=0;i<fNames.length;i++){fName=fNames[i];if(typeof row.data[fName]==="undefined"){row.data[fName]="";pos=$.inArray(fName,row.keyFields);if(pos!==-1){row.data[fName]=row.keys[pos].toString();}}
fSpan=Runner.getFieldSpan(fName,row.id).html(row.data[fName]);for(j=0;j<this.totalFields.length;j++){if(this.totalFields[j].fName===fName){fSpan.attr('val',row.rowVals&&row.rowVals[fName]?row.rowVals[fName]:"");break;}}
viewFormat=Runner.pages.PageSettings.getFieldData(this.tName,fName,'viewFormat',this.pageType);if(viewFormat!==Runner.controls.constants.FORMAT_MAP&&viewFormat!==Runner.controls.constants.FORMAT_FILE_IMAGE){fSpan.find('img').each(function(index,image){var src=$(image).attr('src');$(image).attr('src',inlineObj.replaceRndVal(src));});fSpan.find('a').each(function(index,link){var href=$(link).attr('href');$(link).attr('href',inlineObj.replaceRndVal(href));});}}
this.initRowViewControls(row);return row.data;},initRowViewControls:function(row){if(this.pageObj.viewControlsMap){this.pageObj.setupViewContols(this.pageObj.viewControlsMap.controls,$('#'+this.rowPref+row.contextRowId));}},replaceRndVal:function(src){if(!src){return"";}
var rndValPos=src.indexOf('rndVal='),endPos;if(rndValPos===-1){return src+(src.indexOf('?')!=-1?"&":"?")+"rndVal="+Math.random();}
endPos=src.indexOf('&',rndValPos);return src.slice(0,rndValPos+7)+Math.random()+(endPos!==-1?src.slice(endPos):'');},getValuesFromSpan:function(row){var fSpan,images,i,j;row.data={};for(i=0;i<this.fNames.length;i++){fSpan=Runner.getFieldSpan(this.fNames[i],row.id);if(!fSpan.length){continue;}
if($('.sudoslider',fSpan).length){images="";$('li',fSpan).each(function(index,sliderPanel){images+='<li>'+$(sliderPanel).html()+'</li>';});images=images?'<div style="position:relative;"><div class="presudoslider"><ul>'+images+"</ul></div></div>":images;row.data[this.fNames[i]]=images;continue;}
$('.projekktor',fSpan).each(function(j,videoElement){var vElementId=$(videoElement).attr("id"),playList=projekktor(vElementId).getPlaylist();projekktor(vElementId).setStop().selfDestruct();if(playList.length&&playList[0].file.length){$(fSpan.find('video').get(j)).attr({"src":playList[0].file[0].src,"type":playList[0].file[0].type});}});row.data[this.fNames[i]]=fSpan.html();}},getValueFromSpan:function(row,fName){if(row.rowVals&&row.rowVals[fName]){return row.rowVals[fName];}
var span=Runner.getFieldSpan(fName,row.id),val=span.attr('val');return!val&&row.data[fName]!=null?row.data[fName]:val;},initCopyLink:function($link,row){if(!Runner.pages.PageSettings.getTableData(this.tName,"showAddInPopup")||!$link.length){return $link;}
var inlineObj=this;return $link.bind("click",function(e){var pageParams={tName:inlineObj.tName,pageType:Runner.pages.constants.PAGE_ADD,modal:true,keys:row.keys,keyFields:row.keyFields,keyPref:"copyid",baseParams:{parId:inlineObj.id,table:inlineObj.tName,editType:Runner.pages.constants.ADD_POPUP},afterSave:{fn:function(respObj,formObj,fieldControls,page){if(respObj.success){var addedRow=this.addRowToGrid(respObj);this.pageObj.initNewRowButtons&&this.pageObj.initNewRowButtons(addedRow);return true;}
return false;},scope:inlineObj}};Runner.pages.PageManager.openPage(pageParams);return false;});},initCheckBox:function($checkbox){$checkbox.parent().on("click",function(e){if(!$checkbox.is(e.target)){$checkbox.trigger("click");}
e.stopPropagation();});return $checkbox;},changeLinksKeys:function(row){$(row.viewLink).attr('href',Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,row.keys,'editid'));$(row.editLink).attr('href',Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,row.keys,'editid'));$(row.copyLink).attr('href',Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_ADD,row.keys,'copyid'));},initViewLink:function($link,row){if(!this.showViewInPopup||!$link.length){return $link;}
return $link.on("click",this.pageObj.getViewLinkHandler(row,"popup"));},initEditLink:function($link,row){if(!this.showEditInPopup||!$link.length){return $link;}
return $link.on("click",this.pageObj.getEditLinkHandler(row,'popup'));},initInlineEditLink:function($link,row){var newUrl=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,row.keys,'editid'),inlineObj=this;return $link.attr('href',newUrl).bind("click",function(e){(inlineObj.inlineEditObj||inlineObj).inlineEdit(row);return false;});},toggleMassRecButt:function(){this.pageObj.onAfterChangeCheckboxsState();this.massRecButtEditMode=this.isRowsEditing();Runner.toggleButton(this.saveAllButt,this.massRecButtEditMode);Runner.toggleButton(this.cancelAllButt,this.massRecButtEditMode);},isRowsEditing:function(){for(var i=0;i<this.rows.length;i++){if(this.rows[i].submitted!==undefined&&!this.rows[i].submitted){return true;}}
return false;},validate:function(){var invalidControls=[];this.rowFocussed=false;for(var i=0,l=this.rows.length;i<l;i++){invalidControls=this.pageObj.getInvalidControls(Runner.controls.ControlStorage.byId(this.rows[i].id));if(invalidControls.length&&(this.rows[i].isAdd||!this.rowFocussed)){if(this.pageObj.setFirstFocus(this.rows[i].id,invalidControls)){this.rowFocussed=true;}}}
return!this.rowFocussed;},addRowToGrid:function(data,fireEvents){var newAddRow=this.prepareRow(data.vals,true);this.getEditBlock(newAddRow);if(fireEvents){this.afterSubmit(newAddRow,data);}else{this.updateTableRow(newAddRow,data);}
return newAddRow;},initRow:function(row){row.submitted=true;row.revertted=false;row.data={};row.saveLink=false;row.cancelLink=false;row.checkBox=this.initCheckBox($('#check'+this.id+'_'+row.id));row.copyLink=this.initCopyLink($('#copyLink'+row.id),row);row.editLink=this.initEditLink($('#editLink'+row.id),row);row.iEditLink=this.initInlineEditLink($('#iEditLink'+row.id),row);row.viewLink=this.initViewLink($('#viewLink'+row.id),row);},hideRowButtons:function(row){row.viewLink.hide();row.copyLink.hide();row.editLink.hide();row.iEditLink.hide();row.checkBox.hide();},showRowButtons:function(row){row.viewLink?row.viewLink.show():null;row.copyLink?row.copyLink.show():null;if(row.isEditable){row.editLink?row.editLink.show():null;row.iEditLink?row.iEditLink.show():null;}
row.checkBox?row.checkBox.show():null;row.saveLink?row.saveLink.hide():null;row.cancelLink?row.cancelLink.hide():null;},toggleRecordControlButtons:function(toggler){Runner.toggleButton(this.editAllButt,toggler);Runner.toggleButton(this.saveAllButt,toggler);Runner.toggleButton(this.cancelAllButt,toggler);Runner.toggleButton($("[id=print_selected"+this.id+"]"),toggler);Runner.toggleButton($("[id=export_selected"+this.id+"]"),toggler);Runner.toggleButton($("[id=delete_selected"+this.id+"]"),toggler);if(Runner.isBootstrap()){Runner.toggleButton($("[id=update_selected"+this.id+"]"),toggler);}
if(this.pageObj.pageMode==Runner.pages.constants.LIST_DASHBOARD){toggler?$('.rnr-b-recordcontrol',this.pageObj.pageCont).removeClass('rnr-hiddenbrick'):$('.rnr-b-recordcontrol',this.pageObj.pageCont).addClass('rnr-hiddenbrick');}else{this.pageObj.toggleBrick("recordcontrol",toggler);}},prepareRow:function(vals,submitted){var grid=this.pageObj.gridElem,$addRow=$(".gridRowAdd",grid).eq(0),$sepAddRow=$(".gridRowSepAdd",grid).eq(0),newRowId=Runner.genId(),pageId=this.id,newAddRow;if(this.rows.length===0){this.pageObj.showBrick("grid");$("thead tr, tr.footer, tr."+this.classNameBottomRow,grid).removeClass(this.classNameHidden);this.toggleRecordControlButtons(true);}
newAddRow={row:$addRow.clone(true),srow:false,id:newRowId,keys:[],keyFields:[],data:vals,isAdd:true,isEditable:true,contextRowId:newRowId,gridLayout:this.listGridLayout};if($sepAddRow.length){newAddRow.srow=$sepAddRow.clone();newAddRow.srow.removeClass('gridRowSepAdd '+this.classNameHidden);}
this.rows.push(newAddRow);if(this.pageObj.addNewRecordsToBottom){this.rowsOrderData.push({id:newRowId,keys:[]});}else{this.rowsOrderData.unshift({id:newRowId,keys:[]});}
this.replaceElementsIdForAddedRow(newAddRow,pageId);newAddRow.row.removeClass('gridRowAdd '+this.classNameHidden);$(".gridRowAdd",newAddRow.row).removeClass('gridRowAdd '+this.classNameHidden);if(this.listGridLayout===Runner.pages.constants.COLUMNS_LAYOUT){if(!Runner.isBootstrap()){newAddRow.row.children("tr").attr("id",this.rowPref+newAddRow.id);newAddRow.row.children("tr.rnr-row").children("td").attr("data-record-id",newAddRow.id);}else{newAddRow.row.attr("id",this.rowPref+newAddRow.id);newAddRow.row.children("div").attr("data-record-id",newAddRow.id);}}else if(this.listGridLayout===Runner.pages.constants.VERTICAL_LAYOUT||newAddRow.row.hasClass(this.classNameRow)||Runner.isBootstrap()){newAddRow.row.attr("id",this.rowPref+newAddRow.id);newAddRow.row.children("td").attr("data-record-id",newAddRow.id);if(Runner.isBootstrap()){newAddRow.row.children("div").attr("data-record-id",newAddRow.id);}}
if(newAddRow.srow){if(this.pageObj.addNewRecordsToBottom){newAddRow.srow.appendTo($sepAddRow.parent().siblings().last());newAddRow.row.appendTo($sepAddRow.parent().siblings().last());}else{newAddRow.srow.insertAfter($sepAddRow);newAddRow.row.insertAfter($sepAddRow);}}else{if(this.pageObj.addNewRecordsToBottom){newAddRow.row.appendTo($addRow.parent());}else{newAddRow.row.insertAfter($addRow);}}
(this.inlineEditObj||this).initRow(newAddRow);newAddRow.submitted=submitted;return newAddRow;},replaceElementsIdForAddedRow:function(newAddRow,pageId){$("#editLink_add"+pageId,newAddRow.row).attr("id","editLink"+newAddRow.id).hide();$("#copyLink_add"+pageId,newAddRow.row).attr("id","copyLink"+newAddRow.id).hide();$("#check_add"+pageId,newAddRow.row).attr("id","check"+pageId+"_"+newAddRow.id).hide();$("#viewLink_add"+pageId,newAddRow.row).attr("id","viewLink"+newAddRow.id).hide();$("#inlineEdit_add"+pageId,newAddRow.row).attr("id","iEditLink"+newAddRow.id).hide();$("#ieditbuttonsholder"+pageId,newAddRow.row).attr("id","ieditbuttonsholder"+newAddRow.id);$("[id^='cntDet']",newAddRow.row).each(function(idx,el){var $el=$(el);$el.attr("id",$el.attr("id")+newAddRow.id);}).hide();$("[id$='_preview"+pageId+"']",newAddRow.row).hide().each(function(){var
reg=new RegExp(pageId+'$');this.id=this.id.replace(reg,newAddRow.id);});$("[id^='details_add"+pageId+"_']",newAddRow.row).each(function(idx,el){var $el=$(el);$el.attr("id",$el.attr("id").replace("details_add"+pageId+"_","details_"+newAddRow.id+"_"));});$("[id^='details_'][id$='_add"+pageId+"']",newAddRow.row).hide().each(function(){var reg=new RegExp('add'+pageId+'$');this.id=this.id.replace(reg,newAddRow.id);});$("[id^='add"+pageId+"_']",newAddRow.row).each(function(){var reg=new RegExp('^add'+pageId);this.id=this.id.replace(reg,'edit'+newAddRow.id);});},checkRowMasterKeys:function(row,newMasterKeys){if(!this.pageObj.dpObjs||!newMasterKeys||$.isEmptyObject(newMasterKeys)){return;}
$.each(this.pageObj.dpObjs,function(ind,obj){var isKeysChanged=false;if(row.masterKeys==undefined){row.masterKeys=newMasterKeys;isKeysChanged=true;}else{$.each(newMasterKeys[obj.tName],function(kInd,kObj){if(kObj!=row.masterKeys[obj.tName][kInd]){isKeysChanged=true;return false;}});}
if(isKeysChanged){obj.updateChildRecNum(newMasterKeys[obj.tName],row.id);row.masterKeys[obj.tName]=newMasterKeys[obj.tName];obj.closeDetailsById(row.id);}else{obj.updateChildRecNum(row.masterKeys[obj.tName]);}});},lockRow:function(row,ctrlsJSON){}});Runner.util.inlineEditing.InlineAdd=Runner.extend(Runner.util.inlineEditing.InlineEditor,{pageType:Runner.pages.constants.PAGE_ADD,hideSaveButt:false,constructor:function(cfg){Runner.util.inlineEditing.InlineAdd.superclass.constructor.call(this,cfg);this.addEvents("beforeSetVals","beforeInlineAdd");},init:function(){Runner.util.inlineEditing.InlineAdd.superclass.init.call(this);},getSubmitUrl:function(){return Runner.util.inlineEditing.InlineAdd.superclass.getSubmitUrl.call(this)+"?submit=1&inline=1&";},initButtons:function(){Runner.util.inlineEditing.InlineAdd.superclass.initButtons.call(this);this.initAddButton();},reinitButtons:function(){Runner.util.inlineEditing.InlineAdd.superclass.initButtons.call(this);},initAddButton:function(){var inlineAddObj=this;$("[id=inlineAdd"+this.id+"]").unbind("click").bind("click",function(e){inlineAddObj.inlineAdd(inlineAddObj.hideSaveButt);return false;});},cancelButtonHn:function(row,isCancelAll){row.revokeCancel=false;if(typeof row.onBeforeCancel!="undefined"){row.onBeforeCancel();}
if(row.revokeCancel){return false;}
this.removeRowData(row);if(!isCancelAll){this.fireEvent('recalcGridSize');}
Runner.util.inlineEditing.InlineAdd.superclass.cancelButtonHn.call(this);if(typeof row.onCancel!="undefined"){row.onCancel();}
this.fireEvent('cancel',row,this.fNames);Runner.controls.ControlStorage.unregisterById(row.id);return true;},revertRow:function(row){Runner.util.inlineEditing.InlineAdd.superclass.revertRow.call(this,row);this.removeRowData(row);},saveAll:function(){if(Runner.util.inlineEditing.InlineAdd.superclass.saveAll.call(this)){return true;}
for(var i=this.rows.length;i--;){if(this.rows[i]&&!this.rows[i].submitted&&this.rows[i].isAdd){this.rows[i].fileFieldsCount=0;this.rows[i].upploadErrorHappened=0;this.waitForFilesUpload(this.rows[i]);}}
Runner.util.inlineEditing.InlineAdd.superclass.saveAll.call(this);},fireUserEventAfterInline:function(row){if(this.pageObj.isEventExist('afterInlineAdd')){Runner.util.inlineEditing.InlineEdit.superclass.fireUserEventAfterInline.call(this,row);}},initForm:function(row){Runner.util.inlineEditing.InlineAdd.superclass.initForm.call(this,row);3
if(this.lookupParams){row.basicForm.baseParams["forLookup"]=true;row.basicForm.baseParams["table"]=this.lookupParams.table;row.basicForm.baseParams["field"]=this.lookupParams.field;row.basicForm.baseParams["pageType"]=this.lookupParams.pageType;}},afterSubmit:function(row,newData,extAddPageObj){Runner.util.inlineEditing.InlineAdd.superclass.afterSubmit.call(this,row,newData,extAddPageObj);if(row.cancelLink){row.cancelLink.remove();row.cancelLink=null;}
if(row.saveLink){row.saveLink.remove();row.saveLink=null;}
if(row.tempContainer){row.tempContainer.remove();row.tempContainer=null;}
row.isEditOwnRow=true;if(this.pageObj.parId){Runner.pages.PageManager.getById(this.pageObj.parId).setRecountFlagForPopup();}
var allVals=[],allKeys=[],allRowIds=[],selAllHid=$("#select_all"+this.id+":hidden");if(typeof row.fromSaveBtn=="undefined"){for(var i=0;i<this.rows.length;i++){allVals.push(this.rows[i].data);allKeys.push(this.rows[i].keys);allRowIds.push(this.rows[i].id);if(this.rows[i].submitted===false){this.pageObj.isDetailsRecountNeeded=true;return;}}}
if(selAllHid.length){selAllHid.show();}
this.fireEvent('rowsEdited',allVals,newData.fields,allKeys,allRowIds,false,row.fromSaveBtn);this.pageObj.initHeaderCheckBox();row.fromSaveBtn=undefined;},toggleMassRecButt:function(){Runner.util.inlineEditing.InlineAdd.superclass.toggleMassRecButt.call(this);if(!this.isRowsEditing()&&this.rows.length){Runner.toggleButton(this.editAllButt,!this.massRecButtEditMode);}},inlineAdd:function(hideSaveButt,hideRevertButt){var newAddRow;this.fireEvent("beforeInlineAdd");this.pageObj.hideBrick('message');hideRevertButt=hideRevertButt===undefined?false:hideRevertButt;hideSaveButt=hideSaveButt===undefined?false:hideSaveButt;newAddRow=this.prepareRow({},false);this.toggleMassRecButt();this.hideRowButtons(newAddRow);this.getControls(this.pageObj,newAddRow,hideRevertButt,hideSaveButt);},showCancelButton:function(row){this.inlineAddChangeContent=true;this.getEditBlock(row,false,true);}});Runner.util.inlineEditing.InlineEdit=Runner.extend(Runner.util.inlineEditing.InlineEditor,{pageType:Runner.pages.constants.PAGE_EDIT,isUseLocking:false,constructor:function(cfg){Runner.util.inlineEditing.InlineEdit.superclass.constructor.call(this,cfg);this.isUseLocking=Runner.pages.PageSettings.getTableData(this.tName,"locking");this.initLocking();this.addEvents("beforeEditRow");},init:function(){Runner.util.inlineEditing.InlineEdit.superclass.init.call(this);this.initRows();},getSubmitUrl:function(){return Runner.util.inlineEditing.InlineEdit.superclass.getSubmitUrl.call(this)+"?submit=1";},initLocking:function(){if(!this.isUseLocking){return;}
this.locking=new Runner.Locking({tName:this.tName,pageId:this.id});},lockRow:function(row,ctrlsJSON){if(!this.isUseLocking){return;}
var enableCtrls=ctrlsJSON.enableCtrls,confirmTime=ctrlsJSON.confirmTime;if(enableCtrls===undefined){enableCtrls=ctrlsJSON.settings['tableSettings'][this.tName]['enableCtrls'];}
if(confirmTime===undefined){confirmTime=ctrlsJSON.settings['tableSettings'][this.tName]['confirmTime'];}
if(enableCtrls){this.locking.StartLocking(this,row.id,this.getKeysForLocking(row),confirmTime);}},getKeysForLocking:function(row){return this.getLockingKeysString(row.keys);},getLockingKeysString:function(keys){if(!this.isUseLocking){return"";}
var sKeys=[],i;keys=keys||[];for(i=0;i<keys.length;i++){sKeys.push(keys[i]);}
return sKeys.join("&");},showErrorForLockingRecords:function(){var lockingRecords=Runner.pages.PageSettings.getTableData(this.tName,'lockRecIds');if(!lockingRecords.length){return;}
for(var i=0,l=lockingRecords.length;i<l;i++){this.makeError("Record is being edited by another user",this.getRowById(lockingRecords[i]));$('input[id=check'+this.id+'_'+lockingRecords[i]+']',this.pageObj.gridElem).prop('checked',true);}},initRow:function(row){Runner.util.inlineEditing.InlineEdit.superclass.initRow.call(this,row);row.isEditable=true;},initRows:function(){for(var i=0;i<this.rows.length;i++){this.initRow(this.rows[i]);}
if(this.isUseLocking){this.showErrorForLockingRecords();}},initInlineRowEditors:function(){for(var i=0;i<this.rows.length;i++){this.getInlineButtBlock(this.rows[i]);}},initButtons:function(){Runner.util.inlineEditing.InlineEdit.superclass.initButtons.call(this);this.initEditAll();},initEditAll:function(){var inlineObj=this;this.editAllButt.unbind("click").bind("click",function(e){var i,j,row,checkBox,selBoxesArr=[],isEdit=false;$('input[type=checkbox][id^=check'+inlineObj.id+'_]:checked').each(function(){var $box=$(this),recordId=$box.attr('id').substr($box.attr('id').lastIndexOf('_')+1);if(inlineObj.isEditOwn&&!$('#iEditLink'+recordId).length){$box.prop("checked",false);return;}
selBoxesArr.push($box);});for(i=0;i<selBoxesArr.length;i++){for(j=0;j<inlineObj.rows.length;j++){row=inlineObj.rows[j];checkBox=row.checkBox;if($(checkBox[0]).attr('id')!==$(selBoxesArr[i]).attr('id')){continue;}
if(row.keys&&row.keys.length>0){inlineObj.inlineEdit(row);if(inlineObj.rows[i]&&!inlineObj.rows[i].submitted&&!inlineObj.rows[i].isAdd){isEdit=true;}}}}
if(isEdit){inlineObj.toggleMassRecButt();}
e.preventDefault();});},reInit:function(gridRows){Runner.util.inlineEditing.InlineEdit.superclass.reInit.call(this,gridRows);this.initRows();},inlineEdit:function(row,hideRevertButt,hideSaveButt){hideRevertButt=hideRevertButt===undefined?false:hideRevertButt;hideSaveButt=hideSaveButt===undefined?false:hideSaveButt;this.pageObj.hideBrick('message');this.fireEvent("beforeEditRow",row);row.submitted=false;this.clearError(row);this.toggleMassRecButt();this.getValuesFromSpan(row);this.hideRowButtons(row);this.getControls(this.pageObj,row,hideRevertButt,hideSaveButt);var inlineObj=this;setTimeout(function(){$("#"+inlineObj.rowPref+row.id).removeClass('hovered');});},editRecById:function(rowId){var row=this.getRowById(rowId);if(row){this.inlineEdit(row);return true;}
return false;},editAllRecs:function(){for(var i=0;i<this.rows.length;i++){this.inlineEdit(this.rows[i]);}},getRecsId:function(){var recsId={};for(var i=0;i<this.rows.length;i++){recsId[i+1]=this.rows[i].id;}
return recsId;},revertRow:function(row){if(!row.data){return;}
row.submitted=true;row.revertted=true;row.errorDiv=false;if(row.checkBox){row.checkBox.prop("checked",false);}
Runner.util.inlineEditing.InlineEdit.superclass.revertRow.call(this,row);this.showRowButtons(row);this.setValuesIntoSpans(row);this.revertFieldLabels(row);if(this.isUseLocking&&this.locking){this.locking.UnlockRecordInline(this.getKeysForLocking(row));}
if(row.checkBox){row.checkBox.show();}},initForm:function(row){Runner.util.inlineEditing.InlineEdit.superclass.initForm.call(this,row);for(var i=0;i<row.keys.length;i++){row.basicForm.baseParams["editid"+(i+1)]=row.keys[i];}},cancelButtonHn:function(row,isCancelAll){row.revokeCancel=false;if(typeof row.onBeforeCancel!="undefined"){row.onBeforeCancel();}
if(row.revokeCancel){return false;}
this.revertRow(row);if(typeof row.onCancel!="undefined"){row.onCancel();}
this.fireEvent('cancel',row,this.fNames);Runner.util.inlineEditing.InlineEdit.superclass.cancelButtonHn.call(this);if(!isCancelAll){this.fireEvent('recalcGridSize');}
return true;},toggleMassRecButt:function(){Runner.util.inlineEditing.InlineEdit.superclass.toggleMassRecButt.call(this);if(this.rows.length){Runner.toggleButton(this.editAllButt,!this.massRecButtEditMode)}},fireUserEventAfterInline:function(row){if(this.pageObj.isEventExist('afterInlineEdit')){Runner.util.inlineEditing.InlineEdit.superclass.fireUserEventAfterInline.call(this,row);}},afterSubmit:function(row,newData,editPageObj){var oldKeysForLocking=this.getKeysForLocking(row),isEdit;Runner.util.inlineEditing.InlineEdit.superclass.afterSubmit.call(this,row,newData,editPageObj);if(this.isUseLocking&&this.locking){this.locking.ResetSetInterval(oldKeysForLocking);if(editPageObj&&!editPageObj.moveNext){editPageObj.sKeys=this.getLockingKeysString(newData.keys);this.locking.StartLocking(this,row.id,editPageObj.sKeys,Runner.pages.PageSettings.getTableData(this.tName,"confirmTime"));}}
var allVals=[],allKeys=[],allRowIds=[];for(var i=0;i<this.rows.length;i++){if(this.rows[i].submitted===false){return;}
allVals.push(this.rows[i].data);allKeys.push(this.rows[i].keys);allRowIds.push(this.rows[i].id);}
isEdit=!this.pageObj.isDetailsRecountNeeded;delete this.pageObj.isDetailsRecountNeeded;this.fireEvent('rowsEdited',allVals,newData.fields,allKeys,allRowIds,isEdit);},saveAll:function(){if(Runner.util.inlineEditing.InlineEdit.superclass.saveAll.call(this)){return true;}
for(var i=0;i<this.rows.length;i++){if(!this.rows[i].submitted&&!this.rows[i].isAdd){this.rows[i].fileFieldsCount=0;this.waitForFilesUpload(this.rows[i]);}}},isRowEditing:function(row){return row.submitted!==undefined&&!row.submitted;}});Runner.controls.FilterControlFactory=function(baseCfg,searchController){var cfg={searchController:searchController};cfg=Runner.apply(cfg,baseCfg);switch(cfg.filterFormat){case Runner.controls.constants.FILTER_FORMAT_VALUES_LIST:case Runner.controls.constants.FILTER_FORMAT_INTERVAL_LIST:switch(cfg.multiSelect){case Runner.controls.constants.FILTER_MULTISELECT_NONE:return new Runner.controls.SimpleFilterControl(cfg);case Runner.controls.constants.FILTER_MULTISELECT_ON_DEMAND:return new Runner.controls.OnDemandFilterControl(cfg);case Runner.controls.constants.FILTER_MULTISELECT_ALWAYS:return new Runner.controls.MultiSelectFilterControl(cfg);default:throw("Invalid multiselect param("+cfg.multiSelect+") for the "+cfg.filterFormat+" format. Cannot create control!");return;}
case Runner.controls.constants.FILTER_FORMAT_BOOLEAN:return new Runner.controls.SimpleFilterControl(cfg);case Runner.controls.constants.FILTER_FORMAT_INTERVAL_SLIDER:if(cfg.isFieldDateType){return new Runner.controls.DateSliderFilterControl(cfg);}
if(cfg.isFieldTimeType){return new Runner.controls.TimeSliderFilterControl(cfg);}
return new Runner.controls.SliderFilterControl(cfg);default:throw("Invalid filter control's format = "+cfg.filterFormat+". Cannot create control!");}}
Runner.controls.FilterControl=Runner.extend(Runner.emptyFn,{ctrlValue:'',fieldName:'',gfieldName:'',filterFormat:'',multiSelect:0,filtered:false,defaultValuesArray:[],defaultShowValues:[],filterPanelContainerClass:"filterPanelContainer",filterPanelContainer:{},filterContainer:{},searchController:{},btnApplyClass:"filter-btn-apply",btnExpanderClass:"filter-expander",btnExpanderIndicatorClass:"filter-indicator",expanderElem:{},hiddenValuesClass:"filter-hidden",collapsedValuesClass:"filter-collapsed",filterValueBlockContainerClass:"filter-values",filterLinkClass:"filter-link",separator:"",dependent:false,hasDependent:false,goodOutermostParentName:"",goodParentName:"",parentFilterNames:null,hiddenFilterItemClass:"filter-item-hidden",baseCtrlButtonsInitialized:false,constructor:function(cfg){this.defaultValuesArray=[];Runner.apply(this,cfg);this.filterPanelContainer=$("."+this.filterPanelContainerClass);this.filterContainer=$(".filter-"+(this.dependent?this.goodOutermostParentName:this.gfieldName)+"-container");this.expanderElem=$("."+this.btnExpanderClass,this.filterContainer);this.init();},destructor:function(){},init:Runner.emptyFn,initButtons:function(){if(this.baseCtrlButtonsInitialized){return;}
this.initBasicButtons();this.initClearButtons();this.initShowMoreButton();this.baseCtrlButtonsInitialized=true;},initBasicButtons:function(){if(this.dependent){return;}
var ctrl=this,hiddenValuesClass=this.hiddenValuesClass,hiddenFilterItemClass=this.hiddenFilterItemClass,collapsedValuesClass=this.collapsedValuesClass,btnExpanderIndicatorClass=this.btnExpanderIndicatorClass;this.filterContainer.on('click','.'+this.btnApplyClass,function(e){$(this).data('activated',true);ctrl.searchController.submitSearch();return false;}).on('click','.'+this.btnExpanderClass,function(e){var expander=$(this),siblings=expander.parent().find('.'+ctrl.filterValueBlockContainerClass+',.filter-show-more,.filter-field-btn').not('.'+hiddenValuesClass+',.'+hiddenFilterItemClass),goingToHide=siblings.not('.'+collapsedValuesClass).length!==0,expanderIndicator=expander.children('.'+btnExpanderIndicatorClass);ctrl.adjustExpander(goingToHide);siblings.slideToggle(100).promise().done(function(){siblings.css('display','').toggleClass(collapsedValuesClass,goingToHide);});return false;});},updateCollapsedState:function(){var inCollapsedState=this.isCollapsed();if(!this.collapsed&&inCollapsedState){this.toggleCollapsed(false);}else if(this.collapsed&&!inCollapsedState){this.toggleCollapsed(true);}},toggleCollapsed:function(collapsed){var $filterItems=this.filterContainer.find('.'+this.filterValueBlockContainerClass+',.filter-show-more,.filter-field-btn');$filterItems.toggleClass(this.collapsedValuesClass,collapsed);},initClearButtons:function(){if(!this.filtered){return;}
var ctrl=this,clearBtnClass='filter-clear-'+(this.dependent?this.goodOutermostParentName:this.gfieldName);$('.'+clearBtnClass).on('click',function(e){ctrl.clearControl();ctrl.clearDependentFilters();ctrl.searchController.submitSearch();return false;});},initShowMoreButton:function(){var ctrl=this;$(".filterShowMore_"+this.gfieldName).on("click",function(e){var $showMoreElement=$(this).parent();$showMoreElement.siblings("."+ctrl.hiddenFilterItemClass).removeClass(ctrl.collapsedValuesClass).removeClass(ctrl.hiddenFilterItemClass);$showMoreElement.removeClass("filter-show-more").hide();return false;});},clearDependentFilters:function(notMultiSelected){if(!this.hasDependent){return;}
this.searchController.clearDependentFilters(this.dependentFilterNames,notMultiSelected);},setValue:function(value){this.ctrlValue=value;},getValue:function(){return this.ctrlValue;},getDisplayedValue:function(){if(this.defaultShowValues&&this.defaultShowValues.length){return this.defaultShowValues.join(", ");}
return this.getValue();},getPreparedValue:function(value,encoded){var prepValue=value;if(typeof value==="string"){prepValue=this.searchController.searchEscape(value);}
if(encoded&&typeof value==="string"){return encodeURIComponent(prepValue);}
return prepValue;},getFilterValue:function(encoded){var value,prepFName;if(this.ctrlValue===''){return'';}
value=this.getPreparedValue(this.ctrlValue,encoded);prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;return'('+prepFName+this.separator+value+')';},getFilterValueEncoded:function(){return this.getFilterValue(true);},isVisible:function(){return this.filterContainer.is(":visible");},isCollapsed:function(){var $filterItems=Runner.isBootstrap()?this.expanderElem.siblings().children("li"):this.expanderElem.siblings();return!$filterItems.not("."+this.collapsedValuesClass+",."+this.hiddenValuesClass+",."+this.hiddenFilterItemClass).length;},adjustExpander:function(collapsed){var $expanderIcon=$("."+this.btnExpanderIndicatorClass,this.expanderElem);if(!Runner.isBootstrap()){$expanderIcon.html(collapsed?"&#x25BC;":"&#x25B2;");}else{$expanderIcon.toggleClass("glyphicon-triangle-bottom",collapsed);$expanderIcon.toggleClass("glyphicon-triangle-top",!collapsed);}},clearControl:function(){this.setValue('');},updateValue:function(value){this.setValue(value);},isDependent:function(){return this.dependent;},isMultiSelected:function(){return false;}});Runner.controls.SimpleFilterControl=Runner.extend(Runner.controls.FilterControl,{superclass:{},valueLinkClass:"",constructor:function(cfg){Runner.controls.SimpleFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.SimpleFilterControl.superclass;this.valueLinkClass=this.gfieldName+"-filter-value";this.setValue(this.defaultValuesArray.join(', '));this.initButtons();},initButtons:function(){var ctrl=this,delBtnClass="delFilterCtrlButt_"+(this.dependent?this.goodOutermostParentName:this.gfieldName)+"_"+this.searchController.id;if(Runner.isBootstrap()){this.filterPanelContainer.off("click.filters"+this.gfieldName);}
this.filterPanelContainer.on("click.filters"+this.gfieldName,"."+delBtnClass,function(e){var $delButton=$(this);valueToDelete=$(this).data('delete').toString();ctrl.clearFilterValue(valueToDelete,$delButton.parent(".filter-values"));ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;});if(!this.hasDependent){this.filterPanelContainer.on("click.filters"+this.gfieldName,"."+this.filterValueBlockContainerClass+"-"+this.gfieldName,function(e){var $valueLink=$("."+ctrl.valueLinkClass,this);if(!$valueLink.length){return;}
ctrl.ctrlValue=$valueLink.attr("data-filtervalue");ctrl.updateParentFilters($valueLink.data("parentFiltersValues"));ctrl.clearDependentFilters();ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;}).on("click","."+this.valueLinkClass,function(e){e.preventDefault();});}else{$("."+ctrl.filterValueBlockContainerClass+"-"+ctrl.gfieldName,ctrl.filterContainer).removeClass(ctrl.filterLinkClass);this.filterPanelContainer.on("click","."+this.valueLinkClass,function(e){var $valueLink=$(this);ctrl.ctrlValue=$valueLink.data("filtervalue");ctrl.updateParentFilters($valueLink.data("parentFiltersValues"));ctrl.clearDependentFilters();ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;});}
this.superclass.initButtons.call(this);},updateParentFilters:function(parentFiltersValuesData){if(!this.dependent){return;}
this.searchController.updateParentFilters(parentFiltersValuesData);},clearFilterValue:function(valueToDelete,$container){this.setValue('');}});Runner.controls.MultiSelectFilterControl=Runner.extend(Runner.controls.FilterControl,{checkboxes:[],checkboxClass:'',superclass:{},commonCheckboxClass:"multifilter-checkbox",parentCheckboxClass:"",constructor:function(cfg){this.checkboxes=[];Runner.controls.MultiSelectFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.MultiSelectFilterControl.superclass;this.applyButton=$(".filter-apply-"+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.checkboxClass="filter_"+this.gfieldName+"_"+this.searchController.id;this.checkboxes=$("."+this.checkboxClass);this.selectAllCheckbox=$(".filter-selectAll-"+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.parentCheckboxClass=this.dependent?"filter_"+this.goodParentName+"_"+this.searchController.id:"";this.adjustSelectAllCheckbox();if(this.filtered&&!this.dependent){this.setValue(this.defaultValuesArray);}
this.initButtons();},adjustSelectAllCheckbox:function(){var currentState=this.selectAllCheckbox.is(":checked"),allChecked=this.checkboxes.length===this.checkboxes.filter(":checked").length
this.selectAllCheckbox.prop("checked",currentState&&allChecked);},initButtons:function(){var ctrl=this;this.selectAllCheckbox.on("click",function(e){e.stopPropagation();}).on("change",function(e){ctrl.checkboxes.prop("checked",this.checked);ctrl.clearDependentFilters(true);return false;});this.checkboxes.on("click",function(e){ctrl.adjustSelectAllCheckbox();ctrl.adjustDependentFilters(this);ctrl.adjustInvisibleCheckboxes(this);}).on("change",function(e){ctrl.adjustParentFilterCheckbox(this);});if(!this.hasDependent){$("."+this.filterValueBlockContainerClass+"-"+this.gfieldName).on("click",function(e){var $checkbox=$("."+ctrl.checkboxClass,this),checked=$checkbox.prop("checked"),checkbox;if(!$checkbox.length||$checkbox.is(e.target)){return;}
$checkbox.prop("checked",!checked);checkbox=$checkbox.get(0);ctrl.adjustSelectAllCheckbox();ctrl.adjustDependentFilters(checkbox);ctrl.adjustInvisibleCheckboxes(checkbox);$checkbox.trigger("change");});}
this.superclass.initButtons.call(this);},adjustDependentFilters:function(checkbox){this.clearDependentFilters(true);this.adjustDependentFilterCheckboxes(checkbox);},adjustDependentFilterCheckboxes:function(checkbox){if(!this.hasDependent){return;}
var $checkbox=$(checkbox),$filterValueBlock=$checkbox.parent('.'+this.filterValueBlockContainerClass);$('.'+this.commonCheckboxClass,$filterValueBlock).prop('checked',$checkbox.is(':checked'));},adjustParentFilterCheckbox:function(checkbox){if(!this.dependent){return;}
var $checkbox=$(checkbox),$parentFilterValueBlock=$checkbox.parents('.'+this.filterValueBlockContainerClass).eq(1),checked=$checkbox.is(':checked')||$('.'+this.checkboxClass+':checked',$parentFilterValueBlock).length>0;$parentFilterValueBlock.find('.'+this.parentCheckboxClass).prop('checked',checked).trigger('change');},adjustInvisibleCheckboxes:function(checkbox){if(!this.dependent){return}
var $checkbox=$(checkbox),checkboxValue=$checkbox.val(),parentValues=$checkbox.data('parentFiltersValues'),$similarHiddenBoxes=this.checkboxes.not(':visible').filter(function(){var $box=$(this),hiddenParentValues,pName;if($box.val()!==checkboxValue){return false;}
hiddenParentValues=$box.data('parentFiltersValues');for(pName in hiddenParentValues){if(hiddenParentValues[pName]!==parentValues[pName]){return false;}}
return true;});$similarHiddenBoxes.prop('checked',$checkbox.is(':checked')).trigger('change');},setValue:function(arr){this.checkboxes.each(function(index,domCheckbox){var checkbox=$(domCheckbox),pos=$.inArray(checkbox.val(),arr);if(pos!==-1){checkbox.prop('checked',true);arr.splice(pos,1);}});},getValue:function(){var arr=[],i,ctrl=this,$checked=$('.'+this.checkboxClass+':checked'),onDemand=this instanceof Runner.controls.OnDemandFilterControl;if(this.dependent){$checked=$checked.filter(':visible');}
if(this.filtered||this.applyButton.data('activated')||$checked.length!==this.checkboxes.length){$checked.each(function(index,domCheckbox){var $box=$(domCheckbox),values=[$box.val().replace('|','\\|')],parentFiltersValueData,i;if(ctrl.dependent){parentFiltersValueData=$box.data('parentFiltersValues');for(i=0;i<ctrl.parentFilterNames.length;i++){values.push(parentFiltersValueData[ctrl.parentFilterNames[i]].toString().replace('|','\\|'));}}
arr.push(values.join('|'));});}
return arr;},getFilterValue:function(encoded){var arr=this.getValue(),result='';for(i=0;i<arr.length;i++){this.ctrlValue=arr[i];result+=this.superclass.getFilterValue.call(this,encoded);}
return result;},clearControl:function(){this.checkboxes.prop('checked',false);this.selectAllCheckbox.prop('checked',false);},updateValue:function(value){this.checkboxes.prop('checked',false);this.setValue([value]);},isMultiSelected:function(){return true;}});Runner.controls.OnDemandFilterControl=Runner.extend(Runner.controls.FilterControl,{multiSelection:false,checkboxes:[],checkboxClass:'',btnMultiselectClass:"",btnApplyCaption:Runner.lang.constants.TEXT_FILTER_APPLY,superclass:{},multiSelectFCtrl:{},simpleFCtrl:{},filteredValuesClass:"filter-ready-value",valueLinkClass:"",commonCheckboxClass:"multifilter-checkbox",parentCheckboxClass:"",constructor:function(cfg){this.checkboxes=[];Runner.controls.OnDemandFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.OnDemandFilterControl.superclass;this.multiSelectFCtrl=Runner.controls.MultiSelectFilterControl.prototype;this.simpleFCtrl=Runner.controls.SimpleFilterControl.prototype;this.btnMultiselectClass='filter-'+(this.dependent?this.goodOutermostParentName:this.gfieldName)+'-btn-multiselect';this.applyButton=$("."+this.btnMultiselectClass);this.checkboxClass='filter_'+this.gfieldName+"_"+this.searchController.id;this.checkboxes=$('.'+this.checkboxClass);this.parentCheckboxClass=this.dependent?'filter_'+this.goodParentName+"_"+this.searchController.id:'';this.selectAllCheckbox=$('.filter-selectAll-'+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.valueLinkClass=this.gfieldName+'-filter-value';this.setValue(this.defaultValuesArray.join(', '));this.initButtons();},adjustSelectAllCheckbox:Runner.controls.MultiSelectFilterControl.prototype.adjustSelectAllCheckbox,adjustDependentFilters:Runner.controls.MultiSelectFilterControl.prototype.adjustDependentFilters,adjustDependentFilterCheckboxes:Runner.controls.MultiSelectFilterControl.prototype.adjustDependentFilterCheckboxes,adjustParentFilterCheckbox:Runner.controls.MultiSelectFilterControl.prototype.adjustParentFilterCheckbox,adjustInvisibleCheckboxes:Runner.emptyFn,initButtons:function(){var ctrl=this,anotherApplyButtonExists=!!$(".filter-apply-"+this.gfieldName).not(this.applyButton).length;if(this.dependent){anotherApplyButtonExists=!!$(".filter-apply-"+this.goodOutermostParentName).not(this.applyButton).length;}
this.applyButton.one("click",function(e){var $button=$(this);if(anotherApplyButtonExists){$button.hide();}
$button.text(ctrl.btnApplyCaption).addClass(ctrl.btnApplyClass).removeClass(ctrl.btnMultiselectClass);$("."+ctrl.valueLinkClass).removeClass(ctrl.valueLinkClass).addClass("multiSelect-"+ctrl.valueLinkClass);$("."+ctrl.filterValueBlockContainerClass+"-"+ctrl.gfieldName,ctrl.filterContainer).removeClass(ctrl.filterLinkClass);ctrl.checkboxes.show();ctrl.addNewValueLinkFunctionality();ctrl.selectAllCheckbox.show();if(!ctrl.dependent||ctrl.filtered){$("."+ctrl.hiddenValuesClass,ctrl.filterContainer).removeClass(ctrl.hiddenValuesClass);$("."+ctrl.filteredValuesClass+".ondemand",ctrl.filterContainer).hide().addClass(ctrl.hiddenValuesClass);}
$(".show-more-hidden",ctrl.filterContainer).removeClass("show-more-hidden");if(ctrl.dependent&&!ctrl.searchController.hasFilteredParentFilter(ctrl.parentFilterNames)){$(".delFilterCtrlButt_"+(ctrl.dependent?ctrl.goodOutermostParentName:ctrl.gfieldName)+"_"+ctrl.searchController.id).hide();}
ctrl.multiSelection=true;return false;});this.simpleFCtrl.initButtons.call(this);this.multiSelectFCtrl.initButtons.call(this);},updateParentFilters:Runner.controls.SimpleFilterControl.prototype.updateParentFilters,addNewValueLinkFunctionality:function(){var newValueLinkClass='multiSelect-'+this.gfieldName+'-filter-value';this.filterPanelContainer.on('click.filters'+this.gfieldName,'.'+newValueLinkClass,function(e){var $link=$(this),linkValue=$link.data('filtervalue')
$checkbox=$link.siblings().filter(function(){return this.value===linkValue;});$checkbox.prop('checked',true);return false;});},getValue:function(){if(this.multiSelection||this.filtered){return this.multiSelectFCtrl.getValue.call(this);}
return this.superclass.getValue.call(this);},getFilterValue:function(encoded){if(this.multiSelection||this.filtered){return this.multiSelectFCtrl.getFilterValue.call(this,encoded);}
return this.superclass.getFilterValue.call(this,encoded);},clearControl:function(){if(this.multiSelection||this.filtered){this.checkboxes.prop('checked',false);this.selectAllCheckbox.prop('checked',false);}
this.setValue('');},clearFilterValue:function(valueToDelete,$container){if(!this.dependent){this.checkboxes.filter(function(){return this.value===valueToDelete;}).prop('checked',false);return;}
this.checkboxes.filter(function(){return!!$container.find(this).length;}).prop('checked',false);if(this.hasDependent){$('.'+this.commonCheckboxClass,$container).prop('checked',false);}},updateValue:function(value){if(this.multiSelection){this.checkboxes.prop('checked',false);this.setValue([value]);}
this.setValue(value);},isMultiSelected:function(){return this.multiSelection;}});Runner.controls.SliderFilterControl=Runner.extend(Runner.controls.FilterControl,{sliderElem:{},range:true,minValue:0,maxValue:0,step:1,knobsType:0,roundedMax:0,roundedMin:0,roundedMaxKnobValue:0,roundedMinKnobValue:0,useApllyBtn:false,constructor:function(cfg){Runner.controls.SliderFilterControl.superclass.constructor.call(this,cfg);},setDefaultValues:function(){this.ctrlValues=[this.minKnobValue,this.maxKnobValue];},getValue:function(){return this.getCaptionValue(this.ctrlValues[0])+" - "+this.getCaptionValue(this.ctrlValues[1]);},init:function(){var jQsliderValues,sliderParams;jQsliderValues=$("#slider_values_"+this.gfieldName);this.jQmax=$(".slider-max",jQsliderValues);this.jQmin=$(".slider-min",jQsliderValues);this.setDefaultValues();this.range=this.getRange();sliderParams=this.getSliderParams();this.sliderElem=$("#slider_"+this.gfieldName).slider(sliderParams);this.setPageMaxZIndex();this.initButtons();},initShowMoreButton:Runner.emptyFn,setPageMaxZIndex:function(){var handleZIndex=parseInt($('.ui-slider-handle',this.sliderElem).css('z-index'),10);Runner.setZindexMax(handleZIndex);},getRange:function(){if(this.knobsType===Runner.controls.constants.FILTER_KNOBS_MIN_ONLY){return'max';}
if(this.knobsType===Runner.controls.constants.FILTER_KNOBS_MAX_ONLY){return'min';}
return true;},getSliderParams:function(){var filter=this,sliderParams={range:this.range,min:this.roundedMin,max:this.roundedMax,step:parseFloat(this.step)},typeBasedParams;typeBasedParams=this.getSliderParamsByType(this.range);Runner.apply(sliderParams,typeBasedParams);if(!this.useApllyBtn){sliderParams.stop=function(){filter.searchController.submitSearch();}}
return sliderParams;},getSliderParamsByType:function(range){var filter=this;switch(this.range){case'min':return{value:parseFloat(this.roundedMaxKnobValue),slide:function(event,ui){filter.processMaxValue(ui.value,$(this).slider("option","min")===ui.value);}};case'max':return{value:parseFloat(this.roundedMinKnobValue),slide:function(event,ui){filter.processMinValue(ui.value,$(this).slider("option","max")===ui.value);}};default:return{values:[parseFloat(this.roundedMinKnobValue),parseFloat(this.roundedMaxKnobValue)],slide:function(event,ui){var oldValues=$(this).slider("values"),min=ui.values[0],max=ui.values[1],oldMin=oldValues[0],oldMax=oldValues[1];if(min!==oldMin){filter.processMinValue(min,min===max);return;}
if(max!==oldMax){filter.processMaxValue(max,min===max);return;}}};}},processMinValue:function(min,minIsEqualToMax){var value=this.getSliderValue(min,true,minIsEqualToMax);this.setMinValue(value);this.setCaptions(value,true);},processMaxValue:function(max,minIsEqualToMax){var value=this.getSliderValue(max,false,minIsEqualToMax);this.setMaxValue(value);this.setCaptions(value,false);},setCaptions:function(value,isLower){var jQmainCaption=isLower?this.jQmin:this.jQmax,caption=this.getCaptionValue(value);jQmainCaption.html(caption);},getSliderValue:function(value,isLower,minIsEqualToMax){if(value===this.roundedMin){return parseFloat(this.minValue);}
if(value===this.roundedMax){return parseFloat(this.maxValue)}
return value;},getCaptionValue:function(value){if(this.viewAsCurrency){return this.getCurrencyFormattedString(value,this.currencySettings);}
if(this.viewAsNumber){return this.getNumberFormattedString(value,this.numberSettings);}
return value;},setMinValue:function(minValue){this.ctrlValues[0]=minValue;},setMaxValue:function(maxValue){this.ctrlValues[1]=maxValue;},getFilterValue:function(encoded){var value,prepFName;if(this.ctrlValues[0]===undefined&&this.ctrlValues[1]===undefined){return'';}
if(!this.filtered){this.prepareControlValues();}
if(this.knobsAreOnTheLimits()){return'';}
value=this.getTypeBasedValue();prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;return"("+prepFName+this.separator+value+")";},getTypeBasedValue:function(encoded){switch(this.range){case'min':return this.getPreparedMaxValue(encoded);case'max':return this.getPreparedMinValue(encoded);default:var valueMin=this.getPreparedMinValue(encoded),valueMax=this.getPreparedMaxValue(encoded);return valueMin+"~"+valueMax;}},getPreparedMinValue:function(encoded){return this.getPreparedValue(this.ctrlValues[0],encoded);},getPreparedMaxValue:function(encoded){return this.getPreparedValue(this.ctrlValues[1],encoded);},prepareControlValues:function(){if(this.ctrlValues[0]===undefined){this.ctrlValues[0]=this.minValue;}
if(this.ctrlValues[1]===undefined){this.ctrlValues[1]=this.maxValue;}},knobsAreOnTheLimits:function(){return this.ctrlValues[0]===this.minValue&&this.ctrlValues[1]===this.maxValue;},getNumberAbsoluteValueFormatted:function(number){var iDigits=this.commonFormatSettings['decimalDigits'],grouping=this.commonFormatSettings["grouping"],ptr,i,outStart,outEnd;number=number.toFixed(iDigits);intPart=number>=0?Math.floor(number):Math.floor(-number);fracPart=number>=0?number-intPart:-number-intPart;out=intPart.toFixed(0);if(grouping.length&&parseInt(grouping[0],10)){ptr=out.toString().length;for(i=0;i<grouping.length;i++){if(!parseInt(grouping[i],10)){i--;}
if(ptr<=grouping[i]){break;}
ptr=ptr-grouping[i];outStart=out.slice(0,ptr);outEnd=out.slice(ptr);out=outStart+this.commonFormatSettings["thousandSep"]+outEnd;}}
if(iDigits>0){fracPart=(fracPart*Math.pow(10,iDigits)).toFixed(0);while(fracPart.length<iDigits){fracPart="0"+fracPart;}
out+=this.commonFormatSettings["decimalSep"]+fracPart;}
return out;},getNumberFormattedString:function(number){var positiveSign=number>=0,numberSettings=this.formatSettings,outString=this.getNumberAbsoluteValueFormatted(number);if(positiveSign||parseInt(outString,10)===0){return numberSettings["LOCALE_SPOSITIVESIGN"]+outString;}
switch(numberSettings["LOCALE_INEGNUMBER"]){case"0":return"("+outString+")";case"1":return"-"+outString;case"2":return"- "+outString;case"3":return outString+"-";case"4":return outString+" -";default:return outString;}},getCurrencyFormattedString:function(number){var positiveSign=number>=0,currencySettings=this.formatSettings,outString=this.getNumberAbsoluteValueFormatted(number);if(positiveSign||parseInt(outString,10)===0){switch(currencySettings["LOCALE_ICURRENCY"]){case"0":return currencySettings["LOCALE_SCURRENCY"]+outString;case"1":case"2":return currencySettings["LOCALE_SCURRENCY"]+" "+outString;case"3":return outString+" "+currencySettings["LOCALE_SCURRENCY"];default:return outString;}}
switch(currencySettings["LOCALE_INEGCURR"]){case"0":return"("+currencySettings["LOCALE_SCURRENCY"]+outString+")";case"1":return"-"+currencySettings["LOCALE_SCURRENCY"]+outString;case"2":return currencySettings["LOCALE_SCURRENCY"]+"-"+outString;case"3":return currencySettings["LOCALE_SCURRENCY"]+outString+"-";case"4":return"("+outString+currencySettings["LOCALE_SCURRENCY"]+")";case"5":return"-"+outString+currencySettings["LOCALE_SCURRENCY"];case"6":return outString+"-"+currencySettings["LOCALE_SCURRENCY"];case"7":return outString+currencySettings["LOCALE_SCURRENCY"]+"-";case"8":return"-"+outString+" "+currencySettings["LOCALE_SCURRENCY"];case"9":return"-"+currencySettings["LOCALE_SCURRENCY"]+" "+outString;case"10":return outString+" "+currencySettings["LOCALE_SCURRENCY"]+"-";case"11":return currencySettings["LOCALE_SCURRENCY"]+" "+outString+"-";case"12":return currencySettings["LOCALE_SCURRENCY"]+" -"+outString;case"13":return outString+"- "+currencySettings["LOCALE_SCURRENCY"];case"14":return"("+currencySettings["LOCALE_SCURRENCY"]+" "+outString+")";case"15":return"("+outString+" "+currencySettings["LOCALE_SCURRENCY"]+")";default:return outString;}},clearControl:function(){this.ctrlValues=[];}});Runner.controls.DateSliderFilterControl=Runner.extend(Runner.controls.SliderFilterControl,{stepType:Runner.controls.constants.FILTER_STEP_DAY,isFieldDateType:true,processWrappers:true,monthNames:[Runner.lang.constants.TEXT_MONTH_JAN,Runner.lang.constants.TEXT_MONTH_FEB,Runner.lang.constants.TEXT_MONTH_MAR,Runner.lang.constants.TEXT_MONTH_APR,Runner.lang.constants.TEXT_MONTH_MAY,Runner.lang.constants.TEXT_MONTH_JUN,Runner.lang.constants.TEXT_MONTH_JUL,Runner.lang.constants.TEXT_MONTH_AUG,Runner.lang.constants.TEXT_MONTH_SEP,Runner.lang.constants.TEXT_MONTH_OCT,Runner.lang.constants.TEXT_MONTH_NOV,Runner.lang.constants.TEXT_MONTH_DEC],constructor:function(cfg){Runner.controls.DateSliderFilterControl.superclass.constructor.call(this,cfg);},setDefaultValues:function(){var minKnob=this.minKnobValue,maxKnob=this.maxKnobValue;if(minKnob){minKnob=this.parseDateTime(minKnob,this.dateFormat);}
if(maxKnob){maxKnob=this.parseDateTime(maxKnob,this.dateFormat);}
this.ctrlValues=[minKnob,maxKnob];},init:function(){var jQsliderValues=$("#slider_values_"+this.gfieldName);this.jQcaptPrefix=$(".slider-caption-prefix",jQsliderValues);this.jQcaptPostfix=$(".slider-caption-postfix",jQsliderValues);this.dateFormat=Runner.pages.PageSettings.getGlobalData("locale").dateFormat;this.dateDelimiter=Runner.pages.PageSettings.getGlobalData("locale").dateDelimiter;this.minDate=this.parseDateTime(this.minValue,this.dateFormat);this.minDateInMs=this.minDate.getTime();this.maxDate=this.parseDateTime(this.maxValue,this.dateFormat);this.maxDateInMs=this.maxDate.getTime();if(this.stepType===Runner.controls.constants.FILTER_STEP_SEC||this.stepType===Runner.controls.constants.FILTER_STEP_MIN){this.realMaxDate=this.parseDateTime(this.realMaxValue,this.dateFormat);this.realMinDate=this.parseDateTime(this.realMinValue,this.dateFormat);}
Runner.controls.DateSliderFilterControl.superclass.init.call(this);},printDateTime:Runner.controls.DateField.prototype.printDateTime,parseDateTime:Runner.controls.DateField.prototype.parseDateTime,getSliderValue:function(value,isLower,minIsEqualToMax){var prepDate=new Date(this.minDateInMs),year,month,day,unitStep;switch(this.stepType){case Runner.controls.constants.FILTER_STEP_SEC:case Runner.controls.constants.FILTER_STEP_MIN:if(value===this.roundedMax){prepDate=this.realMaxDate;break;}
if(value===this.roundedMin){prepDate=this.realMinDate;break;}
prepDate=new Date(this.minDateInMs+value*1000);break;case Runner.controls.constants.FILTER_STEP_MONTH:month=prepDate.getMonth()+value;prepDate.setMonth(month);if(!isLower){prepDate.setDate(prepDate.getDate()-1);}
if(minIsEqualToMax){month=prepDate.getMonth();year=prepDate.getFullYear();month=isLower?month-1:month+2;day=isLower?1:0;prepDate=new Date(year,month,day);}
break;case Runner.controls.constants.FILTER_STEP_YEAR:month=isLower?0:11;day=isLower?1:31
if(value===this.roundedMax){year=this.maxDate.getFullYear();}else{unitStep=parseFloat(this.step)===1;year=prepDate.getFullYear()+value;if(!isLower){year=(minIsEqualToMax||unitStep)?year:year-1;}else{year=(minIsEqualToMax&&!unitStep)?year-1:year;}}
prepDate=new Date(year,month,day);break;default:prepDate=new Date(this.minDateInMs+value*1000);}
return prepDate;},setCaptions:function(prepDate,isLower){Runner.controls.DateSliderFilterControl.superclass.setCaptions.call(this,prepDate,isLower);if(this.processWrappers){this.setWrapperCaption(isLower,prepDate);}},setWrapperCaption:function(isLower,date){this.setCaptionsVisibility(isLower,date);if(!isLower&&this.showTime){this.jQcaptPostfix.html(this.printTime(date));return;}
if(isLower&&this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){this.jQcaptPrefix.html(this.monthNames[date.getMonth()]);}},setCaptionsVisibility:function(isLower,date){var otherKnobDate=isLower?(this.ctrlValues[1]||this.maxDate):(this.ctrlValues[0]||this.minDate),visible;if(this.showTime){visible=this.checkDatesEqual(otherKnobDate,date);this.jQcaptPostfix.toggle(visible);this.jQmax.toggle(!visible);return;}
if(this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){visible=otherKnobDate.getFullYear()===date.getFullYear();this.jQcaptPrefix.toggle(visible);this.jQmin.toggle(!visible);}},checkDatesEqual:function(date1,date2){return date1.getFullYear()===date2.getFullYear()&&date1.getMonth()===date2.getMonth()&&date1.getDate()===date2.getDate();},getCaptionValue:function(date){if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){return date.getFullYear();}
if(this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){return this.monthNames[date.getMonth()]+" "+date.getFullYear();}
return this.printDateTime(date,this.dateFormat,true);},getPreparedMaxValue:function(encoded){var date=this.ctrlValues[1],stringValue=this.getStringValueFromDate(date);return Runner.controls.DateSliderFilterControl.superclass.getPreparedValue.call(this,stringValue,encoded);},getPreparedMinValue:function(encoded){var date=this.ctrlValues[0],stringValue=this.getStringValueFromDate(date);return Runner.controls.DateSliderFilterControl.superclass.getPreparedValue.call(this,stringValue,encoded);},prepareControlValues:function(){var date;if(this.ctrlValues[0]===undefined||this.ctrlValues[0]===null){date=this.realMinDate||this.minDate;if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){date=new Date(date.getFullYear(),0,1);}
this.ctrlValues[0]=date;}
if(this.ctrlValues[1]===undefined||this.ctrlValues[1]===null){date=this.realMaxDate||this.maxDate;if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){date=new Date(date.getFullYear(),11,31);}
this.ctrlValues[1]=this.maxDate;}},knobsAreOnTheLimits:function(){if(this.ctrlValues[0].toString()===(this.realMinDate||this.minDate).toString()&&this.ctrlValues[1].toString()===(this.realMaxDate||this.maxDate).toString()){return true;}
return false;},getStringValueFromDate:function(date){var dateString,day=date.getDate(),month=date.getMonth()+1,year=date.getFullYear(),hours,minutes,seconds;dateString=year+'-'+month+'-'+day;if(this.showTime){hours=date.getHours();hours=hours<10?'0'+hours:hours;minutes=date.getMinutes();minutes=minutes<10?'0'+minutes:minutes;seconds=date.getSeconds();seconds=seconds<10?'0'+seconds:seconds;dateString+=' '+hours+':'+minutes+':'+seconds;}
return dateString;},printTime:function(date){var hours=date.getHours(),minutes=date.getMinutes(),seconds=date.getSeconds(),time=this.timeFormat,designator;if(!this.is24hoursFormat){designator=hours>=12?this.designators["pm"]:this.designators["am"];designator=hours>=24?"":designator;time=time.replace("tt",designator);hours=hours>12&&hours<24?hours-12:hours;hours=hours===0?12:hours;hours=this.leadingZero&&hours<10?'0'+hours:hours;time=time.replace(this.leadingZero?"hh":"h",hours);}else{hours=this.leadingZero&&hours<10?'0'+hours:hours;time=time.replace(this.leadingZero?"HH":"H",hours);}
time=time.replace("mm",minutes<10?'0'+minutes:minutes);if(this.showSeconds){time=time.replace("ss",seconds<10?'0'+seconds:seconds);}else{time=time.replace(this.timeDelimiter+"ss","");}
return time;}});Runner.controls.TimeSliderFilterControl=Runner.extend(Runner.controls.DateSliderFilterControl,{TimezoneOffsetInHours:0,isFieldTimeType:true,offsetDaytimeHours:24,processWrappers:false,constructor:function(cfg){Runner.controls.TimeSliderFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.TimezoneOffsetInHours=new Date().getTimezoneOffset()/60;this.offsetDaytimeHours=24+this.TimezoneOffsetInHours;Runner.controls.TimeSliderFilterControl.superclass.init.call(this);},getHoursValue:function(date){var dateInHours=date.getTime()/3600000;if(dateInHours<this.offsetDaytimeHours){return date.getHours();}
return Math.floor(dateInHours-this.TimezoneOffsetInHours);},getStringValueFromDate:function(date){var hours=this.getHoursValue(date),minutes=date.getMinutes(),seconds=date.getSeconds();hours=hours<10?'0'+hours:hours;minutes=minutes<10?'0'+minutes:minutes;seconds=seconds<10?'0'+seconds:seconds;return hours+':'+minutes+':'+seconds;},getCaptionValue:function(date){return this.printTime(date);}});Runner.pages.Defaults=function(){this.globalSettings={debugMode:false,pwdStrong:false,isMobile:false,mainPageLayoutVersion:null,webRootPath:"",s508:false,isFB:false,FBappId:"",FBLoginUrl:"",popupPagesLayoutNames:{},loginFormType:0};this.tableSettings={ajaxSuggest:true,confirmTime:250,copy:false,defaultMembership:[],defaultRights:[],detailTables:{},popupPagesLayoutNames:{},dpParams:[],enableCtrls:true,events:{},firstTime:0,columnOrder:[],fieldSettings:{},hasEvents:false,hideColumns:[],isAllowFieldsReordering:false,isAllowShowHideFields:false,isEditOwn:false,isInlineAdd:false,isInlineEdit:false,isShowDetails:false,isUseAudio:false,isUseCK:false,detailsLinksOnList:0,simpleSearchActive:false,isUseHighlite:false,isUsePopUp:false,isUseResize:false,isUseToolTips:false,entityType:0,isUseVideo:false,listGridLayout:0,keys:{},listFields:[],locking:false,lockRecIds:[],masterPageType:"",masterTable:"",masterKeys:[],maxPages:1,nextKeys:{},pageMode:0,pageNumber:0,pageSkinStyle:"",passFieldName:'password',permissions:{},prevKeys:{},proxy:{},recsPerRowList:1,msg_emailError:"",msg_passwordError:"",msg_userError:"",rightsGroups:[],rightsTables:[],shortTNames:[],showAddInPopup:false,showEditInPopup:false,inlineEditAvailable:false,showRows:false,showViewInPopup:false,sKeys:"",strCaption:"",strKey:[],totalFields:[],usersList:[],warnOnLeaving:false,view:false,scrollGridBody:false,searchSaving:false,importFieldsLables:{},printerPageOrientation:Runner.pages.constants.PORTRAIT_PRINT_ORIENTATION,printGridLayout:Runner.pages.constants.HORIZONTAL_LAYOUT,reportPrintLayout:Runner.pages.constants.STEPPED_LAYOUT,reportType:Runner.pages.constants.REPORT_TYPE_STANDART,reportPrintMode:Runner.pages.constants.REPORT_MODE_PRINT_FRIENDLY,reportPrintPartitionType:Runner.pages.constants.REPORT_PRINT_PAGE_FIT,reportPrintGroupsPerPage:3,lowGroup:1,pageWidth:700,pageHeight:900,createPdf:0,pdfFitToPage:1,exportPdf:0,printerPagePDF:false,crossTable:false,isRTL:false,isDashSearchPage:false,afterAddAction:0,afterAddActionDetTable:"",afterEditAction:0,afterEditActionDetTable:"",extraSearchPageParams:null,crossParams:null};this.fieldSettings={acceptFileTypes:".+$",autoCompleteFields:[],autoUpload:false,parentFields:[],compatibilityMode:false,dateEditType:Runner.controls.constants.EDIT_DATE_SIMPLE,dispField:"",editFormat:Runner.controls.constants.EDIT_FORMAT_NONE,freeInput:false,initialYear:100,isDisabled:false,isHidden:false,isUseTimeStamp:false,lastYear:10,lcType:Runner.controls.constants.LCT_DROPDOWN,linkField:"",lookupTable:"",mask:"",maxFileSize:undefined,maxNumberOfFiles:1,maxTotalFileSize:undefined,nHeight:200,nWidth:100,RTEType:"",Multiselect:false,selectSize:1,showTime:false,strName:"",timePick:{},validation:null,viewFormat:Runner.controls.constants.FORMAT_NONE};var self=this,SOURCE_GLOBAL='g',SOURCE_TABLE='t',SOURCE_FIELD='f',getSettings=function(source,settingName){var sourceName=source==SOURCE_GLOBAL?'globalSettings':source==SOURCE_TABLE?'tableSettings':'fieldSettings';if(self[sourceName][settingName]!=undefined){return self[sourceName][settingName];}
return null;};this.getGlobalSettings=function(settingName){return getSettings(SOURCE_GLOBAL,settingName);};this.getTableSettings=function(settingName){return getSettings(SOURCE_TABLE,settingName);};this.getFieldSettings=function(settingName){return getSettings(SOURCE_FIELD,settingName);};this.getValidationSettings=function(){return{regExp:null,validationArr:[],customMessages:[]};};};Runner.pages.Defaults=new Runner.pages.Defaults();Runner.pages.PageManager=function(){var tables={},beforeUnloadPool=[];if(window.onunload){beforeUnloadPool.push(window.onBeforeUnload,window,[]);}
window.onunload=function(){window.Runner.pages.PageManager.callUnload();}
return{register:function(pageController){if(!pageController){return;}
var pageTable=pageController.tName,pageId=pageController.pageId;tables[pageTable]=tables[pageTable]||{};tables[pageTable][pageId]=pageController;},getAt:function(tName,pageId){if(!tables[tName]||!tables[tName][pageId]){return false;}
return tables[tName][pageId];},getById:function(pageId){if(typeof pageId=="undefined"){return false;}
for(var tName in tables){if(typeof tables[tName][pageId]!="undefined"){return tables[tName][pageId];}}
return false;},unregister:function(tName,pageId){if(!tables[tName]){return false;}
if(!pageId){for(var id in tables[tName]){this.unregister(tName,id);}
delete tables[tName];}else if(tables[tName][pageId]){if(typeof tables[tName][pageId].destructor==="function"){tables[tName][pageId].destructor();}
if(tables[tName]!==undefined&&tables[tName][pageId]!==undefined){Runner.pages.PageControlsMap.removeMap(tName,tables[tName][pageId].pageType,pageId);Runner.pages.PageViewControlsMap.removeMap(tName,tables[tName][pageId].pageType,pageId);delete tables[tName][pageId];}}
return true;},initPages:function(){var controlsMap=Runner.pages.PageControlsMap.getMap(),viewControlsMap=Runner.pages.PageViewControlsMap.getMap(),cfg,tName,pageType,pageId;for(tName in controlsMap){for(pageType in controlsMap[tName]){for(pageId in controlsMap[tName][pageType]){Runner.mainPageLayoutVersion=Runner.mainPageLayoutVersion||controlsMap[tName][pageType][pageId].layoutVersion;cfg={tName:tName,pageType:pageType,pageId:pageId,controlsMap:controlsMap[tName][pageType][pageId]||{},viewControlsMap:viewControlsMap[tName][pageType][pageId]||{},pageMode:Runner.pages.PageSettings.getTableData(tName,"pageMode"),openMode:Runner.pages.constants.OPENMODE_PRELOADED};this.initPage(cfg);}}}
this.initPages=Runner.emptyFn;Runner.stopLoading();},createPopup:function(){var args={centered:true,closeByButton:true,modal:this.modal,bodyContent:this.bodyCont,headerContent:this.headerCont,footerContent:this.footerCont};if(!Runner.isBootstrap()){Runner.pages.PageManager.createFlyWin.call(this,args,true,null,$.proxy(this.afterCloseFlyWinHandler,this));}else{Runner.pages.PageManager.createBSWin.call(this,args,true,null,$.proxy(this.afterCloseFlyWinHandler,this));}},putToContainer:function(obj,container){obj=obj||this;container=container||this.openContainer;this.openContainer=this.openContainer||container;$(container).html(obj.bodyCont).prepend(obj.headerCont).append(obj.footerCont);},createPagePanel:function(obj){var $panel=$("<div class='panel panel-primary'></div>"),$headerCont=$(obj.headerCont),$footerCont=$(obj.footerCont),$body,$header,$footer,footerHeight=0;$header=$("<div></div>").addClass("panel-heading").append($headerCont).appendTo($panel);$header.find('.btn').removeClass('btn-primary').addClass('btn-default').addClass('btn-xs');$body=$("<div></div>").addClass("panel-body").html(obj.bodyCont).appendTo($panel);if(obj.dashElementSettings&&obj.dashElementSettings.type==Runner.pages.constants.DASHBOARD_MAP){$body.addClass('bs-dashmap');}
if($footerCont.length){$footer=$("<div></div>").addClass("panel-footer").append($footerCont).appendTo($panel);footerHeight=$footer.height();}
if(obj.dashElementSettings&&obj.dashElementSettings.height){$body.css("height",(obj.dashElementSettings.height-footerHeight)+"px").css("overflow-y","auto");}
return $panel;},putToBootstrapDashContainer:function(obj,$container){obj=obj||this;var $panel=Runner.pages.PageManager.createPagePanel.call(this,obj);Runner.pages.PageManager.insertPanelIntoContainer.call(this,$panel,$container||$(this.openContainer),obj);},insertPanelIntoContainer:function($panel,$container,obj){var $pageDiv;if(this.pageData.gridTabs==''&&!this.$gridTabControl){$container.html('').append($panel);this.pageCont=$container.get(0);return;}
if(!this.$gridTabControl){this.$gridTabControl=$('<ul class="nav nav-tabs" role="tablist"></ul>');$pageDiv=$('<div class="bs-containedpage"></div>');$container.html('').append(this.$gridTabControl).append($pageDiv.append($panel));}else{$pageDiv=$container.children('.bs-containedpage');if(!$pageDiv.length){$pageDiv=$('<div class="bs-containedpage"></div>').appendTo($container);}
$pageDiv.html('').append($panel);}
this.pageCont=$pageDiv.get(0);},putToDashContainer:function(obj,$container){if(Runner.isBootstrap()){return Runner.pages.PageManager.putToBootstrapDashContainer.call(this,obj,$container);}
obj=obj||this;var $table=$("<table class='rnr-dbelemtable'></table>"),$headerCont=$(obj.headerCont),$footerCont=$(obj.footerCont),$body,$header,$footer;if($headerCont.length){if($headerCont.length>1){$headerCont=$("<div></div>").addClass("rnr-dbehcont").append($headerCont);}
$header=$("<td></td>").append($headerCont).appendTo($("<tr></tr>").appendTo($table)).addClass('rnr-tabelemheader');if(this.dashElementSettings){$header.addClass('rnr-dbelemheader');}}
$body=$("<td class='rnr-dbelembody'></td>").html(obj.bodyCont).appendTo($("<tr></tr>").appendTo($table));if(this.dashElementSettings){if(!Runner.isMobile&&this.dashElementSettings.width){$body.children().first().css("width",this.dashElementSettings.width+"px").css("overflow-x","auto");}
if(this.dashElementSettings.height){$body.children().first().css("height",this.dashElementSettings.height+"px").css("overflow-y","auto");}}
if($footerCont.length){if($footerCont.length>1){$footerCont.css("display","inline-block");}
$footer=$("<td class=''></td>").append($footerCont).appendTo($("<tr></tr>").appendTo($table)).addClass('rnr-tabelemfooter');if(this.dashElementSettings){$footer.addClass('rnr-dbelemfooter');}}
$container=$container||$(this.openContainer);$container.html('').append($table);this.pageCont=$container.get(0);},initPage:function(cfg){var page=Runner.pages.PageFactory(cfg),tasksToPrepend=[],tasksToAppend=[];if(!Runner.isMobile&&cfg.openMode===Runner.pages.constants.OPENMODE_POPUP){tasksToPrepend.push(this.createPopup);}else if(cfg.openMode===Runner.pages.constants.OPENMODE_CONTAINER){tasksToPrepend.push(this.putToContainer);}else if(cfg.openMode===Runner.pages.constants.OPENMODE_DASHCONTAINER){tasksToPrepend.push(this.putToDashContainer);}else if(cfg.openMode===Runner.pages.constants.OPENMODE_DASHTABS){tasksToPrepend.push(this.putToDashTab);}else if(cfg.openMode===Runner.pages.constants.OPENMODE_TABVIEW){tasksToPrepend.push(this.putToTab);}
tasksToPrepend.push(page.loadFiles);tasksToPrepend.push(page.createCharts);if(cfg.afterCreateHn){tasksToPrepend.push(cfg.afterCreateHn);}
if(cfg.afterInitHn){tasksToAppend.push(cfg.afterInitHn);}
if(!Runner.isMobile&&cfg.openMode===Runner.pages.constants.OPENMODE_POPUP){if(Runner.isBootstrap()){tasksToAppend.push(function(){Runner.pages.PageManager.correctBSWindowSize(page.bsWin,page);});}else{tasksToAppend.push(function(){Runner.pages.PageManager.correctYUIWindowSize(page.win,cfg.popupCentered,page);});}}
tasksToAppend.push(function(){page.fireEvent('afterPageReady',page,page.proxy,page.id);});page.prependInitTask(tasksToPrepend);page.addInitTask(tasksToAppend);page.goInitQueue();return page;},openPage:function(pageParams){var pageManager=this,ajaxRequestUrl=pageParams.requestUrl||Runner.pages.getUrl(pageParams.tName,pageParams.pageType),reqParams,i;pageParams.pageId=Runner.genId();if(pageParams.multiRecordPage){Runner.setIdCounter(pageParams.pageId+10000);}
pageParams.openMode=pageParams.openMode||Runner.pages.constants.OPENMODE_POPUP;reqParams={id:pageParams.pageId,onFly:1,isNeedSettings:true};if(pageParams.keys){for(i=0;i<pageParams.keys.length;i++){reqParams[(pageParams.keyPref||"editid")+(i+1)]=pageParams.keys[i];}}
reqParams=Runner.apply(reqParams,pageParams.baseParams);this.loadPageLayoutCss(pageParams.tName,pageParams.pageType);Runner.runnerAJAX(ajaxRequestUrl,reqParams,function(ctrlsJSON){Runner.pages.PageSettings.addSettings('',ctrlsJSON.settings);Runner.applyPagesData(ctrlsJSON.pagesData);Runner.util.ScriptLoader.loadCSS(ctrlsJSON.CSSFiles);Runner.util.ScriptLoader.loadCSS(ctrlsJSON.additionalCSS);if(ctrlsJSON.additionalJS){$.each(ctrlsJSON.additionalJS,function(jsFile,jsFileReq){Runner.util.ScriptLoader.addJS([jsFile],jsFileReq);});}
Runner.util.ScriptLoader.onFilesLoaded(function(){Runner.pages.PageControlsMap.addMap(pageParams.tName,pageParams.pageType,pageParams.pageId,ctrlsJSON.controlsMap);Runner.pages.PageViewControlsMap.addMap(pageParams.tName,pageParams.pageType,pageParams.pageId,ctrlsJSON.viewControlsMap);var cfg={submitUrl:ajaxRequestUrl,editType:pageParams.editType||pageParams.baseParams.editType,controlsMap:ctrlsJSON.controlsMap?ctrlsJSON.controlsMap[pageParams.tName][pageParams.pageType][pageParams.pageId]:null,viewControlsMap:ctrlsJSON.viewControlsMap?ctrlsJSON.viewControlsMap[pageParams.tName][pageParams.pageType][pageParams.pageId]:null,headerCont:ctrlsJSON.headerCont||"",bodyCont:pageManager.wrapPageBody(ctrlsJSON.html,pageParams.tName,pageParams.pageType),footerCont:ctrlsJSON.footerCont||"",message:ctrlsJSON.message||""};Runner.apply(cfg,pageParams);Runner.setIdCounter(ctrlsJSON.idStartFrom);pageManager.initPage(cfg)},pageManager);Runner.util.ScriptLoader.load();});return pageParams.pageId;},replaceDashboardGridTabs:function(){if(!this.$gridTabControl){return;}
var $replacementTabs=$(this.pageData.gridTabs),$originalTab=$('[data-target="#'+this.tabSettings.tabPaneId+'"]:not([data-pageid])').closest('li'),$originalLink=$originalTab.children('a');$originalTab.hide();var attrs={'data-target':$originalLink.attr('data-target')}
$replacementTabs.children('a').attr(attrs);$replacementTabs.attr('data-tabidx',$originalTab.attr('data-tabidx'));if(!$originalTab.hasClass('active')){$replacementTabs.removeClass('active');}
this.$gridTabControl.find('[data-target="#'+this.tabSettings.tabPaneId+'"][data-pageid]').parent().remove();$originalTab.after($replacementTabs);this.$originalTab=$originalTab;},wrapPageBody:function(body,tName,pageType){if(!body){return'&nbsp;';}
return'<div class="rnr-pagewrapper '+Runner.pages.PageSettings.getTableData(tName,"pageSkinStyle")[pageType]+'">'+body+'</div>';},putToBootstrapDashTab:function(obj){var $contentContainer=$("<div/>"),$openContainer=$(this.openContainer),tabPaneId="tab"+this.tabSettings.tabControlName+"_"+this.tabSettings.tabId;obj=obj||this;if(!this.tabControl||!this.tabControl.length){this.tabControl=Runner.pages.PageManager.createTabsControl($openContainer,obj.tabSettings.tabControlName,obj.tabSettings.hiddenNav&&!this.pageData.gridTabs);}
$openContainer.show();if(this.pageData.gridTabs){this.$gridTabControl=this.tabControl.children('ul');this.tabSettings.tabPaneId=tabPaneId;this.replaceGridTabs=Runner.pages.PageManager.replaceDashboardGridTabs;}
Runner.pages.PageManager.putToBootstrapDashContainer.call(this,obj,$contentContainer);Runner.pages.PageManager.setTabWithinBootstrapTabsControl(this.tabControl,$contentContainer,tabPaneId,this.tabSettings.tabLabel,this.tabSettings.activeTab,this.tabSettings.tabIndex,this.tabSettings.hideTabsContent);},putToDashTab:function(obj){if(Runner.isBootstrap()){return Runner.pages.PageManager.putToBootstrapDashTab.call(this,obj);}
var $contentContainer=$("<div/>"),$openContainer=$(this.openContainer),tabId="tab"+this.tabSettings.tabControlName+"_"+this.tabSettings.tabId;obj=obj||this;if(!this.tabControl||!this.tabControl.length){this.tabControl=Runner.pages.PageManager.createTabsControl($openContainer,this.tabSettings.tabControlName,obj.tabSettings.hiddenNav);}
$openContainer.show();Runner.pages.PageManager.putToDashContainer.call(this,obj,$contentContainer);Runner.pages.PageManager.setTabWithinTabsControl(this.tabControl,$contentContainer,tabId,this.tabSettings.tabLabel,this.tabSettings.activeTab,this.tabSettings.tabIndex,this.tabSettings.hideTabsContent);},putToBootstrapTab:function(obj){obj=obj||this;var $contentContainer=$("<div/>"),tabId="tab"+this.tabSettings.tabControlName+"_"+this.tabSettings.tabId;if(!this.tabControl||!this.tabControl.length){this.tabControl=Runner.pages.PageManager.createBootstrapTabsControl(this.openContainer,this.tabSettings.tabControlName,this.tabSettings.hiddenNav);}
this.detCont=$contentContainer;Runner.pages.PageManager.putToDashContainer.call(this,obj,$contentContainer);Runner.pages.PageManager.setTabWithinBootstrapTabsControl(this.tabControl,$contentContainer,tabId,this.tabSettings.tabLabel,this.tabSettings.activeTab,this.tabSettings.tabIndex,this.tabSettings.hideTabsContent);},putToTab:function(obj){if(Runner.isBootstrap()){Runner.pages.PageManager.putToBootstrapTab.call(this,obj);return;}
obj=obj||this;var $contentContainer=$("<div/>"),tabId="tab"+obj.tabSettings.tabControlName+"_"+obj.tabSettings.tabId;if(!this.tabControl||!this.tabControl.length){this.tabControl=Runner.pages.PageManager.createTabsControl(obj.openContainer,obj.tabSettings.tabControlName);}
obj.detCont=$contentContainer;$contentContainer.addClass(Runner.pages.PageSettings.getTableData(obj.tName,"pageSkinStyle")[obj.pageType]);Runner.pages.PageManager.putToDashContainer.call(this,obj,$contentContainer);Runner.pages.PageManager.setTabWithinTabsControl(this.tabControl,$contentContainer,tabId,this.tabSettings.tabLabel,this.tabSettings.activeTab,this.tabSettings.tabIndex,this.tabSettings.hideTabsContent);},onTabShown:function(obj,callback){if(!obj.tabControl||!obj.tabControl.length){return;}
var panelId="tab"+obj.tabSettings.tabControlName+"_"+obj.tabSettings.tabId;if(obj.isBootstrap()){obj.tabControl.find("a[data-target='#"+panelId+"'][data-toggle='tab']").on("shown.bs.tab",function(e){callback();});}else{obj.tabControl.on("tabsactivate",function(event,ui){if(ui.newPanel.attr("id")===panelId){callback();}});}},createBootstrapTabsControl:function($container,name,hiddenNav){var $tabsControl=$("#tabs-"+name,$container),hiddenClass=hiddenNav?" hidden":"";if($tabsControl.length){return $tabsControl;}
return $('<div id="tabs-'+name+'"><ul class="nav nav-tabs'+hiddenClass+'" role="tablist" ></ul> <div class="tab-content"></div></div>').appendTo($container);},createTabsControl:function($container,name,hiddenNav){if(Runner.isBootstrap()){return Runner.pages.PageManager.createBootstrapTabsControl.call(this,$container,name,hiddenNav);}
var $tabsControl=$("#tabs-"+name,$container),hiddenClassAttr=hiddenNav?' class="rnr-hiddenelem" ':'';if($tabsControl.length&&$tabsControl.data('ui-tabs')){return $tabsControl;}
return $('<div id="tabs-'+name+'"><ul'+hiddenClassAttr+'></ul></div>').appendTo($container).tabs();},getTabControl:function($container,name){return $("#tabs-"+name,$container);},getDashElementTabControl:function(dashElementName,dashId){return $("#tabs-"+dashElementName,$('#dashelement_'+dashElementName+dashId).get(0));},setTabWithinBootstrapTabsControl:function($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIndex,hideTabsContent){if(!$tabsControl.length){return;}
var activeIdx,$activeLi,$tab=$("#"+tabElementId,$tabsControl);if($tab.length){$tabsControl.find("li[data-tabidx="+rnrTabIndex+"]").show();$tab.html('').append($tabContents);activeIdx=$tabsControl.data("activeIdx");if(activeIdx!==undefined){$activeLi=$tabsControl.children("ul").children("li").eq(activeIdx);if($activeLi.data("tabidx")==rnrTabIndex){$("a[data-toggle='tab']",$activeLi).tab("show");}}
return;}
this.addTabToBootstrapTabsControl($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIndex,hideTabsContent);},setTabWithinTabsControl:function($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIndex,hideTabsContent,tabAttrs){if(Runner.isBootstrap()){Runner.pages.PageManager.setTabWithinBootstrapTabsControl.call(this,$tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIndex,hideTabsContent);return;}
if(!$tabsControl.length||!$tabsControl.data('ui-tabs')){return;}
var $tab=$("#"+tabElementId,$tabsControl),activeIdx;if($tab.length){$tabsControl.find("li[data-rnrtabidx="+rnrTabIndex+"]").show();$tab.html('').append($tabContents);activeIdx=$tabsControl.data("activeIdx");if(activeIdx!==undefined){$tabsControl.tabs("option","active",activeIdx);}
return;}
this.addTabToTabsControl($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIndex,hideTabsContent);},addTabToBootstrapTabsControl:function($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,tabidx,hideTabsContent,tabHref){if(!$tabsControl.length){return;}
var dataAttr='data-tabidx="'+tabidx+'"',added=false,newTabIndex=0,$navigation=$tabsControl.children().first(),$newTab=$('<a data-target="#'+tabElementId+'" role="tab" data-toggle="tab">'+tabLabel+'</a>'),target;if(tabHref){$newTab.attr("href",tabHref);}
if(typeof tabidx==='number'){$('li',$navigation).each(function(idx,li){var $li=$(li),rnrCurrentTabIdx=$li.data('tabidx'),$corrTab;if(rnrCurrentTabIdx===undefined||rnrCurrentTabIdx>tabidx){$('<li role="presentation" '+dataAttr+'></li>').append($newTab).insertBefore($li);target=$li.find('a').data("target")||$li.find('a').attr('href');$corrTab=$(target,$tabsControl);$('<div role="tabpanel" class="tab-pane" id="'+tabElementId+'"/>').append($tabContents).insertBefore($corrTab);newTabIndex=idx;added=true;return false;}});}
if(!added){$('<li role="presentation" '+dataAttr+'></li>').append($newTab).appendTo($navigation);$('<div role="tabpanel" class="tab-pane" id="'+tabElementId+'"/>').append($tabContents).appendTo($(".tab-content",$tabsControl));}
if(activeTab||$('li',$navigation).length===1){$newTab.tab('show');}else{$newTab.tab();}
if(hideTabsContent){$tabContents.hide();}},addTabToTabsControl:function($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIdx,hideTabsContent,tabHref){if(Runner.isBootstrap()){this.addTabToBootstrapTabsControl($tabsControl,$tabContents,tabElementId,tabLabel,activeTab,rnrTabIdx,hideTabsContent,tabHref);return;}
if(!$tabsControl.length||!$tabsControl.data('ui-tabs')){return;}
var dataAttr='',added=false,newTabIndex=0,$navigation=$tabsControl.find('.ui-tabs-nav');if(typeof rnrTabIdx==='number'){dataAttr='data-rnrtabidx="'+rnrTabIdx+'"';$('li',$navigation).each(function(idx,li){var $li=$(li),rnrCurrentTabIdx=$li.data('rnrtabidx'),$corrTab;if(rnrCurrentTabIdx===undefined||rnrCurrentTabIdx>rnrTabIdx){$li.before('<li '+dataAttr+'><a href="#'+tabElementId+'">'+tabLabel+'</a></li>');$corrTab=$($li.find('a').attr('href'),$tabsControl);$('<div id="'+tabElementId+'"/>').append($tabContents).insertBefore($corrTab);newTabIndex=idx;added=true;return false;}});}
if(!added){newTabIndex=$('li',$navigation).length;$navigation.append('<li '+dataAttr+'><a href="#'+tabElementId+'">'+tabLabel+'</a></li>');$('<div id="'+tabElementId+'"/>').append($tabContents).appendTo($tabsControl);}
$tabsControl.tabs('refresh');if(activeTab){$tabsControl.tabs('option','active',newTabIndex);}else if($('li',$navigation).length===1){$tabsControl.tabs('option','active',0);}
if(hideTabsContent){$tabContents.hide();}},loadPageLayoutCss:function(tName,pageType){var tableBased=tName!==Runner.pages.constants.NOT_TABLE_BASED_TNAME&&pageType!==Runner.pages.constants.PAGE_REGISTER,layoutName;if(tableBased){layoutName=Runner.pages.PageSettings.getTableData(tName,"popupPagesLayoutNames")[pageType];}else{layoutName=Runner.pages.PageSettings.getGlobalData("popupPagesLayoutNames")[pageType];}
if(layoutName&&layoutName.indexOf('bootstrap')===false){Runner.util.ScriptLoader.loadCSS(settings.global["webRootPath"]+"pagestyles/"+layoutName+".css");}},createFlyWin:function(args,pageBased,afterCreateHandler,afterCloseHandler,beforeCloseHandler){if(!Runner.Y){return;}
var createHn,self=this,pageCont=document.createElement("DIV"),winAttrs={srcNode:pageCont,zIndex:Runner.genZIndexMax(),visible:false,resize:true,render:true,modal:!!Runner.tabletDevice,headerContent:"&nbsp;",bodyContent:"&nbsp;",footerContent:"&nbsp;"},winWrapper;if(pageBased){this.pageCont=pageCont;}
if(typeof this.addEvents==="function"){this.addEvents("windowSizeCorrected");}
winAttrs=Runner.apply(winAttrs,args);createHn=function(Y){var drag,resize,xy,win=new Y.Panel(winAttrs),widgetBox=win.get('boundingBox').getDOMNode(),$pageWrapper=$(win.bodyNode.getDOMNode());winWrapper=Runner.pages.PageManager.getYUIWinWrapper(win,beforeCloseHandler);if(pageBased){self.win=win;}
$pageWrapper.css("overflow","auto").on('scroll',function(e){$("#shiny_box").hide();$(".rnr-datepicker").hide();$(".search_suggest").css('visibility','hidden');if(typeof self.hideSearchControllerContainers==="function"){self.hideSearchControllerContainers();}});drag=new Y.DD.Drag({node:widgetBox,handles:['.'+win.headerNode.getAttribute("class")]}).plug(Y.Plugin.DDWinScroll).plug(Y.Plugin.DDConstrained,{constrain:{'top':0,'left':0}})
drag.on("drag:drag",function(){$('#shiny_box').hide();$(".rnr-datepicker").hide();$(".search_suggest").css('visibility','hidden');if(typeof self.hideSearchControllerContainers==="function"){self.hideSearchControllerContainers();}});if(winAttrs.resize){Y.Resize.prototype.HANDLE_TEMPLATE='<div class="'+Y.ClassNameManager.getClassName('resize','handle')+' '
+Y.ClassNameManager.getClassName('resize','handle','{handle}')+'">&nbsp;</div>';resize=new Y.Resize({node:widgetBox}).plug(Y.Plugin.ResizeConstrained,{minWidth:100,minHeight:100,preserveRatio:false});resize.on('resize:resize',function(){Runner.pages.PageManager.adjustedYUIWindowBodyHeight(win);$(".rnr-datepicker").hide();if(typeof self.hideSearchControllerContainers==="function"){self.hideSearchControllerContainers();}});}
win.removeButton('close','header');win.addButton({name:'close',isDefault:true,events:{click:function(e){if(beforeCloseHandler&&!beforeCloseHandler(winWrapper)){return false;}
win.destroy(true);}},});win.on('destroy',function(){$('#shiny_box').not("._hintBox").hide();if(typeof self.hideSearchControllerContainers==="function"){self.hideSearchControllerContainers();}
if(afterCloseHandler){afterCloseHandler(winWrapper);}});if(afterCreateHandler){afterCreateHandler(winWrapper);}
if(Runner.isDirRTL()){Y.DD.DDM._pg.setStyles({left:'auto',right:'0'});drag.con.get('constrain').left=$(window).width()-$(document).width();drag.on("drag:start",function(){Y.DD.DDM._pg.setStyles({left:'auto',right:'0'});});}};Runner.Y.use('panel','dd-constrain','dd-scroll','resize-constrain',pageBased?this.asyncInitCall(createHn):createHn);return winWrapper;},getYUIWinWrapper:function(yuiObj,beforeCloseHandler){return{_obj:yuiObj,close:function(){if(beforeCloseHandler&&!beforeCloseHandler(this)){return false;}
yuiObj.destroy(true);},destroy:function(){yuiObj.destroy(true);},setWidth:function(width){yuiObj.set('width',width);Runner.pages.PageManager.correctYUIWindowSize.call(this,yuiObj,true);},setHeight:function(height){yuiObj.set('height',height);Runner.pages.PageManager.correctYUIWindowSize.call(this,yuiObj,true);},setPos:function(x,y){yuiObj.set('x',x);yuiObj.set('y',y);},body:function(){return $(yuiObj.bodyNode.getDOMNode());},header:function(){return $(yuiObj.headerNode.getDOMNode());},footer:function(){return $(yuiObj.footerNode.getDOMNode());},getContextNode:function(){return this.body();},getContentNode:function(){return $(yuiObj.get('boundingBox').getDOMNode());}};},getBSModalMarkup:function(){return'<div class="bs-popup modal" tabindex="-1" role="dialog">'
+'<div class="modal-dialog">'
+'<div class="modal-content">'
+'<div class="modal-header"></div>'
+'<div class="modal-body"></div>'
+'<div class="modal-footer"></div>'
+'</div>'
+'</div>'
+'</div>';},createBSWin:function(args,pageBased,afterCreateHandler,afterCloseHandler,beforeCloseHandler){var $modal=$(Runner.pages.PageManager.getBSModalMarkup.call(this)),$header=$(".modal-header",$modal),$body=$(".modal-body",$modal),$footer=$(".modal-footer",$modal),pageObj=this,mobileMode=$(window).width()<768,modalWrapper={_obj:$modal,close:function(){$modal.modal("hide");},destroy:function(){$modal.modal("hide");},setWidth:function(width){$(".modal-dialog",$modal).width(width);$(".modal-content",$modal).width(width);$body.css("width",width);},setHeight:function(height){$(".modal-content",$modal).height(height);$body.css("height",height);},setPos:function(x,y){if(x){$(".modal-dialog",$modal).css("margin-left","0px");$(".modal-dialog",$modal).css("left",x+"px");}
if(y){$(".modal-dialog",$modal).css("margin-top","0px");$(".modal-dialog",$modal).css("top",y+"px");}},body:function(){return $body;},header:function(){return $header;},footer:function(){return $footer;},getContextNode:function(){return $modal;},getContentNode:function(){return $(".modal-content",$modal);}};if(pageBased){this.pageCont=$modal;this.bsWin=$modal;}
if(args.headerContent==""){args.headerContent="<h2></h2>";}
$header.html(args.headerContent).append($('<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'));$body.html(args.bodyContent);$footer.html(args.footerContent);if(!args.width){args.width=800;}
if(args.height&&!mobileMode){if(args.height>window.innerHeight-60){$(".modal-dialog",$modal).css('margin','0px auto');}
$(".modal-content",$modal).height(args.height-2);}
if(args.width&&!mobileMode){$modal.css('padding-left','0px');$modal.css('padding-right','0px');$(".modal-dialog",$modal).width(args.width);$(".modal-content",$modal).width(args.width);$body.css("width",args.width);}
if(args.x){$(".modal-dialog",$modal).css("margin-left","0px");$(".modal-dialog",$modal).css("left",args.x+"px");}
if(args.y){$(".modal-dialog",$modal).css("margin-top","0px");$(".modal-dialog",$modal).css("top",args.y+"px");}
$modal.on("shown.bs.modal",function(){$body.css("height",args.height-($footer.outerHeight()+$header.outerHeight()));if(afterCreateHandler){afterCreateHandler(modalWrapper);}
if(pageBased){pageObj.fireEvent("windowSizeCorrected");}});if(args.closeByButton){$modal.modal({backdrop:'static',keyboard:false});}
$modal.appendTo(document.body).modal("show");$modal.on("hide.bs.modal",function(e){if(beforeCloseHandler&&!beforeCloseHandler(modalWrapper)){e.preventDefault();e.stopImmediatePropagation();return false;}});$modal.on("hidden.bs.modal",function(){$modal.data("bs.modal",null);if(pageBased){$('#shiny_box').not("._hintBox").hide();if(typeof pageObj.hideSearchControllerContainers==="function"){pageObj.hideSearchControllerContainers();}}
if(afterCloseHandler){afterCloseHandler(modalWrapper);}
$modal.remove();$(".bs-popup").each(function(ind,el){var omData=$(el).data("bs.modal");if(!omData){return;}
omData.checkScrollbar();omData.setScrollbar();omData.$body.addClass('modal-open');});});$(".modal-dialog",$modal).draggable({handle:".modal-header"});$(".modal-content",$modal).css("overflow","hidden").resizable({minWidth:200,minHeight:150,resize:function(event,ui){$header.css("width",ui.element.innerWidth()+"px");$footer.css("width",ui.element.innerWidth()+"px");$body.css("width",ui.element.innerWidth()+"px");$body.css("height",(ui.element.innerHeight()-$header.outerHeight()-$footer.outerHeight())+"px");$modal.toggleClass("bs-smallpopup",ui.element.innerWidth()<Runner.pages.constants.SMALL_MODAL_WIDTH);},handles:"n, e, s, w, ne, nw, se, sw"});if(Runner.isDirRTL()){var rchange=$(".modal-content",$modal).data("uiResizable")._change;rchange.e=function(event,dx){var cs=this.originalSize,sp=this.originalPosition;return{left:sp.left+dx,width:cs.width+dx};};rchange.w=function(event,dx){return{width:this.originalSize.width-dx};};}
return modalWrapper;},correctBSWindowSize:function(bsWin,pageObj){if(pageObj&&pageObj.popupSizeIsCorrected){return;}
if(pageObj&&pageObj.controlsMap&&pageObj.controlsMap.multistep){pageObj.adjustHeightAndWidth();return;}
var winDim=Runner.getWindowDimensions(),halfWinWidth,halfWinHeight,$modalContentBox=$(".modal-content",bsWin),$modalBody=$(".modal-body",bsWin),mWidth,mHeight,mWidthDelta;if(winDim.width<768){if($modalContentBox.height()<winDim.height){$modalBody.height($modalBody.height()-$modalContentBox.height()+winDim.height-2);$modalContentBox.height(winDim.height-2);}
bsWin.css("paddingLeft","");if($modalContentBox.width()<winDim.width){$modalBody.width(winDim.width-2-$modalBody.innerWidth()+$modalBody.width());$modalContentBox.width(winDim.width-2);}
return;}
halfWinWidth=Math.floor(3*winDim.width/4);halfWinHeight=Math.floor(4*winDim.height/5);mWidth=$modalContentBox.width();mWidthDelta=mWidth-$modalBody.width();mHeight=$modalContentBox.height();if(halfWinWidth>100&&mWidth>halfWinWidth){$modalContentBox.width(halfWinWidth);$modalBody.width(halfWinWidth-mWidthDelta);}
if(halfWinHeight>100&&mHeight>halfWinHeight){$modalBody.height($modalBody.height()-mHeight+halfWinHeight);$modalContentBox.height(halfWinHeight);}
$modalContentBox.parent().width($modalContentBox.width());bsWin.toggleClass("bs-smallpopup",$modalContentBox.width()<Runner.pages.constants.SMALL_MODAL_WIDTH);},adjustedYUIWindowBodyHeight:function(win){var $bodyNode=$(win.bodyNode.getDOMNode()),$contentBox=$(win.get("contentBox").getDOMNode()),headerHeight=$(win.headerNode.getDOMNode()).outerHeight(),footerHeight=$(win.footerNode.getDOMNode()).outerHeight(),extraHeight=$bodyNode.outerHeight(true)-$bodyNode.height();$bodyNode.height($contentBox.height()-headerHeight-footerHeight-extraHeight);},correctYUIWindowSize:function(win,centered,pageObj){var scrollY=$(window).scrollTop(),scrollX=$(window).scrollLeft(),winDim=Runner.getWindowDimensions(),halfWinWidth=Math.floor(3*winDim.width/4),halfWinHeight=Math.floor(4*winDim.height/5),newWidth,fullWidth,newHeight,bodyNode,widgetBox,fullHeight;if(pageObj&&pageObj.popupSizeIsCorrected){pageObj.fireEvent("windowSizeCorrected");return;}
if(pageObj&&pageObj.controlsMap&&pageObj.controlsMap.multistep){win.show();pageObj.adjustHeightAndWidth();pageObj.fireEvent("windowSizeCorrected");return;}
bodyNode=win.bodyNode.getDOMNode();widgetBox=win.get("boundingBox").getDOMNode();if(!widgetBox){return;}
newWidth=win.get('width')||widgetBox.offsetWidth;fullWidth=widgetBox.offsetLeft+(!centered&&Runner.isDirRTL()?-newWidth:newWidth);if(fullWidth>winDim.width+scrollX){newWidth=newWidth-(fullWidth-winDim.width)+scrollX-30;}
newWidth=newWidth+18;if(newWidth<100){newWidth=118;}else if(newWidth>halfWinWidth){newWidth=halfWinWidth;}
win.set("width",newWidth);if(centered){win.set("x",Math.floor((winDim.width-newWidth)/2)+scrollX);}
newHeight=win.get('height')||widgetBox.offsetHeight;fullHeight=widgetBox.offsetTop+newHeight;if(fullHeight>winDim.height+scrollY){newHeight=newHeight-(fullHeight-winDim.height)+scrollY-30;}
if(newHeight<100){newHeight=100;}else if(newHeight>halfWinHeight){newHeight=halfWinHeight;}
win.set("height",newHeight);if(centered){win.set("y",Math.floor((winDim.height-newHeight)/2)+scrollY);}
Runner.pages.PageManager.adjustedYUIWindowBodyHeight(win);win.show();if(pageObj){pageObj.fireEvent("windowSizeCorrected");}},createFullScreenWin:function(pageCont,winContent,brickToSet,afterCreateHandler,afterCloseHandler){var allPageBricks=Runner.bricks.Brick.prototype.getBrickObjs('',pageCont,true),$popupWin;for(var i=allPageBricks.length;i--;){if(allPageBricks[i].visible()){this.hideBrick(allPageBricks[i].name);}}
if(brickToSet){this.showBrick(brickToSet);this.replaceBrickContentHTMLWith(brickToSet,winContent);return;}
$popupWin=$('<div></div>').addClass("fullScreenContainer").html(winContent).appendTo('body');},addUnloadHn:function(hn,scope,args){if(typeof hn!=='function'){return;}
beforeUnloadPool.push({hn:hn,scope:scope||window,args:args||[]});},callUnload:function(){var i,handlerData,tName;for(i=0;i<beforeUnloadPool.length;i++){handlerData=beforeUnloadPool[i];handlerData.hn.apply(handlerData.scope,handlerData.args);}
for(tName in tables){this.unregister(tName);}}}}();Runner.namespace('Runner.pages');(function(){if(!window.settings||!window.settings.global||typeof window.settings.global!=='object'){return;}
Runner.debugMode=window.settings.global.debugMode;Runner.isMobile=window.settings.global.isMobile;Runner.mobileDeviceDetected=window.settings.global.mobileDeteced;Runner.setIdCounter(window.settings.global.idStartFrom);Runner.charSet=window.settings.global.charSet;Runner.isAD=window.settings.global.isAD;})();Runner.pages.PageControlsMap=function(){window.controlsMap=window.controlsMap||{};return{addMap:function(tName,pageType,pageId,map){if(!tName||!pageType||typeof pageId=='undefined'){return false;}
if(!controlsMap[tName]){controlsMap[tName]={};}
if(!controlsMap[tName][pageType]){controlsMap[tName][pageType]={};}
if(map){controlsMap[tName][pageType][pageId]=map[tName][pageType][pageId];}},getMap:function(tName,pageType,pageId){if(!tName){return controlsMap;}
if(!pageType){return controlsMap[tName];}
if(typeof pageId=='undefined'){return controlsMap[tName][pageType];}
return controlsMap[tName][pageType][pageId];},removeMap:function(tName,pageType,pageId){if(!tName||!pageType||typeof pageId=="undefined"){return false;}
if(!controlsMap[tName]){return false;}
if(!controlsMap[tName][pageType]){return false;}
delete controlsMap[tName][pageType][pageId];return true;}};}();Runner.pages.PageViewControlsMap=function(){window.viewControlsMap=window.viewControlsMap||{};return{addMap:function(tName,pageType,pageId,map){if(!tName||!pageType||typeof pageId=='undefined'){return false;}
if(!viewControlsMap[tName]){viewControlsMap[tName]={};}
if(!viewControlsMap[tName][pageType]){viewControlsMap[tName][pageType]={};}
if(map){viewControlsMap[tName][pageType][pageId]=map[tName][pageType][pageId];}},getMap:function(tName,pageType,pageId){if(!tName){return viewControlsMap;}
if(!pageType){return viewControlsMap[tName];}
if(typeof pageId=='undefined'){return viewControlsMap[tName][pageType];}
return viewControlsMap[tName][pageType][pageId];},removeMap:function(tName,pageType,pageId){if(!tName||!pageType||typeof pageId=="undefined"){return false;}
if(!viewControlsMap[tName]){return false;}
if(!viewControlsMap[tName][pageType]){return false;}
delete viewControlsMap[tName][pageType][pageId];return true;}};}();Runner.pages.PageSettings=Runner.extend(Runner.emptyFn,{getSettings:function(tName,fName,pageType){if(!tName){return settings;}
if(!fName){return settings.tableSettings[tName];}
return settings.tableSettings[tName]["fieldSettings"][fName][pageType];},checkSettings:function(tName,fName,pageType){return!!this.getSettings(tName,fName,pageType);},fieldSettingsExist:function(tName,fName,key,pageType){if(typeof settings.tableSettings[tName]!=='undefined'&&typeof settings.tableSettings[tName]["fieldSettings"][fName]!=='undefined'&&typeof settings.tableSettings[tName]["fieldSettings"][fName][pageType]!=='undefined'&&typeof settings.tableSettings[tName]["fieldSettings"][fName][pageType][key]!=='undefined'){return true;}
return false;},addPageEvent:function(tName,pType,evName,evHn){if(!settings.tableSettings[tName]){settings.tableSettings[tName]={};}
if(!settings.tableSettings[tName]["events"]){settings.tableSettings[tName]["events"]={};}
if(!settings.tableSettings[tName]["events"][pType]){settings.tableSettings[tName]["events"][pType]={};}
if(!settings.tableSettings[tName]["events"][pType][evName]){settings.tableSettings[tName]["events"][pType][evName]=[];}
settings.tableSettings[tName]["events"][pType][evName].push({hn:evHn});},addSettings:function(tName,addSettings,forceRewrite){if(!addSettings){return;}
var settings=this.getSettings();Runner.apply(settings.global.shortTNames,addSettings.global.shortTNames);if(forceRewrite===true){settings.tableSettings[tName]=addSettings.tableSettings[tName];return;}
if(!tName){Runner.deepCopy(settings.tableSettings,addSettings.tableSettings);}else{settings.tableSettings[tName]=settings.tableSettings[tName]||{};Runner.deepCopy(settings.tableSettings[tName],addSettings.tableSettings[tName]);}},getViewType:function(tName,fName,pageType){return this.getFieldData(tName,fName,"viewFormat",pageType);},getEditFormat:function(tName,fName,pageType){return this.getFieldData(tName,fName,"editFormat",pageType);},getShortTName:function(tName){if(!tName){return"";}
return settings.global.shortTNames[tName]||settings.tableSettings[tName].shortTName||"";},getValidations:function(tName,fName,pageType){if(this.fieldSettingsExist(tName,fName,"validation",pageType)){return this.getFieldData(tName,fName,"validation",pageType);}
return Runner.pages.Defaults.getValidationSettings();},getLookupTable:function(tName,fName,pageType){return this.getFieldData(tName,fName,"lookupTable",pageType);},getLookupSize:function(tName,fName,pageType){return this.getFieldData(tName,fName,"selectSize",pageType);},getLCT:function(tName,fName,pageType){return this.getFieldData(tName,fName,"lcType",pageType);},getShowListOfThumbnailsStatus:function(tName,fName,pageType){return this.getFieldData(tName,fName,"showListOfThumbnails",pageType);},getImageWidth:function(tName,fName,pageType){var nReturn=this.getFieldData(tName,fName,"imageWidth",pageType);return nReturn||null;},getImageHeight:function(tName,fName,pageType){var nReturn=this.getFieldData(tName,fName,"imageHeight",pageType);return nReturn||null;},getTableEventsData:function(tName,pageType){var events=this.getTableData(tName,"events");return events[pageType]||{};},getTableData:function(tName,key){if(typeof settings.tableSettings[tName]!='undefined'&&typeof settings.tableSettings[tName][key]!='undefined'){return this.returnData(settings.tableSettings[tName][key]);}
return this.returnData(Runner.pages.Defaults.getTableSettings(key));},getFieldData:function(tName,fName,key,pageType){if(this.fieldSettingsExist(tName,fName,key,pageType)){return this.returnData(settings.tableSettings[tName]["fieldSettings"][fName][pageType][key]);}
return this.returnData(Runner.pages.Defaults.getFieldSettings(key));},getGlobalData:function(key){if(settings.global[key]!=undefined){return this.returnData(settings.global[key]);}
return this.returnData(Runner.pages.Defaults.getGlobalSettings(key));},returnData:function(data){if(Runner.isArray(data)){return data.slice(0);}
if(data&&typeof data==="object"){var F=function(){};F.prototype=data;return new F();}
return data;}});Runner.pages.PageSettings=new Runner.pages.PageSettings();Runner.pages.ajaxEvents={};Runner.pages.fieldsEvents={};Runner.pages.PageFactory=function(baseCfg){var cfg=Runner.apply({},baseCfg);switch(cfg.pageType){case Runner.pages.constants.PAGE_LIST:if(cfg.pageMode===Runner.pages.constants.RIGHTS_PAGE){if(Runner.isAD){return new Runner.pages.RightsPageAD(cfg);}
return new Runner.pages.RightsPage(cfg);}
if(cfg.pageMode===Runner.pages.constants.MEMBERS_PAGE){return Runner.isAD?new Runner.pages.MembersPageAD(cfg):new Runner.pages.MembersPage(cfg);}
if(cfg.pageMode===Runner.pages.constants.LIST_DASHBOARD||cfg.pageMode===Runner.pages.constants.LIST_DASHDETAILS){return new Runner.pages.ListPageDash(cfg);}
if(cfg.pageMode===Runner.pages.constants.MODE_LIST_DETAILS){if(Runner.isMobile){return new Runner.pages.ListPageMobileDP(cfg);}
return new Runner.pages.ListPageDP(cfg);}
if(Runner.isMobile){if(cfg.openMode===Runner.pages.constants.OPENMODE_POPUP){return new Runner.pages.ListPageFly(cfg);}
return new Runner.pages.ListPageMobile(cfg);}
if(cfg.openMode===Runner.pages.constants.OPENMODE_POPUP){return new Runner.pages.ListPageFly(cfg);}
if(cfg.pageMode===Runner.pages.constants.LIST_AJAX){return new Runner.pages.ListPageAjax(cfg);}
return new Runner.pages.ListPage(cfg);case Runner.pages.constants.PAGE_ADD:if(cfg.editType===Runner.pages.constants.ADD_ONTHEFLY){return new Runner.pages.AddPageFly(cfg);}
if(cfg.pageMode===Runner.pages.constants.EDIT_DASHBOARD){return new Runner.pages.AddPageDash(cfg);}
return new Runner.pages.AddPage(cfg);case Runner.pages.constants.PAGE_EDIT:if(cfg.pageMode===Runner.pages.constants.EDIT_DASHBOARD){return new Runner.pages.EditPageDash(cfg);}
if(cfg.pageMode==Runner.pages.constants.EDIT_SELECTED_SIMPLE||cfg.pageMode==Runner.pages.constants.EDIT_SELECTED_POPUP){return new Runner.pages.EditSelectedPage(cfg);}
return new Runner.pages.EditPage(cfg);case Runner.pages.constants.PAGE_LOGIN:return new Runner.pages.LoginPage(cfg);case Runner.pages.constants.PAGE_REMIND:return new Runner.pages.RemindPage(cfg);case Runner.pages.constants.PAGE_VIEW:return new Runner.pages.ViewPage(cfg);case Runner.pages.constants.PAGE_SEARCH:return new Runner.pages.SearchPage(cfg);case Runner.pages.constants.PAGE_REPORT:if(cfg.pageMode===Runner.pages.constants.MODE_LIST_DETAILS){if(Runner.isMobile){return new Runner.pages.ReportPageMobileDP(cfg);}else{return new Runner.pages.ReportPageDP(cfg);}}
if(Runner.isMobile){return new Runner.pages.ReportPageMobile(cfg);}
return new Runner.pages.ReportPage(cfg);case Runner.pages.constants.PAGE_CHART:if(cfg.pageMode===Runner.pages.constants.MODE_LIST_DETAILS){if(Runner.isMobile){return new Runner.pages.ChartPageMobileDP(cfg);}else{return new Runner.pages.ChartPageDP(cfg);}}
if(Runner.isMobile){return new Runner.pages.ChartPageMobile(cfg);}
if(cfg.openMode===Runner.pages.constants.OPENMODE_DASHCONTAINER){return new Runner.pages.ChartPageDash(cfg);}
if(cfg.openMode===Runner.pages.constants.OPENMODE_DASHTABS){return new Runner.pages.ChartPageDPDash(cfg);}
return new Runner.pages.ChartPage(cfg);case Runner.pages.constants.PAGE_REGISTER:return new Runner.pages.RegisterPage(cfg);case Runner.pages.constants.PAGE_CHANGEPASS:return new Runner.pages.ChangePwdPage(cfg);case Runner.pages.constants.PAGE_EXPORT:return new Runner.pages.ExportPage(cfg);case Runner.pages.constants.PAGE_IMPORT:return new Runner.pages.ImportPage(cfg);case Runner.pages.constants.PAGE_PRINT:return new Runner.pages.PrintPage(cfg);case Runner.pages.constants.PAGE_REPORT_PRINT:return new Runner.pages.ReportPrintPage(cfg);case Runner.pages.constants.PAGE_DASHBOARD:if(Runner.isMobile){return new Runner.pages.DashboardPageMobile(cfg);}
return new Runner.pages.DashboardPage(cfg);case Runner.pages.constants.PAGE_DASHMAP:if(cfg.pageMode===Runner.pages.constants.GRIDBASED_MAP_DASHBOARD){return new Runner.pages.DashboardGridBasedMap(cfg);}
return new Runner.pages.DashboardLeadingMap(cfg);default:cfg.createAsDefault=true;return new Runner.pages.RunnerPage(cfg);}};Runner.pages.getUrl=function(tName,pageType,keys,keyPref){var tableBased=tName!==Runner.pages.constants.NOT_TABLE_BASED_TNAME&&pageType!==Runner.pages.constants.PAGE_REGISTER,url=tableBased?Runner.getPageUrl(Runner.pages.PageSettings.getShortTName(tName),pageType):Runner.getPageUrl(pageType),keyParams=[],i;keys=keys||[];if(!keys.length){return url}
keyPref=keyPref||"editid";for(i=0;i<keys.length;i++){keyParams.push(keyPref+(i+1)+"="+encodeURIComponent(keys[i]))}
return url+"?"+keyParams.join("&")};Runner.pages.RunnerPage=Runner.extend(Runner.util.Observable,{tName:'',pageType:'',modal:false,pageId:-1,controlsMap:null,viewControlsMap:null,headerCont:"",bodyCont:"",footerCont:"",win:null,popupSizeIsCorrected:false,pageCont:null,bricksForReload:[],proxy:null,createAsDefault:false,useAsGlobal:false,shortTName:"",useLocking:false,useAudio:false,useResize:false,bricksForMobileFly:[],buttonNames:[],buttonEventBefore:{},buttonEventAfter:{},validateTimer:null,pageModified:false,oldLayout:false,layoutVersion:2,layoutName:"",tabsPresented:false,useSearchSuggests:false,warnOnLeaving:false,initTaskQueue:null,currentInitTaskIndex:-1,initSubtasksCreated:0,initSubtasksFinished:0,openMode:null,message:"",currentStep:0,reloadTimerId:null,chartObj:null,silentReloading:false,masterTable:"",masterKeys:[],pageData:{},$gridTabControl:null,constructor:function(cfg){Runner.apply(this,cfg);Runner.pages.PageManager.register(this);this.addEvents('beforeInit','afterInit','afterClose');this.id=this.pageId;this.pageData=Runner.getPageData(this.id);this.proxy=this.pageData.proxy;this.useAudio=Runner.pages.PageSettings.getTableData(this.tName,"isUseAudio");this.useResize=Runner.pages.PageSettings.getTableData(this.tName,"isUseResize");this.useLocking=Runner.pages.PageSettings.getTableData(this.tName,"locking");this.warnOnLeaving=Runner.pages.PageSettings.getTableData(this.tName,"warnOnLeaving");this.shortTName=Runner.pages.PageSettings.getShortTName(this.tName);this.masterTable=Runner.pages.PageSettings.getTableData(this.tName,"masterTable");this.masterKeys=Runner.pages.PageSettings.getTableData(this.tName,"masterKeys");this.oldLayout=this.controlsMap&&this.controlsMap.oldLayout;this.layoutVersion=this.controlsMap&&this.controlsMap.layoutVersion;this.layoutName=this.controlsMap?this.controlsMap.layoutName:"";this.tabsPresented=this.isUseTabs();this.pageCont=document.body;if(this.afterInit){this.on({'afterInit':this.afterInit});}
this.initTaskQueue=[];this.addInitTask(this.init);this.initYUI();},isBootstrap:function(){return this.layoutVersion==3;},initYUI:function(){if(Runner.isBootstrap()){return;}
if(typeof Runner.Y=='undefined'){var YUIparams={base:settings.global['webRootPath']+'include/yui/'};if(Runner.debugMode){YUIparams.filter='raw';}else{YUIparams.comboBase=Runner.getPageUrl('combo')+'?';YUIparams.combine=true;}
Runner.Y=YUI(YUIparams);}
this.Y=Runner.Y;$('body').addClass('yui3-skin-sam');$(document).unbind('keydown').bind('keydown',function(e){if(e.which==27){$('.yui3-button-close').click();return false;}});},destructor:function(){this.destroyWin();if(!this.win&&Runner.isMobile&&this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.destructorMobile();}
this.purgeListeners();Runner.controls.ControlStorage.unregisterById(this.pageId);if(this.reloadTimerId){clearTimeout(this.reloadTimerId);}
if(this.chartObj&&this.chartObj.reloadIntervalId){clearInterval(this.chartObj.reloadIntervalId);}},destructorMobile:function(){this.replaceBrickHTMLWith('flypanel_mobile','');for(var i=0;i<this.bricksForMobileFly.length;i++){if(this.bricksForMobileFly[i].name!=='message'){this.showBrick(this.bricksForMobileFly[i].name);}}
this.hideBrick('flypanel_mobile');},addInitTask:function(task){if(Runner.isArray(task)){this.initTaskQueue=this.initTaskQueue.concat(task);}else{this.initTaskQueue.push(task);}},prependInitTask:function(task){if(Runner.isArray(task)){this.initTaskQueue=task.concat(this.initTaskQueue);}else{this.initTaskQueue.splice(0,0,task);}},asyncInitCall:function(func){var pageObj=this;++this.initSubtasksCreated;return function(){if(typeof func==="function"){func.apply(pageObj,arguments);}
++pageObj.initSubtasksFinished;if(pageObj.initSubtasksFinished==pageObj.initSubtasksCreated){pageObj.goInitQueue();}}},goInitQueue:function(){while(++this.currentInitTaskIndex<this.initTaskQueue.length){this.initSubtasksFinished=0;this.initSubtasksCreated=1;this.initTaskQueue[this.currentInitTaskIndex].call(this);++this.initSubtasksFinished;if(this.initSubtasksFinished!==this.initSubtasksCreated){return;}}},init:function(){var pageObj=this;this.fireEvent('beforeInit',this);if(Runner.isMobile&&this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.initFlyMobile()}
this.initMenu();this.initEvents();this.initRunnerButtons();this.initLoginButtons();this.hideFieldsHiddenByUser();this.initLanguageSelector();this.initCollapseButtons();this.initTabsSections();this.initForTabs();if(this.controlsMap&&typeof this.controlsMap.reCaptcha!=="undefined"){this.initReCaptcha();}
if(this.controlsMap&&typeof this.controlsMap.printPdf!=="undefined"){this.initPrintPdf();}
this.initSearch();if(!this.useResize){this.initForGrid();}
if(this.openMode===Runner.pages.constants.OPENMODE_PRELOADED){$("#fixedheader"+this.id,this.pageCont).each(function(){var $header=$(this);ResizeSensor(this,function(){var position=$header.css('position'),height=0,oldUnderheaderMargin=0,newUnderheaderMargin=0,oldSidebarHeight,newSidebarHeight;if(position=='absolute'||position=='fixed'){height=$header.height();}
oldUnderheaderMargin=parseFloat(($('#underheader'+pageObj.id).css('margin-top')||'0').replace('px',''));oldSidebarHeight=parseFloat(($('#sidebar'+pageObj.id).css('top')||'0').replace('px',''));newUnderheaderMargin=height+15;newSidebarHeight=height+1;if(newSidebarHeight!=oldSidebarHeight||newUnderheaderMargin!=oldUnderheaderMargin){$('#underheader'+pageObj.id).css('margin-top',newUnderheaderMargin+'px');$('#sidebar'+pageObj.id).css('top',newSidebarHeight+'px');if(pageObj.adjustBSGridHeight){pageObj.adjustBSGridHeight();}}});});}
if(this.warnOnLeaving&&!Runner.isMobile&&this.openMode!==Runner.pages.constants.OPENMODE_POPUP){$(window).on('beforeunload',function(){return pageObj.beforeUnloadHn();});}
this.replaceGridTabs();this.initGridTabs();},isPageInTab:function(){return this.openMode===Runner.pages.constants.OPENMODE_DASHTABS||this.openMode===Runner.pages.constants.OPENMODE_TABVIEW;},hideFieldsHiddenByUser:function(){var pageObj=this;$('.'+this.makeClassName('hiddenfield')).each(function(idx,elem){if(pageObj.oldLayout){pageObj.toggleParentRow(elem);}
var fieldName=$(elem).data('fieldname'),ctrl=Runner.getControl(pageObj.pageId,fieldName);if(ctrl){ctrl.hiddenByField=true;}});},toggleParentRow:function(element){if(!this.oldLayout){return;}
$(element).parents().each(function(){var $row=$(this);if($row.hasClass('runner-toprow')||$row.hasClass('runner-bottomrow')){return false;}
if($row.hasClass('runner-row')){$row.addClass('runner-hiddenfield');return false;}});},initLanguageSelector:function(){var pageType=this.pageType,$languageLink=$(".rnr-langlink",this.pageCont),$langSelector=$("#languageSelector",this.pageCont),prefix=$langSelector.data("prefix"),extraparams=$langSelector.data("params")||"",pageUrl;if(prefix==="dchart"||prefix==="dreport"){pageType=prefix;}
pageUrl=Runner.pages.getUrl(this.tName,pageType);$languageLink.on("click",function(e){window.location.href=pageUrl+"?"+"language="+$(this).data("lang");return false;});$langSelector.on("change",function(e){window.location.href=pageUrl+"?"+extraparams+"language="+this.options[this.selectedIndex].value;});},initForTabs:function(){this.initControls();this.initViewControls();this.initLookups();this.initChangeCtrlEvents();},initForGrid:function(){if(this.createAsDefault){this.fireEvent('afterInit',this,this.proxy,this.id);}},initReCaptcha:function(){if(!Runner.globalReCaptchaLoader){return;}
Runner.globalReCaptchaLoader.onLoad(function(){this.reCaptcha=new Runner.controls.ReCaptcha(this.controlsMap.reCaptcha);this.reCaptcha.init();},this);},initPrintPdf:function(){this.printPdf=new Runner.controls.PrintPdf(this.controlsMap.printPdf);this.printPdf.init();},initPrintFriendly:function(){var pageObj=this,$toggler=$("[id=print_friendly_togger"+this.id+"]"),$panelBlock=$("#printpanelblock"+pageObj.id);$toggler.unbind("click").bind("click",function(e){$toggler.attr("data-icon",$toggler.attr("data-icon")=="printdown"?"printup":"printdown");$panelBlock.toggleClass('open');});$("#printpanelblock"+this.id+" > .dropdown-menu").unbind("click").bind("click",function(e){e.stopPropagation();});$("#print_friendly_button"+this.id).on("click").on("click",function(e){$toggler.attr("data-icon",$toggler.attr("data-icon")=="printdown"?"printup":"printdown");$panelBlock.toggleClass('open');pageObj.printerFriendlyBtnHandler();return false;});$("#printDetailsToggler"+this.id).unbind("click").bind("click",function(e){$("#printdetailstables"+pageObj.id).toggle();});},printerFriendlyBtnHandler:function(){var $scope=$("#print_friendly_scope"+this.id+" input[type='radio'][name='printScope']:checked"),scopeId=$scope.attr("id"),$selBoxes,form,$detailsBox=$('#printDetailsToggler'+this.id),$records=$('#printPerPage'+this.id),$detailsTablesBoxes=$("input[type=checkbox]","#printdetailstables"+this.id),details=[],requestParams;requestParams={standardSubmit:true,submitUrl:Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_PRINT),target:'_blank',method:'POST',id:this.id,baseParams:{a:"print",records:$records.val()}};if($detailsBox.is(':checked')){$detailsTablesBoxes.each(function(n,box){if(box.checked){details.push(box.value);}});requestParams.baseParams["details[]"]=details;}
if(scopeId=="printSelection"+this.id){$selBoxes=this.getSelBoxes(this.id);if($selBoxes.length){requestParams.addElems=this.cloneFormElements($selBoxes);}}
if(scopeId=="printAll"+this.id){requestParams.baseParams.all=1;}
form=new Runner.form.BasicForm(requestParams);form.submit();form.destructor();},getSettings:function(tName,fName){return Runner.pages.PageSettings.getSettings(tName,fName,this.pageType);},checkSettings:function(tName,fName){return Runner.pages.PageSettings.checkSettings(tName,fName,this.pageType);},resetButtonGroupDisplayStyle:function($buttonGroup){setTimeout(function(){$buttonGroup.css('display','');},500);},initRunnerButtons:function(){$("."+this.makeClassName('button')).each(function(){if($(this).attr('type')==='disabled'){Runner.addDisabledClass(this);}});$("."+this.makeClassName('button-img')).each(function(){if($(this).attr('type')==='disabled'){Runner.addDisabledClass(this);}});},initLoginButtons:function(){var $loginButton,pageObj=this,loginFormType=Runner.pages.PageSettings.getGlobalData("loginFormType");$loginButton=$("[id=loginButton"+this.id+"]").on("click",function(e){if(loginFormType===Runner.pages.constants.LOGIN_POPUP){pageObj.openLoginPage();}else if(loginFormType===Runner.pages.constants.LOGIN_EMBEDED){pageObj.submitLoginForm();}else if(loginFormType===Runner.pages.constants.LOGIN_SEPARATE){window.location.href=Runner.pages.getUrl(Runner.pages.constants.NOT_TABLE_BASED_TNAME,"login")+"?return=true";}
return false;});$('input[name="password"]',"#login_block"+this.id).on("keydown",function(e){if(e.keyCode==13){$loginButton.trigger("click");return false;}});$("[id=logoutButton"+this.id+"]").on("click",function(e){window.location.href=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?a=logout";return false;});if(pageObj.isBootstrap()&&$("ul.dropdown-menu > li","#login_block"+this.id).length<1){$("[data-toggle=dropdown]","#login_block"+this.id).removeAttr("data-toggle");}
$("[id=loginButtonContinue"+this.id+"]").on("click",function(e){pageObj.openLoginPage('','',false,true);return false;});},submitLoginForm:function(){var pageObj=this,pageParams,$loginBlock=$("#login_block"+this.id),ajaxParams={a:"Login",mode:"embeded",id:Runner.genId(),password:$('input[name="password"]',$loginBlock).val(),username:$('input[name="username"]',$loginBlock).val(),remember_password:$('input[name="remember_password"]',$loginBlock).val()};if(Runner.pages.PageSettings.getGlobalData("twoFactorAuth")){pageParams={pageType:Runner.pages.constants.PAGE_LOGIN,tName:Runner.pages.constants.NOT_TABLE_BASED_TNAME,pageId:-1,modal:true,userval:ajaxParams.username,passval:ajaxParams.password,parId:this.id,hostPageObj:this,baseParams:{a:"Login",mode:"embeded",password:$('input[name="password"]',$loginBlock).val(),username:$('input[name="username"]',$loginBlock).val()},afterCreateHn:function(){var redirectUrl=this.pageData.twoStepEmbedRedirect;if(this.twoFactorAuth&&redirectUrl){this.close();window.location.href=redirectUrl;return;}}};Runner.pages.PageManager.openPage(pageParams);return;}
Runner.runnerAJAX(Runner.getPageUrl("login"),ajaxParams,function(respObj){if(respObj.redirect){window.location.href=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?a=login";}
if(respObj.message){if(respObj.messageParam){window.location.href=Runner.getPageUrl("login")+"?message="+respObj.messageParam;return;}
window.location.href=Runner.getPageUrl("login")+"?message=invalidlogin";}});},initLoginLink:function(){var $loginLink=$("[id=loginButtonContinue"+this.id+"]",this.pageCont),pageObj=this;if(!$loginLink.length){$loginLink=$("#loginButtonContinue",this.pageCont);}
$loginLink.on("click",function(e){pageObj.openLoginPage('','',false,true);return false;});},openLoginPage:function(user,pass,afterCreateHn,notRedirect,hostPage){var pageParams={pageType:Runner.pages.constants.PAGE_LOGIN,tName:Runner.pages.constants.NOT_TABLE_BASED_TNAME,pageId:-1,modal:true,userval:user,passval:pass,hostPageObj:hostPage||this,baseParams:{parId:this.id,notRedirect:notRedirect,mode:"popup"}};if(typeof afterCreateHn==="function"){pageParams.afterCreateHn=afterCreateHn;}
Runner.pages.PageManager.openPage(pageParams);},initToolTips:function(toolTips,tName){var div,ctrls,i;tName=tName||this.tName;if(!Runner.pages.PageSettings.getTableData(this.tName,"isUseToolTips")){return;}
if(!$('#shiny_box').length){div=$('<div id="shiny_box"></div>').css('display','none').addClass('shiny_box _hintBox').appendTo(document.body);$('<div></div>').addClass('shiny_box_body '+this.makeClassName('panel')+' '+this.makeClassName('list')).appendTo(div);}
toolTips=toolTips||this.controlsMap&&this.controlsMap.toolTips||[];ctrls=Runner.controls.ControlStorage.byId(this.id);for(i=0;i<ctrls.length;i++){if(ctrls[i]&&typeof toolTips[ctrls[i].fieldName]==='string'){ctrls[i].initToolTip(toolTips[ctrls[i].fieldName],this);}}},initMenu:function(){if(this.isBootstrap()){$('.menu-treelike:not([data-initialized])',this.pageCont).on('click','[data-toggle="collapse"]',function(){var $triangle=$('.menu-triangle',this),right=$triangle.hasClass('glyphicon-triangle-right');$triangle.toggleClass('glyphicon-triangle-right',!right).toggleClass('glyphicon-triangle-bottom',right);}).find('[data-toggle="collapse"]').each(function(){var $triangle=$('.menu-triangle',this),$target=$($(this).data('target')),right=$target.hasClass('in');$triangle.toggleClass('glyphicon-triangle-right',!right).toggleClass('glyphicon-triangle-bottom',right);$(this).attr('aria-expanded',right?'true':'false');}).attr('data-initialized','true');return;}
if($(".runner-hmenu").length&&!$(".runner-hmenu:first").prop("initialized")){Runner.menu.Horizontal.prototype.init();}
if($(".runner-vmenu.simple").length&&!$(".runner-vmenu.simple:first").prop("initialized")){Runner.menu.SimpleVmenu.prototype.init();}
if($(".runner-vmenu.tree").length&&!$(".runner-vmenu.tree:first").prop("initialized")){Runner.menu.TreeLikeVmenu.prototype.init();}
if($(".runner-quickjump").length&&!$(".runner-quickjump:first").prop("initialized")){Runner.menu.QuickJump.prototype.init();}
$('div:first-child.rnr-b-hmenu:not(.initialized)').each(function(index,elem){var $firstChild=$(elem),$menuContainer=$firstChild.parent(),horizontalMenu=new Runner.menu.HorizontalNew();horizontalMenu.init($menuContainer);$firstChild.addClass('initialized');});$(".rnr-b-vmenu.simple:not(.initialized)").each(function(index,elem){var $menuElem=$(elem),simpleVertivalMenu=new Runner.menu.SimpleVmenuNew();simpleVertivalMenu.init($menuElem);$menuElem.addClass('initialized');});if($(".rnr-b-vmenu.simple.initialized").length||$('div:first-child.rnr-b-hmenu.initialized').length){$('body').on('click',function(e){if($(e.target).closest('.touchHover').length==0){$('.touchHover').removeClass('touchHover');}});}
$(".rnr-b-vmenu.tree:not(.initialized)").each(function(index,elem){var $menuElem=$(elem),treeLikeMenu=new Runner.menu.TreeLikeVmenuNew();treeLikeMenu.init($menuElem);$menuElem.addClass('initialized');});if($(".rnr-quickjump").length&&!$(".rnr-quickjump:first").prop("initialized")){Runner.menu.QuickJumpNew.prototype.init();}},destroyVideo:function(){if(typeof projekktor==="undefined"){return;}
var hasMasterList=Runner.pages.PageSettings.getTableData(this.tName,"hasMasterList"),pageObj=this;$('.projekktor',this.pageCont).each(function(){if(!hasMasterList||!$(this).parents('.'+pageObj.makeClassName('c-master')).length){projekktor(this.id).setStop().selfDestruct();}});},pageHasCharts:function(){return!!$('[data-runner-chart-params]',this.pageCont).length;},createCharts:function(){$('[data-runner-chart-params]',this.pageCont).each(function(){Runner.Charts.createChart($(this).data('runner-chart-params'));}).remove();},loadFiles:function(){if(this.pageHasCharts()){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'libs/js/anychart.min.js']);Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'libs/js/migrationTool.js'],settings.global["webRootPath"]+'libs/js/anychart.min.js');}
var yuiFiles=[];if(Runner.pages.PageSettings.getTableData(this.tName,"isUseCK")){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'plugins/ckeditor/ckeditor.js']);}
if(Runner.pages.PageSettings.getTableData(this.tName,"isUseResize")){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/runnerJS/RunnerResizeGrid.js']);}
if(Runner.pages.PageSettings.getTableData(this.tName,"isUseGoogleMap")){switch(Runner.pages.PageSettings.getGlobalData("mapProvider")){case Runner.controls.constants.GOOGLE_MAPS:Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/runnerJS/MapManager.js',settings.global["webRootPath"]+'include/runnerJS/gmap.js']);break;case Runner.controls.constants.OPEN_STREET_MAPS:Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/runnerJS/MapManager.js',settings.global["webRootPath"]+'include/runnerJS/osmap.js',settings.global["webRootPath"]+'plugins/OpenLayers.js']);break;case Runner.controls.constants.BING_MAPS:Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/runnerJS/MapManager.js',settings.global["webRootPath"]+'include/runnerJS/bingmap.js']);break;}}
var fSett=Runner.pages.PageSettings.getTableData(this.tName,"fieldSettings"),fName;for(fName in fSett){if(fSett[fName].timePick){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+"include/timepickr_jquery.timepickr.js"]);}
if(Runner.debugMode&&fSett[fName].editFormat==Runner.controls.constants.EDIT_FORMAT_DATE&&(fSett[fName].dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_DP||fSett[fName].dateEditType==Runner.controls.constants.EDIT_DATE_DD_DP)){Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+"include/yui/calendar.js"],"include/yui/container.js","include/yui/event.js");}}
Runner.util.ScriptLoader.onFilesLoaded(this.asyncInitCall());Runner.util.ScriptLoader.load();if(Runner.isBootstrap()){return;}
if(this.tabsPresented){yuiFiles.push('tabview');}
if(this.useResize&&this.pageType==Runner.pages.constants.PAGE_LIST&&!Runner.isMobile){yuiFiles=yuiFiles.concat(['cookie','json-parse','json-stringify','datatable-base','resize']);}
if(yuiFiles.length){Runner.Y.use(yuiFiles,this.asyncInitCall());}},initFlyMobile:function(){if(!Runner.isMobile||this.openMode!==Runner.pages.constants.OPENMODE_POPUP){return;}
var bricksForMobileFly=this.getBrickObjs('',false,true),pageObj=this,i,l;for(i=0,l=bricksForMobileFly.length;i<l;i++){if(bricksForMobileFly[i].visible()){this.bricksForMobileFly.push(bricksForMobileFly[i]);this.hideBrick(bricksForMobileFly[i].name);}}
this.showBrick("flypanel_mobile");this.replaceBrickContentHTMLWith("flypanel_mobile",this.headerCont||''+this.bodyCont+this.footerCont||'');$('#closefly').bind('click',function(e){Runner.pages.PageManager.unregister(pageObj.tName,pageObj.pageId);});},afterCloseFlyWinHandler:function(win,$modal){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!win&&!win._obj&&!this.win&&!this.bsWin){return;}
this.destroyVideo();this.fireEvent('afterClose');this.unregisterDetails();Runner.pages.PageManager.unregister(this.tName,this.pageId);},unregisterDetails:function(){if(!this.dpObjs){return;}
var tName,detailsPageObj;for(tName in this.dpObjs){detailsPageObj=this.dpObjs[tName].detailsPageObj;if(detailsPageObj){Runner.pages.PageManager.unregister(detailsPageObj.tName,detailsPageObj.pageId);}}},resizeAndMoveWindow:function(oldPageObj){if(Runner.isBootstrap()&&this.openMode===Runner.pages.constants.OPENMODE_POPUP&&this.bsWin&&oldPageObj.bsWin){this.resizeAndMoveBSWindow(oldPageObj);return;}
if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!this.win||!oldPageObj.win){return;}
var $widgetNode=$(oldPageObj.win.get("boundingBox").getDOMNode()),winHeight=Math.max($widgetNode.outerHeight(),oldPageObj.win.get('height'));oldPageObj.win.syncXY();this.win.show();this.setWindowPositionAndSize($widgetNode.outerWidth(),winHeight,oldPageObj.win.get("xy"));this.popupSizeIsCorrected=true;},resizeAndMoveBSWindow:function(oldPageObj){if($(window).width()<768){return;}
var $oldDialog=$(".modal-dialog",oldPageObj.bsWin),$oldModalBody=$(".modal-body",oldPageObj.bsWin),$oldModalContentBox=$(".modal-content",oldPageObj.bsWin),$modalContentBox=$(".modal-content",this.bsWin);$modalContentBox.width($oldModalContentBox.width());$modalContentBox.height($oldModalContentBox.height());$(".modal-body",this.bsWin).width($oldModalBody.width()).height($oldModalBody.height());$(".modal-dialog",this.bsWin).css({top:$oldDialog.css("top"),left:$oldDialog.css("left")});this.bsWin.toggleClass("bs-smallpopup",$modalContentBox.width()<Runner.pages.constants.SMALL_MODAL_WIDTH);this.popupSizeIsCorrected=true;},setWindowPositionAndSize:function(width,height,xy){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!this.win){return;}
this.win.set('width',width);this.win.set('height',height);this.win.set('xy',xy);},destroyWin:function(win,bsWin){if(Runner.isBootstrap()){bsWin=bsWin||this.bsWin;if(bsWin){bsWin.modal("hide");}
return;}
win=win||this.win;if(!win){return;}
var pageObj=this;setTimeout(function(){win.destroy(true);pageObj.win=null;},5);},destroyMobileWin:function(){if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.destructorMobile();}},close:function(){Runner.isMobile?this.destroyMobileWin():this.destroyWin();},setRecountFlagForPopup:Runner.emptyFn,initEvents:function(){var tName=this.createAsDefault&&this.pageType!=Runner.pages.constants.PAGE_PRINT?Runner.pages.constants.NOT_TABLE_BASED_TNAME:this.tName,events=Runner.pages.PageSettings.getTableEventsData(tName,this.pageType),eventHnArr,evName,i;for(evName in events){eventHnArr=events[evName];for(i=0;i<eventHnArr.length;i++){this.on(evName,eventHnArr[i].hn,eventHnArr[i].scope||this);}}},initControls:function(){if(!this.controlsMap){return;}
for(var i=0;i<(this.controlsMap.controls||[]).length;i++){Runner.controls.ControlFactory(this.controlsMap.controls[i],this.pageType,false,this);}},initViewControls:function(){if(!this.viewControlsMap||typeof this.viewControlsMap!=="object"){return;}
this.setupViewContols(this.viewControlsMap.controls,this.pageCont);if(Runner.pages.PageSettings.getTableData(this.tName,"hasMasterList")&&this.viewControlsMap.mViewControlsMap&&typeof this.viewControlsMap.mViewControlsMap==="object"){this.setupViewContols(this.viewControlsMap.mViewControlsMap.controls,$('.rnr-b-mastergridfields'));}},setupViewContols:function(viewContols,pageCont){for(var i=0;i<(viewContols||[]).length;i++){(Runner.viewControls.ViewControlFactory(viewContols[i],this.pageType,pageCont,this)).init();}},initLookups:function(){var pageCtrls=Runner.controls.ControlManager.getAt(this.tName,this.pageId),i;if(!pageCtrls){return;}
for(i=0;i<pageCtrls.length;i++){pageCtrls[i].setDependencies(this.tName,this.pageId);}},hasMaps:function(){return this.controlsMap&&this.controlsMap.gMaps&&this.controlsMap.gMaps.isUseGoogleMap&&Runner.globalGmapLoader;},getTabs:function(tabControlIdx){tabControlIdx=tabControlIdx||0;if(!this.isBootstrap()){return null;}
var $tabContext=$(".panel.with-tabs",this.pageCont).eq(tabControlIdx);if(!$tabContext.length){return null;}
return new Runner.Tabs($tabContext);},isUseTabs:function(){return this.controlsMap&&typeof this.controlsMap.tabs==="object"&&!Runner.isArray(this.controlsMap.tabs);},initTabsSections:function(){this.initTabs();this.initSections();this.initSteps();},initTabs:function(){if(!this.tabsPresented){return;}
var tabs=this.controlsMap.tabs,pageObj=this,tabGroup,tabName;this.tabs={};if(Runner.isBootstrap()){for(tabGroup in tabs){this.tabs[tabGroup]={};for(tabName in tabs[tabGroup]){this.tabs[tabGroup][tabName]=$('[href="#'+tabName+this.id+'"][data-toggle="tab"]');if(this.hasMaps()){this.tabs[tabGroup][tabName].on("shown.bs.tab",function(e){pageObj.mapManager&&pageObj.mapManager.updateLittleMaps();});}}}
return;}
this.Y&&this.Y.use('tabview',function(Y){var tabView;for(tabGroup in tabs){tabView=new Y.TabView({srcNode:'#'+tabGroup+pageObj.id}).render();$('.rnr-tab-navigation',tabView.get('listNode').getDOMNode()).removeClass('rnr-tab-navigation');$('.rnr-hidden-tab-panel',tabView.get('panelNode').getDOMNode()).removeClass('rnr-hidden-tab-panel');tabView.on('selectionChange',function(e){if(e.prevVal){$(e.prevVal.get("srcNode").getDOMNode()).closest('li').removeClass('selected')}
if(e.newVal){$(e.newVal.get("srcNode").getDOMNode()).closest('li').addClass('selected');}
if(pageObj.mapManager){Y.later(0,null,function(){pageObj.mapManager.updateLittleMaps();});}});pageObj.tabs[tabGroup]=tabView;}});},checkIfSectionPresented:function(){return this.controlsMap&&typeof this.controlsMap.sections==="object"&&!Runner.isArray(this.controlsMap.sections);},getSectionCount:function(){return this.isBootstrap()?$(".panel.form-section",this.pageCont).length:0;},getSection:function(sectionIdx){sectionIdx=sectionIdx||0;if(!this.isBootstrap())
return null;var $context=$(".panel.form-section",this.pageCont).eq(sectionIdx);if(!$context.length){return null;}
return new Runner.Section($context);},getSections:function(){var sections=[],i,section,sc=this.getSectionCount();for(i=0;i<sc;i++){section=this.getSection(i);if(section){sections.push(section);}}
return sections;},initSections:function(){if(!this.checkIfSectionPresented()){return;}
if(Runner.isBootstrap()){if(this.hasMaps()){this.getSections().forEach(function(section,idx){var pageObj=this;section.get().on("shown.bs.collapse",function(e){pageObj.mapManager&&pageObj.mapManager.updateLittleMaps();});},this);}
return;}
for(var secId in this.controlsMap.sections){$("#"+secId+this.id+"Butt").bind("click",{secId:secId,pageObj:this},this.toggleSection);}},initSteps:function(){if(!this.controlsMap||!this.controlsMap.multistep){return;}
var $stepnav=$('#stepnav'+this.id),pageObj=this,hashStep,initialStep=this.controlsMap.initialStep,stepSelector=this.isBootstrap()?'li':'a';$stepnav.on('click',stepSelector,function(){var $stepNavCurrentIdx=$stepnav.children().index(this),stepFields,ddStepFields,counter,ddNavValidationResolvedHandler;if($stepNavCurrentIdx<=pageObj.currentStep){pageObj.setCurrentStep($stepNavCurrentIdx);return false;}
stepFields=pageObj.controlsMap.steps[pageObj.currentStep];ddStepFields=[];pageObj.getForm();$.each(pageObj.form.fieldControls,function(idx,control){if($.inArray(control.fieldName,stepFields)!==-1&&control.isSetValidation("DenyDuplicated")){ddStepFields.push(control.fieldName);}});counter=ddStepFields.length;if(!!ddStepFields.length){ddNavValidationResolvedHandler=function(cfName,status){counter=counter-1;if(status){pageObj.un("ddValidationResolved",ddNavValidationResolvedHandler);return;}
if(!!counter){return;}
pageObj.un("ddValidationResolved",ddNavValidationResolvedHandler);if(pageObj.form.validate(stepFields)){pageObj.setCurrentStep($stepNavCurrentIdx);}};pageObj.on("ddValidationResolved",ddNavValidationResolvedHandler);pageObj.form.validate(ddStepFields);return false;}
if(pageObj.form.validate(stepFields)){pageObj.setCurrentStep($stepNavCurrentIdx);}
return false;});$('[id=nextstep'+this.id+']').on('click',function(){var stepFields=pageObj.controlsMap.steps[pageObj.currentStep],ddStepFields=[],counter,ddNSValidationResolvedHandler;if(pageObj.currentStep>=pageObj.controlsMap.steps.length){return false;}
pageObj.getForm();$.each(pageObj.form.fieldControls,function(idx,control){if($.inArray(control.fieldName,stepFields)!==-1&&control.isSetValidation("DenyDuplicated")){ddStepFields.push(control.fieldName);}});counter=ddStepFields.length;if(!!ddStepFields.length){ddNSValidationResolvedHandler=function(cfName,status){counter=counter-1;if(status){pageObj.un("ddValidationResolved",ddNSValidationResolvedHandler);return;}
if(!!counter){return;}
pageObj.un("ddValidationResolved",ddNSValidationResolvedHandler);if(pageObj.form.validate(stepFields)){pageObj.setCurrentStep(pageObj.currentStep+1);}};pageObj.on("ddValidationResolved",ddNSValidationResolvedHandler);pageObj.form.validate(ddStepFields);return false;}
if(pageObj.form.validate(stepFields)){pageObj.setCurrentStep(pageObj.currentStep+1);}
return false;});if(this.openMode==Runner.pages.constants.OPENMODE_PRELOADED){hashStep=parseInt(location.hash.replace('#',''),10);if(hashStep>1&&pageObj.controlsMap.steps[hashStep-1]){initialStep=hashStep-1;}}
this.setCurrentStep(initialStep);},setCurrentStep:function(index){index=parseInt(index);if(this.openMode==Runner.pages.constants.OPENMODE_PRELOADED){location.hash="#"+(index+1);}
var $stepNavLinks=$('#stepnav'+this.id).children();$stepNavLinks.removeClass('active');if($stepNavLinks.length>index){$stepNavLinks.eq(index).addClass('active');}
if(!this.isBootstrap()){$('[id=prevstep'+this.id+']').css('display',index>0?'block':'none');$('[id=nextstep'+this.id+']').css('display',index<$stepNavLinks.length-1?'block':'none');$('[id=saveButton'+this.id+']').css('display',index<$stepNavLinks.length-1?'none':'block');}else{$('[id=prevstep'+this.id+']').toggle(index>0);$('[id=nextstep'+this.id+']').toggle(index<$stepNavLinks.length-1);$('[id=saveButton'+this.id+']').toggle(index>=$stepNavLinks.length-1);}
$('[id^=step_][id$=_'+this.id+']').hide();$("#step_"+index+"_"+this.id).show();if(this.mapManager){this.mapManager.updateLittleMaps();}
this.currentStep=index;},openFieldTabsSections:function(fNamesArr){var steps=this.controlsMap.steps,sections=this.controlsMap.sections,tabs=this.controlsMap.tabs,bs=Runner.isBootstrap(),i,stepIndex,secId,tabInd,selected,tabGroup,tab;if(steps!==undefined&&Runner.isArray(steps)){for(stepIndex=0;stepIndex<steps.length;stepIndex++){for(i=0;i<fNamesArr.length;i++){if($.inArray(fNamesArr[i],steps[stepIndex])!==-1){this.setCurrentStep(stepIndex);selected=true;break;}}
if(selected){break;}}
return;}
if(!Runner.isArray(sections)){for(secId in sections){for(i=0;i<fNamesArr.length;i++){if($.inArray(fNamesArr[i],sections[secId])!==-1){if(bs){$("#section_body_"+secId+this.id).collapse('show');}else{$("#"+secId+this.id).show();$("#"+secId+this.id+"Butt").attr("src",Runner.pages.constants.MINUS_GIF);}
break;}}}}
if(!Runner.isArray(tabs)){for(tabGroup in tabs){tabInd=0;selected=false;for(tab in tabs[tabGroup]){for(i=0;i<fNamesArr.length;i++){if($.inArray(fNamesArr[i],tabs[tabGroup][tab])!==-1){if(bs){this.tabs[tabGroup][tab].tab("show");}else{this.tabs[tabGroup].selectChild(tabInd);}
selected=true;break;}}
if(selected){break;}
tabInd++;}}}},adjustHeightAndWidth:function(){if(!this.win&&!this.bsWin||this.popupSizeIsCorrected){return;}
if(!this.controlsMap.multistep){this.adjustPopWindowHeightByContent();this.adjustPopWindowWidthByContent();return;}
var $allTabs=$('[id^=step_][id$=_'+this.id+']'),$visibleTab=$('[id^=step_][id$=_'+this.id+']:visible'),maxHeight=0,maxWidth=0,$bigger,$wides;if(!$allTabs.length){return;}
$allTabs.css("visibility","hidden");$allTabs.each(function(idx,elem){var $elem=$(elem);$elem.show();if(maxHeight<$elem.height()){maxHeight=$elem.height();$bigger=$elem;}
if(maxWidth<$elem.get(0).scrollWidth){maxWidth=$elem.get(0).scrollWidth;$wides=$elem;}
$elem.hide();});$bigger.show();this.adjustPopWindowHeightByContent();$bigger.hide();$wides.show();this.adjustPopWindowWidthByContent();$allTabs.css("visibility",'visible').hide();$visibleTab.show();},adjustPopWindowHeightByContent:function(contentDivClass){if(!this.win&&!this.bsWin){return;}
contentDivClass=contentDivClass||"rnr-pagewrapper";var $bodyNode,$widgetNode,defaultMaxWinHeight=Math.floor(4*$(window).height()/5),widgetHeightWithoutContent,contentHeight,winHeight,heightDelta,newWinHeight;if(Runner.isBootstrap()){$bodyNode=$(".modal-body",this.bsWin);$widgetNode=$(".modal-content",this.bsWin);heightDelta=$widgetNode.height()-$bodyNode.height();contentHeight=$bodyNode.children("div."+contentDivClass).outerHeight(true);newWinHeight=Math.min(contentHeight+heightDelta,defaultMaxWinHeight);if(newWinHeight>=$widgetNode.height()){$widgetNode.height(newWinHeight);$bodyNode.height(newWinHeight-heightDelta);}
this.bsWin.toggleClass("bs-smallpopup",$widgetNode.width()<Runner.pages.constants.SMALL_MODAL_WIDTH);}else{$bodyNode=$(this.win.bodyNode.getDOMNode());$widgetNode=$(this.win.get("boundingBox").getDOMNode());widgetHeightWithoutContent=$widgetNode.height()-$bodyNode.height();contentHeight=$bodyNode.children("div."+contentDivClass).outerHeight(true);winHeight=Math.max(contentHeight+widgetHeightWithoutContent+1,$widgetNode.height());winHeight=Math.min(winHeight,defaultMaxWinHeight);this.win.set("height",winHeight);}},adjustPopWindowWidthByContent:function(contentDivClass){if(!this.win&&!this.bsWin){return;}
contentDivClass=contentDivClass||"rnr-pagewrapper";var $bodyNode,$widgetNode,$dialog,minWidth,defaultMaxWinWidth=Math.floor(4*$(window).width()/5),widgetWidthWithoutContent,contentWidth,scrollWidth;if(Runner.isBootstrap()){$dialog=$(".modal-dialog",this.bsWin);$bodyNode=$(".modal-body",this.bsWin);$widgetNode=$(".modal-content",this.bsWin);contentWidth=this.controlsMap.multistep?$bodyNode.get(0).scrollWidth:$bodyNode.width();if(contentWidth>defaultMaxWinWidth){$bodyNode.width(defaultMaxWinWidth);$widgetNode.width(defaultMaxWinWidth);}else{$bodyNode.width(contentWidth);$widgetNode.width(contentWidth);$dialog.width(contentWidth);}
this.bsWin.toggleClass("bs-smallpopup",$widgetNode.width()<Runner.pages.constants.SMALL_MODAL_WIDTH);if($dialog.offset().left+$dialog.width()>$(window).width()){$dialog.css({left:($bodyNode.width()-$(window).width())/2});}}else{$bodyNode=$(this.win.bodyNode.getDOMNode());$widgetNode=$(this.win.get("boundingBox").getDOMNode());widgetWidthWithoutContent=$widgetNode.width()-$bodyNode.width(),contentWidth=$bodyNode.children("div."+contentDivClass).outerWidth(true),scrollWidth=$bodyNode.children("div."+contentDivClass)[0].scrollWidth;contentWidth=contentWidth>scrollWidth?contentWidth:scrollWidth;minWidth=Math.max(contentWidth+widgetWidthWithoutContent,$widgetNode.width());minWidth=Math.min(minWidth,defaultMaxWinWidth);this.win.set("width",minWidth);}},toggleSection:function(e){if(!e){return;}
var secId=e.data.secId,pageObj=e.data.pageObj,$button=$(this),$section=$("#"+secId+pageObj.id),toggler=$button.attr("src")===Runner.pages.constants.PLUS_GIF;$section.toggle(toggler);$button.attr("src",toggler?Runner.pages.constants.MINUS_GIF:Runner.pages.constants.PLUS_GIF);if(pageObj.mapManager){pageObj.mapManager.updateLittleMaps();}},setFirstFocus:function(pageId,ctrls){ctrls=ctrls||Runner.controls.ControlManager.getAt(this.tName);if(!ctrls||!ctrls.length){return false;}
var indx,i,fNamesArr=[],step,pageObj=this,spanContIds=[],currentStep,currnetIndxCtrl,firstInvalidIndx=false;for(i=0;i<ctrls.length;i++){if(ctrls[i]&&ctrls[i].isFocusAllowed()){spanContIds[i]=ctrls[i].spanContId;}}
if(this.controlsMap&&this.controlsMap.multistep){for(step in this.controlsMap.steps){$("span[id^='edit"+(pageId||this.id)+"_']").each(function(){indx=$.inArray(this.id,spanContIds);if(currentStep===undefined&&indx>-1&&$.inArray(ctrls[indx].fieldName,pageObj.controlsMap.steps[step])>-1){if(ctrls[indx].isInvalid){currentStep=step;currnetIndxCtrl=indx;firstInvalidIndx=indx;}}});if(currentStep!==undefined){this.setCurrentStep(currentStep);ctrls[currnetIndxCtrl].setFocus();return true;}}}else if(this.controlsMap&&(this.controlsMap.tabs||this.controlsMap.sections)){for(i=0;i<ctrls.length;i++){if(ctrls[i].isInvalid){firstInvalidIndx=firstInvalidIndx||i;fNamesArr.push(ctrls[i].fieldName);}}
this.openFieldTabsSections(fNamesArr);}
$("span[id^='edit"+(pageId||this.id)+"_']:visible").each(function(){indx=firstInvalidIndx!==false?firstInvalidIndx:$.inArray(this.id,spanContIds);if(indx>-1){ctrls[indx].setFocus();return false;}});return true;},isFirstInvalidControl:function(ctrl){return ctrl.spanContId===$("span[id^='edit"+ctrl.id+"_']:visible:has(div.rnr-error-text:visible):first").attr("id");},getInvalidControls:function(ctrls){ctrls=ctrls||Runner.controls.ControlManager.getAt(this.tName);if(!ctrls||!ctrls.length){return[];}
var indx,i,validateAction,invalidCtrls=[];for(i=0;i<ctrls.length;i++){validateAction=ctrls[i].validate();if(ctrls[i].isInvalid||!validateAction.result){invalidCtrls.push(ctrls[i]);}}
return invalidCtrls;},showField:function(fieldName){var ctrl=Runner.getControl(this.pageId,fieldName);$("[data-fieldname="+fieldName+"]").toggleClass(this.makeClassName('hiddenfield'),false);if(ctrl){ctrl.hiddenByField=false;}},hideField:function(fieldName){var ctrl=Runner.getControl(this.pageId,fieldName);$("[data-fieldname="+fieldName+"]").toggleClass(this.makeClassName('hiddenfield'),true);if(ctrl){ctrl.hiddenByField=true;}},hideBricks:function(arrOfNames){for(var i=arrOfNames.length;i--;){this.hideBrick(arrOfNames[i]);}},hideBrick:function(name){var brickObjs=this.getBrickObjs(name),i;for(i=brickObjs.length;i--;){brickObjs[i].hide();}},showBricks:function(arrOfNames){for(var i=arrOfNames.length;i--;){this.showBrick(arrOfNames[i]);}},showBrick:function(name){var brickObjs=this.getBrickObjs(name),i;for(i=brickObjs.length;i--;){brickObjs[i].show();}},toggleBrick:function(name,toggler){toggler?this.showBrick(name):this.hideBrick(name);},showBrickMobile:function(name,contName){var brickObjs=this.getBrickObjs(name,contName),i;for(i=brickObjs.length;i--;){brickObjs[i].show();}},getBricksObjs:function(arrOfNames){var bricksObjs={},i;for(i=0;i<arrOfNames.length;i++){bricksObjs[arrOfNames[i]]=this.getBrickObjs(arrOfNames[i]);}
return bricksObjs;},getBrickObjs:function(name,pageCont,all){return Runner.bricks.Brick.prototype.getBrickObjs(name||'',pageCont||this.pageCont,all,this.layoutVersion,this.id);},getBrickElem:function(name){var bricksArr=this.getBrickObjs(name);if(!bricksArr.length){return false;}
return bricksArr[0].elem},getBrickGridElem:function(){var bricksArr=this.getBrickObjs('grid'),i;for(i=0;i<bricksArr.length;i++){if(!bricksArr[i].elem.closest('.rnr-b-masterinfo').length){return bricksArr[i].elem;}}
return false;},getBrickContentsElem:function(name){var bricksArr=this.getBrickObjs(name);if(!bricksArr.length){return false;}
return bricksArr[0].contentElem;},getBricksHtml:function(pageCont,bricksForReload){var bricksHtml={},i,brick;pageCont=pageCont||this.pageCont;bricksForReload=Runner.isArray(bricksForReload)?bricksForReload:this.bricksForReload;for(i=bricksForReload.length;i--;){if(this.layoutVersion==2){brick=$('.'+this.makeClassName('b-'+bricksForReload[i]),pageCont);}else{brick=$('[data-brick='+bricksForReload[i]+']',pageCont);}
if(brick.length){bricksHtml[bricksForReload[i]]={html:brick.html(),isHidden:brick.hasClass(this.makeClassName("hiddenbrick"))||brick.parent('div').hasClass(this.makeClassName("hiddencontainer"))};}else{bricksHtml[bricksForReload[i]]={html:'',isHidden:true};}}
return bricksHtml;},replaceBricksWith:function(newBricks){for(var name in newBricks){this.replaceBrickWith(name,newBricks[name]);}},replaceBrickWith:function(name,newBrick){var brickObjs=this.getBrickObjs(name),i;for(i=brickObjs.length;i--;){brickObjs[i].replaceWith(newBrick);}},replaceBricksHTMLWith:function(newBricksHTML,pageCont){for(var name in newBricksHTML){this.replaceBrickHTMLWith(name,newBricksHTML[name],pageCont);}},replaceBrickHTMLWith:function(name,newHTML,pageCont){var brickObjs=this.getBrickObjs(name,pageCont),i;for(i=brickObjs.length;i--;){brickObjs[i].replaceHTMLWith(newHTML);}},replaceBricksContentsWith:function(newBricksContents){for(var name in newBricksContents){this.replaceBrickContentWith(name,newBricksContents[name]);}},replaceBrickContentWith:function(name,newContent){var brickObjs=this.getBrickObjs(name),i;for(i=brickObjs.length;i--;){brickObjs[i].replaceContentWith(newContent);}},replaceBricksContentsHTMLWith:function(newContentsHTML){for(var name in newContentsHTML){this.replaceBrickContentHTMLWith(name,newContentsHTML[name]);}},replaceBrickContentHTMLWith:function(name,newHTML){var brickObjs=this.getBrickObjs(name),i;for(i=brickObjs.length;i--;){brickObjs[i].replaceContentHTMLWith(newHTML);}},displayMessage:function(text,styled,error){var messageText=text;if(styled){messageText=this.getMessageText(text,error);}
this.replaceBrickContentHTMLWith('message',messageText);},hideMessage:function(){this.hideBrick('message');},displayHalfPreparedMessage:function(text,error){this.replaceBrickContentHTMLWith('message',this.getMessageText(text,error));if(this.isBootstrap()){this.getBrickContentsElem('message').addClass(error?"alert-danger":" alert-success");}},showPageMessageWithErrorText:function(text){this.displayHalfPreparedMessage(text,true);this.showBrick("message");},getMessageText:function(text,error){if(!this.isBootstrap())
return"<div class='rnr-message"+(error?" rnr-error":"")+"'>"+text+"</div>";return"<h5>"+text+'</h5>';},getSearchController:function(){return this.searchController;},initSearch:function(){if(!this.controlsMap||!this.controlsMap.searchPanelActivated||!this.controlsMap.search||!this.controlsMap.search.searchBlocks){return false;}
this.useSearchSuggests=Runner.pages.PageSettings.getTableData(this.tName,"ajaxSuggest");this.searchController=new Runner.search.SearchController({id:this.pageId,tName:this.tName,pageType:this.pageType,useSuggest:this.useSearchSuggests,usedSrch:this.controlsMap.search.usedSrch,fNamesArr:this.controlsMap.search.allSearchFields,searchFieldsLabels:this.controlsMap.search.allSearchFieldsLabels,searchTableName:this.controlsMap.search.searchTableName,shortTName:this.controlsMap.search.shortSearchTableName,panelSearchFields:this.controlsMap.search.panelSearchFields,isSearchPanelInflexible:this.controlsMap.search.inflexSearchPanel,isSearchRequired:this.controlsMap.search.isSearchRequired,requiredSearchFields:this.controlsMap.search.requiredSearchFields,searchPanelRunByUserApi:this.controlsMap.search.searchPanelRunByUserApi});this.searchController.init(this.controlsMap.search.searchBlocks);},hideSearchControllerContainers:function(){if(this.useSearchSuggests||this.searchController&&this.searchController.useSuggest&&typeof DestroySuggestDiv==="function"){DestroySuggestDiv();}},initChangeCtrlEvents:function(){var ctrls=Runner.controls.ControlManager.getAt(this.tName,this.pageId),i;if(!ctrls){return;}
for(i=0;i<ctrls.length;i++){ctrls[i].on('editing',this.changePageHn,{},this);}},changePageHn:function(e,updContext){if(e&&(e.type=='keyup'||e.type=='keypress'||e.type=='keydown')&&!Runner.isAcceptableKeyCode(e)){return;}
updContext=updContext||{};if(!updContext.resetHappend){this.setPageModified(true);}},isPageModified:function(){return this.pageModified;},setPageModified:function(state){this.pageModified=state;},beforeUnloadHn:function(){if(this.isPageModified()){return Runner.lang.constants.TEXT_QUESTION_UNSAVED_CHANGES;}},makeClassName:function(name){return(this.oldLayout?"runner-":"rnr-")+name;},reload:function(baseParams,reloadParams){var form,pageObj=this;if(this.openMode==Runner.pages.constants.OPENMODE_PRELOADED){form=new Runner.form.BasicForm({addRndVal:false,initImmediately:true,submitUrl:Runner.pages.getUrl(this.tName,this.pageType),standardSubmit:true,baseParams:baseParams,method:"GET"});form.submit();return;}
if(this.containerBased()){this.preparePageForReloading(this.openContainer);if(this.multiRecordPage){baseParams.recordId=Runner.genId();Runner.setIdCounter(this.id+10000);}
baseParams=Runner.apply(this.baseParams,baseParams);baseParams.id=this.id;Runner.runnerAJAX(this.requestUrl||Runner.pages.getUrl(this.tName,this.pageType),baseParams,function(respObj){Runner.apply(pageObj,reloadParams||{});pageObj.pageReloadHn(respObj,reloadParams);});}},cleanupBeforeReload:function(){this.destroyVideo();},preparePageForReloading:function(){},pageReloadHn:function(respObj){var $tabs;if(this.containerBased()){Runner.stopLoading(this.openContainer);if(!respObj.success){$("#message_block"+this.id).html("Submit failed!");}
this.cleanupBeforeReload();Runner.applyPagesData(respObj.pagesData);this.pageData=Runner.getPageData(this.id);this.proxy=this.pageData.proxy;Runner.setIdCounter(respObj.idStartFrom);respObj.bodyCont=Runner.pages.PageManager.wrapPageBody(respObj.html,this.tName,this.pageType);respObj.headerCont=respObj.headerCont||"";respObj.footerCont=respObj.footerCont||"";if(this.openMode==Runner.pages.constants.OPENMODE_CONTAINER||this.openMode==Runner.OPENMODE_PRELOADED_CONTAINER){Runner.pages.PageManager.putToContainer.call(this,respObj);}else if(this.openMode==Runner.pages.constants.OPENMODE_DASHCONTAINER){Runner.pages.PageManager.putToDashContainer.call(this,respObj);}else if(this.openMode==Runner.pages.constants.OPENMODE_DASHTABS){Runner.pages.PageManager.putToDashTab.call(this,respObj);}else if(this.openMode==Runner.pages.constants.OPENMODE_TABVIEW){Runner.pages.PageManager.putToTab.call(this,respObj);}
$(this.openContainer).children(".rnr-pagewrapper").first().html(respObj.html);this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.id];if(this.openMode===Runner.pages.constants.OPENMODE_DASHTABS){this.pageCont=$(this.openContainer);}
this.init();}},replaceGridTabs:function(){if(!this.$gridTabControl){return;}
var $tabs=this.$gridTabControl.find('[data-tabid][data-pageid='+this.id+']');if($tabs.length){$tabs.filter(":not(:first)").parent().remove();$tabs.first().parent().replaceWith(this.pageData.gridTabs);}else{this.$gridTabControl.append(this.pageData.gridTabs);}},containerBased:function(){return this.openMode==Runner.pages.constants.OPENMODE_CONTAINER||this.openMode==Runner.pages.constants.OPENMODE_PRELOADED_CONTAINER||this.openMode==Runner.pages.constants.OPENMODE_DASHCONTAINER||this.openMode==Runner.pages.constants.OPENMODE_DASHTABS||this.openMode==Runner.pages.constants.OPENMODE_TABVIEW;},displayGenericAjaxError:function(message,previewMessage){var showDetailedError=Runner.pages.PageSettings.getGlobalData("showDetailedError"),$indicator,$error,$removelink;if(!previewMessage){previewMessage=showDetailedError?Runner.lang.constants.TEXT_SERVER_ERROR_OCCURRED:Runner.pages.PageSettings.getGlobalData("customErrorMessage")}
if(!previewMessage){return;}
if(showDetailedError){$indicator=$('<div class="rnr-error-indicator">'+previewMessage
+'. <a href=# class="expandlink">'+Runner.lang.constants.TEXT_SEE_DETAILS+'</a></div>');}else{$indicator=$('<div class="rnr-error-indicator">'+previewMessage+'</div>');}
$error=$('<div class="rnr-error-message"></div>').html(message).hide().appendTo(document.body);$removelink=$('<a class="removelink" href="#">Close</a>').appendTo($error);$indicator.css({'margin-left':'-'+$(document.body).css("padding-left").replace("px","")+'px','margin-top':'-'+$(document.body).css("padding-top").replace("px","")+'px','margin-bottom':(1+parseInt($(document.body).css("padding-top").replace("px","")))+'px'}).prependTo(document.body);$removelink.on('click',function(e){$error.remove();$indicator.remove();return false;});$indicator.on('click','.expandlink',function(e){$error.show();$indicator.hide();return false;});},finishDashElementActions:function(updContext,dashAction){updContext=updContext||this.updContext;dashAction=dashAction||this.dashAction;if(!this.dashboard||!updContext||!dashAction){return;}
updContext.continueActions(this.dashboard.getElementByName(this.dashElement),dashAction);this.dashAction=null;this.updContext=null;},setChart:function(chartObj){this.chartObj=chartObj;},hideExcessSeparators:function(){if(!this.isBootstrap()){return;}
var moreButBrickElem=this.getBrickElem("morebutton"),lis,i,prevElemsDysplayed=false,lastDisplayedLi=false;if(!moreButBrickElem){return;}
lis=moreButBrickElem.find('ul.dropdown-menu > li');for(i=0;i<lis.length;i++){if($(lis[i]).attr('role')=="separator"&&(!prevElemsDysplayed||i===0)){$(lis[i]).css('display','none');}else if($(lis[i]).attr('role')=="separator"&&prevElemsDysplayed){prevElemsDysplayed=false;$(lis[i]).css('display','block');lastDisplayedLi=$(lis[i]);}else{if(Runner.util.getChildDisplayedElems($(lis[i])).length>0){prevElemsDysplayed=true;lastDisplayedLi=$(lis[i]);}}}
if(lastDisplayedLi){moreButBrickElem.find("button.dropdown-toggle").removeClass("hideMoreButton");if(lastDisplayedLi.attr('role')=="separator"){lastDisplayedLi.css('display','none');}}else{moreButBrickElem.find("button.dropdown-toggle").addClass("hideMoreButton").parent().removeClass("open");}},initCollapseButtons:function(){var pageObj=this;$("[data-runner-toggle=collapse]",this.pageCont).each(function(){$($(this).data('target'),pageObj.pageCont).addClass('bs-hidden-xs');}).click(function(e){$($(this).data('target'),pageObj.pageCont).each(function(idx,element){var $element=$(element);if(!$element.hasClass('bs-hidden-xs')){$element.addClass('bs-hidden-xs').attr('aria-expanded','false');}else{$element.removeClass('bs-hidden-xs').attr('aria-expanded','true');}});});},clearSelection:Runner.emptyFn,getFormControls:function(){return[];},getExtraPageReloadParams:function(){return{};},initGridTabs:function(){$('[data-pageid='+this.id+'][data-tabid]').off("click").on("click",function(e){if($(this).parent().hasClass('active')){e.preventDefault();}});},getControl:function(fieldName){return Runner.controls.ControlStorage.byIdField(this.id,fieldName);},getInlineRow:Runner.emptyFn});Runner.pages.SearchPage=Runner.extend(Runner.pages.RunnerPage,{dashboard:null,isDashSearchPage:false,constructor:function(cfg){Runner.pages.SearchPage.superclass.constructor.call(this,cfg);this.isDashSearchPage=Runner.pages.PageSettings.getTableData(this.tName,"isDashSearchPage");if(this.dashboard){this.warnOnLeaving=false;}},init:function(){Runner.pages.SearchPage.superclass.init.call(this);this.initButtons();this.fireEvent('afterInit',this,this.proxy,this.id);},initButtons:function(){var pageObj=this;$("#searchButton"+this.pageId).on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.submitAdvancedSearch();}
return false;});$("#resetButton"+this.pageId).on("click",function(e){pageObj.searchController.clearCtrls();pageObj.searchController.initSearchButtonStatus();return false;});$("#backButton"+this.pageId).on("click",function(e){pageObj.searchController.returnSubmit();return false;});},initSearch:function(){var pageType,tName=this.tName,baseParams=this.controlsMap.search.baseParams||this.baseParams||{},pageExtraPrams=Runner.pages.PageSettings.getTableData(this.tName,"extraSearchPageParams");if(this.isDashSearchPage){pageType=this.dashboard.pageType;tName=this.dashboard.tName;}else if(this.pageMode===Runner.pages.constants.SEARCH_DASHBOARD){pageType=this.pageType;}else{pageType=this.controlsMap.search.submitPageType;}
this.searchController=new Runner.search.SearchForm({id:this.pageId,tName:tName,pageType:pageType,searchType:'advanced',baseParams:baseParams,usedSrch:this.controlsMap.search.usedSrch,fNamesArr:this.controlsMap.search.allSearchFields,isSearchRequired:this.controlsMap.search.isSearchRequired,shortTName:Runner.pages.PageSettings.getShortTName(this.tName),requiredSearchFields:this.controlsMap.search.requiredSearchFields,ajaxSubmit:this.pageMode===Runner.pages.constants.SEARCH_DASHBOARD,useSuggest:Runner.pages.PageSettings.getTableData(this.tName,"ajaxSuggest"),formBaseParams:Runner.apply(pageExtraPrams,baseParams)});this.searchController.init(this.controlsMap.search.searchBlocks);if(this.isDashSearchPage){this.searchController.on('afterSearch',function(respObj,srchController,srchForm){this.dashboard.doLoadAction();Runner.toggleButton($("[id=showAll"+this.dashboard.id+"]"),respObj.show_all);},this);}},submitAdvancedSearch:function(){var showAllMode=this.searchController.usedSrch&&!this.searchController.hasNotEmptyControl();if(this.pageMode===Runner.pages.constants.SEARCH_DASHBOARD&&!this.isDashSearchPage){if(showAllMode){this.searchController.prepareForShowAllSubmit();}else{this.searchController.prepareForSearchSubmit();}
this.dashboard.doSearchAction(this.dashElement,this.searchController.getDashSearchParams(showAllMode));return;}
if(showAllMode){this.searchController.showAllSubmit();return;}
this.searchController.submitSearch();}});Runner.pages.ViewPage=Runner.extend(Runner.pages.RunnerPage,{keys:null,keyFields:null,prevKeys:null,nextKeys:null,masterKeys:null,pageType:Runner.pages.constants.PAGE_VIEW,nextButton:null,prevButton:null,editPageButton:null,headerEditPageButton:null,inlineObjectParams:null,isShowDetails:false,dashGridBased:false,constructor:function(cfg){Runner.pages.ViewPage.superclass.constructor.call(this,cfg);this.masterKeys=cfg.masterKeys||Runner.pages.PageSettings.getTableData(this.tName,'masterKeys');this.keys=cfg.keys||Runner.pages.PageSettings.getTableData(this.tName,'keys');this.keyFields=cfg.keyFields||Runner.pages.PageSettings.getTableData(this.tName,'keyFields');this.prevKeys=Runner.pages.PageSettings.getTableData(this.tName,'prevKeys');this.nextKeys=Runner.pages.PageSettings.getTableData(this.tName,'nextKeys');this.isShowDetails=Runner.pages.PageSettings.getTableData(this.tName,"isShowDetails");this.dpTablesParams=this.controlsMap&&this.controlsMap.dpTablesParams;},init:function(){var dbElem,pageObj=this;Runner.pages.ViewPage.superclass.init.call(this);this.initButtons();this.fireEvent('afterInit',this,this.proxy,this.id);if(this.dashboard){dbElem=this.dashboard.getElementByName(this.dashElement);if(dbElem.major&&jQuery.inArray(Runner.pages.constants.PAGE_EDIT,dbElem.tabsPageTypes)===-1){if(!this.updContext||!this.updContext.hasUpdateRecordAction()){this.dashboard.doMoveAction(this.dashElement,{keys:this.keys,masterKeys:this.masterKeys},this.updContext);}
this.dashboard.doReportFirstLastAction(this.dashElement,!this.prevKeys,!this.nextKeys,this.updContext);}
this.finishDashElementActions();if(this.dashboard.getElementByName(this.dashElement).reload){if(this.reloadTimerId){window.clearTimeout(this.reloadTimerId);}
this.reloadTimerId=window.setTimeout(function(){pageObj.dashboard.doTimerReloadAction(pageObj.dashElement,{keys:this.keys});},1000*this.dashboard.getElementByName(this.dashElement).reload);}}},initControls:function(){if(!this.controlsMap){return;}
for(var i=0;i<(this.controlsMap.controls||[]).length;i++){Runner.controls.MockControlFactory(this.controlsMap.controls[i],this.pageType,this.tName,this);}},initLookups:Runner.emptyFn,initForTabs:function(){Runner.pages.ViewPage.superclass.initForTabs.call(this);this.initMap();this.initDetails();},initButtons:function(){var pageObj=this;$("#backButton"+this.id).bind("click",function(e){window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_LIST)+"?a=return";return false;});$("#backToMenuButton"+this.id).bind("click",function(e){window.location.href=Runner.getPageUrl("menu");return false;});$("#closeButton"+this.id).bind("click",function(e){pageObj.close();return false;});this.initNavigationButtons();},initNavigationButtons:function(){var pageObj=this;this.editPageButton=$("#editPageButton"+this.id).on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.openEditPage();}
return false;}).attr("href",Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys));this.headerEditPageButton=$("#headerEditPageButton"+this.id).on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.openEditPage();}
return false;}).attr("href",Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys));this.nextButton=$("[id=nextButton"+this.id+"]");this.prevButton=$("[id=prevButton"+this.id+"]");this.updateNavigationVisibility();this.nextButton.on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.openPrevNextRecordPage(pageObj.nextKeys,1);}
return false;});this.prevButton.on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.openPrevNextRecordPage(pageObj.prevKeys,-1);}
return false;});},updateNavigationVisibility:function(){if(!this.dashboard||this.dashboard.getElementByName(this.dashElement).major){return;}
if((!this.dashAction||!this.dashAction.data.firstRecord)&&(this.dashAction||this.prevKeys&&this.prevKeys.length)){this.prevButton.removeClass("rnr-invisible-button");}
if((!this.dashAction||!this.dashAction.data.lastRecord)&&(this.dashAction||this.nextKeys&&this.nextKeys.length)){this.nextButton.removeClass("rnr-invisible-button");}},openPrevNextRecordPage:function(keys,step){var pageParams,i;if(this.openMode===Runner.pages.constants.OPENMODE_PRELOADED){window.location.href=Runner.pages.getUrl(this.tName,this.pageType,keys);return;}
if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){pageParams=this.getOpenPageParams(keys,this.inlineObjectParams.rowId+step);this.disablePageButtons();Runner.pages.PageManager.openPage(pageParams);return;}
if(this.openMode===Runner.pages.constants.OPENMODE_DASHTABS){if(!this.dashboard.getElementByName(this.dashElement).major){this.dashboard.doMoveAdjacentAction(this.dashElement,step>0);return;}
pageParams={baseParams:{}};for(i=0;i<keys.length;++i){pageParams.baseParams['editid'+(i+1)]=keys[i];}
this.dashboard.loadSingleRecord(this.dashboard.getElementByName(this.dashElement),[Runner.pages.constants.PAGE_EDIT,Runner.pages.constants.PAGE_VIEW],pageParams);}},openEditPage:function(){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!Runner.pages.PageSettings.getTableData(this.tName,"showEditInPopup")){window.location.href=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys);return;}
var pageParams=Runner.pages.EditPage.prototype.getOpenPageParams.call(this,this.keys,this.inlineObjectParams.rowId);this.disablePageButtons();pageParams.popupCentered=true;Runner.pages.PageManager.openPage(pageParams);},disablePageButtons:function(){Runner.addDisabledClass(this.nextButton);Runner.addDisabledClass(this.prevButton);Runner.addDisabledClass(this.editPageButton);Runner.addDisabledClass(this.headerEditPageButton);},enablePageButtons:function(){Runner.delDisabledClass(this.nextButton);Runner.delDisabledClass(this.prevButton);Runner.delDisabledClass(this.editPageButton);Runner.delDisabledClass(this.headerEditPageButton);},getOpenPageParams:function(keys,rowId,inlineObj,afterCreateHn){var hostPage=this,inlineObj=inlineObj||this.inlineObjectParams.getInlineObject(),row=inlineObj.getRowById(rowId),params={tName:inlineObj.tName,pageType:Runner.pages.constants.PAGE_VIEW,keys:keys,keyFields:this.keyFields||row.keyFields,modal:true,dashGridBased:inlineObj.dashGridBased,baseParams:{parId:inlineObj.id,table:escape(inlineObj.tName)},inlineObjectParams:{getInlineObject:function(){return inlineObj;},rowId:rowId}}
if(typeof afterCreateHn==="function"){params.afterCreateHn=afterCreateHn;}else{params.afterCreateHn=function(){if(!this.controlsMap){if(this.message){hostPage.displayHalfPreparedMessage(this.message);hostPage.showBrick('message');}
hostPage.initLoginLink();hostPage.enablePageButtons();if(this.win){this.win.destroy(true);}
if(this.bsWin){this.bsWin.modal('hide');}
return;}
this.resizeAndMoveWindow(hostPage);this.adjustPopWindowHeightByContent();if(hostPage.win){hostPage.win.destroy(true);}
if(hostPage.bsWin){hostPage.bsWin.modal('hide');}}}
if(inlineObj.dashGridBased&&inlineObj.pageObj){params.baseParams.dashTName=inlineObj.pageObj.dashboard.tName;params.baseParams.dashelement=inlineObj.pageObj.dashElement;}
if(hostPage instanceof Runner.pages.ListPageDP&&hostPage.baseParams.mastertable){params.baseParams.mastertable=hostPage.baseParams.mastertable;Runner.apply(params.baseParams,hostPage.controlsMap.masterKeys);}
return params;},initMap:function(){if(!this.hasMaps()){return;}
Runner.globalGmapLoader.onLoad(function(){this.mapManager=new Runner.controls.MapManager(this.controlsMap.gMaps);this.mapManager.init();if(this.isPageInTab()){Runner.pages.PageManager.onTabShown(this,this.mapManager.updateLittleMaps.bind(this.mapManager));}},this);},initDetails:function(){if(!this.isShowDetails||!this.dpTablesParams){return;}
var dtName,dParams,i;this.dpObjs={};for(i=0;i<this.dpTablesParams.length;i++){dtName=this.dpTablesParams[i].tName;dParams={tName:dtName,parId:this.id,masterTName:this.tName,id:this.dpTablesParams[i].id,pType:this.dpTablesParams[i].pType,}
if(!this.dashboard){dParams.controlsMap=this.controlsMap.dControlsMap[dtName];dParams.viewControlsMap=this.viewControlsMap.dViewControlsMap[dtName];this.dpObjs[dtName]=new Runner.util.details.ViewDP(dParams);}else{dParams.masterPageType=this.pageType;dParams.pageType=this.dpTablesParams[i].pType;dParams.masterKeys=this.masterKeys[dtName];dParams.dashTName=this.dashboard.tName;dParams.dashElement=this.dashElement;this.dpObjs[dtName]=new Runner.util.details.ViewEditDashDP(dParams);}
this.dpObjs[dtName].init();}},showNextPrevButtons:function(next,prev){this.prevButton.toggleClass("rnr-invisible-button",!prev);this.nextButton.toggleClass("rnr-invisible-button",!next);}});Runner.pages.EditorPage=Runner.extend(Runner.pages.RunnerPage,{tabs:null,form:null,submitUrl:'',baseParams:null,isShowDetails:false,upploadErrorHappened:false,fileFieldsCount:0,saveButton:null,keepLocking:false,afterSaveAction:-1,constructor:function(cfg){Runner.pages.EditorPage.superclass.constructor.call(this,cfg);this.submitUrl=Runner.getPageUrl(Runner.pages.PageSettings.getShortTName(this.tName),this.pageType);this.submitUrl+="?submit=1&";if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.submitUrl+="fly=1&";}
this.isShowDetails=this.checkIfShowDetails();this.setBaseParams();this.addEvents("beforeSave","afterSave");},checkIfShowDetails:function(){return Runner.pages.PageSettings.getTableData(this.tName,"isShowDetails");},setBaseParams:function(){this.baseParams=this.baseParams||{};this.baseParams["id"]=this.id;this.baseParams["editType"]=this.baseParams["editType"]||this.editType;if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.baseParams["onFly"]=1;}},destructor:function(){Runner.pages.EditorPage.superclass.destructor.call(this);if(this.form){this.form.destructor();this.form=null;}},init:function(){Runner.pages.EditorPage.superclass.init.call(this);if(this.beforeSave){this.on({'beforeSave':this.beforeSave});}
if(this.afterSave){this.on({'afterSave':this.afterSave});}
this.initButtons();},initForTabs:function(){Runner.pages.EditorPage.superclass.initForTabs.call(this);this.initToolTips();this.setFirstFocus();if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.on('windowSizeCorrected',this.setFirstFocus);}},initButtons:function(){var pageObj=this;$("[id=backToMenuButton"+this.id+"]").on("click",function(e){window.location.href=Runner.getPageUrl("menu");return false;});this.saveButton=$("[id=saveButton"+this.id+"]").bind("click",function(){if(Runner.isDisabledButton(this)){return false;}
var $button=$(this),controls,i;pageObj.disablePageButtonsWhileSaving();pageObj.fileFieldsCount=0;pageObj.upploadErrorHappened=false;controls=Runner.controls.ControlManager.getAt(pageObj.tName,pageObj.pageId);for(i=0;i<controls.length;i++){if(controls[i].editFormat==Runner.controls.constants.EDIT_FORMAT_FILE&&controls[i].filesToUploadCount>0){controls[i].errorHappened=false;pageObj.fileFieldsCount++;controls[i].uploadForm.bind('fileuploadstopped',{ctrl:controls[i]},function(e){pageObj.fileFieldsCount--;$button.unbind('fileuploadstopped');if(e.data.ctrl.errorHappened){pageObj.upploadErrorHappened=true;pageObj.errorHn();}else{pageObj.callSaveHn();}});$(".btn-primary.start",controls[i].uploadForm).click();}}
if(pageObj.fileFieldsCount<1){pageObj.saveHn();}
return false;});if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!this.win){return;}
this.win.on("destroy",function(){if(pageObj.locking&&!pageObj.keepLocking){pageObj.locking.UnlockRecordInline(pageObj.sKeys);}});},errorHn:function(row){if(this.fileFieldsCount<1){this.enablePageButtonsAfterSaving();}},callSaveHn:function(){if(this.fileFieldsCount<1&&!this.upploadErrorHappened){this.saveHn();}},getVisibleControls:function(){var controls=Runner.controls.ControlStorage.byId(this.pageId),visibleControls=[],i;for(i=0;i<controls.length;++i){if(!controls[i].hiddenByField){visibleControls.push(controls[i]);}}
return visibleControls;},getFormControls:function(){return this.getVisibleControls();},getForm:function(){this.form=new Runner.form.BasicForm({submitUrl:this.submitUrl,standardSubmit:this.isSubmitStandard(),isFileUpload:true,method:'POST',id:this.pageId,baseParams:this.baseParams,fieldControls:this.getFormControls(),useMultipart:true,submitFailed:{fn:function(response,formObj,fieldControls){if(response===-1){formObj.clearForm();this.showError("<< "+Runner.lang.constants.TEXT_INLINE_ERROR+" >>");}else{this.displayGenericAjaxError(response);}
this.fireEvent("afterSave",{success:false,html:response},formObj,fieldControls,this);this.enablePageButtonsAfterSaving();},scope:this},beforeSubmit:{fn:function(formObj){return this.fireEvent("beforeSave",formObj,formObj.fieldControls,this);},scope:this},validationFailed:{fn:function(formObj,fieldControls,failedControlsArr){var fNamesArr=[],i;for(i=0;i<failedControlsArr.length;i++){fNamesArr.push(failedControlsArr[i].fieldName);}
this.openFieldTabsSections(fNamesArr);setTimeout(function(){failedControlsArr[0].setFocus();},4);this.enablePageButtonsAfterSaving();return false;},scope:this}});},isSubmitStandard:function(){return this.openMode===Runner.pages.constants.OPENMODE_PRELOADED;},saveHn:function(){this.getForm();this.setPageModified(false);this.form.submit();},showError:function(txt,isArr){if(!txt.length){return;}
if(!isArr){this.displayHalfPreparedMessage(txt,true);}else{this.getBrickContentsElem('message').empty();for(var i=0;i<txt.length;i++){this.getBrickContentsElem('message').append(this.getMessageText(txt[i],true)+(i<txt.length-1?'<br>':''));}}
this.showBrick('message');},disablePageButtonsWhileSaving:function(){Runner.addDisabledClass(this.saveButton);},enablePageButtonsAfterSaving:function(){Runner.delDisabledClass(this.saveButton);},enablePageButtons:function(){},cleanupBeforeReload:function(){Runner.pages.EditorPage.superclass.cleanupBeforeReload.call(this);Runner.controls.ControlStorage.unregisterById(this.pageId);this.form.destructor();this.form=null;this.upploadErrorHappened=false;},resetControls:function(){var cntrls=Runner.controls.ControlStorage.byId(this.id),updContext,i;if(!cntrls||!cntrls.length){return;}
updContext={enableNextButtons:false,resetHappend:true,values:{}};for(i=0;i<cntrls.length;i++){if(cntrls[i].mode===this.pageType&&cntrls[i].editFormat!="Readonly"){updContext.values[cntrls[i].fieldName]=cntrls[i].defaultValue;}}
for(i=0;i<cntrls.length;i++){if(cntrls[i].mode===this.pageType&&cntrls[i].editFormat!="Readonly"){cntrls[i].reset(updContext);}}}});Runner.pages.AddPageFly=Runner.extend(Runner.pages.EditorPage,{pageType:Runner.pages.constants.PAGE_ADD,editType:Runner.pages.constants.ADD_ONTHEFLY,lookupCtrl:null,constructor:function(cfg){Runner.pages.AddPageFly.superclass.constructor.call(this,cfg);},setBaseParams:function(){Runner.pages.AddPage.superclass.setBaseParams.call(this);this.baseParams['a']="added";},init:function(){Runner.pages.AddPageFly.superclass.init.call(this);this.fireEvent("afterInit",this,this.proxy,this.id);},initButtons:function(){Runner.pages.AddPage.superclass.initButtons.call(this);var pageObj=this;$("[id='cancelButton"+this.id+"']").on("click",function(e){pageObj.close();return false;});},getForm:function(){if(this.form){return this.form;}
Runner.pages.AddPageFly.superclass.getForm.call(this);this.form.on("successSubmit",function(respObj,basicForm,fieldControls){var evRes=this.fireEvent("afterSave",respObj,basicForm,fieldControls,this);if(evRes!==false){this.close();}},this);}});Runner.pages.AddPage=Runner.extend(Runner.pages.EditorPage,{pageType:Runner.pages.constants.PAGE_ADD,masterSaved:false,inlineObjectParams:null,keys:null,mKeys:null,afterAddId:"",detKeys:null,viewPageButton:null,editPageButton:null,recordAdded:false,constructor:function(cfg){Runner.pages.AddPage.superclass.constructor.call(this,cfg);if(this.openMode===Runner.pages.constants.OPENMODE_POPUP||this.isShowDetails){this.afterSaveAction=Runner.pages.PageSettings.getTableData(this.tName,"afterAddAction");}
if(this.proxy[this.shortTName+"_recordAdded"]){this.recordAdded=true;}},setBaseParams:function(){Runner.pages.AddPage.superclass.setBaseParams.call(this);this.baseParams["a"]="added";if(this.dashboard){this.baseParams.dashelement=this.dashElement;this.baseParams.dashTName=this.dashboard.tName;}
if(this.isShowDetails){this.baseParams["editType"]=this.openMode===Runner.pages.constants.OPENMODE_POPUP?Runner.pages.constants.ADD_MASTER_POPUP:Runner.pages.constants.ADD_MASTER;}},init:function(){Runner.pages.AddPage.superclass.init.call(this);this.fireEvent('afterInit',this,this.proxy,this.id);},initForTabs:function(){Runner.pages.AddPage.superclass.initForTabs.call(this);this.initDetails();},initButtons:function(){Runner.pages.AddPage.superclass.initButtons.call(this);var pageObj=this;$("[id=backButton"+this.id+"], #extraBackButton"+this.id).on("click",function(e){window.location.href=Runner.getPageUrl(Runner.pages.PageSettings.getShortTName(pageObj.tName),Runner.pages.constants.PAGE_LIST,'a=return');return false;});$("[id=cancelButton"+this.id+"]").on("click",function(e){pageObj.close();return false;});if(this.isBootstrap())
this.initNavigationButtons();},initNavigationButtons:function(){var pageObj=this;this.viewPageButton=$("[id='viewPageButton"+this.id+"']").on("click",function(e){var keys=$(this).data("keys");if(Runner.isDisabledButton(this)||!keys){return false;}
Runner.addDisabledClass(this.viewPageButton);pageObj.openEditViewPage("view",keys);return false;});this.editPageButton=$("[id='editPageButton"+this.id+"']").on("click",function(e){var keys=$(this).data("keys");if(Runner.isDisabledButton(this)||!keys){return false;}
Runner.addDisabledClass(this.editPageButton);pageObj.openEditViewPage("edit",keys);return false;});},openEditViewPage:function(pageType,keys){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP){window.location.href=pageType==="view"?Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,keys):Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,keys);return;}
var pageParams=pageType==="view"?Runner.pages.ViewPage.prototype.getOpenPageParams.call(this,keys,this.baseParams.rowId):Runner.pages.EditPage.prototype.getOpenPageParams.call(this,keys,this.baseParams.rowId);Runner.pages.PageManager.openPage(pageParams);},isInlineAddContentChanged:function(tName){if(!this.dpObjs||!this.dpObjs[tName]){return false;}
var inlineObj=this.dpObjs[tName].detailsPageObj.inlineAdd;return inlineObj&&inlineObj.inlineAddChangeContent;},initDetails:function(){if(!this.isShowDetails){return;}
var dpTablesParams=this.controlsMap.dpTablesParams,dtName,dParams,i;if(!dpTablesParams){return;}
this.dpObjs={};for(i=0;i<dpTablesParams.length;i++){dtName=dpTablesParams[i].tName;dParams={tName:dtName,parId:this.id,masterTName:this.tName,id:dpTablesParams[i].id,pType:dpTablesParams[i].pType,controlsMap:this.controlsMap.dControlsMap[dtName],useChildCount:this.openMode===Runner.pages.constants.OPENMODE_POPUP,saveFailed:{fn:this.onDetailsSavingFailed,scope:this},detailsSaved:{fn:this.onDetailsSaved,scope:this}};this.dpObjs[dtName]=new Runner.util.details.AddDP(dParams);this.dpObjs[dtName].init();}},onDetailsSaved:function(detObj,allVals,fields,allKeys,allRowIds){var detailsSaved=true,tName,hostListPage;for(tName in this.dpObjs){if(this.isInlineAddContentChanged(tName)&&this.dpObjs[tName].detailsPageObj.inlineAdd&&(!this.dpObjs[tName].submitMade||!this.dpObjs[tName].submitSucceded)){detailsSaved=false;}else{$("#_"+this.dpObjs[tName].id).parent().remove();}}
if(!detailsSaved){return;}
if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP&&this.afterAddId){window.location.href=Runner.pages.getUrl(this.tName,this.pageType)+"?"+'afteradd='+this.afterAddId;return;}
if(!!allRowIds.length){hostListPage=Runner.pages.PageManager.getAt(this.tName,this.baseParams.parId)
for(tName in hostListPage.dpObjs){hostListPage.dpObjs[tName].updateChildRecNum(this.detKeys[tName]);}
this.runAfterAddAction();}
this.noDetailsToSave=true;},onDetailsSavingFailed:function(detObj,respObj,formObj){var messArr=[],tName,msg,txt,dpId,$detailsGridPosition;for(tName in this.dpObjs){if(this.isInlineAddContentChanged(tName)){if(this.dpObjs[tName].submitMade&&!this.dpObjs[tName].submitSucceded){msg=Runner.lang.constants.TEXT_DETAIL_NOT_SAVED.replace('%s',tName);txt="<div id='_"+this.dpObjs[tName].id+"' class='message mes_not'><<< "+msg+" >>> "
+"</div>";dpId=dpId||this.dpObjs[tName].id;messArr.push(txt);}else if(!this.dpObjs[tName].submitMade){return;}}}
this.form.makeReadonly();$detailsGridPosition=$("#detailPreview"+dpId).position();if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){if(this.isBootstrap()){this.bsWin.animate({scrollTop:$detailsGridPosition.top});}else{$(this.win.bodyNode.getDOMNode()).animate({scrollTop:$detailsGridPosition.top});}}else{$(window).scrollTop($detailsGridPosition.top);}
this.showError(messArr,true);Runner.delDisabledClass(this.saveButton);},addFormEventsForDetails:function(){if(!this.isShowDetails){return;}
this.form.on('beforeSubmit',function(basicForm){var valRes,tName;for(tName in this.dpObjs){if(this.isInlineAddContentChanged(tName)&&!this.dpObjs[tName].validate()){valRes=false;}}
if(!valRes){basicForm.validate();this.enablePageButtonsAfterSaving();}
return valRes;},this);this.form.on('successSubmit',function(respObj,basicForm,fieldControls){if(respObj.success){this.masterSaved=true;this.keys=respObj.keys;this.mKeys=respObj.mKeys;this.message=respObj.message;this.detKeys=respObj.detKeys;this.afterAddId=respObj.afterAddId||"";this.noDetailsToSave=false;for(var tName in this.dpObjs){this.dpObjs[tName].saveDetails(respObj.mKeys[tName]);}}},this);},getForm:function(){if(this.form){return;}
Runner.pages.AddPage.superclass.getForm.call(this);this.addFormEventsForDetails();this.form.on('successSubmit',function(respObj,basicForm,fieldControls){var evRes;if(respObj.hideCaptcha){$('.captcha_block').remove();}
if(respObj.message){this.displayHalfPreparedMessage(respObj.message,!respObj.success);this.showBrick('message');this.adjustHeightAndWidth();}
this.message=respObj.message;this.keys=this.keys||respObj.keys;this.detKeys=this.detKeys||respObj.detKeys;if(respObj.wrongCaptchaFieldName!==undefined){this.openFieldTabsSections([respObj.wrongCaptchaFieldName]);Runner.getControl(this.pageId,respObj.wrongCaptchaFieldName).setFocus();}else{this.setFirstFocus();}
evRes=this.fireEvent("afterSave",respObj,basicForm,fieldControls,this);if(evRes!==false&&(!this.isShowDetails||this.noDetailsToSave)){this.runAfterAddAction();return;}
this.initLoginLink();this.enablePageButtonsAfterSaving();},this);},checkIfNoDetailsWereAdded:function(){for(var tName in this.dpObjs){if(!!this.dpObjs[tName].detailsPageObj.inlineAdd.rows.length){return false;}}
return true;},runAfterAddAction:function(){var pageParams,inlineObj,addedRowId,dTableName,keyParams,dKey,popupMode=this.openMode===Runner.pages.constants.OPENMODE_POPUP,pageObj=this;switch(this.afterSaveAction){case Runner.pages.constants.AA_TO_ADD:if(!popupMode){window.location.href=Runner.pages.getUrl(this.tName,this.pageType);break;}
pageParams=this.getOpenPageParams(null,function(){if(pageObj.message){this.displayHalfPreparedMessage(pageObj.message,false);this.showBrick('message');}
this.resizeAndMoveWindow(pageObj);pageObj.close();});Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AA_TO_VIEW:if(!popupMode){window.location.href=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,this.keys);break;}
inlineObj=this.inlineObjectParams.getInlineObject();addedRowId=inlineObj.rows[inlineObj.rows.length-1].id;pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(this,this.keys,addedRowId);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AA_TO_EDIT:if(!popupMode){window.location.href=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys);break;}
inlineObj=this.inlineObjectParams.getInlineObject();addedRowId=inlineObj.rows[inlineObj.rows.length-1].id;pageParams=Runner.pages.EditPage.prototype.getOpenPageParams.call(this,this.keys,addedRowId,pageObj.message);pageParams.popupCentered=true;Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AA_TO_DETAIL_LIST:dTableName=Runner.pages.PageSettings.getTableData(this.tName,"afterAddActionDetTable");window.location.href=Runner.getPageUrl(dTableName,Runner.pages.constants.PAGE_LIST);break;case Runner.pages.constants.AA_TO_DETAIL_ADD:dTableName=Runner.pages.PageSettings.getTableData(this.tName,"afterAddActionDetTable");keyParams=[];for(dKey in this.detKeys[dTableName]){if(this.detKeys[dTableName].hasOwnProperty(dKey)){keyParams.push(dKey+"="+encodeURIComponent(this.detKeys[dTableName][dKey]));}}
window.location.href=Runner.getPageUrl(dTableName,Runner.pages.constants.PAGE_ADD)
+"?"+keyParams.join("&")+"&mastertable="+encodeURIComponent(this.tName);break;case Runner.pages.constants.AA_TO_LIST:if(!popupMode){window.location.href=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_LIST);break;}
this.close();break;default:this.close();}},isSubmitStandard:function(){return!this.isShowDetails&&this.openMode!==Runner.pages.constants.OPENMODE_POPUP||Runner.isMobile;},saveHn:function(){if(!this.masterSaved){Runner.pages.AddPage.superclass.saveHn.call(this);return;}
if(!this.isShowDetails){return;}
for(var tName in this.dpObjs){this.dpObjs[tName].saveDetails(this.mKeys[tName]);}},getOpenPageParams:function(parId,afterCreateHn){var hostListPage=Runner.pages.PageManager.getAt(this.tName,parId||this.baseParams.parId),inlineObj=hostListPage.inlineAdd||this.inlineObjectParams.getInlineObject(),pageParams={tName:this.tName,pageType:Runner.pages.constants.PAGE_ADD,modal:true,editType:Runner.pages.constants.ADD_POPUP,baseParams:{parId:hostListPage.id||this.baseParams.parId,table:this.tName,editType:Runner.pages.constants.ADD_POPUP},inlineObjectParams:{getInlineObject:function(){return inlineObj;}},afterSave:{fn:function(respObj,formObj,fieldControls,addPageObj){if(respObj.success){var addedRow=inlineObj.addRowToGrid(respObj,true);hostListPage.initNewRowButtons(addedRow);return;}
if(addPageObj.isBootstrap()){addPageObj.bsWin.animate({scrollTop:0});}else{addPageObj.adjustPopWindowHeightByContent();$(addPageObj.win.bodyNode.getDOMNode()).animate({scrollTop:0});}
return false;},scope:hostListPage}};if(this.dashboard){pageParams.baseParams.dashelement=this.dashElement;pageParams.baseParams.dashTName=this.dashboard.tName;}
if(hostListPage.pageMode==Runner.pages.constants.LIST_DASHBOARD||hostListPage.pageMode==Runner.pages.constants.LIST_DASHDETAILS){pageParams.baseParams.dashTName=hostListPage.dashboard.tName;pageParams.baseParams.dashelement=hostListPage.dashElement;}
if(typeof afterCreateHn==="function"){pageParams.afterCreateHn=afterCreateHn;}
if(hostListPage instanceof Runner.pages.ListPageDP&&hostListPage.baseParams.mastertable){pageParams.baseParams.mastertable=hostListPage.baseParams.mastertable;Runner.apply(pageParams.baseParams,hostListPage.controlsMap.masterKeys);}
return pageParams;}});Runner.pages.EditPage=Runner.extend(Runner.pages.EditorPage,{keys:null,keyFields:null,masterKeys:null,prevKeys:null,nextKeys:null,pageType:Runner.pages.constants.PAGE_EDIT,details:null,prevButton:{},nextButton:{},viewPageButton:null,inlineObjectParams:null,dashGridBased:false,recordUpdated:false,dpTablesParams:null,constructor:function(cfg){Runner.pages.EditPage.superclass.constructor.call(this,cfg);this.keys=cfg.keys||Runner.pages.PageSettings.getTableData(this.tName,'keys');this.masterKeys=cfg.masterKeys||Runner.pages.PageSettings.getTableData(this.tName,'masterKeys');this.keyFields=cfg.keyFields||Runner.pages.PageSettings.getTableData(this.tName,'keyFields');this.sKeys=Runner.pages.PageSettings.getTableData(this.tName,"sKeys","");this.prevKeys=Runner.pages.PageSettings.getTableData(this.tName,'prevKeys');this.nextKeys=Runner.pages.PageSettings.getTableData(this.tName,'nextKeys');this.shortTName=Runner.pages.PageSettings.getShortTName(this.tName);this.submitUrl+=this.getKeysUrlParams();if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.afterSaveAction=Runner.pages.PageSettings.getTableData(this.tName,"afterEditAction");}
if(this.proxy[this.shortTName+"_recordUpdated"]){this.recordUpdated=true;}
this.dpTablesParams=this.controlsMap&&this.controlsMap.dpTablesParams;},setBaseParams:function(){Runner.pages.EditPage.superclass.setBaseParams.call(this);this.baseParams["a"]="edited";if(this.dashboard){this.baseParams.dashelement=this.dashElement;this.baseParams.dashTName=this.dashboard.tName;}},init:function(){Runner.pages.EditPage.superclass.init.call(this);this.initLocking();this.fireEvent('afterInit',this,this.proxy,this.id);},initForTabs:function(){Runner.pages.EditPage.superclass.initForTabs.call(this);this.initDetails();},resetEditPage:function(){var reCaptchaClientId;this.resetControls();if(typeof this.controlsMap.reCaptcha!=="undefined"){reCaptchaClientId=$('#reCaptchaFor'+this.controlsMap.reCaptcha.inputCaptchaId).data('client')
grecaptcha.reset(reCaptchaClientId);}
clearTimeout(this.validateTimer);this.setPageModified(false);this.enablePageButtons();},initButtons:function(){Runner.pages.EditPage.superclass.initButtons.call(this);var pageObj=this;$("#resetButton"+this.id).on("click",function(e){pageObj.resetEditPage();e.preventDefault();});$("[id='backButton"+this.id+"'], #extraBackButton"+this.id).on("click",function(e){pageObj.unlockPage(function(){pageObj.backButtonHref()});return false;});$("#closeButton"+this.id).on("click",function(e){pageObj.hideSearchControllerContainers();pageObj.unlockPage(function(){pageObj.close();});return false;});this.initNavigationButtons();},initNavigationButtons:function(){var pageObj=this;this.viewPageButton=$("[id='viewPageButton"+this.id+"']").on("click",function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disablePageButtons();pageObj.unlockPage(function(){pageObj.openViewPage();});return false;}).attr("href",Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,this.keys));this.nextButton=$("[id=nextButton"+this.id+"]");this.prevButton=$("[id=prevButton"+this.id+"]");this.updateNavigationVisibility();if(!this.nextButton.hasClass("rnr-invisible-button")){this.nextButton.on("click",function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disablePageButtons();pageObj.unlockPage(function(){pageObj.openPrevNextRecordPage(pageObj.nextKeys,1);});return false;});}
if(!this.prevButton.hasClass("rnr-invisible-button")){this.prevButton.on("click",function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disablePageButtons();pageObj.unlockPage(function(){pageObj.openPrevNextRecordPage(pageObj.prevKeys,-1);});return false;});}},updateNavigationVisibility:function(){},unlockPage:function(handler){if(this.useLocking&&this.locking){this.locking.UnlockRecord(this.sKeys,'',handler);return;}
handler();},disablePageButtons:function(){Runner.addDisabledClass(this.nextButton);Runner.addDisabledClass(this.prevButton);Runner.addDisabledClass(this.viewPageButton);},enablePageButtons:function(){Runner.delDisabledClass(this.nextButton);Runner.delDisabledClass(this.prevButton);Runner.delDisabledClass(this.viewPageButton);},openViewPage:function(){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!Runner.pages.PageSettings.getTableData(this.tName,"showViewInPopup")){window.location.href=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,this.keys);return;}
var pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(this,this.keys,this.baseParams.rowId);Runner.pages.PageManager.openPage(pageParams);},openPrevNextRecordPage:function(keys,step){if(this.openMode==Runner.pages.constants.OPENMODE_PRELOADED){window.location.href=Runner.pages.getUrl(this.tName,this.pageType,keys);return;}
var pageParams=this.getOpenPageParams(keys,this.baseParams.rowId+step);Runner.pages.PageManager.openPage(pageParams);},getOpenPageParams:function(keys,rowId,message,inlineObj,afterCreateHn){var inlineObj=inlineObj||this.inlineObjectParams.getInlineObject(),row=inlineObj.getRowById(rowId),hostPage=this,params={tName:inlineObj.tName,pageType:Runner.pages.constants.PAGE_EDIT,keys:keys,keyFields:this.keyFields||row.keyFields,modal:true,dashGridBased:inlineObj.dashGridBased,baseParams:{parId:inlineObj.id,rowId:rowId,table:escape(inlineObj.tName),editType:Runner.pages.constants.EDIT_POPUP},inlineObjectParams:{getInlineObject:function(){return inlineObj;},rowId:rowId},afterSave:{fn:function(respObj,formObj,fieldControls,editPageObj){if(respObj.success){if(row){this.afterSubmit(row,respObj,editPageObj);}
return true;}
if(respObj.lockMessage){$('.rnr-locking').html(respObj.lockMessage).css('display','block');return false;}
if(respObj.hideCaptcha){$('.captcha_block').remove();}
editPageObj.displayHalfPreparedMessage(respObj.message||"",true);editPageObj.showBrick('message');if(editPageObj.isBootstrap()){editPageObj.bsWin.animate({scrollTop:0});}else{editPageObj.adjustPopWindowHeightByContent();$(editPageObj.win.bodyNode.getDOMNode()).animate({scrollTop:0});}
return false;},scope:inlineObj}}
if(typeof afterCreateHn==="function"){params.afterCreateHn=afterCreateHn;}else{params.openMode=params.openMode,params.openContainer=params.openContainer,params.afterCreateHn=function(){var reloadParams;if(!this.controlsMap){if(this.message){hostPage.displayHalfPreparedMessage(this.message);hostPage.showBrick('message');}
hostPage.initLoginLink();hostPage.enablePageButtons();this.close();return;}
if(message){this.displayHalfPreparedMessage(message);this.showBrick('message');}
this.resizeAndMoveWindow(hostPage);this.adjustHeightAndWidth();hostPage.keepLocking=true;hostPage.close();}};if(inlineObj.dashGridBased&&inlineObj.pageObj){params.baseParams.dashTName=inlineObj.pageObj.dashboard.tName;params.baseParams.dashelement=inlineObj.pageObj.dashElement;}
if(hostPage instanceof Runner.pages.ListPageDP&&hostPage.baseParams.mastertable){params.baseParams.mastertable=hostPage.baseParams.mastertable;Runner.apply(params.baseParams,hostPage.controlsMap.masterKeys);}
return params;},backButtonHref:function(){window.location.href=Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_LIST,'a=return');},changePageHn:function(){Runner.pages.EditPage.superclass.changePageHn.apply(this,arguments);if(this.isPageModified()){this.disablePageButtons();}},initLocking:function(){if(!this.useLocking){return;}
var pageObj=this;this.locking=new Runner.Locking({tName:this.tName,pageId:this.id,pageType:this.pageType});this.on("afterClose",function(e){pageObj.locking.UnlockDetails();pageObj.locking.UnlockRecord(pageObj.sKeys,'','');},this);pageObj.locking.StartLocking(pageObj,pageObj.id,pageObj.sKeys,Runner.pages.PageSettings.getTableData(pageObj.tName,"confirmTime"));},initDetails:function(){if(!this.isShowDetails||!this.dpTablesParams){return;}
var dtName,dParams,i;this.dpObjs={};for(i=0;i<this.dpTablesParams.length;i++){dtName=this.dpTablesParams[i].tName;dParams={tName:dtName,parId:this.id,masterTName:this.tName,id:this.dpTablesParams[i].id,pType:this.dpTablesParams[i].pType,saveFailed:{fn:this.onDetailsSavingFailed,scope:this},detailsSaved:{fn:this.onDetailsSaved,scope:this},afterDeleteDetails:{fn:this.onDetailsDeleted,scope:this},validationFailed:$.proxy(function(formObj,fieldControls){this.enablePageButtonsAfterSaving();},this)};if(!this.dashboard){dParams.childRecNum=0;dParams.useChildCount=this.openMode===Runner.pages.constants.OPENMODE_POPUP;dParams.controlsMap=this.controlsMap.dControlsMap[dtName];dParams.viewControlsMap=this.viewControlsMap&&this.viewControlsMap.dViewControlsMap?this.viewControlsMap.dViewControlsMap[dtName]:null;this.dpObjs[dtName]=new Runner.util.details.EditDP(dParams);}else{dParams.masterPageType=this.pageType;dParams.pageType=this.dpTablesParams[i].pType;dParams.masterKeys=this.masterKeys[dtName];dParams.dashTName=this.dashboard.tName;dParams.dashElement=this.dashElement;this.dpObjs[dtName]=new Runner.util.details.ViewEditDashDP(dParams);}
this.dpObjs[dtName].init();}},updateRelativeDashElements:function(){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP){this.updateRelativeDashElements=Runner.emptyFn;return;}
var inlineObj=this.inlineObjectParams.getInlineObject();if(inlineObj.dashGridBased&&inlineObj.pageObj){inlineObj.pageObj.loadDependencies(inlineObj.getRowById(this.inlineObjectParams.rowId));return;}
this.updateRelativeDashElements=Runner.emptyFn;},onDetailsSaved:function(detObj,allVals,fields,allKeys,allRowIds){if(!this.form||!Runner.isDisabledButton(this.saveButton)){this.updateRelativeDashElements();return;}
var detailsSaved=true,tName;for(tName in this.dpObjs){if(this.dpObjs[tName].submitMade!==undefined&&(this.dpObjs[tName].detailsPageObj.inlineAdd||this.dpObjs[tName].detailsPageObj.inlineEdit)&&(!this.dpObjs[tName].submitMade||!this.dpObjs[tName].submitSucceded)){detailsSaved=false;}else{$("#_"+this.dpObjs[tName].id).parent().remove();}}
if(!detailsSaved||this.formAlreadySubmitted){return;}
this.formAlreadySubmitted=true;Runner.pages.EditPage.superclass.saveHn.call(this);},onDetailsSavingFailed:function(detObj,respObj,formObj){var messArr=[],pageObj=this,tName,msg,txt,$messageBlock;for(tName in this.dpObjs){if(this.dpObjs[tName].submitMade&&!this.dpObjs[tName].submitSucceded){msg=Runner.lang.constants.TEXT_DETAIL_NOT_SAVED.replace('%s',tName);txt="<div id='_"+this.dpObjs[tName].id+"' class='message mes_not'><<< "+msg+" >>> <br>"
+"<a class='goToDetails' href='#' data-dpid='"+this.dpObjs[tName].id+"' >"+Runner.lang.constants.TEXT_DETAIL_GOTO+" "+tName+"</a>"
+"</div>";messArr.push(txt);}else if(!this.dpObjs[tName].submitMade){return;}}
$messageBlock=this.getBrickContentsElem('message');if(!$(".goToDetails",$messageBlock).length){$messageBlock.on("click",".goToDetails",function(e){var dpId=$(this).data("dpid"),$detailsGridPosition=$("#detailPreview"+dpId).position();if(pageObj.openMode===Runner.pages.constants.OPENMODE_POPUP){if(pageObj.isBootstrap()){pageObj.bsWin.animate({scrollTop:$detailsGridPosition.top});}
else{$(pageObj.win.bodyNode.getDOMNode()).animate({scrollTop:$detailsGridPosition.top});}}else{$(window).scrollTop($detailsGridPosition.top);}
return false;});}
this.showError(messArr,true);this.enablePageButtonsAfterSaving();},onDetailsDeleted:function(){this.updateRelativeDashElements();},getForm:function(){if(this.form){return;}
Runner.pages.EditPage.superclass.getForm.call(this);this.form.on('successSubmit',function(respObj,basicForm,fieldControls){var pageParams,evRes=this.fireEvent("afterSave",respObj,basicForm,fieldControls,this);this.setFirstFocus();if(evRes===false){this.initLoginLink();this.enablePageButtonsAfterSaving();if(respObj.wrongCaptchaFieldName!==undefined){this.openFieldTabsSections([respObj.wrongCaptchaFieldName]);Runner.getControl(this.pageId,respObj.wrongCaptchaFieldName).setFocus();}
this.adjustHeightAndWidth();return;}
this.runAfterEditAction(respObj);},this);},runAfterEditAction:function(respObj){var pageParams,dTableName;switch(this.afterSaveAction){case Runner.pages.constants.AE_TO_EDIT:pageParams=this.getOpenPageParams(respObj.keys,this.baseParams.rowId,respObj.message);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AE_TO_VIEW:pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(this,respObj.keys,this.baseParams.rowId);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AE_TO_NEXT_EDIT:pageParams=this.getOpenPageParams(this.nextKeys,this.baseParams.rowId+1,respObj.message);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AE_TO_PREV_EDIT:pageParams=this.getOpenPageParams(this.prevKeys,this.baseParams.rowId-1,respObj.message);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AE_TO_DETAIL_LIST:dTableName=Runner.pages.PageSettings.getTableData(this.tName,"afterEditActionDetTable");window.location.href=Runner.getPageUrl(dTableName,Runner.pages.constants.PAGE_LIST);break;case Runner.pages.constants.AE_TO_LIST:default:this.close();}},saveHn:function(){if(!this.isShowDetails){Runner.pages.EditPage.superclass.saveHn.call(this);return;}
this.getForm();if(!this.form.validate()){return;}
this.formAlreadySubmitted=false;var saveDpInlines=false,tName,sDp;for(tName in this.dpObjs){sDp=this.dpObjs[tName].saveDetails();saveDpInlines=saveDpInlines||sDp;}
if(!saveDpInlines){Runner.pages.EditPage.superclass.saveHn.call(this);}},setRecountFlagForPopup:function(){if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.needToRecountChildAfterPopup=true;}},getKeysUrlParams:function(){var keysString="",i;for(i=0;i<this.keys.length;i++){this.baseParams["editid"+(i+1)]=this.keys[i];keysString+="editid"+(i+1)+"="+this.keys[i]+'&';}
return keysString;},initDetailsRecalculation:function(){if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP||!this.baseParams.parId){return;}
var parentPage=Runner.pages.PageManager.getById(this.baseParams.parId);if(!parentPage){return;}
this.on('afterClose',function(){var tName,masterKeys;if(!pageObj.needToRecountChildAfterPopup){return;}
for(tName in parentPage.dpObjs){masterKeys=parentPage.dpObjs[tName].getRowById(pageObj.baseParams.rowId).masterKeys;parentPage.dpObjs[tName].updateChildRecNum(masterKeys,pageObj.baseParams.rowId);}});if(parentPage.pageType==Runner.pages.constants.PAGE_LIST){for(tName in parentPage.dpObjs){parentPage.dpObjs[dpObj].closeDetails(parentPage.dpObjs[dpObj].getRowById(this.baseParams.rowId));}}},disablePageButtonsWhileSaving:function(){Runner.pages.EditPage.superclass.disablePageButtonsWhileSaving.call(this);Runner.addDisabledClass(this.closeButton);this.disablePageButtons();},enablePageButtonsAfterSaving:function(){Runner.pages.EditPage.superclass.enablePageButtonsAfterSaving.call(this);Runner.delDisabledClass(this.closeButton);if(!this.isPageModified()){this.enablePageButtons();}}});Runner.pages.EditSelectedPage=Runner.extend(Runner.pages.EditPage,{defaultUncheckedBoxes:[],selection:null,constructor:function(cfg){Runner.pages.EditSelectedPage.superclass.constructor.call(this,cfg);this.selection=this.selection||Runner.pages.PageSettings.getTableData(this.tName,"selection");this.baseParams["selection[]"]=this.selection;},init:function(){Runner.pages.EditSelectedPage.superclass.init.call(this);this.initCheckboxes();},updateSaveButton:function(){this.saveButton.prop("disabled",!$("input[type=checkbox][id^=updsel_][data-field]:checked").length);},initCheckboxes:function(){var pageObj=this;$(".control-label:has(input[type=checkbox])",this.pageCont).addClass("checkbox");$("input[type=checkbox][id^=updsel_][data-field]:not(:checked)").each(function(i,cb){var field=$(cb).data('field'),ctrl=Runner.getControl(pageObj.id,field);if(ctrl){pageObj.defaultUncheckedBoxes.push(field);ctrl.makeReadonly();}});$("input[type=checkbox][id^=updsel_][data-field]",this.pageCont).on("change",function(event){var $cb=$(this),ctrl=Runner.getControl(pageObj.id,$cb.data('field'));if(!ctrl){return;}
if($cb.prop('checked')){ctrl.makeReadWrite();}else{ctrl.makeReadonly();}
pageObj.updateSaveButton();}).on("click",function(event){event.stopPropagation();});$(".control-label.checkbox",this.pageCont).on("click",function(e){$("input[type=checkbox]",this).click();});this.updateSaveButton();},resetEditPage:function(){var pageObj=this;Runner.pages.EditSelectedPage.superclass.resetEditPage.call(this);$("input[type=checkbox][id^=updsel_][data-field]").each(function(i,cb){var $cb=$(cb),checked=$cb.prop("checked");if($.inArray($cb.data("field"),pageObj.defaultUncheckedBoxes)!==-1){if(checked){$cb.click();}}else if(!checked){$cb.click();}});},initNavigationButtons:Runner.emptyFn,updateNavigationVisibility:Runner.emptyFn,getOpenPageParams:function(parId,selection,rowIds,message){var hostListPage=Runner.pages.PageManager.getAt(this.tName,parId||this.baseParams.parId),inlineObj=this.inlineObjectParams?this.inlineObjectParams.getInlineObject():hostListPage.inlineEdit,pageObj=this,params={tName:inlineObj.tName,openContainer:this.openContainer,pageType:Runner.pages.constants.PAGE_EDIT,selection:selection,modal:true,pageMode:Runner.pages.constants.EDIT_SELECTED_POPUP,dashGridBased:inlineObj.dashGridBased,baseParams:{table:escape(inlineObj.tName),parId:hostListPage.id||this.baseParams.parId,editType:Runner.pages.constants.EDIT_POPUP,"selection[]":selection,rowIds:JSON.stringify(rowIds)},inlineObjectParams:{getInlineObject:function(){return inlineObj;}},afterSave:{fn:function(respObj,formObj,fieldControls,editPageObj){var inlineObj=this;editPageObj.displayHalfPreparedMessage(respObj.message||"",!respObj.success);editPageObj.showBrick('message');if(!respObj.success){editPageObj.displayHalfPreparedMessage(respObj.message||"",true);editPageObj.showBrick('message');return false;}
rowIds.forEach(function(rowId){var row=inlineObj.getRowById(rowId);if(row&&respObj[rowId]){inlineObj.afterSubmit(row,respObj[rowId],editPageObj);}});hostListPage&&hostListPage.clearSelection();return true;},scope:inlineObj},afterCreateHn:function(){var reloadParams;if(!this.controlsMap){if(this.message){pageObj.displayHalfPreparedMessage(this.message);pageObj.showBrick('message');}
pageObj.initLoginLink();pageObj.enablePageButtons();this.close();return;}
if(message){this.displayHalfPreparedMessage(message);this.showBrick('message');}
this.resizeAndMoveWindow(pageObj);this.adjustHeightAndWidth();pageObj.keepLocking=true;pageObj.close();}};if(inlineObj.dashGridBased&&inlineObj.pageObj){params.baseParams.dashTName=inlineObj.pageObj.dashboard.tName;params.baseParams.dashelement=inlineObj.pageObj.dashElement;}
return params;},initLocking:Runner.emptyFn,initDetails:Runner.emptyFn,getFormControls:function(){var ctrls=this.getVisibleControls(),controlsNames=this.getCheckedFieldsNames(),captchaEditFieldName=Runner.pages.PageSettings.getTableData(this.tName,"captchaEditFieldName");controlsNames.push(captchaEditFieldName);return ctrls.filter(function(ctrl,idx){return $.inArray(ctrl.fieldName,controlsNames)!==-1;});},getForm:function(){if(this.form){this.form.fieldControls=this.getFormControls();this.baseParams["fields[]"]=this.getCheckedFieldsNames();return;}
this.baseParams["fields[]"]=this.getCheckedFieldsNames();Runner.pages.EditSelectedPage.superclass.getForm.call(this);},getCheckedFieldsNames:function(){var checkedFields=[];$("input[type=checkbox][id^=updsel_][data-field]:checked").each(function(i,cb){checkedFields.push($(cb).data("field"));});return checkedFields;},runAfterEditAction:function(respObj){switch(this.afterSaveAction){case Runner.pages.constants.AE_TO_EDIT:this.enablePageButtonsAfterSaving();pageParams=this.getOpenPageParams(this.baseParams.parId,this.selection,JSON.parse(this.baseParams.rowIds),respObj.message);Runner.pages.PageManager.openPage(pageParams);break;case Runner.pages.constants.AE_TO_LIST:default:this.close();}}});Runner.pages.LoginPage=Runner.extend(Runner.pages.RunnerPage,{isPopUp:false,userval:null,passval:null,captcha:null,userName:null,password:null,hostPageObj:null,notRedirect:false,rememberPassword:null,twoFactorAuth:false,constructor:function(cfg){Runner.pages.LoginPage.superclass.constructor.call(this,cfg);this.twoFactorAuth=Runner.pages.PageSettings.getGlobalData("twoFactorAuth");this.isPopUp=this.openMode===Runner.pages.constants.OPENMODE_POPUP;},init:function(){Runner.pages.LoginPage.superclass.init.call(this);this.initFields();this.initButtons();this.initiUserCodeControls();if(Runner.pages.PageSettings.getGlobalData("isFB")){this.initFBLoginMethod();}
if(this.isPopUp){this.on('windowSizeCorrected',this.setUserFocus);}else{this.setUserFocus();}
this.fireEvent('afterInit',this,this.proxy,this.id);},initLanguageSelector:function(){var $form=$('#form'+this.id,this.pageCont),$langSelector=$("#languageSelector"),extraparams=$langSelector.data("params")||"",pageUrl=Runner.pages.getUrl(this.tName,this.pageType);if(this.isBootstrap()){$(".rnr-langlink",this.pageCont).on("click",function(e){window.location.href=pageUrl+"?"+"language="+$(this).data("lang");return false;});}else{$langSelector.on("change",function(e){$("[name='btnSubmit']",$form).val("");$form.attr("action",pageUrl+"?"+extraparams+"language="+this.options[this.selectedIndex].value);$form.submit();});}},initFields:function(){var pageObj=this;this.userName=$('input[name="username"]',this.pageCont);this.password=$('input[name="password"]',this.pageCont).on('keydown',function(e){if(e.which!=13){return;}
$('#submitLogin'+pageObj.id,pageObj.pageCont).trigger('click');return false;});if(this.userval){this.userName.val(this.userval);}
if(this.passval){this.password.val(this.passval);}
this.captcha=$('#value_captcha_'+this.id);this.notRedirect=$('#notRedirect',this.pageCont).val();this.rememberPassword=$('input[name="remember_password"]',this.pageCont);},setUserFocus:function(){if(!this.userName.prop("disabled")&&this.userName.is(":visible")){this.userName.focus();}},initButtons:function(){var pageObj=this,$regTableLink,$submitLogin=$("#submitLogin"+this.id,this.pageCont);if(!this.isPopUp&&!this.twoFactorAuth){$submitLogin.on("click",function(e){$('#form'+pageObj.id,pageObj.pageCont).submit();return false;});return;}
$regTableLink=$('a[name="RegisterPage"]',this.pageCont).on("click",function(e){pageObj.registerPage($regTableLink.data("table"));return false;});$('a[name="ForgotPasswordPage"]',this.pageCont).on("click",function(e){pageObj.forgotPasswordPage();return false;});$submitLogin.on("click",function(e){Runner.runnerAJAX(Runner.getPageUrl("login"),pageObj.getAJAXLikeLoginSubmitParams(),pageObj.onLoginAction.bind(pageObj));return false;});this.initContinueButton();},initContinueButton:function(){var $continueButton=$("#continueButton",this.pageCont),pageObj=this;$continueButton.on("click",function(e){pageObj.close();return false;});},getAJAXLikeLoginSubmitParams:function(){if(!this.isPopUp&&!this.twoFactorAuth){return null;}
return params={a:"Login",id:this.id,username:this.userName.val(),password:this.password.val(),value_captcha_1:this.captcha.val(),remember_password:this.rememberPassword.is(':checked')?1:0,mode:this.isPopUp?"popup":""};},onLoginAction:function(respObj){var $continueButton=$("#continueButton",this.pageCont),$submitLogin=$("#submitLogin"+this.id,this.pageCont),pageObj=this;if(this.twoFactorAuth&&respObj.secondStepSkipped){this.onVerify(respObj);return;}
if(this.isPopUp){if(respObj.redirect){if(!this.notRedirect){window.location.href=respObj.redirect;return;}
$submitLogin.hide();$continueButton.show();respObj.message=Runner.lang.constants.SUCCES_LOGGED_IN;if(this.isBootstrap()){$('[data-brick="loginheader"]',this.pageCont).html("")}else{this.win.set("headerContent","");}
this.hideBrick('loginfields');this.hideBrick('wrapper');if(this.hostPageObj){this.hostPageObj.hideBrick('message');this.hostPageObj.adjustPopWindowHeightByContent();}}}
if(respObj.message){this.showMessage(respObj.message,!respObj.success);if(this.isPopUp){setTimeout(function(){pageObj.adjustPopWindowHeightByContent()},300);}}
if(this.twoFactorAuth&&respObj.logged){this.replaceBrickContentHTMLWith("loginfields",respObj["loginfields"]);this.replaceBrickContentHTMLWith("loginbuttons",respObj["loginbuttons"]);this.hideBrick("bsloginregister");this.hideBrick("mesreg");this.hideBrick("mesforgot");this.initiUserCodeControls();}},showMessage:function(message,warning){this.showBrick('message');var $messageBrick=this.getBrickElem('message');if(this.isBootstrap()){$messageBrick.toggleClass("alert-danger",warning);$messageBrick.toggleClass("alert-success",!warning);$messageBrick.html(message);}else{$("#login_message",$messageBrick).html(message);}},initiUserCodeControls:function(){var pageObj=this;$("#verifyCode"+this.id).on("click",function(e){if(!Runner.isDisabledButton(this)){var params={a:"verifyCode",SMSCode:$("#userCode"+pageObj.id).val(),mode:pageObj.isPopUp?"popup":"",notRedirect:pageObj.notRedirect}
Runner.runnerAJAX(Runner.getPageUrl("login"),params,pageObj.onVerify.bind(pageObj));}
return false;});$("#resendCode"+this.id).on("click",function(e){var params={a:"resendCode",mode:pageObj.isPopUp?"popup":""}
Runner.runnerAJAX(Runner.getPageUrl("login"),params,pageObj.onResend.bind(pageObj));return false;});},onVerify:function(respObj){if(respObj.redirect&&!this.notRedirect){window.location.href=respObj.redirect;return;}
if(respObj.success&&this.notRedirect){this.hideBrick("loginfields");this.replaceBrickContentHTMLWith("loginbuttons",respObj["loginbuttons"]);this.initContinueButton();this.hostPageObj&&this.hostPageObj.hideBrick("message");}
if(respObj.message){this.showMessage(respObj.message,!respObj.success);}},onResend:function(respObj){if(respObj.message){this.showMessage(respObj.message,!respObj.success);}
$("#verifyCode"+this.id).toggleClass("rnr-invisible-button",!respObj.success);$("#userCodeField"+this.id).toggleClass("rnr-hiddenblock",!respObj.success);},initFBLoginMethod:function(){var pageObj=this;if(typeof FB==="object"&&typeof FB.XFBML==="object"&&typeof FB.XFBML.parse==="function"){FB.XFBML.parse($(".bs-facebook",this.pageCont).get(0));return;}
window.fbAsyncInit=function(){FB.init({appId:Runner.pages.PageSettings.getGlobalData("FBappId"),autoLogAppEvents:true,xfbml:true,version:'v2.9',status:false,cookie:true});FB.Event.subscribe('auth.statusChange',function(response){if(response.authResponse&&response.status=="connected"){var params={fbConnected:true,mode:pageObj.isPopUp?"popup":""};Runner.runnerAJAX(Runner.getPageUrl("login"),params,function(respObj){if(respObj.logged){window.location.href=respObj.url;return;}
pageObj.showMessage(respObj.message);});}else{pageObj.showMessage('User cancelled login or did not fully authorize.');}});FB.AppEvents.logPageView();};(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return;}
js=d.createElement(s);js.id=id;js.src="//connect.facebook.net/en_US/sdk.js";fjs.parentNode.insertBefore(js,fjs);}(document,'script','facebook-jssdk'));},FBLogIn:function(){var newWindow,windowFeatures
screenX=window.screenX!==undefined?window.screenX:window.screenLeft,screenY=window.screenY!==undefined?window.screenY:window.screenTop,outerWidth=window.outerWidth!==undefined?window.outerWidth:document.body.clientWidth,outerHeight=window.outerHeight!==undefined?window.outerHeight:(document.body.clientHeight-22),width=500,height=270;windowFeatures='width='+width+',height='+height+',left='+parseInt(screenX+(outerWidth-width)/2,10)
+',top='+parseInt(screenY+(outerHeight-height)/2.5,10);newWindow=window.open(Runner.pages.PageSettings.getGlobalData("FBLoginUrl"),'Login_by_facebook',windowFeatures);if(window.focus){newWindow.focus();}
return false;},forgotPasswordPage:function(){var pageObj=this,pageParams={pageType:Runner.pages.constants.PAGE_REMIND,tName:Runner.pages.constants.NOT_TABLE_BASED_TNAME,pageId:-1,modal:true,baseParams:{parId:this.id,mode:"popup"},afterCreateHn:function(){var forgotPageObj=this;if(this.win){this.win.getButton("close").detach("click").on("click",function(){forgotPageObj.win.get('boundingBox').hide();forgotPageObj.openLoginPageOnPopUpClose(pageObj.notRedirect,pageObj.hostPageObj);});}else if(this.bsWin){this.bsWin.find("button.close").detach("click").on("click",function(){forgotPageObj.bsWin.modal('hide');forgotPageObj.openLoginPageOnPopUpClose(pageObj.notRedirect,pageObj.hostPageObj);});}
pageObj.close();}};if(this.win){this.win.get('boundingBox').hide();}
if(this.bsWin){this.bsWin.modal('hide');}
Runner.pages.PageManager.openPage(pageParams);},registerPage:function(regTable){var pageObj=this,pageParams={pageType:Runner.pages.constants.PAGE_REGISTER,tName:regTable,pageId:-1,modal:true,baseParams:{parId:this.id},afterCreateHn:function(){var regPageObj=this;pageObj.close();if(this.win){this.win.getButton("close").detach("click").on("click",function(){regPageObj.win.get('boundingBox').hide();regPageObj.openLoginPageOnPopUpClose(pageObj.notRedirect,pageObj.hostPageObj);});}else if(this.bsWin){this.bsWin.find("button.close").detach("click").on("click",function(){regPageObj.bsWin.modal('hide');regPageObj.openLoginPageOnPopUpClose(pageObj.notRedirect,pageObj.hostPageObj);});}}};if(this.win){this.win.get('boundingBox').hide();}
if(this.bsWin){this.bsWin.modal('hide');}
Runner.pages.PageManager.openPage(pageParams);}});Runner.pages.RemindPage=Runner.extend(Runner.pages.RunnerPage,{init:function(){Runner.pages.RemindPage.superclass.init.call(this);this.initButtons();this.fireEvent('afterInit',this,this.proxy,this.id);},initButtons:function(){var pageObj=this;$("[id=submitRemind]",this.pageCont).on("click",function(e){var pageParams={mode:"popup",onFly:2,btnSubmit:'Remind',username_email:$('input[name="username_email"]').val(),value_captcha_1:$('input[id="value_captcha_'+pageObj.id+'"]').val()};Runner.runnerAJAX(Runner.getPageUrl("remind"),pageParams,function(respObj){if(respObj.message){pageObj.showBrick('message');setTimeout(function(){pageObj.adjustPopWindowHeightByContent()},300);if(pageObj.isBootstrap()){pageObj.displayHalfPreparedMessage(respObj.message,true);}else{$("#remind_message").text(respObj.message);}}
if(respObj.html){if(pageObj.win){pageObj.win.set('bodyContent',respObj.html);}
$("[id=closeWindowRemind]").on("click",function(e){pageObj.openLoginPageOnPopUpClose();return false;}).show();$("[id=ProceedToLogin]").hide();$("[id=submitRemind]").hide();}});return false;});},openLoginPageOnPopUpClose:function(notRedirect,hostPage){var pageObj=this;this.openLoginPage('','',function(){pageObj.close();},notRedirect,hostPage);}});Runner.pages.DataPageWithSearch=Runner.extend(Runner.pages.RunnerPage,{shortTName:"",searchController:null,searchSavingEnabled:false,searchParamsLogger:null,nextDetailsTabId:0,constructor:function(cfg){Runner.pages.DataPageWithSearch.superclass.constructor.call(this,cfg);this.shortTName=Runner.pages.PageSettings.getShortTName(this.tName);if(this.isBootstrap()){Runner.setZindexMax($(".sidebar").css("z-index"));}},init:function(){Runner.pages.DataPageWithSearch.superclass.init.call(this);},initForGrid:function(){Runner.pages.DataPageWithSearch.superclass.initForGrid.call(this);this.initPagination();},largeTextOpenerDelegate:function(e){var self=this,$target=$(e.target),bsUsed=Runner.isBootstrap(),query=$target.data("query"),afterCreateTextWin,afterCloseTextWin;if(!$target.is("a")||!query){return;}
if(!bsUsed){afterCreateTextWin=function(win){Runner.pages.PageManager.correctYUIWindowSize(win._obj,true);};}else{afterCreateTextWin=function(win){$("[data-role='closeText']",win.footer()).on("click",function(e){win.destroy();});};}
afterCloseTextWin=function(win){var $content=win.getContentNode(),newWinWidth=bsUsed?$content.width():$content.width()-18,newWinHeight=$content.height();set_cookie('textWinWidth',newWinWidth,'',Runner.getCookieRoot());set_cookie('textWinHeight',newWinHeight,'',Runner.getCookieRoot());};Runner.runnerAJAX(query,{},function(respObj){var args={bodyContent:respObj.success?respObj.textCont:respObj.error||"Server error",width:parseInt(get_cookie("textWinWidth"),10)||550,height:parseInt(get_cookie("textWinHeight"),10)||400};if(bsUsed){if(args.height>200){args.footerContent='<a href="#" data-role="closeText" class="btn btn-default">'+Runner.lang.constants.CLOSE+'</a>';}
Runner.pages.PageManager.createBSWin.call(self,args,false,afterCreateTextWin,afterCloseTextWin);}else{Runner.pages.PageManager.createFlyWin.call(self,args,false,afterCreateTextWin,afterCloseTextWin);}});Runner.Event.prototype.stopEvent(e);},getSearchControllerConfig:function(){return{id:this.pageId,tName:this.tName,pageType:this.pageType,searchTableName:this.tName,shortTName:this.shortTName,usedSrch:this.controlsMap.search.usedSrch,fNamesArr:this.controlsMap.search.allSearchFields,searchFieldsLabels:this.controlsMap.search.allSearchFieldsLabels,panelSearchFields:this.controlsMap.search.panelSearchFields,isSearchPanelInflexible:this.controlsMap.search.inflexSearchPanel,isSearchRequired:this.controlsMap.search.isSearchRequired,requiredSearchFields:this.controlsMap.search.requiredSearchFields,useSuggest:Runner.pages.PageSettings.getTableData(this.tName,"ajaxSuggest"),filterContolsData:this.controlsMap.filters?this.controlsMap.filters.controls:[],searchPanelRunByUserApi:this.controlsMap.search.searchPanelRunByUserApi};},initSearch:function(){if(!this.controlsMap.search){return false;}
this.searchController=new Runner.search.SearchController(this.getSearchControllerConfig());this.searchController.init(this.controlsMap.search.searchBlocks);this.searchSavingEnabled=Runner.pages.PageSettings.getTableData(this.tName,"searchSaving");if(!this.searchSavingEnabled){return;}
this.searchParamsLogger=new Runner.search.SearchParamsLogger({id:this.pageId,tName:this.tName,pageType:this.pageType,savedSearches:this.controlsMap.search.savedSearches||{},}).init(this.searchController);},initPagination:function(){var pageObj=this;$("[data-function=pagination"+this.id+"]").each(function(index,elem){$(elem).bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),reloadParams;if(!$target.is("a")){return false;}
reloadParams=pageObj.getExtraPageReloadParams();pageObj.reload({goto:$target.attr("pageNum")},reloadParams);});});},getExtraPageReloadParams:Runner.emptyFn,initAdvSearch:function(){var pageObj=this;$("[id=advButton"+this.pageId+"]").bind("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"search");});},initPrintFrLink:Runner.emptyFn,initPrintAll:Runner.emptyFn,initExcelLink:function(){var pageObj=this;$("[id=export_to_excel"+this.pageId+"]").bind("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"print","all=1&format=excel");});},initWordLink:function(){var pageObj=this;$("[id=export_to_word"+this.pageId+"]").bind("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"print","all=1&format=word");});},initPDFLink:function(){var pageObj=this;$("[id=export_to_pdf"+this.pageId+"]").bind("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"print","all=1&exportPdf=1");});},initPopupLinks:function(){if(Runner.isMobile||typeof this.dpObjs==="undefined"){return;}
var pageObj=this,detTables=Runner.pages.PageSettings.getTableData(pageObj.tName,"detailTables"),masterMouseOver=function(){var linkId=$(this).attr('id'),shortTName,rowId,masterKeys={},page,tName,row,requestUrl,detTName;shortTName=linkId.match(/^master_(.*)_[\d]+$/);if(!shortTName){shortTName=linkId.match(/^(.*)_preview[\d]+$/);rowId=linkId.match(/([\d]+)$/);}else{rowId=linkId.match(/_([^_]+)$/);}
shortTName=shortTName[1];rowId=rowId[1];for(detTName in detTables){if(Runner.pages.PageSettings.getShortTName(detTName)==shortTName){page=detTables[detTName].pageType;tName=detTName;break;}}
if(!tName){return;}
$.each(pageObj.dpObjs[tName].rows,function(index,tRow){if(tRow.id==rowId){row=tRow;return false;}});if(!row){return;}
$.each(row.masterKeys,function(mKey,mKeyValue){masterKeys[mKey]=mKeyValue||"";});page=page===Runner.pages.constants.PAGE_LIST?'detailspreview':page;requestUrl=Runner.getPageUrl(shortTName,page),pageObj.dpObjs[tName].showPopup(this,requestUrl,pageObj.tName,masterKeys[tName]);};$.each(this.dpObjs,function(tName,tObj){if(detTables[tName].listShowType!=Runner.pages.constants.DP_POPUP){return;}
var $detailLink=$("[id^='master_"+tObj.shortTName+"'],a[id^='"+tObj.shortTName+"_preview']",pageObj.getBrickGridElem());if(Runner.isDirRTL()){$detailLink.attr("dir",$("html").attr("dir"));}
$detailLink.unbind('mouseover').unbind('mouseout').bind({mouseover:masterMouseOver,mouseout:$.proxy(tObj.hidePopup,tObj)});});},initDetails:function(){var tName,detTables=Runner.pages.PageSettings.getTableData(this.tName,"detailTables"),linksOnList=Runner.pages.PageSettings.getTableData(this.tName,"detailsLinksOnList");if(linksOnList==Runner.pages.constants.DL_NONE){return;}
this.dpObjs={};for(tName in detTables){this.dpObjs[tName]=this.createDetailsObject(tName,detTables[tName],this.nextDetailsTabId++);}},createDetailsObject:function(table,dSettings,tabIdx,listShowType){var dpParams={id:this.id,masterTName:this.tName,oldLayout:this.oldLayout,parId:this.id,linksType:Runner.pages.PageSettings.getTableData(this.tName,"detailsLinksOnList"),pageContext:this.pageCont},dpObj;if(typeof listShowType=='undefined'){listShowType=dSettings.listShowType;}
dpParams.tName=table;dpParams.pageType=dSettings.pageType;dpParams.hideChild=dSettings.hideChild;dpParams.dispChildCount=!!parseInt(dSettings.dispChildCount,10);if(listShowType==Runner.pages.constants.DP_NONE){return new Runner.util.details.ListWithoutPreview(dpParams);}
dpParams.proceedLink=dSettings.proceedLink;if(this.controlsMap.gridRows){dpParams.rows=this.controlsMap.gridRows.slice(0);}
if(listShowType==Runner.pages.constants.DP_POPUP){dpObj=new Runner.util.details.DPPopUp(dpParams);dpObj.init();return dpObj;}
dpParams.tabSettings={tabLabel:dSettings.label,tabIndex:tabIdx};dpObj=new Runner.util.details.ListTabbedPreview(dpParams);dpObj.init();if(typeof this.onBeforeShowDetails==="function"){dpObj.on('beforeShowDetails',this.onBeforeShowDetails,this);}
if(typeof this.onAfterShowDetails==="function"){dpObj.on('afterShowDetails',this.onAfterShowDetails,this);}
return dpObj;},onBeforeShowDetails:function(dpObj,row){var shownDPObj,tName;for(tName in this.dpObjs){if(this.dpObjs[tName].getRowByInd(row.rowInd).isShown){shownDPObj=this.dpObjs[tName];break;}}
if(!shownDPObj){dpObj.closeDetailsByInd(row.rowInd);return;}},largeTextOpenerDelegateMobile:function(e){var pageObj=this,$target=$(e.target),query=$target.data("query");if(!$target.is("a")||!query){return false;}
Runner.Event.prototype.stopEvent(e);Runner.runnerAJAX(query,{id:this.id},function(respObj){var brickContent='<div class="rnr-fulltext-content">'
+(respObj.success?respObj.textCont:(respObj.error||"Server error"))
+'</div>';pageObj.replaceBrickContentHTMLWith("fulltext_mobile",brickContent);pageObj.hideBricks(pageObj.bricksArr);pageObj.showBricks(["fulltext_mobile","backbutton"]);});},initLargeTextBackButtonMobileDP:function(){var pageObj=this;$("#backbutton",this.pageCont).unbind("click").bind("click",function(e){pageObj.hideBricks(pageObj.bricksArr);pageObj.showBricks(pageObj.bricksArrList);});},initRecordBlock:function(){var submitUrl=Runner.pages.getUrl(this.tName,this.pageType);$("[id='recordspp"+this.id+"']").on("change",function(e){window.location.href=submitUrl+'?pagesize='+this.options[this.selectedIndex].value;});}});Runner.pages.ListPageCommon=Runner.extend(Runner.pages.DataPageWithSearch,{gridElem:null,isScrollGridBody:false,recsPerRowList:false,heightScrollGridBody:0,constructor:function(cfg){Runner.pages.ListPageCommon.superclass.constructor.call(this,cfg);this.isScrollGridBody=this.isScrollingGrid();this.permis=Runner.pages.PageSettings.getTableData(this.tName,"permissions");this.recsPerRowList=Runner.pages.PageSettings.getTableData(this.tName,"recsPerRowList");},init:function(){this.initGridElem();Runner.pages.ListPageCommon.superclass.init.call(this);this.initResize();this.initSelectAll();this.listenHashTags();this.setUrlParams();},setUrlParams:function(){if(this.dashElement===undefined&&this.pageData.urlParams&&!Runner.Hash.oldbrowser()){Runner.Hash.set(this.pageData.urlParams,true);}},listenHashTags:function(){if(!this.ajaxBaseParams){return;}
var hash=location.hash.replace('#',''),pageObj=this;Runner.Hash.changeUrlListener(function(newUrl){pageObj.preparePageForReloading();Runner.runnerAJAX(newUrl,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj,true);});});if(!hash){return;}
this.preparePageForReloading();Runner.runnerAJAX(Runner.pages.getUrl(this.tName,this.pageType)+"?"+hash,this.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj)});},initForGrid:function(){Runner.pages.ListPageCommon.superclass.initForGrid.call(this)
this.initHeaderCheckBox();this.initInline();this.initMaps();},initGridElem:function(){var bindedGridClickHn=$.proxy(this.gridClickHn,this);this.gridElem=this.getBrickGridElem();$(this.gridElem).unbind("click").bind("click",bindedGridClickHn);$(this.getBrickElem(this.isBootstrap()?'masterlistgrid':'masterinfo')).unbind("click").bind("click",bindedGridClickHn);},initForTabs:function(){this.initControls();if(!this.useResize){this.initViewControls();}
this.initLookups();},getRecsId:function(){if(this.inlineEdit){return this.inlineEdit.getRecsId();}
var recsId={};$('.rnr-row:not(.gridRowAdd)',this.gridElem).not(this.inDetailPreviewContainer).each(function(i,row){var attrId=$(row).attr('id'),lastInd=attrId.lastIndexOf('w');recsId[++i]=parseInt(attrId.substr(lastInd+1));});return recsId;},gridClickHn:function(e){this.largeTextOpenerDelegate(e);},getResizableColumnsData:function(){if(!this.bsResizeInitialized){return null;}
var data={gridWidth:$(this.gridElem).width(),thWidths:{}}
$("th",this.gridElem).each(function(i,th){var $th=$(th),fName=$th.data("field");if(fName){data.thWidths[fName]=$th.width();}});return data;},getResizeColumnsLoggerParams:function(){return{saveParam:Runner.pages.constants.CRESIZE_PARAMS_TYPE,data:JSON.stringify(this.getResizableColumnsData())};},getServerResizableColumnsData:function(){return this.pageData.resizableColumnsData;},initResize:function(){if(Runner.isMobile||!this.useResize){return;}
if(Runner.smallScreen){this.initForGrid();return;}
var pageObj=this,$grid=$(this.gridElem),pageUrl=Runner.pages.getUrl(this.tName,this.pageType),disabledColumns,resizableColumnsData,delta=0;if(this.isBootstrap()){$grid.colResizable({disable:true});if(this.recsPerRowList<=1){resizableColumnsData=this.resizableColumnsData||this.getServerResizableColumnsData();}
disabledColumns=[];$grid.css('width','auto');$("th",this.gridElem).each(function(i,th){var $th=$(th),fName=$th.data("field");if(!fName){disabledColumns.push(i);}else if(resizableColumnsData){$th.width(resizableColumnsData.thWidths[fName]);if(parseInt(resizableColumnsData.thWidths[fName],10)>$th.width()){delta=delta+parseInt(resizableColumnsData.thWidths[fName],10)-$th.width();}}});if(resizableColumnsData){if($grid.width()<resizableColumnsData.gridWidth){$grid.width(resizableColumnsData.gridWidth);}else{$grid.width($grid.width()+delta);}}else{$grid.css('width',$grid.width()+'px');}
$grid.colResizable({resizeMode:'overflow',disabledColumns:disabledColumns,onResize:function(){if(pageObj.recsPerRowList<=1){$.post(pageUrl,pageObj.getResizeColumnsLoggerParams());}}});this.bsResizeInitialized=true;this.initForGrid();this.initViewControls();return;}
this.Y&&this.Y.use('cookie','json-parse','json-stringify','datatable-base','resize',function(Y){pageObj.resizeGrid=pageObj.resizeGrid||new Runner.resize.Grid({tName:pageObj.tName,pageId:pageObj.pageId,oldLayout:pageObj.oldLayout,layoutName:pageObj.layoutName});pageObj.resizeGrid.init();pageObj.initGridElem();pageObj.initForGrid();});},onReoderColumnsStop:function(){if(!this.bsResizeInitialized){return;}
var $grid=$(this.gridElem),pageUrl=Runner.pages.getUrl(this.tName,this.pageType),disabledColumns=[],pageObj=this;$grid.colResizable({disable:true});$("th",this.gridElem).each(function(i,th){if(!$(th).data("field")){disabledColumns.push(i);}});$grid.colResizable({resizeMode:'overflow',disabledColumns:disabledColumns,onResize:function(){$.post(pageUrl,pageObj.getResizeColumnsLoggerParams());}});},initHeaderCheckBox:function(){var pageObj=this;$('.chooseAll'+pageObj.id).parent().unbind("click").bind("click",function(e){var $chooseAll=$('.chooseAll'+pageObj.id,this),checked=$chooseAll.prop("checked");if(!$chooseAll.is(e.target)){checked=!checked;}
$('input[type=checkbox][id^=check'+pageObj.id+'_]').prop("checked",checked);$('input[type=checkbox][id^=chooseAll_'+pageObj.id+']').prop("checked",checked);pageObj.onAfterChangeCheckboxsState();});$('input[type=checkbox][id^=check'+pageObj.id+'_]').unbind("click").bind("click",function(e){pageObj.onAfterChangeCheckboxsState();});},onAfterChangeCheckboxsState:function(){var pageObj=this,$selBoxes=this.getSelBoxes(this.id),$ownedSelBoxes=this.getOwnedSelBoxes(true),$printSelection=$("#printSelection"+this.id),$printPage=$("#printPage"+this.id),$labelPrintSelection=this.isBootstrap()?$printSelection.parent():$printSelection.parent().children("label"),$exportSelectedButton=$("[id=export_selected"+this.id+"]"),$buttons;$('.chooseAll'+this.id).prop("checked",!($selBoxes.length<$('input[type=checkbox][id^=check'+this.id+'_]').length));if(this.isBootstrap()){$buttons=$("[id=delete_selected"+this.id+"]").add("[id=edit_selected"+this.id+"]").add("[id=update_selected"+this.id+"]");if(!$ownedSelBoxes.length){$buttons.each(function(){if($(this).parent().hasClass("massButton"+pageObj.id)){$(this).parent().addClass("disabled")}else{$(this).attr('disabled',"");}});}else{$buttons.each(function(){if($(this).parent().hasClass("massButton"+pageObj.id)){$(this).parent().removeClass('disabled');}else{$(this).removeAttr('disabled',"");}});}}
if($selBoxes.length){$printSelection.prop("disabled",false).prop("checked",true);$labelPrintSelection.css("color","inherit");if(this.isBootstrap()){$exportSelectedButton.parent().removeClass("disabled");}}else{$printSelection.prop("checked",false).prop("disabled",true);$printPage.prop("checked",true);$labelPrintSelection.css("color","gray");if(this.isBootstrap()){$exportSelectedButton.parent().addClass("disabled");}}},getSelBoxes:function(id){return $("input[type='checkbox'][id^='check"+id+"_']:checked");},initSelectAll:function(){var pageObj=this,selectAll=$('#select_all'+this.id),useCaption;if(!selectAll.length){return false;}
useCaption=Runner.pages.PageSettings.getTableData(this.tName,"listGridLayout")!==Runner.pages.constants.HORIZONTAL_LAYOUT;selectAll[0].checkAllStatus=false;selectAll.bind("click",function(e){this.checkAllStatus=!this.checkAllStatus;$('input[type=checkbox][id^=check'+pageObj.id+'_]').prop("checked",this.checkAllStatus);if(useCaption){$(this).html(this.checkAllStatus?Runner.lang.constants.UNSELECT_ALL:Runner.lang.constants.SELECT_ALL);}
pageObj.onAfterChangeCheckboxsState();return false;});},initMaps:function(){if(!this.hasMaps()){return;}
Runner.globalGmapLoader.onLoad(function(){var cfg=this.controlsMap.gMaps;if(this.mapManager){this.mapManager.reinit(cfg.mapsData,cfg.fieldMapsIds);return;}
this.mapManager=new Runner.controls.MapManager(cfg);this.mapManager.init();if(this.inlineEdit){this.inlineEdit.on('cancel',this.mapManager.updateMapsOnEditCancel,this.mapManager);this.inlineEdit.on('afterSubmit',this.mapManager.updateMapsOnAfterEditSubmit,this.mapManager);}
if(this.inlineAdd){this.inlineAdd.on('afterSubmit',this.mapManager.updateMapsOnAfterAddSubmit,this.mapManager);}
if(this.isPageInTab()){Runner.pages.PageManager.onTabShown(this,this.mapManager.updateLittleMaps.bind(this.mapManager));}},this);},initNewRowButtons:function(row){var i,newId,$buttonElem,button;for(i=0;i<this.buttonNames.length;i++){$buttonElem=$("#"+this.buttonNames[i],row.row);if(!$buttonElem.length){continue;}
newId=this.buttonNames[i]+"_"+Runner.genId();$buttonElem.attr('id',newId);button=new Runner.form.Button({id:newId,btnName:this.buttonNames[i]});button.init({args:[this,this.proxy,this.id,true,row]});}},afterInitInlineAdd:function(row){this.initNewRowButtons(row);},preparePageForReloading:function(gridElem){if(this.inlineEdit||this.inlineAdd){(this.inlineEdit||this.inlineAdd).cancelAll();}
if(!this.silentReloading){Runner.runLoading("",gridElem||this.gridElem,this.openMode===Runner.pages.constants.OPENMODE_POPUP,this.win);}},afterInit:function(pageObj,proxy,pageid){this.heightScrollGridBody=proxy['gridHeight'];this.initScrollGridBody();},isScrollingGrid:function(){if(Runner.pages.PageSettings.getTableData(this.tName,"isUseResize")){return false;}
return Runner.pages.PageSettings.getTableData(this.tName,"scrollGridBody");},initBSScrollGridBody:function(){if(!this.isScrollGridBody||!this.isBootstrap()||this.bsScrollBodyInited||$(window).width()<768){return;}
var pageObj=this,maxExtraHeight=80,scrollElementWidth=16,viewPortHeight=$(window).height(),gridHeight=this.gridElem.height(),gridPosition=this.gridElem.position(),$pagination=$("[data-container=pagination]",this.pageCont).not(this.inDetailPreviewContainer),fullGridHeight=gridHeight+gridPosition.top+$pagination.height(),gridWidth=this.gridElem.width(),scrollGridHeight=this.heightScrollGridBody,$thead=$('thead',this.gridElem).not(this.inDetailPreviewContainer),$header=$('thead tr',this.gridElem).not(this.inDetailPreviewContainer),$tbody=$('tbody',this.gridElem).not(this.inDetailPreviewContainer),$tfoot=$('tfoot',this.gridElem).not(this.inDetailPreviewContainer),$bottomRow=$('.'+'rnr-'+'bottomrow',this.gridElem).not(this.inDetailPreviewContainer),theadHeight,bottomHeight,extraDocumentHeight;if(!$tbody.data("resizeHandlerSet")){$(window).resize(function(){pageObj.adjustBSGridHeight();});$tbody.data("resizeHandlerSet",true);}
if(fullGridHeight<viewPortHeight){return;}
$('th',$thead).css({'border-bottom-width':'1px','border-top-width':'1px','border-top-style':'solid','border-top-color':this.gridElem.css('border-top-color'),});this.gridElem.css({position:'relative',border:'none'});this.setEdgeRowsWidthStyles($header,$(null),$bottomRow,true);theadHeight=$header.innerHeight()||32;bottomHeight=$bottomRow.innerHeight();if(!scrollGridHeight){scrollGridHeight=viewPortHeight-gridPosition.top-$pagination.height();extraDocumentHeight=$(document).height()-gridPosition.top-gridHeight;scrollGridHeight=extraDocumentHeight<maxExtraHeight?scrollGridHeight-extraDocumentHeight:scrollGridHeight;scrollGridHeight=scrollGridHeight<0?scrollGridHeight*(-1):scrollGridHeight;if(scrollGridHeight-bottomHeight-theadHeight<32){scrollGridHeight+=theadHeight+32;}}
$thead.css({position:"absolute",height:$thead.height()+'px',top:0+'px','z-index':1,'background-color':"#FFFFFF"});$tbody.css({height:scrollGridHeight+'px',width:gridWidth+scrollElementWidth,position:"absolute","overflow-y":"scroll",top:0+'px','padding-top':$thead.height()+'px','padding-bottom':$tfoot.height()+'px','overflow-x':'hidden'});$tfoot.css({position:"absolute",height:$tfoot.height()+'px',top:scrollGridHeight-$tfoot.height()+'px','z-index':1,'background-color':"#FFFFFF"});this.gridElem.height(scrollGridHeight);this.setEdgeRowsWidthStyles($header,$(null),$bottomRow);$("tbody tr:not(.gridRowAdd):first td",this.gridElem).not(this.inDetailPreviewContainer).each(function(i,el){ResizeSensor(el,function(){pageObj.recalculationBSGridSizeByCell(i,el);});});this.bsScrollBodyInited=true;},adjustBSGridHeight:function(){if(!this.isScrollGridBody||!this.isBootstrap()){return;}
if(!this.bsScrollBodyInited){this.initBSScrollGridBody();return;}
var viewPortHeight=$(window).height(),$tbody=$('tbody',this.gridElem).not(this.inDetailPreviewContainer),tbodyOffset=$tbody.offset(),$pagination=$("[data-container=pagination]",this.pageCont).not(this.inDetailPreviewContainer),fullGridHeight=$tbody.height()+tbodyOffset.top+$pagination.height(),$thead=$('thead',this.gridElem).not(this.inDetailPreviewContainer),$tfoot=$('tfoot',this.gridElem).not(this.inDetailPreviewContainer),theadHeight,bottomHeight,scrollGridHeight,contentHeight;if(fullGridHeight<viewPortHeight){contentHeight=$tbody.get(0).scrollHeight;}
scrollGridHeight=viewPortHeight-tbodyOffset.top-$pagination.height()-$thead.height()-$tfoot.height();if(scrollGridHeight<32){scrollGridHeight=32;}
if(contentHeight&&contentHeight<scrollGridHeight+$thead.height()+$tfoot.height()){scrollGridHeight=contentHeight-$thead.height()-$tfoot.height();}
$tbody.height(scrollGridHeight);$tfoot.css("top",$tbody.innerHeight()-$tfoot.height()+'px');},recalculationBSGridSizeByCell:function(ind,el){if(!this.isBootstrap()){return;}
var scrollElementWidth=16,$tbody=$('tbody',this.gridElem).not(this.inDetailPreviewContainer),$thead=$('thead',this.gridElem).not(this.inDetailPreviewContainer),$tfoot=$('tfoot',this.gridElem).not(this.inDetailPreviewContainer),$header=$('thead tr',this.gridElem).not(this.inDetailPreviewContainer),$bottomRow=$('.rnr-bottomrow',this.gridElem).not(this.inDetailPreviewContainer),$gridCell=$(el),$headerCell=$header.children('th').eq(ind),$footerCell=$bottomRow.children('td').eq(ind),beforeGWidth=$gridCell.data("beforeGWidth"),gWidth,fWidth,hWidth,mWidth,oldTbodyWidth=$tbody.data("oldTbodyWidth")||$tbody.width();gWidth=$gridCell.width();fWidth=$footerCell.width();hWidth=$headerCell.width();mWidth=Math.max(gWidth,fWidth,hWidth);if(beforeGWidth!==undefined&&mWidth<beforeGWidth){return;}
$gridCell.width(mWidth).data("beforeGWidth",mWidth);$footerCell.width(mWidth);$headerCell.width(mWidth);if(beforeGWidth!==undefined){$tbody.width(oldTbodyWidth+mWidth-beforeGWidth);}
$tbody.data("oldTbodyWidth",$tbody.width());$thead.width($tbody.width()-scrollElementWidth);$tfoot.width($tbody.width()-scrollElementWidth);},initScrollGridBody:function(){if(!this.isScrollGridBody){return;}
if(Runner.isBootstrap()){this.initBSScrollGridBody();return;}
var pageObj=this,maxExtraHeight=80,scrollElementWidth=15,viewPortHeight=$(window).height(),gridHeight=this.gridElem.height(),gridPosition=this.gridElem.position(),fullGridHeight=gridHeight+gridPosition.top,extraDocumentHeight,baseClassPref,$divScrollWrappper,$divSrollInner,$header,$footer,$bottomRow,scrollGridHeight,wrapperHeight,theadHeight,footerHeight,bottomHeight;if(fullGridHeight<viewPortHeight){this.isScrollGridBody=false;return;}
scrollGridHeight=this.heightScrollGridBody;$header=$('thead tr',this.gridElem);$footer=$('.footer',this.gridElem);baseClassPref=this.oldLayout?'runner-':'rnr-';$bottomRow=$('.'+baseClassPref+'bottomrow',this.gridElem);this.gridElem.css('width','auto');this.setEdgeRowsWidthStyles($header,$footer,$bottomRow);theadHeight=$header.innerHeight()||32;footerHeight=$footer.innerHeight();bottomHeight=$bottomRow.innerHeight();this.gridElem.data('theadheight',theadHeight);if(!scrollGridHeight){scrollGridHeight=viewPortHeight-gridPosition.top;extraDocumentHeight=$(document).height()-gridPosition.top-gridHeight;scrollGridHeight=extraDocumentHeight<maxExtraHeight?scrollGridHeight-extraDocumentHeight:scrollGridHeight;scrollGridHeight=scrollGridHeight<0?scrollGridHeight*(-1):scrollGridHeight;if(scrollGridHeight-footerHeight-bottomHeight-theadHeight<32){scrollGridHeight+=theadHeight+32;}}
scrollGridHeight=scrollGridHeight-footerHeight-bottomHeight-theadHeight;wrapperHeight=scrollGridHeight+bottomHeight+footerHeight;$divScrollWrappper=$('<div></div>').addClass(baseClassPref+'scrollgrid-wrap').css({'position':'relative','height':wrapperHeight+'px','padding':theadHeight+'px 0 0','margin-bottom':this.gridElem.css('margin-bottom')});$divSrollInner=$('<div></div>').addClass(baseClassPref+'scrollgrid-inner').css({'height':scrollGridHeight+'px','overflow-y':'auto','overflow-x':'hidden','width':this.gridElem.outerWidth(true)+scrollElementWidth+'px'}).scroll(function(){$('div.shiny_box').hide();}).appendTo($divScrollWrappper);this.gridElem.closest('.'+baseClassPref+'s-grid').not('.not-container').before($divScrollWrappper).appendTo($divSrollInner);this.setAbsolutePositionForHeaderAndFooter(true,$header,$footer,$bottomRow,scrollElementWidth,scrollGridHeight,theadHeight,footerHeight);this.addScrollElemWidthToLastCells(scrollElementWidth,$header,$footer,$bottomRow);},setAbsolutePositionForHeaderAndFooter:function(setOffset,$header,$footer,$bottomRow,scrollElementWidth,gridHeight,theadHeight,footerHeight){var newWidth=this.gridElem.width()+scrollElementWidth;$header.css('position','absolute').width(newWidth);$footer.css('position','absolute').width(newWidth);$bottomRow.css('position','absolute').width(newWidth);if(setOffset){$header.css('top','0px');$footer.css('top',gridHeight+theadHeight+'px');$bottomRow.css('top',gridHeight+theadHeight+footerHeight+'px');}},addScrollElemWidthToLastCells:function(scrollElementWidth,$header,$footer,$bottomRow){if(this.oldLayout){return;}
var $thHeader=$('th:last',$header),$thFooter=$('td:last',$footer),$thBottom=$('td:last',$bottomRow);$thHeader.css('width',$thHeader.width()+scrollElementWidth+'px');$thFooter.css('width',$thFooter.width()+scrollElementWidth+'px');$thBottom.css('width',$thBottom.width()+scrollElementWidth+'px');},setEdgeRowsWidthStyles:function($header,$footer,$bottomRow,first){var bsUsed=Runner.isBootstrap(),cellsWidths=[],baseClassPref=this.oldLayout?'runner-':'rnr-',cellsSelector=this.oldLayout?'.'+baseClassPref+'cc':'th, td',rowClass=bsUsed?'bs-gridrow':baseClassPref+'row',$gridRow=$('.'+rowClass+':not(.gridRowAdd):first',this.gridElem).not(this.inDetailPreviewContainer),$gridRowCells=$gridRow.children(cellsSelector);if(bsUsed){$gridRowCells.each(function(ind,cell){var $cell=$(cell);cellsWidths.push($cell.width());$cell.width($cell.width());});if(first){return;}
$header.children(cellsSelector).each(function(ind,cell){var $cell=$(cell);$cell.width(cellsWidths[ind]);});$bottomRow.children(cellsSelector).each(function(ind,cell){var $cell=$(cell);$cell.width(cellsWidths[ind]);});return;}
$gridRowCells.each(function(ind,cell){var $cell=$(cell);if(bsUsed){$cell.css('min-width',$cell.innerWidth()+'px');}else{$cell.css('min-width',$cell.width()+'px');}});$gridRowCells.each(function(ind,cell){var $cell=$(cell);cellsWidths.push(bsUsed?$cell.innerWidth():$cell.outerWidth(true));});this.setOuterElementCellsWidthStyles(cellsSelector,$header,cellsWidths);this.setOuterElementCellsWidthStyles(cellsSelector,$bottomRow,cellsWidths);this.setOuterElementCellsWidthStyles(cellsSelector,$footer,cellsWidths);},setOuterElementCellsWidthStyles:function(cellsSelector,$element,cellsWidths){var bsUsed=Runner.isBootstrap();$element.children(cellsSelector).each(function(ind,cell){var $cell=$(cell),width=cellsWidths[ind],paddings;if(!bsUsed){paddings=$cell.outerWidth(true)-$cell.width(),width=width-paddings;}
$cell.css('width',width+'px');});},setEdgeRowWidthAuto:function(){var baseClassPref=this.oldLayout?'runner-':'rnr-',cellsSelector=this.oldLayout?'.'+baseClassPref+'cc':'th, td',rowClass=baseClassPref+'row',$edgeRows;$edgeRows=$('.'+baseClassPref+'toprow, .'+rowClass+':not(.gridRowAdd):first, .footer, .'+baseClassPref+'bottomrow',this.gridElem).not(this.inDetailPreviewContainer).css('position','static');$edgeRows.children(cellsSelector).css('min-width','auto').css('width','auto');},inDetailPreviewContainer:function(){return $(this).closest('td.dpinline').length;},recalculationGridSize:function(){if(Runner.isBootstrap()){return;}
if(!this.isScrollGridBody||!Runner.pages.PageSettings.getTableData(this.tName,'showRows')){return;}
var pageObj=this,scrollElementWidth=16,baseClassPref=this.oldLayout?'runner-':'rnr-',$divScrollWrappper=this.gridElem.closest('.'+baseClassPref+'scrollgrid-wrap'),$divSrollInner=this.gridElem.closest('.'+baseClassPref+'scrollgrid-inner'),$header=$('.'+baseClassPref+'toprow',this.gridElem).not(this.inDetailPreviewContainer),$footer=$('.footer',this.gridElem).not(this.inDetailPreviewContainer),$bottomRow=$('.'+baseClassPref+'bottomrow',this.gridElem).not(this.inDetailPreviewContainer),scrollGridWidth=$divSrollInner.width(),headerTh=$('th:first',$header),theadHeight=headerTh.get(0).offsetHeight||32;if(Math.abs($header.width()-$("tbody tr:not(.gridRowAdd):first",this.gridElem).width())==scrollElementWidth){return;}
if(!this.oldLayout){$divSrollInner.width(scrollGridWidth-scrollElementWidth);}
this.setEdgeRowWidthAuto();this.setEdgeRowsWidthStyles($header,$footer,$bottomRow);if(this.gridElem.data('theadheight')!==theadHeight){this.recalculateGridHeight($divSrollInner,$divScrollWrappper,$header,$footer,$bottomRow,theadHeight);this.gridElem.data('theadheight',theadHeight);}else{this.setAbsolutePositionForHeaderAndFooter(false,$header,$footer,$bottomRow,scrollElementWidth);}
setTimeout(function(){pageObj.adjustScrollableGridContainer(scrollElementWidth,$divSrollInner);pageObj.addScrollElemWidthToLastCells(scrollElementWidth,$header,$footer,$bottomRow);},0);$divSrollInner.css('overflow-y','auto');},recalculateGridHeight:function($divSrollInner,$divScrollWrappper,$header,$footer,$bottomRow,theadHeight){var height=$divScrollWrappper.height(),footerHeight,bottomHeight;$divSrollInner.css({'overflow-y':'hidden','height':'auto'});$divScrollWrappper.css('height','auto');footerHeight=$footer.innerHeight();bottomHeight=$bottomRow.innerHeight();$divScrollWrappper.css({'height':height,'padding':theadHeight+'px 0 0'});height=height-bottomHeight-footerHeight;$divSrollInner.css('height',height);this.setAbsolutePositionForHeaderAndFooter(true,$header,$footer,$bottomRow,16,height,theadHeight,footerHeight);},adjustScrollableGridContainer:function(scrollElementWidth,$container){$container.width(this.gridElem.width()+scrollElementWidth);},getEditLinkHandler:function(row,method){var pageObj=this;if(method=='popup'){return function(){pageObj.hideBrick('message');pageParams=Runner.pages.EditPage.prototype.getOpenPageParams.call(pageObj,row.keys,row.id,"",pageObj.inlineEdit,Runner.emptyFn);Runner.pages.PageManager.openPage(pageParams);return false;};}
if(method=='new'){return function(){window.open(Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_EDIT,row.keys,'editid'),'_blank');}}
return function(){location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_EDIT,row.keys,'editid');}},getInlineEditObj:function(){if(!this.inlineEdit){this.inlineEdit=new Runner.util.inlineEditing.InlineEdit({id:this.pageId,tName:this.tName,fNames:this.listFields||[],rows:this.controlsMap&&this.controlsMap.gridRows||[]});}
return this.inlineEdit;},getViewLinkHandler:function(row,method){var pageObj=this;if(method=='popup'){return function(){pageObj.hideBrick('message');pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(pageObj,row.keys,row.id,pageObj.getInlineEditObj(),Runner.emptyFn);Runner.pages.PageManager.openPage(pageParams);return false;};}
if(method=='new'){return function(){window.open(Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_VIEW,row.keys,'editid'),'_blank');}}
return function(){location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_VIEW,row.keys,'editid');}},getPrintLinkHandler:function(row,method){var pageObj=this;if(method=='popup'){return function(){pageObj.hideBrick('message');pageParams=Runner.pages.PrintPage.prototype.getOpenPageParams.call(pageObj,row.keys,row.id,pageObj.inlineEdit,Runner.emptyFn);Runner.pages.PageManager.openPage(pageParams);return false;};}
if(method=='new'){return function(){window.open(Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_PRINT,row.keys,'editid'),'_blank');}}
return function(){location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_PRINT,row.keys,'editid');}},getAddLinkHandler:function(row,method){var pageObj=this;if(method=='popup'){return function(){pageObj.hideBrick('message');pageParams=Runner.pages.AddPage.prototype.getOpenPageParams.call(pageObj,pageObj.id);Runner.pages.PageManager.openPage(pageParams);return false;};}
if(method=='new'){return function(){window.open(Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_ADD),'_blank');}}
return function(){location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_ADD);}},getDetailsLinkHandler:function(row,table,method){var pageObj=this,mKeys=[],key,link;for(key in row.masterKeys[table]){mKeys.push(row.masterKeys[table][key]);}
link=Runner.pages.getUrl(table,pageObj.dpObjs[table].pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(pageObj.tName);if(method=='new'){return function(){window.open(link,'_blank');}}
return function(){location.href=link;}},getUrlLinkHandler:function(url,method){var pageObj=this;if(method=='popup'){return function(){var params={url:url};Runner.displayPopup(params);return false;};}
if(method=='new'){return function(){window.open(url,'_blank');}}
return function(){location.href=url;}},getOwnedSelBoxes:function(notUncheckNotOwned){var pageObj=this,notUncheckNotOwned=notUncheckNotOwned||false,$selBoxes=this.getSelBoxes(this.id);return $selBoxes.filter(function(index){var $checkBox=$(this),boxId=$checkBox.attr('id'),rowId=boxId.substr(boxId.lastIndexOf('_')+1);if(!pageObj.getEditRows(rowId)){if(!notUncheckNotOwned){$checkBox.prop("checked",false);}
return false;}
return true;});}});Runner.pages.ListPageFly=Runner.extend(Runner.pages.ListPageCommon,{lookupCtrl:null,lookupBaseParams:null,constructor:function(cfg){Runner.pages.ListPageFly.superclass.constructor.call(this,cfg);this.useResize=false;this.listFields=Runner.pages.PageSettings.getTableData(this.tName,'listFields');this.bricksForReload=["grid","pagination","message","reorder_records","bsgrid_tabs"];this.lookupBaseParams=this.lookupCtrl.getLookupParams(this.pageId);},destructor:function(){Runner.pages.ListPageFly.superclass.destructor.call(this);this.pageCont=null;this.lookupCtrl.pageId=-1;},init:function(){var flyContainer;Runner.pages.ListPageFly.superclass.init.call(this);if(Runner.isMobile){flyContainer=this.getBrickObjs("flypanel_mobile")[0].elem;this.showBrickMobile("vmsearch2",flyContainer);this.showBrickMobile("cancelbutton_mobile",flyContainer);this.hideBricks(["bars_menu_icon"]);}
this.initLinks();this.initSorting();this.initSortByDropdown();if(this.isBootstrap()){$('[id=inlineAdd'+this.id+']').parents('.bs-hidden-xs').removeClass('bs-hidden-xs');}
this.fireEvent('afterInit',this,this.proxy,this.id);},initLinks:function(){this.lookupCtrl.setEnabled();this.initLink($("[type='lookupSelect"+this.pageId+"']"))},initLink:function($link){var pageObj=this;$link.on("click",function(e){var ind=$(this).data("ind");pageObj.close();pageObj.lookupCtrl.setValByInd(ind);pageObj.lookupCtrl.setFocus();pageObj.lookupCtrl.fireEvent("keyup");return false;});},initSearch:function(){this.searchController=new Runner.search.SearchController({id:this.pageId,tName:this.tName,fNamesArr:this.controlsMap.search.allSearchFields,shortTName:this.shortTName,usedSrch:this.controlsMap.search.usedSrch,panelSearchFields:this.controlsMap.search.panelSearchFields,ajaxSubmit:true,useSuggest:false,pageType:this.pageType,formBaseParams:this.lookupBaseParams});this.searchController.init(this.controlsMap.search.searchBlocks);if(!Runner.isMobile){this.searchController.srchForm.on("beforeSubmit",function(){this.preparePageForReloading(this.win?this.win.bodyNode.getDOMNode():null);},this);this.searchController.srchForm.on("submitFailed",function(){Runner.stopLoading(this.win?this.win.bodyNode.getDOMNode():null);},this);}
this.searchController.on("afterSearch",function(respObj,srchController,srchForm){if(!Runner.isMobile){Runner.stopLoading(this.win?this.win.bodyNode.getDOMNode():null);}
this.pageReloadHn(respObj);this.searchController.toggleShowAll(this.searchController.usedSrch);},this);},initInline:function(){if(!Runner.pages.PageSettings.getTableData(this.tName,"isInlineAdd")||!this.permis['add']){return;}
this.inlineAdd=new Runner.util.inlineEditing.InlineAdd(this.getInlineAddParams());this.inlineAdd.init();this.inlineAdd.on("beforeSetVals",function(row,fields){if(row.data[this.lookupCtrl.dispFieldAlias]){row.data[this.lookupCtrl.dispFieldAlias]='<a href="#" type="lookupSelect'+this.searchController.srchForm.baseParams.id+'">'
+row.data[this.lookupCtrl.dispFieldAlias]+'</a>';}else if(row.data[this.lookupCtrl.dispField]){row.data[this.lookupCtrl.dispField]='<a href="#" type="lookupSelect'+this.searchController.srchForm.baseParams.id+'">'
+row.data[this.lookupCtrl.dispField]+'</a>';}else{for(field in row.data){row.data[field]='<a href="#" type="lookupSelect'+this.searchController.srchForm.baseParams.id+'">'+row.data[field]+'</a>';break;}}},this);this.inlineAdd.on("afterSubmit",function(vals,fields,keys,rowId){var $link=$('tr[id="gridRow'+rowId+'"] a[type="lookupSelect'+this.pageId+'"]').eq(0),linkValue,newInd;linkValue=vals[this.lookupCtrl.linkField]===undefined?keys[this.lookupCtrl.linkField]:vals[this.lookupCtrl.linkField];newInd=this.lookupCtrl.addLookupVal(linkValue,vals[this.lookupCtrl.dispFieldAlias]||vals[this.lookupCtrl.dispField]);$link.data("ind",newInd);this.initLink($link);},this);this.inlineAdd.on("afterInit",function(pageObj,proxy,pageid,row){this.afterInitInlineAdd(row);},this);},getInlineAddParams:function(){var params={id:this.pageId,tName:this.tName,fNames:this.listFields,shortTName:this.shortTName,rows:this.controlsMap.gridRows,inlineEditObj:this.inlineEdit,isOldLayout:this.oldLayout,loadSettings:true,lookupParams:{forLookup:true,field:this.lookupCtrl.fieldName,table:this.lookupCtrl.shortTableName},lookupFieldInfo:{linkField:this.lookupCtrl.linkField,dispField:this.lookupCtrl.dispField,dispFieldAlias:this.lookupCtrl.dispFieldAlias}};if(!!this.lookupCtrl.parentCtrls.length){params.lookupParams.parentsExist=true;params.lookupParams.parentCtrlsData=JSON.stringify(this.lookupCtrl.getParentControlsData());}
return params;},initGridTabs:function(){var pageObj=this;$(pageObj.pageCont).on('click','[data-brick=bsgrid_tabs] li > a[data-pageid='+this.id+']',function(e){var url=$(this).attr('href'),tabs=$(this).parents('ul').find('li'),$currentTab=$(this).parent();$.each(tabs,function(e){$(this).removeClass('active');});$currentTab.addClass('active');pageObj.preparePageForReloading();Runner.runnerAJAX(url,pageObj.lookupBaseParams,function(respObj){pageObj.pageReloadHn(respObj);});return false;});},initSorting:function(){var pageObj=this,i;for(i=0;i<this.listFields.length;i++){$('[id="order_'+Runner.goodFieldName(this.listFields[i])+'_'+this.pageId+'"]').on("click",function(e){pageObj.preparePageForReloading();Runner.runnerAJAX($(this).data("href"),pageObj.lookupBaseParams,function(respObj){pageObj.pageReloadHn(respObj)});return false;});}},initSortByDropdown:function(){var pageObj=this;$("[id='sortBy"+this.id+"']").off("change.sortby").on("change.sortby",function(e){var ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?sortby="+$(this).val();pageObj.preparePageForReloading();Runner.runnerAJAX(ajaxURL,pageObj.lookupBaseParams,function(respObj){pageObj.pageReloadHn(respObj);});});},initPagination:function(){var pageObj=this;$.each(this.getBrickObjs('pagination'),function(index,brick){brick.elem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),url;if(!$target.is("a")){return;}
pageObj.preparePageForReloading();url=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?goto="+$target.attr("pageNum");Runner.runnerAJAX(url,pageObj.lookupBaseParams,function(respObj){pageObj.pageReloadHn(respObj)});});});},pageReloadHn:function(respObj){Runner.stopLoading(this.gridElem);if(!respObj.success){this.win.set('bodyContent',"REQUEST FAILED");return;}
this.destroyVideo();Runner.setIdCounter(respObj.idStartFrom);if(Runner.isMobile){this.replaceBricksHTMLWith(this.getBricksHtml(respObj.html),".rnr-b-flypanel_mobile");}else{this.replaceBricksHTMLWith(this.getBricksHtml(respObj.html));}
this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.pageId];this.lookupCtrl.lookupVals=this.controlsMap.lookupVals;this.initLinks();this.initGridElem();this.initSorting();this.initSortByDropdown();if(this.hasMaps()){this.mapManager.init(this.controlsMap.gMaps.mapsData);}
if(this.inlineAdd){this.inlineAdd.reInit(this.controlsMap.gridRows);}
this.searchController.usedSrch=this.controlsMap.search.usedSrch;this.searchController.toggleShowAll(this.searchController.usedSrch);if(typeof respObj.viewControlsMap==="object"&&respObj.viewControlsMap[this.tName][this.pageType][this.pageId].controls){this.reInitViewControls(respObj.viewControlsMap[this.tName][this.pageType][this.pageId].controls);}
this.fireEvent('afterPageReady',this,this.proxy,this.pageId);},reInitViewControls:function(viewControls){this.setupViewContols(viewControls,this.pageCont);},preparePageForReloading:function(gridElem){if(!Runner.isMobile){Runner.pages.ListPageFly.superclass.preparePageForReloading.call(this,gridElem);}},initResize:Runner.emptyFn,initScrollGridBody:Runner.emptyFn,setUrlParams:Runner.emptyFn});Runner.pages.ListPage=Runner.extend(Runner.pages.ListPageCommon,{inlineEdit:null,inlineAdd:null,pageType:Runner.pages.constants.PAGE_LIST,mapManager:null,multipleHint:null,existMultipleHint:false,hideFieldPanelSorted:false,constructor:function(cfg){Runner.pages.ListPage.superclass.constructor.call(this,cfg);this.listFields=Runner.pages.PageSettings.getTableData(this.tName,'listFields');this.multipleHint=$(".rnr-sorthint",document.body);this.isUseInlineEdit=Runner.pages.PageSettings.getTableData(this.tName,"isInlineEdit");this.addEvents("afterInlineAdd","afterInlineEdit");},init:function(){Runner.pages.ListPage.superclass.init.call(this);this.initButtons();this.initSortByDropdown();this.initSection508();this.initUnlockingOnPageUnload();this.initGridClickActions();},initForGrid:function(){Runner.pages.ListPage.superclass.initForGrid.call(this);this.initSorting();this.initDetails();this.initPopupLinks();this.initShowHideColumnToggle();this.initColumnReordering();this.initPrintFriendly();this.fireEvent('afterInit',this,this.proxy,this.id);},initSection508:function(){if(Runner.pages.PageSettings.getGlobalData("s508")){this.s508Obj=new Runner.s508({pageId:this.id,gridObj:this.gridElem,pageURL:Runner.pages.getUrl(this.tName,this.pageType),maxPages:Runner.pages.PageSettings.getTableData(this.tName,"maxPages"),isUseInlineEdit:this.isUseInlineEdit&&this.permis['edit']});this.s508Obj.init();}},showHiddenColumn:function(fieldName){var pageObj=this,$panelBlock=$("#fildhidepanel"+pageObj.id),box=$panelBlock.find('input[data-field="'+fieldName+'"]');if(!box.prop('checked')){box.click();}},initShowHideColumnToggle:function(){if(!Runner.pages.PageSettings.getTableData(this.tName,"isAllowShowHideFields")){return;}
var pageObj=this,$panelBlock=$("#fildhidepanel"+pageObj.id),ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType),hideColumns=Runner.pages.PageSettings.getTableData(this.tName,"hideColumns")||[],colsToHide=hideColumns[Runner.util.getDeviceClass()]||[],$grid=$('[data-brick="grid"][data-pageid='+this.id+']'),columns=$("table.bs-fieldsgrid",$grid).length>0,vertical=!columns&&$grid.hasClass('bs-grid-vertical'),i;if(!$panelBlock.length){return;}
for(i=0;i<colsToHide.length;++i){$panelBlock.find('input[data-field="'+colsToHide[i]+'"]').prop('checked',false);}
$panelBlock.find('a').on('click',function(){$(this).find('input').click();return false;});$panelBlock.find('input').off('click').on('click',function(e){var hideFields=[".dummyField"],field=$(e.toElement||e.target).data('field'),show=$(e.toElement||e.target).prop('checked'),$dataFieldElem=$grid.find("[data-field='"+field+"']");if(vertical){if(show){$dataFieldElem.removeAttr("data-hidden-column");$dataFieldElem.find('.bs-view-label').attr('data-forced-visible-column','');$dataFieldElem.find('.bs-horizontal-value').attr('data-forced-visible-column','');}else{$dataFieldElem.attr("data-hidden-column",'');$dataFieldElem.find('.bs-view-label').removeAttr('data-forced-visible-column');$dataFieldElem.find('.bs-horizontal-value').removeAttr('data-forced-visible-column');}}else{if(show){$dataFieldElem.removeAttr("data-hidden-column").attr('data-forced-visible-column','');}else{$dataFieldElem.attr("data-hidden-column",'').removeAttr('data-forced-visible-column');}}
$panelBlock.find('input').each(function(n,box){if(!box.checked){hideFields.push($(box).data("field"));}});pageObj.onReoderColumnsStop();$.post(ajaxURL,{saveParam:Runner.pages.constants.SHFIELDS_PARAMS_TYPE,data:JSON.stringify(hideFields),deviceClass:Runner.util.getDeviceClass()});e.stopPropagation();});this.initReorderingInSHPanel();},reInitColumnReordering:function(){var columnOrder=Runner.pages.PageSettings.getTableData(this.tName,"columnOrder");this.initColumnReordering(columnOrder,true);},initColumnReordering:function(reInitColumnOrder,ajaxReload){if(!Runner.pages.PageSettings.getTableData(this.tName,"isAllowFieldsReordering")){return;}
var pageObj=this,ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType),columnOrder=reInitColumnOrder||Runner.pages.PageSettings.getTableData(this.tName,"columnOrder"),$gridHorizonatal=$('table[data-brick="grid"][data-pageid='+this.id+']'),$gridVertical=$('.bs-grid-vertical[data-brick="grid"][data-pageid='+this.id+']'),columnNormalOrder={},firstColumnIndex=0,ajaxReload=ajaxReload||false,needClickAfterReorder=[];if($gridHorizonatal.length>0){firstColumnIndex=$gridHorizonatal.find('th[data-field]').first().index();$.each(columnOrder,function(pos,fieldName){columnNormalOrder[fieldName]=pos+firstColumnIndex;});if(reInitColumnOrder){$gridHorizonatal.dragtable("destroy");}
$gridHorizonatal.dragtable({dragaccept:'[data-field]',persistState:function(table){var stateOrder=[];table.el.find('> thead > tr > th[data-field]').each(function(i){var fieldName=$(this).data('field');table.sortOrder[fieldName]=i;stateOrder[i]=fieldName;});pageObj.hideFieldPanelSorted=false;pageObj.hideFieldPanelOrder(stateOrder);$.post(ajaxURL,{saveParam:Runner.pages.constants.FORDER_PARAMS_TYPE,data:JSON.stringify(stateOrder)});},restoreState:columnNormalOrder,beforeStart:function(table,sortableTable){var $visibleDPreviewRows=$gridHorizonatal.find(".rnr-bs-dpreviewrow");$visibleDPreviewRows.each(function(i,item){var $dpButton=$(item).prev().find("a[id^=details_]:first");if($dpButton.length){$dpButton.click();needClickAfterReorder.push($dpButton);}});},beforeStop:function(table,sortableTable){$.each(needClickAfterReorder,function(i,$dpButton){$dpButton.click();});pageObj.onReoderColumnsStop();}});this.onReoderColumnsStop();if(!reInitColumnOrder){pageObj.hideFieldPanelOrder(columnOrder);}
return;}
if($gridVertical.length>0){if(reInitColumnOrder&&!ajaxReload){$gridVertical.find(".panel-body.form-horizontal:visible").sortable("destroy");}
$gridVertical.find(".panel-body.form-horizontal:visible").sortable({cursor:"move",update:function(event,ui){var $currentSortedRecord=$(ui.item).parents(".ui-sortable"),newOrderData=[];$currentSortedRecord.find('.ui-sortable-handle').each(function(i,el){var fieldName=$(this).data('field');if(typeof fieldName!="undefined"){newOrderData.push(fieldName);}});pageObj.hideFieldPanelSorted=false;pageObj.hideFieldPanelOrder(newOrderData);$.post(ajaxURL,{saveParam:Runner.pages.constants.FORDER_PARAMS_TYPE,data:JSON.stringify(newOrderData)});pageObj.initColumnReordering(newOrderData);},create:function(event){$.each(columnOrder,function(pos,fieldName){$(event.target).find('[data-field='+fieldName+']').appendTo(event.target);});if(!reInitColumnOrder){pageObj.hideFieldPanelOrder(columnOrder);}}});}},initReorderingInSHPanel:function(){if(!Runner.pages.PageSettings.getTableData(this.tName,"isAllowFieldsReordering")){return;}
var pageObj=this,$list=$("#fildhidepanel"+this.id).find("ul.dropdown-menu"),ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType);$list.sortable({update:function(event,ui){var newOrderData=[];$list.find('.ui-sortable-handle').each(function(i,el){var fieldName=$(this).find("input[data-field]").data('field');if(typeof fieldName!="undefined"){newOrderData.push(fieldName);}});$.post(ajaxURL,{saveParam:Runner.pages.constants.FORDER_PARAMS_TYPE,data:JSON.stringify(newOrderData)});pageObj.initColumnReordering(newOrderData);},helper:'clone',});},hideFieldPanelOrder:function(columnNormalOrder){var $panelHideFieldBlock=$("#fildhidepanel"+this.id);if(!this.hideFieldPanelSorted&&$panelHideFieldBlock.length){$.each(columnNormalOrder,function(pos,fieldName){$panelHideFieldBlock.find('input[data-field='+fieldName+']').parents("li").appendTo($panelHideFieldBlock.find(".dropdown-menu"));});}
this.hideFieldPanelSorted=true;},initInline:function(){var showAddInPopup=Runner.pages.PageSettings.getTableData(this.tName,"showAddInPopup")&&!Runner.isMobile,showEditInPopup=Runner.pages.PageSettings.getTableData(this.tName,"showEditInPopup")&&!Runner.isMobile,showViewInPopup=Runner.pages.PageSettings.getTableData(this.tName,"showViewInPopup")&&!Runner.isMobile,clickActions=Runner.normalizeClickActionSettings(Runner.pages.PageSettings.getTableData(this.tName,'clickActions')),inlineEditNeeded=false,f;if(clickActions.row.action=='open'||clickActions.row.action=='code'){inlineEditNeeded=true;}
for(f in clickActions.fields){if(clickActions.fields[f].action=='open'||clickActions.fields[f].action=='code'){inlineEditNeeded=true;break;}}
if(this.isUseInlineEdit&&this.permis['edit']||showAddInPopup||showEditInPopup||showViewInPopup||inlineEditNeeded){this.initInlineEdit();}
if(Runner.pages.PageSettings.getTableData(this.tName,"isInlineAdd")&&this.permis['add']||showAddInPopup||showEditInPopup||showViewInPopup||inlineEditNeeded){this.initInlineAdd();}},getInlineEditParams:function(){return{id:this.pageId,tName:this.tName,shortTName:this.shortTName,fNames:this.listFields,rows:this.controlsMap.gridRows,loadSettings:true,isOldLayout:this.oldLayout}},initInlineEdit:function(){this.inlineEdit=new Runner.util.inlineEditing.InlineEdit(this.getInlineEditParams());this.inlineEdit.init();this.inlineEdit.on("afterSave",function(fieldsData){this.fireEvent("afterInlineEdit",fieldsData);},this);this.inlineEdit.on("recalcGridSize",function(){this.recalculationGridSize();},this);this.inlineEdit.on("rowsEdited",function(){this.fireEvent("recalcGridSize");});this.inlineEdit.on("afterInit",function(pageObj,proxy,pageid,row){this.recalculationGridSize();},this);},getInlineAddParams:function(){return{id:this.pageId,tName:this.tName,shortTName:this.shortTName,fNames:this.listFields,rows:this.controlsMap.gridRows,inlineEditObj:this.inlineEdit,loadSettings:true,isOldLayout:this.oldLayout}},initInlineAdd:function(){this.inlineAdd=new Runner.util.inlineEditing.InlineAdd(this.getInlineAddParams());this.inlineAdd.init();this.inlineAdd.on("afterSubmit",function(vals,fields,keys,id,resp){var detailsBricks=this.getBrickObjs('details_found'),tName,detTables,newRowData;if(!detailsBricks.length){detailsBricks=this.getBrickObjs('vdetails_found');}
$.each(detailsBricks,function(ind,brick){$('.rnr-details_found_count',brick.elem[0]).each(function(jnd,detail){var df=parseInt($(detail).html(),10);$(detail).html(df?df+1:'1');});if(!brick.visible()){brick.show();}});if(!Runner.pages.PageSettings.getTableData(this.tName,"showRows")){var pageOfBricks=this.getBrickObjs('page_of');if(!pageOfBricks.length){pageOfBricks=this.getBrickObjs('vpage_of');}
$.each(pageOfBricks,function(ind,brick){if(!brick.visible()){var bPgs=$('b',brick.elem[0]);if($(bPgs).length){$.each(bPgs,function(jnd,page){$(page).html('1');});}else{$('span[name^=pageOf]',brick.elem[0]).html(Runner.lang.constants.TEXT_PAGE+' 1 '+Runner.lang.constants.TEXT_PAGEMAX+' 1');}
brick.show();}});this.showBricks(['recsperpage','vrecsperpage','toplinks_print','toplinks_export','printpanel','bsfieldhidepanel']);$("#print_"+this.id).show();$("#export_"+this.id).show();}
if(resp.noKeys===true){return;}
newRowData={id:id,masterKeys:resp.detKeys,keys:keys};for(tName in this.dpObjs){this.dpObjs[tName].addRow(newRowData);}
detTables=Runner.pages.PageSettings.getTableData(this.tName,"detailTables");for(tName in detTables){$("#master_"+Runner.pages.PageSettings.getShortTName(tName)+"_"+id).show();}},this);this.inlineAdd.on("afterSave",function(fieldsData){this.fireEvent("afterInlineAdd",fieldsData);},this);this.inlineAdd.on("recalcGridSize",function(){this.recalculationGridSize();},this);this.inlineAdd.on("rowsEdited",function(){this.fireEvent("recalcGridSize");});this.inlineAdd.on("afterInit",function(pageObj,proxy,pageid,row){this.afterInitInlineAdd(row);this.recalculationGridSize();},this);},afterInlineAdd:function(fn){this.on('afterInlineAdd',fn,this);},afterInlineEdit:function(fn){this.on('afterInlineEdit',fn,this);},onAfterShowDetails:function(){this.recalculationGridSize();},initButtons:function(){this.initDeleteButton();this.initUpdateSelectedButton();this.initAddButton();this.initRecordBlock();this.initExportLinks();this.initPrintLink();this.initAdminButton();this.initButtonGroupTogglers();this.hideExcessSeparators();},getEditRows:function(rowId){var rows=this.controlsMap.gridRows,i;for(i=0;i<rows.length;i++){if(rows[i].id==parseInt(rowId,10)&&rows[i].isEditOwnRow){return true;}}
return false;},clearSelection:function(){var $selBoxes=this.getSelBoxes(this.id);$selBoxes.prop("checked",false);$(".chooseAll"+this.id).prop("checked",false);this.onAfterChangeCheckboxsState();},initDeleteButton:function(){var pageObj=this,submitUrl=Runner.getPageUrl(this.shortTName,this.pageType),$selBoxes=this.getSelBoxes(this.id);if(this.isBootstrap()){$("[id=delete_selected"+this.id+"]").prop('disabled',$selBoxes.length==0);}
$("[id=delete_selected"+this.id+"]").unbind("click").bind("click",function(e){var $selBoxes=pageObj.getOwnedSelBoxes(),form;if(!$selBoxes.length||!confirm(Runner.lang.constants.TEXT_DELETE_CONFIRM)){return false;}
form=new Runner.form.BasicForm({standardSubmit:true,submitUrl:submitUrl,method:'POST',id:pageObj.id,baseParams:{a:'delete'},addElems:pageObj.cloneFormElements($selBoxes)});form.submit();form.destructor();return false;});},initExportLinks:function(){var pageObj=this,submitUrl;if(this.isBootstrap()){$("[id=export_selected"+this.id+"]").off("click.export").on("click.export",function(e){var $selBoxes=pageObj.getSelBoxes(pageObj.id),selection=[],pageParams;$selBoxes.each(function(i,s){selection.push(s.value);});if(!selection.length){return;}
pageParams=Runner.pages.ExportPage.prototype.getOpenPageParams.call(pageObj,selection);Runner.pages.PageManager.openPage(pageParams);return false;});$("[id=export_"+this.id+"]").off("click.export").on("click.export",function(e){var pageParams=Runner.pages.ExportPage.prototype.getOpenPageParams.call(pageObj,[]);Runner.pages.PageManager.openPage(pageParams);return false;});return;}
submitUrl=Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_EXPORT);$("[id=export_selected"+this.id+"]").off("click.export").on("click.export",function(e){var $selBoxes=pageObj.getSelBoxes(pageObj.id),form;if(!$selBoxes.length){return false;}
form=new Runner.form.BasicForm({standardSubmit:true,submitUrl:submitUrl,target:'_blank',method:'POST',id:pageObj.id,addElems:pageObj.cloneFormElements($selBoxes),baseParams:{a:"export"}});form.submit();form.destructor();});$("[id=export_"+this.id+"]").off("click.export").on("click.export",function(e){window.open(this.href,'wExport');return false;});},initPrintLink:function(){var pageObj=this,submitUrl=Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_PRINT);$("[id=print_selected"+this.id+"]").unbind("click").bind("click",function(e){var $selBoxes=pageObj.getSelBoxes(pageObj.id),form;if(!$selBoxes.length){return false;}
form=new Runner.form.BasicForm({standardSubmit:true,submitUrl:submitUrl,target:'_blank',method:'POST',id:pageObj.id,addElems:pageObj.cloneFormElements($selBoxes),baseParams:{a:"print"}});form.submit();form.destructor();});},initButtonGroupTogglers:function(){var pageObj=this,zIndex=Runner.genZIndexMax(),buttonClass=this.makeClassName("button"),$selectButtonsGroup=$("#selectButtonsGroup"+this.id),$extraButtonsGroup=$("#extraButtonsGroup"+this.id);$("#extraButtonsToggler"+this.id).add("#selectButtonsToggler"+this.id).on('click',function(e){return false;});$selectButtonsGroup.add($extraButtonsGroup).css("z-index",zIndex);$("."+buttonClass,$selectButtonsGroup).on("click",function(e){$selectButtonsGroup.hide();pageObj.resetButtonGroupDisplayStyle($selectButtonsGroup);});$("."+buttonClass,$extraButtonsGroup).on("click",function(e){$extraButtonsGroup.hide();pageObj.resetButtonGroupDisplayStyle($extraButtonsGroup);});},initSortByDropdown:function(){var pageObj=this;$("[id='sortBy"+this.id+"']").off("change.sortby").on("change.sortby",function(e){var reloadParams=pageObj.getSortingReloadParams();pageObj.reload({sortby:this.options[this.selectedIndex].value},reloadParams);});},initAddButton:function(){var pageObj=this;$("[id=addButton"+this.id+"]").unbind("click").bind("click",function(e){if(!Runner.pages.PageSettings.getTableData(pageObj.tName,"showAddInPopup")||Runner.isMobile){window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_ADD);return false;}
var pageParams=Runner.pages.AddPage.prototype.getOpenPageParams.call(pageObj,pageObj.id);pageObj.hideBrick('message');Runner.pages.PageManager.openPage(pageParams);return false;});},initUpdateSelectedButton:function(){var pageObj=this,rowid,$selBoxes=this.getSelBoxes(this.id);if(!Runner.pages.PageSettings.getTableData(pageObj.tName,"updateSelected")){return;}
if(this.isBootstrap()){$("[id=update_selected"+this.id+"]").prop("disabled",!$selBoxes.length);}
$("[id=update_selected"+this.id+"]").off("click").on("click",function(e){var $selBoxes=pageObj.getOwnedSelBoxes(),selection=[],rowIds=[],form,pageParams;$selBoxes.each(function(i,s){selection.push(s.value);rowIds.push($(s).closest("[data-record-id]").data("record-id"));});if(!selection.length){return;}
if(!Runner.pages.PageSettings.getTableData(pageObj.tName,"showEditInPopup")||Runner.isMobile){form=new Runner.form.BasicForm({standardSubmit:true,submitUrl:Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_EDIT),method:'POST',baseParams:{"selection[]":selection}});form.submit();}else{pageObj.hideBrick('message');pageParams=Runner.pages.EditSelectedPage.prototype.getOpenPageParams.call(pageObj,pageObj.id,selection,rowIds);Runner.pages.PageManager.openPage(pageParams);}
return false;});},initAdminButton:function(){$("[id=exitAdminArea"+this.id+"]").bind("click",function(e){window.location.href=Runner.getPageUrl("menu");});$("[id=adminArea"+this.id+"]").bind("click",function(e){window.location.href=Runner.getPageUrl("admin_rights_list");});},cloneFormElements:function($elems){var cloneElems=[];$elems.each(function(i,n){if(n.type=="checkbox"&&!n.checked){return;}
var cln=$('<input type=hidden>').attr('name',$(n).attr('name')).val($(n).val());cloneElems.push(cln);});return cloneElems;},preparePageForReloading:function(gridElem){this.delSortHint();Runner.pages.ListPage.superclass.preparePageForReloading.call(this,gridElem);},initGridTabs:Runner.emptyFn,initSorting:function(){var pageObj=this,i;for(i=0;i<this.listFields.length;i++){$('[id="order_'+Runner.goodFieldName(this.listFields[i])+'_'+this.id+'"]').mouseout(function(){pageObj.delSortHint();}).mousemove(function(e){pageObj.moveSortHint(e);}).mouseover(function(e){pageObj.addSortHint(e);}).mousedown(function(e){var baseParams={orderby:$(this).data("order")},reloadParams=pageObj.getSortingReloadParams();if(e.ctrlKey){baseParams.orderby=$(this).data("multisort")+';'+$(this).data("order");}
pageObj.reload(baseParams,reloadParams);});}},getSortingReloadParams:function(){return this.getExtraPageReloadParams();},getExtraPageReloadParams:function(){var reloadParams;if(this.bsResizeInitialized){reloadParams={resizableColumnsData:this.getResizableColumnsData()};}
return reloadParams;},getSortUrl:function(event,$elem){return event.ctrlKey?$elem.data('href')+';'+$elem.data('multisort'):$elem.data('href');},addSortHint:function(e){this.existMultipleHint=true;this.showSortHint(e);},setCoordinatesSortHint:function(e){var winDim=Runner.getWindowDimensions(),scrollX=$(window).scrollLeft(),scrollY=$(window).scrollTop(),hintY=e.pageY+20,hintX=e.pageX;if(hintX+this.multipleHint.width()>winDim.width+scrollX){hintX-=this.multipleHint.width();}
if(hintY+this.multipleHint.height()>winDim.height+scrollY){hintY-=this.multipleHint.height();}
this.multipleHint.css({left:hintX+"px",top:hintY+"px"});},showSortHint:function(e){if(!this.multipleHint.length){this.multipleHint=$('<span class="rnr-sorthint"><b>'+Runner.lang.constants.TEXT_CTRL_CLICK+'</b></span>').appendTo("body");}
if(this.existMultipleHint){this.setCoordinatesSortHint(e);this.multipleHint.show();}},delSortHint:function(){if(this.multipleHint.length){this.multipleHint.hide();this.existMultipleHint=false;}},moveSortHint:function(e){if(this.multipleHint.length&&this.multipleHint.is(":visible")){this.setCoordinatesSortHint(e);}},initUnlockingOnPageUnload:function(){if(!this.inlineEdit||!this.inlineEdit.isUseLocking){return;}
Runner.pages.PageManager.addUnloadHn(function(){var rows=this.rows,i;for(i=0;i<rows.length;i++){if(!rows[i].submitted){this.locking.UnlockRecordInline(this.getKeysForLocking(rows[i]),true);}}},this.inlineEdit);},initGridClickActions:function(){var clickActions=Runner.normalizeClickActionSettings(Runner.pages.PageSettings.getTableData(this.tName,'clickActions')),vertical=$('.bs-grid-vertical[data-brick="grid"][data-pageid='+this.id+']').length,rowSelector=!vertical?'[id^=gridRow]':'.panel[data-record-id]';this.setClickActionHandler(clickActions.row,rowSelector);for(var f in clickActions.fields){this.setClickActionHandler(clickActions.fields[f],rowSelector+' [data-field='+Runner.goodFieldName(f)+']');}},setClickActionHandler:function(settings,selector){if(settings.action=='open'){this.setOpenClickActionHandler(settings.openData,selector);return;}
if(settings.action=='grid'){if(settings.gridData.action=='details'){this.setDetailsClickActionHandler(settings.gridData.table,selector);}else if(settings.gridData.action=='checkbox'){this.setRowCheckingActionHandler(selector);}else if(settings.gridData.action=='inlineedit'){this.setRowInlineEditActionHandler(selector);}
return;}
if(settings.action=='code'){this.setAjaxActionHandler(settings.codeData.snippet,selector);}},getInlineRow:function(rowId){return this.getInlineEditObj().getRowById(rowId);},setAjaxActionHandler:function(snippet,selector){var pageObj=this;this.gridElem.on('click',selector,function(e){var rowId=pageObj.getRowIdByClickElementMarkup($(e.target)),row=pageObj.getInlineRow(rowId);if(row&&pageObj.inlineEdit&&pageObj.inlineEdit.isRowEditing(row))
return;if(row&&typeof Runner.pages.ajaxEvents[snippet]==='function'){Runner.pages.ajaxEvents[snippet].call(pageObj,pageObj,pageObj.proxy,pageObj.id,row,pageObj.getInlineEditObj());}
if(!$(this).is('[id^=gridRow]')){e.stopPropagation();}});this.gridElem.find(selector).addClass('bs-clickable');},setDetailsClickActionHandler:function(table,selector){var pageObj=this,dpObj=this.dpObjs?this.dpObjs[table]:null,detTables=Runner.pages.PageSettings.getTableData(this.tName,"detailTables");if(this.dashboard){return;}
if(!dpObj||!(dpObj instanceof Runner.util.details.ListTabbedPreview)){if(!detTables[table]){return;}
dpObj=this.createDetailsObject(table,detTables[table],this.nextDetailsTabId++,Runner.pages.constants.DP_INLINE);}
this.gridElem.on('click',selector,function(e){var rowId=pageObj.getRowIdByClickElementMarkup($(e.target)),row=dpObj.getRowById(rowId);if(!row){return;}
if(pageObj.inlineEdit&&pageObj.inlineEdit.isRowEditing(row))
return;dpObj.linkClickHandler(row,e);if(!$(this).is('[id^=gridRow]')){e.stopPropagation();}});this.gridElem.find(selector).addClass('bs-clickable');},getRowIdByClickElementMarkup:function($elem){if($elem.is("[data-gridlink]")||$elem.parents("[data-gridlink]").length){return-1;}
var $row=$elem.closest("[data-record-id]");if($row.length){return $row.data("record-id");}
$row=$elem.closest("[id^='gridRow']");if($row.length){return $row.attr("id").substr(7);}
return-1;},setRowCheckingActionHandler:function(selector){var pageObj=this;this.gridElem.on("click",selector,function(e){var rowId=pageObj.getRowIdByClickElementMarkup($(e.target)),$checkbox,checkbox;if(rowId===-1){return;}
row=pageObj.getInlineRow(rowId);if(row&&pageObj.inlineEdit&&pageObj.inlineEdit.isRowEditing(row))
return;$checkbox=$("input[type='checkbox'][id='check"+pageObj.id+"_"+rowId+"']",pageObj.pageCont);$checkbox.prop("checked",!$checkbox.prop("checked"));pageObj.onAfterChangeCheckboxsState();if(!$(this).is('[id^=gridRow]')){e.stopPropagation();}});},hasInlineEdit:function(){return!!this.inlineEdit;},setRowInlineEditActionHandler:function(selector){var pageObj=this;if(!this.hasInlineEdit()){return;}
this.gridElem.on("click",selector,function(e){var rowId=pageObj.getRowIdByClickElementMarkup($(e.target)),row;if(rowId===-1){return;}
row=pageObj.getInlineRow(rowId);if(row&&!pageObj.inlineEdit.isRowEditing(row)){pageObj.inlineEdit.inlineEdit(row);}
if(!$(this).is('[id^=gridRow]')){e.stopPropagation();}});},setOpenClickActionHandler:function(openData,selector){var handlerFunc,pageObj=this;if(openData.page=='view'){handlerFunc=this.getViewLinkHandler;}else if(openData.page=='edit'){handlerFunc=this.getEditLinkHandler;}else if(openData.page=='add'){handlerFunc=this.getAddLinkHandler;}else if(openData.page=='print'){handlerFunc=this.getPrintLinkHandler;}else if(openData.page=='details'){handlerFunc=this.getDetailsLinkHandler;}else if(openData.page=='url'){handlerFunc=this.getUrlLinkHandler;}else{return;}
this.gridElem.on('click',selector,function(e){var rowId=pageObj.getRowIdByClickElementMarkup($(e.target)),row=pageObj.getInlineRow(rowId);if(!row||openData.page=="edit"&&!row.isEditOwnRow){return;}
if(row&&pageObj.inlineEdit&&pageObj.inlineEdit.isRowEditing(row))
return;if(openData.page=='url'){handlerFunc.call(pageObj,openData.url,openData.how).call();}else if(openData.page=='details'){if(typeof pageObj.dpObjs[openData.table]==="undefined")
return;handlerFunc.call(pageObj,row,openData.table,openData.how).call();}else{handlerFunc.call(pageObj,row,openData.how).call();}
if(!$(this).is('[id^=gridRow]')){e.stopPropagation();}});this.gridElem.find(selector).filter(function(i){if(openData.page=="edit"){var rowId=pageObj.getRowIdByClickElementMarkup($(this)),row=pageObj.getInlineRow(rowId);return row&&row.isEditOwnRow;}
if(openData.page=='details'){return typeof pageObj.dpObjs[openData.table]!=="undefined";}
return true;}).addClass('bs-clickable');}});Runner.pages.ListPageAjax=Runner.extend(Runner.pages.ListPage,{ajaxBaseParams:null,constructor:function(cfg){Runner.pages.ListPageAjax.superclass.constructor.call(this,cfg);this.listFields=Runner.pages.PageSettings.getTableData(this.tName,'listFields');this.ajaxBaseParams={mode:"ajax",id:this.pageId};this.bricksForReload=["details_found","page_of","recsperpage","vrecsperpage","vdetails_found","vpage_of","grid","pagination","message","filterpanel","search_saving_buttons","recordcontrol","reorder_records","bsgrid_tabs"];if(this.isBootstrap()){this.bricksForReload.push("morebutton");}},initSearch:function(){Runner.pages.ListPageAjax.superclass.initSearch.call(this);this.searchController.ajaxSubmit=true;this.searchController.srchForm.standardSubmit=false;this.searchController.srchForm.baseParams=this.ajaxBaseParams;this.searchController.srchForm.on("beforeSubmit",function(form){this.preparePageForReloading();},this);this.searchController.on('afterSearch',function(respObj,srchController,srchForm){Runner.stopLoading();this.pageReloadHn(respObj);},this);this.searchController.srchForm.on('submitFailed',function(){Runner.stopLoading();},this);},initInline:function(){Runner.pages.ListPageAjax.superclass.initInline.call(this);this.initInline=Runner.emptyFn;},reInitInline:function(){this.inlineButtonsIntialized=false;if(this.inlineAdd){this.inlineAdd.reInit(this.controlsMap.gridRows);this.inlineAdd.reinitButtons();}
if(this.inlineEdit){this.inlineEdit.reInit(this.controlsMap.gridRows);this.inlineEdit.reinitButtons();}
if(this.inlineAdd||this.inlineEdit){(this.inlineAdd||this.inlineEdit).toggleMassRecButt();}},initRecordBlock:function(){var pageObj=this;$("[id='recordspp"+this.id+"']").on("change",function(e){var ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?pagesize="+$(this).val();pageObj.preparePageForReloading();Runner.runnerAJAX(ajaxURL,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj);});});},initSortByDropdown:function(){var pageObj=this;$("[id='sortBy"+this.id+"']").off("change.sortby").on("change.sortby",function(e){var ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?sortby="+$(this).val();pageObj.preparePageForReloading();Runner.runnerAJAX(ajaxURL,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj);});});},initGridTabs:function(){var pageObj=this;$(pageObj.pageCont).on('click','[data-brick=bsgrid_tabs] li > a[data-pageid='+this.id+']',function(e){var url=$(this).attr('href'),tabs=$(this).parents('ul').find('li'),$currentTab=$(this).parent();$.each(tabs,function(e){$(this).removeClass('active');});$currentTab.addClass('active');pageObj.preparePageForReloading();Runner.runnerAJAX(url,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj);});return false;});},initSorting:function(){var pageObj=this,i;for(i=0;i<this.listFields.length;i++){$('[id="order_'+Runner.goodFieldName(this.listFields[i])+'_'+this.id+'"]').mouseout(function(){pageObj.delSortHint();}).mousemove(function(e){pageObj.moveSortHint(e);}).mouseover(function(e){pageObj.addSortHint(e);}).mousedown(function(e){var url=pageObj.getSortUrl(e,$(this));pageObj.preparePageForReloading();Runner.runnerAJAX(url,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj)});e.stopPropagation();});}},initDeleteButton:function(){var pageObj=this;$("[id='delete_selected"+this.id+"']").unbind("click").bind("click",function(e){Runner.Event.prototype.stopEvent(e);pageObj.preparePageForReloading();var $selBoxes=pageObj.getSelBoxes(pageObj.id),form;if(!$selBoxes.length||!confirm(Runner.lang.constants.TEXT_DELETE_CONFIRM)){Runner.stopLoading();return false;}
form=new Runner.form.BasicForm({submitUrl:Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?"+$selBoxes.serialize(),standardSubmit:false,method:'POST',baseParams:Runner.apply({a:'delete'},pageObj.ajaxBaseParams),successSubmit:{fn:function(respObj,formObj,fieldControls){this.pageReloadHn(respObj);},scope:pageObj}});form.submit();});},initPagination:function(){var pageObj=this;$.each(this.getBrickObjs('pagination'),function(index,brick){brick.elem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),ajaxURL;if(!$target.is("a")){return false;}
pageObj.preparePageForReloading();ajaxURL=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?goto="+$target.attr("pageNum")
Runner.runnerAJAX(ajaxURL,pageObj.ajaxBaseParams,function(respObj){pageObj.pageReloadHn(respObj)});});});this.initPagination=Runner.emptyFn;},addCustomCss:function(cssRules){var customCellsStyle=this.gridElem.parent().find(".rnr-cells-css");if(customCellsStyle.length){customCellsStyle.html(cssRules);return;}
customCellsStyle=$('<style class="rnr-cells-css" type="text/css"> '+cssRules+' </style>');this.gridElem.parent().prepend(customCellsStyle);},updateMoreButtonsVisibility:function(numberOfRecs,recPerPage){this.toggleBrick("toplinks_print",numberOfRecs>0);this.toggleBrick("toplinks_export",numberOfRecs>0);$("#print_"+this.id).toggle(numberOfRecs>0);$("#export_"+this.id).toggle(numberOfRecs>0);$("#printAll_"+this.id).toggle(numberOfRecs>recPerPage&&recPerPage>0);$("#edit_selected"+this.id).toggle(numberOfRecs>0);$("#delete_selected"+this.id).toggle(numberOfRecs>0);$("#export_selected"+this.id).toggle(numberOfRecs>0);},updatePrintPanel:function(numberOfRecs,recPerPage){this.toggleBrick("printpanel",numberOfRecs>0);},updateFieldHidePanel:function(numberOfRecs){this.toggleBrick("bsfieldhidepanel",numberOfRecs>0);},pageReloadHn:function(respObj,isNaved){Runner.stopLoading();if(!respObj||!respObj.success){this.displayMessage('Submit failed',true,true);return;}
Runner.applyPagesData(respObj.pagesData);this.pageData=Runner.getPageData(this.id);this.proxy=this.pageData.proxy;var respControlsMap=respObj["controlsMap"][this.tName][this.pageType][this.id];isNaved=isNaved||false;Runner.setIdCounter(respObj.idStartFrom);Runner.pages.PageSettings.addSettings(this.tName,respObj.settings,false);this.controlsMap.gridRows=respControlsMap.gridRows;if(this.bsResizeInitialized){this.resizableColumnsData=this.getResizableColumnsData();}
this.destroyVideo();this.replaceBricksHTMLWith(this.getBricksHtml(respObj.html));this.toggleBrick("message",!this.controlsMap.gridRows.length||respObj.usermessage);this.updateMoreButtonsVisibility(respObj["numberOfRecs"],respObj["recPerPage"]);this.updatePrintPanel(respObj["numberOfRecs"],respObj["recPerPage"]);this.updateFieldHidePanel(respObj["numberOfRecs"]);this.onAfterChangeCheckboxsState();this.initGridElem();this.nextDetailsTabId=0;if(!this.useResize){this.initDetails();this.initPopupLinks();this.initSorting();this.reInitColumnReordering();}else{this.initResize();}
this.initHeaderCheckBox();this.initDeleteButton();this.initExportLinks();this.initPrintLink();this.initSelectAll();this.initRecordBlock();this.initUpdateSelectedButton();this.initGridClickActions();this.initSortByDropdown();if(this.isBootstrap()){this.reInitMorebuttonPanel();}
this.searchController.usedSrch=respControlsMap.search&&respControlsMap.search.usedSrch;if(this.searchController.usedSrch){this.searchController.simpleSearchActive=Runner.pages.PageSettings.getTableData(this.tName,"simpleSearchActive");}
if(respControlsMap.search){if(respControlsMap.search.isSearchRequired){this.searchController.toggleResetButton(respControlsMap.search.usedSrch);}else{this.searchController.toggleShowAll(respControlsMap.search.usedSrch);}}
if(respControlsMap.filters){this.searchController.filterContolsData=respControlsMap.filters.controls;this.searchController.initFilters();}
if(this.searchSavingEnabled){this.searchParamsLogger.initSearchSavingButtons();this.searchParamsLogger.initSavedSearchesList();}
if(!isNaved&&this.pageData.urlParams){Runner.Hash.set(this.pageData.urlParams,false);}
this.reInitInline();this.addCustomCss(respObj['cellStyles']);if(this.mapManager&&respControlsMap.gMaps&&respControlsMap.gMaps.isUseGoogleMap){this.mapManager.init(respControlsMap.gMaps.mapsData);}
if(typeof respObj.viewControlsMap==="object"&&respObj.viewControlsMap.controls){this.reInitViewControls(respObj.viewControlsMap.controls);}
this.fireEvent('afterInit',this,this.proxy,this.pageId);if(!this.useResize){this.fireEvent('afterPageReady',this,this.proxy,this.pageId);}
this.hideExcessSeparators();},reInitViewControls:function(viewControls){this.setupViewContols(viewControls,this.pageCont);},reInitMorebuttonPanel:function(){this.initLanguageSelector();this.searchController.srchOptExpander=$("[id=showOptPanel"+this.id+"]");this.searchController.initShowHideToggler();this.searchController.changePanelExpanderState();},initScrollGridBody:Runner.emptyFn});Runner.pages.ListPageDP=Runner.extend(Runner.pages.ListPage,{baseParams:null,detCont:null,useChildCount:true,masterKeys:null,hideSaveButt:false,constructor:function(cfg){Runner.pages.ListPageDP.superclass.constructor.call(this,cfg);this.pageCont=cfg.pageCont||$('#detailPreview'+this.id)[0];this.addEvents("beforeSaveDetails","afterSaveDetails","afterDeleteDetails","afterPageReady");this.baseParams=cfg.baseParams||{id:this.pageId};Runner.apply(this.baseParams,this.controlsMap.masterKeys);},init:function(){Runner.pages.ListPageDP.superclass.init.call(this);if(this.beforeSaveDetails){this.on({'beforeSaveDetails':this.beforeSaveDetails});}
if(this.afterSaveDetails){this.on({'afterSaveDetails':this.afterSaveDetails});}
if(this.afterDeleteDetails){this.on({'afterDeleteDetails':this.afterDeleteDetails});}
if(this.saveFailed){this.on({'saveFailed':this.saveFailed});}},initSearch:Runner.emptyFn,initScrollGridBody:Runner.emptyFn,afterPageReady:Runner.emptyFn,setUrlParams:Runner.emptyFn,recalculationGridSize:function(){var parPageObj=Runner.pages.PageManager.getAt(this.baseParams.mastertable,this.parId);if(parPageObj&&parPageObj.pageType==Runner.pages.constants.PAGE_LIST){parPageObj.recalculationGridSize();}},initDeleteButton:function(){var submitUrl=Runner.getPageUrl(this.shortTName,this.pageType),pageObj=this;$("[id='delete_selected"+this.id+"']").unbind("click").bind("click",function(e){var $selBoxes=pageObj.getSelBoxes(pageObj.id),form;if($selBoxes.length==0||!confirm(Runner.lang.constants.TEXT_DELETE_CONFIRM)){return false;}
form=new Runner.form.BasicForm({standardSubmit:false,submitUrl:submitUrl+"?"+$selBoxes.serialize(),method:'POST',id:pageObj.id,baseParams:Runner.apply({a:'delete',mode:Runner.pages.constants.MODE_LIST_DETAILS},pageObj.baseParams),successSubmit:{fn:function(respObj,formObj,fieldControls){this.fireEvent("afterDeleteDetails");if(this.parId){Runner.pages.PageManager.getById(this.parId).setRecountFlagForPopup();}
this.pageReloadHn(respObj);formObj.destructor();},scope:pageObj}});form.submit();return false;});},initInline:function(){Runner.pages.ListPageDP.superclass.initInline.call(this);this.initInline=Runner.emptyFn;},reInitInline:function(){this.inlineButtonsIntialized=false;if(this.inlineAdd){this.inlineAdd.reInit(this.controlsMap.gridRows);}
if(this.inlineEdit){this.inlineEdit.reInit(this.controlsMap.gridRows);}},initInlineEdit:function(){if(this.baseParams.masterpagetype!==Runner.pages.constants.PAGE_EDIT&&this.baseParams.masterpagetype!==Runner.pages.constants.PAGE_LIST){return;}
Runner.pages.ListPageDP.superclass.initInlineEdit.call(this);if(!this.inlineEdit){return;}
this.inlineEdit.on("beforeSubmit",function(row,inlineObj,formObj){Runner.apply(formObj.baseParams,this.masterKeys);return this.fireEvent("beforeSave",row,inlineObj,formObj);},this);this.inlineEdit.on("rowsEdited",function(allVals,fields,allKeys,allRowIds,isEdited){if(!this.inlineAdd||!this.inlineAdd.isRowsEditing()){this.fireEvent("afterSaveDetails",allVals,fields,allKeys,allRowIds,isEdited);}},this);this.inlineEdit.on("submitFailed",function(respObj,hnScope,formObj,fieldControls){this.fireEvent("saveFailed",respObj,formObj,fieldControls);},this);this.inlineEdit.on("beforeRequestControls",function(inlineObj,inlineEditRow,reqParams){Runner.apply(reqParams,this.masterKeys);},this);this.inlineEdit.on("validationFailed",function(formObj,fieldControls){this.validationFailed();},this);},getInlineAddParams:function(){var params=Runner.pages.ListPageDP.superclass.getInlineAddParams.call(this);params.hideSaveButt=this.hideSaveButt;return params;},initInlineAdd:function(){if(this.baseParams.masterpagetype!==Runner.pages.constants.PAGE_ADD&&this.baseParams.masterpagetype!==Runner.pages.constants.PAGE_EDIT&&this.baseParams.masterpagetype!==Runner.pages.constants.PAGE_LIST){return;}
Runner.pages.ListPageDP.superclass.initInlineAdd.call(this);if(!this.inlineAdd){return;}
this.inlineAdd.on("beforeSubmit",function(row,inlineObj,formObj){Runner.apply(formObj.baseParams,this.masterKeys);return this.fireEvent("beforeSave",row,inlineObj,formObj);},this);this.inlineAdd.on("rowsEdited",function(allVals,fields,allKeys,allRowIds,isEdited,singleSaveBtnPressed){if(!this.inlineEdit||!this.inlineEdit.isRowsEditing()||singleSaveBtnPressed){this.fireEvent("afterSaveDetails",allVals,fields,allKeys,allRowIds,isEdited);}},this);this.inlineAdd.on("submitFailed",function(respObj,hnScope,formObj,fieldControls){this.fireEvent("saveFailed",respObj,formObj,fieldControls);},this);this.inlineAdd.on("beforeRequestControls",function(inlineObj,inlineEditRow,reqParams){Runner.apply(reqParams,this.masterKeys);},this);this.inlineAdd.on("validationFailed",function(formObj,fieldControls){this.validationFailed();},this);},validationFailed:Runner.emptyFn,saveAll:function(mKeys){var saveAllInlines=false;if(this.inlineEdit){if(mKeys){Runner.apply(this.inlineEdit.baseParams,mKeys);this.inlineEdit.baseParams['mastertable']=this.masterTName;}
saveAllInlines=true;this.inlineEdit.saveAll();}
if(this.inlineAdd){if(mKeys){Runner.apply(this.inlineAdd.baseParams,mKeys);this.inlineAdd.baseParams['mastertable']=this.masterTName;}
saveAllInlines=true;this.inlineAdd.saveAll();}
return saveAllInlines;},initSorting:function(){var pageObj=this,i;for(i=0;i<this.listFields.length;i++){$('[id="order_'+Runner.goodFieldName(this.listFields[i])+'_'+this.id+'"]').on("click",function(e){var url=pageObj.getSortUrl(e,$(this));pageObj.preparePageForReloading(pageObj.detCont[0]);Runner.runnerAJAX(url,pageObj.baseParams,function(respObj){pageObj.pageReloadHn(respObj)});});}},initSortByDropdown:function(){var pageObj=this,submitUrl=Runner.pages.getUrl(this.tName,this.pageType);$("[id='sortBy"+this.id+"']").off("change.sortby").on("change.sortby",function(e){var ajaxURL=submitUrl+"?sortby="+$(this).val();Runner.runnerAJAX(ajaxURL,pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});});},initPagination:function(){var pageObj=this;$.each(this.getBrickObjs('pagination'),function(index,brick){brick.elem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),pageNum,url;if(!$target.is("a")){return;}
pageObj.preparePageForReloading(pageObj.detCont[0]);pageNum=$target.attr("pageNum");url=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?goto="+pageNum;Runner.runnerAJAX(url,pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});});});},pageReloadHn:function(respObj){var parPageObj=Runner.pages.PageManager.getAt(this.masterTName,this.parId);Runner.stopLoading(this.detCont[0]);if(!respObj.success){$("#message_block"+this.id).html("Submit failed!");}
Runner.applyPagesData(respObj.pagesData);this.pageData=Runner.getPageData(this.id);this.proxy=this.pageData.proxy;this.destroyVideo();Runner.setIdCounter(respObj.idStartFrom);respObj.bodyCont=respObj.html;if(Runner.isBootstrap()&&(parPageObj.pageType==Runner.pages.constants.PAGE_EDIT||parPageObj.pageType==Runner.pages.constants.PAGE_ADD||parPageObj.pageType==Runner.pages.constants.PAGE_VIEW)){Runner.pages.PageManager.putToContainer.call(this,respObj,this.detCont);}else{Runner.pages.PageManager.putToDashContainer.call(this,respObj,this.detCont);}
if(respObj.controlsMap){this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.pageId];}
this.toggleBrick("message",!this.controlsMap.gridRows.length||respObj.delMess);this.onAfterChangeCheckboxsState();this.initGridElem();this.initSorting();this.initDetails();this.initPopupLinks();this.initHeaderCheckBox();this.initResize();this.initPagination();this.initSelectAll();this.reInitInline();this.initRunnerButtons();this.initGridTabs();this.initDeleteButton();this.initAddButton();this.initUpdateSelectedButton();this.initGridClickActions();this.initSortByDropdown();if(this.hasMaps()){this.mapManager.init(this.controlsMap.gMaps.mapsData);}
if(respObj.viewControlsMap){this.setupViewContols(respObj.viewControlsMap[this.tName][this.pageType][this.pageId].controls,this.pageCont);}
if(!this.useResize){this.fireEvent('afterPageReady',this,this.proxy,this.pageId);}},destructor:function(){if(this.inlineEdit||this.inlineAdd){(this.inlineEdit||this.inlineAdd).cancelAll();}
Runner.pages.ListPageDP.superclass.destructor.call(this);}});Runner.pages.ListPageMobile=Runner.extend(Runner.pages.ListPage,{morePanel:null,menuPanel:null,srchOptDivMobile:null,bricksArr:null,bricksArrList:null,constructor:function(cfg){Runner.pages.ListPageMobile.superclass.constructor.call(this,cfg);this.useResize=false;this.morePanel=$("#more"+this.id);this.menuPanel=$("#menu_mobile_"+this.id);this.srchOptDivMobile=$(".searchOptions",this.pageCont);this.bricksArr=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","vmenu","searchpanel_mobile","backbutton","morelink_mobile","message","grid","filterpanel","pagination","languages","loggedas","details_found","page_of","recsperpage","fulltext_mobile","vmsearch2","cancelbutton_mobile","bars_menu_icon","adv_search_button"];this.bricksArrList=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","morelink_mobile","message","grid","pagination","languages","loggedas","filterpanel","details_found","page_of","recsperpage","bars_menu_icon"];},init:function(){Runner.pages.ListPageMobile.superclass.init.call(this);this.srchOptDivMobile.show();$(window).bind('hashchange',$.proxy(this.updatePageAppearance,this));if(!window.location.hash){window.location.hash="#list";}else{this.updatePageAppearance();}},updatePageAppearance:function(){if(window.location.hash=='#search'){this.showMobileSearchPanel();}
if(window.location.hash=='#menu'){this.showMobileMenu();}
if(window.location.hash=='#list'){this.showMobileListPage();}},initMoreButton:function(){var pageObj=this,offsetLeft;$("#morebutton").unbind("click").bind("click",function(e){if(!pageObj.morePanel.is(":visible")){offsetLeft=e.clientX-pageObj.morePanel.width();pageObj.morePanel.css({left:(offsetLeft>0?offsetLeft:0)+15}).show();}else{pageObj.morePanel.hide();}
return false;});},initMoreClosePanel:function(){var pageObj=this;$("#more_close").unbind("click").bind("click",function(e){pageObj.morePanel.hide();return false;});},showMobileMenu:function(){if(window.location.hash!=='#menu'){return;}
this.hideBricks(this.bricksArr);this.showBricks(["vmenu","backbutton","tableinfo_mobile"]);$("#menu_button").attr("href","#list");Runner.menu.TreeLikeVmenu.prototype.openMenuOnLoad();},initBackButton:function(){var pageObj=this;$("#backbutton").unbind("click").bind("click",function(e){pageObj.showMobileListPage();});},showMobileListPage:function(){if(window.location.hash!=='#list'){return;}
this.hideBricks(this.bricksArr);this.showBricks(this.bricksArrList);$("#menu_button").attr("href","#menu");},showMobileSearchPanel:function(){if(window.location.hash!=='#search'){return;}
var bricksToShow=this.getSearchBricks();this.hideBricks(this.bricksArr);this.showBricks(bricksToShow);this.showBricks(["backbutton","tableinfo_mobile","vmenu_mobile"]);var pageObj=this;if(pageObj.morePanel.is(":visible")){pageObj.morePanel.hide();}},getSearchBricks:function(){var searchBricks=["searchpanel_mobile","backbutton","adv_search_button"];if(this.controlsMap.search.googleLikeFields&&this.controlsMap.search.googleLikeFields.length){searchBricks.push("vmsearch2");}
return searchBricks;},initRowClick:function(){$("td, th","tr[id^='gridRow']").not("[ieditcont='checkBox'], [ieditcont='all'], [class~='rnr-cg']").unbind("click").bind("click",function(e){var $target=$(e.target),$tr,$td,url;if($target.is("a")||$target.parents().hasClass("projekktor")){return;}
$tr=$(this).closest("tr[id^='gridRow']");if(!$tr.length){return;}
$td=$("[data-viewlink],[data-editlink]",$tr);if(!$td.length){return;}
url=$td.data("viewlink")||$td.data("editlink");if(!url){return;}
window.location.href=url;});},largeTextOpenerDelegate:function(e){this.largeTextOpenerDelegateMobile(e);},initSelectAll:function(){var pageObj=this,selectAll=$('#select_all'+this.id),useCaption;if(!selectAll.length){return false;}
useCaption=Runner.pages.PageSettings.getTableData(this.tName,"listGridLayout")!==Runner.pages.constants.HORIZONTAL_LAYOUT;selectAll[0].checkAllStatus=false;selectAll.on("click",function(e){this.checkAllStatus=!this.checkAllStatus;$('input[type=checkbox][id^=check'+pageObj.id+'_]').prop("checked",this.checkAllStatus);if(useCaption){$(this).html(this.checkAllStatus?Runner.lang.constants.UNSELECT_ALL:Runner.lang.constants.SELECT_ALL);}
if(e.stopImmediatePropagation){e.stopImmediatePropagation();}
pageObj.morePanel.hide();});},initSorting:function(){var pageObj=this,i;for(i=0;i<this.listFields.length;i++){$('[id="order_'+Runner.goodFieldName(this.listFields[i])+'_'+this.id+'"]').click(function(e){window.location.href=pageObj.getSortUrl(e,$(this));});}},initButtons:function(){Runner.pages.ListPageMobile.superclass.initButtons.call(this);this.initRowClick();this.initMoreButton();this.initMoreClosePanel();this.initBackButton();}});Runner.pages.ListPageMobileDP=Runner.extend(Runner.pages.ListPageDP,{bricksArr:null,bricksArrList:null,constructor:function(cfg){Runner.pages.ListPageMobileDP.superclass.constructor.call(this,cfg);this.initLargeTextBackButtonMobileDP();this.useResize=false;this.bricksArr=["backbutton","morelink_mobile","message","grid","fulltext_mobile"];this.bricksArrList=["morelink_mobile","message","grid",];},pageReloadHn:function(respObj){Runner.pages.ListPageMobileDP.superclass.pageReloadHn.call(this,respObj);this.initLargeTextBackButtonMobileDP();},largeTextOpenerDelegate:function(e){this.largeTextOpenerDelegateMobile(e);}});Runner.pages.ReportPageMobile=Runner.extend(Runner.pages.ListPageMobile,{pageType:Runner.pages.constants.PAGE_REPORT,constructor:function(cfg){Runner.pages.ReportPageMobile.superclass.constructor.call(this,cfg);this.bricksArr=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","vmenu","searchpanel","backbutton","message","report","filterpanel","pagination","languages","loggedas","vmsearch2","fulltext_mobile","crosscontrols"];this.bricksArrList=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","message","report","filterpanel","pagination","languages","loggedas","crosscontrols"];},init:function(){Runner.pages.ReportPageMobile.superclass.init.call(this);this.fireEvent('afterInit',this,this.proxy,this.id);$(this.getBrickElem('report')).bind("click",$.proxy(this.reportClickHn,this));Runner.pages.ReportPage.prototype.initCrossControls.call(this);},reportClickHn:function(e){this.largeTextOpenerDelegate(e);},getPaginationLink:function(pageNum,linkText,cls){return'<a href="#" pageNum="'+pageNum+'" '+(cls?'class="pag_n"':'')+' style="text-decoration: none;">'+linkText+'</a>';},initAdvSearch:function(){var pageObj=this;$("#advButton"+this.pageId).bind("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"search");});},initRowClick:Runner.emptyFn,initButtons:function(){this.initBackButton();},getSearchBricks:function(){var searchBricks=["searchpanel","backbutton"];if(this.controlsMap.search.googleLikeFields&&this.controlsMap.search.googleLikeFields.length){searchBricks.push("vmsearch2");}
return searchBricks;}});Runner.pages.ReportPage=Runner.extend(Runner.pages.DataPageWithSearch,{pageType:Runner.pages.constants.PAGE_REPORT,dashElement:null,crossTable:false,reportFileName:"",$crossReportTable:null,colorTrTdHighlight:null,constructor:function(cfg){Runner.pages.ReportPage.superclass.constructor.call(this,cfg);this.crossTable=Runner.pages.PageSettings.getTableData(this.tName,"crossTable");this.reportFileName=Runner.getPageUrl(this.shortTName,this.pageType);},init:function(){if(this.pageMode==Runner.pages.constants.REPORT_DASHBOARD){this.initGridTabs=Runner.pages.ListPageDash.prototype.initGridTabs;}else if(this.pageMode==Runner.pages.constants.REPORT_DASHDETAILS){this.initGridTabs=Runner.pages.ChartPageDPDash.prototype.initGridTabs;}
Runner.pages.ReportPage.superclass.init.call(this);this.fireEvent('afterInit',this,this.proxy,this.id);if(this.pageMode!==Runner.pages.constants.REPORT_DASHBOARD){this.initDetails();this.initPopupLinks();}
this.initRecordBlock();this.hideExcessSeparators();this.initPageServiceLinks();this.initLinksMore();this.initMaps();this.initCrossControls();this.processDashElemntActions();},initRecordBlock:function(){if(!this.dashboard){Runner.pages.ReportPage.superclass.initRecordBlock.call(this);return;}
var pageObj=this;$("[id='recordspp"+this.id+"']").on("change",function(e){var ajaxURL=pageObj.reportFileName+"?pagesize="+$(this).val(),params=Runner.apply({id:pageObj.pageId},pageObj.baseParams);pageObj.preparePageForReloading();Runner.runnerAJAX(ajaxURL,params,function(respObj){pageObj.pageReloadHn(respObj);});});},processDashElemntActions:function(){var pageObj=this;if(!this.dashboard){return;}
if(this.dashboard.getElementByName(this.dashElement).major||!this.dashAction){this.updContext=this.dashboard.doReloadListAction(this.dashElement,{},this.updContext);}
this.finishDashElementActions();if(this.dashboard.getElementByName(this.dashElement).reload){if(this.reloadTimerId){window.clearTimeout(this.reloadTimerId);}
this.silentReloading=true;this.reloadTimerId=window.setTimeout(function(){pageObj.dashboard.doTimerReloadAction(pageObj.dashElement);},1000*this.dashboard.getElementByName(this.dashElement).reload);}},getSearchControllerConfig:function(){var cfg=Runner.pages.ReportPage.superclass.getSearchControllerConfig.call(this);if(!this.crossTable){return cfg;}
cfg.formBaseParams=this.getCrosstableParams()||Runner.pages.PageSettings.getTableData(this.tName,"crossParams");return cfg;},initPageServiceLinks:function(){if(this.dashboard){return;}
this.initAdvSearch();this.initPrintFrLink();this.initPrintFriendly();this.initExcelLink();this.initWordLink();this.initPDFLink();this.initAdminButton();},initLinksMore:function(){var bindedReportClickHn=$.proxy(this.largeTextOpenerDelegate,this);$(this.getBrickElem((this.isBootstrap()?"bs":"")+"report")).on("click",bindedReportClickHn);$(this.getBrickElem(this.isBootstrap()?"masterlistgrid":"masterinfo")).off("click").on("click",bindedReportClickHn);},initAdvSearch:function(){var pageObj=this;$("[id=advButton"+this.pageId+"]").on("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"search",pageObj.getParamsString());return false;});},initPrintFrLink:function(){var pageObj=this;$("[id=print_"+this.pageId+"]").on("click",function(e){window.open(Runner.getPageUrl(pageObj.shortTName,"print",pageObj.getParamsString()),'wPrint');return false;});},initPrintAll:function(){var pageObj=this;$("[id=printAll_"+this.pageId+"]").on("click",function(e){window.open(Runner.getPageUrl(pageObj.shortTName,"print","all=1"),'wPrint');});},printerFriendlyBtnHandler:function(){if(this.crossTable){window.open(Runner.getPageUrl(this.shortTName,"print")+"?"+this.getParamsString(),"_blank");return;}
Runner.pages.ReportPage.superclass.printerFriendlyBtnHandler.call(this);},initExcelLink:function(){var pageObj=this;$("[id=export_to_excel"+this.pageId+"]").on("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"print","all=1&format=excel&"+pageObj.getParamsString());return false;});},initWordLink:function(){var pageObj=this;$("[id=export_to_word"+this.pageId+"]").on("click",function(e){window.location.href=Runner.getPageUrl(pageObj.shortTName,"print","all=1&format=word&"+pageObj.getParamsString());return false;});},initPDFLink:function(){var pageObj=this;$("[id=export_to_pdf"+this.pageId+"]").on("click",function(e){window.open(Runner.getPageUrl(pageObj.shortTName,"print","all=1&exportPdf=1&"+pageObj.getParamsString()),'wPrint');return false;});},initAdminButton:function(){$("[id=adminArea"+this.id+"]").on("click",function(e){window.location.href=Runner.getPageUrl("admin_rights_list");});},initMaps:function(){if(!this.hasMaps()){return false;}
Runner.globalGmapLoader.onLoad(function(){this.mapManager=new Runner.controls.MapManager(this.controlsMap.gMaps);this.mapManager.init();if(this.isPageInTab()){Runner.pages.PageManager.onTabShown(this,this.mapManager.updateLittleMaps.bind(this.mapManager));}},this);},initCrossControls:function(){if(!this.crossTable||Runner.isMobile){return;}
this.$crossReportTable=$('#crossTable'+this.id);this.initHighlightColor();this.initCrossTableGroupSelection();this.initCrossTableOperationSelection();this.initCrossDataFieldSelection();this.initCrossHiglighting();this.initCrossHover();this.initCrossHeaders();},initHighlightColor:function(){var $tempElem=$('<span class="highlightColor"></span>');$tempElem.insertBefore(this.$crossReportTable);this.colorTrTdHighlight=$tempElem.css("background-color");$tempElem.remove();},initCrossTableGroupSelection:function(){var pageObj=this;if(this.pageMode===Runner.pages.constants.LIST_DASHBOARD&&this.dashboard){this.initDashCrossTableGroupSelection();return;}
$("#select_group_x"+this.id).on("change",function(e){window.location.href=pageObj.reportFileName+"?"+pageObj.getParamsString();return false;});$("#select_group_y"+this.id).on("change",function(e){window.location.href=pageObj.reportFileName+"?"+pageObj.getParamsString();return false;});},initDashCrossTableGroupSelection:function(){if(!this.crossTable||this.pageMode!==Runner.pages.constants.LIST_DASHBOARD||!this.dashboard){return;}
var pageObj=this,reportDashElems=this.dashboard.getDashElements(this.tName,Runner.pages.constants.DASHBOARD_REPORT,this.dashElement);$("#select_group_x"+this.id).on("change",function(e){var additionalParams={baseParams:{criteria:pageObj.baseParams.criteria,q:pageObj.baseParams.q}};additionalParams.baseParams=Runner.apply(additionalParams.baseParams,pageObj.getCrosstableParams());pageObj.dashboard.loadPage(reportDashElems[0],additionalParams);});$("#select_group_y"+this.id).on("change",function(e){var additionalParams={baseParams:{criteria:pageObj.baseParams.criteria,q:pageObj.baseParams.q}};additionalParams.baseParams=Runner.apply(additionalParams.baseParams,pageObj.getCrosstableParams());pageObj.dashboard.loadPage(reportDashElems[0],additionalParams);});},initCrossTableOperationSelection:function(){var pageObj=this,selector=this.isBootstrap()?"#group_func"+this.id:"[name='group_func"+this.id+"']";$(selector).on("change",function(e){pageObj.refreshCrosstable();return false;});},initCrossDataFieldSelection:function(){var pageObj=this;$("#select_data"+this.id).on("change",function(e){pageObj.refreshCrosstable();return false;});},refreshCrosstable:function(){if(!this.crossTable||Runner.isMobile){return;}
var pageObj=this,postParams={id:this.id,crosstable_refresh:true,rndVal:Math.random()};postParams=Runner.apply(postParams,this.getCrosstableParams());pageObj.searchController.srchForm.baseParams=this.getCrosstableParams();if(this.dashboard){postParams.mode="dashreport";postParams.table=this.dashboard.tName;}
Runner.runnerAJAX(this.reportFileName,postParams,function(response){var colsSummary=response["columnSummary"]["data"];$.each(response["rowsInfo"],function(idx,rowInfo){if(isNaN(idx)){return;}
var record=rowInfo["row_record"]["data"],j;for(j=0;j<record.length;j++){$("#"+record[j]["id_data"]+"_"+pageObj.id).html(record[j]["row_value"]).removeClass("rnr-field-text rnr-field-number rnr-field-crossdate").addClass(response["dataClass"]);}
$("#"+rowInfo["id_row_summary"]+"_"+pageObj.id).html(rowInfo["row_summary"]).removeClass("rnr-field-text rnr-field-number rnr-field-crossdate").addClass(response["dataClass"]);});$.each(colsSummary,function(idx,colSummary){$("#"+colSummary["id_col_summary"]+"_"+pageObj.id).html(colSummary["col_summary"]).removeClass("rnr-field-text rnr-field-number rnr-field-crossdate").addClass(response["dataClass"]);});$("#id_total_summary_"+pageObj.id).html(response["totalSummary"]).removeClass("rnr-field-text rnr-field-number rnr-field-crossdate").addClass(response["dataClass"]);;$("#totals1_"+pageObj.id).html(response["totalsName"]);$("#totals2_"+pageObj.id).html(response["totalsName"]);if(pageObj.isBootstrap()){$("#group_func"+pageObj.id).replaceWith(response["groupFuncCtrl"]);}else{$("#group_func").html(response["groupFuncCtrl"]);}
pageObj.initCrossTableOperationSelection();pageObj.reinitCrossHeaders();if(!this.dashboard&&pageObj.pageMode!==Runner.pages.constants.MODE_LIST_DETAILS){Runner.Hash.set(pageObj.getCrosstableParams(),true);}});},getParamsString:function(){if(!this.crossTable){return"";}
var prms=this.getCrosstableParams();return prms?$.param(prms):"";},getCrosstableParams:function(){var $groupX=$("#select_group_x"+this.id),$groupY=$("#select_group_y"+this.id),params,xType,yType,grfunc_value,$grfunc;if(!this.crossTable||!$groupX.length||!$groupY.length){return null;}
params={x:$groupX.val(),y:$groupY.val(),data:$("#select_data"+this.id).val()};xType=$groupX.find(":selected").data("xtype");yType=$groupY.find(":selected").data("ytype");if(xType){params.xtype=xType;}
if(yType){params.ytype=yType;}
if(this.isBootstrap()){params.op=$("#group_func"+this.id).val();return params;}
$grfunc=$("input[name='group_func"+this.id+"']:checked");if(!$grfunc.length){grfunc_value=$("#group_func_hidden").val();}else{grfunc_value=$grfunc.val();}
params.op=grfunc_value===undefined?0:grfunc_value;return params;},initCrossHiglighting:function(){var pageObj=this,controls=[{selector:'#select_data'+this.id,classname:'bs-cross-highligtdata'},{selector:'#group_func'+this.id,classname:'bs-cross-highligtdata'},{selector:'#select_group_y'+this.id,classname:'bs-cross-highligtrowheaders'},{selector:'#select_group_x'+this.id,classname:'bs-cross-highligtcolheaders'},];jQuery.each(controls,function(idx,item){var $itemEl=$(item.selector).on('click',function(e){$itemEl.data('opened',!$itemEl.data('opened'));}).on('blur',function(e){$itemEl.data('opened',false);pageObj.$crossReportTable.removeClass(item.classname);}).hover(function(){pageObj.$crossReportTable.addClass(item.classname);},function(){pageObj.$crossReportTable.toggleClass(item.classname,$itemEl.data('opened'));});});},initCrossHover:function(){var pageObj=this,styleElemId="crossHighlightcol"+this.id;if(!$("style#"+styleElemId).length){$("<style id='"+styleElemId+"'></style>").insertBefore(this.$crossReportTable);}
this.$crossReportTable.find("td:not(.bs-cross-rowheadercell),th:not(.bs-cross-xsel):not(:first-child)").on('mouseenter',function(e){var curColIndex=e.target.cellIndex+1;$("style#"+styleElemId).html('.bs-crosstab[data-highlightcol="'+curColIndex+'"] > * > tr > *:not(.bs-cross-xsel):nth-child('+curColIndex+'){background: '+pageObj.colorTrTdHighlight+';}');pageObj.$crossReportTable.attr('data-highlightcol',curColIndex);}).on('mouseleave',function(e){pageObj.$crossReportTable.removeAttr('data-highlightcol');});},stabilizeCrossDimensions:function(headStabilize){var pageObj=this,colwidths=[],colheights=[],headheights=[];tWidth=this.$crossReportTable.width();headStabilize=headStabilize===undefined?true:headStabilize;this.$crossReportTable.find('tbody > tr:first-child > td').each(function(i,el){colwidths.push($(el).width());});this.$crossReportTable.find('tbody > tr > td:first-child').each(function(i,el){colheights.push($(el).height());});this.$crossReportTable.find('thead > tr > th:first-child').each(function(i,el){headheights.push($(el).height());});this.$crossReportTable.find('tbody > tr:first-child > td').each(function(i,el){$(el).width(colwidths[i]);});this.$crossReportTable.find('thead > tr:nth-child(2) > th').each(function(i,el){$(el).width(colwidths[i]);if(headStabilize){$(el).height(headheights[1]);}});this.$crossReportTable.find('thead > tr:first-child > th:first-child').width(colwidths[0]);if(headStabilize){this.$crossReportTable.find('thead > tr:first-child > *').height(headheights[0]);}
this.$crossReportTable.find('tbody > tr > td:first-child').each(function(i,el){$(el).height(colheights[i]);$(el).width(colwidths[0]);});this.$crossReportTable.find('tbody > tr > td:nth-child(2)').each(function(i,el){$(el).height(colheights[i]);});this.$crossReportTable.width(tWidth);this.$crossReportTable.find('tbody, thead').width(tWidth);},reinitCrossHeaders:function(){},initCrossHeaders:function(){if(this.dashElement||!this.$crossReportTable||!this.$crossReportTable.length){return;}
var pageObj=this,$thead=this.$crossReportTable.find('thead'),attachThead,detachThead,attachCol,detachCol,updateColPosition,updateHeadPosition,theadAttached=true,colAttached=true,$dummy,$win=$(window),$firstCol=this.$crossReportTable.find('tbody > tr > td:first-child'),$testCell=$($firstCol[0]),headBottom,lastScrollPos={top:0,left:0},$theadFirst=this.$crossReportTable.find('thead > tr > th:first-child'),$xSelectCell=this.$crossReportTable.find('thead > tr:first-child > th:not(:first-child)'),oldHeadFirstWidth,$firstDataRow=this.$crossReportTable.find('tbody > tr:first-child > td:not(:first-child)'),$colHeaders=this.$crossReportTable.find('.bs-cross-colheadercell'),$firstDataCell=this.$crossReportTable.find('tbody > tr:first-child > td:nth-child(2)'),$headDummy,$headDummy2,attachHeadDummy,detachHeadDummy,bgColor,bgColor2=$(".table-striped > tbody > tr:nth-of-type(2n+1):first-child").css('background-color');$thead.parents().each(function(i,el){bgColor=$(el).css('background-color');if(bgColor!=''&&bgColor!='transparent'&&bgColor!='none'&&bgColor!='rgba(0, 0, 0, 0)'){return false;}});$('<style>.bs-detachedcolumn.bs-detachedcolumn > tbody > tr:nth-of-type(2n+1) > td.backDummy { background-color:'+bgColor2+';}.bs-detachedcolumn.bs-detachedcolumn > tbody > tr:nth-of-type(2n) >  td.backDummy { background-color:'+bgColor+';}</style>').insertBefore(this.$crossReportTable);this.stabilizeCrossDimensions();$headDummy=$("<th></th>").css('border-right-width','0px').css('width',$firstCol.eq(0).css('width')).css('height',$xSelectCell.outerHeight()+'px');$headDummy2=$("<th><select class='form-control'></select></th>").css('display','block').css('width',$theadFirst.eq(1).css('width'))
$theadFirst.eq(1).height($theadFirst.eq(1).height()+1);attachHeadDummy=function(){$theadFirst.eq(0).before($headDummy);$firstCol.each(function(){$("<td class='backDummy'></td>").css('height',$(this).outerHeight()).css('width',$(this).outerWidth()).insertAfter($(this));});$headDummy2.insertAfter($('.bs-cross-colheaders th:first-child',pageObj.$crossReportTable));};detachHeadDummy=function(){$headDummy.detach();$headDummy2.detach();$(".backDummy",this.$crossReportTable).remove();};headBottom=$thead.offset().top+$thead.height();attachThead=function(){$thead.css('position','static');theadAttached=true;$dummy.remove();headBottom=$thead.offset().top+$thead.height();};detachThead=function(){var height=$thead.height();$dummy=$('<div></div>').height(height).insertBefore(pageObj.$crossReportTable);$thead.css('position','fixed').css('background',bgColor).css('z-index',10).css('top',0);theadAttached=false;updateHeadPosition();headBottom=$dummy.offset().top+$dummy.height();};updateColPosition=function(){var scrollTop=$win.scrollTop();$firstCol.each(function(i,el){$td=$(el);var topPos=($td.next().next().offset().top-scrollTop)+'px'
$td.css('top',topPos);$('.backDummy',$td.parent()).css('top',topPos);});};updateHeadPosition=function(){if(theadAttached&&!colAttached){$thead.css('left',(-$win.scrollLeft())+'px');$theadFirst.css('left','0');$xSelectCell.css('left',($theadFirst.eq(0).outerWidth())+'px');if(pageObj.$crossReportTable.offset().top<=$win.scrollTop()){$theadFirst.eq(0).css('top','0');$xSelectCell.css('top','0');$theadFirst.eq(1).css('top',($colHeaders.eq(0).offset().top-$win.scrollTop())+'px');}else{$theadFirst.eq(0).css('top',(pageObj.$crossReportTable.offset().top-$win.scrollTop())+'px');$xSelectCell.css('top',(pageObj.$crossReportTable.offset().top-$win.scrollTop())+'px');$theadFirst.eq(1).css('top',($colHeaders.eq(0).offset().top-$win.scrollTop())+'px');}}else if(!theadAttached){$thead.css('left',(pageObj.$crossReportTable.offset().left-$win.scrollLeft())+'px');if(pageObj.$crossReportTable.offset().left<=$win.scrollLeft()){$theadFirst.css('left','0');$xSelectCell.css('left',($theadFirst.eq(0).outerWidth())+'px');}else{$theadFirst.css((pageObj.$crossReportTable.offset().left-$win.scrollLeft())+'px');$xSelectCell.css('left',($theadFirst.eq(0).outerWidth())+'px');}
$theadFirst.eq(0).css('top','0');$xSelectCell.css('top','0');$theadFirst.eq(1).css('top',($colHeaders.eq(0).offset().top-$win.scrollTop())+'px');}};attachCol=function(){detachHeadDummy();pageObj.$crossReportTable.removeClass('bs-detachedcolumn');$firstCol.css('position','static');$theadFirst.css('position','static').css('left',null);$xSelectCell.css('position','static').css('left',null);$theadFirst.css('width',oldHeadFirstWidth);$thead.css('left',pageObj.$crossReportTable.offset().left+'px');colAttached=true;};detachCol=function(){$firstCol.css('position','fixed').css('left',0);pageObj.$crossReportTable.addClass('bs-detachedcolumn');oldHeadFirstWidth=$theadFirst.eq(0).css('width');$theadFirst.css('position','fixed');attachHeadDummy();$theadFirst.css('width',$firstCol.css('width'));$theadFirst.css('background',bgColor);$xSelectCell.css('position','fixed');updateHeadPosition();updateColPosition();colAttached=false;};this.reinitCrossHeaders=function(){if(!theadAttached)
attachThead();if(!colAttached)
attachCol();pageObj.stabilizeCrossDimensions(false);$(window).scroll();}
$win.on('scroll',function(){var top=$win.scrollTop(),left=$win.scrollLeft();if(theadAttached){if(top>=pageObj.$crossReportTable.offset().top){detachThead();}}else{if(top<$dummy.offset().top){attachThead();}}
if(colAttached){if(left>=pageObj.$crossReportTable.offset().left){detachCol();}}else{if(left<pageObj.$crossReportTable.offset().left){attachCol();}}
if(!colAttached&&lastScrollPos.top!=top){updateColPosition();updateHeadPosition();}
if(lastScrollPos.left!=left){updateHeadPosition();}
lastScrollPos={top:top,left:left};}).scroll();}});Runner.pages.ChartPageMobile=Runner.extend(Runner.pages.ListPageMobile,{pageType:Runner.pages.constants.PAGE_CHART,constructor:function(cfg){Runner.pages.ChartPageMobile.superclass.constructor.call(this,cfg);this.bricksArr=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","vmenu","searchpanel","backbutton","message","chart","filterpanel","languages","vmsearch2","loggedas"];this.bricksArrList=["masterinfo_mobile","vmenu_mobile","tableinfo_mobile","search_mobile","message","chart","filterpanel","languages","loggedas"];},init:function(){Runner.pages.ChartPageMobile.superclass.init.call(this);this.fireEvent('afterInit',this,this.proxy,this.id);},initButtons:Runner.emptyFn,getSearchBricks:function(){var searchBricks=["searchpanel","backbutton"];if(this.controlsMap.search.googleLikeFields&&this.controlsMap.search.googleLikeFields.length){searchBricks.push("vmsearch2");}
return searchBricks;}});Runner.pages.ChartPage=Runner.extend(Runner.pages.DataPageWithSearch,{pageType:Runner.pages.constants.PAGE_CHART,constructor:function(cfg){Runner.pages.ChartPage.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.ChartPage.superclass.init.call(this);this.initMaps();this.initLinksMore();this.hideExcessSeparators();this.createCharts();this.fireEvent('afterInit',this,this.proxy,this.id);},chartClickHn:function(e){this.largeTextOpenerDelegate(e);},initLinksMore:function(){var bindedChartClickHn=$.proxy(this.chartClickHn,this);$(this.getBrickElem(this.isBootstrap()?'masterlistgrid':'masterinfo')).unbind("click").bind("click",bindedChartClickHn);},initMaps:function(){if(this.getBrickElem('masterinfo')&&this.hasMaps()){Runner.globalGmapLoader.onLoad(function(){this.mapManager=new Runner.controls.MapManager(this.controlsMap.gMaps);this.mapManager.init();},this);}},initDetails:Runner.emptyFn,initGridTabs:Runner.emptyFn,});Runner.pages.ChartPageDP=Runner.extend(Runner.pages.ChartPage,{constructor:function(cfg){Runner.pages.ChartPageDP.superclass.constructor.call(this,cfg);this.pageCont=$('#detailPreview'+this.id).get(0);this.addEvents("afterPageReady");},init:function(){Runner.pages.ChartPageDP.superclass.init.call(this);},preparePageForReloading:function(gridElem){if(!this.silentReloading){Runner.runLoading("",gridElem||this.gridElem);}},});Runner.pages.ChartPageMobileDP=Runner.extend(Runner.pages.ChartPageMobile,{pageParams:null,constructor:function(cfg){Runner.pages.ChartPageMobileDP.superclass.constructor.call(this,cfg);this.hideBricks(["backbutton"]);},init:function(){if(!this.pageParams){return;}
var $chartDiv=$('div#'+this.pageParams.chartName+this.pageParams.id);this.pageParams.width=$chartDiv.width();this.pageParams.height=$chartDiv.height();Runner.Charts.createDPChart(this.pageParams);}});Runner.pages.ReportPageDP=Runner.extend(Runner.pages.ReportPage,{baseParams:null,constructor:function(cfg){Runner.pages.ReportPageDP.superclass.constructor.call(this,cfg);this.addEvents("afterPageReady");this.pageCont=cfg.pageCont||$('#detailPreview'+this.id)[0];this.baseParams=this.baseParams||{id:this.pageId};Runner.apply(this.baseParams,this.controlsMap.masterKeys);},init:function(){Runner.pages.ReportPageDP.superclass.init.call(this);this.loadFiles();},initCrossTableGroupSelection:function(){var pageObj=this;$("#select_group_x"+this.id).on("change",function(e){pageObj.preparePageForReloading(pageObj.detCont[0]);Runner.runnerAJAX(pageObj.reportFileName+"?"+pageObj.getParamsString(),pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});return false;});$("#select_group_y"+this.id).on("change",function(e){pageObj.preparePageForReloading(pageObj.detCont[0]);Runner.runnerAJAX(pageObj.reportFileName+"?"+pageObj.getParamsString(),pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});return false;});},initSearch:Runner.emptyFn,preparePageForReloading:function(gridElem){if(!this.silentReloading){Runner.runLoading("",gridElem||this.gridElem);}},initPagination:function(){var pageObj=this;$.each(this.getBrickObjs('pagination'),function(index,brick){brick.elem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),pageNum,url;if(!$target.is("a")){return;}
pageObj.preparePageForReloading(pageObj.detCont[0]);pageNum=$target.attr("pageNum");url=Runner.pages.getUrl(pageObj.tName,pageObj.pageType)+"?goto="+pageNum;Runner.runnerAJAX(url,pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});});});},pageReloadHn:function(respObj){var parPageObj=Runner.pages.PageManager.getAt(this.masterTName,this.parId);Runner.stopLoading(this.detCont[0]);Runner.setIdCounter(respObj.idStartFrom);respObj.bodyCont=respObj.html;if(Runner.isBootstrap()&&(parPageObj.pageType==Runner.pages.constants.PAGE_EDIT||parPageObj.pageType==Runner.pages.constants.PAGE_ADD||parPageObj.pageType==Runner.pages.constants.PAGE_VIEW)){Runner.pages.PageManager.putToContainer.call(this,respObj,this.detCont);}else{Runner.pages.PageManager.putToDashContainer.call(this,respObj,this.detCont);}
this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.pageId];this.initPagination();this.initGridTabs();if(this.hasMaps()){this.mapManager.init(this.controlsMap.gMaps.mapsData);}
if(respObj.viewControlsMap){this.setupViewContols(respObj.viewControlsMap[this.tName][this.pageType][this.pageId].controls,this.pageCont);}
this.initCrossControls();},destructor:function(){Runner.pages.ReportPageDP.superclass.destructor.call(this);}});Runner.pages.ReportPageMobileDP=Runner.extend(Runner.pages.ReportPageDP,{bricksArr:null,bricksArrList:null,constructor:function(cfg){Runner.pages.ReportPageMobileDP.superclass.constructor.call(this,cfg);this.initLargeTextBackButtonMobileDP();this.useResize=false;this.bricksArr=["backbutton","morelink_mobile","message","report","fulltext_mobile"];this.bricksArrList=["morelink_mobile","message","report",];},largeTextOpenerDelegate:function(e){this.largeTextOpenerDelegateMobile(e);}});Runner.controls.PrintPdf=Runner.extend(Runner.pages.RunnerPage,{maxwidth:0,varmaxheight:0,pdfbuilt:0,noPrintClass:"rp-noprint",loadingPrintClass:"rnr-loading-print",pageType:'',constructor:function(cfg){Runner.apply(this,cfg);Runner.controls.PrintPdf.superclass.constructor.call(this,cfg);},init:function(){this.init=function(){var printPdf=this,$pdfLink=$(".pdflink");$pdfLink.click(function(e){printPdf.getPdfFile();$(this).parent().click();return false;});}
this.init();},CalcMaxPage:function(){this.maxwidth=0;this.maxheight=0;var minleft=999999,mintop=999999,_self=this;containers=$('[name="page"]').each(function(ind,element){if($('table[class*="runner-c-grid"]',element).length>0){element=$('table[class*="runner-c-grid"]',element).eq(0).get(0);}
if(element.offsetWidth>_self.maxwidth){_self.maxwidth=element.offsetWidth;}
if(element.offsetHeight>_self.maxheight){_self.maxheight=element.offsetHeight;}});if(!containers.length){$('div[class*="runner-s-"], div[class*="rnr-s-"]').each(function(index,element){var el=$(element).children(':eq(0)');if(el.hasClass('runner-c-pdf')||el.hasClass('rnr-c-pdf')||!el.length){return;}
if(el[0].offsetLeft+el[0].offsetWidth>_self.maxwidth){_self.maxwidth=el[0].offsetLeft+el[0].offsetWidth;}
if(el[0].offsetTop+el[0].offsetHeight>_self.maxheight){_self.maxheight=el[0].offsetTop+el[0].offsetHeight;}
if(el[0].offsetLeft<minleft){minleft=el[0].offsetLeft;}
if(el[0].offsetTop<mintop){mintop=el[0].offsetTop;}});}
this.maxwidth=this.maxwidth||document.body.scrollWidth;this.maxheight=this.maxheight||document.body.scrollHeight;if(mintop<999999){this.maxheight-=mintop;}
if(minleft<999999){this.maxwidth-=minleft;}},getPdfFile:function(){this.CalcMaxPage();var connector=window.location.href.indexOf('?')>=0?'&':'?',action,timer,cookie="x"+Math.floor(Math.random()*10000000).toString(),divClass=Runner.isBootstrap()?"bs-top":"rnr-page",self=this;$("."+divClass).first().prepend('<div class="'+this.loadingPrintClass+" "+this.noPrintClass+'">'
+Runner.getLoadingBlock(Runner.lang.constants.TEXT_PDF_BUILD1)
+'</div>');action=window.location.href.replace(/#/g,'')+connector+"pdf=build&width="+this.maxwidth+"&rndval="+cookie;if(this.pageType=='view'){action+='&height='+this.maxheight;}
$("<iframe id=pdfiframe name=pdfiframe></iframe>").css({position:"absolute",top:"-1000px"}).appendTo("body");$("<form method='post' style='display:none' target=pdfiframe action='"+action+"'></form>").appendTo("body").submit();timer=setInterval(function(){var error=$("#pdfiframe").contents().find("body").html();if(get_cookie("pdfDownloadedEnd")==cookie){window.parent.$(".rnr-loading-print").remove();clearInterval(timer);}else if(error!=""){self.displayGenericAjaxError(error,Runner.lang.constants.TEXT_PDF_BUILD3);window.parent.$(".rnr-loading-print").remove();clearInterval(timer);}},500);},setDirectlyLink:function(){$('.pdflink').attr("target","_blank").click(function(){var maxwidth=0,maxheight=0,minleft=999999,mintop=999999,isOldLayout=false,containerClass='rnr-s-',emptyClass='rnr-s-empty',containers;containers=$('[name="page"]').each(function(ind,element){if($('table[class*="runner-c-grid"]',element).length>0){element=$('table[class*="runner-c-grid"]',element).eq(0)[0];}
if(element.offsetWidth>maxwidth){maxwidth=element.offsetWidth;}
if(element.offsetHeight>maxheight){maxheight=element.offsetHeight;}});if(!containers.length){isOldLayout=!!$('div[class^="runner-s-"]').length;if(isOldLayout){containerClass='runner-s-';emptyClass='runner-s-empty';}
containers=$('div[class*="'+containerClass+'"]').not('.'+emptyClass).each(function(){var jQElement=$(this),firstChild=jQElement.children(':eq(0)');if(firstChild[0].offsetLeft+firstChild[0].offsetWidth>maxwidth){maxwidth=firstChild[0].offsetLeft+firstChild[0].offsetWidth;}
if(firstChild[0].offsetTop+firstChild[0].offsetHeight>maxheight){maxheight=firstChild[0].offsetTop+firstChild[0].offsetHeight;}
if(firstChild[0].offsetLeft<minleft){minleft=firstChild[0].offsetLeft;}
if(firstChild[0].offsetTop<mintop){mintop=firstChild[0].offsetTop;}});}
maxwidth=maxwidth||document.body.scrollWidth;maxheight=maxheight||document.body.scrollHeight;if(mintop<999999){maxheight-=mintop;}
if(minleft<999999){maxwidth-=minleft;}
$(this).attr("href","buildpdf.php?url="+encodeURIComponent(window.location)
+'&width='+maxwidth+'&height='+maxheight+'&rndval='+Math.random());});}});Runner.pages.PrintPageCommon=Runner.extend(Runner.pages.RunnerPage,{pageType:Runner.pages.constants.PAGE_PRINT,pageHeight:Runner.pages.constants.VPRINT_PAGE_HEIGHT,pageWidth:Runner.pages.constants.VPRINT_PAGE_WIDTH,repeatClass:"rp-repeat",hideClass:"rp-hide",tableClass:"rp-maintable",pageNoClass:"rp-pageno",noPrintClass:"rp-noprint",pageCountClass:"rp-pagecount",loadingPrintClass:"rnr-loading-print",divideIntoPagesLoadingClass:"divideintopagesloading",divideIntoPagesButtonClass:"divideintopages",zoom:100,preSplit:false,autoZoom:false,edgeClass:"rnr-edge",contentWidth:Runner.pages.constants.VPRINT_PAGE_WIDTH,pages:[],layout:0,pdfFitToPage:1,pdfSplitByRecords:0,createPdf:false,exportPdf:true,hasPdf:false,isRTL:false,$noPrintElements:null,getContentWidth:function(){if(!this.isBootstrap()){return $(".rnr-center").width();}
return $(".rp-page").width()||document.body.clientWidth;},init:function(){Runner.pages.PrintPageCommon.superclass.init.call(this);var pageObj=this;this.contentWidth=this.getContentWidth();if(this.preSplit&&this.autoZoom){$(".rp-page").each(function(i,page){var $page=$(page),wZoom=100.0*pageObj.pageWidth/$page.width(),hZoom=100.0*pageObj.pageHeight/$page.height(),zoom=hZoom<wZoom?hZoom:wZoom;if(zoom>120){zoom=120;}
$page.addClass("page"+i);$("<style>@media print { .page"+i+" { zoom:"+zoom+"%;} }</style>").appendTo(document.head);});}else{if(this.autoZoom){this.zoom=100.0*this.pageWidth/this.contentWidth;this.zoom=this.zoom>120.0?120.0:this.zoom;}
this.pageWidth*=(100.0/this.zoom);this.pageHeight*=(100.0/this.zoom);$("<style>@media print { body { zoom:"+this.zoom+"%;} }</style>").appendTo(document.head);}
this.setPrintOrientation();},constructor:function(cfg){Runner.pages.PrintPageCommon.superclass.constructor.call(this,cfg);this.createPdf=this.proxy.createPdf;if(this.createPdf){this.zoom=Runner.pages.PageSettings.getTableData(this.tName,"pdfPrinterPageScale");this.autoZoom=Runner.pages.PageSettings.getTableData(this.tName,"pdfFitToPage");this.landscapeOrientation=Runner.pages.PageSettings.getTableData(this.tName,"pdfPrinterPageOrientation");this.preSplit=false;}else{this.zoom=Runner.pages.PageSettings.getTableData(this.tName,"printerPageScale");this.autoZoom=Runner.pages.PageSettings.getTableData(this.tName,"isPrinterPageFitToPage");this.landscapeOrientation=Runner.pages.PageSettings.getTableData(this.tName,"printerPageOrientation");this.preSplit=Runner.pages.PageSettings.getTableData(this.tName,"printerSplitRecords")!=0;}
this.layout=Runner.pages.PageSettings.getTableData(this.tName,"printGridLayout");if(this.landscapeOrientation){this.pageWidth=Runner.pages.constants.HPRINT_PAGE_WIDTH;this.pageHeight=Runner.pages.constants.HPRINT_PAGE_HEIGHT;}
this.pdfFitToPage=Runner.pages.PageSettings.getTableData(this.tName,"pdfFitToPage");this.exportPdf=Runner.pages.PageSettings.getTableData(this.tName,"exportPdf");this.hasPdf=Runner.pages.PageSettings.getTableData(this.tName,"printerPagePDF");this.isRTL=Runner.pages.PageSettings.getTableData(this.tName,"isRTL");this.pdfSplitByRecords=Runner.pages.PageSettings.getTableData(this.tName,"printerPDFSplitRecords");},newPage:function(){var tableClass=this.tableClass;return{$page:$("<div class=rp-page></div>"),height:0,$tbody:function(){return this.$page.find("."+tableClass+" > tbody").first();}};},addPage:function(insertAfterIdx,cloneTableOnly){var newPage=this.newPage();if(typeof insertAfterIdx=="undefined"){insertAfterIdx=this.pages.length-1;newPage.$page.appendTo(document.body);}else{this.pages[insertAfterIdx].$page.after(newPage.$page);}
insertAfterIdx++;this.pages.splice(insertAfterIdx,0,newPage);this.cloneBranch(this.pages[0].$page,newPage.$page,cloneTableOnly);newPage.height=newPage.$page.height();return insertAfterIdx;},cloneBranch:function($from,$to,skipRepeat){var pageObj=this;$from.children().each(function(i,elem){var $elem=$(elem),$cloned=null;if($elem.hasClass(pageObj.hideClass)){return;}
if($elem.hasClass(pageObj.tableClass)){$cloned=$(Runner.domShallowCopy(elem)).appendTo($to).append(!skipRepeat?$elem.children("THEAD").clone():$("<thead></thead>")).append($("<tbody></tbody>"));return;}
if($elem.hasClass(pageObj.repeatClass)){$elem.clone().appendTo($to);}else if($elem.find("."+pageObj.repeatClass).length||$elem.find("."+pageObj.tableClass).length){$cloned=$(Runner.domShallowCopy(elem)).appendTo($to);pageObj.cloneBranch($elem,$cloned,skipRepeat);}});},addFirstPage:function(){var newPage=this.newPage();$(document.body).children(":not(meta):not(script):not(style):not(title):not(link):not(iframe)").appendTo(newPage.$page);newPage.$page.appendTo(document.body);this.pages.push(newPage);},splitTableByRows:function(){var pageObj=this,currentPageId=0,$rows=[],firstPageTop,firstPageHeight,$table,firstPageAddOn,rowsSelector=this.layout==Runner.pages.constants.COLUMNS_LAYOUT?"."+this.tableClass:"."+this.tableClass+" > TBODY";Runner.Async.loop([null],function(){firstPageHeight=pageObj.pages[0].$page.height();firstPageTop=pageObj.pages[0].$page.offset().top;$table=pageObj.pages[0].$page.find("."+pageObj.tableClass);firstPageAddOn=firstPageHeight+firstPageTop-($table.offset().top+$table.height());pageObj.pages[0].$page.find(rowsSelector).children().each(function(i,row){$rows.push($(row));});});Runner.Async.loop($rows,function(i,$row){$row.height($row.height()+'px');$row.children().each(function(cellId,cell){var $cell=$(cell);$cell.height($cell.height()+'px');});if(0==currentPageId&&$row.offset().top+$row.height()-firstPageTop+firstPageAddOn<pageObj.pageHeight){return;}
if(0==currentPageId||currentPageId>0&&$row.height()+pageObj.pages[currentPageId].$page.height()>pageObj.pageHeight){currentPageId=pageObj.addPage();}
if(pageObj.layout==Runner.pages.constants.COLUMNS_LAYOUT){$row=$row.children();}
pageObj.pages[currentPageId].$tbody().append($row);});},copyTableColumns:function($srcTable,$dstTable,startCol){var pageObj=this;$.each(["thead","tbody"],function(_i,tag){var $rows=$srcTable.children(tag).children(),$rowContainer=null;if(0==$rows.length){return;}
$rowContainer=$(Runner.domShallowCopy($srcTable.children(tag).get(0))).appendTo($dstTable);$rows.each(function(_i,row){var $dstRow=$(Runner.domShallowCopy(row)).appendTo($rowContainer);$(row).children().slice(startCol).appendTo($dstRow);$(row).children().last().addClass(pageObj.edgeClass);});});},splitTableByColums:function(){if(this.autoZoom){return;}
var pageObj=this;Runner.Async.loop(this.pages,function(idx,page){Runner.Async.loop(page.$page.find("."+pageObj.tableClass+" > thead > tr").children(),function(col,cell){var $cell=$(cell),newPageId;$cell.width($cell.width()+"px");if(pageObj.getLeftOffset($cell)+$cell.width()<pageObj.pageWidth||$cell.hasClass(pageObj.edgeClass)){return;}
newPageId=pageObj.addPage(idx,true);pageObj.copyTableColumns(page.$page.find("."+pageObj.tableClass),pageObj.pages[newPageId].$page.find("."+pageObj.tableClass),col);return false;});});},setPageNumbers:function(){var pageObj=this;Runner.Async.loop([null],function(){var idx,$h1;for(idx=0;idx<pageObj.pages.length;++idx){$h1=pageObj.pages[idx].$page.find("h1");$h1.css("height",$h1.height()+"px");pageObj.pages[idx].$page.find("."+pageObj.pageNoClass).text(idx+1);}
$("."+pageObj.pageCountClass).text(pageObj.pages.length);});},setPrintOrientation:function(){if(Runner.pages.PageSettings.getTableData(this.tName,"printerPageOrientation")!==Runner.pages.constants.PORTRAIT_PRINT_ORIENTATION){$("link:first").before('<style type="text/css" media="print">@page { size: landscape; }</style>');}},setPdfFitToPageParams:function(){if(!this.createPdf||!this.pdfFitToPage){return;}
var scale=this.pageHeight/this.pageWidth,$table=$("."+this.tableClass).first();this.pageWidth=$table.width()+this.getLeftOffset($table);this.pageHeight=this.pageWidth*scale;},initPdf:function(){var pageObj=this,$pdfLink=$(".pdflink");if(!pageObj.hasPdf){return;}
if(pageObj.createPdf){Runner.Async.loop(jQuery.proxy(pageObj.convertPdfFile,pageObj));return;}
if(!this.pdfSplitByRecords){$pdfLink.click(function(e){pageObj.openPrintPdfPageInIframe();$pdfLink.hide();return false;});}else{$pdfLink.click(function(e){pageObj.getPdfFile();$pdfLink.hide();return false;});}
if(pageObj.exportPdf){pageObj.getPdfFile();$pdfLink.hide();}},createDivideIntoPagesLoading:function(){if(this.createPdf){return;}
$(".rnr-page").first().prepend('<div class="'+this.loadingPrintClass+" "+this.divideIntoPagesLoadingClass+" "+this.noPrintClass+'">'
+Runner.getLoadingBlock(Runner.lang.constants.PREPARE_PAGE_FOR_PRINTING)+'</div>');},destroyDivideIntoPagesLoading:function(){if(this.createPdf){return;}
var pageObj=this;Runner.Async.loop([null],function(){$("."+pageObj.divideIntoPagesLoadingClass).remove();});},openPrintPdfPageInIframe:function(){var src=window.location.href+(window.location.href.indexOf("?")>=0?"&":"?")+"pdf=prepare";src+="&selectedRecords="+this.controlsMap.pdfSettings.selectedJSON;src+="&detailTables="+this.controlsMap.pdfSettings.detailTablesJSON;src+="&allPagesMode="+this.controlsMap.pdfSettings.allPagesMode;$("<iframe></iframe>").css({position:"absolute",top:"-10000px",width:$(window).width()+"px",height:$(window).height()+"px",}).appendTo("body").attr("src",src);$("."+(Runner.isBootstrap()?"bs-top":"rnr-page")).first().prepend('<div class="'+this.loadingPrintClass+" "+this.noPrintClass+'">'
+Runner.getLoadingBlock(Runner.lang.constants.TEXT_PDF_BUILD1)
+'</div>');},getLeftOffset:function($obj){if(this.isRTL){return $(window).width()-($obj.offset().left+$obj.outerWidth());}else{return $obj.offset().left;}},afterPagesDivided:function(){if(this.createPdf){$(".rp-page").last().css("page-break-after","auto");return;}
$(document.body).addClass("rp-divided");$("<style>@media screen { .rp-page{ width:"+(this.pageWidth+20)+"px;height:"+(this.pageHeight+20)+"px }} </style>").appendTo(document.head);$("<style>@media print { .rp-page{ width:"+(this.pageWidth)+"px;height:"+(this.pageHeight)+"px }} </style>").appendTo(document.head);if(this.$noPrintElements){this.$noPrintElements.css('display','');}},getPdfFile:function(){var connector=window.location.href.indexOf('?')>=0?'&':'?',action,timer,cookie="x"+Math.floor(Math.random()*10000000).toString(),self=this,div_class=Runner.isBootstrap()?"bs-top":"rnr-page";$("."+div_class).first().prepend('<div class="'+this.loadingPrintClass+" "+this.noPrintClass+'">'
+Runner.getLoadingBlock(Runner.lang.constants.TEXT_PDF_BUILD1)
+'</div>');action=window.location.href.replace(/#/g,'')+connector+"pdf=build&width="+this.contentWidth+"&rndval="+cookie;$("<iframe id=pdfiframe name=pdfiframe></iframe>").css({position:"absolute",top:"-1000px"}).appendTo("body");$form=$("<form method='post' style='display:none' target=pdfiframe action='"+action+"'></form>");if(this.pageType==Runner.pages.constants.PAGE_REPORT_PRINT){$form.append("<input type='hidden' name='all' value='"+this.controlsMap.pdfSettings.allPagesMode+"'>");}else{$form.append("<input type='hidden' name='selectedJSON' value='"+this.controlsMap.pdfSettings.selectedJSON+"'>");$form.append("<input type='hidden' name='detailTablesJSON' value='"+this.controlsMap.pdfSettings.detailTablesJSON+"'>");$form.append("<input type='hidden' name='allPagesMode' value='"+this.controlsMap.pdfSettings.allPagesMode+"'>");}
$form.appendTo("body").submit();timer=setInterval(function(){var error=$("#pdfiframe").contents().find("body").html();if(get_cookie("pdfDownloadedEnd")==cookie){window.parent.$(".rnr-loading-print").remove();clearInterval(timer);}else if(error!=""){self.displayGenericAjaxError(error,Runner.lang.constants.TEXT_PDF_BUILD3);window.parent.$(".rnr-loading-print").remove();clearInterval(timer);}},500);},convertPdfFile:function(){var connector=window.location.href.indexOf('?')>=0?'&':'?',action,timer,cookie="x"+Math.floor(Math.random()*10000000).toString();action=Runner.getPageUrl(this.shortTName,"print","pdf=convert&width="+this.pageWidth+"&rndval="+cookie);$("script").remove();$("<iframe id=pdfiframe name=pdfiframe></iframe>").appendTo("body");$("<form method='post' style='display:none' target=pdfiframe action='"+action+"'>"
+"<textarea name='htmlPdfContent'>"
+"<html>"+$("html").html()+"</html>"
+"</textarea>"
+"</form>").appendTo("body").submit();timer=setInterval(function(){if(get_cookie("pdfDownloadedEnd")==cookie){window.parent.$(".rnr-loading-print").remove();clearInterval(timer);}},500);}});Runner.pages.PrintPage=Runner.extend(Runner.pages.PrintPageCommon,{constructor:function(cfg){Runner.pages.PrintPage.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.PrintPage.superclass.init.call(this);this.initColumnReordering();if(this.createPdf){this.divideIntoPages();}
this.initPdf();this.fireEvent('afterInit',this,this.proxy,this.id);},initDivideIntoPagesButton:function(){$("."+this.divideIntoPagesButtonClass).click($.proxy(this.divideIntoPages,this));},divideIntoPages:function(){var pageObj=this;this.$noPrintElements=$("."+this.noPrintClass+":visible");this.$noPrintElements.hide();$("."+this.divideIntoPagesButtonClass).hide();this.createDivideIntoPagesLoading();this.addFirstPage();switch(this.layout){case Runner.pages.constants.VERTICAL_LAYOUT:this.splitVerticalTableByColums();this.splitVerticalTableByRows();break;case Runner.pages.constants.COLUMNS_LAYOUT:this.splitColumnsTableByColumns();this.splitColumnsTableByRows();break;default:this.splitTableByRows();this.splitTableByColums();}
Runner.Async.loop(jQuery.proxy(this.afterPagesDivided,this));this.setPageNumbers();this.destroyDivideIntoPagesLoading();return false;},splitVerticalTableByRows:function(){var pageObj=this,verticalTableBody="td > table > tbody",rows=[],idx,$newRow,$rowTables,$newRowTables,i,copyTheRest;Runner.Async.loop([null],function(){pageObj.pages[0].$page.find("."+pageObj.tableClass+" > TBODY").children().each(function(rowId,row){rows.push($(row));});});Runner.Async.loop(rows,function(idx,$row){if($row.height()<pageObj.pageHeight){return;}
$newRow=$row.clone();$newRowTables=$newRow.find(verticalTableBody).empty();$row.after($newRow)
rows.splice(idx+1,0,$newRow);$rowTables=$row.find(verticalTableBody);for(i=0;i<$rowTables.length;++i){copyTheRest=false;$rowTables.eq(i).children().each(function(j,vrow){var $vrow=$(vrow);if(($vrow.offset().top-$row.offset().top+$vrow.height()<pageObj.pageHeight)&&!copyTheRest){return;}
copyTheRest=true;$vrow.appendTo($newRowTables[i]);});if(!$newRowTables.eq(i).children().length){$newRowTables.eq(i).parent().remove();}}});pageObj.splitTableByRows();},clearVerticalTablesAndSetWidth:function(){var pageObj=this,$table=this.pages[0].$page.find("."+this.tableClass+" > TBODY"),$rows;$table.children().remove(".rnr-rs");$rows=$table.children();$rows.find(".rnr-cs").remove();Runner.Async.loop($rows,function(rowIdx,row){$(row).children().each(function(cellIdx,cell){var $cell=$(cell);$cell.data("width",$cell.width()).data("offset-left",pageObj.getLeftOffset($cell));});});},splitVerticalTableByColums:function(){var pageObj=this,rows=[],$table,idx,verticalTables,copyTheRest,lastRow,$nextRow;this.clearVerticalTablesAndSetWidth();$table=this.pages[0].$page.find("."+this.tableClass+" > TBODY");Runner.Async.loop([null],function(){$table.children().each(function(rowId,row){rows.push($(row));});});Runner.Async.loop(rows,function(idx,$row){verticalTables=[];copyTheRest=false;lastRow=idx===rows.length-1;$row.children().each(function(i,cell){var $cell=$(cell);$cell.css("min-width",$cell.data("width")+"px");if(($cell.data("offset-left")+$cell.data("width")<pageObj.pageWidth||i==0)&&!copyTheRest){return;}
copyTheRest=true;verticalTables.push($cell);});if(verticalTables.length){if(lastRow){$nextRow=$("<tr></tr>").appendTo($table);rows.push($nextRow);}else{$nextRow=rows[idx+1];}
while(verticalTables.length){$nextRow.prepend(verticalTables.pop());}}});},splitColumnsTableByRows:function(){var pageObj=this,records=[],$newRecord,recordRows,copyTheRest,$recordRow;Runner.Async.loop([null],function(){pageObj.pages[0].$page.find("."+pageObj.tableClass).children().each(function(recordId,record){records.push($(record));});});Runner.Async.loop(records,function(idx,$record){if($record.height()<pageObj.pageHeight){return;}
$newRecord=$record.clone();$newRecord.find(".rnr-row").empty();$record.after($newRecord)
records.splice(idx+1,0,$newRecord);recordRows=$record.find(".rnr-row");recordRows.each(function(idx){copyTheRest=false;$recordRow=recordRows.eq(idx);if(($recordRow.offset().top-$record.offset().top+$recordRow.height()<pageObj.pageHeight)&&!copyTheRest){return;}
copyTheRest=true;$recordRow.appendTo($newRecord);});});this.splitTableByRows();},setWidthColumnsTables:function(){var pageObj=this;Runner.Async.loop(this.pages[0].$page.find("."+this.tableClass).children(),function(recordIdx,record){$(record).find(".rnr-row > td").each(function(recordCellIdx,recordCell){var $recordCell=$(recordCell);$recordCell.data("width",$recordCell.width()).data("offset-left",pageObj.getLeftOffset($recordCell));});});},splitColumnsTableByColumns:function(){var pageObj=this,records=[];this.setWidthColumnsTables();Runner.Async.loop([null],function(){pageObj.pages[0].$page.find("."+pageObj.tableClass).children().each(function(recordIdx,record){records.push($(record));});});Runner.Async.loop(records,function(recordIdx,$record){var $recordRows=$record.find(".rnr-row"),recordRowCellsCount=Math.round($record.find("tr:nth-child(2)").children().length/2),recordRowCellsCountArr=new Array(recordRowCellsCount),allCells=[],splitCell=1,i,rowsPerRecord,edgeRecord;if($record.width()<pageObj.pageWidth){return;}
Runner.Async.loop(recordRowCellsCountArr,function(j){$recordRows.each(function(recordRowIdx,recordRow){var $recordRow=$(recordRow),recordRowCells=$recordRow.children(),$recordRowCellLabel=recordRowCells.eq(j*2),$recordRowCellValue=recordRowCells.eq(j*2+1);$recordRowCellLabel.width($recordRowCellLabel.data("width")+"px");$recordRowCellValue.width($recordRowCellValue.data("width")+"px");if($recordRowCellValue.data("offset-left")+$recordRowCellValue.data("width")>pageObj.pageWidth&&splitCell==1&&j>0){splitCell=j;}
if($recordRowCellLabel.html()!="&nbsp;"){allCells.push($recordRowCellLabel);allCells.push($recordRowCellValue.removeClass(pageObj.edgeClass));}});});Runner.Async.loop([null],function(){$recordRows.remove();rowsPerRecord=Math.ceil(Math.ceil(allCells.length/2)/splitCell);edgeRecord=rowsPerRecord*splitCell*2-rowsPerRecord*2;$record.find("tr:first > td:first").attr("colspan",splitCell*2);for(i=0;i<rowsPerRecord;++i){$record.append('<tr class="rnr-row"></tr>');}
i=0;$recordRows=$record.find(".rnr-row");while(i<allCells.length){$recordRows.each(function(recordRowIdx,recordRow){var emptyCell="<td>&nbsp;</td>",$label=allCells[i]||$(emptyCell),$value=allCells[i+1]||$(emptyCell);if(i>=edgeRecord){$value.addClass(pageObj.edgeClass);}
$(recordRow).append($label).append($value);i+=2;});}});});},getPrintGrid:function(){var bricks=this.getBrickObjs('printgrid');if(bricks.length){return bricks[0].elem;}
return null;},initColumnReordering:function(){if(!Runner.pages.PageSettings.getTableData(this.tName,"isAllowFieldsReordering")){return;}
var columnOrder=Runner.pages.PageSettings.getTableData(this.tName,"columnOrder"),$grid=$(this.getPrintGrid()),i,indices=[],tail=[],orderedIndices=[];if(!$grid.length||!columnOrder.length){return;}
$("th",$grid).not(this.inDetailPreviewContainer).each(function(ind,th){var $th=$(th),gfName=$(th).data("field"),colInd=$.inArray(gfName,columnOrder);if(colInd!==-1){indices[colInd]=ind;}else{tail.push(ind);}});orderedIndices=indices.filter(function(value){return value!==undefined;});if(!orderedIndices.length){return;}
orderedIndices=orderedIndices.concat(tail);$("tr",$grid).not(this.isDetailContainer).each(function(ind,tr){var $tds=$("th, td",tr),$tr=$(tr),i;for(i=0;i<orderedIndices.length;i++){$tr.append($tds.eq(orderedIndices[i]));}});},isDetailContainer:function(){return!!$(this).find(".rnr-print-details").length;},inDetailPreviewContainer:function(){return!!$(this).closest('.rnr-print-details').length;}});Runner.pages.ReportPrintPage=Runner.extend(Runner.pages.PrintPageCommon,{pageType:Runner.pages.constants.PAGE_REPORT_PRINT,tableClass:"rnr-report",$summaryHeader:null,$summaryPage:null,$summaryGlobal:null,summaryPageHeight:0,reportPrintMode:0,groupsPerPage:3,partitionType:0,reportLayout:0,lowGroup:1,reportType:0,constructor:function(cfg){Runner.pages.ReportPrintPage.superclass.constructor.call(this,cfg);this.reportLayout=Runner.pages.PageSettings.getTableData(this.tName,"reportPrintLayout");this.reportPrintMode=Runner.pages.PageSettings.getTableData(this.tName,"reportPrintMode");this.partitionType=Runner.pages.PageSettings.getTableData(this.tName,"reportPrintPartitionType");this.groupsPerPage=Runner.pages.PageSettings.getTableData(this.tName,"reportPrintGroupsPerPage");this.lowGroup=Runner.pages.PageSettings.getTableData(this.tName,"lowGroup");this.reportType=Runner.pages.PageSettings.getTableData(this.tName,"reportType");if(this.reportLayout==Runner.pages.constants.TABULAR_LAYOUT){this.tableClass="rnr-b-report";}
if(this.reportType==Runner.pages.constants.REPORT_TYPE_CROSSTAB){this.tableClass="rnr-cw-grid";}
this.pdfSplitByRecords=3;this.setPdfFitToPageParams();},init:function(){Runner.pages.ReportPrintPage.superclass.init.call(this);if(this.createPdf){this.divideIntoPages();}
this.initDivideIntoPagesButton();this.initPdf();this.fireEvent('afterInit',this,this.proxy,this.id);},initDivideIntoPagesButton:function(){$("."+this.divideIntoPagesButtonClass).click($.proxy(this.divideIntoPages,this));},divideIntoPages:function(){if(this.reportType===Runner.pages.constants.REPORT_TYPE_CROSSTAB)
return false;$("."+this.divideIntoPagesButtonClass).hide();this.$noPrintElements=$("."+this.noPrintClass+":visible");this.$noPrintElements.hide();this.createDivideIntoPagesLoading();this.addFirstPage();this.setTotalsData();this.splitReportTableByRows();this.splitReportTableByColums();this.setPageNumbers();Runner.Async.loop(jQuery.proxy(this.afterPagesDivided,this));this.destroyDivideIntoPagesLoading();return false;},splitReportTableByRows:function(){if(this.reportPrintMode==Runner.pages.constants.REPORT_MODE_PRINT_FRIENDLY){this.splitReportTableOnPrintFriendlyMode();}else{this.splitReportTableOnPrintWholeMode();}},splitReportTableOnPrintFriendlyMode:function(){var pageObj=this;this.splitTableByRows();Runner.Async.loop([null],function(){pageObj.setTotalsDataToPage(pageObj.pages.length-1,pageObj.$summaryHeader);pageObj.setTotalsDataToPage(pageObj.pages.length-1,pageObj.$summaryPage);pageObj.setTotalsDataToPage(pageObj.pages.length-1,pageObj.$summaryGlobal);});},splitReportTableOnPrintWholeMode:function(){var pageObj=this;if(this.partitionType==Runner.pages.constants.REPORT_PRINT_PAGE_FIT){this.splitReportTableByRowsPageFit();Runner.Async.loop([null],function(){pageObj.calculatePageSummary(pageObj.lowGroup);});}else{this.splitReportTableByRowsPerPrintedPage();Runner.Async.loop([null],function(){pageObj.calculatePageSummary(1);});}},calculatePageSummary:function(groupLevel){var pageObj=this,$pageBody,$pageSummary,result={};Runner.Async.loop(this.pages,function(idx,page){$pageBody=page.$tbody();$pageBody.find(".summary-"+groupLevel).each(function(cellId,cell){var $cell=$(cell),type=$cell.data("type"),field=$cell.data("field")||"total",value=$cell.data("value");result=pageObj.calculateGroupsSummary(type,field,value,result);});$pageSummary=$pageBody.find(".page-summary");$pageSummary.each(function(cellId,cell){var $cell=$(cell),type=$cell.data("type"),field=$cell.data("field")||"total",avgValue=0,avgArr,i;if(result[type]&&result[type][field]){if(type=="avg"){avgArr=result[type][field];for(i=0;i<avgArr.length;++i){if(!isNaN(avgArr[i])){avgValue+=avgArr[i];}}
result[type][field]=avgValue/avgArr.length;}
$cell.html(result[type][field]);}});if($pageSummary.length){result={};}});},calculateGroupsSummary:function(type,field,value,result){result[type]=result[type]||{};if(type=="min"||type=="max"){if(typeof result[type][field]=="undefined"&&value!==""){result[type][field]=value;}}else{if(isNaN(result[type][field])){result[type][field]=0;}
if(isNaN(value)){value=0;}}
switch(type){case"sum":result[type][field]+=value;break;case"max":if(value>result[type][field]&&value!==""){result[type][field]=value;}
break;case"min":if(value<result[type][field]&&value!==""){result[type][field]=value;}
break;case"avg":if(!result[type][field]){result[type][field]=[];}
result[type][field].push(value);break;default:result[type][field]=(result[type][field]||0)+value;}
return result;},splitReportTableByRowsPerPrintedPage:function(){var pageObj=this,$rows,$pageBody,pageOffsetTop,pageIdx,groupsCount;Runner.Async.loop(this.pages,function(idx,page){$pageBody=page.$tbody();$rows=page.$page.find("."+pageObj.tableClass+" > TBODY").children();groupsCount=0;Runner.Async.loop($rows,function(rowIdx,row){var $row=$(row);$row.height($row.height()+'px');if($row.hasClass("group-spliter-1")){groupsCount++;}
if(groupsCount<pageObj.groupsPerPage+1){return;}
pageIdx=pageObj.addPage();$pageBody.children().slice(rowIdx).appendTo(pageObj.pages[pageIdx].$tbody());pageObj.setTotalsDataToPage(idx,pageObj.$summaryPage);return false;});});Runner.Async.loop([null],function(){pageObj.setTotalsDataToPage(pageObj.pages.length-1,pageObj.$summaryPage);pageIdx=pageObj.addPage();pageObj.setTotalsDataToPage(pageIdx,pageObj.$summaryHeader);pageObj.setTotalsDataToPage(pageIdx,pageObj.$summaryGlobal);});Runner.Async.loop(this.pages,function(idx,page){pageOffsetTop=page.$page.offset().top;$pageBody=page.$tbody();$rows=page.$page.find("."+this.tableClass+" > TBODY").children();if($pageBody.height()>pageObj.pageHeight){$rows.each(function(rowIdx,row){var $row=$(row);if($row.offset().top+$row.height()-pageOffsetTop<pageObj.pageHeight){return;}
pageIdx=pageObj.addPage(idx,true);$pageBody.children().slice(rowIdx).appendTo(pageObj.pages[pageIdx].$tbody());return false;});}});},splitReportTableByRowsPageFit:function(){var pageObj=this,splitInfo,pageIdx,$pageBody,transferOneLowGroup=false;Runner.Async.loop(this.pages,function(idx,page){$pageBody=page.$tbody();splitInfo=pageObj.getSplitRowPageFit(idx,transferOneLowGroup);if(!splitInfo.splitRow){pageObj.setTotalsDataToPage(idx,pageObj.$summaryHeader);pageObj.setTotalsDataToPage(idx,pageObj.$summaryPage);pageObj.setTotalsDataToPage(idx,pageObj.$summaryGlobal);return false;}
pageIdx=pageObj.addPage();$pageBody.children().slice(splitInfo.splitRow).appendTo(pageObj.pages[pageIdx].$tbody());if((transferOneLowGroup||splitInfo.lowGroupsCount>1)&&splitInfo.lowGroupsCount){pageObj.setTotalsDataToPage(idx,pageObj.$summaryPage);transferOneLowGroup=false;return;}
transferOneLowGroup=true;});},getSplitRowPageFit:function(pageIdx,returnOnFinedFirstLowGroup){if(!this.pages[pageIdx]){return;}
var pageObj=this,pageOffsetTop=this.pages[pageIdx].$page.offset().top,$rows=this.pages[pageIdx].$page.find("."+this.tableClass+" > TBODY").children(),lastLowGroupIdx=0,lowGroupsCount=0,splitRow=0;$rows.each(function(rowIdx,row){var $row=$(row);$row.height($row.height()+'px');if($row.hasClass("group-spliter-"+pageObj.lowGroup)){lastLowGroupIdx=rowIdx;lowGroupsCount++;}
if($row.offset().top+$row.height()+pageObj.summaryPageHeight-pageOffsetTop<pageObj.pageHeight&&!(returnOnFinedFirstLowGroup&&lowGroupsCount)){return;}
splitRow=lowGroupsCount>1?lastLowGroupIdx:rowIdx;return false;});return{lowGroupsCount:lowGroupsCount,splitRow:splitRow};},splitReportTableByColums:function(){var pageObj=this,groupHeadersClass=this.reportLayout==Runner.pages.constants.TABULAR_LAYOUT?"table-header":"group-headers",$groupHeaders;Runner.Async.loop([null],function(){$("."+groupHeadersClass).children().each(function(col,cell){var $cell=$(cell);$cell.width($cell.width()+"px");$cell.attr("data-width",$cell.width());});$groupHeaders=$("."+groupHeadersClass).first().clone();});Runner.Async.loop(this.pages,function(idx,page){var $cells=[];if(!page.$page.find("."+groupHeadersClass).children().length){page.$tbody().prepend($groupHeaders.clone());}
page.$page.find("."+groupHeadersClass).children().each(function(col,cell){$cells.push($(cell));});Runner.Async.loop($cells,function(col,$cell){var newPageId;if(pageObj.getLeftOffset($cell)+$cell.data("width")<pageObj.pageWidth||$cell.hasClass(pageObj.edgeClass)){return;}
newPageId=pageObj.addPage(idx,true);pageObj.copyReportTableColumns(page.$page.find("."+pageObj.tableClass),pageObj.pages[newPageId].$page.find("."+pageObj.tableClass),(col<=1?1:col-1),$groupHeaders.children().length);return false;});});},copyReportTableColumns:function($srcTable,$dstTable,startCol,columnsCount){var pageObj=this;$.each(["thead","tbody"],function(tagId,tag){var $rows=$srcTable.children(tag).children(),$rowContainer;if(!$rows.length){return;}
$rowContainer=$(Runner.domShallowCopy($srcTable.children(tag).get(0))).appendTo($dstTable);$rows.each(function(_i,row){var $dstRow=$(Runner.domShallowCopy(row)).appendTo($rowContainer),$rowCells=$(row).children();if($rowCells.length<columnsCount){if($rowCells.length>startCol){$rowCells.slice(startCol).appendTo($dstRow);$($rowCells[startCol-1]).addClass(pageObj.edgeClass);$dstRow.children().each(function(cellId,cell){var $cell=$(cell),hasColspan=$cell.attr("colspan")!==undefined&&$cell.attr("colspan")!==false;if(hasColspan){$cell.attr("colspan",$rowCells.length-startCol);return false;}});}else{$rowCells.each(function(cellId,cell){var $cell=$(cell),hasColspan=$cell.attr("colspan")!==undefined&&$cell.attr("colspan")!==false,$newCell;if(hasColspan){$cell.attr("colspan",startCol-cellId);$newCell=$(Runner.domShallowCopy($cell.get(0)));$newCell.html("&nbsp;").attr("colspan",columnsCount-startCol).appendTo($dstRow);return false;}});}}else{$rowCells.slice(startCol).appendTo($dstRow);$($rowCells[startCol-1]).addClass(pageObj.edgeClass);}
$rowCells.last().addClass(pageObj.edgeClass);});});},setTotalsData:function(){var pageObj=this,$summaryHeader=$(".summary-header"),$summaryPage=$(".summary-page"),$summaryGlobal=$(".summary-global");this.$summaryHeader=$summaryHeader.clone();this.$summaryPage=$summaryPage.clone();this.$summaryGlobal=$summaryGlobal.clone();$summaryPage.each(function(idx,elem){pageObj.summaryPageHeight+=$(elem).height();});$summaryHeader.remove();$summaryPage.remove();$summaryGlobal.remove();},setTotalsDataToPage:function(pageIdx,$srcElem){if($srcElem.length&&this.pages[pageIdx]){this.pages[pageIdx].$page.find("."+this.tableClass+" > tbody").append($srcElem.clone());}},getContentWidth:function(){if(!this.isBootstrap()){return $(".rnr-report-gridblock").width();}
return $(".rp-page").width()||document.body.clientWidth;}});Runner.pages.DashboardPage=Runner.extend(Runner.pages.RunnerPage,{pageType:Runner.pages.constants.PAGE_DASHBOARD,elements:null,elementTypeInfo:null,dynamicPagesDataByElement:{},constructor:function(cfg){Runner.pages.DashboardPage.superclass.constructor.call(this,cfg);this.elements=Runner.pages.PageSettings.getTableData(this.tName,"dashElements");this.fillElementTypeInfo();},init:function(){Runner.pages.DashboardPage.superclass.init.call(this);this.doLoadAction();this.hideExcessSeparators();this.fireEvent('afterInit',this,this.proxy,this.id);},initSearch:function(){this.searchController=new Runner.search.SearchController({id:this.pageId,tName:this.tName,pageType:this.pageType,ajaxSubmit:true,formBaseParams:{id:this.pageId,mode:"dashsearch"}});this.searchController.init(this.controlsMap.search.searchBlocks);this.searchController.on('afterSearch',function(respObj,srchController,srchForm){srchController.toggleShowAll(respObj.show_all);this.doLoadAction(respObj.show_all?{}:{a:"showall"});},this);},fillElementTypeInfo:function(){var constants=Runner.pages.constants;if(this.elementTypeInfo){return;}
this.elementTypeInfo={};this.elementTypeInfo[constants.DASHBOARD_LIST]={pageType:constants.PAGE_LIST,pageRequestMode:"dashlist",pageMode:constants.LIST_DASHBOARD};this.elementTypeInfo[constants.DASHBOARD_CHART]={pageType:constants.PAGE_CHART,pageRequestMode:"dashchart",pageMode:constants.CHART_DASHBOARD};this.elementTypeInfo[constants.DASHBOARD_REPORT]={pageType:constants.PAGE_REPORT,pageRequestMode:"dashreport",pageMode:constants.REPORT_DASHBOARD};this.elementTypeInfo[constants.DASHBOARD_RECORD]={pageType:constants.PAGE_EDIT,pageRequestMode:"dashrecord",pageMode:constants.EDIT_DASHBOARD};this.elementTypeInfo[constants.DASHBOARD_SEARCH]={pageType:constants.PAGE_SEARCH,pageRequestMode:"dashsearch",pageMode:constants.SEARCH_DASHBOARD};this.elementTypeInfo[constants.DASHBOARD_DETAILS]={pageType:constants.PAGE_LIST,pageRequestMode:"dashdetails",pageMode:constants.LIST_DASHDETAILS};this.elementTypeInfo[constants.DASHBOARD_MAP]={pageType:constants.PAGE_DASHMAP,pageRequestMode:"dashmap",pageMode:constants.MAP_DASHBOARD};},loadSingleRecord:function(dbelem,pageTypes,additionalPageParams,action){var pageObj=this,ret=0;additionalPageParams=additionalPageParams||{};additionalPageParams.openMode=Runner.pages.constants.OPENMODE_DASHTABS;if(pageTypes){pageTypes=$.grep(pageTypes,function(el,idx){return $.inArray(el,dbelem.tabsPageTypes)!==-1;});}
pageTypes=pageTypes||dbelem.tabsPageTypes;this.toggleViewEditSingleRecordTabs(dbelem,action instanceof Runner.Dashboard.SearchAction?false:!dbelem.major||!this.searchController.usedSrch&&!dbelem.masterTable,pageTypes);$.each(pageTypes,function(idx,pageType){additionalPageParams.pageType=pageType;additionalPageParams.tabSettings={tabIndex:$.inArray(pageType,dbelem.tabsPageTypes),tabId:pageType,tabLabel:pageObj.getTabLabel(pageType),tabControlName:dbelem.elementName,activeTab:pageType===dbelem.initialTabPageType}
pageObj.loadPage(dbelem,additionalPageParams,action);++ret;});return ret;},getTabLabel:function(pageType){var _map={};_map[Runner.pages.constants.PAGE_VIEW]=Runner.lang.constants.TEXT_VIEW;_map[Runner.pages.constants.PAGE_ADD]=Runner.lang.constants.TEXT_AA_P_ADD;_map[Runner.pages.constants.PAGE_EDIT]=Runner.lang.constants.TEXT_EDIT;this.getTabLabel=function(pageType){return _map[pageType];};return this.getTabLabel(pageType);},loadDetails:function(dbelem,additionalPageParams,detailKeys,action){var pageObj=this,tables,dkeyParams,params;this.toggleElement(dbelem.elementName,true);additionalPageParams=additionalPageParams||{};additionalPageParams.openMode=Runner.pages.constants.OPENMODE_DASHTABS;additionalPageParams.baseParams=additionalPageParams.baseParams||{};additionalPageParams.baseParams["goto"]=additionalPageParams.baseParams["goto"]||1;$.each(dbelem.details,function(ind,details){additionalPageParams.tabSettings={tabIndex:parseInt(ind),tabId:details.dShortTable,tabLabel:details.dCaptionTable,tabControlName:dbelem.elementName,hideTabsContent:false,activeTab:dbelem.initialTabDetailTable===details.dDataSourceTable,hiddenNav:dbelem.details.length===1};additionalPageParams.pageType=details.dType;additionalPageParams.tName=details.dDataSourceTable;params=jQuery.extend(true,{},additionalPageParams);if(detailKeys){jQuery.extend(params.baseParams,detailKeys[details.dDataSourceTable])
params.baseParams.mastertable=dbelem.table;}
pageObj.loadPage(dbelem,params,action);});return dbelem.details.length;},loadPage:function(dbelem,additionalPageParams,action){var pageParams=this.getDefaultPageParams(dbelem,additionalPageParams.pageType),pageId;pageParams=jQuery.extend(true,pageParams,additionalPageParams||{});pageParams.updContext=additionalPageParams.updContext;pageParams.dashAction=action;pageId=Runner.pages.PageManager.openPage(pageParams);this.setDynamicPageData(pageParams.tName,pageParams.pageType,dbelem,pageId);},getDefaultPageParams:function(dbelem,pageType){var params={dashboard:this,parentId:this.id,pageType:this.getElementPageType(dbelem.type),pageMode:this.getElementPageMode(dbelem.type,pageType),tName:dbelem.table,openMode:Runner.pages.constants.OPENMODE_DASHCONTAINER,openContainer:$('#dashelement_'+dbelem.elementName+this.id)[0],dashElement:dbelem.elementName,dashElementSettings:jQuery.extend(true,{},dbelem),baseParams:{parId:this.id,table:this.tName,dashelement:dbelem.elementName,mode:this.getElementPageRequestMode(dbelem.type)}};if(dbelem.type==Runner.pages.constants.DASHBOARD_LIST||dbelem.type==Runner.pages.constants.DASHBOARD_DETAILS){params.multiRecordPage=true;}
if(dbelem.type==Runner.pages.constants.DASHBOARD_MAP){params.requestUrl=Runner.pages.getUrl(dbelem.table,Runner.pages.constants.PAGE_LIST);params.pageMode=dbelem.updateMoved?Runner.pages.constants.MAP_DASHBOARD:Runner.pages.constants.GRIDBASED_MAP_DASHBOARD;}
return params;},getElementPageType:function(type){return this.elementTypeInfo[type].pageType;},getElementPageMode:function(type,pageType){if(type==Runner.DASHBOARD_DETAILS){if(!this.detailsElementInfo){this.detailsElementInfo={};this.detailsElementInfo[Runner.PAGE_CHART]=Runner.CHART_DASHDETAILS;this.detailsElementInfo[Runner.PAGE_LIST]=Runner.LIST_DASHDETAILS;this.detailsElementInfo[Runner.PAGE_REPORT]=Runner.REPORT_DASHDETAILS;}
return this.detailsElementInfo[pageType];}
return this.elementTypeInfo[type].pageMode;},getElementPageRequestMode:function(type){return this.elementTypeInfo[type].pageRequestMode;},getElementByName:function(name){var elementMap={},i;for(i in this.elements){elementMap[this.elements[i].elementName]=this.elements[i];}
this.getElementByName=function(_name){return elementMap[_name];}
return this.getElementByName(name);},setDynamicPageData:function(tName,pageType,dbelem,pageId){var elementName=dbelem.elementName;if(dbelem.type==Runner.pages.constants.DASHBOARD_RECORD){this.dynamicPagesDataByElement[elementName]=this.dynamicPagesDataByElement[elementName]||{};this.unregisterPageIfExists(tName,this.dynamicPagesDataByElement[elementName][pageType]);this.dynamicPagesDataByElement[elementName][pageType]=pageId;}else if(dbelem.type==Runner.pages.constants.DASHBOARD_DETAILS){this.dynamicPagesDataByElement[elementName]=this.dynamicPagesDataByElement[elementName]||{};this.unregisterPageIfExists(tName,this.dynamicPagesDataByElement[elementName][tName]);this.dynamicPagesDataByElement[elementName][tName]=pageId;}else{this.unregisterPageIfExists(tName,this.dynamicPagesDataByElement[elementName]);this.dynamicPagesDataByElement[elementName]=pageId;}},unregisterPageIfExists:function(tName,pageId){if(pageId){Runner.pages.PageManager.unregister(tName,pageId)}},getDynamicPageObject:function(elementName,second){var elementRecord=this.dynamicPagesDataByElement[elementName],dbelem=this.getElementByName(elementName),pageId,tName;if(!elementRecord||!dbelem){return null;}
if(dbelem.type==Runner.pages.constants.DASHBOARD_RECORD||dbelem.type==Runner.pages.constants.DASHBOARD_DETAILS){pageId=elementRecord[second];}else{pageId=elementRecord;}
if(!pageId){return null;}
tName=dbelem.type==Runner.pages.constants.DASHBOARD_DETAILS?second:dbelem.table;return Runner.pages.PageManager.getAt(tName,pageId);},getDynamicPageId:function(dbelem,tName,pageType){var pageId;if(!this.dynamicPagesDataByElement[dbelem.elementName]){return-1;}
if(dbelem.type==Runner.pages.constants.DASHBOARD_RECORD){pageId=this.dynamicPagesDataByElement[dbelem.elementName][pageType];}else if(dbelem.type==Runner.pages.constants.DASHBOARD_DETAILS){pageId=this.dynamicPagesDataByElement[dbelem.elementName][tName];}else{pageId=this.dynamicPagesDataByElement[dbelem.elementName];}
return pageId||-1;},unregisterDashPage:function(delem,tName,pageType){var pageId=this.getDynamicPageId(delem,tName,pageType);if(pageId!==-1){Runner.pages.PageManager.unregister(tName,pageId);}},getDashElements:function(table,dashTypes,elementName){var delements=[];if(!this.elements){return delements;}
if(!Runner.isArray(dashTypes)){dashTypes=[dashTypes];}
$.each(this.elements,function(ind,dbelem){if($.inArray(dbelem.type,dashTypes)!==-1&&dbelem.table===table&&(!elementName||dbelem.elementName===elementName)){delements.push(dbelem);}});return delements;},toggleElement:function(elementName,toggler){$('#dashelement_'+elementName+this.id).toggle(toggler);},toggleViewEditSingleRecordTabs:function(dElement,toggler,tabsTypes){var $tabsControl=Runner.pages.PageManager.getDashElementTabControl(dElement.elementName,this.id),constants=Runner.pages.constants,useBS=Runner.isBootstrap(),$tabNav,activeIdx,addIdx;tabsTypes=tabsTypes||dElement.tabsPageTypes;if(!$tabsControl||!$tabsControl.length||$.inArray(constants.PAGE_VIEW,tabsTypes)===-1&&$.inArray(constants.PAGE_EDIT,tabsTypes)===-1){return;}
addIdx=$.inArray(constants.PAGE_ADD,dElement.tabsPageTypes);if(addIdx===-1){this.toggleElement(dElement.elementName,toggler);return;}
if(useBS){$tabNav=$("ul.nav-tabs",$tabsControl);}
if(!toggler){if(useBS){$tabsControl.data("activeIdx",$tabNav.children("li").index($tabNav.children("li.active")));$("a[data-toggle='tab']",$tabNav.children("li").eq(addIdx)).tab("show");}else{$tabsControl.data("activeIdx",$tabsControl.tabs("option","active"));$tabsControl.tabs("option","active",addIdx);}}else{activeIdx=$tabsControl.data("activeIdx");if(activeIdx!==undefined){if(useBS){$("a[data-toggle='tab']",$tabNav.children("li").eq(activeIdx)).tab("show");}else{$tabsControl.tabs("option","active",activeIdx);}}}
$.each(dElement.tabsPageTypes,function(idx,type){if(type!==constants.PAGE_ADD&&$.inArray(type,tabsTypes)){$tabsControl.find("li["+(useBS?"data-tabidx":"data-rnrtabidx")+"='"+idx+"']").toggle(toggler);}});},doReportFirstLastAction:function(initiatorName,firstRecord,lastRecord,updContext){var cfg=this.getActionBaseConfig(initiatorName,{firstRecord:firstRecord,lastRecord:lastRecord}),action=new Runner.Dashboard.ReportFirstLastAction(cfg);return this.doAction(action,updContext);},doChangeTabAction:function(initiatorName,tabId,updContext){var cfg=this.getActionBaseConfig(initiatorName,{tabId:tabId}),action=new Runner.Dashboard.ChangeTabAction(cfg);return this.doAction(action,updContext);},doMoveAction:function(initiatorName,data,updContext){var masterData,t,masterAction,moveAction=new Runner.Dashboard.MoveAction(this.getActionBaseConfig(initiatorName,data));updContext=this.doAction(moveAction,updContext);for(t in data.masterKeys){masterData={detailsTable:t,masterKeys:data.masterKeys[t]};masterAction=new Runner.Dashboard.MoveMasterAction(this.getActionBaseConfig(initiatorName,masterData));this.doAction(masterAction,updContext);}
return updContext;},doMoveAdjacentAction:function(initiatorName,goForward,updContext){var cfg=this.getActionBaseConfig(initiatorName,{goForward:goForward}),moveAction=new Runner.Dashboard.MoveAdjacentAction(cfg);return this.doAction(moveAction,updContext);},doReloadListAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.ReloadListAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doTimerReloadAction:function(initiatorName,data){var action=new Runner.Dashboard.TimerReloadAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action);},doLoadAction:function(data,initiatorName,updContext){data=data||{};var action=new Runner.Dashboard.LoadAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doSearchAction:function(initiatorName,searchParams,updContext){var data={searchParams:searchParams},action=new Runner.Dashboard.SearchAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doAction:function(action,updContext){var pageObj=this;updContext=updContext||new Runner.Dashboard.Context();updContext.actions.push(action);setTimeout(function(){for(var i in pageObj.elements){action.apply(pageObj.elements[i],updContext);}},0);return updContext;},doUpdateRecordAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.UpdateRecordAction(this.getActionBaseConfig(initiatorName,data)),t,masterData,masterAction;for(t in data.masterKeys){masterData={detailsTable:t,masterKeys:data.masterKeys[t]};masterAction=new Runner.Dashboard.MoveMasterAction(this.getActionBaseConfig(initiatorName,masterData));this.doAction(masterAction,updContext);}
return this.doAction(action,updContext);},doAddRecordAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.AddRecordAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doMapViewPortChangedAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.MapViewPortChangedAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doDeleteRecordsAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.DeleteRecordsAction(this.getActionBaseConfig(initiatorName,data));return this.doAction(action,updContext);},doNoDataAction:function(initiatorName,data,updContext){var action=new Runner.Dashboard.NoDataAction(this.getActionBaseConfig(initiatorName,data)),t,masterData;if(data&&data.detailTables){for(t in data.detailTables){masterData={detailsTable:t,};masterAction=new Runner.Dashboard.NoDataInMasterAction(this.getActionBaseConfig(initiatorName,masterData));this.doAction(masterAction,updContext);}}
return this.doAction(action,updContext);},getActionBaseConfig:function(initiatorName,data){var initiator=this.getElementByName(initiatorName);return{initiator:initiator,dashboard:this,table:initiator?initiator.table:null,data:data};}});Runner.namespace('Runner.Dashboard');Runner.Dashboard.Context=Runner.extend(Object,{actions:null,constructor:function(){this.actions=[];},continueActions:function(dbElem,action){var i=0,l=this.actions.length,done;for(;i<l;++i){if(this.actions[i]==action){done=action.finishPendingTask(dbElem);break;}}
if(!done){return;}
for(++i;i<l;++i){if(false===this.actions[i].apply(dbElem,this)){break;}}},elementActionPending:function(dbElem){for(var i=this.actions.length;i--;){if(this.actions[i].pending[dbElem.elementName]){return true;}}
return false;},hasUpdateRecordAction:function(){for(var i=this.actions.length;i--;){if(this.actions[i]instanceof Runner.Dashboard.UpdateRecordAction){return true;}}
return false;}});Runner.Dashboard.Action=Runner.extend(Object,{dashboard:null,initiator:null,appliedTo:null,pending:null,data:{},handlerMap:null,constructor:function(cfg){Runner.apply(this,cfg);this.handlerMap={};this.appliedTo={};this.pending={};},checkTable:function(dbElem){return this.table===dbElem.table;},applyToInitiator:function(dbElem){return false;},applicable:function(dbElem){return((this.initiator!=dbElem||this.applyToInitiator(dbElem))&&this.handlerMap[dbElem.type]&&this.checkTable(dbElem));},apply:function(dbElem,updContext){var result;if(this.appliedTo[dbElem.elementName]){return;}
if(updContext.elementActionPending(dbElem)){return;}
if(this.applicable(dbElem)){result=this.handlerMap[dbElem.type].call(this,dbElem,updContext);}
if(result===false){this.pending[dbElem.elementName]=(this.pending[dbElem.elementName]||0)+1;}else if(typeof result=="number"&&result>0){this.pending[dbElem.elementName]=(this.pending[dbElem.elementName]||0)+result;result=false;}else{this.appliedTo[dbElem.elementName]=true;}
return result;},finishPendingTask:function(dbElem){if(!this.pending[dbElem.elementName]){Runner.debugThrow();return true;}
--this.pending[dbElem.elementName];if(!this.pending[dbElem.elementName]){this.appliedTo[dbElem.elementName]=true;}
return!!this.appliedTo[dbElem.elementName];}});Runner.Dashboard.ReloadListAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.ReloadListAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_REPORT]=this.applyList;},applyList:function(dbElem,updContext){var baseParams={};if(this.data.page){baseParams.goto=this.data.page;}
baseParams.tab=this.data.tabId;this.dashboard.loadPage(dbElem,{updContext:updContext,baseParams:baseParams},this);return 1;},applyMap:function(mapElem,updContext){if(mapElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(mapElem.elementName);if(!pageObj){Runner.debugThrow();return;}
pageObj.setMapMarkers(this.data.markersData[pageObj.mapId]);if(this.data.tabId!=""&&pageObj.$gridTabControl){pageObj.$gridTabControl.children().removeClass('active');pageObj.$gridTabControl.find('[data-tabid="'+this.data.tabId+'"]').parent().addClass('active');}}});Runner.Dashboard.LoadAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.LoadAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applySearch;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_REPORT]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_SEARCH]=this.applySearch;},checkTable:function(dbElem){return!this.table||this.table===dbElem.table;},applyList:function(dbElem,updContext){if(!dbElem.major||dbElem.masterTable){return;}
this.dashboard.loadPage(dbElem,{updContext:updContext,baseParams:this.data||{}},this);return 1;},applyChart:function(dbElem,updContext){if(dbElem.masterTable){return;}
this.dashboard.loadPage(dbElem,{updContext:updContext},this);return 1;},applySearch:function(dbElem,updContext){this.dashboard.loadPage(dbElem,{updContext:updContext,baseParams:this.data},this);return 1;},applyRecord:function(dbElem,updContext){var pageTypes=[Runner.pages.constants.PAGE_ADD];if(dbElem.masterTable){return;}
if(dbElem.major){pageTypes.push(Runner.pages.constants.PAGE_VIEW);pageTypes.push(Runner.pages.constants.PAGE_EDIT);}
return this.dashboard.loadSingleRecord(dbElem,pageTypes,{updContext:updContext},this);}});Runner.Dashboard.MoveAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MoveAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyChart;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_DETAILS]=this.applyDetails;},applyList:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){return;}
return pageObj.moveToKeys(this.data.keys,updContext);},applyMap:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(pageObj){pageObj.setMarkerActive(null,this.data.keys);}
return;},applyRecord:function(dbElem,updContext){var pageParams={updContext:updContext,baseParams:{}},i;for(i=0;i<this.data.keys.length;++i){pageParams.baseParams['editid'+(i+1)]=this.data.keys[i];}
if(this.data.vpCoordinates){pageParams.baseParams.vpCoordinates=this.data.vpCoordinates;pageParams.baseParams.mapRefresh=true;}
return this.dashboard.loadSingleRecord(dbElem,[Runner.pages.constants.PAGE_VIEW,Runner.pages.constants.PAGE_EDIT],pageParams,this);},applyDetails:function(dbElem,updContext){var pageParams={updContext:updContext};return this.dashboard.loadDetails(dbElem,pageParams,this.data.masterKeys,this);},applyChart:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){Runner.debugThrow();}
pageObj.setActiveBar(this.data);return;var anyChartId=$("#chart_block"+pageObj.id+" object").attr("id"),chart=AnyChart.getChartById(anyChartId);chart.selectPoint(this.data.seriesId,this.data.pointId,true);return;},});Runner.Dashboard.ChangeTabAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.ChangeTabAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;},applyToInitiator:function(dbElem){return true;},applyList:function(dbElem,updContext){if(!dbElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj||!pageObj.$gridTabControl){return;}
pageObj.$gridTabControl.find('[data-tabid="'+this.data.tabId+'"]').click();return;},applyMap:function(dbElem,updContext){if(!dbElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj||!pageObj.$gridTabControl){return;}
pageObj.processTabChange(updContext,this);return 1;}});Runner.Dashboard.MoveAdjacentAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MoveAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;},applyList:function(dbElem,updContext){if(!dbElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){return;}
return pageObj.setAdjacentSelection(this.data.goForward,updContext,this);},applyRecord:function(dbElem,updContext){if(!dbElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName,Runner.pages.constants.PAGE_EDIT)||this.dashboard.getDynamicPageObject(dbElem.elementName,Runner.pages.constants.PAGE_VIEW);if(!pageObj){return;}
return pageObj.setAdjacentSelection(this.data.goForward,updContext,this);}});Runner.Dashboard.MapViewPortChangedAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MapViewPortChangedAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;},applyList:function(dbElem,updContext){this.dashboard.loadPage(dbElem,{updContext:updContext,baseParams:{vpCoordinates:this.data.vpCoordinates,mapRefresh:true,tab:this.data.tabId}},this);return 1;},applyMap:function(mapElem,updContext){if(mapElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(mapElem.elementName);if(pageObj){pageObj.setMapMarkers(this.data.markersData[pageObj.mapId]);}else{Runner.debugThrow();}}});Runner.Dashboard.UpdateRecordAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.UpdateRecordAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_DETAILS]=this.applyDetails;},applyToInitiator:function(dbElem){return dbElem.type===Runner.pages.constants.DASHBOARD_RECORD;},applyList:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){return;}
pageObj.updateRecord(this.data,updContext,this);},applyMap:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName),recordVals,iconData;if(pageObj){recordVals=Runner.apply({keys:this.data.keys},this.data.rawVals);iconData=this.data.mapIconsData?this.data.mapIconsData[dbElem.elementName]:"";pageObj.updateMapAfterGridLineEdited(recordVals,this.data.oldKeys,iconData);}},applyRecord:function(dbElem,updContext){var pageParams={updContext:updContext,baseParams:{}},pageTypes=[Runner.pages.constants.PAGE_VIEW],i;if(this.initiator!=dbElem){pageTypes.push(Runner.pages.constants.PAGE_EDIT);}
for(i=0;i<this.data.keys.length;++i){pageParams.baseParams['editid'+(i+1)]=this.data.keys[i];}
return this.dashboard.loadSingleRecord(dbElem,pageTypes,pageParams,this);},applyDetails:function(dbElem,updContext){var pageParams={updContext:updContext};return this.dashboard.loadDetails(dbElem,pageParams,this.data.detKeys,this);}});Runner.Dashboard.ReportFirstLastAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MoveAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;},applyRecord:function(dbElem,updContext){var pageObj,i,pageTypes=[Runner.pages.constants.PAGE_VIEW,Runner.pages.constants.PAGE_EDIT];for(i=0;i<pageTypes.length;++i){pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName,pageTypes[i]);if(pageObj){pageObj.showNextPrevButtons(!this.data.lastRecord,!this.data.firstRecord);}}}});Runner.Dashboard.SearchAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MoveAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_SEARCH]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_REPORT]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyList;},applyList:function(dbElem,updContext){if(!dbElem.major&&dbElem.type!=Runner.pages.constants.DASHBOARD_SEARCH){return;}
this.dashboard.loadPage(dbElem,{baseParams:this.data.searchParams,updContext:updContext},this);return 1;},applyRecord:function(dbElem,updContext){var pageTypes=[Runner.pages.constants.PAGE_VIEW,Runner.pages.constants.PAGE_EDIT];if(!dbElem.major){return;}
return this.dashboard.loadSingleRecord(dbElem,pageTypes,{baseParams:this.data.searchParams,updContext:updContext},this);}});Runner.Dashboard.AddRecordAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.UpdateRecordAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;},applyToInitiator:function(dbElem){return dbElem.type===Runner.pages.constants.DASHBOARD_RECORD;},applyList:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){return;}
pageObj.addRecord(this.data,updContext,this);},applyMap:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName),recordVals,iconData;if(pageObj){recordVals=Runner.apply({keys:this.data.keys},this.data.rawVals);iconData=this.data.mapIconsData?this.data.mapIconsData[dbElem.elementName]:"";pageObj.updateMapAfterNewGridLineAdded(updContext,recordVals,iconData);}},applyRecord:function(dbElem,updContext){if(!dbElem.major){return;}
var pageParams={updContext:updContext,baseParams:{}},pageTypes=[Runner.pages.constants.PAGE_VIEW,Runner.pages.constants.PAGE_EDIT],i;for(i=0;i<this.data.keys.length;++i){pageParams.baseParams['editid'+(i+1)]=this.data.keys[i];}
return this.dashboard.loadSingleRecord(dbElem,pageTypes,pageParams,this);}});Runner.Dashboard.DeleteRecordsAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.DeleteRecordsAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;},applyMap:function(dbElem,updContext){var mapPageObj=this.dashboard.getDynamicPageObject(dbElem.elementName),recordVals;if(mapPageObj){mapPageObj.deleteSelectedMarkers(this.data.keyStrings);}}});Runner.Dashboard.MoveMasterAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.MoveMasterAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyChart;this.handlerMap[Runner.pages.constants.DASHBOARD_REPORT]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;},checkTable:function(dbElem){return this.data.detailsTable===dbElem.table&&this.table==dbElem.masterTable;},applyList:function(dbElem,updContext){if(!dbElem.major){return;}
var pageParams={updContext:updContext,baseParams:{mastertable:this.table}},i;for(i in this.data.masterKeys){pageParams.baseParams[i]=this.data.masterKeys[i];}
this.dashboard.loadPage(dbElem,pageParams,this);return 1;},applyChart:function(dbElem,updContext){if(!dbElem.major){return;}
var pageParams={updContext:updContext,baseParams:{mastertable:this.table,mode:"dashdetails",}},i;for(i in this.data.masterKeys){pageParams.baseParams[i]=this.data.masterKeys[i];}
this.dashboard.loadPage(dbElem,pageParams,this);return 1;},applyMap:function(dbElem,updContext){if(!dbElem.major){return;}
var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(pageObj){pageObj.filterMarkersByMaster(this.table,this.data.masterKeys,updContext,this);return 1;}
return 0;},applyRecord:function(dbElem,updContext){var asyncTasksCount,pageTypes=[],pageParams={updContext:updContext,baseParams:{mastertable:this.table}},i;pageTypes.push(Runner.pages.constants.PAGE_ADD);if(dbElem.major){pageTypes.push(Runner.pages.constants.PAGE_EDIT);pageTypes.push(Runner.pages.constants.PAGE_VIEW);}
for(i in this.data.masterKeys){pageParams.baseParams[i]=this.data.masterKeys[i];}
asyncTasksCount=this.dashboard.loadSingleRecord(dbElem,pageTypes,pageParams,this);return asyncTasksCount;}});Runner.Dashboard.NoDataAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.NoDataAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_DETAILS]=this.applyDetails;},applyRecord:function(dbElem,updContext){this.dashboard.toggleViewEditSingleRecordTabs(dbElem,false);this.dashboard.unregisterDashPage(dbElem,dbElem.table,Runner.pages.constants.PAGE_VIEW);this.dashboard.unregisterDashPage(dbElem,dbElem.table,Runner.pages.constants.PAGE_EDIT);},applyDetails:function(dbElem,updContext){var action=this;this.dashboard.toggleElement(dbElem.elementName,false);$.each(dbElem.details,function(ind,details){action.dashboard.unregisterDashPage(dbElem,details.dDataSourceTable,details.dType);});}});Runner.Dashboard.NoDataInMasterAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.NoDataInMasterAction.superclass.constructor.call(this,cfg);this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;},checkTable:function(dbElem){return this.data.detailsTable===dbElem.table&&this.table==dbElem.masterTable;},applyList:function(dbElem,updContext){if(!dbElem.major){return;}
var pageParams={updContext:updContext,baseParams:{mastertable:this.table,nodata:true}};this.dashboard.loadPage(dbElem,pageParams,this);return 1;}});Runner.Dashboard.TimerReloadAction=Runner.extend(Runner.Dashboard.Action,{constructor:function(cfg){Runner.Dashboard.TimerReloadAction.superclass.constructor.call(this,cfg);this.data=this.data||{};this.handlerMap[Runner.pages.constants.DASHBOARD_MAP]=this.applyMap;this.handlerMap[Runner.pages.constants.DASHBOARD_RECORD]=this.applyRecord;this.handlerMap[Runner.pages.constants.DASHBOARD_LIST]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_CHART]=this.applyList;this.handlerMap[Runner.pages.constants.DASHBOARD_REPORT]=this.applyList;},applicable:function(dbElem){return(this.initiator==dbElem);},applyList:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName),reloadData={};if(!pageObj){Runner.debugThrow();}
reloadData.reloadKeys=this.data.keys;if(this.data.resizableColumnsData){reloadData.resizableColumnsData=this.data.resizableColumnsData;}
pageObj.reload({},reloadData);return 1;},applyChart:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){Runner.debugThrow();}
pageObj.reloadChart();},applyMap:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName);if(!pageObj){Runner.debugThrow();}
pageObj.reloadViewportMarkers(updContext,this);return 1;},applyRecord:function(dbElem,updContext){var pageObj=this.dashboard.getDynamicPageObject(dbElem.elementName,Runner.pages.constants.PAGE_VIEW);if(!pageObj){Runner.debugThrow();}
pageObj.reload({});}});Runner.pages.DashboardPageMobile=Runner.extend(Runner.pages.DashboardPage,{constructor:function(cfg){Runner.pages.DashboardPageMobile.superclass.constructor.call(this,cfg);this.bricksArr=["dashboard_mobile","vmenu_mobile","tableinfo_dashboard_mobile","search_dashboard_mobile","search_dashboard_m","vmenu","languages","loggedas_mobile","backbutton"];this.bricksArrList=["dashboard_mobile","vmenu_mobile","tableinfo_dashboard_mobile","search_dashboard_mobile","languages","loggedas_mobile"];},initSearch:Runner.pages.RunnerPage.prototype.initSearch,init:function(){Runner.pages.DashboardPageMobile.superclass.init.call(this);$(window).bind('hashchange',$.proxy(this.updatePageAppearance,this));if(!window.location.hash){window.location.hash="#list";}else{this.updatePageAppearance();}
this.initBackButton();},updatePageAppearance:function(){if(window.location.hash=='#search'){this.showMobileSearchPanel();}
if(window.location.hash=='#menu'){this.showMobileMenu();}
if(window.location.hash=='#list'){this.showMobileListPage();}},showMobileSearchPanel:function(){if(window.location.hash!=='#search'){return;}
this.hideBricks(this.bricksArr);this.showBricks(["search_dashboard_m"]);},showMobileMenu:function(){if(window.location.hash!=='#menu'){return;}
this.hideBricks(this.bricksArr);this.showBricks(["vmenu","backbutton"]);Runner.menu.TreeLikeVmenu.prototype.openMenuOnLoad();},initBackButton:function(){var pageObj=this;$("#backbutton").unbind("click").bind("click",function(e){pageObj.showMobileListPage();});},showMobileListPage:function(){if(window.location.hash!=='#list'){return;}
this.hideBricks(this.bricksArr);this.showBricks(this.bricksArrList);},});Runner.pages.ListPageDash=Runner.extend(Runner.pages.ListPage,{baseParams:null,dashElement:null,selectedId:-1,firstPage:false,lastPage:false,constructor:function(cfg){Runner.pages.ListPageDash.superclass.constructor.call(this,cfg);this.pageCont=$(this.openContainer);this.addEvents("afterPageReady");this.baseParams=this.baseParams||{id:this.pageId};},init:function(){var pageObj=this,$gridElem,reloadActionData;if(this.pageMode===Runner.pages.constants.LIST_DASHDETAILS){this.initGridTabs=Runner.pages.ChartPageDPDash.prototype.initGridTabs;}
Runner.pages.ListPageDash.superclass.init.call(this);$gridElem=$(this.gridElem).removeClass("hoverable");if(this.pageMode===Runner.pages.constants.LIST_DASHDETAILS){return;}
this.firstPage=this.controlsMap.pageNumber===1;this.lastPage=this.controlsMap.pageNumber===this.controlsMap.numberOfPages;reloadActionData={page:this.controlsMap.pageNumber,tabId:this.pageData.tabId,markersData:this.getMarkersForDependentMaps()};this.selectedId=null;if(this.reloadKeys){this.moveToKeys(this.reloadKeys,this.updContext);this.reloadKeys=null;}
if(this.dashboard.getElementByName(this.dashElement).major&&!this.controlsMap.gridRows.length){this.dashboard.doNoDataAction(this.dashElement,{detailTables:Runner.pages.PageSettings.getTableData(this.tName,"detailTables")},this.updContext);}else if(!this.dashAction){if(!this.selectedId&&this.controlsMap.gridRows.length){this.setSelection(this.controlsMap.gridRows[0].id);this.sendMoveAction();}
this.updContext=this.dashboard.doReloadListAction(this.dashElement,reloadActionData,this.updContext);this.fireEvent('afterPageReady',this,this.proxy,this.pageId);}else if(!this.selectedId&&this.dashboard.getElementByName(this.dashElement).major&&this.controlsMap.gridRows.length){if(!this.moveToLastRecord){this.setSelection(this.controlsMap.gridRows[0].id);}else{this.setSelection(this.controlsMap.gridRows[this.controlsMap.gridRows.length-1].id);}
this.moveToLastRecord=false;this.updContext=this.dashboard.doReloadListAction(this.dashElement,reloadActionData,this.updContext);this.sendMoveAction(this.updContext);}
this.finishDashElementActions();this.updContext=null;if(this.dashboard.getElementByName(this.dashElement).reload){if(this.reloadTimerId){window.clearTimeout(this.reloadTimerId);}
this.reloadTimerId=window.setTimeout(function(){var row=pageObj.getRowByRowId(pageObj.selectedId),data={keys:row&&row.keys};if(pageObj.bsResizeInitialized){data.resizableColumnsData=pageObj.getResizableColumnsData();}
pageObj.dashboard.doTimerReloadAction(pageObj.dashElement,data);},1000*this.dashboard.getElementByName(this.dashElement).reload);}
$gridElem.on('click','[data-record-id]',function(){var activeId=$(this).data('record-id');if(pageObj.setSelection(activeId)){pageObj.sendMoveAction();}});},sendMoveAction:function(updContext){var row=this.getRowByRowId(this.selectedId);updContext=this.dashboard.doMoveAction(this.dashElement,{keys:row.keys,masterKeys:row.masterKeys},updContext);return this.sendReportNextPrev(updContext);},sendReportNextPrev:function(updContext){var firstRecord=false,lastRecord=false,visibleIndex=this.inlineAdd.getRowOrderIndex(this.selectedId);if(this.firstPage){firstRecord=this.inlineAdd.getRowIdByOrderIndex(visibleIndex-1)<=0;}
if(this.lastPage){lastRecord=this.inlineAdd.getRowIdByOrderIndex(visibleIndex+1)<=0;}
updContext=this.dashboard.doReportFirstLastAction(this.dashElement,firstRecord,lastRecord,updContext);return updContext;},initInline:function(){Runner.pages.ListPageDash.superclass.initInline.call();this.inlineButtonsIntialized=false;this.initInlineEdit();this.initInlineAdd();if(this.inlineAdd||this.inlineEdit){(this.inlineAdd||this.inlineEdit).toggleMassRecButt();}},scrollIntoViewRecord:function(recordId){var $record=$("[data-record-id="+recordId+"]",this.gridElem),$scrollDiv=$(".rnr-dbelembody",this.pageCont);if(!$record.length||!$scrollDiv.length){return;}
setTimeout(function(){if($scrollDiv.offset().top>$record.offset().top||$scrollDiv.offset().top+$scrollDiv.height()<$record.offset().top+$record.height()){$record.get(0).scrollIntoView();}},500);},isRowInGrid:function(recordId){return!!$("[data-record-id="+recordId+"]",this.gridElem).length;},getRowIdByKeys:function(keys){var rows=this.controlsMap.gridRows,i;for(i=0;i<rows.length;i++){if(Runner.arraysEqual(keys,rows[i].keys,true)){return rows[i].id;}}
return-1;},getRowIdByKey:function(keyField,keyValue){var rows=this.controlsMap.gridRows,i;for(i=0;i<rows.length;i++){if(rows[i].keyFields[0]==keyField&&rows[i].keys[0]==keyValue){return rows[i].id;}}
return-2;},getInlineAddParams:function(){var params=Runner.pages.ListPageDash.superclass.getInlineAddParams.call(this);params.dashGridBased=true;return params;},initInlineAdd:function(){Runner.pages.ListPageDash.superclass.initInlineAdd.call(this);if(this.pageMode==Runner.pages.constants.LIST_DASHDETAILS){return;}
this.inlineAdd.on("afterSubmit",function(vals,fields,keys,rowId,resp){var updContext=this.dashboard.doAddRecordAction(this.dashElement,resp);if(this.mapManager){this.mapManager.updateMapsOnAfterAddSubmit(vals,fields,keys,rowId,resp);}
this.setSelection(rowId);if(this.dashboard.getElementByName(this.dashElement).major){this.sendMoveAction(updContext);}},this);},getInlineEditParams:function(){var params=Runner.pages.ListPageDash.superclass.getInlineAddParams.call(this);params.dashGridBased=true;return params;},initInlineEdit:function(){if(this.inlineEdit){this.inlineEdit.reInit(this.controlsMap.gridRows);return;}
Runner.pages.ListPageDash.superclass.initInlineEdit.call(this);if(this.pageMode==Runner.pages.constants.LIST_DASHDETAILS||!this.inlineEdit){return;}
this.inlineEdit.on("afterSubmit",function(vals,fields,keys,rowId,newData,extEditPageObj){var updContext;this.setSelection(rowId);updContext=this.dashboard.doUpdateRecordAction(this.dashElement,newData);if(this.dashboard.getElementByName(this.dashElement).major){this.sendReportNextPrev(updContext);}},this);},initDeleteButton:function(){var submitUrl=Runner.getPageUrl(this.shortTName,this.pageType),pageObj=this;$("[id='delete_selected"+this.id+"']").on("click",function(e){var $selBoxes=pageObj.getSelBoxes(pageObj.id),form;if(!$selBoxes.length||!confirm(Runner.lang.constants.TEXT_DELETE_CONFIRM)){return false;}
pageObj.selectedId=-1;form=new Runner.form.BasicForm({standardSubmit:false,submitUrl:submitUrl+"?"+$selBoxes.serialize(),method:'POST',id:pageObj.id,baseParams:Runner.apply({a:'delete',id:pageObj.pageId},pageObj.baseParams),successSubmit:{fn:function(respObj,formObj,fieldControls){this.pageReloadHn(respObj);this.doDeleteRecordsAction($selBoxes);if(this.dashboard.getElementByName(this.dashElement).major&&!this.controlsMap.gridRows.length){this.dashboard.doNoDataAction(this.dashElement,{detailTables:Runner.pages.PageSettings.getTableData(this.tName,"detailTables")},this.updContext);}},scope:pageObj}});form.submit();return false;});},doDeleteRecordsAction:function($selBoxes){if(this.dashboard.getElementByName(this.dashElement).major){return;}
var keyStrings=[];$selBoxes.each(function(i,selBox){keyStrings.push(decodeURIComponent($(selBox).val()));});this.dashboard.doDeleteRecordsAction(this.dashElement,{keyStrings:keyStrings},this.updContext);},getMarkersForDependentMap:function(dashMapId){if(!this.controlsMap||!this.controlsMap.gMaps||!this.controlsMap.gMaps.mapsData||!this.controlsMap.gMaps.mapsData[dashMapId]){return[];}
return this.controlsMap.gMaps.mapsData[dashMapId].markers||[];},getMarkersForDependentMaps:function(){var markersData={};if(!this.controlsMap||!this.controlsMap.gMaps||!this.controlsMap.gMaps.mapsData){return markersData;}
$.each(this.controlsMap.gMaps.mapsData,function(mapId,mapData){if(mapData.dashMap){markersData[mapId]=mapData.markers||[];}});return markersData;},getRowOrderIndex:function(rowId){if(this.inlineAdd){return this.inlineAdd.getRowOrderIndex(rowId);}
for(var i=0;i<this.controlsMap.gridRows.length;++i){if(this.controlsMap.gridRows[i].id==rowId){return i;}}
return-1;},getRowByRowId:function(rowId){if(this.inlineAdd||this.inlineEdit){return(this.inlineAdd||this.inlineEdit).getRowById(rowId);}
for(var i=0;i<this.controlsMap.gridRows.length;++i){if(this.controlsMap.gridRows[i].id==rowId){return this.controlsMap.gridRows[i];}}
return null;},getRowIdByOrderIndex:function(rowIdx){if(this.inlineAdd){return this.inlineAdd.getRowIdByOrderIndex(rowIdx);}
return this.controlsMap.gridRows[rowIdx].id;},moveToKeys:function(keys,updContext){var recordId=this.getRowIdByKeys(keys);return this.setSelection(recordId,updContext);},setSelection:function(recordId){var $row=$("tr.bs-gridrow#gridRow"+recordId);if(this.pageMode==Runner.pages.constants.LIST_DASHDETAILS){return false;}
if(recordId<=0||this.selectedId==recordId){return false;}
this.scrollIntoViewRecord(recordId);this.selectedId=recordId;$(".rnr-dbselectedrow",this.gridElem).removeClass("rnr-dbselectedrow");if($row.length){$row.addClass("rnr-dbselectedrow");}else{$("[data-record-id="+recordId+"]",this.gridElem).addClass("rnr-dbselectedrow");}
return true;},setAdjacentSelection:function(goForward,updContext,action){var moveToLastRecord,newPage,reloadParams={},selectedIdx=this.getRowOrderIndex(this.selectedId);if(selectedIdx===-1){return;}
selectedIdx=selectedIdx+(goForward?1:-1);if(selectedIdx>=0&&selectedIdx<this.controlsMap.gridRows.length){this.setSelection(this.getRowIdByOrderIndex(selectedIdx));this.sendMoveAction();return;}
moveToLastRecord=!goForward&&this.controlsMap.pageNumber>0;newPage=moveToLastRecord?this.controlsMap.pageNumber-1:this.controlsMap.pageNumber+1;reloadParams.moveToLastRecord=moveToLastRecord;reloadParams.updContext=updContext;reloadParams.dashAction=action;this.reload({goto:newPage},reloadParams);return false;},updateRecord:function(data,updContext,action){var rowId=this.getRowIdByKeys(data.oldKeys),row=this.inlineEdit.getRowById(rowId);if(row){this.setSelection(row.id);this.inlineEdit.updateTableRow(row,data);if(this.mapManager){this.mapManager.updateMapsOnAfterEditSubmit(data.vals,data.fields,data.keys,row.id,data);}}
if(this.dashboard.getElementByName(this.dashElement).major){this.sendReportNextPrev(updContext);}},addRecord:function(data,updContext,action){var row=this.inlineAdd.addRowToGrid(data,false);this.initNewRowButtons(row);this.setSelection(row.id);if(this.dashboard.getElementByName(this.dashElement).major){this.sendMoveAction(updContext);}},getResizeColumnsLoggerParams:function(){return{saveParam:Runner.pages.constants.CRESIZE_PARAMS_TYPE,data:JSON.stringify(this.getResizableColumnsData()),onDashboard:true,dashElementId:this.dashboard.tName+"_"+this.dashElement};},hasInlineEdit:function(){return this.inlineEdit&&this.dashElementSettings.inlineEdit&&Runner.pages.PageSettings.getTableData(this.tName,"inlineEditAvailable");},getSortingReloadParams:function(){var reloadParams=Runner.pages.ListPageDash.superclass.getSortingReloadParams.call(this),row=this.getRowByRowId(this.selectedId);if(row){reloadParams=reloadParams||{};reloadParams.reloadKeys=row&&row.keys;}
return reloadParams;},initSearch:Runner.emptyFn,initScrollGridBody:Runner.emptyFn,afterPageReady:Runner.emptyFn,initGridTabs:function(){var pageObj=this,eventName='click.'+this.dashElement;if(!this.$gridTabControl){return;}
this.$gridTabControl.off(eventName).on(eventName,'[data-pageid='+this.id+']',function(e){if(!pageObj.dashboard.getElementByName(pageObj.dashElement).major){pageObj.dashboard.doChangeTabAction(pageObj.dashElement,$(this).data("tabid"));return false;}
var baseParams={tab:$(this).data("tabid")},reloadParams=pageObj.getExtraPageReloadParams();pageObj.reload(baseParams,reloadParams);e.preventDefault();});}});Runner.pages.ChartPageDash=Runner.extend(Runner.pages.ChartPage,{baseParams:null,dependentElementsVisible:false,chartObj:null,lastSelectedData:null,constructor:function(cfg){Runner.pages.ChartPageDash.superclass.constructor.call(this,cfg);this.addEvents("afterPageReady");},init:function(){var startMasterKeys=Runner.pages.PageSettings.getTableData(this.tName,"startMasterKeys");Runner.pages.ChartPageDash.superclass.init.call(this);if(this.pageMode!=Runner.pages.constants.CHART_DASHDETAILS){this.lastSelectedData={masterKeys:startMasterKeys};if(this.dashboard.getElementByName(this.dashElement).major){this.updContext=this.dashboard.doReloadListAction(this.dashElement,{masterKeys:startMasterKeys},this.updContext);this.sendMoveAction({masterKeys:startMasterKeys},this.updContext);}}
this.finishDashElementActions();},sendMoveAction:function(data,updContext){this.dashboard.doMoveAction(this.dashElement,{pointId:data.pointId,seriesId:data.seriesId,masterKeys:data.masterKeys},updContext);},handleChartClick:function(data){this.lastSelectedData=data;this.sendMoveAction(data);},setActiveBar:function(data){this.lastSelectedData=data;if(this.chartObj){this.chartObj.selectPoint(data.seriesId,data.pointId,true);}},checkIfMasterKeysUpdated:function(masterData){return masterData&&masterData.seriesId==this.lastSelectedData.seriesId&&masterData.pointId==this.lastSelectedData.pointId},refreshDChartData:function(firstMasterData,masterKeysUpdated){if(firstMasterData===null){return;}
if(masterKeysUpdated){this.lastSelectedData=firstMasterData;}
if(firstMasterData.pointId!=this.lastSelectedData.pointId)
this.setActiveBar(this.lastSelectedData);if(this.dashboard.getElementByName(this.dashElement).major){this.handleChartClick(this.lastSelectedData);}},initGridTabs:function(){this.initGridTabs=Runner.pages.ListPageDash.prototype.initGridTabs;this.initGridTabs();},initSearch:Runner.emptyFn});Runner.pages.ChartPageDPDash=Runner.extend(Runner.pages.ChartPageDash,{constructor:function(cfg){Runner.pages.ChartPageDPDash.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.ChartPageDPDash.superclass.init.call(this);this.finishDashElementActions();},initGridTabs:function(){var pageObj=this;$('[data-pageid='+this.id+'][data-tabid]').on("click",function(e){var $link=$(this),$tab=$link.parent(),$pane;if($tab.hasClass('active')){return false;}
$tab.siblings().removeClass('active');$tab.addClass('active');pageObj.$originalTab.addClass('active');if($link.data('target')){$pane=$($link.data('target'));$pane.addClass('active').siblings().removeClass('active');}
var baseParams={tab:$(this).data("tabid")},reloadParams=pageObj.getExtraPageReloadParams();pageObj.reload(baseParams,reloadParams);e.preventDefault();});}});Runner.pages.EditPageDash=Runner.extend(Runner.pages.EditPage,{dashboard:null,dashElement:"",constructor:function(cfg){Runner.pages.EditPageDash.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.EditPageDash.superclass.init.call(this);if(this.dashboard.getElementByName(this.dashElement).major){if(!this.updContext||!this.updContext.hasUpdateRecordAction()){this.dashboard.doMoveAction(this.dashElement,{keys:this.keys,masterKeys:this.masterKeys},this.updContext);}
this.dashboard.doReportFirstLastAction(this.dashElement,!this.prevKeys,!this.nextKeys,this.updContext);}
this.finishDashElementActions();},showNextPrevButtons:function(next,prev){this.prevButton.toggleClass("rnr-invisible-button",!prev);this.nextButton.toggleClass("rnr-invisible-button",!next);},updateNavigationVisibility:function(){if(this.dashboard.getElementByName(this.dashElement).major){return;}
if(!this.dashAction||!this.dashAction.data.firstRecord){this.prevButton.removeClass("rnr-invisible-button");}
if(!this.dashAction||!this.dashAction.data.lastRecord){this.nextButton.removeClass("rnr-invisible-button");}},openPrevNextRecordPage:function(keys,step,updContext){if(!this.dashboard.getElementByName(this.dashElement).major){this.dashboard.doMoveAdjacentAction(this.dashElement,step>0);return;}
var i,params={baseParams:{}};for(i=0;i<keys.length;++i){params.baseParams['editid'+(i+1)]=keys[i];}
this.dashboard.loadSingleRecord(this.dashboard.getElementByName(this.dashElement),[Runner.pages.constants.PAGE_EDIT,Runner.pages.constants.PAGE_VIEW],params);},getForm:function(){if(this.form){return;}
Runner.pages.EditorPage.prototype.getForm.call(this);this.form.on('successSubmit',function(respObj,basicForm,fieldControls){if(respObj.success){this.dashboard.doUpdateRecordAction(this.dashElement,respObj);this.masterKeys=respObj.detKeys;this.pageReloadHn(respObj);this.fireEvent('afterPageReady',this,this.proxy,this.id);this.enablePageButtonsAfterSaving();return true;}
if(respObj.lockMessage){$('.rnr-locking').html(respObj.lockMessage).show();return false;}
if(this.hideCaptcha){$('.captcha_block').remove();}
this.displayHalfPreparedMessage(respObj.message||"",true);this.showBrick('message');this.initLoginLink();this.enablePageButtonsAfterSaving();return false;},this);},setAdjacentSelection:function(goForward,updContext,action){var pageObj=this;this.disablePageButtons();this.unlockPage(function(){pageObj.openPrevNextRecordPage(goForward?pageObj.nextKeys:pageObj.prevKeys,goForward?1:-1,updContext);});},setFirstFocus:Runner.emptyFn,setRecountFlagForPopup:Runner.emptyFn});Runner.pages.AddPageDash=Runner.extend(Runner.pages.AddPage,{constructor:function(cfg){Runner.pages.AddPageDash.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.AddPageDash.superclass.init.call(this);this.finishDashElementActions();},setBaseParams:function(){Runner.pages.AddPageDash.superclass.setBaseParams.call(this);if(this.isShowDetails){this.baseParams["editType"]=Runner.pages.constants.ADD_MASTER_DASH;}},initButtons:function(){Runner.pages.AddPageDash.superclass.initButtons.call(this);var pageObj=this;$("#resetButton"+this.id).on("click",function(e){pageObj.resetControls();clearTimeout(pageObj.validateTimer);$(this).parent().click();return false;});},getForm:function(){if(this.form){return;}
Runner.pages.EditorPage.prototype.getForm.call(this);this.addFormEventsForDetails();this.form.on('successSubmit',function(respObj,basicForm,fieldControls){if(respObj.success){this.dashboard.doAddRecordAction(this.dashElement,respObj);this.pageReloadHn(respObj);this.fireEvent('afterPageReady',this,this.proxy,this.id);return true;}
if(respObj.hideCaptcha){$('.captcha_block').remove();}
if(respObj.message){this.displayHalfPreparedMessage(respObj.message,true);this.showBrick('message');this.initLoginLink();}
this.enablePageButtonsAfterSaving();return false;},this);},isSubmitStandard:function(){return false;},setFirstFocus:Runner.emptyFn,onDetailsSaved:Runner.emptyFn,});Runner.pages.DashboardMap=Runner.extend(Runner.pages.RunnerPage,{pageType:Runner.pages.constants.PAGE_DASHMAP,mapId:"",mapManager:null,dashboard:null,constructor:function(cfg){Runner.pages.DashboardMap.superclass.constructor.call(this,cfg);this.mapId=Runner.goodFieldName(this.dashboard.tName)+'_'+this.dashElement+'_dashMap';},init:function(){Runner.pages.DashboardMap.superclass.init.call(this);this.initMap();},initMap:function(){var mapCfg=this.getMapCfg(),mapPage=this;if(!Runner.globalGmapLoader||!mapCfg){return;}
Runner.globalGmapLoader.onLoad(function(){this.mapManager=new Runner.controls.MapManager(mapCfg);this.mapManager.initMap(mapPage.mapId,$.proxy(mapPage.onMapLoad,mapPage));if(mapPage.dashboard.getElementByName(mapPage.dashElement).heatMap){this.mapManager.initHeatMap(mapPage.mapId);}},this);},getMapCfg:function(){var mapCfg=this.controlsMap?this.controlsMap.gMaps:null,mapObject=this;mapCfg.addMarkerClickEvent=function(marker,markerData){this.addOnMarkerClickHandler(marker,$.proxy(mapObject.onMarkerClickHandler,mapObject,marker,markerData));};return mapCfg;},onMarkerClickHandler:function(marker,markerData,e,updContext){var moveData=this.getMoveActionData(markerData.keys,markerData.masterKeys);this.setMarkerActive(markerData);return this.dashboard.doMoveAction(this.dashElement,moveData,updContext);},getMoveActionData:function(keys,masterKeys){return{keys:keys,masterKeys:masterKeys};},setMarkerActive:function(markerData,keys){if(this.dashboard.getElementByName(this.dashElement).heatMap){return;}
if(this.mapManager){this.mapManager.setMarkerActive(markerData,this.mapId,keys);}},updateMapAfterNewGridLineAdded:function(updContext,recordVals,iconData){if(this.mapManager){this.mapManager.updateAfterAdd(-1,recordVals,iconData);this.dashboard.doMoveAction(this.dashElement,this.getMoveActionData(recordVals.keys,recordVals.detKeys),updContext);}},updateMapAfterGridLineEdited:function(recordVals,keys,iconData){if(this.mapManager){this.mapManager.updateAfterEdit(-1,recordVals,keys,iconData);}},deleteSelectedMarkers:function(keyStrings){if(this.mapManager){this.mapManager.deleteSelectedMarkers(this.mapId,keyStrings);}},onMapLoad:function(){this.finishDashElementActions();},startTimerReload:function(){var pageObj=this;if(this.reloadTimerId){window.clearTimeout(this.reloadTimerId);}
if(this.dashboard.getElementByName(this.dashElement).reload){this.reloadTimerId=window.setTimeout(function(){var activeMarkerData=pageObj.mapManager.getActiveMarkerData(pageObj.mapId);if(activeMarkerData){pageObj.dashboard.doTimerReloadAction(pageObj.dashElement,{keys:activeMarkerData&&activeMarkerData.keys});}},1000*this.dashboard.getElementByName(this.dashElement).reload);}},setMapMarkers:function(markers){},initGridTabs:function(){var pageObj=this;if(!this.$gridTabControl){return;}
this.$gridTabControl.on('click.'+this.dashElement,'[data-pageid='+this.id+']',function(e){pageObj.$gridTabControl.children().removeClass('active');$(this).parent().addClass('active');pageObj.dashboard.doChangeTabAction(pageObj.dashElement,$(this).data("tabid"));return false;});}});Runner.pages.DashboardLeadingMap=Runner.extend(Runner.pages.DashboardMap,{skipMapEvent:false,constructor:function(cfg){Runner.pages.DashboardLeadingMap.superclass.constructor.call(this,cfg);},getMapCfg:function(){var mapCfg=Runner.pages.DashboardLeadingMap.superclass.getMapCfg.call(this);if(mapCfg){mapCfg.mapsData[this.mapId].centerLat=40.71;mapCfg.mapsData[this.mapId].centerLng=-74.01;}
return mapCfg;},onMapLoad:function(){var pageObj=this;this.reloadViewportMarkers(this.updContext);this.mapManager.onMapViewPortChanged(this.mapId,function(){if(!pageObj.skipMapEvent){pageObj.reloadViewportMarkers();}});},processTabChange:function(updContext,action){var tabId,pageObj=this,dashElement=this.dashboard.getElementByName(this.dashElement);if(!this.$gridTabControl){return;}
baseParams=Runner.apply({mapRefresh:false,tab:action.data.tabId,id:this.id},this.baseParams);updContext=updContext instanceof Runner.Dashboard.Context?updContext:null;action=action instanceof Runner.Dashboard.Action?action:null;Runner.runnerAJAX(this.requestUrl,baseParams,function(respObj){pageObj.pageReloadHn(respObj,updContext,action);});},reloadViewportMarkers:function(updContext,action){var tabId;if(this.mapManager.newMarkerWasAdded(this.mapId)){return;}
var dashElement=this.dashboard.getElementByName(this.dashElement);var vpCoordinates=this.getMapViewPortCoordinates(),pageObj=this,reloadData,baseParams;if(!vpCoordinates){return;}
baseParams=Runner.apply({vpCoordinates:JSON.stringify(vpCoordinates),mapRefresh:true,id:this.id},this.baseParams);if(this.$gridTabControl){baseParams.tab=this.$gridTabControl.children('.active').find('[data-tabid]').data('tabid');}
updContext=updContext instanceof Runner.Dashboard.Context?updContext:null;action=action instanceof Runner.Dashboard.Action?action:null;if(dashElement.clustering||dashElement.heatMap){updContext=this.dashboard.doMapViewPortChangedAction(this.dashElement,reloadData,updContext);activeMarkerData=this.mapManager.getActiveMarkerData(this.mapId);if(activeMarkerData){moveData=this.getMoveActionData(activeMarkerData.keys,activeMarkerData.masterKeys);this.dashboard.doMoveAction(this.dashElement,moveData,updContext);}
return;}
Runner.runnerAJAX(this.requestUrl,baseParams,function(respObj){pageObj.pageReloadHn(respObj,updContext,action);});},getMapViewPortCoordinates:function(){return this.mapManager?this.mapManager.getMapViewPortCoordinates(this.mapId):null;},getMoveActionData:function(keys,masterKeys){var data=Runner.pages.DashboardLeadingMap.superclass.getMoveActionData.call(this,keys,masterKeys),vpCoordinates=this.getMapViewPortCoordinates();if(vpCoordinates){data.vpCoordinates=JSON.stringify(vpCoordinates);}
return data;},onMarkerClickHandler:function(marker,markerData,e,updContext){updContext=Runner.pages.DashboardLeadingMap.superclass.onMarkerClickHandler.call(this,marker,markerData,e,updContext);this.sendReportNextPrev(updContext);},setAdjacentSelection:function(goForward,updContext,action){if(!this.mapManager){return;}
var markerData=this.mapManager.getPrevNextActiveMarkerData(goForward,this.mapId);if(markerData){this.onMarkerClickHandler(markerData.marker,markerData);}},sendReportNextPrev:function(updContext,firstRecord,lastRecord){if(firstRecord===undefined){firstRecord=!this.mapManager.getPrevNextActiveMarkerData(false,this.mapId);}
if(lastRecord===undefined){lastRecord=!this.mapManager.getPrevNextActiveMarkerData(true,this.mapId);}
this.dashboard.doReportFirstLastAction(this.dashElement,firstRecord,lastRecord,updContext);},updateMapAfterNewGridLineAdded:function(updContext,recordVals,iconData){if(!this.mapManager){return;}
Runner.pages.DashboardLeadingMap.superclass.updateMapAfterNewGridLineAdded.call(this,updContext,recordVals,iconData);this.sendReportNextPrev(updContext,true);},deleteSelectedMarkers:function(keyStrings){var updContext;Runner.pages.DashboardLeadingMap.superclass.deleteSelectedMarkers.call(this,keyStrings);if(!this.mapManager||this.mapManager.getActiveMarkerData(this.mapId)){return;}
var firstMarkerData=this.mapManager.getFirtMarkerData(this.mapId),moveData;if(!firstMarkerData){updContext=this.dashboard.doNoDataAction(this.dashElement);return;}
moveData=this.getMoveActionData(firstMarkerData.keys,firstMarkerData.masterKeys);this.mapManager.setMarkerActive(firstMarkerData,this.mapId);updContext=this.dashboard.doMoveAction(this.dashElement,moveData,updContext);this.sendReportNextPrev(updContext,true,false);},pageReloadHn:function(respObj,updContext,action){var reloadData={};this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.id];Runner.applyPagesData(respObj.pagesData);this.pageData=Runner.getPageData(this.id);this.proxy=this.pageData.proxy;if(this.$gridTabControl){this.$gridTabControl.html(this.pageData.gridTabs);}
if(!this.mapManager){return;}
var mapCfg=this.getMapCfg(),activeMarkerData,moveData,dontDeleteMarkers=false,updateViewport=false;if(action==null){dontDeleteMarkers=true;}
if(action&&mapCfg.mapsData[this.mapId]["markers"]&&mapCfg.mapsData[this.mapId]["markers"].length&&!(action instanceof Runner.Dashboard.TimerReloadAction)){updateViewport=true;}
this.skipMapEvent=true;this.mapManager.reinitMapMarkers(this.mapId,mapCfg.mapsData[this.mapId]["markers"],updateViewport,dontDeleteMarkers);this.skipMapEvent=false;reloadData.vpCoordinates=JSON.stringify(this.getMapViewPortCoordinates());reloadData.markersData=Runner.pages.ListPageDash.prototype.getMarkersForDependentMaps.call(this);reloadData.tabId=respObj.tabId;updContext=this.dashboard.doMapViewPortChangedAction(this.dashElement,reloadData,updContext);if(!this.mapManager.hasMarkers(this.mapId)){this.dashboard.doNoDataAction(this.dashElement,null,updContext);return;}
activeMarkerData=this.mapManager.getActiveMarkerData(this.mapId);if(activeMarkerData){moveData=this.getMoveActionData(activeMarkerData.keys,activeMarkerData.masterKeys);updContext=this.dashboard.doMoveAction(this.dashElement,moveData,updContext);}
this.startTimerReload();this.sendReportNextPrev(updContext);this.finishDashElementActions(updContext,action);},filterMarkersByMaster:function(masterTable,masterKeys,updContext,action){var idx,mapObj=this,baseParams=Runner.apply({mastertable:masterTable},this.baseParams);for(idx in masterKeys){baseParams[idx]=masterKeys[idx];}
baseParams.id=this.id;Runner.runnerAJAX(this.requestUrl,baseParams,function(respObj){var markers=respObj.controlsMap[mapObj.tName][mapObj.pageType][mapObj.id].gMaps.mapsData[mapObj.mapId].markers||[];mapObj.skipMapEvent=true;mapObj.mapManager.reinitMapMarkers(mapObj.mapId,markers,true);mapObj.skipMapEvent=false;mapObj.reloadViewportMarkers(updContext,action);});}});Runner.pages.DashboardGridBasedMap=Runner.extend(Runner.pages.DashboardMap,{markersData:null,constructor:function(cfg){Runner.pages.DashboardGridBasedMap.superclass.constructor.call(this,cfg);},getMapCfg:function(){var mapCfg=Runner.pages.DashboardGridBasedMap.superclass.getMapCfg.call(this);mapCfg.mapsData[this.mapId].markers=this.markersData||[];return mapCfg;},setMapMarkers:function(markers){var mapObj=this;this.markersData=markers;if(mapObj.mapManager){mapObj.mapManager.reinitMapMarkers(mapObj.mapId,markers,markers.length>0);}else{Runner.debugThrow();}}});Runner.pages.CheckboxesPage=Runner.extend(Runner.pages.ListPage,{disableCounter:0,columnHeaders:null,rowHeaders:null,ajaxActions:null,cbxPostfix:'',rowCbxPrefix:'',groups:[''],realValues:null,defaultValues:{},constructor:function(cfg){this.ajaxActions={};this.columnHeaders=[];Runner.pages.CheckboxesPage.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.CheckboxesPage.superclass.init.call(this);this.realValues=Runner.pages.PageSettings.getTableData(this.tName,"realValues");this.initGeneralControls();},initGeneralControls:function(){var pageObj=this;$('#saveBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.saveStateToDB(pageObj.saveCheckboxesState());}
return false;});$('#resetBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.resetCheckboxes();}
return false;});},initOrdinaryCheckboxes:function(checkbox){var pageObj=this,saveState=function(){pageObj.checkRowAndColumn();};if(checkbox!=undefined){$(checkbox).click(saveState);return;}
for(var g=0;g<pageObj.groups.length;g++){$.each(pageObj.rowHeaders,function(rIndex,rValue){var cbName='_'+rIndex+'_'+pageObj.groups[g];$.each(pageObj.columnHeaders,function(key,cheader){if($('#cb'+cheader+cbName).attr('id')!=undefined){$('#cb'+cheader+cbName).click(saveState);}});});}},initRowCheckboxes:function(){var pageObj=this,rowclick=function(){var chkBox=this;$.each(pageObj.columnHeaders,function(key,cheader){$('#cb'+cheader+'_'+$(chkBox).attr('id')+'_'+pageObj.cbxPostfix).each(function(){if(this.style.display!='none'){this.checked=$(chkBox).prop('checked');}});});pageObj.checkRowAndColumn();};$('input:checkbox[name^="'+this.rowCbxPrefix+'"]').each(function(){$(this).click(rowclick);});},initHeadCheckboxes:function(){var pageObj=this,headclick=function(){var $chkBox=$(this);$('input[id^='+$chkBox.attr('id')+'_]:visible').prop('checked',$chkBox.prop('checked'));pageObj.checkRowAndColumn();};$.each(this.columnHeaders,function(key,cheader){$('#cb'+cheader).click(headclick);});},saveStateToDB:function(valuesSet){var pageObj=this;$('input:checkbox').prop('disabled',true);this.disableControls(true);Runner.runnerAJAX(Runner.getPageUrl('ug_group'),{state:JSON.stringify(valuesSet),realValues:JSON.stringify(pageObj.rowHeaders),a:this.ajaxActions.saveState},function(respObj){if(!respObj.success){pageObj.replaceBrickContentHTMLWith('message',respObj.error);pageObj.showBrick('message');}else{pageObj.hideBrick('message');pageObj.defaultValues=pageObj.saveCheckboxesState();}
$('input:checkbox').prop('disabled',false);pageObj.disableControls(false);});},checkRowAndColumn:function(){if(this.disableCounter>1){return;}
var pageObj=this,colsState=[],rowsState=[];for(var i=0;i<this.columnHeaders.length;i++){$.each(this.rowHeaders,function(rIndex,rValue){if(colsState[i]==undefined){colsState[i]=[pageObj.columnHeaders[i],true];}
if(rowsState[rIndex]==undefined){rowsState[rIndex]=true;}
var cbxName='#cb'+pageObj.columnHeaders[i]+'_'+rIndex+'_'+pageObj.cbxPostfix;if($(cbxName).attr('id')!=undefined&&!$(cbxName).prop('checked')){colsState[i][1]=rowsState[rIndex]=false;}});}
$.each(colsState,function(key,cstate){$('#cb'+cstate[0]).prop('checked',this[1]);});$.each(rowsState,function(key,rstate){$('input:checkbox[name="'+pageObj.rowCbxPrefix+key+'"]:eq(0)').prop('checked',rstate);});}});Runner.pages.MembersPage=Runner.extend(Runner.pages.ListPage,{pageType:Runner.pages.constants.PAGE_ADMIN_MEMBERS,users:{},groups:{},fields:{},modifiedUsers:{},searchList:[],usersFilterState:"all",isSortTypeAscending:true,constructor:function(cfg){Runner.pages.MembersPage.superclass.constructor.call(this,cfg);this.users=Runner.pages.PageSettings.getTableData(this.tName,"usersList");this.groups=Runner.pages.PageSettings.getTableData(this.tName,"groupsList");this.fields=Runner.pages.PageSettings.getTableData(this.tName,"fieldsList");},init:function(){Runner.pages.MembersPage.superclass.init.call(this);this.initCheckboxes();this.initColumnHeaders();this.initRowHeaders();this.initSearchBox();this.initModifiedFilter();this.initSort();this.initSave();this.initReset();this.initChooseColumns();this.updateRowHeaderStates();this.updateColHeaderStates();},initCheckboxes:function(){var pageObj=this;$(".adminMembersTable").on("click","td:has(.rnr-checkbox:not(.columnheader):not(.rowheader))",function(e){var $checkbox=$(e.target).add($(e.target).find(".rnr-checkbox")).filter(".rnr-checkbox"),userid=$checkbox.attr("data-userid"),group=$checkbox.attr("data-group"),newchecked=$checkbox.attr("data-checked")=="1"?0:1,newUserState={};if(pageObj.users[userid]["groups"][group]==3){return;}
newUserState[group]=newchecked;pageObj.updateModifiedState(newUserState,userid);pageObj.updateRowHeaderState(userid);pageObj.updateColHeaderStates();pageObj.updateRowModifiedState(userid);pageObj.updateControlsState();$checkbox.attr("data-checked",newchecked);return false;});},initColumnHeaders:function(){var pageObj=this;$(".adminMembersTable").on("click",".columnheader",function(e){var $checkbox=$(e.target),group=$checkbox.data("group"),newchecked=$checkbox.attr("data-checked")=="1"?0:1;$(".adminMembersTable").find("[id^=box"+group+"]:visible").each(function(){var $checkbox=$(this);userid=$checkbox.data("userid");newUserState={};if(pageObj.users[userid]["groups"][group]==3){return;}
newUserState[group]=newchecked;$checkbox.attr("data-checked",newchecked);pageObj.updateModifiedState(newUserState,userid);pageObj.updateRowHeaderState(userid);pageObj.updateRowModifiedState(userid);});pageObj.updateColHeaderStates();pageObj.updateControlsState();return false;});},initRowHeaders:function(){var pageObj=this;$(".adminMembersTable").on("click",".rowheader",function(e){var $checkbox=$(e.target),newchecked=$checkbox.attr("data-checked")=="1"?0:1,userid=$checkbox.data("userid"),newUserState={};$.each(pageObj.groups,function(groupId,groupName){if(pageObj.users[userid]["groups"][groupId]==3||!pageObj.isVisibleField(groupId)){return;}
$("#box"+groupId+userid).attr("data-checked",newchecked);newUserState[groupId]=newchecked;});pageObj.updateModifiedState(newUserState,userid);pageObj.updateColHeaderStates();pageObj.updateRowHeaderState(userid);pageObj.updateRowModifiedState(userid);pageObj.updateControlsState();return false;});},updateModifiedState:function(newGroupsStates,userId){var pageObj=this,savedUserGroupsStates=this.users[userId]["groups"],userName=this.users[userId]["userName"],modifiedUserGroupsStates=this.modifiedUsers[userName]||{};$.each(newGroupsStates,function(group,newGroupState){if(typeof savedUserGroupsStates[group]!=='undefined'&&savedUserGroupsStates[group]!=newGroupState){modifiedUserGroupsStates[group]=newGroupState;}else{delete modifiedUserGroupsStates[group];}});if(!$.isEmptyObject(modifiedUserGroupsStates)){this.modifiedUsers[userName]=modifiedUserGroupsStates;}else{delete this.modifiedUsers[userName];}},updateRowHeaderState:function(userId){var pageObj=this,$checkbox=$('#rowbox'+userId),savedStates=this.users[userId]["groups"],userName=this.users[userId]["userName"],modifiedStates=this.modifiedUsers[userName]||{},unsavedState=$.extend({},savedStates,modifiedStates),summState=0,count=0;$.each(unsavedState,function(group,state){if(!pageObj.isVisibleField(group)){return;}
state=state==3?1:state;summState+=state;count++;});if(summState==0){$checkbox.attr("data-checked",0);}else if(summState==count){$checkbox.attr("data-checked",1);}else{$checkbox.attr("data-checked",2);}},updateRowHeaderStates:function(){var pageObj=this;$.each(this.users,function(userId,userInfo){pageObj.updateRowHeaderState(userId);});},updateColHeaderStates:function(){var pageObj=this,colBoxStates={};$.each(pageObj.groups,function(groupId,groupName){colBoxStates[groupId]={"summState":0,"count":0};});$.each(this.users,function(userId,userInfo){if(userInfo["visible"]){var unsavedGroups=$.extend({},userInfo["groups"],pageObj.modifiedUsers[userInfo["userName"]]);$.each(unsavedGroups,function(group,state){state=state==3?1:state;colBoxStates[group]["summState"]+=state;colBoxStates[group]["count"]++;});}});$.each(colBoxStates,function(group,state){var $colBox=$("#colbox"+group);if(state["summState"]==0){$colBox.attr("data-checked",0);}else if(state["summState"]==state["count"]){$colBox.attr("data-checked",1);}else{$colBox.attr("data-checked",2);}});},updateRowModifiedState:function(userId){var pabeObj=this,userName=this.users[userId]["userName"];modifiedGroups=this.modifiedUsers[userName]||{},savedGroups=this.users[userId]["groups"],userModified=false;$.each(savedGroups,function(group,state){var groupModified=group in modifiedGroups;$("#cell"+group+userId).toggleClass("rights-modified",groupModified);userModified=userModified||groupModified;});$("#cellusername"+userId).toggleClass("rights-modified",userModified);$("#cellDisplayName"+userId).toggleClass("rights-modified",userModified);$("#cellEmail"+userId).toggleClass("rights-modified",userModified);},initSearchBox:function(){var pageObj=this;$("#adminMembersSearch").on("input",function(){pageObj.searchList=$(this).val().trim().toUpperCase().match(/[^\s]+/g)||[];pageObj.showHideRows();});},showHideRows:function(){var pageObj=this;$.each(this.users,function(userId,userInfo){pageObj.toggleElement($("#usernamerow"+userId),pageObj.isUserDisplayed(userId));});this.updateColHeaderStates();},isUserDisplayed:function(userId){var pageObj=this,show=true,i,userName=this.users[userId]["userName"]||"";upperCaseUserName=userName.toUpperCase(),upperCaseDisplayUserName=(this.users[userId]["displayUserName"]||"").toUpperCase(),upperCaseEmailUser=(this.users[userId]["emailUser"]||"").toUpperCase(),allModifiedGroupsVisible=false;if(this.searchList.length){show=false;for(i=this.searchList.length-1;!show&&i>=0;--i){show=this.searchList[i]&&(upperCaseUserName.indexOf(this.searchList[i])>=0||upperCaseDisplayUserName.indexOf(this.searchList[i])>=0||upperCaseEmailUser.indexOf(this.searchList[i])>=0);}}
if(userName in this.modifiedUsers){$.each(this.modifiedUsers[userName],function(groupId,groupState){allModifiedGroupsVisible=allModifiedGroupsVisible||pageObj.isVisibleField(groupId);});}
show=show&&(this.usersFilterState=='all'||(this.usersFilterState=='modified'&&userName in this.modifiedUsers&&allModifiedGroupsVisible));this.users[userId]["visible"]=show;return show;},toggleElement:function($elem,show){if(!show){$elem.hide();}else{$elem.css('display','');}},initModifiedFilter:function(){var pageObj=this;(new Runner.linkSelectControl($("#linkselectFilter").get(0))).change(function(){pageObj.usersFilterState=this.val();pageObj.showHideRows();});},setSortIcon:function($link){$("#userNameSort").removeAttr("data-icon");$("#displayNameSort").removeAttr("data-icon");$("#EmailSort").removeAttr("data-icon");$.each(this.groups,function(groupId,groupName){$("#colsort"+groupId).removeAttr("data-icon");});$($link).attr("data-icon",this.isSortTypeAscending?"sortasc":"sortdesc");},sort:function($link,field){var $firstRow=$(".adminMembersTable").find("tr.rnr-row:first"),$insertRow,rowid,group,orderedUsers=[],pageObj=this;$.each(this.users,function(userId,userInfo){userInfo["groups"]=$.extend({},userInfo["groups"],pageObj.modifiedUsers[userInfo["userName"]]);userInfo=$.extend({},{"userId":userId},userInfo);orderedUsers.push(userInfo);});this.isSortTypeAscending=!this.isSortTypeAscending;this.setSortIcon($link);group=$($link).data("group");orderedUsers.sort(function(a,b){var result=0;if(group){a=a["groups"][group]||0;b=b["groups"][group]||0;}else{a=a[field];b=b[field];}
if(a>b){result=pageObj.isSortTypeAscending?1:-1;}else if(b>a){result=pageObj.isSortTypeAscending?-1:1;}
return result;});$.each(orderedUsers,function(idx,userInfo){rowid="usernamerow"+userInfo["userId"];if($firstRow.attr("id")!=rowid&&userInfo["visible"]){$insertRow=$("#"+rowid);$firstRow.after($insertRow);$firstRow=$insertRow;}});},initSort:function(){var pageObj=this;$("#userNameSort").on("click",function(){pageObj.sort(this,'userName');});$("#displayNameSort").on("click",function(){pageObj.sort(this,'displayUserName');});$("#EmailSort").on("click",function(){pageObj.sort(this,'emailUser');});$.each(this.groups,function(groupId,groupName){$("#colsort"+groupId).on("click",function(){pageObj.sort(this);});});},initSave:function(){var pageObj=this;$("#saveBtn").on("click",function(){if(Runner.isDisabledButton(this)){return false;}
pageObj.disableControls();$.ajax({type:"POST",data:{values:JSON.stringify(pageObj.modifiedUsers),a:'saveMembers'},dataType:"json",error:function(jqXHR,textStatus,errorThrown){pageObj.displayGenericAjaxError(jqXHR.responseText);pageObj.updateControlsState();},success:function(_respObj){var respObj=_respObj||{error:"Error. Null response"};if(!respObj.success){pageObj.displayMessage(respObj.error,true,true);pageObj.updateControlsState();return false;}
$.each(pageObj.modifiedUsers,function(userName,groups){var userId=pageObj.getUserIdByUserName(userName);pageObj.users[userId]["groups"]=$.extend({},pageObj.users[userId]["groups"],groups);delete pageObj.modifiedUsers[userName];pageObj.updateRowModifiedState(userId);});pageObj.updateControlsState();}});return false;});},disableControls:function(){Runner.addDisabledClass($('#resetBtn'));Runner.addDisabledClass($('#saveBtn'));this.setPageModified(false);},enableControls:function(){Runner.delDisabledClass($('#resetBtn'));Runner.delDisabledClass($('#saveBtn'));this.setPageModified(true);},updateControlsState:function(){if($.isEmptyObject(this.modifiedUsers)){this.disableControls();}else{this.enableControls();}},initReset:function(){var pageObj=this;$("#resetBtn").click(function(){if(Runner.isDisabledButton(this)){return false;}
$.each(pageObj.modifiedUsers,function(userName,groups){var userId=pageObj.getUserIdByUserName(userName);$.each(groups,function(groupId,state){state=state?0:1;$("#box"+groupId+userId).attr("data-checked",state);});delete pageObj.modifiedUsers[userName];pageObj.updateRowModifiedState(userId);pageObj.updateRowHeaderState(userId);});pageObj.updateColHeaderStates();pageObj.updateControlsState();return false;});this.updateControlsState();},getUserIdByUserName:function(userName){var userId=0;$.each(this.users,function(idx,userInfo){if(userInfo["userName"]==userName){userId=idx;return false;}});return userId;},initChooseColumns:function(){var pageObj=this,bsUsed=Runner.isBootstrap(),args={modal:true,centered:true,headerContent:Runner.lang.constants.AA_CHOOSE_COLUMNS_TO_DIPLAY,bodyContent:''};$('#chooseColumnsButton').on('click',function(e){if(bsUsed){args.footerContent='<a href="#" id="mpSelectAll" class="btn btn-primary">'+Runner.lang.constants.SELECT_ALL+'</a>'
+'<a href="#" id="mpAASelectNone" class="btn btn-default">'+Runner.lang.constants.AA_SELECT_NONE+'</a>'
+'<a href="#" id="mpAAOk" class="btn btn-default">'+Runner.lang.constants.AA_OK+'</a>'
+'<a href="#" id="mpAACancel" class="btn btn-default">'+Runner.lang.constants.CANCEL+'</a>';Runner.pages.PageManager.createBSWin(args,false,$.proxy(pageObj.flyWinHandler,pageObj));}else{Runner.pages.PageManager.createFlyWin(args,false,$.proxy(pageObj.flyWinHandler,pageObj));}
return false;});},addButtonToFlyWin:function(win,label,name,action){if(!win){return;}
win.addButton({label:label,name:name,template:"<a />",classNames:"rnr-button",section:Runner.Y.WidgetStdMod.BOTTOM,action:action});},selectAllNoneToFlyWin:function(State,modifiedFields){$.each(this.fields,function(idx,fieldInfo){$("#"+idx+"fieldCheckbox").attr("data-checked",State);modifiedFields[idx]={"visible":State};});},flyWinHandler:function(win){if(!win&&!$win._obj){return false;}
var pageObj=this,bsUsed=Runner.isBootstrap(),modifiedFields={},$rows=$("<div></div>"),$modal;$.each(this.fields,function(idx,fieldInfo){var $row=$('<a class="chooseColumnsLink"></a>').text(" "+fieldInfo["caption"]),$checkBox=$('<span class="rnr-checkbox rowheader" id="'+idx+'fieldCheckbox"></span>').attr("data-checked",fieldInfo["visible"]).prependTo($row);$row.on("click",function(){var newChecked=$checkBox.attr("data-checked")=="1"?0:1;$checkBox.attr("data-checked",newChecked);modifiedFields[idx]={"visible":newChecked};}).appendTo($rows);});if(bsUsed){$modal=win._obj;$rows.appendTo($(".modal-body",$modal));$("#mpSelectAll",$modal).on("click",function(e){pageObj.selectAllNoneToFlyWin(1,modifiedFields);});$("#mpAASelectNone",$modal).on("click",function(e){pageObj.selectAllNoneToFlyWin(0,modifiedFields);});$("#mpAAOk",$modal).on("click",function(e){$.each(modifiedFields,function(idx,fieldInfo){var fieldName=pageObj.fields[idx]["name"],sortLink=idx==="0"?$("#displayNameSort"):$("#colsort"+fieldName);pageObj.fields[idx]=$.extend({},pageObj.fields[idx],fieldInfo);pageObj.toggleElement($("#tdsort"+fieldName),fieldInfo["visible"]);pageObj.toggleElement($("#tdbox"+fieldName),fieldInfo["visible"]);pageObj.toggleElement($("[id^=cell"+fieldName+"]"),fieldInfo["visible"]);if(sortLink.attr("data-icon")){pageObj.isSortTypeAscending=!pageObj.isSortTypeAscending;pageObj.sort($("#userNameSort"),'userName');}});pageObj.updateRowHeaderStates();pageObj.showHideRows();$modal.modal("hide");});$("#mpAACancel",$modal).on("click",function(e){$modal.modal("hide");});return;}
$rows.appendTo(win._obj.bodyNode.getDOMNode());this.addButtonToFlyWin(win._obj,Runner.lang.constants.SELECT_ALL,"selectAll",function(e){pageObj.selectAllNoneToFlyWin(1,modifiedFields);});this.addButtonToFlyWin(win._obj,Runner.lang.constants.AA_SELECT_NONE,"selectNone",function(e){pageObj.selectAllNoneToFlyWin(0,modifiedFields);});this.addButtonToFlyWin(win._obj,Runner.lang.constants.AA_OK,"ok",function(e){$.each(modifiedFields,function(idx,fieldInfo){var fieldName=pageObj.fields[idx]["name"],sortLink=idx==="0"?$("#displayNameSort"):$("#colsort"+fieldName);pageObj.fields[idx]=$.extend({},pageObj.fields[idx],fieldInfo);pageObj.toggleElement($("#tdsort"+fieldName),fieldInfo["visible"]);pageObj.toggleElement($("#tdbox"+fieldName),fieldInfo["visible"]);pageObj.toggleElement($("[id^=cell"+fieldName+"]"),fieldInfo["visible"]);if(sortLink.attr("data-icon")){pageObj.isSortTypeAscending=!pageObj.isSortTypeAscending;pageObj.sort($("#userNameSort"),'userName');}});pageObj.updateRowHeaderStates();pageObj.showHideRows();win._obj.destroy(true);});this.addButtonToFlyWin(win._obj,Runner.lang.constants.CANCEL,"cancel",function(e){win._obj.destroy(true);});Runner.pages.PageManager.correctYUIWindowSize(win._obj,true);},isVisibleField:function(fieldName){var visible=false;$.each(this.fields,function(idx,fieldInfo){if(fieldInfo["name"]==fieldName&&fieldInfo["visible"]==1){visible=true;return false;}});return visible;}});Runner.pages.RightsPage=Runner.extend(Runner.pages.ListPage,{pageType:Runner.pages.constants.PAGE_ADMIN_RIGHTS,TEXT_AA_ADD_NEW_GROUP:Runner.lang.constants.AA_ADD_NEW_GROUP,TEXT_AA_RENAMEGROUP:Runner.lang.constants.AA_RENAMEGROUP,renameidx:-1,groups:null,tables:null,masks:{},modifiedRights:{},shortTables:{},tablesFilterState:"all",SEARCHLIST:[],menuOrderedTables:null,alphaOrderedTables:null,disabledMode:false,allExpanded:false,orderMethod:'menu',$groupControl:null,constructor:function(cfg){var pageObj=this;Runner.pages.RightsPage.superclass.constructor.call(this,cfg);this.groups=Runner.pages.PageSettings.getTableData(this.tName,"groups");this.savedRights=Runner.pages.PageSettings.getTableData(this.tName,"rights");this.tables=Runner.pages.PageSettings.getTableData(this.tName,"tables");this.pageMasks=Runner.pages.PageSettings.getTableData(this.tName,"pageMasks");this.menuOrderedTables=Runner.pages.PageSettings.getTableData(this.tName,"menuOrderedTables");this.alphaOrderedTables=Runner.pages.PageSettings.getTableData(this.tName,"alphaOrderedTables");jQuery.each(this.tables,function(table){pageObj.shortTables[this[0]]=table;});},init:function(){Runner.pages.RightsPage.superclass.init.call(this);Runner.addDisabledClass($('#resetBtn'));Runner.addDisabledClass($('#saveBtn'));if(this.isBootstrap()){this.$groupControl=$('[data-brick="bsugrightsgroups"]');}else{this.$groupControl=$('.group');this.$groupControl.prop('disabled',false);}
this.initMasks();this.initSearchBox();this.initGroupsList();this.initSelGroup();this.initColumnHeaders();this.initRowHeaders();this.initCheckboxes();this.initRightsControls();this.initModifiedFilter();this.initOrderControl();this.initExpandAll();this.initExpandCollapseControls();this.initSave();this.initReset();this.initCopyPermissions();this.showHideRows();},initSelGroup:function(){var groupCount=0;if(!this.isBootstrap()){jQuery.each(this.groups,function(){++groupCount;});if($('.group ').attr('orientation')!='horizontal'){$('.group').attr('size',groupCount);}
if(!$('.group :selected')){$('.group :first').prop('selected',true);}}},initMasks:function(){this.masks={add:'A',edt:'E',del:'D',lst:'S',exp:'P',imp:'I',adm:'M'}},initRightsControls:function(){var pageObj=this,afterCreatePopup=function(win){$('.groupname').css('width',"300px");$('.alert-danger').hide();$('.groupname').focus();$('#saveGroupBtn').click(function(){if(pageObj.save()){win.close();}else{win.setHeight(260);$('.alert-danger').show();}});$('.groupname').keydown(function(e){if(e.keyCode!=13){return;}
if(pageObj.save()){win.close();}else{win.setHeight(260);$('.alert-danger').show();}});},afterClosePopup=function(){pageObj.disableGroupButtons(false);};$('#saveGroupBtn').click(function(){pageObj.save();return false;});$('#addGroupBtn').click(function(e){var params;if(Runner.isDisabledButton(this)){return false;}
pageObj.renameidx=-1;pageObj.disableGroupButtons(true);if(!pageObj.isBootstrap()){$('.group').prop('disabled',true);$('.rnr-ugaddarea').show();$('.groupname').focus().val(pageObj.makename(Runner.lang.constants.AA_GROUP_NEW));$('.gmessage').html(pageObj.TEXT_AA_ADD_NEW_GROUP);return false;}
params={header:pageObj.TEXT_AA_ADD_NEW_GROUP,width:340,height:200,afterClose:afterClosePopup,afterCreate:afterCreatePopup};params.html="<div class='alert alert-danger'></div>"
+"<div>"
+"<input class='groupname form-control' type='text' value='"+pageObj.makename(Runner.lang.constants.AA_GROUP_NEW)+"'>"
+"</div>";params.footer="<a id='saveGroupBtn' class='btn btn-primary' href='#'>Save</a>";Runner.displayPopup(params);return false;});$('#delGroupBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.deletegroup();}
return false;});$('#renGroupBtn').click(function(e){var selectedIdVal,selectedHtmlVal,params;if(!pageObj.isBootstrap()){selectedIdVal=this.currentGroup||$('.group option:selected').val();}else{selectedIdVal=this.currentGroup||$("ul.nav-tabs").find("li.active").find("a").attr("value");}
selectedHtmlVal=pageObj.groups[selectedIdVal];if(Runner.isDisabledButton(this)||selectedIdVal<0){return false;}
pageObj.disableGroupButtons(true);if(!pageObj.isBootstrap()){$('.group').prop('disabled',true);$('.rnr-ugaddarea').show();$('.groupname').focus().val(selectedHtmlVal);$('.gmessage').html(pageObj.TEXT_AA_RENAMEGROUP);pageObj.renameidx=$('.group')[0].selectedIndex;return false;}
pageObj.renameidx=$("ul.nav-tabs").find("li.active").find("a").attr("value");params={header:pageObj.TEXT_AA_RENAMEGROUP,width:340,height:200,afterClose:afterClosePopup,afterCreate:afterCreatePopup};params.html="<div class='alert alert-danger'></div>"
+"<div><input class='groupname form-control' type='text' value='"+selectedHtmlVal+"'></div>";params.footer="<a id='saveGroupBtn' class='btn btn-primary' href='#'>Save</a>";Runner.displayPopup(params);return false;});$('.groupname').keydown(function(e){if(e.keyCode!=13){return;}
pageObj.save();return false;});$('#cancelBtn').click(function(){pageObj.hideBrick('message');$('.rnr-ugaddarea').hide();$('.group').prop('disabled',false);pageObj.disableGroupButtons(false);if(pageObj.renameidx>=0){$('.groupname').val('');}});},disableGroupButtons:function(isDisable){if(isDisable){Runner.addDisabledClass($('#addGroupBtn'));Runner.addDisabledClass($('#delGroupBtn'));Runner.addDisabledClass($('#renGroupBtn'));Runner.addDisabledClass($('#copyPermissions'));if(this.isBootstrap()){$("li").addClass("disabled");}}else{Runner.delDisabledClass($('#addGroupBtn'));Runner.delDisabledClass($('#copyPermissions'));if(this.isBootstrap()){$("li").removeClass("disabled");}
$('#addGroupBtn').prop('disabled',isDisable);this.setButtonsActiveState();}},setButtonsActiveState:function(){if($('.group :selected').val()<0||$("ul.nav-tabs").find("li.active").find("a").attr("value")<0){Runner.addDisabledClass($('#delGroupBtn'));Runner.addDisabledClass($('#renGroupBtn'));$('#delGroupBtn').css("opacity",0);$('#renGroupBtn').css("opacity",0);}else{Runner.delDisabledClass($('#delGroupBtn'));Runner.delDisabledClass($('#renGroupBtn'));$('#delGroupBtn').css("opacity",100);$('#renGroupBtn').css("opacity",100);this.initRunnerButtons();$('.groupname').val(this.groups[$('.group :selected').val()]);}},deletegroup:function(){var pageObj=this,id,ajaxParams;if(!pageObj.isBootstrap()){id=$('.group :selected').val();}else{id=$("ul.nav-tabs").find("li.active").find("a").attr("value");}
ajaxParams={id:id,a:'del'};if(id<0){return;}
if(!confirm(Runner.lang.constants.AA_DELETEGROUP+" "+this.groups[id]+'?')){return;}
Runner.runnerAJAX(Runner.getPageUrl('ug_group'),ajaxParams,function(respObj){var groupCount=0,newId;if(!pageObj.isBootstrap()){if(!respObj.success){pageObj.replaceBrickContentHTMLWith('message','Error deleting record!');pageObj.showBrick('message');return;}
pageObj.hideBrick('message');}else{if(!respObj.success){$('.alert-danger').html('Error deleting record!');return false;}}
if(!pageObj.groups.hasOwnProperty(id)){pageObj.groups=Runner.apply({},pageObj.groups);}
delete pageObj.groups[id];if(!pageObj.modifiedRights.hasOwnProperty(id)){pageObj.modifiedRights=Runner.apply({},pageObj.modifiedRights);}
delete pageObj.modifiedRights[id];if(!pageObj.isBootstrap()){newId=$('.group :selected').prev().val();$('.group :selected').remove();if(newId){$(".group [value='"+newId+"']").prop('selected',true);}else{$('.group :first').prop('selected',true);}
$('.group').trigger('change');}else{newId=$("ul.nav-tabs").find("li.active").prev().find("a").attr("value");$("ul.nav-tabs").find("li.active").remove();if(newId){$("a[value="+newId+"]").click();}else{$("[role=presentation] :first").find("a").click();}}
pageObj.updateGroupsModifiedStates();});},initReset:function(){var pageObj=this;$('#resetBtn').click(function(){if(Runner.isDisabledButton(this)){return false;}
pageObj.modifiedRights={};pageObj.groupListChange();pageObj.updateGroupsModifiedStates();return false;})},disableControls:function(){this.disabledMode=true;this.setPageModified(false);Runner.addDisabledClass($('#resetBtn'));Runner.addDisabledClass($('#saveBtn'));},enableControls:function(){this.disabledMode=false;this.setPageModified(true);Runner.delDisabledClass($('#resetBtn'));Runner.delDisabledClass($('#saveBtn'));},initSave:function(){var pageObj=this;$('#saveBtn').click(function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disableControls();pageObj.hideMessage();$.ajax({type:"POST",data:{values:JSON.stringify(pageObj.modifiedRights),a:'saveRights'},dataType:"json",error:function(jqXHR,textStatus,errorThrown){pageObj.displayGenericAjaxError(jqXHR.responseText);pageObj.enableControls();},success:function(_respObj){var respObj=_respObj||{error:"Error. Null response"};if(!respObj.success){pageObj.displayMessage(respObj.error,true,true);pageObj.enableControls();return;}
jQuery.each(pageObj.modifiedRights,function(group,permissionsObj){jQuery.each(permissionsObj,function(table,perm){if(typeof pageObj.savedRights[table]=='undefined'){pageObj.savedRights[table]={};}
pageObj.savedRights[table][group]=perm;});});pageObj.modifiedRights={};pageObj.groupListChange();pageObj.updateGroupsModifiedStates();pageObj.disabledMode=false;}});return false;});},makename:function(groupName){var n=1,gr=$('.group option'),tgroupName=groupName,found;while(1){found=false;jQuery.each(this.groups,function(groupId,groupName){if(groupName==tgroupName){found=true;return false;}});if(!found){return tgroupName;}
tgroupName=groupName+n;n++;}},save:function(){var pageObj=this,i,name,ajaxParams,existGroupName;if(!pageObj.isBootstrap()){for(i=0;i<$('.group option').length;i++){if(this.groups[$('.group option:eq('+i+')').val()]==$('.groupname').val()&&this.renameidx!=i){pageObj.replaceBrickContentHTMLWith('message','Group with such name is allready exist!');pageObj.showBrick('message');return;}}}else{existGroupName=false;$.each($("[role=presentation]").find("a"),function(){ind=$(this).attr("value");if(pageObj.groups[$(this).attr("value")]==$('.groupname').val()&&pageObj.renameidx!=ind){$('.alert-danger').html('Group with such name is allready exist!');existGroupName=true;return;}});if(existGroupName){return false;}}
if(this.renameidx==-1){name=$('.groupname').val();ajaxParams={name:name,a:'add'};Runner.runnerAJAX(Runner.getPageUrl('ug_group'),ajaxParams,function(respObj){var groupCount=0,id;if(!pageObj.isBootstrap()){if(!respObj.success){pageObj.replaceBrickContentHTMLWith('message','Error adding group!');pageObj.showBrick('message');return;}}else{if(!respObj.success){$('.alert-danger').html('Error adding group!');return false;}}
pageObj.hideBrick('message');id=respObj.id;pageObj.groups[id]=name;if(!pageObj.isBootstrap()){$('.rnr-ugaddarea').hide();$('<option value="'+id+'">'+name+'</option>').appendTo($('.group')).prop('selected',true);jQuery.each(pageObj.groups,function(){++groupCount;});$('.group').attr('size',groupCount);$('.group').trigger('change');$('.groupname').val('');$('.group').prop('disabled',false);}else{$("[data-brick=bsugrightsgroups]").append("<li class='' role='presentation'><a value='"+id+"' href='#'>"+name+"</a></li>");$("a[value="+id+"]").click();}
pageObj.disableGroupButtons(false);});return true;}
this.renameidx=-1;if(!pageObj.isBootstrap()){if(this.groups[$('.group :selected').val()]==$('.groupname').val()){this.saveEnd();return;}
ajaxParams={id:$('.group :selected').val(),name:$('.groupname').val(),a:'rename'}}else{if(this.groups[$("ul.nav-tabs").find("li.active").find("a").attr("value")]==$('.groupname').val()){this.saveEnd();return true;}
ajaxParams={id:$("ul.nav-tabs").find("li.active").find("a").attr("value"),name:$('.groupname').val(),a:'rename'}}
var name=$('.groupname').val();Runner.runnerAJAX(Runner.getPageUrl('ug_group'),ajaxParams,function(respObj){if(!pageObj.isBootstrap()){if(!respObj.success){pageObj.replaceBrickContentHTMLWith('message','Error renaming group!');pageObj.showBrick('message');return;}
pageObj.groups[$('.group :selected').val()]=name;$('.group :selected').html(name);pageObj.updateGroupModifiedState($('.group :selected').val());}else{if(!respObj.success){$('.alert-danger').html('Error renaming group!');return false;}
pageObj.groups[$("ul.nav-tabs").find("li.active").find("a").attr("value")]=name;$("ul.nav-tabs").find("li.active").find("a").html(name);pageObj.updateGroupModifiedState($("ul.nav-tabs").find("li.active").find("a").attr("value"));}
pageObj.saveEnd();});return true;},saveEnd:function(){this.hideBrick('message');$('.rnr-ugaddarea').hide();$('.groupname').val('');$('.group').prop('disabled',false);this.disableGroupButtons(false);},initCheckboxes:function(){var pageObj=this;$(".rightsTable").on("click","td:has(.rnr-checkbox:not(.columnheader):not(.rowheader))",function(e){var $checkbox=$(e.target).add($(e.target).find(".rnr-checkbox")).filter(".rnr-checkbox"),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1",shortTable=pageObj.getTableNameFromBox($checkbox.attr("id")),table=pageObj.shortTables[shortTable],modifiedMask;if(pageObj.disabledMode){return false;}
if(0==$checkbox.length){return;}
$checkbox.attr("data-checked",newchecked);modifiedMask=pageObj.updateModifiedState(pageObj.readTablePermissionsFromGrid(shortTable),shortTable);pageObj.updateRowModifiedState(shortTable,modifiedMask);pageObj.updateRowHeaderState(table);pageObj.updateColHeaderStates();pageObj.updateGroupsModifiedStates();return false;});},initColumnHeaders:function(){var pageObj=this;$(".rightsTable").on("click",".columnheader",function(e){var $checkbox=$(e.target),perm=$checkbox.data("perm"),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1";if(pageObj.disabledMode){return;}
$(".rightsTable").find("[id^=box"+perm+"]:visible").each(function(){var shortTable=pageObj.getTableNameFromBox(this.id),table=pageObj.shortTables[shortTable];if(pageObj.pageMasks[pageObj.shortTables[shortTable]].indexOf(perm)==-1){return;}
$(this).attr("data-checked",newchecked);modifiedMask=pageObj.updateModifiedState(pageObj.readTablePermissionsFromGrid(shortTable),shortTable);pageObj.updateRowModifiedState(shortTable,modifiedMask);pageObj.updateRowHeaderState(table);});pageObj.updateGroupsModifiedStates();$checkbox.attr("data-checked",newchecked);});},initRowHeaders:function(){var pageObj=this;$(".rightsTable").on("click",".rowheader",function(e){var $checkbox=$(e.target),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1",shortTable=$checkbox.data("table"),table=pageObj.shortTables[shortTable];if(pageObj.disabledMode){return;}
jQuery.each(pageObj.pageMasks[table].split(""),function(){pageObj.getBoxObj(this,shortTable).attr("data-checked",newchecked);});$checkbox.attr("data-checked",newchecked);modifiedMask=pageObj.updateModifiedState(pageObj.readTablePermissionsFromGrid(shortTable),shortTable);pageObj.updateRowModifiedState(shortTable,modifiedMask);pageObj.updateRowHeaderState(table);pageObj.updateColHeaderStates();pageObj.updateGroupsModifiedStates();return false;});},groupListChange:function(){var pageObj=this;if(this.isBootstrap()){this.currentGroup=this.$groupControl.find('li.active > a').attr('value');}else{this.currentGroup=$('.group :selected').val();}
jQuery.each(this.tables,function(table){var tableRights=pageObj.getTableActivePermissions(table,pageObj.currentGroup),shortName=this[0];jQuery.each(pageObj.masks,function(right,identifier){var checked=tableRights.indexOf(identifier)>-1?"1":"0";pageObj.getBoxObj(identifier,shortName).attr("data-checked",checked);});pageObj.updateRowModifiedState(shortName,pageObj.getTableModifiedMask(table));});this.updateRowHeaderStates();this.showHideRows();},initGroupsList:function(){var pageObj=this;if(this.isBootstrap()){this.$groupControl.on('click','a[value]',function(){pageObj.$groupControl.children('.active').removeClass('active');$(this).parent().addClass('active');pageObj.groupListChange();pageObj.setButtonsActiveState();});pageObj.groupListChange();pageObj.setButtonsActiveState();}else{$('.group').on('change',function(e){pageObj.groupListChange();pageObj.setButtonsActiveState();});$('.group').change();}},updateGroupHasVisibleItemsFlag:function(menuItem){var pageObj=this;menuItem.hasVisibleItems=false;if(!menuItem.items){return;}
jQuery.each(menuItem.items,function(){var subitem=pageObj.menuOrderedTables[this];pageObj.updateGroupHasVisibleItemsFlag(subitem);if(subitem.table&&pageObj.tables[subitem.table].visible||subitem.hasVisibleItems){menuItem.hasVisibleItems=true;}});},updateAllHasVisibleItemsFlags:function(){var pageObj=this;jQuery.each(this.menuOrderedTables,function(){if(typeof this.parent==='undefined'){pageObj.updateGroupHasVisibleItemsFlag(this);}});},isItemInExpandedSet:function(menuItem){if(typeof menuItem.parent==='undefined'){return true;}
if(this.menuOrderedTables[menuItem.parent].collapsed){return false;}
return this.isItemInExpandedSet(this.menuOrderedTables[menuItem.parent]);},showHideRows:function(){var pageObj=this,displayGroupControls=false,indentTables=false,$table=$(".rightsTable");jQuery.each(pageObj.tables,function(tableName,table){table.showOnModifiedMode=false;table.visible=pageObj.isTableDisplayed(tableName);});if(this.orderMethod!='menu'||this.tablesFilterState!='all'){jQuery.each(pageObj.tables,function(tableName,table){var shortTable=table[0];pageObj.toggleElement($("#row_"+shortTable),table.visible);table.showOnModifiedMode=table.visible;});jQuery.each(pageObj.menuOrderedTables,function(idx){if(this.table){return;}
pageObj.toggleElement(pageObj.getGroupRow(idx),false);});}else if(!this.SEARCHLIST.length){indentTables=true;jQuery.each(pageObj.menuOrderedTables,function(idx){if(this["items"]){displayGroupControls=true;}
pageObj.toggleElement(pageObj.getGroupRow(idx),pageObj.isItemInExpandedSet(this));});}else{this.updateAllHasVisibleItemsFlags();indentTables=true;jQuery.each(pageObj.menuOrderedTables,function(idx){var display=this.hasVisibleItems||this.table&&pageObj.tables[this.table].visible;pageObj.toggleElement(pageObj.getGroupRow(idx),display);});}
pageObj.updateColHeaderStates();$("#expandAll").toggle(displayGroupControls);$table.toggleClass("groupcontrols",displayGroupControls);$table.toggleClass("indenttables",indentTables);},initSearchBox:function(){var pageObj=this;$("#tableRightsSearch").on("input",function(){pageObj.SEARCHLIST=$(this).val().trim().toUpperCase().match(/[^\s]+/g)||[];pageObj.showHideRows();});},getBoxObj:function(perm,shortTable){return $("#box"+perm+shortTable);},updateModifiedState:function(perm,shortTable,_group){var group=_group||this.currentGroup,table=this.shortTables[shortTable],savedPerm=this.getTableSavedPermissions(table,group),modifiedMask=this.comparePermissions(perm,savedPerm);this.modifiedRights[group]=this.modifiedRights[group]||{};if(modifiedMask){this.modifiedRights[group][table]=perm;}else{delete this.modifiedRights[group][table];}
return modifiedMask;},readTablePermissionsFromGrid:function(shortTable){var pageObj=this,mask="";jQuery.each(this.masks,function(right,identifier){if(pageObj.getBoxObj(identifier,shortTable).attr("data-checked")==1){mask=mask+identifier;}});return mask;},getTableSavedPermissions:function(table,_group){var group=_group||this.currentGroup;return(this.savedRights[table]?this.savedRights[table][group]:"")||"";},getTableActivePermissions:function(table,_group){var group=_group||this.currentGroup,modRights=this.modifiedRights[group],modifiedMask;if(typeof modRights!="undefined"){modifiedMask=modRights[table];if(typeof modifiedMask!="undefined"){return modifiedMask;}}
return this.getTableSavedPermissions(table,group);},updateRowModifiedState:function(shortTable,modifiedMask){var $tableCell=$("#tblcell"+shortTable),tableModified=false;jQuery.each(this.masks,function(right,identifier){var $cell=$("#cell"+identifier+shortTable);$cell.toggleClass("rights-modified",modifiedMask.indexOf(identifier)>-1);tableModified=tableModified||modifiedMask.indexOf(identifier)>-1;});$tableCell.toggleClass("rights-modified",tableModified);},getTableNameFromBox:function(_boxId){var boxId=_boxId||"";return boxId.substring(4);},initModifiedFilter:function(){var pageObj=this,$control=$("#linkselectFilter");if(!this.isBootstrap()){(new Runner.linkSelectControl($control.get(0))).change(function(){pageObj.tablesFilterState=this.val();pageObj.showHideRows();});}else{$control.on("click","a",function(e){pageObj.tablesFilterState=$(this).parent().data('value');pageObj.showHideRows();$control.find('.btn').text($(this).text());});}},getTableModifiedMask:function(table,_group){return this.comparePermissions(this.getTableSavedPermissions(table,_group),this.getTableActivePermissions(table,_group));},comparePermissions:function(perm,savedPerm){var modifiedMask="";jQuery.each(this.masks,function(right,identifier){if((savedPerm.indexOf(identifier)>-1)!=(perm.indexOf(identifier)>-1)){modifiedMask=modifiedMask+identifier;}});return modifiedMask;},areGroupPermissionsModified:function(_group){var group=_group||this.currentGroup,modRights=this.modifiedRights[group];if(typeof modRights=='undefined'){return false;}
return!jQuery.isEmptyObject(modRights);},updateGroupModifiedState:function(_group){var group=_group||this.currentGroup,modified=this.areGroupPermissionsModified(group),$option=$('.group').find('[value='+group+']'),label;label=this.groups[group];$option.text(modified?label+' (*)':label);},updateGroupsModifiedStates:function(){var pageObj=this,isAnyModified=false;jQuery.each(this.groups,function(group,groupName){isAnyModified=isAnyModified||pageObj.areGroupPermissionsModified(group);pageObj.updateGroupModifiedState(group);});this.setPageModified(isAnyModified);Runner.toggleDisabledClass($('#resetBtn'),!isAnyModified);Runner.toggleDisabledClass($('#saveBtn'),!isAnyModified);},updateRowHeaderState:function(table){var $checkbox=$('#rowbox'+this.tables[table][0]),tableRights=this.getTableActivePermissions(table),pageMask=this.pageMasks[table],diff=this.comparePermissions(pageMask,tableRights);if(tableRights&&!diff){$checkbox.attr("data-checked","1");}else if(!tableRights&&pageMask){$checkbox.attr("data-checked","0");}else if(tableRights&&diff){$checkbox.attr("data-checked","2");}else{$checkbox.attr("data-checked","-1");}},updateRowHeaderStates:function(){var pageObj=this;jQuery.each(this.tables,function(table){pageObj.updateRowHeaderState(table);});},isTableDisplayed:function(table){var CAPTION,TABLE,i,show=true;if(this.SEARCHLIST.length!=0){show=false;CAPTION=this.tables[table][1].toUpperCase();TABLE=table.toUpperCase();for(i=this.SEARCHLIST.length-1;!show&&i>=0;--i){show=this.SEARCHLIST[i]&&(TABLE.indexOf(this.SEARCHLIST[i])>=0||CAPTION.indexOf(this.SEARCHLIST[i])>=0);}}
return show&&(this.tablesFilterState=='all'||this.getTableModifiedMask(table)!=""||(this.tablesFilterState=='modified'&&this.tables[table].showOnModifiedMode));},updateColHeaderStates:function(){var pageObj=this,colBoxStates={A:-1,D:-1,E:-1,S:-1,P:-1,I:-1,M:-1};jQuery.each(this.tables,function(table){var tableRights,pageMask,finish=true;if(!pageObj.isTableDisplayed(table)){return;}
tableRights=pageObj.getTableActivePermissions(table),pageMask=pageObj.pageMasks[table];jQuery.each(colBoxStates,function(perm,state){if(state==2){return;}
finish=false;if(pageMask.indexOf(perm)==-1){return;}
if(tableRights.indexOf(perm)==-1){if(state==-1){colBoxStates[perm]=0;}else if(state==1){colBoxStates[perm]=2;}}else{if(state==-1){colBoxStates[perm]=1;}else if(state==0){colBoxStates[perm]=2;}}});if(finish){return false;}});jQuery.each(colBoxStates,function(perm,state){$("#colbox"+perm).attr("data-checked",state);});},orderTablesAlphabetically:function(){var $row=$(".rightsTable").find("tr.rnr-row:first"),idx=0,table,$insertRow,rowid;while($row.length){if(idx>=this.alphaOrderedTables.length){break;}else{table=this.alphaOrderedTables[idx];rowid="row_"+this.tables[table][0];if($row.get(0).id!=rowid){$insertRow=$("#"+rowid);$insertRow.insertBefore($row);$row=$insertRow;}}
++idx;$row=$row.next();}
this.showHideRows();},orderTablesAsMenu:function(){var $row=$(".rightsTable").find("tr.rnr-row:first"),idx=0,table,title,id,$insertRow,rowid;while($row.length&&idx<this.menuOrderedTables.length){if(idx>=this.menuOrderedTables.length){break;}
table=this.menuOrderedTables[idx].table;if(table){rowid="row_"+this.tables[table][0];}else{rowid="grouprow_"+idx;}
if($row.get(0).id!=rowid){$insertRow=$("#"+rowid);$insertRow.insertBefore($row);$row=$insertRow;}
++idx;$row=$row.next();}
this.showHideRows();},initOrderControl:function(){var pageObj=this,$control=$("#linkselectOrder");if(!this.isBootstrap()){(new Runner.linkSelectControl($control.get(0))).change(function(){pageObj.orderMethod=this.val();if(pageObj.orderMethod=='menu'){pageObj.orderTablesAsMenu();}else{pageObj.orderTablesAlphabetically();}});}else{$control.on("click","a",function(e){if($(this).parent().data("value")=='menu'){pageObj.orderTablesAsMenu();}else{pageObj.orderTablesAlphabetically();}
$control.find('.btn').text($(this).text());});}},initExpandAll:function(){var pageObj=this;$("#expandAll").on('click',function(e){jQuery.each(pageObj.menuOrderedTables,function(groupId){if(!this.items){return;}
pageObj.expandGroup(groupId,!pageObj.allExpanded);});pageObj.allExpanded=!pageObj.allExpanded;$(this).text(pageObj.allExpanded?Runner.lang.constants.TEXT_COLLAPSE_ALL:Runner.lang.constants.TEXT_EXPAND_ALL);});},getGroupRow:function(groupId){var table=this.menuOrderedTables[groupId].table;return table?$("#row_"+this.tables[table][0]):$("#grouprow_"+groupId);},expandGroup:function(groupId,toExpand){var pageObj=this,$tr=this.getGroupRow(groupId),menuItem=pageObj.menuOrderedTables[groupId];menuItem.collapsed=!toExpand;if(this.isBootstrap()){$tr.find("[data-group-expander]").toggleClass("glyphicon-triangle-right",!toExpand).toggleClass("glyphicon-triangle-bottom",toExpand);}else{$tr.find(".rnr-expandCollapse").attr("data-state",toExpand?"open":"closed");}
this.showHideRows();},initExpandCollapseControls:function(){var pageObj=this,selector=this.isBootstrap()?"tr:has([data-group-expander])":"tr:has(.rnr-expandCollapse)";$(".rightsTable").on("click",selector,function(e){var $target=$(e.target);$tr=$target.closest("tr"),groupId=$tr.data("groupid")||0,toExpand=(pageObj.menuOrderedTables[groupId].collapsed==true);pageObj.expandGroup(groupId,toExpand);});},copyGroupPermissions:function(from){var pageObj=this;jQuery.each(this.tables,function(table){var shortTable=this[0],rights=pageObj.getTableActivePermissions(table,from),modifiedMask=pageObj.updateModifiedState(rights,shortTable);});this.updateGroupsModifiedStates();$('.group').change();},initCopyPermissions:function(){var pageObj=this,bsUsed=Runner.isBootstrap(),args={modal:true,centered:true,headerContent:Runner.lang.constants.AA_COPY_PERMISS_FROM,bodyContent:'<div id=groupCopySelector></div>'},afterCreateDialog=function(win){var $list=$("#groupCopySelector",win.getContextNode()),activeGroupId=bsUsed?$("ul.nav-tabs").find("li.active").find("a").attr("value"):$('.group option:selected').val();$.each(pageObj.groups,function(groupId,groupName){if(activeGroupId==groupId){return;}
var groupLink=$('<a class="groupCopyLink" href=#></a>').text(groupName).data('groupid',groupId);if(groupId<0){groupLink.prependTo($list);}else{groupLink.appendTo($list);}});$list.on('click','a',function(e){pageObj.copyGroupPermissions($(e.target).data('groupid'));win.destroy();if(bsUsed){$("ul.nav-tabs").find("li.active").find("a").click();}
return false;});if(!bsUsed){Runner.pages.PageManager.correctYUIWindowSize(win._obj,true);}};$('#copyPermissions').on('click',function(e){if(Runner.isDisabledButton(this)){return false;}
if(bsUsed){Runner.pages.PageManager.createBSWin(args,false,afterCreateDialog);}else{Runner.pages.PageManager.createFlyWin(args,false,afterCreateDialog);}
return false;});},toggleElement:function($elem,show){if(!show){$elem.hide();}else{$elem.css('display','');}}});Runner.linkSelectControl=(function(){var _constructor=function(element){var _self=this,dispValue;if(!(this instanceof _constructor)){return new _constructor(element);}
this.$elem=$(element);this.$displayElem=this.$elem.find('.rnr-linkselect-display');this.$list=this.$elem.find('.rnr-linkselect-list');this.value="";dispValue=this.$displayElem.text();this.$options=this.$elem.find('.rnr-linkselect-item');this.$options.each(function(){if(dispValue==$(this).text()){$(this).attr("data-selected","true");_self.value=$(this).data("value");return false;}});this.$elem.click(".rnr-linkselect-item",function(e){return _constructor.prototype.clickHandler.call(_self,e.target);});this.$elem.mouseover(function(){_self.$list.css('display','');});return this;};_constructor.prototype.change=function(handler){var _self=this;this.$elem.change(function(){handler.apply(_self,arguments);});};_constructor.prototype.val=function(){return this.value;};_constructor.prototype.clickHandler=function(item){var $item=$(item);if(typeof $item.attr('data-selected')!='undefined'){return;}
this.$options.removeAttr('data-selected');$item.attr('data-selected','true');this.value=$item.data('value');this.$displayElem.text($item.text());this.$elem.change();this.$list.hide();};return _constructor;}());Runner.pages.MembersPageAD=Runner.extend(Runner.pages.ListPageCommon,{pageType:Runner.pages.constants.PAGE_ADMIN_MEMBERS,rows:null,constructor:function(cfg){Runner.pages.MembersPageAD.superclass.constructor.call(this,cfg);this.baseParams.id=this.pageId;if(this.isBootstrap()){this.bricksForReload=["ugadmemgrid","message","pagination"];}
else{this.bricksForReload=["grid","message","pagination"];}
this.rows=this.controlsMap.gridRows;},destructor:function(){Runner.pages.MembersPageAD.superclass.destructor.call(this);this.pageCont=null;$('.group').prop('disabled',false);this.parObj.disableGroupButtons(false);},init:function(){Runner.pages.ListPageFly.superclass.init.call(this);this.initButtons();this.initRows();},initAddGrLink:function(row){var pageObj=this;row.addGrLink=$('#iAddLink'+row.id).bind("click",function(e){pageObj.addToGroup(row);return false;});},getSelections:function(){var selBoxesArr=[];$('input[type=checkbox][id^=check][name^=selection]:checked').each(function(){selBoxesArr.push($(this));});return selBoxesArr;},initCheckBoxGr:function(row){var pageObj=this;row.checkBoxGr=$('#check'+this.id+'_'+row.id).bind("click",function(e){var selBoxesArr=pageObj.getSelections(),$addSelBtn=$('#addSelBtn');if(selBoxesArr.length&&Runner.isDisabledButton($addSelBtn)){Runner.delDisabledClass($addSelBtn);}else if(!selBoxesArr.length&&!Runner.isDisabledButton($addSelBtn)){Runner.addDisabledClass($addSelBtn);}});},initHeaderCheckBox:function(){var pageObj=this;$('.chooseAll'+pageObj.id).unbind("click").bind("click",function(e){$('input[type=checkbox][id^=check'+pageObj.id+'_]').prop('checked',this.checked);$('input[type=checkbox][id^=chooseAll_'+pageObj.id+']').prop('checked',this.checked);var selBoxesArr=pageObj.getSelections(),$addSelBtn=$('#addSelBtn');if(selBoxesArr.length&&Runner.isDisabledButton($addSelBtn)){Runner.delDisabledClass($addSelBtn);}else if(!selBoxesArr.length&&!Runner.isDisabledButton($addSelBtn)){Runner.addDisabledClass($addSelBtn);}});},initRow:function(row){this.initAddGrLink(row);this.initCheckBoxGr(row);},initRows:function(){for(var i=0;i<this.rows.length;i++){this.initRow(this.rows[i]);}},getRowById:function(rowId){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id===rowId){return this.rows[i];}}
return false;},initButtons:function(){var pageObj=this,$addSelBtn=$('#addSelBtn').unbind('click').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.addSelectedToGroup();}
return false;});Runner.addDisabledClass($addSelBtn);},initResize:Runner.emptyFn,initSearch:function(){this.searchController=new Runner.search.SearchController({id:this.pageId,tName:this.tName,fNamesArr:this.controlsMap.search.allSearchFields,shortTName:this.shortTName,usedSrch:this.controlsMap.search.usedSrch,panelSearchFields:this.controlsMap.search.panelSearchFields,ajaxSubmit:true,useSuggest:false,pageType:this.pageType});this.searchController.init(this.controlsMap.search.searchBlocks);this.searchController.srchForm.baseParams=this.baseParams;this.searchController.srchForm.on("beforeSubmit",function(form){this.preparePageForReloading(this.win?this.win.bodyNode.getDOMNode():null);},this);this.searchController.on('afterSearch',function(respObj,srchController,srchForm){Runner.stopLoading(this.win?this.win.bodyNode.getDOMNode():null);this.pageReloadHn(respObj);this.searchController.toggleShowAll(this.searchController.usedSrch)},this);this.searchController.srchForm.on('submitFailed',function(){Runner.stopLoading(this.win?this.win.bodyNode.getDOMNode():null);},this);},initInline:Runner.emptyFn,initPagination:function(){var pageObj=this;$.each(this.getBrickObjs('pagination'),function(index,brick){brick.elem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),url;if(!$target.is("a")){return;}
if(!Runner.isMobile){pageObj.preparePageForReloading();}
url=Runner.pages.getUrl(pageObj.tName,pageObj.pageType,{})+"?goto="+$target.attr("pageNum");Runner.runnerAJAX(url,pageObj.baseParams,function(respObj){pageObj.pageReloadHn(respObj)});});});},pageReloadHn:function(respObj){Runner.stopLoading(this.gridElem);if(respObj.success){Runner.setIdCounter(respObj.idStartFrom);this.replaceBricksHTMLWith(this.getBricksHtml(respObj.html));this.controlsMap=respObj.controlsMap[this.tName][this.pageType][this.pageId];this.rows=this.controlsMap.gridRows;this.initButtons();this.initRows();this.initHeaderCheckBox();this.searchController.usedSrch=this.controlsMap.search.usedSrch;this.searchController.toggleShowAll(this.searchController.usedSrch);}else{this.win.set('bodyContent',"REQUEST FAILED");}},addSelectedToGroup:function(){var row,i,pageObj=this,selBoxesArr=this.getSelections();for(i=0;i<selBoxesArr.length;i++){row=pageObj.getRowById(parseInt(selBoxesArr[i].val(),10));if(row){pageObj.addToGroup(row);}}
pageObj.destructor();this.parObj.disableGroupButtons(false);},addToGroup:function(obj){var elemVal=obj.keys['name'],pageObj=this;if(elemVal==''){return;}
for(var groupId in pageObj.parObj.groups){if(pageObj.parObj.groups[groupId]==elemVal){pageObj.replaceBrickContentHTMLWith('message','Group with such name is allready exist!');pageObj.showBrick('message');return;}}
Runner.runnerAJAX(Runner.getPageUrl('admin_admembers','list'),{name:elemVal,a:'addgr'},function(ret){var id=ret.id,groupCount=0;if(!ret.success){pageObj.replaceBrickContentHTMLWith('message','Error adding group!');pageObj.showBrick('message');return;}
pageObj.parObj.groups[id]=elemVal;pageObj.hideBrick('message');if(!pageObj.isBootstrap()){$('<option value="'+id+'">'+elemVal+'</option>').appendTo($('.group')).prop('selected',true);}else{$("li.active").removeClass();$('<li class="active" role="presentation"><a href="#" value="'+id+'">'+elemVal+'</a></li>').insertAfter($('.nav-tabs').find('li:last'));$("li.active").find("a").click();}
jQuery.each(pageObj.parObj.groups,function(){++groupCount;});$('.group').attr('size',groupCount);$('.group').trigger('change');$('.groupname').val('');$('input[type=checkbox][id^=check][name^=selection][value='+obj.id+']').hide();obj.addGrLink.hide();});}});Runner.pages.RightsPageAD=Runner.extend(Runner.pages.RightsPage,{initRightsControls:function(){var pageObj=this;$('#addGroupBtn').click(function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disableGroupButtons(true);$('.group').prop('disabled',true);pageObj.renameidx=-1;var pageParams={tName:"admin_admembers",pageType:Runner.pages.constants.PAGE_LIST,pageMode:Runner.pages.constants.MEMBERS_PAGE,parObj:pageObj,modal:true,baseParams:{table:"admin_admembers"}};Runner.pages.PageManager.openPage(pageParams);return false;});$('#delGroupBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.deletegroup();}
return false;});},});Runner.pages.ExportPage=Runner.extend(Runner.pages.RunnerPage,{selection:null,constructor:function(cfg){Runner.pages.ExportPage.superclass.constructor.call(this,cfg);this.submitUrl=Runner.pages.getUrl(this.tName,this.pageType);this.selection=this.baseParams?this.baseParams["selection[]"]:Runner.pages.PageSettings.getTableData(this.tName,"selection");},init:function(){Runner.pages.ExportPage.superclass.init.call(this);this.initButtons();this.initExportControls();this.fireEvent('afterInit',this,this.proxy,this.id);},initExportControls:function(){var settings=JSON.parse(localStorage.getItem("export_"+this.tName)),$csvDelimiter=$("#csv_delimiter"+this.id),$exportFieldsCtrl=$("#exportFields"+this.id),$buttonSave=$("[id=saveButton"+this.id+"]"),pageObj=this,chosenCtrl,saveExportFieldsStateOnCtrlChange,delimiter;$('input[type=radio][name=type]',this.pageCont).on("change",function(e){var disabled=$(this).val()!=="csv";$csvDelimiter.prop("disabled",disabled).toggleClass("greyed-input",disabled);});if(settings){delimiter=settings.delimiter;$('input[type=radio][name=type][value="'+settings.exportType+'"]',this.pageCont).prop("checked",true).trigger("change");$('input[type=radio][name=records][value="'+settings.records+'"]',this.pageCont).prop("checked",true);$('input[type=radio][name="txtformatting"][value="'+settings.txtFormatting+'"]',this.pageCont).prop("checked",true);}else{delimiter=Runner.pages.PageSettings.getTableData(this.tName,"csvDelimiter");}
$csvDelimiter.val(delimiter);if($exportFieldsCtrl.length){$exportFieldsCtrl.chosen();chosenCtrl=$exportFieldsCtrl.data("chosen");saveExportFieldsStateOnCtrlChange=function(settings){settings=settings||{};settings.exportFields=chosenCtrl.getOrderedMultipleValue();localStorage.setItem("export_"+pageObj.tName,JSON.stringify(settings));};$exportFieldsCtrl.on("change",function(e){var fields=$(this).val()||[];Runner.toggleDisabledClass($buttonSave,!fields.length);if(fields.length){saveExportFieldsStateOnCtrlChange(settings);}});$(chosenCtrl.search_choices).sortable({item:".search-choice",stop:function(event,ui){$(".search-field",this).appendTo(this);saveExportFieldsStateOnCtrlChange(settings);}});if(settings&&settings.exportFields){chosenCtrl.setOrderedMultipleValue(settings.exportFields);}
Runner.toggleDisabledClass($buttonSave,!($exportFieldsCtrl.val()||[]).length);}},initButtons:function(){var pageObj=this,$exportFieldsCtrl=$("#exportFields"+this.id);$("[id=saveButton"+this.id+"]").on("click",function(e){var settings={exportType:$('input[type=radio][name=type]:checked',pageObj.pageCont).val(),records:$('input[type=radio][name=records]:checked',pageObj.pageCont).val(),txtFormatting:$("[name='txtformatting']:checked",pageObj.pageCont).val(),delimiter:$("#csv_delimiter"+pageObj.id).val(),exportFields:$exportFieldsCtrl.data("chosen")&&$exportFieldsCtrl.data("chosen").getOrderedMultipleValue()}
pageObj.form=new Runner.form.BasicForm({submitUrl:pageObj.submitUrl,standardSubmit:true,method:'POST',id:pageObj.pageId,baseParams:{type:settings.exportType,records:settings.records,txtformatting:settings.txtFormatting,delimiter:settings.delimiter,"exportFields[]":settings.exportFields,"selection[]":pageObj.selection}});pageObj.form.submit();pageObj.form.destructor();pageObj.form=null;localStorage.setItem("export_"+pageObj.tName,JSON.stringify(settings));return false;});$("[id=cancelButton"+this.id+"]").on("click",function(e){pageObj.close();return false;});},getOpenPageParams:function(selection){return{tName:this.tName,pageType:Runner.pages.constants.PAGE_EXPORT,modal:true,requestUrl:Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_EXPORT),baseParams:{a:"export","selection[]":selection}};}});Runner.pages.ImportPage=Runner.extend(Runner.pages.RunnerPage,{pageType:Runner.pages.constants.PAGE_IMPORT,submitUrl:"",fileImport:true,CSVPreview:false,importFieldsLabels:{},columnsListData:null,previewControls:null,$fileUploadButton:null,$textInsertButton:null,$backButton:null,$importButton:null,$continueTextImport:null,fileUploaderSupported:false,$hiddenFileInput:null,$dropZone:null,modeConstants:{DATA_CHOOSING:0,PREVIEW:1,RESULTS:2},importPageMode:0,settingsHash:"",excelDateFields:{},constructor:function(cfg){this.previewControls={};Runner.pages.ImportPage.superclass.constructor.call(this,cfg);this.importPageMode=this.modeConstants.DATA_CHOOSING;this.importFieldsLabels=Runner.pages.PageSettings.getTableData(this.tName,"importFieldsLables");this.submitUrl=Runner.pages.getUrl(this.tName,this.pageType);this.fileUploaderSupported=this.isAutoFileUploadSupported();},init:function(){Runner.pages.ImportPage.superclass.init.call(this);this.initFileUploader();this.initButtons();this.fireEvent('afterInit',this,this.proxy,this.id);},isAutoFileUploadSupported:function(){var div=document.createElement('div'),dndSupport='draggable'in div||('ondragstart'in div&&'ondrop'in div),xhr2Support='XMLHttpRequest'in window&&'withCredentials'in new XMLHttpRequest();return!!window.File&&!!window.FileList&&!!window.FormData&&xhr2Support&&dndSupport;},initButtons:function(){var pageObj=this;this.$fileUploadButton=$("[id='uploadImportFile"+this.id+"']").on("click",function(e){if(pageObj.fileUploaderSupported){pageObj.$hiddenFileInput.trigger('click');}else{pageObj.showImportPreview();}
return false;});this.$textInsertButton=$("[id='switchToTextInsertion"+this.id+"']").on("click",function(e){pageObj.switchToTextInput();return false;});this.$backButton=$("[id='backTo"+this.id+"']").on("click",function(e){pageObj.backToDataChoosing();return false;});this.$continueTextImport=$("[id='continueTextImport"+this.id+"']").on("click",function(e){if(!Runner.isDisabledButton(this)){$(this).hide();pageObj.showImportPreview();}
return false;});this.$importButton=$("[id='importButton"+this.id+"']").on("click",function(e){if(!Runner.isDisabledButton(this)){$(this).hide();pageObj.$backButton.hide();pageObj.importData();}
return false;});$("[id='backToList"+this.id+"']").on("click",function(e){window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_LIST)+"?a=return";return false;});},backToDataChoosing:function(){if(this.importPageMode===this.modeConstants.DATA_CHOOSING&&!this.fileImport){this.switchToFileChoosing();}else if(this.importPageMode===this.modeConstants.PREVIEW){this.hideBrick("import_preview");this.$importButton.hide();if(!this.fileImport){this.switchToTextInput();}else{this.switchToFileChoosing();}}
this.importPageMode=this.modeConstants.DATA_CHOOSING;},switchToFileChoosing:function(){this.fileImport=true;this.showBrick("importheader_text");this.showBrick("importfields");this.hideBrick("import_rawtext_control");this.toggleDropZone(false);this.$continueTextImport.hide();this.$backButton.hide();},switchToTextInput:function(){this.fileImport=false;this.hideBrick("importheader_text");this.hideBrick("importfields");this.showBrick("import_rawtext_control");this.$continueTextImport.show();this.$backButton.show();this.initTextArea();},initTextArea:function(){if(this.fileImport){return;}
var $continueButton=this.$continueTextImport,$textArea;$textArea=$("#importText"+this.id).on("keyup",function(e){if(Runner.isAcceptableKeyCode(e)){Runner.toggleDisabledClass($continueButton,$textArea.val().trim()==="");}}).on("change",function(e){Runner.toggleDisabledClass($continueButton,$textArea.val().trim()==="");}).bind('paste',function(e){Runner.toggleDisabledClass($continueButton,false);}).val("");this.initTextArea=function(){if(!this.fileImport){Runner.toggleDisabledClass($continueButton,$textArea.val().trim()==="");$textArea.focus();}};this.initTextArea();},initFileUploader:function(){if(!this.fileUploaderSupported){$("#importUploadFallback"+this.id).show();return;}
this.initDropZone();this.initHiddenFileInput();},initDropZone:function(){var pageObj=this;this.$dropZone=$("#importDropzone"+this.id,this.pageCont).on('drop',function(e){if(!pageObj.fileImport||pageObj.importPageMode!==pageObj.modeConstants.DATA_CHOOSING){return false;}
var dataTransfer=e.originalEvent.dataTransfer,files=dataTransfer.files;pageObj.showImportPreview(files);pageObj.$dropZone.hide();return false;}).on('click',function(e){if(pageObj.fileImport&&pageObj.importPageMode===pageObj.modeConstants.DATA_CHOOSING){pageObj.$hiddenFileInput.trigger('click');}
return false;});$(this.pageCont).on('dragenter',function(e){if(pageObj.fileImport&&pageObj.importPageMode===pageObj.modeConstants.DATA_CHOOSING){pageObj.toggleDropZone(true);}
return false;}).on('dragover',function(e){return false;}).on('drop',function(e){setTimeout(function(){if(pageObj.fileImport&&pageObj.importPageMode===pageObj.modeConstants.DATA_CHOOSING){pageObj.toggleDropZone(false);}},400);return false;});},toggleDropZone:function(toggler){if(!this.fileUploaderSupported){return;}
this.$dropZone.toggle(toggler);this.$fileUploadButton.toggle(!toggler);this.$textInsertButton.toggle(!toggler);this.toggleBrick("importheader_text",!toggler);},initHiddenFileInput:function(){var pageObj=this;if(this.$hiddenFileInput&&this.$hiddenFileInput.length){this.$hiddenFileInput.remove();}
this.$hiddenFileInput=$('<input type="file" id="hiddenImpotFile'+this.id+'"></input>').css('visibility','hidden').appendTo(this.pageCont).on('change',function(e){pageObj.showImportPreview(this.files);pageObj.initHiddenFileInput();});},showImportPreview:function(files){if(this.fileImport&&this.fileUploaderSupported){this.showImportPreviewUsingXHR(files);return;}
this.showImportPreviewUsingIframe();},showImportPreviewUsingXHR:function(files){if(!this.fileUploaderSupported||!files||!files.length){return;}
var formData=new FormData(),pageObj=this;formData.append("useXHR",true);formData.append("id",this.pageId);formData.append("a","importPreview");formData.append("importType","file");formData.append("importFile"+this.id,files[0]);$.ajax({url:this.submitUrl+"?"+"rndVal="+Math.random(),data:formData,type:"POST",dataType:"json",processData:false,contentType:false,success:function(respObj){pageObj.processPreviewData(respObj);},error:function(respObj){pageObj.switchToFileChoosing();pageObj.displayGenericAjaxError(respObj.responseText);}});},showImportPreviewUsingIframe:function(){var pageObj=this,importFormParams={baseParams:{id:this.pageId,a:"importPreview",importType:this.fileImport?"file":"text"}};if(this.fileImport){importFormParams.addElems=[$("#importFile"+this.id)];}else{importFormParams.baseParams["importText"]=$("#importText"+this.id).val();}
Runner.submitRunnerFormInIframe(this.submitUrl,importFormParams,function(respObj,formObj,fieldControls){pageObj.processPreviewData(respObj);},function(rawText){pageObj.switchToFileChoosing();pageObj.displayGenericAjaxError(rawText);});},readExcelDateFieldsFromPreviewData:function(previewData){var i;this.excelDateFields={};for(i=0;i<previewData.fieldsData.length;++i){if(previewData.fieldsData[i].dateTimeType&&previewData.fieldsData[i].requireFormatting){this.excelDateFields[previewData.fieldsData[i].fName]=true;}}},processPreviewData:function(respObj){var previewData=respObj.previewData;if(!previewData||Runner.isArray(previewData)&&!previewData.length){return;}
this.$importButton.show();this.$backButton.show();this.importPageMode=this.modeConstants.PREVIEW;this.showBrick("import_preview");this.hideBrick("import_rawtext_control");this.hideBrick("importheader_text");this.hideBrick("importfields");this.generateSettingsHash(previewData);this.readExcelDateFieldsFromPreviewData(previewData);this.adjustPreviewSettings(previewData);this.initPreviewSettingsControls(previewData);this.showPreviewData(previewData);},generateSettingsHash:function(previewData){var firstLineData=previewData.CSVPreview?this.getCSVTableData([previewData.CSVlinesData[0]],previewData.delimiter):previewData.tableData[0],fieldsData=previewData.fieldsData||[],hashObj={cols:firstLineData.length};if(!fieldsData.length){hashObj["names"]=firstLineData;}
hashObj["table"]=this.tName;this.settingsHash=Runner.md5(JSON.stringify(hashObj));},adjustPreviewSettings:function(previewData){var settingsString=localStorage.getItem("import_"+this.settingsHash),storedSettings;if(settingsString){storedSettings=JSON.parse(settingsString);previewData.fieldsData=storedSettings.importFieldsData;previewData.useHeadersLine=storedSettings.useHeadersLine;if(storedSettings.dateFormat!==""){previewData.dateFormat=storedSettings.dateFormat;}
if(previewData.CSVPreview){previewData.delimiter=storedSettings.delimiter;}}},initPreviewSettingsControls:function(previewData){$("#dateFormatSettings"+this.id).toggle(!!previewData.dateFormat);this.previewControls["dateFormat"]=!previewData.dateFormat?null:$("#importDateFormat"+this.id).val(previewData.dateFormat);this.initHeaderInFirstLineControl(previewData.useHeadersLine);this.CSVPreview=previewData.CSVPreview;this.initCSVPreviewSettingsControls(previewData);},initHeaderInFirstLineControl:function(useHeadersLine){var pageObj=this,checked=useHeadersLine===undefined?true:!useHeadersLine;this.previewControls["headersLineIsNotUsed"]=$("#columnsInFirstLine"+this.id).prop("checked",checked).on("change",function(e){var toggler=$(this).prop("checked"),$headersTableRow=$("tr:first","#importPreviewBodyTable"+pageObj.id);$headersTableRow.toggleClass("rnr-import-disabled",toggler);pageObj.adjustImportPreviewButtons();});this.initHeaderInFirstLineControl=Runner.emptyFn;},refreshPreviewData:function(radioEl,previewData){var updatedPreviewData=$.extend({},previewData),radioValue=$(radioEl).val();updatedPreviewData.delimiter=radioValue!=="other"?radioValue:this.previewControls["customDelimiter"].val();updatedPreviewData.fieldsData=this.columnsListData;if(updatedPreviewData.delimiter){this.showPreviewData(updatedPreviewData);}},initCSVPreviewSettingsControls:function(previewData){$("#delimiterSettings"+this.id).toggle(!!this.CSVPreview);if(!this.CSVPreview){return;}
var pageObj=this,delimiter=previewData.delimiter||",",$matchedRadio=$(".importDelimiters",this.pageCont).filter(function(){return this.value===delimiter;}).prop("checked",true);this.previewControls["customDelimiter"]=$("#customDelimiter"+this.id);this.previewControls["delimiters"]=$(".importDelimiters",this.pageCont).unbind("change").on("change",function(e){pageObj.refreshPreviewData(this,previewData);});$("#customDelimiter"+this.id,this.pageCont).unbind("input").on("input",function(e){if($(".importDelimiters[value='other']",this.pageCont).prop("checked")){pageObj.refreshPreviewData(this,previewData);}});if(!$matchedRadio.length){$(".importDelimiters[value='other']",this.pageCont).prop("checked",true);this.previewControls["customDelimiter"].val(delimiter);}},showPreviewData:function(previewData){if(!previewData.tableData&&!previewData.CSVlinesData){return;}
var tableData=previewData.CSVPreview?this.getCSVTableData(previewData.CSVlinesData,previewData.delimiter):previewData.tableData,fieldsData=previewData.fieldsData||[],dateFormat=previewData.dateFormat;this.setPreviewTableMarkup(tableData,fieldsData,dateFormat);this.initPreviewTableControls();if($.isEmptyObject(this.columnsListData)){this.previewControls["headersLineIsNotUsed"].prop("checked",false);var $headersTableRow=$("tr:first","#importPreviewBodyTable"+this.id);$headersTableRow.toggleClass("rnr-import-disabled",false);}
this.adjustImportPreviewButtons(tableData.length);$("#importErrorMessage"+this.id).html("").hide();},adjustImportPreviewButtons:function(numberOfRows){if(numberOfRows===undefined){numberOfRows=$("tr","#importPreviewBodyTable"+this.id).length;}
Runner.toggleDisabledClass(this.$importButton,!numberOfRows||numberOfRows===1&&this.previewControls["headersLineIsNotUsed"].is(":checked")||$.isEmptyObject(this.columnsListData));},setPreviewTableMarkup:function(tableData,fieldsData,dateFormat){if(this.isBootstrap()){return this.setPreviewTableMarkupBootstrap(tableData,fieldsData,dateFormat);}
var pageObj=this,styleString='',$table=$('#importPreviewBodyTable'+this.id),$importGridHead=$("#importGridHead"+this.id),$tableHead=$('<thead></thead>'),$tableBody=$('<tbody></tbody>'),headersLineIsNotUsed=this.previewControls["headersLineIsNotUsed"].is(":checked"),dataLength=headersLineIsNotUsed&&tableData[1]?tableData[1].length:tableData[0].length,i,j,$tr,rowData,cellValue,headerName,headersColumn,$headTable,$style;for(i=0;i<dataLength;i++){$('<th class="prvcell import-column-'+i+'"></th>').html(this.getImportFieldsSelectMarkup(i,fieldsData[i]?fieldsData[i].fName:'')).appendTo($tableHead);}
for(i=0;i<tableData.length;i++){$tr=$('<tr></tr>');rowData=tableData[i];headersColumn=i===0&&headersLineIsNotUsed;if(headersColumn){$tr.addClass("rnr-import-disabled");}
for(j=0;j<dataLength;j++){cellValue=rowData[j];if(!headersColumn&&cellValue&&fieldsData[j]&&this.excelDateFields[fieldsData[j].fName]){cellValue=this.getDateFormattedValue(cellValue,dateFormat);}
$('<td class="prvcell import-column-'+j+'"></td>').text(cellValue).appendTo($tr);}
$tr.appendTo($tableBody);}
$table.children().remove();$table.append($tableHead).append($tableBody);$tableHead.children().each(function(i,th){var $th=$(th),width=$th.width(),thWidth=width+'px',tdWidth=(width-8)+'px';$th.css({'width':thWidth,'min-width':thWidth,'max-width':thWidth});styleString+='#importPreviewBodyTable'+pageObj.id+' > * > * > td:nth-child('+(i+1)+') '
+'{ width:'+tdWidth+'; min-width:'+tdWidth+'; max-width:'+tdWidth+'; }';});$style=$('#previewTableStyle'+pageObj.id);if(!$style.length){$style=$("<style id=previewTableStyle"+pageObj.id+"></style>").appendTo(document.head);}
$style.html(styleString);$headTable=$(Runner.domShallowCopy($table.get(0)));$importGridHead.empty().height($tableHead.height()).append($headTable);$headTable.attr("id","importPreviewHeadTable"+this.id).css("position","absolute").append($tableHead);$headTable.offset({left:$table.offset().left});$table.parent().scroll(function(e){$headTable.offset({left:$table.offset().left});});},setPreviewTableMarkupBootstrap:function(tableData,fieldsData,dateFormat){var pageObj=this,styleString='',$table=$('#importPreviewBodyTable'+this.id),$importGridHead=$("#importGridHead"+this.id),$tableHead=$('<thead></thead>'),$tableBody=$('<tbody></tbody>'),headersLineIsNotUsed=this.previewControls["headersLineIsNotUsed"].is(":checked"),dataLength=headersLineIsNotUsed&&tableData[1]?tableData[1].length:tableData[0].length,i,j,$tr,rowData,cellValue,headerName,headersColumn,$headTable,$style;for(i=0;i<dataLength;i++){$('<th class="prvcell import-column-'+i+'"></th>').html(this.getImportFieldsSelectMarkup(i,fieldsData[i]?fieldsData[i].fName:'')).appendTo($tableHead);}
for(i=0;i<tableData.length;i++){$tr=$('<tr></tr>');rowData=tableData[i];headersColumn=i===0&&headersLineIsNotUsed;if(headersColumn){$tr.addClass("rnr-import-disabled");}
for(j=0;j<dataLength;j++){cellValue=rowData[j];if(!headersColumn&&cellValue&&fieldsData[j]&&this.excelDateFields[fieldsData[j].fName]){cellValue=this.getDateFormattedValue(cellValue,dateFormat);}
$('<td class="prvcell import-column-'+j+'"></td>').text(cellValue).appendTo($tr);}
$tr.appendTo($tableBody);}
$table.children().remove();$table.append($tableHead).append($tableBody);$tableHead.children().each(function(i,th){var $th=$(th),width=$th.width(),thWidth=width+'px',tdWidth=(width)+'px';$th.css({'width':thWidth,'min-width':thWidth,'max-width':thWidth});styleString+='#importPreviewBodyTable'+pageObj.id+' > * > * > td:nth-child('+(i+1)+') '
+'{ width:'+tdWidth+'; min-width:'+tdWidth+'; max-width:'+tdWidth+'; }';});$style=$('#previewTableStyle'+pageObj.id);if(!$style.length){$style=$("<style id=previewTableStyle"+pageObj.id+"></style>").appendTo(document.head);}
$style.html(styleString);$(".importColumnSelector").addClass("form-control");$table.addClass("table table-condensed table-bordered");$headTable=$(Runner.domShallowCopy($table.get(0)));$importGridHead.empty().height($tableHead.height()).append($headTable);$headTable.attr("id","importPreviewHeadTable"+this.id).css("position","absolute").append($tableHead);$headTable.offset({left:$table.offset().left});$table.parent().scroll(function(e){$headTable.offset({left:$table.offset().left});});},initPreviewTableControls:function(){var pageObj=this,$previewTable=$('#importPreviewBodyTable'+this.id),$importcolumnsSelectors=$(".importColumnSelector",this.pageCont);this.columnsListData={};$importcolumnsSelectors.on("change",function(e){var $select=$(this),currValue=$select.val(),idx=$select.data("idx");$(".import-column-"+idx,$previewTable).toggleClass("rnr-import-disabledColumn",currValue==="");if(currValue===""){delete pageObj.columnsListData[idx];pageObj.adjustImportPreviewButtons();return false;}
pageObj.columnsListData[idx]={fName:currValue};pageObj.adjustImportPreviewButtons();$importcolumnsSelectors.not(this).filter(function(){return $(this).val()===currValue;}).val("").trigger("change");});$importcolumnsSelectors.each(function(idx,select){var currValue=$(this).val();$(".import-column-"+idx,$previewTable).toggleClass("rnr-import-disabledColumn",currValue==="");if(currValue!==""){pageObj.columnsListData[idx]={fName:$(this).val()};}});},getCSVTableData:function(lines,delimiter){var tableData=[],i;for(i=0;i<lines.length;i++){tableData.push(this.parceCSVLine(lines[i],delimiter));}
return tableData;},parceCSVLine:function(line,delimiter){if(typeof line!=="string"){return[];}
if(line.charAt(line.length-1)==='\n'){line=line.slice(0,-1);}
if(!line.length){return[];}
var currentChar,i,cellValue='',quoted=false,cells=[];for(i=0;i<line.length;i++){currentChar=line.charAt(i);if(currentChar==='"'){if(!quoted){quoted=true;}else{if(line.charAt(i+1)==='"'){i=i+1;}else{quoted=false;}}}
if(currentChar===delimiter&&!quoted){cells.push(cellValue);cellValue='';}else{cellValue+=currentChar;}}
cells.push(cellValue);return cells;},getDateFormattedValue:function(dateValue,dateFormat){if(isNaN(parseInt(dateValue,10))){return dateValue;}
var date=new Date(dateValue*1000),day=date.getDate(),month=date.getMonth()+1,year=date.getFullYear(),formattedValue=dateFormat;formattedValue=formattedValue.replace(/yyyy/i,year);formattedValue=formattedValue.replace(/yy/i,year);formattedValue=formattedValue.replace(/MM/i,month<10?'0'+month:month);formattedValue=formattedValue.replace(/M/i,month);formattedValue=formattedValue.replace(/dd/i,day<10?'0'+day:day);formattedValue=formattedValue.replace(/d/i,day);return formattedValue;},getImportFieldsSelectMarkup:function(idx,headerName){var optionsList=this.getImportFieldsOptions(headerName);return'<select class="importColumnSelector" data-idx="'+idx+'" id="importColumn'+idx+'">'+optionsList+'</select>';},getImportFieldsOptions:function(headerName){var options=['<option value=""></option>'],selectedAttr;$.each(this.importFieldsLabels,function(fieldName,fieldLabel){selectedAttr=fieldName===headerName?'selected="selected"':'';options.push('<option value="'+fieldName.replace(/"/g,'&quot;')+'" '+selectedAttr+'>'+fieldLabel+'</option>');});return options.join("");},getImportDateFormat:function(){var $dateFomat=this.previewControls["dateFormat"];return $dateFomat&&$dateFomat.length?$dateFomat.val():"";},isHeadersLineUsed:function(){return!this.previewControls["headersLineIsNotUsed"].prop("checked");},getImportDelimiter:function(){if(!this.CSVPreview){return;}
var delimiter=this.previewControls["delimiters"].filter(":checked").val();if(delimiter==="other"){delimiter=this.previewControls["customDelimiter"].val();}
return delimiter||",";},getImportFieldsData:function(){return this.columnsListData;},importData:function(){var pageObj=this,importData={CSV:this.CSVPreview,delimiter:this.getImportDelimiter(),useHeadersLine:this.isHeadersLineUsed(),dateFormat:this.getImportDateFormat(),importFieldsData:this.getImportFieldsData()},ajaxParams={a:"importData",importData:JSON.stringify(importData)};this.showBrick("import_process");$("#importProgress"+this.id).empty().append(Runner.getLoadingBlock(Runner.lang.constants.IMPORT_PROCESSING_RECORDS));this.saveImportSettings(importData);Runner.submitRunnerFormInIframe(this.submitUrl,{baseParams:ajaxParams},function(respObj,formObj,fieldControls){if(respObj.failed){$("#importErrorMessage"+pageObj.id).html(respObj.message||Runner.lang.constants.IMPORT_FAILED).show();pageObj.backToImportPreview();return;}
pageObj.importPageMode=pageObj.modeConstants.RESULTS;$("#reportText"+pageObj.id).html(respObj.reportText);pageObj.showBrick("import_results");pageObj.hideBrick("import_preview");pageObj.hideBrick("import_process");pageObj.initalizeReportResultButtons(respObj.unprocessedRecordsNumber>0);},function(rawText){pageObj.backToImportPreview();pageObj.displayGenericAjaxError(rawText);});},backToImportPreview:function(){if(this.importPageMode!==this.modeConstants.PREVIEW){return;}
this.hideBrick("import_process");this.$backButton.show();this.$importButton.show();},saveImportSettings:function(importData){localStorage.setItem("import_"+this.settingsHash,JSON.stringify(importData));},initalizeReportResultButtons:function(hasNotImportedRecords){var pageObj=this,saveReportSelectorBase=hasNotImportedRecords?'saveErrorReport':'saveReport';$("[id='newImport"+this.id+"']").on("click",function(e){window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_IMPORT);return false;}).show();$("[id='"+saveReportSelectorBase+this.id+"']").on("click",function(e){Runner.submitRunnerFormInIframe(pageObj.submitUrl,{baseParams:{a:"downloadReport"}},function(respObj,formObj,fieldControls){},function(rawResponce){pageObj.displayGenericAjaxError(rawResponce);});return false;}).show();if(hasNotImportedRecords){$(".errorReportButtons"+pageObj.id).show();$("[id='saveUnprocessedData"+this.id+"']").on("click",function(e){Runner.submitRunnerFormInIframe(pageObj.submitUrl,{baseParams:{a:"downloadUnprocessed"}},function(respObj,formObj,fieldControls){},function(rawResponce){pageObj.displayGenericAjaxError(rawResponce);});return false;});}}});Runner.pages.RegisterPage=Runner.extend(Runner.pages.RunnerPage,{submitUrl:"",registred:false,passFieldName:"",userFieldName:"",emailFieldName:"",fileFieldsCount:0,form:null,upploadErrorHappened:false,controls:{},saveButton:{},constructor:function(cfg){Runner.pages.RegisterPage.superclass.constructor.call(this,cfg);this.submitUrl=Runner.getPageUrl(Runner.pages.constants.PAGE_REGISTER);this.addEvents("beforeSave");},init:function(){Runner.pages.RegisterPage.superclass.init.call(this);if(this.beforeSave){this.on({'beforeSave':this.beforeSave});}
this.initFields();this.initButtons();this.initControlEvents();this.addValidation();if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){this.on('windowSizeCorrected',this.setFirstFocus);}else{this.setFirstFocus();}
this.initPreValidation();this.fireEvent('afterInit',this,this.proxy,this.id);},initFields:function(){var i,fName,realFieldName,fields=["passFieldName","userFieldName","emailFieldName"];for(i=0;i<fields.length;i++){fName=fields[i];realFieldName=Runner.pages.PageSettings.getTableData(this.tName,fName);this[fName]=realFieldName;if(realFieldName){this.controls[realFieldName]=Runner.getControl(this.pageId,realFieldName);}}},addValidation:function(){var ctrlName,ctrl,ctrlEmail=this.controls[this.emailFieldName],ctrlLogin=this.controls[this.userFieldName],ctrlPass=this.controls[this.passFieldName];if(ctrlEmail){ctrlEmail.valueElem.attr('autocomplete','off');ctrlEmail.addValidation('IsEmail');ctrlEmail.addValidation('DenyDuplicated');ctrlEmail.customValidationFailedMessages['DenyDuplicated']={message:Runner.lang.constants.TEXT_INLINE_EMAIL_ALREADY1
+"&nbsp;<i>%value%</i>&nbsp;"
+Runner.lang.constants.TEXT_INLINE_EMAIL_ALREADY2,messageType:'Text'}}
if(ctrlLogin){ctrlLogin.valueElem.attr('autocomplete','off');ctrlLogin.addValidation('DenyDuplicated');ctrlLogin.customValidationFailedMessages['DenyDuplicated']={message:Runner.lang.constants.TEXT_INLINE_USERNAME_EXISTS1
+"&nbsp;<i>%value%</i>&nbsp;"
+Runner.lang.constants.TEXT_INLINE_USERNAME_EXISTS2,messageType:'Text'}}
if(ctrlPass&&Runner.pages.PageSettings.getGlobalData("pwdStrong")){ctrlPass.addValidation('CheckStrongPassword');}
for(ctrlName in this.controls){ctrl=this.controls[ctrlName];if(!ctrl){continue;}
if(!ctrl.isSetValidation('IsRequired')){ctrl.addValidation('IsRequired');}}},initButtons:function(){var pageObj=this;this.saveButton=$("a[id=saveButton"+this.id+"]").bind("click",function(e){var ctrls=Runner.controls.ControlManager.getAt(pageObj.tName),$button=$(this),ctrl,index;$button.addClass('disabled');pageObj.upploadErrorHappened=false;pageObj.fileFieldsCount=0;for(index=0;index<ctrls.length;index++){ctrl=ctrls[index];if(ctrl.editFormat==Runner.controls.constants.EDIT_FORMAT_FILE&&ctrl.filesToUploadCount>0){pageObj.fileFieldsCount++;ctrl.errorHappened=false;ctrl.uploadForm.bind('fileuploadstopped',{ctrl:ctrl},function(e,data){pageObj.fileFieldsCount--;$button.unbind('fileuploadstopped');if(e.data.ctrl.errorHappened){pageObj.upploadErrorHappened=true;pageObj.callErrorHn();}else{pageObj.callSaveHn();}});$(".btn-primary.start",ctrl.uploadForm).click();}}
if(pageObj.fileFieldsCount<1){pageObj.callSaveHn();}
return false;});},callErrorHn:function(){if(this.fileFieldsCount<1){this.saveButton.removeClass('disabled');}},callSaveHn:function(){if(this.upploadErrorHappened||this.fileFieldsCount>0){return;}
this.getForm();this.setPageModified(false);this.form.submit();},initControlEvents:function(){var confirmCtrl=Runner.controls.ControlManager.getAt(this.tName,this.id,"confirm"),passCtrl=this.controls[this.passFieldName];if(!confirmCtrl){return;}
passCtrl.on("blur",function(e){if(this.getValue()!=confirmCtrl.getValue()&&confirmCtrl.getValue()!=""){confirmCtrl.markInvalidWidthCusttomMessages("notMatchPasswords",[Runner.lang.constants.PASSWORDS_DONT_MATCH]);confirmCtrl.setFocus();return;}
confirmCtrl.clearInvalid();});confirmCtrl.on("blur",function(e){if(this.getValue()!=passCtrl.getValue()){this.markInvalidWidthCusttomMessages("notMatchPasswords",[Runner.lang.constants.PASSWORDS_DONT_MATCH]);return;}
this.clearInvalid();});},initPreValidation:function(){var invalidControls=[],userErrorMessage=Runner.pages.PageSettings.getTableData(this.tName,"msg_userError"),emailErrorMessage=Runner.pages.PageSettings.getTableData(this.tName,"msg_emailError"),passwordErrorMessage=Runner.pages.PageSettings.getTableData(this.tName,"msg_passwordError");if(userErrorMessage!==""){this.controls[this.userFieldName].markInvalidWidthCusttomMessages("userErrorMessage",[userErrorMessage]);invalidControls.push(this.controls[this.userFieldName]);}
if(emailErrorMessage!==""){this.controls[this.emailFieldName].markInvalidWidthCusttomMessages("emailErrorMessage",[emailErrorMessage]);invalidControls.push(this.controls[this.emailFieldName]);}
if(passwordErrorMessage!==""){this.controls[this.passFieldName].markInvalidWidthCusttomMessages("passwordErrorMessage",[passwordErrorMessage]);invalidControls.push(this.controls[this.passFieldName]);}
this.setFirstFocus(this.id,invalidControls);},openLoginPageOnPopUpClose:function(notRedirect,hostPage){var pageObj=this,user=this.registred?this.controls[this.userFieldName].getValue():'',pass=this.registred?this.controls[this.passFieldName].getValue():'';this.openLoginPage(user,pass,function(){pageObj.close();},notRedirect,hostPage);},getForm:function(){var pageObj=this;this.form=this.form||new Runner.form.BasicForm({id:this.pageId,method:'POST',submitUrl:this.submitUrl,isFileUpload:true,standardSubmit:this.openMode!==Runner.pages.constants.OPENMODE_POPUP,baseParams:{btnSubmit:"Register",id:this.pageId,onFly:this.openMode===Runner.pages.constants.OPENMODE_POPUP?1:0},fieldControls:Runner.controls.ControlManager.getAt(this.tName),beforeSubmit:{fn:function(formObj){var confirmCtrl=Runner.controls.ControlManager.getAt(this.tName,this.id,"confirm"),passCtrl=this.controls[this.passFieldName];if(confirmCtrl&&passCtrl&&passCtrl.getValue()!==confirmCtrl.getValue()){Runner.delDisabledClass(this.saveButton);return false;}
return this.fireEvent("beforeSave",formObj,formObj.fieldControls,this);},scope:this},successSubmit:{fn:function(respObj,basicForm,fieldControls){var $procToLogin;if(respObj.html){this.registred=true;if(this.bsWin){$(".modal-body",this.bsWin).html(respObj.html);}else{this.win.set('bodyContent',respObj.html);}
$("a[id=closeWindowRegister]").bind("click",function(e){pageObj.openLoginPageOnPopUpClose();return false;})
$procToLogin=$("a[id=ProceedToLogin]").hide();if($procToLogin.length){this.saveButton.hide();}else{Runner.delDisabledClass(this.saveButton);}}else if(!respObj.success&&respObj.message){this.displayHalfPreparedMessage(respObj.message,true);if(respObj.wrongCaptchaFieldName!==undefined){this.openFieldTabsSections([respObj.wrongCaptchaFieldName]);Runner.getControl(this.pageId,respObj.wrongCaptchaFieldName).setFocus();this.adjustHeightAndWidth();}
Runner.delDisabledClass(this.saveButton);}
else if(!respObj.success&&respObj.withoutMessage){this.setFirstFocus();Runner.delDisabledClass(this.saveButton);}},scope:this},validationFailed:{fn:function(formObj,fieldControls,failedControlsArr){var fNamesArr=[],i;for(i=0;i<failedControlsArr.length;i++){fNamesArr.push(failedControlsArr[i].fieldName);}
this.openFieldTabsSections(fNamesArr);setTimeout(function(){failedControlsArr[0].setFocus();},4);Runner.delDisabledClass(this.saveButton);},scope:this},submitFailed:{fn:function(response,formObj,fieldControls){Runner.delDisabledClass(this.saveButton);},scope:this},});}});Runner.pages.ChangePwdPage=Runner.extend(Runner.pages.RunnerPage,{form:null,fields:null,submitUrl:"",controls:null,saveButton:{},oldPassFieldName:"oldpass",newPassFieldName:"newpass",confirmFieldName:"confirm",constructor:function(cfg){Runner.pages.ChangePwdPage.superclass.constructor.call(this,cfg);this.fields=[this.oldPassFieldName,this.newPassFieldName,this.confirmFieldName];this.submitUrl=Runner.getPageUrl(Runner.pages.constants.PAGE_CHANGEPASS);this.addEvents("beforeSave");},init:function(){Runner.pages.ChangePwdPage.superclass.init.call(this);if(this.beforeSave){this.on({'beforeSave':this.beforeSave});}
this.initFields();this.initButtons();this.initControlEvents();this.addValidation();this.initPreValidation();this.setFirstFocus();this.fireEvent('afterInit',this,this.proxy,this.id);},initFields:function(){this.controls={};for(var i=0;i<this.fields.length;i++){this.controls[this.fields[i]]=Runner.getControl(this.pageId,this.fields[i]);}},initButtons:function(){var pageObj=this;this.saveButton=$("[id=saveButton"+this.id+"]").on("click",function(e){$(this).addClass('disabled');pageObj.callSaveHn();return false;});},callSaveHn:function(){var form=this.form||new Runner.form.BasicForm({id:this.pageId,method:'POST',submitUrl:this.submitUrl,standardSubmit:true,useMultipart:true,fieldControls:Runner.controls.ControlManager.getAt(this.tName),baseParams:{btnSubmit:"Change",id:this.pageId,token:this.proxy["token"]},beforeSubmit:{fn:function(formObj){return this.fireEvent("beforeSave",formObj,formObj.fieldControls,this);},scope:this},validationFailed:{fn:function(formObj,fieldControls){Runner.delDisabledClass(this.saveButton);},scope:this},submitFailed:{fn:function(response,formObj,fieldControls){Runner.delDisabledClass(this.saveButton);},scope:this},});this.form=form;this.setPageModified(false);form.submit();},errorHn:function(row){this.saveButton.removeClass('disabled');},initControlEvents:function(){var confirmCtrl=this.controls[this.confirmFieldName],newPassCtrl=this.controls[this.newPassFieldName];newPassCtrl&&newPassCtrl.on('edited',function(e){if(this.getValue()!=confirmCtrl.getValue()&&confirmCtrl.getValue()!=""){confirmCtrl.markInvalidWidthCusttomMessages("notMatchPasswords",[Runner.lang.constants.PASSWORDS_DONT_MATCH]);confirmCtrl.setValue('');confirmCtrl.setFocus();return;}
confirmCtrl.clearInvalid();});confirmCtrl&&confirmCtrl.on('edited',function(e){if(this.getValue()!=newPassCtrl.getValue()){this.markInvalidWidthCusttomMessages("notMatchPasswords",[Runner.lang.constants.PASSWORDS_DONT_MATCH]);this.setValue('');newPassCtrl.setValue('');newPassCtrl.setFocus();return;}
this.clearInvalid();});},addValidation:function(){var ctrlName,ctrl,newPassCtrl=this.controls[this.newPassFieldName];if(newPassCtrl&&Runner.pages.PageSettings.getGlobalData("pwdStrong")){newPassCtrl.addValidation('CheckStrongPassword');}
for(ctrlName in this.controls){ctrl=this.controls[ctrlName];if(!ctrl){continue;}
if(!ctrl.isSetValidation('IsRequired')){ctrl.addValidation('IsRequired');}}},initPreValidation:function(){var passwordErrorMessage=Runner.pages.PageSettings.getTableData(this.tName,"msg_passwordError");if(passwordErrorMessage!==""&&this.controls[this.newPassFieldName]){this.controls[this.newPassFieldName].markInvalidWidthCusttomMessages("passwordErrorMessage",[passwordErrorMessage]);}}});Runner.search.SearchForm=Runner.extend(Runner.util.Observable,{id:-1,tName:"",shortTName:"",pageType:"",usedSrch:false,useSuggest:false,searchType:"panel",fNamesArr:[],baseParams:null,formBaseParams:null,isSearchRequired:false,requiredSearchFields:null,srchForm:null,ctrlsShowMap:{},ajaxSubmit:false,optCombosArr:[],searchFields:null,searchButton:null,conditionRadioTop:null,smplSrchBox:null,simpleSrchTypeCombo:null,simpleSrchFieldsCombo:null,constructor:function(cfg){this.fNamesArr=[];this.ctrlsShowMap={};this.baseParams={};this.searchFields={};this.optCombosArr=[];this.requiredSearchFields=[];Runner.apply(this,cfg);Runner.search.SearchForm.superclass.constructor.call(this,cfg);this.conditionRadioTop=$('input:radio[name=srchType'+this.id+']');this.smplSrchBox=$('#ctlSearchFor'+this.id);this.simpleSrchTypeCombo=$('#simpleSrchTypeCombo'+this.id);this.simpleSrchFieldsCombo=$('#simpleSrchFieldsCombo'+this.id);this.addEvents('beforeSearch','afterSearch');},init:function(ctrlsBlocks){this.initControlBlocks(ctrlsBlocks);this.initSearchFields();this.initSearchFieldsHandlers();this.initForm();this.initButtons();},initForm:function(){this.srchForm=new Runner.form.BasicForm({id:this.id,addRndVal:false,isSearchForm:true,initImmediately:true,submitUrl:this.getSubmitUrl(),standardSubmit:!this.ajaxSubmit,baseParams:this.formBaseParams||this.baseParams||{},method:this.ajaxSubmit?"POST":"GET"});this.srchForm.on('successSubmit',function(respObj){this.fireEvent('afterSearch',respObj,this,this.srchForm);},this);},getSubmitUrl:function(){var tName=this.searchTableName||this.tName,pageType=this.pageType;if(this.pageType===Runner.pages.constants.PAGE_DREPORT||this.pageType===Runner.pages.constants.PAGE_DCHART){tName="";}else if(this.pageType!==Runner.pages.constants.PAGE_REPORT&&this.pageType!==Runner.pages.constants.PAGE_CHART&&this.pageType!==Runner.pages.constants.PAGE_PRINT&&this.pageType!==Runner.pages.constants.PAGE_DASHBOARD&&this.pageType!==Runner.pages.constants.PAGE_SEARCH){pageType=Runner.pages.constants.PAGE_LIST;}
return Runner.pages.getUrl(tName,pageType);},initCombo:function(recId,fName,map){var comboId=this.getComboId(fName,recId),$combo=$("#"+comboId),tName=this.tName,controller=this;$combo.bind("change",function(e){var setEmpty=this.value==='Empty'||this.value==='NOT Empty',ctrl0=Runner.controls.ControlManager.getAt(tName,recId,fName,0),ctrl1;ctrl0.updateAppearance(this.value);ctrl0.toggle(!setEmpty);controller.toggleSearhButtonStatus();if(map.length===2){ctrl1=Runner.controls.ControlManager.getAt(tName,recId,fName,1);}
if(ctrl1){ctrl1.toggle(this.value==='Between'||this.value==='NOT Between');}});this.optCombosArr.push($combo);},initButtons:function(){this.searchButton=$("#searchButton"+this.id);this.initSearchButtonStatus();},initControlBlocks:function(ctrlsBlocks){for(var i=0;i<ctrlsBlocks.length;i++){this.addRegCtrlsBlock(ctrlsBlocks[i].fName,ctrlsBlocks[i].recId,ctrlsBlocks[i].ctrlsMap);if(this.isSearchPanelInflexible){this.inflexSearchOptions[ctrlsBlocks[i].fName]=ctrlsBlocks[i].inflexSearchOption;}}},initSearchFieldsHandlers:function(){var fName,recId,ctrlIndices,i,ctrl;for(fName in this.ctrlsShowMap){for(recId in this.ctrlsShowMap[fName]){ctrlIndices=this.ctrlsShowMap[fName][recId];for(i=0;i<ctrlIndices.length;i++){ctrl=Runner.controls.ControlManager.getAt(this.tName,recId,fName,ctrlIndices[i]);this.initSearchField(ctrl);}}}},initSearchField:function(ctrl){if(!ctrl){return;}
if(ctrl.ctrlInd===0&&!ctrl.cached){this.addSearchField(ctrl.fieldName,ctrl.id);}
this.initSuggest(ctrl);this.setHandlerForRequiredField(ctrl);},initSuggest:function(ctrl){if(!this.useSuggest||!ctrl.useSearchSuggests()){return;}
var searchController=this,$searchSuggestDiv=$("#search_suggest");if(!$searchSuggestDiv.length){$searchSuggestDiv=$('<div id="search_suggest"></div>').appendTo('body');}
$searchSuggestDiv.addClass("search_suggest");ctrl.on('keyup',function(e){if(!Runner.isAcceptableKeyCode(e)||!ctrl.implySuggests()){return;}
if(searchController.submitTimeout){clearTimeout(searchController.submitTimeout);}
searchController.submitTimeout=setTimeout(function(){var srchTypeComboId=searchController.getComboId(searchController.tName,searchController.id),srchTypeCombo=$('#'+srchTypeComboId),suggestUrl=Runner.getPageUrl('searchsuggest','','table='+searchController.shortTName);searchSuggest_new(e,ctrl,srchTypeCombo,'advanced',suggestUrl);},700);});ctrl.on('keydown',function(e){searchController.listenEvent(e,this.valueElem.get(0));});},listenEvent:function(oEvent,oElement){var searchController=this,iKeyCode=(window.event||oEvent).keyCode;switch(iKeyCode){case 38:if(this.useSuggest){moveUp(oElement);}
break;case 40:if(this.useSuggest){moveDown(oElement);}
break;case 13:if(this.useSuggest){DestroySuggestDiv();}
if(!Runner.isDisabledButton(searchController.searchButton)){searchController.submitSearch();}
break;case 9:if(this.useSuggest){DestroySuggestDiv();}}},submitSavedSearch:function(searchParams){this.ajaxSubmit=false;this.srchForm.baseParams={};this.srchForm.standardSubmit=true;var q=searchParams['q'],qs=searchParams['qs'],f=searchParams['f'],criterion=searchParams['criteria'];this.fireEvent('beforeSearch',this,this.srchForm);this.srchForm.clearForm();this.srchForm.searchSubmit=true;if(qs!==undefined&&qs!==''){this.srchForm.addToForm('qs',qs);this.srchForm.addToSearchForm('qs',encodeURIComponent(qs));}
if(q!==undefined&&q!==''){this.srchForm.addToForm('q',q);this.srchForm.addToSearchForm('q',encodeURIComponent(q));}
if(f!==undefined&&f!==''){this.srchForm.addToForm('f',f);this.srchForm.addToSearchForm('f',encodeURIComponent(f));}
if(criterion&&criterion!=='and'){this.srchForm.addToForm('criteria',criterion);this.srchForm.addToSearchForm('criteria',encodeURIComponent(criterion));}
if(qs===''&&this.ajaxSubmit){this.srchForm.addToForm('q','');}
this.srchForm.addToForm('savedSearch',true);this.srchForm.addToSearchForm('savedSearch',true);this.usedSrch=true;this.srchForm.submit();},submitSearch:function(){var simpleQuery;this.fireEvent('beforeSearch',this,this.srchForm);this.srchForm.clearForm();this.srchForm.searchSubmit=true;simpleQuery=this.addSimpleQueryParams();this.addAdvansedQueryParams(simpleQuery);this.addFilterParams();this.addCriteriaParam();this.prepareForSearchSubmit();this.srchForm.submit();},prepareForSearchSubmit:function(){this.usedSrch=true;},addSimpleQueryParams:function(){var i,valSeparator='~',simpleQuery='',simpleQueryEncoded='',simpleSrchTypeComboVal=this.simpleSrchTypeCombo.val(),simpleQueryArr=[this.searchEscape(this.smplSrchBox.val()||"",true),'',''];simpleQueryArr[1]=this.searchEscape(this.simpleSrchFieldsCombo.val()||"",true);if(simpleSrchTypeComboVal=='Contains'){simpleSrchTypeComboVal="";}else{simpleSrchTypeComboVal=Runner.pages.constants.SEARCH_OPTIONS[simpleSrchTypeComboVal];}
simpleQueryArr[2]+=simpleSrchTypeComboVal||"";for(i=simpleQueryArr.length-1;i>=0;i--){simpleQuery=simpleQueryArr[i]+(simpleQuery==''?'':valSeparator)+simpleQuery;simpleQueryEncoded=encodeURIComponent(simpleQueryArr[i])+(simpleQueryEncoded==''?'':valSeparator)+simpleQueryEncoded;}
if(simpleQuery!=''){this.srchForm.addToForm('qs',simpleQuery);this.srchForm.addToSearchForm('qs',simpleQueryEncoded);}
return simpleQuery;},addCriteriaParam:function(){var criterion=this.getSearchCriterion();if(criterion!=='and'){this.srchForm.addToForm('criteria',criterion);this.srchForm.addToSearchForm('criteria',encodeURIComponent(criterion));}},getSearchCriterion:function(){return this.conditionRadioTop.length?this.conditionRadioTop.filter(':checked').val():'and';},addAdvansedQueryParams:function(simpleQuery){var queryParams=this.getSearchControlsQueryParams(),query=queryParams['query'],queryEncoded=queryParams['queryEncoded'];if(query!=''){this.srchForm.addToForm('q',query);this.srchForm.addToSearchForm('q',queryEncoded);return;}
if(simpleQuery==''&&this.ajaxSubmit){this.srchForm.addToForm('q','');}},getSearchControlsQueryParams:function(){var i,fName,ind,valSeparator='~',fieldSeparator=')(',query='',queryEncoded='';for(fName in this.ctrlsShowMap){for(ind in this.ctrlsShowMap[fName]){var fMap=this.ctrlsShowMap[fName][ind],ctrl1=Runner.controls.ControlManager.getAt(this.tName,ind,fName,fMap[0]),srchCombo=$('#'+this.getComboId(fName,ind)),cachedRow=$("#"+this.getFilterRowId(fName,ind,this.srchWinShowStatus)),srchCheckBox=$('#'+this.getCheckBoxId(fName,ind)),fieldQuery='',fieldQueryEncoded='',comboVal,fieldArray,ctrl2=null;if(!ctrl1.appearOnPage()){continue;}
comboVal=srchCombo.length?srchCombo.val():this.getInflexSearchOption(fName);if(comboVal.indexOf('Between')!==-1&&fMap[1]){ctrl2=Runner.controls.ControlManager.getAt(this.tName,ind,fName,fMap[1]);}
if(ctrl1.isEmpty()&&comboVal.indexOf('Empty')==-1&&(comboVal.indexOf('Between')==-1||ctrl2&&ctrl2.isEmpty())||cachedRow.css('display')=='none'){continue;}
fieldArray=['',this.searchEscape(ctrl1.getStringValue()),ctrl1.ctrlType,''];if(comboVal!=''){if(srchCheckBox.length&&srchCheckBox.prop("checked")){comboVal="NOT "+comboVal;}
fieldArray[0]=Runner.pages.constants.SEARCH_OPTIONS[comboVal];}
if(ctrl2){fieldArray[3]=this.searchEscape(ctrl2.getStringValue());}
for(i=fieldArray.length;i--;){fieldQuery=fieldArray[i]+(fieldQuery==''?'':valSeparator)+fieldQuery;fieldQueryEncoded=encodeURIComponent(fieldArray[i])+(fieldQueryEncoded==''?'':valSeparator)+fieldQueryEncoded;}
query+=(query!=''?fieldSeparator:'(')+this.searchEscape(fName)+valSeparator+fieldQuery;queryEncoded+=(queryEncoded!=''?fieldSeparator:'(')+encodeURIComponent(this.searchEscape(fName))+
valSeparator+fieldQueryEncoded;}}
return{query:query===''?query:query+')',queryEncoded:queryEncoded===''?queryEncoded:queryEncoded+')'};},addFilterParams:function(){var i,ctrl,filterValue,filterValueEncoded,query='',queryEncoded='';if(!this.filterControls||!this.filterControls.length){return;}
for(i=0;i<this.filterControls.length;i++){ctrl=this.filterControls[i];filterValue=ctrl.getFilterValue();if(filterValue){query+=filterValue;filterValueEncoded=ctrl.getFilterValueEncoded();queryEncoded+=filterValueEncoded;}}
if(query===''){queryEncoded=query='all';}
this.srchForm.addToForm('f',query);this.srchForm.addToSearchForm('f',queryEncoded);},searchEscape:function(value,searchSimple){if(typeof value=="object"){var formObj=this;$.each(value,function(index,element){value[index]=formObj.searchEscape(value[index],searchSimple);});return value;}
if(!value){return"";}
value=value.replace(/\\/g,"\\\\").replace(/~/g,"\\~");if(searchSimple){return value;}
return value.replace(")(","\\)(");},addExtraPageParams:function(){return;},addToShowMap:function(fName,ind,ctrlMap){this.ctrlsShowMap[fName]=this.ctrlsShowMap[fName]||{};this.ctrlsShowMap[fName][ind]=ctrlMap;},addRegCtrlsBlock:function(fName,ind,ctrlMap){if(ctrlMap){this.addToShowMap(fName,ind,ctrlMap);}
this.initCombo(ind,fName,ctrlMap);},getComboId:function(fName,ind){return"srchOpt_"+ind+"_"+Runner.goodFieldName(fName);},getFilterRowId:function(fName,ind){return"filter_"+ind+"_"+Runner.goodFieldName(fName);},getCheckBoxId:function(fName,ind){return"not_"+ind+"_"+Runner.goodFieldName(fName);},showAllSubmit:function(){this.srchForm.clearForm();this.srchForm.addToForm('a','showall');this.prepareForShowAllSubmit();this.srchForm.submit();},prepareForShowAllSubmit:function(){this.usedSrch=false;this.simpleSearchActive=false;this.clearSimpleSearch();this.clearCtrls();},returnSubmit:function(){this.srchForm.clearForm();this.srchForm.addToForm('a','return');this.srchForm.submit();},clearCtrls:function(){var $defaultOption,$select,i;jQuery.each(Runner.controls.ControlStorage.byTable(this.tName),function(){this.clear();});for(i=0;i<this.optCombosArr.length;i++){$select=this.optCombosArr[i];if(!$select.length){continue;}
$defaultOption=$select.find('option[data-default-option]');$defaultOption=$defaultOption.length?$defaultOption:$select.find('option').eq(0);$defaultOption.prop('selected',true);$select.change();}
$("input[id^=not_]").prop('checked',false);this.conditionRadioTop.first().prop('checked',true);},hasNotEmptyControl:function(){var fName,searchFields,i;for(fName in this.searchFields){searchFields=this.searchFields[fName];for(i=0;i<searchFields.length;i++){if(searchFields[i].checkIfCtrlsValuesSet()){return true;}}}
return false;},clearSimpleSearch:function(){var defaultOption;this.smplSrchBox.val('');if(this.simpleSrchFieldsCombo.length){defaultOption=$("option:visible:eq(0)",this.simpleSrchFieldsCombo).val();this.simpleSrchFieldsCombo.val(defaultOption);}
if(this.simpleSrchTypeCombo.length){defaultOption=$("option:visible:eq(0)",this.simpleSrchTypeCombo).val();this.simpleSrchTypeCombo.val(defaultOption);}},initSearchFields:function(){for(var i=0;i<this.fNamesArr.length;i++){this.searchFields[this.fNamesArr[i]]=[];}},addSearchField:function(fName,id){if(!this.searchFields[fName]){return;}
this.searchFields[fName].push(new Runner.search.SearchField({id:id,fName:fName,searchObj:this}));},setHandlerForRequiredField:function(ctrl){var searchController=this,$ctrlElem;if(!this.isFieldRequired(ctrl.fieldName)){return false;}
ctrl.on("editing",function(){searchController.toggleSearhButtonStatus();});ctrl.on("edited",function(){searchController.toggleSearhButtonStatus();});$ctrlElem=ctrl.getDispElem();if($ctrlElem instanceof jQuery){$ctrlElem.on("input",function(){searchController.toggleSearhButtonStatus();});}},isFieldRequired:function(fName){if($.inArray(fName,this.requiredSearchFields)===-1){return false;}
return true;},toggleSearhButtonStatus:function(){var requiredFieldsLength=this.requiredSearchFields.length,i,j,rfName,rfSearchFields,disable;if(!requiredFieldsLength){return;}
for(i=0;i<requiredFieldsLength;i++){rfName=this.requiredSearchFields[i];rfSearchFields=this.searchFields[rfName];disable=true;for(j=0;j<rfSearchFields.length;j++){if(rfSearchFields[j].checkIfCtrlsValuesSet()){disable=false;break;}}
if(disable&&(this.simpleSrchFieldsCombo.val()!==rfName||this.smplSrchBox.val()==='')){break;}}
this.searchButton.closest('.rnr-button, .btn').toggleClass('disabled',disable);},initSearchButtonStatus:function(){var searchController=this;if(!this.requiredSearchFields.length){return false;}
this.toggleSearhButtonStatus();this.simpleSrchFieldsCombo.on("change",function(e){searchController.toggleSearhButtonStatus();});this.smplSrchBox.on("change",function(e){searchController.toggleSearhButtonStatus();});},getDashSearchParams:function(showAllMode){var searchParams={},searchQueryParams;if(showAllMode){searchParams['a']='showall';}else{searchQueryParams=this.getSearchControlsQueryParams();if(searchQueryParams['query']){searchParams['q']=searchQueryParams['query'];searchParams['criteria']=this.getSearchCriterion();}}
return searchParams;}});Runner.search.options={CONTAINS:"Contains",EQUALS:"Equals",STARTS_WITH:"Starts with",MORE_THAN:"More than",LESS_THAN:"Less than",BETWEEN:"Between",EMPTY:"Empty",NOT_CONTAINS:"NOT Contains",NOT_EQUALS:"NOT Equals",NOT_STARTS_WITH:"NOT Starts with",NOT_MORE_THAN:"NOT More than",NOT_LESS_THAN:"NOT Less than",NOT_BETWEEN:"NOT Between",NOT_EMPTY:"NOT Empty"};Runner.search.optionsText={"Contains":Runner.lang.constants.CONTAINS,"Equals":Runner.lang.constants.EQUALS,"Starts with":Runner.lang.constants.STARTS_WITH,"More than":Runner.lang.constants.MORE_THAN,"Less than":Runner.lang.constants.LESS_THAN,"Between":Runner.lang.constants.BETWEEN,"Empty":Runner.lang.constants.EMPTY,"NOT Contains":Runner.lang.constants.NOT_CONTAINS,"NOT Equals":Runner.lang.constants.NOT_EQUALS,"NOT Starts with":Runner.lang.constants.NOT_STARTS_WITH,"NOT More than":Runner.lang.constants.NOT_MORE_THAN,"NOT Less than":Runner.lang.constants.NOT_LESS_THAN,"NOT Between":Runner.lang.constants.NOT_BETWEEN,"NOT Empty":Runner.lang.constants.NOT_EMPTY};Runner.search.SearchField=Runner.extend(Runner.emptyFn,{fName:"",id:0,opt:null,searchObj:null,constructor:function(cfg){Runner.apply(this,cfg);this.init();},init:function(){this.opt=$('#'+this.searchObj.getComboId(this.fName,this.id)).get(0);},reInit:function(){if(!this.id){this.getId();}
this.init();},isReInitSuccess:function(){if(typeof this.opt=='undefined'){this.reInit();if(!this.id){return false;}}
return true;},getName:function(){return this.fName;},getId:function(){if(!this.id){var id=this.searchObj.getLastAddedInd(this.fName);if(!this.searchObj.isFieldShownById(this.fName,id)){this.id=id;}}
return this.id;},getControl:function(){return Runner.controls.ControlManager.getAt(this.searchObj.tName,this.id,this.fName);},getSecondControl:function(){return Runner.controls.ControlManager.getAt(this.searchObj.tName,this.id,this.fName,1);},getOption:function(){if(!this.isReInitSuccess()||!this.opt){return false;}
for(var j=0;j<this.opt.options.length;j++){if(this.opt.options[j].selected){return this.opt.options[j].value;}}},setOption:function(value){if(typeof value=='undefined'||!value){return;}
if(!this.isReInitSuccess()){return;}
for(var j=0;j<this.opt.options.length;j++){if(this.opt.options[j].value==value){this.opt.selectedIndex=j;$(this.opt).change();break;}}},addOption:function(value){if(typeof value=='undefined'||!value){return;}
if(!this.isReInitSuccess()){return;}
var text=Runner.search.optionsText[value];var opt=new Option(text,value);$(opt).html(text);$(this.opt).append(opt);},getOptions:function(){if(!this.isReInitSuccess()){return false;}
return this.opt.options;},removeOption:function(value){if(!this.isReInitSuccess()){return;}
if(this.opt.options.length==1){this.searchObj.hideCtrlTypeCombo();return;}
for(var j=0;j<this.opt.options.length;j++){if(this.opt.options[j].value==value){if(this.opt.options[j].selected){if(j==0){this.opt.selectedIndex=j+1;}else{this.opt.selectedIndex=j-1;}}
this.opt.remove(j);break;}}},remove:function(){this.searchObj.deleteField(this.fName,this.id);},clearFieldCtrls:function(){var ctrl;ctrl=this.getControl();if(ctrl){ctrl.clear();}
ctrl=this.getSecondControl();if(ctrl&&!ctrl.spanContElem.is(":visible")){ctrl.clear();}},checkIfCtrlsValuesSet:function(){var ctrl,ctrl1,option=this.getOption();if(option==="Empty"||option==="NOT Empty"){return true;}
ctrl=this.getControl();ctrl1=this.getSecondControl();if((option==="Between"||option==="NOT Between")&&(!ctrl.isEmpty()||!ctrl1.isEmpty())){return true;}
if(ctrl&&ctrl.isEmpty()){return false;}
if(ctrl1&&ctrl1.spanContElem.is(":visible")&&ctrl1.isEmpty()){return false;}
return ctrl||ctrl1;}});Runner.controls.FilterControlFactory=function(baseCfg,searchController){var cfg={searchController:searchController};cfg=Runner.apply(cfg,baseCfg);switch(cfg.filterFormat){case Runner.controls.constants.FILTER_FORMAT_VALUES_LIST:case Runner.controls.constants.FILTER_FORMAT_INTERVAL_LIST:switch(cfg.multiSelect){case Runner.controls.constants.FILTER_MULTISELECT_NONE:return new Runner.controls.SimpleFilterControl(cfg);case Runner.controls.constants.FILTER_MULTISELECT_ON_DEMAND:return new Runner.controls.OnDemandFilterControl(cfg);case Runner.controls.constants.FILTER_MULTISELECT_ALWAYS:return new Runner.controls.MultiSelectFilterControl(cfg);default:throw("Invalid multiselect param("+cfg.multiSelect+") for the "+cfg.filterFormat+" format. Cannot create control!");return;}
case Runner.controls.constants.FILTER_FORMAT_BOOLEAN:return new Runner.controls.SimpleFilterControl(cfg);case Runner.controls.constants.FILTER_FORMAT_INTERVAL_SLIDER:if(cfg.isFieldDateType){return new Runner.controls.DateSliderFilterControl(cfg);}
if(cfg.isFieldTimeType){return new Runner.controls.TimeSliderFilterControl(cfg);}
return new Runner.controls.SliderFilterControl(cfg);default:throw("Invalid filter control's format = "+cfg.filterFormat+". Cannot create control!");}}
Runner.controls.FilterControl=Runner.extend(Runner.emptyFn,{ctrlValue:'',fieldName:'',gfieldName:'',filterFormat:'',multiSelect:0,filtered:false,defaultValuesArray:[],defaultShowValues:[],filterPanelContainerClass:"filterPanelContainer",filterPanelContainer:{},filterContainer:{},searchController:{},btnApplyClass:"filter-btn-apply",btnExpanderClass:"filter-expander",btnExpanderIndicatorClass:"filter-indicator",expanderElem:{},hiddenValuesClass:"filter-hidden",collapsedValuesClass:"filter-collapsed",filterValueBlockContainerClass:"filter-values",filterLinkClass:"filter-link",separator:"",dependent:false,hasDependent:false,goodOutermostParentName:"",goodParentName:"",parentFilterNames:null,hiddenFilterItemClass:"filter-item-hidden",baseCtrlButtonsInitialized:false,constructor:function(cfg){this.defaultValuesArray=[];Runner.apply(this,cfg);this.filterPanelContainer=$("."+this.filterPanelContainerClass);this.filterContainer=$(".filter-"+(this.dependent?this.goodOutermostParentName:this.gfieldName)+"-container");this.expanderElem=$("."+this.btnExpanderClass,this.filterContainer);this.init();},destructor:function(){},init:Runner.emptyFn,initButtons:function(){if(this.baseCtrlButtonsInitialized){return;}
this.initBasicButtons();this.initClearButtons();this.initShowMoreButton();this.baseCtrlButtonsInitialized=true;},initBasicButtons:function(){if(this.dependent){return;}
var ctrl=this,hiddenValuesClass=this.hiddenValuesClass,hiddenFilterItemClass=this.hiddenFilterItemClass,collapsedValuesClass=this.collapsedValuesClass,btnExpanderIndicatorClass=this.btnExpanderIndicatorClass;this.filterContainer.on('click','.'+this.btnApplyClass,function(e){$(this).data('activated',true);ctrl.searchController.submitSearch();return false;}).on('click','.'+this.btnExpanderClass,function(e){var expander=$(this),siblings=expander.parent().find('.'+ctrl.filterValueBlockContainerClass+',.filter-show-more,.filter-field-btn').not('.'+hiddenValuesClass+',.'+hiddenFilterItemClass),goingToHide=siblings.not('.'+collapsedValuesClass).length!==0,expanderIndicator=expander.children('.'+btnExpanderIndicatorClass);ctrl.adjustExpander(goingToHide);siblings.slideToggle(100).promise().done(function(){siblings.css('display','').toggleClass(collapsedValuesClass,goingToHide);});return false;});},updateCollapsedState:function(){var inCollapsedState=this.isCollapsed();if(!this.collapsed&&inCollapsedState){this.toggleCollapsed(false);}else if(this.collapsed&&!inCollapsedState){this.toggleCollapsed(true);}},toggleCollapsed:function(collapsed){var $filterItems=this.filterContainer.find('.'+this.filterValueBlockContainerClass+',.filter-show-more,.filter-field-btn');$filterItems.toggleClass(this.collapsedValuesClass,collapsed);},initClearButtons:function(){if(!this.filtered){return;}
var ctrl=this,clearBtnClass='filter-clear-'+(this.dependent?this.goodOutermostParentName:this.gfieldName);$('.'+clearBtnClass).on('click',function(e){ctrl.clearControl();ctrl.clearDependentFilters();ctrl.searchController.submitSearch();return false;});},initShowMoreButton:function(){var ctrl=this;$(".filterShowMore_"+this.gfieldName).on("click",function(e){var $showMoreElement=$(this).parent();$showMoreElement.siblings("."+ctrl.hiddenFilterItemClass).removeClass(ctrl.collapsedValuesClass).removeClass(ctrl.hiddenFilterItemClass);$showMoreElement.removeClass("filter-show-more").hide();return false;});},clearDependentFilters:function(notMultiSelected){if(!this.hasDependent){return;}
this.searchController.clearDependentFilters(this.dependentFilterNames,notMultiSelected);},setValue:function(value){this.ctrlValue=value;},getValue:function(){return this.ctrlValue;},getDisplayedValue:function(){if(this.defaultShowValues&&this.defaultShowValues.length){return this.defaultShowValues.join(", ");}
return this.getValue();},getPreparedValue:function(value,encoded){var prepValue=value;if(typeof value==="string"){prepValue=this.searchController.searchEscape(value);}
if(encoded&&typeof value==="string"){return encodeURIComponent(prepValue);}
return prepValue;},getFilterValue:function(encoded){var value,prepFName;if(this.ctrlValue===''){return'';}
value=this.getPreparedValue(this.ctrlValue,encoded);prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;return'('+prepFName+this.separator+value+')';},getFilterValueEncoded:function(){return this.getFilterValue(true);},isVisible:function(){return this.filterContainer.is(":visible");},isCollapsed:function(){var $filterItems=Runner.isBootstrap()?this.expanderElem.siblings().children("li"):this.expanderElem.siblings();return!$filterItems.not("."+this.collapsedValuesClass+",."+this.hiddenValuesClass+",."+this.hiddenFilterItemClass).length;},adjustExpander:function(collapsed){var $expanderIcon=$("."+this.btnExpanderIndicatorClass,this.expanderElem);if(!Runner.isBootstrap()){$expanderIcon.html(collapsed?"&#x25BC;":"&#x25B2;");}else{$expanderIcon.toggleClass("glyphicon-triangle-bottom",collapsed);$expanderIcon.toggleClass("glyphicon-triangle-top",!collapsed);}},clearControl:function(){this.setValue('');},updateValue:function(value){this.setValue(value);},isDependent:function(){return this.dependent;},isMultiSelected:function(){return false;}});Runner.controls.SimpleFilterControl=Runner.extend(Runner.controls.FilterControl,{superclass:{},valueLinkClass:"",constructor:function(cfg){Runner.controls.SimpleFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.SimpleFilterControl.superclass;this.valueLinkClass=this.gfieldName+"-filter-value";this.setValue(this.defaultValuesArray.join(', '));this.initButtons();},initButtons:function(){var ctrl=this,delBtnClass="delFilterCtrlButt_"+(this.dependent?this.goodOutermostParentName:this.gfieldName)+"_"+this.searchController.id;if(Runner.isBootstrap()){this.filterPanelContainer.off("click.filters"+this.gfieldName);}
this.filterPanelContainer.on("click.filters"+this.gfieldName,"."+delBtnClass,function(e){var $delButton=$(this);valueToDelete=$(this).data('delete').toString();ctrl.clearFilterValue(valueToDelete,$delButton.parent(".filter-values"));ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;});if(!this.hasDependent){this.filterPanelContainer.on("click.filters"+this.gfieldName,"."+this.filterValueBlockContainerClass+"-"+this.gfieldName,function(e){var $valueLink=$("."+ctrl.valueLinkClass,this);if(!$valueLink.length){return;}
ctrl.ctrlValue=$valueLink.attr("data-filtervalue");ctrl.updateParentFilters($valueLink.data("parentFiltersValues"));ctrl.clearDependentFilters();ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;}).on("click","."+this.valueLinkClass,function(e){e.preventDefault();});}else{$("."+ctrl.filterValueBlockContainerClass+"-"+ctrl.gfieldName,ctrl.filterContainer).removeClass(ctrl.filterLinkClass);this.filterPanelContainer.on("click","."+this.valueLinkClass,function(e){var $valueLink=$(this);ctrl.ctrlValue=$valueLink.data("filtervalue");ctrl.updateParentFilters($valueLink.data("parentFiltersValues"));ctrl.clearDependentFilters();ctrl.searchController.rememberFilterPanelState();ctrl.searchController.submitSearch();return false;});}
this.superclass.initButtons.call(this);},updateParentFilters:function(parentFiltersValuesData){if(!this.dependent){return;}
this.searchController.updateParentFilters(parentFiltersValuesData);},clearFilterValue:function(valueToDelete,$container){this.setValue('');}});Runner.controls.MultiSelectFilterControl=Runner.extend(Runner.controls.FilterControl,{checkboxes:[],checkboxClass:'',superclass:{},commonCheckboxClass:"multifilter-checkbox",parentCheckboxClass:"",constructor:function(cfg){this.checkboxes=[];Runner.controls.MultiSelectFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.MultiSelectFilterControl.superclass;this.applyButton=$(".filter-apply-"+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.checkboxClass="filter_"+this.gfieldName+"_"+this.searchController.id;this.checkboxes=$("."+this.checkboxClass);this.selectAllCheckbox=$(".filter-selectAll-"+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.parentCheckboxClass=this.dependent?"filter_"+this.goodParentName+"_"+this.searchController.id:"";this.adjustSelectAllCheckbox();if(this.filtered&&!this.dependent){this.setValue(this.defaultValuesArray);}
this.initButtons();},adjustSelectAllCheckbox:function(){var currentState=this.selectAllCheckbox.is(":checked"),allChecked=this.checkboxes.length===this.checkboxes.filter(":checked").length
this.selectAllCheckbox.prop("checked",currentState&&allChecked);},initButtons:function(){var ctrl=this;this.selectAllCheckbox.on("click",function(e){e.stopPropagation();}).on("change",function(e){ctrl.checkboxes.prop("checked",this.checked);ctrl.clearDependentFilters(true);return false;});this.checkboxes.on("click",function(e){ctrl.adjustSelectAllCheckbox();ctrl.adjustDependentFilters(this);ctrl.adjustInvisibleCheckboxes(this);}).on("change",function(e){ctrl.adjustParentFilterCheckbox(this);});if(!this.hasDependent){$("."+this.filterValueBlockContainerClass+"-"+this.gfieldName).on("click",function(e){var $checkbox=$("."+ctrl.checkboxClass,this),checked=$checkbox.prop("checked"),checkbox;if(!$checkbox.length||$checkbox.is(e.target)){return;}
$checkbox.prop("checked",!checked);checkbox=$checkbox.get(0);ctrl.adjustSelectAllCheckbox();ctrl.adjustDependentFilters(checkbox);ctrl.adjustInvisibleCheckboxes(checkbox);$checkbox.trigger("change");});}
this.superclass.initButtons.call(this);},adjustDependentFilters:function(checkbox){this.clearDependentFilters(true);this.adjustDependentFilterCheckboxes(checkbox);},adjustDependentFilterCheckboxes:function(checkbox){if(!this.hasDependent){return;}
var $checkbox=$(checkbox),$filterValueBlock=$checkbox.parent('.'+this.filterValueBlockContainerClass);$('.'+this.commonCheckboxClass,$filterValueBlock).prop('checked',$checkbox.is(':checked'));},adjustParentFilterCheckbox:function(checkbox){if(!this.dependent){return;}
var $checkbox=$(checkbox),$parentFilterValueBlock=$checkbox.parents('.'+this.filterValueBlockContainerClass).eq(1),checked=$checkbox.is(':checked')||$('.'+this.checkboxClass+':checked',$parentFilterValueBlock).length>0;$parentFilterValueBlock.find('.'+this.parentCheckboxClass).prop('checked',checked).trigger('change');},adjustInvisibleCheckboxes:function(checkbox){if(!this.dependent){return}
var $checkbox=$(checkbox),checkboxValue=$checkbox.val(),parentValues=$checkbox.data('parentFiltersValues'),$similarHiddenBoxes=this.checkboxes.not(':visible').filter(function(){var $box=$(this),hiddenParentValues,pName;if($box.val()!==checkboxValue){return false;}
hiddenParentValues=$box.data('parentFiltersValues');for(pName in hiddenParentValues){if(hiddenParentValues[pName]!==parentValues[pName]){return false;}}
return true;});$similarHiddenBoxes.prop('checked',$checkbox.is(':checked')).trigger('change');},setValue:function(arr){this.checkboxes.each(function(index,domCheckbox){var checkbox=$(domCheckbox),pos=$.inArray(checkbox.val(),arr);if(pos!==-1){checkbox.prop('checked',true);arr.splice(pos,1);}});},getValue:function(){var arr=[],i,ctrl=this,$checked=$('.'+this.checkboxClass+':checked'),onDemand=this instanceof Runner.controls.OnDemandFilterControl;if(this.dependent){$checked=$checked.filter(':visible');}
if(this.filtered||this.applyButton.data('activated')||$checked.length!==this.checkboxes.length){$checked.each(function(index,domCheckbox){var $box=$(domCheckbox),values=[$box.val().replace('|','\\|')],parentFiltersValueData,i;if(ctrl.dependent){parentFiltersValueData=$box.data('parentFiltersValues');for(i=0;i<ctrl.parentFilterNames.length;i++){values.push(parentFiltersValueData[ctrl.parentFilterNames[i]].toString().replace('|','\\|'));}}
arr.push(values.join('|'));});}
return arr;},getFilterValue:function(encoded){var arr=this.getValue(),result='';for(i=0;i<arr.length;i++){this.ctrlValue=arr[i];result+=this.superclass.getFilterValue.call(this,encoded);}
return result;},clearControl:function(){this.checkboxes.prop('checked',false);this.selectAllCheckbox.prop('checked',false);},updateValue:function(value){this.checkboxes.prop('checked',false);this.setValue([value]);},isMultiSelected:function(){return true;}});Runner.controls.OnDemandFilterControl=Runner.extend(Runner.controls.FilterControl,{multiSelection:false,checkboxes:[],checkboxClass:'',btnMultiselectClass:"",btnApplyCaption:Runner.lang.constants.TEXT_FILTER_APPLY,superclass:{},multiSelectFCtrl:{},simpleFCtrl:{},filteredValuesClass:"filter-ready-value",valueLinkClass:"",commonCheckboxClass:"multifilter-checkbox",parentCheckboxClass:"",constructor:function(cfg){this.checkboxes=[];Runner.controls.OnDemandFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.superclass=Runner.controls.OnDemandFilterControl.superclass;this.multiSelectFCtrl=Runner.controls.MultiSelectFilterControl.prototype;this.simpleFCtrl=Runner.controls.SimpleFilterControl.prototype;this.btnMultiselectClass='filter-'+(this.dependent?this.goodOutermostParentName:this.gfieldName)+'-btn-multiselect';this.applyButton=$("."+this.btnMultiselectClass);this.checkboxClass='filter_'+this.gfieldName+"_"+this.searchController.id;this.checkboxes=$('.'+this.checkboxClass);this.parentCheckboxClass=this.dependent?'filter_'+this.goodParentName+"_"+this.searchController.id:'';this.selectAllCheckbox=$('.filter-selectAll-'+(this.dependent?this.goodOutermostParentName:this.gfieldName));this.valueLinkClass=this.gfieldName+'-filter-value';this.setValue(this.defaultValuesArray.join(', '));this.initButtons();},adjustSelectAllCheckbox:Runner.controls.MultiSelectFilterControl.prototype.adjustSelectAllCheckbox,adjustDependentFilters:Runner.controls.MultiSelectFilterControl.prototype.adjustDependentFilters,adjustDependentFilterCheckboxes:Runner.controls.MultiSelectFilterControl.prototype.adjustDependentFilterCheckboxes,adjustParentFilterCheckbox:Runner.controls.MultiSelectFilterControl.prototype.adjustParentFilterCheckbox,adjustInvisibleCheckboxes:Runner.emptyFn,initButtons:function(){var ctrl=this,anotherApplyButtonExists=!!$(".filter-apply-"+this.gfieldName).not(this.applyButton).length;if(this.dependent){anotherApplyButtonExists=!!$(".filter-apply-"+this.goodOutermostParentName).not(this.applyButton).length;}
this.applyButton.one("click",function(e){var $button=$(this);if(anotherApplyButtonExists){$button.hide();}
$button.text(ctrl.btnApplyCaption).addClass(ctrl.btnApplyClass).removeClass(ctrl.btnMultiselectClass);$("."+ctrl.valueLinkClass).removeClass(ctrl.valueLinkClass).addClass("multiSelect-"+ctrl.valueLinkClass);$("."+ctrl.filterValueBlockContainerClass+"-"+ctrl.gfieldName,ctrl.filterContainer).removeClass(ctrl.filterLinkClass);ctrl.checkboxes.show();ctrl.addNewValueLinkFunctionality();ctrl.selectAllCheckbox.show();if(!ctrl.dependent||ctrl.filtered){$("."+ctrl.hiddenValuesClass,ctrl.filterContainer).removeClass(ctrl.hiddenValuesClass);$("."+ctrl.filteredValuesClass+".ondemand",ctrl.filterContainer).hide().addClass(ctrl.hiddenValuesClass);}
$(".show-more-hidden",ctrl.filterContainer).removeClass("show-more-hidden");if(ctrl.dependent&&!ctrl.searchController.hasFilteredParentFilter(ctrl.parentFilterNames)){$(".delFilterCtrlButt_"+(ctrl.dependent?ctrl.goodOutermostParentName:ctrl.gfieldName)+"_"+ctrl.searchController.id).hide();}
ctrl.multiSelection=true;return false;});this.simpleFCtrl.initButtons.call(this);this.multiSelectFCtrl.initButtons.call(this);},updateParentFilters:Runner.controls.SimpleFilterControl.prototype.updateParentFilters,addNewValueLinkFunctionality:function(){var newValueLinkClass='multiSelect-'+this.gfieldName+'-filter-value';this.filterPanelContainer.on('click.filters'+this.gfieldName,'.'+newValueLinkClass,function(e){var $link=$(this),linkValue=$link.data('filtervalue')
$checkbox=$link.siblings().filter(function(){return this.value===linkValue;});$checkbox.prop('checked',true);return false;});},getValue:function(){if(this.multiSelection||this.filtered){return this.multiSelectFCtrl.getValue.call(this);}
return this.superclass.getValue.call(this);},getFilterValue:function(encoded){if(this.multiSelection||this.filtered){return this.multiSelectFCtrl.getFilterValue.call(this,encoded);}
return this.superclass.getFilterValue.call(this,encoded);},clearControl:function(){if(this.multiSelection||this.filtered){this.checkboxes.prop('checked',false);this.selectAllCheckbox.prop('checked',false);}
this.setValue('');},clearFilterValue:function(valueToDelete,$container){if(!this.dependent){this.checkboxes.filter(function(){return this.value===valueToDelete;}).prop('checked',false);return;}
this.checkboxes.filter(function(){return!!$container.find(this).length;}).prop('checked',false);if(this.hasDependent){$('.'+this.commonCheckboxClass,$container).prop('checked',false);}},updateValue:function(value){if(this.multiSelection){this.checkboxes.prop('checked',false);this.setValue([value]);}
this.setValue(value);},isMultiSelected:function(){return this.multiSelection;}});Runner.controls.SliderFilterControl=Runner.extend(Runner.controls.FilterControl,{sliderElem:{},range:true,minValue:0,maxValue:0,step:1,knobsType:0,roundedMax:0,roundedMin:0,roundedMaxKnobValue:0,roundedMinKnobValue:0,useApllyBtn:false,constructor:function(cfg){Runner.controls.SliderFilterControl.superclass.constructor.call(this,cfg);},setDefaultValues:function(){this.ctrlValues=[this.minKnobValue,this.maxKnobValue];},getValue:function(){return this.getCaptionValue(this.ctrlValues[0])+" - "+this.getCaptionValue(this.ctrlValues[1]);},init:function(){var jQsliderValues,sliderParams;jQsliderValues=$("#slider_values_"+this.gfieldName);this.jQmax=$(".slider-max",jQsliderValues);this.jQmin=$(".slider-min",jQsliderValues);this.setDefaultValues();this.range=this.getRange();sliderParams=this.getSliderParams();this.sliderElem=$("#slider_"+this.gfieldName).slider(sliderParams);this.setPageMaxZIndex();this.initButtons();},initShowMoreButton:Runner.emptyFn,setPageMaxZIndex:function(){var handleZIndex=parseInt($('.ui-slider-handle',this.sliderElem).css('z-index'),10);Runner.setZindexMax(handleZIndex);},getRange:function(){if(this.knobsType===Runner.controls.constants.FILTER_KNOBS_MIN_ONLY){return'max';}
if(this.knobsType===Runner.controls.constants.FILTER_KNOBS_MAX_ONLY){return'min';}
return true;},getSliderParams:function(){var filter=this,sliderParams={range:this.range,min:this.roundedMin,max:this.roundedMax,step:parseFloat(this.step)},typeBasedParams;typeBasedParams=this.getSliderParamsByType(this.range);Runner.apply(sliderParams,typeBasedParams);if(!this.useApllyBtn){sliderParams.stop=function(){filter.searchController.submitSearch();}}
return sliderParams;},getSliderParamsByType:function(range){var filter=this;switch(this.range){case'min':return{value:parseFloat(this.roundedMaxKnobValue),slide:function(event,ui){filter.processMaxValue(ui.value,$(this).slider("option","min")===ui.value);}};case'max':return{value:parseFloat(this.roundedMinKnobValue),slide:function(event,ui){filter.processMinValue(ui.value,$(this).slider("option","max")===ui.value);}};default:return{values:[parseFloat(this.roundedMinKnobValue),parseFloat(this.roundedMaxKnobValue)],slide:function(event,ui){var oldValues=$(this).slider("values"),min=ui.values[0],max=ui.values[1],oldMin=oldValues[0],oldMax=oldValues[1];if(min!==oldMin){filter.processMinValue(min,min===max);return;}
if(max!==oldMax){filter.processMaxValue(max,min===max);return;}}};}},processMinValue:function(min,minIsEqualToMax){var value=this.getSliderValue(min,true,minIsEqualToMax);this.setMinValue(value);this.setCaptions(value,true);},processMaxValue:function(max,minIsEqualToMax){var value=this.getSliderValue(max,false,minIsEqualToMax);this.setMaxValue(value);this.setCaptions(value,false);},setCaptions:function(value,isLower){var jQmainCaption=isLower?this.jQmin:this.jQmax,caption=this.getCaptionValue(value);jQmainCaption.html(caption);},getSliderValue:function(value,isLower,minIsEqualToMax){if(value===this.roundedMin){return parseFloat(this.minValue);}
if(value===this.roundedMax){return parseFloat(this.maxValue)}
return value;},getCaptionValue:function(value){if(this.viewAsCurrency){return this.getCurrencyFormattedString(value,this.currencySettings);}
if(this.viewAsNumber){return this.getNumberFormattedString(value,this.numberSettings);}
return value;},setMinValue:function(minValue){this.ctrlValues[0]=minValue;},setMaxValue:function(maxValue){this.ctrlValues[1]=maxValue;},getFilterValue:function(encoded){var value,prepFName;if(this.ctrlValues[0]===undefined&&this.ctrlValues[1]===undefined){return'';}
if(!this.filtered){this.prepareControlValues();}
if(this.knobsAreOnTheLimits()){return'';}
value=this.getTypeBasedValue();prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;return"("+prepFName+this.separator+value+")";},getTypeBasedValue:function(encoded){switch(this.range){case'min':return this.getPreparedMaxValue(encoded);case'max':return this.getPreparedMinValue(encoded);default:var valueMin=this.getPreparedMinValue(encoded),valueMax=this.getPreparedMaxValue(encoded);return valueMin+"~"+valueMax;}},getPreparedMinValue:function(encoded){return this.getPreparedValue(this.ctrlValues[0],encoded);},getPreparedMaxValue:function(encoded){return this.getPreparedValue(this.ctrlValues[1],encoded);},prepareControlValues:function(){if(this.ctrlValues[0]===undefined){this.ctrlValues[0]=this.minValue;}
if(this.ctrlValues[1]===undefined){this.ctrlValues[1]=this.maxValue;}},knobsAreOnTheLimits:function(){return this.ctrlValues[0]===this.minValue&&this.ctrlValues[1]===this.maxValue;},getNumberAbsoluteValueFormatted:function(number){var iDigits=this.commonFormatSettings['decimalDigits'],grouping=this.commonFormatSettings["grouping"],ptr,i,outStart,outEnd;number=number.toFixed(iDigits);intPart=number>=0?Math.floor(number):Math.floor(-number);fracPart=number>=0?number-intPart:-number-intPart;out=intPart.toFixed(0);if(grouping.length&&parseInt(grouping[0],10)){ptr=out.toString().length;for(i=0;i<grouping.length;i++){if(!parseInt(grouping[i],10)){i--;}
if(ptr<=grouping[i]){break;}
ptr=ptr-grouping[i];outStart=out.slice(0,ptr);outEnd=out.slice(ptr);out=outStart+this.commonFormatSettings["thousandSep"]+outEnd;}}
if(iDigits>0){fracPart=(fracPart*Math.pow(10,iDigits)).toFixed(0);while(fracPart.length<iDigits){fracPart="0"+fracPart;}
out+=this.commonFormatSettings["decimalSep"]+fracPart;}
return out;},getNumberFormattedString:function(number){var positiveSign=number>=0,numberSettings=this.formatSettings,outString=this.getNumberAbsoluteValueFormatted(number);if(positiveSign||parseInt(outString,10)===0){return numberSettings["LOCALE_SPOSITIVESIGN"]+outString;}
switch(numberSettings["LOCALE_INEGNUMBER"]){case"0":return"("+outString+")";case"1":return"-"+outString;case"2":return"- "+outString;case"3":return outString+"-";case"4":return outString+" -";default:return outString;}},getCurrencyFormattedString:function(number){var positiveSign=number>=0,currencySettings=this.formatSettings,outString=this.getNumberAbsoluteValueFormatted(number);if(positiveSign||parseInt(outString,10)===0){switch(currencySettings["LOCALE_ICURRENCY"]){case"0":return currencySettings["LOCALE_SCURRENCY"]+outString;case"1":case"2":return currencySettings["LOCALE_SCURRENCY"]+" "+outString;case"3":return outString+" "+currencySettings["LOCALE_SCURRENCY"];default:return outString;}}
switch(currencySettings["LOCALE_INEGCURR"]){case"0":return"("+currencySettings["LOCALE_SCURRENCY"]+outString+")";case"1":return"-"+currencySettings["LOCALE_SCURRENCY"]+outString;case"2":return currencySettings["LOCALE_SCURRENCY"]+"-"+outString;case"3":return currencySettings["LOCALE_SCURRENCY"]+outString+"-";case"4":return"("+outString+currencySettings["LOCALE_SCURRENCY"]+")";case"5":return"-"+outString+currencySettings["LOCALE_SCURRENCY"];case"6":return outString+"-"+currencySettings["LOCALE_SCURRENCY"];case"7":return outString+currencySettings["LOCALE_SCURRENCY"]+"-";case"8":return"-"+outString+" "+currencySettings["LOCALE_SCURRENCY"];case"9":return"-"+currencySettings["LOCALE_SCURRENCY"]+" "+outString;case"10":return outString+" "+currencySettings["LOCALE_SCURRENCY"]+"-";case"11":return currencySettings["LOCALE_SCURRENCY"]+" "+outString+"-";case"12":return currencySettings["LOCALE_SCURRENCY"]+" -"+outString;case"13":return outString+"- "+currencySettings["LOCALE_SCURRENCY"];case"14":return"("+currencySettings["LOCALE_SCURRENCY"]+" "+outString+")";case"15":return"("+outString+" "+currencySettings["LOCALE_SCURRENCY"]+")";default:return outString;}},clearControl:function(){this.ctrlValues=[];}});Runner.controls.DateSliderFilterControl=Runner.extend(Runner.controls.SliderFilterControl,{stepType:Runner.controls.constants.FILTER_STEP_DAY,isFieldDateType:true,processWrappers:true,monthNames:[Runner.lang.constants.TEXT_MONTH_JAN,Runner.lang.constants.TEXT_MONTH_FEB,Runner.lang.constants.TEXT_MONTH_MAR,Runner.lang.constants.TEXT_MONTH_APR,Runner.lang.constants.TEXT_MONTH_MAY,Runner.lang.constants.TEXT_MONTH_JUN,Runner.lang.constants.TEXT_MONTH_JUL,Runner.lang.constants.TEXT_MONTH_AUG,Runner.lang.constants.TEXT_MONTH_SEP,Runner.lang.constants.TEXT_MONTH_OCT,Runner.lang.constants.TEXT_MONTH_NOV,Runner.lang.constants.TEXT_MONTH_DEC],constructor:function(cfg){Runner.controls.DateSliderFilterControl.superclass.constructor.call(this,cfg);},setDefaultValues:function(){var minKnob=this.minKnobValue,maxKnob=this.maxKnobValue;if(minKnob){minKnob=this.parseDateTime(minKnob,this.dateFormat);}
if(maxKnob){maxKnob=this.parseDateTime(maxKnob,this.dateFormat);}
this.ctrlValues=[minKnob,maxKnob];},init:function(){var jQsliderValues=$("#slider_values_"+this.gfieldName);this.jQcaptPrefix=$(".slider-caption-prefix",jQsliderValues);this.jQcaptPostfix=$(".slider-caption-postfix",jQsliderValues);this.dateFormat=Runner.pages.PageSettings.getGlobalData("locale").dateFormat;this.dateDelimiter=Runner.pages.PageSettings.getGlobalData("locale").dateDelimiter;this.minDate=this.parseDateTime(this.minValue,this.dateFormat);this.minDateInMs=this.minDate.getTime();this.maxDate=this.parseDateTime(this.maxValue,this.dateFormat);this.maxDateInMs=this.maxDate.getTime();if(this.stepType===Runner.controls.constants.FILTER_STEP_SEC||this.stepType===Runner.controls.constants.FILTER_STEP_MIN){this.realMaxDate=this.parseDateTime(this.realMaxValue,this.dateFormat);this.realMinDate=this.parseDateTime(this.realMinValue,this.dateFormat);}
Runner.controls.DateSliderFilterControl.superclass.init.call(this);},printDateTime:Runner.controls.DateField.prototype.printDateTime,parseDateTime:Runner.controls.DateField.prototype.parseDateTime,getSliderValue:function(value,isLower,minIsEqualToMax){var prepDate=new Date(this.minDateInMs),year,month,day,unitStep;switch(this.stepType){case Runner.controls.constants.FILTER_STEP_SEC:case Runner.controls.constants.FILTER_STEP_MIN:if(value===this.roundedMax){prepDate=this.realMaxDate;break;}
if(value===this.roundedMin){prepDate=this.realMinDate;break;}
prepDate=new Date(this.minDateInMs+value*1000);break;case Runner.controls.constants.FILTER_STEP_MONTH:month=prepDate.getMonth()+value;prepDate.setMonth(month);if(!isLower){prepDate.setDate(prepDate.getDate()-1);}
if(minIsEqualToMax){month=prepDate.getMonth();year=prepDate.getFullYear();month=isLower?month-1:month+2;day=isLower?1:0;prepDate=new Date(year,month,day);}
break;case Runner.controls.constants.FILTER_STEP_YEAR:month=isLower?0:11;day=isLower?1:31
if(value===this.roundedMax){year=this.maxDate.getFullYear();}else{unitStep=parseFloat(this.step)===1;year=prepDate.getFullYear()+value;if(!isLower){year=(minIsEqualToMax||unitStep)?year:year-1;}else{year=(minIsEqualToMax&&!unitStep)?year-1:year;}}
prepDate=new Date(year,month,day);break;default:prepDate=new Date(this.minDateInMs+value*1000);}
return prepDate;},setCaptions:function(prepDate,isLower){Runner.controls.DateSliderFilterControl.superclass.setCaptions.call(this,prepDate,isLower);if(this.processWrappers){this.setWrapperCaption(isLower,prepDate);}},setWrapperCaption:function(isLower,date){this.setCaptionsVisibility(isLower,date);if(!isLower&&this.showTime){this.jQcaptPostfix.html(this.printTime(date));return;}
if(isLower&&this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){this.jQcaptPrefix.html(this.monthNames[date.getMonth()]);}},setCaptionsVisibility:function(isLower,date){var otherKnobDate=isLower?(this.ctrlValues[1]||this.maxDate):(this.ctrlValues[0]||this.minDate),visible;if(this.showTime){visible=this.checkDatesEqual(otherKnobDate,date);this.jQcaptPostfix.toggle(visible);this.jQmax.toggle(!visible);return;}
if(this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){visible=otherKnobDate.getFullYear()===date.getFullYear();this.jQcaptPrefix.toggle(visible);this.jQmin.toggle(!visible);}},checkDatesEqual:function(date1,date2){return date1.getFullYear()===date2.getFullYear()&&date1.getMonth()===date2.getMonth()&&date1.getDate()===date2.getDate();},getCaptionValue:function(date){if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){return date.getFullYear();}
if(this.stepType===Runner.controls.constants.FILTER_STEP_MONTH){return this.monthNames[date.getMonth()]+" "+date.getFullYear();}
return this.printDateTime(date,this.dateFormat,true);},getPreparedMaxValue:function(encoded){var date=this.ctrlValues[1],stringValue=this.getStringValueFromDate(date);return Runner.controls.DateSliderFilterControl.superclass.getPreparedValue.call(this,stringValue,encoded);},getPreparedMinValue:function(encoded){var date=this.ctrlValues[0],stringValue=this.getStringValueFromDate(date);return Runner.controls.DateSliderFilterControl.superclass.getPreparedValue.call(this,stringValue,encoded);},prepareControlValues:function(){var date;if(this.ctrlValues[0]===undefined||this.ctrlValues[0]===null){date=this.realMinDate||this.minDate;if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){date=new Date(date.getFullYear(),0,1);}
this.ctrlValues[0]=date;}
if(this.ctrlValues[1]===undefined||this.ctrlValues[1]===null){date=this.realMaxDate||this.maxDate;if(this.stepType===Runner.controls.constants.FILTER_STEP_YEAR){date=new Date(date.getFullYear(),11,31);}
this.ctrlValues[1]=this.maxDate;}},knobsAreOnTheLimits:function(){if(this.ctrlValues[0].toString()===(this.realMinDate||this.minDate).toString()&&this.ctrlValues[1].toString()===(this.realMaxDate||this.maxDate).toString()){return true;}
return false;},getStringValueFromDate:function(date){var dateString,day=date.getDate(),month=date.getMonth()+1,year=date.getFullYear(),hours,minutes,seconds;dateString=year+'-'+month+'-'+day;if(this.showTime){hours=date.getHours();hours=hours<10?'0'+hours:hours;minutes=date.getMinutes();minutes=minutes<10?'0'+minutes:minutes;seconds=date.getSeconds();seconds=seconds<10?'0'+seconds:seconds;dateString+=' '+hours+':'+minutes+':'+seconds;}
return dateString;},printTime:function(date){var hours=date.getHours(),minutes=date.getMinutes(),seconds=date.getSeconds(),time=this.timeFormat,designator;if(!this.is24hoursFormat){designator=hours>=12?this.designators["pm"]:this.designators["am"];designator=hours>=24?"":designator;time=time.replace("tt",designator);hours=hours>12&&hours<24?hours-12:hours;hours=hours===0?12:hours;hours=this.leadingZero&&hours<10?'0'+hours:hours;time=time.replace(this.leadingZero?"hh":"h",hours);}else{hours=this.leadingZero&&hours<10?'0'+hours:hours;time=time.replace(this.leadingZero?"HH":"H",hours);}
time=time.replace("mm",minutes<10?'0'+minutes:minutes);if(this.showSeconds){time=time.replace("ss",seconds<10?'0'+seconds:seconds);}else{time=time.replace(this.timeDelimiter+"ss","");}
return time;}});Runner.controls.TimeSliderFilterControl=Runner.extend(Runner.controls.DateSliderFilterControl,{TimezoneOffsetInHours:0,isFieldTimeType:true,offsetDaytimeHours:24,processWrappers:false,constructor:function(cfg){Runner.controls.TimeSliderFilterControl.superclass.constructor.call(this,cfg);},init:function(){this.TimezoneOffsetInHours=new Date().getTimezoneOffset()/60;this.offsetDaytimeHours=24+this.TimezoneOffsetInHours;Runner.controls.TimeSliderFilterControl.superclass.init.call(this);},getHoursValue:function(date){var dateInHours=date.getTime()/3600000;if(dateInHours<this.offsetDaytimeHours){return date.getHours();}
return Math.floor(dateInHours-this.TimezoneOffsetInHours);},getStringValueFromDate:function(date){var hours=this.getHoursValue(date),minutes=date.getMinutes(),seconds=date.getSeconds();hours=hours<10?'0'+hours:hours;minutes=minutes<10?'0'+minutes:minutes;seconds=seconds<10?'0'+seconds:seconds;return hours+':'+minutes+':'+seconds;},getCaptionValue:function(date){return this.printTime(date);}});Runner.search.SearchFormWithUI=Runner.extend(Runner.search.SearchForm,{srchOptShowStatus:false,srchWinShowStatus:false,ctrlChooseMenuStatus:false,ctrlTypeComboStatus:false,srchOptExpander:null,srchBlock:null,showAllButton:null,showAllButtStatus:false,srchCtrlsBlock:null,srchBlockStatus:true,ctrlChooseMenuList:null,showOptText:Runner.lang.constants.TEXT_SEARCH_SHOW_OPTIONS,hideOptText:Runner.lang.constants.TEXT_SEARCH_HIDE_OPTIONS,showComboText:Runner.lang.constants.TEXT_SHOW_OPTIONS,hideComboText:Runner.lang.constants.TEXT_HIDE_OPTIONS,searchTypeCombosArr:null,srchFilterRowArr:null,searchFieldsLabels:null,showHideSearchOptionsButton:null,pageObj:null,searchBricks:null,topCritCont:null,clonedContainers:[],constructor:function(cfg){this.srchFilterRowArr=[];this.searchFieldsLabels={};this.searchTypeCombosArr=[];this.searchBricks=['search','vsearch2','searchpanel'];Runner.search.SearchFormWithUI.superclass.constructor.call(this,cfg);this.pageObj=Runner.pages.PageManager.getAt(this.tName,this.id);this.srchOptExpander=$("[id=showOptPanel"+this.id+"]");this.topCritCont=$('.srchCritTop',this.pageObj.pageCont);this.srchBlock=$("#search_block"+this.id);this.srchCtrlsBlock=$(".controlsBlock",this.pageObj.pageCont);this.showAllButton=$("[id=showAll"+this.id+"]");this.showHideSearchOptionsButton=$('#showHideSearchType'+this.id);this.addSearchFieldButton=$("#showHideControlChooseMenu"+this.id);this.showAllButtStatus=this.usedSrch;this.initCtrlChooseMenu();if(this.pageObj.isBootstrap()){this.initCtrlPanelOptions();}},initCtrlPanelOptions:function(){var self=this,panelOptions=$("#searchPanelOptions"+this.id);$(".close-button",panelOptions).on("click",function(e){self.toggleSearchOptions();});Runner.util.dropPositionSet(panelOptions.find(".dropdown-toggle"));},initCtrlChooseMenu:function(){if(this.ctrlChooseMenuList&&!this.ctrlChooseMenuList.length){return;}
var list=$('<ul class="list-group rnr-list controlChooseMenu"></ul>'),controller=this,i,li,fName;if(this.pageObj.isBootstrap()){list.addClass("dropdown-menu");}
for(i=0;i<this.fNamesArr.length;i++){li=$('<li></li>').appendTo(list);if(!this.pageObj.isBootstrap()){li.addClass("list-group-item");}
fName=this.fNamesArr[i];$('<a href="#" class="rnr-button link" >'+this.searchFieldsLabels[fName]+'</a>').attr("id","addSearchControl_"+fName).appendTo(li).bind("click touchend",{fName:fName},function(e){controller.addFilter(e.data.fName);e.preventDefault();if(!controller.pageObj.isBootstrap()){controller.hideCtrlChooseMenu();controller.addSearchFieldButton.parent().addClass("hiddenButtonGroup");return false;}});}
this.ctrlChooseMenuList=list.insertAfter(this.addSearchFieldButton);Runner.util.dropPositionSet(this.addSearchFieldButton);},getComboContId:function(fName,ind){return"searchType_"+ind+"_"+Runner.goodFieldName(fName);},getComboId:function(fName,id){return"srchOpt_"+id+"_"+Runner.goodFieldName(fName);},showSearchWin:function(e){this.hideCtrlChooseMenu();this.pageObj.hideBrick("search_buttons");this.pageObj.hideBrick("vsearch1");var x=e?(e.x||e.pageX):50,y=e?(e.y||e.pageY):50,width=(e&&e.w)?e.w:400,height=(e&&e.h)?e.h:(Runner.isIE?200:0),$window,windowWidth,windowHeight,args,diffWidth,diffHeight;if(e){$window=$(window);windowWidth=$window.width();windowHeight=$window.height();diffWidth=windowWidth-width;diffHeight=windowHeight-height;x=diffWidth<x?diffWidth-15:x;y=diffHeight<y?diffHeight-15:y;if(x<0){x=0;width=400;}
if(y<0){y=0;height=windowHeight;}}
args={xy:[x,y],width:width,headerContent:'<span style="color: white;">'+Runner.lang.constants.SEARCH_FOR+'</span>'
+'<span style="position:absolute; top:2px; right:23px;">'
+'<a id="pinSrchWin'+this.pageObj.id+'" class="rnr-button img" href="#" data-icon="panelunfloat" title="Floating window" >'
+'</a></span>'};if(height){args.height=height;}
Runner.pages.PageManager.createFlyWin.call(this,args,false,$.proxy(this.afterCreateSearchFlyWinHandler,this));},afterCreateSearchFlyWinHandler:function(win){if(!win){return;}
win=win._obj;var searchFormObj=this;this.win=win;this.getBricksFromParent(win);this.srchWinShowStatus=true;this.showSearchOptions();this.initWinDelButtons(win);$("[id='pinSrchWin"+this.pageObj.id+"']").bind("click",function(e){searchFormObj.hideSearchWin(win);searchFormObj.showSearchOptions();return false;});$(win.getButton("close").getDOMNode()).on('click',function(e){searchFormObj.hideSearchWin(win);});win.publish("searchFieldsNumberChanged");win.on("searchFieldsNumberChanged",function(){Runner.pages.RunnerPage.prototype.adjustPopWindowHeightByContent.call(searchFormObj,"rnr-flycontainer")});Runner.pages.PageManager.correctYUIWindowSize(win,false,this);},initWinDelButtons:function(win){$(win.bodyNode.getDOMNode()).bind('click',{srchController:this},this.delButtonHandler);},hideSearchControllerContainers:function(){this.pageObj.hideSearchControllerContainers();},addCtrlsHtml:function(fName,ind,blockHTML){this.addPanelHtml(fName,ind,blockHTML);var rowCont=$('#'+this.getFilterRowId(fName,ind,this.srchWinShowStatus)),cells=rowCont.children(),cellHTML='<div class="rnr-searchtype">'+blockHTML.comboHtml+'</div>'
+'<div class="rnr-searchcontrol">'+blockHTML.control1+'</div>'
+'<div class="rnr-searchcontrol">'+blockHTML.control2+'</div>';if(this.pageObj.isBootstrap()){rowCont.append(cellHTML);}else if(!Runner.isMobile){cells.eq(0).html(blockHTML.delButt);cells.eq(2).html(cellHTML);}else{cells.eq(1).html(cellHTML);}},getBricksFromParent:function(win){var bricksObjs=this.pageObj.getBricksObjs(this.searchBricks),_self=this,newContents=$("<div class='rnr-flycontainer'></div>"),brickName;this.clonedContainers=[];for(brickName in bricksObjs){$.each(bricksObjs[brickName],function(index,_brick){var alreadyCloned,clonedCont;alreadyCloned=$.grep(_self.clonedContainers,function(n,i){return n.source.is(_brick.contObj);});if(!alreadyCloned.length){clonedCont=_brick.contObj.cloneEmpty();_self.clonedContainers.push({source:_brick.contObj,clone:clonedCont,bricks:[_brick]});}else{clonedCont=alreadyCloned[0].clone;alreadyCloned[0].bricks.push(_brick);}
_brick.moveTo(clonedCont);_brick.show();});}
$.each(_self.clonedContainers,function(index,container){container.clone.appendTo(newContents);});win.set("bodyContent",newContents.get(0));},setBricksToParent:function(win){$.each(this.clonedContainers,function(index,container){var source=container.source;$.each(container.bricks,function(index,brick){brick.moveTo(source);});});win.set("bodyContent","");},toggleShowAll:function(toggler){toggler?this.showShowAll():this.hideShowAll();},hideShowAll:function(){Runner.hideButton(this.showAllButton);this.showAllButtStatus=false;},showShowAll:function(){Runner.showButton(this.showAllButton);this.showAllButton.parent().show();this.showAllButtStatus=true;},hideSearchWin:function(win){this.setBricksToParent(win);this.hideCtrlChooseMenu();this.hideSearchOptions();this.pageObj.showBrick("search_buttons");this.pageObj.showBrick("vsearch1");this.pageObj.destroyWin.call(this);this.srchWinShowStatus=false;},showSearchBlock:function(){this.srchBlock.show();this.srchBlockStatus=true;},hideSearchBlock:function(){this.srchBlock.hide();this.srchBlockStatus=false;},toggleSearchBlock:function(){this.srchBlockStatus&&!this.srchWinShowStatus?this.hideSearchBlock():this.showSearchBlock();},showSearchOptions:function(){this.pageObj.showBrick('searchpanel');this.srchOptShowStatus=true;this.changePanelExpanderState();this.recalculationGridSize();},hideSearchOptions:function(){this.pageObj.hideBrick('searchpanel');$('.rnr-datepicker').hide();this.srchOptShowStatus=false;this.changePanelExpanderState();this.recalculationGridSize();},changePanelExpanderState:function(){if(!this.srchOptShowStatus){if(this.pageObj.isBootstrap()){this.srchOptExpander.removeClass("active").attr("title",Runner.lang.constants.TEXT_SHOW_SEARCH_PANEL).html(Runner.lang.constants.TEXT_SHOW_SEARCH_PANEL);}else{this.srchOptExpander.attr('title',this.showOptText).attr("data-icon","paneldown");}}
else{if(this.pageObj.isBootstrap()){this.srchOptExpander.addClass("active").attr("title",Runner.lang.constants.TEXT_HIDE_SEARCH_PANEL).html(Runner.lang.constants.TEXT_HIDE_SEARCH_PANEL);}else{this.srchOptExpander.attr("title",this.hideOptText).attr("data-icon","panelup");}}},toggleSearchOptions:function(){this.srchOptShowStatus&&!this.srchWinShowStatus&&!this.isSearchPanelInflexible?this.hideSearchOptions():this.showSearchOptions();this.hideCtrlChooseMenu();},showCtrlChooseMenu:function(){return;if(!this.ctrlChooseMenuList||!this.ctrlChooseMenuList.length){this.initCtrlChooseMenu();}
var controller=this,hideHandler=function(){controller.hideCtrlChooseMenu();},showHandler=function(){controller.showCtrlChooseMenu();};this.showTask=new Runner.util.DelayedTask(showHandler);this.hideTask=new Runner.util.DelayedTask(hideHandler);this.ctrlChooseMenuList.bind('mouseover',function(e){controller.hideTask.cancel();controller.showTask.delay(50,showHandler,null,[e]);}).bind('mouseout',function(e){controller.showTask.cancel();controller.hideTask.delay(50,hideHandler,null,[e]);});this.showCtrlChooseMenu=function(){var buttonPosition=this.addSearchFieldButton.offset();this.hideTask.cancel();this.ctrlChooseMenuList.css({'top':buttonPosition.top+this.addSearchFieldButton.outerHeight()+'px','left':buttonPosition.left+(Runner.isDirRTL()?this.addSearchFieldButton.outerWidth()-this.ctrlChooseMenuList.outerWidth():0)+'px'}).show();if(this.ctrlChooseMenuList.width()<this.addSearchFieldButton.width()){this.ctrlChooseMenuList.width(this.addSearchFieldButton.width());}
Runner.setZindexMaxToElem(this.ctrlChooseMenuList);this.ctrlChooseMenuStatus=true;}
this.showCtrlChooseMenu();},hideCtrlChooseMenu:function(){var _self=this;if(!this.ctrlChooseMenuList||!this.ctrlChooseMenuList.length){this.initCtrlChooseMenu();}
this.ctrlChooseMenuList.hide();this.pageObj.resetButtonGroupDisplayStyle(this.ctrlChooseMenuList);this.ctrlChooseMenuStatus=false;},toggleCtrlChooseMenu:function(){this.ctrlChooseMenuStatus?this.hideCtrlChooseMenu():this.showCtrlChooseMenu();},showCtrlTypeCombo:function(){this.toggleSearchControlsOptionsCombo(true);},hideCtrlTypeCombo:function(){this.toggleSearchControlsOptionsCombo(false);},toggleSearchControlsOptionsCombo:function(toggler){var $select,selectValue;for(var i=0;i<this.searchTypeCombosArr.length;i++){$select=this.searchTypeCombosArr[i].find('select');selectValue=$select.val();if(selectValue==='Empty'||selectValue==='NOT Empty'){this.updateControlSearchOptionsCombo($select,toggler);$select.val(selectValue);continue;}
this.searchTypeCombosArr[i].toggle(toggler);$select.toggle(toggler);}
if(this.pageObj.isBootstrap()){this.showHideSearchOptionsButton.find("a").html(toggler?this.hideComboText:this.showComboText);this.showHideSearchOptionsButton.find("a").attr('title',toggler?this.hideComboText:this.showComboText);}
else{this.showHideSearchOptionsButton.html(toggler?this.hideComboText:this.showComboText);this.showHideSearchOptionsButton.attr('title',toggler?this.hideComboText:this.showComboText);}
this.ctrlTypeComboStatus=toggler;},updateControlSearchOptionsCombo:function($select,toggler){var $options=$select.find('option'),$emptyOptions;if(!toggler&&$options.not("[value='Empty'],[value='NOT Empty']").length){$select.data("options",$options.clone());$emptyOptions=$select.find("option[value='Empty'], option[value='NOT Empty']").clone();$options.remove();$select.append($emptyOptions);return;}
if(toggler&&$select.data("options")){$options.remove();$select.append($select.data("options"));$select.data("options",null);}},toggleCtrlTypeCombo:function(){this.toggleSearchControlsOptionsCombo(!this.ctrlTypeComboStatus);},toggleSearchButtonsState:function(ctrlsCount){var topCriteriaController=this.topCritCont,optionsButton=this.showHideSearchOptionsButton,bottomSearchButt=$('.bottomSearchButt',this.pageObj.pageCont),controlsBlock=$('.controlsBlock',this.pageObj.pageCont);this.toggleSearchButtonsState=function(ctrlsCount){topCriteriaController.toggle(ctrlsCount>1);bottomSearchButt.toggle(ctrlsCount>0);optionsButton.toggle(ctrlsCount>0);if(this.pageObj.isBootstrap()){controlsBlock.toggle(ctrlsCount>0);}}
this.toggleSearchButtonsState(ctrlsCount);},recalculationGridSize:function(){if(Runner.isBootstrap()){return;}
var scrollGridBody=this.pageObj.isScrollGridBody,recsPerRowList=this.pageObj.recsPerRowList,baseCalssPref=this.pageObj.oldLayout?"runner-":"rnr-",footer,bottomRow,newTheadHeight,scrollGridHeight,footerHeight,bottomHeight;if(!scrollGridBody||recsPerRowList>1){return;}
newTheadHeight=$('thead tr th',this.pageObj.gridElem).height();if(newTheadHeight==this.pageObj.gridElem.data('theadheight')){return;}
scrollGridHeight=$("."+baseCalssPref+"scrollgrid-inner").height();footer=$('tr.footer td',this.pageObj.gridElem);bottomRow=$('.'+baseCalssPref+'bottomrow',this.pageObj.gridElem);footerHeight=footer.height();bottomHeight=bottomRow.height();footer.css("top",(scrollGridHeight+newTheadHeight-footerHeight-bottomHeight)+"px");bottomRow.css("top",(scrollGridHeight+newTheadHeight-bottomHeight)+"px");this.pageObj.gridElem.closest("."+baseCalssPref+"scrollgrid-wrap").css('padding',newTheadHeight+'px 0 0');this.pageObj.gridElem.data('theadheight',newTheadHeight);}});Runner.search.SearchController=Runner.extend(Runner.search.SearchFormWithUI,{ajaxSearchUrl:"",styleDispNoneText:'display: none;',simpleSearchActive:false,isSearchPanelInflexible:false,panelSearchFields:[],searchPanelRunByUserApi:false,inflexSearchOptions:{},searchTableName:"",filterContolsData:[],filterControls:[],submitTimeout:null,resetButton:null,constructor:function(cfg){Runner.search.SearchController.superclass.constructor.call(this,cfg);this.ajaxSearchUrl=Runner.getPageUrl(this.shortTName,"search");this.simpleSearchActive=Runner.pages.PageSettings.getTableData(cfg.tName,"simpleSearchActive");},init:function(ctrlsBlocks){Runner.search.SearchController.superclass.init.call(this,ctrlsBlocks);this.initFastSearch();this.initFilters();this.remindSearchPanelState();this.savePanelsStateBeforeUnload();},savePanelsStateBeforeUnload:function(){var serachController=this;$(window).on('beforeunload',function(){serachController.rememberSearchPanelState();serachController.rememberFilterPanelState();});},initFastSearch:function(){var searchController=this;this.smplSrchBox.on('keyup',function(e){if(Runner.isMobile||!Runner.isAcceptableKeyCode(e)){return;}
if(searchController.submitTimeout){clearTimeout(searchController.submitTimeout);}
var srchBoxObj=this;searchController.submitTimeout=setTimeout(function(){if(searchController.useSuggest){searchSuggest(e,srchBoxObj,'ordinary',Runner.getPageUrl('searchsuggest','','table='+searchController.shortTName),1);}},500);}).on('keydown',function(e){searchController.listenEvent(e,this);});},initButtons:function(){var searchController=this;Runner.search.SearchController.superclass.initButtons.call(this);$("#searchButtTop"+this.id).bind("click",function(e){searchController.submitSearch();return false;});this.resetButton=$("[id=clearSearch"+this.id+"]").on("click",function(e){searchController.clearSearch();return false;});this.initShowHideToggler();$("#showSrchWin"+this.id).bind("click",function(e){searchController.showSearchWin(e);return false;});if(!this.pageObj.isBootstrap()){this.addSearchFieldButton.on("click",function(e){$(this).parent().removeClass("hiddenButtonGroup");return false;}).on("mouseenter",function(){$(this).parent().removeClass("hiddenButtonGroup");});}
this.showHideSearchOptionsButton.on("click",function(e){searchController.toggleCtrlTypeCombo();$(this).parent().click();return false;});this.showAllButton.on("click",function(e){searchController.showAllSubmit();return false;});this.initSearchButton();this.initDelButtons();},initShowHideToggler:function(){var searchController=this;$("#showOptPanel"+this.id).bind("click",function(e){$(this).parent().click();searchController.toggleSearchOptions();if(searchController.getVisibleBlocksCount()===0){$("#showHideControlChooseMenu"+searchController.id).next().find("a:first").click();}
return false;});},toggleResetButton:function(toggler){toggler?this.showResetButton():this.hideResetButton();},hideResetButton:function(){Runner.hideButton(this.resetButton);},showResetButton:function(){Runner.showButton(this.resetButton);this.resetButton.parent().show();},initSearchButton:function(){var searchController=this;this.searchButton.bind("click",function(e){if(!Runner.isDisabledButton(this)){searchController.submitSearch();}
return false;});},initDelButtons:function(){this.srchCtrlsBlock.bind('click touchend',{srchController:this},this.delButtonHandler);},delButtonHandler:function(e){var srchController=e.data.srchController,$target=$(e.target).closest(".searchPanelButton"),fName=$target.attr("fName"),ctrlId,i;if(!$target.length||!fName){return;}
ctrlId=parseInt($target.attr("ctrlId"),10);for(i=0;i<srchController.fNamesArr.length;i++){if(fName==Runner.goodFieldName(srchController.fNamesArr[i])){fName=srchController.fNamesArr[i];break;}}
srchController.delCtrl(fName,ctrlId);return false;},getTheFirstSearchControlValue:function(){var i,fName,searchFields;if(this.simpleSearchActive){return this.smplSrchBox.val();}
for(i=0;i<this.filterControls.length;i++){if(this.filterControls[i].filtered){return this.filterControls[i].getDisplayedValue();}}
for(fName in this.searchFields){searchFields=this.searchFields[fName];for(i=0;i<searchFields.length;i++){if(searchFields[i].checkIfCtrlsValuesSet()){return searchFields[i].getControl().getStringValue();}}}
return"search";},getLastAddedInd:function(filterName){if(!this.ctrlsShowMap[filterName]){return 0;}
var maxInd=0,beforeMaxInd=0,i=0,ind;for(ind in this.ctrlsShowMap[filterName]){ind=parseInt(ind,10);if(maxInd<ind){beforeMaxInd=maxInd;maxInd=ind;}
if(i===0){beforeMaxInd=maxInd;}
i++;}
return beforeMaxInd;},getLastAddedRow:function(filterName){var beforeMaxInd=this.getLastAddedInd(filterName),$filterObj;if(!beforeMaxInd){return null;}
$filterObj=$('#'+this.getFilterRowId(filterName,beforeMaxInd));return!!$filterObj.length?$filterObj:null;},addPanelHtml:function(fName,ind,blockHTML){var newSrchCtrlContId=this.getFilterRowId(fName,ind),filterRowHtml=this.createTableRow(newSrchCtrlContId,'srchPanelRow',this.styleDispNoneText,''),newSrchCtrlCont,fNameCellHtml,comboHtml;this.srchCtrlsBlock.append(filterRowHtml);newSrchCtrlCont=$("#"+newSrchCtrlContId);if(this.pageObj.isBootstrap()){newSrchCtrlCont.append('<label>'+blockHTML.fLabel+'</label>'+blockHTML.delButt);}else{if(!Runner.isMobile){newSrchCtrlCont.append(this.createTableCell('srchPanelCell','',''));fNameCellHtml=this.createTableCell('srchPanelCell','',blockHTML.fLabel+':&nbsp;');}else{fNameCellHtml=this.createTableCell('srchPanelCell','',blockHTML.delButt+'&nbsp;'+blockHTML.fLabel+':&nbsp;');}
newSrchCtrlCont.append(fNameCellHtml);comboHtml=this.createTableCell('srchPanelCell srchPanelCell2',(this.ctrlTypeComboStatus?'':this.styleDispNoneText),'');newSrchCtrlCont.append(comboHtml);}
return newSrchCtrlCont;},addRegCtrlsBlock:function(fName,ind,ctrlIndArr,blockHTML){if(blockHTML){this.addCtrlsHtml(fName,ind,blockHTML);}
Runner.search.SearchController.superclass.addRegCtrlsBlock.call(this,fName,ind,ctrlIndArr);this.searchTypeCombosArr.push($("#"+this.getComboContId(fName,ind)));this.srchFilterRowArr.push($("#"+this.getFilterRowId(fName,ind)));this.toggleSearchButtonsState(this.getVisibleBlocksCount());},createTableRow:function(id,cssClass,style,innerHtml){if(this.pageObj.isBootstrap()){return'<div class="'+cssClass+' form-group" id="'+id+'" style="'+style+'">'+innerHtml+'</div>';}
if(!Runner.isMobile){return'<tr class="'+cssClass+'" id="'+id+'" style="'+style+'">'+innerHtml+'</tr>';}
return'<div class="'+cssClass+'" id="'+id+'" style="'+style+'">'+innerHtml+'</div>';},createTableCell:function(cssClass,style,innerHtml){if(!Runner.isMobile){return'<td class="'+cssClass+'" style="'+style+'">'+innerHtml+'</td>';}
return'<div class="'+cssClass+'" style="'+style+'">'+innerHtml+'</div>';},putCachedBlock:function(filterName,cachedInd,parentFieldNames){var cachedRowId=this.getFilterRowId(filterName,cachedInd),$cachedRow=$("#"+cachedRowId),$lastAddedRow,$lastAddedParentRow,i;parentFieldNames=parentFieldNames||[];for(i=0;i<parentFieldNames.length;i++){$lastAddedParentRow=this.getLastAddedRow(parentFieldNames[i]);if($lastAddedParentRow){$cachedRow.insertAfter($lastAddedParentRow);$cachedRow.show();return;}}
$lastAddedRow=this.getLastAddedRow(filterName);if($lastAddedRow&&$lastAddedRow.attr("id")!==cachedRowId){$cachedRow.insertBefore($lastAddedRow);}else{this.srchCtrlsBlock.prepend($cachedRow);}
$cachedRow.show();},createLoadingBox:function(filterName){var loadTr=$('<tr>').addClass('srchPanelRow'),loadTd=$('<td>');loadTd.attr('colspan','3').addClass('cellBorderRightHovered').addClass('cellBorderLeftHovered').addClass('cellBorderCenterHovered').html('&nbsp;&nbsp;'+filterName+':&nbsp;loading&nbsp;...&nbsp;').appendTo(loadTr);return loadTr;},putLoadingBox:function(loadBox,filterName){var $lastAddedRow=this.getLastAddedRow(filterName);if($lastAddedRow){loadBox.insertBefore($lastAddedRow);}else{this.srchCtrlsBlock.append(loadBox);}},setDependencies:function(ctrl,triggerReload){var parentFNames,parentFData,i,parentFName,parentInd;if(ctrl.cached||!ctrl.hasDependencies()){return;}
parentFData={};parentFNames=ctrl.getParentLookupFieldNames();for(i=0;i<parentFNames.length;i++){parentFName=parentFNames[i];if(!this.ctrlsShowMap[parentFName]){continue;}
parentInd=this.getLastAddedInd(parentFName);if(!this.ctrlsShowMap[parentFName][parentInd]){continue;}
parentFData[parentFName]={rowId:parentInd,ctrlIndex:this.ctrlsShowMap[parentFName][parentInd][0]}}
ctrl.setDependencies(this.tName,0,parentFData);},getShownFilterNames:function(){var fNamesArr=[],fName,ind;for(fName in this.ctrlsShowMap){for(ind in this.ctrlsShowMap[fName]){ind=parseInt(ind,10);if(this.isFieldShownById(fName,ind)){fNamesArr.push(fName);}}}
return fNamesArr;},showCached:function(filterName){if(!this.ctrlsShowMap[filterName]){return false;}
var cachedInd,ind,cachedCtrlIndArr,firstCtrlFromCache;for(ind in this.ctrlsShowMap[filterName]){ind=parseInt(ind,10);if(!this.isFieldShownById(filterName,ind)){cachedInd=ind;break;}}
if(cachedInd===undefined){return false;}
cachedCtrlIndArr=this.ctrlsShowMap[filterName][cachedInd];firstCtrlFromCache=Runner.controls.ControlManager.getAt(this.tName,cachedInd,filterName,cachedCtrlIndArr[0]);firstCtrlFromCache.cached=false;if(!firstCtrlFromCache.hidden){firstCtrlFromCache.show();}
this.setDependencies(firstCtrlFromCache,true);this.putCachedBlock(filterName,cachedInd,firstCtrlFromCache.parentFieldNames);if(this.ctrlTypeComboStatus){$("#"+this.getComboContId(filterName,cachedInd)).show();}
if(!this.srchWinShowStatus&&!Runner.isMobile){firstCtrlFromCache.setFocus();}
return firstCtrlFromCache;},addFilter:function(filterName,userCallBack){var isShown=!!this.showCached(filterName),controller=this,$loadBox,ajaxParams;if(!isShown){$loadBox=this.createLoadingBox(filterName);this.putLoadingBox($loadBox,filterName);}else{this.toggleSearchControlsOptionsCombo(this.ctrlTypeComboStatus);}
ajaxParams={isNeedSettings:true,searchControllerId:this.id,mode:"inlineLoadCtrl",layoutVersion:this.pageObj.layoutVersion,ctrlField:filterName,id:Runner.genId()};Runner.runnerAJAX(this.ajaxSearchUrl,ajaxParams,function(ctrlJSON,queryStatus){var i,ctrl,ind,sFInd,firstCtrlFromCache;controller.addRegCtrlsBlock(filterName,ctrlJSON.divInd,(ctrlJSON.control2?[0,1]:[0]),ctrlJSON);if(ctrlJSON.settings){Runner.pages.PageSettings.addSettings(controller.searchTableName,ctrlJSON.settings);}
for(i=0;i<ctrlJSON.ctrlMap.length;i++){ctrlJSON.ctrlMap[i].cached=isShown;ctrl=Runner.controls.ControlFactory(ctrlJSON.ctrlMap[i],controller.pageType,false,controller.pageObj);controller.initSearchField(ctrl);}
if(!isShown){firstCtrlFromCache=controller.showCached(filterName);$loadBox.remove();controller.toggleSearchButtonsState(controller.getVisibleBlocksCount());controller.toggleSearchControlsOptionsCombo(controller.ctrlTypeComboStatus);}
$(".srchPanelCell2").show();if(!controller.isFieldShownById(filterName,ctrlJSON.divInd)){ind=controller.getLastAddedInd(filterName);controller.addSearchField(filterName,ind);}
if(firstCtrlFromCache&&!controller.srchWinShowStatus&&!Runner.isMobile){firstCtrlFromCache.setFocus();}
if(typeof userCallBack==='function'){sFInd=controller.searchFields[filterName].length-1;userCallBack(controller.searchFields[filterName][sFInd]);}
if(controller.win){controller.win.fire("searchFieldsNumberChanged");}});},addFilterInNumber:function(filterName,number,userCallBack){for(var i=0;i<number;i++){this.addFilter(filterName,userCallBack);}},isFieldShownById:function(fName,id){var fieldId=this.getFilterRowId(fName,id);return $("#"+fieldId).is(":visible");},delCtrl:function(fName,ctrlId){var ctrlsShowMap=this.ctrlsShowMap[fName][ctrlId],ctrl,i;for(i=0;i<ctrlsShowMap.length;i++){ctrl=Runner.controls.ControlManager.getAt(this.tName,ctrlId,fName,ctrlsShowMap[i]);if(ctrl.isLookupWizard()){ctrl.clearChildrenLinks(true);}
Runner.controls.ControlStorage.unregister(ctrlId,fName,ctrlsShowMap[i]);}
this.removeComboById(this.getComboContId(fName,ctrlId));this.removeFilterById(this.getFilterRowId(fName,ctrlId));if(this.win){this.win.fire("searchFieldsNumberChanged");}
this.toggleSearchButtonsState(this.getVisibleBlocksCount());delete this.ctrlsShowMap[fName][ctrlId];if(this.useSuggest){DestroySuggestDiv();}
for(i=0;i<this.searchFields[fName].length;i++){if(parseInt(this.searchFields[fName][i].id,10)===ctrlId){this.searchFields[fName].splice(i,1);break;}}
this.toggleSearhButtonStatus();},removeFilterById:function(id){var controller=this;$.each(this.srchFilterRowArr,function(idx,$elem){if($elem.attr('id')===id){$elem.remove();controller.srchFilterRowArr.splice(idx,1);return false;}});},removeComboById:function(id){var controller=this;$.each(this.searchTypeCombosArr,function(idx,$elem){if($elem.attr('id')==id){controller.searchTypeCombosArr.splice(idx,1);return false;}});},getVisibleBlocksCount:function(){var visCount=0,rowArr=this.srchFilterRowArr,i;for(i=0;i<rowArr.length;i++){if(rowArr[i].css('display')!=='none'){visCount++;}}
return visCount;},resetCtrls:function(){var objIndForCM,fName,ind,i,ctrl;for(fName in this.ctrlsShowMap){for(ind in this.ctrlsShowMap[fName]){for(i=0;i<this.ctrlsShowMap[fName][ind].length;i++){objIndForCM=this.ctrlsShowMap[fName][ind][i];ctrl=Runner.controls.ControlManager.getAt(this.tName,this.id,fName,objIndForCM);ctrl.reset();}}}
return false;},rememberSearchPanelState:function(){var searchPanelString=localStorage.getItem('searchPanel'),panelStateObj={srchPanelOpen:this.srchOptShowStatus,srchCtrlComboOpen:this.ctrlTypeComboStatus,srchWinOpen:this.srchWinShowStatus,openFilters:[]},searchPanel={},widgetBox;if(this.srchWinShowStatus){this.win.syncXY();widgetBox=$(this.win.get('boundingBox').getDOMNode());panelStateObj.winState={x:this.win.get("x"),y:this.win.get("y"),h:widgetBox.height(),w:widgetBox.width()-18};}
if(!this.usedSrch){panelStateObj.openFilters=this.getShownFilterNames();}
if(searchPanelString){searchPanel=JSON.parse(searchPanelString);}
searchPanel['panelState_'+this.shortTName+'_'+this.id]=panelStateObj;localStorage.setItem('searchPanel',JSON.stringify(searchPanel));},remindSearchPanelState:function(){var panelStateString=localStorage.getItem('searchPanel'),panelStateObj,searchPanel;if(panelStateString){searchPanel=JSON.parse(panelStateString);panelStateObj=searchPanel['panelState_'+this.shortTName+'_'+this.id];}
if(!panelStateObj&&!this.searchPanelRunByUserApi){if(this.panelSearchFields.length){this.showSearchOptions();}
return;}
if(!this.isSearchPanelInflexible){if(panelStateObj&&panelStateObj.srchWinOpen&&this.isWinStateCorrect(panelStateObj.winState)){this.hideSearchOptions();this.showSearchWin(panelStateObj.winState);}else if(panelStateObj&&panelStateObj.srchPanelOpen||this.searchPanelRunByUserApi){this.showSearchOptions();}}
else{this.showSearchOptions();}
if(panelStateObj&&panelStateObj.srchCtrlComboOpen){this.showCtrlTypeCombo();return;}
this.hideCtrlTypeCombo();},isWinStateCorrect:function(winState){if(!winState||winState.x===undefined||winState.y===undefined||!winState.w||!winState.h){return false;}
return true;},getFieldIds:function(fName,disp){var idsArr=[],id;if(this.ctrlsShowMap[fName]){for(id in this.ctrlsShowMap[fName]){if(disp!==true||this.isFieldShownById(fName,id)){idsArr.push(id);}}}
return idsArr;},getSearchFields:function(fName){var allFields,i,j,fName;if(typeof fName!=='undefined'){return this.searchFields[fName];}
allFields=[];for(i=this.fNamesArr.length;i--;){fName=this.fNamesArr[i];for(j=0;j<this.searchFields[fName].length;j++){allFields.push(this.searchFields[fName][j]);}}
return allFields;},addField:function(fName,callback){if(!fName){return;}
this.addFilter(fName,callback);},deleteField:function(fName,id){if(!fName){return;}
if(typeof id!=='undefined'){this.delCtrl(fName,id);return;}
var ids=this.getFieldIds(fName,true);for(var i=0;i<ids.length;i++){this.delCtrl(fName,ids[i]);}
this.searchFields[fName]=[];},clear:function(){var shownFields=this.getShownFilterNames();for(var i=0;i<shownFields.length;i++){this.deleteField(shownFields[i]);}},display:function(as){switch(as){case"show":if(!this.srchWinShowStatus){this.showSearchOptions();}else{this.hideSearchWin();}
break;case"hide":if(this.srchWinShowStatus){this.hideSearchWin();}
this.hideSearchOptions();break;case"popup":this.showSearchWin();break;}},toggleOptions:function(as){switch(as){case"show":this.showCtrlTypeCombo();break;case"hide":this.hideCtrlTypeCombo();break;}},toggleCriteria:function(as){switch(as){case"all":$('#all_checkbox',this.pageObj.pageCont).prop('checked',true);break;case"any":$('#any_checkbox',this.pageObj.pageCont).prop('checked',true);break;case"show":this.topCritCont.show();break;case"hide":this.topCritCont.hide();break;}},getInflexSearchOption:function(fName){return this.inflexSearchOptions[fName];},clearSearchPanel:function(){var fName,i,fSearchFields,defaultOption;for(fName in this.searchFields){fSearchFields=this.searchFields[fName];defaultOption=this.isSearchPanelInflexible?this.getInflexSearchOption(fName):Runner.lang.constants.CONTAINS;for(i=0;i<fSearchFields.length;i++){fSearchFields[i].clearFieldCtrls();fSearchFields[i].setOption(defaultOption);}}
this.toggleCriteria("all");},clearSearch:function(){this.clearSearchPanel();this.clearSimpleSearch();},initSearchField:function(ctrl){if(!ctrl){return;}
Runner.search.SearchController.superclass.initSearchField.call(this,ctrl);this.setDependencies(ctrl);},isTableSearchable:function(){return this.tName===this.searchTableName;},initFilters:function(){this.initFilterControls();this.adjustExpanderSigns();this.updateFilterPanelVisibility();},initFilterControls:function(){var i,filterControl;for(i=0;i<this.filterControls.length;i++){this.filterControls[i].destructor();}
this.filterControls=[];for(i=0;i<this.filterContolsData.length;i++){filterControl=Runner.controls.FilterControlFactory(this.filterContolsData[i],this);if(filterControl){this.filterControls.push(filterControl);}}},updateFilterPanelVisibility:function(){if(this.pageObj.isBootstrap()){return;}
var hidePanel=true,i;for(i=0;i<this.filterControls.length;i++){if(this.filterControls[i].isVisible()){hidePanel=false;break;}}
if(hidePanel){this.pageObj.hideBrick("filterpanel");}},rememberFilterPanelState:function(){if(!this.filterControls.length){return;}
var stateId='filtersState_'+this.shortTName+'_'+this.id,filterPanelString=localStorage.getItem('filterPanel'),oldFiltersState={},filtersState={},filterPanel={},filter,i;if(filterPanelString){filterPanel=JSON.parse(filterPanelString);oldFiltersState=filterPanel[stateId]||{};}
for(i=0;i<this.filterControls.length;i++){filter=this.filterControls[i];filtersState[filter.fieldName]=filter.isVisible()?filter.isCollapsed():oldFiltersState[filter.fieldName];}
filterPanel[stateId]=filtersState;localStorage.setItem('filterPanel',JSON.stringify(filterPanel));},adjustExpanderSigns:function(){if(!this.filterControls.length){return;}
var filtersStateString=localStorage.getItem('filterPanel'),filterPanel,filtersStateObj,i,isCollapsed;if(filtersStateString){filterPanel=JSON.parse(filtersStateString);filtersStateObj=filterPanel['filtersState_'+this.shortTName+'_'+this.id];}
if(!filtersStateString||!filtersStateObj){for(i=0;i<this.filterControls.length;i++){this.filterControls[i].updateCollapsedState();}
return;}
for(i=0;i<this.filterControls.length;i++){isCollapsed=filtersStateObj[this.filterControls[i].fieldName];this.filterControls[i].toggleCollapsed(isCollapsed);this.filterControls[i].adjustExpander(isCollapsed);}},updateParentFilters:function(parentFiltersData){var i,filter,filterValue;for(i=0;i<this.filterControls.length;i++){filter=this.filterControls[i];filterValue=parentFiltersData[filter.fieldName];if(filterValue!==undefined){filter.updateValue(filterValue);}}},clearDependentFilters:function(dependentFiltersNames,notMultiSelected){var i,filter;for(i=0;i<this.filterControls.length;i++){filter=this.filterControls[i];if(filter.isDependent()&&$.inArray(filter.fieldName,dependentFiltersNames)!==-1&&(!notMultiSelected||!filter.isMultiSelected())){filter.clearControl();}}},hasFilteredParentFilter:function(parentFiltersNames){var i,filter;for(i=0;i<this.filterControls.length;i++){filter=this.filterControls[i];if($.inArray(filter.fieldName,parentFiltersNames)!==-1&&filter.filtered){return true;}}
return false;}});Runner.search.SearchParamsLogger=Runner.extend(Runner.emptyFn,{savedSearches:{},saveSearchButton:null,savedSearchesButton:null,searchControllerConnector:null,id:-1,tName:"",pageType:"",savedSeachLinkClass:"savedSearch",deleteSearchBtnClass:"deleteSearch",constructor:function(cfg){Runner.apply(this,cfg);},init:function(searchController){this.initSearchControllerConntector(searchController);this.initSearchSavingButtons();this.initSavedSearchesList();return this;},initSearchControllerConntector:function(searchController){var Connector=function(){this.getProperty=function(propertyName){return searchController[propertyName];}
this.submitSavedSearch=function(searchParams){searchController.submitSavedSearch(searchParams);}
this.getTheFirstSearchControlValue=function(){return searchController.getTheFirstSearchControlValue();}}
this.searchControllerConnector=new Connector();this.initSearchControllerConntector=Runner.emptyFn;},initSearchSavingButtons:function(){var logger=this;this.saveSearchButton=$("#saveSearch"+this.id).off("click.slogger").on("click.slogger",function(e){if(!Runner.isDisabledButton(this)){Runner.addDisabledClass(this);logger.saveSearchClickHandler(e);}
return false;});this.savedSearchesButton=$("#savedSearches"+this.id).on("click",function(e){return false;});},saveSearchClickHandler:function(e){if(!e){return;}
var logger=this,searchNameId="searchName"+this.id,searchName=this.getDefaultSearchName(),args={modal:true,centered:true,headerContent:Runner.lang.constants.TEXT_SEARCH_SAVING,bodyContent:this.getSaveSearchDialogContent(searchName,searchNameId)};if(Runner.isBootstrap()){args.footerContent='<a href="#" id="spButtonSave'+this.id+'" class="btn btn-primary">'+Runner.lang.constants.TEXT_SAVE+'</a>'
+'<a href="#" id="spButtonCancel'+this.id+'" class="btn btn-default">'+Runner.lang.constants.TEXT_CANCEL+'</a>';Runner.pages.PageManager.createBSWin(args,false,function(win){var $modal=win._obj,$searchName=$("#"+searchNameId).focus();$("#spButtonSave"+logger.id).on("click",function(ev){var searchName=$searchName.val();logger.saveSearch(searchName);$modal.modal("hide");return false;});$("#spButtonCancel"+logger.id).on("click",function(ev){$modal.modal("hide");return false;});},function(win){var $modal=win._obj;Runner.delDisabledClass(logger.saveSearchButton);});return;}
Runner.pages.PageManager.createFlyWin(args,false,function(winWrapper){var Y=Runner.Y,win=winWrapper._obj,searchNameElem=Y.DOM.byId(searchNameId,win.bodyNode.getDOMNode());win.bodyNode.setStyle("textAlign","center");win.addButton({label:Runner.lang.constants.TEXT_SAVE,name:"saveButton",template:"<a />",classNames:"rnr-button main",section:Y.WidgetStdMod.BODY,action:function(e){var bodyDomNode=win.bodyNode.getDOMNode(),searchName=searchNameElem.value;e.preventDefault();logger.saveSearch(searchName);win.destroy(true);}});win.addButton({label:Runner.lang.constants.TEXT_CANCEL,template:"<a />",classNames:"rnr-button",section:Y.WidgetStdMod.BODY,action:function(e){e.preventDefault();win.destroy(true);}});win.on('destroy',function(){Runner.delDisabledClass(logger.saveSearchButton);});Runner.pages.PageManager.correctYUIWindowSize(win,true);searchNameElem.focus();});},saveSearch:function(searchName){var logger=this,ajaxURL=Runner.pages.getUrl(this.tName,this.pageType),ajaxParams={saveSearch:true,searchName:searchName};Runner.runnerAJAX(ajaxURL,ajaxParams,function(params){if(!logger.savedSearches[searchName]){logger.addSearchToSavedSearchesList(searchName);}
logger.savedSearches[searchName]=params
logger.savedSearchesButton.show();});this.saveSearchButton.remove();},getDefaultSearchName:function(){var searchName=this.searchControllerConnector.getTheFirstSearchControlValue(),re=/(.+_)(\d+)$/,matches;while(this.savedSearches[searchName]){matches=re.exec(searchName);if(matches){searchName=matches[1]+(parseInt(matches[2],10)+1);}else{searchName+='_1';}}
return searchName;},getSaveSearchDialogContent:function(searchName,searchNameId){return'<div class="rnr-searchname">'
+'<label for="searchName">'+Runner.lang.constants.TEXT_SEARCH_NAME+'&nbsp</label>'
+'<input id="'+searchNameId+'" type="text" value="'+searchName+'" name="searchName">'
+'</div>';},initSavedSearchesList:function(){var searchName,logger=this;this.savedSearchesList=$('<ul id="savedSearchedList'+this.id+'" class="rnr-list"></ul>').addClass('rnr-saved-searches');if(Runner.isBootstrap()){this.savedSearchesList.hide();$('#savedSearchedList'+this.id).detach();}
for(searchName in this.savedSearches){if(this.savedSearches.hasOwnProperty(searchName)){this.addSearchToSavedSearchesList(searchName);}}
this.savedSearchesList.insertAfter(this.savedSearchesButton).on('click','.'+this.savedSeachLinkClass,function(e){var searchName=$(this).parent('li').data('search'),searchParams=logger.savedSearches[searchName];logger.searchControllerConnector.submitSavedSearch(searchParams);return false;}).on('click','.'+this.deleteSearchBtnClass,function(){var deleteSearch=$(this),searchName;if(deleteSearch.hasClass('disabled')){return;}
searchName=deleteSearch.parent('li').data('search');logger.deleteSavedSearch(searchName);deleteSearch.addClass('disabled');return false;});Runner.setZindexMaxToElem(this.savedSearchesList);},addSearchToSavedSearchesList:function(searchName){var item=$('<li></li>').data('search',searchName).appendTo(this.savedSearchesList);$('<a data-icon="remove" href="#"></a>').on("touchend",function(){$(this).trigger("click")}).addClass(this.deleteSearchBtnClass).appendTo(item);$('<a href="#"></a>').on("touchend",function(){$(this).trigger("click")}).addClass(this.savedSeachLinkClass).html(searchName).appendTo(item);if(Runner.isBootstrap())
this.savedSearchesList.show();},deleteSavedSearch:function(searchName){if(!this.savedSearches[searchName]){return;}
var logger=this,args={modal:true,centered:true,headerContent:Runner.lang.constants.TEXT_DELETE_SEARCH_CAPTION,bodyContent:this.getDeleteSearchDialogContent()};if(Runner.isBootstrap()){args.footerContent='<a href="#" id="spButtonYes'+this.id+'" class="btn btn-primary">'+Runner.lang.constants.TEXT_YES+'</a>'
+'<a href="#" id="spButtonNo'+this.id+'" class="btn btn-default">'+Runner.lang.constants.TEXT_NO+'</a>';Runner.pages.PageManager.createBSWin(args,false,function(win){var $modal=win._obj;$("#spButtonYes"+logger.id).on("click",function(ev){var ajaxURL=Runner.pages.getUrl(logger.tName,logger.pageType),ajaxParams={deleteSearch:true,searchName:searchName};Runner.runnerAJAX(ajaxURL,ajaxParams,Runner.emptyFn);logger.removeSavedSearchesListItem(searchName);delete logger.savedSearches[searchName];if($.isEmptyObject(logger.savedSearches)){logger.savedSearchesButton.hide();logger.savedSearchesList.hide();Runner.pages.PageManager.getById(logger.id).hideExcessSeparators();}
$modal.modal("hide");return false;});$("#spButtonNo"+logger.id).on("click",function(ev){$modal.modal("hide");return false;});},function(win){var $modal=win._obj;logger.getSavedSearchesListItem(searchName).children('.'+logger.deleteSearchBtnClass).removeClass('disabled');});return;}
Runner.pages.PageManager.createFlyWin(args,false,function(winWrapper){var Y=Runner.Y,win=winWrapper._obj;win.bodyNode.setStyle("textAlign","center");win.addButton({label:Runner.lang.constants.TEXT_YES,name:"yesButton",template:"<a />",classNames:"rnr-button main",section:Y.WidgetStdMod.BODY,action:function(e){e.preventDefault();var ajaxURL=Runner.pages.getUrl(logger.tName,logger.pageType),ajaxParams={deleteSearch:true,searchName:searchName};Runner.runnerAJAX(ajaxURL,ajaxParams);logger.removeSavedSearchesListItem(searchName);delete logger.savedSearches[searchName];if($.isEmptyObject(logger.savedSearches)){logger.savedSearchesButton.hide();}
win.destroy(true);}});win.addButton({label:Runner.lang.constants.TEXT_NO,template:"<a />",classNames:"rnr-button",section:Y.WidgetStdMod.BODY,action:function(e){e.preventDefault();win.destroy(true);}});win.on('destroy',function(){logger.getSavedSearchesListItem(searchName).children('.'+logger.deleteSearchBtnClass).removeClass('disabled');});Runner.pages.PageManager.correctYUIWindowSize(win,true);});},getDeleteSearchDialogContent:function(){return'<div class="rnr-delete-search">'
+Runner.lang.constants.TEXT_DELETE_SEARCH
+'</div>';},removeSavedSearchesListItem:function(searchName){this.getSavedSearchesListItem(searchName).remove();},getSavedSearchesListItem:function(searchName){return $('li',this.savedSearchesList).filter(function(){return $(this).data('search')===searchName;});}});Runner.namespace('Runner.form');Runner.form.BasicForm=Runner.extend(Runner.util.Observable,{id:-1,baseParams:null,isFileUpload:false,standardSubmit:false,ajaxForm:null,searchForm:null,isSearchForm:false,searchSubmit:false,fieldControls:null,addElems:null,formEl:null,ioEl:null,ioElId:'',submitUrl:'',method:'POST',target:'',addRndVal:true,useMultipart:false,deleteAfterSubmit:false,initImmediately:false,isFormReady:false,setFocus:true,constructor:function(cfg){this.addElems=[];this.ajaxForm={};this.baseParams={};this.fieldControls=[];Runner.apply(this,cfg);this.addEvents('beforeSubmit','successSubmit','submitFailed','validationFailed');if(this.beforeSubmit){this.on({'beforeSubmit':this.beforeSubmit});}
if(this.successSubmit){this.on({'successSubmit':this.successSubmit});}
if(this.submitFailed){this.on({'submitFailed':this.submitFailed});}
if(this.validationFailed){this.on({'validationFailed':this.validationFailed});}
Runner.form.BasicForm.superclass.constructor.call(this,cfg);if(this.initImmediately){this.initForm();}},destructor:function(destroyControls){if(destroyControls===true){for(var i=0;i<this.fieldControls.length;i++){this.fieldControls[i].unregister();}}
if(this.ioEl&&this.ioEl.length){var $iframe=this.ioEl;setTimeout(function(){$iframe.remove();},0);}
if(this.formEl&&this.formEl.length){this.formEl.remove();}},submit:function(){this.triedToSubmit=true;var beforeSubmitRes=this.fireEvent('beforeSubmit',this),formObj=this;if(beforeSubmitRes===false||!this.validate()){return false;}
if(this.isFileUpload||this.standardSubmit){if(this.searchSubmit&&Runner.charSet=="utf-8"){var queryStr,i,queryParts=[],vars={},paramsStr=window.location.href,paramNames=['rname','cname'],param;$.each(this.searchForm,function(formParameter,parameterValue){queryParts.push(formParameter+'='+parameterValue);});if(paramsStr.substr(paramsStr.length-1)=='#'){paramsStr=paramsStr.substr(0,paramsStr.length-1);}
paramsStr.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});for(i=0;i<paramNames.length;i++){if(vars[paramNames[i]]){queryParts.push(paramNames[i]+'='+encodeURIComponent(vars[paramNames[i]]));}}
for(param in this.baseParams){queryParts.push(param+'='+encodeURIComponent(this.baseParams[param]));}
queryStr=queryParts.join('&');queryStr=this.submitUrl+(queryStr?'?'+queryStr:queryStr);if(queryStr.length<2040){location.href=queryStr;return true;}
this.formEl.attr('method','POST');}
this.initForm();this.addFormSubmit();this.formEl.submit();}else{this.addFormSubmit();Runner.runnerAJAX(this.submitUrl,this.ajaxForm,function(respObj){formObj.fireEvent("successSubmit",respObj,formObj,formObj.fieldControls);});}
return true;},initForm:function(){if(this.isFormReady){return;}
if(this.isFileUpload&&!this.standardSubmit){this.createIFrame();this.createForm();}else if(this.standardSubmit){this.createForm();}
this.isFormReady=true;},clearForm:function(){if(this.formEl&&this.formEl.length){this.formEl.children().remove();}
this.ajaxForm={};this.searchForm={};},addFormSubmit:function(){var arrClns,i,j,param;if(this.isFormReady&&!this.isSearchForm){this.clearForm();}
if(this.addRndVal){this.baseParams["rndVal"]=Math.random();}
if(this.formEl&&this.formEl.length){for(i=0;i<this.fieldControls.length;i++){arrClns=this.fieldControls[i].getForSubmit();for(j=0;j<arrClns.length;j++){$(arrClns[j]).appendTo(this.formEl);}}
for(param in this.baseParams){this.addToForm(param,this.baseParams[param]);}
for(i=0;i<this.addElems.length;i++){$(this.addElems[i]).appendTo(this.formEl);}
return;}
this.ajaxForm=Runner.apply(this.ajaxForm,this.baseParams);for(i=0;i<this.fieldControls.length;i++){this.ajaxForm[this.fieldControls[i].fieldName]=this.fieldControls[i].getStringValue();}
for(i=0;i<this.addElems.length;i++){$(this.addElems[i]).appendTo(this.formEl);this.addToForm(this.addElems[i].attr("id")||this.addElems[i].attr("name"),this.addElems[i].val());}},addToForm:function(id,val){var i;if(val===undefined||id===undefined||val===null||id===null){return;}
if(Runner.isArray(val)){for(i=0;i<val.length;++i){this.addToForm(id,val[i]);}
return;}
if(this.isFileUpload||this.standardSubmit){if(!this.formEl){this.initForm();}
$('<input id="'+id+'" name="'+id+'" type="hidden"></input>').val(val.toString()).appendTo(this.formEl);if(this.searchSubmit){this.ajaxForm[id]=val;}}else{this.ajaxForm[id]=val;}},addToSearchForm:function(id,val){if(val!==undefined&&id!==undefined&&val!==null&id!==null){this.searchForm[id]=val;}},validate:function(controlsNames){var invalidControls,controlsToValidate;if(controlsNames){controlsToValidate=[];$.each(this.fieldControls,function(idx,control){if($.inArray(control.fieldName,controlsNames)!==-1){controlsToValidate.push(control);}});}else{controlsToValidate=this.fieldControls;}
invalidControls=Runner.pages.RunnerPage.prototype.getInvalidControls.call(this,controlsToValidate);if(invalidControls.length){if(Runner.isBootstrap()){$.each(invalidControls,function(i,ctrl){var hiddenColumnByJs=ctrl.spanContElem.parents("[data-hidden-column]"),hiddenColumn=hiddenColumnByJs.length?hiddenColumnByJs:ctrl.spanContElem.parents("[class*='bs-hidden-column']"),hiddenColumnName;if(hiddenColumn.length){hiddenColumnName=hiddenColumn.data("field");ctrl.pageObj.showHiddenColumn(hiddenColumnName);}});}
if(this.setFocus){Runner.pages.RunnerPage.prototype.setFirstFocus.call(this,this.id,invalidControls);}
this.fireEvent("validationFailed",this,controlsToValidate,invalidControls);return false;}
return true;},createIFrame:function(){if(this.ioEl){return false;}
var frameId='uploadFrame_'+this.id,basicForm=this,$iframe=$('<iframe id="'+frameId+'" name="'+frameId+'"/>').css({border:'0',height:'1px',width:'1px',display:'none'}).appendTo('body');$iframe.bind('load',function(e){var bodyElem=$(this).contents().find('body').get(0),response,responseObj,rawResponse=bodyElem.innerHTML;if(rawResponse!==''){try{response=$('<div>'+rawResponse+'</div>').text();responseObj=JSON.parse(response);}catch(e){if(!basicForm.isEventExist('submitFailed')){rawResponse=$(this).contents().find('head').html()+rawResponse;Runner.pages.RunnerPage.prototype.displayGenericAjaxError(rawResponse);}
basicForm.fireEvent('submitFailed',rawResponse,basicForm,basicForm.fieldControls);if(basicForm.deleteAfterSubmit){basicForm.destructor(true);}
return;}
basicForm.fireEvent('successSubmit',responseObj,basicForm,basicForm.fieldControls);}else{basicForm.fireEvent('submitFailed',rawResponse,basicForm,basicForm.fieldControls);}
if(basicForm.deleteAfterSubmit){basicForm.destructor(true);}});this.ioEl=$iframe;this.ioElId=frameId;},createForm:function(){if(this.formEl){return false;}
var $form=$('<form/>').attr({action:this.submitUrl,method:this.method}).css('display','none').appendTo('body');if(this.target){$form.attr('target',this.target);}
if(this.ioEl){$form.attr('target',this.ioElId);}
if(this.isFileUpload||this.useMultipart){$form.attr('enctype','multipart/form-data');}
this.formEl=$form;},makeReadonly:function(){for(var i=0;i<this.fieldControls.length;i++){this.fieldControls[i].makeReadonly();}},makeReadWrite:function(){for(var i=0;i<this.fieldControls.length;i++){this.fieldControls[i].makeReadWrite();}}});Runner.runnerAJAX=function(submitUrl,baseParams,succesHandler){var basicForm=new Runner.form.BasicForm({id:Runner.genId(),standardSubmit:false,isFileUpload:true,submitUrl:submitUrl,method:'POST',baseParams:baseParams,deleteAfterSubmit:true,successSubmit:{fn:succesHandler,scope:window}});basicForm.submit();};Runner.submitRunnerFormInIframe=function(submitUrl,cfgParams,succesSubmitHandler,submitFailedHandler){var basicForm,formParams={method:'POST',id:Runner.genId(),standardSubmit:false,isFileUpload:true,submitUrl:submitUrl,deleteAfterSubmit:true};if(cfgParams.baseParams&&typeof cfgParams.baseParams==="object"){formParams.baseParams=cfgParams.baseParams}
if(Runner.isArray(cfgParams.addElems)){formParams.addElems=cfgParams.addElems;}
if(typeof succesSubmitHandler==="function"){formParams.successSubmit={fn:succesSubmitHandler,scope:window}}
if(typeof submitFailedHandler==="function"){formParams.submitFailed={fn:submitFailedHandler,scope:window}}
basicForm=new Runner.form.BasicForm(formParams);basicForm.submit();}
Runner.namespace('Runner.util.details');Runner.util.details.DP=Runner.extend(Runner.util.Observable,{tName:"",shortTName:"",masterTName:"",masterShortTName:"",masterPageType:"",ajaxRequestUrl:"",pageType:"",dpShowType:Runner.pages.constants.DP_NONE,id:0,parId:1,oldLayout:false,classBasePrefix:"",constructor:function(cfg){Runner.apply(this,cfg);Runner.util.details.DP.superclass.constructor.call(this,cfg);this.shortTName=Runner.pages.PageSettings.getShortTName(this.tName);this.masterShortTName=Runner.pages.PageSettings.getShortTName(this.masterTName);this.ajaxRequestUrl=Runner.getPageUrl(this.shortTName,this.pageType);this.classBasePrefix=this.oldLayout?"runner-":"rnr-";this.parPageObj=Runner.pages.PageManager.getById(this.parId);if(this.parPageObj){this.masterPageType=this.parPageObj.pageType;}},init:Runner.emptyFn});Runner.util.details.InlineDP=Runner.extend(Runner.util.details.DP,{rows:null,hideChild:false,parPageObj:null,pageContext:null,constructor:function(cfg){this.rows=[];Runner.util.details.InlineDP.superclass.constructor.call(this,cfg);this.addEvents("beforeShow","afterShow");},init:function(){for(var i=0;i<this.rows.length;i++){this.initRow(this.rows[i]);}},initRow:function(row,setHref){if(!row.row||!row.row.length){row.row=$("#gridRow"+row.id,this.pageContext);if(!row.row.length){row.row=$("#master_"+this.shortTName+row.id,this.pageContext);}
if(!row.row.length){row.row=$("#"+this.shortTName+"_preview"+row.id,this.pageContext).closest('tr[id^=gridRow]');}
if(!row.row.length){row.row=$("#details_"+row.id,this.pageContext).closest('tr[id^=gridRow]');}
if(!row.row.length){row.row=$(".bs-grid-vertical-cell[data-record-id='"+row.id+"']",this.pageContext).closest('div[id^=gridRow]');}}
if(this.linksType==Runner.pages.constants.DL_INDIVIDUAL||Runner.isBootstrap()&&this.linksType==Runner.pages.constants.DL_SINGLE||this.tabSettings.tabIndex==0){this.initLink(row,setHref);}},initLink:function(row,setHref){},addRow:function(row){row.rowInd=this.rows.length;this.rows.push(row);this.initRow(row,true);this.setChildRecNum(row,this.getChildCountBySameKeys(row));},getChildCountBySameKeys:function(row){var mKeysAsString=JSON.stringify(row.masterKeys[this.tName]),i;for(i=0;i<this.rows.length;i++){if(this.rows[i].id!=row.id&&mKeysAsString==JSON.stringify(this.rows[i].masterKeys)){return this.rows[i].childNum;}}
return"0";},updateChildRecNum:function(masterKeys,rowId){var dp=this,mKeys=[],reqParams,k;for(k in masterKeys){mKeys.push(masterKeys[k]);}
reqParams={mKeys:JSON.stringify(mKeys),dTable:this.tName,dSTable:this.shortTName,pageType:this.pageType,mTable:this.masterTName,mSTable:this.masterShortTName}
Runner.runnerAJAX(Runner.getPageUrl("detreccount"),reqParams,function(respObj){if(!respObj.success){return;}
if(dp.hideChild&&dp.linksType==Runner.pages.constants.DL_SINGLE){$("#details_"+rowId).toggle(!!parseInt(respObj.recsCount,10));}
if(rowId!=undefined){dp.updateChildRecNumById(masterKeys,respObj.recsCount,rowId);}else{dp.updateChildRecNumByKeys(masterKeys,respObj.recsCount);}});},updateChildRecNumById:function(masterKeys,detNum,rowId){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id==rowId){this.setChildRecNum(this.rows[i],detNum);}}},updateChildRecNumByKeys:function(masterKeys,detNum){var mKeysAsString=JSON.stringify(masterKeys),i;for(i=0;i<this.rows.length;i++){if(mKeysAsString==JSON.stringify(this.rows[i].masterKeys[this.tName])){this.setChildRecNum(this.rows[i],detNum);}}},setChildRecNum:function(row,detNum){var $detNumberSpan=$("#cntDet_"+this.shortTName+"_"+row.id),numberOfDetails=parseInt(detNum,10),countText="";if(!$detNumberSpan.length){$detNumberSpan=row.row.find('#'+this.shortTName+'_preview'+row.id).find('span').attr('id',"#cntDet_"+this.shortTName+"_"+row.id);if(!$detNumberSpan.attr('id')){$detNumberSpan=row.row.find('#master_'+this.shortTName+"_"+row.id).find('span').attr('id',"#cntDet_"+this.shortTName+"_"+row.id);}}
if($detNumberSpan.length){if(numberOfDetails>0){$detNumberSpan.show();}
if(Runner.isBootstrap()&&this.linksType==Runner.pages.constants.DL_SINGLE){if($detNumberSpan.hasClass("details-badge")){$detNumberSpan.html(numberOfDetails).parent().toggleClass("hidden-badge",!numberOfDetails);}else{$("span:not(.glyphicon)",$detNumberSpan).html(numberOfDetails).toggle(numberOfDetails>0);}
return;}
if(numberOfDetails>0){countText="("+numberOfDetails+")";}
$detNumberSpan.html(countText).parent().toggle(!this.hideChild||numberOfDetails>0);return;}
row.row.find('#'+this.shortTName+'_preview'+row.id).toggle(!this.hideChild||numberOfDetails>0);},getRowByInd:function(ind){for(var i=0;i<this.rows.length;i++){if(this.rows[i].rowInd==ind){return this.rows[i];}}
return null;},getRowById:function(id){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id==id){return this.rows[i];}}
return null;},closeDetailsById:function(rowId){}})
Runner.util.details.DPPopUp=Runner.extend(Runner.util.details.InlineDP,{timeout:null,masterDetails:null,prevLink:null,constructor:function(cfg){Runner.util.details.DPPopUp.superclass.constructor.call(this,cfg);this.dpShowType=Runner.pages.constants.DP_POPUP;this.masterDetails={show:false,flag:"",counter:0};},initLink:function(row,setHref){var href,mKeys,key,linkQr="#"+this.shortTName+"_preview"+row.id;if(setHref===true){mKeys=[];for(key in row.masterKeys[this.tName]){mKeys.push(row.masterKeys[this.tName][key]);}
href=Runner.pages.getUrl(this.tName,this.pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(this.masterTName);$(linkQr).attr('href',href);}},showPopup:function(link,url,mastertable,masterKeys){var urlsDiff=false,pageObj=this,$detailsPopupEl=$("."+this.classBasePrefix+"details-popup");if(url&&url!==$detailsPopupEl.data("url")){urlsDiff=true;$detailsPopupEl.data("url",url);}
clearTimeout($detailsPopupEl.data("timeout"));if($detailsPopupEl.css("display")=='none'||(url!=undefined&&this.prevLink!=link)||urlsDiff){this.timeout=setTimeout(function(){pageObj.prevLink=link;pageObj.masterDetails.flag=url;pageObj.masterDetails.show=true;pageObj.masterDetails.counter++;Runner.runnerAJAX(url,{counter:pageObj.masterDetails.counter,mastertable:mastertable,masterKeys:JSON.stringify(masterKeys),mode:'listdetailspopup'},function(respObj){var detailsPopup,linkPosition;if(!respObj.success||!pageObj.masterDetails.show){return;}
detailsPopup=$("."+pageObj.classBasePrefix+"details-popup");if(!detailsPopup.length){detailsPopup=$('<div class="'+pageObj.classBasePrefix+'details-popup" style="display:none; position: absolute; left: 0px; top: 0px;"> </div>').appendTo('body');}
detailsPopup.bind({mouseenter:function(){pageObj.showPopup();},mouseleave:function(){pageObj.hidePopup();}});if(pageObj.masterDetails.counter==respObj.counter){detailsPopup.html(respObj.body);if(respObj.CSSFiles){detailsPopup.addClass("page-detailspreview "+pageObj.classBasePrefix+"pagewrapper ");Runner.util.ScriptLoader.loadCSS(respObj.CSSFiles);}
if(pageObj.pageType===Runner.pages.constants.PAGE_CHART){Runner.util.ScriptLoader.addJS([window.settings.global["webRootPath"]+'libs/js/anychart.min.js']);Runner.util.ScriptLoader.addJS([window.settings.global["webRootPath"]+'libs/js/migrationTool.js'],window.settings.global["webRootPath"]+'libs/js/anychart.min.js');Runner.util.ScriptLoader.onFilesLoaded(function(){Runner.Charts.createChart($('[data-runner-chart-params]',detailsPopup).data('runner-chart-params'));},pageObj);Runner.util.ScriptLoader.load();}}
linkPosition=$(link).offset();detailsPopup.css({top:linkPosition.top+"px",left:linkPosition.left+(Runner.isDirRTL()?-detailsPopup.outerWidth():$(link).outerWidth())+"px",display:''});});},100);$("."+this.classBasePrefix+"details-popup").data("timeout",this.timeout);}},hidePopup:function(){var detailPopup=$('.'+this.classBasePrefix+'details-popup');this.masterDetails.show=false;if(detailPopup.css("display")=='none'||!detailPopup.length){clearTimeout(detailPopup.data("timeout"));return;}
this.timeout=setTimeout(function(){detailPopup.hide();detailPopup.html("");},200);detailPopup.data("timeout",this.timeout);$(".runner-details-popup").data("timeout",this.timeout);}});Runner.util.details.recDP=Runner.extend(Runner.util.details.DP,{detailsPageObj:null,id:-1,submitMade:false,submitSucceded:true,useChildCount:false,init:function(){Runner.util.details.recDP.superclass.init.call(this);this.initButton();this.initDpPage();this.addEvents('detailsSaved');if(this.detailsSaved){this.on({'detailsSaved':this.detailsSaved});}
if(this.saveFailed){this.on({'saveFailed':this.saveFailed});}
if(this.afterDeleteDetails){this.on({'afterDeleteDetails':this.afterDeleteDetails});}},initDpPage:function(){var cfg=this.getPageConfig();this.detailsPageObj=Runner.pages.PageManager.initPage(cfg);},initGridTabs:function(){var pageObj=this;$('[data-pageid='+this.id+'][data-tabid]').on("click",function(e){if(!$(this).parent().hasClass('active')){pageObj.reload({tab:$(this).data("tabid")});}
e.preventDefault();});},getPageConfig:function(cfg){return Runner.apply(cfg||{},{tName:this.tName,pageType:this.pType,openMode:Runner.pages.constants.OPENMODE_PRELOADED_CONTAINER,openContainer:$("#detailPreview"+this.id),pageId:this.id,controlsMap:this.controlsMap,viewControlsMap:this.viewControlsMap,masterTName:this.masterTName,detCont:$("#detailPreview"+this.id),useChildCount:this.useChildCount,childRecNum:0,parId:this.parId,pageMode:Runner.pages.constants.MODE_LIST_DETAILS,baseParams:{id:this.id,mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),masterpagetype:this.masterPageType},afterSaveDetails:{fn:function(allVals,fields,allKeys,allRowIds,isEdit){this.submitMade=true;this.submitSucceded=true
this.fireEvent("detailsSaved",this,allVals,fields,allKeys,allRowIds);},scope:this},saveFailed:{fn:function(respObj,formObj,fieldControls){this.submitMade=true;this.submitSucceded=false;this.fireEvent("saveFailed",this,respObj,formObj);},scope:this},afterDeleteDetails:{fn:function(){this.fireEvent("afterDeleteDetails");},scope:this},validationFailed:this.validationFailed,initGridTabs:this.initGridTabs});},validationFailed:Runner.emptyFn,initButton:function(){var id=this.id,$button=$('#dpMinus'+id);$button.on('click',function(e){if($button.is(':visible')){$('.projekktor','#detailPreview'+id).each(function(){projekktor(this.id).setStop();});}
setTimeout(function(){var src=$button.attr('src'),newSrc=src==Runner.pages.constants.MINUS_GIF?Runner.pages.constants.PLUS_GIF:Runner.pages.constants.MINUS_GIF;$('#detailPreview'+id).toggle();$button.attr('src',newSrc);},100);});},saveDetails:function(mKeys){if(!this.detailsPageObj||this.detailsPageObj.pageType!==Runner.pages.constants.PAGE_LIST){return;}
this.submitSucceded=false;this.submitMade=false;return this.detailsPageObj.saveAll(mKeys);},validate:function(){if(!this.detailsPageObj||this.detailsPageObj.pageType!==Runner.pages.constants.PAGE_LIST){return;}
var addValidRes=this.detailsPageObj.inlineEdit?this.detailsPageObj.inlineEdit.validate():true,editValidRes=this.detailsPageObj.inlineAdd?this.detailsPageObj.inlineAdd.validate():true;return editValidRes&&addValidRes;},destructor:function(){if(this.detailsPageObj){this.detailsPageObj.destructor();}}});Runner.util.details.AddDP=Runner.extend(Runner.util.details.recDP,{constructor:function(cfg){this.pageType=Runner.pages.constants.PAGE_ADD;Runner.util.details.AddDP.superclass.constructor.call(this,cfg);},initDpPage:function(){Runner.util.details.AddDP.superclass.initDpPage.call(this);this.detailsPageObj.on('beforeSave',function(row,inlineObj,formObj){if(inlineObj.inlineAddChangeContent!==true){inlineObj.cancelAll();return false;}},this);},getPageConfig:function(){var cfg={hideSaveButt:true,afterInit:{fn:function(pageObj,proxy,pageId){if(!pageObj.inlineAdd){return;}
pageObj.inlineAdd.inlineAdd(true,true);pageObj.inlineAdd.on("createControls",function(row,ctrls){var inlineAddContentChangeHandler,i;if(this.inlineAddChangeContent){return true;}
inlineAddContentChangeHandler=function(){this.fireEvent('inlineAddContentChange',row);}
for(i=0;i<this.rows.length;i++){if(this.rows[i]!==row&&!$(this.rows[i].cancelLink).is(":visible")){this.showCancelButton(this.rows[i]);return true;}}
this.inlineAddChangeContent=false;this.on('inlineAddContentChange',this.showCancelButton,this,{single:true});for(i=0;i<ctrls.length;i++){ctrls[i].on('editing',inlineAddContentChangeHandler,{single:true},this);}},pageObj.inlineAdd);},scope:this}};return Runner.util.details.AddDP.superclass.getPageConfig.call(this,cfg);}});Runner.util.details.EditDP=Runner.extend(Runner.util.details.recDP,{constructor:function(cfg){this.pageType=Runner.pages.constants.PAGE_EDIT;Runner.util.details.EditDP.superclass.constructor.call(this,cfg);}});Runner.util.details.ViewDP=Runner.extend(Runner.util.details.recDP,{constructor:function(cfg){this.pageType=Runner.pages.constants.PAGE_VIEW;Runner.util.details.ViewDP.superclass.constructor.call(this,cfg);}});Runner.util.details.ViewEditDashDP=Runner.extend(Runner.util.details.recDP,{dashTName:"",dashElement:"",constructor:function(cfg){Runner.util.details.ViewEditDashDP.superclass.constructor.call(this,cfg);this.openContainer=$("#dp_"+Runner.goodFieldName(this.masterTName)+"_"+this.masterPageType+"_"+this.id);},init:function(){this.addEvents('detailsSaved','saveFailed');if(this.detailsSaved){this.on({'detailsSaved':this.detailsSaved});}
if(this.saveFailed){this.on({'saveFailed':this.saveFailed});}
this.getDetails();},getDetails:function(){var dpObj=this,params=Runner.apply(this.getDetailsRequestParams(),this.masterKeys);Runner.setIdCounter(params.id+1000);Runner.runnerAJAX(this.ajaxRequestUrl,params,function(respObj){var cfg,jsFile;if(respObj.noData||!respObj.success){dpObj.openContainer.parents(".panel").eq(0).hide();return;}
Runner.setIdCounter(respObj.idStartFrom);Runner.pages.PageSettings.addSettings(dpObj.tName,respObj.settings,false);Runner.applyPagesData(respObj.pagesData);if(respObj.additionalCSS){Runner.util.ScriptLoader.loadCSS(respObj.additionalCSS);}
if(respObj.CSSFiles){Runner.util.ScriptLoader.loadCSS(respObj.CSSFiles);}
cfg=dpObj.getNewDetailPageConfig(respObj,params.id);if(dpObj.masterPageType==Runner.pages.constants.PAGE_EDIT&&respObj.headerButtonsBlock){cfg.afterCreateHn=function(){this.openContainer.parents(".panel").eq(0).find(".panel-heading .panel-title span").html(respObj.headerButtonsBlock)}}
if(respObj.additionalJS){for(jsFile in respObj.additionalJS){Runner.util.ScriptLoader.addJS([jsFile],respObj.additionalJS[jsFile]);}
Runner.util.ScriptLoader.onFilesLoaded(function(){dpObj.detailsPageObj=Runner.pages.PageManager.initPage(cfg);},this);Runner.util.ScriptLoader.load();}else{dpObj.detailsPageObj=Runner.pages.PageManager.initPage(cfg);}});},getDetailsRequestParams:function(){return{id:Runner.genId(),mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),mastertable:this.masterTName,masterid:this.id,masterpagetype:this.masterPageType,table:this.dashTName,dashelement:this.dashElement};},getNewDetailPageConfig:function(respObj,newId){return{bodyCont:respObj.html,headerCont:respObj.headerCont,footerCont:respObj.footerCont,openMode:Runner.pages.constants.OPENMODE_CONTAINER,openContainer:this.openContainer,tName:this.tName,pageId:newId,pageType:this.pageType,controlsMap:respObj.controlsMap[this.tName][this.pageType][newId]||{},viewControlsMap:respObj.viewControlsMap[this.tName][this.pageType][newId]||{},pageMode:Runner.pages.constants.MODE_LIST_DETAILS,masterKeys:this.masterKeys,parId:this.parId,masterTName:this.masterTName,pageCont:this.openContainer,detCont:this.openContainer,afterSaveDetails:{fn:function(allVals,fields,allKeys,allRowIds,isEdit){this.submitMade=true;this.submitSucceded=true
this.fireEvent("detailsSaved",this,allVals,fields,allKeys,allRowIds);},scope:this},saveFailed:{fn:function(respObj,formObj,fieldControls){this.submitMade=true;this.submitSucceded=false;this.fireEvent("saveFailed",this,respObj,formObj);},scope:this},afterDeleteDetails:this.afterDeleteDetails,validationFailed:this.validationFailed,baseParams:{id:newId,mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),masterpagetype:this.masterPageType,mastertable:this.masterTName,table:this.dashTName,dashelement:this.dashElement},initGridTabs:this.initGridTabs};}});Runner.util.details.ListTabbedPreview=Runner.extend(Runner.util.details.InlineDP,{tabSettings:null,proceedLink:false,dispChildCount:false,recsPerRowList:1,constructor:function(cfg){Runner.util.details.ListTabbedPreview.superclass.constructor.call(this,cfg);this.dpShowType=Runner.pages.constants.DP_INLINE;this.recsPerRowList=Runner.pages.PageSettings.getTableData(this.masterTName,"recsPerRowList");this.listGridLayout=Runner.pages.PageSettings.getTableData(this.masterTName,"listGridLayout");this.tabSettings=this.tabSettings||{};this.tabSettings.tabIndex=this.tabSettings.tabIndex||0;this.tabSettings.tabId=this.tabSettings.tabId||this.shortTName;this.tabSettings.tabLabel=this.tabSettings.tabLabel||this.shortTName;this.tabSettings.hideTabsContent=this.tabSettings.hideTabsContent||false;},getTabTableLink:function(row){var mKeys=[],key;for(key in row.masterKeys[this.tName]){mKeys.push(row.masterKeys[this.tName][key]);}
return Runner.pages.getUrl(this.tName,this.pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(this.masterTName);},getTabLabel:function(row){if(!this.proceedLink||!this.parPageObj.isBootstrap()){return this.tabSettings.tabLabel;}
var href=this.getTabTableLink(row);return'<span id="bsproceed_'+this.shortTName+row.id+'" class="bs-proceed-link" data-plink="'+href+'">'
+this.tabSettings.tabLabel
+'<button class="btn btn-xs btn-link bs-proceed-icon">'
+' <span class="glyphicon glyphicon-new-window "></span>'
+'</button>'
+'</span>';return'<span id="bsproceed_'+this.shortTName+row.id+'" class="bs-proceed-link" data-plink="'+href+'">'
+this.tabSettings.tabLabel
+'<button class="btn btn-xs btn-link bs-proceed-icon">'
+' <span class="glyphicon glyphicon-new-window "></span>'
+'</button>'
+'</span>';},initLink:function(row,setHref){var dpObj=this,href,mKeys,key,linkQr=this.linksType==Runner.pages.constants.DL_SINGLE?"#details_"+row.id:"#"+this.shortTName+"_preview"+row.id,$link=$(linkQr);if(this.linksType==Runner.pages.constants.DL_SINGLE&&!$link.hasClass(this.classBasePrefix+"hiddenelem")){$link.show();}
if(!Runner.isMobile&&!$link.data("initialized")){$link.on("click",function(e){return dpObj.linkClickHandler(row,e);}).data("initialized",true);}
if(this.linksType==Runner.pages.constants.DL_SINGLE){$("#details_"+row.id+"_"+this.shortTName).on("click",function(e){return dpObj.linkClickHandler(row,e);});}
if(setHref===true){mKeys=[];for(key in row.masterKeys[this.tName]){mKeys.push(row.masterKeys[this.tName][key]);}
href=Runner.pages.getUrl(this.tName,this.pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(this.masterTName);$link.attr('href',href);}},initRow:function(row,setHref){Runner.util.details.ListTabbedPreview.superclass.initRow.call(this,row,setHref);this.setDetailLinksIds(row);},setDetailLinksIds:function(row){if(this.recsPerRowList<=1){return;}
var $detLinks,pattern;row.detLinksId=[];if(Runner.isBootstrap()&&this.linksType==Runner.pages.constants.DL_SINGLE){$detLinks=$("[id^='details_'].glyphicon",row.row);$detLinks=$detLinks.length?$detLinks:$("[id^='details_']",row.row);$detLinks.each(function(idx,el){row.detLinksId.push($(el).attr("id").substr(8));});return;}
pattern=this.shortTName+"_preview";$("[id^="+pattern+"]",row.row).each(function(){row.detLinksId.push(this.id.substr(pattern.length));});if(row.detLinksId.length){return;}
pattern="details_";$("[id^="+pattern+"]:not(.glyphicon)",row.row).each(function(){row.detLinksId.push(this.id.substr(pattern.length));});},linkClickHandler:function(row,e){var bsUsed=Runner.isBootstrap(),switchCondition=false,closeCondition=row.isShown,$link=$(e.target),corTabIdx;if(row.isShown&&(this.linksType==Runner.pages.constants.DL_INDIVIDUAL||bsUsed&&this.linksType==Runner.pages.constants.DL_SINGLE&&$link.attr("id")!=="details_"+row.id)){corTabIdx=this.parPageObj.dpObjs[this.tName].tabSettings.tabIndex;if(bsUsed){switchCondition=!$("li[data-tabidx='"+corTabIdx+"']",row.detTd).hasClass("active");}else{switchCondition=!$("li[data-rnrtabidx='"+corTabIdx+"']",row.detTd).hasClass("ui-tabs-active");}}
if(switchCondition){if(bsUsed){$("[data-toggle='tab'][href='"+"#tabdetails"+row.id+'_'+this.shortTName+"']").click();}else{$("#"+$('#tabdetails'+row.id+'_'+this.shortTName).attr("aria-labelledby")).click();}
return false;}
if(closeCondition){this.closeDetails(row,$link);return false;}
this.openDetailsTabs(row,$link);return false;},isTabToShow:function(tName,row){if(this.parPageObj.dpObjs[tName].dpShowType!=Runner.pages.constants.DP_INLINE){return false;}
return!row.hiddentabs||jQuery.inArray(tName,row.hiddentabs)===-1;},openDetailsTabs:function(row,$link){var tabTNames=[],$tabControl,tabSettings,dpObjs,tabElementId,tName,i,href;for(tName in this.parPageObj.dpObjs){if(this.isTabToShow(tName,row)){if(tName==this.tName){tabTNames.unshift(tName);}else{tabTNames.push(tName);}}}
if(!tabTNames.length||this.recsPerRowList==1&&row.detTd){return;}
this.createPreviewRow(row);row.isShown=true;if(Runner.isBootstrap()){if(this.recsPerRowList>1){var $linkTd=$link.closest('td');$linkTd.addClass("bs-details-opened");$linkTd.nextUntil("[colid='endrecord']").addClass("bs-details-opened");$linkTd.prevUntil("[colid='endrecord']").addClass("bs-details-opened");}else{row.row.addClass("bs-details-opened");}}
$tabControl=Runner.pages.PageManager.createTabsControl(row.detTd,"details"+row.id);for(i=0;i<tabTNames.length;i++){tName=tabTNames[i],dpObjs=this.parPageObj.dpObjs[tName],tabElementId="tabdetails"+row.id+"_"+dpObjs.tabSettings.tabId;href=dpObjs.proceedLink&&dpObjs.parPageObj.isBootstrap()?dpObjs.getTabTableLink(row):"";Runner.pages.PageManager.addTabToTabsControl($tabControl,"",tabElementId,dpObjs.getTabLabel(row),tName==this.tName,dpObjs.tabSettings.tabIndex,false,href);this.parPageObj.dpObjs[tName].getDetails(row);}
$tabControl.find('.bs-proceed-link').closest('[data-toggle="tab"]').addClass("bs-proceed-link");$tabControl.on('click.detailsTabControl','.bs-proceed-link',function(){var $pLink=$(this);if($pLink.closest("li").hasClass("active")&&$pLink.data("plink")){window.location.href=$pLink.data("plink");return false;}});this.parPageObj.hideBrick("message");},getParams:function(row){return Runner.apply({id:Runner.genId(),mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),mastertable:this.masterTName,masterid:this.id,masterpagetype:this.masterPageType,goto:1},row.masterKeys[this.tName]);},getDetails:function(row){var params=this.getParams(row),dt=this;Runner.setIdCounter(params.id+1000);this.fireEvent('beforeShowDetails',this,row);Runner.runnerAJAX(this.ajaxRequestUrl,params,function(respObject){dt.showDetails(respObject,row,params);});},showDetails:function(respObj,row,params){var errContent,$tabsControl,cfg,jsFile;$tabsControl=Runner.pages.PageManager.getTabControl(row.detTd,"details"+row.id);if(respObj.success===false){errContent=Runner.pages.RunnerPage.prototype.getMessageText(Runner.lang.constants.TEXT_NO_RECORDS,true);Runner.pages.PageManager.setTabWithinTabsControl($tabsControl,errContent,"tabdetails"+row.id+"_"+this.tabSettings.tabId,this.getTabLabel(row),false,this.tabSettings.tabIndex);return;}
Runner.setIdCounter(respObj.idStartFrom);Runner.pages.PageSettings.addSettings(this.tName,respObj.settings,false);Runner.applyPagesData(respObj.pagesData);if(this.recsPerRowList>1&&row.detTd&&row.detTd.length&&!$.contains(row.detTd[0],document.body)){delete row.detTd;}
if(!row.detTd){this.createPreviewRow(row);}
row.isShown=true;if(respObj.additionalCSS){Runner.util.ScriptLoader.loadCSS(respObj.additionalCSS);}
if(respObj.CSSFiles){Runner.util.ScriptLoader.loadCSS(respObj.CSSFiles);}
row.detPage=row.detPage||{};cfg=this.getNewDetailPageConfig(respObj,row,params.id);if(Runner.pagesData[params.id].gridTabs){cfg.$gridTabControl=$tabsControl.children('ul');}
if(respObj.additionalJS){for(jsFile in respObj.additionalJS){Runner.util.ScriptLoader.addJS([jsFile],respObj.additionalJS[jsFile]);}
Runner.util.ScriptLoader.onFilesLoaded(function(){row.detPage[this.tName]=Runner.pages.PageManager.initPage(cfg);},this);Runner.util.ScriptLoader.load();}else{row.detPage[this.tName]=Runner.pages.PageManager.initPage(cfg);}},initGridTabs:function(){var pageObj=this;$('[data-pageid='+this.id+'][data-tabid]').on("click",function(e){var $link=$(this),url=$(this).attr('href'),$tab=$link.parent(),$pane;if($tab.hasClass('active')){return;}
$tab.siblings().removeClass('active');$tab.addClass('active');if($link.data('target')){$pane=$($link.data('target'));$pane.addClass('active').siblings().removeClass('active');}
pageObj.$originalTab.addClass('active');pageObj.openContainer=pageObj.detCont[0];pageObj.silentReloading=true;pageObj.reload({tab:$(this).data("tabid")});return false;});},replaceGridTabs:function(){if(!this.$gridTabControl){return;}
var $replacementTabs=$(this.pageData.gridTabs),$originalTab=$('#bsproceed_'+this.shortTName+this.rowId).closest('li'),$originalLink=$originalTab.children('a');$originalTab.hide();this.$gridTabControl.find('[data-tabid][data-pageid='+this.id+']').parent().remove();if(!$originalTab.hasClass('active')){$replacementTabs.removeClass('active');}
this.$originalTab=$originalTab;$replacementTabs.each(function(i){var $tab=$(this),$link=$tab.children('a'),$span=$originalLink.children().clone(),attrMap={};jQuery.each($originalLink.get(0).attributes,function(){attrMap[this.name]=this.value;});attrMap.href=attrMap.href+'&tab='+$link.data('tabid');$span.attr('data-plink',attrMap.href);$link.attr(attrMap);$span.contents()[0].data=$link.text();$link.html('').append($span);});$originalTab.after($replacementTabs);},getNewDetailPageConfig:function(respObj,row,newId){var newTabSettings=jQuery.extend(true,{},this.tabSettings,{tabControlName:"details"+row.id,label:this.getTabLabel(row)});return{tabControl:Runner.pages.PageManager.getTabControl(row.detTd,"details"+row.id),bodyCont:respObj.html,headerCont:respObj.headerCont,footerCont:respObj.footerCont,openMode:Runner.pages.constants.OPENMODE_TABVIEW,tabSettings:newTabSettings,openContainer:row.detTd,tName:this.tName,pageId:newId,rowId:row.id,pageType:this.pageType,controlsMap:respObj.controlsMap[this.tName][this.pageType][newId]||{},viewControlsMap:respObj.viewControlsMap[this.tName][this.pageType][newId]||{},pageMode:Runner.pages.constants.MODE_LIST_DETAILS,detCont:row.detCont,masterKeys:row.masterKeys[this.tName],parId:this.parId,baseParams:this.getDetailPageBaseParams(newId,row.masterKeys[this.tName]),afterSaveDetails:{fn:function(allVals,fields,allKeys,allRowIds,isEdited){this.submitMade=true;this.submitSucceded=true;if(!isEdited){this.updateChildRecNum(row.masterKeys[this.tName]);}
this.fireEvent("detailsSaved",this,allVals,fields,allKeys,allRowIds);},scope:this},afterDeleteDetails:{fn:function(){this.updateChildRecNum(row.masterKeys[this.tName]);},scope:this},saveFailed:{fn:function(respObj,formObj,fieldControls){this.submitMade=true;this.submitSucceded=false;this.fireEvent("saveFailed",this,respObj,formObj);},scope:this},afterInit:{fn:function(){this.fireEvent('afterInit',this,this.proxy,this.id);this.fireEvent('afterShowDetails');},scope:this},replaceGridTabs:this.replaceGridTabs,initGridTabs:this.initGridTabs};},createPreviewRow:function(row){var $lastRecordRow=row.row.filter(":last"),$nextGridRow=$lastRecordRow.next(),$childrenTd=$lastRecordRow.children('td'),previewCellName=this.masterShortTName+"_previewcell",previewRowClass=this.classBasePrefix+(Runner.isBootstrap()?"bs-":"")+'dpreviewrow',detTdselector,colspan,colSpanArr,start,i;if($nextGridRow.hasClass(previewRowClass)){row.detTr=$nextGridRow;detTdselector=this.recsPerRowList>1?"#"+previewCellName+row.id:'.dpinline';row.detTd=$(detTdselector,$nextGridRow);if(this.recsPerRowList>1){row.detTd.addClass('dpinline');}
return;}
row.detTr=$("<tr></tr>").addClass(previewRowClass).insertAfter($lastRecordRow);if(this.recsPerRowList>1){if(this.listGridLayout==Runner.pages.constants.VERTICAL_LAYOUT){for(i=0;i<this.recsPerRowList;i++){$("<td></td>").attr('id',previewCellName+row.detLinksId[i]).addClass('dpframe-cl dpframe-cc dpframe-cr').appendTo(row.detTr);}}else{colSpanArr=[];start=0;$childrenTd.each(function(i,td){if($(td).attr("colid")=="endrecord"){colSpanArr.push(i-start);start=i+1;}});colSpanArr.push($childrenTd.length-start);for(i=0;i<colSpanArr.length;i++){$('<td colspan="'+colSpanArr[i]+'"></td>').attr('id',previewCellName+row.detLinksId[i]).addClass('dpframe-cl dpframe-cc dpframe-cr').appendTo(row.detTr);$("<td></td>").addClass(this.classBasePrefix+'cs').attr('colid',"endrecord").appendTo(row.detTr);}}
row.detTd=$("#"+previewCellName+row.id,row.detTr).addClass('dpinline');}else{colspan=0;$childrenTd.each(function(i,td){colspan+=$childrenTd[i].colSpan;});colspan=this.oldLayout?$childrenTd.length-2:colspan;row.detTd=$("<td></td>").addClass('dpinline dpframe-cc').appendTo(row.detTr).attr('colspan',colspan);if(this.listGridLayout==Runner.pages.constants.VERTICAL_LAYOUT){row.detTd.addClass('dpframe-cl dpframe-cr');return;}
if(this.oldLayout){$("<td></td>").addClass(this.classBasePrefix+'cl dpframe-cl').prependTo(row.detTr);$("<td></td>").addClass(this.classBasePrefix+'cr dpframe-cr').appendTo(row.detTr);}}},getDetailPageBaseParams:function(newId,masterKeys){return Runner.apply({id:newId,mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),masterpagetype:this.masterPageType,mastertable:this.masterTName},masterKeys);},closeDetails:function(row,$link){if(!row.isShown){return;}
for(var tName in row.detPage){Runner.pages.PageManager.unregister(row.detPage[tName].tName,row.detPage[tName].pageId);}
if(Runner.isBootstrap()){if(this.recsPerRowList>1&&$link){var $linkTd=$link.closest('td');$linkTd.removeClass("bs-details-opened");$linkTd.nextUntil("[colid='endrecord']").removeClass("bs-details-opened");$linkTd.prevUntil("[colid='endrecord']").removeClass("bs-details-opened");}else{row.row.removeClass("bs-details-opened");}}
if(this.recsPerRowList>1&&!this.isTdReset(row)){this.resetCell(row);}else{row.detTr.remove();delete row.detTr;row.detTd.remove();delete row.detTd;}
if(row.detCont){row.detCont.remove();delete row.detCont;}
row.isShown=false;},closeDetailsByInd:function(ind){var row=this.getRowByInd(ind);if(row){this.closeDetails(row);}},closeDetailsById:function(rowId){var row=this.getRowById(rowId);if(row){this.closeDetails(row);}},isTdReset:function(row){var removeTd=false,i,dpTd;for(i=0;i<row.detLinksId.length;i++){dpTd=$("#"+this.masterShortTName+"_previewcell"+row.detLinksId[i]);if(row.detLinksId[i]!=row.id){if(dpTd.html()!=''){return false;}
removeTd=true;}}
return removeTd;},resetCell:function(row){row.detTd.empty();if(this.recsPerRowList>1&&Runner.isBootstrap()){row.detTd.removeClass('dpinline');}},destructor:function(){for(var i=0;i<this.rows.length;i++){this.closeDetails(this.rows[i]);}}});Runner.util.details.ListWithoutPreview=Runner.extend(Runner.util.details.InlineDP,{constructor:function(cfg){Runner.util.details.ListWithoutPreview.superclass.constructor.call(this,cfg);this.dpShowType=Runner.pages.constants.DP_NONE;},init:Runner.emptyFn,initLink:function(row,setHref){var key,mKeys=[];for(key in row.masterKeys[this.tName]){mKeys.push(row.masterKeys[this.tName][key]);}
$("#"+this.shortTName+"_preview"+row.id).attr("href",Runner.pages.getUrl(this.tName,this.pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(this.masterTName));}});Runner.AjaxRow=function(inlineRow){this.row=inlineRow;if(!inlineRow){this.row={id:1,gridLayout:""};}}
Runner.AjaxRow.prototype={fieldCell:function(fName){var $span=Runner.getFieldSpan(fName,this.row.id);if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT){return $span.closest("div");}
return $span.closest("[data-field]");},getFieldText:function(fName){var $span=Runner.getFieldSpan(fName,this.row.id);return $span.html();},setFieldText:function(fName,text){var $span=Runner.getFieldSpan(fName,this.row.id);$span.html(text);},getFieldValue:function(fName){if(this.row.rowVals&&typeof this.row.rowVals[fName]!='undefined'){return this.row.rowVals[fName];}
var $span=Runner.getFieldSpan(fName,this.row.id);return $span.attr("val").trim();},setFieldValue:function(fName,value){var $span=Runner.getFieldSpan(fName,this.row.id);$span.attr("val",value);},record:function(){if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){return $(".panel-body","[data-record-id='"+this.row.id+"']");}
return $("[data-record-id='"+this.row.id+"'][data-field]");},getDefaultMessageCell:function(){if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){return this.record();}
return this.record().eq(0);},setMessage:function(message,container){var $messageWrap;if(!container&&this.row.messageContainer){this.row.messageContainer.html(message);return;}
container=container||this.getDefaultMessageCell();$messageWrap=$(".row-message",container);if($messageWrap.length){this.row.messageContainer=$messageWrap.html(message);return;}
if(this.row.gridLayout===Runner.pages.constants.VERTICAL_LAYOUT||this.row.gridLayout===Runner.pages.constants.COLUMNS_LAYOUT){this.row.messageContainer=$("<div class='row-message'></div>").html(message).prependTo(container);}else{this.row.messageContainer=$("<span class='row-message'></span>").html(message).appendTo(container);}},getMessage:function(){if(this.row.messageContainer){return this.row.messageContainer.html();}
return"";},id:function(){return this.row.id;},getRowObject:function(){return this.row;}};