$(document).ready(function(){
	document.LAB_FEE_COUNTER = 0;
	
	$('#bottom_left a').each(function(){
		var aClass = $(this).attr('class');
		var aHref = $(this).attr('href');

		if (
				typeof aClass !== 'undefined'
				&& aClass !== false
				&& typeof aHref !== 'undefined'
				&& aHref !== false
		) {
			$(this).click(function(){
				var content = $('#bottom_right .content.body .' + aClass);

				if ($(content).length) {
					if ($(content).is(':hidden')) {
						$(content).show();
						$(content).siblings('div').hide();
					}
					return false;
				} else {
					
				}
			});
		}
	});

	var changeContentType = function (selector) {
		var type = '';
		$(selector).each(function(){
			if ($(this).attr('checked') == 'checked') {
				type = $(this).val(); 
			}
		});

		if (type == 'Location') {
			$('.input.pages.select').hide().children('select').val('');
			$('#ContentTitle').parent('div.input').hide();
			$('.input.locations.select').show();
		} 
		if (type == 'Page') {
			$('.input.locations.select').hide().children('select').val('');
			$('#ContentTitle').parent('div.input').show();
			$('.input.pages.select').show();
		} 		
	}
	
	var conType = $('[name="data[Content][type]"]');
	changeContentType(conType);
	conType.change(function(){
		changeContentType(conType);
	});
	
	$('button.form.reset').click(function(){
		var pathName = $(this).parents('form').attr('action').split('/');
		pathName.length = 3;
		document.location = pathName.join('/');
	});

	$('#ReportForm .add.row').click(function(){
		var parent = $(this).parents('table');
		var target = parent.children('tbody:first').children('tr:last');
		var clone = target.clone();
		
		var numberRegEx = /[0-9]+/;
		
		number = Number(numberRegEx.exec($('td:first input', clone).attr('id')));
		number++;
		
		$('input, select', clone).each(function(){
			var id = $(this).attr('id');
			var name = $(this).attr('name');
			var re = /\d+/;
			
			if ($(this).hasClass('hasDatepicker')) {
				$(this).removeClass('hasDatepicker');
			}

			$(this).attr('id',id.replace(re, number));
			$(this).attr('name',name.replace(re, number));
			$(this).val('');
		});
		parent.children('tbody:first').append(clone);
		
		addEvents();
		
		return false;
	});


	function addEvents () {
		$('tr td a.delete.row').click(function(){
			$(this).parents('tr').remove();
			
			return false;
		});

		$('.lab.price.unit select').each(function(){
			function update (obj) {
				//var labUnitPrice = parseFloat($(obj).val());
				var labUnitPrice = $(obj).val();
				var quantity = 0;
				var retailUnitPrice = 0;

				if (document.LAB_FEE_COUNTER > 0) {
					$(obj).siblings('input.description.test').val($("#" + $(obj).attr('id') + " option[value='" + labUnitPrice + "']").text());
				}

				if (isNaN(labUnitPrice)) {
					labUnitPrice = 0;
				}
				labUnitPrice = parseFloat($(obj).val());
				$(obj).parents('td').siblings('td.fee.lab.price.unit').text('$' + labUnitPrice.toFixed(2));
				
				quantity = $(obj).parents('td').siblings('.quantity').children('input').val();
				retailUnitPrice = $(obj).parents('td').siblings('.price.retail.unit').children('input').val();
				
				updateRow(quantity, retailUnitPrice, labUnitPrice, $(obj).parents('tr'));
			}
			update(this);
			$(this).change(function(){
				update(this);
			});
		});
	
		$('.quantity input').each(function(){
			function update (obj) {
				var labUnitPrice = 0;
				var quantity = parseInt($(obj).val());
				var retailUnitPrice = 0;
			
				if (isNaN(quantity)) {
					$(obj).val('');
				} else {
					$(obj).val(quantity);
				}
				
				labUnitPrice = $(obj).parents('td').siblings('.lab.price.unit').children('select').val();
				retailUnitPrice = $(obj).parents('td').siblings('.price.retail.unit').children('input').val();
		
				updateRow(quantity, retailUnitPrice, labUnitPrice, $(obj).parents('tr'));
			}
			update(this);
			$(this).blur(function(){
				update(this);
			});
		});
	
		$('.price.retail.unit input').each(function(){
			function update (obj) {
				var labUnitPrice = 0;
				var quantity = 0;
				var retailUnitPrice = parseFloat($(obj).val());
				
				if (isNaN(retailUnitPrice)) {
					$(obj).val('');
				} else {
					$(obj).val(retailUnitPrice.toFixed(2));
				}
		
				quantity = $(obj).parents('td').siblings('.quantity').children('input').val();
				labUnitPrice = $(obj).parents('td').siblings('.lab.price.unit').children('select').val();
				
				updateRow(quantity, retailUnitPrice, labUnitPrice, $(obj).parents('tr'));
			}
			update(this);
			$(this).blur(function(){
				update(this);
			});
		});
		
		$(".billType select").each(function(){
			setCodDate(this);
		}).change(function(){
			setCodDate(this);
		});

		if (typeof $.datepicker !== "undefined") {
			$("#ReportForm td.date input").datepicker({dateFormat:'yy/mm/dd'});
		}
	}

	addEvents();
	
	function updateTotals () {
		var qty = 0;
		var gross = 0.0;
		var labFees = 0.0;
		var net = 0.0;
		var commission = 0.0;
		var payToContractor = 0.0;
		var codTotal = 0.0;
		
		var moneyRegEx = /[0-9]+\.[0-9]{2}/;
		
		var moneyClasses = [
			['.gross',0.0]
			,['.fee.lab.total',0.0]
			,['.money.net.sub',0.0]
			,['.commission.fee',0.0]
			,['.net.total',0.0]
		];
		
		var tmp = '';
		
		$('tbody .quantity input').each(function(){
			tmp = parseInt($(this).val());
			if (isNaN(tmp)) {
				tmp = 0;
			}
			
			qty += tmp;
		});
		$('tfoot .quantity').text(qty);
		
		for (i in moneyClasses) {
			$(moneyClasses[i][0], 'tbody').each(function(){
				tmp = $(this).text();
				tmp = parseFloat(moneyRegEx.exec(tmp));
				if (isNaN(tmp)) {
					tmp = 0.0;
				}
				moneyClasses[i][1] += parseFloat(tmp);
				
				if (moneyClasses[i][0] == '.gross' && $(this).parents('tr').children('td.billType').children('select').val() == 'COD') {
					codTotal += tmp;
				}
			});

			$(moneyClasses[i][0], 'tfoot').text('$' + moneyClasses[i][1].toFixed(2));
			$('tfoot .cod.total').text('$' + codTotal.toFixed(2));
		}
	}
	
	function updateRow (quantity, retailUnitPrice, labUnitPrice, rowObject) {
		var COMMISSION_RATE = 0.075;//7.5%
		var qty = parseInt(quantity);
		var retail = parseFloat(retailUnitPrice);
		var lab = parseFloat(labUnitPrice);
		var gross = 0.0;
		var labTotal = 0.0;
		var net = 0.0;
		var commission = 0.0;
		var payToContractor = 0.0;

		if (isNaN(qty)) {
			qty = 0;
		}
		if (isNaN(retail)) {
			retail = 0.0;
		}
		if (isNaN(lab)) {
			lab = 0.0;
		}

		gross = qty * retail;
		labTotal = qty * lab;
		// labTotal can be zero
		//if (gross && labTotal) {
			net = gross - labTotal;
			commission = COMMISSION_RATE * net;
			payToContractor = net - commission;
		//}

		rowObject.children('.gross').text('$' + gross.toFixed(2));
		rowObject.children('.fee.lab.total').text('$' + labTotal.toFixed(2));
		rowObject.children('.net.sub').text('$' + net.toFixed(2));
		rowObject.children('.commission.fee').text('$' + commission.toFixed(2));
		rowObject.children('.net.total').text('$' + payToContractor.toFixed(2));
		
		updateTotals();
	}

	function setCodDate (billTypeObj) {
		if ($(billTypeObj).val().toLowerCase() == "cod") {
			$(billTypeObj).parents('td').siblings('td.cod.date').children('input').removeAttr("disabled");
		} else {
			$(billTypeObj).parents('td').siblings('td.cod.date').children('input').val("");
			$(billTypeObj).parents('td').siblings('td.cod.date').children('input').attr("disabled", "disabled");
		}

		updateTotals();
	}

	//Hack to fix incorrect option selected in lab type
	function fixLabType () {
		var description = "";
		var hiddenInput = "";
		var priceSelect = "";
		var value = "";
		
		$(".description.test").each(function(){
			hiddenInput = $(this);
			description = hiddenInput.val();
			priceSelect = $(this).siblings('select');
			
			priceSelect.children('option').each(function(){
				if ($(this).text() != description) {
					$(this).removeAttr('selected');
				} else {
					value = $(this).val();
				}
			});
			priceSelect.val(value);
			//alert("two");
			document.LAB_FEE_COUNTER++;
		});
	}
	
	//Fires after document ready. Doesn't need to fire at other times
	fixLabType();
	
	var id_for_wysiwyg = 'top_right_content';
	if ($('#id_for_content').length) {
		id_for_wysiwyg= $('#id_for_content').val();
	}
	
	$('textarea.tinymce').tinymce({
		body_id:id_for_wysiwyg
		,content_css:'/css/layout.css'
		,script_url:'/js/tiny_mce/tiny_mce.js'
		,theme:"advanced"
		,theme_advanced_buttons4 : "forecolor,backcolor,fontselect"
		,theme_advanced_fonts : "Andale Mono=andale mono,times;"+
								"Arial=arial,helvetica,sans-serif;"+
								"Arial Black=arial black,avant garde;"+
								"Book Antiqua=book antiqua,palatino;"+
								"Comic Sans MS=comic sans ms,sans-serif;"+
								"Courier New=courier new,courier;"+
								"Georgia=georgia,palatino;"+
								"Helvetica=helvetica;"+
								"Impact=impact,chicago;"+
								"Symbol=symbol;"+
								"Tahoma=tahoma,arial,helvetica,sans-serif;"+
								"Terminal=terminal,monaco;"+
								"Times New Roman=times new roman,times;"+
								"Trebuchet MS=trebuchet ms,geneva;"+
								"Verdana=verdana,geneva;"+
								"Webdings=webdings;"+
								"Wingdings=wingdings,zapf dingbats"
	});
});
