//
// jQuery.fixedLayer.js
//
(function($){
	var _self;
	var cfg = {};
	var defaults = {
		triggerClass: ".bt-popup",
		targetClass:  ".layer-popup",
		triggerEvent: "mouseover"
	};
	
	var isMSIE = function(){
		if(navigator.userAgent.indexOf('MSIE')!==-1){
			return parseInt(navigator.appVersion.toLowerCase().replace(/.*msie[ ]/,'').match(/^[0-9]+/));
		}
		return -1;
	}
	
	var methods = {
		init: function(options){
			cfg = $.extend(defaults, options||{});
			
			return this.each(function(){
				var trigger = $(this).find(cfg.triggerClass);
				var target = $(this).find(cfg.targetClass);
				var show = function(element, duration){
					if(0<isMSIE()&&isMSIE()<9){
						element.show(0);
					} else {
						element.fadeIn(duration);
					}
				}
				var hide = function(element, duration){
					if(0<isMSIE()&&isMSIE()<9){
						element.hide(0);
					} else {
						element.fadeOut(duration);
					}
				}
				
				hide(target, 0);
				
				var collisionDetect = function(x, y){
					var o1 = target.find('p').offset();
					var o2 = target.find('div').offset();
					var b1 = { width:  target.find('p').outerWidth(), height:  target.find('p').outerHeight() };
					var b2 = { width: target.find('div').outerWidth(), height: target.find('div').outerHeight() };
					x = x + $(this).scrollLeft();
					y = y + $(this).scrollTop();
					//console.log((o1.left < e.clientX) && (e.clientX < o1.left+b1.width) && (o1.top < e.clientY) && (e.clientY < o1.top+b1.height));
					//console.log((o2.left < e.clientX) && (e.clientX < o2.left+b2.width) && (o2.top < e.clientY) && (e.clientY < o2.top+b2.height));
					//console.log($(this).scrollTop()+","+e.clientY+","+o1.top+","+o1.top+b1.height);
					//console.log(e);
					return (
						(o1.left < x) && (x < o1.left+b1.width) && (o1.top < y) && (y < o1.top+b1.height)
					) || (
						(o2.left < x) && (x < o2.left+b2.width) && (o2.top < y) && (y < o2.top+b2.height)
					); 
				};
				var onmouseover = function(e){
					if(collisionDetect(e.clientX, e.clientY)===false){
						hide(target, 250)
						$(window).unbind("mousemove", onmouseover);
					}
				};
				trigger.bind(cfg.triggerEvent, function(){
					show(target, 250);
					$(document).bind("mousemove", onmouseover);
				});
			});
		}
	};
	$.fn.fixedLayer = function(method){
		_self = $(this);
			
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.simpleGmap' );
		}
	};
})(jQuery);
