if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(search, this_len) {
		if (this_len === undefined || this_len > this.length) {
			this_len = this.length;
		}
		return this.substring(this_len - search.length, this_len) === search;
	};
}

AUI().ready(function(A){ 
	//setInitAltroTextArea();
	optionalRadio();
});

var Loading = {
    start: function () {
        $('.loader').addClass('active');
        $('#wrapper').addClass('blur');
    },

    end: function () {
        $('.loader').removeClass('active');
        $('#wrapper').removeClass('blur');
    }
}

function optionalRadio () {
    $('.optional_radio input[type="radio"]').on('click keyup', function () {
        if ($(this).data('check')) {
            $(this).prop('checked', false);
        }
        $(this).data('check', this.checked);
    });
}


function setInitAltroTextArea() {
    $('.altro_check input[type=checkbox]').each( function(){
       if($(this).is(':checked')) {
           $(this).closest(".row").next().find('input, textarea').prop('disabled', false);
       }else {
           $(this).closest(".row").next().find('input, textarea').prop('disabled', true);
       }
    });
}

$('.altro_check input[type=checkbox]').change(
    function() {
        if($(this).is(':checked')) {
            $(this).closest(".row").next().find('input, textarea').prop('disabled', false);
        } else {
            $(this).closest(".row").next().find('input, textarea').prop('disabled', true);
        }
    }
);

$('.check-disable-row .first-check input[type=checkbox]').change(
    function() {
        if($(this).is(':checked')) {
            $(this).closest(".check-disable-row").find('.disabled-check input, .disabled-check textarea').prop('disabled', false).removeClass('disabled');
        }else {
            $(this).closest(".check-disable-row").find('.disabled-check input, .disabled-check textarea').prop('disabled', true).prop('checked', false).addClass('disabled');
        }
    }
);

$('label.checkbox').click(
    function(event) {
        if(!$(event.target).hasClass('field')){
        	$(this).parent().find('.field').trigger('click');
        }
    }
);

function uncheck_radio_before_click(radio) {
    if(radio.prop('checked'))
        radio.one('click', function(){ radio.prop('checked', false); } );
}

/*$('body').on('mouseup', 'label.radio .field', function(){
    var radio = $(this);
    uncheck_radio_before_click(radio);
})*/

$('body').on('mouseup', 'label.radio', function(){
    var label = $(this);
    var radio;
    if(label.attr('for'))
        radio=$('#'+label.attr('for')).filter('input[type="radio"]');
    else
        radio=label.find('input[type="radio"]');
    if(radio.length)
        uncheck_radio_before_click(radio);
})