var options={};

var aEmployees=[], aTerminals=[], aEvents=[], aTotal=[], aPunches=[];

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.fromDate=opener.cmbFromDate.value;
	options.toDate=opener.cmbToDate.value;

	options.fromTime=opener.cmbFromTime.GetValue();
	options.toTime=opener.cmbToTime.GetValue();
	options.event=opener.cmbEvents2.selectedKey;
	options.eventValue=opener.cmbEvents2.value;
	options.terminal=opener.cmbTerminals.selectedKey;
	options.terminalValue=opener.cmbTerminals.value;
	options.orderby=opener.cmbOrder2.selectedKey;
	options.orderbyValue=opener.cmbOrder2.value;
}
function Report_Load_Model() {
	report.AddStyle('title','color:#592D00; font-size: 14pt; font-weight: bold; font-style: italic;');
	report.AddStyle('header_label','color:#592D00; font-weight: bold;');
	report.AddStyle('header_value','color:#592D00; font-style: italic;');
	report.AddStyle('headers','background: #E8E8E8 url(design.report.png) repeat-x 0 0; font-weight: bold;');
	report.AddStyle('employee','background: #DEDEDE url(design.report.png) repeat-x 0 -24px;');
	report.AddStyle('values.pair','background:#F0F0F0;');

	report.AddTable('title',{height: 30, border_top: true, border_left: true, border_right: true, border_color: '#EEE', className: 'title'});
	report.tables['title'].Add();
	
	report.AddTable('head_single',{height: 16});
	report.tables['head_single'].Add({width: 100, 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: 100, border_left: true, border_color: '#EEE', className: 'header_label'});
	report.tables['head_double'].Add({width: 275, 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'});

	report.AddTable('head_issue',{height: 16});
	report.tables['head_issue'].Add({width: 100, border_left:true, border_color:'#EEE', className: 'header_label'});
	report.tables['head_issue'].Add({width: 400, className: 'header_value'});
	report.tables['head_issue'].Add({width: 140, className: 'header_label'});
	report.tables['head_issue'].Add({border_right:true, border_color: '#EEE', className: 'header_value'});
	
	report.AddTable('headers',{className: 'headers', height: 24});
	report.tables['headers'].Add({width: 90});
	report.tables['headers'].Add({width: 55});
	if(options.orderby=='1'){ report.tables['headers'].Add({width: 250}); }
	report.tables['headers'].Add({width: 140});
	report.tables['headers'].Add({width: 140});
	
	report.tables['headers'].Add({width: 60});
	
	report.AddTable('employees',{className: 'employee', border_left:true, border_right:true, border_color: '#D9D9D9'});
	report.tables['employees'].Add();

	report.AddTable('values',{className: 'values'});
	report.tables['values'].Add({width: 90});
	report.tables['values'].Add({width: 55});
	if(options.orderby=='1'){ report.tables['values'].Add({width: 250}); }
	report.tables['values'].Add({width: 140});
	report.tables['values'].Add({width: 140});
	report.tables['values'].Add({width: 60});
	
	//if(options.orderby=='1'){ report.orientation=1; }
}
function Report_Load_Data() {

	{ //Select events
		var ajaxEvents = new Ajax("SELECT * FROM INCIDENCIAS{c} ORDER BY Codigo");
		ajaxEvents.oncomplete=function(){
			aEvents=[];
			for(var i in this.json.row) {
				var item=this.json.row[i];
				aEvents[item.Codigo]={};
				aEvents[item.Codigo].code=item.Codigo;
				aEvents[item.Codigo].description=item.Descripcion;
				aEvents[item.Codigo].text=item.Codigo+' - '+item.Descripcion;
			}
		}
	}
	{ //Select terminals
		var ajaxTerminals = new Ajax("SELECT * FROM TERMINALES{c} ORDER BY Codigo");
		ajaxTerminals.oncomplete=function() {
			aTerminals=[];
			for(var i in this.json.row) {
				var item=this.json.row[i];
				aTerminals[item.Codigo]={};
				aTerminals[item.Codigo].code=item.Codigo;
				aTerminals[item.Codigo].description=item.Descripcion;
				aTerminals[item.Codigo].text=item.Codigo+' - '+item.Descripcion;
			}
		}
	}

	{ //Select all data
		var whereItems = [];
		whereItems.push("f.Fecha>='"+options.fromDate+"' AND f.Fecha<='"+options.toDate+"'");
		whereItems.push("f.Hora>='"+options.fromTime+"' AND f.Hora<='"+options.toTime+"'");
		
		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 + "'"); }
		if(options.event != 'All') { whereItems.push("f.IdIncidencia = '" + options.event + "'"); }
		if(options.terminal != 'All') { whereItems.push("f.IdTerminal = '" + options.terminal + "'"); }
		
		var ajaxData = new Ajax(Convert.Format("SELECT f.*, e.Nombre, e.Apellidos FROM FICHAJES{c} f INNER JOIN EMPLEADOS{c} e ON e.Codigo = f.IdEmpleado WHERE {0} ORDER BY IdEmpleado,Fecha,Hora ASC",whereItems.join(" AND ")));
		ajaxData.oncomplete = function() {
			for(var i in this.json.row) {
				var db = this.json.row[i];
				if(IsInEmployees(db.IdEmpleado)) {
					if(typeof(aEmployees[db.IdEmpleado])=="undefined"){ aEmployees[db.IdEmpleado]={text: db.IdEmpleado+' - '+db.Nombre+' '+db.Apellidos, checks: []}; }
					aPunches.push({
						employee: db.IdEmpleado,
						date: db.Fecha,
						time: db.Hora,
						event: aEvents[db.IdIncidencia].text,
						terminal: (typeof(aTerminals[db.IdTerminal])!="undefined")?aTerminals[db.IdTerminal].text:LngStr('unknown'),
						denny: 0
					});
				}
			}
		}
		
		var ajaxData2 = new Ajax(Convert.Format("SELECT f.*, e.Nombre, e.Apellidos FROM FICHAJES_ACCESO{c} f INNER JOIN EMPLEADOS{c} e ON e.Codigo = f.IdEmpleado WHERE {0} ORDER BY IdEmpleado,Fecha,Hora ASC", whereItems.join(" AND ")));
		ajaxData2.oncomplete = function() {
			for(var i in this.json.row) {
				var db = this.json.row[i];
				if(IsInEmployees(db.IdEmpleado)) {
					if(typeof(aEmployees[db.IdEmpleado])=="undefined"){ aEmployees[db.IdEmpleado]={text: db.IdEmpleado+' - '+db.Nombre+' '+db.Apellidos, checks: []}; }
					aPunches.push({
						employee: db.IdEmpleado,
						date: db.Fecha,
						time: db.Hora,
						event: aEvents[db.IdIncidencia].text,
						terminal: (typeof(aTerminals[db.IdTerminal])!="undefined")?aTerminals[db.IdTerminal].text:LngStr('unknown'),
						denny: db.Denegado
					});
				}
			}
		}
	}
	
	
	AjaxManager.Create('basic');
	AjaxManager.Create('data');
	AjaxManager.group['basic'].Add(ajaxEvents);
	AjaxManager.group['basic'].Add(ajaxTerminals);
	AjaxManager.group['data'].Add(ajaxData);
	AjaxManager.group['data'].Add(ajaxData2);
	
	AjaxManager.group['basic'].Start();
	AjaxManager.group['basic'].oncomplete=function() {
		AjaxManager.group['data'].Start();
	}

}
function Report_Process_Data() {
	report.SetSection('head');
	report.Add('title',[options.title]);
	report.AddSpace(5,'head_single');
	report.Add('head_single',[LngStr('company',true),COMPANY.code+' - '+COMPANY.description]);
	report.Add('head_double',[LngStr('from',true),options.fromEmployeeValue,LngStr('to',true),options.toEmployeeValue]);
	report.Add('head_double',[COMPANY.department+':',options.departmentValue,COMPANY.center+':',options.centerValue]);
	report.Add('head_double',[LngStr('from_date',true),Convert.Date(options.fromDate),LngStr('to_date',true),Convert.Date(options.toDate)]);
	report.Add('head_double',[LngStr('from_time',true),Convert.Time(options.fromTime),LngStr('to_time',true),Convert.Time(options.toTime)]);
	report.Add('head_double',[LngStr('event',true),options.eventValue,LngStr('terminal',true),options.terminalValue]);
	
	report.AddSpace(10,true);
	
	if(options.orderby==0){ report.Add('headers',[LngStr('date'), LngStr('hour'), LngStr('event'), LngStr('terminal'), LngStr('denny')]); }
	else{ report.Add('headers',[LngStr('date'), LngStr('hour'), LngStr('employee'), LngStr('event'), LngStr('terminal'), LngStr('denny')]); }
	
	report.SetSection('body');
	
	aPunches.sort(function(a, b){
		var x=((options.orderby==0)?a.employee:'')+''+a.date+''+a.time;
		var y=((options.orderby==0)?b.employee:'')+''+b.date+''+b.time;
		
		if(x<y){ return -1; }
		else if(x>y){ return 1; }
		else{ return 0; }
	});
	var last_date='';
	var last_employee='';
	
	
	for(var i in aPunches){
		var p=aPunches[i];
		var date=(last_date==p.date)?'':Convert.Date(p.date, true);
		var time=Convert.Time(p.time, true);
		var employee=aEmployees[p.employee].text;
		var denny=p.denny==0?LngStr('no'):LngStr('yes')
		
		if(options.orderby==0){
			if(last_employee!=p.employee){
				date=Convert.Date(p.date, true);
				report.Add('employees',['<div class="arrow"></div> '+employee]); 
			}
			
			report.Add('values', [date, time, p.event, p.terminal, denny]);
		}
		else{ report.Add('values', [date, time, employee, p.event, p.terminal, denny]); }
		
		last_employee=p.employee;
		last_date=p.date;
	}
}