﻿/* Sync Qty fields */
function updateQty(whichField) {
    var qty = $("[id$='_quantity']");
    var qty2 = $("[id$='_qty2']");
    if (whichField == "qty2")
        qty.attr("value", qty2.attr("value"));
    else
        qty2.attr("value", qty.attr("value"));
}
var origMessaging = "";
var origStockValue = "";
var origStockValueSet = false;
//when the page is done loading, if we have Instock then take out usually
$(document).ready(function () {
    //for each of the items in the items tabs
    $(".Item_Avail").each(function (a, b) {
        var inHtml = $(this).html();
        //inHtml = inHtml.toString().toLowerCase();
        if (inHtml.toString().toLowerCase().indexOf("in stock") >= 0) {
            if (inHtml.toString().toLowerCase().indexOf("usually") >= 0) {
                inHtml = inHtml.replace("Usually", "");
                inHtml = inHtml.replace("ships", "Ships");
                $(this).html(inHtml);
            }
        }
    });
    removeUsuallyIfInStock();

});

function removeUsuallyIfInStock() {
    //not for the global inv messaging on the page
    if ($(".globalINVMSG").length) {
        if ($(".globalINVMSG").html().toString().toLowerCase().indexOf("in stock") >= 0) {
            //$("#divAvailabilityMsg1").html().toString().toLowerCase().indexOf("
            //$("#divAvailabilityMsg1Bottom")
            var inHtml = $("#divAvailabilityMsg1").html();
            if (inHtml.toString().toLowerCase().indexOf("usually") >= 0) {
                inHtml = inHtml.replace("Usually", "");
                inHtml = inHtml.replace("ships", "Ships");
                //$(this).html(inHtml);
                $("#divAvailabilityMsg1Bottom").html(inHtml);
                $("#divAvailabilityMsg1").html(inHtml);
            }

        }
    }
}

/* Availability Messaging Functions */
function skuSelector1_SelectedIndexChangedHandler(e) {

    if (origMessaging == "") {
        origMessaging = $("#divAvailabilityMsg1").html();
    }
    if (origStockValue == "" && origStockValueSet == false) {
        origStockValue = $(".globalINVMSG").html();
        origStockValueSet = true;
    }

    /* Handle Availability messaging */

    var availMsg = "";
    /*(e.get_availabilityMessage() != null && e.get_availabilityMessage() != "") ? e.get_availabilityMessage() : "&nbsp;";*/

    //$get("divAvailability").innerHTML = availMsg;

    //var qtyMsg = "&nbsp;";

    var btnAdd = $get("addToCartDiv");
    var btnAdd2 = $get("addToCartDiv2");
    var btnAddOff = $get("addToCartDivOff");
    var btnAdd2Off = $get("addToCartDiv2Off");
    var btnWish = $get("addToWishDiv");
    var btnWishOff = $get("addToWishDivOff");

    if (e.get_quantityAvailable() != null) {
        //show active add to cart button
        btnAdd.style.display = "block";
        btnAdd2.style.display = "block";
        if (btnWish) btnWish.style.display = "block";
        //hide inactive add to cart button
        btnAddOff.style.display = "none";
        btnAdd2Off.style.display = "none";
        if (btnWishOff) btnWishOff.style.display = "none";
    } else {
        //hide active add to cart button
        btnAdd.style.display = "none";
        btnAdd2.style.display = "none";
        if (btnWish) btnWish.style.display = "none";
        //show inactive add to cart buttons
        btnAddOff.style.display = "block";
        btnAdd2Off.style.display = "block";
        if (btnWishOff) btnWishOff.style.display = "block";
    }
    //$get("spanNumAvail").innerHTML = qtyMsg;


    /* Handle displaying selected values */
    if (e.get_selectedSku() != null && e.get_selectedSku() != "") {
        $get("skuAsSelected").innerHTML = e.get_selectedSku();
        $get("skuAsSelected2").innerHTML = e.get_selectedSku();
        $get("ErrorNoSku").style.display = "none"; // just in case error message for no sku is displaying
        $get("ErrorNoSku2").style.display = "none"; // just in case error message for no sku is displaying
        $get("ErrorNoSkuWish").style.display = "none"; // just in case error message for no sku is displaying
        //displayAvailability(e);
    }
    else {
        $get("skuAsSelected").innerHTML = "----";
        $get("skuAsSelected2").innerHTML = "";
    }

    /*Handle displaying selected manu ID */
    if (e.get_orderCode() != null && e.get_orderCode() != "") {
        $get("manuAsSelected").innerHTML = e.get_orderCode();
    }
    else {
        $get("manuAsSelected").innerHTML = "----";
    }

    //show selected price
    if (e.get_selectedSku() != null && e.get_selectedPrice() != "") {
        $get("priceAsSelected").innerHTML = "Price as Selected: <span class='price'>$" + CurrencyFormatted(e.get_selectedPrice()) + "</span>";
        $get("priceAsSelected2").innerHTML = "$" + CurrencyFormatted(e.get_selectedPrice());
        //update percentSaved
        if ($("#percentSaved")) {
            $("#percentSaved").hide();
            var perSave = "";
            if (e.get_selectedMsrpPrice() > (1.05 * e.get_selectedPrice())) perSave = "You Save " + Math.round((1 - (e.get_selectedPrice() / e.get_selectedMsrpPrice())) * 100) + "%";
            $("#percentSavedSku").html(perSave);
            $("#percentSavedSku").show();
        }
        //change tab heading text
        $("#Tab_Heading_Text").html("");
        $("#Tab_Heading_Text").show();
        $("#Tab_Heading_Link").hide();
    }
    else {
        $get("priceAsSelected").innerHTML = "";
        $get("priceAsSelected2").innerHTML = "";
        if ($("#percentSaved")) {
            $("#percentSavedSku").hide();
            $("#percentSaved").show();
        }
        //change tab heading text
        $("#Tab_Heading_Text").html("Please Make a Selection For Each Available Product Option");
        $("#Tab_Heading_Text").show();
        $("#Tab_Heading_Link").hide();
    }


    /* Not showing selected options
    
    //show selected options
    var options = "";
    if(e.get_selectedValues()) 
    {
    var sv = e.get_selectedValues();

    for(var i=0; i < sv.length; i++) 
    {
    if ((sv[i] != "" && sv[i] != "null" && sv[i] != null) && ((typeof showOptions != "undefined" && showOptions[i] != null && showOptions[i] == "True") || (typeof showOptions == "undefined")))
    options += "<li>" + sv[i] + "<\/li>";
    }

    }
    if (options != "")
    options = "<strong>Selected Options: </strong><br><ol>" + options + "<\/ol>" + "<div class='skuAvail'>" + availMsg + "</div>";
    else 
    options = "<div class='noSelectionMsg'>Select <a class='view_options_link' href='#tabs'>Product Options</a> to Purchase This Item:</div>"; //no options and no sku selected 
    $get("optionsAsSelected").innerHTML = options;
    */

    /* If already selected from each set and we don't have a sku selected -- bad combo made */
    var alreadySelected = e.get_selectedValues();
    var hasNull = false;
    for (var s = 0; s < alreadySelected.length; s++) {
        if (alreadySelected[s] == null || alreadySelected[s] == "" || alreadySelected[s] == "null")
            hasNull = true;
    }

    if ($get("ErrorBadCombo")) {
        if (hasNull == false && (e.get_selectedSku() == null || e.get_selectedSku() == "")) {
            $get("ErrorBadCombo").style.display = "block";
        } else {
            $get("ErrorBadCombo").style.display = "none";
        }
    }
    if (skusAndMessaging != null && skusAndMessaging != undefined && skusAndMessaging != 'undefined') {
        //top add to cart button messaging location

        var selectedSkuLumensInv = null;
        var selectedSkuVendorInv = null;
        var selectedSkuBackOrder = null;
        var selectedSkuShippingStatement = null;
        var selectedSkuInStock = null;
        var origBackOrder = null;
        for (var i = 0; i < skusAndMessaging.length; i++) {
            if (skusAndMessaging[i].sku == e.get_selectedSku()) {
                //parseInt
                if (skusAndMessaging[i].LumensInventory != null && skusAndMessaging[i].LumensInventory != 'null' &&
                skusAndMessaging[i].LumensInventory != 'undefined' && skusAndMessaging[i].LumensInventory != undefined) {
                    if (skusAndMessaging[i].LumensInventory == "") {
                        skusAndMessaging[i].LumensInventory = 0;
                    }
                    selectedSkuLumensInv = parseInt(skusAndMessaging[i].LumensInventory);
                }
                if (skusAndMessaging[i].VendorInventory != null && skusAndMessaging[i].VendorInventory != 'null' &&
                skusAndMessaging[i].VendorInventory != 'undefined' && skusAndMessaging[i].VendorInventory != undefined) {
                    if (skusAndMessaging[i].VendorInventory == "") {
                        skusAndMessaging[i].VendorInventory = 0;
                    }
                    selectedSkuVendorInv = parseInt(skusAndMessaging[i].VendorInventory);
                }
                origBackOrder = skusAndMessaging[i].BackOrder;
                selectedSkuBackOrder = "<span style='color:red'>"+skusAndMessaging[i].BackOrder+"</span>";
                selectedSkuShippingStatement = skusAndMessaging[i].ShippingStatement;
                selectedSkuInStock = skusAndMessaging[i].SkuInStock;
                if (selectedSkuLumensInv != null && selectedSkuVendorInv != null) {
                    if (selectedSkuLumensInv > 0 || selectedSkuVendorInv > 0) {
                        $(".globalINVMSG").html("In Stock");
                    }
                    else {
                        $(".globalINVMSG").html("");
                    }
                }
                else {
                    $(".globalINVMSG").html("");
                }
            }
        }
        var inventoryMessage = computeINVMessage(selectedSkuLumensInv, selectedSkuBackOrder, selectedSkuVendorInv, selectedSkuShippingStatement, selectedSkuInStock, origBackOrder);
        if (inventoryMessage != "") {
            $("#divAvailabilityMsg1").html(inventoryMessage);
            $("#divAvailabilityMsg1Bottom").html(inventoryMessage);
        }
        //check if $("[id$='_hiddenSkuField']"); doesnt have a value, and set to what was there on page load
        if ($("[id$='_hiddenSkuField']").val() == "") {

            $("#divAvailabilityMsg1").html(origMessaging);
            $("#divAvailabilityMsg1Bottom").html(origMessaging);
            $(".globalINVMSG").html(origStockValue);

        }
        removeUsuallyIfInStock();
    }
}
function computeINVMessage(selectedSkuLumensInv, selectedSkuBackOrder, selectedSkuVendorInv, selectedSkuShippingStatement, selectedSkuInStock, origBackOrder) {

    var retval = "";
    var hasShippingStatement = true;
    if (selectedSkuShippingStatement == null || selectedSkuShippingStatement == '') {
        hasShippingStatement = false;
    }
    if (selectedSkuLumensInv != null) {
        if (selectedSkuLumensInv > 0) {
            retval = "Ships next business day";
            return retval;
        }
    }
    if (selectedSkuVendorInv != null) {
        if (selectedSkuVendorInv > 0) {
            if (hasShippingStatement) {
                if (selectedSkuShippingStatement.indexOf("week") >= 0) {
                    if (selectedSkuInStock != null && selectedSkuInStock != '') {
                        if (selectedSkuInStock == 'True') {
                            retval = "Usually ships in " + selectedSkuShippingStatement;
                        }
                        else {
                            retval = "Usually ships in " + selectedSkuShippingStatement;
                        }
                    }
                    else {
                        retval = "Usually ships in " + selectedSkuShippingStatement;
                    }
                }
                else {
                    retval = "Ships in " + selectedSkuShippingStatement;
                }
                return retval;
            }
        }
    }
    if (selectedSkuVendorInv != null) {
        if (selectedSkuVendorInv == 0) {
            if (origBackOrder != null && origBackOrder != '') {
                retval = selectedSkuBackOrder;
                retval += "<br />";
                retval += "<a href='#product_items' onclick='openItemsTab()' class='view_items_link'>See all shipping times</a>";

                return retval;
            }
            if (hasShippingStatement) {

                retval = "Usually ships in " + selectedSkuShippingStatement;
                if (selectedSkuShippingStatement.indexOf("week") >= 0) {
                    //retval = "Special order item. " + retval;
                    if (selectedSkuInStock == 'True') {
                        retval = "" + retval;
                    }
                    
                }
                return retval;
            }
        }
    }
    if (selectedSkuVendorInv != null) {
        if (selectedSkuVendorInv < 0) {
            if (origBackOrder != null && origBackOrder != '') {
                retval = selectedSkuBackOrder;
                retval += "<br />";
                retval += "<a href='#product_items' onclick='openItemsTab()' class='view_items_link'>See all shipping times</a>";
                return retval;
            }
            if (hasShippingStatement) {
                retval = "Usually ships in " + selectedSkuShippingStatement;
                if (selectedSkuShippingStatement.indexOf("week") >= 0) {
                    //retval = "Special order item. " + retval;
                    if (selectedSkuInStock == 'True') {
                        retval = "" + retval;
                    }
                   
                }
                return retval;
            }
        }
    }


    return retval;
}

function imageAttributeSelector1_SelectedIndexChanged(e) {
    var isIE = ((navigator.appName) == "Microsoft Internet Explorer") ? true : false;

    var eControl, pTD, pTDHtml, selDiv = null;

    //if selecting an attribute...
    if (e.get_selectedValue() != null && e.get_selectedValue() != "null" && e.get_selectedValue() != "") { /* Need to check for null and "null" because of IE */
        //get the element from the selected attribute
        eControl = e.get_selectedControl().get_element();
        //get the element's offsetParent (TD.product_details)
        pTD = eControl.offsetParent;

        if (pTD) {
            pTDHtml = pTD.innerHTML;

            //go up through parents in DOM until reach the containing TR then find the second col TD and fill with pTD.innerHTML
            if (pTD.offsetParent) {
                if (isIE == true && pTD.offsetParent.offsetParent.nextElementSibling) {
                    isIE = false;
                }

                if (isIE == true) {
                    if (pTD.offsetParent.offsetParent.nextSibling) {
                        if (pTD.offsetParent.offsetParent.nextSibling.children[1]) selDiv = pTD.offsetParent.offsetParent.nextSibling.children[1];
                    }
                }
                else {
                    if (pTD.offsetParent.offsetParent.nextElementSibling) {
                        if (pTD.offsetParent.offsetParent.nextElementSibling.children[1]) selDiv = pTD.offsetParent.offsetParent.nextElementSibling.children[1];
                    }
                    else if (pTD.offsetParent.offsetParent.nextSibling.nextSibling) {
                        if (pTD.offsetParent.offsetParent.nextSibling.nextSibling.lastChild) selDiv = pTD.offsetParent.offsetParent.nextSibling.nextSibling.lastChild;  //For FF 3.0.15
                    }
                }
            }
        }
    } else {//if deselecting an attribute
        //eControl = e.originalTarget;
        eControl = e.get_element();

        //get the element's offsetParent (TD.product_details)
        //themeImageUrl defined on product.aspx page
        pTDHtml = "<img src='" + themeImageUrl + "/option_no_select.gif' alt='Select option' \/>";

        //go up through parents in DOM until reach the containing TR then find the second col TD and fill with pTD.innerHTML
        if (isIE == true && eControl.offsetParent.nextElementSibling) {
            isIE = false;
        }

        if (isIE == true) {
            if (eControl.offsetParent.nextSibling) {
                if (eControl.offsetParent.nextSibling.children[1]) selDiv = eControl.offsetParent.nextSibling.children[1];
            }
        }
        else {
            if (eControl.offsetParent.nextElementSibling) {
                if (eControl.offsetParent.nextElementSibling.children[1]) selDiv = eControl.offsetParent.nextElementSibling.children[1];
            }
            else if (eControl.offsetParent.nextSibling.nextSibling) {
                if (eControl.offsetParent.nextSibling.nextSibling.lastChild) selDiv = eControl.offsetParent.nextSibling.nextSibling.lastChild;  /*For FF 3.0.15*/
            }
        }
    }

    //set selDiv's innerHTML to pTDHtml
    if (selDiv) selDiv.innerHTML = pTDHtml;
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}


/* Swatch Functions */
//this function will cause the main image to swap when a swatch is rolled over.
//you must add the following to the swatch control declaration:
//  OnClientThumbNailMouseOver="SwatchOver" 
function SwatchOver(sender, eventArgs) {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = "assets/images/swatches/" + sender._swatches[eventArgs.index].Image;
}

//this function will cause the main image to swap when a swatch is rolled off.
//you must add the following to the swatch control declaration:
//  OnClientThumbnailMouseOut="SwatchOut" 
function SwatchOut(sender, eventArgs) {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = mainImageSrc;
}

//this function will cause the main image to swap when a swatch is clicked.
//you must add the following to the swatch control declaration:
//  OnClientSelectedIndexChanged="SwatchClick"
function SwatchClick(sender) {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = "assets/images/swatches/" + sender.get_selectedImage();
}


/* Alternate Functions */
//this function will cause the main image to swap when an alternate is rolled over.
//you must add the following to the swatch control declaration:
//  OnClientThumbNailMouseOver="SwatchOver" 
function AlternateOver(imageName) {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = "assets/images/alternates/" + imageName;
}

//this function will cause the main image to swap when an alternate is rolled off.
//you must add the following to the swatch control declaration:
//  OnClientThumbnailMouseOut="SwatchOut"
function AlternateOut() {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = mainImageSrc;
}

//this function will cause the main image to swap when an alternate is clicked.
//you must add the following to the swatch control declaration:
//  OnClientSelectedIndexChanged="SwatchClick"
function AlternateClick(imageName) {
    var mainImage = document.getElementById("MainImage");
    mainImage.src = "assets/images/alternates/" + imageName;

}

/* Jumbo Functions */
var winPhoto;
function makeNewWindow(path, title) {
    winPhoto = window.open("", "AltView", "height=500,width=500,status=0,scrollbars=0,location=0,resizable=1");
    winPhoto.document.open();
    winPhoto.document.write('<html>');
    winPhoto.document.write('    <head>');
    winPhoto.document.write('        <title>');
    winPhoto.document.write(title);
    winPhoto.document.write('        </title>');
    winPhoto.document.write('<sc' + 'ript lang=javascript>');
    winPhoto.document.write('var largeimage = new Image();');
    winPhoto.document.write('largeimage.src ="' + path + '"');
    winPhoto.document.write('</s' + 'cript>');
    winPhoto.document.write('    </head>');
    winPhoto.document.write('    <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">');
    winPhoto.document.write('    <table border="0" cellspacing="0" cellpadding="3" align="center" bgcolor="#FFFFFF">');
    winPhoto.document.write('      <tr>');
    winPhoto.document.write('        <td align="center" class="dept_products_in"><img align=center src="' + path + '" onLoad="window.resizeTo(largeimage.width+60,largeimage.height+140);" ></td>');
    winPhoto.document.write('      </tr>');
    winPhoto.document.write('      <tr>');
    winPhoto.document.write('        <td align="center"><a href="javascript:window.close();" class="large_image">Close window</a><br></td>');
    winPhoto.document.write('      </tr>');
    winPhoto.document.write('     </table>	');
    winPhoto.document.write('    </body>');
    winPhoto.document.write('</html>');
    winPhoto.document.close();
    winPhoto.focus();
    return false;
}

/* Update monogramming fields and quantities*/
function updateMonogram1() {
    var msg = $("#gift_msg");
    var theValue = msg.val();
    var mono1 = $("[id$='_monogram_1']");
    var giftCk = $("[id$='_gift_wrap']");
    var q1 = $("[id$='_quantity']");
    var q2 = $("[id$='_quantity2']");

    //update monogram field if checkbox checked and message value is set
    if (theValue != "" && theValue != msg.attr("title") && giftCk.attr("checked")) {
        mono1.val("Gift Message: " + theValue.replace(/,/g, ' ') + ";"); //fill mono value
    }
    else {
        mono1.val(""); //clear mono value
    }
    //update qty field for gift wrap when checkbox checked
    if (giftCk.attr("checked")) {
        q2.val(q1.val()); //make qty = product's qty so wrap IS added to cart
        $get("GiftWrapPop").style.display = "block"; //show popup
    }
    else {
        q2.val("0"); //make qty 0 so that wrap is NOT added to cart
        $get("GiftWrapPop").style.display = "none"; //hide popup
    }
}


//builds a backorder message based on backorder date contained in vendorCode
function displayAvailability(e) {
    var vendorCode = e.get_vendorCode();
    if (vendorCode != "" && vendorCode != null && checkValidDate(vendorCode)) {
        var BackOrderDt = new Date(vendorCode);
        var today = new Date();
        if (BackOrderDt > today) {
            var str = "";
            //str += "This option is on backorder<br />";
            str += "Ships ";

            if (BackOrderDt.getDate() <= 15) {
                str += "mid ";
            }
            else {
                str += "late ";
            }

            str += lookupMonthStr(BackOrderDt.getMonth());
            str += "<br />";
            str += "<a href='#product_items' onclick='openItemsTab()' class='view_items_link'>See all shipping times</a>";
            $get("divAvailabilityMsg2").innerHTML = str;
            $get("divAvailabilityMsg1").style.display = "none";
            $get("divAvailabilityMsg2").style.display = "block";

            $get("divAvailabilityMsg2Bottom").innerHTML = str;
            $get("divAvailabilityMsg1Bottom").style.display = "none";
            $get("divAvailabilityMsg2Bottom").style.display = "block";
        }
        else {
            $get("divAvailabilityMsg1").style.display = "block";
            $get("divAvailabilityMsg2").style.display = "none";

            $get("divAvailabilityMsg1Bottom").style.display = "block";
            $get("divAvailabilityMsg2Bottom").style.display = "none";
        }
    }
    else {
        $get("divAvailabilityMsg1").style.display = "block";
        $get("divAvailabilityMsg2").style.display = "none";

        $get("divAvailabilityMsg1Bottom").style.display = "block";
        $get("divAvailabilityMsg2Bottom").style.display = "none";
    }
}

//checks a string is a valid date format
function checkValidDate(dateStr) {
    // http://www.breakingpar.com/bkp/home.nsf/0/75A5C758B9DF576087256AFB00140789
    // dateStr must be of format month day year with either slashes
    // or dashes separating the parts. Some minor changes would have
    // to be made to use day month year or another format.
    // This function returns True if the date is valid.

    //JMS addition, remove anthing from a space and beyond in case time is added after year
    if (dateStr.indexOf(' ') != -1) dateStr = dateStr.substring(0, dateStr.indexOf(' '));

    var slash1 = dateStr.indexOf("/");
    if (slash1 == -1) { slash1 = dateStr.indexOf("-"); }
    // if no slashes or dashes, invalid date
    if (slash1 == -1) { return false; }
    var dateMonth = dateStr.substring(0, slash1)
    var dateMonthAndYear = dateStr.substring(slash1 + 1, dateStr.length);
    var slash2 = dateMonthAndYear.indexOf("/");
    if (slash2 == -1) { slash2 = dateMonthAndYear.indexOf("-"); }
    // if not a second slash or dash, invalid date
    if (slash2 == -1) { return false; }
    var dateDay = dateMonthAndYear.substring(0, slash2);
    var dateYear = dateMonthAndYear.substring(slash2 + 1, dateMonthAndYear.length);
    if ((dateMonth == "") || (dateDay == "") || (dateYear == "")) { return false; }
    // if any non-digits in the month, invalid date
    for (var x = 0; x < dateMonth.length; x++) {
        var digit = dateMonth.substring(x, x + 1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text month to a number
    var numMonth = 0;
    for (var x = 0; x < dateMonth.length; x++) {
        digit = dateMonth.substring(x, x + 1);
        numMonth *= 10;
        numMonth += parseInt(digit);
    }
    if ((numMonth <= 0) || (numMonth > 12)) { return false; }
    // if any non-digits in the day, invalid date
    for (var x = 0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x + 1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text day to a number
    var numDay = 0;
    for (var x = 0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x + 1);
        numDay *= 10;
        numDay += parseInt(digit);
    }
    if ((numDay <= 0) || (numDay > 31)) { return false; }
    // February can't be greater than 29 (leap year calculation comes later)
    if ((numMonth == 2) && (numDay > 29)) { return false; }
    // check for months with only 30 days
    if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) {
        if (numDay > 30) { return false; }
    }
    // if any non-digits in the year, invalid date
    for (var x = 0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x + 1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text year to a number
    var numYear = 0;
    for (var x = 0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x + 1);
        numYear *= 10;
        numYear += parseInt(digit);
    }
    // Year must be a 2-digit year or a 4-digit year
    if ((dateYear.length != 2) && (dateYear.length != 4)) { return false; }
    // if 2-digit year, use 50 as a pivot date
    if ((numYear < 50) && (dateYear.length == 2)) { numYear += 2000; }
    if ((numYear < 100) && (dateYear.length == 2)) { numYear += 1900; }
    if ((numYear <= 0) || (numYear > 9999)) { return false; }
    // check for leap year if the month and day is Feb 29
    if ((numMonth == 2) && (numDay == 29)) {
        var div4 = numYear % 4;
        var div100 = numYear % 100;
        var div400 = numYear % 400;
        // if not divisible by 4, then not a leap year so Feb 29 is invalid
        if (div4 != 0) { return false; }
        // at this point, year is divisible by 4. So if year is divisible by
        // 100 and not 400, then it's not a leap year so Feb 29 is invalid
        if ((div100 == 0) && (div400 != 0)) { return false; }
    }
    // date is valid
    return true;
}

// returns a string for the desired month
function lookupMonthStr(intMonth) {
    var strMonth = "";
    intMonth += 1;
    switch (intMonth) {
        case 1:
            return "January";
            break;
        case 2:
            return "February";
            break;
        case 3:
            return "March";
            break;
        case 4:
            return "April";
            break;
        case 5:
            return "May";
            break;
        case 6:
            return "June";
            break;
        case 7:
            return "July";
            break;
        case 8:
            return "August";
            break;
        case 9:
            return "September";
            break;
        case 10:
            return "October";
            break;
        case 11:
            return "November";
            break;
        case 12:
            return "December";
            break;
        default:
            return "month";
    }
}
