var Search = {
	users: [],
	input: function() {
		if(!$('thumbs')) return;
		var s = $('search');
		Search.users = $$($('thumbs').getElementsByTagName('a'));
		Search.users.each(function(e) {
			e.$tmp.user = e.getProperty('title').split('::')[0].toLowerCase();
		});
		s.setStyle('display','block');
		s.addEvent('focus', function() {
			if(window.webkit) this.value ='';
			else this.select();
		});
		s.addEvent('keypress', function() {
			Search.search.delay(200);
		});
		s.onsubmit = function() { return false; };
	},
	search: function() {
		var v = $('search').value.toLowerCase();
		if(v=='buscar usuario...') v='';
		Search.users.each(function(e) {
			if(e.$tmp.user.contains(v)) {
				e.getFirst().setOpacity(1);
			} else {
				e.getFirst().setOpacity(0.2);
			}
		});
	},
	focus: function(el) {
		Search.users.each(function(e) {
			if(el==e) {
				e.getFirst().setOpacity(1);
			} else {
				e.getFirst().setOpacity(0.2);
			}
		});
	}
};

var Users = Tips.extend({
	build: function(el) {
		el.addEvent('click', function(event) {
			event=new Event(event).stop();
			$('overflow').toggleClass('hide').setStyle('height', $('thumbs').offsetHeight +'px').setOpacity(0.1);
			Search.focus(el);
			var ul = new Element('ul', {'class': this.options.className + '-ul'}).inject(this.wrapper);
			var alias = el.getProperty('rel');
			var list =  blogs[alias];
			if(alias) {
				var list = list.map(function(e) {
					return new Element('li').adopt(new Element('a', { href:e[1],title:e[1]}).setHTML(e[0]));
				});
			} else { list=[]; }
			ul.adopt(new Element('li').adopt(new Element('a', { href:el.getProperty('href'),title:'Mi perfil',style:'font-weight:bold'}).setHTML('Mi perfil &#x2192;')),list);
		}.bind(this));
		this.parent(el);
	}
});


var DateSlider = {
  start: '2003-11',
  end: '2020-01',
  from: null,
  to: null,
  objFrom: null,
  objTo: null,
  step: 0,
  maxStep: 0,
  
  meses: ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'],
  
  init: function() {
      // Calculamos nuevas fechas
      var _start = DateSlider.start.split('-');
      var _end = DateSlider.end.split('-');
      _end = new Date(_end[0], _end[1]);
      var hoy = new Date();
      if (_end > hoy) {
        var anyo = hoy.getFullYear();
        var mes = hoy.getMonth()+1;
        _end = new Array(anyo, mes);
        DateSlider.end = anyo+'-'+mes;
      }
      var inputs = $$('#buscador-fechas input');

      // Creamos elementos
      var contenedor = $('buscador-usuarios');
      // Fechas
			var ul = new Element('ul', {'class': 'year', 'style': 'width:2200px'}).injectTop(contenedor);
      var div = new Element('div', {'class': 'clear'}).injectTop(contenedor);
      // Flecha derecha
      div = new Element('div', {'class': 'arrowr'}).injectBefore(contenedor);
      var a = new Element('a', {'href': '#', 'onclick':'DateSlider.right();', 'title' : 'Mover a la derecha'}).inject(div);
      var img = new Element('img', {'alt' : 'Mover a la derecha', 'src' : '/images/system/arrowr.png'}).inject(a);
      // Flecha izquierda
      div = new Element('div', {'class': 'arrowl'}).injectBefore(contenedor);
      a = new Element('a', {'href': '#', 'onclick':'DateSlider.left();', 'title' : 'Mover a la izquierda'}).inject(div);
      img = new Element('img', {'alt' : 'Mover a la izquierda', 'src' : '/images/system/arrowl.png'}).inject(a);
			// Escribo los años
		  DateSlider.maxStep = _end[0] - _start[0];
			for (var i=_start[0]; i<=_end[0]; i++) {
        var li = new Element('li').setText(i).inject(ul);
			  var inicio = i==_start[0]?_start[1]-1:0;
			  var fin = i==_end[0]?_end[1]:12;
  			var ul2 = new Element('ul', {'class': 'month'}).inject(li);
			  for (var j=0; j<12; j++) {
			    if (j>=inicio && j<=fin) {
            var li2 = new Element('li').inject(ul2);
            a = new Element('a', {'href': '#', 'rel': DateSlider.formatoFecha(i, (j+1))}).setText(DateSlider.meses[j].substring(0,3)).inject(li2);
            a.addEvent('click', function() {
                if (DateSlider.to != null || DateSlider.from == null) {
                  DateSlider.to = null;
                  if (DateSlider.objTo != null) DateSlider.objTo.removeClass('mes-seleccionado');
                  DateSlider.objTo = null;
                  if (DateSlider.objFrom != this && DateSlider.objFrom != null) DateSlider.objFrom.removeClass('mes-seleccionado');
                  DateSlider.from = this.rel;
                  DateSlider.objFrom = this;
                } else {
                  if (DateSlider.objFrom != DateSlider.objTo && DateSlider.objTo != null) DateSlider.objTo.removeClass('mes-seleccionado');
                  DateSlider.objTo = this;
                  DateSlider.to = this.rel;
                }
                DateSlider.setInput();

                DateSlider.dibujarRango();                
              }
            );
          } else {
            var li2 = new Element('li').inject(ul2);
            var a = new Element('span').setText(DateSlider.meses[j].substring(0,3)).inject(li2);
          }
          if (j==11) li2.addClass('mes-sin-borde');
        }
      }
      $('desde').addEvent('blur', function() { DateSlider.getFromInput() });
      $('hasta').addEvent('blur', function() { DateSlider.getFromInput() });
      DateSlider.getFromInput();
    },
    
  getFromInput: function() {
    DateSlider.from = $('desde').getProperty('value');
    DateSlider.objFrom = $E('a[rel='+DateSlider.from+']');
    DateSlider.to = $('hasta').getProperty('value');
    DateSlider.objTo = $E('a[rel='+DateSlider.to+']');
    DateSlider.setInput();
    DateSlider.dibujarRango();
  },
  
  formatoFecha: function(anyo, mes) {
    return anyo+'/'+(mes<10? '0'+mes:mes);
  },
  
  setInput: function() {
    var desde = DateSlider.from.split('/');
    desde = new Date(desde[0], desde[1]-1, 1);
    var hasta = DateSlider.to != null? DateSlider.to.split('/'): new Array(3000, 10);
    hasta = new Date(hasta[0], hasta[1]-1, 1);
    if (desde > hasta) {
      var aux = DateSlider.from;
      DateSlider.from = DateSlider.to;
      DateSlider.to = aux;
      
      aux = DateSlider.objFrom;
      DateSlider.objFrom = DateSlider.objTo;
      DateSlider.objTo = aux;
      
    } 
    $('desde').setProperty('value', DateSlider.from); 
    $('hasta').setProperty('value', DateSlider.to);
  },
  
  dibujarRango: function() {
    // Dibujo el rango entre las fechas
    var aes = $$('#buscador-usuarios a');
    var estado = false;
    for (var i=0; i<aes.length; i++) {
      if (aes[i] == DateSlider.objFrom) {
        aes[i].removeClass('mes-rango');
        aes[i].addClass('mes-seleccionado');
        estado = true;
      } 
      if (aes[i] == DateSlider.objTo) {
        aes[i].removeClass('mes-rango');
        aes[i].addClass('mes-seleccionado');
        estado = false;
      } 
      if (aes[i] != DateSlider.objFrom && aes[i] != DateSlider.objTo) {
        if (estado) {
          aes[i].addClass('mes-rango');
          aes[i].removeClass('mes-seleccionado');
        } else {
          aes[i].removeClass('mes-rango');
          aes[i].removeClass('mes-seleccionado');
        }
      }
    }
  },
  
  left: function() {
    if (DateSlider.step > 0) DateSlider.step--;
    $('buscador-usuarios').scrollTo(312*(DateSlider.step));
  },
  
  right: function() {
    if (DateSlider.step < DateSlider.maxStep) DateSlider.step++;
    $('buscador-usuarios').scrollTo(312*(DateSlider.step));
  },
}

window.addEvent('domready', function() {
	Search.input();
  	if ($('thumbs')) {
  		new Users($('thumbs').getElementsByTagName('a'), {
  			initialize:function(){
  				this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 300, wait: false}).set(0);
  			},
  			onShow: function(toolTip) {
  				this.fx.start(0.9);
  			},
  			onHide: function(toolTip) {
  				if($('overflow').hasClass('hide')) this.fx.start(0);
  			}
  		});
		$('overflow').addEvent('click', function(e) {
			this.toggleClass('hide');
			Search.search();
		});
  	}
  if ($('buscador-usuarios')) {
    DateSlider.init();
  }
});
