var fdata = null;
var freq = ['day', 'month'];

function init_form(data) {
	var form_objs = $$('form');
	
	if(form_objs.length > 0) {
		form_objs[0].onsubmit = function() {
			$('submit_button').hide();
			$('loading_icon').show();
		}
	}
	
	
	// =================================
	// = Select Current Billing Method =
	// =================================
	
	var bmfound = false;
	var bmfirst = null;
	var bm = document.getElementsByName('billing[method]');	
	
	if(bm.length > 0) {
		for(var i=0; i<bm.length; i++) {
			if(! bmfirst) bmfirst = bm[i];
			if(bm[i].checked ) {
				bmfound = true;
				toggle_billing_method(bm[i]);
				break;
			}
		}
	
		if(! bmfound) {
			bmfirst.checked = true;
			toggle_billing_method(bmfirst);
		}
	}
	
	// ======================================================
	// = Observe input fields with prices attatched to them =
	// ======================================================
	
	for(var i=0; i<data.fields.length; i++) {
		var fi = $(document.getElementsByName('reg['+data.fields[i].uniq+']')[0]);
		if(data.fields[i].type == 'check') {
			var exp_func = toggle_export.bind(fi, data.fields[i].uniq);
			fi.observe('click', calc_total);
			fi.observe('click', exp_func);
			if(fi.checked) exp_func();
		}
		else if(data.fields[i].type == 'qbox' || data.fields[i].type == 'abox') fi.observe('change', calc_total);
	}
	
	if(data.has_cat > 0 && (data.form_type == 1 || data.form_type == 2))
		$(document.getElementsByName('info[category]')[0]).observe('change', calc_total);
	
	if(data.form_type == 3) {
		var subso = document.getElementsByName('info[subs]');
		for(var i=0; i<subso.length; i++) $(subso[i]).observe('click', calc_total);
		$(document.getElementsByName('info[amount]')[0]).observe('change', calc_total);
	}
	
	if(data.fmode > 1 && data.has_quan > 0)
		$(document.getElementsByName('info[quantity]')[0]).observe('change', calc_total);

	if(data.fmode > 1 && data.has_coupon > 0) {
		var ccode = $('coupon_update_button');
		if(ccode) $('coupon_update_button').observe('click', apply_coupon_code);
	}
	
	// =============
	// = Finish up =
	// =============

	fdata = data;
	calc_total();
	
	var agree = document.getElementsByName('info[agree]');
	if(agree.length > 0) {
		if($(agree[0]).hasClassName('xerror')) {
			var alab = $($(agree[0]).parentNode).select('label');
			if(alab.length == 1) {
				alab[0].setStyle({color: 'red'});
			}
		}
	}
}

function apply_coupon_code() {
	new Ajax.Request('/request/webconnex/get_coupon_code', {
		method:'post',
		parameters : {id : fdata.id, coupon : $(document.getElementsByName('info[coupon]')[0]).value},
		onSuccess: function(transport){
			var response = transport.responseText || '';
			var vals = response.split('|');
			for(var i=0; i<fdata.fields.length; i++) {
				if(fdata.fields[i].type == 'coupon') {
					fdata.fields[i].amount = parseFloat(vals[0]) || 0;
					fdata.fields[i].am_unit = parseInt(vals[1]) || 0;
					fdata.fields[i].setup_fee = parseFloat(vals[2]) || 0;
					fdata.fields[i].sf_unit = parseInt(vals[3]) || 0;
					fdata.fields[i].tried = 1;
					break;
				}
			}
			calc_total();
		}
	});
}

function calc_total() {
	if(fdata.form_type < 1) return;
	
	var amount = parseFloat(fdata.amount) || 0;
	var setup_fee = parseFloat(fdata.setup_fee) || 0;
	var subs = parseInt(fdata.subs) || 0;
	var subs_per = parseInt(fdata.subs_per) || 0;
	var quantity = 0;
	if(fdata.fmode > 1 && fdata.has_quan > 0) quantity = parseInt(document.getElementsByName('info[quantity]')[0].value) || 1;
	
	if(fdata.has_cat > 0 && (fdata.form_type == 1 || fdata.form_type == 2)) {
		var cats = $(document.getElementsByName('info[category]')[0]);
		var catv = cats.options[cats.selectedIndex].value;
		for(var i=0; i<fdata.cats.length; i++) {
			if(fdata.cats[i].uniq == catv) {
				amount = parseFloat(fdata.cats[i].amount) || 0;
				setup_fee = parseFloat(fdata.cats[i].setup_fee) || 0;
				subs = parseInt(fdata.cats[i].subs) || 0;
				subs_per = parseInt(fdata.cats[i].subs_per) || 0;
				break;
			}
		}
	}
	
	if(fdata.form_type == 3) {
		var subso = document.getElementsByName('info[subs]');
		for(var i=0; i<subso.length; i++) {
			if(subso[i].checked) {
				var subss = subso[i].value.split(',');
				subs = parseInt(subss[0]) || 0;
				subs_per = parseInt(subss[1]) || 0;
				break;
			}
		}
		var custom_amount = parseFloat($(document.getElementsByName('info[amount]')[0]).value) || 0;
		if(subs > 0) {
			amount = custom_amount;
			setup_fee = 0;
		} else {
			amount = 0;
			setup_fee = custom_amount;
		}
	}
	
	if(fdata.fmode > 1 && fdata.has_quan > 0 && quantity > 1) {
		amount = amount * quantity;
		setup_fee = setup_fee * quantity;
	}
	
	var base_amount = amount;
	var base_setup_fee = setup_fee;
	var days = 0;
	var quans = 0;
	
	if(subs_per == 1) days = subs * 30;
	else days = subs;
	
	if((fdata.form_type != 2 && fdata.form_type != 3) || subs < 1) {
		amount = 0;
		base_amount = 0;
		subs = 0;
		subs_per = 0;
	}
	
	for(var i=0; i<fdata.fields.length; i++) {
		var fi = $(document.getElementsByName('reg['+fdata.fields[i].uniq+']')[0]);
		var famount = parseFloat(fdata.fields[i].amount) || 0;
		var fsetup_fee = parseFloat(fdata.fields[i].setup_fee) || 0;
		
		if(fdata.fields[i].am_unit > 0 && famount > 0) {
			if(fdata.fields[i].am_unit == 1) famount = base_amount * (famount / 100);
			else if(fdata.fields[i].am_unit == 2) famount = amount * (famount / 100);	
			else if(fdata.fields[i].am_unit == 3) famount = famount * days;
			else if(fdata.fields[i].am_unit == 4) famount = famount * quans;
		}
		
		if(fdata.fields[i].sf_unit > 0 && fsetup_fee > 0) {
			if(fdata.fields[i].sf_unit == 1) fsetup_fee = base_setup_fee * (fsetup_fee / 100);
			else if(fdata.fields[i].sf_unit == 2) fsetup_fee = setup_fee * (fsetup_fee / 100);
			else if(fdata.fields[i].sf_unit == 3) fsetup_fee = fsetup_fee * days;
			else if(fdata.fields[i].sf_unit == 4) fsetup_fee = fsetup_fee * quans;
		}
		
		if(subs < 1) famount = 0;
		
		if(fdata.fields[i].type == 'check' && fi.checked) {
			amount = amount + famount;
			setup_fee = setup_fee + fsetup_fee;
		} else if(fdata.fields[i].type == 'coupon') {
			amount = amount - famount;
			setup_fee = setup_fee - fsetup_fee;		
		} else if(fdata.fields[i].type == 'qbox') {
			var quan = parseInt(fi.value) || 0;
			quans = quans + quan;
			if(quan > 0) {
				amount = amount + (famount * quan);
				setup_fee = setup_fee + (fsetup_fee * quan);
			}
		} else if(fdata.fields[i].type == 'abox') {
			var abox_amount = parseFloat(fi.value) || 0;
			setup_fee = setup_fee + abox_amount;
		} else if(fdata.fields[i].type == 'quantity' && quantity > 0) {
			quans = quans + quantity;
		} else if(fdata.fields[i].type == 'fee') {
			amount = amount + famount;
			setup_fee = setup_fee + fsetup_fee;
		} else if(fdata.fields[i].type == 'total') {
			update_total('total_'+fdata.fields[i].uniq, amount, subs, subs_per, setup_fee);
		}
		
		var lineitem = $('lineitem_'+fdata.fields[i].uniq);
		var ftext = '';	
		
		if(lineitem) {
			if(famount > 0 && subs > 0) {
				ftext = '$' + dollar_format(famount) + ' every ';
				if(subs > 1) ftext += subs + ' ';
				ftext += freq[subs_per];
				if(subs > 1) ftext += 's';
			}
			
			if(fsetup_fee > 0) {
				if(famount > 0 && subs > 0) ftext += ' + ';
				ftext += '$' + dollar_format(fsetup_fee); //+ ' one-time';
			}
			
			if(ftext != '') {
				if(fdata.fields[i].type == 'qbox') ftext += ', per quantity';
				else if(fdata.fields[i].type == 'coupon') ftext = 'Subtract ' + ftext;
				lineitem.update(' ['+ftext+']');
			} else if(fdata.fields[i].am_unit > 0 || fdata.fields[i].sf_unit > 0) {
				lineitem.update(' [to be calculated]');
			} else {
				if(fdata.fields[i].type == 'coupon' && fdata.fields[i].tried) lineitem.update('[invalid code]');
				else lineitem.update();
			}
		}
	}
	
	update_total('eric_total', amount, subs, subs_per, setup_fee, 'Total: ');
}

function update_total(elem, amount, subs, subs_per, setup_fee, prefix) {
	var total_text = '';
	elem = $(elem);
	if(! prefix) prefix = '';
	
	if(amount > 0 && subs > 0) {
		total_text = prefix + '$' + dollar_format(amount) + ' every ';
		if(subs > 1) total_text += subs + ' ';
		total_text += freq[subs_per];
		if(subs > 1) total_text += 's';
	}
	
	if(setup_fee > 0) { // one time
		if(amount > 0 && subs > 0) total_text += ' + ';
		else total_text += prefix;
		total_text += '$' + dollar_format(setup_fee); //+ ' one-time';
	}
	
	if(total_text == '') total_text = '&nbsp;'
	
	if(elem) elem.update(total_text);
}

function toggle_billing_method(obj) {
	$('credit_card').hide();
	$('bank_draft').hide();
	$('billing_common1').hide();
	$('billing_common2').hide();
	$('paypal').hide();
	$('elayaway').hide();
	switch(obj.value) {
		case '0':
			$('credit_card').show();
			$('billing_common1').show();
			$('billing_common2').show();
			break;
		case '1':
			$('bank_draft').show();
			$('billing_common1').show();
			$('billing_common2').show();
			break;
		case '2':
			$('paypal').show();
			break;
		case '3':
			$('elayaway').show();
			break;
	}
}

function toggle_export(uniq) {
	var exp = $('export_' + uniq);
	if(exp) {
		if(this.checked) $('export_' + uniq).show();
		else $('export_' + uniq).hide();
	}
}

function auto_copy(dryrun) {
	var flbs = $$('label[for^="field_"]');
	var fpbl = {};
	
	for(var i=0; i<flbs.length; i++) {
		var label = flbs[i].innerHTML.toString().replace(/<([A-Za-z]+[A-Za-z0-9]*).*>.*<\/\1>/, '').strip();
		fpbl[label] = $(flbs[i].parentNode);
	}
	
	var blbs = $$('label[for^="billing_"]');
	
	for(var i=0; i<blbs.length; i++) {
		var label = blbs[i].innerHTML.toString().replace(/<([A-Za-z]+[A-Za-z0-9]*).*>.*<\/\1>/, '').strip();
		var drycount = 0;
		if(typeof fpbl[label] != 'undefined') {
			var billf = $(blbs[i].parentNode).select('input', 'textarea', 'select');
			var fielf = fpbl[label].select('input', 'textarea', 'select');
			if(billf.length == fielf.length) {
				for(var f=0; f<billf.length; f++) {
					if(billf[f].tagName == fielf[f].tagName && (billf[f].tagName != 'INPUT' || billf[f].type == fielf[f].type)) {
						if(! dryrun) {
							var tagn = billf[f].tagName.toUpperCase();
							if(tagn == 'INPUT') {
								var itype = billf[f].type.toUpperCase();
								if(itype == 'TEXT') {
									billf[f].value = fielf[f].value;
								} else if(itype == 'CHECKBOX' || itype == 'RADIO'){
									billf[f].checked = fielf[f].checked;
									billf[f].defaultChecked = fielf[f].defaultChecked;
								} else {
									break;
								}
							} else if(tagn == 'TEXTAREA') {
								billf[f].value = fielf[f].value;
							} else if(tagn == 'SELECT') {
								billf[f].selectedIndex = fielf[f].selectedIndex;
							}
						}
						drycount++;
					} else {
						 break;
					}
				}
			}
		}
	}
	
	if(dryrun && drycount == 0) {
		$('auto_copy_wrap').hide();
	}
	
	return false;
}