﻿var recentItemsContainerFadeOutTimerId;

function addToCart(productInstanceId, quantity) {
    if(!quantity || quantity == '' || quantity == '0' || !/^\d{1,3}$/.test(quantity)) {
        alert('The quantity you entered is not valid.');
        return false;
    }
    
    var addButton = document.getElementById('cv_ip_productInstance_add');
    var parameters = new Object();
    parameters.productInstanceId = productInstanceId;
    parameters.quantity = quantity;
    if(addButton) disableLinkButton(addButton);
    ajaxServiceCall('addToCart', 
        function(xmlDoc) {
            if(addButton) enableLinkButton(addButton);
            page_updateMiniCartCounts(xmlDoc);
            page_updateRecentCartListing(xmlDoc);
        }, parameters);
    return true;
}

function removeFromCart(productInstanceId) {
    if(!confirm('Are you sure you want to remove this item from your shopping cart?'))
        return false;
    
    var parameters = new Object();
    parameters.productInstanceId = productInstanceId;
    ajaxServiceCall('removeFromCart',
        function(xmlDoc) {
            page_updateCartCounts(xmlDoc);
            page_updateCartListing(xmlDoc);
        }, parameters);
    
    return true;
}

function adjustCartQuantity(domSender, productInstanceId) {
    var quantity = domSender.value;
    if(!quantity || quantity == '') quantity = 0;
    
    if(!/^\d{1,4}$/.test(quantity)) {
        alert('The quantity you entered is not valid.');
        focusAndSelectElement(domSender);
        return false;
    }
    else if(quantity == 0) {
        if(removeFromCart(productInstanceId))
            return true;
        else {
            focusAndSelectElement(domSender);
            return false;
        }
    }

    var parameters = new Object();
    parameters.productInstanceId = productInstanceId;
    parameters.quantity = quantity;
    ajaxServiceCall('adjustCartQuantity', 
        function(xmlDoc) {
            page_updateCartCounts(xmlDoc);
            page_updateCartListing(xmlDoc);
        }, parameters);
    
    return true;
}

function adjustDiscountCode(code) {
    if(!code || code == '' || !/^[a-zA-Z0-9]{1,16}$/.test(code)) {
        alert('The promotion code you entered is not valid; promotion codes are alphanumeric and contain no spaces.');
        return false;
    }
    
    var parameters = new Object();
    parameters.code = code;
    ajaxServiceCall('adjustPromoCode', 
        function(xmlDoc) {
            page_updateCartListing(xmlDoc);
            page_updateCartCounts(xmlDoc);
            var inputBox = document.getElementById('cart_promotionCode');
            if(inputBox && inputBox.value == '')
                alert('The promotion code you entered was not accepted.');
        }, parameters);
        
    return true;
}

function page_updateCartListing(xmlDoc) {
    var itemAttributes = Array('productName', 'typeName', 'genderName', 'colorName', 'teamName', 'sizeName', 'quantity', 'price', 'computedPrice', 'lastAdded');
    var resultTable = getMultipleXmlTagAttributes(xmlDoc, '/response/item', 'productInstanceId', itemAttributes);
    var productInstanceIds = Array();
    
    if(resultTable.length == 0) {
        // sadly, an empty cart must require a reload
        window.location.reload();
        return;
    }
    
    for(var key in resultTable) {
        var productInstanceId = resultTable[key].productInstanceId;
        var associatedRow = document.getElementById('cartList_' + productInstanceId);
        if(associatedRow) {
            // update rows
            for(var i = 0; i < itemAttributes.length; ++i)  {
                var itemAttribute = itemAttributes[i];
                var associatedCell = document.getElementById('cartList_' + productInstanceId + '_' + itemAttribute);
                if(associatedCell) associatedCell.innerHTML = resultTable[key][itemAttribute];
            }
            
            // ...an input box requires a slightly different approach than innerHTML :)
            var associatedQuantityInput = document.getElementById('cartList_' + productInstanceId + '_quantity_input');
            if(associatedQuantityInput) associatedQuantityInput.value = resultTable[key]['quantity'];
        }
        else {
            // there are new rows, which requires a full reload of the page.
            window.location.reload();
            return;
        }
        
        // Mark this product instnace as seen so we can remove missing items later
        productInstanceIds.push(productInstanceId);
    }

    var rowsToRemove = Array();
    var cartList = document.getElementById('cartList');
    if(cartList) {
        var rowTags = cartList.getElementsByTagName('tr');
        for(var i = 0; i < rowTags.length; ++i)
            if(rowTags[i].id != "" && /^cartList_\d+$/.test(rowTags[i].id) && !array_contains(productInstanceIds, rowTags[i].id.split('_')[1]))
                rowsToRemove.push(rowTags[i]);
    }
    
    for(var i = 0; i < rowsToRemove.length; ++i)
        cartList.removeChild(rowsToRemove[i]);
}

function page_updateRecentCartListing(xmlDoc) {
    var recentItemsContainer = document.getElementById('cart_' + 'recentItems'), universal = document.getElementById('universal');
    if(recentItemsContainer && universal) {
        recentItemsContainer.innerHTML = '';
        recentItemsContainer.style.top = '' + (universal.offsetHeight - 7) + 'px'; // 7 is the padding on the box
        
        fadeElementIn(recentItemsContainer, 'block');
        if(recentItemsContainerFadeOutTimerId) clearTimeout(recentItemsContainerFadeOutTimerId);
        recentItemsContainerFadeOutTimerId = setTimeout(function() { fadeElementOut(recentItemsContainer); }, msTimeToDisplayMiniatureCartRecentItems);

        var resultTable = getMultipleXmlTagAttributes(xmlDoc, '/response/recent', 'productInstanceId', Array('productName', 'typeName', 'genderName',
                            'colorName', 'teamName', 'sizeName', 'cartImage', 'quantity', 'price', 'computedPrice'));
        
        var innerHtml = '<table><thead><tr><td colspan="2">Just Added:</td><td class="X"><a href="javascript:completeFadeOut(document.getElementById(\'cart_recentItems\'))"><img src="../images/buttons/x.gif" alt="X" title="Close this popup layer" /></a></td></tr></thead><tbody>';
        for(var key in resultTable) {
            var productAttributes = resultTable[key];
            innerHtml += '<tr><td rowspan="2"><img src="' + (productAttributes['cartImage'] != '' ? productAttributes['cartImage'] : '../images/catalog/product/missing/color/cart.gif') + '" alt="' + productAttributes['productName'] + ' product image" width="65" height="65" /></td>' +
                            '<td style=\"width: 100%\">' +
                                '<div class="Description">' + productAttributes['typeName'] + ': ' + productAttributes['productName'] + '<br />' +
                                productAttributes['genderName'] + ' ' + productAttributes['sizeName'] + ' in ' + (productAttributes['teamName'] != "" ? (productAttributes['teamName'] + ' ') : '') + productAttributes['colorName'] + '</div>' +
                                '<div class="Price">' + productAttributes['computedPrice'] + ' (' + productAttributes['quantity'] + ' @ ' + productAttributes['price'] + ')</div>' +
                            '</td></tr>' +
                            '<tr><td class="Checkout"><a href="cart.aspx" title="Shopping Cart">view cart</a> <a href="cart.aspx" title="Shopping Cart"><img src="../images/buttons/checkout.gif" /></a></td></tr>';
            break;
        }
        
        innerHtml += '</tbody></table>'
        
        recentItemsContainer.innerHTML = innerHtml;
    }
}

function page_updateCartCounts(xmlDoc) {
    var countAttributes = Array('subtotal', 'tax', 'shipping', 'promotionCode', 'promotionDiscount', 'promotionReason', 'total');
    var resultList = getSingleXmlTagAttributes(xmlDoc, '/response/count', countAttributes);
    for(var i = 0; i < countAttributes.length; ++i) {
        var attribute = countAttributes[i];
        var spanElement = document.getElementById('cart_' + attribute);
        if(spanElement) {
            if(spanElement.tagName.toLowerCase() == 'input') spanElement.value = resultList[attribute];
            else spanElement.innerHTML = resultList[attribute];
        }
    }
}

function page_updateMiniCartCounts(xmlDoc) {
    var countAttributes = Array('quantitySum', 'computedPriceSum');
    var resultList = getSingleXmlTagAttributes(xmlDoc, '/response/count', countAttributes);
    for(var i = 0; i < countAttributes.length; ++i) {
        var attribute = countAttributes[i];
        var spanElement = document.getElementById('cart_' + attribute);
        if(spanElement) {
            if(spanElement.value) spanElement.value = resultList[attribute];
            else spanElement.innerHTML = resultList[attribute];
        }
    }
}


/*
 * CATALOG VIEW : INSTANCE PICKER
 */

function cv_ip_ctDropdownChanged() {
    var selectedProductInstanceGS = document.getElementById('cv_ip_productInstance_gs').value;
    var selectedProductInstanceCT = document.getElementById('cv_ip_productInstance_ct').value;
    var selectedContainer = document.getElementById('cv_ip_productInstance_selected');
    
    selectedContainer.innerHTML = '&nbsp;'
    cv_ip_selectedProductInstanceId = -1;
    cv_ip_selectedProductInstanceOffset = -1;
    if(selectedProductInstanceGS != '' && selectedProductInstanceCT != '') {
        for(var i = 0; i < cv_ip_productInstances.length; ++i) {
            var ithProductInstance = cv_ip_productInstances[i];
            if(selectedProductInstanceCT == (ithProductInstance.teamName + '::::' + ithProductInstance.colorName) && selectedProductInstanceGS == ithProductInstance.gsName) {
                cv_ip_selectedProductInstanceOffset = i;
                cv_ip_selectedProductInstanceId = ithProductInstance.id;
                cv_ip_updateSelectedContainer();
                cv_cvip_setColorTeam(selectedProductInstanceCT.split('::::')[1], selectedProductInstanceCT.split('::::')[0]);
            }
        }
    }
    cv_ip_updateSelectedContainer();
}

function cv_ip_updateSelectedContainer() {
    var addButton = document.getElementById('cv_ip_productInstance_add');
    var selectedProductInstanceGS = document.getElementById('cv_ip_productInstance_gs').value;
    var selectedProductInstanceCT = document.getElementById('cv_ip_productInstance_ct').value;
    var quantityValue = '';
    
    for(var i = 0; i < cv_ip_quantity.value.length; ++i) {
        if(cv_ip_quantity.value.charAt(i) <= '9' && cv_ip_quantity.value.charAt(i) >= '0')
            quantityValue += cv_ip_quantity.value.charAt(i);
    }
    cv_ip_quantity.value = quantityValue;
    var selectedContainer = document.getElementById('cv_ip_productInstance_selected');
    if(selectedProductInstanceGS == '' || selectedProductInstanceCT == '' || cv_ip_selectedProductInstanceOffset == -1 || quantityValue == '' || quantityValue == '0' || quantityValue == '00' || quantityValue == '000') {
        selectedContainer.innerHTML = '';
        disableLinkButton(addButton);
    } else {
        var productInstance = cv_ip_productInstances[cv_ip_selectedProductInstanceOffset];
        if(productInstance.sell) {
            selectedContainer.innerHTML = '@ ' + formatMoney(productInstance.price) + '/each = ' + formatMoney(productInstance.price * cv_ip_quantity.value);
            enableLinkButton(addButton);
        }
        else {
            selectedContainer.innerHTML = 'Selection Unavailable';
            disableLinkButton(addButton);
        }
    }
}

function cv_ip_gsDropdownPopulate() {
    var gsDropdown = document.getElementById('cv_ip_productInstance_gs');
    var ctDropdown = document.getElementById('cv_ip_productInstance_ct');
    
    var possibleGSs = Array();
    for(var i = 0; i < cv_ip_productInstances.length; ++i) possibleGSs[cv_ip_productInstances[i].gsName] = true;
    
    fixDropdownValues(gsDropdown, possibleGSs);
    ctDropdown.disabled = true;
    cv_ip_updateSelectedContainer();
    
    // on the initial loading, ONLY, we should check to see if there is only one gender .. and if so .. select it
    if(gsDropdown.options.length == 2) {
        gsDropdown.value = gsDropdown.options[1].value;
        cv_ip_gsDropdownChanged();
    }
}

function cv_ip_gsDropdownChanged() {
    var ctDropdown = document.getElementById('cv_ip_productInstance_ct');
    var selectedProductInstanceGS = document.getElementById('cv_ip_productInstance_gs').value;
    var addButton = document.getElementById('cv_ip_productInstance_add');
    
    if(selectedProductInstanceGS == '') {
        ctDropdown.disabled = true;
    }
    else {
        ctDropdown.disabled = false;
        var possibleCTs = new Array();
        var disabledCTs = new Array();
        for(var i = 0; i < cv_ip_productInstances.length; ++i) {
            var ithProductInstance = cv_ip_productInstances[i];
            if(selectedProductInstanceGS == cv_ip_productInstances[i].gsName)  {
                possibleCTs[ithProductInstance.teamName + '::::' + ithProductInstance.colorName] = true;
                if(!ithProductInstance.sell)
                    disabledCTs[ithProductInstance.teamName + '::::' + ithProductInstance.colorName] = true;
            }
        }
        
        fixDropdownValues(ctDropdown, possibleCTs, disabledCTs);
        cv_ip_ctDropdownChanged();
    }
    cv_ip_updateSelectedContainer();
    
    // on the change of the gs dropdown, if the new color dropdown only reveals one option, it can be selected.
    if(ctDropdown.options.length == 2) {
        ctDropdown.value = ctDropdown.options[1].value;
        setTimeout(function() { cv_ip_ctDropdownChanged(); }, 100);
    }
}


/*
 * CATALOG VIEW : COLOR VIEW IMAGE AND PICKER
 */
 
function cv_cvip_moreViews(productId) {
    window.open('catalog_viewAlternate.aspx?i=' + productId, '', 'width=600,height=500');
}

function cv_cvip_loadSwatches() {
    var innerHtml = '';

    for(var i = 0; i < cv_cvip_colorViews.length; ++i) {
        var ithColorView = cv_cvip_colorViews[i];
        innerHtml += ' <a href="javascript:cv_cvip_setActive(' + i + ')" id="coreContentDetailProductFeaturesPicker_colorList_' + i + '" class="Inactive">'
                  + '<img src="' + (ithColorView.swatchImage ? ithColorView.swatchImage : (ithColorView.colorRgbTriplet ? cv_cvip_colorViews_transparent : cv_cvip_colorViews_swatchMissing))
                  + '" title="' + (ithColorView.swatchImage ? (ithColorView.colorName + ' color swatch') : ('No color swatch for ' + ithColorView.colorName + ' is available'))
                  + '" width="17" height="17" alt="[' + ithColorView.colorName + ']" ' + (ithColorView.colorRgbTriplet ? (' style="background-color: #' + ithColorView.colorRgbTriplet + ';"') : '') + ' /></a> ';
    }
    cv_cvip_colorListSpan.innerHTML = innerHtml + '<br />';
}

function cv_cvip_noSwatches() {
    cv_cvip_colorListSpan.innerHTML = cv_cvip_featuredColorSpan.innerHTML = '&mdash;';
    disableLinkButton(cv_cvip_zoomLink);
}

function cv_cvip_setColorTeam(color, team) {
    for(var i = 0; i < cv_cvip_colorViews.length; ++i) {
        var ithColorView = cv_cvip_colorViews[i];
        if(ithColorView.colorName == color && ithColorView.teamName == team) {
            cv_cvip_setActive(i);
            return;
        }
    }
    
    // unsuccessful finding a matching color view
    for(var i = 0; i < cv_cvip_colorViews.length; ++i) {
        var ithImg = document.getElementById('coreContentDetailProductFeaturesPicker_colorList_' + i);
        if(ithImg) ithImg.className = 'Inactive';
    }
    cv_cvip_viewImg.src = cv_cvip_colorViews_detailMissing;
    cv_cvip_viewImg.alt = '[Color View Unavailable]';
    cv_cvip_viewImg.title = 'No views of product are available.';
    cv_cvip_featuredColorSpan.innerHTML = '&mdash;';
    disableLinkButton(cv_cvip_zoomLink);
    cv_cvip_currentOffset = -1;
}

function cv_cvip_setActive(offset) {
    for(var i = 0; i < cv_cvip_colorViews.length; ++i) {
        var ithImg = document.getElementById('coreContentDetailProductFeaturesPicker_colorList_' + i);
        if(ithImg) ithImg.className = (i == offset) ? 'Active' : 'Inactive';
    }
    
    cv_cvip_zoomLink.href = "javascript:cv_cvip_setDetail()";
    cv_cvip_zoomImg.src = cv_cvip_zoomImg.src.replace('detailViewOut', 'detailViewIn');
    
    cv_cvip_currentOffset = offset;
    var newColorView = cv_cvip_colorViews[offset];
    if(newColorView.detailImage) {
        cv_cvip_viewImg.src = newColorView.detailImage;
        cv_cvip_viewImg.alt = '[View of ' + newColorView.colorName + ']';
        cv_cvip_viewImg.title = 'Product in the ' + newColorView.colorName + ' color';        
    }
    else {
        cv_cvip_viewImg.src = cv_cvip_colorViews_detailMissing;
        cv_cvip_viewImg.alt = '[Color View Unavailable]';
        cv_cvip_viewImg.title = 'No normal view of product in the ' + newColorView.colorName + ' color is available.';
    }
    cv_cvip_featuredColorSpan.innerHTML = newColorView.colorName + (newColorView.teamName != '' ? (' (' + newColorView.teamName + ')') : '');
    
    // only allow zooming if the product has a zoom view
    if(newColorView.zoomImage) enableLinkButton(cv_cvip_zoomLink);
    else disableLinkButton(cv_cvip_zoomLink);
}

function cv_cvip_setDetail() {
    if(cv_cvip_currentOffset == -1) return;
    
    var newColorView = cv_cvip_colorViews[cv_cvip_currentOffset];
    if(newColorView.zoomImage) {
        cv_cvip_viewImg.src = newColorView.zoomImage;
        cv_cvip_zoomImg.src = cv_cvip_zoomImg.src.replace('detailViewIn', 'detailViewOut');
        cv_cvip_viewImg.alt = '[Detailed view of ' + newColorView.colorName + ']';
        cv_cvip_viewImg.title = 'Product in the ' + newColorView.colorName + ' color, detail';
        cv_cvip_zoomLink.href = "javascript:cv_cvip_setActive(cv_cvip_currentOffset)";
    }
    else {
        cv_cvip_viewImg.src = cv_cvip_colorViews_detailMissing;
        cv_cvip_viewImg.alt = '[Detailed View Unavailable]';
        cv_cvip_viewImg.title = 'No detailed in view of product in the ' + newColorView.colorName + ' color is available.';
    }
}


/*
 * CATALOG VIEW : SUPPLEMENTAL INFORMATION TAB BOX
 */

// This implemented to expand to the height of the tallest element. I can write the other way, too, if needed, by marking
// the height of the activated box height and setting the container to it. - Dave

// TODO. If we can do some sort of visual effect to draw the user to this part of the screen when the tab switches, that
// would be beneficial for when the page is too short to scroll.
var cv_supplemental_boxHeight_set = false;
function cv_supplemental_activate(section) {
    var tabLine = document.getElementById('cv_supplemental_tabs');
    var tabs = tabLine.getElementsByTagName('a');
    var desiredTabId = 'cv_supplemental_' + section + '_tab';
    for(var i = 0; i < tabs.length; ++i) {
        var ithTab = tabs[i];
        if(ithTab.className == 'Button') {
            if(ithTab.id == desiredTabId) disableLinkButton(ithTab);
            else enableLinkButton(ithTab);
        }
    }
    
    var boxContainer = document.getElementById('cv_supplemental_boxes');
    var boxes = boxContainer.getElementsByTagName('div');
    var desiredBox = 'cv_supplemental_' + section + '_box';
    var maximumHeight = 0;
    for(var i = 0; i < boxes.length; ++i) {
        var ithBox = boxes[i];
        if(ithBox.className == 'TabBox') {
            maximumHeight = Math.max(maximumHeight, ithBox.offsetHeight);
            ithBox.style.position = 'absolute';
            ithBox.style.visibility = desiredBox == ithBox.id ? 'visible' : 'hidden';
        }
    }
    
    if(!cv_supplemental_boxHeight_set) { 
        var newHeight = '' + (maximumHeight + 5 + 5 + 10 /*padding on the box plus some space for the link*/) + 'px';
        boxContainer.style.height = newHeight;
        for(var i = 0; i < boxes.length; ++i) {
            var ithBox = boxes[i];
            if(ithBox.className == 'TabBox')
                ithBox.style.height = newHeight;
        }
        cv_supplemental_boxHeight_set = true;
    }
}

function cv_supplemental_collapseTech(collapseBoolean) {
    var techBox = document.getElementById('cv_supplemental_tech_box');
    var spans = techBox.getElementsByTagName('span');
    var noData = true;
    for(var i = 0; i < spans.length; ++i)
        if(spans[i].className == 'Description') {
            spans[i].style.display = collapseBoolean ? 'none' : 'inline';
            noData = false;
        }
    if(noData)
        return;
    
    var toggleLink = document.getElementById('cv_supplemental_tech_box_toggle');
    var toggleLinkTop = document.getElementById('cv_supplemental_tech_box_toggleTop');
    
    if(!toggleLink) {
        toggleLink = document.createElement('a');
        toggleLink.className = 'StickyLink';
        toggleLink.id = 'cv_supplemental_tech_box_toggle';
        techBox.appendChild(toggleLink);
    }
    if(!toggleLinkTop) {
        toggleLinkTop = document.createElement('a');
        toggleLinkTop.className = 'StickyLinkTop';
        toggleLinkTop.id = 'cv_supplemental_tech_box_toggleTop';
        techBox.insertBefore(toggleLinkTop, document.getElementById('cv_supplemental_tech_box_ul'));
    }
    
    toggleLinkTop.href =  toggleLink.href = 'javascript:cv_supplemental_collapseTech(' + (collapseBoolean ? 'false' : 'true') + ')';
    toggleLinkTop.innerHTML = toggleLink.innerHTML = collapseBoolean ? 'Show More' : 'Hide Details';
}
