
$(document).ready(function() {

function number_format (number, decimals, dec_point, thousands_sep) {
    var exponent = "";
    var numberstr = number.toString ();
    var eindex = numberstr.indexOf ("e");
    var i;
    if (eindex > -1) {
        exponent = numberstr.substring (eindex);
        number = parseFloat (numberstr.substring (0, eindex));
    }
    if (decimals != null) {
        var temp = Math.pow (10, decimals);
        number = Math.round (number * temp) / temp;
    }
    var sign = number < 0 ? "-" : "";
    var integer = (number > 0 ? Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
    var fractional = number.toString ().substring (integer.length + sign.length);
    dec_point = dec_point != null ? dec_point : ".";
    fractional = decimals != null && decimals > 0 || fractional.length > 1 ? (dec_point + fractional.substring (1)) : "";
    if (decimals != null && decimals > 0) {
        for (i = fractional.length - 1, z = decimals; i < z; ++i) fractional += "0";
    }
    thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? thousands_sep : null;
    if (thousands_sep != null && thousands_sep != "") {
    	for (i = integer.length - 3; i > 0; i -= 3) integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
    }
    return sign + integer + fractional + exponent;
}

(function( $ ){
    $.fn.RWKCheckout = function( method, value ) {
        var methods = {
// BASE SHOW //
            showCheckout : function () {
                var obj = this;
                var jobj = $(this);
                obj.oldPosition = $(window).scrollTop();
                if ($('.co-bg').size()) return false;
                if (!$('.checkout', $(this)).size()) {
                    obj._initCheckout();
                }
                var bg = $('<div></div>').addClass('co-bg').css('height', ($('.page').outerHeight()-130)+'px').click(function () {
                    obj.hideCheckout();
                });
                $('.page').append(bg);
                $('.co-cart-arrow', jobj).removeClass('icon-arrow-down').addClass('icon-arrow-up');
                $('.checkout', jobj).show();
                obj.open = true;
            },
// BASE HIDE //
            hideCheckout : function () {
                var obj = this;
                var jobj = $(this);
                obj.open = false;
                $('.co-bg,.checkout-bg,.checkout-page').remove();
                $('.co-cart-arrow', jobj).addClass('icon-arrow-down').removeClass('icon-arrow-up');
                $('.checkout', jobj).hide();
                $(window).scrollTop(obj.oldPosition);
            },
// SAVE PAYMENT //
            _savePayment : function () {
                var obj = this;
                var jobj = $(this);
                var data = $('.co-form-payment, input[name="stored_card"]', jobj).serializeArray();
                data.push({name:'action', value:'update-payment'});
                return obj._query(data);
            },
            _addVoucher : function () {
                var obj = this;
                var jobj = $(this);
                var res = obj._query({action:'add-voucher',voucher:$('#co-voucher', jobj).val()});
                if (res) $('#co-voucher', jobj).val('');
                return res;
            },
            _requestPassword : function () {
                var obj = this;
                var jobj = $(this);
                var res, data;
                if ($('#co-login-user', jobj).val() == 'Benutzername, E-Mail-Adresse oder Kundennummer' || $('#co-login-user', jobj).val() == ''){
                    obj._showError([{message:'Bitte geben Sie Ihren Benutzernamen, Ihre E-Mail-Adresse oder Ihre Kundennummer ein. Sie erhalten dann ihr Passwort an die hinterlegte E-Mail-Adresse gesendet.',fields:['#co-login-user']}]);
                }
                else {
                    var data = {typ:'C',pwd:'',userpasswort:$('#co-login-user', jobj).val()};
                    $.ajax({
                        url:"/index.php",
                        async:false, dataType:"text", data:data,
                        type:'POST',
                        success:function (result) {
                            if (result.search(/Passwortanfrage\swurde\sper/) != -1) {
                                obj._showNote([{message:'Ihre Passwortanfrage wurde verarbeitet. Bitte schauen Sie in Ihrem E-Mail Postfach nach.',fields:[]}]);
                                $('.co-error', jobj).removeClass('co-error');
                            } else {
                                obj._showError([{message:'Leider konnte Ihr Benutzername nicht gefunden werden.',fields:['#co-login-user']}]);
                            }
                        }
                    });
                }
            },
// CC RESULT //
            ccResult : function (result) {
                var obj = this;
                var jobj = $(this);
                var errors = [];
                if (typeof result.status != 'undefined' && result.status == 'VALID') {
                    $('input[name="cardpan"]', jobj).val('');
                    $('input[name="cardcvc2"]', jobj).val('');
                    var truncated = result.truncatedcardpan;
                    $('input[name="pcardpan"]', jobj).val(result.pseudocardpan+''+truncated.substring(truncated.length - 3, truncated.length));
                    var res = obj._savePayment();
                    if (res) {
                        $('input[name="pcardpan"]', jobj).val('');
                        $('#co-stored-cc1', jobj)[0].checked = true;
                        $('input[name="stored_card"]', jobj).trigger("change");
                        obj._goTo('next');
                    }
                }
                else {
                    if (result.errorcode == 7 || result.errorcode == 1079) {
                        errors.push({message:result.customermessage, fields:["#co-card-cvc"]});
                    } else if (result.errorcode == 33) {
                        errors.push({message:result.customermessage, fields:["#co-card-expire-month", "#co-card-expire-year"]});
                    } else if (result.errorcode == 877) {
                        errors.push({message:result.customermessage, fields:["#co-card-number"]});
                    } else if (result.errorcode == 880) {
                        errors.push({message:result.customermessage, fields:["#co-card-type"]});
                    }
                    if (!errors.length) errors.push({message:'Die Kreditkartenprüfung ist fehlgeschlagen.', fields:[]});
                    obj._showError(errors);
                    return false;
                }
                return false;
            },
// CC CHECK //
            _ccCheck : function () {
                var obj = this;
                var jobj = $(this);
                var errors = [];
                if (
                    (!$('input[name="stored_card"]').size() || $('input[name="stored_card"]:checked').val() == 0)
                    && (!$('input[name="pcardpan"]').val() || $('input[name="stored_card"]:checked').val() == 0)
                ) {
                    //cc_error_reset();
                    cc_data['cardcvc2'] = $('input[name="cardcvc2"]', jobj).val($('input[name="cardcvc2"]', jobj).val().replace(/[^\d]/g, '')).val(); 
                    cc_data['cardpan'] = $('input[name="cardpan"]', jobj).val($('input[name="cardpan"]', jobj).val().replace(/[^\d]/g, '')).val();
                    cc_data['cardtype'] = $('select[name="cardtype"]', jobj).val();
                    cc_data['cardexpiredate'] = $('select[name="cardexpireyear"]', jobj).val()+''+$('select[name="cardexpiremonth"]', jobj).val();
                    if (cc_data['cardcvc2'].length == 0 || cc_data['cardcvc2'].length > 4) {
                        errors.push({message:'Bitte Prüfziffer prüfen.',fields:["#co-card-cvc"]});
                    }
                    if (cc_data['cardpan'].length < 16 || cc_data['cardpan'].length > 19) {
                        errors.push({message:'Bitte Kreditkartennummer prüfen.',fields:["#co-card-number"]});
                    }
                    if ($('select[name="cardexpireyear"]', jobj).val() == 0 || $('select[name="cardexpiremonth"]').val() == 0) {
                        errors.push({message:'Bitte geben Sie die Gültigkeitsdauer an.',fields:["#co-card-expire-month", "#co-card-expire-year"]});
                    }
                    if (errors.length) {
                        obj._showError(errors);
                        return false;
                    }
                    $('*', jobj).removeClass('co-error');
                    var pay1 = new PayoneRequest(cc_data, {"callback_function_name":obj.opt.cc_callback});
                    pay1.checkAndStore();
                    return false;
                }
            },
// PLACE ORDER //
            _placeOrder : function () {
                var obj = this;
                var jobj = $(this);
                var data = $('input,select,textarea', $('.co-place-order', jobj)).serializeArray();
                data.push({name:'action', value:'place-order'});
                obj._query(data);
                return false;
            },
// INIT CHECKOUT //
            _initCheckout : function () {
                var stamp = new Date().getTime();
                var obj = this;
                var jobj = $(this);
                $.ajax({
                    url: obj.opt.template+"?"+stamp,
                    async: false, dataType: "html",
                    success:function (html) { jobj.append(html); }
                });
                obj.checkout = true;
                obj._update();
                $('.co-step1', jobj).show();
                $('.co-step1 .co-topic-close, .co-shopping', jobj).click(function () {
                    obj.hideCheckout();
                    return false;
                });
                $('.cod-shipping', jobj).click(function () {
                    obj._query();
                    return false;
                });
                $('.co-step1 .co-next', jobj).click(function () {
                    if (window.location.protocol != 'https:' || window.location.pathname.substr(0, 12) != '/bestellung/') {
                        href = 'https://'+window.location.host;
                        if (window.location.pathname.substr(0, 12) != '/bestellung/') {
                            href = href + '/bestellung';
                        }
                        href = href + window.location.pathname + window.location.search;
                        window.location.href = href;
                    } else obj._goTo ('next')
                    return false;
                });
                $('.co-step1 .co-closed', jobj).click(function () { obj._goTo(1); });
                $('.co-step3 .co-closed', jobj).click(function () { obj._goTo(3); });
                $('.co-step4 .co-closed', jobj).click(function () { obj._goTo(4); });
                $('.co-step5 .co-closed', jobj).click(function () { obj._goTo(5); });
                $('.co-btn-login', jobj).click(function () { 
                    if (obj._query({action:'login',user:$('#co-login-user', jobj).val(),pass:$('#co-login-pass', jobj).val()})) {
                        obj._goTo('next');
                    }
                    return false;
                });
                $('#co-login-user,#co-login-pass', jobj).bind('keypress', function(e) {
                    var code = (e.keyCode ? e.keyCode : e.which);
                    if (code == 13) $('.co-btn-login', jobj).trigger('click');
                });
                $('#co-login-user').blur(function () {
                    if ($(this).val() == '') {
                        $(this).css('color', '#666666');
                        $(this).val('Benutzername, E-Mail-Adresse oder Kundennummer');
                    }
                });
                $('#co-login-user').focus(function () {
                    if ($(this).val() == 'Benutzername, E-Mail-Adresse oder Kundennummer') {
                        $(this).css('color', '#000000');
                        $(this).val('');
                    }
                });
                $('#co-login-pass').blur(function () {
                    if ($(this).val() == '') {
                        $(this).css('display', 'none');
                        $('#co-login-pass-txt').css('display', 'block');
                    }
                });
                $('#co-login-pass-txt').focus(function () {
                        $(this).css('display', 'none');
                        $('#co-login-pass').css('display', 'block');
                        $('#co-login-pass').focus();
                    });
                $('.co-voucher-reload', jobj).click(function () { 
                    if ($('#co-voucher', jobj).val().length) obj._addVoucher();
                    else $('#co-voucher', jobj)[0].focus();
                    return false;
                });
                $('.co-btn-register', jobj).click(function () {
                    if (typeof obj.plugin.customer != 'undefined' && typeof obj.plugin.customer.id != 'undefined' && obj.plugin.customer.id == 0) {
                        $('.co-register-aform', jobj).hide();
                        $('.co-btn-insert', jobj).unbind('click').click(function () {
                            var data = $('input, select', $('.co-register-uform', jobj)).serializeArray();
                            data.push({name:'action', value:'add-login'});
                            var res = obj._query(data);
                            if (res) {
                                $('.co-address-form', jobj).hide();
                                obj._goTo(3);
                            }
                            return false;
                        });
                    }
                    if ($('.co-register-full', jobj).is(':visible')) {} //$('.co-register', jobj).slideUp('slow');
                    else {
                        $('.co-btn-insert', jobj).text('Anmelden');
                        $('.co-register', jobj).hide();
                        $('.co-register-guest', jobj).hide();
                        $('.co-register-full', jobj).show();
                        $('.co-register', jobj).slideDown('slow');
                        $(window).scrollTop($('.co-register').position().top + 120);
                    }
                    return false;
                });
                $('.co-btn-guest', jobj).click(function () { 
                    if (obj.plugin.customer != null && typeof obj.plugin.customer.id != 'undefined') {
                        obj._goTo(3);
                    } else {
                        if ($('.co-register-guest', jobj).is(':visible')) {} //$('.co-register', jobj).slideUp('slow');
                        else {
                            $('.co-btn-insert', jobj).text('Weiter');
                            $('.co-register', jobj).hide();
                            $('.co-register-full', jobj).hide();
                            $('.co-register-guest', jobj).show();
                            $('.co-register', jobj).slideDown('slow');
                            $(window).scrollTop($('.co-register').position().top + 120);
                        }
                    }
                    return false;
                });
                $('.co-btn-edit-shipping', jobj).click(function () {
                    if (typeof obj.plugin.customer.id != 'undefined') {
                        if (obj.plugin.customer.id == 0) obj._editGuestShipping();
                        else obj._chooseAddress();
                    } else obj._goTo(1);
                    return false;
                });
                $('.co-btn-edit-address', jobj).click(function () {
                    if (typeof obj.plugin.customer.id != 'undefined') {
                        if (obj.plugin.customer.id == 0) obj._editAddress();
                        else obj._editAddress();
//                        else obj._chooseAddress();
                    } else obj._goTo(1);
                    return false;
                });
                $('.co-btn-same-address', jobj).click(function () {
                    res = obj._query({action:'same-address'});
                    if (res) {
                        obj._goTo(4);
                        return false;
                    }
                    return false;
                });
                $.each(obj.plugin.countries, function (foo, country) {
                    var opt = $('<option></option>').text(country.name).attr('value', country.nationalityPlate);
                    if (country.nationalityPlate == 'D') opt.attr('selected', 'selected');
                    $('#co-register-nationalityPlate', jobj).append(opt);
                    $('#co-address-nationalityPlate', jobj).append(opt.clone());
                });
                $('.co-register-full .co-btn-insert', jobj).click(function () { 
                    obj._insertCustomer('full');
                    return false;
                });
                $('.co-register-guest .co-btn-insert', jobj).click(function () { 
                    obj._insertCustomer('guest');
                    return false;
                });
                $('#co-register-nationalityPlate', jobj).change(function () {
                    if ($('#co-register-nationalityPlate', jobj).val() == 'D') {
                        $('.co-register-phone-req').css('display', 'none');
                        $('.co-register-phone-opt').css('display', 'inline');
                    } else {
                        $('.co-register-phone-req').css('display', 'inline');
                        $('.co-register-phone-opt').css('display', 'none');
                    }
                });
                $('#co-address-nationalityPlate', jobj).change(function () {
                    if ($('#co-address-nationalityPlate', jobj).val() == 'D') {
                        $('.co-address-phone-req').css('display', 'none');
                        $('.co-address-phone-opt').css('display', 'inline');
                    } else {
                        $('.co-address-phone-req').css('display', 'inline');
                        $('.co-address-phone-opt').css('display', 'none');
                    }
                });

                $('#co-paymentOptionID', jobj).change(function () { 
                    if (typeof $(this).data('old') != 'undefined' && $(this).data('old') != $(this).val()) {
                        $('.co-step5 .co-closed', jobj).hide();
                    }

                    if ($(this).val() == 1007) {
                        $('.co-payment-option-bank', jobj).hide();
                        if (obj.plugin.creditCard != null) {
                            $('#co-stored-cc1', jobj)[0].checked = true;
                            $('input[name="stored_card"]', jobj).trigger("change");
                            $('.co-payment-option-cc-stored', jobj).show();
                            $('.co-payment-option-cc-new', jobj).hide();
                        } else {
                            $('#co-stored-cc0', jobj)[0].checked = true;
                            $('input[name="stored_card"]', jobj).trigger("change");
                            $('.co-payment-option-cc-stored', jobj).hide();
                            $('.co-payment-option-cc-new', jobj).show();
                        }
                        $('input[name="stored_card"]', jobj).change();
                        $('.co-payment-option-cc', jobj).show();
                    } else if ($('option:selected', $(this)).data('bank')) {
                        $('.co-payment-option-cc', jobj).hide();
                        $('.co-payment-option-bank', jobj).show();
                    } else $('.co-payment-option-cc, .co-payment-option-bank', jobj).hide();
                    $(this).data('old', $(this).val());
                    $('.co-payment-note', jobj).text($('option:selected', $(this)).data('note'));
                });

                $('input[name="paymentRadio"]', jobj).live('change', function () { 
                    $('#co-paymentOptionID', jobj).val($('input[name="paymentRadio"]:checked', jobj).val());
                    $('#co-paymentOptionID', jobj).trigger('change');
                });
                
                $('.co-step4 .co-payment-option-bank #payment-change').click(function () {
                    $('.co-step4 .co-payment-option-bank input').show();
                    $('.co-step4 .co-payment-option-bank .star').show();
                    $('.co-step4 .co-payment-option-bank .ba_data').hide();
                    $('.co-step4 .co-payment-option-bank #payment-change').hide();
                    return false;
                });
                
                $('input[name="stored_card"]', jobj).change(function () { 
                    if ($('input[name="stored_card"]:checked', jobj).val() == 0) {
                        $('.co-payment-option-cc-new', jobj).show();
                    } else $('.co-payment-option-cc-new', jobj).hide();
                });
                $('.co-btn-save-payment', jobj).click(function () { 
                    if ($('#co-voucher').val().length) {
                        if (!obj._addVoucher()) return false;
                    }
                    obj._checkPayment(); 
                    return false; 
                });
                $('.co-btn-place-order', jobj).click(function () { obj._placeOrder(); return false; });
                $('.co-btn-pass', jobj).click(function () { obj._requestPassword(); return false; });
                $('.co-btn-ab-add').click(function () { obj._chooseAddress(true); return false; });
                obj.checkout = true;
            },
// VALID PAYMENT //
            _checkPayment : function () {
                var obj = this;
                var jobj = $(this);
                if ($('#co-paymentOptionID', jobj).val() == 1007 && $('input[name="stored_card"]:checked', jobj).val() == 0) {
                    obj._ccCheck();
                    return false;
                }
                if (obj._savePayment()) obj._goTo('next');
                return false;
            },

// GOTO //
            /**
             * page shifter
             * possible values: prev, next, int
             */
            _goTo : function (target) {
                var obj = this;
                var jobj = $(this);
                if (target == 'next') target = obj.page + 1;
                if (target == 'prev') target = obj.page - 1;
                if (target > 6) target = 6;
                if (target < 1) target = 1;
                if (obj.plugin.cart.length == 0) {
                    target = 1;
                } else if (obj.plugin.customer != null && obj.plugin.customer.id != 0 && target == 2) {
                    target = 3;
                } else if (obj.plugin.customer == null && target > 2) {
                    target = 2;
                }
                $('.co-step'+obj.page+' .co-closed', jobj).show();
                $('.co-step'+obj.page+' .co-content', jobj).hide();
                if (obj.page != 1) $('.co-step'+obj.page+' .co-topic', jobj).hide();
                $('.co-step'+target, jobj).show();
                $('.co-step'+target+' .co-closed', jobj).hide();
                $('.co-step'+target+' .co-content', jobj).eq(0).show();
                $('.co-step'+target+' .co-topic', jobj).show();
                // some specials
                $('.co-register', jobj).hide();
                if (target == 4) {
                    $('.co-save-payment', jobj).show();
                    if (obj.page == 1) {
                        $('.co-step3 > div', jobj).hide();
                        $('.co-step3 .co-closed', jobj).show();
                        $('.co-step3', jobj).show();
                    }
                }
                $(window).scrollTop(0);
                obj.page = target;
            },
// GOTO RESUBMIT //
            _resubmit : function (page) {
                var obj = this;
                var jobj = $(this);
                var i;
                for (i = 5; i >= obj.opt.lastPage; i--) {
                    if (i > page) $('.co-step'+i+' .co-closed', jobj).hide();
                }
                if (page < obj.page) obj._goTo(page);
            },
// QUERY //
            _query : function (data) {
                var obj = this;
                var jobj = $(this);
                var stamp = new Date().getTime();
                var status = false;
                $.ajax({
                    url:"/checkout.ajax.php?"+stamp,
                    async:false, dataType:"json", data:data,
                    type:'POST',
                    success:function (json) {
                        $('*', jobj).removeClass('co-error');
                        if (typeof json.status != 'undefined') {
                            obj.plugin = json;
                            if (json.status) {
                                if (typeof json.redirect != 'undefined' && json.redirect != null) {
                                    window.location.href = json.redirect;
                                    return false;
                                } else {
                                        obj._update();
                                    status = true;
                                    if (json.note.length) obj._showNote(json.note, json.noteTitle);
                                }
                            }
                            else obj._showError(json.error, json.errorTitle);
                        }
                    }
                });
                return status;
            },
// ERRORS //
            _showError : function (errors, errorTitle) {
                if (typeof errorTitle == 'undefined')  {
                    errorTitle = 'Fehler';
                }                   
                var jobj = $(this);
                var ul = $('<ul></ul>').addClass('dia-list');
                var i, j;
                for (i = 0; i < errors.length; i++) {
                    ul.append($('<li></li>').html(errors[i].message));
                    for (j = 0; j < errors[i].fields.length; j++) {
                        $(errors[i].fields[j], jobj).addClass('co-error');
                    }
                }
                $('<div class="co-dialog" title="' + errorTitle + '"></div>').append(ul).dialog({
                    modal:true
                });
            },
            _showNote : function (notes, noteTitle) {
                if (typeof noteTitle == 'undefined')  {
                    noteTitle = 'Hinweis';
                }   
                var jobj = $(this);
                var ul = $('<ul></ul>').addClass('dia-list');
                var i, j;
                for (i = 0; i < notes.length; i++) {
                    ul.append($('<li></li>').text(notes[i].message));
                }
                $('<div title="' + noteTitle + '"></div>').append(ul).dialog({
                    modal:true
                });
            },
// INSERT CUSTOMER //
            /**
             * @todo pre-validation could be done
             */
            _insertCustomer : function (type) {
                var obj = this;
                var jobj = $(this);
                var data = $('input, select', $('.co-register', jobj)).serializeArray();
                data.push({name:'type', value:type});
                data.push({name:'action', value:'insert-customer'});
                var res = obj._query(data);
                if (res && obj.plugin.customer != null) obj._goTo('next');
                else {
                    $('#co-register-confirm').val('1');
                }
            },
// ADDRESS EDIT //
            _editAddress : function () {
                var obj = this;
                var jobj = $(this);
                $('.co-ab').hide();
                obj._setupAddressForm(this.plugin.address);
                $('.btn-co-address', jobj).unbind('click').click(function () {
                    var data = $('input, select', $('.co-address-form', jobj)).serializeArray();
                    data.push({name:'action', value:'update-customer'});
                    var res = obj._query(data);
                    if (res) {
                        $('.co-address-form', jobj).hide();
                        $('.co-step4 .co-closed, .co-step5 .co-closed').hide();
                    } else {
                        $('#co-address-confirm').val('1');
                    }
                    return false;
                });
                $('.co-address-form-topic', jobj).hide();
                $('.co-address-form1', jobj).css('display', 'inline');
                $('.co-address-form', jobj).show();
            },
// ADDRESS BOOK //
            _addressBook : function () {
                $('.co-address-form').hide();
                $('.co-ab').show();
            },
// ADDRESS SHIPPING NEW / ADDRESS BOOK SWITCH //
            _chooseAddress : function (newAddress) {
                var obj = this;
                var jobj = $(this);
                if (typeof obj.plugin.addressBook != 'undefined' && obj.plugin.addressBook.length
                    && (typeof newAddress == 'undefined' || newAddress == false)
                ) {
                    obj._addressBook();
                }
                else {
                    $('.co-ab', jobj).hide();
                    if (obj.plugin.sameAddress) obj._setupAddressForm();
                    else obj._setupAddressForm(this.plugin.shippingAddress);
                    $('.btn-co-address', jobj).unbind('click').click(function () {
                        var data = $('input, select', $('.co-address-form', jobj)).serializeArray();
                        data.push({name:'action', value:'add-shipping-address'});
                        var res = obj._query(data);
                        if (res) {
                            $('.co-address-form', jobj).hide();
                            obj._addressBook();
                        } else $('#co-address-confirm').val('1');
                        return false;
                    });
                    $('.co-address-form-topic', jobj).hide();
                    $('.co-address-form2', jobj).css('display', 'inline');
                    $('.co-address-form', jobj).show();
                }
            },
// SET SHIPPING ADDRESS  //
            _setShippingAddress : function (shippingAddressID) {
                var obj = this;
                var jobj = $(this);
                var data = {action:'set-shipping-address',shippingAddressID:shippingAddressID};
                var res = obj._query(data);
                if (res) {
                    obj._goTo('next');
                    return true;
                }
                return false;
            },
// EDIT GUEST SHIPPING ADDRESS //
            _editGuestShipping : function () {
                var obj = this;
                var jobj = $(this);
                obj._setupAddressForm(this.plugin.shippingAddress);
                $('.btn-co-address', jobj).unbind('click').click(function () {
                    var data = $('input, select', $('.co-address-form', jobj)).serializeArray();
                    data.push({name:'action', value:'update-guest-shipping'});
                    var res = obj._query(data);
                    if (res) {
                        $('.co-address-form', jobj).hide();
                        obj._goTo('next');
                    } else $('#co-address-confirm').val('1');
                    return false;
                });
                $('.co-address-form-topic', jobj).hide();
                $('.co-address-form3', jobj).css('display', 'inline');
                $('.co-address-form', jobj).show();
            },
// EDIT SHIPPING ADDRESS //
            _editShipping : function (shippingAddressID) {
                var obj = this;
                var jobj = $(this);
                var ab = obj.plugin.addressBook;
                var address;
                $.each(ab, function (k, v) {
                    if (v.addressID == shippingAddressID) {
                        address = v;
                    }
                });
                if (address) {
                    $('.co-ab', jobj).hide();
                    obj._setupAddressForm(address);
                    $('.btn-co-address', jobj).unbind('click').click(function () {
                        var data = $('input, select', $('.co-address-form', jobj)).serializeArray();
                        data.push({name:'action', value:'update-shipping-address'});
                        data.push({name:'addressID', value:address.addressID});
                        var res = obj._query(data);
                        if (res) {
                            $('.co-address-form', jobj).hide();
                            obj._addressBook();
                        } else $('#co-address-confirm').val('1');
                        return false;
                    });
                    $('.co-address-form-topic', jobj).hide();
                    $('.co-address-form3', jobj).css('display', 'inline');
                    $('.co-address-form', jobj).show();
                }
            },
// REMOVE SHIPPING ADDRESS //
            _removeShipping : function (shippingAddressID) {
                var obj = this;
                var jobj = $(this);
                var data = {action:'remove-shipping-address',addressID:shippingAddressID};
                var res = obj._query(data);
                if (res) {
                    obj._chooseAddress();
                    return true;
                }
                return false;
            },
            _setupAddressForm : function (address) {
                var obj = this;
                var jobj = $(this);
                $('input, select', $('.co-address-form', jobj)).val('');
                if (typeof address != 'undefined') {
                    showWebmiles = false;
                    $.each(address, function (k, v) { 
                        $('#co-address-'+k, jobj).val(v);
                        if (k == 'webmilesID' && v !== '') {
                            showWebmiles = true;
                        }
                    });
                    if (showWebmiles == true) {
                        $('#wrap-address-webmilesID').show();
                        $('#wrap-address-addon').css('float', 'left');
                    } else {
                        $('#wrap-address-webmilesID').hide();
                        $('#wrap-address-addon').css('float', 'none');
                    }
                }
                else $('#co-address-nationalityPlate', jobj).val('D');
                $('#co-address-nationalityPlate', jobj).trigger('change');
            },
// UI UPDATE //
            _update : function () {
                var obj = this;
                var jobj = $(this);
                var payment;
                // summary
                    $('.cod-goods', jobj).text(obj._price(obj.plugin.summary.goods / 100));
                if (obj.plugin.summary.discount) {
                    $('.cod-discount', jobj).text(obj._price(obj.plugin.summary.discount / 100));
                    $('.cod-box-discount', jobj).show();
                } else $('.cod-box-discount', jobj).hide();
                if (obj.plugin.summary.volumeDiscount) {
                    $('.cod-volumeDiscount', jobj).text(obj._price(obj.plugin.summary.volumeDiscount / 100 * -1));
                    $('.cod-volumeDiscountOrderSummary', jobj).text(obj._price(obj.plugin.summary.volumeDiscountOrderSummary / 100));
                    $('.cod-volumeDiscountPercentage', jobj).text(obj.plugin.summary.volumeDiscountPercentage);
                    $('.cod-box-volumeDiscount', jobj).show();
                } else {
                    $('.cod-volumeDiscount', jobj).text(obj._price(0));
                    $('.cod-box-volumeDiscount', jobj).hide();
                }
                if (obj.plugin.summary.voucher) {
                    $('.cod-voucher', jobj).text(obj._price(obj.plugin.summary.voucher / 100 * -1));
                    $('.cod-box-voucher', jobj).show();
                } else $('.cod-box-voucher', jobj).hide();
                if (obj.plugin.summary.check) {
                    $('.cod-check', jobj).text(obj._price(obj.plugin.summary.check / 100 * -1));
                    $('.cod-box-check', jobj).show();
                } else $('.cod-box-check', jobj).hide();
                if (obj.plugin.summary.check || obj.plugin.summary.voucher) {
                    $('.cod-voucher-check', jobj).text(obj._price((obj.plugin.summary.voucher + obj.plugin.summary.check) / 100 * -1));
                } else $('.cod-voucher-check', jobj).text(obj._price(0));
                if (obj.plugin.summary.webmiles) {
                    $('.cod-webmiles', jobj).text(obj.plugin.summary.webmiles);
                    if (typeof obj.plugin.customer != 'undefined' && obj.plugin.customer.webmilesID != 'undefined' && obj.plugin.customer.webmilesID.length) $('.cod-box-webmiles', jobj).show();
                    else $('.cod-box-webmiles', jobj).hide();
                } else $('.cod-box-webmiles', jobj).hide();
                $('.cod-shipping', jobj).text(obj._price(obj.plugin.summary.shipping / 100));
                $('.cod-total', jobj).text(obj._price(obj.plugin.summary.total / 100));
                $('.cod-countGoods', jobj).text(obj.plugin.summary.countGoods);
                if (obj.plugin.shipping.freeShippingValue > 0) {
                    $('.cod-shippingDesc', jobj).text('('+obj.plugin.shipping.countryISO+' - ab '+obj._price(obj.plugin.shipping.freeShippingValue / 100)+' frei)').css('display', 'block'); 
                } else $('.cod-shippingDesc', jobj).empty().hide();
                if (obj.plugin.sameAddress) {
                    $('.co-box-greeting').hide();
                    $('.co-box-greeting textarea').val('');
                } else $('.co-box-greeting').show();

                obj._updateAddressBook();
                obj._updateCartItemList();
                obj._updateCustomer();
                obj._updatePaymentOptions();
            },
// UI UPDATE ADDRESS BOOK //
            _updateAddressBook : function () {
                var obj = this;
                var jobj = $(this);
                var ab = obj.plugin.addressBook;
                var tpl, address;
                $('.co-ab-box', jobj).remove();
                if (ab.length) {
                    if (ab.length < 3) {
                        $('.co-btn-ab-add').show();
                    } else $('.co-btn-ab-add').hide();
                    $.each(ab, function (k, address) {
                        var tpld = $('.co-ab-desc-tpl', jobj).clone().removeClass('co-ab-desc-tpl').addClass('co-ab-box');
                        var tpla = $('.co-ab-action-tpl', jobj).clone().removeClass('co-ab-action-tpl').addClass('co-ab-box');
                        $.each(address, function (k, v) { $('.cod-ab-'+k, tpld).text(v); });
                        $('.co-btn-ab-set', tpla).data('id', address.addressID).click(function () {
                            obj._setShippingAddress($(this).data('id'));
                            return false;
                        });
                        $('.co-btn-ab-edit', tpla).data('id', address.addressID).click(function () {
                            obj._editShipping($(this).data('id'));
                            return false;
                        });
                        $('.co-btn-ab-remove', tpla).data('id', address.addressID).click(function () {
                            obj._removeShipping($(this).data('id'));
                            return false;
                        });
                        tpld.insertAfter($('.co-ab-desc-tpl', jobj));
                        tpla.insertAfter($('.co-ab-action-tpl', jobj));
                    });
                }

            },

// UI UPDATE CUSTOMER //
            _updateCustomer : function () {
                // Rechnungsadresse
                var obj = this;
                var jobj = $(this);
                if (obj.plugin.customer == null) return false;
                $.each(obj.plugin.address, function (k, v) {
                    $('.cod-address-'+k, jobj).text(v);
                });
                $.each(obj.plugin.shippingAddress, function (k, v) {
                    $('.cod-shipping-'+k, jobj).text(v);
                });
            },
// UI UPDATE PAYMENT OPTIONS //
            _updatePaymentOptions : function () {
                var obj = this;
                var jobj = $(this);
                var option, value_old, opt, cc, ba;
                var hit = false;
                if (obj.plugin.customer == null || obj.plugin.paymentOptions == null) return false;
                // aktuellen Wert ziehen
                value_old = null;
                if ($('#co-paymentOptionID', jobj).size() > 1) {
                    value_old = $('#co-paymentOptionID option', jobj).val();
                } else value_old = obj.plugin.paymentOptionID;
                $('#co-paymentOptionID option', jobj).not('.co-default').remove();
                $('.co-payment-optionsx', jobj).empty();
                $.each(obj.plugin.paymentOptions, function (k, option) {
                    var podiv   = $('<div class="co-payment-option" style="width:200px;float:left;"></div>');
                    var poradio = $('<input type="radio" name="paymentRadio" id="paymentOption" style="margin-right:10px;float:left;margin-top:11px;" />').attr('id', 'paymentOption'+option.paymentOptionID).attr('value', option.paymentOptionID);
                    //var polabel = $('<br />');
                    var polabel = $('<label style="padding-bottom:6px;display:block;width:120px;float:left;padding-top:21px;background-image:url(https://www.rindchen.de/img/checkout/za-'+option.paymentOptionID+'-on.png);background-repeat:no-repeat;"></label>').text(option.paymentOptionName).attr('for', 'paymentOption'+option.paymentOptionID);
                    if (value_old == option.paymentOptionID) {
                        poradio.prop('checked', true);
                        hit = option;
                    }
                    opt = $('<option></option>').attr('value', option.paymentOptionID).text(option.paymentOptionName).data('bank', option.bankAccountDataRequired).data('note', option.note);
                    if (value_old == option.paymentOptionID) {
                        opt.attr('selected', true);
                        hit = option;
                    }
                    $('#co-paymentOptionID', jobj).append(opt);
                    podiv.append(poradio).append(polabel);
                    $('.co-payment-optionsx', jobj).append(podiv);

                });
                if (obj.plugin.creditCard != null) {
                    cc = obj.plugin.creditCard;
                    $('.cod-cc-brand', jobj).text(cc.brand);
                    $('.cod-cc-expiry', jobj).text(cc.expiry);
                    $('.cod-cc-pan', jobj).text(cc.pan);
                    $('#co-stored-cc1', jobj).prop('checked', true);
                    $('input[name="stored_card"]', jobj).trigger('change');
                } else {
                    $('#co-stored-cc0', jobj).prop('checked', true);
                    $('input[name="stored_card"]', jobj).trigger('change');
                }

                if (obj.plugin.bankAccount != null) {
                    ba = obj.plugin.bankAccount;
                    var stars = '';
                    for(i = 0; i < ba.accountNumber.length - 3; i++) {
                        stars = stars + '* ';
                    }
                    stars = stars + ba.accountNumber.substring(ba.accountNumber.length - 3 , ba.accountNumber.length);
                    $('.cod-bank-accountNumber', jobj).text(stars);
                    $('#co-payment-accountNumber-data', jobj).text(stars);
                    $('.cod-bank-bankName', jobj).text(ba.bankName);
                    $('#co-payment-bankName-data', jobj).text(ba.bankName);
                    $('.cod-bank-bankCode', jobj).text(ba.bankCode);
                    $('#co-payment-bankCode-data', jobj).text(ba.bankCode);
                    $('#co-payment-accountNumber', jobj).val(ba.accountNumber);
                    $('#co-payment-bankName', jobj).val(ba.bankName);
                    $('#co-payment-bankCode', jobj).val(ba.bankCode);
                } else {
                    $('.co-step4 .co-payment-option-bank input').show();
                    $('.co-step4 .co-payment-option-bank .star').show();
                    $('.co-step4 .co-payment-option-bank .ba_data').hide();
                    $('.co-step4 .co-payment-option-bank #payment-change').hide();
                }
                // selected option not available or something is missing
                if (!hit || (hit.paymentOptionID == 1007 && obj.plugin.creditCard == null) || (hit.bankAccountDataRequired && obj.plugin.bankAccount == null)) {
                    obj._resubmit(4);
                }
                $('.cod-box-bank,.cod-box-cc', jobj).hide();
                if (hit) {
                    if (hit.bankAccountDataRequired) $('.cod-box-bank', jobj).show();
                    if (hit.paymentOptionID == 1007) $('.cod-box-cc', jobj).show();
                    $('.cod-payment-paymentOptionName', jobj).text(hit.paymentOptionName);
                    $('.cod-payment-note', jobj).text(hit.note);
                }
                $('#co-paymentOptionID', jobj).change();
                $('input[name="paymentOptionID"]', jobj).trigger('change');
                $('input[name="stored_card"]', jobj).trigger('change');
            },

// UI UPDATE CART //
            _updateCartItemList : function () {
                var obj = this;
                var jobj = $(this);
                var items_remote = [];
                var items_update = [];
                var items_new = [];
                if (obj.plugin.cart.length) $('.co-step1 .co-next', jobj).show();
                else $('.co-step1 .co-next', jobj).hide();
                if (obj.plugin.cart.length) {
                    $('.cod-box-cart-empty', jobj).hide();
                    $('.cod-box-subtotal', jobj).show();
                } else {
                    $('.cod-box-subtotal', jobj).hide();
                    $('.cod-box-cart-empty', jobj).css('display', '');
                }
                if (obj.checkout) {

                    // new
                    $.each(obj.plugin.cart, function (key, item) {
                        items_remote.push(item.cartItemID);
                    });
                    // removed
                    $('.co-cart-item-x', jobj).each(function () {
                        if (jQuery.inArray($(this).data('id'), items_remote) == -1) {
                            $(this).remove();
                        }
                        // update
                        else items_update.push($(this).data('id'));
                    });
                    $.each(obj.plugin.cart, function (key, item) {
                        var citem = item;
                        // wenn nicht in update - neu anlegen
                        if (jQuery.inArray(citem.cartItemID, items_update) == -1) {
                            if (item.cartVisible) {
                                tr = $('.co-cart-table .co-cart-item-tpl', jobj).clone();
                                tr.removeClass('co-cart-item-tpl').addClass('co-cart-item-x');
                                obj._initCartItem(tr, citem);
                                tr.insertAfter($('.co-cart-table .co-cart-item:last', jobj)); // :last-child
                            }
                        }
                    
                        // update
                        $('.co-cart-item-x', jobj).each(function () {
                            if (item.cartVisible && $(this).data('id') == citem.cartItemID) {
                                obj._updateCartItem($(this), citem);
                            }
                        });  

                    });
                }
            },
// UI UPDATE CART ITEM //
            _updateCartItem : function (tr, item) {
                var obj = this;
                var jobj = $(this);
                var timeout = null;
                var info;
                $('.co-product-name', tr).text(item.text1);
                $('.co-quantity-value', tr).val(item.cartQuantity);
                if (item.cartQuantityFixed) {
                    $('.co-quantity-value', tr).attr('readonly', true);
                    $('.co-quantity-value', tr).css('border-color', 'white');
                } else {
                    $('.co-quantity-value', tr).attr('readonly', false);
                    $('.co-quantity-value', tr).css('border-color', '#CCCCCC');
                }
                $('.co-cart-item-value', tr).text(obj._price(item.price * item.cartQuantity));
                $('.co-product-price', tr).text(obj._price(item.price));
                $('.co-product-id', tr).text(item.productID);
                $('.co-product-volume', tr).text(obj._volume(item.volume, item.volumeUnit));
                info = [];
                if (typeof item.color == 'string' && item.color.length) {
                    info.push(item.color);
                }
                if (typeof item.region == 'string' && item.region.length) {
                    info.push(item.region);
                }
                if (typeof item.country == 'string' && item.country.length) {
                    info.push(item.country);
                }
                $('.co-product-desc', tr).text(info.join(', '));
                $('.co-image-file', tr).attr('src', obj._image(item.image));
                if (item.cartBonusInKindQuantity) {
                    $('.co-bik-quantity', tr).text(item.cartBonusInKindQuantity);
                    $('.co-bik-desc', tr).text(item.cartBonusInKindText);
                    $('.co-bik-value', tr).text(obj._price(item.price * item.cartBonusInKindQuantity * -1)).show();
                    $('.co-bik', tr).show();
                } else {
                    $('.co-bik', tr).hide();
                    $('.co-bik-value', tr).hide();
                }
                if (!item.cartQuantityFixed) {
                    $('.co-quantity-more, .co-quantity-less', tr).show();
                } else $('.co-quantity-more, .co-quantity-less', tr).hide();
                if (item.cartRemovable) {
                    $('.co-remove-item', tr).show();
                } else $('.co-remove-item', tr).hide();
            },
// INIT CART ITEM //
            _initCartItem : function (tr, item) {
                var obj = this;
                var jobj = $(this);
                var timeout = null;
                tr.data('id', item.cartItemID);
                $('.co-quantity-more', tr).click(function () {
                    var q = $('.co-quantity-value', $(this).closest('.co-cart-item')).val() * 1 + 1;
                    obj._query({action:'update-quantity',cartItemID:$(this).closest('.co-cart-item').data('id'),quantity:q});
                });
                $('.co-quantity-less', tr).click(function () {
                    var q = $('.co-quantity-value', $(this).closest('.co-cart-item')).val() * 1 - 1;
                    obj._query({action:'update-quantity', cartItemID:$(this).closest('.co-cart-item').data('id'),quantity:q});
                });
                $('.co-remove-item', tr).click(function () {
                    obj._query({action:'update-quantity', cartItemID:$(this).closest('.co-cart-item').data('id'),quantity:0});
                });
                $('.co-quantity-value', tr).change(function () {
                    var q = $(this).val();
                    obj._query({action:'update-quantity', cartItemID:$(this).closest('.co-cart-item').data('id'),quantity:$(this).val()});
                    if ($(this).val() < q) obj._showNote([{message:"Die Anzahl wurde auf die verfügbare Menge reduziert."}]);
                });
                $('.co-quantity-value', tr).keyup(function() {
                    var quantity = $(this);
                    if (timeout != null) clearTimeout(timeout);  
                    timeout = setTimeout(function () { quantity.change(); timeout = null;  }, 2000);
                });
            },

// HELPER PRICE //
            _price : function (price) { return '€ '+number_format(price, 2, ',', '.'); },
// HELPER VOLUME //
            _volume : function (vol, unit) {
                if (typeof vol != 'undefined' && vol > 0) {
                    return number_format(vol / 1000, 2, ',', '.')+' '+unit;
                }
                return '';
            },
// HELPER IMAGE //
            _image : function (image) { return '/img/wein/'+image+'a.jpg'; }
        };
        var settings = {
            cc_callback : 'cc_result'
            , template : '/checkout.tpl.php'
            , page : 1
            , lastPage : 5
        };
        return this.each(function(){
            var jobj = $(this);
            var obj = this;
            var init = false;
            var i;
            if (methods[method]) {
                return this[method].apply(this, [value]);
            } else if ( typeof method === 'object' || ! method ) {
                init = true;
            }
            if (init) {
                this.page = 1;
                this.plugin = {};
                this.opt = $.extend({}, settings, method);
                this.page = this.opt.page;
                this.open = false;
                this.checkout = false;
                $.extend(this, methods);
                $('.co-cart', $(this)).click(function () {
                    if ($('.co-cart-arrow', jobj).hasClass('icon-arrow-up')) {
                        obj.hideCheckout();
                    } else {
                        obj.showCheckout();
                    }
                });
                this._query();
                $('.co-cart', $(this)).show();
            }

        });
    }
})( jQuery );

});

