$(document).ready(function() {
    // We use the jQuery validator plugin to do input validation
    // http://docs.jquery.com/Plugins/Validation

    // call the validate method on our form, and pass in our explicit options
    $("#frmSubmitLoggedIn").validate({
        onkeyup:false,
        rules: {
            first_name: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            last_name: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            email: {
                required:true,
                email:true,
                maxlength:255,
                emailCheck:false,    // remote check for duplicate email address
            },
            city: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            state: {
                required:true,
                minlength:1,
                maxlength:100,
                validChars:true,
            },
            zip: {
                required:true,
                minlength:2,
                maxlength:20,
                validChars:true,
            },
            pet_name: {
                required:true,
                minlength:2,
                maxlength:45,
                validChars:true,
            },
            pet_type: {
                required:true
            },
            pet_story: {
                required:true
            },
            pet_listing_type: {
                required:true
            }
        },
        messages: {
            first_name: {
                required: "First Name is required.",
                minlength: jQuery.format("First Name must be at least {0} characters in length."),
                maxlength: jQuery.format("First Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            last_name: {
                required: "Last Name is required.",
                minlength: jQuery.format("Last Name must be at least {0} characters in length."),
                maxlength: jQuery.format("Last Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            email: {
                required: "Email Address is required.",
                email: "Email Address must be valid.",
                maxlength: jQuery.format("Email Address can not exceed {0} characters in length."),
                emailCheck:"<span class='navDrk'>Email Already Registered, <a href='/formSubmit.php?goToStep=1'>Login Here</a>.</span>"
            },
            city: {
                required: "City is required.",
                minlength: jQuery.format("City must be at least {0} characters in length."),
                maxlength: jQuery.format("City can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            state: {
                required: "State is required.",
                minlength: jQuery.format("State must be at least {0} characters in length."),
                maxlength: jQuery.format("State can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            zip: {
                required: "Zip is required.",
                minlength: jQuery.format("Zip must be at least {0} characters in length."),
                maxlength: jQuery.format("Zip can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            pet_name: {
                required: "Pet Name is required.",
                minlength: jQuery.format("Pet Name must be at least {0} characters in length."),
                maxlength: jQuery.format("Pet Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            pet_type: {
                required: "Pet Type is required."
            },
            pet_story: {
                required: "Pet Story is required."
            },
            pet_listing_type: {
                required: "Listing Type is required."
            }
        }
    });

    $("#frmSubmit").validate({
        onkeyup:false,
        rules: {
            first_name: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            last_name: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            email: {
                required:true,
                email:true,
                maxlength:255,
                emailCheck:true    // remote check for duplicate email address
            },
            city: {
                required:true,
                minlength:2,
                maxlength:100,
                validChars:true,
            },
            state: {
                required:true,
                minlength:1,
                maxlength:100,
                validChars:true,
            },
            zip: {
                required:true,
                minlength:2,
                maxlength:20,
                validChars:true,
            },
            pet_name: {
                required:true,
                minlength:2,
                maxlength:45,
                validChars:true,
            },
            pet_type: {
                required:true
            },
            pet_story: {
                required:true
            },
            pet_listing_type: {
                required:true
            }
        },
        messages: {
            first_name: {
                required: "First Name is required.",
                minlength: jQuery.format("First Name must be at least {0} characters in length."),
                maxlength: jQuery.format("First Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            last_name: {
                required: "Last Name is required.",
                minlength: jQuery.format("Last Name must be at least {0} characters in length."),
                maxlength: jQuery.format("Last Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            email: {
                required: "Email Address is required.",
                email: "Email Address must be valid.",
                maxlength: jQuery.format("Email Address can not exceed {0} characters in length."),
                emailCheck:"<span class='navDrk'>Email Already Registered, <a href='/formSubmit.php?goToStep=1'>Login Here</a>.</span>",
            },
            city: {
                required: "City is required.",
                minlength: jQuery.format("City must be at least {0} characters in length."),
                maxlength: jQuery.format("City can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            state: {
                required: "State is required.",
                minlength: jQuery.format("State must be at least {0} characters in length."),
                maxlength: jQuery.format("State can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            zip: {
                required: "Zip is required.",
                minlength: jQuery.format("Zip must be at least {0} characters in length."),
                maxlength: jQuery.format("Zip can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            pet_name: {
                required: "Pet Name is required.",
                minlength: jQuery.format("Pet Name must be at least {0} characters in length."),
                maxlength: jQuery.format("Pet Name can not exceed {0} characters in length."),
                validChars: "Please supply valid characters only.",
            },
            pet_type: {
                required: "Pet Type is required."
            },
            pet_story: {
                required: "Pet Story is required."
            },
            pet_listing_type: {
                required: "Listing Type is required."
            }
        }
    });

		// Limit characters for pet story to 500
		$('#pet_story').keyup(function(){
			limitChars('pet_story', 500, 'pet_story_limit');
		})

    // when the DOM element with id="pet_type" is clicked....
    $("#pet_type").change(function() {

        // and issue an AJAX request to a PHP script in the same directory
        // getJSON is a method that expects a JSON-encoded data structure to be returned
        // there are other AJAX methods too. See http://docs.jquery.com/Ajax
        $.getJSON("/includes/getbreeds.php", // 1st arg to getJSON is the URI of the script
                  { 
                    pet_type: $("#pet_type").val(),  
                  },
                  // 2nd arg to getJSON is an array of key-value pairs to send 
                  // to the script. As many as you want.
                  // left-side is the GET variable name as seen by the target
                  // script, right-side is the value that will be sent.
                  // the above 2 args will cause the AJAX script to be hit with
                  // the query string: ?zipcode=90019&random=noise
                  // assuming that the user typed "90019" into the
                  // element on this page with the id="zip"
                    

                  // 3rd arg is the callback function for the AJAX response
                  // The script.php responds in a JSON format so jQuery can
                  // understand the data structure natively, without you 
                  // writing awful parsing of your own:
                  function(j) {
                      // erase all OPTIONs from existing select menu on the page
                      $('#pet_breed1 options').remove(); 
                      $('#pet_breed2 options').remove(); 
                      
                      // You will rebuild new options based on the JSON response...
                      var options = '<option value="">--Select--</option>';
                      // "j" is the json object that was output by your PHP script
                      // it is the array of key-value pairs to turn 
                      // into option value/labels...
                      for (var i = 0; i < j.length; i++) 
                      {
                          options += '<option value="' +
                                     j[i].optionValue + '">' +
                                     j[i].optionDisplay + 
                                     '</option>';
                      }
                      // stick these new options in the existing select menu
                      $("#pet_breed1").html(options);
                      $("#pet_breed2").html(options);
                      // now your select menu is rebuilt with dynamic info
                  } 
        ); // end getJSON 
    }); // end clicked button to trigger AJAX  

});

// extend the validation plugin to do remote username and email dupe checking
jQuery.validator.addMethod('emailCheck', function(email) {
    var postURL = "/includes/json_email_check.php";
    $.ajax({
        cache:false,
        async:false,
        type: "POST",
        data: "email=" + email,
        url: postURL,
        success: function(msg) {
            result = (msg=='TRUE') ? true : false;
        }
    });
    return result;
}, '');

// check for unwanted characters
$.validator.addMethod('validChars', function (value) {
    var result = true;

    // unwanted characters
    var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

    for (var i = 0; i < value.length; i++) {
        if (iChars.indexOf(value.charAt(i)) != -1) {
            return false;
        }
    }
    return result;
}, '');