/*	******************************

		API wrapper for PHP api project

		Author: Madrid M. 

		Date: May 2010

		Requires: Jquery + PHP api project

		Notes: 

			Used to be an easy wrapper for the php wrapper I wrote 

			to offer an easy api access. Defaults to json,GET, and the rest url is 

			in the api.config object.

		

		@examples--:

		

		1)-----get data and use a custom callback-----

			api.callMethod("photos.getRecent",{callback:function(data){

				alert(data);

			}});

		

		2)-----a generic submission/post method----- 

			api.callMethod("contest.enterContest",{data:{name:"John Smith",email:"john@gmail.com"}});

			

		3)-----rare use but could be embedded in a different function to poll the last method you just hit with same options

			api.refresh();

		

		

		

******************************	*/

	

	

// Declare Global Namespace

if(typeof(api) == 'undefined') { var api = {};  }

//Set API Settings

api.config = {

	rest: 'api/rest'

};



//can refresh the last method with options you just executed

api.refresh = function() {

	api.callMethod(api.last.method,api.last.options);

}

// Calls api method with ajax

api.callMethod = function(method,options) {

			

		 var defaults = {format:'json',type:'GET',single:false};

		 api.last={method:method,options:options}; //used for refresh()

		 api.locker=false; //used to store lastReponse()

		 var options = $.extend(defaults, options);  //extends default options

		 var defaultData = {method:method,format:options.format};

		 var newData = $.extend(defaultData, options.data);  

		//process our json/text/xml data and callback

		 onSuccess = function(rData){

				if(options.callback) options.callback(rData);

		 };

		 onError = function(xml,errortxt,thrown){

				if(options.onError) options.onError(errortxt);

		 };
 		$.ajax({

		    cache: false,
		    type:options.type,
		    url: api.config.rest,
			data:newData,
			dataType: options.format,
			error: onError,
		    success: onSuccess

		 });

}


