﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="Common.js" />
/// <reference name="MicrosoftAjax.js" />
/// <reference path="../Services/ProductService.asmx" />
var _product;
var _availableProducts;
var _availableMultiMapBookProducts;
var _availableMultiDigitalMapProducts;
var _price;
var _defaultdigitalsize     = "48x64";
var _wallmapformat          = 2;
var _mapbookformat          = 3;
var _digitalmapformat       = 4;
var _reportmapformat        = 5;

var _countycoveragelevel    = 1;
var _metroareacoveragelevel = 2;
var _usacoveragelevel       = 3;
var _statecoveragelevel     = 8;
var _citycoveragelevel      = 10;

var _locationofcart         = "/cart/";
var _ERROR                  = false;
var _ERROR_MESSAGE          = "";
var _OK_CART                = false;
var _totalitems             = 0;

var _PremiumExampleImage;
var _PremiumCartoImage;
var _ColorCastExampleImage;
var _ColorCastCartoImage;
var _RedLineExampleImage;
var _RedLineCartoImage;
var _BasicExampleImage;
var _BasicCartoImage;
var _PremiumNoRingImage;
var _ColorCastNoRingImage;
var _RedLineNoRingImage;
var _BasicNoRingImage;
var _buttonHTML;
var _splittesting = false;

var PORTRAIT                        = 0;
var LANDSCAPE                       = 1;

var _imageOrientation               = new Array();
var _streetDetailDescription        = ({ ""             : "Select Street & Highway Detail",
                                         "allstreets"   : "Full Streets & Highways",
                                         "majorstreets" : "Major Streets & Highways",
                                         "highways"     : "Highways Only",
                                         "nohighways"   : "Without Highways" });

function setProduct(val) {
    _product = val;
}

Array.prototype.getProductBySize = function(size) {
    for(var i = 0; i < this.length; i++) {
        if(this[i].Size == size)
            return this[i];
    }
}

function indexOf(array, item) {
    for (var i = 0; i < array.length; i++)
        if (array[i] == item)
            return i;
            
    return -1;
}

function toCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

$(function() {
    ProductService.GetCurrentProduct(
        function(product) {
            //  return a null from the server to refresh the client side
            if (product == null) {
                window.location.reload(true);
                return;
            }

            setProduct(product);

            if (location.href.indexOf('/basic/') != -1) {
                SetBasicImages();
            } else if (location.href.indexOf('/red-line/') != -1) {
                SetRedLineImages();
            } else if (location.href.indexOf('/colorcast/') != -1) {
                SetColorCastImages();
            } else {
                SetPremiumImages();
            }

            ProductService.GetAvailableProducts(_product,
                function(availableProducts) {
                    _availableProducts = availableProducts;

                    //  update the sizes available for the map
                    UpdateSizes();

                    //  add the boundaries available for the map coverage level
                    UpdateBoundaries();

                    //  update the prices for the map
                    UpdatePrices();

                    //  check for multiformat product page
                    if ($("#multiformatproductpage").length > 0) {
                        UpdateMultiStreetDetail();

                        UpdateMultiWallMapSizes();

                        if ($("#wallmaplinkspricematrix").length > 0) {
                            $("span[name='addtocartmatrixlink']").click(AddWallMapLinkToCart);

                            //  multi format add to cart
                            $("#MultiDigitAddToCartButton").click(function() {
                                //  check for anything selected, before showing the button change
                                if ($("input[type=checkbox]:checked,input[name=digitalfiletype][id!=nofiletype]:checked").length > 0) {
                                    $(this).parent().parent().html("<div style=\"height: 24px; font-style: italic;\">Adding to cart... Please wait.</div>");
                                    MultiAddItemToCart();
                                    return false;
                                } else {
                                    alert("Please select the items you want added to your cart.");
                                }
                            });

                            $("div[id^='addtocartlink-mapbook']").click(AddMapBookLinkToCart);

                        }

                        //  map book format value for the enum
                        _product.MMFormat = _mapbookformat;
                        ProductService.GetAvailableMultiMapBookProducts(_product,
                            function(availableProducts) {
                                _availableMultiMapBookProducts = availableProducts;

                                UpdateMultiMapBooks();
                            });

                        _product.MMFormat = _digitalmapformat;
                        ProductService.GetAvailableMultiDigitalMapProducts(_product,
                            function(availableProducts) {
                                _availableMultiDigitalMapProducts = availableProducts;

                                UpdateMultiDigitalMaps();

                                CheckInstantDownloadAvailability();
                            });

                        UpdateMultiReportMaps();

                        //  hide the street detail for the pod usa maps
                        if (_product.MMCoverageLevel == _usacoveragelevel && _product.IsPOD == true) {
                            if ($(".usastreetdetailoptions").length > 0) {
                                $(".usastreetdetailoptions").css("display", "none");
                            }
                        }
                    } else if ($("#SingleFormatPriceMatrix").length > 0) {
                        SetupSingleFormatStreetSelectionHighlighting();

                        UpdateSingleFormatStreetDetail();

                        UpdatePriceMatrixWallMapSizes();

                        $("span[name='addtocartmatrixlink']").click(AddSingleFormatWallMapToCart);
                    }
                }
            );
        }
    );

    if ($("#MapDigitalComputerTypeList").length > 0) {
        $("#MapDigitalComputerTypeList").append("<option value=\"PC\">PC</option>");
        $("#MapDigitalComputerTypeList").append("<option value=\"Mac\">Mac</option>");
    }

    if ($("#MapDigitalFileDeliveryList").length > 0) {
        $("#MapDigitalFileDeliveryList").append("<option value=\"Download\">Download</option>");
        $("#MapDigitalFileDeliveryList").append("<option value=\"CD-ROM\">CD-ROM</option>");
    }

    //  single format add to cart
    if ($("#AddToCartButton").length > 0) {
        $("#AddToCartButton").click(function() {
            $("#AddToCartButton").parent().html("<em>Adding to cart... Please wait.</em>");
            AddItemToCart();
            return false;
        });
    }

    //  multi format add to cart
    if ($("#MultiAddToCartButton").length > 0) {
        $("#MultiAddToCartButton").click(function() {
            //  check for anything selected, before showing the button change
            if ($("input[type=checkbox]:checked,input[name=digitalfiletype][id!=nofiletype]:checked").length > 0) {
                $("#MultiAddToCartButton").parent().parent().html("<div style=\"height: 24px; font-style: italic;\">Adding to cart... Please wait.</div>");
                MultiAddItemToCart();
                return false;
            } else {
                alert("Please select the items you want added to your cart.");
            }
        });
    }

    //  adds a pointer cursor when the user hovers over an edition swatch example
    function EditionHover(id) {
        $("#" + id).hover(
            function() {
                $(this).css("cursor", "pointer");
            },
            function() {
                $(this).css("cursor", "default");
            }
        );
    }

    if ($("input[name=digitalfiletype]").length > 0) {
        $("input[name=digitalfiletype]").click(EnableDigitalOptions);
    }

    SetupEditionHighlighting();

    //  we only want this to show up on the old multi format page 12/4/09
    if ($("#SingleFormatPriceMatrix").length < 0) {
        SetupStreetSelectionHighlighting();
    }

    //  check if premium edition swatch exists
    if ($("#premiumedition").length > 0) {
        $("#premiumedition").click(
            function() {
                SetPremiumImages();
            });
    }
    if ($("#premiumeditionlink").length > 0) {
        $("#premiumeditionlink").click(
            function() {
                SetPremiumImages();
            });
        EditionHover("premiumeditionlink");
    }

    //  check if colorcast edition swatch exists
    if ($("#colorcastedition").length > 0) {
        $("#colorcastedition").click(
            function() {
                SetColorCastImages();
            });
    }
    if ($("#colorcasteditionlink").length > 0) {
        $("#colorcasteditionlink").click(
            function() {
                SetColorCastImages();
            });
        EditionHover("colorcasteditionlink");
    }

    //  check if red line edition swatch exists
    if ($("#redlineedition").length > 0) {
        $("#redlineedition").click(
            function() {
                SetRedLineImages();
            });
    }
    if ($("#redlineeditionlink").length > 0) {
        $("#redlineeditionlink").click(
            function() {
                SetRedLineImages();
            });
        EditionHover("redlineeditionlink");
    }

    //  check if basic edition swatch exists
    if ($("#basicedition").length > 0) {
        $("#basicedition").click(
            function() {
                SetBasicImages();
            });
    }
    if ($("#basiceditionlink").length > 0) {
        $("#basiceditionlink").click(
            function() {
                SetBasicImages();
            });

        EditionHover("basiceditionlink");
    }

    function ResetEditionStyles() {
        $("#premiumedition").removeClass("editionSelected").addClass("edition");
        $("#basicedition").removeClass("editionSelected").addClass("edition");
        $("#redlineedition").removeClass("editionSelected").addClass("edition");
        $("#colorcastedition").removeClass("editionSelected").addClass("edition");
    }

    //  sets all examples to premium
    function SetPremiumImages() {
        var _radiusRing = $('input:radio[name=RadiusRingDetailList]:checked').val();

        //  radius ring on map has different image
        if (_radiusRing == "withoutradiusring") {
            $("#wallmapimageexample").attr("src", _PremiumNoRingImage);
            _product.ImagePath = _PremiumNoRingImage;
        } else {
            $("#wallmapimageexample").attr("src", _PremiumExampleImage);
            _product.ImagePath = _PremiumExampleImage;
        }

        $("#carto-viewer-iframe").attr("src", _PremiumCartoImage);
        $("#mapbookimageexample").attr("src", "/images/products/map-book-premium-example.jpg");
        //        $("#reportmapimageexample").attr("src", "/images/products/report-maps-premium-example.jpg");
        $("#digitalmapimageexample").attr("src", "/images/products/digital-maps-premium-example.jpg");
        ResetEditionStyles();
        $("#premiumedition").removeClass("edition").addClass("editionSelected");

        if ($("#PremiumRadio").length > 0) {
            $("#PremiumRadio").attr("checked", "checked");
        }
        if ($("#premiumedition").length > 0) {
            $("#premiumedition").attr("checked", "checked");
        }

        $("#MapTitle").html("Premium Style 2009");

        return false;
    }

    //  sets all examples to colorcast
    function SetColorCastImages() {
        var _radiusRing = $('input:radio[name=RadiusRingDetailList]:checked').val();

        //  radius ring on map has different image
        if (_radiusRing == "withoutradiusring") {
            $("#wallmapimageexample").attr("src", _ColorCastNoRingImage);
            _product.ImagePath = _ColorCastNoRingImage;
        } else {
            $("#wallmapimageexample").attr("src", _ColorCastExampleImage);
            _product.ImagePath = _ColorCastExampleImage;
        }

        $("#carto-viewer-iframe").attr("src", _ColorCastCartoImage);
        $("#mapbookimageexample").attr("src", "/images/products/map-book-colorcast-example.jpg");
        //        $("#reportmapimageexample").attr("src", "/images/products/report-maps-colorcast-example.jpg");
        $("#digitalmapimageexample").attr("src", "/images/products/digital-maps-colorcast-example.jpg");
        ResetEditionStyles();
        $("#colorcastedition").removeClass("edition").addClass("editionSelected");

        if ($("#ColorCastRadio").length > 0) {
            $("#ColorCastRadio").attr("checked", "checked");
        }
        if ($("#colorcastedition").length > 0) {
            $("#colorcastedition").attr("checked", "checked");
        }

        $("#MapTitle").html("ColorCast Style 2009");

        return false;
    }

    //  sets all examples to red line
    function SetRedLineImages() {
        var _radiusRing = $('input:radio[name=RadiusRingDetailList]:checked').val();

        //  radius ring on map has different image
        if (_radiusRing == "withoutradiusring") {
            $("#wallmapimageexample").attr("src", _RedLineNoRingImage);
            _product.ImagePath = _RedLineNoRingImage;
        } else {
            $("#wallmapimageexample").attr("src", _RedLineExampleImage);
            _product.ImagePath = _RedLineExampleImage;
        }

        $("#carto-viewer-iframe").attr("src", _RedLineCartoImage);
        $("#mapbookimageexample").attr("src", "/images/products/map-book-red-line-example.jpg");
        //        $("#reportmapimageexample").attr("src", "/images/products/report-maps-red-line-example.jpg");
        $("#digitalmapimageexample").attr("src", "/images/products/digital-maps-red-line-example.jpg");
        ResetEditionStyles();
        $("#redlineedition").removeClass("edition").addClass("editionSelected");

        if ($("#RedLineRadio").length > 0) {
            $("#RedLineRadio").attr("checked", "checked");
        }
        if ($("#redlineedition").length > 0) {
            $("#redlineedition").attr("checked", "checked");
        }

        $("#MapTitle").html("RedLine Style 2009");

        return false;
    }

    //  sets all examples to basic
    function SetBasicImages() {
        var _radiusRing = $('input:radio[name=RadiusRingDetailList]:checked').val();

        //  radius ring on map has different image
        if (_radiusRing == "withoutradiusring") {
            $("#wallmapimageexample").attr("src", _BasicNoRingImage);
            _product.ImagePath = _BasicNoRingImage;
        } else {
            $("#wallmapimageexample").attr("src", _BasicExampleImage);
            _product.ImagePath = _BasicExampleImage;
        }

        $("#carto-viewer-iframe").attr("src", _BasicCartoImage);
        $("#mapbookimageexample").attr("src", "/images/products/map-book-basic-example.jpg");
        //        $("#reportmapimageexample").attr("src", "/images/products/report-maps-basic-example.jpg");
        $("#digitalmapimageexample").attr("src", "/images/products/digital-maps-basic-example.jpg");
        ResetEditionStyles();
        $("#basicedition").removeClass("edition").addClass("editionSelected");

        if ($("#BasicRadio").length > 0) {
            $("#BasicRadio").attr("checked", "checked");
        }
        if ($("#basicedition").length > 0) {
            $("#basicedition").attr("checked", "checked");
        }

        $("#MapTitle").html("Basic Style 2009");

        return false;
    }

    //  checks to see if raidus ring details are on the page, enables them to use
    RadiusRingsDetails();

    if ($("#NewWindow").length > 0) {
        $("#NewWindow").click(function() {
            window.open(this.href);
            return false;
        });
    }
    if ($(".NewWindow").length > 0) {
        $(".NewWindow").click(function() {
            window.open(this.href);
            return false;
        });
    }

    EnableDigitalOptions();

    ProductService.SplitTesting(function(_return) {
        _splittesting = _return;

        if (_splittesting) {
            //SplitTestQuantityBox();
            //SplitTestAddToCartButtonInEachArea();
        }
    });

    //  Paper Map
    AddFinishingOption($(".pmpaper"), $("#pmpaperpopup"), $("#closepaperpopup"));

    //  Laminated Map
    AddFinishingOption($(".pmlaminated"), $("#pmlaminatedpopup"), $("#closelaminatedpopup"));

    //  Synthetic Map
    AddFinishingOption($(".pmsynthetic"), $("#pmsyntheticpopup"), $("#closesyntheticpopup"));

    //  Maps on Rails
    AddFinishingOption($(".pmrails"), $("#pmrailspopup"), $("#closerailspopup"));

    //  Spring Rollers
    AddFinishingOption($(".pmspringrollers"), $("#pmspringrollerspopup"), $("#closespringrollerspopup"));

    //  ReStickers
    AddFinishingOption($(".pmrestickers"), $("#pmrestickerspopup"), $("#closerestickerpopup"));

    //  Mounted on Wood
    AddFinishingOption($(".pmmounted"), $("#pmmountedpopup"), $("#closemountedpopup"));

    //  Framed Map (old Mounted)
    AddFinishingOption($(".pmframed"), $("#pmframedpopup"), $("#closeframedpopup"));

    //  Magnetic Map
    AddFinishingOption($(".pmmagnetic"), $("#pmmagneticpopup"), $("#closemagneticpopup"));

});

function AddMapBookLinkToCart()
{
    var _user = new TrackUser();
    var _items = Array();
    var _element = $(this);
    
    _user.__type = "ProductService+TrackUser";
    _user.WebID = getCookie("WebID");
    _user.SessionID = getCookie("SessionID");
    
    $("input:checked,select,input[type=text]").each(
        function() {
            var _item = new TrackItem({ InputID: $(this).attr("id"), InputValue: $(this).val() });
            
            _item.__type = "ProductService+TrackItem";
            _items.push(_item);
        }
    );

    //  store the data, and fire a callback function
    ProductService.StoreRawData(_user, _items,
        function() {
            AddMapBookLinkToCartFinish(_element);
        },
        function(e) {
            AddMapBookLinkToCartFinish(_element);
        }
    );
}

function AddMapBookLinkToCartFinish(Item)
{
    /// <summary>
    /// Adds the selected map book to the cart.
    /// </summary>
    var _streetdetail               = "";
    var _edition                    = "";
    
    var _mapbooksize                = "";
    var _mapbookquantity            = "";

    //  radius ring on map, by default is without radius ring
    var _radiusring                 = "withoutradiusring";

    //  determine street detail
    if($("input:radio[name=MultiStreetDetailList]").length > 0) {
        _streetdetail = $('input:radio[name=MultiStreetDetailList]:checked').val();        
    }

    //  determine map style/edition
    if($("input:radio[name=editions]").length > 0) {
        _edition = $("input:radio[name=editions]:checked").val();
    }

    //  determines the radius ring detail, if available on the page
    if($('input:radio[name=RadiusRingDetailList]').length > 0) {
        _radiusring = $('input:radio[name=RadiusRingDetailList]:checked').val();
    }
    _mapbooksize = $(Item).attr("val");
    _mapbookquantity = $("#largemapbookquantity").val();
    _mapbookquantity = MultiNullQuantityCheck($("#largemapbookquantity").val());
        
    //  map book format
    _product.MMFormat = _mapbookformat;    
    _totalitems++;
    ProductService.SaveMultiMapBook(_product, _edition, _streetdetail, _mapbooksize, _mapbookquantity, _radiusring,
        function(Success) {
            SendToCart();
        },
        function(Error) {
            SendToCart();
            _ERROR = true;
            _ERROR_MESSAGE += "Error Adding Map Book/s"
        }
    );            
}

function AddWallMapLinkToCart() {
    /// <summary>
    /// Tracks the raw data from the page, that is sent to the cart.
    /// </summary>
    var _user = new TrackUser();
    var _items = Array();
    var _element = $(this);
    
    _user.__type = "ProductService+TrackUser";
    _user.WebID = getCookie("WebID");
    _user.SessionID = getCookie("SessionID");
    
    $("input:checked,select,input[type=text]").each(
        function() {
            var _item = new TrackItem({ InputID: $(this).attr("id"), InputValue: $(this).val() });
            
            _item.__type = "ProductService+TrackItem";
            _items.push(_item);
        }
    );

    //  store the data, and fire a callback function
    ProductService.StoreRawData(_user, _items,
        function() {
            AddWallMapLinkToCartFinish(_element);
        },
        function(e) {
            AddWallMapLinkToCartFinish(_element);
        }
    );
}

function AddWallMapLinkToCartFinish(Item) {
    /// <summary>
    /// Adds the selected item to the cart.
    /// </summary>
    //  wm, mb, dm, rp
    var _streetdetail               = "";
    var _edition                    = "";

    //  wall map
    var _wallmapsize                = "";
    var _wallmapfinishingoption     = "";
    var _wallmapquantity            = 1;
    
    var _radiusring                 = "";
    
    //  determine street detail
    if($("input:radio[name=MultiStreetDetailList]").length > 0) {
        _streetdetail = $('input:radio[name=MultiStreetDetailList]:checked').val();        
    }
    
    //  determine map style/edition
    if($("input:radio[name=editions]").length > 0) {
        _edition = $("input:radio[name=editions]:checked").val();
    }
    
    //  determines the radius ring detail, if available on the page
    if($('input:radio[name=RadiusRingDetailList]').length > 0) {
        _radiusring = $('input:radio[name=RadiusRingDetailList]:checked').val();
    }
    
    //  determine wall map size, finsihing option, and quantity
    if($("#multiwallmappricematrix").length > 0 && $("#wallmapquantity").length > 0) {
        _wallmapquantity = $("#wallmapquantity").val();
        if(_wallmapquantity == null || _wallmapquantity == "" || _wallmapquantity < 0) {
            _wallmapquantity = 1;
        }
    }
    
    if($("#wallmaplinkspricematrix").length > 0) {
        var _finishingAndSize = Item.attr("id");
        var _wallmapfinishingoption = _finishingAndSize.split("-")[0];
        var _wallmapsize = _finishingAndSize.split("-")[1];
        
        _product.MMFormat = _wallmapformat;
        
        if(_wallmapfinishingoption == "SpringRollers")
            _wallmapfinishingoption = "Spring Rollers";
            
        if(_wallmapfinishingoption == "WoodenRails")
            _wallmapfinishingoption = "Wooden Rails";
        
        //alert(_product + "--" + _wallmapfinishingoption + "--" + _wallmapsize + "--" + _edition + "--" + _streetdetail + "--" + _radiusring);
        
        //  submit all options to the server       
        ProductService.SaveMultiWallMap(_product, _wallmapfinishingoption, _wallmapsize, _wallmapquantity, _edition, _streetdetail, _radiusring,
            function(success) {
                window.location = _locationofcart;
                return false;
            },
            function(error) {
                alert(error.get_message());
                alert(error.get_stackTrace());
            }
        );
    }
}


function SplitTestAddToCartButtonInEachArea() {
    /// <summary>
    /// Remove the current add to cart button, then add one to each section, three in total
    /// </summary>
    
    //  Hide the old add to cart button
    $("#MultiAddToCartDiv").hide();
    
    $("#MultiDigitAddToCartDiv").show();
    $("#MultiMapBookAddToCartDiv").show();
    $("#MultiWallMapAddToCartDiv").show();
}

function SplitTestQuantityBox() {
    /// <summary>
    /// This was javascript for a failed split test.
    /// </summary>

    //  Set all values to 0 to start
    $("#wallmapquantity").val("0");
    $("#smallmapbookquantity").val("0");
    $("#largemapbookquantity").val("0");
    $("#digitalquantity").val("0");
    
    //  Wall Map Handling
    $("input[id^='Magnetic'],input[id^='Mounted'],input[id^='SpringRollers'],input[id^='WoodenRails'],input[id^='Laminated']").click( function() {
        if($(this).is(':checked')) {
            $("#wallmapquantity").val("1");
        }
        
        if($("input[id^='Magnetic']:checked,input[id^='Mounted']:checked,input[id^='SpringRollers']:checked,input[id^='WoodenRails']:checked,input[id^='Laminated']:checked").length == 0) {
            $("#wallmapquantity").val("0");
        }
    });
    
    $("#wallmapquantity").keyup( function () {
        if($(this).val() == "0") {
            $("input[id^='Magnetic'],input[id^='Mounted'],input[id^='SpringRollers'],input[id^='WoodenRails'],input[id^='Laminated']").attr("checked", "");
        }
    });
    
    //  Map Book Handling
    $("#smallmapbook,#largemapbook").click( function() {
        if($(this).is(':checked')) {
            $("#" + $(this).attr("id") + "quantity").val("1");
        } else {
            $("#" + $(this).attr("id") + "quantity").val("0");
        }
    });
    
    $("#smallmapbookquantity,#largemapbookquantity").keyup( function() {
        if($(this).val() == "0") {
            $("#" + $(this).attr("id").replace("quantity", "")).attr("checked", "");
        }
        if($(this).val() == "") {
            $("#" + $(this).attr("id").replace("quantity", "")).attr("checked", "");
            $(this).val("0");
        }
    });
       
    //  Digital Map Handling
    $("#pdffiletype,#aifiletype").click( function() {
        if($(this).is(':checked')) {
            $("#digitalquantity").val("1");
        }
    });
    
    $("#nofiletype").click( function() {
        if($(this).is(':checked')) {
            $("#digitalquantity").val("0");
        }
    });
    
    $("#digitalquantity").keyup( function() {
        if($(this).val() == "0") {
            $("#nofiletype").attr("checked", "checked");
        }
    });
}

function SetupEditionHighlighting() {
    var _edtionBoxes = $("#basicedition,#premiumedition,#redlineedition,#colorcastedition");
    
    if(_edtionBoxes.length > 0) {
        _edtionBoxes.mouseover(
            function() {
                if($(this).hasClass("editionSelected")) return;
                
                $(this).addClass("editionHighlighted");
            }
        ).mouseout(
            function() {
                $(this).removeClass("editionHighlighted");
            }
        );
    }
}

function CheckInstantDownloadAvailability() {
    /// <summary>
    /// Checks to see if instant download should be available for the current coverage level / street detail combination
    /// </summary>
    /// <remarks>
    /// Currently allowed combinations to check for:
    ///     State level & (only Highway detail)
    ///     County/City/Metro Area level & (only Full Street detail)
    /// </remarks>
    
    //  Grabs the currently selected street detail levels
    var _streetdetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    var _instantdownloadavailable = false;
    var _covlevel = _product.MMCoverageLevel;
//    var _majorstreets = false;
//    var _fullstreets = false;
//    
    //  See which detail levels download is possibly available for
//    for(var i = 0; i < _availableMultiDigitalMapProducts.length; i++) {
//        for(var j = 0; j < _availableMultiDigitalMapProducts[i].StreetDetails.length; j++) {
//            if(_availableMultiDigitalMapProducts[i].StreetDetails[j].Detail == "allstreets") {
//                _fullstreets = true;
//            } else if (_availableMultiDigitalMapProducts[i].StreetDetails[j].Detail == "majorstreets") {
//                _majorstreets = true;
//            }
//        }
//    }
//    
    //  If the default size for digital download (in wall map version) is not available, turn off instant download ability
    if($("input[id$='" + _defaultdigitalsize + "']").attr("disabled") == true) {
        _instantdownloadavailable = false;
    } else if (_streetdetail != "highways" && _streetdetail != "nohighways") {
        //  If full streets are available, thats the version that is downloadable, major streets will always be available when full streets is
//        if(_fullstreets == true && _streetdetail == "allstreets") {
//            _instantdownloadavailable = true;
//        }
//        
        //  If full streets is not available, and major streets is, and they clicked on major streets, thats the version that is downloadable
//        if(_majorstreets == true && _fullstreets == false && _streetdetail == "majorstreets") {
//            _instantdownloadavailable = true;
//        }
//        
        //  We need a better way to determine the availability...until then this will have to work:
        _instantdownloadavailable = true;
    }
    
    //  State is a special case
    if(_covlevel == _statecoveragelevel && _streetdetail == "highways") {
        _instantdownloadavailable = true;
    }
    
    if(_instantdownloadavailable) {
        $("div[id$='InstantDownloadArea']").css("display", "");
    } else {
        $("div[id$='InstantDownloadArea']").css("display", "none");
    }
}

function SetupStreetSelectionHighlighting() {
    var _combo = $('input:radio[name=MultiStreetDetailList]');
    
    if($("#mmmultiformatproductpage").length <= 0) {
        $(".streetdetailselection").mouseover(
            function() {
                $(this).addClass("streetdetailselectionHighlighted");
            }
        ).mouseout (
            function() {
                $(this).removeClass("streetdetailselectionHighlighted");
            }
        );
        
        $("#AllStreetSelectionBox").click(
            function() {
                if($("#AllStreets").attr("disabled") != "") return;
                
                $("#AllStreets").attr("checked", "checked");
                _combo.parent().removeClass("streetdetailselectionSelected");
                $(this).addClass("streetdetailselectionSelected");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
                            
            }
        );
        
        $("#MajorStreetSelectionBox").click(
            function() {
                if($("#MajorStreets").attr("disabled") != "") return;
            
                $("#MajorStreets").attr("checked", "checked");
                _combo.parent().removeClass("streetdetailselectionSelected");
                $(this).addClass("streetdetailselectionSelected");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
            }
        );
        
        $("#HighwaySelectionBox").click(
            function() {
                if($("#Highways").attr("disabled") != "") return;
                
                $("#Highways").attr("checked", "checked");
                _combo.parent().removeClass("streetdetailselectionSelected");
                $(this).addClass("streetdetailselectionSelected");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
            }
        );
        
        $("#NoHighwaySelectionBox").click(
            function() {
                if($("#NoHighways").attr("disabled") != "") return;
                
                $("#NoHighways").attr("checked", "checked");
                _combo.parent().removeClass("streetdetailselectionSelected");
                $(this).addClass("streetdetailselectionSelected");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
            }
        );
    }
    
    if ($("#mmmultiformatproductpage").length >= 1) {
    
        $("#AllStreets").click(
            function() {
                if($("#AllStreets").attr("disabled") != "") return;
                
                $("#AllStreets").attr("checked", "checked");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
                            
            }
        );
        
        $("#MajorStreets").click(
            function() {
                if($("#MajorStreets").attr("disabled") != "") return;
            
                $("#MajorStreets").attr("checked", "checked");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
            }
        );
        
        $("#Highways").click(
            function() {
                if($("#Highways").attr("disabled") != "") return;
                
                $("#Highways").attr("checked", "checked");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
                
                CheckInstantDownloadAvailability();
            }
        );
        
        $("#NoHighways").click(
            function() {
                if($("#NoHighways").attr("disabled") != "") return;
                
                $("#NoHighways").attr("checked", "checked");
                
                UpdateMultiWallMapSizes();
                UpdateMultiReportMaps();
                // UpdateMultiMapBooks();
                // UpdateMultiDigitalMaps();
            }
        );
    }
}

function EnableDigitalOptions() {
    if($("input[name=digitalfiletype]").length == 0) return;
    
    var _enabled = ($("input[name=digitalfiletype]:checked").val() != "");
    var _elements = $("input[name=digitaldelivery],input[name=pcormac]");
    
    if(_enabled)
        _elements.removeAttr("disabled");
    else
        _elements.attr("disabled", "disabled");
}

function UpdateBoundaries() {
    if($("#MapGeographyList").length > 0) {
        //  Boundaries are based upon the coverage level, therefore we can get away with setting i=0   
        var i = 0;

        //  display the boundary options
        for(var j = 0; j <= _availableProducts[i].BoundaryOptions.length - 1; j++) {
            var _b = _availableProducts[i].BoundaryOptions[j].Boundary;
            $("#MapGeographyList").append("<option value=\"" + _b + "\">" + _b + "</option>");
        }
    }
}


function UpdateSizes() {
    if($("#MapSizeList").length > 0) {
        //  set up the on change event
        $("#MapSizeList").change( function() {
            UpdateFinishingOptions();
            UpdateStreetDetailOptions();
            UpdatePrices();
        });

        //  display the available sizes
        for(var i = 0; i <= _availableProducts.length - 1; i++) {
            var _s = _availableProducts[i].Size;
            
            //  report map only
            if(_product.MMFormat == _reportmapformat && _s == "8.5x11" && _s == "11x17" && _s == "17x22") {
                $("#MapSizeList").append("<option value=\"" + _s + "\">" + _s + " inches</option>");
            }
            
            //  wall map only
            if(_product.MMFormat == _wallmapformat && _s != "8.5x11" && _s != "11x17" && _s != "17x22") {
                $("#MapSizeList").append("<option value=\"" + _s + "\">" + _s + " inches</option>");
            } 
            
            //  everything except report map and wall map
            if (_product.MMFormat != _wallmapformat && _product.MMFormat != _reportmapformat) {
                $("#MapSizeList").append("<option value=\"" + _s + "\">" + _s + " inches</option>");
            }
        }
    }
    
    //  update the finishing options, based on the selected size
    UpdateFinishingOptions();
    
    //  update the street detail options, based on the selected size
    UpdateStreetDetailOptions();
}

function UpdateFinishingOptions() {
    if($("#MapFinishingOptionsList").length > 0) {
        //  set up the on change event
        $("#MapFinishingOptionsList").change( function() {
            UpdatePrices();
        });

        //  grab the selected size
        var _size = $("#MapSizeList option:selected").val();
        
        //  get the product details for a selected size
        var _product = _availableProducts.getProductBySize(_size);
        
        //  remove all previous finsihing options
        $("#MapFinishingOptionsList option").remove();
        
        //  display the avialable finishing options
        for(var i = 0; i <= _product.FinishingOptions.length - 1; i++) {
            var _o = _product.FinishingOptions[i].Option;
            var _od = _o;
            
            //  correctly display a couple options
            if(_o == "Wooden Rails") {
                _od = "...w/ Wooden Rails";
            } else if (_o == "Spring Rollers") {
                _od = "...on Spring Rollers";
            }
            
            $("#MapFinishingOptionsList").append("<option value=\"" + _o + "\">" + _od + "</option>");
        }
    }
}

function UpdateStreetDetailOptions() {
    if($('input:radio[name=StreetDetailList]').length > 0) {
        var _availproduct;
        
        $('.singleformatstreetdetailtablerow').css("display", "inline");
        
        //  set up the on change event
        $('input:radio[name=StreetDetailList]').click( function() {
            UpdatePrices();
        });  

        $('input:radio[name=StreetDetailList]').attr("disabled", "disabled");

        if(_product.MMCoverageLevel == _usacoveragelevel) {
            $('input:radio[name=StreetDetailList][value=nohighways]').attr("checked", "checked");
        } else {
            $('input:radio[name=StreetDetailList][value=highways]').attr("checked", "checked");
        }
        
        //  create a new array for street details to remove
        var _remove = new Array();
    
        //  grab the selected size
        var _size = $("#MapSizeList option:selected").val();
        
        //  get the product details for a selected size
        if(_product.MMFormat == _digitalmapformat) {
            _availproduct = _availableProducts.getProductBySize(_defaultdigitalsize);
        } else {
            _availproduct = _availableProducts.getProductBySize(_size);
        }
        
        //  loop through all of the street detail options       
        for(var i = 0; i <= _availproduct.StreetDetails.length - 1; i++) {
            var _sd = _availproduct.StreetDetails[i].Detail;
            $('input:radio[name=StreetDetailList][value=' + _sd + ']').removeAttr("disabled");
        }
    }
    
    if($('#AllStreets').attr('disabled') && $('#MajorStreets').attr('disabled')){
        $('#singleformatstreetdetailtablerow').css("display", "none");
    
    }
}

function UpdatePrices() {
    if($("#MapQuantityList").length > 0) {
        //  empty the option list first
        $("#MapQuantityList option").remove();
    
        //  grab the selected size
        var _size = $("#MapSizeList option:selected").val();

        //  grab the selected street detail option
        var _streetdetailoption = $('input:radio[name=StreetDetailList]:checked').val();
        
        var _finishingoption = $("#MapFinishingOptionsList option:selected").val();
        
        //  get the product details for a selected size
        var _avialproduct = _availableProducts.getProductBySize(_size);
        
        if(_product.MMFormat == _wallmapformat) {
            _price = _avialproduct.Prices[_finishingoption][_streetdetailoption];
        } else if(_product.MMFormat == _mapbookformat) {
            _price = _avialproduct.Prices[_size][_streetdetailoption];
            
            if(_price > 999.99) {
                $(".singleformatquantitytablerow").html("<td>&nbsp;</td><td colspan=\"2\"><div style=\"line-height: 15px; font-size: 13px; font-weight: bold; color: #000000;\">Please call 1-888-434-6277<br>for pricing information.</div></td>");
            }
        } else if(_product.MMFormat == _digitalmapformat) {
            _price = _avialproduct.Prices[_defaultdigitalsize]
        }
        
        for(var i = 0; i < 10; i++) {
            _q = i + 1;
            _p = _q * _price;
            $("#MapQuantityList").append("<option value=\"" + _q + "\">" + _q + " - " + toCurrency(_p) + "</option>");
        }   
    }
    
    //  for digital prices
    if($("#MapDigitalFileTypeList").length > 0 ) {
        //  empty the option list first
        $("#MapDigitalFileTypeList option").remove()

        //  set the default size
        var _size = _defaultdigitalsize;
        
        //  get the product details for a selected size
        var _avialproduct = _availableProducts.getProductBySize(_size);
        
        var _prices = _avialproduct.Prices[_defaultdigitalsize];
        
        for(var _p in _prices) {
            $("#MapDigitalFileTypeList").append("<option value=\"" + _p + "\">" + _p + " - " + toCurrency(_prices[_p]) + "</option>");
        }        
    }
}

function UpdateMultiStreetDetail() {
    var _combo = $('input:radio[name=MultiStreetDetailList]');
    var _temp;

    if(_combo.length > 0) {
        var _c = 0;
        
        $('input:radio[name=MultiStreetDetailList]').attr("disabled", "disabled");
        
        $('input:radio[name=MultiStreetDetailList][value=highways]').attr("checked", "checked");
        _combo.parent().removeClass("streetdetailselectionSelected");
        
        if($("#mmmultiformatproductpage").length <= 0) {
            $('input:radio[name=MultiStreetDetailList][value=highways]').parent().addClass("streetdetailselectionSelected");
        }
    
        //  loop through all of the street detail options           
        for(var i = 0; i < _availableProducts.length; i++) {
            for(var k = 0; k < _availableProducts[i].StreetDetails.length; k++) {
                var _sd = _availableProducts[i].StreetDetails[k].Detail;
                $('input:radio[name=MultiStreetDetailList][value=' + _sd + ']').removeAttr("disabled");
            }
        }
        
        if($('#AllStreets:enabled,#MajorStreets:enabled,#Highways:enabled,#NoHighways:enabled').length <= 1){
            $('#multiformatstreetdetailtablerow').css("display", "none");
        }
        
        if((_temp = $('#AllStreets:disabled,#MajorStreets:disabled')).length == 2) {
            _temp.parent().css("display", "none");
        }
        
        if((_temp = $('#NoHighways:disabled')).length == 1) {
            _temp.parent().css("display", "none");
        }
        
    }
}

function UpdateMultiWallMapSizes() {
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    var _previouslychecked = new Array();
    var _z = 0; //  count of previously select, specifc to map size
    var _y = 0; //  count of newly available boxes
    var _x = 0; //  count of previously selected boxes

    for(var i = 0; i < _availableProducts.length; i++) {
        var _size = _availableProducts[i].Size
        //  make sure all options are disabled to start with
        for(var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
            _finishingoption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g,'');
            
            if($("#" + _finishingoption + "-" + _size + ":checked").val()) {
                //  add previously checked map to the array
                _previouslychecked[_z] = _finishingoption + "-" + _size;
                //  increment array count
                _z++;
                _x++;
            }
            
            $("#" + _finishingoption + "-" + _size).attr("disabled", "disabled").attr("checked", "");
            $("#" + _finishingoption + "-" + _size).addClass("wallmapmatrixlinkdisabled").removeClass("wallmapmatrixlink");
            $("#" + _finishingoption + "-" + _size + "-span").css("text-decoration", "line-through").css("color", "#acacac");
            $("#" + _size + "-icon").addClass("mapsizeimagefaded");
        }
        
        var _finishingoption = "";
        var _available = false;
        for(var k = 0; k < _availableProducts[i].StreetDetails.length; k++) {
            if(_availableProducts[i].StreetDetails[k].Detail == _streetDetail) {
                _available = true;
            }
            
            if(_available == true) {
                for(var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
                    _finishingoption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g,'');
                    //  remove all of the disabling attributes for the products that exist
                    $("#" + _finishingoption + "-" + _size).removeAttr("disabled");
                    $("#" + _finishingoption + "-" + _size).removeClass("wallmapmatrixlinkdisabled").addClass("wallmapmatrixlink");
                    $("#" + _finishingoption + "-" + _size + "-span").css("text-decoration", "none").css("color", "#000000");
                    $("#" + _size + "-icon").removeClass("mapsizeimagefaded");
                }
                
                //  lets re-check the previously checked, if they're available
                for(var b = 0;  b < _previouslychecked.length; b++) {
                    $("#" + _previouslychecked[b]).attr("checked", "checked");
                    _y++;
                }
            }
            _available = false;
        }
        _previouslychecked = new Array();
        _z = 0;
    }
    //alert("prev: " + _x + "\nnow: " + _y);
    //activate msg box here
//    if(_x > _y) {
//        var _v;
//        _v = _x - _y;
//        $("#wallmapcheckboxalert").show("normal");
//    }
}

function UpdateMultiDigitalMaps() {
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    
    DisableDigitalMaps();
    
    for( var i = 0; i < _availableMultiDigitalMapProducts.length; i++) {
        var _size = _availableMultiDigitalMapProducts[i].Size;
        var _filetype = _availableMultiDigitalMapProducts[i];
        
        if(_size == _defaultdigitalsize) {
            var _available = false;
            
            for(var j = 0; j < _availableMultiDigitalMapProducts[i].StreetDetails.length; j++) {
                if(_availableMultiDigitalMapProducts[i].StreetDetails[j].Detail == _streetDetail) {
                    _available = true;
                }
            }
            
            if(_available == true) {
                EnableDigitalMaps();
                
                var _digitalaiprice = _availableMultiDigitalMapProducts[i].Prices[_defaultdigitalsize]["Adobe AI"]
                var _digitalpdfprice = _availableMultiDigitalMapProducts[i].Prices[_defaultdigitalsize]["Adobe PDF"]
                
                $("#digitalpdfprice").html(toCurrency(_digitalpdfprice));
                $("#digitalaiprice").html(toCurrency(_digitalaiprice));
            }
        }
    }
}

function DisableDigitalMaps() {
    $("#digitalpdfprice").html("Please Call.");
    $("#digitalaiprice").html("Please Call.");

    $("#nodigitalmap").attr("checked", "checked");
    $("#pdffiletype").attr("disabled", "disabled");
    $("#aifiletype").attr("disabled", "disabled");

    EnableDigitalOptions();
}

function EnableDigitalMaps() {
    $("#digitalpdfprice").css("text-decoration", "none");
    $("#digitalaiprice").css("text-decoration", "none");
    
    $("#pdffiletype").attr("disabled", "");
    $("#aifiletype").attr("disabled", "");
    
    EnableDigitalOptions();
}

function UpdateMultiMapBooks() {
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    
    DisableMapBooks();
    
    for(var i = 0; i < _availableMultiMapBookProducts.length; i++) {
        var _size = _availableMultiMapBookProducts[i].Size;
        
        if(_size == "8.5x11" || _size == "11x17") {
            var _finishingoption = "";
            var _available = false;
            for(var k = 0; k < _availableMultiMapBookProducts[i].StreetDetails.length; k++) {
                if(_availableMultiMapBookProducts[i].StreetDetails[k].Detail == _streetDetail) {
                    _available = true;
                }
            }
            if(_available == true) {
                //  remove all of the disabling attributes for the products that exist
                $("#largemapbook").removeAttr("disabled");
                $("#smallmapbook").removeAttr("disabled");
                $("#smallmapbookquantity").removeAttr("disabled");
                $("#largemapbookquantity").removeAttr("disabled");
                
                var _mapbookprice = _availableMultiMapBookProducts[i].Prices[_size]["" + _streetDetail + ""];
                
                //  if the price is greater than our threshold, the database probably doesn't contain a record
                //  for the coverage area map book, thus leaving the default value set(very high)
                if(_size == "11x17") {
                    if(_mapbookprice > 999.99) {
                        $("#largemapbookprice").css("text-decoration", "none");
                        DisableMapBooks();
                    } else {
                        $("#largemapbookprice").css("text-decoration", "none").html(toCurrency(_mapbookprice));
                        $("#multimapbooklargeavail").css("display", "inline");
                        $("#multimapbooklargenotavail").css("display", "none");                        
                    }
                }
                if(_size == "8.5x11") {
                    if(_mapbookprice > 999.99) {
                        $("#smallmapbookprice").css("text-decoration", "none");
                        DisableMapBooks();
                    } else {
                        $("#smallmapbookprice").css("text-decoration", "none").html(toCurrency(_mapbookprice));
                        $("#multimapbooksmallavail").css("display", "inline");
                        $("#multimapbooksmallnotavail").css("display", "none");
                    }
                }
            }
        }
    }
}

function DisableMapBooks() {
    $("#largemapbook").attr("disabled", "disabled").attr("checked", "");
    $("#smallmapbook").attr("disabled", "disabled").attr("checked", "");
    $("#smallmapbookquantity").attr("disabled", "disabled");
    $("#largemapbookquantity").attr("disabled", "disabled");
    $("#largemapbookprice").html("Please Call.");
    $("#smallmapbookprice").html("Please Call.");
    $("#multimapbooksmallavail").css("display", "none");
    $("#multimapbooklargeavail").css("display", "none");
    $("#multimapbooksmallnotavail").css("display", "inline").html("<div style=\"line-height: 15px; font-size: 13px; font-weight: bold; color: #000000;\">Please call<br />1-888-434-6277<br />for pricing information.</div>");
    $("#multimapbooklargenotavail").css("display", "inline").html("<div style=\"line-height: 15px; font-size: 13px; font-weight: bold; color: #000000;\">Please call<br />1-888-434-6277<br />for pricing information.</div>");    
}

function UpdateMultiReportMaps() {
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    
    DisableReportsMaps();
    
    for(var i = 0; i < _availableProducts.length; i++) {
        var _size = _availableProducts[i].Size
        
        if((_size == "8.5x11" && $("#smallreportmap").length > 0) || (_size == "11x17" && $("#largereportmap").length > 0) || (_size == "17x22" && $("#extralargereportmap").length > 0)) {
            var _finishingoption = "";
            var _available = false;
            for(var k = 0; k < _availableProducts[i].StreetDetails.length; k++) {
                if(_availableProducts[i].StreetDetails[k].Detail == _streetDetail) {
                    _available = true;
                }
            }
            if(_available == true) {
                for(var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
                    _finishingoption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g,'');
                    //  remove all of the disabling attributes for the products that exist
                    if(_size == "11x17") {
                        $("#largereportmapprice").css("text-decoration", "none").html(toCurrency(_availableProducts[i].Prices.Laminated["" + _streetDetail + ""]));
                        $("#largereportmapquantity").removeAttr("disabled");
                        $("#largereportmap").removeAttr("disabled");
                        $("#multireportlargeavail").css("display", "inline");
                        $("#multireportlargenotavail").css("display", "none");
                    }
                    if(_size == "8.5x11") {
                        $("#smallreportmapprice").css("text-decoration", "none").html(toCurrency(_availableProducts[i].Prices.Laminated["" + _streetDetail + ""]));
                        $("#smallreportmapquantity").removeAttr("disabled");
                        $("#smallreportmap").removeAttr("disabled");
                        $("#multireportsmallavail").css("display", "inline");
                        $("#multireportsmallnotavail").css("display", "none");
                    }
                }
            }
        }
    }
}

function DisableReportsMaps() {
    $("#largereportmap").attr("disabled", "disabled").attr("checked", "");
    $("#smallreportmap").attr("disabled", "disabled").attr("checked", "");
    $("#smallreportmapquantity").attr("disabled", "disabled");
    $("#largereportmapquantity").attr("disabled", "disabled");
    $("#largereportmapprice").html("Please Call.");
    $("#smallreportmapprice").html("Please Call.");
    $("#multireportsmallavail").css("display", "none");
    $("#multireportlargeavail").css("display", "none");
    $("#multireportsmallnotavail").css("display", "inline").html("<div style=\"line-height: 15px; font-size: 13px; font-weight: bold; color: #000000;\">Please call<br />1-888-434-6277<br />for pricing information.</div>");
    $("#multireportlargenotavail").css("display", "inline").html("<div style=\"line-height: 15px; font-size: 13px; font-weight: bold; color: #000000;\">Please call<br />1-888-434-6277<br />for pricing information.</div>");
}

function RadiusRingsDetails() {
    var _tempedition = "";
    //  this is a radius map
    if($("#WithRadiusRing").length > 0 && $("#WithoutRadiusRing").length > 0) {
        $("#RadiusRing").removeAttr("disabled");
        $("#NoRadiusRing").removeAttr("disabled");
        
        $("#RadiusRing").click( function() {
            if($("input:radio[name=editions]").length > 0) {
                _tempedition = $("input:radio[name=editions]:checked").val();
            }
            if(_tempedition == "premium") {
                $("#wallmapimageexample").attr("src", _PremiumExampleImage);
                _product.ImagePath = _PremiumExampleImage;
            } else if (_tempedition == "colorcast") {
                $("#wallmapimageexample").attr("src", _ColorCastExampleImage);
                _product.ImagePath = _ColorCastExampleImage;
            } else if (_tempedition == "redline") {
                $("#wallmapimageexample").attr("src", _RedLineExampleImage);
                _product.ImagePath = _RedLineExampleImage;
            } else if (_tempedition == "basic") {
                $("#wallmapimageexample").attr("src", _BasicExampleImage);
                _product.ImagePath = _BasicExampleImage;
            }
        });
        
        $("#NoRadiusRing").click( function() {
            if($("input:radio[name=editions]").length > 0) {
                _tempedition = $("input:radio[name=editions]:checked").val();
            }
            if(_tempedition == "premium") {
                $("#wallmapimageexample").attr("src", _PremiumNoRingImage);
                _product.ImagePath = _PremiumNoRingImage;
            } else if (_tempedition == "colorcast") {
                $("#wallmapimageexample").attr("src", _ColorCastNoRingImage);
                _product.ImagePath = _ColorCastNoRingImage;
            } else if (_tempedition == "redline") {
                $("#wallmapimageexample").attr("src", _RedLineNoRingImage);
                _product.ImagePath = _RedLineNoRingImage;
            } else if (_tempedition == "basic") {
                $("#wallmapimageexample").attr("src", _BasicNoRingImage);
                _product.ImagePath = _BasicNoRingImage;
            }
        });
    }
}

function MultiAddItemToCart() {
    var _user = new TrackUser();
    var _items = Array();
    
    _user.__type = "ProductService+TrackUser";
    _user.WebID = getCookie("webUserID");
    _user.SessionID = getCookie("SessionID");
    
    $("input:checked,select,input[type=text]").each(
        function() {
            var _item = new TrackItem({ InputID: $(this).attr("id"), InputValue: $(this).val() });
            
            _item.__type = "ProductService+TrackItem";
            _items.push(_item);
        }
    );
    
    ProductService.StoreRawData(_user, _items,
        function() {
            MultiAddItemToCartFinish();
        },
        function(e) {
            MultiAddItemToCartFinish();
        }
    );
}

function MultiAddItemToCartFinish() {
    //  wm, mb, dm, rp
    var _streetdetail               = "";
    var _edition                    = "";

    //  wall map
    var _wallmapsize                = "";
    var _wallmapfinishingoption     = "";
    var _wallmapquantity            = "";
    
    //  map book
    var _mapbooksize                = "";
    var _mapbookquantity            = "";
    
    //  report map
    var _reportmapsize              = "";
    var _reportmapquantity          = "";
    
    //  digital map
    var _digitalmapfiletype         = "";
    var _digitalmappctype           = "";
    var _digitalmapdeliverymethod   = "";
    var _digitalmapquantity         = "";
    
    //  radius ring on map, by default is without radius ring
    var _radiusring                 = "withoutradiusring";
    
    //  determine street detail
    if($("input:radio[name=MultiStreetDetailList]").length > 0) {
        _streetdetail = $('input:radio[name=MultiStreetDetailList]:checked').val();        
    }
    
    //  determine map style/edition
    if($("input:radio[name=editions]").length > 0) {
        _edition = $("input:radio[name=editions]:checked").val();
    }
    
    //  determines the radius ring detail, if available on the page
    if($('input:radio[name=RadiusRingDetailList]').length > 0) {
        _radiusring = $('input:radio[name=RadiusRingDetailList]:checked').val();
    }
    
    //  determine wall map size, finsihing option, and quantity
    if($("#multiwallmappricematrix").length > 0 && $("#wallmapquantity").length > 0) {
        _wallmapquantity = MultiNullQuantityCheck($("#wallmapquantity").val());           
        for(var i = 0; i < _availableProducts.length; i++) {
            var _size = _availableProducts[i].Size;
            for(var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
                _finishingoption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g,'');
                var _foEnum = _availableProducts[i].FinishingOptions[j].Option;
                if($("#" + _finishingoption + "-" + _size).length > 0) {
                    if($("#" + _finishingoption + "-" + _size + ":checked").val()) {
                        //  wall map format
                        _product.MMFormat = _wallmapformat;
                        //  make call to server, saving the wall map item
                        
                        _totalitems++;
                        
                        ProductService.SaveMultiWallMap(_product, _foEnum, _size, _wallmapquantity, _edition, _streetdetail, _radiusring,
                            function(Success) {
                                SendToCart();
                            },
                            function(Error) {
                                SendToCart();
                                _ERROR = true;
                                _ERROR_MESSAGE += "Error Adding Wall Map/s"
                            }
                        );
                    }
                }
            }
        }
    }
    
    //  determine small map book quantity
    if(($("#smallmapbook").length > 0 && $("#largemapbookquantity").length > 0)) {
        if ($("#smallmapbook:checked").val()) {
            _mapbookquantity = MultiNullQuantityCheck($("#largemapbookquantity").val());
            _mapbooksize = $("#smallmapbook").val();
            //  map book format
            _product.MMFormat = _mapbookformat;
            
            _totalitems++;
            
            ProductService.SaveMultiMapBook(_product, _edition, _streetdetail, _mapbooksize, _mapbookquantity, _radiusring,
                function(Success) {
                    SendToCart();
                },
                function(Error) {
                    SendToCart();
                    _ERROR = true;
                    _ERROR_MESSAGE += "Error Adding Small Map Book/s"
                }
            );            
        }
    }
    
    //  determine large map book quantity
    if($("#largemapbook").length > 0 && $("#largemapbookquantity").length > 0) {
        if ($("#largemapbook:checked").val()) {
            _mapbookquantity = MultiNullQuantityCheck($("#largemapbookquantity").val());
            _mapbooksize = $("#largemapbook").val();
            //  map book format
            _product.MMFormat = _mapbookformat;
            
            _totalitems++;
            
            ProductService.SaveMultiMapBook(_product, _edition, _streetdetail, _mapbooksize, _mapbookquantity, _radiusring,
                function(Success) {
                    SendToCart();
                },
                function(Error) {
                    SendToCart();
                    _ERROR = true;
                    _ERROR_MESSAGE += "Error Adding Large Map Book/s"
                }
            );
        }
    }
    
    //  determine small report map quantity
    if($("#smallreportmap").length > 0 && $("#smallreportmapquantity").length > 0) {
        if($("#smallreportmap:checked").val()) {
            _reportmapquantity = MultiNullQuantityCheck($("#smallreportmapquantity").val());
            _reportmapsize = $("#smallreportmap").val();
            //  wall map format (report map is small wall map)            
            _product.MMFormat = _wallmapformat;
            
            _totalitems++;
            
            ProductService.SaveMultiReportMap(_product, _edition, _streetdetail, _reportmapsize, _reportmapquantity, _radiusring,
                function(Success) {
                    SendToCart();
                },
                function(Error) {
                    SendToCart();
                    _ERROR = true;
                    _ERROR_MESSAGE += "Error Adding Small Report Map/s"
                }
            );            
        }
    }
    
    //  determine large report map quantity
    if($("#largereportmap").length > 0 && $("#largereportmapquantity").length > 0) {
        if($("#largereportmap:checked").val()) {
            _reportmapquantity = MultiNullQuantityCheck($("#largereportmapquantity").val());
            _reportmapsize = $("#largereportmap").val();
            //  wall map format (report map is small wall map)
            _product.MMFormat = _wallmapformat;
            
            _totalitems++;
            
            ProductService.SaveMultiReportMap(_product, _edition, _streetdetail, _reportmapsize, _reportmapquantity, _radiusring,
                function(Success) {
                    SendToCart();
                },
                function(Error) {
                    SendToCart();
                    _ERROR = true;
                    _ERROR_MESSAGE += "Error Adding Large Report Map/s"
                }
            );
        }
    }
    
    //  determine digital map file type, computer compatibility, delivery method, and quantity
    if($("input:radio[name=digitalfiletype]").length > 0 && !$("#nodigitalmap").attr("checked")) {
        _digitalmapfiletype = $("input:radio[name=digitalfiletype]:checked").val();
        _digitalmappctype = $("input:radio[name=pcormac]:checked").val();
        _digitalmapdeliverymethod = $("input:radio[name=digitaldelivery]:checked").val();
        _digitalmapquantity = MultiNullQuantityCheck($("#digitalquantity").val());
        //  digital map format
        _product.MMFormat = _digitalmapformat;
        
        _totalitems++;
        
        ProductService.SaveMultiDigitalMap(_product, _edition, _streetdetail, _digitalmapfiletype, _digitalmappctype, _digitalmapdeliverymethod, _digitalmapquantity, _radiusring,
            function(Success) {
                SendToCart();
            },
            function(Error) {
                SendToCart();
                _ERROR = true;
                _ERROR_MESSAGE += "Error Adding Digital Map/s";
            }
        );
    }    
}

function AddItemToCart() {
    var _user = new TrackUser();
    var _items = Array();
    
    _user.__type = "ProductService+TrackUser";
    _user.WebID = getCookie("webUserID");
    _user.SessionID = getCookie("SessionID");
    
    $("input:checked,select,input[type=text]").each(
        function() {
            var _item = new TrackItem({ InputID: $(this).attr("id"), InputValue: $(this).val() });
            
            _item.__type = "ProductService+TrackItem";
            _items.push(_item);
        }
    );
    
    ProductService.StoreRawData(_user, _items,
        function() {
            AddItemToCartFinish();
        },
        function(e) {
            AddItemToCartFinish();
        }
    );
}

function AddItemToCartFinish() {
    var _size               = "";
    var _finishingoption    = "";
    var _streetdetail       = "";
    var _boundary           = "";
    var _digitaltype        = "";
    var _pctype             = "";
    var _deliverymethod     = "";
    var _quantity           = "1";
    
    if($("#MapSizeList").length > 0) {
        _size = $("#MapSizeList option:selected").val();
    }
    if($("#MapFinishingOptionsList").length > 0) {
        _finishingoption = $("#MapFinishingOptionsList option:selected").val();
    }
    if($('input:radio[name=StreetDetailList]').length > 0) {
        _streetdetail = $('input:radio[name=StreetDetailList]:checked').val();
    }
    if($("#MapGeographyList").length > 0) {
        _boundary = $("#MapGeographyList option:selected").val();
    }
    if($("#MapDigitalFileTypeList").length > 0 ) {
        _digitaltype = $("#MapDigitalFileTypeList option:selected").val();
    }
    if($("#MapDigitalComputerTypeList").length > 0) {
        _pctype = $("#MapDigitalComputerTypeList option:selected").val();
    }
    if($("#MapDigitalFileDeliveryList").length > 0) {
        _deliverymethod = $("#MapDigitalFileDeliveryList option:selected").val();
    }
    if($("#MapQuantityList").length > 0) {
        _quantity = $("#MapQuantityList option:selected").val();
    }
    
    ProductService.SaveProduct(_product, _size, _finishingoption, _streetdetail, _boundary,
                               _digitaltype, _pctype, _deliverymethod, _quantity,
        function(success) {
            //  redirect to the cart on success
            window.location = _locationofcart;
            return false;
        },
        function(error) {
            
        }
    );
}

function SendToCart() {
    _totalitems--;
    if(_totalitems <= 0) {
        location.href = _locationofcart;
        return false;
    }
}

function MultiNullQuantityCheck(quantity) {
    if (quantity == null || quantity == "" || quantity < 0) {
        return 1;
    }
    else {
        return quantity;
    }
}

function AddFinishingOption(Button, PopUp, ClosePopUp) {
    AddClick(Button, PopUp);
    AddCloseButton(ClosePopUp, PopUp);
    AddMouseEvents(Button);
    AddMouseEvents(ClosePopUp);
}

//  Adds effect and positions all finishing option 'learn more' popups
function AddClick(Element, PopUp) {
    Element.click(function() {
        var _element = $(this);
        var _popup = PopUp;

        //  Close all other popups
        var _pmPopUps = $("div[id^='pm']");
        _pmPopUps.slideUp("normal");

        //  UPDATED:  102909 - change the left to include the 130px so the popup didn't overlap other learn more buttons      
        var _spanOffsetTop = 0;
        if (_element[0].tagName == "SPAN") {
            _spanOffsetTop = 25;
        }

        //   this grabs the parent element that the learn more pop ups reside in, this provides a reference point for the positioning
        var _parentelement = $("#multiwallmappricematrix");

        _popup
            .css("top", _element.offset().top + _element.outerHeight(false) + _spanOffsetTop)
            .css("left", _element.offset().left + 130)
            .css("z-index", "100");

        if (_popup.is(":visible")) {
            _popup.slideUp("normal");
        } else {
            _popup.slideDown("normal");
        }
    });
}

//  Adds functionality to the close buttons on the popups
function AddCloseButton(Element, PopUp) {
    Element.click(function() {
        var _popup = PopUp;

        if (_popup.is(":visible")) {
            _popup.slideUp("normal");
        }
    });
}

//  Adds mouse effects for non-link, clickable elements
function AddMouseEvents(Element) {
    Element.mouseover(function() { $(this).css("cursor", "pointer"); });
    Element.mouseout(function() { $(this).css("cursor", "default"); });
}

function UpdateSingleFormatStreetDetail() {
    /// <summary>
    /// Updates the street detail radio button list for single format wall map pages.
    /// </summary>

    //  only allow this to execute if the controls are on the page
    if ($('input:radio[name=SingleStreetDetailList]').length > 0) {
        //  set up click event for street detail radio buttons
        $('input:radio[name=SingleStreetDetailList]').click(function() {
            UpdatePriceMatrixWallMapSizes();
        });

        //  disable all street details to start with
        $('input:radio[name=SingleStreetDetailList]').attr("disabled", "disabled");

        //  assign highways as the default checked option
        $('input:radio[name=SingleStreetDetailList][value=highways]').attr("checked", "checked");
        $('input:radio[name=SingleStreetDetailList][value=highways]').parent().addClass("streetdetailselectionSelected");

        //  loop through the street detail radio buttons and update them
        for (var i = 0; i < _availableProducts.length; i++) {
            for (var k = 0; k < _availableProducts[i].StreetDetails.length; k++) {
                var _sd = _availableProducts[i].StreetDetails[k].Detail;
                $('input:radio[name=SingleStreetDetailList][value=' + _sd + ']').removeAttr("disabled");
            }
        }
    }
}

function UpdatePriceMatrixWallMapSizes() {
    /// <summary>
    /// Toggles the availability of items in the price matrix depending on their street detail/availability.
    /// </summary>

    //  only allow this to execute if the controls are on the page
    if ($('input:radio[name=SingleStreetDetailList]').length > 0) {
        //  the street detail that's currently selected
        var _streetDetail = $('input:radio[name=SingleStreetDetailList]:checked').val();
        var _finishingOption = "";

        //  loop through all the items available
        for (var i = 0; i < _availableProducts.length; i++) {
            //  grab size of current item
            var _size = _availableProducts[i].Size;

            //  disable all options to start with
            for (var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
                //  grab the finishing options of the current item
                _finishingOption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g, '');

                //  grey out the price
                $("#" + _finishingOption + "-" + _size + "-span").css("text-decoration", "line-through").css("color", "#acacac");
                //  disable the link
                $("#" + _finishingOption + "-" + _size).removeClass("wallmapmatrixlink").addClass("wallmapmatrixlinkgreyout");
                $("#" + _finishingOption + "-" + _size).unbind('click', AddSingleFormatWallMapToCart);
                //  fade the column header
                //$("#" + _size + "-icon").addClass("mapsizeimagefaded");
                
            }

            //  not available by default, to prevent an order we can't fill
            var _available = false;

            //  loop through the street details of our products
            for (var k = 0; k < _availableProducts[i].StreetDetails.length; k++) {
                //  if a product has a street detail available that matches the selected street detail turn it on
                if (_availableProducts[i].StreetDetails[k].Detail == _streetDetail) {
                    _available = true;
                }

                //  if the product is available, enable the element on the page
                if (_available == true) {
                    //  loop through the finishing options for the available product
                    for (var j = 0; j < _availableProducts[i].FinishingOptions.length; j++) {
                        _finishingOption = _availableProducts[i].FinishingOptions[j].Option.replace(/\s+/g, '');

                        //  unfade the price
                        $("#" + _finishingOption + "-" + _size + "-span").css("text-decoration", "none").css("color", "#000000");
                        //  enable the link
                        $("#" + _finishingOption + "-" + _size).removeClass("wallmapmatrixlinkgreyout").addClass("wallmapmatrixlink");
                        //  unfade the column header
                        $("#" + _size + "-icon").removeClass("mapsizeimagefaded");
                        //  all elements are available by default, we'll disable unavailable shortly
                        $("#" + _finishingOption + "-" + _size).bind('click', AddSingleFormatWallMapToCart);
                    }
                }

                //  reset availability to false to prevent others from showing that shouldn't
                _available = false;
            }
        }
    }
}

function SetupSingleFormatStreetSelectionHighlighting() {
    /// <summary>
    /// Sets up the highlighting for street detail selections on the single format price matrix product page.
    /// </summary>

    var _combo = $('input:radio[name=SingleStreetDetailList]');

    $(".streetdetailoption").mouseover(
        function() {
            $(this).addClass("streetdetailselectionHighlighted");
        }
    ).mouseout(
        function() {
            $(this).removeClass("streetdetailselectionHighlighted");
        }
    );

    $("#AllStreetSelectionBox").click(
        function() {
            if ($("#AllStreets").attr("disabled") != "") return;

            $("#AllStreets").attr("checked", "checked");
            _combo.parent().removeClass("streetdetailselectionSelected");
            $(this).addClass("streetdetailselectionSelected");

            UpdatePriceMatrixWallMapSizes();
        }
    );

    $("#MajorStreetSelectionBox").click(
        function() {
            if ($("#MajorStreets").attr("disabled") != "") return;

            $("#MajorStreets").attr("checked", "checked");
            _combo.parent().removeClass("streetdetailselectionSelected");
            $(this).addClass("streetdetailselectionSelected");

            UpdatePriceMatrixWallMapSizes();
        }
    );

    $("#HighwaySelectionBox").click(
        function() {
            if ($("#Highways").attr("disabled") != "") return;

            $("#Highways").attr("checked", "checked");
            _combo.parent().removeClass("streetdetailselectionSelected");
            $(this).addClass("streetdetailselectionSelected");

            UpdatePriceMatrixWallMapSizes();
        }
    );

    $("#NoHighwaySelectionBox").click(
        function() {
            if ($("#NoHighways").attr("disabled") != "") return;

            $("#NoHighways").attr("checked", "checked");
            _combo.parent().removeClass("streetdetailselectionSelected");
            $(this).addClass("streetdetailselectionSelected");

            UpdatePriceMatrixWallMapSizes();
        }
    );
}

function AddSingleFormatWallMapToCart() {
    /// <summary>
    /// Tracks the raw data from the page, that is sent to the cart.
    /// </summary>
    var _user = new TrackUser();
    var _items = Array();
    var _element = $(this);

    _user.__type = "ProductService+TrackUser";
    _user.WebID = getCookie("WebID");
    _user.SessionID = getCookie("SessionID");

    $("input:checked,select,input[type=text]").each(
        function() {
            var _item = new TrackItem({ InputID: $(this).attr("id"), InputValue: $(this).val() });

            _item.__type = "ProductService+TrackItem";
            _items.push(_item);
        }
    );

    //  store the data, and fire a callback function
    ProductService.StoreRawData(_user, _items,
        function() {
            AddSingleFormatWallMapToCartFinish(_element);
        },
        function(e) {
            AddSingleFormatWallMapToCartFinish(_element);
        }
    );
}

function AddSingleFormatWallMapToCartFinish(Item) {
    /// <summary>
    /// Adds the selected item to the cart.
    /// </summary>
    var _streetdetail = "";

    //  grab the street detail selected
    if ($('input:radio[name=SingleStreetDetailList]').length > 0) {
        _streetdetail = $("input:radio[name=SingleStreetDetailList]:checked").val();
    }

    if ($("#SingleFormatPriceMatrix").length > 0) {
        var _finishingAndSize = Item.attr("id");
        var _finishingOption = _finishingAndSize.split("-")[0];
        var _size = _finishingAndSize.split("-")[1];

        //  submit all options to the server       
        ProductService.SaveProduct(_product, _size, _finishingOption, _streetdetail, "5 Digit Zip Codes",
                "", "", "", "1",
            function(success) {
                window.location = _locationofcart;
                return false;
            },
            function(error) {

            }
        );
    }
}