

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}





$(document).ready(function() {
    
    


    // $(".stop_enter").on("keypress", function (e) {
    //       if (e.keyCode == 13) {
    //         // alert("sa")
    //         // console.log($(this).attr('tabindex'));
    //         e.preventDefault();
    //         // $(this).closest('div').next().find('.stop_enter').first().focus();
    //         $.autotab.next();
    //         // e.which   = 9;
    //         // e.keyCode = 9;

    //         // $(this).trigger(e);

    //       }
    // });

    // $(".page-content").on("keyup",".bootstrap-select", function (e) {
    //       if (e.keyCode == 9 || e.which ==9) {
           
    //         // e.preventDefault();
    //         console.log($(this).find('ul li.active a').html())
         
    //         $(this).find('div.bs-searchbox input.form-control').val('');
            
    //         if($(this).find('ul li.active').attr('data-original-index') !="0"){
              
    //           $(this).find('ul li.selected a').trigger('click');
    //           $(this).find('ul li.active a').trigger('click');
              
    //           $(this).find('ul li.active').removeClass('active');
    //           $(this).find('ul li.selected').addClass('active');
              
    //         }
    //       }
    // })


    

    // $('.page-content').on('click',".bootstrap-select", function(e){

    //   if($(this).find('ul li.selected').length > 0){
    //     $('[tabindex=22]').focus();
    //   }
      
    // });

    // $("#purchase_item_body").on("keypress",".stop_enter", function (e) {
    //       if (e.keyCode == 13) {
    //         // console.log($(this).closest('div').next().find('.stop_enter').first().focus());
    //         e.preventDefault();
    //         // $(this).closest('div').next().find('.stop_enter').first().focus();
    //         $.autotab.next();
    //       }
    // });

    // $("#edited_purchase_contain").on("keypress",".stop_enter", function (e) {
    //   // alert(e.keyCode)
    //       if (e.keyCode == 13) {
    //         // console.log($(this).closest('div').next().find('.stop_enter').first().focus());
    //         e.preventDefault();
    //         // $(this).closest('div').next().find('.stop_enter').first().focus();
    //         $.autotab.next();
    //       }
    // });

});

 // Format Displaying Curreny for displaying only
  function currency_format_display(cash,cur='$'){
    // console.log(cash);
    if(isNaN(cash) || cash == null || cash==0 || cash==undefined){
      return "$ "+ 0;
    }else{
      //return cur +" "+ cash;
      
      var value = parseFloat(cash);
      var num =   value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + ' '+cur;
      return num;
      //return cur +" "+ value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }

  }


  function currency_format_display_no_space(cash,cur='$'){
    // console.log(cash);
    if(isNaN(cash) || cash == null || cash==0){
      return  0 + " $";
    }else{
      //return cur +" "+ cash;
      
      var value = parseFloat(cash);
      var num =   value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") +cur;
      return num;
      //return cur +" "+ value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }

  }


  function currency_format(cash,cur='$'){
    // console.log(cash);
    if(isNaN(cash) || cash == null || cash==0 || cash==undefined){
      return "$ "+ 0;
    }else{
      return cur +" "+ parseFloat(cash).toFixed(2);
      
     // var value = parseFloat(cash);
     // var num = '$ ' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
     // return num;
    }

  }


  function escape_notes(){
    $("span[data-popup='tooltip']").each(function(){
        var deco = $(this).attr('data-original-title');
        deco = decodeURIComponent(deco);
        $(this).attr('data-original-title',deco);
     }); 
  }

  function escapeHtml(unsafe) {
    
    if(unsafe == null || unsafe=='' || unsafe==undefined){
      return unsafe;
    }else{
      safe = unsafe.replace(/%/g, "&_25_;");
      safe = safe.replace(/\\/g, "&_5C_;");
      safe = safe.replace(/"/g, "&_quot_;");
      safe = safe.replace(/'/g, "&#_039_;");
      safe = safe.replace(/\n/g, "&#_013_;");
      //alert(safe)
      return safe;
    }

    
 }

 function decodeURIComponent_back(unsafe) {
    if(unsafe == null || unsafe=='' || unsafe==undefined){
      return unsafe;
    }else{
      safe = unsafe.replace(/&_25_;/g, "%");
      safe = safe.replace(/&_5C_;/g, "\\");
      safe = safe.replace(/&_quot_;/g, '"');
      safe = safe.replace(/&#_039_;/g, "'");
      safe = safe.replace(/&#_013_;/g, "\n");

      return safe;
    }
    
    // alert(safe)
    
 }

 Date.dateDiff = function(datepart, fromdate, todate) {
    datepart = datepart.toLowerCase();
    var diff = todate - fromdate;
    var divideBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     n:60000,
                     s:1000 };

    return Math.floor( diff/divideBy[datepart]);
  }


  function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return 'not';
  }

   // Chart setup
    function animatedDonut(element, size, CNC,Clean,Glue,Chek,PVC,Con) {

        // Add data set
        var data = [
            {
                "status": "CNC",
                "icon": "<i class='status-mark border-danger-300 position-left'></i>",
                "value": CNC,
                "color": "#ff0000"
            }, {
                "status": "Cleaning Wood",
                "icon": "<i class='status-mark bg-pink position-left'></i>",
                "value": Clean,
                "color": "#ff00ff"
            }, {
                "status": "Glue",
                "icon": "<i class='status-mark border-orange-300 position-left'></i>",
                "value": Glue,
                "color": "#ff8000"
            }, {
                "status": "Check Point",
                "icon": "<i class='status-mark border-success-300 position-left'></i>",
                "value": Chek,
                "color": "#00ff00"
            }, {
                "status": "PVC",
                "icon": "<i class='status-mark bg-yellow-300 position-left'></i>",
                "value": PVC,
                "color": "#FFFF00"
            }, {
                "status": "Control",
                "icon": "<i class='status-mark border-info-300 position-left'></i>",
                "value": Con,
                "color": "#00bfff"
            }
        ];

        // Main variables
        var d3Container = d3.select(element),
            distance = 2, // reserve 2px space for mouseover arc moving
            radius = (size/2) - distance,
            sum = d3.sum(data, function(d) { return d.value; });


        // Tooltip
        // ------------------------------

        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .direction('e')
            .html(function (d) {
                return "<ul class='list-unstyled mb-5'>" +
                    "<li>" + "<div class='text-size-base mb-5 mt-5'>" + d.data.icon + d.data.status + "</div>" + "</li>" +
                    "<li>" + "Total: &nbsp;" + "<span class='text-semibold pull-right'>" + d.value + "</span>" + "</li>" +
                    "<li>" + "Ratio: &nbsp;" + "<span class='text-semibold pull-right'>" + (100 / (sum / d.value)).toFixed(2) + "%" + "</span>" + "</li>" +
                "</ul>";
            });


        // Create chart
        // ------------------------------

        // Add svg element
        var container = d3Container.append("svg").call(tip);
        
        // Add SVG group
        var svg = container
            .attr("width", size)
            .attr("height", size)
            .append("g")
                .attr("transform", "translate(" + (size / 2) + "," + (size / 2) + ")");  


        // Construct chart layout
        // ------------------------------

        // Pie
        var pie = d3.layout.pie()
            .sort(null)
            .startAngle(Math.PI)
            .endAngle(3 * Math.PI)
            .value(function (d) { 
                return d.value;
            }); 

        // Arc
        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius / 1.5);


        //
        // Append chart elements
        //

        // Group chart elements
        var arcGroup = svg.selectAll(".d3-arc")
            .data(pie(data))
            .enter()
            .append("g") 
                .attr("class", "d3-arc")
                .style({
                    'stroke': '#fff',
                    'stroke-width': 2,
                    'cursor': 'pointer'
                });
        
        // Append path
        var arcPath = arcGroup
            .append("path")
            .style("fill", function (d) {
                return d.data.color;
            });

        // Add tooltip
        arcPath
            .on('mouseover', function (d, i) {

                // Transition on mouseover
                d3.select(this)
                .transition()
                    .duration(500)
                    .ease('elastic')
                    .attr('transform', function (d) {
                        d.midAngle = ((d.endAngle - d.startAngle) / 2) + d.startAngle;
                        var x = Math.sin(d.midAngle) * distance;
                        var y = -Math.cos(d.midAngle) * distance;
                        return 'translate(' + x + ',' + y + ')';
                    });
            })
            .on("mousemove", function (d) {
                
                // Show tooltip on mousemove
                tip.show(d)
                    .style("top", (d3.event.pageY - 40) + "px")
                    .style("left", (d3.event.pageX + 30) + "px");
            })
            .on('mouseout', function (d, i) {

                // Mouseout transition
                d3.select(this)
                .transition()
                    .duration(500)
                    .ease('bounce')
                    .attr('transform', 'translate(0,0)');

                // Hide tooltip
                tip.hide(d);
            });

        // Animate chart on load
        arcPath
            .transition()
                .delay(function(d, i) { return i * 500; })
                .duration(500)
                .attrTween("d", function(d) {
                    var interpolate = d3.interpolate(d.startAngle,d.endAngle);
                    return function(t) {
                        d.endAngle = interpolate(t);
                        return arc(d);  
                    }; 
                });


        //
        // Append counter
        //

        // Append text
        svg
            .append('text')
            .attr('text-anchor', 'middle')
            .attr('dy', 6)
            .style({
                'font-size': '17px',
                'font-weight': 500
            });

        // Animate text
        svg.select('text')
            .transition()
            .duration(1500)
            .tween("text", function(d) {
                var i = d3.interpolate(this.textContent, sum);
                return function(t) {
                    this.textContent = d3.format(",d")(Math.round(i(t)));
                };
            });
    }


   function Checks(id,types=null,min=null,max=null,badge=null){
        var name = $("#"+id).val();
        var placeholder = $("#"+id).attr('placeholder');
        if(types == null){  // it mean string

              if(min !=null && max !=null){
                  if(name =='' || name.length < min || name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة في الحقل لا تقل عن ")+ min + Translation(" ولا تزيد عن " + max),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name ==''  || name.length < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة في الحقل لا تقل عن ")+ min ,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name ==''  ||  name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة في الحقل لا تزيد عن ") + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name ==''){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("حقل ") + placeholder + Translation(" لا يجب ان يبقى فاغ"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }else if(types == 'No'){  // it mean numbers

              if(min !=null && max !=null){
                  if(name !='' && isNaN(name) || name < min || name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة عددية بين")+ min + Translation(" و ") + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null && badge !=null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).removeClass('badge-primary');
                    $("#"+id).addClass('badge-warning');

                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة عددية اكبر من ")+ min,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).removeClass('badge-warning');
                      $("#"+id).addClass('badge-primary');
                      return true;
                  }


                }else if(min !=null && max ==null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');
                    
                    noty({
                            width: 200,
                            text: Translation("الرجاء قم بادخال قيمة عددية اكبر او تساوي ")+ min + Translation(" في حقل ") + placeholder,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name !='' && isNaN(name) ||  name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء ادخال قيمة عددية اقل من ") + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name !='' && isNaN(name)){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: Translation("الرجاء ادخال قيمة عددية"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }
    }

$(function() {
  // tag input

  // Basic initialization
    $('.tokenfield').tokenfield();
  //
    // Teal
    //

    // Add class on init
    $('.tokenfield-teal').on('tokenfield:initialize', function (e) {
        $(this).parent().find('.token').addClass('bg-teal')
    });

    // Initialize plugin
    $('.tokenfield-teal').tokenfield();

    // Add class when token is created
    $('.tokenfield-teal').on('tokenfield:createdtoken', function (e) {
        $(e.relatedTarget).addClass('bg-teal')
    });

    // ========================================
    //
    // Tags input
    //
    // ========================================


    // Display values
    $('.tags-input, [data-role="tagsinput"], .tagsinput-max-tags, .tagsinput-custom-tag-class').on('change', function(event) {
        var $element = $(event.target),
            $container = $element.parent().parent('.content-group');

        if (!$element.data('tagsinput'))
        return;

        var val = $element.val();
        if (val === null)
        val = "null";
    
        $('pre.val > code', $container).html( ($.isArray(val) ? JSON.stringify(val) : "\"" + val.replace('"', '\\"') + "\"") );
        $('pre.items > code', $container).html(JSON.stringify($element.tagsinput('items')));
        Prism.highlightAll();
    }).trigger('change');



    // Basic examples
    // ------------------------------

    // Basic initialization
    $('.tags-input').tagsinput();


    // Allow dublicates
    $('.tags-input-dublicates').tagsinput({
        allowDuplicates: true
    });


    // Set maximum allowed tags
    $('.tagsinput-max-tags').tagsinput({
        maxTags: 5
    });


    // Custom tag class
    $('.tagsinput-custom-tag-class').tagsinput({
        tagClass: function(item){
            return 'label bg-success';
        }
    });

});