/**
 * The code between here and the HSBC copyright notice is derived from the unobfuscated library under the following terms:
 *
 * Unobfuscated accessibility library
 * @requires jQuery and jQuery UI
 *
 * Copyright (c) 2011 @unobfuscator http://unobfuscated.blogspot.com/
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Version: 0.3
 * 
 */

var unobfuscated = {};
(function( $) {
    // Unobfuscated globals go here
    var locale = 'en';
    var focusStack = [];
    var localeStrings = {
        en: {
            onmessage:"If you can hear this announcement, your setup supports WAI-ARIA. Press the Ctrl key 3 times to make this announcement never appear again."
            ,offmessage:"Press the Ctrl key 3 times to toggle WAI-ARIA off"
            ,confirmScreenReaderUser:"It looks like you use a screen reader and this screen reader is {0}. If this is true, select OK?"
            ,menuStatusText:", menu item {0} of {1}" // {0} == thisnum, {1} == totalnum
            ,tabStatusText:", tab {2} {0} of {1}" // {0} == thisnum, {1} == totalnum, {2} if selected
            ,selectedText:", Selected,"
            ,dialogAppeared:"A Dialog Box Has Appeared. Use the Tab key to navigate to the dialog."
            ,searchThenTab:'Search for services. Tab to see results'
            ,showLess:'Show less'
            ,showMore:'Show more'
            ,emailProgram:"Email program"
            ,escToClose:", press ESC to close"
        }
    }
    // Unobfuscated public functions go here
    $.getMessage = function( name) {
        if ( typeof localeStrings[locale] != 'undefined') {
            if ( typeof localeStrings[locale][name] != 'undefined') {
                return localeStrings[locale][name];
            }
        }
        return "";
    };
    $.setLocale = function( newLocale) {
        locale = newLocale;
    };
    $.debug = function(msg){
        if(window.console && window.console.log){
            window.console.log(msg);
        } else {
            jQuery('#debug').empty().append( jQuery('<p>').text(msg));
        }
    };
    $.getCurrentFocus= function() {
        if ( focusStack.length < 1) return null;
        return focusStack[focusStack.length-1];
    };
    $.getPreviousFocus= function() {
        if ( focusStack.length <= 1) return null;
        return focusStack[focusStack.length-2];
    };
    $.isLastFocusInsideWidget= function( ourNode) {
        var prev = $un.getPreviousFocus();
        while ( prev && prev.nodeName.toLowerCase() != "body") {
            if ( prev == ourNode) {
                break;
            }
            prev = prev.parentNode;
        }
        if ( prev && prev.nodeName.toLowerCase() == "body") return false;
        return true;
    };
    $.setA2aTabOffscreenText = function() {
        // This function sets offscreen text so the screen reader knows which tab is
        // activated and how many tabs there are
        var tabCount = jQuery('.a2a_tabs').length;
        jQuery('.a2a_tabs>div>span>span').remove();
        jQuery('.a2a_tabs>div>span').each( function(i, s) {
            var t = $un.getMessage( 'tabStatusText');
            var st = $un.getMessage( 'selectedText');
            t = t.replace( "{0}", i+1);
            t = t.replace( "{1}", tabCount);
            if ( jQuery(s).parent().hasClass( 'a2a_tab_selected')) {
                t = t.replace( "{2}", st);
            } else {
                t = t.replace( "{2}", "");
            }
            var os = jQuery( '<span>').attr("class", "offscreen").text( t);
            jQuery( s).append( os);
        });
    };
    // Unobfuscated initialization goes here
    (function() {
        jQuery(document).delegate( "*", "focusin", function( event) {
            if ( focusStack[focusStack.length-1] != event.target) {
                focusStack.push( event.target);
                if ( focusStack.length > 5) {
                    focusStack.splice( 0, focusStack.length - 5);
                }
            }
        });
    })();
})(unobfuscated);
var $un = unobfuscated;

/*
 * The code below this point was developed by Dylan Barrell @Deque Systems for HSBC
 * Copyright (C) 2011 HSBC, All rights reserved
 */


jQuery( document).ready( function() {
    var a2aShift = false;
    jQuery( '#a2apage_dropdown').delegate( "*", 'keydown', function(e) {
        if ( e.which == 16) {
            a2aShift = true;
        }
    }).delegate( "*", 'keyup', function(e) {
        if ( e.which == 16) {
            a2aShift = false;
        }
    });
    jQuery('.a2a_tabs>div>span').each( function(i, s) {
        // Change the tab text when the tabs are clicked
        jQuery(s).attr("tabindex", 0).bind( 'keydown', function( e) {
            if ( e.which == 13) {
                jQuery( e.target).trigger( 'click');
            }
        }).bind( 'click', function( e) {
            setTimeout( $un.setA2aTabOffscreenText, 0);
        });
    });
    // remove on blur handler which causes problems for keyboard users
    // also remove title because we are adding a better label
    jQuery('#a2apage_find').attr("onblur","").attr('title', "").before(
        // Add label to the search input field
        jQuery('<label>').attr( 'for', 'a2apage_find').attr('class', 'offscreen').text($un.getMessage('searchThenTab'))
    );
    // Set focus when the UI is activated
    jQuery('.a2a_dd').bind('click', function(e) {
        jQuery( '.a2a_tab_selected>span').focus();
    });

    function focusOnShowMoreLess() {
        jQuery( '#a2apage_show_more_less').focus();
    }
    // Make the more/less link keyboard focussable and add off screen text to communicate the state
    jQuery( '#a2apage_show_more_less').attr( 'tabindex', 0).append(
        jQuery( '<span>').attr( 'class', 'offscreen').text( $un.getMessage('showMore'))
    ).bind( 'click', function( e) {
        if ( jQuery( this).find( '.a2a_i_uarr').length) {
            jQuery( this).find( '>span.offscreen').text( $un.getMessage('showLess'));
            setTimeout( focusOnShowMoreLess, 0);
        } else {
            jQuery( this).find( '>span.offscreen').text( $un.getMessage('showMore'));
            setTimeout( focusOnShowMoreLess, 0);
        }
    }).bind( 'blur focusout', function(e) {
        // the blur and focus are required to make sure that the handler
        // for the search does not trigger while we are focussed on the show more
        a2a.page.inFocus = a2a.page.fsave;
    }).bind( 'focusin focus', function(e) {
        a2a.page.fsave = a2a.page.inFocus ;
        a2a.page.inFocus = [0,0];
    });
    // add the necessary style for the focus on the more/less
    jQuery('head').append( "<style>.a2a_menu a:focus {\n    background-color: #EEEEEE;\n    border: 1px solid #CCCCCC;\n    color: #000000;\n    text-decoration: none;\n}</style>");
    
    // Add off screen text for the email program image link
    jQuery( '#a2apage_email_client').append(
        jQuery( '<span>').attr('class', 'offscreen').text( $un.getMessage('emailProgram'))
    );
    
    // Add focus management and Esc key to get rid of the UI
    jQuery( '#a2apage_dropdown').bind( 'keydown', function(e) {
        if ( e.which == 27) {
            e.preventDefault();
            e.stopPropagation();
            try {
                // try to set the focus, may fail if focus was never inside the document, hence try-catch
                jQuery(this.previousFocus).focus();
            } catch( err) {};
            a2a.onMouseOut_delay();
            jQuery(this).attr('style','display:none;');
        }
    }).bind( "focus focusin", function( event) {
        if ( !$un.isLastFocusInsideWidget( this)) {
            // need to remember this node because it is outside the dialog box
            this.previousFocus = $un.getPreviousFocus();
        }
        this.isFocussed = true;
    }).bind( "blur focusout", function( event) {
        this.isFocussed = false;
    }).each( function( i, d) {
        d.previousFocus = $un.getPreviousFocus();
    });
    var a2aText = jQuery( '#a2apage_powered_by').text();
    jQuery( '#a2apage_powered_by').keydown( function(e) {
        if ( e.which == 9) {
            if ( !a2aShift) {
                e.preventDefault();
                e.stopPropagation();
                jQuery('.a2a_tabs>div>span')[0].focus();
            }
        }
    }).text( a2aText + $un.getMessage( 'escToClose'));
    jQuery('.a2a_tabs>div>span').eq(0).keydown( function(e) {
        if ( e.which == 9) {
            if ( a2aShift) {
                e.preventDefault();
                e.stopPropagation();
                jQuery('#a2apage_powered_by').focus();
            }
        }
    });
    jQuery( '#a2apage_powered_by').bind( 'focusin', function(e) {
        jQuery( '#a2apage_powered_by').text( a2aText + $un.getMessage( 'escToClose'));
     });
     try{
        // Overwrite the function that sets the focus on the find when that tab is activated as this can cause disorientation
        a2a.focus_find = function() { return true;};
     }catch(e){}
    
    // Set the tabs initial offscreen text
    $un.setA2aTabOffscreenText();
});


