window.addEvent('domready', function() {


	var arr = Array('protocol', 'invoice', 'price','contract');

	for(i=0;i<arr.length;i++) {

		var str = arr[i];
		//console.log(str);
		if ($(str)) {
			$(str).addEvent('click', function() {
				toggleField(this);
			});
		}


	}

	function toggleField(el) {
		if ($(el.id + '_e')) {
			var hiddenDiv = $(el.id + '_e');

			if (el.type == 'checkbox') {
				if (el.checked == true) {
					hiddenDiv.setStyle('display', 'block');
				} else {
					hiddenDiv.setStyle('display', 'none');
				}
			}
		}
	}


	$$('table#priceTbl tr td a.addMe').each(function(item) {
		item.addEvent('click', function() {
			// we clicked the +.. thats awesome

			var tr = item.getParent('tr');

			// clone the entire <tr>
			var html = tr.clone();

			// Find the <tbody>
			var tbod = item.getParent('tbody');

			// Get a collection of rows..
			var tRows = tbod.getElements('tr');

			// Figure out which row to insert it into..
			if ((tRows.length - 1) >= 0) {
				var insInto = tRows[tRows.length-1];
			} else {
				var insInto = tRows[0];
			}



			// Copy all the inputs values into the new fields we've just made
			// (IE does this anyway... firefox doesnt..)
			var i = 0;
			html.getElements('input').each(function(inp) {
				inp.value = tr.getElements('input')[i].value
				i++;
			});

			// Now set the a so that it takes away a row!
			html.getElement('a').set({'html':'<img alt="delete this product" src="/images/icons/minus.gif"/>'}).addEvent('click', function() {
				this.getParent('tr').destroy();
			});;


			// Add it into the page
			html.inject(insInto, 'before');


			// clear the vals of the old inputs
			tr.getElements('input').each(function(inp) {
				// Clear ALL values within the tr.
				inp.set('value', '');
			});


		});
	});
});
