$(document).ready(function () {
    /*----------------------------------------------------------------------------
    Global Vars
    -----------------------------------------------------------------------------*/
    // These are used to determine where the site is being viewed from.
    var loc = window.location;
    var domain = loc.hostname;
    var splitDomain = loc.pathname.split('/');
    var siteRepo = splitDomain[1];    

    // Localhost
    if (domain == 'localhost') {
        var baseUrl = loc.protocol + '//' + loc.hostname + ':' + loc.port + '/' + siteRepo + '/';
    }

    // Staging
    else if (domain == 'staging.looking4parking.com') {
        var baseUrl = loc.protocol + '//' + loc.hostname + '/';
    }

    // Approval
    else if (domain.indexOf('approval') != -1) {
        var baseUrl = loc.protocol + '//' + loc.hostname + '/';
    }

    // Approval and Live 
    else {
        var baseUrl = '/';
    }

		// remove backend validation on inputs
		$(':input').removeAttr('required');


    /*----------------------------------------------------------------------------
    Ajax Defaults
    -----------------------------------------------------------------------------*/
    function ajaxDefaults() {

        $.ajaxSetup({
            async: false,
            type: 'POST',
            dataType: "html",
            url: baseUrl + 'frontend.ashx',
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //$('html').html(XMLHttpRequest.responseText);
                alert(XMLHttpRequest.responseText);
            }
        });
    } ajaxDefaults();


    function GetQueryStrings(strHref) {
        if (!strHref)
            strHref = location.href;

        var aQS = strHref.split("?");
        var rtn = {}

        aQS = aQS[1].split("&");

        if (aQS.length > 1) {
            for (i = 0; i < aQS.length; i++) {
                var kv = aQS[i].split("=");
                eval("rtn['" + kv[0] + "']='" + kv[1] + "'");
            }
        }

        return rtn;
    }


    // This is because it is only a simple form and would have to use
    // a somewhat convoluted html structure to work with the existing scripts.
    // Besides it isn't publically available only to our PR team.
    (function() {
      var $prForm = $('#PRSubscribeForm');
      if ($prForm.length) {
        
        // Submit the form on the submit button being clicked.
        $prForm.find('.submit').live("click", function(evt) {
        
          var formData = $('#PRSubscribeForm').find(':input').serialize();
          $.ajax({
            data: {
              "op": "addToCampaignMonitor",
              "formData": formData
            },
            beforeSend: function () {
              $('#PRSubscribeForm .message').remove();
            },
            success: function (strResponse) {
              $('#PRSubscribeForm').append("<p class=\"message success\">" + strResponse + "</p>");
            },
            error: function (xhr) {
              $('#PRSubscribeForm').append("<p class=\"message error\">Error: " + xhr.responseText + "</p>");
            },
            complete: function() {
              $('#PRSubscribeForm .message').fadeIn();
            }
          });

        });
      }
    })();



    function date() {
        //Date Picker
        $('.datepicker').datepicker({
            dateFormat: 'dd/mm/yy'
            //showOn: 'both',
            //buttonImage: 'media/images/icons/calendar.png', 
            //buttonImageOnly: true,							
        });

        // Date and Time Picker
        $('.datetimepicker').each(function () {
            // for each .datetimepicker, get id and use it to create var instance 
            var pickerID = $(this).attr('id');
            var dtp = $('#' + pickerID);

            // activate each picker by ID
            dtp.datetimepicker({
                dateFormat: 'dd/mm/yy',
                hourGrid: 4,
                stepMinute: 15,
                minuteGrid: 15,
                separator: ' @ '
            });

            // if input has default value, use it to set the picker's default date/time
            if (dtp.val().length) {
                dtp.datetimepicker('setDate', (dtp.val()));
            }
        });

        $('.timepicker').each(function () {
            // for each .timepicker, get id and use it to create var instance 
            var pickerID = $(this).attr('id');
            var tp = $('#' + pickerID);

            // if input has default value
            if (tp.val().length) {

                // value is formated hh:mm so we need to split those 
                var getDefaultTime = tp.val();
                var defaultTime = getDefaultTime.split(':');

                // activate picker with default time
                tp.timepicker({
                    hour: defaultTime[0],
                    minutes: defaultTime[1]
                });
            }
            else {
                // activate standard timepicker
                tp.timepicker({});
            }
        });
    };


		$('div.moreContent').hide();
		$('.readMoreLink a').click(function(e){
			e.preventDefault();
			$(this).parent('.readMoreLink').prev('.moreContent').toggle('fast');		
			$(this).text($(this).text() == 'More' ? 'Less' : 'More');
		});



    //============================================================================
    // New Wams (Working Progress) Client Code Implementation - OPEN
    //----------------------------------------------------------------------------
    // Dependencies:
    //    wams.client.js
    //    wams.client.datatables.js
    //============================================================================


    // We need to implement this function in order for the website to update.
    // The code will execute on first run, and thereafter we can call it
    // explicitly to rearm (initialise) the various page elements and features.
    (Wams.Rearm = function () {

        // Initialise the DataTables.
        //    Here we do them individually but we could do a more generic
        //    selector to initialise a group / set of datatables.
        // See: wams.client.datatables.js for details.
        Wams.DataTables.Init({
            "datatables": "#MembersPendingOrders, #MembersPreviousOrders, #MembersCancelledOrders",
            "view": function (strData) {

                // Keep a record of the current view.
                var htmlPreviousViewState = $('#mainContent').html();

                // Update the contents.
                $('#mainContent').html(strData);

                var iTransactionID = $('#mainContent .transaction').attr("id");

                // Datepicker on Account Page
                date();


                // Resend Confirmation Email
                $('#mainContent .transaction .resend').live("click", function (e) {
                    $.ajax({
                        data: {
                            op: "ResendTransactionConfirmationEmail",
                            tid: iTransactionID,
                            email: $('#customerEmailToResendTo').val()
                        },
                        beforeSend: function () {
                            $('.response').remove();
                        },
                        success: function () {
                            alert('Thanks. Your confirmation has been resent to you.');
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('Error: ' + XMLHttpRequest.responseText);
                        },
                        complete: function () {
                            $('.response').fadeIn();
                        }
                    });
                });


                // Cancel Transaction Button.
                $('#mainContent .transaction .cancel').live("click", function (e) {
                    e.preventDefault();

                    iTransactionID = $('#mainContent .transaction').attr("id");

                    Wams.DataTables.RequestActionHtml("preCancelTransaction", iTransactionID, function (data) {
                        $('#mainContent .mockTabs').html(data);
                        $('#mainContent .section').addClass("last");
                        $('#mainContent .savefunctions .save, #mainContent .savefunctions .cancel, #mainContent .savefunctions.extra').remove();
                        $('#AcceptCancellationButton').addClass("btn dark").click(function (e) {
                            if (confirm("Are you sure?\nThis action cannot be undone!")) {
                                $.ajax({
                                    data: {
                                        op: "postCancelTransaction",
                                        id: iTransactionID,
                                        reason: $('#CancellationReason').val()
                                    },
                                    success: function (data) {
                                        // Restore the previous view and update the DataTables.
                                        $('#mainContent').html(htmlPreviousViewState);
                                        $('#mainContent .datatable').each(function () {
                                            Wams.DataTables.Load(this, $(this).attr("id"));
                                        });
                                    }
                                });
                            }
                        });
                    });

                    return false;
                });

                // Save Transaction Button.
                $('#mainContent .transaction .save').live("click", function (e) {
                    e.preventDefault();

                    iTransactionID = $('#mainContent .transaction').attr("id");

                    // serialize selected form inputs
                    var formData = $('#mainContent .transaction').find(':input').serialize();

                    // make ajax call
                    $.ajax({
                        data: {
                            op: "preAmendTransaction",
                            id: iTransactionID,
                            "formData": formData
                        },
                        success: function (data) {
                            $('#mainContent .mockTabs').html(data);
                            $('#mainContent .section').addClass("last");
                            $('#mainContent .savefunctions .save, #mainContent .savefunctions .cancel, #mainContent .savefunctions.extra').remove();

                            formData = $('#mainContent .transaction').find(':input').serialize();

                            $('#mainContent .mockTabs').append("<input type=\"button\" class=\"btn confirm dark\" id=\"ConfirmAmendButton\" name=\"ConfirmAmendButton\" value=\"Confirm\">");

                            $('#mainContent .mockTabs .confirm').click(function (e) {
                                e.preventDefault();

                                $.ajax({
                                    data: {
                                        op: "confirmTransactionAmendment",
                                        id: iTransactionID,
                                        "data": formData
                                    },
                                    success: function (data) {
                                        $('#mainContent .mockTabs').html(data);
                                        $('#mainContent .section').addClass("last");

                                        formData = $('#mainContent .transaction').find(':input').serialize();

                                        if ($('#mainContent .mockTabs .confirm').length) {
                                            $('#mainContent .mockTabs .confirm').click(function (e) {
                                                e.preventDefault();

                                                formData = $('#mainContent .transaction').find(':input').serialize();

                                                $.ajax({
                                                    data: {
                                                        op: "amendmentPayment",
                                                        "data": formData
                                                    },
                                                    success: function (data) {
                                                        $('#mainContent .mockTabs').html(data);
                                                    }
                                                });

                                                return false;
                                            });
                                        } // if
                                    }   // success
                                });   // ajax

                                return false;
                            });


                        }
                    });


                    // Restore the previous view and update the DataTables.
                    //          $('#mainContent').html(htmlPreviousViewState);
                    //          $('#mainContent .datatable').each(function () {
                    //            Wams.DataTables.Load(this, $(this).attr("id"));
                    //          });

                    return false;
                });


                // Add a back link that will restore the previous state.
                $('#mainContent .back').live("click", function (e) {
                    e.preventDefault();

                    $('#mainContent').html(htmlPreviousViewState);
                    Wams.Rearm();

                    return false;
                });


            }
        });



    })();

    //============================================================================
    // New Wams (Working Progress) Client Code Implementation - CLOSE
    //============================================================================


    // Cancel glyph home page links
    $('.glyph').click(function () { return false; });

    /*------------------------------------
    Scrollables
    ------------------------------------*/
    $(".contentBoxImageScrollable").scrollable({ circular: true }).autoscroll(3000);
    $(".navi a").attr("href", "#");
    //$(".contentScrollable").scrollable({ circular: true }).navigator('.navi'); //.autoscroll(3500);

    /*
    function quoteFormTabs() {

    // Set cookie
    $('#searchNavigation li').click(function () {
    var lastTab = $(this).index();
    $.cookie('tabIndex', lastTab);
    });

    // Retrieve cookie 
    if ($.cookie('tabIndex')) {
    var defaultTab = $.cookie('tabIndex');
    }
    else {
    defaultTab = 0;
    }

    // Due to bug with tabs not accepting 0 as an initial pane, have had to activate tabs one of two ways.
    if (defaultTab != 0) { // if not 0, set with initial pane specified
    $('#searchNavigation').tabs('.panes > .pane', {
    current: 'selected',
    initialIndex: defaultTab
    });
    }
    else { // else set without initial pane
    $('#searchNavigation').tabs('.panes > .pane', {
    current: 'selected'
    })

    }
    }
    quoteFormTabs();
    */

    //	    $(function() {
    //      var api = $('#searchNavigation').tabs(".panes > .pane", {
    //        api:true,
    //		current: 'selected',
    //        // set the index from a cookie, if a cookie value exists
    //        initialIndex: $.cookie('cookie_selected_tab_index') !== 'undefined' && $.cookie('cookie_selected_tab_index') != null  ?  $.cookie('cookie_selected_tab_index') : '0'
    //      });
    //
    //      api.onClick(function(event, tabIndex) {
    //        $.cookie('cookie_selected_tab_index', tabIndex, { expires: 7 }); // set cookie
    //      });
    //    });


    /*-------------------------------------------------------------------
    Add Comments Displayer
    --------------------------------------------------------------------*/
    $(".postCommentLink").click(function (e) {
        e.preventDefault();

        if ($("#AddCommentForm").is(':hidden')) {
            $("#AddCommentForm").slideDown(250);
            $("#AddCommentForm_Name").focus();
        } else {
            $("#AddCommentForm").slideUp(250);
        }

        if ($("#AddReviewForm").is(':hidden')) {
            $("#AddReviewForm").slideDown(250);
            $("#AddReviewForm_Name").focus();
        } else {
            $("#AddReviewForm").slideUp(250);
        }


        return false;
    });

    /*-------------------------------------------------------------------
    Colorbox
    --------------------------------------------------------------------*/
    $("a[rel='cb']").colorbox({
        maxHeight: "95%",
        maxWidth: "95%"
    });

    /*-------------------------------------------------------------------
    HACK: Make the first tab in the info scroller active.
    --------------------------------------------------------------------*/
    //$("#parkingInfoBox .navi li:first").addClass("active");

    /*----------------------------------------
    The L4P Side Bar Navigations.
    ------------------------------------------*/
    $(".sidebar .nav").slidingNav(); // Custom Bitmedia Plugin.

    /*----------------------------------------
    The Text Scroller
    ------------------------------------------*/
    $(".textScroller").scrollable({ circular: true, easing: "linear", speed: 250 }).autoscroll(3000);


    /*-----------------------------------------
    Empty Section HACK
    Hide the <div class="section">'s when empty.
    -------------------------------------------*/
    $(".section").each(function () {
        // If the section is empty...
        if (!$.trim($(this).html())) {
            // ...hide it.
            $(this).hide();
        }
    });

    /*-----------------------------------------
    Last Section HACK
    Add class 'last' to the last visible section.
    -------------------------------------------*/
    $("#mainContent .section").not(":hidden").filter(":last").addClass("last");

    /*-----------------------------------------
    Last Links li HACK
    -------------------------------------------*/
    $(".links").each(function(){ $(this).find("li:last").addClass("last"); });

    /*---------------------------------------------------------
    Subscribe Input HACK
    Erase the text when clicked and put it back if empty.
    ------------------------------------------------------------*/
    var defaultSubscribeText = "Enter email address";
    // Hide the text
    $("#Subscribe").click(function (e) {
        if ($(this).val() == defaultSubscribeText) {
            $(this).val("");
        }
    });
    // Add it back.
    $("#Subscribe").blur(function (e) {
        if ($(this).val() == "") {
            $(this).val(defaultSubscribeText);
        }
    });

    /*---------------------------------------------------------------------------------------
    Vendor Tool Tips
    ---------------------------------------------------------------------------------------*/
    if ($.browser.msie && $.browser.version == "6.0") { } else {
        $("img[title]").tooltip();
    }


    /*---------------------------------------------------------------------------------------
    Frequently Asked Questions.
    ---------------------------------------------------------------------------------------*/
    $("ul.faq li h5").click(function (e) {
        if ($(this).parent().hasClass("expanded")) {
            $(this).parent().removeClass("expanded");
        } else {
            $(this).parent().addClass("expanded");
        }
    }).filter(":first").click();


    /*---------------------------------------------------------------------------------------
    Terms and Conditions Pop up
    ---------------------------------------------------------------------------------------*/
    if ($('#termsAndConditionsDetails')) {
        var url = $("#paymentInformation .tandc a").attr("href");
        //alert(url);
        $('#termsAndConditionsDetails #mainContent').load(url, function () { });

        $("#paymentInformation .tandc a").click(function (e) {
            $.facebox($('#termsAndConditionsDetails').html());
            return false;
        });
    }

    /*---------------------------------------------------------------------------------------
    Back Buttons.
    ---------------------------------------------------------------------------------------*/
    $(".back a, .back").click(function (e) {
        // Go to the last page.
        window.history.go(-1);
        return false;
    });

    /*---------------------------------------------------------------------------------------
    Print Buttons.
    ---------------------------------------------------------------------------------------*/
    $('.print a').click(function () {
        window.print();
        return false;
    });


    //  /*---------------------------------------------------------------------------------------
    //  The Vehicle Details Section
    //  ---------------------------------------------------------------------------------------*/
    //  if ($("#vehicleDetails")) {
    //
    //    var carTabs = $("#vehicleDetails .vehicles ul");
    //    var carPanes = $("#vehicleDetails .items");
    //    var carCounter = 1; // We use this to increment the form IDs.
    //
    //    //------------------------------------------------------------------------
    //    // Hook up the add car function.
    //    //------------------------------------------------------------------------
    //    $("#vehicleDetails .add").click(function (e) {
    //
    //      if (carTabs.find(":last").index() > 6) {
    //        return false;
    //      }
    //
    //      // Append the new Tab.
    //      var newTab = carTabs.append("<li></li>").find(":last");
    //      var idx = carCounter += 1;
    //
    //      // Append the new Car Details Pane.
    //      var strNewPaneHtml =
    //        " <div class='item'>" +
    //        "    <div class='row'>" +
    //        "      <label>Registration:</label>" +
    //        "      <input type='text' id='carReg_" + idx + "' name='carReg_" + idx + "' class='required' value='' />" +
    //        "    </div>" +
    //        "    <div class='row'>" +
    //        "      <label>Car Make:</label>" +
    //        "      <input type='text' id='carMake_" + idx + "' name='carMake_" + idx + "' class='required' value='' />" +
    //        "    </div>" +
    //        "    <div class='row'>" +
    //        "      <label>Car Model:</label>" +
    //        "      <input type='text' id='carModel_" + idx + "' name='carModel_" + idx + "' class='required' value='' />" +
    //        "    </div>" +
    //        "    <div class='row'>" +
    //        "      <label>Car Colour:</label>" +
    //        "      <input type='text' id='carColour_" + idx + "' name='carColour_" + idx + "' class='required' value='' />" +
    //        "    </div>" +
    //        "    <div class='row'>" +
    //        "     <label>No. of Passengers:<br />" +
    //        "      <span style='font-size:9px;'>(including the driver)</span></label>" +
    //        "      <select id='carPassengers_" + idx + "' name='carPassengers_" + idx + "'>" +
    //        "        <option value='01' selected>01</option>" +
    //        "        <option value='02'>02</option>" +
    //        "        <option value='03'>03</option>" +
    //        "        <option value='04'>04</option>" +
    //        "        <option value='05'>05</option>" +
    //        "        <option value='06'>06</option>" +
    //        "        <option value='07'>07</option>" +
    //        "        <option value='08'>08</option>" +
    //        "        <option value='09'>09</option>" +
    //        "        <option value='10'>10</option>" +
    //        "        <option value='11'>11</option>" +
    //        "        <option value='12'>12</option>" +
    //        "      </select>" +
    //        "      <a href='#' class='btn dark remove'>Remove</a>" +
    //        "    </div>" +
    //        "  </div>";
    //      carPanes.append(strNewPaneHtml);
    //
    //      // Dymanically name and style the tabs so we don't have to worry
    //      // about removing them later.
    //      carTabs.children().each(function () {
    //        $(this).text("Car " + ($(this).index() + 1));
    //        $(this).removeClass("last");
    //      });
    //
    //      // Link the last style rule with the new tab.
    //      newTab.addClass("last");
    //
    //      // Reinitialise the tabbing and select the new tab.
    //      carTabs.tabs(carPanes.find(".item"));
    //      newTab.click();
    //
    //      return false;
    //    });
    //
    //    //------------------------------------------------------------------------
    //    // Hook up the dymanic car removal function.
    //    //------------------------------------------------------------------------
    //    $("#vehicleDetails .remove").live("click", function (e) {
    //      var idx = $(this).parents(".item").index();
    //
    //      // Remove the tab and pane.
    //      $(carTabs.find("li").get(idx)).remove();
    //      $(carPanes.find(".item").get(idx)).remove();
    //
    //      // Dymanically name and style the tabs so we don't have to worry
    //      // about removing them later.
    //      carTabs.children().each(function () {
    //        $(this).text("Car " + ($(this).index() + 1));
    //        $(this).removeClass("last");
    //      });
    //
    //      // Link the last style rule with the new tab.
    //      carTabs.find(":last").addClass("last");
    //
    //      // Reinitialise the tabbing and select the new tab.
    //      carTabs.tabs(carPanes.find(".item"));
    //      carTabs.find(":last").click();
    //
    //      return false;
    //    });
    //  }

    /*---------------------------------------------------------------------------------------
    Add Car 
    ---------------------------------------------------------------------------------------*/
    // Hide tab nav if only one car
    if ($('#vehicleDetails .item:last').index() == 0) {
        $('#vehicleDetails .tab_list').hide();
    }

    // hide all items except for the first one and set selected class
    $('#vehicleDetails .item:visible').not(':first').hide();
    $('#vehicleDetails ul li:first').addClass('current');

    /*------------------------------------------
    Add Car
    ------------------------------------------*/
    $('#vehicleDetails .add').click(function (e) {
        // get index of last item and add 2 to get display index
        var index = $(this).parents('#vehicleDetails').find('.item:last').index() + 2;

        // clone the template and insert it
        var template = $('#vehicleDetails .item:first').clone();
        $(template).appendTo('#vehicleDetails .items');
        $('#vehicleDetails .item:last').append('<a href="#" class="btn dark remove">Remove</a>');

        // append the template by removing any values and then replace id and name with index aware values
        $('#vehicleDetails .item:last :input').each(function () {
            var inputID = $(this).attr('id').replace(/\d+/g, '') + index;
            var inputName = $(this).attr('name').replace(/\d+/g, '') + index;
            $(this).val('').attr('id', inputID).attr('name', inputName);
        });

        // show nav, remove current class and drop in new nav item
        $('#vehicleDetails .tab_list').show();
        $('#vehicleDetails ul .current').removeClass('current');
        $('#vehicleDetails ul').append('<li class="current">Car' + index + '</li>');

        // hide visible item and show new one
        $('#vehicleDetails .item:visible').hide();
        $('#vehicleDetails .item:last').show();

        e.preventDefault();
    });

    // Tab Nav
    $('#vehicleDetails li').live('click', function () {
        var index = $(this).index();

        // nav
        $('#vehicleDetails li.current').removeClass('current');
        $(this).addClass('current');

        // items
        $('#vehicleDetails .item:visible').hide();
        $('#vehicleDetails .item:eq(' + index + ')').show();
    });

    /*------------------------------------------
    Remove Car
    ------------------------------------------*/
    $('#vehicleDetails .remove').live('click', function () {
        var index = $('#vehicleDetails li.current').index();

        // if there is a car after one being removed, select it.
        if ($('#vehicleDetails li.current').next('li').length) {
            $('#vehicleDetails .item:visible').next('.item').show();
            $('#vehicleDetails li.current').next('li').show().addClass('current');
        }
        // else select the previous car
        else {
            $('#vehicleDetails .item:visible').prev('.item').show();
            $('#vehicleDetails li.current').prev('li').show().addClass('current');
        }

        // remove 
        $('#vehicleDetails .item:eq(' + index + ')').remove();
        $('#vehicleDetails li:eq(' + index + ')').remove();

        // reset car numbers
        $('#vehicleDetails li').each(function () {
            var newindex = $(this).index() + 1;
            // append the template by removing any values and then replace id and name with index aware values
            $(this).html('Car ' + newindex);
        });

        // reset IDs and Names
        $('#vehicleDetails .item').each(function () {
            var newindex = $(this).index() + 1;
            $(this).find(':input').each(function (index, element) {
                var inputID = $(this).attr('id').replace(/\d+/g, '') + newindex;
                var inputName = $(this).attr('name').replace(/\d+/g, '') + newindex;
                $(this).attr('id', inputID).attr('name', inputName);
            });

        });


        // Hide tab nav if only one car needs checking again.
        if ($('#vehicleDetails .item:last').index() == 0) {
            $('#vehicleDetails .tab_list').hide();
        }

        return false;
    });



    /*---------------------------------------------------------------------------------------
    Search Results Amend Quote Form
    ---------------------------------------------------------------------------------------*/
    $('.searchResults #amendQuoteButton').click(function (e) {
        e.stopPropagation();
        e.preventDefault();
        if ($('.searchResults .amendQuoteContainer').is(':hidden')) {
            $('.searchResults .amendQuoteContainer').css("display", "block");
            $(this).css("-webkit-border-radius", "0px"); $(this).css("-moz-border-radius", "0px"); $(this).css("border-radius", "0px");
            $('#amendQuoteButton span').html('Close');
        } else {
            $('.searchResults .amendQuoteContainer').css("display", "none");
            $(this).css("-webkit-border-radius", "5px"); $(this).css("-moz-border-radius", "5px"); $(this).css("border-radius", "5px");
            $('#amendQuoteButton span').html('Amend Quote');
        }
    });

    /*  // Hide the quote form when it loses focus.
    $('html').click(function () {
    $('.searchResults .amendQuoteContainer').css("display", "none");
    $('.searchResults #amendQuoteButton').css("-webkit-border-radius", "5px");
    $('.searchResults #amendQuoteButton').css("-moz-border-radius", "5px");
    $('.searchResults #amendQuoteButton').css("border-radius", "5px");
    });

    $('.searchResults .amendQuoteContainer').click(function (e) {
    e.stopPropagation();
    });*/

    /*---------------------------------------------------------------------------------------
    Search Results Tab Sections
    ---------------------------------------------------------------------------------------*/
    var searchTabs = $("ul#searchTabs > li");
    searchTabs.click(function (e) {

        // Only do something if an unselected tab is clicked.
        if (!$(this).hasClass("current")) {

            $("ul#searchTabs > li").removeClass("current");
            $(this).addClass("current");

            // Hide all then display loading.
            $("#searchResults .items > div").css("display", "none");
            $(".infoLink").css("display", "none");
            $("#searchResults .items").append('<div class="loading"></div>');
            $('.loading').activity({ segments: 12, width: 7.5, space: 1, length: 15, color: '#CCC', speed: 1.5 });

            // Delay the update.
            setTimeout(function () {

                // Remove the loading animation.
                $(".loading").activity(false).remove();

                $('#BookingInfoBar h3').text('No booking fee. No credit card fee. No cancellation fee with 24 hours notice.');

                // Check for Meet And Greet
                if ($("ul#searchTabs > li.current").hasClass("meetAndGreet")) {
                    $("#searchResults .items > .meetAndGreet").css("display", "block");
                    $(".infoLink.meetAndGreet").fadeIn(); //css("display", "block");
                }
                // Check for Park and Ride
                else if ($("ul#searchTabs > li.current").hasClass("parkAndRide")) {
                    $("#searchResults .items > .parkAndRide").css("display", "block");
                    $(".infoLink.parkAndRide").fadeIn(); //css("display", "block");
                }
                // Check for On Site
                else if ($("ul#searchTabs > li.current").hasClass("onSite")) {
                    $("#searchResults .items > .onSite").css("display", "block");
                    $(".infoLink.onSite").fadeIn(); //css("display", "block");
                    $('#BookingInfoBar h3').text('No booking fee. No credit card fee.');
                }
                // Otherwise, simply display everything
                else {
                    $("#searchResults .items > div").css("display", "block");
                }

            }, 750);
        }

    });



    /*---------------------------------------------------------------------------------------
    Datepicker
    ---------------------------------------------------------------------------------------*/
    // Datepicker on Homepage
    $('#searchContainer .panes > div').each(function () {
        var container = $(this).attr('id');
        var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
            dateFormat: 'dd/mm/yy',
            yearRange: '1',
            maxDate: +365,
            minDate: 0,
            numberOfMonths: 3,
            showAnim: '',
            duration: 'fast',
            onSelect: function (selectedDate) {
                if ($('#' + container).hasClass('toSelected')) {
                    // Do nothing
                }
                else {
                    if ($(this).attr('id') === container + 'From') {
                        // Set min date to match selected
                        $('#' + container + 'To').datepicker('option', 'minDate', selectedDate);

                        // set date +7 from selected
                        var advanceDate = $(this).datepicker('getDate');
                        advanceDate.setDate(advanceDate.getDate() + 7);
                        $('#' + container + 'To').datepicker('setDate', advanceDate);
                    }
                    else {
                        $('#' + container).addClass('toSelected');
                    }
                }



            },
            onClose: function () {
                // if form has already been validated, force validation when date is entered
                if ($('#' + container + ' .form').hasClass('validated')) {
                    $(this).valid();
                }
            }
        });
        // Insert Default From Date of today
        if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
            var currentTime = new Date();
            currentTime.setDate(currentTime.getDate());
            var day = ('0' + currentTime.getDate()).slice(-2);
            var month = ('0' + (currentTime.getMonth() + 1)).slice(-2);
            var year = currentTime.getFullYear();
            var TodayDate = day + "/" + month + "/" + year;
            $('#' + container + 'From').val(TodayDate);
        };
        // Inser Default To Date of +7
        if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
            var currentTime = new Date();
            currentTime.setDate(currentTime.getDate() + 7);
            var day = ('0' + currentTime.getDate()).slice(-2);
            var month = ('0' + (currentTime.getMonth() + 1)).slice(-2);
            var year = currentTime.getFullYear();
            var TodayDate = day + "/" + month + "/" + year;
            $('#' + container + 'To').val(TodayDate);
        }
    });

    // Datepicker on Quick Search 
    $(function () {
        if ($('#quickQuoteForm').length) {
            var container = "quickQuote";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }

        // Amend Quote
        if ($('#amendQuoteForm').length) {
            var container = "amendQuote";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }

        // Amend Quote
        if ($('#parkingSearchForm').length) {
            var container = "parkingSearch";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }

        // Amend Quote
        if ($('#airportHotelsSearchForm').length) {
            var container = "airportHotelsSearch";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }

        // Amend Quote
        if ($('#parkingAndHotelsSearchForm').length) {
            var container = "parkingAndHotelsSearch";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }


        // Amend Quote
        if ($('#portParkingSearchForm').length) {
            var container = "portParkingSearch";
            var dates = $('#' + container + 'From, #' + container + 'To').datepicker({
                dateFormat: 'dd/mm/yy',
                yearRange: '1',
                maxDate: +365,
                minDate: 0,
                numberOfMonths: 3,
                showAnim: '',
                duration: 'fast',
                onSelect: function (selectedDate) {
                    var option = this.id == container + "From" ? "minDate" : "maxDate",
			instance = $(this).data("datepicker"),
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings
			);
                    dates.not(this).datepicker("option", option, date);
                },
                onClose: function () {
                    // if form has already been validated, force validation when date is entered
                    if ($('#' + container + ' .form').hasClass('validated')) {
                        $(this).valid();
                    }
                }
            });
            // Insert Default From Date of today
            if ($('#' + container + 'From').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate())
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'From').val(TodayDate);
            };
            // Inser Default To Date of +7
            if ($('#' + container + 'To').val() == "") { // if value is empty. insert default date.
                var currentTime = new Date()
                currentTime.setDate(currentTime.getDate() + 7)
                var day = ('0' + currentTime.getDate()).slice(-2)
                var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
                var year = currentTime.getFullYear()
                var TodayDate = day + "/" + month + "/" + year
                $('#' + container + 'To').val(TodayDate);
            }
        }


    });







    /*---------------------------------------------------------------------------------------
    Timepicker
    NOTE: Disabled as we are not using it for now.
    ---------------------------------------------------------------------------------------
    $('#parkingSearchFromTime, #parkingSearchToTime').timepicker({
    stepHour : 1,
    stepMinute: 15,
    hourGrid: 4,
    minuteGrid: 15
    });
    */

    /*---------------------------------------------------------------------------------------
    Vendor Ratings
    ---------------------------------------------------------------------------------------*/
    if ($('#ContentID').length) {
        var contentID = $('#ContentID').val();

        // Get initial average value
        $.ajax({
            data: {
                "op": "getAverageRating",
                "content_id": contentID
            },
            success: function (data) {
                $($('input[type=radio].star')[parseInt(data) - 1]).attr("checked", "checked");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#rate').html('<div class="message error">Error: ' + XMLHttpRequest.responseText + '</div>');
            },
            complete: function () {
                $('#rate').fadeIn(300);
            }
        });


        $('input[type=radio].star').rating({
            callback: function (value, link) {

                $.ajax({
                    data: {
                        "op": "addRating",
                        "content_id": contentID,
                        "value": value
                    },
                    beforeSend: function () {

                    },
                    success: function (data) {
                        // Hide the star control
                        $('.star-rating-control').fadeOut(300, function () {
                            $("#rate .message").remove();

                            // Append the message.
                            $('#rate').append('<div class="message success">Thank you for your rating.</div>');

                            // Display the message.
                            $(".message").fadeIn(300);
                        });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $('#rate').html('<div class="message error">Error: ' + XMLHttpRequest.responseText + '</div>');
                    }
                });
            }
        });
    }

    /*---------------------------------------------------------------------------------------
    Review Vendor
    ---------------------------------------------------------------------------------------*/
    $('.addReview').toggle(function (e) {
        e.preventDefault();
        $(this).parents('.sideColContainer').find('#reviewForm').slideDown();
        $(this).parents('.sideColContainer').find('.items').slideUp();
    }, function (e) {
        e.preventDefault();
        $(this).parents('.sideColContainer').find('.items').slideDown();
        $(this).parents('.sideColContainer').find('#reviewForm').slideUp();
    });



    /*---------------------------------------------------------------------------------------
    Uniform
    ---------------------------------------------------------------------------------------*/
    //$("select, input:checkbox, input:radio, input:file").uniform();



    /*---------------------------------------------------------------------------------------
    Dropkick
    ---------------------------------------------------------------------------------------*/
    // find each dropdown and activate it by its ID
    $('.dropdown').not('#Payment_CardType').each(function () {
        var selectId = $(this).attr('id')
        $('#' + selectId).dropkick({
        // Dropkick waits until form submit before selecting the right option on the original input 
        // We need to select it manually as we submit via ajax
        //      change: function (value) {
        //        $('#' + selectId + ' option[value=]' + value).attr('selected', 'selected');
        //      }
    });
});

// remove html class put in by dropkick
if ($('form[action=payment]').length || $('body.paymentPage').length) {
    $('html').removeClass(' dk_fouc');
}

$('div').not('.dk_options').click(function () {
    if ($('.dk_open').length) {
        $('.dk_open').removeClass('dk_open');
    };
});




// find payment dropdown and insert classes
/*
$('#dk_container_Payment_CardType ul a').each(function () {
var cardType = $(this).attr('data-dk-dropdown-value');
$(this).addClass(cardType);
});
*/

//function setHeight(){
//    alert($(this).attr('id'));
//	var wh = $(window).height();
//    var offset = $(this).offset();
//    
//    var h = wh - offset.top - 100 + $(window).scrollTop();
//    
//    if (h > wh - 120) {
//        h = wh - 120;
//    }
//    else if (h < 200) { // min height
//        h = 200; // min height
//    }
//    
//    if (h > 700) { // max height
//        h = 700;
//    }
//    
//    // Set the height
//    $(this).children('ul').height(h);
//}
//
//
//$('.dk_container').each(function() {
//	setHeight();
//  });
//
//
//// Bind some stuff
//$(window).bind('resize scroll', function(){
//    setHeight();
//});




/*---------------------------------------------------------------------------------------
Facebox
---------------------------------------------------------------------------------------*/
$('a[rel*=facebox]').facebox();

/*---------------------------------------------------------------------------------------
Search Results Filtering
---------------------------------------------------------------------------------------*
$('#searchNavigation a').click(function (e) {
e.preventDefault();

function loading() {
$('#searchResults .wrapper').fadeOut('fast', function () {
if ($('#searchResults .wrapper').length == 0) {
$('#searchResults').append('<div class="loading"><img src="media/images/ajax-loader.gif" alt=""/></div>');
}
else { $('#searchResults .loading').show(); }
});
}

function filter() {
var filterby = $(this).attr('class').replace(' selected', '');
// show all parking
if (filterby == 'allParking') {
$('#searchResults .wrapper .product, #searchResults #recommendedProducts').show();
}
// filter parking
else {
$('#searchResults .wrapper .product').each(function () {
if ($(this).hasClass(filterby)) {
$(this).show;
if ($(this).hasClass('recProduct')) {
$('#searchResults #recommendedProducts').show();
}
}
else {
$(this).hide();
var recProduct = $('#recommendedProducts .product:visible').length;
if (recProduct == 0) {
$('#recommendedProducts').hide();
}
else {
$('#recommendedProducts').show();
}
}
});
}
}

function fadeIn() {}


});

/*---------------------------------------------------------------------------------------
Booking Summary Page Vehicle Tabs
---------------------------------------------------------------------------------------*/
$("#vehicleList ul").tabs("#vehiclePanes .items > .item");


/*---------------------------------------------------------------------------------------
Cookie Test
---------------------------------------------------------------------------------------*/
// set cookiue
$.cookie('test', 'pass');
// drop cookie into var
var testcookie = $.cookie('test');
// if cookie comes back, they are enabled.
if (testcookie === 'pass') {
    // delete cookie so each page refresh has a new test
    $.cookie('test', null);
    // else cookies are not enabled
} else {
    $('body').prepend('<div id="nocookies"><span>We\'re sorry, but it would appear that you do not have cookies enabled. Please enable and try again.</span></div>');
};


$('.accountOptions .logout').live('click', function () {
    $.ajax({
        data: {
            "op": "logMemberOut"
        },
        success: function (data) {
            window.location.href = data;
        }
    });
    return false;
});




/*---------------------------------------------------------------------------------------


DO NOT EDIT BELOW THIS LINE - EXCEPT TO ADD AN ADDITIONAL FORM FOR VALIDATION

	
---------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------
FORMS
---------------------------------------------------------------------------------------*/

/*------------------------------------
Book Now Links
------------------------------------*/
$('#searchResults a.bookNowLink').live('click', function () {
    var id = $(this).parent('div').parent('div').parent('div').parent('div').parent('div').attr('id');
    var cid = $(this).parent('div').parent('div').parent('div').parent('div').find('.moreInfo').find('a').attr('id');
    var price = $(this).parent('div').parent('div').find('.priceValue').text();
    var roomCode = $(this).parent('div').parent('div').parent('div').find('#roomCode').val();
		
		if ($(this).parent('div').parent('div').find('.discountStar').length){
			var discount = $(this).parent('div').parent('div').find('.discountStar').text();
		}
		else {
				var discount = '0';
		}

    //alert("Room Code: " + roomCode);

    $.ajax({
        data: {
            "op": "bookNowL4P",
            "id": id,
            "cid": cid,
            "price": price,
						"discount":discount,
            "roomCode": roomCode
        },
        success: function () {
            if (baseUrl == '/') {
                window.location.href = "https://www.looking4parking.com/payment";
            }
            else {
                window.location.href = "payment";
            }
        }
    });

    return false;
});





/*------------------------------------
Validator
------------------------------------*/
$('form').validate({
    onsubmit: false,
    focusInvalid: false,
    onkeyup: false,
    errorClass: 'invalid',
    validClass: 'valid',
    errorElement: 'div',
    errorPlacement: function (error, element) {
        error.appendTo(element.parent('.row'));
    },
    highlight: function (element, errorClass) {
        $(element).addClass(errorClass).fadeOut(function () {
            $(element).fadeIn();
        });
    },
    unhighlight: function (element, errorClass) {
        $(element).removeClass(errorClass);
    }
});

// VALIDATION
function Validate(evt) {
    // Obtain the form's ID by finding the .form which contains the submit
    var $group = $(this).parents('.form');
    var formID = $group.attr('id');
    var isValid = true;


    // Find all inputs in the form and validate them
    $group.find(':input').not('[type=button], [type="checkbox"]').each(function (i, item) {

        //       if ($group.hasClass('validated')) { return false; }

        // if an item is invalid, form is invalid
        if (!$(item).valid()) {
            isValid = false;
        }
    });

    $group.addClass('validated');


    // If form is invalid, prevent submission
    if (!isValid) {
        evt.preventDefault();
    }

    // allow submission
    else {

        submitForm(formID);
    }
}




/*------------------------------------
Attch Validator to all forms
------------------------------------*/
$('.form .submitButton input').each(function (index, element) {
    $(this).click(Validate);
});

$('.form :text').each(function (index, element) {
    $(this).keydown(function (evt) {
        // if Enter key has been pressed
        if (evt.keyCode == 13) {
            // go to the next input
            var $nextInput = $(this).nextAll(':input:first');
            // if next input is submit run validation
            if ($nextInput.is(':submit')) {
                if ($('.tandc :input').is(':checked')) {
                    Validate(evt);
                }
                else {
                    alert('You must accept the Terms and Conditions');
                }

            }
            else {
                // prevent default and focus on the next input
                evt.preventDefault();
                $nextInput.focus();
            }
        }
    });
});



/*------------------------------------
FORM SUBMIT
------------------------------------*/
// 	On submit, the validator runs first and if all good, it will call submitForm(formID) and pass the form's ID through the formID argument.

// 	Each form's ajax submit must be included in a switch and the case MUST match the ID of the form it's for.

// 	ALL forms MUST have a containing div with the following format where x is a variable for your form name. ie: contactForm
//	<div id="xForm" class="form"></div> 

function submitForm(formID) {
    switch (formID) {

        /* MAIN QUOTE FORM */ 

        // The quote form uses one ajax script for multiple forms, so has to rely on cascade and the formID sent by our validator                                                                                                                                                                                  
        case "parkingSearchForm":
        case "hotelsSearchForm":
        case "airportHotelsSearchForm":
        case "parkingAndHotelsSearchForm":
        case "portParkingSearchForm":
        case "portHotelsSearch":
        case "quickQuoteForm":

            // serialize selected form inputs
            var formData = $('#' + formID).find(':input').serialize();

            // get the ID of the currently active pane
            var currentPane = $('#searchContainer .panes > div:visible').attr('id');
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            // make ajax call
            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData
                },
                beforeSend: function () {
                    /*
                    // remove any prior error messages
                    $('#searchContainer .ajaxError').remove();
                    //  Eye candy - fade out the form and append ajax swirly
                    $('#searchContainer #' + currentPane + ' .row').fadeTo('fast', 0.5);
                    $('#searchContainer #' + currentPane + ' .form').append('<div class="loading"></div>');
                    */
                    $('#' + formID + ' .ajaxError').remove();
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');

                    if (formID == 'quickQuoteForm' || $('body').hasClass('search')) {
                        $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#4d3e63', speed: 1.5 });
                    }
                    else {
                        $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#fff', speed: 1.5 });
                    }
                },
                success: function (data) {
                    // on success from server, forward user to the following page. Back End will take care of them from there.
                    //alert("Forwarding Address: " + data);
                    window.location.href = data;
                    //alert(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    /*
                    $('#searchContainer #' + currentPane + ' .row').fadeTo('fast', 1);
                    $('#searchContainer #' + currentPane + ' .loading').activity(false).remove();
                    $('#searchContainer #' + currentPane + ' .form').append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>');
                    */
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' .loading').activity(false).remove();
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>');
                },
                complete: function () {
                    //$('#searchContainer #' + currentPane + ' input[type=button]').removeAttr('disabled');
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                }
            });

            break;





        /* AMEND QUOTE FORM */ 
        case "amendQuoteForm":

            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            // make ajax call
            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#4d3e63', speed: 1.5 });
                },
                success: function () {
                    // on success from server, forward user to the following page. Back End will take care of them from there.
                    window.location.href = "airport-parking-quote";
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' .loading').activity(false).remove();
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                },
                complete: function () {
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                }
            });
            break;


        /* PAYMENT FORM */ 
        case "paymentForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            // make ajax call
            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData
                },
                beforeSend: function () {
                    // remove any prior error messages  
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#4d3e63', speed: 1.5 });
                },
                success: function () {
                    // on success from server, forward user to the following page. Back End will take care of them from there.
                    window.location.href = "payment-success";
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // remove any prior error messages  
                    $('#' + formID + ' .error').remove();

                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' .loading').activity(false).remove();
                    $('#' + formID + ' .submitButton').after('<div class="error"><em>Error: </em> ' + XMLHttpRequest.responseText + '</div>');
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                },
                complete: function () {
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                }
            });
            break;

        /* MAILING LIST SUBCRIBE FORM */ 
        case "subscribeForm":

            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();

            $('#' + formID + ' input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "addToCampaignMonitor",
                    "formData": formData
                },
                beforeSend: function () {
                    $('#' + formID + ' .message').remove();
                },
                success: function (data) {
                    $('#' + formID).append("<p class=\"message success\">" + data + "</p>");
                },
                error: function (xhr) {
                    $('#' + formID).append("<p class=\"message error\">Error: " + xhr.responseText + "</p>");
                }
            });
            break;


        case "AddCommentForm":
        case "AddReviewForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();
            var pageUrl = location.href;

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "pageUrl": pageUrl
                },
                beforeSend: function () {
                    $('.addCommentResponse').remove();
                },
                success: function () {
                    $('#' + formID).after('<p class="addCommentResponse success">Your comments have been submitted and shall be displayed once approved.</p>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $('#' + formID).after('<p class="addCommentResponse error"><em>Error:</em> ' + XMLHttpRequest.responseText + '</p>');
                    $('#' + formID + ' .submitButton input').attr('disabled', 'false');
                },
                complete: function () {
                    $('.addCommentResponse').fadeIn();
                }
            });
            break;

        /***********************************************************************
        * Login Forms Section.
        ************************************************************************/ 

        /* Members Login Form */ 
        case "LoginMembersForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#4d3e63', speed: 1.5 });
                },
                success: function (data) {
                    window.location.href = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')

                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                    $('#' + formID + ' .loading').activity(false).remove();
                }
            });
            break;

        /* Non-Members Login form */ 
        case "LoginBookingForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({ segments: 12, width: 7.5, space: 6, length: 15, color: '#4d3e63', speed: 1.5 });
                },

                success: function (data) {
                    window.location.href = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')

                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                    $('#' + formID + ' .loading').activity(false).remove();
                }
            });
            break;

        /* New Members Registration Form */ 
        case "LoginRegisterForm":
        case "MemberActivationForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();
            var pageUrl = location.href;

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "url": pageUrl
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({
                        segments: 12,
                        width: 7.5,
                        space: 6,
                        length: 15,
                        color: '#4d3e63',
                        speed: 1.5
                    });
                },

                success: function (data) {
                    window.location.href = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')

                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                    $('#' + formID + ' .loading').activity(false).remove();
                }
            });
            break;


        case "AccountEditDetailsForm":
        case "AccountEditCarForm":
        case "AccountChangePasswordForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();
            var pageUrl = location.href;

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "url": pageUrl
                },
                beforeSend: function () {

                    // remove any prior messages
                    $('#' + formID + " .success").remove();
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({
                        segments: 12,
                        width: 7.5,
                        space: 6,
                        length: 15,
                        color: '#4d3e63',
                        speed: 1.5
                    });
                },

                success: function (data) {
                    $('#' + formID).append('<div class="success">' + data + '</div>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')

                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                    $('#' + formID + ' .loading').activity(false).remove();
                }
            });
            break;

        case "RetrievePasswordForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();
            var pageUrl = location.href;

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "url": pageUrl
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();
                    $('#' + formID + ' .success').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({
                        segments: 12,
                        width: 7.5,
                        space: 6,
                        length: 15,
                        color: '#4d3e63',
                        speed: 1.5
                    });
                },

                success: function (data) {
                    $('#RetrievePasswordForm .success').remove();
                    $('#RetrievePasswordForm').append('<div class="success">' + data + '</div>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' .loading').activity(false).remove();
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                }
            });
            break;

        case "ResetPasswordForm":
            // serialize form data
            var form = $('#' + formID);
            var formData = form.find(':input').serialize();
            var pageUrl = location.href;

            var aQS = GetQueryStrings();

            // disable submit button 
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');


            //        alert("op:formSubmit");
            //        alert("formData:" + formData);
            //        alert("url:"+ pageUrl);
            //        alert("mID:" + aQS["mID"]);
            //        alert("uID:" + aQS["uID"]);


            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "url": pageUrl,
                    "mID": aQS["mID"],
                    "uID": aQS["uID"]
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({
                        segments: 12,
                        width: 7.5,
                        space: 6,
                        length: 15,
                        color: '#4d3e63',
                        speed: 1.5
                    });
                },

                success: function (data) {
                    //alert("Password Reset");
                    form.find('.success').remove();
                    form.append('<div class="success">' + data + '</div>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    form.append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')
                    form.find('input[type=button]').removeAttr('disabled');
                },
                complete: function () {
                    form.find('.row').fadeTo('fast', 1);
                    form.find('.loading').activity(false).remove();
                    form.find('input[type=button]').removeAttr('disabled');
                }
            });
            break;



        case "contactUsForm":
            // serialize form data
            var formData = $('#' + formID).find(':input').serialize();
            var pageUrl = location.href;

            // disable submit button
            $('#' + formID + ' .submitButton input').attr('disabled', 'disabled');

            $.ajax({
                data: {
                    "op": "formSubmit",
                    "formData": formData,
                    "url": pageUrl
                },
                beforeSend: function () {

                    // remove any prior error messages
                    $('#' + formID + ' .ajaxError').remove();

                    //  Eye candy - fade out the form and append ajax swirly
                    $('#' + formID + ' .row').fadeTo('fast', 0.5);
                    $('#' + formID).append('<div class="loading"></div>');
                    $('.loading').activity({
                        segments: 12,
                        width: 7.5,
                        space: 6,
                        length: 15,
                        color: '#4d3e63',
                        speed: 1.5
                    });
                },

                success: function (data) {
                    $('#' + formID).append('<div class="success">' + data + '</div>');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // on ajax error, alert the user that there has been a problem
                    $('#' + formID).append('<div class="ajaxError">' + XMLHttpRequest.responseText + '</div>')
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                },
                complete: function () {
                    $('#' + formID + ' .row').fadeTo('fast', 1);
                    $('#' + formID + ' .loading').activity(false).remove();
                    $('#' + formID + ' input[type=button]').removeAttr('disabled');
                }
            });
            break;



    }
}



});

