
var Api = {
    head: false,
    pn: 0,
    terms: '',

    init: function ()        
    {        
        var i,el,
            results = YAHOO.util.Dom.getElementsByClassName('result', 'div','main');
        for (i in results) {
            el = results[i];
            if (typeof el != 'function') {
                if (! el.id) {
                    continue;
                }
                this.capture(el,i);
            }
        }
    },
    capture: function (el,i)
    {
        var l,
            article = el.id,
            source = el.getAttribute('alt'),
            links = YAHOO.util.Dom.getElementsByClassName('capture', 'a',el);
            
        for (l in links) {
            links[l].onmousedown = function () { Api.click(source,article,i); }
        }
    },



    click: function (source,article,pos)
    {   
        pos = parseInt(pos,10)+1;
        var link = 'click.php?source_id='+source+'&article_key='+article+'&pos='+pos+'&pn='+this.pn+'&terms='+this.terms;
        this.send(link);
    },

    get_head: function ()
    {
        if (this.head) {
            return this.head;
        }
        var head = document.getElementsByTagName("head");
        if (head.length==0) {
            head = document.createElement("HEAD");
            document.appendChild(head);
        } else {
            head = head[0];
        }
        this.head = head;
        return head;
    },



    send: function (link)
    {
        link += '&ts='+ (new Date().getTime());        
        var js = document.createElement("SCRIPT");
            js.type="text/javascript";
            js.charset="utf-8";
            js.src = link;
        var head = this.get_head();
            head.appendChild(js);
        if (window.location.hash == '#debug') {
            try {
                console.log(js.src);
            } catch (e) {
                alert(js.src);
            }
        }
    }

}
