//create enumerations for possible header types, themes and languages
/*
function Enums()
{
   //There is no sense instansiating Enums
   throw Error.notImplemented();
}
Enums.HeaderTypes = {main_site:0, location_specific:1, jump_page:2};
Enums.HeaderThemes = {dm:0, fda:1, mp:2};
Enums.HeaderLangs = {en:0, es:1, fr:2};
*/	


//note that "class" is a reserved word in IE

//adds a css class to the target
function add_class(target, new_class)
{
	//Check to see if the target already has the class. If it does,
	//we don't need to add it.
	if(target.className.indexOf(new_class) == -1)
	{
		target.className += " " + new_class;
	}

}

//removes a css class from the target
function remove_class(target, class_to_remove)
{
	target.className = target.className.replace(class_to_remove,"");
}

//replaces a css class on the target with a new css class
function replace_class(target, old_class, new_class)
{
	target.className = target.className.replace(old_class, new_class);
}


function text_large()
{
	add_class(document.body, "large");
	create_cookie("dm20_text_size", "large", 365);
}

function text_normal()
{
	remove_class(document.body, "large");
	create_cookie("dm20_text_size", "normal", 365);	
}


function create_cookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function read_cookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}





////////////////////
//Javascript string 
////////////////////

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}





/****************************************************************************
set_locale changes the locale.
****************************************************************************/
function set_locale(locale, environment)
{
	if(environment == 'PREVIEW')
	{
		add_or_replace_url_var('locale', locale);
	}
	else
	{
		//alert(document.location.href);
			
		if (document.location.href.indexOf("en_US") != -1)
		{
			document.location.href = document.location.href.replace("en_US", locale);
		}
		else if (document.location.href.indexOf("es_US") != -1)
		{
			document.location.href = document.location.href.replace("es_US", locale);
		}
		else if (document.location.href.indexOf("fr_CA") != -1)
		{
			document.location.href = document.location.href.replace("fr_CA", locale);
		}
		else
		{
			//The home page doesn't use the locale-baked-into-path method (on our end it's just dmlive.tuesday.com)
			//This gets around that by appending the locale to the path so that the URL rewriter can work with it.
			var str = document.location.href + locale + "/";
			str.replace("#", "");
			str.replace("//", "/");
			document.location.href = str;
		}
	}
}


/****************************************************************************
The following functions change the URL's variables
****************************************************************************/
function add_or_replace_url_var(name, value)
{


	//alert(strip_anchor_from_url(document.location));

	//Is the var already set?
	if (document.location.href.indexOf(name + "=") == -1)
	{
		var anchor 				= get_anchor_from_url(document.location.href);
		var anchorless_href 	= strip_anchor_from_url(document.location.href);


		//is there a question mark in the url?
		var delimiter = "";
		if (document.location.href.indexOf("?") == -1)
		{
			delimiter = "?";
		}
		else
		{
			delimiter = "&";
		}

		//Create the new url with the var added onto the end
		var new_url = anchorless_href + delimiter + name + "=" + value + anchor;

		//Add the new var onto the end
		document.location.href = new_url;
	}
	else
	{
		//Is it in there as an ampersand var or a question mark var?
		var delimiter = "";
		var location = document.location.href.indexOf("&" + name + "=");
		if (location == -1)
		{
			delimiter = "?";
		}
		else
		{
			delimiter = "&";
		}


		//Get the URL variables
		var hash = get_url_vars();

		//replace the current var with the new var in the location href
		var current_var 	= delimiter + name + "=" + hash[name];
		var new_var 		= delimiter + name + "=" + value;

		document.location.href = document.location.href.replace(current_var, new_var);
	}
}



// Read a pages GET URL variables and return them as an associative array.
function get_url_vars()
{
	var anchorless_href = strip_anchor_from_url(window.location.href);

	var vars = [], hash;
	var hashes = anchorless_href.slice(anchorless_href.indexOf('?') + 1).split('&');

	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		//vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

function get_anchor_from_url(url)
{
	//Does it contain a hashmark?
	var anchor_pos = url.indexOf("#");


	if (anchor_pos == -1)
	{
		return "";
	}


	var ret = url.substring(anchor_pos-1)
	return ret;
}



function strip_anchor_from_url(url)
{
	//ensure that it is a string
	var my_url = url + " ";

	//Does it contain a hashmark?
	var anchor_pos = my_url.indexOf('#');
	if (anchor_pos == -1)
		return url;
	else
		return my_url.substring(0, anchor_pos);
}




/****************************************************************************
Prints a sub-nav-item. Used on Press Room, Veterans and possibly other sections.
****************************************************************************/
function print_sub_nav_item(link_dest, link_body, current_page, force_highlight)
{

	//Should this link be highlighted (and not clickable?)
	//If we are forcing highlight on this link, then yes obviously.
	//Also, we want the link to be highlighted if the current page is the same as the link's destination.
	//The link_dest looks like this, since we get it from $PAGE_LINK[section_name/page_name]: "/7d9d7292n9fr8262bd/section_name/pagename_name.page"
	//The current_page looks like this, since we get it from $CONTEXT{pageName}: "section_name/page_name"
	//So, we check if longer one (link_dest) contains the shorter one (current_page).
	if (force_highlight || link_dest.indexOf(current_page) != -1)
	{
		document.write("<span class=\"sub_nav_selected\">" + link_body + "</span>" );
	}
	else
	{
		document.write("<a class=\"sub_nav_link\" href=\""  + link_dest + "\">" + link_body + "</a>");
	}
}



/****************************************************************************
Prints a link.
<script>print_link("$PAGE_LINK[.]", "index", "Home Page");</script>
****************************************************************************/
function print_link(page_link_dot, concat_path, link_body)
{
	//Get the location of the last slash
	var loc = page_link_dot.lastIndexOf("/");
	
	//Get the substring up to the last slash.
	var base = page_link_dot.substring(0, loc);
	
	//Get the final path
	var final_path = base + '/' + concat_path + ".page";
	
	//Write out a link tag
	document.write("<a href=\"" + final_path + "\">" + link_body + "</a>");
}





/****************************************************************************
Pretty-Prints XML
****************************************************************************/
function xml_dump(xml) 
{
	document.write
	(
		format_xml(xml).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;")
	);
}



/****************************************************************************
Pretty-Prints XML
****************************************************************************/

function format_xml(xml)
{
	var reg = /(>)(<)(\/*)/g;
	var wsexp = / *(.*) +\n/g;
	var contexp = /(<.+>)(.+\n)/g;
	xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
	var pad = 0;
	var formatted = '';
	var lines = xml.split('\n');
	var indent = 0;
	var lastType = 'other';
	
	
	// 4 types of tags - single, closing, opening, other (text, doctype, comment) - 4*4 = 16 transitions 
	var transitions = 
	{
	    'single->single'    : 0,
	    'single->closing'   : -1,
	    'single->opening'   : 0,
	    'single->other'     : 0,
	    'closing->single'   : 0,
	    'closing->closing'  : -1,
	    'closing->opening'  : 0,
	    'closing->other'    : 0,
	    'opening->single'   : 1,
	    'opening->closing'  : 0, 
	    'opening->opening'  : 1,
	    'opening->other'    : 1,
	    'other->single'     : 0,
	    'other->closing'    : -1,
	    'other->opening'    : 0,
	    'other->other'      : 0
	};

	for (var i=0; i < lines.length; i++) 
	{
		var ln = lines[i];
	    
		//Does this line look like this: "foobarbaz</tag>"
		//If so, add it to the previous line. Makes for nicer looking XML!
		if (ln.match(/.+<\/.+>/))
		{
			formatted += ln;
			indent -=1;
		}
		else
		{
			var single = Boolean(ln.match(/<.+\/>/)); // is this line a single tag? ex. <br />
			var closing = Boolean(ln.match(/<\/.+>/)); // is this a closing tag? ex. </a>
			var opening = Boolean(ln.match(/<[^!].*>/)); // is this even a tag (that's not <!something>)
			var type = single ? 'single' : closing ? 'closing' : opening ? 'opening' : 'other';
			var fromTo = lastType + '->' + type;
			lastType = type;
			var padding = '';

			indent += transitions[fromTo];
			for (var j = 0; j < indent; j++)
			{
				padding += '    ';
			}

			formatted += '\n' + padding + ln;
		}
	}

	return formatted;
}



///////////////////////////////////
//Support for the Site Search Box
///////////////////////////////////
function handle_search_box(form_id, input_id)
{
	//alert("form_id = '" + form_id + "', input_id='" + input_id +"'");

	//Blank it out if the user left the default value
	var target_input = document.getElementById(input_id); 
	if (target_input.value == 'Enter text')
	{
		target_input.value = '';
	}
	
	//Submit the form
	var target_form = document.getElementById(form_id);
	target_form.submit();
}

function handle_key_press(event, form_id, input_id)
{
	if(event.keyCode==13)
	{
		handle_search_box(form_id, input_id);
	}
}