
$(document).ready(function() {
    yearLinks.init();
	anchors.addBehaviors();
	overlay.init();
	
	$('a.feeLink').hover(
		function() {
			$(this).siblings('p').show();
		},
		function() {
			$(this).siblings('p').hide();
		}
	);
	
	
	$('a#calcRate').click(function(e){
		e.preventDefault();
		if ($('input#totalVol').val() <= 0) {
			var rateStr = "N/A";
			alert("Please Try Again");
		} else {
			var newRate = String(Math.round(($('input#totalFee').val() / $('input#totalVol').val())*1000)/1000);
		
			if (isNaN(newRate)) {
				var rateStr = "N/A";
				alert("Please Try Again");
			} else {
				var rateStr = Math.round((newRate * 100) * 1000)/1000 + "%";
			}
		}
		
		$("#results span").html(rateStr);
	});

});


/* =================================================================== */
// for suckerfish dhtml menus
sfHover = function() {
	$('#navLevelOne li').each( function() {
		$(this).hover( function() {
			$(this).addClass('sfhover');
		}, function() {
			$(this).removeClass('sfhover');
		});
	});
}();
/* =================================================================== */
/* =================================================================== */
// Solution Focus show/hide functionality
(function(){
		$('.solutionFocus ul li').children('div').hide();
		$('.solutionFocus ul li').hover(function(e){
				$(this).children('div').show();
		}, function(e){
			$(this).children('div').hide();
		});
})();
/* =================================================================== */

/* =================================================================== */
// To set up and show and hide the Country/Region dropdown
(function(){
	var config = {
		closeLink:		'closeLink',
		displayClass:	'subContent',
		langLink: 		'nav-Languages',
		navLink:		'nav-Countries',
		openClass:		'open',
		subLink:		'choose-country',
		regionsID:		'regions'
	}
	
	// set up click event
	$('#'+config.navLink+', #'+config.subLink+', .'+config.closeLink).click( function(e) {
		showHideCountryDropDown(this);
		e.preventDefault();
	});
	$('#'+config.langLink).click( function(e) {
		$('#'+config.langLink).toggleClass('open');
		$('#'+config.regionsID).toggle();
		e.preventDefault();
	});
	// function called upon click
	function showHideCountryDropDown(link) {
		if ($('#'+config.regionsID).hasClass(config.openClass) && !$(link).hasClass(config.openClass) && !$(link).hasClass(config.closeLink)) {
			$('.'+config.openClass).removeClass(config.openClass);
			$('.'+config.displayClass).removeClass(config.displayClass);
			$('#'+config.regionsID).hide();
		} else {
			$('.'+config.openClass+':not(#'+config.regionsID+')').removeClass(config.openClass);
		}
		$(link).addClass(config.openClass)
		$('#'+config.regionsID).toggleClass('open').toggle(10, function () {
			(link.id == config.subLink) ? $(this).addClass(config.displayClass) : $(this).removeClass(config.displayClass);
			($(this).hasClass(config.openClass)) ? $(link).addClass(config.openClass) : $(link).removeClass(config.openClass);
		});
	}
})();
/* =================================================================== */

/* =================================================================== */
// To set up and show and hide the HP details
(function(){
	// hide details if JS is enabled
	$('#HPoverview .close, #HPoverview .expandable').removeClass('hide');
	$('#HPoverview div').hide();
	
	// setting up click events
	$('#HPoverview .close a').click(function (e){
			e.preventDefault();
			hideDetails();
	});
	
	$('#HPoverview .expandable a').click(function (e){
			e.preventDefault();
			showDetails();
	});

	// Show details function
	function showDetails() {
		$('#HPoverview div').show();
		$('#HPoverview .expandable').hide();
		$('#compliance').css('margin-top', '60px');
	}
	
	// Hide details function
	function hideDetails() {
		$('#HPoverview div').hide();
		$('#HPoverview .expandable').show();
		$('#compliance').css('margin-top', '27px');
	}
})();
/* =================================================================== */

/* =================================================================== */
// To set up and show and hide the Search box
(function(){
	var config = {
		navLink 	: 'nav-Search',
		searchForm	: 'search',
		searchField : 'searchField'
	}
	// set up click event
	$('#'+config.navLink).click( function(e) {
		showHideSearch();
		e.preventDefault();
	});
	// function called upon click
	this.showHideSearch = function() {
		$('#'+config.navLink).toggleClass('open');
		$('#'+config.searchForm).toggle();
		$('#'+config.searchField).focus();
	}
})();
/* =================================================================== */

/* =================================================================== */
var overlay = {
	config: {
		itemHeight: 510,
		itemWidth: 575,
		opacity: 6
	},
	
	init: function () {
		var links = $('a[rel="overlay"]').click(function (e) {
			e.preventDefault();
			overlay.open($(this));
		});
	},
	
	close: function () {
		$('#overlayBackground').remove();
		$('#overlay').remove();
	},
	
	createOverlay: function (url) {
		$(url+' a').removeClass('hide');
		$('body').append('<div id="overlayBackground"></div>');
		$('body').append('<div id="overlay"></div>');
		$('#overlay').prepend($(url).clone());
		$('#overlay a, #overlayBackground, #overlay').click(function (e) {
				e.preventDefault();
				overlay.close();
		});
		overlay.setStyles();
	},
	
	getDimensions: function (obj) {
		var x,y;
		var w = obj[0].clientWidth;
		var h = obj[0].clientHeight;
		
		if (w == 0) {
			w = 550;
			h = 350;
		}
		
		return {width:w,height:h};
	},
	
	open: function (el) {
		var url = $(el).attr('href');
		overlay.createOverlay(url);
	},
	
	setStyles: function () {
		var background = $('#overlayBackground');
		var overlayItem = $('#overlay');
		var closeLink = $('a', overlayItem);
		var pageDimensions = overlay.getDimensions($('#envelope'));
		var browserWindow = overlay.window();
		var backgroundWidth = '';
		
		(pageDimensions.width > browserWindow.width) ? backgroundWidth = pageDimensions.width : backgroundWidth = browserWindow.width-17;
		
		$(background).css({
				'background': '#000000',
				'height' : (pageDimensions.height)+'px',
				'width' : backgroundWidth+'px',
				'filter': 'alpha(opacity='+ overlay.config.opacity +'0)',
				'-moz-opacity' : overlay.config.opacity/10,
				'-khtml-opacity' : overlay.config.opacity/10,
				'opacity' : overlay.config.opacity/10,
				'position' : 'absolute',
				'top' : '0px',
				'left' : '0px',
				'z-index': '200'
		});
		$(overlayItem).css({
				'background': '#ffffff',
				'border' : '2px solid #919498',
				'height' : overlay.config.itemHeight,
				'padding' : '20px',
				'position' : 'absolute',
				'top' : ((browserWindow.height-(overlay.config.itemHeight+40))/2)+browserWindow.top+'px',
				'left' : (browserWindow.width-(overlay.config.itemWidth+40))/2+'px',
				'width' : overlay.config.itemWidth,
				'z-index' : '210'
		});
		
		$('div', overlayItem).css({
				'display' : 'block'
		});
		
		$(closeLink).css({
				'display' : 'block',
				'margin' : '10px 0 0 0'
		});
	},
	
	window: function (obj) {
		var h,w,x,y;
		
		if (self.innerHeight) { // all except Explorer 
			w = self.innerWidth;
			h = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		} else if (document.body) {// other Explorers
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		} 
		
		if (self.pageYOffset) { // all except Explorer
			x = self.pageXOffset;
			y = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		} else if (document.body) { // all other Explorers
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		} 
		
		return {width:w,height:h,top:y,left:x};
	}
};
/* =================================================================== */

/* =================================================================== */
// Set up the show/hide functionality for the team bios and collateral page
(function(){
        var config = {
            closeBioText :      'Close',
            containerDiv :      'expandable',
            hiddenClass  :      'hide',
            openClass    :      'open',
            readMoreLink :      'readMore',
            readMoreText :      'Read more'
        }
        
        $('#'+config.containerDiv+' > div > div').addClass(config.hiddenClass);
        $('.'+config.readMoreLink).removeClass(config.hiddenClass);
        
        $('#'+config.containerDiv).children('div').children('h3').children('a').click( function(e) {
                toggleBio(this.href);
                e.preventDefault();
        });
        
        $('#'+config.containerDiv).children('div').children('.'+config.readMoreLink).children('a').click( function(e) {
                toggleBio(this.href);
                e.preventDefault();
        });
        
        this.toggleBio = function(link) {
            var linkArr = link.split('#');
            $('#'+linkArr[1]+' > div').toggleClass(config.hiddenClass);
            $('#'+linkArr[1]+' > h3 > a').toggleClass(config.openClass);
            toggleReadLink($('#'+linkArr[1]).children('.'+config.readMoreLink).children('a'));
        };
        
        this.toggleReadLink = function(readLink) {
            if($(readLink).text() == config.readMoreText){
                $(readLink).text(config.closeBioText)
            }else{
                $(readLink).text(config.readMoreText)
            }
        };
})();
/* =================================================================== */

/* =================================================================== */
// Set up the show/hide functionality for the faq page
(function(){
        var config = {
            containerDiv:	'expandable',
            hiddenClass:	'hide',
            openClass:		'open'
        }
        
		hideAnswers();
		
        $('.'+config.containerDiv+' li  p').hide();
        
        $('.'+config.containerDiv+' li h4 a').click( function(e) {
            e.preventDefault();
			toggleFaq(this);
        });
		
		function hideAnswers() {
			$('.'+config.containerDiv+' li  p').hide();
			resetIcons();
		}
		
		function resetIcons () {
			$('.'+config.containerDiv+' li').removeClass(config.openClass);
		}
		
		function toggleFaq (link) {
			var parentLI = $(link).parents('li');
			if ($(parentLI).hasClass(config.openClass)) {
				hideAnswers();
				$(parentLI).removeClass(config.openClass);
			} else {
				hideAnswers();
				$(parentLI).addClass(config.openClass);
				$(parentLI).children('p').show();
			}
		}
})();
/* =================================================================== */

/* =================================================================== */
// content switcher
(function() {
	var config = {
		className	: 'current',
		divClass	: 'contentSwitcherContent'
	}
	// set up click event
	$('.'+config.divClass + ' ul').click( function(e) {
		var $target = $(e.target);
		if( $target.is("a") ) {
			switchContent( $target.parent('li') );
		}
		e.preventDefault();
	});
	// function called upon click, pass in the li that was clicked
	function switchContent($o) {
		var index = $o.parent('ul').children('li').index($o[0]);
		if (index >= 0) {
			// switch class in divs to div that matches index of clicked link
			$('.'+config.divClass + ' div').removeClass(config.className).eq(index).addClass(config.className);
			// switch 'current' class in list of items
			$o.siblings().children().removeClass(config.className).end().end().children('a').addClass(config.className);
		}
	}
})();
/* =================================================================== */


/* =================================================================== */
// Set up News page archive links
var yearLinks = {
        containerDiv :      'newsList',
        hideClass :         'hide',
        selectedClass :     'selected',
        yearDiv :           'yearSelector',
        
        attachEvents : function () {
            $('#'+this.yearDiv+' > li').children('a').click( function(e) {
                var $target = $(e.target);
                while (!$target.is('li')) {
                    $target = $target.parent();
                    if ($target.is('body')) {
                        return;
                    }
                }
                yearLinks.toggleYear($target);
                e.preventDefault();
            });
        },
        
        hideContent : function () {
            var selectedLink = $('#'+yearLinks.yearDiv+' > li > .selected').attr('href');
            selectedLink = selectedLink.split('#');
            $('.'+yearLinks.containerDiv).not('#'+selectedLink[1]).addClass(yearLinks.hideClass);
        },
        
        init : function () {
            if( $('#'+yearLinks.yearDiv) && $('#'+yearLinks.yearDiv).size() > 0 ) {
                yearLinks.hideContent();
                yearLinks.attachEvents();
            }
        },
        
        toggleYear : function ($target) {
            var selectedLink = $target.children('a').attr('href');
            selectedLink = selectedLink.split('#');
            $target.siblings().children('a').removeClass(yearLinks.selectedClass);
            $target.children('a').addClass(yearLinks.selectedClass);
            $('.'+yearLinks.containerDiv).removeClass(yearLinks.hideClass);
            $('.'+yearLinks.containerDiv).not('#'+selectedLink[1]).addClass(yearLinks.hideClass);
        }
        
};
/* =================================================================== */


/* =================================================================== */
// various link functionality - popups, external, onstate
// original script taken from Jeremy Keith
var anchors = {
	a: Object,
	addBehaviors : function() {
		$('a').each( function() {
			var $a = $(this);
			// external links
			if ( ($a.attr('href')) && ($a.attr('rel')=='external') || $a.hasClass('doc') ) {
				$a.click( function() {
					return anchors.openWin(this,"");
				});
			}
			if ( $a.hasClass('external') || $a.hasClass('pdf') ) {
				$a.click( function(e) {
					$(e).preventDefault;
					return anchors.openWin(this,"");
				});
			}
			// popup
			if ( $a.hasClass('popup') ) {
				$a.click( function() {
					return anchors.openWin(this,"height=626,width=990,scrollbars=yes,resizable=1");
				});
			}
			// popup Chat
			if ( $a.hasClass('popupChat') ) {
				$a.click( function() {
					return anchors.openWin(this," height=480, width=599, scrollbars=yes, resizable=1, menubar=0");
				});
			}
			// popup
			if ( $a.hasClass('demoWindow') ) {
				$a.click( function() {
					return anchors.openWin(this,"height=600,width=800");
				});
			}
			// onstate
			if ( $a.attr('href') == location.href ) {
				$a.addClass('onstate');
			}
		});
	},
	openWin : function(o,params) {
		window.open(o.href, "newwin","" + params + "");
		return false;
	}
};
/* =================================================================== */


/* =================================================================== */
// function to add events crossbrowser
// from: http://www.dustindiaz.com/rock-solid-addevent/
// uncomment the EventCache lines if using EventCache function from code lib
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

// use only with addEvent function
// this is here to clear the event cache to prevent memory leaks
// for more info:  http://novemberborn.net/javascript/event-cache
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);
/* =================================================================== */
