var viaCount=0;
//var viaCountDropDown=0;
var processingError=false;
var viaLimit=3; // limited to 4
var errorCol = "#fe8600;";
var ROUTE_CONFIRMED = false;

function populateFields(from, to, confFrom, confTo)
{
	// Determine the database
	var radioGB = document.getElementById("dbGB");
	var radioIreland = document.getElementById("dbIreland");
	var radioEurope = document.getElementById("dbEurope");
	
	if (radioGB.checked)
		setDatabase("B");
	else if (radioIreland.checked)
		setDatabase("I");
	else if (radioEurope.checked)
		setDatabase("E");

	processingError=false; // reset
	//clear all via drop down menus
	clearViaDropDowns();
	// search from and to
	if(searchPlace(from)){populateField(confFrom)};
	if(searchPlace(to)){populateField(confTo)};
	//now process the vias
	for(count=0; count<viaCount; count++)
	{
		var viaName = "via"+count.toString();
		var inputId = document.getElementById("via"+count.toString());
		if(inputId.value.length != 0)
		{
			if(searchPlace(inputId))
			{
				//create a via drop down and populate
				var dropId = document.getElementById(createViaDropDown());
				populateField(dropId);
			}
		}
	}

	showConfirmRoute();
}


function searchPlace(searchField)
{
	getNewValues(searchField.value);

	if(hasError())
	{
		searchField.value=getError();
		setErrorBG(searchField);
		processingError=true;

		return false;
	} else {
		// clear any error colours
		setWhiteBG(searchField);
	}
	//return boolean if search ok
	return true;
}

function populateField(resField)
{
	//only one option now 
	//reset options
	//resField.options.length=0;
	var res = getResults();
	
	if(res.length>0)
	{
		resField.value=res[0][1];
	}
	/*
	for(cnt = 0; cnt < res.length; cnt++)
	{
		var optn = new Option();
		optn.text = res[cnt][0];
		optn.value = res[cnt][1];
		resField.options.add(optn);
	}
	*/
	
}

function showConfirmRoute() {
	if(!processingError)
	{
 		 $('#fragment-1').attr("class","map-tabs-panel map-tabs-hide");
		 $('#fragment-2').attr("class","map-tabs-panel");
		ROUTE_CONFIRMED = true;
	}
}

/** creates a via input box if max vias (viaLimit) has not been reached **/
function createVia()
{
	if(viaCount>viaLimit)
	{
		alert("Sorry, only " + (viaLimit+1) + " via locations allowed.");
		$('div > .via').text('');// remove the 'Add via?' link
		return;
	}
	var message="Please enter a location";
	if(viaCount!=0)
	{
		//check previous via is populated otherwise don't create another
		var prev = document.getElementById("via"+(viaCount-1).toString());
		if(prev.value.length == 0 || prev.value == message)
		{
			prev.value = message;
			setErrorBG(prev);
			return;
		} else {
			// clear the error background colour
			setWhiteBG(prev);
		}
	}
	var viaId="via"+viaCount.toString();
	viaCount++;
	//viaHtmlInput = '<label for=\"'+viaId+'\">Via: <input id=\"'+viaId+'\" type=\"Text\" class=\"routeText\"></label>';

	var label = $('<label>Via: </label>');
	label.attr('for', viaId);

	var input = $('<input type="text" class="routeText">');
	input.attr("id", viaId);
	input.keypress(searchFieldKeypress);

	var c = $("#inputFields");
	var newdiv = $('<div>');

	newdiv.attr("id", "routeVia"+viaCount);

	newdiv.append(label);
	newdiv.append(input);
	c.append(newdiv);
	
	if(viaCount >= viaLimit) {
		$('div > .via').text('');
	}
}

function createViaDropDown()
{
	var dropDownId = "viaChoice"+viaCountDropDown.toString();
	viaCountDropDown++;
	var viaHtmlDropdown = '<label for=\"'+dropDownId+'\">Via: <select id=\"'+dropDownId+'\" class=\"routeText\"></select></label>';
	var c = document.getElementById("dropdownFields");
	var newdiv = document.createElement("div");
	newdiv.setAttribute("id", "viaDropDown"+viaCountDropDown);
	newdiv.innerHTML = viaHtmlDropdown;
	c.appendChild(newdiv);
	return dropDownId;
}

function clearViaDropDowns()
{
	//get parent
	//var p = $("#getRouteDv");
	//remove each child
	for(var inc = 1; inc <= viaCountDropDown; inc++)
	{
		var c = $("#viaDropDown"+inc.toString());
		//p.remove(c);
		c.remove();
	}
	viaCountDropDown=0; // reset
}

function clearViaInputs()
{
	for(var inc = 1; inc <= viaCount; inc++)
	{
		var c = $("#routeVia"+inc.toString());
		//p.remove(c);
		c.remove();
	}
	viaCount=0; // reset
}

function reverseRoute()
{

	//get current start input
	var tmpFromPlace=$("#routeFrom").val();
	//get current end input
	var tmpToPlace=$("#routeTo").val();
	//get current start confirmations
	var tmpFromSelect=$("#confirmFrom").html();
	//get current to confirmations
	var tmpToSelect=$("#confirmTo").html();
	//get selected index from
	var tmpFromSelectedIndex=$("#confirmFrom").attr("selectedIndex");
	//get selected index to
	var tmpToSelectedIndex=$("#confirmTo").attr("selectedIndex");
	
	//get current via inputs
	var arrViaText=new Array();
	var arrViaOptions=new Array();
	var arrViaSelectedIndex=new Array();

	for (var i=0;i<viaCount;i++)
	{
		arrViaText.push($("#via"+i).val());
    		arrViaOptions.push($("#viaChoice" + i).html())
		arrViaSelectedIndex.push($("#viaChoice" + i).attr("selectedIndex"));
	}



	//set start input to end input
	$("#routeFrom").val(tmpToPlace);
	//set end input to start input
	$("#routeTo").val(tmpFromPlace);
	//set start confirmation to end confirmation (all select options?)
	$("#confirmFrom").html(tmpToSelect);	
	//set end confirmation to start cnofirmation (all select options?)
  	$("#confirmTo").html(tmpFromSelect);
	//set via options to reverse via select options

	arrViaText.reverse();
	arrViaOptions.reverse();
	arrViaSelectedIndex.reverse();
	
	//set selected index from
	 $("#confirmFrom option:eq(" + tmpToSelectedIndex + ")").attr("selected","selected");
	//set selected index to
	 $("#confirmTo option:eq(" + tmpFromSelectedIndex + ")").attr("selected","selected");

  for (var i=0;i<viaCount;i++)
	{
  	  $("#via" + i).val(arrViaText[i]);
  	  $("#viaChoice" + i).html(arrViaOptions[i]);
	  var id="#viaChoice" + i + "  option:eq(" + arrViaSelectedIndex[i] + ")";
	  $(id).attr("selected","selected");
 	}

	 
 	 
	 $('#fragment-1').attr("class","map-tabs-panel map-tabs-hide");
	 $('#fragment-2').attr("class","map-tabs-panel");

 	 scrollToID("mapcontainer");
	
    //tidy up
    tmpFromPlace='';
	//get current end input
	tmpToPlace='';
	//get current start confirmations
	tmpFromSelect='';
	//get current to confirmations
	tmpToSelect='';
	//get selected index from
	tmpFromSelectedIndex='';
	//get selected index to
	tmpToSelectedIndex='';
	
	//get current via inputs
	arrViaText='';
	arrViaOptions='';
	arrViaSelectedIndex='';
	
	//resubmit route
 	 getRouteAndDestinationHotelsAndAds();
}


/** Keypress event handler for route search */
function searchFieldKeypress(e) {
	if(e.which == 13) {
		var routeFrom = document.getElementById("routeFrom");
		var routeTo = document.getElementById("routeTo");
		var confirmFrom = document.getElementById("confirmFrom");
		var confirmTo = document.getElementById("confirmTo");		
		populateFields(routeFrom,routeTo,confirmFrom,confirmTo);
		if (!processingError) {
			getRouteAndDestinationHotelsAndAds();
		}
	}
}

function reset() {
	clearViaDropDowns();
	return true;
}

function resetInputFields()
{
		// confirm tab is not already selected, so do our stuff
		
		// Delete the from and to text
		var fromText = document.getElementById("routeFrom");
		var toText = document.getElementById("routeTo");
		setWhiteBG(fromText);
		fromText.value = "";
		setWhiteBG(toText);
		toText.value = "";
		
		// Remove all via inputs
		clearViaInputs();
		
}

function setDatabase(db) {
	database = db;
}

function getDatabase() {
	return database;
}

/** convenience function for setting the background to errorCol on the given widget **/
function setErrorBG(widget) {
	//widget.setAttribute("style", "background-color: " + errorCol);
	widget.style.cssText = "background-color: " + errorCol;
}

/** convenience function for setting the background white on the given widget **/
function setWhiteBG(widget) {
	//widget.setAttribute("style", "background-color: #FFFFFF;");
	widget.style.cssText = "background-color: #FFFFFF;";
}




