var options={};

var aDays=[], aEmployees=[], aEvents=[];

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.employeePage=opener.chkPageEmployee2.GetCheck();
	options.at_least_one=opener.chkOnlyEmployees.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('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: 250});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	report.tables['headers'].Add({width: 70});
	
	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: 250});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
	report.tables['values'].Add({width: 70});
}
function Report_Load_Data() {
	AjaxManager.Create('basic');
	AjaxManager.Create('data');
	{//Select days/weeks
		var fromDay = Convert.FromStoreDate(options.fromDate);
		var toDay = Convert.FromStoreDate(options.toDate);
		
		var weekDay = Convert.WeekDay(fromDay);

		var iniDay=new Date(fromDay.getFullYear(),fromDay.getMonth(),fromDay.getDate()-weekDay);
		weekDay = Convert.WeekDay(toDay);
		var endDay=new Date(toDay.getFullYear(),toDay.getMonth(),toDay.getDate()+(7-weekDay));
		while(iniDay<=endDay){
			var current=Convert.ToStoreDate(iniDay);
			if(current>=options.fromDate && current<=options.toDate){
				aDays[current]=LngStr('unprocessed');
			}
			else{
				aDays[current]='---';
			}
			iniDay.setDate(iniDay.getDate()+1);
		}
		
	}
	{//Basic
		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 db=this.json.row[i];
					aEvents[db.Codigo]={ text: db.Descripcion }
				}
			}
			else{ alert(this.text); }
		}
		
		var whereItems = [];
		if (options.fromEmployee != 'All') {
			if (options.toEmployee == 'None') { whereItems.push("e.Codigo = '"+options.fromEmployee+"'"); }
			else { whereItems.push("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 ajaxEmployees = new Ajax(Convert.Format("SELECT Codigo,Nombre,Apellidos FROM EMPLEADOS{c} e {0} ORDER BY Codigo", whereItems.length!=0?('WHERE '+whereItems.join(" AND ")):''));
		AjaxManager.group['basic'].Add(ajaxEmployees);
		ajaxEmployees.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var db=this.json.row[i];
					if(IsInEmployees(db.Codigo)){
						aEmployees[db.Codigo]={ text: db.Descripcion };
						aEmployees[db.Codigo]={
							text: db.Codigo+' - '+db.Nombre+' '+db.Apellidos,
							dates: {},
							has_absence: false,
							has_closed: false
						};
						for(var j in aDays){
							aEmployees[db.Codigo].dates[j]={date: j, year: j.substr(0,4), text:  aDays[j], has_absence: false, work: 0};
						}
					}
				}
			}
			else{ alert(this.text); }
		}
		
	}
	{
		whereItems.push("c.Fecha>='"+options.fromDate+"' AND c.Fecha<='"+options.toDate+"'");
	}
	{//Calendar
		if(options.at_least_one){
			var ajaxCalendar=Ajax(Convert.Format("SELECT e.Codigo, c.Fecha, c.IdTipoDia, t.Laborable FROM CALENDARIO{c} c INNER JOIN EMPLEADOS{c} e ON ((c.IdCalendario=e.Codigo AND c.Publico='0') OR (c.IdCalendario=e.IdCalendario AND c.Publico='1')) INNER JOIN TIPO_DIA{c} t ON c.IdTipoDia=t.Codigo WHERE {0} ORDER BY c.Fecha ASC, c.Publico DESC", whereItems.join(" AND ")));
			AjaxManager.group['basic'].Add(ajaxCalendar);
			ajaxCalendar.oncomplete=function(){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var db=this.json.row[i];
					aEmployees[db.Codigo].dates[db.Fecha].work=db.Laborable;
				}
			}
		}		
	}
	{//Select all data
		var ajaxData=Ajax(Convert.Format("SELECT c.* FROM CIERRE{c} c INNER JOIN EMPLEADOS{c} e ON c.IdEmpleado=e.Codigo WHERE {0} ORDER BY c.IdEmpleado, c.Fecha", whereItems.join(" AND ")));
		AjaxManager.group['data'].Add(ajaxData);
		ajaxData.oncomplete=function(){
			for(var i=0,iLen=this.json.row.length;i<iLen;i++){
				var db=this.json.row[i];
				if(IsInEmployees(db.IdEmpleado)){
					var employee=aEmployees[db.IdEmpleado];
					var date=aEmployees[db.IdEmpleado].dates[db.Fecha];
					
					employee.has_closed=true;
					date.has_closed=true;
					date.daytype=db.TipoDia;
					date.week=db.Semana;
					date.year=db.Anho;
					switch(db.TipoDia){
						case 'I':
							date.text=aEvents[db.Incidencia].text;
							if(date.work!=0){
								date.has_absence=true; 
								employee.has_absence=true; 
							}
							break;
						case 'D':
							date.text=LngStr('holiday');
							break;
						default: 
							date.text=LngStr('present');
							if(db.TipoDia[0]!='H' && date.work!=0){
								date.has_absence=true; 
								employee.has_absence=true; 
							}
							break;
					}
				}
			}
		}
	}
	
	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.AddSpace(10,true);
	report.Add('headers',[LngStr('date'), LngStr('weekday_1'), LngStr('weekday_2'), LngStr('weekday_3'), LngStr('weekday_4'), LngStr('weekday_5'), LngStr('weekday_6'), LngStr('weekday_7')]);
	
	report.SetSection('body');

	for(var i in aEmployees){
		if(aEmployees[i].has_closed && (!options.at_least_one || aEmployees[i].has_absence)){
			var lastDate='';
			report.Add('employees',['<div class="arrow"></div> '+aEmployees[i].text]);
			var count=0, has_closed=false, has_absence=false;
			var arrayDates=[];
			for(var j in aEmployees[i].dates){
				var date = aEmployees[i].dates[j];
				arrayDates.push(date);
				if(date.has_absence){ has_absence=true; }
				if(date.has_closed){ has_closed=true; }
				count++;
				if(count==7){
					if(has_closed && (!options.at_least_one || has_absence)){
						report.Add('values',[FormatWeek(WeekNumber(arrayDates[6].date), arrayDates[6].year), arrayDates[0].text, arrayDates[1].text, arrayDates[2].text, arrayDates[3].text, arrayDates[4].text, arrayDates[5].text, arrayDates[6].text]);
					}
					arrayDates=[];
					has_absence=false;
					has_closed=false;
					count=0;
				}
			}
			if(options.employeePage){ report.Add('@break') };
		}
	}
}