(function(){
	
	$.appreciateButton = function(options){

		// The options object must contain a URL and a Holder property
		// These are the URL of the Appreciate php script, and the
		// div in which the badge is inserted

		if(!'url' in options || !'holder' in options){
			return false;
		}
		
		var element = $(options.holder);
		
		// Forming the url of the current page:
		
		var currentURL = document.URL;
		
		// Issuing a GET request. A rand parameter is passed
		// to prevent the request from being cached in IE
		
		$.get(options.url,{url:currentURL,rand:Math.random()},function(response){
		
			// Creating the appreciate button:
			
			var button = $('<a>',{href:'',class:'appreciateBadge',html:'Appreciate Me'});

			if(!response.voted){
				// If the user has not voted previously,
				// make the button active / clickable.
				button.addClass('active');
			}
			else button.addClass('inactive');
			
			button.click(function(){
				if(button.hasClass('active')){

					button.removeClass('active').addClass('inactive');
					
					if(options.count){
						// Incremented the total count
						$(options.count).html(1 + parseInt(response.appreciated));
					}
					
					// Sending a GET request with a submit parameter.
					// This will save the appreciation to the MySQL DB.
					
					$.getJSON(options.url,{url:currentURL,submit:1});
				}
				
				return false;
			});
			
			element.append(button);
			
			if(options.count){
				$(options.count).html(response.appreciated);
			}
		},'json');
				
		
		return element;
	}
	
})(jQuery);
