// JavaScript Document
viewAsset = function(guid) {
	var page = 'http://player.discoveryeducation.com/views/extView.cfm?guidAssetId='+guid+'&blnPopup=1&productCode=US';
	var windowprops = "width=846,height=452,location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes";
	window.open(page, "", windowprops);
}





// JavaScript Document
//Contains global UI functions




//Global Loader:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
//The Global loader currently provides 3 different sizes.  Small, Large, & Text (Text will only display text and no graphic)
//:::: binder = the div that will be matched in size and height by the white screen
//:::: text = text string to be displayed above the loader
//:::: size = takes a size parameter 'small' OR 'large' OR 'text' (note: 'text' removes the graphic and will only display the text past in the previous 'text' parameter)
//:::: newId = If declared, assigns an id to the loader for instances where multiple loading graphics may be present at once.  newId must be passed when clearLoad() is called, if supplied to globalLoad()
//ex: globalLoad('elemen-to-insert-into', 'text-to-display', 'small or large or text', 'optional: an id if multiple loaders are open');
globalLoad = function (binder, text, size, newId) {
		lHeight = $(binder).getHeight();
		lWidth = $(binder).getWidth();
		Element.insert($(binder), '<div id="contentLoader" class="contentLoader" style="height:' + lHeight + 'px;width:' + lWidth + 'px;" align="center"><div id="loaderImg' + size + '">' + text +'</div></div>');
		
		if (typeof newId != "undefined") {
			$('contentLoader').id = "contentLoader" + newId;
		}		
}


//Clear loader
clearLoad = function (closeId) {
	
	if (typeof closeId != "undefined") {
		Element.remove($('contentLoader' + closeId));
	} else {
		Element.remove($('contentLoader'));
	}
}





//Global Lightwindow:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/*
Note: globalWin utilizes the globalBase element that is created with the DE global header and footer
- to init an instance of the global light window, call globalWin('path-to-file','title of light window')
- globalWin will adapt to the size of the file being called.  The file should not contain body or html tags or links to styles.  Stylesheets, etc should be loaded into the parent document.
- a height and width must be defined in the top node/element of the file being loaded into the light window
*/

//check for IE
var IE = document.all?true:false;

globalWin = function (path,title) {
	
	//hide flash objects
	if($$("object")){
		var flashEls = $$("object");
		for (var i=0; i<flashEls.length; i++) {
			flashEls[i].style.visibility = "hidden";
		}
	}
		
	if($$("iframe")){
		var frames = $$("iframe");
		for (var i=0; i<frames.length; i++) {
			frames[i].style.visibility = "hidden";
		}
	}

	
	//create the screen
	var win = "<div id='globalWin' onclick='clearWin();' align='center'></div>";
	
	//insert into DOM
	Element.insert($('body'), win);
	
	//set it's width and height
	var newDim = document.body.getHeight();
	var loaderCoord = newDim/2-80;

	$('globalWin').style.height = newDim+"px";
	$('globalWin').style.width = "100%";
	
	//if IE remove els by default	
	if	(IE) {
		removeEls('hide');
	}
	
	
	//create the content window
	var conWin = "<div id='conWin' align='center'><div id='conWinInner' style='top:40px;' align='center'></div></div>";
	//insert into DOM
	$('globalWin').insert({before: conWin});
	resizeLoader();
	$('conWinInner').style.visibility = "hidden";
	

	//scroll observer
	Event.observe(window, 'scroll', function() {
		if ($('globalWin')){										 
			resizeWin(1);
		}
	});

	//resize observer
	Event.observe(window, "resize", function() {
		if ($('globalWin')){										 
			resizeWin(1);
		}
	});
	
	
	//creat the content window
	new Ajax.Updater('conWinInner', path, {
  		parameters: {  },
		evalScripts: true,
		onComplete: function(){
			var badTag = $$('#conWinInner title');
			var badTag2 = $$('#conWinInner meta');
			
			//var badTags = $$('title');
			//Element.remove($$('title'));
			for (var i=0; i<badTag.length; i++) {
				Element.remove(badTag[i]);
			}
			for (var i=0; i<badTag2.length; i++) {
				Element.remove(badTag2[i]);
			}
			
			var windowContent = $('conWinInner').firstDescendant();
			var conWidth = $(windowContent).getWidth();
			$('conWinInner').style.width = conWidth+"px";
			
			//if title is provided
			if(title != ''){
				//insert the header
				var titleWin = "<h4 class='win' align='left'>"+title+"</h4>";
				$('conWinInner').insert({top: titleWin});
			}
			//insert close window link
			//var closeWin = "<div id='closeWin' onclick='clearWin();'>X close</div>";
			//$('conWinInner').insert(closeWin);
	
			resizeWin();
			//Element.remove($('winLoader'));
			
			//this is a bit of trickery as display none mess's w/ positioning above
			$('conWinInner').hide();
			$('conWinInner').style.visibility = "";
			$('conWinInner').appear();
		}
	});
	
}

removeEls = function(act) {
	if (act == 'hide'){
		$$('select').each(function(s,index) {
			s.hide();
		});
	} else {
		$$('select').each(function(s,index) {
			s.show();
		});
	}
}



resizeWin = function(observeCall) {
	//set a default for now
	var element = 'conWinInner';
	if($(element) != null) {
		if(typeof window.innerHeight != 'undefined') {
			
			yWithScroll = document.body.scrollHeight;
			var maxTop = Math.round(yWithScroll - $(element).getHeight());
			
			var newHeight = Math.round(document.viewport.getScrollOffsets().top + 
			((window.innerHeight - $(element).getHeight()))/2);

			if (newHeight < 0) {
				var newHeight = 1;
			} else if (newHeight > maxTop){//if the new position is great than the height of the lightwindow - body height
				var newHeight = maxTop - 1;
			}
			
			if (window.innerHeight < $(element).getHeight() && observeCall != 1){
				$(element).style.top = newHeight+'px';
			} else if (window.innerHeight > $(element).getHeight()){
				$(element).style.top = newHeight+'px';
			}
				
		} else {//this is IE primarily 
			
			yWithScroll = document.body.scrollHeight;
			var maxTop = Math.round(yWithScroll - $(element).getHeight());
			
			var newHeight = Math.round(document.viewport.getScrollOffsets().top + 
			((document.viewport.getHeight() - $(element).getHeight()))/2)
			
			if (newHeight < 0) {
				var newHeight = 1;
			} else if (newHeight > maxTop){
				var newHeight = maxTop - 1;
			}
		
			
			if (document.viewport.getHeight() < $(element).getHeight() && observeCall != 1){
				$(element).style.top = newHeight+'px';
			} else if (document.viewport.getHeight() > $(element).getHeight()){
				$(element).style.top = newHeight+'px';
			}
			
		}
	}
}

resizeLoader = function(observeCall) {
	//set a default for now
	var element = 'winLoader';
	if($(element) != null) {
		if(typeof window.innerHeight != 'undefined') {
			
			yWithScroll = document.body.scrollHeight;
			var maxTop = Math.round(yWithScroll - $(element).getHeight());
			
			var newHeight = Math.round(document.viewport.getScrollOffsets().top + 
			((window.innerHeight - $(element).getHeight()))/2);

			if (newHeight < 0) {
				var newHeight = 1;
			} else if (newHeight > maxTop){//if the new position is great than the height of the lightwindow - body height
				var newHeight = maxTop - 1;
			}
			
			if (window.innerHeight < $(element).getHeight() && observeCall != 1){
				$(element).style.top = newHeight+'px';
			} else if (window.innerHeight > $(element).getHeight()){
				$(element).style.top = newHeight+'px';
			}
				
		} else {//this is IE primarily 
			
			yWithScroll = document.body.scrollHeight;
			var maxTop = Math.round(yWithScroll - $(element).getHeight());
			
			var newHeight = Math.round(document.viewport.getScrollOffsets().top + 
			((document.viewport.getHeight() - $(element).getHeight()))/2)
			
			if (newHeight < 0) {
				var newHeight = 1;
			} else if (newHeight > maxTop){
				var newHeight = maxTop - 1;
			}
		
			
			if (document.viewport.getHeight() < $(element).getHeight() && observeCall != 1){
				$(element).style.top = newHeight+'px';
			} else if (document.viewport.getHeight() > $(element).getHeight()){
				$(element).style.top = newHeight+'px';
			}
			
		}
	}
}

clearWin = function () {
	Element.remove($('globalWin'));
	Element.remove($('conWin'));
	
	var flashEls = $$("object");
	for (var i=0; i<flashEls.length; i++) {
		flashEls[i].style.visibility = "visible";
	}
	
	if($$("iframe")){
		var frames = $$("iframe");
		for (var i=0; i<frames.length; i++) {
			frames[i].style.visibility = "visible";
		}
	}
	
	
	if	(IE) {
		removeEls('show');
	}	
}





//DE Tabs
//When using globalTabs()
//(a).  use a domready observer to get all tabs w/ class=de-tab
//(b).  pass in a function (f) argument -- this will be evaluated onclick
globalTabs = function(f) {
	func = f;
	$$('a.de-tab').each(function(item) {
		item.observe('click', tabAction);
		
	});		
}


tabAction = function() {
	
	var tabID = this.id;
	var currClass=$(tabID).className;
	var pos=currClass.endsWith('-sel')
	
	if (pos!=true)
	{
		$$('a.de-tab').each(function(item) {
			item.className = currClass;
		});	
		
		$$('a.de-tab-sel').each(function(item) {
			item.className = currClass;
		});	
		
		$(tabID).className = currClass+"-sel";
		

		var fr = func; //Here I am passing a reference to function 'f', without parameters
		fr(tabID); //the 'f' function is invoked, without parameter			
		
		
	} else {
		return;
	}
}



function popWindow(url,width,height){
	// set the width and height of the playlist popup window to be created
	popupWidth = width;
	popupHeight = height;
	popupURL = url;
	// attempt to determine the width and height of the user's current window - default to 800x600
	windowWidth = 800;
	windowHeight = 600;
	try {
		if (self.innerWidth) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (parent.document.documentElement && parent.document.documentElement.clientWidth) {
			windowWidth = parent.document.documentElement.clientWidth;
			windowHeight = parent.document.documentElement.clientHeight;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (parent.document.body) {
			windowWidth = parent.document.body.clientWidth;
			windowHeight = parent.document.body.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	} catch(err) {
		windowWidth = 800;
		windowHeight = 600;
	}

	// determine the position of our popup window based on the current window size
	popupLeft = (windowWidth/2)-(popupWidth/2);
	popupTop = (windowHeight/2)-(popupHeight/2);

	myUrl = popupURL;
	myTarget = "refPopupWindow";
	myArgs = 'width='+popupWidth+',height='+popupHeight+',location=0,menubar=0,resizable=1,scrollbars=1,status=0,titlebar=1,toolbar=0,hotkeys=0,top='+popupTop+',left='+popupLeft;
	refPopupWindow = window.open( myUrl, myTarget, myArgs );
	refPopupWindow.focus();
}



flashClearWin = function() {
	setTimeout("clearWin();",100);
}

flashCloseAddTo = function() {
	setTimeout("closeAddTo();",100);
}
	
	
	
	
	
	


function DaysInMonth(Y, M) 
{
    with (new Date(Y, M, 1, 12)) {
        setDate(0);
        return getDate();
    }
}
function datediff(date1, date2) 
{
    var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
	 y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();

    if (d1 < d2) {
        m1--;
        d1 += DaysInMonth(y2, m2);
    }
    if (m1 < m2) {
        y1--;
        m1 += 12;
    }
    return [y1 - y2, m1 - m2, d1 - d2];
}

function getYearsOld(bdyear, bdmon, bdday, curyear, curmon, curday)
{
	if (curday == "undefined" || curday == null || String(Number(curday)).toLowerCase() == "nan")
	{
		var dat = new Date();
		curday = dat.getDate();
		curmon = dat.getMonth() + 1;
		curyear = dat.getFullYear();
	}
	
	var curd = new Date(curyear, curmon - 1, curday);
	var bdd = new Date(bdyear, bdmon - 1, bdday);
	
	var dife = datediff(curd, bdd);
	
	return dife[0];
}





/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);





/*Various xprize site functions*/
function isTeamEmail() {
	var emailAddress = escape(Trim(String($("email").value)));
	var teamName = escape(Trim(String($("teamName").value)));
	
	new Ajax.Request('/cfcs/contest.cfc?method=IsTeamEmail&teamName=' + teamName + '&email=' + emailAddress + '&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText).toLowerCase();
			if (successText.indexOf('success') >= 0){
				return true;
			}
			else {
				return false;
			}
		  }
	});
}

//login function
function signIn() {
	resultLogin = resultValidLogin.validate();			
	if (resultLogin != true){
		return;
	}
	
	new Ajax.Request('/cfcs/contest.cfc?method=Authenticate&email='+$("login").value+'&passcode='+$("password").value+'&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText);
			if (successText.indexOf('success') >= 0){
				$('loginWindow').hide();
				$('loginSuccess').show();
				$('loginSuccessText').appear();
				/*setTimeout("location.reload(true)",1500);*/
				setTimeout("location.href='/contest/team-toolbox.cfm'",1500);
			}else{
				$('errorMsg').appear();
			}
		  }
	});	
}

function loginHome() {
	resultLoginHome = resultValidLoginHome.validate();			
	if (resultLoginHome != true){
		return;
	}
	
	new Ajax.Request('/cfcs/contest.cfc?method=Authenticate&email='+$("homeLogin").value+'&passcode='+$("homePassword").value+'&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText);
			if (successText.indexOf('success') >= 0){
				/*setTimeout("location.reload(true)",1500);*/
				setTimeout("location.href='/contest/team-toolbox.cfm'",1500);
			}else{
				$('errorMsgHome').appear();
			}
		  }
	});	
}

function logOut(){
	new Ajax.Request('/cfcs/contest.cfc?method=logOut&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {				
			setTimeout("location.reload(true)",2200);
		  }
	});
}

function forgotPassword(){
	$('loginWindow').hide();
	$('passwordWindow').show();
	resultValidLookup = new Validation('passwordForm');
}

function forgotPasswordAction(){
	resultLoookup = resultValidLookup.validate();			
	if (resultLoookup != true){
		return;
	}
	
	var emailAddress = $("loginForgot").value;
	var teamName = $("teamName").value;
	
	new Ajax.Request('/cfcs/contest.cfc?method=IsTeamEmailPass&teamName=' + teamName + '&email=' + emailAddress + '&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText).toLowerCase();
			if (successText.indexOf('success') >= 0){
				$('passwordFields').hide()
				$('successText').appear();
			}
			else {
				$('errorMsg2').show();
				return;
			}
		  }
	});
	
	
}
		
		
		
		
/*Form scripts*/
function submitForm(formX){
	//1st validate form	
	result = valid.validate();
	
	if (formX == "step1") {
		if (result != false) {
			
			if ($("memberType").value == "mentor") {
				result = CheckMember("", true);
			}
			else {
				result = CheckMember("", false);
			}
			
			if (result != false) {
				$(formX).submit();
			}
		}
	}
	else if (formX == "step3") {
		if (result != false) {
			if ($("email-mentor") != null) {
				result = CheckMember("-mentor", true);
			}
			if (result != false && $("email-req1") != null) {
				result = CheckMember("-req1", false);
			}
			if (result != false) {
				result = CheckMember("-req2", false);
			}
			if (result != false && $("save-opt1").value == "1") {
				result = CheckMember("-opt1", false);
			}
			if (result != false && $("save-opt2").value == "1") {
				result = CheckMember("-opt2", false);
			}
			if (result != false && $("save-opt3").value == "1") {
				result = CheckMember("-opt3", false);
			}
		}
		
		if (result != false){
			$(formX).submit();
		}
	}
	else {
		if (result != false){
			$(formX).submit();
		}
	}
}


function addOptional(){
	if($('opt1').style.display=='none'){
		Effect.SlideDown('opt1');
		$('save-opt1').value = "1";
	}else if($('opt2').style.display=='none'){
		Effect.SlideDown('opt2');
		$('save-opt2').value = "1";
	}else if($('opt3').style.display=='none'){
		Effect.SlideDown('opt3');
		$('save-opt3').value = "1";
		$('btn-addmember').fade();
	}
}


function removeOptional(num){
	Effect.SlideUp('opt'+num);
	$('save-opt' + num).value = "0";
	$('btn-addmember').appear();
}


function step1Type(type){
	if(type=='mentor'){
		$('step1phone').show();
	}else {
		$('step1phone').hide();
	}
}
		
		
		
		
function CheckMember(postFix, check21)
{
	var isGood = true;
	
	if (postFix == "undefined" || postFix == null)
	{
		postFix = "";
	}
	
	var emailAddress = Trim($("email" + postFix).value);
		
	new Ajax.Request('/cfcs/contest.cfc?method=IsEmailAvailable&email=' + escape(emailAddress), {
		asynchronous: false,
		method: 'get',
		onSuccess: function(transport) {
			var successText = Trim(String(transport.responseText));
			if(successText == "success") {
				isGood = true;
			}
			else {
				alert("Team members cannot be on multiple teams.\n" + emailAddress + " is already a member of an existing team.");
				isGood = false;
			}
	  	},
	  	onFailure: function() {
	  		alert("There was an error processing your request.\nPlease try again later.");
	  		isGood = false;
	  	}
	});
	
	if (isGood != false) {
		
		if (check21) {
			if (getYearsOld($("yearBirth" + postFix).value, $("monthBirth" + postFix).value, $("dayBirth" + postFix).value) < 21) {
				alert("Sorry! The adult mentor must be 21 years old.");
				isGood = false;
			}
		}
		else {
			if (getYearsOld($("yearBirth" + postFix).value, $("monthBirth" + postFix).value, $("dayBirth" + postFix).value, 2010, 3, 1) < 14) {
				if (postFix == "") {
					alert("Sorry! You must be 14 years of age or older by March 1, 2010 to compete. Keep checking the Web site for fun opportunities to stay involved.");
				}
				else {
					alert("Sorry! All members must be 14 years of age or older by March 1, 2010 to compete. Keep checking the Web site for fun opportunities to stay involved.");
				}
				isGood = false;
			}
		}
	}
	
	return isGood;
}


function Trim(astring)
{
	return astring.replace(/^\s*/, "").replace(/\s*$/, ""); //Trim the start and end of string;
}		


function updateUserTS(){
	//clear body mousemove observer
	$('body').stopObserving('mousemove');
	
	new Ajax.Request('/cfcs/contest.cfc?method=UpdateUserTS&returnFormat=plain', {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText);
			if (successText.indexOf('success') >= 0){
				updateTimerId = setTimeout ( "setActiveObserver()", 7000 );
				//alert('Timer updated');
			}else{
				alert('Your session has been inactive for 25 minutes.  Please log in back in to make edits.');
			}
		  }
	});	
	
}

function setActiveObserver(){
	Event.observe('body', 'mousemove', function() {
		updateUserTS();
	});
}


function setUnloadActions(){
	
	$$('a').each(function(item) {
		Event.observe(item, 'click', function() {
			//if(item.className!="extLink"){									  
				internalLink=true;
			//}
		});
	});	
	
	//window.onunload=unloadSignOut;
	/*Event.observe(window,'beforeunload',function(){
    		unloadSignOut();
	}); */
	window.onbeforeunload=unloadSignOut;
	
	
	internalLink=false;
}


function unloadSignOut(){
	if(internalLink!=true){
		new Ajax.Request('/cfcs/contest.cfc?method=logoutContest', {
		  asynchronous: false,
		  method: 'get'
		});	
	}
	internalLink=false;
}



function isLockedTimer(mG,lN){
	isLockedTimerVar = setInterval ( "isLockedCheck()", 20000 );
	memberGUID = mG;
	
}

function isLockedCheck(){
	new Ajax.Request('/cfcs/contest.cfc?method=CanSaveContestEntry&memberGUID='+memberGUID, {
		  method: 'get',
		  onSuccess: function(transport) {
			var successText = String(transport.responseText);
			if (successText.indexOf('true') >= 0){
				isLockedIsExpired();
				clearInterval ( isLockedTimerVar );

			}
		  }
	});	
}


function isLockedIsExpired(){
	globalWin('/contest/takeControl.cfm','');
}


function swapTabsGrade(el){

	if($(el).hasClassName('sel')){
		return;
	}else{
		$$('.gradeBand-tabs a.sel').each(function(item){
			$(item.id+'-wrap').hide();	
			$(item.id).removeClassName('sel');	
			
		});
		
		$(el).addClassName('sel');
		$(el+'-wrap').show();
		
	}
	
	
	
}
