SearchHelper = {
    ajaxUrl: '',
    qsa: '',

    _searchControl: null,
    _inputObserver: null,
    _inputAjaxUpdater: null,

    initialize: function(url) {
        this.ajaxUrl = url;
        this._searchControl = $('searchbox');
        Event.observe(this._searchControl, "keypress", this.onSearchKeyPress.bindAsEventListener(this));
    },

    onSearchKeyPress: function (event) {
        if (this._inputObserver) clearTimeout(this._inputObserver);
        this._inputObserver = setTimeout(this.onTimerAfterKeyPress.bind(this), 200);
    },

    onTimerAfterKeyPress: function(event) {
        if (this._inputAjaxUpdater) {
            this._inputAjaxUpdater.transport.abort();
        }

        var l = this._searchControl.value.strip().length;
        if (l > 1 || l == 0) {
            this._inputAjaxUpdater = new Ajax.Updater(
                'jit_static__personalnavigation', 
                this.ajaxUrl + "?keyword=" + encodeURIComponent(this._searchControl.value) + (this.qsa != '' ? '&' + this.qsa : ''), {
                evalScripts: true
            });
        }
    }
}




ShoppingCard = {
    
    locale: '',
    ajaxUrl: '',
    checkoutUrl: '',
    
    quantityToInt: function(quantity) {
        if (typeof quantity == "string") {
            quantity = quantity.toLowerCase().replace(/^\s+|\s+$/g, '');
        }
        var value = parseInt(quantity);

        if (!isNaN(value)) return value;

        switch (quantity) {
            case 'eins':
            case 'one':return 1;
            case 'zwei':
            case 'two':return 2;
            case 'drei':
            case 'three':return 3;
            case 'vier':
            case 'four':return 4;
            case 'fünf':
            case 'five':return 5;
            case 'sechs':
            case 'six':return 6;
            case 'sieben':
            case 'seven':return 7;
            case 'acht':
            case 'eight':return 8;
            case 'neun':
            case 'nine':return 9;
            case 'zehn':
            case 'ten':return 10;
            case 'elf':
            case 'eleven':return 11;
            case 'zwölf':
            case 'twelve':return 12;
        }

        return 0;
    },


    formatCurrency: function(price) {
        if (this.locale == 'de') return (price/100).toFixed(2).replace(/\./g, ",") + " &euro;";
        return "&euro;" + (price/100).toFixed(2);
    },
    
    addQuantity: function(event_id, category, quantity) {
        var el            = $('quantity_' + event_id + '_' + category);

        this.setQuantity(event_id, category, Math.max(0, parseInt(el.value) + quantity));
    },


    setQuantity: function(event_id, category, quantity) {
        var el            = $('quantity_' + event_id + '_' + category),
            quantity      = Math.min(1000, Math.max(0, this.quantityToInt(quantity)));

        el.value = quantity;
        this.updatePrice(event_id, category);

        var ajax = new Ajax.Request(this.ajaxUrl, {
            method: 'post',
            parameters: 'quantity[' + event_id + '][' + category + ']=' + quantity,

            onSuccess: (function(transport) {
                $('card_item_event_' + event_id + '_' + category).removeClassName('error');
            }).bind(this),

            onFailure: (function(transport) {
                var response = $H(eval('(' + transport.responseText + ')'));
                if (response['errors']) {
                    $H(response['errors']).each(function(item) {
                        var input = item[0].replace(/[^_]*_/, '');
                        var error = item[1];
                        $('card_item_event_' + event_id + '_' + category).addClassName('error');
                        $('notice_' + input).innerHTML = error;
                    });
                }
                if (response['available']) {
                    $H(response['available']).each(function(item) {
                        var input = item[0];
                        var available = item[1];
                        $('quantity_' + input).value = available;
                    });
                }
                this.updatePrice(event_id, category);
            }).bind(this)
        });
    },


    updatePrice: function(event_id, category) {
        var el            = $('quantity_' + event_id + '_' + category),
            elSinglePrice = $('single_price_' + event_id + '_' + category),
            elTotalPrice  = $('total_price_' + event_id + '_' + category),
            elSingleFee   = $('single_fee_' + event_id + '_' + category),
            elTotalFee    = $('total_fee_' + event_id + '_' + category),
            elTotalSum    = $('total_sum'),
            quantity      = Math.max(this.quantityToInt(el.value)),
            price,
            _this         = this;

        if (quantity < 0)    quantity = 0;
        if (quantity > 1000) quantity = 1000;

        if (elTotalPrice && elSinglePrice) {
            price = elSinglePrice.value * quantity;
            elTotalPrice.update(this.formatCurrency(price));
            
            if (elTotalFee && elSingleFee) {
                price = elSingleFee.value * quantity;
                elTotalFee.update(this.formatCurrency(price));
            }
            
            if (elTotalSum) {
                price = 0;        
                $$("input.shoppingcarditem").each(function(el) {
                    matches = el.id.match(/quantity_(\d+)_(\d+)/);
                    event_id = matches[1];
                    category = matches[2];
                    elSinglePrice = $('single_price_' + event_id + '_' + category);
                    price += elSinglePrice.value * _this.quantityToInt(el.value);
                    elSingleFee = $('single_fee_' + event_id + '_' + category);
                    if (elSingleFee) {
                        price += elSingleFee.value * _this.quantityToInt(el.value);
                    }
                });
                elTotalSum.update(this.formatCurrency(price));
            }
        }
    },

    updateCard: function() {
        new Ajax.Updater('shopping_card_salable', this.ajaxUrl, {
            parameters: $('shopping_card_form').serialize()
        });
    },

    openCheckout: function() {
        window.open(this.checkoutUrl, "jit_checkout", "width=700,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no");
    },

    openTermsOfUse: function(anchor) {
        window.open(anchor.href, "jit_termsofuse", "width=700,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no");
    },
    
    updateTouLink: function(directDebit) {
        var elCb = $("accept_tou_1"), elLab = $("accept_tou_label"), elLabDD = $("accept_tou_label_directdebit");
        
        if (elCb) elCb.checked = false;
        if (elLab && elLabDD) {
            ( directDebit ? elLab : elLabDD).hide();
            (!directDebit ? elLab : elLabDD).show();
        }
    }

}

