//////////////////////////////////////////////////////////////////
//
//    Caret Functions
//
//////////////////////////////////////////////////////////////////
function getCaretEnd(obj){
	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		var Lp=obj.createTextRange();
		try{
			Lp.setEndPoint("EndToEnd",M);
		} catch (e) {
			return 0;
		}
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
function getCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		var Lp=obj.createTextRange();
		try{
			Lp.setEndPoint("EndToStart",M);
		} catch (e) {
			return 0;
		}
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
function setCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}

//////////////////////////////////////////////////////////////////
//
//    Escape function
//
//////////////////////////////////////////////////////////////////
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}; 

function print_r(thearray){
	var str;
	for (var item1 in thearray)
	{
		str += item1 + " = " + thearray[item1]+"\n";
	}
	alert(str);
}


function print_r2(thearray){
	var str;
	for (var item1 in thearray)
	{
		str += "["+item1+"]\n";
		for (var item2 in thearray[item1])
		{
			str += "\t["+item2+"] = "+thearray[item1][item2]+"\n";
		}
	}
	alert(str);
}

var handlepress;
var actb_list_func = null;
var extraparm = null;
var actb_callback = null;
var actb_keep_missing_id = false;
function actb_wlb(obj,evt,idName,formName, list_func, extra, callback){
	actb_list_func = list_func;
	extraparm = extra;
	actb_callback = callback;
	actb(obj,evt,null,idName,formName, "");
}

function actb(obj,evt,ca,idName,formName, nextID){
	
	///////////////////////////
	// ---- Variables ---- 
	///////////////////////////
	var next_field = document.getElementById(nextID); //inorder to tab to next field, must pass in id of next field
	var actb_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
	var actb_lim = 4;    // Number of elements autocomplete can show (-1: no limit)
	var actb_firstText = false; // should the auto complete be limited to the beginning of keyword?
	var actb_mouse = true; // Enable Mouse Support
	var actb_delimiter = new Array();  // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete

	///////////////////////////
	// --- Styles ---
	///////////////////////////
	var actb_bgColor = '#FFFFFF';
	var actb_textColor = '#000000';
	var actb_hColor = '#CCCCCC';
	var actb_fFamily = 'Verdana';
	var actb_fSize = '11px';
	var actb_hStyle = 'text-decoration:underline;font-weight="bold"';

	///////////////////////////
	// ---- Constants ---- 
	///////////////////////////
	var actb_delimwords = new Array();
	var actb_cdelimword = 0;
	var actb_delimchar = new Array();
	var actb_keywords = new Array();
	var actb_display = false;
	var actb_pos = 0;
	var actb_total = 0;
	var actb_curr = null;
	var actb_rangeu = 0;
	var actb_ranged = 0;
	var actb_pre = 0;
	var actb_toid;
	var actb_tomake = false;
	var actb_getpre = "";
	var actb_mouse_on_list = true;
	var actb_kwcount = 0;
	var actb_caretmove = false;

	
	actb_keywords = ca;
	actb_id_name = idName;
	actb_curr = obj;

	var oldkeydownhandler = document.onkeydown;
	var oldblurhandler = obj.onblur;
	var oldkeypresshandler = obj.onkeypress;

	document.onkeydown = actb_checkkey;
	obj.onblur = actb_clear;
	obj.onkeypress = actb_keypress;
	

	function actb_clear(evt){
		if (!evt) evt = event;
		document.onkeydown = oldkeydownhandler;
		actb_curr.onblur = oldblurhandler;
		actb_curr.onkeypress = oldkeypresshandler;
		actb_removedisp();
	}
	
	
	function actb_parse(n){
		if (actb_delimiter.length > 0){
			var text = actb_delimwords[actb_cdelimword].trim().addslashes();
			var textlen = actb_delimwords[actb_cdelimword].trim().length;
		}else{
			var text = actb_curr.value.addslashes();
			var textlen = actb_curr.value.length;
		}
		var tobuild = '';
		var i;

		text = text.trim();
		n = n.trim();

		if (actb_firstText){
			var re = new RegExp("^" + text, "i");
		}else{
			var re = new RegExp(text, "i");
		}

		//n=3/
		//text=3 /

		var matched = n.search(re);
				
		for (i=0;i<matched;i++){
			tobuild += n.substr(i,1);
		}
		
		tobuild += "<font style='"+(actb_hStyle)+"'>"
		for (i=matched;i<textlen+matched;i++){
			tobuild += n.substr(i,1);
		}

		tobuild += "</font>";
		for (i=textlen+matched;i<n.length;i++){
			tobuild += n.substr(i,1);
		}
		return tobuild;
	}
	
	
	function curTop(){
		actb_toreturn = 0;
		obj = actb_curr;
		while(obj){
			actb_toreturn += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return actb_toreturn;
	}

	
	function curLeft(){
		actb_toreturn = 0;
		obj = actb_curr;
		while(obj){
			actb_toreturn += obj.offsetLeft;
			obj = obj.offsetParent;
		}
		return actb_toreturn;
	}

	function actb_generate(){
		
		if (document.getElementById('tat_table')){ actb_display = false;document.body.removeChild(document.getElementById('tat_table')); } 
		if (actb_kwcount == 0){
			actb_display = false;
			return;
		}
		
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.position='absolute';
		a.style.border='2px solid #777777';
		a.style.top = eval(curTop() + actb_curr.offsetHeight) + "px";
		a.style.left = curLeft() + "px";
		a.style.backgroundColor=actb_bgColor;
		a.id = 'tat_table';
		
		document.body.appendChild(a);		
		var i;
		var first = true;
		var j = 1;
		if (actb_mouse){
			a.onmouseout= actb_table_unfocus;
			a.onmouseover=actb_table_focus;
		}
		var counter = 0;
		for (i=0;i<actb_keywords.length;i++){
			
			counter++;
			r = a.insertRow(-1);
			if (first && !actb_tomake){
				r.style.backgroundColor = actb_hColor;
				first = false;
				actb_pos = counter;
			}else if(actb_pre == i){
				r.style.backgroundColor = actb_hColor;
				first = false;
				actb_pos = counter;
			}else{
				r.style.backgroundColor = actb_bgColor;
			}
			r.id = 'tat_tr'+(j);
			c = r.insertCell(-1);
			c.style.color = actb_textColor;
			c.style.fontFamily = actb_fFamily;
			c.style.fontSize = actb_fSize;
			c.style.cursor = 'hand';
			c.innerHTML = actb_parse(actb_keywords[i][0]);
			c.id = 'tat_td'+(j);
			c.setAttribute('pos',j);
			
			if (actb_mouse){
				c.onclick=actb_mouseclick;
				c.onmouseover = actb_table_highlight;
			}
			j++;
			
			if (j - 1 == actb_lim && j < actb_total){
				r = a.insertRow(-1);
				r.style.backgroundColor = actb_bgColor;
				c = r.insertCell(-1);
				c.style.color = actb_textColor;
				c.style.fontFamily = 'arial narrow';
				c.style.fontSize = actb_fSize;
				c.style.cursor   = 'hand';
				c.align='center';
				c.innerHTML = '\\/';
				if (actb_mouse){
					c.onclick = actb_mouse_down;
				}
				break;
			}
		}
		if(typeof(actb_showabove) != "undefined" && actb_showabove == true){
			a.style.top = eval(curTop() - (a.clientHeight+10) ) + "px";
		}
		actb_rangeu = 1;
		actb_ranged = j-1;
		actb_display = true;
		if (actb_pos <= 0) actb_pos = 1;
		hideShowCovered();
	}
	
	
	function actb_remake(){
		document.body.removeChild(document.getElementById('tat_table'));
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.border='1px solid #CCCCCC';
		a.style.position='absolute';
		a.style.top = eval(curTop() + actb_curr.offsetHeight) + "px";
		a.style.left = curLeft() + "px";		
		a.style.backgroundColor=actb_bgColor;
		a.id = 'tat_table';
		if (actb_mouse){
			a.onmouseout= actb_table_unfocus;
			a.onmouseover=actb_table_focus;
		}
		document.body.appendChild(a);
		
		var i;
		var first = true;
		var j = 1;
		if (actb_rangeu > 1){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_fSize;
			c.style.cursor   = 'hand';
			c.align='center';
			c.innerHTML = '/\\';
			if (actb_mouse){
				c.onclick = actb_mouse_up;
			}
		}
		for (i=0;i<actb_keywords.length;i++){
			
			if (j >= actb_rangeu && j <= actb_ranged){
				r = a.insertRow(-1);
				r.style.backgroundColor = actb_bgColor;
				r.id = 'tat_tr'+(j);
				c = r.insertCell(-1);
				c.style.color = actb_textColor;
				c.style.fontFamily = actb_fFamily;
				c.style.fontSize = actb_fSize;
				c.style.cursor   = 'hand';
				c.innerHTML = actb_parse(actb_keywords[i][0]);
				c.id = 'tat_td'+(j);
				c.setAttribute('pos',j);
				if (actb_mouse){
					c.onclick=actb_mouseclick;
					c.onmouseover = actb_table_highlight;
				}
				j++;
			}else{
				j++;
			}
			
			if (j > actb_ranged) break;
		}
		if (j-1 < actb_total){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_fSize;
			c.style.cursor   = 'hand';
			c.align='center';
			c.innerHTML = '\\/';
			if (actb_mouse){
				c.onclick = actb_mouse_down;
			}
		}
		if(typeof(actb_showabove) != "undefined" && actb_showabove == true){
			a.style.top = eval(curTop() - (a.clientHeight+10) ) + "px";
		}
		hideShowCovered();
	}
	
	
	function actb_goup(){
		if (!actb_display) return;
		if (actb_pos == 1) return;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_bgColor;
		actb_pos--;
		if (actb_pos < actb_rangeu) actb_moveup();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_timeOut);
	}
	
	
	function actb_godown(){
		if (!actb_display) return;
		if (actb_pos == actb_total) return;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_bgColor;
		actb_pos++;
		if (actb_pos > actb_ranged) actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_timeOut);
	}
	
	
	function actb_movedown(){
		actb_rangeu++;
		actb_ranged++;
		actb_remake();
	}
	
	
	function actb_moveup(){
		actb_rangeu--;
		actb_ranged--;
		actb_remake();
	}


	/* Mouse */
	function actb_mouse_down(){
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_bgColor;
		actb_pos++;
		actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_hColor;
		actb_curr.focus();
		actb_moue_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_timeOut);
	}


	function actb_mouse_up(evt){
		if (!evt) evt = event;
		if (evt.stopPropagation){
			evt.stopPropagation();
		}else{
			evt.cancelBubble = true;
		}
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_bgColor;
		actb_pos--;
		actb_moveup();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_hColor;
		actb_curr.focus();
		actb_moue_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_timeOut);
	}
	
	
	function actb_mouseclick(evt){
		if (!evt) evt = event;
		if (!actb_display) return;
		actb_mouse_on_list = 0;
		actb_pos = this.getAttribute('pos');
		actb_penter();
		actb_curr.focus();
	}
	

	function actb_table_focus(){
		actb_mouse_on_list = 1;
	}
	
	
	function actb_table_unfocus(){
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_timeOut);
	}


	function actb_table_highlight(){
		actb_mouse_on_list = 1;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_bgColor;
		actb_pos = this.getAttribute('pos');
		while (actb_pos < actb_rangeu) actb_moveup();
		while (actb_pos > actb_ranged) actb_mousedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_timeOut);
	}


	function actb_insertword(a,b){

		if (actb_delimiter.length > 0){
			str = '';
			l=0;
			for (i=0;i<actb_delimwords.length;i++){
				if (actb_cdelimword == i){
					str += a;
					l = str.length;
				}else{
					str += actb_delimwords[i];
				}
				if (i != actb_delimwords.length - 1){
					str += actb_delimchar[i];
				}
			}
			if (!b){
				b = "";
			}
			else{
				actb_curr.value = str;
			}
			document.forms[formName].elements[actb_id_name].value = b;
			setCaret(actb_curr,l);
		}else{
			if (!b){
				b = "";
			}
			if(!actb_keep_missing_id){
				actb_curr.value = a;
			}
			document.forms[formName].elements[actb_id_name].value = b;
		}
		actb_mouse_on_list = 0;
		actb_removedisp();
		if (actb_callback != null){
			actb_callback();
		}
	}


	function actb_penter(){
		if (!actb_display) return;
		actb_display = false;
		var word = '';
		var id = '';
		var c = 0;
		for (var i=0;i<=actb_keywords.length;i++){
			c++;
			if (c == actb_pos){
				word = actb_keywords[i][0];
				id = actb_keywords[i][1];
				break;
			}
		}
		actb_insertword(word,id);
		
	}


	function actb_removedisp(){
		
		if (!actb_mouse_on_list){
			actb_display = false;
			if (document.getElementById('tat_table')){ 
					hideShowCovered("SHOW");
					document.body.removeChild(document.getElementById('tat_table'));
					
			}
			if (actb_toid) clearTimeout(actb_toid);
		}
	}


	function actb_keypress(){
		return !actb_caretmove;
	}


	function actb_checkkey(evt){
		try{
			window.clearTimeout(handlepress);
		} catch(e){}
		if (!evt) evt = event;
		a = evt.keyCode;
		caret_pos_start = getCaretStart(actb_curr);
		actb_caretmove = 0;
		switch (a){
			case 38:
				actb_goup();
				actb_caretmove = 1;
				return false;
				break;
			case 40:
				actb_godown();
				actb_caretmove = 1;
				return false;
				break;
			case 9:
				actb_callback = null;
				actb_penter();
				actb_caretmove = 1;
				actb_curr.blur();
				for (var i=0; i<actb_curr.form.elements.length; i++){
					if (actb_curr.form.elements[i] === actb_curr){
						if (evt.shiftKey){
							for (var x=i-1; x>=0; x--){
								try{
									actb_curr.form.elements[x].focus();
									// it worked!  break out of loop
									break;
								}catch(e){
									//do nothing
								}
							}
						} else {
							for (var x=i+1; x<actb_curr.form.elements.length; x++){
								try{
									actb_curr.form.elements[x].focus();
									// it worked!  break out of loop
									return false;
									break;
								}catch(e){
									//do nothing
								}
							}
						}
					}
				}
				return false;
				break;
			case 13:
				actb_penter();
				actb_caretmove = 1;
				return false;
				break;
			default:
				handlepress = setTimeout(function(){actb_tocomplete(a)},250);
				break;
		}
	}

	function actb_tocomplete(kc){
		if (kc == 38 || kc == 40 || kc == 13 || actb_curr.value.length <= 1) return;
		
		if (actb_list_func != null){
			if (extraparm != null){
				actb_keywords = actb_list_func(actb_curr.value, extraparm);
			} else {
				actb_keywords = actb_list_func(actb_curr.value, "");
			}
		}
		
		if (!actb_keywords){
			return;
		}

		var i;
		if (actb_display){ 
			var word = 0;
			var c = 0;
			for (var i=0;i<=actb_keywords.length;i++){
				c++;
				if (c == actb_pos){
					word = i;
					break;
				}
			}
			actb_pre = word;
		} else { 
			actb_pre = -1
		}
		
		if (actb_curr.value == ''){
			actb_mouse_on_list = 0;
			actb_removedisp();
			return;
		}
		if (actb_delimiter.length > 0){
			caret_pos_start = getCaretStart(actb_curr);
			caret_pos_end = getCaretEnd(actb_curr);
			
			delim_split = '';
			for (i=0;i<actb_delimiter.length;i++){
				delim_split += actb_delimiter[i];
			}
			delim_split = delim_split.addslashes();
			delim_split_rx = new RegExp("(["+delim_split+"])");
			c = 0;
			actb_delimwords = new Array();
			actb_delimwords[0] = '';
			for (i=0,j=actb_curr.value.length;i<actb_curr.value.length;i++,j--){
				if (actb_curr.value.substr(i,j).search(delim_split_rx) == 0){
					ma = actb_curr.value.substr(i,j).match(delim_split_rx);
					actb_delimchar[c] = ma[1];
					c++;
					actb_delimwords[c] = '';
				}else{
					actb_delimwords[c] += actb_curr.value.charAt(i);
				}
			}

			var l = 0;
			actb_cdelimword = -1;
			for (i=0;i<actb_delimwords.length;i++){
				if (caret_pos_end >= l && caret_pos_end <= l + actb_delimwords[i].length){
					actb_cdelimword = i;
				}
				l+=actb_delimwords[i].length + 1;
			}
			var t = actb_delimwords[actb_cdelimword].addslashes().trim();
		}else{
			var t = actb_curr.value.addslashes();
		}
		if (actb_firstText){
			var re = new RegExp("^" + t, "i");
		}else{
			var re = new RegExp(t, "i");
		}
		
		actb_total = 0;
		actb_tomake = false;
		actb_kwcount = 0;

		for (i=0;i<actb_keywords.length;i++){
			actb_total++;
			actb_kwcount++;
			if (actb_pre == i) actb_tomake = true;
		}
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_timeOut);
		actb_generate();
	}


	function getAbsolutePos(el) {
		var r = { x: el.offsetLeft, y: el.offsetTop };
		
		if (el.offsetParent) {
			var tmp = getAbsolutePos(el.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}
		return r;
	}


	function checkOverlap (rx1, rx2, ry1, ry2, lx1, lx2, ly1, ly2) {
		overlap = false;
		//if the first point in the line is between the two x's and the two y's //overlap
		if ((rx1 <= lx1) && (lx1 <= rx2) && (ry1 <= ly1) && (ly1 <= ry2)) {overlap = true;}
		//if the second point in the line is between the two x's and the two y's //overlap
		if ((rx1 <= lx2) && (lx2 <= rx2) && (ry1 <= ly2) && (ly2 <= ry2)) {overlap = true;}
		//if the lines far left point is less than the rectangles far left point AND the lines far right point is more than the rectangles far right point AND the lines left point is between the top and bottom points of the rectangle //overlap
		if ((lx1 <= rx1) && (lx2 >= rx2) && (ry1 >= ly1) && (ly1 >= ry2)) {overlap = true;}
		//if the lines far top point is less than the rectangles far top point AND the lines far bottom point is more than the rectangles far bottom point AND the lines top point is between the left and right points of the rectangle //overlap
		if ((ly1 <= ry1) && (ly2 >= ry2) && (rx1 >= lx1) && (lx1 >= rx2)) {overlap = true;}
		return overlap;
	}


	function hideShowCovered (show) {
		
		var tags = new Array ('applet', 'iframe', 'select');
		var el = document.getElementById('tat_table');
		
		var p = getAbsolutePos(el);
		var EX1 = p.x;
		var EX2 = el.offsetWidth + EX1;
		var EY1 = p.y;
		var EY2 = el.offsetHeight + EY1;

		for (var k = 0; k < tags.length; k++) {
			var ar = document.getElementsByTagName(tags[k]);
			var cc = null;

			for (var i = 0; i < ar.length; i++) {
				
				cc = ar[i];
				if(cc.src == "javascript:false;"){//this is a special case with the overlib popup
					continue;
				}
				p = getAbsolutePos(cc);
				
				var CX1 = p.x;
				var CX2 = cc.offsetWidth + CX1;
				var CY1 = p.y;
				var CY2 = cc.offsetHeight + CY1;

				overlap = false;

				//if line one   intersects with rectangle then overlap
				if(!show){
					if(!overlap){overlap = checkOverlap(EX1, EX2, EY1, EY2, CX1, CX2, CY1, CY1);}
					//if line two   intersects with rectangle then overlap
					if(!overlap){overlap = checkOverlap(EX1, EX2, EY1, EY2, CX2, CX2, CY1, CY2);}
					//if line three intersects with rectangle then overlap
					if(!overlap){overlap = checkOverlap(EX1, EX2, EY1, EY2, CX2, CX1, CY2, CY2);}
					//if line four  intersects with rectangle then overlap
					if(!overlap){overlap = checkOverlap(EX1, EX2, EY1, EY2, CX1, CX1, CY2, CY1);}

					if (overlap)
					{
						cc.style.visibility = "hidden";
					}
					else
					{
						cc.style.visibility = "visible";
					}
				}
				if(show=="SHOW"){
					cc.style.visibility = "visible";
				}
			}
		}
	}
}