/* Copyright (c) 2008 Maximus_Decimus
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* Copyright notice and license must remain intact for legal use
* jMDPopupWindow
* Version: 1.0 (Aug 28, 2008)
* Requires: jQuery 1.2+
*/
(function($) {
	$.fn.jMDPopupWindow = function(options) {
		//Merge default and user options
		var opts = $.extend({}, $.fn.jMDPopupWindow.defaults, options);
		var buttons = '';
		//create container if not found
		if ($(opts.container).length == 0)
		$('<div id="'+opts.container.slice(1)+'" style="z-index: 1000;"></div>').appendTo("body");

		//create data block if not found
		if ($(opts.data_block).length == 0)
		$('<div id="'+opts.data_block.slice(1)+'"></div>').appendTo("body");

		//initialize
		$(opts.container).css({
			position: "absolute",
			display: "inline"
		}).hide();
		
		$(opts.data_block).hide();
		//$(opts.data_block+" .title .text").html(opts.title);
		//$(opts.data_block+" .content .padding").html(opts.text);
	
		var getPosition = function (e){
			var top = 0;
			var left = 0;
			if (e.pageX || e.pageY) {
				left = e.pageX + opts.topOff;
				top = e.pageY + opts.topOff;
			}
			else {
				left = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft + opts.topOff;
				top = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop + opts.topOff;
			}
			
			if((left + $(opts.container).width()) > document.body.clientWidth)
			{
				left = document.body.clientWidth - $(opts.container).width();
			}
			
			if(opts.oncenter)
			{
				left = (document.body.clientWidth/2) - ($(opts.container).width() / 2);
				top = (document.body.clientHeight/2) - ($(opts.container).height() / 2);
			}
			$(opts.container).css({
				top: top,
				left: left
			});
		};
		// close the popup window
		var closeBox = function(){
			$(opts.container).hide().empty();
		};
 

		$(".MDPopupWindowClose").css({
			cursor: 'pointer'
		})
		$(".MDPopupWindowClose").bind("click", closeBox);

		$(opts.container).show().empty();
		$(opts.data_block).clone(true).show().appendTo(opts.container);
		getPosition(opts.ev);

	}
	// default options
	$.fn.jMDPopupWindow.defaults = {
		ev: 'click',
		topOff: 0,
		leftOff: 0,
		opacity:  1.0,
		buttons: false,
		buttons_onclick: '',
		container: '#MDPopupWindowContainter',
		data_block: '#MDPopupWindowDataBlock',
		title: 'Вход для менеджеров',
		text: '',
		oncenter: true
	};
})(jQuery);
