// * modalDialog.js **15/01/2010**V09/4**
// displays modal dialog boxes for main images, related ad images, related feature images, map locations
// using UI/Dialog http://docs.jquery.com/UI/Dialog

/* call as follows in a <script></script> block on your page

	$(document).ready(function() {
	// modal dialog
	modalDialog('modal_i',modal_w,modal_h);
	});
	
	function requires three arguments to be passed in:
	"modal_i" - classname of link you want to trigger a modal dialog
	"modal_w" - modal width
	"modal_h" - modal height
*/

function modalDialog(modal_i,modal_w,modal_h) {
	var myID = "#"+modal_i;
	// check placeholder myID element doesn't already exist before appending it to body, ready to be invoked as a modal
	if ($(myID).length === 0) { 
		$('<div id="'+modal_i+'"><\/div>').appendTo("body");
	}
	// set modal options (see http://docs.jquery.com/UI/Dialog/dialog#options)
	// on close we empty the contents of the placeholder myID div using jQuery's html(""), ready for the next click event
	// note height +36 to allow for sizing of title bar, resize widget
	$(myID).dialog({autoOpen:false,bgiframe:true,close:function(ev,ui){$(myID).html("");},modal:true,overlay:{opacity:0.7,background:'black'},width:modal_w,height:modal_h+36}); 
	// add "Click to close" title to close icon
	$(".ui-dialog-titlebar-close").attr("title","Click to close");
	// bind function to click event of appropriately-classed links
	$("."+modal_i).click(function(){
		// clear any existing titles, eg if page contains related ad/related feature/main image
		$('.ui-dialog-title').html("");
		// get the URL of the link this function is bound to
		var url = $(this).attr("href");
		// get the REL of the link to determine modal behaviour
		var mode = $(this).attr("rel");
		if ($(this)[0].tagName == "AREA") { // link from an imagemap
			mode = "url";
		}
		if (mode == "img") {
			// get the URL of the link this function is bound to
			var url = $(this).attr("href");
			// get the TITLE of the child image this function is bound to
			var title = $(this).children().attr("title");
			// image, appended to myModal div
			$(myID).append('<img src="'+url+'" title="'+title+'" \/>').dialog('open');
		}
		if (mode == "url") {
			// get the TITLE of the link this function is bound to
			var title = $(this).attr("title");
			// add title to modal
			$('.ui-dialog-title').html(title);
			// external content, iframed and appended to myModal div
			$(myID).append('<iframe style="margin:0;padding:0;border:0" src="'+url+'" width="'+modal_w+'" height="'+modal_h+'"><\/iframe>').dialog('open');
		}
		// stop the browser from following the link if JS is enabled, forcing it to be handled in a modal
		return false;
	});
}
