//check for investigation page

if ($('#sonarpage').val() == 1)
{
    var hosturl = $('#hosturl').val();
    var tdate = $("#tdate").val();
    var patientId = $("#patientId").val();
    var controllName = $("#controllName").val();
    var slideIndex = 1;

    $('#imagePrintAll').click(function (event)
    {
        //on click
        if (this.checked)
        {
            // check select status
            $('.imagePrint').each(function () { //loop through each checkbox
                //this.checked = true;  //select all checkboxes with class "checkbox1"
                $(this).attr('checked', 'checked');
                $(this).parent().addClass('checked');
            });
        } else
        {
            $('.imagePrint').each(function () { //loop through each checkbox
                //this.checked = false; //deselect all checkboxes with class "checkbox1"
                $(this).removeAttr('checked');
                $(this).parent().removeClass('checked');
            });
        }
    });


    //Add Row for semen
    $("#addPic").live('click', function () {
        var empty = $('#emptyImage').val();
        if (empty == 1)     // there is not empty one
        {
            $('#emptyImage').val(0);     // there is empty one
            //add new row in html
            $("#pic_div").append('<div class="col-md-3">'
                    + '<div class="row clinick ltr">'
                    + '<div class="col-md-12">'
                    + '<div class="form-group form-md-line-input form-md-floating-label has-info">'
                    + '<input type="text" class="form-control datepicker  txtc edited" id="sonardateM1" data-tableName="sonar" data-colName="sonardate"  value="' + tdate + '"/>'
                    + '<label for="form_control_1">date</label>'
                    + '</div>'
                    + '</div></div>'

                    + '<div class="row clinick ltr">'
                    + '<div class="col-md-12">'
                    + ' <div class="fileinput fileinput-new" data-provides="fileinput">'
                    + '<div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 250px; height: 170px;"> </div>'
                    + '<div> <span class="btn default btn-file"> <span class="fileinput-new"> Select image </span> <span class="fileinput-exists"> Change </span>'
                    + ' <input type="file" name="sonarimg1[]" multiple  id="sonarFileM1" class="form-control " accept="image/*" >'
                    + '</span> </div>'
                    + '</div>'
                    + '</div></div>'

                    + '<div class="row clinick ltr" >'
                    + ' <div class="col-md-12">'
                    + '<div class="form-group form-md-line-input form-md-floating-label has-info">'
                    + '<input type="text" class="form-control" id="notesM1" data-tableName="sonar" data-colName="notes"/>'
                    + '<label for="form_control_1">Notes</label>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '<div class="row clinick ltr"><div class="col-md-6">'
                    //+ '<button type="button" class="btn btn-xs red fright removesonar" id="delsonar' + sonaritr + '" data-tableName="sonar" data-id="' + sonarid + '"><i class="fa fa-close"></i></button>'
                    //+ '<input type="checkbox" class="imagePrint" name="pic[]"   id="imagePrint' + sonarid + '" value="' + sonarid + '"/> '
                    + '  </div>'
                    + '</div>'
                    + '</div>');
            $('#sonarFileM1').change(function ()   // image   multi
            {
                $('#talks-loading').show();
                var files = $("#sonarFileM1")[0].files;
                var isValid = 2;
                for (var i = 0; i < files.length; i++)
                {
                    //alert(files[i].name);
                    var valid = checkImage(files[i].name);
                    if (valid == 2)
                    {

                    } else if (valid == 1)
                    {
                        isValid = 1;
                    }
                }

                if (isValid == 2)
                {
                    var myformdata = new FormData();
                    myformdata.append("type", "image");
                    myformdata.append("name", 'sonarFileM1');
                    myformdata.append("date", $("#sonardateM1").val());
                    myformdata.append("note", $("#notesM1").val());
                    myformdata.append("patientId", patientId);
                    myformdata.append("imgCount", files.length);
                    jQuery.each(jQuery('#sonarFileM1')[0].files, function (i, file)
                    {
                        myformdata.append('file-' + i, file);
                    });
                    $.ajax({
                        url: hosturl + '/controllers/sonar.php?ac=uploadmulti', // Url to which the request is send
                        type: "POST", // Type of request to be send, called as method
                        data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                        contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                        cache: false, // To unable request pages to be cached
                        processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                        success: function (data)  		// A function to be called if request succeeds
                        {
                            //$('#sonarFileM1One').remove();
                            //alert(data);
                            // $('#sonarFileM1Parent').prepend(data);
                            if (data == 1)
                            {
                                location.reload();
                            }

                            //$('#talks-loading').hide();
                        }
                    });
                }

            });

            $('.datepickertoday').datepicker('setDate', '+0');
            $(".datepicker").datepicker({
                todayBtn: "linked",
                // autoclose: true,
                todayHighlight: true,
                format: 'yy/mm/dd',
                isRTL: true
            });
        } else
        {
            alert('fill empty images first .....');
        }

    });

    $("#addvid").live('click', function () {
        var empty = $('#emptyVideo').val();

        if (empty == 1)       // there is not empty one
        {
            $('#emptyVideo').val(0);     // there is empty one
            $("#vid_div").append('<div class="col-md-3 vid-sonar">'
                    + '<div class="row clinick ltr" >'
                    + '<div class="col-md-12">'
                    + '<div class="form-group form-md-line-input form-md-floating-label has-info">'
                    + '<input type="text" class="form-control datepicker txtc edited" id="sonardatevM1"  value="' + tdate + '"/>'
                    + '<label for="sonardatevM1">Date</label>'
                    + ' </div>'
                    //+ '<div class="form-group form-md-line-input form-md-floating-label has-info">'
                    //+ '<input type="text" class="form-control updateElement txtl edited" id="originalname' + sonarviditr + '" data-tableName="sonar" data-colName="originalname" data-id="' + sonarid + '" value=""/>'
                    //+ ' <label for="originalname' + sonarviditr + '">Video Name</label>'
                    //+ '</div>'
                    + '  </div>'
                    + '</div>'
                    + ' <div class="row clinick ltr" >'
                    + '<div class="col-md-12">'
                    + '<div class="fileinput fileinput-new" data-provides="fileinput">'
                    + '<div>'
                    + '<span class="input-group-addon btn default btn-file" style="right: 0px; top: 3px;" > '
                    + '<span class="fileinput-new"> Select file </span> '
                    + '<span class="fileinput-exists"> Change </span>'
                    + '<input type="file" name="sonarvidM1" multiple  id="sonarvidM1" accept="video/mp4" class=" form-control " >'
                    + '</span> '
                    //+ '<a  class="input-group-addon btn vid-show" id="show' + sonarviditr + '" data-id="' + sonarid + '" style="display : none;"> Show </a>'
                    //+ '<a  class="input-group-addon btn vid-download" id="download' + sonarviditr + '"  style="display : none;"  href="' + hosturl + '/controllers/sonar.php?ac=downloadfile&id=' + sonarid + '" > Download </a> '

                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '<div class="row clinick ltr" >'
                    + '<div class="col-md-6">'
                    //+ ' <button type="button" class="btn btn-xs red fright removesonar" id="delsonar' + sonarviditr + '" data-tableName="sonar" data-id="' + sonarid + '"><i class="fa fa-close"></i></button>'
                    + '</div>'
                    + '</div>'
                    + '</div>');

            $('#sonarvidM1').change(function ()   // image   multi
            {
                $('#talks-loading').show();
                var files = $("#sonarvidM1")[0].files;
                var isValid = 2;
                for (var i = 0; i < files.length; i++)
                {
                    //alert(files[i].name);
                    var valid = checkVideo(files[i].name);
                    if (valid == 2)
                    {

                    } else if (valid == 1)
                    {
                        isValid = 1;
                    }
                }

                if (isValid == 2)
                {
                    var myformdata = new FormData();
                    myformdata.append("type", "video");
                    myformdata.append("name", 'sonarvidM1');
                    myformdata.append("date", $("#sonardatevM1").val());
                    //myformdata.append("note", $("#notesM1").val());
                    myformdata.append("patientId", patientId);
                    myformdata.append("imgCount", files.length);
                    jQuery.each(jQuery('#sonarvidM1')[0].files, function (i, file)
                    {
                        myformdata.append('file-' + i, file);
                    });
                    $.ajax({
                        url: hosturl + '/controllers/sonar.php?ac=uploadmulti', // Url to which the request is send
                        type: "POST", // Type of request to be send, called as method
                        data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                        contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                        cache: false, // To unable request pages to be cached
                        processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                        success: function (data)  		// A function to be called if request succeeds
                        {
                            //$('#sonarFileM1One').remove();
                            //alert(data);
                            // $('#sonarFileM1Parent').prepend(data);
                            if (data == 1)
                            {
                                location.reload();
                            }

                            //$('#talks-loading').hide();
                        }
                    });
                }

            });

            $('.datepickertoday').datepicker('setDate', '+0');
            $(".datepicker").datepicker({
                todayBtn: "linked",
                // autoclose: true,
                todayHighlight: true,
                format: 'yy/mm/dd',
                isRTL: true
            });
        } else
        {
            alert('fill empty videos first .....');
        }

    });
    //remove semen row
    $(".removesonar").live('click', function ()
    {
        var sonaritr = $("#sonaritr").val();
        var id = $(this).attr("data-id");
        if (id != 0) {
            //delete with ajax
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=del', {id: id}, function (res)
            {

            });
        }

        $(this).parent().parent().parent().remove();
        //$("#sonaritr").val(sonaritr-1);

    });

    $('.sonarFile').change(function ()   // image
    {
        $('#talks-loading').show();
        var Id = $(this).attr('data-id');
        var name = $(this).attr('name');
        //alert(name);
        var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
        if (filename != "")
        {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;

            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();
            if ($.inArray(ext, ['jpg', 'jepg', 'png', 'gif']) == -1)
            {
                alert("pictures only allowed (jpg , gif , png , jepg)");
                $('#talks-loading').hide();
            } else
            {
                var myformdata = new FormData();
                myformdata.append("type", "image");
                myformdata.append("Id", Id);
                myformdata.append("name", name);
                jQuery.each(jQuery('#' + name)[0].files, function (i, file)
                {
                    myformdata.append('file-' + i, file);
                });
                $.ajax({
                    url: hosturl + '/controllers/sonar.php?ac=upload', // Url to which the request is send
                    type: "POST", // Type of request to be send, called as method
                    data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                    cache: false, // To unable request pages to be cached
                    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                    success: function (data)  		// A function to be called if request succeeds
                    {
                        $('#talks-loading').hide();
                    }
                });
            }
        } else
        {
            //$(this).val("");
        }
    });

    $('.sonarvid').change(function ()   // video
    {
        $('#talks-loading').show();
        var Id = $(this).attr('data-id');
        var name = $(this).attr('name');
        var itr = $(this).attr('data-itr');

        var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
        if (filename != "")
        {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;

            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();
            if ($.inArray(ext, ['mp4']) == -1)
            {
                //$(this).val("");
                alert("Only mp4 video allowed");
                $('#talks-loading').hide();
            } else
            {
                var myformdata = new FormData();
                myformdata.append("type", "video");
                myformdata.append("Id", Id);
                myformdata.append("name", name);
                jQuery.each(jQuery('#' + name)[0].files, function (i, file)
                {
                    myformdata.append('file-' + i, file);
                });
                //alert('    تم تحميل الملف بنجاح .... ');
                $.ajax({
                    url: hosturl + '/controllers/sonar.php?ac=upload', // Url to which the request is send
                    type: "POST", // Type of request to be send, called as method
                    data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                    cache: false, // To unable request pages to be cached
                    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                    success: function (data)  		// A function to be called if request succeeds
                    {
                        $('#show' + itr).show();
                        $('#show' + itr).attr('data-file', data);
                        $('#download' + itr).show();
                        $('#originalname' + itr).val(filename);
                        $('#talks-loading').hide();
                    }
                });
            }
        } else
        {

        }
    });

    $(".vid-show").live('click', function ()
    {
        var videoName = $(this).attr('data-file');
        $('#source_vediourl').attr('src', hosturl + '/../upload/sonarvedio/1/' + videoName);
        $('#video_vediourl').load();
        $("#showVideo").modal('show');
        var vid = document.getElementById("video_vediourl");
        vid.play();
    });

    $("#closemodel").live('click', function ()
    {
        var vid = document.getElementById("video_vediourl");
        vid.pause();
    });

    $("#printPic").live('click', function ()
    {
        var images = Array();
        $('.imagePrint').each(function ()
        {
            if ($(this).is(":checked"))
            {
                images.push($(this).val());
            }
        });

        var jsonString = JSON.stringify(images);

        $.post(hosturl + '/controllers/' + controllName + '.php?ac=printpic', {jsonString: jsonString, patientId: patientId}, function (res)
        {
            //print
            $("#pImg").html(res);
            $.print("#pImg");
            $("#pImg").html('');
        });




        //$.print("#pImg");
    });


    $('#sonarFileM1').change(function ()   // image   multi
    {
        $('#talks-loading').show();
        var files = $("#sonarFileM1")[0].files;
        var isValid = 2;
        for (var i = 0; i < files.length; i++)
        {
            //alert(files[i].name);
            var valid = checkImage(files[i].name);
            if (valid == 2)
            {

            } else if (valid == 1)
            {
                isValid = 1;
            }
        }

        if (isValid == 2)
        {
            var myformdata = new FormData();
            myformdata.append("type", "image");
            myformdata.append("name", 'sonarFileM1');
            myformdata.append("date", $("#sonardateM1").val());
            myformdata.append("note", $("#notesM1").val());
            myformdata.append("patientId", patientId);
            myformdata.append("imgCount", files.length);
            jQuery.each(jQuery('#sonarFileM1')[0].files, function (i, file)
            {
                myformdata.append('file-' + i, file);
            });
            $.ajax({
                url: hosturl + '/controllers/sonar.php?ac=uploadmulti', // Url to which the request is send
                type: "POST", // Type of request to be send, called as method
                data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                cache: false, // To unable request pages to be cached
                processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                success: function (data)  		// A function to be called if request succeeds
                {
                    //$('#sonarFileM1One').remove();
                    //alert(data);
                    // $('#sonarFileM1Parent').prepend(data);
                    if (data == 1)
                    {
                        location.reload();
                    }

                    //$('#talks-loading').hide();
                }
            });
        }

    });


    $('#sonarvidM1').change(function ()   // image   multi
    {
        $('#talks-loading').show();
        var files = $("#sonarvidM1")[0].files;
        var isValid = 2;
        for (var i = 0; i < files.length; i++)
        {
            //alert(files[i].name);
            var valid = checkVideo(files[i].name);
            if (valid == 2)
            {

            } else if (valid == 1)
            {
                isValid = 1;
            }
        }

        if (isValid == 2)
        {
            var myformdata = new FormData();
            myformdata.append("type", "video");
            myformdata.append("name", 'sonarvidM1');
            myformdata.append("date", $("#sonardatevM1").val());
            //myformdata.append("note", $("#notesM1").val());
            myformdata.append("patientId", patientId);
            myformdata.append("imgCount", files.length);
            jQuery.each(jQuery('#sonarvidM1')[0].files, function (i, file)
            {
                myformdata.append('file-' + i, file);
            });
            $.ajax({
                url: hosturl + '/controllers/sonar.php?ac=uploadmulti', // Url to which the request is send
                type: "POST", // Type of request to be send, called as method
                data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                cache: false, // To unable request pages to be cached
                processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                success: function (data)  		// A function to be called if request succeeds
                {
                    //$('#sonarFileM1One').remove();
                    //alert(data);
                    // $('#sonarFileM1Parent').prepend(data);
                    if (data == 1)
                    {
                        location.reload();
                    }

                    //$('#talks-loading').hide();
                }
            });
        }

    });

    function checkVideo(filename)
    {
        filename = filename.replace(/C:\\fakepath\\/i, '');
        if (filename != "")
        {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;

            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();

            if ($.inArray(ext, ['mp4']) == -1)
            {
                //$(this).val("");
                alert("Only mp4 video allowed");
                $('#talks-loading').hide();
                return 1;
            } else
            {
                return 2;
            }
        } else
        {
            return 1;
        }
    }


    function checkImage(filename)
    {
        filename = filename.replace(/C:\\fakepath\\/i, '');
        if (filename != "")
        {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;

            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();
            if ($.inArray(ext, ['jpg', 'jepg', 'png', 'gif', 'jpeg']) == -1)
            {
                alert("pictures only allowed (jpg , gif , png , jepg , jpeg)");
                $('#talks-loading').hide();
                return 1;
            } else
            {
                return 2;
            }
        } else
        {
            return 1;
        }
    }

    $("body").on('click', '.showFile', function ()
    {
        var itr = $(this).attr('data-itr');

        $.post(hosturl + '/controllers/' + controllName + '.php?ac=getpatientimg', {patientId: patientId}, function (res)
        {
            $("#scrollImgDiv").html(res);

            slideIndex = itr;
            showDivs(itr);

            //  $("#showFileM").modal('show');
            $('#showFileM').modal({keyboard: true});
        });

    });

    $(document).keydown(function (e) {
        console.log($('#showFileM').is(':visible'));
        if ($('#showFileM').is(':visible')) {
            switch (e.which) {
                case 37:
                    plusDivs(-1);
                    break;

                case 39:
                    plusDivs(1);
                    break;
            }
        }
    });

    function plusDivs(n) {
        slideIndex = Number(slideIndex) + Number(n);
        showDivs(slideIndex);
//        showDivs(slideIndex += n);
    }

    function currentDiv(n) {
        showDivs(slideIndex = n);
    }

    function showDivs(n) {
        var i;
        var x = document.getElementsByClassName("mySlides");
        var dots = document.getElementsByClassName("demo");
        if (n > x.length) {
            slideIndex = 1;
        }
        if (n < 1) {
            slideIndex = x.length;
        }
        for (i = 0; i < x.length; i++) {
            x[i].style.display = "none";
        }
        for (i = 0; i < dots.length; i++) {
            dots[i].className = dots[i].className.replace(" w3-red", "");
        }
        x[slideIndex - 1].style.display = "block";
        dots[slideIndex - 1].className += " w3-red";
    }

}
