// Allows multiple onload events to be added to your page.
function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn);
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
      {
        oldfn();
        fn();
      };
    }
  }
}

// Add Listeners below
addLoadListener(printForm);
addLoadListener(hideBodySections);
addLoadListener(attendeeUpdate);
addLoadListener(javascriptOn);
addLoadListener(javascriptOff);

function printForm() {
	var printButton = document.getElementById('print_button');
	printButton.onclick = function() {
		window.print();
	};
	return false;
}

function hideBodySections() {
	var bodySectionsHide = getElementsByClassName(document, 'div','section_body');
	for (i=0; i< bodySectionsHide.length; i++) {
		bodySectionName = 'section' + i + '_body';
		offsetHeight = bodySectionsHide[i].offsetHeight + 15;
		bodySectionsHide[i].animation = new OpenCloseAnimation(bodySectionName,offsetHeight);
		bodySectionsHide[i].animation.startClose(true);
	}
	//showBodySection(1);
}

var attendeeLoad = 0; // Allows for auto-expansion of 1st section after entering attendee value
function attendeeUpdate() {
	var attendeeInput = document.getElementById('attendee_total');
	attendeeInput.onkeyup = function() {
		if (attendeeLoad == 0) {
			showBodySection(1);
			attendeeLoad = 1;
		}
		totalForm();
	};
}

function showBodySection(x) {
	if (attendeeLoad == 0) attendeeLoad = 1; // Removes the section 1 animation if user expands section before entering attendee value
	var bodySectionName = 'section' + x + '_body';
	var bodySectionControlName = 'section' + x + '_controlShow';
	var bodySection = document.getElementById(bodySectionName);
	var bodySectionControl = document.getElementById(bodySectionControlName);
	var bodySectionHeight = bodySection.style.height;
	if (bodySectionHeight == '0px') {
		
		bodySection.animation.startOpen();
		//bodySection.style.height = 'auto';
		bodySectionControl.src = 'images/icons/minus.gif';
		bodySectionControl.setAttribute('alt','Collapse Section Icon');
		bodySectionControl.setAttribute('title','Collapse this section');
		var sectionInputs = bodySection.getElementsByTagName('input');
		for (i = 0; i < sectionInputs.length; i++) {
			sectionInputs[i].style.display = 'inline';
		}
	} else {
		bodySection.animation.startClose();
		//bodySection.style.height = '0px';
		bodySectionControl.src = 'images/icons/plus.gif';
		bodySectionControl.setAttribute('alt','Expand Section Icon');
		bodySectionControl.setAttribute('title','Expand this section');
		var sectionInputs = bodySection.getElementsByTagName('input');
		setTimeout(function() {
			for (i = 0; i < sectionInputs.length; i++) {
				sectionInputs[i].style.display = 'none';
			}
		} , 700);
	}
}

function hideInputs(section) {
	var sectionInputs = section.getElementsByTagName('input');
	for (i = 0; i < sectionInputs.length; i++) {
		sectionInputs[i].style.display = 'none';
	}
}

function addRow(x) {
	var sectionBodyIdName = 'section' + x + '_body';
	var sectionBodyAddName = 'section' + x + '_addrow';
	var defaultRows = getElementsByClassName(document.getElementById(sectionBodyIdName), 'div', 'section_body_item');
	var addedRows = getElementsByClassName(document.getElementById(sectionBodyIdName), 'div', 'section_body_item_add');
	var addedFieldCount = addedRows.length;
	var fieldCount = defaultRows.length + addedRows.length;
	if (addedFieldCount > 0) {
		var lastAddedRowNumber = (addedRows[addedFieldCount-1].getAttribute('id').substring(15));
		var fieldCount = lastAddedRowNumber;
	}
	fieldCount++;
	var newRow = document.createElement('div');
	newRow.type = 'text';
	newRow.name = 'section' + x + '_newrow_title' + fieldCount;
	newRow.id = 'section' + x + '_newrow' + fieldCount;
	newRow.className = 'section_body_item_add';
	var sectionBodyId = document.getElementById(sectionBodyIdName);
	var sectionBodyAdd = document.getElementById(sectionBodyAddName);
	offsetHeight = sectionBodyId.offsetHeight + 25;
	sectionBodyId.animation = new OpenCloseAnimation(sectionBodyIdName,offsetHeight);
	sectionBodyId.animation.startOpen();
	sectionBodyId.insertBefore(newRow, sectionBodyAdd);
	addRowHTML =
		'<div class="section_body_control"><a href="#" onclick="deleteRow(' + x + ', ' + fieldCount + '); return false;"><img id="" src="images/icons/delete.gif" alt="Delete Option Icon" title="Delete this option" /></a></div>' +
		'<div class="section_body_input_title"><input type="text" id="section' + x + '_title' + (fieldCount-1) + '" name="section' + x + '_item[]"  /></div>' +
		'<div class="section_body_input_qty"><input type="text" id="section' + x + '_qty' + (fieldCount-1) + '" name="section' + x + '_item[]" value="0" onkeyup="updateLineItem(' + x + ',' + (fieldCount-1) + ');" /></div>' +
		'<div class="section_body_input_val">x $ <input type="text" id="section' + x + '_val' + (fieldCount-1) + '"  name="section' + x + '_item[]" value="0" onkeyup="updateLineItem(' + x + ',' + (fieldCount-1) + ');" /> =</div>' +
		'<div class="total_prefix">$</div>' +
		'<div class="section_body_input_tot"><input type="hidden" id="section' + x + '_tot' + (fieldCount-1) + '" name="section' + x + '_item[]" class="section_total" value="0" readonly /><div class="item_total" id="section' + x + '_disp' + (fieldCount-1) + '"></div></div>';
	newRow.innerHTML = addRowHTML;
}

function deleteRow(x, y) {
	var addRowId = 'section' + x + '_newrow' + y;
	var deletedRow = document.getElementById(addRowId);
	var deletedRowParent = deletedRow.parentNode;
	removedRow = deletedRowParent.removeChild(deletedRow);
	var sectionBodyIdName = 'section' + x + '_body';
	var sectionBodyId = document.getElementById(sectionBodyIdName);
	offsetHeight = sectionBodyId.offsetHeight - 25;
	sectionBodyId.animation = new OpenCloseAnimation(sectionBodyIdName,offsetHeight);
	sectionBodyId.animation.startOpen();
	totalSection(x);
}

function updateLineItem(x,y) {
	var sectionQtyName = 'section' + x + '_qty' + y;
	var sectionValName = 'section' + x + '_val' + y;
	var sectionTotName = 'section' + x + '_tot' + y;
	var sectionDispName = 'section' + x + '_disp' + y;
	var sectionQty = document.getElementById(sectionQtyName).value;
	var sectionVal = document.getElementById(sectionValName).value;
	var sectionTot = document.getElementById(sectionTotName);
	var sectionDisp = document.getElementById(sectionDispName);
	sectionTot.value =  formatTo(Math.round((sectionQty * sectionVal) * 100) / 100, 2);
	sectionDisp.innerHTML = sectionTot.value;
	totalSection(x);
	}
	
function totalSection(x) {
	var sectionName = 'section' + x;
	var sectionTotalName = 'section' + x + '_total';
	var sectionTotalDispName = 'section' + x + '_totalDisp';
	var itemTotalGroup = getElementsByClassName(document.getElementById(sectionName), 'input', 'section_total');
	var sectionTotal = 0;
	for (i=0; i < itemTotalGroup.length; i++) {
		sectionTotal = sectionTotal + parseFloat(itemTotalGroup[i].value);
	}
	var sectionTotalItem = document.getElementById(sectionTotalName);
	var sectionTotalDisp = document.getElementById(sectionTotalDispName);
	sectionTotalItem.value =  formatTo(Math.round(sectionTotal * 100) / 100, 2);
	sectionTotalDisp.innerHTML = sectionTotalItem.value;
	totalForm();
}


function totalForm() {
	// Variables
	var headerTotal = document.getElementById('attendee_total').value;
	var section1Total = document.getElementById('section1_total').value;
	var section2Total = document.getElementById('section2_total').value;
	var section3Total = document.getElementById('section3_total').value;
	var section4Total = document.getElementById('section4_total').value;
	var section5Total = document.getElementById('section5_total').value;
	var section6Total = document.getElementById('section6_total').value;
	var headerTotal = parseFloat(headerTotal);
	var section1Total = Math.round(parseFloat(section1Total) * 100) / 100;
	var section2Total = Math.round(parseFloat(section2Total) * 100) / 100;
	var section3Total = Math.round(parseFloat(section3Total) * 100) / 100;
	var section4Total = Math.round(parseFloat(section4Total) * 100) / 100;
	var section5Total = Math.round(parseFloat(section5Total) * 100) / 100;
	var section6Total = Math.round(parseFloat(section6Total) * 100) / 100;
	
	// Calculations
	var sectionTotal = (section1Total+section2Total+section3Total+section4Total+section5Total+section6Total);
	var attendeeAverage = (sectionTotal / headerTotal);
	
	var formTotalCP = document.getElementById('form_total_cp');
	var formTotalCPDisp = document.getElementById('form_total_cpDisp');
	var formTotalFooter = document.getElementById('form_total_footer');
	var formTotalFooterDisp = document.getElementById('form_total_footerDisp');
	var formAttendeeAvg = document.getElementById('form_attendee_average');
	var formAttendeeAvgDisp = document.getElementById('form_attendee_averageDisp');
	formTotalCP.value = formatTo(sectionTotal, 2);
	formTotalFooter.value =  formatTo(Math.round(sectionTotal * 100) / 100, 2);
	if (headerTotal == 0 || !headerTotal) {
		formAttendeeAvg.value = "N/A";
	} else {
		formAttendeeAvg.value =  formatTo(Math.round(attendeeAverage * 100) / 100, 2);
	}
	formTotalFooterDisp.innerHTML = formTotalFooter.value;
	formTotalCPDisp.innerHTML = formTotalCP.value;
	formAttendeeAvgDisp.innerHTML = formAttendeeAvg.value;
	addValue(section1Total, section2Total, section3Total, section4Total, section5Total, section6Total);
	
}

function addValue(u,v,w,x,y,z) {
	var flashy = getFlashMovieObject("flashy");
	flashy.SetVariable("/:wedge_sleeping", u);
	flashy.SetVariable("/:wedge_meeting", v);
	flashy.SetVariable("/:wedge_food", w);
	flashy.SetVariable("/:wedge_tech", x);
	flashy.SetVariable("/:wedge_travel", y);
	flashy.SetVariable("/:wedge_other", z);
	
}

function getFlashMovieObject(movieName) {
	if (window.document[movieName]) {
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1) {
		if (document.embeds && document.embeds[movieName]) {
			return document.embeds[movieName];
		}
	} else {
		return document.getElementById(movieName);
	}
}

function javascriptOn() {
	var jsOnElements = getElementsByClassName(document, 'div', 'javascript_on');
	for (i=0; i<jsOnElements.length; i++) {
		jsOnElements[i].style.display='block';
	}
}

function javascriptOff() {
	var jsOffElements = getElementsByClassName(document, 'div', 'javascript_off');
	for (i=0; i<jsOffElements.length; i++) {
		jsOffElements[i].style.display='none';
	}
}

function roundTo(base, precision) {
	var m = Math.pow(10, precision);
	var a = Math.round(base*m) / m;
	return a;
}

function formatTo(base, precision) {
	var a = roundTo(base, precision);
	var s = a.toString();
	
	var decimalIndex = s.indexOf(".");
	if (precision > 0 && decimalIndex < 0) {
		decimalIndex = s.length;
		s += '.';
	}
	
	while (decimalIndex + precision + 1 > s.length) {
		s += '0';
	}
	
	return s;
}
	

// ---
/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}
// ---
// Array support for the push method in IE 5
Array.prototype.push = ArrayPush;
function ArrayPush(value){
	this[this.length] = value;
}