﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />

$.fn.knowit = {};

var c;
var selectedPrice;
var selectedPrices;
var ATagclickable;
var LabelToBeClickableIndex;
var theVat;
var USES_EL_AREA = false;
var DEFAULT_EL_AREA;
var PRICETYPE_GROUP_IS_RORLIG = false;
var PRICE_TYPE_INFOBOX = "";
var PriceCatcherGlobaltest;

$(document).ready(function () {
    //------------------------------------------------------
    // VARIABLER
    //------------------------------------------------------
    var COMES_FROM_SHOW_PRICES = false;
    var contactForm = $("#AgreementForm", document.body);
    var steps = $("#Steps", contactForm);
    var panes = $("> div", contactForm);
    var GreenChoiceVar = 0;
    var companyId = MarketPlace;
    var step1 = $("#step1");
    var info = $("#AgreementInfo");
    var fieldsets = $(step1.children("div.fieldset"));
    var customerType = $("#customer-type", step1);
    var housing = $("#Housing", step1);
    var agreement = $("#agreement", step1);
    var date = $("#DateChoice", step1);
    var priceCapturer = $("#price-capturer", step1);
    var greenChoice = $("#green-choice", step1);
    var AnnualBoxFirst = 0;
    var dd = $("dd", info);

    //ResizeWindow-Event
    if (jQuery.browser.msie && jQuery.browser.version < 8) {
    }
    else {
        $(window).bind("resize", function () {
            onResizeWindow(PRICETYPE_GROUP_IS_RORLIG);
        });
    }
    //------------------------------------------------------
    $("#AgreementInfo").append("<div style='display:none' id='Html1'>" +

    $("#AgreementInfo").html() + "</div>");

    $("#Html1 .hd").html('');
    $("#Html1 .panel1").html('');
    $("#Html1 .panel2").html('');
    $("#Html1 .panel3").html('');

    if (ChosenPriceType.length > 0 && ChosenPeriod.length > 0 && ChosenStartDate.length > 0) {
        COMES_FROM_SHOW_PRICES = true;
    }

    //------------------------------------------------------
    // BROWSER-SPECIFIKT
    //------------------------------------------------------


    if (jQuery.browser.msie && jQuery.browser.version == 8 && SodraCSSFixPersonal != "True") {
        $("#personal-data .column").css("margin-left", "140px");
        $("#BindTime").css("margin-left", "140px");
        //$(".Annualtextbox").css('width', '150px');

    }
    if (jQuery.browser.msie && jQuery.browser.version == 7) {
        $(".InputLastNameWidth").css("margin-top", "3px");
        $("#AgreementFillOutForm").css("padding-left", "60px");
        $("#BindTime").css("margin-left", "140px");
    }

    if (jQuery.browser.mozilla && SodraCSSFixPersonal != "True") {

        $("#personal-data .column").css('margin-left', '125px');
    }

    var isSafari = $.browser.safari;
    if (isSafari) {
        //$("#personal-data .column").css('margin-left', '115px');¨'
        $("#AgreementInfo dt").css("width", "120px");
        $("#AgreementInfo .panel dl").css("overflow", "hidden");
        $("#personal-data .Step2LabelMargin").css('margin-left', '1em');
    }
    //------------------------------------------------------

    //------------------------------------------------------
    // GÖM/VISA OLIKA SAKER BEROENDE PÅ KUND...
    //------------------------------------------------------
    if (ShowMemberNumberTextArea == "False") {
        $("#MemberNumber").parent().parent().hide();
        $("#MemberDataArea").hide();
        $(".Memberinfo").hide();
        $(".Memberinfo").prev().hide();
        $(".MedlemsInfo").prev().hide();
        $(".MedlemsInfo").hide();
    }
    if (HideEnvironmentChoice == "True") {
        $("#makeAnEnvironmentChoiceDiv").hide();

    }
    else {
        $("#makeAnEnvironmentChoiceDiv").show();
    }
    if (HideClubEnergy == "True") {
        $("#clubEnergyDiv").hide();
    }
    else {
        $("#clubEnergyDiv").show();
    }
    if (HideEnvironmentEmailCb == "True") {
        $("#environmentMailDiv").remove();
        $(".EnviromentChoice").prev().remove();
        $(".EnviromentChoice").remove();
        $("#EnvironmentConf").prev().remove();
        $("#EnvironmentConf").remove();


    }
    else {
        $("#environmentMailDiv").show();
    }
    if (HideAutoGiroChoice == "True") {
        $("#Autogiro").hide();
        $("#AutoGiroLbl").hide();
    }
    else {
        $("#Autogiro").show();
        $("#AutoGiroLbl").show();
    }
    if (HideEfakturaChoice == "True") {
        $("#EInvoice").prev().hide();
        $("#EInvoice").hide();
        $("#EInvoice").next().hide();
    }
    else {
        $("#EInvoice").prev();
        $("#EInvoice").show();
        $("#EInvoice").next().show();
    }

    if (UseSpecialCustomerTypes == "True") {
        $("#custTypeSpecial").show();
        $("#custTypeNormal").hide();
    }
    else {
        $("#custTypeSpecial").hide();
        $("#custTypeNormal").show();
    }
    //------------------------------------------------------

    //------------------------------------------------------
    //DÖLJ/VISA Boendeform
    //------------------------------------------------------
    if (HideHouseingForm == "True") {
        $('#HousingRadioButtonContainer').remove();
        $('#housingHeader').html('Energiförbrukning');
        $("#Housing1").css("padding-left", "100px");

        //Ta bort "Boende" från högerspalten
        var container = $("#AgreementInfo dl:eq(0) dd");
        //$(".boende").addClass('Closed');
        //container.eq(2).addClass('Closed');
        //$(".boende").removeClass('Open');
        //container.eq(2).removeClass('Open');
        $(".boende").remove();
        container.eq(2).remove();

        $(".LivingForm").prev().remove();
        $(".LivingForm").remove();
    }
    else {
        $('#HousingRadioButtonContainer').show();
        $('#housingHeader').html('Boendeform');
    }
    //------------------------------------------------------

    //------------------------------------------------------
    // START-UP: Göm, visa, initiera, css-trolla...
    //------------------------------------------------------

    //Hämta default-elområde för företaget
    GetDefaultElArea(companyId);

    //Fyll elområdens-dropdown
    FillElAreas(companyId);

    $('#step1Done').hide();
    $('#step2Done').hide();
    $('#btnGotoStep2').attr("disabled", true);
    $("#TotalPriceInYear").attr("checked", true);

    GenerateHelperText(PageId);
    ValidationRules(RequiredStdValidate, RequiredFirstName, RequiredSecondName, RequiredAddress,
            RequiredPostalCode, RequiredPlace, RequiredPhoneDayTime, RequiredEveningTime, RequiredEmail,
            RequiredBuildningId, RequiredAreaId, RequiredUseAltAdress, RequiredAltAdress, RequiredAltPostalCode, RequiredAltPlace
    );

    RoundedCorners();
    IE6Fix();
    DimEnhancement();
    SetVisibility(0, 1, fieldsets);

    //Gör så att "Ditt nya elavtal" (högerrutan) följer scrollning
    //$('#RightArea').makeFloat({ x: "current", y: "current", speed: "normal", alwaysVisible: true });
    onResizeWindow(PRICETYPE_GROUP_IS_RORLIG);
    //$(".info-box").hide();

    $("#BuildingIDFixed").val('735999');

    ATagclickable = false;
    LabelToBeClickableIndex = 0;

    $(".fieldset a").css("cursor", "default");
    $("#step1 .fieldset input").attr("disabled", true);
    $("#step1 .fieldset:first input").attr("disabled", false);
    $(".fieldset a").css("text-decoration", "none");
    $("#Order").attr('disabled', 'disabled');
    $("#Bindtime-capture legend:first").hide();
    $("#MainArea").css("overflow", "visible");

    $("#HideAltAdress").hide();
    $("#step2").hide();
    $("#step3").hide();

    //Dimma alla fieldsets utom första
    fieldsets.addClass('Opacity3CSS'); // css('opacity', '0.3');
    fieldsets.eq(0).removeClass('Opacity3CSS');
    fieldsets.eq(0).removeClass('Opacity3CSSIE8');
    $("#NewCustomerRadio").removeAttr('style');
    $("#AlreadyCustomerRadio").removeAttr('style');

    //Göm Påslag och Miljöval i högerspalten
    //var container = $("#AgreementInfo dl:eq(1) dd");
    if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
        $('#EnergyPrice').hide();
        $('#EnergyPrice').next().hide();
        $(".SuppCharge").hide();
        $(".SuppCharge").next().hide();
    }
    else {
        $(".SuppCharge").hide();
        $(".SuppCharge").next().hide();
    }
    $(".Miljo").hide();
    $(".Miljo").next().hide();
    //------------------------------------------------------

    //------------------------------------------------------
    //Om man kommit hit via "ShowPrices"
    //------------------------------------------------------
    if (COMES_FROM_SHOW_PRICES) {
        //Markera vald kundtyp
        if (ChosenIsSpecial == "") {
            if (ChosenIsExistingCustomer == "true") {
                $("#NewCustomerRadio").attr('checked', false);
                $("#AlreadyCustomerRadio").attr('checked', true);
            }
            else {
                $("#NewCustomerRadio").attr('checked', true);
                $("#AlreadyCustomerRadio").attr('checked', false);
            }
        }
        else {
            switch (ChosenIsSpecial) {
                case "Medlem":
                    $("#memberRadio").attr('checked', true);
                    $("#EmployedRadio").attr('checked', false);
                    $("#PartnerRadio").attr('checked', false);
                    break;
                case "Tillsvidareanställd":
                    $("#memberRadio").attr('checked', false);
                    $("#EmployedRadio").attr('checked', true);
                    $("#PartnerRadio").attr('checked', false);
                    break;
                case "Samarbetspartner":
                    $("#memberRadio").attr('checked', false);
                    $("#EmployedRadio").attr('checked', false);
                    $("#PartnerRadio").attr('checked', true);
                    break;
                default: return;
            }
        }

        $("#btnElAreaSearch").show();
        $('#AreaID').val(ChosenElAreaId); //Sätt vald rads id i "Områdeskod/Id" (steg 2)

        //Öppna upp "Boendeform"
        SetVisibility(0, 2, fieldsets);
        ClearInfo();
        ClearHousing(fieldsets);

        if (ChosenIsNormalTax == "false")
            $("#ReducedPrice").attr('checked', true);
        else
            $("#ReducedPrice").attr('checked', false);

        //$('#elarea').val(ChosenElArea);
        if (USES_EL_AREA)
            $('#elarea').setDropDownValue(ChosenElArea);
        //GetDatesAndPriceTypes();
    }
    //------------------------------------------------------

    //------------------------------------------------------
    //Tillåt enbart siffror/Tillåt enbart bokstäver
    //------------------------------------------------------
    $('.Annualtextbox').OnlyNumbers();
    $('#PostalCode').OnlyNumbers();
    $('#CivRegNumber').OnlyNumbers();
    $('#PhoneDayTime').PhoneNbr();
    $('#PhoneEveningTime').PhoneNbr();
    $('#AltPostalCode').OnlyNumbers();
    $("#BuildingID").OnlyNumbers();
    $("#AreaID").OnlyLetters();
    //------------------------------------------------------

    //------------------------------------------------------
    // EVENTS: Click, change, keyup, live
    //------------------------------------------------------

    //********************************
    //STEG1: KUNDTYP
    //********************************

    //********************
    //Radioknappar
    //********************
    $("input", customerType).click(function () {
        SetVisibility(0, 2, fieldsets);
        $("#btnElAreaSearch").show();
        ClearInfo();
        ClearHousing(fieldsets);
    });

    //********************
    //Radioknapps-label och Radios
    //********************
    $("#AlreadyCustomer").click(function () {
        CustomerTypeEvent(companyId, false, false, false, false, true, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#AlreadyCustomerRadio").click(function () {
        CustomerTypeEvent(companyId, false, false, false, false, true, fieldsets);
        $("#btnElAreaSearch").show();
    });

    $("#NewCustomer").click(function () {
        CustomerTypeEvent(companyId, true, false, false, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#NewCustomerRadio").click(function () {
        CustomerTypeEvent(companyId, true, false, false, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#Member").click(function () {
        CustomerTypeEvent(companyId, false, true, false, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#memberRadio").click(function () {
        CustomerTypeEvent(companyId, false, true, false, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });

    $("#Employed").click(function () {
        CustomerTypeEvent(companyId, false, false, true, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#EmployedRadio").click(function () {
        CustomerTypeEvent(companyId, false, false, true, false, false, fieldsets);
        $("#btnElAreaSearch").show();
    });

    $("#Partner").click(function () {
        CustomerTypeEvent(companyId, false, false, false, true, false, fieldsets);
        $("#btnElAreaSearch").show();
    });
    $("#PartnerRadio").click(function () {
        CustomerTypeEvent(companyId, false, false, false, true, false, fieldsets);
        $("#btnElAreaSearch").show();
    });

    //********************************
    //STEG1: BOENDEFORM
    //********************************

    ///********************
    //ElOmråde
    //********************
    if (USES_EL_AREA) {
        $("#elarea").change(function () {
            ReducedPriceAndElAreaChangeLogic();
        });
        $("#btnElAreaSearch").click(function () {
            openSearchPopUp();
        });

        $("#refListAll").click(function () {
            SearchElAreas("%");
        });

        //Ajaxified search, search while you type (at least 2 char)
        $("#tbSearch").keyup(function (e) {
            if ($("#tbSearch").val().length > 0) {
                SearchElAreas($("#tbSearch").val());
            }
            else {
                $("#totalHits").html("");
                $("#searchResult").hide();
            }
        });
    }
    //********************
    //Radioknapps-label
    //********************
    var HouseingRadioButtonContainer = $("#HousingRadioButtonContainer");
    $("label", HouseingRadioButtonContainer).click(function () {
        if (LabelToBeClickableIndex > 1) {
            $(this).prev().attr('checked', true);
            $(this).addClass("SelectedHousingRadioButton");
            if ($(".Annualtextbox").val().length > 0) {
                var currentValue = parseInt($(".Annualtextbox").val());
                var stopHere = preventFurtherChangesIfAnnualToHigh(currentValue);
                if (!stopHere) {
                    SetVisibility(0, 3, fieldsets);
                    ClearDeal();
                    ClearPrices();
                    ClearCheckboxes(2, 6, fieldsets);
                }
            }
            dd.eq(2).html($(this).html());
        }
        GetDatesAndPriceTypes();
    });

    //********************
    //Radioknappar
    //********************
    $("input", HouseingRadioButtonContainer).click(function () {
        if (LabelToBeClickableIndex > 1) {
            $(this).attr('checked', true);
            $(this).next().addClass("SelectedHousingRadioButton");
            if ($(".Annualtextbox").val().length > 0) {
                var currentValue = parseInt($(".Annualtextbox").val());
                var stopHere = preventFurtherChangesIfAnnualToHigh(currentValue);
                if (!stopHere) {
                    SetVisibility(0, 3, fieldsets);
                    ClearDeal();
                    ClearPrices();
                    ClearCheckboxes(2, 6, fieldsets);
                }
            }

            dd.eq(2).html($(this).next().html());

            GetDatesAndPriceTypes();
        }
    });

    //********************
    //Din årsförbrukning
    //********************
    $('.Annualtextbox').change(function () {
        var currentValue = parseInt($(this).val());
        preventFurtherChangesIfAnnualToHigh(currentValue);
    });
    $(".Annualtextbox").click(function () {
        if (LabelToBeClickableIndex > 1) {
            var box = $(this).val();
            var InputTags = $("label", HouseingRadioButtonContainer);
            var FoundCheckedRadioButton = false;
            InputTags.each(function () {
                if ($(this).hasClass("SelectedHousingRadioButton")) {
                    FoundCheckedRadioButton = true;
                    dd.eq(2).html($(this).html());
                }
            });
        }
    });

    var sTimer;
    if (!COMES_FROM_SHOW_PRICES) {
        $(".Annualtextbox").keyup(function () {
            onAnnualTextBoxChange($(this));
        });
    }
    else {
        $(".Annualtextbox").keyup(function () {
            var detta = $(this);

            if (sTimer) clearTimeout(sTimer);
            sTimer = setTimeout(function () {
                onAnnualTextBoxChange(detta);
            }, 500);
        });
    }
    //********************

    //********************
    //Reducerat skatt
    //********************
    $("#ReducedPrice").click(function () {
        ReducedPriceAndElAreaChangeLogic();
    });

    //********************************
    //STEG1: STARTDATUM
    //********************************
    $("select", date).change(function () {
        ClearDeal();
        ClearPrices();
        ClearCheckboxes(5, 6, fieldsets);

        $('#btnGotoStep2').attr("disabled", true);

        if ($(this).val() != "-1") {

            dd.eq(0).html($(":selected", this).html());
            SetVisibility(0, 4, fieldsets);
            ClearCheckboxes(2, 6, fieldsets);
            $("#AgreementFillOutForm").hide();
            $("#BindTime").html('');
        }
        else {
            SetVisibility(0, 3, fieldsets);
            ClearDeal();
            ClearPrices();
            ClearCheckboxes(2, 6, fieldsets);

            var isExistingCustomer;
            if (UseSpecialCustomerTypes == "True")
                isExistingCustomer = true;
            else {
                isExistingCustomer = $("input:checked", customerType).next().html() == "Redan kund";
            }
            GetPriceDates(companyId, isExistingCustomer);
            GetPriceTypes(companyId);
        }
    });

    //********************************
    //STEG1: AVTALSFORM
    //********************************

    //********************
    //Avtalsform: label
    //********************
    $("fieldset:eq(0) label", agreement).live("click", function () {
        if (LabelToBeClickableIndex > 3) {
            $(this).prev().attr("checked", true);
            SetVisibility(0, 4, fieldsets);

            //CLEAR AgreementTime
            var container = $("#AgreementInfo dl:eq(0) dd");
            container.eq(1).html("-");

            ClearPrices();
            ClearCheckboxes(4, 6, fieldsets);

            var priceTypeId = $(this).prev().val();
            GetPricesAndAddons(priceTypeId, $(this).html());
        }
    });

    //********************
    //Avtalsform: Radio
    //********************

    $("fieldset:eq(0) input", agreement).live("click", function () {
        if (LabelToBeClickableIndex > 3) {
            $(this).attr("checked", true);
            SetVisibility(0, 4, fieldsets);

            //CLEAR AgreementTime
            var container = $("#AgreementInfo dl:eq(0) dd");
            container.eq(1).html("-");

            ClearPrices();
            ClearCheckboxes(4, 6, fieldsets);

            var priceTypeId = $(this).val();
            GetPricesAndAddons(priceTypeId, $(this).next().html());
        }
    });


    //********************
    //Avtalslängd: radio
    //********************
    $("#BindTime input").live("click", function () {
        if (LabelToBeClickableIndex > 3) {
            SetVisibility(0, 7, fieldsets);
            $("#AgreementLength").show();
            $("#AgreementLength").next().show();
            dd.eq(1).html($(this).next().html());
        }
    });

    //********************
    //Avtalslängd: label
    //********************
    $("#BindTime label").live("click", function () {
        if (LabelToBeClickableIndex > 3) {
            SetVisibility(0, 7, fieldsets);
            $("#AgreementLength").show();
            $("#AgreementLength").next().show();
            $(this).prev().attr("checked", true);
            dd.eq(1).html($(this).html());
        }
    });

    //********************************
    //STEG1: PRISFÅNGAREN
    //********************************

    //********************
    //Bindningsnivå: radio
    //********************
    $("#BindLevel input").live("click", function () {
        if (LabelToBeClickableIndex > 4) {
            var the_radio = $("#PriceCapturerTime input:radio:checked");
            if (the_radio.length == 0) {
                $('#btnGotoStep2').attr("disabled", true);
                $('#step1Done').hide();
            }
            else {
                $('#btnGotoStep2').removeAttr("disabled");
            }
        }
    });
    //********************
    //Bindningsnivå: label
    //********************
    var PriceLevel1 = $("#BindLevel");
    $("label", PriceLevel1).live("click", function () {
        if (LabelToBeClickableIndex > 4) {
            $(this).prev().attr('checked', true);
            var the_radio = $("#PriceCapturerTime input:radio:checked");
            if (the_radio.length == 0) {
                $('#btnGotoStep2').attr("disabled", true);
                $('#step1Done').hide();
            }
            else {
                $('#btnGotoStep2').removeAttr("disabled");
            }
        }
    });

    //********************
    //Bindningstid: label
    //********************
    var PriceCapture1 = $("#PriceCapturerTime");
    $("label", PriceCapture1).live("click", function () {
        if (LabelToBeClickableIndex > 4) {
            $(this).prev().attr('checked', true);
            var the_radio = $("#BindLevel input:radio:checked");
            if (the_radio.length == 0) {
                $('#btnGotoStep2').attr("disabled", true);
                $('#step1Done').hide();
            }
            else {
                $('#btnGotoStep2').removeAttr("disabled");
            }
        }
    });
    //********************
    //Bindningstid: radio
    //********************
    $("#PriceCapturerTime input").live("click", function () {
        if (LabelToBeClickableIndex > 4) {
            var the_radio = $("#BindLevel input:radio:checked");
            if (the_radio.length == 0) {
                $('#btnGotoStep2').attr("disabled", true);
                $('#step1Done').hide();
            }
            else {
                $('#btnGotoStep2').removeAttr("disabled");
            }
        }
    });

    //********************************
    //STEG1: MILJÖVAL
    //********************************

    //********************
    //Radioknappar
    //********************
    $("fieldset:eq(0) input", greenChoice).live("click", function () {
        EditPriceWithEnvironmentChoice(parseFloat($(this).val()).toFixed(2), false);
    });

    //********************
    //Radioknapps-label
    //********************
    $("fieldset:eq(0) label", greenChoice).live("click", function () {
        if (LabelToBeClickableIndex > 5) {
            $(this).prev().attr('checked', true);

            SetVisibility(0, 7, fieldsets);

            EditPriceWithEnvironmentChoice(parseFloat($(this).prev().val()).toFixed(2), false);
        }
    });

    //********************
    //Miljövänlig bekräftelse...
    //********************
    $("#GoodForEnviromentMail").live("click", function () {
        if ($("#GoodForEnviromentMail").hasClass('checked')) {
            $("#GoodForEnviromentMail").attr('checked', false);
            $("#GoodForEnviromentMail").removeClass('checked');
        }
        else {
            $("#GoodForEnviromentMail").attr('checked', true);
            $("#GoodForEnviromentMail").addClass('checked');
        }
        SetVisibility(0, 7, fieldsets);
    });

    //********************************
    //STEG2:
    //********************************

    //********************
    //Inget personnr
    //********************
    $("#NoCivRegNumber").click(function () {
        if ($("#NoCivRegNumber").hasClass("NoCivRegNumberSelected")) {
            $(this).attr('checked', false);
            $(this).removeClass("NoCivRegNumberSelected");
            $(this).addClass("NoCivRegNumberUnSelected");
        }
        else {
            $(this).attr('checked', true);
            $(this).addClass("NoCivRegNumberSelected");
            $(this).removeClass("NoCivRegNumberUnSelected");
        }
    });

    //********************
    //AnläggningsID
    //********************
    $("#BuildingID").keydown(function (e) {
        SameRightColumn();

        var key = e.charCode || e.keyCode || 0;

        SameRightColumn();

        var maxLength = 12;
        var length = this.value.length;
        if (length >= maxLength) {
            //Allow SHIFT, TAB, BACKSPACE, DELETE, RightArrow, LeftArrow
            if (key == 16 || key == 9 || key == 8 || key == 46 || key == 39 || key == 37) {
            }
            else {
                e.preventDefault();
            }
        }
    });

    //********************
    //Områdeskod/id
    //********************
    $("#AreaID").keydown(function (e) {
        SameRightColumn();
        var key = e.charCode || e.keyCode || 0;

        var maxLength = 3;
        var length = this.value.length;
        if (length >= maxLength) {
            //Allow SHIFT, TAB, BACKSPACE, DELETE, RightArrow, LeftArrow
            if (key == 16 || key == 9 || key == 8 || key == 46 || key == 39 || key == 37) {
            }
            else {
                e.preventDefault();
            }
        }
    });

    //********************
    //Annan adress...
    //********************
    $("#UseAltAddress").click(function () {

        if ($("#UseAltAddress").is(':checked')) {
            $("#HideAltAdress").show('slow');
            RoundedCorners();
            $("#AgreementForm .fieldset").css('margin-bottom', '20px');
        }
        else {
            $("#HideAltAdress").hide('slow');
            RoundedCorners();
            $("#AgreementForm .fieldset").css('margin-bottom', '20px');
        }

    });

    $("#NoCivRegNumber").live("click", function () {
        SameRightColumn();
    });
    $("#CivRegNumber").live("click", function () {
        SameRightColumn();
    });
    $("#FirstName").live("click", function () {
        SameRightColumn();
    });
    $("#SecondName").live("click", function () {
        SameRightColumn();
    });
    $("#Address").live("click", function () {
        SameRightColumn();
    });
    $("#PostalCode").live("click", function () {
        SameRightColumn();
    });
    $("#Place").live("click", function () {
        SameRightColumn();
    });
    $("#PhoneDayTime").live("click", function () {
        SameRightColumn();
    });
    $("#PhoneEveningTime").live("click", function () {
        SameRightColumn();
    });
    $("#EMail").live("click", function () {
        SameRightColumn();
    });
    $("#UseAltAddress").live("click", function () {
        SameRightColumn();
    });
    $("#UseAltAddress").live("click", function () {
        SameRightColumn();
    });
    $("#AltAddress").live("click", function () {
        SameRightColumn();
    });
    $("#AltPostalCode").live("click", function () {
        SameRightColumn();
    });
    $("#AltPlace").live("click", function () {
        SameRightColumn();
    });

    var paymentField = $("#payment");
    $("input", paymentField).live("click", function () {
        SameRightColumn();
    });
    $("label", paymentField).live("click", function () {
        SameRightColumn();
    });

    $("#AreaID").live("click", function () {
        SameRightColumn();
    });
    $("#BuildingID").live("click", function () {
        SameRightColumn();
    });

    //********************************
    //STEG3:
    //********************************

    //********************
    //Jag godkänner...
    //********************
    $("#cbAgreeToTerms").click(function () {
        if ($("#cbAgreeToTerms").is(':checked')) {
            $("#Order").removeAttr('disabled');
        }
        else {
            $("#Order").attr('disabled', 'disabled');
        }
    });

    //********************************
    //HÖGERSPALTEN:
    //********************************

    //Float/Unfloat
    $('#doTheFloat').click(function () {
        if ($('#doTheFloat').hasClass("pinFloat")) {
            $('#doTheFloat').removeClass("pinFloat");
            $('#doTheFloat').addClass("unPinFloat");
            $('#RightArea').stopFloat();
        }
        else {
            $('#doTheFloat').removeClass("unPinFloat");
            $('#doTheFloat').addClass("pinFloat");
            $('#RightArea').restartFloat();
        }
    });

    //Månadskostnad-radio
    $("#TotalPriceInMonth").click(function () {
        $('#TotalPriceInYear').removeAttr('checked');
        SetTotalPrice();
        if ($("#TotalPrice").text() == "0 kr/år") {
            $("#TotalPrice").text("0 kr/mån");
        }

    });

    //Månadskostnad-label
    $("#monthLabel").click(function () {
        $("#TotalPriceInYear").attr('checked', false);
        $("#TotalPriceInMonth").attr('checked', true);
        SetTotalPrice();
        if ($("#TotalPrice").text() == "0 kr/år") {
            $("#TotalPrice").text("0 kr/mån");
        }
    });

    //Årskostnad-radio
    $("#TotalPriceInYear").click(function () {
        $('#TotalPriceInMonth').removeAttr('checked');
        SetTotalPrice();
        if ($("#TotalPrice").text() == "0 kr/mån") {
            $("#TotalPrice").text("0 kr/år");
        }
    });

    //Årskostnad-label
    $("#yearLabel").click(function () {
        $("#TotalPriceInMonth").attr('checked', false);
        $("#TotalPriceInYear").attr('checked', true);
        SetTotalPrice();
        if ($("#TotalPrice").text() == "0 kr/mån") {
            $("#TotalPrice").text("0 kr/år");
        }
    });

    $("#doTheFloat").addClass("pinFloat");
    $("#toggle1").addClass("Toggle-button");
    $("#toggle2").addClass("Toggle-button");
    $("#toggle3").addClass("Toggle-button");

    if (jQuery.browser.msie && jQuery.browser.version == 6) {
        $("#doTheFloat").css("top", "-25px");
        $("#toggle1").css("top", "-25px");
        $("#toggle2").css("top", "-25px");
        $("#toggle3").css("top", "-25px");
    }

    $(".Toggle-button").each(function () {
        if ($(this).next().hasClass("Closed")) {
            $(this).addClass("Toggle-button2");
        }
    });

    $("#toggle1").click(function () {
        if ($(this).next().hasClass("Open")) {
            $("#toggle1").removeClass("Toggle-button");
            $("#toggle1").addClass("Toggle-button2");
            $(this).next().removeClass("Open");
            $(this).next().addClass("Closed");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixOpen($(this));
            }
        }
        else if ($(this).next().hasClass("Closed")) {
            $("#toggle1").removeClass("Toggle-button2");
            $("#toggle1").addClass("Toggle-button");
            $(this).next().removeClass("Closed");
            $(this).next().addClass("Open");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixClosed($(this));
            }
        }
    });
    $("#toggle2").click(function () {
        if ($(this).next().hasClass("Open")) {
            $("#toggle2").removeClass("Toggle-button");
            $("#toggle2").addClass("Toggle-button2");
            $(this).next().removeClass("Open");
            $(this).next().addClass("Closed");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixOpen($(this));
            }
        }
        else if ($(this).next().hasClass("Closed")) {
            $("#toggle2").removeClass("Toggle-button2");
            $("#toggle2").addClass("Toggle-button");
            $(this).next().removeClass("Closed");
            $(this).next().addClass("Open");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixClosed($(this));
            }
        }
    });
    $("#toggle3").click(function () {
        if ($(this).next().hasClass("Open")) {
            $("#toggle3").removeClass("Toggle-button");
            $("#toggle3").addClass("Toggle-button2");
            $(this).next().removeClass("Open");
            $(this).next().addClass("Closed");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixOpen($(this));
            }
        }
        else if ($(this).next().hasClass("Closed")) {
            $("#toggle3").removeClass("Toggle-button2");
            $("#toggle3").addClass("Toggle-button");
            $(this).next().removeClass("Closed");
            $(this).next().addClass("Open");
            if (jQuery.browser.msie && jQuery.browser.version == 6) {
                TheArrowToggleIE6FixClosed($(this));
            }
        }
    });

    //------------------------------------------------------
    // slut EVENTS
    //------------------------------------------------------
    function TheArrowToggleIE6FixOpen(ctrl) {
        $(ctrl).parent().height("30px");
        $(ctrl).next().hide();
        if ($(ctrl).parent().hasClass("panel3")) {
            $(ctrl).parent().height("80px");
            $(ctrl).next().children().hide();
        }
    }
    function TheArrowToggleIE6FixClosed(ctrl) {
        $(ctrl).next().show();
        if ($(ctrl).parent().hasClass("panel1"))
            $(ctrl).parent().height("150px");
        else if ($(ctrl).parent().hasClass("panel2"))
            $(ctrl).parent().height("250px");
        else if ($(ctrl).parent().hasClass("panel3")) {
            $(ctrl).parent().height("180px");
            $(ctrl).next().children().show();
        }
    }

    //------------------------------------------------------
    // DIVERSE FUNKTIONER
    //------------------------------------------------------
    function onAnnualTextBoxChange(theBox) {
        if (LabelToBeClickableIndex > 1) {
            var box = theBox.val();
            if (HideHouseingForm == "True") {
                AnnualTextBoxLogic(box, true);
                if (box.length > 0) {
                    GetDatesAndPriceTypes();
                }
            }
            else {
                var InputTags = $("label", HouseingRadioButtonContainer);
                var FoundCheckedRadioButton = false;
                InputTags.each(function () {
                    if ($(this).hasClass("SelectedHousingRadioButton")) {
                        FoundCheckedRadioButton = true;
                        dd.eq(2).html($(this).html());
                    }
                });
                AnnualTextBoxLogic(box, FoundCheckedRadioButton);
            }

            if (box.length == 0) {
                GetDatesAndPriceTypes();
                ClearCheckboxes(2, 6, fieldsets);
                $("#PriceTypeName").html("Pris");
                $("#agreement fieldset").html('');
                $("#BindTime").html('');
                $("#BindLevel").html('');
                $("#PriceCapturerTime").html('');
                $("#green-choice fieldset").html('');
                $("#Date").attr('disabled', 'disabled');
                $("#AgreementFillOutForm").hide();
                $("#AnnualYearFee").next().text('-');
            }
        }
    }
    function GetDatesAndPriceTypes() {
        var isExistingCustomer;
        if (UseSpecialCustomerTypes == "True")
            isExistingCustomer = true;
        else {
            isExistingCustomer = $("input:checked", customerType).next().html() == "Redan kund";
        }
        GetPriceDates(companyId, isExistingCustomer);
        GetPriceTypes(companyId);

        if (COMES_FROM_SHOW_PRICES) {
            OpenUpSectionsAndSetChosenValues();
        }
    }

    function ReducedPriceAndElAreaChangeLogic() {
        if (LabelToBeClickableIndex > 1) {
            var container = $("#AgreementInfo dl:eq(1) dd");

            var priceTypeId = $("fieldset:eq(0) input:checked", agreement).val();
            if (priceTypeId != undefined) {
                var usesPeriod = UsesPeriod(priceTypeId);

                var startDate = $("select", date).val();
                if (startDate != undefined && startDate != "-1") {
                    var normalTax = true;
                    if ($("#ReducedPrice").is(':checked')) {
                        normalTax = false;
                    }
                    var environmentChoice = 0;
                    var isExistingCustomer;
                    if (UseSpecialCustomerTypes == "True")
                        isExistingCustomer = true;
                    else {
                        isExistingCustomer = $("input:checked", customerType).next().html() == "Redan kund";
                    }

                    var the_value = $("#BindTime input:radio:checked").val();
                    var the_index = 0;
                    if (the_value != undefined) {
                        var the_radio = $("#BindTime input:radio:checked");
                        var the_radios = $("#BindTime input:radio");
                        the_index = the_radios.index(the_radio);
                        //var the_label = the_radio[0].nextElementSibling.textContent;
                        //var the_label = the_radio[0].nextSibling.textContent;
                        var the_label;
                        if (jQuery.browser.msie && jQuery.browser.version <= 8) {
                            the_label = the_radio[0].nextSibling.nextSibling.innerText; //IE6, IE7, IE8
                        }
                        else {
                            the_label = the_radio[0].nextElementSibling.textContent; //FF, CHROME/SAFARI
                        }


                        GetPrice(companyId, normalTax, environmentChoice, priceTypeId, isExistingCustomer, startDate, usesPeriod, the_index, true);
                        var prices = selectedPrice;
                        SetPrice(prices.SupplementCharge, prices.PurchaseCost, prices.Certificate, prices.NetCost, prices.RowTotal, prices.RowTotal2000Kwh, prices.RowTotal5000Kwh, prices.RowTotal20000Kwh, prices.RowVat);

                        if (usesPeriod) {
                            if (the_value != undefined) {
                                var allRadios = $("#BindTime input:radio");
                                $.each(allRadios, function (i, n) {
                                    if (n.value == the_value)
                                        allRadios[i].checked = true;
                                });
                                dd.eq(1).html(the_label);
                            }
                        }

                        OpenNextButton();

                        //Om miljöval valt, ändra priset med miljövalet inkluderat!
                        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
                            var environmentChoice = container.eq(8).html();
                        }
                        else {
                            var environmentChoice = container.eq(3).html();
                        }

                        if (environmentChoice != "-") {
                            environmentChoice = parseFloat(environmentChoice.replace(" öre/kWh", "")).toFixed(2);
                            if (environmentChoice > 0)
                                EditPriceWithEnvironmentChoice(environmentChoice, true);
                        }
                    }
                    else {
                        operationMethodForAgreement();
                    }
                }
            }
        }
    }

    function SearchElAreas(q) {
        $.ajax({
            type: "POST",
            url: "/Utilities/Services/PriceGadgetWebService.asmx/SearchElAreas",
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{search:'" + q + "'}",
            success: function (response) {
                if (response.d.length > 0) {
                    $("#totalHits").html("Antal träffar: <b style=color:black>" + response.d.length + "</b>");
                    $("#searchResult").show();
                    var container = $("#searchBody");
                    container.html('');
                    $.each(response.d, function (i, n) {
                        container.append("<tr class=searchRow><td id=rowElAreaId>" + n.ElAreaId + "</td><td>" + n.ElAreaName + "</td><td id=rowElArea>" + n.ElArea + "</td></tr>");
                    });

                    //ZebraStripes **************
                    var oddColor = '#FFFFFF';
                    var evenColor = '#ECEDEC'; //'#e9f0da';

                    $("#tblSearchResult").children('tbody').children('tr.searchRow:odd').css({ 'background-color': oddColor, 'color': 'black' });
                    $("#tblSearchResult").children('tbody').children('tr.searchRow:even').css({ 'background-color': evenColor, 'color': 'black' });
                    //****************************

                    //ClickEvent for tableRow
                    $('.searchRow').each(function () {
                        var row = $(this);
                        var backColor = $(this).css('background-color');

                        //#818d66 #C3C4C6
                        row.hover(function () {
                            $(this).css({ 'background-color': '#EBF6D5', 'color': 'black' });
                        }, function () {
                            $(this).css({ 'background-color': backColor, 'color': 'black' });
                        });

                        row.click(function () {
                            var theElArea = $(this).find('#rowElArea').html();
                            var theElAreaId = $(this).find('#rowElAreaId').html();
                            var pattern = /[0-9]+/; //Leta efter siffror!
                            var matches = theElArea.match(pattern);

                            $('#elarea').val(matches);
                            $('#AreaID').val(theElAreaId); //Sätt vald rads id i "Områdeskod/Id" (steg 2)

                            //Stäng ner popupen
                            $('#swedEnergyPopUp').dialog('close');

                            ReducedPriceAndElAreaChangeLogic();
                        });
                    });
                }
                else {
                    $("#searchResult").hide();
                    $("#totalHits").html("Antal träffar: <b style=color:red>" + response.d.length + "</b>");
                }
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    }

    function GetPricesAndAddons(priceTypeId, priceTypeName) {
        PriceTypeGroupIsRorlig(priceTypeId);
        var usesPeriod = UsesPeriod(priceTypeId);

        var startDate = $("select", date).val();
        var normalTax = true;
        if ($("#ReducedPrice").is(':checked')) {
            normalTax = false;
        }
        var environmentChoice = 0;
        var thePriceIndex = 0;
        var isExistingCustomer;
        if (UseSpecialCustomerTypes == "True")
            isExistingCustomer = true;
        else {
            isExistingCustomer = $("input:checked", customerType).next().html() == "Redan kund";
        }

        if (startDate != undefined && startDate != "-1") {
            GetPrice(companyId, normalTax, environmentChoice, priceTypeId, isExistingCustomer, startDate, usesPeriod, thePriceIndex, false);
            GetAddons(companyId, priceTypeId, usesPeriod);

            $("h3:eq(1)", info).html(priceTypeName);
        }

        if (!usesPeriod) {
            SetVisibility(0, 7, fieldsets);
            $("#AgreementLength").hide();
            $("#AgreementLength").next().hide();
            $("#price-capturer input").removeAttr('disabled');
        }
    }

    function OpenUpSectionsAndSetChosenValues() {
        if (COMES_FROM_SHOW_PRICES) {
            if ($(".Annualtextbox").val().length > 0) {
                //SetVisibility(0, 7, fieldsets);
                //********************************************************
                //Rätt datum förvalt
                //********************************************************
                //$("select", date).val(ChosenStartDate);
                $("select", date).setDropDownValue(ChosenStartDate);
                $("#AgreementStart").next().text(ChosenStartDate);

                //********************************************************
                //Rätt pristyp (avtalsform) förvald
                //********************************************************
                var allRadios = $("#agreement input:radio");
                var theText;
                //Om de är borta, ladda pristyperna!
                if (allRadios.length == 0) {
                    GetPriceTypes(companyId);
                    allRadios = $("#agreement input:radio");
                }
                $.each(allRadios, function (i, n) {
                    if (n.value == ChosenPriceType) {
                        allRadios[i].checked = true;

                        if (jQuery.browser.msie && jQuery.browser.version <= 8) {
                            theText = allRadios[i].nextSibling.nextSibling.innerText; //IE6, IE7, IE8
                        }
                        //                            else if (jQuery.browser.msie && jQuery.browser.version == 8) {
                        //                                theText = allRadios[i].nextSibling.innerText + "2";
                        //                            }
                        else {
                            theText = allRadios[i].nextElementSibling.textContent; //FF, CHROME/SAFARI
                        }
                    }
                });

                //********************************************************
                //Öppna upp avtalsform
                //********************************************************
                var tempAvtalsStart = ChosenStartDate;
                if (tempAvtalsStart == undefined || tempAvtalsStart == null || tempAvtalsStart == "")
                    tempAvtalsStart = "-";
                dd.eq(0).html(tempAvtalsStart);
                SetVisibility(0, 4, fieldsets);
                $("#AgreementFillOutForm").hide();
                $("#BindTime").html('');

                //********************************************************
                //Fixa med priser och tillägg och perioder...
                //********************************************************
                GetPricesAndAddons(ChosenPriceType, theText);

                //********************************************************
                //Välj rätt avtalslängd och sätt priserna
                //********************************************************
                var usesPeriod = UsesPeriod(ChosenPriceType);
                var theLabel;
                var the_index = 0;
                if (usesPeriod) {
                    $("#AgreementLength").show();
                    $("#AgreementLength").next().show();
                    var allRadios2 = $("#BindTime input:radio");
                    $.each(allRadios2, function (i, n) {
                        if (n.value == ChosenPeriod) {
                            allRadios2[i].checked = true;
                            if (jQuery.browser.msie && jQuery.browser.version <= 8) {
                                theLabel = allRadios2[i].nextSibling.nextSibling.innerText;
                            }
                            //                                else if (jQuery.browser.msie && jQuery.browser.version == 8) {
                            //                                    theLabel = allRadios2[i].nextSibling.innerText;
                            //                                }
                            else {
                                theLabel = allRadios2[i].nextElementSibling.textContent;
                            }
                        }
                    });
                    //Ta reda på prisindex
                    var the_radio = $("#BindTime input:radio:checked");
                    var the_radios = $("#BindTime input:radio");
                    the_index = the_radios.index(the_radio);

                    $("#AgreementStart").next().text(ChosenStartDate);
                    $("#AgreementLength").next().text(theLabel);
                    var the_housing_value = $("#HousingRadioButtonContainer input:radio:checked").next().text();
                    $("#LivingForm").next().text(the_housing_value);
                }
                else {
                    $("#AgreementLength").hide();
                    $("#AgreementLength").next().hide();
                }

                //Sätt priserna
                if (selectedPrice != undefined) {
                    var prices = selectedPrices[the_index];

                    SetPrice(prices.SupplementCharge, prices.PurchaseCost, prices.Certificate, prices.NetCost, prices.RowTotal, prices.RowTotal2000Kwh, prices.RowTotal5000Kwh, prices.RowTotal20000Kwh, prices.RowVat);
                }
                //********************************************************

                //********************************************************
                //Öppna upp miljöval, enabla Nästa-knappen
                //********************************************************
                SetVisibility(0, 7, fieldsets);
                $("#green-choice input").removeAttr('disabled');
                $('#btnGotoStep2').removeAttr("disabled");
            }
        }
    }

    function AnnualTextBoxLogic(theValue, foundCheckedRadioButton) {
        if (theValue.length > 0 && foundCheckedRadioButton) {
            var startDate = $("select", date).val();
            if (startDate != undefined && startDate != "-1") {
                SetVisibility(0, 7, fieldsets);
            }
            else {
                SetVisibility(0, 3, fieldsets);
            }

            SetTotalPrice();

            if (COMES_FROM_SHOW_PRICES) {
                OpenUpSectionsAndSetChosenValues();
            }

        }
        else {
            SetVisibility(0, 2, fieldsets);
            ClearDeal();
            ClearPrices();
        }
    }

    //Töm miljöval
    function EmptyEnvironmentChoices() {
        $("fieldset:eq(0) input", greenChoice).attr("checked", false);
        var container = $("#AgreementInfo dl:eq(1) dd");
        $(".Miljo").hide();
        $(".Miljo").next().hide();
        if (DoSeparatePrices == "True" || DoSeparatePrices == "true")
            container.eq(8).html("0");
        else
            container.eq(3).html("0");
        GreenChoiceVar = 0;

        var the_radios = $("fieldset:eq(0) input", greenChoice);
        the_radios[the_radios.length - 1].checked = true;
    }

    //Visa popup om årsavgift är större än "maxgräns"
    function preventFurtherChangesIfAnnualToHigh(currentValue) {
        if (currentValue > parseInt(MaxValueForAnnual)) {
            openPopUpMaxAnnual();
            SetVisibility(0, 2, fieldsets);
            return true;
        }
        return false;
    }

    //Ändra pris när man väljer miljöval
    function EditPriceWithEnvironmentChoice(theValue, forceChange) {
        var changesMade = false;

        //----------------------
        var mVat = parseFloat(theVat.replace(",", "."), 10).toFixed(2); //Moms
        var calcVat = ((parseFloat(mVat) + 100) / 100);
        var theRealValue = ((parseFloat(theValue) * calcVat));

        var theVatOnEnvironment = (theRealValue - parseFloat(theValue)).toFixed(2);
        //----------------------

        var container = $("#AgreementInfo dl:eq(1) dd");
        var compare = $("#AgreementInfo dl:eq(2) dd");

        $(".Miljo").show();
        $(".Miljo").next().show();

        var apartment = parseFloat(compare.eq(0).html());
        var house = parseFloat(compare.eq(1).html());
        var electric = parseFloat(compare.eq(2).html());

        var NumericValue1 = parseFloat($('#hiddenTotalPrice').val());
        var theRowVat = parseFloat($('#hiddenRowVat').val());

        theRowVat = (theRowVat + parseFloat(theVatOnEnvironment)).toFixed(2);

        var NumericValue2 = parseFloat(theRealValue);
        var NumericValue3, apVal, hoVal, elVal;
        if (GreenChoiceVar == 0) {
            NumericValue3 = NumericValue1 + NumericValue2;
            apVal = apartment + NumericValue2;
            hoVal = house + NumericValue2;
            elVal = electric + NumericValue2;

            GreenChoiceVar = NumericValue2;
            changesMade = true;
        }
        else {
            if (NumericValue2 != GreenChoiceVar) {
                NumericValue3 = NumericValue1 + NumericValue2;
                apVal = apartment + NumericValue2 - GreenChoiceVar;
                hoVal = house + NumericValue2 - GreenChoiceVar;
                elVal = electric + NumericValue2 - GreenChoiceVar;

                GreenChoiceVar = NumericValue2;
                changesMade = true;
            }
            if (forceChange) {
                NumericValue3 = NumericValue1 + NumericValue2;
                apVal = apartment + NumericValue2 - GreenChoiceVar;
                hoVal = house + NumericValue2 - GreenChoiceVar;
                elVal = electric + NumericValue2 - GreenChoiceVar;

                GreenChoiceVar = NumericValue2;
                changesMade = true;
            }
        }

        if (changesMade) {
            if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
                container.eq(10).html(NumericValue3.toFixed(2) + " öre/kWh"); //Totalt
                container.eq(8).html(theValue + " öre/kWh"); //Miljöval

                container.eq(9).html(theRowVat + " öre/kWh"); //Moms
            }
            else {
                container.eq(5).html(NumericValue3.toFixed(2) + " öre/kWh"); //Totalt
                container.eq(3).html(theValue + " öre/kWh"); //Miljöval

                container.eq(4).html(theRowVat + " öre/kWh"); //Moms
            }
            compare.eq(0).html(apVal.toFixed(2));
            compare.eq(1).html(hoVal.toFixed(2));
            compare.eq(2).html(elVal.toFixed(2));

            SetTotalPrice();
        }

        if (theValue == 0)
            EmptyEnvironmentChoices();

    }

    function SameRightColumn() {
        $("#AgreementStart").next().text($("#Avtalsstart").text());
        $("#AgreementLength").next().text($("#Avtalslangd").text());
        $("#LivingForm").next().text($("#Boende").text());

        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
            //Separated
            $("#TotalPriceSep").next().text($("#totalPris").text());
            $("#EnergyPriceSep").next().text($("#Energipris").text());
            $("#CertSep").next().text($("#ElCertification").text());
            $("#PurchaseCostSep").next().text($("#Inkopskostnad").text());
            $("#SuppChargeSep").next().text($("#paslag").text());
        }
        else {
            //Not separated
            $("#EnergyPrice").next().text($("#Energipris").text());
            $(".SuppCharge").next().text($("#paslag").text());
        }

        $("#EnergyTax").next().text($("#Energiskatt").text());
        $(".Miljo").next().text($("#EnviromentChoice").text());
        $("#Moms").next().text($("#Moms1").text());
        $("#TotPrice").next().text($("#Totalt").text());
        $("#AnnualYearFee").next().text($("#Arligt").text());
    }

    function operationMethodForAgreement() {
        //$(this).prev().attr("checked", true);
        SetVisibility(0, 4, fieldsets);

        //CLEAR AgreementTime
        var container = $("#AgreementInfo dl:eq(0) dd");
        container.eq(1).html("-");

        ClearPrices();
        ClearCheckboxes(4, 6, fieldsets);

        var priceTypeId = $("fieldset:eq(0) input:checked", agreement).val();
        PriceTypeGroupIsRorlig(priceTypeId);
        var usesPeriod = UsesPeriod(priceTypeId);


        var startDate = $("select", date).val();
        var normalTax = true;
        if ($("#ReducedPrice").is(':checked')) {
            normalTax = false;
        }
        var environmentChoice = 0;
        var thePriceIndex = 0;
        var isExistingCustomer;
        if (UseSpecialCustomerTypes == "True")
            isExistingCustomer = true;
        else {
            isExistingCustomer = $("input:checked", customerType).next().html() == "Redan kund";
        }

        if (startDate != undefined && startDate != "-1") {
            GetPrice(companyId, normalTax, environmentChoice, priceTypeId, isExistingCustomer, startDate, usesPeriod, thePriceIndex, false);
            GetAddons(companyId, priceTypeId, usesPeriod);

            //  $("h3:eq(1)", info).html($(this).html());
        }

        if (!usesPeriod) {
            SetVisibility(0, 7, fieldsets);
            $("#price-capturer input").removeAttr('disabled');
        }
    }
    //------------------------------------------------------
    // slut DIVERSE FUNKTIONER
    //------------------------------------------------------


    if (jQuery.browser.msie && jQuery.browser.version == 6 && MarketPlaceName == "Södra el") {
        //  $("#Housing1").css("margin-left", "0px");
        $("#SodraWithHousing").css("margin-left", "0px");
        $("#Housing1").css("width", "250px");
        //$("#BindTime").css("margin-left", "10px");
        $("#AgreementFillOutForm").css("padding-left", "10px");
        // alert($("#BindTime").html());
        // $("#step1 .fieldset:first").height("300px");
        // $("#step1 .Inner").height("300px");
        //RoundedCorners();
        $("#step1 .fieldset:first").height("100px");
        $("#step1 .Inner:first").height("100px");
        $("#SodraHeightInner").height("600px");
        $("#SodraHeightOuter").height("600px");
    }


    if (HidePriceCatcher == "True")
        $("#priceCapturerDiv").css("display", "none");


});
//slut "document.ready"


//------------------------------------------------------
//FUNKTIONER
//------------------------------------------------------
function SetTotalPrice() {
    var container = $("#AgreementInfo dl:eq(1) dd");
    var totalPrice;
    if (DoSeparatePrices == "True" || DoSeparatePrices == "true")
        totalPrice = container.eq(10).html();
    else
        totalPrice = container.eq(5).html();

    if (totalPrice != "-") {
        var annualBox = $('.Annualtextbox').val();
        var currentTotalVal;
        var currentAnnualFee;
        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
            currentTotalVal = container.eq(10).html();
            currentAnnualFee = container.eq(11).html();
        }
        else {
            currentTotalVal = container.eq(5).html();
            currentAnnualFee = container.eq(6).html();
        }

        if (currentTotalVal != "") {
            var annualFeeToUse = parseFloat(currentAnnualFee.replace(" öre/kWh", ""));
            var NumericValue1 = parseFloat(currentTotalVal.replace(" öre/kWh", ""));
            var NumericValue2 = parseFloat(annualBox);
            var NumericValue3 = NumericValue1 * NumericValue2;
            NumericValue3 = NumericValue3 / 100;

            var NumericValue4 = (NumericValue3 + annualFeeToUse);

            if ($('#TotalPriceInMonth').attr('checked') == true) {
                NumericValue4 = NumericValue4 / 12;
                $("#TotalPrice").html(NumericValue4.toFixed(0) + " kr/mån");
            }
            else {
                $("#TotalPrice").html(NumericValue4.toFixed(0) + " kr/år");
            }
        }
    }
}

function getCurrentPriceTypeId() {
    var step1 = $("#step1");
    var agreement = $("#agreement", step1);
    var priceTypeId = $("fieldset:eq(0) input:checked", agreement).val();

    return priceTypeId;
}

function SetPrice(suppCharge, purchaseCost, cert, net, total, apartment, house, electric, rowVat) {
    var container = $("#AgreementInfo dl:eq(1) dd");

    var priceTypeId = getCurrentPriceTypeId();

    if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
        //TOTALT ELPRIS
        var elPrice = parseFloat(suppCharge) + parseFloat(purchaseCost) + parseFloat(cert) + parseFloat(net);
        if (net != "-")
            container.eq(0).html(elPrice.toFixed(2) + " öre/kWh");
        else
            container.eq(0).html("-");

        //ELPRIS
        if (net != "-" && net != "0" && net != "0.0" && net != "0.00")
            container.eq(1).html(net + " öre/kWh");
        else
            container.eq(1).html(net);

        //ASTERISK-ELPRIS
        if (DoShowAsterisk() && (priceTypeId == NearPriceId || priceTypeId == MixedPriceId)) {
            if (priceTypeId == NearPriceId) {
                $("#EnergyPriceSep").html("Elpris <span class=asteriskColor>*</span>");
            }
            if (priceTypeId == MixedPriceId) {
                $("#EnergyPriceSep").html("Elpris <span class=asteriskColor>**</span>");
            }
        }
        else
            $("#EnergyPriceSep").html("Elpris");
        //--------------------

        //AVGIFT FÖR ELCERT
        if (cert != "-" && cert != "0" && cert != "0.0" && cert != "0.00")
            container.eq(2).html(cert + " öre/kWh");
        else {
            if (cert == "0" || cert == "0.0" || cert == "0.00")
                container.eq(2).html(" ingår i elpriset");
            else
                container.eq(2).html(cert);
        }

        //INKÖPSKOSTNAD
        if (purchaseCost != "-" && purchaseCost != "0" && purchaseCost != "0.0" && purchaseCost != "0.00") {
            container.eq(3).html(purchaseCost + " öre/kWh");
            $("#PurchaseCostSep").show();
            $("#PurchaseCostSep").next().show();
        }
        else {
            container.eq(3).html(purchaseCost);
            $("#PurchaseCostSep").hide();
            $("#PurchaseCostSep").next().hide();
            
        }
        //PÅSLAG
        if (suppCharge != "-" && suppCharge != "0" && suppCharge != "0.0" && suppCharge != "0.00") {
            container.eq(4).html(suppCharge + " öre/kWh");

            //ASTERISK-PÅSLAG
            if (DoShowAsterisk() && priceTypeId == NearPriceId) {
                $("#SuppChargeSep").html("Påslag <span class=asteriskColor>*</span>");
            }
            else
                $("#SuppChargeSep").html("Påslag");
            
            $("#SuppChargeSep").show();
            $("#SuppChargeSep").next().show();
        }
        else {
            container.eq(4).html(suppCharge);
            $("#SuppChargeSep").hide();
            $("#SuppChargeSep").next().hide();
        }

        //MOMS
        if (rowVat != "-") {
            container.eq(9).html(rowVat + " öre/kWh");
            $('#hiddenRowVat').val(rowVat);
        }
        else {
            container.eq(9).html(rowVat);
            $('#hiddenRowVat').val("");
        }
    }
    else {
        var elPrice = (parseFloat(net) + parseFloat(cert) + parseFloat(purchaseCost)).toFixed(2);
        if (net != "-")
            container.eq(0).html(elPrice + " öre/kWh");
        else
            container.eq(0).html(net);

        //ASTERISK-ELPRIS
        if (DoShowAsterisk() && (priceTypeId == NearPriceId || priceTypeId == MixedPriceId)) {
            if (priceTypeId == NearPriceId) {
                $("#EnergyPrice").html("Elpris <span class=asteriskColor>*</span>");
            }
            if (priceTypeId == MixedPriceId) {
                $("#EnergyPrice").html("Elpris <span class=asteriskColor>**</span>");
            }
        }
        else
            $("#EnergyPrice").html("Elpris");
        //--------------------

        if (suppCharge != "-" && suppCharge != "0" && suppCharge != "0.0" && suppCharge != "0.00") {
            container.eq(1).html(suppCharge + " öre/kWh");

            //ASTERISK-PÅSLAG
            if (DoShowAsterisk() && priceTypeId == NearPriceId) {
                $(".SuppCharge").html("Påslag <span class=asteriskColor>*</span>");
            }
            else
                $(".SuppCharge").html("Påslag");
            
            $(".SuppCharge").show();
            $(".SuppCharge").next().show();
        }
        else {
            $(".SuppCharge").hide();
            $(".SuppCharge").next().hide();
        }

        if (rowVat != "-") {
            container.eq(4).html(rowVat + " öre/kWh");
            $('#hiddenRowVat').val(rowVat);
        }
        else {
            container.eq(4).html(rowVat);
            $('#hiddenRowVat').val("");
        }
    }

    if (total != "-") {
        var currentAnnualFee;
        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
            currentAnnualFee = container.eq(11).html();
        }
        else {
            currentAnnualFee = container.eq(6).html();
        }

        if ($(".Annualtextbox").val().length > 0) {
            var annualFeeToUse = parseFloat(currentAnnualFee.replace(" öre/kWh", ""));
            var NumericValue2 = parseFloat($(".Annualtextbox").val().toString().replace(" öre/kWh", ""));
            var NumericValue1 = parseFloat(total.toString().replace(" öre/kWh", ""));
            var NumericValue3 = NumericValue2 * NumericValue1;
            NumericValue3 = NumericValue3 / 100;

            var NumericValue4 = (NumericValue3 + annualFeeToUse);


            if ($('#TotalPriceInMonth').attr('checked') == true) {
                NumericValue4 = NumericValue4 / 12;
                $("#TotalPrice").html(NumericValue4.toFixed(0) + " kr/mån");
            }
            else {
                $("#TotalPrice").html(NumericValue4.toFixed(0) + " kr/år");
            }

            $("#TotalPrice").css("padding-top", "15px");
        }
        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
            container.eq(10).html(total + " öre/kWh");
        }
        else {
            container.eq(5).html(total + " öre/kWh");
        }
        $('#hiddenTotalPrice').val(total);
    }
    else {
        if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
            container.eq(10).html(total);
        }
        else {
            container.eq(5).html(total);
        }
        $("#TotalPrice").html("0 kr/år");
        $('#hiddenTotalPrice').val("");
        $("#TotalPriceInMonth").attr("checked", false);
        $("#TotalPriceInYear").attr("checked", false);
        $("#TotalPriceInYear").attr("checked", true);
    }


    var compare = $("#AgreementInfo dl:eq(2) dd");
    compare.eq(0).html(apartment);
    compare.eq(1).html(house);
    compare.eq(2).html(electric);
}

function ClearPrices() {
    SetPrice("-", "-", "-", "-", "-", "-", "-", "-", "-");
    var container = $("#AgreementInfo dl:eq(1) dd");
    if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
        container.eq(7).html("-"); //ENERGISKATT
        container.eq(9).html("-"); //MOMS
        container.eq(10).html("-"); //TOTALT
    }
    else {
        container.eq(2).html("-"); //ENERGISKATT
        container.eq(3).html("-"); //MOMS
        container.eq(4).html("-"); //TOTALT
    }
}

function ClearDeal() {
    var container = $("#AgreementInfo dl:eq(0) dd");
    container.eq(0).html("-");
    container.eq(1).html("-");
}

function ClearInfo() {
    SetPrice("-", "-", "-", "-", "-", "-", "-", "-", "-");
    var container1 = $("#AgreementInfo dl:eq(0) dd");
    container1.eq(0).html("-");
    container1.eq(1).html("-");
    container1.eq(2).html("-");
    var container = $("#AgreementInfo dl:eq(1) dd");
    if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
        container.eq(7).html("-"); //ENERGISKATT
        container.eq(9).html("-"); //MOMS
        container.eq(10).html("-"); //TOTALT
    }
    else {
        container.eq(2).html("-"); //ENERGISKATT
        container.eq(3).html("-"); //MOMS
        container.eq(4).html("-"); //TOTALT
    }
}

function ClearHousing(item) {
    ClearCheckboxes(1, 2, item);
    $("#AgreementInfo dl:eq(0) dd:eq(2)").html('-');
}

function CheckIfDateIsSelected() {
    var date = $("#DateChoice", $("#step1"));
    var startDate = $("select", date).val();

    if (startDate == undefined || startDate == "-1") {
        $('#btnGotoStep2').attr("disabled", true);
    }
}

function SetVisibility(from, to, item) {


    item.addClass("Opacity3CSS");

    item.slice(from, to).removeClass("Opacity3CSS");
    item.slice(from, to).removeClass("Opacity3CSSIE8");
    //css('opacity', '1');

    var tmp = item.slice(from, to);
    tmp.find("input").attr("disabled", false);
    //tmp.find("input").attr('style',"");

    tmp.find("select").attr("disabled", false);
    if (jQuery.browser.msie) {
        tmp.find("#Housing1 span").css('color', 'black');
        tmp.find("legend span").css('color', 'black');
        //tmp.find("input").css('opacity', '1');
        tmp.find("legend span").css('color', 'black')
        tmp.find("label").css('color', 'black');
        tmp.find(".Inner").corner("round 5px").parent().css('padding', '1px').corner("round 6px");
        tmp.find(".Cloud").corner("round 2px").parent().css('padding', '1px').corner("round 5px");

        if (USES_EL_AREA)
            tmp.find("#elAreas").css('color', 'black');
    }

    if (to <= 3) {
        $('#btnGotoStep2').attr("disabled", true);
        $('#step1Done').hide();
    }
    else
        CheckIfDateIsSelected();

    if (to == 3) {
        ATagclickable = true;
        $(".fieldset a").css("cursor", "pointer");
    }
    LabelToBeClickableIndex = to;
}

function ClearCheckboxes(from, to, item) {
    item.slice(from, to).find("input").attr('checked', false);
    item.slice(from, to).find("input").attr("disabled", false);

}

function Next() {
    $("#Avtalsstart").text($("#AgreementStart").next().text());
    $("#Avtalslangd").text($("#AgreementLength").next().text());
    $("#Boende").text($("#LivingForm").next().text());

    if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
        $("#totalPris").text($("#TotalPriceSep").next().text());
        $("#Energipris").text($("#EnergyPriceSep").next().text());
        $("#ElCertification").text($("#CertSep").next().text());
        $("#Inkopskostnad").text($("#PurchaseCostSep").next().text());
        $("#paslag").text($("#SuppChargeSep").next().text());
    }
    else {
        $("#Energipris").text($("#EnergyPrice").next().text());
        $("#paslag").text($(".SuppCharge").next().text());
    }

    $("#Energiskatt").text($("#EnergyTax").next().text());
    $("#EnviromentChoice").text($(".Miljo").next().text());
    $("#Moms1").text($("#Moms").next().text());
    $("#Totalt").text($("#TotPrice").next().text());
    $("#Arligt").text($("#AnnualYearFee").next().text());

    $("#step1").hide();
    $('#step1Done').show();
    $("#step2").show();
    //if ($("#aspnetForm").valid())
    // $("#Steps").tabs().next();
    var currentTab = $(".active");
    $("#Steps").addClass("Active1");
    $("#Steps").removeClass("Active0");
    currentTab.removeClass("active");
    currentTab.next().addClass("active");

    $(".TopBanner1").hide();
    $(".TopBanner2").show()
    $(".TopBanner3").hide();

    //Scrolla upp till toppen
    $('html, body').animate({ scrollTop: 0 }, 'slow');
}

function Next4() {
    Order();
}

function ToStep3() {
    CheckIfPersonummerIsOk($("#CivRegNumber").val());
}

function BackToStep2() {
    $("#step1").hide();
    $("#step2").show();
    $("#step3").hide();
    $("#Steps").addClass("Active1");
    $("#Steps").removeClass("Active2");
    var currentTab = $(".active");
    currentTab.removeClass("active");
    currentTab.prev().addClass("active");
    $(".TopBanner1").hide();
    $(".TopBanner2").show()
    $(".TopBanner3").hide();
}
//Order();
function Order() {
    var priceTypeId = getCurrentPriceTypeId();
   
    var fromAddress = MarketPlaceSignature;
    var toAdress = MailToMarketResponsible;
    var fromName = MarketPlaceName;
    var toName = $(".FirstNameInfo").text() + " " + $(".LastNameInfo").text();

    //-------------------------------------------------------------------
    //TEXTBODY_1
    //-------------------------------------------------------------------
    $("#step3").append("<div style='display:none' id='HtmlToSendInMail'>" + $("#OrderInfo").html() + "</div>");

    $("#HtmlToSendInMail dl dt").each(function (intIndex) {
        if ($(this).is(":contains('Årskostnad')")) {
            $(this).text("");
            $(this).next().text("");
        }
        else {
            $(this).append(" " + $(this).next().text());
            $(this).next().text(" ");
        }
    });

    var nextText = $("#HtmlToSendInMail #cbAgreeToTerms").next().text();
    if ($("#cbAgreeToTerms").is(':checked')) {
        //$("#HtmlToSendInMail #cbAgreeToTerms").next().text("[x] " + nextText);
        $("#HtmlToSendInMail #cbAgreeToTerms").html("");
        $("#HtmlToSendInMail #cbAgreeToTerms").replaceWith("<div>[x] " + nextText + "</div>");
        $("#HtmlToSendInMail #lblForATT").remove();
    }
    else {
        //$("#HtmlToSendInMail #cbAgreeToTerms").next().text("[]" + nextText);
        $("#HtmlToSendInMail #cbAgreeToTerms").html("");
        $("#HtmlToSendInMail #cbAgreeToTerms").replaceWith("<div>[] " + nextText + "</div>");
        $("#HtmlToSendInMail #lblForATT").remove();
    }

    $("#HtmlToSendInMail #Order").remove();
    $("#Order").remove();

    $("#HtmlToSendInMail #Step3GoBack").remove();
    $("#Step3GoBack").remove();

    if (UseSpecialCustomerTypes == "True") {
        $("#HtmlToSendInMail .LivingForm").prev().remove();
        $("#HtmlToSendInMail .LivingForm").remove();

        $("#HtmlToSendInMail #BindLevelInfo").prev().remove();
        $("#HtmlToSendInMail #BindLevelInfo").remove();


        $("#HtmlToSendInMail #BindTimeInfo").prev().remove();
        $("#HtmlToSendInMail #BindTimeInfo").remove();


        $("#HtmlToSendInMail .EnviromentChoice").prev().remove();
        $("#HtmlToSendInMail .EnviromentChoice").remove();


        $("#HtmlToSendInMail #EnvironmentConf").prev().remove();
        $("#HtmlToSendInMail #EnvironmentConf").remove();

        $("#HtmlToSendInMail .ClubInfo").prev().remove();
        $("#HtmlToSendInMail .ClubInfo").remove();

        $("#HtmlToSendInMail #EnvironmentConf").prev().remove();
        $("#HtmlToSendInMail #EnvironmentConf").remove();


        $("#HtmlToSendInMail .MedlemsInfo").prev().remove();
        $("#HtmlToSendInMail .MedlemsInfo").remove();

    }
    var textBody = $("#HtmlToSendInMail").html();
    //textBody = textBody.replace("Beställ", "");
    //textBody = textBody.replace("Tillbaka", "");
    //-------------------------------------------------------------------

    //-------------------------------------------------------------------
    //TEXTBODY_2
    //-------------------------------------------------------------------

    if (DoShowAsterisk() && (priceTypeId == NearPriceId || priceTypeId == MixedPriceId)) {
        var container = $("#AgreementInfo dl:eq(1) dd");
        //----------------------------------------
        //Fixa till mailet för Närpris ----
        //----------------------------------------
        if (priceTypeId == NearPriceId) {
            if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
                $("#AgreementInfo #EnergyPriceSep").html("Elpris");
                $("#AgreementInfo #SuppChargeSep").html("Påslag");

                container.eq(1).append(" (Grundpris)"); //Lägg till text till elpriset
                container.eq(4).append(" (Senast kända månadspris)"); //Lägg till text till påslaget
            }
            else {
                $("#AgreementInfo #EnergyPrice").html("Elpris");
                $("#AgreementInfo .SuppCharge").html("Påslag");

                container.eq(0).append(" (Grundpris)");
                container.eq(1).append(" (Senast kända månadspris)");
            }
            
            $("#AgreementInfo").append("<div style='display:none' id='HtmlToSendInMail1'>" + $("#AgreementInfo").html() + "</div>");
        }
        //----------------------------------------
        //Fixa till mailet för Mixat pris -----
        //----------------------------------------
        if (priceTypeId == MixedPriceId) {
            if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
                $("#AgreementInfo #EnergyPriceSep").html("Elpris");
                container.eq(1).append(" (Fast elpris + senaste månadens Rörligt m. bytesrätt)/2"); //Lägg till text till elpriset
            }
            else {
                $("#AgreementInfo #EnergyPrice").html("Elpris");
                container.eq(0).append(" (Fast elpris + senaste månadens Rörligt m. bytesrätt)/2"); //Lägg till text till elpriset
            }
            $("#AgreementInfo").append("<div style='display:none' id='HtmlToSendInMail1'>" + $("#AgreementInfo").html() + "</div>");
        }
        //----------------------------------------
    }
    else
        $("#AgreementInfo").append("<div style='display:none' id='HtmlToSendInMail1'>" + $("#AgreementInfo").html() + "</div>");
    
    $("#HtmlToSendInMail1 .hd").html('');
    $("#HtmlToSendInMail1 .panel0").html('');
    //-------------------------------------------
    //Ta bort års/månadskostnad
    //-------------------------------------------
    $("#HtmlToSendInMail1 dl dt").each(function (intIndex) {
        $(this).append(" " + $(this).next().text());
        $(this).next().text(" ");
    });
    if (UseSpecialCustomerTypes == "True") {
        $("#HtmlToSendInMail1 #LivingForm").prev().remove();
        $("#HtmlToSendInMail1 #LivingForm").remove();


        $("#HtmlToSendInMail1 .Miljo").prev().remove();
        $("#HtmlToSendInMail1 .Miljo").remove();
        $("#Html1").remove();

    }
    var textBody2 = $("#HtmlToSendInMail1").html();
    //-------------------------------------------------------------------

    //*************************
    //IE6-TEXTBODY_1
    //*************************
    $("#HtmlToSendInMail dl dt").each(function (intIndex) {
        $(this).append(" " + $(this).next().text());
        $(this).next().text("<br>");
    });
    $("#HtmlToSendInMail h2").each(function (intIndex) {
        $(this).text($(this).text() + "<br>");
    });
    $("#HtmlToSendInMail li").each(function (intIndex) {
        $(this).text($(this).text() + "<p>");
    });
    var textBody1_ToIE6 = $("#HtmlToSendInMail").text();
    textBody1_ToIE6 = textBody1_ToIE6.replace("Beställ", "");
    textBody1_ToIE6 = textBody1_ToIE6.replace("Tillbaka", "");
    //*************************

    //*************************
    //IE6-TEXTBODY_2
    //*************************
    $("#HtmlToSendInMail1 dl dt").each(function (intIndex) {
        $(this).append(" " + $(this).next().text());
        $(this).next().text("<br>");
    });
    $("#HtmlToSendInMail1 h2").each(function (intIndex) {
        $(this).text("<p>" + $(this).text());
    });
    var textBody2_ToIE6 = $("#HtmlToSendInMail1").text();
    textBody2_ToIE6 = textBody2_ToIE6.replace("Månadskostnad", "");
    textBody2_ToIE6 = textBody2_ToIE6.replace("Årskostnad", "");
    textBody2_ToIE6 = textBody2_ToIE6.replace("Avtal", "<br>");
    //*************************

    var market = MarketPlaceId;
    var orderMail = $(".EMailInfo").text();

    var enviromentMail = false;
    if ($("#GoodForEnviromentMail").is(':checked')) {
        enviromentMail = true;
    }

    var autoGiroChosen = false
    if ($("#payment input:checked").val() == "Autogiro")
        autoGiroChosen = true;

    if (jQuery.browser.msie && jQuery.browser.version == 6) {
        SendMail(NoReplyMail, toAdress, fromName, toName, MarketPlaceName, textBody1_ToIE6, textBody2_ToIE6, market, "", orderMail, enviromentMail, autoGiroChosen);
    }
    else {
        SendMail(NoReplyMail, toAdress, fromName, toName, MarketPlaceName, textBody, textBody2, market, "", orderMail, enviromentMail, autoGiroChosen);
    }

    $("#step3 dl dt").each(function (intIndex) {
        $(this).text().replace(" " + $(this).next().text(), "");
    });
}

function ToStep1() {
    //if ($("#aspnetForm").valid())
    $("#step1").show();
    $("#step2").hide();
    $("#step3").hide();

    $("#Steps").addClass("Active0");
    $("#Steps").removeClass("Active1");

    var currentTab = $(".active");
    currentTab.removeClass("active");
    currentTab.prev().addClass("active");

    $(".TopBanner1").show();
    $(".TopBanner2").hide()
    $(".TopBanner3").hide();
}

function GetPriceDates(companyId, isExistingCustomer) {

    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetStartDates",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "', isExistingCustomer:'" + isExistingCustomer + "'}",
        success: function (response) {
            var container = $("#DateChoice select");
            container.html('');
            container.html('<option value="-1">Välj datum</option>');
            $.each(response.d, function (i, n) {
                container.append("<option value=\"" + n.Id + "\">" + n.Date + "</option>");
            });
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function GetPriceTypes(companyId) {
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetAgreementTypes",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "'}",
        success: function (response) {
            var container = $("#agreement fieldset:eq(0)");
            container.html('');
            $.each(response.d, function (i, n) {
                container.append("<input type=\"radio\" value=\"" + n.Id + "\" name=\"deal\" disabled=\"\" />&nbsp;<label>" + n.Name + "</label><br/>");
            });
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function GetPriceCatchers(companyId, priceTypeId, calledFromReduceClick) {
    //PriceCatcherPrices
    var doDisable = !calledFromReduceClick;
    var disableString;
    if (doDisable)
        disableString = " disabled=\"\"";
    else
        disableString = "";

    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetAllPriceCatcherItems",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "', priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            var container = $("#price-capturer fieldset:eq(0)");
            container.show();
            if (response.d.length == 0) {
                container.html('');
                $("#priceCapturerDiv").hide();
            }


            $.each(response.d, function (i, n) {
                if (i == 0)
                    container.html('<legend>Bindningsnivå</legend>');
                container.append("<input type=\"radio\" value=\"" + n.PricePerKwh + "\" name=\"bindlevel\" " + disableString + " />&nbsp;<label>" + n.PricePerKwh + " öre</label> ");
            });
        },
        error: function (response) {
            alert(response.responseText);
        }
    });

    //PriceCatcherTimes
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetAllPriceCatcherTimes",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "', priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            var container2 = $("#price-capturer fieldset:eq(1)");
            container2.show();
            if (response.d.length == 0)
                container2.html('');

            $.each(response.d, function (i, n) {
                if (i == 0)
                    container2.html('<legend>Bindningstid</legend>');
                container2.append("<input type=\"radio\" value=\"" + n.PriceCatcherTime + "\" name=\"bindtime\" " + disableString + " />&nbsp;<label>" + TranslateDates(n.PriceCatcherTime) + "</label> ");
            });
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function GetPrice(companyId, normalTax, environmentChoice, priceTypeId, isExistingCustomer, startDate, usesPeriod, priceIndex, calledFromReduceClick) {
    var usesSpecialCustTypes = false;

    var theElArea = DEFAULT_EL_AREA;
    if (USES_EL_AREA)
        theElArea =  $('#elarea').val();

    if (UseSpecialCustomerTypes == "True")
        usesSpecialCustTypes = true;

    $('#btnGotoStep2').attr("disabled", true);
    $('#step1Done').hide();

    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetPriceById",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "',normalTax:'" + normalTax + "', environmentChoice:'" + environmentChoice + "', priceTypeId:'" + priceTypeId + "', isExistingCustomer:'" + isExistingCustomer + "', startDate:'" + startDate + "', usesSpecialCustomerTypes:'" + usesSpecialCustTypes + "', elArea:'" + theElArea + "'}",
        success: function (response) {
            var container = $("#AgreementInfo dl:eq(1) dd");
            if (response.d == null) {
                alert("Det finns inga priser inlagda för perioden!");
                var priceCatcher = $("#price-capturer fieldset:eq(0)");
                priceCatcher.html('');
                var period = $("#BindTime");
                period.html('');
                SetVisibility(0, 4, $($("#step1").children("div.fieldset")));
                return;
            }
            if (DoSeparatePrices == "True" || DoSeparatePrices == "true") {
                if (response.d.AnnualFee == 0) {
                    container.eq(11).prev().hide();
                    container.eq(11).hide();
                }
                container.eq(11).html(response.d.AnnualFee + " kr/år");
                container.eq(7).html(response.d.EnergyTax + " öre/kWh");
            }
            else {
                if (response.d.AnnualFee == 0) {
                    container.eq(6).prev().hide();
                    container.eq(6).hide();
                }
                container.eq(6).html(response.d.AnnualFee + " kr/år");
                container.eq(2).html(response.d.EnergyTax + " öre/kWh");
            }
            theVat = response.d.Vat;

            if (usesPeriod) {
                var usePC = UsesPriceCatcher(priceTypeId);
                if (usePC) {
                    
                    GetPriceCatchers(companyId, $("fieldset:eq(0) input:checked", $("#agreement", $("#step1"))).val(), calledFromReduceClick);

                    }
                var period = $("#BindTime");
                period.html('');

                $.each(response.d.PeriodsAndPrices, function (i, n) {
                    period.append("<input type=\"radio\" onclick=\"SetPrice('" + n.SupplementCharge + "', '" + n.PurchaseCost + "', '" + n.Certificate + "', '" + n.NetCost + "', '" + n.RowTotal + "', '" + n.RowTotal2000Kwh + "', '" + n.RowTotal5000Kwh + "', '" + n.RowTotal20000Kwh + "','" + n.RowVat + "');OpenNextButton();SetYearPrices();\" value=\"" + n.PeriodValue + "\" name=\"cbBindtime\" />");
                    period.append("&nbsp;<label onclick=\"SetPrice('" + n.SupplementCharge + "', '" + n.PurchaseCost + "', '" + n.Certificate + "', '" + n.NetCost + "', '" + n.RowTotal + "', '" + n.RowTotal2000Kwh + "', '" + n.RowTotal5000Kwh + "', '" + n.RowTotal20000Kwh + "','" + n.RowVat + "');OpenNextButton();SetYearPrices();\" >" + TranslateDates(n.PeriodValue) + "</label><br/> ");
                });

                //Visa priserna
                if (response.d.PeriodsAndPrices.length > 0) {
                    selectedPrice = response.d.PeriodsAndPrices[priceIndex];
                    selectedPrices = response.d.PeriodsAndPrices;
                }
                else
                    alert("Det finns inga priser inlagda för pristypen!");
            }
            else {
                var usePC2 = UsesPriceCatcher(priceTypeId);
                if (usePC2)
                    GetPriceCatchers(companyId, $("fieldset:eq(0) input:checked", $("#agreement", $("#step1"))).val(), calledFromReduceClick);

                //Stäng ner bindningstid.
                var period = $("#BindTime");
                period.html('');

                OpenNextButton();

                //Visa priserna
                if (response.d.PeriodsAndPrices.length > 0) {
                    var prices = response.d.PeriodsAndPrices[0];
                    SetPrice(prices.SupplementCharge, prices.PurchaseCost, prices.Certificate, prices.NetCost, prices.RowTotal, prices.RowTotal2000Kwh, prices.RowTotal5000Kwh, prices.RowTotal20000Kwh, prices.RowVat);
                    selectedPrice = response.d.PeriodsAndPrices[0];
                    selectedPrices = response.d.PeriodsAndPrices;
                }
                else
                    alert("Det finns inga priser inlagda för pristypen!");
            }
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function OpenNextButton() {
    $('#btnGotoStep2').removeAttr('disabled');
    CheckIfDateIsSelected();
}
function SetYearPrices() {
    $("#TotalPriceInMonth").attr('checked', false);
    $("#TotalPriceInYear").attr('checked', true);
    SetTotalPrice();
    if ($("#TotalPrice").text() == "0 kr/mån") {
        $("#TotalPrice").text("0 kr/år");
    }
}

function TranslateDates(inValue) {
    switch (parseInt(inValue)) {
        case 12:
            return "1 år ";
            break;
        case 18:
            return "1,5 år ";
            break;
        case 24:
            return "2 år ";
            break;
        case 30:
            return "2,5 år ";
            break;
        case 36:
            return "3 år ";
            break;
        case 42:
            return "3,5 år ";
            break;
        case 48:
            return "4 år ";
            break;
        case 54:
            return "4,5 år ";
            break;
        case 60:
            return "5 år ";
            break;
        case 66:
            return "5,5 år ";
            break;
        case 72:
            return "6 år ";
            break;
        default: return inValue + " mån";
    }
}

function GetAddons(companyId, priceTypeId, usesPeriod) {
    var disableString;
    if (usesPeriod)
        disableString = " disabled=\"\"";
    else
        disableString = "";

    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetAddons",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "', priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            var container = $("#green-choice fieldset");
            container.html('');

            $.each(response.d, function (i, n) {
                container.append("<input type=\"radio\" value=\"" + n.PricePerKwh + "\" name=\"addon\" " + disableString + " />&nbsp;<label>" + n.Addon + "</label><br/>");
            });

            if (response.d.length > 0) {
                if (container.hasClass("Nothing") == false)
                    container.append("<input type=\"radio\" value=\"" + 0 + "\" name=\"addon\" checked=\"checked\" " + disableString + " />&nbsp;<label>" + "Inget" + "</label><br/>");

                $(".Nothing").attr('checked', 'checked');
            }
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function CheckIfPersonummerIsOk(pnr) {
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/CheckIfPersonnummerIsOk",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{pnr:'" + pnr + "'}",
        success: function (response) {
            var PersonCheckOk = response.d;
            var EmailCheckOk = true;

            if ($("#NoCivRegNumber").hasClass("NoCivRegNumberSelected"))
                PersonCheckOk = true;

            if (!PersonCheckOk) {
                alert("Personnumret är felaktigt!");
                return false;
            }

            var emailValue = $("#EMail").val();

            //IF USER ENTERS VALUE IN EMAIL, CHECK IF THE VALUE IS VALID
            if (emailValue.length > 0) {
                $.ajax({
                    type: "POST",
                    url: "/Utilities/Services/PriceGadgetWebService.asmx/CheckIfEmailIsOk",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "{email:'" + emailValue + "'}",
                    success: function (response) {
                        EmailCheckOk = response.d;

                        if (!EmailCheckOk) {
                            alert("Angiven epostadress är felaktig!");
                            return false;
                        }
                    }
                });
            }
            else
                EmailCheckOk = true;
            //-----------------------

            if ($("#BuildingID").val().length != 12) {
                $("#BuildingID").addClass("error");
            }
            if ($("#AreaID").val().length != 3) {
                $("#AreaID").addClass("error");
            }

            var Validate = false;
            //  var noCivNbrValidate = NoCivNbrValidate();
            //  var paymentRadioButtonOk = paymentValidate();

            var step11 = $("#step1");
            var customerType1 = $("#customer-type", step11);

            if ($("#aspnetForm").valid() && PersonCheckOk && EmailCheckOk) {
                if (UseSpecialCustomerTypes == "True" || SodraCSSFixPersonal == "True") {
                    $(".Elcert").next().remove();
                    $(".Elcert").remove();
                    var the_radio = $("#custTypeSpecial input:radio:checked");
                    var the_radios = $("#custTypeSpecial input:radio");
                    the_index = the_radios.index(the_radio);
                    //var the_label = the_radio[0].nextElementSibling.textContent;
                    //var the_label = the_radio[0].nextSibling.textContent;
                    var the_label;
                    if (jQuery.browser.msie && jQuery.browser.version <= 8) {
                        the_label = the_radio[0].nextSibling.nextSibling.innerText; //IE6, IE7, IE8
                    }
                    else {
                        the_label = the_radio[0].nextElementSibling.textContent; //FF, CHROME/SAFARI
                    }

                    $(".CustomerType").text($("#custTypeSpecial input:checked").next().text());
                }
                else {
                    if ($("input:checked", customerType1).next().html() == "Redan kund")
                        $(".CustomerType").text("Redan kund");
                }

                if (USES_EL_AREA) {
                    $(".OI_ElArea").text($('#elarea option:selected').text());
                }
                else {
                    $(".OI_ElArea").prev().remove();
                    $(".OI_ElArea").remove();
                }

                $(".LivingForm").text($("#Boende").text());
                $(".AnnualUse").text($(".Annualtextbox").val() + " kWh");
                $(".StartDateInfo").text($("#Avtalsstart").text());
                $(".AgreementInfo").text($("#PriceTypeName").text());

                if ($("#Avtalslangd").val().length > 0)
                    $(".ddAgreementLength").text($("#Avtalslangd").text());
                else {
                    $(".ddAgreementLength").prev().remove();
                    $(".ddAgreementLength").remove();
                }

                $("#TotInfo").text($("#TotalPrice").text().replace("/år", ""));

                var envChoiceText = $("#green-choice fieldset input:checked").next().text();
                if (envChoiceText.length > 0) {
                    $(".EnviromentChoice").text(envChoiceText);
                }
                else {
                    $(".EnviromentChoice").prev().remove();
                    $(".EnviromentChoice").remove();
                }

                if ($("#GoodForEnviromentMail").is(':checked')) {
                    $("#EnvironmentConf").text('Ja');
                }
                else {
                    $("#EnvironmentConf").text('Nej');
                }

                //Gömt 

                if ($("#ClubChoose option:selected").text() == "Välj klubb") {
                    $(".ClubInfo").hide();
                    $(".ClubInfo").prev().hide();
                    $(".ClubInfo").text("");
                }
                else {
                    $(".ClubInfo").show();
                    $(".ClubInfo").prev().show();
                    $(".ClubInfo").text($("#ClubChoose option:selected").text());
                }

                //$(".BindTimeInfo").text($("#BindTime input:checked").next().text());
                //PriceCapturerTime
                if ($("#PriceCapturerTime input:checked").size() > 0) {
                    $("#BindTimeInfo").show();
                    $("#BindTimeInfo").prev().show();
                    $("#BindTimeInfo").text($("#PriceCapturerTime input:checked").next().text());
                }
                else {
                    $("#BindTimeInfo").prev().remove();
                    $("#BindTimeInfo").remove();
                }
                if ($("#BindLevel input:checked").size() > 0) {
                    $("#BindLevelInfo").show();
                    $("#BindLevelInfo").prev().show();
                    $("#BindLevelInfo").text($("#BindLevel input:checked").next().text());
                }
                else {

                    $("#BindLevelInfo").prev().remove();
                    $("#BindLevelInfo").remove();
                }

                //Personal info
                if ($("#CivRegNumber").val().length > 0)
                    $(".PersonalNumberInfo").html($("#CivRegNumber").val());
                else
                    $(".PersonalNumberInfo").html("<br>");
                $(".FirstNameInfo").html($("#FirstName").val());
                $(".LastNameInfo").html($("#SecondName").val());
                $(".AdressInfo").html($("#Address").val());
                $(".PostCodeInfo").html($("#PostalCode").val());
                $(".PlaceInfo").html($("#Place").val());
                $(".PhoneDayInfo").html($("#PhoneDayTime").val());
                $(".PhoneEvningInfo").html($("#PhoneEveningTime").val());
                if ($("#EMail").val().length > 0)
                    $(".EMailInfo").html($("#EMail").val());
                else
                    $(".EMailInfo").html("<br>");

                $(".MedlemsInfo").html($("#MemberNumber").val());

                var buildingIdInfo = $("#BuildingIDFixed").val() + $("#BuildingID").val();
                $(".BuildingIdInfo").html(buildingIdInfo);

                $(".AreaIdInfo").text($("#AreaID").val());

                if ($("#UseAltAddress").is(':checked')) {
                    $(".BuildingAddressInfo").prev().show();
                    $(".BuildingAddressInfo").show();
                    $(".BuildingPostalCodeInfo").prev().show();
                    $(".BuildingPostalCodeInfo").show();
                    $(".BuildningPlaceInfo").prev().show();
                    $(".BuildningPlaceInfo").show();

                    if ($("#AltAddress").val().length > 0) {
                        $(".BuildingAddressInfo").html($("#AltAddress").val());
                    }

                    if ($("#AltPostalCode").val().length > 0) {
                        $(".BuildingPostalCodeInfo").html($("#AltPostalCode").val());
                    }

                    if ($("#AltPlace").val().length > 0) {
                        $(".BuildningPlaceInfo").html($("#AltPlace").val());
                    }
                }
                else {
                    $(".BuildingAddressInfo").html("");
                    $(".BuildingPostalCodeInfo").html("");
                    $(".BuildningPlaceInfo").html("");
                    $(".BuildingAddressInfo").prev().hide();
                    $(".BuildingAddressInfo").hide();
                    $(".BuildingPostalCodeInfo").prev().hide();
                    $(".BuildingPostalCodeInfo").hide();
                    $(".BuildningPlaceInfo").prev().hide();
                    $(".BuildningPlaceInfo").hide();
                }

                $("#PaymentInfo").text($("#payment input:checked").next().text());

                $("#step1").hide();
                $("#step2").hide();
                $("#step3").show();
                $(".TopBanner1").hide();
                $(".TopBanner2").hide()
                $(".TopBanner3").show();
                var currentTab = $(".active");
                $("#Steps").addClass("Active2");
                $("#Steps").removeClass("Active1");
                currentTab.removeClass("active");
                currentTab.next().addClass("active");
                $('#step2Done').show();
            }
            $(".error").html("");

            $('html, body').animate({ scrollTop: 0 }, 'slow');
        }
    });
}

function PriceTypeGroupIsRorlig(priceTypeId) {
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/PriceTypeGroupIsRorlig",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            PRICETYPE_GROUP_IS_RORLIG = response.d;
            onResizeWindow(response.d);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function onResizeWindow(doShow) {
    $('#RightArea').makeFloat({ x: "current", y: "current", speed: "normal", alwaysVisible: true, alwaysTop: true });

    $('#RightArea').removeAttr('style');

    GetInfoBoxInfo(PageId);
    $('.info-box').html(PRICE_TYPE_INFOBOX);
    if (PRICE_TYPE_INFOBOX == "" || PRICE_TYPE_INFOBOX == undefined)
        $(".info-box").hide();
    else {
        $(".info-box").show();
    }


//    if (jQuery.browser.msie && jQuery.browser.version == 6) {
//        $('#RightArea').makeFloat({ x: "current", y: "current", speed: "normal", alwaysVisible: true, alwaysTop: true });
//    }
//    else {
        var offset = $('#RightArea').offset();
        var currentX = offset.left;
        var currentY = (offset.top - 10);

        $('#RightArea').makeFloat({ x: currentX, y: currentY, speed: "normal", alwaysVisible: true, alwaysTop: true });
    //}
}

function UsesPeriod(priceTypeId) {
    var usesPeriod = false;
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/UsesPeriod",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            if (!response.d) {
                $("#BindTime").hide();
                $("#Bindtime-capture legend:first").hide();
            }
            else {

                $("#BindTime").show();
                $("#Bindtime-capture legend:first").show();

            }

            usesPeriod = response.d;
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
    return usesPeriod;
}

function UsesPriceCatcher(priceTypeId) {
    var usesPeriod = false;
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/UsesPriceCatcher",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            if (!response.d)
                $("#priceCapturerDiv").hide();
            else
                $("#priceCapturerDiv").show();

            usesPeriod = response.d;
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
    return usesPeriod;
}

function SendMail(fromAddress, toAddress, fromName, toName, subject, plainTextBody, plainTextBody2, market, emailSender, orderMail, enviromentMail, autoGiroChosen) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/SendMail",
        async: false,
        dataType: "json",
        data: "{fromAddress:'" + fromAddress + "', toAddress:'" + toAddress + "', fromName:'" + fromName + "', toName:'" + toName + "', subject:'" + subject + "', plainTextBody:'" + plainTextBody + "', plainTextBody2:'" + plainTextBody2 + "', OrderMail:'" + orderMail + "', EnviromentMail:'" + enviromentMail + "', FromNameTO_Lek:'" + MailFromName + "', PageId:'" + PageId + "', IsAutoGiro:'" + autoGiroChosen + "', AutoAttachUrl:'" + AutoGiroFilePath + "', TOA_AttachUrl:'" + AvtalsVillkorFilePath + "'}",
        success: function (response) {
            if (response.d == "") {
                window.location = OrderSucceededPageUrl;
                return false;
            }
            else
                alert(response.d);
        },
        error: function (XMLHttpRequest, textStatus) {
            window.location = OrderFailedPageUrl;
            return false;
            //alert(XMLHttpRequest.responseText);
        }
    });
}

function GenerateHelperText(pageId) {
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetMainBodys",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{PageId:'" + pageId + "'}",
        success: function (response) {
            $.each(response.d, function (i, n) {
                if (n != "") {
                    $(".ToolTip" + i).qtip({
                        style: {
                            name: 'dark',
                            tip: true
                        },
                        hide: {
                            fixed: true, // Make it fixed so it can be hovered over

                            delay: 1000



                        },
                        content: n,
                        position: {
                            target: 'mouse',
                            adjust: { mouse: true, screen: true },
                            type: 'absolute',
                            corner: {
                                tooltip: 'bottomLeft' // Use the corner...
                            }
                        }
                    });
                }
            });
        },
        error: function (response) {
            alert(response.d);
        }
    });
}

function GetInfoBoxInfo(pageId) {
    priceTypeId = getCurrentPriceTypeId();
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetInfoBoxInfo",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{pageId:'" + pageId + "', priceTypeId:'" + priceTypeId + "'}",
        success: function (response) {
            PRICE_TYPE_INFOBOX = response.d;
        }
    });
}

function RoundedCorners() {
    //Dim box
    if (jQuery.browser.msie) {
        $(".Cloud").corner("round 2px").parent().css('padding', '1px').corner("round 5px");
        if (jQuery.browser.version >= 8) {
            $(".info-box").corner();
            $(".Inner").corner("round 5px").parent().css('padding', '1px').corner("round 6px");
            $(".Inner:first").corner("round 5px").parent().css('padding', '1px').corner("round 6px")
        } else {
            $(".info-box").corner("round 8px").parent().css('padding', '1px').corner("round 5px");
            $(".Cloud").corner("round 7px").parent().css('padding', '1px').corner("round 6px");
            $(".Inner").corner("round 7px").parent().css('padding', '1px').corner("round 6px");
            if (jQuery.browser.version == 6) {
                //$(".info-box").corner("round 10px");//.parent().css('padding', '1px');
                $(".info-box").css("height", "170px").corner("round 10px");
                $(".Inner").css("height", "70px");
            }
        }

    } else {
        $(".info-box").corner();
        $(".Cloud").corner("round 7px").parent().css('padding', '1px').corner("round 6px");
        $(".Inner").corner("round 7px").parent().css('padding', '1px').corner("round 6px");
    }
}
//BrowserStyle adjustment
function IE6Fix() {
    //Safari and Chrome
    if (jQuery.browser.safari) {
        $("#Bindtime-capture").css("margin-left", "120px");
        $("#Bindtime-capture").css("width", "100px");
    }

    if (jQuery.browser.msie && jQuery.browser.version == 6) {
        // $(".ToolTip5").css("background", "transparent url(../images/help-button-icon.gif) no-repeat center center");
//        $(".panel .Toggle-button").css("top", "-25px");
//        $(".panel .Toggle-button").css("z-index", "1000");
        $(".panel .help-button").css("top", "45px");
        $(".panel .help-button").css("left", "5px");
        // $(".panel2").parent().css("height", "250px");
        // $(".panel1").parent().css("height", "150px");
        $("#price-capturer").parent().css("width", "493px");
        $("#price-capturer").parent().css("overflow", "hidden");
        $(".panel1").height("150px");
        $(".panel2").height("250px");
        $(".Closed").parent().css("height", "80px");
        $(".Closed").children().hide();
        //  $("#HousingRadioButtonContainer").css("margin-left", "100px");
        if (MarketPlaceId == "sodra" || MarketPlaceId == "sodra-el" || MarketPlaceId == "sodra-el.com" ) {
            $("#Bindtime-capture").css("margin-left", "0px");
            $("#Bindtime-capture").css("width", "210px");
            
            $("#BindTime").css("width", "170px");
            $("#BindTime").css("margin-left", "43px");
            
            $("#priceTypeRadio").css("margin-left", "43px");
            
            $(".MiddleColumnWidth").css("width", "140px");
            
            $("#agreement").css("width", "210px");
        }
        else {
            $("#Bindtime-capture").css("margin-left", "100px");
            $("#BindTime").css("margin-left", "10px");
        }
        $("#makeAnEnvironmentChoiceDiv label").css('color', 'black');
        $(".Cloud").parent().css('width', '512px');
        $(".Cloud").height('150px');
        $("#building-data").parent().height('150px');
        $("#agreement").parent().parent().height('150px');
        $("#payment").parent().parent().height('130px');
        $(".Cloud").parent().css('overflow', 'hidden');
        $("#personal-data").parent().height('415px');

        $("#makeAnEnvironmentChoiceDiv span").css('color', 'black');

        $(".ToolTip5").removeAttr('style');
        $("#help-button .ToolTip5").css("right", "250px");
        $("#help-button .ToolTip5").css("top", "60px");
        $(".ToolTip5").removeClass("help-button");
        $(".ToolTip5").addClass("help-button-cloud");
        $("personal-data").nextAll().addClass("column");
        $(".InputLastNameWidth").css("margin-right", "150px");
        $("#step2 fieldset:first").css('width', ' 490px');

        $(".TopBanner2").hide();
        $(".TopBanner3").hide();
        $(".fieldsets").css("width", "485px");

        $("#AltPlace").css("width", "300px");
        $("#AltPostalCode").css("width", "300px");
        $("#AltAddress").css("width", "300px");
        $("#AltPlace").css("margin-left", "0");
        $("#AgreementFillOutForm").css("padding-left", "20px");
        $("#priceCapturerDiv").height("150px");
        $("#priceCapturerDiv .Inner").height("150px");
    }
}

//Dim enhancement for IE 8
function DimEnhancement() {
    if (jQuery.browser.msie && jQuery.browser.version > 7) {
        // $("#step1 .fieldset input").addClass('Opacity3CSSIE8');  //css('opacity', '0.1');
        $("#step1 .fieldset label").css('color', 'grey');
        $("#step1 .fieldset #column span").css('color', 'grey');
        $("#Housing1 span").css('color', 'grey');
        $("#step1 .fieldset legend span").css('color', 'grey');
        $("#step1 .fieldset:first input").css('opacity', '1');
        $("#step1 .fieldset:first legend span").css('color', 'black')
        $("#step1 .fieldset:first label").css('color', 'black');

        if (USES_EL_AREA) {
            $("#elAreas").css('color', 'grey');
            $("#elarea").attr("disabled", true);
            $("#btnElAreaSearch").hide();
        }
    }
    else {
        if (USES_EL_AREA) {
            $("#elarea").attr('disabled', 'disabled');
            $("#btnElAreaSearch").hide();
        }
    } 
}

//********************************
// STEG1: POPUPS
//********************************
function openPopUp() {
    if (LabelToBeClickableIndex > 2) {
        if (HaveDifferentSupplierLinkUrl != undefined || HaveDifferentSupplierLinkUrl != null)
            popUp(); //window.open(HaveDifferentSupplierLinkUrl, "Kontakta oss", 'height=550,width=700,resizable=1,scrollbars=1').focus();
    }
}
function openPopUpMaxAnnual() {
    if (MaxAnnualLinkUrl != undefined || MaxAnnualLinkUrl != null) {
        popUpMaxAnnual();  //window.open(MaxAnnualLinkUrl, "Kontakta oss", 'height=550,width=700,resizable=1,scrollbars=1').focus();
    }
}
function openPopUpTOA() {
    if (TermsOfAgreementPageUrl != undefined || TermsOfAgreementPageUrl != null) {
        popUpTOA();
    }
}
function popUp() {
    var mywindow = window.open(HaveDifferentSupplierLinkUrl,
        "Kontaktaoss", "location=1,status=1,scrollbars=1,resizable=1,width=800,height=600");
    mywindow.moveTo(0, 0);
}
function popUpMaxAnnual() {
    var mywindow = window.open(MaxAnnualLinkUrl,
        "Kontaktaoss", "location=1,status=1,scrollbars=1,resizable=1,width=800,height=600");
    mywindow.moveTo(0, 0);
}

function popUpTOA() {
    var mywindow = window.open(TermsOfAgreementPageUrl,
        "Avtalsvillkor", "location=1,status=1,scrollbars=1,resizable=1,width=800,height=600");
    mywindow.moveTo(0, 0);
}

//********************************
// Steg2: VALIDERA
//********************************
function ValidationRules(RequiredStdValidate, RequiredFirstName, RequiredSecondName, RequiredAddress,
RequiredPostalCode, RequiredPlace, RequiredPhoneDayTime, RequiredEveningTime, RequiredEmail, RequiredBuildningId,
RequiredAreaId, RequiredUseAltAdress, RequiredAltAdress, RequiredAltPostalCode, ReqAltPlace

) {
    var ReqStdValidate = RequiredStdValidate == "True" ? true : false;
    var ReqFirstName = RequiredFirstName == "True" ? true : false;
    var ReqSecondName = RequiredSecondName == "True" ? true : false;
    var ReqAddress = RequiredAddress == "True" ? true : false;
    var ReqPostalCode = RequiredPostalCode == "True" ? true : false;
    var ReqPlace = RequiredPlace == "True" ? true : false;
    var ReqPhoneDayTime = RequiredPhoneDayTime == "True" ? true : false;
    var ReqEveningTime = RequiredEveningTime == "True" ? true : false;
    var ReqEmail = RequiredEmail == "True" ? true : false;
    var ReqBuildningId = RequiredBuildningId == "True" ? true : false;
    var ReqAreaId = RequiredAreaId == "True" ? true : false;
    var ReqUseAltAdress = RequiredUseAltAdress == "True" ? true : false;
    var ReqAltAdress = RequiredAltAdress == "True" ? true : false;
    var ReqAltPostalCode = RequiredAltPostalCode == "True" ? true : false;
    var RequiredAltPlace = ReqAltPlace == "True" ? true : false;
    if (ReqStdValidate || (ReqFirstName == false && ReqSecondName == false && ReqAddress == false && ReqPostalCode == false
    && ReqPlace == false && ReqPhoneDayTime == false && ReqEveningTime == false && ReqEmail == false && ReqBuildningId == false
    && ReqAreaId == false && ReqUseAltAdress == false && ReqAltAdress == false && ReqAltPostalCode == false && RequiredAltPlace == false)) {
        $("#aspnetForm").validate({
            rules: {
                CivRegNumber: { required: "#NoCivRegNumber:unchecked" },
                BuildingID: { required: true, minlength: 12 },
                FirstName: "required",
                SecondName: "required",
                Address: "required",
                PostalCode: "required",
                Place: "required",
                PhoneDayTime: "required",
                EMail: { required: "#GoodForEnviromentMail:checked" },
                PhoneEveningTime: "required",
                AreaID: { required: true, minlength: 3 }

            },
            messages: {
                CivRegNumber: "",
                BuildingID: "",
                FirstName: "",
                SecondName: "",
                Address: "",
                PostalCode: "",
                Place: "",
                PhoneDayTime: "",
                EMail: "",
                PhoneEveningTime: "",
                AreaID: "",
                payment: ""
            }
        });
    }
    else {

        $("#aspnetForm").validate({
            rules: {
                CivRegNumber: { required: "#NoCivRegNumber:unchecked" },
                BuildingID: { required: ReqBuildningId, minlength: 12 },
                FirstName: { required: ReqFirstName },
                SecondName: { required: ReqSecondName },
                Address: { required: ReqAddress },
                PostalCode: { required: ReqPostalCode },
                Place: { required: ReqPlace },
                PhoneDayTime: { required: ReqPhoneDayTime },
                EMail: { required: "#GoodForEnviromentMail:checked" },
                PhoneEveningTime: { required: ReqEveningTime },
                AreaID: { required: ReqAreaId, minlength: 3 },
                AltAdress: { required: ReqAltAdress },
                AltPostalCode: { required: ReqAltPostalCode },
                AltPlace: { required: RequiredAltPlace }
            },
            messages: {
                CivRegNumber: "",
                BuildingID: "",
                FirstName: "",
                SecondName: "",
                Address: "",
                PostalCode: "",
                Place: "",
                PhoneDayTime: "",
                EMail: "",
                PhoneEveningTime: "",
                AreaID: "",
                payment: "",
                AltAdress: "",
                AltPostalCode: "",
                AltPlace: ""
            }
        });
    }
}
//------------------------------------------------------
// Genmensamma funktioner för Label i steg 1 och Radioknappar
//------------------------------------------------------
function CustomerTypeEvent(companyId, NewCustomerRadioChecked, memberRadioChecked, employedRadioChecked, partnerRadio, alreadyCustomerRadio, fieldsets) {
    $("#NewCustomerRadio").attr('checked', NewCustomerRadioChecked);
    $("#memberRadio").attr('checked', memberRadioChecked);
    $("#EmployedRadio").attr('checked', employedRadioChecked);
    $("#PartnerRadio").attr('checked', partnerRadio);
    $("#AlreadyCustomerRadio").attr('checked', alreadyCustomerRadio);
    SetVisibility(0, 2, fieldsets);
    ClearInfo();
    ClearHousing(fieldsets);
}
function FillElAreas(companyId) {
    searchPopUpSetup();
    
    USES_EL_AREA = UsesElArea(companyId);
    if (USES_EL_AREA == false) {
        $('#elAreas').hide();
        return;
    }
    
    //Fill ElArea-dropdown
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetElAreas",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "'}",
        success: function (response) {
            var container = $('#elarea');
            container.html('');
            //container.html('<option value="-1"></option>');
            $.each(response.d, function (i, n) {
                container.append("<option value=\"" + n.AreaNumber + "\">" + n.AreaName + "</option>");
            });

            //SetDefaultElArea(companyId);
            $('#elarea').setDropDownValue(DEFAULT_EL_AREA);
        },
        error: function (response) {
            alert(response.d);
        }
    });
}
function searchPopUpSetup() {
    $('#swedEnergyPopUp').dialog({
        autoOpen: false,
        height: 380,
        width: 450,
        modal: true,
        draggable: true,
        resizable: true
    });
}

function openSearchPopUp() {
    ResetPopUpData();
    $('#swedEnergyPopUp').dialog('open');
    $("#tbSearch").focus(); //Markören i sökrutan när fönstret laddats...
    return false;
}
function ResetPopUpData() {
    $("#searchResult").hide();
    $("#searchBody").html("");
    $("#tbSearch").val("");
    $("#totalHits").html("");
}
function GetDefaultElArea(companyId) {
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/GetDefaultElArea",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "'}",
        success: function (response) {
            DEFAULT_EL_AREA = response.d;
        }
    });
}

function UsesElArea(companyId) {
    var uea = false;
    $.ajax({
        type: "POST",
        url: "/Utilities/Services/PriceGadgetWebService.asmx/UsesElArea",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{companyId:'" + companyId + "'}",
        success: function (response) {
            uea = response.d;
        }
    });
    return uea;
}

function DoShowAsterisk() {
    if (ShowAsterisk == "True")
        return true;
    if (ShowAsterisk == "true")
        return true;

    return false;
}
//------------------------------------------------------
// slut FUNKTIONER
//------------------------------------------------------

//------------------------------------------------------
// JQUERY-"PLUGINS"
//------------------------------------------------------

//************************
// Numeric only function
//************************
//8: "backspace", 46: "delete", 9: "tab", 36: "home", 35: "end"
jQuery.fn.OnlyNumbers =
function () {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.charCode || e.keyCode || 0;

            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                key == 36 ||
                key == 35 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

//************************
// Numeric only function
//************************
//8: "backspace", 46: "delete", 9: "tab", 36: "home", 35: "end", 109: "-"
jQuery.fn.PhoneNbr =
function () {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.charCode || e.keyCode || 0;

            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                key == 36 ||
                key == 35 ||
                key == 109 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

//************************
// Letters only function
//************************
//8: "backspace", 46: "delete", 9: "tab", 36: "home", 35: "end"
jQuery.fn.OnlyLetters =
function () {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.charCode || e.keyCode || 0;

            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                key == 36 ||
                key == 35 ||
                key == 222 || //ä
                key == 221 || //å
                key == 192 || //ö
                (key >= 37 && key <= 40) ||
                (key >= 65 && key <= 90));
        })
    })
};
//------------------------------------------------------
// slut JQUERY-"PLUGINS"
//------------------------------------------------------

