/*
 * $Workfile: jquery.panels.js $
 * $Revision: 73 $
 * $Modtime: 17/02/10 12:42 $
 * $Author: Peter.goulborn $
 *
 * Astun jQuery Panels
 * Copyright (c) 2009 Astun Technology
 *
 * List of panel plugins:
 *	- faultlayers
 *	- findnearest
 *	- markerplacer
 *	- addresssearch (autocomplete)
 *	- searchfor
 *	- showmapcategories
 *	- takemeto
 *	- mapsourceswitcher
 *	- basemapswitcher
*/



(function($) {
	$.fn.faultlayers = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.faultlayers.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title'),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement)),
			$eventElement = $('#'+o.eventElement);

		//Fire the event and get the list of fault layers
			Event.observe( eventElement, 'astun:faultlogger_layersupdated', setLayers);
		
		//Method which will be called after you get the results (layers list)
		function setLayers(evt) {
			var faults	= evt.memo.list;
			//Check if we got the list otherwise return
				if(!faults || typeof faults.length=='undefined' || faults.length==0) return !$(panel).remove();
				else $eventElement.trigger(visibilityTriggerEvent,false);

			var	current	= evt.memo.current,
				$layers = $('<ul/>').addClass('atFaultLayer');//Set the layers object and append it to the body
			
			//Set the title of the panel
				$title.html((faults.length>1) ? o.manyLayersHeaderTxt : o.oneLayerHeaderTxt);
			//Insert empty ul list into the body
				$body.html($layers);
			
			//Run through the Array
			$.each(faults,function(i,n) {
				var thisLayer = $(this)[0],
					href = document.location.toString().replace( /type=.*[&$](.*)/ig, '$1' );
					href += ( href.indexOf('?') > 0 ) ? '&' : '?' ;
					href += 'type=' + thisLayer.layerName;
				
				var	$layer = $('<a/>')
								.attr('href',href)
								.html('<img src="'+thisLayer.iconImage+'">' + thisLayer.displayName)
								.appendTo($layers)
								.wrap("<li></li>");

				//Bind click to unactive and unbind to active layers
				if( thisLayer == current )
				{
					$layer.attr('id','active').css("cursor","default").removeAttr('href').click(function(){ return false; });
				}
				else
				{
					$layer
						.fadeTo("fast", 0.7)
						.click(function(){
							eventElement.fire( 'astun:faultlogger_setlayer',
							{ 
								'name':  thisLayer.layerName.replace( ' ', '_' ), 
								'index': i
							});
							return false;
						})
						.hover(
							function(){ $(this).addClass('ui-corner-all').fadeTo('slow', 1); }, //Hover in
							function(){ $(this).removeClass('ui-corner-all').fadeTo('fast', 0.7); } //Hover out
						)
				}
			});//End of .each
		}//End of function setLayers
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.faultlayers.defaults = {
		oneLayerHeaderTxt: "You are reporting on",
		manyLayersHeaderTxt: "Select category to report",
		eventElement: 'atMap'
	};
	
})(jQuery);









(function($) {
	$.fn.markerplacer = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.markerplacer.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement)),
			$eventElement = $('#'+o.eventElement),
			$continueBtn = $('<a href="#"></a>')
							.html(o.continueBtnTxt)
							.css({'padding': 4, 'text-decoration':'none', 'display':'block', 'text-align':'center', 'width': '20%', 'margin':'8px 0' })
							.addClass('ui-state-disabled ui-corner-all '+ o.continueBtnCssClass)
							.click(function(e){
								//If disabled do nothing
								if(!$(this).hasClass('ui-state-disabled'))
								{
									window.logFault(e);
								}
								return false;
							});

		//Bind method to enable continue button
		$eventElement.bind('markerPlaced',function(){
			$continueBtn.removeClass('ui-state-disabled').addClass('ui-state-default')
		});
		
		//Add some extra bits to the notes if required i.e themedAlerts==true
			if(o.themedAlerts)
			{
				var noteStart	= '<div class="ui-state-highlight ui-corner-all" style="padding:0 0.7em; margin-top: 10px;"><span class="ui-icon ui-icon-info" style="float:left; margin-right:0.3em"></span>',
					//Just replace the css note classes with css error classes in the above line, the rest is the same
					errorStart	= noteStart.replace('ui-state-highlight','ui-state-error').replace('ui-icon-info','ui-icon-alert'),
					noteEnd 	= '</div>';
				o.editModeHelpNote = noteStart+o.editModeHelpNote+noteEnd;//Notice
				o.viewModeHelpNote = noteStart+o.viewModeHelpNote+noteEnd;//Notice
				o.editModeError = errorStart+o.editModeError+noteEnd;//Error
			}


		//Fire the event and get the list of fault layers
			Event.observe(eventElement, 'astun:faultlogger_layersupdated', preparePanel );
			
			//$eventElement.bind('allowEditing',function(e, status) { preparePanel(e,status); });

		function preparePanel(evt)
		{
			//Clear the body
				$body.html('');

			
			//To check if there is only 1 layer selected
			//var faults = evt.memo.list,
			var disabledClass = '';

			if(!window.faultlogger.editing.allowed)
			{
				o.disableInStart = true;
				disabledClass = (typeof evt.memo.current.layerName=='undefined') ? 'ui-state-disabled' : '';
			}
			
			//Insert a button for enabling and disabling
				var $placerLink	= $('<a href="#"></a>')
									.addClass('ui-state-default ui-corner-all ' + o.btnCssClass + ' ' + disabledClass)
									.hover(function(){ $(this).addClass('ui-state-hover') }, function(){ $(this).removeClass('ui-state-hover') })
									.css({'padding':'4px', 'display':'block', 'width':'60%', 'text-align':'center', 'text-decoration':'none'})
									.html((o.disableInStart) ? o.editModeTxt : o.viewModeTxt)
									.attr('data-mode', (o.disableInStart) ? 0 : 1)//0 = disabled(view mode) & 1 = enabled(edit mode)
									.click(function(){
										//Check if button is disabled than just return
										if($(this).hasClass('ui-state-disabled'))
										{
											alert('Please select the category to report first.');
											return false;
										}
										//Toggle the mode first
										if($(this).attr('data-mode')==0) {
											$(this).attr('data-mode',1);
											$(this).html(o.viewModeTxt);
										}
										else {
											$(this).attr('data-mode',0);
											$(this).html(o.editModeTxt);
										}
										//Trigger the event to implement the mode
										$placer.trigger('changeMode',$(this).attr('data-mode'));
										return false;
									})
									.appendTo($body),
			//Helper on the map
					$helper =	$('<div/>')
								.addClass('ui-state-default'+ o.helperCssClass)
								.hover(function(){ $(this).addClass('ui-state-hover') }, function(){ $(this).removeClass('ui-state-hover') })
								.css({
									'padding':2,
									'position':'absolute',
									'top' : $(o.attachHelperTo).offset().top,
									//'left': ($(o.attachHelperTo).width()/2)-(parseInt(o.helperWidth.replace('px',''))/2),
									'right' : 450,
									'border': '2px solid',
									'border-top':'none',
									'font-weight':'lighter',
									'font-size' : '15px',
									'-moz-border-radius-bottomleft':o.helperCornerRadius,
									'-webkit-border-bottom-left-radius':o.helperCornerRadius,
									'-moz-border-radius-bottomright':o.helperCornerRadius,
									'-webkit-border-bottom-right-radius':o.helperCornerRadius,
									'width' : o.helperWidth,
									'text-align' : 'center'
								})
								.appendTo('body')
								.hide(),
			//Now the actual placer
					$placer = 	$('<div/>')
									.appendTo($body)
									.bind('changeMode',function(e,mode){
										//Check if faultlogger is undefinied
										if(typeof window.faultlogger == 'undefined')
										{	
											//alert("Error: 'faultlogger' is undefined.");
											var faultlogger = {'editing': {'enabled':true, 'allowed':true}};
										}
										//View mode
										if(mode==0)
										{
											$(this).html(o.viewModeHelpNote);
											window.faultlogger.editing.enabled = false;
										}
										//Edit mode
										else
										{
											//If edit mode is allowed
											if(window.faultlogger.editing.allowed)
											{
												$(this).html(o.editModeHelpNote);
												window.faultlogger.editing.enabled = true;
											}
											//If edit mode is not allowed, issue an error msg
											else $(this).html(o.editModeError);
										}
										//Change helper
											$helper.slideUp(o.helperAnimationSpeed, function(){ 
													$(this).html((mode==0) ? o.helperViewModeTxt : o.helperEditModeTxt);
													$(this).slideDown(o.helperAnimationSpeed)
											});
										//Css tweaks
											$(this).find('.ui-icon').css('margin-top',"12px").find('p').css('margin','8px 0');
									});//End of .bind

			//Append continue button
			$body.append($continueBtn);

			//If user want to disable the edit mode in start | Put a delay because faultlogger.editing.allowed return false without this (even if it is true) i.e defined somewhere after this code
			$placer.trigger('changeMode', (o.disableInStart) ? 0 : 1);
			
		}//End of function
	}//End of Plugin
	
	
	// Public: plugin defaults options
	$.fn.markerplacer.defaults = {
		modeHeaderTxt: "Marker placement",
		btnCssClass: '',
		editModeTxt: "Enable marker placement",
		viewModeTxt: "Disable marker placement",
		editModeHelpNote: "<p><b>Click the map</b> where you wish to set the location.</p> <p>Use the Find Address panel to search for a particular address.</p> <p id='atCaseInteraction'>The interaction will be assigned to a new case.</p> <p>When you've specified the location you want, please press the Continue button.</p>",
		editModeError: "<p>Edit mode is not allowed.</p>",
		viewModeHelpNote: "<p><b>Click the above button</b> to enable placing markers on the map.</p>",
		eventElement: 'atMap',
		disableInStart : false,
		continueBtnTxt: "Continue",
		continueBtnCssClass: '',
		themedAlerts:true,
		attachHelperTo : '#atMap',
		helperCssClass : '',
		helperViewModeTxt: 'View mode',
		helperEditModeTxt: 'Edit mode',
		helperAnimationSpeed: 200,
		helperCornerRadius: '8px',
		helperWidth: '100px'
	};
	
})(jQuery);









(function($) {
	$.fn.findnearest = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.findnearest.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement)),
			$eventElement = $('#'+o.eventElement);
		//Load the panel when source is loaded
		preparePanel();
		function preparePanel()
		{
			var
			//Main form wrapper
				$form = $('<form/>').appendTo($body),
			//Clear results
				$results = $('<div/>').addClass('atFindNearestClearResults').appendTo($form),
			//Layer selector
				$layerSelector = $('<select/>')
									.addClass('atFindNearestDD')
									.change(function(){
										o.pseudoLayer.layerName = $(this).val();
					  	  				o.pseudoLayer.displayName = $(this).find('option:selected').html();
									})
									.appendTo($form)
									,
			//Number of results dropdown
				$numOfResults = $('<select/>')
									.addClass('atFindNearestDD')
									.change(function(){
										 o.pseudoLayer.query.findNearest.maxResults = $(this).val();
									})
									.appendTo($form),
			//Distance dropdown
				$distance = $('<select/>')
									.addClass('atFindNearestDD')
									.change(function(){
										 o.pseudoLayer.query.findNearest.distance = $(this).val();
									})
									.appendTo($form),
			//Go button
				$goBtn = $('<input type="submit" value="Go">')
							.click(function(){
								$eventElement.trigger('loaderDialogVisibility', true);
								eventElement.fire( "astun:layerQuery", {'layer': o.pseudoLayer} );
								return false;
							})
							.appendTo($form),
			//Clear results link
				$clearResults = $('<a/>')
									.attr('href','#')
									.html('Clear current query results')
									.click(function(){
										eventElement.fire( "astun:layerQuery", {'reset': true} );
										return false;
									})
									.hide()
									.appendTo($form),
				layerControl = data.memo.layerControl,
				loadLayers = {},
				//Get the settings
				settings = new Astun.iSharemaps.myNeighbourhood.getSettings;
				o.distances = settings.queryDistances || o.distances;
				o.results = settings.queryResults || o.results;

			//Populate the result dropdown
			$.each(o.results,function(i,result) {
				$('<option/>')
					.attr('value',result.split('~')[0])
					.html(result.split('~')[1])
					.appendTo($numOfResults)
			})
		
			//Populate the distance dropdown
				$.each(o.distances,function(i,distance) {
					$('<option/>')
						.attr('value',distance.split('~')[0])
						.html(distance.split('~')[1])
						.appendTo($distance)
				})

			//Populate the layer selector dropdown
				var groups = data.memo.layerControl.layerGroups;
			//Check if we got groups than remove the disable class from the jRibbon tool otherwise remove the panel
				if(!groups || typeof groups.length=='undefined' || groups.length==0) return !$(panel).remove();
				
			//Loop through all the groups
			$.each(groups,function(i,group){
				//Now fetch all its layers
				$.each(group.layers,function(j,layer){
					if ( layer.query.findNearest ) {
						$option = $('<option/>')
									.attr('value',layer.layerName)
									.html(layer.displayName)
									.appendTo($layerSelector)
					}
				})	//End of layers.each
			})	//End of groups.each
			
			//Check if the the drop down is empty than remove the panel
			if($layerSelector.find('option').length==0) return !$(panel).remove();
			else $eventElement.trigger(visibilityTriggerEvent,false);
			
			//Style the dropdowns, options and clearResults link
				//Common styles for all elements
					$form.find('select,input,a:last').addClass('ui-state-default ui-corner-all').css({'outline':'none', 'padding':3, 'background':'none'});
				//Styles for each elment	
					$form.find('select').css({ 'width':'100%', 'margin-top':3 });
					$form.find('option').css('padding','2px');
					$form.find('input').css({'float':'right', 'margin':'5px 3px 3px', 'padding':'4px 2px'});
					$form.find('a:last').css({ 'padding':2, 'margin-top':4, 'float':'left', 'width':160, 'text-align':'center', 'text-decoration':'none' });
			
			//Set layers
				o.pseudoLayer.layerName = $layerSelector.val();
				o.pseudoLayer.displayName = $layerSelector.find('option:first').html();
			    o.pseudoLayer.query.findNearest.distance = $distance.val();
			    o.pseudoLayer.query.findNearest.maxResults = $numOfResults.val();

				var setFindNearestLayerEvent = function( evt ) {
					//Hide the loader and clear result button
					$eventElement.trigger('loaderDialogVisibility', false);
					//If no results found than dont show the clear results link
					if(evt.memo.html.indexOf('No results found')<0) $clearResults.fadeIn('slow');
				}
				var resetFindNearestLayerEvent = function( evt ) { $clearResults.fadeOut('slow'); }

				Event.observe( eventElement, 'astun:resultsReceived', setFindNearestLayerEvent.bindAsEventListener( this ) );
				Event.observe( eventElement, 'astun:resultsCleared', resetFindNearestLayerEvent.bindAsEventListener( this ) );

				loadLayers = null;
			}
	}//End of Plugin
	
	
	// Public: plugin defaults options
	$.fn.findnearest.defaults = {
		modeHeaderTxt	: "Find Nearest",
		eventElement	: 'atMap',
		distances 		: [ '250~250m','500~0.5km','1000~1.0km','2500~2.5km' ],
		results			: [ '2~Two results','5~Five results','10~Ten results','25~Twenty five results','50~Fifty results' ],
		pseudoLayer		: {
							'layerName': '',
							'displayName': '',
							'query':
								{
									'findNearest':
									{
										'distance': 0,
										'maxResults': 0
									}
			    			}
		    			}
	};
	
})(jQuery);





(function($) {
	$.fn.addresssearch = function(panel,visibilityTriggerEvent,data,options) {

		// Extend the options if any provided
		var	 o = $.extend({}, $.fn.addresssearch.defaults, options),
		
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.searchHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content').html(''),
		//The input box
			input = $('<input type="text" name="'+o.textBoxId+'" id="'+o.textBoxId+'" style="width:87%; margin-right:2px;background:none;color:#000;font-weight:normal">')
					.addClass('ui-widget-header ui-corner-all '+o.textBoxClass)
					.css(o.inputCSS)
					.val(o.textBoxDefaultValue),
		//Search button
		 searchBtn = $('<input type="button" value="'+o.searchBtnLabel+'" style="background:none;color:#000;font-weight:normal">')
					.addClass('ui-widget-header ui-corner-all '+o.submitBtnClass)
					.css('padding','4px 2px')
					.click(function(e)
					{ 
						var searchString = $.trim(input.val());
						//If textbox has the default text than just return and focus it.
						if(searchString==$.trim(o.textBoxDefaultValue))
						{
							//If input is not animated than apply the effect otherwise if you click the button many times, it will queue up the effect
							if(!input.is(':animated') && $.fn.effect)
							{
								input.effect('highlight', {}, 3000).val('').focus();
							}
							return false;
						}
						//Check if this click is triggered - if yes than just display the current address
						if($(this).data('triggered'))
						{
							//Make the value false
							$(this).data('triggered', false);
							writeResults( e, true );
							return false;
						}
						//If textbox value is less the zero than wait untill user type something in
						if($.trim(searchString).length>0)
						{
							//Fire the event for autocomplate
							o.findPageNum = 0;
							//Call the method to start search
							goFindAddress();
						}
						return false;
					})
		
		//Check if this search is for addressbar
			var label='',cancelSearch='';

			if(o.addressBarSearch)
			{
				//Show the search bar
				$(this).find('#atLocationSearch').addClass('ui-corner-all').css('visibility','visible');
				$(this).css('visibility','visible');
				$body = $(this).find('p:first').html('');
				//label and cancel search
				label = $('<label/>').attr('for',o.textBoxId).html('Search for a location: ');
				//Re-styling it
				input.attr('style', 'width:350px; margin-right:2px;background:none;color:#000;font-weight:normal;padding:5px 2px');
				searchBtn.val('Find');
				//If current location is already shown on the page
				if($('#atLocationDisplay').length!=0)
				{
					//Very very strange - without the following line IE7 doest not push the lower divs downward
					if($.browser.msie && $.browser.version == '7.0')
					{
						$('#atLocationBar')
							.after($('<div/>')
							.css({'clear':'both', 'height':0}).html('&nbsp;'));
					}
					//Round corner
					$('#atLocationDisplay').addClass('ui-corner-all').find('#atLocationBar_lblTextCurrentLocation').css('margin-right',3);
					//Append body to the locationDisplay and hide it
					$body.appendTo('#atLocationDisplay').hide();
					//Style the change button
					$('#atLocationBar_btnChangeLocation')
						.addClass('ui-widget-header ui-corner-all cancel-address-search')
						.css({'background':'none', 'color':'#000', 'font-weight':'normal','padding': ($.browser.msie) ? 0 : '3px 2px','margin-top':-4})
						.click(function()
						{
							//Hide the current address phara
							$('#atLocationDisplay').find('p:first').hide();
							//Incase if user want to cancel the 'change address'
							cancelSearch = $('<input type="button" value="Cancel" style="background:none;color:#000;font-weight:normal;padding:4px 2px;margin-left:2px">')
											.addClass('ui-widget-header ui-corner-all cancel-address-search')
											.click(function()
											{
												//Show the hidden msg showing current address
												$('#atLocationDisplay').find('p:first').show();
												//Hide the form to change address
												$body.hide();
												//This line is to reposition the panel wrapper basically.
												$(window).trigger('resize',[true]);
												return false;
											});
							//Remove the cancel button
							$body.find('.cancel-address-search').remove();
							//Show the form to change the address
							$body.show();
							//Append the cancel Search button just created above
							searchBtn.after(cancelSearch);
							//Focus the input so user just start typing instead of click the input to search
							input.focus();
							//This line is to reposition the panel wrapper basically.
							$(window).trigger('resize',[true]);
						return false;
					});
				}
			}
			//Preparing the container to show the current address
			var $currentAddress = $('<div/>')
									.attr('id','atCurrentlySelectedAddress')
									.addClass((!o.addressBarSearch) ? 'ui-state-highlight ui-corner-all' : '')
									.css({'padding':'0pt 7px', 'margin':'5px 0pt'})
									.append(
										$('<p/>')
											.css('margin','6px 0pt 6px')
											.append(
												//Marker image
												$('<img src="images/addressiconsmall.gif" />').css({'float':'left', 'margin':'0pt 6px 30px 0pt'}),
												'<strong>Current address: </strong>',
												'<span class="atSelectedAddress"></span>'
											)
									);
			//If the search is a normal search (not panel) than remove the marker image
			if(o.addressBarSearch)
			{
				$currentAddress
					.width('auto')
					.find('img')
					.remove();
			}
		
		//Create form, append textbox and submit buttom and finally appendto the body of the panel
			var	form = $('<form id="searchForm" method="GET"></form>')
						.height((o.addressBarSearch) ? 25 : 30)
						.append(label,input,searchBtn)//Append the input box and Submit button
						.appendTo($body)//And finally append itself to the body of the panel or whatever $body is
						.submit(function(){ return false });//Do nothing on form submit
		
		var mapEventElement = Element.extend(document.getElementById(o.eventElement));
		if(o.addressBarSearch)
		{
			o.eventElement = 'atMapSpurForm';
		}
		var eventElement = Element.extend(document.getElementById(o.eventElement));
		
		
		//Start the jQuery autoComplete engine
		if(o.showAutoCompleter)
		{
			input.astun_autocomplete(input,o);
		}
		else
		{
			//If autocompleter is false than trigger Click event of button if user press enter
			input
			.keydown(function(e)
			{
				//Stop event to propagate
				Astun.JS.Common.stopEventProp(e);
				//Track last key pressed
				if(e.keyCode==13)
				{
					searchBtn.trigger('click');
				}
			})
			.focus(function()
			{
				//Check if the value is not changed from default text than clear the textbox, Onblur we will do the opposite
				if($.trim($(this).val())==o.textBoxDefaultValue)
				{
					$(this).val('');
				}
			})
			.blur(function()
			{
				//Check if the textbox is empty the put the default value in it.
				if($.trim($(this).val())=='')
				{
					$(this).val(o.textBoxDefaultValue);
				}
			});
		}
		
		//If the url has a parameter to search the result than just hide the results and use autocomplete search
		if($('#atAddressResultsDiv').length>0)
		{
			//Hide the non-js address result
			$('#atAddressResultsDiv').hide(); //Disable this line for debuging
			//Take the search key word
			var sWord = $('#atAddressResultsDiv').find('.match:first').html();
			//Populate the textbox with the search word
			if($.trim(sWord)!='')
			{
				input.val(sWord);
				//Trigger the click event of the FIND button to perform search
				setTimeout(function(){ searchBtn.trigger('click') } ,100);
			}
		}

		//If results not found than write error inside the panel
		function writeNotFound()
		{
			//Hide loader
			showLoader(false);
		
			//Remove any previoues errors.
			$('#jqNoResultsFound').remove();
			
			//Clear any previous results
			form.next('.aw_results').remove();
			
			//Replace the results with error msg.
			form.after(o.notFoundStr);
			$(window).trigger('resize',[true]);
			
			//Put the hide button witht he error msg (requested by rbwm)
			$('#jqNoResultsFound .ui-state-error').append(
				$('<span/>')
					.addClass('ui-icon ui-icon-closethick')
					.css({
						'position'	: 'absolute',
						'top'		: 6,
						'right'		: 6,
						'cursor'	: 'pointer'
					})
					.attr('title','hide')
					.click(function(e)
					{
						var animation = (o.addressBarSearch) ? 'hide' : 'slideUp';
						var speed = (o.addressBarSearch) ? 1 : o.animationSpeed;
						$('#jqNoResultsFound')[animation](speed,function(){ input.val('').focus(); $(window).trigger('resize',[true]); });
						//Stop event to propagate
						Astun.JS.Common.stopEventProp(e);
						return false;
					})
			)
			
		}
		
		
		var goFindAddress = function()
		{		
			$('.ac_results').slideUp(o.animationSpeed, function() { restoreInputCorners() });
			//Unbind all previous events
			Event.stopObserving(eventElement, 'astun:addressesFound');
			Event.stopObserving(eventElement, 'astun:addressesNotFound');

			//Rebind (fresh copy) the events again
			Event.observe( eventElement, 'astun:addressesFound', writeResults);

			//Event listner if address NOT found
			Event.observe( eventElement, 'astun:addressesNotFound', writeNotFound);
			
			showLoader(true);//First of all show loader while the Ajax gets the result.
			searchString = input.val();
			eventElement.fire( 'astun:findAddress',{ 'searchString': searchString, 'limit': o.itemsPerPage, 'offset': o.itemsPerPage * o.findPageNum});
		}
		
		
		//Function which will write the results inside the panel
		var writeResults = function( evt, justShowCurrentAddress )
		{
			//First hide the ajax loader
			showLoader(false);

			if(evt!=null && evt.memo)
			{
				var addresses = evt.memo.results.data,
					results = evt.memo.results,
					countFirst = evt.memo.offset + 1;
					/*	When we start typing the autocomplete starts and return 20 results and when we press enter it returns 5 results
						so when we press enter, sometimes we get 20 results which takes the results from the response of autocomplete call.
						To avoid the conflict, just check if results are 20 than this means that it came from the response of autocomplete so just return false
					*/
					if(addresses.length==$.fn.astun_autocomplete.defaults.maxItemsToShow)
					{
						return false;
					}
			}
			
			var resultsWrapper = $('<div class="aw_results"></div>'),
				resultsList = $('<ol/>').attr('start',countFirst||1),
				resultsNav = $('<ul/>').addClass('ui-state-default ui-corner-all').css({'background':'#eee', 'margin': '5px 0 0'});

				if(o.addressBarSearch)
				{
					resultsWrapper.width(566);
					resultsList.css('margin',10);
					resultsNav.css({'border-style':'solid', 'padding-top':3});
				}
			
			//Append empty elements after the form
				input.parents('form:first').parent().find('.aw_results, #jqNoResultsFound').remove();//Remove any previous results
				input.parents('form:first').after(resultsWrapper.append(resultsList,resultsNav));
			
			//Check if a cookie is already been set for the current address
				var cookieCurrentAdd = Astun.JS.Common.getCookie('astun:currentLocation');
				cookieAddressObj = (cookieCurrentAdd) ? cookieCurrentAdd.evalJSON() : null;
				cookieCurrentAdd = (cookieAddressObj==null || cookieAddressObj.address=="Not set, click 'Change' to choose an address") ? '' : cookieAddressObj.address;			
			
			//If empty than dont display it at all - otherwise append it to the body and populate with the address	
				if(cookieCurrentAdd!='')
				{
					//create the hyper link if user is on the map page
					$linkedAddress = $('<a href="#"></a>')
						.css('text-decoration','underline')
						.attr('title','Click to navigate to this address')
						.html($.trim(cookieCurrentAdd))
						.click(function()
						{
							//debug(cookieCurrentAdd+'\n'+ cookieAddressObj.uid  +'\n'+  cookieAddressObj.x  +'\n'+ cookieAddressObj.y  +'\n');
							mapEventElement.fire( 'astun:setAddress',
							{
								'address':cookieCurrentAdd,
								'uid': cookieAddressObj.uid,
								'x': cookieAddressObj.x,
								'y': cookieAddressObj.y
							});
							return false;
						});

					resultsWrapper.before($currentAddress);
					if($('#atMap').length!=0)
					{
						$currentAddress.show().find('.atSelectedAddress').html($linkedAddress);
						$('#atLocationBar_lblCurrentLocation').html($linkedAddress.clone(true));
					}
					else
					{
						$currentAddress.show().find('.atSelectedAddress').html(cookieCurrentAdd);
						$('#atLocationBar_lblCurrentLocation').html($currentAddress.find('.atSelectedAddress').html());
					}
					
				}
			
				//Reset search link
				var clearLink = $('<a href="#" id="atClearAuResults"><span style="float:left" class="'+o.clearIconClass+'"></span>Clear search</a>')
								.click(function()
								{
									var animation = (o.addressBarSearch) ? 'hide' : 'slideUp';
									var speed = (o.addressBarSearch) ? 1 : o.animationSpeed;
									//Remove the current selected address panel
									$currentAddress[animation](speed,function(){$(this).remove()});
									//Hide results
									$('.aw_results')[animation](speed,function()
									{ //Slide up and than remove it from DOM (just for some animation ;)
										//Remove results
										$(this).remove();
										//Delete the cookies
										Astun.JS.Common.setCookie('astun:currentLocation', '', -1 ,'', '/');
										Astun.JS.Common.setCookie('astun:mapView', '', -1 ,'', '/');
										//Clear the marker on the map
										$('#'+o.eventElement).find("img[src*='addressiconsmall.gif']").hide();
										//Clear and focus the textbox
										input.val('').focus();
										$(window).trigger('resize',[true]);
									});
									return false;
								});
			
			//If we need to show just current address than remove resultsList and reset search to the resultsNav
			if(!o.addressBarSearch && justShowCurrentAddress && cookieCurrentAdd!='')
			{
				resultsNav.append($('<li/>').css('left',8).append(clearLink));
				if($.browser.msie)
				{
					resultsNav.css('width',$body.width()-2);
				}
				resultsList.remove();
				return;
			}
			
			//Add extra class to know that this is a toobar address search
			if(o.addressBarSearch)
			{
				input
					.parents('form:first')
					.parent()
					.find('.aw_results')
					.addClass('aw_results_toolbar');
			}
			
			if(evt==null)
			{
				resultsNav.remove();
				resultsList.remove();
				return
			}
			if( results.name === 'tempLocSearch' )
			{	
				//Popluate the address
				$.each(addresses,function(i,n)
				{
					var addressLink = $('<a/>')
							.attr('href','?action=SetAddress&UniqueId='+n[0])
							.html(n[7])
							.click(function()
							{
								//If this is a toolbar search than do nothing (return)
								if(o.addressBarSearch)
								{
									return;
								}
								eventElement.fire( 'astun:setAddress',
								{
									'address': n[7],
									'uid': n[0],
									'x': n[4],
									'y': n[5]
								});
								//Trigger the go button to hide the results
								searchBtn.data('triggered',true).trigger('click');
								$(window).trigger('resize',[true]);
								return false;
							})
						,
						addressItem = $('<li/>')
							.append(addressLink)
							.appendTo(resultsList);
						//Add some style if this is a normal search (not panel)
						if(o.addressBarSearch)
						{
							addressItem.css('margin-left',35)
						}
				});
			}//End of FindAddress
			
			//Setting up the next and previous links if results available
			if( countFirst > 1 || evt.memo.more )
			{
				//For previous link
				if( countFirst > 1)
				{
					var prevNav = $('<li style="left:8px"></li>')
									.appendTo(resultsNav),
						prevLink = $('<a/>')
									.attr('href','atFindAddress.aspx?searchString'+input.val()+'&page='+( o.findPageNum - 1 ))
									.html('<span style="float:left" class="'+o.prevIconClass+'"></span> '+ o.previousLinkLabel)
									.addClass(o.previousLinkClass)
									.click(function()
									{
										--o.findPageNum;
										goFindAddress( evt );
										return false;
									})
									.appendTo(prevNav);
					if(o.addressBarSearch)
					{
						prevNav
							.css('margin-left',0)
							.find('span:first')
							.css('margin-top',2);
					}
				}//End of prevous link
				
				//For next link
				if( evt.memo.more )
				{
					
					var nextNav = $('<li style="right:8px;width:45px;height:30px;cursor:pointer"></li>')
									.appendTo(resultsNav),
						nextLink = $('<a/>')
									.css('cursor','pointer')
									.attr('href','atFindAddress.aspx?searchString'+input.val()+'&page='+( o.findPageNum + 1 ))
									.html('<span style="float:left">'+o.nextLinkLabel+ '</span> <span style="float:right" class="'+o.nextIconClass+'"></span>')
									.addClass(o.nextLinkClass)
									.click(function()
									{
										++o.findPageNum;
										goFindAddress( evt );
										return false;
									})
									.appendTo(nextNav);
					if(o.addressBarSearch)
					{
						nextLink
							.find('span:last')
							.css('margin-top',2);
					}
				}//End of next link
				
				
				
			}//End of next and previous links
			
			//Clear results link
			var	clearNav = $('<li class="aw_clearResults"></li>')
							.appendTo(resultsNav)
							//If there are only 2 'li' than keep the 'left' as 8px otherwise push it to the the middle
							.css('left',(resultsNav.find('.atResultsNavBackWard').length==0) ? 8 : ($('.aw_results').width()/2)-37)
							.append(clearLink);
				if(o.addressBarSearch)
				{
					clearNav
						.css('margin-left',0)
						.find('span:first')
						.css('margin-top',2);
				}
			//End of clear results link	
			
			//Scroll the panel to bottom if required
				$('.atPanelInnerWrapper').scrollTo($body.parents('.ui-dialog'), o.animationSpeed, {offset: {top:-5} });
			
			//Finally trigger window.resize to reposition any absolute divs
			$(window).trigger('resize',[true]);
		
		}//End of writeResults function
		
		//Show the current selected address if any in cookie
		writeResults( null, true );
		
		//Show or hide the ajax loader
		function showLoader(status)
		{
			input.css('background', (status) ? 'Window url("'+o.loadingImgUrl+'") 98% 50% no-repeat' : 'none');
		}
		
		function restoreInputCorners()
		{
			input.css({
				'-moz-border-radius-bottomleft':'',
				'-webkit-border-bottom-left-radius':'',
				'-moz-border-radius-bottomright':'',
				'-webkit-border-bottom-right-radius':''
			});
		}
	}
	
	// Public: plugin defaults options
	$.fn.addresssearch.defaults = {
		searchHeaderTxt: "Find Address",
		textBoxId : "atTextSearch",
		searchBtnLabel: 'Go',
		textBoxClass: '',
		textBoxDefaultValue : 'Postcode / House number',
		inputCSS: { 'padding' : '5px 2px' },
		submitBtnClass: '',
		eventElement: 'atMap',
		itemsPerPage: 5,
		findPageNum : 0,
		loadingImgUrl : 'images/jQuery/loaderSml.gif',
		notFoundStr : '\
		<div id="jqNoResultsFound" class="ui-widget" style="margin: 6px 0 0;position:relative"> \
				<div style="padding: 0pt 0.7em;" class="ui-state-error ui-corner-all"> \
					<p style="margin:6px 0;"><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"/> \
					<strong>Alert:</strong> No address found.</p> \
				</div> \
			</div>',
		previousLinkClass : 'atResultsNavBackWard',
		previousLinkLabel : 'Previous',
		prevIconClass : 'ui-icon ui-icon-seek-prev',
		nextLinkClass : 'atResultsNavForward',
		nextLinkLabel : 'Next',
		nextIconClass : 'ui-icon ui-icon-seek-next',
		clearIconClass : 'ui-icon ui-icon-close',
		animationSpeed : 800,
		addressBarSearch : false,
		showAutoCompleter : true
	};
	
})(jQuery);


/*
Home: http://www.pengoworks.com/workshop/jquery/autocomplete.htm
Doc: http://www.pengoworks.com/workshop/jquery/autocomplete_docs.txt
Script: http://www.pengoworks.com/workshop/jquery/lib/jquery.autocomplete.js
*/
(function($) {
	$.fn.astun_autocomplete = function(input,extendedOptions) {
	// Extend the options if any provided
	var	 o = $.extend({}, $.fn.astun_autocomplete.defaults, extendedOptions);
	// Create a link to self
	var me = $(this);
	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");
	// Apply inputClass if necessary
	if(o.inputClass)
	{
		$input.addClass(o.inputClass);
	}
	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results).hide();
	$results
		.addClass(o.resultsClass)
		.css("position", "absolute")
		.attr('aria-labelledby','JQaddressSearchResults')
		.width(( o.width > 0 ) ? o.width : '')
		.hide();

	// Add to body element
		$("body").append(results);
	
		input.autocompleter = me;
	
		var timeout = null,
			prev = "",
			active = -1,
			cache = {},
			keyb = false,
			hasFocus = false,
			lastKeyPressCode = null,
			orgVal = '';
		

	//Select using DOM method to avoid any conflict with jQuery
	var eventElement = Element.extend(document.getElementById(o.eventElement));
	
	$input
	.keydown(function(e)
	{
		orgVal = $input.val();
		//Stop event to propagate
		Astun.JS.Common.stopEventProp(e);

		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode)
		{
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 37:  // left
				break;
			case 39:  // right
				break;
			case 27:  // esc
				$results.hide();
				break;
			case 13: // return
				if($('li.ac_over').length==0)
				{
					//Trigger Go Button to start search
					setTimeout(function(){ $input.parents('form').find("input[type='button']:first").trigger('click'); } ,100);
					//Restor the input corvers - css for round corners
					restoreInputCorners();
					//Slide up results and than trigger Go Button
					$results.hide();
					//Hide any loader
					showLoader(false);
					break;
				}
				else if( selectCurrent() )
				{
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				
				break;
			default:
				active = -1;
				if(timeout)
				{
					clearTimeout(timeout);
				}
				timeout = setTimeout(function()
				{
					//Get the textbox value and trim it
					var searchString = $.trim($input.val());
					//Check if the old and new values are same than return - user just press a space
					if($.trim(orgVal)==searchString)
					{
						return;
					}
					//If textbox value is less the zero than wait untill user type something in
					if(searchString.length>0)
					{
						//First of all show loader while the Ajax gets the result.
						showLoader(true);

						//Unbind all previous events
							Event.stopObserving(eventElement, 'astun:addressesFound');
							Event.stopObserving(eventElement, 'astun:addressesNotFound');

						//Rebind (fresh copy) the events again
						Event.observe( eventElement, 'astun:addressesFound', autoResults );
						
						//Event listner if address NOT found
						Event.observe( eventElement, 'astun:addressesNotFound', autoNotFound);
						
						//Fire the event for autocomplate
						eventElement.fire( 'astun:findAddress',{ 'searchString': searchString, 'limit': o.maxItemsToShow, 'offset': 0 });
					}
					
				}, o.delay);
				break;
		}
	})
	.focus(function()
	{
		//Track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
		//Check if the value is not changed from default text than clear the textbox, Onblur we will do the opposite
		if($.trim($(this).val())==o.textBoxDefaultValue)
		{
			$(this).val('');
		}
	})
	.blur(function()
	{
		//Track whether the field has focus
		hasFocus = false;
		if($.trim($(this).val()).length==0)
		{
			hideResults();
		}
		//There is a bug in IE browser when you click the result's pane scrollbar, it will trigger the blur event of the input and the result will disappear
		if(!$.browser.msie)
		{
			hideResults();
		}
		showLoader(false);
		//Check if the textbox is empty the put the default value in it.
		if($.trim($(this).val())=='')
		{
			$(this).val(o.textBoxDefaultValue);
		}
		restoreInputCorners();
	});


	//The callback function which will be fired when the results found
	function autoResults( response )
	{
		//Hide any previous errors first
		$('#jqNoResultsFound').remove();

		//Get results
		var addresses = [];
		$.each(response.memo.results.data,function(i,n)
		{
			addresses[i] = n[7]+'<span style="display:none">'+n[7]+'~'+n[0]+'~'+n[4]+'~'+n[5]+'</span>';
		});
		o.data = addresses;
		showLoader(false);
		onChange();//Here we start the autocomplete process
	}
	
	//Method when address not found
	function autoNotFound()
	{
		//Hide loader
		showLoader(false);

		//Remove any previoues errors.
		$('#jqNoResultsFound').remove();
		//Replace the results with error msg.
		$results.html(o.notFoundStr);
		showResults();
	}
	
	function showLoader(status)
	{
		$input.css('background', (status) ? 'Window url("'+o.loadingImgUrl+'") 98% 50% no-repeat' : 'none');
	}

	hideResultsNow();

	function onChange()
	{
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) )
		{
			restoreInputCorners();
			return $results.hide();
		}

		var v = $input.val();

		if(v.length >= o.minChars)
		{
			$input.addClass(o.loadingClass);
			requestData(v);
		}
		else
		{
			$input.removeClass(o.loadingClass);
			$results.hide();
			restoreInputCorners();
		}
	};
	
	function restoreInputCorners()
	{
		$input.css({
			'-moz-border-radius-bottomleft':'',
			'-webkit-border-bottom-left-radius':'',
			'-moz-border-radius-bottomright':'',
			'-webkit-border-bottom-right-radius':''
		});
	}

 	function moveSelect(step)
	{

		var lis = $("li", results);
		if(!lis)
		{
			return;
		}

		active += step;

		if(active < 0)
		{
			active = 0;
		}
		else if(active >= lis.size())
		{
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		$('.ac_results ul').scrollTo('.ac_over',{offset: {top:-100}});
		
		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent()
	{
		var li = $("li.ac_over", results)[0];
		if(!li)
		{
			var $li = $("li", results);
			if(o.selectOnly)
			{
				if($li.length == 1)
				{
					li = $li[0]; 
				}
			}
			else if(o.selectFirst)
			{
				li = $li[1];
			}
		}
		if(li)
		{
			selectItem(li);
			return true;
		}
		else
		{
			return false;
		}
	};

	function selectItem(li)
	{
		if(!li)
		{
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue);
		
		var splitStr = v.split("<span");
		
		//Other values
		params = '<span'+splitStr[1];//Put the missing part of the html tag back so that it can be replaced entiredly in the following line
		params = params.replace(/<(?:.|\s)*?>/g, "");//Replace the whole span tag to get pure data
		params = params.split('~');
		
		//Original value
		v = params[0];
		
		//If this is a toolbar search than just open the url and return
		if(o.addressBarSearch)
		{
			var href = window.location+'?action=SetAddress&UniqueId='+params[1];
			window.location = href;
			//alert("The page will navigate to: \n"+href);
			return;
		}
		
		//Navigate the Map to the selected location
		eventElement.fire( 'astun:setAddress',
		{
			'address': params[0],
			'uid': params[1],
			'x': params[2],
			'y': params[3]
		});
		
		input.lastSelected = v;
		prev = v;
		$results.html('');
		hideResultsNow();
		
		//Trigger submit form AFTER populating the textbox.
		$input.parents('form').find("input[type='button']").data('triggered',true).trigger('click');
		
		//Callback function
		if(o.onItemSelect) 
		{
			setTimeout(function() { o.onItemSelect(li,params) }, 1);
		}
	};

	// selects a portion of the input string
	function createSelection(start, end)
	{
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange )
		{
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		}
		else if( field.setSelectionRange )
		{
			field.setSelectionRange(start, end);
		}
		else
		{
			if( field.selectionStart )
			{
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue)
	{
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 )
		{
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults()
	{
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = $input.offset();
		// either use the specified width, or autocalculate based on form element
		var iWidth = (o.width > 0) ? o.width : $input.width()+parseInt($input.css('padding-right').replace("px",''))+parseInt($input.css('padding-left').replace("px",''));
		// reposition
		$results.css({
			'width': parseInt(iWidth) + "px",
			'top': parseInt(pos.top + $input.height()+parseInt(2*$input.css('border-width').replace("px",''))+parseInt($input.css('padding-bottom').replace("px",''))+parseInt($input.css('padding-top').replace("px",''))) + "px",
			'left': pos.left + "px",
			'z-index' : 999999
		}).show();
		
		//And finally remove the bottom round corners of the textbox so it results stick to it properly
		restoreInputCorners();
		
		/*ToDo: It just heighlight the first occurrence of the keyword - it should be a for loop check every character etc*/
		/*Heighlight the keywords in the list
		$results.find('ul  li').each(function(){
			var $this = $(this);
			$this.html($this.html().replace($input.val(),"<b>"+$input.val()+"</b>"));
		});
		*/
		
		//Trim the options If they are getting into two lines due to a space in the start or at the end
		if(o.trimAddresses && !($.browser.msie && $.browser.version=="6.0"))
		{
			//First get the smallest height which we can keep as standard
			var smlestHight = 100000;
			$results.find('ul  li').each(function(){ smlestHight = ($(this).height() < smlestHight) ? $(this).height() : smlestHight; });
			
			
			//Now check the height of each item, if it is greater than the smallest height than trim the text
			$results.find('ul  li').each(function()
			{
				if($(this).height()>smlestHight)
				{	
					var orgValue = $(this).html();
						orgValue = orgValue.split("<");
					
					v = $.trim(orgValue[0]);
					
					//alert($(this).html()+"\n\n"+v[0]+"\n\n"+v[1]);
					//Rest of the part of the string
					params = '<'+orgValue[1];
					
					for (var i = 0; i <= v.length; i++)
					{
						var newStr = v.substring(0, v.length-i);
						$(this).html(newStr+'...'+params).attr('title',v);
						if($(this).height()==smlestHight)
						{
							break;
						}
					}
				}
			});
		}
		
	};
	
	//Move search results when window is resized
	$(window).resize(function()
	{
		if($results.find('ul').length>0 && $results.is(':visible'))
		{
			showResults();
		}
	});
	
	$('.atPanelInnerWrapper').scroll(function ()
	{ 
		hideResults();
    });


	function hideResults()
	{
		if(timeout)
		{
			clearTimeout(timeout);
		}
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow()
	{
		if(timeout)
		{
			clearTimeout(timeout);
		}
		showLoader(false);
		if($results.is(":visible"))
		{
			$results.hide();
			restoreInputCorners();
		}
		if(o.mustMatch)
		{
			var v = $input.val();
			if(v != input.lastSelected)
			{
				selectItem(null);
			}
		}
	};

	function receiveData(q, data)
	{
		if(data)
		{
			$input.removeClass(o.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 )
			{
				return hideResultsNow();
			}

			if($.browser.msie)
			{
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));

			//Add show all results
			if(o.showFullResults)
			{
				$(results).append(
					$('<div class="ui-widget-header ac_linksWrapper"></div>')
						.append
						(
						 	//Show full results link
							$('<a style="float:left"></a>')
							.html('<span style="float:left" class="'+o.linksClass+'"></span>'+ o.fullResultsLabel)
							.addClass('ac_links')
							.click(function()
							{
								//Slide up results and than trigger Go Button
								$results.slideUp(function()
								{
									$input.parents('form:first').find("input[type='button']:first").trigger('click');
								});
								return false;
							}),
							
							//Clear results link
							$('<a style="float:right"></a>')
							.html('<span style="float:left" class="'+o.linksClass+'"></span> Close')
							.addClass('ac_links')
							.click(function()
							{
								$results.slideUp();
								$input.val('').blur();
								return false;
							}),
							'<div style="clear:both"></div>'
						)
				);
			}
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( o.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) )
			{
				autoFill(data[0]);
			}
			showResults();
		}
		else hideResultsNow();
	};

	function parseData(data)
	{
		if(!data)
		{
			return null;
		}
		var parsed = [];
		var rows = data.split(o.lineSeparator);
		for(var i=0; i < rows.length; i++)
		{
			var row = $.trim(rows[i]);
			if(row)
			{
				parsed[parsed.length] = row.split(o.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data)
	{
		var ul = document.createElement("ul");
		var num = data.length;
		
		$(ul).css({
			'overflow-y': 'auto',
			'overflow-x': 'hidden'
		});
		
		if($.browser.msie && $.browser.version=="6.0")
		{
			$(ul).css('height',o.maxHeight);
		}
		else $(ul).css('max-height',o.maxHeight);
		
		// limited results to a max number
		if((o.maxItemsToShow > 0) && (o.maxItemsToShow < num))
		{
			num = o.maxItemsToShow;
		}
		for(var i=0; i < num; i++)
		{
			var row = data[i];
			if(!row)
			{
				continue;
			}
			var li = document.createElement("li");
				li.innerHTML = row.split('<')[0];
				li.selectValue = row;
			var extra = null;
			if(row.length > 1)
			{
				extra = [];
				for (var j=1; j < row.length; j++)
				{
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li)
				.hover
				(
					function()
					{
						$("li", ul).removeClass("ac_over");
						$(this).addClass("ac_over");
						active = $("li", ul).indexOf($(this).get(0));
					},
					function()
					{
						$(this).removeClass("ac_over");
					}
				)
				.click(function(e)
				{
					e.preventDefault();
					//Stop event to propagate
					Astun.JS.Common.stopEventProp(e);
					selectItem(this)
				});
		}
		return ul;
	};

	function requestData(q)
	{
		if(!o.matchCase)
		{
			q = q.toLowerCase();
		}
		
		// recieve the cached data
		if(o.data)
		{
			receiveData(q, o.data);
		}
		else
		{
			showLoader(false);
		}
	};

	function loadFromCache(q)
	{
		if(!q)
		{
			return null;
		}
		if(cache.data[q])
		{
			return cache.data[q];
		}
		if(o.matchSubset)
		{
			for (var i = q.length - 1; i >= o.minChars; i--)
			{
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if(c)
				{
					var csub = [];
					for(var j = 0; j < c.length; j++)
					{
						var x = c[j];
						var x0 = x[0];
						if(matchSubset(x0, q))
						{
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub)
	{
		if(!o.matchCase)
		{
			s = s.toLowerCase();
		}
		var i = s.indexOf(sub);
		if(i == -1)
		{
			return false;
		}
		return i == 0 || o.matchContains;
	};

	this.flushCache = function()
	{
		flushCache();
	};

	this.setExtraParams = function(p)
	{
		o.extraParams = p;
	};

	this.findValue = function()
	{
		var q = $input.val();

		if(!o.matchCase)
		{
			q = q.toLowerCase();
		}
		var data = o.cacheLength ? loadFromCache(q) : null;
		if(data)
		{
			findValueCallback(q, data);
		} 
		else
		{
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data)
	{
		if(data)
		{
			$input.removeClass(o.loadingClass);
		}

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++)
		{
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() )
			{
				li = document.createElement("li");
				if(o.formatItem)
				{
					li.innerHTML = o.formatItem(row, i, num);
					li.selectValue = row[0];
				}
				else
				{
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 )
				{
					extra = [];
					for (var j=1; j < row.length; j++)
					{
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}
		if( o.onFindValue )
		{
			setTimeout(function() { o.onFindValue(li) }, 1);
		}
	}
	
	$.fn.indexOf = function(e)
	{
		for( var i=0; i<this.length; i++ )
		{
			if( this[i] == e )
			{
				return i;
			}
		}
		return -1;
	};
	}
	
	// Public: plugin defaults options
	$.fn.astun_autocomplete.defaults = {
		data : null,
		inputClass : "ac_input",
		resultsClass : "ac_results",
		minChars : 1,
		delay : 900,
		matchCase : 0,
		matchSubset : 1,
		matchContains : 0,
		cacheLength : 1,
		mustMatch : 0,
		loadingClass : "ac_loading",
		selectFirst :  true,
		selectOnly : false,
		maxItemsToShow : 20,
		autoFill : false,
		width :  0,
		maxHeight :  220,
		showFullResults : true,
		fullResultsLabel : 'Show full results', //Depends on showFullResults
		linksClass : 'ui-icon ui-icon-close', //Depends on showFullResults
		trimAddresses : true
	};
})(jQuery);// JavaScript Document







(function($) {
	$.fn.searchfor = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.searchfor.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement))
			$eventElement = $('#'+o.eventElement);
		
		//Load the panel when source is loaded
		preparePanel();
		
		function preparePanel()
		{
			var
			//Main form wrapper
				$form = $('<form/>').submit(function(){ $(this).find("input[type='submit']").trigger('click'); return false; }).appendTo($body),

			//Layer selector
				$layerSelector = $('<select/>')
									.addClass('atSearchForDD')
									.appendTo($form),
			//Search textbox
				$distance = $('<input/>')
									.addClass('atSearchForTB')
									.appendTo($form),
			//Go button
				$goBtn = $('<input type="submit" value="Go">')
							.click(function(){
								$eventElement
									.trigger('loaderDialogVisibility', true)
									.trigger('searchISM',[$layerSelector.val(),$layerSelector.find(':selected').data('searchField'),$distance.val()]);
								return false;
							})
							.appendTo($form),
			//Clear results link
				$clearResults = $('<a href="#"></a>')
									.html('Clear current query results')
									.click(function(){
										eventElement.fire( "astun:layerQuery", {'reset': true} );
										return false;
									})
									.hide()
									.appendTo($form),
			//The layer object
			layerControl = data.memo.layerControl;

			//Populate the layer selector dropdown
				var groups = data.memo.layerControl.layerGroups;

			//Check if we got groups than remove the disable class from the jRibbon tool otherwise remove the panel
				if(!groups || typeof groups.length=='undefined' || groups.length==0) return !$(panel).remove();
				else
				{
					$.each(groups,function(i,group){
						//Now fetch all its layers
						$.each(group.layers,function(j,layer){
							if ( layer.searchField!=null ) {
								$option = $('<option/>')
											.data('searchField',layer.searchField)
											.attr('value',layer.layerName)
											.html(layer.displayName)
											.appendTo($layerSelector)
							}
						})	//End of layers.each
					})	//End of groups.each
					//If there is nothing in the dropdown than remove the panel
					if($layerSelector.find('option').length==0) return !$(panel).remove();
					else $eventElement.trigger(visibilityTriggerEvent,false);
				}
			//Style the dropdowns, options and clearResults link
				//Common styles for all elements
					$form.find('select,input,a')
							.addClass('ui-state-default ui-corner-all').css({'outline':'none', 'padding':3, 'background':'none'})
							.css({ 'width':'98%', 'margin-top':3 })
					$form.find('option,input').css('padding','2px')
					$form.find("input").css({'width':'96%', 'padding':'5px 2px'})
					$form.find("input[type='submit']").css({'width':'auto', 'float':'right', 'margin':'5px 8px 3px','padding':'4px 2px'})
					$form.find('a:last').css({ 'padding':2, 'margin-top':4, 'float':'left', 'width':160, 'text-align':'center', 'text-decoration':'none' });
					
					var setFindNearestLayerEvent = function( evt ) {
						//Hide the loader and clear result button
						$eventElement.trigger('loaderDialogVisibility', false);
						//If no results found than dont show the clear results link
						if(evt.memo.html.indexOf('No results found')<0) $clearResults.fadeIn('slow');
					}
				var resetFindNearestLayerEvent = function( evt ) { $clearResults.fadeOut('slow'); }

				Event.observe( eventElement, 'astun:resultsReceived', setFindNearestLayerEvent.bindAsEventListener( this ) );
				Event.observe( eventElement, 'astun:resultsCleared', resetFindNearestLayerEvent.bindAsEventListener( this ) );
			}
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.searchfor.defaults = {
		modeHeaderTxt	: "Search For",
		eventElement	: 'atMap'
	};
})(jQuery);









(function($) {
	$.fn.showmapcategories = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.showmapcategories.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content').css('position','relative'),
			eventElement = Element.extend(document.getElementById(o.eventElement)),
			$eventElement = $('#'+o.eventElement);

		//Load the panel when source is loaded
		preparePanel();
		
		//Check the number of active or inactive links and 'check' the checkbox accordingly
			$eventElement.bind('updateCheckboxCounter',function(e,groupDisplayName){
				var g = $body.find("h3[aria-labelledby='"+groupDisplayName+"']").parent();
				g.find(':checkbox').fadeTo("fast",(g.find('.inactive').length>0 && g.find('.active').length>0) ? o.inactiveLayerFade : 1);
				g.find(':checkbox').attr('checked',(g.find('.active').length==0) ? '' : 'checked' );
				//Update the counter
				g.find('.atMapLayersCounter').html(g.find('.active').length+'/'+g.find('li').length);
			})

		function preparePanel()
		{
			var groups = data.memo.layerControl.layerGroups;
			//Check if we got the data
				if(!groups || typeof groups.length=='undefined' || groups.length==0) return !$(panel).remove();
				else $eventElement.trigger(visibilityTriggerEvent,false);
			//Run loop through main groups and display them
			$.each(groups,function(i,group){
				var $group		= $('<div/>')
									.addClass('atMainLayersGroup ui-state-default ui-corner-all')
									.css({'background':'#fff', 'margin-bottom':2})
									.appendTo($body),
					$heading	= $('<h3/>')
									.css({'margin':0, 'padding':5, 'cursor':'pointer', 'border-width':0, 'font-size':'1em', 'position' : 'relative'})
									.addClass('ui-state-default ui-corner-all')
									.attr('aria-labelledby',group.displayName)
									.bind("mouseenter mouseleave", function(e){
										$(this).parent().toggleClass("ui-state-hover");
									})
									.append(
										$('<span/>')
											.addClass('ui-icon ui-icon-triangle-1-e')
											.css({'width':16, 'height':16, 'float':'left'})
											,
											group.displayName
									)
									.click(function(){
										//Save ref
										var self=$(this);
										//Hide all other panes if true
										if(o.togglePanes)
										{
											$body.find('.atMainLayersGroup').each(function(){
												if($(this).hasClass('.ui-state-active') && $(this).find('h3:first').attr('aria-labelledby')!=self.attr('aria-labelledby')) $(this).find('h3:first').trigger('click');
											});
										}
										self.next('ol').slideToggle(o.helperAnimationSpeed,
											function(){
												//Change the active class of the parent element
													self.parent().toggleClass('ui-state-active');
												//Change the icon class of itself
													self.find('.ui-icon').toggleClass('ui-icon-triangle-1-e').toggleClass('ui-icon-triangle-1-s');
												//Save the opened in cookies settings
													var openGroups = new Array();
														$body.find('.atMainLayersGroup').each(function(){
															if($(this).hasClass('.ui-state-active'))
															openGroups.push($(this).find('h3:first').attr('aria-labelledby'))
														});
													if(openGroups.length!=0) eventElement.fire('astun:saveSetting', {'setting': 'layerPanelOpenGroups', 'value': openGroups.toJSON()});
											})
									})
									.appendTo($group),
					$content = $('<ol/>')
								.css({'padding':4, 'margin':0, 'list-style':'none'})
								.hide()
								.appendTo($group);

					//Now fetch all its layers
					$.each(group.layers,function(j,layer){
						if( !layer.currentlyVisible && !layer.active ) {
							return; //don't show layers that can't be turned on.
						}
						//Check if scale is provide otherwise take the default scale
						var scale	= (layer.query.findNearest && layer.query.findNearest.scale) ? layer.query.findNearest.scale : o.defaultScale;
							$layer	= $('<li/>')
										.attr({'aria-labelledby':layer.displayName, 'aria-describedby':layer.layerName})
										.fadeTo("fast",(layer.currentlyVisible) ? 1 : o.inactiveLayerFade)
										.addClass((layer.currentlyVisible) ? 'active' : 'inactive')
										.css({'padding':4, 'padding-bottom':10 ,'margin':2, 'border-bottom' : '1px dotted #ccc', 'position':'relative'})
										.height(22)
										.append(
											$queryIcon	= (layer.query && (layer.query.bufferSearch || layer.query.showMy || layer.query.findNearest))
															?
																	$('<a/>')
																	.css({
																		'position'	: 'absolute',
																		'left'		: 2
																	})
																	.addClass('atQueryLink')
																	.append(
																		$('<img />')
																			.addClass('queryicon')
																			.attr({
																				'src':'images/atLayerQuery.png',
																				'alt':
																					(layer.query.findNearest)
																					?
																						'Show the nearest '+
																						layer.query.findNearest.maxResults
																						+ ' ' +
																						layer.displayName
																						+ ' ' +
																						'within '+
																						layer.query.findNearest.distance
																						+ ' ' +
																						scale
																					//ShowMy
																					:
																						'Show my '+
																						layer.displayName
																			})
																			.css({
																				 'border'	 : 'none',
																				 'margin-top':1
																			})
																	)
																	.click(function(){
																		if($(this).find('img').hasClass('atQueryLayerShown'))
																		{
																			eventElement.fire("astun:layerQuery", {'reset': layer});
																		}
																		else
																		{
																			eventElement.fire("astun:layerQuery", {'layer': layer});
																		}
																		return false;
																	})
																	.attr({
																		'href':'#',
																		'title':
																				(layer.query.findNearest)
																				?
																					'Show the nearest '+
																					layer.query.findNearest.maxResults
																					+ ' ' +
																					layer.displayName
																					+ ' ' +
																					'within '+
																					layer.query.findNearest.distance
																					+ ' ' +
																					scale
																				//ShowMy
																				:
																					'Show my '+
																					layer.displayName
																	})
																	//.simpletooltip({width:200})
																:''
															,
											$layerDesc	= $('<a/>')
															.css({'display':'block', 'margin-left':32,'width':'80%', 'position':'relative'})
															.attr({
																'href' : '#',
																'title': 'Click to'+ ((layer.currentlyVisible) ? ' hide ' : ' show ') + layer.displayName + ' on the map.'
															})
															.addClass('atLayerLink')
															.append(
																$('<img />')
																	.attr({'src':layer.icon, 'alt': 'Click to'+ ((layer.currentlyVisible) ? ' hide ' : ' show ') + layer.displayName + ' on the map.' })
																	.css({
																		'position'	: 'absolute',
																		'border' 	: 'none'
																	})
																,
																$('<span/>')
																	.html(layer.displayName)
																	.css({
																		'padding'		: 3,
																		'padding-left'	: 32,
																		'padding-top'	: 5,
																		'display'		: 'block',
																		'font-weight'	: 'normal'
																	})
															)
															.click(function(){
																//Toggle layer
																$eventElement.trigger('toggleLayer',layer.layerName);
																//And deselect the Query icon
																if($(this).closest('li').find('img:first').hasClass('atQueryLayerShown'))
																{
																	eventElement.fire("astun:layerQuery", {'reset': layer});
																}
																return false;
															})
										)
										//Finally append the <li> list to the main content body
										.appendTo($content);
					})	//End of layers.each
					
					
					//Now put the checkbox with each heading
						$heading
							.append(
								$('<span/>')
									.addClass('atMapLayersCounterStatus')
									.append(
											$('<span/>').addClass('atMapLayersCounter'),
											$('<input type="checkbox">')
											.click(function(e){
												//If this is checked than uncheck it and hide all layers in group and viceversa
												if(!$(this).is(':checked'))
												{
													$eventElement.trigger('hideLayerGroup',group.displayName);
													if($(this).parents('.atMainLayersGroup').find('ol').is(':visible')) $heading.trigger('click');
												}
												else
												{
													$eventElement.trigger('showLayerGroup',group.displayName);
													if(!$(this).parents('.atMainLayersGroup').find('ol').is(':visible')) $heading.trigger('click');
												}
												//Stop event to propagate
												Astun.JS.Common.stopEventProp(e);
											})
										)
									.css({
										'position'	: 'absolute',
										'right'		: ($.browser.msie && $.browser.version=="6.0") ? 25 : 4 ,
										'top'		: 3
									})
								)
					//Update the checkbox and counter status of each group
						setTimeout(function() { $eventElement.trigger('updateCheckboxCounter',[group.displayName]); } ,10);
			})	//End of groups.each

			
			//Load the settings cookie and see if any of the group need to be open					 
				eventElement.fire('astun:loadSetting',{
					setting: 'layerPanelOpenGroups',
					loadFunction: function(opened){
									var openGroups = (!!opened) ? opened.evalJSON() : false;
									$.each(openGroups,function(){
										$body.find("h3[aria-labelledby='"+this+"']").trigger('click');
									})
								  }
				});

			//Event handling for query icon
				Event.observe( eventElement, 'astun:resultsReceived', function(event){
					if(event.memo.type && event.memo.type==='findNearest' && !event.memo.displayName) return alert('No results found.');
					$body.find('li').each(function(){
						//Now change the image and css for the current one
						var $queryLink = $(this).find('.atQueryLink'),
							$layerLink = $(this).find('.atLayerLink'),
							queryTitle = $queryLink.attr('title') || '',
							layerTitle = $layerLink.attr('title') || '';
						//If layer is selected
						if($(this).attr('aria-labelledby')==event.memo.displayName)
						{
							//Change the title of the link
							layerTitle = layerTitle.replace('show','hide');
							queryTitle = queryTitle.replace('Show','Hide');
							var
							queryImgLink = 'images/atLayerNoQuery.png',
							queryClass = 'addClass';
						}
						//Un toggle all other Query layers
						else
						{
							//Change the title of the link					
							layerTitle = layerTitle.replace('hide','show');
							queryTitle = queryTitle.replace('Hide','Show');
							var
							queryImgLink = 'images/atLayerQuery.png',
							queryClass = 'removeClass';
						}
							
						//Query icon: Change title and Change the class and img of the icon
						if(queryTitle!='')
							$queryLink
								.attr('title',queryTitle)
								.find('.queryicon:first').attr({'src':queryImgLink, 'alt':queryTitle})
								[queryClass]('atQueryLayerShown');
						//Layer icon: Change title and Change the class and img of the icon
						if(layerTitle!='')
							$layerLink
								.attr('title',layerTitle)
								.find('img:first').attr('alt',layerTitle);
					})
				});
				
				Event.observe( eventElement, 'astun:resultsCleared',  function(event){
					var $selectedLi = $body.find("li[aria-labelledby='"+event.memo.displayName+"']");
						$selectedLi.find('.queryicon').attr('src','images/atLayerQuery.png').removeClass('atQueryLayerShown');
						var $queryLink = $selectedLi.find('a:first');
						var title = $queryLink.attr('title') || '';
						title = title.replace('Hide','Show');
						if(title!='') $queryLink.attr('title',title).find('.queryicon').attr('alt',title);
				} );
		
		
			//Event handling to fade in or out the shown or hidden layers
			$eventElement.bind('layerShown',function(e, layerName)
			{
				//Fade the layer link
				var ln = $body.find("li[aria-describedby='"+layerName+"']")
					ln.fadeTo("fast",1)
						.addClass('active')
						.removeClass('inactive');
				if(ln.find('.atLayerLink').length==0) return;
				//Change the title
				var title = ln.find('.atLayerLink').attr('title').replace('show','hide');
							ln.find('.atLayerLink').attr('title',title).find('img:first').attr('alt',title);
				//Update the counter
				var	gn = ln.parents('.atMainLayersGroup').find('h3').attr('aria-labelledby');
					$eventElement.trigger('updateCheckboxCounter',[gn]);
					
			})
			.bind('layerHidden',function(e, layerName)
			{
				//Fade the layer link
				var	ln = $body.find("li[aria-describedby='"+layerName+"']")
						  ln.fadeTo("fast",o.inactiveLayerFade)
							.addClass('inactive')
							.removeClass('active');
				if(ln.find('.atLayerLink').length==0) return;
			//Change the title
				var title = ln.find('.atLayerLink').attr('title').replace('hide','show');
							ln.find('.atLayerLink').attr('title',title).find('img:first').attr('alt',title);
				//Update the counter
				var	gn = ln.parents('.atMainLayersGroup').find('h3').attr('aria-labelledby');
					$eventElement.trigger('updateCheckboxCounter',[gn]);
			});
			
			/*//Event handling of showing or hiding all layers
			$eventElement.bind('layerGroupShown',function(e, displayName)
			{
				alert('show');
				//Update the counter
					var header = $body.find("h3[aria-describedby='"+displayName+"']");
						header.find(':checkbox').attr('checked','checked')
						header.find('.atMapLayersCounterStatus').trigger('updateCheckboxesCounter')
					
			})
			.bind('layerGroupHidden',function(e, displayName)
			{
				alert('hide');
				//Update the counter
					var header = $body.find("h3[aria-describedby='"+displayName+"']");
						header.find(':checkbox').attr('checked','')
						header.find('.atMapLayersCounterStatus').trigger('updateCheckboxesCounter')
			})*/
		}
	}//End of Plugin
	
	
	// Public: plugin defaults options
	$.fn.showmapcategories.defaults = {
		modeHeaderTxt	: "Show Map Categories",
		eventElement	: 'atMap',
		defaultScale	: 'meters',
		inactiveLayerFade: 0.6,
		togglePanes:true //When we click any of the heading, it will hide the body of all other panes
	};
})(jQuery);









(function($) {
	$.fn.takemeto = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.takemeto.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement));
			$eventElement = $('#'+o.eventElement);

		//Call the function
			preparePanel();
		//Method which will be called after you get the results (layers list)
			function preparePanel() {
				//Save the whole object
					var takeMeTo = data.memo.mapSource.takeMeTo;
				//Check if we got the data
					if(!takeMeTo || typeof takeMeTo.length=='undefined' || takeMeTo.length==0) return !$(panel).remove();
					else $eventElement.trigger(visibilityTriggerEvent,false);

				//Loop through all the links and print them
				$.each(takeMeTo,function(i,link){
					var $link = $('<a href="#"></a>')
									.css({'display':'block','padding':5})
									.append(
										  $('<span/>')
										  	.css('float','left')
										  	.addClass('ui-icon ui-icon-carat-1-e')
										  ,
										  $('<span/>')
										  	.html(link.name)
									)
									.wrap('<div/>')
										.parent()	//The div in above line
										.css({'margin-bottom':3})
										.addClass('ui-state-default ui-corner-all')
										.data('cordsHash',link.easting+'|'+link.northing)
										.bind('mouseenter mouseleave', function(){ $(this).toggleClass('ui-state-hover'); })
										.click(function(){
											//Add active class to myself
												$(this).addClass('active');
											//Now move the map
												$eventElement.trigger('mapMove',link)
											//Toggle layer
												$eventElement.trigger('showLayer',link.layer)
											return false;
										})
										.appendTo($body)
				})
				//Check if map is moved than remove the active class from the links
				$eventElement.bind('mapMove',function(e,newCords){
					if($body.find('.active').data('cordsHash')==newCords.easting+'|'+newCords.northing)
					{
						//Remove active class from other items
							$body.find('.ui-state-active').removeClass('ui-state-active');
						//Remove the active class and the jQuery active class
							$body.find('.active').addClass('ui-state-active').removeClass('active');
					}
				})
			}//End of function setLayers
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.takemeto.defaults = {
		modeHeaderTxt	: "Take Me To",
		eventElement	: 'atMap'
	};
})(jQuery);









(function($) {
	$.fn.mapsourceswitcher = function(panel,visibilityTriggerEvent,data,options) {
		// Extend the options if any provided
			var	 o = $.extend({}, $.fn.mapsourceswitcher.defaults, options),
		//Get the title and body of the panel
		 	$title = $(panel).find('.ui-dialog-title').html(o.modeHeaderTxt),
			$body  = $(panel).find('.ui-dialog-content'),
			eventElement = Element.extend(document.getElementById(o.eventElement));
			$eventElement = $('#'+o.eventElement),
		
		//List is saved in map element in atolMapSourceManager.js line# 59+-
			mpList = $.data(eventElement,'rootMapSource');
		//Check if there is one map source than remove the panel
		if(mpList.length<2) return !$(panel).remove();
		else $eventElement.trigger(visibilityTriggerEvent,false);
			//Hide loader if any
			$eventElement.trigger('loaderDialogVisibility', false);
			$.each(mpList, function(i,mp){
					$('<a href="#"></a>')
						.css({'display':'block','padding':5})
							.append(
								  $('<span/>').css('float','left').addClass('ui-icon ui-icon-carat-1-e'),
								  $('<span/>').html(mp.displayName)
							)
							.wrap('<div/>')
								.parent()//The div in above line
								.css({'margin-bottom':3})
								.addClass('ui-state-default ui-corner-all')
								//Check if this is the selected map source than make it active
								.addClass(($.data(eventElement,'currentlyActiveMapSource')==mp.mapName) ? 'ui-state-active' : '')
								.data('mapName',mp.mapName)
								.bind('mouseenter mouseleave', function(){ $(this).toggleClass('ui-state-hover'); })
								.click(function(e){
									//If it has active class than dont do anything as the map source is already selected
									if(!$(this).hasClass('ui-state-active')) $eventElement.trigger('loadMapSource',[mp.mapName,'ism']);
									//Clear any results on the map
									eventElement.fire( "astun:layerQuery", {'reset': true} );
									//Show loader
									$eventElement.trigger('loaderDialogVisibility', true);
									//Stop event to propagate
									Astun.JS.Common.stopEventProp(e);
									return false;
								})
								.appendTo($body)
			});
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.mapsourceswitcher.defaults = {
		modeHeaderTxt	: 'Show Map',
		eventElement	: 'atMap',
		mainCssClass	: 'atMapSourceSwitcher'
	};
})(jQuery);









(function($) {
	$.fn.basemapswitcher = function(options) {
		// Extend the options if any provided
			var	o = $.extend({}, $.fn.basemapswitcher.defaults, options),
				eventElement = Element.extend(document.getElementById(o.eventElement)),
				$eventElement = $('#'+o.eventElement);

			$eventElement.bind('mapSourceLoaded',function(evt,mapSource,type,name){
				//All possible map sources
				if(type=='root')
				{
					//Save them
					var allMapSources = mapSource.baseMapSources;
					$.data($eventElement, "allMapSources", $.makeArray(allMapSources));
				}
				//Active basemap sources
				else if(type=='ism')
				{
					//Save them
					var currentMSarr = $.makeArray(mapSource.baseMaps);
					//Remove basemap switcher if any
						$('#atJqBaseMapSwitcher').remove();
					//Check if there is only 1 active map source, than just return and dont display anything on map
						if(currentMSarr.length==1) return;
					//Now we create the switcher
						var arrAll = $.data($eventElement,'allMapSources');
						$bmSwitcher = $('<div/>')
										.attr('id','atJqBaseMapSwitcher')
										.addClass('ui-state-active '+ o.mainCssClass)
										.appendTo($eventElement)
										.css({
											'position': 'absolute',
											'top' : 7,
											'right' : 5,
											'z-index' : 10000,
											'border' : 'none',
											'background' : 'none'
										})
										.html($('<ul/>').css({'display':'inline', 'list-style-type': 'none','margin':0,'padding':0}));
					//Compare the 2 lists and create the switcher
						$.each(arrAll, function(){
							var mn = this.mapName, dn = this.displayName;
							if($.inArray(mn, currentMSarr)!=-1)
							{
								//Create button for it
								$('<li/>')
									.append(
										$('<a href="#"></a>')
											.attr({'data-value':mn, 'style': 'cursor: pointer !important'})
											.html(dn)
											.addClass('ui-state-default ui-border-outset')
											.css({'padding':3,'font-size':13,'display':'block','float':'left'})
											.click(function(e){
												//If it has active class than dont do anything as the map source is already selected
												if(!$(this).hasClass('ui-state-active')) $eventElement.trigger('loadMapSource',[mn,'raster']);
												//Stop event to bubble out
												Astun.JS.Common.stopEventProp(e);
												return false;
											})
									)
									.css({'display':'inline','margin':0})
									.appendTo($bmSwitcher.find('ul'))
							}
						});
						//Round corner to the first and last item
						$bmSwitcher.find('ul a:first').addClass('ui-corner-tl ui-corner-bl');
						$bmSwitcher.find('ul a:last').addClass('ui-corner-tr ui-corner-br');
				}
				else if(type=='raster')
				{
					$('#atJqBaseMapSwitcher li a').each(function(){
						//Remove active class from other elements
						$(this).removeClass('ui-state-active ui-border-inset');
						//Add active class to the active element
						if($.trim($(this).attr('data-value'))==$.trim(name)) { $(this).addClass('ui-state-active ui-border-inset') }
						//Change the position of the zoombar if jRibbon is active
						setTimeout(function() { $eventElement.trigger('moveZoomBarWithJRibbon'); $eventElement.trigger('moveZoomBarWithPanelWrapper') } ,2000);
					});
				}
			});
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.basemapswitcher.defaults = {
		eventElement	: 'atMap',
		mainCssClass	: 'atBaseMapSwitcher'
	};
})(jQuery);
