var options={};
var aEmployees=[];
var Term={Day:'3', Week: '0', Month: '1', Year: '2', None: '4'};

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.group=opener.cmbGroup.selectedKey;
	options.term=opener.cmbTerm.selectedKey;
	options.year=opener.cmbYear.selectedKey;
	options.month=opener.cmbMonth.selectedKey;
	options.fromWeek=opener.cmbFromWeek.selectedKey;
	options.fromWeekValue=opener.cmbFromWeek.value;
	options.toWeek=opener.cmbToWeek.selectedKey;
	options.toWeekValue=opener.cmbToWeek.value;
	options.fromDate=opener.cmbFromDate.value;
	options.toDate=opener.cmbToDate.value;
	options.employeePage=opener.chkEmployeePage.GetCheck();
	options.showTotal=opener.chkTotal.GetCheck();
}

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('group','background: linear-gradient(#EDEDED, #DDD);');
	
	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: 300});
	report.tables['headers'].Add({width: 100});
	report.tables['headers'].Add({width: 100});
	
	report.AddTable('employees',{className: 'employee', border_left:true, border_right:true, border_color: '#D9D9D9'});
	report.tables['employees'].Add();
	
	report.AddTable('group',{className: 'group'});
	report.tables['group'].Add();

	report.AddTable('values',{className: 'values'});
	report.tables['values'].Add({width: 300});
	report.tables['values'].Add({width: 100});
	report.tables['values'].Add({width: 100});	
}

function Report_Load_Data(){
	{ //Select Employees & Centers
		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 + "'"); }

		switch(options.term) {
			case Term.Day:
					whereItems.push("c.Fecha>='" + options.fromDate + "' AND c.Fecha<='" + options.toDate + "'");
					break;
				case Term.Week:
					whereItems.push("c.Semana>=" + options.fromWeek + " AND c.Semana<=" + options.toWeek + " AND c.Anho='" + options.year + "'");
					break;
				case Term.Month:
					whereItems.push("c.Anho='" + options.year + "' AND c.Mes=" + options.month);
					break;
				case Term.Year:
					whereItems.push("c.Anho='" + options.year + "'");
					break;
		}
		var whereClausule = whereItems.join(" AND ");
		if(whereClausule!="") { whereClausule=" WHERE "+whereClausule; }
		
		var orderClausule = (options.group=='Employee')?'e.Codigo':'e.IdUbicacion, e.IdCentro';

		var ajaxEmployees = new Ajax(Convert.Format("SELECT DISTINCT e.Codigo, e.Nombre, e.Apellidos, e.IdPerfil, c.IdAcumulador FROM (EMPLEADOS{c} e INNER JOIN CIERRE_ACUMULADORES{c} c ON e.Codigo = c.IdEmpleado) {0} ORDER BY {1}",whereClausule,orderClausule));
		ajaxEmployees.oncomplete=function(){
			aEmployees=[];
			for(var i in this.json.row){
				var item=this.json.row[i];
				if(IsInEmployees(item.Codigo)){
					aEmployees[item.Codigo]={};
					aEmployees[item.Codigo].code=item.Codigo;
					aEmployees[item.Codigo].name=item.Nombre;
					aEmployees[item.Codigo].surname=item.Apellidos;
					aEmployees[item.Codigo].text=item.Codigo+' - '+item.Nombre+' '+item.Apellidos;
					aEmployees[item.Codigo].group={};
				}
			}
		}
	}

	{ //Select Accruals
		aAccruals=opener.aAccruals;
		for(var i in aAccruals){
			aAccruals[i].totalTime=0;
			aAccruals[i].totalTimes=0;
		}
	}

	{ //Select all data
		var sqlWhere='';
		var sqlGroup='';
		var sqlSelect='';
		
		switch(options.term){
			case Term.None:
				sqlWhere="Fecha>='"+options.fromDate+"' AND Fecha<='"+options.toDate+"'";
				break;
			case Term.Day: 
				sqlSelect = 'Fecha value,';
				sqlWhere = "Fecha>='"+options.fromDate+"' AND Fecha<='"+options.toDate+"'";
				sqlGroup = 'Fecha,';
				break;
			case Term.Week:
				sqlSelect = 'Semana value,';
				sqlWhere = "Semana>="+options.fromWeek+" AND Semana<="+options.toWeek+" AND Anho='"+options.year+"'";
				sqlGroup = 'Semana,';
				break;
			case Term.Month:
				sqlSelect = 'Mes value,';
				sqlWhere = "Anho='"+options.year+"' AND Mes="+options.month;
				sqlGroup = 'Mes,';
				break;
			case Term.Year:
				sqlSelect = 'Anho value,';
				sqlWhere = "Anho='" + options.year + "'";
				sqlGroup = 'Anho,';
				break;
		}
		sqlGroup += 'IdAcumulador, IdEmpleado';
		
		var ajaxData = new Ajax(Convert.Format("SELECT {0}{1}, Sum(TotalTiempo) As Tiempo, Sum(TotalVeces) As Veces FROM CIERRE_ACUMULADORES{c} WHERE {2} GROUP BY {1} ORDER BY IdEmpleado, IdAcumulador", sqlSelect, sqlGroup, sqlWhere));
		ajaxData.oncomplete = function(){
			for(var i in this.json.row) {
				var db = this.json.row[i];
				if(IsInEmployees(db.IdEmpleado) && aAccruals[db.IdAcumulador].show){
					var group = GetGroup(db.IdEmpleado, db.value);
					
					group[db.IdAcumulador] = {};
					group[db.IdAcumulador].time = db.Tiempo;
					group[db.IdAcumulador].times = db.Veces;
					
					if(options.showTotal) {
						aAccruals[db.IdAcumulador].totalTime += Convert.Int(db.Tiempo);
						aAccruals[db.IdAcumulador].totalTimes += Convert.Int(db.Veces);
					}
				}
			}
		}
	}

	AjaxManager.Create('basic');
	AjaxManager.Create('data');
	AjaxManager.group['basic'].Add(ajaxEmployees);
	AjaxManager.group['data'].Add(ajaxData);
	
	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_double');
	report.Add('head_double',[LngStr('from',true),options.fromEmployeeValue,LngStr('to',true),options.toEmployeeValue]);
	
	switch(options.term){
		case Term.Day:
			report.Add('head_double',[LngStr('from_date',true),Convert.Date(options.fromDate),LngStr('to_date',true),Convert.Date(options.toDate)]);
			break;
		case Term.Week:
			report.Add('head_double',[LngStr('from_week',true),options.fromWeekValue,LngStr('to_week',true),options.toWeekValue]);
			report.Add('head_single',[LngStr('year',true),options.year]);
			break;
		case Term.Month:
			report.Add('head_double',[LngStr('month',true),LngStr('month_'+options.month),LngStr('year',true),options.year]);
			break;
		case Term.Year:
			report.Add('head_single',[LngStr('year',true),options.year]);
			break;
	}

	report.Add('head_single',[LngStr('company',true),COMPANY.code+' - '+COMPANY.description]);
	report.Add('head_single',[COMPANY.department+':',options.departmentValue]);
	report.Add('head_single',[COMPANY.center+':',options.centerValue]);

	report.AddSpace(10,true);
	report.Add('headers',[LngStr('accrual'), LngStr('time'), LngStr('times')]);
	
	report.SetSection('body');
	for(var i in aEmployees){
		if(Size(aEmployees[i].group)>0){
			report.Add('employees',['<div class="arrow"></div> '+aEmployees[i].text]);
		}
		
		for(var j in aEmployees[i].group) {
			report.Add('group', [j]);
			for(var k in aEmployees[i].group[j]){
				var accrual = aEmployees[i].group[j][k];
				report.Add('values',[aAccruals[k].Text, Convert.Minutes(accrual.time), accrual.times]);
			}
		}
		if(options.employeePage){ report.Add('@break') };
	}
	
	if(options.showTotal) {
		report.Add('employees',['<div class="arrow"></div> Total']);
		for(var i in aAccruals) {
			if(aAccruals[i].show) {
				report.Add('values',[aAccruals[i].Text, Convert.Minutes(aAccruals[i].totalTime), Convert.Int(aAccruals[i].totalTimes)]);
			}
		}
	}
}

function GetGroup(employee, value){
	var label = GetGroupLabel(value);
	
	if(!IsDefined(aEmployees[employee].group[label])){
		aEmployees[employee].group[label] = {};
	}
		
	return aEmployees[employee].group[label];
}

function GetGroupLabel(value){
	var result = '';
	switch(options.term){
		case Term.None:
			result = LngStr('from', true) + Convert.Date(options.fromDate) + ' - ' + LngStr('to', true) + Convert.Date(options.toDate);
			break;
		case Term.Day:
			result = Convert.Date(value, true);
			break;
		case Term.Week:
			result = FormatWeek(value, options.year);
			break;
		case Term.Month:
			result = LngStr('month_'+value);
			break;
		case Term.Year:
			result = value;
			break;
	}
	
	return result;
}