
<script>

    function documentID(arg) {
        return document.getElementById(arg);
    }
</script>

<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>Draft Message</strong><hr>
        </div>

        <div class="col-sm-12" style="color: green;">
            <strong>
                <span id="error_msg"></span>
            </strong>
        </div>





        <?php foreach ($edit_draft_message as $val) { ?>
            <?php
            $sent_email = array(false);
            if (isset($message_receiver_info)) {
                foreach ($message_receiver_info as $receiver) {
                    $sent_email[$receiver->person_email] = TRUE;
                }
            }
            
          
            ?>
            <input type="hidden" name="message_id" id="message_id" value="<?php echo $message_id; ?>">
           
            <input type="hidden" name="cross_flag" id="cross_flag" value="1">
            <input type="hidden" name="uploading_status" id="uploading_status" value="0">
       
            <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="blank_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"  name="message_body" oninput="saveMessage();" class="form-control   " rows="2"  cols="80" placeholder="Message Text Here ..." onkeyup="clear_error();"  style="max-width: 560px; max-height: 60px;"><?php if ($val->message_body) {
        echo $val->message_body;
    } ?></textarea>
                </div>
            </div>


            <!--        <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">
                <Span class="col-sm-10 pull-left">
                    
                        <?php
                        foreach ($edit_draft_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" id="existing_attachment<?php echo $attach->message_attachmen_id;?>">
                            <a href="javascript:;" onclick="DownloadSend('<?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>
                           <a href="javascript:;" onclick=" draft_existing_attachment_cancel('<?php echo $val->message_id;?>','<?php echo $attach->message_attachmen_id;?>', '<?php echo $attach->message_sender_attachment; ?>' );"><i class="fa fa-times-circle " id="cross"></i></a>
                        </p>
                        

                        
                        

                        <input 
                            name="message_files_name"   
                            id="message_files_name" 
                            type="hidden"
                            value="<?php echo $attach->message_attachment_original_name; ?>">
                        <?php } ?>

                </Span>
                <input name="message_files_name" id="message_files_name" type="hidden" value="">
<!--                <input type="hidden" id="hidden_uploaded_file_path" value="">        -->
               
            </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="">

                    <br>
                </span >
            <input type="hidden" name="upload_submit" id="upload_submit" value="0">

                <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>
        <?php } ?>
        <div  id="file_error" style="color: red;" class="form-group  col-sm-12 text-left ">

        </div>
         <div  id="file_error_submit" 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">

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;
       if (email_address == "")
        {

        }
        else {
        
            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";
                }

               
            }, 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 = documentID('message_id').value;

        var uploadMessageUrl = '<?php echo base_url() . 'edit-message-body-draft-message'; ?>';
        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);
//            email_address = '';
//            message_body = '';



            //documentID('form_view').innerHTML = '';
            //       documentID('message_id').value = xmlhttp1.responseText;
            //xmlhttp1.send(null);
        }, false);
        xmlhttp1.addEventListener("error", function () {
            alert("not 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);

    }


//get previous attachment id



    //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 = '';
            }
        }
  else{
                documentID('file_error').innerHTML = 'File type is not Matched. Please browse another file type.';
                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("upload_done_all").setAttribute('style', 'display:block');
                   var cross_flag= documentID("cross_flag").value;
                    if(cross_flag == 1){
                    var parent = document.getElementById("upload_done_all");
                    var div1 = document.createElement('div');
                    div1.setAttribute('id', 'prog' + Counter);
                    parent.appendChild(div1);
                     documentID("prog" + Counter).setAttribute('style', 'display:none');
                 
                    var data1 = "<div id='progressBar"+Counter+"' class='progress-bar progress-bar-success progress-bar-striped'  role='progressbar' aria-valuenow='40' aria-valuemin='0' aria-valuemax='100' style=''></div>";
                    div1.innerHTML = data1;
                     documentID("prog" + Counter).setAttribute('style', 'display:block');
                     documentID("prog" + Counter).setAttribute('style', 'height:5px ; width: 50%;');
                     
                    var percent = (event.loaded / event.total) * 100;
                    documentID("progressBar"+ Counter).setAttribute('style', 'width:' + Math.round(percent) + '%');
                     if (Math.round(percent) === 100) {
                             documentID('upload_submit').value=0;
                            documentID('message_files').removeAttribute("disabled");
                            documentID('file_error').innerHTML = "";
                            documentID('message_files').value = '';
                        }
                        else{
                             documentID('upload_submit').value=1;
                             documentID('message_files').setAttribute('disabled', '');
                             documentID('file_error').innerHTML = "For more upload please wait untill completing upload.";
                        }
                         }
                         else if(cross_flag == 0){
                             xmlhttp2.abort();
                              
                         }
                        
        }, false);

                xmlhttp2.addEventListener("load", function () {
                    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 DownloadSend(messageId, 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(); ?>' + 'send-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-send/' + 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;
    }
    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;
    if(uploading_status ==1){
        var url='<?php echo base_url(); ?>' +'cancel-download-draft';
           
            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"+fileNumber).setAttribute('style', 'display:none');    
            documentID('cross_flag').value = 1;
             documentID('message_files').value = '';
             
            }, 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 draft_existing_attachment_cancel(message_id,message_attachmen_id, hidden_uploaded_file){
    var xmlhttp5 = false;
        try {
            xmlhttp5 = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp5 = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp5 = false;
            }
        }
        if (!xmlhttp5 && typeof XMLHttpRequest != 'undefined') {
            xmlhttp5 = new XMLHttpRequest();
        }
        
         
        var hidden_uploaded_file_path= hidden_uploaded_file;
        var message_id= message_id;
        var message_attachmen_id_exist= message_attachmen_id;
    
       
       
        var url='<?php echo base_url(); ?>' +'existing-cancel-download-draft';
            
            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_exist",message_attachmen_id_exist);
        
        
        
        
        xmlhttp5.addEventListener("load", function () {
       documentID("existing_attachment"+message_attachmen_id_exist).setAttribute('style', 'display:none');   
           
             
            }, false);
            xmlhttp5.addEventListener("error", function () {
                alert("not sent");
            }, false);
            xmlhttp5.addEventListener("abort", function () {
                alert("Aborted");
            }, false);

            xmlhttp5.open("POST", url);
            xmlhttp5.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 SubmitVal= documentID('upload_submit').value;
         if(SubmitVal==0){
        var url = "msg/sent";

        var email_address = documentID('to_address').value;
        var message_id = documentID('message_id').value;
      
        var message_body = documentID('message_body').value;
        if (message_body == "" || email_address == "")
        {
            if (email_address == ""){
                documentID('blank_error').innerHTML = "please enter an email address";
            }else if (message_body == "")
            {
                documentID('blank_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);
            
            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 == '1') {
                        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);
            }
           


        }
         else if(SubmitVal==1){
        documentID('file_error_submit').innerHTML = "Wait untill completing the upload. ";
        }
         return true;
    }
    function  clear_error()
    {
        documentID('blank_error').innerHTML = " ";
    }


</script>