// JavaScript Document
$(function(){  //Form ready for manipulation

   //alert("charCount.js");
   /*************************************************************************
   ************* Limit and display characters left in a text field *********
   *************************************************************************/
  //Update the count when user types in the form
   $('textarea[maxlength]').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));

		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}else{
            var curr_length = $(this).val().length;
            
            if(curr_length >= max-50 && curr_length < max-15){
                //Change text color to yellow
                //console.log('yellow');
                $(this).parent().find('.charsRemaining').find('span').css('color', '#FFD800');
            }else if(curr_length >= max-15){
                //Change text color to red
                //console.log('red');
                $(this).parent().find('.charsRemaining').find('span').css('color', 'red');
            }else{
                $(this).parent().find('.charsRemaining').find('span').css('color', 'green');
            }
        }

		$(this).parent().find('.charsRemaining').find('span').text(max - $(this).val().length);
	});

    //Update the count when the page loads
    $('textarea[maxlength]').each(function(){
        var startCount = $(this).val().length;
        var max = parseInt($(this).attr('maxlength'));

        var curr_length = $(this).val().length;

        if(curr_length >= max-50 && curr_length < max-15){
            //Change text color to yellow
            //console.log('yellow');
            $(this).parent().find('.charsRemaining').find('span').css('color', '#FFD800');
        }else if(curr_length >= max-15){
            //Change text color to red
            //console.log('red');
            $(this).parent().find('.charsRemaining').find('span').css('color', 'red');
        }
        
        $(this).parent().find('.charsRemaining').find('span').text(max-startCount);

    });
    //end of character warning code

}); //end document ready function
