/* >>>>>>>>>> BEGIN source/controllers/search_controller.js */
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!');
        }


    };
};
/* >>>>>>>>>> BEGIN source/core.js */
// ==========================================================================
// Project:   GoogleSearch
// Copyright: @2013 My Company, Inc.
// ==========================================================================
/*globals GoogleSearch */
sc_require('controllers/search_controller');

/** @namespace

  My cool new app.  Describe your application.

  @extends SC.Object
*/
GoogleSearch = SC.Application.create(
  /** @scope GoogleSearch.prototype */ {

  NAMESPACE: 'GoogleSearch',
  VERSION: '0.1.0',

  // This is your application store.  You will use this store to access all
  // of your model data.  You can also set a data source on this store to
  // connect to a backend server.  The default setup below connects the store
  // to any fixtures you define.
  store: SC.Store.create().from(SC.Record.fixtures),

  // TODO: Add global constants or singleton objects needed by your app here.
  searchController: new SearchController
  
});

/* >>>>>>>>>> BEGIN source/theme.js */
// ==========================================================================
// Project:   GoogleSearch
// Copyright: @2013 My Company, Inc.
// ==========================================================================
/*globals GoogleSearch */

// This is the theme that defines how your app renders.
//
// Your app is given its own theme so it is easier and less
// messy for you to override specific things just for your
// app.
//
// You don't have to create the whole theme on your own, though:
// your app's theme is based on SproutCore's Ace theme.
//
// NOTE: if you want to change the theme this one is based on, don't
// forget to change the :css_theme property in your buildfile.
GoogleSearch.Theme = SC.AceTheme.create({
  name: 'google-search'
});

// SproutCore needs to know that your app's theme exists
SC.Theme.addTheme(GoogleSearch.Theme);

// Setting it as the default theme makes every pane SproutCore
// creates default to this theme unless otherwise specified.
SC.defaultTheme = 'google-search';

/* >>>>>>>>>> BEGIN source/views/intro.js */
GoogleSearch.IntroView = SC.Pane.extend({
    
   childViews: ['titleLabel', 'usageInfo'],
   
   layout: { centerX: 0, left: 0, right: 0, top: 0, height: 125 },
   
   titleLabel: SC.LabelView.design({
       classNames: ['heading-xlarge'],
       layout: { centerX: 0, left: 0, right: 0, top: 25, bottom: 45, height: 40 },
       textAlign: SC.ALIGN_CENTER,
       tagName: "h1",
       value: "Google Custom-Search API - SproutCore"
   }),
   
   usageInfo: SC.LabelView.design({
       classNames: ['heading-large'],
       layout: { centerX: 0, left: 0, right: 0, top: 70, bottom: 0, height: 30 },
       textAlign: SC.ALIGN_CENTER,
       tagName: "h2",
       value: "Sisesta otsisõna ja vajuta otsi."
   })
   
});
/* >>>>>>>>>> BEGIN source/views/items_view.js */
GoogleSearch.ItemsView = SC.StaticContentView.extend({
    classNames: ['result-items'],
    content: '<section></section>',
    tagName: 'section',
        
    init: function()
    {
        arguments.callee.base.apply(this,arguments);
        
        // Register components
        GoogleSearch.get('searchController').registerItemsView(this);
    }
});

/* >>>>>>>>>> BEGIN source/views/next_button.js */
GoogleSearch.NextButtonView = SC.ButtonView.extend({
    buttonBehavior: SC.PUSH_BEHAVIOR,
    title: 'Järgmised',

    init: function()
    {
         arguments.callee.base.apply(this,arguments);

        // Register components
        GoogleSearch.get('searchController').registerNextButtonView(this);
    }
});
/* >>>>>>>>>> BEGIN source/views/prev_button.js */
GoogleSearch.PrevButtonView = SC.ButtonView.extend({
    buttonBehavior: SC.PUSH_BEHAVIOR,
    title: 'Eelmised',

    init: function()
    {
         arguments.callee.base.apply(this,arguments);

        // Register components
        GoogleSearch.get('searchController').registerPrevButtonView(this);
    }
});
/* >>>>>>>>>> BEGIN source/views/results_count.js */
GoogleSearch.ResultsCountView = SC.LabelView.extend({
    classNames: ['text-italic'],
    textAlign: SC.ALIGN_CENTER,
    value: '',
    
    init: function()
    {
         arguments.callee.base.apply(this,arguments);

        // Register components
        GoogleSearch.get('searchController').registerResultsCountView(this);
    }
})
/* >>>>>>>>>> BEGIN source/views/results_tab.js */
sc_require('views/items_view');
sc_require('views/prev_button');
sc_require('views/next_button');
sc_require('views/results_count');

GoogleSearch.ResultsTabView = SC.View.extend({
    
    childViews: 'resultsCountView resultsItemsScrollView prevButton nextButton'.w(),
    layout: { left: 0, right: 0, top: 0, bottom: 0 },
    
    resultsCountView: GoogleSearch.ResultsCountView.design({
        layout: {  centerX: 0, width: 670, top: 50 }
    }),
    
    resultsItemsScrollView: SC.ScrollView.design({
        classNames: ['result-items-view'],
        layout: {  centerX: 0, width: 670, top: 80, bottom: 50 },
        hasHorizontalScroller: NO,
        hasVerticalScroller: YES,
        borderStyle: SC.BORDER_NONE,
        contentView: GoogleSearch.ItemsView.design({
            layout: { top: 0, left: 0, right:0, bottom: 0, width: 670 }
        })
    }),
    
    prevButton: GoogleSearch.PrevButtonView.design({
        layout: {  centerX: -60, bottom: 10, width: 100, height: 24 },
        defaultResponder: 'GoogleSearch.ResultsTabView',
        action: 'prevButtonClick'
    }),
    
    nextButton: GoogleSearch.NextButtonView.design({
        layout: {  centerX: 60, bottom: 10, width: 100, height: 24 },
        defaultResponder: 'GoogleSearch.ResultsTabView',
        action: 'nextButtonClick'
    }),
    
    prevButtonClick: function(evt) {
        // TODO: Remove
        console.log('PrevButton Click!');
        
        GoogleSearch.get('searchController').loadPreviousResults();
    },
            
    nextButtonClick: function(evt) {
        // TODO: Remove
        console.log('NextButton Click!');
        
        GoogleSearch.get('searchController').loadNextResults();
    }
});
/* >>>>>>>>>> BEGIN source/views/search.js */
GoogleSearch.SearchView = SC.View.extend({
   
    childViews: 'searchFieldLabel searchField searchButton resetButton filterBox'.w(),
    layout: { width: 670 },
    defaultResponder: 'GoogleSearch.TabHostView',
    
    searchFieldLabel: SC.LabelView.design({
        layout: { left: 0, right: 0, top: 0 },
        textAlign: SC.ALIGN_LEFT,
        tagName: 'p',
        value: 'Otsisõna'
    }),
    
    searchField: SC.TextFieldView.design({
        layout: { left: 0, width: 450, top: 22, height: 24 },
        errorLabel: "Sisesta otsisõna!",
        validator: SC.Validator.NotEmpty.create() 
    }),
    
    searchButton: SC.ButtonView.design({
        layout: { left: 460, width: 100, top: 22, height: 24 },
        buttonBehavior: SC.PUSH_BEHAVIOR,
        title: 'Otsi',
        defaultResponder: 'GoogleSearch.SearchView',
        action: 'searchButtonClick'
    }),
    
    resetButton: SC.ButtonView.design({
        layout: { left: 570, width: 100, top: 22, height: 24 },
        buttonBehavior: SC.PUSH_BEHAVIOR,
        title: 'Tühjenda',
        defaultResponder: 'GoogleSearch.SearchView',
        action: 'resetButtonClick'
    }),
    
    filterBox: SC.CheckboxView.design({
        layout: { left: 0, right: 0, top: 55 },
        buttonBehavior: SC.PUSH_BEHAVIOR,
        title: 'Filtreeri korduvad tulemused'
    }),
          
    resetButtonClick: function(evt)
    {
        if(this.get('filterBox').isSelected)
        {
            this.get('filterBox').set('isSelected', false);
        }
        this.get('searchField').setFieldValue('');
    },
    
    searchButtonClick: function(evt)
    {
        var keyword = this.get('searchField').getFieldValue();
        var filter = (this.get('filterBox').isSelected) ? 1 : 0;
        if(this.get('searchField').performValidate() === SC.VALIDATE_OK)
        {
            GoogleSearch.get('searchController').search(
                keyword, 1, 10, filter,
                function() { 
                    GoogleSearch.get('searchController').switchTabs();
                },
                function() {
                    SC.AlertPane.error({
                        message: "Tõrge!",
                        description: "Andmevahetusel tekkis viga! Korda otsingut!"
                    });
                }
            );  
        }
        else
        {
            SC.AlertPane.error({
                message: "Otsisõna sisestamata!",
                description: "Sisesta otsisõna ja vajuta otsi."
            });
        }
    }
    
});
/* >>>>>>>>>> BEGIN source/views/search_tab.js */
sc_require('views/search');

GoogleSearch.SearchTabView = SC.View.extend({
    
    childViews: ['searchView'],
    
    layout: { 
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
    },
    
    searchView: GoogleSearch.SearchView.design({
        layout: { centerX: 0, centerY: 0, top: 50, width: 670 }
    })
    
});
/* >>>>>>>>>> BEGIN source/views/tab_host.js */
sc_require('views/results_tab');
sc_require('views/search_tab');

GoogleSearch.TabHostView = SC.TabView.extend({

    layout: { 
        centerX: 0,
        left: 0,
        right: 0,
        top: 125,
        bottom: 0
    },
    classNames: ['bg-white'],
    
    tabLocation: SC.TOP_LOCATION,
    nowShowing: 'GoogleSearch.SearchTabView',
    itemTitleKey: 'title',
    itemValueKey: 'value',
    
    items: [
        { title: 'Otsi', value: 'GoogleSearch.SearchTabView' },
        { title: 'Tulemused', value: 'GoogleSearch.ResultsTabView' }
    ],
   
    tabsToggle: function()
    {
        (this.get('nowShowing') === 'GoogleSearch.ResultsTabView') ?
            this.set('nowShowing', 'GoogleSearch.SearchTabView') : 
            this.set('nowShowing', 'GoogleSearch.ResultsTabView');
    }
    
});
/* >>>>>>>>>> BEGIN source/resources/main_page.js */
sc_require('views/intro');
sc_require('views/tab_host');

GoogleSearch.mainPage = SC.Page.design({
    
    mainPane: SC.MainPane.design({
        childViews: ['headerView', 'tabHostView', 'loadingView'],
  
        headerView: GoogleSearch.IntroView.design(),
        tabHostView: GoogleSearch.TabHostView.design(),
        
        loadingView: SC.LabelView.design({
            layout: { top: 0, left: 0},
            classNames: ['loading-panel'],
            value: 'Laadin tulemusi...',
            isVisible: false
        })
    })
    
});
/* >>>>>>>>>> BEGIN source/main.js */
sc_require('controllers/search_controller');

GoogleSearch.main = function main() {

    GoogleSearch.getPath('mainPage.mainPane').append();

    // Register TabHost
    GoogleSearch.get('searchController').registerTabHostView(
            GoogleSearch.get('mainPage').get('mainPane').get('tabHostView')
    );
    // Register LoadingPanel
    GoogleSearch.get('searchController').registerLoadingPanel(
            GoogleSearch.get('mainPage').get('mainPane').get('loadingView')
    );
         
};


function main() { GoogleSearch.main(); }

