/*@cc_on@*/
//var currentMatch = new match();
var emailFlag = true, firstNameFlag, surnameFlag, req, currentSel = 1,lastSearch;
aMatch = new Array();
newMatch = new Array();
divList = new Array();
var eventBox="";


//CREATE KEYBOARD EVENTS FOR KEYUP & KEYDOWN
if( document.captureEvents ) {
    //non IE
    if( Event.KEYUP ) {
        //NS 4, NS 6+, Mozilla 0.9+
        document.captureEvents( Event.KEYUP );
        document.captureEvents( Event.KEYDOWN );
    }
}
document.onkeyup = registerUp;
document.onkeydown = registerDown;
document.onclick = registerPageClick;

function registerPageClick(e){
if (eventBox!="")
{
	if(document.getElementById(eventBox + "Div") != null)
	{
	opt2  = document.getElementById(eventBox + "Div")
	opt2.innerHTML=''
	opt2.style.visibility = "hidden"
	opt2.style.height = "0px"
	}
	if(document.getElementById(eventBox + "Frame") != null)
	{
	opt2  = document.getElementById(eventBox + "Frame")
	
	opt2.style.visibility = "hidden"
	opt2.style.height = "0px"
	}
}
}

function registerDown(e) {
	
	
	if( !e ) {
        //if the browser did not pass the event information to the
        //function, we will have to obtain it from the event register
        if( window.event ) {
            //DOM
            e = window.event;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
            return;
        }
    }
	if( typeof( e.which ) == 'number' ) {
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        e = e.which;
    } else if( typeof( e.keyCode ) == 'number'  ) {
        //IE, NS 6+, Mozilla 0.9+
        e = e.keyCode;
    } else if( typeof( e.charCode ) == 'number'  ) {
        //also NS 6+, Mozilla 0.9+
        e = e.charCode;
    } else {
    		alert('fail');
        //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
        return;
    }
  
    if (e == 9) {
    	setTimeout("ProcessTab()",0)
		}
	
}
   
function registerUp(e) {
  var target = window.event ? window.event.srcElement : e ? e.target : null;
  
            eventBox = target.name
			if (eventBox=="origin"|| eventBox =="destination")
				opt_option2(String.fromCharCode(e));
  
	if( !e ) {
        //if the browser did not pass the event information to the
        //function, we will have to obtain it from the event register
        if( window.event ) {
            //DOM
            e = window.event;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
            return;
        }
    }
	if( typeof( e.which ) == 'number' ) {
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        e = e.which;
    } else if( typeof( e.keyCode ) == 'number'  ) {
        //IE, NS 6+, Mozilla 0.9+
        e = e.keyCode;
    } else if( typeof( e.charCode ) == 'number'  ) {
        //also NS 6+, Mozilla 0.9+
        e = e.charCode;
    } else {
    		alert('fail');
        //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
        return;
    }
   
   // alert(String.fromCharCode(e));
  
  
     
    //window.alert('The key pressed has keycode ' + e +
     //  ' and is key ' + String.fromCharCode( e ) );
	
	if(divList.length > 0) {
	
		if (e == 38) {
			currentSel--;
			if (currentSel < 1) {currentSel = 1 }
			selectItem(currentSel);
		}	
		else if (e == 40) {
			currentSel++;
			if (currentSel > divList.length) {currentSel = divList.length}
			selectItem(currentSel);
		}
		else if (e == 13) {
				myMatch = newMatch[currentSel-1].option4;
				setLastEntry(aMatch[myMatch].ToTextBox)
		}
		
		else {
			currentSel = 1;
		}
	}
	else if (e == 9) {
			//setTimeout("ProcessTab()",0)
	}
}

function ProcessTab() {


  
 }


function match(myoption1, myoption4)
{
	this.ToTextBox = myoption1; //email
	this.option4 = myoption4; //position
}

//return the options available for the option2s based on the supplied option1
function opt_option2()
{	

	//If IE display the emailSearchTool
	divList = new Array();
	newMatch = new Array();
	currentMatch = getLastEntry();
	//alert(lastSearch)
	if(currentMatch.length == 1 && lastSearch != currentMatch)  {
		
		getRssFeed(currentMatch);
		//alert(aMatch.length)
		lastSearch = currentMatch;
	}else if (lastSearch== null){
		getRssFeed(currentMatch.substring(0,1));
		//alert(aMatch.length)
		lastSearch = currentMatch;
	
	}
	
	var maxOptions = aMatch.length;
	
	//
	//Reset the emailSearchTool
	opt2  = document.getElementById(eventBox + "Div")
	opt2.innerHTML=''
	opt2.style.visibility = "hidden"
	opt2.style.height = "0px"
	
	opt2  = document.getElementById(eventBox + "Frame")
	
	opt2.style.visibility = "hidden"
	opt2.style.height = "0px"
	
	
	var optionCount = 0
	//search match array for available options
	
	for (var i=0; i<maxOptions; i++) {	
		
		if (currentMatch.length > 0 ) {
		
			//tempEmailFlag = eval(aMatch[i].ToTextBox.substring(0,currentMatch.length).toLowerCase() == currentMatch.substring(0,currentMatch.length));
			//alert(tempEmailFlag)
			
			//if(tempEmailFlag )
			tempString = aMatch[i].ToTextBox
			
			switch (currentMatch.toLowerCase())
			{
			case "s": case "st": case "sta":case "stat": case "str":
			
				//alert(tempString + "!")
				
				tempString = removeString(tempString, "street")
				tempString = removeString(tempString, "street")
				tempString = removeString(tempString,"station")
				break	
			case "r": case "ro": case "roa": case "road":
				tempString = removeString(tempString, "road")
				break
			case "r": case "of": case "off":case "offi":case "office":
				tempString = removeString(tempString, "office")	
				break
			case "z":
				tempString = removeString(tempString, "zone")	
				
				break
			}
			
			if(tempString.toLowerCase().indexOf(currentMatch.toLowerCase())>-1)
			{
			
					myOption = new Array();
					myOption = new match(tempString,aMatch[i].option4);
					newMatch.push(myOption);

					someString = addItem(myOption,optionCount,currentMatch)
//alert()

					tempstring = document.getElementById(eventBox + "Div").innerHTML + someString
					

					eval('document.getElementById(eventBox + "Div").innerHTML=tempstring')
					//alert()
					selectItem(1);
					//document.getElementById(eventBox + "Div").style.visibility = "visible";
					optionCount++;
					if(optionCount>15)
					{
					i=maxOptions+1
					}
			}
		} else {
			//Reset & hide the emailSearchTool
			eval("document.getElementById(eventBox + 'Div').innerHTML=''")
			document.getElementById(eventBox + "Div").style.visibility = "hidden"
			document.getElementById(eventBox + "Div").style.height = "0px"
		} 
		
		//set the height to the number of current options
		
	}
	//alert(optionCount)
		if(optionCount > 0 && optionCount<16)
		{
			opt2  = document.getElementById(eventBox + "Div")
		
			opt2.style.visibility = "visible";
			opt2.style.height = divList.length * 15 + "px"
			//opt2.width = opt2.scrollWidth
			
			
			opt2frame = document.getElementById(eventBox + "Frame")
			
			opt2frame.style.visibility = "visible";			
			opt2frame.style.height = opt2.offsetHeight
			opt2frame.style.width = opt2.offsetWidth
		} 
		
}
function removeString(tempString, inputText)
{
	
	streetPos = tempString.toLowerCase().indexOf(inputText)
	
	if (streetPos>1)
	{	
	//alert(tempString)	
		tempString = tempString.substring(0,streetPos) + tempString.substring(streetPos+inputText.length,tempString.length)
	//alert(tempString)	
	}
	return tempString
}
function selectItem(mySelection) {
	//deselect other items
	for (i=1;i <= divList.length;i++ ) 
	{
		eval("document.getElementById('divItem" + i + "').style.background='#F6F5F3'");
		eval("document.getElementById('divItem" + i + "').style.color='#000000'");
	}
	eval("document.getElementById('divItem" + mySelection + "').style.background='#AA0000'");
	eval("document.getElementById('divItem" + mySelection + "').style.color='#FFFFFF'");
}

function selectItemOver(mySelection) {
	//Set currentSel to what mouse has selected (incase enter or tab is pressed)
	currentSel = mySelection;
}

function addBold(myString, myPos, matchString) {
	startPos = myString.toLowerCase().indexOf(matchString.toLowerCase());
	
	leftString = myString.substring(0,startPos);
	midString = myString.substring(startPos,startPos+myPos);
	rightString = myString.substring(startPos+myPos,myString.length);
	
	myString = leftString +"<b>" + midString + "</b>" + rightString
	return myString;
}


//******* TODO: text with a ' breaks the code because of the string concat **********

function addItem (myMatch,myMatchNo,currentMatch) {
	if(emailFlag) {
		emailText = addBold(myMatch.ToTextBox,currentMatch.length, currentMatch);
	} else {
		emailText=myMatch.ToTextBox
	}
	
	
	if (myMatchNo<15)
	{
	divList.push("divItem" + divList.length);
	
	myItem = "<div id='divItem" + divList.length + "' style='font-size:x-small;padding:2px;cursor:pointer;width:100%;background:#FFFFFF' onMouseover=selectItem(" + divList.length + ");selectItemOver(" + divList.length + ") onClick=setLastEntry('"+ escape(myMatch.ToTextBox) +"')>" + emailText + " </div>"
	//alert(myItem)
	}
	else
	{
	myItem=""
	}
	return myItem;
}

function getLastEntry () {
	//Extract typed text back to "," & remove leading white spaces
	fullText = document.getElementById(eventBox).value.toLowerCase()
	
	cursorPos = fullText.lastIndexOf(',') + 1;
	
	return fullText
}

function setLastEntry (myString) {
	//Replace typed text back to "," with populated data (from emailSearchTool)
	myString = unescape(myString)
	fullText = document.getElementById(eventBox).value
	cursorPos = fullText.lastIndexOf(',') + 1;
	newText = fullText.substring(0,cursorPos) + myString 
	document.getElementById(eventBox).value = myString //newText
	document.getElementById(eventBox).focus();
	
	//Reset & hide the emailSearchTool
	opt2  = document.getElementById(eventBox + "Div")
	
	opt2.innerHTML=''
	opt2.style.visibility = "hidden"
	opt2.style.height = "0px"
	
	opt2Frame  = document.getElementById(eventBox + "Frame")
		
	opt2Frame.style.visibility = "hidden"
	opt2Frame.style.height = "0px"
	
	currentSel = 0;
	setCaretToEnd(document.getElementById(eventBox));
}
function setCaretToEnd (input) {
  setSelectionRange(input, input.value.length, input.value.length);
}

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function getRssFeed(srchString) {

		aMatch = new Array();
		
		if (document.implementation && document.implementation.createDocument)
		{
		
			//Mozilla
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead")
		url = "/apps/vline/tripplanner/GetNamesAsXML.asp?name=" + srchString

			req = new XMLHttpRequest();
			//req.onreadystatechange = processRssFeedMozilla;	
			req.open('GET', url, false)
			req.send(null);
			processRssFeedMozilla()
		}
		else if (window.ActiveXObject)
		{
			//IE
			req = new ActiveXObject("MSXML2.XMLHTTP");
		req.onreadystatechange = processRssFeed;	
    	
    	eval("req.open('GET', '/apps/vline/tripplanner/GetNamesAsXML.asp?name=" + srchString + "', false)");
    	
		
    	req.send();
    }
		else
		{
			return;
		}
		document.getElementById("loadStamp").innerHTML = document.getElementById("loadStamp").innerHTML + " '" + srchString + "' XML Data requested at " + Date() + "<br>"
		
}

function processRssFeedMozilla() {

 // only if req shows "complete"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
    
      var doc  = req.responseXML;

      var thename = doc.childNodes[0].getElementsByTagName('name')
      
      var contactMatch = thename.length
      
      for (i = 0;i < contactMatch;i++) {
    
      		aMatch[i]= new match(thename[i].firstChild.nodeValue, i)
      	
          }
       //opt_option2()
    } else {      
      
    }
    //alert(aMatch.length)
  }
}

function processRssFeed() {
  // only if req shows "complete"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      var doc  = req.responseXML;
  // alert(req.responseText)
      var thename = doc.childNodes[0].getElementsByTagName('name')
   
      var contactMatch = thename.length
      
      for (i = 0;i < contactMatch;i++) {
      		aMatch[i]= new match(thename[i].text, i)
      }
     } else {      
      
    }
  }
}

function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

