(function($) {
$.widget("ui.pinboard", $.extend({}, $.ui.mouse, {
    init: function() {
        var options = this.options;
        this.element.addClass("ui-pinboard");
        this.mouseInit();
    },

    mouseDown: function(e) {
        var options = this.options;
        var targetRect = e.target.getBoundingClientRect();
        if (this.options.selectionType != 'none') {
            this.addPin(e.clientX - Math.round(targetRect.left),
                e.clientY - Math.round(targetRect.top));
        }
    },

    removePins: function() {
        this.element.html('');
    },

    addPin: function(x, y, href) {
        var options = this.options;

        var pinHTML = '<div class="'+this.options.pinClass+'"></div>';
	if (href) {
            pinHTML = '<div class="'+this.options.pinClass+'" onclick="document.location=\''+href+'\';"></div>';
	}
        if (this.options.selectionType == 'single') {
            this.element.html(pinHTML);
        } else {
            this.element.append(pinHTML);
        }
        var newPin = this.element.find('div.pin:last');
        this.element.find('div.pin:last').css('left', (x-newPin.width()/2)+'px').css(
            'top', (y-newPin.height()/2)+'px');

        if ($.isFunction(this.options.pinAdded)) {
            this.options.pinAdded(newPin, x, y);
        }
    },

    destroy: function() {
        this.element.removeClass("ui-pinboard");
        this.mouseDestroy();
    }
}));

$.extend($.ui.pinboard, {
    defaults: {
        pinClass: 'pin',
        selectionType: 'none',
        pinAdded: {},
        pinOver: {},
        pinClick: {}
    }
});
})(jQuery);
