/*
 *  Copyright 2010 KLARNA AB. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification, are
 *  permitted provided that the following conditions are met:
 *
 *     1. Redistributions of source code must retain the above copyright notice, this list of
 *        conditions and the following disclaimer.
 *
 *     2. Redistributions in binary form must reproduce the above copyright notice, this list
 *        of conditions and the following disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY KLARNA AB "AS IS" AND ANY EXPRESS OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KLARNA AB OR
 *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  The views and conclusions contained in the software and documentation are those of the
 *  authors and should not be interpreted as representing official policies, either expressed
 *  or implied, of KLARNA AB.
 *
 */

var Klarna = Class.create({
    initialize: function() {
        this.element_id = false;
        this.merchant_id = false;
        this.fee = false;
        this.country = false;
        this.url = false;
        this.osc_url = false;
        this.osc_url2 = false;
    },

    setMerchantId: function(merchant_id) {
        this.merchant_id = merchant_id;
    },

    setElementId: function(element_id) {
        this.element_id = element_id;
    },

    setFee: function(fee) {
        this.fee = fee;
    },

    setCountry: function(country) {
        this.country = country;
    },

    setUrl: function(url) {
        this.url = url;
    },

    setOneStepUrl: function(osc_url) {
        this.osc_url = osc_url;
    },

    setOneStepUrl2: function(osc_url2) {
        this.osc_url2 = osc_url2;
    },

    loadExternal: function() {
        var script = new Element('script', {
           src: 'https://static.klarna.com/external/js/klarnaConsentNew.js'
        });
        $$('head').first().insert(script);
    },

    loadAgreement: function() {
        if (jQuery('#klarna_invoice_popup').length == 0) {
            openAgreement('de');
        }
    },

    showInvoiceTerms: function() {
        var invoice = this;
        openAgreement(invoice.country);
        ShowKlarnaPopup(invoice.merchant_id, invoice.fee, 'invoice', '');
    },

    showPartPaymentTerms: function() {
        var part = this;
        openAgreement(part.country);
        ShowKlarnaPopup(part.merchant_id, part.fee, 'part', '');
    },

    showSpecPaymentTerms: function(link) {
        console.log(link);
        var spec = this;
        openAgreement(spec.country);
        ShowKlarnaPopup(spec.merchant_id, spec.fee, 'spec', link);
    },

    showInvoiceConcent: function() {
        var invoiceConcent = this;
        openAgreement(invoiceConcent.country);
        ShowKlarnaConsentPopup(invoiceConcent.merchant_id, 'invoice');
    },

    showPartPaymentConcent: function() {
        var partPaymentConcent = this;
        openAgreement(partPaymentConcent.country);
        ShowKlarnaConsentPopup(partPaymentConcent.merchant_id, 'part');
    },

    showSpecPaymentConcent: function() {
        var specPaymentConcent = this;
        openAgreement(specPaymentConcent.country);
        ShowKlarnaConsentPopup(specPaymentConcent.merchant_id, 'spec');
    },

    getAddresses: function(pno) {
        var elemt = this.element_id;
        Element.show('loadingmask-' + this.element_id);
        var reloadurl = this.url;
        new Ajax.Updater('output-div-' + this.element_id, reloadurl + '?cache' + parseInt(Math.random() * 99999999) + '&type=' + this.element_id, {
            parameters: 'pno=' + pno,
            onComplete: function(response) {
                Element.hide('loadingmask-' + elemt);
                }
            });
       },


    getAddressesOneStep: function(pno) {

        var elemt = this.element_id;
        var reloadurl = this.url;
        if($('billing-address-select') != undefined) {
         if($('billing-address-select').getValue().length != 0)
            return;
        }
        Element.show('klarna_spinner');

        if ($('klarna_error')) {
            $('klarna_error').remove();
        }

        $('klarna_input').select('input')[0].removeClassName('validation-failed');

        new Ajax.Request(reloadurl, {
            method: 'post',
            parameters: 'pno=' + pno + '&type=klarna_invoice',
            onSuccess: function(transport) {
                if (transport.responseText.isJSON()) {
                    var json = transport.responseText.evalJSON(true);

                    if(json.length > 1) {
                        // Clear the dropdown
                        $('klarna_multi_address_select').options.length = 0;

                        $('klarna_address').show();
                        klarna.setFields(json[0].join("|"));
                        json.each(function(s, index) {
                            var info;
                            var opt = document.createElement('option');

                            opt.value = s.join('|');
                            if(s[0].length == 0){
                                info = s.splice(1, 4);
                                info[0] = s[2];
                            }
                            else{
                                info = s.splice(0, 5);
                            }
                            opt.text = info.join(", ");
                            $('klarna_multi_address_select').options.add(opt);


                        });
                    } else {
                        $('klarna_address').hide();
                        klarna.setFields(json[0].join("|"));
                    }
                } else {
                    $('klarna_input').insert({
                        bottom: '<p id="klarna_error" style="clear: both;">' + transport.responseText + '</p>'
                    });
                    $('klarna_input').select('input')[0].addClassName('validation-failed');
                }
                Element.hide('klarna_spinner');
            }

    });

    },

    setFields: function(obj) {
        var objArr = obj.split("|");

        if (objArr[0].length == 0) {
            if ($('billing:company') != undefined) {
                $('billing:company').setValue(objArr[6]);
            }

            if ($('billing:firstname') != undefined) {
                $('billing:firstname').addClassName('validation-failed').enable();
            }

            if ($('billing:lastname') != undefined) {
                $('billing:lastname').addClassName('validation-failed').enable();
            }

            if ($('shipping:company') != undefined) {
                $('shipping:company').setValue(objArr[6]);
            }

            if ($('shipping:firstname') != undefined) {
                $('shipping:firstname').enable();
            }

            if ($('shipping:lastname') != undefined) {
                $('shipping:lastname').enable();
            }
        } else {
            if ($('billing:firstname') != undefined) {
                $('billing:firstname').setValue(objArr[0]); //.disable();
            }

            if ($('billing:lastname') != undefined) {
                $('billing:lastname').setValue(objArr[1]); //.disable();
            }

            if ($('shipping:firstname') != undefined) {
                $('shipping:firstname').setValue(objArr[0]); //.disable();
            }

            if ($('shipping:lastname') != undefined) {
                $('shipping:lastname').setValue(objArr[1]); //.disable();
            }

            if ($('billing:company') != undefined) {
                $('billing:company').setValue("");
            }

            if ($('shipping:company') != undefined) {
                $('shipping:company').setValue("");
            }
        }

        if ($('billing:street1') != undefined) {
            $('billing:street1').setValue(objArr[2]); //.disable();
        }

        if ($('shipping:street1') != undefined) {
            $('shipping:street1').setValue(objArr[2]); //.disable();
        }

        if ($('billing:city') != undefined) {
            $('billing:city').setValue(objArr[4]); //.disable();
        }

        if ($('shipping:city') != undefined) {
            $('shipping:city').setValue(objArr[4]); //.disable();
        }

        if ($('billing:postcode') != undefined) {
            $('billing:postcode').setValue(objArr[3]); //.disable();
        }

        if ($('shipping:postcode') != undefined) {
            $('shipping:postcode').setValue(objArr[3]); //.disable();
        }

        if ($('billing:email') != undefined) {
            $('billing:email').addClassName('validation-failed');
        }

        if ($('billing:telephone') != undefined) {
            $('billing:telephone').addClassName('validation-failed');
        }

        if ($('billing:country_id') != undefined) {
            $('billing:country_id').setValue('SE'); //.disable();
        }

        if ($('shipping:country_id') != undefined) {
            $('shipping:country_id').setValue('SE'); //.disable();
        }

        // Refresh the payment options when selecting Klarna
        // Use this method so the fields will have time to reload
        setTimeout(function() {
            $$('[name="payment[method]"]').each(function(item) {
                item.observe('click', function(e) {
                    var ele = Event.element(e);

                    if(ele.getValue() == "klarna_invoice" || ele.getValue() == "klarna_partpayment") {
                        $('klarna_input').show();
                    } else {
                        $('klarna_input').hide();
                    }
                });
            });
        }, 1500);
    },
    enableFields: function() {
        $('billing_address').select('input', 'select').each(function(item) {
                item.enable();
            }
        );
        $('shipping_address').select('input', 'select').each(function(item) {
                item.enable();
            }
        );
    },
    disableFields: function() {
        var fields = new Array();
        fields[0] = $('billing:firstname');
        fields[1] = $('billing:lastname');
        fields[2] = $('billing:company');
        fields[3] = $('billing:street1');
        fields[4] = $('billing:street2');
        fields[5] = $('billing:postcode');
        fields[6] = $('billing:city');
        fields[7] = $('billing:country_id');

        fields[8] = $('shipping:firstname');
        fields[9] = $('shipping:lastname');
        fields[10] = $('shipping:company');
        fields[11] = $('shipping:street1');
        fields[12] = $('shipping:street2');
        fields[13] = $('shipping:postcode');
        fields[14] = $('shipping:city');
        fields[15] = $('shipping:country_id');

        for (var i = 0; i < fields.length; i++) {
            if (fields[i] != undefined) {
                fields[i]; //.disable();
            }
        }

        $('billing:use_for_shipping_yes'); //.disable();
    }

});

var klarna = new Klarna();
var klarnapp = new Klarna();

document.observe('dom:loaded', function() {
    jQuery.noConflict();

    if (typeof klarnapartpaymentlang == 'undefined') {
        klarna.loadExternal();
    }

    var method = jQuery('input[type=radio][name="payment[method]"]:checked').val();

    if (method == "klarna_invoice" || method == "klarna_partpayment" || method == "klarna_specpayment") {
        jQuery('#klarna_input').show();
        klarna.disableFields();
    } else {
        jQuery('#klarna_input').hide();
        klarna.enableFields();
    }

    jQuery('input[type=radio][name="payment[method]"]').live("click", function() {
        var method = jQuery('input[type=radio][name="payment[method]"]:checked').val();
        if (method == "klarna_invoice" || method == "klarna_partpayment" || method == "klarna_specpayment") {
            jQuery('#klarna_input').show();
            klarna.disableFields();
        } else {
            jQuery('#klarna_input').hide();
            klarna.enableFields();
        }
    });
});
