/**
 * @author markcq8
 */

function fontResizer(smallFont,medFont,largeFont)
{
function clearSelected() { $(".smallFont").removeClass("curFont"); $(".medFont").removeClass("curFont"); $(".largeFont").removeClass("curFont"); }
function saveState(curSize) {	var date = new Date(); date.setTime(date.getTime()+(7*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); document.cookie = "fontSizer"+"="+curSize+expires+"; path=/"; equalHeight($(".equalheight")); equalHeight($(".equalheight2")); equalHeight($(".equalheight3")); }

$(".smallFont").click(function(){ $('html').css('font-size', smallFont); clearSelected(); $(".smallFont").addClass("curFont"); saveState(smallFont);  });

$(".medFont").click(function(){ $('html').css('font-size', medFont); clearSelected(); $(".medFont").addClass("curFont"); saveState(medFont); });

$(".largeFont").click(function(){ $('html').css('font-size', largeFont); clearSelected(); $(".largeFont").addClass("curFont"); saveState(largeFont); });

function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; }

var savedSize = getCookie('fontSizer');

if (savedSize!="") { $('html').css('font-size', savedSize); switch (savedSize) { case smallFont: $(".smallFont").addClass("curFont"); break; case medFont: $(".medFont").addClass("curFont"); break; case largeFont: $(".largeFont").addClass("curFont"); break; default: $(".smallFont").addClass("curFont"); } }
else { $('html').css('font-size', smallFont); $(".smallFont").addClass("curFont"); }
}

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
		$(this).height("auto");
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}


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"), "");
	}
	
};

var cookie = {

	set: function(name, value, days){
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + date.toGMTString();
		}
		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){
		this.set(name, "", -1);
	}
	
};

var filter = {
	
	run: function(selector, query){
		//filter results based on query  
   		query =   $.trim(query); //trim white space  
   		query = query.replace(/ /gi, '|'); //add OR for regex query  
   
   		$(selector).each(function() {  
     		($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide() : $(this).show();
   		});  
 	},
	
	init: function(){  
		$("#tableSearch").keyup(function(event){
			//if esc is pressed or nothing is entered  
     		if (event.keyCode == 27 || $(this).val() == '') {  
       		//if esc is pressed we want to clear the value of search box  
       			$(this).val('');  
               	//we want each row to be visible because if nothing  
	          	//is entered then all rows are matched.  
       			$('#textfilter tbody tr').show();  
     		} else {  
       			filter.run('#textfilter tbody tr', $(this).val());  
     		}   
		} 
	)}
		
};



var bookmark = {
	
	toggle: function(){
		$(".tipsy").hide();
		$("#bookmarks ul").toggle();
		if ($("#bookmarks .open").hasClass("on")) {
			$("#bookmarks .open").removeClass("on");
		}else{
			$("#bookmarks .open").addClass("on");
		}
	},
	
	display: function(){
		//display bookmarks list
		var x = cookie.get('bookmarks');
		var output = "<div class=\"top\"><span class=\"open\"  onclick=\"bookmark.toggle();\" title=\"Open Bookmarks\">Bookmarks</span> <span class=\"add\" onclick=\"bookmark.add(); return false;\" title=\"Bookmark this page\"></span></div>";
		if (x == "-" || x == "" || x === null) {
			output += "<ul>";
			output += "<li class=\"none\">You have no bookmarks</li>";
			output += "</ul>";
		}
		else {
			output += "<ul>";
			for (var i in bookmarkList) {
				output += "<li><a title=\"Go to '";
				output += i;
				output += "'\" href=\"";
				output += bookmarkList[i];
				output += "\">";
				output += i;
				output += "</a><a class=\"remove\" href=\"#\" onclick=\"bookmark.remove('" + i + "'); return false\" title=\"Remove this bookmark\">[Remove]</a></li>";
			}
			output += "</ul>";
		}
		$("#bookmarks").html(output);	
		cookie.set("bookmarks", this.serialize(), "365");
	},

	remove: function(title){
		$(".tipsy").hide();
		// Remove bookmark with specific name
		delete bookmarkList[title];
		cookie.set("bookmarks", this.serialize(), "365");
		this.display();
		$("#bookmarks .open").addClass("on");
		return false;
	},
	
	add: function(){
		//Add new bookmark
		$(".tipsy").hide();
		var title = util.trim(window.document.title.split("|", 1));
		if (this.exists() === true) {
			//If a bookmark with this URL already exists, Display a message and exit
			alert("This page is already in your bookmark list");
			return false;
		}
		else {
			if (typeof(bookmarkList[title]) == 'undefined') {
				//If there is no bookmark with this name add it
				bookmarkList[title] = window.location.pathname;
				cookie.set("bookmarks", this.serialize(), "365");
				this.display();
				$("#bookmarks .open").addClass("on");
				return true;
			}
			else{
				for (i = 1; i <= 100; i++) {
					if (bookmarkList[title + " (" + i + ")"] === undefined) {
						//If there is a bookmark with the same name add incrimental number
						//Add bookmark
						bookmarkList[title + " (" + i + ")"] = window.location.pathname;
						i = 100;
						cookie.set("bookmarks", this.serialize(), "365");
						this.display();
						$("#bookmarks .open").addClass("on");
						return false;
					}
				}
			}
		}
	},
	
	exists: function(){
		//check if a bookmark with this URL exists
		for (var i in bookmarkList) {
			if(bookmarkList[i] == window.location.pathname){
				return true;
			}
		}
		return false;
	},
	
	serialize: function(){
		//Convert bookmarkList hash to a string suitable for a cookie
		var cookieString = "";
		for (var i in bookmarkList){
			cookieString += "^";
			cookieString += i;
			cookieString += "|";
			cookieString += bookmarkList[i];
		}
		return cookieString;
	},
	
	displayCookieString: function(){
		//Display the cookie string for testing
		var cookieString = this.serialize();
		$("#cookieString").html(cookieString);	
	},
	
	getBookmarksFromCookie: function(){
		//Get bookmarks list from cookie
		var cookieString = cookie.get("bookmarks");
		var pairs = cookieString.split("^");
		for(var i=0; i<pairs.length; i++){
			//Split cookie string into name/url pairs
			var parts = pairs[i].split("|");
			for(var j=0; j<parts.length; j++){
				//Split pairs into two strings
				if(j % 2){
					//Insert strings into bookmarkList object
				    //console.info("bookmarkList2[" + parts[j-1] + "]" + " = \"" + parts[j] + "\";");
					bookmarkList[parts[j-1]] = parts[j];
				}
			}
		}
	},
	
	init: function(){
		//alert(cookie.get("bookmarks"))
		if (cookie.get("bookmarks") === null) {
			//alert("set!")
			cookie.set("bookmarks", "-", "365");
			//alert(cookie.get("bookmarks"))
		}
		bookmarkList = {};
		this.getBookmarksFromCookie();
		this.display();
		$("#bookmarks").addClass("json");
		$("#bookmarks ul").hide();
	}

};

var highContrast = {
	
	setActiveStyleSheet: function(title){
		var i, a, main;
		for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
			if (a.getAttribute("rel").indexOf("style") != -1 &&
			a.getAttribute("title")) {
				a.disabled = true;
				if (a.getAttribute("title") == title) 
					a.disabled = false;
			}
		}
	},
	
	init: function(){
		var x = cookie.get('contrast');
		if(x === null){
			cookie.set("contrast", "normal")
		}
		if(x == "high"){
			highContrast.setActiveStyleSheet("High Contrast");
		}
		
		$(".contrast").click(function(){
			var x = cookie.get('contrast');
			if(x == "high"){
				highContrast.setActiveStyleSheet("Normal");
				cookie.set("contrast", "normal");
			}else{
				highContrast.setActiveStyleSheet("High Contrast");
				cookie.set("contrast", "high");
			}
		});
	}
	
};

var AEGON = {
	
	fontSize: function(){
		$(".fontResizer").show();
		fontResizer('100%','115%','130%');
	},
	
	searchBox: function(){
		if ($("#search_box").val() == ""){
			$("#search_box").val("Search");
		}
				$("#search_box").focus(function(){
					if( this.value == "Search" ){
						this.value = "";
						$("#search_box").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "Search";
						$("#search_box").css("color", "#999");
					}
				});
		
		if ($("#search_box_body").val() == ""){
			$("#search_box_body").val("Search");
		}
				$("#search_box_body").focus(function(){
					if( this.value == "Search" ){
						this.value = "";
						$("#search_box_body").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "Search";
						$("#search_box_body").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(){
		$("#frn").val("Enter FRN to register");
				$("#frn").focus(function(){
					if( this.value == "Enter FRN to register" ){
						this.value = "";
						$("#frn").css("color", "#333");
					}
				}).blur( function(){
					if ( !this.value.length ) {
						this.value = "Enter FRN to register";
						$("#frn").css("color", "#999");
					}
				});
		},
		
	globalSelect: function(){
		$("#mixed-combo").specialselectCombo(
			{
				emptyText: "AEGON global sites", autoFill: true
			}
		);
	},
	
	copyrightDate: function(){
            var date = new Date();
            var year = date.getFullYear();
            $("#copyright span").html(year);
    },
	  
	tooltips: function(){
		$("a.tooltip").tooltip({
			bodyHandler: function() {
				return $($(this).attr("href")).html();
			},
			showURL: false,
			track: true,
			delay: 0
		});
		$(".footnote").hide();
	},
		
	init: function(){
		this.fontSize();
		this.searchBox();
		this.globalSelect();
		this.emailto();
		this.frn();
		this.copyrightDate();
		this.tooltips();
		highContrast.init();
		bookmark.init();
		filter.init();
	}
};

$(document).ready(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;
	})
})

$(document).ready(function() {
	$('input:checkbox').checkbox({cls:'checkbox'});
	$('input:radio').checkbox();
});

$(document).ready(function() { 
	$(".sortable").tablesorter(); 
 }); 

$(document).ready(function() {
	equalHeight($(".equalheight"));
});

$(document).ready(function() {
	equalHeight($(".equalheight2"));
});

$(document).ready(function() {
	equalHeight($(".equalheight3"));
});
			
$(document).ready(function() {
	AEGON.init();
});


// Sliding hide/show box
$(document).ready(function() {
  $('.expandbox .expandInfo').hide();
  $('.expandbox .expandToggle').click(function(e) {
   	$(this).siblings('.expandbox .expandInfo').slideToggle(400);
    return false;
  });
});




$(function(){
    $('.searchable a[href*=#]').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;
            }
        } 
    });
});





//TOOLBAR DROPDOWN 
$(document).ready(function() {
// Build sub navigation login tab
	$("#toolbar #login").addClass("top")
	$("#toolbar #login").append("<ul class=\"submenu\"><li><a href=\"#\">Customer login</a></li><li class=\"last\"><a href=\"#\">Adviser login</a></li></ul>");

});


hide_menus = function() {
	$(".openMenu").removeClass("openMenu")
	$(".submenu").hide();
} 

//timeouts stop menus from prematurely closing
menu_timeouts = [];
clear_timeouts = function() {
	var menu_timeouts_copy = menu_timeouts;
	menu_timeouts = [];
	for (var i=0; i < menu_timeouts_copy.length; i++) {
		window.clearTimeout(menu_timeouts_copy[i]);
	};
}


$(document).ready(function() {
	//topnav on mouse over
	$("#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;
    })
	
	//topnav on mouseout
	$("#toolbar #login").mouseout (function(){
		menu_timeouts.push(window.setTimeout(hide_menus,400));
		return false;
    })
});






// TOOLTIP
(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, 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 + 30}).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);

            });
            
        });
        
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.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);




 $(function() {
	
	$('#toolbar .fontResizer span, #toolbar  #bookmarks span, #toolbar .search .search_button, #toolbar #global_go').tipsy({gravity: 't'});
    $('#toolbar .remove').tipsy({gravity: 'r'});
  });




