var subscribe = false;

$( function() { 
		subscribe = new Subscribe ( $('#subscribe') );
	});


function Subscribe( el ) {
	var self = this;
	var e = el;
	self.quantity = 0;
	totalBox = e.find('#subscribe-total');

	e.find('input[name=confirm]').click( function() {
			$(this).blur();
			self.confirm();
		});

	e.find('input[name=process]').click( function() {
			$(this).blur();
			self.process();
		});

	e.find('#confirm-cancel').click( function() {
		$('#subscribe-confirm').hide();
		$('#subscribe-form').show();
		});


	this.update = function() {

		var total = 0;

		e.find('input.product-selected').each( function() {

				var discount = 0;

				var r = $(this).attr('rel').split('|');
				var price = r[1];

				if ( r[2] != '' ) {
					var discounts = r[2].split(',');
					for ( i in discounts ) {
						var d = discounts[i].split(':');
						// d[0] is product, d[1] is discount amount
						if ( discount < d[1] && $('#product-selected-' + d[0]).attr('checked') ) {
							discount = d[1];
						}
					}
				}

				$('#product-price-' + r[0]).html( formatCurrency ( price - discount ) );

				if ( $(this).attr('checked') ) {
					total += price - discount;
				}

			});

		totalBox.html( '<span>' + formatCurrency ( total ) + '</span>' );
		$('#confirm-total strong').html( formatCurrency ( total ) );

	}
	
 	e.find('.dataset input.product-parent').click( function () {
			var r = $(this).attr('rel').split('|');
			if ( ! $(this).attr('checked') ) {
				$('.product-child-' + r[0] ).attr('checked', '' );
			}
			$(this).blur();
			self.update();
		});

 	e.find('.dataset input.product-child').click( function () {
			$(this).blur();
			if ( $(this).attr('checked') ) {
				var r = $(this).attr('rel').split('|');
				$('input[name=product-selected-' + r[2] + ']' ).attr('checked', 'checked' );

				var n = $(this).attr('name');

				if ( 'product-selected-TTA_daily' == n ) {
					$('input[name=product-selected-TTA_monthly]' ).attr('checked', '' );
				} else if ( 'product-selected-TTA_monthly' == n ) {
					$('input[name=product-selected-TTA_daily]' ).attr('checked', '' );
				}
			}
			self.update();
		});


	this.validate = function() {

		var els = e.find('input.product-selected:checked');
		if ( els.length == 0 ) {
			alert ( 'Please select at least one product to subscribe to');
			scroll(0,0);
			return false;
		}
		
		e.find('input.validate-invalid').removeClass('validate-invalid');

		e.find('input.validate-numeric').each ( function () {
				var el = $(this);
				el.val( el.val().replace(/[^\d]/g, '' ) );
			});

		e.find('input.validate-mandatory').each ( function () {
				var el = $(this);
				if ( '' == el.val() ) {
					el.addClass('validate-invalid');
				}
			});

		e.find('input.validate-email').each ( function () {
				var el = $(this);
				if ( '' == el.val() || ! validateEmail ( el.val() ) ) {
					el.addClass('validate-invalid');
				}
			});

		
		var els = $('.validate-invalid');

		if ( els.length > 0 ) {
			els[0].focus();
			return false;
		}

		return true;

	}


	this.confirm = function() {

		if ( ! self.validate() ) {
			return false;
		}

		$('#subscribe-form').hide();
		$('#subscribe-confirm').show();

		$('#confirm-email').html( e.find('input[name=email]').val() );
		$('#confirm-total').show();

	}


	this.process = function() {

		$('#subscribe-confirm').hide();
		$('#subscribe-processing').show();

		var t = [];
		var products = '';
		e.find('input.product-selected:checked').each( function() {
				var n = $(this).attr('name');
				var v = $(this).val();
				if ( '' != v && NaN != v ) {
					t.push ( n + ':' + v );
				}

			});

		products = t.join('|');

		// form request
		
		request = {
			rpc: 'process',
			products_subscribed: products,
			email : e.find('input[name=email]').val(),
			username : e.find('input[name=username]').val(),
			salutation : e.find('select[name=salutation]').val(),
			name_first : e.find('input[name=name_first]').val(),
			name_last : e.find('input[name=name_last]').val(),
			organisation : e.find('input[name=organisation]').val(),
			address : e.find('input[name=address]').val(),
			city : e.find('input[name=city]').val(),
			state : e.find('input[name=state]').val(),
			postcode : e.find('input[name=postcode]').val(),
			country : e.find('select[name=country]').val(),
			phone : e.find('input[name=phone]').val()
		}

		$.post ( 
				'/subscribe', 
				request, 
				function (response) { 
					if ( response.status == 'ok' ) { 
						$('#subscribe-processing').hide();
						$('#subscribe-processed').show();
					} else if ( response.status == 'error' ) { 
						return false;
					}
					return false;
				}, 'json' );

		return false;


	}


}


// helpers

function validateEmail(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1) {
		return false; 
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
		return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
		return false;
	}

	if (str.indexOf(at,(lat+1))!=-1) {
		return false;
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
		return false;
	}

	if (str.indexOf(dot,(lat+2))==-1) {
		return false;
	}
		
	if (str.indexOf(" ") != -1) {
		return false;
	}

	return true;
}

function formatCurrency( num ) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
