window.addEvent('load', function() {
	try {
		$A(document.getElementsByTagName('a')).filter(
			function(item) { 
				return item.href.toLowerCase().indexOf('.pdf') > 0 || item.href.toLowerCase().indexOf("global-liquidity.gs.com") > 0 ||  
					(
						!( 
							item.href.toLowerCase().indexOf('.gs.com') > 0 || item.href.toLowerCase().indexOf('.goldmansachs.com') > 0 
						) 
						&& item.href.toLowerCase().indexOf("javascript:") != 0
					); 
				}
			).each(function(pdf){
				pdf.target="_blank";
			}
		);
	} catch (e) {}
});

GoldmanSachs.PageOverlay.prototype._gsamInit = GoldmanSachs.PageOverlay.prototype.initialize;

GoldmanSachs.PageOverlay.prototype.initialize = function(url) {
	GoldmanSachs.PageOverlay.prototype._gsamInit.apply(this, arguments);
	if ($defined(url)) GoldmanSachs.PageOverlay.onDeck = this;
}

GoldmanSachs.AudienceVerification = new Class({
	options : { },
	initialize : function(options) {
		this.setOptions(options||{});

		if (!options.url || !options.expectedCookieValue)
			return;

		var cookieValue = Cookie.get('audience');

		if (options.expectedCookieValue != cookieValue) {
			this.overlay = new GoldmanSachs.PageOverlay(options.url);
			this.overlay.closeButton.removeEvents(); 
			this.overlay.overlayBG.removeEvents();
			
			this.overlay.closeButton.addEvent('click', function(){
				window.location = 'http://www2.goldmansachs.com/gsam/audience_selector/index.html';
			});
		}
	}
});
GoldmanSachs.AudienceVerification.implement(new Options);

GoldmanSachs.AudienceVerificationForm = new Class({
    options : { },
	initialize : function(button, checkbox, checkboxLabel, cookieValue, options) {
        this.setOptions(options||{});

		checkbox.addEvent('click', function(){
			if (checkbox.checked) button.disabled = false;  
			else button.disabled = true; 
		});
		checkboxLabel.addEvent('click', function(){
			if (checkbox.checked) {
				checkbox.checked = false;
				button.disabled = true;
			} else {
				checkbox.checked = true;
				button.disabled = false;
			}
		});
        
		
		if (this.options.closeRedirect && this.options.closeRedirect !== null) {
        	var closeRedirect = this.options.closeRedirect;
        	GoldmanSachs.PageOverlay.onDeck.closeButton.removeEvents();
        	GoldmanSachs.PageOverlay.onDeck.closeButton.addEvent('click', function(){
            	window.location = closeRedirect;
            });
        }

        var redirect = this.options.redirect;
        button.addEvent('click', function(){
            if (button.disabled) return;
            
            Cookie.set('audience', cookieValue, {path:'/'});
            
            if (redirect) 
            	window.location = redirect;
            else if (GoldmanSachs.PageOverlay.onDeck) {
            	GoldmanSachs.PageOverlay.onDeck.destroy();
            }
        });
	}
});
GoldmanSachs.AudienceVerificationForm.implement(new Options);

GoldmanSachs.AudienceSelector = new Class({
	options : { },
	initialize : function(options) {
		this.setOptions(options||{});
		
		var _self = this;
		
		if (!this.checkUserType()) {
			new Ajax(options.url, {
				method : 'get', 
				evalScripts : true, 
				update : this.options.update,
				onComplete : function() {
					var mo = new GoldmanSachs.ModalOverlay($(_self.options.overlayTrigger), $(_self.options.overlayTarget));
					
					mo.addEvent('doShow', _self.doShow.bind(_self));
					mo.addEvent('doHide', _self.doHide.bind(_self));
					
					mo.doShow(null);
				}
			}).request();
		}
	},
	getCookie : function () { return Cookie.get('audience'); },
	setCookie : function (id) { Cookie.set('audience', id, {path:'/', duration : this.getDuration()}); },
	getDuration : function() {
		var input = $(this.options.durationInput);
		if (input) {
			return input.checked ? 100 : false;
		} else {
			return false;
		}
	},
	checkUserType : function () {
		var cookie = this.getCookie();
		var selectedUrl = window.location.href;
        var userType = getUrlParameter("userType");
        if (selectedUrl.indexOf('/gsam/advisors') > 0 && userType == "advUS") {
        	this.setCookie(userType);
        	return true;
        } else if (selectedUrl.indexOf('/gsam/individuals') > 0 && userType == "indUS") {
        	this.setCookie(userType);
        	return true;
        } else {
        	return false;
        }
	},
	doShow : function() { 
		var cookie = this.getCookie();
		
		if (!cookie || (!this.isApp() && this.requiresRedirect(cookie))) {
			return;
		} else {
			throw "no redirect needed";						
		}	
	},
	doHide : function(event) { 
		if (event && event.target) { 
			var id = event.target.id;
			if (id) { 
				if (id.indexOf('http')>=0) {
					this.setCookie("none");
					this.redirect(id);
					throw "redirecting";	
				} else {
					var cookie = this.setCookie(id);
					if (this.isApp() || this.requiresRedirect(id)) {
						this.redirect(id);
						throw "redirecting";
					}
				}
			} 
		} 
	},
	requiresRedirect : function(id) {
		var url = window.location.href;
		
		if (id == "advUS") {
			return url.indexOf('/gsam/advisors') < 0; 
		} else if (id == "indUS") {
			return url.indexOf('/gsam/individuals') < 0;
		} else {
			return true;
		}
	},
	isApp : function() {
		return window.location.href.indexOf("/gsam/app") > 0;
	},
	redirect : function(id) {
		var url = window.location.href;
		
		if (id == "advUS") {
			window.location = url.replace('gsam/individuals', 'gsam/advisors');
		} else if (id == "indUS") {
			window.location = url.replace('gsam/advisors', 'gsam/individuals');
		} else {
			window.location = id;
		}
	}
});
GoldmanSachs.AudienceSelector.implement(new Options);

function calcHeight(frameName)
{
  //find the height of the internal page
  var the_height=document.getElementById(frameName).contentWindow.document.body.scrollHeight;
  //change the height of the iframe
  document.getElementById(frameName).height=the_height;
}

function setDefaultView(audience)
{
    var expiredays = "91";
    var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);
    document.cookie="audience=" +escape(audience)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + "; path=/";
	location.reload(true);
}

function setSiteView(audience)
{
	var exdate = new Date();
	exdate.setTime(exdate.getTime()+ 1000*60*30);
	document.cookie="audience=" +escape(audience)+";expires="+exdate.toGMTString() + "; path=/";
}

function switchSiteView(audience)
{
	if (audience == "advUS")
	{
		setSiteView("advUS");
		if (window.location.href.indexOf("pubweb.gsam") > 0)		
			window.location = "/pubweb.gsam.advisors/pages/gsam/advisors/";
		else
			window.location = "/gsam/advisors/";
	} 
	else
	{
		if (audience == "indUS")
		{
			setSiteView("indUS");
			if (window.location.href.indexOf("pubweb.gsam") > 0)		
				window.location = "/pubweb.gsam.individuals/pages/gsam/individuals/";
			else
				window.location = "/gsam/individuals/";
		}
		else
		{
			
			window.location = "/gsam/audience_selector/index.html?aud="	
		}
	}
}

function switchLanguage(lang) {
    var url = window.location.href;
    var newUrl = url;
    if(newUrl.indexOf('language=')>=0) {
    	newUrl = newUrl.replace(/language=EN|language=IT|language=FR|language=DE|language=NL/g, 'language=' + lang.toUpperCase());
    }
    newUrl = newUrl.replace(/\/en\/|\/de\/|\/fr\/|\/it\/|\/fl\//g, '/' + lang + '/');
    if(newUrl.indexOf('language=FL')>=0){
    	newUrl = newUrl.replace(/language=FL/g, 'language=NL');
    }
    if (url != newUrl)
    	window.location = newUrl;
}

function getUrlParameter(name) {
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var tmpURL = window.location.href;  
	var results = regex.exec( tmpURL );  
	if( results == null )    
		return "";  
	else    
		return results[1];
}

function launchEconUpdate(eventURL)	{
	window.open(eventURL,"","width=850,height=500","resizable=1,scrollbars=0");
}

window.addEvent('load', function(){ 
	if (window.location.href.indexOf('/gsam/app') > 0) {
		var c = Cookie.get('audience'); 
		if (c=='advUS') {
			document.forms[0].action="/gsam/advisors/search/search.gscgi"
		} else if (c=='indUS') {
			document.forms[0].action="/gsam/individuals/search/search.gscgi"
		}
	} 
})

GoldmanSachs.PageOverlay.prototype.synonyms = {
	'advisors' : ['individuals'],
	'individuals' : ['advisors']	
}

GoldmanSachs.GSAMToolTip = new Class({
	options: {
		offsets: {'x': 16, 'y': 16},
		delay: 200 
	},
	initialize: function (trigger, target, options) {
		if (!trigger || !target) return; // fail fast

		this.setOptions(options);
		
		this.trigger = trigger;
		this.target = target;

		var coords = this.target.getCoordinates();
		this.width = coords.width;
		this.height = coords.height;

		this.trigger.addEvent('mouseover', this.doShow.bind(this));
		this.trigger.addEvent('mouseout', this.doHide.bind(this));
		
		this.target.addEvent('mouseover', this.stayOpen.bind(this));
		this.target.addEvent('mouseout', this.doHide.bind(this));
		
		this.fx = new Fx.Style(this.target, 'opacity', {duration: this.options.delay, wait: false}).set(0);
	},
	stayOpen: function() {
		this.fx.stop();
		this.fx.set(1);
		this.show();
	},
	doShow: function (e) {
		var event = new Event(e);
		this.fx.start(1);
		this.locate(event);
		this.show();
	},
	doHide: function() {
		this.fx.start(0);
		this.hide();
	},
	show: function() {
		// to be overridden
	},
	hide: function() {
		// to be overridden
	},
	locate: function(event) {
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var pos = this.trigger.getPosition();

		var l = pos.x - (this.options.offsets.x + this.width);
		var t = pos.y + this.options.offsets.y;

		this.target.setStyles({
			'left': l,
			'top': t
		});
		
		var tip = this.target.getCoordinates();		
		if (scroll.x > tip.left) {
			this.target.setStyle('left', (l + scroll.x - tip.left + this.options.offsets.x));
		}
	}
});
GoldmanSachs.GSAMToolTip.implement(new Options);
