function isTextEmpty(input) {

    if ($(input).val().length == 1 || $(input).val().length == 0) {
        return true;
    }

}

function getXMLHttpRequest() {
    var xmlhttp = false;

    if (window.ActiveXObject) {
        try {
            var versionIds = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
                "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0",
                "Msxml2.XMLHTTP.2.6", "Microsoft.XMLHTTP.1.0",
                "Microsoft.XMLHTTP.1", "Microsoft.XMLHTTP"
            ];
            for (var i = 0; i < versionIds.length && xmlhttp == false; i++) {
                xmlhttp = CreateXmlHttp(versionIds[i]);
            }
        } catch (e) {}
    } else if (window.XMLHttpRequest) {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    return xmlhttp;
}

function _AutoCompleteData(e, tagid, _code, _desc, tablename, pointto1, pointto2) {
    var input = document.getElementById(tagid);
    var _code = document.getElementById(_code);
    var _desc = document.getElementById(_desc);

    var _pointto1 = document.getElementById(pointto1);
    var _pointto2 = document.getElementById(pointto2);

    if (!e) {
        var e = window.Events;
    }
    var intKey = (window.Events) ? e.which : e.keyCode;

    var fieldtag = document.getElementById(tagid).getAttribute("tag"); // primary key or description
    var otherterm;

    if (fieldtag == 'primarykey') {
        otherterm = $(_desc).val();

    }
    if (fieldtag == 'description') {
        otherterm = $(_code).val();
    }

    if ((intKey == 38) || (intKey == 40) || (intKey == 37) || (intKey == 39) || (intKey == 17) || (intKey == 16)) return false;
	
	 

    $(input).autocomplete({
        //   source: "report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" +fieldtag+ "&" +"tablename="+tablename +'&otherterm=' +otherterm,
        source: "report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" + fieldtag + "&" + "tablename=" + tablename,
        minLength: 1,
        selectFirst: false,
        select: function(e, ui) {
            if (ui.item) {
                if (_code) $(_code).val(ui.item.id);
                if (_desc) $(_desc).val(ui.item.name);

                if (typeof(pointto1) != "undefined") $(_pointto1).val(ui.item.id);
                if (typeof(pointto2) != "undefined") $(_pointto2).val(ui.item.name);

                $(tagid).trigger("change");

            }
        },
        change: function(e, ui) {
            if (ui.item) {
                if (_code) $(_code).val(ui.item.id);
                if (_desc) $(_desc).val(ui.item.name);

                if (typeof(pointto1) != "undefined") $(_pointto1).val(ui.item.id);
                if (typeof(pointto2) != "undefined") $(_pointto2).val(ui.item.name);
            }
        },
        focus: function(e, ui) {
            if (ui.item) {
                if (_code) $(_code).val(ui.item.id);
                if (_desc) $(_desc).val(ui.item.name);

                if (typeof(pointto1) != "undefined") $(_pointto1).val(ui.item.id);
                if (typeof(pointto2) != "undefined") $(_pointto2).val(ui.item.name);

                $(tagid).trigger("change");

            }
        }

    });

}

function _Check_EnterPressed(_e, _myid, _second_id, _tag, _tablename, pointto1, pointto2, _btn) {
 
    var w = 868;
    var h = 601;
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    //***************************************************************************************************
    // MATH .RANDOM IS USED TO ALWAYS HAVE A UNIQUE FORM NAME CZ BROWSER WON'T OPEN 2 INSTANCE OF SAME FORM.
    var formname = 'window_' + Math.floor(Math.random() * (55555 - 1 + 1) + 1) + "";
    var formparams = 'width=' + w + ',height=' + h + ' ,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes , top=' + top + ', left=' + left;
    var urltoopen;
    urltoopen = '';
    urltoopen = urltoopen + 'report/form_report.php?';
    /* table name */
    urltoopen = urltoopen + 'tablename=' + _tablename + '&';

    if (_tag == 'primarykey') {
        urltoopen = urltoopen + 'fieldtag=' + 'primarykey' + '&';
    } else {
        urltoopen = urltoopen + 'fieldtag=' + 'description' + '&';
    }

    var _value = document.getElementById(_myid);
    var _valueOther = document.getElementById(_second_id);

    urltoopen = urltoopen + 'term=' + encodeURIComponent($(_value).val()) + '&';
    urltoopen = urltoopen + 'otherterm=' + encodeURIComponent($(_valueOther).val()) + '&';
    urltoopen = urltoopen + 'txtid=' + _myid + '&';
    urltoopen = urltoopen + 'fill=' + _second_id + '&';
    urltoopen = urltoopen + 'pointto1=' + pointto1 + '&';
    urltoopen = urltoopen + 'pointto2=' + pointto2 + '';

    //***************************************************************************************************

    var intKey = (window.Event) ? _e.which : _e.keyCode;

    var _me = document.getElementById(_myid);
    var _second = document.getElementById(_second_id);

    if (intKey == 8 || intKey == 46) // BACKSPACE   OR       DELETE KEY
    {
        if (isTextEmpty($(_me))) {

            $(_me).val('');
            $(_second).val('');
        }
    }

    if (intKey == 13 || _btn == 'btn') {
  
        x = document.form1;
        //************
        var myid = document.getElementById(_myid);
        var secondid = document.getElementById(_second_id);
        //************

        var xmlhttp = getXMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //var data = xmlhttp.responseText.split("[BRK]");
                var data = xmlhttp.responseText + '';

                //   alert(data);
                var count = data.split('"value"').length - 1;

                ///////////////////////////////////////////////for onblur	  alert(count);
                //  alert(count);
                /*
                Split Json in javascript  and loop over json
                https://stackoverflow.com/questions/733314/jquery-loop-over-json-result-from-ajax-success*/
                if (count > 0) {
					 
                    var inputP = document.getElementById(_myid);
                    var inputdesc = document.getElementById(_second_id);

                    var pnt_to1 = document.getElementById(pointto1);
                    var pnt_to2 = document.getElementById(pointto2);

                    var found = false;

                    data = $.parseJSON(data);
                    $.each(data, function(_items) {
                        //  console.log (_items);
                        //   console.log (data[_items]);
                        //  alert(data[_items].id);
                        if (_tag == 'primarykey') {
                            var result = data[_items].id + '';

                            if ($(inputP).val() + '' == result && result != "") {

                                // alert(found);		
                                if (!found) {

                                    $(inputdesc).val(data[_items].name);

                                    $(pnt_to1).val(data[_items].id);
                                    $(pnt_to2).val(data[_items].name);
                                    found = true;

                                }

                            }

                        } else if (_tag == 'description') {
                            var result = data[_items].name + '';

                            if ($(inputP).val().toUpperCase().trim() == result.toUpperCase().trim() && result != "")
                            //	//	//	//	    //  && (xmlhttp.responseText.split('"'+ $(inputP).val()  + '"').length-1==1) )
                            {
                                if (!found) {
                                    $(inputP).val(data[_items].name);
                                    $(inputdesc).val(data[_items].id);

                                    $(pnt_to1).val(data[_items].id);
                                    $(pnt_to2).val(data[_items].name);
                                    found = true;

                                }

                            }
                        }

                    });

				 
                    if (!found || _btn == 'btn') {
                        var input = document.getElementById(_myid);
                        if ($(inputP).val() != "" || _btn == 'btn')
                            window.open(urltoopen + '', formname, formparams);
                    } else {
                        //var _value  = document.getElementById(_myid);
                        //$(_value).val('s');
                        $('.ui-autocomplete').css("display", "none");

                    }

                } else {

                    if ($(_me).val().length != 0 || _btn == 'btn') {
                        var input = document.getElementById(_myid);
                        if ($(inputP).val() != "" || _btn == 'btn')
                            window.open(urltoopen + '', formname, formparams);
                    }

                }

            }
        }
        var secondid = document.getElementById(_second_id);

        if (_tag == 'primarykey')

        {
            xmlhttp.open("GET", "report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" + _tag + "&" + "tablename=" + _tablename + "&term=" + encodeURIComponent($(myid).val()));
        } else

        {
            xmlhttp.open("GET", "report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" + _tag + "&" + "tablename=" + _tablename + "&term=" + encodeURIComponent($(myid).val()) + '&otherterm=' + encodeURIComponent($(secondid).val()));
        }

        xmlhttp.send();

    }

    $('#custom_error').remove();

}

function _CHECKISVALID(_e, _myid, _second_id, _tag, _tablename, pointto1, pointto2, _btn) {

    var _flag = 0;
    var xmlhttp = getXMLHttpRequest();
    var myid = document.getElementById(_myid);

    if ($(myid).val() == '') {
        return true;
    }

    var secondid = document.getElementById(_second_id);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var data = xmlhttp.responseText + '';

            var count = data.split('"value"').length - 1;

            // alert(count);

            if ((count >= 1 || $(myid).val().length == 0) && _tag == 'primarykey') {

                // var resultprimary = '';

                var resultprimary = new Array();

                // test

                if (parseInt(count) > 0)

                {
                    data = $.parseJSON(data);
                    $.each(data, function(_items) {
                        //  console.log (_items);
                        //   console.log (data[_items]);
                        //  alert(data[_items].id);

                        //  resultprimary = data[_items].id + '';

                        var _canadd = true;

                        if (resultprimary.length > 0) {
                            for (i = 0; i < resultprimary.length; i++) {

                                if ((data[_items].id.indexOf(resultprimary[i]) >= 0) || (resultprimary[i].indexOf(data[_items].id) >= 0))
                                //  if(resultprimary[i].indexOf(data[_items].id) >=0)
                                {
                                    _canadd = true;
                                } else {
                                    _canadd = false;
                                }

                            }
                        }

                        if (_canadd == true)
                            resultprimary.push(data[_items].id + '');

                    });
                }

                //test				

                if (_tag == 'primarykey' && resultprimary.length == count)

                {

                    var found1 = false;
                    $.each(data, function(_items) {

                        // alert((data[_items].name + '').toLowerCase());
                        // alert($(myid).val().toLowerCase());

                        if ((data[_items].id + '').toLowerCase().trim() == $(myid).val().toLowerCase().trim())

                        {
                            found1 = true;
                        }

                    });

                    if (found1 == true) {
                        _flag = 0;
                        $('#custom_error').remove();
                        return true;
                    } else {
                        _flag = 1;
                    }

                } else {
                    _flag = 1;
                }

            } else {
                _flag = 1;
            }

            if ((count >= 1 || $(myid).val().length == 0) && _tag == 'description') {

                var resultdescription = new Array();

                // test

                if (parseInt(count) > 0)

                {
                    data = $.parseJSON(data);
                    $.each(data, function(_items) {
                        //  console.log (_items);
                        //   console.log (data[_items]);
                        //  alert(data[_items].id);

                        var _canadd = true;

                        if (resultdescription.length > 0) {

                            for (i = 0; i < resultdescription.length; i++) {

                                // if(resultdescription[i] )

                                if ((resultdescription[i].indexOf(data[_items].name) >= 0) || (data[_items].name.indexOf(resultdescription[i]) >= 0))
                                //   if (data[_items].name.indexOf(resultdescription[i]) >= 0)

                                {
                                    _canadd = true;
                                } else {
                                    _canadd = false;
                                }

                            }
                        }

                        if (_canadd == true)
                            resultdescription.push(data[_items].name + '');

                    });

                }

                //test				
                //alert($(myid).val().toLowerCase());
                if ((_tag == 'description' && resultdescription.length == count))

                { // check at least that one value in array result description strictly exist in data
                    var found1 = false;

                    $.each(data, function(_items) {

                        // alert((data[_items].name + '').toLowerCase());
                        // alert($(myid).val().toLowerCase());

                        if ( ((data[_items].name) + '').toLowerCase().trim() == $(myid).val().toLowerCase().trim())

                        {
                            found1 = true;
                        }

                    });

                    if (found1 == true) {
                        _flag = 0;
                        $('#custom_error').remove();
                        return true;
                    } else {
                        _flag = 1;
                    }

                } else {
                    _flag = 1;
                }

            } else {
                _flag = 1
            }

            if (_flag == 1)
            //if(     (count !=1 && $(myid).val().length >0)  || (_flag == 1))
            {

                //alert('not fun');

                setTimeout(function() {

                    $('#custom_error').remove();

                    var position = $(myid).position();
                    var _left = (position.left);
                    var _right = (position.right);
                    var _bottom = (position.bottom);
                    var _top = (position.top);

                    var _width = $(myid).width();

                    $("<div id = 'custom_error' style = 'position:absolute; background: url(report/images/errorhelper.png)  no-repeat; background-size:cover;'> </div>").insertAfter($(myid).closest('tr'));

                    $('#custom_error').css("left", _left);
                    $('#custom_error').css("width", '189px');
                    $('#custom_error').css("height", "49px");
                    $('#custom_error').html('<center><div style = "user-select: none;  -ms-user-select: none;-moz-user-select: none;-khtml-user-select: none; -webkit-user-select: none;   -webkit-touch-callout: none; display: inline-block;width: auto;margin-top: 10%;font-size: 13px;"><b>Not Found</b></div></center>');

                }, 100);

                var focused = document.activeElement;

                //	alert( focused.id);
                //alert(focused.id);
                //alert(_myid);alert( _second_id);

                if (focused == _myid || focused == _second_id) {

                } else {

                    document.getElementById(_myid).focus();
                }

                return false;
            }

        }
    }
    var secondid = document.getElementById(_second_id);

    //	xmlhttp.open("GET","report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" +_tag+ "&" +"tablename="+_tablename +"&term="+$(myid).val()+'&otherterm=' +$(secondid).val());

    xmlhttp.open("GET", "report/ajax/Get_ReportAutocompleteQuery.php?fieldtag=" + _tag + "&" + "tablename=" + _tablename + "&term=" + encodeURIComponent($(myid).val()));
    xmlhttp.send();

}