/*
 *  Adds an annoying Clippy with tips on the page
 *  @author:  H. Yankov (hristo.yankov at gmail dot com)
 *  @version: 1.0.2 (Jan/19/2011)
 *	http://yankov.us
 */

var __clippyOpts;
var __paddingX = 50;
var __paddingY = 50;
 
function __changeClippyText() {
	var msg = __clippyOpts.hints[__getRandomInt(0, __clippyOpts.hints.length - 1)];
	$("div.clippyText").html(msg);
	setTimeout("__changeClippyText();", __clippyOpts.hintChangeTimeOut);
}

function __relocateClippy() {
	var x = __getRandomInt(10, $(document).width() - __paddingX);
	var y = __getRandomInt(10, $(document).height() - __paddingY);
	$("div.clippyContainer").css({ left: x, top: y});
}

function __getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
 
(function($) {
$.fn.addClippy = function(options) {
	var targetNode = $(this);

	// Init
	$.fn.addClippy.defaults = {
		initialPosition: { right: 100, top: 70 },
		initialPositionRandom: false,
		hints: [],
		hintChangeTimeOut: 10000,
		icon: '../info/Clippy.png',
		initialText: 'Help stefano11.it',
		relocateOnHover: false,
		onClickDelegate: function() {}
	}
    __clippyOpts = $.extend({}, $.fn.addClippy.defaults, options);
	
	// Add Clippy's DOM to the page
	targetNode.append(
		"<div class='clippyContainer'>" +
			"<div class='clippyIcon'><img src='" + __clippyOpts.icon + "'></div>" +
			"<div class='clippyText'>" + __clippyOpts.initialText  + "</div>" +
			"<div class='clippyClear'></div>" +
		"</div>"
	);
	
	// Determine the paddings, when the image is loaded
	$("div.clippyIcon > img").load(function() {
		__paddingX = $("div.clippyIcon > img").width() + $("div.clippyText").width();
		__paddingY = $("div.clippyIcon > img").height();
	});
	
	// Clippy should be positioned randomly
	if (__clippyOpts.initialPositionRandom)
		__relocateClippy();
	// Clippy should have a fixed position
	else
		$("div.clippyContainer").css(__clippyOpts.initialPosition);
	
	// Execute a delegate function if Clippy is ever clicked
	$("div.clippyIcon").click(__clippyOpts.onClickDelegate);
	
	// Clippy should be repositioned on hover. LOL.
	if (__clippyOpts.relocateOnHover)
		$("div.clippyIcon").hover(__relocateClippy, function () { });
	
	// Set the timer job to change the hints
	setTimeout("__changeClippyText();", __clippyOpts.hintChangeTimeOut);
};
})(jQuery);
