ajaxData_Accruals.Add(ajaxManager, 'basic');
ajaxData_Payrolls.Add(ajaxManager, 'basic');
ajaxData_Balances.Add(ajaxManager, 'basic');
ajaxData_Formulas.Add(ajaxManager, 'basic');

function Load_Report_List(){
	
	var ajaxList=$.AjaxDB($.Strings.Format("SELECT * FROM LISTADOS_FOR{c} WHERE Tipo='Arithmetic' AND (IdUsuario={0} OR Id IN "+
	"(SELECT IdConfiguracion FROM FORMULAS_VISIBILIDAD{c} WHERE IdUsuario={0}))", USER.id), Ajax.Dontwait);
	grid.ClearRows();
	grid.Loading(true);
	ajaxList.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];
					grid.NewRow([item.Nombre, item.Valor, [$.lng('erease'), 'delete'], item.Orden], item.Id);
				}
			}
		}
		else{$.Debug.Add(this.text);}
		grid.Loading(false);
	}
}

function FormulaWindow(id, is_new){
	{//Controles
		var win=$.Objects.Window(610,465);
	
		var gp_column=$.ControlAdd('container', [10,5,270,350], win);
		$.ControlAdd('label', [10, 10, 200, 20], gp_column, $.Lang.Get('column_type')+':');
		var cmb_column=$.ControlAdd('combo', [5, 25, 260, 20], gp_column);
		var gr_column=$.ControlAdd('grid', [5, 49, 260, 294], gp_column, {sortable: false, editable: false, fixedfocus: true, columns: [{type: 'simple', key: 'formula', text: $.lng('column'), width: '250'},{type: 'hide'}]});
	
		var btn_right=$.ControlAdd('button_icon', [290, 100, 30, 30], win, {text: '', icon: 'size19 arrow_right'});
		var btn_left=$.ControlAdd('button_icon', [290, 140, 30, 30], win, {text: '', icon: 'size19 arrow_left'});
		btn_right.SetEnabled(false);
		btn_left.SetEnabled(false);
		
		var gr_fields=$.ControlAdd('grid', [330, 10, 270, 348], win, {sortable: false, editable: false, fixedfocus: true, columns: [{type: 'simple', key: 'alias', text: $.lng('alias'), width: '50'}, 
																																	{type: 'simple', key: 'formula', text: $.lng('column'), width: '200'},
																																	{type: 'hide'},
																																	{type: 'hide'},
																																	{type: 'hide'}
																																	]});
		$.ControlAdd('label', [10, 375, 200, 20], win, $.lng('formula_name')+':');
		$.ControlAdd('label', [10, 400, 200, 20], win, $.lng('formula')+':');
		var txt_title=$.ControlAdd('textbox', [200, 370, 400, 20], win);
		var txt_formula=$.ControlAdd('textbox', [200, 395, 400, 20], win);

		var btn_accept=$.ControlAdd('button_icon', [10, 430, 290, 22], win, {text: $.lng('accept'), icon: 'size16 accept'});
		var btn_cancel=$.ControlAdd('button_icon', [310, 430, 290, 22], win, {text: $.lng('cancel'), icon: 'size16 cancel'});
	}
	{//Eventos
		btn_accept.onclick=function(){
			var id=win.is_new?$.DateTime.Ticks():win.id;
			if(win.is_new){ $.AjaxDBSave('LISTADOS_FOR{c}', ['Id','Nombre', 'Valor', 'Tipo', 'IdUsuario'], [id, txt_title.GetText(),  txt_formula.GetText(), 'Arithmetic', USER.id]); }
			else{
				$.AjaxDBSave('LISTADOS_FOR{c}', ['Nombre', 'Valor', 'Tipo'], [txt_title.GetText(), txt_formula.GetText(), 'Arithmetic'], "Id='"+id+"'"); 
				$.AjaxDBDelete('LISTADOS_FOR_COL{c}', "IdFormula='"+id+"'");
			}

			for(var i=0,iLen=gr_fields.rows.length; i<iLen; i++){
				var row=gr_fields.rows[i];
				var tipo=row.cells[2].value;
				var valor=row.cells[3].value.toUpperCase();
				if(tipo=='TotalAttendance'){ valor='TATTENDANCETOTAL'; }
				if(tipo=='StandardHours'){ valor='STDHOURS'; }
				ret=$.AjaxDBSave('LISTADOS_FOR_COL{c}', ['IdFormula', 'Nombre', 'Alias', 'Tipo', 'Valor'], [id, row.cells[4].value, row.cells[0].value, tipo, valor]);
			}

			
			win.Hide();
			Load_Report_List();
		}
		btn_cancel.onclick=function(){
			win.Hide();
		}
		gr_column.addcheck=function(value, section, key){
			if(!$.isDefined(key)){ key=section;}
			
			var exist=false;
			for(var i=0, iLen=gr_fields.rows.length;i<iLen;i++){
				if(gr_fields.rows[i].cells[2].value==section && gr_fields.rows[i].cells[3].value==key){ exist=true; }
			}
			if(!exist){
				var name=((section=='Accruals' || section=='Payroll')?key+' - ':'')+value
				gr_column.NewRow([name, value], key); 
			}
		}
		
		gr_column.onrowclick=function(){ btn_right.SetEnabled(true); }
		gr_fields.onrowclick=function(){ btn_left.SetEnabled(true); }
		cmb_column.onchange=function(){
			btn_right.SetEnabled(false);
			gr_column.ClearRows();
			switch(this.selectedKey){
				case 'TotalAttendance':
					gr_column.addcheck($.lng('total_attendance'), 'TotalAttendance', 'TATTENDANCETOTAL');
					break;
				case 'StandardHours':
					gr_column.addcheck($.lng('duty_time'), 'StandardHours', 'STDHOURS');
					break;
				case 'Accruals':
					for(var i in aAccruals){
						var item = aAccruals[i];
						gr_column.addcheck(item.Descripcion, 'Accruals', item.Codigo);
					}
					break;
				case 'Balance':
					for(var i in aBalances){
						var item = aBalances[i];
						gr_column.addcheck(item.Text, 'Balance', item.Codigo);
					}
					break;
				case 'Payroll':
					for(var i in aPayrolls){
						var item = aPayrolls[i];
						gr_column.addcheck(item.Descripcion, 'Payroll', item.Codigo);
					}
					break;
			}
		}
		btn_right.onclick=function(){
			var letter=$.Strings.Chr(97+gr_fields.rows.length);
			for(var i=0, iLen=gr_fields.rows.length;i<iLen;i++){
				var chr=gr_fields.rows[i].cells[0].value;
				if(chr!=$.Strings.Chr(97+i)){ letter=$.Strings.Chr(97+i); break; }
			}
			gr_fields.NewRow([letter, '<div class="icon size16 '+cmb_column.selectedKey+'"></div>'+gr_column.rows[gr_column.selectedIndex].cells[0].value, cmb_column.selectedKey, gr_column.selectedKey, gr_column.rows[gr_column.selectedIndex].cells[1].value], letter)
			gr_column.rows[gr_column.selectedIndex].Delete();
			gr_fields.columnmodel.columns[0].order();
			this.SetEnabled(false);
		}
		btn_left.onclick=function(){
			if(btn_left.enabled){
				var row=gr_fields.rows[gr_fields.selectedIndex];
				row.Delete();
				if(row.cells[2].value==cmb_column.selectedKey){
					cmb_column.onchange();
				}
				btn_left.SetEnabled(false);
			}
		}
	}
	{//Timer comprobacion formula
		txt_formula.onkeydown=function(event){
			if($.isDefined(this.timer)){ clearTimeout(this.timer); }
			this.timer=setTimeout(function(){ check_formula(); }, 1000);
		}
		function check_formula(){
			var formula=txt_formula.GetText();
			for(var i=0, iLen=gr_fields.rows.length;i<iLen;i++){
				var chr=gr_fields.rows[i].cells[0].value;
				formula=formula.replace(new RegExp(chr,'g'), 1);
			}
			try{
				var result=eval(formula);
				txt_formula.SetStyle("green");
			}
			catch(e){ txt_formula.SetStyle("red"); }
		}
	}	
	{//Functions
		win.Load=function(id, is_new){
			win.id=$.isDefined(id)?id:null;
			win.is_new=is_new;
			txt_title.SetText('');
			txt_formula.SetText('');
			gr_fields.ClearRows();
			txt_formula.ClearStyle();
			btn_right.SetEnabled(false);
			btn_left.SetEnabled(false);
			
			if($.isDefined(id)){
				var ajax=$.AjaxDB("SELECT * FROM LISTADOS_FOR_COL{c} WHERE IdFormula='"+id+"' ORDER By Alias", Ajax.Wait);
				if(!ajax.json.error){
					for(var i=0,iLen=ajax.json.row.length;i<iLen;i++){
						var item=ajax.json.row[i];
						var name=((item.Tipo=='Accruals' || item.Tipo=='Payroll')?item.Valor+' - ':'')+item.Nombre;
						
						gr_fields.NewRow([item.Alias, name, item.Tipo, item.Valor, item.Nombre], item.Alias);
					}
				}
				else{ $.Debug.Add(ajax.text); }
			
				
				var ajax=$.AjaxDB("SELECT * FROM LISTADOS_FOR{c} WHERE Id='"+id+"'", Ajax.Wait);
				if(!ajax.json.error){
					if(ajax.json.row.length!=0){
						var item=ajax.json.row[0];
						if(item.IdUsuario!=USER.id){ btn_accept.SetEnabled(false); }
						txt_title.SetText(item.Nombre);
						txt_formula.SetText(item.Valor);
						check_formula();
					}
				}
				else{ $.Debug.Add(ajax.text); }
			}
			cmb_column.onchange();
			win.Show();
		}
	}
	ajaxManager.group['basic'].Start();
	cmb_column.AddItem($.lng('total_attendance'),'TotalAttendance','TotalAttendance');
	cmb_column.AddItem($.lng('duty_time'),'StandardHours','StandardHours');	
	cmb_column.AddItem($.lng('accruals'),'Accruals','Accruals');
	cmb_column.AddItem($.lng('accrual_balance'),'Balance','Balance');
	cmb_column.AddItem($.lng('payroll'),'Payroll','Payroll');
	cmb_column.AddItem($.lng('formula'),'Formula','Formula');
	return win;
}

function CustomColumsWindow(max_length){
	{// Controles
		var win=$.Objects.Window(960, 500);
		$.ControlAdd('label', [10, 10, 300, 20], win, $.lng('fields_selection')+':');
		win.max_length=max_length;
		win.columns=[];
		
		var btn_add=$.ControlAdd('button_icon', [10, 25, 940, 20], win, {text: $.lng('new_field'), icon: 'new'});
		
		var columns = [{type: 'simple', key: 'order', width: '30'},
					{type: 'text', key: 'name', text: $.lng('name'), width: '400'},
					{type: 'combo', key: 'type', text: $.lng('type'), width: '200'},
					{type: 'combo', key: 'value', text: $.lng('value'), width: '230'},
					{type: 'button', key: 'button', width: '19'},
					{type: 'hide', key: 'value', width: '19'}
					];

		var gr_fields=$.ControlAdd('grid', [10, 50, 940, 403], win, {sortable: false, editable: true, columns: columns});
		
		var btn_accept=$.ControlAdd('button_icon', [10, 465, 470, 22], win, {text: $.lng('accept'), icon: 'size16 accept'});
		var btn_cancel=$.ControlAdd('button_icon', [485, 465, 465, 22], win, {text: $.lng('cancel'), icon: 'size16 cancel'});
	}
	{// Eventos
		btn_add.onclick=function(){
			if(win.max_length>gr_fields.rows.length){
				win.AddColumn([$.lng('total_attendance'),'TotalAttendance',0,'TotalAttendance']);
			}
		}
		btn_accept.onclick=function(){
			win.columns=[];
			for(var i=0, iLen=gr_fields.rows.length; i<iLen; i++){
				var cell=gr_fields.rows[i].cells;
				var values=[cell[1].value, cell[2].references.object.selectedKey, cell[3].references.object.selectedKey, cell[5].value];
				if(win.max_length==0){ values.splice(0,0,cell[0].value); }
				win.columns[i]=values;
			}
			win.Hide();
		}
		btn_cancel.onclick=function(){
			win.Hide();
		}
		gr_fields.columnmodel.columns[4].oncellclick=function(cell){
			var row=cell.references.row;
			var cell=row.cells;
			
			if(win.max_length=='fixed'){
				cell[2].references.object.SetSelectedKey('');
				cell[3].references.object.SetSelectedKey('');
			}
			else{ row.Delete(); }
		}
	}
	{// Functions
		win.AddColumn=function(values){
			if(win.max_length!=0){ var row=gr_fields.NewRow([gr_fields.rows.length+1,values[0], values[1], values[2], '<div class="icon grid small delete"></div>', values[3]]); }
			else{ var row=gr_fields.NewRow([values[0],values[1], values[2], values[3], '', values[4]]); }

			row.ChangeStyle('editable');
			
			var combo=row.cells[2].references.object;
			var combo2=row.cells[3].references.object;
			
			combo.AddHideItem('', '');
			combo.AddItem($.lng('total_attendance'),'TotalAttendance','TotalAttendance');
			combo.AddItem($.lng('duty_time'),'StandardHours','StandardHours');
			combo.AddItem($.lng('worked_days'),'WorkedDays','WorkedDays');
			if(aAccruals.legth!=0){ combo.AddItem($.lng('accruals'),'Accruals','Accruals'); }
			if(aBalances.legth!=0){ combo.AddItem($.lng('accrual_balance'),'Balance','Balance'); }
			if(aPayrolls.legth!=0){ combo.AddItem($.lng('payroll'),'Payroll','Payroll'); }
			if(Jade.Utils.Privilege('report_formulas')){ combo.AddItem($.lng('formula'),'Formula','Formula'); }

			combo.onchange=function(){
				combo2.Clear();
				switch(combo.selectedKey.toLowerCase()){
					case 'accruals':
						for(var i in aAccruals){
							var item = aAccruals[i];
							combo2.AddItem(item.Text, item.Codigo, 'Accruals');
						}
						break;
					case 'balance':
						for(var i in aBalances){
							var item = aBalances[i];
							combo2.AddItem(item.Text, item.Codigo, 'Balance');
						}
						break;
					case 'payroll':
						for(var i in aPayrolls){
							var item = aPayrolls[i];
							combo2.AddItem(item.Text, item.Codigo, 'Payroll');
						}
						break;
					case 'formula':
						for(var i in aFormulas){
							var item = aFormulas[i];
							combo2.AddItem(item.Text, item.Codigo, 'Formula');
						}
						break;
					case 'totalattendance':
						combo2.AddHideItem('', 'TATTENDANCETOTAL');
						break;
					case 'standardhours':
						combo2.AddHideItem('', 'STDHOURS');
						break;
					case 'workeddays':
						combo2.AddHideItem('', 'WORKEDDAYS');
						break;
					case '':
						combo2.AddHideItem('');
						break;
				}
			}
			if(win.max_length!=0){
				combo.SetSelectedKey(values[1]);
				combo2.SetSelectedKey(values[2]);
			}
			else{
				combo.SetSelectedKey(values[2]);
				combo2.SetSelectedKey(values[3]);
			}
			
			combo2.onchange=function(){
					switch(combo.selectedKey){
						case 'TotalAttendance': case 'StandardHours': case 'WorkedDays':
							if(win.max_length!=0){ row.cells[1].SetValue(combo.value); }
							row.cells[5].SetValue(combo.selectedKey);
							break;
						case 'Formula':
							if(win.max_length!=0){ row.cells[1].SetValue(combo2.value); }
							row.cells[5].SetValue(aFormulas[combo2.selectedKey].Value);
							break;
						default:
							if(win.max_length!=0){ row.cells[1].SetValue(combo2.value); }
							row.cells[5].SetValue(combo.selectedKey+combo2.selectedKey);
							break;
					}

			}
		}
		win.onshow=function(){
			gr_fields.ClearRows();
			for(var i in win.columns){
				win.AddColumn(win.columns[i]);
			}
		}
		win.Clear=function(){
			gr_fields.ClearRows();
			win.columns=[];
		}
	}
	{// Column lenght 0
		if(win.max_length==0){ 
			btn_add.SetVisible(false); 
			gr_fields.Location(10, 25, 940, 428);
		}
	}
	return win;
}

function ConditionWindow(){
	{// Controles
		var win=$.Objects.Window(610, 500);
		$.ControlAdd('label', [10, 10, 300, 20], win, $.lng('fields_selection')+':');
		win.values={formula: '', condition: 'EveryRecord', columns: []};

		var btn_add=$.ControlAdd('button_icon', [10, 25, 590, 20], win, {text: $.lng('new_field'), icon: 'new'});		
		var columns = [{type: 'simple', key: 'order', text: $.lng('alias'), width: '50'},
					{type: 'combo', key: 'type', text: $.lng('type'), width: '220'},
					{type: 'combo', key: 'value', text: $.lng('value'), width: '270'},
					{type: 'button', key: 'value', width: '19'},
					{type: 'hide', key: 'value', width: '19'}
					];
		var gr_fields=$.ControlAdd('grid', [10, 50, 590, 252], win, {sortable: false, editable: true, columns: columns});
		
		$.ControlAdd('label', [10, 313, 200, 20], win, $.lng('condition')+':');
		var txt_formula=$.ControlAdd('textbox', [10, 330, 590, 20], win);
		
		var group=$.ControlAdd('container', [10, 350, 590, 100], win);
		$.ControlAdd('label', [10, 10, 570, 20], group, $.lng('condition_options')+':');
		var option1=$.ControlAdd('option', [15, 30, 570, 20], group, $.lng("condition_option_1"));
		var option2=$.ControlAdd('option', [15, 50, 570, 20], group, $.lng("condition_option_2"));
		var option3=$.ControlAdd('option', [15, 70, 570, 20], group, $.lng("condition_option_3"));
		
		
		var btn_accept=$.ControlAdd('button_icon', [10, 465, 290, 22], win, {text: $.lng('accept'), icon: 'size16 accept'});
		var btn_cancel=$.ControlAdd('button_icon', [305, 465, 295, 22], win, {text: $.lng('cancel'), icon: 'size16 cancel'});
		
	}
	{// Eventos
		btn_add.onclick=function(){
			win.AddColumn([$.Strings.Chr(97+gr_fields.rows.length), '', 'TotalAttendance',]);
		}
		btn_accept.onclick=function(){
			win.values.columns=[];
			win.values.formula=txt_formula.GetText();
			for(var i=0,iLen=gr_fields.rows.length; i<iLen; i++){
				var cell=gr_fields.rows[i].cells;
				win.values.columns[i]=[cell[0].value, cell[4].value, cell[1].references.object.selectedKey, cell[2].references.object.selectedKey];
			}
			if(option1.GetCheck()){ win.values.condition='EveryRecord'; }
			if(option2.GetCheck()){ win.values.condition='AtLeastOneRecord'; }
			if(option3.GetCheck()){ win.values.condition='Total'; }
			win.Hide();
		}
		btn_cancel.onclick=function(){
			win.Load(win.values);
			win.Hide();
		}
		gr_fields.columnmodel.columns[3].oncellclick=function(cell){
			cell.references.row.Delete();
		}
	}
	{// Functions
		win.AddColumn=function(values){
			var row=gr_fields.NewRow([values[0], values[2], values[3], '<div class="icon grid small delete"></div>']);
			row.ChangeStyle('editable');
			
			var combo=row.cells[1].references.object;
			var combo2=row.cells[2].references.object;
			
			combo.AddHideItem('', '');
			combo.AddItem($.lng('total_attendance'),'TotalAttendance','TotalAttendance');
			combo.AddItem($.lng('duty_time'),'StandardHours','StandardHours');	
			if(aAccruals.legth!=0){ combo.AddItem($.lng('accruals'),'Accruals','Accruals'); }
			if(aBalances.legth!=0){ combo.AddItem($.lng('accrual_balance'),'Balance','Balance'); }
			if(aPayrolls.legth!=0){ combo.AddItem($.lng('payroll'),'Payroll','Payroll'); }
			combo.AddItem($.lng('formula'),'Formula','Formula');			
			combo.onchange=function(){
				combo2.Clear();
				switch(combo.selectedKey){
					case 'Accruals':
						for(var i in aAccruals){
							var item = aAccruals[i];
							combo2.AddItem(item.Text, item.Codigo, 'Accruals');
						}
						break;
					case 'Balance':
						for(var i in aBalances){
							var item = aBalances[i];
							combo2.AddItem(item.Text, item.Codigo, 'Balance');
						}
						break;
					case 'Payroll':
						for(var i in aPayrolls){
							var item = aPayrolls[i];
							combo2.AddItem(item.Text, item.Codigo, 'Payroll');
						}
						break;	
					case 'Formula':
						for(var i in aFormulas){
							var item = aFormulas[i];
							combo2.AddItem(item.Text, item.Codigo, 'Formula');
						}
						break;
					default:
						combo2.AddHideItem('', '');
						//combo2.Clear();
						break;
				}
			}
			combo.SetSelectedKey(values[2]);
			combo2.SetSelectedKey(values[3]);
			
			combo2.onchange=function(){
					switch(combo.selectedKey){
						case 'TotalAttendance': case 'StandardHours':
							row.cells[4].SetValue(combo.value);
							break;
						case 'Formula':
							row.cells[4].SetValue(aFormulas[combo2.selectedKey].Text);
							break;
						default:
							row.cells[4].SetValue(combo2.value);
							break;
					}

			}
		}
		win.Load=function(values){
			if(typeof(values)!="undefined"){
				win.values=values;
				winCondition.SetOption(values.condition);
				txt_formula.SetText(values.formula);
			
				gr_fields.ClearRows();
				for(var i in values.columns){
					win.AddColumn(values.columns[i]);
				}
				check_formula();
			}
		}
		win.SetOption=function(option){
			switch(option){
				case 'EveryRecord':
					option1.SetCheck(true);
					break;
				case 'AtLeastOneRecord':
					option2.SetCheck(true);
					break;
				case 'Total':
					option3.SetCheck(true);
					break;
				default: 
					option1.SetCheck(true);
					break;
			}
		}
		win.Clear=function(){
			win.SetOption('EveryRecord');
			txt_formula.SetText('');
			gr_fields.ClearRows();
			check_formula();
		}
	}
	{// Timer comprobacion formula
		txt_formula.onkeydown=function(event){
			if($.isDefined(this.timer)){ clearTimeout(this.timer); }
			this.timer=setTimeout(function(){ check_formula(); }, 1000);
		}
		function check_formula(){
			var formula=txt_formula.GetText();
			for(var i=0, iLen=gr_fields.rows.length;i<iLen;i++){
				var chr=gr_fields.rows[i].cells[0].value;
				formula=formula.replace(new RegExp(chr,'g'), 1);
			}
			try{
				formula=parse_formula(formula);
				var result=eval(formula);
				txt_formula.SetStyle("green");
			}
			catch(e){ txt_formula.SetStyle("red"); }
		}
		function parse_formula(value){
			value=value.replace(/=/g, '==');
			value=value.replace(/\&/g, '&&');
			value=value.replace(/\|/g, '||');
			value=value.replace(/<==/g, '<=');
			value=value.replace(/>==/g, '>=');
			return value;
		}
	}
	return win;
}