/**
 * @author: Jeremy Manoto
 */


 	/**
 	 * APIMETHODS: Definition of HTTP request types for use with APIHandler
 	 */
	var APIMETHODS = {
		POST: "POST",
		GET: "GET",
		DELETE: "DELETE",
		PUT: "PUT"
	}




	/**
	 * APIHandler: One function to handle all GBP API Calls
	 */
	var APIHandler = base2.Base.extend({
		
		/**
		 * The Callback function to perform after the request
		 */
		Callback: function() {
			
		},

		/* 
		 * METHODS
		 * -------------------------------------------------- */

		constructor: function(options) {
			this.SetOptions(options);
			if (this.Options.Auto) {
				return this.Go();
			}
		},

		SetOptions: function(options) {
			this.defaults = {
				Url: 				'',
				Method: 			APIMETHODS.POST,
				Data: 				{},
				Async: 				false,
				Timeout: 			240000,
				Callback: 			null,
				Cache:				false,
				Auto: 				true,
				OnBefore: 			null,
				OnComplete: 		null,
				OnError:			null,
				UseCacheBuster: 	false,
				ProcessData:		true,
				DataType:			"text",
				ContentType:		"application/x-www-form-urlencoded"
			}

			this.Options = jQuery.extend({}, this.defaults, options);
		},


		/**
		 * Perform the request to the API.
		 * Returns an object with representing the response
		 */
		Go: function() {
			
			var Options = this.Options;
			var method = this.Options.Method;
			var url = this.Options.Url;
			if (this.Options.UseCacheBuster) {
				url = url + "&cache=" + CacheBuster();
			}
			var data = this.Options.Data;
			var apiHandlerObject = this;
			
			this.Response = jQuery.ajax({
								type: method,
								url: url,
								data: data,
								dataType: Options.DataType,
								processData: Options.ProcessData,
								contentType: Options.ContentType,
								timeout: Options.Timeout,
								async: Options.Async,
								cache: Options.Cache,
								
								//Runs before AJAX request is made
								beforeSend: function() {
									if (Options.BeforeSend != null) {
										Options.BeforeSend();
									}
								},

								//If the request was successful
								success: function(response) {
									try {
										apiHandlerObject.Response = apiHandlerObject.FormatResponse(response);
										if (Options.Callback != null) {
											Options.Callback(apiHandlerObject.Response);
										}
									} catch (exception) {
										//Possible User Abort
									}
								},

								//If an error occurs in the request
								error: function(xhr, status, ex) {
									try {
										if (xhr.statusText) {
											var err = (xhr.statusText);
											if (err) 
												ShowError(err, "APIHandler:error");
											else 
												ShowError("Unknown server error.", "APIHandler.error(nostatus)");
										}
									} catch (exception) {
										//apiHandlerObject.ShowError(exception);
									}
									
									if (Options.OnError != null) {
										Options.OnError(xhr);
									}
									
									return;
								},

								//Runs after success/error
								complete: function(xhr, status) {
									if(Options.OnComplete != null) {
										Options.OnComplete(xhr, status);
									}
								}

							});

			if (!Options.Async) {
				this.Response = this.FormatResponse(this.Response.responseText);
			}


		},

		/**
		 * Formats a plain text response into the standard format
		 *  Result: bool
		 * 	ResponseType: "Normal"
		 * 	Message: ""
		 * 	Value: object
		 * 
		 * @param {Object} response
		 */
		FormatResponse: function(responseText) {

			var response;
			try {
				response = JSON.parse(responseText);

				try {
					response.Value = JSON.parse(response.Value);
					//response.Value = eval(response.Value);
				} catch (e) {
					response.Value = eval("[" + response.Value + "]")[0];


				}


			} catch (ex) {
				
				//this.ShowError(ex);
			}


			return response;
		},


		/**
		 * Displays a standard error message
		 * @param {Object} message
		 */
		ShowError: function(message, header) {
			if (header == null) header = "Error";
			//jQuery("<div class='ui-state-error'>" + message + "</div>").dialog({ zIndex: 5000});
			var jGrowlOptions = {
				position: "center",
				theme: "error",
				header: header,
				sticky: true
			}
			jQuery.jGrowl(message, jGrowlOptions);
		},
		
		/**
		 * Aborts an API Request
		 */
		Abort: function() {
			try {
				if (this.Response.abort) {
					this.Response.abort();
				}
			} catch (exception) {
				
			}
		}
	});
	
	
	function CacheBuster() {
		
		return Math.random()*99999999;
		
	}
	
	
	function parseJSON(responseText) {

			var response;
			try {
				response = JSON.parse(responseText);

				try {
					response.Value = JSON.parse(response.Value);
					//response.Value = eval(response.Value);
				} catch (e) {
					response.Value = eval("[" + response.Value + "]")[0];
				}

			} catch (ex) {

				//this.ShowError(ex);
			}

			return response;
		}

	
