/*********************************************************************************************************
/* Written by Cary Buchmann. (cjbuchmann)
/*
/* April 11, 2011
/*
/* JS AjaxPost
/* 
/* param form - the form we wish to submit
/* param ajaxUrl - the url that we wish to submit to
/* param method - either 'get' or 'post'. NOTE - currently only post works.
/* param useStatusResponse - determines if we'll get a response such as 'data{status : 1}'.
/*
/* JS AjaxPost is a dynamic piece of javascript that will submit any form that does not
/* contain file inputs.
/********************************************************************************************************/

function JSAjaxPost(form, ajaxUrl, method, useStatusResponse)
{
	this.form = form;
	this.url = ajaxUrl;
	this.method = method;
	
	//stores the full site response
	//and the response status of the last request
	this.lastResponse;
	this.lastStatus;
	
	this.debugging = false;
	this.showMessageSent = true;
	
	//set this to true if you intend to return a response in the form data(status=>[status], ...)
	//where status = true if successful or false if not.
	this.useStatusResponse = useStatusResponse; 
	
	var _alert = new JSAlertBox('0');
	var _obj = this;
	
	this.init = function()
	{
		_alert.init();
	}
	
	this.sendAjaxRequest = function(callback)
	{
		var postData = _obj.getAjaxData();
		
		$
		.post(_obj.url, postData, function(data){
			
			var orig = data;
			
			try
			{
				data = $.parseJSON(data);
				
				if(data.status == 1)
				{
					if(_obj.showMessageSent)
						_alert.showAlert("Message Sent", data.message);
				}
				else
				{
					var errors = "";
					
					if(data.errors)
					{
						for(error in data.errors)
						{
							errors += "<div>"+data.errors[error]+"</div>";
						}
					}
					else if(data.error)
					{
						errors+= "<div>"+data.error+"</div>";
					}
					
					status = false;

					_alert.showAlert("Error", errors);
				}
					
				_obj.lastStatus = data.status;
				_obj.lastResponse = data;
				
							
				if(callback)
					callback();
			}
			catch(e)
			{
				_alert.showAlert("Error", "an error occured receiving the server response.");
				
				_alert.showAlert("Debug", "alert with debug "+orig);
				if(_obj.debugging)
					_alert.showAlert("Debug", "alert with debug "+orig);
				
				
				//alert("an error occured receiving the server response. :: "+data);
				_obj.lastResponse = data;
				_obj.lastStatus = false;
				return false;
			}
			
		}) 
		.error(function(data){
			alert("An error occurred connecting to "+_obj.url+". Please try again later.");
			
			if(_obj.debugging)
					_alert.showAlert("Debug", "alert with debug "+data);
			return false;
		});
	}
	
	this.getAjaxData = function()
	{
		return $(_obj.form+" input, "+_obj.form+" textarea, "+_obj.form+" select").serializeArray();
	}
	
	this.getLastRequestStatus = function()
	{
		return _obj.lastStatus;
	}
	
	this.getLastRequestResponse = function()
	{
		return _obj.lastResponse;
	}
}
