(function($) {
	$.fn.UItoTop = function(options) {
		var defaults = {
			text: '',
			min: 500,
			scrollSpeed: 800,
			containerID: 'toTop',
			containerHoverID: 'toTopHover',
			easingType: 'linear',
			min_width: parseInt($('body').css("min-width"),10),
			main_width: parseInt($('body').css("min-width"),10)/2
		};

		var settings = $.extend(defaults, options);
		var containerIDhash = '#' + settings.containerID;
		var containerHoverIDHash = '#' + settings.containerHoverID;

		$('body').append('<a href="#" id="' + settings.containerID + '">' + settings.text + '</a>');

		var button_width = parseInt($(containerIDhash).css("width")) + 90
		var button_width_1 = parseInt($(containerIDhash).css("width")) + 20
		var max_width = defaults.min_width + button_width;
		var margin_right_1 = -(defaults.main_width + button_width_1)
		var margin_right_2 = -(defaults.main_width - 20)
		
		function top() {
			if(($(window).width() <= max_width) && ($(window).width() >= defaults.min_width)) {
				$(containerIDhash).stop().animate({marginRight: margin_right_2, right: '50%'});
			} else {
				if($(window).width() <= defaults.min_width) {
					$(containerIDhash).stop().css({marginRight: 0, right: 10})
				} else {
					$(containerIDhash).stop().animate({marginRight: margin_right_1, right: '50%'})
				}
			}
		}
		top()
		$(containerIDhash).hide().click(function() {
			$('html, body').stop().animate({scrollTop: 0}, settings.scrollSpeed, settings.easingType);
			$('#' + settings.containerHoverID, this).stop().animate({'opacity': 0}, settings.inDelay, settings.easingType);
			return false;
		})

		.prepend('<span id="' + settings.containerHoverID + '"></span>')
		.hover(function() {
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 1
				}, 600, 'linear');
			}, function() {
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 0
				}, 700, 'linear');
			});

		$(window).scroll(function() {
			var sd = $(window).scrollTop();
			if(typeof document.body.style.maxHeight === "undefined") {
				$(containerIDhash).css({
					'position': 'absolute',
					'top': $(window).scrollTop() + $(window).height() - 50
				});
			}
			if (sd > settings.min) {
				$(containerIDhash).stop(true, true).fadeIn(600);
			} else {
				$(containerIDhash).fadeOut(800);
			}
		});
		$(window).resize(function() {
			top()
		})
};
})(jQuery);