﻿function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function goToPPC() {
    window.location = '?mode=ppc';
}

$(document).ready(function () {
    //remove target attribute if webkit browser - webkit (chrome, safari) forms will not submit with target attribute.
    if (is_webkit) {
        $('#buyauto-form').removeAttr('target');
    };
    // validate the top homeimprovement form when it is submitted
    $("#buyauto-form").validate({
        rules: {
            make: {
                required: true
            },
            model: {
                required: true
            },
            zip: {
                required: true,
                postalcode: true
            }
        },
        messages: {
            make: "",
            model: "",
            zip: ""
        },
        submitHandler: function (form) {
            leadFormSubmit();
        }

    });

    //Postal code method - not included in validation plugin.
    jQuery.validator.addMethod("postalcode", function (postalcode, element) {
        return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
    }, "Please specify a valid postal/zip code");

    $(function () {
        $("#dialog").dialog({
            autoOpen: false,
            modal: true
        });
        $("#dialog-2").dialog({
            autoOpen: false,
            modal: true
        });
    });
    var myErrorcode = gup('errorcode');
    if (myErrorcode == '0') {
        $("#dialog").dialog('open');
    };
    if (myErrorcode == '2') {
        $("#dialog-2").dialog('open');
    };
});

function cascadeSelect(parent, child) {
    var childOptions = child.find('option:not(.static)');
    child.data('options', childOptions);

    parent.change(function () {
        childOptions.remove();
        child
          .append(child.data('options').filter('.sub_' + this.value))
          .change();
    })

    childOptions.not('.static, .sub_' + parent.val()).remove();

}

$(function () {
    myForm = $('#buyauto-form');
    myMake = myForm.find('#make');
    myModel = myForm.find('#model');

    cascadeSelect(myMake, myModel);
});

