function UpdateAptTypesList() {
    var adults = $("#adults").val();
    var children = $("#children").val();
    var occupants = 0;
    var needToAlert = false;
    $("#apart_type").html("");
    // how many occupants do we have?
    occupants = parseInt(adults) + parseInt(children);
    // If the number is greater than zero, which it will be
    if (occupants > 0) {
        var count = 0;
        $.getJSON('/home/GetApartmentTypes?occupants=' + occupants, function (types) {
            $.each(types, function (i, item) {
                count++;
                // Append the apartment type
                $("#apart_type").append($("<option></option>").attr("value", item.SOLARId).text(item.Type));
            });
            // If there were no apartments then display the message
            if (count == 0) {
                alert("Your selection exceeds the maximum occupancy for this apartment type, however we may still be able to help, just call our reservations team on 0845 122 04 05.")
                $("#adults").val('2')
                $("#children").val('0')
                // Repopulate the list
                UpdateAptTypesList();
            }
        });
    }
}

function UpdateAptTypesListBookingPage() {
    var adults = $("#adults_book").val();
    var children = $("#children_book").val();
    var locId = $("input[name=locationId]").val()
    var occupants = 0;
    var needToAlert = false;
    $("#apt_book_type_book").html("");
    // how many occupants do we have?
    occupants = parseInt(adults) + parseInt(children);
    // If the number is greater than zero, which it will be
    if (occupants > 0) {
        var count = 0;
        $.getJSON('/home/GetApartmentTypesForLocationAjax?occupants=' + occupants + '&locationId=' + locId, function (types) {
            $.each(types, function (i, item) {
                count++;
                // Append the apartment type
                $("#apt_book_type_book").append($("<option></option>").attr("value", item.SOLARId).text(item.Type));
            });
            // If there were no apartments then display the message
            if (count == 0) {
                alert("Your selection exceeds the maximum occupancy for this apartment type, however we may still be able to help, just call our reservations team on 0845 122 04 05.")
                $("#adults_book").val('2')
                $("#children_book").val('0')
                // Hide children box
                $('.child_ages').addClass('child_ages_hide');
                // Repopulate the list
                UpdateAptTypesListBookingPage();
            }
        });
    }
}

// Deals with populating the guest text boxes
function fillGuestDetails(guestCheck)
{
    // Get the index
    var index = guestCheck.value.substring(guestCheck.value.length - 1, guestCheck.value.length);
    if ($(guestCheck).is(":checked")) {
        // Now populate the relevant controls using jquery
        $("#title_apt_" + index).val($("#hdnTitle").val());
        $("#first_name_apt_" + index).val($("#hdnFirst").val());
        $("#last_name_apt_" + index).val($("#hdnLast").val());
        $("#company_apt_" + index).val($("#hdnCompany").val());
        $("#mobile_apt_" + index).val($("#hdnMobile").val());
        $("#email_apt_" + index).val($("#hdnEmail").val());
    }
    else {
        $("#title_apt_" + index).val('');
        $("#first_name_apt_" + index).val('');
        $("#last_name_apt_" + index).val('');
        $("#company_apt_" + index).val('');
        $("#mobile_apt_" + index).val('');
        $("#email_apt_" + index).val('');
    }
    
};

// Removed outside of jQuery document/ready as it wasn't working in firefox
function load_counter(idx, slide) {
    return '<li><a href="#">' + (idx + 1) + '</a></li>';
};

function pagerFactory(idx, slide) {
    // var s = idx > 2 ? ' style="display:none"' : '';
    return '<li><a class="pic_nav" href="#">' + (idx + 1) + '</a></li>';
};

function TimeoutRedirect() {
    location.href = '/errors/timeout';
}

function ManageExtras(checkbox) {
    var url = '/Booking/ManageExtra';
    var method = '';

    // remove or add it, post to our url
    if ($(checkbox).is(":checked"))
        method = 'addExtra';
    else
        method = 'removeExtra';
    
    // easy to send thes values using json
    var postData = { values: $(checkbox).val(), method:method };
    // AJAX Post
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: postData,
        traditional: true,
        success: function (data) {
            // Now update the labels
            $('#extrasCost').html(data.totalExtra);
            $('#bookingCost').html(data.totalBooking);
        }
    })
};


// Defaults
var _globalNights = 1;
var _globalAdults = 1;
var _globalChildren = 0;
var _globalApartType = 0;

jQuery(document).ready(function ($) {

    $("#payment_method").change(function (e) {
        // Ajax post back to update the CC price
        // get the code
        var code = $(this).val();
        // set it to 0 so it can just be parsed as such
        if (code == '')
            code = 'DELTA';

        var url = "";

        // online or offline?
        if ($("#hdnBookingType").val() == "offline") {
            url = "CalculateCreditCardChargeOffline";
        }
        else {
            url = "CalculateCreditCardCharge";
        }

        var postData = { code: code };
        $.ajax({
            url: '/booking/' + url,
            type: "POST",
            dataType: "json",
            data: postData,
            traditional: true,
            success: function (data) {
                if (data.ccCharge == 0) {// Now update the labels
                    $('#ccChargeLabel').html('N/A');
                }
                else {
                    $('#ccChargeLabel').html(data.symbol + data.ccCharge);
                }
                // and the total
                $('#grandTotal').html(data.grandTotal);
            }
        });
    });

    // Offline booking page
    $("#offline_billing").click(function () {
        if ($("#offline_billing").is(":checked")) {
            $("#bill_add_1").val($("#booker_add_1").html());
            $("#bill_add_2").val($("#booker_add_2").html());
            $("#bill_town").val($("#booker_town").html());
            $("#bill_postcode").val($("#booker_postcode").html());
            $("#bill_country").val($("#booker_country").html());
        }
        else {
            $("#bill_add_1").val("");
            $("#bill_add_2").val("");
            $("#bill_town").val("");
            $("#bill_postcode").val("");
            $("#bill_country").val("");
        }
    });


    // For the payment page
    $("#billing").click(function () {
        if ($("#billing").is(":checked")) {
            var count = 1;
            while (count < 5) {
                $("#address_" + count).val($("#hdn" + count).val())
                count++;
            };
        }
        else {
            var count = 1;
            while (count < 5) {
                $("#address_" + count).val('')
                count++;
            };
        }
    });

    $('#booking_3 input:checkbox').click(function () {
        ManageExtras(this);
    });

    $("#staying_yourself").click(function () {
        // Show or don't show the guests details as the person logged in
        // If checked
        if ($("#staying_yourself").is(":checked")) {
            // set the text boxes
            $("#first_name").val($("#fname").val());
            $("#last_name").val($("#lname").val());
            $("#phone").val($("#telephone").val());
            $("#mobile").val($("#hdnmobile").val());
            $("#email").val($("#hdnemail").val());
            $("#title").val($("#hdntitle").val());
        }
        else {
            $("#title").val('Mr');
            $("#first_name").val('');
            $("#last_name").val('');
            $("#phone").val('');
            $("#mobile").val('');
            $("#email").val('');
        }
    });

    // navigation checker
    var currentLoc = location.pathname;
    var link = '';
    if (currentLoc == '/') {
        // set the home link
        link = 'homeLink';
    }
    if (currentLoc.indexOf("account") != -1) {
        link = 'loginLink';
    }
    if (currentLoc.indexOf("destinations") != -1) {
        link = 'destLink';
    }
    if (currentLoc.indexOf("special_offers") != -1) {
        link = 'offersLink';
    }
    if (currentLoc.indexOf("contact") != -1) {
        link = 'contactLink';
    }
    if (currentLoc.indexOf("why") != -1) {
        link = 'whysacoLink';
    }
    if (currentLoc.indexOf("my_saco") != -1) {
        link = 'mysacoLink';
    }


    if (link != '') {// Set the underline so we know where we are
        $("#" + link).css('text-decoration', 'underline');
    }

    // Nice for showing the corporate company box
    $("#usertype").change(function () {
        var corpOrLeisure = $('#usertype option:selected').val();
        if (corpOrLeisure == "corporate") {
            // Show row, which has validation
            $('#companyRow').show('slow');
        }
        else {
            // hide div
            $('#companyRow').hide('slow');
        }
    });


    // Draws the relevant number of option boxes for the children
    $("#children_book").change(function () {
        var children = $('#children_book option:selected').val();
        // Counter for ID's
        if (children != 0) {
            // hide them all again if user wants to change number
            $('.child_counter').hide();
            // show the actual row containing all the items
            $('.child_ages_hide').removeClass('child_ages_hide');
            var i = 1;
            // and render the dynamic number of children
            while (i <= children) {
                $("#divchild" + i).show();
                // Increment counter
                i++;
            }
        } else {
            // hide if user decides to remove kids
            $('.child_ages').addClass('child_ages_hide');
        }
    });

    // Used for setting quick search option indexes
    $('#number_nights').val(_globalNights);
    $('#adults').val(_globalAdults);
    $('#children').val(_globalChildren);
    $('#apart_type').val(_globalApartType);
    // main apartment page
    $('#number_nights_book').val(_globalNights);
    $('#adults_book').val(_globalAdults);
    $('#children_book').val(_globalChildren);
    // $('#apt_book_type_book').index(_globalApartType);
    $('#apt_book_type_book option:eq(' + _globalApartType + ')').attr('selected', 'selected');

    // Can't set the apartment as what they search for
    // may not be available as part of the actual apartment itself
    // $('#apart_type').val(_globalApartType);

    if ($('#pic_holder').length > 0) {
        $('#pic_holder').cycle({
            fx: 'fade', // fade 
            timeout: 2500,
            speed: 2000,
            pause: 1,
            pager: '#pic_nav',
            pagerAnchorBuilder: pagerFactory
        });
    }

    // But not with the cities, nice ajax post back just an auto postback here
    $("#booking_currency").change(function () {
        $("#rateForm").submit();
    });

    // Toggle the side bar stuff
    $("#find_header").click(function (e) {
        // css check
        if ($('#find_header').hasClass('closed_box')) {
            $('#find_header').removeClass('closed_box');
        }
        else {
            $('#find_header').addClass('closed_box');
        }

        // Now hide the div
        $("#side_search").toggle('fast');
    });

    $("#startGallery").click(function (e) {
        StartApartSlider();
    });

    // Carried from the old site
    $("#adults").change(function () {
        UpdateAptTypesList()
    });

    $("#children").change(function () {
        UpdateAptTypesList()
    });

    // used on the book page for checking apartment types
    $("#adults_book").change(function () {
        UpdateAptTypesListBookingPage()
    });

    $("#children_book").change(function () {
        UpdateAptTypesListBookingPage();
    });

    // Wire up the validation engine
    $("#booking_form_forme").validationEngine({ validationEventTrigger: "form.submit", scroll: false });
    $("#booking_form_forme2").validationEngine({ validationEventTrigger: "form.submit", scroll: true });
    $("#regform").validationEngine({ scroll: false });
    $("#regformmain").validationEngine({ scroll: true });
    $("#changepwd").validationEngine({ scroll: false });
    $("#loginform").validationEngine({ scroll: false });
    $("#comp").validationEngine({ scroll: false });
    $("#enqform").validationEngine({ scroll: false });
    $("#booking_2").validationEngine({ scroll: false });
    $("#booking_4").validationEngine({ validationEventTrigger: "form.submit", scroll: true });
    $("#offline_1").validationEngine({ validationEventTrigger: "form.submit", scroll: true });

    // Clicking in any cell on the details page erases the success message
    $("input", "#regform").focus(function () {
        $("#result").html("");
    })
    // Same for the password pages
    $("input", "#changepwd").focus(function () {
        $("#pwdresult").html("");
    })

    $('#changepwd').submit(function () {
        // 'this' refers to the current submitted form
        var str = $(this).serialize();
        input = $(':input')
        // Only call the method if the page validated successfully
        if ($("#changepwd").validationEngine('validate')) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: input,
                success: function (result) {
                    $('#pwdresult').html(result);
                },
                error: function (result) {
                    $('#pwdresult').html(result);
                }
            });
        }
        return false;
    });

    $('#regform').submit(function () {
        // 'this' refers to the current submitted form
        var str = $(this).serialize();
        input = $(':input')
        // Only call the method if the page validated successfully
        if ($("#regform").validationEngine('validate')) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: input,
                success: function (result) {
                    $('#result').html(result);
                },
                error: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });

    // Function to empty textboxes on click
    $('input#searchbox').click(function (e) {
        $(this).val('');
        $(this).css('font-style', "normal");
    })

    $("input#searchbox").autocomplete({
        source: function (request, response) {
            query = request.term
            // define a function to call your Action (assuming UserController)
            $.ajax({
                type: "POST",
                url: '/home/QuickSearch',
                // query will be the param used by your action method
                data: { SearchVal: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.label, value: item.label };
                    }))
                }
            })
        },
        minLength: 1 // require at least one character from the user
    }).data("autocomplete")._renderItem = function (ul, item) {
        var result_item = item.label;
        var x = new RegExp(query, 'ig'); // notice the escape \ here... 
        result_item = result_item.replace(x, function (FullMatch, n) {
            return '<span class="highlight">' + FullMatch + '</span>'
        });
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a class='autocomplete_link'>" + result_item + "</a>")
            .appendTo(ul);
    };

    // Special offers jQuery, we have to redirect sadly due to the URLS
    $("#choose_region").change(function () {
        var optionSelectedValue = $('#choose_region option:selected').val();
        top.location.href = "../special_offers/" + optionSelectedValue;
    });

    // But not with the cities, nice ajax post back just an auto postback here
    $("#choose_city").change(function () {
        $("#form").submit();
    });

    $('#filter_location').click(function () {
        $("#form").submit();
    });

    if ($('a.launch_modal').length > 0) {
        $('a.launch_modal').each(function () {
            var m_width = parseInt($(this).attr('href').match(/width=[0-9]+/i)[0].replace('width=', ''));
            var m_height = parseInt($(this).attr('href').match(/height=[0-9]+/i)[0].replace('height=', ''));

            $(this).fancybox({
                'width': m_width,
                'height': m_height,
                'autoScale': false,
                'showCloseButton': true,
                'speedIn': 100,
                'speedOut': 100,
                'overlayShow': true,
                'scrolling': 'no',
                'type': 'iframe'
            });
        });
    }

    // Shows the pic_holder div again if they click on a number
    $("#pic_nav").click(function () {
        // show rosettes
        $("a.rosette_offer").show();
        $("a.rosette_seller").show();
        $("#pic_holder").show();
        $("#google_sv").hide();
        $("#google_map").hide();
    });

    // Deals with the maps on the apartment page
    $("a.view_map").click(function (e) {
        e.preventDefault();
        // Hide the pic slider and show google map
        $("#pic_holder").hide();
        $("#google_sv").hide();
        $("#google_map").show();
        // Hide rosettes
        $("a.rosette_offer").hide();
        $("a.rosette_seller").hide();
        // Load the google map into the image
        initializeMap();
    });

    $("a.view_sv").click(function (e) {
        e.preventDefault();
        // Hide all
        $("#pic_holder").hide();
        $("#google_map").hide();
        // show street view
        $("#google_sv").show();
        // Hide rosettes
        $("a.rosette_offer").hide();
        $("a.rosette_seller").hide();
        // Load street view into the image
        sv();
    });


    // results page show map div 
    if ($('#results_map').length > 0) {
        $('#results_as_map').click(function (e) {
            e.preventDefault();
            //$('#results_map').show('fast');
            $('#results_map').css('display', 'block');
            $('#search_result_options a').removeClass('slctd');
            $(this).addClass('slctd');
            initialize();
        });

        $('#results_as_list').click(function (e) {
            e.preventDefault();
            $('#results_map').css('display', 'none');
            $('#search_result_options a').removeClass('slctd');
            $(this).addClass('slctd');
        });
    }

    // set body js-only class	
    $('body').attr('id', 'js_only');

    // home page sliding images
    if ($('#home_carousel').length > 0) {
        $('#home_carousel').cycle({
            fx: 'scrollHorz', // fade
            timeout: 6000,
            speed: 1000,
            prev: '#pic_prev',
            next: '#pic_next',
            pager: '#pic_nav',
            pagerAnchorBuilder: load_counter
        });
    }

    // booking forms stuff

    $('#home_book div.book:last').css('margin-top', '4px');
    $('#home_book div.book:first div.book_item').css('display', 'none');


    // The quick search box on the home page.
    $('#home_book div h2').click(function (e) {
        e.preventDefault();
        ShowSearchHome(this);
    });

    $('.findme').click(function (e) {
        $('#whatis').hide();
        $('#home_book div').removeClass('current_book');

        $('#findanapartment').show('fast', function () {
            $('#findanapartment').parents('div.book').addClass('current_book');
        });

    });

    function ShowSearchHome(obj) {

        if (!$(obj).parent().hasClass('current_book')) {

            $('div.book_item').hide('fast', function () {
                $('#home_book div').removeClass('current_book');
            });

            $(obj).parents().children('div.book_item').show('fast', function () {
                $(obj).parents('div.book').addClass('current_book');
            });
        }
    }
    // booking forms sub nav

    // $('#find_nav li:last').addClass('last_book_nav');	
    $('#find_nav a').click(function (e) {
        e.preventDefault();
        $('#find_nav a').removeClass('current_leaf');
        $('.find_item').removeClass('find_item_current');
        $(this).addClass('current_leaf');
        var which_link = $(this).attr('href').substring(1, 20);
        $('#' + which_link).addClass('find_item_current');
    });


    // booking forms sub nav

    // $('#find_nav li:last').addClass('last_book_nav');	
    $('#what_nav a').click(function (e) {
        e.preventDefault();
        $('#what_nav a').removeClass('current_leaf');
        $('.what_item').removeClass('what_item_current');
        $(this).addClass('current_leaf');
        var which_link = $(this).attr('href').substring(1, 20);
        $('#' + which_link).addClass('what_item_current');
    });

    // fade homepage awards

    if ($('#innerfader').length > 0) {
        $('#innerfader').innerfade({
            animationtype: 'fade',
            speed: 'normal',
            timeout: 4000,
            type: 'sequence',
            containerheight: '66px'
        });
    }

    // UI date picker for booking form
    $("#checkin").datepicker({
        showOn: "button",
        dayNames: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        dateFormat: 'dd/mm/yy',
        buttonImage: "/assets/gfx/bcgs/calendar.png",
        buttonImageOnly: true,
        minDate: +1
    });


    $("#apt_checkin_book").datepicker({
        showOn: "button",
        dayNames: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        dateFormat: 'dd/mm/yy',
        buttonImage: "/assets/gfx/bcgs/calendar.png",
        buttonImageOnly: true,
        showOptions: "down",
        minDate: +1
    });


    // apartment page panels
    $('.apartment_all .apt_panel:first').addClass('apt_panel_show');

    $('#apt_panel_swith li a').click(function (e) {
        e.preventDefault();
        $('.apartment_all .apt_panel').removeClass('apt_panel_show');
        $('#apt_panel_swith li a').removeClass('slctd');
        var which_panel = $(this).attr('href').substring(1, 20);
        $('#' + which_panel).addClass('apt_panel_show');
        $(this).addClass('slctd');
    });

    $('.content_sub li a').unbind('click');

    // lets break the web with hashbangs, together...!
    if ($('.apartment_details').length > 0) {
        var hash = window.location.hash;
        if (hash != '') {
            $('.apartment_all .apt_panel').removeClass('apt_panel_show');
            $('#apt_panel_swith li a').removeClass('slctd');
            $(hash).addClass('apt_panel_show');
            $('.apartment_all_nav a').filter(function () {
                return $(this).attr('href') == hash;
            }).addClass('slctd');
        }
    }

    // apartments panel offers insets 

    $('#apt_offers .offers_panel:first .offers_panel_inner').slideDown('fast', function () {
        $(this).parents().children('.offers_panel_inner').addClass('offers_panel_show');
    });

    $('.offers_panel h3').click(function (e) {
        if (!$(this).parents().children('.offers_panel_inner').hasClass('offers_panel_show')) {
            $('#apt_offers .offers_panel_inner').removeClass('offers_panel_show');
            $('.offers_panel_inner').slideUp('fast');
        }
        $(this).parents().children('.offers_panel_inner').slideDown('fast', function () {
            $(this).parents().children('.offers_panel_inner').addClass('offers_panel_show');
        });
    });

    // map popup function to override default 
    $('#map_link').click(function (e) {
        e.preventDefault();
        var map_url = $(this).attr('href');
        window.open(map_url, 'map_window', 'height=670,width=720');
    });

    // booking page
    $('#booking_thumb').click(function (e) {
        e.preventDefault();
        var thumb_url = $(this).attr('href');
        window.open(thumb_url, 'thumb_window', 'height=300,width=450');
    })



    //    // registration form
    //    $('#show_registration_form').click(function (e) {
    //        $('#registration_form').show('slow');
    //    });

    // home page modals
    if ($('#sign_up_form').length > 0) {
        $("#sign_up_form").fancybox({
            'showCloseButton': true,
            'speedIn': 100,
            'speedOut': 100,
            'overlayShow': true,
            'width': 540,
            'height': 700,
            'scrolling': 'no'
        });
    }

    // Rosettes
    if ($('#offers_rosettes').length > 0) {
        $("#offers_rosettes a[title]").tooltip();
    };

    if ($('#search_help_box').length > 0) {
        $('#search_help_box a[title]').tooltip();
    };

    // Payment page
    if ($('#code').length > 0) {
        $('#code[title]').tooltip();
    };


});
  
