var map = new Object(); //store the map object in memory for faster referencing
var mapInit = false;  //stop the engine from sending flash commands to a incomplete render of the flash app

var isBuying,rentOrBuy;

function selectRegion( regionID ) {
	$j('option','#'+rentOrBuy+'RegionId').each(function(n) {
		if( $j(this).val() == regionID ) {
			$j(this).parent().attr('selectedIndex',n);
		}
	});

	if( isBuying ) {
		refreshAreaBuying(true);
	} else {
		refreshAreaRenting(true);
	}
	updateAreaClickFunctions();
	return void(0);
}

function selectArea( areaID, state ) {
	$j('#area' + areaID, '#'+rentOrBuy+'Area').attr('checked', (state) ? true : false );
	updateSuburbList();
}

function areaExists( areaID ) {
	if(	$j('input[value=' + areaID + ']','#'+rentOrBuy+'Area').length ) {
		return true;
	}
	return false;
}

function regionExists( regionID ) {
	if( $j('option[value=' + regionID + ']','#'+rentOrBuy+'RegionId').length ) {
		return true;
	}
	return false;
}

function updateAreaClickFunctions() {
	$j('input[type=checkbox]','#'+rentOrBuy+'Area').each(function() {
		$j(this)
		.unbind()
		.click( updateSuburbList ) //dsp_area.cfm
		.click(function() {
			if( mapInit ) map.sendFlashTickArea( $j(this).val() );
		})
		.parent()
		.find('a:first')
		.unbind()
		.attr('areaID', $j(this).val() ) //reduce referencing speed in the jscript engine
		.click(function() {
			if( mapInit ) map.sendFlashTickArea( $j(this).attr('areaID') );
		});
	});
}

var readyRepeater = setInterval( checkReady, 1000 );
function checkReady( e ) {
	try {
		$j('div#ufoTest').children(0).get(0).jsReady();
	} catch (e) {
		/* flash not ready */
	}
}

function flashReady( e ) {
	//called from flash
	var data = new Object();
	data.regions = new Array();
	var thisRegion;
	map = $j('div#ufoTest').children(0).get(0); //build the map object
	mapInit = true;
 	isBuying = ( $j('#buyingRegionId').length == 1 ) ? true : false ;
	rentOrBuy = ( isBuying ) ? 'buying' : 'renting' ;
	
	$j('#'+rentOrBuy+'RegionId').change(function() {
		$j('div#ufoTest').children(0).get(0).sendFlashToRegion( $j(this).val() );
	});
	
	clearInterval ( readyRepeater );
	
	/* build map data */
	if( isBuying ) {
		data.areas = regionAreasBuying;
	} else {
		data.areas = regionAreasRenting;
	}
	return data;
}
