//==============================================
certificate.login = {
    process: function() {
        var valid = true;
        if ($('#username').val().length === 0) {
            valid = false;
            $('#username').css('border-color','crimson');
        } else {
            $('#username').css('border-color','');
        }
        if ($('#password').val().length === 0) {
            valid = false;
            $('#password').css('border-color','crimson');
        } else {
            $('#password').css('border-color','');
        }
        if (valid) {
            var a = $.md5($('#password').val());
            var b = $.md5(a);
            var c = $.md5(b);
            $('#md5pass').val(c);
            $("#auth").submit();
        }
    }, //==============================================
    nullFunction: function() {
        //certificate.shared.log('null');
    } //==============================================
}

certificate.order = {
    wasSent: false,
    disable: false,
    objTipsTable: [],
    objTipsTableT: [],
    tipsBase: 0,
    tipsBaseT: 0,
    tipsBaseO: 0,
    del: function(i) {
        var processed = false;
        for (var ii = 0; ii < certificate.v.dataX.length; ii++) {
            if (certificate.v.dataX[ii].status === 'success') {
                processed = true;
            }
        }
        if (certificate.v.dataX[i].status === 'success') {} else if (!processed) {
            certificate.v.dataX[i].first = $('#cert_' + i + '_First').val();
            certificate.v.dataX[i].last = $('#cert_' + i + '_Last').val();
            certificate.v.dataX[i].email = $('#cert_' + i + '_Email').val();
            certificate.v.dataX[i].certificate = $('#cert_' + i + '_Certificate').val();
            certificate.v.dataX[i].dvalue = $('#cert_' + i + '_Value').val();
            certificate.v.dataX[i].cnt = $('#cert_' + i + '_Cnt').val();
            certificate.v.dataX[i].gift = $('#cert_' + i + '_Gift').val();
            certificate.v.dataX[i].from = $('#cert_' + i + '_From').val();
            certificate.v.dataX[i].message = $('#cert_' + i + '_Message').val();
            certificate.v.dataX[i].hasmessage = $('#cert_' + i + '_HasMessage').val();
            certificate.v.dataX[i].action_del = 'Y';
            $('#row_' + i).remove();
            $("#unDelete").css('display','inline-block');
            var ix = 0;
            for (var iy = certificate.v.dataX.length - 1; iy >= 0; iy--) {
                if (certificate.v.dataX[iy].action_del === 'N') {
                    ix++;
                }
            }
            if (certificate.v.max > ix) {
                $('#contactAddButton').css('display','inline-block');
            } else {
                $('#contactAddButton').css('display','none');
            }
            if (ix > 0) {
                certificate.order.buildPageFromJSON();
                certificate.order.autoFix();
            } else {
                $('#insertButton').html('');
            }
        }
        /*
        certificate.order.formSubmit();
        var passid = theID;
        $.post(
            "section/_delete_education.php", {
                'passid': passid
            },
            function(data) {
                certificate.shared.saveComplete(data);
            }
        )
        .done(function(data) {
            certificate.order.obj.edit();
        });
    */
    }, //==============================================
    processOrder: function() {
        var valid = true;

        if ($('#order').val().length > 3) {
            if(isNaN($('#order').val())){
                $('#order').css('border-color','crimson');
                valid = false
            } else {
                $('#order').css('border-color','');
            }
        } else {
            $('#order').css('border-color','crimson');
            valid = false;
        }


        if ($('#count').val().length > 0) {
            if(isNaN($('#count').val())){
                $('#count').css('border-color','crimson');
                valid = false
            } else {
                $('#count').css('border-color','');
                certificate.v.max = Number($('#count').val());
            }
        } else {
            $('#count').css('border-color','crimson');
            valid = false;
        }
        if ($('#dvalue').val().length > 0) {
            $('#dvalue').css('border-color','');
        } else {
            $('#dvalue').css('border-color','crimson');
            valid = false;
        }



        if ($('#order').val().length > 4 && !$('#justrecord').prop('checked')) {
            if (confirm('Order has more than 4 digits.\nIs that OK?')) {
                $('#esendparent').css('display','inline-block');
                certificate.order.toggleOrderJustRecord();
            } else {
                $('#order').css('border-color','crimson');
                valid = false;
            }
        }



        if (valid) {
            certificate.order.checkOrderNumber();
            certificate.order.disable = true;

            certificate.order.disableFields();
            $('#processButton').css('display','none');
        }


        // $('#order').removeAttr('disabled');
    }, //==============================================
    enableFields: function() {
        $('#order').removeAttr("disabled");
        $('#justrecord').removeAttr("disabled");
        $('#count').removeAttr("disabled");
        $('#dvalue').removeAttr("disabled");
        $('#cardtype1').removeAttr("disabled");
        $('#cardtype0').removeAttr("disabled");
        $('#totaltip').removeAttr("disabled");
        $('#splittip').removeAttr("disabled");
        // certificate.order.enableFields();
    }, //==============================================
    disableFields: function() {
        $('#order').attr('disabled','disabled');
        $('#justrecord').attr('disabled','disabled');
        $('#count').attr('disabled','disabled');
        $('#dvalue').attr('disabled','disabled');
        $('#cardtype1').attr('disabled','disabled');
        $('#cardtype0').attr('disabled','disabled');
        $('#totaltip').attr('disabled','disabled');
        $('#splittip').attr('disabled','disabled');

        // certificate.order.disableFields();
    }, //==============================================
    add: function() {
        if (typeof certificate.v.dataX === 'undefined' || !certificate.v.dataX) {var test = 2;} else {
            var valid = certificate.order.autoFix();
            if ((certificate.v.subtotal+1) === certificate.v.max || certificate.v.subtotal === 0 || (certificate.v.subtotal+1) < certificate.v.max) {
                var test = 2;
            } else {
                var test = 0;
            }
        }
        // console.log(certificate.v.subtotal);
        // console.log(test);
        if (test > 1 ) {
            try {
                for (var i = 0; i < certificate.v.dataX.length; i++) {
                    try {
                    certificate.v.dataX[i].first = $('#cert_' + i + '_First').val();
                    certificate.v.dataX[i].last = $('#cert_' + i + '_Last').val();
                    certificate.v.dataX[i].email = $('#cert_' + i + '_Email').val();
                    certificate.v.dataX[i].certificate = $('#cert_' + i + '_Certificate').val();
                    certificate.v.dataX[i].dvalue = $('#cert_' + i + '_Value').val();
                    certificate.v.dataX[i].cnt = $('#cert_' + i + '_Cnt').val();

                    certificate.v.dataX[i].gift = $('#cert_' + i + '_Gift').val();

                    certificate.v.dataX[i].from = $('#cert_' + i + '_From').val();
                    certificate.v.dataX[i].message = $('#cert_' + i + '_Message').val();
                    certificate.v.dataX[i].hasmessage = $('#cert_' + i + '_HasMessage').val();

                    certificate.v.dataX[i].tip = $('#cert_' + i + '_TipEach').val();
                    certificate.v.dataX[i].card = $('#cardtype').val();
                    certificate.v.dataX[i].esend = $('#esend').val();
                    } catch (err) {}
                }
            } catch (err) {}
            if (typeof certificate.v.dataX === 'undefined' || !certificate.v.dataX) {
                certificate.v.dataX = [{"field_id":"0","first":"","last":"","email":"","certificate":"","dvalue":$('#dvalue').val(),"status":"","cnt":certificate.v.max,"gift":$('#gift').val(),"hasmessage":$('#giftmessage').val(),"action_del":"N"}];
                // console.log(certificate.v.dataX)
                // console.log(certificate.v.dataX.length)
                certificate.order.buildPageFromJSON();
                // certificate.order.calcTotal();
                // certificate.order.doThisWhenDone('total', 800, certificate.order.calcTotal);
                
            } else {
                certificate.v.dataX.push({"field_id":"0","first":"","last":"","email":"","certificate":"","dvalue":$('#dvalue').val(),"status":"","cnt":1,"gift":$('#gift').val(),"hasmessage":$('#giftmessage').val(),"action_del":"N"});
                certificate.order.buildPageFromJSON();
                certificate.order.autoFix();
                certificate.order.processUpdatedRows();
                
                // certificate.order.calcTotal();
            }
        }
    }, //==============================================
    deleterow: function(id) {
        if (confirm('Delete?')) {
            window.location.href = '?id=' + id + '&delete&manage';
        }
    }, //==============================================
    togglerow: function(id,tog) {
        if (!tog) {
            ans = confirm('Restore?');
        } else {
            ans = confirm('Used?');
        }
        if (ans) {
            window.location.href = '?id=' + id + '&toggle='+tog+'&manage';
        }
    }, //==============================================
    status: function() {
    }, //==============================================
    genSequence: function(cnt) {
        ////////////////////////////////////////  CNT
        if (cnt === 1) {
            certificate.v.sequence++;
            var result = certificate.v.sequence;
        } else {
            certificate.v.sequence++;
            var result = certificate.v.sequence.toString();
            result += '-'
            for (var i = 0; i < cnt; i++) {
                certificate.v.sequence++;
            }
            certificate.v.sequence--;
            result += certificate.v.sequence.toString();
            
        }
        return result;
    }, //==============================================
    autoFix: function() {
        ////////////////////////////////////////  CNT
        // certificate.order.autoFix();
        // certificate.order.calcTotal();
        var valid = true;
        var processed = false;
        for (var ii = 0; ii < certificate.v.dataX.length; ii++) {
            if (certificate.v.dataX[ii].status === 'success') {
                processed = true;
            }
        }
        if (!processed) {
            certificate.v.total = 0;
            certificate.v.subtotal = 0;
            var item = '';
            var cnt = 0;
            var on = 0;
            for (var i = 0; i < certificate.v.dataX.length; i++) {
                if (certificate.v.dataX[i].action_del === 'N') {
                    item = '#cert_' + i + '_Cnt';

                    if(isNaN($(item).val())){
                        $(item).val(1);
                        certificate.v.dataX[i].gcnt = 1;
                    }
                    cnt = Number($(item).val());
                    certificate.v.dataX[i].gcnt = cnt;
                    certificate.v.total += cnt;
                    if (on > 0) {
                        certificate.v.subtotal += cnt;
                    }
                    on++;
                }
            }
            if (certificate.v.total > certificate.v.max || certificate.v.total < certificate.v.max) {

                var newFirst = certificate.v.max - certificate.v.subtotal;
                
                certificate.v.dataX[0].gcnt = newFirst;
                if (newFirst > 0) {
                    var notDone = true;
                    for (var i = 0; i < certificate.v.dataX.length; i++) {
                        if (certificate.v.dataX[i].action_del === 'N') {
                            $('#cert_'+i+'_Cnt').val(newFirst);
                            break
                        }
                    }
                    // certificate.order.calcTotal();
                    $('#totalcalc').css('display','none');
                    $('#totalcalc span').text(certificate.v.total);
                    $('#contactAddButton').css('display','inline-block');
                    $('#processCertificatesButton').css('display','inline-block');
                } else {
                    $('#contactAddButton').css('display','none');
                    $('#processCertificatesButton').css('display','none');
                    $('#totalcalc').css('display','inline-block');
                    $('#totalcalc span').text('Error Total: '+certificate.v.total);
                    valid = false;
                }
            }
            if (valid) {
                $('#contactAddButton').css('display','inline-block');
                $('#totalcalc').css('display','none');
                $('#processCertificatesButton').css('display','inline-block');
                certificate.v.total = 0;
                certificate.v.subtotal = 0;
                var on = 0;
                for (var i = 0; i < certificate.v.dataX.length; i++) {
                    if (certificate.v.dataX[i].action_del === 'N') {
                        item = '#cert_' + i + '_Cnt';
                        cnt = Number($(item).val());
                        certificate.v.total += cnt;
                        if (on > 0) {
                            certificate.v.subtotal += cnt;
                        }
                        on++;
                    }
                }
                if ((certificate.v.subtotal+1) === certificate.v.max) {
                    $('#contactAddButton').css('display','none');
                }
                certificate.v.sequence = 0;
                var cnt = 0;
                var update = '';
                for (var i = 0; i < certificate.v.dataX.length; i++) {
                    cnt = Number($('#cert_' + i + '_Cnt').val());
                    update = certificate.order.genSequence(cnt);
                    // console.log(update);
                    // console.log('#cert_' + i + '_CertCount');

                    $('#cert_' + i + '_CertCount').text(update);
                    $('#cert_' + i + '_Certificate').val(update);
                }
            }
        }
        
        return valid;
        // certificate.order.buildPageFromJSON();
    }, //==============================================
    updateTotal: function(selectX) {

        var valid = false;
        var result = 1;
        var thisID = $(selectX).parent().parent().parent().attr("idx");
        var showCalc = '#cert_' + thisID + '_CertCount';
        $(showCalc).text("1");

        var difference = function (a, b) { return Math.abs(a - b); }


        if ($(selectX).val().includes("-")) {
            try {
                var val = $(selectX).val();
                var sp = val.split("-");
                var a = Number(sp[0]);
                var b = Number(sp[1]);
                // console.log(a);
                // console.log(b);
                if (a > 0 && b > 0 && b > a) {
                    var difference = function (a, b) { return Math.abs(a - b)+1; }
                    result = difference(a,b);
                    // console.log(difference);
                    // var difference = function (a, b) { return Math.abs(b - a); }
                    // console.log(difference);
                    $(showCalc).text(result);
                    valid = true;
                } else {
                    $(showCalc).text("Err");
                }
            } catch (err) {
                $(showCalc).text("Err");
            }
        }
        // if (valid) {
        //     certificate.order.calcTotal();
        // }
        return result;
    }, //==============================================
    calcTotal: function() {
        ////////////////////////////////////////  _Certificate
        console.log('** cert **');
        var total = 0;
        certificate.v.total = 0;
        certificate.v.subtotal = 0;
        try {
            for (var i = 0; i < certificate.v.dataX.length; i++) {
                try {
                    total = certificate.order.updateTotal('#cert_' + i + '_Certificate');
                    certificate.v.total += total
                    if (i > 0) {
                        certificate.v.subtotal += total
                    }
                } catch (err) {
                    total += 1;
                }
            }
        } catch (err) {}
        console.log(total);
        $('#totalcalc span').text(certificate.v.total);
        if (certificate.v.total > certificate.v.max) {
            $('#contactAddButton').css('display','none');
            $('#totalcalc').css('display','inline-block');
            $('#totalcalc span').text('Error Total: '+certificate.v.total);
            // certificate.order.autoFix();
        } else if (certificate.v.total < certificate.v.max) {
            $('#contactAddButton').css('display','none');
            $('#totalcalc').css('display','inline-block');
            $('#totalcalc span').text('Error Total: '+certificate.v.total);
            // certificate.order.autoFix();
        } else {
            $('#totalcalc').css('display','none');
            $('#contactAddButton').css('display','inline-block');
        }
        
    }, //==============================================
    valid: function() {
        var valid = true;
        var ix = 0
        try {
            for (var iy = certificate.v.dataX.length - 1; iy >= 0; iy--) {
                if (certificate.v.dataX[iy].action_del === 'N') {
                    ix++;
                }
            }
        } catch (err) {}
        try {
            for (var i = 0; i < certificate.v.dataX.length; i++) {
                try {
                    if (certificate.v.dataX[i].action_del === 'N') {
                        var item = '#cert_' + i + '_First';
                        if ($(item).val().length) {
                            $(item).css('border-color','');
                        } else {
                            $(item).css('border-color','crimson');
                            valid = false;
                        }


                        var item = '#cert_' + i + '_Last';
                        if ($(item).val().length) {
                            $(item).css('border-color','');
                        } else {
                            $(item).css('border-color','crimson');
                            valid = false;
                        }



                        var item = '#cert_' + i + '_Certificate';
                        if ($(item).val().length) {
                            $(item).css('border-color','');
                        } else {
                            $(item).css('border-color','crimson');
                            valid = false;
                        }

                        var item = '#cert_' + i + '_Value';
                        if ($(item).val().length) {
                                $(item).css('border-color','');
                        } else {
                            $(item).css('border-color','crimson');
                            valid = false;
                        }


                        var item = '#cert_' + i + '_Email';
                        if ($(item).val().length) {
                            if ($(item).val().includes("@") && $(item).val().includes(".")) {
                                $(item).css('border-color','');
                            } else {
                                $(item).css('border-color','crimson');
                                valid = false;
                            }
                        } else {
                            $(item).css('border-color','crimson');
                            valid = false;
                        }

                        if (valid) {
                            var g = $('#cert_' + i + '_Gift').val();
                            var m = $('#cert_' + i + '_HasMessage').val();
                            if ((g === 1 || g === '1') && (m === 1 || m === '1')) {
                                certificate.v.messageid = i;
                                valid = certificate.gift.valid();
                            }
                        }

                    }
                } catch (err) {}
            }
        } catch (err) {}
        return valid
    }, //==============================================
    excel: function() {
        certificate.order.download('excel.php','certificates.csv');
    }, //==============================================
    download: function(uri, filename) {
        var link = document.createElement('a');
        if (typeof link.download === 'string') {
            document.body.appendChild(link);
            link.download = filename;
            link.href = uri;
            link.click();
            document.body.removeChild(link);
        } else {
            location.replace(uri);
        }
    }, //==============================================
    formSubmit: function() {
        $('#processCertificatesButton').css('display','none');
        if (certificate.order.valid() && certificate.order.autoFix()) {
            $('#processCertificatesButton').css('display','none');
            $('#contactAddButton').css('display','none');

            $('body').append(certificate.v.loader);
            certificate.order.enableFields();
            // $('#loading img').css('height',$( window ).height());

            for (var i = 0; i < certificate.v.dataX.length; i++) {
                try {
                    certificate.v.dataX[i].first = $('#cert_' + i + '_First').val();
                    certificate.v.dataX[i].last = $('#cert_' + i + '_Last').val();
                    certificate.v.dataX[i].email = $('#cert_' + i + '_Email').val();
                    certificate.v.dataX[i].certificate = $('#cert_' + i + '_Certificate').val();
                    certificate.v.dataX[i].dvalue = $('#cert_' + i + '_Value').val();
                    certificate.v.dataX[i].cnt = $('#cert_' + i + '_Cnt').val();

                    certificate.v.dataX[i].gift = $('#cert_' + i + '_Gift').val();

                    certificate.v.dataX[i].from = $('#cert_' + i + '_From').val();
                    certificate.v.dataX[i].message = $('#cert_' + i + '_Message').val();
                    certificate.v.dataX[i].hasmessage = $('#cert_' + i + '_HasMessage').val();

                    certificate.v.dataX[i].tip = $('#cert_' + i + '_TipEach').val();
                    certificate.v.dataX[i].card = $('#cardtype').val();
                    certificate.v.dataX[i].esend = $('#esend').val();
                    if (certificate.v.dataX[i].tip === '') {
                        certificate.v.dataX[i].tip = 0;
                        $('#cert_' + i + '_TipEach').val('0');
                    }
                } catch (err) {}
            }
            $('#JSON').val(JSON.stringify(certificate.v.dataX));
            // console.log($('#JSON').val());
            $.post("processCertificates2.php", $("#certificates").serialize())
                .done(function(data) {
                    // certificate.shared.saveComplete(data);
                    // console.log(data);
                    try {
                        certificate.v.dataX = JSON.parse(data)
                        for (var i = 0; i < certificate.v.dataX.length; i++) {
                            if (certificate.v.dataX[i].status === 'success') {
                                certificate.order.wasSent = true;
                                $('#row_'+i+' .eDelete').html('Success');
                                $('#row_'+i+' .eDelete').css('color','forestgreen');
                            } else if (certificate.v.dataX[i].status === 'saved') {
                                certificate.order.wasSent = true;
                                $('#row_'+i+' .eDelete').html('Saved');
                                $('#row_'+i+' .eDelete').css('color','forestgreen');
                            } else {
                                $('#row_'+i+' .eDelete').html('Failure');
                            }
                        }
                        var processed = true;
                        for (var ii = 0; ii < certificate.v.dataX.length; ii++) {
                            if (certificate.v.dataX[ii].action_del === 'N') {
                                if (certificate.v.dataX[ii].status === 'success') {} else {
                                    processed = false;
                                }
                            }
                        }
                        if (processed) {
                            $('#processCertificatesButton').css('display','none');
                        } else {
                            $('#processCertificatesButton').css('display','inline-block');
                        }
                    } catch (err) {
                        alert('Error');
                        $('#processCertificatesButton').css('display','inline-block');
                    }
                    $('#loading').remove();
                    certificate.order.disableFields();
                });
        } else {
            $('#processCertificatesButton').css('display','inline-block');
        }
        $('#reload').remove();
        $('body').append('<center><span id="reload" class="button" onclick="window.location.href=\'?\'"> Reload </span></center>');
    }, //==============================================
    loadJSON: function() {
        if (certificate.shared.isLoaded(3)) {
            certificate.order.buildPageFromJSON();
        } else {
            setTimeout(function() { certificate.order.loadJSON(); }, 800);
        }
    },//==============================================
    unDelete: function() {
        $("#unDelete").css('display','none');
        for (var i = 0; i < certificate.v.dataX.length; i++) {
            try {
                if ($('#cert_' + i + '_First').length) {
                    certificate.v.dataX[i].first = $('#cert_' + i + '_First').val();
                    certificate.v.dataX[i].last = $('#cert_' + i + '_Last').val();
                    certificate.v.dataX[i].email = $('#cert_' + i + '_Email').val();
                    certificate.v.dataX[i].certificate = $('#cert_' + i + '_Certificate').val();
                    certificate.v.dataX[i].dvalue = $('#cert_' + i + '_Value').val();
                    certificate.v.dataX[i].cnt = $('#cert_' + i + '_Cnt').val();
                    certificate.v.dataX[i].gift = $('#cert_' + i + '_Gift').val();

                    certificate.v.dataX[i].from = $('#cert_' + i + '_From').val();
                    certificate.v.dataX[i].message = $('#cert_' + i + '_Message').val();
                    certificate.v.dataX[i].hasmessage = $('#cert_' + i + '_HasMessage').val();

                }
                certificate.v.dataX[i].action_del = 'N';
            } catch(err) {
                certificate.v.dataX[i].action_del = 'N';
            }
        }
        //certificate.v.dataX = JSON.parse(certificate.v.recover);
        certificate.order.buildPageFromJSON();
        certificate.shared.scrollTo();
        setTimeout(function() { certificate.order.required(); }, 2000);
        /*certificate.v.closeFunction = certificate.shared.nullFunction;
        certificate.order.saveThenOpen();*/
    },//==============================================
    saveThenOpen: function() {
        certificate.shared.close();
        certificate.shared.runWhen(null, 'closed', function(){certificate.order.obj.edit();});
    }, //==============================================
    htmlRow: function(i, id, first, last, email, certificate, cnt, dvalue, status, gift,from,message, hasmessage) {
        // certificate.order.htmlRow(i, field_id, first, last, email, certificate, cnt, dvalue, status);
            if (typeof i === 'undefined') {
                i = certificate.v.dataX.length - 1;
            }
            if (typeof id === 'undefined') {
                id = 0;
            }
            if (typeof first === 'undefined') {
                first = '';
            }
            if (typeof last === 'undefined') {
                last = '';
            }
            if (typeof email === 'undefined') {
                email = '';
            }
            if (typeof status === 'undefined') {
                status = '';
            }
            if (typeof dvalue === 'undefined') {
                dvalue = '';
            }
            if (typeof cnt === 'undefined') {
                cnt = '';
            }
            if (typeof from === 'undefined') {
                from = 'From Name';
            }
            if (typeof message === 'undefined') {
                message = 'Message';
            }
            if (gift === '1' || gift === 1) {
                var giftLabel = 'is a Gift';
                var messageCode = ''
            } else {
                var giftLabel = 'not a Gift';
                var messageCode = 'style="display:none;"'
            }
            if (hasmessage === '1' || hasmessage === 1) {
                var msgaction = 'Edit';
            } else {
                var msgaction = 'Add';
            }

            $('#contactBody').append('\
            <div id="row_' + i + '" class="certItemParent " idx="' + i + '">\
                <div id="eDelete" class="eDelete" title="delete" onClick="certificate.order.del(' + i + ');">\
                   <img src="images/delete.png">\
                </div>\
                <div class="certItem">\
                    <div class="itemLabel first"> First: </div>\
                    <div id="eefDegree" class="certField">\
                        <input name="First_' + i + '" type="text" id="cert_' + i + '_First" class="certbox" value="' + first + '">\
                    </div>\
                </div>\
                <div class="certItem">\
                    <div class="itemLabel last"> Last: </div>\
                    <div id="eefSchool" class="certField">\
                        <input name="Last_' + i + '" type="text" id="cert_' + i + '_Last" class="certbox" value="' + last + '">\
                    </div>\
                </div>\
                <div class="certItem">\
                    <div class="itemLabel email"> Email: </div>\
                    <div class="certField">\
                        <input name="Email_' + i + '" type="text" id="cert_' + i + '_Email" class="certbox" value="' + email + '">\
                    </div>\
                </div>\
                <div class="certItem">\
                    <div class="itemLabel certificate"> Count: </div>\
                    <div class="certField">\
                        <input name="Certificate_' + i + '" type="text" id="cert_' + i + '_Cnt" class="certbox sbox crt" value="' + cnt + '">\
                        <input name="Certificate_' + i + '" type="hidden" id="cert_' + i + '_Certificate" class="certbox sbox " value="' + certificate + '">\
                        <span id="cert_' + i + '_CertCount" class="blue"></span>\
                    </div>\
                </div>\
                <div class="certItem">\
                    <div class="itemLabel value"> Value: </div>\
                    <div class="certField">\
                        <input name="Value_' + i + '" type="text" id="cert_' + i + '_Value" class="certbox " style="width:180px;" value="' + dvalue + '">\
                    </div>\
                </div>\
                \
                <div class="certItem" >\
                    <div class="itemLabel gift button" id="cert_' + i + '_GiftLabal" onclick="certificate.order.toggleItemGift(' + i + ');" title="click to change"> ' + giftLabel + ' </div>\
                        <input name="Gift_' + i + '" type="hidden" id="cert_' + i + '_Gift" class="certbox " value="' + gift + '">\
                </div>\
                \
                <div class="certItem" '+messageCode+'>\
                    <div class="itemLabel gift button" id="cert_' + i + '_MessageLabel"  title="click to change" onclick="certificate.order.messageOpen(' + i + ');"> '+msgaction+' Message </div>\
                    <input name="HasMessage_' + i + '" type="hidden" id="cert_' + i + '_HasMessage"  value="' + hasmessage + '">\
                </div>\
                \
                <br />\
                <div class="certItem tipgroup" >\
                    <div class="itemLabel value button tip" onclick="certificate.order.newPopup(' + i + ');"> Manage Tip: </div>\
                    <div class="certField">\
                        <span id="cert_' + i + '_TipGroup_Label"></span>\
                        <span id="cert_' + i + '_TipEach_Label"></span>\
                        <input name="TipGroup_' + i + '" type="hidden" id="cert_' + i + '_TipGroup" class="certbox " style="width:180px;" value="">\
                        <input name="TipEach_' + i + '" type="hidden" id="cert_' + i + '_TipEach" class="certbox " style="width:180px;" value="">\
                    </div>\
                </div>\
                <div id="GM_' + i + '" class="giftmessage" style="display:none;">\
                    <span class="close" onClick="certificate.order.messageClose(this);">X</span>\
                    <div class="giftmessageinner">\
                        <div class="giftheader">Gift Message <span></span></div>\
                        <hr /><br /><div class="items">\
                            <div>\
                                <p>\
                                    <input name="from" type="text" id="cert_'+i+'_From" class="certbox from" value="'+from+'" style="width: 250px;">\
                                    <br />\
                                    <textarea name="message" type="text" id="cert_'+i+'_Message" class="certbox message" style="width: 250px;" maxlength="300">'+message+'</textarea>\
                                    <br />\
                                    <span class="msgcnt"></span>\
                                    <span class="button" onClick="certificate.order.removeMessage(' + i + ');">No Message</span>\
                                </p>\
                            </div>\
                        </div>\
                    </div>\
                </div>\
                <br />\
                <div id="someSpace"></div>\
            </div>\
            <input name="id_' + i + '" type="hidden" id="id_' + i + '" value="' + id + '"/>\
            ');
            
    }, //==============================================
    buildPageFromJSON: function() {
        //certificate.v.recover = JSON.stringify(certificate.v.dataX);
        $('#contactBody').html('');
        $('#insertButton').html('');
        var ix = 0
        try {
            for (var iy = certificate.v.dataX.length - 1; iy >= 0; iy--) {
                if (certificate.v.dataX[iy].action_del === 'N') {
                    ix++;
                }
            }
        } catch (err) {}
        var iw = 0;
        try {
            for(var i = 0;i < certificate.v.dataX.length; i++){
                if (certificate.v.dataX[i].first === null) {
                    certificate.v.dataX[i].first = '';
                }
                if (certificate.v.dataX[i].last === null) {
                    certificate.v.dataX[i].last = '';
                }
                if (certificate.v.dataX[i].email === null) {
                    certificate.v.dataX[i].email = '';
                }
                if (certificate.v.dataX[i].dvalue === null) {
                    certificate.v.dataX[i].dvalue = '';
                }
                if (certificate.v.dataX[i].cnt === null) {
                    certificate.v.dataX[i].cnt = '';
                }
                if (certificate.v.dataX[i].gift === null) {
                    certificate.v.dataX[i].gift = $('#gift').val();
                }
                if (certificate.v.dataX[i].from === null) {
                    certificate.v.dataX[i].from = 'From Name';
                }
                if (certificate.v.dataX[i].message === null) {
                    certificate.v.dataX[i].message = 'Message';
                }
                if (certificate.v.dataX[i].hasmessage === null) {
                    certificate.v.dataX[i].hasmessage = '0';
                }
                // if (certificate.v.dataX[i].certificate === null) {
                if (certificate.v.dataX[i].action_del === 'N') {
                    certificate.v.dataX[i].certificate = certificate.order.certGen(iw,ix);
                    iw++;
                }
                // }
                if (certificate.v.dataX[i].action_del === 'N') {
                    certificate.order.htmlRow(i, certificate.v.dataX[i].field_id, certificate.v.dataX[i].first, certificate.v.dataX[i].last, certificate.v.dataX[i].email, certificate.v.dataX[i].certificate, certificate.v.dataX[i].cnt, certificate.v.dataX[i].dvalue, certificate.v.dataX[i].status, certificate.v.dataX[i].gift,certificate.v.dataX[i].from,certificate.v.dataX[i].message,certificate.v.dataX[i].hasmessage);
                    // certificate.order.htmlRow(i, field_id, first, last, email, certificate, cnt, dvalue, status);
                }
            }
        } catch (err) {}
            
        $('#insertButton').append('<div style="display:block;margin: 20px;width:80%;margin:20px;"><div style="float:right;"><div id="totalcalc" style="color: crimson;font-size: larger;padding: 20px;"><span></span></div><span id="processCertificatesButton" class="button" onclick="certificate.order.formSubmit();" >Send Certificates</span></div></div>');
        $('.message').off('keydown');
        $('.message').off('focus');
        $('.message').off('blur');

        $('.from').off('keyup');
        $('.from').off('focus');

        $('#contactBody').append('<script>$(".crt").keyup(function() {certificate.order.doThisWhenDone("autofix", 800, certificate.order.autoFix);});</script>');
        var code = '<script>\n\
                        $( ".from" ).focus(function() {\n\
                          if ($(this).val() === "From Name") {\n\
                            $(this).val("");\n\
                          }\n\
                        });\n\
                        $( ".from" ).blur(function() {\n\
                          if ($(this).val() === "") {\n\
                            $(this).val("From Name");\n\
                          }\n\
                        });\n\
                        $( ".message" ).focus(function() {\n\
                          if ($(this).val() === "Message") {\n\
                            $(this).val("");\n\
                          } \n\
                          $("#GM_" + certificate.v.messageid + " .msgcnt").text(300-$(this).val().length)\n\
                        });\n\
                        $( ".message" ).blur(function() {\n\
                          if ($(this).val() === "") {\n\
                            $(this).val("Message");\n\
                            $("#GM_" + certificate.v.messageid + " .msgcnt").text("");\n\
                            \n\
                            certificate.gift.valid();\n\
                          }\n\
                        });\n\
                        $( ".certbox" ).blur(function() {\n\
                            certificate.gift.valid();\n\
                        });\n\
                        $( ".message" ).keydown(function() {\n\
                                $("#GM_" + certificate.v.messageid + " .msgcnt").text(300-$(this).val().length);\n\
                            \n\
                            if ($(this).val().length > 300) {\n\
                                // $("#GM_" + certificate.v.messageid + " .msgcnt").text("");\n\
                                $(this).css("border-color","crimson");\n\
                                $(this).css("border-width","2px");\n\
                                $("#GM_" + certificate.v.messageid + " .msgcnt").css("color","crimson");\n\
                            } else {\n\
                                $("#GM_" + certificate.v.messageid + " .msgcnt").css("color","black");\n\
                            }\n\
                        });\n\
                    </script>';
        $('#contactBody').append(code);

        if (certificate.v.max > ix) {
            $('#contactAddButton').css('display','inline-block');
        } else {
            $('#contactAddButton').css('display','none');
        }
        
        try{
            if (Number($('#totaltip').val()) < 5) {$('.tipgroup').css('display','none');$('.certItemParent').css('height','41px');}

        } catch (err) {
            if (Number($('#totaltip').val()) < 5) {$('.tipgroup').css('display','none');$('.certItemParent').css('height','41px');}
        }
        
        certificate.order.tipFirst();
        // $('#edubody').append('<input type="hidden" id="confirmLoad2" value="loaded"/>');
    
    }, //==============================================
    certGen: function(i,ix) {
        // console.log(i,ix,certificate.v.max);
        var result = '1-';
        if (i === 0) {
            var thisResult = (certificate.v.max - ix) + 1;
            if (thisResult === 1) {
                result = 1;
            } else {
                result += thisResult;
            }
        } else {
            result = (certificate.v.max - i) + 1;
        }
        return result;
    }, //==============================================
    runDoThis: function(myLabel) {
        if (typeof certificate.v.doThis !== 'undefined') {
            var nowish = start = new Date().getTime();
            var run = false;
            for (var j = 0; j < certificate.v.doThis.length; j++) {
                var thisLabel = certificate.v.doThis[j].myLabel;
                var thisWait = certificate.v.doThis[j].wait;
                var thisStamp = certificate.v.doThis[j].stamp;
                if (myLabel === thisLabel) {

                    if ((nowish - thisStamp) > thisWait) {var checkStamp =  true;} else {var checkStamp =  false;}
                    if (checkStamp) {
                        var run = true;
                        var thisLabel = certificate.v.doThis[j].myLabel;
                        var thisScript = certificate.v.doThis[j].script;
                    }
                }
            }
        }
        if (run) {
            thisScript();
        }
    }, //==============================================
    doThisWhenDone: function(myLabel, waitfor, script) {
        var isNew = true;
        var isFirst = false;
        var stamp = start = new Date().getTime();
        if (typeof certificate.v.doThis === 'undefined') {
            var nextID = 0
            certificate.v.doThis = new Array();
            certificate.v.doThis = [];
            certificate.v.doThis.length = 0;
            var isFirst = true;
        } else {
            var nextID = certificate.v.doThis.length;
        }
        if (!isFirst) {
            for (var j = 0; j < certificate.v.doThis.length; j++) {
                var thisLabel = certificate.v.doThis[j].myLabel;
                if (myLabel === thisLabel) {
                    var isNew = false;
                    certificate.v.doThis[j] = {
                        myLabel: myLabel,
                        stamp: stamp,
                        wait: waitfor,
                        script: script
                    };
                }
            }
        }
        if (isNew) {

            certificate.v.doThis[nextID] = {
                myLabel: myLabel,
                stamp: stamp,
                wait: waitfor,
                script: script
            };
        }
        var waitforAbout = waitfor + 50;
        setTimeout(function() { certificate.order.runDoThis(myLabel); }, waitforAbout);

        // certificate.order.doThisWhenDone(myLabel, waitfor, script);
        // certificate.order.doThisWhenDone('total', 800, certificate.order.calcTotal);
    }, //==============================================
    runWhen: function(editingThis_TFVar, loadedClosedTrue, script, param1, param2, param3) {
        var checkAgain = 50;
        if (typeof editingThis_TFVar === 'undefined') { var editingThis_TFVar = null; }
        if (typeof param1 === 'undefined') { var param1 = null; }
        if (typeof param2 === 'undefined') { var param2 = null; }
        if (typeof param3 === 'undefined') { var param3 = null; }

        if (loadedClosedTrue === 'loaded') {

        } else if (loadedClosedTrue === 'closed') {

        } else if (loadedClosedTrue === 'true') {
            var evalSTR = 'var test = ' + editingThis_TFVar;
            eval(evalSTR);
            if (typeof test === 'undefined') { var test = null; }
            if (test === true) {
                setTimeout(function() {
                    if (param3 !== null) {
                        script(param1,param2,param3);
                    } else if (param2 !== null) {
                        script(param1,param2);
                    } else if (param1 !== null) {
                        script(param1);
                    } else {
                        script();
                    }
                }, 50);
            } else {
                setTimeout(function() {
                    certificate.order.runWhen(editingThis_TFVar, loadedClosedTrue, script, param1, param2, param3);
                }, checkAgain);
                
            }
        } else if (loadedClosedTrue === 'false') {
            var evalSTR = 'var test = ' + editingThis_TFVar;
            eval(evalSTR);
            if (typeof test === 'undefined') { var test = null; }
            if (test === false) {
                setTimeout(function() {
                    if (param3 !== null) {
                        script(param1,param2,param3);
                    } else if (param2 !== null) {
                        script(param1,param2);
                    } else if (param1 !== null) {
                        script(param1);
                    } else {
                        script();
                    }
                }, 50);
            } else {
                setTimeout(function() {
                    certificate.order.runWhen(editingThis_TFVar, loadedClosedTrue, script, param1, param2, param3);
                }, checkAgain);
                
            }
        }
        // certificate.order.runWhen('certificate.v.loadcomplete', 'true', function(){});
    }, //==============================================
    numProcess: function(n) {
        try{ var result = Number(n); } catch (err) { var result = 99; }
        return result
    }, //==============================================
    checkOrderNumber: function() {
        // certificate.v.loadcomplete = false;
        // certificate.order.runWhen('certificate.v.loadcomplete', 'true', function(){certificate.order.add();});
        if (location.href.includes('file://')) {
            certificate.order.add();
        } else {
            $.post("checkOrderNumber.php", $("#certificates").serialize())
                .done(function(data) {
                    // console.log(data);
                    if (certificate.order.numProcess(data) > 0) {
                        $('#order').css('border-color','crimson');
                        certificate.order.enableFields();
                        $('#processButton').css('display','inline-block');
                        alert('Order in use');
                    } else {
                        $('#processButton').css('display','none');
                        $('#contactAddButton').css('display','inline-block');
                        certificate.order.add();
                    }

                    $('#loading').remove();
                });
        }

    }, //==============================================
    showall: function() {
        $('.email').each(function( index ) {
            $('#'+$(this).parent().attr('id')).css('display','table-row');
        });
        // certificate.order.showall()
    }, //==============================================
    search: function(field,search) {
        $('.'+field).each(function( index ) {
            var thevalue = $(this).text();
            if (thevalue.toLowerCase().includes(search.toLowerCase())) {
                $('#'+$(this).parent().attr('id')).css('display','table-row');
            } else {
                $('#'+$(this).parent().attr('id')).css('display','none');
            }
        });
        // certificate.order.search(field,search)
    }, //==============================================
    toggleOrderGift: function() {
        if (!certificate.order.disable) {
            if ($('#gift').val() === '1') {
                $('#gift').val('0');
                $('#giftlabel').text('No');
                $('#giftchild').css('display','none');
                $('#giftmessage').val('1');
                certificate.order.toggleOrderGiftMessage();
            } else {
                $('#gift').val('1');
                $('#giftlabel').text('Yes');
                $('#giftchild').css('display','block');
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleOrderEmailSend();
    }, //==============================================
    toggleOrderGiftMessage: function() {
        if (!certificate.order.disable) {
            if ($('#giftmessage').val() === '1') {
                $('#giftmessage').val('0');
                $('#giftmessagelabel').text('No');
            } else {
                $('#giftmessage').val('1');
                $('#giftmessagelabel').text('Yes');
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleOrderGiftMessage();
    }, //==============================================
    toggleOrderEmailSend: function() {
        if (!certificate.order.disable) {
            if ($('#esend').val() === '1') {
                $('#esend').val('0');
                $('#esendlabel').text('No');
            } else {
                $('#esend').val('1');
                $('#esendlabel').text('Yes');
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleOrderEmailSend();
    }, //==============================================
    toggleOrderCardType: function() {
        if (!certificate.order.disable) {
            if ($('#cardtype').val() === '1') {
                $('#cardtype').val('0');
                $('#cardtypelabel').text('Black');
            } else {
                $('#cardtype').val('1');
                $('#cardtypelabel').text('Gold');
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleOrderCardType();
    }, //==============================================
    validAutoJustRecord: function() {
        certificate.order.toggleOrderJustRecord();
    }, //==============================================
    toggleItemGift: function(i) {
        var cg = '#cert_' + i + '_Gift';
        var cgl = '#cert_' + i + '_GiftLabal';
        var mbutton = '#cert_' + i + '_MessageLabel';
        var mbox = '#GM_' + i;

        if (!certificate.order.wasSent) {
        // if (true) {
            if ($(cg).val() === '1') {
                $(cg).val('0');
                $(cgl).text('not a Gift');
                $(mbutton).parent().css('display','none');
                $(mbox).css('display','none');
            } else {
                $(cg).val('1');
                $(cgl).text('is a Gift');
                $(mbutton).parent().css('display','inline-block');
                certificate.order.messageOpen(i);
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleItemGift(i);
    }, //==============================================
    toggleOrderJustRecord: function() {
        if (!certificate.order.disable) {
            if ($('#justrecord').prop('checked')) {
                $('#justrecord').prop('checked', false);
                $('#esend').val('0');
                certificate.order.toggleOrderEmailSend();
                setTimeout(function(){
                    $( "#esendparent" ).fadeOut( "slow", function() {
                        if ($('#justrecord').prop('checked')) {
                            $('#esendparent').css('display','block');
                        } else {
                            $('#esend').val('0');
                            certificate.order.toggleOrderEmailSend();
                        }
                        
                    });
                }, 800);

                // $('#esendparent').css('display','none');
            } else {
                $('#esendparent').css('display','block');
                $('#justrecord').prop('checked', true);
                $('#esend').val('1');
                certificate.order.toggleOrderEmailSend();
            }
        }
        document.getSelection().removeAllRanges();
        // certificate.order.toggleOrderJustRecord();
    }, //==============================================
    tipTotalEach: function() {

        $('.tipitem').each(function( index ) {
            var thevalue = $(this).val();
            var row = Number($(this).attr('row'));
            var par = Number($(this).attr('par'));

            certificate.v.tippar = par;
            if(isNaN($(this).val())){
                // console.log('nan');
                $(this).val(certificate.order.tipsBase);
                certificate.order.objTipsTable[par].updateItem(row,Number($(this).val()));
            } else if (thevalue.length === 0) {
                // console.log('is0');
                $(this).val('0');
                certificate.order.objTipsTable[par].updateItem(row,Number($(this).val()));
            } else {
                // console.log('go');
                certificate.order.objTipsTable[par].updateItem(row,Number($(this).val()));
            }
        });
        // certificate.order.dump();
        certificate.order.newtipsBase();
        certificate.order.newPopup(certificate.v.tippar);
        // certificate.order.tipTotalEach();
    }, //==============================================
    updateGroup: function() {
        var row = certificate.v.tiprow;
    }, //==============================================
    newPopup: function(row) {
        $('#selectsomething').remove();
        var theLabel = 'Manage Tips'
        // $('body').append('<div id="selectsomething"><span class="close" onClick="$(\'#selectsomething\').remove();">X</span><div id="selectsomethinginner"><span id="selectheader">'+ theLabel +'</span><hr /><input type="text" id="grouptip" value="'+grouptip+'"><br /><div class="items"></div></div></div>');
        $('body').append('<div id="selectsomething"><span class="close" onClick="certificate.v.tipID = \'\'; certificate.order.tipTotalEach(); $(\'#selectsomething\').remove();">X</span><div id="selectsomethinginner"><span id="selectheader">'+ theLabel +'</span><hr /><div class="items"></div></div></div>');

        
        // console.log(certificate.order.objTipsTable[row].items.length);
        // try {
            for (var i = 0; i < certificate.order.objTipsTable[row].items.length; i++) {
                // console.log(certificate.order.objTipsTable[row].items[i].val);
                $('#selectsomething .items').append('<div class="item" ><input type="text" par="'+row+'" row="'+i+'" id="tip_'+i+'" name="tip_'+i+'" class="tipitem" value="'+certificate.order.objTipsTable[row].items[i].val+'" style="width: 50px;" ></div>');
            }
        // } catch(err) {}
        $('#selectsomething').append('<script>$(".tipitem").keyup(function() {certificate.v.tipID = $(this).attr("id"); certificate.order.doThisWhenDone("total", 2000, certificate.order.tipTotalEach);});</script>');
        $('#selectsomething').append('<div class="tiperror" style="color: crimson; font-size: x-large; padding: 5px; margin-bottom: 20px;"></div>');
        $('#selectsomething').append('<div class="tiptotalarea" style="font-size: x-large; padding: 5px; margin-bottom: 20px;"></div>');

        certificate.order.tipTotalCalc();
        // certificate.order.newPopup(row,grouptip,count);
        // certificate.order.newPopup(0);
    }, //==============================================
    tipFirst_old: function() {
        try {
            var totaltip = Number($('#totaltip').val());
            if (totaltip > 0) {
                if ($('#splittip').prop('checked')) {
                    var divUpG = totaltip / certificate.v.dataX.length;
                    var tipeachG = divUpG.toFixed(2);


                    for(var i = 0;i < certificate.v.dataX.length; i++){
                        var cnt = 'cert_' + i + '_Cnt';

                        var divUpE = tipeachG / Number($('#'+cnt).val());
                        var tipeachE = divUpE.toFixed(2);

                        var tgl = 'cert_' + i + '_TipGroup_Label';
                        var tel = 'cert_' + i + '_TipEach_Label';
                        var tgf = 'cert_' + i + '_TipGroup';
                        var tef = 'cert_' + i + '_TipEach';
                        $('#'+tgl).text('Group: ' + tipeachG + ', ');
                        $('#'+tel).text('Each: ' + tipeachE);

                        $('#'+tgf).val(tipeachG);
                    }


                }
            }
            
        } catch(err) {}
        


        // certificate.order.tipFirst();


    }, //==============================================
    tipFirst: function() {
        // try {
            certificate.order.objTipsTable = [];
            certificate.objRow.instances = [];
            

            var totaltip = Number($('#totaltip').val());
            var count = Number($('#count').val());
            if (totaltip > 0 && count > 0) {
                if ($('#splittip').prop('checked')) {
                    var divUpE = totaltip / count;

                    var cleanTipText = divUpE.toString();
                    var tmp0 = cleanTipText.split('.');
                    var cleanTip = tmp0[0];

                    var tipeachE = cleanTip;
                    
                    // var tipeachE = divUpE.toFixed(2);
                    certificate.order.tipsBase = tipeachE;
                    certificate.order.tipsBaseO = tipeachE;

                    for(var i = 0;i < certificate.v.dataX.length; i++){
                        var cnt = 'cert_' + i + '_Cnt';
                        var tipeachG = tipeachE * Number($('#'+cnt).val());

                        var tgl = 'cert_' + i + '_TipGroup_Label';
                        var tel = 'cert_' + i + '_TipEach_Label';
                        var tgf = 'cert_' + i + '_TipGroup';
                        var tef = 'cert_' + i + '_TipEach';


                        var items = [];
                        for(var ii = 0;ii < Number($('#'+cnt).val()); ii++){
                            items.push(new certificate.objRow(i,ii, tipeachE));
                        }

                        certificate.order.objTipsTable.push(new certificate.objTable(i, cnt, tgl, tel, tgf, tef, tipeachE, items));
                    }
                    certificate.order.tipsBaseT = certificate.order.tipsBase;
                    certificate.order.processUpdatedRows();

                }
            } else if (totaltip > 0) {} else if (totaltip === 0) {} else { alert('Error');}
            
        // } catch(err) {}
        


        // certificate.order.tipFirst();

    }, //==============================================
    dump: function() {
        console.log('');
        console.log('dump start');
        for(var i = 0;i < certificate.order.objTipsTable.length; i++){
            for(var ii = 0;ii < certificate.order.objTipsTable[i].items.length; ii++){
                console.log(certificate.order.objTipsTable[i].items[ii].val);
            }
        }
        console.log('dump end');
        console.log('``');
        // certificate.order.dump();
    }, //==============================================
    newtipsBase: function() {
        $(this).css('border-color','');
        $('#selectsomething .tiperror').append('');

        $('#processCertificatesButton').css('display','inline-block');
        $('.tipgroup').css('border-color','');

        certificate.order.tipsBaseT = certificate.order.tipsBase;
        var totaltip = Number($('#totaltip').val());
        var count = Number($('#count').val());
        var subTotal = 0;
        // console.log('tipsBase old: '+certificate.order.tipsBase);
        var ix = 0;
        for(var i = 0;i < certificate.order.objTipsTable.length; i++){
            for(var ii = 0;ii < certificate.order.objTipsTable[i].items.length; ii++){
                if (Number(certificate.order.objTipsTable[i].items[ii].val) !== Number(certificate.order.tipsBase)) {
                    subTotal += Number(certificate.order.objTipsTable[i].items[ii].val);
                    // console.log(certificate.order.objTipsTable[i].items[ii].val);
                    ix++;
                }
            }
        }

        // console.log('subTotal: '+subTotal);
        // console.log('totaltip: '+totaltip);
        if (ix>0) {
            // console.log('Calc: '+(totaltip - subTotal));
            // console.log('ix: '+ix);
            var valid = true;
            if (totaltip < subTotal) { valid = false; }
            var calc = totaltip - subTotal;

            if (calc < 0) { valid = false; }








            if (valid) {
                // console.log('x1');
                var tipsBase = (totaltip - subTotal)/(count-ix);
                if (tipsBase > 0) {
                    // console.log('x2');
                    var cleanTipText = tipsBase.toString();
                    var tmp0 = cleanTipText.split('.');
                    var cleanTip = tmp0[0];
                    // var cleanTip = certificate.order.round5(tipsBase);
                    if (cleanTip < 5) {
                        var cleanTip = 0;
                    }
                    certificate.order.tipsBase = cleanTip;
                } else {
                    certificate.order.tipsBase = 0;
                    setTimeout(function(){ $('#selectsomething .tiperror').append('Error'); certificate.order.tipError(); }, 200);
                    // console.log('Error');
                    $('#processCertificatesButton').css('display','none');
                    $('.tipgroup').css('border-color','crimson');
                }

            } else {
                certificate.order.tipsBase = 0;
                setTimeout(function(){ $('#selectsomething .tiperror').append('Error'); certificate.order.tipError(); }, 200);
                // console.log('Error');
                $('#processCertificatesButton').css('display','none');
                $('.tipgroup').css('border-color','crimson');
            }
            // console.log('tipsBase new: '+certificate.order.tipsBase);
                certificate.order.processUpdatedRows();
            if (tipsBase > 0) { } ///
        }

        

        // certificate.order.newtipsBase();
    }, //==============================================
    processUpdatedRows: function() {
        for(var i = 0;i < certificate.order.objTipsTable.length; i++){
            certificate.order.objTipsTable[i].processUpdatedRows();
            // certificate.order.objTipsTable[i].tglF();
            // certificate.order.objTipsTable[i].telF();
            // certificate.order.objTipsTable[i].tefF();
            // certificate.order.objTipsTable[i].tgfF();
        }
        // certificate.order.processUpdatedRows();
    }, //==============================================
    testStuff: function() {
        certificate.order.tipFirst();
        certificate.order.objTipsTable[0].updateItem(0,20);
        certificate.order.objTipsTable[0].updateItem(1,10);
        certificate.order.objTipsTable[1].updateItem(0,1);
        certificate.order.objTipsTable[1].updateItem(1,30);
        certificate.order.newtipsBase();
        

        // certificate.order.testStuff();
    }, //==============================================
    initiateTest: function() {
        $('#selectsomething').remove();
        certificate.order.tipFirst();
        $('#order').val('2346');
        $('#count').val('8');
        $('#totaltip').val('100');
        $('#processButton').click();
        setTimeout(function(){ $('.tip').click(); }, 1000);
        

        // certificate.order.initiateTest();
    }, //==============================================
    round5: function(x) {
        return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
        // certificate.order.round5(x);
    }, //==============================================
    tipTotalCalc: function() {
        var result = 0;
        for(var i = 0;i < certificate.order.objTipsTable.length; i++){
            for(var ii = 0;ii < certificate.order.objTipsTable[i].items.length; ii++){
                result += Number(certificate.order.objTipsTable[i].items[ii].val); 
            }
        }
        // console.log(result);
        if (Number($('#totaltip').val()) > result) {
            setTimeout(function(){
                $('.tiptotalarea').html('');
                $('.tiptotalarea').append('<div> Tip Paid: ' + $('#totaltip').val() + '</div>');
                $('.tiptotalarea').append('<div> Tip Allocated: ' + result + '</div>');
            }, 200);
        } else if (Number($('#totaltip').val()) < result) {
            setTimeout(function(){
                $('.tiptotalarea').html('');
                $('.tiptotalarea').append('<div> Tip Paid: ' + $('#totaltip').val() + '</div>');
                $('.tiptotalarea').append('<div> Tip Allocated: ' + result + '</div>');
                $('.tiptotalarea').append('<br />');
                $('.tiptotalarea').append('<div> Over By: ' + (result - Number($('#totaltip').val())) + '</div>');
                certificate.order.tipError();
            }, 200);
        } else {
            setTimeout(function(){
                $('.tiptotalarea').html('');
                $('.tiptotalarea').append('<div> Tip Total: ' + result + '</div>');
            }, 200);
        }
        
        // certificate.order.tipTotalCalc();
    }, //==============================================
    tipError: function() {
        var error = false;
        $('.tipitem').each(function( index ) {
            if ($(this).val() > certificate.order.tipsBaseT ) {
                error = true;
                $(this).css('border-color','crimson');
                $('#selectsomething .tiperror').text('Error');
                $('.tipgroup').css('border-color','crimson');
            }
        });
        if (!error) {
            $('.tipitem').css('border-color','');
            $('#selectsomething .tiperror').text('');
            $('.tipgroup').css('border-color','');
        }
        // certificate.order.tipError();
    }, //==============================================
    removeMessage: function(i) {
        $('#cert_' + i + '_MessageLabel').text('Add Message');
        $('#cert_' + i + '_HasMessage').val('0');
        $('#GM_'+i).css('display','none');
        $('#cert_' + i + '_MessageLabel').parent().css('border-color','');
        
    }, //==============================================
    messageOpen: function(i) {
        if (!certificate.order.wasSent) {
            $('#cert_' + i + '_MessageLabel').text('Edit Message');
            $('#cert_' + i + '_HasMessage').val('1');

            certificate.v.ok2open = true;
            $('.giftmessage').each(function( index ) {
                if ($(this).css('display').toLowerCase().includes('block')) {
                    if (!certificate.gift.valid()) {
                        certificate.v.ok2open = false;
                    }
                }
            });
            if (certificate.v.ok2open) {
                $('.giftmessage').css('display','none');
                $('#row_' + i + ' .giftmessage').css('display','block');
                $('#row_' + 1 + ' .giftmessage').css('display');
                
                certificate.v.messageid = i;
                $('.giftheader span').text('');
                var cntOfGifts = 0 ;
                if (certificate.v.dataX.length > 1) {
                    for (var ii = 0; ii < certificate.v.dataX.length; ii++) {
                        if ($('#cert_' + ii + '_Gift').val() === '1' || $('#cert_' + ii + '_Gift').val() === 1) {
                            cntOfGifts++;
                        }
                    }

                    if (cntOfGifts > 1) {
                        $('.giftheader span').text(i+1);
                    }
                }
                setTimeout(function() {
                    if (!$('#cert_'+i+'_Message').val().includes('Message')) {
                        $('#cert_'+i+'_Message').focus();
                    }
                    
                }, 80);
                
            }
        }
        // certificate.order.messageOpen(i);
    }, //==============================================
    messageClose: function(that) {
        if (certificate.gift.valid()) {
            $(that).parent().css('display','none');
        }
        // certificate.order.messageClose(this);
    }, //==============================================
    justUpdate: function() {
        console.log('_____________');
        for (var i = 0; i < certificate.v.dataX.length; i++) {
            certificate.v.dataX[i].first = $('#cert_' + i + '_First').val();
            certificate.v.dataX[i].last = $('#cert_' + i + '_Last').val();
            certificate.v.dataX[i].email = $('#cert_' + i + '_Email').val();
            certificate.v.dataX[i].certificate = $('#cert_' + i + '_Certificate').val();
            certificate.v.dataX[i].dvalue = $('#cert_' + i + '_Value').val();
            certificate.v.dataX[i].cnt = $('#cert_' + i + '_Cnt').val();

            certificate.v.dataX[i].gift = $('#cert_' + i + '_Gift').val();

            certificate.v.dataX[i].from = $('#cert_' + i + '_From').val();
            certificate.v.dataX[i].message = $('#cert_' + i + '_Message').val();
            certificate.v.dataX[i].hasmessage = $('#cert_' + i + '_HasMessage').val();

            certificate.v.dataX[i].tip = $('#cert_' + i + '_TipEach').val();
            certificate.v.dataX[i].card = $('#cardtype').val();
            certificate.v.dataX[i].esend = $('#esend').val();
            console.log(i+' Tip: '+certificate.v.dataX[i].tip);
        }
        // certificate.order.justUpdate();
    }, //==============================================
    nullFunction: function() {
        //certificate.shared.log('null');
    } //==============================================
}


certificate.objTable = function(row, cnt, tgl, tel, tgf, tef, val, items) {
    this.row = row;
    this.cnt = cnt;
    this.tgl = tgl;
    this.tel = tel;
    this.tgf = tgf;
    this.tef = tef;
    this.val = val;
    this.items = items;
}

certificate.objRow = function(par, row, val) {
    this.par = par;
    this.row = row;
    this.val = val;
    certificate.objRow.instances.push(this);
}

certificate.objRow.instances = [];
certificate.objRow.prototype.pump = function(data) {  }




certificate.objTable.prototype.tglF = function(data) { $('#'+this.tgl).text('' + data + ' '); }

certificate.objTable.prototype.telF = function() { $('#'+this.tel).text('$'+certificate.order.tipsBase+' each'); }
//certificate.objTable.prototype.tefF = function(data) { $('#'+this.tef).val(data.toFixed(2)); }
certificate.objTable.prototype.tgfF = function(data) { $('#'+this.tgf).val(data.toFixed(2)); }
certificate.objTable.prototype.updateItem = function(row,val) {
    // console.log('old: '+this.items[row].val);
    this.items[row].val = val;
    // console.log('new: '+this.items[row].val);
    // console.log('test: '+val);
    for(var i = 0;i < certificate.objRow.instances.length; i++){
        if (certificate.objRow.instances[i].par === this.row && certificate.objRow.instances[i].row === row) {
            certificate.objRow.instances[i].val = val;
        }
    }
}
certificate.objTable.prototype.processUpdatedRows = function() {
    var result = '';
    var ucnt = 0;
    for(var ii = 0;ii < this.items.length; ii++){
        if (Number(this.items[ii].val) === Number(certificate.order.tipsBaseT)) {
            this.items[ii].val = certificate.order.tipsBase;
            result += '' + certificate.order.tipsBase.toString() + ',';
            ucnt++;
        } else {
            result += '' + this.items[ii].val.toString() + ',';
        }
        
    }
    // certificate.order.dump();
    result += 'END';
    result = result.replace(',END','').replace('END','');



    var cntX = certificate.v.dataX[this.row].gcnt;
    console.log(this.row+' count: '+cntX);
    if (cntX > 1) {
    // if (Number($('#'+this.cnt).val()) > 1) {
        $('#'+this.tef).val(''+result+'');
    } else {
        $('#'+this.tef).val(result);
    }
    // console.log(this.items.length +' === '+ ucnt);
    if (this.items.length === ucnt) {
        this.telF()
        $('#'+this.tgl).text('');
    } else {
        $('#'+this.tgl).text('' + result + '');
        $('#'+this.tel).text('');
    }
    
    
}



// certificate.v.loader = '<div id="loading"><img src="images/dance.gif"></div>';
certificate.v.loader = '<div id="loading"><img src="images/gears.gif"></div>';
certificate.v.tipID = '';
// setTimeout(function(){}, 2000);




// $('#order').removeAttr('disabled');
// certificate.order.disable = true;
// $('#order').attr('disabled','disabled')

// certificate.order.objTipsTable
// certificate.order.tipsBase

certificate.v.preval = true;
certificate.gift = {
    process: function() {
        return false;
        certificate.v.preval = true;
        
        if (certificate.gift.valid()) {
            $("#transfer").submit();
        }

    }, //==============================================
    status: function() {
    }, //==============================================
    valid: function() {
        certificate.v.preval = true;
        var valid = true;
        var i = certificate.v.messageid;
        var messageButton = '#cert_' + i + '_MessageLabel';
        
        // var giftField = 'cert_' + i + '_Gift';
        // var hasmessage = '#cert_' + i + '_HasMessage';
        // if ($(hasmessage).val() === 1 || $(hasmessage).val() === '1') {
            try {
                var item = '#cert_' + i + '_Message';

                if ($(item).val().length && !$(item).val().includes('Message')) {
                    $(item).css('border-color','');
                } else  {
                    $(item).css('border-color','crimson');
                    valid = false;
                }
                var item = '#cert_' + i + '_From';
                if ($(item).val().length && !$(item).val().includes('From Name')) {
                    $(item).css('border-color','');
                } else  {
                    $(item).css('border-color','crimson');
                    valid = false;
                }
                if (valid) {
                    $(messageButton).parent().css('border-color','');
                } else {
                    $(messageButton).parent().css('border-color','crimson');
                }
            } catch (err) {}
        // }
        return valid
    }, //==============================================
    initiateTest: function() {
        $('#order').val('9999');
        $('#totaltip').val('1000');
        $('#count').val('8');
        $('#processButton').click();
        setTimeout(function() {
            $('#contactAddButton').click();
            $('#contactAddButton').click();
            setTimeout(function() {
                $('#cert_1_Cnt').val('3');
                certificate.order.processUpdatedRows();
            }, 800);
        }, 100);

        // certificate.gift.initiateTest();
    }, //==============================================
    nullFunction: function() {
        //certificate.shared.log('null');
    } //==============================================
}
// setTimeout(function() {  }, 800);
// setTimeout(function() { certificate.gift.initiateTest(); }, 200);



setTimeout(function(){
    // if (location.href.includes('new_index')) {
        $('#orderBody').css('text-align','left');
        $('.certItem').css('display','block');
        $('#esendparent').css('display','none');
        $('#giftchild').css('display','none');
        console.log('_____________');
        certificate.gift.initiateTest();
        setTimeout(function() { certificate.order.justUpdate(); }, 200);
        
    // }
}, 800);



