/*
 *  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://integration.klarna.com/js/klarnainvoice.js'
        });
        $$('head').first().insert(script);
        var scriptpp = new Element('script', {
            src: 'https://integration.klarna.com/js/klarnapart.js'
        });
        $$('head').first().insert(scriptpp);
    },

    showTerms: function() {
        var manager = this;
        InitKlarnaInvoiceElements(manager.element_id, manager.merchant_id, manager.country, manager.fee);
        ShowKlarnaInvoicePopup();
    },

    showPPTerms: function() {
        var managerpp = this;
        InitKlarnaPartPaymentElements(managerpp.element_id, managerpp.merchant_id, managerpp.country, managerpp.fee);
        ShowKlarnaPartPaymentPopup();
    },

    getAddresses: function(pno) {
        var elemt = this.element_id;
        Element.show('loadingmask-' + this.element_id);
        var reloadurl = this.url;
        var type = this.element_id;
        if(type == 'cod'){
            type = 'klarna_invoice';
        }
        new Ajax.Updater('output-div-' + this.element_id, reloadurl + '?cache' + parseInt(Math.random() * 99999999) + '&type=' + type, {
            parameters: 'pno=' + pno,
            evalScripts: true,
            onComplete: function(response) {
                Element.hide('loadingmask-' + elemt);
                get_save_billing_function( AW_ACP.cartURL + 'ajax/save_billing/', AW_ACP.cartURL + 'ajax/set_methods_separate/', false)();
            }
        });
    },


    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');
        new Ajax.Request(reloadurl, {
            method: 'post',
            parameters: 'pno=' + pno + '&type=klarna_invoice',
            onSuccess: function(transport) {

                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 opt = document.createElement('option');

                        opt.value = s.join('|');
                        if(s[0].length == 0)
                            s = s.splice(1, 4);
                        else
                            s = s.splice(0, 5);

                        opt.text = s.join(", ");
                        $('klarna_multi_address_select').options.add(opt);


                    });
                } else {
                    $('klarna_address').hide();
                    klarna.setFields(json[0].join("|"));



                }
                Element.hide('klarna_spinner');
            }

        });

    },

    setFields: function(obj) {

        var objArr = obj.split("|");

        if(objArr[0].length == 0) {

            if($('billing:company') != undefined) {
                $('billing:company').setValue(objArr[1]);
            }
            if($('billing:firstname') != undefined) {
                $('billing:firstname').setStyle({
                    border:'1px solid red'
                }).enable();
            }
            if($('billing:lastname') != undefined) {
                $('billing:lastname').setStyle({
                    border:'1px solid red'
                }).enable();
            }

            if($('shipping:company') != undefined){
                $('shipping:company').setValue(objArr[1]);
            }

            if($('shipping:firstname') != undefined){
                $('shipping:firstname').enable();
            }

            if($('shipping:lastname') != undefined){
                $('shipping:lastname').enable();
            }

        } else {
            if($('billing:firstname') != undefined) {
                $('billing:firstname').setValue(objArr[0]);
            }

            if($('billing:region') != undefined) {
                $('billing:region').setValue(objArr[4]);
            }
            if($('shipping:region') != undefined) {
                $('shipping:region').setValue(objArr[4]);
            }

            if($('billing:lastname') != undefined) {
                $('billing:lastname').setValue(objArr[1]);
            }

            if($('shipping:firstname') != undefined)
                $('shipping:firstname').setValue(objArr[0]).enable();

            if($('shipping:lastname') != undefined)
                $('shipping:lastname').setValue(objArr[1]).enable();

            if($('billing:company') != undefined) {
                $('billing:company').setValue("");
            }

            if($('shipping:company') != undefined) {
                $('shipping:company').setValue("");
            }
        }

        if($('billing:street1') != undefined) {
            $('billing:street1').setValue(objArr[2]);
        }
        if($('shipping:street1') != undefined) {
            $('shipping:street1').setValue(objArr[2]);
        }
        if($('billing:city') != undefined) {
            $('billing:city').setValue(objArr[4]);
        }
        if($('shipping:city') != undefined) {
            $('shipping:city').setValue(objArr[4]);
        }
        if($('billing:postcode') != undefined) {
            $('billing:postcode').setValue(objArr[3]);
        }
        if($('shipping:postcode') != undefined) {
            $('shipping:postcode').setValue(objArr[3]);
        }
        if($('billing:email') != undefined) {
            $('billing:email').setStyle({
                border:'1px solid red'
            });
        }
        if($('billing:telephone') != undefined) {
            $('billing:telephone').setStyle({
                border:'1px solid red'
            });
        }
        if($('billing:country_id') != undefined) {
            $('billing:country_id').setValue('SE');
        }
        if($('shipping:country_id') != undefined) {
            $('shipping:country_id').setValue('SE');
        }

        // 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);
                    var klarnaInput = $('klarna_input');
                    if(ele.getValue() == "klarna_invoice" || ele.getValue() == "klarna_partpayment") {
                        if(klarnaInput){
                            klarnaInput.show();
                        }
                    } else {
                        if(klarnaInput){
                            klarnaInput.hide();
                        }
                    }
                });
            });
        }, 1500);
    }
});

var klarna = new Klarna();
var klarnapp = new Klarna();
var klarnacod = new Klarna();

document.observe('dom:loaded', function() {
    if(typeof klarnapartpaymentlang == 'undefined') {
        klarna.loadExternal();
    }
});


