/**
 * @author apipkin
 * 
 * changes:
 * 		<div class="dropBox">
 * 			<h2>Content</h2>
 * 		</div>
 * 
 * into:
 * 		<div class="dropBox">
 * 			<div class="db_tl">
 * 				<div class="db_tr">
 * 					<div class="db_content">
 * 						<h2>Content</h2>
 * 					</div>
 * 				</div>
 * 			</div>
 * 			<div class="db_bl">
 * 				<div class="db_br">
 * 				</div>
 * 			</div>
 * 		</div>
 * 
 * for expandabling box styling
 * 
 * 
 * adds hover function to copy drop box to a ul in the menu option
 */


$().ready(function(){
	
	$('.dropBox').wrapInner('<div class="db_tl"><div class="db_content"></div><div class="db_tr"></div></div>')
	             .append('<div class="db_bl"><div class="db_br"></div></div>');

	$('#mainMenu li').hover(function(){
		// check to see if the element is already moused over
		if($(this).hasClass('hover'))
		{
			return 0;
		}
		
		// fix the element for ie 6
		$(this).addClass('hover');
		
		// get the id from the element
		var id = $(this).attr('id').replace('mm','');
		
		// add an element to contain the drop box
		$(this).append('<ul></ul>');
		
		// create target for drop box container
		var dbc = $('#mm'+id+' ul');
		
		// copy the drop box to the element
		if($('#db'+id).text() != '')
		{
			$(this).children().filter('a').addClass('hasBox');
		}else{
			return;
		}
		dbc.append($('#db'+id).clone());
		
               dbc.find('.db_bl').width(dbc.find('.db_tl').width());

		// get center x
		var mmw = parseFloat($('#mm'+id).width());
		var ulc = parseFloat(dbc.width());
		var newX = (parseFloat($('#mm'+id).width())/2) - (parseFloat(dbc.width()) / 2);
		
		// reposition		
		dbc.css('left',newX);
		
		// check if center x plus width is past page edge
		var pageCords = ObjectPosition($('#headWrapper'));
		var dbCords = ObjectPosition(dbc);
		
		// calculate and test for overage
		var overage = (dbCords[0] + dbc.width())-pageCords[0] - $('#headWrapper').width() + 14;
		if(overage > 0)
		{
			dbc.css('left',newX - overage);
		} 
		heightFix(dbc);
		
	},function(){
		$(this).removeClass('hover');
		$(this).children().filter('a').removeClass('hasBox');
		$(this).children().filter('ul').remove();
	});
});

function heightFix(dbc)
{
}


function ObjectPosition(obj)
{
	var curleft = 0;
	var curtop = 0;
	obj = obj[0];
	if(obj.offsetParent)
	{
		do{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}
