﻿var Event = YAHOO.util.Event;
var Dom = YAHOO.util.Dom;
var $ = Dom.get;

ajax_request = function() {

    this.success = null;
    this.failure = null;
    this.scope = null;
    this.cache = null;

    if (arguments[0] != null)
        this.success = arguments[0];

    if (arguments[1] != null)
        this.failure = arguments[1];

    if (arguments[2] != null)
        this.scope = arguments[2];

    if (arguments[3] != null)
        this.cache = arguments[3];

    this.call = function(u) {

        var _callback = {
            success: this.success,
            failure: this.failure,
            scope: this.scope,
            cache: this.cache
        };

        YAHOO.util.Connect.asyncRequest('GET', u, _callback, null);

    };
}

basketManager = {

    genericFailure: function(o) {

        alert('Failed to communicate with server. Please refresh the page.');
    },

    getBasket: function() {

        var url = '/_common/services/getbasket.aspx';

        var request = new ajax_request();
        request.success = this.getBasketSuccess;
        request.failure = this.genericFailure;
        request.cache = false;
        request.scope = this;

        request.call(url);

        return false;
    },

    getBasketSuccess: function(o) {

        $('miniBasket').innerHTML = o.responseText;
    },

    updateBasket: function(productId, qtyCtrl, mode) {

        var qty = $(qtyCtrl).value;
        $(qtyCtrl).value = '';

        var url = '/_common/services/savebasket.aspx';

        url += '?productId=' + productId;
        url += '&qty=' + qty;
        url += '&mode=' + mode;

        if (qty == '') {
            alert('Please enter a quantity');
            return false;
        }

        if (isNaN(qty)) {
            alert('The quantity field only accepts numbers.');
            return false;
        }

        var request = new ajax_request();
        request.success = this.updateBasketSuccess;
        request.failure = this.genericFailure;
        request.cache = false;
        request.scope = this;

        request.call(url);

        return false;
    },

    updateBasketSuccess: function(o) {

        basketManager.getBasket();
    }
};
