﻿/*  
==  CENTURY UK FUNCTIONS
==  Eonicweb 2011
==  Authors: Will Hancock & Calvin Davis
*/

// global vars
var hideCartTimer;
var timeout = null;
var cartTotal = null; 


// Document ready function
$(document).ready(function () {
    initialiseMainMenu();
    initialiseUserLogin();

    // setup for the ajax cart
    if ($("#orderBrief .cartTotal").exists()) {
        cartTotal = Number($("#orderBrief .cartTotal").html().substring(1).replace(/,/gi, ''))
    }
    ajaxCart();

    // dealer search
    if ($(".dealerSearchListing ").exists()) {
        dealerSearch();
    }

    // listener for geocoder button when editing contacts
    initialiseContactGeocoderButton();

    // quick order form
    if ($('.quickOrderForm').exists()) {
        initialiseQuickOrderForm();
    }

    $('body').addClass('js');
    galleryThumbList();

    // product detail additional content
    if ($('.additionContent').exists()) {
        addtionalContent();
    }

    if ($("#column1 .ProductPageMenu").exists() && $("#column2 .ProductPageMenu").exists()) {
        equalHeightByRow();
    }

    //equalHeight($(".ProductPageMenu .productMenu "));

});


/**
* Runs after common JavaScript
*/
function ewAfterCommon() {
}

function addtionalContent() {
    $('.additionContent').hide();
    $('.additionContent:first').show();
    $('.additionalLinks ul li:first a').addClass('active');

    $('.additionalLinks ul li a.addLinks').click(function (clicky) {
        clicky.preventDefault();

        if ($(this).hasClass('active') == false) {

            $('.additionalLinks ul li a').removeClass('active');
            $(this).addClass('active');
            var currentTab = $(this).attr('href');
            $('.additionContent').slideUp();
            $(currentTab).slideDown();
        }
    });
}

/* Slides open the user login box at the top of the page */
function initialiseUserLogin() {
	var $userLogin = $('#userLogin');
	
	// Show if there is an alert, otherwise hide
	if ($userLogin.find('.alert').exists()) {
		$userLogin.show();
	} else {
		$userLogin.hide();
	}

    $('#loginLink .login').click(function (e) {
        e.preventDefault();
        $userLogin.slideToggle();
    });
}



function galleryThumbList() {
    // setup for .GalleryImageList
    if ($('.thumbList').exists() == true) {

        // link hover hide and show
        $('.GalleryImageList .active').css('display', 'block');
        var gallery = $('.GalleryImageList');
        var imgLarge = $('.lightbox.active');

        centreItem(gallery, imgLarge);

        //        add indicator arrow graphic
        //        $('<span id="linkArrow"></span>').appendTo('#linkNav');
        //        linkArrowPos();

        // Create and setup background images for fade in and out
        $('.thumbList a').each(function () {

            var itemId = $(this).attr('id').replace(/tn/g, 'det');
            var itemImgName = $(this).attr('rel');

            //            $('<div id="homeBg' + itemId + '" class="homeBg"></div>').appendTo('#main');
            //            $('#homeBg' + itemId).css('background-image', 'url(' + itemImgName + ')');
            //            $('.homeBg:first').show();
        });

        $('.thumbList a').click(function (e) {
            e.preventDefault();
            var gallery = $(this).parents('.GalleryImageList');
            var imgLarge = gallery.find('.lightbox');
            var itemId = $(this).attr('id').replace(/tn/g, 'det');
            //          var linkOffset = $(this).offset().left;
            //          var linkWidth = ($(this).width() + 10) / 2;

            if (!$('#' + itemId).is(':visible')) {
                // fade all large images out
                imgLarge.each(function () {
                    $(this).fadeOut().removeClass('active');
                });
                //                $('.homeBg').each(function () {
                //                    $(this).fadeOut()
                //                });

                // locate the relevant large image and show
                $('#' + itemId).addClass('active').fadeIn();

                //              $('#homeBg' + itemId).fadeIn();

                //              linkArrowPos(linkOffset, linkWidth);

                //centre the large image in the gallery space
                centreItem(gallery, $('#' + itemId));
            }
        });

        // set link href to use the title attribute
        //        $('#linkNav a').each(function () {
        //            $(this).attr('href', $(this).attr('title'));
        //        });
    }
}

function centreItem(container, item) {

    var containerWidth = container.width();

    item.each(function () {
        var itemWidth = $(this).width();
        var offset = (containerWidth - itemWidth) / 2;

        item.css('left', offset + 'px');
    });
}




/**
* AJAX add to cart functions
*/
function ajaxCart() {

    // view hide cart listener
    $("a#viewCart").click(function (clicky) {
        clicky.preventDefault();
        cartBriefOpenClose();
    });

    cartActionListeners();

}

/* Function to trigger listners for the cartListing */
function cartActionListeners() {

    /* Add to cart button action */
    $("input[name='cartAdd']").click(function (clicky) {
        clicky.preventDefault();
        // clear interval incase they have already clicked.
        clearInterval(hideCartTimer);
        // disable button
        $(this).attr('disabled', 'disabled');
        $(this).addClass('disabled');
        $(this).val('Please wait...');

        ajaxAddToCart($(this).parents("form"));

        // if quick order add to cart
        if ($(this).parents(".quickAddListing").exists()) {
            resetQuickOrderForm();
        }
    });
    cartBriefActionListeners();
}

// listeners on cart Brief
function cartBriefActionListeners() {
    /* Delete action */
    $("#cartListingBrief a.delete").click(function (clicky) {
        clicky.preventDefault();
        // user using it so clear hide timer
        clearInterval(hideCartTimer);

        var cartCmd = $(this).attr('href');
        var parentRowId = $(this).parents("tr.orderItem").attr('id');
        deleteCartRow(parentRowId, cartCmd);

    });

    /* Update Qty actions */
    $("#cartListingBrief .qtyControls a").click(function (clicky) {
        clicky.preventDefault();
        // user using it so clear hide timer
        clearInterval(hideCartTimer);

        var action;
        if ($(this).hasClass('increase')) {
            action = 'increase';
        } else if ($(this).hasClass('decrease')) {
            action = 'decrease';
        }

        if (action) {
            // lets do something
            var cartCmd;
            var newQty;
            var parentRowId = $(this).parents("tr.orderItem").attr('id');
            var itemId = getId(parentRowId, '-');
            var currentQty = $(this).parents("td.quantity").find("input.qtyBox").val();
            // whats the new qty
            if (action == 'increase') {
                newQty = Number(currentQty) + 1;
            } else if (action == 'decrease' && currentQty > 1) {
                newQty = Number(currentQty) - 1;
            }

            // if decrease on 1, might as well delete
            if (action == 'decrease' && currentQty == 1) {
                deleteCartRow(parentRowId, '?cartCmd=Remove&id=' + itemId);
            } else {
                // disable for mad clickers
                disableCartBrief();
                // update
                cartCmd = '/?cartCmd=Update&itemId-' + itemId + '=' + newQty + '&getCart=true';
                ajaxCartCmd(cartCmd, function () {
                    updateCart();
                });

                // update box
                $(this).parents("td.quantity").find("input.qtyBox").val(newQty);
            }
        }
    });
}

function ajaxAddToCart(oCartForm) {


    var data = 'cartAdd=true&' + $(oCartForm).serialize();
    url = String(window.location);

    //scrolUp to cart
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: 0 }, 500);

    cartBriefOpenClose('open', function () {
        disableCartBrief();
    });

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function (msg) {
            updateCart(function () {
                // re-enable add to cart buttons
                $("input[name='cartAdd']").each(function () {
                    if ($(this).attr('disabled')) {
                        $(this).removeAttr('disabled');
                        $(this).removeClass('disabled');
                        $(this).val($(this).attr('title'));
                    }
                });

            });

            // set interval to hide cart after x secs.
            hideCartTimer = setInterval(function () {
                cartBriefOpenClose('close', function () {
                    // clear after one loop
                    clearInterval(hideCartTimer);
                });
            }, 7000);
        }
    });

}


// function to handle the sliding up and down of cart brief
function cartBriefOpenClose(action, callback) {

    /* decide what to do */
    if (action == 'open' | action == 'close') {
        // if act passed through
    } else {
        // decide from button class to open or close
        if ($("a#viewCart").hasClass('hideCart')) {
            action = 'close';
        } else {
            action = 'open';
        }
    }
    /* DO IT!! */
    if (action == 'open') {
        $(".cartSummary").addClass('cartSummaryOpen');
        $("#orderBrief .cartSummary .contents").css('display', 'block');
        $(".cartSummary").removeClass('empty');
        $("a#viewCart").html('Hide basket');
        $("a#viewCart").addClass('hideCart');
        $("#cartBreakdown").slideDown('slow', function () {
            // callback
            if (callback) {
                callback();
            }
        });


    } else if (action == 'close') {
        $("a#viewCart").html('View basket');
        $("a#viewCart").removeClass('hideCart');
        $("#cartBreakdown").slideUp('slow', function () {
            $(".cartSummary").removeClass('cartSummaryOpen');
            // callback
            if (callback) {
                callback();
            }
        });

    }
}

function deleteCartRow(row, cartCmd) {

    $("tr#" + row).slideUp('slow', function () {
        $(this).remove();

        if ($("#cartListingBrief tr.orderItem").length == 0) {
            ajaxCartCmd(cartCmd);
            // return cartBrief to standard state
            resetCart();
        } else {
            disableCartBrief();
            ajaxCartCmd(cartCmd, function () {
                updateCart();
            });
        }
    });


}


// sticks up loading graphic to disable anymore clicks till ready.
function disableCartBrief() {
    // stop anymore actions or mad clickers!
    var loadingHTML = '<div class="cartBriefLoading"></div>';
    var lwidth = Number($(".cartSummary").width()) - 2;
    var lheight = $(".cartSummary").height();
    $(".cartSummary").append(loadingHTML);
    $(".cartSummary .cartBriefLoading").width(lwidth);
    $(".cartSummary .cartBriefLoading").height(lheight);
}

// returns the cart to an empty state
function resetCart() {
    cartBriefOpenClose('close', function () {
        $("#orderBrief .cartSummary .contents").fadeOut('slow', function () {
            $("#orderBrief .cartSummary").addClass('empty');
            updateCartBrief('0', '0.00');
        });
    });
}

// goes and gets the complete cart back from eonicweb
function updateCart(callback) {
    var random = Math.floor(Math.random() * 10000)
    var url = '/?getCart=' + random;
    $("form#cart").load(url, function () {
        $(".cartBriefLoading").fadeOut('fast');
        // when cart returned
        if ($("#cartListingBrief").exists()) {
            // reinitialise listeners
            cartBriefActionListeners();
            // get new total and items
            var newTotal = $("#cartListingBrief .totalPrice").html();
            newTotal = newTotal.substring(1);
            newItems = getId($("#cartListingBrief").attr('class'), '-');
            updateCartBrief(newItems, newTotal);
        } else if ($("#cartBreakdown #cartError").exists()) {
            updateCartBrief('0', '0.00');
            var wait = setInterval(function () {
                clearInterval(wait);
                resetCart();
            }, 3000);
        }
        if (callback) {
            callback();
        }
    });
}

// updates the elements out side of the cartListing
function updateCartBrief(items, total) {
    $("#orderBrief .count .number").html(items);
    if (items == 1) {
        $("#orderBrief .count .text").html('item');
    } else {
        $("#orderBrief .count .text").html('items');
    }
    var currentTotal = $("#orderBrief .cartTotal").html();
    currencySymbol = currentTotal.substring(0, 1);
    $("#orderBrief .cartTotal").html(currencySymbol + total);

    // track add to cart in Analytics
    var canonicalLink = $("link[rel='canonical']").attr('href');
    var valueAdded = Math.round((Number(total.replace(/,/gi, '')) - cartTotal) * 100) / 100;
    cartTotal = total;

    // commented for ds01 or will error
    if(_gaq){
        _gaq.push(['_trackEvent', 'Ecommerce', 'AddToCart', canonicalLink, valueAdded]);
    }
    

}

/*  ==  GENERIC FUNCTIONAL FUNCTIONS  ==  */
function ajaxCartCmd(url, callback) {
    $.ajax({
        url: url,
        statusCode: {
            302: function () {
                alert('cart updated');
            },
            404: function () {
                alert('There was an error, please refresh your page and try again.');
            },
            200: function () {
                if (callback) {
                    callback();
                }
            }
        }
    });

}
function getId(str, seperator) {
    var i;
    var sId;
    i = str.indexOf(seperator);
    sId = str.substring(i + 1);
    return sId;
}




// Find a stockist listener
function dealerSearch() {

    $("#findStockist #findStockistSubmit").click(function (brap) {
        brap.preventDefault();
        var stockistPostcode = $('#findStockist #stockistPostcode').val();
        if (!stockistPostcode) {
            alert('Please enter a valid UK postcode');
        } else {
            getAndPopulateStockistLongLat(stockistPostcode, function () {
                submitDealerSearch();
            });
        }
    });
}
function getAndPopulateStockistLongLat(postcode, success) {

    var geocoder = new google.maps.Geocoder();

    // get address, and callback function
    geocoder.geocode({ 'address': postcode }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            var addLat = results[0].geometry.location.lat();
            var addLng = results[0].geometry.location.lng();

            // write coords to inputs
            $("#stockistLatitude").val(addLat);
            $("#stockistLongitude").val(addLng);

            // callback for success
            success();

        } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
            $("#stockistLatitude").val('');
            $("#stockistLongitude").val('');
            alert('Postcode not recognised. Please re-enter and try again.');
        }
    });
}




function submitDealerSearch() {
    var stockistPostcode = $('#findStockist #stockistPostcode').val();
    stockistPostcode = stockistPostcode.replace(' ', '+');
    var stockistLatitude = $('#findStockist #stockistLatitude').val();
    var stockistLongitude = $('#findStockist #stockistLongitude').val();
    var distance = $('#findStockist #stockistDistance').val();
    var sTop = $('#findStockist #stockistTop').val();
    var ewSubmitClone_findStockist = 'Find';
    var currentPageURL = getCurrentPageURL();

    var dealerSearchURL = currentPageURL + '?stockistPostcode=' + stockistPostcode + '&stockistLatitude=' + stockistLatitude + '&stockistLongitude=' + stockistLongitude + '&distance=' + distance + '&ewSubmitClone_findStockist=' + ewSubmitClone_findStockist + '&top=' + sTop;
    window.location = dealerSearchURL;
}

function getCurrentPageURL() {
    url = $("#findStockist").attr('action');
    return url;
}

function initialiseContactGeocoderButton() {
    $('.initialiseContactGeocoderButton').click(function (e) {
        // Prevent form submission
        e.preventDefault();

        // Store initial label
        var $this = $(this);
        var label = $this.val();

        // Create an array of address details
        var address = [
			$('#cContentStreet').val(),
			$('#cContentCity').val(),
			$('#cContentState').val(),
			$('#cContentPostalCode').val(),
		];

        // Turn address array into a comma separated string
        var addressString = address.join(',');

        // Change label
        $this.val('Please wait...');

        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({ address: addressString }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                // Set lat and long values in relevant inputs
                var location = results[0].geometry.location;
                $('#cContentLocationLat').val(location.lat());
                $('#cContentLocationLong').val(location.lng());

            } else {
                alert('Couldn\'t find the latitude and longitude for the address provided. Try including more details.');
            }

            // Change to initial button label
            $this.val(label);
        });
    });
}

function equalHeight(group) {
    tallest = 0;
    group.each(function () {
        thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

function equalHeightByRow() {

    var column1Modules = new Array();
    var column2Modules = new Array();
    var longestColumn;

    $("#column1 .module").each(function () {
        var productMenu = false;
        var productHeight = '';
        var menuHeight = '';
        if ($(this).find(".ProductPageMenu").exists()) {
            productMenu = true;
            productHeight = $(this).find(".productMenu").height();
            menuHeight = $(this).find(".popularCategories").height();
        } else {
            // get module height
            
            productHeight = $(this).height();
        }
        column1Modules.push({ "productMenu":productMenu,"productHeight": productHeight, "menuHeight": menuHeight });
    });
    $("#column2 .module").each(function () {
        var productMenu = false;
        var productHeight = '';
        var menuHeight = '';
        if ($(this).find(".ProductPageMenu").exists()) {
            productMenu = true;
            productHeight = $(this).find(".productMenu").height();
            menuHeight = $(this).find(".popularCategories").height();
        } else {
            // get module height 
            productHeight = $(this).height();
        }
        column2Modules.push({ "productMenu": productMenu, "productHeight": productHeight, "menuHeight": menuHeight });
    });

    longestColumn = column1Modules.length;
    if (column2Modules.length > column1Modules.length) {
        longestColumn = column2Modules.length;
    }

    for (var i = 0; i < longestColumn; i++) {
        if (column1Modules[i] && column2Modules[i]) {
            if (column1Modules[i].productMenu && column2Modules[i].productMenu) {
                var heighestP = column1Modules[i].productHeight;
                if (column2Modules[i].productHeight > heighestP) {
                    heighestP = column2Modules[i].productHeight;
                }
                adjustPHeight(i, heighestP, 'productMenu');
                var heighestM = column1Modules[i].menuHeight;
                if (column2Modules[i].menuHeight > heighestM) {
                    heighestM = column2Modules[i].menuHeight;
                }
                adjustPHeight(i, heighestM, 'popularCategories');
            }
        }
    }

 

}

function adjustPHeight(nth, height, element) {
    $("#column1 .module").eq(nth).find("." + element).height(height);
    $("#column2 .module").eq(nth).find("." + element).height(height);
}

/*  ================================================================================================  */
/*  ==  QUICK ORDER FORMS STUFF  ===================================================================  */
/*  ================================================================================================  */
function initialiseQuickOrderForm() {

    // append autocompleteList
    var autocompleteContainer = '<ul id="autocompleteContainer"><li class="loading">Loading</li></ul>';
    $(".quickOrderForm li.stockCode").append(autocompleteContainer);

    // initialise the auto complete
    // Key press - LEEETS GOOOO!
    $("#qoStockCode").keyup(function (event) {
        clearTimeout(timeout);

        // What was pressed
        var sKeyPressed = whatKey(event.keyCode);
        // What to do
        //alert(event.keyCode);
        switch (sKeyPressed) {
            case false: /*DO NOTHING*/break;
            case 'down':
                acPseudoSelect(sKeyPressed);
                break;
            case 'up':
                acPseudoSelect(sKeyPressed);
                break;
            case 'ENTER':
                // only do something on enter if highlighted
                if ($("ul#autocompleteContainer").find("a.active").exists()) {
                    // add it
                    selectProductToAdd($("ul#autocompleteContainer").find("a.active"));
                }
                else if (!$("ul#autocompleteContainer li").exists() && $(".quickOrderForm #qoProductId").val() != '') {
                    // add via click
                    additemToList();
                }
                break;
            default:
                // slide down
                if (!$("ul#autocompleteContainer").is(":visible")) {
                    $("ul#autocompleteContainer").slideDown('fast');
                }
                else {
                    $("ul#autocompleteContainer li.loading").slideDown('fast');
                }
                timeout = setTimeout("getResults(" + event.keyCode + ");", 350);
                break;
        }
    });

    // add to click listener
    $(".quickOrderForm #qoAdd").click(function (clicky) {
        clicky.preventDefault();
        additemToList();
    });


    // delete from quote listener
    deleteFromQuoteListener();
}

function getResults(pKeyCode) {
    // GET RESULTS - NOW
    var searchString = $(".quickOrderForm #qoStockCode").val();
    //alert('key:' + pKeyCode + ' string:' + searchString);
    if (searchString && searchString != ' ') {
        $.getJSON("/tools/quicksearch.ashx?q=" + searchString, function (oSearchResults) {
            var qString = $(".quickOrderForm #qoStockCode").val();
            $("ul#autocompleteContainer li.loading").slideUp('fast');

            // if results - write em.
            if (oSearchResults.ewqs.length > 0) {

                // write results to autocomplete box 
                var currentItem = '';
                var currentHTML = '';
                var wholeList = '';
                for (var i = 0; i < oSearchResults.ewqs.length; i++) {
                    currentItem = oSearchResults.ewqs[i];
                    currentHTML = buildAutoCompleteAnchor(currentItem, qString.toUpperCase());
                    wholeList = wholeList + currentHTML;
                }
                $("ul#autocompleteContainer").html(wholeList);

                // set listeners for selection
                $("ul#autocompleteContainer a").click(function (clicky) {
                    clicky.preventDefault();
                    selectProductToAdd($(this));
                });
            } else {
                // show no results
                $("ul#autocompleteContainer").html('<li class="noresults">No products found. Please check your stockcode again</li>');
            }
        });
    }
}

function buildAutoCompleteAnchor(currentItem, qString) {
    // currentItem is array[id,name,stockcode]

    var stockCode = currentItem[2];
    var reg = new RegExp(qString, 'gi');
    stockCode = stockCode.replace(reg, "<b>" + qString + "</b>");
    var thisHTML = '<li><a href="#" id="autocompleteItem-' + currentItem[0] + '" title="' + currentItem[2] + '">' + stockCode + ' - <span class="name">' + currentItem[1] + '</span></a></li>';
    return thisHTML;
}

// function, passed the anchor from the autocomplete, adds product to add line
function selectProductToAdd(acLink) {
    var productId = getId($(acLink).attr('id'), '-');
    var productName = $(acLink).find('.name').html();
    var productStockCode = $(acLink).attr('title');

    // add details to form inputs
    $(".quickOrderForm input#qoProductId").val(productId);
    $(".quickOrderForm input#qoStockCode").val(productStockCode);
    $(".quickOrderForm input#qoName").val(productName);
    $(".quickOrderForm input#qoName").attr('title', productName);

    // enable add button
    $(".quickOrderForm #qoAdd").removeAttr('disabled');
    $(".quickOrderForm #qoAdd").removeClass('disabled');

    // reset auto complete
    resetAutoComplete();
}

function acPseudoSelect(action) {
    var currentActive = '';

    if ($("ul#autocompleteContainer").children("li").exists()) {
        // down
        if (action == 'down') {
            // if an already active
            if ($("ul#autocompleteContainer").find(".active").exists()) {
                currentActive = $("ul#autocompleteContainer").find("a.active");
                if ($(currentActive).parent('li').next('li').find('a').exists()) {
                    $(currentActive).removeClass('active');
                    $(currentActive).parent('li').next('li').find('a').addClass('active');
                }
            } else {
                // else make first active
                $("ul#autocompleteContainer li:first-child a").addClass('active');
            }
        } else if (action == 'up') {
            if ($("ul#autocompleteContainer").find(".active").exists()) {
                currentActive = $("ul#autocompleteContainer").find("a.active");
                $(currentActive).removeClass('active');
                $(currentActive).parent('li').prev('li').find('a').addClass('active');
            }
        }
    }
}

// returns english for what type of key was pressed
function whatKey(pKeyCode) {
    var keyGroup;

    if (pKeyCode == 8 || pKeyCode == 46) {
        keyGroup = 'delete';
    }
    else if (pKeyCode == 38) {
        keyGroup = 'up';
    }
    else if (pKeyCode == 40) {
        keyGroup = 'down';
    }
    else if (pKeyCode == 13) {
        keyGroup = 'ENTER';
    }
    else if ((pKeyCode >= 32 && pKeyCode <= 175) || pKeyCode == 189) {
        keyGroup = 'alphanumeric';
    }
    else {
        keyGroup = false;
    }
    return keyGroup;
}



function additemToList() {

    // disable add button and stockcode
    $(".quickOrderForm #qoStockCode").attr('readonly', 'readonly');
    $(".quickOrderForm #qoStockCode").addClass('readonly');
    $(".quickOrderForm #qoQty").addClass('readonly');
    $(".quickOrderForm #qoQty").attr('readonly', 'readonly');

    $(".quickOrderForm #qoAdd").attr('disabled', 'disabled');
    $(".quickOrderForm #qoAdd").addClass('disabled');
    $(".quickOrderForm #qoAdd").addClass('loading');


    // go get productId - make sure hasn't got options.
    var productId = $("input#qoProductId").val();
    var productQty = $("input#qoQty").val();
    var ajaxURL = '/tools/quicksearch.ashx?productLookup=&id=' + productId + '&qty=' + productQty;

    $(".quickAddListing .reviewContent").load(ajaxURL, function () {
        if ($(".quickAddListing .reviewContent .selectProductOptions").exists()) {
            // make them choose
            $("p.instructions").slideUp('fast');
            $(".reviewContent").slideDown('slow');

            // listener when selected
            $(".selectProductOptions #sOptionsAdd").click(function (e) {
                e.preventDefault();
                $(this).val('Please wait...');
                addToQuote();
            });

            // undo loading button
            $(".quickOrderForm #qoAdd").removeClass('loading');
        } else {
            // add to quote
            addToQuote();



        }
    });


}

function resetQuickFindForm() {
    // sort stockcode
    $("#qoStockCode").removeAttr('readonly');
    $("#qoStockCode").removeClass('readonly');
    $("#qoStockCode").val('');
    // productIdstore
    $("#qoProductId").val('');
    // productName
    $("#qoName").val('');
    $("#qoName").removeAttr('title');
    //qty back to 1
    $("#qoQty").val('1');
    $(".quickOrderForm #qoQty").removeClass('readonly');
    $(".quickOrderForm #qoQty").removeAttr('readonly');
    // add button
    $(".quickOrderForm #qoAdd").attr('disabled', 'disabled');
    $(".quickOrderForm #qoAdd").addClass('disabled');
    $(".quickOrderForm #qoAdd").removeClass('loading');
}

function resetAutoComplete() {
    // remove items
    $(".quickOrderForm #autocompleteContainer").slideUp('fast', function () {
        $(".quickOrderForm #autocompleteContainer").html('');
    });
}
function resetQuickOrderForm() {
    destroyQuote();
    $("#quoteForm").slideUp('fast');
    $("p.instructions").slideDown('slow');
}
function updateQuote() {
    var random = Math.floor(Math.random() * 10000)
    var getQuoteUrl = '/?getQuote=' + random;


    $("#quoteForm .quoteListing").load(getQuoteUrl, function () {
        // listeners for delete
        deleteFromQuoteListener();
        // hide instructions
        $("p.instructions").slideUp('fast');
        // slide listing down
        $("#quoteForm").slideDown('slow');
        // empty review contnet
        $(".quickAddListing .reviewContent").slideUp('fast', function () { 
            $(".quickAddListing .reviewContent").html('');
        });
        
        // reset quick find form
        resetQuickFindForm();
    });

}



function addToQuote() {

    var productData = $(".quickAddListing .reviewContent").find("form").serialize();
    var quoteSubmissionData = 'quoteAdd=true&' + productData;
    url = String(window.location);

    $.ajax({
        type: "POST",
        url: url,
        data: quoteSubmissionData,
        success: function () {
            updateQuote();
        }
    });
}
function deleteFromQuoteListener() {

    $(".quickOrderTable .deleteQItem").click(function (click) {
        click.preventDefault();

        var deleteRequest = '/' + $(this).attr('href');
        // ajax delete command
        $.ajax(deleteRequest);
        // remove html
        $(this).parents("tr.orderItem").fadeOut('fast', function () {
            $(this).remove();

            // if last - reset whole form
            if (!$(".quickOrderTable tbody tr").exists()) {
                resetQuickOrderForm();
            }
        });



    });

}
function destroyQuote() {
    var url = String(window.location);
    var data = 'quoteQuit=true';
    $.ajax({
        type: "POST",
        url: url,
        data: data
    });
}





/**
* ################################
* ### Main menu initialisation ###
* ################################
*/
function initialiseMainMenu() {
	var $menu = $('#mainMenu');
	var $fullMenu = $('#fullMainMenu');

	// Get content from full menu at bottom of page
	if ($fullMenu.exists()) {
		$menu.empty().append($fullMenu.children());
		$fullMenu.remove();
	} else {
		// If there's no full menu, then we can end things now
		return;
	}

	// Variables
	var colWidth = 165;
	var colSpacing = 10;
	var itemsPerCol = 9;
	var maxCols = 5;

	$menu.find('.level-1-item').each(function () {
		$level1Item = $(this);
		$level1Link = $level1Item.find('.level-1-link');
		$level2 = $level1Item.find('.level-2');
		$level2Items = $level2.find('.level-2-item');

		// Set width of level 2
		var cols = Math.ceil($level2Items.find('.link').size() / itemsPerCol);
		if (cols > maxCols) {
			cols = maxCols;
		}
		$level2.css({ width: cols * colWidth + (cols - 1) * colSpacing });

		// Position horizontally
		var level2Width = $level2.outerWidth();
		var leftMin = -$level1Item.position().left;
		var leftMax = $menu.outerWidth() + leftMin - level2Width;
		var left = ($level1Item.outerWidth() - level2Width) / 2;
		if (left < leftMin) {
			left = leftMin;
		} else if (left > leftMax) {
			left = leftMax;
		}
		$level2.css({ left: left });

		// Position vertically
		$level2.css({ top: $level1Item.outerHeight() });

		// Create double-width columns
		$level2Items.each(function () {
			var $level2Item = $(this);
			if ($level2Item.find('.link').size() > itemsPerCol) {
				$level2Item.addClass('two-columns');
			}
		});

		// Order level 2 by size (largest first)
		
		var array = $level2Items.get();
		array.sort(function (a, b) {
			var sizeA = $(a).find('.level-3-item').size();
			var sizeB = $(b).find('.level-3-item').size();
			return sizeA < sizeB;
		});
		$.each(array, function (index, item) {
			$level2.append(item);
		});
		

		// Initialise Masonry (need to unhide container for this to work)
		$level2.show().masonry({
			itemSelector: '.level-2-item',
			columnWidth: colWidth,
			gutterWidth: colSpacing
		}).hide();

	    // Setup hover
	    var fadeDuration = 200;
	    var setDelay;
	    $level1Item.hover(function () {
	        var $item = $(this);
	        setDelay = setTimeout(function () { $item.addClass('hover').find('.level-2').fadeIn(fadeDuration) }, 300);
	        //$(this).addClass('hover').find('.level-2').fadeIn(fadeDuration);
	    }, function () {
	        clearTimeout(setDelay);
	        $(this).removeClass('hover').find('.level-2').fadeOut(fadeDuration);
	    });
	});
}

/**
* jQuery Masonry v2.0.110901
* A dynamic layout plugin for jQuery
* The flip-side of CSS Floats
* http://masonry.desandro.com
*
* Licensed under the MIT license.
* Copyright 2011 David DeSandro
*/
(function (a, b, c) { var d = b.event, e; d.special.smartresize = { setup: function () { b(this).bind("resize", d.special.smartresize.handler) }, teardown: function () { b(this).unbind("resize", d.special.smartresize.handler) }, handler: function (a, b) { var c = this, d = arguments; a.type = "smartresize", e && clearTimeout(e), e = setTimeout(function () { jQuery.event.handle.apply(c, d) }, b === "execAsap" ? 0 : 100) } }, b.fn.smartresize = function (a) { return a ? this.bind("smartresize", a) : this.trigger("smartresize", ["execAsap"]) }, b.Mason = function (a, c) { this.element = b(c), this._create(a), this._init() }; var f = ["position", "height"]; b.Mason.settings = { isResizable: !0, isAnimated: !1, animationOptions: { queue: !1, duration: 500 }, gutterWidth: 0, isRTL: !1, isFitWidth: !1 }, b.Mason.prototype = { _filterFindBricks: function (a) { var b = this.options.itemSelector; return b ? a.filter(b).add(a.find(b)) : a }, _getBricks: function (a) { var b = this._filterFindBricks(a).css({ position: "absolute" }).addClass("masonry-brick"); return b }, _create: function (c) { this.options = b.extend(!0, {}, b.Mason.settings, c), this.styleQueue = [], this.reloadItems(); var d = this.element[0].style; this.originalStyle = {}; for (var e = 0, g = f.length; e < g; e++) { var h = f[e]; this.originalStyle[h] = d[h] || "" } this.element.css({ position: "relative" }), this.horizontalDirection = this.options.isRTL ? "right" : "left", this.offset = {}; var i = b(document.createElement("div")); this.element.prepend(i), this.offset.y = Math.round(i.position().top), this.options.isRTL ? (i.css({ "float": "right", display: "inline-block" }), this.offset.x = Math.round(this.element.outerWidth() - i.position().left)) : this.offset.x = Math.round(i.position().left), i.remove(); var j = this; setTimeout(function () { j.element.addClass("masonry") }, 0), this.options.isResizable && b(a).bind("smartresize.masonry", function () { j.resize() }) }, _init: function (a) { this._getColumns("masonry"), this._reLayout(a) }, option: function (a, c) { b.isPlainObject(a) && (this.options = b.extend(!0, this.options, a)) }, layout: function (a, c) { var d, e, f, g, h, i; for (var j = 0, k = a.length; j < k; j++) { d = b(a[j]), e = Math.ceil(d.outerWidth(!0) / this.columnWidth), e = Math.min(e, this.cols); if (e === 1) this._placeBrick(d, this.colYs); else { f = this.cols + 1 - e, g = []; for (i = 0; i < f; i++) h = this.colYs.slice(i, i + e), g[i] = Math.max.apply(Math, h); this._placeBrick(d, g) } } var l = {}; l.height = Math.max.apply(Math, this.colYs) - this.offset.y, this.options.isFitWidth && (l.width = this.cols * this.columnWidth - this.options.gutterWidth), this.styleQueue.push({ $el: this.element, style: l }); var m = this.isLaidOut ? this.options.isAnimated ? "animate" : "css" : "css", n = this.options.animationOptions, o; for (j = 0, k = this.styleQueue.length; j < k; j++) o = this.styleQueue[j], o.$el[m](o.style, n); this.styleQueue = [], c && c.call(a), this.isLaidOut = !0 }, _getColumns: function () { var a = this.options.isFitWidth ? this.element.parent() : this.element, b = a.width(); this.columnWidth = this.options.columnWidth || this.$bricks.outerWidth(!0) || b, this.columnWidth += this.options.gutterWidth, this.cols = Math.floor((b + this.options.gutterWidth) / this.columnWidth), this.cols = Math.max(this.cols, 1) }, _placeBrick: function (a, b) { var c = Math.min.apply(Math, b), d = 0; for (var e = 0, f = b.length; e < f; e++) if (b[e] === c) { d = e; break } var g = { top: c }; g[this.horizontalDirection] = this.columnWidth * d + this.offset.x, this.styleQueue.push({ $el: a, style: g }); var h = c + a.outerHeight(!0), i = this.cols + 1 - f; for (e = 0; e < i; e++) this.colYs[d + e] = h }, resize: function () { var a = this.cols; this._getColumns("masonry"), this.cols !== a && this._reLayout() }, _reLayout: function (a) { var b = this.cols; this.colYs = []; while (b--) this.colYs.push(this.offset.y); this.layout(this.$bricks, a) }, reloadItems: function () { this.$bricks = this._getBricks(this.element.children()) }, reload: function (a) { this.reloadItems(), this._init(a) }, appended: function (a, b, c) { if (b) { this._filterFindBricks(a).css({ top: this.element.height() }); var d = this; setTimeout(function () { d._appended(a, c) }, 1) } else this._appended(a, c) }, _appended: function (a, b) { var c = this._getBricks(a); this.$bricks = this.$bricks.add(c), this.layout(c, b) }, remove: function (a) { this.$bricks = this.$bricks.not(a), a.remove() }, destroy: function () { this.$bricks.removeClass("masonry-brick").each(function () { this.style.position = "", this.style.top = "", this.style.left = "" }); var c = this.element[0].style; for (var d = 0, e = f.length; d < e; d++) { var g = f[d]; c[g] = this.originalStyle[g] } this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"), b(a).unbind(".masonry") } }, b.fn.imagesLoaded = function (a) { function h() { --e <= 0 && this.src !== f && (setTimeout(g), d.unbind("load error", h)) } function g() { a.call(b, d) } var b = this, d = b.find("img").add(b.filter("img")), e = d.length, f = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; e || g(), d.bind("load error", h).each(function () { if (this.complete || this.complete === c) { var a = this.src; this.src = f, this.src = a } }); return b }; var g = function (a) { this.console && console.error(a) }; b.fn.masonry = function (a) { if (typeof a == "string") { var c = Array.prototype.slice.call(arguments, 1); this.each(function () { var d = b.data(this, "masonry"); if (!d) g("cannot call methods on masonry prior to initialization; attempted to call method '" + a + "'"); else { if (!b.isFunction(d[a]) || a.charAt(0) === "_") { g("no such method '" + a + "' for masonry instance"); return } d[a].apply(d, c) } }) } else this.each(function () { var c = b.data(this, "masonry"); c ? (c.option(a || {}), c._init()) : b.data(this, "masonry", new b.Mason(a, this)) }); return this } })(window, jQuery);

/**
* #######################################
* ### End of main menu initialisation ###
* #######################################
*/





/*  =======================================================================================  */
/*  ==  END QUICK ORDER FORMS STUFF  ======================================================  */
/*  =======================================================================================  */

/*
* jQuery Orbit Plugin 1.2.3
* www.ZURB.com/playground
* Copyright 2010, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/


(function ($) {

    $.fn.orbit = function (options) {

        //Defaults to extend options
        var defaults = {
            animation: 'horizontal-push', 		// fade, horizontal-slide, vertical-slide, horizontal-push
            animationSpeed: 600, 				// how fast animtions are
            timer: true, 						// true or false to have the timer
            advanceSpeed: 4000, 				// if timer is enabled, time between transitions 
            pauseOnHover: false, 				// if you hover pauses the slider
            startClockOnMouseOut: false, 		// if clock should start on MouseOut
            startClockOnMouseOutAfter: 1000, 	// how long after MouseOut should the timer start again
            directionalNav: true, 				// manual advancing directional navs
            captions: true, 					// do you want captions?
            captionAnimation: 'fade', 			// fade, slideOpen, none
            captionAnimationSpeed: 600, 		// if so how quickly should they animate in
            bullets: false, 					// true or false to activate the bullet navigation
            bulletThumbs: false, 			// thumbnails for the bullets
            bulletThumbLocation: '', 		// location from this file where thumbs will be
            afterSlideChange: function () { } 		// empty function 
        };

        //Extend those options
        var options = $.extend(defaults, options);

        return this.each(function () {

            // ==============
            // ! SETUP   
            // ==============

            //Global Variables
            var activeSlide = 0,
            	numberSlides = 0,
            	orbitWidth,
            	orbitHeight,
            	locked;

            //Initialize
            var orbit = $(this).addClass('orbit'),
            	orbitWrapper = orbit.wrap('<div class="orbit-wrapper" />').parent();
            orbit.add(orbitWidth).width('1px').height('1px');

            //Collect all slides and set slider size of largest image
            var slides = orbit.children('img, a, div');
            slides.each(function () {
                var _slide = $(this),
                	_slideWidth = _slide.width(),
                	_slideHeight = _slide.height();
                if (_slideWidth > orbit.width()) {
                    orbit.add(orbitWrapper).width(_slideWidth);
                    orbitWidth = orbit.width();
                }
                if (_slideHeight > orbit.height()) {
                    orbit.add(orbitWrapper).height(_slideHeight);
                    orbitHeight = orbit.height();
                }
                numberSlides++;
            });

            //Animation locking functions
            function unlock() {
                locked = false;
            }
            function lock() {
                locked = true;
            }

            //If there is only a single slide remove nav, timer and bullets
            if (slides.length == 1) {
                options.directionalNav = false;
                options.timer = false;
                options.bullets = false;
            }

            //Set initial front photo z-index and fades it in
            slides.eq(activeSlide)
            	.css({ "z-index": 3 })
            	.fadeIn(function () {
            	    //brings in all other slides IF css declares a display: none
            	    slides.css({ "display": "block" })
            	});

            // ==============
            // ! TIMER   
            // ==============

            //Timer Execution
            function startClock() {
                if (!options.timer || options.timer == 'false') {
                    return false;
                    //if timer is hidden, don't need to do crazy calculations
                } else if (timer.is(':hidden')) {
                    clock = setInterval(function (e) {
                        shift("next");
                    }, options.advanceSpeed);
                    //if timer is visible and working, let's do some math
                } else {
                    timerRunning = true;
                    pause.removeClass('active')
                    clock = setInterval(function (e) {
                        var degreeCSS = "rotate(" + degrees + "deg)"
                        degrees += 2
                        rotator.css({
                            "-webkit-transform": degreeCSS,
                            "-moz-transform": degreeCSS,
                            "-o-transform": degreeCSS
                        });
                        if (degrees > 180) {
                            rotator.addClass('move');
                            mask.addClass('move');
                        }
                        if (degrees > 360) {
                            rotator.removeClass('move');
                            mask.removeClass('move');
                            degrees = 0;
                            shift("next");
                        }
                    }, options.advanceSpeed / 180);
                }
            }
            function stopClock() {
                if (!options.timer || options.timer == 'false') { return false; } else {
                    timerRunning = false;
                    clearInterval(clock);
                    pause.addClass('active');
                }
            }

            //Timer Setup
            if (options.timer) {
                var timerHTML = '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>'
                orbitWrapper.append(timerHTML);
                var timer = orbitWrapper.children('div.timer'),
                	timerRunning;
                if (timer.length != 0) {
                    var rotator = $('div.timer span.rotator'),
                    	mask = $('div.timer span.mask'),
                    	pause = $('div.timer span.pause'),
                    	degrees = 0,
                    	clock;
                    startClock();
                    timer.click(function () {
                        if (!timerRunning) {
                            startClock();
                        } else {
                            stopClock();
                        }
                    });
                    if (options.startClockOnMouseOut) {
                        var outTimer;
                        orbitWrapper.mouseleave(function () {
                            outTimer = setTimeout(function () {
                                if (!timerRunning) {
                                    startClock();
                                }
                            }, options.startClockOnMouseOutAfter)
                        })
                        orbitWrapper.mouseenter(function () {
                            clearTimeout(outTimer);
                        })
                    }
                }
            }

            //Pause Timer on hover
            if (options.pauseOnHover) {
                orbitWrapper.mouseenter(function () {
                    stopClock();
                });
            }

            // ==============
            // ! CAPTIONS   
            // ==============

            //Caption Setup
            if (options.captions) {
                var captionHTML = '<div class="orbit-caption"></div>';
                orbitWrapper.append(captionHTML);
                var caption = orbitWrapper.children('.orbit-caption');
                setCaption();
            }

            //Caption Execution
            function setCaption() {
                if (!options.captions || options.captions == "false") {
                    return false;
                } else {
                    var _captionLocation = slides.eq(activeSlide).data('caption'); //get ID from rel tag on image
                    _captionHTML = $(_captionLocation).html(); //get HTML from the matching HTML entity            		
                    //Set HTML for the caption if it exists
                    if (_captionHTML) {
                        caption
		            		.attr('id', _captionLocation) // Add ID caption
		                	.html(_captionHTML); // Change HTML in Caption 
                        //Animations for Caption entrances
                        if (options.captionAnimation == 'none') {
                            caption.show();
                        }
                        if (options.captionAnimation == 'fade') {
                            caption.fadeIn(options.captionAnimationSpeed);
                        }
                        if (options.captionAnimation == 'slideOpen') {
                            caption.slideDown(options.captionAnimationSpeed);
                        }
                    } else {
                        //Animations for Caption exits
                        if (options.captionAnimation == 'none') {
                            caption.hide();
                        }
                        if (options.captionAnimation == 'fade') {
                            caption.fadeOut(options.captionAnimationSpeed);
                        }
                        if (options.captionAnimation == 'slideOpen') {
                            caption.slideUp(options.captionAnimationSpeed);
                        }
                    }
                }
            }

            // ==================
            // ! DIRECTIONAL NAV   
            // ==================

            //DirectionalNav { rightButton --> shift("next"), leftButton --> shift("prev");
            if (options.directionalNav) {
                if (options.directionalNav == "false") { return false; }
                var directionalNavHTML = '<div class="slider-nav"><span class="right">Right</span><span class="left">Left</span></div>';
                orbitWrapper.append(directionalNavHTML);
                var leftBtn = orbitWrapper.children('div.slider-nav').children('span.left'),
                	rightBtn = orbitWrapper.children('div.slider-nav').children('span.right');
                leftBtn.click(function () {
                    stopClock();
                    shift("prev");
                });
                rightBtn.click(function () {
                    stopClock();
                    shift("next")
                });
            }

            // ==================
            // ! BULLET NAV   
            // ==================

            //Bullet Nav Setup
            if (options.bullets) {
                var bulletHTML = '<ul class="orbit-bullets"></ul>';
                orbitWrapper.append(bulletHTML);
                var bullets = orbitWrapper.children('ul.orbit-bullets');
                for (i = 0; i < numberSlides; i++) {
                    var liMarkup = $('<li>' + (i + 1) + '</li>');
                    if (options.bulletThumbs) {
                        var thumbName = slides.eq(i).data('thumb');
                        if (thumbName) {

                            var liMarkup = $('<li class="has-thumb">' + i + '</li>');
                            if (i == (numberSlides - 1)) {
                                liMarkup = $('<li class="has-thumb last">' + i + '</li>');
                            }
                            if (i == 0) {
                                liMarkup = $('<li class="has-thumb first">' + i + '</li>');
                            }
                            liMarkup.css({ "background": "url(" + options.bulletThumbLocation + thumbName + ") no-repeat" });
                        }
                    }
                    orbitWrapper.children('ul.orbit-bullets').append(liMarkup);
                    liMarkup.data('index', i);
                    liMarkup.click(function () {
                        stopClock();
                        shift($(this).data('index'));
                    });
                }
                setActiveBullet();
            }

            //Bullet Nav Execution
            function setActiveBullet() {
                if (!options.bullets) { return false; } else {
                    bullets.children('li').removeClass('active').eq(activeSlide).addClass('active');
                }
            }

            // ====================
            // ! SHIFT ANIMATIONS   
            // ====================

            //Animating the shift!
            function shift(direction) {
                //remember previous activeSlide
                var prevActiveSlide = activeSlide,
                	slideDirection = direction;
                //exit function if bullet clicked is same as the current image
                if (prevActiveSlide == slideDirection) { return false; }
                //reset Z & Unlock
                function resetAndUnlock() {
                    slides
                    	.eq(prevActiveSlide)
                    	.css({ "z-index": 1 });
                    unlock();
                    options.afterSlideChange.call(this);
                }
                if (slides.length == "1") { return false; }
                if (!locked) {
                    lock();
                    //deduce the proper activeImage
                    if (direction == "next") {
                        activeSlide++
                        if (activeSlide == numberSlides) {
                            activeSlide = 0;
                        }
                    } else if (direction == "prev") {
                        activeSlide--
                        if (activeSlide < 0) {
                            activeSlide = numberSlides - 1;
                        }
                    } else {
                        activeSlide = direction;
                        if (prevActiveSlide < activeSlide) {
                            slideDirection = "next";
                        } else if (prevActiveSlide > activeSlide) {
                            slideDirection = "prev"
                        }
                    }
                    //set to correct bullet
                    setActiveBullet();

                    //set previous slide z-index to one below what new activeSlide will be
                    slides
                    	.eq(prevActiveSlide)
                    	.css({ "z-index": 2 });

                    //fade
                    if (options.animation == "fade") {
                        slides
                        	.eq(activeSlide)
                        	.css({ "opacity": 0, "z-index": 3 })
                        	.animate({ "opacity": 1 }, options.animationSpeed, resetAndUnlock);
                    }
                    //horizontal-slide
                    if (options.animation == "horizontal-slide") {
                        if (slideDirection == "next") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "left": orbitWidth, "z-index": 3 })
                            	.animate({ "left": 0 }, options.animationSpeed, resetAndUnlock);
                        }
                        if (slideDirection == "prev") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "left": -orbitWidth, "z-index": 3 })
                            	.animate({ "left": 0 }, options.animationSpeed, resetAndUnlock);
                        }
                    }
                    //vertical-slide
                    if (options.animation == "vertical-slide") {
                        if (slideDirection == "prev") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "top": orbitHeight, "z-index": 3 })
                            	.animate({ "top": 0 }, options.animationSpeed, resetAndUnlock);
                        }
                        if (slideDirection == "next") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "top": -orbitHeight, "z-index": 3 })
                            	.animate({ "top": 0 }, options.animationSpeed, resetAndUnlock);
                        }
                    }
                    //push-over
                    if (options.animation == "horizontal-push") {
                        if (slideDirection == "next") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "left": orbitWidth, "z-index": 3 })
                            	.animate({ "left": 0 }, options.animationSpeed, resetAndUnlock);
                            slides
                            	.eq(prevActiveSlide)
                            	.animate({ "left": -orbitWidth }, options.animationSpeed);
                        }
                        if (slideDirection == "prev") {
                            slides
                            	.eq(activeSlide)
                            	.css({ "left": -orbitWidth, "z-index": 3 })
                            	.animate({ "left": 0 }, options.animationSpeed, resetAndUnlock);
                            slides
                            	.eq(prevActiveSlide)
                            	.animate({ "left": orbitWidth }, options.animationSpeed);
                        }
                    }
                    setCaption();
                } //lock
            } //orbit function
        }); //each call
    } //orbit plugin call
})(jQuery);


