//////////////////////////////////////////////////////////////
//Header Menus
//////////////////////////////////////////////////////////////
var dm20_showing_menus = false;

//var dm20_list_menus=[];



function dm20_show_menu(section)
{

	dm20_showing_menus = true;
	
	var target;
	
	for (var x=0; x<dm20_list_menus.length; x++)
	{
		target = document.getElementById(dm20_list_menus[x]);
		if (target) target.style.display = "none";
	}
	
	
	target = document.getElementById(section);
	if (target) target.style.display = "block";
}




function dm20_timer_hide_menus()
{
	//alert("Starting timer. dm20_list_menus is " + dm20_list_menus);
	dm20_showing_menus = false;
	setTimeout('dm20_hide_menus_timeout()',1000);
}


function dm20_hide_menus_timeout()
{
	//alert("Timer done. dm20_showing_menus is " + dm20_showing_menus);

	if(!dm20_showing_menus)
	{
		for (var x=0; x<dm20_list_menus.length; x++)
		{
			//alert("handling " + x);
			target = document.getElementById(dm20_list_menus[x]);
			if(target) target.style.display = "none";
		}	
	}
}




//////////////////////////////////////////////////////////////
//Class-altering stuff, usually for applying the text size class
//////////////////////////////////////////////////////////////
//note that "class" is a reserved word in IE
//adds a css class to the target
function dm20_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 dm20_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 dm20_replace_class(target, old_class, new_class)
{
	target.className = target.className.replace(old_class, new_class);
}






//////////////////////////////////////////////////////////////
//Text-Size Changing
//////////////////////////////////////////////////////////////

function dm20_text_large(is_header_footer_service)
{
	
	dm20_add_class(document.body, "large");


	$("a.dm20_link").each(function()
	{ 
		//If it doesn't contain textsize, then add it.
		if (this.href.indexOf("textsize") == -1)	
		{
			this.href += "&textsize=large";
		}

	});


	
	if (!is_header_footer_service)
	{
		dm20_create_cookie("dm20_text_size", "large", 365);
	}
	
}

function dm20_text_normal(is_header_footer_service)
{
	dm20_remove_class(document.body, "large");
	

	//If we're in header_footer_service mode, then do a dom traversal looking for dm_20 links
	$("a.dm20_link").each(function()
	{ 
		//If it does contain textsize, remove it.
		if (this.href.indexOf("textsize") != -1)	
		{
			this.href = this.href.replace("&textsize=large", "");
		}

	});	
	
	if (!is_header_footer_service)
	{
		//If we're in header_footer_service mode, then do a dom traversal looking for dm_20 links
		dm20_create_cookie("dm20_text_size", "normal", 365);
	}

}



//////////////////////////////////////////////////////////////
//Cookie Handling, used for text-size persistance
//////////////////////////////////////////////////////////////
function dm20_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 dm20_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 extensions
///////////////////////////////

function dm20_trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function dm20_ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function dm20_rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}





/****************************************************************************
set_locale changes the locale.
****************************************************************************/
function dm20_set_locale(locale, environment)
{
	if(environment == 'PREVIEW')
	{
		dm20_add_or_replace_url_var('locale', locale);
	}
	else
	{
		//alert(document.location.href);
		
		var new_url = dm20_add_or_replace_url_var_in_string('textsize', '');
		

			
		if (new_url.indexOf("en_US") != -1)
		{
			new_url = new_url.replace("en_US", locale);
		}
		else if (new_url.indexOf("en_CA") != -1)
		{
			new_url = new_url.replace("en_CA", locale);
		}
		else if (new_url.indexOf("es_US") != -1)
		{
			new_url = new_url.replace("es_US", locale);
		}
		else if (new_url.indexOf("fr_CA") != -1)
		{
			new_url = new_url.replace("fr_CA", locale);
		}
		else if (new_url.indexOf("zh_CN") != -1)
		{
			new_url = new_url.replace("zh_CN", locale);
		}
		else if (new_url.indexOf("ko_KR") != -1)
		{
			new_url = new_url.replace("ko_KR", locale);
		}		
		else if (new_url.indexOf("vi_VN") != -1)
		{
			new_url = new_url.replace("vi_VN", 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.
			new_url = new_url + locale + "/";
			new_url.replace("#", "");
			new_url.replace("//", "/");
			
		}
		
		
		document.location.href = new_url;
	}
}


/****************************************************************************
The following functions change the URL's variables
****************************************************************************/
function dm20_add_or_replace_url_var_in_string(name, value)
{
	var new_url;

	//alert(dm20_strip_anchor_from_url(document.location));

	//Is the var already set?
	if (document.location.href.indexOf(name + "=") == -1)
	{
		var anchor 		= dm20_get_anchor_from_url(document.location.href);
		var anchorless_href 	= dm20_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
		new_url = anchorless_href + delimiter + name + "=" + value + anchor;


	}
	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 = dm20_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;

		new_url = document.location.href.replace(current_var, new_var);
	}
	
	
	//Add the new var onto the end
	return new_url;	
}



/****************************************************************************
The following functions change the URL's variables
****************************************************************************/
function dm20_add_or_replace_url_var(name, value)
{
	document.location.href = dm20_add_or_replace_url_var_in_string(name, value);	
}



// Read a pages GET URL variables and return them as an associative array.
function dm20_get_url_vars()
{
	var anchorless_href = dm20_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 dm20_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 dm20_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 dm20_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 dm20_xml_dump(xml) 
{
	//Dump the xml
	document.write(dm20_format_xml(xml).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"));
}


/****************************************************************************
Check JavaTime
****************************************************************************/
function dm20_check_java_time(java_time_string) 
{

	//Example:
	//2011-01-28 14:58:07.505

	var year		= java_time_string.substring(0,4);
	var month 		= parseInt(java_time_string.substring(5,7)) - 1;
	var day 		= java_time_string.substring(8,10);
	var hours 		= java_time_string.substring(11,13);
	var minutes 		= java_time_string.substring(14,16);
	var seconds 		= java_time_string.substring(17,19);
	var milliseconds 	= java_time_string.substring(20,23);

	//Create some date objects	
	var java_date = new Date(year, month, day, hours, minutes, seconds, milliseconds);
	var now_date = new Date();

	//Subtract the epoch value to get the clock skew in ms	
	var clock_skew = now_date.getTime() - java_date.getTime();
	
	document.write("<br><br>******************************Clock Skew Test******************************");
	document.write("<br>Java Server Date: " + java_date + "<br>Java Script Date: " + now_date);
	document.write("<br><br>Clock Skew: " + clock_skew / 1000 + " Seconds");
	document.write("<br><br>On dynamic pages, clock skew should generally stay about the same number of seconds<br>between page refreshes as this means the page is being regenerated.<br>If it is steadily increasing there could be a potential server caching issue, <br>and you should check to see if the query string parameters that this <br>component takes are declared as External Parameter Datums in the .component file.");
	
}





/****************************************************************************
Pretty-Prints XML
****************************************************************************/

function dm20_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 dm20_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.toLowerCase() == 'enter text' || target_input.value == '')
	{
		alert("Please enter a search term");		
	}
	else
	{
		//Submit the form
		var target_form = document.getElementById(form_id);
		target_form.submit();
	}
}

function dm20_handle_key_press(event, form_id, input_id)
{
	if(event.keyCode==13)
	{
		dm20_handle_search_box(form_id, input_id);
	}
	

}


///////////////////////////////////////////
//Support for the HeaderFooter Search Box
///////////////////////////////////////////
function dm20_handle_search_box_headerfooter(input_id, destination)
{
	var tar = document.getElementById(input_id);
	var search_term = tar.value;
	
	if (search_term == '' || search_term.toLowerCase() == 'enter text')
	{
		alert("Please enter a search term");
	}	
	else
	{
		document.location = destination + "&searchterm=" + search_term;
	}
}



function dm20_handle_key_press_headerfooter(event, input_id, destination)
{
	if(event.keyCode==13)
	{
		dm20_handle_search_box_headerfooter(input_id, destination)
		if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
	}
}


/////////////////////////////////////////
//javascript_ampersand
//You can't write out an ampersand in a javascript block in xsl or it will die
/////////////////////////////////////////
var javascript_ampersand = '&';

