var editMode = false;

var ajaxGetContactTypeValuesUrl;
var sourceIconClasses;
var sourceIconNames;
var noWritePermissionsErrorMessage;

(function ($, undefined) {

    $.fn.addressForm = function (options) {

        function init(options)
        {
            ajaxGetContactTypeValuesUrl = options.ajaxGetContactTypeValuesUrl;
            sourceIconClasses = options.sourceIconClasses;
            noWritePermissionsErrorMessage = options.noWritePermissionsErrorMessage;

            sourceIconNames = options.sourceIconNames;
            initAddressListButtons(options);
            initAddressDetailView();
            initBDayPicker(options);
        }


        function initAddressDetailView()
        {
            initAddressDetailCrudButtons();
            setEditModeForFirstPageLoade();
            initRemoveAvatar();
            initImageUploadeFiled();


            initRingtoneOnChange();
            initContactTypeOnChange();
            initAddressDetailIconActions();


            setContactTypeVisibility();
            setRingtoneVisibility();

            initLastContactTabHeader();

            setInputFieldVisibility();
            setSubSectionVisibility();

            toggleContactNoteVisibility();
        }

        function initAddressListButtons()
        {
            initCreateBtn(options);
            initWrenchMenu();
        }

        function initAddressDetailCrudButtons()
        {
            initDeleteButton(options);
            initEditToggle();
            initSaveBtn();
            fixTooltipPositions();
        }

        function initAddressDetailIconActions()
        {

            initMeilToContact();
            initOpenContactWebsite();
            initSendFax(options);
        }

        function setEditModeForFirstPageLoade()
        {
            if ($('#Addresses_id').val() === "") {
                $("#Addresses_contact_type_drop").prop("selectedIndex", 0);
                $('#editToggle').click();
            }
        }

        function initDeleteButton(options) {

            var deleteId = '#' + options.deleteButtonId;
            $(deleteId).click(function (e) {
                showConfirmDialog(options);

            });
        }

        function showConfirmDialog(option) {

            var options = {
                confirmMessage: ajaxCreateDeleteConfirmMessage(option),
                dialogHeader: option.deleteConfirmHeader,
                confirmText: option.deleteConfirmBtnConfirm,
                cancelText: option.deleteConfirmBtnCancel,
                height: 'auto',
                width: '500',
                position: ['center', 250],
                confirmCmd: function () {
                    var url = option.deleteUrl;
                    url += "&id=" + $('#Addresses_id').val();
                    ajaxDeleteAddress(url);
                },
                cancelCmd: function () {
                    setTimeout(function () {
                        $('#deleteButton').removeClass('active');
                    }, 1);
                    closeConfirmModal();
                    return true;
                }
            };
            var plDialog = new $.plDialog(options);
            plDialog.showConfirmDialog();
        }

        function ajaxCreateDeleteConfirmMessage(option){
            return $.ajax({
                url: option.getAjaxDeleteConfirmMessageURL,
                type: "POST",
                async: false,
                dataType: "html",
                data: {addressBookId: option.bookId, message: option.deleteConfirmMessage},
            }).responseText;
        }

        function closeConfirmModal() {
            $('#group_actions_dropdown').prop("selectedIndex", 0);
            $('#dialog-confirm.modal-body').dialog("close");
        }

        function ajaxDeleteAddress(url) {
            fadeOutAddressDetails();

            $.ajax({
                type: 'POST',
                url: url,
                context: document.body
            }).done(function (data) {
                $('#deleteButton').removeClass('active');
                $.fn.yiiGridView.update("addresses-grid",
                        {
                            complete: function () {
                                if ($('#addresses-grid tbody tr:first-child').find("td").length === 1) {
                                    $("#createNewContact").trigger("click");
                                } else {
                                    $('#addresses-grid tr:first-child').trigger('click');
                                }
                            }
                        });
            });
            closeConfirmModal();
        }
        function initRemoveAvatar()
        {
            $('#removeAvatar').click(function () {
                $('#avatarBox .avatarPreview').css('background-image', '').removeClass('active');
                $('#deleteImg').attr('checked', true);
                $('#Addresses_contact_jpegphoto').val('');
            });
        }

        function initMeilToContact()
        {
            $('#addressDetail:not(.editMode) div.email label').click(function (e) {
                if (editMode) {
                    return false;
                }
                var el = $(this).parent().find('input');
                var link = 'mailto:' + el.val();
                window.location.href = link;
            });
        }

        function initOpenContactWebsite()
        {
            $('#addressDetail:not(.editMode) div.url label').click(function (e) {
                if (editMode) {
                    return false;
                }
                var el = $(this).parent().find('input');
                var url = el.val();

                if (url.indexOf("://") === -1) {
                    url = 'http://' + url;
                }
                window.open(url, '_blank');
            });
        }

        function initEditToggle() {

            $('#editToggle').click(function () {
                toggleEditMode(this);
                toggleHeaderFieldsVisibility();

                setContactTypeVisibility();
                setRingtoneVisibility();

                setSubSectionVisibility();
                setInputFieldVisibility();

                toggleContactNoteVisibility();
                return false; // don't reloade the page
            });
        }

        function toggleEditMode(toggleEditBtn)
        {
            $('#editToggle').toggleClass('active');
            editMode = $(toggleEditBtn).hasClass('active');
            $("#addressDetail").toggleClass("editMode", editMode);
        }

        function toggleHeaderFieldsVisibility()
        {
            $('#contactHeader input').each(function () {
                var inputElement = $(this);
                // skip protected fields
                if (!inputElement.hasClass('protected'))
                    inputElement.prop('disabled', !editMode);

                if (editMode) {
                    inputElement.attr("placeholder", inputElement.data("placeholder")).trigger("input");
                    if ('Addresses_org_name' !== inputElement.attr('id')) {
                        inputElement.show();
                    } else {
                        inputElement.css({'visibility': 'visible'});
                    }
                } else {
                    inputElement.attr("placeholder", '').trigger("input");
                    if (inputElement.val() === '') {
                        if ('Addresses_org_name' !== inputElement.attr('id')) {
                            inputElement.hide();
                        } else {
                            inputElement.css({'visibility': 'hidden'});
                        }
                    }
                }
            });
        }

        function toggleContactNoteVisibility()
        {
            $('#contactDetail input, #Addresses_contact_note').each(function () {
                var inputElement = $(this);

                // skip protected fields
                if (!inputElement.hasClass('protected')) {
                    inputElement.prop('disabled', !editMode);
                }
                if (editMode) {
                    inputElement.attr("placeholder", inputElement.data("placeholder")).trigger("input");
                    var parent = inputElement.parent();

                    if (parent.hasClass('row')) {
                        parent.show();
                    }
                } else {
                    inputElement.attr("placeholder", '').trigger("input");

                    var parent = inputElement.parent();
                    if (inputElement.val() === '' && parent.hasClass('row')) {
                        parent.hide();
                    }
                }
            });
        }

        function initSaveBtn()
        {
            $('#saveAlias').click(function () {
                $('#addressookSaveButton').trigger('click');
                return false;
            });
        }

        function initCreateBtn()
        {
            $('#createNewContact').click(function () {
                $('#deleteImg').attr('checked', false);
                $('#avatarBox .avatarPreview').css('background-image', '').removeClass('active');
                $('#addressDetail input, #Addresses_contact_note').each(function () {

                    // prevent clearing protrcted fields
                    var protectedFields = new Array('YII_CSRF_TOKEN', 'Addresses[contact_tid]', 'Addresses[contact_owner]');

                    if (protectedFields.indexOf(this.name) !== -1) {
                        return true;
                    }

                    var inputElement = $(this);
                    if (inputElement.attr('id') === 'Addresses_source') {
                        setSourceIcon(0);
                        inputElement.val(options.defaultContactSourceName);
                    } else {
                        inputElement.val('');
                    }
                    inputElement.trigger("input");
                });

                if (!editMode) {
                    $('#editToggle').click();
                }
                fadeInAddressDetails();
                return false;
            });
        }

        function initImageUploadeFiled()
        {
            $('#Addresses_contact_jpegphoto').change(function (e) {
                if (this.files !== 'undefined' && typeof FileReader !== 'undefined') {

                    for (var f = 0; f < this.files.length; f++) {
                        var file = this.files[f];
                        var reader = new FileReader();

                        if (!/image\/(jpeg|jpg|png|gif)/.test(file.type)) {
                            alert('Dateityp "' + file.type + '" wird nicht unterstützt.');
                            continue;
                        }

                        $('#deleteImg').attr('checked', false);
                        $(reader).load(previewImage);

                        reader.readAsDataURL(file);
                    }
                }
            });
        }

        function initBDayPicker(options)
        {
            $(".dateTimePicker")
                    .datetimepicker({
                        startView: 4,
                        minView: 2,
                        formatType: 'php',
                        format: options.bdayFormat,
                        autoclose: true,
                        forceParse: false
                    })
                    .on('hide', function (ev) {
                        $('#Addresses_contact_bday').trigger('input');
                    });
        }

        function initWrenchMenu()
        {
            $('.addressBookTitle').on('click', '#settings', function (e) {
                togglePopover($('#settings').parent().parent());
                return false;
            });
        }

        function initSendFax(options)
        {
            if (options.faxGUIEnabled != true) {
                return;
            }

            $('.sendFax').on('click', function () {
                var editMode = false;
                if ($('#addressDetail').hasClass('editMode')) {
                    if (options.modelIsNewRecord !== 'true') {
                        editMode = true;
                    }
                }

                if (!editMode) {
                    var attributeName = $(this).parent().next().attr('id').replace('Addresses_', '') + '_ic';
                    $.ajax({
                        url: options.getJsonAddressCanonizedNumberUrl,
                        dataType: 'json',
                        data: {
                            addressId: $('#Addresses_id').val(),
                            attributeName: attributeName
                        },
                        context: document.body
                    }).success(function (address) {

                        var number = address.number;

                        $.ajax({
                            type: "GET",
                            url: options.createFaxUrl,
                            dataType: 'html'
                        }).success(function (data) {

                            $('#addresses-grid_Modal').find('h4').text(options.createFaxModalHeader);
                            $('#addresses-grid_Modal_saveBtn').text(options.createFaxSaveBtnText);
                            $('#addresses-grid_Modal').modal('show');
                            $('#addresses-grid_Modal .modal-body').html(data);
                            $('#UCItem_fax_number').val(number);
                        });

                    });
                }
            });

            $('#addresses-grid_Modal_saveBtn').on('click', function () {
                $('#create-fax-form').submit();
            });
        }

        function initContactTypeOnChange()
        {
            $('#contactTypeValueToggle').on('click', function () {
                toggleContactTypeInputType();
            });

            $('#Addresses_contact_type_drop').on('change', function () {
                var contacTypeDropdown = $(this);
                if (contacTypeDropdown.val().length === 0) {
                    toggleContactTypeInputType();
                } else {
                    $('#Addresses_contact_type').val(contacTypeDropdown.find(':selected').val());
                }
            });

        }

        function toggleContactTypeInputType() {
            if ($('#Addresses_contact_type').is(":visible")) {
                $('#Addresses_contact_type').hide();
                $('#contactTypeValueToggle').hide();
                $('#Addresses_contact_type_drop').show();
                $('#Addresses_contact_type_drop').prop('selectedIndex', 0);
                $('#Addresses_contact_type').val($('#Addresses_contact_type_drop').find(":selected").val());
            } else {
                $('#Addresses_contact_type').val($('#Addresses_contact_type_drop').find(":selected").val());
                $('#Addresses_contact_type_drop').hide();
                $('#contactTypeValueToggle').show();
                $('#Addresses_contact_type').attr("placeholder", $('#Addresses_contact_type').data("placeholder")).trigger("input");
                $('#Addresses_contact_type').prop("disabled", false).show();
            }
        }

        function initRingtoneOnChange()
        {
            $("#Addresses_ringtone_drop").change(function () {
                var value = $(this).find(":selected").val();
                $('#Addresses_ringtone').val(value);
            });
        }

        function initLastContactTabHeader()
        {
            $('#lastContactTabHeader').on('shown', function (e) {
                $.fn.yiiGridView.update("last-contact-grid");
            });
        }

        function fixTooltipPositions()
        {
            //fix for jumping tooltips : 
            $('#editToggle').click(function () {
                if ($('#addressDetail').hasClass('editMode')) {
                    $('#editToggle').find('.tooltip').css({'left': '-21px'});
                } else {
                    $('#editToggle').find('.tooltip').css({'left': '16px'});
                }
            });
        }

        init(options);
        if ($('#Addresses_id').val() === "" && $("#createNewContact").length === 0) {
            fadeOutAddressDetails();
        } else {
            fadeInAddressDetails();
        }

    };
})(jQuery);

function loadAddress(id, getJsonAddressURL, bookId, photoshowUrl)
{
    if (id === '') {
        return false;
    }

    fadeOutAddressDetails();
    turnEditModeOff();

    $.ajax({
        url: getJsonAddressURL,
        dataType: 'json',
        data: {addressId: id, bookId: bookId},
        context: document.body
    }).done(function (data) {

        setAvatarImage(data, photoshowUrl);
        setInputValues(data);

        setContactTypeVisibility();
        setRingtoneVisibility();
        setSourceIcon(data.source);

        setInputFieldVisibility();
        setSubSectionVisibility();

        reloadLastContactGrid();
        fadeInAddressDetails();

    }).error(function (e, e2, e3) {
        console.log(e3);
        fadeInAddressDetails();
    });

    return true;
}

function setInputValues(data)
{
    var headerFields = new Array('n_given', 'n_prefix', 'n_middle', 'n_family');
    $.each(data, function (attribute, value) {
        if (attribute === 'contact_jpegphoto') {
            return true;
        }
        var inputElement = $('#Addresses_' + attribute);
        inputElement.val(value).trigger("input");
        hideLabels(inputElement, attribute, headerFields);
    });
}

function setSubSectionVisibility()
{
    if ($('#Addresses_id').val() === "" && $('#createNewContact').length === 0) {
        $(".subsection").each(function (i, section) {
            $(section).hide();
        });
    } else if (editMode === true) {
        $(".subsection").each(function (i, section) {
            $(section).show();
        });
    } else {
        $(".subsection").each(function (i, section) {

            var showSection = false;
            $(section).find("input").each(function (i, e) {
                if (e.value.length > 0) {
                    showSection = true;
                }
            });
            if (showSection || editMode === true) {
                $(section).show();
            } else {
                $(section).hide();
            }
        });
    }
}

function setInputFieldVisibility()
{
    if (editMode === true) {
        $('#contactDetail input').each(function (index, inputField) {

            if ($(inputField).hasClass("protected")) {
                return;
            }

            if (inputField.id === "Addresses_contact_type") {
                return;
            }


            if ($(inputField).val().length === 0) {
                $(inputField).attr("placeholder", $(inputField).data("placeholder")).trigger("input");
            }
            $(inputField).prop('disabled', !editMode);

            if (inputField.id === "Addresses_ringtone") {
                $(inputField).hide();
            } else {
                $(inputField).show();
            }
            $(inputField).parent().show();
        });
    } else {
        $('#contactDetail input').each(function (index, inputField) {

            var input = $(inputField);
            if (input.val().length > 0) {
                input.parent().show();
                input.show();
            }
            input.trigger("input");
            input.prop('disabled', !editMode);
        });
    }

}

function fadeOutAddressDetails()
{
    $('#addressDetail').addClass("out").removeClass("in");
}

function fadeInAddressDetails()
{
    $('#addressDetail').addClass("in").removeClass("out");
}

function turnEditModeOff()
{
    if (editMode) {
        $('#editToggle').trigger('click');
    }
}

function setAvatarImage(data, photoshowUrl)
{
    if (data.contact_jpegphoto === "1") {
        var imageUrl = photoshowUrl;
        imageUrl += '&modelId=' + data.id;
        imageUrl += '&changed=' + data.changed;
        $('#avatarBox .avatarPreview')
                .css('background-image', 'url(' + imageUrl + ')')
                .addClass('active');
    } else {
        $('#avatarBox .avatarPreview').css('background-image', '').removeClass('active');
    }
    $('#deleteImg').attr('checked', false);
}

function hideLabels(inputElement, attribute, headerFields)
{

    var label = false;
    if (headerFields.indexOf(attribute) !== -1) {
        label = inputElement;
    } else if (inputElement.parent().hasClass('row')) {
        label = inputElement.parent()
    }
    if (label !== false && inputElement.val() !== '') {
        label.show();
    } else if (label === false) {
        return;
    } else {
        label.hide();
    }
}

function reloadLastContactGrid()
{
    if ($('#lastContactTab').hasClass('active')) {
        $.fn.yiiGridView.update("last-contact-grid");
    }
}

function setSubHeaderVisibility(sectionName)
{
    if (!editMode) {
        var sectionId = '#' + sectionName + " input";
        $('#' + sectionName).hide();
        $('#' + sectionName + " input").each(function (i, e) {
            if ($(e).val().length > 0) {
                $('#' + sectionName).show();
            }
        });
    } else {
        $('#' + sectionName).show();
    }
}

function setContactTypeVisibility()
{
    var toggleElement = $('#contactTypeValueToggle');
    var textField = $("#Addresses_contact_type");
    var dropdown = $("#Addresses_contact_type_drop");

    setDropdownValue(textField, dropdown);

    if (editMode) {
        showDropdown(dropdown, textField, toggleElement);
    } else {
        hideDropdown(dropdown, textField, toggleElement);
    }
}

function setDropdownValue(textField, dropdown)
{
    var textFieldValue = textField.val();
    if (textFieldValue === "0" || textFieldValue === "") {
        dropdown.prop("selectedIndex", 0);
    } else if (dropdown.find("option[value='" + textFieldValue + "']").length) {
        dropdown.val(textFieldValue);
    } else if (dropdown.find("option:contains('" + textFieldValue + "')").length) {
        dropdown.val(dropdown.find("option:contains('" + textFieldValue + "')").val());
    }
}

function showDropdown(dropdown, textField, toggleElement)
{
    textField.hide();
    textField.val(dropdown.find(":selected").val());
    if (typeof toggleElement === "object") {
        toggleElement.hide();
    }
    dropdown.show();
    dropdown.parent().show();
}

function hideDropdown(dropdown, textField, toggleElement)
{
    var textFieldValue = textField.val();
    textField.show();
    dropdown.hide();
    if (typeof toggleElement === "object") {
        toggleElement.hide();
    }

    if (dropdown.prop("selectedIndex") === 0) {
        textField.val("");
        dropdown.parent().hide();
    } else {
        if (dropdown.val() === textFieldValue) {
            textField.val(dropdown.find('option[value="' + textFieldValue + '"]').text());
        } else {
            textField.val(dropdown.find(":selected").text());
        }
        dropdown.parent().show();
    }
}

function setRingtoneVisibility()
{
    var textField = $("#Addresses_ringtone");
    var dropdown = $("#Addresses_ringtone_drop");

    setDropdownValue(textField, dropdown);

    if (editMode) {
        showDropdown(dropdown, textField);
    } else {
        hideDropdown(dropdown, textField);
    }

    /*
     if (editMode) {
     $('#Addresses_ringtone_drop').show();
     //$('#Addresses_ringtone_drop').parent().show();
     $('#Addresses_ringtone').val($('#Addresses_ringtone_drop').find(":selected").val());
     $('#Addresses_ringtone').hide();
     } else {
     $('#Addresses_ringtone_drop').hide();
     $('#Addresses_ringtone').val($('#Addresses_ringtone_drop').find(":selected").text()).trigger("input");
     }
     */

}

function checkAddressesVisibility(address) {

    var length = 0;
    $('#' + address + ' input').each(function () {
        var inputElement = $(this);
        if (editMode || inputElement.val().length > 0) {
            inputElement.show();
            length += inputElement.val().length;

            if (inputElement.next().is('br')) {
                inputElement.next().show();
            }
        } else {
            if (inputElement.val() === '') {
                inputElement.hide();
                if (inputElement.next().is('br')) {
                    inputElement.next().hide();
                }
            } else {
                length += inputElement.val().length;
            }
        }
    });

    if (editMode || length > 0) {
        $('#' + address).show();
    } else if (length === 0) {
        $('#' + address).hide();
    }
}

function checkPhonesVisibility(phones) {

    var length = 0;
    $('#' + phones + ' input').each(function () {
        var inputElement = $(this);


        if (editMode || inputElement.val().length > 0) {
            inputElement.parent().show();
            length += inputElement.val().length;
        } else {
            if (inputElement.val() === '') {
                inputElement.parent().hide();
            } else {
                length += inputElement.val().length;
            }
        }
    });

    if (editMode || length > 0) {
        $('#' + phones).show();
    } else if (length === 0) {
        $('#' + phones).hide();
    }
}

function previewImage(e) {
    var img = $(document.createElement('img'));
    $(img).attr('src', e.target.result);
    $('#avatarBox .avatarPreview').css('background-image', 'url(' + e.target.result + ')').addClass('active');
}

function updateURLParameter(url, param, paramVal)
{
    var TheAnchor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL)
    {
        var tmpAnchor = additionalURL.split("#");
        var TheParams = tmpAnchor[0];
        TheAnchor = tmpAnchor[1];
        if (TheAnchor)
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (i = 0; i < tempArray.length; i++)
        {
            if (tempArray[i].split('=')[0] !== param)
            {
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    } else
    {
        var tmpAnchor = baseURL.split("#");
        var TheParams = tmpAnchor[0];
        TheAnchor = tmpAnchor[1];

        if (TheParams)
            baseURL = TheParams;
    }

    if (TheAnchor)
        paramVal += "#" + TheAnchor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

function togglePopover(element) {
    if (element.hasClass('open')) {
        element.removeClass('open').popover('hide');
    } else {
        element.addClass('open').popover('show');
    }
}

function aftValidate(form, data, hasError)
{
    if (!hasError) {
        $('#errorList').hide();
        var formData = new FormData($('#addressbookaddresses-form')[0]);
        $.ajax({
            url: form.attr('action'), //server script to process data
            type: 'POST',
            xhr: function () {  // custom xhr
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) { // check if upload property exists
                    //myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            //Ajax events
            beforeSend: function () {
            },
            success: function (data) {

                setInputValues(data);
                setSourceIcon(data.source);
                updateContactTypeDropdown(data.contact_type);
                updateCallableNumbers(data);
                $('#Addresses_id').val(data.id);
                $('#editToggle').click();
                refreshGrid();
            },
            statusCode: {
                403: function () {
                    alert(noWritePermissionsErrorMessage);
                }
            },
            // Form data
            data: formData,
            //Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false
        });
    } else {
        var errors = '';

        $('#errorList').show();
        $('#errorList').addClass('alert');
        $.each(data, function (index, value) {
            errors += value + '<br>';
        });
        $('#errorList').html(errors);
    }
    return false;
}

function updateCallableNumbers(model) {

    $('.sendFax').each(function () {
        var attributeName = $(this).parent().next().attr('id').replace('Addresses_', '') + '_ic';
        $(this).parent().next().attr('data-icnumber', model[attributeName]);
    });
}

function refreshGrid() {
    $.fn.yiiGridView.update('addresses-grid');
}

function updateContactTypeDropdown(typeId)
{
    $.ajax({
        url: ajaxGetContactTypeValuesUrl,
        dataType: 'json'
    }).success(function (data) {

        var dropdown = $("#Addresses_contact_type_drop");
        var addNewTypeOption = dropdown.find('option:last-child').clone();
        dropdown.find('option').each(function (i, e) {
            e.remove();
        });

        $.each(data, function (index, contactType) {
            $('<option />').val(contactType.id).text(contactType.name).appendTo(dropdown);
        });
        addNewTypeOption.appendTo(dropdown);
        $("#Addresses_contact_type").val(typeId);
        setContactTypeVisibility();
    });
}

function setSourceIcon(source)
{
    $.each(sourceIconClasses, function (i, iconClass) {
        $('#sourceLabelIcon').removeClass(iconClass);
    });

    $('#sourceLabelIcon').addClass(sourceIconClasses[source]);
    $('#sourceLabelIcon').parent().parent().find("input").val(sourceIconNames[source]);
}

function checkAllGridCheckboxes()
    {

        document.getElementById("addresses-grid_c0_all").checked = 'checked';
        var items = document.getElementsByName("selectedRows[]");
        for (i = 0; i < items.length; i++) {
            document.getElementById("addresses-grid_c0_" + i).checked = 'checked';
        }
    }

    function disableAllGridCheckboxes()
    {
        document.getElementById("addresses-grid_c0_all").disabled = 'disabled';
        var items = document.getElementsByName("selectedRows[]");
        for (i = 0; i < items.length; i++) {
            document.getElementById("addresses-grid_c0_" + i).disabled = 'disabled';
        }
    }

    function uncheckAllGridCheckboxes()
    {

        document.getElementById("addresses-grid_c0_all").checked = '';
        var items = document.getElementsByName("selectedRows[]");
        for (i = 0; i < items.length; i++) {
            document.getElementById("addresses-grid_c0_" + i).checked = '';
        }
    }

    function enableAllGridCheckboxes()
    {
        document.getElementById("addresses-grid_c0_all").disabled = '';
        var items = document.getElementsByName("selectedRows[]");
        for (i = 0; i < items.length; i++) {
            document.getElementById("addresses-grid_c0_" + i).disabled = '';
        }
    }