﻿var TrackReferrer = new Class({
    initialize: function() {
        this.maxurls = 5;
        this.hash = new Hash.Cookie('ref', { 'path': '/', 'duration': 30 });
        this.data = this.hash.get('data');
        if (!this.data)
            this.data = [];
    },
    
    update: function() {
        var referrer = document.referrer;
        if (referrer && referrer.indexOf('http://' + window.location.host) != 0 && referrer.indexOf('https://' + window.location.host) != 0) {
            var found = false;
            this.data.each(function(r) {
                found = found || referrer == r;
            });
            if (!found) {
                this.data[this.data.length] = referrer;
                if (this.data.length > this.maxurls)
                    this.data.splice(0,1);
                this.hash.set('data', this.data);
                this.hash.save();
            }
        }
        return this;
    },
    
    list: function() {
        return this.data;
    },
    
    serialize: function() {
        var result = '';
        for (var i=0; i<this.data.length; i++) {
            if (i>0) result += '\n';
            result += this.data[i];
        }
        return result;
    }
});

window.addEvent('domready', function() {
    new TrackReferrer().update();
});
