

// Get the value of a control
function getFieldValue(object) {
    if (object.hasClass('YesNoPicker'))
        return "" + (object.find('input')[0].checked || (object.find('input')[1].checked ? false : object.data('undefined')));
    else if (object.attr('type') == "radio")
        return "" + object[0].checked;
    else if (object.attr('type') == "checkbox")
        return "" + object[0].checked;
    else if (object.is('span')) // asp.net radio button list
        return "" + object.find('input:checked').val();
    else
        return "" + object.val()
}

// Get dump of form contents
function getFormDump(jRoot) {

    var tagName = jRoot[0].tagName;
    if (typeof tagName == 'undefined') {
        var innerDump = '';
        var children = jRoot.contents();
        for (var i = 0; i != children.length; ++i)
            innerDump += getFormDump($(children[i]));
        return innerDump;
    }
    tagName = tagName.toLowerCase();

    if (jRoot.hasClass('ignore-on-form-dump'))
        return '<!-- tag omitted: ' + tagName + '#' + jRoot.attr('id') + ' -->';

    var attrDump = '';
    var attributes = jRoot[0].attributes;
    for (var i = 0; i != attributes.length; ++i) {
        var svalue = attributes[i].value.replace('"', '\\"');
        attrDump += ' ' + attributes[i].name + '="' + attributes[i].value + '"';
    }
    if (jRoot.is(':input')) {
        var svalue = jRoot.val().replace('"', '\\"');
        attrDump += ' [value]="' + svalue + '"';
    }

    var innerDump = '';
    var children = jRoot.contents();
    for (var i = 0; i != children.length; ++i)
        innerDump += getFormDump($(children[i]));

    return '<' + tagName + attrDump + '>' + innerDump + '</' + tagName + '>';
}


// Hides an element if its dependency is a certain value
// - ctl - the dependent class
var DataDependent = function (ctl) {

    var dependency = $('#' + ctl.data('dependency'));
    var value = ctl.data('value');

    // on change handler
    this.onChange = function () {
        if (getFieldValue(dependency) == "" + value)
            ctl.addClass('visible');
        else
            ctl.removeClass('visible');
    };

    // attach handler to change event
    if (dependency.hasClass('YesNoPicker'))
        dependency.find('input').change(this.onChange);
    else if (dependency.attr('type') == "radio")
        $('input[name="' + dependency.attr('name') + '"]').change(this.onChange);
    else
        dependency.change(this.onChange);

    // init
    this.onChange();
    ctl.addClass('javascript');

};


// Handler for the default button
//  - btn - the default button
//  - root - the root of the inputs; if blank, page form is used
var DefaultButton = function (btn, root) {

    // Find our form
    root = root || $(btn.parents('form')[0]);

    // Find our inputs
    var inputs = root.find('input,select').filter(function () {
        var type = $(this).attr('type');
        return type != 'button' && type != 'submit';
    });

    // attach inputs to button
    inputs.each(function () {
        $(this).keypress(function (e) {
            if (e.which == 13) {
                btn.click()
                e.preventDefault();
            }
        });
    });

};


// Just like RequiredFieldValidator
// Except it's only enabled when its dependent control is enabled
RequiredDependentFieldValidatorEvaluateIsValid = function (val) {
    val = $(val);
    var controltovalidate = $('#' + val.data('val-controltovalidate'));
    var dependency_control = $('#' + val.attr('dependency-control'));
    var when_value = val.attr('when-value').toLowerCase();

    var validate = false;
    if (dependency_control.hasClass('YesNoPicker')) {
        when_value = when_value.match(/yes|true|1/) ? true : false;
        validate = dependency_control.find('input')[0].checked === when_value;
    }
    else {
        validate = getFieldValue(dependency_control) == when_value;
    }

    return !validate || getFieldValue(controltovalidate).length > 0;

};


// Preview image on file upload
var UploadImagePreview = function (img) {
    var upl = $('#' + img.data('for'))[0];
    $(upl).change(function () {
        if (upl.files && upl.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                img.attr('src', e.target.result);
            };
            reader.readAsDataURL(upl.files[0]);
        }
    });
}


/***
Initialize UI on load
*/
$(document).ready(function () {

    // initialize default buttons
    $("input[type='submit'].default").each(function () {
        var btn = $(this);
        var group = btn.data('group') && $('#' + btn.data('group'));
        new DefaultButton(btn, group);
    });

    // Initialize data dependencies
    $('.dependent').each(function () {
        new DataDependent($(this));
    });

    // Initialize image upload previews
    $('.upload-image-preview').each(function () {
        new UploadImagePreview($(this));
    });

});


/* Support maxlength for textarea */

$(document).ready(function() {
    $("textarea").bind('input propertychange', function () {
        var maxLength = Math.max(
            $(this).data('maxlength') || 0,
            $(this).attr('maxlength') || 0,
            50);
        if ($(this).val().length > maxLength) {
            $(this).val($(this).val().substring(0, maxLength));
        }
    })
});


/* Error link that scrolls to an error */
var ErrorLink = function (link) {
    var that = this;
    this.errors = [];

    this.addError = function (validator) {
        var key = validator.id;
        if (!(key in this.errors))
            this.errors[key] = validator;
        this.refreshUI();
    };

    this.removeError = function (validator) {
        var key = validator.id;
        if (key in this.errors)
            delete this.errors[key];
        this.refreshUI();
    };

    this.refreshUI = function () {
        link.addClass('hidden');
        for (var key in this.errors) {
            if (!this.errors.hasOwnProperty(key))
                continue;
            link.removeClass('hidden');
            link.data('target', this.errors[key]);
        }
    };

    this.gotoError = function (validator) {
        var id = '#' + validator.id;
        $([document.documentElement, document.body]).animate({
            scrollTop: $(id).offset().top - 150
        }, 500);
        $(id).addClass('signal');
        setTimeout(function () { $(id).removeClass('signal') }, 1000);
    };

    this.checkValidity = function (validator) {
        if (!validator.isvalid)
            this.addError(validator);
        else
            this.removeError(validator);
    };

    // Wire up events
    $(Page_Validators).each(function () {
        if (typeof this.controltovalidate === 'undefined') {
            this.id = $(this).attr('id');
            this.isvalid = ! $(this).is(':visible');
        }
        else {
            var validator = this;
            $('#' + this.controltovalidate).change(function () {
                that.checkValidity(validator);
                that.refreshUI();
            });
        }
        that.checkValidity(this);
        that.refreshUI();
    });
    $('input[type=submit]').click(function () {
        setTimeout(function () {
            $(Page_Validators).each(function () {
                that.checkValidity(this);
            });
            that.refreshUI();
        }, 0);
    });
    $(window).on('signature_validated', function (event, jSig, result) {
        var validator = jSig.find('.required')[0];
        validator.id = $(validator).attr('id');
        validator.isvalid = result;
        that.checkValidity(validator);
    });
    link.click(function (event) {
        event.preventDefault();
        for (var key in that.errors) {
            if (!that.errors.hasOwnProperty(key))
                continue;
            that.gotoError(that.errors[key]);
            return;
        }
    });
};

