/* Site search with the Google AJAX Search API. */

var results_div_box = 'search_results_box';
var results_div_id = 'search_results';

function site_search(domain, query, txt_enterquery,  txt_searching, txt_noresults) {
    // must not be empty
    if (!query.match('\\S')) {
        alert(txt_enterquery);
        return;
    }

    this.query = query;
    this.txt_noresults = txt_noresults;

    // tell the user we're searching
    this.box = document.getElementById(results_div_box);
    this.box.style.display = 'block';

    this.page = document.getElementById(results_div_id);
    this.page.id = results_div_id;
    this.page.innerHTML += '<p>'+txt_searching+'</p>';

    // set up the search
    this.gwebsearch = new GwebSearch();
    this.gwebsearch.setResultSetSize('large');
    this.gwebsearch.setUserDefinedLabel('');
    this.gwebsearch.setLinkTarget(GSearch.LINK_TARGET_SELF);
    this.gwebsearch.setSiteRestriction(domain);

    this.gwebsearch.clearResults();
    this.gwebsearch.setSearchCompleteCallback(this, site_search.prototype.done);

    // set up the page
    this.branding = GSearch.getBranding();
    this.page.innerHTML = '<table class="gsc-branding"><tr><td class="gsc-branding-text" style="margin-right: 2px; font-size: 8px padding-bottom : 2px; text-align : right; vertical-align : top;">s tehnologijom </td><td> <img src="http://www.google.com/uds/css/small-logo.png" alt="" style="vertical-align : bottom;" /></td></tr></table>';
    this.page.innerHTML += '<p style="text-align: right; padding-right: 10px"><a href="/pretraga/?q=' + this.query + '">Otvori rezultate u novoj stranici</a></p>';
    this.page.appendChild(this.branding);

    // go!
    this.gwebsearch.execute(query);
}

site_search.prototype.done = function() {
    results = this.gwebsearch.results;
    for (i = 0; i < results.length; i++) {
        results[i].html.childNodes[1].innerHTML = "<a href='"+results[i].unescapedUrl+"'>"+results[i].unescapedUrl+"</a>";
        this.page.insertBefore(results[i].html.cloneNode(true), this.branding);
    }

    cursor = this.gwebsearch.cursor;

    if ( ! cursor && results.length == 0) {
        this.page.innerHTML += '<p>'+this.txt_noresults+'</p>';
    } else if (cursor.currentPageIndex < cursor.pages.length - 1) {
        // this is recursive. GWebSearch will re-call its callback, ie this function, when it gets the next page of result.
        this.gwebsearch.gotoPage(cursor.currentPageIndex + 1);
    }
}