(function(){
	
	jQuery.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 = jQuery(options.holder);
		
		// Forming the url of the current page:
		
		var currentURL = window.location.protocol+'//'+window.location.host+window.location.pathname;
		
		// Issuing a GET request. A rand parameter is passed
		// to prevent the request from being cached in IE
		
		jQuery.get(options.url,{url:currentURL,rand:Math.random()},function(response){
		
			// Creating the appreciate button:
			
			var button = jQuery('<a>',{href:'',className:'appreciateBadge',html:'Imprima o cupom'});

			/* if(!response.voted){
				// If the user has not voted previously,
				// make the button active / clickable.
				button.addClass('active');
			}
			else  button.addClass('inactive'); */
			
			button.addClass('active');
			
			button.click(function(){
				if(button.hasClass('active')){

										
					jQuery.blockUI({ message: jQuery('#imprimeform'), css: { width: '275px' } });
					
					jQuery('#imprimirsubmit').click(function() { 
						jQuery.blockUI({ message: jQuery('#question'), css: { width: '275px' } }); 
						
						if(options.count){
						// Incremented the total count
						jQuery(options.count).html('N&uacute;mero de pessoas que j&aacute; imprimiram: ' + (1 + parseInt(response.appreciated))); }
						
						// Sending a GET request with a submit parameter.
						// This will save the appreciation to the MySQL DB.
						
						var jnome= encodeURI(document.getElementById( 'imprimenome' ).value);
						var jemail = encodeURI(document.getElementById( 'imprimeemail' ).value);
		
					
						jQuery.getJSON(options.url,{url:currentURL,submit:1,nome:jnome,email:jemail});
					
						button.removeClass('active').addClass('inactive');
						
					}); 
					

				}
				
				return false;
			});
			
			element.append(button);
			
			if(options.count){
				jQuery(options.count).html('N&uacute;mero de pessoas que j&aacute; imprimiram: ' + response.appreciated);
			}
		},'json');
				
		
		return element;
	}
	
})(jQuery);
