/*
 * SPLASH BOX - a modalvindu created for vb.no
 * 
 * Todo: cleanup, make internal function internal only
 * Todo: make hooks after show, hide
 * Todo: add title field in top right corner
 * 
 */

(function($) {

	$.fn.splashBox = function(settings){
		/* settings */
		settings = jQuery.extend({
	    	'width': 500
	    	, 'height': 400
	    	, 'close': true
	    	, 'overlay': false
	    	, 'timetolive': 0		// settings in milliseconds
	    	, 'event': 'click'		// event to trigger box on
	    	, 'appendto': 'body'	// 
	    	, 'animatemove': true
	    	, 'left': 0
	    	, 'top': 0
	    	, 'href': ''
	    	, 'showtitle': false
	    	, 'id': createUnique(this)
	    	, iframe: false
	    	, afterClose: false
	  	},settings);

		$(this).each(function(){
			$(this).bind(settings.event, function(e){
				$.fn.splashBox.init(this,settings);	
				return false;
			});
		});
		
	}
	
	$.fn.splashBox.init = function(obj,settings){
		/* check for existing box */
		var id = settings.id;
		var jid = '#' + id;
		var exists = checkUnique(id);
		var url = settings.href;
		$(obj).attr("splashid",id);
		
		if (!settings.iframe)
		{
			jQuery.ajax({
				url:  url.length > 0 ? url : $(obj).attr("href")
				, cach: false
				, success: function(html){
					if (!exists){
						$.fn.splashBox.createBox(id,jid,html,settings);
					} 
					else {
						$.fn.splashBox.updateBox(id,jid,html,settings);
					}
					$.fn.splashBox.configBox(jid,id,settings);
					$.fn.splashBox.boxIn(jid,settings);
				}
			});
		}
		else
		{
			// onload="$.fn.splashBox.alertit(this)"
			var iframe = '<iframe id="splash_frame"  width="100%" height="100%" frameborder="0" hspace="0" src="' + url + '"></iframe>';
			

			if (!exists){
				$.fn.splashBox.createBox(id,jid,iframe,settings);
				$.fn.splashBox.boxIn(jid,settings);
			}				
		}
	}
	
	$.fn.splashBox.configBox = function(jid,id,settings){

		// close button
		if (!settings.close) $(jid + ' .splash_close').hide(0);

		// time to live
		if (settings.timetolive > 0 ) setTimeout('$.fn.splashBox.closeBox("'+jid+'")',settings.timetolive);

		// title
		//jQuery(jid + " .splash_title").css("display","none");
		if (settings.showtitle && jQuery("a[splashid="+id+"][title]").length > 0) $.fn.splashBox.getTitle(jid,id);

	}
	
	$.fn.splashBox.getTitle = function(jid,id) {
		var title = jQuery("a[splashid="+id+"][title]").length > 0 
			? jQuery("a[splashid="+id+"]").attr("title")
			: '';
		jQuery(jid + " .splash_title").html(title).css("display","block");
		
	}
	
	$.fn.splashBox.boxIn = function(jid,settings){

		$(jid + ' .splash_bg').css("display","none");
		$(jid + ' .splash_outer').positionBox(settings).fadeIn("slow",function(){
			$(jid + ' .splash_bg').css("display","block");
		});
	
		
	}
	$.fn.splashBox.boxOut = function(jid){
		$(jid + ' .splash_bg').css("display","none");
		$(jid + ' .splash_outer').fadeOut("fast",function(){
			$(jid + ' .splash_bg').css("display","block");
		});	
	}
	
	$.fn.splashBox.getPageScroll = function() {
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}

		return [xScroll, yScroll]; 
	};
	
	var getViewport = function() {
		var scroll = $.fn.splashBox.getPageScroll();

		return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
	};
	
	$.fn.positionBox = function(settings) {
		var viewportPos = getViewport();
		var itemLeft = settings.left == 0  
			? viewportPos[2] + Math.round((viewportPos[0] - settings.width) / 2) - 20
			: settings.left;
		var itemTop	= settings.top == 0
			? viewportPos[3] + Math.round((viewportPos[1] - settings.height) / 2) - 40
			: settings.top;
		var itemOpts = {
			'left':	itemLeft
			, 'top': itemTop
			, 'width': settings.width
			, 'height': settings.height
		}
		if ( $(this).filter(":visible").length == 0 ){
			$(this).css(itemOpts);
		} 
		else {
			$(this).animate(itemOpts,"normal");	
		}
		
		return this;
	}
	
	$.fn.addShadow = function(){
		var positions = "n,ne,e,se,s,sw,w,nw";
		var pa = positions.split(',');
		for (i = 0; i < pa.length; i++)
		{
			$(this).append(
				$(document.createElement("div"))
				.addClass("splash_bg splash_bg_" + pa[i])
			);
		}
		return this;
	}
	
	$.fn.splashBox.createBox = function(id,jid,data,settings)
	{
		var b = $('<div class="splash">' +
					'<div class="splash_outer">' +
						'<div class="splash_inner">' +
							'<div class="splash_close"></div>' +
							'<div class="splash_title"></div>' +
							'<div class="splash_shadow"></div>' +
							'<div class="splash_content"></div>' + 
						'</div>' +
					'</div>' +
					'<div class="splash_overlay"></div>' +
				'</div>').attr("id",id);
		b.appendTo(settings.appendto);
		$(jid + ' .splash_outer')
			.css({ 
				width: settings.width + 'px'
				, height: settings.height + 'px'
		});
		$(jid + ' .splash_close').click(function(){ $.fn.splashBox.closeBox(jid,settings) });
		$(jid + ' .splash_content').append(data);
		$(jid + ' .splash_shadow').addShadow();
		$(jid + ' .splash_overlay').createOverlay(settings);
		return;
	}
	
	$.fn.splashBox.closeBox = function(jid,settings){
		opt = typeof settings == 'undefined' ? {} : settings;
		$.fn.splashBox.boxOut(jid);
		$.fn.removeOverlay(jid);
		if(opt.afterClose) opt.afterClose();

		
	}
	$.fn.removeOverlay = function(jid){
		$(jid + ' .splash_overlay').css("display","none");
	}
	$.fn.createOverlay = function(settings){
		if (settings.overlay)
		{
			
			$(this).css({
					'width': $(window).width()
					, 'height': $(document).height()
					, 'opacity': 0.5
					, 'background': 'white'
					, 'position': 'absolute'
					, 'top': 0
					, 'left': 0
				});
			
			//console.log(overlay);
		}
		return this;
	}
	
	$.fn.splashBox.updateBox = function(id,jid,data)
	{
		$(jid +' .splash_content')
			.fadeOut("fast")
			.html(data)
			.fadeIn("fast");
	}

	/* internal functions */

	var checkUnique = function(id)
	{
		return jQuery("[splashid="+id+"]").length > 0 ? true: false;
		//var id = $(obj).attr("splashid");
		//return typeof id == 'undefined' ? [createUnique(), false] : [id, true];
	}

	var createUnique = function()
	{
		return 'splash-' + Math.ceil(1000*Math.random());	
	}

	$.fn.getAllSplashBoxes = function(){
		var ret = [];
		jQuery(".splash[id]:visible").each(function(i){
			ret.push(jQuery(this).attr("id"));
		});
		return ret;
	}
	
	closeFamilyBox = function(me){
		var traverse = function(obj){
			var myObj = obj;
			if ( obj.nodeName == '#document' || jQuery(obj).attr("class") == 'splash' )
			{
				if ( jQuery(obj).attr("class") == 'splash' )
					$.fn.splashBox.closeBox('#' + obj.id);
			}
			else
			{
				traverse(jQuery(obj)[0].parentNode);
			}
		}
		traverse(me);
	}
	
})(jQuery);