var options={};
var aEmployees=[],aAccruals=[],aEvents=[],aWorkdays=[],aPayrolls=[],aColumns=[],aFields=[], aFieldAccruals=[],aFieldPayrolls=[];
var FieldName={TotalPresencia: 'TOTALATTENDANCE', HorasEstandar: 'STANDARDHOURS', Acumulador: 'ACCRUALS', Coste: 'PAYROLL'};
var headerHeight=23;

function Report_Load_Vars() {
	options.title=opener.txtTitle.GetText();
	options.fromEmployee=opener.cmbFromEmployee.selectedKey;
	options.fromEmployeeValue=opener.cmbFromEmployee.value;
	options.toEmployee=opener.cmbToEmployee.selectedKey;
	options.toEmployeeValue=opener.cmbToEmployee.value;
	options.department=opener.cmbDepartment.selectedKey;
	options.departmentValue=opener.cmbDepartment.value;
	options.center=opener.cmbCenter.selectedKey;
	options.centerValue=opener.cmbCenter.value;
	
	options.month=opener.cmbMonth.selectedKey;
	options.monthValue=opener.cmbMonth.value;
	options.year=opener.cmbYear.selectedKey;
	options.yearValue=opener.cmbYear.value;

	aAccruals=opener.aAccruals;
	aPayrolls=opener.aPayrolls;
	aColumns=opener.winCC.columns;
	
	{//Presence period
		var ajaxPeriod=new Ajax("SELECT Desde,Hasta FROM PERIODOS_PRESENCIA{c} WHERE Mes='"+Convert.PadLeft(options.month, '0', 2)+"'", true);
		if(!ajaxPeriod.json.error){
			var fromDate=options.year+options.month+'01';
			var toDate=options.year+options.month+'31';
			
			if(ajaxPeriod.json.row.length!=0){
				var item=ajaxPeriod.json.row[0];
				fromDate=item.Desde;
				toDate=item.Hasta;
				if(fromDate>toDate){
					if(options.month=='01'){
						fromDate = (options.year-1)+fromDate;
						toDate = options.year+toDate;
					}
					else if(option.month=='12'){
						fromDate = options.year+fromDate;
						toDate = (options.year+1)+toDate;
					}
				}
				else{
					fromDate = options.year+fromDate;
					toDate = options.year+toDate;
				}
			}
			options.fromDate=fromDate;
			options.toDate=toDate;
		}
	}
}
function Report_Load_Model() {
	{//Title---------------------------------------------------------------------------------------------------------------------------------------------------------------------
		report.AddStyle('title','color:#592D00; font-size: 14pt; font-weight: bold; font-style: italic;');
		report.AddTable('title',{height: 30, border_top: true, border_left: true, border_right: true, border_color: '#EEE', align: 'center', className: 'title'});
		report.tables['title'].Add();
	}
	{//Head----------------------------------------------------------------------------------------------------------------------------------------------------------------------
		report.AddStyle('header_label','color:#592D00; font-weight: bold;');
		report.AddStyle('header_value','color:#592D00; font-style: italic;');
		
		report.AddTable('head_single',{height: 16});
		report.tables['head_single'].Add({width: 150, border_left: true, border_color: '#EEE', className: 'header_label'});
		report.tables['head_single'].Add({border_right: true, border_color: '#EEE', className: 'header_value'});
		
		report.AddTable('head_double',{height: 16});
		report.tables['head_double'].Add({width: 150, border_left: true, border_color: '#EEE', className: 'header_label'});
		report.tables['head_double'].Add({width: 500, className: 'header_value'});
		report.tables['head_double'].Add({width: 100, className: 'header_label'});
		report.tables['head_double'].Add({border_right: true, border_color: '#EEE', className: 'header_value'});
	}
	{//Column headers------------------------------------------------------------------------------------------------------------------------------------------------------------
		report.AddStyle('headers1','font-size: 7pt; background: #E3E3E3 url(design.header.png) repeat-x 0 -1px;');
		report.AddTable('headers1',{className: 'headers1', height: 20,padding: 0, border_top: true, border_bottom: true, border_right: true, border_color: '#AAA', border_bottom_color: '#E3E3E3'});
		report.tables['headers1'].Add({width: 112, border_left: true});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 147, align: 'center', border_bottom_color: '#AAA'});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		report.tables['headers1'].Add({width: 49});
		
		
		report.AddStyle('headers2','font-size: 7pt; background: #E3E3E3');
		report.AddTable('headers2',{className: 'headers2', height: 65, padding: 0, align: 'center', border_right: true, border_color: '#AAA'});
		report.tables['headers2'].Add({width: 112, border_left: true});
	
		report.AddStyle('headers3','background: #E3E3E3 url(design.header.png) repeat-x 0 -1px');
		report.AddTable('headers3',{className: 'headers3', height: 20, padding: 0, align: 'center', border_top: true, border_bottom: true, border_right: true, border_color: '#888'});
		report.tables['headers3'].Add({width: 112, border_left: true});
	}
	{//Values--------------------------------------------------------------------------------------------------------------------------------------------------------------------
		report.AddStyle('values','font-size: 9pt;');
		report.AddStyle('yellow','background: #FF6;');
		report.AddStyle('red','background: #F60;');
		report.AddTable('values',{className: 'values', padding: 4, border_bottom: true, border_right: true, border_color: '#444'});
		report.tables['values'].Add({className: 'values yellow', width: 112, border_left: true });
	}
	{//Total----------------------------------------------------------------------------------------------------------------------------------------------------------------
		report.AddStyle('total','background: #FFC000; font-size: 9pt;');
		report.AddTable('total',{className: 'total', padding: 4, border_bottom:true, border_right: true, border_color: '#444'});
		report.tables['total'].Add({width: 112, border_left: true});
	}
	
	for(var i=0,iLen=19;i<=iLen;i++){
		report.tables['headers2'].Add({width: 49, border_color: '#AAA'});
		report.tables['headers3'].Add({width: 49, border_color: '#888'});
		
		if(i!=2){
			report.tables['values'].Add({width: 49}); 
			report.tables['total'].Add({width: 49});
		}
		else{
			report.tables['values'].Add({className: 'values red', width: 49}); 
			report.tables['total'].Add({className: 'total red', width: 49});
		}
		
	}
	report.orientation=1;
}
function Report_Load_Data(){
	AjaxManager.Create('basic');
	AjaxManager.Create('closure');
	AjaxManager.Create('data');
	{//Get formula fields--------------------------------------------------------------------------------------------------------------------------------------------------------
		for(var i=0,iLen=aColumns.length; i<iLen; i++){
			var column=aColumns[i];
			if(column[2]=='Formula'){
				column.formula=column[4];
				var ajaxFormula=new Ajax("SELECT * FROM LISTADOS_FOR_COL{c} WHERE IdFormula='"+column[3]+"' ORDER By Alias", true);
				if(!ajaxFormula.json.error){
					for(var j=0,jLen=ajaxFormula.json.row.length;j<jLen;j++){
						var item=ajaxFormula.json.row[j];
						switch(item.Tipo){
							case 'TotalAttendance': case 'StandardHours':
								column.formula=column.formula.replace(new RegExp(item.Alias,'g'), item.Tipo.toUpperCase());
							default:
								column.formula=column.formula.replace(new RegExp(item.Alias,'g'), item.Tipo.toUpperCase()+item.Valor);
								break;
						}
					}
				}
			}
			else{ column.formula=column[4].toUpperCase(); }
		}
		
		if(isFieldUsed(FieldName.TotalPresencia)){ aFields.push(FieldName.TotalPresencia); }
		if(isFieldUsed(FieldName.HorasEstandar)){ aFields.push(FieldName.HorasEstandar); }
		for(var i in aAccruals){
			var name=FieldName.Acumulador+i;
			if(isFieldUsed(name)){
				aFields.push(name);
				aFieldAccruals.push(i);
			}
		}
		for(var i in aPayrolls){
			var name=FieldName.Coste+i;
			if(isFieldUsed(name)){
				aFields.push(name);
				aFieldPayrolls.push(i);
			}
		}
	}
	{//Basic---------------------------------------------------------------------------------------------------------------------------------------------------------------------
		{//Events---------------------------------------------------------------------------------------------------------------------------------------------------------------------
			var ajaxEvents = new Ajax("SELECT Codigo,Descripcion FROM INCIDENCIAS{c} ORDER BY Codigo");
			AjaxManager.group['basic'].Add(ajaxEvents);
			ajaxEvents.oncomplete=function(){
				if(!this.json.error){
					for(var i=0,iLen=this.json.row.length;i<iLen;i++){
						var item=this.json.row[i];
						aEvents[item.Codigo]={ text: item.Codigo+' - '+item.Descripcion }
					}
				}
				else{ alert(this.text); }
			}
		}
		{//Workdays-------------------------------------------------------------------------------------------------------------------------------------------------------------------
			var ajaxWorkdays = new Ajax("SELECT Codigo,Descripcion FROM HORARIOS{c} ORDER BY Codigo");
			AjaxManager.group['basic'].Add(ajaxWorkdays);
			ajaxWorkdays.oncomplete=function(){
				if(!this.json.error){
					for(var i=0,iLen=this.json.row.length;i<iLen;i++){
						var item=this.json.row[i];
						aWorkdays[item.Codigo]={ text: item.Codigo+' - '+item.Descripcion }
					}
				}
				else{ alert(this.text); }
			}
		}
	}
	{//Where---------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var whereItems=[];
		if (options.fromEmployee != 'All') {
			if(options.toEmployee=='None') { whereItems.push("e.Codigo = '"+options.fromEmployee+"'"); }
			else { whereItems.push("e.Codigo >= '"+options.fromEmployee+"' AND e.Codigo <= '"+options.toEmployee+"'"); }
		}
		if(options.department != 'All') { whereItems.push("e.IdUbicacion = '" + options.department + "'"); }
		if(options.center != 'All') { whereItems.push("e.IdCentro = '" + options.center + "'"); }
		var whereClausule = whereItems.join(' AND ');
		if(whereClausule!=''){ whereClausule=' AND '+whereClausule; }
	}
	{//Closure-------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var sql="SELECT c.IdEmpleado, e.Nombre, e.Apellidos, c.Fecha, c.Fecha, c.Semana, c.Mes, c.Anho, c.Incidencia, c.TipoDia, c.Total, c.HorasEstandar "+
		"FROM CIERRE{c} c INNER JOIN EMPLEADOS{c} e ON e.Codigo = c.IdEmpleado "+
		"WHERE c.TipoDia <> 'D' AND c.Mes = '{0}' AND c.Anho = '{1}' {2} ORDER BY c.IdEmpleado, c.Fecha ASC";
		var ajaxClosure = new Ajax(Convert.Format(sql, options.month, options.year, whereClausule));
		AjaxManager.group['closure'].Add(ajaxClosure);
		ajaxClosure.oncomplete=function(){
			for(var i=0,iLen=this.json.row.length;i<iLen;i++){
				var item=this.json.row[i];
				var id=item.IdEmpleado;
				var date=item.Fecha;
				if(IsInEmployees(id)){
					if(typeof(aEmployees[id])=="undefined"){
						aEmployees[id]={code: item.IdEmpleado, name: item.Nombre+' '+item.Apellidos,text: item.IdEmpleado+' - '+item.Nombre+' '+item.Apellidos, dates: [], duttytime: []};
					}
					aEmployees[id].dates[date]={
						Incidencia: item.Incidencia,
						TipoDia: item.TipoDia,
						Semana: item.Semana,
						Mes: item.Mes,
						Anho: item.Anho,
						fields:{},
						checks:[]
					};
					for(var x=0,xLen=aFields.length;x<xLen;x++){
						aEmployees[id].dates[date].fields[aFields[x]]=0;
					}
					aEmployees[id].dates[date].fields[FieldName.TotalPresencia]=item.Total;
					aEmployees[id].dates[date].fields[FieldName.HorasEstandar]=item.HorasEstandar;
				}
			}
		}
	}
	{//Data----------------------------------------------------------------------------------------------------------------------------------------------------------------------
		whereClausule=whereClausule.replace(new RegExp('e.Codigo','gi'),"c.IdEmpleado");
		whereClausule=whereClausule.replace(new RegExp('e.Codigo','gi'),"c.IdEmpleado");
		
		{//Dutytime--------------------------------------------------------------------------------------------------------------------------------------------------------------
			var ajaxDutytime=new Ajax(Convert.Format("SELECT * FROM EMPLEADOS_HORAS_ESTANDAR{c} c WHERE c.Anho>='{0}' AND c.Mes>='{1}' {2}", options.year, options.month, whereClausule));
			AjaxManager.group['data'].Add(ajaxDutytime);
			ajaxDutytime.oncomplete=function(){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					if(typeof(aEmployees[item.IdEmpleado])!="undefined"){
						aEmployees[item.IdEmpleado].duttytime[item.Anho+item.Mes]=item.Total;
					}
				}
			}
		}
		
		{//Checks----------------------------------------------------------------------------------------------------------------------------------------------------------------
			var ajaxChecks= new Ajax(Convert.Format("SELECT c.IdEmpleado, FechaValor,Hora, IdIncidencia, IdTerminal FROM FICHAJES{c} c INNER JOIN EMPLEADOS{c} e ON e.Codigo = c.IdEmpleado "+
			"WHERE c.FechaValor>='{0}' AND c.FechaValor<='{1}' AND Cerrado='1' {2} ORDER BY IdEmpleado,FechaValor,Hora", options.fromDate, options.toDate, whereClausule));
			AjaxManager.group['data'].Add(ajaxChecks);
			ajaxChecks.oncomplete=function(){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					var id=item.IdEmpleado;
					var date = item.FechaValor;
					if(typeof(aEmployees[id])!="undefined" && typeof(aEmployees[id].dates[date])!="undefined"){
						aEmployees[id].dates[date].checks.push({Hora: item.Hora,IdIncidencia: item.IdIncidencia});
					}
				}
			}
		}
		{//Accruals--------------------------------------------------------------------------------------------------------------------------------------------------------------
			if(aFieldAccruals.length!=0){
				var sqlAccruals = " AND c.IdAcumulador";
				if(aFieldAccruals.length==1){ sqlAccruals+="='"+aFieldAccruals[0]+"'"; }
				else{ sqlAccruals+=" IN ('"+aFieldAccruals.join("','")+"')" }
				var ajaxAccruals = new Ajax(Convert.Format("SELECT IdEmpleado,IdAcumulador,Fecha,TotalTiempo FROM CIERRE_ACUMULADORES{c} c INNER JOIN EMPLEADOS{c} e ON e.Codigo = c.IdEmpleado "+
				"WHERE c.Mes = '{0}' AND c.Anho = '{1}'{2}{3} ORDER BY IdEmpleado,Fecha", options.month, options.year, whereClausule, sqlAccruals));
				AjaxManager.group['data'].Add(ajaxAccruals);
				ajaxAccruals.oncomplete=function(){
					for(var i=0, iLen=this.json.row.length; i<iLen; i++){
						var item=this.json.row[i];
						var id=item.IdEmpleado;
						var date=item.Fecha;
						if(typeof(aEmployees[id])!="undefined" && typeof(aEmployees[id].dates[date])!="undefined"){
							aEmployees[id].dates[date].fields[FieldName.Acumulador+item.IdAcumulador]=item.TotalTiempo;
						}
					}
				}
			}
		}
		{//Payrolls--------------------------------------------------------------------------------------------------------------------------------------------------------------
			if(aFieldPayrolls.length!=0){
				var sqlPayrolls = " AND c.IdCosteConcepto";
				if(aFieldPayrolls.length==1){ sqlPayrolls+="='"+aFieldPayrolls[0]+"'"; }
				else{ sqlPayrolls+=" IN ('"+aFieldPayrolls.join("','")+"')" }
				var ajaxPayrolls = new Ajax(Convert.Format("SELECT IdEmpleado,IdCosteConcepto,Fecha,Tiempo FROM CIERRE_COSTES{c} c INNER JOIN EMPLEADOS{c} e ON e.Codigo = c.IdEmpleado "+
				"WHERE c.Mes = '{0}' AND c.Anho <= '{1}'{2}{3} ORDER BY IdEmpleado,Fecha", options.month, options.year, whereClausule, sqlPayrolls));
				AjaxManager.group['data'].Add(ajaxPayrolls);
				ajaxPayrolls.oncomplete=function(){
					for(var i=0, iLen=this.json.row.length; i<iLen; i++){
						var item=this.json.row[i];
						var id=item.IdEmpleado;
						var date=item.Fecha;
						if(typeof(aEmployees[id])!="undefined" && typeof(aEmployees[id].dates[date])!="undefined"){
							aEmployees[id].dates[date].fields[FieldName.Coste+item.IdCosteConcepto]=item.Tiempo;
						}
					}
				}
			}
		}
	}
	
	AjaxManager.group['basic'].Start();
	AjaxManager.group['basic'].oncomplete=function(){ AjaxManager.group['closure'].Start(); }
	AjaxManager.group['closure'].oncomplete=function(){ AjaxManager.group['data'].Start(); }
}
function Report_Process_Data(){
	
	for(var i in aEmployees){
		var employee=aEmployees[i];
		var totColumns=[];
		{//Header--------------------------------------------------------------------------------------------------------------------------------------------------------------------
			report.SetSection('head');
			report.SetSection('body');
			report.Add('title',[options.title]);
			report.AddSpace(5,'head_double');
			report.Add('head_double',['Ime i prezime radnika:',employee.text,'Poslodavac:',COMPANY.description]);
			report.Add('head_single',['Godina:',options.yearValue]);
			report.Add('head_single',['Mjesec:',options.monthValue]);
			report.AddSpace(15,'head_double');
			report.Add('headers1',[' ',' ',' ','Dnevno radno vrijeme u satima','','','','','','','','','','','','','']);
			report.Add('headers2',['Datum','Početak rada (hh:mm)', 'Završetak rada (hh:mm)', 'Ukupno', 'Rad noću', 'Rad nedjeljom i blagdanom', 'Prekid rada bez odgovor nosti radnika',
			'Prekovre meni rad', 'Preraspo dijela radnog vremena', 'Izostanak / neradni dani i sl.', 'Sati priprav nosti', 'Godišnji odmor', 'Bolovanje',
			'Plaćeni dopust', 'Neplaćeni dopust', 'Izostanak / privatno', 'Štrajk', 'Isključenje s rada', 'Službeni put', 'Terenski rad', 'Porodiljnji i sl. dopusti']);
			report.Add('headers3',[' ','1','2','3','3.a','3.b','3.c','3.d','4','5','6','7','8','9','10','11','12','13','14','15','16']);
			
		}
		{//Body
			for(var x in employee.dates){
				var date = employee.dates[x];
				var valColumns=[];
				valColumns.push(Convert.Date(x, true, '.'));

				if(date.checks.length>0){ valColumns.push(Convert.Time(date.checks[0].Hora)); }
				else{ valColumns.push(''); }

				if(date.checks.length>1){ valColumns.push(Convert.Time(date.checks[date.checks.length-1].Hora)); }
				else{ valColumns.push(''); }
				
				totColumns.push('UKUPNO:');
				totColumns.push('');
				for(var y=0,yLen=17;y<=yLen;y++){
					var value=0;
					var column=aColumns[y];
					
					if(column.formula!="NONE" && column.formula!=""){
						if(column[2]!="Formula"){ value=date.fields[aColumns[y].formula]; }
						else{
							value=column.formula;
							for(var z=0,zLen=aFields.length;z<zLen;z++){
								var reg=new RegExp(aFields[z], 'gi');
								value=value.replace(reg,date.fields[aFields[z]]);
							}
							value=eval(value);
						}
					}
					value=Convert.Int(value)
					
					if(typeof(totColumns[y+3])=="undefined"){ totColumns[y+3]=0; }
					totColumns[y+3] += value;
					valColumns.push((value==0)?'':Convert.Minutes(value));
				}
				report.Add('values', valColumns);
			}
		}
		{//Total
			
			for(var y=3,yLen=20; y<=yLen; y++){
				totColumns[y] = Convert.Minutes(totColumns[y]);
			}
			report.Add('total', totColumns);
		}
		report.Add('@break');
	}
}

{//Functions--------------------------------------------------------------------------------------------------------------------------------------------------------------
	function isFieldUsed(value){
		for(var i=0,iLen=aColumns.length;i<iLen;i++){
			if(aColumns[i].formula.indexOf(value)>=0){
				return true; 
			}
		}
		return false;
	}
}