
var table ,  html_opt;

    // ===========================================
    // ===========================================
    //            Color Picker
    // ===========================================
    // ===========================================

    // Color palette
    var demoPalette = [
          ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
          ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
          ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
          ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
          ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
          ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
          ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
          ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
    ]

    // ===========================================
    // ===========================================
    //            Icon Picker
    // ===========================================
    // ===========================================

     var table_invoice     =`
                            <html>

                              <head>
                                  <meta http-equiv=Content-Type content="text/html; charset=unicode">
                                  <meta name=Generator content="Microsoft Word 15 (filtered)">
                                  <style>
                                      <!--
                                      /* Font Definitions */
                                      
                                      @font-face {
                                          font-family: "Cambria Math";
                                          panose-1: 2 4 5 3 5 4 6 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: Calibri;
                                          panose-1: 2 15 5 2 2 2 4 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Calibri Light";
                                          panose-1: 2 15 3 2 2 2 4 3 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Century Gothic";
                                          panose-1: 2 11 5 2 2 2 2 2 2 4;
                                      }
                                      
                                      @font-face {
                                          font-family: "Sakkal Majalla";
                                          panose-1: 2 0 0 0 0 0 0 0 0 0;
                                      }
                                      /* Style Definitions */
                                      
                                      p.MsoNormal,
                                      li.MsoNormal,
                                      div.MsoNormal {
                                          margin-top: 0in;
                                          margin-right: 0in;
                                          margin-bottom: 8.0pt;
                                          margin-left: 0in;
                                          line-height: 105%;
                                          font-size: 11.0pt;
                                          font-family: "Calibri", sans-serif;
                                      }
                                      
                                      h2 {
                                          mso-style-link: "Heading 2 Char";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          page-break-after: avoid;
                                          font-size: 8.0pt;
                                          font-family: "Calibri Light", sans-serif;
                                          color: #262626;
                                          font-weight: normal;
                                      }
                                      
                                      p.MsoHeader,
                                      li.MsoHeader,
                                      div.MsoHeader {
                                          mso-style-link: "Header Char";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          font-size: 8.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      a:link,
                                      span.MsoHyperlink {
                                          color: blue;
                                          text-decoration: underline;
                                      }
                                      
                                      a:visited,
                                      span.MsoHyperlinkFollowed {
                                          color: purple;
                                          text-decoration: underline;
                                      }
                                      
                                      span.Heading2Char {
                                          mso-style-name: "Heading 2 Char";
                                          mso-style-link: "Heading 2";
                                          font-family: "Calibri Light", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      p.msonormal0,
                                      li.msonormal0,
                                      div.msonormal0 {
                                          mso-style-name: msonormal;
                                          margin-right: 0in;
                                          margin-left: 0in;
                                          font-size: 12.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      span.HeaderChar {
                                          mso-style-name: "Header Char";
                                          mso-style-link: Header;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                      }
                                      
                                      p.msopapdefault,
                                      li.msopapdefault,
                                      div.msopapdefault {
                                          mso-style-name: msopapdefault;
                                          margin-right: 0in;
                                          margin-bottom: 8.0pt;
                                          margin-left: 0in;
                                          line-height: 105%;
                                          font-size: 12.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      p.msochpdefault,
                                      li.msochpdefault,
                                      div.msochpdefault {
                                          mso-style-name: msochpdefault;
                                          margin-right: 0in;
                                          margin-left: 0in;
                                          font-size: 10.0pt;
                                          font-family: "Times New Roman", serif;
                                      }
                                      
                                      p.Slogan,
                                      li.Slogan,
                                      div.Slogan {
                                          mso-style-name: Slogan;
                                          margin-top: 0in;
                                          margin-right: 0in;
                                          margin-bottom: 3.0pt;
                                          margin-left: 0in;
                                          font-size: 7.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #A6A6A6;
                                          letter-spacing: .2pt;
                                          font-style: italic;
                                      }
                                      
                                      p.ContactInfo,
                                      li.ContactInfo,
                                      div.ContactInfo {
                                          mso-style-name: "Contact Info";
                                          margin-top: 26.0pt;
                                          margin-right: 0in;
                                          margin-bottom: 0in;
                                          margin-left: 0in;
                                          margin-bottom: .0001pt;
                                          text-align: center;
                                          font-size: 8.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #A6A6A6;
                                      }
                                      
                                      p.ThankYou,
                                      li.ThankYou,
                                      div.ThankYou {
                                          mso-style-name: "Thank You";
                                          margin: 0in;
                                          margin-bottom: .0001pt;
                                          text-align: center;
                                          font-size: 9.0pt;
                                          font-family: "Calibri", sans-serif;
                                          color: #262626;
                                          font-weight: bold;
                                          font-style: italic;
                                      }
                                      
                                      span.companyphones {
                                          mso-style-name: company_phones;
                                      }
                                      
                                      span.companyemail {
                                          mso-style-name: company_email;
                                      }
                                      
                                      span.invoiceno {
                                          mso-style-name: invoice_no;
                                      }
                                      
                                      span.invoicedate {
                                          mso-style-name: invoice_date;
                                      }
                                      
                                      span.deliverystatus {
                                          mso-style-name: delivery_status;
                                      }
                                      
                                      span.destination {
                                          mso-style-name: destination;
                                      }
                                      
                                      .MsoChpDefault {
                                          font-size: 10.0pt;
                                      }
                                      
                                      @page WordSection1 {
                                          size: 841.9pt 595.3pt;
                                          margin: .5in .5in .5in .5in;
                                      }
                                      
                                      div.WordSection1 {
                                          page: WordSection1;
                                      }
                                      
                                      -->
                                  </style>

                              </head>

                              <body lang=EN-US link=blue vlink=purple>

                                  <div class=WordSection1>

                                      <div align=center>
                              `;


    
    function edit_items(itemid){
      
      $("#edit_objid").val(itemid);

      $.ajax({
                url: "models/crul_color.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"get_edit","itm_id":itemid} ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Category");
                },
                success: function(res) {

                  if(res.is_success == true){
                     $("#edit_status_color").val(res.data[0][1]);
                     $("#edit_status_name").val(res.data[0][2]);

                      $(".colorpicker").spectrum({
                        showPalette: true,
                        palette: demoPalette,
                        showInput: true,
                        showAlpha: true,
                        allowEmpty: true,
                        
                      }); 

                     $('#edit_form_cont').modal('toggle');
                  }else{
                    swal({
                            title: "Cancelled",
                            text: Translation(res.data),
                            confirmButtonColor: "#2196F3",
                            type: "error"
                        });
                  }
                }
      });
     
      
    }

    function delete_items(itemid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box
        swal({
            title: Translation("هل انت متأكد؟!"),
            text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: Translation("موافق: امسح!"),
            cancelButtonText: Translation("الغاء الامر"),
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_status.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Category");
                },
                success: function(res) {

                  if(res.is_success == true){
                    swal({
                            title: Translation("حذف!"),
                            text: Translation("لقد تم حذف الفئة بنجاح"),
                            confirmButtonColor: "#66BB6A",
                            type: "success"
                        });
                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  }else{
                    swal({
                            title: "Cancelled",
                            text: Translation(res.data),
                            confirmButtonColor: "#2196F3",
                            type: "error"
                        });
                  }
                }
            });
            }
        }); // /confirm
    }

    function get_color(){

      $.ajax({
          url: "models/crul_status.php",
          type:"POST",
          dataType : "JSON",
          data: {"type":"get"},
          complete:function(){
            
          },
          beforeSend:function(){
            
          },
          success: function(res) {

            if(res.is_success == true){
               
                       
              html_opt   = `<option value="0">اختر من القائمة لتغيير حالة المادة</option>`;
              for (var i = 0; i < res.data.length; i++) {
                html_opt += `<option data-icon='class="label label-block" style="background-color:${res.data[i].status_color}; width:55px; height:25px; border:1px solid black;' value='${res.data[i].color_status_id}' >${res.data[i].status_name}</option>`;
              }
                

              $('#color_id_fk').html(html_opt);             
              $('#color_status_id_fk').html(html_opt);             

              $('#color_status_id_fk').selectpicker('refresh');
                
                

            }else{

              swal({
                      title: Translation("خطأ"),
                      text: Translation(res.data),
                      confirmButtonColor: "#2196F3",
                      type: "error"
                  });

            }
            
          }
      });

    }

    function print_product(){
      $("#print_modal").modal('toggle');
    }

    function show_invoice(itm,printing=null,detail_show=null){

          
          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";

       
          var today = new Date();
          var dd    = today.getDate();
          var mm    = today.getMonth()+1; //January is 0!
          var yyyy  = today.getFullYear();

          if(dd<10) {
              dd = '0'+dd
          } 

          if(mm<10) {
              mm = '0'+mm
          } 

          today = yyyy + '/' + mm + '/' + dd;


          $.ajax({
                url : 'models/crul_status.php',
                type : 'POST',
                data : {type:'print', color_id : itm},
                dataType : 'json',
                success : function(response) {
                    // console.log(response)
                    
                        headers =`
                                  <table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0 width="92%" style='width:92.0%;border-collapse:collapse'>
                                      <tr style='height:.25in'>
                                          <td  nowrap  style='width:33.44%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 5.4pt 0in 5.4pt;height:.25in'>
                                              <p class=Slogan style='line-height:105%'><span style='font-family:"Century Gothic",sans-serif'>
                                              <img   width=86 height=77 src="`+COMPANY_LOGO+`"></span></p>
                                          </td>
                                          <td  colspan=3 style='width:59.32%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 0in 0in 0in;height:.25in'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                                <span style='font-size:36.0pt;  font-family:"Century Gothic",sans-serif;color:#A6A6A6'>        
                                                </span>
                                                <span style='font-size:36.0pt;font-family:"Century Gothic",sans-serif;color:#A8D08D'> </span>
                                                <span style='font-size:36.0pt;font-family:"Century Gothic",sans-serif;color:#FFC000'>
                                                `+Translation('PRODUCT STATUS')+`
                                                </span></p>
                                          </td>
                                          <td width="7%" nowrap style='width:7.24%;border:none;border-bottom:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:.25in'>
                                              <p class=MsoNormal dir=RTL style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:right;direction:rtl;unicode-bidi:embed'>
                                                <span dir=LTR><img width=31 height=62 src="image/sys/image005.gif"></span></p>
                                          </td>
                                      </tr>
                                      <tr style='height:25.15pt' align="center">
                                          <td width="23%" nowrap  style='width:23.78%;border:solid windowtext 1.0pt;   border-top:none;padding:0in 5.4pt 0in 5.4pt;height:25.15pt'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;   text-align:center'>
                                                <b><span style='font-size:12.0pt;line-height:105%'>
                                                `+Translation('List No.')+`
                                                </span> 
                                              </b>
                                              </p>
                                          </td>
                                          
                                          <td width="11%" colspan=3 style='width:11.66%;border-top:none;border-left:   none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;   padding:0in 0in 0in 0in;height:25.15pt'>
                                              
                                          </td>
                                          
                                          <td width="21%" nowrap  style='width:21.94%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;   padding:0in 5.4pt 0in 5.4pt;height:25.15pt'>
                                              <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;   text-align:center;line-height:normal'>
                                                <b><span style='font-size:12.0pt'>
                                                `+Translation('Date')+`
                                                </span> </b>
                                              </p>
                                          </td>
                                      </tr>
                                      <tr style='height:26.95pt' align="center">
                                          <td width="23%" nowrap  style='width:23.78%;border:solid windowtext 1.0pt;   border-top:none;padding:0in 5.4pt 0in 5.4pt;height:26.95pt'>
                                           <input type="text" value="1" style="text-align:center; border: hidden;">
                                          </td>
                                          
                                          <td width="11%" colspan=3 style='width:11.66%;border-top:none;border-left:   solid windowtext 1.0pt;border-bottom:solid windowtext 1.0pt;border-right:  none;padding:0in 0in 0in 0in;height:26.95pt'>
                                              
                                          </td>
                                          
                                          <td width="21%" nowrap  style='width:21.94%;border-top:none;   border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:26.95pt'>
                                              `+today+`
                                          </td>
                                      </tr>`;
                        
                        

                      customer_details = ``;

                      attach =  `

                                    <tr style='height:26.0pt'>
                                        <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt; border-top:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('#')+`</span>
                                              </b>
                                            </p>
                                        </td>
                                        <td width="37%" nowrap  style='width:37.14%;border-top:none;  border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('كود اربيل')+`</span> </b></p>
                                        </td>
                                        <td width="7%" nowrap  style='width:7.52%;border:solid windowtext 1.0pt;  border-left:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('كود تركيا')+`</span></b>
                                            </p>
                                        </td>
                                        <td width="9%" nowrap  style='width:9.24%;border:solid windowtext 1.0pt;  border-left:none;padding:0in 5.4pt 0in 5.4pt;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b><span style='color:black'>`+Translation('الحالة')+`</span></b>
                                            </p>
                                        </td>
                                        <td width="6%" style='width:6.32%;border:solid windowtext 1.0pt;border-left: none;padding:0in 0in 0in 0in;height:26.0pt'>
                                            <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                              <b>`+Translation('اللون')+`</b>
                                            </p>
                                        </td>
                                       
                                    </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){                        

                        
                          attach = attach + ` 

                                              <tr style='height:15.0pt' align="center">
                                                  <td width="7%" nowrap style='width:7.28%;border:solid windowtext 1.0pt;  border-top:none;padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                        `+response.invoice[i].product_id+`
                                                      </p>
                                                  </td>
                                                  <td width="37%" align="left" nowrap style='width:37.14%;border:none;border-bottom:  solid windowtext 1.0pt;padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal style='font-weight:bold; margin-bottom:0in;margin-bottom:.0001pt;line-height:  normal'>
                                                        <span style='font-size:10.0pt;font-family:"Times New Roman",serif'>
                                                        `+response.invoice[i].erbil_code+`
                                                        </span>
                                                      </p>
                                                     
                                                      

                                                      
                                                  </td>
                                                  <td width="7%"  style='width:7.52%;border-top:none;border-left:solid windowtext 1.0pt; border-bottom:solid windowtext 1.0pt;border-right:solid black 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center;line-height:normal'>
                                                        <b>
                                                        <span style='color:black'>
                                                        `+response.invoice[i].turkish_code+`
                                                        </span></b>
                                                      </p>
                                                  </td>
                                                  <td width="9%" nowrap  style='width:9.24%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid gray 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      
                                                        `+response.invoice[i].status_name+`
                                                      
                                                  </td>

                                                  <td width="9%" nowrap  style='background-color:${response.invoice[i].status_color};width:9.24%;border-top:none; border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid gray 1.0pt;  padding:0in 5.4pt 0in 5.4pt;height:15.0pt'>
                                                      
                                                      
                                                  </td>
                                                 
                                                  
                                              </tr>`;
                        
                        
                       
                      } // for i

                      if(printing != null){
                        print_attach = `
                                        <script>
                                          window.print();
                                          window.onload = function() { window.print(); }
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }

                      footers =`

                                <tr style='height:6.0pt'>
                                    <td width="100%" colspan=5 valign=top style='width:100.0%;padding:0in 5.4pt 0in 5.4pt;  height:6.0pt'>
                                        <p class=ThankYou style='line-height:105%'>
                                        `+Translation('Thank you for your business!')+`
                                        </p>
                                    </td>
                                </tr>
                               
                                <tr style='height:.25in'>
                                    <td width="42%" nowrap colspan=2 style='width:42.02%;padding:0in 5.4pt 0in 5.4pt;  height:.25in'>
                                        <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center'>
                                        `+COMPANY_PHONE+`
                                        </p>
                                    </td>
                                  
                                    <td width="41%" nowrap colspan=3 style='width:41.86%;padding:0in 5.4pt 0in 5.4pt;  height:.25in'>
                                        <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;  text-align:center'>
                                        <span style='color:black'>`+COMPANY_EMAIL+`</span></p>
                                    </td>
                                </tr>
                               
                               
                            </table>

                        </div>

                    </div>

                </body>



                  
                     `+print_attach+`
                    </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                       HTML_VIEW = table_invoice + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                        window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }

    function get_products(){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_product_sell'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('اﺧﺘﻴﺎﺭ اﻟﻤﺎﺩﺓ')+'</option>';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          var tp =response[i][2];
                          var BC =response[i][4];
                          attach = attach + '<option  data-subtext="'+Translation('اﻟﺮﻣﺰ اﻻﺟﻨﺒﻲ : ')+tp+' || '+Translation('الرمز التسلسلي : ')+BC+'" value="'+response[i][0]+'" data-forgin-code="'+response[i][2]+'" data-item_type_id="'+response[i][3]+'">'+response[i][1]+'</option>';
                        }
                        $("#product_id").html(attach);
                        $("#product_id_fk\\[\\]").html(attach);
                        $('#product_id_fk\\[\\]').selectpicker('refresh');


                     
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }


$(document).ready(function() {

    get_color();
    get_products()

    $("#product_div").on('click','#add_btn', function(){
        $("#product_div").append(`<div class="form-group">
                        <div class="col-sm-8">
                          <div class="input-group">
                            <label class="input-group-addon multi_lang">Product</label>
                            <select id="product_id_fk[]" name="product_id_fk[]" class="bootstrap-select1" data-live-search="true"  data-width="100%">
                              ${$("#product_id").html()}
                            </select>

                            <button type="button" id="add_btn" class="btn btn-primary btn-labeled btn-labeled-left ">
                              <i  class="icon-add"></i>
                            </button>
                          </div>
                        </div>

                      </div>`);

        $('#product_id_fk\\[\\]').selectpicker('refresh');


    })

    $('body').on('change','.bootstrap-select', function(e){
      console.log(this.id)
      

      if (this.id !='') {
        
        var id = this.id;
        var spt = id.split('_');

        var product_id  = spt[1];
        var color_id    = $(this).val();

        $.ajax({
                url: "models/crul_status.php",
                type:"POST",
                dataType : "JSON",
                data: { "type":"save",
                        product_id:product_id,
                        color_id : color_id
                        } ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Category");
                },
                success: function(res) {

                  if(res.is_success == true){

                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      $('.bootstrap-select').selectpicker('refresh');

                      noty({
                                      width: 200,
                                      text: Translation(res.data),
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                   
                      $(".colorpicker").spectrum({
                        showPalette: true,
                        palette: demoPalette,
                        showInput: true,
                        showAlpha: true,
                        allowEmpty: true,
                        
                      }); 

                  }else{
                    swal({
                            title: "Cancelled",
                            text: Translation(res.data),
                            confirmButtonColor: "#2196F3",
                            type: "error"
                        });
                  }
                }
      });

      }
    })
  
    $('#add_form').submit(function(event) {
      event.preventDefault();
           

          
      var fd=new FormData(this);
          
      fd.append("type",'create');
           
      $("#submit_add_btn").attr('disabled',true);

      $.ajax({
          url: "models/crul_status.php",
          type:"POST",
          dataType: "JSON",
          data: fd,
          processData: false,
          contentType: false
      
      })
      .done(function(res) {
         
          if(res.is_success == true){

            $("#add_form")[0].reset();
            $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

            noty({
                  width: 200,
                  text: Translation(res.data),
                  type: 'success',
                  dismissQueue: true,
                  timeout: 2000,
                  layout: 'topRight',
                  callback: {
                              onClose: function() {location.reload();},
                              },
            });

         
          }else{
              swal({
                  title: Translation("خطأ"),
                  text: Translation(res.data),
                  confirmButtonColor: "#66BB6A",
                  type: "warning"
              });
          }

          $("#submit_add_btn").attr('disabled',false);
      })
      .fail(function(err) {
          $("#submit_add_btn").attr('disabled',false);

           swal({
              title: Translation("خطأ"),
              text: (err),
              confirmButtonColor: "#66BB6A",
              type: "error"
          });
          $("#submit_add_btn").attr('disabled',false);
      })
      .always(function() {
          console.log("complete");
          $("#submit_add_btn").attr('disabled',false);

      });
      
    });


     // submit editable Visa Application form
    $('#edit_form').submit(function(event) {
            event.preventDefault();
           

            var catId       = $("#edit_objid").val();

            var status_color   = $("#edit_status_color").val();
            var status_name    = $("#edit_status_name").val();

            var Check1 = true;
            var Check2 = true;

          

            if(Check1 && Check2 ){
                $.ajax({
                    url: "models/crul_color.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {status_color:status_color,
                            status_name:status_name,
                            obj_id:catId,
                            type:'update'},
                    complete:function(){
                      //hideLoader();
                    },
                    beforeSend:function(){
                      //showLoader("Updating Category");
                    },
                    success: function(res) {
                      if(res.is_success == false){
                          $("#edit-form-cont").collapse('hide');
                          $('#edit_form_cont').modal('toggle');
                          $("#edit_form")[0].reset();
                          swal({
                              title:Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                      
                      }else{

                          $("#edit_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#edit_form_cont').modal('toggle');
                          noty({
                                  width: 200,
                                  text: Translation(res.data), //'Product Successfully Update',
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                                });
                      }
                    }
                });
              }
    });

    $('#print_form').on('submit', function(e){
        e.preventDefault();

        var name        = $("#color_id_fk").val();

       
        
        
        show_invoice(name)


    });

    
    

});






$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    

    $(".colorpicker").spectrum({
        // flat: true,
        showPalette: true,
        // showPaletteOnly: true,
        palette: demoPalette,
        showInput: true,
        showAlpha: true,
        allowEmpty: true,

        // togglePaletteOnly: true,
        // togglePaletteMoreText: 'More',
        //   togglePaletteLessText: 'Less',
        //   palette: demoPalette
    }); 


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 4 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });

    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    

   
   var table = $('.datatable-column-search-inputs').DataTable({
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_status.php",
        "data": function(d){
          d.type = "load";
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });
                  $('.bootstrap-select').selectpicker('refresh');
            },
        "columnDefs": [
          {
              "targets": 5,
              "data": null,
              "render": function (data,type,row) {

                      return  `<ul class='icons-list pull-right'>
                                      
                                        <li class='text-primary-600'>
                                            <select id="color_${row[0]}" name="color_${row[0]}" class="bootstrap-select" data-live-search="true"  data-width="100%">
                                            ${html_opt}
                                            </select>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash'></i>
                                            </a>
                                        </li>

                                    </ul>

                                    `;

                      $('.bootstrap-select').selectpicker('refresh');

                  }
          },

          {
             "render": function(data, type, row){


                      return  `<span class="label label-block" data-popup='tooltip' data-original-title='${data}' style="background-color:${data}; width:55px; height:25px; border:1px solid black;"> </span>`;


             },
             "targets": 4
          },

         
            
           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            $('.bootstrap-select').selectpicker('refresh');

            if(   aData[4] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }
        },
        "order": [[1,'asc']],
                "displayLength": 25,
 

        initComplete: function () {

            $('.bootstrap-select').selectpicker('refresh');

         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-primary"
                                      id="add_Item_Btn">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+Translation(CURRENT_BTN)+`
                                    </a>`);  

          $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                          <button id="print_product" type="button"
                          class="btn bg-purple-400 btn-labeled " onclick="print_product();"><b><i class="icon-printer2">
                          </i></b> <span id="inv_filter">`+Translation('طباعة المواد')+`</span> </button>
                          
                      </div>`);


            this.api().columns().every( function() {
                var column = this;
                

            });
        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });

        $('.bootstrap-select').selectpicker('refresh');
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



