var List = {
	init: function(){
		this.filter.open = false;
		
		this.filter.container = $('filtros');

		this.filter.blocks = this.filter.container.getElements('.filter');
		this.filter.handles = this.filter.container.getElements('h4');
		this.filter.handles.each(function(el,i){el.getFirst().addEvent('click',this.toggleFilter.bind(this,[i]));},this);

		this.filter.toggler = document.getElement('#navList strong').addEvent('click',this.toggleFilters.bind(this));
		this.filter.allToggler = document.getElement('#filtros h2').addEvent('click',this.toggleFilters.bind(this));

		this.filter.buttons = this.filter.container.getElements('input[type=button]').associate(['reset','submit']);
		this.filter.buttons.reset.addEvent('click',this.submit.bind(this,[true]));
		this.filter.buttons.submit.addEvent('click',this.submit.bind(this,[false]));

		this.filter.inputs = $$('#filtros input[type=text]','select').associate(
			['sr','fd','fh','sm','si','ct','tg','pg','rw']
		);
		this.filter.inputs.ac = this.filter.container.getElements('input[name=ac]');

		this.filter.inputs.pg.addEvent('change',this.submit.bind(this,[false]));
		this.filter.inputs.rw.addEvent('change',this.setRows.bind(this));

		//on key "enter" -> send form
		['sr','fd','fh'].each(function(l){this.filter.inputs[l].addEvent('keyup',function(e){var ev=new Event(e);if(ev.key=='enter'){this.submit(false);}}.bind(this));},this);

		//order
		this.orders = [null,null,null,null,[1,0],[3,2],[5,4],[7,6],[9,8],[11,10]];
		$$('th').each(function(el,i){
			if(this.orders[i]){
				el.addClass('sorter').addEvent('click',this.setOrder.bind(this,[i]));
			}
		},this);

		//select rows
		this.trs = $$('thead tr,tbody tr');
		$$('.check').each(function(el,i){el.addEvent('click',this.selectRow.bind(this,[i]));},this);

		//rows options
		$$('tfoot span').each(function(el,i){
			if(i==0){
				el.addEvent('click',this.deleteRows.bind(this));
			}else if(i==3){
				el.addEvent('click',this.createBoletin.bind(this));
			}else{
				el.addEvent('click',this.updateRows.bind(this,[2-i]));
			}
		},this);

		//tr hover
		$$('tbody tr').each(function(el){
			el.addEvents({
				'mouseenter':function(){this.addClass('hover');},
				'mouseleave':function(){this.removeClass('hover');}
			});
		});

		//datePickers
		this.dp = {};
		['fd','fh'].each(function(l){
			this.dp[l] = new datePicker(this.filter.inputs[l],fechas);
			this.filter.inputs[l].set('name',l).addEvents({
				'focus':this.dp[l].show.bind(this.dp[l]),
				'keyup':function(e){
					var ev = new Event(e);
					var l = ev.target.name;
					if(ev.key=='delete'){
						this.dp[l].deselect().update().hide();
				}}.bind(this)
			}).readOnly = true;
			if(this.filter.inputs[l].value!=''){
				var rdate = this.filter.inputs[l].value.split('/').associate(['d','m','y']);
				this.dp[l].setFullDate(rdate.y.toInt(),rdate.m.toInt()-1,rdate.d.toInt());
			}
		},this);

		//check filters
		var filtered = false;
		var ls = [['sr'],['ct'],['tg'],['ac'],['fd','fh']];
		for(var l=0;l<ls.length;l++){
			for(var i=0;i<ls[l].length;i++){
				if(this.filter.params[ls[l][i]]!=this.filter.defaults[ls[l][i]]){
					this.toggleFilter(l);
					filtered = true;
					break;
				}
			}
		}
		if(filtered){this.toggleFilters();}

		//request
		this.request = new Request({url:BASE.web+'proveedor_items.ajax',onSuccess:function(r){if(this['on'+this.request.action]){this['on'+this.request.action](r);}}.bind(this),onFailure:onError});
	},

	requestSubmit: function(action,data){
		Loading.show();
		this.request.action = action;
		this.request.send({data:'action='+action+'&tp='+proveedor_tipo.id+'&'+data});
	},

	/* seleccionar filas */
	selectRow: function(i){
		if(this.trs[i].hasClass('selected')){
			if(i>0){
				$$(this.trs[0],this.trs[i]).removeClass('selected');
			}else{
				this.trs.removeClass('selected');
			}
		}else{
			if(i>0){
				if(this.getSelectedRows(true)+2==this.trs.length){
					$$(this.trs[0],this.trs[i]).addClass('selected');
				}else{
					this.trs[i].addClass('selected');
				}
			}else{
				this.trs.addClass('selected');
			}
		}
	},

	getSelectedRows: function(count){
		return count ? $$('tbody .selected').length : $$('tbody .selected').get('row');
	},

	/* ordenamiento */
	setOrder: function(i){
		this.filter.params.or = this.orders[i][(this.filter.params.or==this.orders[i][0]?1:0)];
		this.submit(false);
	},

	/* resultados por pagina */
	setRows: function(l){
		this.filter.inputs.pg.selectedIndex = 0;
		this.submit(false);
	},

	/* mostrar/ocultar filtros */
	toggleFilter: function(i){
		this.hideDatePickers();
		$$(this.filter.handles[i],this.filter.blocks[i]).toggleClass('active');
	},

	toggleFilters: function(){
		this.hideDatePickers();
		if(this.filter.open){
			this.filter.container.addClass('hidden');
			this.filter.toggler.innerHTML = 'Mostrar filtros <em>&uarr;</em>';
		}else{
			this.filter.container.removeClass('hidden');
			this.filter.toggler.innerHTML = 'Ocultar filtros <em>&darr;</em>';
		}
		this.filter.open = !this.filter.open;
	},

	/* recolectar parametros de filtros */
	gatherParams: function(){
		for(var i in this.filter.inputs){
			var value = '';
			if($type(this.filter.inputs[i])=='array'){
				this.filter.inputs[i].each(function(el){
					if(el.checked){
						value += el.value;
					}
				},this);
				if(value==''){
					value = this.filter.defaults[i];
				}
			}else if(i=='sr'){
				value = parseSearchString(this.filter.inputs[i].value);
			}else if(['fd','fh'].contains(i)){
				value = this.filter.inputs[i].value.trim();
				if(value.test(/^[\d]{1,2}\/[\d]{1,2}\/[\d]{4}$/)){
					value = value.replace(/^([\d])\//,'0$1/').replace(/[^\d]([\d])\//g,'/0$1/').replace(/^([\d]+)\/([\d]+)\/([\d]+)$/g,'$3-$2-$1');
				}else{
					value = '';
				}
			}else{
				value = this.filter.inputs[i].value.trim();
			}
			this.filter.params[i] = value;
		}
	},

	paramsToUrl: function(){
		var url = '';
		this.gatherParams();
		for(var i in this.filter.params){
			if($defined(this.filter.defaults[i]) && this.filter.defaults[i]!=this.filter.params[i]){
				url += '/'+i+':'+this.filter.params[i];
			}
		}
		return url;
	},

	/* enviar peticion de filtro */
	submit: function(reset){
		Loading.show();
		if(reset){
			redirect(this.url+'/tp:'+this.filter.params.tp);
		}else{
			redirect(this.url+this.paramsToUrl());
		}
	},

	/* cambiar estado de filas */
	updateRows: function(i){
		var selected = this.getSelectedRows();
		if(selected.length>0){
			this.updateStatusValue = i;
			this.requestSubmit('Update','key=activo&value='+i+'&rows='+selected.join(','));
		}
	},

	onUpdate: function(response){
		if(response=='true'){
			var klass = 'estado '+(this.updateStatusValue>0?'enabled':'disabled');
			$$('tr.selected').each(function(tr){
				tr.getChildren()[4].className = klass;
			});
			Loading.hide();
		}
	},

	/* armar boletin */
	createBoletin: function(){
		var selected = this.getSelectedRows();
		if(selected.length>0){
			this.requestSubmit('CreateBoletin','lng='+LNG.code+'&rows='+selected.join(','));
		}
	},

	onCreateBoletin: function(response){
		if(response.test(/^[\d]+$/)){
			redirect('boletines/editar/'+response);
		}else if(response=='false'){
			Loading.hide();
		}
	},

	/* eliminar filas */
	deleteRows: function(){
		var selected = this.getSelectedRows();
		if(selected.length>0 && confirm('Está seguro que desea eliminar los registros seleccionados?')){
			this.requestSubmit('Delete','rows='+selected.join(','));
		}
	},

	onDelete: function(response){
		if(response=='true'){
			reload();
		}
	},

	/* ocultar datePickers */
	hideDatePickers: function(){
		$each(this.dp,function(dp){
			dp.hide();
		},this);
	}
};

window.addEvent('domready',List.init.bind(List));