/**
 *
 * Project Vote Smart Glossary Term Highlighter
 * Copyright 2008 Project Vote Smart
 * 
 * Auto glossary linking
 * 
 * Created: 2008-03-11 (mike)
 * 
 * Last modified:
 *  
 */

$(document).ready(function() {
        
        // Now let's get us the term list
        $.ajax({
                type: 'GET',
                url: '/xmldata/glossary.xml',
                dataType: 'text/xml',
                success: function(xml) {
                        
			var pattern_array = new Array();
                        var j = 0;
                        // Grab all the terms from the list
			// Build term regex array
                        $(xml).find('term').each(function() {
				pattern_array[j] = "(" + $(this).find('word').text() + ")(s|ing|ed)*";
				pattern_array[j] = new RegExp().compile(pattern_array[j], 'i');
				j++;
                        });
//			alert(pattern_array.toString()i+ ' ' + j);                       
			var found_pattern=-1;
                        $(".content *:not(a):not(option):not(.special):not(.hed):not(.hed_large)").each(function() { //:not(a):not(.special):not(.hed):not(.hed_large)
                                
                                if ($(this).children("*:not(br):not(hr):not(input)").size() > 0) return; 
                                if ($(this).is("xmp, pre")) return; 
                                if ($(this).is("h1, h2, h3, h4, h5")) return;
                                
			        var html = $(this).html(); 
				//searches for all patterns
				for(ii=0;ii<j;ii++){
					found_pattern = html.search(pattern_array[ii]);
					//if the pattern was found then link it
					if(found_pattern!=-1){
                                		var newhtml = html.replace(pattern_array[ii], '<a class="glossary" title="Define: $1" href="/glossary/define.php?term=$1" onclick="window.open(\'/glossary/define.php?term=$1\', \'Glossary\', \'menubar=yes,location=no,resizable=yes,scrollbars=yes,status=no,height=200,width=500\'); return false;">$1$2</a>');
                               			$(this).html(newhtml);
			       			var html = $(this).html();
						//remove pattern found so that it is not glossed multiple times 
						for(jj=0;jj<j;jj++){
							if(jj>=ii){
								if((jj+1)!=j)
									pattern_array[jj] = pattern_array[jj+1];
							}
						}
						j--;
//						alert(pattern_array.toString()+ ' ' + j);                       
						//set one back to search newly shifted pattern
						ii--;
                               		}
				}
                        });
                }
        });
        
});
