﻿/*global window: false, document: false, setTimeout: false, clearTimeout: false, jQuery: false */
(function ($) {
    "use strict";

    // focus on first element with class focus
    $(document).ready(function () {
        $(".focus:first").focus();
    });

    // enable the main menu drop downs
    $(document).ready(function () {
        $("#nav li").mouseover(function () {
            $(this).addClass("over");
        });
        $("#nav li").mouseout(function () {
            $(this).removeClass("over");
        });
    });

    // enable the side bar to collapse and expand
    $(document).ready(function () {
        $("#accordion h3").click(function () {
            $(this).next().toggle("medium");
            return false;
        });
    });

    // enable date picker for all elements with the date class
    $(document).ready(function () {
        $('.date').datepicker({ dateFormat: "mm/dd/yy", showButtonPanel: true });
    });


    // apply jquery ui to buttons
    $(document).ready(function () {
        $("button, input:submit", "div.main").button();
        $("a.button").button();
        $(".view-cart-button").button({ icons: { primary: 'ui-icon-cart', secondary: null} });
    });

    // make all the list items in each list the same height
    $(document).ready(function () {
        $(".result-listing ul").each(function () {
            var maxHeight = 0;
            $("a", this).each(function () {
                if ($(this).height() > maxHeight) {
                    maxHeight = $(this).height();
                }
            });
            $("a", this).each(function () {
                var changeInHeight = maxHeight - $(this).height();
                $(this).height(maxHeight);
                $("span.add-quantity", this).css({ "margin-top": changeInHeight + 4 });
            });
        });
        $(".result-listing ul span.add-quantity input").click(function (event) {
            event.preventDefault();
        });
    });

    // slideshow
    $(document).ready(function () {
        function getData(element, key, defaultValue) {
            var data = $(element).data(key);
            return undefined === data ? defaultValue : data;
        }
        function showSlideshowImage(image, slideshow, options) {
            var videoId = null;
            slideshow.children(options.tagName + ":visible").hide();
            image.show(options.showDuration);
            videoId = image.attr("data-video");
            if (typeof (videoId) === "string" && videoId.length > 0) {
                $('img', options.videoThumbnail).attr("src", window.location.protocol + "//i.ytimg.com/vi/" + videoId + "/default.jpg");
                options.videoThumbnail.show();
            } else if (null !== options.videoThumbnail) {
                options.videoThumbnail.hide();
            }
            slideshow.children(".ss-controls").children("a.ssc-selected").removeClass("ssc-selected");
            slideshow.children(".ss-controls").children("a.ssc-numbered").eq(image.index()).addClass("ssc-selected");
        }
        function setSlideshowTimer(slideshow, options, delay) {
            options.timer = setTimeout(function () {
                var next = null,
                    hiddenImages = null;
                if (options.random) {
                    hiddenImages = slideshow.children(options.tagName + ":hidden");
                    next = hiddenImages.eq(Math.floor(Math.random() * hiddenImages.length));
                } else {
                    next = slideshow.children(options.tagName + ":visible").next(options.tagName);
                    if (next.length === 0) {
                        next = slideshow.children(options.tagName + ":first");
                    }
                }
                showSlideshowImage(next, slideshow, options);
                setSlideshowTimer(slideshow, options);
            }, (undefined === delay ? options.delay : delay));
        }
        $(".slideshow").each(function () {
            var slideshow = $(this),
                options = {},
                controls = null,
                video = null,
                i = 0;
            options.delay = getData(slideshow, "ss-delay", 8000);
            options.random = getData(slideshow, "ss-random", false);
            options.tagName = getData(slideshow, "ss-tag-name", "a");
            options.showDuration = getData(slideshow, "ss-duration", 1000);
            options.playPauseControl = getData(slideshow, "ss-play-pause-control", true);
            options.numberedControls = getData(slideshow, "ss-numbered-controls", true);
            options.prevNextControls = getData(slideshow, "ss-prev-next-controls", false);
            options.bottom = getData(slideshow, "ss-bottom", 15);
            options.right = getData(slideshow, "ss-right", 15);
            options.top = getData(slideshow, "ss-top", NaN);
            options.left = getData(slideshow, "ss-left", NaN);
            options.autoPlay = getData(slideshow, "ss-auto-play", true);
            options.videoThumbnail = null;
            options.videoDialog = null;

            if (slideshow.children(options.tagName + "[data-video]").length > 0) {
                video = $('<div class="video"></div>').appendTo(slideshow);

                // create the video player dialog
                options.videoDialog = $('<div title="Video" class="hidden"><iframe class="youtube-player" width="568" height="344" src="' + $().dv('url', 'blank') + '"></iframe></div>')
                        .appendTo(video)
                        .dialog({
                            autoOpen: false,
                            minWidth: 600,
                            resizable: false,
                            close: function (event, ui) {
                                options.videoDialog.children("iframe").attr("src", $().dv('url', 'blank'));
                            },
                            open: function (event, ui) {
                                options.videoDialog.dialog("option", "title", "Video: " + slideshow.children(options.tagName + ":visible").attr("data-video-title"));
                                options.videoDialog.children("iframe").attr("src", window.location.protocol + "//www.youtube.com/embed/" + slideshow.children(options.tagName + ":visible").attr("data-video") + "?rel=0&autoplay=1&showsearch=0&fs=1&wmode=opaque");
                            }
                        });

                // create the video player thumbnail
                options.videoThumbnail = $('<a href="#" class="hidden"><img src="" alt="Click here to play the video." /><span class="ui-icon ui-icon-play"></span></a>')
                        .appendTo(video)
                        .click(function () {
                            if (options.videoDialog.dialog("isOpen")) {
                                options.videoDialog.dialog("close");
                                options.videoDialog.dialog("option", "position", "center");
                            }
                            options.videoDialog.dialog("open");
                            return false;
                        });
                $("span", options.videoThumbnail).button();
                showSlideshowImage(slideshow.children(options.tagName + ":first"), slideshow, options);
            }

            if (slideshow.children(options.tagName).length < 2) {
                return;
            }

            if (options.playPauseControl || options.numberedControls || options.prevNextControls) {
                // create the controls
                controls = $('<div class="ss-controls"></div>');
                slideshow.append(controls);
                if (!isNaN(options.bottom)) {
                    controls.css("bottom", options.bottom);
                }
                if (!isNaN(options.right)) {
                    controls.css("right", options.right);
                }
                if (!isNaN(options.top)) {
                    controls.css("top", options.top);
                }
                if (!isNaN(options.left)) {
                    controls.css("left", options.left);
                }
                if (options.playPauseControl) {
                    controls.append('<a href="#" class="ssc-play-pause ssc-pause"></a>');
                }
                if (options.prevNextControls) {
                    controls.append('<a href="#" class="ssc-prev">&lt;</a>');
                }
                if (options.numberedControls) {
                    for (i = 0; i < slideshow.children(options.tagName).length; i += 1) {
                        controls.append('<a href="#" class="ssc-numbered' + (i === 0 ? ' ssc-selected' : '') + '">' + (i + 1).toString() + '</a>');
                    }
                }
                if (options.prevNextControls) {
                    controls.append('<a href="#" class="ssc-next">&gt;</a>');
                }

                // wire up the click handlers
                controls.children("a.ssc-play-pause").click(function () {
                    clearTimeout(options.timer);
                    if ($(this).hasClass("ssc-play")) {
                        setSlideshowTimer(slideshow, options, 0);
                    }
                    $(this).toggleClass("ssc-play ssc-pause");
                    return false;
                });
                controls.children("a.ssc-prev").click(function () {
                    var prev = slideshow.children(options.tagName + ":visible").prev(options.tagName);
                    if (prev.length === 0) {
                        prev = slideshow.children(options.tagName + ":last");
                    }
                    showSlideshowImage(prev, slideshow, options);
                    return false;
                });
                controls.children("a.ssc-numbered").click(function () {
                    showSlideshowImage(slideshow.children(options.tagName).eq($(this).text() - 1), slideshow, options);
                    return false;
                });
                controls.children("a.ssc-next").click(function () {
                    var next = slideshow.children(options.tagName + ":visible").next(options.tagName);
                    if (next.length === 0) {
                        next = slideshow.children(options.tagName + ":first");
                    }
                    showSlideshowImage(next, slideshow, options);
                    return false;
                });
            }
            if (options.autoPlay) {
                setSlideshowTimer(slideshow, options);
            }
        });
    });

    // add to order form buttons
    $(document).ready(function () {
        $('button.add-to-order-form').live('click', function (event) {
            var $button = $(this),
                $selectOrderFormDialog = null,
                $message = null,
                $form = null,
                $selectList = null,
                $newFormNameLine = null,
                $newFormName = null,
                productNumberValue = null,
                quantityValue = null;

            event.preventDefault();

            // get the product number and quantity from the inputs elements specified by the id attributes
            productNumberValue = $('#' + $button.attr('data-product-number-id')).val();
            quantityValue = $('#' + $button.attr('data-quantity-id')).val();
            if ('' !== quantityValue) {
                quantityValue = parseInt(quantityValue, 10);
                if (isNaN(quantityValue)) {
                    quantityValue = '';
                }
            }

            // get the list of existing editable order forms
            $.get($(document).dv('url', 'get-editable-order-forms')).success(function (orderForms) {
                if ($(document).dv('check-ajax-result', orderForms)) return;
                // create a form with a select list and a text box for creating a new list
                $form = $('<form action="#" method="get"></form>').submit(function (event) {
                    event.preventDefault();
                });
                $form.validate({
                    errorClass: "field-validation-error",
                    errorElement: "p",
                    ignore: ":hidden"
                });
                $message = $('<p style="margin-bottom: 5px;"></p>').append('<span class="editor-label">Select an order form:</span>').appendTo($form);
                $selectList = $('<select />').appendTo($('<p style="margin-bottom: 5px;"></p>').appendTo($form));
                $.each(orderForms, function (i) {
                    $('<option />', { 'value': orderForms[i].Id, 'text': orderForms[i].Name }).appendTo($selectList);
                });
                $('<option value="0">Create new order form</option>').appendTo($selectList);
                $newFormName = $('<input name="newFormName" />');
                $newFormNameLine = $('<p />')
                    .append('<span class="editor-label">Name: </span>')
                    .append($newFormName)
                    .appendTo($form).hide();
                $newFormName.rules('add', { required: true, rangelength: [1, 100] });
                $newFormName.keydown(function (event) {
                    if (event.which === 13) {
                        event.preventDefault();
                        $selectOrderFormDialog.dialog('option', 'buttons')['Add to order form']();
                    }
                });
                if (orderForms.length > 0) {
                    $selectList.change(function () {
                        $newFormNameLine.toggle('0' === $selectList.val());
                        $newFormName.focus();
                    });
                } else {
                    $newFormNameLine.show();
                }

                // create the dialog that will display the form
                $selectOrderFormDialog = $('<div />', { 'title': 'Select Order Form' }).append($form).dialog({
                    autoOpen: true,
                    modal: false,
                    minWidth: 365,
                    resizable: true,
                    closeOnEscape: true,
                    buttons: {
                        'Close': function () {
                            $selectOrderFormDialog.dialog('close');
                        },
                        'Add to order form': function () {
                            var id = $selectList.val(),
                                newFormNameValue = null;

                            function addProduct() {
                                // add the product to the order form
                                $(document).dv('modify-form-products', id, [{ ProductNumber: productNumberValue, Quantity: quantityValue}], function (result) {
                                    if (result === false) {
                                        $selectOrderFormDialog.dialog('close');
                                        $(document).dv('system-error', 'add the product to your order form');
                                        return;
                                    } else {
                                        $form.replaceWith('<p>The product was added to your order form.</p>');
                                        $selectOrderFormDialog.dialog('option', 'title', 'Product Added');
                                        $selectOrderFormDialog.dialog('option', 'buttons', {
                                            'Close': $selectOrderFormDialog.dialog('option', 'buttons').Close,
                                            'View Order Form': function () {
                                                window.location.href = $(document).dv('url', 'order-forms') + '/' + id;
                                            }
                                        });
                                        $selectList.remove();
                                    }
                                });
                            }

                            if ('0' === id) {
                                // create a new order form
                                if (!$form.valid()) {
                                    return;
                                }
                                newFormNameValue = $newFormName.val();
                                $(document).dv('modify-form', 0, newFormNameValue, function (data) {
                                    if (data === false) {
                                        $selectOrderFormDialog.dialog('close');
                                        $(document).dv('system-error', 'create the new order form');
                                        return;
                                    } else {
                                        id = data.Id;
                                        // add the product to the new order form
                                        addProduct();
                                    }
                                });
                            } else {
                                // add the product to an existing order form
                                addProduct();
                            }
                        }
                    },
                    close: function () {
                        $selectOrderFormDialog.dialog('destroy');
                        $selectOrderFormDialog.remove();
                    }
                });
            }).error(function () {
                $(document).dv('system-error', 'add the product to an order form');
            });
        });
    });

    // The dv jQuery plugin
    var methods = {
        'url': function (urlKey) {
            return $("#dv-urls").attr("data-" + urlKey);
        },
        'check-ajax-result': function (data) {
            if (typeof (data.redirect) === "string") {
                window.location.href = data.redirect + "?ReturnUrl=" + encodeURIComponent($(document).dv('url', 'current'));
                return true;
            }
            return false;
        },
        'get-content': function (contentId, alwaysShowContent) {
            var $mainThis = this;
            $.get($(document).dv('url', 'get-content'), { contentId: contentId, alwaysShowContent: alwaysShowContent })
                .success(function (data) {
                    if ($(document).dv('check-ajax-result', data)) return;
                    $mainThis.each(function () {
                        $(this).empty().append(data);
                    });
                });
            return $mainThis;
        },
        'please-wait': function (options) {
            var $pleaseWaitDialog = $("#please-wait-dialog"),
                progressIndicatorImageUrl = $(document).dv('url', 'please-wait-image'),
                settings = {
                    close: null,
                    autoOpen: false
                };
            if (typeof (options) === 'object') {
                $.extend(settings, options);
            } else if ('open' === options) {
                settings.autoOpen = true;
            }
            if ($pleaseWaitDialog.length === 0) {
                // preload the progress indicator image
                $('<img />', { src: progressIndicatorImageUrl });

                $pleaseWaitDialog = $('<div />', { id: 'please-wait-dialog', title: 'Processing' })
                    .appendTo($("body"))
                    .append($('<p />').append('<span />', { "class": 'ui-icon ui-icon-alert' }).append('Please wait while we process your request.'))
                    .dialog({
                        autoOpen: settings.autoOpen,
                        modal: true,
                        minWidth: 365,
                        resizable: false,
                        closeOnEscape: false,
                        open: function () {
                            $(".ui-dialog-titlebar-close", $pleaseWaitDialog.prev()).hide();
                            $pleaseWaitDialog.prev().css({
                                "background-image": 'url(' + progressIndicatorImageUrl + ')',
                                "background-repeat": "no-repeat",
                                "background-position": "right center"
                            });
                        },
                        close: settings.close
                    });
            } else if (settings.autoOpen) {
                $pleaseWaitDialog.dialog('open');
            } else {
                $pleaseWaitDialog.dialog('close');
            }
        },
        'system-error': function (errorMessage) {
            var $errorDialog = $('<div />', { title: 'Sorry, we are having problems with our system.' });
            $('<p />').appendTo($errorDialog).append($('<span />', { "class": 'ui-icon ui-icon-alert' })).append('We could not ' + errorMessage + ' at this time. Please try again later.');
            $errorDialog.dialog({
                modal: true,
                minWidth: 365,
                buttons: {
                    Close: function () {
                        $errorDialog.dialog('close');
                    }
                },
                close: function () {
                    $errorDialog.dialog('destroy');
                }
            });
        },
        'scroll-to-top': function ($dialog) {
            var $mainThis = this;
            return $mainThis.each(function () {
                var $eachThis = $(this);
                $(document).scrollTop($eachThis.position().top - $eachThis.height() - 5);
                $dialog.dialog("widget").position({ of: $eachThis, my: "center top", at: "center bottom", offset: "0 2" });
            });
        },
        'modify-form': function (id, name, callback) {
            $.post($(document).dv('url', 'modify-form'), { id: id, name: name })
                .success(function (form) {
                    if ($(document).dv('check-ajax-result', form)) return;
                    callback(form);
                })
                .error(function () {
                    callback(false);
                });
        },
        'modify-form-products': function (id, products, callback) {
            var data = { id: id },
                i = 0;
            for (i = 0; i < products.length; i += 1) {
                data['products[' + i.toString() + '].ProductNumber'] = products[i].ProductNumber;
                data['products[' + i.toString() + '].Quantity'] = products[i].Quantity;
            }
            $.post($(document).dv('url', 'modify-form-products'), data)
                .success(function (products) {
                    if ($(document).dv('check-ajax-result', products)) return;
                    callback(products);
                })
                .error(function () {
                    callback(false);
                });
        },
        'product-lookup': function (options) {
            var $mainThis = this,
                settings = {
                    'use-dialog': true,
                    'dialog-title': 'Product Lookup',
                    'open-dialog-button-text': 'Add Product',
                    'ok-button-text': 'Add Product',
                    'alt-ok-button-text': 'Update Product',
                    'collect-quantity': true,
                    'quantity-rules': { required: true, range: [1, 99999999] },
                    'help-content-id': null,
                    'product-selected': null,
                    'auto-complete-url': $(document).dv('url', 'product-lookup-autocomplete'),
                    'get-existing-quantity': false,
                    'show-existing-quantity': false,
                    'existing-quantity-label': 'existing',
                    'toggle-autocomplete': false,
                    'autocomplete-initially': true
                };
            return $mainThis.each(function () {
                if (options) {
                    $.extend(settings, options);
                }

                // create error messages, product number and description fields, and initialize other variables
                var $eachThis = $(this),
                    $notFoundMessage = $('<p class="ui-state-highlight ui-corner-all hidden"><span class="ui-icon ui-icon-info"></span>No products match what you entered.</p>').appendTo($eachThis).hide(),
                    $errorMessage = $('<p class="ui-state-error ui-corner-all hidden"><span class="ui-icon ui-icon-alert"></span>Sorry, we are having problems with our system. We could not search for products at this time. Please try again later.</p>').appendTo($eachThis).hide(),
                    $productNumberLine = $('<p><span class="editor-label">Product number</span> </p>').appendTo($eachThis),
                    $productNumberField = $('<input type="text" pattern="[0-9]*" style="width:100px;" />').appendTo($productNumberLine),
                    $descriptionLine = $('<p><span class="editor-label">Product description</span> </p>').appendTo($eachThis),
                    $descriptionField = $('<input type="text" style="width:370px;" />').appendTo($descriptionLine),
                    $lastLookupField = $productNumberField,
                    $quantityForm = null,
                    $quantityFormValidator = null,
                    $quantityLine = null,
                    $quantityField = null,
                    $existingQuantityLabel = null,
                    helpContentId = null,
                    $helpContent = null,
                    $autoCompleteButton = null,
                    isAutocompleteOn = settings['autocomplete-initially'],
                    dialogButtons = {},
                    $okButton = null;

                // create optional quantity field
                if (settings['collect-quantity']) {
                    $quantityForm = $('<form action="#" method="get" novalidate="novalidate"></form>').appendTo($eachThis);
                    $quantityFormValidator = $quantityForm.validate({
                        errorClass: "field-validation-error",
                        errorElement: "div",
                        ignore: ":hidden"
                    });
                    $quantityLine = $('<p><span class="editor-label">Quantity</span> </p>').appendTo($quantityForm);
                    $quantityField = $('<input type="text" pattern="[0-9]*" name="q" style="width: 50px" />').appendTo($quantityLine)
                        .keydown(function (event) {
                            if (event.which === 13 || event.which === 9) {
                                // click the ok button when the enter or tab key is pressed down
                                event.preventDefault();
                                if (!$okButton.button("option", "disabled")) {
                                    $okButton.click();
                                }
                            } else if (event.which === 8 && $(this).val().length === 0) {
                                // move back to the last lookup field when the backspace key is pressed down
                                event.preventDefault();
                                $lastLookupField.focus();
                            }
                        });
                    $quantityField.rules('add', settings['quantity-rules']);
                    $quantityLine.append(' ');
                    $existingQuantityLabel = $('<span></span>').appendTo($quantityLine);
                } else {
                    $existingQuantityLabel = $('<p></p>').appendTo($mainThis);
                }

                // create help content
                helpContentId = settings['help-content-id'];
                if (helpContentId !== null) {
                    $helpContent = $('<div class="space-below"></div>')
                        .insertBefore($productNumberLine)
                        .hide()
                        .dv('get-content', helpContentId, true);
                    $('<button>Need Help?</button>')
                        .appendTo($productNumberLine)
                        .css("margin-left", "5px")
                        .button().click(function (event) {
                            event.preventDefault();
                            $helpContent.toggle('fade', {}, 500);
                        });
                }

                // reset the form
                function resetForm(exceptLastLookupField, focusOnLastLookupField) {
                    $notFoundMessage.hide();
                    $errorMessage.hide();
                    if (exceptLastLookupField) {
                        if ($lastLookupField[0] === $descriptionField[0]) {
                            $productNumberField.val("");
                        } else {
                            $descriptionField.val("");
                        }
                    } else {
                        $productNumberField.val("");
                        $descriptionField.val("");
                    }
                    if (settings['collect-quantity']) {
                        $quantityField.val('');
                        $quantityFormValidator.resetForm();
                    }
                    $existingQuantityLabel.text("");
                    $okButton.button("option", "disabled", isAutocompleteOn);
                    $okButton.button("option", "label", settings['ok-button-text']);
                    if (focusOnLastLookupField) {
                        $lastLookupField.focus();
                    }
                }

                // create the ok button handler
                function okButtonHandler() {
                    var productNumberValue = $productNumberField.val(),
                        descriptionValue = $descriptionField.val(),
                        quantityValue = NaN;
                    if (settings['collect-quantity']) {
                        if (!$quantityForm.valid()) {
                            return;
                        }
                        quantityValue = $quantityField.val();
                    }
                    if (typeof (settings['product-selected']) === 'function') {
                        settings['product-selected'](productNumberValue, descriptionValue, quantityValue, $productNumberLine.attr("data-quantity-in"), $productNumberLine.attr("data-url"));
                    }
                    resetForm(false, true);
                }

                if (!settings['use-dialog']) {
                    // create the ok button
                    $okButton = $('<button />', { text: settings['ok-button-text'] })
                        .insertAfter($eachThis)
                        .button({ disabled: true })
                        .click(function (event) {
                            event.preventDefault();
                            okButtonHandler();
                        });
                } else {
                    // create the dialog and hte open dialog button
                    dialogButtons[settings['ok-button-text']] = function () {
                        okButtonHandler();
                    };
                    dialogButtons.Cancel = function () {
                        $eachThis.dialog("close");
                    };

                    $('<button />', { text: settings['open-dialog-button-text'] })
                        .insertAfter($eachThis)
                        .button()
                        .click(function (event) {
                            event.preventDefault();
                            if ($eachThis.dialog("isOpen")) {
                                $eachThis.dialog("close");
                                $eachThis.dialog("option", "position", "center");
                            }
                            $eachThis.dialog("open");
                        });

                    $eachThis.dialog({
                        autoOpen: false,
                        buttons: dialogButtons,
                        modal: false,
                        minWidth: 595,
                        title: settings['dialog-title'],
                        open: function () {
                            resetForm(false, true);
                        }
                    });

                    $okButton = $('div.ui-dialog-buttonpane div.ui-dialog-buttonset button:first', $eachThis.parent());
                }

                // create handlers for the autocomplete text boxes
                function autocompleteSource(request, responseCallback) {
                    $lastLookupField = this.element;
                    resetForm(true, false);
                    $.post(settings['auto-complete-url'], { "term": request.term, "byDescription": $lastLookupField[0] === $descriptionField[0], "includeCartQuantity": settings['get-existing-quantity'] === true })
                        .success(function (data) {
                            if ($(document).dv('check-ajax-result', data)) return;
                            $notFoundMessage.toggle(data.length < 1);
                            responseCallback(data);
                        }).error(function () {
                            $errorMessage.show();
                            responseCallback([]);
                        });
                }
                function autocompleteOpen() {
                    $lastLookupField = $(this);
                    $(this).autocomplete("widget").css("width", "500");
                    if ($("li", $(this).autocomplete("widget")).length === 1) {
                        $("li:first a", $lastLookupField.autocomplete("widget")).mouseenter().click();
                    }
                }
                function autocompleteFocus(event, ui) {
                    $lastLookupField = $(this);
                    event.preventDefault();
                    $descriptionField.val(ui.item.label.substr(ui.item.value.length + 1));
                    $productNumberField.val(ui.item.value);
                }
                function autocompleteSelect(event, ui) {
                    var existingQuantityValue = null;
                    $lastLookupField = $(this);
                    if (!ui.item) {
                        resetForm(true, true);
                        return;
                    }
                    event.preventDefault();
                    $descriptionField.val(ui.item.label.substr(ui.item.value.length + 1));
                    $productNumberField.val(ui.item.value);
                    if (settings['get-existing-quantity'] === true) {
                        existingQuantityValue = ui.item.cartQuantity.toString();
                        $productNumberLine.attr("data-url", ui.item.url);
                    } else if (typeof (settings['get-existing-quantity']) === 'function') {
                        existingQuantityValue = settings['get-existing-quantity'](ui.item.value);
                    }
                    if (typeof (existingQuantityValue) === 'string') {
                        $productNumberLine.attr("data-quantity-in", existingQuantityValue);
                        if (settings['show-existing-quantity']) {
                            if (existingQuantityValue !== '0') {
                                $existingQuantityLabel.text(" " + existingQuantityValue + " " + settings['existing-quantity-label']);
                                $okButton.button("option", "label", settings['alt-ok-button-text']);
                            } else {
                                $existingQuantityLabel.text(" 0 " + settings['existing-quantity-label']);
                                $okButton.button("option", "label", settings['ok-button-text']);
                            }
                        }
                    }
                    if (settings['collect-quantity']) {
                        $quantityField.focus();
                    }
                    $okButton.button("enable");
                }
                function autocompleteChange(event, ui) {
                    $lastLookupField = $(this);
                    if (!ui.item) {
                        resetForm(true, false);
                    }
                }
                function autocompleteKeydown(event) {
                    // if the enter or tab key is pressed down focus on the quantity input or search if autocomplete is on
                    $lastLookupField = $(this);
                    if (event.which === 13 || event.which === 9) {
                        event.preventDefault();
                        if (isAutocompleteOn) {
                            $lastLookupField.autocomplete("search");
                        } else {
                            $quantityField.focus();
                        }
                    }
                }

                // makes the product number text box an autocomplete text box
                $productNumberField.autocomplete({
                    source: autocompleteSource,
                    minLength: 2,
                    open: autocompleteOpen,
                    select: autocompleteSelect,
                    focus: autocompleteFocus,
                    change: autocompleteChange
                }).keydown(autocompleteKeydown);
                $descriptionField.autocomplete({
                    source: autocompleteSource,
                    minLength: 2,
                    open: autocompleteOpen,
                    select: autocompleteSelect,
                    focus: autocompleteFocus,
                    change: autocompleteChange
                }).keydown(autocompleteKeydown);

                // toggle autocomplete
                function toggleAutocomplete(enable) {
                    isAutocompleteOn = enable;
                    $lastLookupField = $productNumberField;
                    resetForm(true, true);
                    $autoCompleteButton.toggleClass("ac-on", enable);
                    $productNumberField.autocomplete("option", "disabled", !enable);
                    $descriptionLine.toggle(enable);
                    $autoCompleteButton.button("option", "label", enable ? "Turn autocomplete off" : "Turn autocomplete on")
                        .attr("title", enable ? "Turn off for faster data entry" : "Turn on to search for products");
                }

                if (settings['toggle-autocomplete']) {
                    // turn autocomplete on/off when the button is clicked
                    $autoCompleteButton = $('<button />').appendTo($productNumberLine)
                        .button()
                        .css("margin-left", "5px")
                        .click(function () {
                            toggleAutocomplete(!$(this).hasClass("ac-on"));
                            return false;
                        });
                    toggleAutocomplete(settings['autocomplete-initially']);
                }
            });
        }
    };
    $.fn.dv = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.dv');
        }
    };

    $(document).ready(function () {
        $("#create-cart-dialog").dialog({
            autoOpen: false,
            modal: true,
            minWidth: 365,
            buttons: {
                "Create Cart": function () {
                    var nameLength = $.trim($("#new-cart-name-field").val()).length;
                    $("#create-cart-name-length-info").hide();
                    if (nameLength < 1 || nameLength > 20) {
                        $("#create-cart-name-length-info").show();
                        $("#new-cart-name-field").focus();
                        return;
                    }
                    $('#cart-options-form input[name="newCartName"]').val($("#new-cart-name-field").val());
                    $(document).dv('please-wait', 'open');
                    $('#cart-options-form').submit();
                    $("#create-cart-dialog").dialog("close");
                },
                "Close": function () {
                    $('#cart-options').val($('#cart-options').attr('data-current-id'));
                    $("#create-cart-dialog").dialog("close");
                }
            },
            open: function () {
                $("#create-cart-name-length-info").hide();
                $("#new-cart-name-field").val("");
            }
        });
        if ($.browser.msie && $.browser.version < 7) {
            $("#create-cart-dialog").dialog("option", "minHeight", "215");
        }

        $("#new-cart-name-field").keydown(function (event) {
            if (event.which === 13) {
                event.preventDefault();
                $("#create-cart-dialog").dialog("option", "buttons")["Create Cart"]();
            }
        });

        $('#cart-options').live('change', function (event) {
            if ($(this).val() !== "") {
                $(document).dv('please-wait', 'open');
                $(this).parents('form').submit();
            } else {
                $("#create-cart-dialog").dialog("open");
                event.preventDefault();
            }
        });
    });
} (jQuery));

