/*!@license
 * Infragistics.Web.ClientUI Data Binding Plugin 21.2.12
 *
 * Copyright (c) 2011-2022 Infragistics Inc.
 *
 * igDataSource provides the following functionality:
 * - read and parse local XML , JSON , and HTML data
 * - normalize / transform the above data according to a schema
 * - data type conversion (date, string, number, etc.)
 * - define relationships between two and more flat data sources - with primary/foreign keys, etc
 * - build URL params for requests that get remote data
 * - in case of scenarios such as paging, understand and prase the response - expect that it's in a predefined format that can be additionall configured by the developer
 * - get data from WCF services
 * - ability to combine local with remote functionality
 * - queueing AJAX requests
 *	paging,filtering (searching), and sorting functionality that are control-independent are also implemented here
 *	the idea of this code is to serve as a data-source abstraction layer (client-side data source control)
 *	that may well be used by all other client-side controls , such as dropdown, tree, menu, etc.
 *
 * http://www.infragistics.com/
 *
 * Depends on:
 *	jquery.js
 *	infragistics.util.js
 *  infragistics.util.jquery.js
 *
 */
"use strict";(function(factory){if(typeof define==="function"&&define.amd){define(["jquery","./infragistics.util","./infragistics.util.jquery"],factory)}else{return factory(jQuery)}})(function($){/*!@license
* Infragistics.Web.ClientUI data source localization resources 21.2.12
*
* Copyright (c) 2011-2022 Infragistics Inc.
*
* http://www.infragistics.com/
*
*/
(function($){$.ig=$.ig||{};$.ig.locale=$.ig.locale||{};$.ig.locale.en=$.ig.locale.en||{};$.ig.DataSourceLocale=$.ig.DataSourceLocale||{};$.ig.locale.en.DataSourceLocale={invalidDataSource:"The supplied data source is invalid. It happens to be a scalar.",unknownDataSource:"Cannot determine the data source type. Please specify if it is JSON or XML data.",errorParsingArrays:"There was an error parsing the array data and applying the defined data schema: ",errorParsingJson:"There was an error parsing the JSON data and applying the defined data schema: ",errorParsingXml:"There was an error parsing the XML data and applying the defined data schema: ",errorParsingHtmlTable:"There was an error extracting the data from the HTML Table and applying the schema : ",errorExpectedTbodyParameter:"Expected a tbody or a table as a parameter.",errorTableWithIdNotFound:"The HTML Table with the following ID was not found: ",errorParsingHtmlTableNoSchema:"There was an error parsing the Table DOM: ",errorParsingJsonNoSchema:"There was an error parsing/evaluating the JSON string: ",errorParsingXmlNoSchema:"There was an error parsing the XML string: ",errorXmlSourceWithoutSchema:"The supplied data source is an xml document, but there is no defined data schema ($.IgDataSchema) ",errorUnrecognizedFilterCondition:" The filter condition that was passed was not recognized: ",errorRemoteRequest:"The remote request to fetch data has failed: ",errorSchemaMismatch:"The input data doesn't match the schema, the following field couldn't be mapped: ",errorSchemaFieldCountMismatch:"The input data doesn't match the schema in terms of number of fields. ",errorUnrecognizedResponseType:"The response type was either not set correctly, or it was not possible to detect it automatically. Please set settings.responseDataType and/or settings.responseContentType.",hierarchicalTablesNotSupported:"Tables are not supported for HierarchicalSchema",cannotBuildTemplate:"The jQuery template could not be built. There are no records present in the data source, and no columns defined.",unrecognizedCondition:"Unrecognized filtering condition in the following expression: ",fieldMismatch:"The following expression contains an invalid field or filtering condition: ",noSortingFields:"There are no fields specified. You need to specify at least one field to sort by, when calling sort().",filteringNoSchema:"There is no schema / fields specified. You need to specify a schema with field definitions and types to be able to filter the data source.",noSaveChanges:"Saving changes was not successful. Server did not return Success object or returned Success:false.",errorUnexpectedCustomFilterFunction:"An unexpected value was provided for a custom filtering function. A function or string is expected."};$.ig.DataSourceLocale.locale=$.ig.DataSourceLocale.locale||$.ig.locale.en.DataSourceLocale;return $.ig.locale.en.DataSourceLocale})($);$.ig=$.ig||{};if(!window.Infragistics){window.Infragistics=$.ig}$.ig.DataSource=$.ig.DataSource||Class.extend({settings:{id:"ds",outputResultsName:null,callback:null,callee:null,data:[],dataSource:null,dataBinding:null,dataBound:null,requestType:"GET",type:"unknown",schema:null,primaryKey:null,responseTotalRecCountKey:null,responseDataKey:null,responseDataType:null,responseContentType:null,localSchemaTransform:true,urlParamsEncoding:null,urlParamsEncoded:null,paging:{enabled:false,type:"remote",pageSize:5,pageSizeUrlKey:null,pageIndexUrlKey:null,pageIndex:0,appendPage:false},filtering:{type:"remote",caseSensitive:false,applyToAllData:true,customFunc:null,filterExprUrlKey:null,filterLogicUrlKey:"filterLogic",defaultFields:[],expressions:[],exprString:"",customConditions:null},sorting:{defaultDirection:"none",defaultFields:[],applyToAllData:true,customFunc:null,compareFunc:null,customConvertFunc:null,type:"remote",caseSensitive:false,sortUrlKey:null,sortUrlAscValueKey:null,sortUrlDescValueKey:null,expressions:[],exprString:""},groupby:{defaultCollapseState:false,groupRecordKey:"__gbRecord",groupSummaryRecordKey:"__gbSummaryRecord",summaries:[],summariesPosition:"bottom",pagingMode:"allRecords"},summaries:{type:"remote",summaryExprUrlKey:"summaries",summariesResponseKey:"summaries",summaryExecution:"afterfilteringandpaging",columnSettings:[]},fields:[],serializeTransactionLog:true,aggregateTransactions:false,autoCommit:false,updateUrl:null,rowAdded:null,rowUpdated:null,rowInserted:null,rowDeleted:null},init:function(options){var tempSource,tempCallee,arrayAlready=false,metadata;if(options){tempSource=options.dataSource;if(tempSource&&($.type(tempSource)==="array"||$.type(tempSource)==="object")){if($.type(tempSource)==="object"&&options.responseDataKey&&options.type!=="json"){metadata=tempSource.Metadata;options.dataSource=$.ig.findPath(tempSource,options.responseDataKey);if(metadata&&options.dataSource.Metadata===undefined){options.dataSource.Metadata=metadata}arrayAlready=true}else{options.dataSource=null}}if(options.callee){tempCallee=options.callee;options.callee=null}this.settings=$.extend(true,{},$.ig.DataSource.prototype.settings,options);if(arrayAlready){this.settings.type="array"}else if(tempSource&&($.type(tempSource)==="array"||$.type(tempSource)==="object")){options.dataSource=tempSource;this.settings.dataSource=tempSource}if(tempCallee){this.settings.callee=tempCallee;tempCallee=null}}this.settings.paging.pageIndex=0;this._isBound=false;this._url=null;this._dsCallback=null;this._data=[];this._dataView=[];if(this.settings.type==="unknown"){this._runtimeType=this.analyzeDataSource()}else{this._runtimeType=this.settings.type}this._parser=new $.ig.TypeParser;this._schema=null;this._isSortingReq=false;this._isFilteringReq=false;this._isPagingReq=false;this._isSummariesReq=false;this._dataSummaries=[];this._recCount=0;this._hasCount=false;this._initSchema();this._transactionLog=[];this._accumulatedTransactionLog=[];return this},_initSchema:function(){var i;if(this.settings.schema){if(this.settings.schema instanceof $.ig.DataSchema){this._schema=this.settings.schema}else{if(this.settings.type!=="unknown"){this._schema=new $.ig.DataSchema(this.settings.type,this.settings.schema)}else{this._schema=new $.ig.DataSchema(this._runtimeType,this.settings.schema)}this._schema._pk=this.settings.primaryKey}this._fields={};for(i=0;i<this._schema.fields().length;i++){if(typeof this._schema.fields()[i].mapper==="string"&&typeof window[this._schema.fields()[i].mapper]==="function"){this._schema.fields()[i].mapper=window[this._schema.fields()[i].mapper]}if(typeof this._schema.fields()[i].mapper==="function"){this._hasMapper=true}this._fields[this._schema.fields()[i].name]=this._schema.fields()[i]}}},fields:function(fields){if(fields===undefined||fields===null){return this.settings.fields}this.settings.fields=fields;return this},analyzeDataSource:function(){var ds=this.dataSource(),dc,$dsObj;if(ds===undefined||ds===null){return"empty"}if($.type(ds)==="function"){return"function"}if($.type(ds)==="array"){return"array"}if($.type(ds)==="number"||$.type(ds)==="boolean"||$.type(ds)==="date"){return"invalid"}if($.type(ds)==="string"){ds=$.trim(ds);if(ds.startsWith("/")){return"remoteUrl"}if($("#"+this.settings.id).length>0&&ds.toLowerCase().startsWith("<table")){return"htmlTableString"}if(ds.toLowerCase().startsWith("<table")){dc="<div id='"+this.settings.id+"' style='display:none;visibility:hidden;'>"+ds+"</div>";$(dc).appendTo($("body"));return"htmlTableString"}if(!ds.startsWith("[")&&!ds.startsWith("{")&&!ds.startsWith("<")){if(!ds.startsWith("http://")&&!ds.startsWith("https://")){try{$dsObj=$("#"+ds);if($dsObj.length>0&&$dsObj[0].nodeName.toLowerCase()==="table"){return"htmlTableId"}}catch(e){}}this._url=ds;return"remoteUrl"}return"unknown"}if(ds.nodeName&&ds.nodeName.toLowerCase()==="table"){return"htmlTableDom"}if(ds.nodeName&&(ds.nodeName.toLowerCase()==="ul"||ds.nodeName.toLowerCase()==="ol")){return"htmlListDom"}if(ds.nodeName&&ds.nodeName.toLowerCase()==="select"){return"htmlSelectDom"}return"unknown"},dataView:function(){return this._dataView},data:function(){return this._data},transformedData:function(transformedExecution){var data;switch(transformedExecution){case"priortofilteringandpaging":data=this._data;break;case"afterfilteringbeforepaging":if(this._transformedData!==undefined){data=this._transformedData}else{data=this._data}break;case"afterfilteringandpaging":data=this.dataView();break;default:data=this._dataView;break}return data},dataSummaries:function(){var s=this.settings.summaries,type=s.type;if(type==="local"){this._dataSummaries=this.transformedData(s.summaryExecution)}return this._dataSummaries},schema:function(s,t){if(s===undefined||s===null){return this._schema}if(s instanceof $.ig.DataSchema){this._schema=s}else{if(t===null||t===undefined){this._schema=new $.ig.DataSchema(s.type,s)}else{this._schema=new $.ig.DataSchema(t,s)}this._schema._pk=this.settings.primaryKey}return this},pagingSettings:function(p){if(p===undefined||p===null){return this.settings.paging}this.settings.paging=p;return this},filterSettings:function(f){if(f===undefined||f===null){return this.settings.filtering}this.settings.filtering=f;return this},sortSettings:function(s){if(s===undefined||s===null){return this.settings.sorting}this.settings.sorting=s;return this},summariesSettings:function(s){if(s===undefined||s===null){return this.settings.summaries}this.settings.summaries=s;return this},dataSource:function(ds){if(ds===undefined||ds===null){return this.settings.dataSource}this.settings.dataSource=ds;this.analyzeDataSource();return this},type:function(t){if(t===undefined||t===null){return this._runtimeType}this.settings.type=t;return this},findRecordByKey:function(key,ds,objPath){var i,data=ds||this._data,len=data?data.length:0,search=len>0&&$.isArray(data[0])?this._lookupPkIndex():this.settings.primaryKey;for(i=0;i<len;i++){if(data[i][search]===key){return data[i]}}return null},removeRecordByKey:function(key,origDs){var i,len,data,count=0,all=[this._data],prime=this.settings.primaryKey,primeIdx=this._lookupPkIndex(),search;this._addOnlyUniqueToCollection(all,this._dataView);this._addOnlyUniqueToCollection(all,this._filteredData);this._addOnlyUniqueToCollection(all,origDs);while(count<all.length){data=all[count++];len=data?data.length:0;search=len>0&&$.isArray(data[0])?primeIdx:prime;for(i=0;i<len;i++){if(data[i]&&data[i][search]===key){$.ig.removeFromArray(data,i);break}}}},removeRecordByIndex:function(index,origDs){var i,len,record,data=this._data,view=this._dataView,filter=this._filteredData;if(!data||isNaN(index)||index<0||index>=data.length){return}record=data[index];$.ig.removeFromArray(data,index);if(origDs){$.ig.removeFromArray(origDs,index)}data=data===view?filter:view;while(record){len=data?data.length:0;for(i=0;i<len;i++){if(data[i]===record){$.ig.removeFromArray(data,i);break}}if(data===filter){return}data=filter}},setCellValue:function(rowId,colId,val,autoCommit){var t=this._createCellTransaction(rowId,colId,val);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}return t},updateRow:function(rowId,rowObject,autoCommit){var t=this._createRowTransaction(rowId,rowObject),oldRow=this.settings.primaryKey===null?this._data[parseInt(rowId,10)]:this.findRecordByKey(rowId),rowIndex=this.settings.primaryKey===null?rowId:$.ig.indexInArray(this._data,oldRow);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowUpdated)==="function"){if(this.settings.callee){this.settings.rowUpdated.apply(this.settings.callee,[{rowIndex:rowIndex,newRow:rowObject,oldRow:oldRow},this])}else{this.settings.rowUpdated({rowIndex:rowIndex,newRow:rowObject,oldRow:oldRow},this)}}return t},addRow:function(rowId,rowObject,autoCommit){var t=this._createNewRowTransaction(rowId,rowObject);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowAdded)==="function"){if(this.settings.callee){this.settings.rowAdded.apply(this.settings.callee,[{rowId:rowId,row:rowObject},this])}else{this.settings.rowAdded({rowId:rowId,row:rowObject},this)}}return t},insertRow:function(rowId,rowObject,rowIndex,autoCommit,parentRowId){var t=this._createInsertRowTransaction(rowId,rowObject,rowIndex);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowInserted)==="function"){if(this.settings.callee){this.settings.rowInserted.apply(this.settings.callee,[{rowId:rowId,row:rowObject,rowIndex:rowIndex},this])}else{this.settings.rowInserted({rowId:rowId,row:rowObject,rowIndex:rowIndex},this)}}return t},deleteRow:function(rowId,autoCommit){var t=this._createDeleteRowTransaction(rowId),row=this.settings.primaryKey===null?this._data[parseInt(rowId,10)]:this.findRecordByKey(rowId),rowIndex=this.settings.primaryKey===null?rowId:$.ig.indexInArray(this._data,row),isNewRow=false,i,j;for(i=0;this.settings.aggregateTransactions&&i<this._transactionLog.length;i++){if(this._transactionLog[i].type==="newrow"&&this._transactionLog[i].rowId===rowId){isNewRow=true;rowId=this._transactionLog[i].rowId;this._removeTransactionByTransactionId(this._transactionLog[i].tid);for(j=0;j<this._accumulatedTransactionLog.length;j++){if(this._accumulatedTransactionLog[j].rowId===rowId){$.ig.removeFromArray(this._accumulatedTransactionLog,j)}}break}}if(!(this.settings.aggregateTransactions&&isNewRow)){this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowDeleted)==="function"){if(this.settings.callee){this.settings.rowDeleted.apply(this.settings.callee,[{rowId:rowId,row:row,rowIndex:rowIndex},this])}else{this.settings.rowDeleted({rowId:rowId,row:row,rowIndex:rowIndex},this)}}}return t},addNode:function(data){var t=this._createAddNodeTransaction(data);this._addTransaction(t)},removeNode:function(data){var t=this._createRemoveNodeTransaction(data);this._addTransaction(t)},getDetachedRecord:function(t){var o=$.type(this._data[0])==="array"?[]:{},i,originalRec;if(this.settings.primaryKey===null){originalRec=this._data[parseInt(t.rowId,10)]}else{originalRec=this.findRecordByKey(t.rowId)}if($.type(this._data[0])!=="array"){for(i in originalRec){if(originalRec.hasOwnProperty(i)){o[i]=originalRec[i]}}}else{for(i=0;i<originalRec.length;i++){o[i]=originalRec[i]}}if(t.type==="cell"){o[t.col]=t.value;return o}if($.type(o)!=="array"){for(i in t.row){if(t.row.hasOwnProperty(i)){o[i]=t.row[i]}}}else{for(i=0;i<t.row.length;i++){o[i]=t.row[i]}}return o},commit:function(id){if(id!==null&&id!==undefined){this._commitTransactionsByRowId(id)}else{this._transactionLog.reverse();while(this._transactionLog.length>0){this._commitTransaction(this._transactionLog.pop())}}if(this._getFieldsWithFormatter().length){this._generateFormattedRecords()}},rollback:function(id){var i,trans;if(id!==null&&id!==undefined){trans=this._rollbackTransactionsByRowId(id)}else{i=this._transactionLog.length;while(i-- >0){this._rollbackTransaction(this._transactionLog[i])}}return trans},pendingTransactions:function(){return this._transactionLog},allTransactions:function(){return this._accumulatedTransactionLog},_createCellTransaction:function(rowId,colId,val){return{type:"cell",rowId:rowId,tid:this._generateTransactionId(),col:colId,value:val}},_createRowTransaction:function(rowId,rowObject){return{type:"row",tid:this._generateTransactionId(),row:rowObject,rowId:rowId}},_createNewRowTransaction:function(rowId,rowObject){return{type:"newrow",tid:this._generateTransactionId(),row:rowObject,rowId:rowId}},_createInsertRowTransaction:function(rowId,rowObject,rowIndex){return{type:"insertrow",tid:this._generateTransactionId(),row:rowObject,rowId:rowId,rowIndex:rowIndex}},_createDeleteRowTransaction:function(rowId){return{type:"deleterow",tid:this._generateTransactionId(),rowId:rowId}},_createAddNodeTransaction:function(data){return{type:"addnode",tid:this._generateTransactionId(),tdata:data}},_createRemoveNodeTransaction:function(data){return{type:"removenode",tid:this._generateTransactionId(),tdata:data}},_addTransaction:function(t){var exists=false,i=0,prop,globalt,j,dirty=true,k,shouldAggregateTransactions=this.settings.autoCommit===false&&this.settings.aggregateTransactions===true,isSameAsOrigValue=false,rec=shouldAggregateTransactions?this.findRecordByKey(t.rowId):null;if(t.type==="cell"){for(i=0;i<this._transactionLog.length;i++){if(this._transactionLog[i].rowId===t.rowId&&this._transactionLog[i].col===t.col){exists=true;if(shouldAggregateTransactions){if(rec&&rec[t.col]===t.value){for(k=0;k<this._accumulatedTransactionLog.length;k++){if(this._accumulatedTransactionLog[k].rowId===this._transactionLog[i].rowId){$.ig.removeFromArray(this._accumulatedTransactionLog,k)}}this._removeTransactionByTransactionId(this._transactionLog[i].tid);dirty=false}}if(dirty){this._transactionLog[i].value=t.value;this._syncGlobalTransaction(this._transactionLog[i])}}if(shouldAggregateTransactions&&rec&&rec[t.col]===t.value){isSameAsOrigValue=true}}for(j=0;j<this._transactionLog.length;j++){if(this._transactionLog[j].type==="newrow"&&this._transactionLog[j].rowId===t.rowId){if(t.type==="row"){this._transactionLog[j].value=t.value}else{this._transactionLog[j].row[t.col]=t.value}this._syncGlobalTransaction(this._transactionLog[j]);return}}}else if(t.type==="row"){for(i=0;i<this._transactionLog.length;i++){if(this._transactionLog[i].rowId===t.rowId&&this._transactionLog[i].type!=="cell"){exists=true;if(shouldAggregateTransactions){dirty=false;for(prop in t.row){if(rec&&t.row.hasOwnProperty(prop)&&t.row[prop]!==rec[prop]){dirty=true;break}}for(j=0,!dirty;j<this._transactionLog.length;j++){if(this._transactionLog[j].type==="newrow"&&this._transactionLog[j].rowId===t.rowId){this._transactionLog[j].row=t.row;this._syncGlobalTransaction(this._transactionLog[j]);return}}}if(dirty){this._transactionLog[i].row=t.row;this._syncGlobalTransaction(this._transactionLog[i])}else{for(k=0;k<this._accumulatedTransactionLog.length;k++){if(this._accumulatedTransactionLog[k].rowId===this._transactionLog[i].rowId){$.ig.removeFromArray(this._accumulatedTransactionLog,k)}}this._removeTransactionByTransactionId(this._transactionLog[i].tid)}}}if(shouldAggregateTransactions){for(prop in t.row){isSameAsOrigValue=true;if(!(t.row.hasOwnProperty(prop)&&rec&&t.row[prop]===rec[prop])){isSameAsOrigValue=false;break}}}}else if(t.type==="addnode"||t.type==="removenode"){this._transactionLog.push(t);this._accumulatedTransactionLog.push(t);return}if(!exists&&!isSameAsOrigValue){this._transactionLog.push(t);globalt=$.extend(true,{},t);this._accumulatedTransactionLog.push(globalt)}},_syncGlobalTransaction:function(t){var i,prop;if(!t){return}if(t.type==="cell"){for(i=0;i<this._accumulatedTransactionLog.length;i++){if(this._accumulatedTransactionLog[i].rowId===t.rowId&&this._accumulatedTransactionLog[i].col===t.col){this._accumulatedTransactionLog[i].value=t.value;break}}}else if(t.type==="row"||t.type==="insertrow"||t.type==="newrow"){for(i=0;i<this._accumulatedTransactionLog.length;i++){if(this._accumulatedTransactionLog[i].rowId===t.rowId&&this._accumulatedTransactionLog[i].type!=="cell"){for(prop in t.row){if(t.row.hasOwnProperty(prop)){this._accumulatedTransactionLog[i].row[prop]=t.row[prop]}}}}}},_serializeDate:function(date){if($.type(date)!=="date"){return date}if(this.settings.enableUTCDates){date=date.toISOString()}else{date=$.ig.toLocalISOString(date)}return date},_removeTransactionByTransactionId:function(tid,removeFromAll){var i;for(i=0;i<this._transactionLog.length;i++){if(this._transactionLog[i].tid===tid){$.ig.removeFromArray(this._transactionLog,i);break}}if(removeFromAll===true){for(i=0;i<this._accumulatedTransactionLog.length;i++){if(this._accumulatedTransactionLog[i].tid===tid){$.ig.removeFromArray(this._accumulatedTransactionLog,i);break}}}},_removeTransactionsByRecordId:function(id){var i;for(i=0;i<this._transactionLog.length;i++){if(this._transactionLog[i].rowId===id){$.ig.removeFromArray(this._transactionLog,i);break}}},_addRow:function(row,index,origDs){var data,key,i,count=0,schema=this.settings.schema,layouts=schema?schema.layouts:null,lo,pdata,all=[this._data],newRow,collectionProcessedData=[];this._addOnlyUniqueToCollection(all,this._dataView);this._addOnlyUniqueToCollection(all,origDs);if(this._filter&&this._filteredData&&this.settings.paging.enabled&&this.settings.paging.type==="local"){this._addOnlyUniqueToCollection(all,this._filteredData)}if(this._vgbData&&this.isGroupByApplied(this.settings.sorting.expressions)){this._addOnlyUniqueToCollection(all,this._vgbData)}if(layouts){for(key in layouts){if(layouts.hasOwnProperty(key)){if((key.match(/\//g)||[]).length!==1){continue}if(layouts[key].key&&!row.hasOwnProperty(layouts[key].key)){if(layouts[key].responseDataKey){lo={};lo[layouts[key].responseDataKey]=[]}else{lo=[]}row[layouts[key].key]=lo}}}}while(count<all.length){data=all[count++];if(this._preprocessAddRow){pdata=this._preprocessAddRow.apply(this,Array.prototype.slice.call(arguments).concat([data]));data=(pdata||{}).layoutData;if(data){for(i=0;i<collectionProcessedData.length;i++){if(collectionProcessedData[i]===data){data=null;break}}if(data){collectionProcessedData.push(data)}}}if(data){newRow=row;if(origDs&&data!==origDs&&$.type(row)==="object"){newRow=$.extend(true,{},row)}if(index>=0&&index<data.length){data.splice(index,0,newRow)}else{data.push(newRow)}if(this._postprocessAddRow&&pdata){pdata.newData=data;this._postprocessAddRow.apply(this,Array.prototype.slice.call(arguments).concat(pdata));data=pdata.cashedData}}}},_updateRecOnCommit:function(t,records){var i,j,rec,prop;if(t.type==="cell"){for(j=0;j<records.length;j++){rec=records[j];if(rec){rec[t.col]=t.value}}}else if(t.type==="row"){if($.type(t.row)==="array"){for(j=0;j<records.length;j++){rec=records[j];if(rec){for(i=0;i<t.row.length;i++){rec[i]=t.row[i]}}}}else{for(j=0;j<records.length;j++){rec=records[j];if(rec){for(prop in t.row){if(t.row.hasOwnProperty(prop)){rec[prop]=t.row[prop]}}}}}}},_commitTransaction:function(t){var rec,origRec,origDs=this.settings.localSchemaTransform?this._origDs:null;if(origDs===this._data){origDs=null}if(this.settings.primaryKey===null){rec=this._data[parseInt(t.rowId,10)];if(origDs){origRec=origDs[parseInt(t.rowId,10)]}}else{rec=this.findRecordByKey(t.rowId);if(origDs){origRec=this.findRecordByKey(t.rowId,origDs)}}if(t.type==="cell"||t.type==="row"){this._updateRecOnCommit(t,[rec,origRec])}else if(t.type==="deleterow"){if(this.settings.primaryKey===null){this.removeRecordByIndex(parseInt(t.rowId,10),origDs)}else{this.removeRecordByKey(t.rowId,origDs)}if(this.isGroupByApplied(this.settings.sorting.expressions)){this._generateGroupByData(this._filter?this._filteredData:this._data,this.settings.sorting.expressions)}}else if(t.type==="newrow"){this._addRow(t.row,-1,origDs)}else if(t.type==="insertrow"){this._addRow(t.row,t.rowIndex,origDs)}this._removeTransactionByTransactionId(t.tid)},_rollbackTransaction:function(t){this._removeTransactionByTransactionId(t.tid,true)},_commitTransactionsByRowId:function(id){var i;for(i=0;i<this._transactionLog.length;i++){if(this._transactionLog[i].rowId===id){this._commitTransaction(this._transactionLog[i])}}},_rollbackTransactionsByRowId:function(id){var i,trans=[];i=this._transactionLog.length;while(i-- >0){if(this._transactionLog[i].rowId===id){trans.push(this._transactionLog[i]);this._rollbackTransaction(this._transactionLog[i])}}return trans},_addOnlyUniqueToCollection:function(collection,item){var i;for(i=0;i<collection.length;i++){if(collection[i]===item){return}}collection.push(item)},transactionsAsString:function(){return JSON.stringify(this._accumulatedTransactionLog)},_generateTransactionId:function(){return((1+Math.random())*parseInt("10000",16)).toString(16).substring(1,5)},_lookupPkIndex:function(){var i;if(this._pkIndex!==undefined){return this._pkIndex}if(typeof this.settings.primaryKey==="string"){if(this.schema()&&this.schema().fields()&&this.schema().fields().length>0){for(i=0;i<this.schema().fields().length;i++){if(this.schema().fields()[i].name===this.settings.primaryKey){this._pkIndex=i;return i}}}}this._pkIndex=this.settings.primaryKey;return this.settings.primaryKey},saveChanges:function(success,error){if(this.settings.updateUrl!==null){var me=this,opts,i,prop,t,serializedTransactionLog=[];for(i=0;i<this._accumulatedTransactionLog.length;i++){t=$.extend(true,{},this._accumulatedTransactionLog[i]);if(t.type==="cell"){t.value=this._serializeDate(t.value)}else if(t.type==="row"||t.type==="insertrow"||t.type==="newrow"){for(prop in t.row){if(t.row.hasOwnProperty(prop)){if($.type(t.row[prop])==="date"){t.row[prop]=this._serializeDate(t.row[prop])}else{t.row[prop]=t.row[prop]}}}}serializedTransactionLog.push(t)}opts={type:"POST",url:this.settings.updateUrl,data:{ig_transactions:JSON.stringify(serializedTransactionLog)},success:function(data,textStatus,jqXHR){if(data.Success){me._saveChangesSuccess(data,textStatus,jqXHR);if(success){success(data,textStatus,jqXHR)}}else{me._saveChangesError(jqXHR,textStatus,$.ig.util.getLocaleValue("DataSourceLocale","noSaveChanges"));if(error){error(jqXHR,textStatus,$.ig.util.getLocaleValue("DataSourceLocale","noSaveChanges"))}}},error:function(jqXHR,textStatus,errorThrown){me._saveChangesError(jqXHR,textStatus,errorThrown);if(error){error(jqXHR,textStatus,errorThrown)}}};this._ajaxRequest=$.ajax(opts)}},_saveChangesSuccess:function(data,textStatus,jqXHR){var schs,sche,i;if(data.Success){this.commit();this._transactionLog=[];this._accumulatedTransactionLog=[];schs=this._saveChangesHandlers;i=schs?schs.length:0;while(i-- >0){schs[i](data,textStatus,jqXHR)}}else{sche=this._saveChangesErrorHandlers;i=sche?sche.length:0;while(i-- >0){sche[i](jqXHR,textStatus,$.ig.util.getLocaleValue("DataSourceLocale","noSaveChanges"))}}},_saveChangesError:function(jqXHR,textStatus,errorThrown){var sche=this._saveChangesErrorHandlers,i=sche?sche.length:0;while(i-- >0){sche[i](jqXHR,textStatus,errorThrown)}},_addChangesSuccessHandler:function(functionDelegate){if(this._saveChangesHandlers===undefined){this._saveChangesHandlers=[]}this._saveChangesHandlers[this._saveChangesHandlers.length]=functionDelegate},_removeChangesSuccessHandler:function(functionDelegate){if(this._saveChangesHandlers!==undefined){var index=$.ig.indexInArray(this._saveChangesHandlers,functionDelegate);if(index>-1){this._saveChangesHandlers=this._saveChangesHandlers.slice(0,index).concat(this._saveChangesHandlers.slice(index+1,this._saveChangesHandlers.length))}}},_addChangesErrorHandler:function(functionDelegate){if(this._saveChangesErrorHandlers===undefined){this._saveChangesErrorHandlers=[]}this._saveChangesErrorHandlers[this._saveChangesErrorHandlers.length]=functionDelegate},_removeChangesErrorHandler:function(functionDelegate){if(this._saveChangesErrorHandlers!==undefined){var index=$.ig.indexInArray(this._saveChangesErrorHandlers,functionDelegate);if(index>-1){this._saveChangesErrorHandlers=this._saveChangesErrorHandlers.slice(0,index).concat(this._saveChangesErrorHandlers.slice(index+1,this._saveChangesErrorHandlers.length))}}},dataBind:function(callback,callee){var table,tableObj,dsObj,ds,s,p=this.settings,args,resKey,noCancel=true,callDataBound=true,f,fApplied;this._transactionLog=[];this._accumulatedTransactionLog=[];if(!callback){callback=p.callback}args={cancel:false};if($.isFunction(p.dataBinding)){noCancel=p.dataBinding(this,args);if(noCancel===undefined){noCancel=true}}if(noCancel){if(this.settings.type==="unknown"&&(this._runtimeType===null||this._runtimeType===undefined)){this._runtimeType=this.analyzeDataSource()}else if(this._runtimeType==="json"){ds=this.dataSource();if($.type(ds)==="string"){ds=$.trim(ds);if(ds.startsWith("/")||ds.startsWith("http://")||ds.startsWith("https://")){this._runtimeType="remoteUrl"}}}switch(this._runtimeType){case"function":this._data=p.dataSource();if(this.schema()&&this.settings.localSchemaTransform){this._data=this.schema().transform(this._data)}break;case"array":if(this.schema()&&this.settings.localSchemaTransform){this._data=this.schema().transform(this.dataSource());if(this.dataSource().Metadata){this._metadata=this.dataSource().Metadata;this.summariesResponse(this.settings.summaries.summariesResponseKey,this.dataSource())}this._origDs=this.dataSource()}else{this._data=this.dataSource()}break;case"htmlTableDom":case"htmlTableId":case"htmlTableString":if(this._tableBound){break}this._runtimeType=this.analyzeDataSource();if(this._runtimeType==="htmlTableId"){tableObj=$("#"+this.dataSource());table=this._validateTable(tableObj)}else if(this._runtimeType==="htmlTableString"){tableObj=$("#"+this.settings.id+" > table");table=this._validateTable(tableObj)}else{table=this.dataSource()}if(this.schema()&&this.settings.localSchemaTransform){this._data=this.schema().transform(table)}else{this._data=this.tableToObject(table)}this._tableBound=true;break;case"htmlListDom":this._data=this.schema().transform(this.dataSource());break;case"htmlSelectDom":this._data=this.schema().transform(this.dataSource());break;case"invalid":throw new Error($.ig.util.getLocaleValue("DataSourceLocale","invalidDataSource"));case"unknown":case"json":case"xml":if(this.settings.type!=="json"&&p.type!=="xml"){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","unknownDataSource"))}else{resKey=this.settings.responseDataKey;if($.type(this.dataSource())==="string"){if(p.type==="json"){dsObj=this.stringToJSONObject(this.dataSource())}else{dsObj=this.stringToXmlObject(this.dataSource())}}else{dsObj=this.dataSource()}if(this.schema()&&this.settings.localSchemaTransform===true){this._data=this.schema().transform(dsObj);if(resKey!==null&&resKey!==undefined){this._origDs=$.ig.findPath(dsObj,resKey)}else{this._origDs=dsObj}}else if((!this.schema()||this.settings.localSchemaTransform===false)&&p.type==="json"){if(resKey!==null&&resKey!==undefined){this._data=this._origDs=$.ig.findPath(dsObj,resKey)}else{this._data=dsObj}this._origDs=dsObj}else if(!this.schema()&&p.type==="xml"){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorXmlSourceWithoutSchema"))}this.totalRecordsCount(null,this.settings.responseTotalRecCountKey,dsObj,this);if(dsObj&&dsObj.Metadata){this._metadata=dsObj.Metadata}this.summariesResponse(this.settings.summaries.summariesResponseKey,dsObj)}break;case"remoteUrl":callDataBound=false;this._remoteData(callback,callee);break;case"empty":this._data=[];this._dataView=[];this._dataSummaries=[];break;default:break}this._dataView=this._data;this._filter=false;f=p.filtering;s=p.sorting;fApplied=false;if(f.type==="local"&&this._runtimeType!=="remoteUrl"&&f.defaultFields.length>0){this.filter(f.defaultFields);fApplied=true}if(s.type==="local"&&this._runtimeType!=="remoteUrl"&&s.defaultFields.length>0&&(!fApplied||s.defaultFields!==s.expressions)){this.sort(s.defaultFields,s.defaultDirection)}if(!this._gbDataView&&this.isGroupByApplied(this.settings.sorting.expressions)){this._generateGroupByData(this._filter?this._filteredData:this._data,this.settings.sorting.expressions)}if(p.paging.enabled&&p.paging.type==="local"&&this._runtimeType!=="remoteUrl"){this._page()}if(!this._filter||!this._transformedData){this._populateTransformedData()}if(this._runtimeType!=="remoteUrl"){this._invokeCallback(callee,callback)}this._internalDataBound(!args.cancel&&callDataBound)}return this},getCellValue:function(fieldName,record){var field,result;if(!this._hasMapper||!this._fields||this._fields[fieldName]===undefined||this._fields[fieldName].type!=="object"||!record[fieldName]){return record[fieldName]}field=this._fields[fieldName];if(field&&typeof field.mapper==="function"){result=field.mapper(record)}else{result=record[fieldName]}return result},_getFieldTypeFromSchema:function(fieldName){var field,type,ds=this.dataSource();field=this._fields?this._fields[fieldName]:null;if(!field){return undefined}if(this.type()==="remoteUrl"){ds=this.data()}else if(this.type()==="json"&&ds!==null&&ds!==undefined&&this.settings.responseDataKey!==null){ds=$.ig.findPath(ds,this.settings.responseDataKey)}if(typeof field.mapper==="function"&&$.type(ds)==="array"&&ds.length>0){
type=$.type(field.mapper(ds[0]))}else{type=field.type}return type},_internalDataBound:function(callDatabound){if(callDatabound&&$.isFunction(this.settings.dataBound)){this.settings.dataBound(this)}},summariesResponse:function(key,dsObj){if(!dsObj||!key){this._dataSummaries=this._dataSummaries||[];return this.dataSummaries()}var rec,resPath,i,schema,func,offsets,offset,obj;if(key.length>0){rec=dsObj;resPath=key.split(".");for(i=0;i<resPath.length;i++){if(rec===null||rec===undefined){break}rec=rec[resPath[i]]}this._dataSummaries=rec}else{this._dataSummaries=dsObj}this._dataSummaries=this._dataSummaries||[];if(this.settings.localSchemaTransform===true&&this.schema()&&dsObj&&dsObj.Metadata&&dsObj.Metadata.timezoneOffsetsSummaries){offsets=dsObj.Metadata.timezoneOffsetsSummaries;this._dataSummaries._serverOffsetsSummaries=offsets;schema=this.schema().schema;if(schema&&schema.fields){for(i=0;i<schema.fields.length;i++){if((schema.fields[i].type==="date"||schema.fields[i].type==="time")&&offsets[schema.fields[i].name]!==undefined){key=schema.fields[i].name;for(func in offsets[key]){if(offsets[key].hasOwnProperty(func)){offset=offsets[key][func];obj=this._dataSummaries[key][func];if($.type(obj)==="string"){this._dataSummaries[key][func]=new Date(obj)}}}}}}}return this._dataSummaries},_applySchema:function(forceApply){var schema=this.schema(),ds,s=this.settings.sorting,p=this.settings.paging,filtering=this.settings.filtering;if(schema&&schema.fields&&schema.fields().length>0&&(this.settings.localSchemaTransform||forceApply)){this._origDs=this._data;schema._type=$.type(this._data);ds=schema.transform(this._data);this._data=ds;this._dataView=this._data;if(s.type==="local"&&s.defaultFields.length>0){this.sort(s.defaultFields,s.defaultDirection)}else if(this.isGroupByApplied(s.expressions)){this._generateGroupByData(this._filter?this._filteredData:this._data,s.expressions)}if(filtering.type==="local"&&filtering.defaultFields.length>0){this.filter(filtering.defaultFields)}if(p.enabled&&p.type==="local"){this._page()}}},_populateTransformedData:function(data){if(data!==null&&data!==undefined){this._transformedData=data}else{this._transformedData=this._data}},_invokeCallback:function(callee,callback){var cbResolved,calleeResolved;cbResolved=callback||this.settings.callback;calleeResolved=callee||this.settings.callee;if(cbResolved){if(calleeResolved){cbResolved.apply(calleeResolved,[true,"",this])}else{cbResolved(true,"",this)}}},_remoteData:function(callback,callee){var params,url=this.settings.dataSource,dataType=this.settings.responseDataType,contentType=this.settings.responseContentType,options,verb=this.settings.requestType;params=this._encodeUrl();if(callback){this._customCallback=callback}else{this._customCallback=null}this._callee=callee;options={url:url,data:verb==="GET"?params:JSON.stringify(params),type:verb,dataType:dataType,async:true,context:this,contentType:contentType,cache:false,dataFilter:this._dataFilter,success:this._successCallback,complete:this._completeCallback,converters:{"text json":function(value){return value}},error:this._errorCallback};this._processRequest(options)},_dataFilter:function(data,type){var ds,schema=this.context.schema(),rawData,t=this.context.settings.type,ver,returnString=false;if(type===undefined||type===null){if(typeof data==="object"&&data&&typeof data.charAt!=="function"){if($.isXMLDoc(data)){type="xml"}else{type="json"}}else{type="text"}}if(type==="xml"){schema._type="xml";ds=this.context._processXmlResponse(data,true,this.context)}else if(type==="json"){if(schema){schema._type="json"}if($.type(data)==="string"){rawData=JSON.parse(data)}else{rawData=data}returnString=true;ds=this.context._processJsonResponse(rawData,this.context)}else{if($.fn.jquery){ver=$.fn.jquery.split(".")}if(ver&&ver.length>=2){if(parseInt(ver[1],10)>4||parseInt(ver[0],10)>1){this.dataTypes=[];this.dataTypes.push("text");returnString=true}}data=$.type(data)==="string"?$.trim(data):data;if(data&&$.type(data)==="string"&&(data.startsWith("<?xml")||data.startsWith("<"))||t==="xml"){if(schema){schema._type="xml"}ds=this.context._processXmlResponse(this.context.stringToXmlObject(data),false,this.context)}else if(data&&$.type(data)==="string"&&data.startsWith("[")||(t==="json"||t==="array")){if(schema){schema._type="json"}ds=this.context._processJsonResponse(JSON.parse(data),this.context)}else if(data&&$.type(data)==="string"&&data.startsWith("{")||t==="json"){if(schema){schema._type="json"}ds=this.context._processJsonResponse(JSON.parse(data),this.context)}else if($.isXMLDoc(data)){if(schema){schema._type="xml"}ds=this.context._processXmlResponse(data,true,this.context)}else if(data!==""&&data!==null){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedResponseType"))}}if(returnString){if(!(this.context.settings.paging&&this.context.settings.paging.enabled&&this.context.settings.paging.appendPage)){this.context._data=ds}this.context._alreadySet=true}return ds},_successCallback:function(data){var x,len=data?data.length:0;if((data===undefined||data===null)&&!this._alreadySet){this._data=[];this._dataView=[]}else{if(this._data.length>=0&&this.settings.paging&&this.settings.paging.enabled&&this.settings.paging.appendPage){for(x=0;x<len;++x){this._data[this._data.length]=data[x]}}else{if(this._alreadySet){this._dataView=this._data}else{this._data=data;this._dataView=data}}}this._alreadySet=false;this._populateTransformedData();this._isPagingReq=false;this._isFilteringReq=false;this._isSortingReq=false;this._isSummariesReq=false},_errorCallback:function(req,status,error){var f=this._customCallback||this.settings.callback,errmsg,statusMsg;this._isPagingReq=false;this._isFilteringReq=false;this._isSortingReq=false;this._isSummariesReq=false;if(req&&req.status&&req.statusText){statusMsg=" ( "+req.status+" "+req.statusText+" ) ";if(req.status===200&&error!==undefined){statusMsg=" ( "+(error.message||error)+" ) "}}else if(status!==null){statusMsg=" ( "+status+" ) "}else if(error!==undefined){statusMsg=" ( "+(error.message||error)+" ) "}errmsg=$.ig.util.getLocaleValue("DataSourceLocale","errorRemoteRequest")+statusMsg;if(f&&this._callee){f.apply(this._callee,[false,errmsg,req,this])}else if(f){f(false,errmsg,req,this)}},_completeCallback:function(){var f,callee,s=this.settings.sorting,p=this.settings.paging,filtering=this.settings.filtering;if(filtering.type==="local"&&filtering.defaultFields.length>0){this.filter(filtering.defaultFields)}if(s.type==="local"&&s.defaultFields.length>0){this.sort(s.defaultFields,s.defaultDirection)}else if(this.isGroupByApplied(s.expressions)){this._generateGroupByData(this._filter?this._filteredData:this._data,s.expressions)}if(p.enabled&&p.type==="local"){this._page()}this._internalDataBound(true);f=this._customCallback||this.settings.callback;callee=this._callee||this.settings.callee;if(f&&callee){f.apply(callee,[true,"",this])}else if(f){f(true,"",this)}},_processRequest:function(options){var o,s;if(this.settings.responseDataType==="jsonp"){o={dataType:"jsonp",type:"GET",url:options.url,data:options.data,success:$.proxy(this._jsonpFilter,this),error:$.proxy(this._errorCallback,this)};s=this.settings;if(s.jsonp!==undefined&&s.jsonp!==null){o.jsonp=this.settings.jsonp}if(s.jsonpCallback!==undefined){o.jsonpCallback=this.settings.jsonpCallback}this._ajaxRequest=$.ajax(o)}else{this._ajaxRequest=$.ajax(options)}},_jsonpFilter:function(data){var resp,x;this.context=this;resp=this._dataFilter(data,"json");if(!resp.length&&$.type(resp)==="object"){resp=[resp]}if(this._data.length>=0&&this.settings.paging&&this.settings.paging.enabled&&this.settings.paging.appendPage){for(x=0;x<resp.length;++x){this._data[this._data.length]=resp[x]}}else{this._data=resp;this._dataView=resp}this._populateTransformedData();this._completeCallback()},_processJsonResponse:function(data,context){var ds,schema=context.schema(),resKey,resPath,i;if(this._responseData){this._responseData(data)}if(data.Metadata){this._metadata=data.Metadata}if(schema&&schema.fields&&schema.fields().length>0&&this.settings.localSchemaTransform){ds=schema.transform(data)}else{resKey=context.settings.responseDataKey;if(resKey!==null&&resKey!==undefined){resPath=resKey.split(".");if(resPath.length>0){ds=data;for(i=0;i<resPath.length;i++){ds=ds[resPath[i]]}if(typeof ds==="string"){ds=JSON.parse(ds)}}else{ds=data}}else{ds=data}}if(context._isPagingReq||context._isFilteringReq){this.totalRecordsCount(null,this.settings.responseTotalRecCountKey,data,context)}this.summariesResponse(this.settings.summaries.summariesResponseKey,data);return ds},_processXmlResponse:function(data,isParsed,context){var ds,schema=context.schema(),tmpSchema,resKey;if(schema&&schema.fields&&schema.fields().length>0){ds=this.settings.localSchemaTransform?schema.transform(data):data}else{resKey=context.settings.responseDataKey;if(resKey&&resKey!==""){tmpSchema=new $.ig.DataSchema;ds=context._xmlToArray(tmpSchema._findXmlRecordsRoot(data,resKey))}else{ds=context._xmlToArray(data)}}return ds},_xmlToArray:function(data){var ds=[],root=data,i,r,j,name,val,o;o=window.ActiveXObject;if(data&&data.childNodes&&data.childNodes.length===1){root=data.childNodes[0]}for(i=0;i<root.childNodes.length;i++){r=root.childNodes[i];ds[i]=[];for(j=0;j<r.childNodes.length;j++){name=o===undefined?r.childNodes[j].localName:r.childNodes[j].baseName;val=o===undefined?r.childNodes[j].textContent:r.childNodes[j].text;ds[i][name]=val}}return ds},_encodeUrl:function(){var props=this.settings,sParams={},fParams={},pParams={},params,selParams={},sumParams={},extraParams={},pkParams={},noCancel=true;params={sortingParams:sParams,filteringParams:fParams,pagingParams:pParams,selectParams:selParams,summariesParams:sumParams,extraParams:extraParams,pkParams:pkParams};if($.isFunction(props.urlParamsEncoding)){noCancel=props.urlParamsEncoding(this,params)}if(noCancel){this._encodeSelectParams(params);this._encodeSortingParams(params);this._encodeFilteringParams(params);this._encodePagingParams(params);this._encodeSummariesParams(params);this._encodePkParams(params);if($.isFunction(this.settings.encodeExtraParams)){this.settings.encodeExtraParams(this,params)}if($.isFunction(props.urlParamsEncoded)){props.urlParamsEncoded(this,params)}}return $.extend(true,{},params.sortingParams,params.filteringParams,params.pagingParams,params.selectParams,params.summariesParams,params.extraParams,params.pkParams)},_encodePkParams:function(params){var p=this.settings.paging,s=this.settings.sorting,f=this.settings.filtering,sm=this.settings.summaries,pk=this._schema?this._schema._pk:null;if(pk&&(p.enabled&&p.type==="remote"||(s.type==="remote"||f.type==="remote"||sm.type==="remote"))){params.pkParams.pk=pk}},_encodeSelectParams:function(params){var selParams=params.selectParams,i;if(!this.settings.localSchemaTransform&&this.schema()&&this.schema().fields().length>0){selParams.$select="";for(i=0;i<this.schema().fields().length;i++){if(i!==0){selParams.$select+=","}selParams.$select+=this.schema().fields()[i].name}}else if(!this.settings.localSchemaTransform&&this.schema()&&this.schema().fields().length===0){selParams.$select="*"}},_encodePagingParams:function(params){var p=this.settings.paging;if(p.enabled&&p.type==="remote"){this._isPagingReq=true;if(p.pageIndexUrlKey!==null&&p.pageSizeUrlKey!==null){params.pagingParams[p.pageIndexUrlKey]=this.pageIndex();params.pagingParams[p.pageSizeUrlKey]=this.pageSize()}else{params.pagingParams.$skip=this.pageIndex()*this.pageSize();params.pagingParams.$top=this.pageSize();params.pagingParams.$inlinecount="allpages";if(this.settings.responseTotalRecCountKey===null){this.settings.responseTotalRecCountKey="d.__count"}}}},_encodeSortingParams:function(params){var s=this.settings.sorting,tmpdir,i,sfields,fieldName,field,url,urlQS,key,hlayout=null;if(s.type==="remote"){if(s.exprString){sfields=this._parseSortExpressions(s.exprString)}else{sfields=s.expressions}this._isSortingReq=true;for(i=0;i<sfields.length;i++){if(sfields[i].layout){hlayout=sfields[i].layout}fieldName=sfields[i].fieldName;if(s.sortUrlAscValueKey!==null&&s.sortUrlDescValueKey!==null&&s.sortUrlKey!==null){tmpdir=sfields[i].dir&&sfields[i].dir.toLowerCase().startsWith("asc")?s.sortUrlAscValueKey:s.sortUrlDescValueKey;field=this._getSchemaField(fieldName);if(field&&field.type){key=s.sortUrlKey+"("+fieldName+":"+field.type+")"}else{key=s.sortUrlKey+"("+fieldName+")"}params.sortingParams[key]=tmpdir}else{if(params.sortingParams.$orderby===undefined){params.sortingParams.$orderby=""}params.sortingParams.$orderby=params.sortingParams.$orderby+fieldName+" "+sfields[i].dir.toLowerCase();if(i<sfields.length-1){params.sortingParams.$orderby+=","}}}if(hlayout){url=this.settings.dataSource;if(url&&$.type(url)==="string"&&url.indexOf("layout="+hlayout)>=0){url=url.substr(url.indexOf("?")+1);urlQS=url.split("&");for(i=0;i<urlQS.length;i++){if(urlQS[i].indexOf("layout=")>=0){if(urlQS[i].replace("layout=","")===hlayout){hlayout=null}break}}}if(hlayout){params.sortingParams.layout=hlayout}}}},_encodeFilteringParams:function(params){var f=this.settings.filtering,ffields,i,key,exprNotReq,cond,d,day,month,year,curDate,expr,fieldName,field,logic="and";if(f.type==="remote"){if(f.exprString){ffields=this._parseFilterExprString(f.exprString)}else{ffields=f.expressions}for(i=0;i<ffields.length;i++){this._isFilteringReq=true;cond=ffields[i].cond;fieldName=ffields[i].fieldName;exprNotReq=this._isFilteringExprNotReq(cond);if(f.filterExprUrlKey!==null){field=this._getSchemaField(fieldName);if(field&&field.type){key=f.filterExprUrlKey+"("+fieldName+":"+field.type+")"}else{key=f.filterExprUrlKey+"("+fieldName+")"}if($.type(ffields[i].expr)==="date"){d=Date.UTC(ffields[i].expr.getFullYear(),ffields[i].expr.getMonth(),ffields[i].expr.getDate(),ffields[i].expr.getHours(),ffields[i].expr.getMinutes())}else{d=encodeURIComponent(ffields[i].expr)}if(params.filteringParams[key]===undefined){params.filteringParams[key]=ffields[i].cond+"("+(exprNotReq?"":d)+")"}else{params.filteringParams[key]=params.filteringParams[key]+","+ffields[i].cond+"("+(exprNotReq?"":d)+")"}}else{if(params.filteringParams.$filter===undefined){params.filteringParams.$filter=""}expr=ffields[i].expr;if($.type(expr)==="string"){if(!f.caseSensitive){fieldName="tolower("+fieldName+")";expr=expr.toLowerCase()}expr=expr.replace(/\'/g,"''")}if(ffields[i].cond==="startsWith"){params.filteringParams.$filter+="startswith("+fieldName+","+"'"+expr+"') eq true"}else if(ffields[i].cond==="endsWith"){params.filteringParams.$filter+="endswith("+fieldName+","+"'"+expr+"') eq true"}else if(ffields[i].cond==="contains"){params.filteringParams.$filter+="indexof("+fieldName+","+"'"+expr+"') ge 0"}else if(ffields[i].cond==="doesNotContain"){params.filteringParams.$filter+="indexof("+fieldName+","+"'"+expr+"') eq -1"}else if(ffields[i].cond==="equals"){if($.type(ffields[i].expr)==="string"){params.filteringParams.$filter+=fieldName+" eq "+"'"+expr+"'"}else{params.filteringParams.$filter+=ffields[i].fieldName+" eq "+ffields[i].expr}}else if(ffields[i].cond==="true"){params.filteringParams.$filter+=ffields[i].fieldName+" eq true"}else if(ffields[i].cond==="false"){params.filteringParams.$filter+=ffields[i].fieldName+" eq false"}else if(ffields[i].cond==="doesNotEqual"){if($.type(ffields[i].expr)==="string"){params.filteringParams.$filter+=fieldName+" ne "+"'"+expr+"'"}else{params.filteringParams.$filter+=ffields[i].fieldName+" ne "+ffields[i].expr}}else if(ffields[i].cond==="greaterThan"){params.filteringParams.$filter+=ffields[i].fieldName+" gt "+ffields[i].expr}else if(ffields[i].cond==="lessThan"){params.filteringParams.$filter+=ffields[i].fieldName+" lt "+ffields[i].expr}else if(ffields[i].cond==="greaterThanOrEqualTo"){params.filteringParams.$filter+=ffields[i].fieldName+" ge "+ffields[i].expr}else if(ffields[i].cond==="lessThanOrEqualTo"){params.filteringParams.$filter+=ffields[i].fieldName+" le "+ffields[i].expr}else if(ffields[i].cond==="null"){params.filteringParams.$filter+=ffields[i].fieldName+" eq null"}else if(ffields[i].cond==="notNull"){params.filteringParams.$filter+=ffields[i].fieldName+" ne null"}else if(ffields[i].cond==="empty"){params.filteringParams.$filter+="length("+ffields[i].fieldName+") eq 0"}else if(ffields[i].cond==="notEmpty"){params.filteringParams.$filter+="length("+ffields[i].fieldName+") gt 0"}else if(ffields[i].cond==="on"){expr=this._parser.toDate(ffields[i].expr);year=expr.getFullYear();month=expr.getMonth()+1;day=expr.getDate();params.filteringParams.$filter+="day("+ffields[i].fieldName+") eq "+day+" and ";params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="notOn"){expr=this._parser.toDate(ffields[i].expr);year=expr.getFullYear();month=expr.getMonth()+1;day=expr.getDate();params.filteringParams.$filter+="day("+ffields[i].fieldName+") ne "+day+" or ";params.filteringParams.$filter+="month("+ffields[i].fieldName+") ne "+month+" or ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") ne "+year}else if(ffields[i].cond==="after"){expr=this._parser.toDate(ffields[i].expr);params.filteringParams.$filter+=ffields[i].fieldName+" gt DateTime'"+$.ig.formatter(expr,"date","yyyy-MM-ddT23:59:59")+"'"}else if(ffields[i].cond==="before"){expr=this._parser.toDate(ffields[i].expr);params.filteringParams.$filter+=ffields[i].fieldName+" lt DateTime'"+$.ig.formatter(expr,"date","yyyy-MM-dd")+"'"}else if(ffields[i].cond==="today"){expr=this._parser.toDate(ffields[i].expr);year=expr.getFullYear();month=expr.getMonth()+1;day=expr.getDate();params.filteringParams.$filter+="day("+ffields[i].fieldName+") eq "+day+" and ";params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="yesterday"){expr=this._parser.toDate(ffields[i].expr);year=expr.getFullYear();month=expr.getMonth()+1;day=expr.getDate();params.filteringParams.$filter+="day("+ffields[i].fieldName+") eq "+day+" and ";params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="thisMonth"){curDate=new Date;month=curDate.getMonth()+1;year=curDate.getFullYear();params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="lastMonth"){curDate=new Date;month=curDate.getMonth()+1;year=curDate.getFullYear();if(month===1){month=12;year--}else{month--}params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="nextMonth"){curDate=new Date;month=curDate.getMonth()+1;year=curDate.getFullYear();if(month===12){month=1;year++}else{month++}params.filteringParams.$filter+="month("+ffields[i].fieldName+") eq "+month+" and ";params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="thisYear"){curDate=new Date;year=curDate.getFullYear();params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="lastYear"){curDate=new Date;year=curDate.getFullYear()-1;params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}else if(ffields[i].cond==="nextYear"){curDate=new Date;year=curDate.getFullYear()+1;params.filteringParams.$filter+="year("+ffields[i].fieldName+") eq "+year}logic="and";if(ffields[i].logic&&ffields[i].logic.toLowerCase()==="or"){logic="or"}if(i<ffields.length-1){params.filteringParams.$filter+=" "+logic+" "}}}if(f.filterLogicUrlKey!==null&&ffields.length>0){params.filteringParams[f.filterLogicUrlKey]=ffields[0].logic}}},_encodeSummariesParams:function(params){var i,j,s=this.settings.summaries,cs=s.columnSettings,methodsStr,field,key,fieldName,csLength=cs.length;if(s.type==="remote"){if(!csLength&&s.calculateAll){params.summariesParams[s.summaryExprUrlKey+"(all)"]="*"}for(i=0;i<csLength;i++){methodsStr="";if(cs[i].summaryOperands===undefined||cs[i].summaryOperands===null){continue}for(j=0;j<cs[i].summaryOperands.length;j++){if(cs[i].summaryOperands[j].active===true||cs[i].summaryOperands[j].active===1){methodsStr+=cs[i].summaryOperands[j].type+","}}if(methodsStr!==""){fieldName=cs[i].columnKey;field=this._getSchemaField(fieldName);if(field&&field.type){key=s.summaryExprUrlKey+"("+fieldName+":"+field.type+")"}else{key=s.summaryExprUrlKey+"("+fieldName+")"}params.summariesParams[key]=methodsStr.slice(0,-1)}}}},_getSchemaField:function(fieldName){var i,field;if(this.settings.schema){for(i=0;i<this.settings.schema.fields.length;i++){field=this.settings.schema.fields[i];if(field.name===fieldName){return field}}}return null},filteredData:function(){return this._filteredData},_page:function(keepRecords){var count=0,data;if(keepRecords===undefined){keepRecords=false}if(keepRecords){count=this._dataView.length}else{this._dataView=[]}data=this._filter?this._filteredData:this._data;this._generatePageData(data,count)},_getPageStartEndIndex:function(data){var startIndex=this.pageIndex()*this.pageSize(),endIndex;if(startIndex>=data.length){this.settings.paging.pageIndex=0;startIndex=this.pageIndex()*this.pageSize()}endIndex=startIndex+this.pageSize()>=data.length?data.length:startIndex+this.pageSize();return{startIndex:startIndex,endIndex:endIndex}},_generateGroupByPageDataForAllRecords:function(){var i,data=this.visibleGroupByData(),sgb=this.settings.groupby||{},metadata=this._getPageStartEndIndex(data),startIndex=metadata.startIndex,endIndex=metadata.endIndex;for(i=startIndex;i<endIndex;i++){this._gbDataView.push(data[i]);if(!data[i][sgb.groupRecordKey]&&!data[i][sgb.groupSummaryRecordKey]){this._dataView.push(data[i])}}},_generateGroupByPageDataForDataRecordsOnly:function(data){var i,rec,startIndex=0,parents=[],sgb=this.settings.groupby||{},visible=true,level=100,levelCollapsed,gbData=this.groupByData(),len=gbData.length,metadata=this._getPageStartEndIndex(data),startDataRec=data[metadata.startIndex],endDataRec=data[metadata.endIndex-1];for(i=0;i<len;i++){if(gbData[i]===startDataRec){startIndex=i;break}}for(i=startIndex-1;i>=0;i--){rec=gbData[i];if(rec[sgb.groupRecordKey]){if(level>rec.level){level=rec.level;parents.unshift(rec);this._gbDataView.unshift(rec);if(rec.collapsed){this._gbDataView=[rec];visible=false;levelCollapsed=level}if(!level){break}}}}for(i=startIndex;i<len;i++){rec=gbData[i];if(rec[sgb.groupRecordKey]){if(rec.level<=levelCollapsed||visible){levelCollapsed=rec.level;visible=!rec.collapsed;this._gbDataView.push(rec)}}else{this._dataView.push(rec);if(visible){this._gbDataView.push(rec)}if(rec===endDataRec){while(i++<len){rec=gbData[i];if(rec&&rec[sgb.groupSummaryRecordKey]){if(rec.level<=levelCollapsed||visible){this._gbDataView.push(rec)}}else{break}}break}}}},_generateGroupByPageData:function(data){this._dataView=[];this._gbDataView=[];return this.settings.groupby.pagingMode==="allRecords"?this._generateGroupByPageDataForAllRecords(data):this._generateGroupByPageDataForDataRecordsOnly(data)},_generatePageData:function(data,count){if(this.isGroupByApplied()){return this._generateGroupByPageData(data,count)}var i,metadata=this._getPageStartEndIndex(data),startIndex=metadata.startIndex,endIndex=metadata.endIndex;for(i=startIndex;i<endIndex;i++){this._dataView[count++]=data[i]}},_compareValues:function(x,y){if((x===null||x===undefined)&&(y===null||y===undefined)){return 0}if((x===null||x===undefined)&&y!==null&&y!==undefined){return-1}if(x!==null&&x!==undefined&&(y===null||y===undefined)){return 1}return x>y?1:x<y?-1:0},_sortByFieldExpression:function(data,f,direction,convertf){var arr=[],i,dataLen=data.length,reverse,sortF,caseSensitive=this.settings.sorting.caseSensitive,compareValFunc=f.compareFunc,rec,val,formatter=f.formatter,self=this,mapper=this._hasMapper,fieldType;if(f.dir!==undefined&&f.dir!==null){reverse=f.dir.toLowerCase().startsWith("desc");reverse=reverse?-1:1}else if(direction!==undefined&&direction!==null&&direction!==""){reverse=direction.toLowerCase().startsWith("desc");reverse=reverse?-1:1}fieldType=this._getFieldTypeFromSchema(f.fieldName);for(i=0;i<dataLen;i++){rec=data[i];val=mapper?self.getCellValue(f.fieldName,rec):rec[f.fieldName];if(formatter){val=formatter(val,f.fieldName)}if(convertf){val=convertf(val,f.fieldName)}if(caseSensitive===false&&val!==undefined&&val!==null&&val.toLowerCase){val=val.toLowerCase()}else if(val&&val.getTime){val=this._getDateAsNumber(val,fieldType)}arr.push({val:val,rec:rec})}sortF=function(){return function(obj1,obj2){var arr1,arr2,a=obj1.val,b=obj2.val,recordsData,recordsDataReverse;recordsData={fieldName:f.fieldName,recordX:obj1.rec,recordY:obj2.rec};recordsDataReverse={fieldName:f.fieldName,recordX:obj2.rec,recordY:obj1.rec};arr1=reverse*compareValFunc(a,b,recordsData);arr2=reverse*compareValFunc(b,a,recordsDataReverse);if(arr1<arr2){return-1}if(arr1>arr2){return 1}return 0}};arr=arr.sort(sortF());for(i=0;i<dataLen;i++){data[i]=arr[i].rec}return data},_getDateAsNumber:function(dateObject,fieldType){if(!dateObject||!dateObject.getTime){return dateObject}if(fieldType==="time"){return $.ig.Date.prototype.getTimeOfDay(dateObject)}return dateObject.getTime()},_resetDateObjectToCurrentDate:function(dateObject){if(!dateObject||!dateObject.getTime){return dateObject}var currentDate=new Date;var result=new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),dateObject.getHours(),dateObject.getMinutes(),dateObject.getSeconds(),dateObject.getMilliseconds());return result},_sortDataRecursive:function(data,fields,fieldIndex,defSortDir,convertFunc){var i,j,len=data.length,expr,gbExpr,gbData,gbDataLen,fieldsLen=fields.length;fieldIndex=fieldIndex||0;if(fieldIndex>fieldsLen-1||len<=1){return data}expr=fields[fieldIndex];data=this._sortByFieldExpression(data,expr,defSortDir,convertFunc);if(fieldIndex>=fieldsLen-1){return data}for(i=0;i<len;i++){gbExpr=fields[fieldIndex];gbData=this._groupedRecordsByExpr(data,i,expr);gbDataLen=gbData.length;if(gbDataLen>1&&fieldIndex+1<fieldsLen){gbData=this._sortDataRecursive(gbData,fields,fieldIndex+1,defSortDir,convertFunc)}for(j=0;j<gbDataLen;j++){data[i+j]=gbData[j]}i+=gbDataLen-1}return data},sort:function(fields,direction){var i,s=this.settings.sorting,convertFunc,isGb,p=this.settings.paging,data,resetPaging=false;if($.type(fields)==="string"){fields=this._parseSortExpressions(fields)}if(fields===undefined||fields===null){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","noSortingFields"))}fields=this._findSortingExpressionsForLayout(fields,this.settings.key);isGb=this.isGroupByApplied(fields);if(s.applyToAllData&&s.type==="local"){if(this._filter&&(p.type==="local"&&p.enabled===true||p.enabled===false||p.type==="remote"&&p.enabled===true&&this.settings.filtering.type==="local")){data=this._filteredData}else{data=this.data()}resetPaging=true}else{data=this.dataView()}if($.type(s.customFunc)==="function"){data=s.customFunc(data,fields,direction)}else{if(!direction){direction=""}if($.isFunction(s.customConvertFunc)){convertFunc=s.customConvertFunc}if($.type(fields)==="string"){fields=this._parseSortExpressions(fields)}if(fields.length>0){for(i=0;i<fields.length;i++){if(fields[i].compareFunc){if(typeof fields[i].compareFunc==="string"&&typeof window[fields[i].compareFunc]==="function"){fields[i].compareFunc=window[fields[i].compareFunc]}}if(typeof fields[i].compareFunc!=="function"){fields[i].compareFunc=this._compareValues}}this._allDataSorted=data===this.data();if(data.length>1){if($.type(s.compareFunc)==="function"){data.sort(s.compareFunc(fields,this.settings.schema,direction.toLowerCase().startsWith("asc")?false:true,convertFunc))}else{data=this._sortDataRecursive(data,fields,0,direction,convertFunc)}}}}if(isGb){this._generateGroupByData(data,fields)}if(resetPaging){if(!this._filter){this._data=data}else{this._filteredData=data}}if(resetPaging&&p.type==="local"){this._page()}else{this._dataView=data}this._populateTransformedData(data);return this},clearLocalSorting:function(){var s=this.settings.sorting,p=this.settings.paging,data,resetPaging=false;if(s.applyToAllData&&s.type==="local"){if(this._filter&&(p.type==="local"&&p.enabled===true||p.enabled===false)){data=this._filteredData}else{data=this.data()}resetPaging=true}else{data=this.dataView()}if(resetPaging&&p.type==="local"){if(!this._filter){this._data=data}else{this._filteredData=data}this._page()}else{this._dataView=data}this._populateTransformedData();return this},_parseSortExpressions:function(s){var fields=[],tmp,tmp2,i;tmp=s.split(",");for(i=0;i<tmp.length;i++){fields[i]={};tmp2=$.trim(tmp[i]).split(" ");fields[i].fieldName=tmp2[0];fields[i].dir=tmp2[1]}return fields},_splitFilterExpression:function(search){var matches=search.match(/\"[^\"]+\"/g)||[],res=[],i;for(i=0;i<matches.length;i++){search=search.replace(matches[i],"");res.push(matches[i].replace(/\"/g,""))}matches=search.split(/\s+/);res=res.concat(matches);return res},_filterAllFields:function(val,data,fields){fields=fields||this.schema().fields();if(!fields||!fields.length){return[]}var i,j,len=data.length,filteredData=[],count=0,curr,formattedRecords=(this.schema()||{})._formattedRecords||[],push,searchExprs=this._splitFilterExpression(val),se=[];for(i=0;i<searchExprs.length;i++){curr=searchExprs[i];if(curr){push=true;for(j=0;j<se.length;j++){if(se[j]===curr||se[j].indexOf(curr)!==-1){push=false;break}if(curr.indexOf(se[j])!==-1){se.splice(j,1);j=-1}}if(push){se.push(this.settings.filtering.caseSensitive?curr:curr.toLowerCase())}}}if(!se.length){return data}for(i=0;i<len;i++){if(this._findMatchByFields(se,data[i],fields,formattedRecords[i]||null)){filteredData[count++]=data[i]}}return filteredData},_findMatchByFields:function(searchTokens,rec,fields,formattedRecord){var j,fl=fields.length,dataVal,fieldName,i,ignoreCase=!this.settings.filtering.caseSensitive,s="";for(j=0;j<fl;j++){fieldName=fields[j].name;if(formattedRecord&&formattedRecord[fieldName]!==undefined){dataVal=formattedRecord[fieldName]}else{dataVal=this._hasMapper?this.getCellValue(fieldName,rec):rec[fieldName]}dataVal=dataVal===null||dataVal===undefined?"":dataVal;s+=dataVal+"||"}s=ignoreCase?s.toLowerCase():s;for(i=0;i<searchTokens.length;i++){if(s.indexOf(searchTokens[i])===-1){return false}}return true},_getFieldsWithFormatter:function(){var i,f,res=[];if(!this.schema()){return res}f=this.schema().fields();for(i=0;i<f.length;i++){if(f[i].formatter){res.push(f[i])}}return res},_generateFormattedRecords:function(data){var i,j,f,len,fr=[],schema=this.schema(),fields=this._getFieldsWithFormatter(),fieldsLen=fields.length;data=data||this._data;len=data.length;if(!len||!schema||!fieldsLen){return}for(i=0;i<len;i++){fr[i]={};for(j=0;j<fieldsLen;j++){f=fields[j];fr[i][f.name]=f.formatter(data[i][f.name],data[i],f)}}schema._formattedRecords=fr},filterByText:function(expression,fields){fields=fields||this.schema().fields();return this.filter([{filterAllFields:true,expr:expression,fields:fields}])},filter:function(fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings){var i,j,expr=null,count=0,skipRec=false,data,t,k,schema,fields,field,tmpbool,resetPaging,allFieldsExpr,f=this.settings.filtering,p=this.settings.paging,s=this.settings.sorting;this._clearGroupByData();schema=this.schema();if(schema===null||schema===undefined){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","filteringNoSchema"))}if($.type(fieldExpressions)==="string"){expr=fieldExpressions}if($.type(fieldExpressionsOnStrings)==="string"){allFieldsExpr=fieldExpressionsOnStrings}else if($.type(fieldExpressionsOnStrings)==="undefined"){fieldExpressionsOnStrings=[]}if($.type(fieldExpressions)==="array"&&fieldExpressions.length===0&&$.type(fieldExpressionsOnStrings)==="array"&&fieldExpressionsOnStrings.length===0){
return}if(f.applyToAllData&&f.type==="local"){data=this.data();resetPaging=true}else{if(this._cachedDataView&&this._cachedDataView.length>0){data=this._cachedDataView}else{this._cachedDataView=$.merge([],this.dataView());data=this._cachedDataView}}if($.type(f.customFunc)==="function"){data=f.customFunc(fieldExpressions,data);this._filteredData=data;this._dataView=[]}else if(fieldExpressions&&fieldExpressions.length&&fieldExpressions[0]&&fieldExpressions[0].filterAllFields){data=this._filterAllFields(fieldExpressions[0].expr,data,fieldExpressions[0].fields||schema.fields());this._filteredData=data;this._dataView=[]}else{this._dataView=[];this._filteredData=[];if(expr){fieldExpressions=this._parseFilterExprString(expr)}if(allFieldsExpr){fieldExpressionsOnStrings=this._parseFilterExprString(allFieldsExpr)}for(i=0;i<data.length;i++){skipRec=false;for(j=0;j<fieldExpressions.length;j++){fields=schema.fields();if(fieldExpressions[j].fieldIndex!==undefined&&fieldExpressions[j].fieldIndex<fields.length){field=fields[fieldExpressions[j].fieldIndex];t=field.type;skipRec=!this._findMatch(data[i][field.name],fieldExpressions[j].expr,t,!f.caseSensitive,fieldExpressions[j].cond,fieldExpressions[j].preciseDateFormat,field.name,data[i])}else{if(fieldExpressions[j].dataType!==undefined&&fieldExpressions[j].dataType!==null){t=fieldExpressions[j].dataType}else{t=this._getFieldTypeFromSchema(fieldExpressions[j].fieldName)}skipRec=!this._findMatch(data[i][fieldExpressions[j].fieldName],fieldExpressions[j].expr,t,!f.caseSensitive,fieldExpressions[j].cond,fieldExpressions[j].preciseDateFormat,fieldExpressions[j].fieldName,data[i])}tmpbool=fieldExpressions[j].logic!==null&&fieldExpressions[j].logic!==undefined&&(fieldExpressions[j].logic.toLowerCase()==="or"||fieldExpressions[j].logic.toLowerCase()==="and")?fieldExpressions[j].logic:boolLogic;if(tmpbool===undefined||tmpbool===null||$.type(tmpbool)!=="string"){tmpbool="and"}if(skipRec&&tmpbool.toLowerCase()==="and"){break}else if(!skipRec&&tmpbool.toLowerCase()==="or"){break}}if(!skipRec){for(j=0;j<fieldExpressionsOnStrings.length;j++){fields=schema.fields();t=undefined;if(fieldExpressionsOnStrings[j].fieldIndex){if(fieldExpressionsOnStrings[j].fieldIndex<fields.length){t=fields[fieldExpressionsOnStrings[j].fieldIndex].type}skipRec=!this._findMatch(data[i][fieldExpressionsOnStrings[j].fieldIndex],fieldExpressionsOnStrings[j].expr,"string",!f.caseSensitive,fieldExpressionsOnStrings[j].cond,fieldExpressionsOnStrings[j].preciseDateFormat,fieldExpressionsOnStrings[j].fieldName,data[i])}else{for(k=0;k<fields.length;k++){if(fields[k].name===fieldExpressionsOnStrings[j].fieldName){t=fields[k].type;break}}skipRec=!this._findMatch(data[i][fieldExpressionsOnStrings[j].fieldName],fieldExpressionsOnStrings[j].expr,"string",!f.caseSensitive,fieldExpressionsOnStrings[j].cond,fieldExpressionsOnStrings[j].preciseDateFormat,fieldExpressionsOnStrings[j].fieldName,data[i])}tmpbool=fieldExpressionsOnStrings[j].logic!==null&&fieldExpressionsOnStrings[j].logic!==undefined&&(fieldExpressionsOnStrings[j].logic.toLowerCase()==="or"||fieldExpressionsOnStrings[j].logic.toLowerCase()==="and")?fieldExpressionsOnStrings[j].logic:boolLogic;if(tmpbool===undefined||tmpbool===null||$.type(tmpbool)!=="string"){tmpbool="and"}if(skipRec&&tmpbool.toLowerCase()==="and"){break}else if(!skipRec&&tmpbool.toLowerCase()==="or"){break}}}if(!skipRec){this._filteredData[count++]=data[i]}}}this._filter=true;if(f.type==="local"&&s.type==="local"&&s.enabled&&s.expressions.length>0){this.sort(s.expressions)}if(resetPaging&&p.type==="local"&&p.enabled===true){if(this.persistedPageIndex()>0){this.settings.paging.pageIndex=this.persistedPageIndex()}else{this.settings.paging.pageIndex=0}this.pageSizeDirty(true);this._page();this.persistedPageIndex(null)}else if(!this._vgbData||!this._vgbData.length){if(this.isGroupByApplied()){this._generateGroupByData(this._filteredData,s.expressions)}for(i=0;i<this._filteredData.length;i++){this._dataView[i]=this._filteredData[i]}}this._populateTransformedData(this._filteredData);return this},clearLocalFilter:function(){var i,data,resetPaging,sa=false,f=this.settings.filtering,p=this.settings.paging,s=this.settings.sorting;this._clearGroupByData();if(f.applyToAllData&&f.type==="local"){data=this.data();resetPaging=true}else{if(this._cachedDataView&&this._cachedDataView.length>0){data=this._cachedDataView}else{this._cachedDataView=$.merge([],this.dataView());data=this._cachedDataView}}this._dataView=[];this._filteredData=data;if(s.type==="local"&&s.enabled&&s.expressions.length>0){this.sort(s.expressions);sa=true}if(resetPaging&&p.type==="local"&&p.enabled===true){this._filter=true;this.settings.paging.pageIndex=0;this.pageSizeDirty(true);this._page()}else{if(p.enabled===false){this._filter=true}if(!sa){if(this.isGroupByApplied()){this._generateGroupByData(this._filteredData,s.expressions)}for(i=0;i<this._filteredData.length;i++){this._dataView[i]=this._filteredData[i]}}}this._populateTransformedData(this._filteredData);return this},_parseFilterExprString:function(expr){var exprs=$.trim(expr).split(/(?=AND+)|(?=OR+)/i),i,j,fields=[],tmp,tmp2,isInvalid=true;for(i=0;i<exprs.length;i++){fields[i]={};tmp=$.trim(exprs[i]).split(/(?= \=+)|(?=<>+)|(?=>+)|(?=<+)|(?=LIKE+)|(?=NOT\WLIKE)+|(?=>\=+)|(?=<\=+)/);if($.trim(exprs[i]).toLowerCase().startsWith("and")){fields[i].logic="AND"}else if($.trim(exprs[i]).toLowerCase().startsWith("or")){fields[i].logic="OR"}if(i>0&&(fields[i].logic==="AND"||fields[i].logic==="OR")){fields[i-1].logic=fields[i].logic}if(tmp[0].toLowerCase().startsWith("and")||tmp[0].toLowerCase().startsWith("or")){fields[i].fieldName=$.trim(tmp[0].split(" ")[1])}else{fields[i].fieldName=$.trim(tmp[0])}tmp2=$.trim(tmp[1]).split(" ");if(exprs[i].indexOf("<>")!==-1){tmp2[0]="<>";tmp2[1]=tmp[2].replace(">","")}if(tmp2.length>2){for(j=2;j<tmp2.length;j++){tmp2[1]=tmp2[1]+" "+tmp2[j]}tmp2=[tmp2[0],tmp2[1]]}if(tmp[1].startsWith("NOT")){fields[i].expr=$.trim(tmp[2].replace("LIKE",""))}else{fields[i].expr=tmp2[1]}for(j=0;j<this.schema().schema.fields.length;j++){if(this.schema().schema.fields[j].name===fields[i].fieldName){isInvalid=false;break}}if(isInvalid){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","fieldMismatch")+fields[i].fieldName)}isInvalid=true;if(tmp2[0]===">"){fields[i].cond="greaterThan"}else if(tmp2[0]==="LIKE"){if(fields[i].expr.startsWith("%")&&fields[i].expr.endsWith("%")){fields[i].cond="contains"}else if(fields[i].expr.endsWith("%")){fields[i].cond="startsWith"}else if(fields[i].expr.startsWith("%")){fields[i].cond="endsWith"}else{fields[i].cond="equals"}fields[i].expr=fields[i].expr.replace(/%/g,"")}else if(tmp2[0]==="NOT LIKE"||tmp2[0]==="NOT"){if(fields[i].expr.startsWith("%")&&fields[i].expr.endsWith("%")){fields[i].cond="doesNotContain"}else{fields[i].cond="doesNotEqual"}fields[i].expr=fields[i].expr.replace(/%/g,"")}else if(tmp2[0]==="="){fields[i].cond="equals"}else if(tmp2[0]==="<>"){fields[i].cond="doesNotEqual"}else if(tmp2[0]==="<"){fields[i].cond="lessThan"}else if(tmp2[0]==="<="){fields[i].cond="lessThanOrEqualTo"}else if(tmp2[0]===">="){fields[i].cond="greaterThanOrEqualTo"}else{throw new Error($.ig.util.getLocaleValue("DataSourceLocale","unrecognizedCondition")+expr)}}return fields},_isFilteringExprNotReq:function(cond){return cond==="false"||cond==="true"||cond==="today"||cond==="yesterday"||cond==="thisMonth"||cond==="lastMonth"||cond==="nextMonth"||cond==="thisYear"||cond==="lastYear"||cond==="nextYear"||cond==="null"||cond==="notNull"||cond==="empty"||cond==="notEmpty"},_findMatch:function(val,expr,t,ignoreCase,cond,preciseDateFormat,colKey,rec){var tmpExpr,custConds=this.settings.filtering.customConditions,f,func,exprNotReq=this._isFilteringExprNotReq(cond);val=this.getCellValue(colKey,rec);if($.type(val)==="function"){val=val()}if(custConds&&(f=custConds[cond]||custConds[colKey+"_"+cond])){func=f.filterFunc;if($.type(func)==="function"){f=func}else if(window[func]&&typeof window[func]==="function"){f=window[func]}else{throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnexpectedCustomFilterFunction"))}return f(val,expr,t,ignoreCase,preciseDateFormat,colKey)}if(expr===""&&!exprNotReq){return true}tmpExpr=$.trim(expr);if(t==="regexp"||t==="string"&&tmpExpr.startsWith("/")&&tmpExpr.endsWith("/")){if(t==="regexp"){return this._findRegExpMatch(val,expr,false)}return this._findRegExpMatch(val,tmpExpr.substring(1,tmpExpr.length-1),true)}if($.type(val)==="date"&&(t===undefined||t===null)||t==="date"){try{expr=this._parser.toDate(expr)}catch(ignore){}return this._findDateMatch(val,expr,cond,preciseDateFormat)}if(t==="time"){try{expr=this._parser.toTime(expr)}catch(ignore){}return this._findTimeMatch(val,expr,cond)}if($.type(val)==="boolean"&&(t===undefined||t===null)||(t==="boolean"||t==="bool")){return this._findBoolMatch(val,cond)}if($.type(val)==="number"&&(t===undefined||t===null)||t==="number"){return this._findNumericMatch(val,expr,cond)}return this._findStringMatch(val,expr,ignoreCase,cond)},_findStringMatch:function(val,expr,ignoreCase,cond){var localVal;if(val!==null&&val!==undefined){localVal=ignoreCase?val.toString().toLowerCase():val||""}else{localVal=val}if(expr!==null&&expr!==undefined){expr=ignoreCase?expr.toString().toLowerCase():expr.toString()}if(cond==="startsWith"){return localVal!==null&&localVal!==undefined&&localVal.startsWith(expr)}if(cond==="endsWith"){return localVal!==null&&localVal!==undefined&&localVal.endsWith(expr)}if(cond==="contains"){return localVal!==null&&localVal!==undefined&&localVal.indexOf(expr)!==-1}if(cond==="doesNotContain"){return localVal!==null&&localVal!==undefined&&localVal.indexOf(expr)===-1}if(cond==="equals"){return localVal!==null&&localVal!==undefined&&localVal===expr}if(cond==="doesNotEqual"){return localVal!==null&&localVal!==undefined&&localVal!==expr}if(cond==="null"){return localVal===null}if(cond==="notNull"){return localVal!==null}if(cond==="empty"){return localVal===null||localVal===undefined||localVal.length===0}if(cond==="notEmpty"){return localVal===null||localVal===undefined||localVal.length!==0}throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedFilterCondition")+cond)},_findRegExpMatch:function(val,expr,str){if(str){return new RegExp(expr).test(val)}return val.match(expr)},_findNumericMatch:function(val,expr,cond){if($.type(expr)!=="number"){expr=this._parser.toNumber(expr)}if(cond==="equals"){return val===expr}if(cond==="doesNotEqual"){return val!==expr}if(cond==="greaterThan"){return val>expr}if(cond==="lessThan"){return val<expr}if(cond==="greaterThanOrEqualTo"){return val>=expr}if(cond==="lessThanOrEqualTo"){return val<=expr}if(cond==="null"){return val===null}if(cond==="notNull"){return val!==null}if(cond==="empty"){return val===null||val===undefined||isNaN(val)}if(cond==="notEmpty"){return val!==null&&val!==undefined&&!isNaN(val)}throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedFilterCondition")+cond)},_findBoolMatch:function(val,cond){if(cond==="true"){return val}if(cond==="false"){return!val}if(cond==="null"){return val===null}if(cond==="notNull"){return val!==null}if(cond==="empty"){return val===null||val===undefined}if(cond==="notEmpty"){return val!==null&&val!==undefined}throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedFilterCondition")+cond)},_getDateParts:function(date){if(!date||$.type(date)!=="date"){return null}var yrs,day,mdate,mins,hrs,month;if(this.settings.enableUTCDates){yrs=date.getUTCFullYear();month=date.getUTCMonth();day=date.getUTCDay();mdate=date.getUTCDate();hrs=date.getUTCHours();mins=date.getUTCMinutes()}else{yrs=date.getFullYear();month=date.getMonth();day=date.getDay();mdate=date.getDate();hrs=date.getHours();mins=date.getMinutes()}return{year:yrs,month:month,day:day,mdate:mdate,hours:hrs,mins:mins}},_findDateMatch:function(val,expr,cond,preciseDateFormat){var day1,mins1,hs1,yrs1,day2,mins2,hs2,yrs2,month1,month2,eq,cur,yrs3,month3,mday1,mday2,mday3,yesterday,onEq,valDateParts,exprDateParts;if(val!==null&&val!==undefined){valDateParts=this._getDateParts(val);day1=valDateParts.day;mday1=valDateParts.mdate;mins1=valDateParts.mins;hs1=valDateParts.hours;yrs1=valDateParts.year;month1=valDateParts.month}if($.type(expr)==="date"){exprDateParts=this._getDateParts(expr);day2=exprDateParts.day;mday2=exprDateParts.mdate;mins2=exprDateParts.mins;hs2=exprDateParts.hours;yrs2=exprDateParts.year;month2=exprDateParts.month}else{expr=new Date(expr)}cur=new Date;yesterday=new Date(cur.getTime());yesterday.setDate(yesterday.getDate()-1);mday3=cur.getDate();yrs3=cur.getFullYear();month3=cur.getMonth();eq=day1===day2&&mins1===mins2&&hs1===hs2&&yrs1===yrs2&&month1===month2;if(cond==="equals"){return eq}if(cond==="doesNotEqual"){return!eq}if(cond==="before"){return val<expr}if(cond==="after"){return val>expr}if(cond==="today"){return mday1===mday3&&month1===month3&&yrs1===yrs3}if(cond==="yesterday"){return yesterday.getDate()===mday1&&yesterday.getMonth()===month1&&yesterday.getFullYear()===yrs1}if(cond==="thisMonth"){return month1===month3&&yrs1===yrs3}if(cond==="lastMonth"){if(month3===0){return month1===11&&yrs1===yrs3-1}return month1===month3-1&&yrs1===yrs3}if(cond==="nextMonth"){if(month3===11){return month1===0&&yrs1===yrs3+1}return month1===month3+1&&yrs1===yrs3}if(cond==="thisYear"){return yrs1===yrs3}if(cond==="lastYear"){return yrs1===yrs3-1}if(cond==="nextYear"){return yrs1===yrs3+1}if(cond==="on"||cond==="notOn"){onEq=yrs1===yrs2&&month1===month2&&mday1===mday2;if(preciseDateFormat){if(preciseDateFormat.indexOf("m")>=0){onEq=onEq&&mins1===mins2}if(preciseDateFormat.indexOf("h")>=0||preciseDateFormat.indexOf("H")>=0){onEq=onEq&&hs1===hs2}if(preciseDateFormat.indexOf("s")>=0){onEq=onEq&&val.getSeconds()===expr.getSeconds()}if(preciseDateFormat.indexOf("f")>=0){onEq=onEq&&val.getMilliseconds()===expr.getMilliseconds()}}if(cond==="on"){return onEq}return!onEq}if(cond==="null"){return val===null}if(cond==="notNull"){return val!==null}if(cond==="empty"){return val===null||val===undefined}if(cond==="notEmpty"){return val!==null&&val!==undefined}throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedFilterCondition")+cond)},_findTimeMatch:function(val,expr,cond){var mins1,hs1,mins2,hs2,eq,valDateParts,exprDateParts;if(val!==null&&val!==undefined){valDateParts=this._getDateParts(val);hs1=valDateParts.hours;mins1=valDateParts.mins}if($.type(expr)==="date"){exprDateParts=this._getDateParts(expr);hs2=exprDateParts.hours;mins2=exprDateParts.mins}else{expr=new Date(expr)}eq=mins1===mins2&&hs1===hs2;if(cond==="at"){return eq}if(cond==="notAt"){return!eq}if(cond==="before"){return hs1<hs2||hs1===hs2&&mins1<mins2}if(cond==="after"){return hs1>hs2||hs1===hs2&&mins1>mins2}if(cond==="atBefore"){return hs1<hs2||hs1===hs2&&mins1<=mins2}if(cond==="atAfter"){return hs1>hs2||hs1===hs2&&mins1>=mins2}if(cond==="null"){return val===null}if(cond==="notNull"){return val!==null}if(cond==="empty"){return val===null||val===undefined}if(cond==="notEmpty"){return val!==null&&val!==undefined}throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorUnrecognizedFilterCondition")+cond)},totalRecordsCount:function(count,key,dsObj,context){var rec,totalRecPath,i;if(context!==undefined&&context!==null){if(key){rec=dsObj;if(rec.hasOwnProperty(key)){rec=rec[key]}else{totalRecPath=key.split(".");for(i=0;i<totalRecPath.length;i++){rec=rec[totalRecPath[i]]}}if(dsObj&&rec!==undefined&&rec!==null){if($.type(rec)==="number"){this._recCount=rec}else{this._recCount=parseInt(rec,10)}this.hasTotalRecordsCount(true)}else{this.hasTotalRecordsCount(false)}}else{this.hasTotalRecordsCount(false)}}else if(count!==undefined&&count!==null){this._recCount=count}return this._recCount},hasTotalRecordsCount:function(hasCount){if(hasCount===undefined||hasCount===null){return this._hasCount}this._hasCount=hasCount},metadata:function(key){if(key===null||key===undefined||key===""||this._metadata===null||this._metadata===undefined){return this._metadata}return this._metadata[key]},totalLocalRecordsCount:function(){if(this.isGroupByApplied()&&this._vgbData&&this.settings.groupby.pagingMode==="allRecords"){return this._vgbData.length}if(!this._filter){return this._data.length}return this._dataView.length},pageCount:function(){var c,realCount;if(this.isGroupByApplied()&&this._vgbData&&this.settings.groupby.pagingMode==="allRecords"){realCount=this._vgbData.length}else if(!this._filter){realCount=this.totalRecordsCount()>0?this.totalRecordsCount():this._data.length}else{realCount=this.totalRecordsCount()>0?this.totalRecordsCount():this._filteredData.length}c=Math.ceil(realCount/this.settings.paging.pageSize);return c===0?1:c},pageIndex:function(index){if(index===undefined||index===null){return this.settings.paging.pageIndex===undefined?0:this.settings.paging.pageIndex}this.settings.paging.pageIndex=parseInt(index,10);this._cachedDataView=null;if(this.settings.paging.type==="local"){this._page(this.settings.paging.appendPage);this._invokeCallback()}else{this.dataBind()}return this},persistedPageIndex:function(value){if(value===undefined){return this.settings.paging._persistedPageIndex}else{this.settings.paging._persistedPageIndex=value}},prevPage:function(){this.pageIndex(this.pageIndex()===0?0:this.pageIndex()-1);return this},nextPage:function(){if(this.pageIndex()>=this.pageCount()-1){return this}this.pageIndex(this.pageIndex()+1);return this},pageSize:function(s){if(s===undefined||s===null){return this.settings.paging.pageSize}this.settings.paging.pageSize=parseInt(s,10);if(this.settings.paging.appendPage){this.settings.paging.pageIndex=0;this._cachedDataView=null}if(this.settings.paging.type==="local"){this._page();this._invokeCallback()}else{this.dataBind()}return this},pageSizeDirty:function(dirty){if(dirty===undefined||dirty===null){return this._dirty}this._dirty=dirty},recordsForPage:function(p){var d=[],si,ps,ei,i,c=0;ps=this.pageSize();si=p*ps;ei=si+ps>=this._data.length?this._data.length:si+ps;for(i=si;i<ei;i++){d[c++]=this._data[i]}return d},tableToObject:function(tableDOM){try{var rows=$(tableDOM).children("tbody").children(),len,data,i,j;len=rows.length>0?rows[0].cells.length:0;data=[];for(i=0;i<rows.length;i++){data[i]=[];for(j=0;j<len;j++){data[i][j]=rows[i].cells[j].innerHTML}}return data}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingHtmlTableNoSchema")+e.message)}},_validateTable:function(obj){if(obj.length===0){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorTableWithIdNotFound")+this.dataSource())}else{return obj[0]}},stringToJSONObject:function(s){var data={};try{data=JSON.parse(s)}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingJsonNoSchema")+e.message)}return data},stringToXmlObject:function(s){var doc,parser;try{if(window.ActiveXObject){doc=new ActiveXObject("Microsoft.XMLDOM");doc.async="false";doc.loadXML(s)}else{parser=new DOMParser;doc=parser.parseFromString(s,"text/xml")}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingXmlNoSchema")+e.message)}return doc},groupByData:function(){return this._gbData},visibleGroupByData:function(){return this._vgbData},groupByDataView:function(){return this._gbDataView},_groupedRecordsByExpr:function(data,startInd,gbExpr,gbRes){var i,res=[],cmpRes,groupval,currval,mapper=this._hasMapper,cmpFunc=gbExpr.compareFunc,key=gbExpr.fieldName,len=data.length,fieldType=this._getFieldTypeFromSchema(gbExpr.fieldName);gbRes=gbRes||{};if(!cmpFunc){cmpFunc=function(val1,val2){return val1===val2}}startInd=startInd||0;res.push(data[startInd]);groupval=mapper?this.getCellValue(key,data[startInd]):data[startInd][key];if(groupval&&groupval.getTime){gbRes.val=this._getDateAsNumber(groupval,fieldType)}else{gbRes.val=groupval}startInd++;for(i=startInd;i<len;i++){currval=mapper?this.getCellValue(key,data[i]):data[i][key];if(currval&&currval.getTime){currval=this._getDateAsNumber(currval,fieldType)}cmpRes=cmpFunc(currval,gbRes.val,{fieldName:key,recordX:data[startInd],recordY:data[i]});if(cmpRes===0||cmpRes===true){res.push(data[i])}else{break}}return res},toggleGroupByRecord:function(id,collapsed){var ds=this._gbData,i,len=ds.length,res=[],lvl,row,hidden,gbrow,p=this.settings.paging,gbSumRow,sgb=this.settings.groupby||{};this._gbCollapsed=this._gbCollapsed||{};this._gbCollapsed[id]=!!collapsed;for(i=0;i<len;i++){row=ds[i];gbrow=row[sgb.groupRecordKey];gbSumRow=row[sgb.groupSummaryRecordKey];if(gbrow&&row.id===id){row.collapsed=!!collapsed}if(hidden){if((gbrow||gbSumRow)&&row.level<=lvl){hidden=false}else{continue}}if(gbrow&&row.collapsed){hidden=true;lvl=row.level}else{lvl=null}res.push(row)}this._vgbData=res;this._gbDataView=this._vgbData;if(p.enabled&&p.type==="local"){this._page()}if(sgb.recordToggledCallback){$.ig.util.invokeCallback(sgb.recordToggledCallback,[id,collapsed])}},isGroupByRecordCollapsed:function(gbRec){var id=typeof gbRec==="string"||!gbRec?gbRec:gbRec.id,state;this._gbCollapsed=this._gbCollapsed||{};state=this._gbCollapsed[id];return state===undefined?this.settings.groupby.defaultCollapseState:state},_resetGroupByCollapseStates:function(){this._gbCollapsed={}},_processGroupsRecursive:function(data,gbExprs,gbInd,parentCollapsed,parentId){var i,j,hc,len=data.length,resLen,gbExpr,res,gbRec,groupRecordKey=this.settings.groupby.groupRecordKey,summaries=this.settings.groupby.summaries;gbInd=gbInd||0;parentId=parentId||"";if(!gbInd||!this._gbData){this._gbData=[];this._vgbData=[]}for(i=0;i<len;i++){gbExpr=gbExprs[gbInd];gbRec={gbExpr:gbExpr,level:gbInd,len:1,recs:[],val:undefined};gbRec[groupRecordKey]=true;this._gbData.push(gbRec);if(!parentCollapsed){this._vgbData.push(gbRec)}res=this._groupedRecordsByExpr(data,i,gbExpr,gbRec);gbRec.fieldName=gbExpr.fieldName;resLen=res.length;hc=gbRec.val?String(gbRec.val).getHashCode():"";gbRec.id=parentId+gbExpr.fieldName+":"+hc;gbRec.collapsed=this.isGroupByRecordCollapsed(gbRec);if(gbInd+1<gbExprs.length){this._processGroupsRecursive(res,gbExprs,gbInd+1,gbRec.collapsed||parentCollapsed,gbRec.id+":")}else{for(j=0;j<resLen;j++){this._gbData.push(res[j]);if(!gbRec.collapsed&&!parentCollapsed){this._vgbData.push(res[j])}}}gbRec.recs=res;gbRec.len=resLen;if(summaries&&summaries.length>0){this._calculateGroupBySummaries(gbRec,parentCollapsed)}i+=resLen-1}},_calculateGroupBySummaries:function(gbRec,parentCollapsed){var res=gbRec.recs,gbSummaryRec={summaries:{},level:gbRec.level+1,groupValue:gbRec.val,id:gbRec.id},fieldValues,i,j,sumFunc,summaries=this.settings.groupby.summaries,sumFuncName,summary,summaryVal,fieldType,getValuesPerField,self=this;gbSummaryRec[this.settings.groupby.groupSummaryRecordKey]=true;getValuesPerField=function(arr,fieldName,fieldType){if(fieldType==="time"){return arr.map(function(val){return self._resetDateObjectToCurrentDate(val[fieldName])})}return arr.map(function(val){return val[fieldName]})};for(i=0;i<summaries.length;i++){summary=summaries[i];fieldType=this._getFieldTypeFromSchema(summary.field);fieldValues=getValuesPerField(res,summary.field,fieldType);for(j=0;j<summary.summaryFunctions.length;j++){sumFunc=summary.summaryFunctions[j];sumFuncName=typeof sumFunc==="string"?sumFunc:"custom";summaryVal=$.ig.calcSummaries(sumFuncName,fieldValues,sumFunc,fieldType,res);if(!gbSummaryRec.summaries[summary.field]){gbSummaryRec.summaries[summary.field]=[]}gbSummaryRec.summaries[summary.field].push(summaryVal)}}this._addSummaryRecToArray(gbSummaryRec,gbRec,this._gbData);if(!gbRec.collapsed&&!parentCollapsed){this._addSummaryRecToArray(gbSummaryRec,gbRec,this._vgbData)}},_addSummaryRecToArray:function(gbSummaryRec,gbRec,array){var index;if(this.settings.groupby.summariesPosition==="bottom"||this.settings.groupby.summariesPosition==="both"){gbSummaryRec.position="bottom";array.push($.extend({},gbSummaryRec))}if(this.settings.groupby.summariesPosition==="top"||this.settings.groupby.summariesPosition==="both"){index=array.indexOf(gbRec);gbSummaryRec.position="top";array.splice(index+1,0,$.extend({},gbSummaryRec))}},_generateGroupByData:function(data,gbExprs,collapsedRows){var i,newgb=[],gbs=this.settings.groupby||{};data=data||this._data;gbExprs=this._findSortingExpressionsForLayout(gbExprs||[],this.settings.key);this._gbData=[];this._vgbData=[];this._gbDataView=[];this._gbCollapsed=collapsedRows||this._gbCollapsed;if($.type(gbExprs)!=="array"||!gbExprs.length){return data}for(i=0;i<gbExprs.length;i++){if(gbExprs[i].isGroupBy){newgb.push(gbExprs[i])}}gbExprs=newgb;if(!gbExprs.length){return data}this._processGroupsRecursive(data,gbExprs,0,false,"");this._gbDataView=this._vgbData;if(gbs.dataGeneratedCallback){$.ig.util.invokeCallback(gbs.dataGeneratedCallback)}return this.groupByData()},_clearGroupByData:function(){this._gbData=[];this._vgbData=[];this._gbDataView=[]},isGroupByApplied:function(exprs){exprs=this._findSortingExpressionsForLayout(exprs||this.settings.sorting.expressions,this.settings.key);return!!(exprs&&exprs.length&&exprs[0].isGroupBy)},_findSortingExpressionsForLayout:function(expressions,layout){return(expressions||[]).filter(function(expr){return!expr.layout&&!layout||expr.layout===layout})}});$.ig.TypeParser=$.ig.TypeParser||Class.extend({toStr:function(obj){return this.isNullOrUndefined(obj)?"":obj+this.empty()},toDate:function(obj){if(this.isNullOrUndefined(obj)||obj===""||$.type(obj)==="function"){return null}if($.type(obj)==="date"){return obj}var d;d=new Date(obj);if(isNaN(d)){d=$.ig.util.dateFromISO(obj)}return d},toTime:function(obj){if(this.isNullOrUndefined(obj)||obj===""||$.type(obj)==="function"){return null}if($.type(obj)==="date"){return obj}var d=new Date;var result=new Date(d.toDateString()+" "+obj);if(isNaN(result)){return null}return result},toNumber:function(obj){return this.isNullOrUndefined(obj)||$.type(obj)==="function"?null:obj*this.num()},toBool:function(obj){var typeObj=$.type(obj);if(typeObj==="boolean"){return obj}if(this.isNullOrUndefined(obj)||typeObj==="function"){return false}if(obj==="1"||obj===1||typeObj==="string"&&obj.toLowerCase()==="true"){return true}return false},isNullOrUndefined:function(obj){return obj===null||obj===undefined},empty:function(){return""},num:function(){return 1}});$.ig.DataSchema=$.ig.DataSchema||Class.extend({schema:{fields:[{name:undefined,type:undefined,xpath:undefined,mapper:undefined,formatter:undefined}],searchField:null,outputResultsName:null,childDataProperty:null},init:function(type,options){$.ig.DataSchema.prototype.schema.fields=[];if(options){this.schema=$.extend(true,{},$.ig.DataSchema.prototype.schema,options)}this._type=type;this._parser=new $.ig.TypeParser;this._parser._serverOffset=0},transform:function(data){var ndata=[];switch(this._type){case"array":ndata=this._arrays(data);break;case"json":ndata=this._json(data);break;case"xml":ndata=this._xml(data);break;case"htmlTableDom":ndata=this._table(data);break;case"htmlListDom":ndata=this._list(data);break;case"htmlSelectDom":ndata=this._select(data);break;case"singleRow":ndata=this._row(data);break;default:throw new Error("unknown data source type: "+this._type)}return ndata},_setResKey:function(resKey,out){if(!this.isEmpty(resKey)){out[resKey]=[];return out[resKey]}return out},_convertType:function(t,obj){if(t==="string"){return this._parser.toStr(obj)}if(t==="date"||t==="time"){return this._parser.toDate(obj)}if(t==="number"){return this._parser.toNumber(obj)}if(t==="boolean"||t==="bool"){return this._parser.toBool(obj)}return obj},_val:function(field,val,results,i,rec){var t=field.type,j=null;if(!this.isEmpty(t)){if(this.isEmpty(field.name)){results[i][j]=this._convertType(t,val)}else{results[i][field.name]=this._convertType(t,val);if(t==="date"||t==="time"){this._addOffset(results[i],field.name,i)}}}else{if(this.isEmpty(field.name)){if(rec){results[i][j]=rec[i][j]}else{results[i][j]=val}}else{if(rec){results[i][field.name]=rec[i][field.name]}else{results[i][field.name]=val}}}if(field.formatter){this._formattedRecords=this._formattedRecords||[];this._formattedRecords[i]=this._formattedRecords[i]||{};this._formattedRecords[i][field.name]=field.formatter(results[i][field.name],results[i],field)}},_addOffset:function(result,fieldName,i){var id=this._pk?result[this._pk]:i;if(this._serverOffsets&&this._serverOffsets[id]&&!this.isEmpty(this._serverOffsets[id][fieldName])){result["igoffset_"+fieldName]=this._serverOffsets[id][fieldName]}},isEmpty:function(o){return o===undefined||o===null||o===""},_row:function(dataRow,index){var t,j,f,tmp,schema=this.schema,fields=schema.fields,fLen=fields.length,fName,nDataRow={};for(j=0;j<fLen;j++){f=fields[j];fName=f.name;tmp=dataRow[fName];t=f.type;if(!this.isEmpty(t)){if(this.isEmpty(fName)){nDataRow[j]=this._convertType(t,tmp)}else{nDataRow[fName]=this._convertType(t,tmp);if(t==="date"||t==="time"){this._addOffset(nDataRow,fName,index)}}}else{if(this.isEmpty(fName)){nDataRow[j]=tmp}else{nDataRow[fName]=tmp}}}return nDataRow},_arrays:function(data){var i,j,tmp,hasArrays,resKey=this.schema.outputResultsName,out={},results;results=this._setResKey(resKey,out);if(this.isObjEmpty(results)&&$.type(results)!=="array"){results=[];out=results}try{if(data.length>0){hasArrays=$.type(data[0])==="array"}for(i=0;i<data.length;i++){if(data[i]===undefined){continue}results.push({});for(j=0;j<this.schema.fields.length;j++){if(hasArrays){tmp=data[i][j]}else{tmp=data[i][this.schema.fields[j].name]}this._val(this.schema.fields[j],tmp,results,results.length-1)}}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingArrays")+e.message)}return out},_getDataBySearchField:function(data){var searchPath,i,token,root;if(!this.isEmpty(this.schema.searchField)){searchPath=this.schema.searchField.split(/[\[.\]]/);for(i=0;i<searchPath.length;i++){token=searchPath[i];if(token.length===0){continue}token=/^(0|[1-9]\d*)$/.test(token)?parseInt(token,10):token.replace(/^('|")|('|")$/g,"");root=root?root[token]:data[token];if(root===undefined||root===null){break}}if(!root&&$.type(data)==="array"){root=data}}return root},_processMetadata:function(data){if(data.Metadata&&data.Metadata.timezoneOffset!==undefined&&!isNaN(data.Metadata.timezoneOffset)){this._serverOffset=data.Metadata.timezoneOffset;this._parser._serverOffset=this._serverOffset;if(data.Metadata.timezoneOffsets){this._serverOffsets=data.Metadata.timezoneOffsets;this._parser._serverOffsets=data.Metadata.timezoneOffsets}}else{this._parser._serverOffset=0}},_json:function(data){var i,j,root,resKey=this.schema.outputResultsName,out={},results;results=this._setResKey(resKey,out);if(this.isObjEmpty(results)){results=[];out=results}try{this._processMetadata(data);root=this._getDataBySearchField(data);if(root===undefined||this.isEmpty(this.schema.searchField)){root=data}if(!root.length&&$.type(root)==="object"){root=[root]}if(root&&root.length&&root.length>0){for(i=0;i<root.length;i++){results[i]={};if(this._pk&&this._pk!=="ig_pk"){for(j=0;j<this.schema.fields.length;j++){if(this.schema.fields[j].name===this._pk){break}}if(j<this.schema.fields.length){if(root[i][this._pk]===undefined){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorSchemaMismatch")+this._pk)}this._val(this.schema.fields[j],root[i][this.schema.fields[j].name],results,i,root)}}for(j=0;j<this.schema.fields.length;j++){if(this.schema.fields[j].name!=="ig_pk"&&this.schema.fields[j].name!==this._pk){this._val(this.schema.fields[j],root[i][this.schema.fields[j].name],results,i,root)}}}}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingJson")+e.message)}return out},_xml:function(data,recursiveSF){var i,j,root,resNode,item,resKey=this.schema.outputResultsName,out={},results,namespaced,sf,k,r,rc,len1,len2,o,carrysf,ireal=0,s;o=window.ActiveXObject;results=this._setResKey(resKey,out);if(this.isObjEmpty(results)){results=[];out=results}try{if(!this.isEmpty(this.schema.searchField)){namespaced=this._xmlHasNamespaces(data);if(!namespaced){if(window.ActiveXObject===undefined){
if(!recursiveSF||recursiveSF.length<=0){root=data.evaluate(this.schema.searchField,data,null,XPathResult.ANY_TYPE,null)}else{root=data.evaluate(recursiveSF,data,null,XPathResult.ANY_TYPE,null)}}else{if(!(data instanceof ActiveXObject)){s=(new XMLSerializer).serializeToString(data);data=new window.ActiveXObject("Microsoft.XMLDOM");data.async=false;data.loadXML(s)}root=data.selectNodes(this.schema.searchField)}}else{if(this.schema.searchField.startsWith("//")){sf=this.schema.searchField.substring(2,this.schema.searchField.length)}else{sf=this.schema.searchField}root=this._findXmlRecordsRoot(data,sf)}}else{root=data}if(!namespaced){if(root&&window.ActiveXObject!==undefined){for(i=0;i<root.length;i++){item=root.item(i);results[i]={};for(j=0;j<this.schema.fields.length;j++){resNode=item.selectSingleNode(this.schema.fields[j].xpath);if(resNode){if(resNode.nodeType===1&&this.schema.childDataProperty&&resNode.nodeName===this.schema.childDataProperty){this.schema.searchField=this.schema.childDataProperty;results[i][resNode.nodeName]=this._xml(item)}else{this._val(this.schema.fields[j],resNode.text,results,i)}}else{results[i][this.schema.fields[j].name]=""}}}}else if(root){i=0;item=root.iterateNext();while(item){results[i]={};for(j=0;j<this.schema.fields.length;j++){resNode=data.evaluate(this.schema.fields[j].xpath,item,null,XPathResult.ANY_TYPE,null).iterateNext();if(resNode){if(resNode.nodeType===1&&this.schema.childDataProperty&&(resNode.nodeName===this.schema.childDataProperty||resNode.nodeName===this.schema.seachField)){if(!recursiveSF||recursiveSF.length<=0){carrysf=this.schema.searchField+"["+(i+1)+"]/"+this.schema.childDataProperty}else{carrysf=recursiveSF+"["+(i+1)+"]/"+this.schema.childDataProperty}results[i][this.schema.childDataProperty]=this._xml(data,carrysf)}else{this._val(this.schema.fields[j],resNode.textContent,results,i)}}else{results[i][this.schema.fields[j].name]=""}}i++;item=root.iterateNext()}}}else{len1=root.childNodes.length;ireal=0;for(i=0;i<len1;i++){r=root.childNodes[i];results.push({});for(j=0;j<this.schema.fields.length;j++){len2=r.childNodes.length;for(k=0;k<len2;k++){rc=r.childNodes[k];if(this.schema.fields[j].name===(o===undefined?rc.localName:rc.baseName)){this._val(this.schema.fields[j],o===undefined?rc.textContent:rc.text,results,ireal);break}}}if($.isEmptyObject(results[ireal])){results.pop()}else{ireal++}}}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale",".errorParsingXml")+e.message)}return out},_findXmlRecordsRoot:function(data,field){var i,len,r,o,ret;o=window.ActiveXObject;if((o===undefined?data.localName:data.baseName)===field){ret=data.parentNode}else if(data&&data.childNodes&&data.childNodes.length>0){len=data.childNodes.length;for(i=0;i<len;i++){r=data.childNodes[i];if(r.childNodes&&r.childNodes.length>0){ret=this._findXmlRecordsRoot(r,field)}}}return ret},_xmlHasNamespaces:function(data){var i,ns,r,len,fc;if(data.childNodes&&data.childNodes.length&&data.childNodes.length>0){len=data.childNodes.length;for(i=0;i<len;i++){r=data.childNodes[i];if(!r){return false}ns=r.namespaceURI;if(ns!==""&&ns!==undefined&&ns!==null){return true}}if(r&&r.childNodes&&r.childNodes.length>0){fc=r.childNodes[0];if(!fc){return false}ns=fc.namespaceURI;return ns!==""&&ns!==undefined&&ns!==null}}return false},_table:function(data){var i,j,r,tbody,rows,resKey=this.schema.outputResultsName,out={},results;tbody=$(data).find("tbody")[0];results=this._setResKey(resKey,out);if(this.isObjEmpty(results)){results=[];out=results}try{if(tbody&&tbody.nodeName&&tbody.nodeName==="TBODY"){rows=tbody.rows;for(i=0;i<rows.length;i++){r=rows[i];results[i]={};for(j=0;j<this.schema.fields.length;j++){this._val(this.schema.fields[j],r.cells[j].innerHTML,results,i)}}}else{throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorExpectedTbodyParameter"))}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingHtmlTable")+e.message)}return out},_list:function(data){var parsedData,img,anchor,id,li,ul,self=this,d=$(data),text,i,header,descriptions,counts,jqmNS="data-";if($.mobile&&$.mobile.ns){jqmNS+=$.mobile.ns}parsedData=[];if(d&&(d.is("ul")||d.is("ol"))&&d.children().length>0){d.children("li:not(["+jqmNS+'role="itemTemplate"], ['+jqmNS+'role="detailsTemplate"], ['+jqmNS+'role="dividerTemplate"])').each(function(index){li=$(this);img=li.children("img");parsedData[index]={};if(self.schema.hasOwnProperty("primaryKey")){self._val(self.schema.primaryKey,li.index(),parsedData,index)}if(self.schema.hasOwnProperty("isDivider")){self._val(self.schema.isDivider,li.attr(jqmNS+"role")==="list-divider",parsedData,index)}if(img.length>0&&img.attr("src")){if(self.schema.hasOwnProperty("imageUrl")){self._val(self.schema.imageUrl,img.attr("src"),parsedData,index)}}anchor=li.children("a");if(anchor.length>0){text=anchor.html();if(anchor.attr("href")){if(self.schema.hasOwnProperty("navigateUrl")){self._val(self.schema.navigateUrl,anchor.attr("href"),parsedData,index)}}if(anchor.attr("target")){if(self.schema.hasOwnProperty("target")){self._val(self.schema.target,anchor.attr("target"),parsedData,index)}}if(img.length===0){img=anchor.children("img");if(img.length>0){img.each(function(){if(this.outerHTML){text=text.replace(this.outerHTML,"")}else{text=text.replace($("<div>").append(this).html(),"")}})}if(img.length>0&&img.attr("src")){if(self.schema.hasOwnProperty("imageUrl")){self._val(self.schema.imageUrl,img.attr("src"),parsedData,index)}}}}else{text="";for(i=0;i<li[0].childNodes.length;i++){if(li[0].childNodes[i].nodeType===3&&li[0].childNodes[i].data){text+=$.trim(li[0].childNodes[i].data)}}}if(self.schema.hasOwnProperty("header")){header=li.children("h1, h2, h3, h4, h5, h6");if(header.length===0&&anchor.length>0){header=anchor.children("h1, h2, h3, h4, h5, h6")}if(header.length>0){self._val(self.schema.header,header.text(),parsedData,index);header.each(function(){if(this.outerHTML){text=text.replace(this.outerHTML,"")}else{text=text.replace($("<div>").append(this).html(),"")}})}}if(self.schema.hasOwnProperty("description")){descriptions=li.children("p, dd");if(descriptions.length===0&&anchor.length>0){descriptions=anchor.children("p, dd")}if(descriptions.length>0){self._val(self.schema.description,descriptions.text(),parsedData,index);descriptions.each(function(){if(this.outerHTML){text=text.replace(this.outerHTML,"")}else{text=text.replace($("<div>").append(this).html(),"")}})}}if(self.schema.hasOwnProperty("count")){counts=li.children("span.ui-li-count");if(counts.length===0&&anchor.length>0){counts=anchor.children("span.ui-li-count")}if(counts.length>0){self._val(self.schema.count,parseInt(counts.text(),10),parsedData,index);counts.each(function(){if(this.outerHTML){text=text.replace(this.outerHTML,"")}else{text=text.replace($("<div>").append(this).html(),"")}})}}if(self.schema.hasOwnProperty("text")){self._val(self.schema.text,text,parsedData,index)}id=li.attr("id");if(id){if(self.schema.hasOwnProperty("value")){self._val(self.schema.value,id,parsedData,index)}}ul=li.children("ul, ol");if(ul.length>0){if(self.schema.hasOwnProperty("childData")&&self.schema.childData.hasOwnProperty("name")){parsedData[index][self.schema.childData.name]=self._list(ul)}}})}return parsedData},_select:function(data){var parsedData=[],self=this;$(data).children().each(function(i){var $curOption=$(this);parsedData[i]={};if($curOption.is("optgroup")){parsedData[i].Group={groupName:this.label,groupItems:self._select(this)}}else{self._val(self.schema.fields[0],$curOption.val(),parsedData,i);self._val(self.schema.fields[1],$curOption.text(),parsedData,i)}});return parsedData},isObjEmpty:function(obj){var prop;for(prop in obj){if(obj.hasOwnProperty(prop)){return false}}return true},fields:function(){return this.schema.fields}});$.ig.RemoteDataSource=$.ig.RemoteDataSource||$.ig.DataSource.extend({init:function(options){if(!options){options={}}options.type="remoteUrl";this._super(options);return this}});$.ig.JSONDataSource=$.ig.JSONDataSource||$.ig.DataSource.extend({settings:{type:"json"},init:function(options){if(!options){options={}}options.type="json";this._super(options);return this}});$.ig.RESTDataSource=$.ig.RESTDataSource||$.ig.DataSource.extend({settings:{restSettings:{create:{url:null,template:null,batch:false},update:{url:null,template:null,batch:false},remove:{url:null,template:null,batch:false},encodeRemoveInRequestUri:true,contentSerializer:null,contentType:"application/json; charset=utf-8"}},init:function(options){if(!options){options={}}else{this._defaultTypeOverridden=options.restSettings&&options.restSettings.contentType&&options.restSettings.contentType!==this.settings.restSettings.contentType}options.restSettings=$.extend(true,this.settings.restSettings,options.restSettings);this._createHttpHandlers();this._createLogVerbMapping();this._setLazyUrls();this._super(options);return this},saveChanges:function(success,error){var log,verb,batchOps={POST:[],PUT:[],DELETE:[],CELL:[]},i;this._asyncCallbackCount=0;this._isc=success&&typeof success==="function"?success:null;this._iec=error&&typeof error==="function"?error:null;for(i=0;i<this._accumulatedTransactionLog.length;i++){log=this._accumulatedTransactionLog[i];verb=this._logVerbMap[log.type];if(log.type==="cell"){batchOps.CELL.push(log)}else if(this._isBatch(verb)===true){batchOps[verb].push(log)}else{this._asyncCallbackCount++;this._saveSingleChange(verb,log)}}if(batchOps.CELL.length>0){this._saveAllCellChanges(batchOps.CELL)}if(batchOps.POST.length>0){this._asyncCallbackCount++;this._saveAllCreateChanges(batchOps.POST)}if(batchOps.PUT.length>0){this._asyncCallbackCount++;this._saveAllUpdateChanges(batchOps.PUT)}if(batchOps.DELETE.length>0){this._asyncCallbackCount++;this._saveAllDeleteChanges(batchOps.DELETE)}},_saveSingleChange:function(verb,change){var data,url;data=verb==="POST"||verb==="PUT"?change.row:null;url=this._getProperUrl(verb,false,verb==="DELETE"||verb==="PUT"?change.rowId:undefined);this._call(verb,url,data)},_saveAllCellChanges:function(cellLogs){var i,combined={},rowLogs=[],cl;for(i=0;i<cellLogs.length;i++){cl=cellLogs[i];if(combined[cl.rowId]===undefined){combined[cl.rowId]={};combined[cl.rowId].row=this.findRecordByKey(cl.rowId)}combined[cl.rowId].row[cl.col]=cl.value}$.each(combined,function(key,value){value.rowId=key;rowLogs.push(value)});if(this._isBatch("PUT")===true){this._asyncCallbackCount++;this._saveAllUpdateChanges(rowLogs)}else{for(i=0;i<rowLogs.length;i++){this._asyncCallbackCount++;this._saveSingleChange("PUT",rowLogs[i])}}},_saveAllCreateChanges:function(createLogs){var data=[],i;for(i=0;i<createLogs.length;i++){data.push(createLogs[i].row)}this._call("POST",this._getProperUrl("POST",true),data)},_saveAllUpdateChanges:function(updateLogs){var data=[],urlParams="?",i;for(i=0;i<updateLogs.length;i++){data.push(updateLogs[i].row);urlParams+="index="+updateLogs[i].rowId+(i!==updateLogs.length-1?"&":"")}this._call("PUT",this._getProperUrl("PUT",true)+urlParams,data)},_saveAllDeleteChanges:function(deleteLogs){var urlParams="",i,data=null;if(this.settings.restSettings.encodeRemoveInRequestUri===true){urlParams="?";for(i=0;i<deleteLogs.length;i++){urlParams+="index="+deleteLogs[i].rowId+(i!==deleteLogs.length-1?"&":"")}}else{data=[];for(i=0;i<deleteLogs.length;i++){data.push(deleteLogs[i].rowId)}}this._call("DELETE",this._getProperUrl("DELETE",true)+urlParams,data)},_createHttpHandlers:function(){this._okHandler=$.proxy(this._responseOk,this);this._createdHandler=$.proxy(this._responseCreated,this);this._noContentHandler=$.proxy(this._responseNoContent,this);this._httpHandlers={POST:{201:this._createdHandler},PUT:{200:this._okHandler,201:this._createdHandler,204:this._noContentHandler},DELETE:{200:this._okHandler,204:this._noContentHandler}}},_createLogVerbMapping:function(){this._logVerbMap={newrow:"POST",row:"PUT",deleterow:"DELETE",cell:"PUT"}},_setLazyUrls:function(){var rs=this.settings.restSettings,tempUrl=null,tempTmpl=null;$.each(rs,function(key,value){if(value){if(value.url){tempUrl=value.url}if(value.template){tempTmpl=value.template}}});$.each(rs,function(key,value){if(value){if(value.url!==undefined&&value.url===null){value.url=tempUrl}if(value.template!==undefined&&value.template===null){value.template=tempTmpl}}});this._putUrl=rs.update.url;this._putTmpl=rs.update.template;this._postUrl=rs.create.url;this._postTmpl=rs.create.template;this._deleteUrl=rs.remove.url;this._deleteTmpl=rs.remove.template},_getProperUrl:function(verb,batch,id){var vL=verb.toLowerCase(),url=this["_"+vL+"Url"];if(url&&url.length>0&&url.substr(url.length-1)!=="/"){url+="/"}if(!batch||batch===false){if(this["_"+vL+"Tmpl"]!==null){url=this["_"+vL+"Tmpl"];if(id){url=url.replace("${id}",id)}}else{if(id){url+=id}}}return url},_responseOk:function(data,textStatus,jqXHR){this._asyncCallbackCount--;if(this._asyncCallbackCount===0){this._saveChangesSuccess({Success:textStatus==="success"},textStatus,jqXHR)}},_responseCreated:function(data,textStatus,jqXHR){this._asyncCallbackCount--;if(this._asyncCallbackCount===0){this._saveChangesSuccess({Success:textStatus==="success"},textStatus,jqXHR)}},_responseNoContent:function(data,textStatus,jqXHR){this._asyncCallbackCount--;if(this._asyncCallbackCount===0){this._saveChangesSuccess({Success:textStatus==="success"||textStatus==="nocontent"},textStatus,jqXHR)}},_isBatch:function(verb){switch(verb){case"POST":return this.settings.restSettings.create.batch;case"PUT":return this.settings.restSettings.update.batch;case"DELETE":return this.settings.restSettings.remove.batch;default:return false}},_call:function(verb,url,data){var dataString,ct=this.settings.restSettings.contentType,serializer=this.settings.restSettings.contentSerializer,self=this;if(serializer!==null){if(typeof serializer==="string"){serializer=window[serializer]}}if(data!==null){dataString=serializer!==null?serializer(data):JSON.stringify(data)}else{if(!this._defaultTypeOverridden){ct="text/plain"}dataString=""}this._ajaxRequest=$.ajax({type:verb,url:url,data:dataString,statusCode:this._httpHandlers[verb],contentType:ct,cache:false,success:function(data,textStatus,jqXHR){if(self._isc){self._isc(data,textStatus,jqXHR)}},error:function(jqXHR,textStatus,errorThrown){self._saveChangesError(jqXHR,textStatus,errorThrown);if(self._iec){self._iec(jqXHR,textStatus,errorThrown)}},processData:true})}});$.ig.JSONPDataSource=$.ig.JSONPDataSource||$.ig.DataSource.extend({settings:{jsonp:null,jsonpCallback:null,type:"json"},init:function(options){if(!options){options={}}options.responseDataType="jsonp";this._super(options);return this}});$.ig.XmlDataSource=$.ig.XmlDataSource||$.ig.DataSource.extend({init:function(options){if(!options){options={}}options.type="xml";this._super(options);return this}});$.ig.FunctionDataSource=$.ig.FunctionDataSource||$.ig.DataSource.extend({settings:{type:"function"},init:function(options){if(!options){options={}}options.type="function";this._super(options);return this}});$.ig.HtmlTableDataSource=$.ig.HtmlTableDataSource||$.ig.DataSource.extend({settings:{type:"htmlTableDom"},init:function(options){if(!options){options={}}options.type="htmlTableDom";this._super(options);return this}});$.ig.ArrayDataSource=$.ig.ArrayDataSource||$.ig.DataSource.extend({init:function(options){if(!options){options={}}options.type="array";this._super(options);return this}});$.ig.MashupDataSource=$.ig.MashupDataSource||$.ig.DataSource.extend({mashupSettings:{ignorePartialRecords:false,dataSource:[]},init:function(options){this._super(options);if(options){this.settings=$.extend(true,{},$.ig.DataSource.prototype.settings,options);this.settings=$.extend(true,{},$.ig.MashupDataSource.prototype.mashupSettings,this.settings)}this._sources=[];this._dataBindingComplete=false;this._sourcesStatus=[];this._hashedDataViews=[];return this},_checkDataBindingComplete:function(status,msg,ownerDs){var i,j,k,hasPrimaryKeys=true,hasForeignKeys=false,totalLength=0,data=[],merged=[],d,rindex=0,keyVal,prop,keyIndexHash,fkeyIndexHash,mergedData;this._dataBindingComplete=true;for(i=0;i<this._sources.length;i++){if(this._sources[i]===ownerDs){this._sourcesStatus[i]=1}if(this._sourcesStatus[i]===0){this._dataBindingComplete=false}}if(this._dataBindingComplete){for(i=0;i<this._sources.length;i++){if(this._sources[i].settings.primaryKey===""||this._sources[i].settings.primaryKey===null||this._sources[i].settings.primaryKey===undefined){hasPrimaryKeys=false;break}}for(i=0;i<this._sources.length;i++){if(this._sources[i].settings.foreignKey!==""&&this._sources[i].settings.foreignKey!==null&&this._sources[i].settings.foreignKey!==undefined){hasForeignKeys=true;break}}totalLength=this._sources[0].dataView().length;for(i=0;i<this._sources.length;i++){totalLength=this.settings.ignorePartialRecords?this._sources[i].dataView().length<totalLength?this._sources[i].dataView().length:totalLength:this._sources[i].dataView().length>totalLength?this._sources[i].dataView().length:totalLength}if(hasPrimaryKeys&&!hasForeignKeys){for(i=0;i<this._sources.length;i++){this._hashedDataViews[i]={};for(j=0;j<this._sources[i].dataView().length;j++){this._hashedDataViews[i][this._sources[i].dataView()[j][this._sources[i].settings.primaryKey]]=this._sources[i].dataView()[j]}}keyIndexHash={};j=0;for(i=0;i<this._hashedDataViews.length;i++){for(keyVal in this._hashedDataViews[i]){if(this._hashedDataViews[i].hasOwnProperty(keyVal)){if(keyIndexHash.hasOwnProperty(keyVal)){data[keyIndexHash[keyVal]]=$.extend(true,{},data[keyIndexHash[keyVal]],this._hashedDataViews[i][keyVal]);merged[keyIndexHash[keyVal]]++}else{data.push({});merged.push(1);data[j]=$.extend(true,{},data[j],this._hashedDataViews[i][keyVal]);keyIndexHash[keyVal]=j;j++}}}}if(this.settings.ignorePartialRecords){for(i=merged.length-1;i>=0;i--){if(merged[i]<this._sources.length){data.splice(i,1)}}}}else if(hasForeignKeys&&hasPrimaryKeys){for(i=0;i<this._sources.length;i++){this._hashedDataViews[i]={};for(j=0;j<this._sources[i].dataView().length;j++){this._hashedDataViews[i][this._sources[i].dataView()[j][this._sources[i].settings.primaryKey]]=this._sources[i].dataView()[j]}}keyIndexHash=[{}];fkeyIndexHash=[{}];for(i=0;i<this._hashedDataViews.length;i++){j=0;for(keyVal in this._hashedDataViews[0]){if(this._hashedDataViews[0].hasOwnProperty(keyVal)){if(!keyIndexHash[i]){keyIndexHash.push({})}if(!keyIndexHash[i].hasOwnProperty(keyVal)){keyIndexHash[i][keyVal]=j;j++;if(this._sources[i+1]&&this._sources[i+1].settings.foreignKey){if(!fkeyIndexHash[i]){fkeyIndexHash.push({})}fkeyIndexHash[i][keyVal]=this._hashedDataViews[0][keyVal][this._sources[i+1].settings.foreignKey]}}}}}mergedData=$.extend(true,{},data,this._hashedDataViews[0]);for(i=0;i<this._hashedDataViews.length;i++){if(this._sources[i].settings.foreignKey===null||this._sources[i].settings.foreignKey===undefined){continue}mergedData=this._mergeSources(this._hashedDataViews[i],this._sources[i].settings.foreignKey,fkeyIndexHash[i-1],mergedData)}j=0;for(var mergedRecKey in mergedData){data[j]=mergedData[mergedRecKey];j++}}else{for(i=0;i<totalLength;i++){data[i]={};rindex=0;for(j=0;j<this._sources.length;j++){d=this._sources[j];if(d.dataView()[0].length){for(k=0;k<d.dataView()[0].length;k++){data[i][rindex++]=i>=d.dataView().length?"":d.dataView()[i][k]}}else{for(prop in d.dataView()[i]){if(d.dataView()[i].hasOwnProperty(prop)){data[i][prop]=i>=d.dataView().length?"":d.dataView()[i][prop]}}}}}}this.settings.dataSource=data;this.settings.type="array";this._runtimeType=this.analyzeDataSource();this.dataBind()}},_mergeSources:function(dataView,fKey,fkeyIndex,data){var newObject={},fkValueCollection;for(var recID in data){if(Array.isArray(data[recID][fKey])){newObject={};fkValueCollection=data[recID][fKey];for(var fk in fkValueCollection){var currValue=dataView[fkValueCollection[fk]];for(var variable in currValue){if(variable!==fKey){if(newObject.hasOwnProperty(variable)){newObject[variable].push(currValue[variable])}else{newObject[variable]=[currValue[variable]]}}}}data[recID]=$.extend(true,{},data[recID],newObject)}else{data[recID]=$.extend(true,{},data[recID],dataView[fkeyIndex[recID]])}}return data},setCellValue:function(rowId,colId,val,autoCommit){var rowObject=this.findRecordByKey(rowId,this._data),t,rec,self=this,newObject,lookupRecord;$(this._sources).each(function(){if(this.settings.foreignKey&&this.settings.foreignKey===colId){if(Array.isArray(val)){newObject={};for(var value in val){lookupRecord=this.dataSource()[val[value]];for(var variable in lookupRecord){if(variable!==this.settings.foreignKey){if(newObject.hasOwnProperty(variable)){newObject[variable].push(lookupRecord[variable])}else{newObject[variable]=[lookupRecord[variable]]}}else{newObject[variable]=val}}}rowObject=$.extend(true,{},rowObject,newObject)}else if(this.settings.foreignKey===colId){rowObject=$.extend(true,{},rowObject,this.dataSource()[val])}if(this.settings.primaryKey===null){rec=self._data[parseInt(rowId,10)]}else{rec=self.findRecordByKey(rowId,self._data)}for(var prop in rec){rec[prop]=rowObject[prop]}}});t=this._createCellTransaction(rowId,colId,val);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}return t},updateRow:function(rowId,rowObject,autoCommit){var t,newObject,lookupRecord,oldRow=this.settings.primaryKey===null?this._data[parseInt(rowId,10)]:this.findRecordByKey(rowId),rowIndex=this.settings.primaryKey===null?rowId:$.ig.indexInArray(this._data,oldRow);$(this._sources).each(function(){if(this.settings.foreignKey){if(Array.isArray(rowObject[this.settings.foreignKey])){newObject={};for(var value in rowObject[this.settings.foreignKey]){lookupRecord=this.dataSource()[rowObject[this.settings.foreignKey][value]];for(var variable in lookupRecord){if(variable!==this.settings.foreignKey){if(newObject.hasOwnProperty(variable)){newObject[variable].push(lookupRecord[variable])}else{newObject[variable]=[lookupRecord[variable]]}}}}rowObject=$.extend(true,{},rowObject,newObject)}else if(rowObject[this.settings.foreignKey]!==oldRow[this.settings.foreignKey]){rowObject=$.extend(true,{},rowObject,this.dataSource()[rowObject[this.settings.foreignKey]])}}});t=this._createRowTransaction(rowId,rowObject);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowUpdated)==="function"){if(this.settings.callee){this.settings.rowUpdated.apply(this.settings.callee,[{rowIndex:rowIndex,newRow:rowObject,oldRow:oldRow},this])}else{this.settings.rowUpdated({rowIndex:rowIndex,newRow:rowObject,oldRow:oldRow},this)}}return t},addRow:function(rowId,rowObject,autoCommit){var t,newObject,lookupRecord;$(this._sources).each(function(){if(this.settings.foreignKey){if(Array.isArray(rowObject[this.settings.foreignKey])){newObject={};for(var value in rowObject[this.settings.foreignKey]){lookupRecord=this.dataSource()[rowObject[this.settings.foreignKey][value]];for(var variable in lookupRecord){if(variable!==this.settings.foreignKey){if(newObject.hasOwnProperty(variable)){newObject[variable].push(lookupRecord[variable])}else{newObject[variable]=[lookupRecord[variable]]}}}}rowObject=$.extend(true,{},rowObject,newObject)}else{rowObject=$.extend(true,{},rowObject,this.dataSource()[rowObject[this.settings.foreignKey]])}}});t=this._createNewRowTransaction(rowId,rowObject);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowAdded)==="function"){if(this.settings.callee){this.settings.rowAdded.apply(this.settings.callee,[{rowId:rowId,row:rowObject},this])}else{this.settings.rowAdded({rowId:rowId,row:rowObject},this)}}return t},insertRow:function(rowId,rowObject,rowIndex,autoCommit,parentRowId){var t,newObject,lookupRecord,oldRow;$(this._sources).each(function(){if(this.settings.foreignKey){if(Array.isArray(rowObject[this.settings.foreignKey])){newObject={};for(var value in rowObject[this.settings.foreignKey]){lookupRecord=this.dataSource()[rowObject[this.settings.foreignKey][value]];for(var variable in lookupRecord){if(variable!==this.settings.foreignKey){if(newObject.hasOwnProperty(variable)){newObject[variable].push(lookupRecord[variable])}else{newObject[variable]=[lookupRecord[variable]]}}}}rowObject=$.extend(true,{},rowObject,newObject)}else{rowObject=$.extend(true,{},rowObject,this.dataSource()[rowObject[this.settings.foreignKey]])}}});t=this._createInsertRowTransaction(rowId,rowObject,rowIndex);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowInserted)==="function"){if(this.settings.callee){this.settings.rowInserted.apply(this.settings.callee,[{rowId:rowId,row:rowObject,rowIndex:rowIndex},this])}else{this.settings.rowInserted({rowId:rowId,row:rowObject,rowIndex:rowIndex},this)}}return t},dataBind:function(){var i,ds=this.settings.dataSource;if(this._dataBindingComplete||this._sources.length>0){this._dataBindingComplete=false;this._super()}else{this._dataBindingComplete=false;for(i=0;i<ds.length;i++){if(ds[i]instanceof $.ig.DataSource){this._sources[i]=ds[i]}else if(ds[i].hasOwnProperty("dataSource")&&ds[i].dataSource instanceof $.ig.DataSource){this._sources[i]=ds[i].dataSource}else{this._sources[i]=new $.ig.DataSource(ds[i])}this._sources[i].settings.callee=this;this._sources[i].settings.callback=this._checkDataBindingComplete;this._sourcesStatus[i]=0}for(i=0;i<ds.length;i++){this._sources[i].dataBind()}}return this}});$.ig.HierarchicalDataSource=$.ig.HierarchicalDataSource||Class.extend({settings:{autogenerate:false,initialDataBindDepth:0,maxDataBindDepth:-1,defaultChildrenDataProperty:"children",callback:null,callee:null,data:[],dataSource:null,dataBinding:null,dataBound:null,type:"unknown",responseDataType:null,responseContentType:null,localSchemaTransform:true,urlParamsEncoding:null,urlParamsEncoded:null,requestType:"GET",odata:false,paging:{},sorting:{},filtering:{},schema:[]},init:function(options){if(options){this.__ds=options.dataSource;options.dataSource=null;this.settings=$.extend(true,{},$.ig.HierarchicalDataSource.prototype.settings,options);this.settings.dataSource=this.__ds}this._rootopts=this.settings;this._rootopts.urlParamsEncoded=$.proxy(this._encodeHierarchicalUrlParams,this);if(this._rootopts.dataSource&&typeof this._rootopts.dataSource._xmlToArray==="function"&&typeof this._rootopts.dataSource._encodePkParams==="function"){this._rootds=this._rootopts.dataSource;this._rootds.settings.urlParamsEncoded=this.settings.urlParamsEncoded;this._rootds.settings.odata=this.settings.odata;if(!this._rootds.settings.schema){this._rootds.settings.schema={}}this._rootds.settings.schema.layouts=this.settings.schema.layouts}else{if($.type(this._rootopts.dataSource)==="string"&&this._rootopts.dataSource.indexOf("$callback=?")!==-1){this._rootds=new $.ig.JSONPDataSource(this._rootopts)}else if(this._rootopts.restSettings&&(this._rootopts.restSettings.update.url!==null||this._rootopts.restSettings.update.template!==null||this._rootopts.restSettings.create.url!==null||this._rootopts.restSettings.create.template!==null||this._rootopts.restSettings.remove.url!==null||this._rootopts.restSettings.remove.template!==null)){this._rootds=new $.ig.RESTDataSource(this._rootopts)}else{this._rootds=new $.ig.DataSource(this._rootopts)}}},dataBind:function(callback,callee){this._rootds.dataBind(callback,callee)},root:function(){if(!this._rootds){this._rootds=new $.ig.DataSource(this._rootopts)}return this._rootds},dataAt:function(path,keyspath){var data=this.root().data(),paths=path.split("/"),kp=keyspath.split("/"),k,i,searchField="Records",j,cd=null,ckey=this.settings.primaryKey,ckeyval="",ckeys=[],ckeyvals=[],match=false;for(i=0;i<paths.length;i++){ckey=paths[i].split(":")[0];ckeyval=paths[i].split(":")[1];if(paths[i]!==""){for(j=0;data&&j<data.length;j++){if(data[j][ckey]!==undefined&&!data[j][ckey].charAt&&ckeyval.charAt){ckeyval=parseInt(ckeyval,10)}match=data[j][ckey]===ckeyval;if(match){cd=data[j][kp[i]];searchField=this.root().schema&&this.root().schema()&&this.root().schema().schema?this.root().schema().schema.searchField:searchField;if(cd&&paths.length>1&&i<paths.length-1&&$.type(cd)!=="array"&&cd[searchField]){cd=cd[searchField]}break}}data=cd}}return cd},_encodeUrlPath:function(rowid,name){return"path="+rowid+"&layout="+name},_encodeHierarchicalUrlParams:function(owner,args){var expand="",layouts=this.settings.schema.layouts,i,j,tmp,name,lc=0;if(this.settings.odata&&this.settings.initialDataBindDepth!==0){i=j=0;for(name in layouts){if(layouts.hasOwnProperty(name)){lc++}}lc++;for(name in layouts){if(layouts.hasOwnProperty(name)){if($.type(layouts[name])!=="function"){if(name.startsWith("/")){name=name.substring(1,name.length-1)}tmp=name.split("/");for(i=0;i<tmp.length;i++){tmp[i]=tmp[i].substring(0,tmp[i].indexOf(":"))}tmp=tmp.join("/");if(j!==0&&j!==lc-1){expand+=","}expand+=tmp;j++}}}args.selectParams.$expand=expand}else{args.selectParams.dbdepth=this.settings.initialDataBindDepth}}});$.ig.TreeHierarchicalDataSource=$.ig.TreeHierarchicalDataSource||$.ig.DataSource.extend({settings:{treeDS:{childDataKey:null,foreignKey:null,initialExpandDepth:-1,enableRemoteLoadOnDemand:false,dataSourceUrl:null,requestDataCallback:null,requestDataSuccessCallback:null,requestDataErrorCallback:null,propertyExpanded:null,propertyDataLevel:null,expandedKey:"__ig_options.expanded",dataLevelKey:"__ig_options.dataLevel",initialFlatDataView:false,customEncodeUrlFunc:null,persistExpansionStates:false,filtering:{fromLevel:0,toLevel:-1,displayMode:"showWithAncestors",matchFiltering:"__matchFiltering"},sorting:{fromLevel:0,toLevel:-1},paging:{mode:"rootLevelOnly",contextRowMode:"none"}}},_isHierarchicalDataSource:true,init:function(options){if(!options){options={}}this._totalRecordsCount=0;options.treeDS=$.extend(true,{},this.settings.treeDS,options.treeDS);this._flatVisibleData=[];options.treeDS.expandedKey=options.treeDS.propertyExpanded||options.treeDS.expandedKey;options.treeDS.dataLevelKey=options.treeDS.propertyDataLevel||options.treeDS.dataLevelKey;this._super(options);this._isHierarchicalDataSource=options.treeDS.foreignKey===null?true:false;return this},_checkGeneratedSchema:function(){var s=this.settings.treeDS,fs=this.settings.filtering,propertyExp=s.expandedKey,propertyMatchFiltering=s.filtering.matchFiltering;this._checkGeneratedSchemaByKey(s.childDataKey);if(!this._isHierarchicalDataSource){this._checkGeneratedSchemaByKey(s.foreignKey)}if(propertyExp!==null&&propertyExp!==undefined){this._addSchemaField(propertyExp,"boolean")}if(fs&&fs.enabled&&fs.type==="remote"&&propertyMatchFiltering){this._addSchemaField(propertyMatchFiltering,"boolean")}if(s.initialFlatDataView&&s.dataLevelKey){this._addSchemaField(s.dataLevelKey,"number")}},_addSchemaField:function(propName,propType){if(!this.schema()||!this.schema().schema){return}var i,schema=this.schema().schema,fields=schema.fields;if($.type(fields)!=="array"){return}for(i=0;i<fields.length;i++){if(fields[i].name===propName){return}}schema.fields.push({name:propName,type:propType})},_checkGeneratedSchemaByKey:function(key){if(key===null||key===undefined){return}var schema=this.schema(),i,fields=schema.fields(),fL=fields.length;for(i=0;i<fL;i++){if(fields[i].name===key){if(fields[i].name===this.settings.treeDS.childDataKey&&fields[i].type){delete fields[i].type}break}}if(i===fL){fields.push({name:key})}},_applySchema:function(forceApply){var s=this.schema();s.transform=$.proxy(this._transformSchema,this);this._checkGeneratedSchema();this._super(forceApply);this.generateFlatDataView()},dataBind:function(callback,callee){this._totalRecordsCount=0;this._dataBinding=true;this._isHierarchicalDataSource=this.settings.treeDS.foreignKey===null?true:false;var s=this.schema();this.isTransformedToHierarchicalData(false);if(s){if(this.schema().schema.fields.length!==0||this.settings.treeDS.enableRemoteLoadOnDemand){this._checkGeneratedSchema()}if(!this._transformCallback){this._transformCallback=$.proxy(s.transform,s);s.transform=$.proxy(this._transformSchema,this)}}this._flatDataView=[];this._generatedFlatData=false;this._dataBoundDepth=null;this._super(callback,callee)},getParentRowsForRow:function(dataRow,ds){
var key,data=ds||this._data,search,propL,i,res,objPath={},rec,prows;if(dataRow===undefined||dataRow===null){return[]}if($.type(dataRow)==="object"){search=data&&$.isArray(data[0])?this._lookupPkIndex():this.settings.primaryKey;key=dataRow[search];if(key===undefined||key===null){return[]}}else{key=dataRow}if(this._metadata&&$.type(this._metadata.ancestors)==="array"){prows=this._metadata.ancestors;propL=this.settings.treeDS.dataLevelKey;res=[];for(i=0;i<prows.length;i++){res.push({row:this.schema()._row(prows[i]),level:prows[i][propL]})}return res}rec=this.findRecordByKey(key,data,objPath);if(!rec){return[]}return objPath.parentRows},_internalDataBound:function(callDatabound){this._dataBinding=false;this._super(callDatabound)},_completeCallback:function(){if(this.settings.localSchemaTransform){this.generateFlatDataView()}this._super()},getDataBoundDepth:function(){if(this._dataBoundDepth===null||this._dataBoundDepth===undefined){this._dataBoundDepth=0;this._getDataBoundDepthRecursive()}return this._dataBoundDepth},_getDataBoundDepthRecursive:function(data,level){var i,layoutKey=this.settings.treeDS.childDataKey,dataLen,dataRow;if(!this._dataBoundDepth){this._dataBoundDepth=0}if(!level){level=0}if(data===undefined){data=this.data()}if(level>this._dataBoundDepth){this._dataBoundDepth=level}if($.type(data)==="array"){dataLen=data.length;for(i=0;i<dataLen;i++){dataRow=data[i];if(!dataRow){continue}if(dataRow&&$.type(dataRow[layoutKey])==="array"&&dataRow[layoutKey].length){this._getDataBoundDepthRecursive(dataRow[layoutKey],level+1)}}}},_processJsonResponse:function(data,context){this.schema()._processMetadata(data);if(data&&data.Metadata&&data.Metadata.initialFlatDataView!==undefined){this.settings.treeDS.initialFlatDataView=data.Metadata.initialFlatDataView;this._checkGeneratedSchema()}return this._super(data,context)},isTransformedToHierarchicalData:function(isTransformed){if(isTransformed===undefined||isTransformed===null){return this._transformedHierarchicaData}this._transformedHierarchicaData=isTransformed},transformToHierarchicalData:function(data){if($.type(data)!=="array"){return data}var i,rowData,nData,parents=[],children=[],dataLen=data.length;for(i=0;i<dataLen;i++){rowData=$.extend(true,{},data[i]);if(this._hasRecordParent(rowData,data)){children.push(rowData)}else{parents.push(rowData)}}nData=this._getDataLayouts(parents,children);this.isTransformedToHierarchicalData(true);return nData},_getDataLayouts:function(parents,children){var i,pLen=parents.length,key=this.settings.primaryKey,layoutKey=this.settings.treeDS.childDataKey,res=[],parent,cp;for(i=0;i<pLen;i++){parent=parents[i];cp=this._getChildrenByKeyInFlatDS(parents[i][key],children);children=cp.others;if(cp.children.length>0){parent[layoutKey]=this._getDataLayouts(cp.children,children)}res.push(parent)}return res},_getChildrenByKeyInFlatDS:function(foreignKey,data){var i,dr,len=data.length,fKey=this.settings.treeDS.foreignKey,others=[],children=[];for(i=0;i<len;i++){dr=data[i];if(dr[fKey]===foreignKey){children.push(dr)}else{others.push(dr)}}return{children:children,others:others}},_hasRecordParent:function(dataRecord,ds){var i,dataRecordKey,dataRecordPKey,dsRowKey,dsLen,s=this.settings.treeDS,rlv=s.foreignKeyRootValue,foreignKey=s.foreignKey,key=this.settings.primaryKey;dataRecordPKey=dataRecord[foreignKey];if(dataRecordPKey===null||dataRecordPKey===undefined){return false}if(rlv===false){dataRecordKey=dataRecord[key];if(dataRecordKey===null||dataRecordKey===undefined){return false}dsLen=ds.length;for(i=0;i<dsLen;i++){dsRowKey=ds[i][key];if(dsRowKey!==dataRecordKey&&dsRowKey===dataRecordPKey){return true}}return false}return dataRecordPKey!==rlv},_transformSchema:function(data){if(this.settings.treeDS.initialFlatDataView){return this._transformCallback(data)}return this.processDataPerLevel(data,0)},processDataPerLevel:function(data,level,suppressTransformation){var i,layoutKey=this.settings.treeDS.childDataKey,dataLen,dataRow,isRootLevel=false,expDepth=this.settings.treeDS.initialExpandDepth,exp,nData=[],s=this.schema(),layout,hasChildren,lLen,propertyExp=this.settings.treeDS.expandedKey,propertyDataLevel=this.settings.treeDS.dataLevelKey,applyPropertyDataLevel=propertyDataLevel!==null&&propertyDataLevel!==undefined,applyPropertyExp=propertyExp!==null&&propertyExp!==undefined;if(!data){data=this.data()}if($.type(data)==="object"){data=s._getDataBySearchField(data)}if(!level){if(!this._isHierarchicalDataSource&&!this.isTransformedToHierarchicalData()){if(this.metadata("flatToHierarchicalDataTransformed")){this.isTransformedToHierarchicalData(true)}else{data=this.transformToHierarchicalData(data)}}this._totalRecordsCount=0;this._flatData=[];isRootLevel=true;level=0}if(!data){return data}if($.type(data)==="array"){if(!this._dataBoundDepth){this._dataBoundDepth=0}if(level>this._dataBoundDepth){this._dataBoundDepth=level}dataLen=data.length;try{for(i=0;i<dataLen;i++){dataRow=data[i];if(!dataRow){continue}this._totalRecordsCount++;layout=dataRow[layoutKey];exp=dataRow[propertyExp];if(!suppressTransformation){dataRow=s._row(dataRow,i)}this._flatData.push(dataRow);nData.push(dataRow);hasChildren=$.type(layout)==="array";lLen=-1;if(hasChildren){lLen=layout.length}if(applyPropertyExp){if(exp===undefined||exp===null){exp=true;if(hasChildren&&lLen===0){exp=false}if(expDepth!==-1&&expDepth<=level){exp=false}}if(exp===0){exp=false}dataRow[propertyExp]=exp}if(applyPropertyDataLevel){dataRow[propertyDataLevel]=level}if(hasChildren&&lLen>0){dataRow[layoutKey]=this.processDataPerLevel(layout,level+1,suppressTransformation)}}}catch(e){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","errorParsingArrays")+e.message)}}else{nData=this._transformCallback(data)}if(isRootLevel){this._generatedFlatData=true}return nData},getFlatDataForRecord:function(record,level){if(!record){return}var layoutKey=this.settings.treeDS.childDataKey,propertyDataLevel=this.settings.treeDS.dataLevelKey,data=record[layoutKey];if(data){if(level===undefined||level===null){level=0;if(propertyDataLevel!==null&&propertyDataLevel!==undefined&&record[propertyDataLevel]){level=record[propertyDataLevel]}}return this.generateFlatData(data,level)}},generateFlatData:function(data,level){var obj,flatData=[],flatVisibleData=[];if(!level){level=0}obj={flatData:flatData,flatVisibleData:flatVisibleData,recordsCount:0,visibleRecordsCount:0};this._generateFlatDataRecursive(data,level,obj,false);return obj},_generateFlatDataRecursive:function(data,level,obj,parentCollapsed){var i,dataRow,dataLen,exp,expDepth=this.settings.treeDS.initialExpandDepth,propertyExp=this.settings.treeDS.expandedKey,propertyDataLevel=this.settings.treeDS.dataLevelKey,layoutKey=this.settings.treeDS.childDataKey,applyPropertyDataLevel=propertyDataLevel!==null&&propertyDataLevel!==undefined,applyPropertyExp=propertyExp!==null&&propertyExp!==undefined;if(!data){data=this.data()}if(!level){level=0}if($.type(data)==="array"){dataLen=data.length;for(i=0;i<dataLen;i++){dataRow=data[i];if(!dataRow){continue}obj.recordsCount++;obj.flatData.push(data[i]);if(applyPropertyExp){exp=dataRow[propertyExp];if(exp===undefined||exp===null){exp=true;if(expDepth!==-1&&expDepth<=level){exp=false}}if(exp===0){exp=false}dataRow[propertyExp]=exp}if(applyPropertyDataLevel){dataRow[propertyDataLevel]=level}if(!parentCollapsed){obj.flatVisibleData.push(dataRow);obj.visibleRecordsCount++}if(dataRow&&$.type(dataRow[layoutKey])==="array"&&dataRow[layoutKey].length){this._generateFlatDataRecursive(dataRow[layoutKey],level+1,obj,!exp||parentCollapsed)}}}},generateFlatDataView:function(){var data,resObj;if(this.settings.treeDS.initialFlatDataView){this._flatDataView=this._data;return}data=this.dataView();if(!this.shouldCallGenerateFlatDataView()&&!data.length){data=!this._filter?this.data():this._filteredData}resObj=this.generateFlatData(data);this._flatDataView=resObj.flatVisibleData},flatDataView:function(){if(this.settings.treeDS.initialFlatDataView){return this._data}return this._flatDataView},_generateFlatDataAndCountProperties:function(){var data=!this._filter?this.data():this._filteredData,resObj=this.generateFlatData(data);this._flatData=resObj.flatData;this._totalRecordsCount=resObj.recordsCount;this._flatVisibleData=resObj.flatVisibleData},getVisibleFlatData:function(){if(!this._flatVisibleData){this._generateFlatDataAndCountProperties()}return this._flatVisibleData},getFlatData:function(){if(!this._flatData||this._flatData.length!==this._totalRecordsCount){this._generateFlatDataAndCountProperties()}return this._flatData},getFlatDataCount:function(){return this._totalRecordsCount},_page:function(keepRecords){if(this.settings.treeDS.paging.mode==="rootLevelOnly"){return this._super(keepRecords)}var count=0,startIndex,endIndex,i=0;if(keepRecords===undefined){keepRecords=false}if(keepRecords){count=this._flatVisibleData.length}else{this._flatDataView=[]}this._generateFlatDataAndCountProperties();startIndex=this.pageIndex()*this.pageSize();endIndex=startIndex+this.pageSize()>=this._flatVisibleData.length?this._flatVisibleData.length:startIndex+this.pageSize();for(i=startIndex;i<endIndex;i++){this._flatDataView[count++]=this._flatVisibleData[i]}},setExpandedStateByRowIndex:function(index,expanded,callbackArgs){var rec=this.flatDataView()[index];return this._expandCollapseRecord(rec,expanded,callbackArgs)},setExpandedStateByPrimaryKey:function(rowId,expanded,callbackArgs){var rec=this.findRecordByKey(rowId,null);return this._expandCollapseRecord(rec,expanded,callbackArgs)},getExpandStateById:function(rowId){var rec=this.findRecordByKey(rowId),propertyExp=this.settings.treeDS.expandedKey,applyPropertyExp=propertyExp!==null&&propertyExp!==undefined;if(!rec||!applyPropertyExp){return}return rec[propertyExp]},toggleRow:function(rowId,callbackArgs){var rec=this.findRecordByKey(rowId),expanded,propertyExp=this.settings.treeDS.expandedKey,applyPropertyExp=propertyExp!==null&&propertyExp!==undefined;if(!rec||!applyPropertyExp){return}expanded=!rec[propertyExp];return this._expandCollapseRecord(rec,expanded,callbackArgs)},_encodeUrlPath:function(path,depth){var p="path="+path;if(depth!==undefined){p+="&depth="+depth}return p},_requestDataSuccess:function(requestArgs,data){var layoutKey=this.settings.treeDS.childDataKey,layoutData,level,record,callbackArgs,expand;if($.type(data)==="object"){record=requestArgs.record;callbackArgs=requestArgs.callbackArgs;expand=requestArgs.expand;level=record[this.settings.treeDS.dataLevelKey];layoutData=this.processDataPerLevel(data,level+1);record[layoutKey]=layoutData;this._onRecordToggled(record,expand,callbackArgs)}},_encodeUrl:function(){var params=this._super(),s=this.settings.treeDS,paramName;if(s.persistExpansionStates){params=this._encodeExpansionStates(params)}if(s.foreignKey){params.fk=s.foreignKey;if(s.foreignKeyRootValue!==undefined){params.fkRootValue=s.foreignKeyRootValue}}paramName=s.propertyDataLevel?"propertyDataLevel":"dataLevelKey";params[paramName]=s[paramName];paramName=s.propertyExpanded?"propertyExpanded":"expandedKey";params[paramName]=s[paramName];params.childDataKey=s.childDataKey;params.initialExpandDepth=s.initialExpandDepth;if(s.enableRemoteLoadOnDemand){params.loadOnDemand=true}return params},_encodePagingParams:function(params){var p=this.settings.paging;this._super(params);if(p.enabled&&p.type==="remote"){params.pagingParams["paging.mode"]=this.settings.treeDS.paging.mode;params.pagingParams["paging.contextRowMode"]=this.settings.treeDS.paging.contextRowMode}},_encodeSortingParams:function(params){var s=this.settings.sorting;this._super(params);if(s.enabled&&s.type==="remote"){params.sortingParams["sorting.fromLevel"]=this.settings.treeDS.sorting.fromLevel;params.sortingParams["sorting.toLevel"]=this.settings.treeDS.sorting.toLevel}},_encodeFilteringParams:function(params){var f=this.settings.filtering;this._super(params);if(f.enabled&&f.type==="remote"){params.filteringParams["filtering.fromLevel"]=this.settings.treeDS.filtering.fromLevel;params.filteringParams["filtering.toLevel"]=this.settings.treeDS.filtering.toLevel;params.filteringParams.__matchFiltering=this.settings.treeDS.filtering.matchFiltering;params.filteringParams["filtering.displayMode"]=this.settings.treeDS.filtering.displayMode}},_encodeExpansionStates:function(params){var key,listHasValues=false,list=this._listExpansionStates,newList;if(list){newList={};for(key in list){if(list.hasOwnProperty(key)){listHasValues=true;newList[key]=list[key].state}}if(listHasValues){params.listExpansionStates=newList}}return params},_requestData:function(record,expand,callbackArgs){if(!record){return}var opts,me=this,url,path,params,func,s=this.settings.treeDS,args={record:record,callbackArgs:callbackArgs,expand:expand};path=this.getPathBy(record);params=this._encodeUrl();params.expand=expand;url=s.dataSourceUrl+"?"+this._encodeUrlPath(path,record[s.dataLevelKey]);func=s.customEncodeUrlFunc;if(func){if($.type(func)!=="function"){if(window[func]&&typeof window[func]==="function"){func=window[func]}else{func=null}}if(func){url=func(record,expand)}}opts={type:"GET",url:url,data:params,success:function(data,textStatus,jqXHR){var func=s.requestDataErrorCallback,noCancel=true;if($.type(func)==="function"){noCancel=func(args,data,textStatus,jqXHR)}if(noCancel){me._requestDataSuccess(args,data,textStatus,jqXHR)}},error:function(jqXHR,textStatus,errorThrown){var func=s.requestDataErrorCallback;if($.type(func)==="function"){func(args,jqXHR,textStatus,errorThrown)}}};$.ajax(opts)},_applyToggleCallback:function(resObj,callbackArgs){if(!callbackArgs){return}var rec=resObj.record,res=resObj.result,expand=resObj.expand,callback=callbackArgs.callback,args=callbackArgs.args;if(!callback||$.type(callback)!=="function"){return}callback(rec,expand,res,args)},_saveExpansionStateByPKVal:function(pkVal,expand){if(this.settings.treeDS.persistExpansionStates){if(!this._listExpansionStates){this._listExpansionStates={}}if(pkVal!==null&&pkVal!==undefined){if(this._listExpansionStates[pkVal]&&this._listExpansionStates[pkVal].initState===expand){delete this._listExpansionStates[pkVal]}else{this._listExpansionStates[pkVal]={state:expand,initState:!expand}}}}},_onRecordToggled:function(record,expand,callbackArgs){var propertyExp=this.settings.treeDS.expandedKey,filteredRecord=null,res=record,resObj,paging=this.settings.paging,pkVal,applyPropertyExp=propertyExp!==null&&propertyExp!==undefined;resObj={result:false,record:res,expand:expand};if(!record){this._applyToggleCallback(resObj,callbackArgs);return}pkVal=record[this.settings.primaryKey];if(this._filter){if(pkVal!==null&&pkVal!==undefined){filteredRecord=this.findRecordByKey(pkVal,this._filteredData);if(filteredRecord){res=filteredRecord}}}if(applyPropertyExp){record[propertyExp]=expand;if(filteredRecord){filteredRecord[propertyExp]=expand}if(this.settings.treeDS.persistExpansionStates&&!this.settings.treeDS.enableRemoteLoadOnDemand){this.dataBind()}else{if(paging&&paging.enabled&&this.settings.treeDS.paging.mode!=="rootLevelOnly"){if(paging.type==="local"){this._page();this._invokeCallback()}}else{if(this.shouldCallGenerateFlatDataView()){this.generateFlatDataView()}}}}resObj.result=true;resObj.record=res;this._applyToggleCallback(resObj,callbackArgs)},_expandCollapseRecord:function(record,expand,callbackArgs){if(!record){return}var s=this.settings,treeSettings=s.treeDS,func,layout,layoutKey=treeSettings.childDataKey;this._saveExpansionStateByPKVal(record[this.settings.primaryKey],expand);if(s.paging.enabled&&s.paging.type==="remote"&&treeSettings.paging.mode==="allLevels"){this.dataBind();return}if(expand&&treeSettings.enableRemoteLoadOnDemand){layout=record[layoutKey];if(layout===true||$.type(layout)==="array"&&!layout.length){func=treeSettings.requestDataCallback;if($.type(func)==="string"){func=window[func]}if($.type(func)!=="function"){func=$.proxy(this._requestData,this)}func(record,expand,callbackArgs);return}}this._onRecordToggled(record,expand,callbackArgs)},sort:function(fields,direction){var s=this.settings.sorting,p=this.settings.paging,data,resetPaging=false;if(fields===undefined||fields===null){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","noSortingFields"))}this._generatedFlatData=false;if(s.applyToAllData&&s.type==="local"){if(this._filter&&(p.type==="local"&&p.enabled===true||p.enabled===false||p.type==="remote"&&p.enabled===true&&this.settings.filtering.type==="local")){data=this._filteredData}else{data=this.data()}resetPaging=true}else{data=this.dataView()}data=this.sortDataRecursive(data,0,fields,direction);if(resetPaging&&p.type==="local"){if(!this._filter){this._data=data}else{this._filteredData=data}this._page()}else{this._dataView=data}if(this.shouldCallGenerateFlatDataView()){this.generateFlatDataView()}this._populateTransformedData(data);return this},sortDataRecursive:function(data,level,fields,direction){var layoutKey=this.settings.treeDS.childDataKey,i,childDS,dataLen=data.length,s=this.settings.treeDS.sorting;if(s.toLevel===-1||s.toLevel>=level){for(i=0;i<dataLen;i++){childDS=data[i][layoutKey];if(childDS&&childDS.length>0){childDS=this.sortDataRecursive(childDS,level+1,fields,direction)}}}if((s.fromLevel<=level||s.fromLevel===-1)&&(s.toLevel>=level||s.toLevel===-1)){data=this.sortData(data,fields,direction)}return data},sortData:function(data,fields,direction){var s=this.settings.sorting,schema,sortF,convertFunc,settings=this.settings,self=this;if($.type(s.customFunc)==="function"){data=s.customFunc(data,fields,direction)}else{schema=this.settings.schema;if(!direction){direction=""}if($.type(s.compareFunc)==="function"){sortF=s.compareFunc}else{sortF=function(grid,fields,schema,reverse,convertf,caseSensitive){reverse=reverse?-1:1;function compareVals(format,enableUTCDates,rowTemplate,x,y){if(format){if($.type(x)==="date"&&$.type(y)==="date"){if(format==="time"||format==="timeLong"||format==="h:mm:ss tt"){x=new Date("January 01, 2000 "+$.ig.formatter(x,"date",format,rowTemplate,enableUTCDates));y=new Date("January 01, 2000 "+$.ig.formatter(y,"date",format,rowTemplate,enableUTCDates))}}}if((x===null||x===undefined)&&(y===null||y===undefined)){return 0}if((x===null||x===undefined)&&y!==null&&y!==undefined){return-1}if(x!==null&&x!==undefined&&(y===null||y===undefined)){return 1}return x>y?1:x<y?-1:0}return function(obj1,obj2){var i,f,arr1=[],arr2=[],a,b,key,col,format,o,enableUTCDates,rowTemplate;if(grid){o=grid.options;enableUTCDates=o.enableUTCDates;rowTemplate=!o.rowTemplate||o.rowTemplate.length<=0}for(i=0;i<fields.length;i++){key=fields[i].fieldName;if(grid&&grid.columnByKey){col=grid.columnByKey(key);if(col!==undefined&&col!==null){format=col.format}}if(fields[i].layout&&(settings.key&&settings.key!==fields[i].layout||!settings.key)){continue}f=fields[i];if(f.fieldIndex>=0){f.fieldName=f.fieldIndex}a=self.getCellValue(f.fieldName,obj1);b=self.getCellValue(f.fieldName,obj2);if(convertf!==undefined){a=convertf(a,f.fieldName);b=convertf(b,f.fieldName)}if(caseSensitive===false){if(a!==undefined&&a!==null&&a.toLowerCase){a=a.toLowerCase()}if(b!==undefined&&b!==null&&b.toLowerCase){b=b.toLowerCase()}}if(f.dir!==undefined&&f.dir!==null){reverse=f.dir.toLowerCase().startsWith("desc");reverse=reverse?-1:1}else if(direction!==undefined&&direction!==null&&direction!==""){reverse=direction.toLowerCase().startsWith("desc");reverse=reverse?-1:1}if(fields.length===1){arr1=reverse*compareVals(format,enableUTCDates,rowTemplate,a,b);arr2=reverse*compareVals(format,enableUTCDates,rowTemplate,b,a)}else{if(reverse===-1){arr1.push(-compareVals(format,enableUTCDates,rowTemplate,a,b));arr2.push(-compareVals(format,enableUTCDates,rowTemplate,b,a))}else{arr1.push(compareVals(format,enableUTCDates,rowTemplate,a,b));arr2.push(compareVals(format,enableUTCDates,rowTemplate,b,a))}}}if(arr1<arr2){return-1}if(arr1>arr2){return 1}return 0}}}if($.isFunction(s.customConvertFunc)){convertFunc=s.customConvertFunc}if($.type(fields)==="string"){fields=this._parseSortExpressions(fields)}if(fields.length>0){data=data.sort(sortF(this.settings.callee,fields,schema,direction.toLowerCase().startsWith("asc")?false:true,convertFunc,s.caseSensitive));this._allDataSorted=data===this.data()}}return data},totalLocalRecordsCount:function(){var fdv=this._flatVisibleData;if(fdv&&this.settings.paging.type!=="remote"&&this.settings.treeDS.paging.mode!=="rootLevelOnly"){return fdv.length}return this._super()},pageCount:function(){var p=this.settings.paging;if(p.enabled&&p.type==="local"&&this.settings.treeDS.paging.mode==="allLevels"){return Math.ceil(this.totalLocalRecordsCount()/p.pageSize)||1}return this._super.apply(this,arguments)},getFilteringMatchRecordsCount:function(){var count=this.metadata("filtering.countRecords");if(count!==undefined&&count!==null){return count}return this.totalRecordsCount()},filter:function(fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings){var i,f=this.settings.filtering,p=this.settings.paging,data,resetPaging;if(f.applyToAllData&&f.type==="local"){data=this.data();resetPaging=true}else{if(this._cachedDataView&&this._cachedDataView.length>0){data=this._cachedDataView}else{this._cachedDataView=$.merge([],this.dataView());data=this._cachedDataView}}this._filteredRecordsCount=0;this._generatedFlatData=false;this._filteredData=this._filterDataRecursive(data,0,fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings);this._dataView=[];this._filter=true;if(resetPaging&&p.type==="local"&&p.enabled===true){this.settings.paging.pageIndex=0;this.pageSizeDirty(true);this._page()}else{for(i=0;i<this._filteredData.length;i++){this._dataView[i]=this._filteredData[i]}}if(this.shouldCallGenerateFlatDataView()){this.generateFlatDataView()}this._populateTransformedData(this._filteredData);return this},_filterDataRecursive:function(data,level,fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings){var i,j,expr=null,count=0,skipRec=false,f=this.settings.filtering,foundChildDS,subDS,t,k,schema,fields,tmpbool,allFieldsExpr,stringVal,fExprLen,fExprStrLen,propertyExp=this.settings.treeDS.expandedKey,filteredData=[],childDS,layoutKey=this.settings.treeDS.childDataKey,fts=this.settings.treeDS.filtering,matchFiltering=fts.matchFiltering;schema=this.schema();if(schema===null||schema===undefined){throw new Error($.ig.util.getLocaleValue("DataSourceLocale","filteringNoSchema"))}if($.type(fieldExpressions)==="string"){expr=fieldExpressions}if($.type(fieldExpressionsOnStrings)==="string"){allFieldsExpr=fieldExpressionsOnStrings}else if($.type(fieldExpressionsOnStrings)==="undefined"){fieldExpressionsOnStrings=[]}if($.type(fieldExpressions)==="array"&&fieldExpressions.length===0&&$.type(fieldExpressionsOnStrings)==="array"&&fieldExpressionsOnStrings.length===0){return}if($.type(f.customFunc)==="function"){filteredData=f.customFunc(fieldExpressions,data)}else{if(expr){fieldExpressions=this._parseFilterExprString(expr)}if(allFieldsExpr){fieldExpressionsOnStrings=this._parseFilterExprString(allFieldsExpr)}fExprLen=fieldExpressions.length;fExprStrLen=fieldExpressionsOnStrings.length;for(i=0;i<data.length;i++){if(matchFiltering){delete data[i][matchFiltering]}if(!((fts.fromLevel<=level||fts.fromLevel===-1)&&(fts.toLevel>=level||fts.toLevel===-1))){childDS=data[i][layoutKey];if(childDS&&childDS.length){childDS=this._filterDataRecursive(childDS,level+1,fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings);if(childDS&&childDS.length>0){filteredData[count++]=$.extend(true,{},data[i]);filteredData[count-1][layoutKey]=childDS}}continue}skipRec=false;for(j=0;j<fExprLen;j++){fields=schema.fields();if(fieldExpressions[j].fieldIndex!==undefined){if(fieldExpressions[j].fieldIndex<fields.length){t=this._getFieldTypeFromSchema(fields[fieldExpressions[j].fieldIndex].name)}skipRec=!this._findMatch(data[i][fieldExpressions[j].fieldIndex],fieldExpressions[j].expr,t,!f.caseSensitive,fieldExpressions[j].cond,fieldExpressions[j].preciseDateFormat)}else{if(fieldExpressions[j].dataType!==undefined&&fieldExpressions[j].dataType!==null){t=fieldExpressions[j].dataType}else{for(k=0;k<fields.length;k++){if(fields[k].name===fieldExpressions[j].fieldName){t=this._getFieldTypeFromSchema(fields[k].name);break}}}skipRec=!this._findMatch(data[i][fieldExpressions[j].fieldName],fieldExpressions[j].expr,t,!f.caseSensitive,fieldExpressions[j].cond,fieldExpressions[j].preciseDateFormat,fieldExpressions[j].fieldName,data[i])}tmpbool=fieldExpressions[j].logic!==null&&fieldExpressions[j].logic!==undefined&&(fieldExpressions[j].logic.toLowerCase()==="or"||fieldExpressions[j].logic.toLowerCase()==="and")?fieldExpressions[j].logic:boolLogic;if(tmpbool===undefined||tmpbool===null||$.type(tmpbool)!=="string"){tmpbool="and"}if(skipRec&&tmpbool.toLowerCase()==="and"){break}if(!skipRec&&tmpbool.toLowerCase()==="or"){break}}if(!skipRec&&fExprStrLen){for(j=0;j<fExprStrLen;j++){fields=schema.fields();if(fieldExpressionsOnStrings[j].fieldIndex){if(fieldExpressionsOnStrings[j].fieldIndex<fields.length){t=this._getFieldTypeFromSchema(fields[fieldExpressionsOnStrings[j].fieldIndex].name)}stringVal=data[i][fieldExpressionsOnStrings[j].fieldIndex]?data[i][fieldExpressionsOnStrings[j].fieldIndex].toString():"";skipRec=!this._findMatch(stringVal,fieldExpressionsOnStrings[j].expr,"string",!f.caseSensitive,fieldExpressionsOnStrings[j].cond,fieldExpressionsOnStrings[j].preciseDateFormat,fieldExpressionsOnStrings[j].fieldName,data[i])}else{for(k=0;k<fields.length;k++){if(fields[k].name===fieldExpressionsOnStrings[j].fieldName){t=this._getFieldTypeFromSchema(fields[k].name);break}}stringVal=data[i][fieldExpressionsOnStrings[j].fieldName]!==null&&data[i][fieldExpressionsOnStrings[j].fieldName]!==undefined?data[i][fieldExpressionsOnStrings[j].fieldName].toString():"";skipRec=!this._findMatch(stringVal,fieldExpressionsOnStrings[j].expr,"string",!f.caseSensitive,fieldExpressionsOnStrings[j].cond,fieldExpressionsOnStrings[j].preciseDateFormat,fieldExpressionsOnStrings[j].fieldName,data[i])}tmpbool=fieldExpressionsOnStrings[j].logic!==null&&fieldExpressionsOnStrings[j].logic!==undefined&&(fieldExpressionsOnStrings[j].logic.toLowerCase()==="or"||fieldExpressionsOnStrings[j].logic.toLowerCase()==="and")?fieldExpressionsOnStrings[j].logic:boolLogic;if(tmpbool===undefined||tmpbool===null||$.type(tmpbool)!=="string"){tmpbool="and"}if(skipRec&&tmpbool.toLowerCase()==="and"){break}if(!skipRec&&tmpbool.toLowerCase()==="or"){break}}}foundChildDS=false;childDS=data[i][layoutKey];subDS=null;if(childDS&&childDS.length){childDS=this._filterDataRecursive(childDS,level+1,fieldExpressions,boolLogic,keepFilterState,fieldExpressionsOnStrings);if(childDS&&childDS.length>0){subDS=data[i][layoutKey];data[i][layoutKey]=null;filteredData[count++]=$.extend(true,{},data[i]);data[i][layoutKey]=subDS;filteredData[count-1][layoutKey]=childDS;foundChildDS=true;if(propertyExp){filteredData[count-1][propertyExp]=true}if(!skipRec&&matchFiltering){filteredData[count-1][matchFiltering]=true;this._filteredRecordsCount++}}}if(!skipRec&&!foundChildDS){if(fts.displayMode==="showWithAncestors"&&childDS){subDS=data[i][layoutKey];data[i][layoutKey]=null;filteredData[count]=$.extend(true,{},data[i]);data[i][layoutKey]=subDS;filteredData[count][layoutKey]=null;count++}else{if(childDS){subDS=data[i][layoutKey];data[i][layoutKey]=null}filteredData[count]=$.extend(true,{},data[i]);if(subDS){filteredData[count][layoutKey]=subDS;data[i][layoutKey]=subDS}count++}this._filteredRecordsCount++;if(matchFiltering){filteredData[count-1][matchFiltering]=true}if(childDS&&propertyExp){filteredData[count-1][propertyExp]=false}}}}return filteredData},getFilteredRecordsCountFromDataView:function(){var fdv=this.flatDataView(),i,count=0,propMatchFiltering=this.settings.treeDS.filtering.matchFiltering;if(this._filter){for(i=0;i<fdv.length;i++){if(fdv[i][propMatchFiltering]){count++}}}return count},getFilteredRecordsCount:function(){if(this._filter){return this._filteredRecordsCount}return 0},clearLocalFilter:function(){this.clearMatchFiltering();this._super();this._filter=false;if(this.shouldCallGenerateFlatDataView()){this.generateFlatDataView()}},shouldCallGenerateFlatDataView:function(){var s=this.settings,paging=s.paging;return!paging||!paging.enabled||paging.type!=="local"||this.settings.treeDS.paging.mode==="rootLevelOnly"},clearMatchFiltering:function(data){var i,fts=this.settings.treeDS.filtering,dataLen,layout,matchFiltering=fts.matchFiltering,layoutKey=this.settings.treeDS.childDataKey;if(!matchFiltering){return}if(!data){data=this._filteredData;if(!data){return}}dataLen=data.length;for(i=0;i<dataLen;i++){delete data[i][matchFiltering];layout=data[i][layoutKey];if(layout){this.clearMatchFiltering(layout)}}},getPathBy:function(record){if(record===null||record===undefined){return null}var data=this._data,resRecord,search,key,objPath={path:""},path,len=data?data.length:0;search=len>0&&$.isArray(data[0])?this._lookupPkIndex():this.settings.primaryKey;if($.type(record)!=="object"){key=record}else{key=record[search]}resRecord=this.findRecordByKey(key,null,objPath);if(!resRecord){return null}path=objPath.path;if(path!==""){path+="/"}return path+key},_findIndexInFlatDS:function(ds,foreignKeyValue,targetInd){var i,dr,fKey=this.settings.treeDS.foreignKey,len=ds.length,lastInd,layoutInd=0,foundLayout=false;for(i=0;i<len;i++){dr=ds[i];if(dr[fKey]===foreignKeyValue){foundLayout=true;lastInd=i;if(targetInd===layoutInd){return i}layoutInd++}}if(foundLayout){return++lastInd}return-1},findRecordByKey:function(key,ds,objPath){var i,d,layouts=[],res,path,data=ds||this._data,len=data?data.length:0,dsLayoutKey=this.settings.treeDS.childDataKey,search=len>0&&$.isArray(data[0])?this._lookupPkIndex():this.settings.primaryKey;objPath=objPath||{path:"",parentRows:[]};objPath.parentRows=objPath.parentRows||[];objPath.path=objPath.path||"";for(i=0;i<len;i++){d=data[i];if(d[search]===key){objPath.parentRows.push({row:d,level:d[this.settings.treeDS.dataLevelKey]});return data[i]}if(d[dsLayoutKey]){path=objPath.path;if(path!==""){path+="/"}layouts.push({layout:d[dsLayoutKey],objPath:{path:path+d[search],parentRows:objPath.parentRows.concat({row:d,level:d[this.settings.treeDS.dataLevelKey]})}})}}len=layouts.length;for(i=0;i<len;i++){res=this.findRecordByKey(key,layouts[i].layout,layouts[i].objPath);objPath.path=layouts[i].objPath.path;objPath.parentRows=layouts[i].objPath.parentRows;if(res){return res}}return null},_invokeCallback:function(callee,callback){if(!this.schema()&&this._dataBinding){this._data=this.processDataPerLevel(this._data,0,true)}if(this.shouldCallGenerateFlatDataView()){this.generateFlatDataView()}this._super(callee,callback)},removeRecordByKey:function(key,origDs){var data,count=0,all=[this._data];this._addOnlyUniqueToCollection(all,this._dataView);this._addOnlyUniqueToCollection(all,this._filteredData);if(!this._isHierarchicalDataSource){this._removeRecordInFlatDs(origDs,key)}else{this._addOnlyUniqueToCollection(all,origDs)}while(count<all.length){data=all[count++];this._removeRecordByKeyForData(key,data)}},_removeRecordInFlatDs:function(data,key,fk){if(!data||!$.isArray(data)||!data.length||key===undefined&&fk===undefined){return}var i,prime=this.settings.primaryKey,tmp,pkSearch=$.isArray(data[0])?this._lookupPkIndex():prime,fkSearch=this.settings.treeDS.foreignKey;for(i=0;i<data.length;i++){if(data[i]){if(key!==undefined&&data[i][pkSearch]===key){$.ig.removeFromArray(data,i);this._removeRecordInFlatDs(data,undefined,key);break}else if(fk!==undefined&&data[i][fkSearch]===fk){tmp=data[i][pkSearch];$.ig.removeFromArray(data,i);this._removeRecordInFlatDs(data,undefined,tmp);i=0}}}},_removeRecordByKeyForData:function(key,data){if(!data){return false}var i,prime=this.settings.primaryKey,len=data?data.length:0,search=len>0&&$.isArray(data[0])?this._lookupPkIndex():prime,layoutKey=this.settings.treeDS.childDataKey,layoutData=[],found=false;for(i=0;i<len;i++){if(data[i]){if(data[i][search]===key){$.ig.removeFromArray(data,i);found=true;break}if(data[i][layoutKey]){layoutData.push(data[i][layoutKey]);
}}}if(!found){len=layoutData.length;for(i=0;i<len;i++){found=this._removeRecordByKeyForData(key,layoutData[i]);if(found){return true}}}else{return true}return false},deleteRow:function(rowId,autoCommit){var ret=this._super.call(this,rowId,autoCommit);this._dataBoundDepth=null;this.getDataBoundDepth();return ret},getChildrenByKey:function(key,ds){var childKey=this.settings.treeDS.childDataKey,rec=this.findRecordByKey(key,ds);if(rec&&rec[childKey]){return rec[childKey]}return null},insertRow:function(rowId,rowObject,rowIndex,autoCommit,parentRowId){if(parentRowId===null||parentRowId===undefined){return this._super(rowId,rowObject,rowIndex,autoCommit)}var t=this._createInsertNodeTransaction(rowId,rowObject,rowIndex,parentRowId);this._addTransaction(t);if(autoCommit===true){this.commit(rowId)}if($.type(this.settings.rowInserted)==="function"){if(this.settings.callee){this.settings.rowInserted.apply(this.settings.callee,[{rowId:rowId,row:rowObject,parentRowId:parentRowId,rowIndex:rowIndex},this])}else{this.settings.rowInserted({rowId:rowId,row:rowObject,parentRowId:parentRowId,rowIndex:rowIndex},this)}}return t},_createInsertNodeTransaction:function(rowId,rowObject,rowIndex,parentRowId){return{type:"insertnode",tid:this._generateTransactionId(),row:rowObject,rowId:rowId,rowIndex:rowIndex,parentRowId:parentRowId}},_commitTransaction:function(t){var origDs,dv,rec;if(t.type==="insertnode"){origDs=this.settings.localSchemaTransform?this._origDs:null;if(origDs===this._data){origDs=null}this._addRow(t.row,t.rowIndex,origDs,t.parentRowId);this._removeTransactionByTransactionId(t.tid)}else{this._super(t);if(this._filter&&(t.type==="cell"||t.type==="row")){dv=this.dataView();rec=this.findRecordByKey(t.rowId,dv);if(rec){this._updateRecOnCommit(t,[rec])}}}if(!this.settings.paging.enabled||!(t.type==="cell"||t.type==="row")){if(this.settings.paging.type!=="remote"){this._generateFlatDataAndCountProperties()}this.generateFlatDataView()}},_preprocessAddRow:function(row,index,origDs,at,data){var newRow,recAt,res={parentRec:null,cashedData:data,layoutData:null},childKey=this.settings.treeDS.childDataKey;if(at===undefined||at===null||!data){res.layoutData=data;return res}if(!this._isHierarchicalDataSource&&data===origDs){if($.type(row)==="object"){newRow=$.extend(true,{},row)}if(this.settings.treeDS.foreignKey!==null){newRow[this.settings.treeDS.foreignKey]=at}data.push(newRow);return res}recAt=this.findRecordByKey(at,data);if(!recAt){return res}recAt[childKey]=recAt[childKey]||[];res.parentRec=recAt;res.layoutData=recAt[childKey];return res},_postprocessAddRow:function(row,index,origDs,at,pdata){var parentRec=pdata?pdata.parentRec:null,childKey=this.settings.treeDS.childDataKey;if(parentRec&&pdata.newData&&childKey!==null){parentRec[childKey]=pdata.newData;if(parentRec[this.settings.treeDS.dataLevelKey]===this.getDataBoundDepth()){this._dataBoundDepth++}}},_addRow:function(row,index,origDs,at){var ret=this._super.call(this,row,index,origDs,at);if(at!==undefined&&at!==null&&!this.settings.treeDS.dataLevelKey){this._dataBoundDepth=null;this.getDataBoundDepth()}return ret}});return $});