/* 
 * LSA is the scope of all custom objects created for LandScope America by NavigationArts.
 * This is so any outside JS code won't conflict with the functions and variables.
 */
if (!LSA) {
	// defining this first so that it can be re-used by other variables.
	var LSA = {
		ercBasePath: "/_res/flex/erc/"
	}
	LSA = {
    // redefining this variable so that it doesn't disappear
    ercBasePath: LSA.ercBasePath,
		/* 
		 * The following variables are tracked to manage the mouseover states
		 * of the primary navigation. Default is what is marked when the page loads
		 * and Over is what is marked as the user is interacting with the page.
		 */
		navMainDefaultLI: "",
		navMainOverLI: "",
		
		mapMinHeight: 425,
		
		expressInstallSWF: LSA.ercBasePath + "playerProductInstall.swf",
		requiredFlashVersion: "9.0.124",
		
		/* Explore Related Content default values. */
		ercID: "contentErc",
		ercHeight: "340",
		ercWidth: "262",
		ercVars: {basepath: LSA.ercBasePath},
		ercParams: { allowScriptAccess: "sameDomain", wmode: "transparent" },
		ercAttributes: false,
		ercSWF: LSA.ercBasePath + "erc.swf",
		
		/* Explore Related Content default values. */
		mapViewerID: "mapViewer",
		mapViewerHeight: "100%",
		mapViewerWidth: "100%",
		mapViewerVars: {basepath: LSA.ercBasePath},
		mapViewerParams: { allowScriptAccess: "sameDomain", wmode: "transparent" },
		mapViewerAttributes: false,
		mapViewerSWF: LSA.ercBasePath + "mapviewer.swf",
		
		contentViewerInnerDiv: "contentViewerDiv",
		contentViewerHeight: "100%",
		contentViewerWidth: "100%",
		contentViewerVars: {basepath: LSA.ercBasePath},
		contentViewerParams: {quality: "best", bgcolor: "#000000", allowScriptAccess: "sameDomain", wmode: "transparent" },
		contentViewerAttributes: {id: cv.contentViewerDiv, name: cv.contentViewerDiv, align: "middle"},
    contentViewerSWF: LSA.ercBasePath + "contentviewer.swf",  
    
    preloaderHeight: "100%",
    preloaderWidth: "100%",
    preloaderVars: {},
    preloaderParams: {wmode: "transparent", quality: "best", bgcolor: "#000000", allowScriptAccess: "sameDomain"},
    preloaderAttributes: {id: cv.contentViewerPreloader, name: cv.contentViewerPreloader},
    preloaderSWF: LSA.ercBasePath + "preloader.swf",
			
		/* DCC (dynamic content carosel) vars. */
		dccTimer: "", /* control the setTimeout of switching between slides. */
		dccDelay: 7000, /* how long of a delay between slides. */
		dccFadeIn: 2000, /* how long before the DCC nav fades in */
		dccActive: 0, /* set the active DCC Slide, it will always be the first slide (0 based index). */
		
    navMenuSensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
    navMenuInterval: 250, // number = milliseconds for onMouseOver polling interval       
    navMenuTimeout: 0, // number = milliseconds delay before onMouseOut       
    
    
		/* DCC function to activate the next slide. */
		dccNextSlide: function(){
			var thisOne = jQuery("#contentDccNav li.on a");
			var nextOne = jQuery(thisOne).parent("li").next().find("a");
			var thisCounter = jQuery("#contentDccNav li").index(jQuery(thisOne).parent("li"));
			/* if the current 'on' nav item is the last one, turn on the first one. */
			if(thisCounter == (jQuery("#contentDccNav li").size() - 1)) {
				nextOne = jQuery("#contentDccNav li:first-child a");
			}
			jQuery(nextOne).click();
			LSA.dccStartTimer();
		},
		/* 
		 * Whenever a next slide is activated (manually or automaticlly) clear the timeout (so the 
		 * full dccDelay happens) and start the timeout up again.
		 */
		dccStartTimer: function(){
			window.clearTimeout(LSA.dccTimer);
			LSA.dccTimer = window.setTimeout(function() {LSA.dccNextSlide();}, LSA.dccDelay);
		},
		
		/* 
		 * This hides/shows the second level navigation (the drop down menus).
		 * This function is called onMouseOver and onMouseOut of the LI and UL in the main nav.
		 */
		navMainHideShow: function(){
			if (this.navMainOverLI) {
				/* Remove the 'on' state from the LI (hard coded CLASS) because we don't want to show two LIs as being 'on'. */
				jQuery("#" + this.navMainDefaultLI).removeClass("active");
				
				/* Remove the 'on' state from the LI that last had the CLASS applied by this function. */
				jQuery("#navMain li.hover").removeClass("hover");
				jQuery("#" + this.navMainOverLI).addClass("hover");
			}
			else {
				jQuery("#navMain li.hover").removeClass("hover");
				jQuery("#" + this.navMainDefaultLI).addClass("active");
			}
		},
		
		/*
		 * This hides/shows the slidedown layer for the Sign In form.
		 * Fading in/out the other objects below isn't necessary, but it looks nicer
		 * this way because of the background gradients.
		 */
		navSigninHideShow: function(){
			if (jQuery("#navSignin").css("display") == "none") {
				jQuery("#jsImgClose, #navSigninRegister, #navSigninAccount").fadeIn();
				jQuery("#navSignin").slideDown("fast");
			}
			else {
				jQuery("#jsImgClose, #navSigninRegister, #navSigninAccount").fadeOut();
				jQuery("#navSignin").slideUp("slow");
			}
		},
		
		/* The following variable is used to denote if the "Share" drop down menu is visible. */
		shareOver: 0, /* 1 means it's showing, 0 = hidden */
		/* 
		 * This hides/shows the "Share" drop down menu.
		 * This function is called onMouseOver and onMouseOut of the Share A and DIV drop down.
		 */
		shareHideShow: function(){
			if (this.shareOver) {
				jQuery("#contentFunctions div").show();
			}
			else {
				jQuery("#contentFunctions div").hide();
			}
		},
		
		/*
		 * to account for prefilled forms via the browser. don't want overlapping label and values.
		 */
		isPrefilled: function(){
			jQuery("#txtEmail, #txtPassword, #txtEmail2, #txtPassword2").focus().blur();
		},
		
		/*
		 * On the map page - resize the container so the flash takes up the whole page
		 */
		mapResize: function(){
			var allowedHeight = parseInt(jQuery(window).height()) - (parseInt(jQuery("#content").offset().top) + parseInt(jQuery("#siteinfo").outerHeight()));
			if (allowedHeight < LSA.mapMinHeight) {
				allowedHeight = LSA.mapMinHeight;
			}
			jQuery("#mapViewer").css("height", allowedHeight + "px");
		},
    
    getTypeAndIdFromLink: function(linkObj) {
      var relValue = jQuery(linkObj).attr("rel");
      var values = relValue.split(".");
      return values;
    },
    
    handleDocumentClick: function(linkObj) {
      var href = jQuery(linkObj).attr("href");
      LSA.openDocumentWindow(href);
      return false;
    },
    
    rewriteVideoLink: function(linkObj) {
      var href = jQuery(linkObj).attr("href");
      var contentId = LSA.extractContentId(href);
      if (contentId != null) {
        jQuery(linkObj).attr("rel", "Video." + contentId);
        jQuery(linkObj).attr("class", "fileLink");
      }
    },
    
    openDocumentWindow: function(url) {
      var name = LSA.extractName(url);
      window.open(url, 'popup' + name, 'height=500,width=500,scrollbars=yes,resizable=yes'); 
    },
    
    extractContentId: function(url) {
      var name = LSA.extractName(url);
      var contentId = null;
      if (name != null) {  
        var nameRegex = /item\d+/;
        if (nameRegex.test(name)) {
          contentId = name.substring(4, name.length);
        }
      }
      return contentId;
    },
    
    extractName: function(href) {
      var lastSlashIndex = href.lastIndexOf("/");
      var lastDotIndex = href.lastIndexOf(".");
      var name = null;
      if (lastSlashIndex >= 0 && lastDotIndex >= 0) {  
        name = href.substring(lastSlashIndex + 1, lastDotIndex);
      }
      return name;
    }
	};
} 

/* override content viewer variable values */
if (cv) {
	cv.basePath = LSA.ercBasePath;
	cv.mapViewerId = LSA.mapViewerID;
	cv.mapViewerHtmlUrl = '/map/';
}
	
	
/*
 * jQuery DOMdocument.ready
 */
jQuery(document).ready(function($){
	/* define that the browser has JS enabled (stands for "With JavaScript"), used in the CSS */
	$("body").addClass("wjs");
	
	/* when we're on the map page add a resize function */
	if($("body.templateMap").size() > 0) {
		$("#branding").wrap("<div id='jsBrandingWrapperLeft'><div id='jsBrandingWrapperRight'></div></div>")
		$(window).resize(function(){
			LSA.mapResize();
		});
	}
	
	/*
	 ** This adds different background colors to alternate table rows - Todd Parks
	 */
	$("table.alternate tr:even").css("background-color", "#f6f6f6");
	$("table.alternate tr:odd").css("background-color", "#fefefe");

	/* 
	 * Page authors can indicate that a table cell needs to use a tooltip
	 * by setting the cell's class to 'tooltip-cell' and adding a link within the cell
	 * with the link target set to #foo, where #foo corresponds to a tooltip div
	 * that is added below. This javascript rewrites the link so that the cluetip 
	 * plugin will attach the correct tooltip.
	 */
	$('.tooltip-cell a').each(function(){
	  tooltipDiv = '#tooltiptext-' + $(this).attr('href').substring(1);
	  $(this).attr('href', tooltipDiv);
	  $(this).attr('rel', tooltipDiv);
	  $(this).attr('class', 'tooltip');
	  $(this).cluetip({local:true, showTitle: false, dropShadow: false});
	});

	/** Add the tooltip divs to the page, inserting them into the right rail. */
    if ($('.tooltip').size() > 0) {
      tooltipsHtml = '<div id="tooltiptext-pop" class="tooltipcontent"><div class="inside">U.S. Census Bureau, 2010</div></div>';
      tooltipsHtml += '<div id="tooltiptext-pop-change" class="tooltipcontent"><div class="inside">U.S. Census Bureau, Population Division, Interim State Population Projections, 2005</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-area" class="tooltipcontent"><div class="inside">Trust for Public Land&#146;s Conservation Almanac, June 2008</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-public" class="tooltipcontent"><div class="inside">Trust for Public Land&#146;s Conservation Almanac, June 2008</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-private" class="tooltipcontent"><div class="inside">Land Trust Alliance, 2010 Census (data through Dec. 31, 2010)</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-development" class="tooltipcontent"><div class="inside">NRCS NRI 2003 summary report</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-diversity" class="tooltipcontent"><div class="inside">NatureServe analysis, July 2008, update modeled on the 2002 States of the Union Report</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-risk" class="tooltipcontent"><div class="inside">NatureServe analysis, July 2008, update modeled on the 2002 States of the Union Report</div></div>';
	  tooltipsHtml += '<div id="tooltiptext-bucks" class="tooltipcontent"><div class="inside">Trust for Public Land&#146;s Conservation Almanac, June 2008</div></div>';
      $('#contentRelated').append(tooltipsHtml);
    }
	
	/* pretty up these INPUTs */
	$("#navGlobal input[type=text], #navSigninAccount input, #contentRelated select, #contentRelated input, #contentRelated textarea, #contentSearchForm input").niceforms();
	
	/* insert the bg image DIVs. these are purely decorative. */
	$("#container").wrap("<div id='jsMountains'><div id='jsGradientContainer'><div id='jsGradient'></div></div></div>");
	
	/* set all the IDs for the nav so they can be styled uniquely. this is because we are using image replacement. */
	$("#navMain>ul>li").each(function(i){
		$(this).attr("id", "navMainLI" + i);
	});
	
	/* 
	 * set the default LI, this will be used to reset the nav back to the default state
	 * after all mouseover/out events have fired.
	 */
	LSA.navMainDefaultLI = $("#navMain ul li.active").attr("id");
	
	/* 
   * Sets the onMouseOver/out events for the main nav. 
   * This will hide/show the dropdown 2nd level nav.
   * The hoverIntent plugin is used to avoid accidentally triggering the menus. 
   */
  LSA.navMenuConfigLi = {
    sensitivity: LSA.navMenuSensitivy,
    timeout: LSA.navMenuTimeout,
    interval: LSA.navMenuInterval,
    over: function() {
      LSA.navMainOverLI = $(this).attr("id");
      LSA.navMainHideShow();
    },
    out: function() {
      LSA.navMainOverLI = "";
      LSA.navMainHideShow();
    }
  };
  
  LSA.navMenuConfigUl = {
    sensitivity: LSA.navMenuSensitivy,
    timeout: LSA.navMenuTimeout,
    interval: LSA.navMenuInterval,
    over: function(){
      LSA.navMainOverLI = $(this).parents("li").attr("id");
      LSA.navMainHideShow();
    },
    out:function() {
      LSA.navMainOverLI = "";
      LSA.navMainHideShow();
    }
  }
  
  $("#navMain>ul>li").hoverIntent(LSA.navMenuConfigLi);
  $("#navMain>ul>li>ul").hoverIntent(LSA.navMenuConfigUl);
	
	/* properly hide the slidedown DIV so it starts off hidden, ready to be shown when the user wants it. */
	$("#navSignin").hide();
	
	/* insert the bg image DIVs and the 'close' DIV. */
	$("#navSignin").prepend("<div id='jsImgTop'></div><div id='jsImgBottom'></div><div id='jsImgClose'></div>");
	
	/* set the events to hide/show #NAVSIGNIN */
	$("#navGlobal a.login").click(function(){
		LSA.navSigninHideShow();
		return false;
	});
	$("#navSignin #jsImgClose").click(function(){
		LSA.navSigninHideShow();
		return false;
	});
	
	/* 
	 * set events for login form (in #NAVSIGNIN) interactivity. since the labels are absolutely positioned
	 * over the INPUT we need to hide them onClick, and show then onBlur.
	 */
	$("#txtPassword").focus(function(){
		$("#txtPasswordLabel").hide();
	}).blur(function(){
		if (!$(this).attr("value")) {
			$("#txtPasswordLabel").show();
		}
	});
	$("#txtPasswordLabel").click(function(){
		$("#txtPassword").focus();
	});
	
	$("#txtEmail").focus(function(){
		$("#txtEmailLabel").hide();
	}).blur(function(){
		if (!$(this).attr("value")) {
			$("#txtEmailLabel").show();
		}
	});
	$("#txtEmailLabel").click(function(){
		$("#txtEmail").focus();
	});
	
	/* 
	 * set events for login form (in #CONTENTRELATED) interactivity. since the labels are absolutely positioned
	 * over the INPUT we need to hide them when clicked on, and show them onblur. Same deal as #NAVSIGNIN fields.
	 */
	$("#txtPassword2").focus(function(){
		$("#txtPasswordLabel2").hide();
	}).blur(function(){
		if (!$(this).attr("value")) {
			$("#txtPasswordLabel2").show();
		}
	});
	$("#txtPasswordLabel2").click(function(){
		$("#txtPassword2").focus();
	});
	
	$("#txtEmail2").focus(function(){
		$("#txtEmailLabel2").hide();
	}).blur(function(){
		if (!$(this).attr("value")) {
			$("#txtEmailLabel2").show();
		}
	});
	$("#txtEmailLabel2").click(function(){
		$("#txtEmail2").focus();
	});
	
	/* make HRs able to be styled consistantly */
	$("#content hr").wrap("<div class='hr'></div>");
	
	/* :psuedo-classes for Safari and IE
	** The alt class can be used to give different
	** background colors to alternate list items in
	** a ul.
	*/
		$("ul, ol").each(function(){
			$("li:first", this).addClass("first-child");
			$("li:last", this).addClass("last-child");
			$("li:even", this).addClass("alt");
		});
		
		$("#navGlobal ul:first-child").addClass("first-child");
		
		if ($("#contentBreadcrumb a").size() > 0) {
			$("#contentBreadcrumb a").eq($("#contentBreadcrumb a").size()-1).addClass("last-child");
		}
	
	/* set the focus/blur events for the global search form (upper right) */
	if ($("#navGlobal form").size() > 0) {
		var searchText = "Search";
		var searchField = $("#navGlobal input[type=text]");
		
		if ($(searchField).val() === "") {
			$(searchField).val(searchText);
		}
		$(searchField).focus(function(){
			if ($(this).val() == searchText) {
				$(this).val("");
			}
		});
		$(searchField).blur(function(){
			if ($(this).val() === "") {
				$(this).val(searchText);
			}
		});
	}
	
	/* set the onchange events for the 'Go Straight To Your State' form (right rail) */
	if ($("#goStraightToYourStateSelect").size() > 0) {
		$("#goStraightToYourStateSelect").change(function() {
			var newURL = $("option:selected", $(this)).val();
			if (newURL != "") {
				location.href = $("option:selected", $(this)).val();
			}
		});
	}
	
	if ($("#ltaStateSelect").size() > 0) {
    $("#ltaStateSelect").change(function() {
      var selectedState = $("option:selected", $(this)).val();
      if (selectedState != "") {
        window.location.hash = selectedState;
      }
    });
  }
	
	/* set the focus/blur events for the 'Go to the map' form (right rail) */
	if ($("#goToTheMap").size() > 0) {
		var goToTheMapText = $("#goToTheMap label").html().replace(":", "");
		var goToTheMapField = $("#goToTheMap input[type=text]");
		
		if ($(goToTheMapField).val() === "") {
			$(goToTheMapField).val(goToTheMapText);
		}
		$(goToTheMapField).focus(function(){
			if ($(this).val() == goToTheMapText) {
				$(this).val("");
			}
		});
		$(goToTheMapField).blur(function(){
			if ($(this).val() === "") {
				$(this).val(goToTheMapText);
			}
		});
		$("#goToTheMap form").submit(function() {
		    if ($(goToTheMapField).val() == goToTheMapText) {
		      $(goToTheMapField).val("");
		    }
		    return true;
		  });
		
	}
	
	/* set the focus/blur events for the 'Receive updates' form (right rail) */
	if ($("#receiveUpdates").size() > 0) {
		var receiveUpdatesText = $("#receiveUpdates label").html().replace(":", "");
		var receiveUpdatesField = $("#receiveUpdates input[type=text]");
		
		if ($(receiveUpdatesField).val() === "") {
			$(receiveUpdatesField).val(receiveUpdatesText);
		}
		$(receiveUpdatesField).focus(function(){
			if ($(this).val() == receiveUpdatesText) {
				$(this).val("");
			}
		});
		$(receiveUpdatesField).blur(function(){
			if ($(this).val() === "") {
				$(this).val(receiveUpdatesText);
			}
		});
	}
	
	/* quick facts websites will open in a new window */
	if ($("div.quickfacts a.external").size() > 0) {
		$("div.quickfacts a.external").click(function(){
			window.open($(this).attr("href"));
			return false;
		});
	}

	/* initalize lightbox pop-up functionality */
	//$("div.featuredImage a").lightbox();
	$("div.featuredImage a").click(function(){
		var values = LSA.getTypeAndIdFromLink(this);
	    var tmpType = values[0];
	    var tmpID = values[1];
		if (tmpType == "video") {
			openContentViewer("video", "Videos", ['' + tmpID], 0);
			return false;
		}
		else if (tmpType == "photo"){
			openContentViewer("photo", "Photos", ['' + tmpID], 0);
			return false;
		}
	});
  
  
  // Add event handler for all PDF and word doc links so they open in a new, 
  // undecorated window when clicked.
  $("a:not(.fileLink)[href$='pdf']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  $("a:not(.fileLink)[href$='PDF']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  $("a:not(.fileLink)[href$='doc']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  $("a:not(.fileLink)[href$='DOC']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  $("a:not(.fileLink)[href$='docx']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  $("a:not(.fileLink)[href$='DOCX']").click(function() {
    return LSA.handleDocumentClick(this);
  });
  
  // Rewrite video links to launch the content viewer when clicked
  $("a[href$='flv']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='FLV']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='wmv']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='WMV']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='mov']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='MOV']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='mp3']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  $("a[href$='MP3']:not(.fileLink)").each(function() { LSA.rewriteVideoLink(this); });
  
  // This makes it a little bit harder for people to directly download a video
  $("a.fileLink[rel^='Video']").attr("href", "");
  
  $("a.fileLink").click(function(){
    var values = LSA.getTypeAndIdFromLink(this);
    var url = $(this).attr("href");
    var contentSubType = values[0];
    var contentId = values[1];
    if (contentSubType == "PDF" || contentSubType == "MSWord") {
      LSA.openDocumentWindow(url);
      return false;
    } else if (contentSubType == "Video") {
      openContentViewer("video", "Videos", ['' + contentId], 0);
      return false;
    }
  });
	
	/* 
	 * Add all the content of the 'functions' bar. This bar is empty without JS because none of
	 * the items can work without JS.
	 */
	if ($("#contentFunctions").size() > 0) {
		var tempHTML = '<a onmouseover="LSA.shareOver = 1;LSA.shareHideShow();" onmouseout="LSA.shareOver = 0;LSA.shareHideShow();" id="jsFunctionsShare">Share</a>';
			tempHTML = tempHTML + '<a onclick="window.print();" id="jsFunctionsPrint">Print</a>';
			//tempHTML = tempHTML + '<a onclick="alert(\'insert function here\');" id="jsFunctionsFavorites">Add to Favorites</a>';
			tempHTML = tempHTML + '<div onmouseover="LSA.shareOver = 1;LSA.shareHideShow();" onmouseout="LSA.shareOver = 0;LSA.shareHideShow();"><ul>';
      tempHTML = tempHTML + '<li><a href="http://www.facebook.com/sharer.php?u=' + window.location.href + '&amp;t=' + document.title + '" id="jsFunctionsFacebook">Facebook</a></li>';
			tempHTML = tempHTML + '<li><a href="http://www.stumbleupon.com/submit?url=' + window.location.href + '&amp;title=' + document.title + '" id="jsFunctionsStumbleUpon">Stumble Upon</a></li>';
			tempHTML = tempHTML + '<li><a href="http://digg.com/submit?url=' + window.location.href + '&amp;title=' + document.title + '" id="jsFunctionsDigg">Digg</a></li>';
			tempHTML = tempHTML + '<li><a href="http://reddit.com/submit?url=' + window.location.href + 'amp;title=' + document.title + '" id="jsFunctionsReddit">Reddit</a></li>';
			tempHTML = tempHTML + '<li><a href="http://del.icio.us/post?url=' + window.location.href + '&amp;title=' + document.title + '" id="jsFunctionsDelicious">Del.icio.us</a></li>';
			tempHTML = tempHTML + '<li><a href="http://furl.net/storeIt.jsp?u=' + window.location.href + '&amp;t=' + document.title + '" id="jsFunctionsFurl">Furl</a></li>';
			tempHTML = tempHTML + '<li><a href="http://www.technorati.com/faves?add=' + window.location.href + '" id="jsFunctionsTechnorati">Technorati</a></li>';
			tempHTML = tempHTML + '</ul></div>';
		$("#contentFunctions").prepend(tempHTML);
	}

	/*
	 * Homepage functions for the 'Conservation News and Updates' tabs (bottom right of homepage).
	 * When the tab is clicked, the HREF is the ID of the object to be shown.
	 * Show the default one with the 'on' CLASS.
	 */
	if ($("#contentNewsUpdates").size() > 0) {
		$($("#contentNewsUpdates ul.tabs li.on a").attr("href")).show();
		
		$("#contentNewsUpdates ul.tabs a").click(function() {
			$("#contentNewsUpdates div").hide();
			$("#contentNewsUpdates li.on").removeClass("on");
			
			$(this).parent("li").addClass("on");
			$($(this).attr("href")).show();
			return false;
		});
	}
	
	/*
	 * Homepage functions for the 'See what's popular today' (right rail).
	 * When an H3 is clicked, the HREF is the ID of the object to be shown. 
	 * Any visible one will be hidden when showing a new one.
	 */
	if ($("#whatsPopular").size() > 0) {
		$("#whatsPopular h3.on").next().show();
		$("#whatsPopular>h3").click(function(){
			if ($(this).attr("class") != "on") {
				$("#whatsPopular div:visible").slideUp();
				$("#whatsPopular h3.on").removeClass("on");
				
				$(this).addClass("on");
				$(this).next().slideDown();
				return false;
			}
		});
	}
	
	/*
	 * If there is more than one DCC slide, initalize all the required functions.
	 */
	if($("#contentDccNav li").size() > 1) {
		/*
		 * Loop through each nav item to assign proper IDs (so image replacement can happen)
		 * and to create containers for each slide as they are brought in via Ajax.
		 * The first slide is treated differently because the content is already on the page and
		 * it's going to flaged as 'on'.
		 */
		$("#contentDccNav li").each(
			function(i) {
				$(this).attr("id", "contentDccNav" + i).attr("class", "");
				if(i === 0) {
					$(this).addClass("on");
					$("#contentDccSlides ul li").attr("id", "contentDccSlidesLi" + i);
				}
				else {
					$("#contentDccSlides ul").append("<li id='contentDccSlidesLi" + i + "'></li>");
					$("#contentDccSlidesLi" + i).load($("a", this).attr("href") + " p");
				}
			}
		);
		
		/*
		 * Add functionality to the nav - onClick events.
		 * Hide the old 'on' one, identify the new 'on' one (the one clicked), and then show it.
		 * Then start the countdown on the auto rotation of slides.
		 */
		$("#contentDccNav li a").click(
			function() {
				if($(this).parent("li").attr("class") != "on") {
					$("#contentDccSlidesLi" + LSA.dccActive).fadeOut();
					$(this).parent("li").siblings(".on").removeClass("on");
					$(this).parent("li").addClass("on");
					LSA.dccActive = $("#contentDccNav ul li").index($(this).parent());
					$("#contentDccSlidesLi" + LSA.dccActive).fadeIn();
				}
				if($("#dccPlayPause").attr("class") != "pause") {
					LSA.dccStartTimer();
				}
				return false;
			}
		);

		/*
		 * Add functionality to the play/pause button.
		 * Swap images and clear the timer/start the timer.
		 */
		$("#dccPlayPause").click(function(){
			if($(this).attr("class") == "pause") {
				$(this).attr("src", $(this).attr("src").replace("play.gif", "pause.gif"));
				LSA.dccNextSlide();
				$(this).removeClass("pause");
			}
			else {
				$(this).attr("src", $(this).attr("src").replace("pause.gif", "play.gif"));
				window.clearTimeout(LSA.dccTimer);
				$(this).addClass("pause");
			}
		});
		
		/* Show the DCC nav, and start the auto rotation timer */
		$("#contentDccNav").fadeIn(LSA.dccFadeIn);
		LSA.dccStartTimer();
	}
	
	/*
	 * copyright info
	 * was .copyright, changed to #contentTitle .copyright
	 */
	$("#contentTitle .copyright").each(function(i){
		if(i === 0){
			$("#siteinfoLegal").append("<ul></ul>");
		}
		$("#siteinfoLegal ul").append("<li>" + $(this).html() + "</li>");
	});
	
	/*
	 * clear form fields
	 */	
	LSA.isPrefilled();
	
	$("div.myAccountWidget table tr").each(function(i) {
		if(i % 2 === 0) {
			$(this).addClass("zebra");
		}
	});
  
  /* If the user doesn't have the correct flash version installed, the areas of the page
     that require flash show up as blue boxes. Unfortunately, this includes the
     content viewer's popupdiv, which takes up 100% of the screen real estate.
     This hides the div so the user can at least see the rest of the web page. */
   if (!swfobject.hasFlashPlayerVersion(LSA.requiredFlashVersion)) {
    $("#" + cv.contentViewerPreloaderDiv).css("visibility", "hidden");
    $("#" + cv.contentViewerDiv).css("visibility", "hidden");
  }
  
  /* initalize SWFObject, the explore related content in the right rail */
  if ($("#" + LSA.ercID).size() > 0) {
    swfobject.embedSWF(LSA.ercSWF, LSA.ercID, LSA.ercWidth, LSA.ercHeight, 
        LSA.requiredFlashVersion, LSA.expressInstallSWF, LSA.ercVars, LSA.ercParams, 
        LSA.ercAttributes);
  }
  
  if ($("#" + LSA.mapViewerID).size() > 0) {
    // we append a dummy value to ensure the URL is different every time
    // so the response doesn't get cached
    $.getJSON('/validateMapViewerToken/?token=' + LSA.mapViewerToken + '&dummyValue=' + new Date().getTime(), null,  
      function(data){
        if (data.valid == false) {
          newMapViewerVars = { reloadState: true, basepath: LSA.mapViewerVars.basepath };
          if (LSA.mapViewerVars.mode) {
            newMapViewerVars.mode = LSA.mapViewerVars.mode;       
          }
          LSA.mapViewerVars = newMapViewerVars;
        }
        swfobject.embedSWF(LSA.mapViewerSWF, LSA.mapViewerID, LSA.mapViewerWidth, 
            LSA.mapViewerHeight, LSA.requiredFlashVersion, LSA.expressInstallSWF, 
            LSA.mapViewerVars, LSA.mapViewerParams, LSA.mapViewerAttributes);
        LSA.mapResize();
      });
  }
  
  if ($("#" + cv.contentViewerPreloaderDiv).size() > 0) {
    swfobject.embedSWF(LSA.preloaderSWF, cv.contentViewerPreloaderSWF, 
        LSA.preloaderWidth, LSA.preloaderHeight,
        LSA.requiredFlashVersion, LSA.expressInstallSWF, 
        LSA.preloaderVars, LSA.preloaderParams, LSA.preloaderAttributes);
    if (navigator.appName.indexOf("Microsoft") != -1) {
      cvReady();
    }
  }
});



