﻿function countCharsUp(control) {
    var textCtrl = $get('charCounterText');
    if (textCtrl) {
        var charLeft = countCharsLeft(control);
        if (charLeft >= 0) {
            textCtrl.innerHTML = charLeft + ' character(s) left';
            textCtrl.style.color = 'Gray';
        }
        else {
            textCtrl.innerHTML = 'Entered text is too long - truncated to ' + MaximumNumberOfCharacters + ' characters!'
            control.value = control.value.substr(0, MaximumNumberOfCharacters);
            textCtrl.style.color = 'Red';
        }
    }
    return true;
}

function countCharsDown(e, control) {
    if (countCharsLeft(control) <= 0) {
        killEvent(e);
    }
    return true;
}

function countCharsLeft(control) {
    var maxSize = MaximumNumberOfCharacters;
    return maxSize - (control.value ? control.value.length : 0);
}

function killEvent(e) {
    if (typeof (e) == "undefined") {
        if (typeof (event) != "undefined")
            e = event;
    }
    if (e.keyCode >= 32 || e.keyCode == 13 || e.keyCode == 9) {
        if (e && e.preventDefault) {
            e.preventDefault();
        }
        else if (e) {
            e.returnValue = false;
        }
    }
}

function cleanUpDataEntry(control, storageDest) {
    var HTMLRegExp = new RegExp('<(.|\n)+?>', 'g');
    //var dest = $get('<%# addlVehicleDetailsInput.ClientID %>');
    var dest = $get(storageDest);
    var saved = control.value;


    //if (typeof(control.value) != "undefined" && dest != null)
    if (control != null && dest != null) {
        control.value = control.value.replace(HTMLRegExp, '');
        dest.value = control.value;
        if (dest.value != saved) {
            if (Vehix_InfoBox)
                Vehix_InfoBox.show('sampledescription', 'encodingwarning');
        }
        else {
            var openElement = new RegExp('<[A-Z,a-z,0-9]', 'g');
            control.value = control.value.replace(openElement, '');
            dest.value = control.value;
            if (dest.value != saved) {
                if (Vehix_InfoBox)
                    Vehix_InfoBox.show('sampledescription', 'encodingwarning');
            }
        }
    }

    return countCharsUp(control);
}
