/*
 *  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');
        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 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("|"));



                }
                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').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[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]);
            }

            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);
                    if(ele.getValue() == "klarna_invoice" || ele.getValue() == "klarna_partpayment") {
                        $('klarna_input').show();
                    } else
                        $('klarna_input').hide();
                    });
            });
        }, 1500);
    }
});

var klarna = new Klarna();
var klarnapp = new Klarna();

document.observe('dom:loaded', function() {    
    jQuery.noConflict();
    if(typeof klarnapartpaymentlang == 'undefined') {
        klarna.loadExternal();
    }
});


