// JavaScript to fill in the left nav with h1 element content for product page menus

function write_h1() {
	
	//only do stuff if h1 exists...
	if (document.body.getElementsByTagName("h1").length > 0) {
		var h1_value = document.body.getElementsByTagName("h1")[0].firstChild.nodeValue; //ex: Hydrotite Construction Joint Profiles
		
		var string = h1_value; //create string variable equal to h1_value
	
		//var str = h1_value.replace(/ /g,"<br />"); //hackish solution of replace spaces with html breaks
	
		var space_search = h1_value.search(/ /i);//store the location of the first space in space_search
	
		if(h1_value.length > 14 && space_search >= 0) {
			//test to see if h1 content length is greater than or equal to 15 characters long, 
			//and if space_search == a non zero number (true) -- meaning h1_value contains space characters
		
			var h1_words = new Array(); //create a new array
		
			//first, split array by space character, storing each word in separate array element h1_words
			h1_words = h1_value.split(" ");
		
			var counter = 0;
		
			//test length of first word, if <= 14, replace string variable value
			if(h1_words[counter].length <= 15) { 
				string = h1_words[counter];
			}
			//if first word is > than 15 chars
			else {
				//store first 15 characters in string, followed by a break, then the rest of the word
				string = h1_words[counter].slice(0, 16); //store first 15 chars to string
				string += '<br />'; //add a break
				string += h1_words[counter].slice(16, -1); //store last chars to string
			}
		
			var line_length = string.length;
		
			var br_search = h1_value.search(/>/i);//store the location of the first >, if there is one
		
			//if a br is found (since first word was > than 15 chars...
			if(br_search >= 0){
				br_position = string.lastIndexOf(">") + 1;
				line_length -= br_position; //subtract br_position from line_length to get length of newest line (characters after most recent > character)
			}
		
			++counter; //increment counter, start loop with h1_words[1]
		
			while(counter < h1_words.length) {
				if(h1_words[counter].length + line_length <= 14) {
					//first add space to end of current string and add next word
					string = string + ' ' + h1_words[counter];
				
					line_length += h1_words[counter].length + 1; //reset line_length now that characters have been added to string
				}
				else {
					//if h1_words[1].length + line_length > 14, put a break in the string, and then add h1_words[1]
					string = string + '<br />' + h1_words[counter];
				
					line_length = h1_words[counter].length; //reset line length to number of chars after <br />
				}
				++counter; //duh
			}
		}
		//write the string
		document.write(string);
	}
}		