﻿jQuery.validator.setDefaults({
    invalidHandler: function(form, validator) {
        console.log(validator.errorList);
        console.log(validator.errorList.length);

        for (var i = 0; i < validator.errorList.length; i++) {
            var element = $(validator.errorList[i].element);
            var message = validator.errorList[i].message;
            element.attr("title", message);
            element.parent().find(".msg-icon").css({ backgroundImage: "url(/assets/img/form-validation-negative.png)" });
        }
        // select all desired input fields and attach tooltips to them
        $("form :input[title]").tooltip({
            // place tooltip on the right edge
            position: "center right",
            // a little tweaking of the position
            offset: [-2, 10],
            // use the built-in fadeIn/fadeOut effect 
            effect: "fade",
            // custom opacity setting   
            opacity: 0.7,
            // use this single tooltip element 
            tip: '.tooltip'
        });
    }
});

jQuery.fn.clearSelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    });
}

jQuery.fn.fillSelect = function(data) {
    return this.clearSelect().each(function() {
        if (this.tagName == 'SELECT') {
            var dropdownList = this;
            $.each(data, function(index, optionData) {
                var option = new Option(optionData.Text, optionData.Value);

                if ($.browser.msie) {
                    dropdownList.add(option);
                }
                else {
                    dropdownList.add(option, null);
                }
            });
        }
    });
}

$(function() {
    $("textarea").elastic();

    var tooltip = $(".tooltip");
    var form = $("form");

    // select all desired input fields and attach tooltips to them
    $("form :input[title]").tooltip({
        // place tooltip on the right edge
        position: "center right",
        // a little tweaking of the position
        offset: [-2, 10],
        // use the built-in fadeIn/fadeOut effect 
        effect: "fade",
        // custom opacity setting   
        opacity: 0.7,
        // use this single tooltip element 
        tip: '.tooltip'
    });

    $("#CountryId").change(function() {
        var stateControl = $("#StateId");
        stateControl.parent().find(".msg-icon").css({ backgroundImage: "url(/assets/img/spinner.gif)" });
        $.getJSON("/Ajax/CountryInfo", { countryId: $(this).val() }, function(data) {
            form.find("label[for='StateId']").text(data.Data.RegionName);
            form.find("label[for='PostalCode']").text(data.Data.PostalCodeName);
            stateControl.fillSelect(data.ListData);
            stateControl.parent().find(".msg-icon").css({ backgroundImage: "none" });
        });
    });
});
