/*
 * $Workfile: jquery.panels.js $
 * $Revision: 13 $
 * $Modtime: 3/08/10 16:04 $
 * $Author: Aamir.afridi $
 *
 * Astun jQuery Panels
 * Copyright (c) 2009 Astun Technology
 *
 * List of panel plugins:
 *	- faultlayers
 *	- findnearest
 *	- markerplacer
 *	- addresssearch (astun_autocomplete)
 *	- searchfor
 *	- layerscatalog
 *	- showmapcategories
 *	- takemeto
 *	- mapsourceswitcher
 *	- basemapswitcher
 *	- panelsaccordion
*/



(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
		preparePanel();

		function preparePanel(evt)
		{
			//Clear the body
				$body.empty();
	
			//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/>'),
			//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()
							{
								//Check if search term provided
								if($.trim($distance.val())=='')
								{
									alert('Please enter the value to search for.');
									return false;
								}
								$eventElement.trigger('loaderDialogVisibility', true);
								eventElement.fire( "astun:layerQuery", {'layer': o.pseudoLayer} );
								return false;
							})
							.appendTo($form),
			//Clear results link
				$clearResults = $('<a/>')
									.attr('href','#')
									.html('Clear results from map')
									.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
			
			$form.appendTo($body);
			
			//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-bottom':3 });
					$form
						.find('option').css('padding','2px');
					$form
						.find('input')
						.css({'float':'right', 'margin':'1px', '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 )
				{
					if(evt.memo.type=="findNearest")
					{
						//Hide the loader and clear result button
						eventElement.fire( 'astun:dataLoadComplete', {} );
					}
					//If results found than show the clear results link
					if(evt.memo.html.indexOf('No results found')==-1)
					{
						$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);
							//If solo map than return
							if(Astun.appType=='solo')
							{
								$body.find('.aw_results').slideUp(o.animationSpeed);
								return;
							}
							writeResults( e, true );
							return false;
						}
						//If textbox value is less the zero than wait untill user type something in
						if($.trim(searchString).length>0)
						{
							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]);
												if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show();//fixing ie error
												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]);
							if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show();//fixing ie error
						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) ? 'auto' : 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
						if($.browser.msie)
						{
							setTimeout(function(){
								$('#atWelcomePanel, #atMap').hide().show();//fixing ie error
							},500);
						}
		
		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 astun_autocomplete 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 astun_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]);
			if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show();//fixing ie error
			
			//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'		: 10,
						'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]); if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show(); });
						//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;
					/*	When we start typing the astun_autocomplete 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 astun_autocomplete call.
						To avoid the conflict, just check if results are 20 than this means that it came from the response of astun_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]);
										if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show();//fixing ie error
									});
									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 toolbar 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]
								});
								//If solo map than return
								if(Astun.appType=='solo') return false;
								//Trigger the go button to hide the results
								searchBtn.data('triggered',true).trigger('click');
								$(window).trigger('resize',[true]);
								if($.browser.msie) $('#atWelcomePanel').hide().show();//fixing ie error
								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]);
			if($.browser.msie) $('#atWelcomePanel, #atMap').hide().show();//fixing ie error
		
		}//End of writeResults function
		

		//Show the current selected address if any in cookie
		//If solo map than return
		if(Astun.appType!='solo')
		{
			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;margin-top:3px" class="ui-icon ui-icon-alert"/> \
					<strong>Error:</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
Original 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.astun_autocomplete = 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).find('p .ui-icon').css('margin-top',0);
		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))
		{
			//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);









(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;
							}),

			//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 results from map')
									.click(function()
									{
										//Empty the textbox
										$distance.val('')
										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);
					}
				}
			
			//Append form to the body
			$form.appendTo($body);
				
			//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', 'width':'100%', 'margin-bottom':3})
					$form
						.find('option,input')
						.css('padding','2px')
					$form
						.find("input")
						.css({'width':'98%', 'padding':'5px 2px'})
					$form
						.find("input[type='submit']")
						.css({'width':'auto', 'float':'right', 'margin':'1px','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
						if(evt.memo.type=='searchISM')
						{
							eventElement.fire( 'astun:dataLoadComplete', {} );
						}
						//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.layerscatalog = function(options) {
		//Before starting anything, check if layers catalog is needed
		if(!astun.enableLayersCatalog)
		{
			return false;
		}
		// Extend the options if any provided and define the vars
			var	o = $.extend({}, $.fn.layerscatalog.defaults, options),
				eventElement = Element.extend(document.getElementById(o.eventElement)),//Event elements
				$eventElement = $('#'+o.eventElement),
				groups = astun.data.memo.layerControl.layerGroups,
				mapSource = $eventElement.data('currentlyActiveMapSource').replace(/[\s\/]+/g, '_') || '',//Replace all special chars with underscores to make a valid cookie name
				mapType = 'int_', //Intranet or ishare
				layersCookieName = 'lyrs_'+mapType+mapSource, //Making the cookie name as short as possible i.e. lyrs = layers because it counts towards the cookie size
				layersStr,//Will hold the layers name
				error=false;
		
		//Check if we have enough groups and layers
		if(!groups || typeof groups.length=='undefined' || groups.length==0)
		{
			return false;
		}
		
		//Try to load the cookie having list of all layers using state manager
		eventElement.fire('astun:loadSetting',
		{
			setting: layersCookieName,
			loadFunction:function(layers)
			{
				//Check if layers is null that means cookie is not there so create the cookie and add the layers to it
				layersStr = (typeof layers=='undefined' || layers=='undefined' || layers==null) ? false : layers
			}
		});
		
		//Remove any previous dialogs
		$('.'+o.mainCssClass).closest('.ui-dialog').andSelf().remove();
		
		//Append an empty div at the end of the body which will be converted to dialog
		var mainDialog = $('<div/>')
						.addClass(o.mainCssClass)
						.css({'padding':4, 'position':'relative','overflow-y':'auto'})
						.attr({'title':o.modeHeaderTxt, 'id':'layersCatalogDialog'})
							.append( $('<div/>').addClass('atLayersCatalogList') )
						.appendTo('body');
		//Define the main body of the dialog
		var $body = mainDialog.find('.atLayersCatalogList');
		
		//Check all the checkboxes and act accordingly
		$eventElement
			.unbind('updateCounter closeLayersCatalog refreshShowMapCategories')
			.bind('updateCounter',function(e,groupDisplayName)
			{
				var 
					//Group selector
					g = $body.find("h3[aria-labelledby='"+groupDisplayName+"']").parent(),
					//Checked layers
					c = parseInt(g.find('ol:first :checkbox:checked').length,10),
					//Total layers
					t = parseInt(g.find('ol:first > li').length,10);
					//Update the counter
					g.find('.atMapLayersCounter').html(c+'/'+t);
					
				//If there is one checkbox checked than check the main group checkbox but fade it out
					g.find(':checkbox:first')
						.attr('checked',(c>0) ? 'checked' : '')
						.fadeTo(1,(c===t || c==0) ? 1 : 0.6);
				//Check if all the checkboxes are checked than check the parent group checkbox as well
				

			})
			.bind('closeLayersCatalog',function()
			{
				//alert('Close LayersCatalog');
				mainDialog.dialog('close');
			})
			.bind('refreshShowMapCategories',function()
			{
				//Empty the body of the shop maps categories
				$('#showmapcategories').empty();
				
				//Recall the plugin
				var $newPanel = $('#showmapcategories').closest('.ui-dialog');
				//Call the plugin again which will update itself automatically with new data
				$newPanel.showmapcategories($newPanel,'',astun.data,{});
			});
		
		
		var $groups = $('<div/>');
		
		//Run loop through main groups and display them
			$.each(groups,function(i,group)
			{
				//Try to find the number of layers in this group, if 0 than return
				if(group.layers.length==0)
				{
					return false;
				}
				
				//If found=true than go and create the header
				var $group		= $('<div/>')
									.addClass('atMainLayersGroup ui-state-default ui-corner-all')
									.css({'background':'#fff', 'margin-bottom':2})
									.appendTo($groups),
					$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-plus')
											.css({'width':16, 'height':16, 'float':'left', 'margin-top':-1})
											,
											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-plus').toggleClass('ui-icon-minus');
													//Scroll to the current group
													$('.'+o.mainCssClass).scrollTo(self, 400, {offset: {top:-4}});
												});
									})
									.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)
					{
						//Check if this layer exists in cookie string, if not than return
						//Enable it just for debuging: if(layer.layerName=='PrimarySchools') layer.layerName='nothing';
						var alreadyAdded = false;
						if(layersStr)
						{
							if($.inArray(layer.layerName, layersStr.split(','))!=-1)
							{
								alreadyAdded = true;
							}
						}

						//Now check the if not visible and not active than return
						if( !layer.initiallyVisible && !layer.active )
						{
							return; //Don't show layers that can't be turned on or off by the user.
						}
						
						//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})
										.addClass('atLayerSet')
										.css({'padding':4, 'padding-bottom':10 ,'margin':2, 'border-bottom' : '1px dotted #ccc', 'position':'relative'})
										.height(22)
										.append(
										   $layerDesc = $('<a/>')
														.css({'display':'block', 'margin-left': 0,'width':'80%', 'position':'relative'})
														.attr('title',(alreadyAdded) ? 'Layer already added. Uncheck the checkbox to remove it.' : 'Check the checkbox to select this layer')
														.addClass('atLayerLink')
														.append(
															$('<img />')
																.attr({'src':layer.icon })
																.css({
																	'position'	: 'absolute',
																	'border' 	: 'none'
																})
															,
															$('<span/>')
																.html(layer.displayName)
																.css({
																	'padding'		: 3,
																	'padding-left'	: 32,
																	'padding-top'	: 5,
																	'display'		: 'block',
																	'font-weight'	: 'normal'
																})
														)
													,
										//Wrapper for the check and options on the right handside of each layer
										$optWrapper = $('<div/>')
														.css({'display': 'block', 'width':'40px', 'margin-top':-20, 'float':'right','text-algin':'right','position':'relative'})
														.append(
															//Checkbox to show the status of visible and hidden layers
															$visibilityCb = $('<input type="checkbox">')
																				.css('float','left')
																				.attr('checked',(alreadyAdded) ? 'checked' : '')
																				.addClass('atLayerChkbox')
																				.addClass(alreadyAdded ? 'added' : '')
																				//Get the title of the actual link on hover
																				.hover(function()
																				{
																					$(this)
																					.attr('title',$(this).parents('li').find('.atLayerLink').attr('rel'))
																				})
																				.click(function()
																				{
																					$eventElement.trigger('updateCounter',[group.displayName]);
																				})
																				.unbind('removeLayerFromMap')
																				.bind('removeLayerFromMap',function()
																				{
																					//If layer has class added and now its uncheck than remove the layer from map as well
																					if($(this).hasClass('added') && !$(this).is(':checked'))
																					{
																						//Hide the layer from map
																						$eventElement.trigger('hideLayer',layer.layerName);
																						//$('#showmapcategories').find("li[aria-describedby='"+layer.layerName+"'] :checkbox:first").trigger('click');
																					}
																				})
															,
															$('<span/>')
																			.css({'float':'left', 'padding-top':2, 'margin-left':3, 'border':'none', 'background':'none'})
																			.append(
																				$('<a/>')
																					.attr('title','Some information about this layer')
																					.html('Information')
																					.addClass('ui-icon ui-icon-info')
																					.click(function()
																					{
																						alert('Layer information');
																					})
																				)
														)
										)
										//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')
											,
											//Checkbox to check or uncheck all layer
											$('<input type="checkbox">')
											.click(function(e)
											{
												//Save the ref
												var 
													$this = $(this),
													list = $this.closest('.atMainLayersGroup').find('li :checkbox');
												//If this is checked than uncheck it and hide all layers in group and viceversa
												list.each(function()
												{
													$(this).attr('checked',($this.is(':checked')) ? 'checked' : '');
												});
												
												//Update the counter
												$eventElement.trigger('updateCounter',[group.displayName]);
												
												//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('updateCounter',[group.displayName]); } ,10);
			})	//End of groups.each
		
		//Append all groups to the body
		$body.append($groups);
		
		//Save the ref to the layers button
		var	$layersBtn = $('#jribbon .bigLayers').closest('.bigJrTool');
						
		mainDialog.dialog({
					modal: true,
					//resizable: true,
					buttons: {"Close": function() { $(this).dialog("close") } },
					closeOnEscape : true,
					draggable: !o.layersBtn,
					width:400,
					height:300,
					minHeight:200,
					minWidth:100,
					close:	function()//On close, destroy the dialog
							{
								$(this).dialog("destroy").remove();
								//Also restore the round corner for the layers button
								$layersBtn.css({
									'-moz-border-radius-bottomleft': 6,
									'-webkit-border-bottom-left-radius': 6
							   });

							}
		 })
		//The reason we are hiding ui-resizable-ne here is that we dont need it but css class is there for infobox plugin.
		.parent().find('.ui-resizable-ne').hide();
		
		
		//Now check if dialog has been called from 'layers button' than add some css to this dialog to give it a look of a drop down
		if(o.layersBtn)
		{
			//Now get the top and left position of the layers button
				l = $layersBtn.offset().left,
				t = $layersBtn.offset().top + $layersBtn.height();
			//Now assign the top and left values to the dialog and also Remove the round corner of top left from dialog
			jQuery('.ui-dialog:last')
				.css({
					'left': l ,
					'top' : t,
					'-moz-border-radius-topleft': 0,
					'-webkit-border-top-left-radius': 0
				})
			//Also remove the bottom left round corner css from the layers button itself
			$layersBtn.css({
						'-moz-border-radius-bottomleft': 0,
						'-webkit-border-bottom-left-radius': 0
					   });
			
		}
		

		//Fix the font size and z-index
			$('.ui-widget-overlay:last').css('z-index',1000000);
			$('.ui-dialog:last')
				.css({'font-size':12, 'z-index':10000000})
				//Add the list icon
				.find('.ui-dialog-buttonpane')
					.append(
						$('<button/>')
							//.css({'padding':'0.2em 0.6em 0.3em', 'margin':'0.5em 0.4em 0.5em 0', 'cursor':'pointer', 'width':'auto', 'float':'right','overflow':'visible', 'line-height':'1.4em'})
							.addClass('ui-state-success ui-corner-all')
							.bind('mouseenter mouseleave',function(){ $(this).toggleClass('ui-state-success-hover') })
							.html('Add layers')
							.click(function(){
								//Check if layers were added already and now they are unchecked than remove it from the map
								$body.find('.atLayerChkbox').trigger('removeLayerFromMap');
								//Now get the layers to add to the cookie
								var layersToAdd = $body.find('.atLayerChkbox:checked');
								if(layersToAdd.length==0)
								{
									alert('No layer is selected. Please select one or more layers to add.');
								}
								else
								{
									//Get the layers name for the selected layers
									var newLayersStr='';
									layersToAdd.each(function()
									{
										newLayersStr += ',' + $(this).closest('.atLayerSet').attr('aria-describedby');
										//If we the option is false than disable the checkbox
										$(this)
											.attr('disabled','disabled')
											//Also fadeout the layers
											.closest('.atLayerSet')
											.fadeTo('fast', o.closeWhenLayersAdded ? 1 : 0.6);
									});
									
									//Update the layersStr
									layersStr = $.trim(newLayersStr).substr(1);
									
									//Now save this in cookie
									eventElement.fire('astun:saveSetting',
									{
										'setting': layersCookieName,
										'value': layersStr
									});
									
									if(o.closeWhenLayersAdded)
									{
										mainDialog.dialog('close');
									}
									
									//Alert on success
									//alert(o.layersSavedMsg);
									
									//Refresh the showMapCategories panel
									$eventElement.trigger('refreshShowMapCategories');
								}
								return false;
							})
					);
			
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.layerscatalog.defaults = {
		modeHeaderTxt	: 'Select layer or group to add',
		eventElement	: 'atMap',
		togglePanes:true, //When we click any of the heading, it will hide the body of all other panes
		mainCssClass	: 'atLayersCatalog',
		closeWhenLayersAdded : true,
		layersSavedMsg : 'Layers saved successfully'
	};
})(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),
			mapSource = $eventElement.data('currentlyActiveMapSource').replace(/[\s\/]+/g, '_') || '',
			lc = astun.enableLayersCatalog;//Create the shortcut for the layers catalog enabler
			ckb = o.useCheckboxForIshare;//Create the shortcut for using checkbox for ishare instead of fadeIn and fadeOut
			
			//Check if 'lc' is true than for sure its intranet so disable(false) 'ckb'
			ckb = lc ? false : ckb;
			
			//Change the opacity of the inactive layers to 1 in layers catalog as it will be handled with checkbox for layers catalog
			if(lc || ckb)
			{
				o.inactiveLayerFade = 1;
			}

		//Load the panel when source is loaded
		preparePanel();
		
		//Check the number of active or inactive links and 'check' the checkbox accordingly
			$eventElement
				.unbind('updateCheckboxCounter openLayersCatalog')
				.bind('updateCheckboxCounter',function(e,groupDisplayName)
				{
					var g = $body.find("h3[aria-labelledby='"+groupDisplayName+"']").parent();
					g.find(':checkbox:first').fadeTo("fast",(g.find('.inactive').length>0 && g.find('.active').length>0) ? 0.6 : 1);
					g.find(':checkbox:first').attr('checked',(g.find('.active').length==0) ? '' : 'checked' );
					//Update the counter
					g.find('.atMapLayersCounter').html(g.find('.active').length+'/'+g.find('ol:first > li').length);
				})
				.bind('openLayersCatalog',function(e,options)
				{
					//debug('"openLayersCatalog" has been triggered from a = '+ e.target.nodeName);
					var options = !options ? '' : options;
					$().layerscatalog(options);
				})
		
		//Adding the edit list button to the title of the panel
		if(lc && $('.atEditLayersList').length==0)
		{
			//Add the 'Edit list' button to the header of the panel
			$(panel)
				.find('.ui-dialog-titlebar')
				.append(
					$('<a/>')
						.attr('href','#')
						.css({'padding':2, 'margin-top':-3, 'display':'block', 'width':60, 'font-size':11, 'float':'right','margin-right':26, 'text-decoration':'none'})
						.addClass('atEditLayersList ui-state-default ui-corner-all')
						.bind('mouseenter mouseleave',function(){ $(this).toggleClass('ui-state-hover') })
						.append(
							$('<span/>').addClass('ui-icon ui-icon-pencil').css('float','left'),
							$('<span/>').html('Edit list').css({'float':'left','padding-left':2})
						)
						.click(function(){
							$eventElement.trigger('openLayersCatalog');
							return false;
						})
				)
		}
		
		
		//Add arrow to the layers button in jRibbon
		var $layersBtn = $('#jribbon .bigLayers').closest('.bigJrTool');
		if($layersBtn.length!=0 && $('#atArrowOpenLC').length==0)
		{
			$layersBtn.append(
				$('<a/>')
					.attr({
						 'href': '#',
						 'title': 'Click to open layers catalog',
						 'id': 'atArrowOpenLC'
					})
					.append(
						$('<span/>')
							.addClass('ui-icon ui-icon-triangle-1-s')
							.css({'margin':'0 auto', 'height':12})
					)
					.css({
						'width' : '100%',
						'display' : 'block',
						'position' : 'absolute',
						'bottom' : 0,
						'padding-bottom':1,
						'border-width' : 0,
						'border-top-width' : 1,
						'border-color':'#fff',
						'background' : 'none',
						'-moz-border-radius-bottomleft': 6,
						'-webkit-border-bottom-left-radius': 6,
						'-moz-border-radius-bottomright': 6,
						'-webkit-border-bottom-right-radius': 6
					})
					.click(function(e)
					{
						var opts = { 'layersBtn':true };
						$eventElement.trigger('openLayersCatalog',[opts]);
						//Now check if layers panel is not opened, than open it so user can see changes
						if(!$(this).closest('.bigJrTool').hasClass('ui-state-hover'))
						{
							$(this).closest('.bigJrTool').trigger('click');
						}
						return false;
					})
					.simpletooltip()
					.hover(
						function(){ $(this).css('background-color', '#E0E0E0'); },
						function(){ $(this).css('background-color', '#fff');}
					)
			)
		}
		
		
		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);
				}
			
			
			/*
			For details read: http://intranet.astun.local/docs/development:story_of_layer_catalog_and_display#user_selects_layer_from_different_map_source
			We are going to see if the cookie with list of layers for the current map source

			So first check if map source is selected as we will try to find a cookie with this name
			Remove all spaces and '/' and replace it with underscores, also check wheather lc is true than we should now that this cookie is for intranet
			*/
			var	mapType = lc ? 'int_' : 'ish_', //Intranet or ishare
				layersCookieName = 'lyrs_'+mapType+mapSource, //Making the cookie name as short as possible
				visibleLayersCookieName = 'vLyrs_'+mapType+mapSource, //vLyrs = Visible layers
				layersStr,//Will hold the layers name
				visibleLayersStr,//Will hold the visible layers name
				error=false;

			//Try to load the cookie having list of all layers using state manager
			eventElement.fire('astun:loadSetting',
			{
				setting: layersCookieName,
				loadFunction:function(layers)
				{
					//Check if layers is null that means cookie is not there so create the cookie and add the layers to it
					layersStr = (typeof layers=='undefined' || layers=='undefined' || layers==null) ? false : layers
				}
			});
			
			
			//If no layers found than simply append this object to the body of the panel.
			var $noLayersFound = $('<div/>')
				.css({'padding':5,'margin':'5px 0'})
				.addClass('ui-state-highlight ui-corner-all')
				.append(
					$('<span/>')
						.css({'float':'left','margin-right':'0.3em'})
						.addClass('ui-icon ui-icon-info')
						,
					$('<span/>')
						.append(
							'<strong>No Layers selected</strong><br>Please select layers from ',
							$('<a/>')
								.attr('href','#')
								.html('layer catalog.')
								.css('text-decoration','underline')
								//Show the layers catalog
								.click(function()
								{
									$eventElement.trigger('openLayersCatalog');
									return false;
								})
						)
				);
			
			
			//Now check if relyOnCookie is true than if the layersStr is false > dont show the layers and show the layers catalog
			if(!layersStr && o.relyOnCookie && lc)
			{
				$body.append($noLayersFound)
				return false;
			}
			
			//Try to load the cookie having list of all VISIBLE layers using state manager
			eventElement.fire('astun:loadSetting',
			{
				setting: visibleLayersCookieName,
				loadFunction:function(vLayers)
				{
					//Check if layers is null that means cookie is not there so create the cookie and add the layers to it
					visibleLayersStr = (typeof vLayers=='undefined' || vLayers=='undefined' || vLayers==null) ? false : vLayers;
				}
			});
			
			
			//If layersStr or visibleLayersStr is false than create a new string and save it in a cookie
			if(!layersStr || !visibleLayersStr)
			{
				//Free the variables and set the flag
				if(!layersStr)
				{
					layersStr = '';
					var saveLayersList = true;
				}
				
				if(!visibleLayersStr)
				{
					visibleLayersStr = '';
					var saveVisibleLayersList = true;
				}
				

				//Loop through all the groups	
				$.each(groups,function(i,group)
				{
					//Create a string of layers and save it in a cookie (must be less than 4kb)
					$.each(group.layers,function(k,layer)
					{
						if( !layer.currentlyVisible && !layer.active )
						{
							return;
						}
						else
						{
							//Create a string of layers displayname but before concatinating check the length of the string should not exceed 4kb
							if(layersStr.length>o.cookieStringLength || visibleLayersStr.length>o.cookieStringLength)
							{
								error=true;
								return;
							}
							else
							{
								layersStr = (saveLayersList) ? layersStr+','+layer.layerName : layersStr;
								//Save only when current layer visiblity is true
								if(layer.currentlyVisible)
								{
									visibleLayersStr = (saveVisibleLayersList) ? visibleLayersStr+','+layer.layerName : visibleLayersStr;
								}
							}
						}
					});//End of inner .each (layer)
				});//End of outer .each (group)	
				
				//Display any error msg
				if(error)
				{
					alert(o.saveBigCookieMsg);
				}

				//Save the list of layers in a cookie
				if(saveLayersList)
				{
					eventElement.fire('astun:saveSetting',
					{
						'setting': layersCookieName,
						'value': $.trim(layersStr).substr(1) //Remove the first comma from the string
					});
				}
			}
			
			
			var $groups = $('<div/>');
			
			//Run loop through main groups and display them
			$.each(groups,function(i,group)
			{
				//Before showing the group header, check if it has at least 1 layer saved in cookie string than display it otherwise return to exit the loop
					var hasLayers = false;
					$.each(group.layers,function(j,layer)
					{
						if( !layer.currentlyVisible && !layer.active )
						{
							return; //Don't show layers that can't be turned on or off by the user.
						}
						//Now check if layer exists in a cookie string we have 'layersStr'
						//if($.trim(layer.layerName)=='JobCentres') return found=false; //Enable this line only for debuging
						if($.inArray(layer.layerName, layersStr.split(','))!=-1)
						{
							return hasLayers=true;
						}
					});
				
				//Check if NOT hasLayers than return (group has no layers so just return and dont go for creating the group header and body)
				if(!hasLayers)
				{
					return;
				}
				
				//If found=true than go and create the header
				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-plus')
											.css({'width':16, 'height':16, 'float':'left', 'margin-top':-1})
										,
										group.displayName
									)
									.click(function()
									{
										//Save ref
										var self=$(this);
										//Hide all other panes if true
										if(o.togglePanes && !$.browser.msie)
										{
											$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:first').toggleClass('ui-icon-plus').toggleClass('ui-icon-minus');
													//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'))
																}
															});
														//Save the open group in cookie
														if(openGroups.length!=0)
														{
															eventElement.fire('astun:saveSetting', {'setting': 'layerPanelOpenGroups', 'value': openGroups.toJSON()});
														}
														//If all groups are closed, delete the cookie
														else
														{
															Astun.JS.Common.setCookie('astun:layerPanelOpenGroups', '', -1 ,'', '');
														}
												})
									})
									.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)
					{
						//Check if this layer exists in cookie string, if not than return
						//Enable it just for debuging: if(layer.layerName=='PrimarySchools') layer.layerName='nothing';
						if($.inArray(layer.layerName, layersStr.split(','))===-1)
						{
							return;
						}
						//Now check the if not visible and not active than return
						if( !layer.currentlyVisible && !layer.active )
						{
							return; //Don't show layers that can't be turned on or off by the user.
						}
						
						//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",($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? 1 : o.inactiveLayerFade)
										.addClass(($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? 'active' : 'inactive')
										.addClass('atLayerSet')
										.css({'padding':4, 'padding-bottom':10 ,'margin':2, 'border-bottom' : '1px dotted #ccc', 'position':'relative'})
										.height(22)
										.append(
										//Show neartest icon
										$queryIcon	= (layer.query && (layer.query.bufferSearch || layer.query.showMy || layer.query.findNearest))
														?
																$('<a/>')
																.css({
																	'position'	: 'absolute',
																	'left'		: 2
																})
																.addClass(lc ? 'atHidden' : '')//Layers catalog setup
																.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': lc ? 0 : 32,'width':'80%', 'position':'relative', 'cursor': (lc || ckb) ? 'default':'pointer'})
														.attr({
															'href' : '#',
															'title': (lc || ckb) ? '' : 'Click to'+ (($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? ' hide ' : ' show ') + layer.displayName + ' on the map.',
															'rel': (!lc || !ckb) ? '' : 'Click to'+ (($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? ' hide ' : ' show ') + layer.displayName + ' on the map.'
														})
														.addClass('atLayerLink')
														.append(
															$('<img />')
																.attr({'src':layer.icon, 'alt': (lc || ckb) ? layer.displayName : 'Click to'+ (($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? ' 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(e,triggeredFrom)
														{
															//Check if the event is triggered from checkbox than allow otherwise return false
															if((lc || ckb) && triggeredFrom != 'checkbox')
															{
																return false;
															}
															//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;
														})
													,
										//Wrapper for the check and options on the right handside of each layer
										$optWrapper = $('<div/>')
														.css({'display': (lc || ckb) ? 'block':'none', 'width': ckb ? 'auto' : 40, 'margin-top':-20, 'margin-right': ckb ? -1 : 0,'text-algin':'right','position':'relative'})
														.append(
															//Checkbox to show the status of visible and hidden layers
															$visibilityCb = $('<input type="checkbox" class="atVckb">')
																				.attr('checked',($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? 'checked' : '')
																				.attr('rel',($.inArray(layer.layerName, visibleLayersStr.split(','))!=-1) ? 'checked' : '')//Just for ie6
																				//Get the title of the actual link on hover
																				.hover(function()
																				{
																					$(this).attr('title',$(this).parents('li').find('.atLayerLink').attr('rel'))
																				})
																				.click(function()
																				{
																					//Disable it so user cannot click it again while the layer is loading, enable it after layer is loaded
																					$(this).attr('disabled','disabled')
																					//Trigger the click event of layer and pass checkbox as string to confirm that it has been triggered from checkbox
																					$(this)
																						.parents('li')
																						.find('.atLayerLink')
																						.trigger('click',['checkbox']);
																					return false;
																				})
															,
															$optionsArrow = $('<span/>')
																			.addClass('atLayerOptionsHandler')
																			.css({
																				'display':ckb ? 'none' : '',
																				'float':'right',
																				'margin-top':
																					($.browser.msie && $.browser.version!='8.0') ?
																					-20
																					:
																					($.browser.mozilla && $.browser.version=='1.9') ?
																					-17
																					:
																					1
																			})
																			//Append the icon
																			.append(
																				$('<span/>').addClass(($.browser.msie && $.browser.version!='8.0') ? 'ui-icon ui-icon-triangle-1-nw' : 'ui-icon ui-icon-triangle-1-se')
																			)
															,
															$options = $('<div/>')
																		.addClass('atLayerOptions ui-state-default ui-corner-all')
																		.css({'position':'absolute','padding':($.browser.msie && $.browser.version!='8.0') ? 2 : 3,'top':0,'margin-top':($.browser.msie && $.browser.version!='8.0') ? -3 : 22,'right':($.browser.msie && $.browser.version!='8.0') ? 12 : -4, 'z-index':5000})
																		.append(
																			//Upward arrow to give the effect of a popup
																			$('<span/>')
																				.addClass('ui-icon ui-icon-triangle-1-n')
																				.css('float','right')
																				.wrap('<span></span>')
																					.parent()
																					.addClass('ui-state-disabled')
																					.css({'display':($.browser.msie && $.browser.version!='8.0') ? 'none' : 'block','margin-top':-14,'float':'right','width' : '100%'})
																			,
																			//Content
																			$('<ul/>')
																				.css({'list-style':'none','padding':0,'margin':0,'width':($queryIcon=='') ? 64 : 80,'text-align':'center'})
																				.append(
																					//Remove icon
																					$('<li/>')
																						.attr('title','Click to remove this layer from the list.')
																						//.simpletooltip({fadeSpeed:1,width:200})
																						.css({'float':'left','margin-right':2,'padding':2,'border':'none','background':'none'})
																						.addClass('ui-state-error')
																						.append(
																							$('<a/>')
																								.attr('href','#')
																								.html('Remove layer')
																								.addClass('ui-icon ui-icon-circle-minus')
																								.click(function(e,isTriggered)
																								{
																									//If triggered from outside than dont show the confirm msg but just delete layer
																									if(!isTriggered)
																									{
																										if(!confirm(o.confirmDeleteLayerMsg))
																										{
																											return false;
																										}
																									}
																									
																									//First check if layer is visible on map than hide the layer and than remove it
																									if($(this).closest('.atLayerSet').hasClass('active'))
																									{
																										$(this).closest('.atLayerSet').find(':checkbox:first').trigger('click');
																									}
																									
																									//Check if the group has not any other layers than remove the group heading as well
																									if($(this).closest('.atMainLayersGroup').find('.atLayerSet').length==1)
																									{
																										//Remove the header
																										$(this)
																											.closest('.atMainLayersGroup')
																											.slideUp(isTriggered ? 0 : 'normal', function()
																																{
																																	//Remove the layer from the DOM
																																	$(this).remove();
																																	//Next check if all the layer and groups are deleted than display the no layers msg
																																	if($body.find('ol').length==0)
																																	{
																																		$body.append($noLayersFound);
																																	}
																																});
																									}
																									else
																									{
																										//Remove the whole layer object from the list
																										$(this)
																											.closest('.atLayerSet')
																											.slideUp('normal',	function()
																																{
																																	//Remove the layer
																																	$(this).remove();
																																	//Update the layers counter
																																	$eventElement.trigger('updateCheckboxCounter',[group.displayName]);
																																});
																									}
																									
																									//Update the cookie
																									//Load the cookie to get the current value
																									eventElement.fire('astun:loadSetting',
																									{
																										setting: layersCookieName,
																										loadFunction:function(layers)
																										{
																											layersStr = (typeof layers=='undefined' || layers=='undefined' || layers==null) ? false : layers
																										}
																									});
																									//Now update the cookie
																									//First check if layername is present in the cookie, only than update the cookie and remove it from the list
																									if(layersStr)
																									{
																										if($.inArray($.trim(layer.layerName), layersStr.split(','))!=-1)
																										{
																											//Remove the layername from the cookie
																											var arr  = layersStr.split(','); //Create an array
																											//Remove the layer name from the array	
																											arr = (arr.length==1) ? '' : jQuery.grep(arr,function(value){ return value != layer.layerName; });
																											//Convert the ammended array back to string
																											layersStr = arr.toString();
																											
																											//If layers string is empty than just delete the cookie altogether
																											if(layersStr=='')
																											{
																												Astun.JS.Common.setCookie('astun:'+layersCookieName, '', -1 ,'', '');
																											}
																											
																											//Save the list of visible layers in a cookie
																											eventElement.fire( 'astun:saveSetting',
																											{
																												'setting': layersCookieName,
																												'value': layersStr
																											});
																										}
																									}
																									return false;
																								})
																							)
																					,
																					//Checkbox for visibility in results
																					$('<li/>')
																						.attr('title','Check to show the results for the layer "' + layer.displayName+'"')
																						.css({'float':'left','margin-right':4})
																						.html(
																							$('<input type="checkbox" class="atInfoClickChkb">')
																								.attr({'disabled':'disabled'})
																								.removeAttr(layer.infoClick=='200' ? 'disabled' : 'rel')
																								//Add or remove it from the cookie
																								.click(saveInCookie)
																						)
																					,
																					//Find nearest icon
																					$('<li/>')
																						.css({'float':'left','margin-right':2,'border':'none','background':'none', 'display':($queryIcon=='') ? 'none' : ''})
																						.addClass('atQueryLink')
																						.append(
																							$('<a/>')
																								.attr('href','#')
																								.html(
																									$('<img src="images/atLayerQuery.png"/>')
																									.height(14)
																									.addClass('queryicon')
																									.css({'margin-bottom':-5, 'border': 'none'})
																								)
																								.hover(function()
																								{
																									$(this)
																									.attr('title',$(this).closest('.atLayerSet').find('.atQueryLink').attr('title'))
																								})
																								.click(function()
																								{
																										$(this).closest('.atLayerSet').find('.atQueryLink').trigger('click');
																										return false;
																								})
																							)
																					,
																					//Information icon
																					$('<li/>')
																						.css({'float':'left','padding-top':2,'border':'none','background':'none'})
																						.append(
																							$('<a/>')
																								.attr('title','Information about this layer')
																								.html('Information')
																								.addClass('ui-icon ui-icon-info')
																								.click(function()
																								{
																									alert(layer.help==null || layer.help ? 'No information found' : layer.help);
																								})
																							)
																				)
																		)
																		//Hide in start
																		.hide()
																		
														)
														//To fix the position if we have a layer name exceeding one line
														.wrap('<div></div>')
															.parent()
															.css({'position':'absolute','right':0,'top':26})
										)
										//Finally append the <li> list to the main content body
										.appendTo($content);
										
					})	//End of layers.each
					
					//CSS for the wrapper for IE6 and other browsers
					var cssObj =	($.browser.msie && $.browser.version=="6.0")
									?
									{
										'position'	: 'absolute',
										'right' : 29,
										'top' : 3,
										'display':'block',
										'width' : (lc) ? 59 : 'auto'
									}
									:
									($.browser.mozilla && $.browser.version=="1.9") ?
									{
										'float'	: 'right',
										'margin-top' : -17,
										'margin-right': 5,
										'display':'block',
										'width' : (lc) ? 59 : 'auto'
									}
									:
									{
										'float'	: 'right',
										'margin-top' : ($.browser.msie && $.browser.version!='8.0') ? -20 : -3,
										'margin-right': ($.browser.msie && $.browser.version!='8.0') ? 5 : 'auto',
										'display':'block',
										'width' : (lc) ? 59 : 'auto'
									}
										
					
					//Now put the checkbox with each heading
						$heading
							.append(
								$('<span/>')
									.addClass('atMapLayersCounterStatus')
									.css(cssObj) //For 'cssObj' see above lines
									.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);
													//Now check if the group is expended than collapse it
													if($(this).parents('.atMainLayersGroup').find('ol').is(':visible'))
													{
														$heading.trigger('click');
													}
												}
												else
												{
													//$eventElement.trigger('showLayerGroup',group.displayName); // See ticket no 3271
													//Show all the layers inside the panel NOT in the group, read the above line
													$(this).parents('.atMainLayersGroup').find('.atVckb').each(function(){
														//Check every checkbox for each layer
														$(this).trigger('click');
													});
													//Now check if the group is collapsed than expend it
													if(!$(this).parents('.atMainLayersGroup').find('ol').is(':visible'))
													{
														$heading.trigger('click');
													}
												}
												//Stop event to propagate
												Astun.JS.Common.stopEventProp(e);
											}),
										//Add the options pop up
										$('<div/>')
											.css({
												 'display': (lc) ? 'block':'none',
												 'position':'relative',
												 'margin-left': lc ? 41 : 'auto',
												 'margin-top' : -19
											})
											.append(
												$('<span/>')
													.addClass('atLayerOptionsHandlerHeading')
													.css({'margin-top':($.browser.msie && $.browser.version!='8.0') ? -20 : 1})
													//Append the icon
													.append(
														$('<span/>').addClass(($.browser.msie && $.browser.version!='8.0') ? 'ui-icon ui-icon-triangle-1-nw' : 'ui-icon ui-icon-triangle-1-se')
													)
												,
												$('<div/>')
													.hide()
													.addClass('atLayerOptionsHeading ui-state-default ui-corner-all')
													.css({'position':'absolute','padding':($.browser.msie && $.browser.version!='8.0') ? 2 : 3,'top':0,'margin-top':($.browser.msie && $.browser.version!='8.0') ? -6 : 22,'right':($.browser.msie && $.browser.version!='8.0') ? 12 : -4, 'z-index':5000})
													.append(
														//Upward arrow to give the effect of a popup
														$('<span/>')
															.addClass('ui-icon ui-icon-triangle-1-n')
															.css('float','right')
															.wrap('<span></span>')
																.parent()
																.addClass('ui-state-disabled')
																.css({'display':($.browser.msie && $.browser.version!='8.0') ? 'none' : 'block','margin-top':-14,'float':'right','width' : '100%'})
														,
														//Content
																$('<ul/>')
																	.css({'list-style':'none','padding':0,'margin':0,'width':20,'text-align':'center'})
																	.append(
																		//Remove icon
																		$('<li/>')
																			.attr('title','Click to remove this layer group.')
																			//.simpletooltip({fadeSpeed:1,width:200})
																			.css({'float':'left','margin-right':2,'padding':2,'border':'none','background':'none'})
																			.addClass('ui-state-error')
																			.append(
																				$('<a/>')
																					.attr('href','#')
																					.html('Remove layer')
																					.addClass('ui-icon ui-icon-circle-minus')
																					.click(function(e)
																					{
																						if(confirm(o.confirmDeleteLayersGroupMsg))
																						{
																							//Now loop through all the layers and trigger the delete layer sign for each layer
																							$(this).parents('.atMainLayersGroup').find('ol').find('.ui-icon-circle-minus').each(function()
																							{
																								$(this).trigger('click',true);
																							});
																							
																							//Also remove the whole group
																							$(this).parents('.atMainLayersGroup').slideUp('normal',function(){$(this).remove()});
																							
																							//Also do the css tweaks again to make the room for the popups
																							$eventElement.trigger('smlpopupCssTweaks');
																						}
																						Astun.JS.Common.stopEventProp(e);
																						return false;
																					})
																			)
																	)
														
														)
											)
									)
								)
							
					var timer;
					//Handling the hide and show of options
					$('.atLayerOptionsHandler, .atLayerOptions, .atLayerOptionsHandlerHeading, .atLayerOptionsHeading')
						.hover(function()
						{
							//clear the timer
							clearTimeout(timer);
							//Hide any other opened options
							$('.atLayerOptions, .atLayerOptionsHeading').hide();
							//Show the current small pop up
							var $popup = $(this).parent().find('.atLayerOptions, .atLayerOptionsHeading');
							$popup.show();
						},
						function()
						{
							//Wait for sometime before hidding it
							var opts = $(this).parent().find('.atLayerOptions, .atLayerOptionsHeading');
							timer = setTimeout(function(){opts.hide(); } ,o.popupHideDelay)
						})
						
						
					//Checkbox 'checked' status update - IE6 only
						setTimeout(function()
						{
							if($.browser.msie && $.browser.version=="6.0")
							{
								//Visibility checkbox
								$body.find('.atVckb').each(function()
								{
									var that = $(this);
									that.attr('checked', that.attr('rel'));
								});
							}
							//Update the checkbox and counter status of each group
							$eventElement.trigger('updateCheckboxCounter',[group.displayName]);
							
						} ,10);
					
			})	//End of groups.each

			//$body.append($groups);
			
			//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  && event.memo.type !=='findNearest') )
					{
						return;
					}
					else if (!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 / check or uncheck the check of for each layer
			$eventElement
			.unbind('layerShown layerHidden')
			.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((lc || ckb) ? 'rel' : 'title').replace('show','hide');
				if((lc || ckb))
				{
					ln
					.find('.atLayerLink')
					.attr('rel',title)
					.find('img:first')
					.attr('alt',title);
				}
				else
				{
					ln
					.find('.atLayerLink')
					.attr('title',title)
					.find('img:first')
					.attr('alt',title);
				}
				
				//Check the checkbox
				if(lc || ckb)
				{
					setTimeout(function(){ln.find(':checkbox:first').attr('checked','checked').removeAttr('disabled')},100);
				}

				//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((lc || ckb) ? 'rel' : 'title').replace('hide','show');
				if((lc || ckb))
				{
					ln
					.find('.atLayerLink')
					.attr('rel',title)
					.find('img:first')
					.attr('alt',title);
				}
				else
				{
					ln
					.find('.atLayerLink')
					.attr('title',title)
					.find('img:first')
					.attr('alt',title);
				}
				//Uncheck the checkbox
				if(lc || ckb)
				{
					setTimeout(function(){ln.find(':checkbox:first').attr({'checked':'','disabled':''})},100);
				}

				//Update the counter
				var	gn = ln.parents('.atMainLayersGroup').find('h3').attr('aria-labelledby');
					$eventElement.trigger('updateCheckboxCounter',[gn]);
			});
			
			$eventElement
			.unbind('smlpopupCssTweaks')
			.bind('smlpopupCssTweaks',function()
			{
				//Not for IE
				if($.browser.msie && $.browser.version!='8.0')
				{
					return false;
				}
				
				//Some css tweaks
				setTimeout(function()
				{
					var t;//Timer
					$body.find('.atMainLayersGroup:last')
						.css('margin-bottom',1)
						//On hover of last heading's popup arrow, increasing the bottom margin so that user can see the popup
						.find('.atLayerOptionsHandlerHeading, .atLayerOptionsHeading, .atLayerOptionsHandler:last, .atLayerOptions:last')
							.hover(
								function()
								{
									//Check if the layer group is collapsed than increase the bottom margin because there is already room for the popup
									var p = $(this).parents('.atMainLayersGroup'),
										$that = $(this);
									if(!p.hasClass('ui-state-active'))
									{
										//clear the timer
										clearTimeout(t);
										p.animate({marginBottom:32},300,function(){
											//Scroll the panel wrapper down
											$('.atPanelInnerWrapper').scrollTo($that,{offset: {top:10000}});
										});
									}
									else if($(this).hasClass('atLayerOptionsHandler') || $(this).hasClass('atLayerOptions'))
									{
										//clear the timer
										clearTimeout(t);
										p.animate({marginBottom:15},300,function(){
											//Scroll the panel wrapper down
											$('.atPanelInnerWrapper').scrollTo($that,{offset: {top:10000}});
										});
									}
								},
								function()
								{
									var that = $(this);
									t = setTimeout(function(){ that.parents('.atMainLayersGroup').animate({marginBottom:1},300); },o.popupHideDelay);
								}
							);
				},100);
			})
			.trigger('smlpopupCssTweaks');	
		}
		
		var layersResultsCookieName = 'rLayers_'+mapSource //Name of the cookie which will hold the name of the layers that the user dont want the results to be displayed when search query is performed
		
		//Functions to check if layer name is included in the cookie / save the layer name in cookie (For the checkbox in small popup with each layer)
		function checkboxHandler()
		{
			//First check all
			$body.find('.atInfoClickChkb').attr('checked','checked');
			var rLayers = false;
			
			//Uncheck those which exist in cookie
			eventElement.fire('astun:loadSetting',
			{
				setting: layersResultsCookieName,
				loadFunction:function(layers)
				{
					//Check if layers is null that means cookie is not there so create the cookie and add the layers to it
					rLayers = (typeof layers=='undefined' || layers=='undefined' || layers==null) ? false : layers;
				}
			});

			//Now check if its not false than uncheck those checkboxes
			if(rLayers)
			{
				$.each(rLayers.split(','),function(i,l)
				{
					$body.find('li[aria-describedby="'+l+'"]').find('.atInfoClickChkb').removeAttr('checked');
				});
			}
		}
		
		//Call it on setTimeout so that it work with IE6 as well
		setTimeout(checkboxHandler,10);
		
		function saveInCookie()
		{
			//IE6 needs setTimeout
			setTimeout(function()
			{
				//Find the layers that are UNchecked
				var vLayersArr=new Array();
				$body.find('.atInfoClickChkb:not(:checked)').parents('.atLayerSet').each(function()
				{
					vLayersArr.push($(this).attr('aria-describedby'));
				})
				//Save it in cookie
				if(vLayersArr.length!=0)
				{
					eventElement.fire('astun:saveSetting',
					{
						'setting': layersResultsCookieName,
						'value': vLayersArr.toString()
					});
				}
				//Delete the cookie
				else
				{
					Astun.JS.Common.setCookie('astun:'+layersResultsCookieName, '', -1 ,'', '');
				}
			},10);
		}
		
	}//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
		cookieStringLength : 4070,
		popupHideDelay : 800,//The time in which the popup will hide itself when user mouseout the popup
		relyOnCookie : true,
		useCheckboxForIshare:true,//User in normal ishare to turn on or off the layer, you can use checkbox instead of fade in and out
		saveBigCookieMsg : 'Saving to many layers failed, This is a known issue and will be fixed in the upcoming version.',
		confirmDeleteLayerMsg:'Are you sure you want to remove this layer?\nNote: You can add this and other layers from layers catalog later again.',
		confirmDeleteLayersGroupMsg:'Are you sure you want to remove all the layers in this group?'
	};
})(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'),/*.css('position','relative')*/
			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');
											}
										)//end of .bind
										.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)
				});
				
				//Remove the bottom margin from the last item
				$body.find('div:last').css('margin-bottom',0);
				
				//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 for only visible map sources
		var mpListVisible = new Array();
		$.each(mpList, function(i,mp) {
			if(mp.hidden) return;
			mpListVisible.push(mp);
		});
		
		//Check if there is one map source than remove the panel
		if(mpListVisible.length<2)
		{
			return !$(panel).remove();
		}
		else
		{
			$eventElement.trigger(visibilityTriggerEvent,false);
		}
			//Hide loader if any
			eventElement.fire( 'astun:dataLoadComplete', {} );
			$.each(mpListVisible, function(i,mp)
			{
				$('<a href="#" rel="Active layer"></a>')
					.css({'display':'block','padding':5})
						.append(
							  $('<span/>').css('float','left').addClass('ui-icon ui-icon-carat-1-e'),
							  $('<span/>').html(mp.displayName)
						)
						.removeAttr(($.data(eventElement,'currentlyActiveMapSource')==mp.mapName) ? 'href' : 'rel')
						.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'))
								{
									return false;
								}
								//If it has NOT active class than load the map
								else
								{
									//Show loader
									$eventElement.trigger('loaderDialogVisibility', true);
									//Stop event to propagate
									Astun.JS.Common.stopEventProp(e);
									//Delete the cookie having the list of visible layers - Ticket no: 3006 Astun.JS.Common.setCookie('astun:visibleLayers', '', -1 ,'', '');
									//Clear any results on the map
									eventElement.fire( "astun:layerQuery", {'reset': true} );
									//Show the message in panels wrapper
									$('#panels').html(
										$('<div/>')
											.css({'text-align':'center','margin':'25px 0','font-size':17})
											.html('Loading panels...')
									);
									//Load the map source - Settimeout is used so that the loader show itself completely
									setTimeout(function(){ $eventElement.trigger('loadMapSource',[mp.mapName,'ism']); },80);
									return false;
								}
								
							})
							.appendTo($body);
			});
			
			//Remove the bottom margin from the last item
			$body.find('div:last').css('margin-bottom',0);
			
	}//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);








(function($) {
	$.fn.panelsaccordion = function(options) {
		// Extend the options if any provided
		var	o = $.extend({}, $.fn.panelsaccordion.defaults, options),
			$container = $(this),
			cookieName = 'panelsaccordionstatus',
			list;
		
		if($.browser.msie)
		{
			$container.css('padding-top',10);
		}
		
		//Wrap inner contents into one main wrapper
		$container.find('.atPanel').each(function(i) {
			if($.browser.msie && $.browser.version=='6.0') $(this).find('.atPanelContent').attr('style','margin-top:5px !important');
			$(this).find('.atPanelContent').wrapAll('<div class="atPanelParentContent" style="position:relative" rel="'+i+'" />');//style="display:block;background:#ccc"
			//Fixing ie bug
			if($.browser.msie)
			{
				$(this).css('margin-top',-4);
				$(this).after('<div style="visibility:hidden;height:1px !important;padding:0;margin:0; line-height:1px"></div>');
			}
			//Give it a height
			var phight = $(this).find('.atPanelParentContent').height();
			phight = phight+10;
			$(this).find('.atPanelParentContent').height(phight);
		});
		
		//Check cookie
		var list = Astun.JS.Common.getCookie(cookieName);
			list = (typeof list=='undefined' || list=='undefined' || list==null) ? false : list;
		
		//If null than hide all but show just the first/indexDefaultOpen content
		if(list)
		{
			//Go through the list and show the content
			jQuery('.atPanelParentContent').hide();
			jQuery.each(list.split(','),function(){ jQuery('.atPanelParentContent').eq(this).show(); })
		}
		else
		{
			$('.atPanelParentContent')
				//Hide all
				.hide()
				//Filter the one which should be shown in the start
				.filter(function(index){ return o.showInStart=='none' ?  false : o.showInStart=='all' ? true : index==o.indexDefaultOpen; })
				.show();
		}
		
		
		//Onclick toggle the content of the panel
		$container
			.find('.atPanelHeader h3')
			.prepend(
				$('<span/>')
					.css({'cursor':'pointer','float':'left','width':12,'display':'block'})
					.addClass('atPanelStatusSign')
			)
			.parent()
			.css('cursor','pointer')
			.attr('title','Click to toggle the contents of this panel.')
			.click(function()
			{
				var that = $(this).addClass();
				//Stop if it is already animated
				if(that.parents('.atPanel').find('.atPanelParentContent').is(':animated')) return false;

				that
					.parents('.atPanel')
					.find('.atPanelParentContent')
						.slideToggle('slow',function()
						{
							$container.trigger('adjustcssclass',true);
						});
				return false;
			});
		
		
		//Add classes to the open and close panels
		$container
			.bind('adjustcssclass',	function(e,clicked)
			{
				//Also change the sign
				$('.atPanelParentContent:hidden').parents('.atPanel').find('.atPanelStatusSign').html('+ ');
				$('.atPanelParentContent:visible').parents('.atPanel').find('.atPanelStatusSign').html('&ndash; ');
				
				if(!clicked) return;
				
				//If save in cookie is false
				if(!o.saveIncookie) return !Astun.JS.Common.setCookie(cookieName, '', -1 ,'', '');
				
				//Save the list of open panels in cookie
				var ar = new Array();
				$('.atPanelParentContent:visible')
					.each(function(){
						ar.push($(this).attr('rel'))
					})
				
				if(ar.length>0)
				{
					Astun.JS.Common.setCookie(cookieName, ar.toString(), 300 ,'', '');
				}
				else
				{
					Astun.JS.Common.setCookie(cookieName, '', -1 ,'', '');
				}
			})
			.trigger('adjustcssclass');
	}//End of Plugin
	
	// Public: plugin defaults options
	$.fn.panelsaccordion.defaults = {
		saveIncookie:true,
		showInStart:'none', //Possible values 'all' : 'none'
		indexDefaultOpen:0 //If cookie not set
	};
})(jQuery);
