$(function() {

	commonStuff();

	if ($('#bigcarousel').length) Carousel.big();
	if ($('.pagetop .lucy').length) Carousel.pagetop();
	if ($('#productcarousel').length) Carousel.product();
	
	if ($('.subnav').length && ($('.bulleted.h4ed').length || $('.blocked h3').length) && (!$('.blocked.reports').length)) gogoSubSubNav();
	
	if ($('.boomer').length) $.boomer();
	
	if ($('#gmap').length) Gmap.launch();
});

var Carousel = {
	big: function() {
		$('#bigcarousel').lucy({
			displayed: 1,
			width: 980,
			height: 335,
			scrollbar: true,
			scrollbarheight: 7,
			scrollbarwidth: 14 * $('#bigcarousel').find('.view > ul > li').length, //make sure that the width of the overall bar is enough for the background image
			left: ".right",
			right: ".left",
			scrollbarsnap: true,
			animtime : 1000
		});
	},
	pagetop: function() {
		$('.pagetop .lucy').lucy({
			displayed: 1,
			width: 635,
			height: 290,
			left: ".right",
		    right: ".left",
			numbar: true
		});
		if ($('.pagetop .lucy > .view > ul > li').length == 1) $('.pagetop .lucy > a').remove();
	},
	product: function() {
		$('#productcarousel').lucy({
			displayed: 1,
			width: 295,
			height: 295,
			left: ".right",
			right: ".left"
		});
	}
};

var commonStuff = function() {
	$('#search input,footer input[type=text]').blur(function() {
		if ($(this).val() !== "") $(this).addClass("focussed");
		else $(this).removeClass("focussed");
	});
	
	$('#totop').click(function(e) {
	    e.preventDefault();
	    $('html, body').animate({scrollTop:0}, 'slow');
	});
	
	$('#mailchimp-form').prev().click(function(e) {
	    e.preventDefault();
	    $(this).fadeOut("fast", function() {
	    	$(this).remove();
	    	$('#mailchimp-form').fadeIn();
	    });
	});
	$('#mailchimp-form').submit(function() {
	    var f = $(this);
	    $.ajax({
	    	url: f.attr('action'),
	    	data: f.serialize() + '&isAjax=1',
	    	dataType: 'jsonp',
	    	success: function(r) {
	    		if (r.worked) f.empty().html("<span>Thank You For Subscribing</span>");
	    		else alert(r.message);
	    	}
	    });
	    return false;
	});
	
	if ($.support.opacity) Konami.init();
	
	$('a[href^="http://"],a[href^="https://"]').attr({target: "_blank"});
	
	fixHeight();
	$(window).resize(function() { fixHeight(); });
};

var fixHeight = function() {
	var o = $('section > div');
	
	o.attr("style", "").removeAttr("style");
	
	var t = $(window).height() - 532;
	
	o.css({ minHeight: t + "px" });
};

var Form = {
	contact: function(f) {
		$.ajax("/do_contact", {
			type: "POST",
			dataType: 'json',
			data: f.serialize()+'&ajax=1',
			success: function(data) {
				var block = f;
				if (data.worked) {
					var formelements = block.children(); //seperate this from the fadeout ness below for better performance
					formelements.fadeOut("fast", function() {
						$(this).remove();
						if (block.find("p").length < 1) block.append('<div class="enquiry-thanks">'+data.message+'</div>');
					});
					if (block.find('.enquiry-error').length) block.find('.enquiry-error').fadeOut('fast', function() { $(this).remove(); });
				}
				else {
					if (!block.find('.enquiry-error').length) {
						block.prepend('<p style="height:0;overflow:hidden;margin-top:5px" class="enquiry-error">Please check the <u>red</u> fields and try again.</p>');
						block.find('.enquiry-error').animate({height:"23px"}, "slow");
					}
					f.find("input, textarea, select").attr("style", "").removeAttr("style");
					$.each(data.errors, function(i, val) {
						f.find("input[name="+val+"], textarea[name="+val+"], select[name="+val+"]").css({ borderColor: "#bc3732" });
					});
				}
			}
		});
		return false;
	}
};

var Gmap = {
	//the map
	m: null,
	
	//map pins
	i: null,

	init: function() {
		this.i = new google.maps.MarkerImage('/media/images/icon-map.png', new google.maps.Size(44, 48));
	
		var c = new google.maps.LatLng(52.959656, -0.031836);

		this.m = new google.maps.Map(document.getElementById("gmap"), {
			zoom: 12,
			center: c,
			minZoom: 3,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});
		
		var mr = new google.maps.Marker({
			position: c,
			map: this.m,
			icon: this.i,
			title: "Calders and Grandidge"
		});
		
		gogoSubSubNav(); //problem?
	},

	launch: function() {
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=Gmap.init";
		document.body.appendChild(script);
	}
};

var gogoSubSubNav = function() {
	$('.subnav a[href="' + document.location.pathname + '"]').after('<menu class="subsubnav"></menu>');
	
	var q = $('.bulleted.h4ed h4,.blocked h3,.indented h4');
	
	var s = $('.subnav .subsubnav');
	var c = q.length;
	c--;	// eaches index is zero based!
	
	q.each(function(i, v) {
		var t = $(this).html();
		s.append('<li><a href="#h4' + i + '">' + t + '</a></li>');
		$(this).html('<a name="h4' + i + '">' + t + '</a>');
		if (i == c) s.fadeIn(1000);
	});
};

var Konami = {

	barrelRoll: function() {
		c = 360;
		setInterval(function(){
			if (c < 1) return;
			var css = 'rotate(' + --c + 'deg) skewX(' + c + 'deg)';
			
			$('body').css({ 
				"-webkit-transform": css + " rotateX(" + c + "deg)",
				"-moz-transform": css,
				"-ms-transform": css,
				"-o-transform": css
			});
			
		}, 360/1000);
	},
	
	init: function() {
		var k = [];
		//http://unwrongest.com/blog/konami-code-why-so-verbose-when-you-can-make-it-in-140-characters/
		addEventListener("keyup", function(e) {
			k.push(e.keyCode);
			if (k.toString().indexOf("38,38,40,40,37,39,37,39,66,65") >= 0) {
				Konami.barrelRoll();
				k = [];
			} 
		}, true);
	
	}

};

// lucy v15
(function(f){f.fn.lucy=function(h){var b,a,e,g,d;g={mover:function(c,d){if(a.notloner){var e=0-parseInt(a.carousel.css("margin-left"),10);a.carousel.eq(0).animate({marginLeft:c},b.animtime,b.easing,function(){if(b.displayed==1&&(e/=b.width+b.margin,a.items.eq(e).find("iframe").length)){var c=a.items.eq(e).html();a.items.eq(e).empty().html(c)}var f=parseInt(a.carousel.css("margin-left"),10),c=0-f/(b.width+b.margin)+1;b.scrollbar?b.scrollbar2d?(a.scrollbar.find(".active").removeClass("active"),a.scrollbar.find("a[rel="+ c+"]").addClass("active")):(f=(0-f/a.carousel.width())*a.scrollmarker.parent().width(),b.scrollbarsnap?a.scrollmarker.css({marginLeft:f}):a.scrollmarker.animate({marginLeft:f},"fast")):b.numbar&&(a.numbar.find(".active").removeClass("active"),a.numbar.find("a[rel="+c+"]").addClass("active"));typeof d=="function"&&d();typeof b.afterAnimation=="function"&&b.afterAnimation(c)})}},reset:function(){var c=false;a.timer!==null&&(d.stop(),c=true);b.autoscroll&&c?g.mover(0,d.go()):g.mover(0)}};d={init:function(c){b= f.extend({},{displayed:1,width:300,height:200,margin:10,left:".left",right:".right",autoscroll:false,easing:"swing",speed:1E3,animtime:"fast",scrollbar:false,scrollbarelem:".scrollbar",scrollbarheight:0,scrollbarwidth:200,scrollbarsnap:false,numbar:false,numbarelem:".numbers",afterAnimation:null,freezeOnBlur:true,indicator:false,playpause:true,scrollbar2d:false,scrollbarelemw:0,scrollbarelemh:0,indicatorbar:false},c);a={timer:null};a.div=e;a.carousel=e.find(".view > ul");a.items=a.carousel.children(); a.count=a.items.length;a.items.width(b.width).height(b.height).css({marginRight:b.margin});a.carousel.width(a.count*(b.width+b.margin));e.find(".view").width(b.displayed*(b.width+b.margin)-b.margin).height(b.height);if(b.indicator)f.support.opacity?(e.append('<div class="timer"><div class="outer"><div class="inner"></div></div></div>'),a.idegrees=0,a.indicator=e.find(".timer"),a.imask=a.indicator.find(".outer"),a.irotator=a.imask.find(".inner"),b.playpause&&a.indicator.click(function(){a.timer=== null?d.go():d.stop()})):b.indicator=false;if(b.indicatorbar&&(e.append('<div class="indicatorbar"><div></div></div>'),a.iwidth=0,a.indicator=e.find(".indicatorbar div"),b.playpause))e.append('<a class="playpause" href="#"></a>'),a.playpause=e.find(".playpause"),a.playpause.click(function(b){b.preventDefault();a.timer===null?d.go():d.stop()});a.notloner=a.items.length>1?true:false;if(a.notloner){if(b.scrollbar){a.scrollbar=e.find(b.scrollbarelem);a.scrollbar.height(b.scrollbarheight).width(b.scrollbarwidth); for(c=1;c<=a.count;c++)a.scrollbar.append('<a href="#" rel="'+c+'"></a>');c=a.scrollbar.find("a");b.scrollbar2d?(c.height(b.scrollbarelemh).width(b.scrollbarelemw),c.eq(0).addClass("active")):(a.scrollbar.prepend('<div class="scrollmarker"></div>'),a.scrollmarker=e.find(".scrollmarker"),a.scrollmarker.width(e.find(".view").width()/a.carousel.width()*a.scrollbar.width()).height(b.scrollbarheight),c.width(1/a.count*a.scrollbar.width()).css({position:"relative",top:0-b.scrollbarheight}));c.each(function(){f(this).click(function(c){c.preventDefault(); (b.indicator||b.indicatorbar)&&b.playpause&&a.timer!==null&&d.stop();d.moveTo(f(this).attr("rel"))})})}else if(b.numbar){a.numbar=e.find(b.numbarelem);for(var c="<ul>",g=1;g<=a.count;g++)c=c+'<li><a href="#" rel="'+g+'">'+g+"</a></li>";a.numbar.html(c+"</ul>");a.numbar.find("a").click(function(c){c.preventDefault();(b.indicator||b.indicatorbar)&&b.playpause&&a.timer!==null&&d.stop();d.moveTo(f(this).attr("rel"))});a.numbar.find("li:first-child a").addClass("active")}e.find(b.left).click(function(c){c.preventDefault(); (b.indicator||b.indicatorbar)&&b.playpause&&a.timer!==null&&d.stop();a.carousel.is(":animated")||d.moveLeft()});e.find(b.right).click(function(c){c.preventDefault();(b.indicator||b.indicatorbar)&&b.playpause&&a.timer!==null&&d.stop();a.carousel.is(":animated")||d.moveRight()});b.autoscroll&&(d.go(),(!b.indicator&&!b.indicatorbar||!b.playpause)&&e.hover(function(){d.stop()},function(){d.go()}),b.freezeOnBlur&&(f(window).bind("blur",function(){d.stop()}),f(window).bind("focus",function(){d.go()})))}}, go:function(){if(a.timer===null)b.indicator?(a.timer=setInterval(function(){var b="rotate("+a.idegrees+"deg)";a.idegrees+=2;a.irotator.css({"-webkit-transform":b,"-moz-transform":b,"-ms-transform":b,"-o-transform":b});a.idegrees>180&&a.imask.addClass("halfway");if(a.idegrees>360)a.imask.removeClass("halfway"),a.idegrees=0,d.moveLeft()},b.speed/180),b.playpause&&a.indicator.removeClass("pause").addClass("play")):b.indicatorbar?(a.timer=setInterval(function(){a.iwidth++;a.indicator.width(a.iwidth+"%"); if(a.iwidth>100)a.iwidth=0,a.indicator.width(0),d.moveLeft()},b.speed/100),b.playpause&&a.playpause.removeClass("pause").addClass("play")):a.timer=setInterval(function(){d.moveLeft()},b.speed)},moveLeft:function(){parseInt(a.carousel.css("margin-left"),10)-b.displayed*b.margin+parseInt(a.carousel.width(),10)<=b.displayed*b.width?g.reset():g.mover("-="+(b.width+b.margin))},moveRight:function(){var c="+="+(b.width+b.margin);parseInt(a.carousel.css("margin-left"),10)>=0&&(c="-="+(a.count-b.displayed)* (b.width+b.margin));g.mover(c)},moveTo:function(c){var d=a.count-b.displayed;c>d?c=d:c--;g.mover(0-c*(b.width+b.margin))},stop:function(){b.indicator&&b.playpause&&a.indicator.removeClass("play").addClass("pause");b.indicatorbar&&b.playpause&&a.playpause.removeClass("play").addClass("pause");clearInterval(a.timer);a.timer=null}};return this.each(function(){e=f(this);d[h]?(b=e.data("settings"),a=e.data("constants"),d[h](Array.prototype.slice.call(arguments,1))):typeof h==="object"||!h?(b={},a={},d.init(h)): f.error("Method "+h+" does not exist fool!");e.data("settings",b);e.data("constants",a)})}})(jQuery);

// boomer v4
(function(a){var e={close:function(){a.support.opacity?a("#boomer").fadeOut("fast",function(){a("#boomer .instructions").click();a("#boomer img").remove()}):(a("#boomer").hide(),a("#boomer .instructions").click(),a("#boomer img").remove())},getRatioed:function(a,b,d){return a/b*d},getSize:function(c,b){var d=a(window).height()-40,f=a(window).width()-40;if(c>f||b>d)b>d&&(c=e.getRatioed(d,b,c),b=d),c>f&&(b=e.getRatioed(f,c,b),c=f),c=Math.round(c),b=Math.round(b);return{width:c,height:b}},init:function(c){c= a.extend({targetClass:".boomer"},c);a("body").append('<div id="boomer"><div id="boomer-back"></div><div id="boomer-box"><div class="contents"><div class="controls"><a class="close" href="#">Exit</a><a class="reset" href="#">Reset Zoom</a></div><div class="caption"></div></div></div>');a("#boomer, #boomer-back").width(a(window).width()).height(a(window).height());a(c.targetClass).live("click",function(b){b.preventDefault();e.open(a(this))});a("#boomer .close").click(function(a){a.preventDefault();e.close()});a("#boomer .reset").click(function(a){a.preventDefault(); e.resetZoom()});a(window).resize(function(){a("#boomer, #boomer-back, #boomer .instructions").width(a(window).width()).height(a(window).height());if(a("#boomer img").length){var b=e.getSize(a("#boomer").data("img").width,a("#boomer").data("img").height);a("#boomer img, #boomer .contents,#boomer .caption").width(b.width);a("#boomer .controls").width(b.width-10);a("#boomer .contents").height(b.height).css({marginTop:0-b.height/2})}});a("#boomer .contents").mousewheel(function(b,d){a(this).find("img").length&& e.zoom(b,d);return false}).mousemove(function(b){a(this).find("img").length&&e.reposition(b.pageX,b.pageY);return false});a(document).keyup(function(a){a.keyCode==27&&e.close()})},open:function(c){a.support.opacity?a("#boomer").fadeIn():a("#boomer").show();a("#boomer").append('<div class="instructions"></div>');a("#boomer .instructions").width(a(window).width()).height(a(window).height()).click(function(){a(this).remove()});a("#boomer .contents, #boomer .controls").attr("style","");var b="",b=c.attr("title"); b===void 0&&(b=c.prop("title"));e.showImage(c.attr("href"),b)},preload:function(c,b){var d=new Image;if(b){if(b.loaded&&typeof b.loaded=="function")d.onload=function(){b.loaded({width:d.width,height:d.height,src:d.src,obj:a("<img />").attr("src",d.src)})};if(b.loaded&&typeof b.error=="function")d.onerror=function(a){b.error(a)}}d.src=c},reposition:function(c,b){var d=a("#boomer .contents"),f=d.offset(),e=d.find("img"),g=c-f.left,f=b-f.top,g=0-(g/d.width()*e.width()-g),d=0-(f/d.height()*e.height()- f),g=Math.ceil(g),d=Math.ceil(d);g>0&&(g=0);d>0&&(d=0);e.css({left:g+"px",top:d+"px"})},resetZoom:function(){a("#boomer img").width(a("#boomer .contents").width())},showImage:function(c,b){a("#boomer .caption").empty();e.preload(c,{loaded:function(d){b.length>0&&a("#boomer .caption").html("<p>"+b+"</p>");a("#boomer .contents").prepend(d.obj);var c=e.getSize(d.width,d.height);a("#boomer img,#boomer .caption").width(c.width);a("#boomer .controls").width(c.width-10);a("#boomer").data("img",{width:d.width, height:d.height});c.marginTop=0-c.height/2;a.support.opacity?a("#boomer-box .contents").animate(c,"fast",function(){a("#boomer img").fadeIn()}):(a("#boomer-box .contents").css(c),a("#boomer img").show())},error:function(){e.close();alert("Image does not exist: "+c)}})},zoom:function(c,b){var d=a("#boomer .contents").width(),f=a("#boomer").data("img").width,h=a("#boomer img").width()+b*60;h>f&&(h=f);h<=d?(d!=f?e.reposition(0,0):e.reposition(0,c.pageY),e.resetZoom()):(a("#boomer img").width(h),e.reposition(c.pageX, c.pageY))}};a.boomer=function(c){if(e[c])return e[c].apply(this,Array.prototype.slice.call(arguments,1));else if(typeof c==="object"||!c)return e.init(c);else a.error("Method "+c+" does not exist fool!");return a(this)}})(jQuery);

//jquery mousewheel 3.0.4 http://brandonaaron.net/code/mousewheel/docs
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(i){var g=i||window.event,f=[].slice.call(arguments,1),j=0,h=true,e=0,d=0;i=c.event.fix(g);i.type="mousewheel";if(i.wheelDelta){j=i.wheelDelta/120}if(i.detail){j=-i.detail/3}d=j;if(g.axis!==undefined&&g.axis===g.HORIZONTAL_AXIS){d=0;e=-1*j}if(g.wheelDeltaY!==undefined){d=g.wheelDeltaY/120}if(g.wheelDeltaX!==undefined){e=-1*g.wheelDeltaX/120}f.unshift(i,j,e,d);return c.event.handle.apply(this,f)}})(jQuery);
