// Realise Helper Tools 2011
// A collection of very simple, unobtrusive functions to help with development

$(function () {
    window.tools = {	
        searchBox: function () {			
            // Adds default search text to search input
            var changed = false;
			
			var searchValue = "Search";
			
			if (vanilla.ln == "fr-CA") searchValue = "Recherche";
			
            $('#search2').addClass('quiet').val(searchValue).bind('change', function () { if (!changed) { changed = true; } }).bind('focus', function () { $(this).removeClass('quiet'); if (!changed) { $(this).val(''); } }).bind('blur', function () { if (!changed) { $(this).val(searchValue); $(this).addClass('quiet'); } });
        },

        iPad: function () {
			//ipad and iphone fix
			if (vanilla.os == "ipad" || vanilla.os == "iphone") {			
				$("#primaryNav li a").click(function(){
					//we just need to attach a click event listener to provoke iPhone/iPod/iPad's hover event
				});
			}
        },

        cssHelper: function () {
            // CSS HELPER CLASSES =================
            // Adds class to every 2rd li a in related links within grid9 
            $("div.related ul").each(function(){
				$(this).find("li:odd").addClass("odd");
			});

            // For each table on the page
            $("table").each(function ()
            {
                // Highlight the odd and even rows, ignore the archived rows though
				if (!$(this).hasClass("dontStripe")) {
					$(this).find("tr:not(.archived):even").addClass("odd"); // Odd and even gets switched around to deal with zero/one indexing
					$(this).find("tr:not(.archived):odd").addClass("even");
				}

                // Highlight the first and last row in the table
                $(this).find("tr").last().not(".notLast").addClass("last");
                $(this).find("th").first().not(".notFirst").addClass("first");
				
                // Highlight the first and last th/td in each row
                $(this).find("tr").each(function () 
                {
                    $(this).find("th, td").last().not(".notLast").addClass("last");
					$(this).find("th, td").first().not(".notFirst").addClass("first");
                });
            });
			
            // Stripey li's - used for search results mainly
            $("ul.stripe").each(function ()
            {
                // Highlight the odd and even rows		
                $(this).find("li:even").addClass("odd"); // Odd and even gets switched around to deal with zero/one indexing
                $(this).find("li:odd").addClass("even");
				
                // Highlight the first and last row in a list
                $(this).find("li").first().not(".notFirst").addClass("first");
                $(this).find("li").last().not(".notLast").addClass("last");
            });
			
            // Remove border from first and last type2 div within a type 1
            $(".type1").each(function ()
            {
                $(this).find(".type2").first().addClass("first");
                $(this).find(".type2").last().addClass("last");
				
				$(this).find("ul").last().addClass("last");
				
				$(this).find("h2").first().addClass("first");
            });
			
            // Highlight the first and last items in each ul and ol
            $("ul, ol").each(function ()
            {
                $(this).find("li").first().not(".notFirst").addClass("first");
                $(this).find("li").last().not(".notLast").addClass("last");
            });
			
            $("#content").each(function ()
            {
                $(this).find("div.floatLeftThird").last().addClass("last");
            });
			
			$(".tab").find("ul").first().addClass("first");
			
            // Highlight the last p in disclaimer div to remove margin-bottom
            $(this).find("div.disclaimer").each(function ()
            {
                $(this).find("p").last().addClass("last");
            });
        },

        externalLinks: function () {
            // EXTERNAL LINKS ======================
			setTimeout(function(){ // Add in a slight delay to break the flow and stop the script timing out in IE
				var links = $("a").not(".external");
				
				if (vanilla.site == "olive_institutional" && links.length > 500) return false; // Don't even attempt to do this if there's too many links
				
				links.filter("a[rel='external'], a[target='_blank']").addClass("external").attr("title", "Link opens in a new window").click(function (event)
				{
					window.open(this.href);
					event.preventDefault(); // Stop the link from opening a new window but don't block WebTrends
				});
				
				links.filter(".noExternalIcon").removeClass("external");
			}, 400);
        },		
		
        iconClasses: function () {
            // ADD ICONS CLASSES TO FILE LINKS ======================
			setTimeout(function(){ // Add in a slight delay to break the flow and stop the script timing out in IE
				var links = $("a");
				
				if (vanilla.site == "olive_institutional" && links.length > 500) return false; // Don't even attempt to do this if there's too many links
				
				// Filter out links that already have classes on them
				links = links.not(".pdf").not(".txt").not(".doc").not(".xls").not(".csv").not(".email");

				// PDF links
				links.filter("a[href$='.pdf'], a[href$='.pdf ']").addClass("pdf").attr("title", "Adobe Acrobat document - Link opens in a new window");

				// Txt links
				links.filter("a[href$='.txt']").addClass("txt").attr("title", "Text document - Link opens in a new window");

				// Word document links
				links.filter("a[href$='.doc']").addClass("doc").attr("title", "Word document - Link opens in a new window");

				// Excel links
				links.filter("a[href$='.xls'], a[href$='.csv']").addClass("xls").attr("title", "Spreadsheet - Link opens in a new window");
				
				// Email links
				links.filter("a[href^='mailto:']").addClass("email").attr("title", "Send an email to this address");
				
				// Adjust li for icon link within, removes duplicate icons
				var iconLinks = $("#content ul li").not(".hasIcon").children("a");
				
				iconLinks.filter(".pdf, .txt, .doc, .external, .print").each(function(){
					var txt = $(this).parent().html();
					txt = $.trim(txt);
					txt = txt.substring(0,2).toLowerCase();
					
					if (txt == '<a') $(this).parent().addClass('hasIcon');
				});
			}, 600);
        },
		
		enforceRelatedHeights: function () {
			// Ensures related resources on the same row match in height
			$(".grid9 div.related ul li:even").each(function(){				
				var even = $(this);
				var odd  = $(this).next(".odd");
				
				if (!odd.length) return false;
				
				var evenHeight = even.height();
				var oddHeight  = odd.height();

				if (evenHeight > oddHeight)
					odd.height(evenHeight);
				else
					even.height(oddHeight);
			});
		},

        backButton: function () {
            // Back button - returns to previous page
            $('a.back').click(function ()
            {
                parent.history.back();
                return false;
            });
        },

        footer: function () {
			// FOOTER =========================	
            var slide = false;
            var height = $("#footerContent").height();
            $("#footerContent").find("div").each(function ()
            {
                if ($(this).height() > height) height = $(this).height();
            });
            $("#footerContent").css("height", height);
            $("#footerContent").hide();
            var speed = 500;
            $("#footerTrigger").click(function ()
            {
                var docHeight = $(document).height();
                var windowHeight = $(window).height();
                var scrollPos = docHeight - windowHeight + height;
                $("#footerContent").animate({ "height": "toggle" }, speed);
                $(this).removeClass("open");
                if (slide == false) {
                    if ($.browser.opera) {
                        $("html").animate({ scrollTop: scrollPos + "px" }, speed);
                    } else {
                        $("html, body").animate({ scrollTop: scrollPos + "px" }, speed);
                    }
                    $(this).addClass("open");
                    slide = true;
                } else {
                    slide = false;
                }
            });
        },

        primaryMenus: function () {
            if (vanilla.os == "ipad" || vanilla.os == "iphone") return false; // Don't bother with menus on iDevices
			
			// PRIMARY MENUS =========================
            var menuDelay = 400;
            var menuItemWidth = 226;
            var maxWidth = 960;
            var menuTimeout = 0;
            $("#primaryNav").find(".sectionLink").mouseover(showNav);
            $("#primaryNav").mouseout(function ()
            {
                menuTimeout = setTimeout(function ()
                {
                    hideNav();
                }, menuDelay);
            });
            function hideNav()
            {
                $("#primaryNav").find("li ul").hide();
                $("#primaryNav").find("li").removeClass("hover");
            }
            function showNav()
            {
                hideNav();
                $(this).addClass("hover");
                $(this).find("ul").show();
                var menu = $(this).children("ul");
                var guideElement = $("#header .inner"); // This represents the width and area our menu should match
                clearTimeout(menuTimeout);
                if (menu.find(".hasChildren").length) { // If this is a "mega" menu
                    menu.addClass("mega");
                    var children = menu.children("li").not(".level2Top").not(".level2Right");
                    var length = children.length;
                    menu.width(length * menuItemWidth); // Work out the width to use
                    // If the menu is too wide then shrink it till it fits
                    while (menu.outerWidth() > guideElement.outerWidth()) {
                        if (length < 2) menu.width(guideElement.outerWidth()); // Worst case scenario - squeeze menu to min possible width - this should never actually happen
                        length--;
                        menu.width(length * menuItemWidth); // Work out the width to use
                    }
                }
                // Make sure our menu is never narrower than the actual menu item (especially on foreign-language sites)
                if (menu.outerWidth() < $(this).outerWidth()) menu.width($(this).outerWidth());
                if (menu.offset()) {
                    // If the menu has gone off the right-hand side of the available area, push it back
                    if (menu.offset().left + menu.outerWidth() > guideElement.offset().left + guideElement.outerWidth())
                        menu.offset({ left: (guideElement.offset().left + guideElement.outerWidth()) - menu.outerWidth() });
                    // If the menu is too far right past it's actual then push it back a little
                    if (menu.offset().left + menu.outerWidth() < $(this).offset().left + $(this).outerWidth())
                        menu.offset({ left: $(this).offset().left + $(this).outerWidth() - menu.outerWidth() });
                    // If the menu is STILL outwith the available area, then push it back as far left as possible
                    else if (menu.offset().left + menu.outerWidth() > guideElement.offset().left + guideElement.outerWidth())
                        menu.offset({ left: guideElement.offset().left });
                }
            }
        },

        selectNavigation: function () {
            // SELECT NAVIGATION MENU =========================	
            $("select.headerSelect, li.selector select").change(function ()
            { // Whenever this select box is changed, take it's value as a new window location
                if ($(this).val() == "" || $(this).attr("id") == "countrySelect") return false; // Don't proceed if the value is empty
                if ($(this).find("option:selected").hasClass("external"))
                    window.open($(this).val()); // Open in a new window
                else
                    window.location = $(this).val(); // Open in this window
                return false;
            });
        },

        simpleTabs: function () {
            // SIMPLE TABS =========================
            $("div.tabs").each(function ()
            {
                var self = this;
                $(self).children("div").hide().first().show();
                $(self).find("ul.tabNav a").click(function ()
                {
                    $(self).find("ul.tabNav a").removeClass("selected");
                    $(this).addClass("selected");
                    $(self).children("div").hide().filter(this.hash).show().add;
                    return false;
                }).first().click();
            });
        },

        accordion: function () {
            // ACCORDION =========================
            // Set default open/close settings
            $(".accordionContainer").hide(); // Close all containers
            $(".accordionTrigger.accordionOpen").addClass("active").next().show();
            var slidingInProgress = false;
            // On Click
            $(".accordionTrigger").click(function ()
            {
                if (slidingInProgress) return false;
                if ($(this).next().is(":hidden")) { // If immediate next container is closed...
                    slidingInProgress = true;
                    var naughtyChildren = "";
                    // Because IE7 and IE6 are stupid we need to temporaily hide certain child elements
                    if ($("body").hasClass("ie7") || $("body").hasClass("ie6")) naughtyChildren = "*";
                    // Slide up the immediate next container
                    $(".accordionTrigger").removeClass("active").next().slideUp(function ()
                    {
                        slidingInProgress = false;
                    }).find(naughtyChildren) // Hide certain elements in IE7 and IE6.css("visibility", "hidden");
                    // Slide down the immediate next container
                    $(this).toggleClass("active").next().slideDown(function ()
                    {
                        $(this).find(naughtyChildren).css("visibility", "visible"); // Unhide certain elements in IE7 and IE6
                        slidingInProgress = false;
                    }).find(naughtyChildren) // Hide certain elements in IE7 and IE6.css("visibility", "hidden");
                } else { // If this item is open then close it
                    slidingInProgress = true;
                    var naughtyChildren = "";
                    // Because IE7 and IE6 are stupid we need to temporaily hide certain child elements
                    if ($("body").hasClass("ie7") || $("body").hasClass("ie6")) naughtyChildren = "*";
                    // Slide up the immediate next container
                    $(".accordionTrigger").removeClass("active").next().slideUp(function ()
                    {
                        slidingInProgress = false;
                    }).find(naughtyChildren) // Hide certain elements in IE7 and IE6.css("visibility", "hidden");
                }
                return false;
            });
        },
		
		tableIconFixes: function () {
			// Adds an extra class to table cells containing icons to help sort their width
			$("table td.icons").each(function(){
				var children = $(this).children("a, img").length;

				var classNames = ["noIcons", "oneIcon", "twoIcons", "threeIcons", "fourIcons", "fiveIcons", "sixIcons", "sevenIcons", "eightIcons", "nineIcons", "manyIcons"];
				
				if (children < 0) children = 0;
				if (children > 10) children = 10;
				
				$(this).addClass(classNames[children]);
			});
		},
		
		disclaimer: function() {
			// Checks to see if the user has hit the site before this session - if not shows a modal disclaimer
			var validation = $("#validation");			
			var url = window.location + "";
			
			// If there is validation content and this isn't the legal info page
			if (validation.length && url.indexOf("legal_information") == -1) {								
				// If no session cookie is set
				if (!window.tools.session.check()) {
					// Create a modal popup
					$("#validation").modalBox({
						onShow: function () {
							// If the user accepts then set a session cookie and close the popup
							$(".validationAccept").focus().click(function(){
								window.tools.session.set();
								$("#validation").modalBox({hide: true});
								return false;
							});
						}
					});
				}
			}
		},
		
		modalLinks: function() {
			// Find links on the page and gives them actions to open modal popups
			$("a.modalLink").click(function(){
				var link = $(this).attr("href");

				var options = {};
				
				if ($(this).hasClass("modalAjax"))
					options.ajax = link;
				else if ($(this).hasClass("modalIframe"))
					options.iframe_src = link;
				else
					options.inline = link;
				
				$.modalBox(options);
				
				return false;
			});
		},
		
		session: {
			// Quick functions for checking and setting session cookies
			set: function(modifier) {
				$.cookie("session_cookie" + modifier, "true", {path: "/"});
			},
			
			check: function(modifier) {
				return ($.cookie("session_cookie" + modifier) == "true");
			},
			
			clear: function(modifier) {
				$.cookie("session_cookie" + modifier, null);
			}
		},
		
		literatureBlocks: function() {
			// Only used on literature homepage, makes all blocks on a row the same height

			$(".literature .grid9 .floatLeftThird, .support .grid9 .floatLeftThird").each(function(x){				
				if (x % 3 == 0) {
					var items = [$(this), $(this).next(), $(this).next().next()];
					
					var maxHeight = 0;
					
					for (var x = 0; x < items.length; x++)
						if (items[x].height() > maxHeight) maxHeight = items[x].height();
						
					for (var x = 0; x < items.length; x++)
						items[x].height(maxHeight);
				}
			});
		},
		
		segmentMemory: function() {
			// On multisegment (or multi-language) sites, remember the current setting so the user shouldn't see the segment selector again
			if (
				vanilla.segment != "all" && 
				vanilla.segment != "" &&
				(
					vanilla.segment == "consumer" || 
					vanilla.segment == "ifa" || 
					vanilla.segment == "wealth" || 
					vanilla.segment == "institutional" || 
					vanilla.segment == "consultant" || 
					vanilla.segment == "bank"
				)
			)
				$.cookie("segment", vanilla.segment, {path: "/", expires: 14});
				
			if (vanilla.ln != "")
				$.cookie("ln", vanilla.ln, {path: "/", expires: 14});
		},
			
		prospectusCheck: function() {
			// Certain PDFs need a disclaimer before them
			if (vanilla.site == "uk" && vanilla.segment == "consumer") { // This code only applies to UK consumer
				// For these two document types run special code
				$("a[href*='/R_Investment_Funds_Application/']").addClass("agreeProspectus");
				$("a[href*='/O_Investment_Funds_Application_Form/']'").addClass("agreeProspectus");

				// When this type of link is clicked
				$(".agreeProspectus").unbind("click").click(function(event) {
					// Create our hidden modal content if it doesn't exist
					if (!$("#propspectusCheck").length) {
						$("body").append(
							$("<div/>")
							.addClass("hidden")
							.attr("id", "propspectusCheck")
							.append("<h2>Confirmation required</h2>")
							.append("<p>I confirm I have read a copy of the Fund Prospectus</p>")
							.append("<p>For details see our <a href='/consumer/literature/144/inside.html#subsection426' rel='external' class='prospectuses external'>Prospectuses</a></p>")
							.append(
								$("<div/>")
								.attr("id", "modalControls")
								.append("<a class='button closeModal' href='#'><em>Cancel</em></a>")
								.append("<a class='button prospectusCheck' href='" + $(this).attr("href") + "'><em>OK</em></a>")
							)
						)
					}

					// Now show our modal popup
					$("#propspectusCheck").modalBox({onShow: function(){
						$(".prospectuses").click(function() {
							window.open(this.href);
							return false;
						});
						
						// If the user accepts
						$(".prospectusCheck").click(function(){
							window.open(this.href);	// Open the PDF in a new window
							$.modalBox({hide: true}); // Close the modal
							
							return false;
						})
					}});
					
					return false;
				});
			}
		},
		
		// for www header select your region dropdown
        headerSiteSelect: function () {
			$('#countrySelectInside span.selectTitle').click(function() {
				$('ul.headerSelectSite').slideToggle('100', function() {
					 $('#countrySelectInside span.selectTitle').toggleClass("opened");
				});
			});
        },
		
		fixEmptyCells: function() {
			// IE won't render empty TDs nodes properly so make sure there's always a &nbsp; at least
			if (vanilla.browser == "ie ie7" && (vanilla.section != "literature" && vanilla.section != "support")) { // Only run this code for IE7 and not on Literature
				$("td, th").each(function() {
					if ($.trim($(this).html()) == "") $(this).html("&nbsp;");
				});
			}
		}
    };

	
    $(document).ready(function () {
		if (typeof(vanilla) == "undefined") 
			vanilla = {
				segment:             '',
				ln:                  '',
				nav:                 '',
				nav_ln:              '',
				url:                 '',
				url_selectable:      '',
				display_nav:         '',
				section:             '',
				usage:               '',
				site:                '',
				urlPrefix:           '',
				otherLang:           '',
				otherLangText:       '',
				urlPrefixMultiLang:  '',
				browser:             '',
				os:                  ''
			};
	
        // Run each of our functions
        for (var key in tools) {
             if (typeof(tools[key]) == "function") tools[key]();
        }
	});
});
