var options={};

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

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.event=opener.cmbEvents1.selectedKey;
	options.eventValue=opener.cmbEvents1.value;
	options.order=opener.cmbOrder.selectedIndex;
	options.orderValue=opener.cmbOrder.value;
	options.pageemployee=opener.chkPageEmployee1.GetCheck();
	options.checks=opener.chkViewChecks.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.AddStyle('checks','background: #FFF5D4 url(design.report.png) repeat-x 0 -46px;');

	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: 100});
	report.tables['headers'].Add({width: 80});
	report.tables['headers'].Add({width: 80});
	report.tables['headers'].Add({width: 80});
	report.tables['headers'].Add({width: 200});
	report.tables['headers'].Add({width: 200});
	
	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: 100});
	report.tables['values'].Add({width: 80});
	report.tables['values'].Add({width: 80});
	report.tables['values'].Add({width: 80});
	report.tables['values'].Add({width: 200});
	report.tables['values'].Add({width: 200});
	
	report.AddTable('checks',{className: 'checks'});
	report.tables['checks'].Add({width: 80});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
	report.tables['checks'].Add({width: 90});
}
function Report_Load_Data(){
	AjaxManager.Create('basic');
	AjaxManager.Create('data');
	{//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); }
			}
		}
		{//Workday
			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); }
			}
		}
	}

	{ //Select all data
		var whereItems = [];
		whereItems.push(" AND d.Fecha>='"+options.fromDate+"' AND d.Fecha<='"+options.toDate+"'");
		
		if (options.fromEmployee != 'All') {
			if (options.toEmployee == 'None') { whereItems.push("d.IdEmpleado = '"+options.fromEmployee+"'"); }
			else { whereItems.push("d.IdEmpleado >= '"+options.fromEmployee+"' AND d.IdEmpleado <= '"+options.toEmployee+"'"); }
		}
		if(options.department != 'All') { whereItems.push("c.IdUbicacion = '" + options.department + "'"); }
		if(options.center != 'All') { whereItems.push("c.IdCentro = '" + options.center + "'"); }
		if(options.event != 'All') { whereItems.push("d.IdIncidencia = '" + options.event + "'"); }
		
		var strWhere=whereItems.join(" AND ");
		var strOrder=iif(options.order==0,'d.IdEmpleado','e.Nombre');
		
		var ajaxData = new Ajax(Convert.Format(
		"SELECT d.*, e.Nombre, e.Apellidos, c.TipoDia, c.Incidencia As IdHorario  "
		+ "FROM CIERRE_DESGLOSE_DIAS{c} d INNER JOIN CIERRE{c} c on d.IdEmpleado=c.IdEmpleado AND d.Fecha=c.Fecha "
		+ "INNER JOIN EMPLEADOS{c} e ON d.IdEmpleado=e.Codigo "
		+ "AND c.TipoDia <> 'D' {0} "
		+ "ORDER BY {1},d.Fecha, d.HoraInicio", strWhere, strOrder));
		AjaxManager.group['data'].Add(ajaxData);
		ajaxData.oncomplete = function() {
			for(var i in this.json.row) {
				var item = this.json.row[i];
				if(IsInEmployees(item.IdEmpleado)) {
					if(typeof(aEmployees[item.IdEmpleado])=="undefined"){
						aEmployees[item.IdEmpleado]={text: item.IdEmpleado+' - '+item.Nombre+' '+item.Apellidos, dates: []};
					}
					var employee = aEmployees[item.IdEmpleado];
					if(typeof(employee.dates[item.Fecha])=="undefined") {
						employee.dates[item.Fecha]={};
						employee.dates[item.Fecha].items=[];
						employee.dates[item.Fecha].checks=[];
					}
					var date = employee.dates[item.Fecha];
					var subitem = {};
					subitem.from = item.HoraInicio;
					subitem.to = item.HoraFin;
					subitem.duration = item.Total;
					subitem.event = item.IdIncidencia;
					//alert(item.TipoDia+' '+item.TipoDia[0]);
					subitem.workday = (item.TipoDia[0]=='H')?item.IdHorario:'';
					date.items.push(subitem);
				}
			}
		}
	}
	{ //Checks data
		if(options.checks){
			whereItems=[];
			whereItems.push("FechaValor>='"+options.fromDate+"' AND FechaValor<='"+options.toDate+"'");
			if (options.fromEmployee != 'All') {
				if (options.toEmployee == 'None') { whereItems.push("IdEmpleado = '"+options.fromEmployee+"'"); }
				else { whereItems.push("IdEmpleado >= '"+options.fromEmployee+"' AND IdEmpleado <= '"+options.toEmployee+"'"); }
			}
			if(options.department != 'All') { whereItems.push("c.IdUbicacion = '" + options.department + "'"); }
			if(options.center != 'All') { whereItems.push("c.IdCentro = '" + options.center + "'"); }
			if(options.event != 'All') { whereItems.push("d.IdIncidencia = '" + options.event + "'"); }
			
			var ajaxChecks = new Ajax(Convert.Format("SELECT IdEmpleado,FechaValor,Hora FROM FICHAJES{c} WHERE {0} AND Virtual = 0 ORDER BY IdEmpleado,FechaOriginal, HoraOriginal",whereItems.join(" AND ")));
			AjaxManager.group['data'].Add(ajaxChecks);
			ajaxChecks.oncomplete=function() {
				var lastDate='';
				var lastEmployee='';
				var count=0;
				for(var i in this.json.row) {
					var item = this.json.row[i];
					if(lastEmployee!=item.IdEmpleado || lastDate!=item.FechaValor ) { count=0; lastEmployee=item.IdEmpleado; lastDate=item.FechaValor; }
					
					if(typeof(aEmployees[lastEmployee])!="undefined"){
						var employee=aEmployees[lastEmployee]
						if(typeof(employee.dates[lastDate])!="undefined") {
							var date = employee.dates[lastDate];
							var uBound = date.checks.length;
							if(count%2==0){ date.checks[uBound]=Convert.Time(item.Hora); }
							else{
								date.checks[uBound-1] += ' - '+Convert.Time(item.Hora);
							}
							count++;
						}
					}
				}
			}
		}
	}

	AjaxManager.group['basic'].Start();
	AjaxManager.group['basic'].oncomplete=function(){ AjaxManager.group['data'].ProgressiveStart(); }
}
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('event',true),options.eventValue,LngStr('order',true),options.orderValue]);
	
	report.AddSpace(10,true);
	report.Add('headers',[LngStr('date'), LngStr('from'), LngStr('to'), LngStr('duration'), LngStr('event'), LngStr('workday')]);
	
	report.SetSection('body');
	function NewCheckLine(array,isNew){
		if(typeof(isNew)=="undefined"){ isNew=true; }
		if(array.length!=0) {
			report.Add('checks',[iif(isNew,LngStr('checks',true),''),iif(typeof(array[0])!="undefined",array[0],''),iif(typeof(array[1])!="undefined",array[1],'')
			,iif(typeof(array[2])!="undefined",array[2],''),iif(typeof(array[3])!="undefined",array[3],''),iif(typeof(array[4])!="undefined",array[4],'')
			,iif(typeof(array[5])!="undefined",array[5],''),iif(typeof(array[6])!="undefined",array[6],'')
			]);
		}
	}
	for(var i in aEmployees) {
		var employee=aEmployees[i];
		report.Add('employees',['<div class="arrow"></div> '+aEmployees[i].text]);
		for(var j in employee.dates){
			var date = employee.dates[j];
			var first=true;
			for(var k in date.items){
				var item = date.items[k];
				
				report.Add('values',[first?Convert.Date(j,true):'', Convert.Time(item.from), Convert.Time(item.to), Convert.Minutes(item.duration), aEvents[item.event].text, (item.workday!='')?aWorkdays[item.workday].text:'']);
				first=false;
			}
			if(options.checks){
				var arrayChecks=[];
				var count=0;
				var firstLine=true;
				for(var k in date.checks){
					var check = date.checks[k];
					arrayChecks.push(check);
					if(count==7) {
						NewCheckLine(arrayChecks,firstLine);
						firstLine=false;
						arrayChecks=[];
					}
					count++;
				}
				NewCheckLine(arrayChecks, firstLine);
			}
		}
		if(options.pageemployee){ report.Add('@break') };
	}
}