/************************************
 *
 * An add-on to Prototype 1.5 to speed up the $$ function in usual cases.
 *
 * http://www.sylvainzimmer.com/index.php/archives/2006/06/25/speeding-up-prototypes-selector/
 * 
 * Authors: 
 *    - Sylvain ZIMMER <sylvain _at_ jamendo.com>
 *
 * Changelog:
 *   v1 (2006/06/25)
 *     - Initial release
 *
 * License: AS-IS
 *
 * Trivia: Check out www.jamendo.com for some great Creative Commons music ;-)
 *
 ************************************/
 
 
 
// We don't extend the Selector class because we want 
// to be able to use it if the expression is too complicated.
var SelectorLiteAddon=Class.create();


SelectorLiteAddon.prototype = {

  // This is the constructor. It parses the stack of selectors.
  initialize: function(stack) {
    
    this.r=[]; //results
    this.s=[]; //stack of selectors
    this.i=0;  //stack pointer
    
    //Parse the selectors
    for (var i=stack.length-1;i>=0;i--) {
    
      //This is the parsed selector. Format is : [tagname, id, classnames]
      var s=["*","",[]]; 
      
      //The unparsed current selector
      var t=stack[i];
      
      //Parse the selector backwards
      var cursor=t.length-1;
      do {
        
        var d=t.lastIndexOf("#");
        var p=t.lastIndexOf(".");
        cursor=Math.max(d,p);
        
        //Found a tagName
        if (cursor==-1) {
          s[0]=t.toUpperCase();
          
        //Found a className
        } else if (d==-1 || p==cursor) {
          s[2].push(t.substring(p+1));
          
        //Found an ID
        } else if (!s[1]) {
          s[1]=t.substring(d+1);
        }
        t=t.substring(0,cursor);
      } while (cursor>0);
      this.s[i]=s;
    }
  },
  
  //Returns a list of matched elements below a given root.
  get:function(root) {
    this.explore(root || document,this.i==(this.s.length-1));
    return this.r;
  },
  
  //Recursive function where the actual search is being done.
  // elt: current root element
  // leaf: boolean, are we in a leaf of the search tree?
  explore:function(elt,leaf) {
    
    //Parsed selector
    var s=this.s[this.i];
    
    //Results
    var r=[];
    
    //Selector has an ID, use it!
    if (s[1]) {
    
      e=$(s[1]);      
      if (e && (s[0]=="*" || e.tagName==s[0]) && e.childOf(elt)) {
       r=[e];
      }
      
    //Selector has no ID, search by tagname.
    } else {
      r=$A(elt.getElementsByTagName(s[0]));
    }
    
    
    //Filter the results by classnames. 
    //Todo: by attributes too?
    //Sidenote: The performance hit is often here.
    
    //Single className : that's fast!
    if (s[2].length==1) { //single classname
      r=r.findAll(function(o) {
      
        //If the element has only one classname too, the test is simple!
        if (o.className.indexOf(" ")==-1) {
          return o.className==s[2][0];
        } else {
          return o.className.split(/\s+/).include(s[2][0]);
        }
      });
    
    //Multipe classNames, a bit slower.
    } else if (s[2].length>0) {
      r=r.findAll(function(o) {
      
        //If the elemtn has only one classname, we can drop it.
        if (o.className.indexOf(" ")==-1) { 
          return false;
        } else {
        
          //Check that all required classnames are present.
          var q=o.className.split(/\s+/);
          return s[2].all(function(c) {
            return q.include(c);
          });
        }
      });
    }
    
    
    //Append the results if we're in a leaf
    if (leaf) {
      this.r=this.r.concat(r);
      
    //Continue exploring the tree otherwise
    } else {
      ++this.i;
      r.each(function(o) {
        this.explore(o,this.i==(this.s.length-1));
      }.bind(this));
    }
  }
  
}


//Overwrite the $$ function.
var $$old=$$;

var $$=function(a,b) {

  //expression is too complicated, forward the call to prototype's function!
  if (b || a.indexOf("[")>=0) return $$old.apply(this,arguments);
  
  //Otherwise use our addon!
  return new SelectorLiteAddon(a.split(/\s+/)).get();
}




var beh_forms_controls = function(inp) {
  inp.onchange = function() {
    inp.style.borderStyle = 'dotted';
  },
  inp.onfocus = function() {
    if (!inp.form) {
      return;
    }
    if (inp.type != 'checkbox' && inp.type != 'radio') {
      inp.style.borderColor     = '#000';
      inp.style.backgroundColor = '#ffc';
    }
    var labels = inp.form.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
      if (labels[i].htmlFor == inp.id) {
        labels[i].style.textDecoration = 'underline';
        break;
      }
    }
  },
  inp.onblur = function() {
    if (!inp.form) {
      return;
    }
    if (inp.type != 'checkbox' && inp.type != 'radio') {
      inp.style.borderColor     = '#aaf';
      inp.style.backgroundColor = '#fff';
    }
    var labels = inp.form.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
    if (labels[i].htmlFor == inp.id) {
        labels[i].style.textDecoration = 'none';
        break;
      }
    }
  }
}

function validarForm (f) {
  var pasa    = true;
  var labels  = f.getElementsByTagName('label');
  var fallado = null;

  for (i = 0; i < labels.length; i++) {
    if (labels[i].className == 'req') {
      control = document.getElementById(labels[i].htmlFor);
      if (control.value == '' && control.type != 'hidden' && control.disabled == false) {
        labels[i].style.color = 'red';
        pasa = false;
        if (null == fallado) fallado = control;
      } else {
        labels[i].style.color = 'black';
      }
    }
  }

  if (!pasa) {
    mostrar_tab_de(fallado);
    alert('Uno o más campos obligatorios no han sido llenados.');
    fallado.focus();
  }
  return pasa;
}

var beh_forms = {
	'input'    : beh_forms_controls,
	'textarea' : beh_forms_controls,
	'select'   : beh_forms_controls,
  'form' : function(f) {
    f.onsubmit = function() {
      return validarForm(f);
    }
  }
}

Behaviour.register(beh_forms);

Behaviour.addLoadEvent(function(){
  setMaxLength();
  marcar_campos_req();

  var autos = $$('.autofocus');
  var i;

  if (0) {
    autos[0].focus();
  } else {
  	var inputs = document.getElementsByTagName('input');
  	if (inputs.length > 0) {
  		for (i = 0; i < inputs.length; i++) {
  			if (!inputs[i].disabled && inputs[i].type != 'hidden' && inputs[i].className != 'noautofocus') {
  			  var object = inputs[i];
  			  var hidden = false;
  			  while (object) {
  			    if (object.style.display == 'none' || object.style.visibility == 'hidden') {
  			      hidden = true;
  			      break;
  			    }
  			    object = object.parentElement;
  			  }
  			  if (!hidden) {
  			    inputs[i].focus();
  			    break;
  			  }
  			}
  		}
  	}
  }

  var errores = $$('.form_error');
  var nodo;
  var page = null;
  for (i = 0; i < errores.length; i++) {
    if (   (errores[i].innerText   && errores[i].innerText.replace(/^\s+|\s+$/, '') != '')
        || (errores[i].textContent && errores[i].textContent.replace(/^\s+|\s+$/, '') != '')
       )
    {
      nodo = $(errores[i].id.substring(10));
      mostrar_tab_de(nodo);
      break;
    }
  }


});

function mostrar_tab_de(nodo)
{
  var page = null;

  while (nodo) {
    if (nodo.className && nodo.className.indexOf('tab-page') != -1) {
      page = nodo;
    }
    if (nodo.className && nodo.className.indexOf('dynamic-tab-pane-control') != -1) {
      if (null != page) {
        var tp = eval(nodo.getAttribute('var'));
        for (var i = 0; i < tp.pages.length; i++) {
          if (tp.pages[i].element.id == page.id) {
            tp.setSelectedIndex(i);
            page = null;
            break;
          }
        }
      }
    }
    nodo = nodo.parentNode;
  }
}

function marcar_campos_req()
{
  asterisco = document.createElement('span');
  asterisco.appendChild(document.createTextNode(' *'))
  asterisco.style.color = 'red';
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    if (labels[i].className == 'req') {
      labels[i].appendChild(asterisco.cloneNode(true));
    }
  }
}

function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength') && null == x[i].relatedElement) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	if (maxLength == null) maxLength = this.maxlength;
	var currentLength = this.value.length;
	if (currentLength > maxLength) {
		this.relatedElement.className = 'toomuch';
		this.className = 'toomuch';
  } else {
		this.relatedElement.className = '';
		this.className = '';
	}
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}

function escape_params(content) {
  var result = "";
  var length = content.length;

  for (var i = 0; i < length; i++) {
    var ch = content.charAt(i);
    switch (ch) {
      case '+':
        result += "&#43;";
        break;
      default:
        result += ch;
    }
  }
  return escape(result);
}
