
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;},isSystemCSSFile:function(filePath){return filePath.indexOf("/pages/")===-1;},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);file=_self.cssFilePath(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];if(Runner.ext=="aspx"){filePath=Runner.getFullResourcePath(_self.cssFilePath(files[i]));}else{filePath=_self.cssFilePath(files[i]);}
css=document.createElement('link');css.setAttribute('rel','stylesheet');css.setAttribute('type','text/css');css.setAttribute('href',filePath);head.appendChild(css);}});},cssFilePath:function(file){if(file.indexOf("style.css")!==-1){return file+"?"+settings.global.wizardBuildKey+"&"+settings.global.projectBuildKey;}else if(this.isSystemCSSFile(file)){return file+"?"+settings.global.wizardBuildKey;}else{return file+"?"+settings.global.projectBuildKey;}},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;}
var addKey;if(this.isSystemJSFile(this.jsFiles[idx].name)){addKey="?"+settings.global.wizardBuildKey;}else{addKey="?"+settings.global.projectBuildKey;}
js.setAttribute('src',this.jsFiles[idx].name+addKey);document.getElementsByTagName('HEAD')[0].appendChild(js);return true;},isSystemJSFile:function(filePath){return filePath.indexOf("pageevents")===-1;},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){var self=this;if($.inArray(session,this.loadedSes)==-1){window.setTimeout(function(){self.fireEvent('filesLoaded'+session);},0);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];var $container=$("#"+chartParams.containerId);anychart.licenseKey(Runner.anychartLicense);$.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){$('<div id="'+chartParams.containerId+'_header"></div>').html(data.header).css("text-align","center").appendTo($("#"+chartParams.containerId));$('<div id="'+chartParams.containerId+'_footer"></div>').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++){var $gCont=$('<div id="'+chartParams.containerId+'g'+i+'"></div>').css({width:"100%",height:"100%","float":"left","margin-right":"15px"}).insertAfter($("#"+chartParams.containerId+"_header"));$gCont.css("height","-="+(hHeight+fHeight)+"px");$gCont.css("width",($gCont.width()/data.gauge.length)+"px").css("width","-=15px");Runner.Charts.setupChart(data.gauge[i],{height:$gCont.height(),refreshTime:chartParams.refreshTime,pageId:chartParams.pageId,containerId:chartParams.containerId+'g'+i,width:$gCont.width(),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=false,credits;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-($(window).scrollLeft()||$(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 $clickedMenu=$(e.target).closest(toggle);if($this.length==0){$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($clickedMenu.closest($parent).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}
Runner.getUrlParams=function(){var vars={};var parts=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});return vars;}
$(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.escapeHtml=function(str){if(str===null||str===undefined){return"";}
return str.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;");}
Runner.generateId=(function(){var chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';return function(length){var ret='';for(var i=0;i<length;++i){ret+=chars.charAt(Math.floor(Math.random()*chars.length));}
return ret;}})();Runner.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;});};Runner.Dialog=function(button,params){params=params||{};var title=params['title']||'',_fields=params['fields']||[],header=params['header'];var okString=params.ok!==undefined?params.ok:'OK';var cancelString=params.cancel!==undefined?params.cancel:'Cancel';var fields=_fields.map(function(field,idx){if(typeof field!=='object'){field={name:field};}
field.name=field.name||'';return field;});var html='';if(header!==undefined){html='<div>'+header+'</div>';}
var controls=fields.map(function(field,idx){var label=field.label;if(label===undefined){label=field.name;}
field.name=field.name||'';var controlText='<div class="form-group">';var fieldId=button.btnName+'_control_'+idx;controlText+='<label for="'+fieldId+'">'+label+'</label>';if(field.type==='textarea'){controlText+='<textarea id="'+fieldId+'" class="form-control"></textarea>';}else{controlText+='<input type="text" id="'+fieldId+'" class="form-control">';}
controlText+='</div>';return controlText;});var okButtonId=button.btnName+'_button_ok',cancelButtonId=button.btnName+'_button_cancel';var okButton=okString!==''?('<button class="btn btn-primary" id="'+okButtonId+'">'+okString+'</button>'):'';var cancelButton=cancelString!==''?('<button class="btn btn-default" id="'+cancelButtonId+'">'+cancelString+'</button>'):'';var win=Runner.displayPopup({html:html+controls.join(""),header:title,footer:okButton+' '+cancelButton,afterCreate:function(){fields.forEach(function(field,idx){var fieldId=button.btnName+'_control_'+idx;if(field.value!==undefined){$('#'+fieldId).val(field.value);}});$('#'+button.btnName+'_control_0').focus();}});$('#'+cancelButtonId).on('click',function(){win.close();});$('#'+okButtonId).on('click',function(){fields.forEach(function(field,idx){var fieldId=button.btnName+'_control_'+idx;button.params[field.name]=$('#'+fieldId).val();});win.close();button.submitHandler();});return false;};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.Locking=Runner.extend(Runner.emptyFn,{tName:"",pageId:0,pageObj:null,pageName:"",rowLocking:[],constructor:function(cfg){Runner.apply(this,cfg);this.pageObj=Runner.pages.PageManager.getAt(this.tName,this.pageId);this.shortTName=Runner.pages.PageSettings.getShortTName(this.tName);this.pageName=Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_EDIT);},UnlockRecord:function(keys,sid,func){window.clearInterval(this.rowLocking["timeid"+keys]);this.UnlockDetails();var xmlhttp=$.get(this.pageName,{action:'unlock',keys:escape(keys),sid:sid,rndval:Math.random()},function(xml){})
if(typeof func==="function"){var mscount=0,tfunc=function(){if(mscount>=600||xmlhttp.readyState>=2){func();return;}
mscount+=5;setTimeout(tfunc,5);};tfunc();}},ConfirmLock:function(keys,rowid){var lockObj=this,params={action:'confirm',keys:escape(keys),rndval:Math.random()};$.get(this.pageName,params,function(xml){if(xml==''){return;}
var arrCntrl=Runner.controls.ControlManager.getAt(lockObj.tName);for(var i=0;i<arrCntrl.length;i++){if(arrCntrl[i].id==rowid){arrCntrl[i].setDisabled();}}
$('.rnr-locking').html(xml).show();Runner.addDisabledClass($('a[id=saveButton'+lockObj.pageId+']'));clearInterval(lockObj.rowLocking['timeid'+keys]);},"html");},UnlockAdmin:function(keys,oldid,startEdit){var lockObj=this,params={action:'lockadmin',keys:escape(keys),startEdit:startEdit,oldid:oldid,rndval:Math.random()};$.get(this.pageName,params,function(xml){if(xml=='lock'){var arrCntrl=Runner.controls.ControlManager.getAt(lockObj.tName);for(var i=0;i<arrCntrl.length;i++){arrCntrl[i].setEnabled();}
Runner.delDisabledClass($('a[id=saveButton'+lockObj.pageId+']'));$('#message_block'+lockObj.pageId).empty();}
$('.rnr-locking').hide();});},UnlockRecordInline:function(keys,sync){if(!keys){return;}
window.clearInterval(this.rowLocking["timeid"+keys]);this.UnlockDetails();var keyArr=[],tmpArr=keys.split("&"),pos,getParams,i;for(i=0;i<tmpArr.length;i++){pos=tmpArr[i].indexOf("=");keyArr.push(tmpArr[i].substr(pos+1));}
getParams={url:this.pageName,data:{action:'unlock',keys:escape(keyArr.join("&")),rndval:Math.random()},success:function(xml){},};if(sync){getParams.async=false;}
$.ajax(getParams);},StartLocking:function(pageObj,rowid,sKeys,confirmTime){this.rowLocking['timeid'+sKeys]=setInterval(function(){pageObj.locking.ConfirmLock(sKeys,rowid);},confirmTime*1000);},ResetSetInterval:function(keys){if(!keys){return;}
window.clearInterval(this.rowLocking["timeid"+keys]);},UnlockDetails:function(){if(!Runner.pages.PageSettings.getTableData(this.pageObj.tName,"isShowDetails")||!this.pageObj.controlsMap.dpTablesParams){return;}
var dpTablesParams=this.pageObj.controlsMap.dpTablesParams,detailPage,i;for(i=0;i<dpTablesParams.length;i++){detailPage=this.pageObj.dpObjs[dpTablesParams[i].tName].detailsPageObj;if(detailPage.inlineAdd||detailPage.inlineEdit){(detailPage.inlineAdd||detailPage.inlineEdit).cancelAll();}}}});Runner.namespace('Runner.s508');Runner.s508=Runner.extend(Runner.emptyFn,{calc508column:true,s508td:null,s508column:-1,gridObj:null,pageId:-1,pageURL:null,maxPages:1,isUseInlineEdit:false,constructor:function(cfg){Runner.apply(this,cfg);},init:function(){this.section508setEvents();this.s508pagination();this.s508jumpto();if(this.isUseInlineEdit){this.s508inlineEdit();}},section508setEvents:function(focusedControl,setFocusInTD){if(!this.gridObj){return false;}
if(this.gridObj.attr("s508table")==undefined){this.gridObj.attr("s508table","true");this.setFocusFirstElement();}
var self=this,s508eventArrow=function(e){self.calc508column=true;switch(e.which){case 40:self.calc508column=false;self.click_arrow(this,"next",self.s508column);break;case 38:self.calc508column=false;self.click_arrow(this,"prev",self.s508column);break;case 9:self.calc508column=true;break;default:self.calc508column=true;break;}},focusHandler=function(){if(self.calc508column){self.s508column=self.getControlColumn(this);}};$("input,a,textarea,select",this.gridObj).each(function(){$elem=$(this);if(!$elem.attr("event508")){$elem.attr("event508","true").bind({keydown:s508eventArrow,focus:focusHandler});}});if(focusedControl){this.s508column=this.getControlColumn(focusedControl.spanContElem);}
if(setFocusInTD&&this.s508td){var func=function(){$("input:first,a:first,textarea:first,select:first",self.s508td).focus();};setTimeout(func,100);$("[id^=iEditLink"+this.pageId+"_]",this.s508td).bind("keydown",function(e){if(e.altKey&&e.which==69){$(this).click();Runner.Event.prototype.stopEvent(e);}});}},getControlColumn:function(control){var parentTr=this.find508tr(control),parentTrFound=false,tdObj=false;$(control).parents().each(function(k,elem){if(parentTrFound){return;}
if(elem===parentTr){parentTrFound=true;}
if($(elem).is("td")){tdObj=elem;}});var numberTd=0,colspanAttr="",tdFound=false;$(parentTr).children().each(function(k,elem){if(elem===tdObj){tdFound=true;}
if(tdFound){return;}
numberTd++;colspanAttr=$(elem).attr("colspan");if(colspanAttr){numberTd+=parseInt(colspanAttr)-1;}});this.s508td=tdObj;return numberTd;},find508tr:function(control){var trObj=false,mainTableFound=false;$(control).parents().each(function(k,elem){if(mainTableFound){return;}
if($(elem).is("tr")){trObj=elem;}
if($(elem).attr("s508table")=="true"){mainTableFound=true;}});return trObj;},click_arrow:function(control,direction,colnum){var tr=$(this.find508tr(control)),isNext=direction=="next",trobj=isNext?$(tr).next():$(tr).prev();while($("input,a,textarea,select",trobj).length==0&&$(trobj).get(0)||$(trobj).css("display")=="none"){trobj=isNext?$(trobj).next():$(trobj).prev();}
if(!isNext&&!$(trobj).get(0)&&$(tr).parents().is("tbody")&&$("thead tr:visible",this.gridObj).length>0){trobj=$("thead tr:visible",this.gridObj).get(0);}
if(isNext&&!$(trobj).get(0)&&$(tr).parents().is("thead")&&$("tbody tr:visible",this.gridObj).length>0){trobj=$("tbody tr:visible",this.gridObj).get(0);}
var altElem=focusSet=false;if(colnum==-1){$("input:first,a:first,textarea:first,select:first",trobj).focus();}else{$(trobj).children().each(function(k,elem){if(focusSet){return;}
if($("input:first,a:first,textarea:first,select:first",elem).length>0){if(k<colnum&&altElem||!altElem){altElem=elem;}
if(k==colnum){$("input:first,a:first,textarea:first,select:first",elem).focus();focusSet=true;}}});if(!focusSet&&altElem){$("input:first,a:first,textarea:first,select:first",altElem).focus();}}},setFocusFirstElement:function(sObj){$("input:first,a:first,textarea:first,select:first",$("tbody tr:visible:first",this.gridObj)).focus();},getURLParam:function(name){name=name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS),results=regex.exec(window.location.href);return results==null?"":results[1];},s508pagination:function(){var self=this,s508eventPagination=function(e){NumberPage=self.getURLParam("goto");if(NumberPage==""){NumberPage=1;}
if(e.ctrlKey&&e.which==37){if(NumberPage>1){NumberPage--;window.location.href=self.pageURL+"?goto="+NumberPage;}else{NumberPage=1;}}
if(e.ctrlKey&&e.which==39){if(NumberPage<self.maxPages){NumberPage++;window.location.href=self.pageURL+"?goto="+NumberPage;}else{NumberPage=self.maxPages;}}};$(document).keydown(s508eventPagination);},s508jumpto:function(){var self=this,s508eventJumpTo=function(e){if(e.altKey&&e.which==70){$("#ctlSearchFor"+self.pageId).focus();Runner.Event.prototype.stopEvent(e);}
if(e.altKey&&e.which==77){$("[id^=itemlink]:first").focus();Runner.Event.prototype.stopEvent(e);}};$(document).keydown(s508eventJumpTo);},s508inlineSaveCancel:function(tr_id){var self=this;$("#gridRow"+tr_id).unbind("keydown").bind("keydown",function(e){if(e.altKey&&e.which==83){$("#saveLink"+tr_id).click();Runner.Event.prototype.stopEvent(e);}
if(e.altKey&&e.which==67){$("#revertLink"+tr_id).click();self.s508setFocusToRow(tr_id);Runner.Event.prototype.stopEvent(e);}});},s508setFocusToRow:function(id){$("#gridRow"+id).unbind("keydown");$("#gridRow"+id).find("input:first,a:first,textarea:first,select:first").focus();},s508inlineEdit:function(){var self=this;$("[id^=iEditLink]").each(function(){var parent_tr=$(this).parent("td").parent("tr"),record_id=this.id;$("input,a,textarea,select",parent_tr).each(function(){$(this).keydown(function(e){if(e.altKey&&e.which==69){$("#"+record_id).click();Runner.Event.prototype.stopEvent(e);}});});});}});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','datevalidation','acceptfiletypes'],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:validationRes=window[validatorName](control.getStringValue());break;case this.validatorConsts.userNew: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%',Runner.escapeHtml(strValue.slice(0,100)));control.markInvalidWidthCusttomMessages("DenyDuplicated",[message]);if(control.isFocusAllowed()&&!control.isSetFocus&&Runner.pages.RunnerPage.prototype.isFirstInvalidControl(control)){control.setFocus();}});return true;},"DateValidation":function(){return this.control.validateDate();},"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;},"AcceptFileTypes":function(sVal){var re=new RegExp(this.control.acceptFileTypes||".+$","i");var pos=Math.max(sVal.lastIndexOf('\\'),sVal.lastIndexOf('/'));var fileName=sVal.substr(pos+1);if(fileName&&!re.test(fileName)){return Runner.lang.constants.ERROR_ACCEPT_FILE_TYPES;}
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,params:{},submitHandler:null,pageObj: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);}}}else{rowData.id=-1;}
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){this.pageObj=pageObj;if(Runner.isDisabledButton(this.elem)){e.preventDefault();e.stopPropagation();return;}
var ctrl=this,ajax=ctrl,rowData=this.getRowData(pageObj,isInlineAdd),params={buttId:this.btnName,rndVal:new Date().getTime(),fieldsData:{},masterData:{},masterTable:pageObj.masterTable||null,table:pageObj.pageTable,page:pageObj.pageName},isManyKeys=0,keyObject={},location,res,$checkboxes,i,j,reqParams,row=null,recordControls=[],masterPageObj=null,submit;if(inlineAddRow||rowData.id!==-1){row=new Runner.AjaxRow(pageObj,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();});}}
var submitted=false;submit=function(){if(submitted){return;}
submitted=true;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(result){pageObj.buttonEventAfter[ctrl.btnName](JSON.parse(result),ctrl,pageObj,proxy,pageid,rowData,row,params);ctrl.setEnabled();});}
this.setDisabled();ctrl.params=params;ctrl.submitHandler=submit;ctrl.submit=submit;res=pageObj.buttonEventBefore[this.btnName](params,ctrl,pageObj,proxy,pageid,rowData,row,submit);if(res===false){this.setEnabled();e.preventDefault();e.stopPropagation();return;}
submit();e.preventDefault();e.stopPropagation();},dialog:function(params){return Runner.Dialog(this,params);},addPDF:function(name,params,callback){var button=this;Runner.PDF.create(params,this.pageObj,function(pdf){pdf.getBase64(function(blob){button.params[name]=blob;button.params._base64fields=button.params._base64fields||[];button.params._base64fields.push(name);return callback();})});return false;},});Runner.AjaxRow=function(pageObj,inlineRow){this.row=inlineRow;this.pageObj=pageObj;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){var ctrl=Runner.getControl(this.row.id,fName);if(ctrl){return ctrl.getValue();}
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;},recordId:function(){return this.row.id;},getRowObject:function(){return this.row;},getKeys:function(){return this.row.keys;},getDetails:function(){return this.row.detPage;}};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:cfg.acceptFileTypes=Runner.pages.PageSettings.getFieldData(tName,fName,"acceptFileTypes",pageType);return new Runner.controls.ImageField(cfg);case Runner.controls.constants.EDIT_FORMAT_DATABASE_FILE:cfg.acceptFileTypes=Runner.pages.PageSettings.getFieldData(tName,fName,"acceptFileTypes",pageType);return new Runner.controls.FileField(cfg);case Runner.controls.constants.EDIT_FORMAT_FILE:if(Runner.pages.PageSettings.getFieldData(tName,fName,"compatibilityMode",pageType)){cfg.acceptFileTypes=Runner.pages.PageSettings.getFieldData(tName,fName,"acceptFileTypes",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)||[];cfg.listPageId=Runner.pages.PageSettings.getFieldData(tName,fName,"listPageId",pageType)||"";cfg.addPageId=Runner.pages.PageSettings.getFieldData(tName,fName,"addPageId",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.pageObj.getRowById(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){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);}}},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+']',this.pageObj.pageCont):[];if(this.pageObj.isBootstrap()){if(!this.isInline){this.errContainer=$('<strong class="help-block"></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};}
updContext.dependentsReloaded=updContext.dependentsReloaded||[];if($.inArray(this.fieldName,updContext.dependentsReloaded)!=-1){return;}
updContext.dependentsReloaded.push(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,pageId){var cfg={table:pageObject.tName,pageType:pageType,goodFieldName:Runner.goodFieldName(baseCfg.fieldName),pageContext:pageContext,pageObject:pageObject,pageId:pageId||pageObject.id,};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,{pageId:"",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,imgConfig:null,constructor:function(cfg){Runner.viewControls.ViewImageField.superclass.constructor.call(this,cfg);},init:function(){var ctrl=this;var $imageItems=$('[data-itemid][data-pageid='+this.pageId+'][data-field="'+this.goodFieldName+'"]');$imageItems.each(function(){var $img=$(this).find('.r-images:not([data-initialized])');if(!$img.length){return;}
ctrl.initImageControl($img,$(this));});},getConfig:function($img){if(this instanceof Runner.viewControls.ViewImageField&&this.imgConfig){return this.imgConfig}
var config={multiple:$img.data("multiple"),maxImages:$img.data("max-images"),thumbnails:$img.data("thumbnails"),gallery:$img.data("gallery"),galleryMode:$img.data("gallery-mode"),captionMode:$img.data("caption-mode"),width:$img.data("width"),height:$img.data("height"),thWidth:$img.data("th-width"),thHeight:$img.data("th-height"),fullWidth:!!$img.data("fullwidth"),border:!!$img.data("border"),};if(this instanceof Runner.viewControls.ViewImageField){this.imgConfig=config;}
return config;},initImageControl:function($img,$item){var imgConfig=this.getConfig($img),recordId=$item.data('record-id'),cssPrefix='[data-pageid="'+this.pageId+'"]'
+'[data-itemid="'+$item.data('itemid')+'"]'
+(recordId?'[data-record-id="'+recordId+'"]':'');$img.attr('data-initialized','');var images=$img.data('images').map(function(imgDesc){return{url:imgDesc.thumbnail||imgDesc.image,}});if(!images||!images.length){$img.hide();return;}
if(this.imgConfig.gallery){this.initGallery();}
if(imgConfig.multiple==1){this.createMasonry($img,cssPrefix,images);}else if(!imgConfig.thumbnails){this.createBasic($img,cssPrefix,images);}else{this.createThumbnails($img,cssPrefix,images);}},createBasic:function($img,cssPrefix,images){var imgConfig=this.getConfig($img);$img.addClass(imgConfig.multiple==2?'r-vertcal-images':'r-horizontal-images');var imgIdx=0;images.slice(0,imgConfig.maxImages||undefined).forEach(function(pic){$('<img>').attr('src',pic.url).attr('data-gallery-image',imgIdx++).appendTo($img);});var desktopStyle='';if(imgConfig.width){desktopStyle+='max-width:'+imgConfig.width+'px;\n';desktopStyle+='width:'+imgConfig.width+'px;\n';}
if(imgConfig.height){desktopStyle+='max-height:'+imgConfig.height+'px;\n';}
var desktopStyles={};desktopStyles[cssPrefix+' .r-images > img']=desktopStyle;var mobileStyles={};mobileStyles[cssPrefix+' .r-images > img']='width: 100%;';this.appendStyles($img,mobileStyles,desktopStyles);},createThumbnails:function($img,cssPrefix,images){var imgConfig=this.getConfig($img);$img.addClass(imgConfig.multiple==2?'r-vertcal-thumbs':'r-horizontal-thumbs');var imgIdx=0;images=images.slice(0,imgConfig.maxImages||undefined);images.forEach(function(pic){$('<div>').css({}).attr('data-gallery-image',imgIdx++).appendTo($img).append($("<img></img>").attr('src',pic.url));});if(!imgConfig.thWidth){imgConfig.thWidth=imgConfig.thHeight||150;}
imgConfig.thHeight=imgConfig.thHeight||imgConfig.thWidth;var imgMargin=1;var style='',desktopStyle='';style+='width:'+(imgConfig.thWidth-2*imgMargin)+'px;\n';style+='height:'+(imgConfig.thHeight-2*imgMargin)+'px;\n';var mobileStyle=imgConfig.thWidth<250&&images.length>1?'width: calc( 50% - '+(2*imgMargin)+'px );\nheight: '+(50*imgConfig.thHeight/imgConfig.thWidth)*0.8+'vw;':'width: 100%;\nheight: '+(100*imgConfig.thHeight/imgConfig.thWidth)*0.8+'vw;'
var desktopStyles={},mobileStyles={};desktopStyles[cssPrefix+' .r-images > div']=style;mobileStyles[cssPrefix+' .r-images > div']=mobileStyle;var vScrollBarWidth=imgConfig.multiple==2?20:0;var hScrollBarWidth=imgConfig.multiple==2?0:20;var imgAreaWidth=imgConfig.maxImages!=1?imgConfig.width:imgConfig.thWidth;var imgAreaHeight=imgConfig.maxImages!=1?imgConfig.height:imgConfig.thHeight;if(imgAreaWidth){desktopStyle+='width:'+(imgAreaWidth+hScrollBarWidth)+'px;\n';}
if(imgAreaHeight){desktopStyle+='max-height:'+(imgAreaHeight+vScrollBarWidth)+'px;\n';}
desktopStyles[cssPrefix+' .r-images']=desktopStyle;this.appendStyles($img,{},desktopStyles,mobileStyles);},createMasonry:function($img,cssPrefix,images){$img.addClass('r-masonry');var imgConfig=this.getConfig($img);if(!imgConfig.width){imgConfig.width=imgConfig.height?imgConfig.height*1.5:600;}
if(!imgConfig.height){imgConfig.height=imgConfig.height?imgConfig.height/1.5:400;}
var styles={};var desktopStyle='width: '+imgConfig.width+'px;\n'+'height: '+imgConfig.height+'px;\n';var mobileStyle='height: '+Math.floor(100*imgConfig.height/imgConfig.width)+'vw;\n';var imgIdx=0;var addRow=function(urls,height,rowIdx,morePics){rowIdx=rowIdx||0;var $row=$("<div></div>").addClass('r-masonry-row').attr('data-row',rowIdx).appendTo($img);urls.forEach(function(url,n){var pic=$("<div>").addClass('').css({}).appendTo($row).append($("<img></img>").attr('src',url.url));if(imgConfig.gallery){pic.attr('data-gallery-image',imgIdx++)}
if(n==urls.length-1&&morePics){pic.attr('data-more-pics',morePics)}});var rowSelector=cssPrefix+' .r-images > [data-row="'+rowIdx+'"]';if(height){styles[rowSelector]=(styles[rowSelector]||'')
+'height: '+height+';\n';}}
if(images.length==1){addRow(images,'100%');}else if(images.length==2){var vertical=!imgConfig.height||imgConfig.width&&imgConfig.width<1.3*imgConfig.height;if(vertical){addRow(images.slice(0,1),'50%',0);addRow(images.slice(1),'50%',1);}else{addRow(images);}}else if(images.length==3){addRow(images.slice(0,1),'60%',0);addRow(images.slice(1),'40%',1);}else if(images.length==4){addRow(images.slice(0,2),'50%',0);addRow(images.slice(2),'50%',1);}else if(images.length>=5){addRow(images.slice(0,2),'66%',0);addRow(images.slice(2,5),'34%',1,images.length-5);}
var selNotIntegrated=cssPrefix+':not([data-itemtype="integrated_edit_field"])',selImages=cssPrefix+' .r-images';var desktopStyles={},mobileStyles={};desktopStyles[selNotIntegrated]=desktopStyles[selImages]=desktopStyle;mobileStyles[selNotIntegrated]=mobileStyles[selImages]=mobileStyle;this.appendStyles($img,styles,desktopStyles,mobileStyles);},appendStyles:function($img,styles,desktopStyles,mobileStyles){var block=Object.keys(styles).map(function(sel){return sel+'{\n'+styles[sel]+'}';}).join('\n');var dblock=Object.keys(desktopStyles||{}).map(function(sel){return sel+'{\n'+desktopStyles[sel]+'}';}).join('\n');var mblock=Object.keys(mobileStyles||{}).map(function(sel){return sel+'{\n'+mobileStyles[sel]+'}';}).join('\n');if(this.imgConfig.fullWidth){$('<style>'+
block+'@media print, (min-width: 768px) {\n'+
dblock+'}\n'+'@media screen and (max-width: 767px) {\n'+
mblock+'}\n'+'</style>').appendTo($img);}else{$('<style>'+
block+'\n'+
dblock+'</style>').appendTo($img);}},imageItemTypes:function(){return['grid_field','edit_field','integrated_edit_field'];},initGallery:function(){$(this.pageContext).off('click.photoswipe').on('click.photoswipe','[data-itemtype="grid_field"][data-pageid='+this.pageId+'] [data-gallery-image],'+'[data-itemtype="edit_field"][data-pageid='+this.pageId+'] [data-gallery-image],'+'[data-itemtype="integrated_edit_field"][data-pageid='+this.pageId+'] [data-gallery-image]',function(){var index=$(this).attr('data-gallery-image');Runner.viewControls.ViewImageField.prototype.openGallery($(this).closest('.r-images'),parseInt(index));});if(0==$('.pswp').length){$('<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">'+'     <div class="pswp__bg"></div>'+'     <div class="pswp__scroll-wrap">'+'      <div class="pswp__container">'+'       <div class="pswp__item"></div>'+'       <div class="pswp__item"></div>'+'       <div class="pswp__item"></div>'+'      </div>'+'      <div class="pswp__ui pswp__ui--hidden">'+'       <div class="pswp__top-bar">'+'        <div class="pswp__counter"></div>'+'        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>'+'        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>'+'        <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>'+'        <div class="pswp__preloader">'+'         <div class="pswp__preloader__icn">'+'         <div class="pswp__preloader__cut">'+'          <div class="pswp__preloader__donut"></div>'+'         </div>'+'         </div>'+'        </div>'+'       </div>'+'       <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">'+'        <div class="pswp__share-tooltip"></div> '+'       </div>'+'       <button class="pswp__button pswp__button--arrow--left" >'+'       <span class="glyphicon glyphicon-arrow-left"></span>'+'       </button>'+'       <button class="pswp__button pswp__button--arrow--right"> '+'       <span class="glyphicon glyphicon-arrow-right"></span>'+'       </button>'+'       <div class="pswp__caption">'+'        <div class="pswp__caption__center"></div>'+'       </div>'+'      </div>'+'     </div>'+'    </div>').appendTo(document.body);}},openGallery:function($img,idx){var imgConfig=Runner.viewControls.ViewImageField.prototype.getConfig($img);if(!imgConfig.gallery){return;}
var $item=$img.closest('[data-itemid]');var selector;if(imgConfig.galleryMode==1){selector=$img;}else if(imgConfig.galleryMode==2&&$item.is('[data-record-id]')){selector='[data-pageid="'+$item.data('pageid')+'"][data-record-id="'+$item.data('record-id')+'"] .r-images';}else{selector='[data-pageid="'+$item.data('pageid')+'"] .r-images';}
var images=[];$(selector).each(function(){if($(this).is($img)){idx+=images.length;}
images=images.concat(Runner.viewControls.ViewImageField.prototype.readPictures($(this)));});if(!images.length){return;}
var gallery=new PhotoSwipe($('.pswp')[0],PhotoSwipeUI_Default,images,{index:idx});gallery.init();},readPictures:function($img){return $img.data('images').map(function(pic){var ret={src:pic.image,};var captionMode=$img.data('caption-mode');if(captionMode==2){ret.title=pic.filename;}else if(captionMode==3){ret.title=$img.data('caption');}
return ret;});}});Runner.viewControls["File-based Image"]=Runner.viewControls.ViewImageField;Runner.viewControls["Database Image"]=Runner.viewControls.ViewImageField;Runner.viewControls.ViewFileField=Runner.extend(Runner.viewControls.ViewControl,{constructor:function(cfg){Runner.viewControls.ViewFileField.superclass.constructor.call(this,cfg);}});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);}});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();}},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);},getDispElem:function(){return this.readonlyElem;},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);},"edited":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);},"edited":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.RTECKBase=Runner.extend(Runner.controls.RTEField,{editor:null,constructor:function(cfg){Runner.controls.RTECKBase.superclass.constructor.call(this,cfg);this.controlElementToDisable=$("#disabledCKE_"+this.valContId);this.initCKEditor();if(this.editor){this.initCustomEvents();}},getEditor:function(){return this.editor||false;},assignListOfEvents:function(){this.addEvent(["edited","editing"]);},getValue:function(){return this.editor?this.editor.getData():false;},setValue:function(val){var readOnly=this.isReadonly();if(readOnly){this.makeReadWrite();}
if(!this.editor){readOnly&&this.makeReadonly();return false;}
this.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();},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.RTECK=Runner.extend(Runner.controls.RTECKBase,{initCKEditor:function(){if(!this.appearOnPage()||!window.CKEDITOR){return;}
var nHeight=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,'nHeight',this.pageType);CKEDITOR.replace(this.valContId,{height:nHeight});this.editor=window.CKEDITOR.instances[this.valContId];},addEditEditingListeners:function(){var ctrl=this;if(!this.editor){return;}
this.editor.on("instanceReady",function(){ctrl.editor.document.on("keyup",function(e){if(!e||!Runner.isAcceptableKeyCode(e)){return;}
ctrl.fireEvent("editing");});});this.editor.on("blur",function(e){ctrl.fireEvent("edited");});this.addDelayedEventsListeners();},destructor:function(){this.editor&&CKEDITOR.remove(this.editor);},setFocusOnEditor:function(){var ctrl=this;if(!this.editor){return;}
if(!this.editor.container){this.editor.on('instanceReady',function(){ctrl.editor.focus();ctrl.scrollToElem($(ctrl.editor.container.$));});return;}
this.editor.focus();this.scrollToElem($(editor.container.$));},});Runner.controls.RTECK5=Runner.extend(Runner.controls.RTECKBase,{creationPromise:null,initCKEditor:function(){if(!this.appearOnPage()||!window.ClassicEditor){return;}
var ctrl=this;this.creationPromise=ClassicEditor.create(document.querySelector('#'+this.valContId)).then(function(editor){ctrl.editor=editor;ctrl.initCustomEvents();});},addEditEditingListeners:function(){var ctrl=this,editor=this.getEditor();if(!editor){return;}
this.editor.model.document.on('change:data',function(evt,name,value){ctrl.fireEvent("editing");});this.editor.editing.view.document.on('change:isFocused',function(evt,name,value){if(!value){ctrl.fireEvent("edited");}});this.addDelayedEventsListeners();},destructor:function(){this.editor&&this.editor.destroy();},setFocusOnEditor:function(){var ctrl=this;if(this.editor){this.editor.editing.view.focus();return;}
if(!this.creationPromise){return;}
this.creationPromise.then(function(){ctrl.editor.editing.view.focus();});}});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,acceptFileTypes:undefined,constructor:function(cfg){Runner.controls.ImageField.superclass.constructor.call(this,cfg);if(cfg.acceptFileTypes){this.addValidation("AcceptFileTypes");}},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,acceptFileTypes:undefined,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);});}}
if(cfg.acceptFileTypes){this.addValidation("AcceptFileTypes");}},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"&&type!="AcceptFileTypes"||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
+"&page="+this.pageObj.pageName
+"&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.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,intervalStart:false,intervalEnd:false,intervalErrorMessage:null,notAllowedDays:null,bsDateTimePicker:null,weekdays:"",weekdayMessage:"",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.notAllowedDays={};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();}
this.addValidation("DateValidation");this.weekdays=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"weekdays",this.pageType);if(this.weekdays){this.weekdays=JSON.parse(this.weekdays);}
if(this.weekdays&&this.weekdays.length){this.weekdayMessage=Runner.pages.PageSettings.getFieldData(this.table,this.fieldName,"weekdayMessage",this.pageType);for(var day=0;day<7;++day){if(this.weekdays.indexOf(day)==-1){this.toggleWeekDay(day,false,this.weekdayMessage);}}}},initBSDatepicker:function(){if(!this.useDatePicker){return;}
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),minDate=this.toJSDate(moment().subtract(initialYear,'years').startOf("year")),maxDate=this.toJSDate(moment().add(lastYear,'years').endOf("year")),options={showTodayButton:true,showClose:true,minDate:minDate,maxDate:maxDate,},outerContainerForIE;this.intervalStart=minDate;this.intervalEnd=maxDate;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){this.bsDateTimePicker=$("#"+this.valContId).parents('.bs-date-control');options.format="YYYY-M-D";options.widgetPositioning={horizontal:Runner.isDirRTL()?'left':'right'};options.showTime=this.showTime;this.bsDateTimePicker.datetimepicker(options);ctrl.on("focus",function(){ctrl.bsDateTimePicker.data("DateTimePicker").hide();});this.bsDateTimePicker.on("dp.change",function(e){ctrl.setValue(e.date.toDate(),true);});this.imgCal=$('#imgCal_'+this.valContId).on('click',function(){ctrl.setCorrectAmPmMoment();ctrl.bsDateTimePicker.data("DateTimePicker").toggle();return false;}).on("blur",function(){ctrl.bsDateTimePicker.data("DateTimePicker").hide();});}else if(this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_INLINE||this.dateEditType==Runner.controls.constants.EDIT_DATE_SIMPLE_DP){this.bsDateTimePicker=this.valueElem.parents(".input-group");ctrl.setCorrectAmPmMoment();options.format=this.getDateFormatString().replace(/yy/g,"YYYY").toUpperCase();options.format+=this.showTime?' '+this.getTimeFormatString():'';options.showTime=this.showTime;this.bsDateTimePicker.datetimepicker(options);this.imgCal=$('#imgCal_'+this.valContId).on('click',function(){ctrl.setCorrectAmPmMoment();});}
if(!outerContainerForIE&&this.bsDateTimePicker&&(this.isInline||this.pageObj.openMode!=Runner.pages.constants.OPENMODE_PRELOADED)){this.bsDateTimePicker.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"&&type!=="DateValidation"||this.mode===Runner.controls.constants.MODE_SEARCH){return;}
Runner.controls.DateField.superclass.addValidation.call(this,type);},toggleWeekDay:function(days,enable,message){var ctrl=this;if(!Array.isArray(days)){days=[days];}
days.forEach(function(day){if(!enable){ctrl.notAllowedDays[day]=message;}else{delete ctrl.notAllowedDays[day];}});this.validate(["DateValidation"]);if(this.pageObj.isBootstrap()&&this.useDatePicker){this.bsDateTimePicker.data('DateTimePicker').daysOfWeekDisabled(Object.keys(this.notAllowedDays));}},setAllowedInterval:function(begin,end,message){this.intervalStart=this.toJSDate(begin);this.intervalEnd=this.toJSDate(end);this.intervalErrorMessage=message;this.validate(["DateValidation"]);if(this.pageObj.isBootstrap()&&this.useDatePicker){var picker=this.bsDateTimePicker.data('DateTimePicker'),useCurrent=picker.useCurrent();picker.useCurrent(false);picker.minDate(false);picker.maxDate(false);picker.minDate(this.intervalStart||false);picker.maxDate(this.intervalEnd||false);picker.useCurrent(useCurrent);}},getAllowedInterval:function(){return[this.intervalStart,this.intervalEnd];},validateDate:function(){var value=this.getValue(),intervalMessage=false,day;if(!value){return true;}
if(this.intervalStart&&this.intervalEnd&&(value<this.intervalStart||value>this.intervalEnd)){intervalMessage=this.intervalErrorMessage||Runner.lang.constants.TEXT_INLINE_FIELD_DATE_NOT_IN_INTERVAL;}else if(this.intervalStart&&value<this.intervalStart){intervalMessage=this.intervalErrorMessage||Runner.lang.constants.TEXT_INLINE_FIELD_DATE_EARLIER_THAN_START;}else if(this.intervalEnd&&value>this.intervalEnd){intervalMessage=this.intervalErrorMessage||Runner.lang.constants.TEXT_INLINE_FIELD_DATE_LATER_THAN_END;}
if(intervalMessage){if(this.intervalStart){intervalMessage=intervalMessage.replace("start",this.printDateTime(this.intervalStart,this.dateFormat));}
if(this.intervalEnd){intervalMessage=intervalMessage.replace("end",this.printDateTime(this.intervalEnd,this.dateFormat));}
return intervalMessage;}
day=value.getDay();if(this.notAllowedDays.hasOwnProperty(day)){if(this.notAllowedDays[day]!==undefined)
return this.notAllowedDays[day];else
return Runner.lang.constants.TEXT_INLINE_FIELD_DATE_NOT_ALLOWED_DAY;}
return true;},toJSDate:function(date){var dateObj=date;if(typeof date==="string"){dateObj=this.parseDateTime(date,this.dateFormat);}else if(date instanceof moment){dateObj=date.toDate();}
return this.isDateObject(dateObj)?dateObj:null;},setValue:function(newDate){},getMomentValue:function(){return moment(this.getValue());},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);}else if(newDate instanceof moment){dateObj=newDate.toDate();}
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()||"").toString().trim(),monthVal=(this.valueElem["month"].val()||"").toString().trim(),yearVal=(this.valueElem["year"].val()||"").toString().trim();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);}else if(newDate instanceof moment){dateObj=newDate.toDate();}
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('');if(this.valueElem["day"].length){this.valueElem["day"].get(0).selectedIndex=0;}
if(this.valueElem["month"].length){this.valueElem["month"].get(0).selectedIndex=0;}
if(this.valueElem["year"].length){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:{page:this.addPageId,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.displayValue,respObj.linkValue);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,page:this.pageObj.pageName,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);if(this.masterTName&&this.mainMasterFields.length){ajaxParams.masterData=JSON.stringify(this.getMasterContolData());}
Runner.runnerAJAX(Runner.getPageUrl("autocomplete"),ajaxParams,function(respObj){ctrl.updateLookupData(respObj.data||[],selectedValue,updContext);ctrl.processAutofillDataOnReload(updContext);ctrl.fireEvent("change",updContext);ctrl.clearInvalid();});},processAutofillDataOnReload:function(updContext){if(updContext&&updContext.values&&updContext.values[this.fieldName]){this.setValue(updContext.values[this.fieldName],true,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,page:this.pageObj.pageName,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');divWrapper.children().remove();this.radioElemsArr=[];this.radioElemsCount=0;},addRadio:function(text,value){var $radioButton,$radioLabel,delim='&nbsp;',ind=this.radioElemsArr.length,$divWrapper,$spanWrapper;if(Runner.isPD()){$divWrapper=$('div[data-lookup-options]',this.spanContElem);}else{$divWrapper=$('div',this.spanContElem).not('.rnr-error-text')}
$spanWrapper=$('<span class="radio"><label></label></span>').appendTo($divWrapper);$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',$spanWrapper).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');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,$spanWrapper;if(Runner.isPD()){$divWrapper=$('div[data-lookup-options]',this.spanContElem);}else{$divWrapper=$('div',this.spanContElem).not('.rnr-error-text')}
$spanWrapper=$('<span class="checkbox"><label></label></span>').appendTo($divWrapper);$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=$('<span>').attr('id','data_'+this.valContId+'_'+ind).addClass('rnr-checkbox-label').html(text);$('label',$spanWrapper).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,page:this.pageObj.pageName,table:this.shortTableName,searchField:this.fieldName,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();this.reloadDependentCtrls(updateContext,nullEvent);}});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();},destroySuggest:function(){this.destroyDiv();},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();if(this.pageObj.isBootstrap()){if(Runner.isDirRTL()){this.lookupDiv.css({left:"auto",top:dElementOffset.top+$displayedElem.outerHeight()+"px",right:$(window).width()-dElementOffset.left-$displayedElem.outerWidth()+"px"});}else{this.lookupDiv.css({top:dElementOffset.top+$displayedElem.outerHeight()+"px",left:dElementOffset.left+"px"});}
this.lookupDiv.addClass('dropdown-menu').css({display:"block",width:$displayedElem.width()+"px"});}else{this.lookupDiv.css({top:dElementOffset.top+$displayedElem.outerHeight()+"px",left:dElementOffset.left+(Runner.isDirRTL()?$displayedElem.outerWidth()-this.lookupDiv.outerWidth():0)+"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,page:this.pageObj.pageName,searchFor:this.getDisplayValue(),searchField:this.fieldName,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;}
var $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:{page:this.listPageId,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 Runner.suggests.DestroySuggestDiv!="undefined"){Runner.suggests.DestroySuggestDiv();}
if(!!ctrl.parentCtrls.length){pageParams.baseParams.parentsExist=true;pageParams.baseParams.parentCtrlsData=JSON.stringify(ctrl.getParentControlsData());}
pageParams.baseParams.data=JSON.stringify(ctrl.getControlsData());if(ctrl.lookupOrderBy)
pageParams.baseParams.orderby=ctrl.lookupDesc?"d"+Runner.goodFieldName(ctrl.lookupOrderBy):"a"+Runner.goodFieldName(ctrl.lookupOrderBy);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_list",PAGE_ADMIN_ADMEMBERS:"admin_admembers_list",PAGE_ADMIN_RIGHTS:"admin_rights_list",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,PD_LAYOUT:4,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,constructor:function(cfg){this.rows=[];this.fNames=[];this.baseParams={};Runner.apply(this,cfg);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.r-grid-footer',this.pageObj.gridElem);totalsTr.removeClass(this.classNameHidden);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',page:this.pageObj.pageName,masterpagetype:Runner.pages.PageSettings.getTableData(this.tName,"masterPageType")||"",});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",page:pageObj.pageName,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){if(ctrlsJSON.success!==false){if(inlineObject.loadSettings&&ctrlsJSON.settings){Runner.pages.PageSettings.addSettings(inlineObject.tName,ctrlsJSON.settings,false);}
var proxy=ctrlsJSON.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(!Runner.isPD()){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');}}else{this.pageObj.toggleItemType('grid_inline_save',!hideSaveButt,row.id);if(row.saveLink){return row.saveLink;}
$link=$("#saveLink"+row.id);$link.removeClass('disabled');}
$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(!Runner.isPD()){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');}}else{this.pageObj.toggleItemType('grid_inline_cancel',!hideRevertButt,row.id);if(row.cancelLink){return row.cancelLink;}
$link=$("#revertLink"+row.id);}
$link.on("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(!Runner.isPD()){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.hideElement("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++){var idLink=Runner.isPD()?"#details_"+row.id+"_"+newData.hrefs[i].id:"#"+newData.hrefs[i].id+row.id;$(idLink).attr("href",newData.hrefs[i]["href"]);}}
if(this.lookupParams&&this.lookupFieldInfo&&newData.linkValue!==undefined){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.hideElement("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,new Runner.AjaxRow(this.pageObj,row));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){var inlineObj=this;$link.filter(function(i,elem){return inlineObj.pageObj.showAddInPopup($(elem));}).on("click",function(e){var $link=$(this);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}};if($link.data("page")){pageParams.baseParams["page"]=$link.data("page");}
pageParams.popupWidth=$link.data("popupwidth");pageParams.popupHeight=$link.data("popupheight");Runner.pages.PageManager.openPage(pageParams);return false;});return $link;},initCheckBox:function($checkbox){var $checkBoxCell=$checkbox.parents("[data-checkbox-cell]");if(!$checkBoxCell.length){$checkBoxCell=$checkbox.parent()}
$checkBoxCell.on("click",function(e){if(!$checkbox.is(e.target)&&$checkbox.is(":visible")){$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){var self=this;$link.filter(function(i,elem){return self.pageObj.showViewInPopup($(elem));}).on("click",self.pageObj.getViewLinkHandler(row,'popup'));return $link;},initEditLink:function($link,row){var self=this;$link.filter(function(i,elem){return self.pageObj.showEditInPopup($(elem));}).on("click",self.pageObj.getEditLinkHandler(row,'popup'));return $link;},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($('[id=check'+this.id+'_'+row.id+']'));row.copyLink=this.initCopyLink($('[id=copyLink'+row.id+']'),row);row.editLink=this.initEditLink($('[id=editLink'+row.id+']'),row);row.iEditLink=this.initInlineEditLink($('[id=iEditLink'+row.id+']'),row);row.viewLink=this.initViewLink($('[id=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;if(Runner.isPD()){this.pageObj.toggleItemType('grid_inline_save',false,row.id);this.pageObj.toggleItemType('grid_inline_cancel',false,row.id);if(row.cancelLink){row.cancelLink.off('click');delete row.cancelLink;}
if(row.saveLink){row.saveLink.off('click');delete row.saveLink;}}else{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&&!Runner.isPD()){toggler?$('.rnr-b-recordcontrol',this.pageObj.pageCont).removeClass('rnr-hiddenbrick'):$('.rnr-b-recordcontrol',this.pageObj.pageCont).addClass('rnr-hiddenbrick');}else{this.pageObj.toggleElement("recordcontrol",toggler);}},prepareRow:function(vals,submitted){var grid=this.pageObj.gridElem,$addRow,$sepAddRow=$(".gridRowSepAdd",grid).eq(0),newRowId=Runner.genId(),pageId=this.id,newAddRow;if(Runner.isPD()){$addRow=$(".gridRowAdd[data-pageid="+this.id+"]",grid).add(grid.children("[data-record-id=add]"));}else{$addRow=$(".gridRowAdd",grid).eq(0);}
if(this.rows.length===0){this.pageObj.showElement("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);newAddRow.row.attr('data-hidden',null);$(".gridRowAdd",newAddRow.row).removeClass('gridRowAdd '+this.classNameHidden);if(Runner.isPD()){newAddRow.row.attr('data-record-id',newAddRow.id);newAddRow.row.find('[data-record-id=add]').attr('data-record-id',newAddRow.id);newAddRow.row.attr("id",this.rowPref+newAddRow.id);}else{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.last().parent());}else{newAddRow.row.insertAfter($addRow.last());}}
(this.inlineEditObj||this).initRow(newAddRow);newAddRow.submitted=submitted;return newAddRow;},replaceElementsIdForAddedRow:function(newAddRow,pageId){if(Runner.isPD()){var suffixLength=("_add"+pageId).length;$("[id$=_add"+pageId+"]",newAddRow.row).each(function(){var $elem=$(this);var strId=$elem.attr('id');var idName=strId.substr(0,strId.length-suffixLength);if(idName==='check'){$elem.attr('id',"check"+pageId+"_"+newAddRow.id);}else if(idName==='details'){return;}else{$elem.attr('id',idName+newAddRow.id);}});}else{$("#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();$("#iEditLink_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(!Runner.isPD()){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.hideElement('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.hideElement('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),checkData={value:$box.val(),};if(ctrl.dependent){var parentFiltersValueData=$box.data('parentFiltersValues'),parentValues=[];ctrl.parentFilterNames.forEach(function(pfName){parentValues.push(parentFiltersValueData[pfName].toString().replace('|','\\|'));});checkData.parentValues=parentValues.join('|');}
arr.push(checkData);});}
return arr;},getFilterValue:function(encoded){var arr=this.getValue(),result='';for(i=0;i<arr.length;i++){var value=arr[i].value,parentValues=arr[i].parentValues,prepFName;if(value===''){continue;}
value=this.getPreparedValue(value,encoded);prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;result+='('+prepFName+this.separator+value
+(parentValues?'~~'+parentValues:'')+')';}
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,2);}
if(maxKnob){maxKnob=this.parseDateTime(maxKnob,2);}
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,2);this.minDateInMs=this.minDate.getTime();this.maxDate=this.parseDateTime(this.maxValue,2);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,2);this.realMinDate=this.parseDateTime(this.realMinValue,2);}
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();}
Runner.onMediaChange(function(media){Runner.pages.PageManager.updateMedia(media);});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{if(Runner.isPD()){var itemSelector='[data-itemid]:not(li)';args.headerContent=$(args.headerContent).find(itemSelector).addBack(itemSelector);args.footerContent=$(args.footerContent).find(itemSelector).addBack(itemSelector);if(!Runner.smallScreen){args.width=this.popupWidth;args.height=this.popupHeight;}}
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();}
this.$panel=$panel;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&&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;this.winObject=modalWrapper;}
if(args.headerContent==""){args.headerContent="<h2></h2>";}
$header.append(args.headerContent);$header.append($('<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'));$body.html(args.bodyContent);$footer.append(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");Runner.setZindexMax(parseInt($modal.css('z-index'),10));$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).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};};}
$body.on("scroll",function(e){if(typeof pageObj.hideSearchControllerContainers==="function"){pageObj.hideSearchControllerContainers();}});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);}
$modalBody.width($modalContentBox.width()-$modalBody.outerWidth()+$modalBody.width());$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);}},updateMedia:function(media){Object.keys(tables).forEach(function(table){Object.keys(tables[table]).forEach(function(pageId){tables[table][pageId].updateMedia(media);});})}}}();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_ADMIN_RIGHTS:return Runner.isAD?new Runner.pages.RightsPageAD(cfg):new Runner.pages.RightsPage(cfg);case Runner.pages.constants.PAGE_ADMIN_MEMBERS:return new Runner.pages.MembersPage(cfg);case Runner.pages.constants.PAGE_ADMIN_ADMEMBERS:return new Runner.pages.MembersPageAD(cfg);case Runner.pages.constants.PAGE_LIST: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:return new Runner.pages.RunnerPage(cfg);}};Runner.pages.getUrl=function(tName,pageType,keys,keyPref){if(pageType==='rprint'){pageType='print';}
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)||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:'',pageName:'',isDefaultPage:true,defaultPages:[],modal:false,pageId:-1,controlsMap:null,viewControlsMap:null,headerCont:"",bodyCont:"",footerCont:"",win:null,popupSizeIsCorrected:false,pageCont:null,bricksForReload:[],proxy:null,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:{},layoutHelper:{},fieldItems:{},$gridTabControl:null,leftBarItems: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.pageName=this.pageData.pageName;this.layoutHelper=new Runner.PDLayout(this,{formMap:this.pageData.helperFormItems,itemsByType:this.pageData.helperItemsByType,gridCellMap:this.pageData.cellMaps,itemVisiblity:this.pageData.helperFormItems.itemVisiblity,fieldItems:this.pageData.fieldItems,});if(this.pageData.renderedMediaType!==Runner.getMediaType()){this.updateMedia(Runner.getMediaType());}
set_cookie('mediaType',Runner.getMediaType(),'',Runner.projectRoot());this.fieldItems=this.pageData.helperFieldItems||{};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.defaultPages=Runner.pages.PageSettings.getTableData(this.tName,"defaultPages")||{};this.isDefaultPage=this.defaultPages[this.pageType]==this.pageName;this.oldLayout=this.controlsMap&&this.controlsMap.oldLayout;this.layoutVersion=this.controlsMap&&this.controlsMap.layoutVersion;this.layoutName=this.controlsMap?this.controlsMap.layoutName:"";this.tabsPresented=!!this.getTabsCtrlsCount();this.pageCont=document.body;this.pageTable=this.controlsMap&&this.controlsMap.pageTable?this.controlsMap.pageTable:this.tName;if(this.afterInit){this.on({'afterInit':this.afterInit});}
this.initTaskQueue=[];this.addInitTask(this.init);this.initYUI();},initCustomButtons:function(){var self=this;(this.pageData.buttons||[]).forEach(function(buttonId){Runner.buttonEvents[buttonId].call(self,self,self.proxy,self.id);});},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);this.initCustomButtons();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();}
this.initPdfMake();this.initSearch();if(!this.useResize){this.initForGrid();}
this.initMasterInfoGrid();if(this.openMode===Runner.pages.constants.OPENMODE_PRELOADED){if(settings.global["useCookieBanner"]&&!window.localStorage.getItem("cookie_consent")){var $banner=$('<div class="r-cookie-banner"></div>');$banner.html(settings.global["cookieBanner"]);var $cookieButton=$('<button class="btn btn-default btn-sm"></button>').html(Runner.lang.constants.AA_OK);$banner.append(' ');$banner.append($cookieButton);$('body').append($banner);window.setTimeout(function(){$banner.animate({bottom:0},250);},300);$cookieButton.click(function(){window.localStorage.setItem('cookie_consent',true);$banner.remove();});}
if(Runner.isPD()){$("[data-fixed][data-resize-name]").each(function(){var $mainElem=$(this);var resizeName=$mainElem.data('resize-name');var topMarginElements=$('[data-resize-top="'+resizeName+'"]');var leftMarginElements=$('[data-resize-left="'+resizeName+'"]');ResizeSensor(this,function(){if(Runner.mobileScreen()){topMarginElements.css('margin-top',"");leftMarginElements.css('margin-'+Runner.left,"");}else{var height=$mainElem.height();var width=$mainElem.width();topMarginElements.css('margin-top',height+'px');leftMarginElements.css('margin-'+Runner.left,width+'px');}});});$(".r-vbar-page > .r-left").mCustomScrollbar({theme:"minimal-dark",scrollInertia:0,axis:"y"});$(window).on("scroll",function(e){pageObj.hideSearchControllerContainers();});Runner.setZindexMax(parseInt($(".r-vbar-page > .r-left").css("z-index"),10));this.initCollapseButton();}else{$("#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,pageParam;if(prefix==="dchart"||prefix==="dreport"){pageType=prefix;}
pageUrl=Runner.pages.getUrl(this.tName,pageType);pageParam=this.pageData.pageName?"&page="+this.pageData.pageName:"";$languageLink.on("click",function(e){window.location.href=pageUrl+"?language="+$(this).data("lang")+pageParam;return false;});$langSelector.on("change",function(e){window.location.href=pageUrl+"?"+extraparams+"language="+this.options[this.selectedIndex].value+pageParam;});},initForTabs:function(){this.initControls();this.initViewControls();this.initLookups();this.initChangeCtrlEvents();},initForGrid:function(){if(Object.getPrototypeOf(this)===Runner.pages.RunnerPage.prototype){this.fireEvent('afterInit',this,this.proxy,this.id);}},initMasterInfoGrid:function(){if(!this.pageData.hasMasterList){return;}
$masterGrid=Runner.isPD()?this.findItemType("master_info"):$(this.getBrickElem(this.isBootstrap()?'masterlistgrid':'masterinfo'));$masterGrid.off("click.opentext").on("click.opentext",this.largeTextOpenerDelegate.bind(this));this.initMasterViewControls();},initReCaptcha:function(){if(!Runner.globalReCaptchaLoader){return;}
Runner.globalReCaptchaLoader.onLoad(function(){this.reCaptcha=new Runner.controls.ReCaptcha(this.controlsMap.reCaptcha);this.reCaptcha.init();},this);},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();});$("[id=print_friendly_button"+this.id+"]").on("click").on("click",function(e){var pageName=$(this).data("page")||false;$toggler.attr("data-icon",$toggler.attr("data-icon")=="printdown"?"printup":"printdown");$panelBlock.toggleClass('open');pageObj.printerFriendlyBtnHandler(pageName);return false;});$("#printDetailsToggler"+this.id).unbind("click").bind("click",function(e){$("#printdetailstables"+pageObj.id).toggle();});},printPanelParams: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=[],params={};if($records.length){params.records=$records.val()}
if($detailsBox.is(':checked')){$detailsTablesBoxes.each(function(n,box){if(box.checked){details.push(box.value);}});params["details[]"]=details;}
if(scopeId=="printSelection"+this.id){params["selection[]"]=this.getSelectedRecordKeys();}
if(scopeId=="printAll"+this.id){params.all=1;}
return params;},getSelectedRecordKeys:function(){var selection=[];this.getSelBoxes(this.id).filter(':checked').each(function(){selection.push($(this).val());});return selection;},printerFriendlyBtnHandler:function(pageName){var requestParams={standardSubmit:true,submitUrl:Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_PRINT),target:'_blank',method:'POST',id:this.id,baseParams:this.printPanelParams()};requestParams.baseParams["a"]="print";if(pageName){requestParams.baseParams["page"]=pageName;}
var 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=pageObj.getLogoutUrl();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;});},getLogoutUrl:function(){return Runner.pages.getUrl(this.tName,this.pageType)+"?a=logout";},submitLoginForm:function(){var pageObj=this,pageParams,$loginBlock=$("#login_block"+this.id),ajaxParams={a:"Login",mode:"embeded",id:Runner.genId(),remember_password:$('input[name="remember_password"]',$loginBlock).val()};if($loginBlock.length){ajaxParams.password=$('input[name="password"]',$loginBlock).val();ajaxParams.username=$('input[name="username"]',$loginBlock).val();}else{ajaxParams.password=$('#password'+this.id).val();ajaxParams.username=$('#username'+this.id).val();}
if(Runner.pages.PageSettings.getGlobalData("twoFactorAuth")){pageParams={pageType:Runner.pages.constants.PAGE_LOGIN,tName:Runner.pages.PageSettings.getGlobalData("loginTName"),pageId:-1,modal:true,userval:ajaxParams.username,passval:ajaxParams.password,parId:this.id,hostPageObj:this,baseParams:{a:"Login",mode:"embeded",username:ajaxParams.username,password:ajaxParams.password},requestUrl:Runner.getPageUrl("login")};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){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.NOT_TABLE_BASED_TNAME,pageId:-1,modal:true,userval:user,passval:pass,hostPageObj:hostPage||this,baseParams:{parId:this.id,notRedirect:notRedirect?1:0,mode:"popup"},notRedirect:notRedirect?1:0,requestUrl:Runner.getPageUrl("login")};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.ControlManager.getAt(tName);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(){var pageObj=this;if(this.isBootstrap()){var $menu=$('.menu-treelike');$('.menu-treelike:not([data-initialized])',this.pageCont).on('click','[data-toggle="menu-collapse"]',function(e){var $triangle=$('.menu-triangle',this),$link=$(this),$target=$($link.attr('data-target')),expand=$link.attr('aria-expanded')!=='true';var collapsedBar=$link.closest('.r-left-collapsed').length!=0;if(collapsedBar){expand=true;}
$menu.find('ul').removeClass('r-most-recent');$target.addClass('r-most-recent');$target.parents('ul').addClass('r-most-recent');$triangle.toggleClass('glyphicon-triangle-right',!expand).toggleClass('glyphicon-triangle-bottom',expand);$link.attr('aria-expanded',expand);if(!collapsedBar){$target.collapse(expand?'show':'hide');}else{$target.toggleClass('in',expand).css('height','');$link.attr('aria-expanded',expand?'true':'false');}}).find('[data-toggle="menu-collapse"]').each(function(){var $triangle=$('.menu-triangle',this),$target=$($(this).data('target')),collapsed=!$target.hasClass('in');$triangle.toggleClass('glyphicon-triangle-right',collapsed).toggleClass('glyphicon-triangle-bottom',!collapsed);$(this).attr('aria-expanded',collapsed?'false':'true');}).attr('data-initialized','true');$(document).off('click.collapsed.treemenu').on('click.collapsed.treemenu',function(e){if($('.r-left-collapsed').length!=0&&$(e.target).closest('[data-itemtype="menu"]').length==0){pageObj.closeTreeSubmenus();}});if($('.r-left-collapsed').length!=0){pageObj.closeTreeSubmenus();}
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=this.pageData.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']);}
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")&&!Runner.pages.PageSettings.getGlobalData("staticMapsOnly")){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),$modalBody=$(".modal-body",this.bsWin);$modalContentBox.width($oldModalContentBox.width());$modalContentBox.height($oldModalContentBox.height());$modalBody.width($oldModalBody.width()).height($oldModalBody.height());$modalBody.width($modalContentBox.width()-$modalBody.outerWidth()+$modalBody.width());$(".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 events=Runner.pages.PageSettings.getTableEventsData(this.pageTable,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);},initMasterViewControls:function(){if(!this.pageData.hasMasterList||!this.viewControlsMap.mViewControlsMap||typeof this.viewControlsMap.mViewControlsMap!=="object"){return;}
var context=Runner.isPD()?this.findItemType("master_info"):$('.rnr-b-mastergridfields');var pageId=Runner.pages.PageSettings.getTableData(this.tName,"masterPageId");this.setupViewContols(this.viewControlsMap.mViewControlsMap.controls,context,pageId);},setupViewContols:function(viewContols,pageCont,pageId){for(var i=0;i<(viewContols||[]).length;i++){(Runner.viewControls.ViewControlFactory(viewContols[i],this.pageType,pageCont,this,pageId)).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;},getTabsCtrlsCount:function(){return this.isBootstrap()?$(".panel.with-tabs",this.pageCont).length:0;},getTabsCtrls:function(){var tabCtrls=[];for(var idx=0;idx<this.getTabsCtrlsCount();idx++){tabCtrls.push(this.getTabs(idx));}
return tabCtrls;},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);},initTabsSections:function(){this.initTabs();this.initSections();this.initSteps();},initTabs:function(){if(!this.tabsPresented||!this.hasMaps()){return;}
var pageObj=this;this.getTabsCtrls().forEach(function(tabCtrl){for(var i=0;i<tabCtrl.count();i++){tabCtrl.headerElement(i).on("shown.bs.tab",function(e){pageObj.mapManager&&pageObj.mapManager.updateLittleMaps();});}});},checkIfSectionPresented:function(){return!!this.getSectionCount();},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()||!this.hasMaps()){return;}
this.getSections().forEach(function(section,idx){var pageObj=this;section.get().on("shown.bs.collapse",function(e){pageObj.mapManager&&pageObj.mapManager.updateLittleMaps();});},this);},initSteps:function(){if(!this.controlsMap||!this.controlsMap.multistep){return;}
var $stepnav=$('#stepnav'+this.id),stepsNumber=$stepnav.children().length,pageObj=this,hashStep,initialStep=this.controlsMap.initialStep;$stepnav.on('click','li',function(){var step=$(this).data('step');if(step<=pageObj.currentStep){pageObj.setCurrentStep(step);return false;}
pageObj.validateStep(step);return false;});$('[id=nextstep'+this.id+']').on('click',function(){if(pageObj.currentStep<stepsNumber-1){pageObj.validateStep(pageObj.currentStep+1);}
return false;});if(this.openMode==Runner.pages.constants.OPENMODE_PRELOADED){hashStep=parseInt(location.hash.replace('#',''),10);if(hashStep>1&&hashStep<stepsNumber){initialStep=hashStep-1;}}
this.setCurrentStep(initialStep);},validateStep:function(destStep){var stepFields=this.getStepFields(this.currentStep),ddStepFields=[],pageObj=this,counter,onDuplicatesResolved;this.getForm();$.each(this.form.fieldControls,function(idx,control){if($.inArray(control.fieldName,stepFields)!==-1&&control.isSetValidation("DenyDuplicated")){ddStepFields.push(control.fieldName);}});if(!ddStepFields.length){if(this.form.validate(stepFields)){this.setCurrentStep(destStep);}
return;}
counter=ddStepFields.length;onDuplicatesResolved=function(cfName,hasDuplicates){counter=counter-1;if(hasDuplicates){pageObj.un("ddValidationResolved",onDuplicatesResolved);return;}
if(!!counter){return;}
pageObj.un("ddValidationResolved",onDuplicatesResolved);if(pageObj.form.validate(stepFields)){pageObj.setCurrentStep(destStep);}};this.on("ddValidationResolved",onDuplicatesResolved);this.form.validate(ddStepFields);},getStepFields:function(stepIdx){var stepFields=[];$("#step_"+stepIdx+"_"+this.id).find("[data-fieldname]").each(function(idx,el){stepFields.push($(el).data("fieldname"));});return stepFields;},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');}
$('[id=nextstep'+this.id+']').toggle(index<$stepNavLinks.length-1);$('[id=saveButton'+this.id+']').toggle(index>=$stepNavLinks.length-1);$(".stepFrame[id^='step_'][id$='_"+this.id+"']").hide();$("#step_"+index+"_"+this.id).show();if(this.mapManager){this.mapManager.updateLittleMaps();}
this.currentStep=index;},openFieldTabsSections:function(fNames){var pageObj=this;if(this.controlsMap&&this.controlsMap.multistep){$('#stepnav'+this.id).children().each(function(idx,li){var stepIdx=$(li).data('step'),stepFields=pageObj.getStepFields(stepIdx);for(var i=0;i<fNames.length;i++){if($.inArray(fNames[i],stepFields)!==-1){pageObj.setCurrentStep(stepIdx);return false;}}});}
this.getSections().forEach(function(section){for(var i=0;i<fNames.length;i++){if(section.bodyElement().find(pageObj.getFieldWrapperElement(fNames[i])).length){section.expand();break;}}});this.getTabsCtrls().forEach(function(tabCtrl){var selected=false;for(var j=0;j<tabCtrl.count();j++){for(var i=0;i<fNames.length;i++){if(tabCtrl.bodyElement(j).find(pageObj.getFieldWrapperElement(fNames[i])).length){tabCtrl.activate(j);selected=true;break;}}
if(selected){break;}}});},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=$bodyNode.innerWidth();if(contentWidth>defaultMaxWinWidth){$bodyNode.width(defaultMaxWinWidth);$widgetNode.width(defaultMaxWinWidth);}else{$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);}},setFirstFocus:function(pageId,ctrls){ctrls=ctrls||Runner.controls.ControlManager.getAt(this.tName);if(!ctrls||!ctrls.length){return false;}
var i,fNamesArr=[],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){var steps=$('#stepnav'+this.id).children().map(function(idx,li){return $(li).data('step');}).toArray();for(var i=0;i<steps.length;i++){$("span[id^='edit"+(pageId||this.id)+"_']").each(function(){var idx=$.inArray(this.id,spanContIds);if(currentStep===undefined&&idx>-1&&$.inArray(ctrls[idx].fieldName,pageObj.getStepFields(steps[i]))>-1){if(ctrls[idx].isInvalid){currentStep=steps[i];currnetIndxCtrl=idx;firstInvalidIndx=idx;}}});if(currentStep!==undefined){this.setCurrentStep(currentStep);ctrls[currnetIndxCtrl].setFocus();return true;}}}else if(this.tabsPresented||this.checkIfSectionPresented){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(){var 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;},getFieldWrapperElement:function(fieldName){var $result=$("[data-fieldname='"+fieldName+"']");if($result.length){return $result;}
return $("[data-fieldname]").filter(function(i,e){return $(e).data("fieldname").toString()===fieldName;});},showField:function(fieldName){var pageObj=this;var ctrl=Runner.getControl(this.pageId,fieldName);if(Runner.isPD()){(this.fieldItems[fieldName]||[]).forEach(function(item){pageObj.toggleItem(item,true);});}else{this.getFieldWrapperElement(fieldName).toggleClass(this.makeClassName('hiddenfield'),false);}
if(ctrl){ctrl.hiddenByField=false;}},hideField:function(fieldName){var pageObj=this;var ctrl=Runner.getControl(this.pageId,fieldName);if(Runner.isPD()){(this.fieldItems[fieldName]||[]).forEach(function(item){pageObj.toggleItem(item,false);});}else{this.getFieldWrapperElement(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);},toggleItem:function(itemId,show,recordId){return this.layoutHelper.toggleItem(itemId,show,recordId);},toggleItems:function(itemIds,show){return this.layoutHelper.toggleItems(itemIds.map(function(id){return{itemId:id,show:show};}));},toggleItemType:function(itemType,show,recordId){return this.layoutHelper.toggleItemType(itemType,show,recordId);},hasItemType:function(itemType){return this.layoutHelper.hasItemType(itemType);},findItemType:function(itemType,recordId){return this.layoutHelper.findItemType(itemType,recordId);},findItem:function(itemId,recordId){return this.layoutHelper.findItem(itemId,recordId);},getItemButton:function(itemId,recordId){return this.layoutHelper.findItem(itemId,recordId).children('a');},findForm:function(location){return this.layoutHelper.findForm(location);},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);},getBrickElements:function(name,pageCont,all){return this.getBrickObjs(name,pageCont,all).reduce(function(obj,br){return obj.add(br.elem);},$());},getBrickElem:function(name){var bricksArr=this.getBrickObjs(name);if(!bricksArr.length){return false;}
return bricksArr[0].elem},getBrickGridElem:function(){if(Runner.isPD()){return this.findForm('grid');}
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);}
if(Runner.isPD()){this.findItemType(this.messageItemType()).html(messageText);}else{this.replaceBrickContentHTMLWith('message',messageText);}},displayHalfPreparedMessage:function(text,error){var messageText=this.getMessageText(text,error);var messType;if(Runner.isPD()){messType=this.messageItemType();if(messType==='grid_message'){this.getGridMessageElem().html(messageText);}else{this.findItemType(messType).html(messageText);}}else{this.replaceBrickContentHTMLWith('message',messageText);}
if(this.isBootstrap()){if(Runner.isPD()){if(messType==='grid_message'){this.getGridMessageElem().addClass(error?"alert-danger":" alert-success");}else{this.findItemType(messType).addClass(error?"alert-danger":" alert-success");}}else{this.getBrickContentsElem('message').addClass(error?"alert-danger":" alert-success");}}},showPageMessageWithErrorText:function(text){this.displayHalfPreparedMessage(text,true);this.showElement("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);},getAdvancedSearchUrl:function(){return Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_SEARCH);},initAdvSearch:function(){var pageObj=this;$("[id=advButton"+this.pageId+"][data-popup]").on("click",function(e){var pageParams={requestUrl:pageObj.getAdvancedSearchUrl(),baseParams:{},tName:pageObj.tName,pageType:Runner.pages.constants.PAGE_SEARCH,modal:true,},$button=$(this),page=$button.data("page");if(page){pageParams.baseParams.page=page;}
pageParams.popupWidth=$button.data("popupwidth");pageParams.popupHeight=$button.data("popupheight");Runner.pages.PageManager.openPage(pageParams);return false;});},hideSearchControllerContainers:function(){if(this.useSearchSuggests||this.searchController&&this.searchController.useSuggest&&typeof Runner.suggests.DestroySuggestDiv==="function"){Runner.suggests.DestroySuggestDiv();}
this.searchController&&this.searchController.hideSearchFieldsSuggests();var ctrls=Runner.controls.ControlManager.getAt(this.tName,this.pageId),i;for(i=0;i<ctrls.length;i++){if(ctrls[i]instanceof Runner.controls.EditBoxLookup){ctrls[i].destroySuggest();}}},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.isDefaultPage){baseParams.page=baseParams.page||this.pageName;}
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();if(this.multiRecordPage){baseParams.recordId=Runner.genId();Runner.setIdCounter(this.id+10000);}}
baseParams=Runner.apply(this.getBaseParams(),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.getGrayedElement());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];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;},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;}
$('ul.dropdown-menu').each(function(){var $dropdown=$(this),prevElemsDysplayed=false,lastDisplayedLi=false;if($dropdown.parents(".searchpanel-options").length>0){return;}
if($dropdown.find('li').length<1){$dropdown.prev().css('display','none');}
$dropdown.find('li').each(function(i,li){var $li=$(li);if($li.attr('role')=="separator"&&(!prevElemsDysplayed||i===0)){$li.css('display','none');}else if($li.attr('role')=="separator"&&prevElemsDysplayed){prevElemsDysplayed=false;$li.css('display','block');lastDisplayedLi=$li;}else{if($li.css('display')!=='none'&&Runner.util.getChildDisplayedElems($li).length>0){prevElemsDysplayed=true;lastDisplayedLi=$li;}}});if(lastDisplayedLi){$dropdown.find("button.dropdown-toggle").removeClass("hideMoreButton");if(lastDisplayedLi.attr('role')=="separator"){lastDisplayedLi.css('display','none');}}else{$dropdown.find("button.dropdown-toggle").addClass("hideMoreButton").parent().removeClass("open");if(Runner.isPD()){$dropdown.parent().hide();}}});},mobileCollpased:function($elem){if(Runner.isPD()){return $elem.attr('data-mobile-hidden')!==undefined;}else{return $elem.hasClass('bs-hidden-xs');}},toggleMobileCollapse:function($elem,hide){if(hide===undefined){hide=!this.mobileCollpased($elem);}
if(Runner.isPD()){$elem.attr('data-mobile-hidden',hide?'':null);}else{$elem.toggleClass('bs-hidden-xs',hide);}
$elem.attr('aria-expanded',hide?'true':'false');},initCollapseButtons:function(){var pageObj=this;if(Runner.isPD()){$("[data-runner-toggle=collapse]",this.pageCont).click(function(e){Runner.toggleMoreButtonState();pageObj.layoutHelper.updateMedia(Runner.getMediaType());return false;});}else{$("[data-runner-toggle=collapse]",this.pageCont).each(function(){pageObj.togglePageMobileCollapse($(this).data('target'),true);}).click(function(e){pageObj.togglePageMobileCollapse($(this).data('target'));return false;});}},togglePageMobileCollapse:function(target,hide){var pageObj=this;target=target||'[data-mobile-controlled]';$(target,pageObj.pageCont).each(function(idx,element){pageObj.toggleMobileCollapse($(element),hide);});},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);},showAddInPopup:function($link){if(Runner.isPD()){return $link.attr('data-popup')!==undefined;}
return Runner.pages.PageSettings.getTableData(this.tName,"showAddInPopup")&&!Runner.isMobile;},showEditInPopup:function($link){if(Runner.isPD()){if($link===undefined){return $('[id^=editLink][data-popup]').length>0;}
return $link.attr('data-popup')!==undefined;}
return Runner.pages.PageSettings.getTableData(this.tName,"showEditInPopup")&&!Runner.isMobile;},showViewInPopup:function($link){if(Runner.isPD()){if($link===undefined){return $('[id^=viewLink][data-popup]').length>0;}
return $link.attr('data-popup')!==undefined;}
return Runner.pages.PageSettings.getTableData(this.tName,"showViewInPopup")&&!Runner.isMobile;},getInlineRow:Runner.emptyFn,messageItemType:function(){return'message';},showElement:function(name){this.toggleElement(name,true);},hideElement:function(name){this.toggleElement(name,false);},toggleElement:function(name,show){var _self=this;if(Runner.isArray(name)){name.forEach(function(eName){_self.toggleElement(eName);});}
if(Runner.isPD()){this.element2Item(name).forEach(function(itemType){if(itemType==='grid_message'){_self.toggleGridMessage(show);}else if(itemType==='grid'){_self.layoutHelper.toggleForm('grid',show);}else{_self.toggleItemType(itemType,show);}});}else{var brickName=this.element2Brick(name);if(show){this.showBrick(brickName);}else{this.hideBrick(brickName);}}},element2Item:function(name){if(name==='message'){return[this.messageItemType()];}else if(name==='filterpanel'){return['filter_panel'];}else if(name==='loginfields'||name==='grid'){return['grid'];}else if(name==='searchpanel'){return['search_panel'];}else if(name==='printpanel'){return['print_panel'];}else if(name==='recordcontrol'){return["inline_save_all","inline_cancel_all","delete","update_selected","export_selected","delete_selected"];}else if(name==='bsfieldhidepanel'){return["columns_control"];}
return[];},element2Brick:function(name){return name;},toggleGridMessage:function(show){$('[data-grid-message][data-pageid='+this.id+']').attr('data-hidden',show?null:'');},getGridMessageElem:function(){return $('[data-grid-message][data-pageid='+this.id+']');},openDetailsPreview:function(rowId){if(!this.dpObjs){return;}
var tNames=[],pageObj=this,row,tName,dp;for(tName in this.dpObjs){dp=this.dpObjs[tName];row=row||dp.getRowById(rowId);if(!row){return;}
if(dp.dpShowType===Runner.pages.constants.DP_INLINE&&dp.isTabToShow(tName,row)){tNames.push(tName);}}
if(!tNames.length){return;}
row.row.addClass("bs-details-opened");row.isShown=true;tNames.forEach(function(tName){pageObj.dpObjs[tName].prepareTabControl(row);});this.hideElement("message");},closeDetailsPreview:function(rowId){if(!this.dpObjs){return;}
var row,tName,dp;for(tName in this.dpObjs){dp=this.dpObjs[tName];row=row||dp.getRowById(rowId);if(!row){return;}
if(dp.dpShowType===Runner.pages.constants.DP_INLINE){dp.closeDetails(row);}}},showLoadingBox:function(text){if(this.silentReloading||Runner.isMobile){return;}
var grayed=this.getGrayedElement();if(!grayed){return;}
Runner.runLoading(text||"",grayed,this.openMode===Runner.pages.constants.OPENMODE_POPUP,this.win);},getGrayedElement:function(){if(this.containerBased()){return this.openContainer;}
return this.gridElem;},initPagination:function(){var pageObj=this;var $paginationElem;if(Runner.isPD()){$paginationElem=this.findItemType('pagination');}else{$paginationElem=this.getBrickElements('pagination');}
$paginationElem.bind("click",function(e){Runner.Event.prototype.stopEvent(e);var $target=$(e.target),pageNum,url;if(!$target.is("a")){return;}
pageNum=$target.attr("pageNum");pageObj.preparePageForReloading();pageObj.reload({goto:pageNum},pageObj.getExtraPageReloadParams());});},getBaseParams:function(){return this.baseParams||Runner.getUrlParams();},updateMedia:function(media){this.layoutHelper&&this.layoutHelper.updateMedia&&this.layoutHelper.updateMedia(media);},getRowById:function(rowId){if(!this.inlineEdit){return null;}
return this.inlineEdit.getRowById(rowId);},initPdfMake:function(){var pageObj=this;this.findItemType("view_pdf").add(this.findItemType("print_pdf")).add(this.findItemType("create_pdf")).add(this.findItemType("export_report_pdf")).find("a").click(function(){pageObj.createButtonPDF($(this));});},createButtonPDF:function($item){var params={orientation:$item.data('orientation'),scale:$item.data('scale'),page:$item.data('pdfpage'),pageType:$item.data('pagetype'),scope:$item.data('scope'),split:$item.data('split'),records:$item.data('records'),filename:$item.data('filename'),backgroundImage:$item.data('bg-image'),backgroundOpacity:$item.data('bg-opacity'),beforeCreate:$item.data('before-create')};Runner.PDF.create(params,this,function(pdf){pdf.download(params.filename);});},showHiddenColumn:function(column){},initCollapseButton:function(){if(Runner.mobileScreen()){if(this.leftBarCollapsed()){this.toggleItemType('logo',true);$('.r-left-collapsed').removeClass('r-left-collapsed');this.toggleItemType('collapse_button',false);this.toggleItemType('expand_button',false);delete_cookie('collapse_leftbar',Runner.projectRoot());}
return;}
this.leftBarItems=[];var animateTime=300;var pageObj=this;var $logoCell=$('[data-logo-cell]');var $leftBar=$('.r-left'),$collapseBtn=this.findItemType('collapse_button').find('a'),$expandBtn=this.findItemType('expand_button').find('a');var $content=$('.r-left[data-fixed] + .r-content-col').add('.r-topheader[data-fixed]');var barWidth=$leftBar.attr('data-width')||'300px';var topbarHeight=$('.r-topheader > .navbar').height();if($expandBtn.closest('.r-left').length){$expandBtn.css({height:(topbarHeight)+'px'});}
$logoCell.add(this.layoutHelper.findForm('left')).find('[data-itemtype][data-itemid]').each(function(){var $item=$(this);var itemType=$item.attr('data-itemtype');if(itemType!='expand_button'&&itemType!=='menu'){pageObj.leftBarItems.push($item.attr('data-itemid'));}});var visibleItems=this.layoutHelper.getVisibleItems(this.leftBarItems);var doCollapse=function(){visibleItems=pageObj.layoutHelper.getVisibleItems(pageObj.leftBarItems);pageObj.toggleItems(pageObj.leftBarItems,false);pageObj.toggleItemType('collapse_button',false);pageObj.toggleItemType('expand_button',true);$leftBar.css({'overflow':'hidden','white-space':'nowrap'}).animate({'width':'50px'},animateTime,function(){$('.r-menu-collapsed').attr('data-hidden',null);$('.r-menu-expanded').attr('data-hidden','');$leftBar.addClass('r-left-collapsed');$leftBar.css({'width':'','overflow':'','white-space':''})});var targetCss={'max-width':(window.innerWidth-50)+'px'};targetCss['margin-'+Runner.left]='50px';$content.css({'max-width':'calc( '+window.innerWidth+'px - '+barWidth+'  )'}).animate(targetCss,animateTime,function(){$content.css('margin-'+Runner.left,'').css('max-width','');});pageObj.closeTreeSubmenus();set_cookie('collapse_leftbar',true,'',Runner.projectRoot());}
var doExpand=function(){$leftBar.animate({'flex-basis':barWidth,'width':barWidth},animateTime,function(){$leftBar.css({'flex-basis':'','width':'','overflow':''});$('.r-menu-collapsed').attr('data-hidden','');$('.r-menu-expanded').attr('data-hidden',null);pageObj.toggleItems(visibleItems,true);pageObj.toggleItemType('logo',true);$leftBar.removeClass('r-left-collapsed');pageObj.toggleItemType('collapse_button',true);pageObj.toggleItemType('expand_button',false);});var targetCss={'max-width':'calc( '+window.innerWidth+'px - '+barWidth+'  )'};targetCss['margin-'+Runner.left]=barWidth;$content.animate(targetCss,animateTime,function(){$content.css('margin-'+Runner.left,'');});delete_cookie('collapse_leftbar',Runner.projectRoot());}
$collapseBtn.on('click',function(){doCollapse();return false;});$expandBtn.on('click',function(){doExpand();return false;});this.toggleLeftBar=function(show){show?doExpand():doCollapse();}},closeTreeSubmenus:function(){var $menu=this.findItemType('menu');$menu.find('ul').removeClass('r-most-recent');},leftBarCollapsed:function(){return $('.r-left-collapsed').length>0;},getSelectedRecordKeys:function(){return[];},getSelectedRecordIds:function(){return[];},getSelectedRecords:function(){return[];},getAllRecords:function(){return[];},getRowObject:function(id){return null;},getDetailsPages:function(rowId){var ret={};var pageObj=this;Object.keys(this.dpObjs||{}).forEach(function(dtable){if(pageObj.dpObjs[dtable].detailsPageObj){ret[dtable]=pageObj.dpObjs[dtable].detailsPageObj;}});return ret;},getDetailsPage:function(table,rowId){return this.dpObjs[table]?this.dpObjs[table].detailsPageObj:null;},getMasterPage:function(){return this.masterPageObj||null;},largeTextOpenerDelegate:function(e){var self=this,$target=$(e.target),bsUsed=Runner.isBootstrap(),query=$target.data("query"),fieldLabel=$target.data("fieldlabel"),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();return false;});Runner.pages.PageManager.correctBSWindowSize(win._obj,self);};}
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){args.footerContent='<a href="#" data-role="closeText" class="btn btn-default btn-sm">'+Runner.lang.constants.CLOSE+'</a>';args.headerContent='<span>'+fieldLabel+'</span>';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);},});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;}
if(this.baseParams){delete this.baseParams.page;}},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){var page=$(this).data("page")?encodeURIComponent($(this).data("page")):false;pageObj.searchController.returnSubmit(page);return false;});$("#cancelButton"+this.pageId).on("click",function(e){pageObj.close();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{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:Runner.pages.PageSettings.getTableData(this.tName,"searchPageFields"),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),delegatedSubmit:this.submitAdvancedSearch.bind(this),});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){var page=$(this).data("page")?"&page="+encodeURIComponent($(this).data("page")):"";window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_LIST)+"?a=return"+page;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,pageEditUrl=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys);;this.editPageButton=$("#editPageButton"+this.id).on("click",function(e){var pageName=$(this).data("page")||false;if(!Runner.isDisabledButton(this)){pageObj.openEditPage(pageName);}
return false;});if(this.editPageButton){if(this.editPageButton.data("page")){pageEditUrl+="&page="+this.editPageButton.data("page");}
this.editPageButton.attr("href",pageEditUrl);}
this.headerEditPageButton=$("#headerEditPageButton"+this.id).on("click",function(e){if(!Runner.isDisabledButton(this)){pageObj.openEditPage();}
return false;}).attr("href",pageEditUrl);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(pageName){var pageName=pageName||false,pageEditUrl=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_EDIT,this.keys);if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP){window.location.href=pageEditUrl+(pageName?"&page="+pageName:"");return;}
var pageParams=Runner.pages.EditPage.prototype.getOpenPageParams.call(this,this.keys,this.inlineObjectParams.rowId);this.disablePageButtons();pageParams.popupCentered=true;if(pageName){pageParams.baseParams["page"]=pageName;}
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.showElement('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,masterPageObj:this,}
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);},getBaseParams:function(){var params=Runner.pages.ViewPage.superclass.getBaseParams();for(var i=0;i<this.keys.length;++i){params['editid'+(i+1)]=this.keys[i];}
return params;},});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+="?page="+this.pageName+"&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{Runner.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{if(Runner.isPD()){var $messageElem=this.findItemType(this.messageItemType());$messageElem.html('');for(var i=0;i<txt.length;i++){$messageElem.append(this.getMessageText(txt[i],true)+(i<txt.length-1?'<br>':''));$messageElem.toggleClass('alert-danger',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.showElement("message");},scrollToDetails:function(dpId){var detailsGridPosition=$("#detailPreview"+dpId).position();if(this.openMode===Runner.pages.constants.OPENMODE_POPUP){if(this.isBootstrap()){var $modalBody=$(".modal-body",this.bsWin);$modalBody.animate({scrollTop:detailsGridPosition.top+$modalBody.scrollTop()});}else{$(this.win.bodyNode.getDOMNode()).animate({scrollTop:detailsGridPosition.top});}}else{$(window).scrollTop(detailsGridPosition.top);}},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){var page=$(this).data("page")?"&page="+encodeURIComponent($(this).data("page")):"";window.location.href=Runner.getPageUrl(Runner.pages.PageSettings.getShortTName(pageObj.tName),Runner.pages.constants.PAGE_LIST,'a=return'+page);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,masterPageObj:this,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||this.masterSaved){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=[],pageObj=this,tName,msg,txt,dpId,$messageBlock;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',"<b>"+tName+"</b>");txt="<div id='_"+this.dpObjs[tName].id+"' class='message mes_not'> "+msg
+" <a class='goToDetails' href='#' data-dpid='"+this.dpObjs[tName].id+"'>"
+Runner.lang.constants.TEXT_DETAIL_GOTO+" "+tName+"</a>"
+" </div>";dpId=dpId||this.dpObjs[tName].id;messArr.push(txt);}else if(!this.dpObjs[tName].submitMade){return;}}}
this.form.makeReadonly();$messageBlock=Runner.isPD()?this.findItemType(this.messageItemType()):this.getBrickContentsElem('message');$messageBlock.on("click",".goToDetails",function(e){pageObj.scrollToDetails($(this).data("dpid"));return false;});this.showError(messArr,true);this.scrollToDetails(dpId);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===false){basicForm.validate();this.enablePageButtonsAfterSaving();}
return valRes;},this);this.form.on('successSubmit',function(respObj,basicForm,fieldControls){if(respObj.success){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.showElement("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();}
this.initLoginLink();if(!respObj.success){this.enablePageButtonsAfterSaving();return;}
this.masterSaved=true;evRes=this.fireEvent("afterSave",respObj,basicForm,fieldControls,this);if(evRes!==false&&(!this.isShowDetails||this.noDetailsToSave)){this.runAfterAddAction();return;}},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.showElement("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;},messageItemType:function(){return'add_message';}});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){var btn=this;pageObj.unlockPage(function(){pageObj.backButtonHref(btn);});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,pageViewUrl=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,this.keys);this.viewPageButton=$("[id='viewPageButton"+this.id+"']").on("click",function(e){var pageName=$(this).data("page")||false;if(Runner.isDisabledButton(this)){return false;}
pageObj.disablePageButtons();pageObj.unlockPage(function(){pageObj.openViewPage(pageName);});return false;});if(this.viewPageButton){if(this.viewPageButton.data("page")){pageViewUrl+="&page="+this.viewPageButton.data("page");}
this.viewPageButton.attr("href",pageViewUrl);}
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;}
if(typeof handler==='function'){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(pageName){var pageName=pageName||false,pageViewUrl=Runner.pages.getUrl(this.tName,Runner.pages.constants.PAGE_VIEW,this.keys);if(this.openMode!==Runner.pages.constants.OPENMODE_POPUP){window.location.href=pageViewUrl+(pageName?"&page="+pageName:"");return;}
var pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(this,this.keys,this.baseParams.rowId);if(pageName){pageParams.baseParams["page"]=pageName;}
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.showElement("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.showElement("message");}
hostPage.initLoginLink();hostPage.enablePageButtons();this.close();return;}
if(message){this.displayHalfPreparedMessage(message);this.showElement("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(btn){var page=$(btn).data("page")?"&page="+encodeURIComponent($(btn).data("page")):"";window.location.href=Runner.getPageUrl(this.shortTName,Runner.pages.constants.PAGE_LIST,'a=return'+page);},changePageHn:function(){Runner.pages.EditPage.superclass.changePageHn.apply(this,arguments);if(this.isPageModified()){this.disablePageButtons();}},initLocking:function(){if(!this.useLocking){return;}
$('.rnr-locking:not([data-locked])').show();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,masterPageObj:this,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,dpId;for(tName in this.dpObjs){if(this.dpObjs[tName].submitMade&&!this.dpObjs[tName].submitSucceded){msg=Runner.lang.constants.TEXT_DETAIL_NOT_SAVED.replace('%s',"<b>"+tName+"</b>");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>";dpId=dpId||this.dpObjs[tName].id;messArr.push(txt);}else if(!this.dpObjs[tName].submitMade){return;}}
$messageBlock=Runner.isPD()?this.findItemType(this.messageItemType()):this.getBrickContentsElem('message');$messageBlock.on("click",".goToDetails",function(e){pageObj.scrollToDetails($(this).data("dpid"));return false;})
this.showError(messArr,true);this.scrollToDetails(dpId);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);if(this.pageName){pageParams.baseParams["page"]=this.pageName;}
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();}},messageItemType:function(){return'edit_message';},});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;var $boxes=$("input[type=checkbox][id^=updsel_][data-field]",this.pageCont);if(!Runner.isPD()){$(".control-label:has(input[type=checkbox])",this.pageCont).addClass("checkbox");$(".control-label.checkbox",this.pageCont).on("click",function(e){$("input[type=checkbox]",this).click();});}else{$boxes.parent('label').on("click",function(e){$("input[type=checkbox][id^=updsel_][data-field]",this).click();});}
$("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();}});$boxes.on("change",function(event){var $cb=$(this);var 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();});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.showElement('message');if(!respObj.success){editPageObj.displayHalfPreparedMessage(respObj.message||"",true);editPageObj.showElement('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.showElement('message');}
pageObj.initLoginLink();pageObj.enablePageButtons();this.close();return;}
if(message){this.displayHalfPreparedMessage(message);this.showElement('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.SecurityPlugin=function(cfg){this.appId=cfg.appId;this.onsuccess=cfg.onsuccess;this.onfailure=cfg.onfailure;}
Runner.SecurityPlugin.prototype.getPlugins=function(cfg){var plugins=[],pageData=cfg.pageObj.pageData;if(pageData["isFB"]){cfg.appId=pageData["FBappId"];plugins.push(new Runner.SecurityPluginFB(cfg));}
if(pageData["isGoogleSignIn"]){cfg.appId=pageData['GoogleClientId'];plugins.push(new Runner.SecurityPluginGoogle(cfg));}
return plugins;};Runner.SecurityPluginFB=function(cfg){Runner.SecurityPlugin.call(this,cfg);this.getButtonElem=function(){return $(".bs-facebook",cfg.pageObj.pageCont).get(0);}}
Runner.SecurityPluginFB.prototype=Object.create(Runner.SecurityPlugin.prototype);Runner.SecurityPluginFB.prototype.init=function(){var pl=this;if(typeof FB==="object"&&typeof FB.XFBML==="object"&&typeof FB.XFBML.parse==="function"){FB.XFBML.parse(this.getButtonElem());return;}
window.fbAsyncInit=function(){FB.init({appId:pl.appId,autoLogAppEvents:true,xfbml:true,version:"v2.9",cookie:true});FB.Event.subscribe("auth.statusChange",function(response){if(response.authResponse&&response.status=="connected"){pl.onsuccess({a:"pluginLogin",plugin:"fb",plugin_token:response.authResponse.signedRequest,signed_request:response.authResponse.signedRequest});}else{pl.onfailure();}});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'));};Runner.SecurityPluginFB.constructor=Runner.SecurityPlugin;Runner.SecurityPluginGoogle=function(cfg){Runner.SecurityPlugin.call(this,cfg);this.getButtonId=function(){return'signinButton'+cfg.pageObj.id;}};Runner.SecurityPluginGoogle.prototype=Object.create(Runner.SecurityPlugin.prototype);Runner.SecurityPluginGoogle.prototype.init=function(){var tag=document.createElement('script');var firstScriptTag=document.getElementsByTagName('script')[0];window.gAPILoaded=this.gAPILoaded.bind(this);tag.src="https://apis.google.com/js/client:platform.js?onload=gAPILoaded";tag.setAttribute('defer','');tag.setAttribute('async','');firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);};Runner.SecurityPluginGoogle.prototype.gAPILoaded=function(){var pl=this,onSignIn,auth2;gapi.load('auth2',function(){auth2=gapi.auth2.init({client_id:pl.appId,});var buttonId=pl.getButtonId(),$button=$("#"+buttonId);gapi.signin2.render(buttonId,{scope:'profile email',width:$button.data('width'),height:$button.data('height'),longtitle:true,theme:'dark',onsuccess:onSignIn,onfailure:pl.onfailure});});onSignIn=function(googleUser){auth2.disconnect();pl.onsuccess({a:'pluginLogin',plugin:'go',plugin_token:googleUser.getAuthResponse().id_token,});};};Runner.SecurityPluginGoogle.constructor=Runner.SecurityPlugin;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,form:null,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();this.initSecurityPlugins();if(this.isPopUp){this.on('windowSizeCorrected',this.setUserFocus);}else{this.setUserFocus();}
this.fireEvent('afterInit',this,this.proxy,this.id);},initSecurityPlugins:function(){var pageObj=this;var plugins=Runner.SecurityPlugin.prototype.getPlugins({pageObj:this,onsuccess:function(params){if(pageObj.isPopUp){params.mode="popup";}
var pluginForm=new Runner.form.BasicForm({submitUrl:Runner.getPageUrl("login"),standardSubmit:!pageObj.isPopUp,method:'POST',id:pageObj.pageId,baseParams:params,successSubmit:pageObj.onLoginAction.bind(pageObj),});pluginForm.submit();pluginForm.destructor();pluginForm=null;},onfailure:function(data){if(data){pageObj.showMessage(data.details||data.error,true);return;}
pageObj.showMessage('User cancelled login or did not fully authorize.',true);}});plugins.forEach(function(pl){pl.init();});},initLanguageSelector:function(){var $form=$('#form'+this.id,this.pageCont),$langSelector=$("#languageSelector"),extraparams=$langSelector.data("params")||"",pageUrl=Runner.getPageUrl("login");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.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,simpleSubmit=!this.isPopUp&&!this.twoFactorAuth;$("#submitLogin"+this.id,this.pageCont).on("click",function(e){if(simpleSubmit){pageObj.submitSimpleLoginForm();}else{pageObj.submitRunnerLoginForm();}
return false;});this.initPopupButtons();},initPopupButtons:function(){var pageObj=this;if(!this.isPopUp){return;}
$('a[name="RegisterPage"]',this.pageCont).on("click",function(e){pageObj.registerPage($(this).data("table"));return false;});$('a[name="ForgotPasswordPage"]',this.pageCont).on("click",function(e){pageObj.forgotPasswordPage();return false;});this.initContinueButton();},initContinueButton:function(){var $continueButton=$("#continueButton",this.pageCont),pageObj=this;$continueButton.on("click",function(e){pageObj.close();return false;});},submitSimpleLoginForm:function(){var controlsToValidate=Runner.controls.ControlStorage.byId(this.pageId).slice(),invalidControls=this.getInvalidControls(controlsToValidate);if(!invalidControls.length){this.setFirstFocus(this.pageId,invalidControls);$('#form'+this.id,this.pageCont).submit();}},submitRunnerLoginForm:function(){this.form=this.form||new Runner.form.BasicForm({submitUrl:Runner.getPageUrl("login"),standardSubmit:false,isFileUpload:true,method:'POST',id:this.pageId,fieldControls:Runner.controls.ControlStorage.byId(this.pageId).slice(),successSubmit:this.onLoginAction.bind(this),});this.form.baseParams=this.getAJAXLikeLoginSubmitParams();this.form.submit();},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.isPopUp&&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.hideElement('loginfields');this.hideElement('wrapper');if(this.hostPageObj){this.hostPageObj.hideElement('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){if(Runner.isPD()){this.toggleItemType('auth_code',respObj.success);this.toggleItemType('verify_button',respObj.success);this.toggleItemType('resend_button',true);this.toggleItemType('login_button',false);this.toggleItemType('username',false);this.toggleItemType('password',false);this.toggleItemType('username_label',false);this.toggleItemType('password_label',false);this.toggleItemType('guest_login',false);if(this.isPopUp){this.toggleItemType('loginform_register_link',false);}}else{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.showElement('message');var $messageBrick=Runner.isPD()?this.findItemType(this.messageItemType()):this.getBrickElem('message');if(this.isBootstrap()){$messageBrick.html(message);$messageBrick.toggleClass("alert-danger",warning);$messageBrick.toggleClass("alert-success",!warning);}else{$("#login_message",$messageBrick).text(message);}},initiUserCodeControls:function(){var pageObj=this;$("#verifyCode"+this.id).off("click").on("click",function(e){if(!Runner.isDisabledButton(this)){var params={a:"verifyCode",SMSCode:$("#userCode"+pageObj.id).val(),mode:pageObj.isPopUp?"popup":"",notRedirect:pageObj.notRedirect?1:0,}
Runner.runnerAJAX(Runner.getPageUrl("login"),params,pageObj.onVerify.bind(pageObj));}
return false;});$("#resendCode"+this.id).off("click").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){if(Runner.isPD()){this.toggleItemType('auth_code',false);this.toggleItemType('verify_button',false);this.toggleItemType('resend_button',false);this.toggleItemType('continue_login_button',true);}else{this.hideBrick("loginfields");this.replaceBrickContentHTMLWith("loginbuttons",respObj["loginbuttons"]);}
this.initContinueButton();this.hostPageObj&&this.hostPageObj.hideElement("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);},forgotPasswordPage:function(){var pageObj=this,pageParams={pageType:Runner.pages.constants.PAGE_REMIND,tName:Runner.pages.PageSettings.getGlobalData("loginTName"),requestUrl:Runner.getPageUrl("remind"),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);},messageItemType:function(){return'login_message';},});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.showElement('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.bsWin){$(".modal-body",pageObj.bsWin).html(respObj.html);$(".modal-footer",pageObj.bsWin).html(respObj.footerCont);}else 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();}
if(respObj.additionalJS){$.each(respObj.additionalJS,function(jsFile,jsFileReq){Runner.util.ScriptLoader.addJS([jsFile],jsFileReq);});Runner.util.ScriptLoader.onFilesLoaded(function(){pageObj.pageData.buttons=respObj.pagesData[1]["buttons"];pageObj.initCustomButtons();},pageObj);Runner.util.ScriptLoader.load();}});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,detailsOrder:[],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();},getSearchControllerConfig:function(){var baseParams={};if(!this.isDefaultPage){baseParams.page=this.pageName;}
return{id:this.pageId,tName:this.tName,pageType:this.pageType,baseParams:baseParams,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);},getExtraPageReloadParams:Runner.emptyFn,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");});},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,detTName;if(Runner.isPD()){rowId=$(this).parent().attr('data-record-id');shortTName=$(this).attr('data-short-details');}else{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||"";});pageObj.dpObjs[tName].showPopup(this,pageObj.dpObjs[tName].getUrl(page),pageObj.tName,masterKeys[tName]);};$.each(this.dpObjs,function(tName,tObj){if(detTables[tName].listShowType!=Runner.pages.constants.DP_POPUP){return;}
var $detailLink;if(Runner.isPD()){$detailLink=$("[data-itemtype=grid_details_link][data-pageid="+pageObj.id+"] [data-short-details="+tObj.shortTName+"]");}else{$detailLink=$("[id^='master_"+tObj.shortTName+"'],a[id^='"+tObj.shortTName+"_preview']",pageObj.getBrickGridElem());}
if(Runner.isDirRTL()){$detailLink.attr("dir",$("html").attr("dir"));}
if(Runner.isPD()){$detailLink.unbind('mouseenter').unbind('mouseleave').bind({mouseenter:masterMouseOver,mouseleave:$.proxy(tObj.hidePopup,tObj)});}else{$detailLink.unbind('mouseover').unbind('mouseout').bind({mouseover:masterMouseOver,mouseout:$.proxy(tObj.hidePopup,tObj)});}});},getDetailsOrders:function(){var self=this,firstRecordId,$previeItems;if(!this.detailsOrder.length){firstRecordId=$("[data-itemtype=details_preview]:first",this.gridElem).attr("data-record-id");$previeItems=this.findItemType("details_preview",firstRecordId);if($previeItems.length){$previeItems.each(function(){var tables=$(this).attr("data-orders").split(",");self.detailsOrder=self.detailsOrder.concat(tables);});}}
return this.detailsOrder;},getDetailsTabId:function(tName){var goodTName=Runner.goodFieldName(tName),detOrders;if(Runner.isPD()){detOrders=this.getDetailsOrders();if(detOrders.indexOf(goodTName)!==-1){return detOrders.indexOf(goodTName);}}
return this.nextDetailsTabId++;},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.getDetailsTabId(tName));}},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(this.controlsMap.gridRows){dpParams.rows=this.controlsMap.gridRows.slice(0);}
if(listShowType==Runner.pages.constants.DP_NONE){return new Runner.util.details.ListWithoutPreview(dpParams);}
dpParams.proceedLink=dSettings.proceedLink;dpParams.previewPageId=dSettings.pageId;if(listShowType==Runner.pages.constants.DP_POPUP){if(Runner.isPD()){dpObj=new Runner.util.details.PDPopupDetails(dpParams);}else{dpObj=new Runner.util.details.DPPopUp(dpParams);}
dpObj.init();return dpObj;}
dpParams.tabSettings={tabLabel:dSettings.label,tabIndex:tabIdx};if(Runner.isPD()){dpParams.masterPageObj=this;dpObj=new Runner.util.details.NewListPreview(dpParams);}else{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);var pageObj=this;$("[id='recordspp"+this.id+"']").on("change",function(e){pageObj.reload({pagesize:this.options[this.selectedIndex].value});});},messageItemType:function(){return'grid_message';},});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:Runner.emptyFn,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(){this.gridElem=this.getBrickGridElem();$(this.gridElem).off("click.opentext").on("click.opentext",this.largeTextOpenerDelegate.bind(this));},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;},getResizableColumnsData:function(){if(!this.bsResizeInitialized){return null;}
var data={gridWidth:$(this.gridElem).width(),thWidths:{}}
$("th",this.gridElem).each(function(i,th){var $th=$(th),cellId=$th.data("cellid");if(cellId){data.thWidths[cellId]=$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});resizableColumnsData=this.resizableColumnsData||this.getServerResizableColumnsData();$grid.css('width','auto');$("th",this.gridElem).each(function(i,th){var $th=$(th),cellId=$th.data("cellid");if(resizableColumnsData&&resizableColumnsData.thWidths[cellId]){$th.width(resizableColumnsData.thWidths[cellId]);if(parseInt(resizableColumnsData.thWidths[cellId],10)>$th.width()){delta=delta+parseInt(resizableColumnsData.thWidths[cellId],10)-$th.width();}}});if(resizableColumnsData){if($grid.width()<resizableColumnsData.gridWidth){$grid.width(resizableColumnsData.gridWidth);$grid.css('min-width',resizableColumnsData.gridWidth+'px');}else{$grid.width($grid.width()+delta);}}else{$grid.css('width',$grid.width()+'px');}
$grid.colResizable({resizeMode:'overflow',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),pageObj=this;$grid.colResizable({disable:true});$grid.colResizable({resizeMode:'overflow',onResize:function(){$.post(pageUrl,pageObj.getResizeColumnsLoggerParams());}});},initHeaderCheckBox:function(){var pageObj=this,$checkboxHead=$('.chooseAll'+pageObj.id),$checkBoxHeadCell=$checkboxHead.parents("[data-checkbox-cell]");if(!$checkBoxHeadCell.length){$checkBoxHeadCell=$checkboxHead.parent();}
$checkBoxHeadCell.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+'_]:visible').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();});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"),$expSelBtns=$("[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().is("li")){$(this).parent().addClass("disabled")}else{$(this).attr('disabled',"");}});}else{$buttons.each(function(){if($(this).parent().is("li")){$(this).parent().removeClass('disabled');}else{$(this).removeAttr('disabled',"");}});}}
if(this.isBootstrap()){$expSelBtns.each(function(){if($selBoxes.length){if($(this).parent().is("li")){$(this).parent().removeClass('disabled')}else{$(this).removeAttr('disabled');}}else{if($(this).parent().is("li")){$(this).parent().addClass('disabled')}else{$(this).attr('disabled',true);}}});}
if($selBoxes.length){$printSelection.prop("disabled",false).prop("checked",true);$labelPrintSelection.css("color","inherit");}else{$printSelection.prop("checked",false).prop("disabled",true);$printPage.prop("checked",true);$labelPrintSelection.css("color","gray");}},getSelBoxes:function(){return $("input[type='checkbox'][id^='check"+this.id+"_']:checked");},getSelectedRecordIds:function(){var ret=[];this.getSelBoxes().each(function(){ret.push($(this).closest('[data-record-id]').data('record-id'));});return ret;},getSelectedRecordKeys:function(){var recordKeys=[];var rows=this.getInlineEditObj().rows;this.getSelectedRecordIds().forEach(function(recordId){var row=rows.find(function(r){return r.id==recordId});if(row){recordKeys.push(row.keys.slice());}});return recordKeys;},getSelectedRecords:function(){var recordObjects=[];var pageObj=this;var rows=this.getInlineEditObj().rows;this.getSelectedRecordIds().forEach(function(recordId){var row=rows.find(function(r){return r.id==recordId});if(row){recordObjects.push(new Runner.AjaxRow(pageObj,row));}});return recordObjects;},getRowObject:function(id){var row=this.getInlineEditObj().rows.find(function(r){return r.id==id;});return row?new Runner.AjaxRow(this,row):null;},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;});},getAllRecords:function(){var pageObj=this,inlineObj=this.getInlineEditObj();if(!inlineObj){return[];}
return inlineObj.rows.map(function(row){return new Runner.AjaxRow(pageObj,row);});},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(Runner.pages.PageSettings.getTableData(this.tName,"displayLoading"))
this.showLoadingBox();},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");},getBelowGridHeight:function(){var $belowGrid=this.layoutHelper.getFormElement("below-grid");if(!$belowGrid.length){return 0;}
return $belowGrid.outerHeight(true)+parseInt($belowGrid.css("margin-top"),10)+parseInt($belowGrid.css("margin-bottom"),10);},initScrollGridBody:function(){if(!Runner.isPD()||!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(),fullGridHeight=gridHeight+gridPosition.top+this.getBelowGridHeight(),gridWidth=this.gridElem.width(),scrollGridHeight=this.heightScrollGridBody,$thead=this.gridElem.children('thead'),$header=$thead.children(),$tbody=this.gridElem.children('tbody'),$tfoot=this.gridElem.children('tfoot'),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),$('tfoot tr',this.gridElem));theadHeight=$header.innerHeight()||32;bottomHeight=0;if(!scrollGridHeight){var delta=5;scrollGridHeight=viewPortHeight-gridPosition.top-this.getBelowGridHeight()-delta;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;}}
this.gridElem.width(gridWidth);$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.gridElem.css("margin-bottom",0);$tbody.children(":not(.gridRowAdd)").first().children().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.inGridCell),tbodyOffset=$tbody.offset(),fullGridHeight=$tbody.height()+tbodyOffset.top+this.getBelowGridHeight(),$thead=$('thead',this.gridElem).not(this.inGridCell),$tfoot=$('tfoot',this.gridElem).not(this.inGridCell),theadHeight,bottomHeight,scrollGridHeight,contentHeight;if(fullGridHeight<viewPortHeight){contentHeight=$tbody.get(0).scrollHeight;}
var delta=5;scrollGridHeight=viewPortHeight-tbodyOffset.top-this.getBelowGridHeight()-$thead.height()-$tfoot.height()-delta;if(scrollGridHeight<32){scrollGridHeight=32;}
if(contentHeight&&contentHeight<scrollGridHeight+$thead.height()+$tfoot.height()){scrollGridHeight=contentHeight-$thead.height()-$tfoot.height();}
$tbody.height(scrollGridHeight);if(Runner.isPD()){this.gridElem.height(scrollGridHeight+$thead.height()+$tfoot.height());}
$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.inGridCell),$thead=$('thead',this.gridElem).not(this.inGridCell),$tfoot=$('tfoot',this.gridElem).not(this.inGridCell),$header=$('thead tr',this.gridElem).not(this.inGridCell),$gridCell=$(el),$headerCell=$header.children('th').eq(ind),$footerCell=$tfoot.children('td').eq(ind),beforeGWidth=$gridCell.data("beforeGWidth"),gWidth,fWidth,hWidth,mWidth,oldTbodyWidth=$tbody.data("oldTbodyWidth")||$tbody.width();if(Runner.isPD()){$footerCell=$('tr',$tfoot).children('td').eq(ind);}
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);},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,$gridRowCells;if(Runner.isPD()){rowClass='r-gridrow';}
$gridRow=$('tbody > .'+rowClass+':not(.gridRowAdd):first',this.gridElem).not(this.inGridCell);$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.inGridCell).css('position','static');$edgeRows.children(cellsSelector).css('min-width','auto').css('width','auto');},inDetailPreviewContainer:function(){return $(this).closest('td.dpinline').length;},inGridCell:function(){return $(this).closest('td').length;},adjustScrollableGridContainer:function(scrollElementWidth,$container){$container.width(this.gridElem.width()+scrollElementWidth);},getEditLinkHandler:function(row,method){var pageObj=this;if(method=='popup'){return function(){var $button=$(this),pageParams;pageObj.hideElement('message');pageParams=Runner.pages.EditPage.prototype.getOpenPageParams.call(pageObj,row.keys,row.id,"",pageObj.inlineEdit,Runner.emptyFn);if($button.data("page")){pageParams.baseParams["page"]=$button.data("page");}
pageParams.popupWidth=$button.data("popupwidth");pageParams.popupHeight=$button.data("popupheight");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(){var $button=$(this),pageParams;pageObj.hideElement('message');pageParams=Runner.pages.ViewPage.prototype.getOpenPageParams.call(pageObj,row.keys,row.id,pageObj.getInlineEditObj(),Runner.emptyFn);if($button.data("page")){pageParams.baseParams["page"]=$button.data("page");}
pageParams.popupWidth=$button.data("popupwidth");pageParams.popupHeight=$button.data("popupheight");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.hideElement('message');var 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.hideElement('message');var 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;});},getDetailsPages:function(rowId){var rowObj=this.getRowObject(rowId);return rowObj&&rowObj.getDetails();},getDetailsPage:function(table,rowId){var rowObj=this.getRowObject(rowId);return rowObj&&rowObj.getDetails()[table];}});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"];this.lookupBaseParams=this.lookupCtrl.getLookupParams(this.pageId);this.lookupBaseParams.page=this.pageName;},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.hideElement(["bars_menu_icon"]);}
this.initLinks();this.initSorting();this.initSortByDropdown();if(Runner.isPD()){this.togglePageMobileCollapse(undefined,false);}else 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:Runner.pages.PageSettings.getTableData(this.tName,"ajaxSuggest"),pageType:this.pageType,formBaseParams:this.lookupBaseParams,filterContolsData:this.controlsMap.filters?this.controlsMap.filters.controls:[],delegatedExtraSuggestParams:this.extraSearchSuggestParams.bind(this),});this.searchController.init(this.controlsMap.search.searchBlocks);if(!Runner.isMobile){this.searchController.srchForm.on("beforeSubmit",function(){this.preparePageForReloading();},this);this.searchController.srchForm.on("submitFailed",function(){Runner.stopLoading();},this);}
this.searchController.on("afterSearch",function(respObj,srchController,srchForm){if(!Runner.isMobile){Runner.stopLoading();}
this.pageReloadHn(respObj);this.searchController.toggleShowAll(this.searchController.usedSrch);},this);},extraSearchSuggestParams:function(){return{forLookup:1,mainTable:this.lookupCtrl.table,mainField:this.lookupCtrl.fieldName,mainPageType:this.lookupCtrl.pageType,parentCtrlsData:JSON.stringify(this.lookupCtrl.getParentControlsData()),};},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,newData){var $link=$('tr[id="gridRow'+rowId+'"] a[type="lookupSelect'+this.pageId+'"]').eq(0),linkValue,newInd;newInd=this.lookupCtrl.addLookupVal(newData.linkValue,newData.displayValue);$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,tabsSelector=Runner.isPD()?'.bsgrid_tabs':'[data-brick=bsgrid_tabs]';$(pageObj.pageCont).on('click',tabsSelector+' li > a[data-pageid='+this.id+'][data-tabid]',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);});});},pageReloadHn:function(respObj){Runner.stopLoading();if(!respObj.success){this.win.set('bodyContent',"REQUEST FAILED");return;}
this.destroyVideo();Runner.setIdCounter(respObj.idStartFrom);this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.pageId];if(Runner.isPD()){var $content=this.winObject.getContentNode(),$header=this.winObject.header(),$footer=this.winObject.footer(),$body=this.winObject.body();$body.height($body.height());$body.html(respObj['html']);var itemSelector='[data-itemid]:not(li)',footerContent=$(respObj.footerCont).find(itemSelector).addBack(itemSelector);$footer.html(footerContent);$body.height($content.innerHeight()-$header.outerHeight()-$footer.outerHeight()-$body.outerHeight()+$body.height());this.initSearch();this.initPagination();this.inlineButtonsIntialized=false
this.initInline();this.togglePageMobileCollapse(undefined,false);}else{this.replaceBricksHTMLWith(this.getBricksHtml(respObj.html));}
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);},initResize:Runner.emptyFn,initScrollGridBody:Runner.emptyFn,setUrlParams:Runner.emptyFn,getGrayedElement:function(){if(this.isBootstrap()){return this.bsWin?$(".modal-content",this.bsWin):this.gridElem;}
return this.win?this.win.bodyNode.getDOMNode():this.gridElem;},getBaseParams:function(){return this.lookupBaseParams;},});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")){this.initReorderingInSHPanel();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=Runner.isPD()?$('[data-location="grid"][data-pageid='+this.id+']'):$('[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;});var hideAttr=Runner.isPD()?'data-hidden':'data-hidden-column'
$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(Runner.isPD()){pageObj.layoutHelper.toggleField(field,show);}else{if(vertical){if(show){$dataFieldElem.removeAttr(hideAttr);$dataFieldElem.find('.bs-view-label').attr('data-forced-visible-column','');$dataFieldElem.find('.bs-horizontal-value').attr('data-forced-visible-column','');}else{$dataFieldElem.attr(hideAttr,'');$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(hideAttr).attr('data-forced-visible-column','');$('tfoot tr',this.gridElem).removeAttr(hideAttr);}else{$dataFieldElem.attr(hideAttr,'').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(this.tName,this.pageType),columnOrder=reInitColumnOrder||Runner.pages.PageSettings.getTableData(this.tName,"columnOrder"),$gridHorizonatal=$('table[data-location="grid"][data-pageid='+this.id+']'),$gridVertical=$('.r-grid-vertical[data-pageid='+this.id+']'),columnNormalOrder={},needClickAfterReorder=[],dragged,ctrlKey,firstTarget,skipFirstDrag;if($gridHorizonatal.length>0){columnNormalOrder=this.refineColumnsOrderData(columnOrder,$gridHorizonatal);$gridHorizonatal.find('th[data-field]').on('mousedown',function(e){ctrlKey=e.ctrlKey;firstTarget=e.target;});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)});},clickDelay:150,restoreState:columnNormalOrder,beforeStart:function(table){var $visibleDPreviewRows;if(Runner.isPD()){$visibleDPreviewRows=$gridHorizonatal.find(".r-gridrow.bs-details-opened");}else{$visibleDPreviewRows=$gridHorizonatal.find(".rnr-bs-dpreviewrow");}
$visibleDPreviewRows.each(function(i,item){var $dpButton;if(Runner.isPD()){$dpButton=$(item).find("a[id^=details_]:first");}else{$dpButton=$(item).prev().find("a[id^=details_]:first");}
if($dpButton.length){$dpButton.click();needClickAfterReorder.push($dpButton);}});},beforeStop:function(table){$.each(needClickAfterReorder,function(i,$dpButton){$dpButton.click();});if(Runner.isPD()){needClickAfterReorder=[];}
pageObj.onReoderColumnsStop();var $widget=$gridHorizonatal.data("akottrDragtable");$widget.sortableTable.el.off("mousemove.realdrag");if(!dragged){$(firstTarget).trigger(jQuery.Event("click",{ctrlKey:ctrlKey}));}
firstTarget=undefined;ctrlKey=undefined;dragged=false;skipFirstDrag=false;},beforeMoving:function(table,sortableTable){sortableTable.el.on("mousemove.realdrag",function(e){if(skipFirstDrag){dragged=true;}else{skipFirstDrag=true;}});}});this.onReoderColumnsStop();if(!reInitColumnOrder){pageObj.hideFieldPanelOrder(columnOrder);}
return;}
if(!Runner.isPD()&&$gridVertical.length>0){var selector=".panel-body:visible > table > tbody";if(reInitColumnOrder&&!ajaxReload){$gridVertical.find(selector).sortable("destroy");}
$gridVertical.find(selector).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);}}});}},refineColumnsOrderData:function(columnsOrder,$grid){if(!Array.isArray(columnsOrder)){return{};}
var columnsNormalOrder={},newColumns=[],currentColumnsOrder=[],refinedColumnsOrder=[],firstColumnIndex=$grid.find('th[data-field]').first().index();$grid.find('th[data-field]').each(function(idx,el){var fieldName=$(el).data('field');currentColumnsOrder.push(fieldName);if(columnsOrder.indexOf(fieldName)===-1){newColumns.push(fieldName);}});columnsOrder.forEach(function(fieldName,pos){if(currentColumnsOrder.indexOf(fieldName)!==-1){refinedColumnsOrder.push(fieldName);}})
refinedColumnsOrder.concat(newColumns).forEach(function(fieldName,pos){columnsNormalOrder[fieldName]=pos+firstColumnIndex;})
return columnsNormalOrder;},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(){if(this.controlsMap.gridRows){this.initInlineEdit();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,row){this.fireEvent("afterInlineEdit",fieldsData,row);},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,row){this.fireEvent("afterInlineAdd",fieldsData,row);},this);this.inlineAdd.on("afterInit",function(pageObj,proxy,pageid,row){this.afterInitInlineAdd(row);},this);},afterInlineAdd:function(fn){this.on('afterInlineAdd',fn,this);},afterInlineEdit:function(fn){this.on('afterInlineEdit',fn,this);},onAfterShowDetails:function(){},initButtons:function(){this.initDeleteButton();this.initUpdateSelectedButton();this.initAddButton();this.initRecordBlock();this.initExportLinks();this.initPrintLink();this.initAdvSearch();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,baseParams={a:'delete'};if(!$selBoxes.length||!confirm(Runner.lang.constants.TEXT_DELETE_CONFIRM)){return false;}
if(!this.isDefaultPage){baseParams.page=pageObj.pageName;}
form=new Runner.form.BasicForm({standardSubmit:true,submitUrl:submitUrl,method:'POST',id:pageObj.id,baseParams:baseParams,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);if($(this).data("page")){pageParams.baseParams["page"]=$(this).data("page");}
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,[]);if($(this).data("page")){pageParams.baseParams["page"]=$(this).data("page");}
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;var $button=$("[id=addButton"+this.id+"]").off("click").on("click",function(e){var pageName=$button.data("page");if(!pageObj.showAddInPopup($button)){pageName=pageName?"?page="+pageName:"";window.location.href=Runner.pages.getUrl(pageObj.tName,Runner.pages.constants.PAGE_ADD)+pageName;return false;}
var pageParams=Runner.pages.AddPage.prototype.getOpenPageParams.call(pageObj,pageObj.id);if(pageName){pageParams.baseParams["page"]=pageName;}
pageParams.popupWidth=$button.data("popupwidth");pageParams.popupHeight=$button.data("popupheight");pageObj.hideElement('message');Runner.pages.PageManager.openPage(pageParams);return false;});},initUpdateSelectedButton:function(){var pageObj=this,rowid,$selBoxes=this.getSelBoxes(this.id);if(!Runner.isPD()&&!Runner.pages.PageSettings.getTableData(pageObj.tName,"updateSelected")){return;}
if(Runner.isPD()&&!this.hasItemType("update_selected")){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 false;}
if(!pageObj.showEditInPopup($(this))){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.hideElement('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();if(Runner.pages.PageSettings.getTableData(this.tName,"displayLoading"))
this.showLoadingBox();},initGridTabs:Runner.emptyFn,initSorting:function(){var pageObj=this;this.listFields.forEach(function(listField){$('[id="order_'+Runner.goodFieldName(listField)+'_'+pageObj.id+'"]').on("mouseout",pageObj.delSortHint.bind(pageObj)).on("mousemove",pageObj.moveSortHint.bind(pageObj)).on("mouseover",pageObj.addSortHint.bind(pageObj)).on("click",function(e){pageObj.reload({orderby:e.ctrlKey?$(this).data("multisort")+';'+$(this).data("order"):$(this).data("order")},pageObj.getSortingReloadParams());});});},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(){if(["ADMIN_MEMBERS","ADMIN_ADMEMBERS"].indexOf(this.tName.toUpperCase())!==-1){return;}
var layout=Runner.pages.PageSettings.getTableData(this.tName,"listGridLayout"),clickActions=Runner.normalizeClickActionSettings(Runner.pages.PageSettings.getTableData(this.tName,'clickActions')),rowSelector=layout===Runner.pages.constants.HORIZONTAL_LAYOUT?'[id^=gridRow]':'.panel[data-record-id]';this.setClickActionHandler(clickActions.row,rowSelector);for(var f in clickActions.fields){var fieldSelector=rowSelector+(layout===Runner.pages.constants.VERTICAL_LAYOUT?' ':' td')
+'[data-field='+Runner.goodFieldName(f)+']';this.setClickActionHandler(clickActions.fields[f],fieldSelector);}},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.getDetailsTabId(table),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;}
if(!$elem.closest('[data-location][data-pageid]').is(this.gridElem)||$elem.is('.bs-proceed-link')){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");}},setUrlParams:function(){if(this.dashElement===undefined&&this.pageData.urlParams&&!Runner.Hash.oldbrowser()){Runner.Hash.set(this.pageData.urlParams,true);}},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.getGrayedElement());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(){Runner.pages.ListPageAjax.superclass.initPagination.call(this);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.toggleElement("toplinks_print",numberOfRecs>0);this.toggleElement("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.toggleElement("printpanel",numberOfRecs>0);},updateFieldHidePanel:function(numberOfRecs){this.toggleElement("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.toggleElement("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();},getBaseParams:function(){return this.ajaxBaseParams;},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};if(!this.isDefaultPage){this.baseParams.page=this.baseParams.page||this.pageName;}
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,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){pageObj.preparePageForReloading();Runner.runnerAJAX(pageObj.getSortUrl(e,$(this)),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)});});},pageReloadHn:function(respObj){var parPageObj=Runner.pages.PageManager.getAt(this.masterTable,this.parId);Runner.stopLoading(this.getGrayedElement());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{if(Runner.isPD()){parPageObj.dpObjs[this.tName].revertTmpAboveGrid(this);}
Runner.pages.PageManager.putToDashContainer.call(this,respObj,this.detCont);if(Runner.isPD()){parPageObj.dpObjs[this.tName].makeTmpAboveGrid(this);}}
if(respObj.controlsMap){this.controlsMap=respObj["controlsMap"][this.tName][this.pageType][this.pageId];}
this.toggleElement("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();this.initCustomButtons();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);},showAddInPopup:function($link){return true;},showEditInPopup:function($link){return true;},showViewInPopup:function($link){return true;},getGrayedElement:function(){return this.detCont[0];},});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.initAdminButton();},initLinksMore:function(){var $gridElem=Runner.isPD()?this.findForm('grid'):$(this.getBrickElem((this.isBootstrap()?"bs":"")+"report"));$gridElem.off("click.opentext").on("click.opentext",this.largeTextOpenerDelegate.bind(this));},getAdvancedSearchUrl:function(){return Runner.getPageUrl(this.shortTName,"search",this.getParamsString());},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;});},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.REPORT_DASHBOARD&&this.dashboard){this.initDashCrossTableGroupSelection();return;}
$("#select_group_x"+this.id).on("change",function(e){window.location.href=pageObj.reportFileName+"?"+pageObj.getParamsString({axis:'x'});return false;});$("#select_group_y"+this.id).on("change",function(e){window.location.href=pageObj.reportFileName+"?"+pageObj.getParamsString({axis:'y'});return false;});},initDashCrossTableGroupSelection:function(){if(!this.crossTable||this.pageMode!==Runner.pages.constants.REPORT_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("r-field-text r-field-number rnr-field-crossdate").addClass(response["dataClass"]);}
$("#"+rowInfo["id_row_summary"]+"_"+pageObj.id).html(rowInfo["row_summary"]).removeClass("r-field-text r-field-number rnr-field-crossdate").addClass(response["dataClass"]);});$.each(colsSummary,function(idx,colSummary){$("#"+colSummary["id_col_summary"]+"_"+pageObj.id).html(colSummary["col_summary"]).removeClass("r-field-text r-field-number rnr-field-crossdate").addClass(response["dataClass"]);});$("#id_total_summary_"+pageObj.id).html(response["totalSummary"]).removeClass("r-field-text r-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(additionalParams){if(!this.crossTable){return"";}
var prms=this.getCrosstableParams(additionalParams);return prms?$.param(prms):"";},getCrosstableParams:function(additionalParams){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()};Object.keys(additionalParams||{}).forEach(function(k){params[k]=additionalParams[k];});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.hideExcessSeparators();this.initAdvSearch();this.createCharts();this.fireEvent('afterInit',this,this.proxy,this.id);},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(){if(Runner.pages.PageSettings.getTableData(this.tName,"displayLoading"))
this.showLoadingBox();},});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();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();Runner.runnerAJAX(pageObj.reportFileName+"?"+pageObj.getParamsString(),pageObj.baseParams,function(respObj){pageObj.pageReloadHn.call(pageObj,respObj)});return false;});},initSearch:Runner.emptyFn,pageReloadHn:function(respObj){var parPageObj=Runner.pages.PageManager.getAt(this.masterTName,this.parId);Runner.stopLoading(this.getGrayedElement());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);},getGrayedElement:function(){return this.detCont[0];}});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.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",zoom:100,preSplit:false,autoZoom:false,edgeClass:"rnr-edge",contentWidth:Runner.pages.constants.VPRINT_PAGE_WIDTH,pages:[],layout:0,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;var zoom=120;this.contentWidth=this.getContentWidth();if(this.autoZoom){$(".rp-page").each(function(i,page){var wZoom=100.0*pageObj.pageWidth/$(page).width();if(wZoom>120){wZoom=120;}
zoom=zoom>wZoom?wZoom:zoom;});this.zoom=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");},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);}});},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);});});},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>');}},});Runner.pages.PrintPage=Runner.extend(Runner.pages.PrintPageCommon,{dpObjs:null,constructor:function(cfg){Runner.pages.PrintPage.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.PrintPage.superclass.init.call(this);this.baseParams=this.baseParams||{};this.baseParams.selection=this.pageData.printSelection;this.baseParams.all=this.pageData.printAll;this.baseParams.details=this.pageData.printDetails;this.baseParams.records=this.pageData.printRecords;this.initColumnReordering();this.initDetails();this.fireEvent('afterInit',this,this.proxy,this.id);},initDetails:function(){if(!this.viewControlsMap||!this.viewControlsMap.dViewControlsMap){return;}
this.dpObjs={};for(var tName in this.viewControlsMap.dViewControlsMap){var dParams={tName:tName,masterTName:this.tName,pageId:this.viewControlsMap.dViewControlsMap[tName].id,viewControlsMap:this.viewControlsMap.dViewControlsMap[tName],masterPageObj:this,};this.dpObjs[tName]=new Runner.pages.PrintPageDetails(dParams);this.dpObjs[tName].init();}},getPrintGrid:function(){if(Runner.isPD()){return this.layoutHelper.getFormElement("grid");}
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||!Array.isArray(columnOrder)||!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(){if(Runner.isPD()){return!!$(this).find(".details-grid").length}
return!!$(this).find(".rnr-print-details").length;},inDetailPreviewContainer:function(){if(Runner.isPD()){return!!$(this).closest(".details-grid").length}
return!!$(this).closest('.rnr-print-details').length;},});Runner.pages.PrintPageDetails=Runner.extend(Runner.pages.RunnerPage,{constructor:function(cfg){Runner.pages.PrintPageDetails.superclass.constructor.call(this,cfg);},init:function(){Runner.pages.PrintPageDetails.superclass.init.call(this);},initPdfMake:Runner.emptyFn,});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";}},isCrossTable:function(){return this.reportType==Runner.pages.constants.REPORT_TYPE_CROSSTAB;},init:function(){Runner.pages.ReportPrintPage.superclass.init.call(this);this.baseParams=this.baseParams||{};this.baseParams.all=this.pageData.printAll;this.baseParams.records=this.pageData.printRecords;this.fireEvent('afterInit',this,this.proxy,this.id);},getContentWidth:function(){if(!this.isBootstrap()){return $(".rnr-report-gridblock").width();}
return $(".rp-page").width()||document.body.clientWidth;},getBaseParams:function(){var baseParams=Runner.pages.ReportPrintPage.superclass.getBaseParams.call(this);if(this.isCrossTable()&&this.pageData.crossParams){return Runner.apply(baseParams,this.pageData.crossParams);}
return baseParams;},});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.initAdvSearch()
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",page:this.pageName},useSuggest:true});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}
additionalPageParams.baseParams=additionalPageParams.baseParams||{};additionalPageParams.baseParams.page=dbelem.pageNames[pageType];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.toggleDashElement(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.baseParams.page=details.pageName;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),page:dbelem.pageName,}};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;},toggleDashElement: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.toggleDashElement(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.toggleDashElement(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);this.moveElements();$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.r-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();});},moveElements:function(){var $aboveGridForm=this.layoutHelper.getFormElement("above-grid");var $firstCell=$aboveGridForm.find('[data-cellid]:first');var $buttonItems=$aboveGridForm.find('[data-button-item]');var $displayingItem=this.layoutHelper.findItemType('details_found');var $headerCont=$('<div></div>').attr('class','rnr-dbebrick rnr-dberight').appendTo(this.$panel.children('.panel-heading'));$headerCont.append($displayingItem).append($firstCell.children()).append($buttonItems);var $buttons=$headerCont.find('.btn');$buttons.removeClass('btn-lg').removeClass('btn-sm').addClass('btn-xs');$buttons.filter('.btn-primary').removeClass('btn-primary').addClass('btn-default');},showAddInPopup:function($link){return true;},showEditInPopup:function($link){return true;},showViewInPopup:function($link){return true;},});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.showElement('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.showElement('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.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(.r-admin-checkbox:not(.columnheader):not(.rowheader))",function(e){var $checkbox=$(e.target).add($(e.target).find(".r-admin-checkbox")).filter(".r-admin-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("r-rights-modified",groupModified);userModified=userModified||groupModified;});$("#cellusername"+userId).toggleClass("r-rights-modified",userModified);$("#cellDisplayName"+userId).toggleClass("r-rights-modified",userModified);$("#cellEmail"+userId).toggleClass("r-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.toggleJQElement($("#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;},toggleJQElement:function($elem,show){if(!show){$elem.hide();}else{$elem.css('display','');}},initModifiedFilter:function(){var pageObj=this,$control=$("#linkselectFilter");$control.on("click","a",function(e){pageObj.usersFilterState=$(this).parent().data('value');pageObj.showHideRows();$control.find('.btn').text($(this).text());$control.find('.dropdown-toggle').click();return false;});},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');return false;});$("#displayNameSort").on("click",function(){pageObj.sort(this,'displayUserName');return false;});$("#EmailSort").on("click",function(){pageObj.sort(this,'emailUser');return false;});$.each(this.groups,function(groupId,groupName){$("#colsort"+groupId).on("click",function(){pageObj.sort(this);return false;});});},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){Runner.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 flyWinHandler=this.flyWinHandler.bind(this),args={modal:true,centered:true,bodyContent:'',headerContent:Runner.lang.constants.AA_CHOOSE_COLUMNS_TO_DIPLAY,footerContent:this.getChooseColumnsFooter()};$('#chooseColumnsButton').on('click',function(e){Runner.pages.PageManager.createBSWin(args,false,flyWinHandler);return false;});},getChooseColumnsFooter:function(){return'<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>';},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,modifiedFields={},$rows=$("<div></div>"),$modal=win._obj;$.each(this.fields,function(idx,fieldInfo){var $row=$('<a class="chooseColumnsLink"></a>').text(" "+fieldInfo["caption"]),$checkBox=$('<span class="r-admin-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);});$rows.appendTo($(".modal-body",$modal));$("#mpSelectAll",$modal).on("click",function(e){pageObj.selectAllNoneToFlyWin(1,modifiedFields);return false;});$("#mpAASelectNone",$modal).on("click",function(e){pageObj.selectAllNoneToFlyWin(0,modifiedFields);return false;});$("#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);$("[data-column='"+fieldName+"']")
pageObj.toggleJQElement($("#tdsort"+fieldName),fieldInfo["visible"]);pageObj.toggleJQElement($("#tdbox"+fieldName),fieldInfo["visible"]);pageObj.toggleJQElement($("[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");return false;});$("#mpAACancel",$modal).on("click",function(e){$modal.modal("hide");return false;});},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;},getLogoutUrl:function(){return Runner.getPageUrl(this.pageType)+"?a=logout";},});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,groups:null,tables:null,pages:null,masks:{},modifiedRights:{},modifiedRestrictedPages:{},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.apply({},Runner.pages.PageSettings.getTableData(this.tName,"groups"));this.savedRights=Runner.pages.PageSettings.getTableData(this.tName,"rights");this.savedPageRestrictions=Runner.pages.PageSettings.getTableData(this.tName,"pageRestrictions");this.tables=Runner.pages.PageSettings.getTableData(this.tName,"tables");this.pages=Runner.pages.PageSettings.getTableData(this.tName,"allPages")||{};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;});this.$groupControl=$('[data-groups]');},init:function(){Runner.pages.RightsPage.superclass.init.call(this);Runner.addDisabledClass($('#resetBtn'));Runner.addDisabledClass($('#saveBtn'));this.initMasks();this.initSearchBox();this.initGroupsList();this.initColumnHeaders();this.initRowHeaders();this.initCheckboxes();this.initPageCheckboxes();this.initShowHidePages();this.initGroupsButtons();this.initModifiedFilter();this.initOrderControl();this.initCopyPermissions();this.initExpandAll();this.initExpandCollapseControls();this.initSave();this.initReset();this.showHideRows();},initMasks:function(){this.masks={add:'A',edt:'E',del:'D',lst:'S',exp:'P',imp:'I',adm:'M'}},getPopupAfterCreateHn:function(onButtonSaveClick){var onButtonSaveClickHn=function(win,groupName){var success=onButtonSaveClick(groupName);if(success){win.close();return;}
$('.alert-danger',win.getContentNode()).show();Runner.pages.PageManager.correctBSWindowSize(win._obj);};return function(win){var context=win.getContentNode();var $grName=$('.groupname',context).css('width','300px').focus().keydown(function(e){if(e.keyCode==13){onButtonSaveClickHn(win,$(this).val());}});$('.alert-danger',context).hide();$('#saveGroupBtn',context).click(function(){onButtonSaveClickHn(win,$grName.val());return false;});};},initGroupsButtons:function(){var pageObj=this,afterClosePopup=this.disableGroupButtons.bind(this,false),afterCreatePopupAdd=this.getPopupAfterCreateHn(this.addNewGroup.bind(this)),afterCreatePopupRename=this.getPopupAfterCreateHn(this.renameGroup.bind(this));$('#addGroupBtn').click(function(e){if(Runner.isDisabledButton(this)){return false;}
var params={header:pageObj.TEXT_AA_ADD_NEW_GROUP,width:340,height:200,afterClose:afterClosePopup,afterCreate:afterCreatePopupAdd,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>",footer:"<a id='saveGroupBtn' class='btn btn-primary' href='#'>Save</a>",};Runner.displayPopup(params);pageObj.disableGroupButtons(true);return false;});$('#delGroupBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.deletegroup();}
return false;});$('#renGroupBtn').click(function(e){var selectedIdVal=pageObj.currentGroup||pageObj.$groupControl.find("li.active").find("a").attr("value");if(Runner.isDisabledButton(this)||selectedIdVal<0){return false;}
var params={header:pageObj.TEXT_AA_RENAMEGROUP,width:340,height:200,afterClose:afterClosePopup,afterCreate:afterCreatePopupRename,html:"<div class='alert alert-danger'></div>"
+"<div><input class='groupname form-control' type='text' value='"
+pageObj.groups[selectedIdVal]+"'></div>",footer:"<a id='saveGroupBtn' class='btn btn-primary' href='#'>Save</a>",};Runner.displayPopup(params);pageObj.disableGroupButtons(true);return false;});},disableGroupButtons:function(isDisable){if(isDisable){Runner.addDisabledClass($('#addGroupBtn'));Runner.addDisabledClass($('#delGroupBtn'));Runner.addDisabledClass($('#renGroupBtn'));Runner.addDisabledClass($('#copyPermissions'));$("li").addClass("disabled");}else{Runner.delDisabledClass($('#addGroupBtn'));Runner.delDisabledClass($('#copyPermissions'));$("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=$("ul.nav-tabs").find("li.active").find("a").attr("value");if(id<0){return;}
if(!confirm(Runner.lang.constants.AA_DELETEGROUP+" "+this.groups[id]+'?')){return;}
Runner.runnerAJAX(Runner.getPageUrl('ug_group'),{id:id,a:'del'},function(respObj){var groupCount=0,newId;if(!respObj.success){$('.alert-danger').html('Error deleting record!');return false;}
delete pageObj.groups[id];if(!pageObj.modifiedRights.hasOwnProperty(id)){pageObj.modifiedRights=Runner.apply({},pageObj.modifiedRights);}
delete pageObj.modifiedRights[id];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();});},addNewGroup:function(name){var existGroupName=!!Object.keys(this.groups).filter(function(ind){return this.groups[ind]==name;},this).length;if(existGroupName){$('.alert-danger').html('Group with such name is already exist!');return false;}
var pageObj=this;Runner.runnerAJAX(Runner.getPageUrl('ug_group'),{name:name,a:'add'},function(respObj){if(!respObj.success){pageObj.displayMessage('Error adding group!',true);return false;}
var groupIdx=respObj.id;var $groupTab=$("<a value='"+groupIdx+"' href='#'></a>").text(name);pageObj.hideElement('message');pageObj.groups[groupIdx]=name;pageObj.$groupControl.append($("<li role='presentation'></li>").append($groupTab));$groupTab.click();});return true;},renameGroup:function(name){var groupIdx=this.currentGroup||this.$groupControl.find("li.active").find("a").attr("value");var existGroupName=!!Object.keys(this.groups).filter(function(ind){return this.groups[ind]==name&&groupIdx!=ind},this).length;if(existGroupName){$('.alert-danger').html('Group with such name is already exist!');return false;}
var pageObj=this;Runner.runnerAJAX(Runner.getPageUrl('ug_group'),{id:groupIdx,name:name,a:'rename'},function(respObj){if(!respObj.success){pageObj.displayMessage('Error renaming group!',true);return;}
pageObj.groups[groupIdx]=name;pageObj.$groupControl.find("a[value='"+groupIdx+"']").text(name);});return true;},initReset:function(){var pageObj=this;$('#resetBtn').click(function(){if(!Runner.isDisabledButton(this)){pageObj.modifiedRights={};pageObj.modifiedRestrictedPages={};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'));},getModifications:function(){var ret={},pageObj=this;Object.keys(this.modifiedRights).forEach(function(g){ret[g]={};});Object.keys(this.modifiedRestrictedPages).forEach(function(g){ret[g]={};});Object.keys(ret).forEach(function(g){var tableRights=pageObj.modifiedRights[g]||{},tablePages=pageObj.modifiedRestrictedPages[g]||{};Object.keys(tableRights).forEach(function(t){ret[g][t]={permissions:tableRights[t],pages:tablePages[t]||pageObj.getSavedRestrictedPages(t,g)};});Object.keys(tablePages).forEach(function(t){ret[g][t]=ret[g][t]||{permissions:pageObj.getTableSavedPermissions(t,g),pages:tablePages[t]};});});return ret;},initSave:function(){var pageObj=this;$('#saveBtn').click(function(e){if(Runner.isDisabledButton(this)){return false;}
pageObj.disableControls();pageObj.hideElement("message");$.ajax({type:"POST",data:{data:JSON.stringify(pageObj.getModifications()),a:'saveRights'},dataType:"json",error:function(jqXHR,textStatus,errorThrown){Runner.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;});});jQuery.each(pageObj.modifiedRestrictedPages,function(group,permissionsObj){jQuery.each(permissionsObj,function(table,perm){if(typeof pageObj.savedPageRestrictions[table]=='undefined'){pageObj.savedPageRestrictions[table]={};}
pageObj.savedPageRestrictions[table][group]=perm;});});pageObj.modifiedRights={};pageObj.modifiedRestrictedPages={};pageObj.groupListChange();pageObj.updateGroupsModifiedStates();pageObj.disabledMode=false;}});return false;});},makename:function(groupName){var n=1,tgroupName=groupName,found;while(1){found=!!Object.keys(this.groups).filter(function(groupId){return this.groups[groupId]==tgroupName;},this).length;if(!found){return tgroupName;}
tgroupName=groupName+n;n++;}},initShowHidePages:function(){var pageObj=this;$(".rightsTable").on("click.pages","[data-show-pages]",function(e){var $link=$(this);var shortTable=$link.data('table');$("tr[data-table="+shortTable+"]").attr('data-hidden',null);$("[data-table="+shortTable+"][data-hide-pages]").attr('data-hidden',null);$link.attr('data-hidden','');return false;});$(".rightsTable").on("click.pages","[data-hide-pages]",function(e){var $link=$(this);var shortTable=$link.data('table');$("tr[data-table="+shortTable+"]").attr('data-hidden','');$("[data-table="+shortTable+"][data-show-pages]").attr('data-hidden',null);$link.attr('data-hidden','');return false;});},initCheckboxes:function(){var pageObj=this;$(".rightsTable").on("click.checkboxes","td:has(.r-admin-checkbox:not(.columnheader):not(.rowheader):not([data-page]))",function(e){if(pageObj.disabledMode){return false;}
var $checkbox=$(this).find(".r-admin-checkbox"),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1",shortTable=pageObj.getTableNameFromBox($checkbox.attr("id")),table=pageObj.shortTables[shortTable],permission=$checkbox.data('permission'),modifiedMask;$checkbox.attr("data-checked",newchecked);modifiedMask=pageObj.updateModifiedState(pageObj.readTablePermissionsFromGrid(shortTable),shortTable);pageObj.updatePagePermissions(table,permission,newchecked=="1",true);pageObj.updatePagesInGrid(shortTable);pageObj.updateRowModifiedState(shortTable,modifiedMask);pageObj.updateRowHeaderState(table);pageObj.updateColHeaderStates();pageObj.updateGroupsModifiedStates();return false;});},initPageCheckboxes:function(){var pageObj=this;$(".rightsTable").on("click.checkboxes","td:has(.r-admin-checkbox:not(.columnheader):not(.rowheader)[data-page])",function(e){if(pageObj.disabledMode){return false;}
var $checkbox=$(this).find(".r-admin-checkbox"),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1",shortTable=$checkbox.data("table"),table=pageObj.shortTables[shortTable],page=$checkbox.data("page");pageObj.updateRestrictedPage(table,page,checked);var permission=pageObj.pages[table][page];if(pageObj.updateTablePermissions(shortTable,page,newchecked==="1")){pageObj.getBoxObj(permission,shortTable).attr("data-checked",newchecked);pageObj.updateRowModifiedState(shortTable,permission);pageObj.updateRowHeaderState(table);pageObj.updateColHeaderStates();}
pageObj.updatePagesInGrid(shortTable);$checkbox.attr("data-checked",newchecked);pageObj.updateGroupsModifiedStates()
return false;});},updateTablePermissions:function(shortTable,page,enable){var table=this.shortTables[shortTable];var permission=this.pages[table][page];var currentPermissions=this.getTableActivePermissions(table);var tablePages=this.pages[table];if(enable&&currentPermissions.indexOf(permission)===-1){this.updateModifiedState(currentPermissions+permission,shortTable);Object.keys(tablePages).forEach(function(p){if(p!=page&&tablePages[p]===permission){this.updateRestrictedPage(table,p,true);}},this);return true;}else if(!enable){var activePages=this.activeRestrictedPages(table);var enabledPage=!Object.keys(tablePages).filter(function(page){return tablePages[page]===permission&&activePages[page]===undefined;}).length;if(enabledPage){var idx=currentPermissions.indexOf(permission);this.updateModifiedState(currentPermissions.substring(0,idx)+currentPermissions.substring(idx+1),shortTable);return true;}}
return false;},updatePagePermissions:function(table,permission,enable,updateAllPages){var pageObj=this;var group=this.currentGroup;var groupObj=this.modifiedRestrictedPages[group];if(!groupObj){groupObj={};this.modifiedRestrictedPages[group]=groupObj;}
var pages=groupObj[table];if(!pages){pages=JSON.parse(JSON.stringify(this.savedPageRestrictions[table]?this.savedPageRestrictions[table][group]||{}:{}));groupObj[table]=pages;}
var pagePermTypes=this.pages[table];if(enable){if(updateAllPages){Object.keys(pages).forEach(function(p){if(pagePermTypes[p]===permission){delete pages[p];}});}else{var activePages=this.activeRestrictedPages(table);var tablePages=this.pages[table]
var enabledPage=!Object.keys(tablePages).filter(function(page){return tablePages[page]===permission&&activePages[page]===undefined;}).length;if(enabledPage){Object.keys(pages).forEach(function(p){if(pagePermTypes[p]===permission){delete pages[p];}});}}}
if(this.pageListsEqual(groupObj[table],this.getSavedRestrictedPages(table,group))){delete groupObj[table];}},updatePagesInGrid:function(shortTable){var group=this.currentGroup,pageObj=this,table=this.shortTables[shortTable],tableRights=this.getTableActivePermissions(table,group),tableSavedRights=this.getTableSavedPermissions(table,group),activePages=this.activeRestrictedPages(table),savedPages=this.getSavedRestrictedPages(table);Object.keys(pageObj.pages[table]||{}).forEach(function(page){var enabled=tableRights.indexOf(pageObj.pages[table][page])!==-1&&!activePages[page];var wasEnabled=tableSavedRights.indexOf(pageObj.pages[table][page])!==-1&&!savedPages[page];pageObj.getPageBoxObj(pageObj.pages[table][page],shortTable,page).add(pageObj.getWholePageBoxObj(shortTable,page)).attr("data-checked",enabled?"1":"0");$('#pagecell'+pageObj.pages[table][page]+shortTable+'_'+page).closest('tr').toggleClass('r-rights-modified',wasEnabled!=enabled);});},initColumnHeaders:function(){var pageObj=this;$(".rightsTable").on("click","td:has(.r-admin-checkbox.columnheader[data-perm])",function(e){if(pageObj.disabledMode){return;}
var $checkbox=$(this).find(".r-admin-checkbox.columnheader"),perm=$checkbox.data("perm"),checked=$checkbox.attr("data-checked")=="1",newchecked=checked?"0":"1";$(".rightsTable").find("[id^=box"+perm+"]:visible").each(function(){var shortTable=pageObj.getTableNameFromBox(this.id),table=pageObj.shortTables[shortTable];if(pageObj.pageMasks[table].indexOf(perm)==-1){return;}
$(this).attr("data-checked",newchecked);var modifiedMask=pageObj.updateModifiedState(pageObj.readTablePermissionsFromGrid(shortTable),shortTable);pageObj.updateRowModifiedState(shortTable,modifiedMask);pageObj.updateRowHeaderState(table);pageObj.updatePagePermissions(table,perm,newchecked=="1",false);pageObj.updatePagesInGrid(shortTable);});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();['A','E','S','P','I'].forEach(function(perm){pageObj.updatePagePermissions(table,perm,newchecked=="1",false);});pageObj.updatePagesInGrid(shortTable);return false;});},groupListChange:function(){var pageObj=this;this.currentGroup=this.$groupControl.find('li.active > a').attr('value');jQuery.each(this.tables,function(table){var tableRights=pageObj.getTableActivePermissions(table,pageObj.currentGroup),shortName=this[0];jQuery.each(pageObj.masks,function(right,permission){var checked=tableRights.indexOf(permission)>-1?"1":"0";pageObj.getBoxObj(permission,shortName).attr("data-checked",checked);});pageObj.updateRowModifiedState(shortName,pageObj.getTableModifiedMask(table));pageObj.updatePagesInGrid(shortName);});this.updateRowHeaderStates();this.showHideRows();},initGroupsList:function(){var pageObj=this;this.$groupControl.on('click','a[value]',function(){pageObj.$groupControl.children('.active').removeClass('active');$(this).parent().addClass('active');pageObj.groupListChange();pageObj.setButtonsActiveState();return false;});pageObj.groupListChange();pageObj.setButtonsActiveState();},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;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.toggleJQElement($("#row_"+shortTable),table.visible);table.showOnModifiedMode=table.visible;var $pagesRows=$('[data-table="'+shortTable+'"');pageObj.toggleJQElement($pagesRows,table.visible);});jQuery.each(pageObj.menuOrderedTables,function(idx){if(this.table){return;}
pageObj.toggleJQElement(pageObj.getGroupRow(idx),false);});}else if(!this.SEARCHLIST.length){indentTables=true;jQuery.each(pageObj.menuOrderedTables,function(idx){if(this["items"]){displayGroupControls=true;}
var display=pageObj.isItemInExpandedSet(this);pageObj.toggleJQElement(pageObj.getGroupRow(idx),display);if(pageObj.menuOrderedTables[idx].table){var $pagesRows=$('[data-table="'+pageObj.tables[pageObj.menuOrderedTables[idx].table][0]+'"');pageObj.toggleJQElement($pagesRows,display);}});}else{this.updateAllHasVisibleItemsFlags();indentTables=true;jQuery.each(pageObj.menuOrderedTables,function(idx){var display=this.hasVisibleItems||this.table&&pageObj.tables[this.table].visible;pageObj.toggleJQElement(pageObj.getGroupRow(idx),display);if(pageObj.menuOrderedTables[idx].table){var $pagesRows=$('[data-table="'+pageObj.tables[pageObj.menuOrderedTables[idx].table][0]+'"');pageObj.toggleJQElement($pagesRows,display);}});}
pageObj.updateColHeaderStates();$("#expandAll").toggle(displayGroupControls);$(".rightsTable").toggleClass("groupcontrols",displayGroupControls).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);},getPageBoxObj:function(perm,shortTable,page){return $("#pagebox"+perm+shortTable+'_'+page);},getWholePageBoxObj:function(shortTable,page){return $("#wholepagebox_"+shortTable+'_'+page);},updateRestrictedPage:function(table,page,restrict,_group){var group=_group||this.currentGroup;var groupObj=this.modifiedRestrictedPages[group];if(!groupObj){groupObj={};this.modifiedRestrictedPages[group]=groupObj;}
groupObj[table]=groupObj[table]||JSON.parse(JSON.stringify(this.getSavedRestrictedPages(table,group)));if(restrict){groupObj[table][page]=true;}else{delete groupObj[table][page];}
if(this.pageListsEqual(groupObj[table],this.getSavedRestrictedPages(table,group))){delete groupObj[table];}},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]:"")||"";},getSavedRestrictedPages:function(table,_group){var group=_group||this.currentGroup;return(this.savedPageRestrictions[table]?this.savedPageRestrictions[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);},activeRestrictedPages:function(table,_group){var group=_group||this.currentGroup,modTables=this.modifiedRestrictedPages[group],modifiedPages;modifiedPages=modTables?modTables[table]:undefined;if(modifiedPages){return modifiedPages;}
return this.getSavedRestrictedPages(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("r-rights-modified",modifiedMask.indexOf(identifier)>-1);tableModified=tableModified||modifiedMask.indexOf(identifier)>-1;});$tableCell.toggleClass("r-rights-modified",tableModified);},getTableNameFromBox:function(_boxId){var boxId=_boxId||"";return boxId.substring(4);},initModifiedFilter:function(){var pageObj=this,$control=$("#linkselectFilter");$control.on("click","a",function(e){pageObj.tablesFilterState=$(this).parent().data('value');pageObj.showHideRows();$control.find('.btn').text($(this).text());$control.find('.dropdown-toggle').click();return false;});},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;return Object.keys(this.modifiedRights[group]||{}).length
+Object.keys(this.modifiedRestrictedPages[group]||{}).length>0;},updateGroupsModifiedStates:function(){var isAnyModified=!!Object.keys(this.groups).filter(function(groupIdx){return this.areGroupPermissionsModified(groupIdx);},this).length;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("tbody").find("tr[id^='row_']:first"),idx=0,currentRowId,table,shortTName,$insertRow,rowid,$pageRows;while($row.length){if(idx>=this.alphaOrderedTables.length){break;}
if($row.is('[data-page]')){$row=$row.next();continue;}
table=this.alphaOrderedTables[idx];shortTName=this.tables[table][0];rowid="row_"+shortTName;currentRowId=$row.get(0).id;$insertRow=$("#"+rowid);if($insertRow.length&&currentRowId!=rowid){$pageRows=$(".rightsTable").find("tbody").find("tr[data-table='"+shortTName+"'][data-page]");$insertRow.add($pageRows).insertBefore($row);$row=$insertRow;}
++idx;$row=$row.next();}
this.showHideRows();},orderTablesAsMenu:function(){var $row=$(".rightsTable").find("tbody").find("tr:first"),idx=0,table,$insertRow,rowid,shortTName,$pageRows;while($row.length&&idx<this.menuOrderedTables.length){if(idx>=this.menuOrderedTables.length){break;}
if($row.is('[data-page]')){$row=$row.next();continue;}
table=this.menuOrderedTables[idx].table;if(table){shortTName=this.tables[table][0];rowid="row_"+this.tables[table][0];}else{rowid="grouprow_"+idx;}
if($row.get(0).id!=rowid){$insertRow=$("#"+rowid);$pageRows=$(".rightsTable").find("tbody").find("tr[data-table='"+shortTName+"'][data-page]");$insertRow.add($pageRows).insertBefore($row);$row=$insertRow;}
++idx;$row=$row.next();}
this.showHideRows();},initOrderControl:function(){var pageObj=this,$control=$("#linkselectOrder");$control.on("click","a",function(e){if($(this).parent().data("value")=='menu'){pageObj.orderTablesAsMenu();}else{pageObj.orderTablesAlphabetically();}
$control.find('.btn').text($(this).text());$control.find('.dropdown-toggle').click();return false;});},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);return false;});},getGroupRow:function(groupId){var table=this.menuOrderedTables[groupId].table;return table?$("#row_"+this.tables[table][0]):$("#grouprow_"+groupId);},expandGroup:function(groupId,toExpand){var $tr=this.getGroupRow(groupId),menuItem=this.menuOrderedTables[groupId];menuItem.collapsed=!toExpand;$tr.find("[data-group-expander]").toggleClass("glyphicon-triangle-right",!toExpand).toggleClass("glyphicon-triangle-bottom",toExpand);this.showHideRows();},initExpandCollapseControls:function(){var pageObj=this;$(".rightsTable").on("click","tr[data-groupid]:has([data-group-expander])",function(e){var groupId=$(this).data("groupid")||0;pageObj.expandGroup(groupId,pageObj.menuOrderedTables[groupId].collapsed);});},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,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=$("ul.nav-tabs").find("li.active").find("a").attr("value");$.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();$("ul.nav-tabs").find("li.active").find("a").click();return false;});};$('#copyPermissions').on('click',function(e){if(!Runner.isDisabledButton(this)){Runner.pages.PageManager.createBSWin(args,false,afterCreateDialog);}
return false;});},toggleJQElement:function($elem,show){if(!show){$elem.hide();}else{$elem.css('display','');}},pageListsEqual:function(pages1,pages2){var kPages1=Object.keys(pages1);var kPages2=Object.keys(pages2);if(kPages2.length!==kPages1.length){return false;}
return kPages1.filter(function(p){return!pages2[p];}).length===0;},getLogoutUrl:function(){return Runner.getPageUrl(this.pageType)+"?a=logout";},});Runner.pages.MembersPageAD=Runner.extend(Runner.pages.ListPageCommon,{pageType:Runner.pages.constants.PAGE_ADMIN_ADMEMBERS,rows:null,constructor:function(cfg){Runner.pages.MembersPageAD.superclass.constructor.call(this,cfg);this.baseParams.id=this.pageId;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(){this.initGridElem();Runner.pages.ListPageCommon.superclass.init.call(this);this.initButtons();this.initRows();},initButtons:function(){var pageObj=this,$addSelBtn=$('#addSelBtn');$addSelBtn.off('click').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.addSelectedToGroup();}
return false;});Runner.addDisabledClass($addSelBtn);},initRows:function(){this.rows.forEach(function(row){this.initAddGrLink(row);this.initCheckBoxGr(row);},this);},initAddGrLink:function(row){var pageObj=this;row.addGrLink=$('#iAddLink'+row.id).on("click",function(e){pageObj.addToGroup(row);return false;});},initCheckBoxGr:function(row){var pageObj=this;row.checkBoxGr=$('#check'+this.id+'_'+row.id).on("click",function(e){var checked=$(this).attr("data-checked")||"0";var newcheked=checked==="0"?"1":"0";$(this).attr("data-checked",newcheked);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);}
$('.r-admin-checkbox[id^=chooseAll_'+pageObj.id+']').attr('data-checked',selBoxesArr.length===$('.r-admin-checkbox[id^=check'+pageObj.id+'_]').length?"1":"0");});},getSelections:function(){var selBoxesArr=[];$('.r-admin-checkbox[id^=check][name^=selection][data-checked="1"]').each(function(){selBoxesArr.push($(this));});return selBoxesArr;},initHeaderCheckBox:function(){var pageObj=this;$('#chooseAll_'+this.id).off("click").on("click",function(e){var checked=$(this).attr("data-checked")||"0";var newchecked=checked==="0"?1:0;$('.r-admin-checkbox[id^=check'+pageObj.id+'_]').attr('data-checked',newchecked);$('.r-admin-checkbox[id^=chooseAll_'+pageObj.id+']').attr('data-checked',newchecked);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);}});},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);this.searchController.on('afterSearch',function(respObj,srchController,srchForm){Runner.stopLoading();this.pageReloadHn(respObj);this.searchController.toggleShowAll(this.searchController.usedSrch)},this);this.searchController.srchForm.on('submitFailed',function(){Runner.stopLoading();},this);},initInline:Runner.emptyFn,pageReloadHn:function(respObj){Runner.stopLoading();var $content=this.winObject.getContentNode(),$header=this.winObject.header(),$footer=this.winObject.footer(),$body=this.winObject.body();if(!respObj.success){$body.html("REQUEST FAILED");return;}
Runner.setIdCounter(respObj.idStartFrom);$body.height($body.height());$body.html(respObj['html']);$footer.html(respObj['footerCont']);$body.height($content.innerHeight()-$header.outerHeight()-$footer.outerHeight()-$body.outerHeight()+$body.height());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);this.initSearch();this.initPagination();},addSelectedToGroup:function(){this.getSelections().forEach(function($box){var row=this.getRowById(parseInt($box.attr("value"),10));this.addToGroup(row);},this);this.destructor();},getRowById:function(rowId){for(var i=0;i<this.rows.length;i++){if(this.rows[i].id===rowId){return this.rows[i];}}
return false;},addToGroup:function(row){if(!row||row.keys.name==''){return;}
var groupName=row.keys.name,pageObj=this;for(var groupId in this.parObj.groups){if(this.parObj.groups[groupId]==groupName){this.displayMessage('Group with such name is allready exist!');return;}}
Runner.runnerAJAX(this.requestUrl,{name:groupName,a:'addgr'},function(ret){if(!ret.success){pageObj.displayMessage('Error adding group!',true,true);return;}
pageObj.hideElement('message');pageObj.parObj.addGroupToTable(groupName,ret.id);$('.r-admin-checkbox[id^=check][name^=selection][value='+row.id+']').hide();row.addGrLink.hide();});}});Runner.pages.RightsPageAD=Runner.extend(Runner.pages.RightsPage,{initGroupsButtons:function(){var pageObj=this;$('#addGroupBtn').click(function(e){if(Runner.isDisabledButton(this)){return false;}
var pageParams={tName:"admin_admembers",pageType:Runner.pages.constants.PAGE_ADMIN_ADMEMBERS,pageMode:Runner.pages.constants.MEMBERS_PAGE,parObj:pageObj,modal:true,baseParams:{table:"admin_admembers"},requestUrl:Runner.getPageUrl("admin_admembers",Runner.pages.constants.PAGE_LIST)};Runner.pages.PageManager.openPage(pageParams);pageObj.disableGroupButtons(true);return false;});$('#delGroupBtn').click(function(e){if(!Runner.isDisabledButton(this)){pageObj.deletegroup();}
return false;});},addGroupToTable:function(groupName,id){this.groups[id]=groupName;$("li.active",'[data-groups]').removeClass();$('<li class="active" role="presentation"><a href="#" value="'+id+'">'+groupName+'</a></li>').insertAfter($('.nav-tabs[data-groups]').find('li:last'));$("li.active",'[data-groups]').find('a').click();$('.group').attr('size',Object.keys(this.groups).length).trigger('change');$('.groupname').val('');},});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,page:pageObj.pageName}});pageObj.form.submit();pageObj.form.destructor();pageObj.form=null;localStorage.setItem("export_"+pageObj.tName,JSON.stringify(settings));pageObj.close();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;});},bricksToBlocks:{import_preview:"importPreview",import_rawtext_control:"copyAndPasteText",importfields:"importFields",importheader_text:"importheaderText",import_process:"importProgress",import_results:"reportText"},toggleBlock:function(name,toggler){if(this.layoutVersion===4){$("#"+this.bricksToBlocks[name]+this.id).toggle(toggler);}else{this.toggleElement(name,toggler);}},showBlock:function(name){this.toggleBlock(name,true);},hideBlock:function(name){this.toggleBlock(name,false);},backToDataChoosing:function(){if(this.importPageMode===this.modeConstants.DATA_CHOOSING&&!this.fileImport){this.switchToFileChoosing();}else if(this.importPageMode===this.modeConstants.PREVIEW){this.hideBlock("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.showBlock("importheader_text");this.showBlock("importfields");this.hideBlock("import_rawtext_control");this.toggleDropZone(false);this.$continueTextImport.hide();this.$backButton.hide();},switchToTextInput:function(){this.fileImport=false;this.hideBlock("importheader_text");this.hideBlock("importfields");this.showBlock("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.toggleBlock("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();Runner.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();Runner.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.showBlock("import_preview");this.hideBlock("import_rawtext_control");this.hideBlock("importheader_text");this.hideBlock("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.showBlock("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.showBlock("import_results");pageObj.hideBlock("import_preview");pageObj.hideBlock("import_process");pageObj.initalizeReportResultButtons(respObj.unprocessedRecordsNumber>0);},function(rawText){pageObj.backToImportPreview();Runner.displayGenericAjaxError(rawText);});},backToImportPreview:function(){if(this.importPageMode!==this.modeConstants.PREVIEW){return;}
this.hideBlock("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){Runner.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){Runner.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;});if(Runner.isPD()){this.findItemType("register_reset").bind("click",function(e){pageObj.resetControls();});}},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;}
if(Runner.isPD()){$confirmItem=$("[data-itemtype$=confirm_password][data-pageid="+this.id+"]");if(!$confirmItem.length)
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],pdConfirmCheck=true;if(Runner.isPD()){$confirmItem=$("[data-itemtype$=confirm_password][data-pageid="+this.id+"]");pdConfirmCheck=$confirmItem.length;}
if(confirmCtrl&&pdConfirmCheck&&passCtrl&&passCtrl.getValue()!==confirmCtrl.getValue()){confirmCtrl.markInvalidWidthCusttomMessages("notMatchPasswords",[Runner.lang.constants.PASSWORDS_DONT_MATCH]);Runner.delDisabledClass(this.saveButton);return false;}
return this.fireEvent("beforeSave",formObj,formObj.fieldControls,this);},scope:this},successSubmit:{fn:function(respObj,basicForm,fieldControls){var $procToLogin,$header;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;})
if(Runner.isPD()){$header=$(".modal-header",this.bsWin);$header.children("*:not(.close)").remove();$header.prepend(respObj.headerCont);this.toggleItemType("register_reset",false);}
$procToLogin=$("a[id=ProceedToLogin]").hide();if($procToLogin.length){this.saveButton.hide();}else{Runner.delDisabledClass(this.saveButton);}
if(respObj.additionalJS){$.each(respObj.additionalJS,function(jsFile,jsFileReq){Runner.util.ScriptLoader.addJS([jsFile],jsFileReq);});Runner.util.ScriptLoader.onFilesLoaded(function(){pageObj.pageData.buttons=respObj.pagesData[pageObj.id]["buttons"];pageObj.initCustomButtons();},pageObj);Runner.util.ScriptLoader.load();}}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},});},resetControls:function(){var cntrls=Runner.controls.ControlStorage.byId(this.id),updContext,i;if(!cntrls||!cntrls.length){return;}
updContext={resetHappend:true,values:{}};for(i=0;i<cntrls.length;i++){if(cntrls[i].editFormat!="Readonly"){updContext.values[cntrls[i].fieldName]=cntrls[i].defaultValue;}}
for(i=0;i<cntrls.length;i++){if(cntrls[i].editFormat!="Readonly"){cntrls[i].reset(updContext);}}}});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:"",pageObj:null,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,delegatedSubmit:null,delegatedExtraSuggestParams:null,constructor:function(cfg){this.fNamesArr=[];this.ctrlsShowMap={};this.baseParams={};this.searchFields={};this.optCombosArr=[];this.requiredSearchFields=[];Runner.apply(this,cfg);this.pageObj=Runner.pages.PageManager.getAt(this.tName,this.id);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 controller=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(controller.submitTimeout){clearTimeout(controller.submitTimeout);}
controller.submitTimeout=setTimeout(function(){controller.searchSuggestForCtrl(ctrl);},700);});ctrl.on('keydown',function(e){controller.listenEvent(e,this.valueElem.get(0));});},listenEvent:function(oEvent,oElement){switch((window.event||oEvent).keyCode){case 38:this.useSuggest&&Runner.suggests.moveUp(oElement);break;case 40:this.useSuggest&&Runner.suggests.moveDown(oElement);break;case 9:this.useSuggest&&Runner.suggests.DestroySuggestDiv();break;case 13:this.useSuggest&&Runner.suggests.DestroySuggestDiv();if(!Runner.isDisabledButton(this.searchButton)){this.delegatedSubmit?this.delegatedSubmit():this.submitSearch();}
break;}},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','');}
if(!this.pageObj.isDefaultPage){this.srchForm.addToForm('page',this.pageObj.pageName);this.srchForm.addToSearchForm('page',this.pageObj.pageName);}
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();if(!Object.keys(this.srchForm.searchForm).length){return;}
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(page){this.srchForm.clearForm();this.srchForm.searchSubmit=false;this.srchForm.addToForm('a','return');if(page){this.srchForm.addToForm('page',page);}
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;},searchSuggestForSimple:function($searchBox){var fieldName=$("#simpleSrchFieldsCombo1").val()||'',startWith=$("#simpleSrchTypeCombo1").val()=="Starts with",setValueFn=function(value){$searchBox.val(value);};this.searchSuggest($searchBox,fieldName,$searchBox.val(),startWith,setValueFn);},searchSuggestForCtrl:function(ctrl){var srchTypeComboId=this.getComboId(ctrl.fieldName,this.id),startWith=$('#'+srchTypeComboId).val()=='Starts with',setValueFn=function(value){ctrl.setValue(value,true);};this.searchSuggest(ctrl.getDispElem(),ctrl.fieldName,ctrl.getValue(),startWith,setValueFn);},getSuggestUrl:function(){return Runner.getPageUrl('searchsuggest','','table='+this.shortTName);},searchSuggest:function($el,fName,currValue,startWith,setValueFn){Runner.suggests.searchSuggest($el);var reqParams={searchFor:currValue,searchField:fName||'',rndVal:new Date().getTime(),start:startWith?1:0,pageType:this.pageType,page:this.pageObj.pageName};if(typeof this.delegatedExtraSuggestParams==='function'){reqParams=Runner.apply(reqParams,this.delegatedExtraSuggestParams());}
Runner.runnerAJAX(this.getSuggestUrl(),reqParams,function(respObj){Runner.suggests.onSearchSuggestResponse(respObj,setValueFn);});},hideSearchFieldsSuggests:function(){for(var fName in this.searchFields){var searchFields=this.searchFields[fName];for(var i=0;i<searchFields.length;i++){var ctrl=searchFields[i].getControl();if(ctrl instanceof Runner.controls.EditBoxLookup){ctrl.destroySuggest();}}}}});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),checkData={value:$box.val(),};if(ctrl.dependent){var parentFiltersValueData=$box.data('parentFiltersValues'),parentValues=[];ctrl.parentFilterNames.forEach(function(pfName){parentValues.push(parentFiltersValueData[pfName].toString().replace('|','\\|'));});checkData.parentValues=parentValues.join('|');}
arr.push(checkData);});}
return arr;},getFilterValue:function(encoded){var arr=this.getValue(),result='';for(i=0;i<arr.length;i++){var value=arr[i].value,parentValues=arr[i].parentValues,prepFName;if(value===''){continue;}
value=this.getPreparedValue(value,encoded);prepFName=this.searchController.searchEscape(this.fieldName);prepFName=encoded?encodeURIComponent(prepFName):prepFName;result+='('+prepFName+this.separator+value
+(parentValues?'~~'+parentValues:'')+')';}
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,2);}
if(maxKnob){maxKnob=this.parseDateTime(maxKnob,2);}
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,2);this.minDateInMs=this.minDate.getTime();this.maxDate=this.parseDateTime(this.maxValue,2);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,2);this.realMinDate=this.parseDateTime(this.realMinValue,2);}
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,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.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.hideElement("search_buttons");this.pageObj.hideElement("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(){if(this.pageObj.leftBarCollapsed()&&this.pageObj.leftBarItems&&this.pageObj.leftBarItems.indexOf('search_panel')!=-1){this.pageObj.toggleLeftBar(true);}
this.pageObj.showElement('searchpanel');if(Runner.isPD()){this.pageObj.toggleItemType('hide_search_panel',true);this.pageObj.toggleItemType('show_search_panel',false);}
this.srchOptShowStatus=true;this.changePanelExpanderState();},hideSearchOptions:function(){this.pageObj.hideElement('searchpanel');if(Runner.isPD()){this.pageObj.toggleItemType('hide_search_panel',false);this.pageObj.toggleItemType('show_search_panel',true);}
$('.rnr-datepicker').hide();this.srchOptShowStatus=false;this.changePanelExpanderState();},changePanelExpanderState:function(){if(Runner.isPD()){return;}
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);}});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 controller=this;this.smplSrchBox.on('keydown',function(e){controller.listenEvent(e,this);});if(this.useSuggest){if(!$('#search_suggest').length){$('<div id="search_suggest"></div>').addClass("search_suggest").appendTo('body');}
this.smplSrchBox.on('keyup',function(e){if(Runner.isMobile||!Runner.isAcceptableKeyCode(e)){return;}
if(controller.submitTimeout){clearTimeout(controller.submitTimeout);}
controller.submitTimeout=setTimeout(function(){controller.searchSuggestForSimple(controller.smplSrchBox);},500);})}},getSuggestUrl:function(){if(this.pageType===Runner.pages.constants.PAGE_DASHBOARD){return Runner.getPageUrl('searchsuggest','','table='+Runner.pages.PageSettings.getShortTName(this.tName));}
return Runner.getPageUrl('searchsuggest','','table='+this.shortTName);},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).add("#hideOptPanel"+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){Runner.suggests.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.hideElement("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.pageObj=searchController.pageObj;}
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();logger.searchControllerConnector.pageObj.toggleItemType("saved_searches",true);Runner.pages.PageManager.getById(logger.id).hideExcessSeparators();});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=$("#savedSearchedList"+this.id);for(searchName in this.savedSearches){if(this.savedSearches.hasOwnProperty(searchName)){this.addSearchToSavedSearchesList(searchName);}}
this.savedSearchesList.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;});},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).attr('title',Runner.lang.constants.TEXT_DELETE_SEARCH_CAPTION);$('<a href="#"></a>').on("touchend",function(){$(this).trigger("click")}).addClass(this.savedSeachLinkClass).html(searchName).appendTo(item);},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();logger.searchControllerConnector.pageObj.toggleItemType("saved_searches",false);}
$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();logger.searchControllerConnector.pageObj.toggleItemType("saved_searches",false);}
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()&&invalidControls[0].pageObj.pageType==Runner.pages.constants.PAGE_LIST){$.each(invalidControls,function(i,ctrl){var hiddenColumnName=ctrl.spanContElem.closest('[data-field]').data('field');if(hiddenColumnName){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.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=$("[id=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.parPageObj.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);}}},setPDChildRecNum:function(row,detNum){var $detNumberSpan=$("#cntDet_"+this.shortTName+"_"+row.id),numberOfDetails=parseInt(detNum,10),countText="";if($detNumberSpan.length){if(numberOfDetails>0){$detNumberSpan.show();}
if(!this.hideChild||numberOfDetails>0){$detNumberSpan.parent().show();}
if($detNumberSpan.closest(".details-badge").length){$detNumberSpan.html(numberOfDetails).parent().toggleClass("hidden-badge",this.hideChild&&!numberOfDetails);}else{$detNumberSpan.html("("+numberOfDetails+")");}
return;}
row.row.find('#details_'+row.id+'_'+this.shortTName).toggle(!this.hideChild||numberOfDetails>0);},setChildRecNum:function(row,detNum){if(Runner.isPD()){this.setPDChildRecNum(row,detNum);return;}
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};},getUrl:function(page){return Runner.getPageUrl(this.shortTName,page===Runner.pages.constants.PAGE_LIST?'detailspreview':page);},initLink:function(row,setHref){var href,mKeys,key,linkQr="#"+this.shortTName+"_preview"+row.id;if(Runner.isPD()){linkQr="[id=details_"+row.id+"_"+this.shortTName+"]";}
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(){var params;pageObj.prevLink=link;pageObj.masterDetails.flag=url;pageObj.masterDetails.show=true;pageObj.masterDetails.counter++;if(Runner.isPD()){params=Runner.apply({counter:pageObj.masterDetails.counter,mastertable:mastertable,mode:'listdetailspopup',page:pageObj.previewPageId,id:Runner.genId()},masterKeys);}else{params={counter:pageObj.masterDetails.counter,mastertable:mastertable,masterKeys:JSON.stringify(masterKeys),mode:'listdetailspopup'};}
Runner.runnerAJAX(url,params,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-base.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,masterPageObj:this.masterPageObj,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'<span id="bsproceed_'+this.shortTName+row.id+'" >'
+this.tabSettings.tabLabel
+'</span>';}
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>';},initLink:function(row,setHref){var dpObj=this,href,mKeys,key,$allDetailsLink=$("[id=details_"+row.id+"]"),$singleDetailsLink=$("[id=details_"+row.id+"_"+this.shortTName+"]"),$oldStyleDetailsLink=$("#"+this.shortTName+"_preview"+row.id),$links=$($allDetailsLink).add($singleDetailsLink).add($oldStyleDetailsLink);if(!Runner.isPD()){if(this.linksType==Runner.pages.constants.DL_SINGLE&&!$links.hasClass(this.classBasePrefix+"hiddenelem")){$allDetailsLink.show();}}
$links.each(function(){var $link=$(this);if($link.data("initialized")){return;}
$link.on("click",function(e){return dpObj.linkClickHandler(row,e);}).data("initialized",true);});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);$links.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.hideElement("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]);}
var idLink=Runner.isPD()?"details_"+row.id+"_"+this.shortTName:this.shortTName+"_preview"+row.id;$("#"+idLink).attr("href",Runner.pages.getUrl(this.tName,this.pageType,mKeys,"masterkey")+"&mastertable="+encodeURIComponent(this.masterTName));}});Runner.namespace('Runner.util.details');Runner.util.details.PDPopupDetails=Runner.extend(Runner.util.details.DPPopUp,{constructor:function(cfg){Runner.util.details.PDPopupDetails.superclass.constructor.call(this,cfg);},getUrl:function(page){return Runner.getPageUrl(this.shortTName,page);}});Runner.util.details.NewListPreview=Runner.extend(Runner.util.details.ListTabbedPreview,{previewItemId:'',previewContainers:null,previewPageId:'',constructor:function(cfg){Runner.util.details.NewListPreview.superclass.constructor.call(this,cfg);this.previewContainers={};},openDetailsTabs:function(row,$link){var tabTNames=[],tName,i;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){return;}
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");}
row.isShown=true;for(i=0;i<tabTNames.length;i++){tName=tabTNames[i];var dpObj=this.parPageObj.dpObjs[tName];dpObj.prepareTabControl(row,tName===this.tName);}
this.parPageObj.hideElement("message");},prepareTabControl:function(row,setActive){this.createPreviewRow(row);var $tabControl=Runner.pages.PageManager.createTabsControl(this.previewContainers[row.id],"details_"+this.previewItemId+row.id);var tabElementId="tab"+this.tabControlName(row)+"_"+this.tabSettings.tabId;var href=this.proceedLink&&this.parPageObj.isBootstrap()?this.getTabTableLink(row):"";Runner.pages.PageManager.addTabToTabsControl($tabControl,"",tabElementId,this.getTabLabel(row),setActive,this.tabSettings.tabIndex,false,href);$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.getDetails(row);},getParams:function(row){return Runner.apply({id:Runner.genId(),page:this.previewPageId||'',mode:Runner.pages.constants.MODE_LIST_DETAILS,rndVal:Math.random(),mastertable:this.masterTName,masterid:this.id,masterpagetype:this.masterPageType,masterpage:this.parPageObj.pageName,masterPageObj:this.masterPageObj,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;if(!row.isShown||!this.previewContainers[row.id]){return;}
$tabsControl=Runner.pages.PageManager.getTabControl(this.previewContainers[row.id],"details_"+this.previewItemId+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,"tab"+this.tabControlName(row)+"_"+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(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.makeTmpAboveGrid(row.detPage[this.tName]);},this);Runner.util.ScriptLoader.load();}else{row.detPage[this.tName]=Runner.pages.PageManager.initPage(cfg);this.makeTmpAboveGrid(row.detPage[this.tName]);}},makeTmpAboveGrid:function(detPage){var $aboveGridForm=detPage.layoutHelper.getFormElement("above-grid"),$previewItem=$('[data-details-'+this.shortTName+'][data-record-id="'+detPage.rowId+'"]'),$newForm,$newCol,$newRow,$items;$newCol=$("<div/>").addClass("r-align-left col-md-12").attr("data-cellid",'tmp-above-grid_c1').attr("data-pageid",$aboveGridForm.attr("data-pageid"));$("[data-cellid]:first-child > [data-itemid]",$aboveGridForm).appendTo($newCol);$items=$("[data-details-inside][data-short-table="+this.shortTName+"]",$previewItem).children();$items.appendTo($newCol);$items.attr("from-data-details-inside",'');$newRow=$("<div/>").addClass("row").append($newCol);$newForm=$("<div/>").addClass("r-form").attr("data-location","tmp-above-grid").attr("data-pageid",$aboveGridForm.attr("data-pageid")).append($newRow);$newForm.insertAfter($aboveGridForm);$("[data-itemid]",$newForm).after(" ");$aboveGridForm.remove();},revertTmpAboveGrid:function(detPage){var $previewItem=$('[data-details-'+detPage.shortTName+'][data-record-id="'+detPage.rowId+'"]'),$dataDetailsInside=$("[data-details-inside][data-short-table="+detPage.shortTName+"]",$previewItem);detPage.layoutHelper.getFormElement("tmp-above-grid").find("[from-data-details-inside]").appendTo($dataDetailsInside);},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);},createPreviewRow:function(row){var $previewItem=$('[data-details-'+this.shortTName+'][data-record-id="'+row.id+'"]');this.previewContainers[row.id]=$previewItem.children('[data-details-preview]');this.previewItemId=this.previewItemId||$previewItem.attr('data-itemid');this.parPageObj.toggleItem(this.previewItemId,true,row.id);},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);this.revertTmpAboveGrid(row.detPage[tName]);}
this.previewContainers[row.id].empty();delete this.previewContainers[row.id];row.row.removeClass("bs-details-opened");this.parPageObj.toggleItem(this.previewItemId,false,row.id);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){this.previewContainers[row.id].empty();},destructor:function(){for(var i=0;i<this.rows.length;i++){this.closeDetails(this.rows[i]);}},tabControlName:function(row){return"details_"+this.previewItemId+row.id;},getNewDetailPageConfig:function(respObj,row,newId){var cfg=Runner.util.details.NewListPreview.superclass.getNewDetailPageConfig.call(this,respObj,row,newId);cfg.masterPageObj=this.masterPageObj;cfg.tabSettings.tabControlName=this.tabControlName(row);cfg.tabControl=Runner.pages.PageManager.getTabControl(this.previewContainers[row.id],"details_"
+this.previewItemId+row.id);cfg.openContainer=this.previewContainers[row.id];return cfg;},initLink:function(row,setHref){var dpObj=this,href,mKeys,key,$allDetailsLink=$("[id=details_"+row.id+"]"),$singleDetailsLink=$("[id=details_"+row.id+"_"+this.shortTName+"]"),$links=$singleDetailsLink;if(this.tabSettings.tabIndex===0){$links=$links.add($allDetailsLink);}
$links.each(function(){var $link=$(this);if($link.data("initialized")){return;}
$link.on("click",function(e){return dpObj.linkClickHandler(row,e);}).data("initialized",true);});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);$links.attr('href',href);}},linkClickHandler:function(row,e){var switchCondition=false,closeCondition=row.isShown,$link=$(e.target),corTabIdx;var $clickedItemElem=$(e.target).closest('[data-itemid]');if(row.isShown&&$clickedItemElem.attr('data-itemtype')=='grid_details_link'){switchCondition=$(".active > a[data-target=#tabdetails_"+this.previewItemId+row.id+"_"+this.shortTName+"]").length===0;}
if(switchCondition){$("a[data-target=#tabdetails_"+this.previewItemId+row.id+"_"+this.shortTName+"]").eq(0).click();return false;}
if(closeCondition){this.closeDetails(row,$link);return false;}
this.openDetailsTabs(row,$link);return false;},});Runner.ItemDisplayCondition={Always:0,MobileOpened:1,MobileAlways:2,DesktopMobileOpened:3,DesktopMobileAlways:4,Desktop:5,}
Runner.PDLayout=function(page,layoutHelper){this.page=page;this.formMap=layoutHelper.formMap;this.itemsByType=layoutHelper.itemsByType;this.gridCellMap=layoutHelper.gridCellMap;this.itemVisiblity=layoutHelper.itemVisiblity||{};this.fieldItems=layoutHelper.fieldItems;}
Runner.PDLayout.prototype={itemQuery:function(id,recordId){if(recordId===undefined){return'[data-itemid='+id+'][data-pageid='+this.page.id+']';}
return'[data-itemid='+id+'][data-pageid='+this.page.id+'][data-record-id='+recordId+']';},findForm:function(location){return this.getFormElement(location);},getFormElement:function(formLocation){return $('#form_'+formLocation+'_'+this.page.id);},findItem:function(id,recordId){return $(this.itemQuery(id,recordId));},findItemType:function(type,recordId){var self=this;return(this.itemsByType[type]||[]).reduce(function(obj,itemId){return obj.add(self.itemQuery(itemId,recordId));},$());},hasVisibleItem:function(id,recordId,$formElement){return $(this.itemQuery(id,recordId)+':not([data-hidden]):not([data-media-hidden]):first',$formElement).length!=0;},findCell:function(formLocation,cellId,recordId){var searchString='[data-cellid='+formLocation+'_'+cellId+'][data-pageid='+this.page.id+']';if(recordId!==undefined){searchString+='[data-record-id='+recordId+']';}
return $(searchString);},findCellRow:function(formLocation,rowIdx,recordId){return this.findCell(formLocation,rowIdx,recordId).parent();},toggleItem:function(itemId,show,recordId){this.toggleItems([{itemId:itemId,show:show,recordId:recordId,}]);},elementVisible:function($elem){return($elem.attr('data-hidden')===undefined&&$elem.attr('data-media-hidden')===undefined);},getVisibleItems:function(itemList){var pd=this;return itemList.filter(function(id){return pd.elementVisible(pd.findItem(id));});},toggleItems:function(items,mediaToggle){var attribute=mediaToggle?'data-media-hidden':'data-hidden';var _this=this;var modifiedItems=[];items.forEach(function(item){var $itemElem=_this.findItem(item.itemId,item.recordId);if($itemElem.length==1&&$itemElem.parent().is('[data-itemid="'+item.itemId+'"]')){$itemElem=$itemElem.add($itemElem.parent());}
var wasVisible=_this.elementVisible($itemElem);if($itemElem.length==1&&item.show===($itemElem.attr(attribute)===undefined)){return;}
$itemElem.attr(attribute,(!item.show)||null);var nowVisible=_this.elementVisible($itemElem);if(wasVisible!==nowVisible){modifiedItems.push(item);}});var processedRowsCols={};var formsToShow={};var formsToHide={};modifiedItems.filter(function(item){return item.show;}).forEach(function(item){var formLocation=_this.formMap.itemForms[item.itemId];formsToShow[formLocation]=true;_this.updateFormCells(formLocation,item.itemId,item.recordId,item.show,processedRowsCols);});modifiedItems.filter(function(item){return!item.show;}).forEach(function(item){var formLocation=_this.formMap.itemForms[item.itemId];formsToHide[formLocation]=true;_this.updateFormCells(formLocation,item.itemId,item.recordId,item.show,processedRowsCols);});Object.keys(formsToShow).forEach(function(location){_this.updateFormVisiblity(location,true);});Object.keys(formsToHide).forEach(function(location){if(!formsToShow[location]){_this.updateFormVisiblity(location,false);}});},updateFormCells:function(formLocation,itemId,recordId,show,processedRowsCols){var self=this;if(this.gridCellMap===undefined||!this.gridCellMap[formLocation]){return;}
var itemLoc=this.formMap.itemLocations[itemId];if(itemLoc===undefined||itemLoc.location!==formLocation){return;}
var map=this.gridCellMap[formLocation];var cell=map.cells[itemLoc.cellId];cell=this.skipAndUpdatePrecessedRowsCols(processedRowsCols,formLocation,cell,recordId,show);if(!cell.rows.length&&(show&&!cell.cols.length||!show&&!cell.visibleCols.length)){return;}
if(show){this.showRowOnly(formLocation,itemLoc.cellId,recordId);if(!this.cellColVisible(formLocation,itemLoc.cellId)){this.toggleCol(formLocation,cell.cols[0],true);}
if(!this.cellVisible(formLocation,itemLoc.cellId,recordId)){this.toggleRow(formLocation,cell.rows[0],recordId,true);}}else{cell.rows.forEach(function(rowIdx){if(self.canHideRow(formLocation,rowIdx,recordId)){self.toggleRow(formLocation,rowIdx,recordId,false);}});cell.visibleCols.forEach(function(colIdx){if(self.canHideCol(formLocation,colIdx)){self.toggleCol(formLocation,colIdx,false);}});}},skipAndUpdatePrecessedRowsCols:function(processedRowsCols,formLocation,mapCell,recordId,show){var _this=this;var formRowsCols=processedRowsCols[formLocation];if(!formRowsCols){formRowsCols={rows:{},cols:{}};processedRowsCols[formLocation]=formRowsCols;}
var ret={rows:[],cols:[],visibleCols:[]};mapCell.rows.forEach(function(row,idx){if(show&&idx>0){return;}
var rowKey=row+'_'+recordId;if(formRowsCols.rows[rowKey]){return;}
ret.rows.push(row);formRowsCols.rows[rowKey]=true;});srcCols=show?mapCell.cols:mapCell.visibleCols;dstCols=show?ret.cols:ret.visibleCols;srcCols.forEach(function(col,idx){if(show&&idx>0){return;}
if(formRowsCols.cols[col]){return;}
dstCols.push(col);formRowsCols.cols[col]=true;});return ret;},updateFormVisiblity:function(formLocation,show){var $formElement=this.getFormElement(formLocation);if($formElement.siblings('[data-location]').length==0){$formElement=$formElement.add($formElement.parent());}
var formHidden=$formElement.is('[data-hidden]');if(formHidden==!show){return;}
if(show){$formElement.attr('data-hidden',null);return;}
for(var i in this.formMap.formItems[formLocation]){if(this.hasVisibleItem(this.formMap.formItems[formLocation][i],undefined,$formElement)){return;}}
$formElement.attr('data-hidden','');},toggleForm:function(formLocation,show){var $formElement=this.getFormElement(formLocation);if($formElement.parent().is('[data-formblock]')){$formElement=$formElement.parent();}
$formElement.attr('data-hidden',show?null:'');},toggleItemType:function(itemType,show,recordId){var itemIds=this.itemsByType[itemType]||[],self=this;this.toggleItems(itemIds.map(function(itemId){return{itemId:itemId,show:show,recordId:recordId};}));},hasItemType:function(itemType){var itemIds=this.itemsByType[itemType]||[];return itemIds.length>0;},cellColVisible:function(formLocation,cellId){var map=this.gridCellMap[formLocation];var cellCols=map.cells[cellId].cols;return Object.keys(map.cells).filter(function(cell){return map.cells[cell].visibleCols.filter(function(colIdx){return cellCols.indexOf(colIdx)!==-1;}).length!==0;}).length!==0;},toggleCol:function(formLocation,colIdx,show){var self=this;var map=this.gridCellMap[formLocation];var colCells=Object.keys(map.cells).filter(function(cellId){return map.cells[cellId].cols.indexOf(colIdx)!==-1;});colCells.forEach(function(cellId){var cell=map.cells[cellId];if(show){cell.visibleCols.push(colIdx);if(cell.visibleCols.length>1){self.findCell(formLocation,cellId).attr('colspan',cell.visibleCols.length);}else{self.findCell(formLocation,cellId).attr('data-hidden',null);}}else{cell.visibleCols=cell.visibleCols.filter(function(idx){return idx!==colIdx;});var cells=self.findCell(formLocation,cellId);cells.attr({'colspan':cell.visibleCols.length>1?cell.visibleCols.length:null,});if(cell.visibleCols.length===0){cells.attr('data-hidden','');}}});},showRowOnly:function(formLocation,cellId,recordId){var $row=this.findCellRow(formLocation,cellId,recordId);if($row.attr('data-hidden')!==undefined){$row.attr('data-hidden',null);}},toggleRow:function(formLocation,rowIdx,recordId,show){var self=this;var map=this.gridCellMap[formLocation];var rowCells=Object.keys(map.cells).filter(function(cellId){return map.cells[cellId].rows.indexOf(rowIdx)!==-1;});var cellsArr=[];rowCells.forEach(function(cellId){var cell=map.cells[cellId];var $cell=self.findCell(formLocation,cellId,recordId);cellsArr=cellsArr.concat($cell.toArray());if(show){if($cell.attr('data-hidden')!==undefined){$cell.attr('data-hidden',null);$cell.attr('rowspan',null);}else{var rowspan=$cell.attr('rowspan')||1;$cell.attr('rowspan',rowspan+1);}}else{var rowspan=$cell.attr('rowspan')||1;if(rowspan>1){$cell.attr('rowspan',rowspan-1);}else{$cell.attr('rowspan',null);$cell.attr('data-hidden','');}}});$(cellsArr).closest('tr').attr('data-hidden',show?null:'');},cellVisible:function(formLocation,cellId,recordId){var $cell=this.findCell(formLocation,cellId,recordId);return!$cell.is('[data-hidden]')&&!$cell.closest('tr').is('[data-hidden]');},canHideRow:function(formLocation,rowIdx,recordId){var self=this;var map=this.gridCellMap[formLocation];var rowCells=Object.keys(map.cells).filter(function(cellId){return map.cells[cellId].rows.indexOf(rowIdx)!==-1;});if(rowCells.filter(function(cellId){return!!map.cells[cellId].fixedAtClient;}).length!==0){return false;}
var rowItems=rowCells.reduce(function(items,cellId){return items.concat(map.cells[cellId].items);},[]);return!rowItems.filter(function(itemId){return self.hasVisibleItem(itemId,recordId);}).length;},canHideCol:function(formLocation,colIdx){var self=this;var map=this.gridCellMap[formLocation];var colCells=Object.keys(map.cells).filter(function(cellId){return map.cells[cellId].cols.indexOf(colIdx)!==-1;});if(colCells.filter(function(cellId){return!!map.cells[cellId].fixedAtClient;}).length!==0){return false;}
var colItems=colCells.reduce(function(items,cellId){return items.concat(map.cells[cellId].items);},[]);return!colItems.filter(function(itemId){return self.hasVisibleItem(itemId);}).length;},updateMedia:function(media){var _this=this;var items=Object.keys(this.itemVisiblity).map(function(itemId){return{itemId:itemId,show:!!_this.mediaMap[media][_this.itemVisiblity[itemId]],};});this.toggleItems(items,true);$("[data-mobile-hidden]").attr("data-mobile-hidden",null);},mediaMap:{0:{0:true,3:true,4:true,5:true,},1:{0:true,2:true,4:true,},2:{0:true,2:true,3:true,1:true,4:true,}},getFieldItems:function(field){return this.fieldItems[field]||[];},toggleField:function(field,show){this.toggleItems(this.getFieldItems(field).map(function(id){return{itemId:id,show:show};}));}}
Runner.util.details.PDPopupDetails=Runner.extend(Runner.util.details.DPPopUp,{constructor:function(cfg){Runner.util.details.PDPopupDetails.superclass.constructor.call(this,cfg);},getUrl:function(page){return Runner.getPageUrl(this.shortTName,page);}});Runner.namespace('Runner.resize');Runner.resize.Grid=Runner.extend(Runner.emptyFn,{pageId:-1,gridSettings:null,columnObjs:null,isShowRows:false,isUseInlineAdd:false,oldLayout:false,layoutName:"",classBasePrefix:"",constructor:function(cfg){Runner.apply(this,cfg);this.pageObj=Runner.pages.PageManager.getAt(this.tName,this.pageId);this.isShowRows=Runner.pages.PageSettings.getTableData(this.tName,"showRows");this.isUseInlineAdd=Runner.pages.PageSettings.getTableData(this.tName,"isInlineAdd");},init:function(){if(!this.isUseInlineAdd&&!this.isShowRows){this.pageObj.fireEvent('afterPageReady',this.pageObj,this.pageObj.proxy,this.pageObj.id);return;}
this.classBasePrefix=this.oldLayout?'runner-':'rnr-';this.cellWrapperClass=this.classBasePrefix+'resize-cellwrapper';this.gridSettings={classes:{table:this.pageObj.gridElem[0].className,thead:{trs:[],ths:[]},tbody:{trs:[],bodyCells:[]}},styles:{table:this.pageObj.gridElem.attr('style')||'',thead:{trs:[],ths:[]},tbody:{trs:[]}},ieconts:{ths:[],tds:[]},rowids:[],recordIds:[]};this.parseGridHeader();this.parseGridBodyFoot();this.pageObj.initViewControls();this.pageObj.fireEvent('afterPageReady',this.pageObj,this.pageObj.proxy,this.pageObj.id);},hasColRowSpans:function(cell){return cell.colspan||cell.rowspan;},isNotMatch:function(){var table=$(this).closest('table');return!table.hasClass('runner-c-grid')&&!table.hasClass('rnr-c-grid');},parseGridHeader:function(){if(!this.pageObj.Y){return;}
var Y=this.pageObj.Y,self=this,initCookies=[],gridCookies=Y.Cookie.get(self.pageObj.shortTName),grSettings=this.gridSettings;this.columnObjs=[];$('thead tr.'+this.classBasePrefix+'toprow',this.pageObj.gridElem).each(function(i){var columnId=0;grSettings.classes.thead.trs[i]=this.className;grSettings.styles.thead.trs[i]=$(this).attr('style')||'';$('th',this).not(self.isNotMatch).each(function(){var $th=$(this);if(self.hasColRowSpans(this)){return;}
self.columnObjs[columnId]={key:'column'+columnId,label:$th.html()||'&nbsp;',allowHTML:true,sortable:false};if(!gridCookies){initCookies[initCookies.length]=this.offsetWidth;}
grSettings.ieconts.ths[columnId]=$th.attr('ieditcont')||'';grSettings.classes.thead.ths[columnId]=this.className;grSettings.styles.thead.ths[columnId]=$th.attr('style')||'';columnId++;});});if(!gridCookies){Y.Cookie.set(this.pageObj.shortTName,Y.JSON.stringify(initCookies));}},parseGridBodyFoot:function(){var self=this,areaCodes=[],grSettings=this.gridSettings;$('tbody tr.'+this.classBasePrefix+'row, tbody tr.'+this.classBasePrefix+'bottomrow',this.pageObj.gridElem).each(function(i){var areaCode={},parseColumn=self.isShowRows&&(self.isUseInlineAdd&&i==1||!self.isUseInlineAdd&&i==0)||!self.isShowRows&&self.isUseInlineAdd&&i==0;grSettings.rowids[i]=this.id;grSettings.classes.tbody.bodyCells[i]=[];grSettings.classes.tbody.trs[i]=this.className;grSettings.styles.tbody.trs[i]={tr:$(this).attr('style')||'',tds:[]};$tds=$('td',this).not(self.isNotMatch).each(function(columnId){var $td=$(this);if(self.hasColRowSpans(this)){return;}
if($td.hasClass(self.classBasePrefix+'edge')||$td.hasClass(self.classBasePrefix+'cl')||$td.hasClass(self.classBasePrefix+'cr')||$td.parent().hasClass(self.classBasePrefix+'bottomrow')){areaCode[self.columnObjs[columnId].key]=$td.html();}else{areaCode[self.columnObjs[columnId].key]='<div class="'+self.cellWrapperClass+'">'+$td.html()+'</div>';}
if(parseColumn){grSettings.ieconts.tds[columnId]=$td.attr('ieditcont')||'';}
grSettings.styles.tbody.trs[i].tds[columnId]=$td.attr('style')||'';grSettings.classes.tbody.bodyCells[i].push(this.className);});grSettings.recordIds.push($tds.eq(0).data("record-id"));areaCodes.push(areaCode);});this.createResizeGrid(areaCodes);},createResizeGrid:function(data){if(!this.pageObj.Y){return;}
var Y=this.pageObj.Y,self=this,gridPar=self.pageObj.gridElem.parent(),table=new Y.DataTable.Base({columns:self.columnObjs,data:data}),$newGridElem;gridPar.children(":not(.rnr-cells-css)").remove();table.render(gridPar[0]);$newGridElem=self.setOldGridSettings().css({overflow:'hidden','table-layout':'fixed',width:this.totalGridWidth+'px'});Y.Resize.prototype.HANDLE_TEMPLATE='<div class="'+Y.ClassNameManager.getClassName('resize','handle')+' '
+Y.ClassNameManager.getClassName('resize','handle','{handle}')+'">'
+'<div class="'+Y.ClassNameManager.getClassName('resize','handle','inner')+' '+Y.ClassNameManager.getClassName('resize','handle','inner','{handle}')+'">'
+'&nbsp;'
+'</div>'
+'</div>';$('th',gridPar).not('.'+this.classBasePrefix+'cl, .'+this.classBasePrefix+'cr'+', .'+self.classBasePrefix+'edge').not(this.isNotMatch).each(function(){var $th=$(this),handle=Runner.isDirRTL()?'l':'r',resizeEventType=Y.UA.gecko?'resize:align':'resize:resize',cellWrapperStyle='width: '+$th.width()+'px; white-space: nowrap;',resize;$th.html('<div class="'+self.cellWrapperClass+'" style="'+cellWrapperStyle+'">'+$th.html()+'</div>');resize=new Y.Resize({node:this,handles:handle,defMinWidth:0});if(Y.UA.ie){resize.delegate.dd._move=function(ev){ev.pageX=window.event.screenX;return Y.DD.Drag.prototype._move.call(resize.delegate.dd,ev);}
resize.delegate.dd.on('drag:mouseDown',function(e){e.ev.pageX=window.event.screenX;});}
resize.on(resizeEventType,function(event){this._defResizeAlignFn(event);event.preventDefault();var nodeElem=this.get('node').getDOMNode(),gridCookies=Y.JSON.parse(Y.Cookie.get(self.pageObj.shortTName)),oldCellWidth=nodeElem.offsetWidth,newCellWidth=this.info.offsetWidth;cellIndex=nodeElem.cellIndex,gridWidth=self.pageObj.gridElem[0].offsetWidth,$nodeElem=$(nodeElem),nodeBorderAndPaddings=$nodeElem.outerWidth()-$nodeElem.width(),columnClass='yui3-datatable-col-'+$nodeElem.attr('data-yui3-col-id');$(self.pageObj.gridElem).css('width',gridWidth+(newCellWidth-oldCellWidth)+'px');$('.'+columnClass,gridPar).css('width',this.info.offsetWidth+'px');$('.'+columnClass+' div.'+self.cellWrapperClass,gridPar).css('width',this.info.offsetWidth+'px');$('div.'+self.cellWrapperClass,nodeElem).css('width',(this.info.offsetWidth-nodeBorderAndPaddings)+'px');});if(Runner.isDirRTL()){resize.on('drag:start',function(){Y.DD.DDM._pg.setStyles({left:'auto',right:'0'});});}
resize.on('resize:end',function(event){event.preventDefault();});if(Y.UA.gecko||Y.UA.ie){var node=$('<div style="position:relative"></div>');$th.children().appendTo(node);node.appendTo($th);}else{$th.css('position','relative');}});if(Runner.isDirRTL()){Y.DD.DDM._pg.setStyles({left:'auto',right:'0'});}},setOldGridSettings:function(){var self=this,$newGridElem=$('.'+this.classBasePrefix+'s-grid table.yui3-datatable-table',this.pageObj.pageCont),grSettings=this.gridSettings,gridCookies;$newGridElem.parent().addClass(this.classBasePrefix+'s-grid').addClass('not-container').addClass(this.layoutName);$newGridElem.parent().parent().addClass(this.classBasePrefix+'c-grid');$newGridElem.addClass(grSettings.classes.table);if(grSettings.styles.table){$newGridElem.attr('style',grSettings.styles.table);}
gridCookies=this.pageObj.Y.JSON.parse(this.pageObj.Y.Cookie.get(this.pageObj.shortTName));this.totalGridWidth=0;$('thead tr',$newGridElem).not(this.isNotMatch).each(function(i){var $tr=$(this);$tr.addClass(grSettings.classes.thead.trs[i]);if(grSettings.styles.thead.trs[i]){$tr.attr('style',grSettings.styles.thead.trs[i]);}
$('th',$tr).not(self.isNotMatch).each(function(j){var $th=$(this);$th.addClass(grSettings.classes.thead.ths[j]);if(grSettings.styles.thead.ths[j]){$th.attr('style',grSettings.styles.thead.ths[j]);}
if(!$th.hasClass(self.classBasePrefix+'edge')&&!$th.hasClass(self.classBasePrefix+'cl')&&!$th.hasClass(self.classBasePrefix+'cr')&&gridCookies[j]!==0){$th.css('width',gridCookies[j]+'px');}else{$th.css('width',$th.width()+'px');}
self.totalGridWidth+=$th.width();if(grSettings.ieconts[j]){$th.attr('ieditcont')=grSettings.ieconts.ths[j];}});});$('tbody.yui3-datatable-data tr',$newGridElem).not(this.isNotMatch).each(function(i){var $tr=$(this),isRowTFoot,recordId=grSettings.recordIds[i];$tr.addClass(grSettings.classes.tbody.trs[i]);isRowTFoot=$tr.hasClass('footer');this.id=grSettings.rowids[i];if(!isRowTFoot&&grSettings.styles.tbody.trs[i].tr){$tr.attr('style',grSettings.styles.tbody.trs[i].tr);}
$('td',this).not(self.isNotMatch).each(function(j){var $td=$(this);$td.addClass(grSettings.classes.tbody.bodyCells[i][j]);if(recordId!==undefined){$td.attr("data-record-id",recordId);}
if(!isRowTFoot){if(grSettings.styles.tbody.trs[i].tds[j]){$td.attr('style',grSettings.styles.tbody.trs[i].tds[j]);}
if(grSettings.ieconts[j]){$td.attr('ieditcont')=grSettings.ieconts.tds[j];}}});});return $newGridElem;}});Runner.AjaxRow=function(pageObj,inlineRow){this.row=inlineRow;this.pageObj=pageObj;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){var ctrl=Runner.getControl(this.row.id,fName);if(ctrl){return ctrl.getValue();}
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;},recordId:function(){return this.row.id;},getRowObject:function(){return this.row;},getKeys:function(){return this.row.keys;},getDetails:function(){return this.row.detPage;}};Runner.PDF={customTableLayouts:{vrecord:{hLineWidth:function(i,node){return(i===0||i===node.table.body.length)?0.1:0;},vLineWidth:function(i,node){return(i===0||i===node.table.widths.length)?0.1:0;},hLineColor:function(i,node){return'gray';},vLineColor:function(i,node){return'gray';},},panel:{hLineWidth:function(i,node){return(i<2||i===node.table.body.length)?0.1:0;},vLineWidth:function(i,node){return(i===0||i===node.table.widths.length)?0.1:0;},hLineColor:function(i,node){return'gray';},vLineColor:function(i,node){return'gray';},}},create:function(params,pageObj,callback){params.orientation=params.orientation||'portrait';params.scale=params.scale||100;params.table=params.table||pageObj.tName;if(!params.pageType){if(params.page){var pages=Runner.pages.PageSettings.getTableData(params.table,'pages')||{};params.pageType=pages[page];}
if(!params.pageType){if(params.table==pageObj.tName&&pageObj.pageType=='view'){params.pageType='view';}else{params.pageType='print';}}}
params.page=params.page||pageObj.pageName;params.scope=params.scope||0;params.split=params.split||0;params.records=params.records||20;params.filename=params.filename||'file.pdf';return Runner.PDF.loadLibrary(function(){Runner.PDF.loadJSON(params,pageObj,function(docDefinition){var callEventAndCreatePDF=function(){var ret=true;if(params.beforeCreate instanceof Function){ret=params.beforeCreate.call(pageObj,docDefinition,create);}
if(ret!==false){create();}}
var create=function(){callback(pdfMake.createPdf(docDefinition));}
var loadingCJK=false;if(Runner.PDF.processCJK(docDefinition,params)){loadingCJK=true;Runner.PDF.loadCJKFont(callEventAndCreatePDF);}
Runner.PDF.postProcessJson(docDefinition,params,function(){Runner.PDF.prepareBackground(docDefinition,params)
pdfMake.tableLayouts=Runner.PDF.customTableLayouts;if(!loadingCJK){callEventAndCreatePDF();}});});});},prepareBackground:function(docDefinition,params){if(!docDefinition.background||!docDefinition.background.image){return;}
var height=792,width=612;if(params.orientation==='landscape'){height=612;width=792;}
var multiplier=1.08;height*=multiplier;width*=multiplier;var imgWidth=docDefinition.background.imgWidth;var imgHeight=docDefinition.background.imgHeight;if(!imgHeight||!imgWidth){imgWidth=width;imgHeight=height;}
var xoffset=0,yoffset=0;if(imgWidth/imgHeight>width/height){docDefinition.background.height=height;docDefinition.background.width=imgWidth*height/imgHeight;xoffset=(width-docDefinition.background.width)/2;}else{docDefinition.background.width=width;docDefinition.background.height=imgHeight*width/imgWidth;yoffset=(height-docDefinition.background.height)/2;}
docDefinition.background.absolutePosition={x:xoffset,y:yoffset}
var opacity=parseInt(params.backgroundOpacity);if(!isNaN(opacity)){docDefinition.background.opacity=opacity/100;}},loadLibrary:function(callback){var path=settings.global["webRootPath"]+'include/pdfmake/';var mainFile='pdfmake.min.js';var fontFiles=['roboto.js'];Runner.util.ScriptLoader.addJS([path+mainFile]);Runner.util.ScriptLoader.addJS(fontFiles.map(function(f){return path+f;}),path+mainFile);Runner.util.ScriptLoader.onFilesLoaded(function(){if(pdfMake&&pdfMake.addVirtualFileSystem){pdfMake.addVirtualFileSystem(Runner.PDF.vfs);}
pdfMake.fonts={Roboto:{normal:'Roboto-Regular.ttf',bold:'Roboto-Medium.ttf',italics:'Roboto-Italic.ttf',bolditalics:'Roboto-MediumItalic.ttf'},};callback();});Runner.util.ScriptLoader.load();},loadCJKFont:function(callback){var assignFonts=function(){var filename='NotoSansCJKtc-Regular.ttf';pdfMake.fonts['Noto Sans CJK']={normal:filename,bold:filename,italics:filename,bolditalics:filename};}
if(Runner.PDF.vfs['NotoSansCJKtc-Regular.ttf']){assignFonts();window.setTimeout(callback,0);return;}
Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/pdfmake/cjk.js']);Runner.util.ScriptLoader.addJS([settings.global["webRootPath"]+'include/pdfmake/zip.js']);Runner.runLoading(Runner.lang.constants.LOADING_FONTS);Runner.util.ScriptLoader.onFilesLoaded(function(){zip.workerScriptsPath="include/pdfmake/";zip.createReader(new zip.Data64URIReader(Runner.PDF.vfs['NotoSansCJKtc-Regular.zip']),function(zipReader){zipReader.getEntries(function(entries){entries[0].getData(new zip.Data64URIWriter("text/plain"),function(data){zipReader.close();Runner.PDF.vfs['NotoSansCJKtc-Regular.ttf']=data;delete Runner.PDF.vfs['NotoSansCJKtc-Regular.zip'];assignFonts();Runner.stopLoading();callback();});});});});Runner.util.ScriptLoader.load();},loadJSON:function(params,pageObj,callback){var baseParams=pageObj?Runner.apply({},pageObj.getBaseParams()):{};baseParams=Runner.apply(baseParams,{pdfjson:true,id:Runner.genId(),page:params.page});if(params.backgroundImage){baseParams['pdfBackgroundImage']=params.backgroundImage;}
var printPanelParams=pageObj?pageObj.printPanelParams():{};if(Object.keys(printPanelParams).length!==0){baseParams=Runner.apply(baseParams,printPanelParams);}
if(params.scope==0){}
else if(params.scope==1){baseParams.all=1;}
else if(params.scope===2){baseParams.selection=pageObj?pageObj.getSelectedRecordKeys():[];if(!baseParams.selection||!baseParams.selection.length){return;}}
if(params.split==0){delete baseParams.records;}else if(params.split==1){baseParams.records=params.records;}
params.table=params.table||pageObj.tName;if(params.pageType==='view'){(params.keys||[]).forEach(function(value,idx){baseParams['editid'+(idx+1)]=value;});}
if(params.selection instanceof Array){baseParams['selection[]']=params.selection.map(function(keys){return keys.map(function(k){return Runner.escapeHtml(k);}).join('&');});}
jQuery.post((Runner.pages.getUrl(params.table,params.pageType)),baseParams,function(respData){var pdfDocument,message;try{eval(respData);}catch(e){message=(typeof e=='string'?e:e.message)+"<br>"||'';}
if(pdfDocument===undefined){Runner.displayGenericAjaxError(message+'<br>'+respData);return;}
callback.call(pageObj,pdfDocument);});},traversePdfObject:function(obj,predicate,exitPredicate){Object.keys(obj).forEach(function(k){if(obj[k]instanceof Object){if(predicate(obj[k],k,obj)!==false){if(obj[k]instanceof Object){Runner.PDF.traversePdfObject(obj[k],predicate,exitPredicate);if(exitPredicate){exitPredicate(obj[k],k,obj);}}}}});},processCJK:function(docDefinition,params){if(!Runner.PDF.detectChinese){return false;}
Runner.PDF.needCJK=false;Runner.PDF.createCJKRegex();Runner.PDF.traversePdfObject(docDefinition.content,function(obj,key,parent){},function(obj,key,parent){if(typeof obj.text=='string'){obj.text=Runner.PDF.processCJKString(obj.text);}else{if(obj instanceof Array&&key!=='widths'){parent[key]=obj.map(function(str){if(typeof str!=='string'){return str;}
var updated=Runner.PDF.processCJKString(str);if(typeof updated==='string'){return updated;}
return{text:updated};});}}});return Runner.PDF.needCJK;},processHtml:function(pdfDocument,callback){var testHtml=function(str){return str.indexOf("<")!==-1;}
var processHtmlString=function(str){if(!testHtml(str)){return str;}
var $tmpPDFHTML=$('<iframe id="tmpPDFHTML"/>').hide().appendTo('body').contents().find('body').append(str);var ret=$tmpPDFHTML.text();$('iframe#tmpPDFHTML').remove();return ret;}
var imgUrlsObj={};var htmlStack=[];Runner.PDF.traversePdfObject(pdfDocument.content,function(obj,key,parent){if(obj.isHtml){htmlStack.push(true);}
if(htmlStack.length&&obj&&(typeof obj.text=='string'||obj instanceof Array)){if(typeof obj.text=='string'){obj.text=processHtmlString(obj.text);}else{parent[key]=obj.map(function(o){if(typeof o=='string'){return processHtmlString(o);}
return o;});}}
if(obj&&(typeof obj.image=='string')&&obj.image.indexOf('data:image')!==0){imgUrlsObj[obj.image]=obj.image;}},function(obj,key,parent){if(obj.isHtml){htmlStack.pop();}});var imgUrlsArr=Object.keys(imgUrlsObj);var corruptedImg='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACLSURBVDhP7ZBBDsAgCAT7/9/0Ub7DboQQtItK06NzICuBCfGqP3FEa4jojtEJBhdpcqBZSpm4EiLUiSsnApErIfJo17ErwiFGQgSwgCxr8rQmQhvsICLBlu35bnpCEaALtAm4yE9HmwP8j+z+IUuVMMBFqLKP6rPVNtgRiiYkREt01ME/+wNHtKLWB6NMdkWl1LLKAAAAAElFTkSuQmCC';var processImageUrl=function(url){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.responseType='arraybuffer';xhr.onload=function(e){var contentType=xhr.getResponseHeader('Content-Type');var arr=new Uint8Array(this.response);var strArr='';for(var i=0;i<arr.byteLength;i++){strArr+=String.fromCharCode(arr[i]);}
var b64=btoa(strArr);var dataURL="data:"+contentType+";base64,"+b64;if(contentType=='image/jpeg'||contentType=='image/png'){imgUrlsObj[url]=dataURL;processImgUrlsList();}else{var canvas=document.createElement("canvas");var ctx=canvas.getContext("2d");var img=new Image();img.onload=function(){try{canvas.width=img.width;canvas.height=img.height;ctx.drawImage(img,0,0);var dataUrlPng=canvas.toDataURL("image/png");$(canvas).remove();imgUrlsObj[url]=dataUrlPng;processImgUrlsList();}catch(e){$(canvas).remove();imgUrlsObj[url]=corruptedImg;processImgUrlsList();}};img.onerror=function(){$(canvas).remove();imgUrlsObj[url]=corruptedImg;processImgUrlsList();}
img.src=dataURL;}};xhr.onerror=function(e){imgUrlsObj[url]=corruptedImg;processImgUrlsList();};xhr.send();}
var processImgUrlsList=function(){if(imgUrlsArr.length==0){Runner.PDF.traversePdfObject(pdfDocument.content,function(obj,key,parent){if(obj&&(typeof obj.image=='string')&&obj.image.indexOf('data:image')!==0){obj.image=imgUrlsObj[obj.image]||corruptedImg;}},function(){});callback();}else{processImageUrl(imgUrlsArr.pop());}}
processImgUrlsList();},postProcessJson:function(pdfDocument,params,callback){var textStack=[];var textNode=function(obj){if(!obj||obj.text!==undefined||typeof obj=='string'){return true;}
return false;}
var stackNode=function(obj){return obj&&typeof obj==='object'&&!(obj instanceof Array)&&obj.text===undefined;}
var canConvertToText=function(obj){if(obj.stack){if(!obj.stack.length){return true;}
if(obj.stack.length===1){return textNode(obj.stack[0]);}}
return false;}
var multiplier=0.5;var qrMultiplier=1.5;if(params.pageType==='view'){multiplier*=1.2;}
if(params.orientation==='landscape'){multiplier=multiplier*11/8.5;}
multiplier=multiplier*params.scale/100;var firstPageBreak=true;var inColor=[];var vPadding=4;var hPadding=8;var pageIndicatorText;var maxImgWidthPx=params.orientation==='landscape'?761:510;Runner.PDF.traversePdfObject(pdfDocument.content,function(obj,key,parent){if(firstPageBreak&&obj.pageBreak!==undefined){delete obj.pageBreak;firstPageBreak=false;}
if(obj.page_indicator){parent[key]='';pageIndicatorText=obj.text;return;}
if(obj.table&&obj.layout){obj.layout.paddingLeft=function(){return hPadding*multiplier;}
obj.layout.paddingRight=function(){return hPadding*multiplier;}
obj.layout.paddingTop=function(){return vPadding*multiplier;}
obj.layout.paddingBottom=function(){return vPadding*multiplier;}}
if(obj.heights){obj.heights.forEach(function(height,_idx){obj.heights[_idx]*=multiplier;});}
if(obj.hasOwnProperty('checkbox')){obj.canvas=Runner.PDF.pdfCheckbox(obj.checkbox,multiplier);delete obj.checkbox;delete obj.text;}
if(obj.text&&typeof obj.text==='object'&&!(obj.text instanceof Array)){obj.text=[obj.text];}
if(obj.stack&&typeof obj.stack==='object'&&!(obj.stack instanceof Array)){obj.stack=[obj.stack];}
if(!!obj.hidden){parent[key]='';return;}
if(obj.fontSize){obj.fontSize*=multiplier;}
if(obj.margin){if(Array.isArray(obj.margin)){obj.margin.forEach(function(m,index,array){array[index]=m*multiplier;});}else{obj.margin*=multiplier;}}
if(obj.fit){obj.fit*=multiplier*qrMultiplier;if(obj.fit<40){obj.fit=40;}}
if(canConvertToText(obj)){parent.text=parent.stack;delete parent.stack;}
if(textNode(obj)){textStack.push(obj);}
if(obj.color){inColor.push(true);}
if(obj.link&&!inColor.length){obj.color='#337ab7';inColor.push(true);}
if(obj.image){obj.width*=multiplier;obj.height*=multiplier;if(!isNaN(obj.width)&&obj.width>maxImgWidthPx){obj.width=maxImgWidthPx;}}
if(obj.table){if(!obj.table.body||!obj.table.body.length){obj.text='';delete obj.table;return;}}
if(obj.tableForm){var spannedCells={};obj.body=obj.body.map(function(row){return row.filter(function(cell){if(cell.cellId){if(!cell.row&&!cell.col){spannedCells[cell.cellId]=[cell.rowSpan||1,cell.colSpan||1];return true;}else{var spannedCell=spannedCells[cell.cellId];if(!spannedCell||spannedCell[0]<=cell.row||spannedCell[1]<=cell.col){return false;}}}
return true;});});}
if(obj.tableForm){obj.body.forEach(function(row){var addCells=0;while(row.length<obj.widths.length){row.push({});}});}},function(obj,key,parent){if(textNode(obj)){textStack.pop();if(obj.hasStack){var lastTextElem=null;obj.stack=(obj.text instanceof Array?obj.text:[obj.text]).reduce(function(stack,e){if(typeof e==='string'||textNode(e)){if(lastTextElem){lastTextElem.text.push(e);}else{lastTextElem={text:[e]}
stack.push(lastTextElem);}}else{stack.push(e);lastTextElem=null;}
return stack;},[]);delete obj.text;}}
if(stackNode(obj)){if(textStack.length){textStack[textStack.length-1].hasStack=true;}}
if(obj.color){inColor.pop();}});Runner.PDF.traversePdfObject(pdfDocument,function(obj,key,parent){if(obj.text&&obj.text instanceof Array&&obj.text.length>1){obj.text=obj.text.reduce(function(newText,txt,idx){if(idx>0){newText.push(' ');}
newText.push(txt);return newText;},[]);}});if(pageIndicatorText){pdfDocument.header=function(page,pagecount){var replace=function(str){return str.replace('%current%',page).replace('%total%',pagecount);}
var newText='';if(typeof pageIndicatorText=='string'){newText=replace(pageIndicatorText);}else if(pageIndicatorText instanceof Array){newText=pageIndicatorText.map(function(str){if(str.text&&typeof str.text=='string'){var clone=JSON.parse(JSON.stringify(str));clone.text=replace(clone.text);return clone;}else if(typeof str=='string'){return replace(str);}});}
return{text:newText,fontSize:7,alignment:'right',margin:[20,3]};}}
pdfDocument.pageOrientation=params.orientation;Runner.PDF.processHtml(pdfDocument,callback);},pdfCheckbox:function(checked,zoom){zoom*=0.6;var color=checked?'#000000':'#a0a0a0';var checkbox=[{lineColor:color,type:'rect',x:0,y:0,w:20*zoom,h:20*zoom,lineWidth:1.5*zoom,}]
if(checked){checkbox.push({lineColor:color,type:'polyline',lineWidth:2.5*zoom,points:[{x:4*zoom,y:10*zoom},{x:8*zoom,y:15*zoom},{x:16*zoom,y:5*zoom}]});}
return checkbox;},open:function(params,pageObj,win){if(window.navigator&&window.navigator.msSaveOrOpenBlob){win=null;}else{win=win||window.open('','_blank');}
Runner.PDF.create(params,pageObj,function(pdf){if(!win){pdf.download(params.filename);}else{pdf.open(win);}});},download:function(params,filename,pageObj){if(filename){params.filename=filename;}
Runner.PDF.create(params,pageObj,function(pdf){pdf.download(params.filename);});},JAPANESE_RANGE:'[\\u4e00-\\u9fff]|[\\u3400-\\u4dbf]|[\\u{20000}-\\u{2a6df}]|[\\u{2a700}-\\u{2b73f}]|[\\u{2b740}-\\u{2b81f}]|[\\u{2b820}-\\u{2ceaf}]|[\\uf900-\\ufaff]|[\\u3300-\\u33ff]|[\\ufe30-\\ufe4f]|[\\uf900-\\ufaff]|[\\u{2f800}-\\u{2fa1f}]',CHINESE_RANGE:'[\\u3000-\\u303f]|[\\u3040-\\u309f]|[\\u30a0-\\u30ff]|[\\uff00-\\uff9f]|[\\u4e00-\\u9faf]|[\\u3400-\\u4dbf]',KOREAN_RANGE:'[\\uac00-\\ud7af]|[\\u1100-\\u11ff]|[\\u3130-\\u318f]|[\\ua960-\\ua97f]|[\\ud7b0-\\ud7ff]',CJK_REGEX:null,CJK_FONT:'Noto Sans CJK',createCJKRegex:function(){this.CJK_REGEX=new RegExp('\\s*(('
+[this.JAPANESE_RANGE,this.CHINESE_RANGE,this.KOREAN_RANGE].join('|')
+')+\\s*)+','ug');this.createCJKRegex=function(){};},processCJKString:function(str){return this.updateStringFont(str,this.CJK_REGEX,this.CJK_FONT,'needCJK');},updateStringFont:function(str,re,font,flag){var ret=str,lastIndex=0,match;while((match=re.exec(str))!==null){if(!(ret instanceof Array)){ret=[];}
if(match.index>lastIndex){ret.push(str.substr(lastIndex,match.index-lastIndex));}
ret.push({text:match[0],font:font});lastIndex=match.index+match[0].length;}
if(lastIndex<str.length&&(ret instanceof Array)){ret.push(str.substr(lastIndex));}
if(ret instanceof Array){this[flag]=true;}
return ret;},detectChinese:true,}