$(document).ready(function ()
{
    /*
     * Procedures
     */

    // Show Overlay
    function showOverlay(message, fn)
    {
        $('#overlay > div h3').text(message);
        $('#overlay').fadeIn();
        if(fn)
            fn();
    }

    // Hide Overlay
    function hideOverlay()
    {
        $('#overlay').fadeOut();
    } 

    // Notify
    function notify(message)
    {
        showOverlay(message);
        setTimeout(function () { hideOverlay(); }, 1000);
    }

    // Init table
    function initTable(resultSet)
    {
        emptyTable();
        setResultsCount(resultSet.searchInformation.formattedTotalResults);
        initPagination(resultSet);
    }

    // Set results count
    function setResultsCount(count)
    {
        $('#resultCount').text(count);
        $('#resultCount').show();
    }

    // Activate results tab
    function activateResultsTab()
    {
        $('#main-tabs a[href="#results"]').tab('show');
    }

    // Empty results
    function emptyTable()
    {
        $('#resultTable > tbody:last').empty();
    }

    // Fill table
    function fillTable(resultSet)
    {
        for(var i = 0; i < resultSet.items.length; i++)
        {
            var row = '<tr><td><h5 class="text-left"><a href="{link}">{title}</a></h5><p class="text-left">{brief}</p><p class="text-info"><a href="{link}">{displayLink}</a></p>';
            $('#resultTable > tbody:last').append(
                     row.replace('{title}', resultSet.items[i].htmlTitle)
                        .replace('{brief}', resultSet.items[i].htmlSnippet)
                        .replace(new RegExp('{link}', 'g'), resultSet.items[i].link)
                        .replace('{displayLink}', resultSet.items[i].displayLink)

            );
        }
    }

    // Init pagination
    function initPagination(resultSet)
    {
        var count = resultSet.queries.request[0].count;
        var total = resultSet.queries.request[0].totalResults;
        var start = resultSet.queries.request[0].startIndex;

        var prev = '<li class="previous {disabled}" data-start="{start}"><a href="javascript:void(0);">&larr; Eelmised</a></li>';
        var next = '<li class="next {disabled}" data-start="{start}"><a href="javascript:void(0);">Järgmised &rarr;</a></li>';

        $('#showingResultsOf').html("<em>Näitan tulemusi " + start + " - " + (start + count - 1) + "  " + total + "-st.</em>");

        // Remove
        $('#pagination').empty();

        // Init and fill
        if(start === 1)
        {
            prev = prev.replace('{disabled}', 'disabled');
            prev = prev.replace('{start}', '');
        }
        else
        {
            prev = prev.replace('{start}', start - 10);
        }

        if(start + count < total)
        {
            next = next.replace('{disabled}', '');
            next = next.replace('{start}', start + 10);
        }
        else
        {
            next = next.replace('{disabled}', 'disabled');
            next = next.replace('{start}', '');
        }

        $('#pagination').append(prev);
        $('#pagination').append(next);

        // Assign event handlers
        $('#pagination li').click(function ()
        {
            if(! $(this).hasClass('disabled'))
            {
                showOverlay('Laadin tulemusi...',
                    doSearch(
                            $('#query').val(),
                            $(this).data('start'),
                            10,
                            ($('#filter').is(':checked') ? 1 : 0),
                            handleQuery
                        )
                );
            }
        });

        // Scroll to results
        $('html, body').animate({
            scrollTop: $('#resultTable').offset().top
        }, 1000);
    }

    // Query
    function doSearch(query, start, count, filter, fn)
    {  
        var searchAPI = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyAvnr_EiOfpj0Ub97QkQIEek6npmDFoZko&cx=002647590579739994937:ntvk68za0vo&q={query}&num={num}&start={start}&filter={filter}';

        $.get(searchAPI.replace('{query}', query).replace('{num}', count).replace('{start}', start).replace('{filter}', filter), function (data)
        {
            fn(data);
        }, 'json').fail(function (e)
        {
            notify('Andmevahetusel tekkis viga! Korda otsingut!');
            $('#searchBtn').button('reset');
        });
    }

    // Handle query
    function handleQuery(response)
    {
		if(response.items) 
		{
			initTable(response);
			fillTable(response);
			activateResultsTab();

			// Dismiss idle
			$('#searchBtn').button('reset');

			// Hide overlay
			hideOverlay();
		} 
		else
		{
			// Dismiss idle
			$('#searchBtn').button('reset');

			// Hide overlay
			hideOverlay();
			
			notify('Andmevahetusel tekkis viga! Korda otsingut!');
		}
    }

    /*
     * Event handlers
     */ 

    // Search Button clicked
    $('#searchBtn').click(function()
    {
        if($('#query').val())
        {
            // Show idle
            $('#searchBtn').button('loading');

            // Handle query
            doSearch($('#query').val(), 1, 10, ($('#filter').is(':checked') ? 1 : 0), handleQuery);
        }
        else
        {
            notify('Otsisõna sisestamata!');
        }
    });
});    