var klarnaGeneralLoaded = true;
var red_baloon_busy = false;
var blue_baloon_busy = false;
var address_busy = false;
var baloons_moved = false;
var flagChange_active = false;
var changeLanguage_busy = false;
var openBox_busy = false;
var showing_companyNotAlowed_box = false;

var klarna_js_loaded = true;
//Variable to hold the validation errors
var redBaloonTextArray = [];
//Variable to hold the chosen payment method
var chosen;

var currentMinHeight_invoice;
var currentMinHeight_part;
var currentMinHeight_spec;


var global_countryCode;
var global_language_invoice;
var global_language_part;
var global_language_spec;
var shipmentAddressInput;
var shipmentAddressInput_invoice;
var shipmentAddressInput_spec;
var shipmentAddressInput_part;

var global_sum;
var global_flag;
var global_type;
var lang_companyNotAllowed;

//Added setup.pathCode and setup.path_img as var to use in the javascript
var global_pathCode;
var global_path_img;
var global_sPath;

var paramValues_invoice;
var paramNames_invoice;

var paramValues_part;
var paramNames_part;

var paramValues_spec;
var paramNames_spec;

var select_spec_bday;
var select_spec_bmonth;
var select_spec_byear;
var gender;

var spec_ITId;
var part_ITId;
var invoice_ITId;

var lang_personNum;
var lang_orgNum;


//Load when document finished loading
jQuery(document).ready(function (){                            
                	
	doDocumentIsReady();                

        /** @todo Specific magento changes // selected payment method **/
	var box 	= jQuery('input[type=radio][name="payment[method]"]:checked');
	var choice 	= jQuery(box).val();
        chosen          = "#payment_form_" + choice;
	if (choice != "klarna_invoice")
	{
		jQuery('#klarna_box_invoice_top_right').css({"display": "none"});
		jQuery('#klarna_box_invoice').animate({"min-height": "55px", "height": "55px"}, 200);
		jQuery('#klarna_box_invoice').find('.klarna_box_bottom').css({"display": "none"});
	}
	else {
		jQuery('#klarna_box_invoice').find('.klarna_box_bottom').fadeIn('fast');
	}

	if (choice != "klarna_partpayment")
	{
		jQuery('#klarna_box_part_top_right').css({"display": "none"});
		jQuery('#klarna_box_part').animate({"min-height": "55px", "height": "55px"}, 200);
		jQuery('#klarna_box_part').find('.klarna_box_bottom').css({"display": "none"});
	}
	else {
		jQuery('#klarna_box_part').find('.klarna_box_bottom').fadeIn('fast');
	}

	if (choice != "klarna_specpayment")
	{
		jQuery('#klarna_box_spec_top_right').css({"display": "none"});
		jQuery('#klarna_box_spec').animate({"min-height": "55px", "height": "55px"}, 200);
		jQuery('#klarna_box_spec').find('.klarna_box_bottom').css({"display": "none"});
	}
	else {
		jQuery('#klarna_box_spec').find('.klarna_box_bottom').fadeIn('fast');
	}

	baloons_moved = true;                
});

function removeBaloons() 
{    
    var baloon = jQuery('.klarna_baloon').first().clone();
    var baloon2 = jQuery('.klarna_red_baloon').first().clone();
    var baloon3 = jQuery('.klarna_blue_baloon').first().clone();   
     
    jQuery('.klarna_baloon').each(function () {
        jQuery(this).remove();
    });    
    
    jQuery('.klarna_red_baloon').each(function () {
        jQuery(this).remove();
    });    
        
    jQuery('.klarna_blue_baloon').each(function () {
        jQuery(this).remove();
    });
    
    jQuery('body').append(baloon);
    jQuery('body').append(baloon2);
    jQuery('body').append(baloon3);
}

function triggerChoosePaymentOption() {    
    var checked = jQuery('input[type=radio][name="payment[method]"]:checked');
    if(checked.length > 0) {
        jQuery("#payment_form_klarna_partpayment").show();
        jQuery("#payment_form_klarna_invoice").show();
        jQuery("#payment_form_klarna_specpayment").show();
        jQuery(checked).trigger("triggerChoosePaymentOption", [ checked.val() ]);
    }
    else {
        jQuery("#payment_form_klarna_partpayment").show();
        jQuery("#payment_form_klarna_invoice").show();
        jQuery("#payment_form_klarna_specpayment").show();
        jQuery('input[type=radio][name="payment[method]"]').trigger("triggerChoosePaymentOption", [ 'not_klarna' ]);
    }
}

function doDocumentIsReady()
{               
	var foundBox = false;
	currentMinHeight_invoice    = jQuery('#klarna_box_invoice').height();
	currentMinHeight_part 	= jQuery('#klarna_box_part').height();        
	currentMinHeight_spec 	= jQuery('#klarna_box_spec').height();   

	jQuery(document).bind('triggerChoosePaymentOption', function (e, choice){
                if (openBox_busy == false)
		{
                    //Magento fix
                    //Remove the red baloon, empty the validation array and update the chosen variable if we're switching payment method                    
                    redBaloonTextArray.length = 0;
                    jQuery("#klarna_red_baloon").hide();
                    chosen          = "#payment_form_" + choice;
                    
                    openBox_busy = true;                                        
                    if (choice == "klarna_invoice")
                    {
                            jQuery('#klarna_box_part_top_right').fadeOut('fast');
                            jQuery('#klarna_box_part').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_part').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_spec_top_right').fadeOut('fast');
                            jQuery('#klarna_box_spec').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_spec').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_invoice').animate({"height" : "100%"}, 200, function () {
                                    jQuery(this).find('.klarna_box_bottom').fadeIn('fast', function () {
                                            jQuery('.klarna_box_bottom_content_loader').fadeOut();

                                            if (showing_companyNotAlowed_box)
                                            {
                                                    hideRedBaloon();
                                            }
                                    });
                                    jQuery('#klarna_box_invoice_top_right').fadeIn('fast');

                                    if (invoice_different_language)
                                            jQuery('.klarna_box_bottom_languageInfo').fadeIn('fast');

                                    invoice_active = true;
                                    openBox_busy = false;
                            });
                    }
                    // @todo Changed to klarna_partpayment instead of klarna_partPayment
                    else if (choice == "klarna_partpayment")
                    {
                            jQuery('#klarna_box_invoice_top_right').fadeOut('fast');
                            jQuery('#klarna_box_invoice').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_invoice').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_spec_top_right').fadeOut('fast');
                            jQuery('#klarna_box_spec').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_spec').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_part').animate({"height" : "100%"}, 200, function () {
                                    jQuery(this).find('.klarna_box_bottom').fadeIn('fast', function () {
                                            jQuery('.klarna_box_bottom_content_loader').fadeOut();

                                            if (showing_companyNotAlowed_box)
                                            {
                                                    hideRedBaloon();
                                            }
                                    });
                                    jQuery('#klarna_box_part_top_right').fadeIn('fast');

                                    if (part_different_language)
                                            jQuery('.klarna_box_bottom_languageInfo').fadeIn('fast');

                                    part_active = true;
                                    openBox_busy = false;
                            });
                    }
                    else if (choice == "klarna_specpayment")
                    {
                            jQuery('#klarna_box_invoice_top_right').fadeOut('fast');
                            jQuery('#klarna_box_invoice').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_invoice').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_part_top_right').fadeOut('fast');
                            jQuery('#klarna_box_part').animate({"min-height": "55px", "height": "55px"}, 200);
                            jQuery('#klarna_box_part').find('.klarna_box_bottom').fadeOut('fast');

                            jQuery('#klarna_box_spec').animate({"min-height": currentMinHeight_spec, "height": currentMinHeight_spec}, 200, function () {
                                    jQuery(this).find('.klarna_box_bottom').fadeIn('fast', function () {
                                            jQuery('.klarna_box_bottom_content_loader').fadeOut();

                                            if (showing_companyNotAlowed_box)
                                            {
                                                    hideRedBaloon();
                                            }
                                    });
                                    jQuery('#klarna_box_spec_top_right').fadeIn('fast');

                                    if (spec_different_language)
                                            jQuery('.klarna_box_bottom_languageInfo').fadeIn('fast');

                                    spec_active = true;
                                    openBox_busy = false;
                            });
                    }
                    else {
                            jQuery('#klarna_box_part_top_right').fadeOut('fast');
                            jQuery('#klarna_box_invoice_top_right').fadeOut('fast');
                            jQuery('#klarna_box_spec_top_right').fadeOut('fast');

                            jQuery('.klarna_box_bottom').fadeOut('fast', function () {
                                    jQuery('#klarna_box_invoice').animate({"min-height": "55px", "height": "55px"}, 200);
                                    jQuery('#klarna_box_part').animate({"min-height": "55px", "height": "55px"}, 200);
                                    jQuery('#klarna_box_spec').animate({"min-height": "55px", "height": "55px"}, 200);

                                    jQuery('.klarna_box_bottom_languageInfo').fadeOut('fast');

                                    invoice_active = false;
                                    part_active = false;
                                    spec_active = false;
                                    openBox_busy = false;
                            });
                    }
		}                
	});

	// P-Classes box actions
	jQuery('.klarna_box').find('ol').find('li').live('mouseover', function (){
		if (jQuery(this).attr("id") != "click")
			jQuery(this).attr("id", "over");
	}).live('mouseout', function (){
		if (jQuery(this).attr("id") != "click")
			jQuery(this).attr("id", "");
	}).live('click', function (){
		resetListBox(jQuery(this).parent("ol"));
		jQuery(this).attr("id", "click");
		jQuery(this).find('div').append('<img src=\"' + global_path_img + '/images/ok.gif" border="0" alt="Chosen" />');

		var value = jQuery(this).find('span').html();                
		var name = jQuery(this).parent("ol").attr("id");
                /** @todo Name doesn't get updated to the correct value with addSetupValue() **/
		jQuery("input:hidden[name='payment[klarna_partpayment_pclass]']").attr("value", value);
	});


        /** 
         * @todo Specific magento changes // foreach payment method 
         * @note changed this part to use live() instead.
        **/
        jQuery('input[type=radio][name="payment[method]"]').live("click", function() {            
            var value = jQuery(this).val();
            jQuery("#payment_form_klarna_partpayment").show();
            jQuery("#payment_form_klarna_invoice").show();
            jQuery("#payment_form_klarna_specpayment").show();
            jQuery(this).trigger("triggerChoosePaymentOption", [ value ]);
	});
        
//        var checked = jQuery('input[type=radio][name="payment[method]"]:checked');
//        if(typeof checked != 'undefined') {
//            var value = checked.val();
//            jQuery("#payment_form_klarna_partpayment").show();
//            jQuery("#payment_form_klarna_invoice").show();
//            jQuery("#payment_form_klarna_specpayment").show();
//            jQuery(checked).trigger("triggerChoosePaymentOption", [ value ]);
//        }
        
        if(typeof global_countryCode != 'undefined'){
            if (global_countryCode == "de" || global_countryCode == "nl")
            {
		if (gender == 'm' || gender == '1')
                    {
                            jQuery('.Klarna_radio[value=0]').attr('checked', 'checked');
                    }
		else if (gender == 'f' || gender == '0')
                    {
                            jQuery('.Klarna_radio[value=1]').attr('checked', 'checked');
                    }
            }
        }

	// Input field on focus
	jQuery('.klarna_box').find('input').live('focusin', function () {
                removeBaloons();
		setBaloonInPosition(jQuery(this), false);
	}).live('focusout', function () {
		hideBaloon();
	});

	// Chosing the active language
	jQuery('.box_active_language').live('click', function () {
		if (flagChange_active == false)
		{
			flagChange_active = true;

			jQuery(this).parent().find('.klarna_box_top_flag_list').slideToggle('fast', function () {
				if (jQuery(this).is(':visible'))
				{
					jQuery(this).parent('.klarna_box_top_flag').animate({opacity: 1.0}, 'fast');
				}
				else {
					jQuery(this).parent('.klarna_box_top_flag').animate({opacity: 0.4}, 'fast');
				}

				flagChange_active = false;
			});
		}
	});

	jQuery('.klarna_box_top_flag_list img').live('click', function (){
		if (changeLanguage_busy == false)
		{
			changeLanguage_busy = true;

			var newIso = jQuery(this).attr("alt");

			jQuery('#box_active_language').attr("src", jQuery(this).attr("src"));

			var box = jQuery(this).parents('.klarna_box_container');
			var paramsValues;
			var paramNames;
			var type;

			if (box.find('.klarna_box').attr("id") == "klarna_box_invoice")
			{
				paramsValues = paramValues_invoice;
				paramNames = paramNames_invoice;
				type = "invoice";
			}
			else if (box.find('.klarna_box').attr("id") == "klarna_box_part")
			{
				paramsValues = paramValues_part;
				paramNames = paramNames_part;
				type = "part";
			}
			else if (box.find('.klarna_box').attr("id") == "klarna_box_spec")
			{
				paramsValues = paramValues_spec;
				paramNames = paramNames_spec;
				type = "spec";
			}
			else {
				return ;
			}
                        
			changeLanguage(box, paramsValues, paramNames, newIso, global_countryCode, type);
		}
	});

	//setTimeout('prepareRedBaloon()', 2000);

//	jQuery('#klarna_red_baloon').live('mouseover', function (){
//		showRedBaloonShowAgain();
//	});
//
//	jQuery('#klarna_red_baloon').live("mouseout blur", function (){
//		showRedBaloonHidden();
//	});

	jQuery('.klarna_box_bottom_languageInfo').live('mousemove', function (e) {
		showBlueBaloon(e.pageX, e.pageY, jQuery(this).find('img').attr("alt"));
	});

	jQuery('.klarna_box_bottom_languageInfo').live('mouseout', function () {
		hideBlueBaloon();
	});

	jQuery('.Klarna_pnoInputField').live("keyup blur focus change", function (){
            var pnoField = jQuery(this);
            var box = jQuery(this).parents('.klarna_box_container');
            var ptype;
            if (box.find('.klarna_box').attr("id") == "klarna_box_invoice")
            {
                    ptype = "invoice";
            }
            else if (box.find('.klarna_box').attr("id") == "klarna_box_part")
            {
                    ptype = "part";
            }
            else if (box.find('.klarna_box').attr("id") == "klarna_box_spec")
            {
                    ptype = "spec";
            }
            else {
                    return ;
            }
            getAddress(jQuery(this), (jQuery(this).parents('.klarna_box').attr("id") == "klarna_box_invoice"), (jQuery(this).parents('.klarna_box').attr("id") == "klarna_box_invoice" ? pnoField : null), ptype);
        });	
        
        
        
        /**
         * Custom Magento validation
         */
        Validation.addAllThese([
            ['klarna-required-entry', ' ', function(v, elm) {
                var result = ((v != "") && (v != null) && (v.length != 0))
                //Append to the red baloons
                if(result == false){
                    var label = jQuery(elm).prev().text();
                    prepareRedBaloonText(label);
                }
                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){
                    var label = jQuery(elm).parent().parent().prev().text();
                    prepareRedBaloonText(label);
                }
                return result;
            }],
            ['klarna-validate-one-required', ' ', function (v,elm) {
                var options = jQuery(chosen + ' .klarna-validate-one-required');
                return $A(options).any(function(elm) {
                    var result = $F(elm);
                    //Append to the red baloons
                    if(result == null) {
                        var label = options.first().prev().text();
                        prepareRedBaloonText(label);
                    }
                    return result;
                });
            }],
            ['klarna-validate-concent', ' ', function(v, elm) {
                var result = ((v != "") && (v != null) && (v.length != 0))
                //Append to the red baloons
//                if(result == false){
//                    jQuery.ajax({
//                        type: "GET",
//                        url: global_pathCode + "klarnaAjax.php",
//                        data: 'action=languagepack&subAction=jsLanguagePack&sText=no_consent&sISO=' + global_countryCode + '&sPath='+global_sPath,
//                        success: function(response){
//                            //jQuery('<li/>', {text: response}).appendTo('#klarna_red_baloon_content');
//                            prepareRedBaloonText(response);
//                            showRedBaloonText();
//                        }
//                    });
//                }
                return result;
            }],
            ['klarna-validate-show-baloon', ' ', function (v,elm) {
                //Only run if there isn't a concent button present
                //because then the baloon will be displayed with the ajax callback
//                if(typeof jQuery(chosen + ' .klarna-validate-concent') == 'undefined') {
//                    showRedBaloonText();
//                }
                return true;
            }]
        ]);        
}

/**
 * Get the validation messages and append it to the internal array
 */
function prepareRedBaloonText(label) {
    if(jQuery.inArray(label, redBaloonTextArray) == -1 && label.length > 0) {
        redBaloonTextArray.push(label);
    }
}

/**
 * Fill the red baloon with fields from the internal array
 */
function showRedBaloonText() {
    if(redBaloonTextArray.length > 0) {
        //Create a unsorted list with the fields that didn't validate'
        var ul = jQuery('<ul/>');
        jQuery.each(redBaloonTextArray, function(i, val) {
            jQuery('<li/>', {text: val}).appendTo(ul);
        });         
        //Get the balooncontent and empty it of any existing text
        var baloonContent = jQuery('#klarna_red_baloon_content');    
        baloonContent.empty();
        ul.appendTo(baloonContent);
        //Display the baloon at the correct container
        var container = jQuery(chosen + " .klarna_logo");
        showRedBaloon(container);
    }    
    else {
        jQuery('#klarna_red_baloon').hide();
    }
    
    //Clear the array for further validation
    redBaloonTextArray.length = 0;
    
}

function prepareRedBaloon ()
{
	if (jQuery('#klarna_red_baloon_content div').html() != "")
	{
		var field;
		
		if (typeof red_baloon_paymentBox == 'undefined')
		{
			field = jQuery(document).find('.klarna_logo');
		}
		else {
			field = jQuery(document).find('img[id='+red_baloon_paymentBox+']');
		}
	
		showRedBaloon(field);
		setTimeout('showRedBaloonHidden()', 3000);
	}
}

function getAddress (box, companyAllowed, field, type)
{    
	var pno_value = jQuery(box).val();

	// Set the PNO to the other fields
	jQuery(document).find('.Klarna_pnoInputField').each(function () {
		jQuery(this).val(pno_value);
	});

	// Do check
	if (pno_value != "")
	{
		jQuery(document).find('.klarna_box_bottom_content_loader').each(function () {
			if (!jQuery(this).is(":visible"))
				jQuery(this).fadeIn('fast');
		});

		if (!validateSocialSecurity(pno_value))
		{
			jQuery(document).find('.klarna_box_bottom_content_loader').each(function () {
				jQuery(this).fadeOut('fast');
			});

			if (jQuery('.klarna_box_bottom_address').is(":visible"))
				jQuery('.klarna_box_bottom_address').slideUp('fast');
		}
		else
		{
			if (!address_busy)
			{
				address_busy = true;
				
				// Get the new klarna_box
				jQuery.ajax({
					type: "GET",
					url: global_pathCode + "klarnaAjax.php",
					data: "action=getAddress&country="+global_countryCode+"&pno="+pno_value+"&type="+type,
					success: function(xml){
                                            
                                            jQuery(xml).find('error').each(function () {
                                               showRedBaloon(jQuery(box));
                                               jQuery('#klarna_red_baloon_content div').html(jQuery(this).text());
                                               jQuery('.klarna_box_bottom_address_content').html('');
                                               jQuery('.klarna_box_bottom_address').slideUp('fast');
                                               jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () {
                                                        address_busy = false;
                                               });
                                            });
                                            var isAddress = (jQuery(xml).find('address').length > 0);
                                            var selectBox = (jQuery('address', xml).length > 1);
                                            var inputInvoice;
                                            var inputPart;
                                            var inputSpec;
                                            var string = "";
                                            
                                            if(isAddress) {
                                            
                                                jQuery(xml).find('address').each(function (index, value) {
							var isCompany = (jQuery('companyName', this).length > 0);
								if (!selectBox)
								{
									var inputValue = (isCompany ? jQuery(this).find('companyName').text() : jQuery(this).find('first_name').text() + "|" + jQuery(this).find('last_name').text());
									inputValue += "|"+jQuery(this).find('street').text();
									inputValue += "|"+jQuery(this).find('zip').text()+"|"+jQuery(this).find('city').text();
									inputValue += "|"+jQuery(this).find('countryCode').text();

									if (typeof shipmentAddressInput_invoice != "undefined")
										inputInvoice = '<input type="hidden" name="'+shipmentAddressInput_invoice+'" value="'+inputValue+'" />';

									if (typeof shipmentAddressInput_part != "undefined")
										inputPart = '<input type="hidden" name="'+shipmentAddressInput_part+'" value="'+inputValue+'" />';

									if (typeof shipmentAddressInput_spec != "undefined")
										inputSpec = '<input type="hidden" name="'+shipmentAddressInput_spec+'" value="'+inputValue+'" />';

									string += "<p>"+(isCompany ? jQuery(this).find('companyName').text() : jQuery(this).find('first_name').text() + " " + jQuery(xml).find('last_name').text())+"</p>";
									string += "<p>"+jQuery(this).find('street').text()+"</p>";
									string += "<p>"+jQuery(this).find('zip').text()+" "+jQuery(this).find('city').text()+"</p>";
									//string += "<p>"+jQuery(this).find('countryCode').text()+"</p>";

									inputInvoice += string;
									inputPart += string;
									inputSpec += string;
								}
								else {
									var inputValue = (isCompany ? jQuery(this).find('companyName').text() : jQuery(this).find('first_name').text() + "|" + jQuery(this).find('last_name').text());
									inputValue += "|"+jQuery(this).find('street').text();
									inputValue += "|"+jQuery(this).find('zip').text()+"|"+jQuery(this).find('city').text();
									inputValue += "|"+jQuery(this).find('countryCode').text();

									string += '<option value="'+inputValue+'">';
									string += (isCompany ? jQuery(this).find('companyName').text() : jQuery(this).find('first_name').text() + " " + jQuery(xml).find('last_name').text());
									string += ", "+jQuery(this).find('street').text();
									string += ", "+jQuery(this).find('zip').text()+" "+jQuery(this).find('city').text();
									//string += ", "+jQuery(this).find('countryCode').text();
									string += '</option>';
								}

								if (isCompany)
								{
									jQuery('#invoiceType').val("company");
									jQuery('.referenceDiv').slideDown('fast');

									if (!selectBox)
									{
										jQuery('.klarna_box_bottom').animate({"min-height": "300px"},'fast');
									}

									if (companyAllowed == false && typeof lang_companyNotAllowed != "undefined")
									{
										showRedBaloon(jQuery(box));
										jQuery('#klarna_red_baloon_content div').html(lang_companyNotAllowed);
										showing_companyNotAlowed_box = true;
									}
									else {
										hideRedBaloon();
									}
								}
								else
								{
									jQuery('#invoiceType').val("private");
									jQuery(document).find('.referenceDiv').slideUp('fast');

									jQuery('.klarna_box_bottom').animate({"min-height": "250px"},'fast');

									if (showing_companyNotAlowed_box)
										hideRedBaloon();
								}
							});		

							if (selectBox)
								string += "</select>";

							var selectInvoice;
							var selectPart;
							var selectSpec;

							if (selectBox)
							{
								if (typeof shipmentAddressInput_invoice != "undefined")
									selectInvoice = '<select name="'+shipmentAddressInput_invoice+'">'+string;

								if (typeof shipmentAddressInput_part != "undefined")
									selectPart = '<select name="'+shipmentAddressInput_part+'">'+string;

								if (typeof shipmentAddressInput_spec != "undefined")
									selectSpec = '<select name="'+shipmentAddressInput_spec+'">'+string;
							}

							jQuery('#klarna_box_invoice').find('.klarna_box_bottom_address_content').html((selectBox ? selectInvoice : inputInvoice));

							jQuery('#klarna_box_part').find('.klarna_box_bottom_address_content').html((selectBox ? selectPart : inputPart));

							jQuery('#klarna_box_spec').find('.klarna_box_bottom_address_content').html((selectBox ? selectSpec : inputSpec));

							jQuery('.klarna_box_bottom_address').slideDown('fast');
							jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () {
								address_busy = false;
							});
                                                }
                                                address_busy = false;
					} 
				});
			}
		}
	}
	else {
		jQuery(document).find('.referenceDiv').each(function (){
			if (jQuery(this).is(":visible"))
			{
				jQuery(this).slideUp('fast');
			}
			else {
				jQuery(this).css({"display":"none"});
			}
		});

		jQuery('.klarna_box_bottom_content_loader').fadeOut('fast');

		jQuery(document).find('.klarna_box_bottom_address').each(function () {
			if (jQuery(this).is(":visible"))
			{
				jQuery(this).slideUp('fast');
			}
			else {
				jQuery(this).css({"display":"none"});
			}
		});
	}
}

function showBlueBaloon (x, y, text)
{
	jQuery('#klarna_blue_baloon_content div').html(text);

	var top = (y - jQuery('#klarna_blue_baloon').height())-5;
	var left = (x - (jQuery('#klarna_blue_baloon').width()/2)+5);

	jQuery('#klarna_blue_baloon').animate({"left": left, "top": top}, 10);

	if (!jQuery('#klarna_blue_baloon').is(':visible') && !blue_baloon_busy)
	{
		blue_baloon_busy = true;
		jQuery('#klarna_blue_baloon').fadeIn('fast', function () {
			blue_baloon_busy = false;
		});
	}
}

function hideBlueBaloon ()
{
	if (jQuery('#klarna_blue_baloon').is(':visible') && !blue_baloon_busy)
	{
		jQuery('#klarna_blue_baloon').fadeOut('fast', function () {
			blue_baloon_busy = false;
		});
	}
}

function showRedBaloon (theField)
{
	if (red_baloon_busy || typeof theField == 'undefined')
            	return;
	                        
	red_baloon_busy = true;        

	if (theField == null)
		field = jQuery('#klarna_logo');
	else
		field = jQuery(theField);

	var position = field.offset();
        if(position != null) {
            var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6);
            if (top < 0) top = 10;
            position.top = top;

            var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2);

            position.left = left;

            jQuery('#klarna_red_baloon').css(position);

            jQuery('#klarna_red_baloon').show();
            //jQuery('#klarna_red_baloon').fadeOut('slow');
            red_baloon_busy = false;
        }
}

function showRedBaloonHidden ()
{
	if (red_baloon_busy)
		return;

	red_baloon_busy = true;

	jQuery('#klarna_red_baloon').animate({"opacity": 0}, 500, function () {
		red_baloon_busy = false;
	});
}

function showRedBaloonShowAgain ()
{
	if (red_baloon_busy)
		return;

	red_baloon_busy = true;

	jQuery('#klarna_red_baloon').animate({"opacity": 1.0}, 500, function () {
		red_baloon_busy = false;
	});
}

function hideRedBaloon ()
{
	if (red_baloon_busy)
		return;

	if (jQuery('#klarna_red_baloon').is(':visible') && !red_baloon_busy)
	{
		jQuery('#klarna_red_baloon').fadeOut('fast', function () {
			red_baloon_busy = false;
			showing_companyNotAlowed_box = false;
		});
	}
}

/**
 * This function is only available for swedish social security numbers
 */
function validateSocialSecurity (vPNO)
{
	if (typeof vPNO == 'undefined')
		return false;

	return vPNO.match(/^([1-9]{2})?[0-9]{6}[-\+]?[0-9]{4}$/)
	}

function resetListBox (listBox)
{
	listBox.find('li').each(function (){
		if (jQuery(this).attr("id") == "click")
		{
			jQuery(this).attr("id", "");
		}

		jQuery(this).find('div').find('img').remove();
	});
}

function hideBaloon (callback)
{
	if (jQuery('#klarna_baloon').is(":visible"))
	{
		jQuery('#klarna_baloon').fadeOut('fast', function (){
			if( callback ) callback();

			return true;
		});
	}
	else {
		if( callback ) callback();
		return true;
	}
}

function setBaloonInPosition (field, red_baloon)
{
	hideBaloon(function (){
		var position = field.offset();                
		var name = field.attr('name');
		var value = field.attr('alt');
                
		if (!value && !red_baloon)
		{
			return false;
		}

		if (!red_baloon)
		{
			jQuery('#klarna_baloon_content div').html(value);

			var top = position.top - jQuery('#klarna_baloon').height();    
			if (top < 0) top = 10;
			position.top = top;

			var left = (position.left + field.width()) - (jQuery('#klarna_baloon').width() - 50);

			position.left = left;

			jQuery('#klarna_baloon').css(position);

			jQuery('#klarna_baloon').fadeIn('fast');
		}
		else {
			var top = position.top - jQuery('#klarna_red_baloon').height();
			if (top < 0) top = 10;
			position.top = top;

			var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() - 50);

			position.left = left;

			jQuery('#klarna_red_baloon').css(position);

			jQuery('#klarna_red_baloon').fadeIn('fast');
		}
	});
}

function changeLanguage (replaceBox, paramNames, paramValues, newIso, country, type)
{
	var paramString	= "";
	var valueString = "";
        var inputValue = "";
        
	for (var i = 0; i < paramNames.length; i++)
	{            
		paramString += "&params["+paramValues[i]+"]="+paramNames[i];

		inputValue = jQuery('input[name="'+paramNames[i]+'"]').val();

		if((typeof(inputValue) != "undefined"))
			valueString += "&values["+paramValues[i]+"]="+inputValue;
	}
        
	jQuery.ajax({
		type: "GET",
		url: global_pathCode + "klarnaAjax.php",
		data: 'action=languagepack&subAction=klarna_box&type='+type+'&newIso='+newIso+'&country='+country+'&sum='+global_sum+'&flag='+global_flag+valueString+paramString,
		success: function(response){
			if (jQuery(response).find('.klarna_box'))
			{
				replaceBox.find('.klarna_box').remove();
				replaceBox.append(jQuery(response).find('.klarna_box'));

				if (type == "invoice")
				{
					if (newIso != global_language_invoice)
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeIn('slow', function () {
							changeLanguage_busy = false;
						});
					else 
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeOut('slow', function () {
							changeLanguage_busy = false;
						});
					
					klarna_invoiceReady();
				}

				if (type == "part")
				{
					if(newIso != global_language_part)
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeIn('slow', function () {
							changeLanguage_busy = false;
						});
					else 
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeOut('slow', function () {
							changeLanguage_busy = false;
						});
					
					klarna_partReady();
				}

				if (type == "spec")
				{
					if(newIso != global_language_spec)
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeIn('slow', function () {
							changeLanguage_busy = false;
						});
					else 
						replaceBox.find('.klarna_box_bottom_languageInfo').fadeOut('slow', function () {
							changeLanguage_busy = false;
						});
					
					klarna_specReady();
				}
				
				jQuery('#klarna_invoice_popup').remove();
				openAgreement(country);

				doDocumentIsReady();
			}
			else {
				alert("Error, block not found. Response:\n\n"+response);
			}
		}
	});
}

