/*
 *      Dojo Test Application
 *      Module name: dojo-test-app/testApplication
 *      
 *                
 *      Application controller
 */
define([
    'dojo/_base/config',
    'dojo/parser',
    'dojo/on',
    'dojo/dom-style',
    'dijit/registry',
    'dijit/Dialog',
    'dijit/form/Button',
    'dijit/form/Form',
    'dijit/layout/TabContainer',
    'dijit/layout/ContentPane',
    'dijit/form/ValidationTextBox',
    'dijit/form/CheckBox',
    'dijit/form/ValidationTextBox',
    "dojo/store/Memory",
    "dojo/data/ItemFileReadStore",
    "dojox/grid/DataGrid",
    "dojo/io/script",
    "dojo-test-app/overlay.min"
],
function
(
        config, parser, on, style, registry, Dialog, Button, Form, TabContainer,
        ContentPane, ValidationTextBox, CheckBox, ValidationTextBox, Memory, 
        ItemFileReadStore, DataGrid, JSONP, overlay
) 
{
    // Ui components
    var
        tabContainer = null,
        queryField = null,
        filterResultsBox = null;
        searchForm = null,
        searchBtn = null,
        searchTab = null,
        resultsTab = null,
        resultsGrid = null,
        resultsTitle = null,
        resultsPagination = null,
        nextButton = null,
        prevButton = null;

    // Results grid description
    var        
        hrefFormatter = function(value)
        {
            value = unescape(value);
            return '<a href="http://' + value + '" target="_blank">' + value + '</a>';
        },
                
        resultsLayout = [
            [
                { field: "title", name: "Pealkiri", width: 30 },
                { field: "url", name: "Aadress", width: 20, formatter: hrefFormatter},
                { field: "content", name: "Sisu kokkuvõte", width: 'auto' }
            ]
        ],
        
        dataStoreItems = 
        {
            identifier: 'id',
            label: 'Search results',
            items: 
                [
                ]
        };
    
    // Controller methods and vars
    var 
        // Search counters
        searchCount = null,
        searchTotal = null,
        searchStart = null,
        
        // Init UI
        initUI = function()
        {
            // Get handles to components
            tabContainer = registry.byId('application-tab-container');
            queryField = registry.byId('query');
            filterResultsBox = registry.byId('filter-box');
            searchForm = registry.byId('search-form');
            searchBtn = registry.byId('search-button');
            searchTab =  registry.byId('search-tab');
            resultsTab = registry.byId('results-tab');
            resultsGrid = registry.byId('search-results-grid');
            resultsTitle = registry.byId('results-title');
            resultsPagination = registry.byId('results-pagination');
            nextButton = registry.byId('next-button');
            prevButton = registry.byId('prev-button');
            
            // Lets disable resultsTab until theres no results
            resultsTab.set("disabled", true);
            
            // Events
            on(searchBtn, 'click', function (e) 
            {
                if(searchForm.validate())
                {
                    var query = queryField.getValue().trim();
                    var filterResults = (filterResultsBox.checked) ? 1 : 0;
                    
                    doSearch(query, 1, 10, filterResults, handleQuery);
                }
            });
            
            on(prevButton, 'click', function (e)
            {
                searchStart -= 10;
                
                var query = queryField.getValue().trim();
                var filterResults = (filterResultsBox.checked) ? 1 : 0;

                doSearch(query, searchStart, 10, filterResults, handleQuery);
            });
            
            on(nextButton, 'click', function (e)
            {
                searchStart += 10;
                
                var query = queryField.getValue().trim();
                var filterResults = (filterResultsBox.checked) ? 1 : 0;

                doSearch(query, searchStart, 10, filterResults, handleQuery);
            });
        },

        // Query        
        doSearch = function(query, start, count, filter, fn)
        {
            overlay.show();
            
            var requestUrl = config.googleRequest.requestUrl;
            requestUrl = requestUrl.replace('{query}', query).replace('{num}', count).replace('{start}', start).replace('{filter}', filter);
            
            JSONP.get({
                url: requestUrl,
                callbackParamName: "callback",
                load: function(jsonData) {
                    fn(jsonData);
                },
                error: function(e) {
                    overlay.hide();
                    var errorDlg = new Dialog({
                        title: 'Tõrge',
                        style: 'width: 300px',
                        content: 'Andmevahetusel tekkis viga! Korda otsingut!'
                    });
                    
                    on(errorDlg, 'hide', function (e) 
                    {
                        resultsTab.set('disabled', true);
                        tabContainer.selectChild(searchTab);
                    });
                    
                    errorDlg.show();
                }
            });
        },
        
        initPagination = function()
        {
            resultsTitle.set('content', '<em>Näitan tulemusi ' +
                    searchStart + ' - ' + (searchStart + searchCount - 1) + '  ' + searchTotal + '-st.</em>');
            
            if(searchStart === 1)
                prevButton.set('disabled', true);
            else
                prevButton.set('disabled', false);

            if(searchStart + searchCount < searchTotal)
                nextButton.set('disabled', false);
            else
                nextButton.set('disabled', true);
                
            // Hide overlay
            overlay.hide();
        },
        
        handleQuery = function(resultSet)
        {
            if(resultSet.items)
            {
                // Construct dataStore object
                dataStoreItems.items = [];
                for(var i = 0; i < resultSet.items.length; i++)
                {
                    dataStoreItems.items.push({ 
                        id: i,
                        title : resultSet.items[i].title,
                        url : resultSet.items[i].formattedUrl,
                        content : resultSet.items[i].snippet 
                    });
                }

                dataStore = new dojo.data.ItemFileReadStore({ data: dataStoreItems });

                resultsGrid.setStructure(resultsLayout);
                resultsGrid.setStore(dataStore);

                // Enable results tab and swith onto it
                resultsTab.set('disabled', false);
                tabContainer.selectChild(resultsTab);

                // Set counters
                searchCount = resultSet.queries.request[0].count;
                searchTotal = resultSet.queries.request[0].totalResults;
                searchStart = resultSet.queries.request[0].startIndex;

                // Init pagination
                initPagination();
            } 
            else
            {
                    overlay.hide();
                    var errorDlg = new Dialog({
                        title: 'Tõrge',
                        style: 'width: 300px',
                        content: 'Andmevahetusel tekkis viga! Korda otsingut!'
                    });
                    
                    on(errorDlg, 'hide', function (e) 
                    {
                        resultsTab.set('disabled', true);
                        tabContainer.selectChild(searchTab);
                    });
                    
                    errorDlg.show();
            }
        };
        
    return {
        // Init test-app 
        init   : function () 
        {
            initUI();
        }
    };
});


