var Contacts = (function () {

    var bindFunction = function () {

        var collectionHolder = $('div#tab2 div[data-prototype]');
        $('[data-prototype]').on('click','[data-action="delete-address"]', function(e){
            e.preventDefault();
            var portlet_sortable = $(this).closest('.portlet-sortable');
            var br = portlet_sortable.next();
            $(this).closest('.portlet-sortable').fadeOut("slow",function(){
                br.remove();
                $(this).remove();
            })
        });

        collectionHolder.collection({
            button_template: collectionHolder.data('button-prototype'),
            label: false,
            insert: 'append',
            childrenFilter: "div.portlet-sortable",
            insertButtonSelector: '[data-collection="add-button"]',
            afterCreate: function (e) {
                var element = e.detail.element;

                element.find("input[id$='_primary']").bootstrapSwitch();
                checkPrimaryAddress(element.find("input[id$='_primary']"));
                element.find("input[id$='_billing']").uniform();
                element.find("input[id$='_shipping']").uniform();
                var postalCodeElement = $(element).find("input[name$='[postalCode]']");
                var postalCodeSuggest = CreatePostalCodeSuggestRelatedInfo(postalCodeElement);

                editableTitle(element.find('.address-title'));
            },
            iterateAll: function (index, element) {
                checkPrimaryAddress(element.find("input[id$='_primary']"));
                editableTitle(element.find('.address-title'));
                var postalCodeElement = $(element).find("input[name$='[postalCode]']");
                var postalCodeSuggest = CreatePostalCodeSuggestRelatedInfo(postalCodeElement);

            }
        });
    };

    var CreatePostalCodeSuggestRelatedInfo = function (target) {

        var postalCodeSuggest = new CreateSuggest();

        $(target).on("change", function (e) {
            var _this = $(this);
            var current_form = target.closest('.portlet-sortable');
            var locationId = current_form.find("input[id$='_location']");
            var city_id = current_form.find("input[id$='_city']");
            var provinceLabel = current_form.find("input[id$='_provinceLabel']");
            var province_id = current_form.find("input[id$='_province']");
            var countryLabel = current_form.find("input[id$='_countryLabel']");
            var country_id = current_form.find("input[id$='_country']");
            var cityLabel = current_form.find("input[id$='_cityLabel']");

            $.get(Routing.generate('crm_contact_postalcode_related_info', { postalCode: _this.val() }))
                .success(function (data) {
                    cityLabel.val(data.city);
                    provinceLabel.val(data.province);
                    countryLabel.val(data.country);
                    locationId.val(data.id);
                    //city_id.val(data["cities"][0]["id"]);
                    //province_id.val(data["province"]["id"]);
                    //country_id.val(data["country"]["id"]);
                });
        });

        return postalCodeSuggest;
    };

    var editableTitle = function (element) {
        element
            .editable({
                validate: function (value) {
                    if ($.trim(value) == '') {
                        return Translator.trans('cs_common_base.form.messages.errors.required');
                    }
                    else {
                        $('#' + $(this).data('for')).val(value);
                    }
                },
                mode: 'inline'
            })
            .on('click', function () {
                $('.editable-input :first-child').select().addClass('form-control');
            });
    };

    var preSubmitActions = function () {

        $('[name="comitiumsuite_bundle_crmbundle_contact"]').on('submit', function (e) {
            var success = true;

            $(document).find('[data-required="required"]').each(function () {
                if ($(this).val() == '') {
                    showToastrNotification('error', Translator.trans('cs_contacts.contacts.messages.address_title'));
                    success = false;
                }

                if (!success) {
                    return false;
                }
            });

            return success;
        });
    };

    var bindEnableTrigger = function(selector, route){
      $('[data-action="switch-contact"] input' + selector).on('switchChange.bootstrapSwitch', function (event, state) {
          $.post(Routing.generate(route, {id: $(this).data('id'), enabled: state}))
              .success(function(data){
                  showToastrNotification('success', data.message);
              });
      });
    };

    var checkPrimaryAddress = function(input){
        input.on('switchChange.bootstrapSwitch', function(event, state) {
            var _this = this;
            var primary_address = false;

            var primary_inputs = $("[data-prototype]").find("input[id$='_primary']").toArray();

            for(var i = 0, length =primary_inputs.length;i < length;i++ ){
                var input = $(primary_inputs[i]);

                if(input.attr('id') != $(_this).attr('id')){
                    input.bootstrapSwitch('state', false, true);
                }

                if(input.bootstrapSwitch('state')){
                    primary_address = true;
                }
            }

            if(!primary_address){
                $(primary_inputs[0]).bootstrapSwitch('state', true);
            }
        });
    };

    var bindCollectionsEvents = function() {
        var options = {
            'addElement': '[data-add="subscription"]',
            'deleteElement': '[data-delete="subscription"]',
            'method': 'prepend',
        };

        options[SimpleFormCollection.AFTER_ADD] = function(element) {
            initSelect2(element);
        };

        document.addEventListener("DOMContentLoaded", function() {
            $('[data-collection="content-subscriptions"]').SimpleFormCollection(options);
        });
    };

    var initSelect2 = function(element) {
        $(element).find('select[id$="_subscription"]').each(function(){
            var _this = $(this);

            _this.select2();

            copyExpire(element);

            _this.on('change', function () {
                copyExpire(element);
            })
        });
    };

    var copyExpire = function(element) {
        var _element = $(element);

        _element
            .find("[data-expiration-date]")
            .html(_element.find('select[id$="_subscription"] :selected').data("expire"));
    };

    var bindTabsEvent = function () {
        var fromSearchSelector = $('#crm_contact_search_group');
        var tabSelector = $('#crm_contact_search_tab');
        var filterSelector = $('#crm_contact_search_filter');
        var filterParamSelector = $('#crm_contact_search_filterParam');

        $('body').on('click', '[data-toggle="tab"]', function(e){
            var contactType = $(this).attr('data-type');
            tabSelector.val(contactType);
            filterSelector.val("");
            filterParamSelector.val("");
            fromSearchSelector.change();
        });

        $('body').on('click', '[data-filter]', function(e){
            var _this = $(this);

            if (_this.hasClass("active")) {
                filterSelector.val("");
                filterParamSelector.val("");
            } else {
                filterSelector.val(_this.attr('data-filter'));
                filterParamSelector.val(_this.attr('data-filter-param'));
            }

            fromSearchSelector.change();
        });
    };

    return {
        init: function () {
            bindFunction();
            preSubmitActions();
            bindEnableTrigger('[data-target="contact"]', 'crm_contact_enable');
            bindEnableTrigger('[data-target="newsletter"]', 'crm_contact_newsletter_enable');
            var self = this;
            Pagination.onChange.add(function() {
                self.initDomFunctions($('[data-action="switch-contact"]'));
            });
        },
        initDomFunctions: function(element) {
            $(element).find('[type="checkbox"]').bootstrapSwitch();
        },
        paginationInit: function () {
            var paginator = createPagination($);
            paginator.setUrl(Routing.generate('cs_common_cs_user_page'));
            paginator.setDomSelector('.users_content ul.pagination li a');
            paginator.init();
        },
        bindSubscriptionCollection: function () {
            bindCollectionsEvents();
        },
        bindTabs: function () {
            bindTabsEvent();
        }
    };
})();
