var modals = {

	// permit the width values to be accessed from 
	modalWidth: false,
	modalHeight: false,
	
	start: function() {

		$('a.modal').each( function( modalIndex ) {

			modals.add_frame( modalIndex ); 
			var href = $(this).attr('href');
			if (href.indexOf('://') == -1) href = '/modals' + href;
			$(this).attr('href', href);
			$(this).bind( 'click', function(e) {
				e.preventDefault();		
				modals.open_window(href, $(this).attr('title'), modalIndex );
			});
		});
		
		$('.modalClose, .jqmOverlay').unbind('click');
		$('.modalClose, .jqmOverlay').click( function() {
			modals.close_window();
		});		


		$('.modalDialog span').jqDrag('#modalTitle span');
	},

	add_frame: function( modalIndex ) {
		$('#document').append('<div class="jqmWindow" id="modal' + modalIndex + '">' + 
			'<div class="modalDialog"><div class="modalTitle"><a href="javascript:;" class="modalClose">x</a><span></span></div>' + 
			'<iframe frameborder="0" id="jqmContent" src="" width="640" height="390" ></iframe></div></div>');	
	},
	
	open_window: function(url, title, modalIndex){    

		$('.modalTitle span').text( title );

		// calculate the height of the modal box (it will only contain iframes so the need fixing relative to the
		// height of the page do this each time the page is called so it will take window resizes into account 
		
		var width;
		var height;
		
		// unless defined, fit the modal window 
		// to the viewport width -300
		if ( modals.modalWidth == false ) {
			var windowWidth = $(window).width();
			width = windowWidth - 300;
		} else {
			width = modals.modalWidth;
		}
		

		
		// similarly for window height
		if ( modals.modalHeight == false ) {
			var windowHeight = $(window).height();
			height = windowHeight - 100;
		} else {
			height = modals.modalHeight;
		}
		
		// apply the CSS to 
		$('.jqmWindow').css( 'top', '50px' );
		$('.jqmWindow').css( 'margin-left', '-' + (width/2) + 'px' );
		$('.jqmWindow').height( height + 35 );
		$('.modalDialog iframe').width( width );
		$('.modalDialog iframe').height( height );
		$('.modalDialog iframe').height( height - $('.modalTitle').height() - 35 );

		var dialog = $('#modal' + modalIndex).jqm({ 
			modal: true,
			onShow: function(h) {
				var $modal = $(h.w);                
				var $modalContent = $("iframe", $modal); 
				$modalContent.html('').attr('src', url); 
				if (height > 0) $modal.height(height);    
				if (width > 0) $modal.width(width);    
				h.w.show();          
			} 
		}).jqmShow()        
			
		$('#modal' + modalIndex + ' .modalClose, .jqmOverlay').unbind('click');
		$('#modal' + modalIndex + ' .modalClose, .jqmOverlay').click( function() {
			modals.close_window();
		});
	},
	
	close_window: function( postback ) {
		$('.jqmWindow').jqmHide();	
		$('.jqmWindow iframe').attr('src', '');
	}
	
};



$(modals.start);
