if(jQuery) {
	jQuery.noConflict();
}

/** --------------------------------------------------
 * Cookie Management:
 ** --------------------------------------------------
 * - Check for cookie support
 * - Set a cookie
 * - Get a cookie
 * - Delete a cookie
 ** -------------------------------------------------*/
 
 /* True if cookie support is enabled in this browser
    Sets a test cookie and tries to read its value*/
function cookieSupport() {
	var cookieEnabled = false;
	var testCookieName = "GStestCookie";
	var testCookieValue = "TestCookie";
	var expired = new Date();
	expired.setTime(expired.getTime() + 1800000);
	setCookie(testCookieName, testCookieValue, expired, null, null, null);
	cookieEnabled = (document.cookie.indexOf(testCookieName) != -1)? true : false; //Able to create?
	expired = new Date();  // Create expired date object to delete cookie.
	expired.setTime(expired.getTime() - 1800000);
	setCookie(testCookieName, "deleted", expired, null, null, null);
	return cookieEnabled;
}

/* An adaptation of Dorcht's function for setting a cookie. */
function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

/* Gets the value of a browser cookie by name */
function getCookie(name){
  var cookieName = name + "=";
  var dc = document.cookie;
  if (dc.length > 0) {
    begin = dc.indexOf(cookieName);
    if (begin != -1) {
      begin += cookieName.length;
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    }
  }
  return null;
}

/* An adaptation of Dorcht's function for deleting a cookie. */
function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

/** --------------------------------------------------
 * Font Size Management:
 ** --------------------------------------------------
 * - Global variable "defaultFontSizeSet"
 * - Set font size
 * - Change font size (uses defaultFontSizeSet)
 * - Check for the current font preference and adjust the page if one is found
 * - Remember the current font preference
 ** --------------------------------------------------*/

 /* True if changeFontSize has never been used */
 var defaultFontSizeSet = false;
 
 /* Sets the font size. Does not require a current font size */
 function setFontSize(newFontSize) {
	if(newFontSize != '') {
		changeFontsize(newFontSize, ''); 
	}
 }
 
  /* Takes two strings that can be parsed as integers.
   * Adjusts the current font size. If there is no current font
   * size, the default size is used as a basis for adjustment */
 function changeFontsize(fSize, increment) {
	var mydoc = document.getElementById("mainContent");
	var defaultFontSize = '14';
	
	// When incrementing the current font size, 
	// ensure there is a default font size set. 
	if (!defaultFontSizeSet) {
		defaultFontSizeSet = true;
		if (increment != "")
			setFontSize(defaultFontSize);
	}
	
	//CDW Only get the elements defined below this DIV Level
	if (mydoc.getElementsByTagName)  {
		tags = new Array ( "p", "li", "span", "h1", "h2", "h3", "h4", "h5", "h6", "div" );
		for (j=0; j<tags .length; j++) {
			var getElement = mydoc.getElementsByTagName(tags[j]);
			var eachElement, currentFontSize, fontIncrease, newFontSize;
			for (i=0; i<getElement.length; i++) {
				eachElement = getElement[i];
				
				// either adjust the current font size or set teh font size outright
				if (increment != "") {
					currentFontSize = parseInt(eachElement.style.fontSize);
					fontIncrease = parseInt(increment);
					newFontSize = currentFontSize + fontIncrease;
				} else if (fSize != "") {
					newFontSize = parseInt(fSize);
				}
				
				if (tags[j] == "li") {
					eachElement.style.lineHeight = Math.round(newFontSize*1.2) + "px";
				} else {
					eachElement.style.lineHeight = Math.round(newFontSize*1.5) + "px";
				}
				
				if (fSize != "") {
					switch(tags[j]) {
						case "h2": newFontSize += 0; break;
						case "h3": newFontSize += 0; break;
						case "h4": newFontSize += 0; break;
						case "h5": newFontSize += 0; break;
						case "h6": newFontSize += 0;
					}
				}
				eachElement.style.fontSize = newFontSize + "px";
				rememberFontSizePreference(newFontSize);
			}
		}
	}
}

/* Check for the current font preference and adjust the font size if one is found */
function loadFontSizePreference() {
	var fontPreference = getCookie('fontSize')
	if (fontPreference) {
		setFontSize(fontPreference);
	}
}

/* Store the new font preference in a browser cookie */
function rememberFontSizePreference(newFontSize) {
	setCookie('fontSize', newFontSize);
}

/** --------------------------------------------------
 * Modal window management:
 ** --------------------------------------------------
 * - Display the modal window if hasn't been viewed
 * - Remember that modal window has been viewed
 * - Check whether modal window has been viewed
 ** --------------------------------------------------*/

/* Displays a modal window from "/WizardBuilder/MODAL/subModal.js"
 * windowInfo has height, width and url properties
 * cookieInfo has a name and duration (days) property
 * If cookieInfo is null, popup will not display at all rather than every time the page loads*/
function showPopUp(windowInfo, cookieInfo) {
	if(cookieInfo != null && cookieSupport() && cookieInfo.duration > 0) {
		var hidePopUp = popupHasBeenViewed(cookieInfo.name);
		if(!hidePopUp) {
			showPopAd(windowInfo.url, windowInfo.width, windowInfo.height, '');
			setPopupAsViewed(cookieInfo.name, cookieInfo.duration);
		}
	}
}

/* Sets a browser cookie of the given name that expires in the given time with the value of "true" */
function setPopupAsViewed(cookieName, durationInMilliseconds) {
	var expire = new Date();
	expire.setTime((new Date()).getTime() + durationInMilliseconds);
	setCookie(cookieName, "true", expire, null, null, null);
}

/* returns true if a browser cookie of the given name exists and has a value of "true" */
function popupHasBeenViewed(cookieName) {
	var cookieVal = getCookie(cookieName);
	return (cookieVal != null && cookieVal == "true");
}

/** --------------------------------------------------
 * Embedded youtube video API management:
 ** --------------------------------------------------
 * - onReady function
 * - Add an event listener
 * - Translate player state
 * control YouTube videos embedded using SimpleFlashElementHeader
 * YouTube player API located at: http://code.google.com/apis/youtube/js_api_reference.html
 * ------------------------------------------------------------------------*/
 
// Once the player is ready, it will automatically call onYouTubePlayerReady
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById(playerId);
	if(ytplayer != null) {
		ytplayer.isReady = true;
	}
}

// create your own listener function to handle the player's onStateChange event
function addYoutubeListener(playerId, listenerFunction) {
	ytplayer = document.getElementById(playerId);
	if(ytplayer != null && ytplayer.isReady) {
		ytplayer.addEventListener("onStateChange", listenerFunction);
	}
}

/* Return the meaning of the youtube player's current state
 * use playerObj.getPlayerState() to get the players state number */
function getPlayerStateMeaning(newState) {
	switch(newState) {
		case -1: return "video unstarted";
		case  0: return "video ended";
		case  1: return "video playing";
		case  2: return "video paused";
		case  3: return "video buffering";
		case  5: return "video cued";
		default: return "invalid state";
	}
}

/** -------------------------------------------------------
 * Gets the query string from the url and reads the params 
 * -------------------------------------------------------*/
var qsParm = new Array();
function qs() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
} 

/** -------------------------------------------------------------------------
 * Funds Risk/Reward Meter
 * Swap out Fund risk/reward meter images when hovering over a fund
 * --------------------------------------------------------------------------*/
jQuery(document).ready(function() {
  
	// Copy the current fund's risk meter image into the display box when its link is hovered over
	jQuery('#fundsListTable td>div').each(function() {
		var img = jQuery(this).find('img.fundRiskMeter');
		var meter = jQuery('.fundsListRiskRow td img');
		var temp = meter.attr('src');
		if(img.length > 0) {
			if(img.attr('src') != '') {
				jQuery(this).children('a').hover(
					function() {
						meter.attr('src', img.attr('src'));
					},
					function () {
						meter.attr('src', temp);
					}
				);
			}
		}
	});

/* --------------------------------------------------------------------------
 * control the opening and closing of "drawers" on tools and education and
 * ministry tools pages.
 * ------------------------------------------------------------------------*/


	var drawerControl = {};
	drawerControl.imgOpen = "/~/media/2F1B45A0DF904B348A98F395A005447D.ashx";
	drawerControl.imgClosed = "/~/media/240CE59221CD43F3AD3E95FAD50312F7.ashx";
	drawerControl.txtOpen = "Collapse";
	drawerControl.txtClosed = "Expand";

	// slide a single drawer open over a given period of time
	function expandElement(elem, speed) {
		if(!elem.open) {
			var millis = (typeof speed == 'number')? speed:400;
			jQuery(elem).next(".drawerBody").slideDown(millis);
			jQuery(elem).children(".drawerControls").children("img").attr("src", drawerControl.imgOpen);
			jQuery(elem).children(".drawerControls").children("span").text(drawerControl.txtOpen);
			elem.open = true;
		}
	}
	
	// slide a single drawer closed over a given period of time
	function collapseElement(elem, speed) {
		if(elem.open) {
			var millis = (typeof speed == 'number')? speed:400;
			jQuery(elem).next(".drawerBody").slideUp(millis);
			jQuery(elem).children(".drawerControls").children("img").attr("src", drawerControl.imgClosed);
			jQuery(elem).children(".drawerControls").children("span").text(drawerControl.txtClosed);
			elem.open = false;
		}
	}
	
	// close a single drawer instantly
	function closeElement(elem, speed) {
		if(elem.open) {
			var millis = (typeof speed == 'number')? speed:400;
			jQuery(elem).next(".drawerBody").hide();
			jQuery(elem).children(".drawerControls").children("img").attr("src", drawerControl.imgClosed);
			jQuery(elem).children(".drawerControls").children("span").text(drawerControl.txtClosed);
			elem.open = false;
		}
	}
	
	// slide all drawers open over a given period of time
	function expandAll(speed) {
		jQuery(".drawerControls").parent().each(function(i) {
			expandElement(this, speed);
		});
	}
	
	// slide all drawers closed over a given period of time
	function collapseAll(speed) {
		jQuery(".drawerControls").parent().each(function(i) {
			collapseElement(this, speed)
		});
	}
	
	// close all drawers instantly
	function closeAll(speed) {
		jQuery(".drawerControls").parent().each(function(i) {
			closeElement(this, speed)
		});
	}

	// add click open click close functionality
	jQuery(".drawerControls").parent().each(function(i) {
		this.open = true;
		jQuery(this).click(function () {
			if(this.open) {
				collapseElement(this);
			} else {
				expandElement(this);
			}
		});
	});
	
	/* Closing all the drawers instantly when the page 
	 * loads with javascript instead of starting them
	 * closed with css allows users without javascript
	 * to view the content. */
	closeAll(400);
});