{//Ajax
	var ajaxManager=Jade.AjaxManager();
	ajaxManager.Create('basic');
	{//FIXES
		//DELETE FROM PETICIONES{c} WHERE IdPeticion NOT IN (SELECT DISTINCT IdPeticion FROM PETICIONES_LINEAS{c})
		//DELETE FROM PETICIONES_LINEAS{c} WHERE Valor LIKE ''
		//DELETE FROM PETICIONES_CAMBIOS_ESTADO{c} WHERE IdLinea='0'
		
		//Jade.AjaxDBDelete("PETICIONES{c}", "IdPeticion NOT IN (SELECT DISTINCT IdPeticion FROM PETICIONES_LINEAS{c})");
		//Jade.AjaxDBDelete("PETICIONES_LINEAS{c}", "Valor LIKE ''");
		//Jade.AjaxDBDelete("PETICIONES_CAMBIOS_ESTADO{c}", "IdLinea='0'");
	}
	{//Terms
		var aTerms=[];
		aTerms['0']=Jade.Lang.Get('term_week');
		aTerms['1']=Jade.Lang.Get('term_month');
		aTerms['2']=Jade.Lang.Get('term_year');
		
	}
	{//Employees
		var aEmployees=[];
		var ajaxEmployees=Jade.AjaxDB("SELECT Codigo,Nombre,Apellidos 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($.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;
					}
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//DayTypes
		var aDayTypes=[];
		var ajaxDayTypes=Jade.AjaxDB("SELECT * FROM TIPO_DIA{c} ORDER BY Codigo");
		ajaxDayTypes.Add(ajaxManager,'basic');
		ajaxDayTypes.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					aDayTypes[item.Codigo]={};
					aDayTypes[item.Codigo].Text=item.Codigo+" - "+item.Descripcion;
					aDayTypes[item.Codigo].Codigo=item.Codigo;
					aDayTypes[item.Codigo].Descripcion=item.Descripcion;
					aDayTypes[item.Codigo].Laborable=item.Laborable;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Events
		var aEvents=[];
		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].Valorada=item.Valorada;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Workday
		var aWorkdays=[];
		var ajaxWorkdays=new 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); }
		}
	}
	{//Accruals
		var aAccruals=[];
		var ajaxAccruals=Jade.AjaxDB("SELECT * FROM ACUMULADORES{c} ORDER BY Codigo");
		ajaxAccruals.Add(ajaxManager,'basic');
		ajaxAccruals.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++)	{
					var item=this.json.row[i];
					aAccruals[item.Codigo]={};
					aAccruals[item.Codigo].Text=item.Codigo+" - "+item.Descripcion;
					aAccruals[item.Codigo].Codigo=item.Codigo;
					aAccruals[item.Codigo].Descripcion=item.Descripcion;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Breaks
		var aBreaks=[];
		var ajaxBreaks=Jade.AjaxDB("SELECT * FROM INTERRUPCIONES{c} ORDER BY Codigo");
		ajaxBreaks.Add(ajaxManager,'basic');
		ajaxBreaks.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					aBreaks[item.Codigo]={};
					aBreaks[item.Codigo].Text=item.Codigo+" - "+item.Descripcion;
					aBreaks[item.Codigo].Codigo=item.Codigo;
					aBreaks[item.Codigo].Descripcion=item.Descripcion;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Payrolls
		var aPayrolls=[];
		var ajaxPayrolls=Jade.AjaxDB("SELECT * FROM COSTES{c} ORDER BY Codigo");
		ajaxPayrolls.Add(ajaxManager,'basic');
		ajaxPayrolls.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length; i<iLen;i++){
					var item=this.json.row[i];
					aPayrolls[item.Codigo]={};
					aPayrolls[item.Codigo].Text=item.Codigo+" - "+item.Descripcion;
					aPayrolls[item.Codigo].Codigo=item.Codigo;
					aPayrolls[item.Codigo].Descripcion=item.Descripcion;
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	{//Users
		var aUsers=[];
		var ajaxUsers=new Jade.AjaxDB("SELECT * FROM users WHERE companyId='{c}' OR root='1' ORDER BY id");
		ajaxUsers.Add(ajaxManager,'basic');
		ajaxUsers.oncomplete=function(){
			if(!this.json.error){
				for(var i=0,iLen=this.json.row.length;i<iLen;i++){
					var item=this.json.row[i];
					aUsers[item.id]={};
					aUsers[item.id].name=item.name;
					aUsers[item.id].Text=$.Encrypt.Decrypt(item.name);
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
	}
	ajaxManager.group['basic'].Start();
	ajaxManager.group['basic'].oncomplete=function(){
		if(EMPLOYEES.length!=1 || USER.empl_acc_all=='1' || USER.root==1){
			for(var i in aEmployees){
				cmbEmployee.AddItem(aEmployees[i].Text, aEmployees[i].Codigo);
			}
		}
		LoadPetitions(); 
	}
}
{//Controls
	var gpHeader=Jade.Objects.Container();
	gpHeader.Add();

	var lblDate_From=Jade.Objects.Text(Jade.Lang.Get('from_date')+':');
	lblDate_From.Add(gpHeader);
	var cmbDate_From=Jade.Objects.DatePicker();
	cmbDate_From.Add(gpHeader);

	var lblDate_To=Jade.Objects.Text(Jade.Lang.Get('to_date')+':');
	lblDate_To.Add(gpHeader);
	var cmbDate_To=Jade.Objects.DatePicker();
	cmbDate_To.Add(gpHeader);

	var lblStatus=Jade.Objects.Text(Jade.Lang.Get('status')+':');
	lblStatus.Add(gpHeader);
	var cmbStatus=Jade.Objects.ComboBox();
	cmbStatus.Add(gpHeader);	
	
	var cmdRefresh=Jade.Objects.Button();
	cmdRefresh.SetText(Jade.Lang.Get('refresh'));
	cmdRefresh.Add(gpHeader);
	
	var cmPetitions=Jade.Grids.ColumnModel();
	cmPetitions.Add(Jade.Grids.SpecialTreeColumn({key: 'employee', width: '24', sortable: false}));
	cmPetitions.Add(Jade.Grids.SimpleColumn({key: 'date', text: Jade.Lang.Get('date'), width: '90'}));
	cmPetitions.Add(Jade.Grids.SimpleColumn({key: 'time', text: Jade.Lang.Get('time'), width: '75'}));
	cmPetitions.Add(Jade.Grids.SimpleColumn({key: 'user', text: Jade.Lang.Get('user'), width: '150'}));
	cmPetitions.Add(Jade.Grids.SimpleColumn({key: 'data', text: Jade.Lang.Get('petition'), width: '495'}));
	cmPetitions.Add(Jade.Grids.ComboColumn({key: 'status', text: Jade.Lang.Get('status'), width: '140'}));
	cmPetitions.Add(Jade.Grids.HideColumn({key: 'code'}));
	
	var grPetitions=Jade.Grids.Grid(cmPetitions);
	grPetitions.Add();

	cmdRefresh.onclick=function(){ LoadPetitions(); }
	
	var strYear=Jade.DateTime.CurrentYear();
	var strMonth=Jade.Strings.PadLeft(Jade.DateTime.CurrentMonth(),'0',2);
	var strLastDay=Jade.DateTime.Monthdays(strMonth, strYear);
	
	cmbDate_From.SetValue(strYear+strMonth+'01');
	cmbDate_To.SetValue(strYear+strMonth+strLastDay);
	
	cmbStatus.AddItem(Jade.Lang.Get('all_p_f'),'all');
	cmbStatus.AddItem(Jade.Lang.Get('petition_status_0'),'0');
	cmbStatus.AddItem(Jade.Lang.Get('petition_status_1'),'1');
	cmbStatus.AddItem(Jade.Lang.Get('petition_status_2'),'2');
	
	if(EMPLOYEES.length==1 && USER.empl_acc_all=='0'){
		gpHeader.Location(0,0,1000,40);
		lblDate_From.Location(15,15,100,20);
		cmbDate_From.Location(115,10,105,20);
		lblDate_To.Location(230,15,100,20);
		cmbDate_To.Location(330,10,105,20);
		lblStatus.Location(450,15,95,20);
		cmbStatus.Location(545,10,180,20);
		cmdRefresh.Location(800,10,190,20);
		grPetitions.Location(0,50,1000,490);		
	}
	else{
		gpHeader.Location(0,0,1000,65);
		lblDate_From.Location(15,40,100,20);
		cmbDate_From.Location(115,35,105,20);
		
		lblDate_To.Location(230,40,100,20);
		cmbDate_To.Location(330,35,105,20);
		
		lblStatus.Location(450,40,95,20);
		cmbStatus.Location(545,35,180,20);
		cmdRefresh.Location(800,35,190,20);
		grPetitions.Location(0,75,1000,465);
		
		var lblEmployee=Jade.Objects.Text(Jade.Lang.Get('employee')+':');
		lblEmployee.Location(15,15,100,20);
		lblEmployee.Add(gpHeader);
		
		var cmbEmployee=Jade.Objects.ComboBox();
		cmbEmployee.Location(115,10,610,20);
		cmbEmployee.Add(gpHeader);
		
		$.ControlAdd('searchemployee', [730,10,20,20], gpHeader, cmbEmployee);
		
		cmbEmployee.AddItem(Jade.Lang.Get('all_p_m'),'all');
	}
}
var aPetitions=new Map();

function LoadPetitions(){
	grPetitions.Loading(true);
	
	var ajaxMng=Jade.AjaxManager();
	ajaxMng.Create('basic');
	{//Ajax
		var sqlWhere="";
		sqlWhere += "p.Fecha>='"+cmbDate_From.value+"' AND p.Fecha<='"+cmbDate_To.value+"'";
		if(EMPLOYEES.length==1 && (USER.root==0 && USER.empl_acc_all==0)){  sqlWhere +=" AND p.Clave='"+USER.employee+"'";  }
		else if(cmbEmployee.selectedKey!="all"){ sqlWhere += " AND p.Clave='"+cmbEmployee.selectedKey+"'"; }
		if(cmbStatus.selectedIndex!=0){ sqlWhere += " AND p.Estado='"+cmbStatus.selectedKey+"'"; }
		
		$.AjaxDB("SELECT p.* FROM PETICIONES{c} p WHERE "+sqlWhere+" ORDER BY p.Fecha DESC, p.Hora DESC", Ajax.Dontwait).oncomplete=function(){
			aPetitions = new Map();
			for(var i=0, ilen=this.json.row.length; i<ilen; i++){
				var db=this.json.row[i];
				if(Jade.Utils.IsInEmployees(db.Clave)){
					aPetitions.set(db.IdPeticion, {
						IdPeticion: db.IdPeticion,
						IdUsuario: db.IdUsuario, 
						Fecha: db.Fecha, 
						Hora: db.Hora, 
						Familia: db.Familia, 
						Clave: db.Clave,
						Estado: db.Estado, 
						lines:[], 
						changes:[], 
						comments:[]
					});
				}
			}
			ajaxMng.group['basic'].Start();
		}
		
		var ajaxLines=Jade.AjaxDB("SELECT pl.* FROM PETICIONES_LINEAS{c} pl INNER JOIN PETICIONES{c} p ON p.IdPeticion=pl.IdPeticion WHERE "+sqlWhere+" ORDER BY p.Fecha DESC, p.Hora DESC");
		ajaxLines.Add(ajaxMng,'basic');
		ajaxLines.oncomplete = function(){
			if(!$.isDefined(this.json) || !this.json.error){
				for(var i=0, ilen=this.json.row.length; i<ilen; i++){
					var db=this.json.row[i];
					if(aPetitions.has(db.IdPeticion)){
						aPetitions.get(db.IdPeticion).lines.push({Indice:db.Indice, SubFamilia:db.SubFamilia, Accion:db.Accion, Estado:db.Estado, Valor:db.Valor});
					}
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
		
		var ajaxChanges=Jade.AjaxDB("SELECT p.IdPeticion, pe.Fecha, pe.Hora, pe.IdUsuario, pe.EstadoActual, pe.EstadoAnterior "+
		"FROM PETICIONES_CAMBIOS_ESTADO{c} pe INNER JOIN PETICIONES_LINEAS{c} pl ON pe.IdLinea=pl.Indice INNER JOIN PETICIONES{c} p ON pl.IdPeticion=p.IdPeticion "+
		"WHERE "+sqlWhere+" GROUP BY p.IdPeticion, pe.Fecha, pe.Hora, pe.IdUsuario, pe.EstadoActual, pe.EstadoAnterior ORDER BY p.IdPeticion, pe.Fecha, pe.Hora");
		ajaxChanges.Add(ajaxMng, 'basic');
		ajaxChanges.oncomplete = function(){
			if(!$.isDefined(this.json) || !this.json.error){
				for(var i=0, ilen=this.json.row.length; i<ilen; i++){
					var db=this.json.row[i];
					if(aPetitions.has(db.IdPeticion)){
						aPetitions.get(db.IdPeticion).changes.push({Fecha: db.Fecha, Hora: db.Hora, IdUsuario: db.IdUsuario, EstadoActual: db.EstadoActual, EstadoAnterior: db.EstadoAnterior});
					}
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}
		
		var ajaxComments=Jade.AjaxDB("SELECT pc.* FROM PETICIONES_COMENTARIOS{c} pc INNER JOIN PETICIONES{c} p ON p.IdPeticion=pc.IdPeticion WHERE "+sqlWhere+" ORDER BY pc.IdPeticion,pc.Fecha,pc.Hora");
		ajaxComments.Add(ajaxMng,'basic');
		ajaxComments.petition_index=i;
		ajaxComments.oncomplete=function(){
			if(!$.isDefined(this.json) || !this.json.error){
				for(var i=0, ilen=this.json.row.length; i<ilen; i++){
					var db=this.json.row[i];
					if(aPetitions.has(db.IdPeticion)){
						aPetitions.get(db.IdPeticion).comments.push({Fecha: db.Fecha, Hora: db.Hora, IdUsuario: db.IdUsuario, Texto:db.Texto});
					}
				}
			}
			else{ Jade.Debug.Add(this.text); }
		}		
	}
	
	ajaxMng.group['basic'].oncomplete=function(){
		$.delay(0, this, function(){
			grPetitions.ClearRows();
			var i=0;
			$.each(aPetitions, function(petition, key){
				$.delay(0, this, Petition_Template, [grPetitions, petition, ++i==aPetitions.size]);
			});
			if(i==0){ grPetitions.Loading(false); }
		});
	}
}

function Petition_Change(petition,status){
	var timeChange = new Date();
	for(var i in petition.lines){
		Petition_Line_Change(timeChange, petition.lines[i], petition.Familia, status);
	}
	Jade.AjaxDBSave('PETICIONES{c}', ['Estado'], [status], "IdPeticion='"+petition.IdPeticion+"'");
}
function Petition_Line_Change(timeChange, line, family, status){
	var table='';
	var fields=[];
	var values=[];
	var key='';
	var xml=(Jade.XML.parseToJson(line.Valor)).Petition;
	xml.pk=(typeof(xml.PrimaryKey)!="undefined")?xml.PrimaryKey:null;
	xml.nv=(typeof(xml.NewValues)!="undefined")?xml.NewValues:null;
	xml.ov=(typeof(xml.OldValues)!="undefined")?xml.OldValues:null;
	if($.Utils.Is9Digits()){ xml.pk.EmployeeId=$.Strings.PadLeft(xml.pk.EmployeeId, '0', 9); }
	switch(family){
		case '0':case '1':
			switch(line.SubFamilia){
				case '20':
					if((line.Accion==0 && status==2) || (line.Accion==2 && status==1 && line.Estado==2)){
							values=line.Accion==0?xml.nv:xml.ov
							Jade.AjaxDBSave('EMPLEADOS{c}', 
							['Codigo','Nombre', 'Apellidos', 'IdUbicacion','IdCentro','IdHorario','IdPerfil','IdCalendario','Activo'],
							[xml.pk.EmployeeId, values.Name, $.isDefined(values.Surname)?values.Surname:'', values.Department, values.Center, values.Workday, $.Strings.PadLeft(values.Profile, '0', 9), $.Strings.PadLeft(values.Calendar, '0', 9), '1']);
					}
					else if((line.Accion==0 && status==1 && line.Estado==2) || (line.Accion==2 && status==2)){
						Jade.AjaxDBDelete('CALENDARIO{c}',"IdCalendario='"+xml.pk.EmployeeId+"' AND Publico=0");
						Jade.AjaxDBDelete('CIERRE_ACUMULADORES{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('CIERRE_COSTES_DIAS{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('CIERRE_COSTES{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('CIERRE_DESGLOSE_DIAS{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('CIERRE{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('FICHAJES{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('FICHAJES_ACCESO{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('EMPLEADOS_ALTABAJA{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('EMPLEADOS_HORAS_ESTANDAR{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('EMPLEADOS_BIOMETRIAS{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('OBSERVACIONES{c}',"IdEmpleado='"+xml.pk.EmployeeId+"'");
						Jade.AjaxDBDelete('EMPLEADOS{c}',"Codigo='"+xml.pk.EmployeeId+"'");
					}
					break;
				case '0':case'17':case '19':
					if(status==2){ Jade.AjaxDBSave('EMPLEADOS{c}',xml.nv.field,xml.nv.value,"Codigo='"+xml.pk.EmployeeId+"'"); }
					else if(line.Estado==2 && status==1){ Jade.AjaxDBSave('EMPLEADOS{c}',xml.nv.field,(xml.ov==null)?'':xml.ov.value,"Codigo='"+xml.pk.EmployeeId+"'"); }
					break;
				case '1':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_E_S{c}',
						['IdPerfil', 'Publico', 'IdTipoDia', 'Desde', 'Hasta', 'Redondeada', 'Tipo'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.nv.From, xml.nv.To, xml.nv.Rounding, xml.nv.EntryExit]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.DayType, xml.ov.From, xml.ov.To, xml.ov.Rounding, xml.ov.EntryExit]:null
					);
					break;
				case '2':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_INCIDENCIAS{c}',
						['IdPerfil', 'Publico', 'IdTipoDia', 'Desde', 'Hasta', 'IdIncidencia', 'Tipo'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.nv.From, xml.nv.To, xml.nv.Event, xml.nv.EntryExit]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.DayType, xml.ov.From, xml.ov.To, xml.ov.Event, xml.ov.EntryExit]:null
					);
					break;
				case '4':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_SALDOS{c}',
						['IdPerfil', 'Publico', 'IdAcumulador', 'VecesPermitidas', 'TiempoPermitido', 'Periodo'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.Accrual, xml.nv.Ocurrence, xml.nv.TimeAllowed, xml.nv.Term]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.Accrual, xml.ov.Ocurrence, xml.ov.TimeAllowed, xml.ov.Term]:null
					);
					break;
				case '5':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_INTERRUPCIONES{c}',
						['IdPerfil', 'Publico', 'IdTipoDia', 'IdInterrupcion'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.nv.From, xml.nv.To, xml.nv.Event, xml.nv.EntryExit]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.DayType, xml.ov.From, xml.ov.To, xml.ov.Event, xml.ov.EntryExit]:null
					);
					break;
				case '9':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_COSTES{c}',
						['IdPerfil', 'Publico', 'IdTipoDia', 'IdCoste'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.nv.Payroll]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.DayType, xml.ov.Payroll]:null
					);
					break;
				case '10':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_SIN_ACCESO{c}',
						['IdPerfil', 'Publico', 'Desde', 'Hasta'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.From, xml.nv.To]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.ov.From, xml.ov.To]:null
					);
					break;
				case '13':
					ChangeGeneric(line.Accion, status, line.Estado, 'PERFILES_FORZAR_ACCESO{c}',
						['IdPerfil', 'Publico', 'IdTipoDia', 'Desde', 'Hasta'], [],
						$.isDefined(xml.nv)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.nv.From, xml.nv.To]:null,
						$.isDefined(xml.ov)?[xml.pk.EmployeeId, '0', xml.nv.DayType, xml.ov.From, xml.ov.To]:null
					);
					break;
				case '14':
					Jade.AjaxDBDelete('CALENDARIO{c}',"IdCalendario='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.pk.Date+"' AND Publico=0");
					if(status==2){
						fields=['IdCalendario','Fecha','Publico','IdTipoDia','IdVariante','IdIncidencia','IdHorario','TipoVariante','Observaciones'];
						values=[xml.pk.EmployeeId,xml.pk.Date,0,xml.nv.Daytype,xml.nv.Variant,xml.nv.Event,xml.nv.Workday,xml.nv.ForceVariant,xml.nv.Comments];
						Jade.AjaxDBSave('CALENDARIO{c}',fields,values);
					}
					else if(line.Estado==2 && status==1){
						if(xml.ov!=null){
							fields=['IdCalendario','Fecha','Publico','IdTipoDia','IdVariante','IdIncidencia','IdHorario','TipoVariante','Observaciones'];
							values=[xml.pk.EmployeeId,xml.pk.Date,0,xml.ov.Daytype,xml.ov.Variant,xml.ov.Event,xml.ov.Workday,xml.ov.ForceVariant,xml.ov.Comments];
							Jade.AjaxDBSave('CALENDARIO{c}',fields,values);
						}
					}
					break;
				case '15':
					Jade.AjaxDBDelete('EMPLEADOS_HORAS_ESTANDAR{c}',"IdEmpleado='"+xml.pk.EmployeeId+"' AND Mes='"+xml.pk.Month+"' AND Anho='"+xml.pk.Year+"'");
					fields=['IdEmpleado','Anho','Mes','Total'];
					if(status==2){
						values=[xml.pk.EmployeeId, xml.pk.Year, xml.pk.Month, xml.nv.value];
						Jade.AjaxDBSave('EMPLEADOS_HORAS_ESTANDAR{c}', fields, values);
					}
					else if(line.Estado==2 && status==1 && xml.ov!=null){
						values=[xml.pk.EmployeeId, xml.pk.Year, xml.pk.Month, xml.ov.value];
						Jade.AjaxDBSave('EMPLEADOS_HORAS_ESTANDAR{c}', fields, values);
					}
					break;
				case '16':
					table='EMPLEADOS_ALTABAJA{c}';
					switch(line.Accion){
						case '0':
							if(status==2){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha'], [xml.pk.EmployeeId, xml.nv.Date]); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBDelete(table,"IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.nv.Date+"'"); }
							break;
						case '1':
							if(status==2){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha'], [xml.pk.EmployeeId, xml.nv.Date], "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.ov.Date+"'"); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha'], [xml.pk.EmployeeId, xml.ov.Date], "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.nv.Date+"'"); }
							break;
						case '2':
							if(status==2){ Jade.AjaxDBDelete(table, "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.ov.Date+"'"); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha'], [xml.pk.EmployeeId, xml.ov.Date]); }
							break;							
					}
					$.AjaxDB("SELECT Count(*) c FROM EMPLEADOS_ALTABAJA{c} WHERE IdEmpleado='"+xml.pk.EmployeeId+"'", Ajax.Dontwait).oncomplete=function(){
						$.AjaxDBSave("EMPLEADOS{c}", ["Activo"],[this.json.row[0]['c']%2==0?'0':'1'], "Codigo='"+xml.pk.EmployeeId+"'");
					}
					
					break;
				case '18':
					table='OBSERVACIONES{c}';
					switch(line.Accion){
						case '0':
							if(status==2){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha', 'Hora', 'Texto'], [xml.pk.EmployeeId, xml.nv.Date, xml.nv.Time, xml.nv.Text]); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBDelete(table,"IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.nv.Date+"' AND Hora='"+xml.nv.Time+"'"); }
							break;
						case '1':
							if(status==2){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha', 'Hora', 'Texto'], [xml.pk.EmployeeId, xml.nv.Date, xml.nv.Time, xml.nv.Text], "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.ov.Date+"' AND Hora='"+xml.ov.Time+"'"); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha', 'Hora', 'Texto'], [xml.pk.EmployeeId, xml.ov.Date, xml.ov.Time, xml.ov.Text], "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.nv.Date+"' AND Hora='"+xml.nv.Time+"'"); }
							break;
						case '2':
							if(status==2){ Jade.AjaxDBDelete(table, "IdEmpleado='"+xml.pk.EmployeeId+"' AND Fecha='"+xml.ov.Date+"' AND Hora='"+xml.ov.Time+"'"); }
							else if(line.Estado==2 && status==1){ Jade.AjaxDBSave(table, ['IdEmpleado', 'Fecha', 'Hora', 'Texto'], [xml.pk.EmployeeId, xml.ov.Date, xml.ov.Time, xml.ov.Text]); }
							break;							
					}
					break;
			}
			break;
		case '6':
			if(line.SubFamilia=='0'){
				table='FICHAJES{c}';
				switch(line.Accion){
					case '0':
						if(status==2){
							fields=['IdEmpleado','Fecha','Hora','IdTerminal','IdIncidencia','FechaValor', 'FechaOriginal','HoraOriginal','IdIncidenciaOriginal','Cerrado','Virtual'];
							values=[xml.pk.EmployeeId,xml.nv.Date,xml.nv.Time,'###',xml.nv.EventId,xml.nv.ValueDate,xml.nv.Date,xml.nv.Time,xml.nv.EventId,'0','0'];
							var result=Jade.AjaxDBSave(table,fields,values);
							if(result.error.indexOf('Duplicate entry')>-1){ $.Objects.MessageBox($.Strings.Format($.lng('duplicate_punch'), xml.pk.EmployeeId, $.DateTime.toShowDate(xml.nv.Date), $.DateTime.toShowTime(xml.nv.Time)), 'info'); }
						}
						else if(line.Estado==2 && status==1){
							var result=Jade.AjaxDBDelete(table,"IdEmpleado='"+xml.pk.EmployeeId+"' AND FechaOriginal='"+xml.pk.Date+"' AND HoraOriginal='"+xml.pk.Time+"'");
						}
						break;
					case '1':
						if(status==2){
							fields=['Fecha','Hora','IdTerminal','IdIncidencia','FechaValor','FechaOriginal','HoraOriginal','IdIncidenciaOriginal','Cerrado'];
							values=[xml.nv.Date,xml.nv.Time,'###',xml.nv.EventId,xml.nv.ValueDate,xml.nv.Date,xml.nv.Time,xml.nv.EventId,'0'];
							var result=Jade.AjaxDBSave(table,fields,values,"IdEmpleado='"+xml.pk.EmployeeId+"' AND FechaOriginal='"+xml.ov.Date+"' AND HoraOriginal='"+xml.ov.Time+"'");
							if(result.error.indexOf('Duplicate entry')>-1){ $.Objects.MessageBox($.Strings.Format('El fichaje del empleado {0} el {1} a las {2} ya existe', xml.pk.EmployeeId, $.DateTime.toShowDate(xml.nv.Date), $.DateTime.toShowTime(xml.nv.Time)), 'info'); }
						}
						else if(line.Estado==2 && status==1){
							fields=['Fecha','Hora','IdTerminal','IdIncidencia','FechaValor','FechaOriginal','HoraOriginal','IdIncidenciaOriginal','Cerrado'];
							values=[xml.ov.Date, xml.ov.Time, xml.ov.Terminal, xml.ov.EventId, xml.ov.ValueDate,xml.ov.Date,xml.ov.Time,xml.ov.EventId,'0'];
							var result=Jade.AjaxDBSave(table,fields,values,"IdEmpleado='"+xml.pk.EmployeeId+"' AND FechaOriginal='"+xml.nv.Date+"' AND HoraOriginal='"+xml.nv.Time+"'");
							if(result.error.indexOf('Duplicate entry')>-1){ $.Objects.MessageBox($.Strings.Format('El fichaje del empleado {0} el {1} a las {2} ya existe', xml.pk.EmployeeId, $.DateTime.toShowDate(xml.ov.Date), $.DateTime.toShowTime(xml.ov.Time)), 'info'); }
						}
						break;
					case '2':
						if(status==2){ Jade.AjaxDBDelete(table,"IdEmpleado='"+xml.pk.EmployeeId+"' AND FechaOriginal='"+xml.pk.Date+"' AND HoraOriginal='"+xml.pk.Time+"'"); }
						else if(line.Estado==2 && status==1){
							fields=['IdEmpleado','Fecha','Hora','IdTerminal','IdIncidencia','FechaValor','FechaOriginal','HoraOriginal','IdIncidenciaOriginal','Cerrado','Virtual'];
							values=[xml.pk.EmployeeId,xml.ov.Date,xml.ov.Time,xml.ov.Terminal,xml.ov.EventId,xml.ov.ValueDate,xml.ov.Date,xml.ov.Time,xml.ov.OriginalEventId,'0','0'];
							var result=Jade.AjaxDBSave(table,fields,values);
							if(result.error.indexOf('Duplicate entry')>-1){ $.Objects.MessageBox($.Strings.Format('El fichaje del empleado {0} el {1} a las {2} ya existe', xml.pk.EmployeeId, $.DateTime.toShowDate(xml.ov.Date), $.DateTime.toShowTime(xml.ov.Time)), 'info'); }
						}
						break;
				}
			}
			break;
	}
	
	fields=['IdUsuario','Fecha','Hora','IdLinea','EstadoActual','EstadoAnterior','EstadoEnvio'];
	values=[USER.id, Jade.DateTime.toStoreDate(timeChange), Jade.DateTime.toStoreTime(timeChange), line.Indice, status, line.Estado, '0'];
	Jade.AjaxDBSave('PETICIONES_CAMBIOS_ESTADO{c}', fields, values);
	Jade.AjaxDBSave('PETICIONES_LINEAS{c}', ['Estado'], status, "Indice='"+line.Indice+"'");
	line.Estado=status;
}
function ChangeGeneric(type, action, status, table, fieldsWhere, fields, nv, ov){
	var fieldsAll=fieldsWhere.concat(fields);
	switch(type){
		case 0: case 3:
			if(action==2){ transaction.save(table, fieldsAll, nv); }
			else if(action==1 && status==2){ $.AjaxDBDelete(table, ChangeWhere(fieldsWhere, nv)); }
			break;
		case 1:
			if(action==2){ $.AjaxDBSave(table, fieldsAll, nv, this.ChangeWhere(fieldsWhere, ov)); }
			else if(action==1 && status==2){ $.AjaxDBSave(table, fieldsAll, ov, ChangeWhere(fieldsWhere, nv)); }
			break;
		case 2: case 4:
			if(action==2){ $.AjaxDBDelete(table, this.ChangeWhere(fieldsWhere, ov)); }
			else if(action==1 && status==2){ $.AjaxDBSave(table, fieldsAll, ov); }
			break;
		default:
			$.AjaxDBDelete(table, this.ChangeWhere(fieldsWhere, nv));
			$.AjaxDBSave(table, fieldsAll, (action==1 && status==2 && $.isDefined(ov))?ov:nv);
			break;
	}
}
function ChangeWhere(fields, values){
	var where=[];
	for (var i in fields) {
		if($.isDefined(values[i])){
			where.push( fields[i] + "='" + values[i] + "'" );
		}
	}
	return where.join(' AND ');
}

function Petition_Template(container, petition, last){
	if(petition.lines.length>0){
		var row=container.NewRow(['', Jade.Strings.ToDate(petition.Fecha), Jade.Strings.ToTime(petition.Hora), $.Utils.AAUser(aUsers, petition.IdUsuario), Jade.Strings.VisualTrim(Jade.Utils.PetitionFamily(petition.Familia, petition.Clave, petition.lines[0].Accion),490)]);
		row.data = petition;
		row.builded = false;
		
		{//Estado
			var combo=row.cells[5].references.object;
			combo.row=row;
			combo.SetStyle('grid petition');
			combo.AddHideItem('<span class="p0">'+Jade.Lang.Get('petition_status_0')+'</span>','0','p0');
			combo.AddItem('<span class="p1">'+Jade.Lang.Get('petition_status_1')+'</span>','1','p1');
			combo.AddItem('<span class="p2">'+Jade.Lang.Get('petition_status_2')+'</span>','2','p2');
			combo.SetSelectedKey(petition.Estado);
			if(Jade.Utils.PrivilegeValue('empl_priv')!=2 || (Jade.Utils.PrivilegeValue('empl_priv')==4 && USER.employee == petition.EmployeeCode)){ combo.SetEnabled(false); }
			else{ 
				combo.onchange=function(){
					Petition_Change(this.row.data, this.selectedKey); 
				} 
			}
		}
		{//On expand
			row.container = container.AddSubElement(row, document.createElement('div'));
			row.onexpand = function(){
				if(!this.builded){
					this.builded = true;
					Details_Template(row, row.container, row.data);
				}
			}
		}

	}
	if(last){
		container.Loading(false);
	}
}
function Details_Template(row, container, petition){
	{//Lineas
		$.dom.Add(container, 'div', 'subitem petition_header', null, $.lng('details')+':');
		
		var subitem = $.dom.Add(container, 'div', 'subitem petition');
		for(var j=0,jLen=petition.lines.length;j<jLen;j++){
			if(j>0 && petition.lines[j].SubFamilia!=petition.lines[j-1].SubFamilia){ subitem.grid!=null; }
			Line_Template(subitem, petition, petition.lines[j]); 
		}
	}
	{//Cambios
		if(petition.changes.length>0){
			$.dom.Add(container, 'div', 'subitem petition_header', null, $.lng('status_changes')+':');
			
			var strChanges = '<div class="back text-size"></div>';
			for(var j=0,jLen=petition.changes.length;j<jLen;j++){
				var change=petition.changes[j];
				strChanges += Changes_Template(change.Fecha, change.Hora, change.IdUsuario, change.EstadoAnterior, change.EstadoActual)
			}
			strChanges += '</div>';
			
			$.dom.Add(container, 'div', 'subitem petition text-size', null, strChanges);
		}
	}
	{//Comentarios
		$.dom.Add(container, 'div', 'subitem petition_header', null, $.lng('comments')+':');
		
		var str = '<div class="back text-size"></div>';
		for(var j=0,jLen=petition.comments.length;j<jLen;j++){
			var comment=petition.comments[j];
			str += Comment_Template(comment.Fecha, comment.Hora, comment.IdUsuario, comment.Texto);
		}
		str += '</div>';
		var rowComments = $.dom.Add(container, 'div', 'subitem petition no-border text-size', null, str);
		
		var subitem = $.dom.Add(container, 'div', 'subitem petition text-size');
		subitem.style.height = '144px';
			
		var lblComments=Jade.Objects.Text(Jade.Lang.Get('new_comment')+':');
		lblComments.Location(10,00,960,20);
		lblComments.Add(subitem);
		
		var txtComments=Jade.Objects.TextArea();
		txtComments.Location(10,20,960,100);
		txtComments.Add(subitem);
		
		var cmdComments=Jade.Objects.Button(Jade.Lang.Get('add_comment'));
		cmdComments.Location(10,130,960,20);
		cmdComments.Add(subitem);
		
		cmdComments.rowComments=rowComments;
		cmdComments.IdPetition=petition.IdPeticion;
		cmdComments.IdEmployee=petition.EmployeeCode;
		cmdComments.textarea=txtComments;
		cmdComments.onclick=function(){
			var text=Jade.Strings.Trim(this.textarea.GetText());
			if(text!=''){
				cmdComments.SetEnabled(false);
				var date=Jade.DateTime.toStoreDate(Jade.DateTime.Now());
				var time=Jade.DateTime.toStoreTime(Jade.DateTime.Now());
				text=this.textarea.GetText();
				
				var ajaxDB=Jade.Ajax();
				ajaxDB.AddParam('save', "PETICIONES_COMENTARIOS{c}");
				ajaxDB.AddParamArray('fields', ['IdPeticion','IdUsuario','Fecha','Hora','Texto']);
				ajaxDB.AddParamArray('values', [this.IdPetition,USER.id,date,time,text]);
				ajaxDB.Run('lib/php/ajax_db.php');
				
				if(ajaxDB.json.result=='1'){
					this.rowComments.innerHTML+=Comment_Template(date,time,USER.id,text);
					this.textarea.SetText('');
				}
				cmdComments.SetEnabled(true);
			}
		}
	}
}
function Line_Template(container, petition, line){
	{//Obtenemos y parseamos los valores xml de la peticion
		var oldVal,newVal;
		var xml=Jade.XML.parseToJson(line.Valor);
		if(typeof(xml.Petition)!="undefined" && typeof(xml.Petition.OldValues)!="undefined"){ oldVal=xml.Petition.OldValues; }
		if(typeof(xml.Petition)!="undefined" && typeof(xml.Petition.NewValues)!="undefined"){ newVal=xml.Petition.NewValues; }
	}
	if(!$.isDefined(container.grid) || container.grid.Familia!=petition.Familia || container.grid.SubFamilia!=line.SubFamilia){ Header_Template(container, petition, line); }
	var action_label=Jade.Utils.PetitionLine(line.Accion, petition.Familia, line.SubFamilia, petition.Clave)+':';
	var oValues=[],nValues=[],mValues=[];
	
	switch(petition.Familia){
		case '0':case '1':
			if($.Utils.Is9Digits()){ xml.Petition.PrimaryKey.EmployeeId=$.Strings.PadLeft(xml.Petition.PrimaryKey.EmployeeId, '0', 9); }
			switch(line.SubFamilia){
				case '0': case '17': case '19':
					if(typeof(oldVal)!="undefined"){ oValues=[action_label,oldVal.field,oldVal.value]; }
					if(typeof(newVal)!="undefined"){ nValues=[action_label,newVal.field,newVal.value]; }
					if(typeof(oldVal)!="undefined" && typeof(newVal)!="undefined"){ mValues=['','',newVal.value]; }
					break;
				case '1':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aDayTypes[oldVal.DayType].Text,
							Jade.Strings.ToTime(oldVal.From),
							Jade.Strings.ToTime(oldVal.To),
							Jade.Strings.ToTime(oldVal.Rounding),
							oldVal.EntryExit==0?Jade.Lang.Get('entry'):Jade.Lang.Get('exit')
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aDayTypes[newVal.DayType].Text,
							Jade.Strings.ToTime(newVal.From),
							Jade.Strings.ToTime(newVal.To),
							Jade.Strings.ToTime(newVal.Rounding),
							newVal.EntryExit==0?Jade.Lang.Get('entry'):Jade.Lang.Get('exit')
						];
					}
					break;
				case '2':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aDayTypes[oldVal.DayType].Text,
							Jade.Strings.ToTime(oldVal.From),
							Jade.Strings.ToTime(oldVal.To),
							aEvents[oldVal.Event].Text,
							oldVal.EntryExit==0?Jade.Lang.Get('entry'):Jade.Lang.Get('exit')
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aDayTypes[newVal.DayType].Text,
							Jade.Strings.ToTime(newVal.From),
							Jade.Strings.ToTime(newVal.To),
							aEvents[newVal.Event].Text,
							newVal.EntryExit==0?Jade.Lang.Get('entry'):Jade.Lang.Get('exit')
						];
					}
					break;
				case '4':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aAccruals[oldVal.Accrual].Text,
							oldVal.Ocurrence,
							Jade.Strings.ToTime(oldVal.TimeAllowed),
							aTerms[oldVal.Term]
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aAccruals[newVal.Accrual].Text,
							newVal.Ocurrence,
							Jade.Strings.ToTime(newVal.TimeAllowed),
							aTerms[newVal.Term]
						];
					}
					break;
				case '5':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aDayTypes[oldVal.DayType].Text,
							aBreaks[oldVal.BreakTime].Text
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aDayTypes[newVal.DayType].Text,
							aBreaks[newVal.BreakTime].Text
						];
					}
					break;
				case '9':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aDayTypes[oldVal.DayType].Text,
							aPayrolls[oldVal.Payroll].Text
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aDayTypes[newVal.DayType].Text,
							aPayrolls[newVal.Payroll].Text
						];
					}
					break;
				case '10':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							$.Strings.ToTime(oldVal.From),
							$.Strings.ToTime(oldVal.To)
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							$.Strings.ToTime(newVal.From),
							$.Strings.ToTime(newVal.To)
						];
					}
					break;
				case '13':
					if(typeof(oldVal)!="undefined"){
						oValues=[
							action_label,
							aDayTypes[oldVal.DayType].Text,
							$.Strings.ToTime(oldVal.From),
							$.Strings.ToTime(oldVal.To)
						];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[
							action_label,
							aDayTypes[newVal.DayType].Text,
							$.Strings.ToTime(newVal.From),
							$.Strings.ToTime(newVal.To)
						];
					}
					break;					
				case '14':
					if(typeof(oldVal)!="undefined"){ 
						oValues=[action_label,
						Jade.Strings.ToDate(xml.Petition.PrimaryKey.Date),
						Jade.Strings.VisualTrim($.Utils.AAText(aDayTypes, oldVal.Daytype),84),
						Jade.Strings.VisualTrim((oldVal.Variant!='' && oldVal.Variant!=0)?Jade.Lang.Get('variant')+' '+oldVal.Variant:Jade.Lang.Get('none_f'),84),
						(oldVal.ForceVariant)?Jade.Lang.Get('yes'):Jade.Lang.Get('no'),
						Jade.Strings.VisualTrim((oldVal.Event!='' && oldVal.Event!=0)?$.Utils.AAText(aEvents, oldVal.Event):Jade.Lang.Get('none_f'),84),
						Jade.Strings.VisualTrim((oldVal.Workday!='' && oldVal.Workday!=0)?$.Utils.AAText(aWorkdays, oldVal.Workday):Jade.Lang.Get('none_m'),84),
						Jade.Strings.VisualTrim(oldVal.Comments,210)]; 
					}
					if(typeof(newVal)!="undefined"){ 
						nValues=[action_label,
						Jade.Strings.ToDate(xml.Petition.PrimaryKey.Date),
						Jade.Strings.VisualTrim($.Utils.AAText(aDayTypes, newVal.Daytype),84),
						Jade.Strings.VisualTrim((newVal.Variant!='' && newVal.Variant!=0)?Jade.Lang.Get('variant')+' '+newVal.Variant:Jade.Lang.Get('none_f'),84),
						(newVal.ForceVariant)?Jade.Lang.Get('yes'):Jade.Lang.Get('no'),
						Jade.Strings.VisualTrim((newVal.Event!='' && newVal.Event!=0)?$.Utils.AAText(aEvents, newVal.Event):Jade.Lang.Get('none_f'),84),
						Jade.Strings.VisualTrim((newVal.Workday!='' && newVal.Workday!=0)?$.Utils.AAText(aWorkdays, newVal.Workday):Jade.Lang.Get('none_m'),84),
						Jade.Strings.VisualTrim(newVal.Comments,210)]; 
					}
					if(typeof(oldVal)!="undefined" && typeof(newVal)!="undefined"){ nValues[0]=''; nValues[1]=''; }
					break;
				case '15':
					if(typeof(oldVal)!="undefined"){ 
						oValues = [action_label, Jade.Lang.Get('month_'+xml.Petition.PrimaryKey.Month), xml.Petition.PrimaryKey.Year, $.DateTime.MinutesToHour(oldVal.value, ":")];
					}
					if(typeof(newVal)!="undefined"){ 
						nValues = [action_label, Jade.Lang.Get('month_'+xml.Petition.PrimaryKey.Month), xml.Petition.PrimaryKey.Year, $.DateTime.MinutesToHour(newVal.value, ":")];
					}
					if(typeof(oldVal)!="undefined" && typeof(newVal)!="undefined"){ nValues[0]=''; nValues[1]=''; nValues[2]=''; }
					break;
				case '16':
					if(typeof(oldVal)!="undefined"){ 
						oValues=[action_label, $.Strings.ToDate(oldVal.Date)];
					}
					if(typeof(newVal)!="undefined"){
						nValues=[action_label, $.Strings.ToDate(newVal.Date)];
					}
					break;
				case '18':
					if($.isDefined(oldVal)){
						oValues=[action_label, $.Strings.ToDate(oldVal.Date), $.Strings.ToTime(oldVal.Time), oldVal.Text];
					}
					if($.isDefined(newVal)){
						nValues=[action_label, $.Strings.ToDate(newVal.Date), $.Strings.ToTime(newVal.Time), newVal.Text];
					}
					break;
				case '20':
					value=$.isDefined(newVal)?newVal:oldVal;
					style=$.isDefined(newVal)?'petition_new':'petition_del';
					
					container.grid.AddStyledItem([action_label, Jade.Lang.Get('code'), xml.Petition.PrimaryKey.EmployeeId], style);
					if($.isDefined(value)){
						container.grid.AddStyledItem([action_label, Jade.Lang.Get('name'), value.Name], style);
						container.grid.AddStyledItem([action_label, COMPANY.department, value.Department], style);
						container.grid.AddStyledItem([action_label, COMPANY.center, value.Center], style);
						container.grid.AddStyledItem([action_label, Jade.Lang.Get('workday'), value.Workday], style);
						container.grid.AddStyledItem([action_label, Jade.Lang.Get('profile'), value.Profile], style);
						container.grid.AddStyledItem([action_label, Jade.Lang.Get('calendar'), value.Calendar], style);
						container.grid.Size(950, container.grid.height+100);
					}
					else{ container.grid.Size(950,container.grid.height+13); }
					break;
			}
			break;
		case '6': 
			if(typeof(oldVal)!="undefined"){ oValues=[action_label,Jade.DateTime.toShowDate(oldVal.Date),Jade.DateTime.toShowDate(oldVal.ValueDate),Jade.DateTime.toShowTime(oldVal.Time),$.Utils.AAText(aEvents, oldVal.EventId)]; }
			if(typeof(newVal)!="undefined"){ nValues=[action_label,Jade.DateTime.toShowDate(newVal.Date),Jade.DateTime.toShowDate(newVal.ValueDate),Jade.DateTime.toShowTime(newVal.Time),$.Utils.AAText(aEvents, newVal.EventId)]; }
			break;
	}
	switch(line.Accion){
		case '0':
			if(nValues.length!=0){
				container.grid.AddStyledItem(nValues,'petition_new');
				container.grid.Size(950,container.grid.height+14);
			}
			break;
		case '1':
			container.grid.AddStyledItem(oValues,'petition_mod');
			if(mValues.length>0){ container.grid.AddStyledItem(mValues,'petition_mod'); }
			else if(nValues.length>0){
				nValues[0]='';
				container.grid.AddStyledItem(nValues,'petition_mod'); 
			}
			container.grid.Size(950,container.grid.height+28);
			break;
		case '2':
			if(nValues.length!=0 || oValues.length!=0){
				container.grid.AddStyledItem(oValues,'petition_del');
				container.grid.Size(950,container.grid.height+14);
			}
			break;
		case '3':
			if(nValues.length!=0 || oValues.length!=0){
				container.grid.AddStyledItem(nValues,'petition_new');
				container.grid.Size(950,container.grid.height+14);
			}
			break;
		case '4':
			if(nValues.length!=0 || oValues.length!=0){
				container.grid.AddStyledItem(oValues,'petition_del');
				container.grid.Size(950,container.grid.height+14);
			}
			break;
	
	}
}
function Header_Template(container,petition,line){
	var grid=Jade.Objects.SimpleGrid();
	grid.Location(0,0,950,27,'relative');
	grid.AddHeader('&nbsp;',200,'head');
	grid.Familia=petition.Familia;
	grid.SubFamilia=line.SubFamilia;
	switch(petition.Familia){
		case '0':case '1':
			switch(line.SubFamilia){
				case '0': case '17': case '19': case '20':
					grid.AddHeader(Jade.Lang.Get('field'),200);
					grid.AddHeader(Jade.Lang.Get('value'),550);
					break;
				case '1':
					grid.AddHeader(Jade.Lang.Get('day_type'),250);
					grid.AddHeader(Jade.Lang.Get('from'),100);
					grid.AddHeader(Jade.Lang.Get('to'),100);
					grid.AddHeader(Jade.Lang.Get('rounding'),100);
					grid.AddHeader(Jade.Lang.Get('entry_exit'),200);
					break;
				case '2':
					grid.AddHeader(Jade.Lang.Get('day_type'),250);
					grid.AddHeader(Jade.Lang.Get('from'),70);
					grid.AddHeader(Jade.Lang.Get('to'),70);
					grid.AddHeader(Jade.Lang.Get('incidence'),250);
					grid.AddHeader(Jade.Lang.Get('entry_exit'),110);
					break;
				case '4':
					grid.AddHeader(Jade.Lang.Get('accrual'),310);
					grid.AddHeader(Jade.Lang.Get('ocurrences_allowed'),145);
					grid.AddHeader(Jade.Lang.Get('time_allowed'),145);
					grid.AddHeader(Jade.Lang.Get('term'),150);
					break;		
				case '5':
					grid.AddHeader(Jade.Lang.Get('day_type'),375);
					grid.AddHeader(Jade.Lang.Get('break_time'),375);
					break;
				case '9':
					grid.AddHeader(Jade.Lang.Get('day_type'),375);
					grid.AddHeader(Jade.Lang.Get('payroll'),375);
					break;
				case '10':
					grid.AddHeader(Jade.Lang.Get('from'),375);
					grid.AddHeader(Jade.Lang.Get('to'),375);
					break;
				case '13':
					grid.AddHeader(Jade.Lang.Get('day_type'),400);
					grid.AddHeader(Jade.Lang.Get('from'),175);
					grid.AddHeader(Jade.Lang.Get('to'),175);
					break;					
					
				case '14':
					grid.AddHeader(Jade.Lang.Get('date'),90);
					grid.AddHeader(Jade.Lang.Get('day_type'),90);
					grid.AddHeader(Jade.Lang.Get('variant'),90);
					grid.AddHeader(Jade.Lang.Get('small_force_variant'),90);
					grid.AddHeader(Jade.Lang.Get('incidence'),90);
					grid.AddHeader(Jade.Lang.Get('workday'),90);
					grid.AddHeader(Jade.Lang.Get('comments'),210);
					break;
				case '15':
					grid.AddHeader(Jade.Lang.Get('month'), 200);
					grid.AddHeader(Jade.Lang.Get('year'), 100);
					grid.AddHeader(Jade.Lang.Get('value'), 450);
					break;
				case '16':
					grid.AddHeader($.lng('value'), 750);
					break;
				case '18':
					grid.AddHeader($.lng('date'), 90);
					grid.AddHeader($.lng('time'), 90);
					grid.AddHeader($.lng('text'), 570);
			}
			break;
		case '6':
			grid.AddHeader(Jade.Lang.Get('date'),100);
			grid.AddHeader(Jade.Lang.Get('date'),100);
			grid.AddHeader(Jade.Lang.Get('time'),100);
			grid.AddHeader(Jade.Lang.Get('incidence'),450);
			break;
	}
	grid.Add(container);
	container.grid=grid;
}
function Comment_Template(date,time,user,text){
	var str='';
	str+='<p style="height: 14px;">'+
	Jade.Strings.Format(Jade.Lang.Get('comment_template'),
	'<span class="mark text-size">'+Jade.Strings.ToDate(date)+'</span>',
	'<span class="mark">'+Jade.Strings.ToTime(time)+'</span>',
	'<span class="mark">'+$.Utils.AAUser(aUsers, user)+'</span>')+':</p>';
	
	str+='<p class="comment text-size">'+text.replace(/\n/,'<br />')+'</p>';
	return str;
}
function Changes_Template(date, time, user, start, end){
	var userName='';
	if(typeof(aUsers[user])!="undefined"){ userName=Jade.Encrypt.Decrypt(aUsers[user].name); }
	else{ userName=Jade.Lang.Get('unknown'); }

	var str='';
	str += '<p style="height: 16px;">'+Jade.Strings.Format( Jade.Lang.Get('changes_template'),
				'<span class="mark">'+Jade.Strings.ToDate(date)+'</span>',
				'<span class="mark">'+Jade.Strings.ToTime(time)+'</span>',
				'<span class="mark">'+userName+'</span>',
				'<span class="cell petition_'+start+'">'+Jade.Lang.Get('petition_status_'+start)+'</span>',
				'<span class="cell petition_'+end+'">'+Jade.Lang.Get('petition_status_'+end)+'</span>'
			)+'</p>';
	
	return str;
}