{//Global vars-------------------------------------------------------------------------------------------------------------------------------------------------------------------
	var aEmployees=[];
	var aWorkdays=[];
	var aEvents=[];
	var aDates=[];
	var aTerminals=[];
	var employee='';
	
	var checksAdd=[];
	var checksMod=[];
	var checksDel=[];
}
{//Basic controls----------------------------------------------------------------------------------------------------------------------------------------------------------------
	{//Header--------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var gpHeader=Jade.Objects.Container();
		gpHeader.Location(0,0,1000,65);
		gpHeader.Add();
		{//Combos--------------------------------------------------------------------------------------------------------------------------------------------------------------------
			var lblEmployee = Jade.Objects.Text(Jade.Lang.Get('employee')+':');
			lblEmployee.Location(10,15,100,20);
			lblEmployee.Add(gpHeader);
			var cmbEmployee = Jade.Objects.ComboBox();
			cmbEmployee.Location(100,10,305,20);
			cmbEmployee.Add(gpHeader);
			var lblDate_From = Jade.Objects.Text(Jade.Lang.Get('from_date')+':');
			lblDate_From.Location(440,15,100,20);
			lblDate_From.Add(gpHeader);
			var cmbDate_From = Jade.Objects.DatePicker();
			cmbDate_From.Location(540,10,105,20);
			cmbDate_From.Add(gpHeader);
			var lblDate_To = Jade.Objects.Text(Jade.Lang.Get('to_date')+':');
			lblDate_To.Location(655,15,100,20);
			lblDate_To.Add(gpHeader);
			var cmbDate_To = Jade.Objects.DatePicker();
			cmbDate_To.Location(755,10,105,20);
			cmbDate_To.Add(gpHeader);
		}
		{//Checkboxs-----------------------------------------------------------------------------------------------------------------------------------------------------------------
			var chk_OddChecks = Jade.Objects.CheckBox(Jade.Lang.Get('show_odd_checks'));
			chk_OddChecks.Location(10,40,240,20);
			chk_OddChecks.Add(gpHeader);
			var chk_NoSpecial = Jade.Objects.CheckBox(Jade.Lang.Get('show_no_special'));
			chk_NoSpecial.Location(225,40,240,20);
			chk_NoSpecial.Add(gpHeader);
			var chk_NoChecks = Jade.Objects.CheckBox(Jade.Lang.Get('show_no_checks'));
			chk_NoChecks.Location(460,40,240,20);
			chk_NoChecks.Add(gpHeader);
			var chk_NoClose = Jade.Objects.CheckBox(Jade.Lang.Get('show_no_processed'));
			chk_NoClose.Location(650,40,240,20);
			chk_NoClose.Add(gpHeader);
		}
		{//Buttons-------------------------------------------------------------------------------------------------------------------------------------------------------------------
			$.ControlAdd('searchemployee', [410,10,20,20], gpHeader, cmbEmployee);
			
			var cmdRefresh = Jade.Objects.Button(Jade.Lang.Get('refresh'));
			cmdRefresh.Location(870,10,120,20);
			cmdRefresh.Add(gpHeader);
			var cmdDeleteAll = Jade.Objects.Button(Jade.Lang.Get('delete_all'));
			cmdDeleteAll.Location(870,35,120,20);
			cmdDeleteAll.Add(gpHeader);
			cmdRefresh.onclick = function(){ LoadPunchs(); }
		}
	}
	{//Buttons-------------------------------------------------------------------------------------------------------------------------------------------------------------------
		if(Jade.Utils.Privilege('checks_date_time') && Jade.Utils.Privilege('checks_event') && Jade.Utils.Privilege('checks_add')){
			var cmdOk = Jade.Objects.Button(Jade.Lang.Get('accept'));
			cmdOk.Location(0, 486, 495, 24);
			cmdOk.Add();
			var cmdCancel = Jade.Objects.Button();
			cmdCancel.Location(505, 486, 495, 24);
			cmdCancel.SetText(Jade.Lang.Get('cancel'));
			cmdCancel.Add();
			cmdOk.onclick=function(){ ShowPetitions(); }
			cmdCancel.onclick=function(){ LoadPunchs(); }
		}
	}
	{//Leyenda-------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var gpLegend = Jade.Objects.Container();
		gpLegend.Location(0,510,1000,27);
		gpLegend.SetStyle('transparent');
		gpLegend.Add();
		var lblLegend_1 = Jade.Objects.Text(Jade.Lang.Get('punches_unprocessed'));
		lblLegend_1.Location(10,8,200,20);
		lblLegend_1.Add(gpLegend);
		var lblLegend_2 = Jade.Objects.Text(Jade.Lang.Get('punches_processed'));
		lblLegend_2.Location(210,8,200,20);
		lblLegend_2.Add(gpLegend);
		lblLegend_2.style.color = '#6688CF';
		var lblLegend_3 = Jade.Objects.Text(Jade.Lang.Get('punches_not_saved'));
		lblLegend_3.Location(420,8,260,20);
		lblLegend_3.Add(gpLegend);
		lblLegend_3.style.color = '#FF8C00';
	}
	{//Default values------------------------------------------------------------------------------------------------------------------------------------------------------------
		var strYear=Jade.Strings.PadLeft(Jade.DateTime.CurrentYear(),'0',4);
		var strMonth=Jade.Strings.PadLeft(Jade.DateTime.CurrentMonth(),'0',2);
		var strLastDay=Jade.Strings.PadLeft(Jade.DateTime.CurrentDay(),'0',2);
		cmbDate_From.SetValue(strYear+strMonth+'01');
		cmbDate_To.SetValue(strYear+strMonth+strLastDay);
		chk_OddChecks.SetCheck(true);
		chk_NoSpecial.SetCheck(true);
		chk_NoChecks.SetCheck(false);
		chk_NoClose.SetCheck(true);
	}
}
{//Checks Window-----------------------------------------------------------------------------------------------------------------------------------------------------------------
	{//Controls------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var winPunch=Jade.Objects.Window(450,135);
		
		var winPunch_lbl1=Jade.Objects.Text(Jade.Lang.Get('employee')+':');
		winPunch_lbl1.Location(15,15,100,20);
		winPunch_lbl1.Add(winPunch);
		var winPunch_Employee=Jade.Objects.Text();
		winPunch_Employee.Location(110,15,320,20);
		winPunch_Employee.Add(winPunch);
		
		var winPunch_lbl2=Jade.Objects.Text(Jade.Lang.Get('date')+':');
		winPunch_lbl2.Location(15,40,100,20);
		winPunch_lbl2.Add(winPunch);
		var winPunch_Date=Jade.Objects.Text();
		winPunch_Date.Location(110,40,120,20);
		winPunch_Date.Add(winPunch);
		
		var winPunch_lbl3=Jade.Objects.Text(Jade.Lang.Get('time')+':');
		winPunch_lbl3.Location(245,40,100,20);
		winPunch_lbl3.Add(winPunch);
		var winPunch_Time=Jade.Objects.TimeBox();
		winPunch_Time.Location(345,35,90,20);
		winPunch_Time.Add(winPunch);
		
		var winPunch_lbl3=Jade.Objects.Text(Jade.Lang.Get('incidence')+':');
		winPunch_lbl3.Location(15,70,100,20);
		winPunch_lbl3.Add(winPunch);
		var winPunch_Event=Jade.Objects.ComboBox();
		winPunch_Event.Location(110,65,325,20);
		winPunch_Event.Add(winPunch);
		
		var winPunch_Accept=Jade.Objects.Button();
		winPunch_Accept.Location(15,100,205,20);
		winPunch_Accept.SetText(Jade.Lang.Get('accept'));
		winPunch_Accept.Add(winPunch);
		
		var winPunch_Cancel=Jade.Objects.Button();
		winPunch_Cancel.Location(230,100,205,20);
		winPunch_Cancel.SetText(Jade.Lang.Get('cancel'));
		winPunch_Cancel.Add(winPunch);
	}
	{//Events--------------------------------------------------------------------------------------------------------------------------------------------------------------------
		winPunch_Cancel.onclick=function(){	winPunch.Hide(); }
		winPunch_Accept.onclick=function(){
			winPunch_Accept.SetEnabled(false);
			var valueDate=winPunch.date;
			var valueTime=winPunch_Time.GetValue();
			var valueEvent=winPunch_Event.selectedKey;
			if(typeof(winPunch.cell)=="undefined"){
				var newCell={};
				newCell.Fecha=valueDate;
				newCell.Hora=valueTime;
				newCell.IdIncidencia = valueEvent;
				newCell.FechaValor=valueDate;
				newCell.FechaOriginal=valueDate;
				newCell.HoraOriginal=valueTime;
				newCell.IdIncidenciaOriginal=valueEvent;
				newCell.Tarjeta=aEmployees[employee].Tarjeta;
				newCell.IdUbicacion=aEmployees[employee].IdUbicacion;
				newCell.IdCentro=aEmployees[employee].IdCentro;
				newCell.IdTerminal='###';
				newCell.Cerrado=0;
				newCell.Status=2;
				ReorderDate(winPunch.row,newCell);
				checksAdd.push(newCell);
			}
			else{
				var valueReal=winPunch.cell.realValue;
				if(valueReal.Hora!=valueTime || valueReal.IdIncidencia!=valueEvent){
					switch(valueReal.Status){
						case 2:
							for(var i=0,iLen=checksAdd.length;i<iLen;i++){
								var item = checksAdd[i];
								if(valueReal.Fecha==item.date && valueReal.Hora==item.time && valueReal.IdIncidencia==item.event){
									item[i]={'date': valueDate, 'time': valueTime, 'event': valueEvent}
								}
							}
							break;
						case 3:
							for(var i=0,iLen=checksMod.length;i<iLen;i++){
								var item = checksMod[i];
								var valueOld = winPunch.cell.oldValue;
								if(valueReal.Fecha==item.newDate && valueReal.Hora==item.newTime && valueReal.IdIncidencia==item.newEvent){
									//checksMod[i].newDate = valueDate;
									checksMod[i].newDateValue = valueDate;
									checksMod[i].newTime = valueTime;
									checksMod[i].newEvent = valueEvent;
								}
							}
							break;
						default:
							checksMod.push({'pkDate': valueReal.FechaOriginal, 'pkTime': valueReal.HoraOriginal,'oldDate': valueReal.Fecha,'oldDateValue': valueReal.FechaValor, 'oldTime': valueReal.Hora, 'oldEvent': valueReal.IdIncidencia,'newDate': valueDate,'newDateValue': valueDate, 'newTime': valueTime, 'newEvent': valueEvent});
							break;
					}
					winPunch.cell.realValue.Hora=valueTime;
					winPunch.cell.realValue.IdIncidencia=valueEvent;
					winPunch.cell.realValue.Status=3;
					ReorderDate(winPunch.row);
				}
			}
			
			winPunch.Hide();
		}
	}
	function ShowWindow(row,cell){
		winPunch_Accept.SetEnabled(true);
		winPunch.Show();
		winPunch.row=row;
		winPunch.cell=cell;
		winPunch.date=row.cells[8].value;
		winPunch_Employee.SetText(cmbEmployee.value);
		winPunch_Date.SetText(Jade.DateTime.toShowDate(winPunch.date));
		if(typeof(winPunch.cell)=="undefined"){
			winPunch_Time.SetValue('000000');
			winPunch_Event.SetSelectedIndex(0);
		}
		else{
			winPunch_Time.SetValue(winPunch.cell.realValue.Hora);
			winPunch_Event.SetSelectedKey(winPunch.cell.realValue.IdIncidencia);
		}
	
		if(!Jade.Utils.Privilege('checks_date_time')){ winPunch_Time.SetEnabled(false); }
		if(!Jade.Utils.Privilege('checks_event')){ winPunch_Event.SetEnabled(false); }
	}
}
{//Petitions Window--------------------------------------------------------------------------------------------------------------------------------------------------------------
	{//Controls------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var winPet=Jade.Objects.Window(810,135);
		var winPet_lbl1=Jade.Objects.Text(Jade.Lang.Get('made_petitions')+':');
		winPet_lbl1.Location(15,10,400,20);
		winPet_lbl1.Add(winPet);
		var winPet_Accept = Jade.Objects.Button(Jade.Lang.Get('accept'));
		winPet_Accept.Location(15,100,385,20);
		winPet_Accept.Add(winPet);
		var winPet_Cancel = Jade.Objects.Button(Jade.Lang.Get('cancel'));
		winPet_Cancel.Location(15,100,385,20);
		winPet_Cancel.Add(winPet);
	
		var winPet_lbl2=Jade.Objects.Text(Jade.Lang.Get('petitions_new_checks')+':');
		winPet_lbl2.Location(15,30,400,20);
		winPet_lbl2.Add(winPet);
		var winPet_New = Jade.Objects.SimpleGrid();
		winPet_New.Location(15,50,780,100);
		winPet_New.AddHeader(Jade.Lang.Get('date'),100);
		winPet_New.AddHeader(Jade.Lang.Get('time'),100);
		winPet_New.AddHeader(Jade.Lang.Get('incidence'),580);
		winPet_New.Add(winPet);

		var winPet_lbl3=Jade.Objects.Text(Jade.Lang.Get('petitions_mod_checks')+':');
		winPet_lbl3.Size(400,20);
		winPet_lbl3.Add(winPet);
		var winPet_Mod = Jade.Objects.SimpleGrid();
		winPet_Mod.Size(780,100);
		winPet_Mod.AddHeader('&nbsp;',150,'fixed');
		winPet_Mod.AddHeader(Jade.Lang.Get('date'),100);
		winPet_Mod.AddHeader(Jade.Lang.Get('value_date'),100);
		winPet_Mod.AddHeader(Jade.Lang.Get('time'),80);
		winPet_Mod.AddHeader(Jade.Lang.Get('incidence'),350);
		winPet_Mod.Add(winPet);

		var winPet_lbl4=Jade.Objects.Text(Jade.Lang.Get('petitions_del_checks')+':');
		winPet_lbl4.Size(400,20);
		winPet_lbl4.Add(winPet);
		var winPet_Del=Jade.Objects.SimpleGrid();
		winPet_Del.Size(780,100);
		winPet_Del.AddHeader(Jade.Lang.Get('date'),100);
		winPet_Del.AddHeader(Jade.Lang.Get('time'),100);
		winPet_Del.AddHeader(Jade.Lang.Get('incidence'),580);
		winPet_Del.Add(winPet);	

	}
	{//Events--------------------------------------------------------------------------------------------------------------------------------------------------------------------
		winPet_Cancel.onclick=function(){ winPet.Hide(); }
		winPet_Accept.onclick = function() {
			winPet_Accept.SetEnabled(false);
			if(checksAdd.length!=0 || checksMod.length!=0 || checksDel.length!=0){
				var Fecha=Jade.DateTime.toStoreDate(new Date());
				var Hora=Jade.DateTime.toStoreTime(new Date());
				var IdPeticion=Jade.Encrypt.MD5(USER.id+Fecha+Hora);
				{//Add petition------------------------------------------------------------------------------------------------------------------------------------------------------
					var ajaxPetition=Jade.Ajax();
					ajaxPetition.AddParamArray('fields', ['IdPeticion','IdUsuario','Fecha','Hora','Familia','Clave','Estado','EstadoEnvio']);
					ajaxPetition.AddParamArray('values', [IdPeticion,USER.id,Fecha,Hora,'6',employee,'0','0']);
					ajaxPetition.AddParam('save', "PETICIONES{c}");
					ajaxPetition.Run('lib/php/ajax_db.php');
				}
				{//Add checks------------------------------------------------------------------------------------------------------------------------------------------------------
					for(var i=0,iLen=checksAdd.length;i<iLen;i++){
						var item=checksAdd[i];
						var valor="<Petition>";
						valor+="<PrimaryKey><Date>"+item.FechaOriginal+"</Date><Time>"+item.HoraOriginal+"</Time><EmployeeId>"+employee+"</EmployeeId></PrimaryKey>";
						valor+="<NewValues><Date>"+item.Fecha+"</Date><Time>"+item.Hora+"</Time><EventId>"+item.IdIncidencia+"</EventId><ValueDate>"+item.FechaValor+"</ValueDate><Department>"+item.IdUbicacion+"</Department><Center>"+item.IdCentro+"</Center><Card>"+item.Tarjeta+"</Card></NewValues>";
						valor+="</Petition>";
						var ajaxAdd=Jade.Ajax();
						ajaxAdd.AddParamArray('fields', ['IdPeticion','SubFamilia','Accion','Estado','Valor']);
						ajaxAdd.AddParamArray('values', [IdPeticion,'0','0','0',valor]);
						ajaxAdd.AddParam('save', "PETICIONES_LINEAS{c}");
						ajaxAdd.Run('lib/php/ajax_db.php');
					}
					checksAdd=[];
				}
				{//Mod checks------------------------------------------------------------------------------------------------------------------------------------------------------
					for(var i=0,iLen=checksMod.length;i<iLen;i++){
						var item=checksMod[i];
						var valor="<Petition>";
						valor+="<PrimaryKey><Date>"+item.pkDate+"</Date><Time>"+item.pkTime+"</Time><EmployeeId>"+employee+"</EmployeeId></PrimaryKey>";
						valor+="<NewValues><Date>"+item.newDate+"</Date><Time>"+item.newTime+"</Time><EventId>"+item.newEvent+"</EventId><ValueDate>"+item.newDateValue+"</ValueDate></NewValues>";
						valor+="<OldValues><Date>"+item.oldDate+"</Date><Time>"+item.oldTime+"</Time><EventId>"+item.oldEvent+"</EventId><ValueDate>"+item.oldDateValue+"</ValueDate></OldValues>";
						valor+="</Petition>";
						var ajaxMod=Jade.Ajax();
						ajaxMod.AddParamArray('fields', ['IdPeticion','SubFamilia','Accion','Estado','Valor']);
						ajaxMod.AddParamArray('values', [IdPeticion,'0','1','0',valor]);
						ajaxMod.AddParam('save', "PETICIONES_LINEAS{c}");
						ajaxMod.Run('lib/php/ajax_db.php');
					}
					checksMod=[];
				}
				{//Del checks------------------------------------------------------------------------------------------------------------------------------------------------------				
					for(var i=0,iLen=checksDel.length;i<iLen;i++){
						var item=checksDel[i];
						var valor="<Petition>";
						valor+="<PrimaryKey><Date>"+item.FechaOriginal+"</Date><Time>"+item.HoraOriginal+"</Time><EmployeeId>"+employee+"</EmployeeId></PrimaryKey>";
						valor+="<OldValues><Date>"+item.Fecha+"</Date><Time>"+item.Hora+"</Time><EventId>"+item.IdIncidencia+"</EventId><ValueDate>"+item.FechaValor+"</ValueDate><OriginalEventId>"+item.IdIncidenciaOriginal+"</OriginalEventId><Department>"+item.IdUbicacion+"</Department><Center>"+item.IdCentro+"</Center><Card>"+item.Tarjeta+"</Card><Terminal>"+item.IdTerminal+"</Terminal></OldValues>";
						valor+="</Petition>";
						var ajaxDel=Jade.Ajax();
						ajaxDel.AddParamArray('fields', ['IdPeticion','SubFamilia','Accion','Estado','Valor']);
						ajaxDel.AddParamArray('values', [IdPeticion,'0','2','0',valor]);
						ajaxDel.AddParam('save', "PETICIONES_LINEAS{c}");
						ajaxDel.Run('lib/php/ajax_db.php');
					}
					checksDel=[];
				}
			}
			winPet.Hide();
			LoadPunchs();
		}
	}
	function ShowPetitions(){
		winPet_Accept.SetEnabled(true);
		if(checksAdd.length!=0 || checksMod.length!=0 || checksDel.length!=0){
			var tableCount=0;
			{//Reset grids--------------------------------------------------------------------------------------------------------------------------------------------------------
				Jade.FX.Hide(winPet_lbl2);
				Jade.FX.Hide(winPet_New);
				Jade.FX.Hide(winPet_lbl3);
				Jade.FX.Hide(winPet_Mod);
				Jade.FX.Hide(winPet_lbl4);
				Jade.FX.Hide(winPet_Del);
				winPet_New.Clear();
				winPet_Mod.Clear();
				winPet_Del.Clear();
			}
			{//Add checks--------------------------------------------------------------------------------------------------------------------------------------------------------
				if(checksAdd.length!=0){
					Jade.FX.Show(winPet_lbl2);
					Jade.FX.Show(winPet_New);
					for(var i=0,iLen=checksAdd.length;i<iLen;i++){
						winPet_New.AddItem(Jade.DateTime.toShowDate(checksAdd[i].Fecha),Jade.DateTime.toShowTime(checksAdd[i].Hora),aEvents[checksAdd[i].IdIncidencia].Text);
					}
					tableCount++;
				}
			}
			{//Mod checks--------------------------------------------------------------------------------------------------------------------------------------------------------
				if(checksMod.length!=0){
					Jade.FX.Show(winPet_lbl3);
					Jade.FX.Show(winPet_Mod);
					switch(tableCount){
						case 0:
							winPet_lbl3.Position(15,30);
							winPet_Mod.Position(15,50);
							break;
						case 1:
							winPet_lbl3.Position(15,165,400,50);
							winPet_Mod.Position(15,185);
							break;
					}
					for(var i=0,iLen=checksMod.length;i<iLen;i++){
						winPet_Mod.AddStyledItem([Jade.Lang.Get('old_value'),Jade.DateTime.toShowDate(checksMod[i].oldDate),Jade.DateTime.toShowDate(checksMod[i].oldDateValue),Jade.DateTime.toShowTime(checksMod[i].oldTime),aEvents[checksMod[i].oldEvent].Text],'ghost');
						winPet_Mod.AddItem(Jade.Lang.Get('new_value'),Jade.DateTime.toShowDate(checksMod[i].newDate),Jade.DateTime.toShowDate(checksMod[i].newDateValue),Jade.DateTime.toShowTime(checksMod[i].newTime),aEvents[checksMod[i].newEvent].Text);
					}
					tableCount++;
				}
			}
			{//Del checks--------------------------------------------------------------------------------------------------------------------------------------------------------
				if(checksDel.length!=0){
					Jade.FX.Show(winPet_lbl4);
					Jade.FX.Show(winPet_Del);
					switch(tableCount){
						case 0:
							winPet_lbl4.Position(15,30);
							winPet_Del.Position(15,50);
							break;
						case 1:
							winPet_lbl4.Position(15,165);
							winPet_Del.Position(15,185);
							break;
						case 2:
							winPet_lbl4.Position(15,300);
							winPet_Del.Position(15,320);
							break;				
					}
					for(var i=0,iLen=checksDel.length;i<iLen;i++){
						winPet_Del.AddItem(Jade.DateTime.toShowDate(checksDel[i].Fecha),Jade.DateTime.toShowTime(checksDel[i].Hora),aEvents[checksDel[i].IdIncidencia].Text);
					}
					tableCount++;
				}
			}
			{//Window size-------------------------------------------------------------------------------------------------------------------------------------------------------
				switch(tableCount){
					case 0:
						winPet.Size(810,135);
						winPet_Accept.POsition(15,100);
						winPet_Cancel.POsition(405,100);
						break;
					case 1:
						winPet.Size(810,200);
						winPet_Accept.Position(15,165);
						winPet_Cancel.Position(405,165);
						break;
					case 2:
						winPet.Size(810,335);
						winPet_Accept.Position(15,300);
						winPet_Cancel.Position(405,300);
						break;
					case 3:
						winPet.Size(810,470);
						winPet_Accept.Position(15,435);
						winPet_Cancel.Position(405,435);
						break;
				}		
			}
			winPet.Show();
		}
	}
}
{//Ajax--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	var ajaxManager = Jade.AjaxManager();
	ajaxManager.Create('basic');
	{//Employees-----------------------------------------------------------------------------------------------------------------------------------------------------------------
		var ajaxEmployees=Jade.AjaxDB("SELECT Codigo,Nombre,Apellidos,Tarjeta,IdUbicacion,IdCentro FROM EMPLEADOS{c} ORDER BY Codigo");
		ajaxEmployees.Add(ajaxManager,"basic");
		ajaxEmployees.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					if(Jade.Utils.IsInEmployees(item.Codigo)){
						aEmployees[item.Codigo]={};
						aEmployees[item.Codigo].Text=item.Codigo+' - '+item.Nombre+' '+item.Apellidos;
						aEmployees[item.Codigo].Codigo=item.Codigo;
						aEmployees[item.Codigo].Nombre=item.Nombre;
						aEmployees[item.Codigo].Apellidos=item.Apellidos;
						aEmployees[item.Codigo].Tarjeta=item.Tarjeta;
						aEmployees[item.Codigo].IdUbicacion=item.IdUbicacion;
						aEmployees[item.Codigo].IdCentro=item.IdCentro;
					}
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Workdays------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var ajaxWorkdays=Jade.AjaxDB("SELECT * FROM HORARIOS{c} ORDER BY Codigo");
		ajaxWorkdays.Add(ajaxManager,'basic');
		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]={};
					aWorkdays[item.Codigo].Text=item.Codigo+' - '+item.Descripcion;
					aWorkdays[item.Codigo].Codigo=item.Codigo;
					aWorkdays[item.Codigo].Descripcion=item.Descripcion;
					aWorkdays[item.Codigo].TotalPrimera=item.TotalPrimera;
					aWorkdays[item.Codigo].TotalSegunda=item.TotalSegunda;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Events--------------------------------------------------------------------------------------------------------------------------------------------------------------------
		var ajaxEvents=Jade.AjaxDB("SELECT * FROM INCIDENCIAS{c} ORDER BY Codigo");
		ajaxEvents.Add(ajaxManager,'basic');
		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] = {};
					aEvents[item.Codigo].Text=item.Codigo+' - '+item.Descripcion;
					aEvents[item.Codigo].Codigo=item.Codigo;
					aEvents[item.Codigo].Descripcion=item.Descripcion;
					aEvents[item.Codigo].Tipo=item.Tipo;
					aEvents[item.Codigo].PermiteFichaje=item.PermiteFichaje;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Terminals-----------------------------------------------------------------------------------------------------------------------------------------------------------------
		var ajaxEvents=Jade.AjaxDB("SELECT * FROM TERMINALES{c} ORDER BY Codigo");
		ajaxEvents.Add(ajaxManager,'basic');
		ajaxEvents.oncomplete=function(){
			if(!this.json.error){
				aTerminals['###'] = {};
				aTerminals['###'].Text = Jade.Lang.Get('manual_punch');
				aTerminals['###'].Codigo = '###';
				aTerminals['###'].Descripcion = Jade.Lang.Get('manual_punch');
				
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item = this.json.row[i];
					aTerminals[item.Codigo] = {};
					aTerminals[item.Codigo].Text=item.Codigo+' - '+item.Descripcion;
					aTerminals[item.Codigo].Codigo=item.Codigo;
					aTerminals[item.Codigo].Descripcion=item.Descripcion;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}	
	{//Manager-------------------------------------------------------------------------------------------------------------------------------------------------------------------
		ajaxManager.group['basic'].Start();
		ajaxManager.group['basic'].oncomplete=function(){
			for(var i in aEmployees){ cmbEmployee.AddItem(aEmployees[i].Text,i); }
			for(var i in aEvents){
				if(i=='0000' || (!Jade.Utils.IsSystemIncidence(i) && aEvents[i].PermiteFichaje=='1')){ winPunch_Event.AddItem(aEvents[i].Text,i); }
			}
			LoadPunchs();
		}
	}
}
{//Grid
	{//Controls
		var cmPunchs=Jade.Grids.ColumnModel();
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'date', sortable: false, editable: false, text: Jade.Lang.Get('date'), width: '120'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'entry', sortable: false, selectable: false,  text: Jade.Lang.Get('entry'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'exit', sortable: false, text: Jade.Lang.Get('exit'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'entry', sortable: false, text: Jade.Lang.Get('entry'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'exit', sortable: false, text: Jade.Lang.Get('exit'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'entry', sortable: false, text: Jade.Lang.Get('entry'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'exit', sortable: false, text: Jade.Lang.Get('exit'), width: '110'}));
		cmPunchs.Add(Jade.Grids.SimpleColumn({key: 'event', sortable: false, text: Jade.Lang.Get('workday')+'/'+Jade.Lang.Get('incidence'), width: '200'}));
		cmPunchs.Add(Jade.Grids.HideColumn({key: 'date', width: '0'}));
		cmPunchs.Add(Jade.Grids.HideColumn({key: 'sub', width: '0'}));
		var grChecks = Jade.Grids.Grid(cmPunchs);
		grChecks.Location(0,75,1000,404);
		grChecks.Add();
		var mnuContext = Jade.Objects.ContextMenu();
		mnuContext.AddItem(Jade.Lang.Get('check_add'),'add');
		mnuContext.AddItem(Jade.Lang.Get('petition_option_1'),'modify');
		mnuContext.AddItem(Jade.Lang.Get('check_delete'),'delete');
		mnuContext.AddItem(Jade.Lang.Get('check_change_previus_day'),'previus');
		mnuContext.AddItem(Jade.Lang.Get('check_change_next_day'),'next');
	}
	{//Load punchs
		function LoadPunchs(){
			LoadPunchs_onStart();
			var fromDate=cmbDate_From.value;
			var toDate=cmbDate_To.value;
			var ajaxMng = Jade.AjaxManager();
			ajaxMng.Create('basic');
			aDates=[];
			{//Days without punchs check---------------------------------------------------------------------------------------------------------------------------------------------
				if(chk_NoChecks.GetCheck()){
					var dateStart=Jade.DateTime.fromStoreDate(fromDate);
					var dateEnd=Jade.DateTime.fromStoreDate(toDate);
					for(var dateUse=dateStart;dateUse<=dateEnd;dateUse=Jade.DateTime.AddDays(dateUse,1)){
						var storeDate=Jade.DateTime.toStoreDate(dateUse);
						if(typeof(aDates[storeDate])=="undefined"){ aDates[storeDate]={punch:[]}; }
					}
				}
			}
			{//Ajax punchs-----------------------------------------------------------------------------------------------------------------------------------------------------------
				var ajaxPunchs=Jade.AjaxDB(Jade.Strings.Format("SELECT * FROM FICHAJES{c} WHERE ((FechaValor >= '{0}' AND FechaValor <= '{1}' AND Cerrado = 1) OR (Fecha >= '{0}' AND Fecha <= '{1}' AND Cerrado = 0)) AND IdEmpleado = '{2}' ORDER BY Fecha, Hora", fromDate,toDate,employee));
				ajaxPunchs.Add(ajaxMng,'basic');
				ajaxPunchs.oncomplete=function(){
					if(!this.json.error){
						if(this.json.row.length!=0){
							for(var i=0,iLen=this.json.row.length; i<iLen;i++){
								var item=this.json.row[i];
								var check={};
								check.Fecha=item.Fecha;
								check.Hora=item.Hora;
								check.IdIncidencia=item.IdIncidencia;
								check.FechaValor=item.FechaValor;
								check.FechaOriginal=item.FechaOriginal;
								check.HoraOriginal=item.HoraOriginal;
								check.IdIncidenciaOriginal=item.IdIncidenciaOriginal;
								check.Tarjeta=item.Tarjeta;
								check.IdUbicacion=item.IdUbicacion;
								check.IdCentro=item.IdCentro;
								check.IdTerminal=item.IdTerminal;
								check.Cerrado=item.Cerrado;
								check.Status=parseInt(item.Cerrado,10);
								var strDate = (item.FechaValor+item.Fecha).substr(0,8);
								if(typeof(aDates[strDate])=="undefined"){ aDates[strDate]={punch:[]}; }
								aDates[strDate].punch.push(check);
							}
						}
					}
					else{ Jade.Debug.Add(this.text); }
				}
			}
			{//Ajax workdays---------------------------------------------------------------------------------------------------------------------------------------------------------
				var ajaxWorkdays=Jade.AjaxDB(Jade.Strings.Format("SELECT Fecha, Incidencia FROM CIERRE{c} WHERE Fecha >= '{0}' AND Fecha <= '{1}' AND IdEmpleado = '{2}' AND TipoDia <> 'I' AND TipoDia <> 'D'",cmbDate_From.value,cmbDate_To.value,employee));
				ajaxWorkdays.Add(ajaxMng,'basic');
				ajaxWorkdays.oncomplete=function(){
					if(!this.json.error){
						if(this.json.row.length!=0){
							for(var i=0,iLen=this.json.row.length; i<iLen;i++){
								var item=this.json.row[i];
								if(typeof(aDates[item.Fecha])!="undefined"){ aDates[item.Fecha].workday=item.Incidencia; }
							}
						}
					}
					else{ Jade.Debug.Add(this.text); }
				}
			}
			{//Ajax Manager----------------------------------------------------------------------------------------------------------------------------------------------------------
				ajaxMng.group['basic'].oncomplete=LoadPunchs_onEnd;
				ajaxMng.group['basic'].ProgessiveStart();
			}
		}
		function LoadPunchs_onStart(){
			checksAdd=[];
			checksMod=[];
			checksDel=[];
			employee=cmbEmployee.selectedKey;
			grChecks.Loading(true);
			cmdRefresh.SetEnabled(false);
			cmdDeleteAll.SetEnabled(false);
			grChecks.ClearRows();
		}
		function LoadPunchs_onEnd(){
			DrawPunchs();
			grChecks.Loading(false);
			cmdRefresh.SetEnabled(true);
			cmdDeleteAll.SetEnabled(true);
		}
	}
	{//Draw punchs
		function DrawPunchs(){
			for(var i in aDates){
				var date=aDates[i];
				if(MustAddDay(date)){
					var nPunchs=0;
					var row=Draw_NewRow(i,true);
					for(var j=0,jLen=date.punch.length;j<jLen;j++,nPunchs++){
						if(nPunchs==6) {
							row=Draw_NewRow(i,false);
							nPunchs=0;
						}
						Draw_CellData(row,nPunchs+1,date.punch[j]);
					}
					Draw_MissingExit(row,nPunchs);
				}
			}
		}
		function MustAddDay(date){
			var nPunchs = date.punch.length;
			var hasUnprocessed = false;
			for(var i=0;i<nPunchs;i++){
				if(date.punch[i].Cerrado=='0'){ hasUnprocessed = true }
			}
			if(chk_NoClose.GetCheck() && hasUnprocessed){ return true; }
			if(chk_OddChecks.GetCheck() && nPunchs%2==1){ return true; }
			if(chk_NoChecks.GetCheck() && nPunchs==0){ return true; }
			if(chk_NoSpecial.GetCheck() && nPunchs%2==0 && nPunchs!=0 && !hasUnprocessed){ return true; }
			return false;
		}
		function Draw_MissingExit(row,nChecks){
			if(nChecks%2!=0){
				row.cells[nChecks+1].SetValue(Jade.Lang.Get('missing_exit'));
				row.cells[nChecks+1].ChangeStyle('red');
				if(Jade.Utils.Privilege('checks_add')){
					row.cells[nChecks+1].ondblclick=function(){ ShowWindow(this.references.row); }
				}
			}
		}
		function Draw_NewRow(date, first, insertBefore){
			var strDate = Jade.iif(first, Jade.DateTime.toShowDate(date,true), '');
			var row = grChecks.InsertRow([strDate], insertBefore);
			row.cells[0].ChangeStyle('mark');
			row.cells[7].ChangeStyle('mark');
			row.cells[8].value=date;
			row.cells[9].value=Jade.iif(first,'0','1');
			
			for(var i=1;i<7;i++){ Draw_Cell(row, i); }
			
			if(first){
				if(typeof(aDates[date].workday)!="undefined"){
					row.cells[7].SetValue(aWorkdays[aDates[date].workday].Text);
				}
				else{
					row.cells[7].SetValue($.lng('no_process'));
				}
			}
			
			return row;
		}
		function Draw_Cell(row, index){
			row.cells[index].onmouseover=function(){
				if(this.value!='' && this.value!=Jade.Lang.Get('missing_exit')){
					if(typeof(this.tooltip)=="undefined"){
						this.tooltip = new Jade.Objects.ToolTip();
						Jade.FX.SetOpacity(this.tooltip,80);
						var coords = Jade.Css.RealPosition(this.references.css_cell);
						this.tooltip.Position(coords[0]-108,coords[1]+19);
						this.tooltip.Size(300, 70);
						this.tooltip.Add(document.body);
					}
					Jade.FX.Show(this.tooltip);
					
					var strMsg ='';
					var data = this.realValue;
					strMsg += '<p><b>'+Jade.Lang.Get('date')+':</b> '+Jade.DateTime.toShowDate(data.Fecha)+'</p>';
					strMsg += '<p><b>'+Jade.Lang.Get('time')+':</b> '+Jade.DateTime.toShowTime(data.Hora)+'</p>';
					strMsg += '<b>'+Jade.Lang.Get('terminal')+':</b> '+Jade.Utils.AAText(aTerminals, data.IdTerminal)+'<br />';
					strMsg += '<b>'+Jade.Lang.Get('closed')+':</b> '+((data.Cerrado=='1')?Jade.Lang.Get('yes'):Jade.Lang.Get('no'))+'<br />';
					strMsg += '<b>'+Jade.Lang.Get('incidence')+':</b> '+Jade.Utils.AAText(aEvents, data.IdIncidencia)+'<br />';
					
					this.tooltip.SetText(strMsg);
				}
			}
			row.cells[index].onmouseout=function(){
				if(typeof(this.tooltip)!="undefined"){ Jade.FX.Hide(this.tooltip); }
			}
			row.cells[index].ondblclick=function(){
				if(Jade.Utils.Privilege('checks_date_time')){
					if(this.value!='' && this.value!=Jade.Lang.Get('missing_exit')){ ShowWindow(this.references.row, this); }
					else{ ShowWindow(this.references.row); }
				}
			}
			row.cells[index].oncontextmenu=function(ev){
				var row=this.references.row;
				var cell=this;

				mnuContext.items['add'].SetEnabled(Jade.Utils.Privilege('checks_add'));
				mnuContext.items['modify'].SetEnabled(Jade.Utils.Privilege('checks_date_time') && cell.value!=''  && cell.value!=$.lng('missing_exit'));
				mnuContext.items['delete'].SetEnabled(false);
				mnuContext.items['previus'].SetEnabled(false);
				mnuContext.items['next'].SetEnabled(false);
				
				if(Jade.Utils.Privilege('checks_date_time') && cell.value!='' && cell.value!=Jade.Lang.Get('missing_exit')){
					if(Jade.Utils.Privilege('checks_add')){	mnuContext.items['delete'].SetEnabled(true); }
					if(row.index!=0 && cell.index==0 && row.cells[9].value=='0'){ mnuContext.items['previus'].SetEnabled(true); }
					if(typeof(grChecks.rows[row.index+1])!="undefined" && grChecks.rows[row.index+1].cells[9].value=='0'&&cell.references.row.count==cell.index+1){mnuContext.items['next'].SetEnabled(true);}
				}
				mnuContext.row=row;
				mnuContext.cell=cell;
				mnuContext.MousePop(ev);
			}
		}
		function Draw_CellData(row, position,item) {
			var strValue=Jade.DateTime.toShowTime(item.Hora);
			if(item.IdIncidencia != '0000') { strValue += '['+item.IdIncidencia+']'; }
			row.cells[position].SetValue(strValue);
			row.count = position;
			row.cells[position].index=position-1;
			switch(item.Status){
				case 0:
					row.cells[position].ChangeStyle('');
					break;
				case 1:
					row.cells[position].ChangeStyle('blue');
					break;
				default:
					row.cells[position].ChangeStyle('orange');
					break;
			}
			var realValue={};
			realValue.Fecha=item.Fecha;
			realValue.Hora=item.Hora;
			realValue.IdIncidencia = item.IdIncidencia;
			realValue.FechaValor=item.FechaValor;
			realValue.FechaOriginal=item.FechaOriginal;
			realValue.HoraOriginal=item.HoraOriginal;
			realValue.IdIncidenciaOriginal=item.IdIncidenciaOriginal;
			realValue.Tarjeta=item.Tarjeta;
			realValue.IdUbicacion=item.IdUbicacion;
			realValue.IdCentro=item.IdCentro;
			realValue.IdTerminal=item.IdTerminal;
			realValue.Cerrado = item.Cerrado;
			realValue.Status = item.Status;
			row.cells[position].realValue = realValue;
		}
		function ReorderDate(row,newCell,modification){
			var firstRow=row;
			if(row.cells[9].value=='1') { for(var i = row.index-1; firstRow.cells[9].value!='0'; i--){ firstRow = grChecks.rows[i]; } }
			var firstIndex=firstRow.index;

			var newCells=[];
			for(var i=firstIndex; typeof(grChecks.rows[i])!="undefined" && grChecks.rows[i].cells[8].value==firstRow.cells[8].value;i++){
				for(var j=1;j<=6;j++){
					var cell = grChecks.rows[i].cells[j];
					if(cell.value!='' && cell.value!=Jade.Lang.Get('missing_exit')){ newCells.push(cell.realValue); }
				}
			}
			if(typeof(newCell)!="undefined"){
				if(modification==true){ newCell.Status=3; }
				else{ newCell.Status=2; }
				newCells.push(newCell); 
			}
			var sort=function(a,b){ return (a.Fecha+a.Hora)-(b.Fecha+b.Hora); }
			newCells.sort(sort);
			var date = firstRow.cells[8].value;
			for(var i=firstIndex; typeof(grChecks.rows[i])!="undefined" && grChecks.rows[i].cells[8].value==date;) {
				grChecks.rows[i].Delete();
			}
			var nChecks=0;
			var currentRow;
			if(firstIndex==grChecks.rows.length){ currentRow=Draw_NewRow(date,true); }
			else{ currentRow=Draw_NewRow(date,true,grChecks.rows[firstIndex]); }
			for(var j in newCells){
				if(nChecks==6){
					currentRow=Draw_NewRow(date,false,grChecks.rows[currentRow.index+1]);
					nChecks=0;
				}
				Draw_CellData(currentRow,nChecks+1,newCells[j]);
				nChecks++;
			}
			Draw_MissingExit(currentRow,nChecks);
		}
	}
	{//Events
		mnuContext.items['add'].onclick=function(){
			if(Jade.Utils.Privilege('checks_date_time')){ ShowWindow(mnuContext.row); }
		}
		mnuContext.items['modify'].onclick=function(){
			if(Jade.Utils.Privilege('checks_date_time')){ ShowWindow(mnuContext.row, mnuContext.cell); }
		}		
		mnuContext.items['delete'].onclick=function(){
			mnuContext.cell.value='';
			checksDel.push(mnuContext.cell.realValue);
			ReorderDate(mnuContext.row);
		}
		mnuContext.items['previus'].onclick=function(){
			var currentRow=mnuContext.row;
			var previusRow=currentRow;
			for(var i=currentRow.index;previusRow.index!=0 && previusRow.cells[8].value==currentRow.cells[8].value;i--){
				previusRow=grChecks.rows[i];
			}
			
			var value=mnuContext.cell.realValue;
			value.Status='2';
			checksMod.push({
				'pkDate': value.FechaOriginal, 'pkTime': value.HoraOriginal,
				'oldDate': value.Fecha,'oldDateValue': value.FechaValor, 'oldTime': value.Hora, 'oldEvent': value.IdIncidencia,
				'newDate': value.Fecha,'newDateValue': previusRow.cells[8].value, 'newTime': value.Hora, 'newEvent': value.IdIncidencia
			});
			
			ReorderDate(previusRow,value,true);
			mnuContext.cell.value='';
			ReorderDate(mnuContext.row);
		}
		mnuContext.items['next'].onclick = function() {
			var currentRow=mnuContext.row;
			var nextRow=currentRow;
			for(var i=currentRow.index; nextRow.index!=grChecks.rows.length-1 && nextRow.cells[8].value==currentRow.cells[8].value;i++){
				nextRow=grChecks.rows[i];
			}

			var value=mnuContext.cell.realValue;
			value.Status='2';
			checksMod.push({
				'pkDate': value.FechaOriginal, 'pkTime': value.HoraOriginal,
				'oldDate': value.Fecha,'oldDateValue': value.FechaValor, 'oldTime': value.Hora, 'oldEvent': value.IdIncidencia,
				'newDate': value.Fecha,'newDateValue': nextRow.cells[8].value, 'newTime': value.Hora, 'newEvent': value.IdIncidencia
			});

			mnuContext.cell.value='';
			ReorderDate(mnuContext.row);
			ReorderDate(nextRow, mnuContext.cell.realValue);
		}
	}
}