/*** -- START JAVASCRIPT ENABLED -- ***/

$(function() {
    var body = $('body');
    body.removeClass("js_disabled");
    body.addClass("js_enabled");
});

/*** -- END JAVASCRIPT ENABLED -- ***/

/* ---- OPEN EXTERNAL LINKS IN A NEW WINDOW ---- */

function externalLinks() {
    if (!document.getElementsByTagName) {
        return;
    }
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") &&
            anchor.getAttribute("rel") == "external" || anchor.getAttribute("rel") == "pdf") {
			anchor.target = "_blank";
			anchor.title = "This link will open in a new window";
		}
    }
}

/* ---- Unobtrusive JavaScript Print Link ---- */ 
function printLink() {
	$('div.mainContent')
	.prepend('<p class="btnPrint"><a href="#print" title="Print this page">Print</a></p>');
	$('div.mainContent')
	.append('<p class="btnPrint"><a href="#print" title="Print this page">Print</a></p>');
	
	$('div.mainContent p.btnPrint a').click(function() {
		window.print();
		return false;
	});
}

// FAQs
function faqs() {
	$("dl.faqs dd").hide();
	$("dl.faqs dt").wrapInner("<a href='#non'></a>");
	$("dl.faqs dt a")
		.addClass("show")
		.click(function(){
			$(this).toggleClass("hide");
			$(this).parent().next("dl.faqs dd").slideToggle();
			return false;
		});
}

/* * ---- TEXT CONTRAST LINK ---- * */

//Outside document ready to avoid FOUC
if($.cookie("CONTRAST")) {
	//$("#contrast").attr("href","/styles/" + ($.cookie("CONTRAST")) + ".css" );
	contrastSwitch($.cookie("CONTRAST"));
}

function contrastSwitch(contrast){
	
		var contrast = contrast;

		var stylePath = "/styles/" + contrast + ".css";
		$("#contrast").attr('href',stylePath);
		
		
		
		// LOGO SWITCH OUT
		$('img.contrast_logo').each(function(){
			var currentSrc = $(this).attr('src').slice(0,-8);
			var newLogoSrc = currentSrc + contrast + ".png";
			$(this).attr('src',newLogoSrc);
		});
		
		$.cookie("CONTRAST",contrast, {expires: 365, path: '/'});
		
}


function contrastLink() {

	$("ul.contrast_tool li a").click(function(){
		var contrast = $(this).attr('rel');
		contrastSwitch(contrast);
	
		return false;
	});
}



/* * ---- TEXT RESIZE ---- * */

function resizeText(){
	if($.cookie('TEXT_SIZE')) {
		var cookieVal = $.cookie('TEXT_SIZE');
		$('body').addClass(cookieVal);
		$('.site_tools ul.font_size_tool li.textSize a').removeClass("on");
		$('.site_tools ul.font_size_tool li.textSize a.' + cookieVal).addClass("on");
	}
	$('.site_tools ul.font_size_tool li.textSize a').live('click', function() {
		
		var textSize = $(this).attr('class').split(" ")[0];
		$('body').removeClass('on small mid large').addClass(textSize);
		$('.site_tools ul.font_size_tool li.textSize a').removeClass("on");
		$(this).addClass("on");
		$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
		
		//refreshes page only use if using Cufon, or something which needs to re-draw the screen to update
		Cufon.refresh();
		
		return false;
	});

}


/*** -- START OVERLAY POP UP-- ***/

function overlayPopup(){
	$(".slider-holder li").each(function(){
		var sectionOverlay = $(this).find(".section_overlay");
		//Find the height of the title, subtract it from the total height, and apply css to move it to the bottom
		var sectionOffset = ($(sectionOverlay).height())- ($(this).find(".title_wrap").height());
		$(sectionOverlay).css("bottom","-"+sectionOffset+"px");
		//Slide up overlay on hover
		$(this).hoverIntent(function(){
			$(sectionOverlay).animate({bottom:"0"},300);
		},function(){
			$(sectionOverlay).animate({bottom:"-"+sectionOffset+"px"},300);
		});
	});
}

/*** -- END OVERLAY POP UP-- ***/

/*** -- SHOW/HIDE LABEL -- ***/
		
function showHideLabel() {		
	var $searchLabel = $(".site-search-label");
	if ($(".site-search-text").size()) {
		if ($(".site-search-text").val().length > 0) {
			$searchLabel.css("text-indent", "-9999px");
		}
		$(".site-search-text").focus(function(){
			//$searchLabel.css("text-indent", "-9999px");
			var myLabel = $(this).siblings("label.site-search-label");
			$(myLabel).css("text-indent", "-9999px");
		}).blur(function(){
			if ($(this).val() === "") {
				$searchLabel.css("text-indent", "0");
			}
		});
	}
}

/*
* jQuery Cycle Plugin
* Examples and documentation at: http://malsup.com/jquery/cycle/
* Copyright (c) 2007-2008 M. Alsup
* Version: 2.32 (21-DEC-2008)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
// Cycle Plugin: Core
; eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } (';(4($){7 u=\'2.32\';7 x=$.1y.1z&&/2J 6.0/.2K(2L.2M);4 Q(){3(1A.1B&&1A.1B.Q)1A.1B.Q(\'[D] \'+2N.2O.2P.2Q(26,\'\'))};$.H.D=4(q){3(8.9==0){Q(\'27; 2R 1a 1C 2S 2T\'+($.2U?\'\':\' (2V Z 2W)\'));y 8}7 r=26[1];y 8.11(4(){3(q===2X||q===B)q={};3(q.1D==28){2Y(q){1E\'2Z\':3(8.E)15(8.E);8.E=0;$(8).1b(\'D.1j\',\'\');y;1E\'1F\':8.P=1;y;1E\'29\':8.P=0;3(r===1G){q=$(8).1b(\'D.1j\');3(!q){Q(\'2a Z 1C, 2b Z 29\');y}3(8.E){15(8.E);8.E=0}R(q.1a,q,1,1)}y;30:q={V:q}}}L 3(q.1D==31){7 d=q;q=$(8).1b(\'D.1j\');3(!q){Q(\'2a Z 1C, 2b Z 1k 2c\');y}3(d<0||d>=q.1a.9){Q(\'33 2c 2d: \'+d);y}q.A=d;3(8.E){15(8.E);8.E=0}R(q.1a,q,1,d>=q.M);y}3(8.E)15(8.E);8.E=0;8.P=0;7 e=$(8);7 f=q.1H?$(q.1H,8):e.34();7 g=f.35();3(g.9<2){Q(\'27; 36 37 38: \'+g.9);y}7 j=$.39({},$.H.D.2e,q||{},$.2f?e.2f():$.3a?e.1b():{});3(j.1I)j.1J=j.1K||g.9;e.1b(\'D.1j\',j);j.17=8;j.1a=g;j.S=j.S?[j.S]:[];j.T=j.T?[j.T]:[];j.T.1L(4(){j.1M=0});3(j.18)j.T.1c(4(){R(g,j,0,!j.19)});3(x&&j.1l&&!j.2g)1N(f);7 k=8.3b;j.F=12((k.1m(/w:(\\d+)/)||[])[1])||j.F;j.C=12((k.1m(/h:(\\d+)/)||[])[1])||j.C;j.G=12((k.1m(/t:(\\d+)/)||[])[1])||j.G;3(e.J(\'1n\')==\'3c\')e.J(\'1n\',\'3d\');3(j.F)e.F(j.F);3(j.C&&j.C!=\'1o\')e.C(j.C);3(j.N)j.N=12(j.N);3(j.W){j.X=[];1O(7 i=0;i<g.9;i++)j.X.1c(i);j.X.3e(4(a,b){y 3f.W()-0.5});j.I=0;j.N=j.X[0]}L 3(j.N>=g.9)j.N=0;7 l=j.N||0;f.J({1n:\'2h\',3g:0,3h:0}).2i().11(4(i){7 z=l?i>=l?g.9-(i-l):l-i:g.9-i;$(8).J(\'z-2d\',z)});$(g[l]).J(\'1d\',1).2j();3($.1y.1z)g[l].2k.2l(\'1P\');3(j.U&&j.F)f.F(j.F);3(j.U&&j.C&&j.C!=\'1o\')f.C(j.C);3(j.2m){7 m=0,1e=0;1O(7 i=0;i<g.9;i++){7 n=$(g[i]),w=n.3i(),h=n.3j();m=w>m?w:m;1e=h>1e?h:1e}e.J({F:m+\'2n\',C:1e+\'2n\'})}3(j.1F)e.2o(4(){8.P++},4(){8.P--});7 o=$.H.D.2p[j.V];3($.2q(o))o(e,f,j);L 3(j.V!=\'1Q\')Q(\'3k 3l: \'+j.V);f.11(4(){7 a=$(8);8.2r=(j.U&&j.C)?j.C:a.C();8.2s=(j.U&&j.F)?j.F:a.F()});j.13=j.13||{};j.1f=j.1f||{};j.1g=j.1g||{};f.Z(\':1R(\'+l+\')\').J(j.13);3(j.2t)$(f[l]).J(j.2t);3(j.G){j.G=12(j.G);3(j.O.1D==28)j.O=$.V.3m[j.O]||12(j.O);3(!j.1p)j.O=j.O/2;3n((j.G-j.O)<3o)j.G+=j.O}3(j.1S)j.1T=j.1U=j.1S;3(!j.1q)j.1q=j.O;3(!j.1r)j.1r=j.O;j.2u=g.9;j.M=l;3(j.W){j.A=j.M;3(++j.I==g.9)j.I=0;j.A=j.X[j.I]}L j.A=j.N>=(g.9-1)?0:j.N+1;7 p=f[l];3(j.S.9)j.S[0].1s(p,[p,p,j,1G]);3(j.T.9>1)j.T[1].1s(p,[p,p,j,1G]);3(j.1h&&!j.K)j.K=j.1h;3(j.K)$(j.K).1V(\'1h\',4(){y 1k(g,j,j.19?-1:1)});3(j.1W)$(j.1W).1V(\'1h\',4(){y 1k(g,j,j.19?1:-1)});3(j.Y)2v(g,j);j.3p=4(a,b){7 c=$(a),s=c[0];3(!j.1K)j.1J++;g[b?\'1L\':\'1c\'](s);3(j.2w)j.2w[b?\'1L\':\'1c\'](s);j.2u=g.9;c.J(\'1n\',\'2h\');c[b?\'3q\':\'2x\'](e);3(b){j.M++;j.A++}3(x&&j.1l&&!j.2g)1N(c);3(j.U&&j.F)c.F(j.F);3(j.U&&j.C&&j.C!=\'1o\')f.C(j.C);s.2r=(j.U&&j.C)?j.C:c.C();s.2s=(j.U&&j.F)?j.F:c.F();c.J(j.13);3(j.Y)$.H.D.1X(g.9-1,s,$(j.Y),g,j);3(1t j.1Y==\'4\')j.1Y(c)};3(j.G||j.18)8.E=1Z(4(){R(g,j,0,!j.19)},j.18?10:j.G+(j.2y||0))})};4 R(a,b,c,d){3(b.1M)y;7 p=b.17,14=a[b.M],K=a[b.A];3(p.E===0&&!c)y;3(!c&&!p.P&&((b.1I&&(--b.1J<=0))||(b.1u&&!b.W&&b.A<b.M))){3(b.20)b.20(b);y}3(c||!p.P){3(b.S.9)$.11(b.S,4(i,o){o.1s(K,[14,K,b,d])});7 e=4(){3($.1y.1z&&b.1l)8.2k.2l(\'1P\');$.11(b.T,4(i,o){o.1s(K,[14,K,b,d])})};3(b.A!=b.M){b.1M=1;3(b.21)b.21(14,K,b,e,d);L 3($.2q($.H.D[b.V]))$.H.D[b.V](14,K,b,e);L $.H.D.1Q(14,K,b,e,c&&b.2z)}3(b.W){b.M=b.A;3(++b.I==a.9)b.I=0;b.A=b.X[b.I]}L{7 f=(b.A+1)==a.9;b.A=f?0:b.A+1;b.M=f?a.9-1:b.A-1}3(b.Y)$.H.D.22(b.Y,b.M)}3(b.G&&!b.18)p.E=1Z(4(){R(a,b,0,!b.19)},2A(14,K,b,d));L 3(b.18&&p.P)p.E=1Z(4(){R(a,b,0,!b.19)},10)};$.H.D.22=4(a,b){$(a).3r(\'a\').3s(\'2B\').1P(\'a:1R(\'+b+\')\').3t(\'2B\')};4 2A(a,b,c,d){3(c.23){7 t=c.23(a,b,c,d);3(t!==1i)y t}y c.G};4 1k(a,b,c){7 p=b.17,G=p.E;3(G){15(G);p.E=0}3(b.W&&c<0){b.I--;3(--b.I==-2)b.I=a.9-2;L 3(b.I==-1)b.I=a.9-1;b.A=b.X[b.I]}L 3(b.W){3(++b.I==a.9)b.I=0;b.A=b.X[b.I]}L{b.A=b.M+c;3(b.A<0){3(b.1u)y 1i;b.A=a.9-1}L 3(b.A>=a.9){3(b.1u)y 1i;b.A=0}}3(b.1v&&1t b.1v==\'4\')b.1v(c>0,b.A,a[b.A]);R(a,b,1,c>=0);y 1i};4 2v(a,b){7 c=$(b.Y);$.11(a,4(i,o){$.H.D.1X(i,o,c,a,b)});$.H.D.22(b.Y,b.N)};$.H.D.1X=4(i,b,c,d,e){7 a=(1t e.24==\'4\')?e.24(i,b):\'<a 3u="#">\'+(i+1)+\'</a>\';3(!a)y;7 f=$(a);3(f.3v(\'3w\').9==0)f.2x(c);f.1V(e.2C,4(){e.A=i;7 p=e.17,G=p.E;3(G){15(G);p.E=0}3(1t e.25==\'4\')e.25(e.A,d[e.A]);R(d,e,1,e.M<i);y 1i});3(e.2D)f.2o(4(){e.17.P++},4(){e.17.P--})};4 1N(b){4 1w(s){7 s=12(s).3x(16);y s.9<2?\'0\'+s:s};4 2E(e){1O(;e&&e.3y.3z()!=\'3A\';e=e.3B){7 v=$.J(e,\'2F-2G\');3(v.3C(\'3D\')>=0){7 a=v.1m(/\\d+/g);y\'#\'+1w(a[0])+1w(a[1])+1w(a[2])}3(v&&v!=\'3E\')y v}y\'#3F\'};b.11(4(){$(8).J(\'2F-2G\',2E(8))})};$.H.D.1Q=4(a,b,c,d,e){7 f=$(a),$n=$(b);$n.J(c.13);7 g=e?1:c.1q;7 h=e?1:c.1r;7 i=e?B:c.1T;7 j=e?B:c.1U;7 k=4(){$n.2H(c.1f,g,i,d)};f.2H(c.1g,h,j,4(){3(c.1x)f.J(c.1x);3(!c.1p)k()});3(c.1p)k()};$.H.D.2p={2I:4(b,c,d){c.Z(\':1R(\'+d.N+\')\').J(\'1d\',0);d.S.1c(4(){$(8).2j()});d.1f={1d:1};d.1g={1d:0};d.13={1d:0};d.1x={3G:\'3H\'};d.1Y=4(a){a.2i()}}};$.H.D.3I=4(){y u};$.H.D.2e={V:\'2I\',G:3J,23:B,18:0,O:3K,1q:B,1r:B,K:B,1W:B,1v:B,Y:B,25:B,2C:\'1h\',24:B,S:B,T:B,20:B,1S:B,1T:B,1U:B,3L:B,1f:B,1g:B,13:B,1x:B,21:B,C:\'1o\',N:0,1p:1,W:0,U:0,2m:1,1F:0,2D:0,1I:0,1K:0,2y:0,1H:B,1l:0,1u:0,2z:0}})(3M);', 62, 235, '|||if|function|||var|this|length|||||||||||||||||||||||||return||nextSlide|null|height|cycle|cycleTimeout|width|timeout|fn|randomIndex|css|next|else|currSlide|startingSlide|speed|cyclePause|log|go|before|after|fit|fx|random|randomMap|pager|not||each|parseInt|cssBefore|curr|clearTimeout||container|continuous|rev|elements|data|push|opacity|maxh|animIn|animOut|click|false|opts|advance|cleartype|match|position|auto|sync|speedIn|speedOut|apply|typeof|nowrap|prevNextClick|hex|cssAfter|browser|msie|window|console|found|constructor|case|pause|true|slideExpr|autostop|countdown|autostopCount|unshift|busy|clearTypeFix|for|filter|custom|eq|easing|easeIn|easeOut|bind|prev|createPagerAnchor|onAddSlide|setTimeout|end|fxFn|updateActivePagerLink|timeoutFn|pagerAnchorBuilder|pagerClick|arguments|terminating|String|resume|options|can|slide|index|defaults|metadata|cleartypeNoBg|absolute|hide|show|style|removeAttribute|containerResize|px|hover|transitions|isFunction|cycleH|cycleW|cssFirst|slideCount|buildPager|els|appendTo|delay|fastOnEvent|getTimeout|activeSlide|pagerEvent|pauseOnPagerHover|getBg|background|color|animate|fade|MSIE|test|navigator|userAgent|Array|prototype|join|call|zero|by|selector|isReady|DOM|ready|undefined|switch|stop|default|Number||invalid|children|get|too|few|slides|extend|meta|className|static|relative|sort|Math|top|left|outerWidth|outerHeight|unknown|transition|speeds|while|250|addSlide|prependTo|find|removeClass|addClass|href|parents|body|toString|nodeName|toLowerCase|html|parentNode|indexOf|rgb|transparent|ffffff|display|none|ver|4000|1000|shuffle|jQuery'.split('|'), 0, {}));
// Cycle Plugin: Effects
(function($) {
    // scrollHorz
    $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow', 'hidden').width(); opts.before.push(function(curr, next, opts, fwd) { $(this).show(); var currW = curr.offsetWidth, nextW = next.offsetWidth; opts.cssBefore = fwd ? { left: nextW} : { left: -nextW }; opts.animIn.left = 0; opts.animOut.left = fwd ? -currW : currW; $slides.not(curr).css(opts.cssBefore) }); opts.cssFirst = { left: 0 }; opts.cssAfter = { display: 'none'} };
})(jQuery);

$(document).ready(function(){

	// if($.cookie("CONTRAST")) {
		// contrastSwitch($.cookie("CONTRAST"));	
	// }
  
  //For the property pages, if the title area has the class current we need to highlight the Prices and affordability tab
	var $tabs = $("div#uiTabs");
	if($(".title_area").hasClass("current")) {
    $tabs.tabs({ selected: 3 });
  } else {
    $tabs.tabs();
  }

	
	
	//contrastLink();
	showHideLabel();
	resizeText();
	externalLinks();
	printLink();
	faqs();
	
	$('.qtip').qtip({ style: { name: 'light', tip: true } });
    
	// Apply Cufon 	
	Cufon.replace('h1.cufon, h2.cufon, p.house_01, div.tool_box h1, div.full_three_columns h2, ul#main_navigation, .house_01_a',{
		hover: true
	});
	Cufon.now();
	/*** -- Carousel on homepage-- ***/	
	$("div#homeCarou").CarouSlide({
		slideTime: 5000,
		animTime: 800,
		animType:"slide",
		showBackNext: false,
		autoAnim: true,
		animInfinity: true,
		pauseOnHover: true
	});
	
	/*** -- Carousel on property page-- ***/
	$("div#propertyCarou").CarouSlide({
		slideTime: 5000,
		animTime: 800,
		animType:"slide",
		showBackNext: false,
		autoAnim: false,
		animInfinity: false
	});
	
	//Make sure overlayPopup is firing
	overlayPopup();
	
	animInfinityCallback = function(){
		overlayPopup();
	}
	
	/*** -- Customer profile form -- ***/
	
/* --- START RESIDENTS SECTION SELECTS ---*/
	
	//Determine number of residents
	var $residentSelect = $("#residentNumber select");
	var $residentForm = $(".profile_form");
	$(".resident").hide();
	
	// Calling function from below, to read whats selected on page refresh
	setResidentNumber($residentSelect.attr("value"));
	
	// On change event for selects
	$residentSelect.change(function(){
		// Calling function from below, to read whats selected on change
		setResidentNumber($residentSelect.attr("value"));
	});
	
	function setResidentNumber(val) {
		var residentN = "res" + val;
		// Set id on parent div, used to pass styles through
		$residentForm.attr("id",residentN);	
		$(".resident").hide();
		$(".resident" + val).show();	
	};
	
/* --- END RESIDENTS SECTION SELECTS ---*/

/* --- START MEMBERS SECTION SELECTS ---*/
	
	//Determine number of residents
	var $memberSelect = $("#memberNumber select");
	var $memberWrap = $(".member_wrap");
	$(".member").hide();
	
	// Calling function from below, to read whats selected on page refresh
	setMemberNumber($memberSelect.attr("value"));
	
	// On change event for selects
	$memberSelect.change(function(){
		// Calling function from below, to read whats selected on change
		setMemberNumber($memberSelect.attr("value"));
	});
	
	function setMemberNumber(val) {
		var memberN = "res" + val;
		// Set id on parent div, used to pass styles through
		$memberWrap.attr("id",memberN);	
		$(".member").hide();
		$(".member" + val).show();	
	};
	
/* --- END MEMBERS SECTION SELECTS ---*/
	
	//Show contact boxes
	var $contactSelect = $("#contact_method input");
	var $contactSelected = $("#contact_method input:checked");
	
	$contactSelected.each(function(){
		if ($(this).attr("class")) {
			var contactType = $(this).attr("class");
			if ($(this).is(":checked")) {
				$("." + contactType).show();
			} else {
				$(".jsHide." + contactType).hide();
			}
		}
		
	});
	
	$contactSelect.change(function(){
		if ($(this).attr("class")) {		
			var contactType = $(this).attr("class");
			if ($(this).is(":checked")) {
				$("." + contactType).show();
			} else {
				$(".jsHide." + contactType).hide();
			}
		}
		
	});
	
	$("#benefits input:checked").each(function(){
		var input = $(this);
		showHideBenefits(input);
	});
	
	$("#benefits input").click(function(){
		var input = $(this);
		showHideBenefits(input);
	});
	
	function showHideBenefits(input) {
		var $input = input;
		if($input.hasClass("benefits-yes")) {
				$("#benefits-input").show();
		} else {
			$("#benefits-input").hide();
			$("#benefits-input input").attr("checked",false)
		}	
	}
	
	//Branch finder static location map
	$(".regional_map li").hover(showMapTip,hideMapTip);
	
	/* --- START INPUT TOGGLE PAGE LOAD --- */
	var	optionParent = $('div.profile_form select.input_toggle');
	var	hiddenInput = $('div.profile_form div.hidden_input');
	$(hiddenInput).hide();	
	
	$(optionParent).change(function(){
		
		// If there is a sub select attched to this then go find it and refresh on change 
		var nextHiddenWrap = $(thisSelect).closest('.form_row').next('.hidden_wrap');
		var mySubInputs = $(nextHiddenWrap).find('.sub_select');
		
		var nextHiddenField = $(mySubInputs).closest('.hidden_wrap');
		var mySubField = $(nextHiddenField).find('.sub_hidden');
		
		if (mySubField.length) {
			$(mySubInputs).find('option:first').attr('selected', 'selected');
		}
		
		var thisSelect = $(this); 
		var selectedClass = $(this).find('option:selected').attr('class');
		inputToggle(selectedClass, thisSelect);
		
	});
	
	$(optionParent).each(function(){
		var selected = $(this).find('option:selected');
		if ($(selected).attr('class') != null) {
			var selectedClass = $(selected).attr('class');
			inputToggle(selectedClass);
		} 
		
	});

	/* --- END INPUT TOGGLE --- */

	/* CAROUSEL FEATURES */
	// Cycle Plugin: Activate cycle
	//$('.featureInner').cycle({ fx: 'scrollHorz', speed: 500, timeout: 5000, next: '.next', prev: '.prev' });
	$('.featureInner').cycle({ fx: 'fade', speed: 500, timeout: 5000, next: '.next', prev: '.prev' });
	// Custom Function: Control behaviour
	    $('.play').click(function() { $('.featureInner').cycle('resume'); return false; });
	    $('.pause').click(function() { $('.featureInner').cycle('pause'); return false; });
	    $('.play').hide();
	    $('.pause').click(function() { $(this).hide().siblings('.play').show() });
	    $('.play').click(function() { $(this).hide().siblings('.pause').show() });
	// Custom Function: Control rollover
	imageRollover = { init: function() {
	    this.preload();
	    $(".cycleControls img").hover(
            function() { $(this).attr('src', imageRollover.newimage($(this).attr('src'))); },
            function() { $(this).attr('src', imageRollover.oldimage($(this).attr('src'))); }
        );
	    },
	    preload: function() { $(window).bind('load', function() { $('img').each(function(key, elm) { $('<img>').attr('src', imageRollover.newimage($(this).attr('src'))); }); }); },
	    newimage: function(src) { return src.substring(0, src.search(/(\.[a-z]+)$/)) + 'H' + src.match(/(\.[a-z]+)$/)[0]; },
	    oldimage: function(src) { return src.replace(/H\./, '.'); }
	    };
    imageRollover.init();
	/* END CAROUSEL FEATURES */
});

function showMapTip(){
    if ($.browser.msie && $.browser.version.substr(0,1)<9) {
        $(this).find(".tip").show(); //IE6 cannot render PNG's and opacity at the same time
    } else {
        $(this).find(".tip").fadeIn("fast");
    }
}
    
function hideMapTip(){
    $(this).find(".tip").hide();
}

//Branch finder static location map
$(".regional_map li").hover(showMapTip,hideMapTip);

// Input toggle function
function inputToggle(selectedClass, thisSelect) {
	
	if (selectedClass.length) {
		if ($("#"+selectedClass).length) {
			$("#"+selectedClass).show()
				.siblings()
					.hide();
		} else if (selectedClass == 'hide') {
			var myHiddenWraps = $(thisSelect).closest('.form_row').next('.hidden_wrap');
			var myHiddenInputs = $(myHiddenWraps).find('.hidden_input');
			(myHiddenInputs).hide();
		}
	} else {
		return false;
	}
	
}

/*
var tabHash = {}

tabHash.init = function(){
	
	var $uiTabs = $('div#uiTabs ul.tabs li a');
	var currentUrl = window.location;
	
	//alert(currentUrl);
	
	$($uiTabs).click(function(){
		var thisHash = $(this).attr('href');
		
		newUrl = currentUrl+thisHash;
		
		window.location = newUrl;
	});
	
};

*/

/**
* Copyright (c) 2010 Anders Ekdahl (http://coffeescripter.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.2.4
*
* Demo and documentation: http://coffeescripter.com/code/ad-gallery/
*/
(function($) {
    $.fn.adGallery = function(options) {
        var defaults = { loader_image: 'loader.gif',
            start_at_index: 0,
            description_wrapper: $('#description'), //
            thumb_opacity: 1,
            animate_first_image: false,
            animation_speed: 400,
            width: 390,
            height: 343,
            display_next_and_prev: true,
            display_back_and_forward: true,
            scroll_jump: 0, // If 0, it jumps the width of the container
            slideshow: {
                enable: true,
                autostart: false,
                speed: 5000,
                start_label: 'Start',
                stop_label: 'Stop',
                stop_on_scroll: true,
                countdown_prefix: '(',
                countdown_sufix: ')',
                onStart: false,
                onStop: false
            },
            effect: 'slide-hori', // or 'slide-vert', 'fade', or 'resize', 'none'
            enable_keyboard_move: true,
            cycle: true,
            callbacks: {
                init: false,
                afterImageVisible: false,
                beforeImageVisible: false
            }
        };
        var settings = $.extend(false, defaults, options);
        if (options && options.slideshow) {
            settings.slideshow = $.extend(false, defaults.slideshow, options.slideshow);
        };
        if (!settings.slideshow.enable) {
            settings.slideshow.autostart = false;
        };
        var galleries = [];
        $(this).each(function() {
            var gallery = new AdGallery(this, settings);
            galleries[galleries.length] = gallery;
        });
        // Sorry, breaking the jQuery chain because the gallery instances
        // are returned so you can fiddle with them
        return galleries;
    };

    function VerticalSlideAnimation(img_container, direction, desc) {
        var current_top = parseInt(img_container.css('top'), 40);
        if (direction == 'left') {
            var old_image_top = '-' + this.image_wrapper_height + 'px';
            img_container.css('top', this.image_wrapper_height + 'px');
        } else {
            var old_image_top = this.image_wrapper_height + 'px';
            img_container.css('top', '-' + this.image_wrapper_height + 'px');
        };
        if (desc) {
            desc.css('bottom', '-' + desc[0].offsetHeight + 'px');
            desc.animate({ bottom: 0 }, this.settings.animation_speed * 2);
        };
        if (this.current_description) {
            this.current_description.animate({ bottom: '-' + this.current_description[0].offsetHeight + 'px' }, this.settings.animation_speed * 2);
        };
        return { old_image: { top: old_image_top },
            new_image: { top: current_top }
        };
    };

    function HorizontalSlideAnimation(img_container, direction, desc) {
        var current_left = parseInt(img_container.css('left'), 10);
        if (direction == 'left') {
            var old_image_left = '-' + this.image_wrapper_width + 'px';
            img_container.css('left', this.image_wrapper_width + 'px');
        } else {
            var old_image_left = this.image_wrapper_width + 'px';
            img_container.css('left', '-' + this.image_wrapper_width + 'px');
        };
        if (desc) {
            desc.css('bottom', '-' + desc[0].offsetHeight + 'px');
            desc.animate({ bottom: 0 }, this.settings.animation_speed * 2);
        };
        if (this.current_description) {
            this.current_description.remove();
        };
        return { old_image: { left: old_image_left },
            new_image: { left: current_left }
        };
    };

    function ResizeAnimation(img_container, direction, desc) {
        var image_width = img_container.width();
        var image_height = img_container.height();
        var current_left = parseInt(img_container.css('left'), 10);
        var current_top = parseInt(img_container.css('top'), 10);
        img_container.css({ width: 0, height: 0, top: this.image_wrapper_height / 2, left: this.image_wrapper_width / 2 });
        return { old_image: { width: 0,
            height: 0,
            top: this.image_wrapper_height / 2,
            left: this.image_wrapper_width / 2
        },
            new_image: { width: image_width,
                height: image_height,
                top: current_top,
                left: current_left
            }
        };
    };

    function FadeAnimation(img_container, direction, desc) {
        img_container.css('opacity', 0);
        return { old_image: { opacity: 0 },
            new_image: { opacity: 1 }
        };
    };

    // Sort of a hack, will clean this up... eventually
    function NoneAnimation(img_container, direction, desc) {
        img_container.css('opacity', 0);
        return { old_image: { opacity: 0 },
            new_image: { opacity: 1 },
            speed: 0
        };
    };

    function AdGallery(wrapper, settings) {
        this.init(wrapper, settings);
    };
    AdGallery.prototype = {
        // Elements
        wrapper: false,
        image_wrapper: false,
        gallery_info: false,
        nav: false,
        loader: false,
        preloads: false,
        thumbs_wrapper: false,
        scroll_back: false,
        scroll_forward: false,
        next_link: false,
        prev_link: false,

        slideshow: false,
        image_wrapper_width: 0,
        image_wrapper_height: 0,
        current_index: 0,
        current_image: false,
        current_description: false,
        nav_display_width: 0,
        settings: false,
        images: false,
        in_transition: false,
        animations: false,
        init: function(wrapper, settings) {
            var context = this;
            this.wrapper = $(wrapper);
            this.settings = settings;
            this.setupElements();
            this.setupAnimations();
            if (this.settings.width) {
                this.image_wrapper_width = this.settings.width;
                this.image_wrapper.width(this.settings.width);
                this.wrapper.width(this.settings.width);
            } else {
                this.image_wrapper_width = this.image_wrapper.width();
            };
            if (this.settings.height) {
                this.image_wrapper_height = this.settings.height;
                this.image_wrapper.height(this.settings.height);
            } else {
                this.image_wrapper_height = this.image_wrapper.height();
            };
            this.nav_display_width = this.nav.width();
            this.current_index = 0;
            this.current_image = false;
            this.current_description = false;
            this.in_transition = false;
            this.findImages();
            if (this.settings.display_next_and_prev) {
                this.initNextAndPrev();
            };
            // The slideshow needs a callback to trigger the next image to be shown
            // but we don't want to give it access to the whole gallery instance
            var nextimage_callback = function(callback) {
                return context.nextImage(callback);
            };
            this.slideshow = new AdGallerySlideshow(nextimage_callback, this.settings.slideshow);
            this.controls.append(this.slideshow.create());
            if (this.settings.slideshow.enable) {
                this.slideshow.enable();
            } else {
                this.slideshow.disable();
            };
            if (this.settings.display_back_and_forward) {
                this.initBackAndForward();
            };
            if (this.settings.enable_keyboard_move) {
                this.initKeyEvents();
            };
            var start_at = parseInt(this.settings.start_at_index, 10);
            if (window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
                start_at = window.location.hash.replace(/[^0-9]+/g, '');
                // Check if it's a number
                if ((start_at * 1) != start_at) {
                    start_at = this.settings.start_at_index;
                };
            };

            this.loading(true);
            this.showImage(start_at,
        function() {
            // We don't want to start the slideshow before the image has been
            // displayed
            if (context.settings.slideshow.autostart) {
                context.preloadImage(start_at + 1);
                context.slideshow.start();
            };
        }
      );
            this.fireCallback(this.settings.callbacks.init);
        },
        setupAnimations: function() {
            this.animations = {
                'slide-vert': VerticalSlideAnimation,
                'slide-hori': HorizontalSlideAnimation,
                'resize': ResizeAnimation,
                'fade': FadeAnimation,
                'none': NoneAnimation
            };
        },
        setupElements: function() {
            this.controls = this.wrapper.find('.ad-controls');
            this.gallery_info = $('<p class="ad-info"></p>');
            this.controls.append(this.gallery_info);
            this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
            this.image_wrapper.empty();
            this.nav = this.wrapper.find('.ad-nav');
            this.thumbs_wrapper = this.nav.find('.ad-thumbs');
            this.preloads = $('<div class="ad-preloads"></div>');
            this.loader = $('<img class="ad-loader" src="' + this.settings.loader_image + '">');
            this.image_wrapper.append(this.loader);
            this.loader.hide();
            $(document.body).append(this.preloads);
        },
        loading: function(bool) {
            if (bool) {
                this.loader.show();
            } else {
                this.loader.hide();
            };
        },
        addAnimation: function(name, fn) {
            if ($.isFunction(fn)) {
                this.animations[name] = fn;
            };
        },
        findImages: function() {
            var context = this;
            this.images = [];
            var thumb_wrapper_width = 0;
            var thumbs_loaded = 0;
            var thumbs = this.thumbs_wrapper.find('a');
            var thumb_count = thumbs.length;
            if (this.settings.thumb_opacity < 1) {
                thumbs.find('img').css('opacity', this.settings.thumb_opacity);
            };
            thumbs.each(
        function(i) {
            var link = $(this);
            var detailPageURL = '';
            if (link.attr('href')) { detailPageURL = link.attr('href'); }

            var urlTitle = '';
            if (link.attr('title')) { urlTitle = link.attr('title'); }

            var img = $('img', link);
            var image_src = img.attr('longdesc');
            var thumb = link.find('img');
            // Check if the thumb has already loaded
            if (!context.isImageLoaded(thumb[0])) {
                thumb.load(
              function() {
                  thumb_wrapper_width += this.parentNode.parentNode.offsetWidth;
                  thumbs_loaded++;
              }
            );
            } else {
                thumb_wrapper_width += thumb[0].parentNode.parentNode.offsetWidth;
                thumbs_loaded++;
            };
            link.addClass('ad-thumb' + i);
            link.click(
            function() {
                context.showImage(i);
                context.slideshow.stop();
                return false;
            }
          ).hover(
            function() {
                if (!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
                    $(this).find('img').fadeTo(300, 1);
                };
                context.preloadImage(i);
            },
            function() {
                if (!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
                    $(this).find('img').fadeTo(300, context.settings.thumb_opacity);
                };
            }
          );
            var link = false;
            if (thumb.data('ad-link')) {
                link = thumb.data('ad-link');
            } else if (thumb.attr('longdesc') && thumb.attr('longdesc').length) {
                link = thumb.attr('longdesc');
            };
            var desc = false;
            if (thumb.data('ad-desc')) {
                desc = thumb.data('ad-desc');
            } else if (thumb.attr('alt') && thumb.attr('alt').length) {
                desc = thumb.attr('alt');
            };
            var title = false;
            if (thumb.data('ad-title')) {
                title = thumb.data('ad-title');
            } else if (thumb.attr('title') && thumb.attr('title').length) {
                title = thumb.attr('title');
            };
            var linkText = thumb[0].className.match(/linkText\:\(([^\)]+)\)/);
            if (linkText !== null) {
                linkText = linkText[1];
            };
            context.images[i] = { thumb: thumb.attr('src'), image: image_src, error: false,
                preloaded: false, desc: desc, title: title, size: false,
                link: link, detailPageURL: detailPageURL, urlTitle: urlTitle
            };
        }
      );
            // Wait until all thumbs are loaded, and then set the width of the ul
            var inter = setInterval(
        function() {
            if (thumb_count == thumbs_loaded) {
                thumb_wrapper_width -= 100;
                var list = context.nav.find('.ad-thumb-list');
                list.css('width', thumb_wrapper_width + 'px');
                var i = 1;
                var last_height = list.height();
                while (i < 201) {
                    list.css('width', (thumb_wrapper_width + i) + 'px');
                    if (last_height != list.height()) {
                        break;
                    }
                    last_height = list.height();
                    i++;
                }
                clearInterval(inter);
            };
        },
        100
      );
        },
        initKeyEvents: function() {
            var context = this;
            $(document).keydown(
        function(e) {
            if (e.keyCode == 39) {
                // right arrow
                context.nextImage();
                context.slideshow.stop();
            } else if (e.keyCode == 37) {
                // left arrow
                context.prevImage();
                context.slideshow.stop();
            };
        }
      );
        },
        initNextAndPrev: function() {
            this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
            this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
            this.image_wrapper.append(this.next_link);
            this.image_wrapper.append(this.prev_link);
            var context = this;
            this.prev_link.add(this.next_link).mouseover(
        function(e) {
            // IE 6 hides the wrapper div, so we have to set it's width
            //$(this).css('height', context.image_wrapper_height);
            //$(this).find('div').show();
        }
      ).mouseout(
        function(e) {
            //$(this).find('div').hide();
        }
      ).click(
        function() {
            if ($(this).is('.ad-next')) {
                context.nextImage();
                context.slideshow.stop();
            } else {
                context.prevImage();
                context.slideshow.stop();
            };
        }
      ).find('div').css('opacity', 1);
        },
        initBackAndForward: function() {
            var context = this;
            this.scroll_forward = $('<div class="ad-forward"></div>');
            this.scroll_back = $('<div class="ad-back"></div>');
            this.nav.append(this.scroll_forward);
            this.nav.prepend(this.scroll_back);
            var has_scrolled = 0;
            var thumbs_scroll_interval = false;
            $(this.scroll_back).add(this.scroll_forward).click(
        function() {
            // We don't want to jump the whole width, since an image
            // might be cut at the edge
            var width = context.nav_display_width - 50;
            if (context.settings.scroll_jump > 0) {
                var width = context.settings.scroll_jump;
            };
            if ($(this).is('.ad-forward')) {
                var left = context.thumbs_wrapper.scrollLeft() + width;
            } else {
                var left = context.thumbs_wrapper.scrollLeft() - width;
            };
            if (context.settings.slideshow.stop_on_scroll) {
                context.slideshow.stop();
            };
            context.thumbs_wrapper.animate({ scrollLeft: left + 'px' });
            return false;
        }
      ).css('opacity', 1).hover(
        function() {
            var direction = 'left';
            if ($(this).is('.ad-forward')) {
                direction = 'right';
            };
            thumbs_scroll_interval = setInterval(
            function() {
                has_scrolled++;
                // Don't want to stop the slideshow just because we scrolled a pixel or two
                if (has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
                    context.slideshow.stop();
                };
                var left = context.thumbs_wrapper.scrollLeft() + 1;
                if (direction == 'left') {
                    left = context.thumbs_wrapper.scrollLeft() - 1;
                };
                context.thumbs_wrapper.scrollLeft(left);
            },
            10
          );
            $(this).css('opacity', 1);
        },
        function() {
            has_scrolled = 0;
            clearInterval(thumbs_scroll_interval);
            $(this).css('opacity', 1);
        }
      );
        },
        _afterShow: function() {
            this.gallery_info.html((this.current_index + 1) + ' / ' + this.images.length);
            if (!this.settings.cycle) {
                // Needed for IE
                this.prev_link.show().css('height', this.image_wrapper_height);
                this.next_link.show().css('height', this.image_wrapper_height);
                if (this.current_index == (this.images.length - 1)) {
                    this.next_link.hide();
                };
                if (this.current_index == 0) {
                    this.prev_link.hide();
                };
            };
            this.fireCallback(this.settings.callbacks.afterImageVisible);
        },
        /**
        * Checks if the image is small enough to fit inside the container
        * If it's not, shrink it proportionally
        */
        _getContainedImageSize: function(image_width, image_height) {
            if (image_height > this.image_wrapper_height) {
                var ratio = image_width / image_height;
                image_height = this.image_wrapper_height;
                image_width = this.image_wrapper_height * ratio;
            };
            if (image_width > this.image_wrapper_width) {
                var ratio = image_height / image_width;
                image_width = this.image_wrapper_width;
                image_height = this.image_wrapper_width * ratio;
            };
            return { width: image_width, height: image_height };
        },
        /**
        * If the image dimensions are smaller than the wrapper, we position
        * it in the middle anyway
        */
        _centerImage: function(img_container, image_width, image_height) {
            img_container.css('top', '0px');
            if (image_height < this.image_wrapper_height) {
                var dif = this.image_wrapper_height - image_height;
                img_container.css('top', (dif / 2) + 'px');
            };
            img_container.css('left', '0px');
            if (image_width < this.image_wrapper_width) {
                var dif = this.image_wrapper_width - image_width;
                img_container.css('left', (dif / 2) + 'px');
            };
        },
        _getDescription: function(image) {
            var desc = false;
            if (image.desc.length || image.title.length) {
                var title = '';
                if (image.title.length) {
                    title = '<strong class="ad-description-title">' + image.title + '</strong>';
                };
                var desc = '';
                if (image.desc.length) {
                    desc = '<span>' + image.desc + '</span>';
                };
                desc = '<p class="ad-image-description">' + title + desc + '</p>';
                if (image.detailPageURL.length) {
                    var defaultTitle = "See detail page.";
                    if (image.urlTitle.length) { defaultTitle = image.urlTitle; }
                    desc = desc + '<p><a href="' + image.detailPageURL + '">' + defaultTitle + '</a></p>';
                }
                desc = $(desc);
            };
            return desc;
        },
        /**
        * @param function callback Gets fired when the image has loaded, is displaying
        *                          and it's animation has finished
        */
        showImage: function(index, callback) {
            if (this.images[index] && !this.in_transition) {
                var context = this;
                var image = this.images[index];
                this.in_transition = true;
                if (!image.preloaded) {
                    this.loading(true);
                    this.preloadImage(index, function() {
                        context.loading(false);
                        context._showWhenLoaded(index, callback);
                    });
                } else {
                    this._showWhenLoaded(index, callback);
                };
            };
        },
        /**
        * @param function callback Gets fired when the image has loaded, is displaying
        *                          and it's animation has finished
        */
        _showWhenLoaded: function(index, callback) {
            if (this.images[index]) {
                var context = this;
                var image = this.images[index];
                var img_container = $(document.createElement('div')).addClass('ad-image');
                var img = $(new Image()).attr('src', image.image);
                if (image.link) {
                    var link = $('<a href="' + image.link + '" target="_blank"></a>');
                    link.append(img);
                    img_container.append(link);
                } else {
                    img_container.append(img);
                }
                this.image_wrapper.prepend(img_container);
                var size = this._getContainedImageSize(image.size.width, image.size.height);
                img.attr('width', size.width);
                img.attr('height', size.height);
                img_container.css({ width: size.width + 'px', height: size.height + 'px' });
                this._centerImage(img_container, size.width, size.height);
                var desc = this._getDescription(image, img_container);
                if (desc) {
                    if (!this.settings.description_wrapper) {
                        img_container.append(desc);
                        var width = size.width - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
                        desc.css('width', width + 'px');
                    } else {
                        this.settings.description_wrapper.append(desc);
                    }
                };
                this.highLightThumb(this.nav.find('.ad-thumb' + index));

                var direction = 'right';
                if (this.current_index < index) {
                    direction = 'left';
                };
                this.fireCallback(this.settings.callbacks.beforeImageVisible);
                if (this.current_image || this.settings.animate_first_image) {
                    var animation_speed = this.settings.animation_speed;
                    var easing = 'swing';
                    var animation = this.animations[this.settings.effect].call(this, img_container, direction, desc);
                    if (typeof animation.speed != 'undefined') {
                        animation_speed = animation.speed;
                    };
                    if (typeof animation.easing != 'undefined') {
                        easing = animation.easing;
                    };
                    if (this.current_image) {
                        var old_image = this.current_image;
                        var old_description = this.current_description;
                        old_image.animate(animation.old_image, animation_speed, easing,
              function() {
                  old_image.remove();
                  if (old_description) old_description.remove();
              }
            );
                    };
                    img_container.animate(animation.new_image, animation_speed, easing,
            function() {
                context.current_index = index;
                context.current_image = img_container;
                context.current_description = desc;
                context.in_transition = false;
                context._afterShow();
                context.fireCallback(callback);
            }
          );
                } else {
                    this.current_index = index;
                    this.current_image = img_container;
                    context.current_description = desc;
                    this.in_transition = false;
                    context._afterShow();
                    this.fireCallback(callback);
                };
            };
        },
        nextIndex: function() {
            if (this.current_index == (this.images.length - 1)) {
                if (!this.settings.cycle) {
                    return false;
                };
                var next = 0;
            } else {
                var next = this.current_index + 1;
            };
            return next;
        },
        nextImage: function(callback) {
            var next = this.nextIndex();
            if (next === false) return false;
            this.preloadImage(next + 1);
            this.showImage(next, callback);
            return true;
        },
        prevIndex: function() {
            if (this.current_index == 0) {
                if (!this.settings.cycle) {
                    return false;
                };
                var prev = this.images.length - 1;
            } else {
                var prev = this.current_index - 1;
            };
            return prev;
        },
        prevImage: function(callback) {
            var prev = this.prevIndex();
            if (prev === false) return false;
            this.preloadImage(prev - 1);
            this.showImage(prev, callback);
            return true;
        },
        preloadAll: function() {
            var context = this;
            var i = 0;
            function preloadNext() {
                if (i < context.images.length) {
                    i++;
                    context.preloadImage(i, preloadNext);
                };
            };
            context.preloadImage(i, preloadNext);
        },
        preloadImage: function(index, callback) {
            if (this.images[index]) {
                var image = this.images[index];
                if (!this.images[index].preloaded) {
                    var img = $(new Image());
                    img.attr('src', image.image);
                    if (!this.isImageLoaded(img[0])) {
                        this.preloads.append(img);
                        var context = this;
                        img.load(
              function() {
                  image.preloaded = true;
                  image.size = { width: this.width, height: this.height };
                  context.fireCallback(callback);
              }
            ).error(
              function() {
                  image.error = true;
                  image.preloaded = false;
                  image.size = false;
              }
            );
                    } else {
                        image.preloaded = true;
                        image.size = { width: img[0].width, height: img[0].height };
                        this.fireCallback(callback);
                    };
                } else {
                    this.fireCallback(callback);
                };
            };
        },
        isImageLoaded: function(img) {
            if (typeof img.complete != 'undefined' && !img.complete) {
                return false;
            };
            if (typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
                return false;
            };
            return true;
        },
        highLightThumb: function(thumb) {
            this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
            thumb.addClass('ad-active');
            if (this.settings.thumb_opacity < 1) {
                this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
                thumb.find('img').fadeTo(300, 1);
            };
            var left = thumb[0].parentNode.offsetLeft;
            left -= (this.nav_display_width / 2) - (thumb[0].offsetWidth / 2);
            this.thumbs_wrapper.animate({ scrollLeft: left + 'px' });
        },
        fireCallback: function(fn) {
            if ($.isFunction(fn)) {
                fn.call(this);
            };
        }
    };

    function AdGallerySlideshow(nextimage_callback, settings) {
        this.init(nextimage_callback, settings);
    };
    AdGallerySlideshow.prototype = {
        start_link: false,
        stop_link: false,
        countdown: false,
        controls: false,

        settings: false,
        nextimage_callback: false,
        enabled: false,
        running: false,
        countdown_interval: false,
        init: function(nextimage_callback, settings) {
            var context = this;
            this.nextimage_callback = nextimage_callback;
            this.settings = settings;
        },
        create: function() {
            this.start_link = $('<span class="ad-slideshow-start">' + this.settings.start_label + '</span>');
            this.stop_link = $('<span class="ad-slideshow-stop">' + this.settings.stop_label + '</span>');
            this.countdown = $('<span class="ad-slideshow-countdown"></span>');
            this.controls = $('<div class="ad-slideshow-controls"></div>');
            //this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
            this.countdown.hide();

            var context = this;
            this.start_link.click(
        function() {
            context.start();
        }
      );
            this.stop_link.click(
        function() {
            context.stop();
        }
      );
            $(document).keydown(
        function(e) {
            if (e.keyCode == 83) {
                // 's'
                if (context.running) {
                    context.stop();
                } else {
                    context.start();
                };
            };
        }
      );
            return this.controls;
        },
        disable: function() {
            this.enabled = false;
            this.stop();
            this.controls.hide();
        },
        enable: function() {
            this.enabled = true;
            this.controls.show();
        },
        toggle: function() {
            if (this.enabled) {
                this.disable();
            } else {
                this.enable();
            };
        },
        start: function() {
            if (this.running || !this.enabled) return false;
            var context = this;
            this.running = true;
            this.controls.addClass('ad-slideshow-running');
            this._next();
            this.fireCallback(this.settings.onStart);
            return true;
        },
        stop: function() {
            if (!this.running) return false;
            this.running = false;
            this.countdown.hide();
            this.controls.removeClass('ad-slideshow-running');
            clearInterval(this.countdown_interval);
            this.fireCallback(this.settings.onStop);
            return true;
        },
        _next: function() {
            var context = this;
            var pre = this.settings.countdown_prefix;
            var su = this.settings.countdown_sufix;
            clearInterval(context.countdown_interval);
            this.countdown.show().html(pre + (this.settings.speed / 1000) + su);
            var slide_timer = 0;
            this.countdown_interval = setInterval(
        function() {
            slide_timer += 1000;
            if (slide_timer >= context.settings.speed) {
                var whenNextIsShown = function() {
                    // A check so the user hasn't stoped the slideshow during the
                    // animation
                    if (context.running) {
                        context._next();
                    };
                    slide_timer = 0;
                };
                if (!context.nextimage_callback(whenNextIsShown)) {
                    context.stop();
                };
                slide_timer = 0;
            };
            var sec = parseInt(context.countdown.text().replace(/[^0-9]/g, ''), 10);
            sec--;
            if (sec > 0) {
                context.countdown.html(pre + sec + su);
            };
        },
        1000
      );
        },
        fireCallback: function(fn) {
            if ($.isFunction(fn)) {
                fn.call(this);
            };
        }
    };
})(jQuery);


$(function() {

    var galleries = $('.ad-gallery').adGallery();
    $('#switch-effect').change(
      function() {
          galleries[0].settings.effect = $(this).val();
          return false;
      }
    );
    $('#toggle-slideshow').click(
      function() {
          galleries[0].slideshow.toggle();
          return false;
      }
    );
    $('#toggle-description').click(
      function() {
          if (!galleries[0].settings.description_wrapper) {
              galleries[0].settings.description_wrapper = $('#descriptions');
          } else {
              galleries[0].settings.description_wrapper = false;
          }
          return false;
      }
    );
});
