//
//  Load multimap to find the property location
//
window.addEvent('domready',function(){/*{{{*/
	var popup = new Element('div',{'id':'noticepopup'}).injectAfter($('captchawhy'));/*{{{*/
	$('captchawhy').addEvent('click',function(e){
		e = new Event(e).stop();
		popNotice('captchawhy');
	});
	function popNotice(msg) {
		popup.empty();
		new Ajax('/aj/popNotice/',{
			'method':'get',
			'data': {'popNotice':msg},
			'update': popup,
			'evalScripts':true
		}).request();
	}/*}}}*/
	$('findLocation').setStyle('display','block');
	/* company details only show if company selected from dropdown */
	if ($defined($('propertySubmitterCompany'))) {/*{{{*/
		var cdetails = $('propertySubmitterCompanyDiv');
		cdetails.setStyle('display','none');
	}/*}}}*/
	if ($defined($('propertySubmitterType'))) {/*{{{*/
		$('propertySubmitterType').addEvent('change',function() {
			var val = $('propertySubmitterType').value;
			if (val == 'Company') {
				cdetails.setStyle('display','block');
			} else {
				cdetails.setStyle('display','none');
			}
		});
	}/*}}}*/
	if ($defined($('propertyOwnerDetailsContainer'))) {/*{{{*/
		var odetails = $('propertyOwnerDetailsContainer');
		odetails.setStyle('display','none');
	}/*}}}*/
	if ($defined($('propertySubmitterHolder'))) {/*{{{*/
		$('propertySubmitterHolder').addEvent('change', function() {
			var val = $('propertySubmitterHolder').selectedIndex;
			if (val==2||val==3) {
				odetails.setStyle('display','block');
			} else {
				odetails.setStyle('display','none');
			}
		});
	}/*}}}*/
	initMapLoader();
	function initMapLoader() {/*{{{*/
		$$('#findLocation a').each(function(item){
			item.addEvent('click',function(e){
				e = new Event(e).stop();
				new  Ajax('/aj/propertyMap/',{
					'method': 'get',
					'update': 'findLocation',
					'evalScripts': true,
					'onComplete': function(){
						window.fireEvent('ajmapload');
					}
				}).request();
			});
		});
	}/*}}}*/
	var mapviewer, route_finder, route, loading;
	var location_widget, overview_widget, pan_zoom_widget, map_type_widget;

	$('propertyFormSubmit').addEvent('click',function(e){
		e = new Event(e).stop();
		if ($('propertyLatLong').value == '') {
			gcode = new MMFactory.createGeocoder(processGeoCode);
			var address = new MMAddress();
			var property = $('propertyAddress').value.replace(/,/,'').split("\n");
			address.qs = property[0]+' '+property[1]+' '+property[2]+' '+$('propertyPostcode').value;
			address.country_code = 'UK';
			gcode.geocode(address);
			return false;
		}
		$('propertyForm').submit();
	});
	function processGeoCode() {/*{{{*/
		// if an error occurred, inform the user
		if (gcode.error_code && gcode.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
			popNotice('badAddress');
			return false;
		}
		results = gcode.result_set;

		if (gcode.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
			popNotice('multipleAddress');
		} else {
			$('propertyLatLong').value = results[0].coords;
			$('propertyForm').submit();
		}
	}/*}}}*/
	window.addEvent('ajmapload',function() {/*{{{*/
		$$('#findLocationClose a').each(function(item){/*{{{*/
			item.addEvent('click',function(e){
				e = new Event(e).stop();
				$('findLocation').setHTML('<a href="" class="buttonlink" style="margin-left:20px;">Click here to find the exact location on a map &#187;</a>');
				initMapLoader();
			});
		});/*}}}*/
		var max_zindex = 1000;
		var markers = new Array();
		//add the map
		mapviewer = new MultimapViewer ( document.getElementById ( 'mapviewer' ) );
		// add zoom features
		pan_zoom_widget = new MMPanZoomWidget ();
		mapviewer.addWidget ( pan_zoom_widget );
		mapviewer.setZoomFactor ( 14 );
		// add map type (arial, map, hybrid)
		mapviewer.setMapType(MM_WORLD_HYBRID);
		map_type_widget = new MMMapTypeWidget ();
		mapviewer.addWidget ( map_type_widget );
		// add map overview
		overview_widget = new MMOverviewWidget ();
		mapviewer.addWidget ( overview_widget );
		location_widget = new MMLocationWidget();
		mapviewer.addWidget (location_widget);
		var funcRef = resultsLoaded;
		route_finder = MMFactory.createRouteRequester(funcRef,mapviewer);
		if ($defined($('propertyLatLong'))) {
			mapviewer.addEventHandler('contextMenu',onContextMenu);
			mapviewer.addEventHandler('click',onClick);
			if ($('propertyLatLong').value == '') {
				geocoder = MMFactory.createGeocoder(processResults);
				var address = new MMAddress();
				address.qs = $('propertyAddress').value.replace(/,\n/g,"\n").replace(/\n/g,' ')+' '+$('propertyPostcode').value;
				address.country_code = 'UK';
				geocoder.geocode(address);
			} else {
				var loc = $('propertyLatLong').value.replace(/[()]/g,'').split(/,/);
				pos = new MMLatLon(loc[0],loc[1]);
				mapviewer.goToPosition ( new MMLocation ( pos ));
				markProperty(pos);
			}
		}

		function onContextMenu (type,target,menu,pos,step) {/*{{{*/
			items = [ { label: 'Mark Property', onclick: function() { markProperty(pos); menu.remove(); }, className: 'MMaddmarker'} ];
			menu.addItemsJSON( items );
		}/*}}}*/
		function onClick (type,target,pos,map) {/*{{{*/
			markProperty(pos);
		}/*}}}*/

		function processResults() {/*{{{*/
			// if an error occurred, inform the user
			if (geocoder.error_code && geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
				return false;
			}
			results = geocoder.result_set;
			var ol = document.createElement('ol');

			//loop through the result set
			for (var count=0; count < results.length; count++) {
				var address = results[count].address;
				var li = document.createElement('li');
				//add a link for each result
				var anchor = document.createElement('a');

				anchor.href = '#';
				anchor.result_count = count;
				anchor.onclick = function () { moveToResult(this.result_count); return false; };
				anchor.appendChild(document.createTextNode(address.display_name));
				li.appendChild(anchor);
				ol.appendChild(li);

				//add a marker for each result
				var marker = mapviewer.createMarker(results[count], { 'label' : address.display_name, 'text' : (count+1) });
				//add an infobox for each result
				// marker.setInfoBoxContent('<p>' + address.display_name + '<' + '/p>');
				markers.push(marker);
			}

			$('results_panel').appendChild(ol);

			//if there were multiple matches, display all the results
			if (geocoder.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
				var location = mapviewer.getAutoScaleLocation( markers );
				mapviewer.goToPosition( location ); 

			//otherwise show the only match at the optimal zoom factor
			} else {
				mapviewer.goToPosition( results[0] );
			}
		}/*}}}*/

		function moveToResult (count) {/*{{{*/
			//move the map specified location and open the info box
			mapviewer.goToPosition(results[count]);
			markers[count].openInfoBox();
		}/*}}}*/

		function markProperty(pos) {/*{{{*/

			// add icon
			mapviewer.removeAllOverlays();
			var icon = new MMIcon( '/ui/propertyfinder/propertyMarker.png' );
			icon.iconSize = new MMDimensions( 32, 32 );
			icon.iconAnchor = new MMPoint( 16, 16 );
			var label = $('propertyName').value?$('propertyName').value:'New Property';
			var marker = mapviewer.createMarker ( pos,{'label': label, 'icon':icon, 'inert':true} );
			var html = '';
			html += '<div class="mapbox">'+label+'</div>';

			marker.setInfoBoxContent(html);
			//$('results_panel').setHTML('<pre>'+dump(loc)+'</pre>');
			mapviewer.zoom( 1 );
			mapviewer.goToPosition ( new MMLocation ( pos ));
			var loca = location_widget.getLocationInfo();
			$('propertyLatLong').value = pos.toString();
			var addr = loca.name.replace(/^\s+|\s+$/g, '');
			if (loca.admin1 != '') addr+='\n'+loca.admin1.replace(/^\s+|\s+$/g, '');
			if (loca.admin2 != '') addr+='\n'+loca.admin2.replace(/^\s+|\s+$/g, '');
			$('propertyAddress').value = addr;
			//marker.openInfoBox();
			callRoute(pos);
		}/*}}}*/

	 function callRoute(pos) {/*{{{*/
		 var loc = pos.toString().replace(/[()]/g,'').split(/,/);
		 var locations = new Array();
		 locations[0] = new MMLatLon(loc[0]*1,loc[1]*1);
		 locations[1] = new MMLatLon(loc[0]*1,loc[1]*1+0.0001);
		 route = new MMRoute(locations);
		 route_finder.request(route);
	 }/*}}}*/
	 function resultsLoaded() {/*{{{*/
		 if(route.error_code) {
			 alert(route.error_code + ':' + route.error_explanation);
		 } else {
			 displaySteps(route);
		 }
	 }/*}}}*/
	 function displaySteps(route) {/*{{{*/
		 var stages = route.stages;
		 var steps = stages[0].steps;
		 var roadname =  (steps[0].road_name)?steps[0].road_name:'Unknown Road';
		 $('propertyAddress').value =  roadname.replace(/^\s+|\s+$/g, '')+"\n"+$('propertyAddress').value;
	 }/*}}}*/
			
		function addLocation(num, locations) {/*{{{*/
			var qs = document.getElementById('qs' + num);
			var country_code = document.getElementById('country_code' + num);
			var select =  document.getElementById('select' + num);
			var address = new MMAddress();
			address.qs = qs.value;
			address.country_code = country_code.value;
			locations.push(new MMLocation(address));
		}     /*}}}*/
			
		function cleanMultipleMatches(num) {/*{{{*/
			var qs = document.getElementById('qs' + num);
			var select = document.getElementById('select' + num);
			var addr = document.getElementById('addr' + num);
			var matches = document.getElementById('matches' + num); 
		 
			while (select.firstChild) {
				select.removeChild(select.firstChild);
			}
			qs.value = '';
			matches.style.display = 'none';
			addr.style.display = 'block'; 
		}     /*}}}*/

		function processGeocodingErrors (errors) {/*{{{*/
			for (var i = 0; i < errors.length; i++) {
				if (errors[i].error_code == 'MM_GEOCODE_NO_MATCHES') {
					alert('No matching locations for Location ' + errors[i].input_id);
				} else if (errors[i].error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
					var select  = document.getElementById('select' + errors[i].input_id);

					for (var j = 0; j < errors[i].results.length; j++) {
					var displayName = errors[i].results[j].address.display_name;
					var point = errors[i].results[j].coords; 
					var option = document.createElement('option');
					option.value = point.lat + ',' +point.lon; 
					option.appendChild(document.createTextNode(displayName));
					select.appendChild(option);
					select.selectedIndex=0; 
					}

				document.getElementById('matches' + errors[i].input_id).style.display = 'block';
				document.getElementById('addr' + errors[i].input_id).style.display = 'none';
				}
			}
		}	/*}}}*/
	});/*}}}*/
});/*}}}*/
