/* == GLOBAL VARIABLES ========================================================================== */

var pgHash = location.hash;
var pgHost = location.host;
var pgHref = location.href;
var pgPath = location.pathname;
var pgTitle = document.title;

var referrer = '';
var ajaxHash = '';
var inPrintView = false;

var winH = window.innerHeight;
var winW = window.innerWidth;
var uA = navigator.userAgent.toLowerCase();
var userAgent;

var addthis_cnt = 0;




/* == JQUERY SCRIPTING ========================================================================== */


$(window).load(function () {

    /* ==== DISABLE AJAX CACHING ====*/
    $.ajaxSetup({ cache: false });

    /* ==== DETECT MOBILE DEVICES ==== */
    detectUserAgent();

    /* ==== INIT AJAX LOADER ANIMATION ===== */
    //setupAjaxLoader();


    /* ===== COUNTRY SELECTOR COOKIE CODE ===== */
    //cookie check has been moved into '/global/ui/js/head.js'

    //set cookie
    if ($('#cs_page_identifier').length > 0) {
        $('.worldlist a').click(function (e) {
            set_current_country($(this).attr('href')); //set the country cookie (aka "SelectedCountryPath")
            if ($(this).attr('id') == 'ca_fr') { //if canada french, set sub-cookie
                set_cookie('SAP.SITE.COOKIE', 'PC.LNG=French'); //no exp date = session cookie
            }
        });
    }


    /* ===== CORPORATE SITE ======= */
    if ($('#corporate').length > 0) {
        var currPath = window.location.pathname;
        var currDir = currPath.substr(1).split('/', 1);
        var currSubDir = currPath.substr(1).split('/', 2);
        currSubDir = currSubDir[1];

        if (currSubDir != 'index.epx') { $('#nav-main a[href*="' + currSubDir + '"]').addClass('on'); }
        $('#subleftcol a[href*="' + currPath + '"]').addClass('on');


        //swap 'en' and 'de' directories in the URL accordingly 
        $('#corporate-headerright a').click(function (e) {
            var targSelector = $(this).attr('href').substr(1);
            if (targSelector == 'country-selector.epx') {
                if (currDir == 'corporate-de') {
                    location.href = currPath.replace('corporate-de', 'corporate-en');
                }
            }
            if (targSelector == "country-selector-de.epx") {
                if (currDir == 'corporate-en') {
                    location.href = currPath.replace('corporate-en', 'corporate-de');
                }
            }
            e.preventDefault();
        });
    }


    /* ===== RIGHT COLUMN "ARTICLEDISPLAY" TABLE WIDTH RESIZE =========== */
    if ($('#articledisplay').length > 0) {
        $('#articledisplay table').each(function () {
            if ($(this).attr('width') > 557) {
                $(this).attr('width', 557);
            }
        });
    }


    /* ===== INITIALIZE EVENTS PAGE =========== */
    if ($('.searchevents').length > 0) {
        initSearchEventsForm(); // initialize eventsLeftNav Search Form
        if ($('.datepicker').length > 0) { initEventDatePicker(); } // initialize datepicker object
    }
    if ($('.event-results').length > 0) { //if events search results page
        $('.user-actions').hide(); //don't display save/share buttons
    }


    /* ===== POST PAGE-LOAD INITS ===== */
    $(window).hashchange(function () {
        var classParam = getParamByName('class');
        var pgHash = location.hash;

        if ($('body#home').length > 0) { //is the home page (aka 'new experience')
            if (pgHash === "#" || pgHash === "" || pgHash === 'undefined' || pgHash === null) { closeOverlay(); window.location.hash = ""; }
            else {
                pgHash = pgHash.substr(1);
                var getHref = pgHash;
                openOverlay(getHref, classParam);

                //ajaxHash is used to control the on-states of 2nd and 3rd level navigation
                ajaxHash = getHref; //populate ajaxHash
            }
        }
        else if ($('body#secondary').length > 0) { //is secondary page (ie. ByDesign)
            pgHash = pgHash.substr(1);
            if (pgHash.length > 0) {
                var getHref = pgHash;
                openOverlay(getHref, classParam);
            }

            var currPath = location.pathname.substring(1);
            var targStr = currPath.split('/');

            if (targStr[2] == 'sap-bydesign') { //confirm we are in ByDesign
                var navArray = $('#nav-main ul li a');
                switch (targStr[3]) {
                    case 'what-is-sap-business-bydesign': $(navArray[0]).addClass('on'); break;
                    case 'delivery': $(navArray[1]).addClass('on'); break;
                    case 'customer-testimonials': $(navArray[2]).addClass('on'); break;
                    case 'buy-now': $(navArray[3]).addClass('on'); break;
                    case 'see-it-in-action': $(navArray[4]).addClass('on'); break;
                    case 'resources': $(navArray[5]).addClass('on'); break;
                }
            }

            if (targStr[2] == 'sales-on-demand') { //confirm we are in SalesOnDemand
                var navArray = $('#nav-main ul li a');
                switch (targStr[3]) {
                    case 'see-it-in-action': $(navArray[0]).addClass('on'); break;
                    case 'try-and-buy': $(navArray[1]).addClass('on'); break;
                    case 'delivery': $(navArray[2]).addClass('on'); break;
                }
            }
        }

        else { //is a static page (ie search results/asset viewer)
            pgHash = pgHash.substr(1);
            if (pgHash.length > 0) {
                var getHref = pgHash;
                openOverlay(getHref, classParam);
            }
        }

    }); $(window).hashchange();

    initInputs();

    //initialize background hero images
    if ($('body#home').length > 0) {
        initHeroSwitch();
        if ($('#blackout').length != 0 || $('#overlay').length != 0) { setTimeout("$('#hero-btns a:first').click();", 2000); } //if overlay is open when on page load, fire a delayed click event to triger the pause rotation
    }

    //initialize UMP (universal media player) - removed 07.08.11 - *VS*
    //if ($('.UMP_div').length > 0) { initUMP(); }

    /* ===== IE Z-INDEX BUGFIX TEST ===== */

    if ($.browser.msie && $.browser.version <= 7) {
        var zIndexNumber = 10;
        $('div').each(function () {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber += 10;
        }); //$('#page').css('zIndex', '110');
    }

    /* === MULTI HEADER PHONE NUMBER CHECK AND HOVER FUNCTIONALITY === */

    var isHeaderPhone = $('#utilitynav-phone');
    if (isHeaderPhone[0]) {
        var headerPhoneWrap = '#utilitynav-phone';
        var headerPhoneCount = $(headerPhoneWrap + ' span').size();
        if (headerPhoneCount > 1) {
            $(headerPhoneWrap).addClass('multi');
            $(headerPhoneWrap + ' span').addClass('hoveroff');
            $(headerPhoneWrap + ' span:first').removeClass('hoveroff').addClass('first');
        }
    }

    $('#utilitynav-phone.multi a').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            $('span.hoveroff', this).removeClass('hoveroff').addClass('hoveron');
            $('#nav-utilitybtm li:not(#utilitynav-phone)').hide();
        } else {
            $('span.hoveron', this).removeClass('hoveron').addClass('hoveroff');
            $('#nav-utilitybtm li').show();
        }
    });



    /*=== CAPTURE ALL CLICK EVENTS ===*/

    $(document).bind('click', function (e) { //bind click event to entire document
        var clickedObj = $(e.target); //reference to the clicked object
        //console.log('tag: '+clickedObj.get(0).tagName);


        /*= OVERLAY LOGIC ==*/
        if ($('#overlay').length == 0 || $('#blackout').length == 0) { //overlay is closed
            if (!clickedObj.is('a')) { //not an anchor
                if (heroPaused == false) {
                    pauseHero();
                } else { resumeHero(); }
            }
        }


        /*= BLACKOUT LOGIC =*/
        if ($('#blackout').length > 0) { //blackout exists
            if (clickedObj.is('#blackout.hot')) { //is blackout with class hot
                closeOverlay();
            }
            if (clickedObj.is('#blackout.preview')) {
                closePreviewOverlay();
            }
        }


        /*= QUICKLINKS LOGIC =*/

        if (!clickedObj.is('ul#footer-lefttop li#quick-links a') && !clickedObj.is('#hero-btns a')) { //if not quick-links anchor and if not hero-btns anchor
            if ($('ul#footer-lefttop li#quick-links a.on').length > 0) { //if quick-links is open
                closeOverlayQuicklinks();
            }
        }

        /*= NEWS WIDGET LOGIC =*/

        /*if (!clickedObj.is('#sap-news a') || clickedObj.is('.btn-news-reader')) { //if not news-widget anchor
            if ($('#sap-news h2 a.on').length > 0) { //if news widget is open
                closeOverlayNews();
            }
        }*/


        /*= CHECK FOR PRINT VIEW =*/

        if (inPrintView == true) {
            showBrowserView();
        }

    });



    /* ===== CLICK/HOVER EVENTS - EXPANDABLE LISTS ===== */

    $('a#btn-expandall-subright.off').live('click', function () {
        var el = $(this);
        var elRel = $(this).attr('rel');
        var elMarkup = $(this).html();
        if (elRel == "" || elRel == null) { elRel = 'Collapse All'; }
        $(el).next().find('li:not(.on) a.btn-expanditem-subright').click();
        $(el).removeClass('off').addClass('on').html(elRel).attr('rel', elMarkup);
        return false;
    });
    $('a#btn-expandall-subright.on').live('click', function () {
        var el = $(this);
        var elRel = $(this).attr('rel');
        var elMarkup = $(this).html();
        if (elRel == "" || elRel == null) { elRel = 'Expand All'; }
        $(el).next().find('li.on a.btn-expanditem-subright').click();
        $(el).removeClass('on').addClass('off').html(elRel).attr('rel', elMarkup);
        return false;
    });

    $('a.btn-expanditem-subright').live('click', function () {
        var el = $(this);
        var elP = $(el).parent();
        var elRel = $(this).attr('rel');
        var elMarkup = $(this).html();

        if (elRel == "" || elRel == null) { elRel = 'Less'; }
        $(el).attr('rel', elMarkup);
        $(el).html(elRel);

        if ($(elP).is('.on')) { $(elP).removeClass('on'); }
        else { $(elP).addClass('on'); }
        return false;
    });
    $('.expandable-list li').live('click', function () {
        $(this).find('a.btn-expanditem-subright').click();
    });
    $('ul.expandable-list > li > *').find('a').live('click', function (e) { e.stopPropagation(); });


    // HOVERS
    $('.expandable-list li h4').not('.expandable-list li.on h4').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            $(this).parent('li').css('background', '#FFFFFF none');
        } else {
            $(this).parent('li').css('background', 'transparent none');
        }
    });
    $('.expandable-list li.on h4').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            $(this).parent('li').css('background', '#FFFFFF url(/global/ui/images/backgrounds/bkg-expandablelist-hover.png) repeat-x top;');
        } else {
            $(this).parent('li').css('background', '#FFFFFF none');
        }
    });


    // Secondary > subbottom > expandable
    $('a#btn-expandall-subbottom.off').live('click', function () {
        var el = $(this);
        $(el).next().find('li:not(.on) a.btn-expanditem-subbottom').click();
        $(el).removeClass('off').addClass('on').html('Collapse All <span>&raquo;</span>');
    });
    $('a#btn-expandall-subbottom.on').live('click', function () {
        var el = $(this);
        $(el).next().find('li.on a.btn-expanditem-subbottom').click();
        $(el).removeClass('on').addClass('off').html('Expand All <span>&raquo;</span>');
    });

    $('a.btn-expanditem-subbottom').live('click', function () {
        var el = $(this);
        var elP = $(el).parent();
        if ($(elP).is('.on')) { $(el).html('More <span>&raquo;</span>'); $(elP).find('.rm_expand-pictogram').hide(); $(elP).removeClass('on'); } 
        else { $(el).html('Less <span>&raquo;</span>'); $(elP).find('.rm_expand-pictogram').show(); $(elP).addClass('on'); } // 07.07.11 - *VS*
    });
    $('.expandable-list li').live('click', function () {
        var el = $(this);
        $(el).find('a.btn-expanditem-subbottom').click();
    });


    $('.leftnav-expandable-list .btnToggle').live('click', function () {
        var currClass = $(this).attr('class');
        if (currClass == "btnToggle open") {
            $(this).attr('class', 'btnToggle');
        }
        else {
            $(this).addClass('open');
        }
        //$(this).parent().find('li.leftnav-li-hide').stop(true, true).toggle(1000);
        $(this).parent().find('li.leftnav-li-hide').stop(true, true).toggle();
    });




    /*===== CLICK EVENT - TOP LEFT SAP LOGO  =====*/
    /* no longer need to capture 
    $('#header h1 a, #page h1 a').live('click', function () {
    closeOverlay();
    if ($('body#secondary').length > 0) { //if is secondary page (ie. byDesign)
    window.location = '/';
    }
    });
    */





    /*===== CLICK EVENT - EMPTY ANCHORS  =====*/

    $('a[href=""]').live('click', function () { return false; });



    /*===== CLICK EVENT - CONTEXTUAL EMAIL LINK (OPENS CONTACT US TOP OVERLAY)  =====*/

    $('a.content-utility-email').live('click', function () {
        $('A#utilitynav-contact').click();
        return false;
    });




    /*===== CLICK EVENT - CLOSE OVERLAY BUTTON  =====*/

    $('#overlay a.btn-close-overlay, #roil_form_close').live('click', function () {
        closeOverlay();
        if ($(this).parent().attr('class') === "overlay-worldmap") {
            $('#location-select').removeClass('on');
        }
        return false;
    });





    /*===== CLICK EVENT - FOOTER QUICKLINK =====*/

    $('#quick-links a').bind('click', function () {
        getClass = $(this).attr('class');
        if (getClass === 'on') { closeOverlayQuicklinks(); }
        else {
            $('ul#footer-lefttop li#quick-links ul').slideDown(300, function () { buildQLshadow(); }).children('li:first').children('a').css('border', 'none');
            $(this).parent().addClass('on');
            $(this).addClass('on');
        }
        //return false;
    });




    /*===== CLICK EVENT - QUICKLINK CHILDREN ANCHORS  =====*/

    $('#quick-links ul li a').bind('click', function () {
        $('#QLshadow').remove();
        closeOverlayQuicklinks();
    });




    /*===== CLICK EVENT - WORLD MAP LINKS  =====*/

    if (userAgent != 'default') {
        if ($('#worldmap').length > 0) {
            $('#country-map area').each(function (e) {
                imageMapID = $(this).attr('id');
                $('#' + imageMapID).live('touchstart', function () {
                    mapSwitch($(this).attr('rel'));
                });
            });
            $('#worldmap-left a').each(function (e) {
                countryTitleID = $(this).attr('id');
                $('#' + countryTitleID).live('touchstart', function () {
                    mapSwitch($(this).attr('rel'));
                });
            });
        }

    }

    $('#worldmap-left a').live('click', function () {
        if (($(this).attr('class')) !== 'on') {
            var getRel = $(this).attr('rel');
            $('#worldmaptitle-' + getRel).addClass('on', mapSwitch(getRel));
        }
        return false;
    });

    $('#worldmap-left a').live('mouseover mouseout', function (event) {
        var getRel = $(this).attr('rel');
        if (event.type === 'mouseover') {
            $('#worldmap').prepend('<div id="worldmap-hover-' + getRel + '"></div>');
        } else { $('#worldmap-hover-' + getRel).remove(); }
        return false;
    });



    /*===== CLICK EVENT - UTILITY NAV  =====*/

    $('#utilitynav-locationselect, #utilitynav-buy, #utilitynav-myprofile, #utilitynav-contact').live('click', function () {
        var el = $(this);
        var getHref = $(el).attr('href');
        var getId = $(el).attr('id'); // uses the elements id to pass as a class to the overlay
        if ($(el).hasClass('on')) { $(el).removeClass('on'); closeOverlay(); }
        else { $('#nav-utilitytop a.on').removeClass('on'); $(el).addClass('on'); /*openOverlay(getHref, getId);*/location.hash = getHref + '?class=' + getId; }
        return false;
    });

    $('#utilitynav-chat').live('click', function () {
        window.open('https://as00.estara.com/UI/guivalidate.php?rand=4d5d85975119c&donotcache=1297974673408&accountid=200106293516&referrer=http%3A%2F%2Fwww.sap.com%2Fusa%2Findustries%2Findex.epx&pagetitle=U0FQVW5pdGVkU3RhdGVzLVNBUC1CdXNpbmVzc1NvbHV0aW9uc2J5SW5kdXN0cnl8RW50ZXJwcmlzZVNvbHV0aW9uc2FuZFNlcnZpY2Vz&amp;host=as00.estara.com&template=380392&calltype=webchatpop&var6=ZXN0YXI%3D&estara_fsguid=E427B544FF0F376B6F90478FB3B2F1F1&guiid=43f2de8a9637b&timestamp=1297974678&var2=U0FQVW5pdGVkU3RhdGVzLVNBUC1CdXNpbmVzc1NvbHV0aW9uc2J5SW5kdXN0cnl8RW50ZXJwcmlzZVNvbHV0aW9uc2FuZFNlcnZpY2Vz&guiurlprecalldone=1&upeid=TID-4d5d859729aa8540085907-54762255&var7=VElELTRkNWQ4NTk3MjlhYTg1NDAwODU5MDctNTQ3NjIyNTU%3D&_get=YToxNTp7czoxMDoiZG9ub3RjYWNoZSI7czoxMzoiMTI5Nzk3NDY3MzQwOCI7czo5OiJhY2NvdW50aWQiO3M6MTI6IjIwMDEwNjI5MzUxNiI7czo4OiJyZWZlcnJlciI7czo0MzoiaHR0cDovL3d3dy5zYXAuY29tL3VzYS9pbmR1c3RyaWVzL2luZGV4LmVweCI7czo5OiJwYWdldGl0bGUiO3M6Nzg6IlNBUFVuaXRlZFN0YXRlcy1TQVAtQnVzaW5lc3NTb2x1dGlvbnNieUluZHVzdHJ5fEVudGVycHJpc2VTb2x1dGlvbnNhbmRTZXJ2aWNlcyI7czo4OiJhbXA7aG9zdCI7czoxNToiYXMwMC5lc3RhcmEuY29tIjtzOjg6InRlbXBsYXRlIjtzOjY6IjM4MDM5MiI7czo4OiJjYWxsdHlwZSI7czoxMDoid2ViY2hhdHBvcCI7czo0OiJ2YXI2IjtzOjU6ImVzdGFyIjtzOjEzOiJlc3RhcmFfZnNndWlkIjtzOjMyOiJFNDI3QjU0NEZGMEYzNzZCNkY5MDQ3OEZCM0IyRjFGMSI7czo1OiJndWlpZCI7czoxMzoiNDNmMmRlOGE5NjM3YiI7czo5OiJ0aW1lc3RhbXAiO3M6MTA6IjEyOTc5NzQ2NzgiO3M6NDoidmFyMiI7czo3ODoiU0FQVW5pdGVkU3RhdGVzLVNBUC1CdXNpbmVzc1NvbHV0aW9uc2J5SW5kdXN0cnl8RW50ZXJwcmlzZVNvbHV0aW9uc2FuZFNlcnZpY2VzIjtzOjE3OiJndWl1cmxwcmVjYWxsZG9uZSI7czoxOiIxIjtzOjU6InVwZWlkIjtzOjM1OiJUSUQtNGQ1ZDg1OTcyOWFhODU0MDA4NTkwNy01NDc2MjI1NSI7czo0OiJ2YXI3IjtzOjM1OiJUSUQtNGQ1ZDg1OTcyOWFhODU0MDA4NTkwNy01NDc2MjI1NSI7fQ%3D%3D&timestamphash=3C8169E860825426A7ACC2F67E86A206&wvcalltype=talkbychat&ftcallid=newgui_74581%3A205.240.253.201%3A80%3A1297974679.3079&callindex=15525FFDC6D5F9AC7577875C0174F499&gettopost=1', 'SAPchat', 'height=499,width=495');
        closeOverlay();
        return false;
    });



    /*===== CLICK EVENT - LOGIN CTA ON MY ACCOUNT PANEL  =====*/
    /*-- this content is now being loaded in an iframe
    $('#btn-gotoaccount').live('click', function () {
    openOverlay('/profile/registration.epx', 'utilitynav-reg');
    return false;
    });
    */



    /*===== CLICK EVENTS - FOOTER LINKS: FOLLOW SAP, COMMUNITIES  =====*/

    $('#home #social-network, #home #footerlink-communities').live('click', function () {
        getHref = ajaxHash = $(this).attr('href');
        location.hash = getHref;
        $('#nav-main a.on').removeClass('on');
        $(this).addClass('on');
        return false;
    });



    /*===== CLICK EVENT - MAIN NAV, NEWS FLYOUT  =====*/

    $('#home #nav-main a, #sap-news-wrapper a, #sap-news-bottom a.btn-news-reader').live('click', function () {
        if ($(this).parents('#nav-main').length > 0) {
            $('#nav-main a.on').removeClass('on');
            $(this).addClass('on');
            getHref = ajaxHash = $(this).attr('href');
        }
        else { getHref = $(this).attr('href'); }
        if ($(this).parents('#sap-news-wrapper').length > 0) {
            closeOverlayNews();
        }
        //start: IE7 patch > IE7 has known issues in relation to relative pathing
        if ($(this).attr('class') == 'btn-news-reader' && $.browser.msie && $.browser.version == "7.0") { //if btn-news-reader class and browser is IE7
            getHref = $('#sap-news-wrapper a:first').attr('href'); //open the news reader by manually defaulting to the first article in the widget
        }
        //end: IE7 patch

        if ($('body#secondary').length > 0) {
            location.hash = getHref + '?class=byd-news-overlay';
        } else { location.hash = getHref; }
        return false;
    });


    /*===== CLICK EVENTS - NEWS READER =======*/

    $('#subleft-listC .news-group a').live('click', function () {
        getHref = $(this).attr('href');
        location.hash = getHref;
        $('#subleft-listC .news-group a').removeClass('on').parent().removeClass('on');
        $(this).addClass('on').parent().addClass('on');
        return false;
    });



    /*===== CLICK EVENT - SUB NAV  =====*/

    $('#home #nav-sub a').live('click', function () {
        getHref = ajaxHash = $(this).attr('href');
        location.hash = getHref;
        $('#nav-sub a.on').removeClass('on');
        return false;
    });



    /*===== CLICK EVENT - LEFT NAV  =====*/

    $('#home #subleftcol a[rel="panel"]').live('click', function () {
        getHref = ajaxHash = $(this).attr('href');
        location.hash = getHref;
        $('#subleftcol ul li a.on').removeClass('on');
        $(this).addClass('on');
        return false;
    });



    /*===== CLICK EVENT - LIST TOGGLES  =====*/
    $('.atoz-list dl').addClass('clearfix');
    $('a.list-toggle', $('#subbottom')[0]).live('click', function () { if ($(this).parent().attr('class') === "on") { $(this).parent().removeClass('on'); } else { $(this).parent().addClass('on'); } return false; });
    $('.atoz-list dl dt a').live('click', function () { if ($(this).attr('class') !== "on") { $(this).addClass('on').parent().parent().addClass('on'); } else { $(this).removeClass('on').parent().parent().removeClass('on'); } return false; }); //bugfix 1/10/11_sk
    $('#subright-more-toggle a').live('click', function () { if ($(this).attr('class') !== "on") { $('#subright-top-flexible').attr('class', ''); $(this).addClass('on').html('Minimize -').parents('#subright').addClass('on'); } else { $('#subright-top-flexible').attr('class', currSubRghtTopFlexClass); $(this).removeClass('on').html('More +').parents('#subright').removeClass('on'); } return false; }); //revisited "more" toggle  skiernan_1/5/11
    $('a.expand-all', $('#subright-toggles')[0]).live('click', function () { $('#subright-listB li').addClass('on'); return false; });
    $('a.close-all', $('#subright-toggles')[0]).live('click', function () { $('#subright-listB li').removeClass('on'); return false; });
    $('a.expand-all', $('#atoz-toggle')[0]).live('click', function () { $('#atoz-list-wrapper li dl dt a').each(function () { $(this).addClass('on').parent().parent().addClass('on'); }); return false; });
    $('a.close-all', $('#atoz-toggle')[0]).live('click', function () { $('#atoz-list-wrapper li dl dt a.on').removeClass('on').parent().parent().removeClass('on'); ; return false; });



    /*===== CLICK EVENT - PAGINATION CONTROLS =======*/
    if ($('body#home').length > 0) { //make sure we are in the new home page experience
        $('.page-views a').live('click', function () {
            getHref = $(this).attr('href');
            location.hash = getHref;
            $('.page-views a').removeClass('on');
            $(this).addClass('on');
            return false;
        });

        $('.page-selector a').live('click', function () {
            getHref = $(this).attr('href');
            if (getHref == '' || $(this).hasClass('on') == true || $(this).hasClass('disabled') == true) {
                //do nothing
            }
            else {
                location.hash = getHref;
                $('.page-selector a').removeClass('on');
                $(this).addClass('on');
            }
            return false;
        });
    }
    else {
        $('.page-views a').live('click', function () {
            showLoadAnim('subbottom');
        });

        $('.page-selector a').live('click', function () {
            showLoadAnim('subbottom');
        });
    }



    /*===== CLICK EVENTS - CUSTOMER TESTIMONIALS/CUSTOMER AT0Z =======*/
    $('#form-customertestimonials-filter').live('submit', function (e) {
        srchParam = 'Region=' + $('#filter-region').val() + '&Country=' + $('#filter-country').val() + '&Brochure=' + $('#Brochure').is(':checked') + '&Video=' + $('#Video').is(':checked');
        location.hash = ajaxHash + '?' + srchParam;
        e.preventDefault();
    });

    $('#atoz-menu a').live('click', function () {
        if ($('#atoz-menu').hasClass('customerAZ')) { //if "customer testimonials a-z"
            if ($(this).attr('class') != 'disabled') {
                getHref = $(this).attr('href');
                location.hash = getHref;
                $('#atoz-menu a').removeClass('on');
                $(this).addClass('on');
            }
        }
        else { //not "customer testimonials a-z"
            if ($(this).attr('class') != 'disabled') { //if anchor is not disabled
                var letter = $(this).html().toLowerCase();
                var pos = ($('#atoz-' + letter).position().top) + 170;
                $('html').scrollTop(pos);
            }
        }
        return false;
    });

    $('.a2z-moreless a').live('click', function (e) {
        getHref = $(this).attr('href');
        location.hash = getHref;
        e.preventDefault();
    });

    $('#form-atoz-search').live('submit', function (e) {
        getHref = $(this).attr('action');
        srchParam = 'search=' + $('#atoz-input').val();
        location.hash = getHref + '?' + srchParam;
        e.preventDefault();
    });



    /*===== CLICK EVENT - MY SAP ACCOUNT EXPAND/EDIT TOGGLES  =====*/

    // 'Edit' link
    $('a.editexpand').live('click', function () {
        $(this).parent().parent().parent('.thicktopborder').addClass('on');
        return false;
    });
    // 'Close' link
    $('a.editclose').live('click', function () {
        $(this).parent().parent().parent('.thicktopborder').removeClass('on');
        return false;
    });
    // 'Cancel' link
    $('a.cancellink').live('click', function () {
        $(this).parent().parent('.thicktopborder').removeClass('on');
        return false;
    });
    // 'Save' button
    $('.axshawnbuttons a.btn-cta').live('click', function () {
        $(this).parent().parent('.thicktopborder').removeClass('on');
        return false;
    });




    /*===== CLICK EVENT - MY SAP ACCOUNT > MY SUBCRIPTIONS  =====*/

    var relatedChkbx; //global var use
    $('.newslettertable a.infoicon').live('click', function () {
        var el = $(this);
        var jpgURL = $(el).attr('href');
        var title = $(el).siblings('.NLTitle').html();
        var pos = ($(el).position().top + 200);
        relatedChkbx = $(el).parent().siblings('.col-one').children('input:first');
        applyBlackout('newslettertable');
        $('body').append('<div id="previewContainer" style="position:absolute; top:' + pos + 'px; left:30%; z-index:9999;"><a id="myModalClose"><span>Close</span></a><div id="previewInner"><h3>' + title + '</h3><p><a class="btn-cta" id="subscribeNow" href="javascript:;"><span>Subscribe</span></a></p><img src="' + jpgURL + '" /></div></div>');
        return false;
    });

    $('#subscribeNow').live('click', function () {
        $(relatedChkbx).attr('checked', true);
        closePreviewOverlay();
    });

    $('#myModalClose').live('click', function () {
        closePreviewOverlay();
    });




    /*===== CLICK EVENT - BACK BUTTON (HISTORY.GO)  =====*/
    $('.backBtn').live('click', function (e) {
        if (history.length >= 1) {
            history.go(-1);
        }
        else { location.replace('/index.epx'); }
        e.preventDefault();
    });



    /*===== NEWS WIDGET  =====*/
    var isNews = $('#sap-news-wrapper');
    var newsCtr = $('#sap-news ul li').size();
    if (isNews[0]) {
        var newsHt = parseInt($('#sap-news-wrapper ul li').css('height').substring(0, $('#sap-news-wrapper ul li').css('height').indexOf('px'))) + 2;
    }
    var newsMax = ((newsCtr - 3) * newsHt) * -1;
    var newsCrnt = 0;

    $('#sap-news h2 a').bind('click', function (e) {
        getClass = $(this).attr('class');
        if (getClass === "on") {
            closeOverlayNews();
            if (heroPaused == true) {
                resumeHero();
            }
        } else {
            pauseHero();
            $(this).addClass('on');
            $('#sap-news').append('<div id="sap-news-bottom" class="clearfix" style="z-index:1000"><a href="" class="btn-news-up"></a><a href="" class="btn-news-down"></a><a href="/news-reader/index.epx" onclick="TrackLink(' + "'', 'Open News Reader', 'ClickArea=NewsWidget')" + '" class="btn-news-reader">Open News Reader</a></div>');
            $('#sap-news-wrapper').addClass('sap-news-wrapper-on');
            $('#sap-news').addClass('on');
        }
        e.preventDefault();
    });

    $('.btn-news-down', $('#sap-news')[0]).live('click', function () {
        if (newsCrnt !== newsMax) { newsCrnt = newsCrnt - newsHt; $('#sap-news ul').animate({ top: newsCrnt }, 400); }
        else { newsCrnt = 0; $('#sap-news ul').animate({ top: newsCrnt }, 1000); }
        TrackLink('', 'News-Down', 'ClickArea=NewsWidget');
        //return false;
    });

    $('.btn-news-up', $('#sap-news')[0]).live('click', function () {
        if (newsCrnt !== 0) { newsCrnt = newsCrnt + newsHt; $('#sap-news ul').animate({ top: newsCrnt }, 400); }
        TrackLink('', 'News-Up', 'ClickArea=NewsWidget');
        //return false;
    });


    /*====== SITE SEARCH INIT  ======*/
    $('#searchsite-input').live("focus", function () {
        initInputs();
        $(this).autocomplete({ //header site search input
            minLength: 0,
            delay: 0,
            source: function (request, respond) {
                get_suggestions(request.term, function (response) {
                    respond(eval(response))
                });
            },
            minWidth: 146,
            width: '100%',
            zIndex: 9999,
            select: function (event, ui) {
                $('#searchsite-input').val(ui.item.value);
                $('#searchsite').submit();
            }
        });
    });


    $('#QueryText').autocomplete({
        minLength: 0,
        delay: 0,
        source: function (request, respond) {
            get_suggestions(request.term, function (response) {
                respond(eval(response))
            });
        },
        minWidth: 186,
        width: '100%',
        zIndex: 9999,
        select: function (event, ui) {
            $('#QueryText').val(ui.item.value);
            $('#searchresults').submit();
        }
    });


    /*===== FOOTER PRINT/TEXT CLICK EVENTS =====*/

    var isTextView = $('#footer-textview');
    var isPrintView = $('#footer-printview');
    if (isTextView[0]) { $(isTextView).click(function () { showText(); }) }
    if (isPrintView[0]) { $(isPrintView).click(function () { showPrint(); }) }



    /*==== INITIALIZE A TO Z PAGES =====*/
    $('#atoz-menu a.disabled').each(function () {
        letter = $(this).html().toLowerCase();
        $('#atoz-' + letter).hide();
    });



    /*==== ByDESIGN - GUIDED TOUR =====*/
    if ($('body#secondary').length > 0) { //make sure we are in the byd experience

        $('#tour-launch').click(function (e) {
            var getHref = $(this).attr('href');
            //openOverlay(getHref, 'byd-tour');
            location.hash = getHref + '?class=byd-tour';
            $('html').scrollTop(0); //default scroll position back to top
            e.preventDefault();
        });

    }


    /*==== AJAX LOADING ANIMATIONS ====*/
    $('#searchsite').submit(function (e) {
        showLoadAnim('subbottom');
    });

    $('#searchresults').submit(function (e) {
        showLoadAnim('subbottom');
    });

    /*==== INITIALIZE BYD TOUR ====*/
    if ($('.tour_wrap').length > 0) {
        initBYDtour();
    }


    /*==== INITIALIZE SOCIAL MEDIA SCRIPTS ====*/

    //if "Facebook Like" button is present, load proper scripts
    if ($('.fbLikeButton').length > 0) {
        $.getScript('/global/ui/js/facebook.js');
    }

    //if "Share" (aka addthis) button is present, load proper scripts
    if ($('.sharelink').length > 0) {
        if (addthis_cnt == 0) {
            $.getScript('/global/js/addthis_widget.js', function () {
                addthis_cnt++;
            });
        }
    }

    //initialize leftnav expandable functionality
    if ($('.leftnav-expandable-list').length > 0) {
        if ($('.btnToggle').length == 0) {
            $('.leftnav-expandable-list').each(function () {
                var totalItems = $(this).find('li');
                var linkArray = $(this).find('li a');

                //determine whether to build a collapseable list
                if (totalItems.length > 5) { //if there are more than 5 items in the list, apply a toggle button
                    $.each(totalItems, function (index, value) {
                        if (index > 4) {
                            $(this).addClass('leftnav-li-hide');
                        }
                    });
                    $(this).append('<li class="btnToggle"></li>');
                }

                //determine whether the list should 'open' or stay 'collapsed' on pageload
                $.each(linkArray, function (index, value) { //iterate thru anchors and look for the 'on' state
                    //console.log(index+' : '+value);
                    isOn = $(this).hasClass('on');
                    if (isOn == true) { //if 'on' state is present determine the index of that item in the array
                        if (index >= 5) { //if the 'on' anchor is 5 or greater... open the leftnav menu
                            $(this).parent().siblings('.btnToggle').trigger('click');
                        }
                    }
                });
            });
        }
    }

});    //end of $(window).load








/* ===== FUNCTIONS ========================================================================== */


/* ===== Detect User Agent ===== */

function detectUserAgent() {
    if (uA.search('iphone') > -1) { userAgent = 'iphone'; $('body').addClass(userAgent); }
    else if (uA.search('ipad') > -1) { userAgent = 'ipad'; $('body').addClass(userAgent); }
    else if (uA.search('ipod') > -1) { userAgent = 'ipod'; $('body').addClass(userAgent); }
    else if (uA.search('android') > -1) { userAgent = 'android'; $('body').addClass(userAgent); }
    else if (uA.search('windows ce') > -1) { userAgent = 'windows-mobile'; $('body').addClass(userAgent); }
    else if (uA.search('blackberry') > -1) { userAgent = 'blackberry'; $('body').addClass(userAgent); }
    else if (uA.search('palm') > -1) { userAgent = 'palm'; $('body').addClass(userAgent); }
    else { userAgent = 'default' }
}


/*==== AJAX LOADING ANIMATIONS ====*/
function showLoadAnim(targDiv) {
    targDiv = '#' + targDiv;
    if ($(targDiv).length > 0) {
        $(targDiv).prepend('<div id="XHR_request"><span>PROCESSING...</span></div>');
        $('#XHR_request').fadeIn(500);
        $('html').scrollTop(0); //default scroll position back to top
    } else { $('body').prepend('<div id="XHR_request"><span>PROCESSING...</span></div>'); }
}

function hideLoadAnim() {
    $('#XHR_request').remove();
}


/*==== GET QUERYSTRING PARAM ======*/
function getParamByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}


/* ===== MBOX DIVS ===== */
function mboxAJAXCreate() {
    $('.mboxDefault').each(function () {
        var mboxId = $(this).attr('id');
        mboxDefine(mboxId, mboxId);
        mboxUpdate(mboxId);
    });
}

/*=== GET AJAX ===*/

function getAJAX(url_ref, div_ref) {
    $.ajax({
        type: 'GET',
        url: url_ref,
        global: false,
        beforeSend: function (jqXHR, settings) {
            showLoadAnim('subbottom');
            if(referrer != '')
                jqXHR.setRequestHeader('X-SAP-Referer', referrer);
            referrer = 'http://' + location.host + location.hash.substring(1);
        },
        success: function (data) {
            var sTitle = data.indexOf('<title>') + 7; //find starting index for the title tag
            var eTitle = data.indexOf('</title>'); //find the ending index for the title tag
            $('#nav-utilitytop a.on, #nav-main a.on, #footer a.on').removeClass('on'); //clear previous nav on-states
            //getTitle = $(data).filter("title").text();
            getTitle = data.substring(sTitle, eTitle); //extract substring of start/end indices for the <title></title> tag
            getContent = $(data).find(div_ref).html();
            $('#overlay').fadeIn(500, function () {
                $('#overlay').html(getContent).prepend('<a href="" class="btn-close-overlay" aria-label="Close" aria-describedby="descriptionClose"></a>');
            });
            document.title = getTitle;
            if ($('#blackout').length > 0) {
                var class_ref = $('#overlay').attr('class');
                if (class_ref.substr(0, 11) == 'utilitynav-') {
                    $('#footer').removeClass('footer-panel').css({ 'position': 'absolute', 'z-index': '70' });
                } else { $('#footer').css({ 'position': 'relative' }); }
            } else { $('#footer').addClass('footer-panel').css({ 'position': 'absolute' }); }
            ajaxSuccess(data); //global functions for ajax callbacks
            mboxAJAXCreate();
            hideLoadAnim();
			if (typeof change_phone != "undefined") change_phone(data);
            if (typeof change_liveperson != "undefined") change_liveperson(data);
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(xhr.status + ': ' + xhr.statusText + '\nError Thrown: ' + errorThrown);
        }
    });
}



/*=== BLACKOUT REHEIGHT ===*/

function blackoutReheight() {
    //var blackoutReheight = $('#page-content').height() + $('#header').height() + $('#footer').height() + 8;
    $('#blackout').css('height', $(window).height());
}



/*=== AJAX SUCCESS CALLBACK FUNCTIONS ===*/

var currSubRghtTopFlexClass;
function ajaxSuccess(data) {

    //initialize navigation on-states
    if (ajaxHash.search(/\?/) != -1) { //check for existence of querystring
        ajaxHash = ajaxHash.substring(0, ajaxHash.lastIndexOf('?')) //if found, strip off querystring
    }
    var ancURL = 'a[href="' + ajaxHash + '"]';

    if (ancURL != 'a[href=""]') { //if targeted anchor is not an empty string
        if ($(data).find(ancURL).length > 0) { //if current URL is equivalent to a navigation element on the served page then add class="on"
            $(ancURL).each(function () { //iterate thru each found match (could be multiples href's {ie. main-nav and tabbed nav (ie. solutions and communities)} and we don't want to stop on first match )
                if ($(this).attr('class') != 'on') {
                    $(this).addClass('on');
                }
            });
        }
    }

    //highlight corresponding nav-main item
    var targStr = ajaxHash.substring(1).split('/');
    if ($('body#home').length > 0) { //confirm this is not a secondary page tempate
        var navArray = $('#nav-main ul li a');
        switch (targStr[0]) {
            //header navigation   
            case 'countries': $('#utilitynav-locationselect').addClass('on'); break;
            case 'buy-now': $('#utilitynav-buy').addClass('on'); break;
            case 'profile': $('#utilitynav-myprofile').addClass('on'); break;
            case 'contactsap': $('#utilitynav-contact').addClass('on'); break;
            //main navigation     
            case 'solutions': $(navArray[0]).addClass('on'); break;
            case 'services-and-support': $(navArray[1]).addClass('on'); break;
            case 'about-sap': $(navArray[2]).addClass('on'); break;
            case 'industries': $(navArray[3]).addClass('on'); break;
            case 'customer-testimonials': $(navArray[4]).addClass('on'); break;
            case 'our-partners': $(navArray[5]).addClass('on'); break;
            case 'lines-of-business': $(navArray[6]).addClass('on'); break;
            case 'training-and-education': $(navArray[7]).addClass('on'); break;
            case 'events': $(navArray[8]).addClass('on'); break;
            //footer navigation     
            case 'communities': $('#footerlink-communities').addClass('on'); break;
            case 'social': $('#social-network').addClass('on'); break;
        }
    }
    if ($('body#secondary'.length > 0)) { //confirm we are in the secondary template (ie BYD)
        //if the news reader overlay is open in BYD
        if ($(data).find('.newsreader').length > 0) {
            $('.page-views a').live('click', function () {
                getHref = $(this).attr('href');
                location.hash = getHref;
                $('.page-views a').removeClass('on');
                $(this).addClass('on');
                return false;
            });

            $('.page-selector a').live('click', function () {
                getHref = $(this).attr('href');
                if (getHref == '' || $(this).hasClass('on') == true || $(this).hasClass('disabled') == true) {
                    //do nothing
                }
                else {
                    location.hash = getHref;
                    $('.page-selector a').removeClass('on');
                    $(this).addClass('on');
                }
                return false;
            });
        }
    }

    //if "A to Z" nav menu exists, hide disabled content blocks in "A to Z" list and change background
    if ($(data).find('#atoz-menu').length > 0) {
        $('#sub').addClass('nobkg');
        $('#atoz-menu a.disabled').each(function () {
            letter = $(this).html().toLowerCase();
            $('#atoz-' + letter).hide();
        });
    }
    else if ($(data).find('#sub').attr('class') == 'nobkg') { /* do nothing, leave class='nobkg' in tact */ }
    else { $('#sub').removeClass('nobkg'); } //remove class='nobkg'

    //move myprofile markup
    var myProfileMenu = '#utilitynav-myprofile-menu';
    if ($(myProfileMenu).length > 0) { moveMyProfile(); }

    //initialize multi-promo rotation
    if ($(data).find('#subrightcol-promo').length > 0 || $(data).find('#htb-highlight-right').length > 0) {
        initPromoRotate();
    }


    //init input fields
    initInputs();

    //initialize "more/minimize" link functionality
    if ($('#subright').length > 0) { $('#subright').removeClass('on'); }
    if ($(data).find('#subright-top-flexible').length > 0) { currSubRghtTopFlexClass = $('#subright-top-flexible').attr('class'); }

    //initialize leftnav expandable functionality
    if ($(data).find('.leftnav-expandable-list').length > 0) {
        if ($('.btnToggle').length == 0) {
            $('.leftnav-expandable-list').each(function () {
                var totalItems = $(this).find('li');
                var linkArray = $(this).find('li a');

                //determine whether to build a collapseable list
                if (totalItems.length > 5) { //if there are more than 5 items in the list, apply a toggle button
                    $.each(totalItems, function (index, value) {
                        if (index > 4) {
                            $(this).addClass('leftnav-li-hide');
                        }
                    });
                    $(this).append('<li class="btnToggle"></li>');
                }

                //determine whether the list should 'open' or stay 'collapsed' on pageload
                $.each(linkArray, function (index, value) { //iterate thru anchors and look for the 'on' state
                    //console.log(index+' : '+value);
                    isOn = $(this).hasClass('on');
                    if (isOn == true) { //if 'on' state is present determine the index of that item in the array
                        if (index >= 5) { //if the 'on' anchor is 5 or greater... open the leftnav menu
                            $(this).parent().siblings('.btnToggle').trigger('click');
                        }
                    }
                });
            });
        }
    }

    //initialize UMP (universal media player)  - removed 07.08.11 - *VS*
    //if ($(data).find('.UMP_div').length > 0) { initUMP(); }
	
	//Fire Rich Media's ajaxSuccess function - 07.08.11 - *VS*
	rm_ajaxSuccess();

    //initialize Events LeftNav Search Form
    if ($('.searchevents').length > 0) {
        initSearchEventsForm(); // initialize eventsLeftNav Search Form
        if ($('.datepicker').length > 0) { initEventDatePicker(); } // initialize datepicker object
    }

    //initialize BYD TOUR
    if ($('.tour_wrap').length > 0) {
        initBYDtour();
    }

    //if "Facebook Like" button is present, load appropriate script
    if ($(data).find('.fbLikeButton').length > 0) {
        $.getScript('/global/ui/js/facebook.js');
    }

    //if "Share" (aka addthis) button is present, load appropriate script
    if ($(data).find('.sharelink').length > 0) {
        if (addthis_cnt == 0) {
            $.getScript('/global/js/addthis_widget.js', function () {
                addthis_cnt++;
            });
        }
    }

} //end ajaxsuccess()




/*=== INIT - SEARCH INPUTS - HIDE AND SHOW LABEL APPROPRIATELY ===*/

function initInputs() {
    var elmArr = $('.focusClear');
    elmArr.each(function () {
        $(this).focus('click', function () { $(this).siblings('label:first').hide(); });
        $(this).blur(function () { if ($(this).attr('value') === "") { $(this).siblings('label:first').show(); } });
        if ($(this).attr('value') !== "") { $(this).siblings('label:first').hide(); }
    });
}



/*=== PRELOAD IMAGE FUNCTION ===*/

var cache = [];
function preload() {
    var args_len = arguments.length;
    for (var i = args_len; i--; ) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
    }
}




/*=== COUNTRY SELECTOR ===*/


// MAP HOVER

function areaEnter(getRel) {
    if (userAgent == 'default') {
        if ($('#worldmaptitle-' + getRel).attr('class') !== 'on') { $('#worldmaptitle-' + getRel).addClass('huvver'); }
        $('#worldmap').prepend('<div id="worldmap-hover-' + getRel + '"></div>');
    }
}

function areaLeave(getRel) {
    if (userAgent == 'default') {
        if ($('#worldmaptitle-' + getRel).attr('class') !== 'on') { $('#worldmaptitle-' + getRel).removeClass('huvver'); }
        $('#worldmap-hover-' + getRel).remove();
    }
}


// MAP SWITCH

function mapSwitch(getRel) {
    $('#worldlist-intro').hide();
    $('#worldmap-right .worldlist').hide();
    $('#worldlist-' + getRel).fadeIn(400);
    $('#worldmap-left').css('background', 'url(/global/ui/images/backgrounds/bkg-worldmap-' + getRel + '-current.png) no-repeat 8px 10px');
    $('#worldmap-left a.on, #worldmap-left area.on').removeClass('on');
    $('#worldmaptitle-' + getRel).addClass('on');
    if ($.browser.webkit) { $('area').focus(function () { $(this).blur(); }); }
}




/*=== MAIN PAGE HERO SWITCHER & NEWS WIDGET ROTATION ===*/

// GLOBAL VARS
var heroOn = 1;
var rotateSpeed = 10000;
var autoRotate;
var heroTimer;
var resumeInterval;
var resumeTimeout;
var heroSec = 1;
var heroPaused = false;


/*===== CLICK EVENT - HERO BUTTON  (DO NOT MOVE THIS FUNCTION)  =====*/
$('#hero-btns a').live('click', function () {
    var getRel = $(this).attr('rel');
    var getRelBkgImage = $('#hero ul li:eq(' + (getRel - 1) + ')').attr('rel');
    var currClass = $(this).attr('class');
    if (currClass != 'on' && currClass != 'pause on' && currClass != 'on pause') {
        getRel = parseInt(getRel);
        heroOn = getRel + 1;
        $('#hero-btns a').each(function () {
            var resetHTML = $(this).attr('rel');
            $(this)/*.html(resetHTML)*/.html('').removeClass('on').removeClass('pause');
        });
        $(this).addClass('on').parent().removeClass('pause'); ;
        heroSwitch(getRel, getRelBkgImage);
        return false;
    }
    else {
        if (($(this).attr('class')) == 'on') {
            //$(this).html('| |').addClass('pause');
            pauseHero();
        }
        else {
            //$(this).html(getRel).removeClass('pause');
            resumeHero();
        }
        return false;
    }
});


// PAUSE HERO	
function pauseHero() {
    if ($('#hero-btns').length > 0) {
        heroPaused = true;
        $('#hero-btns').addClass('pause');
        var total_secs = rotateSpeed / 1000;
        var sec = 1;
        var currHeroPos = $('#hero-btns a.on').attr('rel');
        var currTimerPos = $('#hero-timer ul li.spent').length;
        //console.log('currPos: '+currHeroPos+' \ncurrTimer: '+currTimerPos);
        if (currTimerPos > 0) { //timer exists
            if (resumeTimeout != "undefined") {
                clearTimeout(resumeTimeout);
            }
            stopHeroRotate();
            removeHeroTimer();
            //manual rebuild of timer with new remaining time spent
            $('#hero').append('<div id="hero-timer"></div>');
            $('#hero-timer').append('<ul></ul>');
            while (sec <= total_secs) {
                $('#hero-timer ul').append('<li></li>');
                sec++;
            }
            for (x = 1; x <= currTimerPos; x++) { //add styles to represent time spent
                $('#hero-timer ul li:not(.spent):last').addClass('spent');
            }
            //$('#hero-btns a.on').addClass('pause'); //change "hero-btn" instance to paused status
        }
        $('#hero-btns a.on').html('| |').addClass('pause');
    }
}


// RESUME HERO	
function resumeHero() {
    if ($('#hero-btns').length > 0) {
        heroPaused = false;
        $('#hero-btns').removeClass('pause');
        var currHeroPos = $('#hero-btns a.on').attr('rel');
        var currTimerPos = $('#hero-timer ul li.spent').length;
        //console.log('currPos: '+currHeroPos+' \ncurrTimer: '+currTimerPos);
        var resumeSpeed = rotateSpeed - (currTimerPos * 1000); //calculate remaining time before next transition
        resumeInterval = window.setInterval("cycleHeroTimer(" + resumeSpeed + ")", 1000); //set new interval with new time
        resumeTimeout = setTimeout('resetHeroRotation(); rotateHero(' + rotateSpeed + '); startNewsRotation(); resetHeroTimer();', resumeSpeed); //after new interval expires, revert back to default interval
        $('#hero-btns a.on').html(/*currHeroPos*/'').removeClass('pause'); //change "hero-btn" instance to resumed status
    }
}


// HERO SWITCH
function heroSwitch(getRel, getRelBkgImage) {
    var heroCnt = $('#hero ul:first li').size();
    if (heroOn > heroCnt) { heroOn = 1; }
    resetHeroRotation();
    $('#hero li').hide();
    $('#hero' + getRel).fadeIn(100);
    winHeight = $(window).height();
    if (winHeight > 750) {
        var bkgImg = getRelBkgImage.split('.');
        bkgImg = bkgImg[0];
        bkgImg = bkgImg.substr(0, bkgImg.length - 3);
        bkgImg = bkgImg + "-lg.jpg"
        $('#home').css('background', '#222 url(' + bkgImg + ') fixed top no-repeat');
    } else {
        $('#home').css('background', '#222 url(' + getRelBkgImage + ') fixed top no-repeat');
    }
    resetHeroTimer();
    heroPaused = false;
    $('#hero-btns a.on').css('backgroundPosition', '0px 0px');
}


// INITIALIZE HERO SWITCHER
function initHeroSwitch() {
    var heroCnt = $('#hero ul li').size();
    if ($('#hero').length > 0) {
        $('#hero').append('<div id="hero-btns"></div>');
        $('#hero ul li').each(function (index) { $('#hero-btns').append('<a href="" rel="' + (index + 1) + '"></a>'); });
        $('#hero ul li').each(function () {
            getRel = $(this).attr('rel');
            winHeight = $(window).height();
            if (winHeight > 750) {
                var bkgImg = getRel.split('.');
                bkgImg = bkgImg[0];
                bkgImg = bkgImg.substr(0, bkgImg.length - 3);
                bkgImg = bkgImg + "-lg.jpg";
                $('#hero ul li').each(function () { preload(bkgImg); });
            } else {
                preload(getRel);
            }
        });
        startHeroRotate();
        rotateHero(rotateSpeed);
    } else { autoRotate = window.setInterval(function () { startNewsRotation(); }, rotateSpeed); }
}


// ROTATE HERO 
function rotateHero(rSpeed) {
    var heroCnt = $('#hero ul:first li').size();
    if (heroOn > heroCnt) { heroOn = 1; }
    $('#hero-btns a[rel="' + heroOn + '"]').click();
}


// START AUTO ROTATE INTERVAL
function startHeroRotate(rSpeed) {
    //autoRotate = window.setInterval("rotateHero("+rotateSpeed+")", rotateSpeed);
    autoRotate = window.setInterval(function () { rotateHero(rotateSpeed); startNewsRotation(); }, rotateSpeed);
}


// STOP AUTO ROTATE INTERVAL
function stopHeroRotate() {
    window.clearInterval(autoRotate);
    if (resumeInterval != "undefined") {
        window.clearInterval(resumeInterval);
    }
}


// BUILD HERO TIMER
function buildHeroTimer(rSpeed) {
    var total_secs = rSpeed / 1000;
    var sec = 1;
    $('#hero').append('<div id="hero-timer"></div>');
    $('#hero-timer').append('<ul></ul>');
    while (sec <= total_secs) {
        $('#hero-timer ul').append('<li></li>');
        sec++;
    }
    startHeroTimer(rSpeed);
}


// REMOVE HERO TIMER
function removeHeroTimer() {
    window.clearInterval(heroTimer);
    $('#hero-timer').remove();
    heroSec = 1;
}


// CYCLE HERO TIMER
function cycleHeroTimer(rSpeed) {
    var total_secs = rSpeed / 1000;
    var isSpent = $('#hero-timer ul').find('li.spent').length;

    /*-- start: new timer mechanism --*/
    var currBKGpos = '';
    if ($.browser.msie) {
        currBKGpos = $('#hero-btns a.on').css('backgroundPositionY');
        $('#hero-btns a.on').animate({
            backgroundPositionY: (parseInt(currBKGpos) - 2) + 'px'
        }, 800, function () {
            //console.log('anim comp');
        });
    }
    else {
        currBKGpos = $('#hero-btns a.on').css('backgroundPosition');
        var bkgArr = currBKGpos.split(' ');
        $('#hero-btns a.on').animate({
            backgroundPosition: '0px ' + (parseInt(bkgArr[1]) - 2) + 'px'
        }, 1000, function () {
            //console.log('anim comp');
        });
    }
    /*-- end: new timer mechanism --*/

    if (isSpent === 0) {
        $('#hero-timer ul li:last').addClass('spent');
    }
    else {
        $('#hero-timer ul li.spent:first').prev().addClass('spent');
    }

    /* not being used --sk_1/26/11
    if(heroSec == total_secs) {
    $('#hero-btns a.on').css('backgroundPosition','0px 0px');
    removeHeroTimer();
    }
    */
    heroSec++;
}

// ANIMATE BAR
function animateBar() {
    // Setup
    var bar = $('#hero-btns a.on');
    bar.css('backgroundPosition', '0px 0px');
    bar.animate({
        backgroundPosition: '20px 0px'
    }, 1000, 'linear', function () {
        animateBar();
    });
}


// START HERO TIMER
function startHeroTimer(rotateSpeed) {
    heroTimer = window.setInterval("cycleHeroTimer(" + rotateSpeed + ")", 1000);
}


// START HERO ROTATION AND TIMER
function startHeroRotation() {
    startHeroRotate();
    buildHeroTimer(rotateSpeed);
}


// STOP HERO ROTATION AND TIMER
function stopHeroRotation() {
    stopHeroRotate();
    removeHeroTimer();
}


// RESET HERO ROTATION
function resetHeroRotation() {
    stopHeroRotate();
    startHeroRotate();
}


// RESET HERO TIMER
function resetHeroTimer() {
    removeHeroTimer();
    buildHeroTimer(rotateSpeed);
}



// START NEWS ROTATION 
var W_newsCtr = $('#sap-news ul li').size();
var isNews = $('#sap-news-wrapper');
if (isNews[0]) {
    var W_newsHt = parseInt($('#sap-news-wrapper ul li').css('height').substring(0, $('#sap-news-wrapper ul li').css('height').indexOf('px'))) + 2;
}
var W_newsMax = ((W_newsCtr - 1) * W_newsHt) * -1;
var W_newsCrnt = 0;

function startNewsRotation() {
    if ($('.sap-news-wrapper-on').length == 0) { //News widget is closed
        //$('.btn-news-down').click();
        if (W_newsCrnt !== W_newsMax) { W_newsCrnt = W_newsCrnt - W_newsHt; $('#sap-news ul').animate({ top: W_newsCrnt }, 400); }
        else { W_newsCrnt = 0; $('#sap-news ul').animate({ top: W_newsCrnt }, 1000); }
    }
}





/*=== OVERLAYS ===*/

// CLOSE PREVIEW OVERLAY			
function closePreviewOverlay() {
    $('#blackout').remove();
    $('#previewContainer').remove();
}


// CLOSE OVERLAY			
function closeOverlay() {
    if ($('#overlay').length > 0) {
        removeBlackout($('#overlay').attr('class'));
        $('#overlay').fadeOut(500, function () { $('#overlay').remove(); });
        $('#nav-main a.on, ul#nav-utilitytop li a').removeClass('on');
        location.hash = '';
        document.title = pgTitle;
        showHero();
        if ($('#overlay').length != 0) {
            resumeHero();
        }
        $('#footer').removeClass('footer-panel').css({ 'position': 'absolute' });
        $('#header,#footer').css('z-index', '70');
        $('#nav-utilitytop a.on, #nav-utilitybtm a.on').removeClass('on');
        return false;
    }
}


// OPEN OVERLAY
function openOverlay(url_ref, class_ref) {
    if ($('body#home').length > 0) { //is home experience
        pauseHero();
        hideHero();
        if ($('#overlay').length > 0) { //overlay already open
            if (class_ref.search('utilitynav-') > -1) { //if "utilitynav" is found 
                $('#overlay').remove(); //remove open overlay
                $('body').prepend('<div id="overlay"></div>'); //append new overlay to <body>
            }
            $('#overlay').removeClass().addClass(class_ref); //change the class
        } else { //overlay not already open
            if (class_ref.search('utilitynav-') > -1) { //if "utilitynav" is found 
                $('body').prepend('<div id="overlay"></div>'); //append overlay to <body>
            } else { $('#page-content').append('<div id="overlay"></div>'); } //append overlay to #page-content
            $('#overlay').addClass(class_ref); //add class to overlay
        }
    }
    else { //is secondary page (ie. byDesign)
        if ($('#overlay').length > 0) { //overlay already open
            $('#overlay').removeClass().addClass(class_ref); //change the class
        } else { //overlay not already open
            if (class_ref.search('utilitynav-') > -1) { //if "utilitynav" is found 
                $('body').prepend('<div id="overlay"></div>'); //append overlay to <body>
            }
            else if (class_ref.search('byd-news-overlay') > -1) {
                $('body').prepend('<div id="overlay"></div>'); //append overlay to <body>
            }
            else if (class_ref.search('byd-tour') > -1) {
                $('body').prepend('<div id="overlay"></div>'); //append overlay to <body>
            }
            else { $('#page-content').append('<div id="overlay"></div>'); } //append overlay to #page-content
            $('#overlay').addClass(class_ref).css({ 'position': 'absolute', 'top': '120px' }); //add class to overlay
        }
        //if (url_ref.search('/news-reader/') > -1) { $('#overlay').addClass('byd-news-overlay'); }
    }
    getAJAX(url_ref, '#ajax-content-wrapper');
    applyBlackout(class_ref);
}


// CLOSE OVERLAY NEWS
function closeOverlayNews() {
    if ($('.sap-news-wrapper-on').length > 0) {
        $('#sap-news ul').css('top', '0');
        $('#sap-news h2 a.on').removeClass('on');
        $('#sap-news').removeClass('on');
        $('#sap-news-wrapper').removeClass('sap-news-wrapper-on');
        $('#sap-news-bottom').remove();
    }
}


// CLOSE OVERLAY QUICKLINKS
function closeOverlayQuicklinks() {
    if ($('#footer #quick-links.on').length > 0) {
        removeQLshadow();
        $('ul#footer-lefttop li#quick-links ul').slideUp(300);
        $('#quick-links.on').removeClass('on');
        $('#quick-links a.on').removeClass('on');
    }
}


// FOOTER TEXT AND PRINT LINKS
function showBrowserView() {
    $('link[href=/global/ui/css/print.css]').attr('media', 'print');
    resumeHero();
    $('#BrowserView').delay(300).animate({ height: '0px' }, 400, function () { $('#BrowserView').remove(); });
    inPrintView = false; //set global var to false
}
function CreateBrowserViewButton(clickFunc) {
    if ($.browser.msie && $.browser.version == "6.0")
        $('body').append("<div id=\"BrowserView\" style=\"background-image: url('/global/ui/images/buttons/btn-browser-view.png') !important; width: 208px; height: 0px; zoom: 1; cursor: pointer; position: absolute; right: 0px; bottom: 0px; z-index: 100;\"></div>");
    else
        $('body').append("<div id=\"BrowserView\" style=\"background-image: url('/global/ui/images/buttons/btn-browser-view.png') !important; width: 208px; height: 0px; zoom: 1; cursor: pointer; position: fixed; right: 0px; bottom: 0px; z-index: 100;\"></div>");
    $('#BrowserView').delay(300).animate({ height: '23px' }, 400).click(clickFunc);
}
function showText() {
    $('link[href=/global/ui/css/sapcom.css]').attr('media', 'none');
    $('*').attr('style', '');
    CreateBrowserViewButton(function () { window.location.reload(); });
}
function showPrint() {
    $('link[href=/global/ui/css/print.css]').attr('media', 'all');
    pauseHero();
    CreateBrowserViewButton(showBrowserView);
    setTimeout(function () { inPrintView = true }, 1000); //set global var to true 1 second after click event
}


// BLACKOUT
function applyBlackout(class_ref) {

    if ($('#blackout').length == 0) {
        $('body').prepend('<div id="blackout"></div>'); //$('body#home').prepend('<div id="blackout"></div>');
        //$('#footer').addClass('footer-panel');  //commented out by skiernan @ 3/28/11 9:10am to fix floating footer when making a request from the home/landing page
    }

    if (class_ref.substr(0, 11) == 'utilitynav-') {
        $('#blackout').css('z-index', '60').addClass('hot'); //class "hot" is the trigger used to make the overlay close onclick
        $('#overlay').css('z-index', '100');
        $('#footer').removeClass('footer-panel');
    }

    if (class_ref.substr(0) == 'utilitynav-locationselect') {
        $('#overlay').css({ 'left': '50%', 'top': '50px', 'width': '950px', 'margin': '0 0 58px -475px' });
    }

    if (class_ref.substr(0) == 'utilitynav-buy') {
        $('#overlay').css({ 'left': '50%', 'top': '50px', 'width': '950px', 'margin': '0 0 58px -475px' });
    }

    if ((class_ref.substr(0) == 'utilitynav-contact') || (class_ref.substr(0, 14) == 'utilitynav-reg')) {
        $('#header,#footer').css('z-index', '50');
    }

    if (class_ref == 'newslettertable') {
        $('#blackout').css('z-index', '60').addClass('preview'); //class "preview" is the trigger used to make the overlay close onclick
        $('#header,#footer').css('z-index', '50');
    }

    if (class_ref.substr(0) == 'forceLogin') {
        $('#blackout').css('z-index', '60');
        $('#header,#footer').css('z-index', '50');
    }
    if (class_ref == 'registration') {
        $('#blackout').css('z-index', '60');
        $('#header,#footer').css('z-index', '50');
    }

    if (class_ref == 'byd-news-overlay' || class_ref == 'byd-tour') {
        $('#overlay').css({ 'top': '50px', 'z-index': '70' });
        $('#blackout').css('z-index', '60').addClass('hot');
    }

    $('#blackout').css({ 'width': ($(window).width()), 'height': ($(window).height()) }).fadeIn(500).fadeTo(100, 0.4);
}

function removeBlackout(class_ref) {
    $('#blackout').fadeOut(500, function () { $('#blackout').remove(); });
    return false;
}

function hideHero() {
    $('#hero').fadeOut(500);
}

function showHero() {
    $('#hero').css('display', 'block');
}




// SHADOW EFFECTS

function buildQLshadow() {
    $('#quick-links').prepend('<div id="QLshadow"></div>');
    $('#QLshadow').css({ 'width': ($('#quick-links ul').outerWidth() - 1), 'height': ($('#quick-links ul').outerHeight() - 1) });
}

function removeQLshadow() {
    $('#QLshadow').remove();
}



/* no longer needed --sk 3/30
// SEARCH EVENTS
function searchEvents() {
$('#subright .subtab1').hide();
$('#subright .subtab2').show();
}
*/



/*=== SEARCH FILTERS ===*/
function updateFilter(url_ref, elemID) {
    location.hash = url_ref;
    $('#' + elemID).css('opacity', '0.3');
    $.get(url_ref, function (data) {
        getFilterHTML = $(data).find('#' + elemID).html();
        $('#' + elemID).css('opacity', '1');
        $('#' + elemID).html(getFilterHTML);
    });
}

function clearSiteSearchFilters() { //used to uncheck all site-search filters
    $('.srch_filter').attr('checked', false);
}


// ====== EVENTS SEARCH FORM FUNCTIONS ======== //
function initSearchEventsForm() {
    //---- 'Focus Area' section
    $('fieldset.radios input').each(function () {
        if ($(this).is(':checked')) {
            $(this).siblings('select').removeClass('disabled').attr('disabled', false);
        }
    });

    $('fieldset.radios input').change(function () {
        if ($(this).is(':checked')) {
            $('fieldset.radios select').addClass('disabled').attr('disabled', true).val('');
            $(this).siblings('select').removeClass('disabled').attr('disabled', false);
        }
    });

    //---- 'Location' section
    $('#selectregion').change(function () {
        if ($('#selectregion option:selected').val() == '') {
            $('#selectcountry').addClass('disabled').attr('disabled', true);
            $('#selectstate').addClass('disabled').attr('disabled', true);
        }
        else { $('#selectcountry').removeClass('disabled').attr('disabled', false); }
    });

    $('#selectcountry').change(function () {
        if ($('#selectcountry option:selected').val() == '') {
            $('#selectstate').addClass('disabled').attr('disabled', true);
        }
        else { $('#selectstate').removeClass('disabled').attr('disabled', false); }
    });

    if ($('#selectregion').val() != '') {
        $('#selectcountry').removeClass('disabled').attr('disabled', false);
        if ($('#selectcountry').val() != '') {
            $('#selectstate').removeClass('disabled').attr('disabled', false);
        }
    }

    //---- 'Date' section
    if ($('#event-startdate').val() != '') {
        $('label[for="startdate"]').hide();
    }
    if ($('#event-enddate').val() != '') {
        $('label[for="enddate"]').hide();
    }

    /* No longer a need for reset functionality. We now redirect back to the /events/index.epx page.
    //---- 'Reset' button  
    $('.resetbtn').click(function () {
    //-- reset 'Focus Area'
    $('fieldset.radios input').attr('checked', false);
    $('fieldset.radios select').addClass('disabled').attr('disabled', true).val('');
    //-- reset 'Location'
    $('#selectregion').val('');
    $('#selectcountry').addClass('disabled').attr('disabled', true).val('');
    $('#selectstate').addClass('disabled').attr('disabled', true).val('');
    //-- reset 'Date'
    $('#event-startdate').val('');
    $('label[for="startdate"]').show();
    $('#event-enddate').val('');
    $('label[for="enddate"]').show();
    //-- reset 'Type'
    $('input[type=checkbox]').attr('checked', true);
    });
    */

    $('#events-submit').live('click', function (e) {
        showLoadAnim('subbottom');
        $('#eventssearch').submit();
        e.preventDefault();
    });
}

/*=== DATE/CALENDAR (requires jquery ui) ===*/
/*-- Initialize "EVENTS" date picker --*/
function initEventDatePicker() {
    var dates = $("#event-startdate, #event-enddate").datepicker({
        numberOfMonths: 2,
        minDate: -365,
        beforeShow: function (input, inst) { $(this).siblings('label:first').hide(); },
        onSelect: function (selectedDate) {
            $(this).siblings('label:first').hide();
            var option = this.id == "event-startdate" ? "minDate" : "maxDate", instance = $(this).data('datepicker');
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            dates.not(this).datepicker('option', option, date);
        },
        onClose: function (dateText, inst) { if ($(this).val() == "") { $(this).siblings('label:first').show(); } }
    });
}



// ====== UNIVERSAL MEDIA PLAYER ====== //
/*-- Open Video Overlay --*/
$('a[rel="ump"]').live('click', function () {
    var getHref = $(this).attr('href'); location.hash = getHref; return false;
});

/*-- Initialize Universal Media Player --*/
function initUMP() {
    if ($('.ump-asset').length == 0) { //write necessary UMP assets to the DOM
        $('head').append('<link class="ump-asset" rel="stylesheet" type="text/css" href="global/ui/richmedia/css/UMP/rm_UMP_css.css" />');
        var script = document.createElement('script');
        script.setAttribute('src', '/global/ui/richmedia/js/require.js');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('data-main', 'utils/rm_initializer');
        script.setAttribute('class', 'ump-asset');
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    else { //nessary UMP assets already exist, re-init the player
        //UMP.setup();
        UMP.reInit();
    }

    if ($('.chapter').length > 0) {
        //set first chapter defaults
        $('#video-left-col .chapter:first').css({ 'border-top': '1px solid #888' }).addClass('open');
        $('#video-left-col .chapter:first .chapterLink a').addClass('on');
        $('#video-left-col .chapter:first .chapterDetail').css({ 'display': 'block' });

        /*-- Video Chapter Accordian --*/
        $('.chapterLink a').click(function (e) {
            var chapterDiv = $(this).parent().parent();
            var chapterLink = $(this);
            var chapterDetail = $(chapterDiv).find('.chapterDetail');

            //reset all to default
            $('.chapter').removeClass('open');
            $('.chapterLink a').removeClass('on');
            $('.chapterDetail').css('display', 'none');

            //set clicked element to open
            chapterLink.addClass('on');
            $(chapterDiv).addClass('open');
            chapterDetail.slideDown('fast');

            //prevent link from being redirected
            e.preventDefault();
        });
    }
}


/* ===== MY PROFILE MENU =============================================================================================== */
var myProfileMenu = '#utilitynav-myprofile-menu';
if ($(myProfileMenu).length > 0) { moveMyProfile(); }
function moveMyProfile() {
    myProfileMarkup = '<div style="" id="utilitynav-myprofile-menu" class="utility-dropdown">' + $(myProfileMenu).html() + '</div>';
    $(myProfileMenu).remove();
    $('#page-content').append(myProfileMarkup);
}



/* ===== PROMO ROTATION ================================================================================================ */

function initPromoRotate() {

    var promoA_length = $('#subrightcol-promo .promoA').length;
    var promoB_length = $('#htb-highlight-right .promoB').length;
    var promoType = '';
    var promoCount = 0;
    var promoOn = 0;
    var autoPromoRotate;

    if (promoA_length > 0) { promoCount = promoA_length; promoType = 'promoA'; }
    else if (promoB_length > 0) { promoCount = promoB_length; promoType = 'promoB' }

    //console.log('promoCount: '+promoCount);

    if (promoCount > 1) { //if more than one promo exists
        if (promoType == 'promoA') {
            $('#subrightcol-promo').append('<div id="promo-btns"></div>'); //add promo navigation button container
            $('#subrightcol-promo .promoA').each(function (index) { //iterate thru promos
                //$(this).addClass('promo' + (index));
                if ($(this).find('.cta-video').length > 0) { //if promo is a video
                    $('.cta-video', this).wrapInner('<span />'); //apply formatting needed for css rules
                }
                $('#promo-btns').append('<a href="" rel="' + (index) + '"></a>'); //append anchor to promo nav container with unique 'rel' attribute
                if (index == 0) { $('#promo-btns a:first').addClass('on'); } //add class="on" to first promo nav anchor
            });
        }
        if (promoType == 'promoB') {
            $('#htb-highlight-right').append('<div id="promo-btns"></div>'); //add promo navigation button container
            $('#htb-highlight-right .promoB').each(function (index) { //iterate thru promos
                //$(this).addClass('promo' + (index));
                /*
                if ($(this).find('.cta-video').length > 0) { //if promo is a video
                $('.cta-video', this).wrapInner('<span />'); //apply formatting needed for css rules
                }
                */
                $('#promo-btns').append('<a href="" rel="' + (index) + '"></a>'); //append anchor to promo nav container with unique 'rel' attribute
                if (index == 0) { $('#promo-btns a:first').addClass('on'); } //add class="on" to first promo nav anchor
            });
        }
        rotatePromo();
    }

    function rotatePromo() { //start promo rotation timer
        autoPromoRotate = window.setInterval(function () { //set 10 second rotation interval
            promoOn++; //increment "promoOn" variable by 1
            if (promoOn == promoCount) { promoOn = 0; } //if we reach the last promo, reset the "promoOn" variable back to beginning
            $('#promo-btns a:eq(' + promoOn + ')').click(); //trigger click event
        }, 10000);
    }

    function clearPromoInterval() { //clear promo rotation timer
        if (autoPromoRotate != "undefined") { //if the promo rotation timer is defined
            window.clearInterval(autoPromoRotate); //remove the timer
        }
    }

    $('#promo-btns a').live('click', function () { //promo navigation click event listener
        clearPromoInterval(); //clear previously set timer
        rotatePromo(); //start new timer
        getRel = $(this).attr('rel'); //get the current "rel" attribute
        promoOn = getRel; //update the "promoOn" variable
        if (!$(this).hasClass('on')) { //if clicked element does not have a class attribute of "on"
            getRel = parseInt(getRel); //get the value of the "rel" attribute and convert it to an integer
            $('#promo-btns a.on').removeClass('on'); //clear any promo nav items that currently have a class attribute of "on"
            $(this).addClass('on'); //add class attribute of "on" to the clicked element
            if (promoType == 'promoA') {
                $('#subrightcol-promo .promoA').hide(); //hide promos
                $('#subrightcol-promo .promoA:eq(' + getRel + ')').fadeIn(400); //fade in corresponding promo
            }
            if (promoType == 'promoB') {
                $('#htb-highlight-right .promoB').hide(); //hide promos
                $('#htb-highlight-right .promoB:eq(' + getRel + ')').css('display', 'block'); //show corresponding promo
            }
        }
    });

}



// ====== CUSTOM OVERLAYS ============================================================================================== //
//-- added 031711 --sk

var fireCloseOverlay_tier2, fireCloseOverlay_tier3 = '';
var refreshPage = false;

// OPEN OVERLAY LAYER 2
$.extend({
    openOverlay_tier2: function (url, classname, dialogURL, callback) {
        $('#page-content').append('<div id="overlay_tier2"></div>');
        $('#overlay_tier2').addClass(classname);
        $.get(url, function (data) {
            getContent = $(data).find('#ajax-content-wrapper').html();
            $('#overlay_tier2').fadeIn(500, function () { $('#overlay_tier2').html(getContent).prepend('<a href="" class="btn-close-overlay" aria-label="Close" aria-describedby="descriptionClose"></a>'); }).after(function () { blackoutReheight(); });
            if (typeof callback == 'function') {
                callback.call(this, data);
            }
        });
        applyBlackout(classname);
        $('html').scrollTop(0); //default scroll position back to top

        if (dialogURL != undefined && dialogURL != '') {
            fireCloseOverlay_tier2 = 'closeTieredOverlay("overlay_tier2", "' + dialogURL + '")';
        } else { fireCloseOverlay_tier2 = 'closeTieredOverlay("overlay_tier2")'; }
    }
});

// OPEN OVERLAY LAYER 3
$.extend({
    openOverlay_tier3: function (url, classname) {
        $('#page-content').append('<div id="overlay_tier3"></div>');
        $('#overlay_tier3').addClass(classname);
        $.get(url, function (data) {
            getContent = $(data).find('#ajax-content-wrapper').html();
            $('#overlay_tier3').fadeIn(500, function () { $('#overlay_tier3').html(getContent).prepend('<a href="" class="btn-close-overlay" aria-label="Close" aria-describedby="descriptionClose"></a>'); }).after(function () { blackoutReheight(); });
            if (typeof callback == 'function') {
                callback.call(this, data);
            }
        });
        applyBlackout(classname);
        $('html').scrollTop(0); //default scroll position back to top

        fireCloseOverlay_tier3 = 'closeTieredOverlay("overlay_tier3")';
    }
});

//function test(data) { console.log($(data).find('#descriptionClose').html()); }

// CLOSE OVERLAY TIER	
function closeTieredOverlay(elmID, dialogURL, refreshPage) {
    if ($('#overlay_' + elmID).length > 0) {
        if ($('#overlay_' + elmID).hasClass('confirm')) {
            if (dialogURL != undefined) {
                $.openOverlay_tier3(dialogURL, 'registration_overlay');
            }
            else { console.log('Missing Parameter: dialogURL is NOT defined'); }
        }
        else {
            if ($('#overlay_tier3').length > 0) {
                $('#overlay_' + elmID).fadeOut(500, function () { $('#overlay_' + elmID).remove(); });
            }
            else {
                $('#overlay_' + elmID).fadeOut(500, function () { $('#overlay_' + elmID).remove(); });
                $('#blackout').css('z-index', '10');
                $('#header').css('z-index', '70');
                $('#footer').css('z-index', '150');
            }
        }
        if (refreshPage == true) { window.location.reload(); }
    }
}

function closeAllTieredOverlays(refreshPage) {
    $('#overlay_tier2').fadeOut(500, function () { $('#overlay_tier2').remove(); });
    $('#overlay_tier3').fadeOut(500, function () { $('#overlay_tier3').remove(); });
    $('#blackout').css('z-index', '10');
    $('#header').css('z-index', '70');
    $('#footer').css('z-index', '150');
    if (refreshPage == true) { window.location.reload(); }
}

$('#overlay_tier2 a.btn-close-overlay').live('click', function () {
    //console.log('fire... '+fireCloseOverlay_tier2);
    eval(fireCloseOverlay_tier2);
    return false;
});

$('#overlay_tier3 a.btn-close-overlay').live('click', function () {
    //console.log('fire... '+fireCloseOverlay_tier3);
    eval(fireCloseOverlay_tier3);
    return false;
});





// ================ BYD GUIDED TOUR CONTROLS =============================== //

function initBYDtour() {
    var option1 = getCookie('option1');
    var select2 = getCookie('select2');

    //== if cookie is already present, populate drop-downs
    if (option1 != null) {
        $('.tour_choice2 #option1').val(option1);
    }
    if (select2 != null) {
        $('.tour_choice1 #select2').val(select2);
    }

    //== choice option (my company sells) > set cookie
    $('#option1').change(function () { set_cookie('option1', $(this).val()); });

    //== select2 option (I am in) > set cookie
    $("#select2").change(function () { set_cookie('select2', $(this).val()); });

    //== showhide 1
    switch (option1) {
        case 'choice1': $('#option1-' + option1).show(); break;
        case 'choice2': $('#option1-' + option1).show(); break;
        case 'choice3': $('#option1-' + option1).show(); break;
    }

    //== show hide 2
    switch (select2) {
        case 'select1': $('#select2-' + select2).show(); break;
        case 'select2': $('#select2-' + select2).show(); break;
        case 'select3': $('#select2-' + select2).show(); break;
        case 'select4': $('#select2-' + select2).show(); break;
        case 'select5': $('#select2-' + select2).show(); break;
        case 'select6': $('#select2-' + select2).show(); break;
        case 'select7': $('#select2-' + select2).show(); break;
        case 'select8': $('#select2-' + select2).show(); break;
        case 'select9': $('#select2-' + select2).show(); break;
    }

    //== capture button clicks
    $('#tour-start').live('click', function (e) {
        if ($('option[value=None]:selected').val() == "None") {
            alert("please make a selection from both options");
        }
        else { location.hash = $(this).attr('href') + '?class=byd-tour'; }
        e.preventDefault();
    });

    $('.tour-next').live('click', function (e) {
        var url_ref = $(this).attr('href');
        location.hash = url_ref + '?class=byd-tour';
        e.preventDefault();
    });

    $('#tour-close').live('click', function (e) {
        closeOverlay();
        e.preventDefault();
    });

    $('.tour_wrap .leave').live('click', function (e) {
        closeOverlay();
        //e.preventDefault();
    });

    $('.video .related-content a').live('click', function (e) {
        var getAssetID = $(this).attr('rel');
        var getVidPath = $(this).attr('href');
        var parentUMP = $(this).parents('.video').find('.UMP_div');
        $(parentUMP).attr('id', getAssetID).fadeOut('fast').html('\
			<ul>\
				<li id="assetId">' + getAssetID + '</li>\
				<li id="source-mp4">' + getVidPath + '</li>\
				<li id="width">488</li>\
				<li id="height">294</li>\
			</ul>\
		').fadeIn('fast');
        initUMP();
        e.preventDefault();
    });

    //Fix for generated play button when multiple instances of the UMP exist on one page
    if ($('.btnPlay').length > 1) { //if there is more than one play button rendered on the page
        var getInlineStyles = $('#play').attr('style'); //get the inline styles of the first play button
        $('.btnPlay').attr('style', getInlineStyles); //apply these same styles to additonal play buttons
    }

}


/*==== CREATE EMAIL ====*/
function CreateMailMessage(subject, message) {
    var lnk = "mailto:?";
    (subject.length > 0) ? lnk += "subject=" + escape(subject) + "&" : lnk = lnk;
    (message.length > 0) ? lnk += "body=" + escape(message) : lnk = lnk;
    location.href = lnk;
}
