var subscribe = false;

$( function() { 

		$('#amex-surcharge').hide();

		subscribe = new Subscribe ( $('#subscribe') );

		$(':input[name=payment_method]').click( function () {
				$(this).blur();
				var payment_method = $(this).val();
				if ( payment_method == 'card_quarterly' ) {
					$('#credit-card-details').show();

					//for the confirmation screen
					$('.payment-method-invoice').hide();
					$('.payment-method-card').show();
					$('.payment-method-card-quarterly').show();
					$('.payment-method-card-annual').hide();

				} else if  ( payment_method == 'card_annually' ) {
					$('#credit-card-details').show();
					//for the confirmation screen

					$('.payment-method-invoice').hide();
					$('.payment-method-card').show();
					$('.payment-method-card-quarterly').hide();
					$('.payment-method-card-annual').show();

				} else {
					$('#credit-card-details').hide();
					//for the confirmation screen
					$('.payment-method-invoice').show();
					$('.payment-method-card').hide();

				}
				subscribe.update();
			});

		$(':input[name=card_type]').click( function () {
				$(this).blur();
				subscribe.update();
			});
		
	});


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 subtotal = 0;
		var gst = 0;
		var amexSurcharge = 0;
		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') ) {
					subtotal += price - discount;
				}

			});

		// amex surcharge
		var payment_method = $('input[name=payment_method]:checked').val();

		if ( ( payment_method == 'card_annually' || payment_method == 'card_quarterly' ) ) {
			if ( $('input[name=card_type]:checked').val() == 'amex' ) {
				amexSurcharge = subtotal * 0.0275;
				amexSurcharge = Math.round( amexSurcharge * 100 ) / 100
				$('.amex-surcharge').html ( '$' + amexSurcharge );
				$('#amex-surcharge').show();
			} else {
				$('#amex-surcharge').hide();
			}
		} else {
			$('#amex-surcharge').hide();
		}
		
		gst = ( subtotal + amexSurcharge ) * 0.1;
		gst = Math.round( gst * 100 ) / 100

		total = subtotal + amexSurcharge + gst ;

		$('.subscription-subtotal').html( formatCurrency ( subtotal ) );
		$('.subscription-gst').html( formatCurrency ( gst ) );
		totalBox.html( '<span>' + formatCurrency ( total ) + '</span>' );
		$('#confirm-total strong').html( formatCurrency ( total ) );
		$('#confirm-total strong').html( formatCurrency ( total ) );
		var totalQuarterly = total / 4;
		$('#confirm-total .payment-method-card-quarterly strong').html( formatCurrency ( totalQuarterly.toFixed(2) ) );

		$('#payment-method-container p strong').html( formatCurrency ( total ) );
		$('#payment-method-container p.invoice_annually strong').html( formatCurrency ( subtotal + gst ) );
		$('#payment-method-container p.card_quarterly strong').html( formatCurrency ( totalQuarterly ) );

	}
	
 	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() {

		$('#card-error').html('').hide();;

		 var els = e.find('input.product-selected:checked');
		 if ( els.length == 0 ) {
		 	alert ( 'Please select at least one product to subscribe to');
			$('html,body').animate( {scrollTop: 0}, 1000 );
		 	return false;
		 }


		 e.find('.validate-invalid').removeClass('validate-invalid');

		 e.find(':input.validate-mandatory').each ( function () {
		 		var el = $(this);
		 		if ( '' == el.val() ) {
		 			el.addClass('validate-invalid');
		 		}
		 	});

		 e.find(':input.validate-numeric').each ( function () {
		 		var el = $(this);
		 		el.val( el.val().replace(/[^\d]/g, '' ) );
		 		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');
		 		}
		 	});
		//  validation for when payment_method = credit card 

		 var paymentMethod = $(':input[name=payment_method]:checked').val();
		 if ( undefined == paymentMethod ) {
		 	$('#payment-method-container h3').addClass('validate-invalid');
		 }
		
		 if ( paymentMethod != 'invoice_annually') {
			
			 e.find(':input.validate-card-number').each ( function () {
		 		 var el = $(this);
				 var s = el.val();
				 var cardtype = e.find(':input[name=card_type]:checked').val();

		 		 s.replace(/[^\d]/g, '' );
				 el.val( s );

	 			 if ( s == '' ) {
		 			 el.addClass('validate-invalid');
		 		 } else if ( ( cardtype == 'visa' || cardtype == 'mastercard' ) && s.length != 16 ) {
					 el.addClass('validate-invalid');
				 } else if ( cardtype == 'amex' && s.length != 15 ) {
					 el.addClass('validate-invalid');
				 }

		 	 });
			 
		 e.find(':input.validate-card-name').each ( function () {
		 		var el = $(this);
		 		if ( '' == el.val() ) {
		 			el.addClass('validate-invalid');
		 		}
		 	});

		 e.find(':input.validate-card-cvc').each ( function () {
		 		var el = $(this);
		 		el.val( el.val().replace(/[^\d]/g, '' ) );
		 		if ( '' == el.val() ) {
		 			el.addClass('validate-invalid');
		 		}
		 	});

		 	var cardType = $(':input[name=card_type]:checked').val();
		 	if ( undefined == cardType ) {
		 		$('#credit-card-details h3').addClass('validate-invalid');
		 	}
			
//		 	if current year - check month is either current month or future


		 e.find(':input.validate-card-date').each ( function () {
		 		var el = $(this);
		 		if ( '' == el.val() ) {
		 			el.addClass('validate-invalid');
		 		}
		 	});

		 	var cardExpires = $(':input[name=card_year]').val() + $(':input[name=card_month]').val() + "";
		 	if ( cardExpires != '' ) {
		 		var d = new Date();
		 		if ( cardExpires < d.format('Ym') ) {
		 			$(':input[name=card_month]').addClass('validate-invalid');
		 			$(':input[name=card_year]').addClass('validate-invalid');
		 			$(':input[name=card_month]').focus();
		 		}
		 	}
		 }
		
		 var els = $('.validate-invalid');

		 if ( els.length > 0 ) {
			 $('html,body').animate( {scrollTop: $(els[0]).offset().top - 48}, 1000 );
			 els[0].focus();
			 return false;
		 }

		return true;

	}


	this.confirm = function() {

		if ( ! self.validate() ) {
			return false;
		}

		$('#subscribe-form').hide();
		$('#subscribe-confirm').show();
		$('html,body').animate( {scrollTop: 0}, 1000 );

		$('#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(),
	
			payment_method : e.find(':input[name=payment_method]:checked').val(),
			card_type : e.find(':input[name=card_type]:checked').val(),
			card_name : e.find('input[name=card_name]').val(),
			card_number : e.find('input[name=card_number]').val(),
			card_month : e.find('select[name=card_month]').val(),
			card_year : e.find('select[name=card_year]').val(),
			card_cvc : e.find('input[name=card_cvc]').val()

		}

		$.post ( 
				'/subscribe', 
				request, 
				function (response) { 
					if ( response.status == 'ok' ) { 
						$('#subscribe-processing').hide();
						$('#subscribe-processed').show();
					} else if ( response.status == 'card-failed' ) { 
						$('#subscribe-processing').hide();
						$('#subscribe-form').show();
						$('#card-error').html(response.message).show();;
						$('html,body').animate( {scrollTop: $('#card-error').offset().top - 48}, 1000 );
						
					} else if ( response.status == 'error' ) { 
						$('#subscribe-processing').hide();
						$('#subscribe-confirm').hide();
						$('#subscribe-form').show();
						if ( response.error != undefined ) {
							for ( var i in response.error ) {
								$(':input[name=' + i + ']').addClass('validate-invalid');
							}


							var els = $('.validate-invalid');
							if ( els.length > 0 ) {
								$('html,body').animate( {scrollTop: $(els[0]).offset().top - 48}, 1000 );
								els[0].focus();
								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);
}

function formatDate ( datetime ) {

	var monthNames = new Array( "", "January", "February", "March", 
								"April", "May", "June", "July", "August", "September", 
								"October", "November", "December"
								);
	
	var year = datetime.substr ( 0, 4 );
	var month = datetime.substr ( 4, 2 );
	var monthName = monthNames[Number(month)];
	var day = datetime.substr ( 6, 2 ).replace( /^[ 0]/g, '' );

	return day + ' ' + monthName;
}

// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

