//simple box
var csbox_class = Class.create({
	// the html of the box
	window: '<div id="csbox"><center>\n\
				\n\
				<div style="overflow: visible; width: 800px; height: 500px; " id="MB_window">\n\
				<div id="MB_frame" style="bottom: 0px;">\n\
					<div id="MB_header">\n\
						<div id="MB_caption"></div>\n\
						<a href="#inspected_item" title="Close window" id="MB_close"><span>×</span></a>\n\
					</div>\n\
					<div id="MB_content" style="overflow: auto; max-height: 451px;">Loading...</div>\n\
				</div>\n\
			</div>\n\
			</center></div>',
	//insert if not already there
	insert_csbox_if_not_there: function(){
		// adding the html of the csbox if not there
		if(!$('csbox')){
			new Insertion.After($('bodycontent-centered'), this.window);
			$('MB_close').observe('click', function(){
				$('csbox').hide();
			});
		}
	},
	//request a url and put it inside the modalbox
	request: function(action, data, caption, synchronous){
		this.insert_csbox_if_not_there();
		$('csbox').show();
		$('MB_content').innerHTML = '<center><img src="/images/csbox_loading.gif"/></center>';

		this.center_element($('MB_window'));
		$('MB_caption').update(caption);

		// if synchronous is not defined, default asynchronous value = true
		var asynchronous = true;
		if(synchronous)
			asynchronous = false;
		
		if(!data){ data = {} }
		data['ajax_menu_action'] = true; // remove header and footer in clasic code pages
		// Based on bug 1048
		// It seems that the http header ajax flag, does not always make it to the server
		// As this is not a fully suporrted flag, we will ensure that only the header and the footer is obtained
		// sending the necessary control falgs to applicaiton
		data['csstandarad_request'] = true;
		data['type']				= 'html';
		data['dataonly']			= true;
		
		// why just updater?,
		// well, because you can call actions that are either in the classic code or in kohana
		// this will send the required flags to only get the contents in between the header and the footer
		return new Ajax.Updater('MB_content', action, {parameters: data,
														onComplete: function(transport) {
															if(console)
																console.info('modal box ajax completed');
														},
														asynchronous: asynchronous
								});

		
	},
	//center the box
	center_element: function(elt)
	{
		var eltDims     = elt.getDimensions();
		var browserDims = document.body.getDimensions();
	
		var y  =  40;// parseInt(window.pageYOffset)  ;
		var x = (browserDims.width - eltDims.width) / 2;

		var styles = {position : 'absolute',
			left     : x + 'px',
			top		 : y + 'px'
		};
		
		elt.setStyle(styles);
		$('MB_window').cumulativeScrollOffset();

	}

});

csbox_class.instance = false;
// this is the helper class for the csbox
var csbox = function(action, data, caption, synchronous){

	if(!csbox_class.instance)
		csbox_class.instance = new csbox_class();

	return csbox_class.instance.request(action, data, caption, synchronous	);
}

