
//global variables

var searchJSON; //Json object which holds the location data for the search form.


function getSelectedVal(selectObj)
{

	//alert('1');
	//alert(selectObj.val());
	//return 1;//selectObj.attr('value');
	var selVals;
	selVals = selectObj.selectedValues();
	return selVals[0];
}

function getTopSelectedCountry()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-top-country"));
}

function getTopSelectedLocation()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-top-location"));
}

function getTopSelectedSubLocation()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-top-sublocation"));
}


function getBottomSelectedCountry()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-bottom-country"));
}

function getBottomSelectedLocation()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-bottom-location"));
}

function getBottomSelectedSubLocation()
{
	var selVals;
	return getSelectedVal(jQuery("#search-form-bottom-sublocation"));
}

/*****************************************
Fills the sport select with values.
****************************************/
function fillSportSelect(selectID)
{
	var sportJSON;
	var sportSelect;
	

	sportSelect = jQuery(selectID);
	//Clear country select
	sportSelect.empty();
	

	for(var i=0; i < searchJSON.sports.length; i++)
	{
		sportJSON = searchJSON.sports[i];
		//countrySelect.addOption(countryJSON.id, countryJSON.name)
		sportSelect.append('<option value="' + sportJSON.id + '">' + sportJSON.name + '</option>")');
	}
	return;
}


/*****************************************
Fills the country select with values.
****************************************/
function fillCountrySelect(selectID)
{
	var countryJSON;
	var countrySelect;
	

	countrySelect = jQuery(selectID);
	//Clear country select
	countrySelect.empty();
	

	for(var i=0; i < searchJSON.countries.length; i++)
	{
		countryJSON = searchJSON.countries[i];
		//countrySelect.addOption(countryJSON.id, countryJSON.name)
		countrySelect.append('<option value="' + countryJSON.id + '">' + countryJSON.name + '</option>")');
	}
	return;
}


/*****************************************
Called when a new country has been selected.
Updates the location select with locations in the selected country.
****************************************/
function updateTopLocationSelect(countryID)
{
	var countryJSON;
	var locationJSON;
	var locationSelect;

	locationSelect = jQuery("#search-form-top-location");

	countryJSON = findCountryJSON(countryID);
	if (countryJSON == null)
	{
		alert("UpTopLoc Error country not found: " + countryID);
		return
	}

	//Clear locations select
	locationSelect.empty();
	

	//Add new options into select	
	for(var i=0; i < countryJSON.locations.length; i++)
	{
		//Create and add option
		locationJSON = countryJSON.locations[i];
		//locationSelect.addOption(locationJSON.id, locationJSON.name)
		locationSelect.append('<option value="' + locationJSON.id + '">' + locationJSON.name + '</option>")');
	}

	if (countryJSON.locations.length > 0)
	{
		locationSelect.selectOptions(countryJSON.locations[0].id, true);
	}

	updateStyledSelect("#search-form-top .search-location-wrapper");

}

/*****************************************
Called when a new Location has been selected.
Updates the subLocation select with sublocations in the selected location.
****************************************/
function updateTopSubLocationSelect(countryID, locationID)
{
	var countryJSON;
	var locationJSON;
	var subLocationJSON;
	var subLocationSelect;

	countryJSON = findCountryJSON(countryID);
	if (countryJSON == null)
	{
		alert("UpTopSubLoc Error country not found: " + countryID);
		return
	}

	locationJSON = findLocationJSON(countryJSON, locationID);
	if (locationJSON == null)
	{
		alert("Error location not found.");
		return
	}

	subLocationSelect = jQuery("#search-form-top-sublocation");

	//Clear sublocations select
	subLocationSelect.empty();
	
	//Add new options into select	
	for(var i=0; i < locationJSON.sublocations.length; i++)
	{
		//Create and add option
		subLocationJSON = locationJSON.sublocations[i];
		//alert(subLocationJSON.id + " " + subLocationJSON.name);
		//subLocationSelect.addOption(subLocationJSON.id + '', subLocationJSON.name)
		subLocationSelect.append('<option value="' + subLocationJSON.id + '">' + subLocationJSON.name + '</option>")');
	}

	if (locationJSON.sublocations.length > 0)
	{
		subLocationSelect.selectOptions(locationJSON.sublocations[0].id, true);
	}

	updateStyledSelect("#search-form-top .search-sublocation-wrapper");

}


/*****************************************
Called when a new country has been selected.
Updates the location select with locations in the selected country.
****************************************/
function updateBottomLocationSelect(countryID)
{
	var countryJSON;
	var locationJSON;
	var locationSelect;

	locationSelect = jQuery("#search-form-bottom-location");

	countryJSON = findCountryJSON(countryID);
	if (countryJSON == null)
	{
		alert("UpBotLoc Error country not found: " + countryID);
		return
	}

	//Clear locations select
	locationSelect.empty();
	

	//Add new options into select	
	for(var i=0; i < countryJSON.locations.length; i++)
	{
		//Create and add option
		locationJSON = countryJSON.locations[i];
		//locationSelect.addOption(locationJSON.id, locationJSON.name)
		locationSelect.append('<option value="' + locationJSON.id + '">' + locationJSON.name + '</option>")');
	}

	if (countryJSON.locations.length > 0)
	{
		locationSelect.selectOptions(countryJSON.locations[0].id, true);
	}

	updateStyledSelect("#search-form-bottom .search-location-wrapper");

}

/*****************************************
Called when a new Location has been selected.
Updates the subLocation select with sublocations in the selected location.
****************************************/
function updateBottomSubLocationSelect(countryID, locationID)
{
	var countryJSON;
	var locationJSON;
	var subLocationJSON;
	var subLocationSelect;

	countryJSON = findCountryJSON(countryID);
	if (countryJSON == null)
	{
		alert("upBotSubLoc Error country not found: " + countryID);
		return
	}

	locationJSON = findLocationJSON(countryJSON, locationID);
	if (locationJSON == null)
	{
		alert("Error location not found.");
		return
	}

	subLocationSelect = jQuery("#search-form-bottom-sublocation");

	//Clear sublocations select
	subLocationSelect.empty();
	

	//Add new options into select	
	for(var i=0; i < locationJSON.sublocations.length; i++)
	{
		//Create and add option
		subLocationJSON = locationJSON.sublocations[i];
		//alert(subLocationJSON.id + " " + subLocationJSON.name);
		//subLocationSelect.addOption(subLocationJSON.id + '', subLocationJSON.name)
		subLocationSelect.append('<option value="' + subLocationJSON.id + '">' + subLocationJSON.name + '</option>")');
	}

	if (locationJSON.sublocations.length > 0)
	{
		subLocationSelect.selectOptions(locationJSON.sublocations[0].id, true);
	}

	updateStyledSelect("#search-form-bottom .search-sublocation-wrapper");
}



/**
* Find JSON object referring to a Country.
* Params:
* 	countryID - The ID of the country to be returned
*
* 	Returns null on failure.
**/
function findCountryJSON(countryID)
{
	var country;

	for(var i=0; i < searchJSON.countries.length; i++)
	{
		country = searchJSON.countries[i];
		if (country.id == countryID)
		{
			return country;
		}
	}
	return null;
}

/**
* Find JSON object referring to a Location.
* Params:
* 	country - The JSON object of the country containin the location
* 	locationID - The ID of the location to be returned
*
* 	Returns null on failure.
**/
function findLocationJSON(country, locationID)
{
	var location;

	for(var i=0; i < country.locations.length; i++)
	{
		location = country.locations[i];
		if (location.id == locationID)
		{
			return location;
		}
	}
	return null;
}

/*
function pause(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
 }
*/


/* Pause and display a modal dialog if the browser is ie6. Needed to fix javascript bug with select box initialisation.
*/
function pause(numberMillis) {
	jQuery.each(jQuery.browser, function(i, val)
	{
  		if(i=="msie" && jQuery.browser.version.substr(0,1)=="6")
		{
			ie6pause(numberMillis);
		}
	});
}


function ie6pause(numberMillis) {

    var dialogScript = 
        'window.setTimeout(' +
        ' function () { window.close(); }, ' + numberMillis + ');';
     var result = 
// For IE5.
         window.showModalDialog(
           'javascript:document.writeln(' +
            '"<script>' + dialogScript + '<' + '/script>")');
}





/**
* Add jquery onchange events to search form selects to update the dependent selects
**/
function setupSearchLocations()
{
	//Add jquery handlers to update selects
	jQuery("#search-form-top-country").change(function()
	{
		updateTopLocationSelect(getTopSelectedCountry());
	});	

	jQuery("#search-form-top-location").change(function()
	{
		updateTopSubLocationSelect(getTopSelectedCountry(), getTopSelectedLocation());
	});	

	jQuery("#search-form-bottom-country").change(function()
	{
		updateBottomLocationSelect(getBottomSelectedCountry());
	});	

	jQuery("#search-form-bottom-location").change(function()
	{
		updateBottomSubLocationSelect(getBottomSelectedCountry(), getBottomSelectedLocation());
	});	

	//Load location data.	
	//
	jQuery.getJSON("loadlocations.php?useall=true", function(json)
	{
		var countryID;
		var locationID;
		searchJSON = json;

		fillSportSelect("#search-form-top-sport");
		fillSportSelect("#search-form-bottom-sport");
		fillCountrySelect("#search-form-top-country");
		fillCountrySelect("#search-form-bottom-country");
		jQuery("#search-form-top-keywords").val(searchKeywords);	
		pause(10);
		jQuery("#search-form-top-sport").selectOptions(searchSport + "", true);	
		jQuery("#search-form-top-country").selectOptions(searchCountry + "", true);	
		pause(10);
		updateTopLocationSelect(getTopSelectedCountry());
		pause(10);
		jQuery("#search-form-top-location").selectOptions(searchLocation + "", true);	
		pause(10);
		updateTopSubLocationSelect(getTopSelectedCountry(), getTopSelectedLocation());
		pause(10);
		jQuery("#search-form-top-sublocation").selectOptions(searchSubLocation + "", true);	

		if (jQuery("#search-form-bottom-country").length > 0)
		{

			jQuery("#search-form-bottom-keywords").val(searchKeywords);	
			jQuery("#search-form-bottom-sport").selectOptions(searchSport + "", true);	
			jQuery("#search-form-bottom-country").selectOptions(searchCountry + "", true);	
			updateBottomLocationSelect(getBottomSelectedCountry());
			jQuery("#search-form-bottom-location").selectOptions(searchLocation + "", true);	
			updateBottomSubLocationSelect(getBottomSelectedCountry(), getBottomSelectedLocation());
			jQuery("#search-form-bottom-sublocation").selectOptions(searchSubLocation + "", true);	
		}


	styleSearchBoxes();
	});
}


function focusInput(input)
{
       	if (input.val() == input.attr("myDefaultValue"))
	{
		input.val('');
		input.removeClass('default-text');
	}
}

function blurInput(input)
{
	if (input.val() == '')
	{
		if (input.attr("myDefaultValue"))
		{
			input.addClass('default-text');
			input.val(input.attr("myDefaultValue"));
		}
	}
}

function setupInput(input)
{
	if (input.attr("myDefaultValue"))
	{
		input.addClass('default-text');
		//input.val(input.attr("defaultValue"));
	}
}

function styleSearchBoxes()
{
	jQuery(".styled-select select").sSelect()
}

function updateStyledSelect(query)
{
	if (jQuery(query).children("div").length > 0)
	{
		jQuery(query + " div").remove();
		jQuery(query + " select").unbind();
		jQuery(query + " select").sSelect();
		jQuery(query + " select").show().hide();
	}
}



$(document).ready(function()
{
/*
This example script does the greyed out search box trick. Note that it also resets the text on reload in this version. Get rid of setupInput() and add the class manually to change this behaviour.

Uses jquery.

*/
	setupSearchLocations();

	$('.search-keywords').focus(function()
	{
		focusInput($(this));
	});
	$('.search-keywords').blur(function()
	{
		blurInput($(this));
	});


	//Select inputs to have default text.
	$('.search-keywords').each(function()
	{
		$(this).attr("myDefaultValue", "Enter Keywords Here");
		setupInput($(this));
	});

});

