var $j = jQuery.noConflict();

var map;
var markers;
var first_time = true;
var starting_bounds = false;
var markers_count = 0;
var active_marker = false;
var replaced_marker = false;
var replaced_marker_found = false;
var quick_html = false;
var move_listener = false;
var no_props_msg = 'Sorry, no properties were found. Please adjust your criteria or zoom out.';
var open_branch = false;
var trans_type = false;

// The icons
var icon_default = new GIcon(); 
icon_default.image = 'http://www.mappr.co.uk/images/icons/house.png';
icon_default.iconSize = new GSize(16, 27);
icon_default.iconAnchor = new GPoint(1, 27);

var icon_sold = new GIcon(); 
icon_sold.image = 'http://www.mappr.co.uk/images/icons/house_sold.png';
icon_sold.iconSize = new GSize(16, 27);
icon_sold.iconAnchor = new GPoint(1, 27);

var icon_multiple = new GIcon(); 
icon_multiple.image = 'http://www.mappr.co.uk/images/icons/house_multi.png';
icon_multiple.iconSize = new GSize(23, 27);
icon_multiple.iconAnchor = new GPoint(1, 27);

var icon_new = new GIcon(); 
icon_new.image = 'http://www.mappr.co.uk/images/icons/house_new.png';
icon_new.iconSize = new GSize(16, 27);
icon_new.iconAnchor = new GPoint(1, 27);

// Special case(s)
var icon_active = new GIcon(); 
icon_active.image = 'http://www.mappr.co.uk/images/icons/active.png';
icon_active.iconSize = new GSize(16, 27);
icon_active.iconAnchor = new GPoint(1, 27);

var icon_school = new GIcon(); 
icon_school.image = 'http://www.mappr.co.uk/images/icons/school.png';
icon_school.iconSize = new GSize(16, 15);
icon_school.iconAnchor = new GPoint(1, 15);
icon_school.infoWindowAnchor = new GPoint(8, 1);

var icon_railway = new GIcon(); 
icon_railway.image = 'http://www.mappr.co.uk/images/icons/railway.png';
icon_railway.iconSize = new GSize(27, 27);
icon_railway.iconAnchor = new GPoint(13, 27);
icon_railway.infoWindowAnchor = new GPoint(8, 1);

var icon_underground = new GIcon(); 
icon_underground.image = 'http://www.mappr.co.uk/images/icons/subway.png';
icon_underground.iconSize = new GSize(27, 27);
icon_underground.iconAnchor = new GPoint(13, 27);
icon_underground.infoWindowAnchor = new GPoint(8, 1);

function mapLoad() {

	if (!GBrowserIsCompatible()){
		alert ('Sorry, your browser is not compatible with the map.');
		return false;
	}
	
	map = new GMap2( $j('#map')[0] );
	//map.setMapType(G_SATELLITE_3D_MAP);
	
	// Is an area selected already? 
	area_key = $j('select#mappr_areas option:selected').val();
	if(area_key && area_key!=0){
		default_view = areas[area_key][0];
		default_zoom = areas[area_key][1];
	}
	
	// ==== It is necessary to make a setCenter call of some description before adding markers ====
	map.setCenter(default_view, default_zoom);

	
	// Set up the (one and only) active marker, but hide it
	active_marker = new GMarker(map.getCenter(), icon_active); 	// Can be anywhere really but centre it 
	GEvent.addListener(active_marker, 'click', function(){		// Clicking will close details
		close_details();
	});
	active_marker.hide();										// Hide it until clicked
		
	if($j('select[name="branch"] option:selected').val()) {
		move();
	}
	else{
		redrawMap(true); // true denotes onload
	}	
	
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());
	

	// ====== Restricting the range of Zoom Levels =====
	// Get the list of map types      
	var mt = map.getMapTypes();
	// Overwrite the getMaximumResolution() method
	for (var i=0; i<mt.length; i++) {
		mt[i].getMinimumResolution = function() {return min_zoom;}		// Prevents zooming out past a level where the whole of the UK is visible
	}
	//==================================================
	
}	


function show_message(msg){
	$j('#mappr_info').hide();
	$j('#mappr_info').html(msg);
	$j('#mappr_info').fadeIn(500);
}

function get_xml(data){
	//console.log(data);
	//alert(data);
	$j('#mappr_info').hide();
	$j('#mappr_loading').show();
	xml = false;
	$j.getJSON('http://' + mappr_domain + '/clients/' + client_name + '/ajax.php?callback=?', data, 'set_xml'); //todo
			
}



function set_xml(xml_in){
	//console.log('set_xml');
	$j('#mappr_loading').hide();
	xml = xml_in;
	do_draw();
}

// Called when the properties need loading or re-loading following drag
function redrawMap(the_first_time){
//	console.log('redraw');
	
	first_time = (the_first_time!=true) ? false : true; // todo - get rid

	replaced_marker_found = false;
	
	var bounds		= map.getBounds();
	var southWest	= bounds.getSouthWest();
	var northEast	= bounds.getNorthEast();
	
	checkBounds(); // Keeps view on UK	
	
	/*********** get search criteria ***********/
	trans_type = $j('input[name=mappr_type]:checked').val();
	
	var data = {
		
		action: 'search',
		southwest_lng: southWest.lng(),
		northeast_lng: northEast.lng(),
		southwest_lat: southWest.lat(),
		northeast_lat: northEast.lat(), 
		type: trans_type
	
	}
	
	// Extract the min/max prices if available
	//alert($j('input[name=mappr_type]:checked').attr('id') );
	if(trans_type==0){
				
		if($j('input[name=mappr_type]:checked').attr('id') == 'sales'){		
			
			if(min_price = $j('select.mappr_min_price option:selected').val()) {
				$j.extend(data, { min_price: min_price });
			}
			
			if(max_price = $j('select.mappr_max_price option:selected').val()) {
				$j.extend(data, { max_price: max_price });
			}
		}
		
		else{
			
			$j.extend(data, { 'new': 1 });			
			
			if(development_id = $j('input#mappr_development_id').val()) {
				$j.extend(data, { development_id: development_id });
			}
			
			if(min_newhomes_price = $j('select.mappr_min_price_newhomes option:selected').val()) {
				$j.extend(data, { min_newhomes_price: min_newhomes_price });
			}
			
			if(max_newhomes_price = $j('select.mappr_max_price_newhomes option:selected').val()) {
				$j.extend(data, { max_newhomes_price: max_newhomes_price });
			}			
			
		}
	
	}
	else if( (trans_type==1) && ($j('input[name=mappr_type]:checked').attr('id')=='studentlets') ) {	// Student lettings
		
		$j.extend(data, { lettings_type: 3 });
		
		if(min_studentlets_price = $j('select.mappr_min_price_studentlets option:selected').val()) {
			$j.extend(data, { min_lettings_price: min_studentlets_price });
		}
		
		if(mas_studentlets_price = $j('select.mappr_max_price_studentlets option:selected').val()) {
			$j.extend(data, { max_lettings_price: max_studentlets_price });
		}
		
	}
	else if(trans_type==1){		// Lettings
	
		if(min_rent_price = $j('select.mappr_min_rent_price option:selected').val()) {
			$j.extend(data, { min_lettings_price: min_rent_price });
		}
		
		if(max_rent_price = $j('select.mappr_max_rent_price option:selected').val()) {
			$j.extend(data, { max_lettings_price: max_rent_price });
		}
	}
	
	
	if(bedrooms = $j('select.mappr_bedrooms option:selected').val()) {
		$j.extend(data, { bedrooms: bedrooms });
	}
	
	if(min_bedrooms = $j('select.mappr_min_bedrooms option:selected').val()) {
		$j.extend(data, { min_bedrooms: min_bedrooms });
	}
	
	if(max_bedrooms = $j('select.mappr_max_bedrooms option:selected').val()) {
		$j.extend(data, { max_bedrooms: max_bedrooms });
	}
			
	/*// Area
	if(starting_bounds){
		if(branch_id = $j('select[name="branch"] option:selected').val()) {
			$j.extend(data, { branch: branch_id });
		}
	}*/
	
	// Keyword
	var keyword = $j('input[name="mappr_keyword"]').val();
	if(keyword && keyword!='Type keywords here') {
		$j.extend(data, { keyword: keyword });
	}
	/***************************************/

	get_xml(data);

}


function toggle_prices(){

	if( $j('input[name=mappr_type]:checked').val() == 0){
		$j('#mappr_lettingsdiv').hide();	
		$j('#mappr_salesdiv').show();	
		return;
	}
	$j('#mappr_lettingsdiv').show();	
	$j('#mappr_salesdiv').hide();

		
}


function toggle_prices_2(show_div){

	switch(show_div){
		
		case 'sales':
			$('#mappr_salesdiv').show();
			$('#mappr_lettingsdiv').hide();
			$('#mappr_studentletsdiv').hide();
		break;
		
		case 'lettings':
			$('#mappr_salesdiv').hide();
			$('#mappr_lettingsdiv').show();
			$('#mappr_studentletsdiv').hide();
			
		break;
		
		case 'studentlets':
			$('#mappr_salesdiv').hide();
			$('#mappr_lettingsdiv').hide();
			$('#mappr_studentletsdiv').show();
		break;
		
	}
	
}

function toggle_prices_3(show_div){
	
	switch(show_div){
		
		case 'sales':
			$('#mappr_salesdiv').show();
			$('#mappr_lettingsdiv').hide();
			$('#mappr_newhomesdiv').hide();
		break;
		
		case 'lettings':
			$('#mappr_salesdiv').hide();
			$('#mappr_lettingsdiv').show();
			$('#mappr_newhomesdiv').hide();
			
		break;
		
		case 'newhomes':
			$('#mappr_salesdiv').hide();
			$('#mappr_lettingsdiv').hide();
			$('#mappr_newhomesdiv').show();
		break;
		
	}
	
}


function autoFill(id, v){
	
	if( ($j(id).val()) && ($j(id).val()!=v) ) return;
	
	$j(id).css({ color: "#666666" }).attr({ value: v }).focus(function(){
		if($j(this).val()==v){
			$j(this).val("").css({ color: "#333333" });
		}
	}).blur(function(){
		if($j(this).val()==""){
			$j(this).css({ color: "#666666" }).val(v);
		}
	});

}

function add_schools(){
	
	if(map.getZoom()<12){
		$j('input[name="mappr_showschools"]').attr('checked', false);
		return false;
	}
	
	var bounds		= map.getBounds();
	var southWest	= bounds.getSouthWest();
	var northEast	= bounds.getNorthEast();
	
	var data = {
		southwest_lng: southWest.lng(),
		northeast_lng: northEast.lng(),
		southwest_lat: southWest.lat(),
		northeast_lat: northEast.lat()
	}
	
	$j('#mappr_info').hide();
	$j('#mappr_loading').show();
	xml = false;
	$j.getJSON('http://' + mappr_domain + '/schools.php?callback=?', data, 'set_schools');
	$j('#mappr_loading').hide();

}

function create_school_marker(point,name,htmls) {
	//alert('html:'+html);
	var marker = new GMarker(point, icon_school);
	
	// Stop the map being reloaded after any movement that may occur to accomodate info window
	
	GEvent.addListener(marker, 'click', function() {
		remove_listeners();
		GEvent.addListener(map, 'moveend', function() {
			add_listeners();
		});
		marker.openInfoWindowHtml(htmls);
	}); 
	
	
	return marker;
}

function show_schools(schools){
	
	//console.log(schools);
	var xml = GXml.parse(schools);
	schools = xml.documentElement.getElementsByTagName('school');	
	//console.log(schools);
	
	for (var i = 0; i < schools.length; i++) {
		
		var school_html = '<p class="mappr_school"><strong>' + schools[i].getAttribute('name') + '<\/strong><br \/>';
		
		if(schools[i].getAttribute('address1')) school_html += schools[i].getAttribute('address1') + '<br \/>';
		if(schools[i].getAttribute('address2')) school_html += schools[i].getAttribute('address2') + '<br \/>';
		if(schools[i].getAttribute('address3')) school_html += schools[i].getAttribute('address3') + '<br \/>';
		if(schools[i].getAttribute('town')) 	school_html += schools[i].getAttribute('town') + '<br \/>';
		if(schools[i].getAttribute('county'))	school_html += schools[i].getAttribute('county') + '<br \/>';
		if(schools[i].getAttribute('postcode'))	school_html += schools[i].getAttribute('postcode') + '<br \/>';
		school_html += '<br \/>'
		if(schools[i].getAttribute('urn'))		school_html += '<a href="http://www.ofsted.gov.uk/oxcare_providers/urn_search?urn='+schools[i].getAttribute('urn')+'&amp;type=2" target="_blank" class="blue">View Ofsted profile<\/a>';
		school_html += '<\/p>';
		
		//console.log(schools[i].getAttribute('name'));
		var point = new GLatLng(parseFloat(schools[i].getAttribute('lat')),	parseFloat(schools[i].getAttribute('lng')));
		var school_marker = create_school_marker(point, schools[i].getAttribute('name'), school_html);
		
		map.addOverlay(school_marker);
		
	}
	
	return;	

}

function set_schools(xml_in){
	show_schools(xml_in);
}


/* Railways START */
function add_railways(){
	
	if(map.getZoom()<12){
		$j('input[name="mappr_showrailway"]').attr('checked', false);
		return false;
	}
	
	var bounds		= map.getBounds();
	var southWest	= bounds.getSouthWest();
	var northEast	= bounds.getNorthEast();
	
	var data = {
		southwest_lng: southWest.lng(),
		northeast_lng: northEast.lng(),
		southwest_lat: southWest.lat(),
		northeast_lat: northEast.lat()
	}
	
	$j('#mappr_info').hide();
	$j('#mappr_loading').show();
	xml = false;
	$j.getJSON('http://' + mappr_domain + '/railways.php?callback=?', data, 'set_railways');
	$j('#mappr_loading').hide();

}

function create_railways_marker(point,name,htmls) {
	//alert('html:'+html);
	var marker = new GMarker(point, icon_railway);
	
	// Stop the map being reloaded after any movement that may occur to accomodate info window
	
	GEvent.addListener(marker, 'click', function() {
		remove_listeners();
		GEvent.addListener(map, 'moveend', function() {
			add_listeners();
		});
		marker.openInfoWindowHtml(htmls);
	}); 
	
	
	return marker;
}

function show_railways(stations){
	
	//console.log(schools);
	var xml = GXml.parse(stations);
	stations = xml.documentElement.getElementsByTagName('station');	
	//console.log(schools);
	
	for (var i = 0; i < stations.length; i++) {
		
		var station_html = '<p class="mappr_school"><strong>' + stations[i].getAttribute('stationname') + '<\/strong><br \/>';
		station_html += '<br \/>'
		if(stations[i].getAttribute('crscode'))		station_html += '<a href="http://www.nationalrail.co.uk/stations/'+stations[i].getAttribute('crscode')+'/details.html" target="_blank" class="blue">View Station Details.<\/a>';
		station_html += '<\/p>';
		
		//console.log(schools[i].getAttribute('name'));
		var point = new GLatLng(parseFloat(stations[i].getAttribute('lat')),	parseFloat(stations[i].getAttribute('lng')));
		var railway_marker = create_railways_marker(point, stations[i].getAttribute('name'), station_html);
		
		map.addOverlay(railway_marker);
		
	}
	
	return;	

}

function set_railways(xml_in){
	show_railways(xml_in);
}
/* Railways END */

/* Underground START */
function add_underground(){
	
	if(map.getZoom()<12){
		$j('input[name="mappr_showunderground"]').attr('checked', false);
		return false;
	}
	
	var bounds		= map.getBounds();
	var southWest	= bounds.getSouthWest();
	var northEast	= bounds.getNorthEast();
	
	var data = {
		southwest_lng: southWest.lng(),
		northeast_lng: northEast.lng(),
		southwest_lat: southWest.lat(),
		northeast_lat: northEast.lat()
	}
	
	$j('#mappr_info').hide();
	$j('#mappr_loading').show();
	xml = false;
	$j.getJSON('http://' + mappr_domain + '/underground.php?callback=?', data, 'set_underground');
	$j('#mappr_loading').hide();

}

function create_underground_marker(point,name,htmls) {
	//alert('html:'+html);
	var marker = new GMarker(point, icon_railway);
	
	// Stop the map being reloaded after any movement that may occur to accomodate info window
	
	GEvent.addListener(marker, 'click', function() {
		remove_listeners();
		GEvent.addListener(map, 'moveend', function() {
			add_listeners();
		});
		marker.openInfoWindowHtml(htmls);
	}); 
	
	
	return marker;
}

function show_underground(stations){
	
	//console.log(schools);
	var xml = GXml.parse(stations);
	stations = xml.documentElement.getElementsByTagName('underground');	
	//console.log(schools);
	
	for (var i = 0; i < stations.length; i++) {
		
		var station_html = '<p class="mappr_school"><strong>' + stations[i].getAttribute('undergroundstation') + '<\/strong><\/p>';
		
		//console.log(schools[i].getAttribute('name'));
		var point = new GLatLng(parseFloat(stations[i].getAttribute('lat')),	parseFloat(stations[i].getAttribute('lng')));
		var underground_marker = create_underground_marker(point, stations[i].getAttribute('name'), station_html);
		
		map.addOverlay(underground_marker);
		
	}
	
	return;	

}

function set_underground(xml_in){
	show_underground(xml_in);
}
/* Underground END */


function do_draw(){
	//console.log('do_draw');
	
	map.clearOverlays();
	
	// Add branch(es)
	add_branches();
	
	// We already have an active marker so add it in in it's current visibility
	map.addOverlay(active_marker);	
				
	// Add the properties!
	markers_count = addProperties(xml, (!starting_bounds) ? false : true); // We autozoom if starting bounds have been provided
	
	////////// This bit allows the active marker to still show following a redraw ////////////////////////
	if(!first_time && replaced_marker && replaced_marker_found){	
		
		// Map has been reloaded and there has been a still-valid selection. However, by design, the replaced marker won't have been added by addProperties() so add it in now from global object (but hide it)
		map.addOverlay(replaced_marker);
		replaced_marker.hide();
		
	}
	else{
		
		// Map has been reloaded but there's been no selection so all properties will have been populated by addProperties() and we need to hide active marker
		active_marker.hide();
		close_details();
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////

	
	if($j('input[name="mappr_showschools"]').is(':checked')) add_schools();
	if($j('input[name="mappr_showrailway"]').is(':checked')) add_railways();

	// Set up listener so we do not reload on zoom in - as we should already have the markers
	if(first_time || !move_listener) add_listeners();	
	
	//$j('#debug').html('Bounds: ' + map.getBounds() +'<br><br>southwest_lat: ' + data.southwest_lat + '<br>southwest_lng: '+ data.southwest_lng + '<br>northeast_lat: ' + data.northeast_lng + '<br>northeast_lng '+ data.northeast_lng + '<br><br>Props:' + markers_count+ '<br><br>Zoom:' + map.getZoom()); // Debug baby
	
	$j('#mappr_loading').hide();
	
	return markers_count;
}


function addProperties(data, autozoom) {
	
	//$j('#debug').text(data); // Debug baby
	
	xml = GXml.parse(data);
	
	markers = xml.documentElement.getElementsByTagName('marker');	
	markers_count = markers.length;
	if(markers_count>0 && markers_count<=250){
		show_message(markers_count + ' propert' + ((markers_count!=1) ? 'ies' : 'y') + ' found');
	}
	else if(markers_count==0){
		show_message(no_props_msg);
		return;
	}
	else{
		show_message('There are too many results to show on the map - please zoom in or change your criteria');
		return;
	}
	
	if(autozoom){
		// ===== Start with an empty GLatLngBounds object =====     
    	var bounds = new GLatLngBounds();
	}
	
	for (var i = 0; i < markers_count; i++) {
		
		var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),	parseFloat(markers[i].getAttribute('lng')));
		
		if(autozoom){
			// ==== Each time a point is found, extent the bounds to include it =====
        	bounds.extend(point);
		}
		
		var marker = createMarker(point, i);
		
		// We don't add in the replaced property as we add that in later from the global variable instead
		if(!replaced_marker || replaced_marker.property_id != markers[i].getAttribute('id')){
			map.addOverlay(marker);
		}
		else if(!replaced_marker_found && map.getBounds().containsLatLng(replaced_marker.getPoint())){	// Check whether it's in viewport
			replaced_marker_found = true;
		}
		
		// Hide markers that are in the same location as another marker
		if(markers[i].getAttribute('parent_id'))	marker.hide();
		
	}
	
	// Reset removed marker if no longer applicable
	if(replaced_marker){
		
		if (!replaced_marker_found){ // No longer in record set
		 	replaced_marker = false;
		}
		
	}
	else if(autozoom){
		
		// ===== determine the zoom level from the bounds =====
		map.setZoom(map.getBoundsZoomLevel(bounds));
		
		// ===== determine the centre from the bounds ======
		map.setCenter(bounds.getCenter());
		
		show_message('<strong>' + markers_count + '<\/strong> propert' + ((markers_count!=1) ? 'ies' : 'y') + ' found (we\'ve zoomed the map to include all available results)');
		//alert('hold up');
	}
	
	return markers_count; // needed?

}


// If the map position is out of range, move it back
function checkBounds() {
	
	// Perform the check and return if OK
	if (allowedBounds.contains(map.getCenter())) {
	  return;
	}
	// It's not OK, so find the nearest allowed point and move there
	var C = map.getCenter();
	var X = C.lng();
	var Y = C.lat();
	
	var AmaxX = allowedBounds.getNorthEast().lng();
	var AmaxY = allowedBounds.getNorthEast().lat();
	var AminX = allowedBounds.getSouthWest().lng();
	var AminY = allowedBounds.getSouthWest().lat();
	
	if (X < AminX) {X = AminX;}
	if (X > AmaxX) {X = AmaxX;}
	if (Y < AminY) {Y = AminY;}
	if (Y > AmaxY) {Y = AmaxY;}
	//alert ("Restricting "+Y+" "+X);
	map.setCenter(new GLatLng(Y,X));
	
}

// Adds a property to the map inc onclick etc
function createMarker(point, marker_id) {
	//alert(markers[marker_id]);
	
	/*	0 – Available, 1 – SSTC, 2 – SSTCM (Scotland only), 3 – Under Offer, 4 – Reserved, 5 – Let Agreed */
	
	///// Determine which icon we should use /////
	
	// First see if this property is sold
	var status = parseInt(markers[marker_id].getAttribute('status'));
	
	// Is it a master marker representing multiple properties?
	if(markers[marker_id].getAttribute('child_ids')){
		var icon = icon_multiple;
	}
	else if(status == 0 || status==3){	// Still available	
		if(markers[marker_id].getAttribute('new')==0)	var icon = icon_default;
		else var icon = icon_new;
	
	}
	else{ // Sold
		
		var icon = icon_sold;
	}
	
	
	var marker = new GMarker(point, icon);
	marker.property_id = markers[marker_id].getAttribute('id');
	
	// Set up the onclick 
	GEvent.addListener(marker, 'click', function(){
    	
		// Display info panel
		generate_panel(marker_id);
		
		// Show previously replaced marker..?
		if(replaced_marker) replaced_marker.show();
		
		// ..and replace this marker with active marker
		replaced_marker = marker;
		replaced_marker.hide();
		
		//alert(point);
		active_marker.setLatLng(point);
		
		if(active_marker.isHidden())	active_marker.show();
		
		//	$j('img[src$=active2.png]:first').effect('pulsate', { times: 1500 });
		
	});
	
	return marker;
}



// Shows either the SUMMARY panel or a CHOICE panel as necessary for a given marker ID
function generate_panel(marker_id){
	
	close_panel();
	
	var property = markers[marker_id];
	
	if(!property.getAttribute('child_ids')){
		show_panel(get_summary_html(marker_id));
		$j('#mappr_maximise').click(function(){
			full_details(marker_id);
		});
	}
	else{ 
		show_panel(get_choices_html(marker_id));
		$j('#mappr_maximise').hide();
	}
	
	return;
}

function show_panel(contents){
	
	var panel = '<div id="mappr_panel">\
				   <div id="panel_bg" class="move"><\/div>\
				   <div id="mappr_content" class="move"><\/div>\
				   <div id="mappr_nav">\
				   	<a id="mappr_minimise" title="Return to quick details" style="display:none"><img src="http://www.mappr.co.uk/images/min_button.png" /><\/a><a id="mappr_maximise" title="Reveal further details"><img src="http://www.mappr.co.uk/images/max_button.png" /><\/a>\
					<a id="mappr_close" title="Close these details"><img src="http://www.mappr.co.uk/images/close_button.png" /><\/a>\
				   <\/div>\
				 <\/div>';
	
	$j('#map').append(panel);
	
	//$j('#mappr_panel').prepend('');
	$j('#mappr_content').html(contents);
	$j('#mappr_close').click(close_details);
	$j('#mappr_minimise').click(quick_details);
	$j('.mappr_scrollpane').jScrollPane({showArrows:true});
}

function close_panel(){
	$j('#mappr_panel').remove();
}

function choice_made(marker_id){
	close_panel();
	show_panel(get_summary_html(marker_id));//$j('.mappr_scrollpane').jScrollPane({showArrows:true});
	$j('#mappr_maximise').click(function(){
		full_details(marker_id);
	});
}

function show_choices(marker_id){
	close_panel();
	generate_panel(marker_id);
	
}

function get_choices_html(marker_id){
	
	var property = markers[marker_id];
	
	var choices_div = '<div id="mappr_choices" class="mappr_scrollpane">\
					   <p>Please choose a property:</p>';
							
	$j.each( (marker_id + ',' + property.getAttribute('child_ids') ).split(','), function(intIndex, child_id){
		
		var image = markers[child_id].getAttribute('image');
		
		choices_div += '<div class="choices" onclick="choice_made(' + child_id + ')">\
							<img src="' + image + '" alt="" class="choice_img" width="' + (image_width-28) + '" \/><br \/>\
							' + markers[child_id].getAttribute('address') + '<br \/>\
							<strong>' + markers[child_id].getAttribute('price') + '<\/strong>\
						<\/div>';
						
	});
	
	choices_div += '</div>';
	
	return choices_div;
	
}

// Shows summary panel for a single property
function get_summary_html(marker_id){
	
	var property = markers[marker_id];
	var image = property.getAttribute('image') ? property.getAttribute('image') : 'awaiting_medium.jpg';
	
	var details_div = '<div id="mappr_summary">\
					   <h3>' + property.getAttribute('address') + '<\/h3>\
					   <h4>' + property.getAttribute('town') + '<\/h4>\
					   <div id="mappr_mainimageholder">';
					   
	/*	0 – Available, 1 – SSTC, 2 – SSTCM (Scotland only), 3 – Under Offer, 4 – Reserved, 5 – Let Agreed */
	
	var status_id = parseInt(property.getAttribute('status'));
	//alert(trans_type); 
	//alert(status_id);
	
	if(status_id != 0){
		
		switch(status_id){
			
			case 1:
			case -1:
				details_div += '<p class="mappr_sold">' + ((trans_type==0) ? 'SSTC' : 'Let Agreed') + '</p>';
			break;
			
			case 3:
				details_div += '<p class="mappr_underoffer">Under Offer</p>';
			break;
			
			case 5:
				details_div += '<p class="mappr_let">Let</p>';
			break;
			
		}

	}
	else if(property.getAttribute('new')==1)	details_div += '<p class="mappr_new">New!</p>';
	
	details_div += '<img src="' + image + '" alt="" class="mappr_main" width="' + image_width + '" \/>\
				   <\/div>\
				   <p class="mappr_price">' + property.getAttribute('price') + '<\/p>\
				   <p class="mappr_scrollpane">' + property.getAttribute('summary') + '<\/p>\
				   <p id="toggler"><a class="mappr_toggledetails mappr_reveal" onclick="full_details(' + marker_id + ')">&laquo; Reveal more details<\/a><\/p>\
				   <\/div>';

	// Do we need to provide a "Back to choices" link?
	/*if(property.getAttribute('child_ids')) var m_id = marker_id;
	else if(property.getAttribute('parent_id')) var m_id = property.getAttribute('parent_id');
	if(m_id) details_div += '<a id="mappr_backtochoices" class="mappr_toggledetails" onclick="show_choices(' + m_id + ');">Back to choices<\/a>';
	*/
	return details_div;

}

function close_details(){
	
	// Remove all the stuff to do with active property
	if(replaced_marker){
		
		replaced_marker.show();
		active_marker.hide();
		
	}
	
	// Reset these so they don't get shown following a redraw
	active_marker.property_id = -1;
	replaced_marker.property_id = -1;
	
	close_panel();

}

function zoomed(old_level, new_level){
	
	if(new_level<old_level) redrawMap();
	else{
		// We need to work out how many markers are in the viewport as we haven't reloaded the XML
		var viewport_bounds = map.getBounds();
		var mc = 0;
		for (var i = 0; i < markers_count; i++) {
			if(viewport_bounds.containsLatLng( new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng'))) )) mc++;
		}
		
		if(mc>0)	show_message(mc + ' propert' + ((mc!=1) ? 'ies' : 'y') + ' found');
		else 		show_message(no_props_msg);
	}
	//alert('new:' + new_level);
	
}


function full_details(marker_id){
	
	var property = markers[marker_id];
	quick_html = $j('#mappr_content').html(); // Store the summary HTML in case we reduce the panel again
	$j('#mappr_maximise').hide();
	$j('#mappr_content').html('<div id="mappr_summary"><img src="http://www.mappr.co.uk/images/loader.gif" alt="Content is loading" \/><\/div>');
	
	var data = { pid: property.getAttribute('id'), action: 'details' };
	
	$j.getJSON('http://' + mappr_domain + '/clients/' + client_name + '/ajax.php?callback=?', data, 'show_details');
	
}


function show_details(details_html){
	
	$j('.move').animate(
		{ width: typeof( custom_width ) != 'undefined' ? custom_width : 686+'px' }, 
		650,
		'swing',
		function(){
			$j('#mappr_content').html(details_html);
			$j('#mappr_minimise').show();
			$j('.mappr_scrollpane_full').jScrollPane({showArrows:true, scrollbarMargin: 0});
			if(typeof(use_bgiframe) != 'undefined') $j('.mappr_scrollpane_full').bgiframe();
		}
	);
	
}


function quick_details(){
	//var property = markers[marker_id];
	
	$j('#mappr_content').html('<img src="http://www.mappr.co.uk/images/loader.gif" alt="Content is loading" />');
	$j('#mappr_minimise').hide();
	$j('.move').animate(
		{ width: '200px'}, 
		400,
		'swing',
		function(){
			//alert(quick_html);
			$j('#mappr_content').html(quick_html);
			$j('#mappr_maximise').show();
			$j('.mappr_scrollpane').jScrollPane({showArrows:true});
		}
	);
	
	  
}

function add_branch(branch_marker, html, i){
	
	GEvent.addListener(branch_marker, 'infowindowopen', function() {
    	remove_listeners();
    });
	
	GEvent.addListener(branch_marker, 'click', function() {
		branch_marker.openInfoWindowHtml(html);
		add_listeners();
	});
	
	map.addOverlay(branch_marker);
	
	
}

function add_branches(){
	
	for( var i = 0, n = branches.length;  i < n;  ++i ) {
		
		if(branches[i]){
				
			branch_options = { 
				icon: icon_branch, 
				title: branches[i].name + ' Branch - click for details'
			};
			
			branch_marker = new GMarker(branches[i].point, branch_options); 
			var html  = get_branch_html(i);
			add_branch(branch_marker, html, i);// TODO: lose the 1st argument
		}

	}
	
	return;
}


function get_branch_html(i){
	
	var html = '<img src="'+ branches[i].image +'" class="mappr_branchimage" \/>';
	html += '<p class="mappr_branch"><strong>' + branches[i].name + ' Branch<\/strong><br \/>';
	html += branches[i].address1 + '<br \/>';
	if(branches[i].address2)	html += branches[i].address2 + '<br \/>';
	html += branches[i].town + '<br \/>';
	html += branches[i].postcode + '<br \/>';
	html += '<strong>' + branches[i].phone + '<\/strong><br \/>';
	html += '<a href="' + branches[i].link + '">Contact this branch &raquo;<\/a>';
	html += '<\/p>';
	return html;

}

/*function pulsate(){
	//alert($j('img[src$=active2.png'));
	
	//$j('img[src$=active2.png').effect("pulsate", { times: 3 }, 1000);
}
*/

function remove_listeners(){//alert('remove listeners');
	if(move_listener){
		GEvent.removeListener(move_listener);
		move_listener = false;
	}
}

function add_listeners(){
	//alert('add listeners');
	
	if(move_listener==false){		
		move_listener = GEvent.addListener(map, 'moveend', redrawMap);	// Redraw on drag / pan
	}
}

function move(){
	
	if(area_key = $j('select#mappr_areas option:selected').val()) {
		//	console.log(area_key);
		remove_listeners();
		map.setCenter(areas[area_key][0], areas[area_key][1]);
		redrawMap();
	}
	
}


function isset( variable ){
	return( typeof( variable ) != 'undefined' );
}

//var timeout;
$j(document).ready( function(){

	// Onchange
	$j('.onchange').change(redrawMap);
	$j('#mappr_searchform input[type=radio]').click(function(){
		//toggle_prices($(this).attr('id'));
		redrawMap();
	});
	
	$j('input[name="mappr_showschools"]').change(function(){	
		if($j(this).is(':checked')){
			if(map.getZoom()<12){
				show_message('<span style="color:#CB1003">There are too many schools to display - please zoom in and try again.</span>');
				$j(this).attr('checked', false);
			}
			else{
				add_schools();		
				$j('#mappr_info:hidden').show();
			}
		}
		else redrawMap();
	});

	$j('input[name="mappr_showrailway"]').change(function(){	
		if($j(this).is(':checked')){
			if(map.getZoom()<12){
				show_message('<span style="color:#CB1003">There are too many train stations to display - please zoom in and try again.</span>');
				$j(this).attr('checked', false);
			}
			else{
				add_railways();		
				$j('#mappr_info:hidden').show();
			}
		}
		else redrawMap();
	});

	$j('input[name="mappr_showunderground"]').change(function(){
		if($j(this).is(':checked')){
			if(map.getZoom()<12){
				show_message('<span style="color:#CB1003">There are too many underground stations to display - please zoom in and try again.</span>');
				$j(this).attr('checked', false);
			}
			else{
				add_underground();		
				$j('#mappr_info:hidden').show();
			}
		}
		else redrawMap();
	});

	//$('#edit-checkbox-id').is(':checked');
	
	// Keyword search stuff
	var search_timeout = false;

	$j('input[name="mappr_keyword"]').bind('keyup', function() {
		if(search_timeout != false) {
			clearTimeout(search_timeout);
		}
		var $this = this; // save reference to 'this' so we can use it in timeout function
		search_timeout = setTimeout(function() {
			search_timeout = false;
			str = $j('input[name="mappr_keyword"]').val();
			if(str.length >= 3 || str.length == 0){
				redrawMap();
			}
		}, 500);
			
	});
	
	$j('#mappr_areas').change(move);
	$j('#mappr_searchform input[type=radio]').addClass('radio');
	autoFill($j('input[name="mappr_keyword"]'), 'Type keywords here');
	mapLoad();
	
});

$j(window).unload( function(){
	GUnload();
});






























