// var building_type;
// var sqfootage;
// var submission_type;
var total_cost; 
var building_area;
var site_area;
var params;
var project_certification_cost;
var certification_type;
var silent_post_test_url="https://thisisud.com/dashboard/projectSubmissionCallBack.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 uds_header_image_url="https://www.udeworld.com/uds/V3/images/header.4e87d818.png";
var service_type_code="7700";
var ubf_account="9316204381";
var site_code="1290";
$(document).ready(function(){
    
    
    building_type = $("#UD-payments-buildingtype");
    building_area = $("#UD-payments-buildingarea");
    // sqfootage = $("#UD-payments-sqfootage");
    // submission_type = $("#UD-payments-submission-type");
    site_area = $("#UD-payments-sitearea");
    // total_cost = $("#UD-payments-cost");

    params={};window.location.search.replace(/[?&;#]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});

    if(params.redir){
        redir_addr = params.redir;
    }

    /*fetching values for project summary from database*/
    if(params&&params.p!=""){
        // console.log("params: "+params.p);
         $.post("API.php",{payments: "GET_BILLING", id: params.p}, function(data){
            populate_fields(data);
        }, "json");

        // Get ubf billing information 
        $.post("API.php",{payments: "GET_UBF_BILLING_INFO", id: params.p}, function(data){
//            console.log(JSON.stringify(data));
            handle_billing_info(data);
        }, "json");

    }
    
    $("#id-project-overview-bclink").attr("href", "projectOverview.php?edit=true&id="+params.p);

    $("#id-project-overview-bclink").attr("href", "projectOverview.php?edit=true&id="+params.p);

    /*verfies the information, then calls the api.php. API will call insert billing information function.  
    Once insertion into order and billing table is succesful, then the page will be redirected to purchase.php
    */
    $("#payment-billing-submit").on('click',function(){
        var firstname  = $("#payment-firstname").val();
        var lastname   = $("#payment-lastname").val();
        var address    = $("#payment-address").val();
        var city       = $("#payment-city").val();
        var state      = $("#payment-state").val();
        var zip        = $("#payment-zip").val();
        var country    = $("#payment-country").val();
        var email      = $("#payment-email").val();
        var phone      = $("#payment-phone").val();
        var description = $("#UD-payments-submission-type").text();
        // var cost        = $("#UD-payments-cost").html();
        //console.log(cost);
        // Code to call UBF checkout page - START
        var ub_checkout_form = $('<form></form>');
        var attributes_map = new Object;
        attributes_map["add"] = "1";
        attributes_map["amount"] = total_cost;
        attributes_map["item_name"] = certification_type;
        attributes_map["service_type_code"] = service_type_code;
        attributes_map["site_code"] = site_code;
        attributes_map["ubf_account"] = ubf_account;
        var return_url = "https://thisisud.com/dashboard/PaymentReceipt.php?edit=true&id="+params.p;
        console.log(return_url);
        attributes_map["return_url"] = return_url;
        attributes_map["quantity"] = "1";
        attributes_map["header_image"] = uds_header_image_url;
        attributes_map["silent_post_test"] = silent_post_test_url;
        // For pre populating billing information in UBF checkout page - Start
        attributes_map["billing_first_name"] = firstname;
        attributes_map["billing_last_name"] = lastname;
        attributes_map["billing_address"] = address;
        attributes_map["billing_city"] = city;
        attributes_map["billing_state"] = state;
        attributes_map["billing_zip"] = zip;
        attributes_map["billing_country"] = country;
        attributes_map["billing_email"] = email;
        attributes_map["billing_phone"] = phone;
        attributes_map["custom[project_id]"] = params.p;
        attributes_map["custom[project_submission_type]"] = certification_type;
        attributes_map["custom[final_cert_payment]"] = finalcertification_payment;
        attributes_map["custom[pre_cert_payment]"] = precertification_payment;
        console.log(JSON.stringify(attributes_map));
        
        // For pre populating billing information in UBF checkout page - End
        ub_checkout_form.attr("method", "post");
        ub_checkout_form.attr("action", ub_checkout_url);

        $.each(attributes_map, function(key, value) {
        var field = $('<input></input>');
        // console.log("Adding : "+key);
        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);
        console.log(JSON.stringify(key));
        console.log(JSON.stringify(value));
        ub_checkout_form.append(field);
        });
        $(document.body).append(ub_checkout_form);
        // alert("Before Entered")
        

        if(validatename(firstname) && validatename(lastname) && validateaddress(address) && validatecity(city)
         && validatecity(state) && validatecity(country) && validatezip(zip) && validateemail(email)
          && validatephone(phone) && params && params.p!=""){
            // alert("After Entered")
            // var pay_data = new Object;

            // pay_data['billing_first_name']  = firstname;
            // pay_data['billing_last_name']   = lastname;
            // pay_data['billing_address']    = address;
            // pay_data['billing_city']       = city;
            // pay_data['billing_state']      = state;
            // pay_data['billing_zip']        = zip;
            // pay_data['billing_country']    = country;
            // pay_data['billing_email']      = email;
            // pay_data['billing_phone']      = phone;
            // pay_data['project_id'] = params.p;
            // //console.log("pay_data:"+pay_data['firstname']+","+pay_data['lastname']+","+pay_data['address']+","+pay_data['city']+","+pay_data['state']+","+pay_data['zip']+","+pay_data['country']+","+pay_data['email']+","+pay_data['phone']+","+pay_data['description']+","+pay_data['cost']+","+pay_data['project_id']);
            // // alert(JSON.stringify(pay_data));
            // console.log("Sorry")
            // $.post("API.php",{payments: "SUBMIT_BILLING_INFO", data: pay_data}, function(data){
                //  alert(data);
                //  data = JSON.parse(data);
                //  if(data.response){
                     console.log(JSON.stringify(ub_checkout_form))
                    //  alert("All Sett!")
                     ub_checkout_form.submit();
                // }else{
                //         alert("Error while creating order");
                // }                       
                        
            //  });
        }   
    });

    $("#payment-backbtn").on('click', function(){
        document.location.replace(document.referrer);
    });

});


/*populate project summary fields*/
function populate_fields(data){
    if(data == null || data[0] == null)
        return;

    data = data[0];
  //  console.log("data: "+JSON.stringify(data));
    var buildingtypes = data.building_type;
    buildingtypes = buildingtypes.split(";");
    jQuery.each(buildingtypes, function(i, val){
        if(val!=""){
            $(building_type).append("<p>"+val+"</p>");
        }
    });
    // // console.log("buildings: "+buildingtypes);
    // var floor_area;
    // if(data.habitable_floor_area.indexOf("-")>=0)
    //     floor_area = site_area_map[data.habitable_floor_area];
    // else
    //     floor_area = data.habitable_floor_area+" sq.ft";
    // sqfootage.text(floor_area);
    $("#UD-payments-projectname").append("<p style=\"padding-left:180px;\">"+data.project_title+"</p>");
    // project_certification_cost = data.project_certification_cost;
    // $("#UD-payments-cost").append("<p>$"+data.project_certification_cost+"</p>");
    $("#UD-payments-buildingarea").append("<p  style=\"padding-left:180px;\">"+data.habitable_floor_area+" sq. ft </p>");
    $("#UD-payments-sitearea").append("<p  style=\"padding-left:180px;\">"+data.site_area+" sq. ft </p>");
    // if(data.project_submission_type == 0){
    //     certification_type = "Self-assessment";
    //     $("#UD-payments-submission-type").append("<p> Self-assessment </p>");
    // }else{
        certification_type = "isUD Certification";
        $("#UD-payments-submission-type").append("<p> isUD Certification </p>");
    //}
    // console.log(sqfootage.val());

    var buildArea = parseInt(data.habitable_floor_area);
    // alert("BA  " + buildArea);
    var siteArea = parseInt(data.site_area); 
    // alert("SA  " + siteArea);  
    var precertification = data.pre_certification;
    var precertification_paid = data.pre_certification_paid;
    var finalcertification_paid = data.final_certification_paid;
    // alert(precertification_paid);
    // alert(finalcertification_paid);
    // alert("PRE  " + precertificationRadio);
    total_cost = parseInt(displayCalculations(buildArea, siteArea, precertification,precertification_paid, finalcertification_paid));
}

// Check if transaction has been already made for this project id
function handle_billing_info(data){
    console.log(JSON.stringify(data));
    var payment_result = data['payment_result'];
    if(payment_result == 0)
        return;
    else{
        if(payment_result == 1 ){
            var order_id = data['order_id'];
            var project_id = data['project_id'];
            var url = $(location).attr('href').split('payments')[0]+"payment_success.php?p="+encodeURIComponent(project_id)+"&ord="+encodeURIComponent(order_id);
            window.location.href = url;
        }
        else{
            // Display transaction failed/declined message
            alert("Your previous transaction failed/declined.");
        }
    }
}


/*validate given user info*/
function validatename(name){
    var filter = /^([a-zA-Z,.\-'\s\(\)]{3,20})$/;
    if(name!= null && name!= ''){
        if(filter.test(name)){
            return true;
        }
        alert("name invalid");
        return false;
    }
    alert("name invalid");
    return false;
}

function validateaddress(address){
    //var filter = /^\d+\s[A-z]+\s[A-z]$/;
    var filter = /^[a-zA-Z0-9\s,'-]*$/;
    if(address!=null && address != ''){
        if(filter.test(address)){
            return true;
        }
        alert("Address format invalid");
        return false;
    }
    alert("Address format invalid");
    return false;
}

function validatecity(city){
    var filter = /^[a-zA-z] ?([a-zA-z]|[a-zA-z] )*[a-zA-z]$/;
    if(city!= null && city!= ''){
        if(filter.test(city)){
            return true;
        }
        alert("City/state/country format invalid");
        return false;
    }
    alert("city/state/country format invalid");
    return false;
} 

function validateemail(email){
    var filter = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(email!=null && email!= '' && filter.test(email)){
            return true; 
    }
    alert("invalid email address format");
    return false;
}

function validatephone(phone){
    var filter = /(^[0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
    if(phone!= null && phone!= '' && filter.test(phone)){
        return true;
    }
    alert("phone number format invalid");
    return false;
}

function validatezip(zip){
    var filter = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

    if(zip!=null && zip!= '' && filter.test(zip)){
        return true;
    }
    alert("wrong zip code format");
    return false;
}


//Calculator function
function displayCalculations(buildArea, siteArea, precertification, precertification_paid, finalcertification_paid){
    var checked = precertification.split(",");
    checked.pop();
  //  alert(checked);
   // alert(checked.length);
    var buildingamt = 0;
    var siteamt = 0;

    var precertbuildingamt = 0;
    var precertsiteamt = 0;
    var onsitebuildingamt = 0;
    var onsitesiteamt = 0;
    
    if(buildArea > 1 && buildArea <= 100000){
        buildingamt += 4000;
    }
    else if(buildArea > 100000){
        buildingamt += 4000;
        buildadds = (buildArea - 100000) / 10000;
        //alert(adds);
        buildingamt += 200 * Math.ceil(buildadds);
    }
    
    if(siteArea >= 3 && siteArea <= 20){
        siteamt += 1000;
    }
    else if(siteArea > 20){
        siteamt += 1000;
        siteadds = (siteArea - 20);
        //alert(siteadds);
        siteamt += 40 * (siteadds);
    }

    if(checked.length == 0){
        precertbuildingamt = 0;
        precertsiteamt = 0;
        onsitebuildingamt = 0;
        onsitesiteamt = 0;
        precertification_payment = "0";
        finalcertification_payment = "0";
    }
    else if(checked.length == 1)
    {
        if(checked.includes("1")){
      //      alert("Inside 1");
            var container = document.getElementById("pre-cert-div");
            container.style.display = "block";
            precertbuildingamt = buildingamt/2;
            precertsiteamt = siteamt/2; 
            onsitebuildingamt = 0;
            onsitesiteamt = 0;
            precertification_payment = "1";
            finalcertification_payment = "0";
            $('#id-precert-buidling').html('$ '+precertbuildingamt);
            $('#id-precert-site').html('$ '+precertsiteamt);
            $('#precertcontainer').hide();
        }
        else if(checked.includes("2")){
       //     alert("Inside 2");
            var container = document.getElementById("on-site-div");
            container.style.display = "block";
            precertbuildingamt = 0;
            precertsiteamt = 0; 
            onsitebuildingamt = buildingamt;
            onsitesiteamt = siteamt;
            finalcertification_payment = "1";
            precertification_payment = "0";
            $('#id-onsite-buidling').html('$ '+onsitebuildingamt);
            $('#id-onsite-site').html('$ '+onsitesiteamt);
            $('#onsitecontainer').hide();
        }   
    } else{
     //   alert("Inside 3");
        var container = document.getElementById("pre-cert-div");
        container.style.display = "block";
        var container1 = document.getElementById("on-site-div");
        container1.style.display = "block";
        precertbuildingamt = buildingamt/2;
        precertsiteamt = siteamt/2; 
        onsitebuildingamt = buildingamt;
        onsitesiteamt = siteamt;
        precertification_payment = "1";
        finalcertification_payment = "1";

        $('#id-onsite-buidling').html('$ '+onsitebuildingamt);
        $('#id-onsite-site').html('$ '+onsitesiteamt);
        $('#id-onsite-total').html('$ '+(onsitebuildingamt+onsitesiteamt));
        $('#id-precert-buidling').html('$ '+precertbuildingamt);
        $('#id-precert-site').html('$ '+precertsiteamt);
        $('#id-precert-total').html('$ '+(precertbuildingamt+precertsiteamt));
        var x = document.getElementById("onsitecontainer");
        x.style.background = "#f9f9f9";
        var y= document.getElementById("precertcontainer");
        y.style.background = "#f9f9f9";
        $('#id-total-est').attr("style", "float:right; padding-right:78px;");
    }

    var totalamt = onsitebuildingamt+onsitesiteamt+precertbuildingamt+precertsiteamt;
    if(precertification_paid == 1){
        console.log("Precertification amount paid");
        totalamt = totalamt - precertbuildingamt - precertsiteamt;
    }
    if(finalcertification_paid == 1){
        console.log("Final certification amount paid");
        totalamt = totalamt - onsitebuildingamt - onsitesiteamt;
    }
    $('#id-total-est').html('$ '+totalamt);
    return totalamt;
    
};