/*
 * jQuery Tools 1.2.5 - The missing UI library for the Web
 * 
 * [tooltip, tooltip.slide, tooltip.dynamic]
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 * File generated: Wed Jan 12 16:49:28 GMT 2011
 */
(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,d=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];d+=a.outerWidth()+c.offset[1];if(/iPad/i.test(navigator.userAgent))h-=f(window).scrollTop();var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")d-=a/2;if(i=="left")d-=a;return{top:h,left:d}}function u(a,b){var c=this,h=a.add(c),d,i=0,j=
0,m=a.attr("title"),q=a.attr("data-tooltip"),r=o[b.effect],l,s=a.is(":input"),v=s&&a.is(":checkbox, :radio, select, :button, :submit"),t=a.attr("type"),k=b.events[t]||b.events[s?v?"widget":"input":"def"];if(!r)throw'Nonexistent effect "'+b.effect+'"';k=k.split(/,\s*/);if(k.length!=2)throw"Tooltip: bad events configuration for "+t;a.bind(k[0],function(e){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(e)},b.predelay);else c.show(e)}).bind(k[1],function(e){clearTimeout(j);if(b.delay)i=
setTimeout(function(){c.hide(e)},b.delay);else c.hide(e)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(e){if(!d){if(q)d=f(q);else if(b.tip)d=f(b.tip).eq(0);else if(m)d=f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else{d=a.next();d.length||(d=a.parent().next())}if(!d.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;d.stop(true,true);var g=p(a,d,b);b.tip&&d.html(a.data("title"));e=e||f.Event();e.type="onBeforeShow";
h.trigger(e,[g]);if(e.isDefaultPrevented())return c;g=p(a,d,b);d.css({position:"absolute",top:g.top,left:g.left});l=true;r[0].call(c,function(){e.type="onShow";l="full";h.trigger(e)});g=b.events.tooltip.split(/,\s*/);if(!d.data("__set")){d.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&d.bind(g[1],function(n){n.relatedTarget!=a[0]&&a.trigger(k[1].split(" ")[0])});d.data("__set",true)}return c},hide:function(e){if(!d||!c.isShown())return c;
e=e||f.Event();e.type="onBeforeHide";h.trigger(e);if(!e.isDefaultPrevented()){l=false;o[b.effect][1].call(c,function(){e.type="onHide";h.trigger(e)});return c}},isShown:function(e){return e?l=="full":l},getConf:function(){return b},getTip:function(){return d},getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(e,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(n){n&&f(c).bind(g,n);return c}})}f.tools=f.tools||{version:"1.2.5"};f.tools.tooltip=
{conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,b,c){o[a]=[b,c]}};var o={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide();
a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new u(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery);
(function(d){var i=d.tools.tooltip;d.extend(i.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!d.browser.msie});var e={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};i.addEffect("slide",function(g){var a=this.getConf(),f=this.getTip(),b=a.slideFade?{opacity:a.opacity}:{},c=e[a.direction]||e.up;b[c[1]]=c[0]+"="+a.slideOffset;a.slideFade&&f.css({opacity:0});f.show().animate(b,a.slideInSpeed,g)},function(g){var a=this.getConf(),f=a.slideOffset,
b=a.slideFade?{opacity:0}:{},c=e[a.direction]||e.up,h=""+c[0];if(a.bounce)h=h=="+"?"-":"+";b[c[1]]=h+"="+f;this.getTip().animate(b,a.slideOutSpeed,function(){d(this).hide();g.call()})})})(jQuery);
(function(g){function j(a){var c=g(window),d=c.width()+c.scrollLeft(),h=c.height()+c.scrollTop();return[a.offset().top<=c.scrollTop(),d<=a.offset().left+a.width(),h<=a.offset().top+a.height(),c.scrollLeft()>=a.offset().left]}function k(a){for(var c=a.length;c--;)if(a[c])return false;return true}var i=g.tools.tooltip;i.dynamic={conf:{classNames:"top right bottom left"}};g.fn.dynamic=function(a){if(typeof a=="number")a={speed:a};a=g.extend({},i.dynamic.conf,a);var c=a.classNames.split(/\s/),d;this.each(function(){var h=
g(this).tooltip().onBeforeShow(function(e,f){e=this.getTip();var b=this.getConf();d||(d=[b.position[0],b.position[1],b.offset[0],b.offset[1],g.extend({},b)]);g.extend(b,d[4]);b.position=[d[0],d[1]];b.offset=[d[2],d[3]];e.css({visibility:"hidden",position:"absolute",top:f.top,left:f.left}).show();f=j(e);if(!k(f)){if(f[2]){g.extend(b,a.top);b.position[0]="top";e.addClass(c[0])}if(f[3]){g.extend(b,a.right);b.position[1]="right";e.addClass(c[1])}if(f[0]){g.extend(b,a.bottom);b.position[0]="bottom";e.addClass(c[2])}if(f[1]){g.extend(b,
a.left);b.position[1]="left";e.addClass(c[3])}if(f[0]||f[2])b.offset[0]*=-1;if(f[1]||f[3])b.offset[1]*=-1}e.css({visibility:"visible"}).hide()});h.onBeforeShow(function(){var e=this.getConf();this.getTip();setTimeout(function(){e.position=[d[0],d[1]];e.offset=[d[2],d[3]]},0)});h.onHide(function(){var e=this.getTip();e.removeClass(a.classNames)});ret=h});return a.api?ret:this}})(jQuery);
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/**
 * @author Terry Wooton
 * @desc Adds a background layer to an element
 * @version 1.1
 * @example
 * $("#element").add_background("url('/test.gif') bottom left no-repeat");
 * @license free
 * @param background css
 *
 */
jQuery(function($) {
    $(document).ready(function() {
      $.fn.add_layer = function(bg,params) {
        $(this).each(function() {
  
          s = $(this).extend({},params || {});      
      
          $last = ($(this).find('.add_background:last').length > 0 ? $(this).find('.add_background:last') : $(this));
      		$last.html('<div class="add_background"><div>'+$last.html()+'</div></div>');
      		$last = $(this).find('.add_background:last');
      		$last.css({'background':bg,'width':'100%','height':'100%'});

          $last = $(this).find('.add_background div:last');
            
          if(s.insideCss){
       		  $last.css(s.insideCss);
      		}
          if(s.insideClass)
      		  $last.addClass(s.insideClass);  		  
        });
      }      
    });
});
// VERTICALLY ALIGN FUNCTION
(function ($) {
$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = (ph - ah) / 2;
	$(this).css('margin-top', mh);
	});
};
})(jQuery);
/**
 * jQuery Initial input value replacer
 * 
 * Sets input value attribute to a starting value  
 * @author Marco "DWJ" Solazzi - hello@dwightjack.com
 * @license  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * @copyright Copyright (c) 2008 Marco Solazzi
 * @version 0.1
 * @requires jQuery 1.2.x
 */
(function (jQuery) {
  /**
   * Setting input initialization
   *  
   * @param {String|Object|Bool} text Initial value of the field. Can be either a string, a jQuery reference (example: $("#element")), or boolean false (default) to search for related label
   * @param {Object} [opts] An object containing options: 
   *              color (initial text color, default : "#666"), 
   *              e (event which triggers initial text clearing, default: "focus"), 
   *              force (execute this script even if input value is not empty, default: false)
   *              keep (if value of field is empty on blur, re-apply initial text, default: true)  
   */
  jQuery.fn.inputLabel = function(text,opts) {
    o = jQuery.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
    var clearInput = function (e) {
      var target = jQuery(e.target);
      var value = jQuery.trim(target.val());
      if (e.type == e.data.obj.e && value == e.data.obj.innerText) {
        jQuery(target).css("color", "").val("");
        if (!e.data.obj.keep) {
          jQuery(target).unbind(e.data.obj.e+" blur",clearInput);
        }
      } else if (e.type == "blur" && value == "" && e.data.obj.keep) {
        jQuery(this).css("color", e.data.obj.color).val(e.data.obj.innerText);
      }
    };
    return this.each(function () {
          o.innerText = (text || false);
          if (!o.innerText) {
            var id = jQuery(this).attr("id");
            o.innerText = jQuery(this).parents("form").find("label[for=" + id + "]").hide().text();
          }
          else 
            if (typeof o.innerText != "string") {
              o.innerText = jQuery(o.innerText).text();
            }
      o.innerText = jQuery.trim(o.innerText);
      if (o.force || jQuery(this).val() == "") {
        jQuery(this).css("color", o.color).val(o.innerText);
      }
        jQuery(this).bind(o.e+" blur",{obj:o},clearInput);
      
    });
  };
})(jQuery);
// ################################################################################
// Variables detecting certain browsers
//
var ie = jq.browser.msie;
var ie6 = ie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);
var ie7 = ie && /MSIE 7\.0/i.test(window.navigator.userAgent);
var lteie7 = ie6 || ie7;

var mozilla = jq.browser.mozilla;
var safari = jq.browser.safari;
var opera = jq.browser.opera;
var ltefirefox2 = mozilla && parseFloat(jq.browser.version) < 1.9;

// ################################################################################
// The jQuery document ready function
//
jq(document).ready(function($){

  $('html').addClass('js');

  // Removing nowrap in Live Search that seems to have been inserted deliberately for some reason
  $('#livesearch0').removeAttr('style');

   /*
   * ie selector helpers
   */
  if (ie6) {
    
    // The search button is not positioning itself properly so hiding it until the page has been drawn
    //$('#search .submit-wrapper').hide();
    
    // first children
    $('.search-form .search-advanced .criterion:first').addClass('criterion-first');
    $('ul:first-child,' +
      'ol:first-child,' +
      'li:first-child,' +
      '.search-form .search-advanced .criterion:first .form-item:first-child, ' +
      '.portlet:first-child, ' +
      '#sidebar-two .callout p:first-child, ' +
      '.homepage .collage-column:first-child, ' + 
      '.homepage #features .story:first, ' + 
      '.homepage #features p:first-child'
    ).addClass('first');
    



    // form controls
    $('input:text').addClass('text');
    $('input:password').addClass('password');
    $('input:radio').addClass('radio');
    $('input:checkbox').addClass('checkbox');
    $('input:submit').addClass('submit');
    $('input:reset').addClass('reset');
    $('input:button').addClass('button');
    
    // child selectors
    $('.search-form > div > .form-item').addClass('search-normal');
    $('#page-tools > ul').addClass('utilities');
    $('#page-tools > ul > li').addClass('item');
    $('#page-tools > ul > li:last-child').addClass('lastitem');
    
    // attribute selectors
    $('span[lang]').addClass('lang');
    
    // adjacent selectors
    $('#related-items + #related-downloads').addClass('adjacent');
    
    //image INPUTs change to gif
    $('input:image').each(function(){
      var img = $(this);
      var imgSrc = img.attr('src');
      imgSrc = imgSrc.replace('.png', '.gif');
      img.attr('src', imgSrc);
    });
    
    // Now we can show the search button
    //$('#search .submit-wrapper').show();
  }
  
  if (lteie7) {
  
    // Putting answer prefix into first answer paragraph in FAQs
    $('#faqs .tileBody').each(function(){
      var item = $(this);
      var pref = item.find('.faq-answer-prefix');
      var prefText = pref.text();
      var prefClass = pref.attr('class');
      var first = item.find('p:first');
      $('<span/>')
        .addClass(prefClass)
        .text(prefText)
        .prependTo(first);
      pref.remove();
    });
  }
  
  if (ie) {
    $('li:last-child, ' +
      'dd:last-child, ' +
      '.homepage #intro .text p:last-child').addClass('last');
    $('.search-form .search-advanced .criterion:first').addClass('first');
    $('table tr:nth-child(even), #sidebar-two .callout:nth-child(even)').addClass('even');
    $('#sidebar-two .callout:nth-child(odd)').addClass('odd');

    // Pager
    // - extra markup to aid simulating rounded corners in IE
    $('.pager > ul > li > span').addClass('inner').wrap('<span class="outer"/>');
    $('.pager > ul > li > a').wrapInner('<span class="inner"/>');
    // - 'last' class added above not needed on pager list items
    $('.pager li:last-child').removeClass('last');

  }

    
  // js moves label from above input to on top of it; 
  $('#searchGadget').inputLabel(false, {color: "#666666"});

  // Text sizing and colour contrast
  $(document).textSizeAndColourContrast();

  // print link
  $('<li id="print"></li>').prependTo('#page-tools > ul');
  $('<a/>')
    .attr({href: '#print'})
    .text('Print')
    .click(function(e){
      e.preventDefault();
      window.print();
    })
    .appendTo('#print');

  if (ie6) {
    $('#page-tools > ul > li').addClass('item');
  }
  
  $('#LSResult').css({display: 'none'});
  
  // Secondary navigation tweaks
  var currNode = $('#section-navigation li.navTreeCurrentNode');
  if (currNode.children().is('ul')) {
    currNode.addClass('navTreeCurrentNodeWithChildren');
  }
  else {
    currNode.addClass('navTreeCurrentNodeNoChildren');
  }
  
  // IE6 setup for secondary nav
  $('#section-navigation li.navTreeCurrentNodeNoChildren > div > a.navTreeCurrentItem').addClass('navTreeCurrentItemNoChildren');
  

  // Fancy scrolling

  // top link scroll
  $('#top-link > a').click(function(e){
    e.preventDefault();
    $.scrollTo(0, 1000);
  });

  // FAQ pages
  // scroll back to toc
  $('#faqs .back-to-top a').click(function(e){
    e.preventDefault();
    $.scrollTo($('#table-of-contents'), 1000);
  });

  // scroll to target from toc
  $('#faqs #table-of-contents a').click(function(e){
    e.preventDefault();
    var item = $(this);
    var href = item.attr('href');
    var x = href.split('#');
    var target = '#' + x[1];
    $.scrollTo(target, 1000);
  });

  // Workaround: readd newlines removed by lxml after <input> tags
  $('input').after('\n');

  // Homepage navigation tooltips
  $('.homepage #primary-navigation li a').each(function(){
    var item = $(this);
    var text = item.attr('title');
    item.removeAttr('title'); // leaving title attribute causes plugin to fire the default
    var locId = item.parent().attr('id');
    var tipId = locId.replace('portaltab-', 'tip-');
    var tipHtml = $('<div class="tooltip" id="' + tipId + '"><div class="body">' + text + '</div></div>');
    tipHtml.insertAfter('#page').hide();
    item.tooltip({
      effect: 'slide',
      bounce: true,
      tip: '#' + tipId, 
      offset: [-5, 0],
      predelay: 500
    });
  });

  // Map popup tooltips
  initMapToolTips($);

  if (ie6) {
    $('#search .submit-wrapper').hide(1, function(){
      $('#search .submit-wrapper').show(1);
    });
  }

});


// ################################################################################
// Map popups function
//

function initMapToolTips($) {
  //if (!($('.template-contact-us').length)) return;
  
  var offsets = {
      'Northland': { 'Y': 22, 'X': -37 },
      'West and North Auckland': { 'Y': 8, 'X': 66 },
      'Central Auckland': { 'Y': 10, 'X': 52 },
      'East Auckland': { 'Y': 10, 'X': 47 },
      'South Auckland': { 'Y': 11, 'X': 48 },
      'Waikato, Coromandel, King Country': { 'Y': 21, 'X': -4 },
      'Bay of Plenty': { 'Y': 11, 'X': -5 },
      'East Cape, Hawkes Bay': { 'Y': 11, 'X': -75 },
      'Manawatu, Taranaki, Wairarapa': { 'Y': 15, 'X': -1 },
      'Wellington, Hutt Valley': { 'Y': 7, 'X': -14 },
      'Christchurch, Nelson, Marlborough': { 'Y': 34, 'X': -7 },
      'Southern': { 'Y': 28, 'X': 39 }
  };
  
  $('#region-map ul.map-links li a').each(function(){
    var item = $(this);
    var text = item.text();
    var href = item.attr('href');
    var locId = item.parent().attr('id');
    var labelId = locId.replace('map-region-', 'label-');
    var labelHtml = $('<div class="tooltip" id="' + labelId + '"><a href="' + href + '">' + text + '</a>');
    labelHtml.insertAfter('#page').hide();
    // offset the tooltip for each area
    var offsetY, offsetX;
    offsetY = offsets[text].Y;
    offsetX = offsets[text].X;

    item.tooltip({
      tip: '#' + labelId, 
      offset: [offsetY, offsetX],
      predelay: 500
    });
  });
  
  var regions = $('#region-map ul.map-links li a, .template-contact-us .tooltip a');
  
  $('#region-map ul.map-links li a, .template-contact-us .tooltip a').click(function(e){
    e.preventDefault();
    var selReg = $(this);
    var selRegVal = regions.index(selReg);
    // convert tooltip value to same as map value
    var x = regions.length;
    var y = x/2-1;
    var z = x-1;
    if (selRegVal > y) {
      selRegVal = selRegVal-(2*selRegVal-z);
    }
    // change selection
    $('#contact-region option').eq(selRegVal+1).attr({selected: 'selected'});
  });
}


// ################################################################################
// Text size and colour contrast function
//

(function($) {

$.fn.textSizeAndColourContrast = function() {

    // Switch text size and colour contrast stylesheets per user preference.

    var selected_contrast_mode = $.cookie('hnzcContrast') || 'normal';
    var selected_text_mode     = $.cookie('hnzcTextMode') || 'regular';

    var text_sizes = ['small', 'regular', 'large'];

    // Define the set of available text size stylesheets per mode
    var text_stylesheets = {
        normal: {
            small:   "text-size-small.css",
            regular: "text-size-regular.css",
            large:   "text-size-large.css"
        },
        highcontrast: {
            small:   "high-contrast-text-size-small.css",
            regular: "high-contrast-text-size-regular.css",
            large:   "high-contrast-text-size-large.css"
        }
    };

    var cookie_options = { expires: 365, path: '/' };

    var colourContrast = function() {

        var normal_stylesheets = [];

        var node = function() {

            // Returns a DOM node for the colour contrast widget

            var node = $('<div id="high-contrast">'
                         + '<p>This website can be viewed in two colour variations:</p>'
                         + '<ul>'
                         +   '<li>normal contrast</li>'
                         +   '<li>high contrast &mdash; white text on a black background</li>'
                         + '</ul>'
                         + '</div>');
            $('li:eq(0)', node).attr({id: 'high-contrast-mode-normal'});
            $('li:eq(1)', node).attr({id: 'high-contrast-mode-highcontrast'});
            $('li:not(#high-contrast-mode-' + selected_contrast_mode + ')',
               node).wrapInner('<a href="#" />');
            $('a', node).click(function(e) {
                e.preventDefault();
                // Toggle
                selected_contrast_mode =
                  selected_contrast_mode === 'normal' ? 'highcontrast' : 'normal';
                update();
            });
            return node;
        };

        var sheetswitch = function() {

            // Switch to the right set of stylesheets

            var i, s, node, size;

            // Disable or enable the usual stylesheets, as appropriate for this mode
            for (i in normal_stylesheets) {
                s = normal_stylesheets[i];
                s.disabled = selected_contrast_mode === 'highcontrast' ? true : false;
            }

            // Add or remove the high contrast stylesheets
            if (selected_contrast_mode === 'highcontrast') {
                var stylesheets = ['hnzc-high-contrast.css'];

                if ($.browser.msie) {
                    switch (parseInt($.browser.version, 10)) {
                        case 6:
                            stylesheets.push('hnzc-high-contrast-ie6.css');
                            break;
                        case 7:
                            stylesheets.push('hnzc-high-contrast-ie7.css');
                            break;
                        case 8:
                            stylesheets.push('hnzc-high-contrast-ie8.css');
                            break;
                    }
                }

                for (i = 0; i < stylesheets.length; i++) {
                    s = stylesheets[i];
                    $('<link rel="stylesheet" type="text/css"'
                      + ' href="/static/styles/' + s
                      + '" media="screen, projection" />').appendTo('head');
                }
            }
            else if (selected_contrast_mode === 'normal') {
                $('link[href*=hnzc-high-contrast]').remove();
            }

            // Add the appropriate text sizing stylesheets
            $('link[href*=text-size]').remove();
            for (i = 0; i < text_sizes.length; i++) {
                size = text_sizes[i];
                // Note: IE8 breaks if rel and href attributes are added after
                //       creating the node, so we don't do that.
                node = $('<link type="text/css"'
                         + ' media="screen, projection"'
                         + ' href="/static/styles/'
                         + text_stylesheets[selected_contrast_mode][size]
                         + '" rel="' + (size === 'regular' ? '' : 'alternate ')
                         + 'stylesheet"'
                         + '/>');
                $(node).attr('title', size + ' text');
                node.insertAfter('link[media$=projection]:last');
            }

            // Activate the right text size stylesheet
            $('#font-size .absolute li#font-size-' + selected_text_mode + ' a')
                .triggerHandler('click');
        };

        var update = function() {

            // Called by high contrast mode switch event handler.

            // Replace the widget
            var widget = node();
            $('body.section-accessibility #high-contrast').replaceWith(widget);

            // Change the active set of stylesheets
            sheetswitch();

            // Write cookie
            $.cookie('hnzcContrast', selected_contrast_mode, cookie_options);
        };

        // Save list of normal stylesheets so that they can be toggled
        $('link').each(
            function(i) {
                normal_stylesheets.push(this);
            }
        );

        node().insertBefore('body.section-accessibility #content #parent-fieldname-text');
        sheetswitch();

    }();

    var textSizing = function() {

        var node = function() {

            // Return a DOM node for the text sizing widget. The
            // resulting markup reflects the currently selected text
            // mode.

            // The basic idea is that whenever selected_text_mode
            // changes we recreate the text widget node to reflect the
            // new state.

            var size_data = {
                relative: {
                    smaller: { name: "Smaller" },
                    larger:  { name: "Larger" }
                },
                absolute: {
                    small:   { name: "Small",   href: "B" },
                    regular: { name: "Regular", href: "A" },
                    large:   { name: "Large",   href: "C" }
                }
            };

            var size, move, i, linkcontent;

            // Build the basic node
            var node = $('<li id="font-size"><span class="hide">Text size</span>'
                         + '<ul class="relative"></ul>'
                         + '<ul class="absolute"></ul>'
                         + '</li>');

            // Build list elements
            for (size in size_data.relative) {
                var s = size_data.relative[size];
                s.node = $(
                    '<li><a href="#">' + s.name
                    + '<span class="hide"> font size</span></a></li>');
                $(s.node).attr({id: 'font-size-'+size});
                $('a', s.node).attr({title: s.name});
            }

            for (size in size_data.absolute) {
                var s = size_data.absolute[size];
                s.node = $(
                    '<li><a class="replace"><span class="img"></span>'
                        + s.name + ' font size</a></li>');
                $(s.node).attr({id: 'font-size-'+size});
                $('a', s.node).attr({
                  href: '#' + s.href,
                  rel:  size + ' text',
                  title: s.name + ' font size'
                });
            }

            // Add the list element nodes into the main node
            var addListItemNodes = function(sizetype, sizes, node) {
                var selector = 'ul.' + sizetype;
                for (var i = 0; i < sizes.length; i++) {
                    $(selector, node).append(size_data[sizetype][sizes[i]].node);
                }
            };
            addListItemNodes('relative', ['smaller', 'larger'], node);
            addListItemNodes('absolute', text_sizes, node);

            // Add mouse click event handlers
            $('.absolute li a', node).click(function(e) {
                // Absolute resize link clicks
                e.preventDefault();
                size = this.parentNode.id.slice('font-size-'.length);
                if (size in size_data.absolute) {
                    selected_text_mode = size;
                }
                update();
            });
            $('.relative li a', node).click(function(e) {
                // Relative resize link clicks
                e.preventDefault();
                move = this.parentNode.id.slice('font-size-'.length);
                if (move in size_data.relative) {
                    i = $.inArray(selected_text_mode, text_sizes);
                    if (move === 'smaller' && i > 0
                          && text_sizes[i-1] !== undefined) {
                        selected_text_mode = text_sizes[i-1];
                    }
                    else if (move === 'larger' && i < text_sizes.length-1
                          && text_sizes[i+1] !== undefined) {
                        selected_text_mode = text_sizes[i+1];
                    }
                }
                update();
            });

            // Make changes for the current text mode
            switch (selected_text_mode) {
                case "regular":
                    $('li#font-size-regular a', node).addClass('selected');
                    break;
                case "small":
                    $('li#font-size-small a', node).addClass('selected');
                    $('li#font-size-smaller', node).addClass('inactive');
                    linkcontent = $('li#font-size-smaller a', node).contents();
                    $('li#font-size-smaller a', node).replaceWith(linkcontent);
                    break;
                case "large":
                    $('li#font-size-large a', node).addClass('selected');
                    $('li#font-size-larger', node).addClass('inactive');
                    linkcontent = $('li#font-size-larger a', node).contents();
                    $('li#font-size-larger a', node).replaceWith(linkcontent);
                    break;
            }
            return node;
        };

        var sheetswitch = function() {

            // Switch to the right font size stylesheet.
            // The DOM will contain the set of stylesheets for
            // whichever high contrast mode we're in. Whichever one we
            // want should be enabled, the others disabled.

            $('link[title$=" text"][title]').each(
                function(i) {
                    this.disabled = true;
                    if (this.getAttribute('title') === selected_text_mode + ' text') {
                        this.disabled = false;
                    }
                }
            );

        };

        var update = function() {

            // Called by text resizing widget event handlers.

            // Replace the widget
            var widget = node();
            $('#page-tools li#font-size').replaceWith(widget);

            // Change the active stylesheet
            sheetswitch();

            // Write cookie
            $.cookie('hnzcTextMode', selected_text_mode, cookie_options);
        };

        node().prependTo('#page-tools > ul');
        sheetswitch();

    }();

};

})(jQuery);

