var booking = false;

$( function() { 
		booking = new Booker ( $('#expo-form') );

	});


function Booker( el ) {
	var self = this;
	var e = el;
	self.quantity = 0;
	subTotalBox = e.find('.tickets-subtotal');
	totalBox = e.find('.tickets-total');
	countrySelect = e.find('select[name=country]');

	this.update = function() {

		var total = 0;
		quantity = 0;
		e.find('input.quantity').each( function() {

				var notify = false;
				var meta = $(this).attr('rel').split('|');

				var price = meta[0];
				var min = meta[1];
				var max = meta[2];

				// save lookups. replace non-numerics
				var v = $(this).val().replace(/[^\d]/g, '' );
				if ( '' == v ) {
					v = '0';
				}

				v = parseInt( v );

				if ( '0' != v && min > 1 && v < min ) {
					v = min;
				}

				if ( v > max  ) {
					v = max;
					notify = true;
				}
			
				if ( 0 == v ) {
					$(this).val ( '' );
				} else {
					$(this).val ( v );
				}

				quantity += v;
				total += v * price;

				if ( notify ) {
					alert ( 'We do not currently have sufficient ticket stock available for your order. Your order has been adjusted to the maximum available.' );
				}

			});

		self.quantity = quantity;

		subTotalBox.html( formatCurrency ( total ) );

   		if ( countrySelect.val() != 'Australia' ) {
			$('.ticket-postage').show();
   			total += 15;
   		} else {
			$('.ticket-postage').hide();
		}

		if ( total > 10000 ) {
			$('.limit-exceeded').show();
			$('input.submit-process').attr('disabled','disabled');
		} else {
			$('.limit-exceeded').hide();
			$('input.submit-process').attr('disabled','')
		}

		totalBox.html( formatCurrency ( total ) );

	}

	this.purchase = function() {

		self.update();

		if ( ! self.validate() ) {
			return false;
		}

		// marshall ticket info
		
		var t = [];
		var tickets = '';
		e.find('input.quantity').each( function() {
				var n = $(this).attr('name');
				var v = $(this).val();
				if ( '' != v && NaN != v ) {
					t.push ( n + ':' + v );
				}

			});

  		tickets = t.join('|');

		// form request
		
		request = {
			rpc: 'process',
			tickets : tickets,
			email : e.find('input[name=email]').val(),
			name_given : e.find('input[name=name_given]').val(),
			name_family : e.find('input[name=name_family]').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(),
			signup : e.find('input[name=signup]').val()
		}

		e.find('input.submit-process').hide();
		e.find('.submit-processing').show();

		$.post ( 
				'/expo_tickets', 
				request, 
				function (response) { 
					if ( response.status == 'ok' ) { 
						window.location.href=response.paypal_url;
					} else if ( response.status == 'out-of-stock' ) { 
						alert ( 'We do not have enough tickets available for your order. Your order has been adjusted to the maximum available and the fields adjusted highlighted in yellow.' );
						e.find('.submit-processing').hide();
						e.find('input.submit-process').show();
						e.find('input.quantity').removeClass('unavailable');
						for ( i in response.stock ) {
							var item = response.stock[i];
							e.find('input[name=quantity-'+item.key+']').val(item.available).addClass('unavailable');
						}
						scroll(0,0);
						return false;
					}
					return false;
				}, 'json' );

		return false;


	}

	this.validate = function() {

		if ( self.quantity < 1 ) {
			alert ( 'Please select the number of tickets you would like to purchase' );
			return false;
		}

		e.find('input.validate-numeric').each ( function () {
				var el = $(this);
				el.val( el.val().replace(/[^\d]/g, '' ) );
			});

		e.find('input.validate-email').each ( function () {
				var el = $(this);
				if ( '' == el.val() || ! validateEmail ( el.val() ) ) {
					el.addClass('validate-invalid');
				} else {
					el.removeClass('validate-invalid');
				}
			});


		e.find('input.validate-mandatory').each ( function () {
				var el = $(this);
				if ( '' == el.val() ) {
					el.addClass('validate-invalid');
				} else {
					el.removeClass('validate-invalid');
				}
			});

		if ( ! $('input[name=agree]').attr('checked') ) {
			
			$('#conditions-label').addClass('validate-invalid');
		} else {
			$('#conditions-label').removeClass('validate-invalid');
		}
		
		var els = $('.validate-invalid');

		if ( els.length > 0 ) {
			els[0].focus();
			return false;
		}

		return true;
	}
	
	this.timer = setInterval ( self.update, 1000 );
	e.find('input.quantity').change( self.update );

	e.find('input[name=purchase]').click( function() {
			$(this).blur();
			self.purchase();
		});

}


// 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 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;
}

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 log ( s ) {
	if ( $('#log').length == 0 ) {
		$('#background').prepend('<div id="log" style="background: #fc0;">-</div>');
	}
	$('#log').html(s);
}

