﻿var ACC = {
	init: function() {
		ACC.browserFixes();
		ACC.Text.init();
		ACC.customFonts();
		ACC.roundCorners();
		ACC.setupSearchBox();
		ACC.Glossary.init();
	},
		
	customFonts: function() {
		var dollyRatios = [7, 1.46, 12, 1.35, 21, 1.3, 27, 1.26, 31, 1.27, 32, 1.25, 36, 1.26, 37, 1.24, 38, 1.25, 41, 1.24, 42, 1.25, 57, 1.24, 60, 1.23, 61, 1.24, 69, 1.23, 70, 1.24, 101, 1.23, 102, 1.22, 105, 1.23, 107, 1.22, 108, 1.23, 109, 1.22, 110, 1.23, 111, 1.22, 113, 1.23, 116, 1.22, 117, 1.23, 118, 1.22, 119, 1.23, 121, 1.22, 122, 1.23, 1.22];
		
		switch ($(document.body).id) {
			case 'home':
			
				sIFR.replace(dollyBold, { 
					selector: '#intro h1',	
					css: '.sIFR-root { color: #FFFFFF; }', 
					tuneHeight: -5,  
					wmode: 'transparent', 
					ratios: dollyRatios 
				});
			
				sIFR.replace(dollyBold, { 
					selector: '#banner h3',	
					css: '.sIFR-root { color: #FFFFFF; }', 
					tuneHeight: -5,  
					wmode: 'transparent', 
					ratios: dollyRatios 
				});
				
				sIFR.replace(dollyBold, { 
					selector: '#home .corners h3',	
					css: '.sIFR-root { color: #444444; } .sIFR-root a { color: #006699; text-decoration: none; } .sIFR-root a:hover { color: #006699; text-decoration: underline; }', 
					tuneHeight: -5,
					wmode: 'transparent',
					ratios: dollyRatios 
				});		

			break;			
			
			case 'level2':
			
				sIFR.replace(dollyBold, { 
					selector: '#level2 #content .corners h3',	
					css: '.sIFR-root { color: #444444; } .sIFR-root a { color: #006699; text-decoration: none; } .sIFR-root a:hover { color: #006699; text-decoration: underline; }', 
					tuneHeight: -5, 
					wmode: 'transparent',
					ratios: dollyRatios 
				});
				
				sIFR.replace(dollyRoman, { 
					selector: '#level2 .section h3',	
					css: '.sIFR-root { color: #444444; } .sIFR-root a { color: #006699; text-decoration: none; } .sIFR-root a:hover { color: #006699; text-decoration: underline; }', 
					tuneHeight: -5, 
					wmode: 'transparent',
					ratios: dollyRatios 
				});
			/* No 'break' as we want to fall through and also do the default replacements */
			default:
			
				sIFR.replace(dollyBold, { 
					selector: '#informe h3',	
					css: '.sIFR-root { color: #000; }', 
					tuneHeight: -5,  
					wmode: 'transparent', 
					ratios: dollyRatios 
				});
			
				sIFR.replace(dollyBold, { 
					selector: '#main h1',	
					css: '.sIFR-root { color: #222222; }', 
					tuneHeight: -5, 
					opaque: 'false', 
					ratios: dollyRatios 
				});
								
				sIFR.replace(dollyBold, { 
					selector: '#level3-intro h3',	
					css: '.sIFR-root { color: #444444; } .sIFR-root a { color: #006699; text-decoration: none; } .sIFR-root a:hover { color: #006699; text-decoration: underline; }', 
					tuneHeight: -5,
					wmode: 'transparent',
					ratios: dollyRatios
				});
		}
	}, 
	
	roundCorners: function() {
		var tr, tl, br, bl;
		tr = '<span class="inject tr"></span>';
		tl = '<span class="inject tl"></span>';
		br = '<span class="inject br"></span>';
		bl = '<span class="inject bl"></span>';
				
		$$('#header').invoke('insert', { top: tr });	
		$$('#primary-nav a').invoke('insert', { top: tr + tl } );			
		var corners = new Template('<div class="content"><div class="t"></div> #{innerHTML} </div><div class="b"><div>&nbsp;</div></div>');		
		$$('.corners').each(function(el) { el.update(corners.evaluate(el)) });
				
		if($('secondary-nav')) {
			$('secondary-nav').down('li.active').insert({ top: tr + br	});
			$$('#secondary-nav li li a').invoke('insert', { top: "<span>• </span>" } )
		}
		
		$$('.corners h4 > a').each(function(el) { 
			el.update(new Element('span', {'class': 'arrow'}).insert(el.innerHTML));
			el.insert({ top: tr + tl + br + bl });
		});

		$$('#breadcrumb li.first-child a, #get-it-done', '#another-language').invoke('insert', { top: tl + bl } )
		document.fire('corners:rounded');
	},
		
	setupSearchBox: function() {
		var search = $('search');
		if(!search) return;
		search.value = 'Search acc.co.nz for...'
		search.observe('focus', function() { 
			this.clear();
			this.stopObserving('focus');
		});	
	},
		
	Text: {
		init: function() {
			var css = document.styleSheets[0];
			css.cssRules ? this.crossrule = css.cssRules : this.crossrule = css.rules;	
			var currentSize = ACC.Cookie.get('fontresizer');
			if(null != currentSize) {
				this.crossrule[0].style.fontSize = currentSize;	
				ACC.Cookie.set('fontresizer', currentSize, 0, '/');
			}
			
			this.setupTools();			
		},
		
		setupTools: function() {
			if(!$('tools')) return;
			$('increase-text').observe('click', function(event) { 
				ACC.Text.resize(1.08333); /* increase 12 to 13 for browser defaults */
				event.preventDefault(); 
			}); 
			
			$('decrease-text').observe('click', function(event) { 
				ACC.Text.resize(0.92308); /* decrease 13 to 12 for browser defaults */
				event.preventDefault(); 
			}); 
		},
		
		resize: function(multiplier) {	
			var currentSize = this.crossrule[0].style.fontSize.gsub(/%/,'');
			newSize = (currentSize * multiplier) + '%';
			this.crossrule[0].style.fontSize = newSize;
			ACC.Cookie.set('fontresizer', newSize, 0, '/');
		}
	},
	

		browserFixes: function() {		
		$(document.body).addClassName('js');
		
		$$('li:last-child', 'th:last-child', 'td:last-child', 'tr:last-child').invoke('addClassName', 'last-child');
		$$('li:first-child', 'th:first-child', 'td:first-child', 'tr:first-child').invoke('addClassName', 'first-child');
		$$('input').each(function(el) { el.addClassName(el.readAttribute('type')) });
				
		if(Prototype.Browser.IE) {
			document.execCommand("BackgroundImageCache", false, true); /* Fix IE background image flicker */
		}	
		
		if (typeof document.body.style.maxHeight == "undefined") { 
			/* IE6 hover on buttons */
			$(document).observe('corners:rounded', function(){
				$$('input[type="submit"]', 'input[type="reset"]').each(function(el) {
					var className = 'ie-hover';
					if(el.hasClassName('secondary') || el.hasClassName('reset') || el.up('div#header') || el.up('div#homeheader')) { className = 'ie-secondary-hover' }				
					el.observe('mouseover', function(evt){ evt.element().addClassName(className) });
					el.observe('mouseout', function(evt){ evt.element().removeClassName(className) });
				});
				/* PNG Fix */

				DD_belatedPNG.fix('#logo, #banner-link, #banner-link-bottom, #banner-link a, #white-trc, .corners div, #secondary-nav li.active a, #region-overlay');
			});
		}
						
				
		/* Firefox 2 doesn't do border-radius well so add a class to allow hiding of styles. */
		if(Prototype.Browser.Gecko && !Array.reduce) $(document.body).addClassName('lessthanff3');
	},
	
	Cookie: {
		get: function(name) {
			var start = document.cookie.indexOf( name + "=" );
			var len = start + name.length + 1;
			if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
				return null;
			}
			if ( start == -1 ) return null;
			var end = document.cookie.indexOf( ';', len );
			if ( end == -1 ) end = document.cookie.length;
			return unescape( document.cookie.substring( len, end ) );
		},

		set: function(name, value, expires, path, domain, secure) {
			var today = new Date();
			today.setTime( today.getTime() );
			if ( expires ) {
				expires = expires * 1000 * 60 * 60 * 24;
			}
			var expires_date = new Date( today.getTime() + (expires) );
			document.cookie = name+'='+escape( value ) +
				( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
				( ( path ) ? ';path=' + path : '' ) +
				( ( domain ) ? ';domain=' + domain : '' ) +
				( ( secure ) ? ';secure' : '' );
		}	
	},
	
	Map: {
			Region: Class.create({
			initialize: function(name,info,link,bgPosition,coords) {
				this.name = name;
				this.info = info;
				this.link = link;
				this.bgPosition = bgPosition;
				this.coords = coords;
				this.popup = $('map-popup');
			},

			findCentre: function() {
				var xpoints = [];
				var ypoints = [];
				this.coords.each(function(value, index){
					num = Number(value);
					(0 === index % 2) ? xpoints.push(num) : ypoints.push(num);
				});
				function centroidValue(myarray) { return myarray.inject(0, function(acc, n) { return acc + n; }) / myarray.length; }
				this.x = centroidValue(xpoints).round() + 6;
				this.y = centroidValue(ypoints).round() + 12;		
			},

			show: function(template) {
				if($('region-overlay')) $('region-overlay').setStyle({ backgroundPosition : '0 ' + this.bgPosition + 'px' });
				if($('region-overlay-ip')) $('region-overlay-ip').setStyle({ backgroundPosition : '0 ' + this.bgPosition + 'px' });
				this.popup.setStyle({ top: this.y - 10 + 'px', left: this.x + 39 + 'px' });
				this.popup.down('div.inner').update(template.evaluate(this));
				this.popup.show();
				this.popup.setStyle({ width: this.popup.down('div.inner').getWidth() + 12 + 'px'});						
			}
		}),
	
		counsellorTemplate: new Template('#{info}'),

		regionsTemplate: new Template('#{info}<a href="#{link}">More information ›</a>'),
		
		setup: function(template) {
			if(!$('map')) return;	
			this.template = template;
			this.bgPosition = 562;
			var convertName = function(name) { return name.gsub(/\W/,'').toLowerCase() }
			
			$$('#map-nav li a').each( function(a) {
				var name = a.innerHTML.strip();
				var info = a.up('li').cleanWhitespace().innerHTML;
				var link = a.href;
				var region = convertName(name);
				this.bgPosition -= 562;
				this[region] = new ACC.Map.Region(name,info,link, this.bgPosition);			
			}.bind(this));

			$$('#map area').each(function(area){
				var region = convertName(area.readAttribute('alt'));
				this[region].coords = area.readAttribute('coords').split(',');
				this[region].findCentre();
			}.bind(this));

			$('map-nav').down('ul').observe('mouseover', function(evt) {
				var region = convertName(evt.element().innerHTML);
				this[region].show(template);
			}.bind(this)); 

			$('locations').observe('mouseover', function(evt) {
				var region = convertName(evt.element().readAttribute('alt'));
				this[region].show(template);
			}.bind(this));

			document.observe('click', function(evt) { 
				var popup = $('map-popup');
				(evt.element().descendantOf(popup) || evt.element().descendantOf('locations')) ? document.location = popup.down('a').readAttribute('href') : popup.hide();	
			});				
		}		
	},

	equalColumnHeights: function(columns) {
		columns.invoke('setStyle', { height: 'auto' });
		var maxHeight = columns.invoke('getHeight').max();
		//var paddingTop = Number(columns.invoke('getStyle', 'padding-top').max().gsub(/\D/,''));
		var paddingTop = parseInt(columns.invoke('getStyle', 'padding-top').max());
		//var paddingBottom = Number(columns.invoke('getStyle', 'padding-bottom').max().gsub(/\D/,''));
		var paddingBottom = parseInt(columns.invoke('getStyle', 'padding-bottom').max());
		var verticalPadding = paddingTop + paddingBottom;
		maxHeight -= verticalPadding;
		columns.invoke('setStyle', { height: maxHeight + 'px' });
	 	$(document).observe('text:resized', function() { ACC.equalColumnHeights(columns) });
	},

	setupAdvancedSearch: function()  {
		$('adv_search_form').observe('submit', function(evt) { 
			var atLeastOne = $$('#textinputs input').any(function(el){ return $F(el); });
			if(!atLeastOne) {
				alert('You have not entered a valid search word or phrase, please enter one or more search words.');
				evt.stop();
			}
		});
			
		$$('ul.checkboxes input[type=checkbox]').each(
			function(checkbox) {
				var eventName;
				Prototype.Browser.IE ? eventName = 'click' : eventName = 'change';
				checkbox.observe(eventName, function() { toggleCheckboxes(this) })
			}		
		);

		function toggleCheckboxes(checkbox) {		
			var checkboxes = checkbox.up('ul').select('input');		
			var firstCheckBox = checkboxes.first();
			var otherCheckboxes = checkboxes.without(firstCheckBox);
			
			if(firstCheckBox == checkbox && checkbox.checked) { 
				otherCheckboxes.each( function(c) {  c.checked = false });
				return;
			}
							
			var anyChecked = otherCheckboxes.any( function(c) { return c.checked });
			if(anyChecked) firstCheckBox.checked = false;
		}						
	},
	
	Glossary: {	
		init: function() {
			var definitions = $$('dfn');
			if(definitions.length === 0) { return; }	
			this.popup = new Element('div', {'class': 'shadow corners', 'id': 'glossary'});
			this.template = new Template('<div class="content"><div class="t"></div><a class="termlink" href="http://www.google.co.nz/search?q=#{innerHTML}">#{innerHTML}</a><p>#{_title} <a href="http://www.google.co.nz/search?q=#{innerHTML}" class="go">Go to ACC Glossary</a></p></div><div class="b"><div>&nbsp;</div><img src="images/glossary-arrow.png" class="arrow"></div>');						
			$('content').insert(this.popup);
			this.popup.hide();		
			definitions.each( function(dfn){			
	 			dfn.observe('click', function(evt) { ACC.Glossary.togglePopup(this); });
	 			dfn.observe('mouseover', function() { ACC.Glossary.hideTitle(this) });
	 			dfn.observe('mouseout', function() { ACC.Glossary.showTitle(this) });			
	 		});
			
			document.observe('click', function(evt) { 
				var clicked = evt.element();
				var definitionClicked = definitions.any(function(dfn) { return dfn == clicked });
				var popupClicked = clicked.descendantOf(this.popup);
				if(!definitionClicked && !popupClicked) this.popup.hide();
			}.bind(this));	
		},
		
		togglePopup: function(dfn) {
			this.popup.update(this.template.evaluate(dfn))
			this.setPosition(dfn,this.popup);
			this._dfn == dfn ? this.popup.toggle() : this.popup.show();
			this.popup.focus();
			this._dfn = dfn;			
		},
		
		hideTitle: function(dfn) {
			dfn._title = dfn.title;
			dfn.title = '';
			return dfn;
	 	},
	
		showTitle: function(dfn) {
			dfn.title = dfn._title;
			return dfn;
		},
		
		setPosition: function(dfn, popup) {
			var position = dfn.positionedOffset();	
			var top = position[1] - popup.getHeight();
			var left = position[0] - popup.getWidth() + 18 + (dfn.getWidth() / 2);
			if(left < 10) { 
				var arrowPosition = left * -1 + 15;
				popup.down('.arrow').setStyle({right: arrowPosition + 'px' })
				left = 10;
			}			
			popup.setStyle({ left : left + 'px', top : top + 'px' });
			return dfn;
		}	
	}
}

$(document).observe('dom:loaded', function() {ACC.init(); TextResizeDetector.init() });

/* This allows us to detect text resizing, remove sIFR and redo it based on the new text size */
$(document).observe('text:resized', function() { sIFR.rollback(); ACC.customFonts(); });

/* I'm hoping this helps prevent memory leaks! */
$(document).observe('unload', document.stopObserving );

/* START extras */
/* DO NOT REMOVE! Used for the popup links for the glossary items*/
function linkglossary(dDocName,ssTargetNodeId)
{

      var newUrl = g_ssServerRelativeSiteRoot + "about-acc/glossary-of-acc-terms/glossary-items/" + dDocName;   
      window.open(newUrl,"","height=150,width=300,scrollbars=yes");
}

//// Added from old ACC site
function internetPop(theURL,winName,features) { //v2.0

  window.open(g_HttpRelativeWebRoot+theURL,winName,features);

}

