/*
	d_heading: a.k.a. Dynamic Heading (purposely ambiguous so it's not too obvious to savvy surfers)
	This file contains a set of javascript functions that parse out terms in the user's query and
	constructs a custom headline that matches the users search.  There exist various dynamic rules/settings
	that can be toggled on/off to customize the keywords in a user's search that the dynamic headline
	responds to (see constructDynamicSplashHeading()).
*/

/* Calls "getDynamicHeading()" and places the generated heading into
	an element with the given id.  The last three parameters are boolean
    values used to toggle each dynamic rule/setting on or off (1-3 in order).	*/
function insertDynamicHeading(element_id, useDynamicVerb, useDynamicDirectObj, useDynamicAdjective)
{
	try
	{
		var elem = document.getElementById(element_id);
		
		if (typeof(elem) != 'undefined' && elem != null) {
			elem.innerHTML = getDynamicHeading(useDynamicVerb, useDynamicDirectObj, useDynamicAdjective);
		}
	}
	catch(err)
	{
		// do nothing
	}
}

/* Gets the documents referrer, extracts all the parameters, uses them to generate
	a heading according to the boolean values in the rules object passed in. */
function getDynamicHeading(useDynamicVerb, useDynamicDirectObj, useDynamicAdjective)
{	
	try
	{
		querystring = getQueryStringToUse();
		
		// Make a rules object to pass to constructDynamicSplashHeading()
		var rules = new Object();
		rules.useDynamicVerb        = useDynamicVerb;
		rules.useDynamicDirectObj   = useDynamicDirectObj;
		rules.useDynamicAdjective   = useDynamicAdjective;
		
		return constructDynamicSplashHeading(querystring, rules);
	}
	catch(err)
	{
		// do nothing
	}
}

/*  Attempt to use query from the BASEREFERER cookie, else use document.referrer  */
function getQueryStringToUse()
{
	try
	{
		var ref = GetCookie("BASEREFERER");
		if(!ref || ref.indexOf("?") < 0)
			ref = document.referrer;

		/*  Extract the query  */
		var querystring = "";
		var parameterIndex = ref.indexOf("?") + 1;
		if (parameterIndex > 0)
		{
			querystring = ref.substr(parameterIndex);
		}
		
		querystring = scrubString(querystring);
		
		return querystring;
	}
	catch(err)
	{
		// if we broke, we'll return blank
		return "";
	}
}

/* Constructs a grammatically correct heading based on search keywords.  This should
	probably be moved to splash.dll if we go with it on a non-test basis.
	NOTE: The data should be scrubbed of all non-standard characters and punctuation.  Spaces
    are acceptable.	*/
function constructDynamicSplashHeading(querystring, rules)
{
	try
	{
		/*
			// These variables define the default grammatical articles used.  They should probably match the default heading, since these words will form
			// the default heading template when search terms are present.
		*/
		var staticText = " and Get Found by Customers";
		var defaultDirectObject = " Website"
		
		var actionVerb = "Get";                                              // To replace the first verb in the default heading
		var articles = " a", directObject = defaultDirectObject;             // Leaving in 'articles' for later expansion
		var primaryOptionAdjective = "", secondaryOptionAdjective = " FREE"   // Adjectives for the heading (secondaryOptionAdjective 
																			 // can be changed for later expansions)
			
		/*  Default Heading */
		var heading = generateHeadline(actionVerb, articles, secondaryOptionAdjective, primaryOptionAdjective, directObject, staticText);
		
		if (querystring && rules)
		{
			/*
				// Rule 1
				// Fill in the user preferred action verb regardless of tense
				// ex: "creat" -> "create", "creating", "creator"
			*/
			if(rules.useDynamicVerb)
			{
				if (querystring.match(/\bbuild/))
					actionVerb = "Build";
				else if (querystring.match(/\bcreat/))
					actionVerb = "Create";
				else if (querystring.match(/\bmak/))
					actionVerb = "Make";
				else if (querystring.match(/\bdesign/))
					actionVerb = "Design";
			}
			
			/*
				// Rule X (not used)
				// Find the user defined articles.  As you can well see, this really doesn't
				// make much of a difference now.  I'm leaving it in for easy expansion
				// later.
				if (querystring.search("own") > -1)
					articles = " your own";
			*/
			
			/*
				// Rule 2
				// Fill in the user preferred direct object
			*/
			if(rules.useDynamicDirectObj)
			{
				directObject = getDirectObject(querystring, directObject);
			}
			
			/*
				// Rule 3
				// Fill in an adjective that modifies the direct object, if we find a match
			*/
			if(rules.useDynamicAdjective)
			{
				if (querystring.match(/\bpersonal\b/))
					primaryOptionAdjective = " Personal";
				else if (querystring.match(/\bbusiness\b/))
					primaryOptionAdjective = " Business";
			}
			
			/*
				// Rule XX
				// Fill in these higher priority business-related adjectives.  These take
				// precedence over an adjective filled in rule 3.  Leaving this in for
				// easy expansion later.
				if(rules.useDynamicBusinessRef)
				{
					if (querystring.search(/small\s+business/) > -1 || querystring.search("smallbusiness") > -1)
						secondaryOptionAdjective     = " Small Business";
					else if (querystring.search(/home\s+business/) > -1 || querystring.search("homebusiness") > -1)
						secondaryOptionAdjective     = " Home Business";
				}
			*/
			
			/*
				// Define the maximum length of the heading based on the context in which it will appear (a.k.a. how long can the heading
				// be before it breaks page layout).
			*/
			var max_heading_length = 55;
			
			/*
				// Build the dynamic heading.  If the heading is too long, we will 
				// try to shorten it to make it fit.  Start removing rules in the order:
				// four, three, two.
			*/
			heading = generateHeadline(actionVerb, articles, secondaryOptionAdjective, primaryOptionAdjective, directObject, staticText);
			if (heading.length > max_heading_length) {
				/* Lets get rid of rule 3 */
				primaryOptionAdjective = "";
				
				heading = generateHeadline(actionVerb, articles, secondaryOptionAdjective, primaryOptionAdjective, directObject, staticText);
				if (heading.length > max_heading_length) {
					/* Get rid of rule 2. */
					directObject = defaultDirectObject;
					
					heading = generateHeadline(actionVerb, articles, secondaryOptionAdjective, primaryOptionAdjective, directObject, staticText);
				}
			}
		}
		return heading;
	}
	catch(err)
	{
		// return something reasonable
		return "Get a Website and Get Found by Customers";
	}
}

/* Given a verb, articles, adjective, object, and static Text, this function
      generatees a grammatically correct headline. */
function generateHeadline(verb, articles, secondaryAdjective, primaryAdjective, object, staticText)
{
	return (verb + articles + secondaryAdjective + primaryAdjective + object + staticText);
}

function convertTitleCase(value) 
{
	return value.charAt(0).toUpperCase() + value.substring(1);
}

/* This function removes all non-alphanumeric characters from a string
	NOTE: it also converts the string to lower case in the process */
function scrubString(s)
{
	// To properly put spaces in the place of %20's
	s = s.replace(/%20/g," ");
		
	// make it lower case so we don't have to do case-insensitive matching later
	s = s.toLowerCase();
	
	// we're never going to care about non alpha-numeric characters, so let's get rid of them
	s = s.replace(/[^a-z0-9]/g, " ");
	
	return s;
}

/* Searches the query string to create the dynamic direct object. If it can't find 
	anything it likes, it will just return whatever is passed in */ 
function getDirectObject(querystring, directObject)
{
	// Check for a space/newline at the beginning and a space/endline at the end.  Just in case they
	// were spelling something different (though unlikely).
	if (querystring.match(/\bweb\s+site\b/))
		directObject = " Web Site";
	else if (querystring.match(/\bweb\s+page\b/))
		directObject = " Web Page";
	else if (querystring.match(/\bwebpage\b/))
		directObject = " Webpage";
	else if (querystring.match(/\bsite\b/))
		directObject = " Site";
	else if (querystring.match(/\bhomepage\b/))
		directObject = " Homepage";
	else if (querystring.match(/\bhome\s+page\b/))
		directObject = " Home Page";
	else if (querystring.match(/\bfrontpage\b/))
		directObject = " Frontpage";
	else if (querystring.match(/\bfront\s+page\b/))
		directObject = " Front Page";
		
	return directObject;
}

/* We have a dynamic subheadline on some PPC pages */
function getDynamicPPCSubheadline()
{
	var querystring = getQueryStringToUse();
	
	// The starting text is "Easily Start Your Fully-Customizable Website Today!", but we will provision "Start" and "Fully-Customizable"
	var verb = " Start";
	var adjective = " Fully-Customizable";
	
	// provisioning the verb.  Note that we do keep "start" in here, even though it's the default, because if they have "start" and "setup" in their string, we want to use "start"
	if (querystring.match(/\bown\b/))
		verb = " Own";
	else if (querystring.match(/\bstart\b/))
		verb = " Start"
	else if (querystring.match(/\bsetup\b/))
		verb = " Setup";
	else if (querystring.match(/\bpublish\b/))
		verb = " Publish";
	
	// provisioning the adjective
	if (querystring.match(/\bsmall\s+business\b/))
		adjective = " Small Business";
	else if (querystring.match(/\bonline\s+business\b/))
		adjective = " Online Business";
	else if (querystring.match(/\bonline\s+business\b/))
		adjective = " Home Business";
	else if (querystring.match(/\bbusiness\b/))
		adjective = " Business";
	else if (querystring.match(/\bpersonal\b/))
		adjective = " Personal";
	else if (querystring.match(/\bnon-profit\b/))
		adjective = " Non-profit";
		
	// Now we construct the final subheadline
	var subheadline = "Easily" + verb + " Your" + adjective + " Website Today!";
	
	return subheadline;
}

/* We have dynamic bullets for some PPC pages (for now only the first bullet) */
function getDynamicPPCBullet()
{
	try
	{
		var querystring = getQueryStringToUse();
		
		// The starting text is "Website in Minutes"
		var noun = "Website";
		
		// We're leveraging the same function from the splash page
		noun = getDirectObject(querystring, noun);
		
		// Now we construct the final bullet
		var bullet = noun + " in Minutes";
		
		return bullet;
	}
	catch(err)
	{
		// return something reasonable
		return "Website in Minutes";
	}
}