Try some like this to detect visibility:
var state='';
    (function() {
        var hidden, change, vis = {
                hidden: "visibilitychange",
                mozHidden: "mozvisibilitychange",
                webkitHidden: "webkitvisibilitychange",
                msHidden: "msvisibilitychange",
                oHidden: "ovisibilitychange" /* not currently supported */
            };             
        for (hidden in vis) {
            if (vis.hasOwnProperty(hidden) && hidden in document) {
                change = vis[hidden];
                break;
            }
        }
        if (change)//this is for detecting without  focus, so it works for your second requirement
            document.addEventListener(change, onchange);
        else if (/*@cc_on!@*/false) // IE 9 and lower
            document.onfocusin = document.onfocusout = onchange
        else
            window.onfocus = window.onblur = onchange;
        function onchange (evt) {
            var body = document.body;
            evt = evt || window.event;
            if (evt.type == "focus" || evt.type == "focusin")
           {   
        body.className = "visible";
           state='visible';
            }         else if (evt.type == "blur" || evt.type == "focusout")
            {  body.className = "hidden";     state='';}
                else    {    
                body.className = this[hidden] ? "hidden" : "visible";}
        }
    })();
function timeout_trigger() {
if(state=='visible')
{
//    window.open('PAGE','_SELF'); OR some ajax  
}
}
    setTimeout('timeout_trigger()', 30000);
onfocusin and onfocusout are required for IE 9 and lower, while all others make use of onfocus and onblur.