function Favourites(args) {
    this.config = new Object;
    if (typeof(args) == 'object') {
      for (k in args) {
        if (k == 'message') continue;
        this.config[k] = args[k];
      }
    }
    if (!this.config['xml_path']) this.config['xml_path'] = '/xml';
    
    this.cookie_name    = 'nissan-offers-favourites';
    this.cookie_expiry  = 365; //  days;
    this.max_favourites = 6;

    if (!args.message) {
      this.message = {
          removed : 'The vehicle has been removed from your favourites',
          added : 'The vehicle has been added to your favourites',
          saved : 'Your favourites have been saved',
          maxhits : 'Please remove one of the vehicles from your favourites before adding a new one',
          empty : 'There are no vehicles in your favourites',
          require2selected : 'Please select 2 favourites to compare',
          noselected : 'Please select 2 favourites to compare',
          dupe : 'The vehicle is already in your favourites',
          nofaves : 'There are no favourites'
      };
    }
    else this.message = args.message;
}

Favourites.prototype.init = function () {
    this._loadFavourites();
    return;

// User logins not used any more
/*
    var me = this;
    $.get('/favourites?sync=1', {}, function(request) {
        var afav = request.getElementsByTagName('favourites');
        if (afav.length > 0) {
            me._loadFavourites(afav[0].firstChild.nodeValue);
        }
        else {
            me._loadFavourites();
        }
    }, 'xml');
*/
};

Favourites.prototype.shareFavourites = function () {
    $('#feedbackPanel').hide();
    if ($('#favForm .carShot img').length === 0) {
        this._favMessage(this.message.empty);
        return;
    }
    var args = '';
    if (window.location.search.match(/[?&;]d=1/)) {
        args += 'd=1';
    }
    if (window.location.search.match(/[?&;]t=([^&;]+)/)) {
        args += (args.length ? ';' : '') + 't=' + RegExp.$1;
    }
    if ($('#lang').length > 0) {
        var t = $('#lang').val();
        args += ';t='+t;
    }
    window.location = '/favourites' + (args.length ? '?' : '') + args;
};

Favourites.prototype.saveFavourites = function () {
    var fav = this._getCookie(this.cookie_name);
    if (fav) {
        this._setCookie(this.cookie_name, fav, 365);
        this._favMessage(this.message.saved);
    }
    else {
        this._favMessage(this.message.empty);
    }
};

Favourites.prototype.compare2Favourites = function () {
    $('#feedbackPanel').hide();

    var $checked = $('#favForm input[name=fav]:checked');

    if ($checked.length <= 1 || $checked.length > 2) {
        this._favMessage($checked.length === 0 ? this.message.noselected : this.message.require2selected);
        return;
    }
    $('#favForm').submit();
};

Favourites.prototype.checkFavourites = function (flag) {
    var $checked = $('#favForm input[name=fav]:checked');

    if ($checked.length == 2) {
        $('#favForm input[name=fav]:not(:checked)').attr('disabled', true);
    }
    else {
        $('#favForm input[name=fav]').each(function () {
            var $input = $(this);
            if ($input.parent().parent().find('.carShot img').length) {
                $input.attr('disabled', false);
            }
            else {
                $input.attr('disabled', true);
            }
        });
    }
};

Favourites.prototype.addToFavourites = function (id) {
    $('#feedbackPanel').hide();

    var fav = this._getCookie(this.cookie_name);
    var found = false;
    if (fav) {
        var aID = fav.split(",");
        if (aID.length >= this.max_favourites) {
            this._favMessage(this.message.maxhits);
            return;
        }

        for (var i = 0; i < aID.length; i++) {
            if (id == aID[i]) {
                found = true;
                break;
            }
        }

        fav += ',' + id;
    }
    else {
        fav = id;
    }

    if (!found) {
        this._favMessage(this.message.added);
        this._setCookie(this.cookie_name, fav, this.cookie_expiry);
        this._loadFavourite(id);

// Save the favourite into Bookmark_Links
//        $.get('/favourites?sync=1;add=' + id);
    }
    else {
        this._favMessage(this.message.dupe);
    }
};

Favourites.prototype.removeFromFavourites = function (link) {
    $('#feedbackPanel').hide();

    var $link = $(link);
    var $spot = $link.parent().parent().parent();
    var $input = $spot.find('input');
    var id = $input.val();
    if (!id) {
        return;
    }

    var fav = this._getCookie(this.cookie_name);
    var found = false;
    if (fav === '') {
        this._favMessage(this.message.nofaves);
        return;
    }
    var aID     = fav.split(",");
    var aFav    = [];
    var deleted = false;
    for (var i = 0; i < aID.length; i++) {
        if (id != aID[i]) {
            aFav.push(aID[i]);
        }
        else {
            deleted = true;
        }
    }

    fav = aFav.join(",");
    this._setCookie(this.cookie_name, fav, this.cookie_expiry);

    if (deleted) {
        this._favMessage(this.message.removed);

        $input.val('');
        $input.attr('disabled', true);
        $input.attr('checked', false);

        $spot.find('.carShot').html('');

        this.checkFavourites();

// Remove the favourite from Bookmark_Links
//        $.get('/favourites?sync=1;remove=' + id);
    }
};

/* position: 1 = left, 2 = right */
Favourites.prototype.compareUpdate = function (from, to, position) {
    if (!from || !to) {
        return;
    }
    var url = window.location.href;
    if (position == 2) {
        window.location.href = url.replace(new RegExp('(fav=\\d+.*fav=)' + from), "$1" + to);
    }
    else {
        window.location.href = url.replace(new RegExp('fav=' + from), 'fav=' + to);
    }
};

Favourites.prototype.shareURL = function () {
    var $form = $('<form action="/favourites" method="post"></form>');
    if (window.location.search.match(/[?;&]d=1/)) {
        $form.append($('<input type="hidden" name="d" value="1" />'));
    }
    if (window.location.search.match(/[?;&]t=([^;&]+)/)) {
        $form.append($('<input type="hidden" name="t" value="' + RegExp.$1 + '" />'));
    }
    else if ($('#lang').length > 0) {
        var t = $('#lang').val();
        if (t.search(/befr|benl|lux/) == 0) $form.append($('<input type="hidden" name="t" value="' + t + '" />'));
    }
    
    $form.append($('<input type="hidden" name="url" value="' + window.location + '" />'));
    $(document.body).append($form);
    $form.submit();
};

Favourites.prototype._loadFavourites = function (fav) {
    if (typeof(fav) == 'undefined') {
        fav = this._getCookie(this.cookie_name);
    }

// Loading favourites from cookie
    if (fav) {
        var aID = fav.split(",");
        for (var i = 0; i < aID.length; i++) {
            this._loadFavourite(aID[i]);
        }
    }
};

Favourites.prototype._loadFavourite = function (id) {
    var url = window.location.search.match(/[?;&]d=1/) ? ('/cgi-bin/xml.cgi?d=1;id=' + id) : (this.config.xml_path + '/' + id + '.xml');
    var me = this;
    $.ajax({
        type : 'get',
        url : url,
        dataType : 'xml',
        success : function(response) {
            me._parseFavourite(response);
        },
        error : function() {
            me.removeFromFavourites(id);
        }
    });
};

Favourites.prototype._parseFavourite = function (request) {
    var offers = request.getElementsByTagName('offer');
    var $spots = $('.carChoice');

    for (var i = 0; i < offers.length; i++) {
        var offer = this._parseOffer(offers[i]);
        if (!offer.offerid) {
            continue;
        }

        var $input = $($spots.find('input[value=]')[0]);
        if ($input.length) {
            $input.val(offer.offerid);
            $input.attr('disabled', false);
            $input.attr('checked', false);

            $input.parent().parent().children('.carShot').html('<a href="' + offer.detailed_url + '" title="' + offer.vehicle_name + '"><img src="' + offer.vehicle_fav_image + '" width="112" height="58" alt="' + offer.vehicle_name + '" title="' + offer.vehicle_name + '" /></a>');
        }
    }
};

Favourites.prototype._parseOffer = function (offer) {
    var columns = ['offerid', 'vehicle_fav_image', 'vehicle_name', 'detailed_url'];
    var link = {};

    for (var i = 0; i < columns.length; i++) {
        var cObj = offer.getElementsByTagName(columns[i]);

        if (cObj.length === 0) {
            continue;
        }
        link[columns[i]] = cObj[0].firstChild.nodeValue;
    }

    return link;
};

Favourites.prototype._favMessage = function (msg) {
    var $fbPanel = $('#feedbackPanel').html(msg);
    $fbPanel.show();
    setTimeout(function () { $fbPanel.hide() }, 10000);
};

Favourites.prototype._getCookie = function (name) {
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        var aPart = aCookie[i].split("=");
        if (aPart[0] == name) {
            return unescape(aPart[1]);
        }
    }
};

Favourites.prototype._setCookie = function (name, value, expires) {
    var date  = new Date();
    date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * expires));
    document.cookie = name + "=" + escape(value) + "; path=/" + ((expires === 0) ? "" : "; expires=" + date.toGMTString());
};

