// JavaScript Document
// jpelosi 7/22/08

// -------------------------------------
// location mapping functions



// declare some global variables.

var map;
var center;
var geo;
var marker;
var reversegeocoder;
var mapmode;
var mapready=false;
	
	
	
function getAaddressStr(){
 	// i dont think this is being used 	
	var a1 = $F('db_address');
	var a2 = $F('db_address2');
	var city = $F('db_city');
	var state = $F('db_state');
	var country = $F('db_country');
	var zip = $F('db_zip');
	
	if (state.toUpperCase() == "NA" || state.toUpperCase() == "N/A" ){
		state = '';
	}
	
	a=a1;
	if (startsWithNum(a1)){
		a = a1;
	} else if (startsWithNum(a2)){
		a = a2;
	}
	
	a = removeBoxNum(a);
	
	
	//a+city+state+country
	
	output = '';
	if (a!=''){ output += a; }
	if (city!=''){ output += ", "+city; }
	if (state!=''){ output += ", "+state; }
	if (zip!=''){ output += ", "+zip; }
	if (country!=''){ output += ", "+country; }
  	
	return output;
}
 
 
 // string manipulation functions
 // -----------------------------------
function startsWithNum(str){
  	
  	myregexp= /^[0-9]+/
	//myregexp = new RegExp(regexstring, "gi"); // gims
	var ma= str.match(myregexp);
	if (ma==null || ma==false || ma == ''){
		return false;
	} 
	return true
}
  
function removeBoxNum(str){
	myregexp= /(Box|po box|p.o. box|suite|ste|apt|apartment|rm|fl|room|floor)[\s\.#0-9\-a-z]+/gi
	str = str.replace(myregexp, "");
	
	myregexp= /[0-9](th|rd|st|nd)[\s\.](floor|fl)\.?/gi
	str = str.replace(myregexp, "");
	//myregexp = new RegExp(regexstring, "gi"); // gims
	return str;
	//return a1.match(myregexp);
}
	
	
	
/**
	* ----------------------------
	* Initialize the location gmap
	*
*/

function initialize(lon, lat) {
	
	// dont initialize if its set not to display.
	if ($('displayinfo2').checked){ 
		return false; 
	}
	
	// default lat, lon
	// montclair nj 
	defaultlat = 40.812984;
	defaultlon = -74.216477;
	
	
 if (GBrowserIsCompatible()) {
	 
	 	// set up map objects
    map 		= new GMap2(document.getElementById("map_canvas"));
		//center 	= new GLatLng(defaultlat, defaultlon); // center on default
		geo 		= new GClientGeocoder();
		
		
		// reversegeocoder is only used to parse the returned xml, 
		// theres no reverse geocding really.
		reversegeocoder = new GReverseGeocoder(map); 	
		
		
		// is there lat lon values?
		lon = $F('lon');
		lat = $F('lat');
		
		if (!lon.blank() && !lon.empty() && !lat.empty() && !lat.blank()){
			// make center the lat lon fields
			center 	= new GLatLng(lat, lon);
			lev = 15;	
		}  else {
			// make center default lat lon
			center 	= new GLatLng(defaultlat, defaultlon);
			lev = 1;	
		} 
		
		// set up the draggable marker
		marker 	= new GMarker(center, {draggable: true, title: 'Drag this icon to set the map position of your practice'});
		
		// center the map
		map.setCenter(center, lev);
		
		// add the marker
		map.addOverlay(marker);
		
		// map zoom controls
		map.addControl(new GSmallMapControl());
		
		
		// this sets the map mode on page load
		// map mode is whow gmap should determine the address
		// address: do a geo lookup from fields
		// drag: the lat,lon is wherever the marker is placed. dont do an address lookup.
	
		//$('mapmode-link').hide();
		if ($F('g_code') == '[custom]'){
			$('loc-txt').update(getAddressString());
			setmapmode('drag', false);
			
			//$('mapmode-link').show();
		} else {
			$('loc-txt').update($F('g_address'));
			setmapmode('address', false);
		}
		
		
		/*
		if (startmode!=false){
			setmapmode(startmode);
		} else {
			
			mapmode = 'address';
		}
		*/
		
		

	
	
		// Listeners
	
		
		// Marker dragstart listener
		// triggered when the drasg of the marker starts
     GEvent.addListener(marker, "dragstart", function() {
          if (mapmode='address'){setmapmode('drag');}
		});

		// Marker drop listener
		// triggered when the marker is dropped
    GEvent.addListener(marker, "dragend", function() {
		 
		 	// hide the error message
			$('maperror').hide();
			
			// get dropped coords
			var obj  = marker.getLatLng();
			
			// set the hidden gmap form field values
			$('lat').value = obj.lat();
			$('lon').value = obj.lng();
			$('g_address').value = getAddressString();
			
			// since this is a custom addres from a marker drag, 
			// we want to delete all the gmapdata that may be present in the hidden fields
			$('g_zip').value = '';
			$('g_country').value ='';
			$('g_state').value = '';
			$('g_city').value = '';
			$('g_street').value = '';
			$('g_accuracy').value = '';
			$('g_code').value = '[custom]';
			
			// up date the location display string
			$('loc-txt').update(getAddressString());
		
		});
		
	}// end if browser compatible...
	
	
		// flag the map as ready
	  mapready = true;
	
}
// end intialize map.



function getAddressString(){
	// returns a display string fopr the input address fields
	var arr = Array();
	arr.push(trim($F('address')));
	arr.push(trim($F('city')));
	arr.push(trim($F('state')));
	arr.push(trim($F('zip')));
	arr.push(trim($F('country')));
	
	arr.compact();
	
	return arr.without('').join(", ");
}



/* -----------------
	*	set map mode
*/
function setmapmode(mode, lookup){
	
		
	mapmode = mode;
	switch (mode){
		
		case 'drag':
		$('mapmode-link').show();
		
		// up date the location display string
		$('loc-txt').update(getAddressString());
		
		break;
		
		case 'address':
		inputAddr = '';
		$('mapmode-link').hide();
		if (lookup!==false){
		lookupMapFromFields();
		}
		break;
		
	}
}
	
	
function getSuggestedLocation(place){
	
	
	//$('lat').value = place.Point.coordinates[1];
	//$('lon').value = place.Point.coordinates[0];

	return getPlacemarkProp(place, "address");
	
	//$('g_zip').value = getPlacemarkProp(place, "PostalCodeNumber");
	//$('g_country').value = getPlacemarkProp(place,"CountryNameCode");
	//$('g_state').value = getPlacemarkProp(place,"AdministrativeAreaName");
	//$('g_city').value = getPlacemarkProp(place,"LocalityName");
	//$('g_street').value = getPlacemarkProp(place,"ThoroughfareName");
	//$('g_accuracy').value = getPlacemarkProp(place,"Accuracy");
	//$('g_code').value = code;	
	
}
	
	
	
// moves the map and places a marker on the response address
function gotoAddress(response) {
	
	
	if (!response || response.Status.code != 200) {
		// cant locate this address
		// show an error
		handleAccuracy(0);
		
	} else {
		
		/*
		var ret='';
		response.Placemark.each( function (n,i) {
																		 ret += (n+' -- '+i+', ');
																		 } 
																		 );
		*/
	
	
			var place = response.Placemark[0];
			var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			
			// set marker position
			marker.setLatLng(point);	
			
			// zoom level is dependant on the accuracy of the results
			var acc = getPlacemarkProp(place,"Accuracy"); 
			lev= 13; // zoom level
			if (acc==1){ lev = 3; }
			
			// center map on marker
			map.setCenter(point, lev);
			
			// update the hidden fields
		
			updateFields(place, response.Status.code);
		
	}
}
	

	
function relocate(){
	$('maplocation').value = $F('g_address');
	showLocation();		
}


function updateFields(place, code){
	// this updates the hidden gmpan form fields
	
	$('lat').value = place.Point.coordinates[1];
	$('lon').value = place.Point.coordinates[0];

	$('g_address').value = getPlacemarkProp(place, "address");
	$('g_zip').value = getPlacemarkProp(place, "PostalCodeNumber");
	$('g_country').value = getPlacemarkProp(place,"CountryNameCode");
	$('g_state').value = getPlacemarkProp(place,"AdministrativeAreaName");
	$('g_city').value = getPlacemarkProp(place,"LocalityName");
	$('g_street').value = getPlacemarkProp(place,"ThoroughfareName");
	$('g_accuracy').value = getPlacemarkProp(place,"Accuracy");
	$('g_code').value = code;
	
	$('loc-txt').update($('g_address').value);



	handleAccuracy(getPlacemarkProp(place,"Accuracy"));

}
	
function cearGoogleData(){
	// this clears the gmap hidden form fields
	$('g_address').value = '';
	$('g_zip').value = '';
	$('g_country').value = '';
	$('g_state').value = '';
	$('g_city').value = '';
	$('g_street').value = '';
	$('g_accuracy').value = '';
	$('g_code').value = '';
	
}
	
// looks up a location from an input string
function showLocation() {
	
	var address = $F('maplocation'); // input string is a hidden field.
	if (trim(address) == '' || address==null){
		alert('Please Enter An Address.');	
	} else{
		//alert('do lookup');
		geo.getLocations(address, gotoAddress);
	}
	
}
	
// returns the passed properties value of a placemark
// uses the reverse geocoder object
// need to make this its own function eventually
function getPlacemarkProp(placemark, prop) {
	return reversegeocoder.getPlacemarkProperty(placemark,prop);

}

	
function evalCountry(){
	// sets the state/prov dropdown dependant on country value
	$('row_state').show();
	switch ($F('country')){
	
		case 'US':
		getUSStates();
		$('stateprov_label').update('State');
		break;
		
		case 'CA':
		getCAProv();
		$('stateprov_label').update('Province');
		break;
	
		case 'AU':
		getAUProv();
		$('stateprov_label').update('Province');
		break;
		
		default:
		$('row_state').hide();
		$('state').update('');
		
		break;
	}
	
}
	
function getUSStates(){
	var requestOptions = {
			method : 'post',
			parameters : "action=getUSStates",
			onComplete: populateStateSelect
		  };
		  
	new Ajax.Request('/int/phpinc/actions_ajax.php', requestOptions);	
}
	
function getCAProv(){
	var requestOptions = {
			method : 'post',
			parameters : "action=getCAProv",
			onComplete: populateStateSelect
		  };
		  
	new Ajax.Request('/int/phpinc/actions_ajax.php', requestOptions);	
}
	
function getAUProv(){
	var requestOptions = {
			method : 'post',
			parameters : "action=getAUProv",
			onComplete: populateStateSelect
		  };
		  
	new Ajax.Request('/int/phpinc/actions_ajax.php', requestOptions);	
	
}
	
function populateStateSelect(originalRequest){
	//alert(originalRequest.responseText);
	
	var sel = selState;
	eval("var response = ("+originalRequest.responseText+")");

	var opt='';
	var pLabel = 'Province';
	if ($F('country')=='US'){
		pLabel = 'State';	
	}
	opt += '<option value=""> - Select ' + pLabel + ' - </option>';

	response.statesArr.each(function(el, index) {
		
		s = '';
		if(trim(sel) == trim(el.abbreviation) || trim(sel) == trim(el.name)){
		   s = 'selected="selected"';
		   }
		
			opt += '<option value="' + el.abbreviation + '" '+ s +'>' + el.name + '</option>';
		
	});

	$('state').update(opt);
	
}

// utility fucntion to check if a string is empty....
// should use prototpes empty() function instead
function empty(val){
	if (trim(val)=='' || val == null){
		return true;
	}
	return false;
}


// hides / disables the map
function disableMap(){
	$('mapContainer').hide();
}

// show & enable the map
function enableMap(){
	$('mapContainer').show();
	if (!mapready){
		initialize();
	}
}



// set a  global var when an address field is focuse, 
//so we can test if a change has occured
var inputAddr;

function memorizeAddr(){
	inputAddr = getAddressString();
}

// check if the addess has changed when a form field looses focus
function addressHasChanged(){
	if (inputAddr != getAddressString()){
		return true;
	}
	return false;
}

// -----------------



// lookup map from fields
// declare global variables so we can use them in other functions

var country; 
var address;
var state;
var city;
var zip;
			
function lookupMapFromFields(){

	
	
	if (mapready && addressHasChanged()){

			// get addres values from fields
			country = String($F('country'));
			address = String($F('address'));
			state 	= String($F('state'));
			city 		= String($F('city'));
			zip 		= String($F('zip'));
			
			// only do a lookup if the major fields are filled in
			//  || address.blank()
			//  || city.blank()
			if (country.blank() || country.empty()){
				return;
			}
			
			// assemble location lookup string from values by state
			str = '';
			
			switch (country){
					
				case 'US':
					//str = address+", "+city+", "+state+", "+zip+", USA";
					if (!empty(address)) str += address+", ";
					if (!empty(city)) str += city+", ";
					if (!empty(state)) str += state+", ";
				//	if (!empty(zip)) str += zip+", ";
					str += "USA";
					break;
						
				case 'CA':
					//str = address+", "+city+", "+state+", "+zip+", Canada";
					if (!empty(address)) str += address+", ";
					if (!empty(city)) str += city+", ";
					if (!empty(state)) str += state+", ";
					//if (!empty(zip)) str += zip+", ";
					str += "Canada";
					break;
					
				
				case 'AU':
					//str = address+", "+city+", "+state+", AU";
					if (!empty(address)) str += address+", ";
						if (!empty(city)) str += city+", ";
					if (!empty(state)) str += state+", ";
						str += "AU";
						break;
					
				default:
					//str = address+", "+city+", "+country;
					if (!empty(address))str += address+", ";
					if (!empty(city))str += city+", ";
					if (!empty(country)) str += country;
					break;
			}
			//alert (str);
			
			// ------------------------------------
				
			// check if we are in 'address mode'
			if (mapmode == 'address'){
				$('maplocation').value = str;
				showLocation();
			}
		
	}
	
}



function handleAccuracy(ac){

	/*
	ac: a number representing how detailed the location loopup was
	
	ACCURACY CODES
	
	0   Unknown location. (Since 2.59)
	1 	Country level accuracy. (Since 2.59)
	2 	Region (state, province, prefecture, etc.) level accuracy. (Since 2.59)
	3 	Sub-region (county, municipality, etc.) level accuracy. (Since 2.59)
	4 	Town (city, village) level accuracy. (Since 2.59)
	5 	Post code (zip code) level accuracy. (Since 2.59)
	6 	Street level accuracy. (Since 2.59)
	7 	Intersection level accuracy. (Since 2.59)
	8 	Address level accuracy. (Since 2.59)

	*/
	
	ac = ac.toString(); // incase its a number, lets convert it to a string...
	
	// show all the map fields
	$('map_canvas').show();
	$('map_controls').show();
	$('gmap-location').show(); 
	
	// default zoom level
	zoom = 15;
	
	
	switch (ac){
		
		
		case '8':
		case '7':
		case '6':
			$('maperror').update('');
			//displayCloseLocationMsg(lev);
			break;
			
		case '5':
			lev = 'Postal Code';
			displayCloseLocationMsg(lev);
			zoom = 9;
			break;
			
		case '4':
			lev = 'Town / City';
			displayCloseLocationMsg(lev);
			zoom = 9;
			break;
			
		case '3':
			lev = 'County';
			displayCloseLocationMsg(lev);
			zoom = 7;
			break;
			
		case '2':
			lev = 'State / Province';
			displayCloseLocationMsg(lev);
			zoom = 5;
			break;
			
		case '1':
		zoom = 1;
			//exit("this is a country ".$locData['lon'].", ".$locData['lat']."");
			lev = 'Country';
			//displayCloseLocationMsg(lev);
			//$('maperror').update('<div class="warning">We were only able to locate <b>'+ $F('maplocation') + '</b> at the contry level: '+$F('g_address')+'<br> Please relocate your address in the textfield below.</div>');
			break;
		
		case '0':
		zoom = 5;
	
			//$('maperror').update('<div class="warning">Unknown location: <b>'+ $F('maplocation') + '</b><br>Check the spelling of your address, or you may drag the marker below to your exact location.</div>' );
			$('loc-txt').update('');
			
			$('maperror').update('<div class="warning">We were unable to locate the address you have entered.</div>' );
			
			
			//$('map_canvas').hide();
			$('map_controls').show();
			//$('map_none').show();
			$('maperror').show();
	
			break;
		
	}

// center map
center 	= marker.getLatLng();
map.setCenter(center, zoom);

}
	
	
function displayCloseLocationMsg(lev){
	var st = '<div class="warning">';
	
	if (trim($F('address'))==''){
	
		st += 'You did not enter a <b>street address</b>. For optimal search results you should enter your exact address.';

		
	} else {
	
		st += 'We were unable to locate the address you have entered. ';
		st += 'Check the spelling of your address, or you may drag the map marker to a precise location.';
	
	}
	st += '</div>';
	
		//$F('maplocation') 
		//	var st = '<div class="warning">We were only able to locate this address ';
		//	st += 'at the <b>' + lev + '</b> level.<br>';
		//		st += 'You may try to relocate your address below.</div>';
		//st += 'You may do this by re-entering the full address below, or by dragging the map icon to the exact location.</div>';
	
	$('maperror').update(st);
	$('maperror').show();
}
 
 
 
 