/**
 * jget plugin
 * @author Alexandre Magno
 * @desc get a query string to be accessible for javascript
 * @version 1.0
 * @example
 *
 * http://www.foo.com/test.php?var1=test1
 * var outputQuery = $.jget['var1'];
 * $.debug(outputQuery);
 * //Will show 'test1'
 *
 *
 * @license free
 * @param bool vertical, bool horizontal
 * @site http://blog.alexandremagno.net
 *
 */

jQuery.extend({

	//starting the jget object
	jget: {},
	//get the url
	url: window.location.href.replace(/^[^\?]+\??/,''),
	//get the queryString
	parseQuery: function ( query ) {
		var Params = {};
		if ( ! query ) {return Params;}// return empty object
		var Pairs = query.split(/[;&]/);
		for ( var i = 0; i < Pairs.length; i++ ) {
			var KeyVal = Pairs[i].split('=');
			if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
			var key = unescape( KeyVal[0] );
			var val = unescape( KeyVal[1] );
			val = val.replace(/\+/g, ' ');
			Params[key] = val;
		}
		return Params;
	},
	//Make the jget object available to jQuery.extend
	getQueryString: function() {
		this.jget = this.parseQuery(this.url);
	},
	//debugging
	debug: function(message) {
		if(!$.browser.msie) {
			console.info(message);
		} else if($.browser.safari) {
			window.console.log(message);
		} else {
			alert(message);
		}
	}
});

//start the plugin
$.getQueryString();


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// NOTE Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else { // only name given, get cookie
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
};


/***************************************
  Columns
   @author Karl Swedberg
   @version 0.2 (08/19/2008)
   @requires jQuery v1.2.6+
  
***************************************/

(function($) {
$.fn.columns = function(options) {
  var opts = $.extend(true, {}, $.fn.columns.defaults, options);

  return this.each(function(event) {
    var $container = $(this),
      nname = this.nodeName,
      $kids = $container.children(),
      col = 1,
      item = 1,
      items = [],
      cClass = opts.columnClass;
    
    if (opts.columnWrapper) {
      var cw = this.className ? this.className + ' ' + opts.columnWrapperClass : opts.columnWrapperClass;
      var $wrap = $(opts.columnWrapper)
        .addClass(cw + ' ' + cw + '-' + opts.columns)
        .attr('id', this.id)
        .insertBefore($container);
    }
    for (var i=0, klength = $kids.length; i < klength; i++) {
      items.push($kids[i]);
      var itemStart = (klength/opts.columns)*col;
      if (i+1 >= itemStart || i === klength-1) {
      item = Math.ceil(itemStart);  
        var $parent = $('<' + nname + ' class="' + cClass + ' ' + cClass + '-' + col + '"></' + nname + '>')
          .append($(items));
        if (i === klength-1) {
          $parent.addClass(cClass + '-last');
        }
        if (opts.columnWrapper) {
          $parent.appendTo($wrap);
        } else {
          $parent.insertBefore($container);
        }
        if ($parent[0].nodeName == 'OL' && col > 1) {
          $parent.attr('start', start);
        }
        col++;
        items = [];
      }
      var start = item+1;
    }
    
    $container.remove();


  });
};

})(jQuery);


$.fn.columns.defaults = {
	columns: 3,
	columnClass: 'floatcols',
	columnWrapper: '<div></div>', // set to null if you don't want a wrapper around all columns
	columnWrapperClass: 'column-wrapper'
};

/* Browser sniffing?! Only used to lay an  over select boxes in IE6 */
ie6 = false;
if ($.browser.msie) {
	if(parseInt(jQuery.browser.version, 10) == 6){
		ie6 = true;
	}
}

/* catch and replace for swfs */
if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
	$("div.flashalt-pre").addClass("flashalt").removeClass("flashalt-pre").show("normal");
}

OVERLAY = {
	called : false,
	postimeout : 0,
	init : function(triggers){
		// Create overlay div to darken background
		if(!OVERLAY.called){
			OVERLAY.called = true;
			var overlaydiv = document.createElement("div");
			$(overlaydiv).attr("id", "overlay");
			$("body").append(overlaydiv);
			overlaydiv = $(overlaydiv);
			overlaydiv.hide();
			overlaydiv.fadeOut(10);
			overlaydiv.width($("body").width());
			overlaydiv.height($(document).height());   
			overlaydiv.bind("click", OVERLAY.closeOverlay);
			// Create holder div to load overlays into
			var holderdiv = document.createElement("div");
			$(holderdiv).attr("id", "popupholder");
			$(holderdiv).hide();
			$("body").append(holderdiv);
			// Bind close events
			$(document).keyup(function(event){
				if (event.keyCode == 27) {
					OVERLAY.closeOverlay();
				}
			});
		}
		// Link anchors
		$(triggers).bind("click", OVERLAY.openOverlay);
	},
	closeOverlay: function(){
	  if(typeof(pageTracker) == "Object"){
		pageTracker._trackEvent("Overlay", "close");
	  }
		$("#popupholder iframe").attr("src", "");
		$("#popupholder").fadeOut(250, function(){
			if(ie6){
				$("select").css("visibility", "visible");
			}
			$("#overlay").fadeOut(250,function(){
				$("#popupholder").empty();	
			});
		});
		return false;
	},
	openOverlay: function(){
		if(ie6){
			$("select").css("visibility", "hidden");
		}
		$("#overlay").show();
	//	$("#popupholder").show();
		var $this = $(this),
		url = $(this).attr("href");
    if(typeof(pageTracker) == "Object"){
      pageTracker._trackEvent("Overlay", "open", url);
      }
		$("#overlay").css("height", $(document).height()+"px");
		$("#overlay").css("width", $(window).width()+"px");
		
		$("#overlay").fadeTo(250, 0.25);
		// Just load 'oc' (overlay content) div, not whole document
		$("#popupholder").load(url + " #oc", {}, function(data){
			
			if($this.hasClass("video")) {
				flowplayer("player", "/swfs/flowplayer-3.2.5.swf");
			}
			
			OVERLAY.postimeout = setInterval(OVERLAY.posOverlay, 100);
			$("#popupholder").fadeIn(250);
			$("#closeoverlay a, #oc .picoverlay img").bind("click", OVERLAY.closeOverlay);
			$('#contenttabs').before('<ul id="sizenav">').cycle({
				fx:			'fade',
				timeout:	4000,
				speed:		'slow',	    
				height:		319,
				cleartype:	false,
				pager:		'#sizenav',
				pagerAnchorBuilder: function(idx, slide) { 
					return '<li><a href="#">'+$(slide).attr("title")+'</a></li>'; 
				}
			});
			OVERLAY.init("#oc .viewnutrition");
			$('#contenttabs').cycle('pause');
			
			
		});
		return false;
	},
	
	posOverlay: function(){ 
		if($("#oc").width() < 200) {return false;}
		clearInterval(OVERLAY.postimeout);
		$("#oc").css("margin-left", ($(window).width()/2)-($("#oc").width()/2)+"px");
		$("#oc").css("margin-top", ($(window).height()/2)-($("#oc").height()/2)+"px");	
	}
};

function jumpLocation(itemid){
	$("#"+itemid).addClass("highlighted");
	newtop = $("#"+itemid).offset();
	$('html,body').animate({scrollTop: newtop.top+"px"});
	return false;
}

function faqs(){
	if(document.location.href.split("#").length > 1){
	jumpLocation(document.location.href.split("#")[1]);}
	$("#faqlist a").bind("click", function(){
		$("li.highlighted").removeClass("highlighted");
		return jumpLocation($(this).attr("href").split("#")[1]);
	});
	$("p.backtotop a").bind("click", function(){
		return jumpLocation("faqlist");
	});
}



function columnLayout(){
    if($(".pathways").hasClass("col2")){
        $(".pathways li:nth-child(2n-1)").addClass("first");
    }
    if($(".pathways").hasClass("col3")){
        $(".pathways li:nth-child(3n-2)").addClass("first");
    }
}
RECIPETOOLS  = {
	currentopen : "",
	printwin : "",
	init : function(triggers){
		$(triggers).bind("click", function(){
			pageTracker._trackEvent("RecipeTools", "Print", document.title);
			RECIPETOOLS.printwin = window.open($(this).attr("href"), "printwin", "height=600,width=800,resizable=no,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no");
			return false;
		});
	},
	hide : function(){
		if(RECIPETOOLS.currentopen != ""){
			$(RECIPETOOLS.currentopen).removeClass("open");
			RECIPETOOLS.currentopen = "";
		}
		if(RECIPETOOLS.printwin != ""){
			RECIPETOOLS.printwin.close();
			RECIPETOOLS.printwin = "";
		}
	},
	doprint : function(){
		RECIPETOOLS.printwin.print();
		pageTracker._trackEvent("RecipeTools", "Print-Click", document.title);
		RECIPETOOLS.hide();
		return false;
	}
};

COUNTRYSELECT = {	
	inactivestates : {},
	init : function(){
		inactive = COUNTRYSELECT.inactivestates; cd = "#countrydropdown"; sd = "#statedropdown";
		inactive.US = Array();
		$(cd+","+sd).addClass("js");
//		$(cd+", label[for=countrydropdown]").show();
		$(cd+" option[value=US]").attr("selected", "selected");
		
		$(sd+" optgroup option").each(function(i,opt){
			$(opt).addClass($($(opt).parent().get(0)).attr("class"));
		});
		$(sd+" optgroup option").clone().appendTo(sd);
		$(sd+" optgroup").remove();
		
		$(cd+" option[value!=US]").each(function(i,opt){
			inactive[$(opt).val()] = $(sd+" option[class="+$(opt).val()+"]").remove();
		});
		
		$(cd).bind("change", function(){
			$(cd+" option").each( function(i,opt){
				if (inactive[$(opt).val()].length === 0){
					inactive[$(opt).val()] = $(sd+" option[class="+$(opt).val()+"]").remove();
				}
			});
			$(sd).append(inactive[$(cd+" option:selected").val()]);
			inactive[$(cd+" option:selected").val()] = Array();
			
		});
		
		COUNTRYSELECT.getLocations('true');
		
		$("form.findastore").bind("submit", COUNTRYSELECT.getLocations);
	},
	
	getLocations : function(onload){
		$("#countrydropdown, #statedropdown, #familydropdown").attr('disabled', 'disabled');
		$("#locationlist").empty().html('<div class="loader"></div>');
		$.get(
			$("form.findastore").attr("action"),
			{countrydropdown: (onload == 'true' ? $.jget['countrydropdown'] : $("#countrydropdown option:selected").val()),
			statedropdown: (onload == 'true' ? $.jget['statedropdown'] : $("#statedropdown option:selected").val()),
			familydropdown: (onload == 'true' ? $.jget['familydropdown'] : $("#familydropdown option:selected").val())},
			function(data){
				pageTracker._trackPageview($("form.findastore").attr("action")+"?countrydropdown="+ $("#countrydropdown option:selected").val()+"&statedropdown="+$("#statedropdown option:selected").val()+"&familydropdown="+$("#familydropdown option:selected").val());
				$("#locationlist").html(data);
				$('.stategroup ul').columns({columns: 3, columnClass: 'storelist', columnWrapper: null});
				$('.stategroup:last').next().remove();
				$("#countrydropdown, #statedropdown, #familydropdown").removeAttr('disabled');
			}
		);
		$("#findstores").blur();
		return false;
	}
	
};
		
function dealersBrokers(){
	$("#dealersbrokers").empty();
	$.get(
		$("#dealerstate").attr("action"),
		{state: $("#dealerstate option:selected").val()},
		function(data){
			$("#dealersbrokers").html(data);
		}
	);
	return false;
}

var fieldtext = [];
function memorizeTextField(fs, ft){
	if($(fs).length < 1){ return false;}
	fieldtext[fs] = ft;
	var fieldstring = fs;
	if($(fs).val() == ""){
	$(fs).val(fieldtext[fs]);}
	$(fs).bind("click, focus", function(){
		if($(this).val() == fieldtext[fieldstring]){
			$(this).addClass("activated")
			$(this).val("");
		}
	});
	$(fs).bind("blur", function(){
		if($(this).val() == ""){
			$(this).removeClass("activated")
			$(this).val(fieldtext[fieldstring]);
			
		}
	});
}

var addthis_config = {
	username: 'lindsayolives',
	services_compact: 'print, email, digg, facebook, delicious, twitter, favorites, more',
	data_ga_property: 'UA-6725770-1',
  data_track_clickback: true
};


var fctester = 0;
function check_fc(){
	if(typeof(fc_json) != "undefined"){
		if(typeof(fc_json["product_count"]) != "undefined"){
			clearInterval(fctester);
			if(fc_json.product_count > 0){
				$("#viewbasket .checkout").show();
			} else {
			   $("#viewbasket .foxycart").html("<strong>View Basket</strong>");
			}
			$("#viewbasket .foxycart").show();
			$("#viewbasket").css("visibility","visible");
		}
	}
}

var recipeAnimating = false;
function animateRecipeHero(nextSlide){
	if(recipeAnimating){return};
	var current = $(".recipe-hero:visible");
	if(current.attr("id") == nextSlide.attr("id")){
		return;
	}
	recipeAnimating = true;
	current.css("z-index", "9000");
	nextSlide.css("z-index", "8000");
	
	current.find(".recipe-description").animate({left: "-380px"}, 250, function(){
		nextSlide.find(".recipe-description").css("left", "-380px")
		current.fadeOut(250);
		nextSlide.fadeIn(250, function(){
			nextSlide.find(".recipe-description").animate({left: 0}, 250, function(){
				recipeAnimating = false;
			});
		});
	});
	nextSlide.show();
}


function scrollRecipeSearch() {
	var $sidebar   = $("#findrecipes"),
	$window    = $(window),
	offset     = $sidebar.offset(),
	topPadding = 15;
	maxAddition = $("#primary").height()-$sidebar.height()-topPadding-30;

	$window.scroll(function() {
		if ($window.scrollTop() > offset.top) {
			newTop = ($window.scrollTop() - offset.top + topPadding);
			if(newTop > maxAddition) newTop = maxAddition;
			$sidebar.stop().animate({
				marginTop: newTop
			});
		} else {
			$sidebar.stop().animate({
				marginTop: 0
			});
		}
	});
}

homepageAutoRotate = 1;
recipesAutoRotate = 1;
$(document).ready(function(){
	swfobject.embedSWF("/swfs/overview/accents.swf", "productbanner440", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/adventures.swf", "productbanner80", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/blackripe.swf", "productbanner8", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/natural.swf", "productbanner37", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/perfect-paring.swf", "productbanner86", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/snackers.swf", "productbanner38", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/spanish-manz.swf", "productbanner102", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/spanish-queen.swf", "productbanner946", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	swfobject.embedSWF("/swfs/overview/recloseables.swf", "productbanner880", "611", "273", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});

	
	swfobject.embedSWF("/swfs/productsoverview_shell.swf", "productsoverview", "950", "400", "9.0.0", "", {path:"/swfs/"}, {menu: "false", wmode: "transparent"});
	
	RECIPETOOLS.init("#recipeprint, #recipeprintbutton, #olivetoss a,.recipelink");
	$("#printrecipe").bind("click", function(){window.opener.RECIPETOOLS.doprint();});
	
	if($(".search-results #findrecipes").length > 0){
		scrollRecipeSearch()
	}
	
	if($("#recipes-featured-nav").length > 0){
		$("#recipes-featured-nav a").bind("click", function(e){
			if(typeof e.screenX != "undefined"){
				clearInterval(recipesAutoRotate)
			}
			animateRecipeHero($($(this).attr("href")));
			$("#recipes-featured-nav .current").removeClass("current")
			$(this).addClass("current").blur();
			
			return false;
		})
		$("#recipes-featured-nav li:first a").trigger("click");
		
		recipesAutoRotate = setInterval(function(){
			nextRecipe = $("#recipes-featured-nav .current").parent("li").next("li").find("a");
			if(nextRecipe.length == 0){
				nextRecipe = $("#recipes-featured-nav li:first a");
			}
			nextRecipe.trigger("click")
		}, 4500)
		
	}
	
	$(".recipe-hero").hover(
		function(){
			$(this).addClass('hover');
		},
		function(){
			$(this).removeClass('hover');
	}
	).bind("click", function(){
		document.location = $(this).find("a:first").attr("href");
	})
	

	$("table.search tbody tr:nth-child(even)").addClass("even");
    $(".storeoverview li:lt(2)").addClass("first");
    $(".storecats li:nth-child(3n-2)").addClass("first");
    $("#productspecs li:nth-child(3n-2)").addClass("first");
    $(".contentlist li:first").addClass("first");
	
	$("body:eq(0)").prepend("<a href=\"/emergency-message\" id=\"emergencylink\"></a>");

	OVERLAY.init("p.enlarge a, #nutritionlink, .sidebar .photo a, #productspecs a,.videolink, #emergencylink, .overlaylink");
	
	if($("#countrydropdown").length > 0){
		COUNTRYSELECT.init();
	}
	
	if($("#faqlist").length > 0){
		faqs();
	}
	columnLayout();
	
	if($("#dealersbrokers").length > 0){
		dealersBrokers();
	}
	$("#statesubmit").click(dealersBrokers);
	
	fctester = setInterval(check_fc, 500);
	
	$("form.foxycart input[type=submit]").bind("click", function(){
		$("#viewbasket .foxycart").html("<strong>View Basket:</strong> <span id=\"fc_quantity\"></span> Items.");
		$("#viewbasket .checkout").show();
	});
	
	if($("select[name='search']").length > 0){
		$("select[name='search']").change(function(){
		   $(this).parents("form").submit();
		});
	}
	

	
	memorizeTextField("#first_name", "First Name");
	memorizeTextField("#last_name", "Last Name");
	memorizeTextField("#email_address", "Email");
	memorizeTextField("#zip_code", "Zip");
	
	memorizeTextField("#finderright #recipe_search", "Search by keyword");

	$("a[rel~=external]").attr("target","_blank");
	
	$("a[rel~=track]").bind("click",function(){pageTracker._trackPageview("/_exit/"+$(this).attr("rel").replace("track_",""));});
	
	$("#productquickfinder").hover(
		function(){
			$(this).addClass("hover");
		}, 
		function(){
			$(this).removeClass("hover");
		}
	);

	//Comment out the lines below when no emergency notification is active
	/*if ($.cookie("emergencyoverlay") == null) {
				
		$.cookie("emergencyoverlay", "true", {expires: 14});
		
		$("#emergencylink").click(); 

	} */

	//Uncomment the line below when no emergency notification is active
	$.cookie("emergencyoverlay", null, {expires: 12});
	
	if ($.browser.msie && $.browser.version < 9) $('select.wide')
	    .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
	    .bind('click', function() { $(this).toggleClass('clicked'); })
	    .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
	    .bind('blur', function() { $(this).removeClass('expand clicked'); });
	
			if($("#homepage").length < 1){return}

			// homepage stuff
				firstLi = $("#homepage-rotator-navigation li:first");
				$('#homepage-rotator-navigation').infiniteCarousel();
				$("#browse-by-cat").click(function(){
					if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
						$("#homepage-recipe-browser").toggle('fast');
					} else {
						$("#homepage-recipe-browser").slideToggle('fast');
					}
					return false;
				});
				$("#homepage-rotator-navigation img").css("opacity", 0.6)
				$("#homepage-rotator-navigation li").hover(
					function(){
						$(this).find("img").animate({"opacity" : 1}, 200)
						$(this).addClass("hover");
					}, 
					function(){
						if(!$(this).hasClass("current")){
							$(this).find("img").animate({"opacity": 0.6}, 200)
							$(this).removeClass("hover");
						}
					}
				)
				$("#homepage-rotator-navigation li").bind("click", function(e){
					if(typeof e.screenX != "undefined"){
						clearInterval(homepageAutoRotate)
					}
					if($(this).hasClass("current")){return false;}
					$("#homepage-rotator-navigation .current img").animate({"opacity": 0.6}, 200)
					$("#homepage-rotator-navigation .current").removeClass("current").removeClass("hover");
					$(this).addClass("current").blur();
					$(this).find("img").css("opacity", 1);
					animateRecipeHero($($(this).find("a").attr("href")));
					return false;
				});
				firstLi.trigger("click");
				
				homepageAutoRotate = setInterval(homepageRotate, 5000)
	
});


var currentClick = 1;

function homepageRotate() {
	if(currentClick == 3){
		$(".arrow.forward").trigger("click");
		var temp  = setTimeout(function(){$("#homepage-rotator-navigation .current+li").trigger("click")}, 500)
		currentClick = 1;
	} else {
		$("#homepage-rotator-navigation .current+li").trigger("click")
		currentClick++;
	}
}

function homepageNavigation() {
	
}

$.fn.infiniteCarousel = function () {
	function repeat(str, num) {
		return new Array( num + 1 ).join( str );
	}

	return this.each(function () {
		var $wrapper = $('> div', this).css('overflow', 'hidden'),
			$slider = $wrapper.find('> ul'),
			$items = $slider.find('> li'),
			$single = $items.filter(':first'),

			singleWidth = $single.outerWidth(), 
			visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
			currentPage = 1,
			pages = Math.ceil($items.length / visible);            

		function gotoPage(page) {
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;

			
			//set order of elements
			currentLeft = $slider.css("marginLeft").replace("px","")*1;


			// Going forwards
			if(dir == 1 && currentLeft < 0){
				for(var i = 0; i < 3; i++){
					$slider.find("li:first").appendTo($slider);
				}
				$slider.css({marginLeft:  currentLeft + left});
			}
			
			// going backwards
			if(dir == -1 &&  currentLeft == 0){

				for(var i = 0; i < 3; i++){
					$slider.find("li:last").prependTo($slider);
				}
				$slider.css({marginLeft:  currentLeft + left});
			}
			
			// Do animation
			$($wrapper.find('> ul:not(:animated)')).animate({marginLeft : '+=' + left*-1}, 500)

			return false;
		}

		$wrapper.after('<a class="arrow back"><span>&lt;</span></a><a class="arrow forward"><span>&gt;</span></a>');

		// 5. Bind to the forward and back buttons
		$('a.back', this).click(function (e) {
			if(typeof e.screenX != "undefined"){
				clearInterval(homepageAutoRotate)
			}
			return gotoPage(currentPage - 1);
		});

		$('a.forward', this).click(function (e) {
			if(typeof e.screenX != "undefined"){
				clearInterval(homepageAutoRotate)
			}
			return gotoPage(currentPage + 1);
		});

		// create a public interface to move to a specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
	});  
};
