/*
 * Modified by Mojtaba Dashtinejad
 * Added to things:
 * 1: (bug fix) when mousehold occured, the function run immediately first time
 * 2: delay added (third parameter)
*/

/**
 * jQuery mousehold plugin - fires an event while the mouse is clicked down.
 * Additionally, the function, when executed, is passed a single
 * argument representing the count of times the event has been fired during
 * this session of the mouse hold.
 *
 * @author Remy Sharp (leftlogic.com)
 * @date 2006-12-15
 * @example $("img").mousehold(200, function(i){  })
 * @desc Repeats firing the passed function while the mouse is clicked down
 * @url http://remysharp.com/2006/12/15/jquery-mousehold-event/
 *
 * @name mousehold
 * @type jQuery
 * @param Number timeout The frequency to repeat the event in milliseconds
 * @param Function fn A function to execute
 * @cat Plugin
 */

(function ($) {
    $.fn.mousehold = function(timeout, f, delay) {
		var delay = delay || 500;
		
    	if (timeout && typeof timeout == 'function') {
    		f = timeout;
    		timeout = 100;
    	}
    	if (f && typeof f == 'function') {
    		var timer = 0;
			var delaytimer = 0;
    		var fireStep = 0;

    		return this.each(function() {
    			var clearMousehold = function() {
    				clearInterval(timer);
    				clearTimeout(delaytimer);
    				// if (fireStep == 1) f.call(this, 1);
    				fireStep = 0;
    			};

    			$(this).mousedown(function() {
    				fireStep = 1;
    				var ctr = 0;
    				var t = this;

					f.call(t, ctr);
					
    				delaytimer = setTimeout(function () {
						timer = setInterval(function() {
	    					ctr++;
	    					f.call(t, ctr);
	    					fireStep = 2;
	    				}, timeout);
					}, delay);
    			}).mouseout(clearMousehold).mouseup(clearMousehold);
    		});
    	}
    };    
})(jQuery);

