﻿//written by Mark Savage for MidwayUSA.com
//this requires jQuery
//www.jQuery.com

var highestSelectedCharacteristicIndex = 0;
var shouldUpdateDisplay = false;
var currentlySelectedCharacteristicIndex = 0;

var $j = jQuery.noConflict();

//as soon as the page is done loading, bind some events
$j(document).ready(function() {
    $j("select[id^='c']")
        .change(function() {
            var characteristicAttributeString = $j(this).val();
          
            shouldUpdateDisplay = attributeIsVisible(characteristicAttributeString);

            updateCharacteristics(characteristicAttributeString);

            //move this into its own function           
            currentlySelectedCharacteristicIndex = $j(this).attr("id").substring(1, 2);

            if (currentlySelectedCharacteristicIndex >= highestSelectedCharacteristicIndex) {
                //nothing                
            }
            else {                              
                $j("#cartButton").html("");
                $j("#quantity").html("");
                $j("#product_wishlist").html("");

                var i = eval(currentlySelectedCharacteristicIndex + 2);

                while (i <= highestSelectedCharacteristicIndex) {
                    $j.ajax({
                        type: "POST",
                        url: "CharacteristicCascade.asmx/GetEmptyCharacteristic",
                        data: "productNumber=" + $j("#productNumber").html() + "&characteristicIndex=" + i,
                        async: false,
                        success: function(htmlResult) {
                            var newCharacteristic = $j(htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue);

                            $j("select[id='c" + i + "']")
                            .html(newCharacteristic);
                        }
                    });
                    i++;
                }
            }

            highestSelectedCharacteristicIndex = currentlySelectedCharacteristicIndex;            
        });

    if ($j("#preselectItem").html() == null && $j("#c0").html() && ($j("#c0").val().length > 1)) {
        updateCharacteristics($j("#c0").val());
    }
});

function displaySaleItem(saleItemXml) {
    var saleItemId = saleItemXml.getElementsByTagName("Id")[0].childNodes[0].nodeValue;
    var currentPrice = "$" + saleItemXml.getElementsByTagName("CurrentPrice")[0].childNodes[0].nodeValue;
    var currentPriceString = saleItemXml.getElementsByTagName("CurrentPriceString")[0].childNodes[0].nodeValue;
    var description = saleItemXml.getElementsByTagName("Description")[0].childNodes[0].nodeValue;
    var productStatus = saleItemXml.getElementsByTagName("ProductStatus")[0].childNodes[0].nodeValue;
    var productStatusId = parseInt(saleItemXml.getElementsByTagName("ProductStatus")[0].childNodes[0].nodeValue);
    var vendorProductNumber = saleItemXml.getElementsByTagName("VendorProductNumber")[0].childNodes[0].nodeValue;
    var availabilityMessage = saleItemXml.getElementsByTagName("AvailabilityMessage")[0].childNodes[0].nodeValue;
    var webLinksString = saleItemXml.getElementsByTagName("WebLinksString")[0].childNodes[0].nodeValue;

    $j("#currentPrice").html(currentPriceString);    
    $j("#productStatus").html(productStatus);
    $j("#vendorProductNumber").html("| Manufacturer #: " + vendorProductNumber);
    $j("#availabilityMessage").html(availabilityMessage);
    $j("#webLinks").html(webLinksString); 

    updateSaleItemImage(saleItemId);
    loadPackageSizeLink(saleItemId);
    loadProductAction();
    loadWishlistLink();
}

function loadRepresentativeSaleItem() {
    $j.ajax({
        type: "POST",
        url: "CharacteristicCascade.asmx/GetSelectedSaleItem",
        data: "productNumber=" + $j("#productNumber").html() + "&randomValue=" + Math.ceil(1000*Math.random()),
        async: false, 
        cache: false,           
        dataType: "xml",
        success: function(saleItemXml) {
            var saleItemId = saleItemXml.getElementsByTagName("Id")[0].childNodes[0].nodeValue;
            
            updateSaleItemImage(saleItemId);                
        }
    });
}

function updateSaleItemImage(saleItemId) {
    $j("#saleItemImage").html("<img src='http://media.midwayusa.com/ProductImages/Medium/" + saleItemId + ".jpg' />");
    $j("#enlargeImage").html("<img src='http://media.midwayusa.com/ProductImages/Large/" + saleItemId + ".jpg' />");
}

function attributeIsVisible(characteristicAttributeString) {
    //bleh - necessary for now since there's no way real way to tell if an attribute affects the product image
    return characteristicAttributeString.search("Color") > -1;
}

function loadSelectedSaleItem() {
    $j.ajax({
        type: "POST",
        url: "CharacteristicCascade.asmx/GetSelectedSaleItem",
        data: "productNumber=" + $j("#productNumber").html() + "&randomValue=" + Math.ceil(1000*Math.random()),
        async: false,
        cache: false,
        dataType: "xml",
        success: function(saleItemXml) {
            displaySaleItem(saleItemXml);
        }
    });
}

function loadNextCharacteristic(htmlResult, characteristicAttributeString) {    
    var newCharacteristicOptions = $j(htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue);
    var nextCharacteristicSelect = $j("select#c" + (parseInt(characteristicAttributeString.substring(0, 1)) + 1));
    var nextCharacteristicMsg = '';

    if (shouldUpdateDisplay) {
        loadRepresentativeSaleItem();
    }

    nextCharacteristicSelect.html(newCharacteristicOptions);

    nextCharacteristicMsg = nextCharacteristicSelect[0].childNodes[0].childNodes[0].nodeValue;

    $j("#productStatus").html("Availability: " + nextCharacteristicMsg);
    $j("#vendorProductNumber").html("| Manufacturer #: " + nextCharacteristicMsg);

    if ($j("select#c" + (parseInt(characteristicAttributeString.substring(0, 1)) + 1) + " > option").length == 1) {
        nextCharacteristicSelect.change();
    }
    
    //var nextCharacteristicSelectHtml = nextCharacteristicSelect.html();
    
//    if (nextCharacteristicSelectHtml.search("Select")) {
//        alert(nextCharacteristicSelect.html());
//    }
}

function loadPackageSizeLink(saleItemId) {
    $j("#packageSize").html("<a href='javascript:openPackageSizeWindow(" + saleItemId + ");' >Package Size</a> <img src='http://www.midwayusa.com/midwayusa/StaticPages/accessories/accessories_images/logos_icons/package.jpg' alt='Package Size' width='20' height='15' align='absmiddle' />");
}

function loadProductAction() {
    $j.ajax({
        type: "POST",
        url: "CharacteristicCascade.asmx/GetProductAction",
        data: "productNumber=" + $j("#productNumber").html(),
        async: false,
        cache: false,
        dataType: "xml",
        success: function(htmlResult) {
            var productActionHtml = htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue;

            //bleh
            if (productActionHtml.search("Add to Cart") > -1) {
                $j("#quantity").html('Quantity<br /><input id="quantityBox" type="text" align="right" name="quantity" maxlength="3" size="3" value="1">');
            }

            $j("#cartButton").html(htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue);                
        }
    });
}

function loadWishlistLink() {
    $j.ajax({
        type: "POST",
        url: "CharacteristicCascade.asmx/GetWishlistLink",
        data: "productNumber=" + $j("#productNumber").html(),
        async: false,
        cache: false,
        dataType: "xml",
        success: function(htmlResult) {
           $j("#productWishList").html(htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue);
        }
    });
}

function updateCharacteristics(characteristicAttributeString) {
    $j.ajax({
        type: "POST",
        url: "CharacteristicCascade.asmx/HelloWorld", //hello, world!
        data: "characteristicAttributeString=" + characteristicAttributeString + "&productNumber=" + $j("#productNumber").html() + "&randomValue=" + Math.ceil(1000 * Math.random()),
        async: false,
        cache: false,
        dataType: "xml",
        success: function(htmlResult) {
            // if there's only one item left, go get it! else, return the next characteristic and attributes
            if (htmlResult.getElementsByTagName("string")[0].childNodes[0].nodeValue == "1") {                                    
                loadSelectedSaleItem();
            }
            else {
                loadNextCharacteristic(htmlResult, characteristicAttributeString);
            }
        }
    });
}