// JavaScript Document

var BNS = 'Uninitialized';
BNS = function() {

	// let the DOM note that JS is enabled
	$('html').removeClass('no-js').addClass('js-on');

	// determine if userAgent is IE / IE6, dependant on the DOM structure
	var isIE	= ($('#ie6, #ie7, #ie8, #ie9').length) ? true : false;
	var isIE6	= ($('#ie6').length) ? true : false;
	var mobile	= false; // to be implemented

	// input clear
	$('input.clear-on-focus').each( function() {

		$(this).data('initValue', $(this).val());

		$(this).focus( function(e) {

			if ($(this).val() === $(this).data('initValue'))
				$(this).val('');
		});
		$(this).blur( function(e) {

			if ($(this).val() === '')
				$(this).val($(this).data('initValue'));
		});
	});
	// font-sizer
	$('#font-size a').click( function(e) {
		e.preventDefault();
		var fontSizer = $('#font-size');
		var selectedClass = $(this).parent().attr('class');
		var className = 'default';

		fontSizer.attr('class', selectedClass);

		if (selectedClass.indexOf('lrg') != -1)
			className = 'lrg';
		if (selectedClass.indexOf('x-lrg') != -1)
			className = 'x-lrg';

		$('#content,#footer').removeClass('default lrg x-lrg').addClass(className);

		$(this).blur();
	});
	// Fix hovers in IE6
	if (isIE6) {
		$('#font-size li,#footer .products li h3').hover( function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		}
		);
	}

	// mega menu & service menu
	$('#mega-menu > li > a,#service-menu > li > a').keydown( function(e) {
		// tabbing forward
		if (!e.shiftKey) {
			if (e.which == 9) {
				// If we're blurring from the "How do I?" menu item, focus the search field.
				if ($(this).attr('id')=='how') {
					e.preventDefault();
					$(this).parent().removeClass('active');
					$(this).parent().next().find('#search-query').focus();
				} else if ($(this).attr('id')=='mm-tab-g' || $(this).parent().is(':last-child')) {
					e.preventDefault();
					$(this).parent().removeClass('active');
					var contentLink = $('#content a').filter(':visible').eq(0);
					if (contentLink.length) {
						contentLink.focus();
					} else {
						$('#footer a:eq(0)').focus();
					}
				} else {
					var nextTopLevel = $(this).parent().next().find('a:eq(0)');
					if (nextTopLevel.length) {
						e.preventDefault();
						$(this).parent().removeClass('active');
						nextTopLevel.focus();
					}
				}
			}
		}
		//tabbing backward
		else {
			if (e.which == 9) {
				var prevTopLevel = $(this).parent().prev().find('a:eq(0)');
				if (prevTopLevel.length) {
					e.preventDefault();
					$(this).parent().removeClass('active');
					prevTopLevel.focus();
				}
				if ($(this).parent().is(':first-child')) {
					$(this).parent().removeClass('active');
				}
			}
		}
	});
	var menu = {
		services 	: $('#service-menu'),
		mega		: $('#mega-menu'),
		signin		: $('#sign-in-panel'),
		sites		: $('#scotia-sites')
	};

	menu.services.data('contentHeight', 265);
	menu.services.data('tabOpen', false);

	menu.mega.data('contentHeight', 280);
	menu.mega.data('tabOpen', false);

	menu.signin.data('contentHeight', 65);
	menu.signin.data('tabOpen', false);
	
	menu.sites.data('contentHeight', 440);
	menu.sites.data('tabOpen', false);
	
	if (navigator.userAgent.match(/mobile/i)) {
		document.body.ontouchstart = function(e) {
			var $target = $(e.target);
			if (jQuery.contains(menu.mega.get(0),$target.get(0)) || jQuery.contains(menu.services.get(0), $target.get(0)) ) {
				return;
			}

			$('#mega-menu,#service-menu,#sign-in-panel,#scotia-sites').find('a.tab').parent().removeClass('active');
            $('#mega-menu li .content, #service-menu li .content, #sign-in-panel li .content, #scotia-sites li .content').hide();
		}
	}

	function activateMenu(menu) {

		if ( ! menu )
			return;

		if (navigator.userAgent.match(/mobile/i)) {
			// Bind click to close all megamenus and open the clicked one
			var menuItems = menu.find('a.tab');
			menuItems.bind('click', function(e) {
				e.preventDefault();

				var $content = $(this).next();
				// If the user clicked the already active mega menu,
				// navigate to the url
				if ($(this).parent().hasClass('active')) {
					document.location = $(this).attr('href');
				}

				$('#mega-menu,#service-menu,#sign-in-panel,#scotia-sites').find('a.tab').parent().removeClass('active');
				$(this).parent().addClass('active');

				// Hide all open megamenus
				$('#mega-menu li .content, #service-menu li .content, #sign-in-panel li .content, #scotia-sites li .content').hide();
				// Then show the content for the menu clicked
				$content.css('height',menu.data('contentHeight')+'px').show();

			});
		} else {
			// capture MENU mouse leave
			menu.mouseleave( function(e) {

				var node = menu.find('li.active'),
				content = node.children('.content');

				content.css('height', 0);
				content.css('border-width', '0');
				content.css('display', 'none');
				node.removeClass('active');

				menu.data('tabOpen', false);
			});
			// default behavior
			var menuItems = menu.children('li');
			menuItems.each( function(i) {

				$(this).children('.content').css('height', '0');

				// capture MENU ITEM mouse enter
				$(this).mouseenter( function(e) {

					var node = $(e.currentTarget),
					content = node.children('.content');

					if (menu.data('tabOpen')) {

						menu.find('li.active').removeClass('active');
						content.css('display', 'block');
						content.css('border-width','1px');
						content.css('height', menu.data('contentHeight') +'px');
						node.addClass('active');

						menu.data('tabOpen', true);
					} else {

						menuTimeout = window.setTimeout( function() {

							content.css('height', '0');
							content.css('border-width','0');
							content.css('display', 'block');
							content.css('border-width','1px');
							content.animate({
								height: menu.data('contentHeight')
							}, 100, 'swing');
							node.addClass('active');

							menu.data('tabOpen', true);
						}, 500);
					}
				});
				// capture MENU ITEM mouse leave
				$(this).mouseleave( function(e) {

					var node = $(e.currentTarget),
					content = node.children('.content');

					if (menuTimeout)
						clearTimeout(menuTimeout);

					$('.content:animated').stop();

					content.css('height', '0');
					content.css('border-width','0');
					content.css('display', 'none');
					node.removeClass('active');
				});
			});
		}

		// screen reader behavior
		var menuTabs = menu.find('a.tab');
		if (!navigator.userAgent.match(/mobile/i)) {
			menuTabs.each( function(i) {

				$(this).focus( function(e) {

					menuItems.removeClass('active');
					$(this).parent().addClass('active');
					//alert(1);
				});
			});
		}

		// skip & close buttons
		menuItems = menu.children('.content a.skip').add(menu.children('.content a.close'));
		menuItems.click( function(e) {

			var tab = menu.find('li.active');

			tab.removeClass('active');
			tab.next().find('a.tab').focus();
		});
	}
	activateMenu(menu.services);
	activateMenu(menu.mega);
	activateMenu(menu.signin);
	activateMenu(menu.sites);


	// disable dead links
	$('a[href=#]').click( function(e) {
		e.preventDefault();
	});
	learningBar = {
		bar: $('#learning-bar'),
		open: function() {
			if (navigator.userAgent.match(/mobile/i))
				return;
			this.bar.data('auto-opened',true);
			this.bar.addClass('open');
			if (!isIE6) {
				this.bar.find('.content').animate({
					height:'55px'
				},1000);
			} else {
				this.bar.find('.content').height('55px');
				this.ie6fix();
			}
			this.bar.find('.content').show();
			$('#minimize-learning-bar a').text(this.bar.attr('data-close-text'));
			this.bar.find('.content a').removeAttr('tabindex');
		},
		close: function() {
			this.bar.removeClass('open');
			if (!isIE6) {
				this.bar.find('.content').animate({
					height:'0px'
				},500,'linear', function() {
					$(this).hide();
				});
			} else {
				this.bar.find('.content').height('0px');
				this.ie6fix();
			}

			$('#minimize-learning-bar a').text(this.bar.attr('data-open-text'));
			this.bar.find('.content a').attr('tabindex','-1');

		},
		ie6fix: function() {
			var barHeight = this.bar.height();
			this.bar.css('top', $(window).scrollTop() + ($(window).height() - barHeight -2) + "px");
		}
	};

	// Remove skip to page navigation when the page navigation does not exist
	// If the left sidebar doesn't exist, the skip to content link should point to #content, not #content-head
	// Ideally this would be handled by the application and removed from javascript
	if (!$('#side-nav').length) {
		$('#top a[href=#side-nav]').remove();
		$('#top a[href=#content-head]').attr('href','#content');
	}

	// Initialize and enable learning bar
	$('#minimize-learning-bar a').text($('#learning-bar').attr('data-open-text'));
	$('#learning-bar .content a').attr('tabindex','-1');
	$(window).scroll( function() {
		if ($(this).height() + $(this).scrollTop() >= $(document).height() - 500) {
			if (!$('#learning-bar').data('auto-opened')) {
				learningBar.open();
			}
		}
	});
	if (isIE6) {
		$(window).resize( function() {
			learningBar.ie6fix();
		});
	}

	// Minimize learning bar

	$('#minimize-learning-bar').click( function(e) {
		e.preventDefault();
		if (! $(this).parent().hasClass('open')) {
			learningBar.open();
		} else {
			learningBar.close();
		}
	});
	// IE 6
	if (isIE6) {

		// implement fixed positioning for the learning bar
		$(window).scroll( function() {
			learningBar.ie6fix();
		});
		$(document).ready( function() {
			learningBar.ie6fix();
		});
		// Fix hover of question divs
		$('#questions > div').hover( function() {
			if (!$(this).hasClass('active')) {
				$(this).addClass('hover');
			} else {
				$(this).addClass('hover-active');
			}
		}, function() {
			$(this).removeClass('hover hover-active');
		}
		);
	}

	/* Tooltips*/

	$('#help-tooltips strong').hide();
	$('#help-tooltips').hide();

	$('#close-help').live('click', function() {
		$(this).prev().prev().focus().find('img').attr('src','/rd/gfx/icn-info.png');
		$('#context-help,#close-help').remove();
		return false;
	});
	$('#context-help').live('blur', function() {
		//$(this).closest('.tool-tip').eq(0).focus();
		$(this).prev().focus().find('img').attr('src','/rd/gfx/icn-info.png');
		$('#context-help,#close-help').remove();
	});
	$('.tool-tip').each( function() {

		$(this).click( function(e) {
			$(this).find('img').attr('src','/rd/gfx/icn-info-disabled.png');
			$('#context-help, #close-help').remove();

			// Save the reference to the help button, get the href, and the content of the linked <p> element
			var $button = $(this);
			var href = $button.attr('href');
			var content = $(href).html();

			// Create the help item and insert it after the the help button in DOM order
			$button.after('<div id="context-help" role="alertdialog" aria-hidden="false" aria-labelledby="help-title" aria-describedby="help-description"><h3 id="help-title">'+$('#help-tooltips strong').html()+'</h3><div id="help-description">'+content+'</div></div>');
			var $help = $('#context-help');
			$help.find('strong').eq(0).remove();

			// Create the close button and insert it after the help text in DOM order
			$help.after('<a href="#context-help" id="close-help"><img src="/rd/gfx/icn-close.png" alt="Close glossary" /></a>');
			var $close = $('#close-help');

			// Get the top and left position of the help button for positioning the close button and help text, also set the tabindex of the help text to make it focusable

			var $position = $button.position();

			$help
			.css("top",($position.top - 9) + "px")
			.css("left",($position.left + 17) + "px")
			.show();

			closeFix = 2;
            if ($.browser.msie && parseInt($.browser.version)==6 || parseInt($.browser.version)==7) closeFix = 0;

			$close
				.css("top",($position.top - closeFix) + "px")
				.css("left",($position.left + 260) + "px")
				.show();

			var help_el = document.getElementById('context-help');
			help_el.tabIndex = -1;
			help_el.focus();

			$(help_el).keydown( function(e) {
				// ESCAPE key pressed
				if(e.keyCode == 27) {
					//$(this).prevAll('.help').eq(0).focus();
					$(this).prev().focus();
					$('#context-help, #close-help').remove();
					return false;
				}
			});
			return false;

		});
		//$(this).mouseleave( hideToolTip );
	});
	// collapsable Q & A
	var questions = $('.question');
	questions.click( function(e) {

		var clicked = $(e.target);
		if (clicked.parents('.content').length > 0 || clicked.is('.content'))
			return true;

		var isOpen = ($(this).hasClass('active'))? true : false;

		questions.removeClass('active');

		if ( ! isOpen )
			$(this).addClass('active');

		return false;
	});	
	// disclaimer
	var disclaimer = $('.legal');
	disclaimer.click(function(e){

        var clicked = $(e.target);
        if (clicked.parents('.content').length > 0 || clicked.is('.content')) 
            return true;
		
		var isOpen = ($(this).hasClass('active'))? true : false;
		
		disclaimer.removeClass('active');
		
		if ( ! isOpen )
			$(this).addClass('active');

        return false;
	});
	// tabbed content
	var tabbedContent = $('.tabbed-content'),
	controller,
	tabs;

	tabbedContent.each( function() {

		controller = $(this).find('.tab-controller');
		tabs = controller.find('.tabs a');
		tabs.each( function() {

			$(this).click( function(e) {

				e.preventDefault();
				var className = $(this).parent().attr('className')
				controller.attr('className', 'tab-controller ' +className);
				var currentMarker = $('.tabs .current-marker');
				currentMarker.insertBefore($(this));
				$('div.content.'+className).focus();
			});
		});
	});
	
	
	$('a.open-tab').click(function(e){
	
	var target = $(e.target),
		tab = target.attr('href').substr(5);
	
	$('.tab-controller li.' +tab+ ' a').click();
});
	
	
	
	/*
	 * OVERLAYS
	 * 
	 * 	any anchor elements with the CLASS "open-overlay" will open an overlay new.
	 * 	anchor should have the overlay's content ID in the HREF attribute.
	 */
	var overlayMask = $('<div id="overlay-mask"/>');
	$('body').append( overlayMask );
	
	$('a.open-overlay').click(function(e){
		
		e.preventDefault();
		
		var target = $(e.target),
			overlay = $(target.attr('href')),
            origin = $(this),
			closeBtn = overlay.find('a.close');

        if (target.attr('href') == '#ready-to-apply-overlay') {
            $('#ready-to-apply-overlay').data('launcher',target);
            $('#ready-to-apply-overlay').dialog('open');
            return false;
        }
	
	if (target.attr('href') == '#ready-to-apply-overlay-slf') {
            $('#ready-to-apply-overlay-slf').data('launcher',target);
            $('#ready-to-apply-overlay-slf').dialog('open');
            return false;
        }
		
		if (target.attr('href') == '#ready-to-apply-overlay-btr') {
            $('#ready-to-apply-overlay-btr').data('launcher',target);
            $('#ready-to-apply-overlay-btr').dialog('open');
            return false;
        }
		
	 if (target.attr('href') == '#ready-to-apply-overlay-scene') {
            $('#ready-to-apply-overlay-scene').data('launcher',target);
            $('#ready-to-apply-overlay-scene').dialog('open');
            return false;
        }
		
	 if (target.attr('href') == '#business-overlay') {
            $('#business-overlay').data('launcher',target);
            $('#business-overlay').dialog('open');
            return false;
        }
		
		if ( overlay.size() > 0 ){
			
			// document state
			$('body').addClass('overlay-open');
			
			// position elements
			overlayMask.css('height',$('body').height());
			overlay.css('left', (($('body').width() - overlay.outerWidth()) / 2) + $(window).scrollLeft() + "px")
			overlay.css('top', (($(window).height() - overlay.outerHeight()) / 2) + $(window).scrollTop() + "px")
			
			overlayMask.show(); 
			overlay.fadeIn(500);
	    
            $(document).keydown( function(e) {
                if (e.which == 27) { // Esc key
                    closeOverlay(e);	
                }
            });		
			
			function closeOverlay(e){
				
				e.preventDefault();
				
				overlay.fadeOut( 500, function(){
					
					overlayMask.unbind('click.closeOverlay');
					overlayMask.hide();
				});
				
				$('body').removeClass('overlay-open');
				closeBtn.unbind('click.closeOverlay');
			}
			
			overlayMask.bind('click.closeOverlay', closeOverlay);
			closeBtn.bind('click.closeOverlay', closeOverlay);
		}
	});
	
	// zebra stripe
	$('.zebra-stripe > :odd').each( function() {

		$(this).addClass('odd');
	});
	$('table.zebra-stripe tr:even').addClass('odd');

	$('a.toggleHiddenText').click( function() {
		var prevSpan = $(this).prev();
		if (prevSpan.hasClass('hidden')) {
			prevSpan.removeClass('hidden');
			$(this).text($(this).attr('data-lang-less'));
		} else {
			prevSpan.addClass('hidden');
			$(this).text($(this).attr('data-lang-more'));
		}
		return false;
	});
	return 'Initialized';

}();
if (BNS!='Initialized')
	alert('Page could not initialize.');
	
	


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


var COOKIE_NAME = 'ie6';

function closeIEMsg() {
	
	$('.overlay').fadeOut(500)
	$('#overlay-mask').css('display', 'none');
	$('.overlay').css('display', 'none');
}

$(window).load(function(){
	  
  if ( $.browser.msie && $.browser.version == "6.0") {

     if($.cookie(COOKIE_NAME) == null) {
			$.cookie(COOKIE_NAME, 'active', { expires: 1 }); 
			$('#overlay-mask').css('display', 'block');
			$('.overlay').css('display', 'block');

			$('#overlay-mask').css('height',$('body').height());
			
			$('#overlay-mask').after('<div id="ie6-message" class="overlay"><h2>Still using IE6?</h2><p>We noticed that you\'re still using Internet Explorer 6 as your web browser, which we no longer support. To experience Scotiabank.com at its best, please upgrade to <a href="http://windows.microsoft.com/en-CA/internet-explorer/products/ie/home">latest supported version of Internet Explorer</a>. <a href="#" class="red-btn" onclick="javascript:closeIEMsg(); return false;">Back to Scotiabank.com</a></p></div>');
			
			$('.overlay').css('top', (($(window).height() - $('.overlay').outerHeight()) / 2) + $(window).scrollTop() + 'px');
    		$('.overlay').css('left', (($('body').width() - $('.overlay').outerWidth()) / 2) + $(window).scrollLeft() + 'px');
			
			$('.overlay').fadeIn(500);

	}
  }
});

function chkPostalCode() {
		var provPC = document.pc.postalCode.value;
		var regexp = /^\s*[a-ceghj-npr-tvxy]\d[a-ceghj-npr-tv-z](\s)?\d[a-ceghj-npr-tv-z]\d\s*$/i;
		
		if ( provPC.match(regexp) ) {
			provPC = provPC.substr(0, 1)
			provPC = provPC.toUpperCase();
			
			if (provPC == "J" || provPC == "H" || provPC =="G") {
					window.open('https://hermes.manulife.com/can/affinity/travel/travel.nsf/public/scotialifetravelinsurance?open&as=scotiabank ','scotia')
			} else {
					window.open('https://hermes.manulife.com/can/affinity/travel/travel.nsf/public/scotialifetravelinsurance?open&as=scotialife ','scotia')
			}
			return true;
		} else {
			alert('Please enter a valid postal code.');
			
			return false;
		} 
		
	}
