/**
 * Sexy Forms - for mootools 1.2.2
 * @name sexyforms.v1.1.mootools.js
 * @author Eduardo D. Sada - http://www.coders.me/web-html-js-css/javascript/sexy-forms
 * @version 1.1
 * @date 20-Jun-2009
 * @copyright (c) 2009 Eduardo D. Sada (www.coders.me)
 * @license MIT - http://es.wikipedia.org/wiki/Licencia_MIT
 * @example http://www.coders.me/ejemplos/sexy-forms/
*/

Element.implement({
	css: function(params){ return this.setStyles(params);} // costumbre jQuery
});

SexyElement = new Class({

  initialize: function(el) {
    this.element = el;
  },

  addevents: function() {
    this.element.addEvents({
      'focus': function() {
        this.padre.addClass("sexy-"+this.Type+"-focus");
      }.bind(this),
      'blur': function() {
        this.padre.removeClass("sexy-"+this.Type+"-focus");
      }.bind(this)
    });
  },
  
  addhover: function() {
    this.element.addEvents({
      'mouseenter': function() {
        this.padre.addClass("sexy-"+this.Type+"-focus");
      }.bind(this),
      'mouseleave': function(event) {
        this.padre.removeClass("sexy-"+this.Type+"-focus");
      }.bind(this),
      'mousedown': function() {
        this.padre.addClass("sexy-"+this.Type+"-press");
      }.bind(this),
      'mouseup': function(event) {
        this.padre.removeClass("sexy-"+this.Type+"-press");
      }.bind(this)
    });
  },
  
  resetStyle: function(el) {
    el.css({
      'margin'      : 0,
      'padding'     : 0,
      'float'       : 'none',
      'border'      : '0',
      'font-family' : 'inherit',
      'background'  : 'none'
    });
  },
  
  reset: function() {
    if(this.padre) {
      this.element.inject(this.padre, 'before');
      this.padre.dispose();
      this.element.erase('style');
      this.element.removeClass('ocultarlodelmostro');
      this.element.removeClass('sexy-button-input');
      this.element.removeEvents();
      this.element.SexyElement = false;
    }
  }

});



SexyElementText = new Class({

  Extends: SexyElement,
  
  initialize: function(el) {
    this.parent(el);
    this.Type = 'input';
    this.beautifier();
  },
  
  create: function() {
    this.padre = new Element("div", { 'class' : 'sexy-input' });
    this.hijoL = new Element("div", { 'class' : 'sexy-input-left' });
    this.hijoC = new Element("div", { 'class' : 'sexy-input-center' });
    this.hijoR = new Element("div", { 'class' : 'sexy-input-right' });
    this.icon  = new Element("div");

    if (this.element.get('icon')) {
      this.hasIcon = true;
    }

    this.padre.adopt(this.hijoL, this.hijoC, this.hijoR);
    this.padre.inject(this.element, 'before');
    this.hijoC.adopt(this.icon.grab(this.element));
  },
  
  beautifier: function() {
    if (!this.padre && this.element.getStyle('display')!='none') {
      this.create();
      var floating = this.element.getComputedStyle('float');
      var width    = this.element.getComputedStyle('width').toInt() + 14;

      this.resetStyle(this.element);

      if (this.hasIcon) {
        this.icon.css({
          'background'    : 'url('+this.element.get('icon')+') no-repeat left center',
          'padding-left'  : 18 
        });
      }

      this.padre.css({
        'width' : width - 8,
        'float' : floating
      });
      this.element.css({
        'width' : width - 22 - (this.hasIcon?18:0)
      });
      
      if (this.element.get('disabled')) {
        this.padre.addClass("sexy-input-disabled");
      }
      
      this.addevents();

      if(Browser.Engine.trident) { //Fix IE Bug
        this.element.css({"font-family": this.element.getStyle("font-family")});
      }
    }
  }

});

SexyElementTextarea = new Class({

  Extends: SexyElement,
  
  initialize: function(el) {
    this.parent(el);
    this.Type = 'area';
    this.beautifier();
  },
  
  create: function() {
    this.padre = new Element("div", { 'class' : 'sexy-input' });
    this.hijoT = new Element("div", { 'class' : 'sexy-area-top' }).grab(new Element("div", { 'class' : 'sexy-area-top2' }));
    this.hijoC = new Element("div", { 'class' : 'sexy-area-center' });
    this.hijoC2= new Element("div", { 'class' : 'sexy-area-center2' });
    this.hijoB = new Element("div", { 'class' : 'sexy-area-bottom' }).grab(new Element("div", { 'class' : 'sexy-area-bottom2' }));

    this.padre.adopt(this.hijoT.adopt(this.hijoC.adopt(this.hijoB),this.hijoC2));

    this.padre.inject(this.element, 'before');
    this.hijoC.grab(this.element, 'top');
  },
  
  beautifier: function() {
    if (!this.padre && this.element.getStyle('display')!='none') {

      var buguero    = Browser.Engine.trident4 ? 3 : 2;
      var floating   = this.element.getComputedStyle('float');
      var fontFamily = this.element.getComputedStyle("font-family");
      var fontWeight = this.element.getComputedStyle("font-weight");
      var fontSize   = this.element.getComputedStyle("font-size");
      var width      = this.element.getComputedStyle('width').toInt() || this.element.offsetWidth.toInt();
      var height     = this.element.getComputedStyle('height').toInt() || this.element.offsetHeight.toInt();

      this.create();

      if (width>478) {
        width = 478; //max width;
      }

      this.resetStyle(this.element);

      this.element.css({
        'width'       : width,
        'height'      : height,
        'font-family' : fontFamily,
        'font-weight' : fontWeight,
        'font-size'   : fontSize
      });


      this.hijoT.css({'width': (width+15)});
      this.hijoC2.css({'height': (height+10+(Browser.Engine.trident ? buguero : 0))});

      if (this.element.get('disabled')) {
        this.padre.addClass("sexy-area-disabled");
      }
      
      this.addevents();
    }
  }

});

SexyElementButton = new Class({

  Extends: SexyElement,
  
  initialize: function(el) {
    this.parent(el);
    this.Type = 'button';
    this.beautifier();
  },
  
  create: function() {
    this.padre = new Element("div", { 'class' : 'sexy-button' });
    this.hijoL = new Element("div", { 'class' : 'sexy-button-left' });
    this.hijoR = new Element("div", { 'class' : 'sexy-button-right' });
    this.icon  = new Element("div");

    if (this.element.get('icon')) {
      this.hasIcon = true;
    }

    this.padre.adopt(this.hijoL.grab(this.hijoR));
    this.padre.inject(this.element, 'before');
    this.hijoR.grab(this.icon.grab(this.element));
  },
  
  beautifier: function() {
    if (!this.padre && this.element.getStyle('display')!='none') {
      var floating = this.element.getComputedStyle('float');
      this.resetStyle(this.element);
      this.create();
      
      this.padre.css({'float':floating});
      
      if (this.hasIcon) {
        this.icon.css({
          'background'    : 'url('+this.element.get('icon')+') no-repeat left center',
          'padding-left'  : 18 
        });
      }

      if (this.element.get('disabled')) {
        this.padre.addClass("sexy-button-disabled");
      }

      this.addevents();
      this.addhover();

      this.element.addClass('sexy-button-input');
    }
  },
  
  addevents: function() {
    this.parent();
    
    this.padre.addEvents({
      'mouseenter': function() {
        if (this.element.get('disabled')) {
          this.padre.addClass("sexy-button-focus-disabled");
        }
      }.bind(this),
      'mouseleave': function() {
        if (this.element.get('disabled')) {
          this.padre.removeClass("sexy-button-focus-disabled");
        }
      }.bind(this)
    });
  }

});

SexyElementRadio = new Class({

  Extends: SexyElement,
  
  initialize: function(el) {
    this.parent(el);
    this.Type = 'input';
    this.beautifier();
  },
  
  create: function() {
    aClass = this.element.get("type") == "radio" ? 'sexy-input-radio' : 'sexy-input-check';
    this.padre  = new Element("div", {'class' : 'sexy-input'});
    this.aRadio = new Element('div', {'class' : aClass});
  },
  
  beautifier: function() {
    if (!this.element.padre && this.element.getStyle('display')!='none') {
      var floating = this.element.getComputedStyle('float');
      this.resetStyle(this.element);
      this.create();
      
      this.padre.css({'float':floating});

      if(this.element.checked) {
        this.aRadio.addClass("sexy-"+this.element.get("type")+"-checked");
      }

      if (this.element.get('disabled')) {
        this.padre.addClass("sexy-input-disabled");
      }

      this.padre.adopt(this.aRadio);
      this.padre.inject(this.element, 'before');
      this.aRadio.adopt(this.element);

      this.addevents();

      this.element.addClass('ocultarlodelmostro');
    }
  },
  
  blurall: function() {
    $$("input[type=radio][name="+this.element.get("name")+"]").each(function(child) {
      if(this.element !== $(child) && child.SexyElement) {
        if (child.SexyElement.padre)
        {
          child.checked=false;
          child.SexyElement.aRadio.removeClass("sexy-radio-checked");
          child.SexyElement.aRadio.removeClass("sexy-checkbox-checked");
          child.SexyElement.padre.removeClass("sexy-input-focus");
        }
      }
    }.bind(this));
  },
  
  addevents: function() {
    this.parent();
  
    this.aRadio.addEvent('click', function(event){
        if (!this.element.get('disabled')) {
          this.element.checked = this.element.checked ? false : true;

          if (this.element.get("type") == "radio") { //RADIO EVENT
            this.blurall();
            this.element.checked = true;
            this.aRadio.addClass("sexy-radio-checked");
          } else { //CHECKBOX EVENT
            if(this.element.checked) {
              this.aRadio.addClass("sexy-checkbox-checked");
            } else {
              this.aRadio.removeClass("sexy-checkbox-checked");
            }
          }
        }
    }.bind(this));


    this.element.addEvent('click', function(event) {
        this.aRadio.fireEvent('click', event);
    }.bind(this));

  }

});


SexyElementSelect = new Class({

  Extends: SexyElement,
  
  initialize: function(el) {
    this.parent(el);
    this.Type = 'select';
    this.beautifier();
  },
  
  create: function() {
    this.padre = new Element("div", { 'class' : 'sexy-select' });

    this.hijoL = new Element("div", { 'class' : 'sexy-select-left' });
    this.hijoC = new Element("div", { 'class' : 'sexy-select-center' });
    this.hijoR = new Element("a",   { 'class' : 'sexy-select-right', 'href':'#' });
    this.selected = new Element("span").set('text',this.element.options[this.element.options.selectedIndex].text);
    this.icon  = new Element("div");

    if (this.element.get('icon')) {
      this.hasIcon = true;
    }
    
    this.hijoC.grab(this.icon.grab(this.selected));

    this.lista   = new Element("div", { 'class' : 'sexy-select-list' });
    this.listaUL = new Element("ul");

    this.footer = new Element("div", { 'class' : 'sexy-select-last-r' }).grab(
      new Element("div", { 'class' : 'sexy-select-last-l' }).grab(
        new Element("div", { 'class' : 'sexy-select-last-c' })
      )
    );

    this.lista.adopt(this.listaUL, this.footer);
    this.padre.inject(this.element, 'before');
    this.padre.adopt(this.hijoL, this.hijoC, this.hijoR);
    this.lista.inject(this.element, 'before');
  },

  beautifier: function() {
    if (!this.padre && this.element.getStyle('display')!='none') {
      var floating = this.element.getComputedStyle('float');

      this.resetStyle(this.element);
      this.create();
      
      this.padre.css({'float':floating});

      if (this.hasIcon) {
        this.icon.css({
          'background'    : 'url("'+this.element.get('icon')+'") no-repeat left center',
          'padding-left'  : 18 
        });
        this.icon.style.zoom = 1;
      }

      var width = this.element.getStyle('width').toInt()+8+10;
      this.hijoC.css({'width': width});
      this.hijoR.css({
        'margin'      : 0,
        'padding'     : 0
      });
      
      this.createlist();

      this.estado = 0;

      if (this.element.get('disabled')) {
        this.padre.addClass("sexy-select-disabled");
      }

      this.addevents();
      this.element.css({'display': 'none'});

    }

  },
  
  createlist: function() {
    for(iiC=0;iiC<this.element.options.length;iiC++) {
      elemTO = new Element("a", {'href':'#', 'rel':iiC, 'tabindex':999}).set('text',this.element.options[iiC].text);

      elemTO.addEvents({
        'click': function(elemTO, iiC) {
          this.selected.set('text', elemTO.get('text'));
          this.element.options.selectedIndex = iiC;
          this.ocultar();
          
          this.lista.getElements('a').removeClass('hover');
          elemTO.addClass('hover').focus();
          this.hijoR.focus();

          this.element.fireEvent('change');

          return false;
        }.bind(this, [elemTO, iiC]),

        'mouseenter': function(elemTO) {
          this.lista.getElements('a').removeClass('hover');
          elemTO.addClass('hover');
        }.bind(this, [elemTO]),

        'mouseleave': function(elemTO) {
          this.lista.getElements('a').removeClass('hover');
        }.bind(this, [elemTO])
      });

      elemTO.addEvent('selectstart' , $lambda(false));
      elemTO.addEvent('select'      , $lambda(false));
      elemTO.addEvent('dblclick '   , $lambda(false));
      elemTO.addEvent('mousedown '  , $lambda(false));

      this.listaUL.grab(new Element("li").grab(elemTO));

      if ($(this.element.options[iiC]).get('icon')) {
        var icon = new Element("img", {'src':this.element.options[iiC].get('icon'), 'align':'top'});
        icon.css({ 'padding-right'  : 2 });
        icon.inject(elemTO, 'top');
      }

    }
    this.lista.altomaximo = Math.min((this.element.options.length.toInt() + 1) * 20, 160);
  },
    
  ocultar: function() {
    this.lista.morph({'height': [this.lista.altomaximo,0]});
    this.estado = 0;
    eval(this.element.get('onchange'));
    this.element.fireEvent('change');
  },

  mostrar: function() {
    var browser = navigator.appVersion;
    
    this.listaUL.empty();
    this.createlist();
    
    if (browser.indexOf('MSIE 8.0') > -1 ) {
      topadora = this.padre.offsetTop.toInt()-0;
    } else {
      if (Browser.Engine.presto) {
        topadora = this.padre.offsetTop.toInt();
      } else {
        topadora = this.padre.offsetTop.toInt()+(this.padre.getStyle('height').toInt())-2;
      }
    }
    var width = (this.padre.getComputedStyle('width').toInt()||this.padre.offsetWidth.toInt())-6;

    this.lista.css({
      'top'     : topadora,
      'left'    : this.padre.offsetLeft.toInt()+1,
      'width'   : width,
      'display' : 'block'
    });

    this.footer.css({'width': width+6});

    this.lista.set('morph', {duration: 100, transition: Fx.Transitions.Quint.easeOut, onComplete: function(){
      this.lista.css({'display': this.estado?'block':'none'});
    }.bind(this)});

    this.lista.morph({'height': [0,this.lista.altomaximo]});
    this.estado = 1;
  },
  
  addevents: function() {
    this.listaUL.addEvent('selectstart', $lambda(false));
    this.listaUL.addEvent('select'     , $lambda(false));
    this.listaUL.addEvent('dblclick '  , $lambda(false));
    this.listaUL.addEvent('mousedown ' , $lambda(false));

    this.hijoC.addEvent('click', function(event) {
      this.hijoR.fireEvent('click', event);
      this.hijoR.focus();
      return false;
    }.bind(this));

    this.hijoR.addEvent('click', function() {
      if (!this.element.get('disabled')) {
        if (this.estado) {
          this.ocultar();
        } else {
          this.mostrar();
        }
      }
      return false;
    }.bind(this));


    this.padre.addEvents({
      'blur': function() {
        this.ocultar();
      }.bind(this),

      'mouseenter': function() {
        this.addClass("sexy-select-focus");
      },

      'mouseleave': function(event) {
        this.removeClass("sexy-select-focus");
      }
    });

    this.hijoR.addEvent('keydown', function(event) {
        if (!this.element.get('disabled')) {

          if (event.alt && event.key=="down") { //Alt + Down
            if (!this.estado) {
              this.mostrar();
            }
            return false;

          } else if (event.alt && event.key=="up") { // Alt + Up
            this.ocultar();
            return false;

          } else if (event.key=="down") { // Down
            if (this.element.options.selectedIndex != this.element.length-1) {
              this.element.options.selectedIndex +=1;
              this.refresh();
            }
            return false;

          } else if (event.key=="up") { // Up
            if (this.element.options.selectedIndex != 0) {
              this.element.options.selectedIndex -=1;
              this.refresh();
            }
            return false;

          } else if (event.key=="\"") { // PageDown
            if (this.element.options.selectedIndex +6 < this.element.length-1) {
              this.element.options.selectedIndex +=6;
            } else {
              this.element.options.selectedIndex = this.element.length-1;
            }
            this.refresh();
            return false;

          } else if (event.key=="!") { // PageUp
            if (this.element.options.selectedIndex -6 > 0) {
              this.element.options.selectedIndex -=6;
            } else {
              this.element.options.selectedIndex = 0;
            }
            this.refresh();
            return false;

          }
          return true;

        }
    }.bind(this));

    document.addEvents({
      'mousedown': function(event) {
        if (this.estado && !this.lista.hasChild(event.target) && !this.padre.hasChild(event.target)) {
          this.ocultar();
        }
      }.bind(this),
      'keyup': function(event) {
          if (this.estado && !this.lista.hasChild(event.target) && !this.padre.hasChild(event.target)) {
            this.ocultar();
          }
      }.bind(this)
    });
  },
  
  refresh: function() {
    this.selected.set('text',this.element.options[this.element.options.selectedIndex].text);
    this.lista.getElements('a').removeClass('hover');
    this.lista.getElement('a[rel='+this.element.options.selectedIndex+']').addClass('hover');

    fila_ul = this.lista.getElement('ul');
    fila_li = this.lista.getElement('a[rel='+this.element.options.selectedIndex+']');
    
    fila_li.addClass('hover');

    scroll = fila_li.getPosition(fila_ul);
    fila_ul.scrollTo(0, scroll.y-60);
  }

});


Element.implement({

  DoSexy: function() {

    if (!this.SexyElement) {
      if (this.get('tag') == 'input') {
        if (this.get("type") == "text" || this.get("type") == "password" || this.get("type")==null) {
          this.SexyElement = new SexyElementText(this);
        } else if (this.get("type") == "submit" || this.get("type") == "reset" || this.get("type") == "button") {
          this.SexyElement = new SexyElementButton(this);
        } else if (this.get("type") == "radio" || this.get("type") == "checkbox") {
          this.SexyElement = new SexyElementRadio(this);
        }
      } else if (this.get('tag') == 'select') {
        this.SexyElement = new SexyElementSelect(this);
      } else if (this.get('tag') == 'textarea') {
        this.SexyElement = new SexyElementTextarea(this);
      }
    }
  },
  
  reset: function() {
    if (this.SexyElement) {
      this.SexyElement.reset();
    }
  }

});

function beautify_each_form() {
  $$("input", "select", "textarea").each(function(el) {
    el.DoSexy();
  });
};

function reset_each_form(){
  $$("input", "select", "textarea").each(function(el) {
    el.reset();  
  });
};