// Author: Pierre-Abraham Rochat - 09.2010
// custom tool built to open a simple div on top of current window
jQuery.fn.minibox = function(options) {
	
	
	settings = jQuery.extend({
		backgroundColor		:'#ffffff',
		maskColor			:'#000000',
		width				:800,
		height				:600,
		maskOpacity			:0.7, 
		maskName			:'miniMask',
		closeImg			: 'close.png'
	}, options);
	

	// this refers here to the selected element
	var _this = this;
	var closeBtn;
	
	var bg = null;
	
	_init ();
		
	function _init () {
		_buildBackground ();
		_buildThis ();
		_setListeners ();
	}
	
	function open () {
		_showBackground ();
		_showThis ();
	}
	
	
	function close () {
		_hideBackground ();
		_hideThis ();
		
		var vPlayer = flowplayer();
		if (vPlayer != null) {
			vPlayer.pause ();
		}
	}
	
	function _setListeners () {
		if (settings ['triggers'] != null) {
			var triggers = settings ['triggers'];
		
			for (var t in triggers) {
				triggers [t].click (function () {open ();})
			}
			
		}
		
		bg.click (function () {
			close ();			
		})
		
	}

	function _showThis () {
		_this.fadeIn ();
		closeBtn.fadeIn ();
	}
	function _hideThis () {
		_this.fadeOut ('slow', _hideBackground);
		closeBtn.fadeOut ('slow');
	}
	
	function _showBackground () {
		bg.stop(true,true).fadeTo ('slow', settings ['maskOpacity']);
		
	}
	function _hideBackground () {
		bg.stop(true, true).fadeOut ('slow');
	}
	
	function _buildThis () {

		var windowWidth = $(window).width();
		var thisWidth = _this.width();
		var  thisId = _this.attr('id');
		var btnId = thisId+"_btn";
		
		closeBtn = '<a href="#" onclick="return false" class="closeBtn" id='+btnId+'><img src="'+settings ['closeImg']+'" /></a>';
		_this.after (closeBtn);
		closeBtn = $("#"+btnId);
		
		var marginLeft = (windowWidth - thisWidth) / 2;
		var closeBtnLeft = marginLeft + thisWidth;
		
	
		closeBtn.hide ();
		closeBtn.click (_hideThis);
		
		settings ['marginLeft'] = marginLeft
		_this.css ({
			position	:'absolute',
			zIndex 		: 10,
			width 		: settings ['width']+'px',
			// height 		: settings ['height']+'px',
			backgroundColor : settings ['backgroundColor'],
			left		: settings ['marginLeft']+'px',
			top			: 100
		})
	
		$(window).resize(function() {
				var windowWidth = $(window).width();
				var thisWidth = _this.width();

				var marginLeft = (windowWidth - thisWidth) / 2;
		  _this.css ({left:marginLeft});
			closeBtn.css ({left:marginLeft});
		});
		
	
		_this.hide ();
		
			closeBtn.css ({
				position 	:'absolute',
				left 		: marginLeft-20, 
				top			: 80, 
				zIndex		: 1000
			});
		
	}
	
	
	function _buildBackground () {
		$('body').append ("<div id='"+settings ['maskName']+"' style='position:fixed; top:0px; left:0px; z-index:9; background-color:"+settings ['maskColor']+";width:100%; height:100%'>&nbsp;</div>");
		
		bg = $("#"+settings ['maskName']);
		bg.hide ();
		
	}
	
	
	return this;
}
