
/// <reference path="../../typings/jquery/jquery.d.ts"/>

var redir_addr = "";
var projectTitle;
var isUDCertification;
var projectOwner;
var projectArchitect;
var habitableFloorArea;
var siteArea;
var preCertification;
var pre_certification_paid;
var final_certification_paid;
var projectCost;
var projectAStartDate;
var projectAEndDate;
var projectScope;

var contactPerson;
var contactEmail;
var contactTelephone;
var addressLine1;
var addressLine2;
var projectCity;
var projectState;
var projectCountry;
var projectZipcode;
var projectType;

var editMode = false;
var projectId = "";

/* Capatilize the first char */
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
 

$(document).ready(function () {
    
    var user_email = "";
    $('.cl-buttons-second-nav').hide();

    $("img").unveil();
    $("img").trigger("unveil");
    /*Replace the create project icon in navigation bar to active create project icon*/
    $("#id-img-navbar-p-create").attr("src", "images/createproject_icon_active.83ca6dd8.png");
    
    var params={};
    window.location.search.replace(/[?&;#]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});
    var path = window.location.pathname;
    path = path.substring(path.lastIndexOf("/")+1);

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

    $("#id-new-project-inp-p-contact-telephone").intlTelInput({
        nationalMode: true,
        utilsScript: "JS/intlTelInputUtils.70e04798.js" // just for formatting/placeholders etc
    });

    //For Calculator
      $("input[name='id-calculator-inputs']").keyup(function(){
        displayCalculations(pre_certification_paid, final_certification_paid);
      });
  
      $("input[name='certtype']").click(function(){
        displayCalculations(pre_certification_paid, final_certification_paid);
      })

    //fields
    projectTitle = $("#id-new-project-inp-p-title");
    isUDCertification = $("input[name=potentCertificate]:checked");
    projectOwner = $("#id-new-project-inp-p-owner");
    projectArchitect = $("#id-new-project-inp-p-architect");
    habitableFloorArea = $("#id-buildingArea");
    siteArea = $("#id-siteArea");
    preCertification = $("input[name='radio-calculator']:checked");
    // projectCost = $("#id-new-project-inp-p-cost");
    projectAStartDate = $("#id-new-project-inp-p-a-start-date");
    projectAEndDate = $("#id-new-project-inp-p-a-end-date");
    projectScope = $("input[name=name-radio-p-scope]:checked");

    contactPerson = $("#id-new-project-inp-p-contact-person");
    contactEmail = $("#id-new-project-inp-p-contact-email");
    contactTelephone = $("#id-new-project-inp-p-contact-telephone");
    addressLine1 = $("#id-new-project-inp-p-address-line-1");
    addressLine2 = $("#id-new-project-inp-p-address-line-2");
    projectCity = $("#id-new-project-inp-p-city");
    projectState = $("#id-new-project-inp-p-state");
    projectCountry = $("#id-new-project-inp-p-country");
    projectZipcode = $("#id-new-project-inp-p-zipcode");

    projectType = $("#id-select-p-type-project");

    if(params.edit && params.edit === "true" && params.p && params.p != ""){
        editMode = true;
        $(".cl-span-site-title").html('Edit Profile');
        $('title').replaceWith('<title>Edit Profile</title>');
        $.post("API.php",{project: "DETAILS", id: params.p}, function(data){
            populateFields(data);
        }, "json");

        $('.cl-buttons-second-nav').show();
        projectId = params.p;
        attachOverviewEventListener($('#id-global-container'), true, projectId);
    }

    // $(".form-check-input").change(function(){
    //     var val = $(this).val();
    //     var parentHeaderElem = $(this).parent().parent().parent().find("span");
    //     var parentVal = $(parentHeaderElem).attr("data-checked-vals");
    //     parentVal = typeof parentVal === "undefined" ? "": parentVal;
    //     var parentValArr = parentVal === ""? [] : parentVal.split(",");
    //     if(parentValArr.includes(val)){
    //         parentValArr = parentValArr.filter(function(v){
    //             return (v !== val);                
    //         });
    //     }

    //     if($(this).prop("checked")){
    //         parentValArr.push(val);
    //     }
        
    //     $(parentHeaderElem).attr("data-checked-vals",parentValArr.toString());
    // });

    $("#id-btn-new-project-submit").click(function(){              
        //Values
        var projectTitleVal = $("#id-new-project-inp-p-title").val();
        var isUDCertificationVal = $("input[name='potentCertificate']:checked").val();        
        var projectOwnerVal = $("#id-new-project-inp-p-owner").val();
        var projectArchitectVal = $("#id-new-project-inp-p-architect").val();
        var habitableFloorAreaVal = $("#id-buildingArea").val();
        var siteAreaVal = -1;
        var siteAreaVal = $("#id-siteArea").val();
        siteAreaVal = siteAreaVal == "" ? 0:siteAreaVal;
        
        var preCertificationVal="";
        var markedCheckbox = document.getElementsByName('certtype');  
        for (var checkbox of markedCheckbox) {  
          if (checkbox.checked) { 
            // alert(checkbox.value);
            preCertificationVal+= checkbox.value + ",";
          }
        }
        
        var facilityUses="";
        var markedFacilities = document.getElementsByName('facilityuses'); 
        for (var checkbox of markedFacilities) {  
            if (checkbox.checked) {              
              facilityUses+= checkbox.value + ",";
            }
        }

        var serviceuses="";
        var markedservices = document.getElementsByName('potentService'); 
        for (var checkbox of markedservices) {  
            if (checkbox.checked) {              
              serviceuses+= checkbox.value + ",";
            }
        }

        var certificationuses="";
        var markedcertifications = document.getElementsByName('potentCertificate'); 
        for (var radio of markedcertifications) {  
            if (radio.checked) {              
              certificationuses= radio.value + ",";                          
            }
        }
        
        
        var projectAStartDateVal = $("#id-new-project-inp-p-a-start-date").val();
        var projectAEndDateVal = $("#id-new-project-inp-p-a-end-date").val();
        var projectScopeVal = $("input[name=name-radio-p-scope]:checked").val();
        var projectSubmissionTypeVal = $("input[name=name-radio-p-submission-type]:checked").val();

        var contactPersonVal = $("#id-new-project-inp-p-contact-person").val();
        var contactEmailVal = $("#id-new-project-inp-p-contact-email").val();
        var contactTelephoneVal = $("#id-new-project-inp-p-contact-telephone").intlTelInput("getNumber");
        var contactTelephoneCCodeVal = $("#id-new-project-inp-p-contact-telephone").intlTelInput("getSelectedCountryData").iso2;
        var addressLine1Val = $("#id-new-project-inp-p-address-line-1").val();
        var addressLine2Val = $("#id-new-project-inp-p-address-line-2").val();
        var projectCityVal = $("#id-new-project-inp-p-city").val();
        var projectStateVal = $("#id-new-project-inp-p-state").val();
        var projectCountryVal = $("#id-new-project-inp-p-country").val();
        var projectZipcodeVal = $("#id-new-project-inp-p-zipcode").val();
        var projectTypeVal = $("#id-select-p-type-project").val();

        //Elements
        var projectTitleElem = $("#id-new-project-inp-p-title");        
        if($("input[name=potentCertificate]:checked").val()!=undefined){
            var isUDCertificationElem = $("input[name=potentCertificate]:checked");
        }else{
            var isUDCertificationElem = $("#potentCertiContainer");
        }
        var projectOwnerElem = $("#id-new-project-inp-p-owner");
        var projectArchitectElem = $("#id-new-project-inp-p-architect");
        var habitableFloorAreaElem = $("#id-buildingArea");
        var siteAreaElem = $("#id-siteArea");
        var preCertificationElem = $("input[name='radio-calculator']:checked");
        var projectCostElem = $("#id-new-project-inp-p-cost");
        var projectAStartDateElem = $("#id-new-project-inp-p-a-start-date");
        var projectAEndDateElem = $("#id-new-project-inp-p-a-end-date");

        var contactPersonElem = $("#id-new-project-inp-p-contact-person");
        var contactEmailElem = $("#id-new-project-inp-p-contact-email");
        var contactTelephoneElem = $("#id-new-project-inp-p-contact-telephone");
        var contactTelephoneCCodeElem = $("#id-new-project-inp-p-contact-telephone");
        var addressLine1Elem = $("#id-new-project-inp-p-address-line-1");
        var addressLine2Elem = $("#id-new-project-inp-p-address-line-2");
        var projectCityElem = $("#id-new-project-inp-p-city");
        var projectStateElem = $("#id-new-project-inp-p-state");
        var projectCountryElem = $("#id-new-project-inp-p-country");
        var projectZipcodeElem = $("#id-new-project-inp-p-zipcode");
        // var projectTypeElem = $("#id-select-p-type-project");

        

       
        showErrorSpanIfEmpty(projectTitleElem);
        showErrorSpanIfEmpty(isUDCertificationElem);
        //showErrorSpanIfEmpty(projectOwnerElem);
        //showErrorSpanIfEmpty(projectArchitectElem);
        showErrorSpanIfEmpty(contactPersonElem); 
        showErrorSpanIfEmpty(contactEmailElem);
        showErrorSpanIfEmpty(contactTelephoneElem);
        showErrorSpanIfEmpty(contactTelephoneCCodeElem);
        //showErrorSpanIfEmpty(addressLine1Elem);
        //showErrorSpanIfEmpty(projectCityElem);
        //showErrorSpanIfEmpty(projectStateElem);
        //showErrorSpanIfEmpty(projectCountryElem); 
        //showErrorSpanIfEmpty(projectZipcodeElem);
        // showErrorSpanIfEmpty(projectCostElem);
        // showErrorSpanIfEmpty(habitableFloorAreaElem); 
        //showErrorSpanIfEmpty(siteAreaElem); 
        // showErrorSpanIfEmpty(projectTypeElem); 

        //  var data_package = new Object;
        //         data_package['title'] = projectTitleVal;
        //         data_package['owner'] = projectOwnerVal;
        //         data_package['architect'] = projectArchitectVal;
        //         data_package['habitable_floor_area'] = habitableFloorAreaVal;
        //         data_package['site_area'] = siteAreaVal;
        //         data_package['cost'] = projectCostVal;
        //         data_package['a_start_date'] = projectAStartDateVal;
        //         data_package['a_end_date'] = projectAEndDateVal;
        //         data_package['project_scope'] = projectScopeVal;
        //         data_package['project_submission_type'] = projectSubmissionTypeVal;
        //         data_package['project_type'] = projectTypeVal;

        //         data_package['contact_person'] = contactPersonVal;
        //         data_package['contact_email'] = contactEmailVal;
        //         data_package['contact_telephone'] = contactTelephoneVal;
        //         data_package['contact_telephone_c_code'] = contactTelephoneCCodeVal;
        //         data_package['address_line_1'] = addressLine1Val;
        //         data_package['address_line_2'] = addressLine2Val;
        //         data_package['city'] = projectCityVal;
        //         data_package['state'] = projectStateVal;
        //         data_package['country'] = projectCountryVal;
        //         data_package['zipcode'] = projectZipcodeVal;

        // alert(JSON.stringify(data_package));

        if( showErrorSpanIfEmpty(projectTitleElem) && showErrorSpanIfEmpty(isUDCertificationElem)
            && showErrorSpanIfEmpty(contactPersonElem) && showErrorSpanIfEmpty(contactEmailElem) 
            && showErrorSpanIfEmpty(contactTelephoneElem) && showErrorSpanIfEmpty(contactTelephoneCCodeElem) 
            // && showErrorSpanIfEmpty(projectTypeElem)
            /* && showErrorSpanIfEmpty(projectOwnerElem) && showErrorSpanIfEmpty(projectArchitectElem) 
            && showErrorSpanIfEmpty(addressLine1Elem) && showErrorSpanIfEmpty(projectCityElem) 
            && showErrorSpanIfEmpty(projectStateElem) && showErrorSpanIfEmpty(projectCountryElem) 
            && showErrorSpanIfEmpty(projectZipcodeElem) && showErrorSpanIfEmpty(projectCostElem)
            && showErrorSpanIfEmpty(habitableFloorAreaElem) && showErrorSpanIfEmpty(siteAreaElem) */
            // && $.isNumeric(habitableFloorAreaVal) && $.isNumeric(siteAreaVal) && $.isNumeric(projectCostVal) 
            // && ((projectAEndDateVal == '' || projectAStartDateVal == '') || (projectAEndDateVal != '' && projectAStartDateVal != '' && (new Date(projectAEndDateVal) >= new Date(projectAStartDateVal))))
            ){

                if(projectAEndDateVal == ''){
                    projectAEndDateVal = "0001:01:01";
                    
                }
                if(projectAStartDateVal == ''){
                    projectAStartDateVal = "0001:01:01";
                    
                }  
                // alert('set Start '+projectAStartDate);
                // alert('set END '+projectAEndDate);

                var data_package = new Object;
                data_package['title'] = projectTitleVal;
                data_package['owner'] = projectOwnerVal;
                data_package['architect'] = projectArchitectVal;
                data_package['habitable_floor_area'] = habitableFloorAreaVal ? habitableFloorAreaVal : 0;
                data_package['site_area'] = siteAreaVal ? siteAreaVal : 0;
                data_package['pre_certification'] =  preCertificationVal;
                data_package['project_cost'] = projectCost ? projectCost : 0;
                data_package['a_start_date'] = projectAStartDateVal;
                data_package['a_end_date'] = projectAEndDateVal;
                data_package['project_scope'] = projectScopeVal ? projectScopeVal : 0;
                data_package['project_submission_type'] = projectSubmissionTypeVal ? projectSubmissionTypeVal : 0;
                data_package['project_type'] = projectTypeVal ? projectTypeVal : 0;

                data_package['contact_person'] = contactPersonVal;
                data_package['contact_email'] = contactEmailVal;
                data_package['contact_telephone'] = contactTelephoneVal;
                data_package['contact_telephone_c_code'] = contactTelephoneCCodeVal;
                data_package['address_line_1'] = addressLine1Val;
                data_package['address_line_2'] = addressLine2Val;
                data_package['city'] = projectCityVal;
                data_package['state'] = projectStateVal;
                data_package['country'] = projectCountryVal;
                data_package['zipcode'] = projectZipcodeVal;

                // alert(data_package['a_start_date']);
                // alert(data_package['a_end_date']);

                // var b_val = "";
                // $.each($(".cl-div-new-project-building-type-sub-header"), function(index, elem){
                //     var t = typeof $(elem).attr("data-checked-vals") === "undefined" ? "": $(elem).attr("data-checked-vals");
                //     b_val += t+";";
                // });
                // b_val = b_val.substr(0, b_val.length - 1);
                // //alert(b_val);
                data_package['building_type'] = facilityUses;
                data_package['service_type'] = serviceuses;
                data_package['certification_type'] = certificationuses;
                // $("#id-new-project-tbl").css("display","none");
                // $("#id-div-new-project-progress").css("display","flex");
                
                if(editMode){
                    mode = "UPDATE_INFO";
                    msgWait = "Please wait while the project is being updated.";
                    msgSuccess = "Project saved."
                    msgFailure =  "Something went wrong! We couldn't update the project for you. Please retry in a while. Error : ";
                    data_package["id"] = params.p;
                } else {
                    mode = "CREATE";
                    msgWait = "Please wait while a project is being created.";
                    msgSuccess = "Project created."
                    msgFailure =  "Something went wrong! We couldn't create a new project for you. Please retry in a while. Error : ";
                }
                // alert(JSON.stringify(data_package));

                //$("#id-div-new-project-progress-icon").addClass("fa-spinner");
                //$("#id-div-new-project-progress-icon").addClass("fa-spin");
                //$("#id-div-new-project-progress-msg").html(msgWait);
                // alert('inside if');
                $.post("API.php", { project: mode, data: JSON.stringify(data_package) }, function (data) {
                    //$("#id-div-new-project-progress-icon").removeClass("fa-spinner");
                    //$("#id-div-new-project-progress-icon").removeClass("fa-spin");
                    if(data.response){
                        //$("#id-div-new-project-progress-icon").addClass("fa-2x");
                        //$("#id-div-new-project-progress-icon").addClass("fa-check");
                        //$("#id-div-new-project-progress-msg").html(msgSuccess);
                        // show modal dialog
                        project_id = editMode?params.p:data.project_id;                        
                        show_success_popup(msgSuccess,project_id);
                    } else {
                        //$("#id-div-new-project-progress-icon").addClass("fa-2x");
                        //$("#id-div-new-project-progress-icon").addClass("fa-close");
                        //$("#id-div-new-project-progress-msg").html(msgFailure+data.message);
                        // alert();

                        alert(msgFailure+ data.message);
                        // show_success_popup(msgSuccess)
                    }
                },"json");

        } else {
            // Show error spans
            // alert('inside else');
            var modal = $("#id-modal-create-project-error");
            $(modal).modal('show');

            var list_control = $("#id-ul-unchecked-required-project-profile-items");
            list_control.empty();
            var message="";

            if(projectTitleVal == "" || isUDCertificationVal == undefined || contactPersonVal =="" || contactEmailVal=="" || contactTelephoneVal == "" || contactTelephoneCCodeVal=="")
            {
                message="Please fill out all required fields and try again.";
                list_control.append('<li>'+message+'</li>');
            }

            // if(!$.isNumeric(projectCostVal))
            // {
            //     showErrorSpan(projectCostElem);
            //     message="Please input only numbers in Project Cost";
            //     list_control.append('<li>'+message+'</li>');
            // }
        }
    });

    $("#id-btn-new-project-clear").click(function(){
        $("#id-form-new-project-details").trigger("reset");
        $("#id-form-new-project-contact").trigger("reset");
        $("input[type='checkbox']").prop("checked",false);
    });

    // var eventData = {focus : true};
    // $("#id-register-inp-organization").focusout(eventData, validateOrganization);
    // $("#id-register-inp-firstname").focusout(eventData, validateFirstName);
    // $("#id-register-inp-middlename").focusout(eventData, validateMiddleName);
    // $("#id-register-inp-lastname").focusout(eventData, validateLastName);
    // $("#id-register-inp-email").focusout(eventData, validateEmail);
    // $("#id-register-inp-password").focusout(eventData, validatePassword);
    // $("#id-register-inp-confirmpassword").focusout(eventData, validateConfirmPassword);
    // $("#id-register-inp-securityquestion").on('changed.bs.select', validateSecurityQuestion);
    // $("#id-register-inp-securityanswer").focusout(eventData, validateSecurityAnswer);
    // $("#id-register-inp-phone").focusout(eventData, validatePhoneNumber);
    
    // var eventDataLoginUsername = {target : $("#id-login-inp-email"), focus : true};
    // var eventDataLoginPassword = {target : $("#id-login-inp-password"), focus : true};
    // $("#id-login-inp-email").focusout(eventDataLoginUsername, validateEmail);
    // $("#id-login-inp-password").focusout(eventDataLoginPassword, validatePassword);
    
    // var eventDataLoginShortUsername = {target : $("#id-login-short-inp-email"), focus : true};
    // var eventDataLoginShortPassword = {target : $("#id-login-short-inp-password"), focus : true};
    // $("#id-login-short-inp-email").focusout(eventDataLoginShortUsername, validateEmail);
    // $("#id-login-short-inp-password").focusout(eventDataLoginShortPassword, validatePassword);
    
    // $.post("API.php", { register: "QUESTIONS" }, function (data) {
    //     var container = $("#id-register-inp-securityquestion");
    //     var generated_option = '';
    //     $(container).html('');
        
    //     $.each(data, function(index,elem){
    //         generated_option += '<option value="'+elem.sl_no+'">'+elem.question+'</option>';
    //     });
    //     container.html(generated_option);
    //     $(container).selectpicker('refresh');
    // }, 'json');

});


//Calculator function
function displayCalculations(precertification_paid, finalcertification_paid){

    // alert("Pre" + precertification_paid);
    // alert("Final" + finalcertification_paid)
    var buildArea = parseInt($('#id-buildingArea').val());
    var siteArea = parseInt($('#id-siteArea').val());  
    var travelamt = $('#id-travel-cost').val();
    /*travelamt = travelamt.replace("$", "").trim();
    if(!travelamt.localeCompare("TBD")){
        travelamt = 0000;
    } else{
        travelamt = parseInt(travelamt);
    }

    var checked=[];
    var markedCheckbox = document.getElementsByName('certtype');  
    for (var checkbox of markedCheckbox) {  
      if (checkbox.checked)  
        checked.push(checkbox.value);
    }
    
    var buildingamt = 0000;
    var siteamt = 0000;

    var precertbuildingamt = 0000;
    var precertsiteamt = 0000;
    var onsitebuildingamt = 0000;
    var onsitesiteamt = 0000;
    
    if(buildArea > 1 && buildArea <= 100000){
        buildingamt += 4000;
    }
    else if(buildArea > 100000){
        buildingamt += 4000;
        buildadds = (buildArea - 100000) / 10000;
        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){
        $('#id-precert-buidling').html('$ 0000');
        $('#id-precert-site').html('$ 0000');
        $('#id-precert-total').html('$ 0000');

        $('#id-onsite-buidling').html('$ 0000');
        $('#id-onsite-site').html('$ 0000');
        $('#id-onsite-total').html('$ 0000');

        $('#id-total-est').html('$ 0000');
    }
    else if(checked.length == 1)
    {
        if(checked.includes("1")){
            precertbuildingamt = buildingamt/2;
            precertsiteamt = siteamt/2; 
            onsitebuildingamt = 0;
            onsitesiteamt = 0;
            $('#id-precert-buidling').html('$ '+precertbuildingamt);
            $('#id-precert-site').html('$ '+precertsiteamt);
            $('#id-precert-total').html('$ '+(precertbuildingamt+precertsiteamt));

            $('#id-onsite-buidling').html('$ 0000');
            $('#id-onsite-site').html('$ 0000');
            $('#id-onsite-total').html('$ 0000');
        }
        else if(checked.includes("2")){
            precertbuildingamt = 0;
            precertsiteamt = 0;
            onsitebuildingamt = buildingamt;
            onsitesiteamt = siteamt;

            $('#id-precert-buidling').html('$ 0000');
            $('#id-precert-site').html('$ 0000');
            $('#id-precert-total').html('$ 0000');

            $('#id-onsite-buidling').html('$ '+onsitebuildingamt);
            $('#id-onsite-site').html('$ '+onsitesiteamt);
            $('#id-onsite-total').html('$ '+(onsitebuildingamt+onsitesiteamt+travelamt));
           
        }   
        projectCost = onsitebuildingamt+onsitesiteamt+precertbuildingamt+precertsiteamt;
        if(precertification_paid == 1){
            console.log("Precertification Amount Paid");
            projectCost = projectCost - precertbuildingamt - precertsiteamt;
        }
        if(finalcertification_paid == 1){
            console.log("Final certification Amount Paid");
            projectCost = projectCost - onsitebuildingamt - onsitesiteamt;
        }
        // alert("Total" + projectCost);
        if(projectCost == 0){
            $('#id-total-est').html('$ 0000');
        } else {
            $('#id-total-est').html('$ '+projectCost);
        }
    }else{
        precertbuildingamt = buildingamt/2;
        precertsiteamt = siteamt/2; 
        onsitebuildingamt = buildingamt;
        onsitesiteamt = siteamt;
        $('#id-precert-buidling').html('$ '+precertbuildingamt);
        $('#id-precert-site').html('$ '+precertsiteamt);
        $('#id-precert-total').html('$ '+(precertbuildingamt+precertsiteamt));
    
        $('#id-onsite-buidling').html('$ '+onsitebuildingamt);
        $('#id-onsite-site').html('$ '+onsitesiteamt);
        $('#id-onsite-total').html('$ '+(onsitebuildingamt+onsitesiteamt+travelamt));
       
     //   projectCost = onsitebuildingamt+onsitesiteamt+precertbuildingamt+precertsiteamt+travelamt;
        projectCost = onsitebuildingamt+onsitesiteamt+precertbuildingamt+precertsiteamt;
        if(precertification_paid == 1){
            console.log("Precertification Amount Paid");
            projectCost = projectCost - precertbuildingamt - precertsiteamt;
        }
        if(finalcertification_paid == 1){
            console.log("Final certification Amount Paid");
            projectCost = projectCost - onsitebuildingamt - onsitesiteamt;
        }
        if(projectCost == 0){
            $('#id-total-est').html('$ 0000');
        } else {
             $('#id-total-est').html('$ '+projectCost);
        }
    }*/

    
    
}
/*
    Validate Register form fields  
*/

function showErrorSpanIfEmpty(elem){    
    if(!elem)
        return false;

    var parent = $(elem).parent().parent();
    var errorSpan = $(parent).find(".cl-new-project-inp-error-lbl");
    
    if(elem && $(elem).val() && $(elem).val() != '') {
        if(elem.val()=='CertificationOnly'|| elem.val()=='GuidedCertification'){
            $('#potentCertiParent').removeClass("has-danger")
        }
        else{
            $(parent).removeClass("has-danger");
            $(parent).addClass("has-success"); 
            $(elem).removeClass("form-control-danger");
            $(elem).addClass("form-control-success");
            $(errorSpan).removeClass("has-danger");
            $(errorSpan).addClass("has-success");
        }   
        return true;
    } 
    else {      
        $(parent).addClass("has-danger");
        $(parent).removeClass("has-success"); 
        $(elem).removeClass("form-control-success");
        $(elem).addClass("form-control-danger");
        $(errorSpan).addClass("has-danger");
        $(errorSpan).removeClass("has-success");
        return false;
    }
}

function showErrorSpan(elem, show){
    var span = $(elem).parent().parent().find(".cl-lbl");
    if(show){
        $(span).removeClass("has-success");       
        $(span).addClass("has-danger");
        // $(span).show();
    } else {
        $(span).removeClass("has-danger");       
        $(span).addClass("has-success");
    }
}

function populateFields(data){
    if(data == null || data[0] == null)
        return;

    data = data[0];
    console.log(data)
    projectTitle.val(data.project_title);
    projectOwner.val(data.project_owner);
    projectArchitect.val(data.project_architect);
    habitableFloorArea.val(data.habitable_floor_area);
    siteArea.val(data.site_area);
    var checkedarr = data.pre_certification.split(",");
    checkedarr.pop();
    pre_certification_paid = data.pre_certification_paid;
    final_certification_paid = data.final_certification_paid;

    if(pre_certification_paid==1){
        document.getElementById("id-precert").disabled = true;
        document.getElementById("paid-tag").style.display = "inline-block";
    }

    for(var j=0; j<checkedarr.length; j++){
        $(".cert_type_checkbox").find('input[value="'+checkedarr[j]+'"]').prop("checked",true); 
    }


    // $("input[name=radio-calculator]").filter("input[value="+data.pre_certification+"]").attr("checked", "checked");
    // $("input[name=radio-calculator]").filter("input[value="+data.pre_certification+"]").prop("checked", "checked");

    // $("input[name=name-radio-p-scope]").filter("input[value="+data.project_scope+"]").attr("checked", "checked");
    // $("input[name=name-radio-p-scope]").filter("input[value="+data.project_scope+"]").prop("checked", "checked");

    // filling in radio button for the project Submission type
    // $("input[name=name-radio-p-submission-type]").filter("input[value="+data.project_submission_type+"]").attr("checked", "checked");
    // $("input[name=name-radio-p-submission-type]").filter("input[value="+data.project_submission_type+"]").prop("checked", "checked");

    s_date = new Date(data.project_a_start_date);
    e_date = new Date(data.project_a_end_date);
    s_date_converted = s_date.getFullYear()+"-"+("0"+(s_date.getMonth()+1)).slice(-2)+"-"+("0"+s_date.getDate()).slice(-2)
    e_date_converted = e_date.getFullYear()+"-"+("0"+(e_date.getMonth()+1)).slice(-2)+"-"+("0"+e_date.getDate()).slice(-2)

    projectAStartDate.val(s_date_converted);
    projectAEndDate.val(e_date_converted);

    contactPerson.val(data.project_contact_person);
    contactEmail.val(data.project_contact_email);

    if(data.project_contact_telephone && data.project_contact_telephone != null)
        contactTelephone.intlTelInput("setNumber",data.project_contact_telephone);
    
    addressLine1.val(data.project_address_line_1);
    addressLine2.val(data.project_address_line_2);
    projectCity.val(data.project_city);
    projectState.val(data.project_state);
    projectCountry.val(data.project_country);
    projectZipcode.val(data.project_zipcode);
    projectType.val(data.project_type);


  //  alert("Retrived :: " + data.building_type);

    var facilityUses = data.building_type.split(",");
    facilityUses.pop();
    // alert(JSON.stringify(facilityUses));
    for(var j=0; j<facilityUses.length; j++){
        $(".cl-div-new-project-building-types-holder").find('input[value="'+facilityUses[j]+'"]').prop("checked",true); 
    }

    var serviceuses = data.service_type.split(",");
    serviceuses.pop();
    // alert(JSON.stringify(facilityUses));
    for(var j=0; j<serviceuses.length; j++){
        $(".cl-div-new-project-service-types-holder").find('input[value="'+serviceuses[j]+'"]').prop("checked",true); 
    }

    var certificationuses = data.certification_type.split(",");
    certificationuses.pop();
    // alert(JSON.stringify(facilityUses));
    for(var j=0; j<certificationuses.length; j++){
        $(".cl-div-new-project-certification-types-holder").find('input[value="'+certificationuses[j]+'"]').prop("checked",true); 
    }

    // var buildingTypeArr = data.building_type.split(";");
    // //alert("Fetched :: " + JSON.stringify(buildingTypeArr));
    // var buildingTypeSubContainers = $(".cl-div-new-project-building-type-sub-container");
    // if(buildingTypeArr.length === buildingTypeSubContainers.length){
    //     console.log("Inside");
    //     for(var i=0; i< buildingTypeSubContainers.length; i++){
    //         var buildingSubTypeArr = buildingTypeArr[i].split(",");
    //         for(var j=0; j<buildingSubTypeArr.length; j++){
    //             $(buildingTypeSubContainers[i]).find('input[value="'+buildingSubTypeArr[j]+'"]').prop("checked",true);
                
    //         }
    //         var parentHeaderElem = $(this).parent().parent().parent().find("span");
    //        // alert("Sub Array :: " + JSON.stringify(buildingSubTypeArr));
    //         $(parentHeaderElem).prop("data-checked-vals", buildingSubTypeArr.toString());
    //         // alert('parent :: ' + JSON.stringify(parentHeaderElem.id));
    //         // alert('x :: ' + JSON.stringify(x.id));
    //     }

    //     // var val = $(this).val();
        
    //     // var parentVal = $(parentHeaderElem).attr("data-checked-vals");
    //     // // alert(JSON.stringify(parentVal));
    //     // parentVal = typeof parentVal === "undefined" ? "": parentVal;
    //     // var parentValArr = parentVal === ""? [] : parentVal.split(",");
    //     // if(parentValArr.includes(val)){
    //     //     parentValArr = parentValArr.filter(function(v){
    //     //         return (v !== val);                
    //     //     });
    //     // }

    //     // if($(this).prop("checked")){
    //     //     parentValArr.push(val);
    //     // }
    //     //alert("Done");
    // }
    displayCalculations(pre_certification_paid, final_certification_paid);

}

/*
$("#id-new-project-inp-habitable-floor-area").change(function() {
    
    var val = $(this).val();
    // if value is 0 then enable the text box else disable it
    if ( val == 0)
    {        
        // $("#id-textbox-habitable-floor-area").show();
        $("#id-textbox-habitable-floor-area").prop("disabled",false);
        //alert("Enabling text box ");
    }
    else
    {
        $("#id-textbox-habitable-floor-area").prop("disabled",true);
        // $("#id-textbox-habitable-floor-area").hide();
        $("#id-textbox-habitable-floor-area").val("");
        //alert("Desabling the text box");
    }
});
*/

$("#id-btn-project-dashboard").click(function(){
    // var target = "myProjects.php";
    // window.location.href = target;  
    var project_id = $(this).attr("project_id");
    var target = "projectOverview.php?edit=true&id=" + project_id;
    window.location.href = target; 
})

$("#id-btn-project-dashboard-yes").click(function(){
    // var target = "myProjects.php";
    // window.location.href = target; 
    if(project_id || projectId){
        var project_id = $(this).attr("project_id");
        var target = "projectOverview.php?edit=true&id=" + project_id;
        window.location.href = target; 
    }
    else{
        var target = "myProjects.php";
        window.location.href = target;
    }
})

$("#id-btn-edit-project").click(function(){
    var project_id = $(this).attr("project_id");
    var target = "solutions_l.php?edit=true&id=" + project_id;
    window.location.href = target; 
})

var show_success_popup = function (msgSuccess,project_id){
    $("#id-create-project-success-popup-msg").html(msgSuccess);
    var modal = $("#id-modal-create-project-success-popup");
    
    $(modal).find("#id-btn-edit-project").attr("project_id",project_id);
    $(modal).find("#id-btn-project-dashboard").attr("project_id",project_id);
    $(modal).modal('show');
}

// if user clicks outside the modal dialog then 'hidden.bs.modal' event is 
// triggered. Handle this case and reload created project in edit mode
$("#id-modal-create-project-success-popup").on("hidden.bs.modal", function () {
    var modal = $("#id-modal-create-project-success-popup");
    var project_id =  $(modal).find("#id-btn-edit-project").attr("project_id");
    $("#id-modal-create-project-success-popup").modal('hide');
    var target = "createProject.php?edit=true&p=" + project_id;
    window.location.href = target;
});

$("#id-btn-new-project-cancel").click(function(){
    var msg = "Any changes will not be saved. Would you like to continue?";
    $("#id-create-project-cancel-popup-msg").html(msg);
    var modal = $("#id-modal-create-project-cancel-popup");
    $(modal).find("#id-btn-project-dashboard-yes").attr("project_id",projectId);
    $(modal).modal('show');
});

function attachOverviewEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-project-update-btn");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "projectOverview.php?edit=true&id="+projectId ;
            window.location.href = target;
        });
    }
}

