SearchController = function() {
    
    // Private fields
    // -------------------------------------------------------------------------
    var
    // UI handles
    _tabHost = null,
    _loadingPanel = null,
    _itemsContainer = null,
    _prevButton = null,
    _nextButton = null,
    _countLabel = null,
    
    // Search counters & storage
    _searchCount = 0,
    _searchTotal = 0,
    _searchStart = 0,
    _searchResults = new Array(),
    _searchKeyword = null,
    _searchFilter = 0;
   
    // Public methods
    // -------------------------------------------------------------------------
 

    // Private methods
    // -------------------------------------------------------------------------
    
    // Query
    function _handleQuery(resultSet, success) 
    {
        // TODO: Remove
        console.log('Handling query...');
        
        // Clear results array
        _searchResults = new Array();
        
        if(resultSet.items)
        {
            // Fill
            for(var i = 0; i < resultSet.items.length; i++)
            {
                _searchResults.push({ 
                    title : resultSet.items[i].title,
                    url : resultSet.items[i].formattedUrl,
                    summary : resultSet.items[i].snippet 
                });
            }

            // TODO: Remove
            console.log('in Handling query:');

            // Set counters
            _searchCount = resultSet.queries.request[0].count;
            _searchTotal = resultSet.queries.request[0].totalResults;
            _searchStart = resultSet.queries.request[0].startIndex;
            _searchKeyword = resultSet.queries.request[0].searchTerms;
            _searchFilter = parseInt(resultSet.queries.request[0].filter);

            // Callback
            if(success)
                success();
        }
        else
        {
            SC.AlertPane.error({
                message: "Tõrge!",
                description: "Andmevahetusel tekkis viga! Korda otsingut!"
            });
        }
    }
            
    function _prepareItems()
    {
        // TODO: Remove
        console.log('Preparing Items...');
        
        var template = '<ul class="result"><li class="title">{0}</li><li class="summary">{1}</li><li class="url"><a href="http://{2}" target="_blank">{3}</a></li></ul>';
        
        var content = '';
        for(var i = 0; i < _searchResults.length; i++)
        {
            content += template.replace('{0}', _searchResults[i].title)
                        .replace('{1}', _searchResults[i].summary)
                        .replace('{2}', _searchResults[i].url)
                        .replace('{3}', _searchResults[i].url);
        }
        
        // Set content
        _itemsContainer.set('content', content);
        
        // Don't forget to referesh navigation!
        _preparePagination();
    }
            
    function _preparePagination()
    {
        console.log('Preparing pagination...');
        
        if(_prevButton)
        {
            if(_searchStart <= 1)
                _prevButton.set('isEnabled', false);
            else
                _prevButton.set('isEnabled', true);
        }
        
        if(_nextButton)
        {
            if(_searchStart + _searchCount < _searchTotal)
                _nextButton.set('isEnabled', true);
            else
                _nextButton.set('isEnabled', false);
        }
        
        if(_countLabel && _searchCount > 0)
            _countLabel.set('value', 'Näitan tulemusi ' +
                    _searchStart + ' - ' + (_searchStart + _searchCount - 1) + '  ' + _searchTotal + '-st.');
    }
    
    function _toggleLoading() 
    {
        _loadingPanel.set('isVisible', ! _loadingPanel.get('isVisible'));
    }

    
    return {

        // Switch Tabs        
        switchTabs: function()
        {
            _tabHost.tabsToggle();
        },
    
        loadNextResults: function()
        {
            _searchStart += 10;
            
            this.search(
                _searchKeyword, _searchStart, 10, _searchFilter,
                function() {
                    _prepareItems();
                },
                function() {
                    SC.AlertPane.error({
                        message: "Tõrge!",
                        description: "Andmevahetusel tekkis viga! Korda otsingut!"
                    });
                }
            ); 
        },
                
        loadPreviousResults: function()
        {
            _searchStart -= 10;
            
            this.search(
                _searchKeyword, _searchStart, 10, _searchFilter,
                function() {
                    _prepareItems();
                },
                function() {
                    SC.AlertPane.error({
                        message: "Tõrge!",
                        description: "Andmevahetusel tekkis viga! Korda otsingut!"
                    });
                }
            ); 
        },

        // Search
        search: function(keyword, start, count, filter, success, error)
        {
            // Show loading
            _toggleLoading();
            
            var searchString = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyAvnr_EiOfpj0Ub97QkQIEek6npmDFoZko&cx=002647590579739994937:ntvk68za0vo&q={query}&num={num}&start={start}&filter={filter}&callback=?';
            searchString = searchString.replace('{query}', keyword)
                    .replace('{num}', count).replace('{start}', start).replace('{filter}', filter);

            // TODO: Remove    
            console.log('Searching...');
            console.log(searchString);

            $.getJSON(searchString, null, function(data, textStatus, xhr) {

                // TODO: Remove    
                console.log('Request succeeded!');
                
                // Handle query
                _handleQuery(data, success);

            }).fail(function()
            {
                // On error
                // TODO: Remove
                console.log('Request failed!');

                // Call error
                if(error)
                    error();
            }).always(function() 
            { 
                // TODO: Remove
                console.log('Request complete!');
                
                // Hide loading
                _toggleLoading();
            });
        },
            
        registerTabHostView: function(ref)
        {
            _tabHost = ref;

            // TODO: Remove
            console.log('TabHostView registered!');
        },

        registerItemsView: function(ref)
        {
            _itemsContainer = ref;
            _prepareItems();

            // TODO: Remove
            console.log('ItemsView registered!');
        },

        registerNextButtonView: function(ref)
        {
            _nextButton = ref;
            _preparePagination();

            // TODO: Remove
            console.log('NextButtonView registered!');
        },

        registerPrevButtonView: function(ref)
        {
            _prevButton = ref;
            _preparePagination();

            // TODO: Remove
            console.log('PrevButtonView registered!');
        },

        registerResultsCountView: function(ref)
        {
            _countLabel = ref;

            // TODO: Remove
            console.log('ResultsCountView registered!');
        },
                
        registerLoadingPanel: function(ref)
        {
            _loadingPanel = ref;

            // TODO: Remove
            console.log('LoadingPanel registered!');
        }


    };
};