/**
 * Performs a Flesch-Kincaid readability test on the selection text
 * http://en.wikipedia.org/wiki/Flesch-Kincaid_Readability_Test
 *
 * Based on the TextStatistics PHP library
 * http://code.google.com/p/php-text-statistics/
 * 
 * Released under New BSD license
 * http://www.opensource.org/licenses/bsd-license.php
 * 
 * Greatly simplified and ported to JavaScript by Trevor Parscal
*/
$.fn.fleschGradeLevel = function() {
	function averageWordsPerSentence(text) {
		var sentences = text.replace(/[^\.!?]/, '').length;
		var words = text.replace(/[^ ]/, '').length;
		return words / sentences;
	}
	function averageSyllablesPerWord(text) {
		var words = text.split(' ');
		var syllables = 0;
		for (word in words) {
			syllables += countSyllables(words[word]);
		}
		return syllables / words.length;
	}
	function countSyllables(word) {
		var subsyl = [
			'cial', 'tia', 'cius', 'cious', 'giu', 'ion', 'iou', 'sia$', '.ely$'
		];
		var addsyl = [
			'ia', 'riet', 'dien', 'iu', 'io', 'ii', '[aeiouym]bl$',
			'[aeiou]{3}', '^mc', 'ism$', '([^aeiouy])\1l$', '[^l]lien',
			'^coa[dglx].', '[^gq]ua[^auieo]', 'dnt$'
		];
		// Based on Greg Fast's Perl module Lingua::EN::Syllables
		word = word.toLowerCase().replace(/[^a-z]/i, '');
		var wordParts = word.split(/[^aeiouy]+/);
		var validWordParts = [];
		for (wordPart in wordParts) {
			if (wordParts[wordPart] !== '') {
				validWordParts.push(wordParts[wordPart]);
			}
		}
		var syllables = 0;
		// Thanks to Joe Kovar for correcting a bug in the following lines
		for (syl in subsyl) {
			var subsyls = word.match('~' + subsyl[syl] + '~');
			syllables -= subsyls !== null ? subsyls.length : 0;
		}
		for (syl in addsyl) {
			var addsyls = word.match('~' + addsyl[syl] + '~');
			syllables += addsyls !== null ? addsyls.length : 0;
		}
		if (word.length == 1) {
			syllables++;
		}
		syllables += validWordParts.length;
		return syllables == 0 ? 1 : syllables;
	}
	var text = $(this).text();
	return (
		(0.39 * averageWordsPerSentence(text)) +
		(11.8 * averageSyllablesPerWord(text)) -
		15.59
	);
}
/**
 * @author "Trevor Parscal" <trevorparscal@gmail.com>
 * @license CC0 1.0 Universal - http://creativecommons.org/publicdomain/zero/1.0
 */
// Provide a way to get back to the indicator in the statusbar
var $readingLevelIndicator = null;
// Add the indicator with a meter and label to the statusbar
jetpack.statusBar.append({
  html: '<div id="reading-level-indicator"><div class="meter"></div>' +
  		'<div class="label"></div></div>',
  width: 100, // 94px wide with 2px left and right margins and 1px borders
  onReady: function(doc) {
  	$readingLevelIndicator = $(doc).find('#reading-level-indicator');
    $readingLevelIndicator.css({
      	height: '14px',
      	width: '94px',
      	margin: '2px',
      	marginTop: '4px',
      	backgroundColor: 'transparent',
      	border: 'solid 1px #555555'
    });
    $readingLevelIndicator.find('.meter').css({
    	position: 'absolute',
      	height: '14px',
      	width: '0px',
      	backgroundColor: 'white'
      })
    $readingLevelIndicator.find('.label').css({
    	position: 'absolute',
      	height: '12px',
      	width: '86px',
      	color: 'black',
      	fontSize: '10px',
      	marginTop: '1px',
      	marginLeft: '2px',
      	marginRight: '2px',
      	overflow: 'hidden',
      	textShadow: 'rgba(255, 255, 255, 0.25) 1px 1px 0',
      	cursor: 'default'
      })
  }
});
function updateReadingLevelIndicator() {
	var contentDocument = this.contentDocument;
	var $meter = $readingLevelIndicator.find('.meter');
    var $label = $readingLevelIndicator.find('.label');
	$meter.css({'opacity': 0, 'width': 0});
	function showMeter() {
		grade = Math.round(contentDocument.readingLevel);
		switch (grade) {
			case 1: grade += 'st'; break;
			case 2: grade += 'nd'; break;
			case 3: grade += 'rd'; break;
			default: grade += 'th'; break;
		}
		$label.text(grade + ' grade level');
		$meter.animate({
			opacity: 1,
			width: (Math.min(contentDocument.readingLevel, 10) * 9) + 'px'
		});
	}
	if (contentDocument.readingLevel == undefined) {
		var $text = $(contentDocument).find('p');
		if ($text.size()) {
			$label.text('Calculating...');
			setTimeout(function() {
				contentDocument.readingLevel = $text.fleschGradeLevel();
				showMeter();
			}, 1);
		} else {
			$label.text('No valid text');
			contentDocument.readingLevel = null;
		}
	} else if(contentDocument.readingLevel == null) {
		$label.text('No valid text');
	} else {
		showMeter();
	}
}
jetpack.tabs.onFocus(updateReadingLevelIndicator);
jetpack.tabs.onReady(updateReadingLevelIndicator);

