class Instruments {
  constructor() {
    this._iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);
    this.activeData = {};
    this.formsFieldsRecords = {};
    this.loggedin = false;
    //console.log(dayStringArray)
    console.log("Browser Instruments Loaded", getMentorId(), this.daysTotal);
    //console.log('Browser Instruments Loaded',getMentor())
    this.mentorDetails = getMentor();
    this.mentorId = getMentorId();
    //this.getModal(this.mentorDetails,dayStringArray)
    this.bookNowClicks = [];
    this.randomFinanceFacts = [
      `It costs more money to make pennies and nickels than they're actually worth!`,
      `Coins stay in circulation for about 30 years before they get melted down and repurposed`,
      `Two separate agencies create coins and paper money!`,
      `Congress creates “coin programs” to encourage families to collect coins`,
      `Nickels weren’t always made of nickel`,
    ];
    this.db = firebase.firestore();
    this.userTimezone = moment.tz.guess();
    console.log(this.userTimezone);
    this.db
      .collection("Booking Sets")
      .doc(getMentor().MentorUserRef)
      .get()
      .then((doc) => {
        if (doc.exists) {
          this.bookingSet = doc.data();
          if (document.getElementById("timezone-view")) {
            document.getElementById("timezone-view").innerHTML =
              "<p>" + " Converted To->" + this.userTimezone + "</p>";
          }
        } else {
          this.bookingSet = false;
        }
      });
    var offset = new Date().getTimezoneOffset();
    this.timezoneOffsetUser = offset;
    this.timezoneUser = Intl.DateTimeFormat().resolvedOptions().timeZone;
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.displayName = user.displayName;
        this.loggedin = true;
      } else {
      }
    });
    this.renderderedTimeSlotsFlag = false;
  }
  async loadRelatedMentors() {
    let relatedMentors = await this.db
      .collection("Objects")
      .doc("Mentors")
      .collection("records")
      .where(
        "MentorServices",
        "array-contains-any",
        this.mentorDetails.MentorServices.length == 0
          ? ["Finance"]
          : this.mentorDetails.MentorServices
      )
      .limit(5)
      .get();

    let relatedMentorsString = "";
    relatedMentors.forEach((element) => {
      let tagsArr = element.data().MentorServices.map((item) => {
        return `<li>${item}</li>`;
      });
      let reviewScore =
        (element.data().MentorTotalReviewScore
          ? element.data().MentorTotalReviewScore
          : 0) /
        (5 *
          Math.abs(
            element.data().MentorTotalReviews
              ? element.data().MentorTotalReviews
              : 1
          ));
      // ${(data.MentorTotalReviewScore?data.MentorTotalReviewScore:0)/(5*Math.abs(data.MentorTotalReviews?data.MentorTotalReviews:1))}</strong> <span>(${(data.MentorTotalReviews?data.MentorTotalReviews:'0')}
      relatedMentorsString =
        relatedMentorsString +
        `
                    <div class="mentor-box">
                                      <div class="row">
                                          <div class="col-md-9 col-sm-12">
                                              <div class="mentor-info">
                                              <div class="mentor-img">
                                              <img src=${
                                                element.data()
                                                  .MentorImageLink == ""
                                                  ? "images/mentor1.png"
                                                  : element.data()
                                                      .MentorImageLink
                                              } alt="mentor-image" />
                                          </div>
                                          <div class="mentor-dt">
                                          <h2>${element.data().MentorFName} ${
          element.data().MentorLName
        }</h2>
                                          <h3>${
                                            element.data().MentorDesignation
                                          }</h3>
                                          <h4>${
                                            element.data().MentorTagline
                                          }</h4>
                                          <h5>${element.data().MentorCity}, ${
          element.data().MentorCountry
        } (+5:30 UTC)</h5>
                                      </div>
                                              </div>
                                              <div class="description">
                                                  <p>
                                                  ${
                                                    element.data()
                                                      .MentorDescription
                                                  }
                                                  </p>
                                                  <ul>
                                                  ${tagsArr.join(" ")}
                                                
                                                  </ul>
                                              </div>
                                          </div>
                                          <div class="col-md-3 col-sm-12">
                                              <div class="mentor-description">
                                                  <ul class="mentor-info">
                                                      <li hidden ${
                                                        element.data()
                                                          .MentorCareerStrategyCheck
                                                          ? ""
                                                          : "hidden"
                                                      }><img src="images/check-icon.svg" alt="" /> Career Strategy</li>
                                                      <li ${
                                                        element.data()
                                                          .MentorInterviewCheck
                                                          ? ""
                                                          : "hidden"
                                                      }><img src="images/check-icon.svg" alt="" /> Mock Interview</li>
                                                      <li><img src="images/check-icon.svg" alt="" /> Mentoring</li>
                                                  </ul>
                                                  <h6><i class="fas fa-star"></i> ${reviewScore} <span>(${
          element.data().MentorTotalReviews
            ? element.data().MentorTotalReviews
            : "0"
        } reviews)</span></h6>
                                                  <h2>$${
                                                    element.data()
                                                      .MentorMentoringPrice
                                                  } <span>$${
          element.data().MentorMentoringSlashedPrice
            ? element.data().MentorMentoringSlashedPrice
            : element.data().MentorMentoringPrice / 2
        }</span></h2>
                                                  <h5>per 25 mins</h5>
                                                  <ul class="btn-box">
                                                      <li><a href="/mentors/${
                                                        element.id
                                                      }#CallRequest" class="btn-main">Request a Call</a></li>
                                                      <li><a href="/mentors/${
                                                        element.id
                                                      }" class="btn-main2"><span>View Full Profile</span></a></li>
                                                  </ul>
                                              </div>
                                          </div>
                                      </div>
                                  </div>`;
    });
    document.getElementById("related-block").innerHTML =
      document.getElementById("related-block").innerHTML + relatedMentorsString;
    console.log("Related Mentors Loaded");
    return true;
  }
  getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      instruments.formsFieldsRecords.CVFILE = reader.result;
    };
    reader.onerror = function (error) {
      console.log("Error: ", error);
    };
  }
  getModal(data, dayStringArray) {
    let dayString = "";
    dayStringArray.map((ele) => {
      dayString = dayString + ele;
    });

    let monthsArray = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];
    this.modal = `<div class="modal fade" id="wizard-modal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <!-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
                <div class="modal-body">
                    <div class="form-wizard">
                        <form action="" method="post" role="form">
                            <div class="form-wizard-header">
                                <ul class="form-wizard-steps">
                                    <li class="active">
                                        <span>1</span>
                                        Book Slot
                                    </li>
                                    <li>
                                        <span>2</span>
                                        Details
                                    </li>
                                </ul>
                            </div>

                            <fieldset class="wizard-fieldset show">
                                <div class="wizard-block">
                                    <h2>Book 1:1 call with ${
                                      data.MentorFName
                                    } ${data.MentorLName}</h2>

                                    <div class="calendar-block" id="calendar-block">
                                        <div class="form-group">
                                            <select class="form-control" onchange='displayDays()' id="month-selector">
                                            ${monthsArray
                                              .slice(
                                                new Date().getMonth(),
                                                monthsArray.length
                                              )
                                              .map((ele) => {
                                                return `<option value="${new Date().getMonth()}">${ele}, ${new Date().getFullYear()}</option>`;
                                              })
                                              .join(" ")}
                                               
                                            </select>

                                            
                                        </div>

                                        <div class="slider multiple-items" id="multiple-items">
                                           ${dayString}
                                        </div>

                                    <div class="time-block">
                                        <h2>Select Your Preferred Time</h2>

                                        <ul>
                                            <li>
                                                <div>
                                                    <h3>09:00 AM</h3>
                                                    <input type="radio" id="time1" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>10:00 AM</h3>
                                                    <input type="radio" id="time2" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>11:00 AM</h3>
                                                    <input type="radio" id="time3" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li class="selected">
                                                <div>
                                                    <h3>12:00 AM</h3>
                                                    <input type="radio" id="time4" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>01:00 AM</h3>
                                                    <input type="radio" id="time5" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>02:00 AM</h3>
                                                    <input type="radio" id="time6" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>03:00 AM</h3>
                                                    <input type="radio" id="time7" name="radio-group2" />
                                                </div>
                                            </li>
                                            <li>
                                                <div>
                                                    <h3>04:00 AM</h3>
                                                    <input type="radio" id="time8" name="radio-group2" />
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>

                                <div class="modal-footer">
                                    <div class="row">
                                        <div class="col-md-6 col-sm-12">
                                            <h6>You’re saving ₹2000 by booking your first mentor!</h6>
                                            <h2>₹2000</h2>
                                            <p>*Inclusive of all taxes</p>
                                        </div>
                                        <div class="col-md-6 col-sm-12">
                                            <ul>
                                                <li><span>Time : 45 mins</span></li>
                                                <li><a href="javascript:void(0);" class="form-wizard-next-btn btn-main">Next</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset class="wizard-fieldset">
                                <div class="wizard-block">
                                    <h2>Book 1:1 call with John Doe</h2>

                                    <div class="info-form">
                                        <div class="form-group">
                                            <label>Job Role*</label>
                                            <input type="text" class="form-control" />
                                        </div>
                                        <div class="form-group">
                                            <label>Where are you currently working ?*</label>
                                            <input type="text" class="form-control" />
                                        </div>
                                        <div class="form-group">
                                            <label>Goal*</label>
                                            <input type="text" class="form-control" />
                                        </div>
                                        <div class="form-group">
                                            <label>How can we help?* </label>
                                            <input type="text" class="form-control" />
                                        </div>
                                        <div class="upload-group">
                                            <img src="images/upload-icon.svg" alt="" />
                                            Upload your CV
                                            <input type="file" class="form-control" />
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <div class="row">
                                        <div class="col-md-6 col-sm-12">
                                            <h6>You’re saving ₹2000 by booking your first mentor!</h6>
                                            <h2>₹2000</h2>
                                            <p>*Inclusive of all taxes</p>
                                        </div>
                                        <div class="col-md-6 col-sm-12">
                                            <ul>
                                                <li><span>Time : 45 mins</span></li>
                                                <li><a href="javascript:void(0);" class="form-wizard-submit btn-main">pay</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        </div>`;
    $("body").append(this.modal);
    this.sliderInit();
  }
  sliderInit() {
    $("#calendar-block #multiple-items").slick({
      customPaging: function (slider, i) {
        console.log("Slider", slider);
        return i + 1 + "/" + slider.slideCount;
      },
      arrows: false,
      loop: true,
      dots: false,
      autoplay: true,
      infinite: true,
      slidesToShow: 6,
      slidesToScroll: 5,
      autoplaySpeed: 3000,
      speed: 1000,
      autoplay: true,
      responsive: [
        {
          breakpoint: 1600,
          settings: {
            slidesToShow: 6,
            slidesToScroll: 5,
          },
        },
        {
          breakpoint: 1199,
          settings: {
            slidesToShow: 6,
            slidesToScroll: 5,
          },
        },
        {
          breakpoint: 991,
          settings: {
            slidesToShow: 5,
            slidesToScroll: 4,
          },
        },
        {
          breakpoint: 767,
          settings: {
            slidesToShow: 5,
            slidesToScroll: 4,
          },
        },
        {
          breakpoint: 575,
          settings: {
            slidesToShow: 4,
            slidesToScroll: 3,
          },
        },
        {
          breakpoint: 447,
          settings: {
            slidesToShow: 2,
            slidesToScroll: 1,
          },
        },
      ],
    });
  }
  fireModalTest() {
    // console.log('hh')
    $("#wizard-modal1").modal("show");
    // firebase.auth().onAuthStateChanged((user) => {
    //     if (user) {

    //     } else {
    //       // User is signed out
    //       // ...
    //       window.location.href='./login'
    //     }
    //   });
  }
  getAuth() {
    let formAuth = [
      "Job Role",
      "Currently Working Company",
      "Goal",
      "How Can We Help",
    ];
    if (this.bookNowClicks[this.bookNowClicks.length - 1] == "") {
      return false;
    }

    let flag = true;
    formAuth.map((ele) => {
      if (this.formsFieldsRecords[ele]) {
        if (this.formsFieldsRecords[ele] == "") {
          flag = false;
        }
      } else {
        flag = false;
      }
    });
    if (this.activeData["selectedDate"]) {
      if (this.activeData["selectedDate"] == "") {
        flag = false;
      }
    } else {
      flag = false;
    }

    if (this.activeData["selectedTime"]) {
      if (this.activeData["selectedTime"] == "") {
        flag = false;
      }
    } else {
      flag = false;
    }

    return flag;
  }
  payButtonAction() {
    //check
    let auth = this.getAuth(this.formsFieldsRecords);
    console.debug(this.formsFieldsRecords);

    console.debug(this.activeData);
    console.debug(auth);
    if (auth) {
      this.callAPI();
      let timerInterval;
      Swal.fire({
        title: "Please Wait While We Resolve Your Order",
        html: "Do You Know <b></b> .",
        timer: 20000,
        timerProgressBar: true,
        didOpen: () => {
          Swal.showLoading();
          const b = Swal.getHtmlContainer().querySelector("b");
          b.textContent =
            this.randomFinanceFacts[
              Math.floor(
                Math.random() * (this.randomFinanceFacts.length - 1 - 0 + 1)
              ) + 0
            ];
          timerInterval = setInterval(() => {
            let rand =
              Math.floor(
                Math.random() * (this.randomFinanceFacts.length - 1 - 0 + 1)
              ) + 0;
            console.log(rand);
            b.textContent = this.randomFinanceFacts[rand];
            //b.textContent = Swal.getTimerLeft()
          }, 5000);
        },
        willClose: () => {
          clearInterval(timerInterval);
        },
      }).then((result) => {
        /* Read more about handling dismissals below */
        if (result.dismiss === Swal.DismissReason.timer) {
          console.log("I was closed by the timer");
        }
      });
      //this.callAPI()
    } else {
    }
  }
  callAPI() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        var settings = {
          url: `https://api-financementorbox.web.app/hamiltonianfunctions/CREATE_ORDER_MENTOR?mentorId=${getMentorId()}&type=${
            this.bookNowClicks[this.bookNowClicks.length - 1]
          }&userId=${user.uid}`,
          method: "GET",
          timeout: 0,
          headers: {
            userId: user.uid,
            Authorization: user.uid,
          },
        };

        $.ajax(settings).done(function (response) {
          console.log(response); //error check
          instruments.callRazorpay(response);
        });
      } else {
        window.location.href = "../sign-in";
      }
    });
  }
  async callRazorpay(response) {
    let db = firebase.firestore();
    console.log(response);
    console.log(new URL(window.location.href).origin + "/paymentsuccess/");
    await db
      .collection("Order Entities")
      .doc(response.id)
      .set(
        { cstDt: this.activeData, formDt: this.formsFieldsRecords },
        { merge: true }
      );
    var options = {
      key: "rzp_live_NZ0J06Kg2ssCLU", // Enter the Key ID generated from the Dashboard
      // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
      currency: "USD",
      name: "Finance Mentor Box",
      description: "CRM BOOKING",
      redirect: true,
      image: "/images/logo.svg",
      order_id: response.id, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
      callback_url: new URL(window.location.href).origin + "/paymentsuccess/",
      prefill: {
        name: firebase.auth().currentUser.displayName
          ? firebase.auth().currentUser.displayName
          : "",
        email: firebase.auth().currentUser.email,

        contact: firebase.auth().currentUser.phoneNumber
          ? firebase.auth().currentUser.phoneNumber
          : "",
      },

      theme: {
        color: "#3399cc",
      },
    };

    var rzp1 = new Razorpay(options);
    rzp1.open();
  }
  fireModal(ele) {
    console.log(ele.id);
    this.bookNowClicks.push(ele.id);
    let price = this.mentorDetails[ele.id];
    console.log(price);
    document.getElementById("price-modal").innerHTML = `$${price}`;
    document.getElementById("price-modal2").innerHTML = `$${price}`;
  }
  getUser() {
    const user = firebase.auth().currentUser;
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        var uid = user.uid;
        return uid;
      } else {
        window.location.href = "../sign-in";
      }
    });
  }
  showError() {
    Swal.fire({
      icon: "error",
      title: "Required Fields Missing",
      text: "Please Choose the Date and Time",
      footer: "",
    });
  }
  loadOpportunityModal(ele) {}
  getUserTimezone() {}
  tConvert(time) {
    // Check correct time format and split into components
    time = time
      .toString()
      .match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) {
      // If time format correct
      time = time.slice(1); // Remove full string match value
      time[5] = +time[0] < 12 ? "AM" : "PM"; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join(""); // return adjusted time or original string
  }
  renderTimeSlots(timeSlots, date) {
    console.log('Render Method',date);
    
    let str = `<li onclick="instruments.loadOpportunityModal(this)" id="${date}">
                    <div>
                        <h3>No Time Slots Found</h3><h3></h3>
                        <input type="radio" name="radio-group2">
                    </div>
                </li>`;
    let blockedFlag = false;
    let blockedDates = [];
    //For retro fitting
    if (!this.bookingSet.blockedDates) {
      this.bookingSet.blockedDates = [];
    }
    if (this.bookingSet.blockedDates) {
      blockedDates = this.bookingSet.blockedDates.map((ele) => {
        if (new Date(ele).setHours(0, 0, 0, 0) == date.setHours(0, 0, 0, 0)) {
          blockedFlag = true;
        }
        return new Date(ele);
      });
    } else {
      blockedFlag = true;
    }

    let totalDays = this.bookingSet.bookingPeriod;
    let totalDaysGant = 1;
    if (totalDays) {
      let daysStr = totalDays.id.split("*").map((ele) => {
        totalDaysGant = parseInt(ele) * totalDaysGant;
        return parseInt(ele);
      });
      let startPeriod =
        this.bookingSet.lastUpdated != null
          ? this.bookingSet.lastUpdated.toDate()
          : null;

      let endPeriod = new Date(
        startPeriod.setDate(startPeriod.getDate() + totalDaysGant)
      );
      startPeriod =
        this.bookingSet.lastUpdated != null
          ? this.bookingSet.lastUpdated.toDate()
          : null;
      if (startPeriod) {
        if (date > startPeriod && date <= endPeriod) {
        } else {
          blockedFlag = true;
        }
      }
    } else {
      blockedFlag = true;
    }
    if (!this.bookingSet.bookedSet) {
      this.bookingSet.bookedSet = {};
    }
    console.log(
      "Booking Set-->📅",
      this.bookingSet,
      "Blocked Arr",
      blockedDates,
      "Blocked Date Flag--->❌",
      blockedFlag,
      "Total Extra Gant-->🧭",
      totalDaysGant,
      "",
      timeSlots
      
      
    );
    //moment.tz.setDefault(this.bookingSet.timezone.FIELD2);
    if (!blockedFlag) {
      console.log('Unblocked Date')
      
      if (timeSlots) {
        str = "";
        console.log('Timeslots',timeSlots)
        for (let i in timeSlots) {
          let formatteddate;
          //formatteddate-1
          formatteddate =
            date.getDate() <= 9 ? '0'+date.getDate() :  date.getDate();

          // let startTimePeriod = moment(date.getFullYear()+'-'+(date.getMonth()+1)+'-'+ formatteddate+''+timeSlots[i].startBias, "YYYY-MM-DDHH:mma").tz(this.bookingSet.timezone.FIELD2)
          // let endTimePeriod = moment(date.getFullYear()+'-'+(date.getMonth()+1)+'-'+ formatteddate+''+timeSlots[i].endBias, "YYYY-MM-DDHH:mma").tz(this.bookingSet.timezone.FIELD2)

          // console.log('Converted End To->',this.bookingSet.timezone.FIELD2,new Date(moment.tz(endTimePeriod, this.bookingSet.timezone.FIELD2).utc().format()))
          let month=(date.getMonth()+1>=9?date.getMonth()+1:'0'+(date.getMonth()+1))
          let tstart=timeSlots[i].startBias
         tstart=(tstart.length==6?'0'+tstart:tstart)
         let tend = timeSlots[i].endBias;
         tend = tend.length == 6 ? "0" + tend : tend;
         console.log(month,tstart,tend,timeSlots[i],date.getFullYear() +
         "-" +
         month+
         "-" +
         formatteddate +
         "" +
         tstart,
       "YYYY-MM-DDHH:mma")
          let startTimePeriod = moment.tz(
            date.getFullYear() +
              "-" +
              month +
              "-" +
              formatteddate +
              "" +
              tstart,
            "YYYY-MM-DDHH:mma",
            this.bookingSet.timezone.FIELD2
          ); //.toString().split(' '))//.format()))
          let endTimePeriod = moment.tz(
            date.getFullYear() + "-" + month + "" + formatteddate + "" + tend,
            "YYYY-MM-DDHH:mma",
            this.bookingSet.timezone.FIELD2
          ); //.toString().split(' ')//.format()))
          //Converting to Locale
          let convertedStart = new Date(startTimePeriod)
            .toTimeString()
            .split(" ")[0];
          let convertedEnd = new Date(endTimePeriod)
            .toTimeString()
            .split(" ")[0];

            console.log('Start End Time slot',startTimePeriod.toDate(),endTimePeriod.toDate())
          
          
            convertedStart =
            convertedStart.split(":")[0] + ":" + convertedStart.split(":")[1];
          
            convertedEnd =
            convertedEnd.split(":")[0] + ":" + convertedEnd.split(":")[1];
          
            console.log('Start Time Converted->',new Date(startTimePeriod).getDay()==date.getDate(),'End Time Converted ->',convertedEnd)
          
            if (new Date(startTimePeriod).getDay() == date.getDate()) {
            console.log("Chances of Error");
          }
          if (this.bookingSet.bookedSet) {
            if (this.bookingSet.bookedSet[i]) {
              let flag_Booking = true;
              this.bookingSet.bookedSet[i].map((ele) => {
                //console.log('ele.toDate()==',date==ele.toDate(),date,'ele date',ele.toDate())
                if (ele.toDate().getTime() == date.getTime()) {
                  flag_Booking = false;
                }
              });

              if (flag_Booking) {
                //document.getElementById('upper-block').hidden=true
                //document.getElementById('slider-item').hidden=true

                str =
                  str +
                  `
                                <li onclick="selectTime(this)" id="${
                                  i +
                                  "$HAM$" +
                                  date +
                                  "$HAM$" +
                                  (timeSlots[i].startBias +
                                    "-" +
                                    timeSlots[i].endBias)
                                }">
                                    <div>
                                        <h3>${convertedStart} - ${convertedEnd}</h3>
                                        <input type="radio" name="radio-group2">
                                    </div>
                                </li>`;
              }
            } else {
              // document.getElementById('upper-block').hidden=true
              // document.getElementById('slider-item').hidden=true
              str =
                str +
                `
                                <li onclick="selectTime(this)" id="${
                                  i +
                                  "$HAM$" +
                                  date +
                                  "$HAM$" +
                                  (timeSlots[i].startBias +
                                    "-" +
                                    timeSlots[i].endBias)
                                }">
                                    <div>
                                        <h3>${convertedStart} - ${convertedEnd}</h3>
                                        <input type="radio" name="radio-group2">
                                    </div>
                                </li>`;
            }
          } else {
            // document.getElementById('upper-block').hidden=true
            // document.getElementById('slider-item').hidden=true
            str =
              str +
              `
                        <li onclick="selectTime(this)" id="${
                          i +
                          "$HAM$" +
                          date +
                          "$HAM$" +
                          (timeSlots[i].startBias + "-" + timeSlots[i].endBias)
                        }">
                            <div>
                                <h3>${convertedStart} - ${convertedEnd}</h3>
                                <input type="radio" name="radio-group2">
                            </div>
                        </li>`;
          }
        }
        if (str == "") {
          str = ` <li onclick="instruments.loadOpportunityModal(this)" id="${date}">
                        <div>
                            <h3>No Time Slots Found **published</h3><h3></h3>
                            <input type="radio" name="radio-group2">
                        </div>
                    </li>`;
        }
      } else {
        //console.log('No Slots Found')
      }
    } else {
      str = `<li onclick="instruments.loadOpportunityModal(this)" id="${date}">
                    <div>
                        <h3>Not Available on this Date</h3>
                    </div>
                </li>`;
    }

    document.getElementById("time-components").innerHTML = str;
  }
  rearrangeSlick(setIndex, start, end) {
    for (let index = start; index < end; index++) {
      if (index != setIndex) {
        if (document.getElementById(index)) {
          document.getElementById(index).className = "slider-box";
        }
      } else {
        if (document.getElementById(index)) {
          document.getElementById(index).className = "slider-box selected";
        }
      }
    }
  }
  getUlList(itemId, setEle) {
    var lis = document.getElementById(itemId).getElementsByTagName("li");
    var idArray = [];
    for (var counter = 0; counter < lis.length; counter++) {
      idArray.push(lis[counter].id);
      document.getElementById(lis[counter].id).className = "";
      if (setEle == document.getElementById(lis[counter].id)) {
        document.getElementById(lis[counter].id).className = "selected";
      }
    }
    //console.log(idArray)
    return idArray;
  }
  rearrangeTimeSlots(setEle) {
    this.getUlList("time-components", setEle);
    // for (let index = start; index < end; index++) {
    //     if(index!=setIndex)
    //     {
    //         if(document.getElementById(index))
    //         {
    //             document.getElementById(index).className=''
    //         }
    //     }else{
    //         if(document.getElementById(index))
    //         {
    //             document.getElementById(index).className='selected'
    //         }

    //     }

    // }
  }
}
//Debug
var DEBUG = false;
if (!DEBUG) {
  if (!window.console) window.console = {};
  var methods = ["log", "debug", "warn", "info"];
  for (var i = 0; i < methods.length; i++) {
    console[methods[i]] = function () {};
  }
}
let instruments = new Instruments();

console.log("Before Ready", instruments);
displayDays();
async function converTimezone() {}
function displayDays() {
  _iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);
  let ele2 = document.getElementById("month-selector");
  let year = ele2.options[ele2.selectedIndex].text.split(" ")[1];
  let selectedMonth = ele2.value;
  selectedMonth = parseInt(selectedMonth) + 1;
  console.log(year);
  // console.log('SELECTIONS',selectedMonth,year,ele2.innerHTML)
  //$('.calendar-block .multiple-items').slick('slickAdd','<div><h3>' + slideIndex + '</h3></div>');
  const getDays = (year, month) => new Date(year, month, 0).getDate();
  this.daysTotal = getDays(year, parseInt(selectedMonth));

  let dayStringArray = [];
  let dayString = "";
  const weekdays = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  let startDate =
    ele2.value == new Date().getMonth() && year == new Date().getFullYear()
      ? new Date().getDate()
      : 1;
  selectedMonth = selectedMonth > 12 ? selectedMonth - 12 : selectedMonth;
  let totalSlickIndex = 0;
  console.log(
    "Month",
    selectedMonth,
    "Year",
    year,
    this.daysTotal,
    "Start Date",
    startDate
  );
  //window.alert(new Date((parseInt(ele2.value)+1)+'-'+i+'-'+new Date().getFullYear()).getDay(),i)
  // window.alert(weekdays[new Date((parseInt(ele2.value)+1)+'-'+10+'-'+year).getDay()],10)

  for (let i = startDate; i <= this.daysTotal; i++) {
    let dateStr = parseInt(ele2.value) + 1 + "-" + i + "-" + year + " 00:00:00";
    // if(_iOSDevice)
    //     {
    //     window.alert(moment(dateStr,'MM-DD-YYYY hh:mm:ss a').format('dddd a'))
    //     }
    // window.alert((parseInt(ele2.value)+1)+'-'+i+'-'+year);
    //console.log(moment((parseInt(ele2.value)+1)+'-'+i+'-'+new Date().getFullYear()).format('dddd'))
    totalSlickIndex = totalSlickIndex + 1;
    dayStringArray.push(
      `<div class="slider-box" onclick="selectDate(this)" id="${i}"><div><h3>${i}</h3><h6>${
        weekdays[
          new Date(
            parseInt(ele2.value) + 1 + "-" + i + "-" + new Date().getFullYear()
          ).getDay()
        ]
      }</h6><input type="radio" id="calendar${i}"  name="radio-group" /></div></div>`
    );
    dayString =
      dayString +
      `<div><div class="slider-box" onclick="selectDate(this)" id="${i}"><div><h3>${i}</h3><h6>${
        moment(dateStr, "MM-DD-YYYY hh:mm:ss a").format("dddd a").split(" ")[0]
      }</h6><input type="radio" id="calendar${i}" name="radio-group" /></div></div></div>`;
  }
  instruments.bookingDayOffsetCalendar = totalSlickIndex;
  instruments.startDayId = startDate;
  instruments.endDayId = this.daysTotal;
  var days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  $(".calendar-block .multiple-items").slick("unslick");
  document.getElementById("slider-item").innerHTML = "";
  $(".calendar-block .multiple-items").slick("slickAdd", dayString, {
    arrows: false,
    loop: false,
    dots: false,
    autoplay: false,
    draggable: true,
    infinite: false,
    slidesToShow: 6,
    slidesToScroll: 5,
    autoplaySpeed: 3000,
    speed: 1000,
    responsive: [
      {
        breakpoint: 1600,
        settings: {
          slidesToShow: 6,
          slidesToScroll: 5,
        },
      },
      {
        breakpoint: 1199,
        settings: {
          slidesToShow: 6,
          slidesToScroll: 5,
        },
      },
      {
        breakpoint: 991,
        settings: {
          slidesToShow: 5,
          slidesToScroll: 4,
        },
      },
      {
        breakpoint: 767,
        settings: {
          slidesToShow: 5,
          slidesToScroll: 4,
        },
      },
      {
        breakpoint: 575,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 3,
        },
      },
      {
        breakpoint: 447,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1,
        },
      },
    ],
  });
  instruments.renderderedTimeSlotsFlag = true;
  //$('.calendar-block .multiple-items').slick('slickAdd',dayString);
}
// $('.slide').on('click', function() {
//     console.log('fr')
//     $('.calendar-block .multiple-items').slick('slickRemove', $('.slick-slide').index(this) - 1);
//   });
function selectDate(ele) {
  console.log(ele.id);

  instruments.rearrangeSlick(
    parseInt(ele.id),
    instruments.startDayId,
    instruments.endDayId
  );
  let ele2 = document.getElementById("month-selector");
  let year = ele2.options[ele2.selectedIndex].text.split(" ")[1];
  const weekdays = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
  ];
  instruments.activeData.selectMonth = ele2.value;
  instruments.activeData.selectedDate = ele.id;
  instruments.activeData.selectYear = year;
  //console.log(instruments.activeData.selectMonth,instruments.activeData.selectedDate,ele.id)
  let date=moment(((parseInt(ele2.value) + 1)>9?(parseInt(ele2.value) + 1):'0'+(parseInt(ele2.value) + 1)) + "-" + ele.id + "-" + new Date().getFullYear(),'MM-DD-YYYY').toDate()
  let day = date.getDay();
  
  if (instruments.bookingSet) {
    let availability = instruments.bookingSet.availability;
    let availableSlots = availability[day];
    console.log('Date Object before render call',((parseInt(ele2.value) + 1)>9?(parseInt(ele2.value) + 1):'0'+(parseInt(ele2.value) + 1)) + "-" + ele.id + "-" + new Date().getFullYear())
    console.log('Available SLots',availableSlots) 
    let momentOb=moment(((parseInt(ele2.value) + 1)>9?(parseInt(ele2.value) + 1):'0'+(parseInt(ele2.value) + 1)) + "-" + ele.id + "-" + new Date().getFullYear(),'MM-DD-YYYY')
    //console.log('Moment Date',momentOb.toDate())
    console.log('br',date,momentOb.toDate())
    instruments.renderTimeSlots(availableSlots, momentOb.toDate());
  }

}
function selectTime(ele) {
  instruments.rearrangeTimeSlots(ele);
  instruments.activeData.selectedTime = ele.id;
  instruments.activeData.selectedTimeSlotDate = new Date(
    ele.id.split("$HAM$")[1]
  );
  let selectedDate =
    parseInt(instruments.activeData.selectedDate) >= 9
      ? parseInt(instruments.activeData.selectedDate)
      : "0" + parseInt(instruments.activeData.selectedDate);
  let selectMonth =
    parseInt(instruments.activeData.selectMonth) + 1 >= 9
      ? parseInt(instruments.activeData.selectMonth) + 1
      : "0" + (parseInt(instruments.activeData.selectMonth) + 1);

  let selectYear = instruments.activeData.selectYear;
  let dateString = selectMonth + "-" + selectedDate + "-" + selectYear;
  let dateOb = new Date(dateString);

  let bookedSlotId = instruments.activeData.selectedTime.split("$HAM$")[0];
  let dayId = dateOb.getDay();
  let slotDetails = instruments.bookingSet.availability[dayId][bookedSlotId];

  let startTimePeriodMentor = moment.tz(
    dateOb.getFullYear() +
      "-" +
      selectMonth +
      "-" +
      selectedDate +
      "" +
      slotDetails.startBias,
    "YYYY-MM-DDHH:mma",
    instruments.bookingSet.timezone.FIELD2
  ); //.toString().split(' '))//.format()))
  let endTimePeriodMentor = moment.tz(
    dateOb.getFullYear() +
      "-" +
      selectMonth +
      "-" +
      selectedDate +
      "" +
      slotDetails.endBias,
    "YYYY-MM-DDHH:mma",
    instruments.bookingSet.timezone.FIELD2
  ); //.toString().split(' ')//.format()))

  let startTimePeriodMentee = new Date(startTimePeriodMentor).toTimeString();
  let endTimePeriodMentee = new Date(endTimePeriodMentor).toTimeString();
  let startTimePeriodMenteeTS = new Date(startTimePeriodMentor);
  let endTimePeriodMenteeTS = new Date(endTimePeriodMentor);

  instruments.activeData.startTimePeriodMentor =
    startTimePeriodMentor.format("MM/DD/YYYY HH:mm a");
  instruments.activeData.endTimePeriodMentor =
    endTimePeriodMentor.format("MM/DD/YYYY HH:mm a");
  instruments.activeData.startTimePeriodMentee = startTimePeriodMentee;
  instruments.activeData.endTimePeriodMentee = endTimePeriodMentee;
  instruments.activeData.startTimePeriodMenteeTS = startTimePeriodMenteeTS;
  instruments.activeData.endTimePeriodMenteeTS = endTimePeriodMenteeTS;
}
function recordFormItems(ele) {
  if (ele.type != "file") {
    instruments.formsFieldsRecords[ele.id] = ele.value;
  } else {
    let file = ele.files[0];
    instruments.getBase64(file);
    console.log(file);
    document.getElementById(
      "cv-img-src"
    ).innerHTML = ` <label>Your CV is uploaded  ${file.name}</label><br>*donot refresh this window`;
  }
}
//instruments.fireModal({id:'MentorMentoringPrice'})
var callRequestTimeout;
$(document).ready(() => {
  $(document).ready(async function () {
    //start loader
    
    //console.log("Instruments Object 🎹", instruments);
    await instruments.loadRelatedMentors();
    if (window.location.href.indexOf("#CallRequest") != -1) {
      callRequestTimeout = setTimeout(stopTimeoutcallRequest, 50);
      //displayDays()
      //   console.log(instruments)
    }
  });
});

function stopTimeoutcallRequest() {
  if (instruments.renderderedTimeSlotsFlag) {
    let dom = document.getElementById("MentorMentoringPrice");
    dom.click();
    clearTimeout(callRequestTimeout);
    //stop loader
  }
}
