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

		//initialize
		$(opts.container).css({
			position: "absolute",
			display: "inline"
		}).hide().empty();
		
		$(opts.container).hide();
		
		if(opts.width>0) {
			$(opts.container).css({
				width: opts.width
			})
		}
		
		$('<div class="note-body">'
				+'<div class="title">'
					+'<div class="w100">'
						+'<div class="text"></div>'
						+'<div class="note-close">'
							+'<span class="jWindowClose" style="cursor: pointer;"><img border="0" title="закрыть" alt="закрыть" src="/i/note-close.gif"/></span>'
						+'</div>'
						+'<div class="clear"/>'
					+'</div>'
				+'</div>'
				+'<div class="content small-txt">'
					+'<div class="padding"></div>'
				+'</div>'
			+'</div>'
		).appendTo(opts.container);
		$(opts.container+" .title .text").html(opts.title);
		$(opts.container+" .content .padding").html(opts.text);
	
		var getPosition = function (e){
			var top = 0;
			var left = 0;
			
			if (e.pageX || e.pageY) {
				left = e.pageX - opts.leftOff;
				if(opts.top>0) {
					top = document.body.scrollTop + opts.top;
				} else {
					top = e.pageY + opts.topOff;
				}
			}else {
				left = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft - opts.leftOff;
				if(opts.top>0) {
					top = document.body.scrollTop + opts.top;
				} else {
					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);
			}
			
			$(opts.container).css({
				top: top,
				left: left
			});
		};
		// close the popup window
		var closeBox = function(){
			$(opts.container).hide().empty();
		};
 
		if(opts.fadeout){setTimeout (function() {$(opts.container).fadeOut(1000)}, 5000);}

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

		$(opts.container).show();
		getPosition(opts.ev);
	}
	// default options
	$.fn.jWindow.defaults = {
		ev: 'click',
		topOff: 0,
		leftOff: 50,
		opacity:  1.0,
		container: '#eBox',
		title: 'Подсказка',
		text: 'Текст',
		oncenter: false,
		width: 350,
		top: 0,
		fadeout: false
	};
})(jQuery);
