function wonky_Cart() {
}
wonky_Cart.prototype.domain = '';
wonky_Cart.prototype.items = new Array();

/* http://ejohn.org/projects/flexible-javascript-events/ */
function wonky_AddEvent(obj, type, fn) {
    if (obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function() { obj['e' + type + fn](window.event); }
        obj.attachEvent('on' + type, obj[type + fn]);
    } else
        obj.addEventListener(type, fn, false);
}
function wonky_InitCart() {
    wonky_EnsureCookieName();
    var existingCookie = wonky_GetCookie(document.wonkyCookieName);
    if (existingCookie != null && existingCookie.length > 0) {
        var existingCart = wonky_JsonParse(existingCookie);
        if (existingCart != null && existingCart.items != null) {
            var loadedCart = new wonky_Cart();
            var existingTotal = existingCart.items.length;
            if (existingTotal > 0) {
                for (var index = 0; index < existingTotal; index++) {
                    var existingItem = existingCart.items[index];
                    if (existingItem != null) {
                        var itemID = existingItem.itemID + '';
                        var count = existingItem.count;
                        if (itemID != null && itemID.length > 0) {
                            if (count != null && count > 0) {
                                wonky_AddToCart(null, count, itemID, null, false);
                            }
                        }
                    }
                }
            }
        }
    }
    wonky_SetCountsFromTextboxes();
    wonky_RefreshCart();
    wonky_RefreshStatus();
}
wonky_AddEvent(window, 'load', wonky_InitCart);
function wonky_EnsureCookieName() {
    var nameValid = true;
    if (document.wonkyCookieName == null) {
        nameValid = false;
    } else if (document.wonkyCookieName.length == 0) {
        nameValid = false;
    }
    if (nameValid == false) {
        var fallback = '';
        if (document.wonkyCookieNameCopy != null && document.wonkyCookieNameCopy.length == 0) {
            fallback = document.wonkyCookieNameCopy;
        }
        if (fallback.length == 0) {
            fallback = 'WonkyCartCookie';
        }
        document.wonkyCookieName = fallback;
    }
}
function wonky_GetCart() {
    var cart = document.wonky_ShoppingCart;
    if (cart == null || cart.items == null) {
        cart = new wonky_Cart();
    }
    return cart;
}
function wonky_SetCart(cart) {
    document.wonky_ShoppingCart = cart;
}
function wonky_GetFloatValue(id, fallback) {
    var value = null;
    var rawValue = wonky_GetRawValue(id);
    if (rawValue != null) {
        value = parseFloat(rawValue);
    }
    if (value == null) {
        value == fallback;
    }
    return value;
}
function wonky_GetIntegerValue(id, fallback) {
    var value = null;
    var rawValue = wonky_GetRawValue(id);
    if (rawValue != null) {
        value = parseInt(rawValue);
    }
    if (value == null) {
        value == fallback;
    }
    return value;
}
function wonky_GetRawValue(id) {
    var value = null;
    if (id != null && id.length > 0) {
        var element = wonky_Get(id);
        if (element) {
            var tagName = element.tagName;
            if (tagName == 'INPUT') {
                value = element.value;
            }
            else if (tagName == 'SPAN') {
                value = element.innerHTML.replace(/,/g, '');
            }
        }
    }
    return value;
}
function wonky_RefreshCart() {
    var cartDisplay = wonky_GetCartDisplay();
    if (cartDisplay) {
        var subtotal = 0;
        var success = false;
        var subtotalID = cartDisplay.subtotalID;
        var subtotalElement = wonky_Get(subtotalID);
        if (subtotalElement) {
            if (cartDisplay.rows != null) {
                var rowCount = cartDisplay.rows.length;
                for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                    var row = cartDisplay.rows[rowIndex];
                    if (row != null) {
                        var rowID = row.rowID;
                        var itemID = row.itemID;
                        var quantityID = row.quantityID;
                        var quantity = wonky_GetIntegerValue(quantityID, 0);
                        var priceID = row.priceID;
                        var price = wonky_GetFloatValue(priceID, 0);
                        var totalID = row.totalID;
                        if (price > 0) {
                            success = true;
                            var total = quantity * price;
                            subtotal += total;
                            var totalElement = wonky_Get(totalID);
                            if (totalElement) {
                                totalElement.innerHTML = wonky_GetCommaFormattedAmount(total);
                            }
                        }
                    }
                }
            }
        }
        if (success) {
            var formattedSubTotal = wonky_GetCommaFormattedAmount(subtotal);
            subtotalElement.innerHTML = formattedSubTotal;
            var noticeElement = wonky_Get(subtotalID + '-notice');
            if (noticeElement) {
                noticeElement.innerHTML = formattedSubTotal;
            }
        }
    }
}
function wonky_EnsureQuantity(element) {
    if (element) {
        var valueNeeded = true;
        var rawValue = element.value;
        if (rawValue != null && rawValue.length > 0) {
            if (isNaN(rawValue) == false) {
                var value = parseInt(rawValue);
                if (value > -1) {
                    valueNeeded = false;
                }
            }
        }
        if (valueNeeded) {
            element.value = 0;
        }
    }
}
function wonky_EnsureNumbers(element, e) {
    var key;
    var allow = false;
    if (window.event) {
        key = e.keyCode;
    }
    else if (e.which) {
        key = e.which;
    }
    var isBackspace = (key == 8);
    var isNumber = (key >= 48 && key <= 57) || (key >= 96 && key <= 105);
    if (isNumber) {
        if (e.shiftKey && e.altKey && e.ctrlKey) {
            isNumber = false;
        }
    }
    var isArrow = (key >= 37 && key <= 40);
    var isShift = (key == 16);
    var isTab = (key == 9);
    var isEnter = (key == 13);
    var isEsc = (key == 27);
    var isHome = (key == 36);
    var isEnd = (key == 35);
    allow = (isBackspace || isNumber || isArrow || isTab || isEnter || isEsc || isHome || isEnd);
    return allow;
}
function wonky_GetCartDisplay() {
    var cartDisplay = document.WonkyCartDisplay;
    if (cartDisplay == null) {
        var cartDefinition = document.wonkyCartDefinition;
        if (cartDefinition != null && cartDefinition.length > 0) {
            cartDisplay = wonky_JsonParse(cartDefinition);
            if (cartDisplay != null) {
                document.WonkyCartDisplay = cartDisplay;
            }
        }
    }
    return cartDisplay;
}
function wonky_GetCommaFormattedAmount(raw) {
    var number = parseFloat(raw).toFixed(2);
    var unformatted = number + '';
    unformatted = unformatted.replace(/,/g, '');
    x = unformatted.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    var formatted = x1 + x2;
    return formatted;
}
function wonky_UpdateCart(element, dropdownID, itemID, name, navigation) {
    var count = 4;
    var dropdown = wonky_Get(dropdownID);
    if (dropdown) {
        if (dropdown.options) {
            var selectedIndex = dropdown.options.selectedIndex;
            if (selectedIndex != null && selectedIndex > -1) {
                var selectedOption = dropdown.options[selectedIndex];
                if (selectedOption) {
                    var value = selectedOption.value;
                    if (value != null && value.length > 0) {
                        count = parseInt(value);
                    }
                }
            }
        }
    }
    if (isNaN(count)) {
        count = 4;
    }
    wonky_UpdateCartPrivate(element, count, itemID, name, navigation, true);
}
function wonky_EnsureSelected(id, selected) {
    var element = wonky_Get(id);
    if (element != null) {
        if (element.options != null && element.options.length > 0) {
            for (var index = 0; index < element.options.length; index++) {
                var option = element.options[index];
                if (option != null) {
                    var value = option.value.toLowerCase();
                    if (value == selected) {
                        element.selectedIndex = index;
                        break;
                    }
                }
            }
        }
    }
}
function wonky_UpdateCartPrivate(element, addedCount, itemID, name, navigation, showPrompt) {
    if (itemID != null) {
        itemID += '';
        if (itemID.length > 0) {
            var existingCount = wonky_GetCountInCart(itemID);
            var addToCart = true;
            if (existingCount > 0) {
                var word = (existingCount == 1) ? wonky_TireSingular() : wonky_TiresPlural();
                if (name == null || name.length == 0) {
                    name = wonky_OfThesePhrase();
                }
                var message1 = wonky_AlreadyHavePhrase() + ' ' + existingCount + ' ' + name + ' ' + word + ' ' + wonky_InCartPhrase();
                var message2 = ' ' + wonky_AddWord() + ' ' + addedCount + ' ' + wonky_MorePhrase();
                addToCart = confirm(message1 + message2);
            }
            if (addToCart) {
                wonky_AddToCart(element, addedCount, itemID, navigation, name, showPrompt);
            }
        }
    }
}
function wonky_AddToCart(element, addedCount, itemID, navigation, name, showPrompt) {
    var cart = wonky_GetCart();
    if (cart != null && cart.items != null) {
        var success = false;
        var existingItem = wonky_GetItemFromCart(itemID);
        if (existingItem != null) {
            var existingCount = existingItem.count;
            if (existingCount == null) { existingCount = 0 };
            var newCount = existingCount + addedCount;
            existingItem.count = newCount;
            success = true;
        } else {
            var newItem = { 'itemID': itemID + '', 'count': addedCount };
            cart.items[cart.items.length] = newItem;
            success = true;
        }
        if (success) {
            totalCount = wonky_SetCartAndCookie(cart);
            if (showPrompt) {
                wonky_ShowModalMessage(addedCount, totalCount, name);
                if (navigation != null && navigation.length > 0) {
                    document.location = navigation;
                }
            }
        }
    }
}
function wonky_SetCartAndCookie(cart) {
    wonky_SetCart(cart);
    var totalCount = wonky_RefreshStatus();
    var jsonDefinition = wonky_GetJsonDefinition(cart);
    wonky_SetCookie(document.wonkyCookieName, jsonDefinition);
    return totalCount;
}
function wonky_SetCountsFromTextboxes() {
    if (document.wonkyCartIsDisplayed != null && document.wonkyCartIsDisplayed == true) {
        var cartDisplay = wonky_GetCartDisplay();
        if (cartDisplay) {
            if (cartDisplay.rows != null) {
                var rowCount = cartDisplay.rows.length;
                for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                    var row = cartDisplay.rows[rowIndex];
                    if (row != null) {
                        var itemID = row.itemID;
                        var quantityID = row.quantityID;
                        var quantityElement = wonky_Get(quantityID);
                        if (quantityElement) {
                            wonky_SetCountInCart(quantityElement, itemID);
                        }
                    }
                }
            }
        }
    }
}
function wonky_SetCountInCart(element, rowID, itemID, prompt) {
    if (element) {
        var count = parseInt(element.value);
        var cart = wonky_GetCart();
        if (cart != null && cart.items != null) {
            var existingItem = wonky_GetItemFromCart(itemID);
            if (existingItem != null) {
                existingItem.count = count;
                wonky_SetCartAndCookie(cart);
                if (count < 1 && prompt) {
                    wonky_RemoveItemAfterConfirmation(rowID, itemID);
                }
            }
        }
    }
    wonky_RefreshStatus();
}
function wonky_RemoveItemAfterConfirmation(rowID, itemID) {
    var confirmDeletePhrase = wonky_ConfirmRemovePhrase();
    var quantityBoxID = 'wonky-display-quantity-' + itemID;
    var quantityBox = wonky_Get(quantityBoxID);
    var remove = confirm(confirmDeletePhrase);
    if (remove) {
        wonky_RemoveItemFromCart(itemID);
        var row = wonky_Get(rowID);
        if (row) {
            if (quantityBox != null) {
                quantityBox.value = 0;
            }
            row.style.display = 'none';
        }
    } else {
        if (quantityBox != null) {
            quantityBox.value = 1;
            var cart = wonky_GetCart();
            if (cart != null && cart.items != null) {
                var existingItem = wonky_GetItemFromCart(itemID);
                if (existingItem != null) {
                    existingItem.count = 1;
                    wonky_SetCartAndCookie(cart);
                }
            }
        }
    }
    var totalCount = wonky_RefreshStatus();
    wonky_UpdateStatus(totalCount);
    wonky_RefreshCart();
    if (totalCount == 0) {
        var hasItemsDiv = wonky_Get('wonky-cart-has-items');
        var noItemsDiv = wonky_Get('wonky-cart-no-items');
        var checkoutButton = wonky_Get('wonky-display-forward-link');
        if (hasItemsDiv && noItemsDiv) {
            hasItemsDiv.style.display = 'none';
            noItemsDiv.style.display = 'block';
            if (checkoutButton) {
                checkoutButton.style.visibility = 'hidden';
            }
        }
    }
}
function wonky_ShowModalMessage(addedCount, totalCount, name) {
    var dimLayer = wonky_GetDimBackground();
    if (dimLayer != null) {
        dimLayer.style.display = 'block';
    }
    var dropdowns = document.getElementsByTagName('select');
    for (i = 0; i != dropdowns.length; i++) {
        dropdowns[i].style.visibility = 'hidden';
    }
    var modalLayer = wonky_GetModalLayer();
    if (modalLayer != null) {
        wonky_PrepareModalCheckoutMessage(addedCount, totalCount, name);
        var pageScroll = wonky_GetPageScroll();
        modalLayer.style.top = pageScroll + 60 + 'px';
        modalLayer.style.display = 'block';
    }
}
function wonky_PrepareModalCheckoutMessage(addedCount, totalCount, name) {
    var firstWord = (addedCount == 1) ? wonky_TireSingular() : wonky_TiresPlural();
    var firstSentence = '<p>' + wonky_WeHaveAddedPhrase() + ' ' + addedCount + ' ' + name + ' ' + firstWord + ' ' + wonky_ToYourCartPhrase() + '</p>';
    var secondSentence = '';
    if (addedCount != totalCount) {
        var secondWord = (totalCount == 1) ? wonky_TireSingular() : wonky_TiresPlural();
        secondSentence = '<p>' + wonky_YouNowHavePhrase() + ' ' + totalCount + ' ' + secondWord + ' ' + wonky_InYourCart() + '</p>';
    }
    var thirdUrl = wonky_AppPath() + wonky_CartUrl();
    if (thirdUrl == null || thirdUrl.length == 0) {
        thirdUrl = "javascript:;";
    }
    var thirdSentence = '<p class="wonky-action">' + wonky_DoYouWishToPhrase() +
        '<span>' + '<a href="javascript:;" class="wonky-action-continue">' + wonky_ContinueShoppingPhrase() + '</a>' + '</span>' +
        wonky_OrWord() +
        '<span>' + '<a href="' + thirdUrl + '" class="wonky-action-checkout">' + wonky_CheckOutNowPhrase() + '</a>' + '</span>' + '</p>';
    var html = firstSentence + secondSentence + thirdSentence;
    var modalLayerInner = wonky_GetModalLayerInner();
    if (modalLayerInner) {
        modalLayerInner.innerHTML = html;
    }
}
function wonky_HideModalMessage() {
    var dimLayer = wonky_GetDimBackground();
    if (dimLayer != null) {
        dimLayer.style.display = 'none';
    }
    var dropdowns = document.getElementsByTagName('select');
    for (i = 0; i != dropdowns.length; i++) {
        dropdowns[i].style.visibility = 'visible';
    }
    var modalLayer = wonky_GetModalLayer();
    if (modalLayer != null) {
        modalLayer.style.display = 'none';
    }
}
function wonky_GetDimBackground() {
    return wonky_Get('wonky-background');
}
function wonky_GetModalLayer() {
    return wonky_Get('wonky-modal');
}
function wonky_GetModalLayerInner() {
    return wonky_Get('wonky-modal-inner');
}
function wonky_GetPageScroll() {
    var pageScroll;
    if (self.pageYOffset) {
        pageScroll = self.pageYOffset;
        pageScroll = window.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        pageScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        pageScroll = document.body.scrollTop;
    }
    return pageScroll;
}
function wonky_RefreshStatus() {
    var count = 0;
    var cart = wonky_GetCart();
    if (cart != null) {
        if (cart.items != null) {
            var total = cart.items.length;
            if (total > 0) {
                for (var index = 0; index < total; index++) {
                    var item = cart.items[index];
                    if (item != null) {
                        count += item.count;
                    }
                }
            }
        }
    }
    wonky_UpdateStatus(count);
    return count;
}
function wonky_GetJsonDefinition(cart) {
    var definition = '';
    if (cart != null && cart.items != null) {
        var total = cart.items.length;
        var domain = wonky_Domain();
        definition += '{ ';
        if (domain != null && domain.length > 0) {
            definition += '"domain":"' + domain + '", ';
        }
        definition += '"items": [';
        if (total > 0) {
            var separator = '';
            for (var index = 0; index < total; index++) {
                var item = cart.items[index];
                if (item != null) {
                    definition += separator + '{ "itemID":"' + item.itemID + '", "count":' + item.count + '}';
                    separator = ', ';
                }
            }
        }
        definition += '] }';
    }
    return definition;
}
function wonky_GetCountInCart(itemID) {
    var count = 0;
    if (itemID != null && itemID.length > 0) {
        var cart = wonky_GetCart();
        var existingItem = wonky_GetItemFromCart(itemID);
        if (existingItem != null) {
            count = existingItem.count;
        }
    }
    return count;
}
function wonky_GetItemFromCart(itemID) {
    var item = null;
    if (itemID != null) {
        itemID += '';
        if (itemID.length > 0) {
            var cart = wonky_GetCart();
            if (cart != null && cart.items != null) {
                var total = cart.items.length;
                if (total > 0) {
                    for (var index = 0; index < total; index++) {
                        var existingItem = cart.items[index];
                        if (existingItem != null) {
                            if (existingItem.itemID == itemID) {
                                item = existingItem;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    return item;
}
function wonky_RemoveAllItemsFromCart() {
    var cart = wonky_GetCart();
    if (cart != null && cart.items != null) {
        var total = cart.items.length;
        if (total > 0) {
            for (var index = 0; index < total; index++) {
                var existingItem = cart.items[index];
                if (existingItem != null) {
                    existingItem.count = 0;
                    cart.items.splice(index, 1);
                }
            }
        }
        wonky_SetCartAndCookie(cart);
    }
}
function wonky_RemoveItemFromCart(itemID) {
    if (itemID.length > 0) {
        var cart = wonky_GetCart();
        if (cart != null && cart.items != null) {
            var total = cart.items.length;
            if (total > 0) {
                for (var index = 0; index < total; index++) {
                    var existingItem = cart.items[index];
                    if (existingItem != null) {
                        if (existingItem.itemID == itemID) {
                            existingItem.count = 0;
                            cart.items.splice(index, 1);
                            break;
                        }
                    }
                }
            }
            wonky_SetCartAndCookie(cart);
        }
    }
}
function wonky_UpdateStatus(count) {
    var status = wonky_Get('wonky-cart-count');
    if (status) {
        var phrase = wonky_EmptyWord();
        if (count > 0) {
            var tires = (count == 1) ? wonky_TireSingular() : wonky_TiresPlural();
            phrase = count + ' ' + tires;
        }
        var html = '(' + phrase + ')';
        status.innerHTML = html;
    }
}
function wonky_Get(id) {
    var element = document.getElementById(id);
    return element;
}
function wonky_GetCookie(name) {
    var value = '';
    if (name != null && name.length > 0) {
        if (document.cookie.length > 0) {
            cookieStart = document.cookie.indexOf(name + '=');
            if (cookieStart > -1) {
                var valueStart = cookieStart + name.length + 1;
                var valueEnd = document.cookie.indexOf(';', valueStart);
                if (valueEnd < 0) {valueEnd = document.cookie.length; }
                var valueRaw = document.cookie.substring(valueStart, valueEnd);
                value = unescape(valueRaw);
            }
        }
    }
    return value;
}
function wonky_SetCookie(name, value) {
    var expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 3650);
    var path = wonky_AppPath();
    if (path == null || path.length == 0) {
        path = '/';
    }
    if (path.substring(path.length - 1, path.length) != '/') {
        path += '/';
    }
    document.cookie = name + '=' + escape(value) + ';expires=' + expiryDate.toGMTString() + ';path=' + path;
}
function wonky_JsonParse(text) {
    var value = 
            !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
            text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + text + ')');
    return value;
}
function wonky_BuyLinkHover(element) {
    var hoverClass = '-hover';
    var parentNode = element.parentNode;
    if (parentNode) {
        var childAnchors = parentNode.getElementsByTagName("a");
        var childSpans = parentNode.getElementsByTagName("span");
        wonky_AppendCssClass(childAnchors, hoverClass);
        wonky_AppendCssClass(childSpans, hoverClass);
    }
}
function wonky_AppendCssClass(elements, appendClass) {
    if (elements) {
        var count = elements.length;
        if (count > 0) {
            for (var index = 0; index < count; index++) {
                var element = elements[index];
                if (element) {
                    var addClass = true;
                    var existingClass = element.className;
                    if (existingClass.length > appendClass.length) {
                        var existingEnd = existingClass.substring(existingClass.length - appendClass.length, existingClass.length);
                        if (existingEnd == appendClass) {
                            addClass = false;
                        }
                    }
                    if (addClass) {
                        var newClass = existingClass + appendClass;
                        element.className = newClass;
                    }
                }
            }
        }
    }
}
function wonky_BuyLinkBlur(element) {
    var hoverClass = '-hover';
    var parentNode = element.parentNode;
    if (parentNode) {
        var childAnchors = parentNode.getElementsByTagName("a");
        var childSpans = parentNode.getElementsByTagName("span");
        wonky_RemoveCssClass(childAnchors, hoverClass);
        wonky_RemoveCssClass(childSpans, hoverClass);
    }
}
function wonky_RemoveCssClass(elements, appendClass) {
    if (elements) {
        var count = elements.length;
        if (count > 0) {
            for (var index = 0; index < count; index++) {
                var element = elements[index];
                if (element) {
                    var removeClass = false;
                    var existingClass = element.className;
                    if (existingClass.length > appendClass.length) {
                        var existingEnd = existingClass.substring(existingClass.length - appendClass.length, existingClass.length);
                        if (existingEnd == appendClass) {
                            removeClass = true;
                        }
                    }
                    if (removeClass) {
                        var newClass = existingClass.substring(0, existingClass.length - appendClass.length);
                        element.className = newClass;
                    }
                }
            }
        }
    }
}
function wonky_SigninRequiredPrompt() {
    var message = wonky_SigninRequired();
    if (message != null && message.length > 0) {
        alert(message);
    }
}
function wonky_TireSingular() {
    return wonky_ThisOrFallback(document.wonkyTireSingular, 'tire');
}
function wonky_TiresPlural() {
    return wonky_ThisOrFallback(document.wonkyTiresPlural, 'tires');
}
function wonky_AlreadyHavePhrase() {
    return wonky_ThisOrFallback(document.wonkyAlreadyHavePhrase, 'You already have');
}
function wonky_InCartPhrase() {
    return wonky_ThisOrFallback(document.wonkyInCartPhrase, 'in your cart.');
}
function wonky_AddWord() {
    return wonky_ThisOrFallback(document.wonkyAddWord, 'Add');
}
function wonky_MorePhrase() {
    return wonky_ThisOrFallback(document.wonkyMorePhrase, 'more?');
}
function wonky_OfThesePhrase() {
    return wonky_ThisOrFallback(document.wonkyOfThesePhrase, 'of these');
}
function wonky_EmptyWord() {
    return wonky_ThisOrFallback(document.wonkyEmptyWord, 'empty');
}
function wonky_WeHaveAddedPhrase() {
    return wonky_ThisOrFallback(document.wonkyWeHaveAddedPhrase, 'We have added');
}
function wonky_ToYourCartPhrase() {
    return wonky_ThisOrFallback(document.wonkyToYourCartPhrase, 'to your shopping cart.');
}
function wonky_YouNowHavePhrase() {
    return wonky_ThisOrFallback(document.wonkyYouNowHavePhrase, 'You now have');
}
function wonky_InYourCart() {
    return wonky_ThisOrFallback(document.wonkyInYourCart, 'in your cart.');
}
function wonky_DoYouWishToPhrase() {
    return wonky_ThisOrFallback(document.wonkyDoYouWishToPhrase, 'Do you wish to');
}
function wonky_ContinueShoppingPhrase() {
    return wonky_ThisOrFallback(document.wonkyContinueShoppingPhrase, 'Continue Shopping');
}
function wonky_ConfirmRemovePhrase() {
    return wonky_ThisOrFallback(document.wonkyConfirmRemovePhrase, 'Are you sure you want to remove this tire from your cart?');
}
function wonky_SigninRequired() {
    return wonky_ThisOrFallback(document.wonkySigninRequiredMessage, 'You need to be signed in to purchase tires.');
}
function wonky_OrWord() {
    return wonky_ThisOrFallback(document.wonkyOrWord, 'or');
}
function wonky_CartUrl() {
    var url = document.wonkyCartUrl;
    if (url == null || url.length == 0) {
        url = 'javascript:;'
    }
    return url;
}
function wonky_AppPath() {
    var path = document.appPath;
    if (path == null || path.length == 0) {
        path = document.wonkyAppPath;
    }
    if (path == null)
        path = '';
    if (path.length > 0 && path.substring(0, 1) != '/')
        path = '/' + path;
    return path;
}
function wonky_Domain() {
    var domain = document.wonkyDomain;
    return domain;
}
function wonky_CheckOutNowPhrase() {
    return wonky_ThisOrFallback(document.wonkyCheckOutNowPhrase, 'Check Out Now');
}
function wonky_ThisOrFallback(name, fallback) {
    var value = name;
    if (value == null || value.length == 0) {
        value = fallback;
    }
    return value;
}
function wonky_CreateHtml() {
    document.write('<div id="wonky-background" class="wonky-background" style="display:none;" onclick="wonky_HideModalMessage();">');
    document.write('</div>');
    document.write('<div id="wonky-modal" class="wonky-modal" style="display:none;" onclick="wonky_HideModalMessage();">');
    document.write('<div id="wonky-modal-inner" class="wonky-modal-inner">');
    document.write('</div>');
    document.write('</div>');
}

function wonky_FormSubmit(formID, actionID, actionValue, errorID) {
    if (errorID) {
        wonky_ShowDeliveryError(errorID, '');
    }
    if (actionID) {
        var actionElement = wonky_Get(actionID);
        if (actionElement) {
            actionElement.value = actionValue;
        }
    }
    var formElement = wonky_Get(formID);
    if (formElement) {
        formElement.submit();
    }
}
function wonky_SelectRadio(radioID) {
    var radioElement = wonky_Get(radioID);
    if (radioElement) {
        radioElement.checked = 'checked';
    }
}
function wonky_FetchStates(countryID, statesID) {
    var country = wonky_Get(countryID);
    var states = wonky_Get(statesID);
    if (country != null && states != null) {
        states.style.visibility = 'hidden';
        var ajaxClient = GetAjaxClient();
        if (ajaxClient != null) {
            ajaxClient.onreadystatechange = function() {
                if (ajaxClient.readyState == 4) {
                    wonky_PopulateList(states, ajaxClient.responseText);
                }
            }
            var abbreviation = country.options[country.selectedIndex].value;
            var selected = wonky_EncodeQuery(abbreviation);
            var query = 'method=states&country=' + selected;
            var service = wonky_AppPath() + '/App_Services/WonkyWheel.ashx?' + query;
            ajaxClient.open('GET', service, true);
            ajaxClient.send(null);
        }
    }
}
function wonky_PopulateList(element, response) {
    for (var count = element.options.length - 1; count > -1; count--) {
        element.options[count] = null;
    }
    if (response.indexOf('<html>') < 0) {
        var pairs = wonky_JsonParse(response);
        if (pairs != null) {
            element.selectedIndex = 0;
            for (var index = 0; index < pairs.length; index++) {
                var pair = pairs[index];
                if (pair != null) {
                    var name = pair.name;
                    var value = pair.value;
                    var option = new Option(name, value, false, false);
                    element.options[element.length] = option;
                }
            }
            element.style.visibility = 'visible';
        }
    }
}
function wonky_EncodeQuery(query) {
    query = query.replace(/(\s)/g, '+');
    return query;
}
function wonky_ResetPrice(priceID) {
    var priceElement = wonky_Get(priceID);
    if (priceElement != null) {
        priceElement.innerHTML = '';
    }
}
function wonky_GetRefreshUrl() {
    var spinning = document.wonkyRefreshUrl;
    if (wonky_IsAbsoluteUrl(spinning) == false) {
        spinning = wonky_AppPath() + spinning;
    }
    return spinning;
}
function wonky_GetSpinnerUrl() {
    var spinning = document.wonkySpinnerUrl;
    if (wonky_IsAbsoluteUrl(spinning) == false) {
        spinning = wonky_AppPath() + spinning;
    }
    return spinning;
}
function wonky_IsAbsoluteUrl(url) {
    var isAbsoluteUrl = false;
    var protocol = 'http://';
    if (url.length > 0) {
        var lowercaseUrl = url.toLowerCase();
        if (lowercaseUrl.substring(0, protocol.length) == protocol) {
            isAbsoluteUrl = true;
        }
    }
    return isAbsoluteUrl;
}
function wonky_StartPriceSpinner(spinnerID) {
    var spinning = wonky_GetSpinnerUrl();
    wonky_SetPriceSpinner(spinnerID, spinning);
}
function wonky_StopPriceSpinner(spinnerID) {
    var refresh = wonky_GetRefreshUrl();
    wonky_SetPriceSpinner(spinnerID, refresh);
}
function wonky_SetPriceSpinner(spinnerID, spinnerSrc) {
    var spinner = wonky_Get(spinnerID);
    if (spinner != null) {
        var spinnerAlreadyUsingSource = wonky_ImageHasSource(spinner, spinnerSrc);
        if (spinnerAlreadyUsingSource == false) {
            spinner.src = spinnerSrc;
        }
    }
}
function wonky_CalculateShipping(address1ID, address2ID, address3ID, cityID, postcodeID, stateID, countryID, speedID, priceID, spinnerID, errorID) {
    wonky_StartPriceSpinner(spinnerID);
    wonky_ShowDeliveryPrice(priceID, '');
    wonky_ShowDeliveryError(errorID, '');
    var addressValid = true;
    // Address 1
    var address1 = '';
    var address1Box = wonky_Get(address1ID);
    if (address1Box) {
        address1 = wonky_TrimValue(address1Box.value);
    }
    if (address1.length > 0) {
        wonky_SetMessage(address1ID, '');
    } else {
        wonky_ShowRequired(address1ID);
        addressValid = false;
    }
    // Address 2
    var address2 = '';
    var address2Box = wonky_Get(address2ID);
    if (address2Box) {
        address2 = wonky_TrimValue(address2Box.value);
    }
    // Address 3
    var address3 = '';
    var address3Box = wonky_Get(address3ID);
    if (address3Box) {
        address3 = wonky_TrimValue(address3Box.value);
    }
    // City
    var city = '';
    var cityBox = wonky_Get(cityID);
    if (cityBox) {
        city = wonky_TrimValue(cityBox.value);
    }
    if (city.length > 0) {
        wonky_SetMessage(cityID, '');
    } else {
        wonky_ShowRequired(cityID);
        addressValid = false;
    }
    // Post Code
    var postcode = '';
    var postcodeBox = wonky_Get(postcodeID);
    if (postcodeBox) {
        postcode = wonky_TrimValue(postcodeBox.value);
    }
    if (postcode.length > 0) {
        wonky_SetMessage(postcodeID, '');
    } else {
        wonky_ShowRequired(postcodeID);
        addressValid = false;
    }
    // State
    var state = '';
    var stateBox = wonky_Get(stateID);
    if (stateBox) {
        state = wonky_TrimValue(stateBox.value);
    }
    // Country
    var country = '';
    var countryBox = wonky_Get(countryID);
    if (countryBox) {
        country = wonky_TrimValue(countryBox.value);
    }
    // Service
    var speed = '';
    var speedBox = wonky_Get(speedID);
    if (speedBox) {
        speed = wonky_TrimValue(speedBox.value);
    }
    // Weight
    var weight = 0;
    var weightRaw = wonky_TrimValue(document.wonkyCartWeight);
    if (weightRaw != null && weightRaw.length > 0) {
        weight = parseFloat(weightRaw);
    }
    var weightValid = (weight > 0);
    if (addressValid && weightValid) {
        wonky_FetchDeliveryPriceIfPostCodeValid(address1, address2, address3, city, postcode, postcodeID, state, country, speed, priceID, spinnerID, errorID, weight);
    } else {
        wonky_StopPriceSpinner(spinnerID);
        wonky_ShowDeliveryPriceError(priceID);
    }
}
function wonky_TrimValue(value) {
    var trimmed = value;
    if (trimmed == null) {
        trimmed = '';
    }
    if (trimmed.length > 0) {
        trimmed = trimmed.replace(/^\s*/, '').replace(/\s*$/, '');
    }
    return trimmed;
}
function wonky_FetchDeliveryPriceIfPostCodeValid(address1, address2, address3, city, postcode, postcodeID, state, country, speed, priceID, spinnerID, errorID, weight) {
    wonky_ShowDeliveryError(errorID, ''); 
    var ajaxClient = wonky_GetAjaxClient();
    if (ajaxClient != null) {
        ajaxClient.onreadystatechange = function() {
            if (ajaxClient.readyState == 4) {
                var response = ajaxClient.responseText;
                var result = wonky_JsonParse(response);
                var fetchPrice = false;
                if (result != null) {
                    if (result.success == 'true') {
                        fetchPrice = true;
                    } else {
                        wonky_ShowInvalid(postcodeID);
                    }
                }
                if (fetchPrice) {
                    wonky_FetchDeliveryPrice(address1, address2, address3, city, postcode, state, country, speed, priceID, spinnerID, errorID, weight);
                } else {
                    wonky_StopPriceSpinner(spinnerID);
                    wonky_ShowDeliveryPriceError(priceID);
                }
            }
        }
        var now = new Date();
        var timeStamp = "&stamp=" + now.getFullYear() + now.getMonth() + now.getDate() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
        var query = 'method=validatePostCode' + wonky_GetUrlQueryValue("postcode", postcode) + timeStamp;
        var url = wonky_AppPath() + '/App_Services/WonkyWheel.ashx?' + query;
        ajaxClient.open('GET', url, true);
        ajaxClient.send(null);
    }
}
function wonky_FetchDeliveryPrice(address1, address2, address3, city, postcode, state, country, speed, priceID, spinnerID, errorID, weight) {
    var ajaxClient = wonky_GetAjaxClient();
    if (ajaxClient != null) {
        ajaxClient.onreadystatechange = function() {
            if (ajaxClient.readyState == 4) {
                var response = ajaxClient.responseText;
                var result = wonky_JsonParse(response);
                var price = -1;
                var showPrice = false;
                var errorMessage = "Could not connect to web service.";
                if (result != null) {
                    if (result.success == 'true') {
                        showPrice = true;
                        price = parseFloat(result.price);
                        errorMessage = '';
                    } else {
                        if (result.error != null) {
                            errorMessage = result.error;
                        } else {
                            errorMessage = "Unknown error received from web service.";
                        }
                    }
                }
                wonky_StopPriceSpinner(spinnerID);
                if (showPrice) {
                    if (price > 0) {
                        wonky_ShowDeliveryPrice(priceID, '$' + wonky_GetCommaFormattedAmount(price.toFixed(2)));
                    } else {
                        wonky_ShowFreeDeliveryPrice(priceID);
                    }
                } else {
                    wonky_ShowDeliveryPriceError(priceID);
                }
                wonky_ShowDeliveryError(errorID, errorMessage);
            }
        }
        var query = 'method=deliveryPrice' +
            wonky_GetUrlQueryValue('address1', address1) +
            wonky_GetUrlQueryValue('address2', address2) +
            wonky_GetUrlQueryValue('address3', address3) +
            wonky_GetUrlQueryValue('city', city) +
            wonky_GetUrlQueryValue('postcode', postcode) +
            wonky_GetUrlQueryValue('state', state) +
            wonky_GetUrlQueryValue('country', country) +
            wonky_GetUrlQueryValue('speed', speed) +
            wonky_GetUrlQueryValue('weight', weight);
        var url = wonky_AppPath() + '/App_Services/WonkyWheel.ashx?' + query;
        ajaxClient.open('GET', url, true);
        ajaxClient.send(null);
    }
}
function wonky_GetUrlQueryValue(name, value) {
    var valueAsString = '' + value;
    var encodedValue = valueAsString.replace(/(\s)/g, '+');
    var queryValue = '&' + name + '=' + encodedValue;
    return queryValue;
}
function wonky_GetAjaxClient() {
    var ajaxClient;
    try {
        ajaxClient = new XMLHttpRequest();
    }
    catch (e) {
        try {
            ajaxClient = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                ajaxClient = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                ajaxClient = null;
            }
        }
    }
    return ajaxClient;
}
function wonky_ShowFreeDeliveryPrice(priceID) {
    var text = document.wonkyFreeWord;
    if (text == null || text.length == 0) {
        text = 'Free';
    }
    var html = '<span>' + text + '</span>';
    wonky_ShowDeliveryPrice(priceID, html);
}
function wonky_ShowDeliveryPriceError(priceID) {
    var text = document.wonkyErrorWord;
    if (text == null || text.length == 0) {
        text = 'Error';
    }
    var html = '<span>' + text + '</span>';
    wonky_ShowDeliveryPrice(priceID, html);
}
function wonky_ShowDeliveryError(errorID, html) {
    var errorEl = wonky_Get(errorID);
    if (errorEl != null) {
        errorEl.innerHTML = html;
    }
}
function wonky_ShowDeliveryPrice(priceID, html) {
    var priceEl = wonky_Get(priceID);
    if (priceEl != null) {
        priceEl.innerHTML = html;
    }
}
function wonky_ShowRequired(boxID) {
    var text = document.wonkyRequiredWord;
    if (text == null || text.length == 0) {
        text = 'Required';
    }
    wonky_SetMessage(boxID, text);
}
function wonky_ShowInvalid(boxID) {
    var text = document.wonkyInvalidWord;
    if (text == null || text.length == 0) {
        text = 'Invalid';
    }
    wonky_SetMessage(boxID, text);
}

function wonky_SetMessage(boxID, text) {
    var messageID = boxID + '-error';
    var messageEl = wonky_Get(messageID);
    if (messageEl) {
        var html = '';
        if (text.length > 0) {
            html = '<span>' + text + '</span>';
        }
        messageEl.innerHTML = html;
    }
}
function wonky_ImageHasSource(image, source) {
    var hasSource = false;
    if (image != null) {
        var currentSource = image.src;
        var currentLength = currentSource.length;
        var sourceLength = source.length;
        if (currentLength >= sourceLength) {
            var endOfCurrentSource = currentSource.substring(currentLength - sourceLength, currentLength);
            hasSource = (endOfCurrentSource == source);
        }
    }
    return hasSource;
}
function wonky_GotoAfterConfirmation(url, message) {
    var allowGoto = false;
    if (wonky_IsDataDirty()) {
        allowGoto = confirm(message);
    } else {
        allowGoto = true;
    }
    if (allowGoto) {
        wonky_Goto(url);
    }
}
function wonky_Goto(path) {
    var appPath = wonky_AppPath();
    if (appPath.substring(appPath.length - 1, appPath.length) == '/') {
        if (path.substring(0, 1) == '/') {
            path = path.substring(1, path.length);
        }
    }
    var gotoUrl = appPath + path;
    document.location = gotoUrl;
}
function wonky_PreloadImage(url) {
    if (url != null && url.length > 0) {
        if (url.substring(0, 1) == "/") {
            url = wonky_AppPath() + url;
        }
        if (document.preloadedImages == null) document.preloadedImages = new Array();
        var count = document.preloadedImages.length;
        if (count > 0) {
            for (var i = 0; i < count; i++) {
                if (document.preloadedImages[i].src == url) return;
            }
        }
        document.preloadedImages[count] = new Image();
        document.preloadedImages[count].src = url;
    }
}
function pingForIpnResult() {
    if (document.wonkyPingCount == null) {
        document.wonkyPingCount = 0;
    } else {
        document.wonkyPingCount++;
    }
    if (document.wonkyPingCount > 4) {
        document.location = document.wonkyCompletedUrl;
    } else {
        doPingForIpnResult();
    }
}
function doPingForIpnResult() {
    var ajaxClient = wonky_GetAjaxClient();
    if (ajaxClient != null) {
        ajaxClient.onreadystatechange = function() {
            if (ajaxClient.readyState == 4) {
                var response = ajaxClient.responseText;
                var result = wonky_JsonParse(response);
                var isComplete = false;
                var debug = 'response \'' + response + '\' | ';
                if (result != null) {
                    if (result.status != 'unspecified') {
                        isComplete = true;
                    }
                }
                debug += 'isComplete ' + isComplete + ' | ';
                if (isComplete) {
                    document.location = document.wonkyCompletedUrl;
                } else {
                    setTimeout("pingForIpnResult()", 5000);
                }
            }
        }
        var sitekindID = (document.wonkySiteKindID != null) ? document.wonkySiteKindID : -1;
        var websiteID = (document.wonkyWebSiteID != null) ? document.wonkyWebSiteID : -1;
        var checkoutID = (document.wonkyCheckoutID != null) ? document.wonkyCheckoutID : -1;
        var query = 'method=checkoutStatus' +
            wonky_GetUrlQueryValue('sitekindID', sitekindID) +
            wonky_GetUrlQueryValue('websiteID', websiteID) +
            wonky_GetUrlQueryValue('checkoutID', checkoutID);
        var url = wonky_AppPath() + '/App_Services/WonkyWheel.ashx?' + query;
        ajaxClient.open('GET', url, true);
        ajaxClient.send(null);
    } 
}
function wonky_IsDataDirty() {
    var isDirty = (document.wonkyDataIsDirty != null && document.wonkyDataIsDirty == true);
    return isDirty;
}
function wonky_MarkAsDirty() {
    document.wonkyDataIsDirty = true;
}
function wonky_GlobalLoad() {
    if (document.wonkySpinnerUrl != null) {
        wonky_PreloadImage(document.wonkySpinnerUrl);
    }
}
wonky_AddEvent(window, 'load', wonky_GlobalLoad);
