//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var thePopup = "myResource";
//loading popup with jQuery magic!
function loadPopup(form){
    thePopup = form;
    var myform = document.getElementById(thePopup);
    if(myform.myResourceUrl) {
        myform.myResourceUrl.value = window.location.href;
    }
    centerPopup();
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#dialog").fadeIn("slow");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#dialog").fadeOut("slow");
        popupStatus = 0;
    }
}

//centering popup
function centerPopup(){

    $(".popupForm").css({
        "display": "none"
    });

    $("#"+thePopup).css({
        "display": "block"
    });

    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#dialog").height();
    var popupWidth = $("#dialog").width();
    var offset = $("#base_bar").offset();
    var top = offset.top - popupHeight-1;
    var left = offset.left + $("#base_bar").width() - popupWidth -2;
    //centering
    $("#dialog").css({
        "position": "absolute",
        "top": top,
        "left": left
    });
}

$(document).ready(function(){
    // options
    var hideDelay = 500;
    var hideDelayTimer = null;
    var triggers = $(".trigger");
    var popup = $("#dialog");
    $([triggers.get(0), triggers.get(1), triggers.get(2), triggers.get(3), popup.get(0)]).mouseover(function () {
        // stops the hide event if we move from the trigger to the popup element
        if (hideDelayTimer) clearTimeout(hideDelayTimer);
    }).mouseout(function () {
        // reset the timer if we get fired again - avoids double animations
        if (hideDelayTimer) clearTimeout(hideDelayTimer);
        // store the timer so that it can be cleared in the mouseover if required
        hideDelayTimer = setTimeout(function () {
            hideDelayTimer = null;
            disablePopup();
        }, hideDelay);
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 & popupStatus==1){
            disablePopup();
        }
    });
});
