$(
    function()
    {

        var bindFunction = function () {
            $.fn.editable.defaults.mode = 'inline';
            Classified.initEditable();
        };

        if($('body.cs_classifieds').length) {
            Pagination.onChange.add(function () { bindFunction(); });
            bindFunction();
        }

        $('body').on( 'click', '.cs-module-search > div > span',
            function()
            {
                if($('#cs-module-search-advanced').is(':visible'))
                {
                    $('#cs-module-search-advanced').slideUp();
                    $(this).removeClass('active');
                }
                else
                {
                    $('#cs-module-search-advanced').slideDown();
                    $(this).addClass('active');
                }
            }
        )
        .on('click', '[data-highlight]', function(event)
        {
            var container = $(this).data('for');
            var id = container.replace('cs-c-', '');

            event.preventDefault();
            Q.fcall(setClassified, id, container)
                .then(markAsClassified)
                .catch(function (error) {})
                .done();
        });

        //@TODO Mirar com globalitzar el event switch dels checkboxes per la cerca avançada.
        $('#comitiumsuite_bundle_cscmsbundle_csclassified_advancedsearch_highlighted').on('switchChange.bootstrapSwitch', function(event, state) {
            advancedSearch.trigger();
        });

        //Start Highlight functions

        function setClassified( id, container )
        {
            var d = Q.defer();

            $.post( Routing.generate('cs_cms_classifieds_highlight')+'/'+id )
                .done(function(data)
                {
                    d.resolve(container);
                })
                .fail(function(jqXHR)
                {
                    d.reject(new Error(jqXHR.responseText));
                });

            return d.promise;
        }

        function markAsClassified( container )
        {
            var d = Q.defer();
            var theClassified = $('#' + container );
            if($(theClassified).hasClass('highlighted'))
            {
                $(theClassified).removeClass('highlighted');
            }
            else
            {
                $(theClassified).addClass('highlighted');
            }

            return d.promise;
        }

        //end highlight functions

        $(document).on('click', '[data-action="unselect"]',function(){
            $('form[name="comitiumsuite_bundle_cscmsbundle_csclassified"]').trigger('change', false);
        });

        AssetsHelper.signals.onNewAfterRemove.add(function(){
            $('form[name="comitiumsuite_bundle_cscmsbundle_csclassified"]').trigger('change', false);
        });

        //Calculate the price
        var formTimeOut;
        var _form = $('form[name="comitiumsuite_bundle_cscmsbundle_csclassified"]');

        _form.on('change  switchChange.bootstrapSwitch', function(event, hasImage)
        {
            if($('#tab1').is(':visible')) {
                if(typeof formTimeOut !== 'undefined') {
                    clearTimeout(formTimeOut);
                }

                var self = $(this);
                formTimeOut = setTimeout(function() {

                    var json = {
                        text: $('#comitiumsuite_bundle_cscmsbundle_csclassified_defaultLang_text').val(),
                        highlighted: $('#comitiumsuite_bundle_cscmsbundle_csclassified_highlighted').is(':checked')? 1 : 0,
                        startAt: $('#comitiumsuite_bundle_cscmsbundle_csclassified_dates_startAt').val(),
                        endAt: $('#comitiumsuite_bundle_cscmsbundle_csclassified_dates_endAt').val(),
                        asset: ($('.image [data-action="unselect"]').length || $('.image .btn-remove').length) && hasImage != false ? 1 : 0
                    };

                    $.post(Routing.generate('cs_cms_classified_calculate_price'), _form.serialize(), function(data) {
                        $('#classifieds_calculated_price').html(data.total.toFixed(2));
                    });
                }, 500);
            }
        }).
        find('[data-free]').on('switchChange.bootstrapSwitch', function() {
            if($(this).is(':checked'))
            {
                $('#total_price_classified').hide();
                $('#total_price_free_classified').show();
            }
            else
            {
                $('#total_price_free_classified').hide();
                $('#total_price_classified').show();
            }
        }).trigger('switchChange.bootstrapSwitch');
    }
);


var Classified = (function() {

    var initEditable = function() {
        $.fn.editable.defaults.mode = 'inline';
        $('[data-editable]').each(function(i,e) {
            var _this = $(e);
            _this.editable({
                showbuttons: 'bottom',
                url: Routing.generate('cs_cms_classified_set'),
                name: _this.data('name')
            })
        });
    };

    return {
        initEditable: function() {
            initEditable();
        }
    };
})();

