var Destination;
var destCont		= "destCont";
var autosuggest		= "autosuggest";

// Rica - This searches for the availability of searchString in mainString starting from the first letter in mainString.
function startsWith(mainString, searchString)
{
    mainString = mainString.toLowerCase();
    searchString = searchString.toLowerCase();
    
    if(mainString && searchString)
    {		
		var regex = new RegExp("^"+searchString);
		if (mainString.match(regex)) { return true; }
		else { return false; }        
    }
}

// Rica
function _endsWith(element)
{
    var allInputs = document.getElementsByTagName('input');
    var allSelects = document.getElementsByTagName('select');
    var allSpans = document.getElementsByTagName('span');
    var allDivs = document.getElementsByTagName('div');
	var allAs = document.getElementsByTagName('a');
	var allPs = document.getElementsByTagName('p');
	var allTextArea=document.getElementsByTagName('textarea');
	var elemLength = element.length;
    var i=0;

    var allControlArray = new Array();

    if (allInputs && allInputs.length > 0)
        allControlArray = allControlArray.concat(allInputs);
    if (allSelects && allSelects.length > 0)
        allControlArray = allControlArray.concat(allSelects);
    if (allSpans && allSpans.length > 0)
        allControlArray = allControlArray.concat(allSpans);
    if (allDivs && allDivs.length > 0)
        allControlArray = allControlArray.concat(allDivs);
    if (allAs && allAs.length > 0)
        allControlArray = allControlArray.concat(allAs);
    if (allPs && allPs.length > 0)
        allControlArray = allControlArray.concat(allPs);
    if (allTextArea && allTextArea.length > 0)
        allControlArray = allControlArray.concat(allTextArea);
   
    if (allControlArray)
    {
        for (i=0; i<allControlArray.length; i++)
        {
            var controls = allControlArray[i];
            for (j=0; j<controls.length; j++)
            {
                var input = controls[j];
                var idValue = input.id;
                if (idValue)
                {
                    var pos = idValue.indexOf(element);
                    if (pos != -1 && (pos+elemLength)==idValue.length)
                        return idValue;
                }
            }
        }
    } 
    return null;
}

// Rica - Function to return the object of the passed id.
function $fn(element) 
{
	element = document.getElementById(element);
	return element;
}

// Rica
function InitHotelSearch() 
{
    Destination = _endsWith("inpHotelSearch");
    destDiv = $fn(Destination);
    var autoSuggest = new AutoSuggest(destDiv);
    autoSuggest.displayResult();
    document.onclick = closePopupDivs;
}

// Rica - Close the popup div's on document click.
function closePopupDivs(event)
{
	if(typeof (autosuggest) != "undefined")
	{
	    if ($fn(autosuggest) != null) {		
		    //closeAutoSuggest();			
	    }
	}
}

// Rica
function FindDestinationByName(InputDestination)
{
    var destArray;
    var matchingCityDestinations;
    var totalCities;

    matchingCityDestinations = getMatchingDestinations(arrayHotels, InputDestination, true);
    if (matchingCityDestinations != null)
    {
        totalCities = matchingCityDestinations.length;
        destArray = new Array(totalCities);
        
        for(ctr = 0; ctr < totalCities; ctr++)
        {
            destArray[ctr] = new Array(2);
            
            destArray[ctr][0] = matchingCityDestinations[ctr].ID + "#$:~" + matchingCityDestinations[ctr].name;
            if(matchingCityDestinations[ctr].hotels != null)
            {
                destArray[ctr][1] = new Array(matchingCityDestinations[ctr].hotels.length);
                for(ctrHotel = 0; ctrHotel < matchingCityDestinations[ctr].hotels.length; ctrHotel++)
                {
                   destArray[ctr][1][ctrHotel] = matchingCityDestinations[ctr].hotels[ctrHotel].ID + "#$:~" + matchingCityDestinations[ctr].hotels[ctrHotel].name;
                }
            }
        }    
    }
    return destArray;
}

// Rica - show destination/hotel maches when user types search text
var idCounter = 0;
var ajax_list_activeItem;
var ajax_list_FirstItem = false;
var ulList = false;

function AutoSuggest(elem)
{    
	var me = this;	
	this.elem = elem;
	this.eligible = new Array();
	this.inputText = null;
	this.highlighted = -1;
	this.div = $fn(autosuggest);
	var MAXHEIGHT = 140;
	var ENTER = 13;
	var ESC = 27;
	var UP_ARROW = 38;
	var DOWN_ARROW = 40;	
	var TAB = 9;

	if(!elem.id)
	{		
		var id = "autosuggest" + idCounter;
		idCounter++;
		elem.id = id;
	}
	
	elem.onkeydown = function(ev)
	{
		var key = me.getKeyCode(ev);		
		switch(key)
		{
			case ENTER:
						me.useSuggestion();
						ajax_options_rollOverActiveItem(ajax_list_FirstItem,true);
						me.cancelEvent(ev);						
						break;
			case ESC:
						me.hideDiv();
						//showDropDowns();
						break;
			case TAB:
						me.hideDiv();
						break;
			case UP_ARROW:
						
						if (me.highlighted > 0)
						{
							me.highlighted--;							
						}			
						if(!ajax_list_activeItem)return;
						if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
						ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
						
						me.changeHighlight();
						me.cancelEvent(ev);
						break;
			case DOWN_ARROW:					
						var lis = me.div.getElementsByTagName('A');	
						if (me.highlighted < (lis.length-1))
						{	
							me.highlighted++;								
						}							
						
						if(! ajax_list_activeItem){
							ajax_options_rollOverActiveItem(ajax_list_FirstItem,true);
						} else {
							if(!ajax_list_activeItem.nextSibling)
							{	
								me.changeHighlight();
								return;
							}
							ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
						}
						me.changeHighlight();
						me.cancelEvent(ev);
						break;
		}
	};

	elem.onkeyup = function(ev) {
	    var key = me.getKeyCode(ev);
	    switch (key) {
	        case ENTER:
	        case ESC:
	        case UP_ARROW:
	        case DOWN_ARROW:
	            return;
	        default:
	            me.displayResult();
	           
	    }
	};

	elem.onfocus = function(ev) {
	    var key = me.getKeyCode(ev);
	    switch (key) {
	        case ENTER:
	        case ESC:
	        case UP_ARROW:
	        case DOWN_ARROW:
	            return;
	        default:
	            me.displayResult();
	            
	    }
	};

	this.useSuggestion = function()
	{
		if (this.highlighted > -1)
		{		
		    var lis = me.div.getElementsByTagName('A');	
			for (i = 0 ; i < lis.length ; i++)
			{
			    if(me.highlighted == i)
			    {
			        this.elem.value = lis[i].innerHTML;			        
			        //$fn(_endsWith("selectedDestId")).value = lis[i].id;			        
			        break;
			    }				
			}
			this.hideDiv();
			setTimeout("$fn('" + this.elem.id + "').focus()",0);
			//showDropDowns();
		}
    };

    this.displayResult = function() {
        me.inputText = this.value;
        me.getEligible();
        me.createDiv();
        me.positionDiv();
        me.showDiv();
        ulList = $fn(autosuggest).firstChild;
        //set the autosuggest box height to enable scrolling
        if (ulList.offsetHeight <= MAXHEIGHT && ulList.offsetHeight >= 15) {
            ulList.style.height = MAXHEIGHT + 15 + "px";
        }
        else if (ulList.offsetHeight > MAXHEIGHT) {
            ulList.style.height = MAXHEIGHT + 15 + "px";
        }
    }

	this.showDiv = function()
	{			
		this.div.style.display = 'block';
		//IF not windows safari 3.0.4 version, change the marginTop
		if (!saf30)
		{
			this.div.style.marginTop = '3px';
		}
		ajax_options_rollOverActiveItem(ajax_list_FirstItem,true);
		ajax_list_FirstItem.className='';
	};

	this.hideDiv = function()
	{
		this.div.style.display = 'none';
		this.highlighted = -1;
	};

	this.changeHighlight = function()
	{
		var lis = this.div.getElementsByTagName('LI');
		for (i=0;i<lis.length;i++){
				var li = lis[i];	
				if (this.highlighted == i)
				{					
					li.className = "selected";				
				}
				else
				{
					li.className = "";					
				}			
		}
	};

	this.positionDiv = function()
	{
		var el = this.elem;
		var x = 0;
		var y = el.offsetHeight;
		
		while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
		{
			x += el.offsetLeft;
			y += el.offsetTop;
			el = el.offsetParent;
		}

		x += el.offsetLeft;
		y += el.offsetTop;
		
	};

	this.createDiv = function()
	{	
	    var destinationID;
	    var destinationName;
	    var arrayDestinations;
		var ul = document.createElement('ul');
		
		ajax_list_FirstItem = false;
		//loop thru destinations
		if (this.eligible)
		{		
			for (i=0; i < this.eligible.length; i++)
			{
				if(i != "swap")
				{					    
				    destinationID = this.eligible[i][0].split("#$:~")[0];
				    destinationName = this.eligible[i][0].split("#$:~")[1];
					//add city name
					var li = document.createElement('li');				
					li.innerHTML='<a id="CITY:' + destinationID + '" class="oddhotellink">'+ destinationName + '</a>';
					if(!ajax_list_FirstItem)ajax_list_FirstItem = li;
					ul.appendChild(li);
					
					//add hotel names
					if (this.eligible[i][1])
					{
						for(j=0; j<this.eligible[i][1].length; j++)
						{   
						    destinationID = this.eligible[i][1][j].split("#$:~")[0];
					        destinationName = this.eligible[i][1][j].split("#$:~")[1];
					        
						    var li = document.createElement('li');
							li.innerHTML='<a class="hotellink" id="HOTEL:' + destinationID + '" href=' + destinationID + '>'+ destinationName +'</a>';					
							ul.appendChild(li);						
						}
					}			
				}
			}		   
		}
	
		this.div.replaceChild(ul,this.div.childNodes[0]);				
		ul.onmouseover = function(ev)
		{
			var target = me.getEventSource(ev);
			
			while (target.parentNode && target.tagName.toUpperCase() != 'LI')
			{
				target = target.parentNode;
			}
		
			var lis = me.div.getElementsByTagName('LI');
	
			for (i=0;i<lis.length;i++)
			{
				var li = lis[i];
				if(li == target)
				{
					me.highlighted = i;
					break;
				}
			}
			me.changeHighlight();
		};

		this.div.className="suggestion_list";	
	};

	this.getEligible = function()
	{	
		this.eligible = FindDestinationByName(this.elem.value);
	};

	this.getKeyCode = function(ev)
	{
		if(ev)
		{
			return ev.keyCode;
		}
		if(window.event)
		{
			return window.event.keyCode;
		}
	};

	this.getEventSource = function(ev)
	{
		if(ev)
		{
			return ev.target;
		}
	
		if(window.event)
		{
			return window.event.srcElement;
		}
	};

	this.cancelEvent = function(ev)
	{
		if (!ev) var ev = window.event;	    
	    if (ev.preventDefault) ev.preventDefault();
	    if (ev.stopPropagation) ev.stopPropagation();
	    ev.returnValue = false;	    
	    ev.cancelBubble = true;		
	};
}

// Rica
function ajax_options_rollOverActiveItem(item, fromKeyBoard)
{
	if(ajax_list_activeItem) ajax_list_activeItem.className = '';
	item.className='selected';
	ajax_list_activeItem = item;
	
	if(fromKeyBoard){
		if(ajax_list_activeItem.offsetTop>ulList.offsetHeight){
				ulList.scrollTop = eval(ajax_list_activeItem.offsetTop - ulList.offsetHeight + ajax_list_activeItem.offsetHeight + 5);
				if( saf && !isSafari3 ) {
					ulList.scrollTop = ulList.scrollTop + 10;
				}
		}
		if(ajax_list_activeItem.offsetTop<ulList.scrollTop) { ulList.scrollTop = 0; }
	}	
}

// Rica - Close autoSuggest element when user click on the page.
function closeAutoSuggest(event) 
{					
	var eveSource;		
	if (event) { eveSource = event.target.id; }	
	if (window.event) { eveSource   = window.event.srcElement.id; }
	if ((eveSource!=autosuggest)){ $fn(autosuggest).style.display = "none"; }
	$fn("inpHotelSearch").value = "";
}	


// Rica - Browser checks
var ns4	= (document.layers) ? 1 : 0; // Netscape 4
var op 	= (window.opera) ? 1 : 0; // Opera
var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1) ||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1) ||(navigator.userAgent.indexOf("Opera/6")!=-1);
var op7 = (navigator.userAgent.match(new RegExp("[\w\s ]*Opera.7[\w\s ]*"))) ? 1 : 0; // Opera 7
var op8 = (navigator.userAgent.match(new RegExp("[\w\s ]*Opera.8[\w\s ]*"))) ? 1 : 0; // Opera 8
var ie 	= (document.all && !op) ? 1 : 0; // MS Internet Explorer
var ie50 = (ie && !document.createEventObject) ? 1 : 0; // MS Internet Explorer 5.0
var moz = (document.getElementById && !ie) ? 1 : 0; // Mozilla/Gecko Browser
var saf = (navigator.userAgent.lastIndexOf("Safari") > 0);
var saf30 = (navigator.userAgent.lastIndexOf("Safari/523.15") > 0);
var osx = (navigator.userAgent.lastIndexOf("OS X") > 0);
var agt	=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var mac_ie = mac && ie;	
// Detect IE5.5+
var version=0;
if (navigator.appVersion.indexOf("MSIE")!=-1){
	temp=navigator.appVersion.split("MSIE");
	version=parseFloat(temp[1]);
}
var ie7 = (version == 7)? 1 : 0;
var ie6 = (version == 6)? 1 : 0;
var ie55 = (version == 5.5)? 1 : 0;
var isSafari3 = false;
if(window.devicePixelRatio) isSafari3 = true;

