$(function() {

	if ($('#testimonials').length) doLucy($('#testimonials'), {
		width: 280,
		height: 190,
		autoscroll: false,
		margin: 0,
		left: ".right",
		right: ".left"
	});

	if ($('.widecarousel.narrow').length) doLucy($('.widecarousel.narrow'), {
		width: 648,
		height: 221,
		autoscroll: false,
		margin: 0,
		left: ".right",
		right: ".left"
	});
	else if ($('.widecarousel').length) doLucy($('.widecarousel'), {
		width: 648,
		height: 246,
		autoscroll: false,
		margin: 0,
		left: ".right",
		right: ".left"
	});

	Quote.init();

	if ($('#quickenquiry').length) {
	
		$('#quickenquiry input.magic').blur(function() {
			if ($(this).val() == "") $(this).css({ background: "none" });
			else $(this).css({ background: "#515151" });
		});
		$('#quickenquiry textarea.magic').focus(function() {
			if ($(this).val() == "Enquiry:") $(this).val('');
		}).blur(function() {
			if ($(this).val() == "") $(this).val('Enquiry:');
		});
	
	}

	if ($('.scrollable').length) Scrollings.init();
	
	if ($('#gmap').length) Gmap.launch();

	if ($('#enquiryform.dupe').length) Dupequoter.init();
	
	if ($('#enquiryform').length) $('#enquiryform').submit(function() {
		Form.general($(this), false);
		return false;
	});
	if ($('#quickenquiry').length) $('#quickenquiry form').submit(function() {
		Form.general($(this), true);
		return false;
	});

	if (window.location.hash) {
		var hash = window.location.hash;
		hash = hash.replace('#', "");
		if (hash == "quote") setTimeout("$('#quoteform .opener').click();", 500);
	}

	$('#totop').click(function(e) {
		e.preventDefault();
		$('html, body').animate({ scrollTop: 0 }, 'slow');
	});

	Animation.init();

	fixHeight();
	$(window).resize(function() { fixHeight(); });

	$('a[href^="http://"]').attr({target: "_blank", title: "Opens in a new window"});
});

var Animation = {
	init: function() {
		$('header .col-left').append('<div id="animation" class="p1"></div>');
		$('h1').addClass('p1');
		setInterval("Animation.tick()", 1500);
	},
	
	tick: function() {
	
		var a = $('#animation');
		
		var next = "p1";
		var old = "p4";
		
		if (a.hasClass('p1')) { old = "p1"; next = "p2"; }
		if (a.hasClass('p2')) { old = "p2"; next = "p3"; }
		if (a.hasClass('p3')) { old = "p3"; next = "p4"; }

		var time = 500;
	
		a.fadeOut(time, function() {

			a.removeClass(old).addClass(next);
	
			a.fadeIn(time, function() {
				$('h1').removeClass(old).addClass(next);
			});
		});
	}
};

var doLucy = function(elem, settings) {
	if (elem.find('li').length > 1) elem.lucy(settings);
	else elem.addClass('loner').find('> a').remove();
};

var Dupequoter = {

	breakdown: function(s) {
	
		//make a new object
		var r = new Object;
		
		//for each optgroup
		s.find('optgroup').each(function() {
		
			//add its html to the object as an associative array
			r[$(this).attr("label")] = $(this).html();
		});
		
		//empty the select
		s.html('<option value="">-</option>');
		return r;
	},

	init: function() {
		var empty = '<option value="">-</option>';
		var options = $('#eoptions').html();
		$('#eoptions').html(empty);
	
		var colours = this.breakdown($('#ecolour'));
		var inserts = this.breakdown($('#einsert'));
	
		$('#epackaging').change(function() {
			var o = $('#epackaging option:selected');
			
			if (o.val() == "yes") $('#eoptions').html(options).resetSS();
			else $('#eoptions').html(empty).resetSS();
			
			$('#ecolour,#einsert').html(empty).resetSS();
		});
		
		$('#eoptions').change(function() {
			var o = $('#eoptions option:selected');
			
			var c = o.attr('data-colour');
			var i = o.attr('data-insert');
			
			$('#ecolour').html( (c) ? colours[c] : empty ).resetSS();
			$('#einsert').html( (i) ? inserts[i] : empty ).resetSS();
		});
	
		$('#enquiryform select').sSelect();
		$('#enquiryform .second').hide();
		
		$('#enquiryform .first .nextprev').click(function(e) {
			e.preventDefault();
			$('#enquiryform .first').fadeOut(function() {
				$('#enquiryform .second').fadeIn();
			});
		});
		$('#enquiryform .second .nextprev').click(function(e) {
			e.preventDefault();
			$('#enquiryform .second').fadeOut(function() {
				$('#enquiryform .first').fadeIn();
			});
		});
	}

}

var fixHeight = function() {
	var target = $(window).height() - 185;
	$('section').css({ minHeight: target + "px" });
};

var Form = {

	general: function(theform, magic) {
		$.ajax({
			type: "POST",
			url: "/do_contact",
			dataType: 'json',
			data: theform.serialize()+'&ajax=1',
			success: function(data) {
				var block = theform.parent();
				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('<span class="enquiry-error">Please check the <u>red</u> fields and try again.</span>');
					
					if (magic) {
						theform.find("input, textarea").css({ borderColor: "#515151" });
						$.each(data.errors, function(i, val) {
							theform.find("input[name="+val+"], textarea[name="+val+"]").css({ borderColor: "#600" });
						});
					}
					else {
						theform.find("input, textarea").attr("style", "").removeAttr("style");
						$.each(data.errors, function(i, val) {
							theform.find("input[name="+val+"], textarea[name="+val+"]").css({ background: "#600" });
						});
					}
				}
			}
		});
		return false;
	},
	quote: function() {
		var theform = $('#quoteform form');
		$.ajax({
			type: "POST",
			url: "/do_contact",
			dataType: 'json',
			data: theform.serialize()+'&ajax=1',
			success: function(data) {
				if (data.worked) {
					var formelements = theform.find('div'); //seperate this from the fadeout ness below for better performance
					formelements.fadeOut("fast", function() {
						$(this).remove();
						if (theform.find("p").length < 1) theform.find('h4').after('<div class="enquiry-thanks">'+data.message+'</div>');
					});
					if (theform.find('.enquiry-error').length) theform.find('.enquiry-error').fadeOut('fast', function() { $(this).remove(); });
				}
				else {
					if (!theform.find('.enquiry-error').length) theform.find('h4').after('<span class="enquiry-error">Please check the <u>red</u> fields and try again.</span>');
					
					theform.find("input, textarea").css({ borderColor: "#515151" });
					$.each(data.errors, function(i, val) {
						theform.find("input[name="+val+"], textarea[name="+val+"]").css({ borderColor: "#933" });
					});
				}
			}
		});
		return false;
	}

};

var Gmap = {
	m: null,

	init: function() {
		var c = new google.maps.LatLng(53.226546, -0.545494);

		this.m = new google.maps.Map(document.getElementById("gmap"), {
			zoom: 16,
			center: c,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false
		});

		var mr = new google.maps.Marker({
			position: c,
			map: this.m,
			icon: new google.maps.MarkerImage('/media/images/map-pin.png', new google.maps.Size(29,37))
		});
	},
	
	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 Quote = {
	close: function() {
		$('#quoteform form').fadeOut("slow", function() {
			$('#quoteform > div').animate({ height: "5px" }, 500);
		});
	},

	init: function() {
		var qf = $('#quoteformstrip').html();
		$('#quoteformstrip').remove();
		$('body').prepend(qf);
		$('#quoteform .opener').click(function(e) {
			e.preventDefault();
			Quote.open();
		});
		$('#quoteform .closer').click(function(e) {
			e.preventDefault();
			Quote.close();
		});
		$('#quoteform select').sSelect();
		
		$('#quoteform input.magic').blur(function() {
			if ($(this).val() == "") $(this).css({ background: "none" });
			else $(this).css({ background: "#3e3e3e" });
		});
		$('#quoteform textarea.magic').focus(function() {
			if ($(this).val() == "Please give details...") $(this).val('');
		}).blur(function() {
			if ($(this).val() == "") $(this).val('Please give details...');
		});
		
		$('#quoteform').submit(function() {
			Form.quote();
			return false;
		});
	},
	
	open: function() {
		$('#quoteform > div').animate({ height: "270px" }, 500, function() {
			$('#quoteform form').fadeIn("slow");
			$('#quoteform select').resetSS();
		});
	}
};

var Scrollings = {

	click: function(s, c) {
		s.find('.sel').removeClass('sel');
		c.addClass('sel');
	},

	getHash: function() {
		var h = window.location.hash;
		h = h.substring(0, h.length);
		if (h.indexOf("#") > -1) h = h.substring(1, h.length);
		return h;
	},

	init: function() {
	
		var outer = $('.scrollable');
		var limit = $('footer');
	
		var nav = navigator.userAgent.toLowerCase();
		
		outer.find('a').click(function () { Scrollings.click(outer, $(this)); });
		
		// get our initial variables
		var initialPos  	= outer.position().top;
		var initialHeight   = outer.outerHeight();
		
		// Using js we alter the position of left to 'fixed' allowing us to anchor it to the top of the page
		$(window).scroll(function() {
		
			var scrollY 		= (typeof (window.pageYOffset) == 'number') ? window.pageYOffset : (document.body && document.body.scrollTop) ? document.body.scrollTop : (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : 0;
			var scrollX 		= (typeof (window.pageXOffset) == 'number') ? window.pageXOffset : (document.body && document.body.scrollLeft) ? document.body.scrollLeft : (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : 0;
			var top 			= scrollY - (initialPos -5);
			
			// Handle vertical scrolling
			if (top > 0) {
				outer.addClass('scrolled');
			
				var diff = 5;
				var iediff = scrollY + 5;
				// handle it incase they have a small resolution and it overlaps footer
				if (scrollY+initialHeight+84 > limit.position().top) {
					var diff = (scrollY+initialHeight+84) - limit.position().top + 5;
					diff = '-'+diff;
					iediff = (limit.position().top - initialHeight) - 5;
				}
					
				/* ie6/android/iphone doesn't support fixed so we need to use another method... absolute! */
				if (($.browser.msie && $.browser.version == '6.0') || nav.indexOf('mobile safari') > -1 || nav.indexOf('iphone') > -1 || nav.indexOf('Nokia') > -1) {
					outer.css({position:'absolute',top:iediff+'px'});
				}
				// for everything else we can use position: fixed
				else {
					outer.css({position:'fixed',top:diff+'px'});
				}
				// Handle horizontal scrolling first, this will only apply 
				if ((scrollX-11) > 0) {
					var diff = '-'+(scrollX-11);
					var iediff = 11;
					
					// ie6/android/iphone/nokia
					if (($.browser.msie && $.browser.version == '6.0') || nav.indexOf('mobile safari') > -1 || nav.indexOf('iphone') > -1 || nav.indexOf('Nokia') > -1) {
						outer.css({position:'absolute',left:iediff+'px'});
					}
					// for everything else we can use position: fixed
					else {
						outer.css({position:'fixed',left:diff+'px'});
					}
				}
				else {
					outer.css({left:'auto'});
				}
			}
			else outer.removeClass('scrolled').css({position:'static',top:'auto','left':'auto'});
		});
	
		var h = Scrollings.getHash();
		if (h.length > 0) $('.scrollable a[href$=' + h + ']').click();
	
	}
};

//lucy v12
(function(e){e.fn.lucy=function(g){var b,a,c,h={mover:function(c,d){var e=0-parseInt(a.carousel.css("margin-left"));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)}c=0-parseInt(a.carousel.css("margin-left"))/(b.width+b.margin)+1;if(a.loner&&b.scrollbar){var f=(0-parseInt(a.carousel.css("margin-left"))/a.carousel.width())*a.scrollmarker.parent().width(); b.scrollbarsnap?a.scrollmarker.css({marginLeft:f}):a.scrollmarker.animate({marginLeft:f},"fast")}else a.loner&&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(){d.stop();b.autoscroll?h.mover(0,d.go()):h.mover(0)}},d={init:function(f){b=e.extend({},{displayed:1,width:300,height:200,margin:10,left:".left",right:".right",autoscroll:!1,easing:"swing", speed:1E3,animtime:"fast",scrollbar:!1,scrollbarelem:".scrollbar",scrollbarheight:0,scrollbarwidth:200,scrollbarsnap:!1,numbar:!1,numbarelem:".numbers",afterAnimation:null,freezeOnBlur:!0},f);a={timer:null};a.div=c;a.carousel=c.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));c.find(".view").width(b.displayed*(b.width+b.margin)-b.margin).height(b.height);a.loner= a.items.length>1?!0:!1;if(a.loner&&b.scrollbar){a.scrollbar=c.find(b.scrollbarelem);a.scrollbar.height(b.scrollbarheight).width(b.scrollbarwidth);a.scrollbar.append('<div class="scrollmarker"></div>');for(i=1;i<=a.count;i++)a.scrollbar.append(function(){return'<a href="#" rel="'+i+'"></a>'});a.scrollmarker=c.find(".scrollmarker");a.scrollmarker.width(e(c).find(".view").width()/a.carousel.width()*a.scrollbar.width()).height(b.scrollbarheight);a.scrollbar.find("a").width(1/a.count*a.scrollbar.width()).css({position:"relative", top:0-b.scrollbarheight}).each(function(){e(this).click(function(a){a.preventDefault();d.moveTo(e(this).attr("rel"))})})}else if(a.loner&&b.numbar){a.numbar=c.find(b.numbarelem);f="<ul>";for(i=1;i<=a.count;i++)f=f+'<li><a href="#" rel="'+i+'">'+i+"</a></li>";a.numbar.html(f+"</ul>");a.numbar.find("a").click(function(a){a.preventDefault();d.moveTo(e(this).attr("rel"))});a.numbar.find("li:first-child a").addClass("active")}c.find(b.left).click(function(b){b.preventDefault();a.carousel.is(":animated")|| d.moveLeft()});c.find(b.right).click(function(b){b.preventDefault();a.carousel.is(":animated")||d.moveRight()});b.autoscroll&&(d.go(),e(c).hover(function(){d.stop()},function(){d.go()}),b.freezeOnBlur&&(e(window).bind("blur",function(){d.stop()}),e(window).bind("focus",function(){d.go()})))},go:function(){if(a.timer==null)a.timer=setInterval(function(){d.moveLeft()},b.speed)},moveLeft:function(){parseInt(a.carousel.css("margin-left"))-b.displayed*b.margin+parseInt(a.carousel.width())<=b.displayed* b.width?h.reset():h.mover("-="+(b.width+b.margin))},moveRight:function(){var c="+="+(b.width+b.margin);parseInt(a.carousel.css("margin-left"))>=0&&(c="-="+(a.count-b.displayed)*(b.width+b.margin));h.mover(c)},moveTo:function(c){var d=a.count-b.displayed;c>d?c=d:c--;h.mover(0-c*(b.width+b.margin))},stop:function(){clearInterval(a.timer);a.timer=null}};return this.each(function(){c=e(this);d[g]?(b=c.data("settings"),a=c.data("constants"),d[g](Array.prototype.slice.call(arguments,1))):typeof g==="object"|| !g?(b={},a={},d.init(g)):e.error("Method "+g+" does not exist fool!");c.data("settings",b);c.data("constants",a)})}})(jQuery);

//Stylish Select 0.4.5 - http://github.com/sko77sun/Stylish-Select
(function(a){a("html").addClass("stylish-select");if(!Array.prototype.indexOf){Array.prototype.indexOf=function(d){if(this===void 0||this===null){throw new TypeError()}var e=Object(this);var b=e.length>>>0;if(b===0){return -1}var f=0;if(arguments.length>0){f=Number(arguments[1]);if(f!==f){f=0}else{if(f!==0&&f!==(1/0)&&f!==-(1/0)){f=(f>0||-1)*Math.floor(Math.abs(f))}}}if(f>=b){return -1}var c=f>=0?f:Math.max(b-Math.abs(f),0);for(;c<b;c++){if(c in e&&e[c]===d){return c}}return -1}}a.fn.extend({getSetSSValue:function(b){if(b){a(this).val(b).change();return this}else{return a(this).find(":selected").val()}},resetSS:function(){var b=a(this).data("ssOpts");$this=a(this);$this.next().remove();$this.unbind(".sSelect").sSelect(b)}});a.fn.sSelect=function(b){return this.each(function(){var l={defaultText:"Please select",animationSpeed:0,ddMaxHeight:"",containerClass:""};var o=a.extend(l,b),f=a(this),m=a('<div class="selectedTxt"></div>'),u=a('<div class="newListSelected '+o.containerClass+'"></div>'),k=a('<div class="SSContainerDivWrapper" style="visibility:hidden;"></div>'),C=a('<ul class="newList"></ul>'),w=-1,e=-1,j=-1,p=[],z=false,y=false,A;a(this).data("ssOpts",b);u.insertAfter(f);u.attr("tabindex",f.attr("tabindex")||"0");m.prependTo(u);C.appendTo(u);C.wrap(k);k=C.parent();f.hide();m.data("ssReRender",!m.is(":visible"));if(f.children("optgroup").length==0){f.children().each(function(E){var F=a(this).html();var D=a(this).val();p.push(F.charAt(0).toLowerCase());if(a(this).attr("selected")=="selected"){o.defaultText=F;e=j=E}C.append(a('<li><a href="JavaScript:void(0);">'+F+"</a></li>").data("key",D))});A=C.children().children()}else{f.children("optgroup").each(function(){var D=a(this).attr("label"),F=a('<li class="newListOptionTitle">'+D+"</li>"),E=a("<ul></ul>");F.appendTo(C);E.appendTo(F);a(this).children().each(function(){++w;var H=a(this).html();var G=a(this).val();p.push(H.charAt(0).toLowerCase());if(a(this).attr("selected")=="selected"){o.defaultText=H;e=j=w}E.append(a('<li><a href="JavaScript:void(0);">'+H+"</a></li>").data("key",G))})});A=C.find("ul li a")}var r=C.height(),q=u.height(),B=A.length;if(e!=-1){i(e)}else{m.text(o.defaultText)}function s(){var E=u.offset().top,D=a(window).height(),F=a(window).scrollTop();if(r>parseInt(o.ddMaxHeight)){r=parseInt(o.ddMaxHeight)}E=E-F;if(E+r>=D){C.css({height:r});k.css({top:"-"+r+"px",height:r});f.onTop=true}else{C.css({height:r});k.css({top:q+"px",height:r});f.onTop=false}}s();a(window).bind("resize.sSelect scroll.sSelect",s);function v(){u.css("position","relative")}function d(){u.css({position:"static"})}m.bind("click.sSelect",function(D){D.stopPropagation();if(a(this).data("ssReRender")){r=C.height("").height();k.height("");q=u.height();a(this).data("ssReRender",false);s()}a(".SSContainerDivWrapper").not(a(this).next()).hide().parent().css("position","static").removeClass("newListSelFocus");k.toggle();v();if(e==-1){e=0}A.eq(e).focus()});function c(E,D){if(E==true){j=e;f.change()}if(D==true){e=j;i(e)}k.hide();d()}A.bind("click.sSelect",function(E){var D=a(E.target);e=A.index(D);y=true;i(e,true);c()});A.bind("mouseenter.sSelect",function(E){var D=a(E.target);D.addClass("newListHover")}).bind("mouseleave.sSelect",function(E){var D=a(E.target);D.removeClass("newListHover")});function i(D,H){if(D==-1){m.text(o.defaultText);A.removeClass("hiLite")}else{A.removeClass("hiLite").eq(D).addClass("hiLite");var G=A.eq(D).text(),F=A.eq(D).parent().data("key");try{f.val(F)}catch(E){f[0].selectedIndex=D}m.text(G);if(H==true){j=D;f.change()}if(k.is(":visible")){A.eq(D).focus()}}}f.bind("change.sSelect",function(E){var D=a(E.target);if(y==true){y=false;return false}var F=D.find(":selected");e=D.find("option").index(F);i(e)});function t(D){a(D).unbind("keydown.sSelect").bind("keydown.sSelect",function(G){var F=G.which;y=true;switch(F){case 40:case 39:x();return false;break;case 38:case 37:n();return false;break;case 33:case 36:h();return false;break;case 34:case 35:g();return false;break;case 13:case 27:c(true);return false;break}keyPressed=String.fromCharCode(F).toLowerCase();var E=p.indexOf(keyPressed);if(typeof E!="undefined"){++e;e=p.indexOf(keyPressed,e);if(e==-1||e==null||z!=keyPressed){e=p.indexOf(keyPressed)}i(e);z=keyPressed;return false}})}function x(){if(e<(B-1)){++e;i(e)}}function n(){if(e>0){--e;i(e)}}function h(){e=0;i(e)}function g(){e=B-1;i(e)}u.bind("click.sSelect",function(D){D.stopPropagation();t(this)});u.bind("focus.sSelect",function(){a(this).addClass("newListSelFocus");t(this)});u.bind("blur.sSelect",function(){a(this).removeClass("newListSelFocus")});a(document).bind("click.sSelect",function(){u.removeClass("newListSelFocus");if(k.is(":visible")){c(false,true)}else{c(false)}});m.bind("mouseenter.sSelect",function(E){var D=a(E.target);D.parent().addClass("newListSelHover")}).bind("mouseleave.sSelect",function(E){var D=a(E.target);D.parent().removeClass("newListSelHover")});k.css({left:"0",display:"none",visibility:"visible"})})}})(jQuery);
