/**
 * Requires Prototype, jQuery
 * Creator: Peter.goulborn
 * $Revision: 6 $
 * $Author: Peter.goulborn $ 
 * 
 * This file provides interaction with the iSharemaps web services.
 */
 
 Astun.JS.GetData = Class.create({
 });
 
 Astun.JS.GetData.AddressFinder = Class.create( {
	'initialize' : function ( eventElement, getDataURL ) {
	/**
		* Constructor: Astun.JS.GetData.AddressFinder
		* Listens for find address events and calls GetData.aspx to find the 
		* address.
		* This handler is case-insensitive with respect to parameter names, 
		* e.g. foo=bar and FOO=bar are the same.  It does not touch the case of
		* the parameter values.  
		* 
		* Parameters
		* ----------
		* aliases - { object } pairs of parameter names with CSV list of aliases.
		*			 E.g.: {'myparam': 'mp, myparameter'}.  There is no need to 
		*           supply alternatives for different case variants.  The 'key'
		*           will be the name that will be made available by the object.
		* 
		* Returns
		* -------
		* { boolean } - true if valid parameters were found in the URL, 
		*               false otherwise.
		*/
		this.getDataURL = getDataURL;
		this.eventElement = $( eventElement );
	    
		if( jQuery ) {
			this.$eventElement = jQuery( this.eventElement );		
		}
		
		var findAddress = function( searchString, limit, offset ) {
			/**
			* Function: findAddress 
			* Makes a Ajax call  
			*
			* Parameters:
			* searchString - { string } text to search for
			* limit - { integer } number of results to return( default 25 )
			* offset - { integer } where in the results to start from( default 0 )
			*
			* Returns:
			* nothing
			*
			* Events: 
			* Fires astun:addressesFound event with return object as payload
			* This should be:
			* { object } - 'Datatable' object:
			*		{
			*			name,
			*			columns[ 
			*				"UniqueId", 
			*				"Parent", 
			*				"DisplayName", 
			*				"Type", 
			*				"X", 
			*				"Y", 
			*				"Rank", 
			*				"Name", 
			*				"Zoom" 
			*			 ],
			*			data[ 
			*				[ data in column order ],
			*				...
			*			 ]
			*		}
			*
			* 
			*/
				limit = limit || 25;
				if( !offset || offset < 1 ) {
					offset = 0;
				}

				var parameters = {
					'RequestType': 'LocationSearch',
					'location': searchString,
					'pagesize': ( limit + 1 ),
					'startnum' : offset,
					'axuid': new Date().valueOf()
				};
				
				
				var successFunc = function( transport ) 
				{
					var validResponse = false;
					var more = false;
					var results = {};
					
					if( transport.responseText.length ) {
						try {
							results = transport.responseText.evalJSON( );
							validResponse = true;					
							// TODO: should now validate that response is in expected format
						}
						catch( JSONError ) {
							console.warn( JSONError );
						}
					}
					
					if( validResponse ) {
						if( results.data.length > limit ) {
							results.data = results.data.slice( 0, limit );
							more = true;
						}
						this.eventElement.fire( 'astun:addressesFound', { 'results': results, 'limit': limit, 'offset': offset, 'more': more } );
						if( this.$eventElement ) {
							this.$eventElement.trigger( 'addressesFound', [ results, limit, offset, more ] );
						}
					} 
					else {
						this.eventElement.fire( 'astun:addressesNotFound', {} );
						if( this.$eventElement ) {
							this.$eventElement.trigger( 'addressesFound', null, limit, offset, false );
						}
					}
		
				};	//successFunc 
				var callGetData = new Ajax.Request 
				( this.getDataURL, 
					{
						method: 'get',
						parameters: parameters,
						onFailure: function( transport ) 
						{
							alert( "Error: Failed to perform address search!" );
						},
						onSuccess : successFunc.bindAsEventListener( this )			
					}
				); //Ajax request 
		}.bind( this ); //findAddress

		Event.observe( this.eventElement, 'astun:findAddress', function( e ) {
			findAddress( e.memo.searchString, e.memo.limit, e.memo.offset);
		}.bindAsEventListener( this ) );
		
		if( this.$eventElement ) {
			this.$eventElement.bind( 'findAddress', function( evt, searchString, limit, offset) { 
				findAddress( searchString, limit, offset, mapSource );
			} );
		}
		
	} //initialize
}  );//Class.create
