//Track if we have already fired the view count incrementer.
visibleonce = false;
//Did we attatch a listener to watch for visibility change events?
visibilitylistener = false;

// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange; 
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
	hidden = "hidden";
	visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
	hidden = "mozHidden";
	visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
	hidden = "msHidden";
	visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
	hidden = "webkitHidden";
	visibilityChange = "webkitvisibilitychange";
}

// if the page is shown after being hidden, fire the view increment function
function handleVisibilityChange() {
	if (!document[hidden]) {
		visibleOnceActions();
	}
}

function visibleOnceActions() {
	//Don't allow this function to be run multiple times.
	if (visibleonce) return;
	
	if (incrementview) incrementViewcount();
	
	piwikAction();
	
	visibleonce = true;
	
	//We only want to use the listener once. After it has fired, remove it so we don't waste CPU cycles watching for further visibility changes.
	if (visibilitylistener) document.removeEventListener(visibilityChange, handleVisibilityChange, false);
}

// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
	//This browser doesn't handle visibility checks so fire the visible actions immediately.
	visibleOnceActions();
} else {
	//Check if we are visible right now and fire actions if so.
	if (!document[hidden]) {
		visibleOnceActions();
	} else {

		//We're currently not visible, so set up an event listener to fire actions on visibility change later.
		
		document.addEventListener(visibilityChange, handleVisibilityChange, false);
	
		visibilitylistener = true;
	}
}
