/* Booking Form
_____________________________________________________________ */

$(function() {
    
    booking.sHomepagePanel = $('#homepage_panel').html();
    booking.homepagePanelInit();
    booking.loginCheck();
    booking.loadSessionTicketSelection();
    
    if (!$('body').hasClass('internal'))
	{
		booking.init();
	}
    
    booking.sidePanelInit();
});

booking = {
    
    sHomepagePanel: '',
    iOriginId: 0,
    iDestinationId: 0,
    sDepartDate: 0,
    sReturnDate: 0,
    iPassengers: 0,
    
    aOrigins: null,
    aDestinations: null,
    aLocations: null,
    aLocationWaypoints: null,
    objMapLocation: null,
    iMaxPassengers: 10,
    bReturn: false,
    bSupressAdd: false,
    
    aTickets: null,
    aTicketSelection: new Array(),
    iTicketSelectionCost: 0,
    aPriceDetail: null,

    aCalOperatingDays: null,
    objCalTarget: null,
    
    iSelectPanel_X : 0,
    iSelectPanel_Y : 0,
    objSelector: null,
    sSelectedPanel: '',
    aSelectedTickets: { },
    
    aLoggedIn: null,
    iCheckoutRedirect: 0,
    
    // Global from config
    iRewardThreshold: 0,
    iBookingFee: 0,
    iSMSFee: 0,
    iSMSPassenger: 0,
    
    iInterval: 0,
    objBookingMap: null,
    
    sGMapsKey: '',
    
    oUserDetails: null,
    
    iCallCentre: 2,
    iRetailByPass: 3,
    
    
    init: function() {
        
        /*
        * Load Reward Scheme and Booking Fee
        **/
        booking.loadGlobals();
        
        // Get gmaps key from config
        booking.getGmapKey();
        
        /*
        * Date Picker for Depart Date and Return
        **/
        $("#depart_date_div").click(function () {
            
            if ($(".calendar_panel").is(":hidden"))
            {
                booking.bReturn = false;
                booking.objCalTarget = $(this);
                booking.initialiseCalendar();
				
				var iLeft = $('#content_container_wrap').offset().left + 371;
                $('.calendar_panel').css({
                    'left': iLeft+'px'
                });	
            }

            $('.calendar_panel').toggle();
        });
        
        /*
        * Return checkbox
        */
        $('#has_return').click(function () {
            booking.hasReturn();
        });
        
        /*
        * Location selection for Depart from and Going to
        **/
        $('#depart_from_name, #going_to_name').click(function () {
            booking.loadLocations($(this),'select_panel');
        });
        
        /*
        * Passengers selection
        **/
        $('#passengers').click(function () {
            booking.displayPassengers();
            booking.showFormPanel($(this),'number_panel');
        });
        
        /*
        * Show tickets button
        **/
        $('#buy_tickets_form button').click(function () {
            booking.showTickets();
        });
        
       // $(window).unload(function () {
      ///  	booking.logout();
      //  });

        
        booking.displaySidePanel();
    },
    
    homepagePanelInit: function() {
        
        if ($('#main_content #content_panel #homepage_panel').length > 0)
        {
            panel.init();
            $(window).unload( function () { 
               clearInterval(panel.panelInterval);
            });
        }
    },
    
    sidePanelInit: function() {
        
        /*
        * Login and Registration panel setup
        **/
        $('#panel_username a:eq(0)').click(function () {
            booking.displayRegistration();
        });
        
        $('#panel_username a:eq(1)').click(function () {
            booking.displayLogin();
        });
        
        booking.displaySidePanelRewards();
    },
    
    checkoutButtonSetup: function()
    {
        /*
        * Checkout panel setup
        **/
        $('#panel_cart .add_journey').click(function () {
            checkout.bNoCheckout = false;
            booking.resetForm();
            $('#main_content #content_panel #homepage_panel').append( ''+booking.sHomepagePanel +'' );
            booking.homepagePanelInit();
        });
        
        $('#panel_cart .checkout').click(function () {
            // general.loadScript('/lib/javascript/checkout.js', booking.checkout);
            booking.checkout();
        });
    },
    
    checkout: function()
    {
        checkout.displaySummary();
    },
    
    loginCheck: function() {
        
        $.ajax({
            type: "POST",
            url: '/registration.php?action=login_check',
            cache: false,
            dataType: "json",
            success: function(data) {
                booking.aLoggedIn = data;
            },
            complete: function() {
                booking.updateLogin();
            }
        });
    },
    
    displayForgotPasswordDialog: function(responseText, statusText) {
        
        var aData = null;
        
        if (responseText)
        {
            aData = eval('(' + responseText + ')');
        }
        else
        {
            $("#forgot_password").dialog('close');
            booking.error('There has been an error retreiving your details');
        }
        
        if (aData.success == 1)
        {
            $("#forgot_password").html('Your password has been send to the registered email address');
        }
        else
        {
            $("#forgot_password").dialog('close');
            booking.error('There has been an error retreiving your details');
        }
    },
    
    displayForgotPassword: function() {

        $("#login_dialog").dialog('destroy');
        $("#forgot_password").dialog('destroy');
        $('#forgot_password').attr('title','Forgot Password');
        $("#forgot_password").dialog({ autoOpen: false, modal: true, bgiframe: true, buttons: {
                "Cancel": function() {
                    $("#forgot_password").dialog('close');
                    return false;
                },
                "Send Password": function() {
                    if ($("#forgot_password .forgot_password_form").validate().form() == true)
                    {
                        $('#forgot_password .forgot_password_form').ajaxSubmit({ success: function(responseText, statusText) { 
                                booking.displayForgotPasswordDialog(responseText, statusText);
                         } , timeout: 10000 });
                        return false;
                    }
                }
            },
            overlay: {
                opacity: 0.6,
                background: '#000000' 
            },
			width: 500, height: 200
        });
        
        $("#forgot_password").dialog('open');
    },
    
    displayLogin: function(iCheckoutRedirect) {
        if (iCheckoutRedirect == 1)
        {
            booking.iCheckoutRedirect = iCheckoutRedirect;
        }
        
        $("#login_dialog").dialog('destroy');
        $('#login_dialog').attr('title','Sign In');
        $("#login_dialog").dialog({ autoOpen: false, modal: true, buttons: {
                "Cancel": function() {
                    $("#login_dialog").dialog('close');
                    return false;
                },
                "Sign In": function() {
                    if ($("#login_dialog .login_form").validate().form() == true)
                    {
                        $('#login_dialog .login_form').ajaxSubmit({ success: function(responseText, statusText) { 
                                booking.updateLogin(responseText, statusText);
                         } , timeout: 10000 });
                        return false;
                    }
                    return false;
                }
            },
            overlay: {
                opacity: 0.6,
                background: '#000000' 
            },
			width: 500, height: 330
        });
        
        $("#login_dialog").dialog('open');
        
        return false;
    },
    
    displayRegistration: function() {
        
        $("#registration_dialog").dialog('destroy');
        $('#registration_dialog').attr('title','Registration');
        $("#registration_dialog").dialog({ autoOpen: false, modal: true, buttons: {
                "Cancel": function() {
                    $("#registration_dialog").dialog('close');
                    return false;
                },
                "Register": function() {
                    if ($("#registration_dialog .registration_form").validate({invalidHandler: function(e, validator) {
										var errors = validator.numberOfInvalids();
										if (errors) {
											$("#reg_error").show();
										} else {
											$("#reg_error").hide();
										}
									}}).form() == true)
                    {
                        if ($('input#terms').is(':checked'))
                        {
                            $('#registration_dialog .registration_form').ajaxSubmit({ success: function(responseText, statusText) { 
                                booking.updateLogin(responseText, statusText);
                            } , timeout: 10000 });
			    $('#reg_error').hide();                            
                            $("#registration_dialog").dialog('close');
                            return false;
                        }
                        else
                        {
                            if ($("label#agree").length <= 0)
                            {
                                $("input#terms").parent().append('<label id="agree">You must agree to the Terms &amp; Conditions to register</label>');
                            }
			    $('#reg_error').show();
                            
                            $('#registration_dialog .registration_form_wrap')[0].scrollTo('#optin');
                        }
                    }
                    else
                    {
                        $('#registration_dialog .registration_form_wrap').jScrollPane({showArrows:true, scrollbarWidth: 16});
                    }
                    return false;
                }
            },
            overlay: {
                opacity: 0.5,
                background: '#000' 
            },
			width: 500, height: 360
        });
        $("#registration_dialog").dialog('open');
        
        if (booking.aLoggedIn && booking.aLoggedIn.email)
        {
            $("#registration_dialog #registration_email").val( booking.aLoggedIn.email );
        }

        //$('#main_content #content_panel #booking_panel #password-strength').remove();
        //$(".password").pstrength();

        $('#registration_dialog .registration_form_wrap').jScrollPane({showArrows:true, scrollbarWidth: 16});
        
        return false;
    },
    loadUserDetails: function(fromCheckOut) {
    	$.ajax({
            url: '/registration.php?action=get_registered_user_details_json',
            async: false,
            cache: false,
            dataType: "json",
            success: function(data) {
    		    booking.oUserDetails = data;
            },
    	    complete: function() {
            	booking.displayEditDetailsForm(fromCheckOut);
            }
        });
    },
    resetFormFromEditToCreate: function() {
    	// revert the stuff we changed
    	$('#password_reg').removeAttr("disabled");
    	$('#confirm_password').removeAttr("disabled");
    	$('#terms').removeAttr("disabled");
    	$('#optin').removeAttr("disabled");
    	$('#password_reg').parent().show();
    	$('#terms').parent().show();
    	$('#confirm_password').parent().show();
    	$('#optin').parent().show();
    	
    	// change back the action of the form
    	$(".registration_form").attr("action", '/registration.php?action=save');
    	
    	// Unset
    	$('#registration_email').val('');
    	$('#title').val('');
    	$('#name').val('');
    	$('#surname').val('');
    	$('#house_no').val('');
    	$('#street').val('');
    	$('#town').val('');
    	$('#postcode').val('');
    	$('#phone').val('');
    	$('#phone_mobile').val('');
    },
    displayEditDetailsForm: function(fromCheckOut) {
    	var data = booking.oUserDetails;
    	$("#registration_dialog").dialog('destroy');
    	$('#registration_email').val(data.email);
    	$('#title').val(data.title);
    	$('#name').val(data.name);
    	$('#surname').val(data.surname);
    	$('#house_no').val(data.house_no);
    	$('#street').val(data.street);
    	$('#town').val(data.town);
    	$('#postcode').val(data.postcode);
    	$('#phone').val(data.phone);
    	$('#phone_mobile').val(data.mobile);
    	
    	// disable and hide the password field etc - need to replace them after submit
    	$('#password_reg').attr("disabled", true);
    	$('#confirm_password').attr("disabled", true);
    	$('#terms').attr("disabled", true);
    	$('#optin').attr("disabled", true);
    	
    	$('#password_reg').parent().hide();
    	$('#confirm_password').parent().hide();
    	$('#terms').parent().hide();
    	$('#optin').parent().hide();
    	
    	// change the action of the form - again we will need to change this back
    	$(".registration_form").attr("action", '/registration.php?action=update_registered_user_details'); 
    	
        $('#registration_dialog').attr('title','Edit your Details');
        $("#registration_dialog").dialog({ autoOpen: false, modal: true, bgiframe: true, buttons: {
                "Cancel": function() {
        	        booking.resetFormFromEditToCreate();
                    $("#registration_dialog").dialog('close');
                    return false;
                },
                "Update": function() {
                    if ($("#registration_dialog .registration_form").validate().form() == true)
                    {
                        $('#registration_dialog .registration_form').ajaxSubmit({ success: function(responseText, statusText) { 
                            booking.resetFormFromEditToCreate();
                        	
                        	// Update the name we dispaly in the booking pane (it may have changed)
                        	$('.joined_us a').html('Hello ' + $('#name').val() + ' ' + $('#surname').val());
                        	
                        	if (fromCheckOut) {
                        		//$('#main_content #content_panel #booking_panel').html('');
                        		//checkout.customerDetails();
				    $.ajax( {
					    type : "POST",
					    url : '/registration.php?action=registered_user_details',
					    async : false,
					    cache : false,
					    dataType : "json",
					    data : ( {
						    user_id : booking.aLoggedIn.id
					    }),
					    success : function(data) {
						    checkout.aCustomerDetails = data;
					    },
					    complete : function() {
						    $('#checkout_details').remove();
						    $('#booking').remove();
						    checkout.detailsSummary();
						    checkout.world_pay_form(checkout.aCustomerDetails);
						    checkout.aCustomerDetails = null;
					    }
				    });
					
					
				
				}
                        	
                        } , timeout: 10000 });
                        
                        $("#registration_dialog").dialog('close');
                        return false;
                    }
                }
            },
            overlay: {
                opacity: 0.5,
                background: '#000' 
            },
			width: 500, height: 360
        });
        $("#registration_dialog").dialog('open');
        
       // if (booking.aLoggedIn && booking.aLoggedIn.email)
       // {
       //     $("#registration_dialog #registration_email").val( booking.aLoggedIn.email );
       // }
        
        //$('#main_content #content_panel #booking_panel #password-strength').remove();
        //$(".password").pstrength();

        $('#registration_dialog .registration_form_wrap').jScrollPane({showArrows:true, scrollbarWidth: 16});
    },

    updateLogin: function(responseText, statusText) {
        
        if (responseText)
        {
            booking.aLoggedIn = eval('(' + responseText + ')');
        }
        
        if (booking.aLoggedIn)
        {
            if (booking.aLoggedIn.id)
            {
            	// Call center and rpbu MAY use there own fee
            	if (booking.aLoggedIn.accountType == booking.iCallCentre || booking.aLoggedIn.accountType == booking.iRetailByPass) {
            		if (booking.aLoggedIn.booking_fee.length > 0) {
            			booking.iBookingFee = booking.aLoggedIn.booking_fee;
            			booking.displaySidePanel(); // redraw with correct fees applied
                        
            			// Handle login from checkout page
            			if($('#main_content #content_panel #booking_panel').length > 0) {
            				$('#main_content #content_panel #booking_panel').html('');
            				checkout.ticketSummary();
            				$('#main_content #content_panel #booking_panel').append('<div id="checkout_details"></div>');
            				checkout.handleRetailCustomers(booking.aLoggedIn.accountType); // display the form for retail users
            				var details = {
            				    accountType: booking.aLoggedIn.accountType
            				};
            				details.accountType = booking.aLoggedIn.accountType;
            				checkout.world_pay_form(details); // display the world pay form (the button)
            			}
            		}
            	}
            	
                $("#login_dialog").dialog('close');
                
                $('#panel_username a:eq(0)').unbind("click").click(function () {
                    booking.loadUserDetails();
                });
                $('#panel_username a:eq(0)').attr('title','Click to view your details');
                $('#panel_username a:eq(0)').html('Hello '+booking.aLoggedIn.name);
				$('#panel_username span:eq(0)').removeClass('join_us').addClass('joined_us');
                
                $('#panel_username a:eq(1)').unbind("click").click(function () {
                    booking.logout();
                });
                $('#panel_username a:eq(1)').attr('title','click to sign out');
                $('#panel_username a:eq(1)').html('Sign Out');
				$('#panel_username span:eq(1)').removeClass('sign_in').addClass('sign_out');
                
                booking.clearLoginRegisterForm();
                booking.displaySidePanelRewards();
                
                if (checkout.bViewingSummary) {
		    $.ajax( {
				type : "POST",
				url : '/registration.php?action=registered_user_details',
				async : false,
				cache : false,
				dataType : "json",
				data : ( {
					user_id : booking.aLoggedIn.id
				}),
				success : function(data) {
					checkout.aCustomerDetails = data;
				},
				complete : function() {
					checkout.ticketSummary();
					checkout.detailsSummary();
					checkout.handleRetailCustomers();
					checkout.world_pay_form(checkout.aCustomerDetails);
					checkout.aCustomerDetails = null;
				}
			});
		    
		    
			/*$('#main_content #content_panel #booking_panel').html('');
                	checkout.ticketSummary();
                	checkout.detailsSummary(); */
                }
            }
            else if (booking.aLoggedIn.msg && booking.aLoggedIn.msg == 'error')
            {
                $('#login_dialog p.msg').html(booking.aLoggedIn.content).show();
            }
            else if (booking.aLoggedIn.msg && booking.aLoggedIn.msg == 'registration')
            {
                $("#login_dialog").dialog('close');
                $('#panel_username a:eq(0)').trigger('click');
            }
            else if (booking.aLoggedIn.msg && booking.aLoggedIn.msg == 'logout')
            {
                $('#panel_username a:eq(0)').unbind("click").click(function () {
                    booking.displayRegistration();
                });
                $('#panel_username a:eq(0)').attr('title','click to register');
                $('#panel_username a:eq(0)').html('Join Us');
				$('#panel_username span:eq(0)').removeClass('joined_us').addClass('join_us');
                
                $('#panel_username a:eq(1)').unbind("click").click(function () {
                    booking.displayLogin();
                });
                $('#panel_username a:eq(1)').attr('title','click to sign in');
                $('#panel_username a:eq(1)').html('Sign In');
				$('#panel_username span:eq(1)').removeClass('sign_out').addClass('sign_in');
            }
            
            $("#registration_dialog").dialog('close');
            
            if (booking.iCheckoutRedirect == 1)
            {
                checkout.displaySummary();
                booking.iCheckoutRedirect = 0;
            }
        }
    },
    
    clearLoginRegisterForm: function() {
        
        $(':input','.login_form')
         .not(':button, :submit, :reset, :hidden')
         .val('')
         .removeAttr('checked')
         .removeAttr('selected');
         
        $(':input','.registration_form')
         .not(':button, :submit, :reset, :hidden')
         .val('')
         .removeAttr('checked')
         .removeAttr('selected');
	 
	 $('#optin').val(1);
	 $('#reg_error').hide();
    },
    
    logout: function() {
        
        $.ajax({
            type: "POST",
            url: '/registration.php?action=logout',
            async: false,
            cache: false,
            dataType: "json",
            success: function(data) {
                booking.aLoggedIn = data;
            },
            complete: function() {
                booking.updateLogin();
                booking.loadGlobals();
                booking.resetForm();
                booking.displaySidePanel();
                checkout.iConfirmedSMS = null;
                $('#main_content #content_panel #homepage_panel').append( ''+booking.sHomepagePanel +'' );
            }
        });
    },
  
    resetForm: function() {
        
        $('#depart_from_name p:first').html('Select Location');
        $('#depart_from_name input').html('');
        booking.iOriginId = null;
        
        $('#going_to_name p:first').html('Select Location');
        $('#going_to_name input').html('');
        booking.iDestinationId = null;
        
        $('.calendar_panel').hide();
        
        $('#depart_date p:first').html('--/--/--');
        booking.sDepartDate = null;
       
        $('#has_return').attr('checked','');
        $('#return_date_div').removeClass('enabled').addClass('disabled');
        $('#return_date p:first').html('--/--/--');
        booking.sReturnDate = null;
        
        $('#passengers p:first').html('01');
        
        $('body').removeClass('return').removeClass('single');
        $('#main_content #content_panel').html('<div id="add_journey_panel"></div><div id="homepage_panel"></div>');
    },
    
    initialiseCalendar: function() {
        
        if (!booking.iOriginId || !booking.iDestinationId)
        {
            $('.calendar_panel_content').html('<p class="error_msg">Please choose a departing from and going to location.</p>');
        }
        else
        {
            $('.calendar_panel_content').html('');
            $(".calendar_panel .calendar_panel_content").datepicker('destroy');
            $(".calendar_panel .calendar_panel_content").datepicker({
                dateFormat: 'dd/mm/yy',
                beforeShowDay: booking.displayOperatingDays,
                onSelect: function(dateText, inst) {
                    $('p:first',booking.objCalTarget).html(dateText);
                    $('.calendar_panel').toggle();
                },
                onChangeMonthYear: function(year, month, inst) {
                    
                    var iOrig = (booking.bReturn) ? booking.iDestinationId : booking.iOriginId;
                    var iDest = (booking.bReturn) ? booking.iOriginId : booking.iDestinationId;
                    
                    $.ajax({
                        url: '/ticket_booking.php?action=operating_days',
                        data: ({ origin_id: iOrig, destination_id: iDest, month: month, year: year }),
                        async: false,
                        cache: false,
                        dataType: "json",
                        success: function(data) {
                            booking.aCalOperatingDays = data;
                        }
                    });
                }
            });
			
			$('.calendar_panel_content').append('<div class="available_dates"><p class="available_key">Tickets Available</p></div>');
			
        }
    },
    
    displayOperatingDays: function(date) {
        
        if (booking.aCalOperatingDays && booking.aCalOperatingDays.rows.length > 0)
        {
            var dateStr = date.getFullYear() +'-'+ general.pad(date.getMonth(),2) +'-'+ general.pad(date.getDate(),2);
            
            for ( var i in booking.aCalOperatingDays.rows )
            {
                if (general.pad(booking.aCalOperatingDays.rows[i].title,2) == general.pad(date.getDate(),2))
                {
                    return [true, ''];
                }
            }
        }
        
        return [false, ''];
    },
    
    hasReturn: function () {

        if ($('#has_return').is(':checked'))
        {
            $('#return_date_div').removeClass('disabled').addClass('enabled');
            
            $("#return_date_div").click(function () {
                    
                if ($(".calendar_panel").is(":hidden"))
                {
                    booking.bReturn = true;
                    booking.objCalTarget = $(this);
                    booking.initialiseCalendar();
					var iLeft = $('#content_container_wrap').offset().left + 503;
                    $('.calendar_panel').css({
                        'left': iLeft+'px'
                    });	
                }

                $('.calendar_panel').toggle();
            });
        }
        else
        {
            $('.calendar_panel').hide();
            $('#return_date_div').removeClass('enabled').addClass('disabled');
            $('#return_date p:first').html('--/--/--');
            booking.sReturnDate = null;
	    $("#return_date_div").unbind('click');	    
        }
    },
    
    showFormPanel: function(objTarget,sNumSelect) {
        
        booking.objSelector = objTarget;
		
		if (sNumSelect == 'select_panel')
        {
            booking.iSelectPanel_X = objTarget.offset().left;
            booking.iSelectPanel_Y = objTarget.offset().top;
    
            if (objTarget.attr('id') == 'going_to_name')
            {
                $('.'+ sNumSelect).css({
                    'left': '242px'
                });	
            }
            else if (objTarget.attr('id') == 'depart_from_name')
            {
                $('.'+ sNumSelect).css({
                    'left': '14px'
                });	
            }
            if (booking.sSelectedPanel == objTarget.attr('id'))
            {
                booking.calculateSelectPanel(sNumSelect);
                $('.'+ sNumSelect).toggle();
            }
            else
            {
                $('.'+ sNumSelect).hide();
                booking.calculateSelectPanel(sNumSelect);
                $('.'+ sNumSelect).show();
            }
            
            booking.sSelectedPanel = objTarget.attr('id');
            booking.calculateSelectPanel(sNumSelect);
        }
        else if (sNumSelect == 'number_panel')
        {
            $('.'+ sNumSelect).toggle();
            booking.calculateNumberPanel();
        }
    },
    
    calculateNumberPanel: function() {
        
        $('.number_panel .number_panel_content').jScrollPane({showArrows:true, scrollbarWidth: 11});
    },
    
    calculateSelectPanel: function(sNumSelect) {
        
		// alert($('.'+ sNumSelect + ' .select_panel_content ul').height());
		
		if ( $('.'+ sNumSelect + ' .select_panel_content ul').height() > 140 )
		{
            $('.'+ sNumSelect+' .select_panel_content ul, .'+ sNumSelect+' .select_panel_content ul li').css('width','290px');
            $('.'+ sNumSelect+' .select_panel_content ul li a.location').css('width','202px');

			$('.'+ sNumSelect + ' .select_panel_content').css('height','140px');
			$('.'+ sNumSelect + ' .select_panel_content').jScrollPane({showArrows:true, scrollbarWidth: 11});
		}
		else
		{
            $('.'+ sNumSelect+' .select_panel_content ul, .'+ sNumSelect+' .select_panel_content ul li').css('width','311px');
            $('.'+ sNumSelect+' .select_panel_content ul li a.location').css('width','223px');
            
			$('.'+ sNumSelect + ' .select_panel_content').css('height','auto');
			$('.'+ sNumSelect + ' .select_panel_content').jScrollPaneRemove();
		}
    },
    
    loadLocations: function(objTarget, sTarget) {
        
        var sAction = (objTarget.attr('id') == 'depart_from_name') ? 'daily_departures_origin' : 'daily_departures_destination';
        
        $.ajax({
            url: '/ticket_booking.php?action='+sAction+'&origin='+booking.iOriginId,
            cache: false,
            dataType: "json",
            success: function(data) {
                booking.aLocations = data;
            },
            complete: function() {
                if (objTarget.attr('id') == 'depart_from_name')
                {
                    booking.aOrigin = booking.aLocations;
                    booking.aDestinations = null;
                    booking.iDestinationId = null;
                    $('span:eq(0)', objTarget).html( 'Select Location' );
                    $('span:eq(1)',objTarget).html( '' );
                }
                else
                {
                    booking.aDestinations = booking.aLocations;
                }
                
                booking.displayLocations(objTarget,sTarget);
                
                if (sAction == 'daily_departures_destination' && !booking.iOriginId)
                {
                    $('.select_panel .select_panel_content').html('<p class="error_msg">Please choose a departing location.</p>');
                }
                
                booking.showFormPanel(objTarget,'select_panel');
            }
        });
    },
    
    displayLocations: function(objTarget,sTarget) {
        
        if (booking.aLocations.rows)
        {
            var sLinkClass = (objTarget.attr('id') == 'depart_from_name') ? 'pickup_options' : 'dropoff_options';
            var sLinkText = (objTarget.attr('id') == 'depart_from_name') ? 'Pick-up Options' : 'Drop-off Options';
            
			var sHTML = '<ul>';
            for ( var i in booking.aLocations.rows )
            {
                sHTML += '<li><p class="'+sLinkClass+'"><a href="javascript: void(0);" onclick="booking.loadMap('+ booking.aLocations.rows[i].id +');"></a></p><a class="location" href="javascript: void(0);"><span>'+ booking.aLocations.rows[i].title +'</span><span class="hidden">'+ booking.aLocations.rows[i].id +'</span><p>'+ booking.aLocations.rows[i].street +', '+ booking.aLocations.rows[i].postcode +'</p></a></li>';
            }
			$('.'+ sTarget + ' .select_panel_content').html(sHTML+'</ul>');
            

            $('.select_panel li a').click(function () {
                if (!booking.bSupressAdd)
                {
                    $('input',booking.objSelector).val( $('span:eq(1)', this).html() );
                    
                    booking.iOriginId = $('#depart_from_id').val();
                    booking.iDestinationId = $('#going_to_id').val();
                    
                    $('p:first', booking.objSelector).html( $('span:eq(0)', this).html() );
                    $('input', booking.objSelector).val( $('span:eq(1)', this).html() );
                    $(booking.objSelector).siblings('.location_info').html('<a href="javascript: void(0);" onclick="booking.loadMap('+ $('span:eq(1)', this).html() +');">'+ sLinkText +'</a>');
                    $('.select_panel').hide();
                }
                booking.bSupressAdd = false;
            });
        }
    },
    
    displayPassengers: function() {
        
		var sHTML = '<ul>';
        for ( var i=1;i<=41;i++ )
        {
            var iNum = general.pad(i,2);
            sHTML += '<li><a href="javascript: void(0);">'+ iNum +'</a></li>';
        }
        
		$('.number_panel .number_panel_content').html(sHTML+'</ul>');
		
        $('.number_panel .number_panel_content a').click(function () {
	    $('#passengers p:first').html( $(this).html() );
	    $('.number_panel').hide();
        }); 
    },
    
    showTickets: function() {
        
        checkout.bNoCheckout = false;
        
        booking.iOriginId = $('#depart_from_id').val();
        booking.iDestinationId = $('#going_to_id').val();
        booking.sDepartDate = $('#depart_date p:first').html();
        booking.sReturnDate = $('#return_date p:first').html();	
        if (!booking.iOriginId || !booking.iDestinationId || !booking.sDepartDate || booking.sDepartDate == '--/--/--')
        {
            booking.error('You must select a departing location, a going to location and a departure date to view available tickets');
        }
	else if ($('#has_return').is(':checked') && (booking.sReturnDate == 0 || booking.sReturnDate == null || booking.sReturnDate == '--/--/--'))
	{
        var iLeft = $('#content_container_wrap').offset().left + 503;
        $('.calendar_panel').css({
            'left': iLeft+'px'
        });	
		$('.calendar_panel').toggle();
		$('.calendar_panel_content').html('<p class="error_msg">You must select a return date to view available tickets.</p>');
	    //booking.error('You must select a return date to view available tickets');
	}
        else
        {
            clearInterval(panel.panelInterval);
            if ($('#return_date p:first').html() != '--/--/--')
            {
                booking.sReturnDate = $('#return_date p:first').html();
            }
	    else
	    {
		booking.sReturnDate = null;
	    }
            booking.iPassengers = $('#passengers p:first').html();
            
            if (booking.iOriginId && booking.iDestinationId && booking.sDepartDate && booking.iPassengers)
            {
                if (booking.sReturnDate)
                {
                    booking.layoutReturn();
                }
                else
                {
                    booking.layoutSingle();
                }
                
                booking.loadTickets();
            }
            
            booking.displaySidePanel();
        }
    },
    
    error: function(sMsg) {
        
        $("#error").dialog('destroy');
        $('#error').attr('title','Error');
        $('#error').html('<p class="error">'+ sMsg +'</p>');
        $("#error").dialog({ autoOpen: false, modal: true, bgiframe: true, buttons: {
                "Close": function() {
                    $("#error").dialog('close');
                    return false;
                }
            },
			overlay: {
                opacity: 0.5,
                background: '#000000' 
            },
            width: 370, height: 170
        });
        
        $("#error").dialog('open');
    },
    
    loadTickets: function() {

        $.ajax({
            type: "POST",
            url: '/ticket_booking.php?action=show_tickets',
            cache: false,
            dataType: "json",
            data: ({ origin_id : booking.iOriginId, destination_id : booking.iDestinationId, depart_date : booking.sDepartDate, return_date : booking.sReturnDate, passengers : booking.iPassengers }),
            success: function(data) {
                booking.aTickets = data;
            },
            complete: function() {
                booking.displayOutward();
                booking.displayReturn();
                booking.loadSelectedTicketToggle();
            }
        });
    },
    
    dateChange: function(sDate,sTarget,sDir) {
        
        var aMatch = sDate.match(/^(\d+)\/(\d+)\/(\d+)$/);
        var myDate=new Date();
        myDate.setFullYear(aMatch[3],aMatch[2]-1,aMatch[1]);
        
        if (sDir == 1)
        {
            myDate.setDate(myDate.getDate() + 1);
        }
        else
        {
            myDate.setDate(myDate.getDate() - 1);
        }
        
        var sYear = ($.browser.msie) ? myDate.getYear() : (myDate.getYear()+1900);
        var newDate = general.pad(myDate.getDate(),2) +'/'+ general.pad(myDate.getMonth()+1,2) +'/'+ sYear;

        if (sTarget == 'outward')
        {
            $('#outward .journey_date .date:first').html(newDate);
            $('#depart_date p:first').html(newDate);
        }
        else if (sTarget == 'return')
        {
            $('#return .journey_date .date:first').html(newDate);
            $('#return_date p:first').html(newDate);
        }
        
        booking.showTickets();
    },
    
    loadWaypoint: function(objTarget,sRow,iX,iY,isOrigin) {
        
        $.ajax({
            type: "POST",
            url: '/ticket_booking.php?action=daily_departure_waypoints',
            cache: false,
            dataType: "json",
            data: ({ departure_id : sRow, is_origin : isOrigin }),
            success: function(data) {
                booking.aLocationWaypoints = data;
            },
            complete: function() {
                booking.displayWaypoint(objTarget,iX,iY,isOrigin);
            }
        });
    },    
    
    displayWaypoint: function(objTarget,iX,iY,isOrigin) {
        
        if (booking.aLocationWaypoints.rows.length > 0)
        {
            var sHeading = (isOrigin) ? 'Departs' : 'Arrives';
            var sHTML = '<div class="tooltip_content"><h3>'+sHeading+'</h3><p><a href="javascript: void(0);" onclick="$(\'.tooltip\').hide();">Close</a></p><ul class="time">';
            for ( var i in booking.aLocationWaypoints.rows )
            {
                sHTML += '<li><span class="time_info">'+ booking.aLocationWaypoints.rows[i].time +'</span><span class="location_info">'+ booking.aLocationWaypoints.rows[i].title +'</span></li>';
            }
            sHTML += '</ul></div>';
            
            iX = iX - $('#main_content').offset().left;
            iY = iY - $('#main_content').offset().top - 50;
            
            $('.tooltip').css({ 'top': iY+'px', 'left': iX+'px'}).html(sHTML).show();
        }
        booking.bSupressAdd = false;
    },
    
    loadPriceDetail: function(objTarget,sRow,iX,iY) {
        
        $.ajax({
            type: "POST",
            url: '/ticket_booking.php?action=daily_departure_prices',
            cache: false,
            dataType: "json",
            data: ({ departure_id : sRow, passengers : booking.iPassengers }),
            success: function(data) {
                booking.aPriceDetail = data;
            },
            complete: function() {
                booking.displayPriceDetail(objTarget,iX,iY);
            }
        });
    },   
    
    displayPriceDetail: function(objTarget,iX,iY) {
        
        if (booking.aPriceDetail.rows.length > 0)
        {
            var sHTML = '<div class="tooltip_content"><h3>Fare Prices</h3><p><a href="javascript: void(0);" onclick="$(\'.fares_tooltip\').hide();">Close</a></p><ul class="price">';
            for ( var i in booking.aPriceDetail.rows )
            {
                sHTML += '<li><span class="left">'+ booking.aPriceDetail.rows[i].count +' x </span><span class="right">&pound;'+ general.formatNumber(booking.aPriceDetail.rows[i].price,2) +'</span></li>';
            }
            sHTML += '</ul></div>';
            
            iX = iX - $('#main_content').offset().left;
            iY = iY - $('#main_content').offset().top - 50;
            
            $('.fares_tooltip').css({ 'top': iY+'px', 'left': iX+'px'}).html(sHTML).show();
        }
        booking.bSupressAdd = false;
    },
    
    displayOutward: function() {
        
       /* var sHTML   =   '<h2>Outward Journey</h2><p class="journey_date"><span class="previous"><a href="javascript: void(0);">Previous Day</a></span> <span class="date">'+ booking.sDepartDate +'</span> <span class="next"><a href="javascript: void(0);">Next Day</a></span></p>'+
                        '<h3>'+ booking.iPassengers +' x '+ $('#depart_from_name p:first').html() +' to '+ $('#going_to_name p:first').html() +'</h3>'+
                        '<p class="journey_available_key">Availability: <span class="good">Good</span> <span class="limited">Limited</span> <span class="selected">Selected</span></p>'+
                        '<p class="price_guarantee">*Price not guaranteed until checkout is complete.</p>'+
                        '<div class="journey_table scroll-pane">'; */

        var sHTML   =   '<h2>Outward Journey</h2><p class="journey_date"><span class="previous"><a href="javascript: void(0);">Previous Day</a></span> <span class="date">'+ booking.sDepartDate +'</span> <span class="next"><a href="javascript: void(0);">Next Day</a></span></p>'+
                        '<h3>'+ booking.iPassengers +' x '+ $('#depart_from_name p:first').html() +' to '+ $('#going_to_name p:first').html() +'</h3>'+
                        '<p class="journey_available_key">Availability: <span class="good">Good</span> <span class="limited">Limited</span> <span class="selected">Selected</span></p>'+
                        '<div class="journey_table scroll-pane">';
        
        if (booking.aTickets.Outward && booking.aTickets.Outward.length > 0)
        {
            sHTML   +=  '<table class="journey" width="100%" border="0" cellspacing="0" cellpadding="0">'+
                        '<tr>'+
                        '<th class="availability_head">Availability</th>'+
                        '<th class="departs_head">Departs</th>'+
                        '<th class="arrives_head">Arrives</th>'+
                        '<th class="fare_head">Fare*</th>'+
                        '<th class="choose_head">Choose</th>'+
                        '</tr>';

            for ( var i in booking.aTickets.Outward )
            {
                sHTML   +=  '<tr id="row_'+ booking.aTickets.Outward[i].id +'" class="clickable '+ booking.aTickets.Outward[i].availiblity +'" onclick="booking.addTickets(\''+ booking.aTickets.Outward[i].id +'\');">'+
                            '<td class="'+ booking.aTickets.Outward[i].availiblity +'">'+ booking.aTickets.Outward[i].availiblity +'</td>'+
                            '<td>'+ booking.aTickets.Outward[i].departure_time +'<a class="waypoint origin" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Times" /></a></td>'+
                            '<td>'+ booking.aTickets.Outward[i].arrival_time +'<a class="waypoint" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Times" /></a></td>'+
                            '<td>&pound;'+ general.formatNumber(booking.aTickets.Outward[i].standard_departure_price,2) +'<a class="prices" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Fares" /></a></td>'+
                            '<td class="add_to_cart"><a href="javascript: void(0);">Add to cart</a></td>'+
                            '</tr>';
            }
            
            sHTML += '</table>';
        }
        else
        {
            sHTML +=  '<tr><td colspan="5"><p class="not_available">Sorry, there are no available journeys on this date.</p></td></tr>';
        }
        
        sHTML += '</div>';
        
        $('#outward').html(sHTML);
        
        $('#outward .journey_table').jScrollPane({showArrows:true, scrollbarWidth: 16});
        $('#outward .journey_table tr.clickable a').bigTarget({clickZone:'tr:eq(0)'});

        $('#outward .journey_date .previous a:first').click(function(){
            booking.dateChange($('#outward .journey_date .date').html(),'outward',0);
        });
        $('#outward .journey_date .next a:first').click(function(){
            booking.dateChange($('#outward .journey_date .date').html(),'outward',1);
        });
        $('#outward a.waypoint').click(function(e){
            booking.bSupressAdd = true;
            $(".tooltip").hide();
			$(".fares_tooltip").hide();
            if ($(".tooltip").is(":hidden"))
            {
                var isOrigin = ($(this).hasClass('origin')) ? 1 : 0;
                booking.loadWaypoint($(this),$(this).parent().parent().attr('id'),e.pageX,e.pageY,isOrigin);
            }
        });
        $('#outward a.prices').click(function(e){
            booking.bSupressAdd = true;
            $(".tooltip").hide();
			$(".fares_tooltip").hide();
            if ($(".fares_tooltip").is(":hidden"))
            {
                booking.loadPriceDetail($(this),$(this).parent().parent().attr('id'),e.pageX,e.pageY);
            }
        });
    },
    
    displayReturn: function() {
        
        var sHTML   =   '<h2>Return Journey</h2><p class="journey_date"><span class="previous"><a href="javascript: void(0);">Previous Day</a></span> <span class="date">'+ booking.sReturnDate +'</span> <span class="next"><a href="javascript: void(0);">Next Day</a></span></p>'+
                        '<h3>'+ booking.iPassengers +' x '+ $('#going_to_name p:first').html() + ' to ' + $('#depart_from_name p:first').html() +'</h3>'+
                        '<p class="journey_available_key">Availability: <span class="good">Good</span> <span class="limited">Limited</span> <span class="selected">Selected</span></p>'+
                        '<div class="journey_table scroll-pane">';
        
        if (booking.aTickets.Return && booking.aTickets.Return.length > 0)
        {
            sHTML   +=  '<table class="journey" width="100%" border="0" cellspacing="0" cellpadding="0">'+
                        '<tr>'+
                        '<th class="availability_head">Availability</th>'+
                        '<th class="departs_head">Departs</th>'+
                        '<th class="arrives_head">Arrives</th>'+
                        '<th class="fare_head">Fare*</th>'+
                        '<th class="choose_head">Choose</th>'+
                        '</tr>';

            for ( var i in booking.aTickets.Return )
            {
                sHTML   +=  '<tr id="row_'+ booking.aTickets.Return[i].id +'" class="clickable '+ booking.aTickets.Return[i].availiblity +'" onclick="booking.addTickets(\''+ booking.aTickets.Return[i].id +'\');">'+
                            '<td class="'+ booking.aTickets.Return[i].availiblity +'">'+ booking.aTickets.Return[i].availiblity +'</td>'+
                            '<td>'+ booking.aTickets.Return[i].departure_time +'<a class="waypoint origin" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Times" /></a></td>'+
                            '<td>'+ booking.aTickets.Return[i].arrival_time +'<a class="waypoint" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Times" /></a></td>'+
                            '<td>&pound;'+ general.formatNumber(booking.aTickets.Return[i].standard_departure_price,2) +'<a class="prices" href="javascript: void(0);"><img src="/assets/images/layout/buy_tickets/information.gif" align="middle" alt="Show Fares" /></a></td>'+
                            '<td class="add_to_cart"><a href="javascript: void(0);">Add to cart</a></td>'+
                            '</tr>';
            }
            
            sHTML += '</table>';
        }
        else
        {
            sHTML += '<tr><td colspan="5"><p class="not_available">Sorry, there are no available journeys on this date.</p></td></tr>';
        }
        
        sHTML += '</div>';
        
        $('#return').html(sHTML);
        
        $('#return .journey_table').jScrollPane({showArrows:true, scrollbarWidth: 16});
        $('#return .journey_table tr.clickable a').bigTarget({clickZone:'tr:eq(0)'});
        
        $('#return .journey_date .previous a:first').click(function(){
            booking.dateChange($('#return .journey_date .date').html(),'return',0);
        });
        $('#return .journey_date .next a:first').click(function(){
            booking.dateChange($('#return .journey_date .date').html(),'return',1);
        });
        $('#return a.waypoint').click(function(e){
            booking.bSupressAdd = true;
            $(".tooltip").hide();
			$(".fares_tooltip").hide();
            if ($(".tooltip").is(":hidden"))
            {
            	var isOrigin = ($(this).hasClass('origin')) ? 1 : 0;
                booking.loadWaypoint($(this),$(this).parent().parent().attr('id'),e.pageX,e.pageY, isOrigin);
            }
        });
		$('#return a.prices').click(function(e){
            booking.bSupressAdd = true;
            $(".tooltip").hide();
			$(".fares_tooltip").hide();
            if ($(".fares_tooltip").is(":hidden"))
            {
                booking.loadPriceDetail($(this),$(this).parent().parent().attr('id'),e.pageX,e.pageY);
            }
        });
    },
    
    layoutSingle: function() {
        
        $('body').removeClass('return').addClass('single');
        $('#main_content #content_panel').html('<div id="outward"><p class="loading_image">Loading...</p></div>');
    },
    
    layoutReturn: function() {
        
        $('body').removeClass('single').addClass('return');
        $('#main_content #content_panel').html('<div id="outward"><p class="loading_image">Loading...</p></div><div id="return"><p class="loading_image">Loading...</p></div>');
    },
    
    displaySidePanel: function() {

        if (booking.aTicketSelection.length > 0)
        {
            var sHTML = '';
            booking.iTicketSelectionCost = 0;

            for ( var i in booking.aTicketSelection )
            {
                sHTML += '<div class="ticket_summary_top_noscroll"><div class="ticket_summary_noscroll"><p>'+ booking.aTicketSelection[i].passengers +' x '+ booking.aTicketSelection[i].origin_name +' to '+ booking.aTicketSelection[i].destination_name +'</p><p class="date_price"><span class="date_time">'+ booking.aTicketSelection[i].departure_date +', '+ booking.aTicketSelection[i].departure_time +'</span><span class="price">&pound;'+ general.formatNumber(booking.aTicketSelection[i].standard_departure_price,2) +'</span></p><p class="remove"><a href="javascript: void(0);" onclick="booking.removeTickets('+ booking.aTicketSelection[i].id +')">Remove</a></p></div></div>';
                booking.iTicketSelectionCost += (booking.aTicketSelection[i].standard_departure_price - 0);
            }
            
            $('#panel_cart .cart_items').html(sHTML);
			
			sHTML = '<p class="fee"><span id="booking_fee">Booking Fee:</span><span id="total_fee">&pound;'+ general.formatNumber(booking.iBookingFee,2) +'</span></p>';
            booking.iTicketSelectionCost += (booking.iBookingFee - 0);
            
            sHTML += '<p class="cost"><span id="total_cost">Total Cost*:</span><span id="total_price">&pound;'+ general.formatNumber(booking.iTicketSelectionCost,2) +'</span></p>';
            sHTML += '<button type="button" class="add_journey">Add Another Journey</button>';
            sHTML += '<button type="button" class="checkout">Checkout</button>';
            $('#panel_cart .cart_actions').html(sHTML);
            
            booking.calculateSidePanel();
            booking.checkoutButtonSetup();
        }
        else
        {
            $('#panel_cart .cart_items').html('<p>You have 0 journey(s) in cart</p>');
            $('#panel_cart .cart_actions').html('Are you a frequent traveller or commuter? Buy all your tickets at once for better pricing &amp; easier checkout.');
        }
        
        booking.displaySidePanelRewards();
    },
    
    displaySidePanelSummary: function() {
        
        if (booking.aTicketSelection.length > 0)
        {
            $('#panel_cart .cart_items').html('<p>You have '+ booking.aTicketSelection.length +' journey(s) in cart</p>');
            
            /*booking.iTicketSelectionCost = 0;
            for ( var i in booking.aTicketSelection )
            {
                booking.iTicketSelectionCost += (booking.aTicketSelection[i].standard_departure_price - 0);
            }
            booking.iTicketSelectionCost += (booking.iBookingFee - 0);*/
            
            var cost = 0;
            for ( var i in booking.aTicketSelection )
            {
                cost += (booking.aTicketSelection[i].standard_departure_price - 0);
            }
            cost += (booking.iBookingFee - 0);
            
            sHTML = '<p class="cost"><span id="total_cost">Total Cost*:</span><span id="total_price">&pound;'+ general.formatNumber(cost,2) +'</span></p>';
            sHTML += '<button type="button" class="add_journey">Add Another Journey</button>';
            if (!checkout.bNoCheckout)
            {
                sHTML += '<button type="button" class="checkout">Checkout</button>';
            }
            $('#panel_cart .cart_actions').html(sHTML);
            $('#panel_cart .cart_actions .add_journey').click(function(){
                window.location = '/';
            });
            
            $('#panel_cart .cart_actions .checkout').click(function(){
                
                $.ajax({
                    url: '/ticket_booking.php?action=set_checkout',
                    async: false,
                    cache: false,
                    dataType: "json",
                    success: function(data) {
                        window.location = '/';
                    }
                });
            });
            
            $('#panel_cart .cart_items').removeClass('scroll-pane');
            $('#panel_cart .cart_items').jScrollPaneRemove();
            $('#panel_cart .cart_items').css('height','auto');
        }
        else
        {
            $('#panel_cart .cart_items').html('<p>You have 0 journey(s) in cart</p>');
            $('#panel_cart .cart_actions').html('Are you a frequent traveller or commuter? Buy all your tickets at once for better pricing &amp; easier checkout.');
        }
    },

    displaySidePanelRewards: function() {
        if ( (booking.aLoggedIn && booking.aLoggedIn.id) )
        {
            var iFreeTickets = 0;
            var iRewardCount = 0;
            
            if (booking.aLoggedIn && booking.aLoggedIn.reward_count)
            {
            	iRewardCount = booking.aLoggedIn.reward_count;
            }
            
            if (iRewardCount > 0) {
            	iFreeTickets = Math.floor(iRewardCount/booking.iRewardThreshold);
            }

	    if (iFreeTickets == Infinity)
	    {
		if(booking.iRewardThreshold == Infinity || iRewardCount == Infinity)
		{
		    $('#panel_rewards p:first').html('You are only 8 tickets(s) away from earning a free ticket!');
		}
		else
		{
		    $('#panel_rewards p:first').html('You are only '+ (booking.iRewardThreshold - iRewardCount) +' tickets(s) away from earning a free ticket!');
		}
	    }
            else if (iFreeTickets > 0)
            {
            	if (iFreeTickets == 1) {
            		$('#panel_rewards p:first').html('You are entitled to a free ticket!');
            	}
            	else {
            		$('#panel_rewards p:first').html('You are entitled to '+iFreeTickets+' free tickets!');
            	}
            }
            else
            {
                $('#panel_rewards p:first').html('You are only '+ (booking.iRewardThreshold - iRewardCount) +' tickets(s) away from earning a free ticket!');
            }
        }
        else
        {
            $('#panel_rewards p:first').html('<a href="javascript: void(0);">Join Us</a> to earn rewards for your trips. Joining is free and easy.');
            $('#panel_rewards p:first a:eq(0)').click(function () {
                booking.displayRegistration();
            });
        }
    },    
    
    calculateSidePanel: function() {
        
		if ( booking.aTicketSelection.length > 2 )
		{
            $('#panel_cart .cart_items .ticket_summary_top_noscroll').removeClass('ticket_summary_top_noscroll').addClass('ticket_summary_top_scroll');
            $('#panel_cart .cart_items .ticket_summary_noscroll').removeClass('ticket_summary_noscroll').addClass('ticket_summary_scroll');
            
            $('#panel_cart .cart_items').addClass('scroll-pane');
            $('#panel_cart .cart_items').css('height','116px');
            $('#panel_cart .cart_items').jScrollPane({showArrows:true, scrollbarWidth: 11});
		}
		else
		{
            $('#panel_cart .cart_items .ticket_summary_top_noscroll').removeClass('ticket_summary_top_scroll').addClass('ticket_summary_top_noscroll');
            $('#panel_cart .cart_items .ticket_summary_noscroll').removeClass('ticket_summary_scroll').addClass('ticket_summary_noscroll');
            
            $('#panel_cart .cart_items').removeClass('scroll-pane');
            $('#panel_cart .cart_items').jScrollPaneRemove();
            $('#panel_cart .cart_items').css('height','auto');
		}
        
        // $('.equal_height').attr('style','');
        // $('.equal_height').equalHeights();
    },
    
    addTickets: function(id) {
        
        // if (!booking.isAdded(id) || 1) // allow duplicates
        if (!booking.bSupressAdd && !booking.isAdded(id))
        {
            booking.selectedTicketToggle(id);
            
            $.ajax({
                type: "POST",
                url: '/ticket_booking.php?action=add_tickets',
                cache: false,
                dataType: "json",
                data: ({ departure_id : id, passengers : booking.iPassengers }),
                success: function(data) {
                    booking.aTicketSelection.push(data);
                },
                complete: function() {
                    booking.displaySidePanel();
                }
            });
        }
    },

    removeTickets: function(id) {
        
        if (booking.aTicketSelection)
        {
            booking.selectedTicketToggle(id);
            
            var aTmp = new Array();
            for ( var i in booking.aTicketSelection )
            {
                if (id != booking.aTicketSelection[i].id)
                {
                    aTmp.push(booking.aTicketSelection[i]);
                }
            }
            
            booking.aTicketSelection = aTmp;
            booking.displaySidePanel();
            booking.saveSessionTicketSelection();
        }
    },
    
    loadSelectedTicketToggle: function() {
        
        if (booking.aTicketSelection)
        {
            for ( var i in booking.aTicketSelection )
            {
                booking.aSelectedTickets['row_'+ booking.aTicketSelection[i].id] = 0;
                booking.selectedTicketToggle(booking.aTicketSelection[i].id);
            }
        }
    },
    
    selectedTicketToggle: function(id) {
        
        if ($('tr#row_'+ id).hasClass('selected'))
        {
            if (booking.aSelectedTickets['row_'+ id] && booking.aSelectedTickets['row_'+ id] != 0)
            {
                $('tr#row_'+ id).removeClass().addClass(booking.aSelectedTickets['row_'+ id]);
                $('tr#row_'+ id +' td:first').removeClass().addClass(booking.aSelectedTickets['row_'+ id]);
                booking.aSelectedTickets['row_'+ id] = 0;
            }
        }
        else
        {
            booking.aSelectedTickets['row_'+ id] = $('tr#row_'+ id).attr('class');
            $('tr#row_'+ id).removeClass().addClass('selected');
            $('tr#row_'+ id +' td:first').removeClass().addClass('selected');
        }
    },
    
    isAdded: function(id) {
        
        if (booking.aTicketSelection)
        {
            for ( var i in booking.aTicketSelection )
            {
                if (id == booking.aTicketSelection[i].id)
                {
                    return true;
                }
            }
        }
        
        return false;
    },
    
    showCheckout: function () {
        
        $.ajax({
            url: '/ticket_booking.php?action=get_checkout',
            cache: false,
            dataType: "json",
            success: function(data) {
                if (data.checkout)
                {
                    booking.checkout();
                }
            }
        });
    },
    
    /*
    * Get the threshold for the reward scheme
    **/
    loadGlobals : function() {
        
        $.ajax({
            url: '/ticket_booking.php?action=globals',
            async: false,
            cache: false,
            dataType: "json",
            success: function(data) {
                booking.iRewardThreshold = data.threshold;
                booking.iBookingFee = data.web_booking_fee;
                booking.iSMSFee = data.web_sms_fee;
                booking.iSMSPassenger = data.sms_passenger;
                
                if (booking.aLoggedIn && (booking.aLoggedIn.accountType == booking.iCallCentre || booking.aLoggedIn.accountType == booking.iRetailByPass)) {
            		if (booking.aLoggedIn.booking_fee.length > 0) {
            			booking.iBookingFee = booking.aLoggedIn.booking_fee;
            		}
            	}
            }
        });
    },
    
    /*
    * Session Ticket Saving and Loading
    **/
    saveSessionTicketSelection: function() {
        
        if (booking.aTicketSelection && booking.aTicketSelection.length > 0) // update the session
        {
            for ( var i in booking.aTicketSelection )
            {
            	var clearSession = (i==0) ? 1 : 0;
            	
                $.ajax({
                    type: "POST",
                    url: '/ticket_booking.php?action=save_tickets',
                    async: false,
                    cache: false,
                    data: ({ departure_id : booking.aTicketSelection[i].id, passengers : booking.aTicketSelection[i].passengers, clearSession : clearSession}),
                    dataType: "json"
                });
            }
            
            booking.displaySidePanel();
        }
        else // empty the session
        {
            $.ajax({
                type: "POST",
                url: '/ticket_booking.php?action=save_tickets',
                async: true,
                cache: false,
                data: ({ clearSession : 2 }), // 2 = kill em all - tickets, promos, sms, the lot
                dataType: "json"
            });
            
            booking.displaySidePanel();
        }
    },
        
    loadSessionTicketSelection: function() {
        
        $.ajax({
            url: '/ticket_booking.php?action=load_tickets',
            cache: false,
            dataType: "json",
            success: function(data) {
                booking.aTicketSelection = data;
                var aTmp = new Array();
                for ( var i in booking.aTicketSelection.rows )
                {
                    aTmp.push( booking.aTicketSelection.rows[i] );
                }
                booking.aTicketSelection = aTmp;
            },
            complete: function() {
                if (booking.aTicketSelection)
                {
                    if ($('body').hasClass('internal'))
                    {
                        booking.displaySidePanelSummary();
                    }
                    else
                    {
                        booking.displaySidePanel();
                    }
                }
                
                booking.showCheckout();
            }
        });
    },
    
    /*
    * Map functions
    **/
    loadMap: function (iLocation) {
        
        booking.bSupressAdd = true;
        
        $.ajax({
            url: '/ticket_booking.php?action=load_map',
            cache: false,
            dataType: "json",
            data: ({ location_id : iLocation }),
            success: function(data) {
                booking.objMapLocation = data;
            },
            complete: function() {
                booking.bSupressAdd = false;
            	booking.initLoader();
            }
        });
    },
    initLoader: function() {
  	    var script = document.createElement("script");
  	    script.src = "http://www.google.com/jsapi?key="+booking.sGMapsKey+"&callback=booking.loadMapsAPI";
  	    script.type = "text/javascript";
  	    document.getElementsByTagName("head")[0].appendChild(script);
    },
    loadMapsAPI: function() {
  	  google.load("maps", "2", {"callback" : booking.displayMap});
    },
    displayMap: function () {
        
        $("#map_dialog").dialog('destroy');
        $('#map_dialog').attr('title','Map for '+ booking.objMapLocation.items[0].name);
        $("#map_dialog").dialog({ autoOpen: false, modal: true, bgiframe: true, buttons: {
                "Close": function() {
        	        GUnload();
                    $("#map_dialog").dialog('close');
                    return false;
                }
            },
			overlay: {
                opacity: 0.5,
                background: '#000000' 
            },
            width: 740, height: 520
        });
        
        $("#map_dialog").dialog('open');
        booking.insitaliseMap();  
    },

    addMapPoint: function (item) {
        
        var point = new GLatLng(item.latitude, item.longitude);
        var objMarker = new GMarker(point);
        var sHTML = '<div class="bubble">'+item.title+'<br>' + item.street + '<br>' + item.town + '<br>' + item.postcode + '</div>';
        GEvent.addListener(objMarker, "click", function() {
            objMarker.openInfoWindowHtml(sHTML);
        });
        booking.objBookingMap.addOverlay(objMarker);
        
        return point;
    },
    
    insitaliseMap: function () {
        
        if (GBrowserIsCompatible())
        {
           booking.objBookingMap = new GMap2(document.getElementById("map_canvas"));
           booking.objBookingMap.addControl(new GSmallMapControl());
           booking.objBookingMap.addControl(new GMapTypeControl());
           booking.objBookingMap.enableContinuousZoom();
           
            //var points = Array();
            
            if (booking.objMapLocation) {
                $.each(booking.objMapLocation.items, function(i, item) {
                    booking.addMapPoint(item); // points.push(booking.addMapPoint(item));
                });
                //var bounds = new GLatLngBounds();
                //for (var i=0; i< points.length; i++) {
                //    bounds.extend(points[i]);
                //}
                //booking.objBookingMap.setZoom(booking.objBookingMap.getBoundsZoomLevel(bounds));
                var zoom = 13;
                if (booking.objMapLocation.items[0].title.indexOf('Southampton') > -1) {
                	zoom = 11;
                }
                booking.objBookingMap.setCenter(new GLatLng(booking.objMapLocation.items[0].latitude, booking.objMapLocation.items[0].longitude), zoom);
            }
            else {
                booking.objBookingMap.setCenter(new GLatLng(55.877190650848, -4.3424322287105), 13);
            }
           /*
            * function fitMap( map, points ) {
                  var bounds = new GLatLngBounds();
                  for (var i=0; i< points.length; i++) {
                      bounds.extend(points[i]);
                  }
                  map.setZoom(map.getBoundsZoomLevel(bounds));
                  map.setCenter(bounds.getCenter());
              }
            */
            //GEvent.addDomListener(document.getElementById("map_canvas"), "DOMMouseScroll", wheelZoom);
            //GEvent.addDomListener(document.getElementById("map_canvas"), "mousewheel", wheelZoom);
        }
    },
    getGmapKey: function(id) {
    	var url= '/ticket_booking.php?action=get_gmap_key_json';
    	
    	$.ajax({
    	    url: url,
    	    cache: false,
    	    dataType: "json",
    	    async: false,
    	    success: function(data){
	    		booking.sGMapsKey = data.key;
    	    },
    	    error: function(XMLHttpRequest, textStatus, errorThrown) {
    	    	alert('ERROR. textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
    	    }
    	});
    	
    }
}