var silent_post_test_url="https://thisisud.com/dashboard/ubCheckOutCallBack.php";
// var ub_checkout_url="https://ubfoundation.buffalo.edu/test/checkout/index.php";
var ub_checkout_url="https://ubfoundation.buffalo.edu/checkout/index.php";
var return_url = "https://thisisud.com/dashboard/myProjects.php";
var service_type_code="7700";
var ubf_account="9316204381";
var site_code="1290";
var total_supporter_cost = 500;
var total_innovator_cost = 1000;
var plan_type;
var supporter_expiry_date;
var innovator_expiry_date;
var upgrade_date;
var chosen_price_plan; 
var chosen_downgrade_plan;
var chosen_price = 0;
var user_email_id;
var baseAmountForFuture = 0;
var amountToBePaidToday = 0;
var expiryStatus;
var chosen_plan;
var upgrade_or_renew;
var sub_now_or_later;
var is_downgrade;
var is_downgrade_final;
var upgradePlanYearsSelect;
var renewPlanYearsSelect;

var todayEndDate;
var yearsEndDate;

var cost_options = {
    val1 : '1year:  $1500',
    val2 : '2years: $2500',
    val3 : '3years: $3500',
    val4 : '4years: $4500',
    val5 : '5years: $5500',
};

var cost_options2 = {
    val1 : '1year:  $1000',
    val2 : '2years: $2000',
    val3 : '3years: $3000',
    val4 : '4years: $4000',
    val5 : '5years: $5000',
}

var cost_options3 = {
    val1 : '1year:  $500',
    val2 : '2years: $1000',
    val3 : '3years: $1500',
    val4 : '4years: $2000',
    val5 : '5years: $2500',
}

$(document).ready(function () {

    $.post("API.php", { dashboard: "SUBSCRIPTION_TYPE"}, function (data) {
        if(data.response){
            plan_type = data.subscription_type;
            supporter_expiry_date = data.supporter_expiry_date;
            innovator_expiry_date = data.innovator_expiry_date;
            upgrade_date = data.upgrade_date;
            user_email_id = data.email_id;

            if(supporter_expiry_date != null){
                getAmoutAndStatus(supporter_expiry_date);
            }

            if(innovator_expiry_date != null){
                var rounded_val;
                rounded_val = Math.round(getDateDiff(innovator_expiry_date));
                var diff_in_years = Math.ceil(rounded_val/365);

                console.log(diff_in_years > 3);
                console.log(getDateDiff(innovator_expiry_date) < 90);
                console.log(Math.abs(getDateDiff(upgrade_date)) < 365);

                if(supporter_expiry_date == null && (Math.abs(getDateDiff(upgrade_date)) < 365 || getDateDiff(innovator_expiry_date) < 90 || diff_in_years > 3)){
                    $("#supp-button").css({'display':'none'});
                }
            } 

            if(supporter_expiry_date != null && innovator_expiry_date != null){
                updateSubscriptionPlan(supporter_expiry_date, innovator_expiry_date, plan_type);
            }
            else{
                if(supporter_expiry_date!=null && innovator_expiry_date === null && getDateDiff(supporter_expiry_date) < 0){
                    setFreeSubscription("supexp");
                }
                else if(innovator_expiry_date!=null && supporter_expiry_date === null && getDateDiff(innovator_expiry_date) < 0){
                    setFreeSubscription("invexp");
                }
                else{
                    updateUI(plan_type, "");
                }
            }

            // Hide the downgrade button
            if((supporter_expiry_date != null && getDateDiff(supporter_expiry_date) >= 0) || (innovator_expiry_date != null && getDateDiff(innovator_expiry_date) >= 0)){
                $("#table-row12-col-1").css({'display':'none'});
                $("#table-row12-col-2").css({'display':'none'});
                $("#table-row12-col-3").css({'display':'none'});
                $("#table-row13-col-1").css({'display':'none'});
                $("#table-row13-col-2").css({'display':'none'});
                $("#table-row13-col-3").css({'display':'none'});
                $("#table-row14-col-1").css({'display':'none'});
                $("#table-row14-col-2").css({'display':'none'});
                $("#table-row14-col-3").css({'display':'none'});
                $("#table-row15-col-1").css({'display':'none'});
                $("#cost-in-dollars-supporter").css({'display':'none'});
                $("#cost-in-dollars-innovator").css({'display':'none'});
                $("#choose_supp_selector").css({'display':'none'});
                $("#choose_invv_selector").css({'display':'none'});
            }
 
        } else {
            data.message = "There is something wrong. Please try again";
            console.log(data.message);
        }
    },"json");
      
    attachOverviewBtnEventListener();

});

function setFreeSubscription(expiry_type){
    $.post("API.php", { dashboard: "SET_FREE_SUBSCRIPTION", email_id_in_db: user_email_id, exp_type : expiry_type}, function (data) {
        if(expiry_type == "supexp"){
            updateUI(plan_type, "supexp");
            supporter_expiry_date = null;
        }else{
            updateUI(plan_type, "invexp");
            innovator_expiry_date = null;
        }
    },"json");
}

function updateSubscriptionPlan(supporter_expiry_date, innovator_expiry_date, plan_type){
    var upgraded_plan;

    if(plan_type === "Supporter" && getDateDiff(supporter_expiry_date) < 0){

        $.post("API.php", { dashboard: "UPDATE_SUBSCRIPTION_PLAN_FOR_FUTURE_DATE", plan_type: "Innovator", plan: "supporter_expiry_date", email_id_in_db: user_email_id}, function (data) {
            upgraded_plan = "Innovator";
            updateUI(upgraded_plan, "");
        },"json");


    }else if(plan_type === "Innovator" && getDateDiff(innovator_expiry_date) < 0){

        $.post("API.php", { dashboard: "UPDATE_SUBSCRIPTION_PLAN_FOR_FUTURE_DATE", plan_type: "Supporter", plan: "innovator_expiry_date", email_id_in_db: user_email_id}, function (data) {
            upgraded_plan = "Supporter";
            updateUI(upgraded_plan, "");
        },"json");

    }

    else if(upgraded_plan == undefined){
        updateUI(plan_type, "");
    }

}

function updateUI(plan_type, exp_type){
    $("#table-row17-col-2").hide();
    $("#table-row17-col-3").hide();

    if(exp_type === "supexp"){
        $("#table-row17-col-2").text('Expired:');
        $('#table-row18-col-2').html(formatDate(supporter_expiry_date));
        $('#table-row17-col-2').attr("style", "text-align:center; color:red;");
        $("#table-row17-col-2").show();
        $('#supp-button').attr("value","Select");
        return;
    }

    if(exp_type === "invexp"){
        $("#table-row17-col-3").text('Expired:');
        $('#table-row18-col-3').html(formatDate(innovator_expiry_date));
        $('#table-row17-col-3').attr("style", "text-align:center; color:red;");
        $("#table-row17-col-3").show();
        $('#innv-button').attr("value","Select");
        return;
    }


    if(plan_type === 'Supporter'){
        $("#opening-note").text('Thank you for using isUD. You are currently subscribed as a Supporter. You can upgrade to Innovator membership at any time for additional benefits. If you have any questions, please contact us at ').append('<a href="mailto:ap-idea@buffalo.edu">ap-idea@buffalo.edu</a>');
        $('#supporter-title').css("background-color","#F7941E");
        $('#supp-button').attr("value","Renew");
        $('#innv-button').attr("value","Upgrade");
        $('#table-row1-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row1-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row2-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row2-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row3-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row3-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row4-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row4-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row5-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row5-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row6-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row6-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row7-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row7-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row7-col-3').attr("style", "border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row8-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row8-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row9-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row9-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row10-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row10-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row11-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px; font-weight:bold;");
        $('#table-row11-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        
        if(supporter_expiry_date == null){
            $('#table-row12-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
            $('#table-row12-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
            $('#table-row13-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
            $('#table-row13-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
            $('#table-row14-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
            $('#table-row14-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
            $('#table-row15-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
            $('#cost-in-dollars-supporter').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
        }

        $('#table-row16-col-1').attr("style", "text-align:left; border-right:1px dashed black;");
        $('#table-row16-col-2').attr("style", "border-right:1px dashed black; border-bottom:1px dashed black; font-weight:bold; text-align:center;");
        $('#table-row17-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $("#table-row17-col-2").text('Expires:');
        $('#table-row17-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; text-align:center; color:red;");
        $("#table-row17-col-2").show();
        if(innovator_expiry_date != null){
            $("#table-row17-col-3").text('Starts:');
            $('#table-row17-col-3').attr("style", "border-bottom:0px; text-align:center; color:green;");
            $('#table-row17-col-3').show();
            $('#table-row18-col-2').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
            $('#table-row18-col-3').attr("style", "border-bottom:0px; text-align:center; color:green;");
            var stringToDate = new Date(supporter_expiry_date);
            stringToDate.setDate(stringToDate.getDate() + 1);
            $('#table-row18-col-3').html(formatDate(stringToDate.toISOString().substring(0,10)));
        }
        $('#table-row18-col-1').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row18-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; text-align:center; color:red;");
        $('#table-row18-col-2').html(formatDate(supporter_expiry_date));
    }else if(plan_type==='Innovator'){
        $("#opening-note").text('Thank you for using isUD. You are currently subscribed as a Innovator. If you have any questions, please contact us at ').append('<a href="mailto:ap-idea@buffalo.edu">ap-idea@buffalo.edu</a>');
        $('#innovator-title').css("background-color","#F7941E"); 
        $('#innv-button').attr("value","Renew");
        $('#supp-button').attr("value","Downgrade");
        $('#table-row1-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row1-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row2-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row2-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row3-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row3-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row4-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row4-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row5-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row5-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row6-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold;");
        $('#table-row6-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold;");
        $('#table-row7-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold;");
        $('#table-row7-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center;");
        $('#table-row8-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row8-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row9-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row9-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row10-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
        $('#table-row10-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px");
        $('#table-row11-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold");
        $('#table-row11-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold");
        if(innovator_expiry_date == null){
            $('#table-row12-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; background-color: #dddddd;");
            $('#table-row13-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px;");
            $('#table-row13-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; background-color: #dddddd;");
            $('#table-row14-col-2').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold");
            $('#table-row14-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
            $('#cost-in-dollars-innovator').attr("style", "border-right:1px dashed black; border-bottom:0px; font-weight:bold; text-align:center; background-color: #dddddd;");
        }
        $('#table-row16-col-2').attr("style", "border-right:1px dashed black;");
        $('#table-row16-col-3').attr("style", "border-right:1px dashed black; border-bottom:1px dashed black;");
        $("#table-row17-col-3").text('Expires:');
        $('#table-row17-col-2').attr("style", "text-align:left; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row17-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; text-align:center; color:red;");
        $("#table-row17-col-3").show();
        
        $('#table-row18-col-2').attr("style", "text-align:center; border-right:1px dashed black; border-bottom:0px;");
        $('#table-row18-col-3').attr("style", "border-right:1px dashed black; border-bottom:0px; text-align:center; color:red;");
        $('#table-row18-col-3').html(formatDate(innovator_expiry_date));

        if(supporter_expiry_date!=null){
            console.log("Came to invv");
        }
    }
}

function attachOverviewBtnEventListener(){

    $("#supp-button").click(function(ev){
        if(plan_type=='Supporter' && supporter_expiry_date!=null){
            $("#id-renew-continue-popup").modal('show');
            $("#current_sub_end_date_renew").text("Your current subscription will end "+formatDate(supporter_expiry_date));
            var years = total_supporter_cost/500;
            yearsEndDate = addDays(new Date(formatDate(supporter_expiry_date)), years * 365);
            $("#subs_end_date_with_years_renew").text("The selected subscription will end on "+yearsEndDate);
        }else if(plan_type=='Innovator' && innovator_expiry_date!=null){
            $("#id-downgrade-popup").modal('show');
        }
        else{
            tempFunctionForSupp();
        }
    });

    $("#innv-button").click(function(ev){
        if(plan_type == 'Supporter'){
            upgradePlanYearsSelect = $('#upgradePlanYears');
            if(expiryStatus == "Before90" || expiryStatus == "MoreThan2" || expiryStatus == "InBetween90"){
                $("#id-upgrade-membership-popup").modal('show');
                $("#current_sub_end_date_upgrade").text("Your current subscription will end "+formatDate(supporter_expiry_date));
                $("#upgrade_base_price_today").text("Upgrade starting TODAY: $"+amountToBePaidToday);
                todayEndDate = convert(calculate_date_after_proration(amountToBePaidToday, supporter_expiry_date));
                $("#subs_end_date").text("Subscription will end on: "+todayEndDate);
               
                if(expiryStatus == "Before90"){
                    var prices = {
                        val1 : 1500,
                        val2 : 2500,
                        val3 : 3500,
                        val4 : 4500,
                        val5 : 5500,
                    };
                    var value_list = Object.keys(prices).map(k => prices[k]);
                    var i;
                    var j;
                    var new_prices = {};
                    for(i=0; i<value_list.length; i++) {
                        var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                        console.log("Dates Testing");
                        console.log("Look here");
                        console.log(getDateDiffBetweenDatesInYears(date1));
                        if(getDateDiffBetweenDatesInYears(date1) < 6){
                            j = i + 1;
                            new_prices["val"+j] = value_list[i];
                        }
                    }


                    var count = 1;
                    $("#upgradePlanYears").empty();
                    if($('#upgradePlanYears option').length == 0){
                        $.each(new_prices, function(val, text) {
                            upgradePlanYearsSelect.append(
                                $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                            );
                            count = count + 1;
                        });
                    }
                    yearsEndDate = convert(calculate_date_after_proration(1500, supporter_expiry_date));
                    $("#subs_end_date_with_years").text("The selected subscription will end on "+yearsEndDate);
                    $("#upgrade_additional_price_today").text("Upgrade starting TODAY: $500+$1000 per added year");
                }else{
                    yearsEndDate = convert(calculate_date_after_proration(1000, supporter_expiry_date));
                    $("#subs_end_date_with_years").text("The selected subscription will end on "+yearsEndDate);

                    console.log("Second Effect");
                    var prices = {
                        val1 : 1000,
                        val2 : 2000,
                        val3 : 3000,
                        val4 : 4000,
                        val5 : 5000,
                    };
                    console.log("Intense Testing");
                    var value_list = Object.keys(prices).map(k => prices[k]);
                    var i;
                    var j;
                    var new_prices = {};
                    for(i=0; i<value_list.length; i++) {
                        var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                        console.log("Dates Testing");
                        //console.log(getDateDiffBetweenDatesInYears(date1));
                        if(getDateDiffBetweenDatesInYears(date1) < 6){
                            j = i + 1;
                            new_prices["val"+j] = value_list[i];
                        }
                    }

                    var count = 1;
                    $("#upgradePlanYears").empty();
                    if($('#upgradePlanYears option').length == 0){
                        $.each(new_prices, function(val, text) {
                            upgradePlanYearsSelect.append(
                                $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                            );
                            count = count + 1;
                        });
                    }
                }
            }else{
                $("#id-upgrade-membership-popup-less_than_90").modal('show');
                $("#current_sub_end_date_less_than_90").text("Your current subscription will end "+formatDate(supporter_expiry_date));
                $("#upgrade_base_price_today_less_than_90").text("Upgrade starting TODAY: $"+amountToBePaidToday);
                todayEndDate = convert(calculate_date_after_proration(amountToBePaidToday, supporter_expiry_date));
                $("#subs_end_date_less_than_90").text("Subscription will end on: "+todayEndDate);
                yearsEndDate = addDays(new Date(formatDate(supporter_expiry_date)), 1 * 365);
                $("#subs_end_date_with_years_less_than_90").text("The selected subscription will end on "+yearsEndDate);
                
                var prices = {
                    val1 : 1000,
                    val2 : 2000,
                    val3 : 3000,
                    val4 : 4000,
                    val5 : 5000,
                };
                var value_list = Object.keys(prices).map(k => prices[k]);
                var i;
                var j;
                var new_prices = {};
                for(i=0; i<value_list.length; i++) {
                    var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                    if(getDateDiffBetweenDatesInYears(date1) <= 6){
                        j = i + 1;
                        new_prices["val"+j] = value_list[i];
                    }
                }
                
                var count = 1;
                $("#upgradePlanYears").empty();
                if($('#upgradePlanYears option').length == 0){
                    $.each(new_prices, function(val, text) {
                        upgradePlanYearsSelect.append(
                            $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                        );
                        count = count + 1;
                    });
                }
            }
        }else if(plan_type == "Innovator" && innovator_expiry_date!=null){
            $("#id-renew-continue-next-steps-popup").modal('show');
            var prices = {
                val1 : 1000,
                val2 : 2000,
                val3 : 3000,
                val4 : 4000,
                val5 : 5000,
            };
            var value_list = Object.keys(prices).map(k => prices[k]);
            var i;
            var j;
            var new_prices = {};
            renewPlanYearsSelect = $('#renewPlan');
            var dateDiff = getDateDiffBetweenDatesInYears(formatDate(innovator_expiry_date));
            console.log("CheckingDateDiff");
            console.log(dateDiff);

            var determineYears;

            if(dateDiff>=5 || dateDiff<=0){
                determineYears = 0;
            }else if(dateDiff>=4 && dateDiff<5){
                determineYears = 1;
            }
            else if(dateDiff>=3 && dateDiff<4){
                determineYears = 2;
            }
            else if(dateDiff>=2 && dateDiff<3){
                determineYears = 3;
            }
            else if(dateDiff>=1 && dateDiff<2){
                determineYears = 4;
            }else{
                determineYears = 5;
            }
            console.log(determineYears);

            for(i=0; i<determineYears; i++){
                j = i + 1;
                new_prices["val"+j] = value_list[i];
            }
            console.log(new_prices);
            if(Object.keys(new_prices).length === 0){
                $("#renew_no_mem_extension_msg").show();
                $(".select").hide();
                $("#renew_sub_heading").hide();
                $("#current_sub_end_date_renew").hide();
                $("#subs_end_date_with_years_renew").hide();
                $("#continue-button-2").hide();
                $("#cancel-button-2").hide();
                $("#renew_heading").hide();
                return;
            }
            var count = 1;
            $("#renewPlan").empty();
            if($('#renewPlan option').length == 0){
                $.each(new_prices, function(val, text) {
                    renewPlanYearsSelect.append(
                        $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                    );
                    count = count + 1;
                });
            }
            $("#current_sub_end_date_renew").text("Your current subscription will end "+formatDate(innovator_expiry_date));
            var years = total_innovator_cost/1000;
            yearsEndDate = addDays(new Date(formatDate(innovator_expiry_date)), years * 365);
            $("#subs_end_date_with_years_renew").text("The selected subscription will end on "+yearsEndDate);
        }
        else{
            tempFunction(chosen_price);
        }
    });
   
    $("#yes-option").click(function(){
        $("#cancel-continue-buttons").modal('show');
    });

    $("#no-option").click(function(){
        $("#id-downgrade-yes-popup").modal('hide');
        $("#cancel-continue-buttons").modal('hide');
    });

    $("#cancel-button").click(function(){
        $("#id-upgrade-membership-popup").modal('hide');
    });

    $("#cancel-button-1").click(function(){
        $("#id-renew-continue-popup").modal('hide');
    });

    $("#cancel-button-less-than-90").click(function(){
        $("#id-upgrade-membership-popup-less_than_90").modal('hide');
    });

    $('#id-upgrade-membership-popup').on('hidden.bs.modal', function () {
        $("input:radio").attr("checked", false);
        $("#upgradePlanYears").empty();
    })

    $('#id-renew-continue-next-steps-popup').on('hidden.bs.modal', function () {
        $("input:radio").attr("checked", false);
    })

    $('#id-renew-continue-popup').on('hidden.bs.modal', function () {
        $("input:radio").attr("checked", false);
    })

    $('#id-upgrade-membership-popup-renew').on('hidden.bs.modal', function () {
        $("input:radio").attr("checked", false);
        $("#upgradePlan").empty();
    })

    $('#id-upgrade-membership-popup-less_than_90').on('hidden.bs.modal', function () {
        $("input:radio").attr("checked", false);
        $("#upgrade-plan-less-than-90").empty();
    })

    $('#id-renew-continue-popup').on('shown.bs.modal', function () {

        $('input[type=radio]').click(function() {
            if($('#id-renew-continue-popup').hasClass('show')){
                upgrade_or_renew = $(this).val();
            }
        });


        if($('#id-renew-continue-popup').hasClass('show')){
            $("#continue-button-1").click(function(){
                if(upgrade_or_renew == "renew_supp"){
                    $("#id-renew-continue-next-steps-popup").modal('show');

                    // Added from here
                    var prices = {
                        val1 : 500,
                        val2 : 1000,
                        val3 : 1500,
                        val4 : 2000,
                        val5 : 2500,
                    };
                    var value_list = Object.keys(prices).map(k => prices[k]);
                    var i;
                    var j;
                    var new_prices = {};
                    renewPlanYearsSelect = $('#renewPlan');
                    var dateDiff = getDateDiffBetweenDatesInYears(formatDate(supporter_expiry_date));
                    console.log("CheckingDateDiff");
                    console.log(dateDiff);
        
                    var determineYears;
        
                    if(dateDiff>=5 || dateDiff<=0){
                        determineYears = 0;
                    }else if(dateDiff>=4 && dateDiff<5){
                        determineYears = 1;
                    }
                    else if(dateDiff>=3 && dateDiff<4){
                        determineYears = 2;
                    }
                    else if(dateDiff>=2 && dateDiff<3){
                        determineYears = 3;
                    }
                    else if(dateDiff>=1 && dateDiff<2){
                        determineYears = 4;
                    }else{
                        determineYears = 5;
                    }
        
                    console.log(determineYears);
        
                    for(i=0; i<determineYears; i++){
                        j = i + 1;
                        new_prices["val"+j] = value_list[i];
                    }

                    if(Object.keys(new_prices).length === 0){
                        $("#renew_no_mem_extension_msg").show();
                        $(".select").hide();
                        $("#renew_sub_heading").hide();
                        $("#current_sub_end_date_renew").hide();
                        $("#subs_end_date_with_years_renew").hide();
                        $("#continue-button-2").hide();
                        $("#cancel-button-2").hide();
                        $("#renew_heading").hide();
                        return;
                    }
    
                    var count = 1;
                    $("#renewPlan").empty();
                    if($('#renewPlan option').length == 0){
                        $.each(new_prices, function(val, text) {
                            renewPlanYearsSelect.append(
                                $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                            );
                            count = count + 1;
                        });
                    }
                }else{
                    $("#id-upgrade-membership-popup").modal('show');
                    $(".select").show();
                    upgradePlanYearsSelect = $('#upgradePlanYears');
                    if(plan_type == 'Supporter'){
                        if(expiryStatus == "Before90" || expiryStatus == "MoreThan2" || expiryStatus == "InBetween90"){
                            $("#id-upgrade-membership-popup").modal('show');
                            $("#current_sub_end_date_upgrade").text("Your current subscription will end "+formatDate(supporter_expiry_date));
                            $("#upgrade_base_price_today").text("Upgrade starting TODAY: $"+amountToBePaidToday);
                            todayEndDate = convert(calculate_date_after_proration(amountToBePaidToday, supporter_expiry_date));
                            $("#subs_end_date").text("Subscription will end on: "+todayEndDate);
                           
                            if(expiryStatus == "Before90"){
                                var prices = {
                                    val1 : 1500,
                                    val2 : 2500,
                                    val3 : 3500,
                                    val4 : 4500,
                                    val5 : 5500,
                                };
                                var value_list = Object.keys(prices).map(k => prices[k]);
                                var i;
                                var j;
                                var new_prices = {};
                                for(i=0; i<value_list.length; i++) {
                                    var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                                    //console.log(getDateDiffBetweenDatesInYears(date1));
                                    if(getDateDiffBetweenDatesInYears(date1) < 6){
                                        j = i + 1;
                                        new_prices["val"+j] = value_list[i];
                                    }
                                }
                                
                                console.log(new_prices);
                                if(Object.keys(new_prices).length === 0){
                                    $("#renew_no_mem_extension_msg").show();
                                    $(".select").hide();
                                    $("#renew_sub_heading").hide();
                                    $("#current_sub_end_date_renew").hide();
                                    $("#subs_end_date_with_years_renew").hide();
                                    $("#continue-button-2").hide();
                                    $("#cancel-button-2").hide();
                                    $("#renew_heading").hide();
                                    return;
                                }
                                
                                var count = 1;
                                $("#upgradePlanYears").empty();
                                if($('#upgradePlanYears option').length == 0){
                                    $.each(new_prices, function(val, text) {
                                        upgradePlanYearsSelect.append(
                                            $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                                        );
                                        count = count + 1;
                                    });
                                }

            
                                yearsEndDate = convert(calculate_date_after_proration(1500, supporter_expiry_date));
                                $("#subs_end_date_with_years").text("The selected subscription will end on "+yearsEndDate);
                                $("#upgrade_additional_price_today").text("Upgrade starting TODAY: $500+$1000 per added year");
                            }else{
                                yearsEndDate = convert(calculate_date_after_proration(1000, supporter_expiry_date));
                                $("#subs_end_date_with_years").text("The selected subscription will end on "+yearsEndDate);
            
                                var prices = {
                                    val1 : 1000,
                                    val2 : 2000,
                                    val3 : 3000,
                                    val4 : 4000,
                                    val5 : 5000,
                                };
                                var value_list = Object.keys(prices).map(k => prices[k]);
                                var i;
                                var j;
                                var new_prices = {};
                                for(i=0; i<value_list.length; i++) {
                                    var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                                    if(getDateDiffBetweenDatesInYears(date1) < 6){
                                        j = i + 1;
                                        new_prices["val"+j] = value_list[i];
                                    }
                                }
                                
                                console.log(new_prices);
                                if(Object.keys(new_prices).length === 0){
                                    $("#renew_no_mem_extension_msg").show();
                                    $(".select").hide();
                                    $("#renew_sub_heading").hide();
                                    $("#current_sub_end_date_renew").hide();
                                    $("#subs_end_date_with_years_renew").hide();
                                    $("#continue-button-2").hide();
                                    $("#cancel-button-2").hide();
                                    $("#renew_heading").hide();
                                    return;
                                }
                    
                                var count = 1;
                                $("#upgradePlanYears").empty();
                                if($('#upgradePlanYears option').length == 0){
                                    $.each(new_prices, function(val, text) {
                                        console.log("Bunty!!");
                                        upgradePlanYearsSelect.append(
                                            $('<option></option>'). attr("value",val).text(count+"year:  $"+text) 
                                        );
                                        count = count + 1;
                                    });
                                }
                            }
                        }else{
                            $("#id-upgrade-membership-popup-less_than_90").modal('show');
                            $("#current_sub_end_date_less_than_90").text("Your current subscription will end "+formatDate(supporter_expiry_date));
                            $("#upgrade_base_price_today_less_than_90").text("Upgrade starting TODAY: $"+amountToBePaidToday);
                            todayEndDate = convert(calculate_date_after_proration(amountToBePaidToday, supporter_expiry_date));
                            $("#subs_end_date_less_than_90").text("Subscription will end on: "+todayEndDate);
                            yearsEndDate = addDays(new Date(formatDate(supporter_expiry_date)), 1 * 365);
                            $("#subs_end_date_with_years_less_than_90").text("The selected subscription will end on "+yearsEndDate);
                            
                            var prices = {
                                val1 : 1000,
                                val2 : 2000,
                                val3 : 3000,
                                val4 : 4000,
                                val5 : 5000,
                            };
                            var value_list = Object.keys(prices).map(k => prices[k]);
                            var i;
                            var j;
                            var new_prices = {};
                            for(i=0; i<value_list.length; i++) {
                                var date1 = convertToYYYYMMDD(convert(calculate_date_after_proration(value_list[i], supporter_expiry_date)));
                                //console.log(getDateDiffBetweenDatesInYears(date1));
                                if(getDateDiffBetweenDatesInYears(date1) < 6){
                                    j = i + 1;
                                    new_prices["val"+j] = value_list[i];
                                }
                            }
                            
                            console.log(new_prices);
                            if(Object.keys(new_prices).length === 0){
                                $("#renew_no_mem_extension_msg").show();
                                $(".select").hide();
                                $("#renew_sub_heading").hide();
                                $("#current_sub_end_date_renew").hide();
                                $("#subs_end_date_with_years_renew").hide();
                                $("#continue-button-2").hide();
                                $("#cancel-button-2").hide();
                                $("#renew_heading").hide();
                                return;
                            }

                            var count = 1;
                            $("#upgradePlanYears").empty();
                            if($('#upgradePlanYears option').length == 0){
                                $.each(new_prices, function(val, text) {
                                    upgradePlanYearsSelect.append(
                                        $('<option></option>').attr("value",val).text(count+"year:  $"+text) 
                                    );
                                    count = count + 1;
                                });
                            }
                        }
                    }else if(plan_type == "Innovator" && innovator_expiry_date!=null){
                        $(".select").show();
                        $("#id-renew-continue-next-steps-popup").modal('show');
                        $("#current_sub_end_date_renew").text("Your current subscription will end "+innovator_expiry_date);
                        var years = total_innovator_cost/1000;
                        yearsEndDate = addDays(new Date(formatDate(innovator_expiry_date)), years * 365);
                        $("#subs_end_date_with_years_renew").text("The selected subscription will end on "+yearsEndDate);
                    }
                    else{
                        tempFunction(chosen_price);
                    }
                }
            });
        };
    });

    $("#cancel-button-2").click(function(){
        $("#id-renew-continue-next-steps-popup").modal('hide');
        renewPlanYearsSelect.empty();
    });

    $('#myModalSupp').on('shown.bs.modal', function () {
        $('input[type=radio]').click(function() {
            chosen_downgrade_plan = $(this).val();
        });
    });

    $('#id-downgrade-popup').on('shown.bs.modal', function(){
        $('input[type=radio]').click(function() {
            if($('#id-downgrade-popup').hasClass('show')){
                is_downgrade = $(this).val();
            }
        });

        $('#continue-downgrade-button-1').click(function() {
            if(is_downgrade == 'Yes'){
                $('#id-downgrade-yes-popup').modal('show');
                $("#id-downgrade-yes-sub-end").text("Your current subscription will end on "+formatDate(innovator_expiry_date));
                $("#id-downgrade-yes-extend-sub-end").text("isUD does not offer refunds, as per our terms of use. Downgrading your membership level will extend the end date of your new SUPPORTER subscription to "+addDays(new Date(),  Math.round(getDateDiff(innovator_expiry_date))*2));
            }else{
                $('#id-downgrade-popup').modal('hide');
            }
        });
    });

    $('#id-downgrade-yes-popup').on('shown.bs.modal', function (){

        $('input[type=radio]').click(function() {
            if($('#id-downgrade-yes-popup').hasClass('show')){
                is_downgrade_final = $(this).val();
            }
        });

        $('#continue-downgrade-button-2').click(function() {
            if(is_downgrade_final == 'Yes'){
                $.post("API.php", {dashboard: "FREE_DOWNGRADE", innv_expiry_date: innovator_expiry_date, purchase_plan: "Supporter", email_id_in_db: user_email_id} , function (data) {
                        
                },"json");

                $.post("API.php", { dashboard: "SUBSCRIPTION_TYPE"}, function (data) {
                    if(data.response){
                        plan_type = data.subscription_type;
                        supporter_expiry_date = data.supporter_expiry_date;
                        innovator_expiry_date = data.innovator_expiry_date;
                        location.reload();
                    } else {
                        data.message = "There is something wrong. Please try again";
                        console.log(data.message);
                    }
                },"json");
            }else{
                $('#id-downgrade-yes-popup').modal('hide');
            }
        });
    });

    $('#id-upgrade-membership-popup-less_than_90').on('shown.bs.modal', function () {

        $("#continue-button-less-than-90").click(function(){
            if(sub_now_or_later == "today"){
                //total_innovator_cost = amountToBePaidToday;
            }else{
                chosen_price_plan = "subLater";
            }
            tempFunction(chosen_price);
        });

        $('input[type=radio]').click(function() {
            if($('#id-upgrade-membership-popup-less_than_90').hasClass('show')){
                sub_now_or_later = $(this).val();
            }
        });

        $('#upgrade-plan-less-than-90').change(function(){ 
            if(supporter_expiry_date != null && innovator_expiry_date==null){
                total_innovator_cost = parseInt($(this).val());
                var years = total_innovator_cost/1000;
                yearsEndDate = addDays(new Date(formatDate(supporter_expiry_date)), years * 365);
                $("#subs_end_date_with_years_less_than_90").text("The selected subscription will end on "+yearsEndDate);
            }
        });

    });

    //Renew Continue Next Steps PopUp
    $('#id-renew-continue-next-steps-popup').on('shown.bs.modal', function () {

        $('#renewPlan').change(function(){ 
            if(innovator_expiry_date != null && supporter_expiry_date==null){
                var cost_key;
                cost_key = renewPlanYearsSelect.val();
                total_innovator_cost = parseInt(cost_options2[cost_key].split('$')[1]);
                var years = total_innovator_cost/1000;
                yearsEndDate = addDays(new Date(formatDate(innovator_expiry_date)), years * 365);
                $("#subs_end_date_with_years_renew").text("The selected subscription will end on "+yearsEndDate);
            }else if(supporter_expiry_date != null && innovator_expiry_date==null){
                var cost_key;
                cost_key = renewPlanYearsSelect.val();
                total_supporter_cost = parseInt(cost_options3[cost_key].split('$')[1]);
                var years = total_supporter_cost/500;
                yearsEndDate = addDays(new Date(formatDate(supporter_expiry_date)), years * 365);
                $("#subs_end_date_with_years_renew").text("The selected subscription will end on "+yearsEndDate);
            }
            localStorage.setItem("dateIfUpgradedTodayOrYears", yearsEndDate);
        });

        $("#continue-button-2").click(function(ev){
            if(innovator_expiry_date != null && supporter_expiry_date==null){
                localStorage.setItem("total_amount_due", total_innovator_cost);
                localStorage.setItem("years", total_innovator_cost/1000);
                tempFunction(chosen_price);
            }else if(supporter_expiry_date != null && innovator_expiry_date==null){
                localStorage.setItem("total_amount_due", total_supporter_cost);
                localStorage.setItem("years", total_supporter_cost/500);
                tempFunctionForSupp();
            }
        });
    });

    // Upgrade PopUp
    $('#id-upgrade-membership-popup').on('shown.bs.modal', function () {
        var cost_key;
        upgradePlanYearsSelect.change(function(){ 
            cost_key = upgradePlanYearsSelect.val();
            if(expiryStatus == "Before90"){
                total_innovator_cost = parseInt(cost_options[cost_key].split('$')[1]);
            }else{
                total_innovator_cost = parseInt(cost_options2[cost_key].split('$')[1]);
            }
            yearsEndDate = convert(calculate_date_after_proration(total_innovator_cost, supporter_expiry_date));
            $("#subs_end_date_with_years").text("The selected subscription will end on "+yearsEndDate);
        });

        $('input[type=radio]').click(function() {
            if($('#id-upgrade-membership-popup').hasClass('show')){
                $('#continue-button').prop('disabled', false);
                chosen_price_plan = $(this).val();
            }
        });

        $("#continue-button").click(function(ev){

            $("#id-upgrade-membership-popup").modal('hide');
            if(chosen_price_plan == "today"){
                total_innovator_cost = amountToBePaidToday;
                if(total_innovator_cost == 0){
                    $.post("API.php", {dashboard: "FREE_UPGRADE", sup_expiry_date: supporter_expiry_date, purchase_plan: "Innovator", email_id_in_db: user_email_id} , function (data) {
                        
                    },"json");
    
                    $.post("API.php", { dashboard: "SUBSCRIPTION_TYPE"}, function (data) {
                        if(data.response){
                            plan_type = data.subscription_type;
                            supporter_expiry_date = data.supporter_expiry_date;
                            innovator_expiry_date = data.innovator_expiry_date;
                            location.reload();
                        } else {
                            data.message = "There is something wrong. Please try again";
                        }
                    },"json");
                }else{
                    tempFunction(amountToBePaidToday);
                }
            }else{
                tempFunction(total_innovator_cost);
            }

            if(chosen_price_plan == "today"){
                if(expiryStatus == "Before90"){
                    var temp = total_innovator_cost - 500;
                    localStorage.setItem("years", temp/1000);
                }else{
                    localStorage.setItem("years", total_innovator_cost/1000);
                }
                localStorage.setItem("total_amount_due", total_innovator_cost);
                localStorage.setItem("dateIfUpgradedTodayOrYears", todayEndDate);
            }else{
                if(expiryStatus == "Before90"){
                    var temp = total_innovator_cost - 500;
                    localStorage.setItem("years", temp/1000);
                }else{
                    localStorage.setItem("years", total_innovator_cost/1000);
                }
                localStorage.setItem("total_amount_due", total_innovator_cost);
                localStorage.setItem("dateIfUpgradedTodayOrYears", yearsEndDate);
            }
        });
    });

    $('#slct-for-supporter').change(function(){ 
        var value = $(this).val();
        updateSupporterTotalCost(value);
    });

    $('#slct-for-innovator').change(function(){ 
        var value = $(this).val();
        updateInnovatorTotalCost(value);
    });
}

function calculateResidueValues(){
    var date1 = new Date(formatDate(supporter_expiry_date));
    var date2 = new Date();
    var diff = date1.getTime() - date2.getTime();
    //var diff = date1.getTime() - 1634107509000; // Oct 13th, 2021 - One year exactly from subscription.
    //var diff = date1.getTime() - 1647153909000; // March 13th, 2022 - One and half year from subscription.
    //var diff = date1.getTime() - 1668494709000; // Nov 15th, 2022 - Too show the supporter is updated to innovator after sub ends fr supporter.
    var diff_in_days = diff / (1000 * 3600 * 24);
    var credit_left = ((500/365) * (diff_in_days));
    $(".form-check-label_desc").text("You have "+Math.round(diff_in_days)+" days left in your subscription plan and the");
    $(".form-check-label_desc2").text("remaining credit amount as of today is $"+Math.round(credit_left));
}

function getDateDiff(date){
    var date1 = new Date(formatDate(date));
    var date2 = new Date();
    var diff = date1.getTime() - date2.getTime();
    var diff_in_days = diff / (1000 * 3600 * 24);
    return diff_in_days;
}

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDateDiffBetweenDatesInYears(date1){
    var future_date = new Date(formatDate(date1));
    //Testing - Remove it later
    var date = new Date();

    const _MS_PER_DAY = 31536000000;

    //var diff = future_date.getTime() - date.addDays(2).getTime();
    //var diff2 = future_date.getTime() - date.getTime();

    //var diff_in_days = diff / (1000 * 3600 * 24);
    //var diff_in_days2 = diff2 / (1000 * 3600 * 24);

    //console.log(diff_in_days/365);
    //console.log(diff_in_days2/365);
    //return diff_in_days/365;


    var ynew = future_date.getFullYear();
    var mnew = future_date.getMonth();
    var dnew = future_date.getDate();
    var yold = date.getFullYear();
    var mold = date.getMonth();
    var dold = date.getDate();

    const utc1 = Date.UTC(yold, mold, dold);
    const utc2 = Date.UTC(ynew, mnew, dnew);
    console.log(((utc2 - utc1) / _MS_PER_DAY));
    return ((utc2 - utc1) / _MS_PER_DAY);
}

function addDays(date, days){
    return convert(new Date(date.getTime() + days*24*60*60*1000));
}

function convert(str) {
    var date = new Date(str),
      mnth = ("0" + (date.getMonth() + 1)).slice(-2),
      day = ("0" + date.getDate()).slice(-2);
    return [mnth, day, date.getFullYear()].join("/");
}

function convertToYYYYMMDD(str) {
    var doo = new Date(str);
    var date = new Date(doo.getTime() - doo.getTimezoneOffset() * -60000),
      mnth = ("0" + (date.getMonth() + 1)).slice(-2),
      day = ("0" + date.getDate()).slice(-2);
    return [date.getFullYear(), mnth, day].join("/");
}

function formatDate(inputDate) {
    inputDate = convertToYYYYMMDD(inputDate);
    var splitDate = inputDate.split('/');
    if(splitDate.count == 0){
        return null;
    }
    var year = splitDate[0];
    var month = splitDate[1];
    var day = splitDate[2]; 
    return month + '/' + day + '/' + year;
}

function calculate_date_after_proration(chosen_price, supporter_expiry_date){
    no_of_days_left = getDateDiff(supporter_expiry_date);
    console.log(no_of_days_left);
    amount_due = ((500/365) * (no_of_days_left)) + chosen_price; 
    innovator_subs_days_after_proration = ((amount_due/10) * 365)/100;
    var some_date = new Date();
    some_date.setDate(some_date.getDate() + Math.round(innovator_subs_days_after_proration));
    return some_date;
    //$timestamp_now = 1634107509; // Oct 13th, 2021 - One year exactly from subscription.
    //$timestamp_now = 1647153909; // March 13th, 2022 - One and half year from subscription.
    //$timestamp_now = 1668494709; // Nov 15th, 2022 - One and half year from subscription.
}

function calculate_amount_due(chosen_price, supporter_expiry_date){
    no_of_days_left = Math.round(getDateDiff(supporter_expiry_date));
    amount_due = ((500/365) * (no_of_days_left)) + chosen_price; 
    return amount_due;
}

function tempFunction(chosen_price){
    //var ub_checkout_form = $('<form></form>');
    var attributes_map = new Object;
    attributes_map["add"] = "1";
    attributes_map["item_name"] = "isUD Innovator Membership";
    attributes_map["service_type_code"] = service_type_code;
    attributes_map["site_code"] = site_code;
    attributes_map["ubf_account"] = ubf_account;
    attributes_map["return_url"] = return_url;
    attributes_map["quantity"] = "1";
    attributes_map["silent_post"] = silent_post_test_url;
    attributes_map["amount"] = total_innovator_cost;
    attributes_map["custom[email_id_in_db]"] = user_email_id;
    attributes_map["custom[chosen_price_plan]"] = chosen_price_plan;
    attributes_map["custom[supporter_expiry_date]"] = supporter_expiry_date;
    attributes_map["custom[innovator_expiry_date]"] = innovator_expiry_date;
    attributes_map["custom[plan_type]"] = plan_type;
    attributes_map["custom[chosen_price]"] = chosen_price;
    // For pre populating billing information in UBF checkout page - Start
    attributes_map["billing_first_name"] = "";
    attributes_map["billing_last_name"] = "";
    attributes_map["billing_address"] = "";
    attributes_map["billing_city"] = "";
    attributes_map["billing_state"] = "";
    attributes_map["billing_zip"] = "";
    attributes_map["billing_country"] = "";
    attributes_map["billing_email"] = "";
    attributes_map["billing_phone"] = "";
    localStorage.setItem("currentMemberShip", "Innovator");
    localStorage.setItem("billingInfo", JSON.stringify(attributes_map));
    window.location.href = 'memberShipSubscription.php';
    return;
}

function tempFunctionForSupp(){
        //var ub_checkout_form = $('<form></form>');
        var attributes_map = new Object;
        attributes_map["add"] = "1";
        attributes_map["item_name"] = "isUD Supporter Membership";
        attributes_map["service_type_code"] = service_type_code;
        attributes_map["site_code"] = site_code;
        attributes_map["ubf_account"] = ubf_account;
        attributes_map["return_url"] = return_url;
        attributes_map["quantity"] = "1";
        attributes_map["silent_post"] = silent_post_test_url;
        attributes_map["amount"] = total_supporter_cost;
        attributes_map["custom[email_id_in_db]"] = user_email_id;
        attributes_map["custom[supporter_expiry_date]"] = supporter_expiry_date;
        attributes_map["custom[innovator_expiry_date]"] = innovator_expiry_date;
        attributes_map["custom[plan_type]"] = plan_type;
        attributes_map["custom[chosen_price_plan]"] = chosen_price_plan;
        attributes_map["custom[chosen_price]"] = chosen_price;
        attributes_map["custom[chosen_downgrade_plan]"] = chosen_downgrade_plan;
        // For pre populating billing information in UBF checkout page - Start
        attributes_map["billing_first_name"] = "";
        attributes_map["billing_last_name"] = "";
        attributes_map["billing_address"] = "";
        attributes_map["billing_city"] = "";
        attributes_map["billing_state"] = "";
        attributes_map["billing_zip"] = "";
        attributes_map["billing_country"] = "";
        attributes_map["billing_email"] = "";
        attributes_map["billing_phone"] = "";
        localStorage.setItem("currentMemberShip", "Supporter");
        localStorage.setItem("billingInfo", JSON.stringify(attributes_map));
        window.location.href = 'memberShipSubscription.php';
        return;
}

function updateSupporterTotalCost(years){
    const base_cost = 500;
    $('#cost-in-dollars-supporter').html('$'+base_cost * years);
    total_supporter_cost = getTotalCost("Supporter", years);
}

function updateInnovatorTotalCost(years){
    const base_cost = 1000;
    $('#cost-in-dollars-innovator').html('$'+base_cost * years);
    total_innovator_cost = getTotalCost("Innovator", years);
}

function getTotalCost(plan, years){
    if(plan=="Supporter"){
        return 500 * years;
    }else if(plan=="Innovator"){
        return 1000 * years;
    }
}

var leapYear = function(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

function getAmoutAndStatus(supporter_expiry_date){
    // Within 90 days of purchase
    var daysFromPurchase  = Math.round(getDateDiff(upgrade_date)) * -1;
    var daysLeftForExpiry = Math.round(getDateDiff(supporter_expiry_date));
    var isBeforeNinentyDays = daysFromPurchase <= 90;
    var isBeforeTwoYears = daysLeftForExpiry > 365 && daysLeftForExpiry < 730;
    
    if(isBeforeNinentyDays || isBeforeTwoYears){
        console.log("Before 90");
        amountToBePaidToday = 500;
        baseAmountForFuture = 500;
        expiryStatus = "Before90";
        return;
    }

    // More than 2 years left

    if(daysLeftForExpiry >= 730){
        console.log("MoreThan2");
        amountToBePaidToday = 0;
        baseAmountForFuture = 0;
        expiryStatus = "MoreThan2";
        return;
    }

    // Less than 90 days left
    
    if(daysLeftForExpiry <= 90){
        console.log("LessThan90Left");
        amountToBePaidToday = 1000;
        baseAmountForFuture = 0;
        expiryStatus = "LessThan90Left";
        return;
    }

    // > 90 days left before expiry and > 90 days from the time of purchase 
    var isBetweenNinetyDays = daysFromPurchase > 90 && daysLeftForExpiry > 90 && daysLeftForExpiry <= 365;
    if(isBetweenNinetyDays){
        console.log("InBetween90");
        amountToBePaidToday = 1000;
        baseAmountForFuture = 0;
        expiryStatus = "InBetween90";
        return;
    }
}
 