// page init
jQuery(function(){
	initSlideshow();
	initCrawlLine();
	clearInputs();
	hoverForIE6("#nav li", "hover");
	function initNavFix() {
		new touchNav({
			navBlock: 'nav'
		});
	}
});

// slideshow init
function initSlideshow(){
	jQuery('div.visual').fadeGallery({
		slideElements:'ul.gallery > li',
		pagerLinks:'ul.switcher li',
		activeClass:'active',
		autoRotation:true,
		switchTime:5000
	});
}

// slideshow init
function initCrawlLine(){
	jQuery('#sidebar .text-holder').crawlLine({
		crawElement:'div.holder',
		textElement:'p',
		hoverClass:'viewText',
		speed:1
	});
}

// clearInputs
function clearInputs(){
	jQuery ('input:text, input:password, textarea').each(function(){
		var _el = jQuery(this);
		var _val = _el.val();
		_el.bind('focus', function(){
			if(this.value == _val) this.value = '';
		}).bind('blur', function(){
			if(this.value == '') this.value = _val;
		});
	});
}

hoverForIE6(".ul-class li, div.div-class, span , #box, ul#nav li", "hover");

// hover for IE
function hoverForIE6(_list, _class) {
	var _hoverClass = 'hover';
	if(_class) _hoverClass = _class;
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		jQuery(_list).hover(function(){
			jQuery(this).addClass(_hoverClass);
		},function(){
			jQuery(this).removeClass(_hoverClass);
		});
	}
}

// navigation accesibility module
function touchNav(options) {
	this.options = {
		mobileReg: /(ipad|iphone|ipod|android|blackberry|iemobile)/gi,
		hoverClass: 'hover',
		followLink: false,
		menuItems: 'li',
		menuOpener: 'a',
		menuDrop: 'div',
		navBlock: null
	}
	for(var p in options) {
		this.options[p] = options[p];
	}
	this.init();
}
touchNav.prototype = {
	init: function() {
		this.isMobile = (this.options.mobileReg).test(navigator.userAgent);
		if(typeof this.options.navBlock === 'string') {
			this.menu = document.getElementById(this.options.navBlock);
		} else if(typeof this.options.navBlock === 'object') {
			this.menu = this.options.navBlock;
		}
		if(this.menu) {
			this.getElements();
			this.addEvents();
		}
	},
	getElements: function() {
		this.menuItems = this.menu.getElementsByTagName(this.options.menuItems);
	},
	hideActiveDropdown: function() {
		if(this.activeParent) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.removeClass(this.menuItems[i], this.options.hoverClass);
			}
			this.activeParent = null;
		}
	},
	getOpener: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuOpener.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	getDrop: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuDrop.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	addEvents: function() {
		// mobile event handlers
		if(this.isMobile) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				if(this.getDrop(this.menuItems[i])) {
					this.addHandler(this.getOpener(this.menuItems[i]), 'click', this.bind(this.clickHandler,this.menuItems[i]));
				}
			}
			this.addHandler(document.body, 'click', this.bind(this.outsideHandler, this));
			this.addHandler(document.body, 'touchstart', this.bind(this.outsideHandler, this));
		}
		// desktop event handlers
		else {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				this.addHandler(this.menuItems[i], 'mouseover', this.mouseoverHandler);
				this.addHandler(this.menuItems[i], 'mouseout', this.mouseoutHandler);
			}
		}
	},
	outsideHandler: function(e) {
		var childFlag = false;
		if(this.activeParent) {
			this.outsideTarget = e.target || e.currentTarget || e.srcElement;
			while (this.outsideTarget.parentNode) {
				if(this.activeParent == this.outsideTarget) {
					childFlag = true;
					break;
				}
				this.outsideTarget = this.outsideTarget.parentNode;
			}
			if(!childFlag) {
				this.hideActiveDropdown();
			}
		}
	},
	mouseoverHandler: function() {
		this.touchNav.addClass(this, this.touchNav.options.hoverClass);
	},
	mouseoutHandler: function() {
		this.touchNav.removeClass(this, this.touchNav.options.hoverClass);
	},
	clickHandler: function(e) {
		// get current dropdown
		var tNav = this.touchNav;
		tNav.currentElement = e.currentTarget || e.srcElement;
		tNav.currentParent = tNav.currentElement.parentNode;

		// hide previous drop (if exists)
		if(tNav.activeParent && !tNav.isParent(tNav.activeParent, tNav.currentParent) && tNav.currentParent != tNav.activeParent) {
			tNav.hideActiveDropdown();
		}

		// handle current drop
		if(tNav.hasClass(tNav.currentParent, tNav.options.hoverClass)) {
			tNav.removeClass(tNav.currentParent, tNav.options.hoverClass);
			if(tNav.options.followLink) {
				window.location.href = tNav.currentElement.href;
			}
		} else {
			tNav.addClass(tNav.currentParent, tNav.options.hoverClass);
			tNav.activeParent = tNav.currentParent;
			return tNav.preventEvent(e);
		}
	},
	preventEvent: function(e) {
		if(!e) e = window.event;
		if(e.preventDefault) e.preventDefault();
		if(e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		return false;
	},
	isParent: function(parent, child) {
		while(child.parentNode) {
			if(child.parentNode == parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	addHandler: function(object, event, handler) {
		if (typeof object.addEventListener != 'undefined') object.addEventListener(event, this.bind(handler,object), false);
		else if (typeof object.attachEvent != 'undefined') object.attachEvent('on' + event, this.bind(handler,object));
	},
	removeHandler: function(object, event, handler) {
		if (typeof object.removeEventListener != 'undefined') object.removeEventListener(event, handler, false);
		else if (typeof object.detachEvent != 'undefined') object.detachEvent('on' + event, handler);
	},
	hasClass: function(obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function(obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function(obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	},
	bind: function(func, scope){
		return function() {
			return func.apply(scope, arguments);
		}
	}
}

// mobile
//<![CDATA[
var mobi = ['opera', 'iemobile', 'webos', 'android', 'blackberry', 'ipad', 'safari'];
var midp = ['blackberry', 'symbian'];
var siteurl = 'http://www.lifetimefinancial.com.au';
var ua = navigator.userAgent.toLowerCase();
if ((ua.indexOf('midp') != -1) || (ua.indexOf('mobi') != -1) || ((ua.indexOf('ppc') != -1) && (ua.indexOf('mac') == -1)) || (ua.indexOf('webos') != -1)) {
	document.write('<link rel="stylesheet" href="'+siteurl+'/allmobile.css" type="text/css" media="all"/>');
	if (ua.indexOf('midp') != -1) {
		for (var i = 0; i < midp.length; i++) {
			if (ua.indexOf(midp[i]) != -1) {
				document.write('<link rel="stylesheet" href="'+siteurl+'/' + midp[i] + '.css" type="text/css"/>');
			}
		}
	}
	else {
		if ((ua.indexOf('mobi') != -1) || (ua.indexOf('ppc') != -1) || (ua.indexOf('webos') != -1)) {
			for (var i = 0; i < mobi.length; i++) {
				if (ua.indexOf(mobi[i]) != -1) {
					if ((mobi[i].indexOf('blackberry') != -1) && (ua.indexOf('6.0') != -1)) {
						document.write('<link rel="stylesheet" href="'+siteurl+'/' + mobi[i] + '6.0.css" type="text/css"/>');
					}
					else {
						document.write('<link rel="stylesheet" href="'+siteurl+'/' + mobi[i] + '.css" type="text/css"/>');
					}
					break;
				}
			}
		}
	}
}
if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
document.write('<meta name="viewport" content="width=device-width" />');
}
//]]>
// font resize script
fontResize = {
	options: {
		maxStep:1.5,
		defaultFS: 1.0,
		resizeStep: 0.1,
		resizeHolder: 'body',
		cookieName: 'fontResizeCookie'
	},
	init: function() {
		this.domReady(function(){
			this.setDefaultScaling();
			this.addDefaultHandlers();
		});
		return this;
	},
	addDefaultHandlers: function() {
		this.addHandler('increase','inc');
		this.addHandler('decrease','dec');
		this.addHandler('reset');
	},
	setDefaultScaling: function() {
		if(this.options.resizeHolder == 'html') { this.resizeHolder = document.documentElement; }
		else { this.resizeHolder = document.body; }
		var cSize = this.getCookie(this.options.cookieName);
		if(cSize) {
			this.fSize = parseFloat(cSize,10)
		} else {
			this.fSize = this.options.defaultFS;
		}
		this.changeSize();
	},
	changeSize: function(direction) {
		if(typeof direction !== 'undefined') {
			if(direction == 1) {
				this.fSize += this.options.resizeStep;
				if (this.fSize > this.options.defaultFS * this.options.maxStep) this.fSize = this.options.defaultFS * this.options.maxStep;
			} else if(direction == -1) {
				this.fSize -= this.options.resizeStep;
				if (this.fSize < this.options.defaultFS / this.options.maxStep) this.fSize = this.options.defaultFS / this.options.maxStep;
			} else {
				this.fSize = this.options.defaultFS;
			}
		}
		this.resizeHolder.style.fontSize = this.fSize + 'em';
		this.updateCookie(this.fSize.toFixed(0));
		return false;
	},
	addHandler: function(obj, type) {
		if(typeof obj === 'string') { obj = document.getElementById(obj); }
		if(typeof obj !== 'undefined') {
			switch (type) {
				case 'inc':
					obj.onclick = this.bind(this.changeSize,this, [1]);
					break;
				case 'dec':
					obj.onclick = this.bind(this.changeSize,this, [-1]);
					break;
			}
		}
	},
	domReady: function(fn) {
		var scope = this, calledFlag;
		(function(){
			if (document.addEventListener) {
				document.addEventListener('DOMContentLoaded', function(){
					if(!calledFlag) { calledFlag = true; fn.call(scope); }
				}, false)
			}
			if (!document.readyState || document.readyState.indexOf('in') != -1) {
				setTimeout(arguments.callee, 9);
			} else {
				if(!calledFlag) { calledFlag = true; fn.call(scope); }
			}
		}());
	},
	updateCookie: function(scaleLevel) {
		this.setCookie(this.options.cookieName,scaleLevel);
	},
	getCookie: function(name) {
		var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
		return matches ? decodeURIComponent(matches[1]) : undefined;
	},
	setCookie: function(name, value) {
		var exp = new Date();
		exp.setTime(exp.getTime()+(30*24*60*60*1000));
		document.cookie = name + '=' + value + ';' +'expires=' + exp.toGMTString() + ';' +'path=/';
	},
	bind: function(fn, scope, args){
		return function() {
			return fn.apply(scope, args || arguments);
		}
	}
}.init();

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.slideset > div',
		pagerLinks:'div.pager a',
		btnNext:'a.next',
		btnPrev:'a.prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		loadingClass:'ajax-loading',
		loadedClass:'slide-loaded',
		dynamicImageLoad:false,
		dynamicImageLoadAttr:'alt',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:false,
		onBeforeFade:false,
		onAfterFade:false,
		onChange:false,
		disableWhileAnimating:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		if(this.slideshowInit) return; else this.slideshowInit;
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _dynamicImageLoad = _options.dynamicImageLoad;
		var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _loadingClass = _options.loadingClass;
		var _loadedClass = _options.loadedClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;
		var _onBeforeFade = _options.onBeforeFade;
		var _onAfterFade = _options.onAfterFade;
		var _disableWhileAnimating = _options.disableWhileAnimating;

		// gallery init
		var _anim = false;
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;

		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentIndex != _ind) {
						if(_disableWhileAnimating && _anim) return;
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// play pause section
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}

		// dynamic image loading (swap from ATTRIBUTE)
		function loadSlide(slide) {
			if(!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
				var images = slide.find(_dynamicImageLoad) // pass selector here
				var imagesCount = images.length;
				if(imagesCount) {
					slide.addClass(_loadingClass);
					images.each(function(){
						var img = this;
						img.onload = function(){
							img.loaded = true;
							img.onload = null;
							setTimeout(reCalc,_duration);
						}
						img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
						img.setAttribute(_dynamicImageLoadAttr,'');
					}).css({opacity:0});

					function reCalc() {
						var cnt = 0;
						images.each(function(){
							if(this.loaded) cnt++;
						});
						if(cnt == imagesCount) {
							slide.removeClass(_loadingClass);
							images.animate({opacity:1},{duration:_duration,complete:function(){
								if(jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({opacity:'auto'})
							}});
							slide.addClass(_loadedClass)
						}
					}
				}
			}
		}

		// gallery animation
		function prevSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _slides, _prevIndex, _currentIndex);
			}
		}
		function switchSlide() {
			_anim = true;
			if(typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
			_slides.eq(_prevIndex).fadeOut(_duration,function(){
				_anim = false;
			});
			_slides.eq(_currentIndex).fadeIn(_duration,function(){
				if(typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
			});
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
}

/*******************************************************************************************/
// jquery.event.wheel.js - rev 1
// Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
// Liscensed under the MIT License (MIT-LICENSE.txt)
// http://www.opensource.org/licenses/mit-license.php
// Created: 2008-07-01 | Updated: 2008-07-14
// jQuery(body).bind('wheel',function(event,delta){    alert( delta>0 ? "up" : "down" );    });
/*******************************************************************************************/
;(function($){$.fn.wheel=function(a){return this[a?"bind":"trigger"]("wheel",a)};$.event.special.wheel={setup:function(){$.event.add(this,b,wheelHandler,{})},teardown:function(){$.event.remove(this,b,wheelHandler)}};var b=!$.browser.mozilla?"mousewheel":"DOMMouseScroll"+($.browser.version<"1.9"?" mousemove":"");function wheelHandler(a){switch(a.type){case"mousemove":return $.extend(a.data,{clientX:a.clientX,clientY:a.clientY,pageX:a.pageX,pageY:a.pageY});case"DOMMouseScroll":$.extend(a,a.data);a.delta=-a.detail/3;break;case"mousewheel":a.delta=a.wheelDelta/120;if($.browser.opera)a.delta*=-1;break}a.type="wheel";return $.event.handle.call(this,a,a.delta)}})(jQuery);

// plugin craw line
jQuery.fn.crawlLine = function(_options){
	// defaults options
	var _options = jQuery.extend({
		speed:1,
		crawElement:'div',
		textElement:'p',
		hoverClass:'viewText'
	},_options);
	
	return this.each(function(){
		var _THIS = jQuery(this);
		var _el = jQuery(_options.crawElement, _THIS).css('position','relative');
		var _text = jQuery(_options.textElement, _THIS);
		var _clone = _text.clone();
		var _elHeight = 0;
		var _k = 1;
		
		// set parametrs
		var _textHeight = 0;
		_text.each(function(){
			_textHeight += jQuery(this).outerHeight(true);
		});
		var _duration = _textHeight*50 / _options.speed;
		_el.append(_clone);
		_el.css('height', _textHeight*2);
		
		var animate = function() {
			_el.animate({top:-_textHeight}, {queue:false, duration:_duration*_k, easing:'linear', complete:function(){
				_el.css('top', 0);
				_k=1;
				animate();
			}})
		}
		animate();
		
		_THIS.hover(function() {
			_el.stop();
			_THIS.addClass(_options.hoverClass);
	    }, function(){
			_THIS.removeClass(_options.hoverClass);
			_k = (_textHeight + parseInt(_el.css('top')))/_textHeight;
			animate();
		});
		
		_THIS.bind('wheel',function(event,delta){
			var _marginScroll;
			if (delta<0) {
				_marginScroll = parseInt(_el.css('top')) - 20;
				
				//console.log((_marginScroll), _textHeight, _THIS.height());
				
				if(_marginScroll == -_textHeight || _marginScroll < -_textHeight) {
					_el.css('top', 0);
					_marginScroll = -20;
				}
				_el.animate({top:_marginScroll}, {queue:false, duration:100, easing:'linear', complete:function(){
					_k = (_textHeight + parseInt(_el.css('top')))/_textHeight;
				}});
			} else {
				if(parseInt(_el.css('top')) == 0) _el.css('top', -_textHeight);
				_marginScroll = parseInt(_el.css('top')) + 20;
				if (_marginScroll > 0) _marginScroll = 0;
				_el.animate({top:_marginScroll}, {queue:false, duration:100, easing:'linear', complete:function(){
					_k = (_textHeight + parseInt(_el.css('top')))/_textHeight;
				}});
			}
			return false;
		});
	});
}
