BacklinksHandler = new Class({
    initialize: function(form) {
        this.input_panel = $('input_panel');
        this.search_form = $('search_form');
        this.progress_panel = $('progress_panel');
        this.done_panel = $('done_panel');
        this.lookup_counts = $('lookup_counts');
        this.used_count = $('used_count');
        this.limited_panel = $('limited_panel');
        this.results_panel = $('results_panel');
        this.results_table = $('results_table');
        this.lines_per_chunk = 5;
        this.domains = [];
        this.total_domains_count = 0;
        this.limited = false;
        this.test_limit = null;
        this.timeout = null;
        this.done_pre_check = false;
        this.attach();
    },
    lookup: function() {
        var chunk = this.domains.splice(0, this.lines_per_chunk);
        var param = chunk.join(',');
        if (param) {
            new Request.JSON({
                url: '/check/?domains=' + encodeURIComponent(param) + (this.test_limit != null ? '&test-limit='+this.test_limit : ''),
                onSuccess: function(info){
                    if (info.rate_limited) {
                        this.limited = true;
                        this.hide(this.done_panel);
                        this.show(this.limited_panel);
                    }
                    this.update_progress();
                    this.update_used(info.total_lookup_count, info.lookup_limit);
                    this.show(this.results_panel);
                    if (info.results != false) {
                        for (var domain in info.results) {
                            var attr_url = 'http://backlinks.in/go/open-site-explorer/' + encodeURIComponent(domain);
                            var tr = new Element('tr');
                            var td_domain = new Element('td');
                            td_domain.adopt(new Element('a', {
                                text: domain, 
                                href: attr_url,
                                target: '_blank',
                                events: {click: this.pre_check.bind(this)},
                                title: 'More info on '+domain+' from Open Site Explorer'
                            }));
                            var link_count = info.results[domain].link_count;
                            var td_count = new Element('td', {'class': isNaN(link_count) ? 'error' : 'number'});
                            td_count.adopt(new Element('a', {
                                text: info.results[domain].link_count, 
                                href: attr_url,
                                target: '_blank',
                                events: {click: this.pre_check.bind(this)},
                                title: 'More info on '+domain+' link count from Open Site Explorer'
                            }));
                            var td_rank = new Element('td', {'class': isNaN(link_count) ? 'error' : 'rank'});
                            td_rank.adopt(new Element('a', {
                                text: info.results[domain].mozrank.toFixed(2), 
                                href: attr_url,
                                target: '_blank',
                                events: {click: this.pre_check.bind(this)},
                                title: 'More info on '+domain+' mozRank from Open Site Explorer'
                            }));
                            tr.adopt(td_domain, td_rank, td_count);
                            this.insert_row(tr, link_count);
                        }
                    }
                }.bind(this)
            }).get();
        }
        if (this.domains.length > 0)
            this.timeout = setTimeout(this.lookup.bind(this), 5000);
        else
            setTimeout(this.done.bind(this), 2000);
    },
    pre_check: function(e) {
        if (!this.done_pre_check) {
            var iframe = new IFrame('iframe', {
                src: 'http://backlinks.in/go/open-site-explorer',
                styles: {
                    position: 'absolute',
                    width: 1,
                    height: 1,
                    border: 'none'
                }
            });
            $(document.body).adopt(iframe);
            this.done_pre_check = true;
        }
    },
    insert_row: function(tr, link_count) {
        var tbody = this.results_table.tBodies[0];
        if (isNaN(link_count) || tbody.rows.length == 0)
            tr.inject(tbody, 'bottom');
        else {
            var last_row_index = tbody.rows.length - 1;
            for (var index = 0; index < tbody.rows.length; index++) {
                var row = tbody.rows[index];
                var current_count = row.cells[2].get('text');
                if (isNaN(current_count) || current_count < link_count) {
                    tr.inject(row, 'before');
                    break;
                }
                else if (index == last_row_index)
                    tr.inject(row, 'after');
            }
        }
        tr.set('tween', {duration: 2000});
        tr.highlight('#ffe150');
    },
    update_progress: function() {
        var count = this.total_domains_count - this.domains.length;
        this.lookup_counts.set('text', 'Processed ' + count + ' of ' + this.total_domains_count + ' recognised domains');
    },
    update_used: function(total_used, total_allowed) {
        this.used_count.set('html', "You've used " + total_used + ' of ' + total_allowed + ' lookups available today.  Need more? Try <a target="_blank" href="/go/open-site-explorer">Open Site Explorer</a> from SEOMoz.');
    },
    done: function() {
        this.hide(this.progress_panel);
        this.show(this.done_panel);
    },
    cancel: function() {
        clearTimeout(this.timeout);
        this.show(this.input_panel);
        this.hide(this.progress_panel);
    },
    more: function() {
        this.hide(this.done_panel);
        this.show(this.input_panel);
    },
    reset: function() {
        this.hide(this.done_panel);
        this.show(this.input_panel);
        this.results_table.tBodies[0].getChildren().dispose();
        this.hide(this.results_panel);
    },
    attach: function() {
        this.search_form.addEvent('submit', function(e){
            new Event(e).stop();
            this.domains = this.extract_all_domains(this.search_form.domains.value);
            this.total_domains_count = this.domains.length;
            this.hide(this.input_panel);
            this.show(this.progress_panel);
            this.update_progress();
            this.lookup();
        }.bind(this));
    },
    extract_all_domains: function(text) {
        text = text.toLowerCase();
        var domains = [];
        var regex = /(?:http:\/\/|https:\/\/)?([\w-_]+(?:[\w_\.-]+)?\.[a-z]{2,4})/gm;
        var result = null;
        while (result = regex.exec(text)) {
            if (!/\.php$/.test(result[1]) && domains.indexOf(result[1]) == -1)
                domains.push(result[1]);
        }
        return domains; 
    },
    hide: function(elem) {
        elem.style.display = 'none';
    },
    show: function(elem) {
        elem.style.display = 'block';
    }
});

