//	mj.js
//	general js file for Camden - MyJourney
//	Dunc/Lai Kingo
//	March 2008
var browserName = navigator.userAgent.toLowerCase();

if (browserName.indexOf('msie')!=-1) {
is_ie = true;
} else {
is_ie = false;
}
//PIE functions
//	Pinpoint map start settings...

debug = true;

//	Get AJAX object (is_ie and others defined in pwm_support.js)
g_request_object = (is_ie==true) ? (new ActiveXObject("Microsoft.XMLHTTP")) : (new XMLHttpRequest());

//global var - what amenity selected
g_amenity='';

//global var - red selected amenity
g_selected_amenity='';

//where postcode/street search is currently centered on
g_easting = 0;
g_northing = 0;

//what facilities selected for given mode of travel
g_facility='';

g_search_zoom = 2;	//this is the default zoom page you land on after every search

//This is for the map pins A--N ascii code 65--78 inclusive
g_pin_letter = 65; //A
g_max_pin_letter = 78;	//N

g_marker_easting = 0;
g_marker_northing = 0;

//global var to handle transport modes - note modes corrrespond to icon filenames
//the order of the array sorrsponds to the id number of the list e.g. <li id="facilities_6">
//so order and naming is important - ids start from 1 not 0 
g_travel_mode = new Array ( "walking", "driving", "cycling", "mobility", "public", "all" );
g_facilities_menu = new Array ("wc", "wcacc", "tube", "bus", "train", "parking", "paydisplay", "green", "blue", "red", "shopmob");
g_facilities_walking = new Array ("wc", "wcacc", "tube", "bus", "train");
g_facilities_driving = new Array ("wc", "wcacc", "tube", "train", "parking", "paydisplay", "green", "blue", "red");
g_facilities_cycling = new Array ("wc", "wcacc", "tube", "train");
g_facilities_mobility = new Array ("wc", "wcacc", "tube", "train", "shopmob");
g_facilities_public = new Array ("wc", "wcacc", "tube", "bus", "train");

g_amenities_menu = new Array("amenities_health_menu", "amenities_education_menu", "amenities_shopping_menu", 
"amenities_banks_menu", "amenities_work_menu", "amenities_police_menu", "amenities_police_menu", "amenities_accomodation_menu", 
"amenities_worship_menu");


//Camden bespoke popup box
g_popupbox_elem = null;
g_popupbox_shadow = null;






function callSearch(evt)
{
	if ( (evt.keyCode && evt.keyCode == 13) || (evt.which && evt.which == 13)) 
	{
		goButton();
	}
}

function  goButton()
{

	var elem = document.getElementById('searchterm');
	
	if (!elem)
	{
	  alert('Search Input Field not found');
	  return;   
	}
	
	var search_string = '';
	search_string = elem.value;
	 
	 if (  search_string != '' )
	 {
		//alert('Searching for ' + search_string );
	
		search_go('searchterm');
	
		//Clear everything down
		mj_reset_amenities();
		// Load data again to get rid of amenities if there are some already shown
		client_data_load();
	}
	
	return;
}

function mj_do_search()
{
	goButton();
}

function mj_onload_ini()
{

	//	Added this bit (09-07-08) to set the zoom bar on start up. This is done in
	//	client_data_load() but was removed at start zoom...Dunc ;-)

	var p = 1;
	while(1) {
		var id = "map_zoom_" + p;
		var elem = document.getElementById(id);
		if ( !elem )
			break;
		elem.className = (p==pp_get_zoom()) ? "zoom_current" : "link";	//	PP 2.2
		p++;
		}

	g_popupbox_elem = document.createElement ( "DIV" );
	g_popupbox_elem.id = 'div_map_popup';
	//g_popupbox_elem.style.display = 'none';
	g_popupbox_elem.style.left="0px";
	g_popupbox_elem.style.top="0px";
	g_popupbox_elem.style.zIndex=10000;
	g_popupbox_elem.style.position="absolute";

	//g_mapper.viewport.appendChild(g_popupbox_elem);	-- now handled by pp_register_popup()
	
	g_popupbox_shadow = document.createElement ( "DIV" );
	g_popupbox_shadow.id = 'popup_shadow';
	g_popupbox_elem.appendChild(g_popupbox_shadow);

	pp_register_popup ( g_popupbox_elem );

}

function mj_get_letter_pins()
{
var ret_str = '';
var blue_str = '&blue=';
var red_str = '&red=';
var blue = 0;
var red = 0;


	for ( var i=1; i<=5; i++ ) 
	{
		//sourceKey
		var id = 'pin_' + i;
		var elem = document.getElementById(id);
		if ( !elem ) break;
		
		//Easting
		var e_id = 'easting_' + id;
		var elem_ee = document.getElementById(e_id);
		
		//Northing
		var n_id = 'northing_' + id;
		var elem_nn = document.getElementById(n_id);
		
		
		var div_id = 'div_' + id;
		var img = document.getElementById(div_id);
		
		//Re-think pin can turn red if destination selected or selected from amenity
		//so always check hidden field
		
		//Get hidden element for red pins used to store the char code
		var hiddenID = 'dest_' + id;
		var elem2 = document.getElementById(hiddenID);
		
		//alert('mj_get_letter_pins: ' + i + ' : ' + elem2.value);
		
		if ( (elem2.value <= g_max_pin_letter) && ( elem2.value >= 65) )
		{
			red_str += String.fromCharCode(elem2.value) + '~' + elem.value + '~' + elem_ee.value + '~' + elem_nn.value +',';
			red++;
		}
		else
		{
			continue;
		}
		
	} //end of pins
	

	//remove the trailing comma	

	if ( red > 0 )
	{
		ret_str += red_str.substring(0, (red_str.length-1));
	}

	return ret_str;
} //mj_get_letter_pins

function mj_sort_pins(what)
{
var ret_str = '';
var blue_str = '&blue=';
var red_str = '&red=';
var blue = 0;
var red = 0;


	for ( var i=1; i<=5; i++ ) 
	{
		//sourceKey
		var id = 'pin_' + i;
		var elem = document.getElementById(id);
		if ( !elem ) break;
		
		//Easting
		var e_id = 'easting_' + id;
		var elem_ee = document.getElementById(e_id);
		
		//Northing
		var n_id = 'northing_' + id;
		var elem_nn = document.getElementById(n_id);
		
		
		var div_id = 'div_' + id;
		var img = document.getElementById(div_id);
		
		//Re-think pin can turn red if destination selected or selected from amenity
		//so always check hidden field
		
		//Get hidden element for red pins used to store the char code
		var hiddenID = 'dest_' + id;
		var elem2 = document.getElementById(hiddenID);
		
		if ( (elem2.value <= g_max_pin_letter) && ( elem2.value >= 65) )
		{
			// Modified by HK 20-Aug-2008
			// do nothing as alpha pins correspond to selected amenities which are gathered from g_selected_amenity in get_url() 
			continue;
			red_str += String.fromCharCode(elem2.value) + '~' + elem.value + '~' + elem_ee.value + '~' + elem_nn.value +',';
			red++;
		}
		else
		{
			//can still be red plus number
			if ( img.src.indexOf('-red-') != -1 )
			{
				red_str += i + '~' + elem.value + '~' + elem_ee.value + '~' + elem_nn.value +',';
				red++;
			}
			else
			{
				//really blue
				blue_str += i + '~' + elem.value + '~' + elem_ee.value + '~' + elem_nn.value +',';
				blue++;
			}
		}
		
	} //end of pins
	

	//remove the trailing comma	
	if ( blue > 0 )
	{
		ret_str += blue_str.substring(0, (blue_str.length-1));;
	}

	if ( red > 0 )
	{
		ret_str += red_str.substring(0, (red_str.length-1));
	}

	return ret_str;	

} //mj_sort_pins


function get_url () {

	//var url = 'client_data_load.php?';
	var url = '/mysql_client_data_load.php?';

	//	11-08-08 DM - just these 2 lines needed
	var extents = new Array();
	pp_set_datastore ( extents );

	var r = Math.round(10000*Math.random());

	url += '&r=' + r + '&minx=' + extents['min_x'] + '&maxx=' + extents['max_x'];
	url += '&miny=' + extents['min_y'] + '&maxy=' + extents['max_y'];
	url += '&mpp=' + g_pwm_config[g_source_index]['mpp'];

	url += '&search_x=' + g_easting + '&search_y=' + g_northing;

	if ( g_stoneage == true )
		url += '&stoneage';

	//	now get settings from all gui components....
	//	TBD
	
	//	get any pin info...
	if ( g_amenity != '' ) {
		url += '&amenity_cat=' + g_amenity;
		url += mj_sort_pins();
                url += mj_get_letter_pins();
	}
	
	// get selected amenities
	if (g_selected_amenity != '') {
		url += '&sel_amenity=' + g_selected_amenity + '&';
	}
		
	//get facility info
	if ( g_facility != '' ) {
		url += '&facility=' + g_facility;
	}
	
	//prompt('DEBUG', url);
	
	return url;

	}


function mj_update_locator_map () {

	//	Change these if the locator map image changes!
	var minx = 515200;
	var maxx = 545800;
	var miny = 176750;
	var maxy = 189200;
	var mpp = 150;

	var locmap_elem = document.getElementById('div_map_locator');
	if ( !locmap_elem ) {
		if ( debug == true ) alert ( "Unable to get div_map_locator in mj_update_locator_map()" );
		return;
		}

	locmap_elem.style.top = '0px';
	locmap_elem.style.left = '0px';
	locmap_elem.style.width = '204px';
	locmap_elem.style.height = '83px';
	locmap_elem.style.overflow = 'hidden';


	//	Get map position
	var coords = new Array();
	pps_get_map_centre ( coords );

	//	Get map size
	var size = new Array();
	pps_get_map_size ( size );

	//	Create the locator box if it doesn't already...
	var boxelem = document.getElementById('div_map_locator_box');
	if ( !boxelem ) {
		var boxelem = document.createElement ( "DIV" );
		boxelem.id = 'div_map_locator_box';
		boxelem.style.position = 'absolute';
		locmap_elem.appendChild(boxelem);
		}

	//replaced 150 with mpp
	var wid_pix = Math.floor(size['width']/mpp);
	var hgt_pix = Math.floor(size['height']/mpp);

	//LKL 16/06/08 these manual afjustments -10 etc are required because the 
	//located map is not geo-coded so we have to fudge where we are
	
	//var x = Math.floor(((coords['easting'] - minx)/150)-(wid_pix/2));
	var x = Math.floor(((coords['easting'] - minx)/mpp) - 10);
	if ( pp_get_zoom() > 2 )	//	PP 2.2
		x = x + (wid_pix/2) - 5;
		
	var y = Math.floor(((maxy-coords['northing'])/mpp)+(hgt_pix/2));
	if ( pp_get_zoom() < 3 )	//	PP 2.2
		y = y + 10;

	//	Cludge to get around probs with templates
	if ( y<16 ) y = 16;
	if ( (y+hgt_pix) > 100 ) hgt_pix = 100-y;

	boxelem.style.left = x + 'px';
	boxelem.style.top = y + 'px';
	boxelem.style.width = wid_pix + 'px';
	boxelem.style.height = hgt_pix + 'px';
	boxelem.style.border = '1px solid #000000';
	boxelem.style.backgroundColor = '#666666';
	boxelem.style.opacity = 0.5;

	if ( typeof g_stoneage != 'undefined' ) {
		boxelem.style.filter = 'alpha(opacity=50)';
		boxelem.style.fontSize = '1px';
		}
	
	}

function mj_update_selected_destination(id, ee, nn, dest_elem_id)
{

	//alert('mj_update_selected_destination');
	
	var elem = document.getElementById('div_selected_destinations');
	if ( !elem ) 
	{
		if ( debug == true ) alert ( "Unable to get div_selected_destinations in mj_update_selected_destination()" );
		return;
	}

/*	  Check is done in mj_redraw_map() - doesn't call this function is pin already exist
	//create a child div
	dest_elem_id = 'selected_dest_' + sourceKey;
	
	//check if already exist, don't recreate
	if (document.getElementById(dest_elem_id))
		return;
*/
		
	if (elem.style.display =='none')
	  elem.style.display='block';
		
	//Now need to update the hidden field
	var hiddenId = 'dest_' + id;
	var alpha = document.getElementById(hiddenId);
	//alpha.value = String.fromCharCode(g_pin_letter);
	//letter = alpha.value;
	alpha.value = g_pin_letter;
	letter = String.fromCharCode(alpha.value);
		
		
	//Only increment if we have not reached the max, otherwise we keep overwriting the last one	
	if ( g_pin_letter != g_max_pin_letter )
		g_pin_letter++;
					
	var dest_elem = document.createElement ( "DIV" );
	
	//append the child first to the document before accessing any of its properties
	elem.appendChild(dest_elem);
	
	dest_elem.id = dest_elem_id;
	dest_elem.className = 'div_selected_destination_item';
	var name_elem = document.getElementById('name_' + id);
	var addr_elem = document.getElementById('addr_' + id);
	var phone_elem = document.getElementById('phone_' + id);
	var web_elem = document.getElementById('web_' + id);
	
	//javascript:mj_redraw_map($easting, $northing, '$id');
	
	str = '<img src=http://myjourney2.pieout.com/pie-images/map-pin-red-' + letter + '.png width="35" height="46" title="' + letter + '" alt=" + letter +" />';
	if ( (name_elem) && (name_elem.innerHTML != '' ) )
	{
		//val = '<a href="javascript:pps_redraw_map ( ' + ee + ',' + nn +',' + g_map_src +' );"><h3>' + name_elem.innerHTML + '</h3></a>';
		val = '<h3>' + name_elem.innerHTML + '</h3>';
		str += val;
	}
	
	//val ='<h4>&lt;<img src="images/icon-amenities-' + g_amenity + '.png" width="17" height="15" title="' + g_amenity + '" alt="' + g_amenity +'" />' + g_amenity + ' &gt;</h4>';
	val ='<h4><img src="http://myjourney2.pieout.com/images/icon-amenities-' + g_amenity + '.png" width="17" height="15" title="' + g_amenity + '" alt="' + g_amenity +'" />' + g_amenity + ' </h4>';
	str += val;

	if ( (addr_elem) && (addr_elem.innerHTML != '' ) )
	{
		val = '<p>' + addr_elem.innerHTML + '<br />';
		str += val;
	}

	if ( (phone_elem) && (phone_elem.value != '' ) )
	{
		val = 'Tel: ' + phone_elem.value + '<br />';
		str += val;
	}
	
	if ( (web_elem) && (web_elem.value != '' ) )
	{
		var pin_id = 'icon_pin_' + letter;
		val = '<a href=javascript:mj_openWin(\'' + web_elem.value  + '\');>web link</a>';
		str += val;		
	}

	//val += '<a style="float:right;" href=javascript:mj_removeElement(\'' + dest_elem.id   + '\');>Delete</a></p>';
	var ids = dest_elem_id + '\',\'' + 'icon_pin_' + letter + '\',\'' + hiddenId;
	val = '<a style="float:right;" ';
	val += 'href=javascript:mj_remove_destination(\'' + ids  + '\');>Delete</a><div class="clear"></div></p>';
	str += val;
	
	dest_elem.innerHTML = str;
	
	
} //mj_update_selected_destination

function mj_removeElement(id)	
{

	var Node = document.getElementById(id);
	Node.parentNode.removeChild(Node);
	
} //mj_removeElement

function mj_remove_destination(id, pin_id, hiddenId)
{
	//Now need to update the hidden field
	var alpha = document.getElementById(hiddenId);
	if (alpha)
		alpha.value = '';

	//remove the pin if it is on the map
	if ( document.getElementById(pin_id) )
		mj_removeElement(pin_id);

	//Remove the destination
	if (document.getElementById(id))
		mj_removeElement(id);
		
	// Remove it from selected amenity (20-Aug-2008)
	mj_remove_selected_amenity(pin_id.charAt((pin_id.length-1)));
		
	
}

function client_data_load(url_ext)
{
	//	Check g_map_src, as this shows any change in zoom level (we need to ensure that the zoom bar
	//	reflects the actual zoom, as this one works outside of Pinpoint)
	
	var p = 1;
	while(1) {
		var id = "map_zoom_" + p;
		var elem = document.getElementById(id);
		if ( !elem )
			break;
		elem.className = (p==pp_get_zoom()) ? "zoom_current" : "link";	//	PP 2.2
		p++;
		}

	//	Position a suitably-sized box onto the locator map to show where we are...
	//LKL 021008 - locator map removed so no need for this
	//mj_update_locator_map ();	

	var url = get_url ();
	
	//For the clear amenities
	if ( url_ext !=null)
		url += url_ext;

	//prompt('DEBUG:', url);
		
	//	Set up the ajax call
	g_request_object.open ( 'get', url, true );
	g_request_object.onreadystatechange = mj_handle_map_data;
	g_request_object.send(null);

	return;
}

function mj_clear_amenities()
{
	//get the selected pin before we clear everything down
	url = mj_get_letter_pins();
	
	// Close any opened popups
	pp_hide_popup();
	
	mj_reset_amenities();

	client_data_load(url);
}


function mj_reset_amenities()
{
	
	
	var btn = document.getElementById('button_amenities_close');
	if ( !btn ) {
		if ( debug == true ) alert ( "Cannot get element button_amenities_close in mj_reset_amenities()" );
		return;
		}
	
	var ul = document.getElementById('ul_amenities');
	if ( !ul ) {
		if ( debug == true ) alert ( "Cannot get element ul_amenities in mj_amenities_open_close()" );
		return;
		}

	if ( btn.src.indexOf('open') != -1 ) 
	{
		btn.src = '/wp-content/themes/cordobo-green-park-2/img/button-amenities-close.gif';
		ul.style.display = 'block';
		var res = document.getElementById('div_search_results');
		res.innerHTML = "";
		res.style.display = 'none';
	}
	
	//Reset g_amenity
	g_amenity='';
	//if close do nothing 

} //mj_reset_amenities


//	mj_amenities_open_close
//	Opens/closes the amenities menu
function mj_amenities_open_close (id) {
	var btn = document.getElementById(id);
	
	if ( !btn ) {
		if ( debug == true ) alert ( "Cannot get element " + id + " in mj_amenities_open_close()" );
		return;
		}

	var ul = document.getElementById('ul_amenities');
	if ( !ul ) {
		if ( debug == true ) alert ( "Cannot get element ul_amenities in mj_amenities_open_close()" );
		return;
		}

	if ( btn.src.indexOf('close') != -1 ) {
		//	close the amenities menu
		btn.src = '/wp-content/themes/cordobo-green-park-2/img/button-amenities-open.gif';
		ul.style.display = 'none';
		return;
		}

	btn.src = '/wp-content/themes/cordobo-green-park-2/img/button-amenities-close.gif';
	ul.style.display = 'block';
	var res = document.getElementById('div_search_results');
	res.style.display = 'none';

	}

//only one amenity menu allowed to be opened at any one time
function mj_menu_display ( what ) {
var objAmenity;

	//Collpase all amenities
	for ( ii=0; ii<g_amenities_menu.length; ii++ )
	{
		objAmenity = document.getElementById (g_amenities_menu[ii]);
		if ( objAmenity )
			objAmenity.style.display = 'none';
	}
	
	//Open the selected one
	var obj = document.getElementById ( what );
	if ( !obj ) {
		if ( debug == true ) alert ( "Cannot get element " + what + " in mj_menu_display()" );
		return;
		}

	//obj.style.display = (obj.style.display=='none'||obj.style.display.length==0) ? 'block' : 'none';
	obj.style.display = 'block';

	}

//	mj_set_search
//	This function plops the item identified by name,postcode into the search text box and makes the
//	incoming e,n global for find-my-nearest activities
function mj_set_search ( e, n, name, postcode ) {

	g_easting = e;
	g_northing = n;

	var elem = document.getElementById('searchterm');
	if ( !elem ) {
		if ( debug==true ) alert ( "Cannot get element searchterm in mj_set_search()" );
		return;
		}

	var space = (name.length > 1 )?' ':'';
	elem.value = name + space + postcode;

	//	Hide results div
	elem = document.getElementById('div_search_choice');
	if ( !elem ) {
		if ( debug==true ) alert ( "Cannot get element div_search_choice in mj_set_search()" );
		return;
		}
	elem.style.display = 'none';

	//	Reset map and draw marker ...

	//g_map_src = g_search_zoom;
	pps_redraw_map ( e, n, g_search_zoom ); //replace g_map_src with g_search_zoom
	pp_set_marker ( e, n );

	//	This added for printing (ie, to print the flaming red circle)...
	g_marker_easting = e;
	g_marker_northing = n;
	

	}


function mj_recentre_map()
{
	if ( g_easting == 0 || g_northing == 0 ) 
	{
		alert ( "Please specify a street or postcode first" );
		return;
	}
	
	pps_redraw_map ( g_easting , g_northing, pp_get_zoom() ); 	//	PP 2.2

} mj_recentre_map

function mj_menu_search ( what ) {

	g_amenity = what;
	load_amenity(what);

	}
	
function load_amenity(what)
{

	if ( g_easting == 0 || g_northing == 0 ) {
		alert ( "Please specify a street or postcode first" );
		return;
		}

	var elem = document.getElementById('div_search_results');
	elem.innerHTML = "";
	elem.style.display = 'block';

	var url = '/mysql_amenity.php?cat=' + what + '&ref_easting=' + g_easting + '&ref_northing=' + g_northing;
	url += '&mpp=' + g_pwm_config[g_source_index]['mpp'];

	//prompt('DEBUG', url);
	
	//	Set up the ajax call
	g_request_object.open ( 'get', url, true );
	g_request_object.onreadystatechange = client_handle_amenity_ajax;
	g_request_object.send(null);
	
}

function client_handle_amenity_ajax () 
{

	if ( g_request_object.readyState == 4 ) {	// ie, we have a complete response
		var response = g_request_object.responseText;
		switch ( g_request_object.status ) {
			case 200: // Success
				//print out the array 
				//alert( "Found " + response.length + " nearest.");
				if ( response == "No records" ) {
					alert ( "No records found" );
					return;
					}
				mj_amenities_open_close('button_amenities_close');
				mj_process_ajax_results ( response );
				break;
			case 404: // Not found
				alert ( "AJAX error: url not found" );
				break;
			default:
				//alert ( "AJAX error: " + g_request_object.status );
				break;
			}
		}

}


function mj_process_ajax_results ( ajax_response ) {

	var elem = document.getElementById('div_search_results');
	elem.innerHTML = ajax_response;

	setTimeout ( client_data_load, 500 );

	}


function mj_handle_map_data () 
{

	if ( g_request_object.readyState == 4 ) {	// ie, we have a complete response
		var response = g_request_object.responseText;
		switch ( g_request_object.status ) {
			case 200: // Success
				g_mapper.datastore.innerHTML = '<div id=ajax_div style=position:absolute;top:0px;left:0px;width:100%;height:100%;overflow:hidden;>' + response + '</div>';
				break;
			case 404: // Not found
				alert ( "AJAX error: url not found" );
				break;
			default:
				//alert ( "AJAX error: " + g_request_object.status );
				break;
			}
		}

}

function mj_redraw_map(ee, nn, id)
{
	//g_easting = ee;
	//g_northing = nn;
	
	//redraw the pin on the amenities menu from blue to red
	//The id = pin_# where # is a number from 1-5
	
	var el = 'div_' + id;
	var elem = document.getElementById(el);
	
	if ( elem )
	{
		var len = id.length - 1;
		var pinId = id.substring(len);
		
		strURL = "http://myjourney2.pieout.com/pie-images/map-pin-red-" + pinId + ".png";

		//elem.style.backgroundImage="url("+strURL+")";
		elem.src=strURL;

		var eastingId = 'easting_' + id;
		var el_easting = document.getElementById(eastingId);

		var northingId = 'northing_' + id;
		var el_northing = document.getElementById(northingId);
		
		//get the sourcekey
		var sourceKey = document.getElementById(id);
		//alert(sourceKey.value);
	}
	
	/**
	//user has selected an amenity - update selected destination now we have fired AJAX request off
	//check it hasn't already been selected
	var dest_elem_id = 'selected_dest_' + sourceKey.value;
	
	//check if already exist, don't recreate
	if (! document.getElementById(dest_elem_id))
		mj_update_selected_destination(id, el_easting.value, el_northing.value, dest_elem_id);
	**/
	
	
	//Just toggle the map pin from blue to red
	var el2 = 'icon_' + id;
	var elem2 = document.getElementById(el2);
	if ( elem2 )
	{
		var lenMap = id.length - 1;
		var pinIdMap = id.substring(lenMap);
		
		strURL = "http://myjourney2.pieout.com/pie-images/map-pin-red-" + pinId + ".png";
		elem2.style.backgroundImage="url("+strURL+")";
	}
	
		
	//	Reset map and no need to draw marker the circle as this will invalidate the distance calculations
	pps_redraw_map ( ee, nn, pp_get_zoom() ); 	//	PP 2.2

} //mj_redraw_map


function mj_openWin(url) {
	aWindow=window.open(url,"","scrollbars=yes,status=yes,menubar=no,resizable");
	}
	
/*--------------------------------------------------
 * Handles all the travel mode on right hand side
 * of page
 *--------------------------------------------------
*/

//Toggles the tabs in the menu can calls function mj_create_facility_menu() to create 
//the menu items.
function mj_toggle_travel_mode(id, mode)
{

	//uses the src to determine new icon
	//must toggel allothers off
	var img = document.getElementById(id);
	if ( !img ) {
		if ( debug == true ) alert ( "Cannot get element " + id + " for image in mj_toggle_travel_mode()" );
		return;
		}

	var ul = document.getElementById( 'facilities_' + mode );
	if ( !ul ) {
		if ( debug == true ) alert ( "Cannot get element facilities_" + mode + " in mj_toggle_travel_mode()" );
		return;
		}

	if ( img.src.indexOf('-on') != -1 ) {
		//found -on in the filename
		//already on so do nothing - you toggle off by selecting another mode
		return;
		}

	img.src = '/wp-content/themes/cordobo-green-park-2/img/icon-facilities-' + mode + '-on.png';
	img.style.display = 'block';
	ul.style.display = 'block';

	//Sort out the menu
	mj_create_facility_menu(mode);

	//Must toggle all the others off - loop through g_travel_mode
	for ( var ii=0; ii<g_travel_mode.length; ii++ )
	{		
		if ( g_travel_mode[ii].indexOf(mode) == -1 )
		{
			var id = ii + 1;;
			var tab_obj = document.getElementById('facilities_icon_'+id);

			if ( !tab_obj )	continue;
			tab_obj.src = '/wp-content/themes/cordobo-green-park-2/img/icon-facilities-' + g_travel_mode[ii] + '.png';
			tab_obj.style.display = 'block';
			
			//var items = document.getElementById('menu_' + g_travel_mode[ii]);			
			//if ( !items ) continue;
			//items.style.display = 'none';
			
		}
	}
			
} //mj_toggle_travel_mode


//works out of the 10 menu items, which should appear under which mdoe of travel
function mj_create_facility_menu(mode)
{
var elem;
var elem_title;
	
	//Toggle All Off
	for ( var ii=0; ii<g_facilities_menu.length; ii++)
	{
		if (elem = document.getElementById(g_facilities_menu[ii]) )
			elem.style.display='none';
	}
	elem_title = document.getElementById('facilities_title_all');

	switch (mode)
	{
	case 'walking':
		elem_title.innerHTML='Walking';
		for ( var ii=0; ii<g_facilities_walking.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_walking[ii]) )
				elem.style.display='block';
		}				
		break;
	case 'driving':
		elem_title.innerHTML='Driving';
		for ( var ii=0; ii<g_facilities_driving.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_driving[ii]) )
				elem.style.display='block';
		}
		break;
	case 'cycling':
		elem_title.innerHTML='Cycling';
		for ( var ii=0; ii<g_facilities_cycling.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_cycling[ii]) )
				elem.style.display='block';
		}
		break;
	case 'mobility':
		elem_title.innerHTML='Mobility vehicle or wheelchair';
		for ( var ii=0; ii<g_facilities_mobility.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_mobility[ii]) )
				elem.style.display='block';
		}
		break;
	case 'public':
		elem_title.innerHTML='Public transport';
		for ( var ii=0; ii<g_facilities_public.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_public[ii]) )
				elem.style.display='block';
		}				
		break;
	case 'all':
		elem_title.innerHTML='All modes of transport';
		for ( var ii=0; ii<g_facilities_menu.length; ii++)
		{
			if (elem = document.getElementById(g_facilities_menu[ii]) )
				elem.style.display='block';
		}
		break
	default:
		break;
	}
}


//Toggles the menu item on or off in the facilities menu
function mj_toggle_facility(facility)
{
	var img = document.getElementById('img_' + facility );
	
	if ( !img ) {
	if ( debug == true ) alert ( "Cannot get element img_" + facility + " for image in mj_toggle_facility()" );
		return;
	}

	if ( img.src.indexOf('-on') != -1 ) 
	{
		//Toggle off
		img.src = '/wp-content/themes/cordobo-green-park-2/img/button-facilities-off.gif';
		
		//Change the background 
		var elem = document.getElementById('a_' + facility );
			if ( elem ) elem.style.background = '#ededed';
	}
	else
	{
		//Toggle On
		img.src = '/wp-content/themes/cordobo-green-park-2/img/button-facilities-on.gif';

		//Change the background 
		var elem = document.getElementById('a_' + facility );
			if ( elem ) elem.style.background = '#ffffff';
	}
	
	//Display
	img.style.display = 'block';
	
	//LKL UAT 27-03-08 Ron B wnat sgo button remove and data to load when User toggles the menu item
	mj_load_facilities();
	
} //mj_toggle_facility



//Called when user clicks on the Go button after selecting which mode of travel and what facility
//First need to determine what mode of travel the User is in
//Then based on the mode you determine what is switched on
//Importamnt to determine Mode first becasue if All is displayed by default with everything ON

function mj_load_facilities()
{
var elem;
var img;
var ul;
var mode='';
var menu='';

	for ( ii=0; ii<g_travel_mode.length; ii++ )
	{
		img = document.getElementById('facilities_icon_' + (ii + 1) );
		if ( !img ) {
		if ( debug == true ) alert ( "Cannot get element facilities_icon_" + (ii + 1) + " for image in mj_load_facilities()" );
		return;
		}
		
		ul = document.getElementById( 'facilities_' + g_travel_mode[ii] );
		if ( !ul ) {
			if ( debug == true ) alert ( "Cannot get element facilities_" + mode + " in mj_load_facilities()" );
			break;
		}

		if ( img.src.indexOf('-on') != -1 ) 
		{
			//found -on in the filename
			mode = g_travel_mode[ii];
			break;
		}
	} //for which mode of travel
	//alert(mode);
	switch (mode)
	{
	case 'walking':
		for ( var ii=0; ii<g_facilities_walking.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_walking[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_walking[ii] + ',';
				}
		}				
		break;
	case 'driving':
		for ( var ii=0; ii<g_facilities_driving.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_driving[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_driving[ii] + ',';
				}
		}
		break;
	case 'cycling':
		for ( var ii=0; ii<g_facilities_cycling.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_cycling[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_cycling[ii] + ',';
				}
		}
		break;
	case 'mobility':
		for ( var ii=0; ii<g_facilities_mobility.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_mobility[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_mobility[ii] + ',';
				}
		}
		break;
	case 'public':
		for ( var ii=0; ii<g_facilities_public.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_public[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_public[ii] + ',';
				}
		}				
		break;
	case 'all':
		for ( var ii=0; ii<g_facilities_menu.length; ii++)
		{
			if (elem = document.getElementById('img_' + g_facilities_menu[ii]) )
				if ( elem.src.indexOf('-on') != -1 ) 
				{
					//found -on in the filename
					menu = menu + g_facilities_menu[ii] + ',';
				}
		}
		break
	default:
		break;
	}
	
	//remove the last comma
	g_facility = menu.substring(0, (menu.length-1));

	//alert(menu);
	
	//Submit the AJAX request
	var url = get_url ();
	//prompt('DEBUG', url);

	g_request_object.open ( 'get', url, true );
	g_request_object.onreadystatechange = mj_handle_map_data;
	g_request_object.send(null);
	
} //mj_load_facilities

/*--------------------------------------------------
 * End of code to handle the travel mode on right 
 * hand side of page
 *--------------------------------------------------
*/
function get_url_print () {

       //var url = 'client_data_load.php?';
       var url = '/mysql_client_data_load.php?';

       //      11-08-08 DM - just these 2 lines needed
       //var extents = new Array();
       //pp_set_datastore ( extents );

       var info = new pp_get_map_info();

       var r = Math.round(10000*Math.random());

       url += '&r=' + r + '&minx=' + info.min_easting + '&maxx=' + info.max_easting;
       url += '&miny=' + info.min_northing + '&maxy=' + info.max_northing;
       url += '&mpp=' + g_pwm_config[g_source_index]['mpp'];

       url += '&search_x=' + g_easting + '&search_y=' + g_northing;

       if ( g_stoneage == true )
               url += '&stoneage';

       //      now get settings from all gui components....
       //      TBD

       //      get any pin info...
       if ( g_amenity != '' ) {
               url += '&amenity_cat=' + g_amenity;
               url += mj_sort_pins();
	       url += mj_get_letter_pins();
       }

       //get facility info
       if ( g_facility != '' ) {
               url += '&facility=' + g_facility;
       }

       //prompt('DEBUG', url);

       return url;

       }


function mj_print()
{

       var str = get_url_print ();
       var data_url = str.replace (/&/g,"|");
       var copyright = g_pwm_config[g_source_index]['copyright'].replace(/&/g,"|");
       var coords = new Array ();
       if ( pp_get_map_origin ( coords ) == false ) {
               alert ( "Unable to get map origin in client_create_pdf()" );
               return;
               }
       var xp = coords['xp'];
       var yp = coords['yp'];
       var wp = g_mapper.viewport_wid_p;
       var hp = g_mapper.viewport_hgt_p;
       var mpp = g_pwm_config[g_source_index]['mpp'];
       var z = pp_get_zoom();  //      PP 2.2

var info = new pp_get_map_info();
xp = info.centre_easting;
yp = info.centre_northing;

       var url = 'print.php?data=' + data_url + '&client_id=' + g_client_id + '&sc=' + z + '&xp=' + xp + '&yp=' + yp + '&wp=' + wp + '&hp=' + hp;
       url += '&cpy=' + copyright;
       url += '&mpp=' + mpp;

       if ( g_marker_easting != 0 && g_marker_northing != 0 ) {
               //      We need to plot a marker. Eastings/northings no good, we need a pixel pos. Work this out
               //      and pass to print.php as pixels...

               //var x = Math.floor((g_marker_easting - g_data_minx) / g_pwm_config[g_source_index]['mpp']);
               //var y = Math.floor((g_data_maxy - g_marker_northing) / g_pwm_config[g_source_index]['mpp']);

               var x = Math.floor((g_marker_easting - info.min_easting) / g_pwm_config[g_source_index]['mpp']);
               var y = Math.floor((info.max_northing - g_marker_northing) / g_pwm_config[g_source_index]['mpp']);

               if ( x>=0 && x<wp )
                       if ( y>=0 && y<hp )
                               url += '&mx=' + x + '&my=' + y;
               }

       if ( g_stoneage == true )
               url += '&stoneage';

       window.open ( url, "blank" );

}


function mj_print_old()
{

	var str = get_url ();
	var data_url = str.replace (/&/g,"|");
	var copyright = g_pwm_config[g_source_index]['copyright'].replace(/&/g,"|");
	var coords = new Array ();
	if ( pp_get_map_origin ( coords ) == false ) {
		alert ( "Unable to get map origin in client_create_pdf()" );
		return;
		}
	var xp = coords['xp'];
	var yp = coords['yp'];
	var wp = g_mapper.viewport_wid_p;
	var hp = g_mapper.viewport_hgt_p;
	var mpp = g_pwm_config[g_source_index]['mpp'];
	var z = pp_get_zoom();	//	PP 2.2
	var url = 'print.php?data=' + data_url + '&client_id=' + g_client_id + '&sc=' + z + '&xp=' + xp + '&yp=' + yp + '&wp=' + wp + '&hp=' + hp;
	url += '&cpy=' + copyright;
	url += '&mpp=' + mpp;

	if ( g_marker_easting != 0 && g_marker_northing != 0 ) {
		//	We need to plot a marker. Eastings/northings no good, we need a pixel pos. Work this out
		//	and pass to print.php as pixels...
		var x = Math.floor((g_marker_easting - g_data_minx) / g_pwm_config[g_source_index]['mpp']);
		var y = Math.floor((g_data_maxy - g_marker_northing) / g_pwm_config[g_source_index]['mpp']);
		if ( x>=0 && x<wp )
			if ( y>=0 && y<hp )
				url += '&mx=' + x + '&my=' + y;
		}

	if ( g_stoneage == true )
		url += '&stoneage';

	window.open ( url, "blank" );

}


//Camden bespoke popup

function mj_popup_content(x_px, y_px, icon_wid, icon_hgt, content, title, pin)
{
	var markup = "";
	var shadow_img = "../images/popup-shadow.png";
	var pin_img = "../images/map-pin-red-" + pin + ".png";
	if ( is_ie == true )
	{
		g_popupbox_shadow.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + shadow_img + ", sizingMethod='image');";	}
	else
		g_popupbox_shadow.style.backgroundImage = "url(" + shadow_img + ")";
		
	//markup += "</div>";
	markup += "<table onmousedown=\"pps_do_nothing(event);\" onmouseup=\"pps_do_nothing(event);\">";
	markup +="<tr>";
	markup += "<td id=\"popup_topleft\"><img src=\"../images/corner-popup-topleft.png\" width=\"10\" height=\"10\" alt=\" \" /></td>";
	markup += "<td id=\"popup_top\"></td>";
	markup += "<td id=\"popup_topright\"><img src=\"../images/corner-popup-topright.png\" width=\"10\" height=\"10\" alt=\" \" /></td>";
	markup += "</tr>";
	markup += "<tr>";
	markup += "<td id=\"popup_left\"></td>";
	markup += "<td id=\"popup_content\">";
	markup += "<div class=\"popup_content_narrow\">";
	markup += "<a href=\"javascript:mj_hide_popupbox();\"><img id=\"popup_button_close\" src=\"../images/popup-button-close.png\" width=\"16\" height=\"16\" title=\"Close this popup\" alt=\"Close this popup\" /></a>";
	markup += "<img id=\"popup_pin\" src=\"" + pin_img + "\" width=\"35\" height=\"46\" title=\"1\" alt=\"1\" />";
	//Add the title passed in
	markup += "<h3 style='font-size: 1.3em;'>" + title + "</h3>";
	//Add the content passed in 
	markup += content;
	markup += "</div>";
	markup += "</td>";
	markup += "<td id=\"popup_right\"></td>";
	markup += "</tr>";
	markup += "<tr>";
	markup += "<td id=\"popup_botleft\"><img src=\"../images/corner-popup-botleft.png\" width=\"10\" height=\"10\" alt=\" \" /></td>";
	markup += "<td id=\"popup_bottom\"><div><img src=\"../images/popup-arrow.png\" width=\"77\" height=\"45\" alt=\" \" /></div></td>";
	markup += "<td id=\"popup_botright\"><img src=\"../images/corner-popup-botright.png\" width=\"10\" height=\"10\" alt=\" \" /></td>";
	markup += "</tr>";
	markup += "</table>";
	
	g_popupbox_elem.innerHTML = markup;
	//OK the pointy triangle is of dimension 77 wid 45 hgt so we need to offset against the icon
	g_popupbox_elem.style.left = (x_px - 34 )+ 'px';
	g_popupbox_elem.style.top = (y_px - icon_hgt) + 'px';
	g_popupbox_elem.style.display = 'block';
	g_popupbox_elem.style.visibility = 'visible';

}


function mj_hide_popupbox()
{
	if (!g_popupbox_elem)
		return; 	//this shouldn't happen as it is created during the body onload()
	g_popupbox_elem.style.display = 'none';
}

//	This is a cludge to format the pp popup box for Camden...
function mj_fix_popup () {

	var elem = document.getElementById('popup_contents');
	if ( !elem ) return;

	//gets rid of the border around the text body
	elem.style.borderColor = '#ffffff';

	}

function mj_select_destination ( pin_id ) 
{
	//Hide/close the popup
	mj_hide_popupbox();

	//pin_id is just the number 
	var id = 'pin_' + pin_id;
	
	var el = 'div_' + id;
	var elem = document.getElementById(el);

	if ( elem )
	{
		
		var eastingId = 'easting_' + id;
		var el_easting = document.getElementById(eastingId);

		var northingId = 'northing_' + id;
		var el_northing = document.getElementById(northingId);
		
		//get the sourcekey
		var sourceKey = document.getElementById(id);
		//alert(sourceKey.value);
		
		//Need to convert the pin from a number to a letter pin and update the selectd destination.
		var dest_elem_id = 'selected_dest_' + sourceKey.value;
		
		//check if already exist, don't recreate
		if (!(document.getElementById(dest_elem_id)) )
		{
			//Just toggle the map pin from blue to red
			var el2 = 'icon_' + id;
			var elem2 = document.getElementById(el2);
			//current letter (20-Aug-2008)
			var letter = String.fromCharCode(g_pin_letter);
			if ( elem2 )
			{
				var lenMap = id.length - 1;
				var pinIdMap = id.substring(lenMap);
		
				strURL = "http://myjourney2.pieout.com/pie-images/map-pin-red-trans-" + String.fromCharCode(g_pin_letter) + ".png";
				elem2.style.backgroundImage="url("+strURL+")";
			}
			mj_update_selected_destination(id, el_easting.value, el_northing.value, dest_elem_id);
			
			// Modified by HK on 20-Aug-2008
			// Change ref: Camden snag list (no. 5)
			mj_update_selected_amenity(letter,sourceKey.value,el_easting.value,el_northing.value);
		}
	
		//	Reset map and no need to draw marker the circle as this will invalidate the distance calculations
		pps_redraw_map ( el_easting.value, el_northing.value, pp_get_zoom() ); 

	}
	
}

// Modified by HK on 20-Aug-2008
// Change ref: Camden snag list (no. 5)
function mj_update_selected_amenity(letter,id,easting,northing) {
	var amenity = g_amenity;
	if (g_selected_amenity.length>0) g_selected_amenity += ',';
	g_selected_amenity += letter + '~' + id + '~' + easting + '~' + northing + '~' + amenity;
}

function mj_remove_selected_amenity(letter) {
	var selected_amenities = g_selected_amenity.split(',');
	var temp = new Array();
	for (var i=0,len=selected_amenities.length;i<len;i++) {
		if (selected_amenities[i].charAt(0) != letter) {
			temp.push(selected_amenities[i]);
		}
	}
	
	if (temp.length!=0)
		g_selected_amenity = temp.join(',');
	else
		g_selected_amenity = '';
}

function mj_move_popup(ee, nn)
{
	//Get the map extents
	var extents = new pp_get_map_info();

	var min_e = extents.data_min_east;
	var max_e = extents.data_max_east;
	var min_n = extents.data_min_north;
	var max_n = extents.data_max_north;
		
	var e_value = parseFloat(ee);
	var n_value = nn;
	
	offset_bot = (max_n - min_n)/5;
	offset_half = (max_n - min_n)/2;
	
	var yy = nn - offset_half; //can be negative if pin below half way mark

	n_value = offset_half + yy + offset_bot;
	

	//	Reset map and no need to draw marker the circle as this will invalidate the distance calculations
	pps_redraw_map ( e_value, n_value, pp_get_zoom() ); 
	
} //mj_move_popup


function reset_search() {
	g_easting = 0;
	g_northing = 0;
}