/**
 * Requires Prototype, jQuery
 * Creator: Peter.goulborn
 * $Revision: 4 $
 * $Author: Aamir.afridi $ 
 * 
 * This file provides interaction with the iSharemaps web services.
 */
 
 Astun.JS.GetData ={};
 
 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 );
		this.findAddressService = new Astun.JS.GetData.JSONRequester(
			this.getDataURL,
			'callback',
			{
	    		'params': {
					'type': 'jsonp',
					'service': 'LocationSearch'
				}
			}
		);
	    
		if( jQuery ) {
			this.$eventElement = jQuery( this.eventElement );		
		}
		
		var findAddress = function( searchString, limit, offset, showCount ) {
			/**
			* 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;
				}
				offset++ //location search code subtracts 1 from offset for some reason
				
				var parameters = {
					'RequestType': 'LocationSearch',
					'location': searchString,
					'pagesize': ( limit + 1 ),
					'startnum' : offset,
					'gettotals' : showCount || 'false',
					'axuid': new Date().valueOf()
				};
				
				var parseResults = function( json ) {
					var validResponse = false;
					var more = false;
					
					if(json)
					{
						if(json.data)
						{
							// TODO: should now validate that response is in expected format
							validResponse = true;
						}
					}
					else
					{
						validResponse = false;
					}
					
					if( validResponse ) {
						if( json.data.length > limit ) {
							json.data = json.data.slice( 0, limit );
							more = true;
						}
						this.eventElement.fire( 'astun:addressesFound', { 'results': json, 'limit': limit, 'offset': offset, 'more': more } );
						if( this.$eventElement ) {
							this.$eventElement.trigger( 'addressesFound', [ json, limit, offset, more ] );
						}
					} 
					else {
						this.eventElement.fire( 'astun:addressesNotFound', {} );
						if( this.$eventElement ) {
							this.$eventElement.trigger( 'addressesFound', [ null, limit, offset, false ] );
						}
					}
				}.bind( this );
				/* JSONP address search */
				this.findAddressService.request(
					parameters,
					parseResults
				);
				
				
				/* AJAX address search 
				var successFunc = function( transport ) {		
					if( transport.responseText.length ) {
						try {
							results = transport.responseText.evalJSON( );
							parseResults( results );
							// TODO: should now validate that response is in expected format
						}
						catch( JSONError ) {
							console.warn( JSONError );
						}
					}
		
				};	//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, e.memo.showCount);
		}.bindAsEventListener( this ) );
		
		if( this.$eventElement ) {
			this.$eventElement.bind( 'findAddress', function( evt, searchString, limit, offset, showCount) { 
				findAddress( searchString, limit, offset );
			} );
		}
		
	} //initialize
}  );//Class.create


Astun.JS.GetData.JSONRequester = function ( uri, callbackParam, defaults ) {
	   /**
		* Constructor: Astun.JS.GetData.JSONRequester
		* Calls a JSONP webservice and then runs a handler function with the
		* JSON data returned. 
		* !!REQUIRES JQUERY !!
		* 
		* Parameters
		* ----------
		* uri - { String } address of webservice, without querystring
		* callBackParam - { String } the parameter name for the callback 
		*	function; note: this is not the same as the handler function.
		* defaults (optional) - { Object } container for default parameters 
		*	(with values) and handler function, of the form 
		*	{ params, handler }.
		*/
		
	if( !jQuery && !jQuery.getJSON ) {
		return null; //need jQuery getJSON method.
	}
	
	if( 
		( Astun.JS.Common.isString( uri ) && uri.length < 1	)
		&& 
		Astun.JS.Common.isString( callbackFunction )		
	) {
		return null; //no point if these two are not supplied.
	}
	
	
	var pairs = [ callbackParam + '=?' ];
	
	if( defaults ) 
	{
		if( defaults.params ) {
			for( var name in defaults.params ) {
				if ( defaults.params.hasOwnProperty( name ) ) {
					pairs.push( name + '=' + defaults.params[ name ] );
				}
			}			
		}
		if(	
			defaults.handler && 
			typeof defaults.handler === 'function' 
		) {
			this.callHandler = function( json ) {
				defaults.handler( json );
			}
		}
	}
	this.uri = uri + '?' + pairs.join('&');
}
Astun.JS.GetData.JSONRequester.prototype.request = function( params, handler ) {
   /**
	* Function: request
	* Calls a URI for JSON data, using JSONP.  If parameters not specified then 
	*	object defaults used.
	*
	* Parameters:
	* params (optional) - { Object } name: value pairs of  querystring parameters.  Do 
	*	not include callback function parameter, this is set at object 
	*	creation).
	* handler (optional) - { Function } function to call with JSON response as single 
	*	parameter.  Without this, nothing will happen.
	*
	* Returns:
	* nothing, but executes handler function
	* 
	*/
	// Cope if only handler supplied
	if( typeof params === 'function' ) {
		handler = params;
		params = null;
	}
	
	var uriparts = [ this.uri ];
	handler = ( typeof handler === 'function' ) ? handler: this.callHandler;
	
	if( params ) {
		for( var name in params ) {
			if ( params.hasOwnProperty( name ) ) {
				uriparts.push( name + '=' + params[ name ] );
			}
		}		
	}
	
	jQuery.get(
		uriparts.join('&'),
		null,
		handler,
		'jsonp'
	);
	
}


Astun.JS.GetData.GetPrintTemplates = function ( uri, callbackParam, templatePath ) {
	   /**
		* Constructor: Astun.JS.GetData.GetPrintTemplates
		* Calls a JSON webservice and then runs an array of template 
		* filenames and labels.
		* !!REQUIRES JQUERY !!
		* 
		* Parameters
		* ----------
		* uri - { String } address of webservice, without querystring
		* callBackParam - { String } the parameter name for the callback 
		*	function; note: this is not the same as the handler function.
		* templatePath (optional) - { String } path relative to Web root under which
		*	templates are stored.  Webservice will have a default path.
		*/
		
	if( !jQuery && !jQuery.getJSON ) {
		alert( "No jQuery.getJSON method found!" );
		return null; //need jQuery getJSON method.
	}
	
	if( 
		( Astun.JS.Common.isString( uri ) && uri.length < 1	)
	) {
		alert( "No URI for print template webservice!" );
		return null; //no point if these uri not supplied.
	}
	
	
}
