var dialog_config = {
	popups_url: '/skin/displayunlimited/popup/'
};

// ************************************************************************* //

var dialog_cache = {};

function shadow() {
	$('body').append($("<div></div>")
		.attr('class', 'shadow-background')
		.css({
			position: 'absolute',
			left: 0,
			top: 0,
			width: $(window).width(),
			height: $(document).height(),
			background: '#000',
			opacity: 0.6,
			display: 'none'
		}).fadeIn(400));
}

function deshadow() {
	$('.shadow-background').fadeOut(400, function() { $(this).remove(); });
}

function show_error(data, textStatus, errorThrown) {
	shadow();
	alert("Error: " + textStatus);
}

function show_dialog(source, callback) {
	
	var the_dialog;
	var js_obj;
	
	function api() {
		this.closeDialog = function() {
			js_obj.close();	// call cleanup
			the_dialog.fadeOut(400, function() { $('.dialog-ie-iframe').remove(); the_dialog.remove(); });
			deshadow();		
		}
		
		this.switchPanel = function(newPanel, after) {
			the_dialog.find('div.content:visible').fadeOut(400, function() {
				the_dialog.find(newPanel).fadeIn(400, function() { if (after) after(); });
			});
		}
		
		this.send = function(message) {
			
			if (callback) {
				callback(message);
			}
		}
	}
	
	function jsAttach(data, textStatus) {
		try {
			js_obj = eval('(' + data + ')');
			js_obj.init(the_dialog, new api());

			the_dialog.fadeIn(400);
		} catch (e) {
			if (e instanceof SyntaxError) alert("Error: invalid dialog javascript");
			else throw e;
		}
	}

	function dlg(data, textStatus) {
		shadow();

		the_dialog = $(data);
		
		the_dialog.css({
			position: 'absolute',
			display: 'none',
			zIndex: 2
		});
	
		$('body').append(the_dialog);
	
		var pos = {
			left: $(window).width() / 2 - (the_dialog.width() / 2) + $(window).scrollLeft(),
			top: $(window).height() / 2 - (the_dialog.height() / 2) + $(window).scrollTop()
		};
		
		if ($.browser.msie) {
			var iframe = $("<iframe></iframe>");
			iframe.css({
				position: 'absolute',
				left: 0,
				top: 0,
				zIndex: 1,
				opacity: 0,
				width: the_dialog.width(),
				height: the_dialog.height()
			});
			iframe.css(pos);
			iframe.addClass('dialog-ie-iframe');
			$('body').append(iframe);
		}
	
		the_dialog.css(pos);
		
		var js_location = dialog_config.popups_url + source + '.js';
		
		if (dialog_cache[js_location]) {
			jsAttach(dialog_cache[js_location], '');
		}
		else {
			$.ajax({
				url: js_location,
				success: function(data, textStatus) { dialog_cache[js_location] = data; jsAttach(data, textStatus); },
				error: show_error
			});
		}
	}
	
	var html_location = dialog_config.popups_url + source + '.html';
	
	if (dialog_cache[html_location]) {
		dlg(dialog_cache[html_location], '');
	}
	else {
		$.ajax({
			url: dialog_config.popups_url + source + '.html',
			success: function(data, textStatus) { dialog_cache[html_location] = data; dlg(data, textStatus); },
			error: show_error
		});	
	}
}