var activeMenuId = '';      // The most recent active menuItem
var activeSubMenuId = '';      // The most recent subMenu - if you hover over a new sub menu this is so it knows to fade out the old one first.
var subMenuCountdown = 0; // Seconds until the sub menu is faded out.
var subMenuTimeout = 2;   // seconds until subMenu is faded out.
var subMenuTimer; // A reference to the timeout, so it can be deleted.

function rt3_dashboard_menu(sourceObject,event, topUrl, bottomUrl, subMenuId) {
	// Event is the click event object that contains properties of the event.
	// Object is the reference to the object that the mouse acted on,
	if(!sourceObject == undefined || !sourceObject) {
	  object = returnEventObject(event);
	} else {
		object = sourceObject;
	}
	if(event.type == 'click') { // if it was a Mouse Click
		$('div.rt3_dashboard_menu_link').attr('class', 'rt3_dashboard_menu_normal rt3_dashboard_menu_link'); // Reset all other buttons to look 'normal'
		$(object).attr('class','rt3_dashboard_menu_active rt3_dashboard_menu_link'); // change the look of the button clicked to appear "active"
		activeMenuId = $(object).attr('id');
		// in the event this div doesn't have a subMenu, we should hide any other subMenu's that might be showing!
		if(subMenuId == undefined || !subMenuId) {
			$('div.rt3_dashboard_submenu_link').attr('class', 'rt3_dashboard_submenu_normal rt3_dashboard_submenu_link'); // Reset all submenu's links to 'normal'
			rt3_dashboard_submenu_hide_all(false);
		}
		if(topUrl != undefined && topUrl) { // Seeing this was a click event we need to actually load some divs!
		  $.ajax({
		   url: LEAF_URL_ROOT + "/" + topUrl,
		   data: 'candidate='+candidateHash,
		   cache: false,
		   success: function(result) {
		    $('#' + topDivId).html(result);
		   }
		  });
		}
		if(bottomUrl != undefined && bottomUrl) { // We've loaded the top Div, now we need to load the Bottom Div!
		  $.ajax({
		   url: LEAF_URL_ROOT + "/" + bottomUrl,
		   data: 'candidate='+candidateHash,
		   cache: false,
		   success: function(result) {
		    $('#' + bottomDivId).html(result);
		   }
		  });
		}
	} else if(event.type == 'mouseover') {
		if(!$(object).hasClass('rt3_dashboard_menu_active')) {
			$(object).attr('class', 'rt3_dashboard_menu_hover rt3_dashboard_menu_link');
		}
		subMenuObject = $('#'+subMenuId);
	    if($(subMenuObject).attr('id') != undefined) {
        	rt3_dashboard_submenu_toggle(event, subMenuObject, object); // Toggle the subMenu
	    }
	} else if (event.type == 'mouseout') {
		if(!$(object).hasClass('rt3_dashboard_menu_active')) {
			$(object).attr('class', 'rt3_dashboard_menu_normal rt3_dashboard_menu_link');
		}
	} else {
		// debug here if you need to.
	}
	return true;
}

function rt3_dashboard_submenu_prepare(submenu, theParent) {
	// Setup the submenus set their positions, and sizes.
	// called on page load
	if(!submenu || !parent) {
		return false;
	}
	if($(theParent).is("span")) {
		theParent = $(theParent).parent().attr('id');
		theParent = document.getElementById(theParent);
		//alert($(theParent).attr('id'));
	}
	posSelf = elementPosition(submenu);
	if(posSelf[0] = undefined || posSelf[0] > 0) {
		return false;
	}
	posParent = elementPosition(theParent);
	sizeParent = new Array();
	sizeParent[0] = $(theParent).width();
	sizeParent[1] = $(theParent).height();
	sizeSelf = new Array();
	sizeSelf[0] = $(submenu).width();
	sizeSelf[1] = $(submenu).width();
	//alert(sizeParent + "\n" + posParent + "\n" + sizeSelf + "\n" + posSelf);
	offset = sizeOffsetCenter(sizeParent, sizeSelf);
		//alert('OffsetXY: ' + offset);
	topPos = posParent[1] + sizeParent[1];
	leftPos = offset[0] + posParent[0];
	//console.log('submenu_prepare :: Moving to ('+ top + ', ' + left +')');
	$(submenu).css('left', leftPos + 'px').css('top', topPos + 'px').css('display', 'none');
	return true;
}


function rt3_dashboard_submenu_show(subMenuId) {
	// displays the submenu and sets up a timeout to hide the submenu when the timeout timer reaches 0
	//console.log('submenu_show :: ('+ activeSubMenuId +') WAS ACTIVE');
	if(rt3_dashboard_que_length(subMenuId) > 2) {
    	return false;
    }
	activeSubMenuId = subMenuId;
	//console.log('submenu_show :: ('+ subMenuId +') Display');
	$('#'+subMenuId).slideDown('fast');
	return true;
}

function rt3_dashboard_submenu_hide_all(activeId) {
	//console.log('submenu_hide_all :: HIDING ALL');
	$('div.rt3_dashboard_submenu').each(function() {
		thisId = $(this).attr('id');
		if(thisId != activeId) {
			rt3_dashboard_submenu_hide(thisId);
		} else {
		//	console.log('submenu_hide_all :: SKIPPING '+ thisId);
		}
	});
}

function rt3_dashboard_submenu_hide(subMenuId) {
	//console.log('submenu_timeout :: ('+ activeSubMenuId  +') CLEARING');
	clearTimeout(subMenuTimer);
	if(subMenuId == activeSubMenuId) {
		activeSubMenuId = false;
	}
//	console.log('submenu_hide :: ' + subMenuId);
    if(rt3_dashboard_que_length(subMenuId) > 2) {
    	return false;
    }
	$('#' + subMenuId).slideUp('fast', function() {
	  //$(this).css('display', 'none').css('left', '200px').css('top', '100px');
	  	 // $(submenu).queue( [ ] ).stop(); // Clear queued events.
	  	 // $(this).queue( [ ] ).stop(); // Clear queued events.
	});
	return true;
}

function rt3_dashboard_que_length(object) {
  object = returnObject(object);
  queLength = $(object).queue('fx');
  queLength = queLength.length;
  return queLength;
}

function rt3_dashboard_submenu_timeout(newTimer) {
	if(newTimer == true) {
	 // console.log('submenu_timeout :: ('+ activeSubMenuId  +') NEW TIMEOUT - ' + subMenuTimeout + ' seconds');
	  subMenuCountdown = subMenuTimeout; // Reset the countdown.
	 // console.log('submenu_timeout :: ('+ activeSubMenuId  +') T-minus: ' + subMenuCountdown);
	  subMenuTimer = setTimeout('rt3_dashboard_submenu_timeout();', 1000);
	  return true;
	} else {
		// If its not a new Timer, we are doing the countdown.
		if(subMenuCountdown > 1) {
			subMenuCountdown -= 1;
			//console.log('submenu_timeout :: ('+ activeSubMenuId  +') T-minus: ' + subMenuCountdown);
			subMenuTimer = setTimeout('rt3_dashboard_submenu_timeout();', 1000);
			return true;
		} else {
			// If the countdown is 0 or less, that means we need to kill the active div.
			rt3_dashboard_submenu_hide(activeSubMenuId);
			return true;
		}
	}
}

function rt3_dashboard_submenu_toggle(event, submenu, parent) {
	// Toggle the display of the sub menu in and out 
	// This is called when you mouseover a main menu item, 
	// If the parentId of the me
	submenu = returnObject(submenu);
	if(event.type == 'mouseover') {
		currentId = $(submenu).attr('id');
		//console.log('submenu_toggle :: A(' + activeSubMenuId + ')  C(' + currentId + ')');
		if(activeSubMenuId != currentId) {
		  rt3_dashboard_submenu_prepare(submenu, parent);  // Prepare the current subMenu's position.
		  rt3_dashboard_submenu_show(currentId);           // Display the current subMenu, and set it as active.
		  rt3_dashboard_submenu_hide_all(activeSubMenuId); // Hide any existing open subMenus, except for the now active one.
		  rt3_dashboard_submenu_timeout(true);             // Set a display timeout for the subMenu so it hides itself after a specified time.
		} else {
		 // console.log('submenu_toggle :: ('+ $(submenu).attr('id') +') KeepAlive');
		  subMenuCountdown = subMenuTimeout; // Perform keepalive.
		}
	}
}

function rt3_dashboard_submenu(event, topUrl, bottomUrl) {
	// if the parentID is the same as the js variable activeParent don't load the topUrl :-P
	// Manages / displays / hides, handles hover, active, and normal states of dashboard sub-menu's as well as positioning, and loading of content!
	// Detect the event type
	// perform load and animate functions.
	object = returnEventObject(event);
	activeObject = $('.rt3_dashboard_menu_active');
	activeId = $(activeObject).attr('id');
	objectId = $(object).attr('id');
	parentId = objectId.split('_');
	parentId = parentId[0] + '_' + parentId[1] + '_' + parentId[2] + '_' + parentId[3];
	subMenuId = objectId.split('_');
	subMenuId = subMenuId[0] + '_' + subMenuId[1] + '_' + subMenuId[2] + '_' + subMenuId[3] + '_' + subMenuId[4];
	// If the parentId is the ACTIVE ID, then we only load the bottom
	// if the parentId is not the active ID then we make the parentId active, set it as the active and load the top and the bottom.
	if(event.type == 'click') { // if it was a Mouse Click
		rt3_dashboard_submenu_hide(subMenuId); // When you click on a subMenuEntry - Hide the containing subMenu
		$('div.rt3_dashboard_submenu_link').attr('class', 'rt3_dashboard_submenu_normal rt3_dashboard_submenu_link'); // Reset all other buttons to look 'normal'
		$(object).attr('class','rt3_dashboard_submenu_active rt3_dashboard_submenu_link'); // change the look of the button clicked to appear "active"
        if(parentId != activeId) { // if the parentMenu is not the activeMenu
        	activeMenuId = parentId;
        	$('div.rt3_dashboard_menu_link').attr('class', 'rt3_dashboard_menu_normal rt3_dashboard_menu_link'); // Reset all other buttons to look 'normal'
			$('#'+parentId).attr('class','rt3_dashboard_menu_active rt3_dashboard_menu_link'); // change the look of the button clicked to appear "active"
        	// Load the top div
			if(topUrl != undefined && topUrl) {
			  $.ajax({
			   url: LEAF_URL_ROOT + "/" + topUrl,
			   data: 'candidate='+candidateHash,
			   cache: false,
			   success: function(result) {
			    $('#' + topDivId).html(result);
			   }
			  });
			}
        }
		if(topUrl != undefined && topUrl) { // We've loaded the top Div, now we need to load the Bottom Div!
		  $.ajax({
		   url: LEAF_URL_ROOT + "/" + bottomUrl,
		   data: 'candidate='+candidateHash,
		   cache: false,
		   success: function(result) {
		    $('#' + bottomDivId).html(result);
		   }
		  });
		}
	} else if(event.type == 'mouseover') {
		//rt3_dashboard_submenu_keepalive(event, parentId); // Keep the menu alive!
		subMenuCountdown = subMenuTimeout; // Perform keepalive.
		if(!$(object).hasClass('rt3_dashboard_submenu_active')) {
			$(object).attr('class', 'rt3_dashboard_submenu_hover rt3_dashboard_submenu_link');
		}
	// Show the Sub-Menu
	} else if (event.type == 'mouseout') {
		if(!$(object).hasClass('rt3_dashboard_submenu_active')) {
			$(object).attr('class', 'rt3_dashboard_submenu_normal rt3_dashboard_submenu_link');
		}
	// Hide the Sub-Menu
	}
	return true;
}