/* ------------------------------------------------------------------
	Version:		hdp-global-1.0.0.js
	Author:			AKQA
	Description:	Global Heineken JavaScript functions
	Contents:		???
------------------------------------------------------------------- */
/*
the most efficient jQuery selector is '#id', followed by 'tag.class'
parent selectors $('parent#id child.class') add a lot of overhead
*/
var hdp = function() {
	var _this = {
		init : function() {
			hdp.Format.initTextClasses();
			hdp.sharing.init();
			hdp.signUp.init();
			hdp.validate.init();
			hdp.Navigation.init();
			hdp.countryList.init();
			hdp.externalLinks.init();
			hdp.signUp.showSignUpPanelIfAppropriate();
		},
		tracking : {
			trackPageview : function(trackingParam) {
				if (pageTracker) { pageTracker._trackPageview(trackingParam); }
			},
			trackEvent : function(category, action, label, value) {
				if (pageTracker) { pageTracker._trackEvent(category, action, label, value); }
			},
			linkByPost : function(url) {
				if (pageTracker) { pageTracker._linkByPost(url); }
			},
			link : function(url) {
				if (pageTracker) { pageTracker._link(url); }
			}
		},
		sharing : {
			fullyLoaded: false,
			tabSwitchingFunction: null,
			easing: 'easeOutQuart',
			scrollSpeed: 7500,
			absoluteTop: 0,
			init : function(hdpShare) {
				//default sharing setup
				var a2aUrl = hdp.config.baseWebResourcesUrl + '/WebResource/v1/Share.ashx';
				var linkName = document.title; //Can also be specific string
				var linkUrl = location.href; //Can also be specific URL string
				var linkClick = 1; //Switches menu to appear onclick instead of mouseover
				var showTitle = 0; //Shows the title of the item (from a2a_linkname) within the sharing menu
				var numServices = 5000; //Number of share options to display
				var prioritize = ['faves', 'facebook', 'myspace', 'twitter', 'bebo', 'digg', 'netlog', 'delicious', 'wordpress', 'technorati_favorites', 'yahoo_bookmarks', 'blogger_post']; //Options to prioritise
				var customServices = []; //Customise menu UI ['Example dot com', 'http://www.example.com/add?name=A2A_LINKNAME_ENC&url=A2A_LINKURL_ENC', 'http://www.example.com/images/icon_16x16.png']'
				var colorMain = '004f22';
				var colorBorder = '000000';
				var colorLinkText = 'ffffff';
				var colorLinkTextHover = 'ffffff';

				hdpShare = (hdpShare && typeof hdpShare == 'object') ? hdpShare : {};
				a2a_linkname = (hdpShare.linkName) ? hdpShare.linkName : linkName;
				a2a_linkurl = (hdpShare.linkUrl) ? hdpShare.linkUrl : linkUrl;
				a2a_track_links='a2a'; //Activate tracking
				a2a_onclick = (hdpShare.linkClick) ? hdpShare.linkClick : linkClick;
				a2a_show_title = (hdpShare.showTitle) ? hdpShare.showTitle : showTitle;
				a2a_num_services = (hdpShare.numServices) ? hdpShare.numServices : numServices;
				a2a_prioritize = (hdpShare.prioritize) ? hdpShare.prioritize : prioritize;
				a2a_custom_services = (hdpShare.customServices) ? hdpShare.customServices : customServices;
				a2a_color_main = (hdpShare.colorMain) ? hdpShare.colorMain : colorMain;
				a2a_color_border = (hdpShare.colorBorder) ? hdpShare.colorBorder : colorBorder;
				a2a_color_link_text = (hdpShare.colorLinkText) ? hdpShare.colorLinkText : colorLinkText;
				a2a_color_link_text_hover = (hdpShare.colorLinkTextHover) ? hdpShare.colorLinkTextHover : colorLinkTextHover;
				a2a_color_bg = '000000';
				a2a_hide_embeds = (hdpShare.hideEmbeds) ? hdpShare.hideEmbeds : (!navigator.userAgent.match('MSIE')) ? 1 : 0;

				a2a_localize = (hdpShare.localize) ? hdpShare.localize : {};
				if ($('#a2aPage').length === 0) { //if Script reference doesn't already exist then create
					$('body').append('<script type="text/javascript" id="a2aPage" src="' + a2aUrl + '"></script>');
				}
				hdp.sharing.pollForShareCompletion();
			},
			pollForShareCompletion : function() {
				/*
					Waits for all the external A2A code to load, and then additionally, their HTML to be
					appended to the page. Once done, set the hdp.sharing.fullyLoaded boolean to true
					and call hdp.sharing.shareFullyLoaded().

					We do this because we need to modify their content once delivered to the page.
					
					NOTE: Only do this once, in case init is called a second time with different params.
				*/
				if (!hdp.sharing.fullyLoaded) {
					if ($('#a2apage_cols_container').length) {
						hdp.sharing.fullyLoaded = true;
						hdp.sharing.shareFullyLoaded();
					} else {
						setTimeout(function() { hdp.sharing.pollForShareCompletion(); }, 500);
					}
				}
			},
			shareFullyLoaded : function() {
				if (hdp.sharing.fullyLoaded !== true) { return; }

				// Cufon
				if (typeof(Cufon) != 'undefined') { Cufon.replace('#a2apage_dropdown a', { fontFamily: 'Futura Condensed Medium' }); }

				// So we can stop the left / right position of the box changing depending on the user's
				// screen resolution, wrap their outer-most DIV in one of our own that's the right width.
				$('#a2apage_dropdown').parent().wrap('<div id="a2apage_container_outer"></div>');
				
				// Because the content can vary in height (e.g. Disclaimer page), move the whole
				// shebang into the footer element so we're always displaying with the share button
				$('#hdp-footer').prepend($('#a2apage_container_outer'));

				// While we could add onclick events to the tabs to detect switching, their code
				// calls the tab switching function internally as well, which we need to trap
				hdp.sharing.tabSwitchingFunction = a2a.tabs;
				a2a.tabs = hdp.sharing.tabSwitched;

				// Enable smooth scrolling by default (because 'share' panel is the default panel)
				hdp.sharing.enableSmoothScroll();

				// Wrap their table in a DIV that we can control the height of the scrollable section
				$('#a2apage_cols_container').wrap('<div id="a2apage_cols_container_outer"></div>');

				// Add smooth scrolling up and down arrows before and after that DIV
				$('#a2apage_cols_container_outer').before('<a id="a2apage_smooth_scroll_up" class="a2apage_smooth_scroll_button" href="javascript:void(0);"><img src="/assets/global/images/clear.gif" class="a2a_i_uarr" alt="Scroll up"/></a>').after('<a id="a2apage_smooth_scroll_down" class="a2apage_smooth_scroll_button" href="javascript:void(0);"><img src="/assets/global/images/clear.gif" class="a2a_i_darr" alt="Scroll down"/></a>');
				$('div.a2a_tabs:last-child').after('<div class="a2a_close">&nbsp;</div>');
				$('div.a2a_close').bind('click',function(e) { a2a.toggle_dropdown('none',a2a.type); });

				$('#a2apage_smooth_scroll_up').bind('mousedown', function(e) {
					e.preventDefault(); hdp.sharing.scrollUp(e);
				}).bind('mouseup', function(e) {
					e.preventDefault(); hdp.sharing.stopScroll(e);
				}).bind('click', function(e) {
					e.preventDefault();
				});

				$('#a2apage_smooth_scroll_down').bind('mousedown', function(e) {
					e.preventDefault(); hdp.sharing.scrollDown(e);
				}).bind('mouseup', function(e) {
					e.preventDefault(); hdp.sharing.stopScroll(e);
				}).bind('click', function(e) {
					e.preventDefault();
				});

				$('#a2apage_find').bind('keydown', hdp.sharing.resultsFiltered);
			},
			resultsFiltered : function() {
				// When filtering the list, jump it back to the top
				$('#a2apage_cols_container').css('top', '0px');
			},
			tabSwitched : function(tabName, showNote) {
				$('#a2apage_cols_container').css('top', '0px');		// Not done in CSS as we only want to do it on tab switch
				if (tabName == 'DEFAULT') {
					hdp.sharing.enableSmoothScroll();
				} else {
					hdp.sharing.disableSmoothScroll();
				}
				return hdp.sharing.tabSwitchingFunction(tabName, showNote);
			},
			enableSmoothScroll : function() {
				$('#a2apage_dropdown').addClass('show_smooth_scroll_buttons');
			},
			disableSmoothScroll : function() {
				$('#a2apage_dropdown').removeClass('show_smooth_scroll_buttons');
			},
			scrollUp : function(e) {
				$('#a2apage_cols_container').animate({ top:0 }, hdp.sharing.scrollSpeed, hdp.sharing.easing);
			},
			scrollDown : function(e) {
			    a2aContainer = $('#a2apage_cols_container');
				if(!hdp.sharing.absoluteTop) {
					// We can only determine the height of their table once it has been shown
					hdp.sharing.absoluteTop = a2aContainer.parent().height() - a2aContainer.height();
				}

				a2aContainer.animate({ top:hdp.sharing.absoluteTop + 'px' }, hdp.sharing.scrollSpeed, hdp.sharing.easing);
			},
			stopScroll : function(e) {
				$('#a2apage_cols_container').stop();
			}
		},
		signUp : {
			init : function() {
				$('a.ucl-open-close-link').live('click', function(e) {
					e.preventDefault();
					hdp.signUp.openClose();
				});
				$('a.ucl-submit-a').show().bind('click', function(e) {
                    			hdp.tracking.trackPageview('/global/ucl/email/sign_up.link');
					$('form').validate().form();
					if ($('form').valid()) {
						// Get the ID needed to pass to the __doPostBack method from the ID of the anchor
						// We need to replace all underscore chars with dollar signs to convert this sort of syntax:
						//	ctl00_ctl00_ContentPlaceHolder1_AdditionalContent_Signup_LinkButton2
						// to this:
						//	ctl00$ctl00$ContentPlaceHolder1$AdditionalContent$Signup$LinkButton2
						var anchorId = $(e.target).closest('a')[0].id;
						var postBackId = anchorId.replace(/_/g, '$');
						__doPostBack(postBackId, '');
					}
					e.preventDefault();
				});
				$('input.ucl-submit-button').hide();
			},
			hideAddressAndButtonInputsIfSuccessful : function() {
				var successElement = $('div.ucl-signup-div #StatusMessageContainer .True');
				if (successElement.length) {
					// Hide all elements inside the parent container of #StatusMessageContainer
					// except the status message itself
					var updatePanel = $('div.ucl-signup-div #StatusMessageContainer').parent();
					$(':not(#StatusMessageContainer, #StatusMessageContainer *)', updatePanel).hide();
				}
			},
			// Show UCL 'sign up' panel if appropriate
			showSignUpPanelIfAppropriate : function() {
				// If scrollerObject is not passed in, and additionally, the global variable 'hdp.Navigation.mainScroller'
				// doesn't exist, then assume we're on a page without any scroller, e.g. a third-level UCL
				// page such as /star-experience/back-stadium-pass.aspx. If the 'hdp.Navigation.mainScroller' variable does exist,
				// then use it to perform the detection as if it were passed in.
				var showPanel = false;
				if ($('div.hdp-active-slide').length === 0) {
					showPanel = $('div.show-ucl-signup-panel').length > 0;
				} else {
					showPanel = $('div.hdp-active-slide div.show-ucl-signup-panel').length > 0;
				}
				if (showPanel) { $('div.ucl-signup-div').fadeIn(400); }
			},
			close : function() {
				$('div.ucl-signup-div').removeClass('ucl-signup-div-open');
			},
			openClose : function() {
				$('div.ucl-signup-div').toggleClass('ucl-signup-div-open');
			}
		},
		validate : {
			init : function() {
				if (!$('form').length) { return; }							// Do nothing if there are no forms
				if (typeof($('form').validate) === 'undefined') { return; }	// Do nothing if the jQuery validation plugin is not loaded

				$('form').validate({
					onfocusout: false,
					onkeyup: false,
					onclick: false,
					showErrors: function(errorMap, errorList) {
						this.defaultShowErrors();
						hdp.Format.cufonRefresh();
					}
				}); //sets the validation for form in current page
				if ($('input.email').length > 0) {
					$.validator.addMethod('chkSubscribeEmail', function(email) { //add custom validation method for subscriptions
						var emailRegex = new RegExp(/^[a-z0-9]([\-!#\$%&'\*\+\.\/0-9=\?a-z\^_`\{\|\}~])+@((\w([\-!#\$%'\*\+\/0-9=\?a-z\^_`\{\|\}~]*\.)+[a-z]{2,6})|(\[([0-9]{1,3}\.){3}[0-9]{1,3}\]))$/i); // supplied by web power
						return emailRegex.test(email);
					}, 'Please enter a valid email address.');
					
					$('input.email').each(function(i) {
						$(this).rules('add', {
							required: true,
							chkSubscribeEmail: true
						});
					});
				}
			}
		}
	};
	return _this;
}();

hdp.Format = {
	cufonRefresh : function() {
	    // in UCL this is only called when the slides are loaded
	    // all other calls are now cufon.replace
		if (typeof(Cufon) != 'undefined') {
        // only refresh the specific content of slides
        for(var i = 0; i < Cufon.slideContentSelectors.length; i++) {
	        Cufon.refresh(Cufon.slideContentSelectors[i]);
        }
			hdp.Format.initTextClasses();
		}
	},
	initTextClasses : function() {
	    // clear out any elements that mess with vertical alignment
		$('span.ucl-tout-icon ~ span.cufon,span.hdp-tout-icon ~ span.cufon,li.ucl-tout span.cufon:empty').remove();

		$('span.vertical-align-middle').each(function(i) {
		    	el = $(this);
			elP = el.parent();
			effectiveHeight = parseInt(elP.height(), 10) + parseInt(elP.css('padding-top'), 10);
			elP.css({'height':effectiveHeight + 'px', 'padding-top':0, 'position':'relative'});
			c = elP.height() / 2;
			d = el.height() / 2;
			t = c - d;
			el.css({'padding-top':0, 'margin-top':0, 'position':'absolute', 'top':t, 'visibility':'visible'}).removeClass('vertical-align-middle');
		});
	}
};

hdp.Navigation = function() {
	disableFlyBy = false;
	homepage = 'Default.aspx';
	flyByDelay = 0;
	navSpeed = 1000;
	flyBySpeed = 3000;
	flyByEasing = 'easeInOutSine';
	navEasing = 'easeOutQuart';
	currentUrlIndex = 0;
	urls = [];
	function loadSlides() {
	    // loop through all relevant links in the navigation
		var slideViews = $('#hdp-primary-menu li.active').parent().children('li').children('a');
        currentUrlIndex = $('li.active').parent().children('li').index($('li.active'));
        var currentSlide = $('div.hdp-slide:first');
        var parent = currentSlide.parent();
		$(slideViews).each(function (i, n) {
            var url = n.href;
			urls.push(url);
            var id = 'ucl-' + (url.match(/[\w-]+(?=\.\w{3,4}$)/) || 'slide-'+i);
            var html = '<div id="' + id + '" class="hdp-slide"></div>';
			if(i !== currentUrlIndex) {
			    if(i < currentUrlIndex) {
                    $(currentSlide).before(html);
			}
                else if(i > currentUrlIndex) {
                    parent.append(html);
                }
                $('#'+id).css('visibility', 'hidden').load(url + '?ajax=true .hdp-slide', function(html) {
					// A function named "pageLoadCallBack" can be defined in page code, and will be called if it exists
					if (typeof(pageLoadCallBack) != 'undefined') { pageLoadCallBack(); }
					noteLoaded();
		}); 
            }
		});
			totalPagesLoaded = 0;
			noteLoaded = function() {
				totalPagesLoaded++;
			if (totalPagesLoaded === (urls.length - 1)) {
					hdp.Format.cufonRefresh();
					$('div.hdp-slide').css('visibility', 'visible');
					if (hdp.Carousels) {
						if (!hdp.Carousels.active) { hdp.Carousels.init(); }
					}
					hdp.Navigation.fireFlyBy();
				}
			};
	}
	
	function initScroller() {
		// little loop to find the correct 'navSelectors' for scrollers and make sure they all 
		// have unique ids and then select the one that is active/visible as the one to control the scroller
		ii=0;
		$('ul.hdp-secondary-menu').each(function() {
			var naviID = 'secondary-menu-' + ii;
			$(this).attr('id', naviID);
			ii++;
			// change for standalone UCL site - this secondary menu might be a child of the active page
			if ($(this).parent().hasClass('.active')) {
				naviSelector = 'ul#' + $(this).parent().closest('ul').attr('id');
			} else if (!$(this).parent().hasClass('hdp-hide') && !$(this).hasClass('hdp-hide')) {
				naviSelector = 'ul#' + naviID;
			}
		});

		if (typeof(naviSelector) == 'undefined') {
			naviSelector = 'ul#hdp-primary-menu';
		}

		// changed for standalone mode, which loads the 2nd level menu by default
		// hence this test was disabling child items that should have been active
		// this feels very long winded, so if you can streamline it go for it
// originally: $('#hdp-primary-menu li.active').parent().find('a').click(function(e) {
		$('#hdp-primary-menu li.active').siblings('li').find('a').add('#hdp-primary-menu li.active > a').click(function(e) {
			e.preventDefault();
		});

		// Because fly-by pages are not really loaded the onload tracking code never fires, so add onclick tracking
		$(naviSelector).bind('click', function(e) {
			var theAnchor = $(e.target).closest('a');
			var theUrl = '';
			if (theAnchor.length) { theUrl = theAnchor[0].pathname; }
			if (theUrl != '') {
				if (theUrl.charAt(0) != '/') { theUrl = '/' + theUrl; } // Some browsers have a leading /, some don't.
				//hdp.tracking.trackPageview(theUrl);
			}
		});

		hdp.Navigation.mainScroller = $('div.hdp-slides').scrollable({ 
			size: 1,
			navi: naviSelector,
			items: '.hdp-items',
			speed: navSpeed,
			keyboard: false,
			easing: navEasing,
			onBeforeSeek: function() {
				if (hdp.Carousels) {
					hdp.Carousels.closePlayer();
				}
				hdp.signUp.close();
				$('div.ucl-signup-div').fadeOut(400);
			},
			onComplete: function() {
				// this is called twice as part of load for some reason
				// also, there is a bug in the scroller (or our implementation of it)
				// so getIndex and getVisibleItems functions always return
				// the first slide when it is called from load

		                // this function is a work-around of the scroller bug
		                // to return the actual current slide, even if this call is made onload
		                $('div.hdp-active-slide').removeClass('hdp-active-slide');
		                var visibleSlide;
		                var itemsPositionLeft = -1 * parseInt($('div.hdp-items').css('left'));
		                $('div.hdp-slide').each(function(i) {
		                    if(parseInt($(this).position().left) === itemsPositionLeft) { visibleSlide = $(this); return false; }
		                });
		                if(visibleSlide) visibleSlide.addClass('hdp-active-slide');

		                // this is so we don't call the signup and countrylist show/hide twice
		                // we test for IE load event - ignore this call if found
		                // this doesn't fix the problem for non-IE, but IE has the worst performance issues
		                if(window.event && window.event.type == 'readystatechange') {  }
		                else {
				    hdp.signUp.showSignUpPanelIfAppropriate();
				    if (hdp.flashManager) { hdp.flashManager.navigate(); }
		                }
			},
			api:true
		});

		// Create 'onComplete' method as 'onSeek' doesnt do what is says on the tin.
		if (typeof(hdp.Navigation.mainScroller) != 'undefined') {
			protoSeekTo = hdp.Navigation.mainScroller.seekTo;
			hdp.Navigation.mainScroller.seekTo = function(i, time, fn) {
					fn = this.getConf().onComplete;
					protoSeekTo(i, time, fn);
			};
		}

		function logSessionToNotFly() {
			$.cookie('noFly', 'true'); 
		}
		
		function testForHome() {
			test1 = document.location.href.indexOf(homepage) > -1;
			test2 = document.location.href.split('/').length < 5;
			return test1 || test2;
		}
		
		hdp.Navigation.fireFlyBy = function() {
			if (typeof(hdp.Navigation.readyToFly) != 'undefined') {
				timer = setTimeout(function() {
					hdp.Navigation.mainScroller.getConf().speed = flyBySpeed;
					hdp.Navigation.mainScroller.getConf().easing = flyByEasing;
					hdp.Navigation.mainScroller.onSeek(function() {
						hdp.Navigation.mainScroller.getConf().speed = navSpeed;
						hdp.Navigation.mainScroller.getConf().easing = navEasing;
					});
					hdp.Navigation.mainScroller.end();
				}, flyByDelay);
			}
		};
		/* virgil/temp quote out
		if (!$.cookie('noFly') && !disableFlyBy && testForHome()) {
			hdp.Navigation.readyToFly = true;
		} else {
			hdp.Navigation.mainScroller.getConf().speed = 0;
			$('#hdp-primary-menu li.active:last').trigger('click');
			hdp.Navigation.mainScroller.getConf().speed = navSpeed;
		}
		
		logSessionToNotFly();
		*/
	}

	return {
		init: function () {
			if ($('#hdp-viewport').length > 0) {
				loadSlides();
				initScroller();
			} else {
				// If we're on a page with fly-by panels, this is done AFTER all panels are loaded
				if (hdp.Carousels) {
					if (!hdp.Carousels.active) {
						hdp.Carousels.init();
					}
				}
			}
		}
	};
}();

hdp.countryList = function() {
	var _this = {
		easing:'easeOutQuart',
		scrollSpeed : 1300,
		closeTimer : null,
		closeDelay : 2000,
		absoluteTop : 0, // topmost point of scroll
		init: function() {
		    // in IE it's quicker to build an array and join() it than to build a string
			var arrHTML = ['<ul class="hdp-country-list"><li><span class="ucl-no-link">' + $('label.country-list-label').text() + '</span></li>'];
			$('.hdp-country-list option').each(function(i) {
			    if(this.value) {
				    arrHTML[arrHTML.length] = '<li';
				    if(this.selected) { arrHTML[arrHTML.length] = ' class="hdp-selected"'; }
				    arrHTML[arrHTML.length] = '><a href=\"' + this.value + '\">' + this.text + '</a></li>';
			    }
			});
			arrHTML[arrHTML.length] = '</ul>';
			$('div.hdp-country-list-inner').html(arrHTML.join(''));

			// replace cufon for country list
			Cufon.replace('ul.hdp-country-list li', {
				fontFamily: 'Futura Condensed Medium',
				hover: true,
				hoverables: { li: true, span: true },
				separate: 'none'
			});

			if ($('div.hdp-country-list-div').length === 0) { return; }
			// hide the country list for the flash game in non-IE browsers
			hdp.countryList.showHide();
			// close sets the default parameters and positions
			hdp.countryList.close();
			// set the behaviours
			cDiv = $('div.hdp-country-list-div');
			cList = cDiv.find('ul.hdp-country-list');
			cListItems = cList.find('li');
			cDiv.bind('mouseover', function(e) {
					e.preventDefault();clearTimeout(hdp.countryList.closeTimer);
				}).bind('mouseout', function(e) {
					e.preventDefault();hdp.countryList.closeTimer = setTimeout(function() { hdp.countryList.close(); },hdp.countryList.closeDelay);
				});
			cListItems.bind('click', function(e) {
					e.preventDefault();hdp.countryList.openClose(e);
				});
			hdp.countryList.absoluteTop = cList.parent().height() - cList.height();
			cDiv.find('div.hdp-scroll-up').bind('mousedown', function(e) {
					e.preventDefault();hdp.countryList.scrollUp(e);
				}).bind('mouseup', function(e) {
					e.preventDefault();hdp.countryList.stopScroll(e);
				});
			cDiv.find('div.hdp-scroll-down').bind('mousedown', function(e) {
					e.preventDefault();hdp.countryList.scrollDown(e);
				}).bind('mouseup', function(e) {
					e.preventDefault();hdp.countryList.stopScroll(e);
				});
		},
		showHide : function() { // hide the country list for the game page for non-IE browsers
			var hideCountryList = false;
			if(!navigator.userAgent.match('MSIE')) {
			    if (typeof(hdp.Navigation.mainScroller) != 'undefined') {
				    var currentSlide = hdp.Navigation.mainScroller.getVisibleItems()[0];
				    var currentSlideId = '#' + currentSlide.id;
				    hideCountryList = ($(currentSlideId + ' #ucl-star-match-no-flash').length == 1);
			    }
		    	}
			if(hideCountryList) { $('div.hdp-country-list-div').hide(); }
           		 else { $('div.hdp-country-list-div').show(); }
		},
		close : function(e) {
			$('div.hdp-country-list-div').removeClass('hdp-list-open');
			// if one is selected move it into position - otherwise show 'Choose country'
			if ($('ul.hdp-country-list li.hdp-selected').length > 0) {
				$('ul.hdp-country-list').css( {top: '-' + $('ul.hdp-country-list li.hdp-selected').position().top + 'px' } );
			} else if($('ul.hdp-country-list li').length > 0) {
				$('ul.hdp-country-list').css( {top: '-' + $('ul.hdp-country-list li:first').position().top + 'px' } );
			}
		},
		openClose : function(e) {
		    	cDiv = $('div.hdp-country-list-div');
			if (cDiv.hasClass('hdp-list-open')) {
				if ($(e.target).closest('a').length == 1) {
					window.open($(e.target).closest('a').attr('href'));
				} else if ($(e.target).find('a').length == 1) {
					window.open($(e.target).find('a').attr('href'));
				}
			} else {
		        cList = cDiv.find('ul.hdp-country-list');
				var newOffset = parseInt(cList.parent().height(), 10) / 2;
				// this displays the selected option in the centre of the panel
				if (cList.find('li.hdp-selected').length > 0) {
				    cSel = cList.find('li.hdp-selected');
					newOffset -= cSel.position().top;
					newOffset -= 0 - parseInt(cSel.height(), 10) / 2;
				// just check that setting the selected option to the centre
				// doesn't leave a load of black space at the top
				if(newOffset > 0) newOffset = 0 - parseInt(cList.find('li:first').height(), 10);
				} else { // nothing selected, move the first country to the top
					newOffset = 0 - parseInt(cList.find('li:first').height(), 10);
				}
				// if blank space at bottom, add a bit
				// if (newOffset < hdp.countryList.absoluteTop) { newOffset = hdp.countryList.absoluteTop; }
				newOffset = Math.max(newOffset, hdp.countryList.absoluteTop);
				cList.css( { top : newOffset + 'px' } );

				cDiv.toggleClass('hdp-list-open');
			}
		},
		scrollUp : function(e) {
			$('ul.hdp-country-list').animate( { top: 0 }, hdp.countryList.scrollSpeed , hdp.countryList.easing);
		},
		scrollDown : function(e) {
			$('ul.hdp-country-list').animate( { top: hdp.countryList.absoluteTop + 'px' }, hdp.countryList.scrollSpeed, hdp.countryList.easing );
		},
		stopScroll : function(e) {
			var msie = navigator.userAgent.match('MSIE');
			if (msie) {
				setTimeout(function() { $('ul.hdp-country-list').stop();}, 20);	// See HUCL-343
			} else {
				$('ul.hdp-country-list').stop();
			}
		}
	};
	return _this;
}();

hdp.externalLinks = {
	init:function() {
		$('a.hdp-external-link').bind('click', function(e) {
			window.open($(this).attr('href'));
			e.preventDefault();
		});
	}
};

jQuery.extend(jQuery.easing, {
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) { return c/2*t*t + b; }
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) { return c/2*t*t*t + b; }
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; }
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) { return c/2*t*t*t*t*t + b; }
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t===0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t===0) { return b; }
		if (t==d) { return b+c; }
		if ((t/=d/2) < 1) { return c/2 * Math.pow(2, 10 * (t - 1)) + b; }
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) { return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; }
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t===0) { return b; }
		if ((t/=d)==1) { return b+c; }
		if (!p) { p=d*0.3; }
		if (a < Math.abs(c)) { a=c; s=p/4; }
		else { s = p/(2*Math.PI) * Math.asin (c/a); }
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t===0) { return b; }
		if ((t/=d)==1) { return b+c; }
		if (!p) { p=d*0.3; }
		if (a < Math.abs(c)) { a=c; s=p/4; }
		else { s = p/(2*Math.PI) * Math.asin (c/a); }
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t===0) { return b; }
		if ((t/=d/2)==2) { return b+c; }
		if (!p) { p=d*(0.3*1.5); }
		if (a < Math.abs(c)) { a=c; s=p/4; }
		else { s = p/(2*Math.PI) * Math.asin (c/a); }
		if (t < 1) { return -0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s === undefined) { s = 1.70158; }
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s === undefined) { s = 1.70158; }
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s === undefined) { s = 1.70158; }
		if ((t/=d/2) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; }
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) { return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * 0.5 + b; }
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
	}
});

// called when UpdatePanel updates
function pageLoad() {
	hdp.signUp.hideAddressAndButtonInputsIfSuccessful();
	Cufon.replace('div.ucl-signup-div p',Cufon.defaultTextCufon);
}
// runs when the page has completed loading
$(document).ready(function() {
	hdp.init();
});
