/**
 * @author Oakwood Creative - http://oakwood.se
 */

jQuery.fn.crosslog = function(options) {
	
	var defaults = {
		background					: true,
		content							: null,
		fade_speed					: 200,
		width								: 559,
		height							: 500,
		id									: 'crosslog',
		background_id				: 'crosslog_bg',
		background_opacity	: 0.86
	};
	
	var s = $.extend({}, defaults, options);
	
	var scroll_x = scroll_y = viewport_w = viewport_h = inner_w = inner_h = 0;
	
	function window_info() {
		scroll_x = $(window).scrollLeft();
		scroll_y = $(window).scrollTop();
		
		viewport_w = $(window).width();
		viewport_h = $(window).height();
		
		inner_w = window.innerWidth ? window.innerWidth : $(window).width();
		inner_h = window.innerHeight ? window.innerHeight : $(window).height();
	}
	
	this.crosslog_repos = function(width, height){
		var iframe = $('#' + s.id + ' iframe');
		s.width = width;
		s.height = height;
		
		window_info();
		
		var marginTop = - (s.height / 2);
		var top = (inner_h/2) + scroll_y;
		var scrollTop = top + marginTop;
		
		if ( scrollTop < 0 ) {
			scrollTop = top = marginTop = 0;
		}
		$('#' + s.id).css({
			'left'				: (inner_w/2) + scroll_x,
			'top'					: top,
			'marginLeft'	: - (s.width / 2),
			'marginTop'		: marginTop,
			'width'			: s.width
		});
		
		iframe.css({
			'width'			: s.width,
			'height'		: s.height
		});
		
		$(window).scrollTop(scrollTop);
	}
	
	return this.each(function(){
		
		window_info();
		
		var crosslog = $('<div id="'+s.id+'"></div>');
		var crosslog_bg = $('<div id="'+s.background_id+'"></div>');
		
		crosslog.prepend('<a href="#" class="'+s.id+'_close">close</a>').append(s.content).css({
			'left'				: (inner_w/2) + scroll_x,
			'top'					: (inner_h/2) + scroll_y,
			'marginLeft'	: - (s.width / 2),
			'marginTop'		: - (s.height / 2),
			'width'			: s.width
		});
		
		$('.'+s.id+'_close, #'+s.background_id).live('click', function(e){
			e.preventDefault();
			_close();
		});
		
		if (s.background) {
			
			var bg_w = bg_h = 0;
			var position_val;
			var left_val;
			var top_val;
			
			if ( navigator.userAgent.match(/Android/i) ||
			navigator.userAgent.match(/webOS/i) ||
			navigator.userAgent.match(/iPhone/i) ||
			navigator.userAgent.match(/iPod/i) ||
			navigator.userAgent.match(/iPad/i)
			){
				bg_w = $(document).width();
				bg_h = $(document).height();
				position_val = 'absolute';
				left_val = 0;
				top_val = 0;
			} else {
				bg_w = '100%';
				bg_h = '100%';
				position_val = 'fixed';
				left_val = 0;
				top_val = 0;
			}
			
			crosslog_bg.css({
				'position': position_val,
				'width'		: bg_w,
				'height'	: bg_h,
				'left'		: left_val,
				'top'			: top_val,
				'background'	: '#000',
				'opacity'	: s.background_opacity
			}).appendTo($(this)).hide().fadeIn(s.fade_speed);

		}
		
		crosslog.appendTo($(this)).hide().fadeIn(s.fade_speed);
		
		_close = function(){
			$('#'+s.id+', #'+s.background_id).fadeOut(s.fade_speed, function(){
				$(this).remove();
			});
		};
		
	});
	
};

