﻿var lista = new Array();
var lista = new Array();
var lista2  = new Array();
var nivel = 0;
var index = 0;
var index2 = 0;
var total = 0;
var total2 = 0;
var tieneFoco = false;
var caja = null;
var menu_opciones;

window.onload = function (){
	$('top').onclick = arriba;
	$('bottom').onclick = abajo;
	$('left').onclick = izquierda;
	$('right').onclick = derecha;
	$('ok').onclick = ok;

	lista = $$('div#contenido .elemento');
	form = $$('div#contenido form');

	total = lista.length-1;
	if(total>=0){
		seleccionar (lista[index]);
		
	}
	
	$('contenido').scrollTop=0;
	
	Event.observe('back', 'click', volver, false);
	Event.observe('home', 'click', opciones, false);
	Event.observe(document, 'keypress', tecla, true);
	
	try{
		llamando();
	}catch(e){}
	
}

function opciones(){
	menu_opciones = true;
	e = $('home');
	
	txt = '';
	
	txt = txt + '<span id="opcion_1" class="opcion" >ir a...</span>';
	txt = txt + '<span id="opcion_2" class="opcion" >guardar página</span>';
	txt = txt + '<span id="opcion_3" class="opcion" >añadir a favoritos</span>';
	txt = txt + '<span id="opcion_4" class="opcion" >salir</span>';
	
	new Insertion.After(e, "<div id='opciones' class='desplegado desplegado_opciones'>"+ txt +"</div>");
	
	
	lista2 = new Array();
	
	lista2 = $$('#opciones .opcion');
	total2 = lista2.length-1; 
	nivel = 1;	
	seleccionar(lista2[index2]);	
}

function volver(){
	history.back();
	return false;
}

function tecla(e){
	switch(e.keyCode){
		case Event.KEY_UP:{
			arriba();
			Event.stop(e);
			break;
		}
		case Event.KEY_DOWN:{
			abajo();
			Event.stop(e);
			break;
		}		
		case Event.KEY_LEFT:{
			izquierda(e);
			break;
		}		
		case Event.KEY_RIGHT:{
			derecha(e);
			//Event.stop(e);
			break;
		}				
		case Event.KEY_RETURN:{
			Event.stop(e);
			ok();
			break;
		}
		default:{
			//Event.stop(e);
			break;
		}		
	}
}

function ok(){
	var etiqueta = new String;
	if(nivel==0){
		e = lista[index];
		if(tieneFoco == false){
			switch(e.tagName.toString().toLowerCase()){
				case 'a':{
					document.location.href = e;
					break;
				}
				case 'input':{
					//aqui hay que controlar cuando es un submit para enviar el formulario
					if(e.type=='submit'){
						document.forms[0].submit();
						Field.activate(e);
					}
					else{
						if(Element.hasClassName(e,'select')){
							var aux = new String(e.id);
							//posicion para la nueva caja;
							x=Position.cumulativeOffset(e)[0];
							y=Position.cumulativeOffset(e)[1];
							
							aux = aux.replace('texto_','');
							
							var txt = '';
							
							i = 0;
							select[aux].each(
								function(o){	
										id = 'option_'+o.key;
										txt = txt + '<span id="'+ id +'" class="opcion" onclick="index2='+ i +';cambia_combo()">' + o.value + '</span>';
										i++;
								}
							);
							
							caja = new Insertion.After(e, "<div id='caja_"+ aux + "' class='desplegado'>"+ txt +"</div>");
							
							lista2 = new Array();
							lista2 = $$('.desplegado .opcion');
							total2 = lista2.length-1; 
							nivel = 1;	
							seleccionar(lista2[index2]);
							
						}
						else{
							Field.activate(e);
						}
					}
					
					break;
				}
				default:{
					Field.activate(e);
					break;
				}
			}
			tieneFoco = true;
		}else{
			switch(e.tagName){
				case 'a':{
					document.location.href = e;
					break;
				}
				case 'input':{
					$(e).blur();
					
					break;
				}
				case 'select':{
					//Field.focus(e);	
					Element.remove(caja);
					break;
				}	
				default:{
					$(e).blur();
					break;
				}				
			}
			tieneFoco = false;	
		}
	}
	else{
		cambia_combo();
		Element.remove(caja.id);
		nivel=0;
		menu_opciones=false;
	}
}

function cambia_combo(){
	
	id = lista2[index2].id;
	
	valor = id.toString().replace('option_','');
	texto = $(id).innerHTML;
	
	caja=$(id).parentNode;
	aux = caja.id;
	
	input = aux.toString().replace('caja_','texto_');
	$(input).value = texto;
	
	oculto = aux.toString().replace('caja_','oculto_');
	$(oculto).value=valor;
	
}

function arriba(){
	if(nivel>0){
		deSeleccionar(lista2[index2]);
		if(index2>0){
			index2--;
		}
		seleccionar(lista2[index2]);	
		cambia_combo()
	}
	else{
		deSeleccionar(lista[index]);
		if(index>0){
			index--;
		}
		seleccionar(lista[index]);
	}
	return false;
}
function abajo(){
	if(nivel==0){
		deSeleccionar(lista[index]);
		if(index<total){
			index++;
		}
		seleccionar(lista[index]);
		}
	else{
		deSeleccionar(lista2[index2]);
		if(index2<total2){
			index2++;
		}
		seleccionar(lista2[index2]);
		cambia_combo()
	}
	return false;
}

function derecha(e){
	
	if(lista[index].tagName.toString().toLowerCase()!='input'){
		$('contenido').scrollTop = Element.getHeight('contenido')*10;
	}
	else{
		Caret(+1,e);
	}
	return false;
}
function izquierda(e){
	if(lista[index].tagName.toString().toLowerCase()!='input'){
		$('contenido').scrollTop = 0;
	}
	else{
		Caret(-1,e);
	}
	return false;
}

function Caret(incr,e){
	if(e.keyCode != 37 && e.keyCode !=39){
		//solo esta funcion es llamada por hacer click con el raton
		control = lista[index];
		Field.focus(control);
		if(control.tagName == 'input'){
			pos = getCaretPosition(control).end+incr;
			setCaretPosition(control, pos, pos);
		}
	}
}

function seleccionar(e){
	tieneFoco = false;
	if(menu_opciones!=true){
		y = Position.cumulativeOffset(e)[1];
		despl = y-310;
		$('contenido').scrollTop=despl;
	}
	Element.addClassName(e, 'seleccionado');
	
}
function deSeleccionar(e){
	tieneFoco = false;
	Element.removeClassName(e, 'seleccionado');
}

// CaretPosition object
function CaretPosition()
{
 var start = null;
 var end = null;
}

//Next, how to retrieve the caret positions...

function getCaretPosition(oField)
{
 // Initialise the CaretPosition object
 var oCaretPos = new CaretPosition();

 // IE support
 if(document.selection)
 {
  // Focus on the text box
  oField.focus();

  // This returns us an object containing
  // information about the currently selected text
  var oSel = document.selection.createRange();

  // Find out the length of the selected text
  // (you'll see why below)
  var selectionLength = oSel.text.length;

  // Move the selection start to 0 position.
  //
  // This is where it gets interesting, and this is why
  // some have claimed you can't get the caret positions
  // in IE.
  //
  // IE has no 'selectionStart' or 'selectionEnd' property,
  // so we can not get or set this value directly. We can
  // only move the caret positions relative to where they
  // currently are (this should make more sense when you read
  // the next line of code).
  //
  // Note, that even though we have moved the start
  // position on our object in memory, this is not reflected
  // in the browser until we call oSel.select() (which we're
  // not going to do here).
  //
  // Also note, the start position will never be a negative
  // number, no matter how far we try to move it back.
  oSel.moveStart ('character', -oField.value.length);

  // This is where it should start to make sense. We now know
  // our start caret position is the length of the currently
  // selected text minus the original selection length
  // (think about it).
  oCaretPos.start = oSel.text.length - selectionLength;

  // Since the start of the selection is at the start of the
  // text, we know that the length of the selection is also
  // the index of the end caret position.
  oCaretPos.end = oSel.text.length;
 }
 // Firefox support
 else if(oField.selectionStart || oField.selectionStart == '0')
 {
  // This is a whole lot easier in Firefox
  oCaretPos.start = oField.selectionStart;
  oCaretPos.end = oField.selectionEnd;
 }

 // Return results
 return (oCaretPos);
}

//Now that you understand that, we can set the caret position using the same principles...

function setCaretPosition(oField, iCaretStart, iCaretEnd)
{
 // IE Support
 if (document.selection)
 {
  // Focus on the text box
  oField.focus();

  // This returns us an object containing
  // information about the currently selected text
  var oSel = document.selection.createRange();

  // Since we don't know where the caret positions
  // currently are (see comments in getCaretPosition() for
  // further information on this), move them to position 0.
  //
  // Note, the caret positions will never be a negative
  // number, no matter how far we try to move them back.
  oSel.moveStart ('character', -oField.value.length);
  oSel.moveEnd ('character', -oField.value.length);

  // Now we know the caret positions are at index 0, move
  // them forward to the desired position (move end caret
  // position first - actually not sure if moving start
  // caret position first affects the end caret position -
  // it might).
  //
  // Note, we allow for a null end caret position and just
  // default it to the same as the start caret position.
  if(iCaretEnd != null)
   oSel.moveEnd ('character', iCaretEnd);
  else
   oSel.moveEnd ('character', iCaretStart);

  oSel.moveStart ('character', iCaretStart);

  // Everything thus far has just been on our object in
  // memory - this line actually updates the browser
  oSel.select();
 }
 // Firefox support
 else if(oField.selectionStart || oField.selectionStart == '0')
 {
  oField.selectionStart = iCaretStart;

  if(iCaretEnd != null)
   oField.selectionEnd = iCaretEnd;
  else
   oField.selectionEnd = iCaretStart;

  oField.focus();
 }
}

//And that's it, they're the only methods you need! While I'm here though, I'll show you one more trick we use on The Blue Form that many people have asked us about.

//You can see in our form builder we allow users to enter in formula into a text box, much like Microsoft Excel (i.e. =[Cell A]+[Cell B]). For convenience, when a user clicks in the text box, we automatically highlight the entire cell name (in the example above, if somebody clicked on the first 'l', it would automatically select the text from the first '[' to the second ']'.

//Let me show you how we do that...

function selectName(oField)
{
 // Use our previous method to get the current caret positions
 var caretPos = getCaretPosition(oField);

 // Use a handful of string functions to find out where the last
 // and next '[' and ']' characters are. Obviously, this can be
 // any character you like that suits your purpose.
 var text = oField.value;
 var prevText = oField.value.substring(0, caretPos.start);
 var nextText = oField.value.substring(caretPos.end);
 var prevCloseBracket = prevText.lastIndexOf("]");
 var prevOpenBracket = prevText.lastIndexOf("[");
 var nextCloseBracket = nextText.indexOf("]");

 // This basically asks - is our caret currently positioned in
 // the middle of a cell name?
 if(prevOpenBracket > prevCloseBracket && nextCloseBracket != -1)
 {
  // IE Support
  if (document.selection)
  {
   // This returns us an object containing
   // information about the currently selected text
   var oSel = document.selection.createRange();

   // Since we don't know where the start caret position
   // currently is (see comments in getCaretPosition() for
   // further information on this), move it to position 0.
   //
   // Note, the caret position will never be a negative
   // number, no matter how far we try to move it back.
   oSel.moveStart('character', -oField.value.length);

   // Move selection start and end to desired position
   oSel.moveStart('character', prevOpenBracket);
   oSel.moveEnd('character', nextCloseBracket+1);

   // Apply the selection
   oSel.select();
  }
  // Firefox support
  else if(oField.selectionStart || oField.selectionStart == '0')
  {
   oField.selectionStart = prevOpenBracket;
   oField.selectionEnd = caretPos.end + nextCloseBracket+1;
   oField.focus();
  }
 }
}

