/*global $*/

var MJ = MJ || {};

MJ.Controllers = MJ.Controllers || {};

/**
 * Controller for the search input field
 */
MJ.Controllers.SearchInput = (function () {
    var CONSTANTS = { /** @constant **/
        classes : {
            placeholderActive   : 'placeholder'
        },
        ids : {
            searchInput         : 'searchInput'
        }
    },
    elements = {},
    placeholderText;
    
    /**
     * Initialises the controller for the search input field
     */
    function init() {
        var view;
        
        elements.rootNode = $('#' + CONSTANTS.ids.searchInput);
        view = new MJ.Views.SearchInput(MJ.Controllers.SearchInput, elements);
    }
    
    /**
     * Checks if the user's browser support the placeholder attribute
     *
     * @public
     * @return {boolean} True if the browser supports the placeholder attribute
     */
    function placeholderSupport() {
        var hasSupport = ('placeholder' in document.createElement('input'));
        
        if (!hasSupport) {
            placeholderText = elements.rootNode.attr('placeholder');
        }
        
        placeholderSupport = function () {
            
            return hasSupport;
        };
        
        return placeholderSupport();
    }
    
    /**
     * When the user blurs the search input
     *
     * @public
     */
    function viewBlurred() {        
        if (elements.rootNode.val() === '') {
            elements.rootNode.val(placeholderText);
        }
        elements.rootNode.addClass(CONSTANTS.classes.placeholderActive);
    }
    
    /**
     * When the user focuses the search input
     *
     * @public
     */
    function viewFocused() {
        if (elements.rootNode.val() === placeholderText) {
            elements.rootNode.val('');
        }
        elements.rootNode.removeClass(CONSTANTS.classes.placeholderActive);
    }
    
    return {
        placeholderSupport  : placeholderSupport,
        init                : init,
        viewBlurred         : viewBlurred,
        viewFocused         : viewFocused
    };
}());

MJ.Controllers.SearchInput.init();
