var getFunctionsUrl = "/rpc2.php?keyword=";
var phpHelpUrl= "javascript:goToSearchProfilePage(\"";
var httpRequestKeyword = "";
var userKeyword = "";
var suggestions = 0;
var suggestionMaxLength = 30;
var isKeyUpDownPressed = false;
var autocompletedKeyword = "";
var hasResults = false;
var timeoutId = -1;
var position = -1;
var oCache = new Object();
var minVisiblePosition = 0;
var maxVisiblePosition = 9;
var debugMode = true;
 var xmlHttpGetSuggestions = createXmlHttpRequestObject(); 

window.onload = initwidget;

/* function that hides the layer containing the suggestions */
function hidePeopleSuggestions()
{
  var oScroll = document.getElementById("people_scroll");
  oScroll.style.visibility = "hidden";  
  oScroll.style.display = "none"; 
}

function onFocusPeopleIn(stringValue){
	if(stringValue=='FIND PEOPLE IN PHOTOS')
		document.getElementById('people_keyword').value='';
}


// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  var xmlHttp;
  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

/* function that initializes the page */
function initwidget() 
{  
  var oKeyword = document.getElementById("people_keyword");    
  oKeyword.setAttribute("autocomplete", "off");  
  setTimeout("checkForChanges()", 500);
} 

function addToCache(keyword, values)
{
  oCache[keyword] = new Array();
  for(i=0; i<values.length; i++)
    oCache[keyword][i] = values[i];
}

function checkCache(keyword)
{
  if(oCache[keyword])
    return true;
  for(i=keyword.length; i>=0; i--)
  {
	var currentKeyword = keyword;
    if(oCache[currentKeyword])
    {            
      var cacheResults = oCache[currentKeyword];
      var keywordResults = new Array();
      var keywordResultsSize = 0;            
      for(j=0;j<cacheResults.length;j++)
      {
 
        if(cacheResults[j].indexOf(keyword) == 0)               
          keywordResults[keywordResultsSize++] = cacheResults[j];
      }      
      addToCache(keyword, keywordResults);      
      return true;  
    }
  }
  return false;
}

function getSuggestions(keyword) 
{  
  /* continue if keyword isn't null and the last pressed key wasn't up or 
     down */
if(keyword == "FIND PEOPLE IN PHOTOS") keyword="";
  if(keyword != "" && !isKeyUpDownPressed)
  {
    // check to see if the keyword is in the cache
   isInCache = checkCache(keyword);
//	Blocking the Catch Content
	isInCache = false;
 //   // if keyword is in cache...
    if(isInCache == true)          
    {   
      // retrieve the results from the cache          
      httpRequestKeyword=keyword;
      userKeyword=keyword;     
      // display the results in the cache
	  if(oCache[keyword])
		displayResults(keyword, oCache[keyword]);                          
    }
    // if the keyword isn't in cache, make an HTTP request
    else    
    {    
      if(xmlHttpGetSuggestions)
      { 
        try
        {
          /* if the XMLHttpRequest object isn't busy with a previous
             request... */
          if (xmlHttpGetSuggestions.readyState == 4 || 
              xmlHttpGetSuggestions.readyState == 0) 
          {    
            httpRequestKeyword = keyword;
            userKeyword = keyword;
            xmlHttpGetSuggestions.open("GET", 
                                getFunctionsUrl + encode(keyword), true);
			xmlHttpGetSuggestions.onreadystatechange = 
                                                handleGettingSuggestions; 
            xmlHttpGetSuggestions.send(null);
          }
          // if the XMLHttpRequest object is busy...
          else
          {  
            // retain the keyword the user wanted             
            userKeyword = keyword;
            // clear any previous timeouts already set
            if(timeoutId != -1)
              clearTimeout(timeoutId);          
            // try again in 0.5 seconds     
            timeoutId = setTimeout("getSuggestions(userKeyword);", 500);
          }
        }
        catch(e)
 
        {
          displayError("Can't connect to server:\n" + e.toString());
        }
      }
    }    
  }
}

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml)
{
  // initiate the resultsArray
  var resultsArray= new Array();  
  // loop through all the xml nodes retrieving the content  
  for(i=0;i<resultsXml.length;i++)
    resultsArray[i]=resultsXml.item(i).firstChild.data;
  // return the node's content as an array
  return resultsArray;
}

/* handles the server's response containing the suggestions 
   for the requested keyword  */
function handleGettingSuggestions() 
{
  //if the process is completed, decide what to do with the returned data
  var status;
  try{ status = xmlHttpGetSuggestions.status;}catch(e){}

  if (xmlHttpGetSuggestions.readyState == 4) 
  {
    // only if HTTP status is "OK"
    if (status == 200) 
    { 
      try
      {
        // process the server's response
        updateSuggestions();
      }
      catch(e)
      { 
		if(e.toString() != "TypeError: oCache[keyword] has no properties") {
		        // display the error message
		        displayError(e.toString()); 
		}
      }  
    } 
    else
    {
      displayError("There was a problem retrieving the data:\n" + 
                   xmlHttpGetSuggestions.statusText);
    }       
  }
}

/* function that processes the server's response */
function updateSuggestions()
{
  // retrieve the server's response 
  var response = xmlHttpGetSuggestions.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0 
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Void server response." : response);
  // retrieve the document element
  response = xmlHttpGetSuggestions.responseXML.documentElement;
  // initialize the new array of functions' names
  nameArray = new Array();
  // check to see if we have any results for the searched keyword
 
  if(response.childNodes.length)
  {
    /* we retrieve the new functions' names from the document element as 
       an array */
    nameArray= xmlToArray(response.getElementsByTagName("name"));       
  }
  // check to see if other keywords are already being searched for
  
  if(httpRequestKeyword == userKeyword)    
  {
    // display the results array
    displayResults(httpRequestKeyword, nameArray);
  }
  else
  {
    // add the results to the cache
    // we don't need to display the results since they are no longer useful
    addToCache(httpRequestKeyword, nameArray);              
  }
}

/* populates the list with the current suggestions */
function displayResults(keyword, results_array) 
{  
  // start building the HTML table containing the results  
  var div = "<table>"; 
  // if the searched for keyword is not in the cache then add it to the cache
  if(!oCache[keyword] && keyword)
    addToCache(keyword, results_array);
  // if the array of results is empty display a message
  if(results_array.length == 0)
  {
   /* div += "<tr><td>No Profiles Found for <strong>" + keyword + 
           "</strong></td></tr>";*/
	div += "<tr><td>No Profiles Found </td></tr>";
    // set the flag indicating that no results have been found 
    // and reset the counter for results
    hasResults = false;
    suggestions = 0;
  }
  // display the results
  else
  { 
    // resets the index of the currently selected suggestion
    position = -1;
    // resets the flag indicating whether the up or down key has been pressed
    isKeyUpDownPressed = false;
    /* sets the flag indicating that there are results for the searched 
       for keyword */
    hasResults = true;
    // get the number of results from the cache
    suggestions = oCache[keyword].length;
    // loop through all the results and generate the HTML list of results
    for (var i=0; i<oCache[keyword].length; i++) 
    {  
      // retrieve the current function
      crtFunction = oCache[keyword][i];
      // set the string link for the for the current function 
      // to the name of the function
      crtFunctionLink = crtFunction;
      // replace the _ with - in the string link
/*      while(crtFunctionLink.indexOf("_") !=-1)
        crtFunctionLink = crtFunctionLink.replace("_","-");*/
      // start building the HTML row that contains the link to the 
      // PHP help page of the current function
		var linkURL = crtFunctionLink;
		/* while(linkURL.indexOf(" ") !=-1)
			linkURL = linkURL.replace(" ", "-");*/
      div += "<tr id='tr" + i + 
             "' onclick='location.href=document.getElementById(\"a" + i + 
             "\").href;' onmouseover='handleOnMouseOver(this);' " + 
             "onmouseout='handleOnMouseOut(this);'>" + 
             "<td align='left'><a id='a" + i + 
             "' href='" + phpHelpUrl + linkURL + "\");";
      // check to see if the current function name length exceeds the maximum 
      // number of characters that can be displayed for a function name
      if(crtFunction.length <= suggestionMaxLength)
      {
        // bold the matching prefix of the function name and of the keyword
        div += "'><b>" + 
               crtFunction.substring(0, httpRequestKeyword.length) + 
               "</b>"
        div += crtFunction.substring(httpRequestKeyword.length, 
                                     crtFunction.length) + 
               "</a></td></tr>";
      }
      else
      {
        // check to see if the length of the current keyword exceeds 
        // the maximum number of characters that can be displayed
        if(httpRequestKeyword.length < suggestionMaxLength)
        {
          /* bold the matching prefix of the function name and that of the 
             keyword */
          div += "'><b>" + 
                 crtFunction.substring(0, httpRequestKeyword.length) + 
                 "</b>"
          div += crtFunction.substring(httpRequestKeyword.length,
                                       suggestionMaxLength) + 
                 "</a></td></tr>";   
        }
        else
        {
          // bold the entire function name
          div += "'><b>" + 
                 crtFunction.substring(0,suggestionMaxLength) + 
                 "</b></td></tr>"          
        }
      }
    }
  }
  // end building the HTML table
  div += "</table>";
  
  // retrieve the suggest and scroll object
  var oSuggest = document.getElementById("people_suggest");  
  var oScroll = document.getElementById("people_scroll");
  // scroll to the top of the list
  oScroll.scrollTop = 0;
  // update the suggestions list and make it visible
  oSuggest.innerHTML = div;
  oScroll.style.display = "inline";
  oScroll.style.visibility = "visible";
  // if we had results we apply the type ahead for the current keyword
  //if(results_array.length > 0)
    //autocompleteKeyword();      
}

/* function that periodically checks to see if the typed keyword has changed */
function checkForChanges()
{
  // retrieve the keyword object
  var keyword = document.getElementById("people_keyword").value;
  // check to see if the keyword is empty
  if(keyword == "")
  {
    // hide the suggestions
    hidePeopleSuggestions();
    // reset the keywords 
    userKeyword="";
    httpRequestKeyword="";
  }
  // set the timer for a new check 
  setTimeout("checkForChanges()", 500);
  // check to see if there are any changes
  if((userKeyword != keyword) && 
     (autocompletedKeyword != keyword) && 
     (!isKeyUpDownPressed))
    // update the suggestions
    getSuggestions(keyword);
}

/* function that handles the keys that are pressed */
function handlePeopleKeyUp(e) 
{	
  // get the event
  e = (!e) ? window.event : e;
  // get the event's target
  target = (!e.target) ? e.srcElement : e.target;
  if (target.nodeType == 3) 
    target = target.parentNode;
  // get the character code of the pressed button
  code = (e.charCode) ? e.charCode :
       ((e.keyCode) ? e.keyCode :
       ((e.which) ? e.which : 0));
  // check to see if the event was keyup
  if (e.type == "keyup") 
  {     
    isKeyUpDownPressed =false; 
    // check to see we if are interested in the current character
    if ((code < 13 && code != 8) || 
        (code >=14 && code < 32) || 
        (code >= 33 && code <= 46 && code != 38 && code != 40) || 
        (code >= 112 && code <= 123)) 
    {
      // simply ignore non-interesting characters
    }
    else
    /* if Enter is pressed we jump to the PHP help page of the current 
       function */
    if(code == 13)
    { 
      // check to see if any function is currently selected
      if(position>=0)
      {
        location.href = document.getElementById("a" + position).href;
      }        
    }        
    else
    // if the down arrow is pressed we go to the next suggestion
      if(code == 40)
      {    
        newTR=document.getElementById("tr"+(++position));
        oldTR=document.getElementById("tr"+(--position));
        // deselect the old selected suggestion   
        if(position>=0 && position<suggestions-1)
          oldTR.className = "";
 
        // select the new suggestion and update the keyword
        if(position < suggestions - 1)
        {
          newTR.className = "highlightrow";
          updateKeywordValue(newTR);
          position++;         
        }     
        e.cancelBubble = true;
        e.returnValue = false;
        isKeyUpDownPressed = true;        
        // scroll down if the current window is no longer valid
         
        if(position > maxVisiblePosition)
        {    
          oScroll = document.getElementById("people_scroll");
          oScroll.scrollTop += 18;
          maxVisiblePosition += 1;
          minVisiblePosition += 1;
        }
      }
      else
      // if the up arrow is pressed we go to the previous suggestion
      if(code == 38)
      {        
        newTR=document.getElementById("tr"+(--position));
        oldTR=document.getElementById("tr"+(++position));
        // deselect the old selected position
        if(position>=0 && position <= suggestions - 1)
        {       
          oldTR.className = "";
        }
        // select the new suggestion and update the keyword
        if(position > 0)
        { 
          newTR.className = "highlightrow";
          updateKeywordValue(newTR);
          position--;
          // scroll up if the current window is no longer valid
          if(position<minVisiblePosition)
          {
            oScroll = document.getElementById("people_scroll");
            oScroll.scrollTop -= 18;
            maxVisiblePosition -= 1;
            minVisiblePosition -= 1;
          }   
        }     
        else{
        	 
          if(position == 0)
            position--;
           }
        e.cancelBubble = true;
        e.returnValue = false;
        isKeyUpDownPressed = true;  
      }     
  }
}

/* function that updates the keyword value with the value 
   of the currently selected suggestion */
function updateKeywordValue(oTr)
{
  // retrieve the keyword object
  var oKeyword = document.getElementById("people_keyword");
  // retrieve the link for the current function
   var crtLink = document.getElementById("a" + 
                            oTr.id.substring(2,oTr.id.length)).toString();
  // replace - with _ and leave out the .php extension
 /* while(crtFunctionLink.indexOf("-") !=-1)
  crtLink = crtLink.replace("-", " ");
  crtLink = crtLink.substring(0, crtLink.length - 1);*/
  // update the keyword's value
  //oKeyword.value = unescape(crtLink.substring(phpHelpUrl.length, crtLink.length-3));
   var value = unescape(crtLink.substring(phpHelpUrl.length, crtLink.length-3));
   value = value.replace("%2", "");
   oKeyword.value = value.replace("22", "");
}

/* function that removes the style from all suggestions*/
function deselectAll()
{ 
  for(i=0; i<suggestions; i++)
  {
    var oCrtTr = document.getElementById("tr" + i);
    oCrtTr.className = "";    
  }
}

/* function that handles the mouse entering over a suggestion's area 
   event */
function handleOnMouseOver(oTr)
{
  deselectAll();  
  oTr.className = "highlightrow";  
  position = oTr.id.substring(2, oTr.id.length);
}

/* function that handles the mouse exiting a suggestion's area event */
function handleOnMouseOut(oTr)
{
  oTr.className = "";   
  position = -1;
}

/* function that escapes a string */
function encode(uri) 
{ 
  if (encodeURIComponent) 
  { 
    return encodeURIComponent(uri);
  }

  if (escape) 
  {	
    return escape(uri);
  }

}


/* function that selects a range in the text object passed as parameter */
function selectRange(oText, start, length)
{  
  // check to see if in IE or FF
  if (oText.createTextRange) 
  {
    //IE
    var oRange = oText.createTextRange(); 
    oRange.moveStart("character", start); 
    oRange.moveEnd("character", length - oText.value.length); 
    oRange.select();
 
  }
  else 
    // FF
    if (oText.setSelectionRange) 
    {
      oText.setSelectionRange(start, length);
    } 
  oText.focus(); 
}

/* function that autocompletes the typed keyword*/
function autocompleteKeyword()
{
  //retrieve the keyword object
  var oKeyword = document.getElementById("people_keyword");
  // reset the position of the selected suggestion
  position=0;
  // deselect all suggestions
  deselectAll();
  // highlight the selected suggestion 
  document.getElementById("tr0").className="highlightrow";  
  // update the keyword's value with the suggestion
  updateKeywordValue(document.getElementById("tr0"));  
  // apply the type-ahead style
  selectRange(oKeyword,httpRequestKeyword.length,oKeyword.value.length);  
  // set the autocompleted word to the keyword's value
  autocompletedKeyword=oKeyword.value;
}

/* function that displays an error message */
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  alert("Error accessing the server! "+
        (debugMode ? "\n" + message : ""));
//		var error =1;
}

function goToPrifilePage(){
	var uri = "";
	var temp = document.getElementById("people_keyword").value;
	temp = temp.replace(/[^a-zA-Z 0-9]+/g,'-');
	uri = temp.replace(/\s/g,'-');
	uri = uri.toLowerCase();
	window.location='http://guestofaguest.com/directory/'+uri;
}

function goToSearchProfilePage(profileName) {
	var uri = "";
		var temp = profileName;
		temp = temp.replace(/[^a-zA-Z 0-9]+/g,'-');
		uri = temp.replace(/\s/g,'-');
		uri = uri.toLowerCase();
	window.location='http://guestofaguest.com/directory/'+uri;
}

function showBlogRollDiv(divIdNumber, totalNoofDivs, obj) {
	for(var i=0; i < totalNoofDivs; i++) {
		document.getElementById("blogrolldiv"+i).style.display = "none";
		try{
			document.getElementById("black"+i+"active").id="black"+i;
		} catch (e) {
		}
	}
	document.getElementById("blogrolldiv"+divIdNumber).style.display = "inline";
	obj.id += 'active';
}

function focusInPostEmail(email) {
if(email == 'Enter Email...')
   document.postSaveEmail.email.value="";
}
function store_post_email(){
	str = document.postSaveEmail.email.value;
        if(str == "Enter Email...") str = "";
	if(str.length == 0) {
		document.getElementById("postEmailStatus").innerHTML = "<font color='red'>Please enter your Email Id</font>";
	} else {
		var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if(!(str.match(emailRegEx))){
			document.getElementById("postEmailStatus").innerHTML = "<font color='red'>Please enter your correct Email Id</font>";
		} else {

			xmlHttp=GetXmlHttpObject()
			if (xmlHttp==null){
				alert ("Browser does not support HTTP Request");
				return;
			}
			var url="/store_email.php";
			url=url+"?id="+str;
			//xmlHttp.onreadystatechange=stateChanged() ;
			xmlHttp.open("GET",url,false);
			xmlHttp.send(null);
			if (xmlHttp.status==200){ 
				document.getElementById("postEmailStatus").innerHTML=xmlHttp.responseText ;
			}
			return false; 
		}
	}
}

<!--
function onfocusgooglesearch(textvalue) {
	alert(textvalue);
}
//-->
 