// JavaScript Document

if ( typeof(tabConfig) == 'undefined' ) {
    tabConfig = {};
}

if ( document.styleSheets[0].addRule ) {
    // the IE case
    document.styleSheets[0].addRule('.js-displaynone', 'display: none;');
}
else {
    // everything else
    var javascript_stylesheet = document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));
    javascript_stylesheet.type = 'text/css';
    javascript_stylesheet.innerHTML = '.js-displaynone { display: none; }';
}

jQuery().ready(function(){

    // Remove certain elements for small screen resolutions
    if ( screen.width < 1000 ) {
        jQuery('.js-800').remove();
    }

    // Enable the accordion
    jQuery('.js-accordion').accordion({
        autoheight: false,
        header: 'a.js-accordionLink',
        active: '.js-current',
        alwaysOpen: false
    });

    // Reload accordion in the appropriate places
    if ( jQuery('.js-accordion-reload').size() ) {
        jQuery('body').oneTime(3 * 60 * 1000, function () {
            tab.reloadAccordion();
        })
    }

    if ( tabConfig.reloadEvery ) {
        jQuery('body').oneTime(tabConfig.reloadEvery * 1000, function () {
            window.location = window.location;
        });
    }

    // Enable the clock if present
    if ( jQuery('.js-clock').size() ) {
        tab.startClock();
    }

    jQuery('.js-toggle-right-panel').click(function () {
        try {
            var elem = parent.document.getElementById('middleframe')
            if ( elem.cols.match(/,0$/) ) {
                elem.cols = elem.old_cols;
                $(this).html(this.toggle_data.hidetext);
            }
            else {
                elem.old_cols = elem.cols;
                elem.cols = '215,*,0';
                $(this).html(this.toggle_data.showtext);
            }
        }
        catch (e) {
        }
        return false;
    });

    // Whole row clickable (on first link found)
    jQuery('.js-rowclick .odd, .js-rowclick .even')
        .mouseover(function () { document.body.style.cursor = 'pointer' } )
        .mouseout(function () { document.body.style.cursor = '' } )
        .click(function () {
            document.location = jQuery(this).find('a').get(0).href;
        });

    jQuery('.js-messagebox').click(function () {
        jQuery(this).hide(500);
        jQuery(this).next().show(500, function () { this.style.zoom = 'normal'; });
        return false;
    });

    // "new window" links with preferred size
    jQuery('.js-new-window').click(function () {
        if ( match = jQuery(this).attr('class').match(/js-new-window-(\d+)-(\d+)/) ) {
            window.open(this.href, null, "location=1,resizable=1,scrollbars=1,width=" + match[1] + ",height=" + match[2]);
            return false;
        }
    });
});

tab = {
    windows: {}
};

// Function to update My TAB navigation
tab.MyTABUpdateNavigation = function () {
    if ( top.frames.navigation ) {
        jQuery('a', top.frames.navigation.document).each(function () {
            try {
                if ( this.href == top.frames.main.document.location.href ) {
                    jQuery('div.odd', top.frames.navigation.document).addClass('even').removeClass('odd');
                    jQuery(this).parent().addClass('odd').removeClass('even');
                }
            }
            catch (e) {
            }
        });
    }
}

// Function to simulate back button in the browser
tab.back = function () {
    try {
        history.go(-1);
    }
    catch(e) {
        back();
    }
}

// Function to reload accordions while preserving open tabs
tab.reloadAccordion = function () {
    var code;

    jQuery('.js-accordion .selected').each(function() {
        var match;
        if ( match = jQuery(this).attr('id').match(/accordion-(.*)/) ) {
            code = match[1];
        }
    });

    var url;

    try {
        url = location.pathname + '?';
    }
    catch (e) {
        url = '?';
    };

    if ( code ) {
        url += '&code=' + code;
    }

    if ( document.location.href.match(/page=date/)) {
        url += '&page=date';
    }

    document.location.href = url;
};

// Operate the clock
tab.startClock = function () {
    var f = function (x) { if ( x < 10 ) return '0' + x; return x };

    jQuery('.js-clock').each(function () {
        var time = new Date();

        if ( match = jQuery(this).html().match(/([0-9]+):([0-9]+):([0-9]+)/) ) {
            time.setHours(match[1]);
            time.setMinutes(match[2]);
            time.setSeconds(match[3]);
        }

        jQuery(this).everyTime(1000, function () {
            time.setTime(time.getTime() + 1000);
            $(this).html(f(time.getHours()) + ':' + f(time.getMinutes()) + ':' + f(time.getSeconds()));
        });
    });
};

// Open a URL in a frame
tab.frameOpen = function (frame, url) {
    // If we're a frame of the main frameset
    if ( parent.main ) {
        try {
            parent.frames[frame].location.href = url;
        }
        catch(error) {
            parent.document.getElementsByName(frame)[0].src = url;
        }
    }
    // If we're an infopanel
    else {
        if( !window.opener || window.opener.closed ) {
          alert("Reference to TAB website window not found\nPlease close the Infopanel and re-load the Tab website in a new browser window");
        } else {
            try {
                window.opener.parent.frames[frame].location.href = url;
            }
            catch(error) {
                window.opener.parent.document.getElementsByName(frame)[0].src = url;
            }
        }
    }
};

// Wrap the frameOpen call and determine the theme
tab.frameOpenWithTheme = function(frame, url) {
    var themeString = '';
    if ( top.tabTheme ) {
        if ( url.match(/\?/) ) {
            themeString = '&theme=' + top.tabTheme;
        }
        else {
            themeString = '?theme=' + top.tabTheme;
        }
    }
    tab.frameOpen(frame, url + themeString);
}

// Displays a odds/betslip for a given option
tab.sportBetslip = function(date, optionno, theme) {
    var aThemeString = '';
    var qThemeString = '';
    var oldTheme = top.tabTheme;
    top.tabTheme = theme;

    // if we got a theme we need to set the themeString
    if ( theme ) {
        aThemeString = '&theme=' + top.tabTheme;
        qThemeString = '?theme=' + top.tabTheme;
    }

    // reopen these frames regardless
    tab.frameOpen('main', tabConfig.ebeturl + '/sbs/' + date + optionno + '.html' + qThemeString);
    tab.frameOpen('odds', '/sport/options.html?optno=' + optionno + aThemeString );

    // if the theme has changed then we need to refresh the other frames
    if ( oldTheme != top.tabTheme ) {
        tab.frameOpen('results', '/sport/results.html' + qThemeString);
        tab.frameOpen('subnavigation', '/common/subnavigation.html?section=sport' + aThemeString);
        tab.frameOpen('tab', '/common/navigation.html?section=sport' + aThemeString);
    }
};

tab.competitionPage = function(type, id, option, theme) {
    var themeString = '';
    var oldTheme = top.tabTheme;
    top.tabTheme = theme;

    // if we got a theme we need to set the themeString
    if ( theme ) {
        themeString = 'theme=' + theme;
    }

    // reopen these frames regardless
    if ( type == 'livescoring' ) {
        tab.frameOpen('main', '/sport/competition-page-livescoring.html?id=' + id + '&' + themeString);
    }
    else {
        tab.frameOpen('main', '/sport/competition-page.html?id=' + id + '&' + themeString);
    }
    if ( option ) {
        tab.frameOpen('odds', '/sport/options.html?optno=' + option + '&' + themeString );
    }
    else {
        tab.frameOpen('odds', '/sport/options.html?' + themeString );
    }

    // if the theme has changed then we need to refresh the other frames
    if ( oldTheme != top.tabTheme ) {
        tab.frameOpen('results', '/sport/results.html?' + themeString);
        tab.frameOpen('subnavigation', '/common/subnavigation.html?section=sport' + '&' + themeString);
        tab.frameOpen('tab', '/common/navigation.html?section=sport' + '&' + themeString);
    }
};

// Open an infopage
tab.ipOpen = function(page) {
    if ( !tab.windows.infowindow || tab.windows.infowindow.closed ) {
        tab.windows.infowindow = window.open(
            page,
            'info',
            'location=no,status=yes,scrollbars=yes,resizable=yes,width=726,height=581,alwaysRaised=yes'
        );
    }
    else {
        tab.windows.infowindow.location.href = page;
    }
    tab.windows.infowindow.focus();
};

// Open multibet
tab.multibetOpen = function() {
    if ( !tab.windows.multibetwin || tab.windows.multibetwin.closed ) {
        tab.windows.multibetwin = window.open(
            tabConfig.ebeturl + '/sports_multi/sports_list.jsp?firstTime=1',
            'multibet',
            'location=no,status=yes,scrollbars=yes,resizable=yes,width=1020,height=600,alwaysRaised=yes'
        );
    }
    tab.windows.multibetwin.focus();
};

// Open batchbet
tab.batchbetOpen = function() {
    if ( !tab.windows.batchbetwin || tab.windows.batchbetwin.closed ) {
        tab.windows.batchbetwin = window.open(
            tabConfig.ebeturl + '/batchbet/',
            'batchbet',
            'location=no,status=yes,scrollbars=yes,resizable=yes,width=900,height=700,alwaysRaised=yes'
        );
    }
    tab.windows.batchbetwin.focus();
};

// Displays a odds/betslip for a given race
tab.racingBetslip = function(date, code, raceno, btype) {
    tab.frameOpen('odds', tabConfig.ebeturl + '/odds/' + date + code + raceno + '.html');
    tab.frameOpen('main', tabConfig.ebeturl + '/rbs/' + date + code + raceno + btype + '.html');
};

// Open futures
tab.racingFutures = function(date, code, meetno, raceno, odds) {
    tab.frameOpen('main', '/racing/race.html?date=' + date + '&code=' + code + '&meetno=' + meetno + '&raceno=' + raceno);
    if ( odds ) {
        tab.frameOpen('odds', tabConfig.ebeturl + '/odds/' + date + code + raceno + '.html');
    } else {
        tab.frameOpen('odds', '/racing/next10.html');
    }
};

// Open meetings page
tab.racingMeeting = function(date, meetno) {
    tab.frameOpen('main', '/racing/meeting.html?date=' + date + '&meetno=' + meetno);
    tab.frameOpen('odds', '/racing/next10.html');
};

// Open sixpack
tab.racingSixPack = function(date, meetcode, raceno, btype, sourcemeetcode, sourceraceno) {
    tab.frameOpen('main', tabConfig.ebeturl + '/rbs/' + date + meetcode + '1' + btype + '.html') ;
    tab.frameOpen('odds', tabConfig.ebeturl + '/odds/' + date + sourcemeetcode + sourceraceno + '.html');
};

// Open picksix
tab.racingPickSix = function(date, meetcode, btype, sourcemeetcode, sourceraceno) {
    tab.frameOpen('main', tabConfig.ebeturl + '/rbs/' + date + meetcode + '1' + btype + '.html') ;
    tab.frameOpen('odds', tabConfig.ebeturl + '/odds/' + date + sourcemeetcode + sourceraceno + '.html');
};
