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,310,20);
		cmbFromEmployee.Add(gpHeader);
		
		$.ControlAdd('searchemployee', [475,60,20,20], gpHeader, cmbFromEmployee);
		
		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,310,20);
		cmbToEmployee.Add(gpHeader);
		
		$.ControlAdd('searchemployee', [970,60,20,20], gpHeader, cmbToEmployee);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		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 lblFromDate = new $.Objects.Text($.lng('from_date')+':');
		lblFromDate.Location(10,140,150,20);
		lblFromDate.Add(gpHeader);
		var cmbFromDate = new $.Objects.DatePicker();
		cmbFromDate.Location(160,135,335,20);
		cmbFromDate.Add(gpHeader);

		var lblToDate = new $.Objects.Text($.lng('to_date')+':');
		lblToDate.Location(505,140,150,20);
		lblToDate.Add(gpHeader);
		var cmbToDate = new $.Objects.DatePicker();
		cmbToDate.Location(655,135,335,20);
		cmbToDate.Add(gpHeader);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var cmdView=$.Objects.ButtonIcon($.lng('generate_report'), 'size16 view');
		cmdView.Location(655,215,335,22);
		cmdView.Add(gpHeader);
	}
	{//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();
	}	
	{//Controles: Tiempos y costes
		var divTimePayrolls = document.createElement('div');
		divTimePayrolls.style.position = 'absolute';
		divTimePayrolls.style.left='10px';
		divTimePayrolls.style.top='110px';
		divTimePayrolls.style.width = '980px';
		divTimePayrolls.style.height = '100px';
		gpHeader.appendChild(divTimePayrolls);
		
		var lblGroupDate = new $.Objects.Text($.lng('group_by')+':');
		lblGroupDate.Location(0,5,150,20);
		lblGroupDate.Add(divTimePayrolls);
		var cmbGroupDate = new $.Objects.ComboBox();
		cmbGroupDate.Location(150,0,335,20);
		cmbGroupDate.Add(divTimePayrolls);

		var lblViewPunches = new $.Objects.Text($.lng('view_checks')+':');
		lblViewPunches.Location(495,5,150,20);
		lblViewPunches.Add(divTimePayrolls);
		var cmbViewPunches = new $.Objects.ComboBox();
		cmbViewPunches.Location(645,0,335,20);
		cmbViewPunches.Add(divTimePayrolls);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------
		var chkPagePerEmployee = new $.Objects.CheckBox($.lng('page_per_employee'));
		chkPagePerEmployee.Location(0,55,250,20);
		chkPagePerEmployee.Add(divTimePayrolls);
		
		var chkViewWeeklyTotal = new $.Objects.CheckBox($.lng('view_weekly_total'));
		chkViewWeeklyTotal.Location(275,55,250,20);
		chkViewWeeklyTotal.Add(divTimePayrolls);
		
		var chkShowValuation = new $.Objects.CheckBox($.lng('show_valuation_for_payrolls'));
		chkShowValuation.Location(0,80,250,20);
		chkShowValuation.Add(divTimePayrolls);

		
		
		var chkViewMonthlyTotal = new $.Objects.CheckBox($.lng('view_monthly_total'));
		chkViewMonthlyTotal.Location(275,80,250,20);
		chkViewMonthlyTotal.Add(divTimePayrolls);
		
		var chkEmployeeDutyTime = new $.Objects.CheckBox($.lng('dutytime_from_employee_maintenance'));
		chkEmployeeDutyTime.Location(275,80,250,20);
		chkEmployeeDutyTime.Add(divTimePayrolls);

		var chkShowAllDays = new $.Objects.CheckBox($.lng('show_all_days_without_checks'));
		chkShowAllDays.Location(0,105,250,20);
		chkShowAllDays.Add(divTimePayrolls);

		var chkViewEmployeeTotal = new $.Objects.CheckBox($.lng('view_employee_total'));
		chkViewEmployeeTotal.Location(275,105,250,20);
		chkViewEmployeeTotal.Add(divTimePayrolls);
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var cmdCustomColumns=$.Objects.ButtonIcon($.lng('custom_columns'), 'size16 columns');
		cmdCustomColumns.Location(645,53,335,22);
		cmdCustomColumns.Add(divTimePayrolls);		
		
		var cmdConditions=$.Objects.ButtonIcon($.lng('define_conditions'), 'size16 filter');
		cmdConditions.Location(645,79,335,22);
		cmdConditions.Add(divTimePayrolls);
		
		//-------------------------------------------------------------------------------------------------------------------------------------------------------------	
		var winCC=CustomColumsWindow(8);
		var winCondition=ConditionWindow('fixed');
	}
	{//Controles: Bolsas
		var divAccruals = document.createElement('div');
		divAccruals.style.position = 'absolute';
		divAccruals.style.left='10px';
		divAccruals.style.top='110px';
		divAccruals.style.width = '980px';
		divAccruals.style.height = '100px';
		gpHeader.appendChild(divAccruals);
		
		var lblGroup = new $.Objects.Text($.lng('group_by')+':');
		lblGroup.Location(0,5,150,20);
		lblGroup.Add(divAccruals);
		var cmbGroup = new $.Objects.ComboBox();
		cmbGroup.Location(150,0,335,20);
		cmbGroup.Add(divAccruals);

		var lblTerm = new $.Objects.Text($.lng('term')+':');
		lblTerm.Location(495,5,150,20);
		lblTerm.Add(divAccruals);
		var cmbTerm = new $.Objects.ComboBox();
		cmbTerm.Location(645,0,335,20);
		cmbTerm.Add(divAccruals);	

		var lblYear = new $.Objects.Text($.lng('year')+':');
		lblYear.Location(0,30,150,20);
		lblYear.Add(divAccruals);
		var cmbYear = new $.Objects.ComboBox();
		cmbYear.Location(150,25,335,20);
		cmbYear.Add(divAccruals);
		
		var lblMonth = new $.Objects.Text($.lng('month')+':');
		lblMonth.Location(495,30,150,20);
		lblMonth.Add(divAccruals);
		var cmbMonth = new $.Objects.ComboBox();
		cmbMonth.Location(645,25,335,20);
		cmbMonth.Add(divAccruals);

		var lblFromWeek = new $.Objects.Text($.lng('from_week')+':');
		lblFromWeek.Location(0,55,150,20);
		lblFromWeek.Add(divAccruals);
		var cmbFromWeek = new $.Objects.ComboBox();
		cmbFromWeek.Location(150,50,335,20);
		cmbFromWeek.Add(divAccruals);

		var lblToWeek = new $.Objects.Text($.lng('to_week')+':');
		lblToWeek.Location(495,55,150,20);
		lblToWeek.Add(divAccruals);
		var cmbToWeek = new $.Objects.ComboBox();
		cmbToWeek.Location(645,50,335,20);
		cmbToWeek.Add(divAccruals);

		var chkEmployeePage = new $.Objects.CheckBox($.lng('page_per_employee'));
		chkEmployeePage.Location(0,80,250,20);
		chkEmployeePage.Add(divAccruals);
		
		var chkTotal = new $.Objects.CheckBox($.lng('total'));
		chkTotal.Location(275,80,250,20);
		chkTotal.Add(divAccruals);	
		
		var cmdAccrual = new $.Objects.ButtonIcon($.lng('accrual_selection'), 'size16 Accruals');
		cmdAccrual.Location(645,80,335,20);
		cmdAccrual.Add(divAccruals);
		cmdAccrual.onclick = function(){
			grAccrualsWindow.ClearRows();
			for(var i in aAccruals){
				var item = aAccruals[i];
				var row = grAccrualsWindow.AddRow(new $.Grids.Row([item.show,item.Text]),item.Codigo);
				row.cells[0].references.object.SetCheck(item.show);
			}
			accrualsWindow.Show();
		}
	}
	{//Valores: Tiempos y costes
		cmbGroupDate.AddItem($.lng('none_m'),'0');
		cmbGroupDate.AddItem($.lng('term_day'),'1');
		cmbGroupDate.AddItem($.lng('term_week'),'2');
		cmbGroupDate.AddItem($.lng('term_month'),'3');
		cmbViewPunches.AddItem($.lng('none_m'),'none');
		cmbViewPunches.AddItem($.lng('rounded_punches'),'RoundedChecks');
		cmbViewPunches.AddItem($.lng('actual_punches'),'RealChecks');		
	}
	{//Valores: Bolsas
		cmbGroup.AddItem($.lng('employee'),'Employee');
		cmbGroup.AddItem($.lng('group_and_center'),'Department');
		
		cmbTerm.AddItem($.lng('none_m'),'4');
		cmbTerm.AddItem($.lng('term_day'),'3');
		cmbTerm.AddItem($.lng('term_week'),'0');
		cmbTerm.AddItem($.lng('term_month'),'1');
		cmbTerm.AddItem($.lng('term_year'),'2');
		
		for(var i=1; i<=12;i++){ cmbMonth.AddItem($.lng('month_'+i),i); }
		for(var i=$.DateTime.CurrentYear()-10;i<=$.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='{0}' AND (IdUsuario={1} OR IdListado IN "+
			"(SELECT IdConfiguracion FROM LISTADOS_VISIBILIDAD{c} WHERE IdUsuario={1}))", cmbReport.selectedKey, 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: '', condition: '', 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.condition=item.Valor;
								break;
							case 'Condicion':
								params.condition.id=item.Valor;
								break;
							case 'SeleccionBolsas':
								params.columns.push(item.Valor);
								break;								
							default: 
								params[$.Strings.StripAccents(item.Tipo)]=item.Valor;
								break;
						}
					}
				}
				else{ $.Debug.Add(this.text); }
				
				if(cmbReport.selectedKey=='09'){
					//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];
							switch(item.Tipo){
								case 'TotalAttendance': case 'StandardHours':
									params.columns.push([item.Nombre, item.Tipo, item.Valor, item.Tipo]);
									break;
								case 'Formula':
									if($.isDefined(aFormulas[item.Valor])){ params.columns.push([item.Nombre, item.Tipo, item.Valor, aFormulas[item.Valor].Value]); }
									break;
								default:
									params.columns.push([item.Nombre, item.Tipo, item.Valor, 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.Alias, 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);
			
			cmbFromDate.SetValue(values.FechaDesde);
			cmbToDate.SetValue(values.FechaHasta);
			
			switch(cmbReport.selectedKey) {
				case '09':
					Load_Report_Config_Time_Payroll(values);
					break;
				case '10':
					Load_Report_Config_Accruals(values);
					break;
			}
		}
		function Load_Report_Config_Time_Payroll(values){
			cmbGroupDate.SetSelectedKey(values.Desglose);
			cmbViewPunches.SetSelectedKey(values.VerFichajes);
			
			chkPagePerEmployee.SetCheck(values.PaginaPorEmpleado==1);
			chkViewWeeklyTotal.SetCheck(values.TotalizarSemanalmente==1);
			
			chkShowValuation.SetCheck(values.ValoracionCostes==1);
			chkViewMonthlyTotal.SetCheck(values.TotalizarMensualmente==1);
			chkShowAllDays.SetCheck(values.MostrarTodosLosDias==1);
			
			chkViewEmployeeTotal.SetCheck(values.TotalEmpleado==1);
			chkEmployeeDutyTime.SetCheck(values.HorasEstandarMantenimiento==1);
			
			winCC.columns=values.columns;
			
			winCondition.Load(values.condition);
		}
		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;
		}
		function Load_Report_Config_Accruals(values){
			cmbGroup.SetSelectedKey(values.AgruparPor);
			cmbTerm.SetSelectedKey(values.Periodo);
			
			cmbMonth.SetSelectedKey(values.Mes);
			cmbYear.SetSelectedKey(values.Anho);
			
			cmbFromWeek.SetSelectedKey(values.DesdeSemana);
			cmbToWeek.SetSelectedKey(values.HastaSemana);
			
			chkEmployeePage.SetCheck(values.PaginaPorEmpleado==1);
			chkTotal.SetCheck(values.VerTotal==1);
			
			
			for(var key in values.columns){
				aAccruals[values.columns[key]].show = true;
			}
		}
	}
	{//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);
			SaveReportField(is_new, key, 'FechaDesde', cmbFromDate.GetValue());
			SaveReportField(is_new, key, 'FechaHasta', cmbToDate.GetValue());
			
			switch(cmbReport.selectedKey){
				case '09':
					SaveReportField(is_new, key, 'Desglose', cmbGroupDate.selectedKey);
					SaveReportField(is_new, key, 'VerFichajes', cmbViewPunches.selectedKey);
					SaveReportField(is_new, key, 'PaginaPorEmpleado', (chkPagePerEmployee.GetCheck()?1:0));
					SaveReportField(is_new, key, 'TotalizarSemanalmente', (chkViewWeeklyTotal.GetCheck()?1:0));
					SaveReportField(is_new, key, 'ValoracionCostes', (chkShowValuation.GetCheck()?1:0));
					SaveReportField(is_new, key, 'TotalizarMensualmente', (chkViewMonthlyTotal.GetCheck()?1:0));
					SaveReportField(is_new, key, 'MostrarTodosLosDias', (chkShowAllDays.GetCheck()?1:0));
					SaveReportField(is_new, key, 'TotalEmpleado', (chkViewEmployeeTotal.GetCheck()?1:0));
					SaveReportField(is_new, key, 'HorasEstandarMantenimiento', (chkEmployeeDutyTime.GetCheck()?1:0));

					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[0], column[1], column[2]]);
					}
					
					var conditionid=is_new?$.DateTime.Ticks():winCondition.values.id;
					
					$.AjaxDBSave('LISTADOS_FOR{c}', ['Id', 'Valor', 'Tipo'], [conditionid, winCondition.values.formula, 'Logic'], is_new?null:"Id='"+conditionid+"'");
					SaveReportField(is_new, key, 'Condicion',  conditionid);
					SaveReportField(is_new, key, 'AplicarCondicion',  winCondition.values.condition);
					
					if(!is_new && conditionid != ""){ $.AjaxDBDelete("LISTADOS_FOR_COL{c}", 'IdFormula='+conditionid); }
					
					for(var i=0, ilen=winCondition.values.columns.length; i<ilen; i++){
						var row=winCondition.values.columns[i];
						$.AjaxDBSave('LISTADOS_FOR_COL{c}', 
						['IdFormula', 'Nombre', 'Alias', 'Tipo', 'Valor'], 
						[conditionid, row[1], row[0], row[2], row[3]]);
					}
					
					break;
				case '10':
					$.AjaxDBDelete('LISTADOS_FILTROS{c}', "IdListado='"+key+"' AND Tipo='SeleccionBolsas'");
					SaveReportField(is_new, key, 'AgruparPor', cmbGroup.selectedKey);
					SaveReportField(is_new, key, 'Periodo', cmbTerm.selectedKey);
					SaveReportField(is_new, key, 'Mes', cmbMonth.selectedKey);
					SaveReportField(is_new, key, 'Anho', cmbYear.selectedKey);
					SaveReportField(is_new, key, 'DesdeSemana', cmbFromWeek.selectedKey);
					SaveReportField(is_new, key, 'HastaSemana', cmbToWeek.selectedKey);
					SaveReportField(is_new, key, 'PaginaPorEmpleado', (chkEmployeePage.GetCheck()?1:0));
					SaveReportField(is_new, key, 'VerTotal', (chkTotal.GetCheck()?1:0));
					
					for(var i in aAccruals){
						if(aAccruals[i].show){
							$.AjaxDBSave('LISTADOS_FILTROS{c}', ['IdListado', 'Tipo', 'Valor'], [key, 'SeleccionBolsas', aAccruals[i].Codigo]);
						}
					}
					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 reportType = "";
			switch(cmbReport.selectedKey){
				case '09':
					reportType='time_payroll';
					break;
				case '10':
					reportType='accruals';
					break;
			}	
			var report = new $.Report(reportType);
			report.AddValue('title',txtTitle.GetText());
			report.Show(true);
		}	
	}
	{//Eventos: Tiempos y costes
			cmbGroupDate.onchangekey=function(){
			$.FX.Hide(chkEmployeeDutyTime);
			$.FX.Hide(chkViewWeeklyTotal);
			$.FX.Hide(chkViewMonthlyTotal);
			$.FX.Hide(chkViewEmployeeTotal);
			switch(cmbGroupDate.selectedKey){
				case '1':
					$.FX.Show(chkViewWeeklyTotal);
					$.FX.Show(chkViewMonthlyTotal);
					$.FX.Show(chkViewEmployeeTotal);				
					break;
				case '2':
					$.FX.Show(chkViewEmployeeTotal);				
					break;
				case '3':
					$.FX.Show(chkViewEmployeeTotal);				
					$.FX.Show(chkEmployeeDutyTime);
					break;
			}
		}
	}
	{//Eventos: Bolsas
		function GetWeeks(){
			var weeksYear=$.DateTime.WeeksInYear(cmbYear.selectedKey);
			for(var i=1; i<=weeksYear;i++){
				cmbFromWeek.AddItem($.DateTime.WeekFormat(i,cmbYear.selectedKey),i);
				cmbToWeek.AddItem($.DateTime.WeekFormat(i,cmbYear.selectedKey),i);
			}
			cmbFromWeek.SetSelectedKey('1');
			cmbToWeek.SetSelectedKey(weeksYear);
		}
		
		cmbTerm.onchangekey = function(){
			HideTermElements();
			switch(cmbTerm.selectedKey){
				case '3': case '4':
					$.FX.Show(lblFromDate);
					$.FX.Show(cmbFromDate);
					$.FX.Show(lblToDate);
					$.FX.Show(cmbToDate);
					break;
				case '0':
					$.FX.Show(lblYear);
					$.FX.Show(cmbYear);
					$.FX.Show(lblFromWeek);
					$.FX.Show(cmbFromWeek);
					$.FX.Show(lblToWeek);
					$.FX.Show(cmbToWeek);
					break;
				case '1':
					$.FX.Show(lblMonth);
					$.FX.Show(cmbMonth);
					$.FX.Show(lblYear);
					$.FX.Show(cmbYear);
					break;
				case '2':
					$.FX.Show(lblYear);
					$.FX.Show(cmbYear);
					break;
			}
		}

		cmbYear.onchangekey=function(){
			if(cmbTerm.selectedKey=='1') { GetWeeks(); }
		}

		function HideTermElements(){
			$.FX.Hide(lblFromDate);
			$.FX.Hide(cmbFromDate);
			$.FX.Hide(lblToDate);
			$.FX.Hide(cmbToDate);
			
			$.FX.Hide(lblYear);
			$.FX.Hide(cmbYear);
			$.FX.Hide(lblMonth);
			$.FX.Hide(cmbMonth);

			$.FX.Hide(lblFromWeek);
			$.FX.Hide(cmbFromWeek);
			$.FX.Hide(lblToWeek);
			$.FX.Hide(cmbToWeek);
		}	
	}
	{//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; }
			}
		}
	}
	{//Columnas: Bolsas
		var accrualsWindow = new $.Objects.Window(500,460);
		
		var lblAccrualsWindow = new $.Objects.Text($.lng('accrual_selection')+':');
		lblAccrualsWindow.Location(10,10,480,20);
		lblAccrualsWindow.Add(accrualsWindow);
		
		var chkAccrualsWindow = new $.Objects.CheckBox($.lng('select_all'));
		chkAccrualsWindow.Location(10,30,480,20);
		chkAccrualsWindow.Add(accrualsWindow);
		chkAccrualsWindow.SetCheck(true);
		chkAccrualsWindow.onchange=function(){
			var chk_status=chkAccrualsWindow.GetCheck();
			for(var i in grAccrualsWindow.rows){
				grAccrualsWindow.rows[i].cells[0].references.object.SetCheck(chk_status);
			}
		}
		
		var cmAccrualsWindow = new $.Grids.ColumnModel({editable: false});
		cmAccrualsWindow.Add(new $.Grids.SpecialCheckColumn({key: 'code', text:'', width: '22'}));
		cmAccrualsWindow.Add(new $.Grids.SimpleColumn({key: 'description', text: $.lng('description'), width: '350'}));
		
		var grAccrualsWindow = new $.Grids.Grid(cmAccrualsWindow);
		grAccrualsWindow.Location(10,50,480,370);
		grAccrualsWindow.Add(accrualsWindow);
		
		var cmdAccrualsWindowAccept=$.ControlAdd('button_icon', [10,430,235,22], accrualsWindow, {text: $.lng('accept'), icon: 'size16 accept'});
		var cmdAccrualsWindowCancel=$.ControlAdd('button_icon', [255,430,235,22], accrualsWindow, {text: $.lng('cancel'), icon: 'size16 cancel'});

		cmdAccrualsWindowAccept.onclick=function() {
			for(var i in grAccrualsWindow.rows){
				var row = grAccrualsWindow.rows[i];
				aAccruals[row.key].show=row.cells[0].references.object.GetCheck();
			}
			accrualsWindow.Hide();
		}
		
		cmdAccrualsWindowCancel.onclick=function(){
			accrualsWindow.Hide();
		}
	}
	{//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); }

	cmbFromDate.SetValue(strYear+strMonth+'01');
	cmbToDate.SetValue(strYear+strMonth+strLastDay);
	$.FX.Hide(divAccruals);
	$.FX.Hide(divTimePayrolls);
	switch(cmbReport.selectedKey){
		case '09':
			$.FX.Show(divTimePayrolls)
			DefaultValues_Time_Payroll();
			break;
		case '10':
			$.FX.Show(divAccruals);
			DefaultValues_Accruals();
			break;
	}
}
function DefaultValues_Accruals(){
	var strYear = $.DateTime.CurrentYear();
	var strMonth = $.Strings.PadLeft($.DateTime.CurrentMonth(),'0',2);
	cmbGroup.SetSelectedIndex(0);
	cmbTerm.SetSelectedIndex(0);
	cmbMonth.SetSelectedKey(strMonth);
	cmbYear.SetSelectedKey(strYear);
	GetWeeks();
	chkEmployeePage.SetCheck(false);
	chkTotal.SetCheck(false);
	for(var i in aAccruals){
		aAccruals[i].show=false; 
	}
}
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);
	winCC.Clear();
	winCondition.Clear();
	
	/*
	db=$.AjaxDB("SELECT F.*, C.Nombre FROM LISTADOS_FOR{c} F INNER JOIN LISTADOS_COLUMNAS{c} C ON F.Id=C.Valor WHERE C.IdListado=0 ORDER BY C.Orden", Ajax.Wait);
	error=db.json.error;
	if(!db.json.error){
		aFormulas=[];
		for(var i=0,iLen=db.json.row.length;i<iLen;i++){
			var item=db.json.row[i];
			aFormulas[item.Id]={};
			aFormulas[item.Id].Codigo=item.Id;
			aFormulas[item.Id].Value=item.Valor;
			aFormulas[item.Id].Text=item.Nombre;
		}
	}
	else{ $.Debug.Add(db.text); }
	*/
}
cmbReport.onchangekey=function(){
	DefaultValues();
	Load_Report_List();
	cmbTerm.onchangekey();
}
cmbReport.AddItem($.lng('reports_time_payroll'),'09');
cmbReport.AddItem($.lng('reports_accrueds'),'10');	

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+"'");  }
}