var startTime = Date.now();
function jsonEscape(str)  {
    return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}
function checkMsg(stop=0) {
    var from= $("#to-1").val();
    checkSend("",from,1,stop);
}
function checkSend(code,from='',get_messages=0,stop=0) {
    if(stop){
        return false;
    }
    if(code!=''){
        $("#loading-div").show();
        $("#complate-div").hide();

        $.post("checkNotifications.php",{code:code},function (res) {
            if(res!="2"){
                $("#loading-div").hide();
                $("#complate-div").show();
                $("#next").prop('disabled', false);
                $("#next").addClass("highlight");
                $( ".to" ).each(function( index ) {
                    $( this ).val(res);
                });
                $("#toSpan").html(res);
                $("#date-1").trigger("keyup");
                $("#confirm-number-2").trigger("keyup");
                $("#code-3").trigger("keyup");
                $("#comment").trigger("keyup");
            }else{
                $("#loading-div").show();
                $("#complate-div").hide();
                $("#next").prop('disabled', true);
                $("#next").removeClass("highlight");
                if((Date.now() - startTime) <= 120000){
                    setTimeout(function(a) {
                        checkSend(code);
                    },2000);
                }else{
                    $("#loading-div").hide();
                    $("#complate-div").hide();
                    $("#error-div").show();
                }
            }
        });
    }
    if(from!=''){
        $.post("checkNotifications.php",{get:get_messages,from:from},function (res) {
            if(res!="2"){
                $("#conversation").append(res);
                $("#conversation").animate({ scrollTop: $('#conversation').prop("scrollHeight")}, 1000);
            }else{
                $("#next").removeClass("highlight");
            }
            setTimeout(function(a) {
                checkSend('',from,0);
            },2000);
        });
    }
}
function newCode() {
    var code="";
    var btn= $("#new-code-btn");
    code=Math.random().toString().slice(2,6);
    $("#code").html(code);
    checkSend(code);
}
function getLocation() {
    if (navigator.geolocation) {
        return navigator.geolocation.getCurrentPosition(sendPosition);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}
function sendPosition(position) {
    $.post("sendMsg.php",{lat:position.coords.latitude,lng:position.coords.longitude},function (response) {
        response=JSON.stringify(JSON.parse(response), null, "\t");
        response=JSON.stringify(JSON.parse(response), null, 4);
        $("#json4").html(response);
        var curl="curl -X POST \\\n"+
            "https://www.mobily.ws/wa/v1/messages/ \\\n"+
            "-H 'Accept: */*' \\\n"+
            "-H 'Authorization: Bearer *****.*****.*****' \\\n"+
            "-H 'Cache-Control: no-cache' \\\n"+
            "-H 'Connection: keep-alive' \\\n"+
            "-H 'Content-Type: application/json' \\\n"+
            "-H 'Host: www.mobily.ws' \\\n"+
            "-H 'cache-control: no-cache' \\\n"+
            "-H 'content-length: 90' \\\n";
        curl+="-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"location\",\"lat\": \"{lat}\",\"lng\": \"{lng}\",\"name\": \"{name}\",\"address\": \"{address}\"}}'";
        curl=curl.replace("{to}",$("#to-1").val());
        curl=curl.replace("{lat}",position.coords.latitude);
        curl=curl.replace("{lng}",position.coords.longitude);
        $("#curl4").html(curl);
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();
    });
}
function sendFiles(type){
    swal({
        title: "Are you sure?",
        text: "To send this file!",
        type: "success",
        showCancelButton: true,
        confirmButtonColor: "#008000",
        confirmButtonText: "Yes, Send it",
        closeOnConfirm: false
    }, function(isConfirm){
        if (!isConfirm) return false;
        $(".confirm").each(function () {
            $(this).prop("disabled", true);
        });
        var id="#"+type+"Data";
        var file_data = $(id).prop('files')[0];
        var form_data = new FormData();
        form_data.append(type, file_data);
        $.ajax({
            url: 'sendMsg.php', // point to server-side PHP script
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
                $(id).val('');
                swal("Done!", "It was succesfully Send!", "success");
                $(".confirm").each(function () {
                    $(this).prop("disabled", false);
                });
                response=JSON.stringify(JSON.parse(response), null, "\t");
                response=JSON.stringify(JSON.parse(response), null, 4);
                $("#json4").html(response);
                response=JSON.parse(response);
                $.post("checkNotifications.php",{msg_id:response.statuses[0].message_id},function (res) {
                    res=JSON.parse(res);
                    var curl="curl -X POST \\\n"+
                        "https://www.mobily.ws/wa/v1/messages/ \\\n"+
                        "-H 'Accept: */*' \\\n"+
                        "-H 'Authorization: Bearer *****.*****.*****' \\\n"+
                        "-H 'Cache-Control: no-cache' \\\n"+
                        "-H 'Connection: keep-alive' \\\n"+
                        "-H 'Content-Type: application/json' \\\n"+
                        "-H 'Host: www.mobily.ws' \\\n"+
                        "-H 'cache-control: no-cache' \\\n"+
                        "-H 'content-length: 90' \\\n";
                        curl+="-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"{type}\",\"url\": \"{url}\",\"caption\": \"{caption}\"}}'";
                        curl=curl.replace("{to}",res.to);
                        curl=curl.replace("{type}",res.type);
                        curl=curl.replace("{url}",res.body);
                        curl=curl.replace("{caption}",res.caption);
                    $("#curl4").html(curl);
                    hljs.initHighlighting.called = false;
                    hljs.initHighlighting();
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error Sending!", "Please try again", "error");
                var file_data = $(id).val('');
            }
        });
    });
}
$(function(){
    $("#send").click(function() {
    });
    $("#popBtn").on("click",function() {
        $(".action_menu").toggle();
    });
    $(".menuItem").click(function (e) {
        $(".action_menu").toggle();
    });
    $("#image").click(function () {
        document.getElementById('imageData').click();
    });
    $('#imageData').on('change', function() {
        sendFiles("image");
    });
    $("#video").click(function () {
        document.getElementById('videoData').click();
    });
    $('#videoData').on('change', function() {
        sendFiles("video");
    });
    $("#audio").click(function () {
        document.getElementById('audioData').click();
    });
    $('#audioData').on('change', function() {
        sendFiles("audio");
    });
    $("#document").click(function () {
        document.getElementById('documentData').click();
    });
    $('#documentData').on('change', function() {
        sendFiles("document");
    });

    $("#location").click(function () {
        getLocation();
    });
});
$(document).ready(function () {

    newCode();
    $('[data-toggle="tooltip"]').tooltip();
    $('#form-1').formValidation({
        framework: 'bootstrap',
        excluded: [':disabled'],
        icon: false,
        fields: {
            'to-1': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'from-1': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'date-1': {
                validators: {
                    notEmpty: {
                        message: 'Please add date',
                    }
                }
            },
            'time-1': {
                validators: {
                    notEmpty: {
                        message: 'Please add time',
                    }
                }
            },
            'msg-1': {
                validators: {
                    notEmpty: {
                        message: 'Please add message',
                    }
                }
            },
        },
    });
    $(document).on('success.form.fv', '#form-1', function (e) {
        $("#form-1 :input").prop("disabled", true);
        $('#form-1').submit(false);
        $('#form-1').data('formValidation').resetForm();
        $("#submit-1").prop("disabled", true);
        var url = "sendMsg.php";
        var to = $("#to-1").val();
        var date = $("#date-1").val();
        var time = $("#time-1").val();
        var msg = $("#msg-1").val();

        $.post(url,{"to-1":to,"date-1":date,"time-1":time,"msg-1":msg}, function (response) {
            if(response != "2"){
                var response2="";
                $("#form-1 :input").prop("disabled", false);
                $("#form-1").show().scrollTop(0);
                response2=JSON.stringify(JSON.parse(response), null, "\t");
                response2=JSON.stringify(JSON.parse(response), null, 4);
                $("#json1").html(response2);
                hljs.initHighlighting.called = false;
                hljs.initHighlighting();
                response=JSON.parse(response);
                if(!('reason' in response)){
                    $("#success-1").fadeIn();
                    $("#error-1").fadeOut();
                }else{
                    $("#error-1-msg").html(response.reason);
                    $("#success-1").fadeOut();
                    $("#error-1").fadeIn();
                }

            }else {
                $("#form-1 :input").prop("disabled", false);
                $("#form-1").show().scrollTop(0);
                response=JSON.parse(response);
                $("#error-1-msg").html(response.reason);
                $("#error-1").fadeIn();
                $("#success-1").fadeOut();
            }
            $("#submit-1").prop("disabled", false);
            $("#next").prop('disabled', false);
            $("#next").addClass("highlight");
        });
        setTimeout(function () {
            $("#error-1").fadeOut();
            $("#success-1").fadeOut();
        },10000)
    });


    $('#form-2').formValidation({
        framework: 'bootstrap',
        excluded: [':disabled'],
        icon: false,
        fields: {
            'to-2': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'from-2': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'confirm-number-2': {
                validators: {
                    notEmpty: {
                        message: 'Please add Confirm number',
                    }
                }
            },
            'msg-2': {
                validators: {
                    notEmpty: {
                        message: 'Please add message',
                    }
                }
            },
        },
    });
    $(document).on('success.form.fv', '#form-2', function (e) {
        $("#form-2 :input").prop("disabled", true);
        $('#form-2').submit(false);
        $('#form-2').data('formValidation').resetForm();
        $("#submit-2").prop("disabled", true);
        var url = "sendMsg.php";
        var to = $("#to-2").val();
        var confirm = $("#confirm-number-2").val();
        var msg = $("#msg-2").val();

        $.post(url,{"to-2":to,"confirm-number-2":confirm,"msg-2":msg}, function (response) {
            if(response != "2"){
                var response2="";
                $("#form-2 :input").prop("disabled", false);
                $("#form-2").show().scrollTop(0);
                response2=JSON.stringify(JSON.parse(response), null, "\t");
                response2=JSON.stringify(JSON.parse(response), null, 4);
                $("#json2").html(response2);
                hljs.initHighlighting.called = false;
                hljs.initHighlighting();
                response=JSON.parse(response);
                if(!('reason' in response)){
                    $("#success-2").fadeIn();
                    $("#error-2").fadeOut();
                }else{
                    $("#error-2-msg").html(response.reason);
                    $("#success-2").fadeOut();
                    $("#error-2").fadeIn();
                }

            }else {
                $("#form-2 :input").prop("disabled", false);
                $("#form-2").show().scrollTop(0);
                response=JSON.parse(response);
                $("#error-2-msg").html(response.reason);
                $("#error-2").fadeIn();
                $("#success-2").fadeOut();
            }
            $("#submit-2").prop("disabled", false);
            $("#next").prop('disabled', false);
            $("#next").addClass("highlight");
        });
        setTimeout(function () {
            $("#error-2").fadeOut();
            $("#success-2").fadeOut();
        },10000)
    });

    $('#form-3').formValidation({
        framework: 'bootstrap',
        excluded: [':disabled'],
        icon: false,
        fields: {
            'to-3': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'from-3': {
                trigger: 'blur',
                validators: {
                    notEmpty: {
                        message: 'Please add to mobile',
                    },
                    numeric: {
                        message: 'Please add correct to mobile',
                    },
                    stringLength: {
                        min: 9,
                        max: 12,
                        message: 'Please add correct to mobile',
                    }
                }
            },
            'code': {
                validators: {
                    notEmpty: {
                        message: 'Please add code',
                    }
                }
            },
            'msg-3': {
                validators: {
                    notEmpty: {
                        message: 'Please add message',
                    }
                }
            },
        },
    });
    $(document).on('success.form.fv', '#form-3', function (e) {
        $("#form-3 :input").prop("disabled", true);
        $('#form-3').submit(false);
        $('#form-3').data('formValidation').resetForm();
        $("#submit-3").prop("disabled", true);
        var url = "sendMsg.php";
        var to = $("#to-3").val();
        var code = $("#code-3").val();
        var msg = $("#msg-3").val();

        $.post(url,{"to-3":to,"code":code,"msg-3":msg}, function (response) {
            if(response != "2"){
                var response2="";
                $("#form-3 :input").prop("disabled", false);
                $("#form-3").show().scrollTop(0);
                response2=JSON.stringify(JSON.parse(response), null, "\t");
                response2=JSON.stringify(JSON.parse(response), null, 4);
                $("#json3").html(response2);
                hljs.initHighlighting.called = false;
                hljs.initHighlighting();
                response=JSON.parse(response);
                if(!('reason' in response)){
                    $("#success-3").fadeIn();
                    $("#error-3").fadeOut();
                }else{
                    $("#error-3-msg").html(response.reason);
                    $("#success-3").fadeOut();
                    $("#error-3").fadeIn();
                }

            }else {
                $("#form-3 :input").prop("disabled", false);
                $("#form-3").show().scrollTop(0);
                response=JSON.parse(response);
                $("#error-3-msg").html(response.reason);
                $("#error-3").fadeIn();
                $("#success-3").fadeOut();
            }
            $("#submit-3").prop("disabled", false);
            $("#next").prop('disabled', false);
            $("#next").addClass("highlight");
        });
        setTimeout(function () {
            $("#error-3").fadeOut();
            $("#success-3").fadeOut();
        },10000)
    });


    $("#send").click(function (e) {
        var url = "sendMsg.php";
        var message = $("#comment").val();
        $("#comment").val('');
        $.post(url,{"message":jsonEscape(message)}, function (response) {
            if(response != "2"){
                if((response != '')){
                    response=JSON.stringify(JSON.parse(response), null, "\t");
                    response=JSON.stringify(JSON.parse(response), null, 4);
                    $("#json4").html(response);
                    hljs.initHighlighting.called = false;
                    hljs.initHighlighting();
                    response=JSON.parse(response);
                    if(!('reason' in response)){
                        $("#success-4").fadeIn();
                        $("#error-4").fadeOut();
                    }else{
                        $("#error-4-msg").html(response.reason);
                        $("#success-4").fadeOut();
                        $("#error-4").fadeIn();
                    }
                    setTimeout(function () {
                        $("#error-4").fadeOut();
                        $("#success-4").fadeOut();
                    },3000)
                }
            }
            $("#next").prop('disabled', false);
            $("#next").addClass("highlight");
        });
    });

    $("#date-1 , #time-1").keyup(function () {
        var msg="your order has been shipped successfully and expected to be delivered in {date} at {time}";
        msg=msg.replace("{date}",$("#date-1").val());
        msg=msg.replace("{time}",$("#time-1").val());
        $("#msg-1").val(msg);

        var curl="curl -X POST \\\n"+
"https://www.mobily.ws/wa/v1/messages/ \\\n"+
"-H 'Accept: */*' \\\n"+
"-H 'Authorization: Bearer *****.*****.*****' \\\n"+
"-H 'Cache-Control: no-cache' \\\n"+
"-H 'Connection: keep-alive' \\\n"+
"-H 'Content-Type: application/json' \\\n"+
"-H 'Host: www.mobily.ws' \\\n"+
"-H 'cache-control: no-cache' \\\n"+
"-H 'content-length: 90' \\\n"+
"-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"text\",\"text\": \"{msg}\"}}'";
        curl=curl.replace("{to}",$("#to-1").val());
        curl=curl.replace("{msg}",msg);
        $("#curl1").html(curl);
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();
    });
    $("#confirm-number-2").keyup(function () {
        var msg="You have place order {confirmation-number} successfully.";
        msg=msg.replace("{confirmation-number}",$("#confirm-number-2").val());
        $("#msg-2").val(msg);
        var curl="curl -X POST \\\n"+
"https://www.mobily.ws/wa/v1/messages/ \\\n"+
"-H 'Accept: */*' \\\n"+
"-H 'Authorization: Bearer *****.*****.*****' \\\n"+
"-H 'Cache-Control: no-cache' \\\n"+
"-H 'Connection: keep-alive' \\\n"+
"-H 'Content-Type: application/json' \\\n"+
"-H 'Host: www.mobily.ws' \\\n"+
"-H 'cache-control: no-cache' \\\n"+
"-H 'content-length: 90' \\\n"+
"-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"text\",\"text\": \"{msg}\"}}'";
        curl=curl.replace("{to}",$("#to-1").val());
        curl=curl.replace("{msg}",msg);
        $("#curl2").html(curl);
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();

    });
    $("#code-3").keyup(function () {
        var msg="Your verify code is: {code}";
        msg=msg.replace("{code}",$("#code-3").val());
        $("#msg-3").val(msg);
        var curl="curl -X POST \\\n"+
"https://www.mobily.ws/wa/v1/messages/ \\\n"+
"-H 'Accept: */*' \\\n"+
"-H 'Authorization: Bearer *****.*****.*****' \\\n"+
"-H 'Cache-Control: no-cache' \\\n"+
"-H 'Connection: keep-alive' \\\n"+
"-H 'Content-Type: application/json' \\\n"+
"-H 'Host: www.mobily.ws' \\\n"+
"-H 'cache-control: no-cache' \\\n"+
"-H 'content-length: 90' \\\n"+
"-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"text\",\"text\": \"{msg}\"}}'";
        curl=curl.replace("{to}",$("#to-1").val());
        curl=curl.replace("{msg}",msg);
        $("#curl3").html(curl);
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();

    });

    $("#comment").keyup(function () {
        var msg=$("#comment").val();
        var curl="curl -X POST \\\n"+
"https://www.mobily.ws/wa/v1/messages/ \\\n"+
"-H 'Accept: */*' \\\n"+
"-H 'Authorization: Bearer *****.*****.*****' \\\n"+
"-H 'Cache-Control: no-cache' \\\n"+
"-H 'Connection: keep-alive' \\\n"+
"-H 'Content-Type: application/json' \\\n"+
"-H 'Host: www.mobily.ws' \\\n"+
"-H 'cache-control: no-cache' \\\n"+
"-H 'content-length: 90' \\\n"+
"-d '{\"to\": [\"{to}\"],\"message\": {\"type\": \"text\",\"text\": \"{msg}\"}}'";
        curl=curl.replace("{to}",$("#to-4").val());
        curl=curl.replace("{msg}",msg);
        $("#curl4").html(curl);
        hljs.initHighlighting.called = false;
        hljs.initHighlighting();

    });
});

(function() {
  var step = 0;
  var steps = document.getElementsByClassName('step');
  var progressBars = document.getElementsByClassName('progress');
  var prevBtn = document.getElementById('prev');
  var nextBtn = document.getElementById('next');
  var skipBtn = document.getElementById('skip');
  nextBtn.onclick = function() {
    $("#next").removeClass("highlight");
    if(steps==0)
    $("#next").prop('disabled', true);
    if (step < steps.length - 1) {
        progressBars[step].className = 'progress complete';
        $("#setup-"+step).hide();
        step += 1;
        steps[step].className = "step active-step";
        $("#setup-"+step).show();
        if(step>=1){
          $("#prev").show();
        }else {
          $("#prev").hide();
        }
    }
    if(step==1 || step==2){
      $("#skip").show();
    }else{
      $("#skip").hide();
    }
    if(step==3){
        $("#next").hide();
        $("#final").attr("style","background-color: #f59e00;font-weight: 600;");
    }else{
        $("#final").attr("style","");
        $("#next").show();
    }

    if(step==2){
        checkMsg(0);
    }else{
        checkMsg(1);
    }
  }
  skipBtn.onclick = function() {
      $("#next").removeClass("highlight");
      if(steps==0)
          $("#next").prop('disabled', true);
      if (step < steps.length - 1) {
          progressBars[step].className = 'progress complete';
          $("#setup-"+step).hide();
          step += 1;
          steps[step].className = "step active-step";
          $("#setup-"+step).show();
          if(step>=1){
              $("#prev").show();
          }else {
              $("#prev").hide();
          }
      }
      if(step==1 || step==2){
          $("#skip").show();
      }else{
          $("#skip").hide();
      }
      if(step==3) {
          $("#next").hide();
          $("#final").attr("style","background-color: #f59e00;font-weight: 600;");
      }else{
          $("#final").attr("style","");
          $("#next").show();
      }
      if(step==2){
          checkMsg(0);
      }else{
          checkMsg(1);
      }
  }
  prevBtn.onclick = function() {
    $("#next").removeClass("highlight");
      if(step==1){
          $("#next").prop('disabled', true);
          newCode();
      }
    if (step > 0) {
      progressBars[step - 1].className = 'progress';
      steps[step].className = "step";
      $("#setup-"+step).hide();
      step -= 1;
      steps[step].className = "step active-step";
      $("#setup-"+step).show();
        if(step>=1){
            $("#prev").show();
        }else {
            $("#prev").hide();
        }
    }
    if(step==1 || step==2){
      $("#skip").show();
    }else{
      $("#skip").hide();
    }
      if(step==3)
          $("#next").hide();
      else{
          $("#final").attr("style","");
          $("#next").show();

      }
      if(step==2){
          checkMsg(0);
      }else{
          checkMsg(1);
      }
  }
})();
function copy(containerid) {
    var el = document.getElementById(containerid);
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    document.execCommand('copy');
}
