﻿// JScript File
//Copied from APlus - CharactersRemaining.inc

/**
 * global variables used to keep track if items durring timouts
 **/
var span_timeout = null;
var max_timeout = null;
var field_timeout = null;

/**
 * checks to see if keycode is valid and if char count is less than max chars.
 * i used a timeout in this instance to make sure if the user highlights text
 * and hits the delete key, that all the text deleted is accounted for.
 * the first conditions (key code == 8 or 46) handles delete keys and will return
 * true no matter what.
 * the second condition checks to see if you have obtained max chars, if not, return true
 * the final condition checks for arrow keys and returns true no matter what.
 **/
function checkMaxChars(field, e, span, max){
	span_timeout = span;
	max_timeout = max;
	field_timeout = field;
	if(e == null){
		updateSpan(field, span, max);
		return false;
	}
	var key_code = getKeyCode(e);
	if((key_code == 8 || key_code == 46) || (field.value.length < max) || (key_code <= 40 && key_code >= 37)){
		setTimeout("updateSpan(field_timeout, span_timeout, max_timeout)", 1);		
		return true;
	}else{
		return false;
	}
}

/** 
 * Updates the span, if some how the char count is over max chars (copy and paste with mouse)
 * the span is turned red and a warning is provided to the user. After this, only arrow keys
 * and delete keys can be used until the chars remaining is under or at char max.
 **/
function updateSpan(field, span, max){
	if(field.value.length > max){
		span.innerHTML = "<font color='RED'>" + (max - field.value.length) + " Character(s) Remaining</font>";	
	}else{
		span.innerHTML = (max - field.value.length) + " Character(s) Remaining"
	}
}

function getKeyCode(e){
	if(window.event){
		return window.event.keyCode;
	}else if(e){
		return e.which;
	}else{
		return -1;
	}
}


