function changeCSSRule(selectorText,element,v) {
	forEach(getElementsByTagAndClassName(null,selectorText),function(e){
		e.style[element]=v
	})
}

var aletters={' ':null,'\n':null,'\t':null}
var inAccesibilityMode=false;
var lastAccesibilityBackgroundColor='';
var lastAccesibilityColor='';
var lastAccesibilityElement=null;

/**
 * @short Switchs on or off accesibility
 */
switchAccesibility = function(){
	inAccesibilityMode=!inAccesibilityMode;
	log('accesibility ',inAccesibilityMode)
	if (inAccesibilityMode){
		updateLetterAccessKeys()
		changeCSSRule('accesibility_marker','display','inline')
		if ($('accesibility_tip'))
			$('accesibility_tip').style.display='inline'
	}
	else{
		changeCSSRule('accesibility_marker','display','none')
		if ($('accesibility_tip'))
			$('accesibility_tip').style.display='none'
	}
}

var highlightedElements=[]
/**
 * @short Highlights the given elements. Keep last time highlighted, and 
 *        releases them first
 */
highlightElements = function(hl){
	//log('recoer highl',map(function(x){ return x[1] },highlightedElements))
	forEach(highlightedElements,function(e){
		//log('recover .'+e[0]+'. .'+e[1]+'.')
		e[0].style.backgroundColor=e[1]
		e[0].style.color=e[2]
	})

	highlightedElements=[]
	her=[]
	forEach(hl,function(e){
		if (!(e.style.backgroundColor)) {
			ee=[e,e.style.backgroundColor,e.style.color]
			highlightedElements.push(ee)
			//log('set .'+ee[0]+'. .'+ee[1]+'.',typeof e)
			her.push(String(e))
			e.style.backgroundColor='#0F0'
			e.style.color='black'
		}
	})
}

var currentSearch=''
/**
 * @short Activate the given access key (may be lower or upper case)
 */
activateAccessKey=function(k){
	startswith = function (st, s){
		if (!s)
			return;
		for(n=0;n<s.length;n++)
			if (s.charAt(n)!=st.charAt(n))
				return false;
		return true;
	}

	if (k==String.fromCharCode(27)){
		currentSearch=''
		//log('highlight clean')
		highlightElements([])
		return;
	}
	//k=k.toUpperCase()
	currentSearch=currentSearch+k.toUpperCase()

	//log(currentSearch)
	highlight=[]

	m=accessItems.length-1
	while(m>=0 && (!startswith(accessItems[m][0],currentSearch)))
		m-=1
	if (m>=0){
		//log('key',k,'at',m, accessItems[m][0],currentSearch)
	
		acels=[]
		while (m>=0 && startswith(accessItems[m][0],currentSearch)){
			highlight.push(accessItems[m][2])
			acels.push(accessItems[m])
			m-=1
		}
		//log('key',k,'up to',m)
	}
	highlightElements(highlight)

	//log('found ',highlight.length)
	if (highlight.length==0){
		//log(currentSearch,'none found, resetting')
		currentSearch=''
	}
	else if (highlight.length==1){
		highlight[0].style.backgroundColor='yellow'
		highlight[0].focus()
	}
	else{
		doRenumber=function(ren){
			//log('renumber',ren.length,map(function(a){ return a[0] },ren))
			ndig=Math.ceil(Math.log(ren.length+1)/Math.log(10))

			fill0=function(n){
				ndig2=Math.max(Math.ceil(Math.log(n+1)/Math.log(10)),1)
				ret=''
				for (i=0;i<ndig-ndig2;i++)
					ret+='0'
				ret+=n
				return ret
			}

			n=0
			forEach(ren,function(aa){
				nn=fill0(n)
				aa[0]=aa[0]+nn
				appendChildNodes(aa[1],nn)
				n+=1
			})
		}

		last=[null]
		renumberset=[]
		forEach(acels,function(a){
			if (startswith(a[0],last[0])) {
				if (!(last in renumberset))
					renumberset.push(last)
				//renumberset.push(a)
			}
			else{
				n=0
				if (renumberset.length)
					doRenumber(renumberset)
				renumberset=[]
			}
			last=a
		})
		if (renumberset.length)
			doRenumber(renumberset)
	}
}

var accessItems=new Array();

/**
 * @short Adds this ACtive ELement, described at el access hint that is actually
 *        that txt, to the lists.
 *
 * Binary add so I have them ordered
 */
addAccess = function(txt, el, acel){
	txt=txt.toUpperCase().replace(/[^A-Z0-9]/g,'')
	n=0;
	m=accessItems.length;
	txt=String(txt)
	l=0
	while(m>n+1){
		l=Math.floor((m+n)/2)
		if (accessItems[l][0]>txt)
			n=l
		else
			m=l
	}
	accessItems.splice(m,0,[txt,el,acel])
}

/**
 * @short Updates the access keys for all links/inputs...
 */
updateLetterAccessKeys = function(){
	nolettersDigits=/[^A-Z0-9]/g
	accessItems=[]

	addLetter = function(a,_txt,acel){
		txt=_txt.toUpperCase().replace(nolettersDigits,'')//.replace("\n","").replace("\t","").replace(" ")
		//log(txt)

		akey='?'
		forced=false
		if (acel.getAttribute('accesskey')){
			akey=acel.getAttribute('accesskey')
			forced=true
		}
		else{
			akey=txt.charAt(0)
		}
		txtn=SPAN({'class':'accesibility_marker'},akey)
		appendChildNodes(a,txtn)

		if (forced)
			txtn.style.backgroundColor='#CCff00'

		//log('add access key',akey)
		addAccess(txt,txtn,acel)
		addAccess(String(akey),txtn,acel)
		return akey
	}


	forEach(getElementsByTagAndClassName(null,'accesibility_marker'),removeElement)

	forEach(getElementsByTagAndClassName('a',null), function(a){
		//txt=a.text
		addLetter(a.parentNode,a.text || a.innerText ||a.name || a.href || a.id,a)
		//document.write(a.innerText)
	})

	forEach(getElementsByTagAndClassName('input',null), function(a){
		txt=a.name || a.value || "Z"
		addLetter(a.parentNode,txt,a)
	})
	forEach(getElementsByTagAndClassName('textarea',null), function(a){
		txt=a.name
		addLetter(a.parentNode,txt,a)
	})
	forEach(getElementsByTagAndClassName('select',null), function(a){
		//log(a,a.name)
		txt=a.name
		addLetter(a.parentNode,txt,a)
	})
}

/**
 * @short What to do when a key is pressed
 */
onKeyPress = function(e){
	keycode=e.key().code
	st=e.key().string

	//log(keycode,st)

	if (e.target().type)
		tpe=e.target().type.toUpperCase()
	else
		tpe=""
	tag=e.target().tagName.toUpperCase()

	if (tpe=='TEXT' || tpe=='PASSWORD' || tag=='TEXTAREA'){
		if (keycode==27){
			getElementsByTagAndClassName('a',null)[0].focus()
		}
		if (tag=="INPUT"){
			return;
		}
		if (tag=="TEXTAREA"){
			return;
		}
	}

	//log(keycode,st)
	if (keycode==17 || keycode==18 ){
		switchAccesibility()
	}
	else{

		if (keycode>=96 && keycode<=105)
			keycode=keycode-48

		if (String.fromCharCode(keycode).match(/[^A-Za-z0-9]/))
			return;
		activateAccessKey(String.fromCharCode(keycode))
	}
}

/**
 * @short Adds accesibility hooks to allow easy accesibility on all pages.
 */
addAccesibilityHooks=function(){
	//updateLetterAccessKeys()
	//window.document.onkeydown=onKeyPress;

	//document.onkeypress=onKeyPress;
	log('load acces')
	connect(window.document,'onkeyup',onKeyPress)
}

addLoadEvent(addAccesibilityHooks)

