var indexActual=-1;
var classOver = "on";
var classOut  = "off";
var result = new Array();

function submitEnterGifting(event, id) {
        
	if (!$("#callback-typeahead").is(":visible")) submitEnter(event, id);
}

function doAddressBookTypeahead(event, id) {

	if (typeof("adbkCaption")=="undefined") return;
	if (adbkCaption.length==0) return;

	var phone = $("#"+id).val();
	phone = phone.replace(/[^0-9a-z]/gi, '');

	var re = new RegExp(phone,'gi');

	var html = "";
	delete result;
	window.result = new Array();
	for(var i=0; i<adbkCaption.length; i++) {	
		if (adbkCaption[i].replace(/\s+/g,'').match(re) || adbkValue[i].replace(/\s+/g,'').match(re)) {
			html = html + "<li id=\""+adbkValue[i]+"\" onmouseover=\"this.className='"+classOver+"'\" onmouseout=\"this.className='"+classOut+"'\" onclick=\"setPhone("+adbkValue[i]+", '"+id+"')\">"+adbkCaption[i]+"</li>";
			window.result.push(adbkValue[i]);
		}
	} 
	if (html=="" || phone=="") {
		indexActual=-1;
		$("#callback-typeahead").hide();
		return;
	}



	html = "<ul>"+html+"</ul>";

        

	$("#callback-typeahead").html(html);
	$("#callback-typeahead").show();
	setPosition(id);
	
	
	// Bind Keys
	useKeyboard(event.keyCode, id);
}




function setPosition(id) {
	var t = $('#'+id).offset().top+21;
	var l = $('#'+id).offset().left;

	$('#callback-typeahead').css({
	    top:t+'px',
	    left:l+'px'
	});
}

function setPhone(phone, id) {
	phone = phone.toString()
	var p1 = phone.substr(0,3);
	var p2 = phone.substr(3,3);
	var p3 = phone.substr(6,4);
	
	$("#"+id).val("("+p1+") "+p2+"-"+p3);
	$("#callback-typeahead").hide();
	indexActual=-1;
}

function useKeyboard(key, id) {
	var up     = 38;
	var down   = 40;
	var enter  = 13;
	var escape = 27;
	var phone  = "";
	
	if (key!=up && key!=down && key!=enter && key!=escape) return;   
	
	if (key==enter) {
		phone = getActualPhoneIndex();
		setPhone(phone, id);
		return;
	}
	
	if (key==escape) {
		$("#callback-typeahead").hide();
		return;
	}
	
	if (key==down) {
		if (indexActual<(result.length-1)) indexActual++;
		setPhoneStyle();
	}
	
	if (key==up) {
		if (indexActual>0) indexActual--;
		setPhoneStyle();
	}
}

function getActualPhoneIndex() {
	if (indexActual<0 && indexActual>=result.length) return "";
	return result[indexActual];
}

function setPhoneStyle() {
	var phone = getActualPhoneIndex();
	$("#"+phone).attr("className", classOver);
}