function clickIE() { if (event.button==2) return false; }
function clickNS(e) { if (document.layers || document.getElementById && !document.all) if (e.which == 2 || e.which == 3) return false; }
function googletrack(label){
setTimeout('(new Image()).src="http://www.googleadservices.com/pagead/conversion/1069311135/?label='+label+'&guid=ON&script=0"',100);
}
$(function() {

	if (document.layers) {
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown = clickNS;
	}
	else if (document.all && !document.getElementById) document.onmousedown = clickIE;
	document.oncontextmenu = new Function("return false");

	Cart.init();
	Contact.init();
	Controls.init();
	Scrollings.init();
	
	if ($('#news').length) {
	
		$('#news .newsfeed').lucy({
			'displayed' : 2,
			'width' : 330,
			'height' : 175,
			'margin' : 12,
			'autoscroll' : true,
			'animtime' : 800,
			'speed' : 3000
		}).find('.view').height(176);
		
		if ($('#news .newsfeed li').length < 3) {
			var constants = $('#news .newsfeed').data("constants");
			clearInterval(constants['timer']);
			$('#news .newsfeed').unbind();
			$('#scroll_controls').remove();
		}
			
	}
	
	$('a[href^="http://"]').attr({target: "_blank"});
	
	if (window.location.hash) {
		var hash = window.location.hash;
		hash = hash.replace('#', "");
		if (hash == "contact") setTimeout("$('#navigation .contact').click();", 500);
	}
	
	if ($('#blades').length) Blades.init();
});

var Blades = {
	init : function() {
		Blades.setLayout(false);
		
		$('#blades li .control').click(function() {
			 
			if (!$(this).hasClass("active")) {
				var li_this = $(this).parent();
				var active = $('#blades .active');
				var li_to_close = active.parent();
				var index_this = li_this.index();
				var index_to_close = li_to_close.index();
				
				if (index_this > index_to_close) {
					//if we are opening a blade to the right hand side of the one that is currently open
					for (x = index_to_close + 1; x <= index_this; x++) {
						var current = $('#blades li').eq(x);
						var lft = Blades.getLeft(current);
						current.animate({ left: lft-774+36}, Blades.speed, Blades.easing);
					}
				}
				else {
					//we are opening a blade to the left hand side of the one that is currently open
					var x = index_to_close;
					while (x != index_this) {
						var current = $('#blades li').eq(x);
						var lft = Blades.getLeft(current);
						current.animate({ left: lft+774-36}, Blades.speed, Blades.easing);
						x--;
					}
				}
				active.removeClass("active");
				$(this).addClass("active");
			}
			return false;
		});
		
		Blades.go();
		$('#blades .container').hover(function() {
			Blades.stop();
		}, function() {
			Blades.go();
		});
		
		$(window).bind("blur", function() {
			Blades.windowBlurred = true;
			Blades.stop();
		});

		$(window).bind("focus", function() {
			if (Blades.windowBlurred) {
				Blades.windowBlurred = false;
				Blades.go();
			}
		});

	},
	
	setLayout : function(animate) {
		$('#blades li').not('#about').each(function() {
			var howfar = (($(this).index()-1)*42)+774;
		
			if (animate) $(this).animate({ left: howfar },  Blades.speed, Blades.easing);
			else $(this).css({ left: howfar });
		});
	},
	getLeft : function(element) {
		var left = parseInt(element.css('left')) || 0;
		if (typeof(left) != "number") left = 0; //IE is lame
		return left;
	},
	
	tick : function() {
		var chosen = $('#blades .active').parent().index() + 1;	
		if (chosen >= $('#blades li').length) {
			Blades.setLayout(true);
			$('#blades .active').removeClass("active");
			$('#about .control').addClass("active");
		}
		else 
			$('#blades li').eq(chosen).find('.control').click();
	},
	
	timer : null,
	windowBlurred : false,
	speed : 1000,
	easing : 'easeOutSine',
	stop : function() {
		clearInterval(Blades.timer);
		Blades.timer = null;
	},
	go : function() {
		if (Blades.timer == null) Blades.timer = setInterval("Blades.tick()", 5000);
	}
};

var Carousel = {
	video : function() {
		if ($('#videocarousel').length) {
		    $('#videocarousel').each(function() {
		    	if ($(this).find('li').length > 1) {
		    		$(this).lucy({
		    			'width' : 672,
		    			'height' : 296,
		    			'left' : '.right',
		    			'right' : '.left',
		    			'scrollbar' : true,
		    			'scrollbarheight' : 10,
		    			'scrollbarsnap' : true,
		    			'scrollbarwidth' : 10*($('#videocarousel li').length)
		    		});
		    		var sbar = $(this).find('.scrollbar');
					var aas = 0-((sbar.find('a').length*10)/2);
					sbar.css('margin-left', aas+"px");
		    	}
		    	else {
					$(this).css('margin-bottom', 0);
					$(this).find('.left, .right, .scrollbar').remove();
		    		$(this).find('li').width(672);
		    	}
		    });
		}
	}
};

var Cart = {
	add : function(stoneid) {
		$.ajax({
			type: "POST",
            url: "/user/cart",
			dataType: 'json',
            data: '&action=add&stone_id='+stoneid,
			beforeSend: function(){},
			complete: function(){},
			success: function(data) {
				Cart.update(data);
				Cart.flash();
            }
        });
	},
    // addBulk expects an array [1,2,3,4] etc etc
    addBulk : function(link, stones) {
        if (!stones || !link) return false;
        link = '#'+link;
        data = {};
        data.action = 'addbulk';
        data.stones = stones;
        $.ajax({
			type: "POST",
            url: "/user/cart",
			dataType: 'json',
            data: data,
			beforeSend: function(){},
			complete: function(){},
			success: function(data) {
				Cart.update(data);
                Cart.flash();
                $(link).html(data.total+ ' Stones Added. <a href="/user/order">Click here to confirm your order</a>');
            }
        });
        return false;
    },
	flash : function() {
		var flasher = $('#account_control .title');
		if (!flasher.parent().hasClass('active')) {
			var orig = flasher.css('color');
			flasher.animate({color: '#fff'}, 500, function() {
				$(this).animate({color: orig}, 1000, function() {
					$(this).attr('style', '');
				});
			});
		}
	},
	init : function() {
		$.ajax({
			type: "POST",
            url: "/user/cart",
			dataType: 'json',
            data: '',
			beforeSend: function(){},
			complete: function(){},
			success: function(data) {
				Cart.update(data);
				$('#account_control .holder').height(0);
            }
        });  
        
        $('#account_control a.delete').live('click', function() {
        	Cart.remove($(this).attr("rel"));
        	return false;
        });
	},
	remove : function(stoneid) {
		$.ajax({
			type: "POST",
            url: "/user/cart",
			dataType: 'json',
            data: '&action=del&stone_id='+stoneid,
			beforeSend: function(){},
			complete: function(){},
			success: function(data) {
				Cart.update(data);
				Cart.flash();
			}
        });
        
        if($('#stone-results.cart').length) {
            var holder = $('#stone-results');
            $('a.stone-link[rel=' + stoneid + ']', holder).parent().fadeOut("fast", function() {
               $(this).remove();
            });
        }
        else {
            if ($('a.stone-link').length) $('a.stone-link[rel='+stoneid+'] .stone-added').fadeOut("fast", function() {
                    $(this).removeClass('stone-added').addClass('stone-cart').attr('style', '');
            });
        }
        
        if ($('a.sampleorder, a.sampleorderlarge').length) $('.sampleorder[rel=' + stoneid + '], .sampleorderlarge[rel=' + stoneid + ']').fadeOut("fast", function() {
		    $(this).html("Order a sample").removeClass("ordered").unbind();
		    //dirty
				$(this).removeClass("sampleordered").removeClass("sampleorderedlarge");
				
				Stones.activateOrdering();
		    $(this).fadeIn();
				
				//check the direct link and update
				if($('#add-to-basket-direct-link'))
					$('#add-to-basket-direct-link').html("Add to Basket+");
		});
		
	},
	update : function(data) {
		var holder = $('#account_control .holder');
		holder.find('ul').empty().append(data.html);
		holder.find('p').empty().append(data.cartfooter);
	
		var count = 0;
		if ($('#account_control .holder li:first-child a').length)
			count = $('#account_control .holder li').length;

		$('#account_control .title span').html(count);
		
		if (holder.height() > 0) holder.animate({height: (holder.find('li').length*20)+28}, "fast");
	}
};

var Contact = {
	close : function() {
		$('#contact .container').fadeOut(Contact.speed, function() {
			$('#contact').slideUp(Contact.speed, "easeOutCirc", function() {
				Scrollings.updatePos();
				$('#navigation .contact.sel').removeClass('sel');
			});
		});
		Controls.fiddle = false;
		$('#controls').css('top','auto');
	},
	init : function() {
		var contactStrip = $('#contactstrip').html();
		$('#contactstrip').remove();
		$('body').prepend(contactStrip);
		$('#contact form').submit(function(e) { e.preventDefault(); Contact.submit($(this)); });
		$('#closer').click(function() {
			Contact.close();
			return false;
		});
		$('#navigation .contact, #main-menu-enquire').click(function() {
			Contact.open(false);
			return false;
		});
		$('#quote-request').click(function() {
			Contact.quoter();
			return false;
		});
		
		$('#steps-request-quote').click(function() {
			Contact.quoter();
			return false;
		});
		
		$('#steps-send-enquiry').click(function() {
			Contact.open(false);
			return false;
		});
		
		$('#contact input[type=submit]').val(""); //IE is lame
	},
	open : function(tick) {
		$('html, body').animate({scrollTop:0}, 'slow', function() {
			$('#navigation .contact').addClass('sel');
			$('#contact').slideDown(Contact.speed, "easeOutCirc", function() {
				$('#contact .container').fadeIn(Contact.speed, function() {
					Scrollings.updatePos();
					if (tick) $('#contact input[type=checkbox]').attr('checked', true);
					Controls.dofiddle();
				});
			});
			Controls.fiddle = true;
		});
	},
	quoter : function() {
		$('html, body').animate({scrollTop:0}, 'slow', function() {
			Contact.open(true);
		});
	},
	speed : 600,
	submit: function(theform) {
	
		$.ajax({
		    type: "POST",
		    url: "/contact",
		    dataType: 'json',
		    data: theform.serialize()+'&ajax=1',
		    success: function(data) {
		    	var block = theform.parent();
		    	if (data.worked) {
		    		var formelements = block.children().slice(1); //seperate this from the fadeout ness below for better performance
		    		formelements.fadeOut("fast", function() {
		    			$(this).remove();
		    			if (block.find("p").length < 1) block.append('<p class="enquiry-thanks">'+data.message+'</p>');
							setTimeout("Contact.close()", 4000);
		    		});
                    if (block.find('.enquiry-error').length) block.find('.enquiry-error').fadeOut('fast', function() { $(this).remove(); });
		    	}
		    	else {
		    		theform.find('input, textarea').css('border-color', "#707173");
                    if (!block.find('.enquiry-error').length) block.find('h4').append('<span class="enquiry-error"> (please check the <u>highlighted</u> fields and try again)</span>');
		    		$.each(data.errors, function(i, val) {
		    			theform.find("input[name="+val+"], textarea[name="+val+"]").css("border-color", "#949b50");
		    		});
		    	}
		    }
		});
		return false;
	
	},
	
	submitDiscussionForm : function(f) {
		var form = $(f);
		var action = "/contact";
		var data = form.serialize();
		var container = form.parent();
		var messageArea = $('#get-a-quote-form-holder span.form-response');
		$('input[type="text"]', container).css({'border-color' : '#BDBDBD'});
		$('textarea', container).css({'border-color' : '#BDBDBD'});
				
		$.post(action, data, function(response) {
			if(response.worked) {
				messageArea.html("Thank you for your enquiry. We will be in touch soon");
				//clear the form
				$('input[type="text"], textarea', container).val("")
				.css({'border-color' : '#BDBDBD'})
				.prev()
					.css('color','#555756');
			
			}
			else {
				//assume we have an array of errors to loops over and highlight fields
				if(response.errors.length > 0) {
					messageArea.html("Please check your form and try again");
					$.each(response.errors, function(i, error) {
						$("input[name=" + error + "], textarea[name=" + error + "]")
						.css("border-color", "#333333")
						.prev()
							.css('color', '#333'); 				
					});
				}
			}}, "json" );
		return false;
	}

};

var Controls = {
	dofiddle : 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 distance = (scrollY < 280) ? 280 - scrollY : 0;
		$('#controls').css('top', distance+'px');
	},
	
	fiddle : false,
	
	init : function(){
		Controls.activateBasket();
		Controls.activateLogin();
		//Controls.activateSearch();
	},
	
	activateBasket : function() {
		//animate the basket box appearance
		$('#account_control span.title').click(function(){
			var li = $(this).parent();
			var div = li.find("div.holder");
			var height = parseInt(div.height());
			
			if (height == 0) {
				li.addClass("active");
				div.animate({height: (div.find('li').length*20)+28}, "fast");
			} 
			else {
				li.removeClass("active");
				div.animate({height: 0}, "fast");
			}

		});
	},
	
	activateLogin : function() {
		//animate the login box appearance
		$('#login_control span.title').click(function(){
			var li = $(this).parent();
			var div = li.find("div.holder");
			var height = parseInt(div.height());
			
			if (height == 0) {
				li.addClass("active");
				if (div.hasClass("loggedin")) div.animate({height: 65}, "fast");
				else div.animate({height: 95}, "fast");
			} 
			else {
				li.removeClass("active");
				div.animate({height: 0}, "fast");
			}

		});
		
		//change the background images of the login boxes
		$('#login_control input[type=text]').each(function(){
		
			//add a delay to the background image being displayed to allow the browser to load content
			setTimeout('Controls.checkField($("#login_control input[type=text]"), "username")', 500);
		
			$(this).focus(function() {
				$(this).css("background-image", '');
			}).blur(function(){
				if ($(this).val()=='') $(this).css("background-image", 'url(/media/images/login-username.png)');
				else $(this).css("background-image", '');
			});
		});
		$('#login_control input[type=password]').each(function(){
		
			//add a delay to the background image being displayed to allow the browser to load content
			setTimeout('Controls.checkField($("#login_control input[type=password]"), "password")', 500);
			
			$(this).focus(function() {
				$(this).css("background-image", '');
			}).blur(function(){
				if ($(this).val()=='') $(this).css("background-image", 'url(/media/images/login-password.png)');
				else $(this).css("background-image", '');
			});
		});
	},
	
	activateSearch : function() {
		$('#search_control input[type=text]').focus(function(){
			if ($(this).val() == "Type here to search") $(this).val("");
		}).blur(function(){
			if ($(this).val() == "") $(this).val("Type here to search");
		});
	},
	
	checkField : function(field, name) {
		if (field.val() == "") field.css("background-image", "url(/media/images/login-"+name+".png)");
	}
	
};

var Loader = {
	/**
 		* preload
 		* Preloads images (mainly)
 		*/
	preload : function(wut, handler) {
		if ((typeof wut).toLowerCase() == 'string') {
			src = wut;
		}
		else {
			src = $(wut).attr('href');
			try {
				opts = eval('({'+$(wut).attr('rel')+'})');
			}catch(e){}
		}
		// test if it is an image, otherwise we'll use ajax
		if (src.match(/\/photo\/|.jpg$|.jpeg$|.png$|.gif$|.bmp$|.tif$|.tiff$|.gi$/i) || 1){
			var img = new Image();
			if (handler) {
				if (handler.loaded && typeof handler.loaded == 'function') {
					img.onload = function() {
						response = {
							width: img.width,
							height: img.height,
							src: img.src,
							obj: $('<img>').attr('src', img.src)
						};
						handler.loaded(response);
					};
				}
				if (handler.loaded && typeof handler.error == 'function') {
					img.onerror = function(err) {
						handler.error(err);
					}
				}
			}
			img.src = src;
		}
		// ajax
		else {
			$.get(src, function(html){
				if (handler) {
					if (handler.loaded && typeof handler.loaded == 'function') {
						var content = $('<div>').html(html);
						response = {
							width: parseInt(content.children(0).css('width')),
							height: parseInt(content.children(0).css('height')),
							src: src,
							obj: content,
							data: html
						};
						handler.loaded(response);
					}
				}
			});
		}
	}
};


var Login = {
    topHolder : '#login-control',
    loginNo : 95,
    forgotNo : 115,
    
    top: function(form) {
        if (!form) return false;
        
        var data = $(form).serialize();
        var url = $(form).attr('action');
        data += '&ajax=1';          // add ajax handling via js
        
        if ($('#login_control div.holder').height() != 120) {
            $('#login_control div.holder').animate({height:120+'px'},250);
        }
        
        $('#top-login-submit').addClass('progress');
        if (!$('#login-status').length) $('<div id="login-status" class="progress">Logging in...</div>').insertAfter(form);
        else $('#login-status').removeClass().addClass('progress').html('Logging in...');
        $.ajax({
            type        : "POST",
            url         : url,
            data        : data,
            dataType    : 'json',
            success: function(data) {
                /* expecting:
                  data.worked       0/1
                  data.status       (string) it worked or it didnt
                */
                if (typeof data != "object") return false;
                if (data.worked == 1) {
                    // refresh stuff here
                    $('#top-login-submit').removeClass('progress');
                    $('#login-status').removeClass().addClass('success').html(data.status);
                    var redir = window.location.href;
                    if (redir.indexOf('user') == -1) redir = '/';
                    setTimeout(function(){window.location=redir;},750);
                }
                else {
                    $('#top-login-submit').removeClass('progress');
                    $('#login-status').removeClass().addClass('error').html(data.status);
                    $('#top-login-password').focus().select();
                    // it didn't work,
                }
            }
        });
        return false;
    },
    
    std : function(form) {
        if (!form) return false;
        
        var data = $(form).serialize();
        var url = $(form).attr('action');
        data += '&ajax=1';
        
        $('#login-submit').addClass('progress');
        if (!$('#login-std-status').length) $('<div id="login-std-status" class="progress">Logging In...</div>').insertAfter(form);
        else $('#login-std-status').removeClass().addClass('progress').html('Logging in...');
        $.ajax({
            type        : "POST",
            url         : url,
            data        : data,
            dataType    : 'json',
            success: function(data) {
                /* expecting:
                  data.worked       0/1
                  data.status       (string) it worked or it didnt
                */
                if (typeof data != "object") return false;
                if (data.worked == 1) {
                    // refresh stuff here
                    $('#login-submit').removeClass('progress');
                    $('#login-std-status').removeClass().addClass('success').html(data.status);
                    var redir = window.location.href;
                    //if (redir.indexOf('user') != -1) redir = '/stones';
                    setTimeout(function(){window.location=redir;},750);
                }
                else {
                    $('#login-submit').removeClass('progress');
                    $('#login-std-status').removeClass().addClass('error').html(data.status);
                    $('#login-password').focus().select();
                    // it didn't work,
                }
            }
        });
        return false;
    },
    
    registerOrder : function(form) {
        if (!form) return false;
        
        var data = $(form).serialize();
        var url = $(form).attr('action');
        data += '&ajax=1';
        
        $('#register-submit').addClass('progress');
        if (!$('#register-status').length) $('<div id="register-status" class="progress">Registering...</div>').insertAfter(form);
        else $('#register-status').removeClass().addClass('progress').html('Registering...');
        $.ajax({
            type        : "POST",
            url         : url,
            data        : data,
            dataType    : 'json',
            success: function(data) {
                /* expecting:
                  data.worked       0/1
                  data.status       (string) it worked or it didnt
                */
                if (typeof data != "object") return false;
                if (data.worked == 1) {
                    // refresh stuff here
                    googletrack('Nz1UCNmIjAIQn8nx_QM');
                    $('#register-submit').removeClass('progress');
                    $('#register-status').removeClass().addClass('success').html(data.status);
                    var redir = window.location.href;
                    //if (redir.indexOf('user') != -1) redir = '/stones';
                    setTimeout(function(){window.location=redir;},750);
                }
                else {
                    $('#register-submit').removeClass('progress');
                    $('#register-status').removeClass().addClass('error').html(data.status);
                    //$('#register-password').focus().select();
                    // it didn't work,
                }
            }
        });
        return false;
    },
    
    register : function(form) {
        if (!form) return false;
        
        var data = $(form).serialize();
        var url = $(form).attr('action');
        data += '&ajax=1';
        
        $('#register-submit').addClass('progress');
        if (!$('#register-status').length) $('<div style="clear:both"></div><div id="register-status" class="progress">Registering...</div>').insertAfter(form);
        else $('#register-status').removeClass().addClass('progress').html('Registering...');
        $.ajax({
            type        : "POST",
            url         : url,
            data        : data,
            dataType    : 'json',
            success: function(data) {
                /* expecting:
                  data.worked       0/1
                  data.status       (string) it worked or it didnt
                */
                if (typeof data != "object") return false;
                if (data.worked == 1) {
                    // refresh stuff here
                    googletrack('Nz1UCNmIjAIQn8nx_QM');
                    $('#register-submit').removeClass('progress');
                    $('#register-status').removeClass().addClass('success').html(data.status);
                    var redir = window.location.href;
                    if (redir.indexOf('user') != -1) redir = '/';
                    setTimeout(function(){window.location=redir;},750);
                }
                else {
                    $('#register-submit').removeClass('progress');
                    $('#register-status').removeClass().addClass('error').html(data.status);
                    // we must return html
                    $('#register-form').html(data.html);
                    // it didn't work,
                }
            }
        });
        return false;
    },
    
    
    forgot : function(form) {
        if (!form) return false;
        
        var data = $(form).serialize();
        var url = $(form).attr('action');
        
        if ($('#login_control div.holder').height() != 142) {
            $('#login_control div.holder').animate({height:142+'px'},250);
        }
        
        $('#top-forgotpass-submit').addClass('progress');
        if (!$('#top-forgotpass-status').length) $('<div id="top-forgotpass-status" class="progress">Submitting...</div>').insertAfter(form);
        else $('#top-forgotpass-status').removeClass().addClass('progress').html('Submitting');
        $.ajax({
            type        : "POST",
            url         : url,
            data        : data,
            dataType    : 'json',
            success: function(data) {
                /* expecting:
                  data.worked       0/1
                  data.status       (string) it worked or it didnt
                */
                if (typeof data != "object") return false;
                if (data.worked == 1) {
                    // refresh stuff here
                    $('#top-forgotpass-submit').removeClass('progress');
                    $('#top-forgotpass-form').remove();
                    $('#top-forgotpass-status').removeClass().addClass('success').html(data.status);
                }
                else {
                    $('#top-forgotpass-submit').removeClass('progress');
                    $('#top-forgotpass-status').removeClass().addClass('error').html(data.status);
                    // we must return html
                    $('#top-forgotpass-holder').html(data.html);
                    // it didn't work,
                }
            }
        });
        return false;
    },
    
    showForgot : function() {
        if (!$('#top-forgotpass-holder')) return false;
        $('#top-login-holder').fadeOut(500, function() {$('#top-forgotpass-holder').fadeIn();});
        //$('#top-forgotpass-holder').fadeIn();
        
        return false;
    },
    
    showLogin : function() {
        if ($('#login_control div.holder').height() != 110) {
            $('#login_control div.holder').animate({height:'110px'},250);
        }
        $('#top-forgotpass-holder').fadeOut();
        $('#top-login-holder').fadeIn();
        
        return false;
    }
};

var Scrollings = {
	currentPos : 0,
	init : function() {

		/*
			this is based on having a div positioned absolutely flush with the left edge of the browser window
			any spacing on the left hand side should be handled by padding
		*/

		//options
		var bottomSpacing = -26;			//space between bottom of target and limit (might have to be a bizarre number you can't explain)
		var defaultStyles = {position: "absolute", left: "0px", top: "43px"};	//default style for the target
		var limit = $('#get-a-quote');				//element we want to stop scrolling at (i.e. footer or start of footer)
		var target = $('#sidebar');			//telement we want to move
		var topSpacing = 60;			//space between top of target and top edge of browser window when scrolled

		//quick height hack before the main event
		var container = $('#text .container');
		if (target.height() > container.height()) container.height(target.height());

		// you should not need to edit any of the following...

		// get our initial variables
		if (target.length) {
			var nav = navigator.userAgent.toLowerCase();
			Scrollings.mover = target;
			Scrollings.updatePos();
			var initialHeight = target.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;

			if (target.length) {
				var initialPos = Scrollings.currentPos;
				
				var top = scrollY - (initialPos -topSpacing);
				//console.log("scrollY: "+scrollY+" scrollX: "+scrollX+"  initialPos: "+initialPos+"  initialHeight: "+ initialHeight+"  top: "+top);
	 
				// Handle vertical scrolling
				if (top > 0 && $(window).height() > 800) {	
					var diff = topSpacing;
					var iediff = scrollY + (topSpacing*-1.83);
					
					// keep moved element above limit
					if (scrollY+initialHeight+bottomSpacing+(topSpacing*2) > limit.position().top) {
						diff = -1 * ((scrollY+initialHeight+bottomSpacing+topSpacing) - limit.position().top);
						iediff = (limit.position().top - initialHeight) - (topSpacing*3.1);
					}
						
					/* ie6/android/iphone doesn't support fixed so we need to use another method... absolute! */
					if (($.browser.msie && ($.browser.version == '6.0' || $.browser.version == '7.0')) || nav.indexOf('mobile safari') > -1 || nav.indexOf('iphone') > -1 || nav.indexOf('Nokia') > -1) target.css({position:'absolute',top:iediff+'px'});
	
					// for everything else we can use position: fixed
					else target.css({position:'fixed',top:diff+'px'});
	
					// Handle horizontal scrolling
					if (scrollX > 0) {
						var diff = -1 * scrollX;
						
						// ie6/android/iphone/nokia
						if (($.browser.msie && ($.browser.version == '6.0' || $.browser.version == '7.0')) || nav.indexOf('mobile safari') > -1 || nav.indexOf('iphone') > -1 || nav.indexOf('Nokia') > -1) target.css({position:'absolute',left:'0px'});
	
						// for everything else we can use position: fixed
						else target.css({position:'fixed',left:diff+'px'});
					}
					else {
						if ($.browser.msie && ($.browser.version == '6.0' || $.browser.version == '7.0')) target.css({left: "0px"});
						else target.css({left: "auto"});
					}
	
				}
				else target.css(defaultStyles);
			}
			
			//by the way we have a totop link so better do that too...
			if ($('#totop:animated').length < 1)
				if (scrollY >= ($(window).height() / 10)) $('#totop').fadeIn();
				else $('#totop').fadeOut();
			
			if (Controls.fiddle) Controls.dofiddle();
			
		});
		
		$('#totop a').click(function() {
				$('html, body').animate({scrollTop:0}, 'slow');
				return false;
		});
	},
	
	mover : null,
	
	updatePos : function() {
		if (Scrollings.mover != null) {
			//use offset because this particular element is contained in a position: relative, if it isn't use position() instead
			Scrollings.currentPos = Scrollings.mover.offset().top;
		}
	}
	
};

var Stones = {
	activateOrdering : function() {
		$('.sampleorder, .sampleorderlarge').each(function(){
			$(this).click(function(){
				Cart.add($(this).attr('rel'));
				$('.sampleorder, .sampleorderlarge').fadeOut("fast", function() {
					$(this).html("sample added").addClass("ordered").unbind().click(function() { return false; }).fadeIn();
					
					if($(this).hasClass("sampleorder"))
						$(this).addClass("sampleordered");
					if($(this).hasClass("sampleorderlarge"))
						$(this).addClass("sampleorderedlarge");
						
				});
				//added to update text in add to basket link if
				if($('#add-to-basket-direct-link').length > 0)
					$('#add-to-basket-direct-link').html("In Your Basket").unbind().click(function() { return false; });
				return false;
			});
		});
		
		$('#add-to-basket-direct-link').click(function() {
			Stones.addFromStepLink(this);
			return false;
		});
	},
	
	addFromStepLink : function(l) {
		var link = $(l);
		var id = link.attr('rel');
		//Cart.add(id);
		link.html("Sample Added").addClass("ordered");
		$($('.sampleorder')[0]).click();
	},

	init : function() {
		Stones.resizeResults();
		$(window).resize(function() { Stones.resizeResults(); });
		$('#stone-results li').each(function() {
			var link = $(this).find('.stone-link');
			if (link.find('.stone-added').length < 1)
				link.append('<span class="stone-cart"></span>').hover(function(){
					$(this).find('.stone-cart').show();
				}, function() {
					$(this).find('.stone-cart').hide();
				});
		});
		
		$('.stone-cart').live("click", function() {
			Cart.add($(this).parent().attr('rel'));
			$(this).fadeOut("fast", function() {
			    $(this).removeClass('stone-cart').addClass('stone-added').fadeIn();
			});
			$(this).unbind("click");
			return false;
		});
	},
	
	page : function() {
		if ($('.sampleorder, .sampleorderlarge').not('.ordered').length) Stones.activateOrdering();
		else $('.sampleorder, .sampleorderlarge').click(function() { return false; });
		
		if ($('#imagecarousel').length) {
		    $('#imagecarousel').each(function(){
		    	if ($(this).find('li').length > 1) {
		    		$(this).lucy({
		    		    'width' : 672,
		    		    'height' : 282,
		    		    'margin' : 0,
		    		    'left' : '.right',
		    		    'right' : '.left'
		    		});
		    		$('#imagecarouselcontrol a').each(function(){
		    			$(this).click(function() {
		    				if (!$('#imagecarousel ul').is(":animated")) {
		    					$(this).lucy('moveTo', $('#imagecarousel'), $(this).attr("rel"));
		    					$('#imagecarouselcontrol a.active').removeClass('active');
		    					$(this).addClass('active');
		    				}
		    				return false;
		    			});
		    		});
		    		$('#imagecarousel .left, #imagecarousel .right').click(function(){
		    			setTimeout("Stones.updateImageControls()", 210);
		    			return false;
		    		});
		    		if ($('#imagecarouselcontrol li').length < 6) $('#imagecarouselcontrol').width( $('#imagecarouselcontrol li').length * 60 );
		    	}
		    	else {
		    		$(this).find('.left, .right').remove();
		    		$('#imagecarouselcontrol, #imagecarouselcontrol + span, #imagecarouselcontrol + span + p').remove();
		    		$(this).find('li').width(672);
		    	}
		    });
		    $.boom({
		    	'tinyName': "50x30-",
				'thumbName': "430x240-"
		    });
		}
		
		Carousel.video();	
	},
	
	resizeResults : function() {
		return true; //escapey!
		if ($(window).width() > 1023) $('#stone-results').width($(window).width() - 260);
	},
	
	updateImageControls : function() {
	    var carousel = $('#imagecarousel ul');
	    if (!carousel.is(":animated")) {
	    	var number = (parseInt(carousel.css('margin-left')) / carousel.width()) * (-1 * $('#imagecarouselcontrol li a').length) + 1;
	    	$('#imagecarouselcontrol a.active').removeClass('active');
	    	$('#imagecarouselcontrol a[rel='+number+']').addClass('active');
	    }
	}
};





/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;
(function(d){
    var k=d.scrollTo=function(a,i,e){
        d(window).scrollTo(a,i,e)
        };

    k.defaults={
        axis:'xy',
        duration:parseFloat(d.fn.jquery)>=1.3?0:1
        };

    k.window=function(a){
        return d(window)._scrollable()
        };

    d.fn._scrollable=function(){
        return this.map(function(){
            var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;
            if(!i)return a;
            var e=(a.contentWindow||a).document||a.ownerDocument||a;
            return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement
            })
        };

    d.fn.scrollTo=function(n,j,b){
        if(typeof j=='object'){
            b=j;
            j=0
            }
            if(typeof b=='function')b={
            onAfter:b
        };

        if(n=='max')n=9e9;
        b=d.extend({},k.defaults,b);
        j=j||b.speed||b.duration;
        b.queue=b.queue&&b.axis.length>1;
        if(b.queue)j/=2;
        b.offset=p(b.offset);
        b.over=p(b.over);
        return this._scrollable().each(function(){
            var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');
            switch(typeof f){
                case'number':case'string':
                    if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){
                    f=p(f);
                    break
                }
                f=d(f,this);
                case'object':
                    if(f.is||f.style)s=(f=d(f)).offset()
                    }
                    d.each(b.axis.split(''),function(a,i){
                var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);
                if(s){
                    g[c]=s[h]+(u?0:l-r.offset()[h]);
                    if(b.margin){
                        g[c]-=parseInt(f.css('margin'+e))||0;
                        g[c]-=parseInt(f.css('border'+e+'Width'))||0
                        }
                        g[c]+=b.offset[h]||0;
                    if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]
                        }else{
                    var o=f[h];
                    g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o
                    }
                    if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);
                if(!a&&b.queue){
                    if(l!=g[c])t(b.onAfterFirst);
                    delete g[c]
                }
            });
        t(b.onAfter);
            function t(a){
            r.animate(g,j,b.easing,a&&function(){
                a.call(this,n,b)
                })
            }
        }).end()
    };

k.max=function(a,i){
    var e=i=='x'?'Width':'Height',h='scroll'+e;
    if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();
    var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;
    return Math.max(l[h],m[h])-Math.min(l[c],m[c])
    };

function p(a){
    return typeof a=='object'?a:{
        top:a,
        left:a
    }
}
})(jQuery);




// jQuery color animate plugin - http://plugins.jquery.com/project/color
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);}
fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)
return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];return colors[jQuery.trim(color).toLowerCase()];}
function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))
break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]};})(jQuery);

//boom 07 Apr 2011
(function(a){var f={close:function(){a.support.opacity?a("#boom").fadeOut("fast",function(){a("#boom .instructions").click();a("#boom img").remove()}):(a("#boom").hide(),a("#boom .instructions").click(),a("#boom img").remove())},getRatioed:function(a,c,b){return a/c*b},getSize:function(d,c){var b=a(window).height()-40,e=a(window).width()-40;if(d>e||c>b)c>b&&(d=f.getRatioed(b,c,d),c=b),d>e&&(c=f.getRatioed(e,d,c),d=e),d=Math.round(d),c=Math.round(c);return{width:d,height:c}},init:function(d){d=a.extend({targetClass:".boom", tinyName:"_micro",origName:"",thumbName:"_thumb"},d);a("body").append('<div id="boom"><div id="boom-back"></div><div id="boom-box"><div class="contents"><div class="controls"><ul></ul><a class="close" href="#"></a><a class="reset" href="#"></a></div><div class="caption"></div></div></div>');a("#boom, #boom-back").width(a(window).width()).height(a(window).height());a(d.targetClass).live("click",function(c){c.preventDefault();f.open(a(this))});a("#boom .controls li a").live("click",function(c){c.preventDefault(); var b=a(this);b.hasClass("active")||(a.support.opacity?a("#boom img").fadeOut(400,function(){a(this).remove();f.switchToImage(b,b.attr("title"))}):(a("#boom img").remove(),f.switchToImage(b,b.attr("title"))))});a("#boom .close").click(function(a){a.preventDefault();f.close()});a("#boom .reset").click(function(a){a.preventDefault();f.resetZoom()});a(window).resize(function(){a("#boom, #boom-back, #boom .instructions").width(a(window).width()).height(a(window).height());if(a("#boom img").length){var c= f.getSize(a("#boom").data("img").width,a("#boom").data("img").height);a("#boom img,#boom .contents,#boom .captions").width(c.width);a("#boom .controls").width(c.width-10);a("#boom .contents").height(c.height).css({marginTop:0-c.height/2})}});a("#boom .contents").mousewheel(function(c,b){a(this).find("img").length&&f.zoom(c,b);return!1}).mousemove(function(c){a(this).find("img").length&&f.reposition(c.pageX,c.pageY);return!1});a(document).keyup(function(a){a.keyCode==27&&f.close()});a("#boom").data("settings", d)},open:function(d){a.support.opacity?a("#boom").fadeIn():a("#boom").show();a("#boom").append('<div class="instructions"></div>');a("#boom .instructions").width(a(window).width()).height(a(window).height()).click(function(){a(this).remove()});a("#boom .controls ul").empty();var c=a("#boom").data("settings");a(".boom[rel="+d.attr("rel")+"]").each(function(){var b=a(this).find("img").length?a(this).find("img").attr("src"):a(this).parent().find("img").attr("src"),e=b.match(/^\/.*\/([^\/]+)$/);e=!e? b:e[1];e=d.attr("href").indexOf(e.substring(0,e.length-4).replace(c.thumbName,""))>-1?e=' class="active"':"";b=b.replace(c.thumbName,c.tinyName);var h=a.support.opacity?"":' style="font-size:3000px"';a("#boom .controls ul").append('<li style="background-image:url('+b+')"><a'+e+h+' href="#" title="'+a(this).attr("title")+'">&nbsp;</a></li>');f.preload(b.replace(c.thumbName,c.origName))});a("#boom .contents, #boom .controls").attr("style","").removeAttr("style");f.showImage(d.attr("href"),d.attr("title"))}, preload:function(d,c){var b=new Image;if(c){if(c.loaded&&typeof c.loaded=="function")b.onload=function(){c.loaded({width:b.width,height:b.height,src:b.src,obj:a("<img />").attr("src",b.src)})};if(c.loaded&&typeof c.error=="function")b.onerror=function(a){c.error(a)}}b.src=d},reposition:function(d,c){var b=a("#boom .contents"),e=b.offset(),f=b.find("img"),g=d-e.left;e=c-e.top;g=0-(g/b.width()*f.width()-g);b=0-(e/b.height()*f.height()-e);g=Math.ceil(g);b=Math.ceil(b);g>0&&(g=0);b>0&&(b=0);f.css({left:g+ "px",top:b+"px"})},resetZoom:function(){a("#boom img").width(a("#boom .contents").width())},showImage:function(d,c){a("#boom .caption").empty();f.preload(d,{loaded:function(b){c.length>0&&a("#boom .caption").html("<p>"+c+"</p>");a("#boom .contents").prepend(b.obj);var d=a.boom("getSize",b.width,b.height);a("#boom img,#boom .caption").width(d.width);a("#boom .controls").width(d.width-10);a("#boom").data("img",{width:b.width,height:b.height});d.marginTop=0-d.height/2;a.support.opacity?a("#boom-box .contents").animate(d, "fast",function(){a("#boom img").fadeIn()}):(a("#boom-box .contents").css(d),a("#boom img").show())},error:function(b){a.boom("close");alert("Image does not exist: "+d+", "+b)}})},switchToImage:function(d,c){var b=a("#boom").data("settings"),e=d.parent().css("background-image");e=e.replace(/"/g,"").replace(/url\(|\)$/ig,"").replace(b.tinyName,b.origName);a("#boom .active").removeClass("active");d.addClass("active");f.showImage(e,c)},zoom:function(d,c){var b=a("#boom .contents").width(),e=a("#boom").data("img").width, h=a("#boom img").width()+c*60;h>e&&(h=e);h<=b?(b!=e?f.reposition(0,0):f.reposition(0,d.pageY),f.resetZoom()):(a("#boom img").width(h),f.reposition(d.pageX,d.pageY))}};a.boom=function(d){if(f[d])return f[d].apply(this,Array.prototype.slice.call(arguments,1));else if(typeof d==="object"||!d)return f.init(d);else a.error("Method "+d+" 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);

//lucy plugin v7
(function(c){var f={init:function(d){var b=c.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"},d),a={};return this.each(function(){a.div=c(this);a.carousel=c(this).find("ul");a.items=a.carousel.children();a.count=a.items.length/a.carousel.length;a.items.width(b.width).height(b.height).css({marginRight:b.margin}); a.carousel.width(a.count*(b.width+b.margin));c(this).find(".view").width(b.displayed*(b.width+b.margin)-b.margin).height(b.height+b.scrollbarheight);if(b.scrollbar){a.scrollbar=c(this).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="'+i+'"></a>'});a.scrollmarker=c(this).find(".scrollmarker");a.scrollmarker.width(c(this).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(){c(this).click(function(b){b.preventDefault();c(this).lucy("moveTo",a.div,c(this).attr("href"))})})}else if(b.numbar){a.numbar=c(this).find(b.numbarelem);var e="<ul>";for(i=1;i<=a.count;i++)e=e+'<li><a href="#" rel="'+i+'">'+i+"</a></li>";a.numbar.html(e+"</ul>");a.numbar.find("a").click(function(b){b.preventDefault(); c(this).lucy("moveTo",a.div,c(this).attr("rel"))});a.numbar.find("li:first-child a").addClass("active")}c(this).find(b.left).click(function(b){b.preventDefault();a.carousel.is(":animated")||c(this).lucy("moveLeft",a.div)});c(this).find(b.right).click(function(b){b.preventDefault();a.carousel.is(":animated")||c(this).lucy("moveRight",a.div)});c(this).data("settings",b);c(this).data("constants",a);b.autoscroll&&(c(this).lucy("gogoScroller",a.div),c(this).hover(function(){clearInterval(a.timer)},function(){c(this).lucy("gogoScroller", a.div)}))})},gogoScroller:function(d){var b=d.data("settings"),a=d.data("constants");return this.each(function(){a.timer=setInterval(function(){c(this).lucy("moveLeft",a.div)},b.speed);c(this).data("constants",a)})},moveLeft:function(d){var b=d.data("settings"),a=d.data("constants");return this.each(function(){var e=parseInt(a.carousel.css("margin-left"))-b.displayed*b.margin+parseInt(a.carousel.width()),d="-="+(b.width+b.margin);e<=b.displayed*b.width&&(d=0);c(this).lucy("mover",a.div,d)})},mover:function(c, b){var a=c.data("settings"),e=c.data("constants");return this.each(function(){var c=0-parseInt(e.carousel.css("margin-left"));e.carousel.animate({marginLeft:b},a.animtime,a.easing,function(){if(a.displayed==1&&(c/=a.width+a.margin,e.items.eq(c).find("iframe").length)){var b=e.items.eq(c).html();e.items.eq(c).empty().html(b)}a.scrollbar?(b=(0-parseInt(e.carousel.css("margin-left"))/e.carousel.width())*e.scrollmarker.parent().width(),a.scrollbarsnap?e.scrollmarker.css({marginLeft:b}):e.scrollmarker.animate({marginLeft:b}, "fast")):a.numbar&&(b=0-parseInt(e.carousel.css("margin-left"))/(a.width+a.margin)+1,e.numbar.find(".active").removeClass("active"),e.numbar.find("a[rel="+b+"]").addClass("active"))})})},moveRight:function(d){var b=d.data("settings"),a=d.data("constants");return this.each(function(){var e="+="+(b.width+b.margin);parseInt(a.carousel.css("margin-left"))>=0&&(e="-="+(a.count-b.displayed)*(b.width+b.margin));c(this).lucy("mover",a.div,e)})},moveTo:function(d,b){var a=d.data("settings"),e=d.data("constants"); return this.each(function(){var d=e.count-a.displayed;b>d?b=d:b--;c(this).lucy("mover",e.div,0-b*(a.width+a.margin))})}};c.fn.lucy=function(d){if(f[d])return f[d].apply(this,Array.prototype.slice.call(arguments,1));else if(typeof d==="object"||!d)return f.init.apply(this,arguments);else c.error("Method "+d+" does not exist fool!")}})(jQuery);

//jquery columnize plugin - http://plugins.jquery.com/project/columnize
(function(){var cloneEls=new Object();var numColsById=new Object();var uniqueId=0;function _layoutElement(elDOM,settings,balance){var colHeight;var colWidth;var col;var currentColEl;var cols=new Array();var colNum=0;var colSet=0;var el=jQuery(elDOM);numColsById[elDOM.id]=settings.columns;el.empty();function _newColumn(){colNum++;col=document.createElement("DIV");col.className=settings.column;el.append(col);currentColEl=col;colWidth=jQuery(col).width();cols.push(col);for(var j=0;j<subnodes.length;j++){newEl=subnodes[j].cloneNode(false);if(j==0||innerContinued){jQuery(newEl).addClass(settings.continued);}
currentColEl.appendChild(newEl);currentColEl=newEl;}}
function _getMarginBottom(currentColEl){var marginBottom=parseInt(jQuery(currentColEl).css("marginBottom"));if(marginBottom.toString()=='NaN'){marginBottom=0;}
var currentColElParents=jQuery(currentColEl).parents();for(var j=0;j<currentColElParents.length;j++){if(currentColElParents[j]==elDOM){break;}
var curMarginBottom=parseInt(jQuery(currentColElParents[j]).css("marginBottom"));if(curMarginBottom.toString()!='NaN'){marginBottom=Math.max(marginBottom,curMarginBottom);}}
return marginBottom;}
function _skipToNextNode(){while(currentEl&&currentColEl&&!currentEl.nextSibling){currentEl=currentEl.parentNode;currentColEl=currentColEl.parentNode;var node=subnodes.pop();if(node=="A"){href=null;}}
if(currentEl){currentEl=currentEl.nextSibling;}}
var maxHeight=settings.height?settings.height:parseInt(el.css("maxHeight"));if(balance||isNaN(maxHeight)||maxHeight==0){col=document.createElement("DIV");col.className=settings.column;jQuery(col).append(jQuery(cloneEls[elDOM.id]).html());el.append(col);var lineHeight=parseInt(el.css("lineHeight"));if(!lineHeight){lineHeight=Math.ceil(parseInt(el.css("fontSize"))*1.2);}
colHeight=Math.ceil(jQuery(col).height()/settings.columns);if(colHeight%lineHeight>0){colHeight+=lineHeight;}
elDOM.removeChild(col);if(maxHeight>0&&colHeight>maxHeight){colHeight=maxHeight;}}else{colHeight=maxHeight;}
var minHeight=settings.minHeight?settings.minHeight:parseInt(el.css("minHeight"));if(minHeight){colHeight=Math.max(colHeight,minHeight);}
var currentEl=cloneEls[elDOM.id].children(":first")[0];var subnodes=new Array();var href=null;var lastNodeType=0;_newColumn();if(colHeight==0||colWidth==0){return false;}
while(currentEl){if(currentEl.nodeType==1){var newEl;var $currentEl=jQuery(currentEl);if($currentEl.hasClass("dontSplit")||$currentEl.is(settings.dontsplit)){var newEl=currentEl.cloneNode(true);currentColEl.appendChild(newEl);if(col.offsetHeight>colHeight){_newColumn();}
_skipToNextNode();}else{var newEl=currentEl.cloneNode(false);currentColEl.appendChild(newEl);if(col.offsetHeight-_getMarginBottom(currentColEl)>colHeight){currentColEl.removeChild(newEl);var toBeInsertedEl=newEl;_newColumn();currentColEl.appendChild(toBeInsertedEl);newEl=toBeInsertedEl;}
if(currentEl.firstChild){subnodes.push(currentEl.cloneNode(false));currentColEl=newEl;currentEl=currentEl.firstChild;}else{_skipToNextNode();}}
lastNodeType=1;}else if(currentEl.nodeType==3){var newEl=document.createTextNode("");currentColEl.appendChild(newEl);var marginBottom=_getMarginBottom(currentColEl);var words=currentEl.data.split(" ");for(var i=0;i<words.length;i++){if(lastNodeType==3){newEl.appendData(" ");}
newEl.appendData(words[i]);currentColEl.removeChild(newEl);currentColEl.appendChild(newEl);if(col.offsetHeight-marginBottom>colHeight){newEl.data=newEl.data.substr(0,newEl.data.length-words[i].length-1);var innerContinued;if(jQuery(currentColEl).text()==""){jQuery(currentColEl).remove();innerContinued=false;}else{innerContinued=true;}
_newColumn();newEl=document.createTextNode(words[i]);currentColEl.appendChild(newEl);}
lastNodeType=3;}
_skipToNextNode();lastNodeType=0;}else{_skipToNextNode();lastNodeType=currentEl.nodeType;}}
return cols;};jQuery.fn.columnize=function(settings){settings=jQuery.extend({column:"column",continued:"continued",columns:2,balance:true,height:false,minHeight:false,cache:true,dontsplit:""},settings);this.each(function(){var jthis=jQuery(this);var id=this.id;if(!id){id="jcols_"+uniqueId;this.id=id;uniqueId++;}
if(!cloneEls[this.id]||!settings.cache){cloneEls[this.id]=jthis.clone(true);}
var cols=_layoutElement(this,settings,settings.balance);if(!cols){jthis.append(cloneEls[this.id].children().clone(true));}});return this;}})();

//jquery easing plugin - http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing['jswing']=jQuery.easing['swing'];jQuery.extend(jQuery.easing,{def:'easeOutQuad',swing:function(x,t,b,c,d){return jQuery.easing[jQuery.easing.def](x,t,b,c,d);},easeInQuad:function(x,t,b,c,d){return c*(t/=d)*t+b;},easeOutQuad:function(x,t,b,c,d){return-c*(t/=d)*(t-2)+b;},easeInOutQuad:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;},easeInCubic:function(x,t,b,c,d){return c*(t/=d)*t*t+b;},easeOutCubic:function(x,t,b,c,d){return c*((t=t/d-1)*t*t+1)+b;},easeInOutCubic:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t+b;return c/2*((t-=2)*t*t+2)+b;},easeInQuart:function(x,t,b,c,d){return c*(t/=d)*t*t*t+b;},easeOutQuart:function(x,t,b,c,d){return-c*((t=t/d-1)*t*t*t-1)+b;},easeInOutQuart:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t+b;return-c/2*((t-=2)*t*t*t-2)+b;},easeInQuint:function(x,t,b,c,d){return c*(t/=d)*t*t*t*t+b;},easeOutQuint:function(x,t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b;},easeInOutQuint:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t*t+b;return c/2*((t-=2)*t*t*t*t+2)+b;},easeInSine:function(x,t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b;},easeOutSine:function(x,t,b,c,d){return c*Math.sin(t/d*(Math.PI/2))+b;},easeInOutSine:function(x,t,b,c,d){return-c/2*(Math.cos(Math.PI*t/d)-1)+b;},easeInExpo:function(x,t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOutExpo:function(x,t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOutExpo:function(x,t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;},easeInCirc:function(x,t,b,c,d){return-c*(Math.sqrt(1-(t/=d)*t)-1)+b;},easeOutCirc:function(x,t,b,c,d){return c*Math.sqrt(1-(t=t/d-1)*t)+b;},easeInOutCirc:function(x,t,b,c,d){if((t/=d/2)<1)return-c/2*(Math.sqrt(1-t*t)-1)+b;return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b;},easeInElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);return-(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;},easeOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);return a*Math.pow(2,-10*t)*Math.sin((t*d-s)*(2*Math.PI)/p)+c+b;},easeInOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d/2)==2)return b+c;if(!p)p=d*(.3*1.5);if(a<Math.abs(c)){a=c;var s=p/4;}
else var s=p/(2*Math.PI)*Math.asin(c/a);if(t<1)return-.5*(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;return a*Math.pow(2,-10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p)*.5+c+b;},easeInBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*(t/=d)*t*((s+1)*t-s)+b;},easeOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b;},easeInOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;if((t/=d/2)<1)return c/2*(t*t*(((s*=(1.525))+1)*t-s))+b;return c/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;},easeInBounce:function(x,t,b,c,d){return c-jQuery.easing.easeOutBounce(x,d-t,0,c,d)+b;},easeOutBounce:function(x,t,b,c,d){if((t/=d)<(1/2.75)){return c*(7.5625*t*t)+b;}else if(t<(2/2.75)){return c*(7.5625*(t-=(1.5/2.75))*t+.75)+b;}else if(t<(2.5/2.75)){return c*(7.5625*(t-=(2.25/2.75))*t+.9375)+b;}else{return c*(7.5625*(t-=(2.625/2.75))*t+.984375)+b;}},easeInOutBounce:function(x,t,b,c,d){if(t<d/2)return jQuery.easing.easeInBounce(x,t*2,0,c,d)*.5+b;return jQuery.easing.easeOutBounce(x,t*2-d,0,c,d)*.5+c*.5+b;}});
