var $ = function(id){
	return document.getElementById(id);
	};

//Needed for post-animation transparency setting by timeout
var transpFunc = function(id){
	$(id+"_li").style.backgroundColor = 'transparent';
	};

/**
 * PangeaSelector class
 * NB: Depends on YUI Dom collection code
 * Stores a user's selection on the Pangea search page, and handles
 * rendering of the page to represent that.
 * Should be called as a singleton without being instantiated.
 */
var PangeaSelector = function(){
	var hotelChoices=[],areaChoices=[],countryChoices=[],regionChoices=[],
		cityChoices=[],useMaps=false,locked = false;
	/**
	 * Add a hotel to the form, if not there already:
	 * Returns 1 if hotel added, 0 if not
	 */
	var addHotelToForm = function(hotelId){
		inputId = hotelId+"_hidden";
		existingInput = $(inputId);
		if(existingInput == null){
			hotelInput = document.createElement("input");
			hotelInput.type="hidden";
			hotelInput.name="ctyhocn:list";
			hotelInput.value=hotelId;
			hotelInput.id=inputId;
			$('hotelInputDiv').appendChild(hotelInput);
			return 1;
			}
		return 0;
		};

	/**
	 * Get every hotel for the given city and add it to the form
	 * Returns the number of hotels added for counting purposes
	 */
	var addHotelsForCityToForm = function(cityId){
		hotels = city2Hotel[cityId];
		var hotelsAdded = 0;
		for(var i=0; i < hotels.length; i++)
			hotelsAdded += addHotelToForm(hotels[i]);

		return hotelsAdded;
		}

	/**
	 * Get every hotel for the given region and add it to the form:
	 *
	 */
	var addHotelsForRegionToForm = function(regionId){
		var hotelsAdded = 0;
		var cities = region2City[regionId];
		for(var i=0; i < cities.length; i++)
			hotelsAdded += addHotelsForCityToForm(cities[i]);
		return hotelsAdded;
		}

	/**
	 * Get every hotel for the given world area and add it to the form:
	 */
	var addHotelsForAreaToForm = function(areaId){
		var hotelsAdded = 0;
		countries = area2Country[areaId];
		for(var i=0; i < countries.length; i++)
			hotelsAdded += addHotelsForCountryToForm(countries[i]);
		return hotelsAdded;
		}

	/**
	 * Get every hotel for the given country and add it to the form:
	 */
	var addHotelsForCountryToForm = function(countryId){
		hotelsAdded = 0;
		cities = country2City[countryId];
		for(var i=0; i < cities.length; i++)
			hotelsAdded += addHotelsForCityToForm(cities[i]);
		return hotelsAdded;
		}

	/**
	 * Creates a table for holding choices.
	 * @param title - the title to use for the table (Cities, Hotels, etc)
	 * @returns a well formed TABLE element
	 * Note: Only creates the table and header, not the body. That is left to
	 * the caller.
	 */
	var createChoicesTable = function(title){
		var newChoiceList = document.createElement("table");
		newChoiceList.cellspacing="0";
		newChoiceList.cellpadding="0";
		newChoiceList.border="0";
		newChoiceList.className = "resultsTable";
		//newChoiceList.style.marginLeft = "15px";

		var firstCol = document.createElement("col");
		firstCol.width = "60%";
		newChoiceList.appendChild(firstCol);
		var secondCol = document.createElement("col");
		secondCol.width = "30%";
		newChoiceList.appendChild(secondCol);
		var thirdCol = document.createElement("col");
		thirdCol.width = "10%";
		newChoiceList.appendChild(thirdCol);

		var choiceListHeader = document.createElement("thead");
		var choiceListHeaderRow = document.createElement("tr");
		var choiceListHeaderCellPadding = document.createElement("th");
		choiceListHeaderCellPadding.style.width="5%";
		var choiceListHeaderCell = document.createElement("th");
		choiceListHeaderCell.style.width="60%";
		var choiceListHeaderCell2 = document.createElement("th");
		choiceListHeaderCell2.style.width="10%";
		choiceListHeaderCell2.style.textAlign="right";
		choiceListHeaderCell2.style.whiteSpace='nowrap';
		choiceListHeaderCell.innerHTML = title;
		var tt,choiceListHeaderCell3 = document.createElement("th");
		choiceListHeaderCell3.style.width="30%";
		if(site!='jp'){
			tt="HOTELS";
			choiceListHeaderCell3.innerHTML = trForJs['ACTIONS'];
			}
		else{
			tt="HOTELS_SELECTED";
			//choiceListHeaderCell3.innerHTML = trForJs['ACTIONS'];
			}
		if(title!=trForJs[tt]) choiceListHeaderCell2.innerHTML = trForJs[tt];
		choiceListHeaderRow.appendChild(choiceListHeaderCell);
		choiceListHeaderRow.appendChild(choiceListHeaderCell3);
		//choiceListHeaderRow.appendChild(choiceListHeaderCellPadding);
		choiceListHeaderRow.appendChild(choiceListHeaderCell2);
		choiceListHeader.appendChild(choiceListHeaderRow);
		newChoiceList.appendChild(choiceListHeader);
		return newChoiceList;
		};

	/**
	 * Method to create a selection entry (li node) for use in the selection
	 * bar.
	 */
	var createSelectionEntry = function(dataEntry, hotelCount){
		//hotelEntry = document.createElement("li");
		var hotelEntry = document.createElement("tr");
		hotelEntry.id=dataEntry[1]+"_li";
		hotelEntry.style.backgroundColor="transparent";

		var selLabel = document.createElement("td");
		var selLabelText = document.createTextNode(dataEntry[0]);
		selLabel.appendChild(selLabelText);

		var selRmvTd = document.createElement("td");
		//selRmvTd.setAttribute("class", "tdRemovalIcon");
		selRmvTd.setAttribute("nowrap", "nowrap");
		var removeLink = document.createElement("a");
		removeLink.setAttribute("class", "removalIconLink");
		//var removeImage = document.createElement("img");
		//removeImage.src="/media/pangea/images/removeFromCompare.gif";
		//removeImage.setAttribute("class", "compareIcons");
		//removeImage.alt="remove";
		//removeLink.appendChild(removeImage);
		removeLink.href="javascript:PangeaSelector.removeChoice(\""+dataEntry[1]+"\",\""+dataEntry[2] +"\");";
		removeLink.innerHTML = trForJs.MAP_REMOVE;
		selRmvTd.appendChild(removeLink);

	if(PangeaSelector.useMaps && dataEntry[2] == trForJs['CITY']){
		//var selMapTd = document.createElement("td");
		var mapLink = document.createElement("a");
		mapLink.href="javascript:PangeaMap.show('City', '" + dataEntry[1] + "')";
		var mapLinkText = document.createTextNode(trForJs.SHOW_ON_MAP);
		mapLink.appendChild(mapLinkText);
		selRmvTd.appendChild(document.createTextNode(' - '));
		selRmvTd.appendChild(mapLink);
		}

	if(PangeaSelector.useMaps && dataEntry[2] == trForJs['HOTEL']){
		//var selMapTd = document.createElement("td");
		var mapLink = document.createElement("a");
		mapLink.href="javascript:PangeaMap.show('Hotel', '" + dataEntry[1] + "')";
		var mapLinkText = document.createTextNode(trForJs.SHOW_ON_MAP);
		mapLink.appendChild(mapLinkText);
		selRmvTd.appendChild(document.createTextNode(' - '));
		selRmvTd.appendChild(mapLink);
		}

		var countDiv = document.createElement("td");
		if(dataEntry[2] == 'Hotel'){
			countDiv.innerHTML = 1
			}
		else {
			countDiv.innerHTML = hotelCount!=undefined?''+hotelCount:'';
			}
		countDiv.style.textAlign="right";

		hotelEntry.appendChild(selLabel);
		hotelEntry.appendChild(selRmvTd);
		hotelEntry.appendChild(countDiv);
		return hotelEntry;
		};

	/**
	* Method to calculate and render the hotel and page counts
	* @param hotelCount A count of the number of hotels added to the form
	*/
	var renderCounts = function(hotelCount, guideCount){
		//Compute counts (naively for now):
		if (!$("hotelCount")) return;
		var pagesPerHotel = 1;
		var pageCount;
		if(hotelCount == 0) pageCount =0;
		else {
			if($("layoutSummary").checked){pagesPerHotel = 0.25;}
			if($("layoutQuickref").checked){pagesPerHotel = 1;}
			if($("layoutFull").checked){pagesPerHotel = 2.5;}

			//Add in guides (avg 3 pages each), hotels (* factor) and 1 page for
			//contents
			pageCount = Math.ceil(hotelCount * pagesPerHotel) + guideCount * 3 + 1;
			}
		//Render hotel count:
		$("hotelCount").innerHTML = hotelCount;

		//Render page count:
		$("pageCount").innerHTML = pageCount;
		};

	/**
	 * The master rendering method.
	 * Calling this method updates the page state to reflect the current
	 * selection, as stored by PangeaSelector
	 */
	var renderSelf = function(){
		locked = true;
		tid = setTimeout('PangeaSelector._clearLock()',1000);
		//Clear the hotel Input Div:
		var hotelInputDiv = document.createElement("div");
		hotelInputDiv.id="hotelInputDiv";
		$('searchForm').replaceChild(hotelInputDiv, $('hotelInputDiv'));

		//Create a new choices list for the "Your selection" panel:
		var newChoicesDiv = document.createElement("div");
		newChoicesDiv.id="choicesDiv";

		var hotelCount = 0;
		var guideCount = 0;

		//Areas:
		var areasSelected=[];
		if(areaChoices.length>0){
			var newChoiceList = createChoicesTable(trForJs['WORLD_AREAS']);
			var choiceListBody = document.createElement("tbody");

			//Render areas:
			for(var i=0; i<areaChoices.length; i++){
				var thisChoiceCount = addHotelsForAreaToForm(areaChoices[i][1]);
				var areaEntry = createSelectionEntry(areaChoices[i], thisChoiceCount);
				choiceListBody.appendChild(areaEntry);
				hotelCount += thisChoiceCount;
				areasSelected[areasSelected.length] = areaChoices[i][1];
				}
			newChoiceList.appendChild(choiceListBody);
			newChoicesDiv.appendChild(newChoiceList);

			}//areas
		$("areasSelected").value = areasSelected.join(',');

		//Countries:
		var countriesSelected=[]; //Variable to use to store the city choice state
		if( countryChoices.length>0){
			var newChoiceList = createChoicesTable(trForJs["COUNTRIES"]);
			var choiceListBody = document.createElement("tbody");

			//Render countries:
			for(var i=0; i<countryChoices.length; i++){
				var thisChoiceCount = addHotelsForCountryToForm(countryChoices[i][1]);
				var countryEntry = createSelectionEntry(countryChoices[i], thisChoiceCount);
				choiceListBody.appendChild(countryEntry);
				hotelCount += thisChoiceCount;
				countriesSelected[countriesSelected.length]=countryChoices[i][1];
				}
			newChoiceList.appendChild(choiceListBody);
			newChoicesDiv.appendChild(newChoiceList);
			}//countries
		$("countriesSelected").value = countriesSelected.join(',');

		//Regions:
		var regionsSelected=[];
		if(regionChoices.length>0){
			var newChoiceList = createChoicesTable(trForJs["REGIONS"]);
			var choiceListBody = document.createElement("tbody");
			//Render regions:
			for(var i=0; i<regionChoices.length; i++){
				var thisChoiceCount = addHotelsForRegionToForm(regionChoices[i][1]);
				var regionEntry = createSelectionEntry(regionChoices[i], thisChoiceCount);
				choiceListBody.appendChild(regionEntry);
				hotelCount += thisChoiceCount;
				regionsSelected[regionsSelected.length] = regionChoices[i][1];
				}
			newChoiceList.appendChild(choiceListBody);
			newChoicesDiv.appendChild(newChoiceList);
			}//regions
		$("regionsSelected").value = regionsSelected.join(',');

		//Cities:
		var citiesSelected=[]; //Variable to use to store the city choice state
		var destGuidePara = $('guidePara');
		var guideCitySpan = $('guideCitySpan');
        if(destGuidePara){
            destGuidePara.style.display="none";
            guideCitySpan.innerHTML="";
        	}
		if( cityChoices.length > 0){
			var newChoiceList = createChoicesTable(trForJs["CITIES"]);
			var choiceListBody = document.createElement("tbody");
			//Render cities:
			for(var i=0; i<cityChoices.length; i++){
				var cityId = cityChoices[i][1];
				//Make destination guide checkbox visible and add this city to
				//the list if it has a guide
				if(destGuidePara && citiesWithGuides[cityId] && ((brand=='hi' && $('language').value=='uk') || brand=='hp')){
					destGuidePara.style.display="block";
					if(guideCitySpan.innerHTML != ""){
						guideCitySpan.innerHTML = guideCitySpan.innerHTML.replace(/ and/, ",");
						guideCitySpan.innerHTML = guideCitySpan.innerHTML+ ' and ';
						}
					guideCitySpan.innerHTML = guideCitySpan.innerHTML + cityChoices[i][0];
					if($('guideBox').checked) guideCount++;
					}

				var thisChoiceCount = addHotelsForCityToForm(cityId);
				var cityEntry = createSelectionEntry(cityChoices[i], thisChoiceCount);
				choiceListBody.appendChild(cityEntry);
				hotelCount += thisChoiceCount;
				citiesSelected[citiesSelected.length] = cityId;
				}
			newChoiceList.appendChild(choiceListBody);
			newChoicesDiv.appendChild(newChoiceList);
			}//cities
		$("citiesSelected").value = citiesSelected.join(',');

		//Hotels:
		var hotelsSelected=[]; //Variable to use to store the hotel choice state
		if( hotelChoices.length > 0){
			var newChoiceList = createChoicesTable(trForJs["HOTELS"]);
			var choiceListBody = document.createElement("tbody");

			//Render hotels:
			for(var i=0;i<hotelChoices.length;i++){
				var hotelId = hotelChoices[i][1];
				var thisChoiceCount = addHotelToForm(hotelId);
				var hotelEntry = createSelectionEntry(hotelChoices[i]);
				choiceListBody.appendChild(hotelEntry);
				hotelCount++;
				hotelsSelected[hotelsSelected.length] = hotelId;
				if(destGuidePara && hotelsWithGuides[hotelId] && ((brand=='hi' && $('language').value=='uk') || brand=='hp')){
					destGuidePara.style.display="block";
					if(guideCitySpan.innerHTML != ""){
						guideCitySpan.innerHTML = guideCitySpan.innerHTML.replace(/ and/, ",");
						guideCitySpan.innerHTML = guideCitySpan.innerHTML+ ' and ';
						}
					guideCitySpan.innerHTML = guideCitySpan.innerHTML + cityNames[hotelsWithGuides[hotelId]];
					if($('guideBox').checked) guideCount++;
					}
				}
			newChoiceList.appendChild(choiceListBody);
			newChoicesDiv.appendChild(newChoiceList);
			}//hotels
		$("hotelsSelected").value = hotelsSelected.join(',');


		//Put the new choices lists into the doc
		$("selectionDiv").replaceChild(newChoicesDiv, $("choicesDiv"));

		var sb=$('submitButton'),searchHeading=$('searchHeading');
		//If no choices have been made:
		if(hotelChoices.length+areaChoices.length+countryChoices.length+regionChoices.length+cityChoices.length==0){
			if(sb.tagName=="A"){
				sb.className = "btnGray";
				$('submitText').style.color="gray";
				sb.href = "#";
				}
			else sb.disabled = true;
			if(searchHeading)searchHeading.innerHTML = trForJs['SEARCH_FOR_A_LOCATION'];
			}
		//If some choices have been made:
		else{
			if(sb.tagName=="A"){
				$('submitText').style.color = '#ffffff';
				sb.className = "btn";
				}
			else
				sb.disabled = false;
			if(searchHeading)searchHeading.innerHTML = trForJs['ADD_ANOTHER_LOCATION'];
			sb.href = "javascript:$('searchForm').submit();";
			}

		renderCounts(hotelCount, guideCount);
		locked=false;
		clearTimeout(tid);
		};


	//Public methods from here down:
	return {
		/**
		 * Method to register with the YUI autocompleter, to be called when
		 * a selection is made.
		 * Updates the state of the PangeaSelector to contain the new choice.
		 * Then calls for a re-render.
		 */
		addChoice:function(eventType, autoCompArgs){
			if(locked) return;
			dataEntry = autoCompArgs[2];
			dataEntry[0] = dataEntry[0].replace(/&amp;/, '&');
			id = dataEntry[1];
			switch(dataEntry[2]){
				case trForJs['HOTEL']:
					if(! testIdPresent(id,hotelChoices ))
						hotelChoices.push(dataEntry);
					break;
				case trForJs['WORLD_AREA']:
					if(! testIdPresent(id,areaChoices ))
						areaChoices.push(dataEntry);
					break;
				case trForJs['COUNTRY']:
					if(! testIdPresent(id,countryChoices ))
						countryChoices.push(dataEntry);
					break;
				case trForJs['REGION']:
					if(! testIdPresent(id,regionChoices ))
						regionChoices.push(dataEntry);
					break;
				case trForJs['CITY']:
					if(! testIdPresent(id,cityChoices ))
						cityChoices.push(dataEntry);
					break;
				}
			//Add more code here to do what is needed if a geographical division
			renderSelf();
			var mainEntry=$('mainEntry');
			if(mainEntry){
				//Return focus to autocomplete input:
				mainEntry.value="";
				mainEntry.focus();
				//Flash the new choice on the panel:
				$(id+"_li").style.backgroundColor="#FFFFFF";
				elem = jQuery('#'+id+"_li");
				elem.animate({backgroundColor:'#FFFF00'},100).animate({backgroundColor:'#FFFFFF' },1000);
				//Make it go transparent post-animation:
				setTimeout('transpFunc("'+id+'")', 1150);
				}
			},

		/**
		* Method to remove one choice (hotel, area, country, region or city)  given its id
		*/
		removeChoice:function(id, type){
			if(locked) return;
			switch(type){
				case trForJs['HOTEL']:
					for(var i=0; i<hotelChoices.length; i++)
						if(hotelChoices[i][1] == id)
							hotelChoices.remove(i);
					break;

				case trForJs['CITY']:
					for(var i=0; i<cityChoices.length; i++)
						if(cityChoices[i][1] == id)
							cityChoices.remove(i);
					break;

				case trForJs['REGION']:
					for(var i=0; i<regionChoices.length; i++)
						if(regionChoices[i][1] == id)
							regionChoices.remove(i);
					break;

				case trForJs['COUNTRY']:
					for(var i=0; i<countryChoices.length; i++)
						if(countryChoices[i][1] == id)
							countryChoices.remove(i);
					break;

				case trForJs['WORLD_AREA']:
					for(var i=0; i<areaChoices.length; i++)
						if(areaChoices[i][1] == id)
							areaChoices.remove(i);
					break;
				}
			renderSelf();
			var mainEntry=$('mainEntry');
			if(mainEntry)
				//Return focus to autocomplete input:
				$("mainEntry").focus();
			},

		/**
		* Method to call to force re-rendering.
		* Passes on call to renderSelf()
		*/
		refresh:function(){renderSelf();},

		/**
		* Method to call to restore the state from hidden, browser-cached form
		* variables
		*/
		restoreFromForm:function(){
			//Restore hotels:
			hotelString = $("hotelsSelected").value;
			//Don't bother if it hasn't been set yet:
			if(hotelString !=""){
				hotelsToRestore = hotelString.split(',');
				for(i=0; i<hotelsToRestore.length; i++){
					choice = hotelsToRestore[i];
					newEntry = [hotelsDict[choice].replace(/&amp;/,'&'), choice, 'Hotel'];
					hotelChoices.push(newEntry);
					}
				}

			//Restore cities:
			cityString = $("citiesSelected").value;
			//Don't bother if it hasn't been set yet:
			if(cityString !=""){
				citiesToRestore = cityString.split(',');
				for(i=0; i<citiesToRestore.length; i++){
					choice = citiesToRestore[i];
					newEntry = [cityNames[choice], choice, trForJs['CITY']];
					cityChoices.push(newEntry);
					}
				}

			//Restore regions:
			regionString = $("regionsSelected").value;
			//Don't bother if it hasn't been set yet:
			if(regionString !=""){
				regionsToRestore = regionString.split(',');
				for(var i=0; i<regionsToRestore.length; i++){
					var choice = regionsToRestore[i];
					var newEntry = [regionNames[choice], choice, trForJs['REGION']];
					regionChoices.push(newEntry);
					}
				}

			//Restore countries:
			countryString = $("countriesSelected").value;
			//Don't bother if it hasn't been set yet:
			if(countryString !=""){
				countriesToRestore = countryString.split(',');
				for(i=0; i<countriesToRestore.length; i++){
					choice = countriesToRestore[i];
					newEntry = [countryNames[choice], choice, trForJs['COUNTRY']];
					countryChoices.push(newEntry);
					}
				}

			//Restore world areas:
			areaString = $("areasSelected").value;
			//Don't bother if it hasn't been set yet:
			if(areaString !=""){
				areasToRestore = areaString.split(',');
				for(var i=0; i<areasToRestore.length; i++){
					var choice = areasToRestore[i];
					var newEntry = [areaNames[choice], choice, trForJs['WORLD AREA']];
					areaChoices.push(newEntry);
					}
				}
			renderSelf();
			},
		_clearLock:function(){locked=false;}
		};//End public method dictionary
	}();

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to){
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
	};

/**
 * Function to test if an id is present in an array of choices
 */
testIdPresent = function(id, array){
	for(var i=0; i < array.length; i++){
		if(array[i][1]==id)
			return 1;
		};
	return 0;
	}
