ajaxData_Employees.Add(ajaxManager,'basic');
ajaxData_Accruals.Add(ajaxManager,'basic');
ajaxData_Payrolls.Add(ajaxManager,'basic');
ajaxData_Departments.Add(ajaxManager,'basic');
ajaxData_Centers.Add(ajaxManager,'basic');

	
ajaxManager.group['basic'].Start();
ajaxManager.group['basic'].oncomplete=function(){
	cmbFromEmployee.AddItem($.lng('all_p_m'),'All');
	cmbToEmployee.AddItem($.lng('none_m'),'None');
	for(var i in aEmployees){
		if($.Utils.IsInEmployees(aEmployees[i].Codigo)){
			cmbFromEmployee.AddItem(aEmployees[i].Text,aEmployees[i].Codigo);
			cmbToEmployee.AddItem(aEmployees[i].Text,aEmployees[i].Codigo);
		}
	}
	cmbDepartment.AddItem($.lng('all_p_m'),'All');
	for(var i in aDepartments){ cmbDepartment.AddItem(aDepartments[i].Text,i); }
	cmbCenter.AddItem($.lng('all_p_m'),'All');
	for(var i in aCenters){ cmbCenter.AddItem(aCenters[i].Text,i); }

}
{//Controles
	var gpHeader = new $.Objects.Container();
	gpHeader.Location(0,0,1000,245);
	gpHeader.SetStyle('transparent');
	gpHeader.Add();

	var selectedReport=null;
	var aColumns=[];
	{//Controles por defecto-----------------------------------------------------------------------------------------------------------------------------------
		var lblReportType = new $.Objects.Text($.lng('report_type')+':');
		lblReportType.Location(10,15,100,20);
		lblReportType.Add(gpHeader);
		var cmbReport = new $.Objects.ComboBox();
		cmbReport.Location(160,10,830,20);
		cmbReport.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var lblTitle = new $.Objects.Text($.lng('title')+':');
		lblTitle.Location(10,40,100,20);
		lblTitle.Add(gpHeader);
		var txtTitle = new $.Objects.TextBox();
		txtTitle.Location(160,35,830,20);
		txtTitle.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var lblFromEmployee = new $.Objects.Text($.lng('from_employee')+':');
		lblFromEmployee.Location(10,65,150,20);
		lblFromEmployee.Add(gpHeader);
		var cmbFromEmployee = new $.Objects.ComboBox();
		cmbFromEmployee.Location(160,60,335,20);
		cmbFromEmployee.Add(gpHeader);
		
		var lblFromEmployee = new $.Objects.Text($.lng('to_employee')+':');
		lblFromEmployee.Location(505,65,150,20);
		lblFromEmployee.Add(gpHeader);
		var cmbToEmployee = new $.Objects.ComboBox();
		cmbToEmployee.Location(655,60,335,20);
		cmbToEmployee.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var lblDepartment = new $.Objects.Text(COMPANY.department+':');
		lblDepartment.Location(10,90,150,20);
		lblDepartment.Add(gpHeader);
		var cmbDepartment = new $.Objects.ComboBox();
		cmbDepartment.Location(160,85,335,20);
		cmbDepartment.Add(gpHeader);	
		
		var lblCenter = new $.Objects.Text(COMPANY.center+':');
		lblCenter.Location(505,90,150,20);
		lblCenter.Add(gpHeader);
		var cmbCenter = new $.Objects.ComboBox();
		cmbCenter.Location(655,85,335,20);
		cmbCenter.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var lblMonth = Jade.Objects.Text(Jade.Lang.Get('month')+':');
		lblMonth.Location(10,115,150,20);
		lblMonth.Add(gpHeader);
		var cmbMonth = Jade.Objects.ComboBox();
		cmbMonth.Location(160,110,335,20);
		cmbMonth.Add(gpHeader);

		var lblYear = Jade.Objects.Text(Jade.Lang.Get('year')+':');
		lblYear.Location(505,115,150,20);
		lblYear.Add(gpHeader);
		var cmbYear = Jade.Objects.ComboBox();
		cmbYear.Location(655,110,335,20);
		cmbYear.Add(gpHeader);
		
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var cmdCustomColumns=$.Objects.ButtonIcon($.Lang.Get('custom_columns'), 'size16 columns');
		cmdCustomColumns.Location(655,165,335,20);
		cmdCustomColumns.Add(gpHeader);		
		
		var cmdConditions=$.Objects.ButtonIcon($.Lang.Get('define_conditions'), 'size16 filter');
		cmdConditions.Location(655,190,335,20);
		cmdConditions.Add(gpHeader);
		
		var cmdView=$.Objects.ButtonIcon($.lng('generate_report'), 'size16 view');
		cmdView.Location(655,215,335,22);
		cmdView.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var winCC=CustomColumsWindow(0);
		var winCondition=ConditionWindow();
	}
	{//Controles: Lista----------------------------------------------------------------------------------------------------------------------------------------
		var cmReports=$.Grids.ColumnModel({editable: false, fixedfocus: true});
		cmReports.Add($.Grids.SimpleColumn({key: 'title', text: $.lng('report_title'), width: '675'}));
		
		var grReports = new $.Grids.Grid(cmReports);
		grReports.Location(0,255,700,285);
		grReports.Add();
		
		var cmdNew=$.Objects.ButtonIcon($.lng('new_m'), "size16 new");
		cmdNew.Location(705,255,295,22);
		cmdNew.Add();
	
		var cmdSave=$.Objects.ButtonIcon($.lng('save'), "size16 save");
		cmdSave.Location(705,282,295,22);
		cmdSave.Add();	
	
		var cmdDelete=$.Objects.ButtonIcon($.lng('strDelete'), "size16 del");
		cmdDelete.Location(705,309,295,22);
		cmdDelete.Add();
	}	
	{//Valores
		for(var i=1; i<=12;i++){ cmbMonth.AddItem(Jade.Lang.Get('month_'+i),i); }
		for(var i=Jade.DateTime.CurrentYear()-10;i<=Jade.DateTime.CurrentYear()+10;i++){ cmbYear.AddItem(i,i); }	
	}
	{//Eventos: Lista
		function Load_Report_List() {
			selectedReport=null;
			var ajaxRptList=$.AjaxDB($.Strings.Format("SELECT IdListado,Titulo FROM LISTADOS{c} WHERE Tipo='25' AND (IdUsuario={0} OR IdListado IN "+
			"(SELECT IdConfiguracion FROM LISTADOS_VISIBILIDAD{c} WHERE IdUsuario={0}))", USER.id), Ajax.Dontwait);
			ajaxRptList.oncomplete=function(){
				if(!this.json.error){
					grReports.ClearRows();
					for(var i=0,iLen=this.json.row.length;i<iLen;i++){
						var item=this.json.row[i];
						grReports.NewRow([item.Titulo], item.IdListado);
					}
				}
				else{ $.Debug.Add(this.text); }
			}
		}
		grReports.onrowclick=function(row){
			selectedReport=row.key;
			var params={};
			
			var db=$.AjaxDB("SELECT * FROM LISTADOS{c} WHERE IdListado="+row.key, Ajax.Wait);
			var error=db.json.error;
			if(!error){
				params=db.json.row[0];
				params.columns=[];
				params.condition={id: '', formula: '', option: '', columns: []};
				
				db=$.AjaxDB("SELECT Tipo,Valor FROM LISTADOS_FILTROS{c} WHERE IdListado="+row.key, Ajax.Wait);
				error=db.json.error;
				if(!error){
					for(var i=0; i<db.json.row.length!=0;i++){
						var item=db.json.row[i];
						switch(item.Tipo){
							case 'AplicarCondicion':
								params.condition.option=item.Valor;
								break;
							case 'Condicion':
								params.condition.id=item.Valor;
								break;
							case 'SelecciónDeBolsas':
								params['SeleccionDeBolsas']=item.Valor;
								break;
							case 'SelecciónDeBolsas2':
								params['SeleccionDeBolsas2']=item.Valor;
								break;
							case 'SelecciónDeBolsas3':
								params['SeleccionDeBolsas3']=item.Valor;
								break;
							default: 
								params[$.Strings.StripAccents(item.Tipo)]=item.Valor;
								break;
						}
					}
				}
				else{ $.Debug.Add(this.text); }
				
				//Columnas
				db=$.AjaxDB("SELECT * FROM LISTADOS_COLUMNAS{c} WHERE IdListado="+row.key+" ORDER BY Orden", Ajax.Wait);
				error=db.json.error;
				if(!error){
					for(var i=0; i<db.json.row.length!=0;i++){
						var item=db.json.row[i];
						var key=item.Orden-1;
						
						winCC.columns[key][2]=item.Tipo;
						winCC.columns[key][3]=item.Valor;
							
						switch(item.Tipo){
							case 'TotalAttendance': case 'StandardHours':
								winCC.columns[key][4]=item.Tipo;
								break;
							case 'Formula':
								if($.isDefined(aFormulas[item.Valor])){ winCC.columns[key][4]=aFormulas[item.Valor].Value; }
								break;
							default:
								winCC.columns[key][4]=item.Tipo+item.Valor;
								break;
						}
					}
				}
				else{ $.Debug.Add(this.text); }
					
				//Condicion
				if(params.condition.id!=''){
					db=$.AjaxDB("SELECT * FROM LISTADOS_FOR{c} WHERE Id="+params.condition.id+" AND Tipo='Logic'", Ajax.Wait);
					error=db.json.error;
					if(!error){
						if(db.json.row.length>0){
							var item=db.json.row[0];
							params.condition.formula=item.Valor;
							db=$.AjaxDB("SELECT * FROM LISTADOS_FOR_COL{c} WHERE IdFormula="+params.condition.id+" ORDER BY Alias", Ajax.Wait);
							if(!error){
								for(var i=0; i<db.json.row.length!=0;i++){
									var item=db.json.row[i];
									params.condition.columns.push([item.Nombre, item.Tipo, item.Valor]);
								}
							}
							else{ $.Debug.Add(this.text); }
						}
					}
					else{ $.Debug.Add(this.text); }
				}
				Load_Report_Config(params);
			}
			else{$.Debug.Add(this.text); }		
		}
		function Load_Report_Config(values) {
			cmdSave.SetEnabled(USER.id==values.IdUsuario);
			cmdDelete.SetEnabled(USER.id==values.IdUsuario);
			
			txtTitle.SetText(values.Titulo);
			cmbFromEmployee.SetSelectedKey(values.Desde);
			cmbToEmployee.SetSelectedKey(values.Hasta);
			
			cmbDepartment.SetSelectedKey(values.Departamento);
			cmbCenter.SetSelectedKey(values.Centro);

			cmbMonth.SetSelectedKey(values.Mes);
			cmbYear.SetSelectedKey(values.Anho);
		}
		function IsSingleFormula(formula){
			var operators=['+','-','/','*'];
			var retValue=true;
			for(var i=0,iLen=operators.length;i<iLen;i++){
				if(formula.indexOf(operators[i])>0){ retValue=false; }
			}
			return retValue;
		}
	}
	{//Eventos: Botones
		cmdNew.onclick=function(){
			grReports.ClearFocus();
			selectedReport=null;
			cmdSave.SetEnabled(true);
			cmdDelete.SetEnabled(true);
			DefaultValues();
		}
		cmdSave.onclick=function(){
			var is_new=(selectedReport==null);

			var is_new=(selectedReport==null);
			var key=is_new?$.DateTime.Ticks():selectedReport;
			
			if(is_new){ $.AjaxDBSave('LISTADOS{c}', ['IdListado', 'Tipo', 'IdUsuario', 'Titulo', 'Desde', 'Hasta'], [key, cmbReport.selectedKey, USER.id, txtTitle.GetText(), cmbFromEmployee.selectedKey, cmbToEmployee.selectedKey]); }
			else{ $.AjaxDBSave('LISTADOS{c}', ['Tipo', 'IdUsuario', 'Titulo', 'Desde', 'Hasta'], [cmbReport.selectedKey, USER.id, txtTitle.GetText(), cmbFromEmployee.selectedKey, cmbToEmployee.selectedKey], "IdListado='"+key+"'"); }
			
			SaveReportField(is_new, key, 'Departamento', cmbDepartment.selectedKey);
			SaveReportField(is_new, key, 'Centro', cmbCenter.selectedKey);

			
			switch(cmbReport.selectedKey){
				case '25':
					SaveReportField(is_new, key, 'Mes', cmbMonth.selectedKey);
					SaveReportField(is_new, key, 'Anho', cmbYear.selectedKey);
					if(!is_new){ $.AjaxDBDelete("LISTADOS_COLUMNAS{c}", 'IdListado='+selectedReport); }
					for(var i=0, iLen=winCC.columns.length;i<iLen;i++){
						var column=winCC.columns[i];
						$.AjaxDBSave('LISTADOS_COLUMNAS{c}', ['IdListado', 'Orden', 'Nombre', 'Tipo', 'Valor'], [key, i+1, column[1], column[2], column[3]]);
					}
					break;
			}
			Load_Report_List();
			DefaultValues();
		}
		cmdDelete.onclick=function(){
			if(selectedReport!=null){
				$.AjaxDBDelete("LISTADOS{c}", 'IdListado='+selectedReport);
				$.AjaxDBDelete("LISTADOS_FILTROS{c}", 'IdListado='+selectedReport);
				$.AjaxDBDelete("LISTADOS_COLUMNAS{c}", 'IdListado='+selectedReport);
				Load_Report_List();
				DefaultValues();
			}
		}
		cmdView.onclick= function() {
			var report = $.Report('aam');
			report.AddValue('title',txtTitle.GetText());
			report.Show(true);
		}	
	}
	{//Columnas: Tiempos y costes
		{//Button: CustomColumns---------------------------------------------------------------------------------------------------------------------------------------------------------
			cmdCustomColumns.onclick = function() {
				winCC.Show();
			}
		}
		{//Window: Formulas----------------------------------------------------------------------------------------------------------------------------------------------------------------------
			var formulaWindow=$.Objects.Window(360,300);
			formulaWindow.field=0;
			
			var lblFW=$.Objects.Text($.lng('formula_define')+':');
			lblFW.Location(10,10,640,20);
			lblFW.Add(formulaWindow);
			
			var cmFW = new $.Grids.ColumnModel({editable: false, sortable:false});
			cmFW.Add(new $.Grids.SimpleColumn({key: 'letter', text: '', width: '24'}));
			cmFW.Add(new $.Grids.ComboColumn({key: 'description', text: $.lng('description'), width: '250'}));
			cmFW.Add(new $.Grids.ButtonColumn({key: 'button', text: '', width: '35'}));
			
			var grFW=new $.Grids.Grid(cmFW);
			grFW.Location(10,30,340,200);
			grFW.Add(formulaWindow);
			
			var lblFW_formula = new $.Objects.Text($.lng('formula')+':');
			lblFW_formula.Location(10,245,90,20);
			lblFW_formula.Add(formulaWindow);
			
			txtFW=new $.Objects.TextBox();
			txtFW.Location(100,239,250,20);
			txtFW.Add(formulaWindow);
			
			var cmdFW_Accept = new $.Objects.Button();
			cmdFW_Accept.Location(10,265,165,24);
			cmdFW_Accept.SetText($.lng('accept'));
			cmdFW_Accept.Add(formulaWindow);
			cmdFW_Accept.onclick=function() {
				SaveFormula();
			}
		
			var cmdFW_Cancel = new $.Objects.Button();
			cmdFW_Cancel.Location(180,265,170,24);
			cmdFW_Cancel.SetText($.lng('cancel'));
			cmdFW_Cancel.Add(formulaWindow);
			cmdFW_Cancel.onclick=function(){ formulaWindow.Hide(); payrollWindow.Show(); }
			
			grFW.columnmodel.columns[2].oncellclick=function(cell){
				var lastRow = grFW.rows[grFW.rows.length-1];
				lastRow.cells[2].SetValue('');
				var row=AddFieldRow('TATTENDANCETOTAL');
				row.cells[2].SetValue('<div class="icon new"></div>');
			}
			
			function SaveFormula(){
				var index=formulaWindow.field;
				var fields=[];
				var title=txtFW.GetText();
				var formula=title;
				
				for(var i=0,iLen=grFW.rows.length;i<iLen;i++){
					formula=formula.replace(new RegExp($.Strings.Chr(65+i),'g'),$.Strings.Chr(97+i));
				}
				for(var i=0,iLen=grFW.rows.length;i<iLen;i++){
					var cell=grFW.rows[i].cells;
					var combo=cell[1].references.object;
					var text=combo.items[combo.selectedIndex].text;
					if(combo.selectedIndex>1){ text=text.substr(text.indexOf('-')+2); }
					var reg=new RegExp(cell[0].value,'g');
					title=title.replace(reg,text);
					formula=formula.replace(reg,combo.selectedKey);
				}
				if(cmbPW_Column[index].selectedKey!='formula'){ cmbPW_Column[index].SetSelectedKey('formula'); }
				if(txtPW_Column[index].GetText()==""){ txtPW_Column[index].SetText(title); }
				payrollWindow.formula[index]=formula;
				formulaWindow.Hide();
				payrollWindow.Show();
			}
			function AddFieldRow(field){
				var letter=$.Strings.Chr(97+grFW.rows.length);
				var row=grFW.NewRow([letter,'',''],letter);
				var combo=row.cells[1].references.object;
				combo.AddItem($.lng('total_attendance'),'TATTENDANCETOTAL','ATT');
				combo.AddItem($.lng('duty_time'),'STDHOURS','STD');
				for(var x=0 in aAccruals){
					combo.AddItem(aAccruals[x].Text,'ACUM.'+aAccruals[x].Codigo,'ACUM');
				}
				for(var x=0 in aPayrolls){
					combo.AddItem(aPayrolls[x].Text,'CONC.'+aPayrolls[x].Codigo,'CONC');
				}
				combo.SetSelectedKey(field);
				return row;
			}
			function ShowFormula(index){
				var formula=payrollWindow.formula[index];
				formulaWindow.field=index;
				payrollWindow.Hide();
				grFW.ClearRows();
				txtFW.SetText('');
				if(typeof(payrollWindow.formula[index])!="undefined"){
					var formula=payrollWindow.formula[index];
					var aFields=[];

					if(isFormulaField(formula,'TATTENDANCETOTAL')){ aFields.push('TATTENDANCETOTAL'); }
					if(isFormulaField(formula,'STDHOURS')){ aFields.push('STDHOURS'); }
					for(var i in aAccruals){ 
						if(isFormulaField(formula,'ACUM.'+aAccruals[i].Codigo)){ aFields.push('ACUM.'+aAccruals[i].Codigo); }
					}
					for(var i in aPayrolls){
						if(isFormulaField(formula,'CONC.'+aPayrolls[i].Codigo)){ aFields.push('CONC.'+aPayrolls[i].Codigo); }
					}
					for(var i=0,iLen=aFields.length;i<iLen;i++){
						AddFieldRow(aFields[i]);
						formula=formula.replace(new RegExp(aFields[i], 'gi'),$.Strings.Chr(97+i));
					}
					txtFW.SetText(formula);
				}
				if(grFW.rows.length==0){
					AddFieldRow('TATTENDANCETOTAL');
				}
				var lastRow = grFW.rows[grFW.rows.length-1];
				lastRow.cells[2].SetValue('<div class="icon new"></div>');
				
				formulaWindow.Show();
			}
			function isFormulaField(formula,value){
				if(formula.indexOf(value)>=0){ return true; }
				else{ return false; }
			}
		}
	}
	{//Condicion: Tiempos y costes
		cmdConditions.onclick=function(){
			winCondition.Show();
		}
	}
}
function DefaultValues(){
	var strYear=$.DateTime.CurrentYear();
	var strMonth=$.Strings.PadLeft($.DateTime.CurrentMonth(),'0',2);
	var strLastDay=$.Strings.PadLeft($.DateTime.Monthdays(strMonth, strYear),'0',2);
	txtTitle.SetText(cmbReport.value);
	if(cmbFromEmployee.items.length!=0){ cmbFromEmployee.SetSelectedIndex(0); }
	if(cmbToEmployee.items.length!=0){ cmbToEmployee.SetSelectedIndex(0); }
	if(cmbDepartment.items.length!=0){ cmbDepartment.SetSelectedIndex(0); }
	if(cmbCenter.items.length!=0){ cmbCenter.SetSelectedIndex(0); }

	cmbMonth.SetSelectedKey(Jade.Strings.PadLeft(Jade.DateTime.CurrentMonth(),'0',2));
	cmbYear.SetSelectedKey(Jade.DateTime.CurrentYear());
	
	winCC.Clear();
	winCondition.Clear();
	
	winCC.columns = [
	['3','Ukupno','',0,''],
	['3a','Rad noću','',0,''],
	['3b','Rad nedjeljom i blagdanom','',0,''],
	['3c','Prekid rada bez odgovor nosti radnika','',0,''],
	['3d','Prekovre meni rad','',0,''],
	['4','Preraspo dijela radnog vremena','',0,''],
	['5','Izostanak / neradni dani i sl.','',0,''],
	['6','Sati priprav nosti','',0,''],
	['7','Godišnji odmor','',0,''],
	['8','Bolovanje','',0,''],
	['9','Plaćeni dopust','',0,''],
	['10','Neplaćeni dopust','',0,''],
	['11','Izostanak / privatno','',0,''],
	['12','Štrajk','',0,''],
	['13','Isključenje s rada','',0,''],
	['14','Službeni put','',0,''],
	['15','Terenski rad','',0,''],
	['16','Porodiljnji i sl. dopusti','',0,''],
	];
}

function DefaultValues_Time_Payroll(){
	cmbGroupDate.SetSelectedKey('1');
	cmbViewPunches.SetSelectedIndex(1);
	chkPagePerEmployee.SetCheck(false);
	chkViewWeeklyTotal.SetCheck(false);
	chkShowValuation.SetCheck(false);
	chkViewMonthlyTotal.SetCheck(false);
	chkEmployeeDutyTime.SetCheck(false);
	chkViewEmployeeTotal.SetCheck(false);
}

cmbReport.onchangekey=function(){
	DefaultValues();
	Load_Report_List();
}

cmbReport.AddItem('Izvještaj evidencije radnog vremena','25');

function SaveReportField(is_new, id, field, value){
	if(is_new){ $.AjaxDBSave('LISTADOS_FILTROS{c}', ['IdListado', 'Tipo', 'Valor'], [id, field, value]); }
	else{ $.AjaxDBSave('LISTADOS_FILTROS{c}', ['Valor'], [value], "IdListado='"+id+"' AND Tipo='"+field+"'");  }
}