<?php error_reporting(0); ?>
<!DOCTYPE html>
<html>
<head>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <input type="hidden" name="csrf-token" id="csrf-token" value="<?php echo e(csrf_token()); ?>" />
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>" />
    <link rel="stylesheet" href="<?php echo e(asset('asset/bootstrap/css/bootstrap.min.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('asset/css/font-awsome.min.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('asset/css/webphone_new.css')); ?>">

     <link
      href="<?php echo e(asset('assets/webphone/vendor/css/bootstrap.min.css')); ?>"
      media="screen,projection"
      type="text/css"
      rel="stylesheet"
    />
    <link
      href="<?php echo e(asset('assets/webphone/vendor/css/font-awesome.min.css')); ?>"
      media="screen,projection"
      type="text/css"
      rel="stylesheet"
    />
    <link
      href="<?php echo e(asset('assets/webphone/css/main.css')); ?>"
      media="screen,projection"
      type="text/css"
      rel="stylesheet"
    />
 
    <script src="<?php echo e(asset('asset/plugins/jQuery/jQuery-2.1.4.min.js')); ?>"></script>

    <!-- Include Toastr CSS in <head> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">


    
<style>
    
.sticky-toolbar {
    width: 50px;
    position: fixed;
    top: 33%;
    right: 0;
    list-style: none;
    margin: 18px;
    background: #fff;
    -webkit-box-shadow: 0 0 50px 0 rgba(82, 63, 105, 0.15);
    box-shadow: 0 0 50px 0 rgba(82, 63, 105, 0.15);
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    border-top-left-radius: .42rem;
    border-bottom-left-radius: .42rem;
    padding: 0px;
    height: 45px;
}

.other-icons .label-container{
    position:relative;
    bottom:18px;
    right:40px;
    display:table;
    visibility: hidden;
  float:right;
}

.other-icons .label-text{
    color:#FFF;
    background:rgba(51,51,51,0.5);
    display:table-cell;
    vertical-align:middle;
    
    border-radius:3px;
    font-size: 12px;
    padding: 3px 6px;
    line-height: 8px;
}

.other-icons .label-arrow{
    display:table-cell;
    vertical-align:middle;
    color:#333;
    opacity:0.5;
}

.other-icons .clear-btn {
  clear:both;
}
.other-icons ul{
    position: fixed;
    top: 60%;
    right: 1%;
  
    z-index: 999999;
        background: #e9e9e9;
    padding: 4px;
    border-radius: 4px;
}
    


.other-icons ul li{
    list-style:none;
    margin-bottom: 0px;
    line-height: 5px !important;
    list-style-type:none;
    border-bottom:0px
}

.other-icons ul li a{
    
    color: #ff8f00;
    background-color: #f5f5f8;
    border-radius:4px;
    text-align:center;
    box-shadow: 2px 2px 3px #999;
    width:35px;
    height:35px;
    display:block;
}
.other-icons ul li a:hover{
    color:  #f5f5f8;
        background-color:#ff8f00;
}


.other-icons .my-float{
        font-size: 15px;
        line-height:16px;
    margin-top: 11px;
    color: #ff8f00;
}
.other-icons a:hover .my-float{
    color:  #f5f5f8;
}
.bg-red{
    background-color:#F33 !important;
    color:#FFF!important;
}

.bg-green{
color:  #f5f5f8 !important;
        background-color:#ff8f00!important ;
}

.bg-red .my-float{
    color:#FFF!important;
}
.bg-green .my-float{
    color:  #f5f5f8 !important;
}


.other-icons a.clear-btn>div.label-container {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.5s ease;
}
.other-icons a.clear-btn:hover>div.label-container{
  visibility: visible;
  opacity: 1;
}
.logout-icon {
position: fixed;
    top: 2%;
    right: 13px;
    z-index: 999999;
    
    padding: 6px;

    }
.logout-icon a{
    
    color: #172b4c;
    background-color: #f5f5f8;
    border-radius:4px;
    text-align:center;
    /*box-shadow: 2px 2px 3px #999;*/
    width:35px;
    height:35px;
    display:block;
    
    padding: 10px;
    vertical-align: middle;
    display: block;
    font-size: 1.714rem;
    height: 46px;
    text-align: center;
    width: 46px;
    /* line-height: 30px; */
    /* margin: 22px 5px; */
    background-color: #ffffff;
    /* -webkit-box-shadow: 0 0 30px 0 rgba(82, 63, 105, 0.05); */
    box-shadow: 0 0 30px 0 rgba(82, 63, 105, 0.05);
    border-radius: 5px;
    
    
    
}
/*.logout-icon a:hover{
background-color: rgba(0, 0, 0, 0.03);
    color: #2196f3;
}*/


.logout-icon .fa-lock{
      /*  font-size: 15px;
        line-height:16px;
    margin-top: 11px;*/
        color: white;
        font-size: 20px; 
        display: list-item;
        list-style: none;


        
}
/*.logout-icon a:hover .fa-lock{
color: #2196f3;
}*/

#wrapper .dialpad-top-wrapper {
    padding: 40px 25px 10px 25px;
}


.dialpad .dials {
  padding: 5px 10px;}
.icon-content {
    display: none;
}

/* Show content when active class is present */
.icon-content.active {
    display: block;
}

</style>

</head>


<body>


    <div class="row m-l-r-0 dialer-section-wrapper">
        <div id="dash-dailer" class="col-md-10 dash-dailer p-0">

            <?php if(Session::get('level') < 5 )
            {
                ?>

                <iframe  src="/start-dialing" class="iframe">
                Your browser doesn't support iframes
            </iframe> 


                <?php 
            }else
            {
                ?>
                 <iframe  src="/dashboard" class="iframe">
                Your browser doesn't support iframes
            </iframe> 

                <?php
            }
            ?>
           
        </div>

     

         <ul class="wrapper show_nev-red2" style="display: none;"  id="webphone_open">

           <!-- <div class="webphone-container">-->
                     <div id="webphone-content"class="icon-content">  
                    <div id="divCallCtrl" class="containerwebphone"style="margin-right:30px;">

                        <div id="wrapper">
      <div class="dialpad compact">
     
                        <div class="dialpad-top-wrapper">
                        <div style="float:right;">
          <a href="javascript:void(0)" class="closebtn" onclick="closeNav()" title="minimize"><i class="fa fa-minus" aria-hidden="true"></i></a>
          </div>
          <div class="dialer-close btn-enable" style="cursor: pointer;" disabled id="btnRegister" onClick="sipRegister();">
           Enable
            <i class="fa fa-power-off"></i>
          </div>

<div class="dialer-close btn-disable" id="btnUnRegister" style="cursor: pointer;" disabled onClick="sipUnRegister();">
           Disable
            <i class="fa fa-power-off"></i>
          </div>
          
           <label style="width: 100%;text-align:center;" id="txtRegStatus"></label>
                        <label style="width: 100%;text-align:center;" id="txtCallStatus"></label>
          <div class="dial-input">

            <select class="form-control country_code" name="countryCode" id="country_code" style="display: block;background: black;width: 100%;height: 30px;
            padding: 0px 8px;font-size: 14px;line-height: 1.428571;color: white;border: 2px solid #ccc;border-radius: 10px;">
                    <?php if($phone_country): ?>
                    <?php $__currentLoopData = $phone_country; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $phone_codes): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option <?php if($phone_codes->phone_code ==1): ?> selected <?php endif; ?> value="<?php echo e($phone_codes->phone_code); ?>"><?php echo e($phone_codes->country_name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php endif; ?>
                    </optgroup>
                </select>

                <span id="changeCountryCode" style="color: white;font-size: 16px;text-align: center;">+1</span>
            
            <input style="font-size: 16px !important;width: 70%;border-bottom: none !important;text-align: center;"
              type="text"
              class="number"
              id="txtPhoneNumber"
              maxlength="14"
              placeholder="(___) ___-____" 
            />
          </div>
        </div>

                        
                        <div class="dials">
          <table id="dialer_table">
            <tr class="dialer_num_tr">
                <td class="dialer_num"><input type="button" class="dialpad-number" value="1" onclick="sipSendDTMF('1');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="2" onclick="sipSendDTMF('2');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="3" onclick="sipSendDTMF('3');" /></td>

              
            </tr>
            <tr class="dialer_num_tr">
                <td class="dialer_num"><input type="button" class="dialpad-number" value="4" onclick="sipSendDTMF('4');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="5" onclick="sipSendDTMF('5');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="6" onclick="sipSendDTMF('6');" /></td>

            
            </tr>
            <tr class="dialer_num_tr">
                <td class="dialer_num"><input type="button" class="dialpad-number" value="7" onclick="sipSendDTMF('7');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="8" onclick="sipSendDTMF('8');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="9" onclick="sipSendDTMF('9');" /></td>

            </tr>

             <tr class="dialer_num_tr">
                <td class="dialer_num"><input type="button" class="dialpad-number" value="*" onclick="sipSendDTMF('*');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="0" onclick="sipSendDTMF('0');" /></td>
                <td class="dialer_num"><input type="button" class="dialpad-number" value="#" onclick="sipSendDTMF('#');" /></td>

            </tr>

            <tr class="">

                <!--td class=""></td-->
                                <td colspan="2">
<div style="display:flex; justify-content:right;">

                                    <!--button id="offsetbutton" style="display:none;width: 65px;margin: 3px;"></button-->
                                    <div id="divBtnCallGroup" class="btn-group">
                                        <button id="btnCall" onclick="closeNav()" class=""><i class="fa fa-phone"></i></button>
                                    </div>
                                    <button type="button" id="btnHangUp" class="btn btn-primary" onclick='sipHangUp();'><i class="fa fa-phone"></i></button>
                               </div> 
                               </td>
                                <td class="dialer_del_td">
                                    <button id="dialpad-backspace"><i style="color:black;" class="fa fa-chevron-left"></i>
                                    </button>
                                </td>
                            </tr>
           
          </table>
    
        </div>
    </div>
</div>
                    <!--    <hr />
                        <div>
                            <input type="button" class="btn btn-success" id="btnRegister" value="Enable Webphone" disabled onclick='sipRegister();' />
                            <input type="button" class="btn btn-danger" id="btnUnRegister" value="Disable Webphone" disabled onclick='sipUnRegister();' />
                        </div>-->


                        <div id='divCallOptions' class='call-options' style='display:none;opacity: 0; margin-top: 10px'>
                            <input type="button" class="btn btn-primary" style="" id="btnFullScreen" value="FullScreen" disabled onclick='toggleFullScreen();' />
                            <input type="button" class="btn btn-primary" style="" id="btnMute" value="Mute" onclick='sipToggleMute();' />
                            <input type="button" class="btn btn-primary" style="" id="btnHoldResume" value="Hold" onclick='sipToggleHoldResume();' />
                            <input type="button" class="btn btn-primary" style="" id="btnTransfer" value="Transfer" onclick='sipTransfer();' />
                            <input type="button" class="btn btn-primary" style="" id="btnKeyPad" value="KeyPad" onclick='openKeyPad();' />
                        </div>

                        <table style='display:none;width: 100%;'>
                            <tr>
                                <td id="tdVideo" class='tab-video'>
                                    <div id="divVideo" class='div-video'>
                                        <div id="divVideoRemote" style='position:relative; height:100%; width:100%; z-index: auto; opacity: 1'>
                                            <video class="video" width="100%" height="100%" id="video_remote" autoplay="autoplay" style="opacity: 0;
                                            background-color: #000000; -webkit-transition-property: opacity; -webkit-transition-duration: 2s;"></video>
                                        </div>

                                        <div id="divVideoLocalWrapper" style="margin-left: 0px; border:0px solid #009; z-index: 1000">
                                            <iframe class="previewvideo" style="border:0px solid #009; z-index: 1000"></iframe>
                                            <div id="divVideoLocal" class="previewvideo" style=' border:0px solid #009; z-index: 1000'>
                                                <video class="video" width="100%" height="100%" id="video_local" autoplay="autoplay" muted="true" style="opacity: 0;
                                                background-color: #000000; -webkit-transition-property: opacity;
                                                -webkit-transition-duration: 2s;"></video>
                                            </div>
                                        </div>
                                        <div id="divScreencastLocalWrapper" style="margin-left: 90px; border:0px solid #009; z-index: 1000">
                                            <iframe class="previewvideo" style="border:0px solid #009; z-index: 1000"></iframe>
                                            <div id="divScreencastLocal" class="previewvideo" style=' border:0px solid #009; z-index: 1000'></div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                        <ul id="ulCallOptions" class="dropdown-menu" style="visibility:hidden">
                            <li><a href="#" onclick='sipCall("call-audio");'>Audio</a></li>
                            <li><a href="#" onclick='sipCall("call-audiovide`o");'>Video</a></li>
                            <li id='liScreenShare'><a href="#" onclick='sipShareScreen();'>Screen Share</a></li>
                            <li class="divider"></li>
                            <li><a href="#" onclick='uiDisableCallOptions();'><b>Disable these options</b></a></li>
                        </ul>

                       <?php /*?>  @if($client['webphone'] == 0)

                        <div class="overlaywebphone">
                            <a href="#" class="icon" title="User Profile">
                            <i style="font-size: 50px;margin-right: 13px;" class="fa fa-lock"></i></a>
                        </div>
                        @endif

                        <?php */ ?>
                    </div>



                    
                   

                  

                   



                  

                     


                </div>
         </ul>
        <?php /*?>
        <!--  <div  class="logout-icon">
    <a href="{{url('/logout')}}" class="clear-btn " style="background: #2196f3 !important;color:white;">
    <i class="fa fa-lock"></i>
    </a>     
</div>   -->    

<?php */  ?>



<div class="other-icons">
       <ul>
<li>
  <a href="javascript:void(0)" class="clear-btn icon-toggle" id="chat-icon" data-target="chat" onclick="togglePanel('#send-sms')">
        <i class="fa fa-envelope my-float"></i>
    <div class="label-container">
      <div class="label-text">Chat</div>
      <i class="fa fa-play label-arrow"></i>
    </div>
  </a>
</li>

<li>
  <a href="javascript:void(0)" class="clear-btn icon-toggle" id="sms-icon" data-target="sms" onclick="toggleSMSContent('#sms-content')">
    <i class="fa fa-comments my-float"></i>
    <div class="label-container">
      <div class="label-text">ChatAI</div>
      <i class="fa fa-play label-arrow"></i>
    </div>
  </a>
</li>


       
       

<li><a href="#" class="clear-btn icon-toggle"data-target="fax">
<i class="fa fa-print my-float "></i>
<div class="label-container">
<div class="label-text">Fax</div>
<i class="fa fa-play label-arrow"></i>
</div>
</a></li>

<li onclick="openNav()" id="show_nev" class="icon-toggle" data-target="webphone">
 <a href="#" id="wrapper_class" class="clear-btn ">
<i class="fa fa-phone my-float"></i>
<div class="label-container">
<div class="label-text">Webphone</div>
<i class="fa fa-play label-arrow"></i>
</div>
</a>
 </li>
        

</ul>
     </div>  
        <!--ul class="wrapper show_nev-red1 sticky-toolbar" id="wrapper_class">
            <li onclick="openNav()" id="show_nev" class="icon youtube" >
                <span class="tooltip">Webphone</span>
                <span><i class="fa fa-phone"></i></span>
            </li>
        </ul--> 

        <audio id="audio_remote" autoplay="autoplay"></audio>
        <audio id="ringtone" loop src="<?php echo e(URL::asset('asset/audio/ringtone.wav')); ?>"></audio>
        <audio id="ringbacktone" loop src="<?php echo e(URL::asset('asset/audio/ringbacktone.wav')); ?>"></audio>
        <audio id="dtmfTone" src="<?php echo e(URL::asset('asset/audio/dtmf.wav')); ?>"></audio>

    </div>

    <div id="send-sms" class="icon-content" style="display:none;">
      <?php echo $__env->make('dialer.sms', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>

    <div id="sms-content" class="icon-content"style="display: none;">
        <?php echo $__env->make('dialer.chat', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>
    <div id="loader" style="display:none;">
  <i class="fa fa-spinner fa-spin fa-3x"></i>
</div>

    <!-- <script>
$(document).ready(function() {
    $('.icon-toggle').click(function() {
        var target = $(this).data('target');
        $('.icon-content').removeClass('active'); // Hide all content
        $('#' + target + '-content').addClass('active'); // Show clicked icon's content
    });
});
</script> -->
    <script>
$(document).ready(function() {
    $('.icon-toggle').click(function() {
        var target = $(this).data('target');
        $('.icon-content').removeClass('active'); // Hide all content
        $('#' + target + '-content').addClass('active'); // Show clicked icon's content
    });
        $('#sendNewSms').on('click', function() {
        sendSMS();
    });

    $('#cancelSms').on('click', function() {
        $('#send-sms').hide();
    });
});
</script>
    <script>
$(document).ready(function() {
    $(".btn-danger-light").click(function() {
        // Toggle the visibility of the chat box
        $("#sms-content").hide();
    });
});
</script>

<!-- Include jQuery first -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.0/moment.min.js"></script>


<!-- Include Toastr JS before your script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<!-- SweetAlert2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script>    
 $(document).ready(function() {

 
$('#sendNewSmsSubmit').on('click', function() {
    sendSMS();
});

// function sendSMS() {
//     $("#send-sms").show(); 
//     $("#sms-content").hide(); 
//     var country_code = $("#country_code_sms").val();
//     var to = $("#new_to").val();
//     var from = $("#new_from").val();
//     var message = $("#new_message").val();
//     var created_date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

//     if (to === "") {
//         toastr.error("Please enter Number");
//         return;
//     }

//     console.log(country_code, to, from, message, created_date);

//     var data = {
//         from: from,
//         to: country_code + to,
//         message: message,
//         created_date: created_date
//     };

//     // Show spinner
//     $("#loader").fadeIn(200);

//     $.ajax({
//         headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
//         url: '/send_sms_dialer',
//         method: 'POST',
//         data: data,
//         beforeSend: function() {
//             // You can disable the button to prevent double clicks
//             $("#sendNewSmsSubmit").prop("disabled", true).text("Sending...");
//         },
//         success: function(response) {
//             console.log(response);
//             $("#loader").fadeOut(200);
//             $("#sendNewSmsSubmit").prop("disabled", false).text("Submit");

//             toastr.success('✅ SMS sent successfully');
//             $("#send-sms").hide();

//             // Optional: reload after short delay
//         },
//         error: function(errors) {
//             console.error(errors);
//             $("#loader").fadeOut(200);
//             $("#sendNewSmsSubmit").prop("disabled", false).text("Submit");

//             toastr.error('❌ Failed to send SMS. Please try again.');
//         }
//     });
// }

});

</script>
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<!-- <input id="country_code_sms" value="+1">
<input id="new_to" placeholder="Number">
<input id="new_from" placeholder="From">
<textarea id="new_message" placeholder="Message"></textarea>
<div id="loader" style="display:none;">Loading...</div>

<button type="button" id="sendNewSmsSubmit">Submit</button> -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script>$(document).on('click', '#flag-options div', function() {
    const code = $(this).data('code'); // e.g. +91
    const flag = $(this).data('flag'); // e.g. in

    // set hidden input for SMS
    $('#country_code_sms').val(code);

    // optional: visually show selected flag somewhere
    $('#selected-flag-display').html(`<img src="https://flagcdn.com/w40/${flag}.png" class="flag-icon" /> ${code}`);

    console.log("Selected Country Code:", code);
});
</script>
<script>
$(document).on('click', '#sendNewSmsSubmit', function(e) {
    e.preventDefault();
    sendSMS();
});

function sendSMS() {
    var country_code = $("#country_code_sms").val();
    let to = $("#new_to").val();
    let from = $("#new_from").val();
    var message = $("#new_message").val();
    var created_date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
    let fullNumber = country_code + to;
    if (to === "") {
        toastr.error("Please enter Number");
        return;
    }

    var data = {
        from: from,
        to: country_code + to,
        message: message,
        created_date: created_date
    };

    $("#loader").fadeIn(200);

    $.ajax({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        url: '/send_sms_dialer',
        method: 'POST',
        data: data,
        beforeSend: function() {
            $("#sendNewSmsSubmit").prop("disabled", true).text("Sending...");
        },
        success: function(response) {
            $("#loader").fadeOut(200);
            $("#sendNewSmsSubmit").prop("disabled", false).text("Submit");
                  $("#new_message").val("");

            //openDiv1(fullNumber,from); 
            // Ensure response is an object
    try { 
        if (typeof response === "string") response = JSON.parse(response); 
    } catch (e) {}

    console.log("Response:", response);

    // Check success properly
    let success = response.success === true || response.success === "true" ||
                  (response.original && (response.original.success === true || response.original.success === "true"));

    if (success) {
        // Use success toastr
        toastr.success('✅ SMS sent successfully');
    } else {
        let errMsg = response.message || 
                     (response.original && response.original.message) || 
                     'Failed to send SMS.';
        toastr.error('❌ ' + errMsg);
    }
},
   error: function(xhr) {
    $("#loader").fadeOut(200);
    $("#sendNewSmsSubmit").prop("disabled", false).text("Submit");

    let msg = "Something went wrong.";

    try {
        // Try parsing JSON
        let res = xhr.responseJSON || JSON.parse(xhr.responseText);

        // Check multiple possible locations
        if (res.message) {
            msg = res.message;
        } else if (res.original && res.original.message) {
            msg = res.original.message;
        } else {
            msg = JSON.stringify(res); // fallback: show full response
        }
    } catch (e) {
        // fallback if response is plain text
        if (xhr.responseText) msg = xhr.responseText;
    }

    toastr.error('❌ ' + msg);
}

    });
}
</script>

<script>
function togglePanel(panelId) {
    $("#sms-content").hide();
    $(panelId).toggle(); 
}

function toggleSMSContent() {
    $("#sms-content").show(); 
    $("#send-sms").hide(); 
    var formData = new FormData();
    var customer_id = $("#customer_id").val();

    if(customer_id == "") {
        $.ajax({
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            url: '/chat-msg-ai',
            method: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                var data = JSON.parse(response);
                var customerId = data.response.customer_id;
                $("#customer_id").val(customerId);
            },
            error: function (errors) {
                console.log(errors);
            },
        });
    }
}



</script>

<script>
    var maxLength = 160;
    $('#new_message').keyup(function()
    {
        var textlen = maxLength - $(this).val().length;
        $('#rchars').text(textlen);
    });

    $('#new_data_message').keyup(function()
    {
        var textlen = maxLength - $(this).val().length;
        $('#rchars_msg').text(textlen);
    });

</script>
    <script src="<?php echo e(asset('asset/js/SIPml-api.js')); ?>"  type="text/javascript"></script>
    <script type="text/javascript">

        var sTransferNumber;
        var oRingTone, oRingbackTone;
        var oSipStack, oSipSessionRegister, oSipSessionCall, oSipSessionTransferCall;
        var videoRemote, videoLocal, audioRemote;
        var bFullScreen = false;
        var oNotifICall;
        var bDisableVideo = false;
        var viewVideoLocal, viewVideoRemote, viewLocalScreencast; // <video> (webrtc) or <div> (webrtc4all)
        var oConfigCall;
        var oReadyStateTimer;

        C = {
            divKeyPadWidth: 220
        };

        window.onload = function() {
            window.console && window.console.info && window.console.info("location=" + window.location);

            videoLocal = document.getElementById("video_local");
            videoRemote = document.getElementById("video_remote");
            audioRemote = document.getElementById("audio_remote");

            document.onkeyup = onKeyUp;
            document.body.onkeyup = onKeyUp;
            divCallCtrl.onmousemove = onDivCallCtrlMouseMove;

            // set debug level
            SIPml.setDebugLevel((window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_debug') == "true") ? "error" : "info");
            loadCredentials();
            // loadCallOptions();

            // Initialize call button
            uiBtnCallSetText("Call");

            var getPVal = function(PName) {
                var query = window.location.search.substring(1);
                var vars = query.split('&');
                for (var i = 0; i < vars.length; i++) {
                    var pair = vars[i].split('=');
                    if (decodeURIComponent(pair[0]) === PName) {
                        return decodeURIComponent(pair[1]);
                    }
                }
                return null;
            }

            var preInit = function() {
                // set default webrtc type (before initialization)
                var s_webrtc_type = getPVal("wt");
                var s_fps = getPVal("fps");
                var s_mvs = getPVal("mvs"); // maxVideoSize
                var s_mbwu = getPVal("mbwu"); // maxBandwidthUp (kbps)
                var s_mbwd = getPVal("mbwd"); // maxBandwidthUp (kbps)
                var s_za = getPVal("za"); // ZeroArtifacts
                var s_ndb = getPVal("ndb"); // NativeDebug

                if (s_webrtc_type) SIPml.setWebRtcType(s_webrtc_type);

                // initialize SIPML5
                SIPml.init(postInit);

                // set other options after initialization
                if (s_fps) SIPml.setFps(parseFloat(s_fps));
                if (s_mvs) SIPml.setMaxVideoSize(s_mvs);
                if (s_mbwu) SIPml.setMaxBandwidthUp(parseFloat(s_mbwu));
                if (s_mbwd) SIPml.setMaxBandwidthDown(parseFloat(s_mbwd));
                if (s_za) SIPml.setZeroArtifacts(s_za === "true");
                if (s_ndb == "true") SIPml.startNativeDebug();

                //var rinningApps = SIPml.getRunningApps();
                //var _rinningApps = Base64.decode(rinningApps);
                //tsk_utils_log_info(_rinningApps);
            }

            oReadyStateTimer = setInterval(function() {
                    if (document.readyState === "complete") {
                        clearInterval(oReadyStateTimer);
                        // initialize SIPML5
                        preInit();
                    }
                },
                500);

            /*if (document.readyState === "complete") {
                preInit();
            }
            else {
                document.onreadystatechange = function () {
                    if (document.readyState === "complete") {
                        preInit();
                    }
                }
            }*/
        };

        function postInit() { // check for WebRTC support
            if (!SIPml.isWebRtcSupported()) { // is it chrome?
                if (SIPml.getNavigatorFriendlyName() == 'chrome') {
                    if (confirm("You're using an old Chrome version or WebRTC is not enabled.\nDo you want to see how to enable WebRTC?")) {
                        window.location = 'http://www.webrtc.org/running-the-demos';
                    } else {
                        window.location = "index.html";
                    }
                    return;
                } else {
                    if (confirm("webrtc-everywhere extension is not installed. Do you want to install it?\nIMPORTANT: You must restart your browser after the installation.")) {
                        window.location = 'https://github.com/sarandogou/webrtc-everywhere';
                    } else { // Must do nothing: give the user the chance to accept the extension
                            // window.location = "index.html";
                        }
                    }
            }

            // checks for WebSocket support
            if (!SIPml.isWebSocketSupported()) {
                if (confirm('Your browser don\'t support WebSockets.\nDo you want to download a WebSocket-capable browser?')) {
                    window.location = 'https://www.google.com/intl/en/chrome/browser/';
                } else {
                    window.location = "index.html";
                }
                return;
            }

            // FIXME: displays must be per session
            viewVideoLocal = videoLocal;
            viewVideoRemote = videoRemote;

            if (!SIPml.isWebRtcSupported()) {
                if (confirm('Your browser don\'t support WebRTC.\naudio/video calls will be disabled.\nDo you want to download a WebRTC-capable browser?')) {
                    window.location = 'https://www.google.com/intl/en/chrome/browser/';
                }
            }

            btnRegister.disabled = false;
            btnUnRegister.style.display = "none";

            document.body.style.cursor = 'default';
            oConfigCall = {
                audio_remote: audioRemote,
                video_local: viewVideoLocal,
                video_remote: viewVideoRemote,
                screencast_window_id: 0x00000000, // entire desktop
                bandwidth: {
                    audio: undefined,
                    video: undefined
                },
                video_size: {
                    minWidth: undefined,
                    minHeight: undefined,
                    maxWidth: undefined,
                    maxHeight: undefined
                },
                events_listener: {
                    events: '*',
                    listener: onSipEventSession
                },
                sip_caps: [{
                        name: '+g.oma.sip-im'
                    },
                    {
                        name: 'language',
                        value: '\"en,fr\"'
                    }
                ]
            };
        }


        // function loadCallOptions() {
        //     if (window.localStorage) {
        //         var s_value;
        //         if ((s_value = window.localStorage.getItem('org.doubango.call.phone_number'))) txtPhoneNumber.value = s_value;
        //         bDisableVideo = (window.localStorage.getItem('org.doubango.expert.disable_video') == "true");
        //
        //         // txtCallStatus.innerHTML = '<i>Video ' + (bDisableVideo ? 'disabled' : 'enabled') + '</i>';
        //     }
        // }

        function saveCallOptions() {
            if (window.localStorage) {
                // window.localStorage.setItem('org.doubango.call.phone_number', txtPhoneNumber.value);
                window.localStorage.setItem('org.doubango.expert.disable_video', bDisableVideo ? "true" : "false");
            }
        }

        function loadCredentials() {
            if (window.localStorage) {
                window.localStorage.setItem('org.doubango.identity.display_name', '<?php echo Session::get('display_name'); ?>');
                window.localStorage.setItem('org.doubango.identity.impi', '<?php echo Session::get('private_identity'); ?>');
                window.localStorage.setItem('org.doubango.identity.impu', '<?php echo Session::get('public_identity'); ?>');
                window.localStorage.setItem('org.doubango.identity.password', '<?php echo Session::get('password'); ?>');
                window.localStorage.setItem('org.doubango.identity.realm', '<?php echo Session::get('realm'); ?>');
                window.localStorage.setItem('org.doubango.expert.websocket_server_url', '<?php echo Session::get('websocket_server_url'); ?>');
                window.localStorage.setItem('org.doubango.expert.disable_video', "true");
                window.localStorage.setItem('org.doubango.expert.enable_rtcweb_breaker', "true");
                window.localStorage.setItem('org.doubango.expert.sip_outboundproxy_url', "");
                window.localStorage.setItem('org.doubango.expert.ice_servers', "<?php echo Session::get('ice_servers'); ?>");
                window.localStorage.setItem('org.doubango.expert.bandwidth', "");
                window.localStorage.setItem('org.doubango.expert.video_size', "");
                window.localStorage.setItem('org.doubango.expert.disable_early_ims', "true");
                window.localStorage.setItem('org.doubango.expert.disable_debug', "true");
                window.localStorage.setItem('org.doubango.expert.enable_media_caching', "true");
                window.localStorage.setItem('org.doubango.expert.disable_callbtn_options', "true");

            } else {
                console.log("localStorage error");
            }
        };

                    // sends SIP REGISTER request to login
                    function sipRegister() {
                        // catch exception for IE (DOM not ready)
                        try {
                            btnRegister.disabled = true;
                            btnRegister.style.display = "none";
                            btnUnRegister.style.display = "block";
                            if (!window.localStorage.getItem('org.doubango.identity.realm') || !window.localStorage.getItem('org.doubango.identity.impi') || !window.localStorage.getItem('org.doubango.identity.impu')) {
                                //txtRegStatus.innerHTML = '<b>Extension settings are incomplete!</b>';
                                txtRegStatus.innerHTML = '';

                                btnRegister.disabled = false;
                                btnRegister.style.display = "block";
                                btnUnRegister.style.display = "none";
                                return;
                            }
                            var o_impu = tsip_uri.prototype.Parse(window.localStorage.getItem('org.doubango.identity.impu'));
                            if (!o_impu || !o_impu.s_user_name || !o_impu.s_host) {
                                txtRegStatus.innerHTML = "<b>[" + window.localStorage.getItem('org.doubango.identity.impu') + "] is not a valid Public identity</b>";
                                btnRegister.disabled = false;
                                btnRegister.style.display = "block";
                                btnUnRegister.style.display = "none";
                                return;
                            }

                            // enable notifications if not already done
                            if (window.webkitNotifications && window.webkitNotifications.checkPermission() != 0) {
                                window.webkitNotifications.requestPermission();
                            }

                            // save credentials
                            // saveCredentials();

                            // update debug level to be sure new values will be used if the user haven't updated the page
                            SIPml.setDebugLevel((window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_debug') == "true") ? "error" : "info");

                            // create SIP stack
                            oSipStack = new SIPml.Stack({
                                realm: window.localStorage.getItem('org.doubango.identity.realm'),
                                impi: window.localStorage.getItem('org.doubango.identity.impi'),
                                impu: window.localStorage.getItem('org.doubango.identity.impu'),
                                password: window.localStorage.getItem('org.doubango.identity.password'),
                                display_name: window.localStorage.getItem('org.doubango.identity.display_name'),
                                websocket_proxy_url: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.websocket_server_url') : null),
                                outbound_proxy_url: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.sip_outboundproxy_url') : null),
                                ice_servers: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.ice_servers') : null),
                                enable_rtcweb_breaker: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.enable_rtcweb_breaker') == "true" : false),
                                events_listener: {
                                    events: '*',
                                    listener: onSipEventStack
                                },
                                enable_early_ims: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.disable_early_ims') != "true" : true), // Must be true unless you're using a real IMS network
                                enable_media_stream_cache: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.enable_media_caching') == "true" : false),
                                bandwidth: (window.localStorage ? tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.bandwidth')) : null), // could be redefined a session-level
                                video_size: (window.localStorage ? tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.video_size')) : null), // could be redefined a session-level
                                sip_headers: [{
                                        name: 'User-Agent',
                                        value: 'IM-client/OMA1.0 sipML5-v1.2016.03.04'
                                    },
                                    {
                                        name: 'Organization',
                                        value: 'Doubango Telecom'
                                    }
                                ]
                            });

                            if (oSipStack.start() != 0) {
                                txtRegStatus.innerHTML = '<b>Failed to start the SIP stack</b>';
                            } else return;
                        } catch (e) {
                            txtRegStatus.innerHTML = "<b>2:" + e + "</b>";
                        }
                        btnRegister.disabled = false;
                        btnRegister.style.display = "block";
                        btnUnRegister.style.display = "none";
                    }

                    // sends SIP REGISTER (expires=0) to logout
                    function sipUnRegister() {
                        if (oSipStack) {
                            oSipStack.stop(); // shutdown all sessions
                            btnRegister.style.display = "block";
                            btnUnRegister.style.display = "none";
                        }
                    }

                    // makes a call (SIP INVITE)


                    function sipCall(s_type) {
                       // alert(s_type);

                        var numberToCall = txtPhoneNumber.value.replace("(", "").replace(")", "").replace(" ", "").replace("-", "").replace(/_/gi, "");
                        //alert(numberToCall);

                        var selectedCountryCode = $(".country_code").val();

                        //alert(selectedCountryCode);


                        numberToCall = selectedCountryCode + numberToCall;

                       // alert(numberToCall);


                        if (oSipStack && !oSipSessionCall && !tsk_string_is_null_or_empty(numberToCall)) {
                            //alert(numberToCall);
                            if (s_type == 'call-screenshare') {
                                if (!SIPml.isScreenShareSupported()) {
                                    alert('Screen sharing not supported. Are you using chrome 26+?');
                                    return;
                                }
                                if (!location.protocol.match('https')) {
                                    if (confirm("Screen sharing requires https://. Do you want to be redirected?")) {
                                        sipUnRegister();
                                        window.location = 'https://ns313841.ovh.net/call.htm';
                                    }
                                    return;
                                }
                            }
                            btnCall.disabled = true;
                            btnHangUp.disabled = false;

                            // if (window.localStorage) {
                            // oConfigCall.bandwidth = tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.bandwidth')); // already defined at stack-level but redifined to use latest values
                            // oConfigCall.video_size = tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.video_size')); // already defined at stack-level but redifined to use latest values
                            // }

                            // create call session
                            oSipSessionCall = oSipStack.newSession(s_type, oConfigCall);

                            // make call
                            /*var numberToCall = txtPhoneNumber.value;
                            if (numberToCall.length > 9) {
                                numberToCall = '91' + numberToCall;
                            }
*/
                            if (oSipSessionCall.call(numberToCall) != 0) {
                                oSipSessionCall = null;
                                txtCallStatus.value = 'Failed to make call';
                                btnCall.disabled = false;
                                btnHangUp.disabled = true;
                                return;
                            }
                            saveCallOptions();
                        } else if (oSipSessionCall) {
                            txtCallStatus.innerHTML = '<i>Connecting...</i>';
                            oSipSessionCall.accept(oConfigCall);
                        }
                    }
                   

                    // Share entire desktop aor application using BFCP or WebRTC native implementation
                    function sipShareScreen() {
                        if (SIPml.getWebRtcType() === 'w4a') {
                            // Sharing using BFCP -> requires an active session
                            if (!oSipSessionCall) {
                                txtCallStatus.innerHTML = '<i>No active session</i>';
                                return;
                            }
                            if (oSipSessionCall.bfcpSharing) {
                                if (oSipSessionCall.stopBfcpShare(oConfigCall) != 0) {
                                    txtCallStatus.value = 'Failed to stop BFCP share';
                                } else {
                                    oSipSessionCall.bfcpSharing = false;
                                }
                            } else {
                                oConfigCall.screencast_window_id = 0x00000000;
                                if (oSipSessionCall.startBfcpShare(oConfigCall) != 0) {
                                    txtCallStatus.value = 'Failed to start BFCP share';
                                } else {
                                    oSipSessionCall.bfcpSharing = true;
                                }
                            }
                        } else {
                            sipCall('call-screenshare');
                        }
                    }

                    // transfers the call
                    function sipTransfer() {
                        if (oSipSessionCall) {
                            var s_destination = prompt('Enter destination number', '');
                            if (!tsk_string_is_null_or_empty(s_destination)) {
                                btnTransfer.disabled = true;
                                if (oSipSessionCall.transfer(s_destination) != 0) {
                                    txtCallStatus.innerHTML = '<i>Call transfer failed</i>';
                                    btnTransfer.disabled = false;
                                    return;
                                }
                                txtCallStatus.innerHTML = '<i>Transfering the call...</i>';
                            }
                        }
                    }

                    // holds or resumes the call
                    function sipToggleHoldResume() {
                        if (oSipSessionCall) {
                            var i_ret;
                            btnHoldResume.disabled = true;
                            txtCallStatus.innerHTML = oSipSessionCall.bHeld ? '<i>Resuming the call...</i>' : '<i>Holding the call...</i>';
                            i_ret = oSipSessionCall.bHeld ? oSipSessionCall.resume() : oSipSessionCall.hold();
                            if (i_ret != 0) {
                                txtCallStatus.innerHTML = '<i>Hold / Resume failed</i>';
                                btnHoldResume.disabled = false;
                                return;
                            }
                        }
                    }

                    // Mute or Unmute the call
                    function sipToggleMute() {
                        if (oSipSessionCall) {
                            var i_ret;
                            var bMute = !oSipSessionCall.bMute;
                            txtCallStatus.innerHTML = bMute ? '<i>Mute the call...</i>' : '<i>Unmute the call...</i>';
                            i_ret = oSipSessionCall.mute('audio' /*could be 'video'*/ , bMute);
                            if (i_ret != 0) {
                                txtCallStatus.innerHTML = '<i>Mute / Unmute failed</i>';
                                return;
                            }
                            oSipSessionCall.bMute = bMute;
                            btnMute.value = bMute ? "Unmute" : "Mute";
                        }
                    }

                    // terminates the call (SIP BYE or CANCEL)
                    function sipHangUp() {
                        if (oSipSessionCall) {
                            txtCallStatus.innerHTML = '<i>Terminating the call...</i>';
                            oSipSessionCall.hangup({
                                events_listener: {
                                    events: '*',
                                    listener: onSipEventSession
                                }
                            });
                        }
                    }

                    function sipSendDTMF(c) {
                        if (oSipSessionCall && c) {
                            if (oSipSessionCall.dtmf(c) == 0) {
                                try {
                                    dtmfTone.play();
                                } catch (e) {}
                            }
                        }
                    }

                    function startRingTone() {
                        try {
                            ringtone.play();
                            closeNav1();
                        } catch (e) {}
                    }

                    function stopRingTone() {
                        try {
                            ringtone.pause();
                        } catch (e) {}
                    }

                    function startRingbackTone() {
                        try {
                            ringbacktone.play();
                        } catch (e) {}
                    }

                    function stopRingbackTone() {
                        try {
                            ringbacktone.pause();
                        } catch (e) {}
                    }

                    function toggleFullScreen() {
                        if (videoRemote.webkitSupportsFullscreen) {
                            fullScreen(!videoRemote.webkitDisplayingFullscreen);
                        } else {
                            fullScreen(!bFullScreen);
                        }
                    }

                    function openKeyPad() {
                        divKeyPad.style.visibility = 'visible';
                        divKeyPad.style.left = ((document.body.clientWidth - C.divKeyPadWidth) >> 1) + 'px';
                        divKeyPad.style.top = '70px';
                        // divGlassPanel.style.visibility = 'visible';
                    }

                    function closeKeyPad() {
                        divKeyPad.style.left = '0px';
                        divKeyPad.style.top = '0px';
                        divKeyPad.style.visibility = 'hidden';
                        // divGlassPanel.style.visibility = 'hidden';
                    }

                    function fullScreen(b_fs) {
                        bFullScreen = b_fs;
                        if (tsk_utils_have_webrtc4native() && bFullScreen && videoRemote.webkitSupportsFullscreen) {
                            if (bFullScreen) {
                                videoRemote.webkitEnterFullScreen();
                            } else {
                                videoRemote.webkitExitFullscreen();
                            }
                        } else {
                            if (tsk_utils_have_webrtc4npapi()) {
                                try {
                                    if (window.__o_display_remote) window.__o_display_remote.setFullScreen(b_fs);
                                } catch (e) {
                                    divVideo.setAttribute("class", b_fs ? "full-screen" : "normal-screen");
                                }
                            } else {
                                divVideo.setAttribute("class", b_fs ? "full-screen" : "normal-screen");
                            }
                        }
                    }

                    function showNotifICall(s_number) {
                        // permission already asked when we registered
                        if (window.webkitNotifications && window.webkitNotifications.checkPermission() == 0) {
                            if (oNotifICall) {
                                oNotifICall.cancel();
                            }
                            oNotifICall = window.webkitNotifications.createNotification('images/sipml-34x39.png', 'Incaming call', 'Incoming call from ' + s_number);
                            oNotifICall.onclose = function() {
                                oNotifICall = null;
                            };
                            oNotifICall.show();
                        }
                    }

                    function onKeyUp(evt) {
                        evt = (evt || window.event);
                        if (evt.keyCode == 27) {
                            fullScreen(false);
                        } else if (evt.ctrlKey && evt.shiftKey) { // CTRL + SHIFT
                            if (evt.keyCode == 65 || evt.keyCode == 86) { // A (65) or V (86)
                                bDisableVideo = (evt.keyCode == 65);
                                txtCallStatus.innerHTML = '<i>Video ' + (bDisableVideo ? 'disabled' : 'enabled') + '</i>';
                                window.localStorage.setItem('org.doubango.expert.disable_video', bDisableVideo);
                            }
                        }
                    }

                    function onDivCallCtrlMouseMove(evt) {
                        try { // IE: DOM not ready
                            if (tsk_utils_have_stream()) {
                                btnCall.disabled = (!tsk_utils_have_stream() || !oSipSessionRegister || !oSipSessionRegister.is_connected());
                                document.getElementById("divCallCtrl").onmousemove = null; // unsubscribe
                            }
                        } catch (e) {}
                    }

                    function uiOnConnectionEvent(b_connected, b_connecting) { // should be enum: connecting, connected, terminating, terminated
                        btnRegister.disabled = b_connected || b_connecting;
                        btnUnRegister.disabled = !b_connected && !b_connecting;
                        btnCall.disabled = !(b_connected && tsk_utils_have_webrtc() && tsk_utils_have_stream());
                        btnHangUp.disabled = !oSipSessionCall;

                        if (btnRegister.disabled) {
                            btnRegister.style.display = "none";
                            btnUnRegister.style.display = "block";
                        } else {
                            btnRegister.style.display = "block";
                            btnUnRegister.style.display = "none";
                        }

                        if (btnCall.disabled) {
                            btnCall.style.display = "none";
                            btnHangUp.style.display = "inline-block";
                        } else {
                            btnCall.style.display = "inline-block";
                            btnHangUp.style.display = "none";
                        }
                    }

                    function uiVideoDisplayEvent(b_local, b_added) {
                        var o_elt_video = b_local ? videoLocal : videoRemote;

                        if (b_added) {
                            o_elt_video.style.opacity = 1;
                            // uiVideoDisplayShowHide(true);
                        } else {
                            o_elt_video.style.opacity = 0;
                            fullScreen(false);
                        }
                    }

                    function uiVideoDisplayShowHide(b_show) {
                        if (b_show) {
                            tdVideo.style.height = '340px';
                            divVideo.style.height = navigator.appName == 'Microsoft Internet Explorer' ? '100%' : '340px';
                        } else {
                            tdVideo.style.height = '0px';
                            divVideo.style.height = '0px';
                        }
                        btnFullScreen.disabled = !b_show;
                    }

                    function uiDisableCallOptions() {
                        if (window.localStorage) {
                            window.localStorage.setItem('org.doubango.expert.disable_callbtn_options', 'true');
                            uiBtnCallSetText('Call');
                            alert('Use expert view to enable the options again (/!\\requires re-loading the page)');
                        }
                    }

                    function uiBtnCallSetText(s_text) {
                        switch (s_text) {
                            case "Call": {
                                var bDisableCallBtnOptions = (window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_callbtn_options') == "true");
                                btnCall.value = btnCall.innerHTML = bDisableCallBtnOptions ? '<i class="fa fa-phone"></i>' : '<i class="fa fa-phone"></i>';
                                btnCall.setAttribute("class", bDisableCallBtnOptions ? "btn btn-primary" : "btn btn-primary dropdown-toggle");
                                btnCall.onclick = bDisableCallBtnOptions ? function() {
                                    sipCall('call-audio');
                                } : null;
                                // ulCallOptions.style.visibility = bDisableCallBtnOptions ? "hidden" : "visible";
                                if (!bDisableCallBtnOptions && ulCallOptions.parentNode != divBtnCallGroup) {
                                    divBtnCallGroup.appendChild(ulCallOptions);
                                } else if (bDisableCallBtnOptions && ulCallOptions.parentNode == divBtnCallGroup) {
                                    document.body.appendChild(ulCallOptions);
                                }

                                break;
                            }
                            default: {
                                btnCall.value = btnCall.innerHTML = s_text;
                                btnCall.setAttribute("class", "btn btn-primary");
                                btnCall.onclick = function() {
                                    sipCall('call-audio');
                                };
                                ulCallOptions.style.visibility = "hidden";
                                if (ulCallOptions.parentNode == divBtnCallGroup) {
                                    document.body.appendChild(ulCallOptions);
                                }
                                break;
                            }
                        }
                    }

                    function uiCallTerminated(s_description) {
                        uiBtnCallSetText("Call");
                        btnHangUp.value = 'HangUp';
                        btnHoldResume.value = 'hold';
                        btnMute.value = "Mute";
                        btnCall.disabled = false;
                        btnHangUp.disabled = true;
                        btnCall.style.display = "block";
                        btnHangUp.style.display = "none";

                        $("#offsetbutton").show();
                        $("#dialpad-backspace").show();

                        if (window.btnBFCP) window.btnBFCP.disabled = true;

                        oSipSessionCall = null;

                        stopRingbackTone();
                        stopRingTone();

                        txtCallStatus.innerHTML = "<i>" + s_description + "</i>";
                        // uiVideoDisplayShowHide(false);
                        divCallOptions.style.opacity = 0;

                        if (oNotifICall) {
                            oNotifICall.cancel();
                            oNotifICall = null;
                        }

                        // uiVideoDisplayEvent(false, false);
                        // uiVideoDisplayEvent(true, false);

                        setTimeout(function() {
                            if (!oSipSessionCall) txtCallStatus.innerHTML = '';
                        }, 2500);
                    }

                    // Callback function for SIP Stacks
                    function onSipEventStack(e /*SIPml.Stack.Event*/ ) {
                        console.log("onSipEventStack", e);
                        tsk_utils_log_info('==stack event = ' + e.type);
                        switch (e.type) {
                            case 'started': {
                                // catch exception for IE (DOM not ready)
                                try {
                                    // LogIn (REGISTER) as soon as the stack finish starting
                                    oSipSessionRegister = this.newSession('register', {
                                        expires: 200,
                                        events_listener: {
                                            events: '*',
                                            listener: onSipEventSession
                                        },
                                        sip_caps: [{
                                                name: '+g.oma.sip-im',
                                                value: null
                                            },
                                            //{ name: '+sip.ice' }, // rfc5768: FIXME doesn't work with Polycom TelePresence
                                            {
                                                name: '+audio',
                                                value: null
                                            },
                                            {
                                                name: 'language',
                                                value: '\"en,fr\"'
                                            }
                                        ]
                                    });
                                    oSipSessionRegister.register();
                                } catch (e) {
                                    txtRegStatus.value = txtRegStatus.innerHTML = "<b>1:" + e + "</b>";
                                    btnRegister.disabled = false;
                                    btnRegister.style.display = "block";
                                    btnUnRegister.style.display = "none";
                                }
                                break;
                            }
                            case 'stopping':
                            case 'stopped':
                            case 'failed_to_start':
                            case 'failed_to_stop': {
                                var bFailure = (e.type == 'failed_to_start') || (e.type == 'failed_to_stop');
                                oSipStack = null;
                                oSipSessionRegister = null;
                                oSipSessionCall = null;

                                uiOnConnectionEvent(false, false);

                                stopRingbackTone();
                                stopRingTone();

                                // uiVideoDisplayShowHide(false);
                                divCallOptions.style.opacity = 0;

                                txtCallStatus.innerHTML = '';
                                txtRegStatus.innerHTML = bFailure ? "<i>Disconnected: <b>" + e.description + "</b></i>" : "<i>Disconnected</i>";
                                break;
                            }

                            case 'i_new_call': {
                                if (oSipSessionCall) {
                                    // do not accept the incoming call if we're already 'in call'
                                    e.newSession.hangup(); // comment this line for multi-line support
                                } else {
                                    oSipSessionCall = e.newSession;
                                    // start listening for events
                                    oSipSessionCall.setConfiguration(oConfigCall);

                                    // uiBtnCallSetText('Answer');
                                    btnHangUp.value = 'Reject';
                                    btnCall.disabled = false;
                                    btnHangUp.disabled = false;
                                    btnCall.style.display = "block";
                                    btnHangUp.style.display = "inline-block";

                                    $("#offsetbutton").hide();
                                    $("#dialpad-backspace").hide();

                                    startRingTone();

                                    var sRemoteNumber = (oSipSessionCall.getRemoteFriendlyName() || 'unknown');
                                    txtCallStatus.innerHTML = "<i>Incoming call from [<b>" + sRemoteNumber + "</b>]</i>";
                                    showNotifICall(sRemoteNumber);
                                }
                                break;
                            }

                            case 'm_permission_requested': {
                                // divGlassPanel.style.visibility = 'visible';
                                break;
                            }
                            case 'm_permission_accepted':
                            case 'm_permission_refused': {
                                // divGlassPanel.style.visibility = 'hidden';
                                if (e.type == 'm_permission_refused') {
                                    uiCallTerminated('Media stream permission denied');
                                }
                                break;
                            }

                            case 'starting':
                            default:
                                break;
                        }
                    };

                    // Callback function for SIP sessions (INVITE, REGISTER, MESSAGE...)
                    function onSipEventSession(e /* SIPml.Session.Event */ ) {
                        tsk_utils_log_info('==session event = ' + e.type);
                        console.log("onSipEventSession", e);
                        switch (e.type) {
                            case 'connecting':
                            case 'connected': {
                                var bConnected = (e.type == 'connected');
                                if (e.session == oSipSessionRegister) {
                                    uiOnConnectionEvent(bConnected, !bConnected);
                                    txtRegStatus.innerHTML = "<i>" + e.description + "</i>";
                                } else if (e.session == oSipSessionCall) {
                                    btnHangUp.value = 'HangUp';
                                    btnCall.disabled = true;
                                    btnHangUp.disabled = false;
                                    btnTransfer.disabled = false;
                                    btnCall.style.display = "none";
                                    btnHangUp.style.display = "inline-block";

                                    $("#offsetbutton").show();
                                    $("#dialpad-backspace").show();

                                    if (window.btnBFCP) window.btnBFCP.disabled = false;

                                    if (bConnected) {
                                        stopRingbackTone();
                                        stopRingTone();

                                        if (oNotifICall) {
                                            oNotifICall.cancel();
                                            oNotifICall = null;
                                        }
                                    }

                                    txtCallStatus.innerHTML = "<i>" + e.description + "</i>";
                                    divCallOptions.style.opacity = bConnected ? 1 : 0;

                                    if (SIPml.isWebRtc4AllSupported()) { // IE don't provide stream callback
                                        uiVideoDisplayEvent(false, true);
                                        uiVideoDisplayEvent(true, true);
                                    }
                                }
                                break;
                            } // 'connecting' | 'connected'
                            case 'terminating':
                            case 'terminated': {
                                if (e.session == oSipSessionRegister) {
                                    uiOnConnectionEvent(false, false);

                                    oSipSessionCall = null;
                                    oSipSessionRegister = null;

                                    txtRegStatus.innerHTML = "<i>" + e.description + "</i>";
                                } else if (e.session == oSipSessionCall) {
                                    uiCallTerminated(e.description);
                                }
                                break;
                            } // 'terminating' | 'terminated'

                            case 'm_stream_video_local_added': {
                                if (e.session == oSipSessionCall) {
                                    uiVideoDisplayEvent(true, true);
                                }
                                break;
                            }
                            case 'm_stream_video_local_removed': {
                                if (e.session == oSipSessionCall) {
                                    uiVideoDisplayEvent(true, false);
                                }
                                break;
                            }
                            case 'm_stream_video_remote_added': {
                                if (e.session == oSipSessionCall) {
                                    uiVideoDisplayEvent(false, true);
                                }
                                break;
                            }
                            case 'm_stream_video_remote_removed': {
                                if (e.session == oSipSessionCall) {
                                    uiVideoDisplayEvent(false, false);
                                }
                                break;
                            }

                            case 'm_stream_audio_local_added':
                            case 'm_stream_audio_local_removed':
                            case 'm_stream_audio_remote_added':
                            case 'm_stream_audio_remote_removed': {
                                break;
                            }

                            case 'i_ect_new_call': {
                                oSipSessionTransferCall = e.session;
                                break;
                            }

                            case 'i_ao_request': {
                                if (e.session == oSipSessionCall) {
                                    var iSipResponseCode = e.getSipResponseCode();
                                    if (iSipResponseCode == 180 || iSipResponseCode == 183) {
                                        startRingbackTone();
                                        txtCallStatus.innerHTML = '<i>Remote ringing...</i>';
                                    }
                                }
                                break;
                            }

                            case 'm_early_media': {
                                if (e.session == oSipSessionCall) {
                                    stopRingbackTone();
                                    stopRingTone();
                                    txtCallStatus.innerHTML = '<i>Early media started</i>';
                                }
                                break;
                            }

                            case 'm_local_hold_ok': {
                                if (e.session == oSipSessionCall) {
                                    if (oSipSessionCall.bTransfering) {
                                        oSipSessionCall.bTransfering = false;
                                        // this.AVSession.TransferCall(this.transferUri);
                                    }
                                    btnHoldResume.value = 'Resume';
                                    btnHoldResume.disabled = false;
                                    txtCallStatus.innerHTML = '<i>Call placed on hold</i>';
                                    oSipSessionCall.bHeld = true;
                                }
                                break;
                            }
                            case 'm_local_hold_nok': {
                                if (e.session == oSipSessionCall) {
                                    oSipSessionCall.bTransfering = false;
                                    btnHoldResume.value = 'Hold';
                                    btnHoldResume.disabled = false;
                                    txtCallStatus.innerHTML = '<i>Failed to place remote party on hold</i>';
                                }
                                break;
                            }
                            case 'm_local_resume_ok': {
                                if (e.session == oSipSessionCall) {
                                    oSipSessionCall.bTransfering = false;
                                    btnHoldResume.value = 'Hold';
                                    btnHoldResume.disabled = false;
                                    txtCallStatus.innerHTML = '<i>Call taken off hold</i>';
                                    oSipSessionCall.bHeld = false;

                                    if (SIPml.isWebRtc4AllSupported()) { // IE don't provide stream callback yet
                                        uiVideoDisplayEvent(false, true);
                                        uiVideoDisplayEvent(true, true);
                                    }
                                }
                                break;
                            }
                            case 'm_local_resume_nok': {
                                if (e.session == oSipSessionCall) {
                                    oSipSessionCall.bTransfering = false;
                                    btnHoldResume.disabled = false;
                                    txtCallStatus.innerHTML = '<i>Failed to unhold call</i>';
                                }
                                break;
                            }
                            case 'm_remote_hold': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Placed on hold by remote party</i>';
                                }
                                break;
                            }
                            case 'm_remote_resume': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Taken off hold by remote party</i>';
                                }
                                break;
                            }
                            case 'm_bfcp_info': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = 'BFCP Info: <i>' + e.description + '</i>';
                                }
                                break;
                            }

                            case 'o_ect_trying': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Call transfer in progress...</i>';
                                }
                                break;
                            }
                            case 'o_ect_accepted': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Call transfer accepted</i>';
                                }
                                break;
                            }
                            case 'o_ect_completed':
                            case 'i_ect_completed': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Call transfer completed</i>';
                                    btnTransfer.disabled = false;
                                    if (oSipSessionTransferCall) {
                                        oSipSessionCall = oSipSessionTransferCall;
                                    }
                                    oSipSessionTransferCall = null;
                                }
                                break;
                            }
                            case 'o_ect_failed':
                            case 'i_ect_failed': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = '<i>Call transfer failed</i>';
                                    btnTransfer.disabled = false;
                                }
                                break;
                            }
                            case 'o_ect_notify':
                            case 'i_ect_notify': {
                                if (e.session == oSipSessionCall) {
                                    txtCallStatus.innerHTML = "<i>Call Transfer: <b>" + e.getSipResponseCode() + " " + e.description + "</b></i>";
                                    if (e.getSipResponseCode() >= 300) {
                                        if (oSipSessionCall.bHeld) {
                                            oSipSessionCall.resume();
                                        }
                                        btnTransfer.disabled = false;
                                    }
                                }
                                break;
                            }
                            case 'i_ect_requested': {
                                if (e.session == oSipSessionCall) {
                                    var s_message = "Do you accept call transfer to [" + e.getTransferDestinationFriendlyName() + "]?"; //FIXME
                                    if (confirm(s_message)) {
                                        txtCallStatus.innerHTML = "<i>Call transfer in progress...</i>";
                                        oSipSessionCall.acceptTransfer();
                                        break;
                                    }
                                    oSipSessionCall.rejectTransfer();
                                }
                                break;
                            }
                        }
                    }
                </script>
                <script>
                    //Webphone dialpad
                    $(document).on('click', '.dialpad-number', function(e) {
                        var currentVal = $('#txtPhoneNumber').val();
                        var newVal = currentVal + $(this).val();
                        txtPhoneNumber.value = newVal;
                    });
                    //Webphone back button
                    /*$(document).on('click', '#dialpad-backspace', function(e) {
                        var currentVal = $('#txtPhoneNumber').val();
                        var newVal = currentVal.substring(0, currentVal.length - 1);
                        txtPhoneNumber.value = newVal;
                    });*/

                    $(document).on('click', '#dialpad-backspace', function (e) {
    var currentVal = $('#txtPhoneNumber').val();
    currentVal = currentVal.replace("(", "").replace(")", "").replace(" ", "").replace("-", "").replace(/_/gi, "");
    var newVal = currentVal.substring(0, currentVal.length - 1);
    txtPhoneNumber.value = newVal;
});


                    $(document).ready(function() {

                        $("#btnUnRegister").click(function() {
                            $("#wrapper_class").removeClass("bg-green");
                            //$("#wrapper_class").addClass("bg-red");
                            $.ajax({
                                url: 'webphone/switch-access',
                                type: 'POST',
                                data: {
                                    "_token": $("#csrf-token").val(),
                                    is_checked: false
                                },
                                dataType: "json",
                                success: function(response) {
                                    toastr.success(response);
                                    if (response == "Webphone Enabled") {
                                        // window.open("<?php echo e(url('/webphone')); ?>", "webphone", "menubar=0,resizable=0,width=300,height=580");
                                    }
                                },
                                error: function(response) {
                                    console.log(response);
                                }
                            });
                        });
                        setTimeout(function() {
                            //$("#btnRegister").trigger('click');
                            $("#btnRegister").click(function() {
                               // $("#show_nev").removeClass("youtube");
                               // $("#wrapper_class").removeClass("bg-red");

                                
                                //$("#show_nev").addClass("youtube1");
                                $("#wrapper_class").addClass("bg-green");

                                $.ajax({
                                    url: 'webphone/switch-access',
                                    type: 'POST',
                                    data: {
                                        "_token": $("#csrf-token").val(),
                                        is_checked: true
                                    },
                                    dataType: "json",
                                    success: function(response) {
                                        toastr.success(response);
                                        if (response == "Webphone Enabled") {
                                            // window.open("<?php echo e(url('/webphone')); ?>", "webphone", "menubar=0,resizable=0,width=300,height=580");

                                        }
                                    },
                                    error: function(response) {
                                        console.log(response);
                                    }
                                });
                            });

                        }, 1000);
                        window.onbeforeunload = function(e) {
                            e.preventDefault();
                            if (oSipStack || oSipSessionCall) {
                                toastr.error("Don't close this page when you are in connection.");
                                return false;
                            }
                        };
                    });
                </script>



<script>

    $("#country_code").change(function(){

        var code  = $("#country_code").val();
        $("#changeCountryCode").html('+'+code);


    });

     function openNav() {
        $("#webphone_open").toggle();

         $("#sms-content").hide();

    }

     function closeNav1() {

        $("#webphone_open").show();

       
    }
    function closeNav() {

$("#webphone_open").hide();


}

    </script>

<script src="<?php echo e(url('/asset/js/input-mask/jquery.inputmask.js')); ?>"></script>
<script src="<?php echo e(url('asset/js/chat/cf_custom_chat.js')); ?>"></script>



</body>

</html><?php /**PATH /var/www/html/leadmine/leadmine_pro/resources/views/dialer/start_dialer_demo.blade.php ENDPATH**/ ?>