﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />
/// <reference path="Common.js" />
/// <reference name="MicrosoftAjax.js" />
/// <reference path="../Services/ProductService.asmx" />
var _product;
var _countycoveragelevel    = 1;
var _citycoveragelevel      = 10;
var _metrocoveragelevel     = 2;
var _availableProducts;
var _availableMultiMapBookProducts;
var _availableMultiDigitalMapProducts;
var _neighborhoodAvailability = true;
var _price;
var _defaultdigitalsize     = "48x64";
var _wallmapformat          = 2;
var _mapbookformat          = 3;
var _digitalmapformat       = 4;
var _reportmapformat        = 5;

var _usacoveragelevel       = 3;

var _locationofcart         = "/cart/";
var _ERROR                  = false;
var _ERROR_MESSAGE          = "";
var _OK_CART                = false;
var _totalitems             = 0;

var _pagetesting            = false;

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;

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() {

    GetCurrentProduct();
        
    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 && $("#nofiletype").attr("disabled") == "") {
                $("#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.");
            }
        });
    }

    //  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").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.");
            }
        });
    }
        
    //  check if premium edition swatch exists
    if ($("#premiumedition").length > 0 && $("#premiumeditionlink").length > 0) {
        $("#premiumedition").click(
            function() {
                SetPremiumImages();
        });
        $("#premiumeditionlink").click(
            function() {
                SetPremiumImages();
        });
        EditionHover("premiumeditionlink");
    }
    
    //  check if colorcast edition swatch exists
    if ($("#colorcastedition").length > 0 && $("#colorcasteditionlink").length > 0) {
        $("#colorcastedition").click(
            function() {
                SetColorCastImages();
        });
        $("#colorcasteditionlink").click(
            function() {
                SetColorCastImages();
        });
        EditionHover("colorcasteditionlink");
    }
    
    //  check if red line edition swatch exists
    if ($("#redlineedition").length > 0 && $("#redlineeditionlink").length > 0) {
        $("#redlineedition").click(
            function() {
                SetRedLineImages();
        });
        $("#redlineeditionlink").click(
            function() {
                SetRedLineImages();
        });
        EditionHover("redlineeditionlink");
    }
    
    //  check if basic edition swatch exists
    if ($("#basicedition").length > 0 && $("#basiceditionlink").length > 0) {
        $("#basicedition").click(
            function() {
                SetBasicImages();
        });
        $("#basiceditionlink").click(
            function() {
                SetBasicImages();
        });
        EditionHover("basiceditionlink");
    }
    
   
    
    //  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;
        });
    }

    $(".framedplastic").click(function () {
        $('#framedwood_row').parent().parent().css('display', 'none');
        $('#framedexecutive_row').parent().parent().css('display', 'none');
        $('#mount_row').parent().parent().css('display', '');
        DisableFramedExecutiveColors();
        DisableFramedWoodColors();
    });
    $(".framedwood").click(function () {
        DisableFramedExecutiveColors();
        EnabledFramedWoodColors();
    });
    $(".framedexecutive").click(function () {
        EnabledFramedExecutiveColors();
        DisableFramedWoodColors();
    });

    //  Controls the switching of framed maps color types
    $(".framedexecutivedarkoak").click(function () {
        $("#framedexecutivecolorsample").attr("src", "/images/multi-format-product-page/option-framed-dark-oak.jpg");
        $("#framedexecutivetypeimage").attr("src", "/images/multi-format-product-page/pm-framed-executive-dark-oak.jpg");
        $("#framedexecutivetypetext").text("Dark Oak");
        $("form[name$='framedexecutive']'").children("input[name='options']").val("Framed Map with Dark Oak Executive Frame");
    });
    $(".framedexecutivcherrystain").click(function () {
        $("#framedexecutivecolorsample").attr("src", "/images/multi-format-product-page/option-framed-cherry-stained.jpg");
        $("#framedexecutivetypeimage").attr("src", "/images/multi-format-product-page/pm-framed-executive-cherry-stain.jpg");
        $("#framedexecutivetypetext").text("Cherry Stain");
        $("form[name$='framedexecutive']'").children("input[name='options']").val("Framed Map with Cherry Stained Executive Frame");
    });
    $(".framedexecutivelightoak").click(function () {
        $("#framedexecutivecolorsample").attr("src", "/images/multi-format-product-page/option-framed-light-oak.jpg");
        $("#framedexecutivetypeimage").attr("src", "/images/multi-format-product-page/pm-framed-executive-light-oak.jpg");
        $("#framedexecutivetypetext").text("Light Oak");
        $("form[name$='framedexecutive']'").children("input[name='options']").val("Framed Map with Light Oak Executive Frame");
    });
    $(".framedwoodblack").click(function () {
        $("#framedwoodcolorsample").attr("src", "/images/multi-format-product-page/option-framed-black.jpg");
        $("#framedwoodtypeimage").attr("src", "/images/multi-format-product-page/pm-framed-wood-black.jpg");
        $("#framedwoodtypetext").text("Black");
        $("form[name$='framedwood']'").children("input[name='options']").val("Framed Map with Black Wood Frame");
    });
    $(".framedwoodunfinished").click(function () {
        $("#framedwoodcolorsample").attr("src", "/images/multi-format-product-page/option-framed-unfinished.jpg");
        $("#framedwoodtypeimage").attr("src", "/images/multi-format-product-page/pm-framed-wood-unfinished.jpg");
        $("#framedwoodtypetext").text("Unfinished");
        $("form[name$='framedwood']'").children("input[name='options']").val("Framed Map with Unfinished Wood Frame");
    });
    
    //  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"));
    AddFinishingOption($(".pmplasticrails"), $("#pmplasticrailspopup"), $("#closeplasticrailspopup"));
    
    //  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"));

    //  Basic Framed Map
    AddFinishingOption($(".pmframedbasic"), $("#pmframedbasicpopup"), $("#closeframedbasicpopup"));

    //  Executive Framed Map
    AddFinishingOption($(".pmframedexecutive"), $("#pmframedexecutivepopup"), $("#closeframedexecutivepopup"));

    //  Framed Maps - Select Frame Type and Color
    AddSelectionOption($(".framedbasictypebutton"), $(".framedbasicselectionpopup"), $(".closeframedbasicselectionpopup"));

    AddSelectionOption($(".framedexecutivetypebutton"), $(".framedexecutiveselectionpopup"), $(".closeframedexecutiveselectionpopup"));

    AddSelectionOption($("#framedwoodtypetext"), $(".framedbasicselectionpopup"), $(".closeframedbasicselectionpopup"));

    AddSelectionOption($("#framedexecutivetypetext"), $(".framedexecutiveselectionpopup"), $(".closeframedexecutiveselectionpopup"));

    $("#aifiletype, #pdffiletype").click(ToggleInstantDownloadImage);    
});

 //  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/multi-format-product-page/premium_style_report_maps.jpg");
        $("#digitalmapimageexample").attr("src", "/images/multi-format-product-page/premium_style_digital_maps.jpg");
        $("#premiumedition").attr("checked", "checked");
        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/multi-format-product-page/colorcast_style_report_maps.jpg");
        $("#digitalmapimageexample").attr("src", "/images/multi-format-product-page/colorcast_style_digital_maps.jpg");
        $("#colorcastedition").attr("checked", "checked");
        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/multi-format-product-page/redline_style_report_maps.jpg");
        $("#digitalmapimageexample").attr("src", "/images/multi-format-product-page/redline_style_digital_maps.jpg");
        $("#redlineedition").attr("checked", "checked");
        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/multi-format-product-page/map-books-example.jpg");
        $("#reportmapimageexample").attr("src", "/images/multi-format-product-page/basic_style_report_maps.jpg");
        $("#digitalmapimageexample").attr("src", "/images/multi-format-product-page/basic_style_digital_maps.jpg");
        $("#basicedition").attr("checked", "checked");
        return false;
    }

    function ShowExtendedMatrix() {
        $(".otherfinishoptionsheader .intro").hide();
        $(".otherfinishoptionsheader .extended").show();
        $(".otherfinishoptionsmatrix").show();
    }

    function HideExtendedMatrix() {
        $(".otherfinishoptionsmatrix").hide();
        $(".otherfinishoptionsheader .extended").hide();
        $(".otherfinishoptionsheader .intro").show();
    }

    //  Disables radio buttons for framed executive map colors
    function DisableFramedExecutiveColors() {
        $(".framedexecutivedarkoak").attr("disabled", "disabled");
        $(".framedexecutivcherrystain").attr("disabled", "disabled");
        $(".framedexecutivelightoak").attr("disabled", "disabled");
    }

    //  Enables radio buttons for framed executive map colors
    function EnabledFramedExecutiveColors() {
        $(".framedexecutivedarkoak").attr("disabled", "");
        $(".framedexecutivcherrystain").attr("disabled", "");
        $(".framedexecutivelightoak").attr("disabled", "");
    }

    //  Disables radio buttons for framed wood map colors
    function DisableFramedWoodColors() {
        $(".framedwoodblack").attr("disabled", "disabled");
        $(".framedwoodunfinished").attr("disabled", "disabled");
    }

    //  Enables radio buttons for framed wood map colors
    function EnabledFramedWoodColors() {
        $(".framedwoodblack").attr("disabled", "");
        $(".framedwoodunfinished").attr("disabled", "");
    }

function CheckStyleButton(product)
{
    if (product.MMEdition == 1)
    {
        $("#premiumedition").attr("checked", "checked");
        SetPremiumImages();
    }
    else if (product.MMEdition == 2)
    {
        $("#colorcastedition").attr("checked", "checked");
        SetColorCastImages();
    }
    else if (product.MMEdition == 5)
    {
        $("#redlineedition").attr("checked", "checked");
        SetRedLineImages();
    }
    else if (product.MMEdition == 6)
    {
        $("#basicedition").attr("checked", "checked");
        SetBasicImages();
    }
}

//  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");
            }
        );
}

function GetCurrentProduct() {
    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);
            
            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();
                        
                        //  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();
                        });
                        
                        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");
                            }
                        }          
                        
                        CheckStyleButton(_product);              
                    } else if ($("#SingleFormatPriceMatrix").length > 0) {
                        SetupStreetSelectionHighlighting();
                    
                        UpdateSingleFormatStreetDetail();
                        
                        UpdatePriceMatrixWallMapSizes();
                        
                        $("span[name='addtocartmatrixlink']").click(AddSingleFormatWallMapToCart);
                    }
                }
            );
        }
    );
}

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") {
                //  default display size of 48x64, the result of a successfull split test finished on 11/16/09
                if(_s == "48x64") {
                    $("#MapSizeList").append("<option value=\"" + _s + "\" selected>" + _s + " inches</option>");
                } else {
                    $("#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) {
                $("#ctl00_ctl00_body_bodycontent_ProductOptionsControl_QuantityRow").hide();
                $("#ctl00_ctl00_body_bodycontent_ProductOptionsControl_ErrorRow").show();
            }
            else
            {
                $("#ctl00_ctl00_body_bodycontent_ProductOptionsControl_ErrorRow").hide();
                $("#ctl00_ctl00_body_bodycontent_ProductOptionsControl_QuantityRow").show()
            }

        } 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() {
    if($('input:radio[name=MultiStreetDetailList]').length > 0) {
        //  set up the on change event
        $('input:radio[name=MultiStreetDetailList]').click( function() {
            UpdateMultiWallMapSizes();
            UpdateMultiReportMaps();
            UpdateMultiMapBooks();
            UpdateMultiDigitalMaps();
        });  
        
        $('input:radio[name=MultiStreetDetailList]').attr("disabled", "disabled");
        
        
        $('input:radio[name=MultiStreetDetailList][value=highways]').attr("checked", "checked");
    
        //  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");
            }
        }
    }
}

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 + "-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 + "-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;
    }
}

function UpdateMultiDigitalMaps() {
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();
    
    DisableDigitalMaps();

    var _isAI = $("#aifiletype").is(":checked");

    var _available = DetermineInstantDownloadAvailability();

    if(_available == true) 
    {
        EnableDigitalMaps();
                
        ToggleInstantDownloadImage();
    }

    if (_neighborhoodAvailability == false) {
        DisableDigitalMaps();
    }
}

function DetermineInstantDownloadAvailability()
{
    var _available = false;
    var _streetDetail = $('input:radio[name=MultiStreetDetailList]:checked').val();

     for( var i = 0; i < _availableMultiDigitalMapProducts.length; i++) 
     {
        var _size = _availableMultiDigitalMapProducts[i].Size;
        var _filetype = _availableMultiDigitalMapProducts[i];

        if (_size == "48x64")
        {
            for(var j = 0; j < _availableMultiDigitalMapProducts[i].StreetDetails.length; j++) 
            {
                if(_availableMultiDigitalMapProducts[i].StreetDetails[j].Detail == _streetDetail) 
                {
                    _available = true;

                    var _digitalaiprice = _availableMultiDigitalMapProducts[i].Prices["48x64"]["Adobe AI"]
                    var _digitalpdfprice = _availableMultiDigitalMapProducts[i].Prices["48x64"]["Adobe PDF"]
                
                    $("#digitalpdfprice").html(toCurrency(_digitalpdfprice));
                    $("#digitalaiprice").html(toCurrency(_digitalaiprice));
                }
            }
        }
    }

    return _available;
}

function ToggleInstantDownloadImage()
{
    var StreetDetail =  $('input:radio[name=MultiStreetDetailList]:checked').val();
    var IsAdobeIllustrator = $("#aifiletype").is(":checked");

	$("#AvailableForInstant").hide();
	$("#DownloadImage").show();
		
    if (!IsAdobeIllustrator)
    {	
        switch (_product.MMCoverageLevel)
        {
            case 1: //county
			case 2: //metro
			case 10: //city
                if (StreetDetail == "majorstreets")
                {
                    ShowInstantDownload();
                }
                break;
            case 8: //state
                ShowInstantDownload();
                break;
        }
    }
}

function ShowInstantDownload()
{
	$("#AvailableForInstant").show();
	$("#DownloadImage").hide();
}

function HideInstantDownload()
{
	$("#AvailableForInstant").hide();
}

function DisableDigitalMaps() {
    $("#digitalquantity").attr("disabled", "disabled");
    $("#digitalcdrom").attr("disabled", "disabled");
    $("#digitaldownload").attr("disabled", "disabled").attr("checked", "");
    $("#mac").attr("disabled", "disabled");
    $("#pc").attr("disabled", "disabled").attr("checked", "");
    $("#nofiletype").attr("disabled", "disabled");
    $("#aifiletype").attr("disabled", "disabled");
    $("#pdffiletype").attr("disabled", "disabled");
    $("#digitalpdfprice").html("Please Call.");
    $("#digitalaiprice").html("Please Call.");
	
	HideInstantDownload();
}

function EnableDigitalMaps() {
    $("#digitalquantity").removeAttr("disabled");
    $("#digitalcdrom").removeAttr("disabled");
    $("#digitaldownload").removeAttr("disabled").attr("checked", "checked");
    $("#mac").removeAttr("disabled");
    $("#pc").removeAttr("disabled").attr("checked", "checked");
    $("#nofiletype").removeAttr("disabled");
    $("#aifiletype").removeAttr("disabled");
    $("#pdffiletype").removeAttr("disabled");
    $("#digitalpdfprice").css("text-decoration", "none");
    $("#digitalaiprice").css("text-decoration", "none");
}

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");
                    }
                }
            }
        }
    }
    if (_neighborhoodAvailability == false) {
        DisableMapBooks();
    }
}

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" && $("#reportMap17x22").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 == "17x22") {
                        $("#reportMap17x22price").css("text-decoration", "none").html(toCurrency(_availableProducts[i].Prices.Laminated["" + _streetDetail + ""]));
                        //$("#extralargereportmapquantity").removeAttr("disabled");
                        $("#reportMap17x22").removeAttr("disabled");
                        $("#reportMap17x22avail").css("display", "inline");
                        $("#reportMap17x22notavail").css("display", "none");
                    }
                    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");
                    }
                }
            }
        }
    }
    if (_neighborhoodAvailability == false) {
        DisableReportsMaps();
    }
}

function DisableReportsMaps() {
    $("#largereportmap").attr("disabled", "disabled").attr("checked", "");
    $("#smallreportmap").attr("disabled", "disabled").attr("checked", "");
    $("#reportMap17x22").attr("disabled", "disabled").attr("checked", "");

    $("#smallreportmapquantity").attr("disabled", "disabled");
    $("#largereportmapquantity").attr("disabled", "disabled");

    $("#largereportmapprice").html("Please Call.");
    $("#smallreportmapprice").html("Please Call.");
    $("#reportMap17x22price").html("Please Call.");

    $("#multireportsmallavail").css("display", "none");
    $("#multireportlargeavail").css("display", "none");
    $("#reportMap17x22avail").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>");
    $("#reportMap17x22notavail").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("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);
        }
    );
    
    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) {

        if ($("#wallmapquantity").length > 0) {
            _wallmapquantity = MultiNullQuantityCheck($("#wallmapquantity").val());
        }
        else {
            _wallmapquantity = 1;
        }

        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++;

                        //  This method resides in common.js
                        _foEnum += GetFramedFinishingOptions(_finishingoption);

                        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) {
        if ($("#smallmapbook:checked").val()) {
            if ($("#largemapbookquantity").length > 0) {
                _mapbookquantity = MultiNullQuantityCheck($("#largemapbookquantity").val());
            }
            else {
                _mapbookquantity = 1;
            }

            _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) {
        if ($("#largemapbook:checked").val()) {
            if ($("#largemapbookquantity").length > 0) {
                _mapbookquantity = MultiNullQuantityCheck($("#largemapbookquantity").val());
            }
            else {
                _mapbookquantity = 1;
            }

            _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) {
        if ($("#smallreportmap:checked").val()) {
            if ($("#largereportmapquantity").length > 0) {
                _reportmapquantity = MultiNullQuantityCheck($("#largereportmapquantity").val());
            }
            else {
                _reportmapquantity = 1;
            }

            _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) {
        if ($("#largereportmap:checked").val()) {
            if ($("#largereportmapquantity").length > 0) {
                _reportmapquantity = MultiNullQuantityCheck($("#largereportmapquantity").val());
            }
            else {
                _reportmapquantity = 1;
            }

            _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 extra large report map quantity
    if ($("#reportMap17x22").length > 0) {
        if ($("#reportMap17x22:checked").val()) {
            if ($("#largereportmapquantity").length > 0) {
                _reportmapquantity = MultiNullQuantityCheck($("#largereportmapquantity").val());
            }
            else {
                _reportmapquantity = 1;
            }

            _reportmapsize = $("#reportMap17x22").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 Extra Large Report Map/s"
                }
            );
        }
    }

    //  determine digital map file type, computer compatibility, delivery method, and quantity
    if ($("input:radio[name=digitalfiletype]").length > 0 && $("#nofiletype:checked").val() !== "No Digital") {
        _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";
            }
        );
    }

    //  for the new multi format page, make sure at least one digital is checked
    if ($("input:checkbox[name='digitalfiletype']").length > 0 && $("input:checkbox[name='digitalfiletype']").is(":checked")) {
        _digitalmappctype = $("input:radio[name=pcormac]:checked").val();
        _digitalmapdeliverymethod = $("input:radio[name=digitaldelivery]:checked").val();

        if ($("#digitalquantity").length > 0) {
            _digitalmapquantity = MultiNullQuantityCheck($("#digitalquantity").val());
        }
        else {
            _digitalmapquantity = 1;
        }

        _product.MMFormat = _digitalmapformat;

        if ($("#pdffiletype").is(":checked")) {
            _digitalmapfiletype = $("#pdffiletype").val();
            _totalitems++;
            SaveDigitalMultiFormatProduct(_product, _edition, _streetdetail, _digitalmapfiletype, _digitalmappctype, _digitalmapdeliverymethod, _digitalmapquantity, _radiusring);
        }

        if ($("#aifiletype").is(":checked")) {
            _digitalmapfiletype = $("#aifiletype").val();
            _totalitems++;
            SaveDigitalMultiFormatProduct(_product, _edition, _streetdetail, _digitalmapfiletype, _digitalmappctype, _digitalmapdeliverymethod, _digitalmapquantity, _radiusring);
        }
    }
}

function SaveDigitalMultiFormatProduct(product, edition, streetDetail, digitalMapFileType, digitalMapPcType, digitalMapDeliveryMethod, digitalMapQuantity, radiusRing) {
    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("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);
        }
    );
    
    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 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");
                //  fade the column header
                //$("#" + _size + "-icon").addClass("mapsizeimagefaded");
                $("#" + _finishingOption + "-" + _size).unbind('click', AddSingleFormatWallMapToCart);
            }
            
            //  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 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) {
            
            }
        );
    }
    }

    function AddSelectionOption(Button, PopUp, ClosePopUp) {

        if ($("#multiformatproductpage").length > 0) {
            AddMultiSelectionClick(Button, PopUp);
        }
        else {
            AddSelectionClick(Button, PopUp);
        }


        AddCloseButton(ClosePopUp, PopUp);
        AddMouseEvents(Button);
        AddMouseEvents(ClosePopUp);
    }

    //  Adds effect and positions the extended finishing option popups
    function AddMultiSelectionClick(Element, PopUp) {
        Element.click(function () {
            var _element = $(this);
            var _popup = PopUp;

            //   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) - 677 - $("#page-popupcontroller").offset().top)
                .css("left", _element.offset().left - _parentelement.offset().left - 157 - $("#page-popupcontroller").offset().left)
                .css("z-index", "100");

            $("img[class$='selectionpopup']").click();

            if (_popup.is(":visible")) {
                _popup.slideUp("normal");
            } else {
                _popup.slideDown("normal");
            }
        });
    }

    //  Adds effect and positions the extended finishing option popups
    function AddSelectionClick(Element, PopUp) {
        Element.click(function () {
            var _element = $(this);
            var _popup = PopUp;

            //   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 - _parentelement.offset().top + _element.outerHeight(false))
            .css("left", _element.offset().left - _parentelement.offset().left + _element.outerWidth(false) - _popup.outerWidth(false))
            .css("z-index", "100");


            $("img[class$='selectionpopup']").click();

            if (_popup.is(":visible")) {
                _popup.slideUp("normal");
            } else {
                _popup.slideDown("normal");
            }
        });
    }

function AddFinishingOption(Button, PopUp, ClosePopUp) {

    if ($("#multiformatproductpage").length > 0) {
        AddMultiClick(Button, PopUp);
    }
    else {
        AddClick(Button, PopUp);
    }
    AddCloseButton(ClosePopUp, PopUp);
    AddMouseEvents(Button);
    AddMouseEvents(ClosePopUp);
}

//  Adds effect and positions all finishing option 'learn more' popups
function AddMultiClick(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) - 670 + _spanOffsetTop - $("#page-popupcontroller").offset().left)
            .css("left", _element.offset().left - _parentelement.offset().left + 124 - $("#page-popupcontroller").offset().left)
            .css("z-index", "100");

        if (_popup.is(":visible")) {
            _popup.slideUp("normal");
        } else {
            _popup.slideDown("normal");
        }
    });
}

//  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 - _parentelement.offset().top + _element.outerHeight(false) + _spanOffsetTop)
            .css("left", _element.offset().left - _parentelement.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 SetupStreetSelectionHighlighting() {
    /// <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 MultiNullQuantityCheck(quantity) {
    if (quantity == null || quantity == "" || quantity < 0) {
        return 1;
    }
    else {
        return quantity;
    }
}
