var GoogleSearch = new Class({
    Implements: [Options],
    options: {
        form : 'search_form',
        input : 'search_input',
        result : 'work_field',
        inputVal : 'поиск',
        siteURL		: 'vkurseweba.ru',
        searchSite	: true,
        type		: 'web',
        append		: false,
        perPage		: 8,			// A maximum of 8 is allowed by Google
        page		: 0,				// The start page
        term : ''
    },
    initialize: function(options){

        this.setOptions(options);
        this.searchForm = document.id(this.options.form);
        this.searchInput = document.id(this.options.input);
        this.resultDiv = document.id(this.options.result);
        if (!this.searchForm || !this.searchInput || !this.resultDiv) return;

        this.initForm().initNoti().initAutocompleter(); //.initInput();

    },/*
    initInput: function(){
        var val = this.options.inputVal;
        this.searchInput.set({
            value: val,
            events: {
                focus: function(){
                    if(this.value == val) {
                        this.value = '';
                    }
                },
                blur: function(){
                    if(!this.value) {
                        this.value = val;
                    }
                }
            }
        });
        return this;
    },*/
    initNoti: function(){

        this.noti = new myNotimoo({
            width: 301,
            height: 120,
            locationVBase: 0,
            notificationOpacity: 1,
            visibleTime: 2000,
            injectTo: 'sidebar'
        });

        return this;

    },
    initAutocompleter: function(){

        new Autocompleter.Request.JSON(this.searchInput, '/autocomplete/keywords', {
            width: 260,
            onSelection: function(){
                this.googleSearch();
            }.bind(this)
        });

        return this;
    },
    initForm: function(){
        this.searchForm.addEvent('submit', function(e){
            this.googleSearch();
            e && e.stop();
        }.bind(this));
        return this;
    },
    googleSearch: function(options){

        this.setOptions(options);
        var term = this.options.term || this.searchInput.get('value');

        var category = 'search',
        action = 'query';
        if (typeof(pageTracker) == 'object') pageTracker._trackEvent(category, action, term);
        else if(typeof(_gaq) == 'object') _gaq.push(['_trackEvent', category, action, term])
        else throw('Google Analytics tracking object not found'); // if you need to throw errors;

        if(this.options.searchSite){
            term = 'site:'+this.options.siteURL+' '+term;
        }

        var apiURL = 'http://ajax.googleapis.com/ajax/services/search/' + this.options.type + '?v=1.0';

        new Request.JSONP({
            url: apiURL,
            data: {
                q	: term,
                rsz	: this.options.perPage,
                start	: this.options.page * this.options.perPage
            },
            onSuccess: this.procResults.bind(this),
            onRequest: function(){
                this.resultDiv.addClass('loading');
            }.bind(this),
            onComplete: function(){
                this.resultDiv.removeClass('loading');
            }.bind(this),
            timeout: 5000
        }).send();

    },
    procResults: function(o){

        var more = this.resultDiv.getElement('#more'),
        options = this.options,
        results = o.responseData.results;

        more && more.dispose();

        if(results.length){

            var output = '';
            for(var i = 0; i < results.length; i++){
                output += this.markup(results[i]);
            }

            var height = this.resultDiv.getSize().y;
            this.resultDiv.setStyle('height', height);

            if(options.append){
                var ul = this.resultDiv.getElement('ul'),
                html = ul.get('html');
                html += output;
                ul.set('html', html);
            }
            else {
                output = '<ul id="articles" class="site_search">' + output + '</ul>';
                this.resultDiv.empty();
                var pageContainer = new Element('div', {
                    'class': 'pageContainer',
                    html: output
                });
                pageContainer.inject(this.resultDiv);
                pageContainer.getElements('li:first-child').addClass('first');
            }

            var cursor = o.responseData.cursor;

            if( +cursor.estimatedResultCount > (options.page + 1) * options.perPage){
                more = new Element('div',{
                    id:'more',
                    events: {
                        click:function(){
                            this.googleSearch({
                                append:true,
                                page:options.page + 1
                            });
                            more.fade('out');
                        }.bind(this)
                    }
                }).inject(this.resultDiv);
            }

            this.resultDiv.setStyle('height', 'auto');
            var height2 = this.resultDiv.getSize().y;
            this.resultDiv.tween('height', height, height2);

        }
        else {
            this.noti.show({
                message: 'По вашему запросу ничего не найдено'
            });
        }
    },
    markup : function(r){

        // This is class definition. Object of this class are created for
        // each result. The markup is generated by the .toString() method.

        var arr = [];

        r.title = r.title.replace(/(».+)$/, '');

        // GsearchResultClass is passed by the google API
        switch(r.GsearchResultClass){

            case 'GwebSearch':
                arr = [
                '<li>',
                '<h1><a href="',r.url,'">',r.title,'</a></h1>',
                '<p>',r.content,'</p>',
                '<i>',r.visibleUrl,'</i>',
                '</li>'
                ];
                break;
            case 'GimageSearch':
                arr = [
                '<li class="imageResult">',
                '<a href="',r.url,'" title="',r.titleNoFormatting,
                '" class="pic" style="width:',r.tbWidth,'px;height:',r.tbHeight,'px;">',
                '<img src="',r.tbUrl,'" width="',r.tbWidth,'" height="',
                r.tbHeight,'" /></a>','<div class="clear"></div>',
                '<a href="',r.originalContextUrl,'">',r.visibleUrl,'</a>',
                '</li>'
                ];
                break;
            case 'GvideoSearch':
                arr = [
                '<li class="imageResult">',
                '<a href="',r.url,'" title="',r.titleNoFormatting,'" class="pic" style="width:150px;height:auto;">',
                '<img src="',r.tbUrl,'" width="100%" /></a>',
                '<div class="clear"></div>','<a href="',
                r.originalContextUrl,'">',r.publisher,'</a>',
                '</li>'
                ];
                break;
            case 'GnewsSearch':
                arr = [
                '<div class="webResult">',
                '<h2><a href="',r.unescapedUrl,'">',r.title,'</a></h2>',
                '<p>',r.content,'</p>',
                '<a href="',r.unescapedUrl,'">',r.publisher,'</a>',
                '</li>'
                ];
                break;
        }


        return arr.join('');

    }

});

window.addEvent('domready', function(){
    new GoogleSearch();
});
