function initOnChangeSubmits() {
	els = $$('.js-submitOnChange');
	els.each(function(el,index) {
		el.up('form').down('input.js-hideSubmit').hide();
		Event.observe(el,'change',function(event) {
			// Don't submit on empty values ("Choose a student"-type things)
			if($F(el) != '#') {
				el.up('form').submit();
			}
		});		
	});
}

function initTotalForm(form) {

	// set addon
	form.addOnValue = 0;
	if(form.addOn) {
		var addOn = $F(form.addOn);
		form.addOnValue = addOn;		
	}
	
	// set max
	if(form.highValue) {
		var highValue = $F(form.highValue);
		form.highValueValue = highValue;		
	}
	
	// set total possible
	if(form.totalPossible) {
		var totalPossibleValue = $F(form.totalPossible);
		form.totalPossibleValue = totalPossibleValue;		
	}
	
	calcTotals = form.select('.calcTotal').toArray();

	calcTotals.each(function(calcTotal,index){
				
		// get parent container
		pC = calcTotal.up('fieldset');
		if(!pC) pC = calcTotal.up('.fieldset');

		// is there a sibling percentage?
		calcPercent = pC.select('input.calcTotal + input.totalPercent').toArray();
		if(calcPercent) calcTotal.calcPercent = calcPercent[0];

		// get input els
		calcEls = pC.select('input:not(.calcTotal)').toArray();

		calcEls.each(function(calcEl,index){
			if(calcEl.hasClassName('totalExclude')) {
				calcEls.splice(index,1); 
			}
			// IE 6 problem here.
			var rawMultEl = calcEl.up().down('.weight');
			if(rawMultEl) {
				mult = rawMultEl.innerHTML.strip().sub('x','');
				calcEl.multiplier = mult;
			}
		});

		calcTotal.calcFields = calcEls;
	});
	form.calcTotals = calcTotals;
	startTotalFormObserver(form);
}

function startTotalFormObserver(form) {
	new Form.Observer(form,0.3,function(formEl,value) {
		form.masterTotalValue = 0;
		form.calcTotals.each(function(calcTotal,index1) {
			var total = 0;
			var mult = 0;
			calcTotal.calcFields.each(function(calcField,index2) {
				var fieldVal = 0;
				if (calcField.multiplier) {
					mult = calcField.multiplier;
				} else {
					mult = 1;
				}
				fieldValRaw = calcField.getValue();
				if(fieldValRaw == '') fieldValRaw = 0;
				fieldValRaw = parseFloat(fieldValRaw);
				if((form.highValueValue > 0) && (fieldValRaw > form.highValueValue) && !calcField.hasClassName('catAddOn')) {
					calcField.value = form.highValueValue;
					fieldValRaw = form.highValueValue;
				}
				fieldVal = parseFloat(fieldValRaw) * parseFloat(mult);
				total = total + fieldVal;
			});

			if(total > 0) {
				var calcValue = parseFloat(total) + parseFloat(form.addOnValue);
				if(calcValue > form.totalPossibleValue) {
					calcValue = form.totalPossibleValue;
				} 
				// setting the total input field value
				calcTotal.value = calcValue;
				form.masterTotalValue = parseFloat(form.masterTotalValue) + parseFloat(calcValue);
				if((calcTotal.calcPercent) && (form.totalPossibleValue)) {
					calcPercentEl = calcTotal.calcPercent;
					calcPercentValue = Math.floor((parseFloat(calcTotal.value) / parseFloat(form.totalPossibleValue))*100);
					calcPercentEl.value = calcPercentValue;
				}
			} else {
				calcTotal.value = 0;
				if(calcTotal.calcPercent) calcPercent.value = 0;
			}
		});

		if(form.masterTotal) {
			form.masterTotal.value = form.masterTotalValue;
			if(form.masterPercent) {
				a = parseFloat(form.masterTotalValue);
				b = parseFloat(form.totalPossibleValue);
				if(a > 0 && b > 0) {
					form.masterPercent.value = Math.floor((a / b)*100);
				}
			}
		}
	});	
}

function initTabbedBox(box) {
	// hide all but the first tab
	box.select('.tabbedNavContent fieldset').each(function(el,index){
		if(index != 0 && !el.hasClassName('tabPaneIgnore')) {
			el.hide();			
		}
	});

	// loop through nav
	box.select('.tabbedNavWrap ul li a').each(function(el,index){	
		if(index == 0) {
			el.up('li').addClassName('selected');			
		}
		el.setStyle({cursor:'pointer'});
		Event.observe(el,'click',function(event) {
			var trigger = event.element();
			trigger.up('li').addClassName('selected');
			trigger.up('li').siblings().each(function(sib,sIndex) {
				sib.removeClassName('selected');
			});
			box.select('.tabbedNavContent fieldset').each(function(fs,fsIndex){
				var name = trigger.readAttribute('name');
				if(name == 'all') {
					fs.show();
				} else {
					if (fs.hasClassName('tabPane_'+name)) {
						fs.show();
					} else {
						if(!fs.hasClassName('tabPaneIgnore')) {							
							fs.hide();
						}
					}					
				}
			});
		});
	});
	
}

function setMCETabIndex() {
	$$('.mceToolbarContainer > *').each(function(el) {
		el.setAttribute('tabindex','-1');
	});
}

function toggleScoreInputFields() {
	if($('scoreInputToggle')) {
		var form = $('scoreInputToggle').up('form');
		var debug = '';
		var highValue = form.highValue.value;
		var lowValue = form.lowValue.value;
		var tabIndex = 1;
		var elsToChange = form.getElementsByClassName('js-inputToggle');
		elsToChange.each(function(el,index) {
			parentEl = el.up('');
			var options;
			var value;
			var isTablet = false;
			var name = el.name;
			options = '<option></option>';
			if(el.nodeName == 'INPUT') {
				for (var i = lowValue; i <= highValue; i++) {
					if (el.value == i) {
						options = options + '<option selected="selected" value="' + i + '">' + i + '</option>';						
					} else {
						options = options + '<option value="' + i + '">' + i + '</option>';
					}
				}								
				parentEl.update('<select tabindex="' + tabIndex + '" name="' + name + '" class="js-inputToggle">' + options + '</select>');
				isTablet = true;
			} else {
				value = el.options[el.selectedIndex].value;
				parentEl.update('<input size="4" name="' + name + '" value="' + value +'" type="select" class="js-inputToggle" />');				
				isTablet = false;
			}
			if(isTablet == true) {
				createCookie('isTablet',1,1);
			} else {
				eraseCookie('isTablet');
			}
		});
	}
}

function initHighlightTableRows() {
 	var els = Element.getElementsBySelector('tr', '.highlight');
	els.each(function(el,index) {
		el.removeClassName('highlight');
	});
	els.each(function(el,index) {
		// doesn't work well in safari. Why not?
		new Effect.Highlight(el, {
			startcolor: '#FFDE00',
			duration: 1
		});
		el = el.next();
		new Effect.Highlight(el, {
			startcolor: '#FFDE00',
			duration: 1
		});
	});	
}
// Added summaryRowClickParent so that summaryRow click behavior could be properly handled with multiple tables.
var summaryRowClickParent = '';
function initScoreMultipleTable() {
	var elements = $$('table.scoreMultipleTable');
	var rows = new Array();
	var summaryRows = new Array();
	var formRows = new Array();
	elements.each(function(element,index){
		theseRows = element.select('tr');
		theseRows.each(function(thisRow, index)  {
			rows.push(thisRow);
		});
		theseSummaryRows = element.select('tr.summaryRow');
		// This is where the first row gets expanded, on open.
		if(theseSummaryRows[0]) {
			theseSummaryRows[0].hide();
			theseSummaryRows[0].next().show();
		}
		
		theseSummaryRows.each(function(thisSummaryRow, index) {
			summaryRows.push(thisSummaryRow);
		});
		theseFormRows = element.select('tr.formRow');
		theseFormRows.each(function(thisFormRow, index){
			formRows.push(thisFormRow);
		});
	});
	// var scoresWereModifiedNotice = $('scoresWereModifiedNotice');
	var hideAllScoresLinks = $$('.hideAllScores');
	var showAllScoresLinks = $$('.showAllScores');
	
	formRows.each(function(formRow,index) {
		inputs = formRow.select('input').toArray();
		i = inputs.size() - 3;
		inputs[i].addClassName('tabListener');
		inputs[0].addClassName('firstInput');
	});
	
	new Event.observe(document,'keydown',function(e) {
		if(e.keyCode == 9) {
			element = e.element();
			if(element.hasClassName('tabListener')) {
				a = element.up('tr');
				if(a) {
					b =element.up('tr').previous();
					c =element.up('tr').next();
					a.hide();
					b.show();
					updateSummaryRow(a,b);
				}
				if(c) {
					d = c.next();
					c.hide();
					d.show();
					focusEls = d.select('.firstInput').toArray();
					if(focusEls[0]) {
						focusEls[0].focus();
					}
				}
				e.stop();
			} else {
				// do nothing
			}
		}
	});

	summaryRows.each(function(summaryRow,index) {
		// The following functionality got moved up in the early part of the init.
		// This is where the first row gets expanded on open.
		// if(index == 0) {
		// 	summaryRow.hide();
		// 	summaryRow.next().show();
		// }
		summaryRow.observe('click',function(e) {
			var trigger = e.element();
			proceed = true; // by default the closing and opening works, but if updateSummaryRow returns false, then keep the current one open
			summaryRowClickParent = trigger.up(2, 'table').identify();
			formRows.each(function(formRow,index1) {
				// closing a form row
				thisParent = formRow.up(1, 'table').identify();
				if(formRow.visible() && summaryRowClickParent === thisParent) {
					formRow.hide();
					var summaryRow = formRow.previous();
					summaryRow.show();
					if(!updateSummaryRow(formRow,summaryRow)) { // If this returns false, it means that we want to stay where we are
						formRow.show();
						summaryRow.hide();
						proceed = false; // Don't proceed, keep us on this row
					}
				}
			});
			if(proceed) {
				var showEl = trigger.up('tr').next();
				var hideEl = trigger.up('tr');
				hideEl.hide();
				showEl.show();
			}
		});

		var formRow = summaryRow.next();
		var showScoreFlag = summaryRow.select('input.showScoreFlag')[0];
		var summaryRowHideScoreLinkWrap = summaryRow.select('span.hideScoreLinkWrap').toArray().first();
		var summaryRowShowScoreLinkWrap = summaryRow.select('span.showScoreLinkWrap').toArray().first();
		var formRowHideScoreLinkWrap = formRow.select('span.hideScoreLinkWrap').toArray().first();
		var formRowShowScoreLinkWrap = formRow.select('span.showScoreLinkWrap').toArray().first();
		
		if(summaryRowHideScoreLinkWrap) summaryRowHideScoreLinkWrap.observe('click',function(e) {
				summaryRowShowScoreLinkWrap.show();
				summaryRowHideScoreLinkWrap.hide();
				formRowShowScoreLinkWrap.show();
				formRowHideScoreLinkWrap.hide();
				summaryRow.up(2).select('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				showScoreFlag.setAttribute('value','0');
				Event.stop(e);
				return false;
			}
		);

		if(summaryRowShowScoreLinkWrap) summaryRowShowScoreLinkWrap.observe('click',function(e) {
				summaryRowHideScoreLinkWrap.show();
				summaryRowShowScoreLinkWrap.hide();
				formRowHideScoreLinkWrap.show();
				formRowShowScoreLinkWrap.hide();
				summaryRow.up(2).select('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				showScoreFlag.setAttribute('value','1');
				Event.stop(e);
				return false;
			}
		);

		if(formRowHideScoreLinkWrap) formRowHideScoreLinkWrap.observe('click',function(e) {
				summaryRowShowScoreLinkWrap.show();
				summaryRowHideScoreLinkWrap.hide();
				formRowShowScoreLinkWrap.show();
				formRowHideScoreLinkWrap.hide();
				summaryRow.up(2).select('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				showScoreFlag.setAttribute('value','0');
				Event.stop(e);
				return false;
			}
		);
		if(formRowShowScoreLinkWrap) formRowShowScoreLinkWrap.observe('click',function(e) {
				summaryRowHideScoreLinkWrap.show();
				summaryRowShowScoreLinkWrap.hide();
				formRowHideScoreLinkWrap.show();
				formRowShowScoreLinkWrap.hide();
				summaryRow.up(2).select('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				showScoreFlag.setAttribute('value','1');
				Event.stop(e);
				return false;
			}
		);
		
		if(hideAllScoresLinks) hideAllScoresLinks.each(function(hideAllScoresLink,index) {
			hideAllScoresLink.observe('click',function(e) {
				table = $(this).up().adjacent('table')[0];
				
				hideTableScoreLinkWraps(table, 'hide');
				showTableScoreLinkWraps(table, 'show'); 
				
				table.adjacent('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				
				showScoreFlags = table.select('input.showScoreFlag');
				showScoreFlags.each(function(input, index) {
					$(input).setAttribute('value','0');
				});
				
				Event.stop(e);
				return false;
			})
		});
			
		if(showAllScoresLinks) showAllScoresLinks.each(function(showAllScoresLink,index) { 
			showAllScoresLink.observe('click',function(e) {
				table = $(this).up().adjacent('table')[0];
				
				/*This*/ hideTableScoreLinkWraps(table, 'show');
				/* Replaces this:  formRowHideScoreLinkWrap.show();    */
				/* And this:       summaryRowHideScoreLinkWrap.show(); */ 
				
				/*This*/ showTableScoreLinkWraps(table, 'hide'); 
				/* Replaces this: 	formRowShowScoreLinkWrap.hide();    */
				/* And this:     	summaryRowShowScoreLinkWrap.hide(); */
				
				// summaryRow.up(2).select('#scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				table.adjacent('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
				// showScoreFlag.setAttribute('value','1');
				
				showScoreFlags = table.select('input.showScoreFlag');
				showScoreFlags.each(function(input, index) {
					$(input).setAttribute('value','1');
				});
				
				Event.stop(e);
				return false;
			})
		});


		// Setting up the state when the page loads
		if(showScoreFlag.readAttribute('value') == '1') {
			if(summaryRowHideScoreLinkWrap) {
				summaryRowHideScoreLinkWrap.show();
			} 
			if(formRowHideScoreLinkWrap) {
				formRowHideScoreLinkWrap.show();
			}
		} else {
			if(summaryRowShowScoreLinkWrap) {
				summaryRowShowScoreLinkWrap.show();
			}
			if(formRowShowScoreLinkWrap) {
				formRowShowScoreLinkWrap.show();
			}
		}
	});
}

function hideTableScoreLinkWraps(table, showOrHide) {
	hideWraps = table.select('span.hideScoreLinkWrap');
	if(showOrHide == 'show') {
		showTheWraps(hideWraps);
	} else {
		hideTheWraps(hideWraps);
	}
}

function showTableScoreLinkWraps(table, showOrHide) {
	showWraps = table.select('span.showScoreLinkWrap');
	if(showOrHide == 'show') {
		showTheWraps(showWraps);
	} else {
		hideTheWraps(showWraps);
	}
}

function hideTheWraps(wraps) {
	wraps.each(function(wrap, index) {
		$(wrap).hide();
	});
}

function showTheWraps(wraps) {
	wraps.each(function(wrap, index) {
		$(wrap).show();
	});
}

function updateSummaryRow(fR,sR) {
	fRInputs = fR.select('input[type=text]');
			sRCells = sR.select('td').toArray();
			var highKey = fRInputs.size() - 2;
			atLeastOneSetField = false; // set to true if a set field is found in the row
			atLeastOneUnsetField = false; // set to true if an empty field is found in the row
			confirmed = true; // Confirmed will default to true but will be set to the results of a confirm box if there are scored and unscored fields in the row
			fRInputs.each(function(input,index) {
				if(index == highKey) {
					confirmed = true;
		
					if(atLeastOneSetField && atLeastOneUnsetField) {
						confirmed = confirm('The row is only partially scored. Click "Ok" to continue editing this field or "Cancel" to edit another field.');
					}
		
					if(sRCells[index+1]) {
						tdReplace = sRCells[index+1];
						totalScore = input.value;
						totalPossible = $F(input.up('.scoreMultiple').totalPossible);
						if(totalScore == false || totalScore <= 0) {
							totalScore = 0
							calcPercentValue = 0
						} else {
							calcPercentValue = Math.floor((parseFloat(totalScore) / parseFloat(totalPossible))*100);
						}
						value = totalScore + ' / ' + totalPossible + ' = ' + calcPercentValue + '%';
						
						input.up(4).select('.scoresWereModifiedNotice')[0].setStyle({visibility: 'visible'});
						
						tdReplace.innerHTML = value;
					}
				} else {
					
					if(sRCells[index+1]) {
						tdReplace = sRCells[index+1];
						value = input.value;
						if(value == '') {
							value = '-';
							atLeastOneUnsetField = true;
						} else {
							atLeastOneSetField = true;
						}
						tdReplace.innerHTML = value;
					}
				}
			});
	return confirmed;
}


function initSecondaryCollapse() {
	var trig = $('secondaryCollapseTrigger');
	if(trig) {
		// opening event listener
		Event.observe(trig,'click',function(event) {
			if(trig.isClosed != true) {
				new Effect.Parallel (
				[	new Effect.Morph('secondary-wrap',{
						style:{
							marginLeft:'-210px'
					 	}, 
					 	queue:'end'
					}),
					new Effect.Morph('content-wrap',{
						style:{
							marginLeft:'30px'
					 	}, 
					 	queue:'end'
					})	], {duration: .5,
							afterFinish: function(effect) {
								trig.isClosed = true;
								trig.addClassName('collapsed');
							}
						}
				);
			}
		});					
		// closing event listener
		Event.observe('secondary-wrap','click',function(event) {
			if(trig.isClosed == true) {
				new Effect.Parallel (
				[	new Effect.Morph('secondary-wrap',{
						style:{
							marginLeft:'0px'
					 	}, 
					 	queue:'end'
					}),
					new Effect.Morph('content-wrap',{
						style:{
							marginLeft:'233px'
					 	}, 
					 	queue:'end'
						})	], {duration: .5,
								afterFinish: function(effect) {
									trig.isClosed = false;
									trig.removeClassName('collapsed');
								}
							}
				);
			}
		});
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

Event.observe(document,'dom:loaded',function(event) {

	// rounded corners
	Nifty("div.rounded","tl big");
	Nifty("div.rounded1","br big");
	
	// initialize onchangesubmits
	initOnChangeSubmits();

	// initialize score input toggle checkbox	
	// check tablet cookie
	if (readCookie('isTablet') == 1 && $('scoreInputToggle')) {
		$('scoreInputToggle').checked = true;
//		toggleScoreInputFields();
	}
	if($('scoreInputToggle')) {
//		Event.observe($('scoreInputToggle'),'click',function(event) {
//			toggleScoreInputFields();
//		});	
		
	}
	
	// init highlighting
	if($$('.scoreMultiple')) {
		initHighlightTableRows();
	}

	// init tabbedBox
	$$('.tabbedBox').each(function(el,index){		
		initTabbedBox(el);		
	});
	
	// init secondary collapse
	if($('secondaryCollapseTrigger')) {
		initSecondaryCollapse();
	}	
	
	// init formTotals
	$$('.totalForm').each(function(el,index){
		initTotalForm(el);
	});
	
	if($$('table.scoreMultipleTable')) {
		initScoreMultipleTable();
	};

	self.name = "blsci_parent"; 

});


/********************************************************************************************************
 *		The code for table row highlighting effect, we can move this if necessary
 ********************************************************************************************************/

Event.observe(document,'dom:loaded',function(event) {
	if($$('div.viewSelect a').length) {
		scoreAll.init();
	}
});

var scoreAll = {
	init: function() {
		// this.setUp();
		// this.typeChange();
	},
	setUp: function() {
		if(window.location.hash == '#groupSection') {
			$('studentSection').toggle();
		} else {
			if($('groupSection')) {
				$('groupSection').toggle();
			}
		}
	},
	typeChange: function() {
		students = $('studentSection');
		groups = $('groupSection');
		formView = $('scoreAllSwitch');
		if(formView) {
			Event.observe(formView, 'click', function(e) {
				Event.stop(e);

				if(students) {
					if(students.visible()) {
						scoreAll.setSwitchLanguage('student');
						// groups.show();
						// groups.show();
					}
				}
				if(groups.visible()) {
					scoreAll.setSwitchLanguage('group');
				}

				students.toggle();
				groups.toggle();
				$$('.section').toggle();
				$$('.section').toggle();
				
				return false;
			});
			if(location.hash == '#groupSection') {
				window.location.hash = '#groupSection';
				langKey = "group";
				this.setSwitchLanguage(langKey);
				// var len = formView[0].length;
				// for (var i = 0; i < len; i++) {
				// 	if(formView[0][i].value == 'groups') {
				// 		formView[0][i].selected = true;
				// 	}	
				// }
			}
		}
	},
	setSwitchLanguage: function(key) {
		link = $$('.viewSelect a');
		message = "switch to "+key+" scores";
		link[0].update(message);
	}
}



