/*-----------------------------------------------------
-------------------------------------------------------
----------                                  -----------
----------  AEGON UK styles copyright 2010  -----------
----------                                  -----------
-------------------------------------------------------
-------------------------------------------------------
--------------- @author Ross Mason ------------------*/

(function($){

//------------------ MDC OFFERS -----------------------
$(document).ready(function() {$(".scaleTo").each(function() {var $this = $(this);var boxWidth = $(this).css("width");var fontSize = parseInt($(this).css("fontSize"), 10);var $line;var lineWidth;$this.html(function(i,v) {return $("<span>").text(v).css("whiteSpace", "nowrap");});$line = $this.children("span").first();lineWidth = $line.css("width");while ( lineWidth < boxWidth ) {fontSize += 1;$line.css("fontSize", fontSize + "px");lineWidth = $line.css("width");}fontSize -= 1;$line.css("fontSize", fontSize + "px");});}); 

//------------------ UTILITIES ------------------------
var util={trim:function(str,chars){str=str.toString();chars=chars||"\\s";return this.ltrim(this.rtrim(str,chars),chars);},ltrim:function(str,chars){str=str.toString();chars=chars||"\\s";return str.replace(new RegExp("^["+chars+"]+","g"),"");},rtrim:function(str,chars){str=str.toString();chars=chars||"\\s";return str.replace(new RegExp("["+chars+"]+$","g"),"");}};

//------------------ COOKIES --------------------------
var cookie={set:function(name,value,days,domain){var expires="";if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));expires="; expires="+date.toGMTString();}if(domain){document.cookie=name+"="+value+expires+"; path=/; domain="+domain+";";}else{document.cookie=name+"="+value+expires+"; path=/";}},get:function(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)===' '){c=c.substring(1,c.length);}if(c.indexOf(nameEQ)===0){return c.substring(nameEQ.length,c.length);}}return null;},erase:function(name,domain){if(domain){this.set(name,"",-1,domain);}else{this.set(name,"",-1);}}};

//------------------ DOC LIB TABLE FILTER -------------
var docLibTableFilter={run:function(selector,query){query=$.trim(query);query=query.replace(/ /gi,'|');$(selector).each(function(){($(this).text().search(new RegExp(query,"i"))<0)?$(this).hide():$(this).show();}); },init:function(){$("#tableSearch").keyup(function(event){if(event.keyCode==27||$(this).val()===''){$(this).val('');$('#textfilter tbody tr').show();}else{docLibTableFilter.run('#textfilter tbody tr',$(this).val());}})}};

//------------------ ADDTHIS CONFIG -------------------
var addthis_config={"data_track_clickback":true,services_expanded:'email,twitter,facebook,favorites,gmail,hotmail,linkedin,netvibes,digg,wordpress,delicious,stumbleupon,aolmail,bitly,evernote,reddit,tumblr,blogger,'};


/*=====================================================
	CORE INITS
=====================================================*/
var CORE = {


	//-------------- TOOLBAR --------------------------
	countryDropdown: function(){
			$("#mixed-combo").specialselectCombo({
				emptyText:"AEGON global sites",
				autoFill:true
			});
			/*$("#country span").append("<div class=\"submenu\"><div><h3>Global sites</h3><ul><li><a target=\"_blank\" class=\"aegon_group\" href=\"http://www.aegon.com\">AEGON Group</a></li><li><a target=\"_blank\" class=\"aegon_asset_management\" href=\"http://www.aegonassetmanagement.com\">AEGON Asset Management</a></li><li><a target=\"_blank\" class=\"aegon_global_pensions\" href=\"http://www.aegonglobalpensions.com\">AEGON Global Pensions</a></li></ul></div><div><h3>Country sites</h3><ul><li><a target=\"_blank\" class=\"brazil\" href=\"http://www.mongeralaegon.com.br\">Brazil</a></li><li><a target=\"_blank\" class=\"canada\" href=\"http://www.aegoncanada.com\">Canada</a></li><li><a target=\"_blank\" class=\"china\" href=\"http://www.aegon-cnooc.com\">China</a></li><li><a target=\"_blank\" class=\"czech_republic\" href=\"http://www.aegon.cz\">Czech Republic</a></li><li><a target=\"_blank\" class=\"germany\" href=\"http://www.aegon.de\">Germany</a></li><li><a target=\"_blank\" class=\"hungary\" href=\"http://www.aegon.hu\">Hungary</a></li><li><a target=\"_blank\" class=\"india\" href=\"http://www.aegonreligare.com\">India</a></li><li><a target=\"_blank\" class=\"ireland\" href=\"http://www.aegon.ie\">Ireland</a></li><li><a target=\"_blank\" class=\"japan\" href=\"http://www.aegon.jp\">Japan</a></li><li><a target=\"_blank\" class=\"mexico\" href=\"http://www.argosaegon.com/index_seguro.htm\">Mexico</a></li><li><a target=\"_blank\" class=\"netherlands\" href=\"http://www.aegon.nl\">Netherlands</a></li><li><a target=\"_blank\" class=\"poland\" href=\"http://www.aegon.pl\">Poland</a></li><li><a target=\"_blank\" class=\"romania\" href=\"http://www.aegon.ro\">Romania</a></li><li><a target=\"_blank\" class=\"slovakia\" href=\"http://www.aegon.sk\">Slovakia</a></li><li><a target=\"_blank\" class=\"spain\" href=\"http://www.aegon.es\">Spain</a></li><li><a target=\"_blank\" class=\"turkey\" href=\"http://www.aegon.com.tr\">Turkey</a></li><li><a target=\"_blank\" class=\"uk\" href=\"http://www.aegon.co.uk\">UK</a></li><li><a target=\"_blank\" class=\"usa\" href=\"http://www.aegonins.com\">USA</a></li></ul></div></div>");
			$("#country span").mouseover(function(){clear_timeouts();
			$(".openMenu").removeClass("openMenu");$(this).addClass("openMenu");$(this).children().addClass("openMenu");$(".submenu").not(".openMenu").hide();$(".subsubmenu").hide();$(this).children(".submenu").show();return false;});$(".submenu li:last").addClass("last");
			$("#country span").mouseout(function(){menu_timeouts.push(window.setTimeout(hide_menus,400));return false;});*/
			/*$("#country .submenu div:gt(0) li:even").addClass("col1");$("#country div:gt(1) li:odd").addClass("col2");*/
		},

	searchBox: function(){
		if ($("#search_box, #search_box_body, #search_box_doc").val() === ""){
			$("#search_box, #search_box_body, #search_box_doc").val("Search");
		}
				$("#search_box, #search_box_body, #search_box_doc").focus(function(){
					if( this.value == "Search" ){
						this.value = "";
						$("#search_box, #search_box_body, #search_box_doc").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "Search";
						$("#search_box, #search_box_body, #search_box_doc").css("color", "#999");
					}
				});
		},

	selectDropdowns: function(){
			$("#toolbar #login").append("<ul class=\"submenu\"><li><a href=\"http://www.aegon.co.uk/AEGON-customers/Login/\">Customer login</a></li><li class=\"last\"><a href=\"https://www1.scoteq.co.uk/login/showLoginPgAction.do?method=showLoginPage&amp;loginStyle=IFA\">Adviser login</a></li></ul>");
			$("#toolbar #contributionOtherSites, #toolbar #login").mouseover(function(){clear_timeouts();
			$(".openMenu").removeClass("openMenu");$(this).addClass("openMenu");$(this).children().addClass("openMenu");$(".submenu").not(".openMenu").hide();$(".subsubmenu").hide();$(this).children(".submenu").show();return false;});$(".submenu li:last").addClass("last");
			$("#toolbar #contributionOtherSites, #toolbar #login").mouseout(function(){menu_timeouts.push(window.setTimeout(hide_menus,400));return false;});
		},


	//-------------- CONTENT ENHANCMENTS --------------
	dynamicDate: function(){
            var date = new Date();
            var year = date.getFullYear();
            $("#copyright span, .dynamicDate").html(year);
		},
	
	equalHeight: function(){
			function equalHeight(group){currentTallest=0;group.each(function(){$(this).height();thisHeight=$(this).height();if(thisHeight>currentTallest){currentTallest=thisHeight;};});currentTallest = currentTallest+"px";if (jQuery.browser.msie && jQuery.browser.version == 6.0) {group.css({'height': currentTallest}); }group.css({'min-height': currentTallest});};
			equalHeight($(".equalheight"));
			equalHeight($(".equalheight2"));
			equalHeight($(".equalheight3"));
			equalHeight($(".equalheight4"));
		},
	
	
	scrollToAnchor: function(){$('.searchable a[href*=#], .scrollTo, #discountSlider li a').click(function(){if(location.pathname.replace(/^\//,'')==this.pathname.replace(/^\//,'')&&location.hostname==this.hostname){var $target=$(this.hash);$target=$target.length&&$target||$('[name='+this.hash.slice(1)+']');if($target.length){var targetOffset = $target.offset().top;$('html,body').animate({scrollTop:targetOffset},500);return false;}}});},
	
	inPageTabs: function(){
			$("#tabs div").addClass("puff border_grey");
			$("#tabnav, #tabs").addClass("json");
			$("#tabs").children().not(":first").hide();
			$("#tabnav li:first").addClass("on");
			$("#tabnav li a").click(function(){
				$("#tabs").children().hide();
				$("#tabs").children().filter($(this).attr("href")).show();
				$(this).parent().siblings().removeClass("on");
				$(this).parent().addClass("on");
				return false;
			});
		},
		
	expandableBoxes: function(){
			$('.expandbox .expandInfo, .expandbox.selected .expandInfo .expandbox .expandInfo').hide();
			$('.expandbox.selected > .expandInfo').show();

			$('.expandbox .expandToggle').click(function(e) {
				$(this).siblings('.expandbox .expandInfo').slideToggle(400);
				return false;
			});

			$('.topbar .expandToggle').hover(function(){
				$(this).addClass('over');
			}, function() {
				$(this).removeClass('over');
			});

			$('.topbar .expandToggle').toggle(function(){
			if ($(this).parent().hasClass("selected")){
				$(this).parent().removeClass('selected');
			}else{
				$(this).parent().addClass('selected');
			}
			}, function() {
			if ($(this).parent().hasClass("selected")){
				$(this).parent().removeClass('selected');
			}else{
				$(this).parent().addClass('selected');
			}
			});
		},
	
	tables: function(){
			$("table.sortable").tablesorter({widgets: ['zebra']});
			$(".rowSelect tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
		    $(".zebra tr:even").addClass("odd");
			$(".zebraVert td:even").addClass("odd");
			$(".rowSelect tr").click(function() {
				var href = $(this).find("a").attr("href");
				if(href) {window.location = href;}
			});
		},

	checkboxRadio: function(){
			$('input:checkbox').checkbox({cls:'checkbox'});
			$('input:radio').checkbox();
		},
	
	datepicker: function(){
		if ($(".datepicker").val() === ""){
			$(".datepicker").val("dd/mm/yyyy");
		}
				$(".datepicker").focus(function(){
					if( this.value == "dd/mm/yyyy" ){
						this.value = "";
						$(".datepicker").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "dd/mm/yyyy";
						$(".datepicker").css("color", "#999");
					}
				});
		},
		
	rangepicker: function(){
		if ($(".rangepicker").val() === ""){
			$(".rangepicker").val("dd/mm/yyyy - dd/mm/yyyy");
		}
				$(".rangepicker").focus(function(){
					if( this.value == "dd/mm/yyyy - dd/mm/yyyy" ){
						this.value = "";
						$(".datepicker").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "dd/mm/yyyy - dd/mm/yyyy";
						$(".rangepicker").css("color", "#999");
					}
				});
		},
		
	emailto: function(){
		$("#emailto").val("Email address");
				$("#emailto").focus(function(){
					if( this.value == "Email address" ){
						this.value = "";
						$("#emailto").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "Email address";
						$("#emailto").css("color", "#999");
					}
				});
		},
		
	frn: function(){
		if ($("#frn").val() === ""){
			$("#frn").val("Enter FRN");
		}
			$("#frn").focus(function(){
				if( this.value == "Enter FRN" ){
					this.value = "";
					$("#frn").css("color", "#333");
				}
			}).blur( function(){
				if ( !this.value.length ) {
					this.value = "Enter FRN";
					$("#frn").css("color", "#999");
				}
			});
		},
	  
	tooltips: function(){
		$(".tooltip").tooltip({
			bodyHandler: function() {
				return $($(this).attr("href")).html();
			},
			showURL: false,
			track: true,
			delay: 0
		});
			$(".footnote").hide();
		},
	
	jQueryTipsy: function(){
			$.fn.tipsy = function(options) {
				options = $.extend({}, $.fn.tipsy.defaults, options);
				return this.each(function() {
					var opts = $.fn.tipsy.elementOptions(this, options);
					$(this).hover(function() {
						$.data(this, 'cancel.tipsy', true);
						var tip = $.data(this, 'active.tipsy');
						if (!tip) {
							tip = $('<div class="tipsy"><div class="tipsy-inner"/></div>');
							tip.css({position: 'absolute', zIndex: 100000});
							$.data(this, 'active.tipsy', tip);
						}
						if ($(this).attr('title') || typeof($(this).attr('original-title')) != 'string') {
							$(this).attr('original-title', $(this).attr('title') || '').removeAttr('title');
						}
						var title;
						if (typeof opts.title == 'string') {
							title = $(this).attr(opts.title == 'title' ? 'original-title' : opts.title);
						} else if (typeof opts.title == 'function') {
							title = opts.title.call(this);
						}
						tip.find('.tipsy-inner')[opts.html ? 'html' : 'text'](title || opts.fallback);
						var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});
						tip.get(0).className = 'tipsy'; // reset classname in case of dynamic gravity
						tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
						var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
						var gravity = (typeof opts.gravity == 'function') ? opts.gravity.call(this) : opts.gravity;
						switch (gravity.charAt(0)) {
							case 'n':
								tip.css({top: pos.top + pos.height + 10, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-north');
								break;
							case 't':
								tip.css({top: 32, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-north');
								break;
							case 's':
								tip.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-south');
								break;
							case 'e':
								tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}).addClass('tipsy-east');
								break;
							case 'w':
								tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}).addClass('tipsy-west');
								break;
							case 'r':
								tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + 20}).addClass('tipsy-west');
								break;
						}
						if (opts.fade) {
							tip.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 0.8});
						} else {
							tip.css({visibility: 'visible'});
						}
					}, function() {
						$.data(this, 'cancel.tipsy', false);
						var self = this;
						setTimeout(function() {
							if ($.data(this, 'cancel.tipsy')) return;
							var tip = $.data(self, 'active.tipsy');
							if (opts.fade) {
								tip.stop().fadeOut(function() { $(this).remove(); });
							} else {
								tip.remove();
							}
						}, 100);
					});
				});
			};
			$.fn.tipsy.elementOptions = function(ele, options) {
				return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
			};
			$.fn.tipsy.defaults = {
				fade: false,
				fallback: '',
				gravity: 'n',
				html: false,
				title: 'title'
			};
			$.fn.tipsy.autoNS = function() {
				return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 't';
			};(jQuery);
			
			
			//------ FORM TOOLTIPS --------------------
			$('.tipsWrap').each(function () {
				var hideDelay = 500;
				var hideDelayTimer = null;
				var beingShown = false;
				var shown = false;
				var trigger = $('.infoTrigger', this);
				var info = $('.tips', this).css({left:21,visibility:'hidden'});
				$(".infoTrigger").attr({title: ""});
				
			$(info)
				.mouseover(function () {
					// No delay timer when you hover over
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
				})
				.mouseout(function () {
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				hideDelayTimer = setTimeout(function () {
					hideDelayTimer = null;
					info.css({visibility:'hidden'});
				}, hideDelay);
				return false;
			});
			
			$(trigger)
				.mouseover(function () {
				
					// Get height of tooltip
					var height = $(this).next(".tips").height();
					var topoffset = height/2;
					
					// No delay timer when you hover over
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					if (info.css({top:-topoffset,visibility:'visible'})) {
						// don't trigger the animation again
						return;
					} else {
						// reset position of info box
						beingShown = true;
						info.css({top:-topoffset,visibility:'visible'});
					}
					return false;
				})
				.mouseout(function () {
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					hideDelayTimer = setTimeout(function () {
						hideDelayTimer = null;
						info.css({visibility:'hidden'});
					}, hideDelay);
					return false;
				});
			});


			//------ INLINE TOOLTIPS ------------------
			$('.tipsText').each(function () {
				var hideDelay = 500;
				var hideDelayTimer = null;
				var beingShown = false;
				var shown = false;
				var trigger = $('.infoTrigger', this);
				var info = $('.tips', this).css({visibility:'hidden'});
				$(".infoTrigger").attr({title: ""});
				
			$(info)
				.mouseover(function () {
					// No delay timer when you hover over
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
				})
				.mouseout(function () {
				if (hideDelayTimer) clearTimeout(hideDelayTimer);
				hideDelayTimer = setTimeout(function () {
					hideDelayTimer = null;
					info.css({visibility:'hidden'});
				}, hideDelay);
				return false;
			});
				
			$(trigger)
				.mouseover(function () {
				
					// Get height of tooltip
					var height = $(this).next(".tips").height();
					var topoffset = 21;
					
					// Get width of tooltip
					var width = $(this).next(".tips").width();
					var leftoffset = width/2.5;
					
					// No delay timer when you hover over
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					if (info.css({top:topoffset,left:-leftoffset,visibility:'visible'})) {
						// don't trigger the animation again
						return;
					} else {
						// reset position of info box
						beingShown = true;
						info.css({top:topoffset,left:-leftoffset,visibility:'visible'});
					}
					return false;
				})
				
				.mouseout(function () {
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					hideDelayTimer = setTimeout(function () {
						hideDelayTimer = null;
						info.css({visibility:'hidden'});
					}, hideDelay);
					return false;
				});
			});

			//------ TOOLTIP GRAVITY ------------------
			$('#toolbar .fontResizer span, #toolbar .search .search_button, #toolbar #global_go, #toolbar #contributionWho a, #toolbar #contributionlinks a, .pop .info').tipsy({gravity: 't'});
			$('#toolbar .remove, fieldset .info, .info.tooltip').tipsy({gravity: 'r'});
		},
	
	
	//-------------- DOCUMENT LIBRARY -----------------
	
	docLibCopyLink: function(){
		$(".warning").attr("title", "Flash not installed or version not supported.");
			if(typeof $.clipboardReady == 'function') { 
				$.clipboardReady(function(){
					$(".warning").remove();
					$(".copyLink").show();
					$(".copyLink").html("");
					$('<a href="javascript:void(0);" title="Copy link"><img src="/aegonukcontent/assets/img/icons/copy.gif" alt="" /></a>').click(function(){
						text = $(this).parent().parent("td:first a").attr("href");
						$.clipboard(text);
					}).appendTo(".copyLink");
				}, { debug: true } );
			}
		},
		
	
	//-------------- BROWSER FIXES --------------------
	IE6Fixes: function(){
			//------ BUTTONS --------------------------
			$('input.buttonSmall,input.button,input.buttonLarge,button.buttonSmall,button.button,button.buttonLarge,span.buttonSmall,span.button,span.buttonLarge,div.buttonSmall,div.button,div.buttonLarge').hover(function(){$(this).addClass('over');},function(){$(this).removeClass('over');});
			$('input.buttonBlueSmall,input.buttonBlue,input.buttonBlueLarge,button.buttonBlueSmall,button.buttonBlue,button.buttonBlueLarge,span.buttonBlueSmall,span.buttonBlue,span.buttonBlueLarge,div.buttonBlueSmall,div.buttonBlue,div.buttonBlueLarge').hover(function(){$(this).addClass('overBlue');},function(){$(this).removeClass('overBlue');});	
			//------ FILMSTRIP GALLERY ----------------
			$('#filmstrip img, #filmstrip1 img, #filmstrip2 img, #filmstrip3 img, #filmstrip4 img, #filmstrip5 img').hover(function(){$(this).addClass('over');},function(){$(this).removeClass('over');});
			//------ Field focus ----------------------
			$("input, select").focus(function () {$(this).addClass("focus");});
			$("input, select").blur(function () {$(this).removeClass("focus");});
		},
		
	init: function(){
		//TOOLBAR
			this.countryDropdown();
			this.searchBox();
			this.selectDropdowns();
		//CONTENT ENHANCMENTS
			this.dynamicDate();
			this.equalHeight();
			this.scrollToAnchor();
			this.inPageTabs();
			this.expandableBoxes();
			this.tables();
			this.checkboxRadio();
			this.datepicker();
			this.rangepicker();
			this.emailto();
			this.frn();
			this.tooltips();
			this.jQueryTipsy();
		//DOCUMENT LIBRARY
			this.docLibCopyLink();
		//BROWSER FIXES
			this.IE6Fixes();
		docLibTableFilter.init();
	}
};

$(document).ready(function(){CORE.init();$("body").addClass("json");});

})(jQuery)
