/*
 *  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 KlarnaMage = Class.create({
    initialize: function() {
        this.element_id = false;
        this.merchant_id = false;
        this.fee = false;
        this.sum = 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;
    },

    setSum: function(sum) {
        this.sum = sum;
    },

    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 consent = new Element('script', {
            src: 'https://static.klarna.com/external/js/klarnaConsentNew.js'
        });
        $$('head').first().insert(consent);
        var special = new Element('script', {
            src: 'https://static.klarna.com/external/js/klarnaspecial.js'
        });
        $$('head').first().insert(special);
    },

    loadAgreement: function() {
        if (jQuery('#klarna_invoice_popup').length == 0) {
            openAgreement('de');
        }
    },

    showInvoiceTerms: function() {
        if (jQuery('#klarna_invoice_popup').length == 0) {
            openAgreement(klarnaMage.country);
        }
        if (typeof klarnaMage != 'undefined') {
            ShowKlarnaPopup(klarnaMage.merchant_id, klarnaMage.fee, 'invoice', '');
        }
    },

    showPartPaymentTerms: function() {
        if (jQuery('#klarna_invoice_popup').length == 0) {
            openAgreement(klarnaMage.country);
        }
        if (typeof klarnaMage != 'undefined') {
            ShowKlarnaPopup(klarnaMage.merchant_id, klarnaMage.sum, 'part', '');
        }
    },

    showSpecPaymentTerms: function() {
        if (typeof klarnaMage != 'undefined') {
            if (jQuery('#klarna_specialpayment_popup').length == 0) {
                InitKlarnaSpecialPaymentElements('specialCampaignPopupLink', klarnaMage.merchant_id, klarnaMage.country);
            }
            ShowKlarnaSpecialPaymentPopup();
        }
    },

    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();
                    klarnaMage.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();
                    klarnaMage.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);
    },
    clearBalloons: function() {
        var geenBalloon = jQuery('div[id="klarna_baloon"]').clone();
        jQuery('div[id="klarna_baloon"]').each(function () {
            jQuery(this).remove();
        });

        var blueBaloon = jQuery('div[id="klarna_blue_baloon"]').clone();
        jQuery('div[id="klarna_blue_baloon"]').each(function () {
            jQuery(this).remove();
        });

        jQuery('body').append(geenBalloon);
        jQuery('body').append(blueBaloon);

        jQuery(document).find('.klarna_box_bottom_languageInfo').remove();
    },
    doDocumentIsReady: function() {
        klarna.global.currentMinHeight_invoice = jQuery('#klarna_box_invoice').height();
        klarna.global.currentMinHeight_part = jQuery('#klarna_box_part').height();
        klarna.global.currentMinHeight_spec = jQuery('#klarna_box_spec').height();

        if(typeof InitKlarnaSpecialPaymentElements != 'undefined')
            InitKlarnaSpecialPaymentElements('specialCampaignPopupLink', klarna.global.eid, klarna.global.countryCode);
    },
    initPaymentSelection: function() {
        var checked = jQuery('input[type=radio][name="payment[method]"]:checked');
        var selected = jQuery(checked).attr("value");
        if (selected != klarna.global.invoice_name) {
            hidePaymentOption(jQuery('#klarna_box_invoice'));
        } else {
            showPaymentOption(jQuery('#klarna_box_invoice'));
        }

        if (selected != klarna.global.part_name) {
            hidePaymentOption(jQuery('#klarna_box_part'));
        } else {
            showPaymentOption(jQuery('#klarna_box_part'));
        }

        if (selected != klarna.global.spec_name) {
            hidePaymentOption(jQuery('#klarna_box_spec'));
        } else {
            showPaymentOption(jQuery('#klarna_box_spec'));
        }
        if (typeof paymentSelectionInitialized == 'undefined') {
            //Check if we already have a radio button selected for our payment solutions.
            var boxes = jQuery('.klarna_box_container');
            if (boxes.length > 0) {
                var value = jQuery('input[type=radio][name="payment[method]"]:checked').val();
                gChoice = value;
                if (typeof value != 'undefined') {
                    choosePaymentOption(value);
                }
            }
            //Bind our methods to the Magento radio buttons
            jQuery('input[type=radio][name="payment[method]"]').live("click", function() {
                jQuery('#klarna_baloon').hide();
                jQuery('#klarna_red_baloon').hide();
                jQuery('#klarna_blue_baloon').hide();
                jQuery("#payment_form_klarna_partpayment").show();
                jQuery("#payment_form_klarna_invoice").show();
                jQuery("#payment_form_klarna_specpayment").show();
                var value = jQuery(this).val();
                gChoice = value;
                choosePaymentOption(value);
            });
            paymentSelectionInitialized = true;
        }
    }
});

/**
 * Custom Magento validation
 */
Validation.addAllThese([
    ['klarna-validate-text', ' ', function(v, elm) {
        var result = ((v != "") && (v != null) && (v.length != 0))
        //Append to the red baloons
        if(result == false){
            ///
        }
        return result;
    }],
    ['klarna-validate-select', ' ', function(v, elm) {
        var result = ((v != "00") && (v != null) && (v.length != 0));
        //Append to the red baloons
        if(result == false){
            ///
        }
        return result;
    }],
    ['klarna-validate-radio', ' ', function (v,elm) {
        var choice = getPaymentOption();
        var value = jQuery(document).find('input[value="'+choice+'"]').attr("value");
        var paymentBox = jQuery(document).find('ul[id="payment_form_'+ value + '"]');
        var radioChecked = jQuery(paymentBox).find('input[type=radio]:checked');
        if (radioChecked.length > 0 ) {
            jQuery(elm).parent('div[class="klarna_gender_box"]').css('border', '');
            return true;
        } else {
            jQuery(elm).parent('div[class="klarna_gender_box"]').css('border', '1px solid #DD0000');
            return false;
        }
    }],
    ['klarna-validate-checkbox', ' ', function(v, elm) {
        var result = ((v != "") && (v != null) && (v.length != 0))
        if(result == false){
            jQuery(elm).parent('div[class="klarna_box_bottom_input_combo"]').css('border', '1px solid #DD0000');
        } else {
            jQuery(elm).parent('div[class="klarna_box_bottom_input_combo"]').css('border', '');
        }
        return result;
    }]
]);

var klarnaMage = new KlarnaMage();

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

    jQuery('.step-title').click(function(){
        if (typeof klarna != 'undefined') {
            klarna.errorHandler.hideRedBaloon();
        }
    });
    jQuery('button[class="button"]').click(function(){
        if (typeof klarna != 'undefined') {
            klarna.errorHandler.hideRedBaloon();
        }
    });
});


