	var loc = '/_AIR',
		baseUrl = loc + '/meridia?posid=Q74F',
		startLink = baseUrl + '&page=mainMenuMessage_reservation&action=requestAir';
	
	function loadCheckoutSection ( section, preCheckout ) {

		//if ( cart.products.length == 0 ) {
		if ( cart.products.length == 0 ) {
			$('#checkoutContent').html('<div class="_msg _err" style="padding-top:10px;padding-bottom:10px;">' +
				'Cannot proceed to the checkout process because there are no products in your shopping cart</div>');
			return false;
		}

		$('#checkoutContent')
			.block({ message:'please wait...' })
			.load( '/_ecomm/checkout/' + section + ( section.indexOf('?') >= 0 ? '&' : '?' ) + (new Date()).getTime(),
				function () {
					initLinks();
					
// XXX - hack to include only pass insurance at details section
if (console && console.log) console.log(section)

					if (section == 'details.cfm') {
						// pre-checkout modal window flow
						if ( typeof _precheckout !== "undefined" && _precheckout.length > 0  && cart.products.length > 0 ) {
							// find the pass insurance precheckout index
							var pI = -1;
							for (var i=0, iE=_precheckout.length; i < iE; i++)
								if (_precheckout[i].indexOf('passInsurance') >= 0)
									pI = i;
							if (pI != -1)
								loadPreCheckoutSection( pI, true );
						}
					}

				}
			);

		// remove flyouts
		$('#ecommNav .jfVal').stop().remove();

		// hilight the nav sections
		$('#ecommNav div[section]').css({opacity:1});
		$('#ecommNav div[section=' + section + '].navItem').addClass('blueNav')
			.nextAll('div:not([section=' + section + '])').css({opacity:.5}).unbind('click').css({cursor:'default'})
			.find('.guestSelect').unbind('click').css({cursor:'default'});
		$('#ecommNav div[section=' + section + '].navItem')
			.prevAll('.navItem').addClass('greenNav').css({cursor:'pointer'}).unbind('click').bind('click',
				function () {
					// load section
					loadCheckoutSection( $(this).attr('section') );
				}
			);
		
		try {

			// track the current ecommerce section
			pageTracker._trackPageview('/_ecomm/checkout/' + section);

		} catch(e) {}

			
		// load the purchase iframe if air in cart
		for ( var p = 0, pE = cart.products.length, airPurchaseLink = ''; p < pE; p++ ) {
			if ( cart.products[p].type == 'Airfare' ) {
				airPurchaseLink = cart.products[p].air.p;
			}
		}
		$('#airFrame').remove();
		if ( airPurchaseLink ) {
			
			$('body').append('<iframe name="airFrame" id="airFrame" style="display:none;" src="' + airPurchaseLink + '"></iframe>');
			
			// backup detection of successful air purchase if air has been processed and capture the confirmation number
			setInterval(function () {
				var af = $('#airFrame');
				if (af.length) {
					var conf = af.contents().find('input[name=confirmationNumber]');
					if (conf.length && conf.val() && !cart.airConfNo) {
						cart.airConfNo = conf.val();
						// now process the remainder of the sale
						//processSale();
					}
				}
			}, 500);
			
			// handle the iframe load events
			$('#airFrame').load(function () {
				
				// handle generic sabre form errors - except not for confirmation screen
				var errors = $('#airFrame').contents().find('.alert,.error,.criticalInfo'),
					airConfNo = $('#airFrame').contents().find('input[name=confirmationNumber]').val();
				if ( errors.length && !airConfNo ) {
					$('#airContent').empty();
					var errHtml = '';
					errors.each(function () {
						errHtml += '<div class="_err">' + $(this).html() + '</div>';
					});
					errHtml += '<div style="padding:10px; text-align:center;">' +
							'<div class="btn continue" style="min-width:10px; width:auto !important;"><div class="s"></div><div class="m"><div class="c" style="padding:0px 10px;">' +
								'continue' +
							'</div></div><div class="s"></div><br style="clear:both;"></div>' +
						'</div>';
					$('#checkoutContent').unblock().block({message:errHtml, css:{top:30}, centerY:false})
						.find('.continue').click(function () {
							// allow for session to be restarted
							if ( ($('#airFrame').contents().find('.alert,.error,.criticalInfo').html() || '').search(/expired/i) >= 0 ) {
								
								// remove air product from cart
								var prod = -1, p = 0, pE = cart.products.length;
								for (; p < pE; p++) {
									if (cart.products[p].type == 'Airfare') {
										prod = p;
										break;
									}
								}
								if (prod != -1)
									deleteProduct(prod);
								
								$('#airFrame').contents()[0].location.href = startLink;
								
							}
							$('#checkoutContent').unblock();
						});
					// enable search button
					$('[name=search]').attr('disabled', false); 
					// clear results
					return false;
				}
				
				// process the "review detail" step of the air checkout
				var detFm = $('#airFrame').contents().find('form[name=reviewDetailForm]');
					
				// detect if air has been processed and capture the confirmation number
				if ( airConfNo ) {
					cart.airConfNo = airConfNo;
					// now process the remainder of the sale
					processSale();
				} else if ( detFm.length ) {
					// capture input fields
					$('#airFrame').contents().find('body').append('<form method="post" action="' + loc + detFm.attr('action') + '" name="_reviewDetailForm"></form>');
					var ht = '';
					detFm.find(':input').each(function () {
						ht += $('<div>').append($(this).clone()).remove().html();
					});
					$('#airFrame').contents().find('form[name=_reviewDetailForm]').append(ht);
					// GO BABY GO
					$('#airFrame').contents().find('form[name=_reviewDetailForm]').submit();
				}
				
			});
		}
		
	}

	function updateCheckoutDashboard () {

		var section = '';
		
		// draw how many products need guests
		var countParReq = 0,
			countLiabReq = 0;
		$.each( cart.products,
			function ( key, val ) {
				if ( val.parReq )
					countParReq++;
				if ( val.liabReq )
					countLiabReq++;
			}
		);

		// cache for further processing in the leaf-node pages
        $('#ecommNav').data('countParReq', countParReq);

        var findAge = function (birthdate, valDate) {
            var longDateDiff = valDate.getTime() - birthdate.getTime(),
        age = longDateDiff * 0.000000000031689; // new gregorian date calculation
            mmsa.global.util.log('findAge() birthdate:' + birthdate.toLocaleDateString() + ' valDate:' + valDate.toLocaleDateString() + ' age:' + age);
            return age;
        }
        //
        // new check to see if we can infer purchaser allocation
        /*if (cart.products.length == 1) {
            mmsa.global.util.log('new check to see if we can infer purchaser allocation');
            $.each(cart.products, function (key, val) {
                // pass min_age validation findAge
                var passMinAge = true;
                if (val.min_age != 0 &&
                        findAge(new Date(dataservices.cart.purchaser.birth_date), new Date(val.datetime)) < parseFloat(val.min_age)) {
                    passMinAge = false;
                }
                mmsa.global.util.log('infer purchaser allocation passMinAge:' + passMinAge);
                // pass max_age validation
                var passMaxAge = true;
                if (val.max_age != 0 &&
				        findAge(new Date(dataservices.cart.purchaser.birth_date), new Date(val.datetime)) > parseFloat(val.max_age)) {
                    passMaxAge = false;
                }
                mmsa.global.util.log('infer purchaser allocation passMaxAge:' + passMaxAge);
                if (passMinAge && passMaxAge) {
                    mmsa.global.util.log('infer purchaser allocation success!');
                    val.parReq = false;
                    val.participant = -1; // make sure its still allocated to the purchaser
                }
                else {
                    mmsa.global.util.log('infer purchaser allocation failed, cannot allocate to purchaser!');
                }
            });
        }*/
        // end new
        

		/* show flow for checkout with at least one product that requires guest allocation */
		if ( countParReq > 0 ) {
		
			// handle logged in or not
			if (cart.purchaser == null) {

				section = 'login.cfm';

			} else {

				$('#ecommNav [section=login.cfm].details').html(
					'Welcome ' + cart.purchaser.first_name + ' ' + cart.purchaser.last_name +
					', please continue the checkout process');

				// select the next step - WHO
				section = 'who.cfm';

			}

			// draw WHO content to show participants
			if ( cart.participants.length > 0 ) {
				$('#ecommNav [section=who.cfm].details').html( cart.participants.length + ' guest' + ( cart.participants.length > 1 ? 's' : '' ) + ' associated with your order' );
			} else {
				$('#ecommNav [section=who.cfm].details').html( 'Add guests coming on this trip and those purchasing products for' );
			}

			$('#ecommNav [section=allocate.cfm] .detailsSub').remove();
			$('#ecommNav [section=allocate.cfm].details').append( '<div class="detailsSub">' + countParReq + ' product' + ( (countParReq > 1) ? 's' : '' ) + ' requires guests to be assigned to them</div>' );

			// draw text to show how many guests will need details
			$('#ecommNav [section=details.cfm].details').html( 'Provide required information on the ' + cart.participants.length + ' guest' + ( cart.participants.length > 1 ? 's' : '' ) + 
				' in your order' );

		} else {

			// handle logged in or not
			if (cart.purchaser == null) {

				section = 'login.cfm';

			} else {

				$('#ecommNav [section=login.cfm].details').html(
					'Welcome ' + cart.purchaser.first_name + ' ' + cart.purchaser.last_name +
					', please continue the checkout process');

				if (countLiabReq)
					section = 'liability.cfm';
				else
					section = 'finalize.cfm';

			}
		
			// hide who, allocate, details
			$('#ecommNav [section=who.cfm]').remove();
			$('#ecommNav [section=allocate.cfm]').remove();
			$('#ecommNav [section=details.cfm]').remove();
			
			// figure out of there is individual release of liability steps (e.g. MVP release)
			if (!countLiabReq)
				$('#ecommNav [section=liability.cfm]').remove();
			
		}
		
		// redraw the "step X"
		$('#ecommNav [section] .step').each(
			function (ind) {
				$(this).html( 'Step ' + ( ind + 1) );
			}
		);
		
		return section;
	
	}


	var initCheckout = function () {

		// update the dashboard logic and return the normalized section
		var section = updateCheckoutDashboard();

		// figure out pre-checkout steps
		var preCheckout = false;

		// load the normalized section - and only 1 for that matter
		loadCheckoutSection( section, preCheckout );


/* normally load pre-checkout on init - but hacked to load on finalize for pass insurance while MVP sales not happening */
		// pre-checkout modal window flow
		if ( typeof _precheckout !== "undefined" && _precheckout.length > 0 ) {
			// strip out pass insurance for init
			for (var i=0, iE=_precheckout.length; i < iE; i++)
				if (_precheckout[i].indexOf('passInsurance') >= 0)
					_precheckout.splice(i, 1);
			if (_precheckout.length > 0 && cart.products && cart.products.length) {
				// initialize history handling for precheckout modals
				$.history.callback = function (newHash) {
					if (newHash) {
						var hash = newHash.split('/'),
							section = parseInt(hash[2]);
						if (_precheckout.length > 0 && cart.products && cart.products.length)
							loadPreCheckoutSection(section || 0);
					} else {
						loadPreCheckoutSection(0, true);
					}
				}
				// show first precheckout - ignore push to history handler
				loadPreCheckoutSection(0, true);
			}
		}


	};

	// this is the global pre-checkout scope
	var pcPos = 0;
	
	function loadPreCheckoutSection ( pSection, noHistory ) {

		pcPos = pSection;
		$.get( _precheckout[pcPos], 
			function ( data ) {
				if ( $('.blockPage').length > 0 )
					$.unblockUI({ fadeOut: 0 });
				$.blockUI({ fadeIn:0, message:data, centerY:false, css:$.extend( modalCSS, { position:'absolute', opacity:1 } ) });
				initLinks();
			}
		);
		
		// do not put load into history for initial load
		if (!noHistory)
			$.history.push('/PreCheckout/' + pSection);
		
		// ensure we can see the modal
		if ( ( $('.blockMsg').offset()['top'] || 0 ) < Math.max(document.body.scrollTop || document.body.parentNode.scrollTop || 0, window.scrollY || 0) )
			window.scrollTo(0, ( ( $('.blockMsg').offset()['top'] || 0 ) - 10 ) );

	}
	
	(function ($) {
		$.history = {
			hash: window.location.hash,
			lock: false,
			cache: {},
			hashchange: function() {
				var h = $.history,
					newHash = location.hash;
				h.cache[h.hash] = $('.blockUI').clone(true);
				if (newHash !== h.hash && !h.lock)
					h.callback(newHash);
				h.hash = newHash;
				h.lock = false;
			},
			push: function (val) {
				$.history.lock = true;
				location.hash = val;
			}
		};
		$(function () {
			$(window).unbind('hashchange').bind('hashchange', $.history.hashchange);
		});
	})(jQuery);

	
