﻿
if (document.createStyleSheet) {
    document.createStyleSheet('/Content/Styles/CharacterCounter/CharacterCounter.css');
}
else {
    var newSS = document.createElement('link');
    newSS.rel = 'stylesheet';
    newSS.type = 'text/css';
    newSS.href = '/Content/Styles/CharacterCounter/CharacterCounter.css';
    document.getElementsByTagName('head')[0].appendChild(newSS);
}

function attachCSS(cssFile) {
    try {
        document.getElementsByTagName('head')[0].appendChild(cssFile);
    }
    catch (e) {
        setTimeout(function() { attachCSS(cssFile) }, 100);
    }
}

function counterSetup(fieldName, maxlimit) {   
    //Add the function to the field
    var field = document.getElementById(fieldName);
    field.onkeydown = function() { textCounter(fieldName, maxlimit) };
    field.onkeyup = function() { textCounter(fieldName, maxlimit) };
    field.onclick = function() { textCounter(fieldName, maxlimit) };

    //Create the character counter
    var newCC = document.createElement('input');
    newCC.id = 'remLen' + fieldName;
    newCC.name = 'remLen' + fieldName;
    newCC.className = 'CharacterCounter';
    newCC.setAttribute('class', 'CharacterCounter');
    newCC.type = 'text';
    newCC.value = maxlimit;
    newCC.size = 4;
    newCC.maxlength = 4;
    field.parentNode.appendChild(newCC);
}

function textCounter(fieldName, maxlimit) {
    var field = document.getElementById(fieldName);
    var fieldLength = document.getElementById('remLen' + fieldName);

    if (field.value.length > maxlimit) {
        // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    }
    else {
        // otherwise, update 'characters left' counter
        fieldLength.value = maxlimit - field.value.length;
    }
}
