/*
 * jQuery plugin for ajax deletion from the database
 * 
 */
(function($){
    $.fn.mtDeleter = function(options){
    
        var defaults = {
			trigger: ".delete",		//Delete trigger
			deleteClass: "",		//Where to get delete id, if empty the id is retrieved from the clicked element
			deleteKey: "",			//The delete key for dataString
			extraKey: "",			//Ugly fix for delete issue
			alertMessage: "", 		//Send in a nice alertMessage.
			action: function(){},
			callBack: function(){},
			showTrueTime: 2000
        };
        
        var options = $.extend(defaults, options);
        
		
        return this.each(function(){
			
			var obj = $(this);
			
			
			$(options.trigger, obj).live("click",function(){
				
				var id;
				if (options.deleteClass != "") {
					id = $(options.deleteClass).attr("id");
				}else{
					id = $(this).attr("id");	
				} 
				
				/*
				 * Build the dataString based on the key
				 */
				var dataString = options.deleteKey + "=" + id;
				
				/*
				 * Ugly fix for the call from delete issue form
				 */
				if (options.extraKey.length > 0) {
					//for(key in options.extraKeys){
						dataString += "&" + options.extraKey + "=" + $(":input[name='" + options.extraKey + "']", obj).val();
					//}
				}
				
				
				/*
				 * Confirm delete action
				 */
				jConfirm(options.alertMessage.stripHTML(), "Bekräfta", function(response){
					if(response)
						doAjaxDelete(dataString, options.action)
				});
				
			});
		
		
	
        });
        /* End of each */
        
		/*
		 * Do the actual delete in the database
		 */
        function doAjaxDelete(dataString, action){
        	
			$.mtMessage.showLoader("");
		
	        $.ajax({
	            type: "POST",
	            url: action,
	            data: dataString,
				dataType: 'json',
	            success: function(response){
	                showMessage(response);
	            }
	        });
	    }
		
		
		/*
		 * Show the response message
		 */
		function showMessage( response ){
            $.mtMessage.showMessage( response, options.callBack, options.showTrueTime  );
        }
        
    };
    /* End of wrapper function */

})(jQuery);
