var props_ajax = {
	request: function(hash, target, successFunction, errorFunction) {
		new Ajax.Request(target, {
			method: 'post',
			parameters: hash,
			onSuccess: function(transport) { 
				if (props_ajax._ajax_valid(transport.responseText)) {
					eval('response = '+transport.responseText);
					successFunction.call(response);
				} else {
					errorFunction.call(response);
				}
			},
			onFailure: function(transport) { 
				alert('Error connecting to server ('+target+').'); 
			}
		});
	}, 
	
	_ajax_valid: function(json) {
		if (json.length > 0) {
			eval('response = '+json);		
			if (response) return true;
		}
		return false;
	}
};

var props_forms = {
	_message_box: 0,

	validate: function(form) {
		var valid = true;
		
		// remove errors
		$(form).select('input.required.error', 'input.email.error').each(function(s) {
			s.removeClassName('error');
		});
		
		$(form).select('.val-error').each(function(s) {
			s.remove();
		});
	
		// check required		
		$(form).select('input.required', 'textarea.required').each(function(s) {
			if (!props_forms._check_required(s)) {
				s.insert({after: '<span class="val-error">This field is required.</span>'});
				s.addClassName('error');
				valid = false;
			}
		});
		
		// check emails
		$(form).select('input.email').each(function(s) {
			if (((s.hasClassName('required') && props_forms._check_required(s)) || !s.hasClassName('required')) && !props_forms._check_email($F(s))) {
				s.insert({after: '<span class="val-error">Invalid email address.</span>'});
				s.addClassName('error');
				valid = false;
			}
		});
		
		// agreements
		$(form).select('input[type=checkbox].agreement').each(function(s) {
			if (!s.checked) {
				s.insert({after: '<span class="val-error">Please agree to the above terms.</span>'});
				valid = false;
			}
		});
		
		if (valid) {
			// dump all of the empty fields
			$(form).select('input.empty').each(function(s) {
				s.value = '';
			});
		}
		
		return valid;
	},
	
	_check_email: function(str) {
		return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/.test(str);
	},
	
	_check_required: function(input) {
		return (!input.hasClassName('empty') && ($F(input) + '').length > 0);
	},
	
	blur: function(input) {
		input = $(input);
		if (($F(input) + '').length == 0) { 
			input.value = ucfirst(input.name); 
			$(input).addClassName('empty');
			
			if (input.hasClassName('password') && input.type == 'password') {
				input = props_forms._change_type(input, 'text', false);
				//input.setAttribute('type', 'text');
			}
		}
	},
	
	focus: function(input) {
		var inp = $(input);
		if (inp.hasClassName('empty')) {
			if (inp.hasClassName('password') && inp.type == 'text') {
				inp = props_forms._change_type(inp, 'password', true);
				//inp.setAttribute('type', 'password');
			}
			inp.value = '';
			inp.removeClassName('empty');
		}
	},
	
	reset: function(form) {
		form.reset();
		form.select('input.required').each(function(s) {
			s.value = ucfirst(s.name);
			s.addClassName('empty');
		});
		form.select('input[type=password].password.empty').each(function(s) {
			input = props_forms._change_type(s, 'text', false);
			//s.setAttribute('type', 'text');
		});
	},
	
	ajax_submit: function(form, message_box) {
		props_forms._message_box = message_box;
		message_box.removeClassName('error').removeClassName('success').update('');
		props_ajax.request(form.serialize(true), form.getAttribute('action'), props_forms._ajax_response, props_forms._ajax_error);
		props_forms.reset(form);
	},
	
	_ajax_response: function() {
		props_forms._message_box.addClassName(this.status).update(this.message);
	},
	
	_ajax_error: function() {
		props_forms._message_box.addClassName('error').update('There was an error processing your request.  Please try again later.');
	}, 
	
	_change_type: function(input, type, focus) {
		// change the type of the input to type
		if (/MSIE\s8/.test(navigator.userAgent) || /MSIE\s7/.test(navigator.userAgent)) {
			// microsoft makes things difficult... they don't want us to change the type, so we'll make a new element and replace it
			var n = new Element('input');
			
			// new type
			n.type = type;
			
			// copy name
			n.setAttribute('name', input.name);
			
			// copy value
			n.setAttribute('value', $F(input));
			
			// copy classes
			var a_classes = $w(input.className);
			for (var i = 0, j = a_classes.length;i<j;++i) {
				n.addClassName(a_classes[i]);
			}
			
			// save old id,
			var id = $(input).identify();
			
			$(input).replace(n);
			n.id = id;
			
			if (focus) {
				$(id).focus();
			}
			
			// setup blur / focus
			n.onfocus = function() { props_forms.focus(n); };
			n.onblur = function() { props_forms.blur(n); };
						
			return n;
		} else {
			$(input).setAttribute('type', type);
			return input;
		}
	}
};

function ucfirst(str) {
    var f = (str + '').charAt(0).toUpperCase();
    return f + str.substr(1);
}

function totalTable(row) {
	// update row total
	var up = $F(row.down('input.unit-price'));
	var qty = $F(row.down('input.quantity'));
	
	var row_price = up * qty;
	
	row.down('input.row-total').value = row_price;
	row.down('.total .value').update(formatCurrency(row_price));
	
	// update table total
	
	var total = 0;
	
	row.up('tbody').select('input.row-total').each(function(s) {
		total += $F(s) * 1;
	});
	
	row.up('table').down('tfoot .total .value').update(formatCurrency(total));
}

function formatCurrency(num) {
	// returns a number formatted like currency (27,050.38) without a currency symbol
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
	num = parseFloat(num).toFixed(2);
	
	if (num > 999) {
		// add commas
		num = num + ''; // convert to string
		var end = num.substring(num.length - 6);
		var commafy = num.substring(0, num.length - 6);
		while (commafy.length > 0) {
			if (commafy.length > 2) {
				end = commafy.substring(commafy.length - 3) + ',' + end;
				commafy = commafy.substring(0, commafy.length - 3);
			} else {
				end = commafy + ',' + end;
				commafy = '';
			}
		}
		num = end;
	}
    return '$' + num;
}
