// ==UserScript==
// @name           local.ch Citypage Autotabs
// @description    Automatically jumps to the next tab on the local.ch city pages unless disabled.
// @namespace      http://patrice.ch/
// @include        http://www.local.ch/*
// ==/UserScript=

var timeout = null;
var INTERVAL = 5; // in seconds

(function() {
    var records = document.getElementById('records');
    if (records) {
        var arrows = records.getElementsByClassName('cpArrow'),
            selectedIndex = 0;
        if (arrows.length > 0) {
            for (var i = 0; i < arrows.length; i++) {
                if (arrows[i].className.indexOf('activeArrow') > -1) {
                    selectedIndex = i;
                    break;
                }
            }
            var nextIndex = selectedIndex + 1;
            if (nextIndex >= arrows.length) {
                nextIndex = 0;
            }
            var link = arrows[nextIndex].getElementsByTagName('a')[0].href;
        
            // Create information that we're going to reload
            var div = document.createElement('div');
            div.style.position = 'absolute';
            div.style.top = '103px';
            div.style.left = '580px';
            div.style.width = '17em';
            div.style.border = '1px solid #aaa';
            div.style.background = '#ccc';
            div.style.padding = '1em';
            div.innerHTML = 'Reloading every ' + INTERVAL + ' seconds. ';
            document.body.appendChild(div);
        
            function stopReloading(event) {
                clearTimeout(timeout);
                timeout = null;
                event.preventDefault();
                div.innerHTML = 'Automatic reloading stopped.';
            }
        
            // Allow the timeout to be cancelled with cancel button or escape.
            var a = document.createElement('a');
            a.innerHTML = 'Cancel';
            a.href = 'javascript:void(true)';
            a.addEventListener('click', stopReloading, true);
            document.body.addEventListener('keypress', function(ev) {
                if (ev.keyCode == 27) {
                    stopReloading(ev);
                }
            }, true);
            div.appendChild(a);
        
            // Go to next tab
            timeout = setTimeout(function() {
                location.href = link;
            }, INTERVAL * 1000);
        }
    }
})();

