
function disableOrderFormSubmit() {
    $(".orderform input[type='submit']").attr('disabled', 'disabled');
    $(".orderform input[type='submit']").val('Submitting... Please Wait.');
}

function val_account(triggerID, fieldID)
{
    var errors = new Array();
    if ($("#" + triggerID).attr('checked')) {
        var billaccount = $("#" + fieldID).val();
        if (billaccount.length == 6) {
            $.ajax({
                type: "GET",
                async: false,
                url: "/order/validate/account.php",
                data: { number: billaccount },
                success: function(data) {
                    if (data != 1) {
                        errors = errors.concat("The corporate/third party account number you entered is invalid.");
                    }
                }
            });
        } else {
            errors = errors.concat("Please enter the corporate/third party account number.");
        }
    }
    return errors;
}

function val_orderform(f,dept,type) {

    var errors = new Array(0,0);

    switch (f.JobType.value) {

        case 'AP':
            errors = errors.concat(val_AP(f))
        break;

        case 'EMB':
            errors = errors.concat(val_EMB(f))
        break;

        case 'FC':
            errors = errors.concat(val_FC(f))
        break;

        case 'ST':
            errors = errors.concat(val_ST(f))
        break;

    }

    errors = errors.concat(val_account('bill_3rdparty', 'BillTo_Account'));

    if(type == 'Order') {
        //check for File Prep Info
        if (!f.Pay_File_Prep_Fee[1].checked && !f.Pay_File_Prep_Fee[0].checked) {
            errors = errors.concat("Please select YES or NO for File Prep Instructions.");
        }

        if (f.Emergency_Contact[1].checked) {
            if (!IsEmpty(f.Emergency_Email)) {
                if (!IsEmailValid(f.name, "Emergency_Email")) {
                    errors = errors.concat("Emergency Contact email is not a valid email address.");
                }
            } else {
                if (IsEmpty(f.Emergency_Phone)) {
                    errors = errors.concat("Emergency Phone number in case we have file trouble.");
                }
            }
        } else if (!f.Emergency_Contact[0].checked) {
            errors = errors.concat("Please choose a contact in case of file prep problems.");
        }

        // Check Payment Info
        if(type == 'Order') {
            if(val_billing(f)) {
                errors = errors.concat(val_billing(f))
            }
        }
    }

    //check for shipping info
    errors = errors.concat(val_shippingInfo(f))

    // Check terms and conditions
    if (!f.Terms_Conditions.checked) {
        errors[errors.length + 1] = 'You must agree to the terms and conditions';
    }

    // Check the cancellation policy, if this is an order
    if (type == 'Order' && !f.Cancel_Policy.checked) {
        errors[errors.length + 1] = 'You must agree to the cancellation policy';
    }

    //show all errors
    msgs = '';
    c = 1;

    if (errors.length > 2) {
        for (i = 1; i < errors.length; i++) {
            if (errors[i]) {
                msgs += c+') '+errors[i]+'\n'
                c++;
            }
        }

        errorMessage = "Please fix the following missing or incorrect info:\n\r"
        alert(errorMessage+msgs)
        return false

    } else {
        disableOrderFormSubmit();
        return true
    }

}

function val_cannedorderform(f,dept,type)
{
    var errors = new Array(0,0);

    switch (f.JobType.value) {
        case 'FC':
            errors = errors.concat(val_cannedFC(f))
            break;

        case 'ST':
            errors = errors.concat(val_cannedST(f))
            break;
    }

    errors = errors.concat(val_account('bill_3rdparty', 'BillTo_Account'));

    //check for shipping info
    errors = errors.concat(val_cannedshippingInfo(f))

    if (type == 'Order') {
        //check for File Prep Info
        if (!f.Pay_File_Prep_Fee[1].checked && !f.Pay_File_Prep_Fee[0].checked) {
            errors = errors.concat("Please select YES or NO for File Prep Instructions.");
        }

        if (f.Emergency_Contact[1].checked) {
            if (!IsEmpty(f.Emergency_Email)) {
                if (!IsEmailValid(f.name, "Emergency_Email")) {
                    errors = errors.concat("Emergency Contact email is not a valid email address.");
                }
            } else {
                if (IsEmpty(f.Emergency_Phone)) {
                    errors = errors.concat("Emergency Phone number in case we have file trouble.");
                }
            }
        } else if (!f.Emergency_Contact[0].checked) {
            errors = errors.concat("Please choose a contact in case of file prep problems.");
        }

        // Check Payment Info
        if(type == 'Order') {
            if(val_billing(f)) {
                errors = errors.concat(val_billing(f))
            }
        }
    }

    // Check terms and conditions
    if (!f.Terms_Conditions.checked) {
        errors[errors.length + 1] = 'You must agree to the terms and conditions';
    }

    // Check the cancellation policy, if this is an order
    if (type == 'Order' && !f.Cancel_Policy.checked) {
        errors[errors.length + 1] = 'You must agree to the cancellation policy';
    }

    //show all errors
    msgs = '';
    c = 1;

    if (errors.length > 2) {
        for (i = 1; i < errors.length; i++) {
            if (errors[i]) {
                msgs += c+') '+errors[i]+'\n';
                c++;
            }
        }
        errorMessage = "Please fix the following missing or incorrect info:\n\r";
        alert(errorMessage+msgs);
        return false;
    } else {
        disableOrderFormSubmit();
        return true;
    }
}

function val_depositform(f)
{
    var errors = new Array(0,0);

    // Check Payment Info
    if(val_billing(f)) {
        errors = errors.concat(val_billing(f))
    }

    //show all errors
    msgs = '';
    c = 1;

    if (errors.length > 2) {
        for (i = 1; i < errors.length; i++) {
            if (errors[i]) {
                msgs += c+') '+errors[i]+'\n';
                c++;
            }
        }
        errorMessage = "Please fix the following missing or incorrect info:\n\r";
        alert(errorMessage+msgs);
        return false;
    } else {
        return true;
    }
}

function val_cannedFC(f) {
    var errors = new Array();
    var e = 1;

    if (IsEmpty(f.Job_Name)) {
        errors[e++] = "Job Reference Name";
    }
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }
    if (!checkPopUp(f.Job_Proofing)) {
        errors[e++] = "No Proofing Option Selected";
    }
    return errors;
}

function val_cannedST(f) {
    var errors = new Array();
    var e = 1;

    if (IsEmpty(f.Job_Name)) {
        errors[e++] = "Job Reference Name";
    }
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }
    if (!checkPopUp(f.Job_Proofing)) {
        errors[e++] = "No Proofing Option Selected";
    }
    $(".st_ink").each(function() {
        if ($(this).val() == "") {
            errors[e++] = "Ink #" + $(this).attr('ink_number') + " required";
        }
    });
    return errors;
}

////////////////////////////////////////////////////////
//   val_quoteform()
//
//
//
//
//
//
////////////////////////////////////////////////////////


function val_quoteform(f) {
    var errors = new Array(0,0);

    if(!checkPopUp(f.quoteaction)) {
        errors = errors.concat("Select an action to handle this quote.")
    } else {
        theIndexis = f.quoteaction.selectedIndex;

        if(f.quoteaction.selectedIndex == 1) {
            if(val_billing(f)) {
                errors = errors.concat(val_billing(f));
            }
        }

        if(f.quoteaction.selectedIndex == 2) {
            if(IsEmpty(f.Job_Instructions)) {
                errors = errors.concat("No Notes provided")
            }
        }
    }

    //show all errors
    msgs = '';
    c = 1;

    if(errors.length > 2) {
        for(i = 1; i < errors.length; i++) {
            if(errors[i]) {
                msgs += c+') '+errors[i]+'\n'
                c++;
            }
        }

        errorMessage = "Please fix the following missing or incorrect info:\n\r"
        alert(errorMessage+msgs)
        return false

    } else {

        return true
    }

}



////////////////////////////////////////////////////////
//   val_ST()
//
//
//
//
//
//
////////////////////////////////////////////////////////

function val_ST(f) {
    var errors = new Array();
    var e = 1;

    if(IsEmpty(f.Job_Name)) errors[e++] = "Job Reference Name"
    // check for po required
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }
    if(IsEmpty(f.Quantity)) errors[e++] = "Quantity"
    if(IsEmpty(f.Width)) errors[e++] = "Sticker Width"
    if(IsEmpty(f.Height)) errors[e++] = "Sticker Height"
    var product_value = '';
    if(!checkPopUp(f.Product)) {
        errors[e++] = "No Product Selected"
    } else {
        product_value = f.Product.options[f.Product.selectedIndex].value;
        if(product_value == "Foil Labels") {
            if(!checkPopUp(f.Detail)) errors[e++] = "No Foil Color Selected"
        } else if(product_value == "Paper Labels") {
            if(!checkPopUp(f.Detail)) errors[e++] = "No Paper Finish Selected"
        } else if(product_value == "Bumper Stickers") {
            if(!checkPopUp(f.Detail)) errors[e++] = "No Bumper Sticker Stock Selected"
        }
    }

    if(!checkPopUp(f.Shape)) errors[e++] = "No Shape Selected"
    if (product_value != "EcoGreen Stickers" && product_value != "Magnets" && product_value != "Vinyl Decal") {
        if(!checkPopUp(f.Inks)) {
            errors[e++] = "Number of Colors"
        } else {
            var inkvalue = f.Inks.options[f.Inks.selectedIndex].value;
            if (inkvalue == "1 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
            } else if (inkvalue == "2 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
                if(IsEmpty(f.Ink_Color_2)) errors[e++] = "Ink #2"
            } else if (inkvalue == "3 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
                if(IsEmpty(f.Ink_Color_2)) errors[e++] = "Ink #2"
                if(IsEmpty(f.Ink_Color_3)) errors[e++] = "Ink #3"
            } else if (inkvalue == "4 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
                if(IsEmpty(f.Ink_Color_2)) errors[e++] = "Ink #2"
                if(IsEmpty(f.Ink_Color_3)) errors[e++] = "Ink #3"
                if(IsEmpty(f.Ink_Color_4)) errors[e++] = "Ink #4"
            } else if (inkvalue == "5 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
                if(IsEmpty(f.Ink_Color_2)) errors[e++] = "Ink #2"
                if(IsEmpty(f.Ink_Color_3)) errors[e++] = "Ink #3"
                if(IsEmpty(f.Ink_Color_4)) errors[e++] = "Ink #4"
                if(IsEmpty(f.Ink_Color_5)) errors[e++] = "Ink #5"
            } else if (inkvalue == "6 Color") {
                if(IsEmpty(f.Ink_Color_1)) errors[e++] = "Ink #1"
                if(IsEmpty(f.Ink_Color_2)) errors[e++] = "Ink #2"
                if(IsEmpty(f.Ink_Color_3)) errors[e++] = "Ink #3"
                if(IsEmpty(f.Ink_Color_4)) errors[e++] = "Ink #4"
                if(IsEmpty(f.Ink_Color_5)) errors[e++] = "Ink #5"
                if(IsEmpty(f.Ink_Color_6)) errors[e++] = "Ink #6"
            }
        }
    } else if (product_value == "Vinyl Decal") {
        if(IsEmpty(f.Decal_Color)) errors[e++] = "Decal Color"
    }


    if(IsEmpty(f.Front_Filename)) errors[e++] = "File Name"
    if (!checkPopUp(f.Proofs)) {
        errors[e++] = "No Proofing Option Selected";
    }


    return errors;
}



////////////////////////////////////////////////////////
//   val_FC()
//
//
//
//
//
//
////////////////////////////////////////////////////////

function val_FC(f) {
    var errors = new Array();
    var e = 1;

    if (IsEmpty(f.Job_Name)) {
        errors[e++] = "Job Reference Name";
    }
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }
    if (IsEmpty(f.Quantity)) {
        errors[e++] = "Quantity";
    }
    if (IsEmpty(f.Width)) {
        errors[e++] = "Finished Width";
    }
    if (IsEmpty(f.Height)) {
        errors[e++] = "Finished Height";
    }
    if (!checkPopUp(f.Inks1))  {
        errors[e++] = "Inks Side 1";
    } else {
        var inks = f.Inks1.options[f.Inks1.selectedIndex].value;
        if (inks == '5' || inks == '1 Spot' || inks == '2 Spot') {
            if (IsEmpty(f.Spot_Inks1)) {
                errors[e++] = "Spot Inks Side 1";
            }
        }
    }
    if (checkPopUp(f.Inks2))  {
        var inks = f.Inks2.options[f.Inks2.selectedIndex].value;
        if (inks == '5' || inks == '1 Spot' || inks == '2 Spot') {
            if (IsEmpty(f.Spot_Inks2)) {
                errors[e++] = "Spot Inks Side 2";
            }
        }
    }
    if (!checkPopUp(f.Product)) {
        errors[e++] = "No Product is Selected";
    }
    if (!checkPopUp(f.Proofs)) {
        errors[e++] = "No Proofing Option Selected";
    }

    if (!IsRadioChecked(f.name,'Add_our_tag_line')) {
        errors[e++] = "$10 Discount";
    }
    return errors;
}


////////////////////////////////////////////////////////
//   val_AP()
//
//
//
//
//
//
////////////////////////////////////////////////////////

function val_AP(f) {
    var errors = new Array();
    var e = 1;
    var sides = new Array('Front', 'Back', 'Other')
    var sizes = new Array('YS', 'YM', 'YL', 'SM', 'MD', 'LG', 'XL', '2X', '3X', '4X')

    var sidesUsed = 0;

    if(IsEmpty(f.Job_Name)) errors[e++] = "Job Reference Name"
    // check for po required
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }

    for(i = 0; i < sides.length; i++) {
        thisSide = sides[i];
        if(!IsEmpty(f.elements[thisSide+'_Filename'])) {
            sidesUsed++
            if(!checkPopUp(f.elements[thisSide+'_Screens']))  errors[e++] = "Number of "+thisSide+" graphic colors"
            if(IsEmpty(f.elements[thisSide+'_Colors']))  errors[e++] = thisSide+" graphic color names"
            if(!checkPopUp(f.elements[thisSide+'_Position']))  errors[e++] = thisSide+" graphic positioning"
            if(IsEmpty(f.elements[thisSide+'_Width']))  errors[e++] = thisSide+" graphic width"
        }
    }

    if(!sidesUsed) errors[e++] = "No graphics info entered"

    return errors;
}

////////////////////////////////////////////////////////
//   val_EMB()
//
//
//
//
//
//
////////////////////////////////////////////////////////

function val_EMB(f) {
    var errors = new Array();
    var e = 1;
    var sizes = new Array('YS', 'YM', 'YL', 'SM', 'MD', 'LG', 'XL', '2X', '3X', '4X', '5X')

    var theTotal = 0;
    var thisSize = 0;
    var theQty = 0;

    if(IsEmpty(f.Job_Name)) errors[e++] = "Job Reference Name"
    // check for po required
    if (f.porequired.value == 'required' && IsEmpty(f.PO_Number)) {
        errors[e++] = 'PO Number';
    }

    //check products
    productsCount = 0
    for (i = 1; i <= 3; i++) {
        f.elements['Total'+i].value = ""; //reset the total to nothing
        if (checkPopUp(f.elements['Product'+i])) {
            // check color
            productsCount++;
            if (IsEmpty(f.elements['Color'+i])) {
                errors[e++] = "Color: Product #"+i;
            }
            // check sizes
            theTotal = 0;
            for (s = 0; s < sizes.length; s++) {
                thisSize = sizes[s]+i;
                if (f.elements[thisSize].value) {
                    theQty = parseInt(f.elements[thisSize].value)
                    if (isNaN(theQty)) {
                        errors[e++] = "Non-number quantity in Product #" + i + " " + thisSize;
                    } else {
                        theTotal = parseInt(theTotal) + parseInt(theQty);
                    }
                }
            }
            // check total
            if (theTotal == 0) {
                errors[e++] = "No Sizes Set: Product #" + i
            } else {
                f.elements['Total'+i].value = theTotal;
            }
        } else {
            //clear the color box
            f.elements['Color'+i].value = ""
            //clear all sizes
            for(s = 0; s < sizes.length; s++) {
                thisSize = sizes[s]+i;
                f.elements[thisSize].value = ""
            }
        }
    }

    if (!productsCount) {
        errors[e++] = "No products selected";
    }

    return errors;
}


////////////////////////////////////////////////////////
//   val_shippingInfo()
//
//
//
//
//
//
////////////////////////////////////////////////////////


function val_shippingInfo(f) {
    var errors = new Array();
    var e = 1;

    if (f.Turnaround[1].checked) {
        if (rushErrors = isDate(f.In_Hands_By_Date.value)) {
            errors[e++] = "Rush Date: "+rushErrors
        }
    }

    var shipMethods = f.Shipping_Method;
    var shipMethod  = 'ship';
    for (var i=0; i<shipMethods.length; i++) {
        if (shipMethods[i].checked) {
            shipMethod = shipMethods[i].value;
        }
    }

    if (shipMethod == 'ship') {
        if (!checkPopUp(f.Shipping_Carrier)) {
            errors[e++] = "Shipping Carrier"
        }
        if (!checkPopUp(f.Shipping_Type)) {
            errors[e++] = "Shipping Service"
        }
        if (IsEmpty(f.Shipping_Recipient)) {
            errors[e++] = "Shipping Recipient";
        }
        if (IsEmpty(f.Shipping_Address)) {
            errors[e++] = "Shipping Street Address";
        }
        if (IsEmpty(f.Shipping_City)) {
            errors[e++] = "Shipping City";
        }
        if (IsEmpty(f.Shipping_Zip_Code)) {
            errors[e++] = "Shipping ZIP Code";
        }
        if (IsEmpty(f.Shipping_Country)) {
            errors[e++] = "Shipping Country";
        } else if (f.Shipping_Country.value == 'United States') {
            if (!checkPopUp(f.Shipping_State)) {
                errors[e++] = "Shipping State";
            }
        }
        if (IsEmpty(f.Shipping_Phone)) {
            errors[e++] = "Shipping Contact Phone Number";
        }
    }

    return errors;
}

function val_cannedshippingInfo(f) {
    var errors = new Array();
    var e = 1;

    var shipMethod = $("select[name=Shipping_Method]").val();

    if (shipMethod == 'ship') {
        var shipCarrier          = $("select[name=shippingService]").val();
        var shipRate             = $("select[name=shippingRate]").val();
        var shipFedExRate        = $("select[name=fedexShippingRate]").val();
        var shipServiceUPSAcct   = $("select[name=upsShippingMethod]").val();
        var shipServiceFedExAcct = $("select[name=fedexShippingMethod]").val();
        var shipUseAcct          = $("input[name=shippingAccountCheckbox]").attr("checked");
        var shipAcct             = $("input[name=Shipping_Account_Number]").val();

        if (shipCarrier == 'UPS') {
            if (shipUseAcct) {
                if (shipServiceUPSAcct == "") {
                    errors[e++] = "Select a UPS Shipping Method";
                }
                if (shipAcct == "") {
                    errors[e++] = "Provide your UPS Account Number";
                }
            } else {
                if (shipRate == "") {
                    errors[e++] = "Select a shipping method";
                }
            }
        } else if (shipCarrier == 'FedEx') {
            if (shipUseAcct) {
                if (shipServiceFedExAcct == "") {
                    errors[e++] = "Select a FedEx Shipping Method";
                }
                if (shipAcct == "") {
                    errors[e++] = "Provide your FedEx Account Number";
                }
            } else {
                if (shipRate == "") {
                    errors[e++] = "Select a shipping method";
                }
            }
        }
    }

    return errors;
}

function val_billing(f) {
    var errors = new Array();
    var e = 1;

    var payMethods = f.Payment_Method;
    var payMethod  = '';
    for (var i=0; i<payMethods.length; i++) {
        if (payMethods[i].checked) {
            payMethod = payMethods[i].value;
        }
    }

    if (payMethod == '') {
        errors[e++] = 'Payment Method';
    } else if (payMethod == 'Credit Memo') {
        if (!checkPopUp(f.Credit_Memo)) {
            errors[e++] = "Select a Credit Memo";
        }
    } else if (payMethod == 'Credit Card') {
        if (IsEmpty(f.storedCard)) {
            if (IsEmpty(f.Credit_Card_Holder)) {
                errors[e++] = 'Cardholder\'s Name';
            }
            if (!checkPopUp(f.Credit_Card_Type)) {
                errors[e++] = 'Credit Card Type';
            }
            if (IsEmpty(f.CVS)) {
                errors[e++] = 'Card Verification Number';
            } else {
                cardType = f.Credit_Card_Type[f.Credit_Card_Type.selectedIndex].value
                if ((msg = checkCardCVV(cardType, f.CVS.value))) {
                    errors[e++] = msg;
                }
            }
            if (!(cardNumber = cleanCardNum(f.Credit_Card_Number.value))) {
                errors[e++] = 'Re-type your credit card number.';
            } else {
                cardType = f.Credit_Card_Type[f.Credit_Card_Type.selectedIndex].value
                if ((msg = checkCard(cardType, cardNumber))) {
                    errors[e++] = msg;
                }
            }
            if (!checkPopUp(f.Credit_Card_Month)) {
                errors[e++] = "Credit Card Expiration Month";
            }
            if (!checkPopUp(f.Credit_Card_Year)) {
                errors[e++] = "Credit Card Expiration Year";
            }
            if (f.saveCreditCard.checked && IsEmpty(f.saveCreditCardLabel)) {
                errors[e++] = 'Save New Credit Card Label';
            }
        } else {
            if (IsEmpty(f.storedCVV)) {
                errors[e++] = 'Stored Credit Card - Card Verification Number';
            }
        }
    }

    return errors;
}

function updateSTShapeOptions(value) {
    var list = new Array();
    if (value == "Vinyl Decal") {
        list[0] = new Option("- Pick One -", "0", false, false);
        list[1] = new Option("Custom (Please include die-line)", "Custom", true, true);
    } else {
        list[0] = new Option("- Pick One -", "0", true);
        list[1] = new Option("Circle", "Circle");
        list[2] = new Option("Square", "Square");
        list[3] = new Option("Oval", "Oval");
        list[4] = new Option("Rectangle", "Rectangle");
        list[5] = new Option("Custom (Please include die-line)", "Custom");
    }
    var f = document.forms["OrderForm"];
    var menu = f.elements["Shape"];
    menu.options.length = 0;
    for(i = 0; i < list.length; i++) {
        menu.options[i] = list[i];
    }
}

function updateSTColorOptions(value) {
    var pick1 = new Option("- Pick One -", "0");
    var one   = new Option("1 Spot Color", "1 Color");
    var two   = new Option("2 Spot Color", "2 Color");
    var three = new Option("3 Spot Color", "3 Color");
    var four  = new Option("4 Spot Color", "4 Color");
    var five  = new Option("5 Spot Color", "5 Color");
    var six   = new Option("6 Spot Color", "6 Color");
    var full  = new Option("Full Color (Process)", "Full Color");
    var list = new Array();
    if (value == "Paper Labels") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = full;
    } else if (value == "Foil Labels") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
    } else if (value == "Vinyl Stickers") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = full;
    } else if (value == "Clear Stickers") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = full;
    } else if (value == "Bumper Stickers") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = four;
        list[5] = five;
        list[6] = six;
        list[7] = full;
    } else if (value == "EcoGreen Stickers") {
        list[0] = pick1;
        list[1] = full;
        list[1].selected = true;
        list[1].defaultSelected = true;
    } else if (value == "Magnets") {
        list[0] = pick1;
        list[1] = full;
        list[1].selected = true;
        list[1].defaultSelected = true;
    } else if (value == "Window Clings") {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = four;
        list[5] = five;
        list[6] = six;
    } else if (value == "Vinyl Decal") {
        list[0] = pick1;
    } else {
        list[0] = pick1;
        list[1] = one;
        list[2] = two;
        list[3] = three;
        list[4] = four;
        list[5] = five;
        list[6] = six;
        list[7] = full;
    }
    var f = document.forms["OrderForm"];
    var menu = f.elements["Inks"];
    menu.options.length = 0;
    for(i = 0; i < list.length; i++) {
        menu.options[i] = list[i];
    }
}

function checkSTStock(product) {
    var f = document.forms["OrderForm"];
    var i = product.selectedIndex;
    var value = product.options[i].value;
    if (value == "Foil Labels") {
        f.elements["Detail"].disabled = false;
        var list = new Array()
        list[0] = new Array(0,"Select Foil Color")
        list[1] = new Array("Gold","Gold")
        list[2] = new Array("Silver","Silver")
        setOptions(f.elements["Detail"], list)
    } else if (value == "Paper Labels") {
        f.elements["Detail"].disabled = false;
        var list = new Array()
        list[0] = new Array(0,"Select Paper Finish")
        list[1] = new Array("Gloss","Gloss")
        list[2] = new Array("Matte","Matte")
        setOptions(f.elements["Detail"], list)
    }  else if (value == "Bumper Stickers") {
        f.elements["Detail"].disabled = false;
        var list = new Array()
        list[0] = new Array(0,"Select Stock")
        list[1] = new Array("White Vinyl","White Vinyl")
        list[2] = new Array("Clear Vinyl","Clear Vinyl")
        setOptions(f.elements["Detail"], list)
    } else {
        f.elements["Detail"].options.length = 0
        f.elements["Detail"].disabled = true;
    }
    if (value == "Window Clings") {
        hideBox('color_swatches');
        hideBox('clear_color_swatches');
        showBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        hideBox('peelhere');
        showTableRow('Inks_Note');
        showTableRow('Inks_Row');
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        showListItem('Ink_Colors_4');
        showListItem('Ink_Colors_5');
        showListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "Vinyl Decal") {
        hideBox('color_swatches');
        hideBox('clear_color_swatches');
        hideBox('windowcling_color_swatches');
        showBox('cutvinyldecals_color_swatches');
        hideBox('peelhere');
        hideTableRow('Inks_Note');
        hideTableRow('Inks_Row');
        hideListItem('Ink_Colors_1');
        hideListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        showListItem('Decal_Color');
    } else if (value == "Magnets") {
        hideBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        hideBox('clear_color_swatches');
        hideBox('color_swatches');
        hideBox('peelhere');
        hideTableRow('Inks_Note');
        showTableRow('Inks_Row');
        hideListItem('Ink_Colors_1');
        hideListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "EcoGreen Stickers") {
        hideBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        hideBox('clear_color_swatches');
        hideBox('color_swatches');
        showBox('peelhere');
        hideTableRow('Inks_Note');
        showTableRow('Inks_Row');
        hideListItem('Ink_Colors_1');
        hideListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "Bumper Stickers") {
        hideBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        showBox('clear_color_swatches');
        hideBox('color_swatches');
        hideBox('peelhere');
        showTableRow('Inks_Note');
        showTableRow('Inks_Row');
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        showListItem('Ink_Colors_4');
        showListItem('Ink_Colors_5');
        showListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "Clear Stickers") {
        hideBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        showBox('clear_color_swatches');
        hideBox('color_swatches');
        hideBox('peelhere');
        showTableRow('Inks_Note');
        showTableRow('Inks_Row');
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else {
        hideBox('windowcling_color_swatches');
        hideBox('cutvinyldecals_color_swatches');
        hideBox('clear_color_swatches');
        showBox('color_swatches');
        hideBox('peelhere');
        showTableRow('Inks_Note');
        showTableRow('Inks_Row');
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    }
    updateSTShapeOptions(value);
    updateSTColorOptions(value);
}

function checkSTInks(inks)
{
    var f = document.forms["OrderForm"]
    var value = inks.options[inks.selectedIndex].value;
    if (value == "1 Color") {
        showListItem('Ink_Colors_1');
        hideListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "2 Color") {
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "3 Color") {
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "4 Color") {
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        showListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "5 Color") {
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        showListItem('Ink_Colors_4');
        showListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "6 Color") {
        showListItem('Ink_Colors_1');
        showListItem('Ink_Colors_2');
        showListItem('Ink_Colors_3');
        showListItem('Ink_Colors_4');
        showListItem('Ink_Colors_5');
        showListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else if (value == "Full Color") {
        hideListItem('Ink_Colors_1');
        hideListItem('Ink_Colors_2');
        hideListItem('Ink_Colors_3');
        hideListItem('Ink_Colors_4');
        hideListItem('Ink_Colors_5');
        hideListItem('Ink_Colors_6');
        hideListItem('Decal_Color');
    } else {
    }
}

function setOptions(menu, list) {
    //alert(list.length)
    menu.options.length = 0

    for(i = 0; i < list.length; i++) {
        menu.options[i] = new Option(list[i][1], list[i][0])
    }
}

function toggleRushDate(s) {
    if(s == 'off') {
        killBox('In_Hands_By_Date')
    } else {
        activateBox('In_Hands_By_Date')
    }
}

function changeShippingAddress(v) {
    if (typeof(CustomerShippingAddresses[v]) != 'undefined') {
        document.forms[0].elements['Shipping_Recipient'].value = CustomerShippingAddresses[v]['recipient'];
        document.forms[0].elements['Shipping_Dept'].value      = CustomerShippingAddresses[v]['dept'];
        document.forms[0].elements['Shipping_Business'].value  = CustomerShippingAddresses[v]['company'];
        document.forms[0].elements['Shipping_Address'].value   = CustomerShippingAddresses[v]['address1'];
        document.forms[0].elements['Shipping_Address2'].value  = CustomerShippingAddresses[v]['address2'];
        document.forms[0].elements['Shipping_City'].value      = CustomerShippingAddresses[v]['city'];
        document.forms[0].elements['Shipping_State'].value     = CustomerShippingAddresses[v]['state'];
        document.forms[0].elements['Shipping_Zip_Code'].value  = CustomerShippingAddresses[v]['postalCode'];
        document.forms[0].elements['Shipping_Country'].value   = CustomerShippingAddresses[v]['country'];
        document.forms[0].elements['Shipping_Phone'].value     = CustomerShippingAddresses[v]['phone'];
        document.forms[0].elements['Shipping_Phone_Ext'].value = CustomerShippingAddresses[v]['ext'];
        killPopUp('Shipping_New_Label');
    } else {
        document.forms[0].elements['Shipping_Recipient'].value = '';
        document.forms[0].elements['Shipping_Dept'].value      = '';
        document.forms[0].elements['Shipping_Business'].value  = '';
        document.forms[0].elements['Shipping_Address'].value   = '';
        document.forms[0].elements['Shipping_Address2'].value  = '';
        document.forms[0].elements['Shipping_City'].value      = '';
        document.forms[0].elements['Shipping_State'].value     = '';
        document.forms[0].elements['Shipping_Zip_Code'].value  = '';
        document.forms[0].elements['Shipping_Country'].value   = 'United States';
        document.forms[0].elements['Shipping_Phone'].value     = '';
        document.forms[0].elements['Shipping_Phone_Ext'].value = '';
        activatePopUp('Shipping_New_Label');
    }
}

function toggleShippingAddress(b) {

    if(b.checked) {
        killBox('Shipping_Label')
        killBox('Shipping_Recipient')
        killBox('Shipping_Dept')
        killBox('Shipping_Business')
        killBox('Shipping_Address')
        killBox('Shipping_Address2')
        killBox('Shipping_City')
        killPopUp('Shipping_State')
        killBox('Shipping_Zip_Code')
        killPopUp('Shipping_Country')
        killPopUp('Shipping_Phone')
        killPopUp('Shipping_Phone_Ext')
    } else {
        activateBox('Shipping_Label')
        activateBox('Shipping_Recipient')
        activateBox('Shipping_Dept')
        activateBox('Shipping_Business')
        activateBox('Shipping_Address')
        activateBox('Shipping_Address2')
        activateBox('Shipping_City')
        activatePopUp('Shipping_State')
        activateBox('Shipping_Zip_Code')
        activatePopUp('Shipping_Country')
        activateBox('Shipping_Phone')
        activateBox('Shipping_Phone_Ext')
    }
}

function togglePickup(b) {

    if(b.checked) {
        killPopUp('Shipping_Type')
        killPopUp('Shipping_Carrier')
        killBox('Shipping_Account_Number')
        killBox('Shipping_Label')
        killBox('Shipping_Recipient')
        killBox('Shipping_Dept')
        killBox('Shipping_Business')
        killBox('Shipping_Address')
        killBox('Shipping_Address2')
        killBox('Shipping_City')
        killPopUp('Shipping_State')
        killBox('Shipping_Zip_Code')
        killPopUp('Shipping_Country')
        killPopUp('Shipping_Phone')
        killPopUp('Shipping_Phone_Ext')
        killPopUp('Shipping_New_Label');
    } else {
        activatePopUp('Shipping_Type')
        activatePopUp('Shipping_Carrier')
        activateBox('Shipping_Account_Number')
        activateBox('Shipping_Label')
        activateBox('Shipping_Recipient')
        activateBox('Shipping_Dept')
        activateBox('Shipping_Business')
        activateBox('Shipping_Address')
        activateBox('Shipping_Address2')
        activateBox('Shipping_City')
        activatePopUp('Shipping_State')
        activateBox('Shipping_Zip_Code')
        activatePopUp('Shipping_Country')
        activatePopUp('Shipping_Phone')
        activatePopUp('Shipping_Phone_Ext')
        activatePopUp('Shipping_New_Label');
    }
}


function stockPref(type,name,sizes,brand,fabric){
    this.type = type
    this.name = name
    this.sizes = sizes.split("|")
    this.brand = brand.split("|")
    this.fabric = fabric.split("|")

}

function checkProofing(field) {

    choice = field.options[field.selectedIndex].value
    switch (choice) {
        case 0:
            return alert("You need to pick some proofing")
        break;

        case "No Proof":
            return alert("Selecting No Proof means that files are printed as is with no assurance of color accuracy. Request a hard copy proof if color accuracy is critical.")
        break;

        case "Digital Proof":

            return alert("Free of charge (3-4 additional days) these will be sent via email to your main email contact. You must reply to the email with approval. If we received two email addresses, we will send it to both and proceed upon receiving the first approval. These are NOT for color-matching and are only for the purposes of confirming that your files have arrived uncorrupted and opened properly on our end. If you have ANY color concerns, you MUST purchase a hardcopy color proof. If you do not opt to receive a hardcopy color proof, Jakprints will NOT be responsible for ANY color variance or file errors (minor or major) that may occur.")

        break;

        case "Hard Copy Proof":
            return alert("Additional charge (3-4 additional days) This will be sent via UPS to your shipping address. You must return the proof with the signed approval slip for us to proceed with the job. This is REQUIRED for color-matching. If you do NOT opt for a Hardcopy Proof, Jakprints will not be responsible for any color shifts or file errors (minor or major) that may occur. We do not accept customer supplied printouts for color reference. We will only allow proofs back to our pressroom that we have generated on our color-calibrated equipment.")
        break;
    }
}

function checkSTProofing(field) {

    choice = field.options[field.selectedIndex].value
    switch (choice) {
        case 0:
            return false;
            break;

        case "No Proof":
            return alert("Selecting No Proof means that files are printed as is with no assurance of color accuracy.")
            break;

        case "Digital Proof":
            return alert("Free of charge (3-4 additional days) these will be sent via email to your main email contact. You must reply to the email with approval. If we received two email addresses, we will send it to both and proceed upon receiving the first approval. These are NOT for color-matching and are only for the purposes of confirming that your files have arrived uncorrupted and opened properly on our end.")
            break;
    }
}

function setProduct() {
    //set the brands menu
    //set the colors link
    //set the size boxes
}


function remove(child,parent,cmd) {
    if(confirm('Are you sure you want to remove '+child+' from '+parent+'?')) {
        formAction(cmd)
    }
}


function formAction(f,action) {

    alert("The form is: "+f.name+"\nThe action is: "+action)
    f.action = "?action="+action
    f.submit()
}


function val_contest(f) {
    errorText = ""
    errorMessage = ""
    f = document.forms[f]
    //alert('Checking sample request...')

    if(IsEmpty(f.first)) errorText = errorText + "-Your first name is missing.\n"
    if(IsEmpty(f.last)) errorText = errorText + "-Your last name is missing.\n"
    if(IsEmpty(f.phone)) {
        if(!IsEmailValid("contest", "email")) errorText = errorText + "-Please enter an email address or phone number\n"
    } else {
        if(!IsEmpty(f.email)) {
            if(!IsEmailValid("contest", "email")) errorText = errorText + "-Your email address is incorrect\n"
        }
    }

    if(IsEmpty(f.street)) errorText = errorText + "-Your street address is missing\n"
    if(IsEmpty(f.city)) errorText = errorText + "-Your city is missing\n"
    if(!checkPopUp(f.state)) errorText = errorText + "-Select a state\n"
    if(IsEmpty(f.zip)) errorText = errorText + "-Your zip is missing\n"

    if(errorText) {
         errorMessage = "Your entry cannot be sent.\n\n"+errorText+"\n\nPlease correct your form and resubmit your entry. Thanks!"
        alert(errorMessage)
        return false
    } else {
        return true
    }
}


function val_file(fp, ext, filenum, form) {
    errors = ''

    //find the last period
    period_position = fp.lastIndexOf('.')
    extLength = fp.length - period_position
    //alert('the period on '+filenum+' is '+extLength)

    if(extLength > 6) errors += '-Rename File '+filenum+' to include the proper 3 letter extension\r\n'

    //extract the extension from the filename
    extension =''
    for(i = extLength; i >= 1; i--) {
        extension += fp.charAt(fp.length - i)
    }

    //Validate the extension against the array of extensions set above
    extension = extension.toLowerCase()
    valid=0
    for(i=0; i <= ext.length; i++) {
        if(extension == ext[i]) {
            valid++
        }
    }

    if(!valid && !errors) {
        errors += '-Unacceptable file format on File '+filenum+'.\r\n'
    }

    //alert(errors)
    return errors

}


function val_uploadInfo() {
    errorText = ""
    f = document.forms[0]
    //alert('checking info');

    if(IsEmpty(f.oid)) {
        alert("Please enter an Order ID to upload files.\n")
        return false
    } else {
        //alert('all good')
        return true
    }

}


function val_upload() {
    f = document.forms['upload']
    valid_ext = '.tif|.tiff|.jpg|.jpeg|.psd|.eps|.pdf|.qxd|.ind|.indd|.ai|.fh|.zip|.sit|.sitx|.cpt|.gz|.tar'
    extensions = valid_ext.split('|')
    missingFiles = 0
    //alert('Validating...')
    errorText = ''

    for(j = 1; j <= f.numfiles.value; j++) {
        filepath = f.elements['file'+j].value
        if(filepath != 0) {
            errorText += val_file(filepath, extensions, j, document.forms['upload'])
        } else {
            missingFiles++
        }

    }


    if(errorText) {
        alert('Please correct the following:\r\n'+errorText)
        return false;
    } else {

        if(missingFiles == f.elements['numfiles'].value) {
            alert('No files were set to upload')
            return false;
        } else {
            alert('Uploading will begin when you click OK.\n\nPlease do not close your web browser or leave this page until your files are received. This can take a long time depending on the size of your file(s) and your internet connection.')
            document.images['uploading'].src = uploading_on.src
            return true;
        }
    }

}






function val_contact(f) {
    errorText = ""
    errorMessage = ""
    f = document.forms[f]

    if(IsEmpty(f.first)) errorText = errorText + "-Your first name is missing.\n"
    if(IsEmpty(f.last)) errorText = errorText + "-Your last name is missing.\n"
    if(IsEmpty(f.phone)) {
        if(!IsEmailValid("contact", "email")) errorText = errorText + "-We need a valid email address or phone number to respond.\n"
    } else {
        if(!IsEmpty(f.email)) {
            if(!IsEmailValid("contact", "email")) errorText = errorText + "-Your email address is incorrect.\n"
        }
    }


    if(IsEmpty(f.comment)) errorText = errorText + "-Include a comment or question to Jakprints\n"

    if(errorText) {
         errorMessage = "Your message cannot be sent.\n\n"+errorText+"\n\nPlease correct your form and resubmit your message. Thanks!"
        alert(errorMessage)
        return false
    } else {
        return true
    }
}


function val_samples(f) {
    errorText = ""
    errorMessage = ""
    formname = f
    f = document.forms[f]
    //alert('Checking sample request...')

    if(IsEmpty(f.first)) errorText = errorText + "-Your first name is missing.\n"
    if(IsEmpty(f.last)) errorText = errorText + "-Your last name is missing.\n"
    if(IsEmpty(f.phone)) {
        if(!IsEmailValid(formname, "email")) errorText = errorText + "-Please enter an email address or phone number\n"
    } else {
        if(!IsEmpty(f.email)) {
            if(!IsEmailValid(formname, "email")) errorText = errorText + "-Your email address is incorrect\n"
        }
    }

    if(IsEmpty(f.street)) errorText = errorText + "-Your street address is missing\n"
    if(IsEmpty(f.city)) errorText = errorText + "-Your city is missing\n"
    if(!checkPopUp(f.state)) errorText = errorText + "-Select a state\n"
    if(IsEmpty(f.zip)) errorText = errorText + "-Your zip is missing\n"

    if(errorText) {
         errorMessage = "Your sample request cannot be sent.\n\n"+errorText+"\n\nPlease correct your form and resubmit your message. Thanks!"
        alert(errorMessage)
        return false
    } else {
        return true
    }
}


function order(dept,type) {
    f = document.forms['terms']
    errorText = ''

    if(!IsBoxChecked('terms','confirm'))  errorText = errorText + "You must first Agree to the Terms and Conditions\n"

    if(errorText) {
        alert(errorText)
    } else {
        //alert('The shit is checked')
        f.elements['t'].value = type
        f.elements['d'].value = dept
        f.submit()
        return true
    }

}

function val_TC(f) {
    errorText = ""
    errorMessage = ""

    if(!f) {
        f = 0
    }

    if(!IsRadioChecked(f,'t'))  errorText = errorText + "-Specify Order or Quote\n"
    if(!IsBoxChecked(f,'confirm'))  errorText = errorText + "-You must first Agree to the Terms and Conditions\n"

    if(errorText) {
         errorMessage = "Please correct the following missing or incorrect information:\n\n"+errorText
        alert(errorMessage)
        return false
    } else {
        return true
    }
}



/*
function val_AP(f) {
    errorText = ""
    errorMessage = ""

    //Check Billing/Contact info...
    if(IsEmpty(f.firstname)) errorText = errorText + "-First Name\n"
    if(IsEmpty(f.lastname)) errorText = errorText + "-Last Name\n"
    if(IsEmpty(f.company)) errorText = errorText + "-Company Name\n"
    if(IsEmpty(f.street)) errorText = errorText + "-Street Address\n"
    if(IsEmpty(f.city)) errorText = errorText + "-City\n"
    if(IsEmpty(f.state)) errorText = errorText + "-State/Province\n"
    if(IsEmpty(f.zip)) errorText = errorText + "-Zip/Postal Code\n"
    if(IsEmpty(f.country)) errorText = errorText + "-Country\n"
    if(IsEmpty(f.phone)) errorText = errorText + "-Phone Number\n"
    if(!IsEmailValid("reg_form", "email")) errorText = errorText + "-Email address is missing or incorrect\n"
    if(!IsRadioChecked('busType'))  errorText = errorText + "-Specify Business Type\n"

    if(f.total.value != "$0.00") {
        if(!checkPopUp(f.cardType)) errorText = errorText + "-Credit Card Type\n"
        if(IsEmpty(f.cardName)) errorText = errorText + "-Your name off your Credit Card\n"
        if(!checkCCNum(f.cardNumber.value.length)) errorText = errorText + "-Your Card Number\n"
        if(!checkPopUp(f.cc_month)) errorText = errorText + "-Card Expiration Month\n"
        if(!checkPopUp(f.cc_year)) errorText = errorText + "-Card Expiration Year\n"
    }

    if(errorText) {
         errorMessage = "Please correct the following missing or incorrect information:\n\n"+errorText
        alert(errorMessage)
        return false
    } else {
        return true
    }
}*/


//Utility functions...
//Everything below is a standard block for checking form elements for different types of data

function activateRadio(r) {
    radioGroup = document.forms[0].elements[r]
    for (i = 0; i < radioGroup.length; i++) {
        radioGroup[i].disabled = false
    }
}

function killRadio(r)  {
    radioGroup = document.forms[0].elements[r]
    for (i = 0; i < radioGroup.length; i++) {
        radioGroup[i].checked = false
        radioGroup[i].disabled = true
    }
}

function killBox(b)  {
    document.forms[0].elements[b].value = ""
    document.forms[0].elements[b].disabled = true
}

function killPopUp(b)  {
    document.forms[0].elements[b].selectedIndex = 0
    document.forms[0].elements[b].disabled = true
}

function killCheckBox(b)  {
    document.forms[0].elements[b].disabled = true
}

function activateBox(b)  {
    document.forms[0].elements[b].disabled = false
}

function activatePopUp(b)  {
    document.forms[0].elements[b].disabled = false
}

function activateCheckBox(b)  {
    document.forms[0].elements[b].disabled = false
}

function setRadio(r,v) {
    f = document.forms[0]
    f.elements[r][v].checked = true
}

function checkPopUp(p) {
    var thePopUp = p
    var i = thePopUp.selectedIndex
    if(thePopUp[0].selected) {
        return false
    } else {
        if(thePopUp[i].value == 0) {
            return false
        } else {
            return true
        }
    }
}

// -----------------------------------------------------------------
// Function    : IsEmailValid
// Language    : JavaScript
// Description : Checks if given email address is of valid syntax
// Copyright   : (c) 1998 Shawn Dorman
// http://www.goodnet.com/~sdorman/web/IsEmailValid.html
// -----------------------------------------------------------------
// Ver    Date    Description of modification
// --- ---------- --------------------------------------------------
// 1.0 09/04/1996 Original write
// 1.1 09/30/1998 CHG: Use standard header format
// -----------------------------------------------------------------
// Source: Webmonkey Code Library
// (http://www.hotwired.com/webmonkey/javascript/code_library/)
// -----------------------------------------------------------------

function IsEmailValid(FormName,ElemName)
{
var EmailOk  = true
var Temp     = document.forms[FormName].elements[ElemName]
var AtSym    = Temp.value.indexOf('@')
var Period   = Temp.value.lastIndexOf('.')
var Space    = Temp.value.indexOf(' ')
var Length   = Temp.value.length - 1   // Array is from 0 to length-1

if ((AtSym < 1) ||                     // '@' cannot be in first position
    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
    (Period == Length ) ||             // Must be atleast one valid char after '.'
    (Space  != -1))                    // No empty spaces permitted
   {
      EmailOk = false
   }
return EmailOk
}


function IsEmpty(v) {
    if (typeof(v) != 'undefined' && !v.value) {
        return true
    } else {
        return false
    }
}

function checkCCNum(l) {
    n = l
    f = document.forms[0]
    if(f.cardType[4].selected) {
        if(n == 15) {
            return true
         } else {
            return false
         }
    } else {
        if(n == 16) {
            return true
         } else {
            return false
         }
    }
}


function IsRadioChecked(f,r) {
    var radioGroup = document.forms[f].elements[r]
    for (i = 0; i < radioGroup.length; i++) {
        if(radioGroup[i].checked) {
            return true

        }
    }
}

function IsBoxChecked(f,b) {
    if(document.forms[f].elements[b].checked) {
        return true
    }
}


function format (v, decplaces) {
    var str = "" + Math.round (eval(v) * Math.pow(10,decplaces))
    while (str.length <= decplaces) {
        str = "0" + str
    }
    var decpoint = str.length - decplaces
    return str.substring(0, decpoint) + "." + str.substring(decpoint,str.length);
}

function dollarize (v) {
        return "$" + format(v,2)
}


function checkCardNumWithMod10(cardNum) {
    var i;
    var cc = new Array(16);
    var checksum = 0;
    var validcc;

    // assign each digit of the card number to a space in the array
    for (i = 0; i < cardNum.length; i++) {
        cc[i] = Math.floor(cardNum.substring(i, i+1));
    }

    // walk through every other digit doing our magic
    // if the card number is sixteen digits then start at the
    // first digit (position 0), otherwise start from the
    // second (position 1)
    for (i = (cardNum.length % 2); i < cardNum.length; i+=2) {
        var a = cc[i] * 2;
        if (a >= 10) {
            var aStr = a.toString();
            var b = aStr.substring(0,1);
            var c = aStr.substring(1,2);
            cc[i] = Math.floor(b) + Math.floor(c);
        } else {
            cc[i] = a;
        }
    }

    // add up all of the digits in the array
    for (i = 0; i < cardNum.length; i++) {
        checksum += Math.floor(cc[i]);
    }

    // if the checksum is evenly divisble by 10
    // then this is a valid card number
    validcc = ((checksum % 10) == 0);

    return validcc;
}

function cleanCardNum(cardNum) {
    var i;
    var ch;
    var newCard = "";

    // walk through the string character by character to build
    // a new string with numbers only
    i = 0;
    while (i < cardNum.length) {
        // get the current character
        ch = cardNum.substring(i, i+1);
        if ((ch >= "0") && (ch <= "9")) {
            // if the current character is a digit then add it
            // to the numbers-only string we're building
            newCard += ch;
        } else {
            // not a digit, so check if its a dash or a space
            if ((ch != " ") && (ch != "-")) {
                // not a dash or a space so fail
                return false;
            }
        }
        i++;
    }

    // we got here if we didn't fail, so return what we built
    return newCard;
}

function checkCard(cardType, cardNum) {
    var validCard;
    var cardLength;
    var cardLengthOK;
    var cardStart;
    var cardStartOK;

    // check if the card type is valid
    if ((cardType != "Visa") && (cardType != "Mastercard") && (cardType != "American Express") && (cardType != "Discover")) {
        msg = "Please select a card type.";
        return msg;
    }

    // clean up any spaces or dashes in the card number
    //validCard = cleanCardNum(cardNum);
    validCard = cardNum;

    if (validCard != "") {
        // check the first digit to see if it matches the card type
        cardStart = validCard.substring(0,1);
        cardStartOK = ( ((cardType == "Visa") && (cardStart == "4")) ||
                ((cardType == "Mastercard") && (cardStart == "5")) ||
                ((cardType == "American Express") && (cardStart == "3")) ||
                ((cardType == "Discover") && (cardStart == "6")) );
        if (!(cardStartOK)) {
            // card number's first digit doesn't match card type
            msg = "Please make sure the card number you've entered matched the card type you selected.";
            return msg;
        }

        // the card number is good now, so check to make sure
        // it's a the right length
        cardLength = validCard.length;
        cardLengthOK = ( ((cardType == "Visa") && ((cardLength == 13) || (cardLength == 16))) ||
                 ((cardType == "Mastercard") && (cardLength == 16)) ||
                 ((cardType == "American Express") && (cardLength == 15)) ||
                 ((cardType == "Discover") && (cardLength == 16)) );
        if (!(cardLengthOK)) {
            // not the right length
            msg = "Please make sure you've entered all of the digits on your card.";
            return msg;
        }

        // card number seems OK so do the Mod10
        if (checkCardNumWithMod10(validCard)) {
            return false;
        } else {
            msg = "Please make sure you've entered your card number correctly.";
            return msg;
        }
    } else {
        return msg;
    }
}

function checkCardCVV(cardType, cardCVV) {
    var cvvLength;
    var cvvLengthOK;
    var msg;

    // check if the card type is valid
    if ((cardType != "Visa") && (cardType != "Mastercard") && (cardType != "American Express") && (cardType != "Discover")) {
        msg = "Please select a card type.";
        return msg;
    }

    // check to make sure it's a the right length
    cvvLength = cardCVV.length;
    cvvLengthOK = ( ((cardType == "Visa") && (cvvLength == 3)) ||
             ((cardType == "Mastercard") && (cvvLength == 3)) ||
             ((cardType == "American Express") && (cvvLength == 4)) ||
             ((cardType == "Discover") && (cvvLength == 3)) );
    if (!(cvvLengthOK)) {
        // not the right length
        msg = "Please make sure you've entered the correct Card Verification Number.";
        return msg;
    }
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) {
        strDay=strDay.substring(1)
    }
    if (strMonth.charAt(0)=="0" && strMonth.length>1) {
        strMonth=strMonth.substring(1)
    }
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) {
            strYr=strYr.substring(1)
        }
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        return "Format should be : mm/dd/yyyy"
    }
    if (strMonth.length<1 || month<1 || month>12){
        return "Please enter a valid month"
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        return "Please enter a valid day"
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        return "Please enter a valid 4 digit year between "+minYear+" and "+maxYear
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        return "Please enter a valid date"
    }
return false
}


 /**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;


function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateForm(){
    var Phone=document.frmSample.txtPhone

    if ((Phone.value==null)||(Phone.value=="")){
        alert("Please Enter your Phone Number")
        Phone.focus()
        return false
    }
    if (checkInternationalPhone(Phone.value)==false){
        alert("Please Enter a Valid Phone Number")
        Phone.value=""
        Phone.focus()
        return false
    }
    return true
 }


function getDOMElement (elementID)
{
    if(document.getElementById){
        return document.getElementById(elementID);
    } else if (document.all) {
        return document.all.namedItem(elementID);
    } else {
        //alert('the browser you are using is trash.');
        return null;
    }
}

function hideBox(whichBox) {
    thisBox = getDOMElement(whichBox);
    if (thisBox !== null) {
        thisBox.style['visibility'] = 'hidden';
        thisBox.style['display']    = 'none';
    }
}

function showBox(whichBox) {
    thisBox = getDOMElement(whichBox);
    if (thisBox !== null) {
        thisBox.style['visibility'] = 'visible';
        thisBox.style['display']    = 'block';
    }
}

function hideListItem(whichBox) {
    hideBox(whichBox);
}

function showListItem(whichBox) {
    thisBox = getDOMElement(whichBox);
    if (thisBox !== null) {
        thisBox.style['visibility'] = 'visible';
        thisBox.style['display']    = 'list-item';
    }
}

function hideTableRow(whichBox) {
    hideBox(whichBox);
}

function showTableRow(whichBox) {
    thisBox = getDOMElement(whichBox);
    if (thisBox !== null) {
        thisBox.style['visibility'] = 'visible';
        thisBox.style['display']    = 'table-row';
    }
}

function toggleBox(whichBox) {
    thisBox = getDOMElement(whichBox);
    if (thisBox.style.visibility != 'hidden') {
        hideBox(whichBox);
    } else {
        showBox(whichBox);
    }
}

function enableInput(whichInput) {
    thisInput = getDOMElement(whichInput);
    thisInput.disabled = '';
}

function disableInput(whichInput) {
    thisInput = getDOMElement(whichInput);
    thisInput.disabled = 'disabled';
}

function toggleDisabledInput(catalyst, whichInput) {
    thisInput = getDOMElement(whichInput);
    if (catalyst == true) {
        enableInput(whichInput);
    } else {
        disableInput(whichInput);
    }
}
