/*$(document).ready(function() {
  //alert('hi');
  $('#loading').hide();
});*/

$(".make-autocomplete").select2(); //code for auto-complete in service 


$(".chosen-select").chosen(); //js for multiselect

function post_ajax(url, data) 

{
  var result1 = '';
  var result2 = '';
   $.ajax({
        type: "GET",
        url: base_url+'Home/islogedin',
    success: function(response) 
    {
      result1 = response;
      item = JSON.parse(result1);
      //console.log("login ",item)
      if(item.status=='success')
      {   
          $.ajax({
          type: "POST",
          url: url,
          data: data,
          success: function(response) {
            result2 = response;
          },
          error: function(response) {
            result2 = 'error';
          },
          async: false
          });
      }
      else
      {
        window.location.href = base_url+'Home/logout';
      }
    },
    error: function(response) {
      result = 'error';
    },
    async: false
    });
    return result2;
}

function post_ajax_serialize(url, data) 
{
   var result1 = '';
   var result2 = '';
    $.ajax({
        type: "GET",
        url: base_url+'Home/islogedin',
    success: function(response) 
    {
      result1 = response;
      item = JSON.parse(result1);
      //console.log("login ",item)
      if(item.status=='success')
      {   
          $.ajax({
              type: "POST",
              url: url,
              data: data,
              contentType:false,
              processData:false,
          success: function(response) {
            result2 = response;
          },
          error: function(response) {
            result2 = 'error';
          },
          async: false
          });
      }
      else
      {
        window.location.href = base_url+'Home/logout';
      }
    },
    error: function(response) {
      result = 'error';
    },
    async: false
    });
    return result2;
}

/*  $(document).ajaxStart(function(val) {
    console.log('ajaxStart',val)
    $('.full_screen_loader').removeClass('hidden');
  })
  */
  $( document ).ajaxSend(function( event, jqxhr, settings ) {
    if(!(settings.url==base_url+'Home/get_recent_chat') && !(settings.url==base_url+'Home/update_recent_chat'))
    {
     $('.full_screen_loader').removeClass('hidden');
    }
});

  $(document).ajaxStop(function() {
    //console.log('ajaxStop')
    setTimeout(function(){
    $('.full_screen_loader').addClass('hidden');
    },150)
  });



function initialize_map(id) {

   
    var latitude = $('#'+id).data('lat')
    var longitude = $('#'+id).data('lng')

    var myLatlng = new google.maps.LatLng(latitude,longitude);
    var mapOptions = {
    zoom: 14,
    scrollwheel: false,
    disableDefaultUI: true,
    center: myLatlng
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    var contentString = '';
    var infowindow = new google.maps.InfoWindow({
    content: '<div class="map-content"><p>Clinic Location</p></div>'
    });

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map

    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
  }

  function load_filterchange()
  {
    var filter_data = $('#searchfilter_form').serialize();
    //console.log(filter_data);
    var filter_response = post_ajax(base_url+'Searchdoctor/filter_search',filter_data);
    $('#searchresult').html(filter_response);
    load_dynamic_map();

   /* $('#search_filter_loader').addClass('hidden');*/
  }
  
$('#reg-doc-temppic').hide();
function doc_loadthumbnail(file)
 {
  $('#reg-doc-temppic').show();
  var tmppath = URL.createObjectURL(file.files[0]);
  $('#reg-doc-temppic').attr('src',tmppath);
  //console.log(file.files[0])
 }

 $('#reg-pat-temppic').hide();
function pat_loadthumbnail(file)
 {
  $('#reg-pat-temppic').show();
  var tmppath = URL.createObjectURL(file.files[0]);
  $('#reg-pat-temppic').attr('src',tmppath);
  //console.log(file.files[0])
 }

Global_getLocation = function() 
  {
    if (navigator.geolocation) 
    {
     var item =  navigator.geolocation.getCurrentPosition(Global_showPosition,errorCallbackLocation,{timeout:20000});     
    } 
  }

  Global_showPosition = function(position) 
  {
    /*code for reverse geo location*/
      var geocoder = new google.maps.Geocoder;
      var latlng = {lat:position.coords.latitude, lng: position.coords.longitude};
      geocoder.geocode({'location': latlng}, function(results, status) 
      {
        if(status === 'OK')
        {
          if (results[1]) 
          {
            var marker = new google.maps.Marker({position: latlng});
            //console.log("position : ",position.coords.latitude,position.coords.longitude,results[3].formatted_address);
            var location_finder = {'latitude' : position.coords.latitude,
                            'longitude' : position.coords.longitude,
                            'address' : results[3].formatted_address};
            sessionStorage.location_finder = JSON.stringify(location_finder);
          } 
        } 
        else 
        {
          //console.log('Cant Find Your Location!');
        }
      });

  }

//Callback function for Location delay
errorCallbackLocation = function(error)
      {
        //console.log(error)
        if(error.code==3)
          alert(error.message+'. Cant Find Your Location,Try Again Later');
        window.location.reload();
      }

 function cancel_consult(thiss)
{
  var object = {'booking_id': thiss};
  var result = post_ajax(base_url+'Patient/getBooking',object);
  var items = JSON.parse(result);
 
  $('#cancel-consult-modal-name').html(items.doc_name);
  $('#cancel-consult-modal-spec').html(items.doc_specialization);
  $('#cancel-consult-modal-date').html(items.book_date);
  $('#cancel-consult-modal-time').html(items.book_time);
  $('#cancel-consult-modal-pic').attr('src',items.doc_pic);
  $('#cancel-consult-modal-btn').attr('bookingid',items.book_id);
  $('#pop2').modal('show');
}   

function change_consult(thiss)
{
  var object = {'booking_id': thiss};
  var result = post_ajax(base_url+'Patient/reScheduleConsultation',object);
  var items = JSON.parse(result);

  $('#reschedule_book_id').attr('value',items.book_id)
  $('#reschedule_book_clinic').attr('value',items.clinic_id)
  $('#reschedule_book_doctor').attr('value',items.doc_id)
  $('#reschedule-consult-name').html(items.doc_name);
  $('#reschedule-consult-spec').html(items.doc_specialization);
  $('#reschedule-consult-date').html(items.book_date);
  $('#reschedule-consult-time').html(items.book_time);
  $('#reschedule-consult-pic').attr('src',items.doc_pic);
 // $('#reschedule-consult-btn').attr('bookingid',items.book_id);
  $('#pop4').modal('show');
}  

function appendTimer_Service(time)
{
  var element = $('#doc_service_timer');
  element.html(time);
}

function pat_edit_loadthumbnail(file)
 {
  var tmppath = URL.createObjectURL(file.files[0]);
  $('#pat-edt-pic').attr('src',tmppath);
  $('#pat-edt-pic-inp').attr('data-parsley-required','true');
 }

function doc_edit_loadthumbnail(file)
 {
  var tmppath = URL.createObjectURL(file.files[0]);
  $('#doc-edt-pic').attr('src',tmppath);
  //console.log(file.files[0])
  $('#doc-edt-pic-inp').attr('data-parsley-required','true');
 }

 function pat_add_depend_loadthumbnail(file,id)
 {
  //console.log(file.files[0])
  var tmppath = URL.createObjectURL(file.files[0]);
  //console.log(tmppath);
 // $('#pat-add-depend-pic').attr('src',tmppath);
  $('#'+id).attr('src',tmppath);
 }

function readURL(input,id) 
{
    if (input.files && input.files[0]) 
    {
      var reader = new FileReader();
      reader.onload = function (e) 
      {
        $('#'+id).attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
    }
}

 function get_current_datetime_format()
 {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  var stamp = ""+mm+"/"+dd+"/"+yyyy+" "+h+":"+m+":"+s;
  return stamp;
 }

  function getTimezoneOffset(){
    function z(n){return (n<10? '0' : '') + n}
    var offset = new Date().getTimezoneOffset();
    var sign = offset < 0? '+' : '-';
    offset = Math.abs(offset);
    var diff ={'sign':sign, 'hour':z(offset/60 | 0), 'minute':z(offset%60)}
    return diff;
  }

var offset = getTimezoneOffset();

var array_other_obsr_file = [];
function certificate_images_loadthumbnail(file)
   {
    $('#certificate-show-img,#certificate-show-details').empty();
    array_other_obsr_file = [];
    elem = file.files;
    for (var i = 0; i < elem.length; i++) 
    {
      var tmppath = URL.createObjectURL(elem[i]);
      array_other_obsr_file[i] = elem[i];
      var img_div = '<li id="othr-obsr-img'+i+'" pos="'+i+'"><img src="'+tmppath+'"></li>'
      $('#certificate-show-img').append(img_div);

      var name_div = '<li id="othr-obsr-det'+i+'" pos="'+i+'"><div class="ip_attach_file_name">'+elem[i].name+'</div><div class="ip_attach_close remove_othr_obsr_img" pos="'+i+'"><img src="'+base_url+'assets/images/ip_attach_close.png"></div><div class="ip_attach_file_size">'+(elem[i].size)/1000+' KB</div><div class="clear"></div></li>'
      $('#certificate-show-details').append(name_div);
    }
    //console.log(array_other_obsr_file)
 }

$(function(){


/*  CONTACT US PAGE*/
$('#contact-us-send-btn').click(function()
{
  $('#contactus-success,#contactus-error').addClass('hidden');
  if($('#contactus-form').parsley().validate())
  {
    //console.log($('#contactus-form').serialize())
    var result = post_ajax(base_url+'Home/send_contactus',$('#contactus-form').serialize());
    var item = JSON.parse(result);
    if(item.status=="success")
    {
      $('#contactus-form').trigger("reset");
      $('#contactus-success').removeClass('hidden');
    }
    else
    {
      $('#contactus-error').removeClass('hidden');
    }
  }
})

  /*PATIENT NOTIFICATION PAGE BEGINS*/

  $(document).on("click","#pat-noti-loadmore",function() 
  {
    var pageno = $('#pat-noti-pageno').val();
    var result = post_ajax(base_url+'Patient/notification_ajax',{'page':pageno});
    $('#pat-noti-view').html(result);
  })

  $('#request-redemption-btn').click(function()
  {
     $('#redemption-success-error').addClass('hidden')
    if($('#redempetion-req-form').parsley().validate())
    {
      //console.log($('#redempetion-req-form').serialize())
      var result = post_ajax(base_url+'Home/redemptionrequest',$('#redempetion-req-form').serialize());
      var items = JSON.parse(result);
      if(items.status=='success')
      {
        $('.reset-redemption-form').val('');
        $('#redemption-success-error').removeClass('hidden').removeClass('alert-danger').addClass('alert-success').html(items.message);
      }
      else
      {
        $('#redemption-success-error').removeClass('hidden').removeClass('alert-success').addClass('alert-danger').html(items.message);
      }
    }
  })

  /*WALLET PAGE STARTS*/

  $(document).on('click','.delete-bank-btn',function()
  {
    var elm = this;
    var bank_id = this.getAttribute('bankid');
    var result = post_ajax(base_url+'Home/removeBank',{'bank_id': bank_id});
     $('#show_all_saved_banks').html(result);

    var result_new = post_ajax(base_url+'Home/refreshBankList');
    $('#show_bank_for_redemption').html(result_new);
  })
  

  $('#add-bank-reg-btn').click(function()
  {
    $('#add-bank-success-error').addClass('hidden');
    if($('#add-bank-form').parsley().validate())
    {
      //console.log($('#add-bank-form').serialize())
      var result = post_ajax(base_url+'Home/addBank',$('#add-bank-form').serialize());
      var items = JSON.parse(result);
      if(items.status=='success')
      {
        $('#add-bank-success-error').removeClass('alert-danger').addClass('alert-success').removeClass('hidden').html(items.message);
        var result_inner = post_ajax(base_url+'Home/getAllBanks');
        //console.log(result_inner);
        $('#show_all_saved_banks').html(result_inner);
        $('.reset-bank-form').val('');
        
        var result_new = post_ajax(base_url+'Home/refreshBankList');
        $('#show_bank_for_redemption').html(result_new);
      }
      else
      {
        $('#add-bank-success-error').removeClass('alert-success').addClass('alert-danger').removeClass('hidden').html(items.message);
      }
    }
  })

  /*WALLET PAGE ENDS*/

  /*DELETE COLLABORATOR PROFILE*/
  $('#delete-colaborator-btn').click(function()
  {
    var elem = this;
    var colabor = elem.getAttribute('colabor');
    var result = post_ajax(base_url+'Doctor/removeColaborator',{'collaborator_id':colabor});
    var items = JSON.parse(result);
    if(items.status=="success")
    {
        $('#success-collaborator-del').modal('show');
        $("#success-collaborator-del").on("hidden.bs.modal", function () {
        window.location.href= base_url;
        });
    }
    else
    {
      $('#colabor-edit-error').removeClass('hidden').html(items.message);
    }
    
  })

  /*EDIT &UPDATE COLLABORATOR PROFILE SAVE BTN*/
  $('#edit-colaborator-btn').click(function()
  {
    var element = this;
    //console.log(element.getAttribute('collabor'))
    $('#colabor-add-success,#colabor-auth-access-success,#colabor-auth-access-error,#colabor-add-error').addClass('hidden');
    if($('#edit-colaborator-form').parsley().validate())
    {
      //console.log($('#edit-colaborator-form').serialize())
      var formData = new FormData();
      formData.append('data',$('#edit-colaborator-form').serialize());
      formData.append('image', $('#colabor-pic-edit')[0].files[0]);      // Attach file
      formData.append('section', 'profile');      // Attach file
      formData.append('colabor_id', element.getAttribute('collabor'));    
      
      var result = post_ajax_serialize(base_url+'Doctor/updateColaborator',formData);
      var items = JSON.parse(result);
      //console.log(items);
      if(items.status=="success")
      {
        $('#colabor-edit-success').removeClass('hidden');
      }
      else if(items.status=="error" && items.error=="Upload Error")
      {
        $('#colabor-edit-error').removeClass('hidden').html(items.message);
      }
      else 
      {
        $('#colabor-edit-error').removeClass('hidden');
      }
    }
  })


  $('#colabor-auth-access').click(function(){
    $('#colabor-auth-access-success,#colabor-auth-access-error').addClass('hidden');
    var elem = this;
    var colabor = elem.getAttribute('colabor');
    if(colabor!=null&&colabor.length!=0)
    {
      var access_obj = $('#colabor-auth-access-form').serializeArray();
      access_obj[access_obj.length] = {'name':'colabor_id','value':colabor};
      //console.log(access_obj);
      var result = post_ajax(base_url+'Doctor/updateColaborator',access_obj);
      var items = JSON.parse(result);
      if(items.status=='success')
      {
        $('#colabor-auth-access-success').removeClass('hidden');
      }
      else
      {
        $('#colabor-auth-access-error').removeClass('hidden');
      }
    }
    else
    {
      $('#colabor-auth-access-error').removeClass('hidden');
    }
  })

  /*COLABORATOR ADDING EMAIL VALIDATION STARTS*/
/*----------------------------------*/
 window.Parsley.addValidator('emailcolabor', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'email':value }
        var status;
        var result = post_ajax(base_url+'Home/check_email_colabor',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Email not Available!'  }
    });

  $('#add-colaborator-btn').click(function()
  {
    $('#authorize-access-div,#colabor-add-success,#colabor-auth-access-success,#colabor-auth-access-error,#colabor-add-error').addClass('hidden');
    if($('#add-colaborator-form').parsley().validate())
    {
      var formData = new FormData();
      formData.append('data',$('#add-colaborator-form').serialize());
      formData.append('image', $('#colabor-pic')[0].files[0]);      // Attach file
      
      var result = post_ajax_serialize(base_url+'Doctor/saveColaborator',formData);
      var items = JSON.parse(result);
      //console.log(items);
      if(items.status=="success")
      {
        $('#colabor-auth-access').attr('colabor',items.colaborator);
        $('#authorize-access-div,#colabor-add-success').removeClass('hidden');
      }
      else if(items.status=="error" && items.error=="Upload Error")
      {
        $('#colabor-add-error').removeClass('hidden').html(items.message);
      }
      else 
      {
        $('#colabor-add-error').removeClass('hidden');
      }
    }
  })

  //Reset password save btn
  $('#reset-password-save-btn').click(function(){
    if($('#reset-password-form').parsley().validate())
    {
      var result = post_ajax(base_url+'Home/sav_reset',$('#reset-password-form').serialize());
      var items = JSON.parse(result);
      if(items.status=="success")
      {
        $('#forgot-pass-div').addClass('hidden');
        $('#forgot-pass-success').removeClass('hidden');

      }
    }
  })


  $('#broadcast-msg-sent-btn').click(function(){
    var broadcast_msg= $("#broadcasttext").val(CKEDITOR.instances.broadcasttext.getData())[0].value;
    var users = $('#sentbroad-users').html();

    if(broadcast_msg.length>0&&users.length>0)
    {
      var result = post_ajax(base_url+'Doctor/sentBroadcast',{'json_obj':JSON.stringify(json_array_broadcast),'message':broadcast_msg});
      var items = {'status':'success'}
      if(items.status=='success')
      {
        $('#sent-broadcast').modal('hide');
        $('#success').modal('show');
      }
    }
    else if(users.length==0)
    {
      $('#broad-users-error').removeClass('hidden');
    }
    else if(broadcast_msg.length==0)
    {
      $('#broad-msg-error').removeClass('hidden');
    }

  })


  /*FUNCTION FOR SENTING BROADCAST MESSAGE*/
  var json_array_broadcast = [];

  $(document).on('click','.sent-broadcast-btn',function()
  {
    CKEDITOR.instances.broadcasttext.setData('', function(){this.checkDirty();});
    $('#broad-msg-error,#broad-users-error').addClass('hidden');
    json_array_broadcast = []
    $("input:checkbox[name=sent-broad-attend]:checked").each(function() {
        var obj = {'patient_id' : $(this).val(),
                    'pat_name' : $(this).attr('patname'),
                    'pat_pic' : $(this).attr('patpic')
                  }
        json_array_broadcast.push(obj);
    });
    var users = json_array_broadcast.map(x=>x.pat_name).join(",");
    $('#sentbroad-users').html(users);
    $('#sent-broadcast').modal('show');
    
  }) 

  $(document).on('click','.sent-broadcast-btn-sch',function()
  {
    CKEDITOR.instances.broadcasttext.setData('', function(){this.checkDirty();});
    $('#broad-msg-error,#broad-users-error').addClass('hidden');
    json_array_broadcast = []
    $("input:checkbox[name=sent-broad-sch]:checked").each(function() {
        var obj = {'patient_id' : $(this).val(),
                    'pat_name' : $(this).attr('patname'),
                    'pat_pic' : $(this).attr('patpic')
                  }
        json_array_broadcast.push(obj);
    });
    var users = json_array_broadcast.map(x=>x.pat_name).join(",");
    $('#sentbroad-users').html(users);
    $('#sent-broadcast').modal('show');
    
  })

  /*FUNCTION FOR OPEN MEDICAL RECORDS IN RECORDSVIEW PAGE*/
  $('.show_record_recordview_btn').click(function()
  {
    var booking_id = this.getAttribute('book');
    //console.log(booking_id);
    var result = post_ajax(base_url+'Doctor/loadrecord/'+booking_id);
    $('#load-med-record-view').html(result);

  })

  $('.record-section-mail-btn').click(function(){
    var record_id = this.getAttribute('record');
    var section = this.getAttribute('func');
    var result = post_ajax(base_url+'Sentmail/'+section+'/'+record_id);
    var item = JSON.parse(result);
    if(item.status=="success")
    {
      $('#sentmail-dialog-success').modal('show');
    }
    else if(item.status=="error")
    {
      $('#sentmail-dialog-error').modal('show');
    }
  })


  $('.record-sent-mail').click(function(){
    var record_id = this.getAttribute('record');
    var result = post_ajax(base_url+'Sentmail/record/'+record_id);
    var item = JSON.parse(result);
    if(item.status=="success")
    {
      $('#sentmail-dialog-success').modal('show');
    }
    else if(item.status=="error")
    {
      $('#sentmail-dialog-error').modal('show');
    }

  })


  $(document).on("click","#doc-noti-loadmore",function() 
  {
    var pageno = $('#doc-noti-pageno').val();
    var result = post_ajax(base_url+'Doctor/notification_ajax',{'page':pageno});
    $('#doc-noti-view').html(result);
  })

/*DOCTOR - START SERVICE*/
/*----------------------------------------*/
$('#patient_review_record_btn').click(function()
{
  if($('#patient_review_record').parsley().validate())
  { 
    var obj =$('#patient_review_record').serializeArray();
    obj.push({'name':'offset','value':JSON.stringify(offset)})
    var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',obj);
    var items = JSON.parse(result);
    //console.log(items)
    if(items.status=='success')
    {
      $('#review-success').removeClass('hidden').html(items.msg);
      setTimeout(function(){
        $('#review-success').addClass('hidden');
      },10000)
    }
    else
    {
      $('#review-error').removeClass('hidden').html(items.msg);
      setTimeout(function(){
        $('#review-error').addClass('hidden');
      },10000)
    }


   }
})

/*----------------------------------------*/
/*DOCTOR - START SERVICE*/
/*----------------------------------------*/

/*FUNCTION FOR DELETE IMAGES FROM OTHER OBSERVATION - SERVICE*/


$(document).on("click",".remove_othr_obsr_img",function() 
{
  elem = this;
  index = elem.getAttribute('pos');
  array_other_obsr_file.splice(index, 1);
  $('#othr-obsr-img'+index+',#othr-obsr-det'+i).remove();

  //replacing the appending div with new array elements
  $('#certificate-show-img,#certificate-show-details').empty();
  for (var i = 0; i < array_other_obsr_file.length; i++) 
    {
      var tmppath = URL.createObjectURL(array_other_obsr_file[i]);

      var img_div = '<li id="othr-obsr-img'+i+'" pos="'+i+'"><img src="'+tmppath+'"></li>'
      $('#certificate-show-img').append(img_div);

      var name_div = '<li id="othr-obsr-det'+i+'" pos="'+i+'"><div class="ip_attach_file_name">'+array_other_obsr_file[i].name+'</div><div class="ip_attach_close remove_othr_obsr_img" pos="'+i+'"><img src="'+base_url+'assets/images/ip_attach_close.png"></div><div class="ip_attach_file_size">'+(array_other_obsr_file[i].size)/1000+' KB</div><div class="clear"></div></li>'
      $('#certificate-show-details').append(name_div);
    }

})


 /*FUNCTION FOR FINAL SAVE BUTTON - SERVICE*/
 $('#record-final-save-btn').click(function(){

  var form_obj = $('#record-final-save-form').serializeArray();
  var files = array_other_obsr_file;
  if($('#doc-service-record').parsley().validate())
  {
    //console.log($('#doc-service-record').serializeArray())
    var obsr_desc = $("#certificate").val(CKEDITOR.instances.otherobservation.getData());
    var formData = new FormData(); // Currently empty
    formData.append('booking_id', form_obj[0].value);      //
    formData.append('section', form_obj[1].value);      //
    formData.append('obsr', obsr_desc[0].value);      //
    formData.append('main_complaint', $('#doc-service-record').serializeArray()[2].value);      //
    for (var i = 0; i < files.length; i++) 
    {
      formData.append('images[]', files[i]);      //
    }
       /*for (var key of formData.entries()) {
            console.log(key[0] + ', ' + key[1]);
          }*/

    var result = post_ajax_serialize(base_url+'Doctor/save_medicalrecord_finaldata',formData);
    var items = JSON.parse(result);
    //console.log(items)
    if(items.status=='success')
    {
      window.location.href = base_url+'Doctor/endservice/'+items.booking_id;
    }
    else
    {
      $('#final-save-error').removeClass('hidden').html(items.msg);
      setTimeout(function(){
        $('#final-save-error').addClass('hidden');
      },10000)
    }
  }
})


/*FUNCTION FOR SAVING CERTIFICATE DATA IN DB - SERVICE*/

$('#certificate-save-btn').click(function(){

  var certificate_desc = $("#certificate").val(CKEDITOR.instances.certificate.getData());
  //console.log(certificate_desc[0].value.length);
  if($('#add-letter-form').parsley().validate())
  {
      if(certificate_desc[0].value.length<20)
      {
        $('#certificate-error').removeClass('hidden');
        setTimeout(function()
        {
                $('#certificate-error').addClass('hidden');
        },10000)
      }
      else
      {
        var data = {'certificate' : certificate_desc[0].value,
                    'booking_id' : this.getAttribute('bookid'),
                    'section'  : this.getAttribute('section'),
                    'days'  : $('#certificate-days').val(),
                    'cid' : $('#certificate-cid').val()}

        type = $("input[name='choose-certificate-type']:checked").val();
        if(type=='standard')
        {
          data.is_letter_with_cid = false;
        }
        else if(type=="standardcid")
        {
          data.is_letter_with_cid = true;
        }

        var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',data);
        var items = JSON.parse(result);

         if(items.status=="success")
            {
              $('#med-rec-letter-print,#med-rec-letter-mail').removeClass('hidden');
              $('#certificate-success').removeClass('hidden').html(items.msg);
              setTimeout(function(){
                $('#certificate-success').addClass('hidden');
              },10000)
            }
            else
            {
              $('#certificate-error').removeClass('hidden').html(items.msg);
              setTimeout(function(){
                $('#certificate-error').addClass('hidden');
              },10000)
            }

      }
  }
  


})

/*FUNCTION FOR LOADING TEXTAREA DATA - CERTIFICATE*/

$('.certificate-type').change(function()
{
 
  type = $("input[name='choose-certificate-type']:checked").val();
            
  //type =  this.getAttribute('value');
  pat_id = $('#patdetail').attr('patid');
  pat_name = $('#patdetail').text();

  day_count = $('#certificate-days').val();
  if(day_count === null)
  {
    day_count = 'XX';
  }

  cid = $('#certificate-cid').val();
  if(cid === null)
  {
    cid = 'XXXXXXXXXXXXXX';
  }

  if(type=='standard')
  {
    var text = $('#certificatedata').attr("standard");
    var text = text.replace("@@@@", pat_name);
    var text = text.replace("$$$$", pat_id);
   // var text = text.replace("%%%%", cid);
    var text = text.replace("****", day_count);
    //console.log(text);
    //var text = 'I certify for the proper purposes at the request of the interested party that the patient '+pat_name+', bearer of the identity document '+pat_id+' was submitted to medical consultation on this date.As a result, he must stay away from his work for a period of '+day_count+' days from this date.';
  }
  else if(type=="standardcid")
  {
    var text = $('#certificatedata').attr("standardcid");
    var text = text.replace("@@@@", pat_name);
    var text = text.replace("$$$$", pat_id);
    var text = text.replace("%%%%", cid);
    var text = text.replace("****", day_count);
    //console.log(text);
    //var text = 'I certify for the proper purposes at the request of the interested party that the patient '+pat_name+', bearer of the identity document '+pat_id+' was submitted to medical consultation on this date, being a CID-10 affection '+cid+'.As a result, he must stay away from his work for a period of '+day_count+' days from this date.';
  }
  
    CKEDITOR.instances.certificate.setData( text, function()
  {
      this.checkDirty();  // true
  });

})

/*FUNCTION FOR ADDING SELECTED MEDICINE TO DB*/
$('#selected-budget-final-save').click(function()
{
  var lan = $('#language').val();
  count = json_array_budget.length;
  if(count>0)
  {
    //console.log($('#selected-medicine-form').serialize());
    var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',$('#selected-budget-form').serialize());
    var items = JSON.parse(result);
     if(items.status=="success")
        {
          $('#med-rec-budget-mail,#med-rec-budget-print').removeClass('hidden');
          $('#budget-success').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#budget-success').addClass('hidden');
          },10000)
        }
        else
        {
          $('#budget-error').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#budget-error').addClass('hidden');
          },10000)
        }
  }
  else
  {
    if(lan == 'en'){
      $('#budget-error').removeClass('hidden').html("Please Add Procedures");
            setTimeout(function(){
              $('#budget-error').addClass('hidden');
            },10000)
    }else{
       $('#budget-error').removeClass('hidden').html("Por favor, adicione procedimentos");
            setTimeout(function(){
              $('#budget-error').addClass('hidden');
            },10000)
    }
  }
})


/*FUNCTION FOR DELETE ADDED BUDGET*/
$(document).on("click",".budget-delete",function() 
{
  var elem = this;
  var divid = elem.getAttribute('divid');
  var array_pos = elem.getAttribute('pos');

  $('#'+divid).remove();
  json_array_budget[array_pos].amount = 0;
  sum = 0;
  for (var i = 0; i < json_array_budget.length; i++) 
  {
   sum = sum + (json_array_budget[i].amount * json_array_budget[i].quantity);
  }
  $('#budget-total-price').html(sum);

})
/*----------------------------------------*/

/*FUNCTION FOR ADDING SELECTED PROCEDURE TO JSON ARRAY*/
var json_array_budget = [];
$("#add-procedure-btn").click(function()
{
  if($('#add-procedure-form').parsley().validate())
  {
    form_data = $('#add-procedure-form').serializeArray();
    var obj = {'procedure':form_data[0]['value'],
              'quantity':form_data[1]['value'], 
              'amount':form_data[2]['value']}

    json_array_budget.push(obj)
    index = json_array_budget.length-1;

    //console.log(json_array_budget)
    var div = '<li id="bud'+index+'"><div class="child1">'+form_data[1]['value']+'- '+form_data[0]['value']+'</div><div class="child2">R$'+form_data[2]['value']+'</div><div class="clear"></div><input type="hidden" name="budget[]" value='+"'"+JSON.stringify(obj)+"'"+'><hr><button class="ip_exclude budget-delete" type="button" divid="bud'+index+'" pos="'+index+'">Delete</button></li>';
    $('#show-budget-main').append(div);

    sum = 0;
    for (var i = 0; i < json_array_budget.length; i++) 
    {
     sum = sum + (json_array_budget[i].amount * json_array_budget[i].quantity);
    }
    $('#budget-total-price').html(sum);
    $('#budget-select').val('0').trigger('change');
  }
})

/*FUNCTION FOR ADDING EXAM TO DB*/
$('#add-exam-btn').click(function(){

  if($('#add-exam-form').parsley().validate())
  {

    var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',$('#add-exam-form').serialize());
    var items = JSON.parse(result);
     if(items.status=="success")
        {
          $('#med-rec-exam-mail,#med-rec-exam-print').removeClass('hidden');
          $('#exam-success').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#exam-success').addClass('hidden');
          },10000)
        }
        else
        {
          $('#exam-error').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#exam-error').addClass('hidden');
          },10000)
        }

  }

})

/*FUNCTION FOR ADDING SELECTED MEDICINE TO DB*/
$('#selected-medicine-final-save').click(function()
{
  var lan = $('#language').val();
  count = json_array_medicine.length;
  if(count>0)
  {
    //console.log($('#selected-medicine-form').serialize());
    var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',$('#selected-medicine-form').serialize());
    var items = JSON.parse(result);

     if(items.status=="success")
        {

          $('#medicine-success').removeClass('hidden').html(items.msg);
          $('#med-rec-med-print,#med-rec-med-mail').removeClass('hidden');
          setTimeout(function(){
            $('#medicine-success').addClass('hidden');
          },10000)
        }
        else
        {
          if(lan == 'en'){
            $('#medicine-error').html("Please Add Medicine(s)").removeClass('hidden');
                  setTimeout(function(){
                    $('#medicine-error').addClass('hidden');
                  },10000)  
          }else{
            $('#medicine-error').html("Por favor, adicione Medicine (s)").removeClass('hidden');
                  setTimeout(function(){
                    $('#medicine-error').addClass('hidden');
                  },10000) 
          }
        }
  }
  else
  {
    $('#medicine-error').html("Please Add Medicine(s)").removeClass('hidden');
          setTimeout(function(){
            $('#medicine-error').addClass('hidden');
          },10000)
  }
})


/*FUNCTION FOR SAVING EDITED MEDICINE*/
$('#edit-medicine-btn').click(function()
{
  array_pos = $('#edit-medcine-id').val();
  divid = $('#edit-medcine-id').attr('editdiv');

   if($('#edit-medicine-form').parsley().validate())
  {
    var form_data = $('#edit-medicine-form').serializeArray();
    obj = {'name':form_data[0]['value'],
            'quantity':form_data[1]['value'],
            'procedure':form_data[2]['value']}
    
    json_array_medicine[array_pos] = obj;
    index = array_pos;

    var div = '<h6>'+form_data[0]['value']+' '+form_data[1]['value']+'</h6><p>'+form_data[2]['value']+'</p><div class="ip_medical_pres_btn_bay"><input type="hidden" name="medicine_list[]" value='+"'"+JSON.stringify(obj)+"'"+'><button class="ip_medical_pres_btn medicine-edit" divid=med'+index+' pos="'+index+'" type="button">Edit</button><button class="ip_medical_pres_btn2 medicine-delete" divid=med'+index+' pos="'+index+'" type="button">Delete</button></div>'
    $('#med'+index).html(div);

    $('#edit-medicine-select').val('0').trigger('change');//clearing edit medicine form

    $('#edit-medicine-main').addClass('hidden'); //hiding edit form
    $('#add-medicine-main').removeClass('hidden'); //showing add form

  }

})

/*----------------------------------------*/


/*FUNCTION FOR EDIT SELECTED MEDICINE*/
$(document).on("click",".medicine-edit",function() 
{
  var elem = this;
  var divid = elem.getAttribute('divid');
  var array_pos = elem.getAttribute('pos');
  edit_json = $('#'+divid+' .ip_medical_pres_btn_bay input').val();
  data = JSON.parse(edit_json);
  //console.log(data)

  $('#edit-medcine-id').val(array_pos);
  $('#edit-medcine-id').attr('editdiv',divid);

  $('#edit-medicine-select').val(data.name).trigger('change');
  $('#edit-medicine-quantity').val(data.quantity).trigger('change');
  $('#edit-medicine-dosage').val(data.procedure).trigger('change');
  
  $('#add-medicine-main').addClass('hidden'); //hiding add form
  $('#edit-medicine-main').removeClass('hidden'); //showing edit form

})
/*----------------------------------------*/


/*FUNCTION FOR DELETE SELECTED MEDICINE*/
$(document).on("click",".medicine-delete",function() 
{
  var elem = this;
  var divid = elem.getAttribute('divid');
  var array_pos = elem.getAttribute('pos');
  
  //json_array_medicine.splice(array_pos, 1);
  $('#'+divid).remove();

})
/*----------------------------------------*/

/*FUNCTION FOR ADD MEDICINE AND HANDLING MEDICINE JSON DATA*/
var json_array_medicine =[];
$('#add-medicine-btn').click(function(){

  if($('#add-medicine-form').parsley().validate())
  {
    var form_data = $('#add-medicine-form').serializeArray();
    obj = {'name':form_data[0]['value'],
            'quantity':form_data[1]['value'],
            'procedure':form_data[2]['value']}
    
    json_array_medicine.push(obj)
    index = json_array_medicine.length-1;

    var div = '<li id=med'+index+'><h6>'+form_data[0]['value']+' '+form_data[1]['value']+'</h6><p>'+form_data[2]['value']+'</p><div class="ip_medical_pres_btn_bay"><input type="hidden" name="medicine_list[]" value='+"'"+JSON.stringify(obj)+"'"+'><button class="ip_medical_pres_btn medicine-edit" divid=med'+index+' pos="'+index+'" type="button">Edit</button><button class="ip_medical_pres_btn2 medicine-delete" divid=med'+index+' pos="'+index+'" type="button">Delete</button></div></li>'
    $('#show-medicine-main').append(div);

    $('#medicine-select').val('0').trigger('change');
  }
})

/*----------------------------------------*/

/*FUNCTION FOR DETECT CHANGE IN MEDICAL RECORD SELECT*/
$('.select-in-medi-rec').change(function()
{

  var elem = this;
  var type = elem.getAttribute( "type" );
  if(type=="medicine")
  {
     var object = {'medicine_name':$('#medicine-select').val() }
 
      var result = post_ajax(base_url+'Doctor/get_medicine_details',object);
      var items = JSON.parse(result);


      $('#medicine-quantity').html("<option disabled selected >Select Quantity</option>");
      $('#medicine-dosage').html("<option disabled selected>Select Dosage and administration</option>");

      $.each(items, function (i, item) {

      $('#medicine-quantity').append($('<option>', { 
            value: item.medicine_dosage,
            text : item.medicine_dosage 
        }));

      $('#medicine-dosage').append($('<option>', { 
            value: item.medicine_procedure,
            text : item.medicine_procedure 
        }));


      })
     
  }
  else if(type=="medicine-edit")
  {
     var object = {'medicine_name':$('#edit-medicine-select').val() }
   // console.log(object)
      var result = post_ajax(base_url+'Doctor/get_medicine_details',object);
      var items = JSON.parse(result);


      $('#edit-medicine-quantity').html("<option disabled selected >Select Quantity</option>");
      $('#edit-medicine-dosage').html("<option disabled selected>Select Dosage and administration</option>");

      $.each(items, function (i, item) {

      $('#edit-medicine-quantity').append($('<option>', { 
            value: item.medicine_dosage,
            text : item.medicine_dosage 
        }));

      $('#edit-medicine-dosage').append($('<option>', { 
            value: item.medicine_procedure,
            text : item.medicine_procedure 
        }));


      })
     
  }
  else if(type=="exams")
  {
    var object = {'exam_name':$('#exam-select').val() }
    var result = post_ajax(base_url+'Doctor/get_exam_details',object);
    var items = JSON.parse(result);
    
      $('#exam-observation').html("<option disabled selected >Note</option>");
     

      $.each(items, function (i, item) 
      {

        $('#exam-observation').append($('<option>', { 
              value: item.observation,
              text : item.observation 
          }));

      })
     
  }
  else if(type=="budget")
  {
    var object = {'procedure_name':$('#budget-select').val() }
    var result = post_ajax(base_url+'Doctor/get_budget_details',object);
    var items = JSON.parse(result);
  
    $('#budget-quantity').html("<option disabled selected >Value</option>");
    $('#budget-amount').html("<option disabled selected >Amount</option>");
   

    $.each(items, function (i, item) 
    {

      $('#budget-quantity').append($('<option>', { 
            value: item.quantity,
            text : item.quantity 
        }));

      $('#budget-amount').append($('<option>', { 
            value: item.amount,
            text : item.amount 
        }));

    })
     
  }
})

/*SAVE BUTTON FOR ANAMNESIS*/
$('#record-sec-1-btn').click(function()
{

  if ($('#doc-service-record').parsley().validate() ) 
      { 
        var medical_desc = $("#editor1").val(CKEDITOR.instances.editor1.getData());
        //console.log(medical_desc[0].value);
        var data = $('#doc-service-record').serializeArray();
        data[data.length] = { name: "description", value: medical_desc[0].value };
        
        var result = post_ajax(base_url+'Doctor/save_medicalrecord_data',data);
        var items = JSON.parse(result);
        if(items.status=="success")
        {
          $('#anamnesis-success').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#anamnesis-success').addClass('hidden');
          },10000)
        }
        else
        {
          $('#anamnesis-error').removeClass('hidden').html(items.msg);
          setTimeout(function(){
            $('#anamnesis-error').addClass('hidden');
          },10000)
        }
      }
})


/*----------------------------------------*/


/*DOCTOR - EDIT PROFILE*/
/*----------------------------------------*/

  window.Parsley.addValidator('usernamedocedit', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'username':value }
        var status;
        var result = post_ajax(base_url+'Doctor/check_username_edit',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Username not Available!'  }
    }); 


/*----------------------------------------*/

/*PATIENT - EDIT PROFILE*/
/*----------------------------------------*/

  window.Parsley.addValidator('usernamepatedit', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'username':value }
        var status;
        var result = post_ajax(base_url+'Patient/check_username_edit',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Username not Available!'  }
    }); 


/*----------------------------------------*/


/*DOCTOR - MEDICAL RECORDS*/
/*----------------------------------------*/

$(document).on("change","#select-all-attended",function() {
//$('#select-all-attended').change(function()
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
      
    $('.select-attended').prop('checked', true);
  }
  else
  {
    $('.select-attended').prop('checked', false);
  }
})

$(document).on("change","#select-all-scheduled",function() {
//$('#select-all-scheduled').change(function(){
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('.select-scheduled').prop('checked', true);
  }
  else
  {
    $('.select-scheduled').prop('checked', false);
  }
})

  $(document).on("click","#medical_rec_scheduled_next",function() 
{
  var obj = {'currentpage': $('#medical_rec_scheduled_page').attr('page')}
 //console.log(obj)
  var result = post_ajax(base_url+'Doctor/med_rec_scheduled_next',obj);
  $('#schedulled').html(result);
})

  $(document).on("click","#medical_rec_scheduled_prev",function() 
{
  var obj = {'currentpage': $('#medical_rec_scheduled_page').attr('page')}
 //console.log(obj)
  var result = post_ajax(base_url+'Doctor/med_rec_scheduled_prev',obj);
  $('#schedulled').html(result);
})  

$(document).on("click","#medical_rec_attended_next",function() 
{
  var obj = {'currentpage': $('#medical_rec_attended_page').attr('page')}
 //console.log(obj)
  var result = post_ajax(base_url+'Doctor/med_rec_attended_next',obj);
  $('#attended').html(result);
})

  $(document).on("click","#medical_rec_attended_prev",function() 
{
  var obj = {'currentpage': $('#medical_rec_attended_page').attr('page')}
 //console.log(obj)
  var result = post_ajax(base_url+'Doctor/med_rec_attended_prev',obj);
  $('#attended').html(result);
})

$(document).on('keyup','#med_red_scheduled_search',function () {
  var obj = {'text' : $(this).val()}
  // alert ($(this).val());
  var result = post_ajax(base_url+'Doctor/med_rec_scheduled_search',obj);
  $('#schedulled').html(result);
});

$(document).on('keyup','#med_red_attended_search',function () {
  var obj = {'text' : $(this).val()}
  // alert ($(this).val());
  var result = post_ajax(base_url+'Doctor/med_rec_attended_search',obj);
  $('#attended').html(result);
});

$('#med_rec_filter_month').datepicker({
    format: "MM",
    viewMode: "months", 
    minViewMode: "months",
    autoclose:true
});

$('#med_rec_filter_month').on('changeDate', function(ev) 
{
  //console.log(ev.format(0,"mm/dd/yyyy"));
 /* var result = post_ajax(base_url+'Doctor/med_rec_filter_search',obj);
  $('#attended').html(result);*/
})

/*----------------------------------*/

/*DOCTOR SEARCH - COMPLETE PROFILE*/
/*----------------------------------*/

$('#complete_profile_appointment_nextbtn').on('click',function(){
  var date_end = $('#appoint-week-view-day6').data('date');
  var doc_id = $('#appoint-week-view-day6').data('docid');
  var obj = { 'enddate':date_end,
              'doctor_id':doc_id};
   var result = post_ajax(base_url+'Searchdoctor/doctor_complete_profile_appointments_week_next',obj);
   $('#complete_profile_appointment').html(result);
})
$('#complete_profile_appointment_prevbtn').on('click',function(){
  var date_start = $('#appoint-week-view-day0').data('date');
  var doc_id = $('#appoint-week-view-day0').data('docid');
  var obj = { 'startdate':date_start,
              'doctor_id':doc_id};
   var result = post_ajax(base_url+'Searchdoctor/doctor_complete_profile_appointments_week_prev',obj);
   $('#complete_profile_appointment').html(result);
})

/*----------------------------------*/

/*PATIENT DASHBOARD*/
/*----------------------------------*/

/*PATIENT PROFILE DELETE STARTS*/
$("#delete-complete").on("hidden.bs.modal", function () {
    window.location.href= base_url+"Home/logout";
});

$('#pat_del_check_code_sub').click(function()
{
  $('#pat_profile_delete_code_error').addClass('hidden')
  if ($('#pat_profile_delete_confirmation').parsley().validate() ) 
      { 

        var result = post_ajax(base_url+'Patient/check_current_user_confirmationcode',$('#pat_profile_delete_confirmation').serializeArray());
        var items = JSON.parse(result);
        if(items.status=="success")
        {
          $('#delete-con').modal('hide');
          $('#delete-complete').modal('show');
        }
        else
        {
          $('#pat_profile_delete_code_error').removeClass('hidden').html(items.msg);
        }
      }
})

$('#pat_del_check_login_sub').click(function()
{
  $('#pat_profile_delete_error').addClass('hidden')
  if ($('#pat_profile_delete').parsley().validate() ) 
      { 

        var result = post_ajax(base_url+'Patient/check_current_user_credential',$('#pat_profile_delete').serializeArray());
        var items = JSON.parse(result);
        if(items.status=="success")
        {
          $('#delete').modal('hide');
          $('#delete-con').modal('show');
        }
        else
        {
          $('#pat_profile_delete_error').removeClass('hidden').html(items.msg);
        }
      }
})

$('.delete_profile').click(function()
{
  $('.reset-form').val('');
  $('#pat_profile_delete_error').addClass('hidden')
  $('#delete').modal('show');
})

/*PATIENT PROFILE DELETE ENDS*/

$('.patient_dash_scheduled_consult').on("click", function(){
  var result = post_ajax(base_url+'Patient/load_canceled_booking');
  $('#canceled-schedules-div').html(result);
});

$('.patient_dash_canceled_consult').on("click", function(){
  var result = post_ajax(base_url+'Patient/load_canceled_booking');
  $('#canceled-schedules-div').html(result);
});

$('#cancel-consult-modal-btn').click(function()
{
  var bookingid = $(this).attr('bookingid');
  var object = {'booking_id':bookingid,'UTCoffset':offset}
  var result = post_ajax(base_url+'Patient/check_cancelBooking',object);
  var items = JSON.parse(result);
  if(items.status=="success")
  {
    var bookingid = $(this).attr('bookingid');
    var object = {'booking_id':bookingid}
    var html = post_ajax(base_url+'Patient/cancelBooking',object);
    $('#confirmed-schedules-div').html(html);
    $('#pop2').modal('hide');
  }
  else if(items.status=="error")
  {
    $('#pop2').modal('hide');
    $('#pop3').modal('show');
  }
  
 
})


$('#reschedule_book_date').on('changeDate', function(ev) {

  $('#reschedule-consult-timeslot').html('<option disabled selected>Time Slots</option>');

  var object = {'book_date':$('#reschedule_book_date').val(),'clinic_id':$('#reschedule_book_clinic').val(),
                'doctor_id':$('#reschedule_book_doctor').val()}
  var result = post_ajax(base_url+'Searchdoctor/getDoctorClinic_timeslot',object);

  var elements = JSON.parse(result);
  if(elements.length>0)
  {
    $.each(elements, function (i, item) {
    $('#reschedule-consult-timeslot').append($('<option>', { 
          value: item.time,
          text : item.time 
      }));
    })
  }
  else
  {
     $('#reschedule-consult-timeslot').html('<option disabled selected>No Time Slot Available</option>');
  }

});

/*$('#reschedule-consult-btn').click(function(){

  if ($('#reschedule_book_form').parsley().validate() ) 
      { 
        console.log($('#reschedule_book_form').serialize())
        var result = post_ajax(base_url+'Searchdoctor/checkDoctorAvailability',$('#reschedule_book_form').serializeArray());
        var items = JSON.parse(result);
        if(items.status=="success"&&items.msg=="booking success")
        {
          var result = post_ajax(base_url+'Patient/updateBooking',$('#reschedule_book_form').serializeArray()); 
          $('#pop4').modal('hide');
          $('#confirmed-schedules-div').html(result);
        }
        else if(items.status=="fail"&&items.type=="doctor leave")
        {
          $('#err_reschedule_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_reschedule_booking').addClass('hidden');
            },10000);
        }
        else if(items.status=="fail"&&items.type=="booking slot")
        {
          $('#err_reschedule_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_reschedule_booking').addClass('hidden');
            },10000);
        }
      }

})*/


/*----------------------------------*/




/*CONFIRM BOOKING*/
/*----------------------------------*/
$('.timepicker-cus').timepicker();

$('#tab_login_back').click(function(){
  $('.confirm-tab-2').removeClass('active');
  $('#btnTrigger-review').click();
  $('.confirm-tab-1').addClass('active');
});

$('#tab_payment_back').click(function(){
  $('.confirm-tab-3').removeClass('active');
  $('#btnTrigger-review').click();
  $('.confirm-tab-1').addClass('active');
});

$('#confirm_book_date').on('changeDate', function(ev) {
  $('#schedule-consult-timeslot').html('<option disabled selected></option>');
  //console.log($('#confirm_book_date').val());
  var stamp = get_current_datetime_format();
  var object = {'book_date':$('#confirm_book_date').val(),'clinic_id':$('#confirm_book_clinic').val(),
                'doctor_id':$('#confirm_book_doctor').val(),'currenttime':stamp,'UTCoffset':offset}
  var result = post_ajax(base_url+'Searchdoctor/getDoctorClinic_timeslot',object);
  var elements = JSON.parse(result);
  //console.log(elements);
  if(elements.arr.length>0)
  {
    $('#schedule-consult-timeslot').html('<option disabled selected>'+elements.msg+'</option>');
    $.each(elements.arr, function (i, item) {
    $('#schedule-consult-timeslot').append($('<option>', { 
          value: item.time,
          post:item.start,
          text : item.time 
      }));
    })
  }
  else
  {
     $('#schedule-consult-timeslot').html('<option disabled selected>'+elements.msg+'</option>');
  }

});


$('#confirm_booking_continue_btn').click(function()
{
  $('#book_status').val('1'); //make booking_status confirmed
  $('#waitinglist-div').addClass('hidden');
    if ($('#confirm_book_form').parsley().validate() ) 
      { 
        var stamp = get_current_datetime_format();
        var result = post_ajax(base_url+'Searchdoctor/checkDoctorAvailability',$('#confirm_book_form').serialize()+'&currenttime='+stamp);
        var items = JSON.parse(result);
        if(items.status=="success"&&items.isLogin=="false")
        {
          $('.confirm-tab-1').removeClass('active');
          $('#btnTrigger-login').click();
          $('.confirm-tab-2').addClass('active');
        }
        else if(items.status=="success"&&items.isLogin=="true")
        {
          data = $('#confirm_book_form').serializeArray();
          data.push({'name':'offset','value':JSON.stringify(offset)})
          var result = post_ajax(base_url+'Searchdoctor/markbooking',data);
          var items = JSON.parse(result);
          var booking_id = items.booking_id;
          //console.log(items);
          var payment_required = items.payment_required;
          if(payment_required) //Free Consultation -> goto Confirmation page
          {
            $('#book-date-show').html('On '+items.booking_date+' ');
            $('#book-time-show').html(' at '+items.booking_slot);
            $('.confirm-tab-1').removeClass('active');
            $('#btnTrigger-confirmation').click();
            $('.confirm-tab-4').addClass('active');
          }
          else //Paid Consulation -> goto Payment Page
          {
            $('#book-date-show').html('On '+items.booking_date+' ');
            $('#book-time-show').html(' at '+items.booking_slot);
            $('#book_status').attr('book-id',booking_id);

            // $('.confirm-tab-1').removeClass('active');
            // $('#btnTrigger-payment').click();
            // $('.confirm-tab-3').addClass('active');
             $('#select_cash_mode').modal('show');
          }
        } 
        else if(items.status=="waiting")
        {
          $('#info_confirm_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#info_confirm_booking').addClass('hidden');
            },10000);
          $('#waitinglist-div').removeClass('hidden');
        }
        else if(items.status=="fail"&&items.type=="doctor leave")
        {
          $('#err_confirm_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_confirm_booking').addClass('hidden');
            },10000);
        }
        else if(items.status=="fail"&&items.type=="booking slot")
        {
          $('#err_confirm_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_confirm_booking').addClass('hidden');
            },10000);
        }
      }

})

$('#money_cash').click(function(){
  
  var entered_book_id = document.getElementById("book_status").getAttribute("book-id");
  console.log(entered_book_id);

  $('#select_cash_mode').modal('hide');

   var data = {'book_id':entered_book_id,'payment_status':'1','payment_type':'1'};
   var result = post_ajax(base_url+'Searchdoctor/markpayment',data);
   var items = JSON.parse(result);
   console.log(items);
   //if(items == 'true'){
      $('.confirm-tab-1').removeClass('active');
      $('#btnTrigger-confirmation').click();
      $('.confirm-tab-4').addClass('active');
  // }
  // }
  // else //Paid Consulation -> goto Payment Page
  // {
  //   $('#book_status').attr('book-id',booking_id);
  //   $('.confirm-tab-1').removeClass('active');
  //   $('#btnTrigger-payment').click();
  //   $('.confirm-tab-3').addClass('active');
  // }
})

$('#credit_card_cash').click(function(){

   var entered_book_id = document.getElementById("book_status").getAttribute("book-id");
   //console.log(entered_book_id);
   var data = {'book_id':entered_book_id,'payment_status':'0','payment_type':'2'};
   var result = post_ajax(base_url+'Searchdoctor/markpayment_viacredit',data);
   var items = JSON.parse(result);
   //console.log(items);
  // if(items== 'true'){
    $('#select_cash_mode').modal('hide');
    $('.confirm-tab-1').removeClass('active');
    $('#btnTrigger-payment').click();
    $('.confirm-tab-3').addClass('active');
   //}
})

$('#enter_waiting_list_btn').click(function()
{
  $('#book_status').val('0'); //make booking_status waiting_list
  if ($('#confirm_book_form').parsley().validate() ) 
      { 
        //
        var stamp = get_current_datetime_format();
        var result = post_ajax(base_url+'Searchdoctor/checkDoctorAvailability',$('#confirm_book_form').serialize()+'&currenttime='+stamp);
        var items = JSON.parse(result);
        if(items.status=="success")
        {
          $('#info_confirm_booking').html('Booking Slot Available, Press Continue').removeClass('hidden');
          setTimeout(function(){$('#info_confirm_booking').addClass('hidden');},7000)
          $('#waitinglist-div').addClass('hidden');
          $('#book_status').val('1'); //make booking_status confirmed
        }
        else if(items.status=="waiting"&&items.isLogin=="false")
        {
          $('.confirm-tab-1').removeClass('active');
          $('#btnTrigger-login').click();
          $('.confirm-tab-2').addClass('active');
        }
        else if(items.status=="waiting"&&items.isLogin=="true")
        {
          data = $('#confirm_book_form').serializeArray();
          data.push({'name':'offset','value':JSON.stringify(offset)})
          var result = post_ajax(base_url+'Searchdoctor/markbooking',data);
         
          var booking_id = JSON.parse(result).booking_id;
          var items = JSON.parse(result);
          var payment_required = items.payment_required;
          if(payment_required) //Free Consultation -> goto Confirmation page
          {
            $('#book-date-show').html('On '+items.booking_date+' ');
            $('#book-time-show').html(' at '+items.booking_slot);
            $('.confirm-tab-1').removeClass('active');
            $('#btnTrigger-confirmation').click();
            $('.confirm-tab-4').addClass('active');
          }
          else //Paid Consulation -> goto Payment Page
          {
            $('#book_status').attr('book-id',booking_id);
           $('#entered_book_id').val(booking_id);
            $('.confirm-tab-1').removeClass('active');
            $('#btnTrigger-payment').click();
            $('.confirm-tab-3').addClass('active');
          }
        } 
        else if(items.status=="fail"&&items.type=="doctor leave")
        {
          $('#err_confirm_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_confirm_booking').addClass('hidden');
            },10000);
        }
        else if(items.status=="fail"&&items.type=="booking slot")
        {
          $('#err_confirm_booking').html(items.msg).removeClass('hidden');
           setTimeout(function(){
              $('#err_confirm_booking').addClass('hidden');
            },10000);
        }
      }

  })

$('#confirm-book-login_submit').click(function()
{ 
 if ($('#confirm-book-login-form').parsley().validate() ) 
    { 
      Global_getLocation();
      setTimeout(function()
        {
          var curr_location = JSON.parse(sessionStorage.location_finder);
          var LoginData = $('#confirm-book-login-form').serialize()+'&'+'latitude='+curr_location.latitude+'&'+'longitude='+curr_location.longitude+'&'+'address='+curr_location.address;
          var result = post_ajax(base_url+'Home/login',LoginData);
          var items = JSON.parse(result);
          //console.log(items);
          if(items.status=="error"&&items.error=="Login Failed")
          {
            $('#err-login-ajax').html(items.message).removeClass('hidden');
            setTimeout(function(){
              $('#err-login-ajax').addClass('hidden');
            },10000);

          }
          else if(items.status=="success")
          {
            var stamp = get_current_datetime_format();
            var result_inner = post_ajax(base_url+'Searchdoctor/checkDoctorAvailability',$('#confirm_book_form').serialize()+'&currenttime='+stamp);
            var items_inner = JSON.parse(result_inner);
            //console.log(items_inner)
            if((items_inner.status=="success")||(items_inner.status=="waiting"))
            {
              data = $('#confirm_book_form').serializeArray();
              data.push({'name':'offset','value':JSON.stringify(offset)})
              var result = post_ajax(base_url+'Searchdoctor/markbooking',data);
              var booking_id = JSON.parse(result).booking_id;
              var items = JSON.parse(result);
              var payment_required = items.payment_required;
              if(payment_required) //Free Consultation -> goto Confirmation page
              {
                $('#book-date-show').html('On '+items.booking_date+' ');
                $('#book-time-show').html(' at '+items.booking_slot);
                $('.confirm-tab-2').removeClass('active');
                $('#btnTrigger-confirmation').click();
                $('.confirm-tab-4').addClass('active');
              }
              else //Paid Consulation -> goto Payment Page
              {
                $('#book_status').attr('book-id',booking_id);
                $('#entered_book_id').val(booking_id);
                $('.confirm-tab-2').removeClass('active');
                $('#btnTrigger-payment').click();
                $('.confirm-tab-3').addClass('active');
              }
              
            } 
            else if(items_inner.status=="fail")
            {
              $('.confirm-tab-2').removeClass('active');
              $('#btnTrigger-review').click();
              $('.confirm-tab-1').addClass('active');
              $('#err_confirm_booking').html(items_inner.msg).removeClass('hidden');
              setTimeout(function(){
              $('#err_confirm_booking').addClass('hidden');
              },10000);
            }
           
          }
        },1000);

      
    }

})

$('#promocode_submit_btn').click(function()
{
  $('#promocode_status,#promocode_name').val('0');
  doctor_price = $('#book_status').attr('drprice');
  $('#show_offer_div').addClass('hidden');
  $('#show_total_div .ip_amount span').html(doctor_price);
  $('#promo_success_error').addClass('hidden');
   if ($('#confirm_book_form_promo').parsley().validate() ) 
    { 
       var result = post_ajax(base_url+'Searchdoctor/promocode_validate',$('#confirm_book_form_promo').serializeArray());
       var items = JSON.parse(result);
       if(items.status=="success")
       {
        $('#promo_success_error').addClass('alert-success').removeClass('hidden').removeClass('alert-danger').html(items.msg);
        $('#promocode_status').val('1');
        $('#promocode_name').val(items.code);
        total_sum = doctor_price - items.offeramount;
        //console.log(doctor_price,items.offeramount,total_sum);
        $('#show_offer_div').removeClass('hidden');
        $('#show_offer_div .ip_amount span').html(items.offeramount);
        $('#show_total_div .ip_amount span').html(total_sum);

       }
       else
       {
        $('#promo_success_error').addClass('alert-danger').removeClass('hidden').removeClass('alert-success').html(items.msg);
       }
    }
})

$('#promocode_cancel_btn').click(function()
{
  $('#promocode_inp').val('');
  $('#promocode_status,#promocode_name').val('0');
  doctor_price = $('#book_status').attr('drprice');
  $('#show_offer_div').addClass('hidden');
  $('#show_total_div .ip_amount span').html(doctor_price);
  $('#promo_success_error').addClass('hidden');
})

$('#book_payment_btn').click(function(){
  $('#payment-error-div').addClass('hidden');
  if($('#booking-payment-form').parsley().validate())
  {
      var booking_id = $('#book_status').attr('book-id'); //make payment with this id
      //console.log("book",booking_id)
      var result = post_ajax(base_url+'Searchdoctor/booking_payment',{'booking_id':booking_id,'UTCoffset':offset,'data':$('#booking-payment-form').serialize()});
      var items = JSON.parse(result);
      if(items.status=="success"&&items.payment_status=="1")
      {
        //console.log(items);
        $('#book-date-show').html('On '+items.booking_date+' ');
        $('#book-time-show').html(' at '+items.booking_slot);
        $('.confirm-tab-3').removeClass('active');
        $('#btnTrigger-confirmation').click();
        $('.confirm-tab-4').addClass('active');
      }
      else if(items.status=="fail")
      {
        $('#payment-error-div').removeClass('hidden').html(items.message);
        $('#booking-payment-form').trigger("reset");
        //alert('payment error');
      }
  }
  
  
});


/*----------------------------------*/


/*DOCTOR SEARCH STARTS*/
/*----------------------------------*/

  $('.ip_search_home_search_btn').click(function()
  {
    var searchForm = document.getElementById('doctor-search-form');
console.log(searchForm);
    if(document.getElementById('doctor_search_location').value!="")
    {
      $('#locationLattitude').val(search_place.geometry.location.lat());
      $('#locationLongitude').val(search_place.geometry.location.lng());
      searchForm.submit();   
    }
    else
    {
      if (navigator.geolocation) 
      {
        navigator.geolocation.getCurrentPosition(showPosition_home,errorCallbackLocation,{timeout:20000});
      }
      function showPosition_home(position) 
      {
        //console.log(position.coords.latitude,position.coords.longitude)
        $('#locationLattitude').val(position.coords.latitude);  
        $('#locationLongitude').val(position.coords.longitude);    
        searchForm.submit();
       
      }
      
    }
      
  })

  /*DOCTOR SEARCH RESULT-PAGE STARTS*/
/*----------------------------------*/

 

$('.filter-change').on('change',function()
{

/*$('#search_filter_loader').removeClass('hidden');*/
  setTimeout(function(){

 if($('#filter_dr_srch_loc').val()=="" || $('#filter_dr_srch_loc').val()==undefined|| $('#filter_dr_srch_loc').val()==null)
    {
      
      if (navigator.geolocation) 
      {
        navigator.geolocation.getCurrentPosition(showPosition,errorCallbackLocation,{timeout:20000});
      }
      else
      {
        alert("Cant Find Location.Try Again");
      }
      function showPosition(position) 
      {
        
        $('#filter_dr_srch_lat').val(position.coords.latitude);  
        $('#filter_dr_srch_lng').val(position.coords.longitude);  
        // console.log($('#filter_dr_srch_lat').val(),$('#filter_dr_srch_lng').val())
        load_filterchange();
      }
    }
    else
    {
      load_filterchange();
    }
  
 
    
  },1500);
})

$('#load-more').click(function(){

/*  var page = Number($('#pageno').val());
  next = page+1;
  $('#pageno').val(next).trigger('change');*/

});


    

/*----------------------------------*/

/*LOGIN-WIZARD STARTS*/
/*----------------------------------*/
$('.open-loginmodel').click(function(){
  $('.clear-login-data').val("");
  //$('input[name=login_type]').prop('checked', false);
  $("#login_patient").modal("show");
  $('#err-login').addClass('hidden'); 
})

$('#home_registernowbtn a').click(function()
{
  $("#login").modal("hide");
 // $("#choose").modal("show");
  $('#regpaitent').modal("show");
})

$("#login_submit_patient").click(function()
{
  $("#loading").show();
  $('#err-login').addClass('hidden'); 
  if ($('#login-form-patient').parsley().validate() ) 
    { 

      getLocation = function() 
      {
        if (navigator.geolocation) 
        {
         var item =  navigator.geolocation.getCurrentPosition(showPosition,errorCallbackLocation,{timeout:20000});
        } 
        
      }
      
      showPosition = function(position) {
        /*code for reverse geo location*/
          var geocoder = new google.maps.Geocoder;
          var latlng = {lat:position.coords.latitude, lng: position.coords.longitude};
          geocoder.geocode({'location': latlng}, function(results, status) 
          {
            if(status === 'OK')
            {
              if (results[1] && results[3]) 
              {
                var marker = new google.maps.Marker({position: latlng});
                //console.log("position : ",position.coords.latitude,position.coords.longitude,results[3].formatted_address);
                var location_finder = {'latitude' : position.coords.latitude,
                                'longitude' : position.coords.longitude,
                                'address' : results[3].formatted_address};
                do_login(location_finder);
              } 
              else
              {
                alert('Cant Find Your Location!Please Enable');
              }
            } 
            else 
            {
              alert('Cant Find Your Location!');
            }
          });

      }
      getLocation();
      function do_login(location)
      {
       // var LoginData = new FormData(); // Currently empty
       // LoginData.append('LoginData',$('#login-form').serialize()+'&'+'latitude='+location.latitude+'&'+'longitude='+location.longitude+'&'+'address='+location.address);
        /* for (var key of LoginData.entries()) {
            console.log(key[0] + ', ' + key[1]);
          }*/
             var LoginData = $('#login-form-patient').serialize()+'&'+'latitude='+location.latitude+'&'+'longitude='+location.longitude+'&'+'address='+location.address;

       
        var result = post_ajax(base_url+'Home/login',LoginData);
        var items = JSON.parse(result);
        //console.log(items);
        if(items.status=="success" || items.status=="error"){
          $("#loading2").show();
          if(items.status=="success"&&items.data.type=="PATIENT")
          {
            $("#login").modal("hide");
            $("#loading2").show();
            window.location.reload();
            
          }

          if(items.status=="error"&&items.error=="Login Failed")
          {
             $("#loading").hide();
            $("#err-login").html(items.message);
            $('#err-login').removeClass('hidden'); 
          }
          else if(items.status=="error"&&items.error=="Location Update Failed")
          {
             $("#loading").hide();
            $("#err-login").html(items.message);
            $('#err-login').removeClass('hidden'); 
          }
        }
      }

    }
    
    $("#loading").hide();
});

$("#login_submit_doctor").click(function()
{
  $("#loading3").show();
  $('#err-login').addClass('hidden'); 
  if ($('#login-form-doctor').parsley().validate() ) 
    { 

      getLocation = function() 
      {
        if (navigator.geolocation) 
        {
         var item =  navigator.geolocation.getCurrentPosition(showPosition,errorCallbackLocation,{timeout:20000});
        } 
        
      }
      
      showPosition = function(position) {
        /*code for reverse geo location*/
          var geocoder = new google.maps.Geocoder;
          var latlng = {lat:position.coords.latitude, lng: position.coords.longitude};
          geocoder.geocode({'location': latlng}, function(results, status) 
          {
            if(status === 'OK')
            {
              if (results[1] && results[3]) 
              {
                var marker = new google.maps.Marker({position: latlng});
                //console.log("position : ",position.coords.latitude,position.coords.longitude,results[3].formatted_address);
                var location_finder = {'latitude' : position.coords.latitude,
                                'longitude' : position.coords.longitude,
                                'address' : results[3].formatted_address};
                do_login(location_finder);
              } 
              else
              {
                alert('Cant Find Your Location!Please Enable');
              }
            } 
            else 
            {
              alert('Cant Find Your Location!');
            }
          });

      }
      getLocation();
      function do_login(location)
      {
       // var LoginData = new FormData(); // Currently empty
       // LoginData.append('LoginData',$('#login-form').serialize()+'&'+'latitude='+location.latitude+'&'+'longitude='+location.longitude+'&'+'address='+location.address);
        /* for (var key of LoginData.entries()) {
            console.log(key[0] + ', ' + key[1]);
          }*/
             var LoginData = $('#login-form-doctor').serialize()+'&'+'latitude='+location.latitude+'&'+'longitude='+location.longitude+'&'+'address='+location.address;

       
        var result = post_ajax(base_url+'Home/login',LoginData);
        var items = JSON.parse(result);
        //console.log(items);
        if(items.status=="success" || items.status=="error"){
          $("#loading").hide();
          $("#loading2").show();
          if(items.status=="success"&&items.data.type=="DOCTOR")
          {

            $("#login_doctor").modal("hide");
            $("#loading2").show();
            window.location.href= base_url+'Doctor';
            
          }
          else if(items.status=="success"&&items.data.type=="COLLABORATOR")
          {

            $("#login_doctor").modal("hide");
            $("#loading2").show();
            window.location.href= base_url+'Doctor/collaborator';
          }
          if(items.status=="error"&&items.error=="Login Failed")
          {
            $("#loading3").hide();
            $("#err-login").html(items.message);
            $('#err-login').removeClass('hidden'); 
          }
          else if(items.status=="error"&&items.error=="Location Update Failed")
          {
            $("#loading3").hide();
            $("#err-login").html(items.message);
            $('#err-login').removeClass('hidden'); 
          }
        }
      }
      



    }
     $("#loading3").hide();
    
});

/*****ACCESS AS A DOCTOR******/
$('#home_registernowbtn_from_patient').click(function(){
   $('.clear-login-data').val("");
  //$('input[name=login_type]').prop('checked', false);
  $("#login_patient").modal("hide");
  $("#login_doctor").modal("show");
  $('#err-login').addClass('hidden'); 
})
/*----------------------------------*/

/*FORGOT PASSWORD STARTS*/
/*----------------------------------*/

$('#forgot_password_btn_patient').click(function(){
  $('#forgot-pass-error').addClass('hidden');
  $('#login_patient').modal('hide');
  $('#forgot_patient').modal('show');
})

$('#forgot_password_btn_doctor').click(function(){
  $('#forgot-pass-error-doctor').addClass('hidden');
  $('#login_doctor').modal('hide');
  $('#forgot_doctor').modal('show');
})

$('#forgot_password_sent_btn_patient').click(function()
{
  $('#loading4').show();
  $('#forgot-pass-error').addClass('hidden');
  if($('#forgot-pass-form-patient').parsley().validate())
  {
    var result = post_ajax(base_url+'Home/forgotpassword',$('#forgot-pass-form-patient').serialize());
    var items = JSON.parse(result);
    if(items.status=='success')
    {
      $('#forgot_patient').modal('hide');
      $('#loading4').hide();
      $('#verify_patient').modal('show');
    }
    else
    {
      $('#loading4').hide();
      $('#forgot-pass-error').html(items.msg).removeClass('hidden');
    }
    
  }
  
})

$('#forgot_password_sent_btn_doctor').click(function()
{
  $('#loading5').show();
  $('#forgot-pass-error-doctor').addClass('hidden');
  if($('#forgot-pass-form-doctor').parsley().validate())
  {
    var result = post_ajax(base_url+'Home/forgotpassword',$('#forgot-pass-form-doctor').serialize());
    var items = JSON.parse(result);
    if(items.status=='success')
    {
      $('#forgot_doctor').modal('hide');
      $('#loading5').hide();
      $('#verify_doctor').modal('show');
    }
    else
    {
      $('#loading5').hide();
      $('#forgot-pass-error-doctor').html(items.msg).removeClass('hidden');
    }
    
  }
  
})

/*----------------------------------*/

/*REGISTRATION-CHOOSE-WIZARD STARTS*/
/*----------------------------------*/
$('#reg_choose_dct').click(function(){
  // $('#choose').hide();
  $("#choose").modal("hide");
  //$('#reg').modal("show");
})

$('#reg_choose_pat').click(function(){
  $("#choose").modal("hide");
  $('#regpaitent').modal("show");
})

/*----------------------------------*/


/*PATIENT REGISTRATION-WIZARD STARTS*/
/*----------------------------------*/
/*  $( "#reg_datepicker" ).datepicker({
    format: 'mm/dd/yyyy',
    startDate: '-3d'
});
*/
    var navListItems = $('div.setup-panel div a'),
        allWells = $('.setup-content'),
        allNextBtn = $('.nextBtn');

    allWells.hide();

    navListItems.click(function (e) {
        e.preventDefault();
        var $target = $($(this).attr('href')),
            $item = $(this);

        if (!$item.hasClass('disabled')) {
            navListItems.removeClass('btn-success').addClass('btn-default');
            $item.addClass('btn-success');
            allWells.hide();
            $target.show();
            $target.find('input:eq(0)').focus();
        }
    });

    function nextStep(elem) 
    {
      var curStep = $(elem).closest(".setup-content"),
      curStepBtn = curStep.attr("id"),
      nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
      curInputs = curStep.find("input[type='text'],input[type='url']"),
      isValid = true;
      nextStepWizard.removeAttr('disabled').trigger('click');
    };

    function prevStep(elem) 
    {
      var step = elem;
      prevStepWizard = $('div.setup-panel div a[href="#' + step + '"]').parent().prev().children("a"),
      prevStepWizard.removeAttr('disabled').trigger('click');
    };

    $('div.setup-panel div a.btn-success').trigger('click');

    window.Parsley.addValidator('email', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'email':value }
        var status;
        var result = post_ajax(base_url+'Home/check_email',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'This email address already exists!'  }
    });

    window.Parsley.addValidator('bloodgroup', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
       var group = value.toUpperCase();
       var pattern = new RegExp(/(A|B|AB|O)[+-]/);
       var res = pattern.test(group);
       return res;  
      },
      messages: {en:'Enter valid Bloodgroup!'}
    });


    window.Parsley.addValidator('username', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'username':value }
        var status;
        var result = post_ajax(base_url+'Home/check_username',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Username not Available!'  }
    });  

    window.Parsley.addValidator('cpf', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        //console.log(value);
        var cpf = value;
        if (cpf.length != 11) { return false; }

        var regex = /(\d{3})\.?(\d{3})\.?(\d{3})-?(\d{2})/;
        var numeros = cpf.replace(regex, "$1$2$3");
        var digits = cpf.replace(regex, "$4");

        var sum = 0;
        for (var i = 10; i > 1; i--) 
        {
          sum += numeros.charAt(10 - i) * i;
        }
        var result = sum % 11 < 2 ? 0 : 11 - sum % 11;
        if (result != digits.charAt(0)) { return false; }
        numeros = numeros+result;
        sum = 0;
        //alert(numeros);
        for (var i = 11; i > 1; i--) 
        {
          //alert(i+'*'+numeros.charAt(11 - i))
          sum += numeros.charAt(11 - i) * i;
        }

        result = sum % 11 < 2 ? 0 : 11 - sum % 11;
        if (result != digits.charAt(1)) 
        {
          //alert(result+'-'+digits.charAt(1));
          return false;
        }
        else
        { 
          return true;
        }

      },
      messages: { en: 'CPF Invalid'  }
    }); 

    window.Parsley.addValidator('cpfunique', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'cpf':value};
        var status;
        var result = post_ajax(base_url+'Home/check_cpfunique',obj);
        //console.log(result);
        var items = JSON.parse(result);
        if(items.status=='success')
        {
          status = true;
        }
        else
        {
          status = false;
        }
        return status;  
      },
      messages: { en: 'CPF not unique'  }
    });

    window.Parsley.addValidator('cep', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        
        var obj = {'cep':value};
        var status;
        var result = post_ajax(base_url+'Home/check_cep',obj);
        //console.log(result);
        var items = JSON.parse(result);
        if(items.erro!==true)
        {
          status = true;
          if(requirement=="doctor")
          {
            $('#doc-reg-rua').val(items.logradouro);
            $('#doc-reg-locality').val(items.localidade);
            $('#doc-reg-number').val(items.ibge);
            $('#doc-reg-complement').val(items.complemento);
          }
          if(requirement=="patient")
          {
            $('#pat-reg-rua').val(items.logradouro);
            $('#pat-reg-locality').val(items.localidade);
            $('#pat-reg-number').val(items.ibge);
            $('#pat-reg-complement').val(items.complemento);
          }
        }
        else
        {
          status = false;
        }
        return status;  
      },
      messages: { en: 'Invalid CEP'  }
    });  

    $(".nextBtn-1").click(function()
    {
      if ($('#reg-form-patient-1').parsley().validate() ) 
        { 
          
         nextStep(this);/* */
        }
        
    });

    
    $(".nextBtn-2").click(function()
    {
    if ($('#reg-form-patient-2').parsley().validate() ) 
      { 
        nextStep(this);
      }

    }) 

     $(".prevBtn-2").click(function()
    {
      prevStep("step-2");
    })

    $(".nextBtn-3").click(function()
    {
    if ($('#reg-form-patient-3').parsley().validate() ) 
      { 
        nextStep(this);
      }
    })

      $(".prevBtn-3").click(function()
    {
       prevStep("step-3");
    })

    $(".nextBtn-4").click(function()
    {      
      
    if ($('#reg-form-patient-4').parsley().validate() ) 
      { 
        
        var formData = new FormData(); // Currently empty
        formData.append('data',$('#reg-form-patient-1').serialize()+'&'+$('#reg-form-patient-2').serialize()+'&'+$('#reg-form-patient-3').serialize()+'&'+$('#reg-form-patient-4').serialize());
       if(!$('#reg_pat_pic').hasClass('from-facebook'))
       {
         formData.append('pic', $('#reg_pat_pic')[0].files[0]);      // Attach file
       }
       /* for (var key of formData.entries()) {
          console.log(key[0] + ', ' + key[1]);
        }*/

        $.ajax({
                  type: 'POST',
                  url : base_url+'Home/reg_patient',
                  data : formData,
                  async : false,
                  contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
                  processData: false,
                  success: function (result) 
                   {
                     //console.log(result)
                        var items = JSON.parse(result);
                        //console.log(items)
                        if(items.status=="success")
                        {
                          $('.reset-form-custom').val("");
                          $('input[name=reg_pat_gender]').prop('checked', false);
                          $('#regpaitent').modal("hide");
                          prevStep("step-2");
                          setTimeout(function(){
                            $('#login').modal("show");
                            $('#pat-reg-success').removeClass('hidden');
                            setTimeout(function(){$('#pat-reg-success').addClass('hidden');},10000);
                          },500);
                          
                        }
                        else if(items.status=="failure")
                        {
                          //console.log(items.error,items.message)
                          $('.reset-form-custom').val("");
                          $('input[name=reg_pat_gender]').prop('checked', false);
                          $('#regpaitent').modal("hide");
                          prevStep("step-2");
                          $('#pat-reg-error').removeClass('hidden');
                          $('#pat-reg-error p').html(items.message);
                          setTimeout(function(){$('#pat-reg-error').addClass('hidden');},10000);
                        }
                        
                    }                            
        });
       
      }

    })
	
    $(".prevBtn-4").click(function()
    {
       prevStep("step-4");
    })
/*REGISTRATION-WIZARD ENDS*/

/*DOCTOR REGISTRATION-WIZARD STARTS*/
/*----------------------------------*/
 window.Parsley.addValidator('usernamedoc', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        var obj = {'username':value }
        var status;
        var result = post_ajax(base_url+'Home/check_username_doc',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Username not Available!'  }
    });

 window.Parsley.addValidator('emaildoc', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
     // console.log(value);
        var obj = {'email':value }
        var status;
        var result = post_ajax(base_url+'Home/check_email_doc',obj);
        var items = JSON.parse(result);
        if(items.message!="success")
        {
          status = false;
        }
        else
        {                                             
          status = true;
        }
        return status;  
      },
      messages: { en: 'Email not Available!'  }
    });


 
/*DOCTOR REGISTRATION-WIZARD ENDS*/

/* REGISTRATION DATEPICKER JS */
/*----------------------------*/
/*var date = (new Date()).getFullYear();
var cur_date = date - 18;
var max_date = cur_date - 120;*/
$('#registration-container input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    /*endDate:"0d",
    startDate:"-120y"*/
     /*minDate: '-120Y',
     maxDate: '-18Y',*/
     endDate:"-18y",
    startDate:"-120y"
})

$('#doc-registration-container input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    /*endDate:"0d",
    startDate:"-120y"*/
     /*minDate: '-120Y',
     maxDate: '-18Y',*/
     endDate:"-18y",
    startDate:"-120y"
})
/* PATIENT EDIT DATEPICKER JS */
/*----------------------------*/
$('#edit-patient input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
   /* endDate:"0d",
    startDate:"-120y"*/
    endDate:"-18y",
    startDate:"-120y"
})
/*----------------------------*/
/* PATIENT EDIT DEPENDENT DATEPICKER JS */
/*----------------------------*/
$('#edit-patient-dependent input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    endDate:"-18y",
    startDate:"-120y"
})
/*----------------------------*/

/* DOCTOR EDIT DATEPICKER JS */
/*----------------------------*/
$('#edit-doctor input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    endDate:"-18y",
    startDate:"-120y"
})
/*----------------------------*/
/* BOOKING DATEPICKER JS */
/*----------------------------*/
  

$('#booking-container input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    format: "dd-mm-yyyy",
    endDate:"+2m",
    startDate:"0d"
})

/*$('#thedate').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    format: "dd-mm-yyyy",
    endDate:"+2m",
    startDate:"0d"
})*/
/*----------------------------*/
/* SEARCH RESULT DATEPICKER JS */
/*----------------------------*/
$('#ip_datepicker_srch').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    endDate:"+1m",
    startDate:"0d",
    format: "dd-mm-yyyy"
})
/*----------------------------*/
/* DOCTOR LEAVE DATEPICKER JS */
/*----------------------------*/
$('#doc-leave-container input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    },
    startDate:"0d"
})
/*----------------------------*/
/*DATEPICKER JS*/
$('#sandbox-container input').datepicker({
    autoclose: true,
    onSelect: function(dateText) {
      //console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
})/*.on('changeDate', function(ev) {
  console.log($('#confirm_book_date').val());
});*/

$('#sandbox-container input').on('show', function(e){
    console.debug('show', e.date, $(this).data('stickyDate'));
    
    if ( e.date ) {
         $(this).data('stickyDate', e.date);
    }
    else {
         $(this).data('stickyDate', null);
    }
});

$('#sandbox-container input').on('hide', function(e){
    console.debug('hide', e.date, $(this).data('stickyDate'));
    var stickyDate = $(this).data('stickyDate');
    
    if ( !e.date && stickyDate ) {
        console.debug('restore stickyDate', stickyDate);
        $(this).datepicker('setDate', stickyDate);
        $(this).data('stickyDate', null);
    }
});


/*----------------------------------*/


/*APPOINTMENT-CALENDER-TABS*/

	    $(".ip_custom_tabs_menu a").click(function(event) {
	        event.preventDefault();
	        $(this).parent().addClass("current");
	        $(this).parent().siblings().removeClass("current");
	        var tab = $(this).attr("href");
	        $(".ip_custom_tab_content").not(tab).css("display", "none");
	        $(tab).fadeIn();
	    });

/*----------------------------------*/

/*COUNTER*/

	$('.ip_counter').each(function() {
	  var $this = $(this),
	      countTo = $this.attr('data-count');

	  $({ countNum: $this.text()}).animate({
	    countNum: countTo
	  },

	  {

	    duration: 1000,
	    easing:'linear',
	    step: function() {
	      $this.text(Math.floor(this.countNum));
	    },
	    complete: function() {
	      $this.text(this.countNum);
	      //alert('finished');
	    }

	  });
	});

/*----------------------------------*/

/*USER-RATTING*/

	$('#ip_user_rating_form').on('change','[name="rating"]',function(){
	$('#ip_selected_rating').text($('[name="rating"]:checked').val());
});

/*----------------------------------*/

/*HEADER-SHRIKER*/

	$(window).scroll(function() {
  if ($(document).scrollTop() > 52) {
    $('.ip_header_secondary').addClass('ip_shrink');
  } else{
    $('.ip_header_secondary').removeClass('ip_shrink');
  }
});

	$(window).scroll(function() {
  if ($(document).scrollTop() > 52) {
    $('.ip_main_wrapper').addClass('ip_body_scroll');
  } else{
    $('.ip_main_wrapper').removeClass('ip_body_scroll');
  }
});


/*----------------------------------*/

/*DISTANCE-RANGE-SLIDER*/

/*$( "#ip_filter_distance_start" ).val("0 km" );
$( "#ip_filter_distance_end" ).val("10 km" );*/
$( "#ip_filter_distance_range" ).slider({
    range: true,
    min: 0,
    max: 99,
    values: [ 0,10 ],
    slide: function( event, ui ) {
      console.log(event, ui )
      $( "#ip_filter_distance_start" ).val(ui.values[ 0 ] + " km" );
	    $( "#ip_filter_distance_end" ).val(ui.values[ 1 ] + " km" ).trigger('change');
     
    }
  });

/*----------------------------------*/

/*PRICE-RANGE-SLIDER*/
  /*$( "#ip_filter_price_low" ).val("R$ 100");
  $( "#ip_filter_price_high" ).val("R$ 500");*/
  $( "#ip_price_slider" ).slider({
      range: true,
      min: 0,
      max: 5000,
      values: [ 100, 500 ],
      slide: function( event, ui ) {
        console.log(event, ui )
      $( "#ip_filter_price_low" ).val( "R$ " + ui.values[ 0 ]);
		  $( "#ip_filter_price_high" ).val( "R$ " + ui.values[ 1 ]).trigger('change');
      }
    });


/*----------------------------------*/

/*APPOINTMENT-CALENDER*/

 $( "#ip_appointment_calender_div" ).datepicker({
  todayHighlight: true,
  endDate:"+2y",
  startDate:"0d"
 });

/*----------------------------------*/

/*SEARCH-RESULT-TIMEPICKER*/

$('#ip_timepicker').timepicker();


/*----------------------------------*/

/*DOCTOR DASHBOARD*/
var days = ['mon','tue','wed','thu','fri','sat','sun'];

$('.dctr_dsh_timepicker').timepicker();

// $( document ).ready(function() {
//   var clinic = $('#doc_sel_clinic').val();
//   var obj = {"clinic_id": $('#doc_sel_clinic').val()};
//   var result = post_ajax(base_url+'Doctor/getScheduleforClinic',obj);
//   if(result.trim() !== ''){
//     var items = JSON.parse(result);
//     if(clinic == '0'){
//       $('.ip_schedule_week input').prop('checked', false);
        

//         for(i = 0 ; i < days.length ; i++)
//         {
//           //RESETTING PRIMARY SCHEDULE
//           $('#sch_'+days[i]+'_start,#sch_'+days[i]+'_end,#intr_'+days[i]+'_start,#intr_'+days[i]+'_end').val('');
//           $('#intr_chkbx_'+days[i]).prop('checked', false);
//           $('#clinic_day_'+days[i]+'_div').addClass('inp-dis'); 
//           $('#clinic_day_'+days[i]+'_div input').attr('disabled','disabled');
//           $('#clinic_day_'+days[i]+'_div input').removeAttr('data-parsley-required');

//           //RESETTING SECONDARY SCHEDULE
//           $('#sec_sch_'+days[i]+'_start,#sec_sch_'+days[i]+'_end,#sec_intr_'+days[i]+'_start,#sec_intr_'+days[i]+'_end').val('');
//           $('#sec_intr_chkbx_'+days[i]).prop('checked', false);
//           $('#sec_clinic_day_'+days[i]+'_div').addClass('inp-dis'); 
//           $('#sec_clinic_day_'+days[i]+'_div input').attr('disabled','disabled');
//           $('#sec_clinic_day_'+days[i]+'_div input').removeAttr('data-parsley-required');
//         }
//      if(items.status=="fail")
//       {
//         console.log('true');
//         $('.ip_schedule_week input').removeAttr('disabled');
//       }else {
//         console.log('false');
//         var ActiveSchedule = JSON.parse(items.active_schedule);
//         if(ActiveSchedule=="0")
//         {$('#choose-schedule-primary').prop('checked', true);}
//         else if(ActiveSchedule=="1")
//         {$('#choose-schedule-secondary').prop('checked', true);}
        
//         //SETTING PRIMARY SCHDULE
//         var PrimarySchedule = JSON.parse(items.pri_schedule);
//         Object.keys(PrimarySchedule).forEach(function(key,index) 
//         {
//           // key: the name of the object key
//           // index: the ordinal position of the key within the object 
//           var elem  = PrimarySchedule[index];
//           if(elem.day=="mon"||elem.day=="tue"||elem.day=="wed"||elem.day=="thu"||elem.day=="fri"||elem.day=="sat"||elem.day=="sun")
//           {
//             $('#clinic_day_'+elem.day).prop('checked', true);
//             $('#clinic_day_'+elem.day+'_div').removeClass('inp-dis');
//             $('#clinic_day_'+elem.day+'_div input').removeAttr('disabled');

//             //setting schedule time
//             var start_timestamp = new Date('01/01/2017 '+elem.time.start).getTime();
//             var end_timestamp = new Date('01/01/2017 '+elem.time.end).getTime(); 
//             $('#sch_'+elem.day+'_start').timepicker('setTime', new Date(start_timestamp));
//             $('#sch_'+elem.day+'_end').timepicker('setTime', new Date(end_timestamp));
//             $('#sch_'+elem.day+'_start,#sch_'+elem.day+'_end').attr('data-parsley-required','true');

//             //setting interval time
//             if((elem.time.break_from!='null') && (elem.time.break_to!='null'))
//             {
//               $('#intr_chkbx_'+elem.day).prop('checked', true);
//               var start_intr_timestamp = new Date('01/01/2017 '+elem.time.break_from).getTime();
//               var end_intr_timestamp = new Date('01/01/2017 '+elem.time.break_to).getTime();
//               $('#intr_'+elem.day+'_start').timepicker('setTime', new Date(start_intr_timestamp));
//               $('#intr_'+elem.day+'_end').timepicker('setTime', new Date(end_intr_timestamp));
//               $('#intr_'+elem.day+'_start,#intr_'+elem.day+'_end').attr('data-parsley-required','true');
//             }
//             else
//             {
//               $('#intr_'+elem.day+'_start,#intr_'+elem.day+'_end').attr('disabled','disabled');
//             }
//           }
//         });

//          //SETTING SECONDARY SCHDULE
//         var SecondarySchedule = JSON.parse(items.sec_schedule);
//         Object.keys(SecondarySchedule).forEach(function(key,index) 
//         {
//           // key: the name of the object key
//           // index: the ordinal position of the key within the object 
//           var elem  = SecondarySchedule[index];
//           if(elem.day=="mon"||elem.day=="tue"||elem.day=="wed"||elem.day=="thu"||elem.day=="fri"||elem.day=="sat"||elem.day=="sun")
//           {
//             $('#sec_clinic_day_'+elem.day).prop('checked', true);
//             $('#sec_clinic_day_'+elem.day+'_div').removeClass('inp-dis');
//             $('#sec_clinic_day_'+elem.day+'_div input').removeAttr('disabled');

//             //setting schedule time
//             var start_timestamp = new Date('01/01/2017 '+elem.time.start).getTime();
//             var end_timestamp = new Date('01/01/2017 '+elem.time.end).getTime(); 
//             $('#sec_sch_'+elem.day+'_start').timepicker('setTime', new Date(start_timestamp));
//             $('#sec_sch_'+elem.day+'_end').timepicker('setTime', new Date(end_timestamp));
//             $('#sec_sch_'+elem.day+'_start,#sec_sch_'+elem.day+'_end').attr('data-parsley-required','true');

//             //setting interval time
//             if((elem.time.break_from!='null') && (elem.time.break_to!='null'))
//             {
//               $('#sec_intr_chkbx_'+elem.day).prop('checked', true);
//               var start_intr_timestamp = new Date('01/01/2017 '+elem.time.break_from).getTime();
//               var end_intr_timestamp = new Date('01/01/2017 '+elem.time.break_to).getTime();
//               $('#sec_intr_'+elem.day+'_start').timepicker('setTime', new Date(start_intr_timestamp));
//               $('#sec_intr_'+elem.day+'_end').timepicker('setTime', new Date(end_intr_timestamp));
//               $('#sec_intr_'+elem.day+'_start,#sec_intr_'+elem.day+'_end').attr('data-parsley-required','true');
//             }
//             else
//             {
//               $('#sec_intr_'+elem.day+'_start,#sec_intr_'+elem.day+'_end').attr('disabled','disabled');
//             }
//           }
//         });
//       }
//       // $('#choose-schedule-primary').prop('checked', true);
//       // $('#choose-schedule-secondary').prop('checked', true);
//     }
//   }
// });

$('#doc_sel_clinic').change(function(){
    var obj = {"clinic_id": $('#doc_sel_clinic').val()};

      $('.ip_schedule_week input').prop('checked', false);
      

      for(i = 0 ; i < days.length ; i++)
      {
        //RESETTING PRIMARY SCHEDULE
        $('#sch_'+days[i]+'_start,#sch_'+days[i]+'_end,#intr_'+days[i]+'_start,#intr_'+days[i]+'_end').val('');
        $('#intr_chkbx_'+days[i]).prop('checked', false);
        $('#clinic_day_'+days[i]+'_div').addClass('inp-dis'); 
        $('#clinic_day_'+days[i]+'_div input').attr('disabled','disabled');
        $('#clinic_day_'+days[i]+'_div input').removeAttr('data-parsley-required');

        //RESETTING SECONDARY SCHEDULE
        $('#sec_sch_'+days[i]+'_start,#sec_sch_'+days[i]+'_end,#sec_intr_'+days[i]+'_start,#sec_intr_'+days[i]+'_end').val('');
        $('#sec_intr_chkbx_'+days[i]).prop('checked', false);
        $('#sec_clinic_day_'+days[i]+'_div').addClass('inp-dis'); 
        $('#sec_clinic_day_'+days[i]+'_div input').attr('disabled','disabled');
        $('#sec_clinic_day_'+days[i]+'_div input').removeAttr('data-parsley-required');
      }
    var result = post_ajax(base_url+'Doctor/getScheduleforClinic',obj);
    var items = JSON.parse(result);
    //console.log(items);
    $('.ip_schedule_week input').removeAttr('disabled'); //remove disabled

    if(items.status=="success"&&items.pri_schedule!=""&&items.sec_schedule!="")
    {
      // var ScheduleData = JSON.parse(items);

      //SETTING ACTIVE SCHEDULE TYPE
      var ActiveSchedule = JSON.parse(items.active_schedule);
      if(ActiveSchedule=="0")
      {$('#choose-schedule-primary').prop('checked', true);}
      else if(ActiveSchedule=="1")
      {$('#choose-schedule-secondary').prop('checked', true);}
      
      //SETTING PRIMARY SCHDULE
      var PrimarySchedule = JSON.parse(items.pri_schedule);
      Object.keys(PrimarySchedule).forEach(function(key,index) 
      {
        // key: the name of the object key
        // index: the ordinal position of the key within the object 
        var elem  = PrimarySchedule[index];
        if(elem.day=="mon"||elem.day=="tue"||elem.day=="wed"||elem.day=="thu"||elem.day=="fri"||elem.day=="sat"||elem.day=="sun")
        {
          $('#clinic_day_'+elem.day).prop('checked', true);
          $('#clinic_day_'+elem.day+'_div').removeClass('inp-dis');
          $('#clinic_day_'+elem.day+'_div input').removeAttr('disabled');

          //setting schedule time
          var start_timestamp = new Date('01/01/2017 '+elem.time.start).getTime();
          var end_timestamp = new Date('01/01/2017 '+elem.time.end).getTime(); 
          $('#sch_'+elem.day+'_start').timepicker('setTime', new Date(start_timestamp));
          $('#sch_'+elem.day+'_end').timepicker('setTime', new Date(end_timestamp));
          $('#sch_'+elem.day+'_start,#sch_'+elem.day+'_end').attr('data-parsley-required','true');

          //setting interval time
          if((elem.time.break_from!='null') && (elem.time.break_to!='null'))
          {
            $('#intr_chkbx_'+elem.day).prop('checked', true);
            var start_intr_timestamp = new Date('01/01/2017 '+elem.time.break_from).getTime();
            var end_intr_timestamp = new Date('01/01/2017 '+elem.time.break_to).getTime();
            $('#intr_'+elem.day+'_start').timepicker('setTime', new Date(start_intr_timestamp));
            $('#intr_'+elem.day+'_end').timepicker('setTime', new Date(end_intr_timestamp));
            $('#intr_'+elem.day+'_start,#intr_'+elem.day+'_end').attr('data-parsley-required','true');
          }
          else
          {
            $('#intr_'+elem.day+'_start,#intr_'+elem.day+'_end').attr('disabled','disabled');
          }
        }
      });

       //SETTING SECONDARY SCHDULE
      var SecondarySchedule = JSON.parse(items.sec_schedule);
      Object.keys(SecondarySchedule).forEach(function(key,index) 
      {
        // key: the name of the object key
        // index: the ordinal position of the key within the object 
        var elem  = SecondarySchedule[index];
        if(elem.day=="mon"||elem.day=="tue"||elem.day=="wed"||elem.day=="thu"||elem.day=="fri"||elem.day=="sat"||elem.day=="sun")
        {
          $('#sec_clinic_day_'+elem.day).prop('checked', true);
          $('#sec_clinic_day_'+elem.day+'_div').removeClass('inp-dis');
          $('#sec_clinic_day_'+elem.day+'_div input').removeAttr('disabled');

          //setting schedule time
          var start_timestamp = new Date('01/01/2017 '+elem.time.start).getTime();
          var end_timestamp = new Date('01/01/2017 '+elem.time.end).getTime(); 
          $('#sec_sch_'+elem.day+'_start').timepicker('setTime', new Date(start_timestamp));
          $('#sec_sch_'+elem.day+'_end').timepicker('setTime', new Date(end_timestamp));
          $('#sec_sch_'+elem.day+'_start,#sec_sch_'+elem.day+'_end').attr('data-parsley-required','true');

          //setting interval time
          if((elem.time.break_from!='null') && (elem.time.break_to!='null'))
          {
            $('#sec_intr_chkbx_'+elem.day).prop('checked', true);
            var start_intr_timestamp = new Date('01/01/2017 '+elem.time.break_from).getTime();
            var end_intr_timestamp = new Date('01/01/2017 '+elem.time.break_to).getTime();
            $('#sec_intr_'+elem.day+'_start').timepicker('setTime', new Date(start_intr_timestamp));
            $('#sec_intr_'+elem.day+'_end').timepicker('setTime', new Date(end_intr_timestamp));
            $('#sec_intr_'+elem.day+'_start,#sec_intr_'+elem.day+'_end').attr('data-parsley-required','true');
          }
          else
          {
            $('#sec_intr_'+elem.day+'_start,#sec_intr_'+elem.day+'_end').attr('disabled','disabled');
          }
        }
      });

    }

})

//SETTING CUSTOM VALIDATION - PRIMARY SCHEDULE
$('#intr_chkbx_mon').change(function()
{
  var $check = $(this);
  if($check.prop('checked')) 
  { 
    $('#intr_mon_start,#intr_mon_end').removeAttr('disabled');
    $('#intr_mon_start,#intr_mon_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_mon_start,#intr_mon_end').val('');
    $('#intr_mon_start,#intr_mon_end').attr('disabled','disabled');
    $('#intr_mon_start,#intr_mon_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_mon').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_mon_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_mon').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_mon_div input').removeAttr('disabled');
    $('#sch_mon_start,#sch_mon_end,#intr_mon_start,#intr_mon_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_mon_div input').attr('disabled','disabled');
    $('#sch_mon_start,#sch_mon_end,#intr_mon_start,#intr_mon_end').removeAttr('data-parsley-required');
  }
});


$('#intr_chkbx_tue').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_tue_start,#intr_tue_end').removeAttr('disabled');
    $('#intr_tue_start,#intr_tue_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_tue_start,#intr_tue_end').val('');
    $('#intr_tue_start,#intr_tue_end').attr('disabled','disabled');
    $('#intr_tue_start,#intr_tue_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_tue').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_tue_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_tue').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_tue_div input').removeAttr('disabled');
    $('#sch_tue_start,#sch_tue_end,#intr_tue_start,#intr_tue_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_tue_div input').attr('disabled','disabled');
    $('#sch_tue_start,#sch_tue_end,#intr_tue_start,#intr_tue_end').removeAttr('data-parsley-required');
  }
});

$('#intr_chkbx_wed').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_wed_start,#intr_wed_end').removeAttr('disabled');
    $('#intr_wed_start,#intr_wed_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_wed_start,#intr_wed_end').attr('disabled','disabled');
    $('#intr_wed_start,#intr_wed_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_wed').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_wed_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_wed').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_wed_div input').removeAttr('disabled');
    $('#sch_wed_start,#sch_wed_end,#intr_wed_start,#intr_wed_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_wed_div input').attr('disabled','disabled');
    $('#sch_wed_start,#sch_wed_end,#intr_wed_start,#intr_wed_end').removeAttr('data-parsley-required');
  }
});


$('#intr_chkbx_thu').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_thu_start,#intr_thu_end').removeAttr('disabled');
    $('#intr_thu_start,#intr_thu_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_thu_start,#intr_thu_end').attr('disabled','disabled');
    $('#intr_thu_start,#intr_thu_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_thu').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_thu_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_thu').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_thu_div input').removeAttr('disabled');
    $('#sch_thu_start,#sch_thu_end,#intr_thu_start,#intr_thu_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_thu_div input').attr('disabled','disabled');
    $('#sch_thu_start,#sch_thu_end,#intr_thu_start,#intr_thu_end').removeAttr('data-parsley-required');
  }
});

$('#intr_chkbx_fri').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_fri_start,#intr_fri_end').removeAttr('disabled');
    $('#intr_fri_start,#intr_fri_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_fri_start,#intr_fri_end').attr('disabled','disabled');
    $('#intr_fri_start,#intr_fri_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_fri').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_fri_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_fri').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_fri_div input').removeAttr('disabled');
    $('#sch_fri_start,#sch_fri_end,#intr_fri_start,#intr_fri_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_fri_div input').attr('disabled','disabled');
    $('#sch_fri_start,#sch_fri_end,#intr_fri_start,#intr_fri_end').removeAttr('data-parsley-required');
  }
});

$('#intr_chkbx_sat').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_sat_start,#intr_sat_end').removeAttr('disabled');
    $('#intr_sat_start,#intr_sat_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_sat_start,#intr_sat_end').attr('disabled','disabled');
    $('#intr_sat_start,#intr_sat_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_sat').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_sat_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_sat').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_sat_div input').removeAttr('disabled');
    $('#sch_sat_start,#sch_sat_end,#intr_sat_start,#intr_sat_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_sat_div input').attr('disabled','disabled');
    $('#sch_sat_start,#sch_sat_end,#intr_sat_start,#intr_sat_end').removeAttr('data-parsley-required');
  }
});

$('#intr_chkbx_sun').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#intr_sun_start,#intr_sun_end').removeAttr('disabled');
    $('#intr_sun_start,#intr_sun_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#intr_sun_start,#intr_sun_end').attr('disabled','disabled');
    $('#intr_sun_start,#intr_sun_end').removeAttr('data-parsley-required');
  }
});

$('#clinic_day_sun').change(function()
{
  var $check = $(this),
  $div = $('#clinic_day_sun_div');
  if ($check.prop('checked')) 
  { 
    $('#intr_chkbx_sun').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#clinic_day_sun_div input').removeAttr('disabled');
    $('#sch_sun_start,#sch_sun_end,#intr_sun_start,#intr_sun_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#clinic_day_sun_div input').attr('disabled','disabled');
    $('#sch_sun_start,#sch_sun_end,#intr_sun_start,#intr_sun_end').removeAttr('data-parsley-required');
  }
});

//SETTING CUSTOM VALIDATION - SECONDARY SCHEDULE
$('#sec_intr_chkbx_mon').change(function()
{
  var $check = $(this);
  if($check.prop('checked')) 
  { 
    $('#sec_intr_mon_start,#sec_intr_mon_end').removeAttr('disabled');
    $('#sec_intr_mon_start,#sec_intr_mon_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_mon_start,#sec_intr_mon_end').val('');
    $('#sec_intr_mon_start,#sec_intr_mon_end').attr('disabled','disabled');
    $('#sec_intr_mon_start,#sec_intr_mon_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_mon').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_mon_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_mon').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_mon_div input').removeAttr('disabled');
    $('#sec_sch_mon_start,#sec_sch_mon_end,#sec_intr_mon_start,#sec_intr_mon_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_mon_div input').attr('disabled','disabled');
    $('#sec_sch_mon_start,#sec_sch_mon_end,#sec_intr_mon_start,#sec_intr_mon_end').removeAttr('data-parsley-required');
  }
});


$('#sec_intr_chkbx_tue').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_tue_start,#sec_intr_tue_end').removeAttr('disabled');
    $('#sec_intr_tue_start,#sec_intr_tue_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_tue_start,#sec_intr_tue_end').val('');
    $('#sec_intr_tue_start,#sec_intr_tue_end').attr('disabled','disabled');
    $('#sec_intr_tue_start,#sec_intr_tue_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_tue').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_tue_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_tue').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_tue_div input').removeAttr('disabled');
    $('#sec_sch_tue_start,#sec_sch_tue_end,#sec_intr_tue_start,#sec_intr_tue_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_tue_div input').attr('disabled','disabled');
    $('#sec_sch_tue_start,#sec_sch_tue_end,#sec_intr_tue_start,#sec_intr_tue_end').removeAttr('data-parsley-required');
  }
});

$('#sec_intr_chkbx_wed').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_wed_start,#sec_intr_wed_end').removeAttr('disabled');
    $('#sec_intr_wed_start,#sec_intr_wed_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_wed_start,#sec_intr_wed_end').attr('disabled','disabled');
    $('#sec_intr_wed_start,#sec_intr_wed_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_wed').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_wed_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_wed').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_wed_div input').removeAttr('disabled');
    $('#sec_sch_wed_start,#sec_sch_wed_end,#sec_intr_wed_start,#sec_intr_wed_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_wed_div input').attr('disabled','disabled');
    $('#sec_sch_wed_start,#sec_sch_wed_end,#sec_intr_wed_start,#sec_intr_wed_end').removeAttr('data-parsley-required');
  }
});


$('#sec_intr_chkbx_thu').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_thu_start,#sec_intr_thu_end').removeAttr('disabled');
    $('#sec_intr_thu_start,#sec_intr_thu_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_thu_start,#sec_intr_thu_end').attr('disabled','disabled');
    $('#sec_intr_thu_start,#sec_intr_thu_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_thu').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_thu_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_thu').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_thu_div input').removeAttr('disabled');
    $('#sec_sch_thu_start,#sec_sch_thu_end,#sec_intr_thu_start,#sec_intr_thu_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_thu_div input').attr('disabled','disabled');
    $('#sec_sch_thu_start,#sec_sch_thu_end,#sec_intr_thu_start,#sec_intr_thu_end').removeAttr('data-parsley-required');
  }
});

$('#sec_intr_chkbx_fri').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_fri_start,#sec_intr_fri_end').removeAttr('disabled');
    $('#sec_intr_fri_start,#sec_intr_fri_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_fri_start,#sec_intr_fri_end').attr('disabled','disabled');
    $('#sec_intr_fri_start,#sec_intr_fri_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_fri').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_fri_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_fri').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_fri_div input').removeAttr('disabled');
    $('#sec_sch_fri_start,#sec_sch_fri_end,#sec_intr_fri_start,#sec_intr_fri_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_fri_div input').attr('disabled','disabled');
    $('#sec_sch_fri_start,#sec_sch_fri_end,#sec_intr_fri_start,#sec_intr_fri_end').removeAttr('data-parsley-required');
  }
});

$('#sec_intr_chkbx_sat').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_sat_start,#sec_intr_sat_end').removeAttr('disabled');
    $('#sec_intr_sat_start,#sec_intr_sat_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_sat_start,#sec_intr_sat_end').attr('disabled','disabled');
    $('#sec_intr_sat_start,#sec_intr_sat_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_sat').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_sat_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_sat').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_sat_div input').removeAttr('disabled');
    $('#sec_sch_sat_start,#sec_sch_sat_end,#sec_intr_sat_start,#sec_intr_sat_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_sat_div input').attr('disabled','disabled');
    $('#sec_sch_sat_start,#sec_sch_sat_end,#sec_intr_sat_start,#sec_intr_sat_end').removeAttr('data-parsley-required');
  }
});

$('#sec_intr_chkbx_sun').change(function()
{
  var $check = $(this);
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_sun_start,#sec_intr_sun_end').removeAttr('disabled');
    $('#sec_intr_sun_start,#sec_intr_sun_end').attr('data-parsley-required','true');
   }
  else 
  {  
    $('#sec_intr_sun_start,#sec_intr_sun_end').attr('disabled','disabled');
    $('#sec_intr_sun_start,#sec_intr_sun_end').removeAttr('data-parsley-required');
  }
});

$('#sec_clinic_day_sun').change(function()
{
  var $check = $(this),
  $div = $('#sec_clinic_day_sun_div');
  if ($check.prop('checked')) 
  { 
    $('#sec_intr_chkbx_sun').prop('checked','true');
    $div.removeClass('inp-dis');
    $('#sec_clinic_day_sun_div input').removeAttr('disabled');
    $('#sec_sch_sun_start,#sec_sch_sun_end,#sec_intr_sun_start,#sec_intr_sun_end').attr('data-parsley-required','true');
  }
  else 
  {  
    $div.addClass('inp-dis'); 
    $('#sec_clinic_day_sun_div input').attr('disabled','disabled');
    $('#sec_sch_sun_start,#sec_sch_sun_end,#sec_intr_sun_start,#sec_intr_sun_end').removeAttr('data-parsley-required');
  }
});


 window.Parsley.addValidator('consultduration', {
    requirementType: 'string',
    validateString: function(value, requirement) 
    {
        //var obj = {'username':value }
        var status;
        var result = post_ajax(base_url+'Doctor/check_consultduration');
        var items = JSON.parse(result);
        console.log(Number(items.data));
        if(Number(items.data)>0)
        {
          status = true;
        }
        else
        {                                             
          status = false;
        }
        return status;  
      },
      messages: { en: 'Add Consultation Duration First!'  }
    }); 


  window.Parsley
  .addValidator('mintime', {
  requirementType: 'string',
  validateString: function(value, requirement) 
  { defaultDate = "01/01/17";
    //console.log($(requirement).val())
    var time1 = defaultDate+' '+value;
    var time2 = defaultDate+' '+$(requirement).val();
    var date1 = Date.parse(time1);
    var date2 = Date.parse(time2);
   // console.log(time1);
  //console.log("end",date1);
  //console.log("start",date2);
    if(date1 > date2){
    return true;
    }
    else{ return false;  }
  },
  messages: {
  en: 'Time should be greater than Start Time'

  }
  }); 

   window.Parsley
  .addValidator('maxtime', {
  requirementType: 'string',
  validateString: function(value, requirement) 
  { defaultDate = "01/01/17";
    //console.log($(requirement).val())
    var time1 = defaultDate+' '+value;
    var time2 = defaultDate+' '+$(requirement).val();
    var date1 = Date.parse(time1);
    var date2 = Date.parse(time2);
   // console.log(time1);
  //console.log("end",date1);
  //console.log("start",date2);
    if(date1 < date2){
    return true;
    }
    else{ return false;  }
  },
  messages: {
  en: 'Time should be lesser than End Time'

  }
  });

window.Parsley
  .addValidator('mindate', {
  requirementType: 'string',
  validateString: function(value, requirement) 
  { 
    var val1 = value;
    var val2 = $(requirement).val();
    var date1 = Date.parse(val1);
    var date2 = Date.parse(val2);
  
   /* console.log("end",date1);
    console.log("start",date2);*/
    if(date1 >= date2){
    return true;
    }
    else{ return false;  }
  },
  messages: {
  en: 'Invalid End Date'
  }
  });

/*SETTING DOCTOR SCHEDULE*/
$('#doc_sch_sub').click(function(){
  if ($('#doc_sch_sub_form').parsley().validate() ) 
    { 
      //$('#loading').show();
       console.log($('#doc_sch_sub_form').serializeArray());
       var result = post_ajax(base_url+'Doctor/addSchedule',$('#doc_sch_sub_form').serializeArray());
        var items = JSON.parse(result);
      //  console.log(result);
        if(items.status=='success')
        {
         // $('#loading').hide();
          $('#add_schedule_success').removeClass('hidden');
          $('#doc_sel_clinic').val("Select Clinic").trigger('change');
          $('.ip_schedule_week input').attr('disabled', 'disabled'); 
          setTimeout(function(){
          $('#add_schedule_success').addClass('hidden');
          },5000)
        } 
        else if(items.status=='fail')
        {
          //$('#loading').hide();
          $('#add_schedule_fail').html(items.msg);
          $('#add_schedule_fail').removeClass('hidden');
          setTimeout(function(){
          $('#add_schedule_fail').addClass('hidden');
          },5000)
        }
    }
});

/*SETTING CONSULTATION CONFIGURATION*/
 $('#doc_consult_config_sub').click(function()
  {
    if ($('#doc_consult_config_sub_form').parsley().validate() ) 
      { 
        //$('#loading').show();
        var result = post_ajax(base_url+'Doctor/addConsultConfig',$('#doc_consult_config_sub_form').serializeArray());
        var items = JSON.parse(result);
         if(items.status=='success')
        {
           // $('#loading').hide();
          $('#add_consult_config_success').removeClass('hidden');
          setTimeout(function(){
          $('#add_consult_config_success').addClass('hidden');
          },5000)
        } 
        else if(items.status=='fail')
        {
         // $('#loading').hide();
          $('#add_consult_config_fail').removeClass('hidden');
          setTimeout(function(){
          $('#add_consult_config_fail').addClass('hidden');
          },5000)
        }
      }
  })


  $('#doc_leave_sub').click(function()
  {
    if ($('#doc_leave_sub_form').parsley().validate() ) 
      { 
        var result = post_ajax(base_url+'Doctor/addVacation',$('#doc_leave_sub_form').serializeArray());
        var items = JSON.parse(result);
        //console.log(result);
        if(items.status=='success')
        {
          $('#add_vacation_success').removeClass('hidden');
          $('#doc_leave_clinic').val("Select Clinic");
          $('#dctr_leave_start,#dctr_leave_end').val("");
          setTimeout(function(){
          $('#add_vacation_success').addClass('hidden');
          },5000)
        } 
        else if(items.status=='fail')
        {
          $('#add_vacation_fail').removeClass('hidden');
          setTimeout(function(){
          $('#add_vacation_fail').addClass('hidden');
          },5000)
        }
      }
  })

  $(document).on("click","#doc_dash_appoint_cancel",function() 
{
  
  var selectedDate = $('#ip_appointment_calender').val();
  //console.log(selectedDate)
  var obj = {'booking_id':$('#doc_dash_appoint_cancel').attr('bookid') ,'selectedDate': selectedDate}
  var result = post_ajax(base_url+'Doctor/cancelBooking',obj);
  $('#ip-appointments-day').html(result);


/* var result = post_ajax(base_url+'Patient/check_cancelBooking',obj);
  var items = JSON.parse(result);
  console.log(items);
  if(items.status=='success')
  {
    var result = post_ajax(base_url+'Doctor/cancelBooking',obj);
    $('#ip-appointments-day').html(result);
  }
  else
  {
    $('#pop3').modal('show');
  }
*/
})



$('#ip_appointment_calender_div').on('changeDate', function(ev) {
  $('#appointments_day_prevbtn').removeAttr('disabled');
  var selectedDate = ev.format(0,"mm/dd/yyyy");
  var objDate = new Date(selectedDate),locale = "en-us",month = objDate.toLocaleString(locale, { month: "long" });
  var today = new Date(selectedDate);
  var day = today.getDate();
 // console.log($('#ip_appointment_calender').val())
  $('.ip_current_date').html(day);
  $('.ip_current_month').html(month);
  var obj = {'appointment_day' : selectedDate}
  $('#ip_appointment_calender').attr('value',obj.appointment_day);
  var result = post_ajax(base_url+'Doctor/get_myappointments_day',obj);
  $('#ip-appointments-day').html(result);

  var d = new Date();d.setHours(0,0,0,0);
  if(today.getTime()<=d.getTime())
  {$('#appointments_day_prevbtn').attr('disabled','disabled');}

});

$('#appointments_day_nextbtn').on('click',function()
{
  $('#appointments_day_prevbtn').removeAttr('disabled');
  var tomorrow = new Date($('#ip_appointment_calender').val());
  tomorrow.setDate(tomorrow.getDate() + 1);

  today_mnth = tomorrow.getMonth()+1;
  today_day = tomorrow.getDate();
  today_year = tomorrow.getFullYear();
  var next_day = today_mnth+'/'+today_day+'/'+today_year;
  $('#ip_appointment_calender').attr('value',next_day);


  var objDate = new Date(next_day),locale = "en-us",month = objDate.toLocaleString(locale, { month: "long" });
  $('.ip_current_date').html(today_day);
  $('.ip_current_month').html(month);
  var obj = {'appointment_day' : next_day}
  var result = post_ajax(base_url+'Doctor/get_myappointments_day',obj);
  $('#ip-appointments-day').html(result);
  $('#ip_appointment_calender_div').datepicker('update',next_day);

  var d = new Date();d.setHours(0,0,0,0);
  if(tomorrow.getTime()<=d.getTime())
  {$('#appointments_day_prevbtn').attr('disabled','disabled');}
  //alert(next_day)
});

$('#appointments_day_prevbtn').on('click',function()
{
  var tomorrow = new Date($('#ip_appointment_calender').val());
  tomorrow.setDate(tomorrow.getDate() - 1);
  today_mnth = tomorrow.getMonth()+1;
  today_day = tomorrow.getDate();
  today_year = tomorrow.getFullYear();
  var prev_day = today_mnth+'/'+today_day+'/'+today_year;
  $('#ip_appointment_calender').attr('value',prev_day);

  var objDate = new Date(prev_day),locale = "en-us",month = objDate.toLocaleString(locale, { month: "long" });
  $('.ip_current_date').html(today_day);
  $('.ip_current_month').html(month);
  var obj = {'appointment_day' : prev_day}
  var result = post_ajax(base_url+'Doctor/get_myappointments_day',obj);
  $('#ip-appointments-day').html(result);
  $('#ip_appointment_calender_div').datepicker('update',prev_day);

 
  var d = new Date();d.setHours(0,0,0,0);
  if(tomorrow.getTime()<=d.getTime())
  {$('#appointments_day_prevbtn').attr('disabled','disabled');}

});

$('#appointments_day_todaybtn').on('click',function()
{
  
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate());
  today_mnth = tomorrow.getMonth()+1;
  today_day = tomorrow.getDate();
  today_year = tomorrow.getFullYear();
  var tod_day = today_mnth+'/'+today_day+'/'+today_year;
  $('#ip_appointment_calender').attr('value',tod_day);

  var objDate = new Date(tod_day),locale = "en-us",month = objDate.toLocaleString(locale, { month: "long" });
  $('.ip_current_date').html(today_day);
  $('.ip_current_month').html(month);
  var obj = {'appointment_day' : tod_day}
  var result = post_ajax(base_url+'Doctor/get_myappointments_day',obj);
  $('#ip-appointments-day').html(result);
  $('#ip_appointment_calender_div').datepicker('update',tod_day);

  $('#appointments_day_prevbtn').attr('disabled','disabled');
});


/*function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}
*/
//July
//alert(daysInMonth(12,2017)); //31

var month_names = ['January', 'February', 'March','April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December'];
new_date = new Date();
$('.ip_current_date').html(new_date.getDate());
$('.ip_current_month').html(month_names[new_date.getMonth()]);
//alert(n+'-'+d.getFullYear()+'-'+d.getDate())

$('.dctr_dash_appoint_day').on("click", function(){
  $('#appointments_day_todaybtn,#appointments_day_nextbtn,#appointments_day_prevbtn').removeAttr("disabled");
  var tomorrow = new Date($('#ip_appointment_calender').val());
  tomorrow.setDate(tomorrow.getDate());

  var d = new Date();d.setHours(0,0,0,0);
  if(tomorrow.getTime()<=d.getTime())
  {$('#appointments_day_prevbtn').attr('disabled','disabled');}

});

$('.dctr_dash_appoint_week').on("click", function(){
  $('#appointments_day_todaybtn,#appointments_day_nextbtn,#appointments_day_prevbtn').attr('disabled','disabled');
  var result = post_ajax(base_url+'Doctor/doctor_appointments_week');
  $('#dctr_week_appointment').html(result);
});

$('.dctr_dash_appoint_month').on("click", function(){
  $('#appointments_day_todaybtn,#appointments_day_nextbtn,#appointments_day_prevbtn').attr('disabled','disabled');
  var result = post_ajax(base_url+'Doctor/doctor_appointments_month');
  $('#dctr_month_appointment').html(result);
});

/*DOCTOR PROFILE DELETE STARTS*/
$("#doc-delete-complete").on("hidden.bs.modal", function () {
    window.location.href= base_url+"Home/logout";
});

$('#doc_del_check_code_sub').click(function()
{
  $('#doc_profile_delete_code_error').addClass('hidden')
  if ($('#doc_profile_delete_confirmation').parsley().validate() ) 
      { 

        var result = post_ajax(base_url+'Doctor/check_current_user_confirmationcode',$('#doc_profile_delete_confirmation').serializeArray());
        var items = JSON.parse(result);
        //var items = {'status':'success'};
        if(items.status=="success")
        {
          $('#doc-delete-con').modal('hide');
          $('#doc-delete-complete').modal('show');
        }
        else
        {
          $('#doc_profile_delete_code_error').removeClass('hidden').html(items.msg);
        }
      }
})

$('#doc_del_check_login_sub').click(function()
{
  $('#doc_profile_delete_error').addClass('hidden')
  if ($('#doc_profile_delete').parsley().validate() ) 
      { 

        var result = post_ajax(base_url+'Doctor/check_current_user_credential',$('#doc_profile_delete').serializeArray());
        var items = JSON.parse(result);
        //var items = {'status':'success'};
        if(items.status=="success")
        {
          $('#doc-delete').modal('hide');
          $('#doc-delete-con').modal('show');
        }
        else
        {
          $('#doc_profile_delete_error').removeClass('hidden').html(items.msg);
        }
      }
})


$('.doc-delete-profile').click(function()
{
  $('.reset-form').val('');
  $('#doc_profile_delete_error').addClass('hidden')
  $('#doc-delete').modal('show');
})

/*DOCTOR PROFILE DELETE ENDS*/




/*----------------------------------*/


/*SEARCH-RESULT-MAPS*/

var map;
var brooklyn = new google.maps.LatLng(40.6743890, -73.9455);

var stylez = [
    {
      featureType: "all",
      elementType: "all",
      stylers: [
        { saturation: -100 } // <-- THIS
      ]
    }
];

var mapOptions = {
    zoom: 11,
    center: brooklyn,
    mapTypeControlOptions: {
         mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'tehgrayz']
    }
};

/*map = new google.maps.Map(document.getElementById("ip_map_canvas"), mapOptions);

var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" });
map.mapTypes.set('tehgrayz', mapType);
map.setMapTypeId('tehgrayz');*/

/*----------------------------------*/

/*FILTER-FULLCALENDER*/
	 //
	//  $('#ip_fullcalendar').fullCalendar({
	// 		header: {
	// 			left: 'prev,next',
	// 			center: 'title',
	// 			right: ''
	// 		},
	// 		defaultView:'agendaWeek',
	// 		defaultDate: '2017-05-12',
	// 		navLinks: true, // can click day/week names to navigate views
	// 		businessHours: true, // display business hours
	// 		editable: true,
	// 		events: [
	// 			{
	// 				title: 'Available',
	// 				start: '2017-05-08T01:01:00',
	// 				constraint: 'available', // defined below
	// 				color: '#63da37'
	// 			},
	 //
	// 			{
	// 				title: 'Unavailable',
	// 				start: '2017-05-09T01:03:00',
	// 				constraint: 'notavailable', // defined below
	// 				color: '#ff004f'
	// 			},
	 //
	// 		]
	// 	});

/*----------------------------------*/

/*SEARCH_EXPAND*/

/*var form = document.getElementById("search-form");
console.log('where am i?');

document.getElementById("search-form").addEventListener("submit", function (event) {
    var searchText = document.querySelector('[name="search"]').value;
    console.log("submit '%s'", searchText);
    var searchText = document.querySelector('[name="search"]').value = '';
    event.preventDefault();
});

document.getElementById("search-text").addEventListener("click", function (event) {
    var searchText = document.querySelector('[name="search"]').value;
    if (searchText.trim().length > 0) {
        console.log(searchText);
    }
});*/

/*----------------------------------*/
/*CUSTOM*/

$(".tabs-menu a").click(function(event) {
    event.preventDefault();
    $(this).parent().addClass("current");
    $(this).parent().siblings().removeClass("current");
    var tab = $(this).attr("href");
    $(".tab-content").not(tab).css("display", "none");
    $(tab).fadeIn();
});
/*----------------------------------*/
	  
	  $('#home_testimonials').slick({
  dots: true,
  infinite: true,
  autoplay: true,
  speed: 1000,
  slidesToShow: 3,
  slidesToScroll: 1,
  responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
        dots: true
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
    
  ]
});



/*----------------------------------*/

/*RATTING-SCRIPTS*/

$(".ip_star_rate_toggle_btn:not('.noscript') input[type=radio]")
  .addClass("ip_filter_visuallyhidden")
  .change(function() {
    if( $(this).attr("name") ) {
      $(this).parent().addClass("ip_star_rate_toggle_btn_focus").siblings().removeClass("ip_star_rate_toggle_btn_focus")
    } else {
      $(this).parent().toggleClass("ip_star_rate_toggle_btn_focus");
    }
  });


  /*----------------------------------*/

  /*FILTER-SCRIPTS*/

/*  $(".ip_filter_more_list_toggle_btn:not('.noscript') input[type=radio]")
  .addClass("ip_filter_visuallyhidden");
  $(".ip_filter_more_list_toggle_btn:not('.noscript') input[type=radio]")
  .change(function() {

    $(".ip_filter_more_list_toggle_btn").removeClass("ip_filter_more_list_toggle_focus");
    if( $(this).prop("checked") == true ) {
     // alert($(this).attr("name"))
      $(this).parent().addClass("ip_filter_more_list_toggle_focus");
    } else {
      $(this).parent().removeClass("ip_filter_more_list_toggle_focus");
    }
    /*$(this).parent().addClass("ip_filter_more_list_toggle_focus").siblings().removeClass("ip_filter_more_list_toggle_focus");
    if($(this).is(':checked')) {
      $(this).parent().toggleClass("ip_filter_more_list_toggle_focus");
    }
  });
*/
  $(".ip_filter_more_list_toggle_btn:not('.noscript') input[type=radio]")
  .addClass("ip_filter_visuallyhidden")
  .change(function() {
    if( $(this).attr("name") ) {
      $(this).parent().addClass("ip_filter_more_list_toggle_focus").siblings().removeClass("ip_filter_more_list_toggle_focus");
    } else {
      $(this).parent().toggleClass("ip_filter_more_list_toggle_focus");
    }
  });
  
  $(".ip_filter_more_list_toggle_btn:not('.noscript') input[type=checkbox]")
  .addClass("ip_filter_visuallyhidden")
  .change(function() 
  {
    if( $(this).prop("checked") == true ) 
      {$(this).parent().addClass("ip_filter_more_list_toggle_focus"); }
    else 
      {$(this).parent().removeClass("ip_filter_more_list_toggle_focus");}
  });

  /*----------------------------------*/

  /* RETURN-SCRIPT */

  $(".ip_return_option_toggle_btn:not('.noscript') input[type=radio]")
  .addClass("ip_filter_visuallyhidden")
  .change(function() {

    if( $(this).attr("name") ) {
      $(this).parent().addClass("ip_return_option_toggle_focus").siblings().removeClass("ip_return_option_toggle_focus")
    } else {
      $(this).parent().toggleClass("ip_return_option_toggle_focus");
    }
  });


});

$('.cus-map').on('shown.bs.collapse', function () {
    var id = $(this).find('.map_data').first().attr("id");
    setTimeout(function(){initialize_map(id);},300);
  })

function load_dynamic_map(){
   $('.cus-map').on('shown.bs.collapse', function () {
      var id = $(this).find('.map_data').first().attr("id");
      setTimeout(function(){initialize_map(id);},300);
    })
}


window.Parsley.addValidator('uppercase', {
  requirementType: 'number',
  validateString: function(value, requirement) {
    var uppercases = value.match(/[A-Z]/g) || [];
    return uppercases.length >= requirement;
  },
  messages: {
    en: 'Your password must contain at least (%s) uppercase letter.'
  }
});

//has lowercase
window.Parsley.addValidator('lowercase', {
  requirementType: 'number',
  validateString: function(value, requirement) {
    var lowecases = value.match(/[a-z]/g) || [];
    return lowecases.length >= requirement;
  },
  messages: {
    en: 'Your password must contain at least (%s) lowercase letter.'
  }
});

//has number
window.Parsley.addValidator('number', {
  requirementType: 'number',
  validateString: function(value, requirement) {
    var numbers = value.match(/[0-9]/g) || [];
    return numbers.length >= requirement;
  },
  messages: {
    en: 'Your password must contain at least (%s) number.'
  }
});

//has special char
window.Parsley.addValidator('special', {
  requirementType: 'number',
  validateString: function(value, requirement) {
    var specials = value.match(/[^a-zA-Z0-9]/g) || [];
    return specials.length >= requirement;
  },
  messages: {
    en: 'Your password must contain at least (%s) special characters.'
  }
});

  window.Parsley.addValidator('datebirthdoc', {
    requirementType: 'number',
    validateString: function(value, requirement) 
    {

      console.log(value);
      if(value == ''){
        status = true;
      }else{
        status = false;
      }
      // console.log(requirement);
        // var obj = {'email':value }
        // var status;
        // var result = post_ajax(base_url+'Home/check_email_doc',obj);
        // var items = JSON.parse(result);
        // if(items.message!="success")
        // {
        //   status = false;
        // }
        // else
        // {                                             
        //   status = true;
        // }
         return status;  
      },
      messages: { en: 'This field should not be empty.'  }
    });

function datebirth_function(){
  var error = 0;
  var day = $('#birth_day').val();
  var month = $('#birth_month').val();
  var year = $('#birth_year').val();
  // if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)){
  //   if(month == '02'){
  //     if(day > 29){
  //       var error = 1;
  //     }
  //   }
  // }else{
  //    if(month == '02'){
  //       if(day > 28){
  //         var error = 1;
  //       }
  //    }else {
  //       var daymonth = getDaysInMonth(month, year);
  //       if()
  //    }
  // }
  var daymonth = getDaysInMonth(month, year);
  if(daymonth >= day){
    error = 0;
  }else{
    error = 1;
  }

  if(error == '1'){
    $('#error_date').html('<div style="color:#B94A48;font-family: Solomon_book, sans-serif !important;font-size:15px;margin-left:13px">Please choose a valid date</div>');
  }
}

var getDaysInMonth = function(month,year) {
  // Here January is 1 based
  //Day 0 is the last day in the previous month
 return new Date(year, month, 0).getDate();
// Here January is 0 based
// return new Date(year, month+1, 0).getDate();
};

function loadaddress_cep(e,requirement)
{
  if(e.value.length==8)
  {
   var obj = {'cep':e.value};
    var result = post_ajax(base_url+'Home/check_cep',obj);
   // console.log(result);
    var items = JSON.parse(result);
    if(items.erro!==true)
    {
      var urlresult = post_ajax(base_url+'Home/get_url_data',obj);
      if(urlresult != ''){
        var url_data = JSON.parse(urlresult);
        var defaultlat = url_data.results[0].geometry.location.lat;
        var defaultlon = url_data.results[0].geometry.location.lng;
        console.log(defaultlat);

        $('#default_latitude').val(defaultlat);
        $('#default_longitude').val(defaultlon);
      }
      if(requirement=="doctor")
      {
        $('#doc-reg-rua').val(items.logradouro);
        $('#doc-reg-locality').val(items.localidade);
       // $('#doc-reg-number').val(items.ibge);
        $('#doc-reg-complement').val(items.complemento);
      }
      if(requirement=="patient")
      {
        $('#pat-reg-rua').val(items.logradouro);
        $('#pat-reg-locality').val(items.localidade);
        $('#pat-reg-number').val(items.ibge);
        $('#pat-reg-complement').val(items.complemento);
      }
    }
    else
    {
      if(requirement=="doctor")
      {
        $('#doc-reg-rua,#doc-reg-locality,#doc-reg-number,#doc-reg-complement').val('');
      }
      if(requirement=="patient")
      {
        $('#pat-reg-rua,#pat-reg-locality,#pat-reg-number,#pat-reg-complement').val('');
      }
    }
  }
}


/*--------------------------
------- Language Change--------
-----------------------------*/

function langChange(lval) {
    
    //alert(lval.value);
    var lval=lval.value;
    $.ajax({
      type: "POST",
      url: base_url+"Home/langSettings",
      data: {lval:lval},
      success: function(response) {
        console.log(response);
        location.reload();
      }
  });
}
/************new js********************/
/*
  $(function() {
      $("#search_sepciality").autocomplete({
          source: "<?php echo base_url('home/index'); ?>",
          select: function( event, ui ) {
              event.preventDefault();
              $("#search_sepciality").val(ui.item.id);
          }
      });
  });*/

  /* $(function() {
          $( "#search_sepciality" ).autocomplete({ //the recipient text field with id #username
          source: function( request, response ) {
            $.ajax({
                url: base_url+"home/search_doctor_data",
                dataType: "json",
                data: request,
                success: function(data){
                  console.log(data.message);
                    if(data.message != 'fail') {
                      //response(data.data);
                       $('#search_sepciality').html(data);
                    }
                }
            });
        }
    });
});*/

/**********************Search doctor or clinic in frontpage **************************************/

 /* $(document).ready(function () {
    $("#search_sepciality").keyup(function () {
      var language = $('#language').val();
        $.ajax({
            type: "POST",
            url: base_url+"home/search_doctor_data",
            data: {
                keyword: $("#search_sepciality").val()
            },
            dataType: "json",
            success: function (data) {
              console.log(data);
              if(data.message != 'fail'){
                if (data.data.length > 0) {
                  console.log('length');
                    $('#DropdownCountry').empty();
                    $('#search_sepciality').attr("data-toggle", "dropdown");
                    $('#DropdownCountry').dropdown('toggle');
                    document.getElementById("DropdownCountry").style.display = null;
                }
                else if (data.data.length == 0) {
                  
                    $('#search_sepciality').attr("data-toggle", "");
                }
                $.each(data.data, function (key,value) {
                    if (data.data.length >= 0){
                        $("#DropdownCountry").css('display',null);
                        $('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">' + value['specialization_name'] + '</a></li>');
                    }
                });
              }else{
                 $('#DropdownCountry').empty();
                 $('#search_sepciality').attr("data-toggle", "dropdown");
                 $('#DropdownCountry').dropdown('toggle');
                 if(language == 'en'){
                    $('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue"> No Result Found </a></li>');
                 }else{
                    $('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue"> Nenhum resultado encontrado </a></li>');
                 }
                 
              }
            }
        });
    });
    $('ul.txtcountry').on('click', 'li a', function () {
       // $("#DropdownCountry").css('display',null);
        $('#search_sepciality').val($(this).text());
    });
});*/

 $(document).ready(function () {
    $("#search_sepciality").keyup(function () {
      var language = $('#language').val();
        $.ajax({
            type: "POST",
            url: base_url+"home/search_doctor_data",
            data: {
                keyword: $("#search_sepciality").val()
            },
            dataType: "json",
            success: function (data) {
             // console.log(data);
              if(data != ''){
          /*      $("#DropdownCountry").css('display',null);
               $("#DropdownCountry").html(data);*/
                 $('#DropdownCountry').empty();
                    $('#search_sepciality').attr("data-toggle", "dropdown");
                    $('#DropdownCountry').dropdown('toggle');
                    document.getElementById("DropdownCountry").style.display = null;
                    $('#DropdownCountry').append(data);
              }
              else{
                $('#DropdownCountry').empty();
                $('#search_sepciality').attr("data-toggle", "dropdown");
                $('#DropdownCountry').dropdown('toggle');
                document.getElementById("DropdownCountry").style.display = null;
                if(language == 'en'){
                  $('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue"> No Result Found </a></li>');
                }else{
                  $('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue"> Nenhum resultado encontrado </a></li>');
                }
              }
            }
        });
    });

    $('ul.txtcountry').on('click', 'li a', function () {
       // $("#DropdownCountry").css('display',null);
        $(this).parents().addClass('selectedLi');
        $('li.selectedLi').find('input:first').addClass('selectedInput');
        $('#search_sepciality').val($(this).text());
       var selct = $('.selectedInput').val();
        $('#selected_doctor_type').val(selct);
    });

   
});