$(document).ready(function() {

    // Pre-form checks
    // If the selects are set at 'Other', show the Other text box
    if($('#type_of_work :selected').val() == 'Other')
    {
        $('#type_of_work').siblings(':last').show();
    }

    if($('#position :selected').val() == 'Other')
    {
        $('#position').siblings(':last').show();
    }

    if($('.holder-other input:checkbox').is('checked'))
    {
        $('#where_joint_compound_other').show();
    }

    //---------------------------------------------------------------------
    // START VALIDATION
    // --------------------------------------------------------------------

    // Default functionality for validation plugin
    $.validator.setDefaults({
        submitHandler: function (form){
            if(selIsValid())
            {
                $(form).ajaxSubmit({success:showResponse});
            }
        }
    });

    // Additional validation method for Phone #
    jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");
            return this.optional(element) || phone_number.length > 9 &&
                    phone_number.match(/^([2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, "Please specify a valid phone number");

    // Additional validation method for Other fields
    jQuery.validator.addMethod("otherTest", function(other_field, element) {
        return (($(element.parentNode).css('display') != 'none') && other_field == 'Other:') ? false : true;
    }, "This field is required");

    // validate form
    $("#sheetrockfrm").validate({
        invalidHandler: function(form, validator) {
            selIsValid();
        },
        rules: {
            'where_joint_compound[]': {
                required: true,
                maxlength: 2
            },
            phone: {
                required: true,
                phoneUS: true
            },
            position_other: {
                required: true,
                otherTest: true
            },
            type_of_work_other: {
                required: true,
                otherTest: true
            }
        }
    });



    // CHECKBOXES ONLY 2
    var grid_boxes = $('.checkbox-grid').find(':checkbox');
    var max_checked = 2;
    var cnt_checked = 0;

    $(grid_boxes).click(function()
    {
        // because the event fires before we can process it
        // we must set the inverse
        if(this.checked == false) // if was recently checked
        {
            cnt_checked--;

            // Special circumstance for other checkbox
            if($(this).hasClass('otherCheckbox'))
            {
                $('#where_joint_compound_other').hide().val('');
            }

            return true;
        }
        else if(this.checked == true && (cnt_checked != max_checked)) // if was recently unchecked
        {
            cnt_checked++;

            // Special circumstance for other checkbox
            if($(this).hasClass('otherCheckbox'))
            {
                $('#where_joint_compound_other').show();
            }
            
            return true;
        }
        else // falsify everything else
        {
            return false;
        }
    });

    // --------------------------------------------------------------------
    // END VALIDATION
    // --------------------------------------------------------------------

    // SELECT OTHERS
    $('input.other').focus(function(){
        $(this).addClass('other-active');

        if($(this).val() == 'Other:')
        {
            $(this).val('');
        }
    });

    $('input.other').blur(function(){
        if($(this).val() == '')
        {
            $(this).removeClass('other-active').val('Other:');
        }
    });

    // Type of Work, Position other input fields
    $('#type_of_work, #position').change(function()
    {
        // Get 'other' parent div
        var other_div = $(this).siblings(':last');

        if($(this).val() == 'Other')
        {
            // Show parent other div
            $(other_div).show();
        }
        else
        {
            // Hider parent div, find the other input field and change the text
            // back to "Other:", then remove the 'other-active' class
            $(other_div).hide().find(':first-child').val('Other:').removeClass('other-active');
        }
    });
});


// Determine if ranking order select dropdowns
// are valid (blank/ordered)
function selIsValid()
{
        //validate ranking order
        var selects = $('#ranking-order select');
        var valid = true;

        // Blank values
        $(selects).each(function(i, elem)
        {
            if(elem.value == '')
            {
                $(elem).parent().addClass('r-error');
                valid = false;
            }
            else
            {
                // put labels back to how they originally were
                $(elem).parent().removeClass('r-error');
            }
        });

        // (selections must be order/rank based), no duplicate values
        for(var x = 0; x < selects.length; x++)
        {
            $(selects).each(function(i, elem)
            {
                if((selects[x].value == elem.value) && x != i)
                {
                    $(elem).parent().addClass('r-error');
                    valid = false;
                }
            })
        }

        // display errors
        if( ! valid)
        {
            $('.ranking-error').text('All selections are required, using each number only once.').css('display', 'block');
        }
        else
        {
            $('.ranking-error').text('').css('display', 'none');
        }

        return valid;
}

// post-submit callback
function showResponse(responseText, statusText)
{
    //var url = (readCookie('srp_lang') == 'esp') ? '/esp/thankyou.php' : '/thankyou.php';

    if(responseText == 'saved')
    {
        // everything save properly, move to thank you
        window.location = '/thankyou.php';
    }
    else {
        //...
    }
}

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}