;(function($) {
    $.fn.freeReviewInput = function() {
        var elm = this,
        instituteFriendlyUrl = null,
            html = '<p>' +
                '<label for="free-input-institute">' + __('Institute name') + ':</label>' +
                '<input id="free-input-institute" class="input-normal" placeholder="' + __('Type here to choose the provider…') + '">' +
            '</p>' +
            '<p class="hide">' +
                '<label for="free-input-training">' + __('Training') + ':</label>' +
                '<select id="free-input-training">' +
                    '<option value="-">' + __('Select a training…') + '</option>' +
                '</select>' +
            '</p>';
        
        elm.html(html);
        
        var inputElm = elm.find('#free-input-institute');
        
        inputElm.placeholder();
        
        inputElm.autosuggest({
            api: 'http://' + Springest.dataDomain + '/autocomplete/%s.jsonp?api_key=public',
            clickLinkCallback: callback,
            dropdownClass: 'dropdown institute-name',
            logos: 'institutes',
            sections: {
                institutes: __('Found institutes')
            }
        });
        
        
        function callback(elm) {
            instituteFriendlyUrl = /^http:\/\/[a-z\-\.]+\/([a-z0-9\-]+)/.exec(elm.href)[1];
            
            if (typeof instituteFriendlyUrl == 'null') return false;
            
            $.getJSON(SpringestURLs.ajaxTrainings + '/' + instituteFriendlyUrl, [], viewTrainingList);
            
            $('body').trigger('click');
            
            return false;
        }
        
        
        function viewTrainingList(data) {
            var select = elm.find('#free-input-training');
            
            select.find('option:gt(0)').remove();
            select.parent().removeClass('hide');
            
            var html = '';
            
            $.each(data, function(index, training) {
                html += '<option value="' + training.Training.friendly_url + '">' + training.Training.name + '</option>';
            });
            
            select.append(html);
            
            select.change(checkForRedirect);
        }
        
        
        function checkForRedirect() {
            var elm = $(this),
                value = elm.val() || '';
            
            if (value == '-' || value == '' || value.length === 0) return;
            
            window.location.href = '/' + instituteFriendlyUrl + '/' + value + '#' + __('id-submit-review');
        }
    }
})(jQuery);
