$(document).ready( function () {
    $(".navmenuitem").hover(
      function () {
        $(this).addClass('navmenuitemHover');
      }, 
      function () {
        $(this).removeClass('navmenuitemHover');
      }
    );
    if ($("#getstartedbutton").length >= 1)
    {
        $("#getstartedbutton").hover(
        function () {
            $(this).addClass('getstartedbuttonHover');
        }, 
        function () {
            $(this).removeClass('getstartedbuttonHover');
        }
    );
    }
    // Are we on a page to buy something? Perhaps just a form?
    if ($("#Order").length >= 1 || $("#Submit").length >= 1)
    {
        $("form").submit(validateinfusionform);
        $("form tr.forminputrow").children("td").css({
            "backgroundColor": "white",
            "border-top": "1px solid white",
            "border-bottom": "1px solid white"
        });
        // After user has filled in all forms
        // they will see a thank-you page, we
        // are storing some data in cookies to
        // grab at that time
        if ($("#Order").length >= 1)
        {
            // set purchase type in cookie
            //var purchase_type = $("body h1").html();
            //$.cookie('PurchaseType',purchase_type.substr(0,purchase_type.indexOf(" ")));
            
            // set purchase price in cookie
            //var purchase_price = $("#PayTotal_A").attr('value');
            //$.cookie('PurchasePrice',purchase_price);
        }
    }
    // This mess is what moves the gray
    // bar as focus changes on form-inputs
    if ($(":input").length >= 1)
    {
        $(":input").addClass("unfocusedtd");
        $(":input").focus(function () {
                $curr = $(this);
                var labeltd = $curr.parents("tr.forminputrow");
                labeltd.children("td").css({
                    "backgroundColor": "whitesmoke",
                    "border-top": "1px solid Gainsboro",
                    "border-bottom": "1px solid Gainsboro"
                    });
                $(this).removeClass('invalidphonefaxdata');
                $(this).removeClass('missingfielddata');
                $(this).removeClass('unfocusedtd');
                $(this).addClass('focusedtd');
                
            });
        $(":input").blur(function () {
                $curr = $(this);
                var labeltd = $curr.parents("tr.forminputrow");
                labeltd.children("td").css({
                    "backgroundColor": "white",
                    "border-top": "1px solid white",
                    "border-bottom": "1px solid white"
                    });
                $(this).removeClass('focusedtd');
                $(this).addClass('unfocusedtd');
            });
    }
    
    // Final sale-forms thank-you page ... just wanting to
    // display what/how-much they purchased.
    if($(".purchase_package_display") && $(".purchase_price_display"))
    {
        $(".purchase_package_display").html($.cookie('PurchaseType'));
        $(".purchase_price_display").html($.cookie('PurchasePrice'));
    }
});

var numberofmissingfields       = 0;
var numberofbadphonefaxfields   = 0;
var numberofbademailfields      = 0;

function validateinfusionform () {
    var wehavemissingfields = null;
    var wehavebadphonefaxfields = null;
    
    $(".sale-label-req :input, .sale-select-req, .sale-text-req").each (function (i,requiredfield) {
        if(requiredfield.value.toString() == '' || requiredfield.value == null) {
            $(this).addClass('missingfielddata');
            wehavemissingfields = true;
            numberofmissingfields ++;
        }
    });
    
    // On 'info' pages, there is need to require the checkboxes
    // The checkboxes are in a td with class 'sale-label-req' and
    // are surrounded (along with text) by a div to latch color/border onto.
    var missingboxes = false;
    var numberofmissingboxes = 0;
    if($("td.sale-label-req :checkbox"))
    {
        $("td.sale-label-req :checkbox").each (function (i,currcheckbox) {
            if (!this.checked)
            {
                $(this).parent("div").addClass('missingfielddata');
                missingboxes = true;
                numberofmissingboxes++;
            }
        });
        if (missingboxes)
        {
            var alertstr = "Required: "+numberofmissingboxes+" required checkboxes need to be selected.";
            setTimeout("alert('"+alertstr+"')", 300);
            missingboxes = false;
            numberofmissingboxes = 0;
            return false;
        }
    }
    
    // validate creditcard number
    var missingcc = false;
    if($("#CreditCard0CardNumber_data").length >= 1)
    {
        if ($("#CreditCard0CardNumber_data table tr td input").attr('value') == "" ||
            $("#CreditCard0CardNumber_data table tr td input").attr('value') == null)
        {
            setTimeout("alert('Missing Credit Card Number!')", 300);
            $("#CreditCard0CardNumber_data table tr td input").addClass('missingfielddata');
            missingcc = true;
        }
        if (!missingcc && !validateCreditCard($("#CreditCard0CardNumber_data table tr td input").attr('value')))
        {
            setTimeout("alert('Invalid Credit Card number!')", 300);
            $("#CreditCard0CardNumber_data table tr td input").addClass('missingfielddata');
            missingcc = true;
        } 
    }
    
    // validate email field
    // infusion tags with names containing 'Email'
    wehavebademailfields = false;
    if ($(":input[name*='Email']").length >= 1)
    {
        $(":input[name*='Email']").each(function (i) {
            if (this.value == null || this.value == "")
            {
                $(this).addClass('missingfielddata');
                numberofmissingfields++;
            }
            else if(!validemailaddress(this.value))
            {
                $(this).addClass("missingfielddata");
                numberofbademailfields++;
                wehavebademailfields = true;
            }
        });
    }
    
    // validate phone/fax fields
    // infusion tags with names containing 'Phone' and 'Fax'
    wehavebadphonefaxfields = false;
    if ($(":input[name*='Fax']").length >= 1)
    {
        $(":input[name*='Fax']").each(function (i) {
            if (!validphonefax(this.value))
            {
                $(this).addClass("invalidphonefaxdata");
                numberofbadphonefaxfields++;
                wehavebadphonefaxfields = true;
            }
            });
    }
    
    if ($(":input[name*='Phone']").length >= 1)
    {
        $(":input[name*='Phone']").each(function (i) {
            if(!validphonefax(this.value))
            {
                $(this).addClass("invalidphonefaxdata");
                numberofbadphonefaxfields++;
                wehavebadphonefaxfields = true;
            }
            });
    }
    
    if (wehavemissingfields == true || wehavebademailfields == true)
    {
        numberofmissingfields = numberofmissingfields + numberofbademailfields;
        setTimeout("togglewarning()",10);
        if(wehavebadphonefaxfields == true)
        {
            setTimeout("togglephonefaxwarning()",10);
        }
        return false;
    }
    else
    {
        /*if(wehavebadphonefaxfields == true)
        {
            setTimeout("togglephonefaxwarning()",10);
            return false;
        }*/
        return true;
    }
}

function togglewarning () {
    if ($('#fieldwarning').length >= 1)
    {
        $('#fieldwarning').remove();
        
    }
    $('#orderbuttontd').prepend('<p id="fieldwarning" style="border-top: 1px solid red; background-color: mistyrose; padding: 2em;"><b>REQUIRED: '+numberofmissingfields+' required fields were left blank or are not formatted correctly - please complete items in the above red boxes on this page.</b></p>');
    numberofmissingfields = 0;
    numberofbademailfields = 0;
    wehavemissingfields = false;
}
function togglephonefaxwarning () {
    if ($('#phonefaxwarning').length >= 1)
    {
        $('#phonefaxwarning').remove();
        
    }
    if ($('#fieldwarning').length >= 1)
    {
        $('#fieldwarning').after('<p id="phonefaxwarning" style="border-top: 1px solid #f78320; background-color: #ffe2c9; padding: 2em;"><b>OPTIONAL: '+numberofbadphonefaxfields+' phone or fax numbers are not valid - please complete items in the above orange boxes on this page.</b></p>');
        numberofbadphonefaxfields = 0;
        //wehavemissingfields = false;
    }
    else
    {
        $('#orderbuttontd').prepend('<p id="phonefaxwarning" style="border-top: 1px solid #f78320; background-color: #ffe2c9; padding: 2em;"><b>OPTIONAL: '+numberofbadphonefaxfields+' phone or fax numbers are not valid - you may ignore or complete items in the above orange boxes on this page.</b></p>');
        numberofbadphonefaxfields = 0;
        //wehavemissingfields = false;
    }
}

function togglelabeltdbackground (action) {
    if(action == 'focus')
    {
        $(this).addClass('focusedtd');
    }
    else
    {
        $(this).removeClass('focusedtd');
    }
}

function validphonefax(fld) {
    var error = "";
    var stripped = fld.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld == "") {
        error = "You didn't enter a phone number.\n";
        
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        
    }
    //return error;
    if (error == "")
    {
        return true;
    }
    else
    {
        return false;
    }
}

function validemailaddress(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
       //alert("Invalid E-mail ID")
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       //alert("Invalid E-mail ID")
       return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        //alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(at,(lat+1))!=-1){
        //alert("Invalid E-mail ID")
        return false
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        //alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(dot,(lat+2))==-1){
        //alert("Invalid E-mail ID")
        return false
    }
    
    if (str.indexOf(" ")!=-1){
        //alert("Invalid E-mail ID")
        return false
    }

    return true					
    }
