/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @author Alexandre Magno
 * @desc Center a element with jQuery
 * @version 1.0
 * @example
 * $("element").center({
 *
 * 		vertical: true,
 *      horizontal: true
 *
 * });
 * @obs With no arguments, the default is above
 * @license free
 * @param bool vertical, bool horizontal
 * @contribution Paulo Radichi
 *
 */
(function($) {
	$.fn.center = function(params) {
		var op = $.extend({}, $.fn.center.defaults, params);

		return this.each(function() {
			// initializing variables
			var $self = $(this);

			// get the dimensions using dimensions plugin
			var width = $self.width();
			var height = $self.height();
			
			// get the paddings
			var paddingTop = parseInt($self.css("padding-top"));
			var paddingBottom = parseInt($self.css("padding-bottom"));
			
			// get the borders
			var borderTop = parseInt($self.css("border-top-width"));
			var borderBottom = parseInt($self.css("border-bottom-width"));
			
			// get the media of padding and borders
			var mediaBorder = (borderTop + borderBottom) / 2;
			var mediaPadding = (paddingTop + paddingBottom) / 2;
			
			// get the type of positioning
			var positionType = $self.parent().css("position");
			
			// get the half minus of width and height
			var halfWidth = (width / 2) * (-1);
			var halfHeight = ((height / 2) * (-1)) - mediaPadding - mediaBorder;

			// initializing the css properties
			var cssProp = {
				position: 'absolute'
			};

			if (op.vertical) {
				cssProp.height = height;
				cssProp.top = '50%';
				cssProp.marginTop = halfHeight;
			}
			if (op.horizontal) {
				cssProp.width = width;
				cssProp.left = '50%';
				cssProp.marginLeft = halfWidth;
			}

			// check the current position
			if (positionType == 'static') {
				$self.parent().css("position", "relative");
			}
			
			//aplying the css
			$self.css(cssProp);
	   });
	};
	
	$.fn.center.defaults = {
		vertical: true,
		horizontal: true
	};
})(jQuery);
