var objRequest;
var iReturnedRowCount = 0;
var suppressKeys = false;
var MaxNumber = 15;

var isHome = false;
var isDynamicResults = false;
var entity = "";
var KeywordID = "";
var HiddenID = "";
var SelectBoxID = "";

function SendQueryStub(Stub)
{
  	FCWSite.Ajax.AjaxMethods.FindKeyword(Stub, MaxNumber, ProcessSuggestResponseCallback);	
}

//function SendVerityStub(Stub,verityResults)
//{
//	AdvancedSearch.Ajax.AjaxMethods.VeritySearch(Stub, verityResults, ProcessVerityResponseCallback);	
//}

function SetKeyWordID(id)
{
  KeywordID = id;
}

function SetHiddenID(id)
{
  HiddenID = id;
}

function SetHideSelectBox(id)
{
  SelectBoxID = id;
}

function ShowSelectBox()
{
  document.getElementById(SelectBoxID).style.visibility='visible';
}

function HideSelectBox()
{
  document.getElementById(SelectBoxID).style.visibility='hidden';
}

function ProcessSuggestResponseCallback(res)
{
 	if(res == null)
	{
	    ShowResults();
		SetResults("Error reaching the Intuition services... No suggestions.");
	}
	else if(res.value =="")
	{
		SetResults("");	
		HideResults();
	}
	else
	{
		ShowResults();
		SetResults(res.value);
	}
				
}
   
//function CheckExists(term, checkForSynonym, checkForKeyword)
//{
//    AdvancedSearch.Ajax.AjaxMethods.CheckIfExists(term, checkForSynonym, checkForKeyword, ProcessExistsResponseCallback);
//}

function ProcessExistsResponseCallback(res)
{
    exists = res.value;
}

//function ProcessVerityResponseCallback(res)
//{
//	if(res == null)
//	{
//	    ShowVerityResults();
//		SetVerityResults("Error reaching the Verity services... No suggestions.");
//	}
//	else if(res.value =="")
//	{
//		SetVerityResults("");	
//		HideVerityResults();
//	}
//	else
//	{
//		ShowVerityResults();
//		SetVerityResults(res.value);
//	}
//				
//}

function CountReturnedRows()
{
	// we'll simply take the results and use the DOM parser to get back the number of children (rows)
	var ResultsTable = getobject('IntuitionResultsTable');		
	
	if(!ResultsTable)
		//There was an error and the table was not rendered		
		return 1;
	else
		return ResultsTable.firstChild.childNodes.length;
}

function HideResults()
{
	getobject('IntuitionResults').className = 'IntuitionResultsHidden';
}

function ShowResults()
{
	var div = getobject('IntuitionResults');
	//div.style.display = "block";
	div.className = 'IntuitionResults';
	//if(!suppressKeys)	
	//	div.style.bottom = div.offsetHeight + 20;
}

function SetResults(Text)
{
	UserInputSoFar = '';
	getobject('IntuitionResults').innerHTML = Text;

	// iterate all possible rows, to reset the selected row class, and then reset the current index...
	var iLoop;
	try
		{
		if(!suppressKeys)
			for (iLoop=1;iLoop<=iEndScrollRow;iLoop++)
				getobject('IntuitionResultsRow' + iLoop).className = 'NormalRow';
		}
	catch (ex) {} // eat errors
		
	iCurrentScrollRow = 0;

//	if (CountReturnedRows() > 0)
//		ShowResults();
//	else
//		HideResults();
}

//function HideVerityResults()
//{
//	getobject('VerityResults').className = 'IntuitionResultsHidden';
//}

//function ShowVerityResults()
//{
//	var div = getobject('VerityResults');
//	div.className = 'VerityResults';
//	//if(!suppressKeys)	
//	//	div.style.bottom = div.offsetHeight + 20;
//}

//function SetVerityResults(Text)
//{
//	UserInputSoFar = '';
////	HideExplanation();
//	getobject('VerityResults').innerHTML = Text;

//	// iterate all possible rows, to reset the selected row class, and then reset the current index...
//	var iLoop;
//	try
//		{
//		if(!suppressKeys)
//			for (iLoop=1;iLoop<=iEndScrollRow;iLoop++)
//				getobject('IntuitionResultsRow' + iLoop).className = 'NormalRow';
//		}
//	catch (ex) {} // eat errors
//		
//	iCurrentScrollRow = 0;

//	if (CountReturnedRows() > 0)
//		ShowResults();
//	else
//		HideResults();
//}

var UserInputSoFar = '';

function SetInputBoxText(NewText, HiddenText)
{
	var InputBox = getobject(KeywordID);
	var InputHidden = getobject(HiddenID);

	// if there's already something in the UserInputSoFar,
	// then reset to it _before_ our further processing...
	if (UserInputSoFar != '')
	{
		InputBox.value = UserInputSoFar;
	}
				
	// save the user input so far, before the change...
	UserInputSoFar = InputBox.value;
	
	// non-sophisticated way for now...
	getobject(KeywordID).value = NewText;
	getobject(HiddenID).value = HiddenText;

	// select the part they didn't type...
	setSelectionRange(InputBox, UserInputSoFar.length, NewText.length) 
}

function HandleKey(e, CurrentValue)
{
	// 38 = up arrow
	// 40 = down arrow
	// 27  = esc key
	// 13 = enter key
	if (!e) 
		var e = window.event;
	// e gives access to the event in all browsers
	
	if (e.keyCode == 38 && !suppressKeys)
	{
//		HideExplanation();
		if (iCurrentScrollRow > 0)
			{
			iCurrentScrollRow--;
			var iCurrentScrollRowPlusOne = iCurrentScrollRow + 1;
			try
				{
				// iterate all possible rows, to reset the selected row class, and then reset the current index...
				var iLoop;
				try
					{
					for (iLoop=1;iLoop<=iEndScrollRow;iLoop++)
						getobject('IntuitionResultsRow' + iLoop).className = 'NormalRow';
					}
				catch (ex2) {} // eat errors
				getobject('IntuitionResultsRow' + iCurrentScrollRowPlusOne).className = 'NormalRow';
				if (iCurrentScrollRow > 0)
					getobject('IntuitionResultsRow' + iCurrentScrollRow).className = 'SelectedRow';
				// get the text in the currently selected row, to pass back to the input box...
				//SetInputBoxText(getobject('IntuitionResultsTerm' + iCurrentScrollRow).innerHTML);
				}
			catch (ex)
				{} // eat errors for now...
			}	
	}
	else if (e.keyCode == 40 && !suppressKeys)
	{
//		HideExplanation();
        
		if (iCurrentScrollRow < iEndScrollRow)
			{
			iCurrentScrollRow++;
			var iCurrentScrollRowMinusOne = iCurrentScrollRow - 1;
			try
				{				
				var RowAboutToChange = getobject('IntuitionResultsRow' + iCurrentScrollRow);
				if (RowAboutToChange != null)
					{
					// iterate all possible rows, to reset the selected row class, and then reset the current index...
					var iLoop;
					try
						{
						for (iLoop=1;iLoop<=iEndScrollRow;iLoop++)
							getobject('IntuitionResultsRow' + iLoop).className = 'NormalRow';
						}
					catch (ex2) {} // eat errors
					if (iCurrentScrollRowMinusOne > 0)
						getobject('IntuitionResultsRow' + iCurrentScrollRowMinusOne).className = 'NormalRow';
					RowAboutToChange.className = 'SelectedRow';			
					//SetInputBoxText(getobject('IntuitionResultsTerm' + iCurrentScrollRow).innerHTML);
					}
				else
					{
					// if we're here, then there is no next row, so roll back...
					iCurrentScrollRow--;
					}
				}
			catch (ex)
				{
				// if we're here, then we didn't find the next row, so roll back the
				// CurrentScrollRow...
				iCurrentScrollRow--;
				}
			}
	}
	else if (e.keyCode == 27 && !suppressKeys)
	{
		HideResults();
	}
	else if (e.keyCode == 13 && !suppressKeys)
	{
	    //Enter key			    
		var objRow = getobject('IntuitionResultsTerm' + iCurrentScrollRow);
		if(objRow != null)
			SelectCurrentRow();
		else
		    SubmitFormLink();	
		//SetResults("");				
		//HideResults();
	    //CancelEvent(e);
	}
	else
	{
		e.returnValue = true;
		//get the value from text box
		//Only search after the 2nd keystroke on the dynamic search results page
		if(suppressKeys)
		{
			if(CurrentValue.length > 0)
			{
				SendQueryStub(CurrentValue);		
				//SendVerityStub(CurrentValue,10);	
			}				
			else
			{
				//SetResults("");		
				//HideResults();
				//CancelEvent(e);
			}
		}
		else	
			SendQueryStub(CurrentValue);
	    
	}

	// reset the faker, just to be sure...
	FakeKeyDown = false;
}

function HighlightMouseOver(Row, RowNumber)
{
	
	// iterate all possible rows, to reset the selected row class, and then reset the current index...
	var iLoop;
	try
		{
		for (iLoop=1;iLoop<=iEndScrollRow;iLoop++)
			getobject('IntuitionResultsRow' + iLoop).className = 'NormalRow';
		}
	catch (ex) {} // eat errors

	Row.className = 'SelectedRow';
	iCurrentScrollRow = RowNumber;
	
	//SetInputBoxText(getobject('IntuitionResultsTerm' + iCurrentScrollRow).innerHTML);

}

function UnHighlightMouseOver(Row)
{
	
	Row.className = 'NormalRow';
	//iCurrentScrollRow = 0;
	
}

var IE=false;
if (document.all)
    IE=true;
    
function SelectCurrentRow(){

	var myrow = getobject('IntuitionResultsTerm' + iCurrentScrollRow);
    var myHiddenText = getobject('divvalue' + iCurrentScrollRow);
    var myHiddenId = getobject('divid' + iCurrentScrollRow);
    
    if (IE)
        SetInputBoxText(myrow.innerText, myHiddenText.value);
    else    
	    SetInputBoxText(myrow.textContent, myHiddenText.value);
	
	location.href = "/experts/profile.aspx?attorney=" + myHiddenId.value;
	    
	HideResults();
	ShowSelectBox();
	if(isHome)
	{        
//        if(myrow.attributes['attid'].nodeValue != "")
//        {
//            DetermineMoreLink(myrow.attributes['attid'].nodeValue);
//        }
        SubmitFormLink();
    }
    else if(isDynamicResults)
        SubmitFormLink();
    	    
}

var iCurrentScrollRow = 0;
var iStartScrollRow = 1;
var iEndScrollRow = 15;

function DetermineMoreLink(keyword)
{
    AdvancedSearch.Ajax.AjaxMethods.DetermineMoreLink(keyword, DetermineMoreLinkCallback);
}

function DetermineMoreLinkCallback(ret)
{
    if (ret.value != null && ret.value != "")
        getobject('moreinfolink').style.display = 'block';
    else
        getobject('moreinfolink').style.display = 'none';
    
}

// determine DOM functionality
var isIE=document.all;
var isNS6=document.getElementById && !document.all;

// These let us set partial selections on the input box...
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 setCaretToEnd (input) 
	{
	setSelectionRange(input, input.value.length, input.value.length);
	}
	
function setCaretToBegin (input)
	{
	setSelectionRange(input, 0, 0);
	}
	
function setCaretToPos (input, pos)
	{
	setSelectionRange(input, pos, pos);
	}
	
function selectString (input, string)
	{
	var match = new RegExp(string, "i").exec(input.value);
	if (match) 
		{
		setSelectionRange (input, match.index, match.index + match[0].length);
		}
	}
	
function replaceSelection (input, replaceString)
	{
	if (input.setSelectionRange)
		{
		var selectionStart = input.selectionStart;
		var selectionEnd = input.selectionEnd;
		input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd);
		if (selectionStart != selectionEnd) // has there been a selection
			setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
		else // set caret
			setCaretToPos(input, selectionStart + replaceString.length);
		}
	else if (document.selection)
		{
		var range = document.selection.createRange();
		if (range.parentElement() == input)
			{
			var isCollapsed = range.text == '';
			range.text = replaceString;
			if (!isCollapsed)
				{ 
				// there has been a selection
				// it appears range.select() should select the newly 
				// inserted text but that fails with IE
				range.moveStart('character', -replaceString.length);
				range.select();
				}
			}
		}
	}

function LoseFocus(){
    HideResults();
}

function UpdateSearchStats(){
	UpdateSearchStatsInternal(getobject('keyword').value);	
}

function UpdateSearchStatsInternal(term){
	term = decodeURIComponent(term);
	if(term != '')
		AdvancedSearch.Ajax.AjaxMethods.UpdateSearchStatistics(term, null);
}


function getobject(obj){
if (document.getElementById)
return document.getElementById(obj);
else if (document.all)
return document.all[obj];
}

function CancelEvent(e){
    if (e && e.preventDefault) e.preventDefault();
    else if (window.event) e.returnValue = false;
}

//More Info Section
function GetMoreInfoHome(){
    var myrow = getobject('IntuitionResultsTerm' + iCurrentScrollRow);
    if(myrow != null)    
        if(myrow.attributes['attid'].nodeValue != "")        
            AdvancedSearch.Ajax.AjaxMethods.GetMoreInfoAttorney(myrow.attributes['attid'].nodeValue, iGetMoreInfoHomeCallback);
            
            
}

function iGetMoreInfoHomeCallback(ret){    
    if(ret.value != null){
        var infoBox = getobject("MoreInfoBox");
        infoBox.innerHTML = ret.value;
        infoBox.className = "MoreInfo";
    }
}

var xCoord = 1000;
var yCoord = 500;
function GetMoreInfoSearch(myguid, entityType){    
    //xCoord = event.clientX;
    //yCoord = event.clientY;
    
    AdvancedSearch.Ajax.AjaxMethods.GetMoreInfo(myguid, entityType, iGetMoreInfoHomeCallback);
}

function iGetMoreInfoSearchCallback(ret){            
    if(ret.value != null){
        var infoBox = getobject("MoreInfoBox");
        infoBox.innerHTML = ret.value;
        infoBox.className = "MoreInfo";
        infoBox.style.left = xCoord;
        infoBox.style.top = yCoord;
    }
}

function HideMoreInfo(){
    var infoBox = getobject("MoreInfoBox");
    infoBox.className = "MoreInfoHidden";
    infoBox.innerHTML = "";
}
//End More Info Section