/*

Usage of the glossary:

- Fetch a list of keywords from URL. Must be sorted
- Pass the keywords to process function for a given element or list of elements
- Upon rolloever examine 'rel' or 'id' parameter and pull in content or
- Give glossary a key url and have it append content to a given element




*/


var Glossary;
if (!Glossary) {
    Glossary = {};
}

RegExp.escape = function(str)
{
    var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
    return str.replace(specials, "\\$&");
}
// Parse through the passed HTML
// y= html
// _= keyword

/**
 * Process HTML for glossary terms
 * 
 * This function operates as a final state machine and scans through the
 * text/html provided for keywords provided replacing them with markup
 * to trigger appearance and behavior on roll over
 *
 * @param string html - the html string to parse
 * @param array keywords - and array of strings for keywords
 * @param string template - a string template to replace the matched keywords with
 *      The string template may contain tags that themselves will be replaced with
 *      properties determined by this scanner:
 *      {match} - replaces with the matched content
 *
 */
Glossary.process=function(html,keywords,options,template)
{
	
	// parameter defaults
	html= html || '';
	keywords = keywords || [];
	template = template || '<a href="#" target="blank" class="glossary-term" rel="glossy-definition-{id}">{match}</a>';
	options  = options || {};
	
	defaults = {	   
	   match_all : false,
	   match_case: false
    };
	
	for (prop in defaults) {
	   if(options[prop]=='undefined') {
	       options[prop]==defaults[prop];
	   }
	}

	var rules=[]; // array of regular expressions to help match the keywords

	var stoptags  = new RegExp('^(script|style|textarea|a|span)','gi'); // element tags tags to exclude by regex (was u)
	var skiptag   = false; // flag of whether we matched a stoptag (was t)
	
	var seek_from = 0;  // start next search at this position (was q)
	var seek_to   = 0;  // positon of next match
	var seek = '<' // what to find next (alternates between '<' and '>' (was r)
	
	var chunk  = null; // the currently found text (without tags)
	var result = ''; // the resulting html
	var placeholders=[];
	
	// prepare regular expressions for every key word
    for(var i=0; i < keywords.length; i++)
	{
		if(keywords[i]) {
		    // \b means boundary and ensure matching of whole words
		    var mod = keywords[i].term.charAt(0) == '(' ? '' : '\\b';
		    var rule = {
        	   keyword: keywords[i].term,
        	   id: keywords[i].id,
        	   //rule: new RegExp("\\b("+keywords[i].term+")\\b",  '' + (options.match_case ? '': 'i') )
        	   rule: new RegExp(mod+"("+RegExp.escape(keywords[i].term)+")\\b",  '' + (options.match_case ? '': 'i') )
            }
            rules.push(rule); 
		    //console.log(rule);	
		}
	}
	
	
	while(seek_from >= 0) // loop forever unless reset
	{
		// the first position of an open bracket
		var seek_to = html.indexOf( seek, seek_from);
		
		if(seek_to < 0) {
		    // no more starting or end tags after this. reset seek_from (last run around loop). chunk becomes the rest of this content
			chunk = html.substring(seek_from);
			seek_from = -1;
		}
		else
		{
		    // script tag detected. chunk becomes everything from last position postion to the found '<'
		    // seek_from is increment to continue search after '<' in the next loop 
			chunk = html.substring( seek_from, seek_to);
			seek_from = seek_to+1;
		}
		
		
		if(seek == '<') // we searched an opening bracket, so our string is now applicable text content
		{

			if(!skiptag) // is this a forbidden tag?
			{		
				// REPLACE ALL matching keywords with the ad content
				for(var r=0;r<rules.length;r++)
				{
						 // has this term already been matched?
						if (rules[r].matched && !options.match_all) {
						  //console.log(rules[r].keyword,' already matched. Skipping');
       					   continue;
						}
						
						
						// construct the text for a title tag
						title_text='Title'; //AdV.t[ad_pos]+'##'+AdV.d1[ad_pos]+'##'+AdV.d2[ad_pos]+'##'+AdV.du[ad_pos]+'##'+AdV.Y[ad_pos]+'##'+rules[r];
						// convert the regex to a string
						var string1=rules[r].rule+"";
						// anyway gblkeywords just constructs a string that executes on mouse over and click to count views and clicks
						// var gblkeywords=string1.substring(string1.indexOf('(')+1,string1.lastIndexOf(')'));
					
						
						// exclude boundaries that are hyphens, meaning the term cannot be precede or followed by hyphen. \\b considers hyphens
						var match_pos = chunk.search(rules[r].rule);
                        if (chunk.charAt(match_pos-1)=='-' ||  chunk.charAt(match_pos+ rules[r].keyword.length) =='-') {
                            continue;
                        }
                         
                        // set a match
                        rules[r].matched=match_pos != -1;

                        if (match_pos != -1) {
                            rules[r].matched=true;
    						var tpl   = template.replace('{match}', chunk.substr(match_pos,rules[r].keyword.length)).replace('{id}',rules[r].id);
    						
    						// to avoid rematches of partials, we replace with a counter
    						var ph = ':::'+ new Date().getTime() +'-' + rules[r].id + ':::';
    						placeholders[ph]=tpl;

    						var chunk = chunk.replace(rules[r].rule , ph);
                            
                        }
                        
						
						// chunk=chunk.replace(rules[r],"<a href=\""+AdV.Y[ad_pos]+ "\" onMouseOver=\"sendViewInfo('"+AdV.Y[ad_pos]+"','"+gblkeywords+"')\" onclick=\"sendClickInfo('"+AdV.Y[ad_pos]+"','"+gblkeywords+"')\" target=\"_blank\" class=\"toolTip\"  title=\""+title_text+"\">$1</a>");					
						
				}
			}
			else // set t to false
			{
				skiptag=false;
            }
		}	
		
		// if we didn't search an opening bracket then, are we looking at an excluded tag?
		else if(chunk.match( stoptags ))
		{
		    // don't do replacements the next time through
			skiptag=true;
		}
		
		result += chunk + (seek_to < 0 ? '' : seek);  // save the modified content into e
		seek    = seek == '<'?'>':'<'; // alternate between opening and closing brackets
	}
	
    for (placeholder in placeholders) {
        // console.log(placeholder);
       result=result.replace(placeholder,placeholders[placeholder]);
    }
	return result; // return the resulting html
}


