var aSuggestions = [];
var autoSuggestSuggestions=[];
var autoSuggestControl;
var returnFalse = true;
var textEntered;
var enableDisableAutoSuggest=true; // used to switch ON/OFF the autosuggestion; 1.true --> ON 2.false --> turnoff
var siteKey=1;
var highLightedSuggestion;
var successJSONObject=true;
var txtValueWhenServiceHit;
var firstElementInList;	
var nextField;
var divWidth;
var divHeight;
var airports;
var onClickOfTextBoxFrom = false;
var onClickOfTextBoxTo = false;
var selectedContent = [];
var flagForSecondAttempt=false;
var randomnumber;
var noMethodFound="No matches found";
var divTextBoxname;
var bracketIndex="";
var currentObj;	
var oTextbox1;
var oTextbox2;
var resizeVariable;
var ipTxt="shop_from0_temp";

/**
 * Provides suggestions for Airports.
 * @class
 * @scope public
 */
function AirportsSuggestions() {
	this.http;
	
}
/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
AirportsSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                        bTypeAhead /*:boolean*/) {
	//ff29updateOthers();
	aSuggestions = [];	
	autoSuggestControl = oAutoSuggestControl;
    var sTextboxValue = oAutoSuggestControl.textbox.value;	
		sTextboxValue = trim(sTextboxValue);
		textEntered = sTextboxValue;
		ipTxt=oAutoSuggestControl.textbox.id;
		//alert(window.location.href +"   --  "+document.URL+"  **  "+ document.location.protocol+" +++  "+document.location.href);			
    if (sTextboxValue.length == 3){
		aSuggestions = [];	
		txtValueWhenServiceHit=textEntered;
	    var sTextboxValueUC = oAutoSuggestControl.textbox.value.toUpperCase();		
		var fieldName=ipTxt.substring(0,ipTxt.lastIndexOf("_"));
		document.getElementById(fieldName).value = document.getElementById(ipTxt).value	
		var url;
		randomnumber=Math.floor(Math.random()*1000000)
		
		if(isAlpha(sTextboxValueUC))
		{
			if(countrysiteId)siteKey=countrysiteId;
			if(document.location.href.indexOf("http")==0)
			{
			url = "http://travel.united.com/async/cityName/cityNameHint.jsp?siteId=" + siteKey + "&city=" + sTextboxValueUC + "&number=" +randomnumber+" &callback=processJSON&jsoncallback=?";
			}
			if(document.location.href.indexOf("https")==0)
			{
			url = "https://travel.united.com/async/cityName/cityNameHint.jsp?siteId=" + siteKey + "&city=" + sTextboxValueUC + "&number=" +randomnumber+ "&callback=processJSON&jsoncallback=?";	
			}
		}
		else
		{
			return;
		}
		$.getJSON(url);			
	}	
	else if (sTextboxValue.length <= 2){
		aSuggestions = [];	
	 }
	else if (sTextboxValue.length > 3)
	 {	
		aSuggestions = [];
		if(autoSuggestSuggestions.length>=1 && txtValueWhenServiceHit==textEntered.substring(0,3))
		{
			 for (var i=0; i < autoSuggestSuggestions.length; i++) 
			 {
				 var citySuggestion = autoSuggestSuggestions[i].substring(0,autoSuggestSuggestions[i].indexOf(","));
				var stateCountrySuggestion = autoSuggestSuggestions[i].substring(autoSuggestSuggestions[i].indexOf(",")+1,autoSuggestSuggestions[i].indexOf("-"));
				var airportNameSuggestion =autoSuggestSuggestions[i].substr(autoSuggestSuggestions[i].indexOf("-")+1,autoSuggestSuggestions[i].length);
				if(citySuggestion.indexOf("/")>=0 && ((trim(citySuggestion)).toUpperCase()).indexOf(sTextboxValue.toUpperCase())>=0)
				{
					aSuggestions.push(autoSuggestSuggestions[i]);
				}
				else if((citySuggestion.toUpperCase()).indexOf(sTextboxValue.toUpperCase())==0)
				{
					aSuggestions.push(autoSuggestSuggestions[i]);
				}				 
				else if(((trim(stateCountrySuggestion)).toUpperCase()).indexOf(sTextboxValue.toUpperCase())==0 )
				{
					//aSuggestions.push(autoSuggestSuggestions[i]);
				}
				else if(airportNameSuggestion.indexOf("/")>=0 && ((trim(airportNameSuggestion)).toUpperCase()).indexOf(sTextboxValue.toUpperCase())>=0 )
				{
					aSuggestions.push(autoSuggestSuggestions[i]);
				}				 
				else if(((trim(airportNameSuggestion)).toUpperCase()).indexOf(sTextboxValue.toUpperCase())==0 )
				 {
					aSuggestions.push(autoSuggestSuggestions[i]);
				 }			 
			 }
			 if(aSuggestions.length>=1){
				autoSuggestControl.autosuggest(aSuggestions, false);
			 }
			 else{
				aSuggestions = [];
				aSuggestions.push(noMethodFound);
				autoSuggestControl.autosuggest(aSuggestions, false);
				
			 }
		}
		else
		{	
			aSuggestions = [];
			var i;
			for (i=0;i<selectedContent.length;i++)
			{					
				if(selectedContent[i]==textEntered)
				{	
					aSuggestions.push(selectedContent[i]);
					autoSuggestControl.autosuggest(aSuggestions, false);
					flagForSecondAttempt=true;
					break;
				}
				else
				{
					flagForSecondAttempt=false;
				}				
			}
			if(flagForSecondAttempt!=true)
			{	aSuggestions = [];
				txtValueWhenServiceHit=textEntered;
				var sTextboxValueUC = oAutoSuggestControl.textbox.value.toUpperCase();	
				var fieldName=ipTxt.substring(0,ipTxt.lastIndexOf("_"));
				document.getElementById(fieldName).value = document.getElementById(ipTxt).value			
				var url;
				randomnumber=Math.floor(Math.random()*1000000)
			
				if(isAlpha(sTextboxValueUC))
				{	
					if(countrysiteId)siteKey=countrysiteId;
					if(document.location.href.indexOf("http")==0)
					{
					url = "http://travel.united.com/async/cityName/cityNameHint.jsp?siteId=" + siteKey + "&city=" + sTextboxValueUC + "&number=" +randomnumber+" &callback=processJSON&jsoncallback=?";
					}
					if(document.location.href.indexOf("https")==0)
					{
					url = "https://travel.united.com/async/cityName/cityNameHint.jsp?siteId=" + siteKey + "&city=" + sTextboxValueUC + "&number=" +randomnumber+ "&callback=processJSON&jsoncallback=?";	
					}
				}
				else
				{
					return;
				}
				$.getJSON(url);				
			}
		}
			 
	 }
};

/**
 * To trim the given String. 
 * @param myString The String to be trimed with leading and trailing spaces.
 */
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}

function processJSON(jsonData) {
autoSuggestSuggestions=[];
aSuggestions = [];
	if(jsonData!=null)
	{
		if(jsonData.empty == "Y")
		{		
		aSuggestions = [];
		aSuggestions.push(noMethodFound);
		autoSuggestControl.autosuggest(aSuggestions, false);	
		}
		if(jsonData.empty == "N")
		{		
			aSuggestions = [];
			airports = eval(jsonData.airports);
			for (var i=0; i < airports.length; i++) { 		
			aSuggestions.push(airports[i].display_text);
			autoSuggestSuggestions.push(airports[i].display_text);
			}			
			autoSuggestControl.autosuggest(aSuggestions, false);	
		}
		if(jsonData.empty == "E")
		{
			aSuggestions = [];
			successJSONObject=false;
		}
	}
	else
	{
		successJSONObject=false;
	}
}

function stopRKey(evt) { 
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  var keyCode = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
  if ((keyCode==13) && (node.id.indexOf("_temp")!=-1))  {return false;} 
}
document.onkeypress = stopRKey;

// to get the airport code
function getAirportCode(toValue)
{
var airportCode=toValue.substring(toValue.lastIndexOf("(")+1,toValue.lastIndexOf(")"));
return airportCode;
}

//START - FSN Auto-suggest Changes

function documentOnclickForAutosuggest() 
{	
	if(successJSONObject==true)
	{
		if(document.getElementById('autoSuggestDiv'))
		{
		  if((document.getElementById('autoSuggestDiv').style.visibility != "hidden"
				|| document.getElementById('iframe').style.display == "block"))
				{ 	
					if(document.getElementById(divTextBoxname).value == textEntered && highLightedSuggestion!="" && firstElementInList!=noMethodFound )
					{
						document.getElementById(divTextBoxname).value="";
						document.getElementById(divTextBoxname).value=highLightedSuggestion; // currently highlited value
						var id = divTextBoxname; // added to get the current text box ID 
						id=id.substring(0,id.lastIndexOf('_'));	
						var toValue=highLightedSuggestion;
						var assignTxt=getAirportCode(toValue);
						document.getElementById(id).value=assignTxt;
						highLightedSuggestion="";
						assignTxt="";
					}
					document.getElementById('autoSuggestDiv').style.visibility = "hidden";
					document.getElementById('iframe').style.display = 'none';
				}
		  }	  
	 }
	 else
	 {
		document.getElementById("shop_from"+(flightCount-1)).value=document.getElementById("shop_from"+(flightCount-1)+"_temp").value
		document.getElementById("shop_to"+(flightCount-1)).value=document.getElementById("shop_to"+(flightCount-1)+"_temp").value
	 }
}
function updateValue(ipTxt1)
{	
	if(!enableDisableAutoSuggest)
	{	
		document.getElementById("shop_from"+(flightCount-1)).value=document.getElementById("shop_from"+(flightCount-1)+"_temp").value
		document.getElementById("shop_to"+(flightCount-1)).value=document.getElementById("shop_to"+(flightCount-1)+"_temp").value
	}	
	ipTxt = ipTxt1;	// assign the text box ID to a global variable 
	var id = ipTxt; // added to get the current text box ID
	var KeyID 
	if(window.event) {
		KeyID = event.keyCode;		
	}
	if(KeyID && (KeyID!=13 || KeyID!=9 || KeyID!=27)){		
		id=id.substring(0,id.lastIndexOf('_'));
		var txtBoxValue= document.getElementById(ipTxt).value;		
		bracketIndex=txtBoxValue.substring(txtBoxValue.lastIndexOf('('),txtBoxValue.lastIndexOf(')'));
		if(bracketIndex!="")
		{
			document.getElementById(id).value=bracketIndex;
		}
		else
		{
			document.getElementById(id).value=document.getElementById(ipTxt).value;
		}
	}
	
 }

function updateOnclickOftxtBox(txtBoxName)
{	
	document.getElementById(txtBoxName).focus();
	document.getElementById(txtBoxName).select();
	ipTxt = txtBoxName;
}
			
function readyAutosuggest() 
{
	if(enableDisableAutoSuggest)
	{
		var i=0; //flightCount comes from the page
		for( ;i<flightCount; i++) {			
		oTextbox1 = new AutoSuggestControl(document.getElementById("shop_from"+[i]+"_temp"), new AirportsSuggestions());  
		oTextbox2 = new AutoSuggestControl(document.getElementById("shop_to"+[i]+"_temp"), new AirportsSuggestions());
		document.getElementById("shop_from"+[i]+"_temp").value=document.getElementById("shop_from"+[i]).value;
		document.getElementById("shop_to"+[i]+"_temp").value=document.getElementById("shop_to"+[i]).value;
		document.getElementById("shop_from"+[i]+"_temp").setAttribute( "autocomplete", "off" );
		document.getElementById("shop_to"+[i]+"_temp").setAttribute( "autocomplete", "off" );
		}
	}
	else
	{
		var i=0;
		for( ;i<flightCount; i++) {		
			document.getElementById("shop_from"+[i]+"_temp").value=document.getElementById("shop_from"+[i]).value;
			document.getElementById("shop_to"+[i]+"_temp").value=document.getElementById("shop_to"+[i]).value;
		}
	}
}	
				
function resizeAutosuggest() 
{
	var tmp;
	if(document.getElementById('iframe') && document.getElementById('autoSuggestDiv') ){
	document.getElementById('iframe').style.height="";
	document.getElementById('iframe').style.width="";
	document.getElementById('autoSuggestDiv').style.height="";
	document.getElementById('autoSuggestDiv').style.width="";
	}
	var layer = document.getElementById('autoSuggestDiv');
	var iframe = document.getElementById('iframe');	
	if(document.getElementById('autoSuggestDiv'))
	{			
		if(document.getElementById('autoSuggestDiv').style.visibility!="hidden" && document.getElementById('iframe') && document.getElementById('autoSuggestDiv'))
		{	
			if(ipTxt)
			{
				var id = ipTxt; // added to get the current text box ID 
				id=id.substring(0,id.lastIndexOf('_')-1);
				if(id=="shop_from")
				{
					resizeVariable=oTextbox1;
				}
				else if(id=="shop_to")
				{
					resizeVariable=oTextbox2;
				}
			}
			
			if(currentObj) // from autoSuggest.js
			{
				tmp= autoSuggestControl.getElementPosition(currentObj);
			}
			resizeVariable.layer.style.left = tmp.x + "px";
			resizeVariable.layer.style.width = divWidth;
			resizeVariable.layer.style.top = (tmp.y+resizeVariable.textbox.offsetHeight) + "px";
			
			iframe.style.dispaly="block";
			iframe.style.left = resizeVariable.layer.style.left;
			iframe.style.top = resizeVariable.layer.style.top;
			iframe.style.height =divHeight;					
			iframe.style.width = resizeVariable.layer.style.width;
			document.getElementById('autoSuggestDiv').style.height = iframe.style.height;
			
		}			
	}	
}

// to get the airport code
function getAirportCode(toValue)
{
var airportCode=toValue.substring(toValue.lastIndexOf("(")+1,toValue.lastIndexOf(")"));
return airportCode;
}
//END- FSN Auto-suggest Changes 
 function isAlpha(str){
	 var re = /^[a-zA-Z ,\.'-]+$/.test(str);  
	 return re;
}

