var ratingPopUpVisible = false;
var currentRatingCell = null;

/**
 * Show the pop-up with the current ticket's rating in.
 * @param rating ticket rating
 * @param ratingCell table cell containing the star rating
 */
function showRatingPopUp(rating, ratingCell) {
    // Change title to show rating
    var ratingString = "Not Rated";
    if (rating > 0) {
        ratingString = rating + " Star";
        $('ratingDisclaimer').show();
        $('ratingNewFeature').hide();
    } else {
        $('ratingDisclaimer').hide();
        $('ratingNewFeature').show();
    }
    $('currentRating').innerHTML = ratingString;
    // Show the pop-up relative to the star rating cell
    var offsetArray = $(ratingCell).cumulativeOffset();
    var left = (offsetArray[0]) - 70;
    var top = offsetArray[1] + (($(ratingCell).getHeight()/2)+8);
    var ratingPopUp = $('ratingPopUpContainer');
    ratingPopUp.style.left = left + "px";
    ratingPopUp.style.top = top + "px";
    ratingPopUp.show();
    // Identify that the pop-up is showing
    ratingPopUpVisible = true;
    currentRatingCell = ratingCell;
    // Observe the mouse position for when the user moves the mouse off it
    Event.observe(document, 'mousemove', delayHideRatingPopUp)
}

/**
 * Called when the user moves the mouse of the rating cell to see if the pop-up needs to be hidden.
 * @param event mouseout event
 */
function delayHideRatingPopUp(event) {
    // Check if the mouse pointer has moved onto another element within the cell or if it's moved off it completely
    var offRatingCell = isMouseOffElement(event, currentRatingCell);
    var ratingPopUp = $('ratingPopUpContainer');
    var offRatingPopUp = isMouseOffElement(event,  ratingPopUp);

    if (offRatingCell && offRatingPopUp) {
        // Mouse pointer has moved off cell completely so hide box
        // Stop observing the cell as it's no longer relevant
        $(document).stopObserving('mousemove');
        // Identify we intend to hide the polp-up
        ratingPopUpVisible = false;
        // Leave a 200ms delay before hiding in case user moved straight onto other cell
        setTimeout('hideRatingPopUp()', 100);
    }
}

/**
 * Whether the mouse is NOT over a rectangular element.
 * @param event event
 * @param element element to check
 */
function isMouseOffElement(event, element) {
    var offsetArray = element.cumulativeOffset();
    var left = (offsetArray[0]);
    var top = (offsetArray[1]);
    return (event.pointerX() < left || event.pointerX() > (left+element.getWidth()) ||
            event.pointerY() < top || event.pointerY() > (top+element.getHeight()));
}

/**
 * Hides the rating pop-up if visible.
 */
function hideRatingPopUp() {
    // Only fade the pop-up if it's still invisible i.e. user hasn't moved onto another rating in the meantime
    if (! ratingPopUpVisible) {
        $('ratingPopUpContainer').hide();
    }
}