/* Region and location select list behaviours
   Author:		Andrew Hedges, andrew@bookabach.co.nz
   Date:		29/08/08
   Requires:	jquery.js, bookabach.js
*/

if ('undefined' === typeof BOOKABACH) {
	BOOKABACH = {};
}

/*

mapID of first option should be RegionmapID

_cache = {
	"9" : {                     // RegionmapID
		"142" : "National Park" // mapID : Location Name
	}
};

*/

BOOKABACH.regionsAndLocations = (function () {
	// private members
	var
		// values
		_cache,
		_tmpls,
		// functions
		_buildLocationsSelect
	;
	
	_tmpls = {
		option : ['<option value="', 0, '"', 0, '>', 0, '</option>']
	};
	
	_buildLocationsSelect = function (value, selectedId) {
		var locations, options;
		
		selectedId = +selectedId || -1;
		
		if ('undefined' === typeof _cache[value]) {
			// this could be "Any region" or it could be an error state we should handle gracefully
			locations = {};
		} else {
			locations = _cache[value];
		}
		
		// set default option
		_tmpls.option[1] = value;
		_tmpls.option[3] = '';
		_tmpls.option[5] = 'Any location';
		options          = _tmpls.option.join('');
		
		$.each(locations, function (idx, val) {
			_tmpls.option[1]  = idx;
			_tmpls.option[3]  = +idx === selectedId ? ' selected="selected"' : '';
			_tmpls.option[5]  = val;
			options          += _tmpls.option.join('');
		});
		
		$('select[name=locationID]').html(options);
	};
	
	// public members
	return {
		init: function (data, regionId, locationId) {
			var regionValue, selectedIndex;
			
			_cache = data;
			
			// set the region, if we have one
			if ('undefined' === typeof regionId) {
				regionValue   = $('select[name=mapID]').val();
				selectedIndex = 0;
				$.each($('select[name=mapID]')[0].options, function (idx, val) {
					if (regionId === regionValue) {
						selectedIndex = idx;
						return false;
					}
				});
				$('select[name=mapID]')[0].selectedIndex = selectedIndex;
			}
			
			// build initial state of the locations select list
			_buildLocationsSelect($('select[name=mapID]').val(), locationId);
			
			// attach behaviours to regions select list
			$('select[name=mapID]').change(function () {
				_buildLocationsSelect($(this).val(), 0);
			});
			
			// attach behaviours to the form submit
			$('form[name=searchBoxJump]').submit(function () {
				var mapIdSelect;
				mapIdSelect = $('select[name=mapID]')[0];
				mapIdSelect.options[mapIdSelect.selectedIndex].value = $('select[name=locationID]').val();
				return true;
			});
		}
	};
})();
