/**
 * impDDM plugin for dropdown menu
 * September 23, 2009
 * Andrew Timonin @ http://www.impsite.com/
 */

jQuery.fn.impddm = function(options){

    var options = jQuery.extend({
        timer: 500,
        animationSpeed: "slow",
        allwaysShow: false
    }, options);
        

    return this.each(function() {
        var parentPointer = jQuery(this);        
        var id = parentPointer.attr('id');
        var tmp = parentPointer;
        var childPointer;
        var timeout;
        while (1)
        {        
        	if (tmp.length == 0)
		       	return;
		    childPointer = tmp.find("#" + id + "_dropdown");        		    
		    if (childPointer.length != 0)
		    	break;
		    tmp = tmp.parent();        
		}		

        // Parent action
        parentPointer
        .click(function() {
            if(childPointer.data("status") == "opened") {
                dropdownClose();
            } else {
                dropdownShow();
            }
            return false;
        })
        .mouseup(function() {return false;})
        .mouseover(dropdownMouseOver)
        .mouseout(dropdownMouseOut); 

        // Child action
        childPointer
        .mouseup(function() {return false;})
        .mouseover(dropdownMouseOver)
        .mouseout(dropdownMouseOut);

        $(document).mouseup(dropdownClose);

        function dropdownShow() {        	
            childPointer.slideDown(options.animationSpeed).data("status", "opened");
            parentPointer.addClass('selected');
        }

        function dropdownClose() {
            childPointer.slideUp(options.animationSpeed).data("status", "closed");
            parentPointer.removeClass('selected');
            if (timeout) {clearTimeout(timeout);}
        }

        function dropdownMouseOut() {
            if(!options.allwaysShow) {
                if(childPointer.data("status") == "opened") {
                    timeout = setTimeout(dropdownClose, options.timer);
                }
            }
        }

        function dropdownMouseOver() {
            if (timeout) {clearTimeout(timeout);}
        }

    });
};