(function($) {
  $(document).ready(function() {

    setUpTopMenu();
    addTextToSearchBoxes();
    addHoverToContactUsImage();
    setUpLeftNav();

    // Dynamic pages
    if ($("body.dynamic-page").length) {
      setUpLeftWidget();
      setUpScrollableWidget();
    }

    if (dynamicPageUpdates()) {

      // Multi section pages (1 2 3 pages)
      if ($("div.multi-section-wrapper").length) {
        setUpMultiSectionPage($("div.content"));
      }

/* Dynamic updating of pages (apart from multi-pages) not wanted

      // Pages in Life Events section
      if ($("div.life-events-lower-level, div.life-events-top-level").length) {

        // Check if using relative or absolute paths in links
        var relativeLinks = true;
        if ($(".menu ul li:first a").attr("href").indexOf('http://') > -1) {
          relativeLinks = false;
        }

        // Rewrite links on page so that only portions of the page updates when they're clicked
        rewriteNavLinks($("div.menu-and-content"));
        rewriteContentLinks($("div.menu-and-content"), $("div.content"));
        rewriteLinksOutsideNavAndContent();

        // Preload the content areas of the other pages in the same navigation section
        preloadCurrentSectionContentAreas($("div.menu-and-content"));
      }

*/

    }

    /* Accessibility page */
    if ($("body#id9928").length) {
      setDynamicPageUpdatesPreferences();
    }


    /* Make an appointment page */
    if ($("body#id10025").length) {
      setUpAppointmentFormValidation();
    }
    
    /* Request information page */
    if ($("body#id10029").length) {
      setUpRequestInfoFormValidation();
    }
    
    /* Find us page */
    if ($("body#id10021").length) {
      setUpContactCentreSelectBox();
    }
    
    /* Our Team page */
    if ($("body#id9886").length) {
      // setUpOurTeamSelectBox();
    }
    
    /* Pages with striped tables */
    addTableStriping();

    /* Family Trust calculators */
    if ($("body.family-trust-calculator").length) {
      familyTrustCalculators();
    }

    /* GNZS landing page */
    if ($("body#id20721").length) {
      setGNZSDefaultValues();
    }

    /* Family Promise landing pages */
    if ($("body#id25761").length||$("body#id26702").length||$("body#id26706").length||$("body#id29061").length||$("body#id26710").length||$("body#id26714").length||$("body#id29503").length||$("body#id29507").length) {
      setFamilyPromiseDefaultValues();
    }
    
    function isIE() {

      return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);

    } // end isIE


/* All pages */

    function setUpTopMenu() {

      // Add CSS rules to override the :hover rules which show the full menu div
      var cssRules = '<style type="text/css">#top-menu li#personal-services-top-menu-link:hover { background-image: none; }';
      cssRules += '#top-menu li#personal-services-top-menu-link:hover ul { display: none; }</style>';
      $("head").append(cssRules);

      // When user hovers over the Personal Services menu item, fade in the full menu
      $("#personal-services-top-menu-link").hoverIntent(function() {
        $(this).find("ul").customFadeIn(500);
        $(this).css("background", "url(/__data/assets/image/0003/7842/bg-top-menu-hover.gif) no-repeat");
      }, function() {
        $(this).find("ul").customFadeOut(500);
        $(this).css("background", "none");
      });

      // When user clicks on the Personal Services menu item, fade in the full menu and don't follow link to the home page.
      $("#personal-services-top-menu-anchor").click(function() {
        $(this).find("ul").customFadeIn(500);
        $(this).css("background", "url(/__data/assets/image/0003/7842/bg-top-menu-hover.gif) no-repeat");
        return false;
      });

      $("#top-menu-full-menu a").click(function() {
        $("#top-menu-full-menu").find("ul").customFadeOut(500);
      });

    } // end setUpTopMenu


    function addTextToSearchBoxes() {

      // Add text to search box at top right of every page
      $("#words").DefaultValue("Search Public Trust");

      // Add text to search again box if on search results page
      $("#search-again-box").DefaultValue("Try a new search?");

    }


    function addHoverToContactUsImage() {

      $("#contact-pt").hoverIntent(function() {

        // If the hover image does not already exist, insert the it after the existing image. If IE insert a gif, if other browsers insert a png
        var hoverImageHTML;

        if ($("#contact-pt-image-hover").length == 0) {
          if (isIE()) {
            hoverImageHTML = '<img id="contact-pt-image-hover" src="/__data/assets/image/0008/11321/contact-pt-hover.gif" alt="View details" />'
          } else {
            hoverImageHTML = '<img id="contact-pt-image-hover" src="/__data/assets/image/0010/11341/contact-pt-hover.png" alt="View details" />'
          }

          $("#contact-pt").find("a").append(hoverImageHTML);
        }

        // Fade hover image in and out on hover
        $("#contact-pt-image-hover").customFadeIn(500);
      }, function() {
        $("#contact-pt-image-hover").customFadeOut(500);
      });

    } // end addHoverToContactUsImage



/* Dynamic Pages */

    function setUpLeftWidget() {

      // Add CSS rules to override the :hover rules for the left widget
      var cssRules = '<style type="text/css">.widget-content:hover .overlay { background: none; cursor: pointer; }';
      cssRules += '.widget-content .overlay { left: 0; top: 0; display: none; cursor: pointer; }</style>';
      $("head").append(cssRules);

      // When user hovers over one of the widget sections, show the overlay text
      $(".widget-content").hoverIntent(function() {
        var cssHover = {
        "background-color" : "#56849d"
      }
        $(this).find(".overlay").css(cssHover).customFadeIn(200);
      }, function() {
        $(this).find(".overlay").customFadeOut(200);
      });

      // When the user clicks one of the widget sections, go to the linked page (linked under the h3)
      $(".widget-content").click(function() {
        window.location = $(this).find("h3 a").attr("href");
      });

    } // end setUpLeftWidget


    function setUpScrollableWidget() {

      if (dynamicPageUpdates()) {

        $("#scrollable-widget-inner").easySlider({
          auto: true,
          continuous: true,
          pause: 60000
        });

      } else {

        $("#scrollable-widget-inner").easySlider({
          auto: false,
          continuous: false
        });

      }

      // Add previous and next links and make them click the easySlider generated previous and next buttons when clicked
      $("#scrollable-widget").append('<a id="scrollable-widget-previous"><span>Previous featured article</span></a><a id="scrollable-widget-next"><span>Next featured article</span></a>');
      $("#scrollable-widget-previous").click(function() {
        $("#prevBtn a").click();
      })
      $("#scrollable-widget-next").click(function() {
        $("#nextBtn a").click();
      })

      // When user hovers over the content area of the widget, make the heading text underline.
      $("#scrollable-widget-inner").hover(function() {
        $(this).css("cursor", "pointer").find("h3 a").css("text-decoration", "underline");
      }, function() {
        $(this).css("cursor", "auto").find("h3 a").css("text-decoration", "none");
      })

      // When user clicks in the content area of the widget, go to the linked page (linked under the h3)
      $(".scrollable-widget-content").click(function() {
        window.location = $(this).find("h3 a").attr("href");
      });

    } // end setUpScrollableWidget


    function setUpLeftNav() {

      // On Life Events pages, make sure last menu item does not have a bottom border (via a background image)
      $(".menu ul li:last a").css("background-image", "none");

      // On long pages, make sure first menu item does not have a bottom border (via a background image)
      $("#menu ul li:first a").css("background-image", "none");

    } // end setUpLeftNav



/* Multi Section Pages */

    function fadeSectionOutAndIn(divFadeOut, divFadeIn, currentLink, newLink, nextSectionButtonWrapper) {

      // Hide current div
      divFadeOut.customFadeOut("slow", function() {
        // Show chosen div
        divFadeIn.customFadeIn("slow", function() {
          currentLink.removeClass("current");
          newLink.addClass("current");
          if (newLink.hasClass("last")) {
            nextSectionButtonWrapper.customFadeOut(500);
          } else {
            nextSectionButtonWrapper.customFadeIn(500);
//            nextSectionButtonWrapper.find(".nextSectionButton").hide(); // Two step approach necessary for IE 6 & 7
          }
        });
      });
    } // end fadeSectionOutAndIn


    function setUpMultiSectionPage(contentDiv) {

      // Hide all divs inside div.multi-section-wrapper apart from the first one.
      // They should already be hidden by the :first-child selector in the CSS. Except for IE6.
      contentDiv.find("div.multi-section-wrapper > div").not(":first").hide();
      contentDiv.find("div.content").height(322);

      // If the content-inner has a 'multi-section-page' class, remove this class from the content-inner and add it to its parent div.content.
      // This class makes the div.content position:relative, so that the numeric navigation appears in the correct place.
      if (contentDiv.find("div.content-inner").hasClass("multi-section-page")) {
        contentDiv.find("div.content-inner").removeClass("multi-section-page");
        contentDiv.addClass("multi-section-page");
      }

      // Create numeric navigation links. One for each of the divs inside div.multi-section-wrapper
      var noOfDivs = contentDiv.find("div.multi-section-wrapper > div").length;

      if (noOfDivs > 0) {

        // Determine position of links. The links should be centered within the content area.
        var contentDivWidth = 731;
        var widthOfLi = 58;
        var widthOfAnchor = 42;
        var paddingOfLi = (widthOfLi - widthOfAnchor) / 2;
        var leftPosition = (contentDivWidth / 2) - ((widthOfLi / 2) * noOfDivs);
        var linkLeftPos;

        // Create HTML for multi section links
        var multiSectionLinksText = '<div class="multi-section-page-links" style="display: none; left:'  + leftPosition + 'px;"><ol>';
        var count = 1;
        contentDiv.find("div.multi-section-wrapper > div").each(function() {
          if (count == 1) {
            multiSectionLinksText += '<li class="first current"><a href="#' + $(this).attr("id") + '"><div class="multi-section-link-text"><span class="hide">Section </span>' + count + '<span class="hide"> of page</span></div></a></li>';
          } else {

            // linkLeftPos = ((count - 2) * (widthOfAnchor + paddingOfLi)) + widthOfAnchor;
            linkLeftPos = (count - 1) * widthOfAnchor;
            if (count == noOfDivs) {
              multiSectionLinksText += '<li class="last" style="left:' + linkLeftPos + 'px;"><a href="#' + $(this).attr("id") + '"><div class="multi-section-link-text"><span class="hide">Section </span>' + count + '<span class="hide"> of page</span></div></a></li>';
            } else {
              multiSectionLinksText += '<li style="left:' + linkLeftPos + 'px;"><a href="#' + $(this).attr("id") + '"><div class="multi-section-link-text"><span class="hide">Section </span>' + count + '<span class="hide"> of page</span></div></a></li>';
            }
          }
          count++;
        });
        multiSectionLinksText += '</ol></div>';

        // Before inserting into DOM, add HTML for the 'Next' button that appears on right side of content.
        multiSectionLinksText += '<div class="nextSectionButtonWrapper"><a class="nextSectionButton"></a></div>';

        // Insert into DOM
        contentDiv.find("div.content-inner").after(multiSectionLinksText);
        contentDiv.find("div.multi-section-page-links").customFadeIn(1000,function(){

          // Remove IE's background colour, added to make fading look nicer
          contentDiv.find("div.multi-section-page-links").css("background", "none");

        });

        // Add hover event to numeric navigation links. When hovering over the <a> tag, change the background image on the parent <li> tag
/*
        contentDiv.find("div.multi-section-page-links a").hover(
          function() {

            if ($(this).parent("li").hasClass("current")) {
              var cssObj = { 'color': '#f3f3f3' }
            } else {
              var cssObj = { 'color' : '#569cbe' }
            }

            $(this).css(cssObj);

          },
          function(){

            if ($(this).parent("li").hasClass("current")) {
              var cssObj = { 'color': '#f3f3f3' }
            } else {
              var cssObj = { 'color': '#868686' }
            }

            $(this).css(cssObj);
          });
*/

        // Add click events to numeric navigation links
        contentDiv.find("div.multi-section-page-links a").click(function() {

          // Hide current div and show new div
          var newDiv = $(this).attr("href");
          var hashLocation = newDiv.search("#");
          newDiv = newDiv.substring(hashLocation);
          var currentLink = contentDiv.find("div.multi-section-page-links li.current");
          var newLink = $(this).parent("li");
          fadeSectionOutAndIn(contentDiv.find("div.multi-section-wrapper > div:visible"), $(newDiv), currentLink, newLink, contentDiv.find(".nextSectionButtonWrapper"));

          // Change click event for 'Next' button

          contentDiv.find(".nextSectionButton").click(function() {
            currentLink.click();
          })

          return false;
        });

        // Add initial click event to 'Next' button
        contentDiv.find(".nextSectionButton").click(function() {
          var nextLinkLi = contentDiv.find("div.multi-section-page-links li.current").next();
          if (nextLinkLi.length) {
            nextLinkLi.find("a").click();
          }
        })

      }

    } // end setUpMultiSectionPage


/* Loading page sections dynamically */

    function rewriteNavLinks(menuAndContentDiv) {

      rewriteLinksPointingToCurrentSection(menuAndContentDiv, menuAndContentDiv.find("div.menu a"), true);

    } // end rewriteNavLinks


    function rewriteLinksPointingToCurrentSection(menuAndContentDiv, links, withinNav) {

      links.each(function() {

        $(this).click(function() {

          // If link is in left nav, remove the class current from the old 'current' link, and add it to this link.
          if (withinNav) {
            menuAndContentDiv.find(".menu ul li a").removeClass("current");
            // Add the class 'current' and remove the outline around the link (using blur).
            $(this).addClass("current").blur();
          }

          // Check if content div is already loaded
          var assetId = $(this).parent("li").find("span.asset-id").text();
          if ($("#content" + assetId).length) {
            var currentContentArea = menuAndContentDiv.find("div.content:visible");
            var newContentArea = menuAndContentDiv.find("#content" + assetId);
            if (firstViewOfPage(newContentArea)) {
              setUpMultiSectionPage(newContentArea);
            } else {
              // Always show the first page of a multi-page page when page is loaded
              newContentArea.find("div.multi-section-page-links ol li").removeClass("current");
              newContentArea.find("div.multi-section-page-links ol li.first").addClass("current");
            }
            fadeContentAreaOutAndIn(currentContentArea, newContentArea);
          }
          else {
            loadContentAreaAndRewriteLinks(menuAndContentDiv, $(this), true);
          }
          return false;
        });

      });

    } // end rewriteLinksPointingToCurrentSection


    function fadeContentAreaOutAndIn(divFadeOut, divFadeIn) {

      // Hide current div
      divFadeOut.customFadeOut("slow", function() {
        // Show chosen div
        divFadeIn.customFadeIn("slow", function() {
        });
      });
    } // end fadeContentAreaOutAndIn

    function firstViewOfPage(newContentArea) {

      // When a page has been viewed the first time by a user in this section, give the div.content a 'viewed' class
      if (newContentArea.hasClass("viewed")) {
        return false;
      } else {
        newContentArea.addClass("viewed");
        return true;
      }

    } // end firstViewOfPage


    function rewriteRelativeToAbsoluteLinks(contentDiv) {

      if (relativeLinks) {

        // The page URL that Matrix prints out has a trailing slash and no '.html' extension. e.g. www.publictrust.co.nz/life-events/becoming-a-family/
        // The actual URL being viewed will have no trailiing slash and does have an '.html' extension. e.g. www.publictrust.co.nz/life-events/becoming-a-family.html

        // We want to find base URL of the page currently being viewed. e.g. www.publictrust.co.nz/life-events/becoming-a-family/
        // That way we can replace the relative links in the content area with absolute links.

        // Get URL of actual page from a hidden span in the contentDiv
        var siteURL = contentDiv.find(".site-url").text();
        var baseURL = contentDiv.find(".page-url").text();

        // Remove Matrix domain from baseURL
        baseURL = baseURL.substring(siteURL.length);

        // Add current URL to baseURL
        var currentDomain = "http://" + window.location.hostname;
        baseURL = currentDomain + baseURL;

        // Strip off trailing slash if it exists
        if (baseURL.lastIndexOf('/') == baseURL.length - 1) {
          baseURL = baseURL.substring(0, baseURL.length - 1);
        }

        // Strip off the last directory in the URL. e.g. strip off 'becoming-a-family'
        baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);

        // Check each content area div and rewrite the href from relative to absolute URLs
        contentDiv.find("a").not("div.multi-section-page-links a, div.nextSectionButtonWrapper a").each(function(){

          var linkURL = $(this).attr("href");

          // If link is 'above' the page's URL, it will contain one or more "../" at the start of the URL
          if (linkURL.indexOf("../") > -1) {

            var noOfLevelsUp = 0;
            var dotDotSlashPos = 0;
            var tempLinkURL = linkURL;

            // Find how many "../" there are at the start of the link URL. Also strip them off.
            while (dotDotSlashPos > -1) {
              dotDotSlashPos = tempLinkURL.indexOf("../");
              if (dotDotSlashPos > -1) {
                tempLinkURL = tempLinkURL.substring(dotDotSlashPos + 3);
                noOfLevelsUp++;
              }
            }

            // Take the same number of levels off the end of the base URL
            var newLinkURL = baseURL;
            var levels = 0;

            // Trim trailing slash from link
            if (newLinkURL.lastIndexOf('/') == newLinkURL.length - 1) {
              newLinkURL = newLinkURL.substring(0, newLinkURL.length - 1)
            }

            while (levels < noOfLevelsUp) {
              newLinkURL = newLinkURL.substring(0, newLinkURL.lastIndexOf('/'));
              levels++;
            }

            newLinkURL += "/" + tempLinkURL;
          }
          else {

            // Link is at the same level as the current page or below it. We now add the baseURL to the linkURL to create the absolute URL.
            newLinkURL = baseURL + linkURL;
          }

          $(this).attr("href", newLinkURL);

        });
      }
    }


    function rewriteContentLinks(menuAndContentDiv, contentDiv) {

      // First, rewrite relative content area links to be absolute links
      rewriteRelativeToAbsoluteLinks(contentDiv);

      // Find URL of current Life Events section
      var currentSectionURL = menuAndContentDiv.find("div.menu a").attr("href");
      var slashPos = currentSectionURL.lastIndexOf("/");
      currentSectionURL = currentSectionURL.substring(0, slashPos + 1);

      // Check each content area link to see if it links to the current Life Events section or to another section. Also excluding pages using a long page template (these links have a 'long-page' class).
      contentDiv.find("a").not("div.multi-section-page-links a, div.nextSectionButtonWrapper a, a.long-page").each(function() {

        var linkHref = $(this).attr("href");

        // If link points within the current Life Events section, only load the content area of the page
        if (isLinkInCurrentSection(currentSectionURL, $(this))) {

          // Add hidden <span> within link, containing asset id of page that link points to
          var assetId = 0;
          menuAndContentDiv.find("div.menu a").each(function() {
            if ($(this).attr("href") == linkHref) {
              assetId = $(this).parent("li").find("span.asset-id").text();
            }
          });
          if (assetId > 0) {
            $(this).parent("li").prepend('<span class="asset-id">' + assetId + '</span>');
          }

          rewriteLinksPointingToCurrentSection(menuAndContentDiv, $(this), false);

        } else if (linkHref.indexOf("life-events") > 0) {
        // If link points to a different Life Events section, load the nav and the content of the page

          rewriteLinksPointingToDifferentSection($(this));

        } else {
        // If link points to page outside of Life Events section, the page will load normally (page reload). No code needed here.
        }

      });

    } // end rewriteContentLinks


    function rewriteLinksPointingToDifferentSection(links) {

      links.each(function() {

        $(this).click(function() {

          loadNavAndContentAreaAndRewriteLinks($(this));
          return false;
        });

      });

    } // rewriteLinksPointingToDifferentSection

    function isLinkInCurrentSection(currentSectionURL, link) {

      // Code generated by MySource Matrix contains fully qualified links. i.e. with the full domain name at the start of the URL.
      // When this code is exported to a static rip of the site, the links become relative to the current page (and so can contain ../../ etc).
      // This function copes with both scenarios.

      var currentDomain = "http://" + window.location.hostname;
      var linkHref = link.attr("href");

      // Check if the domain is part of the current section url. If it isn't, then we must be on the static rip where links are relative.
      if (currentSectionURL.indexOf(currentDomain) == -1) {

        // Relative links

        // If no slashes, then the link must be in the same section as the current page
        if (linkHref.indexOf('/') == -1) {
          return true;
        } else {
          return false;
        }

      } else {

        // Fully qualified links

        // If current domain is at the start of the links, remove it
        if (currentSectionURL.indexOf(currentDomain) > -1) {
          currentSectionURL = currentSectionURL.substring(currentDomain.length);
        }
        if (linkHref.indexOf(currentDomain) > -1) {
          linkHref = linkHref.substring(currentDomain.length);
        }

        // Find number of slashes in currentSectionURL
        var noOfSlashesInCurrentSectionURL = 0;
        var hrefTemp = currentSectionURL;
        var currentSectionURLSlashPos = 0;

        while (currentSectionURLSlashPos > -1) {
          currentSectionURLSlashPos = hrefTemp.indexOf("/");
          if (currentSectionURLSlashPos > -1) {
            hrefTemp = hrefTemp.substring(currentSectionURLSlashPos + 1);
            noOfSlashesInCurrentSectionURL++;
          }
        }

        // Find number of slashes in link
        var noOfSlashesInLink = 0;
        var hrefTemp = linkHref;
        var linkSlashPos = 0;

        while (linkSlashPos > -1) {
          linkSlashPos = hrefTemp.indexOf("/");
          if (linkSlashPos > -1) {
            hrefTemp = hrefTemp.substring(linkSlashPos + 1);
            noOfSlashesInLink++;
          }
        }

        // If current section URL has 1 or 2 slashes, the current section is the Life Events Top Level
        if (noOfSlashesInCurrentSectionURL < 3) {
          // If there are 1 or 2 slashes in the link URL, it also is in the Life Events Top Level
          if (noOfSlashesInLink < 3) {
            return true;
          } else {
            return false;
          }
        } else {
          // If there are 3 slashes in link URL and the current section URL forms part of the link URL, the link is in the same section
          if (linkHref.indexOf(currentSectionURL) == 0) {
            return true;
          } else {
            return false;
          }
        }
      }

    }  // end isLinkInCurrentSection

    function preloadCurrentSectionContentAreas(menuAndContentDiv) {

      // Go through all nav links and load each pages' content into a hidden div.content
      menuAndContentDiv.find("div.menu a").not(".current").each(function() {
        loadContentAreaAndRewriteLinks(menuAndContentDiv, $(this), false);
      })

    } // end preloadCurrentSectionContentAreas

    function loadContentAreaAndRewriteLinks(menuAndContentDiv, linkToLoad, fadeToNewDiv) {

      var assetId = linkToLoad.parent("li").find("span.asset-id").text();
      var contentBackground = linkToLoad.parent("li").find("span.asset-background").text();

      // Create div.content for new content to go into
      menuAndContentDiv.find("div.content-wrapper").append('<div class="content ' + contentBackground + '" id="content' + assetId + '" style="display: none;"></div>');

      // Load new div.content with content via AJAX
      var currentContentArea = menuAndContentDiv.find("div.content:visible");
      var newContentArea = menuAndContentDiv.find("#content" + assetId);
      var hrefToLoad = linkToLoad.attr("href");
      newContentArea.load(hrefToLoad + " div.content-inner", function() {
        rewriteContentLinks(menuAndContentDiv, newContentArea);
        if (fadeToNewDiv) {
          setUpMultiSectionPage(newContentArea);
          fadeContentAreaOutAndIn(currentContentArea, newContentArea);
        }
      });
    } // end loadContentAreaAndRewriteLinks


    function loadNavAndContentAreaAndRewriteLinks(link) {

      var hrefToLoad = link.attr("href");

      // Create temporary menu-and-content div for new nav and content to go into
      $("#menu-and-content-wrapper").append('<div class="temp-menu-and-content-wrapper style="display:none;"></div>');

      // Load new nav and content into temporary div
     $("#menu-and-content-wrapper div.temp-menu-and-content-wrapper").load(hrefToLoad + " div.menu-and-content", function() {
        $("#menu-and-content-wrapper div.temp-menu-and-content-wrapper div.menu-and-content").hide();
        var newHTML = $("#menu-and-content-wrapper div.temp-menu-and-content-wrapper").html();

        // Add new nav-and-content div into the wrapper
        $("#menu-and-content-wrapper").append(newHTML);

        // Remove the temporary div
        $("#menu-and-content-wrapper div.temp-menu-and-content-wrapper").remove();

        // Fade old nav and content out and fade the new one in. The old one is removed from the DOM.
        fadeNavAndContentAreaOutAndIn($("div.menu-and-content:visible"), $("div.menu-and-content:hidden"));
      });

    } // end loadNavAndContentAreaAndRewriteLinks



    function fadeNavAndContentAreaOutAndIn(divFadeOut, divFadeIn) {

      // Hide current div
      divFadeOut.customFadeOut("slow", function() {
        // Show chosen div
        divFadeIn.customFadeIn("slow", function() {
          divFadeOut.remove();
          setUpMultiSectionPage(divFadeIn.find("div.content"));
          rewriteNavLinks(divFadeIn);
          preloadCurrentSectionContentAreas(divFadeIn);
        });
      });
    } // end fadeNavAndContentAreaOutAndIn




    function rewriteLinksOutsideNavAndContent() {

      // If links point within the Life Events section, load the nav and content area only
      var links = $("a").not("div.menu a, div.content a").filter("a[href*='life-events'], a[href*='index.html'], a[href='/']").not("#personal-services-top-menu-anchor");
      rewriteLinksPointingToDifferentSection(links);

    } // end rewriteLinksOutsideNavAndContent



    function dynamicPageUpdates() {

      var cookieName = "dynamicPageUpdates";

      if ($.cookie(cookieName) == "no") {
        return false;
      } else {
        return true;
      }

    } // end dynamicPageUpdates



    function setDynamicPageUpdatesPreferences() {

      var cookieName = "dynamicPageUpdates";

      // When Accessibilty page loads, check the correct radio button for auto updating pages
      if ($.cookie(cookieName) == "yes") {
        $("form#change-dynamic-page-updates-prefs input.radio").attr("checked","");
        $("form#change-dynamic-page-updates-prefs input#updates-yes").attr("checked","checked");
      } else {

        // If 'No' is checked, then set it. Otherwise, leave the inputs unselected
        if ($.cookie(cookieName) == "no") {
          $("form#change-dynamic-page-updates-prefs input.radio").attr("checked","");
          $("form#change-dynamic-page-updates-prefs input#updates-no").attr("checked","checked");
        }
      }

      // If user chooses to not allow pages to automatically updates (e.g. via Ajax calls) then set a cookie.
      $("form#change-dynamic-page-updates-prefs").submit(function() {

        if ($("form#change-dynamic-page-updates-prefs input.radio:checked").val() == "0") {
          $.cookie(cookieName, 'no', { expires: 10000, path: '/' });
        } else {
          $.cookie(cookieName, 'yes', { expires: 10000, path: '/' });
        }

      });

      // If the page has reloaded after the user setting a preference, add some text to the start of the page
      var updatesQueryString = $(document).getUrlParam("updates");
      if (updatesQueryString != null) {

        var updatedText;
        if (updatesQueryString == "1") {
          updatedText = '<p class="highlight">Your preferences have been updated. Pages on this site will now update dynamically.</p>';
        } else {
          updatedText = '<p class="highlight">Your preferences have been updated. Pages on this site will now reload each time you click a link. They will not update dynamically.</p>';
        }
        $("#content-inner").find("h1:first").after(updatedText);

      }

    } // end of setDynamicPageUpdatesPreferences



    function setUpAppointmentFormValidation() {

      $("#make-an-appointment").validate({
  
        errorLabelContainer: "#form-errors ul",
        
        errorContainer: "#form-errors",

        wrapper: "li",

        rules: {
          title: {
            required: true
          },
          firstName: {
            required: true
          },
          lastName: {
            required: true
          },
          age: {
            required: true
          },
          streetAddress: {
            required: true
          },
          city: {
            required: true
          },
          homePhone: {
            required: true
          },
          email: {
            required: true,
            email: true
          },
          meetingDay: {
            required: true
          },
          meetingMonth: {
            required: true
          },
          meetingYear: {
            required: true
          },
          meetingTopic: {
            required: true
          },
          meetingOffice: {
            required: true
          }
        },
        
        messages: {

          title: "Please enter your title",
          firstName: "Please enter your first name",
          lastName: "Please enter your surname",
          age: "Please enter your age",
          streetAddress: "Please enter your street address",
          city: "Please enter your city",
          homePhone: "Please enter your home phone number",
          email: {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@domain.com"
          },
          meetingDay: "Please enter the day that you would like to meet",
          meetingMonth: "Please select the month that you would like to meet",
          meetingYear: "Please select the year that you would like to meet",
          meetingTopic: "Please select brief details of what you would like to meet about",
          meetingOffice: "Please select the Public Trust office you would like to meet at"
        }

      })


    } // end setUpAppointmentFormValidation



    function setUpRequestInfoFormValidation() {
    
      $("#request-info").validate({
  
        errorLabelContainer: "#form-errors ul",
        
        errorContainer: "#form-errors",

        wrapper: "li",

        rules: {
          title: {
            required: true
          },
          firstName: {
            required: true
          },
          lastName: {
            required: true
          },
          age: {
            required: true
          },
          streetAddress: {
            required: true
          },
          city: {
            required: true
          },
          homePhone: {
            required: true
          },
          email: {
            required: true,
            email: true
          },
          publicationRequired: {
            required: true
          }
        },
        
        messages: {

          title: "Please enter your title",
          firstName: "Please enter your first name",
          lastName: "Please enter your surname",
          age: "Please enter your age",
          streetAddress: "Please enter your street address",
          city: "Please enter your city",
          homePhone: "Please enter your home phone number",
          email: {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@domain.com"
          },
          publicationRequired: "Please enter the publication you would like to receive"
        }

      })
    
    } // end setUpRequestInfoFormValidation()

    function setUpContactCentreSelectBox() {
    
      // Only show the select box if dynamic updates are turned on (and doesn't work without Javascript)
      if (dynamicPageUpdates()) {
      
        // Show select box.
        $("#contact-centre-select-wrapper").show();
        
        // When user chooses an option, take the user to this anchor link.
        $("#contact-centre-select-button").click(function() {
        
          var anchorId = $("#contact-centre-select").find("option:selected").attr("value");
          if (anchorId != "0") {
            window.location.href = "http://" + location.host + location.pathname + "#" + anchorId;
          }
        
        });
      }
    } // end setUpContactCentreSelectBox



    function setUpOurTeamSelectBox() {
    
      // Only show the select box if dynamic updates are turned on (and doesn't work without Javascript)
      if (dynamicPageUpdates()) {
      
        // Show select box.
        $("#pt-team-select-wrapper").show();
        
        // When user chooses an option, take the user to this anchor link.
        $("#pt-team-select-button").click(function() {
        
          var anchorId = $("#pt-team-select").find("option:selected").attr("value");
          if (anchorId != "0") {
            window.location.href = "http://" + location.host + location.pathname + "#" + anchorId;
          }
        
        });
      }
    } // end setUpOurTeamSelectBox


    function addTableStriping() {

      // Add stripes to alternate rows
      $("#content table").each(function() {
        $(this).find("tr:odd").addClass("odd");
        $(this).find("tr:even").addClass("even");
      });

      // Make a different stripe appear when hovering over rows
      $("#content table tr").hover(function() {
        $(this).addClass("hover")
      }, function() {
        $(this).removeClass("hover");
      });

    } // end addTableStriping()



    function familyTrustCalculators() {
    
      $("#calculate").click(function() {

        var age = 0;
        var business = 0;
        var home = 0;
        var assets = 0;

        if ($("#age").length) {
          age = Number($("#age").attr("value"));
        }
        if ($("#business").length) {
          business = Number($("#business").attr("value"));
        }
        if ($("#home").length) {
          home = Number($("#home").attr("value"));
        }
        if ($("#assets").length) {
          assets = Number($("#assets").attr("value"));
        }

        var totalAssets = business + home + assets;
        var years = (Math.round((totalAssets/27000) + 0.5) - 1 + 5);
        var ageNow = age + years;
        var age5 = age + (Math.round(((totalAssets * Math.pow(1.05, 5))/27000) + 0.5) - 1 + 10);
        var years5 = age5 - ageNow;

        var additionalHTML = '<h2>Results</h2><p>Based on your current age, the value of the assets you want to put into a family trust, it will take you ' + years + ' years to protect all of your assets with a family trust and you will be ' + ageNow + ' years old.</p><p>Wait another five years and it would take you an extra ' + years5 + ' years and you will be ' + age5 + ' years old.</p>';
        
        // Add results text
        $("#results").html(additionalHTML);
        
        // Show results and other text
        $("#results-wrapper").slideDown();
  
        return false;

      });

    }; // end familyTrustCalculators


    function setGNZSDefaultValues() {

      $("#firstName").DefaultValue("First name");
      $("#lastName").DefaultValue("Last name");
      $("#email").DefaultValue("Email");
      $("#phone").DefaultValue("Phone");

    } // end setGNZSDefaultValues


    function setFamilyPromiseDefaultValues() {

      $("#firstName").DefaultValue("First name");
      $("#lastName").DefaultValue("Last name");
      $("#email").DefaultValue("Email");
      $("#phone").DefaultValue("Phone");

    } // end setFamilyPromiseDefaultValues

/* Checks for data in form fields - no type validation (email etc) */
function basicValidator(){

	$('#request-info #submit').attr("disabled", "disabled");
	
	$('#request-info .required input').each(function(){
		$(this).addClass('iv');	
	})
	
	function inputHandler($this, defaultValue) {
		
		$this.focus(function(){
			if($this.attr('value') == defaultValue){
				$this.attr('value', "")
			}
		})
		
	
		$this.blur(function(){
			
			if($this.attr('value') == "" || $(this).attr('value') == defaultValue) {
				$this.attr('value') = defaultValue;
                                $this.addClass('iv');
                                $('#request-info #submit').attr("disabled", "disabled");
			}
			
		})
		
		$this.keyup(function(){
	
			$this.removeClass('iv');
			if($('#request-info .required input.iv').length == 0){
				$('#request-info #submit').removeAttr("disabled");
			}
	                if($this.attr('value') == "" || $(this).attr('value') == defaultValue) {
                                $this.addClass('iv');
                                $('#request-info #submit').attr("disabled", "disabled");
			}
		})
		
	}
	
	$('#request-info .required input').each(function(){
		inputHandler($(this), $(this).attr('value'))
	})

}

if ($("body#id29503, body#id29061, body#id29507").length) {
     basicValidator();
     $("#family-promise-slideshow")
    .append('<img src="/__data/assets/image/0019/26821/FPLanding3.jpg" alt="His life has very little past, but plenty of future to look forward to. " />')
    .append('<img src="/__data/assets/image/0003/26823/FPLanding2.jpg" alt="We are no longer just a couple, we are a new family, with new responsibilities. " />')
    .append('<img src="/__data/assets/image/0004/26842/Page-4-Image-and-text.jpg" alt="Of course we knew she would change our lives, we just didnt know how much.  " />')
    .cycle({
        timeout: 10000,
        pause: 1
    })
}

  });
})(jQuery);


/* Cycle plugin for Family Promise landing pages */

(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery)