<div class="col-sm-8">

    <div class="row gray_ttc">
        <br>

        <div class="col-sm-5 col-sm-offset-1 text-left" style="padding: 10px">
            <strong>Message</strong>
        </div>

        <div class="col-sm-5 text-right" >
            <a href="<?php echo base_url() ?>reply-message"> <i class="fa fa-reply" title="Reply"> </i></a>&nbsp;&nbsp;
            <?php
            $person_id = $this->session->userdata('user_id');
            foreach ($preview_rcv_message as $val) {

                $viewer_id = $val->message_viewer_id;
                $viewer_id_array = explode(",", $viewer_id);
                // print_r( $viewer_id_array);
                ?>


                <a href="javascript:;" onclick="unread(<?php echo $val->message_id ?>);
                        return false;" id="unread"> 
                    <i class="fa fa-envelope" title="Mark as Unread" > </i></a>&nbsp;&nbsp


                <a href="javascript:;" onclick="read(<?php echo $val->message_id ?>);
                        return false;" id="read" style="display: none; "> <i class="fa  fa-envelope-o" title="Mark as Read"> </i></a> &nbsp;&nbsp;
<?php } ?>
            <a href="#"> <i class="fa fa-trash-o" title="Remove"> </i></a>&nbsp;&nbsp;
        </div>

        <div class="col-sm-10 col-sm-offset-1 ">
            <hr><br>
        </div>
<?php foreach ($preview_rcv_message as $val) { ?>
            <div class="col-sm-10 col-sm-offset-1 text-left" style="padding: 0">
                <div class="col-sm-12 " style="padding: 0">

                    <div class="col-sm-2">Form</div>
                    <div class="col-sm-1">:</div>

                    <div class="col-sm-9">
                        <?php
                        foreach ($message_sender_info as $sender) {

                            echo $sender->person_email;
                        }
                        ?>
                    </div>


                </div>
                <div class="col-sm-12 " style="padding: 0">
                    <div class="col-sm-2">Date</div>
                    <div class="col-sm-1">:</div>
                    <div class="col-sm-9">
    <?php
    echo date('h:i a', strtotime($val->message_datetime)) . "," . "&nbsp;";
    echo date('d F y', strtotime($val->message_datetime)) . ".";
    ?>
                    </div>

                </div>
                <div class="col-sm-12 " style="padding: 0">
                    <div class="col-sm-2">To</div>
                    <div class="col-sm-1">:</div>

                    <div class="col-sm-9">


                        <span id="fewContent">
                            <?php
                            foreach ($message_receiver_single_info as $single_receiver) {


                                echo $single_receiver->person_email;
                            }
                            ?>

                        </span>
                        <span id="moreContent" style="display: none">
                            <?php
                            foreach ($message_receiver_info as $receiver) {

                                echo $receiver->person_email . "<br>";
                            }
                            ?>
                        </span>
                        <a id="more" class="text-right" href="#" onclick="ViewMoreContent()">More..</a>
                        <a id="less" style="display: none" class="text-right" href="#" onclick="LessMoreContent()">Less..</a>
                    </div>
                </div>

            </div>

            <script>
                function ViewMoreContent() {

                    var less = document.getElementById('less');
                    var more = document.getElementById('more');
                    var fewContent = document.getElementById('fewContent');
                    var moreContent = document.getElementById('moreContent');
                    moreContent.setAttribute('style', 'display:inline');
                    fewContent.setAttribute('style', 'display:none');
                    more.setAttribute('style', 'display:none');
                    less.setAttribute('style', 'display:inline');

                }
                function LessMoreContent() {

                    var less = document.getElementById('less');
                    var more = document.getElementById('more');
                    var moreContent = document.getElementById('moreContent');
                    var fewContent = document.getElementById('fewContent');
                    moreContent.setAttribute('style', 'display:none');
                    fewContent.setAttribute('style', 'display:inline');
                    more.setAttribute('style', 'display:inline');
                    less.setAttribute('style', 'display:none');

                }
            </script>
            <div class="col-sm-10 col-sm-offset-1 ">
                <hr> <br>
            </div>
            <div class="form-group  col-sm-10 col-sm-offset-1 ">
                <div class="col-sm-12" style="background: #fff;padding: 5px">
                    <div class="col-sm-12 gray_ttc" style="padding: 10px">
                    <div class="message_show text-justify "><?php echo $val->message_body; ?></div> 
                    </div>
                </div>

                <div class="input-group">

                 
                    <?php
                    foreach ($preview_rcv_message_attachment[$val->message_id] as $attach) {
                        $message_encrypt_id = $this->encrypt->encode($val->message_id . 'talha');

                        $message_attach_encrypt_id = $this->encrypt->encode($attach->message_attachmen_id . 'talha');
                        ?>
                        <p  class="text-justify">
                            <a href="javascript:;" onclick="Download('<?php echo str_replace("/", "%F2", $message_encrypt_id); ?>', '<?php echo str_replace("/", "%F2", $message_attach_encrypt_id); ?>');
                                    return false;" >
                                <i class="fa fa-download"></i>

                                <?php
                                echo $attach->message_attachment_original_name;
                            }
                            ?>
                        </a>
                    </p>

                </div>
            </div>
<?php } ?>

       
    </div>

</div>

<div class="col-sm-8">

    <div class="row gray_ttc">
        <br>

        <div class="col-sm-10 col-sm-offset-1 text-left" style="padding: 10px">
            <strong>Reply Message</strong><hr>
        </div>
        <strong>
            <?php
            //          $exc = $this->session->userdata('msg');
            // if ($exc) {
            //   echo $exc;
            //  $this->session->unset_userdata('msg');
            //}
            ?>
        </strong>
        <div class="col-sm-12" style="color: green;">
            <strong>
                <span id="error_msg"></span>
            </strong>
        </div>

        <?php foreach ($preview_rcv_message as $val) { ?>
            <?php
            $sent_email = array(false);
            
            if (isset($message_sender_info)) {
                foreach ($message_sender_info as $sender) {
                    $sent_email[$sender->person_email] = TRUE;
                }
            }
        }
        ?>


        <?php
//         // echo validation_errors();
//        $url = "msg/sent";
//        echo form_open_multipart($url, 'class="" id="formID2" name="inviteForm" onsubmit="return checkFields();"');
        ?>

<!--        <form name="send_message" action="<?php //echo base_url();           ?>msg/sent" method="post">-->


        <input class="col-sm-12"  type="hidden" name="to_address" id="to_address" value=""  >

        <div class="col-sm-10 col-sm-offset-1 form-group">
            <select name="email_address"  

                    id="tokenize_placeholder" 
                    class="tokenize-sample" 
                    multiple="multiple" 
                    style="margin: 0px; padding: 0px; border: 0px; display: none;">

                <?php
                foreach ($link_person as $value) {
                    $email = $link_person_info[$value->person_link_id]->person_email;
                    ?>

                    <option value="<?php echo $link_person_info[$value->person_link_id]->person_email; ?>" 
                    <?php
                    if ($sent_email[$email] == TRUE) {
                        echo 'selected';
                    }
                    ?> >

                    <?php echo $link_person_info[$value->person_link_id]->person_email; ?>
                    </option>
<?php } ?>           
            </select>
        </div>
        <div class="col-sm-12 form-group" style="color: red;">
            <strong>
                <span id="error"></span>
            </strong>
        </div>

        <script type="text/javascript">
            $('select#tokenize_placeholder').tokenize({placeholder: "Please Type Person Email or Name"});

        </script> 



        <div class="form-group  col-sm-10 col-sm-offset-1 ">
            <div class="input-group">
                <textarea id="message_body" oninput="saveMessage();"  name="message_body"  class="form-control   " rows="2"  cols="80" placeholder="Message Text Here ..." onkeyup="clear_error();"  style="max-width: 560px; max-height: 60px;"></textarea>
            </div>
        </div>
        <?php foreach($preview_rcv_message as $val) { ?>
        <input type="text" name="message_id" id="message_id" value="<?php echo $val->message_id;?>">
<?php }?>
        <input type="hidden" name="cross_flag" id="cross_flag" value="1">
        <input type="hidden" name="uploading_status" id="uploading_status" value="0">



        <!--        <div class="form-group col-sm-10 col-sm-offset-1 text-left" id="upload_done">
        
                </div>-->


        <div class="col-sm-10 col-sm-offset-1 text-left" id="upload_done_all" style="display: none;" >


        </div>




        <div class="col-sm-6 col-sm-offset-1 ">
            <div class="progress" id="prog" style="height: 5px; display: none; ">
                <div id="progressBar" 
                     class="progress-bar progress-bar-success progress-bar-striped" 
                     role="progressbar" aria-valuenow="40" 
                     aria-valuemin="0" 
                     aria-valuemax="100"
                     style="">
                </div>
            </div>
        </div>

        <div class="col-sm-10 col-sm-offset-1">
            <span class="col-sm-2">
                <script>
                    $(":file").filestyle({
                        'iconName', 'glyphicon glyphicon-paperclip'
                    }
                    );</script>
                <input tabindex="-1" 
                       name="message_files"   
                       onchange="getmessageFileName(this);" 
                       id="message_files" 
                       title="Upload File" 
                       type="file" 
                       class="filestyle"
                       data-input="false"
                       data-iconName="glyphicon glyphicon-paperclip" 
                       data-buttonText=""
                       data-badge="false"
                       value="">
                <input 
                    name="message_files_name"   
                    id="message_files_name" 
                    type="hidden"
                    value="">
                <br>
            </span>
<!--            <span class="col-sm-2">
                <script>
                    $(":file").filestyle({'iconName', 'glyphicon glyphicon-camera'});</script>
                <input name="message_attachment" 

                       title="Upload Image" type="file" 
                       class="filestyle" data-input="false" 
                       data-iconName="glyphicon glyphicon-camera" data-buttonText="" ><br>
            </span>-->
            <span class="col-sm-5 pull-right">
                <a class="pull-right" href="javascript:void(0)" style="padding-right: 25px;">   
                    <i  onclick="return submit();" class="fa fa-send fa-2x" title="Send Message">        
                    </i>
                </a>
            </span>


        </div>
        <div  id="file_error" style="color: red;" class="form-group  col-sm-12 text-left ">

        </div>
        <!--        </form>-->

        <div class="col-sm-12"><br><br></div>
    </div>

</div>
<script type="text/javascript">
    function Download(messageId,messageAttachid)
{
    //alert(messageAttachid);
    var xmlhttp = false;
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
            xmlhttp = new XMLHttpRequest();
        }
        var url= '<?php echo base_url();?>'+'download-authenticate';
        var message_id=messageId;
       // alert(message_id);
        
        var formdata = new FormData();
        formdata.append("message_id",message_id);
        formdata.append("message_attachmen_id",messageAttachid);
        
        xmlhttp.addEventListener("load", function () {
            //alert(xmlhttp.responseText);
            var downloadUrl= '<?php echo base_url();?>'+'action-download/'+message_id+'/'+messageAttachid; 
           if( xmlhttp.responseText == 'allow'){
               window.location.replace(downloadUrl);
           }
            else if(xmlhttp.responseText == 'f'){
               alert("Your file is not found or Empty file.");
           }                 

           else
           {
               alert("Download is canceled");
           }
              
            }, false);
            xmlhttp.addEventListener("error", function () {
                alert("not sent");
            }, false);
            xmlhttp.addEventListener("abort", function () {
                alert("Aborted");
            }, false);

            xmlhttp.open("POST", url);
            xmlhttp.send(formdata);

        
    return true;
}
    var submit_status = 0;
    function getEmailID()
    {
        var xmlhttp3 = false;
        try {
            xmlhttp3 = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp3 = false;
            }
        }
        if (!xmlhttp3 && typeof XMLHttpRequest != 'undefined') {
            xmlhttp3 = new XMLHttpRequest();
        }
        var email_address = documentID('to_address').value;
        var message_id = documentID('message_id').value;
        //  alert(message_id);
        if (email_address == "")
        {

        }
        else {
            //alert("hello");
            var emailUrl = '<?php echo base_url() . 'edit-email-draft-message' ?>';
            var formdata = new FormData();
            formdata.append("email_address", email_address);
            formdata.append("message_id", message_id);
            xmlhttp3.addEventListener("load", function () {
                if (xmlhttp3.responseText == "3")
                {
                    documentID("error_msg").innerHTML = "Please enter an email from your link";
                }

                //xmlhttp3.send(null);        
                // alert(xmlhttp3.responseText);
            }, false);

            xmlhttp3.addEventListener("error", function () {
                alert("not sent");
            }, false);
            xmlhttp3.addEventListener("abort", function () {
                alert("Aborted");
            }, false);

            xmlhttp3.open("POST", emailUrl);
            xmlhttp3.send(formdata);
        }
    }



    function reloadEmail() {

        setTimeout(function () {

            if (submit_status == 0) {
                getEmailID();
                reloadEmail();
            }
        }, 5000);



    }

    reloadEmail();

    // get messgaebody for draft
    function getmessagebodyName() {

        var xmlhttp1 = false;
        try {
            xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp1 = false;
            }
        }
        if (!xmlhttp1 && typeof XMLHttpRequest != 'undefined') {
            xmlhttp1 = new XMLHttpRequest();
        }
        var message_body = documentID('message_body').value

        var message_id;
        if (documentID('message_id').value == '') {
            message_id = '';
        } else {
            message_id = documentID('message_id').value;
        }
//       alert(inputBody);


        var uploadMessageUrl = '<?php echo base_url() . 'msg/send-message-body'; ?>';
        var formdata = new FormData();

        formdata.append("message_body", message_body);

        formdata.append("message_id", message_id);
        //alert(xmlhttp1.responseText);
        //formdata.append("message_body", message_body);
        xmlhttp1.addEventListener("load", function () {
            //alert(xmlhttp1.responseText);

            documentID('message_id').value = xmlhttp1.responseText;
            //  xmlhttp1.send(null);
        }, false);
        xmlhttp1.addEventListener("error", function () {
            alert("not message sent");
        }, false);
        xmlhttp1.addEventListener("abort", function () {
            alert("Aborted");
        }, false);

        xmlhttp1.open("POST", uploadMessageUrl);
        xmlhttp1.send(formdata);

    }
    var f = 0;

    function saveMessage() {

        if (f == 0) {
            reloadPage();
            f = 1;
        }
    }
    function reloadPage() {
        setTimeout(function () {
            if (submit_status == 0) {
                getmessagebodyName();
                reloadPage();
            }
        }, 5000);

    }


    //upload file and image video sender profile for draft
    var fileName = '';
    var allowedFileType = "avi webm mp4 3gp 3gpp flv swf gif jpeg jpg png zip rar txt rtf pdf epub azw3 cbr lit mobi docx  xlsx  pub pptx  one  doc  vsdx  accdb  xlsb  mso  rpmsg  asd  xls oft thmx  mdb  xlsm  mpp  obi  pst snp xsn olm  ost dotx vsd  laccdb accdr  wbk  pptm  dot  ppt xlam onepkg  xltx  mde docm pip ppsx ppsm accde  grv  xla  slk  potx  iaf xlt crtx  xlb  vss xar  xlw pps pa oab  dotm  mpd svd ops pot  xlm  mpt  acl  xltm mdt ade xl vst accdc mdw accdt  mat vdx xsf xll sldx mda  mar ppam accda ppa vsx puz prf maf vtx potm  xlc  wll  accdp";
    var file_attached = '';
    var total_size = 0;
    var Counter = 0;
    function getmessageFileName(inputFile)
    {
        var file = inputFile.files[0];
        fileName = file.name;

        documentID('message_files_name').value = fileName;
        var message_attachment_original_name = documentID('message_files_name').value;

        var message_id = documentID('message_id').value;

        var fileExtention = fileName.split('.').pop().toLowerCase();
        var n = allowedFileType.search(fileExtention);
        if (n > -1) {
            temp_size = total_size + Number(file.size);
            if (temp_size < 26214400) {

                uploaddocumentFile(inputFile, total_size);

                //documentID('upload_done').innerHTML = fileName;

                documentID('file_error').innerHTML = '';
                total_size = temp_size;
            } else {
                documentID('file_error').innerHTML = 'File size must less then 25 Mb';
                documentID('file_name').value = '';
                documentID('message_files').value = '';
            }
        }


        //upload image progress bar work
        function uploaddocumentFile(inputFile, total_size) {
            var xmlhttp2 = false;
            try {
                xmlhttp2 = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {

                try {
                    xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) {
                    xmlhttp2 = false;
                }
            }
            if (!xmlhttp2 && typeof XMLHttpRequest != 'undefined') {
                xmlhttp2 = new XMLHttpRequest();
            }
            var uploadAssignmentFileUrl = '<?php echo base_url(); ?>' + "msg/file-upload";


            var file = inputFile.files[0];



            file_attached = file;
            if (file) {

                var formdata = new FormData();
                formdata.append("message_files", file);
                formdata.append("message_id", message_id);
                formdata.append("total_size", total_size);
                formdata.append("message_attachment_original_name", message_attachment_original_name);



                xmlhttp2.upload.addEventListener("progress", function (event) {
                    documentID("prog").setAttribute('style', 'display:block');
                    documentID("prog").setAttribute('style', 'height:5px');
                    documentID("upload_done_all").setAttribute('style', 'display:block');
                    var cross_flag = documentID("cross_flag").value;
                    if (cross_flag == 1) {
                        var percent = (event.loaded / event.total) * 100;
                        documentID("progressBar").setAttribute('style', 'width:' + Math.round(percent) + '%');

                    }
                    else if (cross_flag == 0) {
                        xmlhttp2.abort();

                    }

                }, false);

                xmlhttp2.addEventListener("load", function () {
                    // alert(xmlhttp2.responseText);
                    if (xmlhttp2.responseText == "null") {
                        documentID('file_error').innerHTML = "Your file is empty.Please try another."
                    }
                    else {
                        var str = xmlhttp2.responseText;

                        var split_word = str.split(",");

                        documentID("message_id").value = split_word[0];
                        //alert(split_word[3]);
                        documentID("uploading_status").value = 1;
                        var parent = document.getElementById('upload_done_all');
                        var div1 = document.createElement('div');
                        div1.setAttribute('id', 'upload' + Counter);
                        parent.appendChild(div1);
                        var data1 = "<input type='hidden' name='hidden_uploaded_file_path' id='hidden_uploaded_file_path" + Counter + "' value=''><input type='hidden' name='message_attachmen_id' id='message_attachmen_id" + Counter + "' value=''>";

                        div1.innerHTML = data1 + split_word[3] + "  <a href='javascript:;' onclick='uploadCancel(" + Counter + "); '><i class='fa fa-times-circle ' id='cross'></i></a>";

                        documentID("message_attachmen_id" + Counter).value = split_word[1];
                        documentID("hidden_uploaded_file_path" + Counter).value = split_word[2];

                        Counter++;

                    }
                }, false);
                xmlhttp2.addEventListener("error", function () {
                    documentID("progressbar").innerHTML = "Upload Failed";
                }, false);
                xmlhttp2.addEventListener("abort", function () {
                    documentID("progressbar").innerHTML = "Upload Aborted";
                }, false);




                xmlhttp2.open("POST", uploadAssignmentFileUrl);
                xmlhttp2.send(formdata);


            }
        }


    }

    function uploadCancel(fileNumber) {

        var xmlhttp4 = false;
        try {
            xmlhttp4 = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp4 = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp4 = false;
            }
        }
        if (!xmlhttp4 && typeof XMLHttpRequest != 'undefined') {
            xmlhttp4 = new XMLHttpRequest();
        }

        var message_id = documentID('message_id').value;

        var hidden_uploaded_file_path = documentID('hidden_uploaded_file_path' + fileNumber).value;

        var message_attachmen_id = documentID('message_attachmen_id' + fileNumber).value;
        var uploading_status = documentID('uploading_status').value;
        //alert(message_attachmen_id);
        if (uploading_status == 1) {
            var url = '<?php echo base_url(); ?>' + 'cancel-download';
            //alert(message_id);
            //alert( hidden_uploaded_file_path); 

            var formdata = new FormData();
            formdata.append("hidden_uploaded_file_path", hidden_uploaded_file_path);
            formdata.append("message_id", message_id);
            formdata.append("message_attachmen_id", message_attachmen_id);
        }
        else {
            documentID('cross_flag').value = 0;
            documentID('uploading_status').value = 0;




        }

        xmlhttp4.addEventListener("load", function () {


            documentID('upload' + fileNumber).innerHTML = '';
            documentID("prog").setAttribute('style', 'display:none');
            documentID('cross_flag').value = 1;

        }, false);
        xmlhttp4.addEventListener("error", function () {
            alert("not upload");
        }, false);
        xmlhttp4.addEventListener("abort", function () {
            alert("Aborted");
        }, false);

        xmlhttp4.open("POST", url);
        xmlhttp4.send(formdata);

        return true;


    }
    function submit()
    {
        var xmlhttp = false;
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
            xmlhttp = new XMLHttpRequest();
        }

        var url = "msg/sent";

        var email_address = documentID('to_address').value;
        var message_id = documentID('message_id').value;

        //var message_attachment_original_name = documentID('message_files_name').value;



        var message_body = documentID('message_body').value;
        // var hidden_uploaded_file_path = documentID('hidden_uploaded_file_path').value;
        // alert(hidden_uploaded_file_path);
        if (message_body == "" || email_address == "")
        {
            if (email_address == "")
                documentID('error').innerHTML = "please enter an email address";
            else if (message_body == "")
            {
                documentID('error').innerHTML = "message body can not be empty";
            }
        } else {
            submit_status = 1;

            var formdata = new FormData();

            formdata.append("email_address", email_address);
            formdata.append("message_body", message_body);
            formdata.append("message_id", message_id);


            //formdata.append("hidden_uploaded_file_path", hidden_uploaded_file_path);

            // formdata.append("message_attachment_original_name", message_attachment_original_name);


            xmlhttp.addEventListener("load", function () {
                //alert(xmlhttp.responseText);


                if (xmlhttp.responseText == '2')
                {

                    documentID('error_msg').innerHTML = "Please Enter Email Address From Your Link";
//                  
                }

                else
                {



                    if (xmlhttp.responseText == '911') {
                        window.location = '<?php echo base_url(); ?>' + 'sent-message';

                    }


                }


            }, false);
            xmlhttp.addEventListener("error", function () {
                alert("not sent");
            }, false);
            xmlhttp.addEventListener("abort", function () {
                alert("Aborted");
            }, false);

            xmlhttp.open("POST", url);
            xmlhttp.send(formdata);

            return true;


        }
    }
    function  clear_error()
    {
        documentID('error').innerHTML = " ";
    }


</script>

