function wrapify(sel, maxChars, tag) {
	// For each element found by the selector
	for(var currentElement = 0; currentElement < $(sel).size(); currentElement++){
		var text = $(sel + ':eq(' + currentElement + ')').text(); // Grab the text from the selected element.
		var lines = Math.round(text.length / maxChars); // Find out how many lines we need to generate.
		var wordArray = text.split(' '); // Create an array by seperating every word using the space as a seperator.
		var totalWords = wordArray.length; // Count the array to find the amount of words
		var currentWord = 0; // Current word index, will be used later
		var html = ''; // Variable to store the html which will be returned to the browser.
		var lineString = ''; // Variable to store each lines text temporarily
		// Empty the selected elements contents
		$(sel + ':eq(' + currentElement + ')').text(' ');
		// For each line
		for(var i = 0; i < lines + 1; i++) {
			var noMoreWords = false; // Allow another word
			// If the current word isn't the last
			if (currentWord < totalWords) {
				html += '<' + tag + '>'; // Opening span tag
				// For each word, starting index number is the current word, loop until end of our words array.
				for (var index = currentWord; index < totalWords ; index++) {					
					var newWordLength = (lineString.length + wordArray[index].length) + 1; // Find out what the length of the string will be if we add another word... And space :)
					// If we've reached the limit for this line ignore
					if (!noMoreWords) {
						// If there is space for another word, add it and move to the next word else if there isn't space no more words allowed for this line.
						if (newWordLength <= maxChars) {
							lineString += wordArray[index]; // Add the current word
							lineString += ' '; // Add space after word
							currentWord++; // Next word
						}else{
							noMoreWords = true; // No more words allowed on this line (in other words do nothing until next line).
						}
					}
				}
				lineString = lineString.trim(); // Trim spaces from the end of the new string
				html += lineString; // Add line to html
				html += '</' + tag + '>'; // End span
				$(sel + ':eq(' + currentElement + ')').append(html); // Append this part of the line to our initially selected element
				html = ''; // Empty ready for next line
				lineString = ''; // Empty ready for next line
			}
		}
	}	
}

$(function () {
wrapify('.wrapify', 40, 'h3');
});

