// JavaScript Document
	var fd=20; //Global animation framedelay
	function initDEPlayer (fv) {
		var params = {
				menu:"false",
				wmode:"transparent",
				allowFullScreen:'true'
			},
			atts = {};
		$('de_vidLoader').observe('change',function(evt){
			var _fv = fv[$F('de_vidLoader')];
			_fv.autoStart = 'true';
			swfobject.embedSWF("http://player.discoveryeducation.com/common/swf/media_player.swf", "de_vidList", "300", "220", "8.0.0", false, _fv, params, atts);
		});
		var t=$('de_vidList');
		t.up().style.backgroundImage=t.style.backgroundImage;
		t.writeAttribute('style',false).observe('click',function(evt){evt.stop(); fireEvent($('de_vidLoader'),'change');});
	}
	function LightBox (elem, cc) {
		var sp=('pageYOffset' in window)?window.pageYOffset:document.documentElement.scrollTop;
		var containerClass = (cc || 'lb-container');
		var saveKey = window.location.hash.indexOf('show_') > -1 ?window.location.hash.split('show_')[1]:null;
		var ol = new Element('div',{'class':'lb-overlay'}).insert(new Element('div',{'class':'lb-shadow'}).observe('click',fireClose)).insert(
			new Element ('div',{'class':containerClass}).insert(elem).insert(
				new Element('a',{href:'#','class':'close'}).update('Close').observe('click',fireClose)
			)
		).observe('lightbox:close',closeLB);
		//Hide flash
		$$('object,select').invoke('hide');
		$('body').insert(ol);
		if(ol.getStyle('position') == 'absolute'){
			$('body').scrollTo();
		}
		function fireClose(evt) {
			if ( evt ) evt.stop();
			ol.fire('lightbox:close');
		}
		function closeLB () {
			if ( saveKey )
				setSavedElement(saveKey,elem);
			window.location.hash = '';
			window.scroll(0,sp);
			ol.remove();
			$$('object,select').invoke('show');
		}
	}
	function _empty(str){ return !str; }
	function fireEvent(element,event){
		if (document.createEventObject){
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on'+event,evt)
		}
		else{
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true ); // event type,bubbling,cancelable
		return !element.dispatchEvent(evt);
		}
	}
	function hashUpdate() {
		var h=window.location.hash;
		if ( ('oldHash' in hashUpdate) && hashUpdate.oldHash == h ) return;
		hashUpdate.oldHash = h;
		if ( h.length <= 1 ){
			$$('.lb-overlay').invoke('fire','lightbox:close');
		}
		if ( h.indexOf('widget_') > -1 ){
			launchWidget(h.split('widget_')[1]);
		}else if ( h.indexOf('show_') > -1 ) {
			var v=h.split('show_')[1], s=null;
			if ( s=getSavedElement(v) ) {
				new LightBox(s);
			} else if ( s=$(v) ){
				new LightBox(s.writeAttribute('style',false))
			} else {
				s = new Element('div')
					.insert(new Element('h1').update('Loading'))
					.insert(new Element('div',{'class':'loading'}));
				new LightBox(s);
				new Ajax.Updater(s,'/cfcs/userAjax.cfc?returnFormat=plain&method='+v);
			}
		}
	}
	function getSavedElement(key, elem) {
		if ( !this.init ){
			this.data={};
			this.init=true;
		}
		if ( arguments.length > 1 ){
			this.data[key] = elem;
		}
		return ( key in this.data )?this.data[key]:null;
	}
	setSavedElement = getSavedElement;
	function launchWidget(wname) {
		var newID = 'widget-'+wname;
		if ( $(newID) ) return;
		var params = { allowScriptAccess: "always", wmode: 'transparent' },
			atts = {},
			fv = {data: '/flash/'+wname+'.xml'};
		new LightBox(
			new Element('a', {
				href:'http://get.adobe.com/flashplayer/',
				target:'_blank',
				id:newID
			}).update( new Element('img',{src:'/flash/widget-noflash-'+wname+'.png'}) ),
			'lb-widget'
		);
		
		if (wname == "pu") {
			document.getElementsByClassName("close")[0].style.right = "-145px";
			document.getElementsByClassName("close")[0].style.top = "30px";
			
			swfobject.embedSWF("/flash/widget_"+wname+".swf", newID, "500", "375", "8.0.0", null, fv, params, atts);
		}
		else {
			document.getElementsByClassName("close")[0].style.right = "-20px";
			document.getElementsByClassName("close")[0].style.top = "-20px";
			
			swfobject.embedSWF("/flash/widget_"+wname+".swf", newID, "300", "310", "8.0.0", null, fv, params, atts);
		}
	}
	function _q(obj) {
		var row, y, result = [], temp = {};
		while(row=obj.DATA.shift()) {
			temp = {};
			for(y in row) {
				temp[String(obj.COLUMNS[y]).toLowerCase()]=row[y];
			}
			result.push(temp);
		}
		return result;
	}
	function linkify (element, link) {
		with (element) {
			style.cursor = 'pointer';
			observe('click',function(e){
				e.stop();
				if( !link.target ){
					window.location = link.href;
				} else {
					window.open(link.href, link.target);
				}
			});
		}
	}
	function uniqueID(prefix) {
		var i=0;
		while ( $(prefix+i) )
			i++;
		return prefix+i;
	}
	function onYouTubePlayerReady(id) {
		if ( $(id).next('.video-drawer') ) enableDrawer(id);
	}
	//This shows the drawer as depicted in the original PSD
	function enableDrawer( ytID ) {
		var yt=$(ytID),
			vp=yt.up('.video-player'),
			vd=vp.down('.video-drawer'),
			ul=vd.down('ul'),
			delay=300,
			timer=null,
			up=vd.down('.up').observe('click',scrollUp),
			down=vd.down('.down').observe('click',scrollDown);
		init();
		function init() {
			var i=0, a;
			while( a = ul.down('a',i++) ){
				a.observe('click',function(e){
					e.stop();
					var a=e.target.up('a');
					yt.loadVideoById( a.href.match(/v=(.+?)$/)[1] );
					vp.down('.video-caption').update('<span>Video:</span>'+a.title);
				});
			}
			refreshButtons();
		}
		function smoothScroll(end) {
			var start = ul.scrollTop,
				diff = end-start,
				time = (new Date).getTime()+delay;
			if (timer) clearInterval(timer);
			timer=setInterval(function(){
				var f=time-(new Date).getTime();
				if( f > 0 ) {
					ul.scrollTop=end-Math.floor( diff*f/delay );
				} else {
					ul.scrollTop=end;
					refreshButtons();
				}
			},fd);
		}
		function scrollUp(e) {
			e.stop();
			smoothScroll(Math.max.apply(Math,[0,ul.scrollTop-ul.clientHeight]));
		}
		function scrollDown(e) {
			e.stop();
			smoothScroll(Math.min.apply(Math,[ul.scrollHeight-ul.clientHeight,ul.scrollTop+ul.clientHeight]));
		}
		function refreshButtons() {
			if (timer) clearInterval(timer);
			if (ul.scrollTop == 0)
				up.addClassName('inactive');
			else
				up.removeClassName('inactive');
			if (ul.scrollTop == ul.scrollHeight-ul.clientHeight)
				down.addClassName('inactive');
			else
				down.removeClassName('inactive');
		}
	}
	function SelectReplacement(s) {
		var ro = new Element('input',{type:'text',readonly:'readonly',name:s.name,value:s.getValue()})
			.addClassName(s.className)
			.observe('keydown',reactKey)
			.observe('blur',unFocus)
			.observe('focus',doFocus);
		var lo = getOptionList();
		var act = new Element('span',{'class':'actuator'});
		var sr = new Element('div',{'class':'select-replacement'}).insert(ro).insert(act).insert(lo).observe('click',toggleList);
		var buffer = '';
		s.replace(sr);
		function getOptionList() {
			var ul = new Element('ul',{'class':'options'});
			s.childElements().each(function(opt){
				ul.insert(
					new Element('li', {'title':opt.value} )
						.update(opt.getText())
						.observe('click',selectItem)
				);
			});
			ul.hide();
			return ul;
		}
		function toggleList() {
			lo.toggle();
		}
		function selectItem(evt) {
			evt.stop();
			var t = evt.target;
			ro.setValue( t.title );
			lo.hide();
		}
		function reactKey(evt) {
			var kc = evt.keyCode, temp = null;
			if ( kc > 64 && kc < 90 ){
				buffer += String.fromCharCode(kc);
				trySelect(buffer);
			}
			switch ( kc ) {
				case 8:
					if ( buffer.length )
						buffer= buffer.substr(0,buffer.length-1);
					trySelect(buffer);
					break;
				case 38:
					if( temp = lo.down('.selected') )
						select( temp.previous() );
					break;
				case 40:
					if( temp = lo.down('.selected') )
						select( temp.next() );
					break;
				default:
			}
		}
		function doFocus(evt) {
			buffer = '';
			lo.descendants().invoke('show').invoke('removeClassName','selected');
			lo.show();
		}
		function unFocus(evt) {
			buffer = '';
			lo.hide();
		}
		function select(elem) {
			if ( elem ) {
				lo.descendants().invoke('removeClassName','selected');
				elem.addClassName('selected');
				ro.setValue(elem.title);
				if ( lo.scrollTop > elem.offsetTop )
					lo.scrollTop=elem.offsetTop;
				else if ( lo.scrollTop + lo.clientHeight < elem.offsetTop + elem.clientHeight )
					lo.scrollTop=elem.offsetTop + elem.clientHeight - lo.clientHeight;
			}
		}
		function trySelect (str) {
			var c = lo.descendants().select(function(e){
				var text = (e.getText()),
					title = e.title,
					regexp = new RegExp('^'+str,'i');
				return !!(title.match(regexp) || text.match(regexp));
			});
			switch (c.size()) {
				case 1:
					select(c[0]);
				case 0:
					lo.descendants().invoke('show');
					break;
				default:
					select(c[0]);
					lo.descendants().invoke('hide');
					c.invoke('show');
			}
		}
	}
	function Gallery(target) {
		var root = $(target);
		var current = 0;
		var maximum = 0;
		var data = [];
		var map = {};
		var timer = null;
		var rotate = null;
		var imgBase = '';
		var next = root.down('.next');
		var prev = root.down('.prev');
		var link = root.down('.gallery-content a');
		if (next) next.observe('click',goNext);
		if (prev) prev.observe('click',goPrev);
		if (link) linkify(root.down('.gallery-item'),link);
		init();
		function getOptions() {
			var params = {}, temp = null;
			$w(root.className).each(function(cn){
				if( cn.indexOf('-')>0 ){
					temp = cn.split('-');
					params[temp[0]]=temp[1];
				}
			});
			return params;
		}
		function init() {
			var opts = getOptions(), x;
			for (x in opts) {
				switch(x){
					case 'data':
						if( opts[x] in window )
							data = window[opts[x]];
						break;
					case 'img':
					case 'title':					
					case 'href':
					case 'text':					
						map[x]=opts[x];
						break;
					case 'rotate':
						rotate = parseInt(opts[x]);
						break;
					case 'base':
						if( opts[x] in window )
							imgBase = window[opts[x]];
				}
			}
			if ( data.length > 0 ) {
				maximum = data.length - 1;
				set( Math.floor( Math.random() * maximum ) );
			} else {
				buttonRefresh();
			}
			if (rotate) {
				with (root) {
					observe('mouseover',stopRotate);
					observe('mouseout',startRotate);
				}
				startRotate();
			}
		}
		function stopRotate() {
			if(timer) {
				clearInterval(timer);
				timer=null;
			}
		}
		function startRotate() {
			if( !timer && rotate ) {
				timer=setInterval(loop,rotate);
			}
		}
		function goNext(e) {
			e.stop();
			if( current < maximum )
				set(current+1);
		}
		function goPrev(e) {
			e.stop();
			if( current > 0 )
				set(current-1);
		}
		function set(idx) {
			if( idx > maximum || idx < 0 )
				return;
			var active=data[idx];
			if( typeof(active) == 'string' ){
				root.down('.gallery-item').update(active);
			} else {
				for( var x in map ){
					
					switch(x){
						case 'img':
							root.down('.gallery-item').style.backgroundImage='url('+imgBase+active[map[x]]+')';
							break;
						/*start :changes made here for removing href link from partners banner (5 aug 2011)*/
						/*case 'title':
							root.down('.gallery-content a').update(active[map[x]]);
							break;*/
						case 'href':
							root.down('.gallery-content a').href=active[map[x]];
							break;
					/*	case 'text':
							root.down('.gallery-item').update(active[map[x]]);*/
							/*change end*/
					}
				}
			}
			current = idx;
			buttonRefresh();
		}
		function buttonRefresh() {
			if( current == maximum )
				next.addClassName('inactive');
			else
				next.removeClassName('inactive');
			if( current == 0 )
				prev.addClassName('inactive');
			else
				prev.removeClassName('inactive');
		}
		function loop() {
			set(current == maximum?0:current+1);
		}
	}
	function ajaxBind() {
		$$('input[type=file]').map(simpleUpload);
		$$('form:not(.validating)')
			.invoke('addClassName','validating')
			.invoke('observe','submit',function(e){
				var f=e.target;
				if( f.validate() ) {
					var m=f.down('[name=method]');
					if( m ){
						new Ajax.Updater(f.up(), '/cfcs/userAjax.cfc?returnFormat=plain', {
							parameters: f.serialize(),
							method: 'POST'
						});
					} else return;
				}
				//Focus on the first field with an error
				var _lb = f.down('.error'), _for = null;
				if (!!_lb)
				if( _for = _lb.readAttribute('for') ) $(_for).focus();
				else if ( _for = _lb.down(':input') ) _for.focus();
				e.stop();
			})
			.invoke('getElements')
			.invoke('invoke','observe','change',function(e){fieldValid(e.target);});
	}
	function simpleUpload(fi, idx){
		var id = fi.identify(),
			fv = {
				pathUploadScript:'http://awesome.discoveryeducation.com/functions/builder-upload.cfm',
				type: 'Videos',
				maxupload: 1000,
				completeFunc:'fileUp'+idx
			},
			params = { allowScriptAccess: "always", wmode: 'transparent' },
			hi=new Element('input',{type:'hidden',name:fi.name,'class':fi.className});
		//Parse class name rules
		$w(fi.className).each(function(A){
			var a=A.split('-');
			if( a[0] in fv )
				fv[a[0]] = a[1];
		});
		if ( !(fv.completeFunc in window) ){
			window[fv.completeFunc] = function(fn) { fireEvent(hi.setValue(fn),'change'); $(id).replace( new Element ('a',{href:'http://static.discoveryeducation.com/feeds/builders/'+fn,target:'_blank'}).update('View Uploaded File') )};
		}
		var atts = {id: id, 'class':'simple-upload'};
		fi.getLabel().insert(hi);
		swfobject.embedSWF("http://static.discoveryeducation.com/global/swf/generic-upload.swf",
			id, "535", "150", "9", null, fv, params, atts);
	}
	function formValid(form) {
		$$('form ul.errors').invoke('remove');
		return !form.getElements().reject(fieldValid).size();
	}
	function clearValidationError(field) {
		var l;
		if( l=getLabel(field) ) l.removeClassName('error').writeAttribute('title',false);
	}
	function fieldValid(field) {
		var rules = $w(field.className),
			empty = field.getValue() == "",
			err = [],
			temp, x, y, z;
		if( field.tagName.toLowerCase() == 'input' ){
			switch( field.type ) {
				case 'radio':
					//Radio is empty if no member is selected
					empty = $$('input[name='+field.name+']').select(function(e){ return e.checked; }).size() == 0;
					break;
				case 'checkbox':
					//checkbox is empty if unchecked
					empty = field.checked;
			}
		}
		if (empty){
			if (rules.member('req')) err.push('This field is required');
		} else {
			if (rules.any(fieldValid.and)) {
				temp=rules.select(fieldValid.and);
				while( x=temp.pop() ) {
					y = field.up('form').getElements().findAll(fieldValid.hasClass(x));
					if( y.select(fieldValid.isEmpty).size() != 0 && y[0] == field ){
						err.push('Please enter each of '+y.invoke('getLabelName',true).reject(_empty).join(' and '));
					}
				}
			}
			if (rules.any(fieldValid.checkPattern)) {
				temp=rules.select(fieldValid.checkPattern);
				while( x=temp.pop() ) {
					if( !field.getValue().match(fieldValid.pattern[x].regexp) ){
						err.push(fieldValid.pattern[x].msg);
					}
				}
			}
			
		}
		if (rules.any(fieldValid.xor)) {
			temp=rules.select(fieldValid.xor);
			while( x=temp.pop() ) {
				y = field.up('form').getElements().findAll(fieldValid.hasClass(x)).invoke('enable');
				if( y.reject(fieldValid.isEmpty).size() != 1 ){
					if( y[0] == field ) err.push('Enter '+y.invoke('getLabelName',true).reject(_empty).join(' or '));
				} else {
					y.select(fieldValid.isEmpty).invoke('disable');
				}
			}
		}
		if (err.length) {
			showValidationError(field,err.join(';'));
			return false;
		} else {
			clearValidationError(field);
			return true;
		}
	}
	fieldValid.xor = startsWith('xor');
	fieldValid.and = startsWith('and');
	fieldValid.isEmpty = function(e) { return e.getValue() == ""; };
	fieldValid.hasClass = function(x){ return function(e){ return e.hasClassName(x); }; };
	fieldValid.checkPattern = function(e) { return (e in fieldValid.pattern); };
	fieldValid.pattern = {
		email: {regexp:/^[a-z0-9._-]+@([a-z0-9-]+\.)+[a-z]{2,6}$/i,msg:'Please enter a valid email address'},
		phone: {regexp:/^(\d{3}\W?){2}\d{4}$/,msg:'Please enter a 10-digit phone number'},
		zip: {regexp:/^\d{5}(-\d{4})?$/,msg:'Please enter a valid zip code'}
	};
	
	function startsWith( prefix ) {
		return function (str) { return str.split('-')[0] == prefix; };
	}
	function showValidationError(field, msg) {
		var label;
		if( label=getLabel(field) ) {
			label.addClassName('error')
				.writeAttribute({title:msg});
		} else {
			if ( !field.up('form').down('ul.errors') ){
				field.up('form').insert({top:'<ul class="errors"></ul>'});
			}
			label=field.up('form').down('ul.errors');
			label.insert('<li>'+field.getLabelName()+': '+msg+'</li>');
		}	
	}
	function getLabel (field) {
		var label = field.up('label'),
			id = field.id,
			temp;
		//Special case for radio inputs
		if (field.up('.select_group')) {
			return field.up('.select_group').siblings().find(function(a){return a.hasClassName('label-like');});
		}
		if ( !label && id ) {
			temp = $$('label[for='+id+']');
			if ( temp.size() ) label=temp[0];
		}
		return label;
	}
	function getLabelName (field) {
		var l = getLabel(field);
		return l?l.getText():(arguments.length>1?'':field.readAttribute('name'));
	}
	function getText (elem) {
		if ( !getText.textProperty ){
			var _p = ['innerText','textContent','text'];
			while( _p.length > 0 && !(_p[0] in elem) ) _p.shift();
			getText.textProperty=_p[0];
		}
		return elem[getText.textProperty];
	}
	function confirmOnExit(bool) {
		if(bool){
			//Remove confirm
			if ('f' in confirmOnExit) {
				Event.stopObserving(window,'beforeunload',confirmOnExit.f,true);
				delete confirmOnExit.f;
			}
		} else {
			//Set confirm
			if( !('f' in confirmOnExit) ){
				confirmOnExit.f = function(e){ e.stop(); };
				Event.observe(window,'beforeunload',confirmOnExit.f,true);
			}
		}
	}
	Element.addMethods({ getLabel: getLabel, getLabelName: getLabelName, getText: getText});
	Element.addMethods('form',{validate:formValid});
	document.observe("dom:loaded",function(){
		$$('.gallery').each(function(target){
			var gallery = new Gallery(target);
		});
		$$('.pr-block').each(function(target){
			if( target.clientHeight > 109 ){
				target.down('.pr-blurb').style.height = '32px';
				target.insert('<a href="#" class="download"><span>Expand</span></a>');
				target.down('.download').observe('click',function(e){
					e.stop();
					target.down('.pr-blurb').style.height = 'auto';
					target.down('.download').remove();
				});
			}
		});
		$$('.pr-logo').each(function(target){
			linkify(target,target.next('a'));
		});
		$$('form.nav select').invoke('observe','change',function(e){
			$(e.target).up('form').submit();
		});
		$$('.tip-du-jour').each(function(target){
			var a = target.down('a');
			if (a)
				linkify(target,a);
		});
		$$('.video-drawer').each( function(e){
			var params = { allowScriptAccess: "always", allowFullScreen: "true" },
				atts = { id: uniqueID('player') },
				videoID = e.down('li a').href.match(/v=(.+)$/)[1],
				placeholderID = e.previous('.video-placeholder').identify();
			swfobject.embedSWF("http://www.youtube.com/v/" + videoID +
				"&enablejsapi=1&playerapiid="+atts.id,
				placeholderID, "300", "220", "8", null, null, params, atts);
		});
		if($$('.blurb').size() && $$('.video-drawer').size()){
			$$('.blurb').invoke('addClassName','blurb-compressed');
		}
		/*$$('a.widget').invoke('observe','click',function(evt){
			evt.stop();
			var e = evt.target.className == "widget"?evt.target:evt.target.up('a.widget'),
				t = $w(e.down('span.wlogo').className),
				newID = 'widget-'+t;
			if ( $(newID) ) return;
			var params = { allowScriptAccess: "always", wmode: 'transparent' },
				atts = {},
				wname = t.find(function(a){ return a != 'wlogo'; }),
				fv = {data: '/flash/'+wname+'.xml'},
				m = e.up('.module'),
				w = m.clientWidth;
			m.insert({after: new Element('div',{'class':'widget-module',style:'width: '+w+'px'}).insert( 
				new Element('a', {
					href:'http://get.adobe.com/flashplayer/',
					target:'_blank',
					id:newID
				}).update( new Element('img',{src:'/flash/widget-noflash-'+wname+'.png'}) )
			)});
			swfobject.embedSWF("/flash/widget_"+wname+".swf", newID, w, "310", "10", null, fv, params, atts);
		});*/
		if ( 'print' in window ) {
			(function() {
				var da = $$('.download-all');
				if ( da.size() > 0 )
					da[da.size()-1].insert({after:'<a href="#" class="print"><span>Print</span></a>'});
				$$('.print').invoke('observe','click',function(e){e.stop();window.print();});
			}) ();
		}
		$$('select.replace').each(function(s){new SelectReplacement(s)});
		ajaxBind();
		hashUpdate();
		//if there are 2 placeholder forms, please toggle them
		var _tf = $$('form.placeholder');
		if (_tf.size() == 2) {
			var _tfa = function(_evt){_evt.stop();_tf.invoke('toggle');}
			_tf[1].hide().down('p.form-instructions').insert( new Element('a',{href:'#'}).update('New entry').observe('click',_tfa) );
			_tf[0].down('p.form-instructions').insert( new Element('a',{href:'#'}).update('Already entered?').observe('click',_tfa) );
		}
		if($$('.tip-du-jour').invoke('getStyle','backgroundImage').any(function(d){return !!d.match(/gif/);})){
			$$('.tip-du-jour')
				.invoke('observe','mouseover',function(evt){$$('.tip-du-jour').invoke('addClassName','hover');})
				.invoke('observe','mouseout',function(evt){$$('.tip-du-jour').invoke('removeClassName','hover');});
		};
});
	
if ('onhashchange' in window){
	Event.observe(window,'hashchange',hashUpdate);
} else {
	setInterval(hashUpdate, 250);
}

