/**
 * Delay function.
 */
Function.prototype.later = function(ms,s) {
	
	var sf = this,
	f = function() {
		var a = f.arguments,
		lf = function() {
			sf.apply(s,a);
		};
		setTimeout(lf,ms);
	};
	return f;
};

/**
 * Start floatObject.
 */
$(function() {

// set default settig.
var	useAnime = true,	// default is using animation
	hAlign = true,	// default is right
	vAlign = true,	// default is bottom
	paddingX = 20,
	paddingY = 10,
	appearTime = 1;

var wn = $(window),
	dc = $(document),
	fo = $('#floatObject'),
	br = $.browser,
	ie = br.msie,
	vs = br.version,
	de = document.documentElement;

if (!fo.length) {
	alert('floatobject.js need "floatObject" id in the body.');
	return;
}

fo.css('display', 'none');

// get custom setting from tag.
var anime = fo.attr('anime'),
	ha = fo.attr('align'),
	va = fo.attr('vertical-align'),
	px = fo.attr('paddingX'),
	py = fo.attr('paddingY'),
	at = fo.attr('appearTime');

switch (anime.toLowerCase()) {
	case 'true':
		useAnime = true;
		break;
	case 'false':
		useAnime = false;
		break;
	default:
		// do nothing.
		break;
}

switch (ha.toLowerCase()) {
	case 'left':
		hAlign = false;
		break;
	case 'right':
		hAlign = true;
		break;
	default:
		// do nothing.
		break;
}

switch (va.toLowerCase()) {
	case 'top':
		vAlign = false;
		break;
	case 'bottom':
		vAlign = true;
		break;
	default:
		// do nothing.
		break;
}

if (px) {
	paddingX = parseInt(px);
}

if (py) {
	paddingY = parseInt(py);
}

if (at) {
	appearTime = at;
}

// IE6 does not set positon:fixed. so animation is indispensable.
useAnime = ie && (parseInt(vs) <= 6) ? true : useAnime;

var pos = useAnime ? 'absolute' : 'fixed';

fo.css('position', pos).css('z-index', 9999);

wn.resize(startMove);
wn.scroll(startMove);

function startMove() {
	
	var first = false,
		w = ie ? de.clientWidth : window.innerWidth,
		h = ie ? de.clientHeight : window.innerHeight;
	
	if (fo.top == undefined) {
		first = true;
	}
	
	fo.top = vAlign ? h - fo.height() - paddingY : paddingY;
	fo.left = hAlign ? w - fo.width() - paddingX : paddingX;
	
	if (useAnime && !first) {
		if (fo.timer) {
			clearTimeout(fo.timer);
		}
		
		fo.timer = setTimeout(function(){
			fo.top += dc.scrollTop();
			fo.left += dc.scrollLeft();
			fo.animate({
				top: fo.top,
				left: fo.left
			});
		}, 100);
	
	} else {
		fo.css('top', fo.top).css('left', fo.left);
	}
	
	if (first) {
		fo.fadeIn.later(appearTime * 1000, fo)();
	}
}

wn.resize();

});

function closeFloatObject() {
	
	$('#floatObject').fadeOut();
}